diff --git a/.cursor/rules/web-artifact-no-degrade.mdc b/.cursor/rules/web-artifact-no-degrade.mdc deleted file mode 100755 index c3ee54c..0000000 --- a/.cursor/rules/web-artifact-no-degrade.mdc +++ /dev/null @@ -1,26 +0,0 @@ ---- -description: Marqdo Web Artifact — no degradation; Document/Endpoint/Resource only -globs: ext/web/**,ext/net/**,ext/data/**,ext/security/**,examples/**/*,tests/ext/web*,doc/design/ext-web*,doc/adr/0007* -alwaysApply: true ---- - -# Web Artifact — 不允许降级 - -Canonical: `doc/adr/0007-web-document-endpoint.md` · `doc/design/ext-web-artifact.md` · `doc/next/007.md` (superseded). - -## Hard bans - -1. **Do not** restore or reintroduce author-facing `compose_main` / `compose_intro` / `compose_*` fragmented table DSLs, god `# page` mutation piles, or `app.configure(...)` junk-drawer APIs. -2. **Do not** use `json.set` / `json.append` bag glue for pages, routes, or middleware. Tables = data. View schema is only `|type|slot|value|attrs|style|` (ZH aliases allowed). -3. **Do not** call `ensure_plugin` or `host_*` from author programs or from `ext/**` (plugin load is facade/capability only). -4. **Do not** register implicit user routes. Declared routes come from Artifact metadata or `web.route`. System routes (`/_part`, `/_form`, …) must appear in `web.inspect`. -5. **Do not** invent DSL, nested frontmatter under `##`, or new table dialects when the design is silent — **stop and ask**. -6. **Do not** mix EN/ZH API names in one `.mq.md`. -7. **Do not** silently delete capabilities. Removals require design text + tests updated in the same change. -8. **Do not** put DB/auth/cache/storage/websocket author APIs back into `ext/web/web.mq.md` — they live in `ext/data`, `ext/security`, `ext/net`. - -## Required direction - -- Document (`type: web` / `类型: 网页`), Endpoint (`type: endpoint` / `类型: 端点`), Resource modules. -- Facade only: `web.page` · `web.route` · `web.serve` · `web.render` · `web.inspect` (ZH mirrors). -- Code is documentation: the `.mq.md` is the page/API docs and the implementation. diff --git a/.cursor/skills/marqdo-dev/SKILL.md b/.cursor/skills/marqdo-dev/SKILL.md deleted file mode 100755 index 3932852..0000000 --- a/.cursor/skills/marqdo-dev/SKILL.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -name: marqdo-dev -description: Write, refactor and verify Marqdo programs, standard libraries and extensions through the executable development handbook. Use native Marqdo file tools and marqdo call; extend capability gaps through plugins or explicit external tools. ---- - -Read [the executable development entry](../../../skills/marqdo-dev/index.mq.md), then [the programming guide](../../../doc/library-development.mq.md). The same guide governs programs, libraries and executable SKILLs. For installed skills, resolve these paths against the Marqdo source checkout. - -Use `**statement**` to execute and `*return*` to return; write `[intent](actual code)` inside executable positions, and `access(coll, key)` to read collections. The guide provides real examples. Native file tasks live in [files.mq.md](../../../skills/marqdo-dev/files.mq.md): read, write, patch, search, inventory, audit and apply. Do not generate Python or shell programs for ordinary file operations. - -Prepare the native engineering plugin with the development entry before using its analysis or process tasks. The repository development binary is `target/debug/marqdo`; installed older binaries may need a bootstrap Cargo build through `lib/sys.mq.md exec`. All subsequent task execution uses `marqdo call`. Keep decisions and sequencing in readable mq.md; use a new extension or a documented foreign tool only for a real capability gap. - -The guide is authoritative for narrative over 50%, immediate parameter/return tables, inline statements and returns, GFM data, index.mq.md organization, recursive Markdown web components, failure evidence and verification. Read each task's contract and grant its actual effects. External processes retain their OS authority. Do not rewrite intentional test fixtures or restore removed compose_* APIs. - -Use the development entry's audit task to discover and review maintained repository sources. Its failed Result retains every finding; write_report=True saves the same evidence under .marqdo/audit. It does not execute inspected source or treat known placeholder warnings as completed logic. diff --git a/.cursor/skills/marqdo-release/SKILL.md b/.cursor/skills/marqdo-release/SKILL.md deleted file mode 100755 index 906be08..0000000 --- a/.cursor/skills/marqdo-release/SKILL.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -name: marqdo-release -description: Prepare, publish and verify a user-authorized Marqdo full, cli or extension release through its executable mq.md handbook. Use for release versioning, immutable tags, matching CI gates, GitHub/R2 parity and Ubuntu PPA publication. ---- - -Read [the executable release entry](../../../skills/marqdo-release/index.mq.md) and use its task routing. Version and mode come from the user; an already stated choice remains authorized. Inspection of an old release does not authorize republishing it. Never infer a new version, replace a tag, force-push or bypass hooks. - -Use `marqdo call` on the actual handbook headings. The repository development binary is `target/debug/marqdo`; prepare its engineering plugin through [the development entry](../../../skills/marqdo-dev/index.mq.md). File reading and authoring use native [file tools](../../../skills/marqdo-dev/files.mq.md). No Python release orchestrator is required. New OS/service capabilities belong at explicit plugin or external-tool boundaries; version decisions, retries and publication order remain readable mq.md. - -The entry preserves full/cli/ext deliverables, separate editor sources, clean-main tagging, bilingual authored notes, exact-commit Release and EK gates, both native platforms, GitHub/R2 identical bytes, VERSION-after-ZIP ordering and Ubuntu source/build/apt evidence. Every applicable obligation must be verified before declaring completion. Default full/cli work includes PPA; gh-pages deployment needs its own instruction. - -Read-only status and verification are separate from publication. Grant effects stated by each task. Inspect Result.ok before value; use --require-ok when an external automation must stop on a failed Result. Credentials stay in their existing private stores. Interactive sudo/GPG/dput or a failed service request remains incomplete: report the concrete failure and the exact handbook recovery call, preserving local evidence. - -Independent extension releases commit reviewed bilingual notes at doc/releases/ext-X.Y.Z.md before tagging. The [pack handbook](../../../skills/marqdo-release/packs.mq.md) and extension-release.yml run native staging, both platform builds, exact-tag release creation and non-clobbering gh asset upload through marqdo call. An existing upload is inspected rather than replaced. Windows execution remains a CI obligation; a local Linux ZIP cannot prove it. diff --git a/.cursor/skills/marqdo-release/reference.md b/.cursor/skills/marqdo-release/reference.md deleted file mode 100755 index 50c4d95..0000000 --- a/.cursor/skills/marqdo-release/reference.md +++ /dev/null @@ -1,3 +0,0 @@ -# Release task reference - -Use [the executable release entry](../../../skills/marqdo-release/index.mq.md) and [its maintained task reference](../../../skills/marqdo-release/reference.md). File authoring, mode rules, native service/process boundaries and recovery live with the actual mq.md tasks. Do not reconstruct the former Python or terminal playbook from historical copies. diff --git a/.cursor/skills/marqdo-release/scripts/detect_version.py b/.cursor/skills/marqdo-release/scripts/detect_version.py deleted file mode 100755 index 32f609a..0000000 --- a/.cursor/skills/marqdo-release/scripts/detect_version.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python3 -"""Detect Marqdo version sources for release Phase 0. Never invent next SemVer.""" -from __future__ import annotations - -import re -import subprocess -import sys -from pathlib import Path - -# …/marqdo/.cursor/skills/marqdo-release/scripts/this.py → parents[4] = repo root -ROOT = Path(__file__).resolve().parents[4] - - -def cargo_version(path: Path) -> str | None: - if not path.is_file(): - return None - m = re.search(r'^version\s*=\s*"([^"]+)"', path.read_text(encoding="utf-8"), re.M) - return m.group(1) if m else None - - -def run(cmd: list[str]) -> str: - try: - out = subprocess.check_output(cmd, cwd=ROOT, stderr=subprocess.DEVNULL, text=True) - return out.strip() - except (subprocess.CalledProcessError, FileNotFoundError): - return "" - - -def main() -> int: - cargo = cargo_version(ROOT / "Cargo.toml") - wasm = cargo_version(ROOT / "crates" / "marqdo-wasm" / "Cargo.toml") - tags = run(["git", "tag", "-l", "v*", "--sort=-v:refname"]) - latest_tag = tags.splitlines()[0] if tags else "(none)" - gh_list = run(["gh", "release", "list", "--limit", "3"]) - latest_gh = "(gh unavailable)" - if gh_list: - # first column is tag name for `gh release list` - latest_gh = gh_list.splitlines()[0].split("\t")[0].strip() - - changelog = ROOT / "CHANGELOG.md" - unreleased = False - unreleased_preview = "" - if changelog.is_file(): - text = changelog.read_text(encoding="utf-8") - m = re.search(r"^## Unreleased\s*\n(.*?)(?=^## |\Z)", text, re.M | re.S) - if m: - body = m.group(1).strip() - # nonempty if any bullet or non-heading content beyond empty section headers - content_lines = [ - ln - for ln in body.splitlines() - if ln.strip() and not re.match(r"^###\s+", ln.strip()) - ] - unreleased = bool(content_lines) - unreleased_preview = " | ".join(content_lines[:3])[:200] - - print("=== Marqdo version detect (do NOT invent next; ask the user) ===") - print(f"repo: {ROOT}") - print(f"Cargo.toml: {cargo or '(missing)'}") - print(f"marqdo-wasm: {wasm or '(missing)'}") - print(f"latest git tag: {latest_tag}") - print(f"latest gh release: {latest_gh}") - print(f"Unreleased notes: {'YES' if unreleased else 'NO/empty'}") - if unreleased_preview: - print(f"Unreleased peek: {unreleased_preview}") - if cargo and latest_tag.lstrip("v") != cargo: - print("WARN: Cargo version != latest tag (expected during pre-bump or lag)") - if cargo and wasm and cargo != wasm: - print("WARN: root Cargo.toml and marqdo-wasm versions differ — sync before release") - print() - print("ASK USER: next SemVer X.Y.Z (tag will be vX.Y.Z)") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/.cursor/skills/marqdo-release/scripts/push-via-hk-jump.py b/.cursor/skills/marqdo-release/scripts/push-via-hk-jump.py deleted file mode 100755 index e7e6672..0000000 --- a/.cursor/skills/marqdo-release/scripts/push-via-hk-jump.py +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env python3 -"""Push / run git|gh through an HK SSH jump host (Paramiko HTTP CONNECT). - -When this machine cannot reach GitHub reliably but can SSH to a host that can -(e.g. hk.cflmy.de), open a local HTTP CONNECT proxy over Paramiko and run the -remaining command with http(s).proxy pointed at it. - -Why Paramiko: OpenSSH/`sshpass` has hung on password auth in this environment; -Paramiko password + direct-tcpip works. - -Credentials (never commit): - HK_SSH_PASSWORD password string - HK_SSH_PASSWORD_FILE file containing password (mode 600 recommended) - or SSH key via Paramiko agent/keys if password unset and key works - -Optional env: - HK_SSH_HOST default hk.cflmy.de - HK_SSH_USER default root - HK_JUMP_PORT default 18081 (local CONNECT listen) - -Usage: - HK_SSH_PASSWORD_FILE=/tmp/hk.pw \\ - python3 .cursor/skills/marqdo-release/scripts/push-via-hk-jump.py -- \\ - git push origin main - - # keep proxy only (Ctrl+C to stop) - ... push-via-hk-jump.py --serve - - # wrap gh - ... push-via-hk-jump.py -- gh release view v0.3.9 -""" -from __future__ import annotations - -import os -import select -import socket -import socketserver -import subprocess -import sys -import threading -import time -from pathlib import Path - -try: - import paramiko -except ImportError as e: # pragma: no cover - raise SystemExit( - "paramiko required: apt install python3-paramiko (or pip install paramiko)" - ) from e - -ROOT = Path(__file__).resolve().parents[4] - - -class _Server(socketserver.ThreadingMixIn, socketserver.TCPServer): - allow_reuse_address = True - daemon_threads = True - - -def load_password() -> str | None: - path = os.environ.get("HK_SSH_PASSWORD_FILE") - if path: - return Path(path).read_text(encoding="utf-8").strip() - pw = os.environ.get("HK_SSH_PASSWORD") - return pw.strip() if pw else None - - -def connect_hk() -> paramiko.SSHClient: - host = os.environ.get("HK_SSH_HOST", "hk.cflmy.de") - user = os.environ.get("HK_SSH_USER", "root") - pw = load_password() - client = paramiko.SSHClient() - client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - kwargs: dict = { - "hostname": host, - "username": user, - "timeout": 20, - "auth_timeout": 25, - "banner_timeout": 25, - } - if pw: - kwargs.update(password=pw, allow_agent=False, look_for_keys=False) - else: - kwargs.update(allow_agent=True, look_for_keys=True) - print(f"== HK jump {user}@{host} ==", flush=True) - client.connect(**kwargs) - _, stdout, stderr = client.exec_command( - "hostname; curl -sS --max-time 20 -o /dev/null -w gh=%{http_code} https://github.com/; echo" - ) - out = stdout.read().decode() - err = stderr.read().decode() - print(out, end="" if out.endswith("\n") else "\n", flush=True) - if err.strip(): - print(err, file=sys.stderr, flush=True) - return client - - -def make_proxy(transport: paramiko.Transport, port: int) -> _Server: - class Handler(socketserver.StreamRequestHandler): - def handle(self) -> None: - try: - first = self.rfile.readline(65536) - if not first: - return - parts = first.decode("latin1", "replace").split() - if len(parts) < 2 or parts[0].upper() != "CONNECT": - self.wfile.write(b"HTTP/1.1 405 Method Not Allowed\r\n\r\n") - return - while True: - line = self.rfile.readline(65536) - if line in (b"\r\n", b"\n", b""): - break - host, _, port_s = parts[1].partition(":") - chan = transport.open_channel( - "direct-tcpip", - (host, int(port_s or "443")), - self.connection.getpeername(), - ) - self.wfile.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") - sock = self.connection - sock.setblocking(False) - chan.setblocking(False) - try: - while True: - r, _, x = select.select([sock, chan], [], [sock, chan], 120) - if x: - break - if sock in r: - data = sock.recv(65536) - if not data: - break - chan.sendall(data) - if chan in r: - data = chan.recv(65536) - if not data: - break - sock.sendall(data) - finally: - try: - chan.close() - except Exception: - pass - except Exception: - pass - - return _Server(("127.0.0.1", port), Handler) - - -def github_basic_auth_header() -> str: - """Authorization: Basic … from local git credential store (no askpass; askpass can hang).""" - import base64 - - out = subprocess.check_output( - ["git", "credential", "fill"], - input=b"protocol=https\nhost=github.com\n\n", - ).decode() - data = dict(line.split("=", 1) for line in out.splitlines() if "=" in line) - user = data.get("username") or "x-access-token" - password = data.get("password") or "" - if not password: - raise SystemExit("no github.com credential in git credential store") - token = base64.b64encode(f"{user}:{password}".encode()).decode() - return f"Authorization: Basic {token}" - - -def github_token() -> str | None: - out = subprocess.check_output( - ["git", "credential", "fill"], - input=b"protocol=https\nhost=github.com\n\n", - ).decode() - data = dict(line.split("=", 1) for line in out.splitlines() if "=" in line) - return data.get("password") or None - - -def run_with_proxy(proxy: str, argv: list[str]) -> int: - env = os.environ.copy() - for k in ( - "http_proxy", - "https_proxy", - "HTTP_PROXY", - "HTTPS_PROXY", - "ALL_PROXY", - "all_proxy", - ): - env.pop(k, None) - - cmd = list(argv) - if cmd and cmd[0] == "git": - # Prefer http.extraHeader over GIT_ASKPASS (askpass has hung under agent/no TTY). - # Do not also set env http_proxy for git — only -c (avoids double-proxy quirks). - auth = github_basic_auth_header() - cmd = [ - "git", - "-c", - f"http.proxy={proxy}", - "-c", - f"https.proxy={proxy}", - "-c", - "credential.helper=", - "-c", - f"http.extraHeader={auth}", - "-c", - "http.version=HTTP/1.1", - "-c", - "http.postBuffer=524288000", - *cmd[1:], - ] - print( - "+", - " ".join( - c if not str(c).startswith("http.extraHeader=") else "http.extraHeader=" - for c in cmd - ), - flush=True, - ) - return subprocess.call(cmd, cwd=ROOT, env=env) - - env["http_proxy"] = proxy - env["https_proxy"] = proxy - env["HTTP_PROXY"] = proxy - env["HTTPS_PROXY"] = proxy - - if cmd and cmd[0] == "gh" and not env.get("GH_TOKEN"): - tok = github_token() - if tok: - env["GH_TOKEN"] = tok - - print("+", " ".join(cmd), flush=True) - return subprocess.call(cmd, cwd=ROOT, env=env) - - -def main(argv: list[str]) -> int: - args = argv[1:] - if not args or args[0] in ("-h", "--help"): - print(__doc__) - return 0 if args else 1 - - serve_only = args == ["--serve"] - if args[0] == "--": - args = args[1:] - if not serve_only and not args: - print("missing command after --", file=sys.stderr) - return 2 - - port = int(os.environ.get("HK_JUMP_PORT", "18081")) - client = connect_hk() - transport = client.get_transport() - assert transport is not None - server = make_proxy(transport, port) - threading.Thread(target=server.serve_forever, daemon=True).start() - proxy = f"http://127.0.0.1:{port}" - print(f"== CONNECT proxy {proxy} ==", flush=True) - # smoke - subprocess.call( - [ - "curl", - "-sS", - "--connect-timeout", - "10", - "--max-time", - "25", - "--proxy", - proxy, - "-o", - "/dev/null", - "-w", - "github=%{http_code}\\n", - "https://github.com/", - ] - ) - - try: - if serve_only: - print("serving; Ctrl+C to stop", flush=True) - while transport.is_active(): - time.sleep(5) - return 1 - return run_with_proxy(proxy, args) - finally: - server.shutdown() - client.close() - - -if __name__ == "__main__": - raise SystemExit(main(sys.argv)) diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md deleted file mode 100755 index 2254761..0000000 --- a/.cursor/skills/marqdo/SKILL.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -name: marqdo -description: Author, run and review readable Marqdo programs, libraries and executable knowledge. Use for .mq.md, marqdo call, Document/Endpoint/Resource web projects and quantum tools; read the executable programming and development handbooks. ---- - -# Marqdo - - - -## CORE SYNTAX - -Occlusion is the current default. `**…**` executes a statement; `*…*` returns. -Use `[intent](actual code)` in an executable position: the label is prose and -only its payload executes. Empty parentheses are a pending None stub. -Read collections with `access(coll, key)`. Classic indexing is only for explicit -legacy sources and migration. Reading narrative references never runs effects. - -| Marker | Meaning | -|---|---| -| `**…**` | Statement (assign / call / expression) | -| `*…*` | Return | -| `[intent](payload)` | Readable intent with executable payload | -| `access(c, k)` | Collection read | -| `- [intent](for items as item)` | Explicit traversal | -| `1.` / `2.` | Branches; numbered * is else | -| GFM table | Data: one column list, one row record, @ row records | - -Read [the executable programming guide](../../../doc/library-development.mq.md) -before authoring. Its actual callable examples demonstrate inline computation, -structured results, defaults and recoverable native file reads. Use -[the development entry](../../../skills/marqdo-dev/index.mq.md) and its file tools for source -work, and [the release entry](../../../skills/marqdo-release/index.mq.md) for an authorized -release. These mq.md files are the working instructions and tools; do not rebuild -a parallel command playbook in SKILL.md. - -Call the actual file and heading with `marqdo call`. In a source checkout use -the built `target/debug/marqdo`; prepare its engineering plugin through the -development entry. Large structured inputs use --args-json FILE or stdin; -JSON strings stay literal during call-session replay. --require-ok makes failed -Results stop external automation while preserving their returned evidence. -Read each function's parameter/return tables and effect contract before calling. - -Author programs as readable explanations: useful narrative exceeds half of -each callable unit; parameter and return tables immediately follow its heading; -inline assignments, actions and returns explain their purpose. Standard libraries -remain single-file handbooks. Multi-file projects and extensions use index.mq.md. -GFM describes data, public helpers describe operations, and components recursively -split web layouts until their content leaves are ordinary Markdown. - -Native Marqdo capabilities handle file reading/writing, tables, parsing, hashing -and network reads. Add an extension for a reusable capability gap or call an -explicit existing external tool with argument arrays. Keep decisions, retries -and the execution flow in mq.md. Do not generate Python or shell programs for -already available native operations. OS processes and plugins retain their OS -authority; an fs-root does not sandbox their own access. - -Use the current [web entry](../../../ext/web/index.mq.md) for Document, Endpoint and -Resource artifacts, or [quantum entry](../../../ext/quantum/index.mq.md) for circuit -workflows. Do not restore removed compose_* or app.configure APIs. Preserve -intentional fixtures and [classic migration context](migration-classic.md). -Validate the real calls and error paths; a narrative ratio or uploaded asset -alone is never functional evidence. diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md deleted file mode 100755 index db46baa..0000000 --- a/.cursor/skills/marqdo/examples.md +++ /dev/null @@ -1,3 +0,0 @@ -# Marqdo executable examples - -Read [the maintained discovery note](../../../skills/marqdo/examples.md) and its actual mq.md source entries. The [programming guide](../../../doc/library-development.mq.md) is authoritative; source examples and real workflow tests stay together rather than being copied into SKILL reference fences. diff --git a/.cursor/skills/marqdo/migration-classic.md b/.cursor/skills/marqdo/migration-classic.md deleted file mode 100755 index 4be585c..0000000 --- a/.cursor/skills/marqdo/migration-classic.md +++ /dev/null @@ -1,3 +0,0 @@ -# Classic migration - -Read [the maintained migration context](../../../skills/marqdo/migration-classic.md) and [the executable programming guide](../../../doc/library-development.mq.md). Historical fixtures retain explicit classic markup; new code uses readable occlusion and access(collection, key). diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md deleted file mode 100755 index d060290..0000000 --- a/.cursor/skills/marqdo/reference.md +++ /dev/null @@ -1,3 +0,0 @@ -# Marqdo executable reference - -Read [the maintained discovery note](../../../skills/marqdo/reference.md) and its actual mq.md source entries. The [programming guide](../../../doc/library-development.mq.md) is authoritative; source examples and real workflow tests stay together rather than being copied into SKILL reference fences. diff --git a/.env.example b/.env.example deleted file mode 100755 index d18b29f..0000000 --- a/.env.example +++ /dev/null @@ -1,12 +0,0 @@ -# Local LLM for Marqdo agent / ext/ai/llm development. -# Copy to `.env` in the repo root (gitignored) and fill secrets. -# Never commit real keys. - -OPENAI_API_KEY= -OPENAI_BASE_URL=https://llm.cflmy.cn/v1 -OPENAI_MODEL=cflmy - -# Aliases also accepted by ext/ai/llm: -# MARQDO_LLM_API_KEY= -# MARQDO_LLM_BASE_URL= -# MARQDO_LLM_MODEL= diff --git a/.env.r2.example b/.env.r2.example deleted file mode 100755 index b725e27..0000000 --- a/.env.r2.example +++ /dev/null @@ -1,9 +0,0 @@ -# Ext CDN / R2 (Cloudflare) — copy to ~/.marqdo/r2.env and chmod 600 -# Never commit real keys. Public downloads: https://ext.marqdo.com - -R2_ACCOUNT_ID= -R2_BUCKET=marqdo -R2_ENDPOINT=https://.r2.cloudflarestorage.com -R2_ACCESS_KEY_ID= -R2_SECRET_ACCESS_KEY= -R2_PUBLIC_BASE=https://ext.marqdo.com diff --git a/.gitattributes b/.gitattributes index 04ad559..efdba87 100755 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,2 @@ -# Multipart protocol examples retain required CRLF bytes in every checkout. -examples/web-net-site/components/content/multipart.txt -text whitespace=cr-at-eol -examples/web-net-site-zh/components/content/multipart.txt -text whitespace=cr-at-eol +* text=auto +*.sh text eol=lf diff --git a/.gitea/ISSUE_TEMPLATE/change.md b/.gitea/ISSUE_TEMPLATE/change.md new file mode 100644 index 0000000..1a47a43 --- /dev/null +++ b/.gitea/ISSUE_TEMPLATE/change.md @@ -0,0 +1,20 @@ +--- +name: 功能、缺陷或迁移 +about: 记录唯一负责仓库、可复现输入与验收 +--- + +## 责任与范围 + +负责仓库、所有者、影响公共契约和关联工单。 + +## 环境与复现 + +平台、组件或制品 SHA、最小输入、命令、实际与预期行为。 + +## 验收 + +真实正例、负例、授权边界和失败条件。跨仓库问题请列出消费者回归。 + +## 交付 + +责任 PR、精确提交、CI 链接及集成 PR。 diff --git a/.gitea/PULL_REQUEST_TEMPLATE.md b/.gitea/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..00ddc53 --- /dev/null +++ b/.gitea/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,11 @@ +## 工单与范围 + +链接责任工单,列出本次提交变更的 gitlink、治理或集成路径。 + +## 组合与证据 + +记录组件提交、C1/C2/C3 链接、可复现命令及支持平台。列出失败和未验证项。 + +## 发行与回滚 + +说明公共协议切换、制品影响、旧基线或回滚方式。 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100755 index 265c2b6..0000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,15 +0,0 @@ -## 层归属(必填,见 doc/design/layers.md) - -- [ ] Language(`src/lex` `src/parse` `src/ast` `src/interp` `src/diagnostics` / 契约) -- [ ] Runtime(`lib/` `plugins/` `crates/` catalog / view / debug / builtin) -- [ ] Document(`*.mq.md` `skills/` `ext/` `public/` `examples/`) - -## 核心表面(见 doc/design/core-surface.md) - -- [ ] 不涉及核心标记 -- [ ] 涉及核心标记:ADR 编号 ______;core-surface.md 与 `CORE_CONSTRUCTS` 已同步(CI 守卫) - -## 验收 - -- [ ] 相关验收(机器可验证)全绿 -- [ ] 全量回归绿(`cargo test` / `go test ./...` 视触及面) diff --git a/.github/workflows/build-markdown-execution-video.yml b/.github/workflows/build-markdown-execution-video.yml deleted file mode 100644 index 9cd6373..0000000 --- a/.github/workflows/build-markdown-execution-video.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Build cinematic Markdown-to-execution video - -on: - push: - branches: [docs/markdown-execution-cinematic-v2] - paths: - - "scripts/render-markdown-execution-promo.py" - - ".github/workflows/build-markdown-execution-video.yml" - workflow_dispatch: - -permissions: - contents: write - -jobs: - video: - if: github.ref_name == 'docs/markdown-execution-cinematic-v2' - runs-on: ubuntu-latest - timeout-minutes: 25 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: true - - name: Prepare fonts, Chrome and Python tools - run: | - sudo apt-get update -qq - sudo apt-get install -y -qq ffmpeg fonts-noto-cjk - python -m pip install --quiet pillow numpy markdown-it-py selenium - google-chrome --version - - name: Render promo video from two original images and Marqdo source - run: python scripts/render-markdown-execution-promo.py - - name: Check resulting video - run: | - test -s assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4 - test -s assets/marketing/marqdo-2.7.1-markdown-to-execution-cover.jpg - test -s assets/marketing/marqdo-2.7.1-markdown-to-execution.srt - ffprobe -v error -show_entries format=duration,size:stream=codec_name,width,height -of json assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4 - - name: Commit compiled video, poster and subtitles - run: | - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4 \ - assets/marketing/marqdo-2.7.1-markdown-to-execution-cover.jpg \ - assets/marketing/marqdo-2.7.1-markdown-to-execution.srt \ - assets/marketing/marqdo-procurement-standard-markdown.png - git diff --cached --quiet || git commit -m "docs: publish cinematic Markdown-to-execution promotional film" - git push origin HEAD:docs/markdown-execution-cinematic-v2 diff --git a/.github/workflows/capture-procurement-marketing.yml b/.github/workflows/capture-procurement-marketing.yml deleted file mode 100644 index 18d052b..0000000 --- a/.github/workflows/capture-procurement-marketing.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: capture-procurement-marketing-assets - -on: - push: - branches: [docs/executable-skill-showcase-271] - paths: - - "scripts/capture-procurement-showcase.py" - - ".github/workflows/capture-procurement-marketing.yml" - workflow_dispatch: - -permissions: - contents: write - -jobs: - capture: - if: github.ref_name == 'docs/executable-skill-showcase-271' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: true - - uses: actions/setup-python@v5 - with: - python-version: "3.11" - - name: Prepare Chrome, Chinese fonts and Python imaging - run: | - python -m pip install --quiet pillow selenium - sudo apt-get update -qq - sudo apt-get install -y -qq fonts-noto-cjk - google-chrome --version - - name: Download Marqdo v2.7.1 Linux release - run: | - mkdir -p /tmp/marqdo-marketing-cli - curl -fL --retry 3 "https://github.com/cflmy/marqdo/releases/download/v2.7.1/marqdo-2.7.1-x86_64-unknown-linux-gnu.zip" -o /tmp/marqdo-marketing.zip - unzip -q /tmp/marqdo-marketing.zip -d /tmp/marqdo-marketing-cli - BIN="$(find /tmp/marqdo-marketing-cli -type f -name marqdo | head -n 1)" - test -n "$BIN" - chmod +x "$BIN" - echo "CLI_BIN=$BIN" >> "$GITHUB_ENV" - - name: Record real command outputs and capture real View - run: python scripts/capture-procurement-showcase.py --cli "$CLI_BIN" - - name: Commit reproducible promotional assets - run: | - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add assets/marketing/procurement-cli.gif assets/marketing/procurement-view.png - git diff --cached --quiet || git commit -m "docs: capture live procurement CLI GIF and View screenshot" - git push origin HEAD:docs/executable-skill-showcase-271 diff --git a/.github/workflows/executable-knowledge.yml b/.github/workflows/executable-knowledge.yml deleted file mode 100755 index e6cc297..0000000 --- a/.github/workflows/executable-knowledge.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: executable-knowledge - -on: - push: - branches: [main] - pull_request: - -jobs: - gate: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - name: Build agent + llm plugins (EK / workbench gates) - run: | - cargo build -p marqdo_plugin_agent --locked - cargo build -p marqdo_plugin_llm --locked - - name: Native agent choice and bounded recovery unit tests - run: cargo test -p marqdo_plugin_agent --locked - - name: Check short AI flow documents - run: | - cargo run --locked -- check ext/ai/flow.mq.md - cargo run --locked -- check ext/ai/recovery.mq.md - cargo run --locked -- check ext/ai/context.mq.md - cargo run --locked -- check tests/ext/ai-native-flow.mq.md - cargo run --locked -- check ext/ai/workflow.mq.md - cargo run --locked -- check tests/ext/ai-native-workflow.mq.md - - name: Native AI flow interpreter smoke (offline) - env: - MARQDO_AGENT_PLUGIN: ${{ github.workspace }}/target/debug/libagent.so - run: | - cargo run --locked -- run tests/ext/ai-native-flow.mq.md - cargo run --locked -- run tests/ext/ai-native-workflow.mq.md - - name: Workbench contracts (M00–M06 / F-subset) - run: cargo test --test workbench_contracts --locked - - name: Offline executable-knowledge gate - run: cargo test --test executable_knowledge --locked - - name: Isolated execute MR-01 (dual 60s SSE + short reads) - run: | - cargo build -p marqdo_plugin_llm --locked - bash scripts/build-web-plugin.sh - cargo test --test isolated_execute_mr01 --locked -- --nocapture - timeout-minutes: 5 - - name: no ignored tests counted as success - run: | - if grep -n '#\[ignore\]' tests/executable_knowledge.rs; then - echo "executable_knowledge must not use #[ignore] as success evidence" >&2 - exit 1 - fi - echo "ok: no #[ignore] in executable_knowledge gate" diff --git a/.github/workflows/extension-release.yml b/.github/workflows/extension-release.yml deleted file mode 100755 index d9240e3..0000000 --- a/.github/workflows/extension-release.yml +++ /dev/null @@ -1,68 +0,0 @@ -# Independent extension sources and native libraries; no CLI/PPA publication. -name: Extension Release - -on: - push: - tags: - - "ext-v*" - -permissions: - contents: write - -jobs: - windows: - runs-on: windows-latest - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - uses: dtolnay/rust-toolchain@stable - - uses: actions/setup-go@v5 - with: - go-version: "1.23.x" - - name: Install cgo toolchain - run: choco install mingw -y - - name: Build the handbook CLI and native capabilities - shell: bash - run: | - set -euo pipefail - export PATH="/c/ProgramData/mingw64/mingw64/bin:/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin:$PATH" - cargo build --release -p marqdo -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering - bash scripts/build-web-plugin.sh - - name: Build and validate the runner's exact pack bytes - shell: bash - run: | - set -euo pipefail - ./target/release/marqdo.exe call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.read,fs.write,environment.read --fs-root . --require-ok --json - - name: Attach source and Windows native packs without replacement - shell: bash - run: | - set -euo pipefail - ./target/release/marqdo.exe call skills/marqdo-release/packs.mq.md attach_ci --effects plugin,fs.read,environment.read --fs-root . --require-ok --json - - linux: - runs-on: ubuntu-latest - needs: windows - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - uses: dtolnay/rust-toolchain@stable - - uses: actions/setup-go@v5 - with: - go-version: "1.23.x" - - name: Install ZIP and cgo tools - run: sudo apt-get update && sudo apt-get install -y zip gcc libc6-dev - - name: Build the handbook CLI and native capabilities - run: | - set -euo pipefail - cargo build --release -p marqdo -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering - bash scripts/build-web-plugin.sh - - name: Build and validate the runner's exact pack bytes - run: target/release/marqdo call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.read,fs.write,environment.read --fs-root . --require-ok --json - - name: Attach Linux native pack without replacement - run: target/release/marqdo call skills/marqdo-release/packs.mq.md attach_ci --effects plugin,fs.read,environment.read --fs-root . --require-ok --json diff --git a/.github/workflows/feature-matrix.yml b/.github/workflows/feature-matrix.yml deleted file mode 100644 index c421147..0000000 --- a/.github/workflows/feature-matrix.yml +++ /dev/null @@ -1,40 +0,0 @@ -# Cargo feature compatibility gate. -# -# `sema` (the core compiler) must build without the `cli` feature. Library -# consumers such as qdagent depend on `marqdo` with `default-features = false`, -# so any unconditional reference to a `cli`-gated module is a release blocker. -# Keep this matrix in sync with the feature graph in Cargo.toml. -name: feature-matrix - -on: - push: - branches: [main] - paths: - - "src/**" - - "Cargo.toml" - - "Cargo.lock" - - ".github/workflows/feature-matrix.yml" - pull_request: - paths: - - "src/**" - - "Cargo.toml" - - "Cargo.lock" - - ".github/workflows/feature-matrix.yml" - workflow_dispatch: - -concurrency: - group: feature-matrix-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -jobs: - lib-feature-matrix: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@1.81.0 - - name: Library builds with no default features - run: cargo check --locked --lib --no-default-features - - name: Library builds with only the cli feature - run: cargo check --locked --lib --no-default-features --features cli - - name: Library builds with default features - run: cargo check --locked --lib diff --git a/.github/workflows/knowledge-proof-full-gate.yml b/.github/workflows/knowledge-proof-full-gate.yml deleted file mode 100644 index a027d89..0000000 --- a/.github/workflows/knowledge-proof-full-gate.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: knowledge-proof-full-gate - -on: - pull_request: - paths: - - "src/knowledge/**" - - "src/sema/**" - - "src/prove/**" - - "tests/**" - - "doc/verification/skill-proof/**" - - ".github/workflows/knowledge-proof-full-gate.yml" - workflow_dispatch: - -concurrency: - group: knowledge-proof-full-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -jobs: - complete-proof-regression: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - name: Install pinned Lean kernel - run: | - curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain leanprover/lean4:v4.35.0 - echo "$HOME/.elan/bin" >> "$GITHUB_PATH" - - name: Validate Lean kernel and embedded proof library - run: | - lean --version - bash scripts/check-proof-library.sh - lean doc/verification/skill-proof/MarqdoModularProof.lean - lean doc/verification/skill-proof/MarqdoEffects.lean - - name: Build and run all knowledge unit tests - run: | - cargo build --locked - cargo test --locked --lib knowledge:: - cargo test --locked --lib sema::ir::tests - - name: Knowledge and execution compatibility suites - run: | - cargo test --locked --test knowledge_proof - cargo test --locked --test executable_knowledge - cargo test --locked --test prove - - name: Full genuine Lean proof matrix - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: | - cargo test --locked --test prove_lean - cargo test --locked --test prove_corpus - cargo test --locked --test conformance diff --git a/.github/workflows/modular-proof-smoke.yml b/.github/workflows/modular-proof-smoke.yml deleted file mode 100644 index af49e59..0000000 --- a/.github/workflows/modular-proof-smoke.yml +++ /dev/null @@ -1,70 +0,0 @@ -name: modular-proof-smoke -on: - pull_request: - paths: - - "src/knowledge/**" - - "src/sema/ir.rs" - - "src/prove/**" - - "tests/prove_lean.rs" - - "doc/verification/skill-proof/**" - - ".github/workflows/modular-proof-smoke.yml" - workflow_dispatch: -concurrency: - group: modular-proof-smoke-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true -jobs: - modular: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - name: Compile isolated modular proof candidates - run: cargo test --locked --lib knowledge::composition::tests -- --nocapture - - name: Compile parameter-projection proof backend - run: cargo test --locked --lib knowledge::projection -- --nocapture - - name: Compile pure-expression VC backend - run: cargo test --locked --lib knowledge::expression::tests -- --nocapture - - name: Unified contract engine and evidence lattice unit tests - run: | - cargo test --locked --lib knowledge::unified::tests -- --nocapture - cargo test --locked --lib knowledge::evidence::tests -- --nocapture - - name: Compile path-sensitive VCs - run: cargo test --locked --lib knowledge::symbolic::tests -- --nocapture - - name: Compile closed-argument VCs - run: cargo test --locked --lib knowledge::vc::tests -- --nocapture - - name: Install Lean 4.35 - run: | - curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain leanprover/lean4:v4.35.0 - echo "$HOME/.elan/bin" >> "$GITHUB_PATH" - - name: Lean proof of exception, ABI and fuel-bound models - run: | - lean doc/verification/skill-proof/MarqdoModularProof.lean - lean doc/verification/skill-proof/MarqdoEffects.lean - - name: Independently composed Lean modules - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean composition_emits_independently_replayable_caller_certificate -- --nocapture - - name: Symbolic parameter projection with independent Lean replay - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean projection_composition_proves_symbolic_caller_and_replays_from_source -- --nocapture - - name: Independent arithmetic contract composition with real Lean - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean pure_expression_composition_proves_and_replays_real_lean -- --nocapture - - name: Three module DAG and branching caller with independent Lean replay - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean unified_modular_contract_proves_multicall_branch_and_transitive_dag -- --nocapture - - name: Regenerated provenance for original Lean certificates - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean g2_certificate_hit_after_real_run -- --nocapture - - name: Linear symbolic arithmetic path implication with real Lean - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean arithmetic_symbolic_path_implication_uses_real_lean -- --nocapture - - name: Symbolic path implication with real Lean - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean symbolic_path_implication_uses_real_lean_without_runtime_promotion -- --nocapture diff --git a/.github/workflows/native-ai-flow.yml b/.github/workflows/native-ai-flow.yml deleted file mode 100644 index da1c944..0000000 --- a/.github/workflows/native-ai-flow.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: native-ai-flow - -on: - push: - branches: - - feat/native-ai-flow-recovery-20261118 - pull_request: - paths: - - 'plugins/agent/**' - - 'ext/ai/flow.mq.md' - - 'ext/ai/context.mq.md' - - 'ext/ai/recovery.mq.md' - - 'ext/ai/workflow.mq.md' - - 'tests/ext/ai-native-*.mq.md' - - '.github/workflows/native-ai-flow.yml' - -jobs: - agent: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - name: Build the agent plugin - run: cargo build -p marqdo_plugin_agent --locked - - name: Run native agent and workflow tests - run: cargo test -p marqdo_plugin_agent --locked - - name: Check the public Marqdo ABI libraries - run: | - cargo run --locked -- check ext/ai/flow.mq.md - cargo run --locked -- check ext/ai/context.mq.md - cargo run --locked -- check ext/ai/recovery.mq.md - cargo run --locked -- check ext/ai/workflow.mq.md - cargo run --locked -- check tests/ext/ai-native-flow.mq.md - cargo run --locked -- check tests/ext/ai-native-workflow.mq.md - - name: Exercise offline integration through Marqdo - env: - MARQDO_AGENT_PLUGIN: ${{ github.workspace }}/target/debug/libagent.so - run: | - cargo run --locked -- run tests/ext/ai-native-flow.mq.md - cargo run --locked -- run tests/ext/ai-native-workflow.mq.md diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml deleted file mode 100755 index 4b69587..0000000 --- a/.github/workflows/pages.yml +++ /dev/null @@ -1,48 +0,0 @@ -# Build public/ with marqdo and publish to the gh-pages branch. -name: User docs site - -on: - push: - branches: [main, master] - paths: - - "public/**" - - "src/**" - - "Cargo.toml" - - "Cargo.lock" - - ".github/workflows/pages.yml" - - "scripts/build-public.*" - - "scripts/run-public-pages.sh" - workflow_dispatch: - -permissions: - contents: write - -jobs: - build-and-deploy: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - - - name: Build & export site - shell: bash - run: bash scripts/run-public-pages.sh - - - name: Verify site shape - run: | - if grep -R "tests/errors" public --include='*.html' ; then - echo "user site must not include tests/errors fixtures" >&2 - exit 1 - fi - test -f public/index.html - test -f public/00-welcome.mq.md - - - name: Deploy to gh-pages - uses: peaceiris/actions-gh-pages@v4 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./public - publish_branch: gh-pages - force_orphan: true diff --git a/.github/workflows/procurement-example.yml b/.github/workflows/procurement-example.yml deleted file mode 100644 index 6d5f6d9..0000000 --- a/.github/workflows/procurement-example.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: procurement-example-smoke -on: - push: - branches: [main, docs/executable-skill-showcase-271] - paths: ["examples/procurement/**", ".github/workflows/procurement-example.yml"] - pull_request: - paths: ["examples/procurement/**", ".github/workflows/procurement-example.yml"] -jobs: - smoke: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Fetch released v2.7.1 Linux CLI - run: | - curl -fL --retry 3 "https://github.com/cflmy/marqdo/releases/download/v2.7.1/marqdo-2.7.1-x86_64-unknown-linux-gnu.zip" -o /tmp/marqdo.zip - unzip -q /tmp/marqdo.zip -d /tmp - BIN="$(find /tmp -type f -name marqdo | head -n 1)" - test -n "$BIN" - chmod +x "$BIN" - echo "CLI_BIN=$BIN" >> "$GITHUB_ENV" - - name: Check and run procurement skill - run: | - "$CLI_BIN" check examples/procurement/index.mq.md - "$CLI_BIN" call examples/procurement/index.mq.md 查询余额 已花费=120 --json - "$CLI_BIN" call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json | tee /tmp/allowed.json - "$CLI_BIN" call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=360 交付要求天数=7 --effects time.read,process.control --json | tee /tmp/denied.json - grep -q '本地模拟' /tmp/allowed.json - grep -q '采购金额超过' /tmp/denied.json diff --git a/.github/workflows/promo-video.yml b/.github/workflows/promo-video.yml deleted file mode 100644 index 4f62fe9..0000000 --- a/.github/workflows/promo-video.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Build Marqdo promotional video - -on: - push: - branches: [docs/promo-video-271] - paths: - - scripts/make-procurement-promo.py - - .github/workflows/promo-video.yml - workflow_dispatch: - -permissions: - contents: write - -jobs: - build-video: - if: github.ref_name == 'docs/promo-video-271' - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: true - - name: Prepare video environment - run: | - sudo apt-get update -qq - sudo apt-get install -qq -y ffmpeg fonts-noto-cjk - python -m pip install --quiet --disable-pip-version-check pillow numpy - ffmpeg -version | head -n 2 - - name: Compose 32-second Marqdo video - run: python scripts/make-procurement-promo.py - - name: Verify deliverable - run: | - test -s assets/marketing/marqdo-2.7.1-promo.mp4 - test -s assets/marketing/marqdo-2.7.1-poster.jpg - test -s assets/marketing/marqdo-2.7.1-promo.srt - ffprobe -v error -show_entries format=duration,size -of default=noprint_wrappers=1 assets/marketing/marqdo-2.7.1-promo.mp4 - - name: Commit video into promotional branch - run: | - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add assets/marketing/marqdo-2.7.1-promo.mp4 assets/marketing/marqdo-2.7.1-poster.jpg assets/marketing/marqdo-2.7.1-promo.srt - git diff --cached --quiet || git commit -m "docs: render Marqdo 2.7.1 promotional video from existing assets" - git push origin HEAD:docs/promo-video-271 diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml deleted file mode 100644 index a119553..0000000 --- a/.github/workflows/proof.yml +++ /dev/null @@ -1,115 +0,0 @@ -# 判定流水线(marqdo prove) -# -# 验证「SKILL 编排文档 → Lean 4 → 自动证明」全链路: -# 1. 构建内置 Lean 底座(MarqdoProof.lean)。 -# 2. 跑判定矩阵(tests/prove_lean.rs):真定理 proved、假定理 unproved、 -# 证书缓存命中跳判定、--require-lean 退出码。 -# 3. CI 硬性要求(MARQDO_PROOF_REQUIRE_LEAN=1):没有工具链即失败, -# 不允许悄悄降级成 unverified。 -# -# 说明:仓库不强制贡献者装 Lean——本工作流在装有 elan 的 runner 上运行; -# 本地无 Lean 时判定状态为 unverified(advisory,不阻塞)。 -name: proof - -on: - push: - branches: [main] - paths: - - "src/prove/**" - - "doc/verification/skill-proof/**" - - "lib/**" - - "tests/prove*.rs" - - ".github/workflows/proof.yml" - pull_request: - paths: - - "src/prove/**" - - "doc/verification/skill-proof/**" - - "lib/**" - - "tests/prove*.rs" - - ".github/workflows/proof.yml" - workflow_dispatch: - -jobs: - proof: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install Rust (1.81) - run: | - rustup toolchain install 1.81.0 --profile minimal - rustup default 1.81.0 - - # leanprover/lean-action@v1 已移除 lean4-version;本仓库运行时只需 lean 二进制 - # (底座内嵌、不经 lake)。用 elan 钉 v4.35.0,与 doc/verification/skill-proof/lean-toolchain 一致。 - - name: Install Lean 4.35.0 (elan) - run: | - curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain leanprover/lean4:v4.35.0 - echo "$HOME/.elan/bin" >> "$GITHUB_PATH" - "$HOME/.elan/bin/lean" --version - - - name: Verify embedded proof library - run: | - chmod +x scripts/check-proof-library.sh - scripts/check-proof-library.sh - - - name: Build - run: cargo build --locked - - - name: Judgment matrix (real Lean; CI requires toolchain) - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_lean - - - name: Rest of prove suite (no toolchain assumptions) - run: cargo test --locked --test prove - - - name: Corpus monotonicity — offline_checked ⊆ lean_proved (40 fixtures) - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test prove_corpus - - - name: T4 differential consistency — interpreter == Lean - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: cargo test --locked --test conformance - - - name: Full sweep — divergence guard bites on injected fault - env: - MARQDO_PROOF_REQUIRE_LEAN: "1" - run: | - # A3:注入分歧必须显式失败(error[proof.divergence],退 1)—— - # 护栏失灵(静默落绿)比单点失败严重得多。 - set -e - tmp=$(mktemp -d) - cat > "$tmp/审批.mq.md" <<'FIXTURE' - --- - markup: occlusion - --- - - # 台账 - - ## 记录 - + `金额` - - | 定理 | 结论 | 策略 | - |---|---|---| - | 记过即记 | 长度(轨迹) = 1 | auto | - - **结果 = [登记](result.ok(value=`金额`))** - - *结果* - FIXTURE - set +e - out=$(cargo run --locked -- prove "$tmp/审批.mq.md" --fault-inject offline-claim --json 2>/dev/null) - code=$? - echo "$out" | head -c 400 - if [ "$code" -ne 1 ]; then - echo "::error::注入分歧未被拦截(exit=$code)——单调性护栏失灵" - exit 1 - fi - echo "$out" | grep -q "proof.divergence" || { - echo "::error::未出现 proof.divergence 诊断" - exit 1 - } - echo "divergence guard OK" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 1ddd5ff..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,227 +0,0 @@ -# Build and attach release binaries when a version tag is pushed. -name: Release - -on: - push: - tags: - - "v*" - workflow_dispatch: - -permissions: - contents: write - -jobs: - windows: - runs-on: windows-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - - - name: Install Go (web plugin) - uses: actions/setup-go@v5 - with: - go-version: "1.23.x" - - - name: Install Node (VS Code extension) - uses: actions/setup-node@v4 - with: - node-version: "20" - - - name: Install MinGW for cgo (web.dll) - run: choco install mingw -y - - - name: Build release CLI + official plugins - shell: bash - run: | - export PATH="/c/ProgramData/mingw64/mingw64/bin:/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin:$PATH" - cargo build --release - cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering - bash ./scripts/build-web-plugin.sh - - - name: Checkout extension sources (branch vscode-extension only) - run: git fetch origin vscode-extension && git checkout origin/vscode-extension -- vscode-extension - - - name: Build VSIX - shell: pwsh - run: | - $ver = "${{ github.ref_name }}".TrimStart("v") - New-Item -ItemType Directory -Force -Path dist | Out-Null - Push-Location vscode-extension - npm ci - npm version "$ver" --no-git-tag-version --allow-same-version - npm run compile - npx @vscode/vsce package --no-dependencies -o "../dist/marqdo-$ver.vsix" - Pop-Location - - - name: Package - shell: pwsh - run: | - $ver = "${{ github.ref_name }}".TrimStart("v") - $target = "x86_64-pc-windows-msvc" - New-Item -ItemType Directory -Force -Path dist | Out-Null - $exe = "marqdo-$ver-$target.exe" - $zip = "marqdo-$ver-$target.zip" - $stdlib = "marqdo-$ver-stdlib.zip" - $source = "marqdo-$ver-source.zip" - $vsix = "marqdo-$ver.vsix" - $public = "marqdo-$ver-public.zip" - $extZip = "marqdo-$ver-ext.zip" - $nativeZip = "marqdo-$ver-native-$target.zip" - Copy-Item target/release/marqdo.exe "dist/$exe" - git archive --format=zip -o "dist/$source" HEAD - ./target/release/marqdo view output public -o public - Compress-Archive -Path public/* -DestinationPath "dist/$public" -Force - $stageExt = "dist/stage-ext" - if (Test-Path $stageExt) { Remove-Item $stageExt -Recurse -Force } - New-Item -ItemType Directory -Force -Path $stageExt | Out-Null - Copy-Item ext "$stageExt/ext" -Recurse - if (Test-Path "dist/$extZip") { Remove-Item "dist/$extZip" -Force } - Compress-Archive -Path "$stageExt/*" -DestinationPath "dist/$extZip" -Force - # Prebuilt native plugins (no Rust required for `marqdo ext add`) - $stageNative = "dist/stage-native" - if (Test-Path $stageNative) { Remove-Item $stageNative -Recurse -Force } - New-Item -ItemType Directory -Force -Path "$stageNative/native" | Out-Null - Copy-Item target/release/web.dll "$stageNative/native/web.dll" - Copy-Item target/release/agent.dll "$stageNative/native/agent.dll" - Copy-Item target/release/quantum.dll "$stageNative/native/quantum.dll" - Copy-Item target/release/linalg.dll "$stageNative/native/linalg.dll" - Copy-Item target/release/llm.dll "$stageNative/native/llm.dll" - Copy-Item target/release/engineering.dll "$stageNative/native/engineering.dll" - if (Test-Path "dist/$nativeZip") { Remove-Item "dist/$nativeZip" -Force } - Compress-Archive -Path "$stageNative/*" -DestinationPath "dist/$nativeZip" -Force - $stage = "dist/stage-bundle" - if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } - New-Item -ItemType Directory -Force -Path $stage | Out-Null - Copy-Item target/release/marqdo.exe "$stage/marqdo.exe" - Copy-Item lib "$stage/lib" -Recurse - Copy-Item ext "$stage/ext" -Recurse - New-Item -ItemType Directory -Force -Path "$stage/ext/native" | Out-Null - Copy-Item target/release/web.dll "$stage/ext/native/web.dll" - Copy-Item target/release/agent.dll "$stage/ext/native/agent.dll" - Copy-Item target/release/quantum.dll "$stage/ext/native/quantum.dll" - Copy-Item target/release/linalg.dll "$stage/ext/native/linalg.dll" - Copy-Item target/release/llm.dll "$stage/ext/native/llm.dll" - Copy-Item target/release/engineering.dll "$stage/ext/native/engineering.dll" - if (Test-Path "dist/$zip") { Remove-Item "dist/$zip" -Force } - Compress-Archive -Path "$stage/*" -DestinationPath "dist/$zip" -Force - $stageLib = "dist/stage-stdlib" - if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force } - New-Item -ItemType Directory -Force -Path $stageLib | Out-Null - Copy-Item lib "$stageLib/lib" -Recurse - if (Test-Path "dist/$stdlib") { Remove-Item "dist/$stdlib" -Force } - Compress-Archive -Path "$stageLib/*" -DestinationPath "dist/$stdlib" -Force - echo "EXE=$exe" >> $env:GITHUB_ENV - echo "ZIP=$zip" >> $env:GITHUB_ENV - echo "STDLIB=$stdlib" >> $env:GITHUB_ENV - echo "VSIX=$vsix" >> $env:GITHUB_ENV - echo "SOURCE=$source" >> $env:GITHUB_ENV - echo "PUBLIC=$public" >> $env:GITHUB_ENV - echo "PUBLISH_EXT=$((Get-Content ext/VERSION -Raw).Trim() -eq $ver)" >> $env:GITHUB_ENV - echo "EXT=$extZip" >> $env:GITHUB_ENV - echo "NATIVE=$nativeZip" >> $env:GITHUB_ENV - - - name: Upload release assets - uses: softprops/action-gh-release@v2 - with: - body_path: doc/releases/${{ github.ref_name }}.md - files: | - dist/${{ env.EXE }} - dist/${{ env.ZIP }} - dist/${{ env.STDLIB }} - dist/${{ env.VSIX }} - dist/${{ env.SOURCE }} - dist/${{ env.PUBLIC }} - fail_on_unmatched_files: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - - name: Upload independently versioned extension assets - if: env.PUBLISH_EXT == 'True' - uses: softprops/action-gh-release@v2 - with: - files: | - dist/${{ env.EXT }} - dist/${{ env.NATIVE }} - fail_on_unmatched_files: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - linux: - runs-on: ubuntu-latest - # Wait until Windows has created the GitHub Release, then attach Linux zips - # (required: native plugins for `marqdo ext add` on Linux + CLI bundle). - needs: windows - steps: - - uses: actions/checkout@v4 - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - - - name: Install Go (web plugin) - uses: actions/setup-go@v5 - with: - go-version: "1.23.x" - - - name: Install zip + cgo toolchain - run: sudo apt-get update && sudo apt-get install -y zip gcc libc6-dev - - - name: Build Linux CLI + official plugins - run: | - set -euo pipefail - cargo build --release - cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering - bash ./scripts/build-web-plugin.sh - - - name: Package Linux native zip + CLI bundle - run: | - set -euo pipefail - VER="${GITHUB_REF_NAME#v}" - TARGET="x86_64-unknown-linux-gnu" - if [[ "$(tr -d '[:space:]' < ext/VERSION)" == "$VER" ]]; then - echo "PUBLISH_EXT=true" >> "$GITHUB_ENV" - fi - mkdir -p dist/stage-native/native - for lib in libweb.so libagent.so libquantum.so liblinalg.so libllm.so libengineering.so; do - src="target/release/${lib}" - if [[ ! -f "$src" && "$lib" == libweb.so ]]; then - src="plugins/web/build/libweb.so" - fi - test -f "$src" || { echo "missing $src" >&2; exit 1; } - cp "$src" "dist/stage-native/native/${lib}" - done - (cd dist/stage-native && zip -r "../marqdo-${VER}-native-${TARGET}.zip" .) - echo "NATIVE=marqdo-${VER}-native-${TARGET}.zip" >> "$GITHUB_ENV" - - stage="dist/stage-linux" - rm -rf "$stage" - mkdir -p "$stage/ext/native" "$stage/lib" - cp target/release/marqdo "$stage/marqdo" - chmod +x "$stage/marqdo" - cp -a lib/. "$stage/lib/" - cp -a ext/. "$stage/ext/" - cp dist/stage-native/native/*.so "$stage/ext/native/" - linux_zip="marqdo-${VER}-${TARGET}.zip" - (cd "$stage" && zip -r "../${linux_zip}" .) - echo "LINUX_ZIP=${linux_zip}" >> "$GITHUB_ENV" - - - name: Upload Linux packages - uses: softprops/action-gh-release@v2 - with: - files: | - dist/${{ env.LINUX_ZIP }} - fail_on_unmatched_files: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - - name: Upload independently versioned Linux native pack - if: env.PUBLISH_EXT == 'true' - uses: softprops/action-gh-release@v2 - with: - files: dist/${{ env.NATIVE }} - fail_on_unmatched_files: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 94642b7..1ab6813 100755 --- a/.gitignore +++ b/.gitignore @@ -1,127 +1,6 @@ -/target/ -/dist/ -# Plugin unit tests use package-relative scratch checkpoints. -/plugins/agent/target/ - -# Copied by gold harness for ABI plugins -/tests/lib/demo.dll -/tests/lib/libdemo.so -/tests/lib/libdemo.dylib -/tests/ext/agent.dll -/tests/ext/libagent.so -/tests/ext/libagent.dylib -/tests/ext/skel.mq.md -/tests/ext/out-demo.mq.md -/tests/ext/ticket.txt -/tests/ext/ticket-stub.txt -/tests/ext/agents/ -/tests/ext/runbooks/ -/tests/ext/templates/ -/tests/ext/reports/ -**/*.rs.bk -.idea/ -.vscode/ -*.pdb -.DS_Store -.marqdo/ -**/.marqdo/ -.marqdo-ext/ -/vendor/ -/.cargo/config.toml - -# Generated HTML beside tracked public/*.mq.md (sources stay in git) -/public/index.html -/public/pages/ - -# VS Code extension: source only on branch `vscode-extension` (see doc/design/vscode-extension-commit.md) -/vscode-extension/ - -# Python spike venv (local) -spike/.venv/ -spike/__pycache__/ -spike/.pytest_cache/ -**/__pycache__/ -*.pyc - -# Built browser WASM (rebuild via crates/marqdo-wasm README) -/examples/web-client-site/static/marqdo_wasm.wasm - -# Local sqlite / scratch -/data/ -/tmp/ -plugins/*/tmp/ -# web smoke/example DBs (cwd-relative or fixture data dirs) -/web-fixtures/ -/tests/ext/web-fixtures/data/ -/tests/ext/entrydir-fixtures/data/ -/examples/web-site/data/ -/examples/web-site-zh/data/ -/examples/web-net-site/data/ -/examples/web-net-site-zh/data/ -/examples/marqdo-blog/data/ - -# Quantum draw/SVG runtime outputs (sources & gold .mq.md stay tracked) -/tests/ext/quantum-*.svg -/tests/ext/linalg-*.svg -/examples/quantum-*/**/*.svg -/examples/quantum-*/*.svg -/examples/linalg-*/**/*.svg -/examples/linalg-*/*.svg -/examples/linalg-*.svg -# oa2026 showcase: SVGs beside the examples ARE tracked; root-level ones are -# run artifacts (draw/plot write to cwd when the example is run from root) -/bell-*.svg -/calculus-*.svg - -# Plot SVGs emitted beside tests / notebooks when demos run -/tests/**/*-plot-*.svg - -# Lean Lake build outputs (sources under verification/ stay tracked) -**/.lake/ - -# PLDI / thesis harness scratch must never land in this tree -.lx*-tmp/ - -# Local ABI plugin copies (use `marqdo ext add quantum` / cargo build) -/ext/native/ -# Install-root path hints from `marqdo ext add` — never belong in the source tree -/ext/*.plugin - -# Go web plugin c-shared build output (./scripts/build-web-plugin.sh) -/plugins/web/build/ - -# PPA build: bundled Rust toolchain (packed into .orig by ppa-build-source.sh only) -/third_party/rust/ -/third_party/ - -# ephemeral sqlite / test artifacts -tests/ext/:memory: - -# local secrets .env - -# sandbox gold leftovers -tests/ext/_sbx_cow/ - -tests/ext/_sbx_*/ -examples/**/_example_sbx/ -.secrets/ - -# Generated runtime resources for callable browser handbook examples -/examples/web-spa-app/static/marqdo_wasm.wasm -/examples/web-spa-app/static/marqdo-bridge.js -/examples/web-collab-doc/static/marqdo_wasm.wasm -/examples/web-collab-doc/static/marqdo-bridge.js - -# Native browser runtime and compiled theme produced by the network-site handbook. -/examples/web-net-site/public/generated/ -/examples/web-net-site-zh/public/generated/ - -# Generated literary-site theme resources (the declarative sources stay tracked). -/examples/web-site/public/generated/ -/examples/web-site-zh/public/generated/ - -# Native browser-effects example generated resources. -/examples/browser-app/static/marqdo_wasm.wasm -/examples/browser-app/static/marqdo-bridge.js -/examples/browser-app/static/theme.css +.env.* +/.migration-work/ +/.integration-work/ +/__pycache__/ +**/__pycache__/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..9493c80 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,18 @@ +[submodule "cli"] + path = cli + url = https://git.cflmy.cn/cflmy/marqdo-cli.git +[submodule "tests/conformance"] + path = tests/conformance + url = https://git.cflmy.cn/cflmy/marqdo-extension-conformance.git +[submodule "tools/view"] + path = tools/view + url = https://git.cflmy.cn/cflmy/marqdo-view.git +[submodule "tools/knowledge"] + path = tools/knowledge + url = https://git.cflmy.cn/cflmy/marqdo-knowledge.git +[submodule "tools/prove"] + path = tools/prove + url = https://git.cflmy.cn/cflmy/marqdo-prove.git +[submodule "tools/lint"] + path = tools/lint + url = https://git.cflmy.cn/cflmy/marqdo-lint.git diff --git a/.woodpecker/eco.yml b/.woodpecker/eco.yml new file mode 100644 index 0000000..2401989 --- /dev/null +++ b/.woodpecker/eco.yml @@ -0,0 +1,25 @@ +when: + event: [push, pull_request, manual] + +steps: + layout: + image: rust:1.100-bookworm + commands: + - apt-get update && apt-get install -y --no-install-recommends ca-certificates git python3 + - python3 scripts/check-layout.py + - python3 -m unittest discover -s tests/integration + - git submodule update --init + - python3 scripts/check-layout.py --checkouts + + candidate: + # Match the Linux/glibc environment already used by View for the RC.4 artifact. + image: mcr.microsoft.com/playwright:v1.49.0-noble + depends_on: [layout] + commands: + - apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git python3 python3-jsonschema build-essential + - | + set -eu + curl -fsSL --retry 3 https://sh.rustup.rs -o /tmp/marqdo-rustup.sh + sh /tmp/marqdo-rustup.sh -y --profile minimal --default-toolchain 1.100.0 --no-modify-path + export PATH="$HOME/.cargo/bin:$PATH" + bash scripts/integration.sh diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a12fd1a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,8 @@ +# Marqdo 维护指引 + +1. 从 [组件目录](components.toml) 和 [架构边界](docs/ARCHITECTURE.md) 确定唯一责任仓库。主仓库处理 gitlink、集成测试、发行组合与治理。 +2. 找到或建立责任仓库的工单,记录目标、当前提交、最小复现、公共契约和验收命令。跨仓库阻塞在上游开关联工单,并在消费者记录回归条件。 +3. 在责任仓库独立修改、构建和测试。需要调整语义或公共协议时,通过 CLI ADR 评审,与实际消费者同候选验证。 +4. 推送子仓库提交后,再在主仓库提交精确 gitlink。区分组件 CI、公共契约 CI 和生态 CI 的证据。以 [开发流程](docs/DEVELOPMENT.md) 为准。 +5. 新接入组件先核对公开 API、直接依赖、独立入口和实际测试。空仓在 [迁移台账](docs/MIGRATION.md) 中保持 planned。 +6. 记录 FAIL 和 UNVERIFIED 的具体环境、命令和日志。只有实际通过且匹配候选 SHA 的证据才可用于集成与发行。 diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index d0458bd..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,1643 +0,0 @@ -# Changelog - -## v2.9.1 — 2026-11-18 · Full release / 正式补丁版本 - -Marqdo 2.9.1 修复 2.9.0 的库构建回归:`knowledge` 属于核心编译器,不再由 `cli` 特性门控,`default-features = false` 的下游库恢复可编译;并新增 feature-matrix CI 守卫。无运行时语义、插件 ABI 或证书格式变化。 - -**EN:** 2.9.1 fixes the 2.9.0 library regression where the core compiler's `knowledge` module was gated on `cli`, breaking `default-features = false` consumers; a feature-matrix CI gate now prevents regressions. No runtime semantics, plugin ABI or certificate format changes. - -### Fixed - -- Library builds with `--no-default-features` again. `sema::ir` unconditionally - emits `proof-index.json` / `proof-obligations.json` through `knowledge`, but - `knowledge` was gated on `cli`; it is now part of the core compiler, so - downstream crates using `default-features = false` no longer hit - `E0433: could not find knowledge in the crate root`. -- CI: `feature-matrix` checks the library with no features, `cli` only, and - default features to prevent feature-gate regressions. - -详情 / Details: [2.9.1 release notes](doc/releases/v2.9.1.md). - -## v2.9.0 — 2026-11-18 · Full release / 正式完整版本 - -Marqdo Verified Knowledge Compiler: source-addressable knowledge proof artifacts, bounded Lean 4 modular contract composition, precise evidence grades, independent replay, and fail-closed unsupported semantics. - -- Unified source-derived pure-function proof DAG with symbolic parameters, sequential calls, total conditional branches, multi-module imports, and kernel-checked caller contracts. -- Stable statement and theorem anchors, dependency closure signatures, proof indexes and source-change invalidation. -- `proved`, `model_proved`, `tested`, `assumed`, `unknown`, `refuted`, `stale` are distinct; Lean Int-model proofs **do not** prove the complete Marqdo `number` or i64 runtime. -- Independent Lean replay and negative regression tests for changed source, missing preconditions, unsupported effects, and false caller conclusions. -- Full CLI/WASM/ext version synchronization, Windows/Linux native archives and editor release packaging (completion requires actual release workflow and asset verification). -- Existing `marqdo prove` behavior, classic knowledge references, and `marqdo call` remain supported. Unsupported loops, recursive functions, dynamic dispatch, plugins and unverified runtime behaviors never become auto-proved. - -Marqdo 2.9.0(full)发布可寻址知识制品、统一纯函数模块化契约组合、真实 Lean 证书独立重放与证据等级;保留旧证明证书重放。仅支持明确的纯整数抽象子集,不宣称完整运行时正确性或所有函数自动可证。 - -详情 / Details: [2.9.0 release notes](doc/releases/v2.9.0.md) · [Trust boundaries](doc/design/verified-knowledge-compiler-boundaries.md). - -## Ext pack v2.8.1 — 2026-11-18 - -### Highlights - -**AI native durable workflow(CLI 仍为 v2.8.0)**:`ext/ai` 以插件侧步骤机交付持久化 -工作流(`workflow`/`flow`/`context`/`recovery`),含有界模型选择、作用域上下文、 -只读失败恢复、`inspect`/`list` 与可隔离 `resume_dir`。Windows 打包使用 `path.join` -根路径与 `System32\tar.exe`。详见 [双语发布说明](doc/releases/ext-2.8.1.md)。 - -```bash -marqdo ext add agent # CDN latest → 2.8.1 -# 或:MARQDO_EXT_VERSION=2.8.1 marqdo ext add agent -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——仅 Extension / Agent Runtime。 - -### Added - -- `ext/ai/workflow`:`open/next/commit/cancel/tick/retry_*`,以及只读 `inspect`/`list` - 与各操作的 host-relative `resume_dir`。 -- `ext/ai/flow` · `context` · `recovery`:ask/choose、作用域打包、CheckpointV2 恢复面。 -- Agent ABI:`agent_workflow_*`、`agent_choice_parse`、`agent_context_scope`、 - `agent_input_*`、`agent_parallel_report`。 -- Offline fixtures:`tests/ext/ai-native-flow.mq.md`、`tests/ext/ai-native-workflow.mq.md`; - CI:`.github/workflows/native-ai-flow.yml`。 - -### Fixed - -- `flow.choose` no longer leaks a branch-local `parsed` value into the function - contract; the repaired-choice path is fully scoped. -- CI builds the agent cdylib and runs offline integration without the removed - `run --effects` flag, using `MARQDO_AGENT_PLUGIN` instead. -- Atomic checkpoint/effect temp names no longer collide under parallel writes; - resume tests no longer race on process-wide cwd. -- Windows `extension-release`:engineering root 使用 `path.join` / cwd 回退; - ZIP 显式调用 `System32\tar.exe`(bsdtar);`packs.ci` 授予 `fs.read`。 - -### Changed - -- 扩展包 SemVer **2.8.1**(`ext/VERSION`);与 CLI **v2.8.0** 可独立安装。 -- 分支已合并 v2.8.0 依赖锁后的 AI 工作流增量,不再从 2.7.1 基线分叉。 - -## v2.8.0 — 2026-11-17 - -`marqdo prove` 正式发布:定理表 → Lean 4 证明 → 自动判定。离线符号执行(F1–F5)无工具链可用,`checked` 永远弱于 `proved`;单调性护栏让判定器缺陷显式失败;假定理给出反例见证;证书缓存与目录模式面向智能体批量出证。 - -`marqdo prove` ships: theorem tables compile to Lean 4 and are judged automatically. Offline symbolic execution works without a toolchain, monotonicity guardrails fail loudly on judger defects, fake theorems get counterexample witnesses, and certificate caching plus directory mode support agent-scale proving. - -详见 [双语发布说明](doc/releases/v2.8.0.md)。 - -## v2.7.1 — 2026-11-11 - -CLI 修复发布:View 实际逻辑的手动开合不再被布局重排或运行结果刷新覆盖;函数、链接、列表和记录按内容排版,手机详情整行展示。核心仍为 19 个构造;拓展库保留 2.7.0。 - -CLI fix release: implementation disclosures retain mouse/keyboard choices across resize, nested source reading and live replacement. Typed call/link/value details preserve real navigation and read-only inspection. Independent extension packs remain 2.7.0. - -详见 [双语发布说明](doc/releases/v2.7.1.md)。旧静态站点需要用新 CLI 重新导出。 - -## v2.7.0 — 2026-11-10 - -### Highlights / 亮点 - -源码手册进入真实开发与用户站点:原生文件操作、可调用开发/发版流程、递归 View 站点及当前请求资源。CLI、WASM、拓展包与编辑器版本统一为 2.7.0。详见 [完整双语发布说明](doc/releases/v2.7.0.md)。 - -Executable source handbooks now drive actual development and user sites: native file operations, callable release tasks, recursive View Documents and current request resources. CLI, WASM, extension packs and editor version are 2.7.0. - -**核心表面 Δ / Core surface Δ**:无增删,仍为 19 个核心构造;沿用既有 Markdown 标记与插件 ABI。 - -### Added - -- Native development and release handbooks, bounded engineering plugin boundaries, literal CLI JSON file/stdin arguments and --require-ok failure propagation. -- 原生文档表读取与保留正文的修改;纯 head 资源,以及当前请求的数据查询、表单与会话导航资源。 -- Both-language recursive user sites, source-aware route inspection, retained theme declarations and actual browser acceptance. -- Structured nested list/control records in the official bridge, documented in EN/ZH browser libraries and the callable browser-app. - -### Fixed - -- Occlusion receivers, nested and hyphenated-path calls, prose literal defaults and exact CLI argument/session replay semantics. -- 授权站点根下的文件/SQLite 定位;嵌套 Document 与 Endpoint 回调上下文;表单重试 CSRF、成功跳转、管理入口与片段选择。 -- Browser duplicate-item deletion, literal content rendering, Back/Forward history and asynchronous outcome reporting. - -### Changed - -- SKILL discovery delegates to executable handbooks; ordinary file IO and orchestration use Marqdo instead of Python release scripts. -- 中英文用户站点保留原始主题、当前文章与管理能力;移除无关的暗恋工程和过时独立浏览器演示,保留底层测试夹具。 -- Native packs include the engineering plugin. Main excludes editor sources; immutable tags, both-platform builds and independent GitHub/CDN/Ubuntu verification remain release obligations. - -## v2.6.0 — 2026-11-08 - -### Highlights / 亮点 - -标准库、拓展库与阅读界面共同围绕“源码即手册,文档即 SKILL,函数即工具”完成更新。 -CLI、WASM、扩展包与 VS Code 扩展统一为 2.6.0。 - -- 标准库新增完整文件整理、二进制与分块、集合处理、结构化数据、文档修改、HTTP、子任务与时区能力。 -- 61 份公开标准库提供 650 个函数,保持单文件自述;多文件拓展库通过 index 组织真实工作流。 -- Quantum 提供可执行实验与会话句柄;Web 明确从区域树递归拆到 Markdown 叶子的工程方式。 -- View 正文只呈现动作说明,实际逻辑进入左右侧注,空括号明确提示待补逻辑;知识区按输入输出与依据组织。 -- Standard libraries add practical file, binary, collection, structured-data, document, HTTP, task and timezone workflows. -- Libraries are executable handbooks with contracts, narrative parameters and readable inline operations; View separates action text, implementation and observed results. - -**核心表面 Δ(Core surface Δ)**:无增删,仍为 19 个核心构造。新增能力属于 Runtime / Document; -行内遮蔽边界与 GFM 转义修复沿用既有标记,不引入另一套语法或 Skill 编译器。 - -### Added - -- 文件:查找、行读写、JSON/CSV 读写、二进制字节和分块操作、临时资源、单文件原子写、摘要检查、目录批处理与可选 ZIP。 -- 集合:范围、枚举、投影、筛选、首项/任一/全部判断、分组汇总、连接、集合运算、模式校验及 key/value 行记录构造。 -- 数据与工程:Result、完整 TOML、IANA 时区/DST、结构化 HTTP 结果与下载、子任务超时/并发/取消、保留周围叙述的受控文档修改。 -- 标准库单文件手册、开发指南、真实工程示例,以及数据、安全、网络、线性代数、AI 的工程入口与安装依赖。 -- Quantum 任务导航、实验与双语门面;Web 递归布局、普通 Markdown 叶子和双语参考站点;call 会话中传递实际资源句柄。 -- View 核心语法阅读指南、实现侧注、可读知识卡片、最终绑定与调用记录,以及静态/实时/无脚本浏览器验收。 - -### Fixed - -- 修复中文智能体单步被说明中的斜体 map 提前返回、事务构造器返回未绑定 self、策略说明标题被误识别为对象等旧问题。 -- 修复行内遮蔽中标签星号和载荷乘法的结束边界,以及 GFM 单元格的转义竖线。 -- 修复整句遮蔽只处理首个链接、改写叙述的问题;普通导航与文字字面量不冒充可执行逻辑。 -- 单文件 View 只分析实际依赖闭包,避免无关同目录模块重名使知识说明整体不可用。 -- 修复回放策略 wire 命令与 agent smoke 工具注册,保持可执行知识门禁可复现。 - -### Changed - -- 标准库和拓展库的参数与返回表紧接标题;移除库源码中的旧加号形参,使用叙述形参与句中赋值、调用、返回。 -- 每个库单元叙述超过 50%;行内代码和绑定数据表仍计作代码,避免以模板或排版替代说明。 -- 知识区将身份和摘要折叠为技术详情,分别呈现静态检查、测试、来源与领域审阅;阅读操作不会执行代码。 -- 既有可用接口、默认值和副作用边界保持兼容。原生专属能力不宣称在 WASM 可用,目录批处理不宣称事务,摘要写入不宣称内核 CAS。 - -### Validation - -- 本地全量回归 984 通过、0 失败、2 个原有忽略项;发布提交与打包产物另行复核。 -- 实际 wasm32 产物通过 ABI、桥接、双语集合与 32 位边界验收。 -- Chromium 验证七种宽度、实时与静态页面、无脚本回退、源码定位、曲线、帧切换与重新运行。 - -## v2.5.1 — 2026-11-07 - -### Highlights - -**View 标注连线与工具栏优化 / View annotation and toolbar refinement**:执行标注精确绑定源码行与字节区间;连续 S 形曲线取代水平长线,标注贴近正文错落排布,并避让正文和相邻连线;浮动工具栏增加文字说明。CLI · wasm · ext **2.5.1**。 - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造);无 Markdown 语法或插件 ABI 变更。 - -### Fixed - -- 执行标注从实际源码片段引出并连接标注标题,不再从正文边缘引出;多调用帧与循环轮次共用准确的源码区间,避免按类型猜测锚点。 -- 处理源码换行、重跑、窗口变化与字体加载后的连线定位;保留密集区域和窄屏的文内降级。 -- 连线连续弯曲、柔和金绿过渡,并为相邻曲线保留间距;宽屏标注更靠近正文,横纵方向错落排布。 - -### Changed - -- 底部工具栏显示“刷新、设置、运行、清理、更多”,保留深浅色配色与原有操作行为。 -- 新增七种屏宽、曲率、连线交叉、两端定位及共享源码帧绑定的浏览器回归。 -- CLI、WASM、扩展包和 VS Code / Cursor 扩展同步 **2.5.1**;扩展包功能沿用 v2.5.0。 - -## v2.5.0 — 2026-11-07 - -### Highlights - -**View 文档阅读界面重构 / View reader redesign**:暖白金色排版、新 Marqdo 标志与花枝羽毛素材;宽屏执行信息左右引出,窄屏回到正文下方;导航、搜索与悬浮工具栏;实时 view 与静态导出同源,公式和素材离线可用。CLI · wasm · ext **2.5.0**。 - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)。本次变更集中于 view 展示与普通文档执行结果刷新;无 Markdown 语法或插件 ABI 变更。 - -```bash -marqdo view public -marqdo view output public -o site -``` - -### Added - -- 暖白/深色阅读主题、新 Logo、透明花枝与羽毛;顶部导航、正文/函数/文件搜索、阅读设置和悬浮工具栏。 -- 宽屏执行标注左右排布与避让,点击查看完整捕获值;窄屏、密集段落和打印采用正文内标注。 -- 内嵌 KaTeX 0.16.22、字体和装饰素材,静态页面断网仍可渲染公式。 -- 六种屏宽的 live/static 浏览器回归与普通文档重跑结果一致性回归。 - -### Fixed - -- 普通文档重跑后,从同一次执行捕获刷新正文、变量与轨迹,避免为更新标注重复执行。 -- 移除重复的正文 `id="structure"`,确保刷新定位到实际正文;修复搜索框 Escape 关闭与隐藏目录焦点行为。 - -### Changed - -- 函数和变量面板按需打开;调用帧与循环轮次选择保留;高级 notebook 操作从工具菜单进入。 -- CLI、WASM、扩展包和 VS Code / Cursor 扩展同步为 **2.5.0**;扩展包功能沿用 v2.4.0 已发布内容。 - -## v2.4.0 — 2026-11-06 - -### Highlights - -**Oracle journal 作语言值**:`foreign.oracle_journal` / `foreign.replay_check` 把观测与纯比较暴露为普通 Marqdo 值(非仅 notebook API);handle/code 不得入 journal;`copy` 拒绝 code。Bytecode / frontend / foreign session 模块化与 applications 金样例;`verification/replay-policy` Lean 策略身份。CLI · wasm · ext **2.4.0**。 - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——变更在 `lib/foreign` 宿主表面与实现结构,不增 Markdown 标记。 - -### Added - -- **`foreign.oracle_journal` / `foreign.replay_check`**:文档级观测列表与纯 journal 比较(`doc/design/oracle-journal-values.md`)。 -- **回归**:`foreign-oracle-{journal,names,failure}`、`foreign-{,session-}copy-code-refuse`、`tests/oracle_journal.rs`、applications 四场景、`verification/replay-policy`。 -- **文档**:`oracle-journal-values.md`;frontend-call / foreign-library 方向笔记。 - -### Fixed - -- **view notebook API**:`OnceLock` 初始化等待兼容 MSRV **1.81**(不再调用 ≥1.84 的 `wait`)。 -- JSON `float_roundtrip` 特征,减少外联浮点往返失真。 - -### Changed - -- Bytecode compile/VM、foreign_doc/session、sema resolution、notebook interrupt 路径拆模块(行为对齐既有 Strong 契约)。 - -## v2.3.0 — 2026-11-01 - -### Highlights - -**Foreign Strong(session / value / replay)**:会话句柄改为不透明 `handle`(不可 JSON 过桥、禁止 text 伪造);`close` 仿射消费(双 close / use-after-close 故障);`replay_check` 对照 oracle journal(旧 `replay_snapshot` 仅重跑保留);GFM 表行 arity 与列长映射拒绝静默补空;Ω 返回域外整数故障。对齐 PLDI Strong 叙事与 Lean SessionReg / \(V_{\mathsf{safe}}\)。CLI · wasm · ext **2.3.0**。 - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——破坏面在宿主 foreign/session/JSON 与表解析纪律,不增 Markdown 标记。 - -### Added - -- **`Value::Handle`**:`session_open` 返回句柄;session 操作拒绝 text 伪造。 -- **`DocumentSession::replay_check`** + API `/api/session/snapshot/replay_check`;snapshot 录音字段 + **`oracle_journal`**(与 execution journal 分名)。 -- **API** `/api/session/oracle_journal`。 -- **文档**:`doc/design/foreign-strong-correspondence.md`;`v-safe-json.md` 补 Handle / 列 arity / Ω 门。 -- **回归**:`foreign-session-{use-before-open,use-after-close,double-close,cold-replay-empty,isolation,handle-no-serialize,result-vsafe-refuse}`;`tests/errors/table-arity.mq.md`。 - -### Fixed - -- 不等宽 GFM 表不再静默补空单元格;解析报 `table row arity mismatch`。 -- Py/Node session bootstrap:Ω 结果 OOD 整数不再 `default=str` 偷渡,宿主升级为故障。 - -### Changed - -- **`session_close`**:未知 / 已关闭句柄 → 故障(不再返回 `False`)。 -- **`session_list`**:`id` 字段为 `handle`。 -- Snapshot export 含 `ok`/`code`/`stdout`/`result`/`source_hash` 与 `oracle_journal`。 - -## v2.2.2 — 2026-11-01 - -### Highlights - -**\(V_{\mathsf{safe}}\) JSON 整数契约落地**:外联 / `json.parse` / `json.stringify` / `session_set` 等共用映射对齐 Lean ForeignJSON——`|n| > 2^{53}-1` 的 JSON 整数显式拒绝(错误前缀 `json: integer outside V_safe`),禁止 Node 路径静默扭曲;宽整数仍用十进制字符串 + 对端 `BigInt`。CLI · wasm · ext **2.2.2**。 - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——宿主 JSON 契约与测试,不改 Markdown 标记。 - -### Added - -- **`doc/design/v-safe-json.md`**:宿主 ↔ Lean \(V_{\mathsf{safe}}\) 契约锁定(`MAX_SAFE`、encode/decode refuse、嵌套、float 为宿主扩展)。 -- **回归**:`tests/lib/json-vsafe-*`、`foreign-vsafe-*`、`foreign-session-vsafe-refuse`(含算术后越界 refuse)。 - -### Fixed - -- **`src/host/json.rs`**:对域外整数与 `u64 > i64::MAX` 显式失败;不再经 `f64`/`Text` 静默降级。 -- **`doc/design/foreign-kernel.md`**:Int→number 仅当 `|n| ≤ 2^{53}-1`;宽整数走 string 桥。 - -### Changed - -- 外联 JSON 桥与 `lib/json` 行为:OOD 整数从「可能静默失真」改为「诊断失败」。 - -## v2.2.1 — 2026-10-30 - -### Highlights - -**view / 静态导出大纲侧栏修复**:带遮蔽(occlusion)语句的文档页里,Functions / Variables 右侧栏会掉到正文下面;中等窗口宽度下也会被错误叠成单列。CLI · wasm · ext **2.2.1**。 - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——布局与 HTML 闭合修复,不改 Markdown 标记。 - -### Fixed - -- **`marqdo view` / `view output`**:occlusion 行提前返回时未关闭 `.doc-block`,把 `#outline-rail` 嵌进 `document-surface`,侧栏排到文档下方;现已闭合并保留标注带。 -- **view 壳 CSS**:大纲折叠改为按主栏 `@container mq-panel` 宽度(32rem),不再用视口 `960px` 媒体查询把右侧栏压到正文下;极窄时大纲上移到文档上方。 - -## v2.2.0 — 2026-10-30 - -### Highlights - -**函数级调用 `marqdo call`**:同一份 `.mq.md` 已经是文档、知识和程序。这一版补上从外部调用其中某个函数的入口。人继续读这一页;开发者、测试和 Agent 用同一条命令传入参数并执行。知识复用、把函数当工具、逐个函数做测试、改完再跑,都是这一入口的用法,不是另一套 Skill 系统。CLI · wasm · ext **2.2.0**。 - -```bash -marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 -# 5 -marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 --json -``` - -**作用**:最小可执行单位从「整份文件」扩展到「文件里的一个函数」。不必为了试一个函数再写 `# main`、打印和包装程序。 - -**价值**:说明和实现仍在同一页。Agent 读函数旁边的叙述,定位函数,传入参数,得到可检查的结果。正式发布和权限仍走已有的项目验证;`call` 默认不开放写文件、进程、网络和插件。 - -说明页:[public/features/22-函数调用.mq.md](public/features/22-函数调用.mq.md) · [public/features/22-call.mq.md](public/features/22-call.mq.md) - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——新增的是 CLI 入口,不新增 Markdown 标记。`**…**` 仍是语句,`*…*` 仍是返回。 - -### Added - -- **`marqdo call <文件.mq.md> <函数> [名字=值 ...]`**:加载该文件及其 import,按显示路径、SymbolId 或唯一短名定位函数,用现有签名和契约绑定参数,再用现有运行时执行。 -- **`--json`**:成功 `{"ok":true,"result":...}`,失败 `{"ok":false,"error":...}`,错误带诊断 `code`。`--backend tree|bytecode` 与 `marqdo run` 相同;指定函数时两个后端都不会改去跑 `# main`。 -- **默认纯函数**:效应含写入、网络、进程或插件时,执行前返回 `artifact.effect_denied`,副作用不会发生。 -- **参照文档** `examples/calculator.mq.md`,以及用户说明页 `public/features/22-*`。 - -### Fixed - -- 官方语法说明与 Agent 语法卡的标记极性与解析器对齐:粗体是语句,斜体是返回。同步测试会实际运行说明里的调用示例。 -- Bytecode 的 `marqdo run --call-lib-path` 执行被点名的导入函数,不再忽略该参数去跑入口。 -- 隔离运行时冒烟测试补上 `InvokeContext.fs_root`,`--tests` 可以编过。 - -### Changed - -- CLI / wasm / `ext/VERSION` **同步 2.2.0**。扩展包版本号对齐;这一版的新能力在 CLI。 - -## v2.1.5 — 2026-10-27 - -### Highlights - -**Agent 可靠工作台 + EKC 热路径**:ResourceView(JSON/CSV/PDF/image `blob_ref`、locator 页/行)· ToolSpec 授权先于调用 · CheckpointV2 / EffectLedger / ContextPackV2 · EKC `ir.json` 暖机与 `--refresh` · Web 短读/控制面与 execute 槽隔离。CLI · wasm · ext **2.1.5**。 - -```bash -git checkout v2.1.5 && cargo build --release -marqdo ext add web # CDN / Releases → 2.1.5 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——工作台协议与 Agent 运行时合同,不新增 Markdown 标记。 - -### Added - -- **ResourceView v1**:有界 JSON/CSV 渲染;PDF/image `blob_ref`;`locator.page` / 行定位;CSV `text` 供 TablePreview。 -- **Agent 合同**:ToolSpec 注册与 authorize-before-call;CheckpointV2 原子 resume;AgentErrorV1;输出通道;ContextPackV2;EffectLedger(含 mutating `run_tool` 水印)。 -- **Workbench fixtures/schemas**:`tests/workbench_contracts` 协议金样例。 -- **EKC `ir.json` 快照**:`marqdo knowledge` 写入 `.marqdo/ekc/graph/ir.json`;查询命令暖机热加载,免全量重编译。 -- **`--refresh`**:`knowledge preflight` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify` 可强制重编译。 - -### Fixed - -- **工程预检热路径**:`knowledge preflight`(及 find/reuse 等)默认不再每次 `ensure_compiled` 全量 compile,修复聊天「工程预检」墙钟过长。 -- **Web 槽隔离**:`short`/`read`/`control` 不再填满 execute 槽;disconnect≠cancel。 -- **CSV ResourceView**:去掉尾部空行伪影。 - -### Changed - -- 查询类 knowledge CLI:**缺投影才 compile**;CI / 源变更请先 `marqdo knowledge` 或 `--refresh`。 -- CLI / wasm / `ext/VERSION` **同步 2.1.5**。 - -## v2.1.4 — 2026-10-26 - -### Highlights - -**默认隔离 HTTP execute(ADR 0009)**:`class=execute` / `sse-live` / `stream:true` 经 Supervisor worker 池(`marqdo run --call-lib-path`),父进程不再 `CallLibPath` 占 `INVOKE_LOCK`;短读 / 未声明非流式仍 `legacy_serial`(ADR 0008)。`/_runtime/*` 控制面;`runtime.isolated_execution=1`;MR-01 双 60s 假 SSE + 短读金样例。CLI · wasm · ext **2.1.4**。 - -```bash -git checkout v2.1.4 && cargo build --release -marqdo ext add web # CDN / Releases → 2.1.4 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——隔离运行时与 Web execute 路径,不新增 Markdown 标记。 - -### Added - -- **默认隔离 execute(ADR 0009)**:HTTP `execute` / `sse-live` / `stream:true` 经 Supervisor worker 池(`marqdo run --call-lib-path`),父进程不再 `CallLibPath` 占 `INVOKE_LOCK`;可选 route `class`;`/_runtime/*` 控制面;`runtime.isolated_execution=1`。 -- **MR-01 金样例**:`tests/isolated_execute_mr01.rs` + `tests/ext/isolated-execute-site/`(双 60s 假 SSE + 短读并行;槽满拒绝);接入 `executable-knowledge` workflow。 -- **Worker CLI**:`marqdo run --call-lib-path` / `--fs-root` / `--args-json` / `--emit-result`;host `runtime` admit/dispatch/cancel/events。 - -### Fixed - -### Changed - -- **compile 1000 门禁**:executable-knowledge / workbench 路径恢复与能力探测诚实(isolated 默认开启)。 -- CLI / wasm / `ext/VERSION` **同步 2.1.4**。 - -## v2.1.3 — 2026-10-25 - -### Highlights - -**知识工作台运行时合同(M00–M06)**:`ModelSelectionV1` / `RunContextV1` / `ModelCallUsageV1` / `DocumentViewV1` / locator / snapshot;严格 selection;usage null≠0;`view document` 只读嵌入;LLM messages + cancel;agent.step selection 继承假模型 e2e;USTC 兼容 live smoke(env 注入)。CLI · wasm · ext **2.1.3**。设计证据仍为 Partial(原生适配器 unavailable;完整宿主 F12 留给应用)。 - -```bash -git checkout v2.1.3 && cargo build --release -marqdo ext add llm # CDN / Releases → 2.1.3 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——工作台合同与 View/LLM/Agent 扩展面,不新增 Markdown 标记。 - -### Added - -- **Workbench M00–M06**:capabilities / selection / RunContext / usage / DocumentView / locator / SnapshotManifest;`tests/workbench_contracts`(含 F02 agent.step+resume、F14 并发);`marqdo view document --out` 只读 HTML 嵌入。 -- **LLM**:`messages=` / `selection=` / `strict_selection`;cancel token;reasoning_content 回退;双端点隔离门禁。 -- **Live**:`tests/workbench_live`(`OPENAI_*` env only;`MARQDO_EXT` 指向仓内 `ext/`)。 -- **Agent skeleton**:子工作簿禁 `llm.llm`,从 env selection `llm.create`。 - -### Fixed - -- **`llm.ask` 升参**:hoist `p` 避免缺参 `missing argument for parameter p`;避免 `~/.marqdo/ext` 陈旧包遮蔽仓内 `ext/`(测试强制 `MARQDO_EXT`)。 - -### Changed - -- CLI / wasm / `ext/VERSION` **同步 2.1.3**。 - -## v2.0.0 — 2026-10-22 - -### Highlights - -**遮蔽语法(Occlusion)落地**:`[描述](实现)` —— 方括号是给人读的描述(**永不执行**),圆括号是**唯一执行体**。配套 `()` 内调用、`access` 取元、`遍历` 遮蔽循环、`labels` 两级检索与债务棘轮、`migrate labels` 迁移;`view` 把描述渲染为正文、实现渲染为代码片、空载荷给「桩」徽章。全仓 **80 个语料文件 / 256 处取元 / 23 处循环** 已迁移(M7),语义零漂移。 - -```bash -git checkout v2.0.0 && cargo build --release -marqdo ext add web # CDN → 2.0.0 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)—— 遮蔽是既有 `[键](集合)` 与 `- [项](集合)` 形状在 `markup: occlusion` 文件中的**第二种读法**,默认 `classic` 语义不变;`access` 是宿主函数(id 212),不是新标记。 - -### Added - -- **M2 遮蔽语法**:`[描述](实现)`;`[]` 为自由文本、永不执行,`()` 为唯一执行体;支持嵌套;空载荷 `()` 值为 `None`(桩)。frontmatter `markup: occlusion` 按文件启用,`MARQDO_MARKUP=occlusion` 可作进程默认。 -- **M1 `()` 内调用**:`加(1)` / `加(1, 2)` / `加(加(1 2), 10)` / `加一 号(31)`(callee 可含空格,解决 D8)/ `txt.str_trim(" x ")`;`)` 是参数终止符,逗号可选,支持嵌套;括号形参数按表达式解析,空格形(`> f k=v`)仍按文本。 -- **M3 `access` 与遮蔽循环**:新增宿主函数 `access(集合, 键)`(别名 `取` / `取值`),与旧取元逐字等价;`- [描述](遍历 集合 为 变量)` 遮蔽循环,接受 `遍历`/`for` 与 `为`/`as`/`in`。 -- **M2.5 / M4 遮蔽诊断**:`label.missing`(空描述,error)、`label.empty_payload`(空载荷,warning)、`label.ref_dangling`(描述里的反引号实体不可解析,error);由 `marqdo check` 一并输出。 -- **M5 隐式遮蔽**:`marqdo check --implicit-labels` 把 `>` 调用上方的叙述当作描述(默认关闭,不改变既有输出)。 -- **M6 T1 会话内陈旧检测**:MLSP `repair_apply` 前后对照 payload 并返回变更的遮蔽点;新增 `session.summary` 会话末一次性汇总。 -- **M7 迁移与版本门**:frontmatter `markup:` 按文件切换解析模式(同进程可混载 classic / occlusion,imports 亦然);`marqdo migrate labels`(多路径、`--write`、`--json`)把 `[键](集合)` 改写为 `[键](access(集合, "键"))`、`- [项](集合)` 改写为遍历形。 -- **M8 债务棘轮与呈现**:`marqdo labels --baseline FILE` 记欠据、`--fail-on-increase` 只许降不许升;`view` 浏览 / 卡片 / 静态导出一致呈现遮蔽:描述为正文、实现为代码片、空载荷「桩」徽章。 -- **M9 两级词表检索**:`marqdo labels`(默认 `pending` 口径 / `--grep` 自定义词 / `--group` / `--also-builtin` / `--count` / `--json`,支持多路径);MLSP `labels.search`;兼容文档写法 `labels pending` / `labels search`。 -- **M10 工程化落点**:`ext/ai` 提示词加入「接不了就申报」;README「工程习惯」;空载荷一律 warning。 -- **示例与教程**:`examples/syntax-tour` 一页跑通全部现行语法;`examples/oa2026-showcase`;`doc/tutorial/15-常见陷阱.md`(D1–D10 实测)。 - -### Fixed - -- **D9 未闭合引号**:不再静默吞掉后续行——分类层与解析层双层修复,直接报错并给出原始行。 -- **`加(31)`**:曾被解析成 `unknown function 加(31`(末个位置实参吞掉 `)`)。 -- **view 解析模式回归**:带 `markup: occlusion` 的文档在 `view` 结构区报 `expected ')' after link-index collection`;新增 `load::parse_source_auto` 统一五处解析点。 - -### Changed - -- **HostFn 单表**:五张分派表合一为 `HOST_FN_TABLE`(`src/host/dispatch.rs` **−404 行**),203 项逐字节一致,行为零变化。 -- **插件 ABI 共享 crate**:新增 `marqdo-plugin-sdk`,5 个原生插件共用同一份 ABI 前言;**ABI 不变**(`include/marqdo_abi.h` / 符号与布局不变)。 -- **精简**:删除归档的 Rust web 插件 `plugins/web-rust-archive/`(14,235 行,非 workspace 成员,已由 Go `libweb` 取代);删除无调用点死代码,收拢 `as_text` 18 处重复、catalog 助手与 view 路由 34 臂,AST 遍历器合流。 -- **语料迁移(M7)**:`public/` `ext/` `tests/` `examples/` `doc/` 等语料加 `markup: occlusion`,改写 **80 个语料文件 / 256 处取元 / 23 处循环**;新增 `tests/ratchet` 锁定标签债务。 -- **文档**:遮蔽语法总纲 + M0–M10 变更记录、标签新鲜度 / 修复回路、函数作为值 6 篇评估、代码体量审计;`doc/design/code-volume-audit.md` 记 53k 行构成。 - -## v2.1.0 — 2026-10-23 - -### Highlights - -**文件级可执行知识语义**:标准库、扩展库、示例与公开文档全部采用显式 `markup: occlusion`;`[描述](实现)` 成为默认链接语义,`access` 与 `遍历` 承担原有取元与循环职责。迁移工具可离线证明语法形状等价,Tree 与 Bytecode 均完成全量回归。 - -```bash -git checkout v2.1.0 && cargo build --release -marqdo ext add web -``` - -**核心表面 Δ**:默认链接语义从 Classic 切换到 Occlusion。未迁移的旧 `[键](集合)` 仅可用 `markup: classic` 或一个版本周期内的 `marqdo run --legacy-markup` / `check --legacy-markup` 执行。 - -### Added - -- **文件级新语义迁移**:`marqdo migrate labels --mark` 可把整个库/目录迁移到显式 `markup: occlusion`,即使文件没有旧式索引也不再依赖进程默认值。迁移验证为语法级、无导入解析依赖,并在写入前比较 Classic 与 Occlusion AST 形状。 -- **显式过渡入口**:`marqdo run --legacy-markup` 与 `marqdo check --legacy-markup` 可在一个版本周期内审阅未迁移的旧文件;环境变量不再改变语法。 - -### Fixed - -- 标准库、扩展库、示例、公开文档与可解析测试夹具迁移为文件级 Occlusion;旧的 `[键](集合)` 和 `- [项](集合)` 分别改为 `access` 与 `遍历`。 - -### Changed - -- 未标注源码默认采用 Occlusion。Classic 仅能通过明确的 frontmatter 或 `--legacy-markup` 进入,避免同一文档因进程配置而静默改变含义。 - -## Unreleased - -### Added - -### Fixed - -### Changed - -## v2.1.2 — 2026-10-24 - -### Highlights - -**可执行知识生产消费链 + View 阅读体验发版门槛**:证据摘要进闭包/句柄;`artifact.verify` / `knowledge adjudicate` 结构化裁决;`artifact.reuse_execute` 与 `agent_eng_bind_execute` / `publish_gate` 实际复用(非 n-gram);`document.extract` 文本/Markdown + PDF/OCR 显式失败;View `KnowledgePresentation`、说明锚点、SSE `page_token` 过期包拒绝;上传 `max_bytes`;门禁 45 项(含 100/1000 单元)。CLI · wasm · ext **2.1.2**。 - -```bash -git checkout v2.1.2 && cargo build --release -marqdo ext add web -cargo test --offline --locked --test executable_knowledge -``` - -**核心表面 Δ(Core surface Δ)**:**无增删关键词**——语义/MLSP/View/Agent 宿主扩展;不改变默认 Occlusion 链接读法与表几何。 - -### Added - -- **证据与闭包(F0/M02)**:来源 digests 进入 artifact/evidence/closure;business handle 改/删来源失效;锚点/可读性诊断。 -- **验证裁决(F0/M03)**:`artifact.verify` 结构化 `may_bind` / `may_publish`;policy 枚举;`knowledge adjudicate`;CLI `--fail`。 -- **语法 Skill(F0/M05)**:CORE SYNTAX 置顶;`migration-classic.md`;`skill_core_card` 与预算截断防护。 -- **绑定执行(F1/M04)**:`artifact.reuse_execute`;`agent_eng_bind_execute` + `eng_publish_gate`(`candidate_only` / product gate);host_query `mlsp`;`tests/ext/agent-eng-bind-gate.mq.md`。 -- **发布与来源(F2/M06–M07)**:统一 `EXCLUDED_DIRS`;`publish_manifest.json`;`function_sources` 函数级来源覆盖。 -- **文档提取(F3/M01)**:`document.extract` DocumentSource→ExtractedDocument;PDF/DOCX/OCR 显式 `failed`;超限截断 `partial`;Web 上传 `MaxBytesReader` / `LimitReader`。 -- **View V0–V3(子集)**:正文优先;no-exec;`KnowledgePresentation`(`semantic_generation` / `page_token` / `local_deps`);SSE 过期包拒绝与帧选择保留;print/响应式;1000 单元 compile smoke。 -- **故事门禁(M08)**:建库→复用→来源变更失效→修复重绑。 - -### Fixed - -- View 说明链接 raw-string 截断;skill_brief / CORE SYNTAX 预算不被冲突旧规则吃掉。 -- 上传体积限制在 multipart 解析前生效(不再只靠内存 form 预算)。 - -### Changed - -- CLI / wasm / `ext/VERSION` **同步 2.1.2**。 -- `tests/executable_knowledge` 门禁扩至 45 项;README 切片进度表与发版子集对齐。 - -## v2.1.1 — 2026-10-23 - -### Highlights - -**可执行知识主链落地(S0–S6)**:BoundCall 双后端共享解析、正文 NarrativeRef、来源/适用期、digest 保护补丁与纯表达式提取、整代 `CURRENT` 投影与闭包摘要;订单发票示例双后端输出 `113`;离线门禁含 100 单元语料与 CLI 冒烟。 - -```bash -git checkout v2.1.1 && cargo build --release -marqdo ext add web -marqdo run examples/executable-knowledge/docs/invoice-answer.mq.md -``` - -**核心表面 Δ**:**无增删关键词**——同模块 `Type.member` 纳入 BoundCall;语义投影新增 `bound_calls` / `dynamic_calls` / `hashes.closure` / NarrativeRef 步骤;不改变默认 Occlusion 链接读法。 - -### Added - -- **BoundCall / DynamicCall**:`sema::bind::resolve_for_exec`;Tree 与 Bytecode 静态路径对齐;`bound_calls.json` / `dynamic_calls.json`;同模块定义树路径绑定。 -- **NarrativeRef**:注释行 Markdown 链接 → `narrate` / `navigation` 步骤;围栏与行内代码不计步骤。 -- **来源与适用性**:frontmatter `sources` / `valid_until` → `evidence=sourced|expired|missing_source`;`artifact.bind policy=business`。 -- **局部编辑与提取**:MLSP `artifact.patch`(digest + wording 回滚);`artifact.extract_pure` 纯表达式预览。 -- **整代与闭包**:`generations//` + `CURRENT`;`hashes.closure` 随依赖变化;锁报告 `classes`。 -- **门禁**:`tests/executable_knowledge`(含 100 单元);CI `.github/workflows/executable-knowledge.yml`;项目扫描 depth/size/count 上限。 -- **示例**:`examples/executable-knowledge` 发票含税链可运行;负知识文档。 - -### Fixed - -- Bytecode 裸名解析不再跨 import scope 误连同名函数;同模块 `Type.member` 写入 path_index 供兄弟调用。 - -### Changed - -- Agent / reuse 发现结果标记 `discovery_only` + `bind_required` / `bind_targets`,不可把打分结果直接当可执行目标。 - -## v1.5.2 — 2026-10-18 - -### Highlights - -**外联 v3 P0/P1**:session eval 支持 raw stdin(Python/Node 持久内核);每 cell 独立 stdin 与 Interrupt;plan generation/add/remove/value API;snapshot export/import/replay;`view capture` / `view output --snapshot` 捕获实时快照;显式 Persist 按钮。CLI · wasm · ext **1.5.2**。 - -```bash -git checkout v1.5.2 && cargo build --release -marqdo ext add web # CDN → 1.5.2 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——外联 v3 扩展 `lib/foreign` 库 API;不改 MQ 关键词 / 表几何。 - -### Added - -- **raw stdin + 每 cell 输入**:session eval 支持 raw stdin;`foreign.session inputs=` 每 cell 独立 stdin;view 增加每卡 stdin 字段与 Interrupt 按钮。 -- **plan API**:plan generation/add/remove/value;运行时 plan 更新与 generation。 -- **snapshot**:snapshot export/import/replay;`view capture` / `view output --snapshot` 捕获 live 快照用于静态导出。 -- **显式 Persist**:Persist 按钮 + `/api/session/cell/persist`。 -- **嵌套 plan 边界**:显式 persist 与嵌套 plan 边界;foreign 拒绝嵌套 view plans。 - -### Fixed - -- **`session_list` arity**:保持空 arity。 - -### Changed - -- CLI / wasm / `ext/VERSION` **同步 1.5.2**。 - -## v1.5.1 — 2026-10-18 - -### Highlights - -**view 静态/动态统一 + 外联值传递**:静态导出与 live view 共用同一套 `foreign_doc` 执行路径;构建时实际运行代码单元并注入 stdout;`foreign.session` 可把 Marqdo 值传入多内核会话;cell stdin 支持 live/static/持久内核三种模式。CLI · wasm · ext **1.5.1**。 - -```bash -git checkout v1.5.1 && cargo build --release -marqdo ext add web # CDN → 1.5.1 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——view 执行路径统一 + 外联值传递;不改 MQ 关键词 / 表几何。 - -### Added - -- **外联值传递**:`foreign.session kernels= cells=` 可把 Marqdo 值传入多内核 view 会话;`view` 只消费 `会话` 绑定,不再识别 `内核表` / `会话表` 保留名。 -- **Cell stdin**:view 增加 `Cell stdin / input` 输入框;Run/Step/Run All 都会传给外联 cells;无状态 cell 使用 raw stdin,持久内核使用 `marqdo_input`;静态导出使用 frontmatter `stdin` 作为构建时输入。 -- **静态导出真实执行**:构建时实际执行代码单元并把 stdout/stderr 注入代码卡;静态示例通过代码 fallback 或 frontmatter `stdin` 提供输入。 -- **可运行外联写回示例**:新增 `examples/foreign-writeback/index.mq.md`,用 `foreign.run` + `writeback.record` 将结果写入 `.mq.md` 的 keyed 槽位。 -- **写回块分组与主题**:view 对写回块按目标分组并统一主题样式。 - -### Fixed - -- **code 卡控制恢复**:恢复每个代码卡的内核切换下拉与 Clean 按钮;Clean 清除单个 cell 输出/记录,不重启内核。 -- **导入函数返回锚定**:导入函数的返回值锚定在调用位置。 -- **静态导出自包含**:静态示例不再依赖空 stdin 或外部内核状态。 -- **Execution 输出清除**:view 清除 Execution 输出从 view 表面。 -- **文档表不再变 call chips**:view 不再把文档表转为 call chips。 -- **写回表标签**:写回表标签保持为行内代码。 - -### Changed - -- **静态/动态统一执行路径**:static 与 live cells 使用同一 `foreign_doc` `run_all` 路径;移除 `In []` / `Out []` 与 Notebook 品牌。 -- **静态按钮行为**:静态页面执行按钮点击显示"静态页面无法真实执行",不伪造成功。 -- **低层会话评估可见**:文档展示低层 session evaluation 为代码围栏。 -- CLI / wasm / `ext/VERSION` **同步 1.5.1**。 - -## v1.5.0 — 2026-10-18 - -### Highlights - -**外联 v2 / 文档原生 Notebook**:`lib/foreign` 从“运行一段代码”升级为完整外联内核:结构化 `invoke` 记录、JSON 进出的 `call` / `call_many`、并行扇出、Python/Node 持久内核、显式状态桥,以及用绑定表声明的 Notebook 单元。`view` 增加 cell 单步、Run All、内核切换、journal、状态面板、浅/深主题与可调高度代码区;高对比度 token 修复了代码和 STRUCTURE 文字与背景区分度不足的问题。CLI · wasm · ext **1.5.0**。 - -```bash -git checkout v1.5.0 && cargo build --release -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——外联 v2 只扩展 `lib/foreign` 的库 API;Notebook 的 `内核表` / `会话表` 是既有绑定表;没有新增 Markdown 标记。 - -### Added - -- **用户静态站(外联 / OKF / EKC)**:新增中英双语 `features/19-foreign-view-cells` 与 `features/20-okf-ekc`,重写 `stdlib/foreign`,首页加入「一份文件三个面」、外联 Python 运行、Notebook 表、OKF/EKC 与 preflight 说明。 -- **`lib/foreign` F0/F1**:`invoke` 结构化记录(`ok`/`code`/`stdout`/`stderr`/`ms`/`timed_out`/`truncated`/`result`);`run`/`run_lang` 新增 `env`/`cwd`/`timeout`/`args`/`max_output`;15 个语言预设;`probe`/`register`/`unset`/`load_config`;`.marqdo/foreign.toml`。 -- **`lib/foreign` F2**:JSON 进 / JSON 出 `call`;并行 `run_many` / `call_many`(有序、单项隔离、并发上限);`invoke` 的 `input` / `output` / `result` / `result_error`。 -- **`lib/foreign` F3/F3.5**:Python / Node 持久会话 `session_open` / `session_eval` / `session_close` / `session_list`;状态桥 `session_set` / `session_get` / `session_names`;会话超时即杀、崩溃隔离、drop 清理。 -- **Notebook D1/D2**:`内核表` / `会话表` 文档原生语法;`DocumentSession`(cell index / 命名内核 / journal / value store);view Notebook 工具栏(Run All / Restart & Run All / Step / State / Journal / Reload)、状态徽标、内核下拉、Push/Pull 状态表单;`POST /api/session/*`。 -- **Notebook D3**:`reload` 重新解析并保留内核,源码变更的 cell 标为 `dirty`;Journal/Reload/Debug 按钮;Debug 打开同一 view 服务的语句级单步页(`/debug` + `/api/debug/*`);状态桥 Push/Pull。 -- **安全与健壮性**:所有外联入口检查 `exec` 能力;有界 stdout/stderr 读取与截断标记;stdin 写线程;Unix 进程组 / Windows `taskkill /T` 超时清理;shell-like argv 切分。 - -### Fixed - -- **view 文档表面与标注 chip**:把旧 view 的 `--ink` / `--fill` / `--line` 等 token 映射到当前主题,修复 STRUCTURE 中 `main`、`内核表 =`、函数名和 annot-chip 深色文字/白色卡片与暗色背景不一致的问题。 -- **view 代码对比度**:移除会互相覆盖的 highlight.js 深/浅两套外链样式,改用内置高对比 token 变量;深色代码正文 `#f0f0f0` on `#1e1e1e`(14.6:1),浅色 `#24292f` on `#f6f8fa`(13.8:1);关键词/字符串/注释均使用可读的对比色。 -- **view 反向代理兼容**:Notebook / Debug 的 API 与 Debug URL 改为相对路径,可在 `/marqdo-view/...` 路径前缀下工作,便于 Docker 内通过 DSH 同源预览。 -- **分支内共同局部变量**:if/else 各臂都赋值的局部变量不再被误提升为必选形参;修复 `# llm` 构造器无端要求 `key`,恢复 agent/llm/ext 全量测试。新增 `branch_else_common_local_is_not_a_param` 回归测试。 -- **外联临时脚本路径**:入口目录为相对路径时,脚本参数现在使用绝对路径,避免 `tests/lib/tests/lib/...` 双拼接。 -- **外联失败可观测**:解释器不存在时进入 `invoke` 记录,`run` 仍报错;view 显示 stderr / exit / ms。 - -### Changed - -- **Notebook view 视觉重做**:采用 VS Code Dark 的扁平色板与 Jupyter 的 cell 组织:单一深色底、明确 surface/border 层级、`In [n]` / `Out [ ]` 提示、顶部 cell 工具栏、无渐变/无重阴影、暗色代码区与一致的字号/间距;保留并统一原始左侧文件导航、右侧 Functions/Variables 栏与 Execution/Source 区块;支持深色/浅色主题切换(localStorage 记忆)与代码区、输出区纵向拖拽调整高度。 -- **`langs`** 现在返回「预设 ∪ 注册 ∪ 配置」的已知语言(原集合是子集)。 -- 大输出从 `Err` 改为「截断 + `truncated=true`」;`subtask` 外联输出同步采用该语义。 - -## v1.4.6 — 2026-10-16 - -### Highlights - -**裸自增升参**:粗体首次赋值的左值按设计 §8.2 视为声明。`**n = n + 1**` 在没有反引号提及时也会把 `n` 升成必选形参;缺参报 `missing argument for parameter`,不再是函数体内的 `undefined variable`。纯局部赋值(`**score = 1**`)与循环变量不升参。CLI · wasm **1.4.6**(扩展包仍为 **1.4.5**)。 - -```bash -git checkout v1.4.6 && cargo build --release -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——升参与 §8.2 对齐(赋值左值声明);不改 MQ 关键词 / 表几何。 - -### Fixed - -- **升参**:`merge_inferred_params` 纳入首次粗体赋值左值。右值在绑定前读取同名(`n = n + 1`)时,该名成为必选推断形参。 - -### Changed - -- CLI / wasm SemVer **1.4.6**。扩展包保持 **1.4.5**。 - -## v1.4.5 — 2026-10-16 - -### Highlights - -**Streamable HTTP MCP + web `/v1` 鉴权硬化**:`agent_mcp_serve` 支持 `transport=http`(MCP Streamable HTTP 2025-03-26);web invoke 注入 `Authorization` / `X-Api-Key`,`ok=false`+`unauthorized` → HTTP 401;`ext/ai` openai/agent 字段访问改 `json.get`,消除 footnote 硬崩。CLI · Ext · wasm **1.4.5**。 - -```bash -git checkout v1.4.5 && cargo build --release -cargo build --release -p marqdo_plugin_agent -# HTTP MCP: -# QDAGENT_MCP_TRANSPORT=http marqdo run cli/求道-mcp.mq.md -marqdo ext add agent # CDN → 1.4.5 -``` - -**核心表面 Δ(Core surface Δ)**:**新增** MCP Streamable HTTP 传输(`transport=http|streamable-http`);web invoke 契约扩展(header 注入 · 401);**无** MQ 关键词 / 表几何变更。 - -### Added - -- **`agent_mcp_serve` Streamable HTTP**:`transport=http` · `host`/`port`/`path`;POST JSON-RPC + 可选 GET SSE;`Mcp-Session-Id`。facade:`ext/ai/agent` `## serve`。 - -### Fixed - -- **web invoke**:`Authorization` / `X-Api-Key` 注入 payload;`jsonWrapInvokeValue` 对 `unauthorized` 返回 401;`{sse}` 自动 event-stream。 -- **`ext/ai/llm/openai` · `agent` · `llm`**:字段访问改 `json.get` / `at`,避免 `[field](x)` 在非 map 上硬崩。 -- **explore workbook**:子任务 `stream=False`(网关 SSE 524 更稳)。 - -### Changed - -- CLI / Ext / wasm SemVer **1.4.5**。 -- 设计:[doc/design/ext-web-artifact.md](doc/design/ext-web-artifact.md)(sse / bearer)。 - -## v1.4.4 — 2026-10-16 - -### Highlights - -**LLM 传输软失败 + `ext/ai` 表优先重构**:上游连接拒绝/超时/HTTP≠200 时,Runtime 返回结构化 `finish|status=error`(不再硬中断 VM);`agent` / `智能体` / `llm/openai` 去掉 `json.set`/`json.append` 袋胶水。含 CLI host · `plugins/llm` · Ext pack **1.4.4**。 - -```bash -git checkout v1.4.4 && cargo build --release -cargo build --release -p marqdo_plugin_llm -marqdo run tests/ext/agent-llm-transport-soft.mq.md -marqdo ext add agent # CDN → 1.4.4 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——HTTP 宿主软失败契约 + Extension 风格重构;不改 MQ 关键词 / 表几何。 - -### Fixed - -- **LLM / Agent 传输软失败**:`host_http_post` / SSE · `plugins/llm` · `ext/ai/llm/openai` 结构化 `finish=error`;`agent.step` / `plan` / `run` 收成 `status=error`。金样 `tests/ext/agent-llm-transport-soft.mq.md`。说明:[doc/research/agent-llm-transport-soft-2026-10.md](doc/research/agent-llm-transport-soft-2026-10.md)。 -- **`agent.run`**:`cache == "soft-hit"` 引号比较(裸 `soft-hit` 曾被解析为减法)。 - -### Changed - -- **`ext/ai` 去 json 胶水**:结果 map / 事件用 GFM 表 + `table.put` / `table.append` / `table.empty_*`。SKILL 正面示例:`.cursor/skills/marqdo-dev` §2 · `marqdo/examples.md` §6e。 -- CLI / Ext / wasm SemVer **1.4.4**。 - -## Ext pack v1.4.3 — 2026-10-16 - -### Highlights - -**Agent cold EFI / resolve 硬崩修复(CLI 仍为 v1.4.2)**:qdagent 接通 `agent.run` 时空 OKF 触发 `unknown function preflight` 与 `missing map key llm_free`。本包修复 `ext/ai/agent` facade 与 `agent` native;金样 `tests/ext/agent-run-cold-efi.mq.md`。说明:[`doc/research/agent-run-efi-resolve-bugs-2026-10.md`](doc/research/agent-run-efi-resolve-bugs-2026-10.md)。 - -```bash -marqdo ext add agent # CDN latest → 1.4.3 -# 或:MARQDO_EXT_VERSION=1.4.3 marqdo ext add agent -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——仅 Extension / Agent Runtime 契约修补。 - -### Fixed -- **`agent.run`**:`efi=True` 改为 `` `self`.preflight ``(不再裸调全局 `preflight`)。 -- **`agent_resolve` miss**:返回字段对齐命中路径,含 `llm_free: false`;facade 对 `llm_free` / route 字段改用 `json.get`。 - -### Changed -- 扩展包 SemVer **1.4.3**(`ext/VERSION`);与 CLI **v1.4.2** 可独立安装。 - -## v1.4.2 — 2026-10-16 - -### Highlights - -**Agent/LLM 优化 O1–O5**:`ext/ai/sandbox` CoW 试跑接入 `agent.trial` / `run sandbox=`(默认关);promote 强制 sandbox proof;步骤路由 `step_route` + EFI preflight + `usage`/`token_cost`;风格 lint 与 `sandbox.report`;技能 `quarantine` 与离线 standing/policy 优化脚本。表优先、少 json 胶水。路线:[ext-ai-optimize.md](doc/roadmap/ext-ai-optimize.md)。 - -```bash -git checkout v1.4.2 && cargo build --release -cargo build --release -p marqdo_plugin_agent -marqdo run tests/ext/agent-sandbox-optin.mq.md -marqdo run examples/agent-sandbox-okf/index.mq.md -# Ubuntu: sudo apt update && sudo apt install marqdo -marqdo ext add agent # CDN latest → 1.4.2 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Extension / Agent Runtime**(`ext/ai` 沙盒与晋升闸门),不触碰语言标记。 - -### Added -- **`ext/ai/sandbox`**:CoW 工作区(`open` / `run` / `diff` / `commit` / `discard` / `inspect` / `profile` / `report`);经 `plugins/agent` `sandbox_*` → `host_query`;默认拒 `plugin`/`exec`/`net`。 -- **O1**:`agent.trial` · `run`/`step` `sandbox=` · 中文 `试跑`/`沙盒=` · 示例 `examples/agent-sandbox-okf/` · 金样 `agent-sandbox-optin`。 -- **O2**:`agent_kb_promote` 默认 sandbox proof;OKF `applies_when`/`fixtures`/`sandbox_profile`/`proof`;harness Skill Lift。 -- **O3**:`agent.step_route` · `ext/ai/policies/step-route.mq.md` · `run efi=`(缺工程知识时软放行)· 结果 `usage`/`token_cost`。 -- **O4**:`scripts/mq-style-lint.sh` · `sandbox.report` markdown 审阅面。 -- **O5**:`agent_kb_quarantine` / `agent.quarantine` · `scripts/optimize-standing-policy.sh`。 - -### Fixed - -### Changed -- CLI / wasm / `ext/VERSION` **同步 1.4.2**。 -- Skill:强制表/链接取元、禁同文件混 EN/ZH、点名 sandbox 试跑习惯。 - -## v1.4.1 — 2026-10-15 - -### Highlights - -**view 叙述标注连线**:Browse / `view output` 中 underline→chip 改为 SVG 正交连线(描述底边中点 → 轨道 → 短竖线 → 值顶边中点);同跨度多帧 chip 共用 annot id;可见 chip 按锚点 L→R;帧切换后重算密度。设计:[view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md)。 - -```bash -git checkout v1.4.1 && cargo build --release -marqdo view public/00-welcome.mq.md --no-open -marqdo view output public -o /tmp/mq-public -# Ubuntu: sudo apt update && sudo apt install marqdo -marqdo ext add web # CDN latest → 1.4.1 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 标注几何与帧 chip 对齐),不触碰语言标记。 - -### Added -- 设计缺口文档 [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md):叙述 fence 卡、帧感知 chip 密度、L-leader 几何约定。 - -### Fixed -- view L-leader:id 与 mark 错配、chip 逆序交叉、border 无色变黑碎段、横线穿过 chip 文字;现为 mid→mid SVG path。 -- 叙述 fence / 代码卡单层渲染;静态页隐藏 Run;主文函数引用 call chip + leader。 - -### Changed -- CLI / wasm / `ext/VERSION` **同步 1.4.1**。 - -## v1.4.0 — 2026-10-15 - -### Highlights - -**叙述统一 + 公式 meta + 图片自写回**:块公式 `% marqdo: var=`;分支/循环体与函数体同权叙述;foreach 中英糖;自写回图片 `![marqdo-out](…)`(扩展名校验)与 view/静态站同源标记;view 展示推断形参实值;欢迎页迁到 v0.3 叙述面。 - -```bash -git checkout v1.4.0 && cargo build --release -marqdo run tests/markup-v03/formula-meta-var.mq.md -marqdo run tests/markup-v03/foreach-narrative.mq.md -marqdo view tests/view/document-annot-demo.mq.md --no-open -# Ubuntu: sudo apt update && sudo apt install marqdo -marqdo ext add web # CDN latest → 1.4.0 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。Language 层在既有 `formula` / `branch-list` / `loop-list` 上扩展语义(块公式 TeX 注释绑定、臂/循环体叙述、foreach 糖);Runtime:自写回图片形态 + view 推断形参展示。设计:[fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)。 - -### Added -- **块公式 meta 绑定**:`$$` 内 `% marqdo: var=`(剥离后解析;可无空 RHS);金样 `tests/markup-v03/formula-meta-var.mq.md`。 -- **控制流叙述统一**:臂/循环体 `parse_indented_body` 与函数体同权;分支条件行支持叙述前缀与行内 `**…**`;foreach 糖 `- 对…的每一项…` / `- for each … in …`。 -- **图片自写回**:路径/URL 且扩展名合法 → `![marqdo-out](…)`;文本仍 HTML 注释;view / `view output` 同源样式卡与 ``。 -- **view 推断形参实值**:Browse 展示 body-inferred 参数绑定值;欢迎页 EN/ZH 迁 v0.3 叙述。 - -### Fixed -- `ext/net/url.encode`:经 `lib/net` 包装,不再直接 `host_*`(金样 `ext_mq_md_never_calls_host`)。 -- PPA 源包:`ppa-build-source.sh` 本地 `.orig` 已在 build-area 时跳过重复 `cp`。 -- view:嵌套调用欢迎页与公式/代码卡渲染清理。 - -### Changed -- CLI / wasm / `ext/VERSION` **同步 1.4.0**;词法评论段遇有序分支臂 / 循环头 / 图片自写回标记时断开,避免吞掉控制流行。 - -## v1.3.3 — 2026-10-15 - -### Highlights - -**view 文档面 Structure**:Browse 保真叙述与标记面(变量/语句/返回无源码定界符);表/循环/分支结构块;语句后绑定值、分支命中臂、函数多调用与循环迭代下拉(默认末帧);`#mq-view-trace` AI JSON。静态 `marqdo view output` 与 live view **同源渲染**(含用户站 `public/` → gh-pages)。 - -```bash -git checkout v1.3.3 && cargo build --release -marqdo view tests/view/document-annot-demo.mq.md --no-open -marqdo view output public -o public -# Ubuntu: sudo apt update && sudo apt install marqdo -marqdo ext add web # CDN latest → 1.3.3 -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 文档面 + 帧选择),不触碰语言标记。 - -### Added -- **Browse Structure 文档面**(`src/view/document.rs` · `annot.rs`):叙述保真、标记面、GFM 表 / `doc-loop` / `doc-branch`、CSS L-leader 标注带。 -- **StmtEvent / CallFrame / LoopFrame** 静默轨迹:post-stmt 绑定、分支 `call_id`、循环 `分 = 分数表[i] · value`;调用/迭代 picker(源码常显,只滤 chip)。 -- **`ViewExecutionReport`** JSON(`#mq-view-trace` · `/api/view-trace` · SSE `trace_json`)。 -- 设计:[view-document-annotations.md](doc/design/view-document-annotations.md) · [view-execution-trace.md](doc/design/view-execution-trace.md) · [view-frame-selection.md](doc/design/view-frame-selection.md);样例 `tests/view/document-annot-demo.mq.md`。 - -### Fixed -- 多调用分支 taken 混叠;调用切换误藏未执行臂源码;循环头重复 chip。 - -### Changed -- CLI / wasm / `ext/VERSION` **同步 1.3.3**;静态导出与 live view 共用 `build_file_view` → 文档面。 - -## Ext pack v1.3.2 — 2026-10-13 - -### Highlights - -**Trailing slash 路由修复(CLI 仍为 v1.3.0)**:Go `ServeMux` 精确匹配导致 `/post/foo/`(带尾部斜杠)落入 404。新增 `withStripTrailingSlash` 中间件作为最外层 handler wrapper,所有下游中间件(RBAC、Tenant、路由)均看到规范化路径。覆盖静态路由、动态路由、根路径、查询参数保留。 - -```bash -marqdo ext add web # CDN latest → 1.3.2 -# 或:MARQDO_EXT_VERSION=1.3.2 marqdo ext add web -``` - -### Fixed - -- **web**: `/post/foo/` trailing slash now routes the same as `/post/foo` (dynamic and static routes). Root `/` unchanged. Query strings preserved after normalization. - -## Ext pack v1.3.1 — 2026-10-08 - -### Highlights - -**OIDC 路径型 `redirect_uri`(CLI 仍为 v1.3.0)**:`redirect_uri=/oidc/callback` 按请求 Host / `X-Forwarded-*` 拼绝对回调,写入会话供 token 交换;可选 `redirect_origins` allowlist。apex / www 多域名无需写死单一绝对 URI。 - -```bash -marqdo ext add web # CDN latest → 1.3.1 -# 或:MARQDO_EXT_VERSION=1.3.1 marqdo ext add web -``` - -### Added -- **路径型 redirect_uri**:绝对 URL 行为不变;路径模式解析 public origin,session 键 `oidc_redirect_uri`。 -- **`redirect_origins` / `回调来源`**:逗号分隔 origin allowlist(路径模式)。 -- **ABI**:`web_app_oidc` 透传 `redirect_origins`;`ext/security/oidc.attach` 文档同步。 - -### Changed -- 扩展包 SemVer **1.3.1**(`ext/VERSION`);与 CLI **v1.3.0** 可独立安装。 - -## v1.3.0 — 2026-09-28 - -### Highlights - -**Engineering Knowledge Compiler(EKC)**:把仓库投影为 AI 可查询的工程知识系统——L0–L4 Catalog、Capability / Decision / Constraint / Failure、知识图、Reuse Preflight(REUSE→ADAPT→CREATE)与 Context Pack。本版 CLI 与扩展包 **同步为 1.3.0**。 - -- **杀手命令**:`marqdo reuse "task"` / `find` / `duplicate` / `impact` / `conflicts` / `stale` / `verify` / `knowledge` -- **Agent**:`agent.preflight` · `agent_eng_*`;`plan … eng_preflight=True` 在造轮子前强制 EFI -- **投影**:`.marqdo/catalog|knowledge|graph|agent/` + `engineering.yaml`;`catalog` 默认挂钩 EKC -- **示例 / 金样**:`examples/engineering-knowledge/` · `tests/engineering/` · `tests/ext/eng-preflight.mq.md` - -```bash -sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo -git checkout v1.3.0 && cargo build --release -marqdo knowledge . -o .marqdo -marqdo reuse "resolve configuration" -marqdo ext add agent -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(知识编译器 + CLI + agent 插件),不触碰语言标记。 - -### Added -- **`src/knowledge/` EKC**:L0–L4 IR、指纹、能力推导、图边、compile、find/reuse/preflight、impact/lifecycle/duplicate、metrics、policy、learn。 -- **CLI**:`knowledge` · `find` · `reuse` · `impact` · `conflicts` · `stale` · `duplicate` · `verify`;`catalog`/`sync` 默认编译 EKC(`--no-knowledge` 可关)。 -- **Agent**:`agent_eng_preflight` / `agent_eng_reuse` / `agent_eng_record`;`ext/ai` `## preflight` + `plan eng_preflight`。 -- **规范**:`doc/design/engineering-knowledge.md`;提案叙事 `doc/next/008.md`(已实现标注)。 - -### Fixed - -### Changed -- **OKF type 注册表**扩展 Capability/Decision/Constraint/Failure/Context Pack/Policy 等([okf.md](doc/design/okf.md))。 -- **核心表面 Δ**:**无增删**。 - -## v1.2.0 — 2026-09-28 - -### Highlights - -**Web Artifact 重写(ADR 0007)**:Document / Endpoint / Resource 一等公民;`type: web|endpoint`(ZH `类型: 网页|端点`);facade `web.page|route|serve|render|inspect|use`;DB/auth/ws 拆到 `ext/data` · `ext/security` · `ext/net`。本版 CLI 与扩展包 **同步为 1.2.0**。 - -- **Document**:文件级 Artifact + `data_source` / `data_order` / `data_where`;正文 Markdown → HTML;列表卡片 / 详情文章由 serve 时加载。 -- **Endpoint**:`# main` 处理器;请求经 `run_artifact` Binding 注入;`response` 序列化 JSON/text/html。 -- **破坏性**:删除作者面 `compose_*` / `app.configure` / 作者 `ensure_plugin`;旧 web gold 移除,新金样 `ext_web_*`。 -- **示例**:`examples/marqdo-blog/` Artifact 站(pages/api/db + smoke);`web-client-site` serve 扫描。 - -```bash -sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo -git checkout v1.2.0 && cargo build --release -bash scripts/build-web-plugin.sh && marqdo ext add web -marqdo run examples/marqdo-blog/serve.mq.md -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——复用 Metadata `type`;装配语义在 ext + plugin。语言标记不变。 - -### Added -- **Web Artifact 模型(ADR 0007)**:`type: web|endpoint`(ZH `类型: 网页|端点`);核心 `src/artifact/`;`sys.artifact_kind`;无 `# main` 时 Result 摘要。 -- **`ext/web` facade**:`page` · `route` · `serve` · `render` · `inspect` · `use`;子模块 page/route/dom/client/component。 -- **`ext/data` · `ext/security` · `ext/net`**:从 monolithic web 拆出 Resource。 -- **统一 View** `|type|slot|value|attrs|style|` + ABI `web_render_nodes` / `web_serve_root` / `web_inspect` / `web_app_use`。 -- **规则**:`.cursor/rules/web-artifact-no-degrade.mdc`;设计 `doc/design/ext-web-artifact.md`。 - -### Fixed -- Document `data_source` / `data_where` now drive list cards and detail articles under `web.serve` (ADR 0007 flat metadata). - -### Changed -- **破坏性**:删除作者面 `compose_*` / `app.configure` / 作者 `ensure_plugin`。旧 web gold 已移除;新金样 `web-artifact-*` / `ext_web_*`。 -- **核心表面 Δ**:**无增删**(复用 Metadata `type`)。 -- 修订 `ext-web.md` C1;`doc/next/007.md` superseded。 - -## v1.1.1 — 2026-09-24 - -### Highlights - -**AI 栈收口(agent + llm)**:语义 `ask`/`stream`/`collect`、Artifact Metadata Binding、Skill Compilation + Adaptive Routing、MCP 客户端与 resume 检查点、可选 `plugins/llm` Transport ABI。 -本版 CLI 与扩展包 **同步为 1.1.1**。 - -- **LLM 原语**:`ext/ai/llm` 从 OpenAI HTTP 客户端提升为 `ask`/`stream`/`collect` 智能原语(`complete` 保留兼容);`LLMResult.tool_calls`;可选原生 `llm_chat_completions`(无 `.so` 时回退 `lib/net`)。 -- **Metadata Binding**:frontmatter `${env|arg|sys|secret}` 加载期解析;Phase 2 将绑定键注入入口 env(正文禁止 `${…}`);`sys.meta` / `--bind`;llm ctor 优先 meta。 -- **Agent**:Skill Compilation(episode → llm_free skills)+ Adaptive Routing(`marqdo` / `small-llm` / `llm` / `auto`;`jev` 为 `small-llm` 兼容别名);MCP **stdio 客户端**;resume 检查点;零 LLM 金样路径。 -- **度量与后端**:`model_turn` usage、named handles(fast/reasoning)、`type:prompt` 加载、openai/ollama 分流。 - -```bash -# Ubuntu PPA / 源码 -sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo -git checkout v1.1.1 && cargo build --release -marqdo ext add llm && marqdo ext add agent -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime**(Metadata Binding、LLM/agent 插件与扩展)变更,不触碰语言标记。 - -### Added -- **`ext/ai/llm` 语义表面**:`ask` / `stream` / `collect`(`complete` 兼容);`LLMResult.tool_calls`(OpenAI-shaped `choices[0].message.tool_calls`);`sys.module_source` + 入口文档 `prompt_body` 离线路径。 -- **`plugins/llm` Transport ABI**(`llm_chat_completions`):`ext/ai/llm/openai` 优先原生插件,否则 `lib/net` HTTP/SSE。 -- **Artifact Metadata Binding**:frontmatter `${env|arg|sys|secret}` → `Module.metadata`;Secret 掩码;`sys.meta` / `--bind`;Phase 2 入口 env 注入(正文拒绝 `${…}`;字节码 prologue 同源)。 -- **Agent Skill Compilation + Adaptive Routing**:episode → `maybe_learn` → llm_free skills;路由后端 `marqdo` / `small-llm` / `llm` / `auto`(`jev` = `small-llm` 兼容别名,不再探测 `MARQDO_JEV`)。 -- **Agent MCP stdio 客户端**(`agent_mcp_client` / `mcp_connect` / `mcp_client_list` / `mcp_client_call`)+ Python mock 离线金样。 -- **Agent resume 检查点**(`.marqdo/agent-resume/.json` — save/load/clear/list;`run` 可设 `resume_id=`)。 -- **AI 栈度量与后端**:`model_turn` usage、named handles(fast/reasoning)、`type:prompt` 加载、openai/ollama 分流、agent-zero-llm 金样。 - -### Fixed -- **plan force 不再冲掉已有 `resources` workbook**(保留 llm_free 资源;金样 `agent-plan-preserve`)。 -- **compiled-skill Marqdo 语法**:llm_free await 不再误落到 plan+HTTP。 - -### Changed -- Adaptive Routing:决策面为 `router_model`(任意 llm handle);`jev` 降为 `small-llm` 文档/兼容别名。 - -## v1.1.0 — 2026-09-23 - -### Highlights - -**AI 原生闭环三件套落地**:核心表面守卫(问题一)· 渐进式契约(问题二)· MLSP for AI(问题三)。 -`marqdo check` 静态契约防漂移、`marqdo mlsp` 让 AI **按需查询**语法而非背诵、`run --json` 统一结构化诊断(错误即数据,供 AI 直接消费)。 -本版 CLI 与扩展包 **同步为 1.1.0**。 - -- **核心要小(问题一)**:`doc/design/core-surface.md` 列出 19 个核心构造 + `CORE_CONSTRUCTS` 守卫测试——任一侧(清单/文档/金样)单边改动 CI 必红;三层架构(Core / Runtime / Document)入 `doc/design/layers.md`。 -- **语义校验(问题二)**:渐进式契约表(`参数`/`返回`/`字段`/集合)嵌入文档叙述;四边界校验(调用实参 / 返回值 / 表绑定 / 键访问);`marqdo check` 静态防漂移(类型 typo / 参数名漂移 / 重复契约必报)。 -- **AI 可靠反馈 + 不必学语法(问题三)**:`marqdo mlsp`(MLSP,行分隔 JSON over stdio)提供 `locate` / `syntax` / `validate` / `repair_targets` / `repair_apply` / `schema`;`syntax` 卡片机械携带戒律原文 / 样例 / 文档锚点,AI 无需预学语法。修复护栏:有界行编辑、越界必拒(abstain)。 -- **验证(P4)**:锚点消融 anchor 一轮修复率 **100%**(双模型,plain 85%/90%);契约消融拦截 100% / 误报 0%;防漂移必报 9/9;核心守卫演练 3/3 必红。详见 [perf-validation-report-2026-09-23.md](doc/roadmap/perf-validation-report-2026-09-23.md)。 - -```bash -# Ubuntu PPA / 源码 -sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo -git checkout v1.1.0 && cargo build --release -marqdo ext add web -``` - -**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造(`heading` / `bold-code` / `italic-return` / `param-list` / `call-quote` / `branch-list` / `loop-list` / `table-bind` / `footnote-index` / `link-index` / …)与 v1.0.7 完全一致,未新增标记。本版为 **Runtime 层(契约校验 / MLSP / 诊断 JSON)** 与 **Document 层(core-surface / layers)** 变更,不触碰语言核心。 - -### Added -- **MLSP(`marqdo mlsp`)**:面向 AI 的语言服务协议(行分隔 JSON over stdio)——`locate` / `syntax` / `validate` / `repair_targets` / `repair_apply` / `schema`;`syntax` 卡片含 `semantics` / `rule` / `sample` / `doc_quote`(自持,机器可读戒律原文)。 -- **`marqdo check`**:静态契约漂移检查(未知类型词 / 参数名漂移 / 返回越约 / 重复契约表 / 错位契约表)。 -- **渐进式契约(Progressive contracts)**:文档叙述内嵌契约表(`参数`/`返回`/`字段` + 集合 `字段`),四边界校验(调用实参 / 返回值 / 表绑定 / 键访问);被绑定的 `字段|类型` 表是**数据**、永不误判为契约。 -- **`marqdo run --json`**:统一结构化诊断(`code` / `severity` / `suggestion` / `doc_anchor` / `doc_quote` / `contract_ref`),错误即数据。 -- **修复护栏**:`mlsp repair_apply` 有界行编辑——只允许落在 `doc_anchor` 指定范围内的编辑,越界整体拒绝(all-or-nothing / abstain)。 -- **守卫与文档**:`doc/design/core-surface.md`(19 构造)、`doc/design/layers.md`(三层架构)、`tests/core_surface.rs`(守卫生效验证)。 - -### Fixed -- **错误链不再扁平化**:`src/load.rs` 以 `label_error` 保留结构化 `Diagnostic`("Error Exit Only" 原则),修复契约类错误被降级为字符串的回归。 -- **契约 parse 边界**:`interp.rs` 键访问优先给出 `index_diag`(索引/键诊断先于取值),空字段 vs 缺字段语义消歧。 - -### Changed -- **`.cursor/skills/marqdo`**:由「背诵式压缩操作手册」改为**查询式工作流**——写码前 `mlsp syntax` / `locate`,提交前 `mlsp validate` + `marqdo check`,修复照 `doc_anchor` 局部改。 -- **契约表一经出现即为完整声明**(新推断的升参未覆盖 ⇒ `contract.param_drift` 警告,不静默)。 -- 取元**主推** `[键](集合)`(`link-index`);`` `集合`[^键] ``(`footnote-index`)保留兼容。 - -### 已知未决(诚实标注) -- **P4 实验 (b) 盲测未达标**:「查询式 vs 全文档背诵」四判据未全立(`deepseek-flash`:docs 4/6 vs query 0/3;端点 infra 削样本)。查询机制本身已验证无缺陷,瓶颈在**模型自查纪律**(不知道自己不知道 ⇒ 不查询)——协议改进(写码前强制自检 / 陌生构造强制查询)列入下一阶段。见 [perf-validation-report-2026-09-23.md](doc/roadmap/perf-validation-report-2026-09-23.md) §3。 - -## Unreleased - -## v1.0.7 — 2026-09-22 - -### Highlights - -**WS / 网络边界加固**:WebSocket 握手同源校验、broadcast/room 默认需登录(`require_auth`/`需要登录` 可显式关闭)、消息 1 MiB × 256 条上限、空 room 回收;HTTP 响应 8 MiB 在读流时截断;`url_encode` 空格 `%20`。本版 CLI 与扩展包 **同步为 1.0.7**。 - -- **安全默认**:浏览器 WS 握手仅同源;有状态 fan-out 端点未登录 401 / 公开直播流显式 `require_auth=False` -- **资源上限**:WS 单条 1 MiB、单连接 256 条;HTTP/SSE 8 MiB 读流截断——对端无法借大响应耗尽内存 -- **测试**:P3 金样对齐 quiet-admin 门禁语义;wasm smoke 以 ESM 加载官方 bridge - -```bash -# Ubuntu PPA / 源码 -sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo -git checkout v1.0.7 && cargo build --release -marqdo ext add web -``` - -### Fixed -- **WS 安全默认**:握手改为同源校验(不再放行任意 Origin);`route_ws` 新增 `require_auth`/`需要登录`,broadcast/room 默认要求登录会话,公开直播流需显式设假,未认证握手 401。 -- **WS 资源上限**:单条消息 1 MiB、单连接最多收集 256 条回复;传输错误/超时返回 `{ok:false, error}`,不再伪装空成功;空 room 自动回收(防 URL 派生 room 名耗尽内存)。 -- **HTTP 响应上限**:8 MiB 上限在读流时截断(含错误路径与 SSE 错误路径),上游无法借超大响应耗尽内存。 - -### Changed -- `net.url_encode`:空格编码为 `%20`(原 `+`),URL 段语义下与字面 `+` 消歧义。 -- `web`/`网页` 文档同步:`route_ws` 的 `require_auth`/`需要登录` 与 `ws.connect` 的收集上限语义。 - -## Unreleased - -### Added - -### Fixed - -### Changed - -## Ext pack v1.0.6 — 2026-09-18 - -### Highlights - -**ext/web OIDC、表单删除与安静管理台(CLI 仍为 v1.0.3)**:OIDC 登录/登出回首页、表单 `删除` 动作、默认关闭内置 admin/RBAC desk、独立 Redis 会话 URL、Postgres CRUD。安装: - -```bash -marqdo ext add web # CDN latest → 1.0.6 -``` - -### Added -- **OIDC**:`auth.oidc` / 网页鉴权 OIDC;登录入口与 `next` 回跳。 -- **表单删除**:`form` 动作 `删除`/`delete`(通用 CRUD,无站点特判)。 -- **列表/路由**:请求上下文、列表装配延续;注销默认回 `/` 避免 IdP 再登录环。 - -### Fixed -- 内置 admin / RBAC desk 默认安静,直至显式 `admin` / `enable_rbac`。 -- 静态资源缓存与 WASM 启动延迟;会话 CSRF 与 Postgres 方言。 - -### Changed -- 扩展包 SemVer **1.0.6**(`ext/VERSION`);与 CLI **v1.0.3** 可独立安装。 - -## Ext pack v1.0.5 — 2026-09-18 - -### Highlights - -**ext/web 请求上下文与表单来源(CLI 仍为 v1.0.3)**:字段 `来源`/`source`(session / route / now)、server-only 盖戳、页面 `列表装配`/`compose_list`;禁止按业务表特判。安装: - -```bash -marqdo ext add web # CDN latest → 1.0.5 -``` - -### Added -- **Request context**:表单提交携带 `_mq_params` / `_mq_return`;`ApplySources` 从 session/route/now 写入。 -- **字段来源列**:`client`(默认)/ `session.username` / `route.NAME` / `now`;非 client 不渲染且覆盖客户端伪造。 -- **列表装配**:`compose_list` / `列表装配`(副绑定 + 条件/排序/插槽),详情页可同页渲染子列表。 -- 设计文:[ext-web-request-context.md](doc/design/ext-web-request-context.md);金样 `ext_web_form_source_live`。 - -### Changed -- 扩展包 SemVer **1.0.5**(`ext/VERSION`);与 CLI **v1.0.3** 可独立安装。 -- 移除评论表名特判(`enrichCommentSubmit`)。 - -## Ext pack v1.0.4 — 2026-09-17 - -### Highlights - -**ext/web 能力面扩展(CLI 仍为 v1.0.3)**:可配置 RBAC、租户作用域、WS `on_message`/presence、原生 SPA 内存路由、协同记事本 MVP。安装: - -```bash -marqdo ext add web # CDN latest → 1.0.4 -``` - -### Added -- **RBAC**:五表(`web_permissions` / `web_roles` / `web_role_permissions` / `web_users` / `web_user_roles`);`app.enable_rbac`、`app.gate permissions=`、`rbac.can`、注册页、`/_rbac/*` 管理 API/desk。 -- **Tenant**:`app.tenant`(path/header/subdomain)+ `tenant_scope` 自动过滤/盖戳。 -- **WebSocket G-WS2**:`route_ws` 支持 `on_message` 钩子、动态 room、`presence` 通道。 -- **Native SPA**:内存 `store_set` / `spa_goto` 与全页 WASM SPA 样站。 -- **Collab MVP**:LWW 文档协议(`DOC\t`)双端协同记事本样站。 - -### Changed -- 扩展包 SemVer **1.0.4**(`ext/VERSION`);与 CLI **v1.0.3** 可独立安装。 - -## v1.0.3 — 2026-09-17 - -### Highlights - -**分发渠道齐备**:Ubuntu PPA 装 CLI;扩展包走 CDN(`ext.marqdo.com`)与 GitHub;CLI 与扩展可分开发版。本版 CLI 与扩展包 **同步为 1.0.3**。 - -**语法**:未绑定的 GFM 表格是可丢弃的集合值,不再报 `unrecognized statement`(文档页可直接写安装表)。 - -```bash -# Ubuntu -sudo add-apt-repository ppa:cflmy/marqdo -sudo apt update && sudo apt install marqdo -marqdo ext add web - -# 或源码 / Releases -git checkout v1.0.3 && cargo build --release -``` - -### Added -- Ubuntu PPA packaging: `debian/` + `scripts/ppa-ship.sh` (一键装工具/打包/dput) + `ppa-build-source.sh` + [ubuntu-ppa.md](doc/design/ubuntu-ppa.md). -- **Extension CDN** (`https://ext.marqdo.com` / Cloudflare R2):`ext add` 下载顺序改为 CDN → GitHub → proxy;独立包版本见 `ext/VERSION` 与 CDN `latest/VERSION`;上传脚本 `scripts/upload-ext-r2.py`(凭据 `~/.marqdo/r2.env`)。设计见 [ext-cdn.md](doc/design/ext-cdn.md)。 -- `ext add` 下载:GitHub 失败后自动回退 `https://proxy.cflmy.top/github.com/…`;可用 `MARQDO_EXT_DOWNLOAD_BASE` 指定首选镜像;加长读写超时。 -- 用户文档(README / `public/00-欢迎` / `features/05-扩展`)标明安装渠道:Ubuntu PPA、GitHub Releases、源码;扩展走 CDN。 - -### Fixed -- `ext/` 导入默认搜索 `~/.marqdo/ext`(与 `marqdo ext add` 安装根一致),无需再手动 `export MARQDO_EXT`。 -- PPA/noble:捆绑 `third_party/rust`(现代 cargo)以构建 Cargo.lock v4;修复首次 Launchpad 构建失败(distro cargo 1.75)。 -- 未绑定的 GFM 表格不再报 `unrecognized statement`:作为集合值求值后丢弃(文档中可写表)。 - -### Changed -- 允许 **CLI 与扩展包分开发版**:扩展包 SemVer 可与 `Cargo.toml` 不同(`MARQDO_EXT_VERSION` / `ext/VERSION` / CDN latest)。 -- 发版 skill:支持 `full` / `cli` / `ext`;扩展必传 R2+GitHub;CLI 走 PPA;需用户操作时打印确切命令。 - -## v1.0.2 — 2026-09-16 - -### Highlights - -**表驱动页面引言(`compose_intro` / `引言装配`)**:英雄区用 GFM「属性 / 值 / 样式」表声明,不再手写 HTML 字符串;WWW Demo 样站与后台门禁一并加固。 - -```bash -git checkout v1.0.2 -cargo build --release -bash ./scripts/build-web-plugin.sh -# 或:解压 Release 的 marqdo-1.0.2-*-native-*.zip / Linux CLI zip -marqdo run examples/web-site-zh/index.mq.md -``` - -### Added -- Go `libweb`:`web_compose_intro` — 将引言表装配为 `.main-intro` HTML;中英 API `页面.引言装配` / `page.compose_intro`(`ext/web`)。 -- 验收样例:`tests/ext/web-intro-compose.mq.md`;`examples/web-site` / `web-site-zh` 升级为表驱动引言 + 文学风壳层 + 卡片→详情路由。 - -### Fixed -- 后台样站:导航/侧栏/页脚槽位与门禁登录挂载对齐;表单字段加宽便于创建。 - -### Changed -- Demo 叙述与种子数据面向 WWW Industry / 可复现演示;作者仍零业务 JS、零手写 `.css`。 - -## v1.0.1 — 2026-09-15 - -### Highlights - -**ext/web(Go libweb)回归修复**:动态路由查询条件恢复 `{param}` 代入;详情 SSR + Markdown;样式表数字不再误报。 - -```bash -git checkout v1.0.1 -cargo build --release -bash ./scripts/build-web-plugin.sh -# 或:解压 Release 的 marqdo-1.0.1-*-native-*.zip / Linux CLI zip -marqdo run examples/marqdo-blog/index.mq.md -``` - -### Added -- Go web plugin:详情页正文 Markdown(goldmark GFM),对齐 Rust `pulldown-cmark` 路径。 - -### Fixed -- **动态路由 `{param}` 未代入查询条件**(`ext/web` Go):`selectPageData` 递归展开 `query` 全部字符串叶子;`data-slot-src` / `_route` 同步替换。`examples/marqdo-blog` `/post/{slug}` 详情 SSR 恢复。 -- **样式表数字单元格误报「可疑 `/` 除法」**:`cssValueSuspicious` 不再把合法 `z-index`/`opacity` 等 number 当警告。 -- Go 1.22+ ServeMux:`/static/` 与 `/static/favicon.svg` 的 GET/HEAD 注册冲突导致博客启动 panic。 -- Rust archive 同步:`resolve_placeholders` 递归 + CSS number 误报收窄(非默认构建路径)。 - -## v1.0.0 — 2026-09-14 - -### Highlights - -**Markdown 语法映射 v0.3 成为 1.0 宪法**:`**粗体**` = 代码,`*斜体*` = 返回,叙述里的 `` `名` `` 声明并推断形参。这是相对 v0.4 / 旧 `*语句*`/`**返回**` 的破坏性对调。Linux 预编译拓展包与 CLI bundle 为 Release 必出资产。 - -```bash -git checkout v1.0.0 -cargo build --release -# Linux:也可直接解压 Release 的 marqdo-1.0.0-x86_64-unknown-linux-gnu.zip -marqdo run tests/markup-v03/inc-prose.mq.md -``` - -### Added -- **Markup v0.3 运行时闭环**:粗体=`代码`、斜体=`返回`、叙述 `` `名` `` 声明与形参推断为唯一映射;金样 `tests/markup-v03/`。 -- **方括号标记调用**与前置修饰语:`礼貌 [问候] x`;取元主语法 `[键](集合)`(脚注取元过渡保留)。 -- **代码即文档叙述面 G1–G4**:模块级 `---` 跳过、装饰性强调、浮点面量、动态键。 -- **粗体表达式语句** `**n + 1**`;`--dump-lines` 标注 `[decl]/[bold]/[italic]`;`--dump-ast` 显示 inferred 形参与死绑定。 -- **Release Linux 包必出**:`linux` job 上传 `*-native-x86_64-unknown-linux-gnu.zip` 与 Linux CLI bundle。 - -### Fixed -- 行首 `` `名`… `` 叙述不再当语句(修复 pages CI:`public/features/16-fs-mid2.mq.md`)。 -- 句中斜体强调(`*very important*` / `*foo.bar*`)不再误收束函数;Decl 名须为标识符;残缺粗体保持 GAP 恢复。 -- 胶合 `` `名`=default …prose `` 为 Decl 而非赋值。 - -### Changed -- 教程 / Skill / `lib` / `ext` / `public` 对齐 v0.3 标记;view 推断形参 `chip inferred`。 - -## v0.4.0 — 2026-09-13 - -### Highlights - -历史说明(2026-11-10):本节的 anlian-mq 是当时发布内容记录,现已移出仓库,旧启动命令不适用于当前工作树。当前完整站点见 examples/web-site 与 examples/web-site-zh。 - -**Go `libweb` 默认落地(W-G0–W-G14)**:官方网页原生插件改为 Go C ABI;CLI / gold / Release 走 `scripts/build-web-plugin.sh`;Rust 源码归档。另附 **anlian-mq** 验收站与表单插槽 / `MARQDO_EXT` 提示修复。 - -```bash -git checkout v0.4.0 -# 构建 web 原生插件(需 Go + cgo): -bash ./scripts/build-web-plugin.sh -marqdo ext add web -marqdo run examples/anlian-mq/index.mq.md -``` - -### Added -- **`plugins/web` Go 全量重写(W-G0–W-G13)**:C ABI 对等装配/DB/表单/listen/鉴权/上传/SEO/WS/驱动/proxy·invoke/定制壳;`scripts/build-web-plugin.sh` → `libweb.so` / `web.dll`;ADR [0004](doc/adr/0004-web-plugin-go.md) · 施工 [ext-web-go-rewrite.md](doc/design/ext-web-go-rewrite.md)。 -- **W-G14 验收**:`examples/anlian-mq/`(暗恋见君风格论坛:路由/登录/粉玻璃主题/片段 API;SQLite 本地可跑)。 -- **GAP-11**:`compose_form` / `表单装配` 支持 `target` / `表单插槽`(如 `#id`),把表单注入引言 HTML 内的挂载点。 - -### Fixed -- **GAP-12**:`ext/…` import 解析失败且未设置 `MARQDO_EXT` 时,错误附带 `hint: set MARQDO_EXT to the directory that contains web/`。 -- **listen 会话 / CSRF**:登录后 `IssueCookie` 不再误设 `Max-Age=0`;页面 ABIs(`query`/`order`/`link_prefix`/`css`/`detail`)与 `web_page_chrome`、`invoke return=html` 对齐 anlian 需求。 - -### Changed -- **默认 `libweb` 为 Go**:Release / gold / `ext add web` 不再构建 Rust `marqdo_plugin_web`;旧 Rust 树移至 `plugins/web-rust-archive/`(非 workspace 成员)。作者面 `ext/web` ABI 名保持兼容。 - -## v0.3.9 — 2026-09-09 - -### Highlights - -**业务联调缺口 GAP-06–10**:解析器不再吞掉嵌套反引号/`text=[…]` 后的函数体;`invoke` 的 `Null` 不再伪装成功;`sys.exec capture=` 可取 stdout;流式 proxy 反缓冲头。 - -```bash -git checkout v0.3.9 -``` - -### Added -- **`sys.exec` / `系统.执行`**:可选 `capture=` / `捕获=`;为真时返回 `{code, stdout, stderr}`(GAP-09)。 - -### Fixed -- **GAP-06/07**:`*…*` 分类对反引号/字符串内的 `*` 不再误判;错误收尾的赋值行不再吞掉后续 `##` 体(`>` / 合法 `*…*` 可脱出注释段);命名参数边界尊重 `[…]`/`{…}`。 -- **GAP-08**:`app.invoke` 对 `Null`/`None` 返回不再伪装成 `{"ok":true}`,改为 500 + `{"ok":false,"error":"null result"}`。 -- **GAP-10**:`app.proxy` `stream=true` 响应补齐 `Cache-Control: no-cache, no-transform` 与 `X-Accel-Buffering: no`。 - -### Changed - -## v0.3.8 — 2026-09-09 - -### Highlights - -**中层标准库 Mid2(M7–M10)收口**:日历/时区、URL、TOML、HTML 转义、base32、实用 fs、薄统计与日志字段——日常脚本与工具配置不再依赖外联或插件。另修复嵌套插件调用后 `GLOBAL_HOST` 被清空导致 `invoke` 失败。 - -```bash -git checkout v0.3.8 -# 或下载 Release 的 exe / zip -marqdo run public/features/14-datetime-url.mq.md -marqdo run public/features/17-stats-log.mq.md -``` - -### Added -- **中层标准库 Mid2 M10**:`lib/stats` / `统计`(mean/median/stdev)与 `log`/`日志` 可选 `fields=`;金样与 public `17-stats-log`。**Mid2 M7–M10 收口**(zip 跳过)。设计 [stdlib-stats-log.md](doc/design/stdlib-stats-log.md)。 -- **中层标准库 Mid2 M9**:`fs.make_dirs` / `remove_tree` / `stat` / `walk`(中英);金样与 public `16-fs-mid2`。设计 [stdlib-fs-mid2.md](doc/design/stdlib-fs-mid2.md)。 -- **中层标准库 Mid2 M8**:`lib/toml` / `配置表`(只读子集)、`lib/html` / `超文本`(escape/unescape)、`encoding` base32;金样与 public `15-toml-html-encoding`。设计 [stdlib-toml.md](doc/design/stdlib-toml.md) · [stdlib-html.md](doc/design/stdlib-html.md)。 -- **中层标准库 Mid2 M7**:`lib/datetime` / `日期时间`(`{unix,zone,iso}` · parse/format/add/in_zone)与 `lib/url` / `地址`(parse · query_parse/stringify);金样与 public `14-datetime-url`。设计 [stdlib-datetime.md](doc/design/stdlib-datetime.md) · [stdlib-url.md](doc/design/stdlib-url.md)。 -- **文档**:中层标准库 Mid 之后缺口盘点与 Mid2(M7–M10)设计/路线——[stdlib-gaps-after-mid.md](doc/research/stdlib-gaps-after-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md) · [stdlib-mid2.md](doc/roadmap/stdlib-mid2.md)。 - -### Fixed -- **`host_query` / GLOBAL_HOST**:嵌套 `call_registered` 结束后恢复外层宿主指针,不再清空;`web_listen` 多轮 `invoke`(中间再调插件)不再报 `no active host context`。 - -### Changed - - -## v0.3.7 — 2026-09-07 - -### Highlights - -**宿主集成 H1–H4**:浏览器同域 SSE/HTTP 流式中继(`app.proxy`)、HTTP→用户 `##`(`app.invoke`)、跨模块 db 方法分发、`corpus_search` 可发现、MCP Server stdio——下游可去掉 Python 旁路。 - -```bash -git checkout v0.3.7 -# 或下载 Release 的 exe / zip -marqdo ext add web && marqdo ext add agent -# *app*.proxy / *app*.invoke · agent.mcp_server -``` - -### Added -- **宿主集成 H1–H4**:`ext/web` `app.proxy`(同域 SSE/HTTP 流式中继)与 `app.invoke`(HTTP→`lib.member`);跨模块 `#` 对象方法查找;`agent.corpus_search` 自动加载插件;`agent.mcp_server` stdio。金样 `web-proxy-invoke-smoke` · `web-hosting-live` · `web-db-cross-module-smoke` · `agent-mcp-server-smoke`。设计 [ext-hosting-fill.md](doc/design/ext-hosting-fill.md) · [ext-hosting.md](doc/roadmap/ext-hosting.md)。 -- **文档**:宿主集成缺口盘点——[ext-hosting-gaps.md](doc/research/ext-hosting-gaps.md)。 - -### Fixed -- **方法分发**:`find_object_type` 沿导入树传递查找,跨模块拿到的 `web.db` 等句柄可再调方法。 - -### Changed - -## v0.3.6 — 2026-09-07 - -### Highlights - -**中层标准库 Mid M1–M6 收口**:通用原语沉入 `lib/`(正则、编解码、路径、哈希、机密、CSV、加厚文本/集合、CLI、日志、UUID),写日常脚本与多数扩展库不再需要原生插件。另含 `ext/linalg` 公式文档面与 agent/llm 稳健性修复。 - -```bash -git checkout v0.3.6 -# 或下载 Release 的 exe / zip -marqdo run public/features/13-log-uuid.mq.md -marqdo ext add linalg # 可选:公式文档 / 线性代数 -``` - - -### Added -- **中层标准库 M6**:`lib/log` / `日志`(级别过滤的一行日志)与 `lib/uuid` / `标识`(v4);金样与 public `13-log-uuid`。设计 [stdlib-log-uuid.md](doc/design/stdlib-log-uuid.md)。**Mid M1–M6 收口。** -- **中层标准库 M5**:`table`/`表` 加厚(sort/sort_by/unique/chunk/zip/flatten)与 `lib/cli`/`命令行`(parse);金样与 public `12-list-cli`。设计 [stdlib-list-cli.md](doc/design/stdlib-list-cli.md)。 -- **中层标准库 M4**:`lib/csv` / `逗号表`(parse/stringify)与 `lib/text` / `文本` 加厚(contains/replace/case/pad/…);金样与 public `11-csv-text`。设计 [stdlib-csv.md](doc/design/stdlib-csv.md) · [stdlib-text-mid.md](doc/design/stdlib-text-mid.md)。 -- **中层标准库 M3**:`lib/hash` / `哈希`(sha256/sha1/md5/hmac_sha256)与 `lib/secrets` / `机密`(token_hex/token_urlsafe);金样与 public `10-hash-secrets`。设计 [stdlib-hash.md](doc/design/stdlib-hash.md) · [stdlib-secrets.md](doc/design/stdlib-secrets.md)。 -- **中层标准库 M2**:`lib/path` / `lib/路径`(join/split/normalize/…)与 `fs`/`文件` 加厚(`copy_file`/`move`/`make_temp`);金样与 public `09-path-fs`。设计 [stdlib-path.md](doc/design/stdlib-path.md) · [stdlib-fs-mid.md](doc/design/stdlib-fs-mid.md)。 -- **中层标准库 M1**:`lib/re` / `lib/正则`(`is_match`/`find`/`find_all`/`replace`/`split`)与 `lib/encoding` / `lib/编码`(base64/hex);host `host_re_*` + `host_encoding_*`;金样与 public `08-re-encoding`。设计 [stdlib-mid.md](doc/design/stdlib-mid.md) · [stdlib-re.md](doc/design/stdlib-re.md) · [stdlib-encoding.md](doc/design/stdlib-encoding.md)。 -- **`ext/linalg`**:L0–L6 + 公式文档面 **F1–F3**(中缀、`declare`、展示/`explicit` 默认化简、`T_ascii`、public「如何写公式文档」);示例 `linalg-transpose` · `linalg-svd` · `linalg-least-squares`。设计:[ext-linalg-formula-doc.md](doc/design/ext-linalg-formula-doc.md)。 - -### Fixed -- **`ext/agent`**:写回改走 `wb.record`(避免 `writeback` 形参遮蔽模块名),不再直调 `host_*`。 -- **`ext/llm`**:`stream_result` 忽略未知 SSE 类型(如 `reasoning`),不再因此退出。 - -### Changed - -## v0.3.5 — 2026-09-04 - -### Highlights - -**`marqdo ext add` 无需本机 Rust**:Release 发布预编译 native 插件;CLI 可自动下载 L1(`*-ext.zip`)与 `*-native-*.zip`。Windows 便携包内含 `ext/native/*.dll`。 - -```bash -git checkout v0.3.5 -# 或下载 Release 的 exe / zip -marqdo ext add web -marqdo ext add agent -marqdo ext add quantum -``` - -### Added -- **预编译原生插件资产**:`marqdo-*-native-x86_64-pc-windows-msvc.zip`、`marqdo-*-native-x86_64-unknown-linux-gnu.zip`;Windows zip 捆绑 `ext/` + native DLL。 -- **`ext add` 下载回退**:本地无 `target/` 时从 GitHub Release 拉取;`MARQDO_EXT_NO_DOWNLOAD=1` / `MARQDO_EXT_VERSION` 可配置。 - -### Changed -- 文档:[ext-cli.md](doc/design/ext-cli.md)、[08-ext-deploy-coupling](doc/design/ext-web-customization/08-ext-deploy-coupling.md)、README 安装步骤以预编译为默认路径。 -- Release workflow:Windows 编插件并上传 native zip;新增 Linux native job。 - -## v0.3.4 — 2026-09-04 - -### Highlights - -**`ext/web` 定制波次 C0–C4 收口**:可配置 admin 前缀与登录回跳、段边界 gates、shell/layout、样式单元格 strict、脚本 defer/version/`asset_version`、条件导航 when/media。附智能体 Wave B0 示例与写回遮蔽修复。 - -```bash -git checkout v0.3.4 -cargo build --release -cargo build --release -p marqdo_plugin_web -marqdo ext add web -# golds: tests/ext/web-c0-admin-prefix … web-c4-nav-when -``` - -### Added -- **智能体 Wave B0**:宪法优先示例 [agent-pong](examples/agent-pong/)(call_site/源码注入)· [agent-okf-flywheel](examples/agent-okf-flywheel/)(OKF `cache=hit`);调研 [agent-framework-2026-09.md](doc/research/agent-framework-2026-09.md);离线 harness [`scripts/agent-harness.sh`](scripts/agent-harness.sh);金样 `agent-constitution-b0`。 -- **`.env.example`**:开发期 OpenAI 兼容网关变量模板(密钥仅本地 `.env`)。 - -### Fixed -- **`agent.step` / `plan` 写回**:参数名 `writeback` 遮蔽 `lib/writeback` import,导致 `writeback=True` 时 `method receiver must be an object map`;改为 `host_writeback_record`。金样 `agent-writeback-shadow`。 -- **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。 -- **`ext/web` C1**:门禁段边界匹配(不再误伤 `/admin-publish`);`gate` 支持 `match` / `on_deny` / `exclude`;`auth` 默认 `on_deny=redirect` + `login_path`;金样 `web-c1-gates`。 -- **`ext/web` C2**:`shell_css=full|minimal|off`;`layout=sidebar|stacked|bare|rail`;full 壳含小屏单列 media;金样 `web-c2-shell-layout`。 -- **`ext/web` C3**:样式装配对数字/布尔值单元格告警,`strict`/`strict_css_cells` 硬错误;`page.css` 作 raw CSS;head 表支持 `defer`/`async`/`version`,`asset_version` 统一 `?v=`;金样 `web-c3-style-head`。 -- **`ext/web` C4**:导航表 `当`/`when`(`auth`/`guest`/`hide`)与 `媒体`/`media`(响应式显隐);listen 注入 `_logged_in`;金样 `web-c4-nav-when`。 - -### Changed -- `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。 -- 中文 `构建单步上下文` 委托英文版(含预算 / READ);新增 `dump_step_context`;live 用例改用仓库根 `.env`。 -- 文档:[ext-web 定制限制](doc/research/ext-web-customization-limits.md) + [解决设计 C0–C4](doc/design/ext-web-customization/)。 - -## v0.3.3 — 2026-09-04 - -### Highlights - -**浏览器作者零业务 JS(路线 D/E/F)**:官方 bridge 自启 + 宿主效应补齐(DOM/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM 表格写法;新增 [marqdo-dev](.cursor/skills/marqdo-dev/SKILL.md) 开发约定。 - -```bash -git checkout v0.3.3 -cargo build --release -marqdo wasm build -# examples: browser-hello / browser-app / browser-media / web-client-site -``` - -### Added -- **路线 D(作者零 JS)**:[roadmap](doc/roadmap/browser-wasm-d.md) · 设计 §16。官方 bridge `mount` / `data-mq-*` 自启;`client_embed` 带 `wasm`/`source`/`boot`;DOM 效应;`examples/web-client-site/`。 -- **路线 E(前端补齐)**:[browser-wasm-e.md](doc/roadmap/browser-wasm-e.md)。多节点 DOM、`add_class`/`remove_class`、cookie、clipboard/download、`fetch_all`/`ws`/`interval`;示例 [browser-app](examples/browser-app/)。 -- **路线 F(媒体/文件,F1–F5)**:[browser-wasm-f.md](doc/roadmap/browser-wasm-f.md)。`read_file`、Canvas 2D、Audio beep、Intersection/ResizeObserver、drag/drop;示例 [browser-media](examples/browser-media/)。 -- **`lib/browser` / `lib/浏览器`**:WASM 客户端效应助手(GFM 表格 + named helpers;勿用 `json.set` 链)。 -- **Skill `marqdo-dev`**:代码即文档 / GFM-first / 库开发约定。 - -### Changed -- 浏览器示例(hello / app / media / web-client)改为表格 + `lib/browser`;`ext/web` 效应助手改用 `table.put`。 -- 标准库模块表收录 `browser`;路线 F 收口 F1–F5(F6 Service Worker 仍可选)。 - -## v0.3.2 — 2026-09-01 - -### Highlights - -**浏览器 Marqdo(路线 C)首版完备**:`wasm-core`、`marqdo wasm build`、会话 ABI、DOM/`fetch`/`after` 效应、官方 bridge、体积与冒烟;并修 Admin 长内容布局、`ext add` 原生插件预检、`@keyframes` 与样式表 `/` 比率约定。 - -```bash -git checkout v0.3.2 -cargo build --release -marqdo wasm build -marqdo ext add web # 改插件后请重新 add -``` - -### Added -- **浏览器 Marqdo(路线 C)**: [ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [design](doc/design/browser-marqdo-wasm.md) · [roadmap C0–C5](doc/roadmap/browser-wasm.md)。 -- **C0/C1**:`wasm-core` feature 门控;`run_source`;crate `crates/marqdo-wasm`(`mq_run` ABI);示例 [examples/browser-hello](examples/browser-hello/)。 -- **C2/C3**:`marqdo wasm build`;会话 `mq_boot`/`mq_call`;GFM wire 表 + `set_text` DOM 回写;[interact.html](examples/browser-hello/interact.html) 计数器示例。 -- **C4**:[ADR 0003](doc/adr/0003-browser-async-effects.md) 效应表(`fetch` / `after`)+ bridge 续体;[fetch.html](examples/browser-hello/fetch.html)。 -- **C5**:`release-wasm` 体积配置;`marqdo wasm build` 报告 KiB 并可选 `wasm-opt`;`run_source` bytecode 单测;会话仍为 tree。 -- **WASM 收口**:规范 `crates/marqdo-wasm/js/marqdo-bridge.js`;`wasm build` 同时拷贝 bridge;Node 冒烟 `tests/wasm`;`web.client_embed` / `网页.客户端挂载`;路线图标 Completed。 -- **发版 Skill**:`.cursor/skills/marqdo-release/`(探测版本 → 用户确认 → 文档/资产/扩展/Release 说明)。 - -### Fixed -- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。 -- **`marqdo ext add`**:安装含原生插件的扩展时**先**定位/自动 `cargo build` 再拷贝 `.mq.md`,避免只装上文稿、运行时报 `native plugin not found`;扩大 `.so` 搜索路径。 -- **`web_style` / 样式装配**:正确输出 `@keyframes` 块(停点为嵌套规则,不再写成 `0%: opacity: 0`)。 -- **样式表含 `/` 的值**:文档明确**引号优先**(`"16/9"`、`"1/5"`);不引入靠空格消歧的表单元格比率折叠。 - -## v0.3.1 — 2026-08-29 - -### Highlights - -**W8 站点资源**:favicon / Head 资源表 / 图片装配一次补齐;并修复相对入口路径下 `entry_dir` 双重拼接导致的嵌套目录问题。 - -```bash -git checkout v0.3.1 -cargo build --release -marqdo ext add web # 改插件后请重新 add -``` - -### Added -- **`ext/web` W8(站点图标 / Head / 图片装配)** ([web-assets-and-images.md](doc/design/web-assets-and-images.md)):`app.icons` / `应用.图标` 挂 `GET /favicon.ico`;`page.head` / `头装配`;`make_images` / `图片装配`;`meta` 认 `icon`/`favicon`/`apple-touch-icon`;`static` 约定 `favicon.*`;金样 `web-assets-smoke` / `web-assets-live`;[marqdo-blog](examples/marqdo-blog/) 接入。 - -### Fixed -- **`host_query("entry_dir")`**:相对入口脚本(如 `tests/ext/….mq.md`)时对进程 cwd 绝对化,避免与 `for_run` 已设的脚本目录 cwd 再次拼接成 `tests/ext/tests/ext/…`。 - -## v0.3.0 — 2026-08-29 - -### Highlights - -本版把 **`ext/web` 网络能力(W0–W7 + P3)**、**`ext/quantum` Q7/Q8**、**`ext/agent` A1–A4** 一并收口到正式发布;并修了网页扩展叙述行误解析、补充 ASGI/生产部署说明与 agent 下一波(B0–B5)缺口调研。 - -**如何拿到本版** - -```bash -# 从源码(推荐跟 main / 本 tag) -git clone https://github.com/cflmy/marqdo.git && cd marqdo -git checkout v0.3.0 -cargo build --release -./target/release/marqdo version - -# 或从 GitHub Releases 下载 Windows 包 / 源码 zip(见 Release 资产) -marqdo version --check -``` - -**扩展(非 stdlib)** - -```bash -cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum -marqdo ext add web && marqdo ext add agent && marqdo ext add quantum -# 中文 id:网页 / 智能体 / 量子 / 大模型 -``` - -### Added -- **调研:`ext/agent` A0–A4 之后缺口** ([agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)):产品化示例、评测 harness、真 MCP、plan resume/HITL、飞轮指标与建议分期 B0–B5;挂到 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md) 与 [doc/README.md](doc/README.md)。 -- **生产部署调研(ASGI)** ([web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)):不能挂 Daphne/Uvicorn;路径为反向代理 → 嵌入式 `listen`(axum)。 -- **`ext/agent` A4(RAG/MCP 证据工具)**: `corpus_search` 本地语料关键词检索;`mcp_list_tools` / `mcp_call` 读 JSON fixture;返回 `authority=workbook`。金样 `agent-tools-rag-a4`。 -- **`ext/agent` A3(上下文预算)**: `source_brief` / 加深版 `skill_brief`;`build_step_context` 默认截断并提示 `READ:source|skill`;`step` 支持最多 `max_reads` 次加深;父 `READ:skill`。金样 `agent-context-budget-a3`。 -- **`ext/agent` A2(过程可见)**: `plan` 过程事件默认写入返回 map 的 `events`(SSE 仍仅 `stream=True`);OKF 命中记 `REUSE` decision;view plan 卡渲染过程时间线。对齐 [agent-streaming.md](doc/roadmap/agent-streaming.md)。 -- **`ext/agent` A1(OKF 复用飞轮)**: `agent_kb_list_tasks` 返回 description/aliases/status/llm_free/hits;`plan` 命中路径暴露 `match`/`score`(summary 含 match kind);soft_match 策展提示带 status/llm_free/description;view plan 卡显示 match。金样 `agent-kb-plan-hit`。路线 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md)。 -- **`ext/web` 样式装配(`web_style` / `网页.样式装配`)**: 样式即数据表格 —— GFM 样式表(`|选择器|属性|值|`,可用 `|媒体|` 列分组进 `@media` 块)经 `样式装配` 函数转成 CSS 文本,再拼装成完整主题。替代"整段手写 CSS 字符串"的写法,贯彻 文档即代码。见 [marqdo-blog](examples/marqdo-blog/styles/theme.mq.md)。 -- **网络能力调研(`doc/design/web-net-capabilities.md`)**: 盘点 `ext/web` + `plugins/web` + `lib/net` 现状,对照主流语言网络栈(FastAPI / Express / Flask / axum),给出「开发一个完整 Web 项目」所需能力的差距清单与分波次补强路线(W1–W7 + P3,**2026-08-28 已全部落地**)。 -- **AI Skill + 文档(ext/web 完结复核)**: `skills/marqdo/` 与 `.cursor/skills/marqdo/` 增加 **ext/web 动态站** 专节(硬规则、API 摘要、§13 最小站点样例);`doc/design/web-net-capabilities.md` 结论/对照表与 W7+P3 实现对齐;`doc/design/ai-skill.md` 更新用途说明。 -- **`ext/quantum` Q7(高阶线性代数 + 高级可视化)**: 密度矩阵 / 部分迹 / Hermitian 谱 / Schmidt / Pauli 期望 / 纯度;SVG:hinton、city、density、paulivec、qsphere、multibloch。全部经 `plugins/quantum` ABI。设计 [ext-quantum-q7.md](doc/design/ext-quantum-q7.md);金样 `quantum-linalg-smoke`、`quantum-viz-advanced-smoke`;示例 [quantum-entanglement](examples/quantum-entanglement/)。 -- **`ext/quantum` Q8a/Q8b(可视化美学)**: `draw theme=dark|light|bw`(默认 dark);标签芯片 + gutter 消除线穿字;门族分色;probs/bloch 共用令牌;view 对 `data-theme` 换图框。设计 [ext-quantum-viz-style.md](doc/design/ext-quantum-viz-style.md)。改插件后须 `marqdo ext add quantum` 再开 view。 - -### Fixed -- **`ext/web` / `网页.mq.md`**:叙述行勿以反引号开头,避免被解析为语句(`examples/marqdo-blog` 可正常 `listen`)。 - -### Changed -- **Frontmatter import syntax**: `import bind:target` / `导入 bind:target` (file `.mq.md` or short name `lib.member`). Removed legacy `> path.mq.md` / `> use` imports. See [module-namespace.md](doc/design/module-namespace.md). - -## v0.2.0 — 2026-08-12 - -### Highlights — official extension libraries - -This release centers on **`ext/`**: optional packages that are **not** part of the embedded stdlib. Install them with the CLI; native plugins (`.so` / `.dll`) ship beside L1 Markdown APIs. - -**How to get extensions** - -```bash -# List what the installer knows about -marqdo ext list - -# Install from the repo's ./ext (or MARQDO_EXT_SOURCE), into ~/.marqdo/ext (or MARQDO_EXT) -marqdo ext add llm -marqdo ext add agent -marqdo ext add web -marqdo ext add quantum - -# Chinese ids work the same (大模型 / 智能体 / 网页 / 量子) -marqdo ext add 量子 - -marqdo ext remove quantum -``` - -Native plugins (agent / web / quantum) must be built once, then `ext add` copies them into `MARQDO_EXT/native/`: - -```bash -cargo build --release -p marqdo_plugin_agent -cargo build --release -p marqdo_plugin_web -cargo build --release -p marqdo_plugin_quantum -marqdo ext add agent -marqdo ext add web -marqdo ext add quantum -``` - -Runtime also resolves plugins from `CARGO_TARGET_DIR`, `target/`, next to the `marqdo` binary, or `MARQDO_*_PLUGIN` env vars. Design: [ext-cli.md](doc/design/ext-cli.md) · [ext-abi.md](doc/design/ext-abi.md). - -| Package | What you get | -|---------|----------------| -| **llm** | OpenAI-compatible chat — [ext-llm.md](doc/design/ext-llm.md) | -| **agent** | Agent layout / orchestration helpers + native plugin — [ext-agent.md](doc/design/ext-agent.md) | -| **web** | HTTP + SQLite site helpers + native plugin — [ext-web.md](doc/design/ext-web.md) | -| **quantum** | State-vector circuits, draw, noise, formula `matrix=` custom gates — [ext-quantum.md](doc/design/ext-quantum.md) | - -User-facing intro: [`public/features/05-extensions.mq.md`](public/features/05-extensions.mq.md) / [`05-扩展.mq.md`](public/features/05-扩展.mq.md). - -### Added -- Full **ext CLI** catalog: `llm`, `agent`, `web`, `quantum` (EN/ZH ids). -- **Quantum (Q0–Q6)**: gates, `run`/`steps`, draw (circuit/probs/bloch), heatmaps, teaching noise incl. amplitude damping, **custom gates from `$$` / `matrix=`**. -- **Web** extension (listen / render / SQLite) with L1 EN/ZH. -- **Agent** native plugin path + installer copy into `native/`. -- View **Variables** panel: previews + click-to-open rich modal (matrices / KaTeX). -- Formula matrix parse (`pmatrix` / `[[…]]`) for executable gate matrices. - -### Changed -- Release notes and docs emphasize extensions vs embedded stdlib. -- Highlight.js CDN path for view pages; Variables panel script escaping fixed. - -## v0.1.2 — 2026-08-07 - -### Added -- **Embedded standard library**: official `lib/*.mq.md` ships inside the `marqdo` binary; disk `lib/` and `MARQDO_LIB` still override. -- **`lib/writeback`** / **`lib/subtask`**: Jupyter-style writeback; concurrent subtasks (file / function / foreign). -- **Surface syntax v0.2**: `` + `param` `` parameters, `1.` ordered branches, backtick identifiers, quoted strings. -- **`marqdo version --check`**: compare installed CLI with latest GitHub release. -- **VS Code extension v0.0.6** (branch **`vscode-extension` only**): v0.2 grammar, update check — see [doc/design/vscode-extension-commit.md](doc/design/vscode-extension-commit.md) - -### Changed -- Subtask `spawn` accepts `path=`, `fn=`, `code=`, or `lang=`+`source=` (not file-only). -- Release notes: standalone `.exe` includes stdlib; bundle/stdlib zips remain optional for overrides. - -## v0.1.1 - -- v0.2 syntax migration, writeback/subtask v1 (file subprocess only), view input deferral, optional parameters. - -## v0.1.0 - -- Initial public releases: tree + bytecode backends, `view` / `debug` / `catalog`, core stdlib, `ext/` installer. diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 414a6af..0000000 --- a/Cargo.lock +++ /dev/null @@ -1,1712 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anstream" -version = "0.6.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "ascii" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" - -[[package]] -name = "assert_cmd" -version = "2.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed72493ac66d5804837f480ab3766c72bdfab91a65e565fc54fa9e42db0073a8" -dependencies = [ - "anstyle", - "bstr", - "doc-comment", - "predicates", - "predicates-core", - "predicates-tree", - "wait-timeout", -] - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bitflags" -version = "2.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530" -dependencies = [ - "memchr", - "regex-automata", - "serde_core", -] - -[[package]] -name = "bumpalo" -version = "3.20.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - -[[package]] -name = "cc" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "num-traits", - "windows-link", -] - -[[package]] -name = "chrono-tz" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd6dd8046d00723a59a2f8c5f295c515b9bb9a331ee4f8f3d4dd49e428acd3b6" -dependencies = [ - "chrono", - "chrono-tz-build", - "phf", -] - -[[package]] -name = "chrono-tz-build" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f10f8c9340e31fc120ff885fcdb54a0b48e474bbd77cab557f0c30a3e569402" -dependencies = [ - "parse-zoneinfo", - "phf_codegen", -] - -[[package]] -name = "chunked_transfer" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" - -[[package]] -name = "clap" -version = "4.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "clap_lex" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "data-encoding" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" - -[[package]] -name = "difflib" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", - "subtle", -] - -[[package]] -name = "doc-comment" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "780955b8b195a21ab8e4ac6b60dd1dbdcec1dc6c51c0617964b08c81785e12c9" - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "find-msvc-tools" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" - -[[package]] -name = "flate2" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - -[[package]] -name = "float-cmp" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" -dependencies = [ - "num-traits", -] - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "futures-core" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" - -[[package]] -name = "futures-macro" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" - -[[package]] -name = "futures-util" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" -dependencies = [ - "futures-core", - "futures-macro", - "futures-sink", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getopts" -version = "0.2.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" -dependencies = [ - "unicode-width", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "http" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "279259b0ac81c89d11c290495fdcfa96ea3643b7df311c138b6fe8ca5237f0f8" -dependencies = [ - "idna_mapping", - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "idna_mapping" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11c13906586a4b339310541a274dd927aff6fcbb5b8e3af90634c4b31681c792" -dependencies = [ - "unicode-joining-type", -] - -[[package]] -name = "include_dir" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" -dependencies = [ - "include_dir_macros", -] - -[[package]] -name = "include_dir_macros" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "indexmap" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "js-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "libc" -version = "0.2.189" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - -[[package]] -name = "libloading" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" -dependencies = [ - "cfg-if", - "windows-targets", -] - -[[package]] -name = "log" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" - -[[package]] -name = "marqdo" -version = "2.9.1" -dependencies = [ - "anyhow", - "assert_cmd", - "chrono", - "chrono-tz", - "clap", - "futures-util", - "getrandom", - "hmac", - "idna_adapter", - "include_dir", - "libc", - "libloading", - "md-5", - "predicates", - "pulldown-cmark", - "regex", - "serde", - "serde_json", - "sha1", - "sha2", - "thiserror", - "tiny_http", - "tokio", - "tokio-tungstenite", - "toml", - "ureq", - "zeroize", - "zip", -] - -[[package]] -name = "marqdo-plugin-sdk" -version = "2.0.0" -dependencies = [ - "serde_json", -] - -[[package]] -name = "marqdo-wasm" -version = "2.9.1" -dependencies = [ - "marqdo", - "serde_json", -] - -[[package]] -name = "marqdo_plugin_agent" -version = "0.1.0" -dependencies = [ - "chrono", - "marqdo-plugin-sdk", - "pulldown-cmark", - "serde_json", -] - -[[package]] -name = "marqdo_plugin_demo" -version = "0.1.0" -dependencies = [ - "marqdo-plugin-sdk", - "serde_json", -] - -[[package]] -name = "marqdo_plugin_engineering" -version = "0.1.0" -dependencies = [ - "base64", - "chrono", - "flate2", - "hmac", - "libc", - "marqdo", - "marqdo-plugin-sdk", - "serde_json", - "sha2", - "ureq", - "zip", -] - -[[package]] -name = "marqdo_plugin_linalg" -version = "0.1.0" -dependencies = [ - "marqdo-plugin-sdk", - "serde", - "serde_json", -] - -[[package]] -name = "marqdo_plugin_llm" -version = "0.1.0" -dependencies = [ - "idna_adapter", - "marqdo-plugin-sdk", - "serde_json", - "ureq", - "zeroize", -] - -[[package]] -name = "marqdo_plugin_quantum" -version = "0.1.0" -dependencies = [ - "marqdo-plugin-sdk", - "serde", - "serde_json", -] - -[[package]] -name = "md-5" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" -dependencies = [ - "cfg-if", - "digest", -] - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "parse-zoneinfo" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" -dependencies = [ - "regex", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "phf" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" -dependencies = [ - "phf_shared", -] - -[[package]] -name = "phf_codegen" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" -dependencies = [ - "phf_generator", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" -dependencies = [ - "phf_shared", - "rand", -] - -[[package]] -name = "phf_shared" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "predicates" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8" -dependencies = [ - "anstyle", - "difflib", - "float-cmp", - "normalize-line-endings", - "predicates-core", - "regex", -] - -[[package]] -name = "predicates-core" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" - -[[package]] -name = "predicates-tree" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" -dependencies = [ - "predicates-core", - "termtree", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pulldown-cmark" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14" -dependencies = [ - "bitflags", - "getopts", - "memchr", - "pulldown-cmark-escape", - "unicase", -] - -[[package]] -name = "pulldown-cmark-escape" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustls" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" -dependencies = [ - "log", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.102.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - -[[package]] -name = "serde_json" -version = "1.0.151" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_spanned" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] - -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "siphasher" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" - -[[package]] -name = "socket2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "termtree" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tiny_http" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" -dependencies = [ - "ascii", - "chunked_transfer", - "httpdate", - "log", -] - -[[package]] -name = "tinyvec" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" -dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - -[[package]] -name = "tokio-tungstenite" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" -dependencies = [ - "futures-util", - "log", - "tokio", - "tungstenite", -] - -[[package]] -name = "toml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.22.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" -dependencies = [ - "indexmap", - "serde", - "serde_spanned", - "toml_datetime", - "toml_write", - "winnow", -] - -[[package]] -name = "toml_write" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" - -[[package]] -name = "tungstenite" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" -dependencies = [ - "byteorder", - "bytes", - "data-encoding", - "http", - "httparse", - "log", - "rand", - "sha1", - "thiserror", - "utf-8", -] - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicase" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-joining-type" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8d00a78170970967fdb83f9d49b92f959ab2bb829186b113e4f4604ad98e180" - -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-width" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "ureq" -version = "2.9.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d11a831e3c0b56e438a28308e7c810799e3c118417f342d30ecec080105395cd" -dependencies = [ - "base64", - "flate2", - "log", - "once_cell", - "rustls", - "rustls-pki-types", - "rustls-webpki", - "url", - "webpki-roots 0.26.11", -] - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wait-timeout" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" -dependencies = [ - "libc", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasm-bindgen" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" -dependencies = [ - "cfg-if", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.3", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "webpki-roots" -version = "0.26.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" -dependencies = [ - "webpki-roots 1.0.9", -] - -[[package]] -name = "webpki-roots" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - -[[package]] -name = "zerocopy" -version = "0.8.56" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.56" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zeroize" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" - -[[package]] -name = "zip" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261" -dependencies = [ - "byteorder", - "crc32fast", - "crossbeam-utils", - "flate2", -] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index b50971f..0000000 --- a/Cargo.toml +++ /dev/null @@ -1,95 +0,0 @@ -[package] -name = "marqdo" -version = "2.9.1" -edition = "2021" -license = "Apache-2.0" -description = "Marqdo — Markdown markers as an interpreted programming language" -readme = "README.md" -repository = "https://github.com/cflmy/marqdo" - -[[bin]] -name = "marqdo" -path = "src/main.rs" -required-features = ["cli"] - -# Lean 判定集成测试(独立目标:缓存/判定/退出码矩阵,见 tests/prove_lean.rs)。 -[[test]] -name = "prove_lean" -path = "tests/prove_lean.rs" -required-features = ["cli"] - -[features] -default = ["native"] -native = ["cli", "view", "net-host", "plugin-host", "exec-host", "fs-host", "tty"] -cli = ["dep:clap"] -view = ["dep:tiny_http"] -net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize", "dep:zip"] -plugin-host = ["dep:libloading"] -exec-host = ["dep:libc"] -fs-host = [] -tty = ["dep:libc"] -wasm-core = [] - -[dependencies] -anyhow = "1" -chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } -clap = { version = "=4.4.18", features = ["derive"], optional = true } -pulldown-cmark = "0.12" -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["float_roundtrip"] } -thiserror = "1" -tiny_http = { version = "0.12", optional = true } -sha2 = { version = "=0.10.9", default-features = false } -sha1 = { version = "=0.10.6", default-features = false } -md-5 = { version = "=0.10.6", default-features = false } -hmac = { version = "=0.12.1", default-features = false } -getrandom = { version = "=0.2.17", default-features = false, features = ["std"] } -# Mid M1: Unicode regex for lib/re (no backrefs; RE2-like). -regex = { version = "=1.13.1", default-features = false, features = ["std", "unicode"] } -# Pin for Cargo/rustc 1.81 (newer rustls/idna/zeroize need edition2024). -ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"], optional = true } -idna_adapter = { version = "=1.1.0", optional = true } -zeroize = { version = "=1.8.1", optional = true } -# Extract GitHub Release ext/native zips (`marqdo ext add` without local Rust). -zip = { version = "=0.6.6", default-features = false, features = ["deflate"], optional = true } -libloading = { version = "=0.8.6", optional = true } -include_dir = "0.7" -libc = { version = "0.2", optional = true } -chrono-tz = "=0.10.0" -toml = "=0.8.23" - -[target.'cfg(target_arch = "wasm32")'.dependencies] -# Custom entropy — no `js`/wasm-bindgen imports (raw mq_* ABI + marqdo-bridge.js). -chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] } -getrandom = { version = "=0.2.17", default-features = false, features = ["custom"] } - -[workspace] -members = [ - "plugins/demo", - "plugins/engineering", - "plugins/agent", - "plugins/llm", - "plugins/quantum", - "plugins/linalg", - "crates/marqdo-wasm", - "crates/marqdo-plugin-sdk", -] -# Official web plugin is Go (`plugins/web/`). The legacy Rust web plugin was -# deleted from the tree (see CHANGELOG); git history keeps it if ever needed. -resolver = "2" - -[dev-dependencies] -assert_cmd = "=2.0.14" -predicates = "=3.1.0" -tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] } -tokio-tungstenite = "0.24" -futures-util = "0.3" - -# Size-oriented profile for `marqdo-wasm` (C5). Use: cargo build -p marqdo-wasm --profile release-wasm --target wasm32-unknown-unknown -[profile.release-wasm] -inherits = "release" -lto = true -codegen-units = 1 -opt-level = "z" -strip = true -panic = "abort" diff --git a/README.md b/README.md index 5e3fa6d..9967e38 100644 --- a/README.md +++ b/README.md @@ -1,575 +1,29 @@ -# Marqdo — Your SKILL is now a TOOL. +# Marqdo 生态集成 -

Write it. Inspect it. Call it.

-

让 SKILL 真正成为工具:文档即知识,知识即可执行。

+Marqdo 以 Markdown 编写可执行程序与可验证知识。这个仓库固定一组组件提交,维护组件责任、跨仓库验收和发行组合。 -

-release -Apache-2.0 -Rust runtime -Pure by default -

+## 使用与开发 -> ## Architecture update — where current Marqdo development lives -> -> **This repository is the historical Marqdo v2 line (latest v2.9.1).** Because -> the language/runtime, CLI, protocol contracts and independent tools have -> different architectures and release/version axes, Marqdo development was split -> across multiple repositories. The current implementation, releases and -> developer entry point is: -> -> **➜ [`cflmy/marqdo-cli`](https://git.cflmy.cn/cflmy/marqdo-cli)** -> ([latest release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1)) -> -> Start new work from `marqdo-cli`. It is an independent Rust implementation -> with a new language contract (RFC-LANG-0002), a different package format and a -> different plugin ABI; the v2 syntax/package/plugin ABI in this repository is -> **not** compatible with it and there is no legacy execution path. Independent -> extension fixtures are kept separately in -> [`cflmy/marqdo-extension-conformance`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance). -> Knowledge/Proof/View are designed as external Tool repositories consuming the -> public CLI protocols, not as built-in commands of this repository. -> -> **中文说明:** 由于架构原因,Marqdo 的语言运行时、CLI、协议与独立工具已拆分到多个仓库开发。本仓库保留 v2 历史线;**最新实现、发布与开发入口是 -> [`cflmy/marqdo-cli`](https://git.cflmy.cn/cflmy/marqdo-cli)**。新开发请从 -> `marqdo-cli` 开始;v2 的语法、包格式和插件 ABI 与它不兼容,不存在旧语法兼容执行路径。 +- 安装语言、CLI 和默认标准库,请使用 [Marqdo CLI 的官方发行](https://git.cflmy.cn/cflmy/marqdo-cli/releases)。各工具和扩展在各自仓库提供安装说明。 +- 修改语言、标准库、领域扩展或工具,请先在 [组件目录](components.toml) 找到唯一责任仓库。开发和发布在该组件内独立进行。 +- 验证生态组合,请初始化此仓库的子模块。Git tree 的 gitlink 固定参与验收的源码提交。 -**Marqdo is a Rust-based, document-native runtime for executable AI skills and tools.** Write human-readable prose, GFM tables, parameter contracts, and real functions in one `.mq.md` document. Call a function by its heading, inspect the implementation, and grant side effects explicitly. - -**Not a prompt wrapper.** The document is interpreted as a program by Marqdo; its tool functions are not merely natural-language instructions. - -

-56s film · -Quickstart · -Procurement demo · -View · -Guide · -Website · -Release notes -

- -## Marqdo 2.9.0 — Verified Knowledge Compiler - -Knowledge statements and claims have stable addresses; verified pure contracts compose across static modules and produce independently replayable Lean certificates. Evidence distinguishes abstract `model_proved` from true runtime `proved`. Unsupported runtime effects and semantics are explicitly unverified. [Proof scope and acceptance](doc/design/verified-knowledge-compiler-boundaries.md) · [Release notes](doc/releases/v2.9.0.md). - -## One Markdown file. Three views. Real execution. - -[![Watch Marqdo 2.7.1 — from Markdown to execution](assets/marketing/marqdo-2.7.1-markdown-to-execution-cover.jpg)](assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4) - -**[▶ Watch the 56-second film](assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4)** · [Bilingual captions](assets/marketing/marqdo-2.7.1-markdown-to-execution.srt) · [Reproducible video source](scripts/render-markdown-execution-promo.py) - -> **The point is not to invent a new document format.** A `.mq.md` file uses Markdown headings, paragraphs and tables. Ordinary Markdown renderers still show a readable document. Marqdo adds explicit execution semantics and a View that can inspect functions, values and their relationships on the same document. - -![Three views, one source — source Markdown, rendered Markdown, executable View](assets/marketing/source-markdown-view-concept.png) - -**Concept artwork** showing the design principle: **source → ordinary Markdown rendering → Marqdo View**. Illustrative labels are not a live execution trace. The video includes [a real View screenshot](assets/marketing/user-procurement-view.png), [a standard Markdown rendering](assets/marketing/marqdo-procurement-standard-markdown.png) produced from the actual procurement source, and a business example verified with the 2.7.1 CLI. - -**One `.mq.md` source, three ways to interact:** - -| Source | Standard Markdown | Marqdo runtime + View | -|---|---|---| -| Edit the same Markdown text | Read headings, prose and data tables | Inspect the same document's calls, values and effects | -| No separate prompt or tool implementation specification needed | Works as ordinary readable documentation | Call named functions with `marqdo call` | - - - -## Quickstart — one function, one command - -Install the [latest 2.9.0 CLI release for Windows or Linux](https://github.com/cflmy/marqdo/releases/tag/v2.9.0), then run from this repository's root: - -```bash -marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 -# => 5 +```sh +git clone https://git.cflmy.cn/cflmy/marqdo.git +cd marqdo +git submodule update --init +python3 scripts/check-layout.py --checkouts ``` -The function heading is the callable name. The function's explanation, parameters, return contract, and implementation live **in the same source file**. Use `--json` for machine-readable call results and diagnostics. No LLM key is needed for this quickstart. +## 组件与维护入口 -## A procurement skill with a ¥600 budget +| 目录 | 内容 | +| --- | --- | +| [cli](cli) | 语言实现、宿主原语和公共协议 | +| [tools](tools) | Knowledge、Prove、View、Lint,各自独立仓库 | +| [tests/conformance](tests/conformance) | 独立公共契约测试 | +| 标准库与扩展 | 九个 `marqdo-std-*`、十九个 `marqdo-ext-*` 已预建空仓,接入状态见迁移台账 | -[Read the complete executable procurement document](examples/procurement/index.mq.md) · [How to run and verify the example](examples/procurement/README.md) +[架构和归属](docs/ARCHITECTURE.md) · [开发、验收和发布](docs/DEVELOPMENT.md) · [迁移台账](docs/MIGRATION.md) · [贡献者和 Agent 指引](AGENTS.md) -This is a **seven-tool, offline demonstration**. It knows the local supplier directory, queries a static price catalog, checks the budget, and conditionally creates a **simulated** work order. It also documents receipt handling, negotiation and supplier switching as unconnected stubs. - -![Animated results from real Marqdo 2.7.1 function calls](assets/marketing/procurement-cli.gif) - -**Real CLI results**, edited into a short animation; the accepted order is explicitly **simulated** and never sent. [Capture workflow](scripts/capture-procurement-showcase.py) · [Passing checks](https://github.com/cflmy/marqdo/actions/runs/43358288563). - -```bash -# 1. Approve suppliers: paused or blacklisted entries are excluded. -marqdo call examples/procurement/index.mq.md 查询采购商 "采购商状态='正常'" --json - -# 2. Quote: SUP_JN, 8 ball bearings × ¥36 = ¥288 (sample price). -marqdo call examples/procurement/index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=8 有效秒数=300 --json - -# 3. Budget: ¥600 - ¥120 = ¥480. -marqdo call examples/procurement/index.mq.md 查询余额 已花费=120 --json - -# 4. Recheck supplier, quote, delivery and budget before a local mock order. -marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json - -# 5. Over budget: ¥600 - ¥360 = ¥240 < ¥288. The mock work order must be denied. -marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=360 交付要求天数=7 --effects time.read,process.control --json -``` - -| Case | Budget check | Expected business result | -|---|---|---| -| `已花费=120` | ¥480 available ≥ ¥288 | `ok: true`, **local simulation only, not sent** | -| `已花费=360` | ¥240 available < ¥288 | `ok: false`, budget denial | -| `SUP_YY` | Supplier on blacklist | Excluded from quote / order | - -**Why this matters:** The document doesn't merely tell an agent to obey a limit. The work-order **function itself** calls supplier validation, price lookup, and `查询余额` before returning an order record. Agent instructions and callable business logic can be inspected together. - -> **Important limits:** Price and supplier records are fixtures; `已花费` is caller supplied. No authoritative budget ledger, concurrent reservation, live supplier prices, ERP messaging, real receipt, or payment is implemented. A successful **simulated** order is **not** a real transaction. The demo is a testable starting point, not a financial safety guarantee. - -## Explore the View - -Marqdo 2.7.1 improves the interactive reading experience: implementation details stay open when manually expanded, structured values are presented more clearly, and function/source links are easier to inspect. It **does not introduce new language syntax or APIs**. - -```bash -marqdo view examples/procurement --no-open -``` - -![Marqdo View — original detailed screenshot provided by the project author](assets/marketing/user-procurement-view.png) - -**Original View screenshot provided by the project author.** Notice the natural document typography, values in the margins, and curved connections originating from function calls in the prose. [Additional automated View capture](assets/marketing/procurement-view.png) · [Static Markdown rendering](assets/marketing/marqdo-procurement-standard-markdown.png). - -## One document, multiple uses - -| Prompt-oriented agent skill | Marqdo executable skill | -|---|---| -| Natural-language tool instructions | Natural-language guidance **and** executable functions | -| Description and code often separated | Heading, parameter table, return table and implementation in one `.mq.md` | -| Validation may require separate wiring | Named function calls can be checked, executed and tested | -| Prompts ask a model to comply | Runtime permissions control **declared** effects of a function call | -| Hard to follow implementation through files | View links readable content and implementation details | - -Agent Skills already support scripts; Marqdo's claim is **one document-native language surface** for authoring, inspecting, executing and reusing functions. This is **not** a claim of full formal verification, zero-delay execution, or OS-level isolation of all plugin/process behavior. - -**Resources:** [Release v2.8.0](https://github.com/cflmy/marqdo/releases/tag/v2.8.0) · [Ext pack 2.8.1](https://github.com/cflmy/marqdo/releases/tag/ext-v2.8.1) · [Procurement example](examples/procurement/index.mq.md) · [Executable library authoring](doc/library-development.mq.md) · [Function calling](public/features/22-函数调用.mq.md) · [Link syntax](doc/design/link-syntax.md) · [Website](https://www.marqdo.com/) - ---- - -## Deep dive · 语言、设计与执行系统 - -标准库单文件本身就是手册:直接阅读[文件库](lib/文件.mq.md)、[集合库](lib/表.mq.md)等源码,按函数标题下的参数表、返回契约和动作说明调用;[工程实践](examples/stdlib-handbook/索引.mq.md)演示文件整理、CSV 汇总与文档维护。 -开发标准库和拓展库请直接阅读[可执行库开发指南](doc/library-development.mq.md):契约表、叙述式实现、遮蔽调用与多文件工程组织均有可运行示范。 - -当前 CLI **2.8.0** 新增 `marqdo prove`:知识文件的定理表编译为 Lean 4 并自动判定真假——没有 Lean 工具链也能离线符号执行(诚实降级,绝不冒充证明),有 Lean 时全链路证明并给出反例见证。参见[发布说明](doc/releases/v2.8.0.md)。 - -独立拓展包 **2.8.1**(CLI 仍为 2.8.0):`ext/ai` 插件侧持久化工作流(选择 / 作用域上下文 / 只读失败恢复 / `inspect`)。`marqdo ext add agent` → CDN latest。参见[拓展包说明](doc/releases/ext-2.8.1.md)。 - -CLI **2.8.0** adds `marqdo prove`: theorem tables in knowledge files compile to Lean 4 and are judged automatically — offline symbolic execution without a toolchain (honest degradation, never impersonating a proof), full proofs with counterexample witnesses when Lean is available. - -Ext pack **2.8.1** (CLI remains 2.8.0): plugin-only durable AI workflows with bounded choice, scoped context, failed-only read-only recovery and `inspect`. - -## 核心优势:可执行知识(Executable Knowledge) - -> **Knowledge That Can Run —— 知识即可执行。** -> Marqdo 不是「用 Markdown 写程序」这么简单:它让一个 `.mq.md` 文档**同时**是文稿、知识与程序——同一份结构,同时服务于人、解释器、工具与 AI。 - -```text - .mq.md(同一份文件) - ┌─────────┼─────────┐ - 文稿 知识 程序 - └─────────┼─────────┘ - ▼ - Marqdo 运行时 - ▼ - 可执行知识(Executable Knowledge) -``` - -| 真正的核心优势 | 说明 | -|------|------| -| **知识-代码一致性**
Knowledge-Code Coherence | 说明、数据、示例与实现**同一份源文件**:文档里的表格就是程序的数据,文档里的调用就是真实执行。「文档过期」不再是悄悄漂移,而是可被机器发现的**知识不一致**——知识陈述本身可以被测试。 | -| **函数即工具**
`marqdo call` | 最小可执行单位是文件中的函数,不只是整份文件。人阅读函数旁边的叙述;开发者、测试和 Agent 用 `marqdo call 文件 函数 名字=值` 执行它。知识复用、工具调用、函数级测试和局部改进是同一入口的四种用法。 | -| **默认安全,AI 友好** | 无标记文字默认是叙述(注释),只有显式标记才进入执行。AI 自由发挥**不会污染**文档与代码的边界——这比「自然语言编程」安全得多,是 AI 原生语言的重要前提。 | -| **multi-view artifact**
`.mq.md` 双后缀即开放接口 | `.mq` 告诉解释器「可执行」,`.md` 告诉整个 Markdown 生态「仍是文档」。GitHub 直接读、VS Code 直接改、搜索引擎直接索引、LLM 直接理解、Marqdo 直接运行。**Marqdo 不占有知识,只是给 Markdown 增加执行语义。** | -| **表格即数据结构** | 程序的数据结构直接就是文档的数据结构:单列竖表 → `List`;横表(1 数据行)→ `Map`;横表(多数据行)→ `Map` of `List`(列向聚合);首列写 `@` / `行` / `row` → 行向记录 `List` of `Map`。取元使用 `access(集合, "键")`,链接 `[描述](表达式)` 只承载叙述与执行体。这是 literate programming 的下一步。 | -| **语义干净** | **返回是架构,打印只是函数**:`*…*` 改变控制流,`print` 只是副作用函数;分支与循环长在 Markdown 结构上(`1.` `2.` 递增 = 分支,`-` = 循环),不是所有列表都被粗暴当成 if。 | -| **AI 的可靠上下文与长期记忆** | 一个 `.mq.md` 同时是 documentation + schema + code + examples + knowledge + executable behavior;AI 不必再拼装 README + OpenAPI + JSON Schema + prompt。整个工程天然就是 AI 的**世界模型**——比 RAG 更接近 Executable RAG。 | -| **链接即调用**
Link as Call | 文档里的 `[描述](类.函数)` 不是装饰,是跨文档类调用;编译器解析类/函数并返回 **LinkInfo**,`view` 显示调用点,EKC 建边,`links.lock` 可选复现。**v2.1 已实现可执行知识基础设施**。 | -| **完整工程,不是玩具** | Rust 正经解释器(词法 / 语法 / 语义 / 树遍历 + 字节码后端)、stdlib、模块与对象、debugger、viewer、catalog、WASM、原生插件 ABI、VS Code 扩展、agent / LLM / MCP。 | - ---- - -## 链接语法:链接即调用(v2.1 设计声明) - -> **这是 v2.1 的可执行知识模型。** -> `[]()` 不新增语法:`[]` 是 Markdown 链接的描述;`()` 是**已有代码**,与 `**代码**` 同权。 -> `#` 是类,`##` 是函数;`类.函数` 是**类调用**。 -> 链接只是给这次调用一个名字;`view` 显示调用信息,编译器返回 **LinkInfo**,EKC 建边。 - -### 两文档,一次类调用 - -知识文档 `libai.mq.md`: - -```markdown -# 李白 - -这个文档存储了李白的信息。 - -## 李白的出生年份 - -*701* -``` - -- `# 李白` = 类; -- `## 李白的出生年份` = 函数; -- `*701*` = 返回值。 - -调用文档 `main.mq.md`: - -```markdown -# main -用户想要知道李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) -``` - -`[]` 是描述,`()` 是已有调用 `李白.李白的出生年份`——**类 `李白` 调用函数 `李白的出生年份`**。 -不需要 `print`:`view` 模式天然显示 `()` 的调用信息(类、函数、签名、值)。 -要终端输出,就把同一段代码放进代码链接并加 `print`: - -```markdown -**year = [李白的出生年份](李白.李白的出生年份)** -> print text=`year` -``` - -输出:`701`。 - -### 四条语义 - -1. **`[]` 永不执行**:描述只给人读、给检索/诊断/展示用。 -2. **`()` 与 `**代码**` 同权**:同一套 parser/evaluator;`类.函数` 是类调用,`obj.函数` 是实例调用。 -3. **`#` 是类,`##` 是函数**:不使用 `self`/`自` 的函数是**类函数**,可直接 `类.函数` 调用;使用 `self`/`自` 的是**实例函数**。 -4. **链接 = 描述 + 调用**:`view` 显示调用点;编译器返回 `LinkInfo`;EKC 建边;`links.lock` 可选复现。 - -### 现状与目标 - -| 能力 | v2.0.0 | v2.1 | -|------|-------------|-----------| -| 本地表达式链接(遮蔽) | ✅ `markup: occlusion` | ✅ | -| `()` 与 `**代码**` 同权 | ✅ 表达式/调用 | ✅ | -| 类调用 `类.函数` | ❌ 需先构造实例 | ✅ 直接调用 | -| 跨文档类索引 | ❌ 需 `import` + 实例 | ✅ 项目类索引 | -| 正文链接 `view` 信息 | ❌ | ✅ 目标/签名/值 | -| LinkInfo / check | ❌(`check` 只查契约) | ✅ `link.*` | -| 链接图边(EKC) | ❌ | ✅ `calls` / `references` | -| `links.lock` 可复现 | ❌ | ✅ 可选 | - -### 知识分层:本体 → 知识个体 → 调用面 - -| 层 | 写法 | 语义 | -|----|------|------| -| L1 本体 | `# 诗人` + 字段/类型表 | 类/模式 | -| L2 知识个体 | `# 李白 = > 诗人` + `## 出生年份` + `*701*` | 单体知识类(不是运行时实例) | -| L3 调用面 | `[出生年份](李白.出生年份)` | 类调用/链接 | - -> `# 李白 = > 诗人` 语法上是继承/特化,语义上是「李白是诗人」的知识个体; -> 运行时实例仍是 `> 诗人` / `> 李白`。详见 [knowledge-layers.md](doc/design/knowledge-layers.md)。 - -兼容迁移示例见 [examples/link-syntax/main.compat.mq.md](examples/link-syntax/main.compat.mq.md)。 - -设计宪法:[doc/design/link-syntax.md](doc/design/link-syntax.md) · 链接示例:[examples/link-syntax/](examples/link-syntax/) · 知识分层示例:[examples/knowledge-layers/](examples/knowledge-layers/) · 证据复核:[occlusion-vs-executable-knowledge-2026-10.md](doc/research/occlusion-vs-executable-knowledge-2026-10.md) - ---- - -## 愿景与期许 - -不把「AI 能写 Marqdo」当终点,而是 **「AI 能可靠地生成可验证的 Marqdo」**: - -1. **AI 可验证语言**:`LLM → Marqdo AST → 语义检查 → 结构化诊断 → LLM 修复 → 合格程序`。让类型与语义检查成为 AI 编程闭环里的强约束,堵住「语义看似合理、类型实则不对」的生成。 -2. **Marqdo Schema / Language Server for AI**:机器可读的语言 Schema(`get_syntax` / `validate` / `repair` …),AI 不必读千行文档猜语法,而是 discover → construct → validate → execute → inspect。 -3. **程序即 AI 长期记忆**:`.mq.md` 工程 = 可执行知识库 = AI 的世界模型(Executable Knowledge Representation)。 -4. **链接即调用 / 可执行知识图**:`[描述](类.函数)` 既是文档链接,也是类/函数调用;编译器解析目标、校验签名、返回 LinkInfo;`view` 显示调用点;`.mq.md` 之间的链接长成文档图 + 知识图 + 程序图(Executable Knowledge Graph)。 -5. **知识可测试**:文档中的示例表自动执行;知识与执行结果不一致会被机器报告——Knowledge-Code Coherence 从理念变为日常。 -6. **知识可证明**:知识文件内的定理表 → Lean 4 定理 → 自动判定(`marqdo prove`);离线符号执行与 Lean 单调一致,分歧显式报错——Trusted Knowledge,判定器缺陷优先于任何绿灯。 -6. **可靠性基准**:让同一个 AI 分别用 Python / TypeScript / Marqdo 完成真实任务,测量生成长度、语法 / 语义错误率、修复轮次、token 消耗与人类阅读 / 修改成本——用实验数据证明「文档型语法降低 LLM 生成熵」。 - ---- - -## 为什么重要 - -| 痛点 | Marqdo 的答案 | -|------|----------------| -| 文档过期、示例跑不通 | **一份源文件**:叙述、结构与执行结果同源 | -| 知识散落在 Wiki / 注释 / 脚本里 | **`.mq.md` 即知识单元**,可浏览、可运行、可检索 | -| 人写给人看,AI / 工具另起一套 | **人机同读同写同构**:标记语言对人类友好,对解释器确定 | -| 大仓里「文档站」与「代码仓」脱节 | `view` 文档站 + `debug` 调试面 + `catalog` 清单,同一棵树长大 | - -这不是「再做一个 Markdown 渲染器」,而是:**把文档升格为可解释的程序与可生长的知识库**,让协作在大型项目里依然站得住。 - ---- - -## 语法速览 - -| 标记 | 含义 | -|------|------| -| 无标记行 | 叙述(注释);行内 `` `名` `` 可声明 | -| `**…**` | **代码**(赋值 / 调用 / 表达式) | -| `[描述](表达式)` | **链接(本地)**:描述 + 代码;`()` 与 `**…**` 同权(默认语义) | -| `[描述](类.函数)` | **链接(跨文档/类调用)**:描述 + 已有类函数调用;可解析、可执行(v2.1 目标) | -| `[描述](url)` | 普通 Markdown 导航链接(惰性,不执行) | -| `*…*` | **返回值**(整行、`返回*n*`、或表达式形) | -| `****` / 整行 `**` / `*None*` | **空返回**(`None`),并结束本函数体 | -| `> print …` 等 | 输出等副作用 = **普通函数**,非架构标记 | -| `#` | **类 / 类型**(知识命名空间;`# main` = 入口) | -| `##` … | **函数**(类下函数;使用 `self`/`自` 时为实例方法) | -| `类.函数` | **类调用**(不使用 `self` 的函数;v2.1 目标) | -| `` > `obj`.method … `` | 方法调用(`obj` 为带 `_type` 的 map) | -| 叙述 `` `名` `` / `` `名`=默认 `` | 形参由体推断(`` + `名` `` 仍可用) | -| `1.` … | 体内 `1.` `2.` … = 分支(`N. *` = else) | -| `-` | 循环(`` - `条件` `` 或 `` - [项](遍历 集合 为 项) ``) | -| 表格 | 集合(几何即类型,见下);取元使用 `access(集合, "键")` | -| 单独一行 `---` / `***` | **叙述分隔**(跳过;不是函数收束) | - -> `[键](集合)` / `- [项](集合)` 是旧取元/循环形;迁移后使用 `access(集合, "键")` 与 `- [描述](遍历 集合 为 项)`。旧形只在显式 `markup: classic` 或 `--legacy-markup` 过渡入口中保留,见 [link-syntax.md](doc/design/link-syntax.md)。 - -```markdown -# main - -> 问候 谁=World - -## 问候 - -向`谁`问好。 - -**print text="Hello " + 谁** -*None* - -## 加一 - -对于输入变量`n`,执行**n=n+1**接着返回*n*。 -``` - -**表格几何即类型**:单列竖表 → `List`;横表(1 数据行)→ `Map`;横表(多数据行)→ `Map` of `List`(列向聚合);首列写 `@` / `行` / `row` → 行向记录 `List` of `Map`。详见 [tables-maps-footnotes.md](doc/roadmap/tables-maps-footnotes.md)。 - -完整约定:[markdown-mapping-v0.3.md](doc/design/markdown-mapping-v0.3.md)。 - ---- - -## 理念 - -1. **叙述默认安全**(无标记 = 注释)。 -2. **返回是架构;打印只是函数。** -3. **代码即文档即知识库**:文稿可执行,执行可回看结构,结构可导航与调试。 -4. **对齐 [OKF](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)(Open Knowledge Format)方向**:清单由工具从 `.mq.md` **自动生成**,不是手填配置——见下节与 [catalog-cli.md](doc/design/catalog-cli.md)。 -5. **正经解释器(Rust)**:词法/行分类 → 语法 → 语义 → 树遍历(及字节码);**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md)。 -6. **语言核心保持小**:Language(标记映射 / AST / 语义 / 类型)、Runtime(stdlib / 插件 ABI / WASM / agent)、Document(知识 + 代码 + UI + AI)三层分明——生态功能不淹没语言身份。 - ---- - -## 工程习惯:允许申报未完成,但不允许假装完成 - -Marqdo 允许你写出"还没接通"的代码——**只要写在描述里**。这样文档整体仍能跑, -而欠账是可见、可数、可结算的(而不是假装完成): - -```markdown -## 检索资料 - -| 返回 | 类型 | 说明 | -|------|------|------| -| | list | 命中列表(当前未接) | - -[按关键词检索,接口未接,待开发](None) - -[ERP 推送,模拟](json.parse text={"ok":true,"stub":true}) -``` - -`[]` 里是**自由描述**(不执行);`()` 里是**目标**(唯一执行)。这条语法叫**链接语法**: -目标是本地表达式时,就是**遮蔽**(把代码折叠在括号里);目标是 `类.函数` 时,就是**跨文档类调用**。 -v2.1 实现了文件级链接语义与可执行知识投影(见 [link-syntax.md](doc/design/link-syntax.md))。 - -**四条约定** - -1. **桩必须能跑**:不得报错,否则整篇文档被阻断。 -2. **桩必须写明返回值**:写 `None` 也比空着好;空 `()` 会报 `label.empty_payload`(warning)。 -3. **申报用词有范例**:内置词表(`待开发` `未实现` `开发中` `模拟` `桩` `示例` `实验` `废弃` …) - 是**推荐用词与默认检索集**,不是语法——写别的说法同样合法。 -4. **接不了就申报,别声称完成**:这条已写进 `ext/ai` 的 agent 提示词。 - -**盘点与门禁** - -```bash -marqdo labels --count # 内置口径:还有多少未完成 -marqdo labels --grep "接口未联调,联调中" --count # 用你自己的说法 -marqdo labels --grep 联调 --also-builtin --count # 自定义 + 内置一起数 -marqdo labels --count --baseline .marqdo/pending.json --fail-on-increase -``` - -最后一条是**棘轮**:只拦"新增未完成",不追旧账。 - -设计依据:[link-syntax.md](doc/design/link-syntax.md) · [occlusion-syntax.md](doc/design/occlusion-syntax.md) · -[occlusion-description-and-search.md](doc/design/occlusion-description-and-search.md) - ---- - -## OKF 风格清单(自动生成) - -从源码派生 YAML / Markdown 知识包(勿手改生成物): - -```bash -marqdo catalog [PATH] -o OUT_DIR -marqdo sync [PATH] -o OUT_DIR # catalog 的别名 - -# Engineering Knowledge Compiler(L0–L4 能力目录 / 复用门闩) -marqdo knowledge [PATH] -o OUT_DIR -marqdo find "authentication" -marqdo reuse "implement oauth login" -marqdo duplicate [--fail] -marqdo verify -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `PATH` | `.` | 工程根或含 `.mq.md` 的目录 | -| `-o` / `--out` | `.marqdo` | 输出目录 | - -`catalog` 成功后默认再跑 EKC(`--no-knowledge` 可关)。产物示例:`catalog.yaml`、`engineering.yaml`、`catalog/capabilities/`、`graph/graph.json`。设计见 [engineering-knowledge.md](doc/design/engineering-knowledge.md) · [catalog-cli.md](doc/design/catalog-cli.md) · 调研 [okf-and-marqdo.md](doc/research/okf-and-marqdo.md)。 - -智能体框架横向调研(LangGraph / CrewAI / 厂商 SDK 等 vs Marqdo 文档驱动优势):[agent-frameworks-and-marqdo.md](doc/research/agent-frameworks-and-marqdo.md) · 优化路线 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md)。 - -```bash -cargo run -- catalog public -o .marqdo -# 或已安装二进制时: -marqdo catalog public -o .marqdo -``` - ---- - -## 现状(v2.7.0) - -- **实际工程与可执行 SKILL(v2.7.0)**:中英文用户站点使用递归 View、普通 Markdown、当前数据/表单/会话资源并保留原始主题。开发与发版手册通过 `marqdo call` 执行,固有文件能力负责读写,工程插件承接进程、认证与格式边界。旧独立浏览器演示已收敛到实际可运行的工程;详见 [2.7.0 发布说明](doc/releases/v2.7.0.md)。 -- **标准库与拓展库手册(v2.6.0)**:61 份公开标准库、650 个函数;源码内参数/返回契约、叙述形参、句中遮蔽调用与真实工程。新增文件/字节/集合/Result/文档/HTTP/任务/TOML/时区工作流;多文件拓展库以 index 组织。 -- **View 可读动作与知识(v2.6.0)**:正文读动作,侧注看实现,运行标注看实际结果;空逻辑明确提示待补。知识说明先看输入、返回、依赖和依据,技术身份按需展开。 -- **Quantum / Web 工程实践(v2.6.0)**:可执行实验、会话句柄与双语门面;网页先递归拆布局,直到叶子可以直接用 Markdown 表达。CLI · wasm · ext · VS Code 扩展同步 **2.7.0**。 - -- **View 连线与工具栏(v2.5.1)**:真实源码锚点、连续 S 形曲线、错落标注与连线避让;底部工具栏增加文字标签。深浅色配色保持一致。CLI · wasm · ext 同步 **2.5.1**。 - -- **View 阅读界面(v2.5.0)**:暖白金色主题、新 Logo 与花枝装饰;真实执行信息左右引出、窄屏内联;导航/搜索/阅读设置/工具栏;重跑同步刷新与离线公式。CLI · wasm · ext 同步 **2.5.0**。 - -- **Oracle journal 语言值(v2.4.0)**:`foreign.oracle_journal` / `foreign.replay_check` 作普通值;handle/code 拒入 journal;bytecode/frontend 硬化;扩展包同步 **2.4.0** -- **Foreign Strong(v2.3.0)**:会话 `handle`(不可过桥)· 仿射 close · `replay_check`/oracle journal · 表 arity refuse · Ω∈\(V_{\mathsf{safe}}\)。扩展包同步 **2.3.0** -- **\(V_{\mathsf{safe}}\) JSON 整数(v2.2.2)**:外联与 `lib/json` 拒绝 `|n| > 2^{53}-1` 的 JSON 整数(对齐 Lean ForeignJSON);宽整数用十进制字符串 + Node `BigInt`。 -- **view 大纲侧栏(v2.2.1)**:修复 occlusion 文档与中等宽度下 Functions / Variables 掉到正文下方的问题;静态 `view output` 同源。 -- **函数级调用(v2.2.0)**:`marqdo call <文件.mq.md> <函数> 名字=值`。同一份文档给人读,也按函数执行;Tree 与 Bytecode 都跑被点名的函数,不回退到 `# main`。默认只执行纯函数。`--json` 给 Agent 读取结果或诊断。说明与价值见 [22-函数调用](public/features/22-函数调用.mq.md)。示例:`marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3` → `5`。扩展包同步 **2.2.1** -- **Agent 可靠工作台(v2.1.5)**:ResourceView(JSON/CSV/PDF/image)· ToolSpec 授权先于调用 · CheckpointV2 / EffectLedger / ContextPackV2 · EKC `ir.json` 暖机与 `--refresh` · Web 短读/控制与 execute 槽隔离;扩展包同步 **2.1.5** -- **默认隔离 HTTP execute(v2.1.4 · ADR 0009)**:`execute` / `sse-live` / `stream:true` → Supervisor worker 池(`--call-lib-path`);父进程不再占 `INVOKE_LOCK`;`/_runtime/*`;`runtime.isolated_execution=1`;MR-01 金样例 -- **知识工作台运行时(v2.1.3)**:ModelSelection / RunContext / usage null≠0 · `view document` 只读嵌入 · LLM selection/messages/cancel · agent.step selection e2e · live smoke(设计 Partial:原生适配器 unavailable) - -- **可执行知识生产链(v2.1.2)**:证据/闭包失效 · `verify`/`adjudicate` · `reuse_execute` / `eng_bind_execute`+`publish_gate` · `document.extract` · View `KnowledgePresentation`+SSE `page_token` · 上传限流 · 门禁 45 项(100/1000 单元) -- **可执行知识主链(v2.1.1)**:BoundCall 双后端 · NarrativeRef · 来源/适用期 · `artifact.patch` / `extract_pure` · 整代 `CURRENT` + closure · 发票示例 `113` -- **链接语法(v2.1.0)**:`[描述](目标)` 描述不执行 · `()` 与 `**代码**` 同权(`加(1)` / `加一 号(31)`)· `access` 取元与 `遍历` 链接循环 · `marqdo labels` 两级检索 / `--baseline` 债务棘轮 · `migrate labels --mark` · 诊断 `label.*` · view 描述正文 + 代码片 + 桩徽章 · **可执行知识 [link-syntax.md](doc/design/link-syntax.md)**(项目索引、LinkInfo、链接图与 lock) -- **外联 v3 P0/P1(v1.5.2)**:raw stdin + 每 cell 独立输入 · plan API · snapshot export/import/replay · `view capture` · Persist 按钮 · 扩展包同步 **1.5.2** -- **view 静态/动态统一 + 外联值传递(v1.5.1)**:静态导出与 live view 共用 `foreign_doc` 执行路径 · 构建时运行注入 stdout · `foreign.session` 值传递 · cell stdin;扩展包同步 **1.5.0** -- **裸自增升参(v1.4.6)**:首次粗体赋值左值即声明;`**n = n + 1**` 无反引号也升为必选形参。扩展包仍为 **1.4.5** -- **Streamable HTTP MCP + web invoke 鉴权(v1.4.5)**:`agent_mcp_serve transport=http` · Bearer/`X-Api-Key` 注入 · `unauthorized`→401 · openai/agent `json.get` 硬化 -- **LLM 传输软失败 + `ext/ai` 表优先(v1.4.4)**:上游不可达 → `status=error`(不 abort);`agent`/`llm` 去 `json.set` 胶水 · [agent-llm-transport-soft-2026-10.md](doc/research/agent-llm-transport-soft-2026-10.md) -- **Ext pack 1.4.3**:修复 `agent.run` cold EFI(`` `self`.preflight `` + miss resolve `llm_free`);已并入 **≥1.4.4** · [agent-run-efi-resolve-bugs-2026-10.md](doc/research/agent-run-efi-resolve-bugs-2026-10.md) -- **Agent/LLM 优化 O1–O5(v1.4.2)**:`ext/ai/sandbox` CoW · `agent.trial` / `sandbox=` · promote sandbox proof · `step_route` / EFI / cost · style lint · quarantine · [ext-ai-optimize.md](doc/roadmap/ext-ai-optimize.md) -- **view 标注连线(v1.4.1)**:underline→chip SVG mid→mid(底边中点→轨道→短竖线→顶边中点)· 帧 chip 共用 id · L→R 密度 · [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md) -- **叙述统一 / 公式 meta / 图片自写回(v1.4.0)**:`% marqdo: var=` 块公式绑定 · 臂/循环体叙述与 foreach 中英糖 · `![marqdo-out](…)` 图片自写回 · view 推断形参实值 · [fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md) -- **view 文档面(v1.3.3)**:Browse Structure 叙述保真 · 标记面 · 分支/循环帧下拉 · AI `#mq-view-trace` · 静态 `view output` / gh-pages 同源 · [view-document-annotations.md](doc/design/view-document-annotations.md) -- **Engineering Knowledge(v1.3.0)**:EKC L0–L4 · `marqdo knowledge|find|reuse|duplicate|verify|…` · Agent `preflight` / REUSE→ADAPT→CREATE · [engineering-knowledge.md](doc/design/engineering-knowledge.md) -- **Web Artifact(v1.2.0 · ADR 0007)**:Document/Endpoint 一等公民(`type: web|endpoint`)· facade `page`/`route`/`serve`/`render`/`inspect`/`use` · Resource 拆到 `ext/data`/`security`/`net` · 统一 View 表 · 破坏性移除 `compose_*`/`configure` -- **AI 栈(v1.1.1)**:`ext/ai/llm` 语义 `ask`/`stream`/`collect` · Artifact Metadata Binding(`${env|arg|sys|secret}`)· Agent Skill Compilation + Adaptive Routing · MCP stdio 客户端 + resume 检查点 · 可选 `plugins/llm` Transport ABI -- **AI 原生闭环(v1.1.0)**:核心表面守卫(19 构造,单边改动 CI 必红)· **渐进式契约**(文档内嵌 `参数`/`返回`/`字段` 表 + 四边界校验 + `marqdo check` 防漂移)· **MLSP for AI**(`marqdo mlsp`:`locate`/`syntax`/`validate`/`repair_targets`/`repair_apply`/`schema`,AI 按需查语法而非背诵)· **结构化诊断**(`run --json`,错误即数据);验证见 [perf-validation-report-2026-09-23.md](doc/roadmap/perf-validation-report-2026-09-23.md) -- 映射与解释器:**v0.3 语法宪法**(`**` 代码 / `*` 返回 / 叙述声明);Phase I 树遍历 + 字节码后端;金样例在 `tests/` 与 `tests/markup-v03/` -- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md) -- **`marqdo view`**:文档浏览器(**文档面** Structure + 标注 / 调用·循环帧 + 函数大纲/搜索 + Execution + Variables 浮窗;`view output` 同构) -- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430;页面 favicon / 品牌使用官方 Logo) -- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页(默认挂钩 EKC) -- **`marqdo knowledge` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify`**:Engineering Knowledge Compiler([engineering-knowledge.md](doc/design/engineering-knowledge.md)) -- **`marqdo version --check`**:与 GitHub 最新 release 对比 -- 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、表、**浏览器效应**、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**;**中层 Mid M1–M6** + **Mid2 M7–M10**(datetime/url/toml/html/fs++/stats/log.fields 等,见 [stdlib-mid.md](doc/design/stdlib-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md)) -- **官方扩展库 `ext/`**(**非** stdlib,本版收口): - - **`web`**:**Artifact 模型(ADR [0007](doc/adr/0007-web-document-endpoint.md))** — `type: web|endpoint` Document/Endpoint;facade `page`/`route`/`serve`/`render`/`inspect`/`use`;Resource 在 `ext/data` · `ext/security` · `ext/net`;设计 [ext-web-artifact.md](doc/design/ext-web-artifact.md);原生 **Go `libweb`**([ADR 0004](doc/adr/0004-web-plugin-go.md));示例 [marqdo-blog](examples/marqdo-blog/) · [web-client-site](examples/web-client-site/) · [完整站点](examples/web-site/) · [中文完整站点](examples/web-site-zh/) - - **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/) - - **`linalg`**:L0–L6 + 公式文档面(中缀 / `declare` / 展示化简);示例 [linalg-transpose](examples/linalg-transpose/) · [linalg-svd](examples/linalg-svd/) · [linalg-least-squares](examples/linalg-least-squares/) - - **`agent`**:A1–A4 + **MCP Server/Client**(stdio + **Streamable HTTP**)+ Skill Compilation + Adaptive Routing + resume + **Engineering preflight**(`agent.preflight` / `eng_preflight`);宿主缺口见 [ext-hosting.md](doc/roadmap/ext-hosting.md) · [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md) · [engineering-knowledge.md](doc/design/engineering-knowledge.md) - - **`llm`**:语义 `ask`/`stream`/`collect`(OpenAI/Ollama;可选原生 `plugins/llm`) - - 安装:`marqdo ext list` / `add …` / `remove`([ext-cli.md](doc/design/ext-cli.md);默认 `~/.marqdo/ext`)。原生插件先 `cargo build -p marqdo_plugin_*` 再 `ext add` -- **原生插件 ABI**:[`include/marqdo_abi.h`](include/marqdo_abi.h) · [ext-abi.md](doc/design/ext-abi.md);`plugins/{demo,agent,web,quantum,linalg,llm}`(`web` 为 Go;其余为 Rust) -- **用户静态站**:`public/` → `view output` → CI 发布 [gh-pages](https://cflmy.github.io/marqdo/) -- **VS Code 扩展**:分支 **`vscode-extension`**(`main` 不跟踪源码;见 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md));Release 附带 `.vsix` -- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-app](examples/browser-app/) · [web-spa-app](examples/web-spa-app/) · [web-collab-doc](examples/web-collab-doc/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md)) -- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md) - -### 如何使用最新 Marqdo(v2.7.0) - -**安装解释器(任选其一)** - -| 方式 | 适用 | 命令 / 链接 | -|------|------|-------------| -| **Ubuntu PPA** | Ubuntu 24.04+(`noble` 等) | `sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo` | -| **GitHub Releases** | Windows / Linux 预编译 zip | https://github.com/cflmy/marqdo/releases | -| **源码** | 需本机 Rust | 见下方 `git clone` + `cargo build --release` | - -**安装官方扩展**(与 CLI 可分开发版):`marqdo ext add …` 默认下载顺序为 **CDN** [`https://ext.marqdo.com`](https://ext.marqdo.com) → GitHub Releases → [`proxy.cflmy.top`](https://proxy.cflmy.top) 镜像。 - -```bash -# 1) 源码安装(跟 tag 或 main) -git clone https://github.com/cflmy/marqdo.git && cd marqdo -git checkout v2.7.0 # 或留在 main -cargo build --release -export PATH="$PWD/target/release:$PATH" -marqdo version -marqdo version --check - -# 2) 跑整个文件,或只调用其中一个函数 -marqdo run tests/structure/hello.mq.md -marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 -marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 --json -marqdo run tests/structure/hello.mq.md --backend bytecode -marqdo view public --no-open -marqdo debug public --no-open -marqdo catalog public -o .marqdo - -# 2b) AI 原生闭环(v1.1.0+):契约检查 / 结构化诊断 / MLSP 查询 -marqdo check tests/contracts/ok_contract.mq.md # 静态契约防漂移 -marqdo run tests/structure/hello.mq.md --json # 结构化诊断(错误即数据) -printf '{"id":1,"method":"syntax","params":{"query":"返回"}}\n' | marqdo mlsp - -# 3) 安装官方扩展(Release / CDN 用户:无需本机 Rust/Go) -marqdo ext add web # 或:网页 — 自动下载 L1 + 预编译 native(Go libweb) -marqdo ext add agent # 或:智能体 -marqdo ext add quantum # 或:量子 -marqdo ext add linalg # 或:线性代数 -marqdo ext add llm # 或:大模型(.mq.md + 可选 native llm) -# 开发者:cargo build --release -p marqdo_plugin_{agent,quantum,linalg,llm} -# bash ./scripts/build-web-plugin.sh # 需 Go + cgo → libweb -# 离线:解压 Windows zip(已含 ext/native)或手动放下 native zip;MARQDO_EXT_NO_DOWNLOAD=1 - -# 4) 动态站示例(扩展装好后) -marqdo run examples/web-site-zh/index.mq.md # 表驱动引言 Demo -marqdo run examples/marqdo-blog/serve.mq.md -marqdo call examples/web-site/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-site --json -# 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8 - -# 5) 浏览器 WASM(可选) -marqdo wasm build -# → dist/wasm/ … 实际工程见 examples/browser-app/ - -# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip -# https://github.com/cflmy/marqdo/releases/tag/v2.7.0 -``` - -开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`: - -```bash -cargo run -- run tests/structure/hello.mq.md -cargo run -- view public --no-open -cargo run -- view output public -o public -powershell -File ./scripts/build-public.ps1 -``` - -**发布包**:GitHub Releases 的单独二进制 **已内置**官方 `lib/`。Ubuntu 用户优先 **PPA** 装 CLI。**扩展库**用 `marqdo ext add …`(CDN → GitHub);设计见 [ext-cdn.md](doc/design/ext-cdn.md) · [ubuntu-ppa.md](doc/design/ubuntu-ppa.md) · [ext-cli.md](doc/design/ext-cli.md)。 - -文档:用户站 [public/](public/) · 设计 [doc/](doc/) · OKF / catalog [catalog-cli.md](doc/design/catalog-cli.md) · 调试 [view-debug.md](doc/design/view-debug.md) · 变更 [CHANGELOG.md](CHANGELOG.md) ---- - -## 命名 - -**Marqdo** = Marq(Markdown)+ do(执行) - -## 许可 - -[Apache License 2.0](LICENSE) +v2 实现、历史文档和示例可从 Git 历史查阅。[v2.9.1 历史树](https://git.cflmy.cn/cflmy/marqdo/src/tag/v2.9.1) diff --git a/assets/marketing/marqdo-2.7.1-markdown-to-execution-cover.jpg b/assets/marketing/marqdo-2.7.1-markdown-to-execution-cover.jpg deleted file mode 100644 index 6f926a6..0000000 Binary files a/assets/marketing/marqdo-2.7.1-markdown-to-execution-cover.jpg and /dev/null differ diff --git a/assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4 b/assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4 deleted file mode 100644 index 04577ed..0000000 Binary files a/assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4 and /dev/null differ diff --git a/assets/marketing/marqdo-2.7.1-markdown-to-execution.srt b/assets/marketing/marqdo-2.7.1-markdown-to-execution.srt deleted file mode 100644 index 4d87a84..0000000 --- a/assets/marketing/marqdo-2.7.1-markdown-to-execution.srt +++ /dev/null @@ -1,35 +0,0 @@ -1 -00:00:00,000 --> 00:00:04,800 -Your SKILL is now a TOOL. -让 Markdown 直接承载可执行语义。 - -2 -00:00:04,800 --> 00:00:11,600 -源码态:标题、段落、表格都沿用 Markdown。 -执行逻辑就在文档之中。 - -3 -00:00:11,600 --> 00:00:18,000 -渲染态:同一份代码也能成为普通 Markdown 文档。 - -4 -00:00:18,000 --> 00:00:25,000 -源码态、标准 Markdown 渲染态、Marqdo View 态。 -三种视图,同一份源文件。 - -5 -00:00:25,000 --> 00:00:32,500 -一份 .mq.md,既可以阅读,也可以编译执行。 - -6 -00:00:32,500 --> 00:00:42,000 -真实 View 截图:函数调用和值沿着优雅曲线呈现。 - -7 -00:00:42,000 --> 00:00:50,800 -预算校验不是文字承诺,而是函数执行。 -模拟订单通过或拒绝,均由运行时返回结果。 - -8 -00:00:50,800 --> 00:00:56,000 -Marqdo 2.7.1 · github.com/cflmy/marqdo diff --git a/assets/marketing/marqdo-2.7.1-poster.jpg b/assets/marketing/marqdo-2.7.1-poster.jpg deleted file mode 100644 index 7f0c427..0000000 Binary files a/assets/marketing/marqdo-2.7.1-poster.jpg and /dev/null differ diff --git a/assets/marketing/marqdo-2.7.1-promo.mp4 b/assets/marketing/marqdo-2.7.1-promo.mp4 deleted file mode 100644 index 233048e..0000000 Binary files a/assets/marketing/marqdo-2.7.1-promo.mp4 and /dev/null differ diff --git a/assets/marketing/marqdo-2.7.1-promo.srt b/assets/marketing/marqdo-2.7.1-promo.srt deleted file mode 100644 index f7339fc..0000000 --- a/assets/marketing/marqdo-2.7.1-promo.srt +++ /dev/null @@ -1,29 +0,0 @@ -1 -00:00:00,000 --> 00:00:03,900 -Your SKILL is now a TOOL. -让 SKILL 真正成为工具。 - -2 -00:00:03,900 --> 00:00:09,000 -One readable document. Callable business logic. -规则、数据、工具在同一份文档里。 - -3 -00:00:09,000 --> 00:00:17,400 -Five verified CLI calls, from quote to decision. -真实 CLI 结果:询价、预算、模拟发单。 - -4 -00:00:17,400 --> 00:00:23,400 -¥120 spent: mock order. ¥360 spent: rejected. -¥120 时模拟通过;¥360 时预算不足。 - -5 -00:00:23,400 --> 00:00:29,000 -Inspect the actual document in Marqdo View. -查看 Marqdo 真实 View 页面。 - -6 -00:00:29,000 --> 00:00:32,000 -github.com/cflmy/marqdo -开源 · Marqdo 2.7.1 diff --git a/assets/marketing/marqdo-procurement-standard-markdown.png b/assets/marketing/marqdo-procurement-standard-markdown.png deleted file mode 100644 index 1a294e1..0000000 Binary files a/assets/marketing/marqdo-procurement-standard-markdown.png and /dev/null differ diff --git a/assets/marketing/procurement-cli.gif b/assets/marketing/procurement-cli.gif deleted file mode 100644 index f60058d..0000000 Binary files a/assets/marketing/procurement-cli.gif and /dev/null differ diff --git a/assets/marketing/procurement-flow.svg b/assets/marketing/procurement-flow.svg deleted file mode 100644 index 6cdbbee..0000000 --- a/assets/marketing/procurement-flow.svg +++ /dev/null @@ -1,42 +0,0 @@ - - - -Marqdo -/ EXECUTABLE SKILLS - -2.7.1 · DEMO -Your SKILL is now a TOOL. -A human-readable document → callable business logic → structured results - - - - -index.mq.md -$ marqdo call ... 向采购商发工单 -## 向采购商发工单 -Read the rules. Call the function. - -报价 = 查询采购商价格(...) -预算 = 查询余额(已花费=...) -1. 剩余额度 < 本单金额 → 拒绝 -One file: prose + contracts + tables -+ executable functions + result records -SUP_JN 数量=8 单价=36 -最高预算 = ¥600 -01 SUPPLIERSUP_JN · active -02 QUOTE8 × ¥36 = ¥288 -03 BALANCE¥600 - already spent -04 DECISIONcheck requested amount - - -✓ 已花费=120 ¥480 ≥ ¥288 -ok: true · 本地模拟,未发送 - - - -✕ 已花费=360 ¥240 < ¥288 -ok: false · 预算不足,拒绝工单 - - -ILLUSTRATED EXPECTED FLOW · NOT A TERMINAL CAPTURE · NO REAL PURCHASE - \ No newline at end of file diff --git a/assets/marketing/procurement-view-concept.svg b/assets/marketing/procurement-view-concept.svg deleted file mode 100644 index f284a76..0000000 --- a/assets/marketing/procurement-view-concept.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - -marqdo -文档 函数 执行 变量 -VIEW CONCEPT / NOT CAPTURE - -采购智能体 -向采购商发工单 -核对准入、价格、交付与预算之后,生成本地模拟工单。 - -参数 -采购商标识符 -text -必填 - -数量 / 单价 / 已花费 -number -必填 - -发单前,必须再次查询并核对本轮的可用余额。 - -预算 = [重新查询预算](查询余额(...)) -1. 剩余额度 < 本单金额 - 返回 [预算不足,拒绝模拟工单](...) -仅在全部检查通过时产生“本地模拟、未发送”的结果。 - -BUDGET CHECK -已花费 ¥360 -剩余额度 ¥240 - -REJECTION -¥240 < ¥288 -拒绝工单 - \ No newline at end of file diff --git a/assets/marketing/procurement-view.png b/assets/marketing/procurement-view.png deleted file mode 100644 index a155e06..0000000 Binary files a/assets/marketing/procurement-view.png and /dev/null differ diff --git a/assets/marketing/source-markdown-view-concept.png b/assets/marketing/source-markdown-view-concept.png deleted file mode 100644 index e6132c5..0000000 Binary files a/assets/marketing/source-markdown-view-concept.png and /dev/null differ diff --git a/assets/marketing/user-procurement-view.png b/assets/marketing/user-procurement-view.png deleted file mode 100644 index 2fe03b1..0000000 Binary files a/assets/marketing/user-procurement-view.png and /dev/null differ diff --git a/cli b/cli new file mode 160000 index 0000000..452e9a3 --- /dev/null +++ b/cli @@ -0,0 +1 @@ +Subproject commit 452e9a32bd9e40dba427d4180691c58bab74449e diff --git a/components.toml b/components.toml new file mode 100644 index 0000000..f7d43d5 --- /dev/null +++ b/components.toml @@ -0,0 +1,382 @@ +# 生态组件职责与构建关系。精确提交由 Git tree 的 gitlink 锁定。 +# planned 的 requires 是设计输入,接入前须核对实际 imports 和发布依赖。 + +[[component]] +id = "cli" +path = "cli" +kind = "core" +state = "active" +owner = "cflmy" +scope = "语言语义、运行时、受控宿主和公共协议" +requires = [] +checks_with = ["conformance"] +release = "base" +entry = "tools/release/smoke.py" + +[[component]] +id = "conformance" +path = "tests/conformance" +kind = "test" +state = "active" +owner = "cflmy" +scope = "可执行的独立公共协议测试" +requires = ["cli"] +checks_with = [] +release = "none" +entry = "scripts/build_all.sh" + +[[component]] +id = "view" +path = "tools/view" +kind = "tool" +state = "active" +owner = "cflmy" +scope = "阅读、运行观察与静态导出" +requires = ["cli"] +checks_with = [] +release = "optional" +entry = "scripts/acceptance.sh" + +[[component]] +id = "knowledge" +path = "tools/knowledge" +kind = "tool" +state = "active" +owner = "cflmy" +scope = "静态知识编译与检索" +requires = ["cli"] +checks_with = [] +release = "optional" +entry = "scripts/ci.sh" + +[[component]] +id = "prove" +path = "tools/prove" +kind = "tool" +state = "active" +owner = "cflmy" +scope = "证明依赖、证书及 Lean 后端" +requires = ["cli"] +checks_with = [] +release = "optional" +entry = "scripts/package-tool.sh" + +[[component]] +id = "lint" +path = "tools/lint" +kind = "tool" +state = "active" +owner = "cflmy" +scope = "静态规则、诊断及显式修复" +requires = ["cli"] +checks_with = [] +release = "optional" +entry = "scripts/package-tool.sh" + +[[component]] +id = "std-core" +path = "stdlib/core" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "Result 与基础数值" +requires = ["cli"] +checks_with = [] +release = "base" + +[[component]] +id = "std-collections" +path = "stdlib/collections" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "List、Map 和 Table 值操作" +requires = ["cli", "std-core"] +checks_with = [] +release = "base" + +[[component]] +id = "std-text" +path = "stdlib/text" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "Unicode 文本、字节值与 UTF-8" +requires = ["cli", "std-core", "std-collections"] +checks_with = [] +release = "base" + +[[component]] +id = "std-encoding" +path = "stdlib/encoding" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "Base64、Base32 和 Hex" +requires = ["cli", "std-core", "std-text"] +checks_with = [] +release = "base" + +[[component]] +id = "std-data" +path = "stdlib/data" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "JSON、CSV、TOML 与 GFM 数据转换" +requires = ["cli", "std-collections", "std-text", "std-encoding"] +checks_with = [] +release = "base" + +[[component]] +id = "std-io" +path = "stdlib/io" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "Console、Stream、格式化和官方 print 别名" +requires = ["cli", "std-core", "std-text"] +checks_with = [] +release = "base" + +[[component]] +id = "std-fs" +path = "stdlib/fs" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "文件、目录与路径" +requires = ["cli", "std-io", "std-text"] +checks_with = [] +release = "base" + +[[component]] +id = "std-system" +path = "stdlib/system" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "时钟、UTC、环境、进程与随机" +requires = ["cli", "std-text", "std-io"] +checks_with = [] +release = "base" + +[[component]] +id = "std-net" +path = "stdlib/net" +kind = "stdlib" +state = "planned" +owner = "cflmy" +scope = "TCP、UDP、TLS 和网络字节流" +requires = ["cli", "std-io", "std-system"] +checks_with = [] +release = "base" + +[[component]] +id = "math" +path = "extensions/math" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "数值算法、统计、符号数学及绘图" +requires = ["cli", "std-core", "std-collections", "std-text"] +checks_with = [] +release = "optional" + +[[component]] +id = "linalg" +path = "extensions/linalg" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "复数、矩阵、分解及数值线性代数" +requires = ["cli", "math"] +checks_with = [] +release = "optional" + +[[component]] +id = "quantum" +path = "extensions/quantum" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "量子电路、态向量、采样与模拟" +requires = ["cli", "linalg"] +checks_with = [] +release = "optional" + +[[component]] +id = "http" +path = "extensions/http" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "HTTP、URL、SSE 与报文生命周期" +requires = ["cli", "std-net", "std-text", "std-encoding"] +checks_with = [] +release = "optional" + +[[component]] +id = "websocket" +path = "extensions/websocket" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "WebSocket 握手、帧与连接语义" +requires = ["cli", "http"] +checks_with = [] +release = "optional" + +[[component]] +id = "ai" +path = "extensions/ai" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "模型协议、流式输出与工具调用数据" +requires = ["cli", "http", "std-data"] +checks_with = [] +release = "optional" + +[[component]] +id = "mcp" +path = "extensions/mcp" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "MCP 协议、传输、发现和调用" +requires = ["cli", "http", "std-system"] +checks_with = [] +release = "optional" + +[[component]] +id = "crypto" +path = "extensions/crypto" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "成熟密码学实现的封装" +requires = ["cli", "std-encoding"] +checks_with = [] +release = "optional" + +[[component]] +id = "database" +path = "extensions/database" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "SQL 参数绑定、事务和驱动连接" +requires = ["cli", "std-data"] +checks_with = [] +release = "optional" + +[[component]] +id = "storage" +path = "extensions/storage" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "本地和对象存储接口" +requires = ["cli", "std-fs"] +checks_with = [] +release = "optional" + +[[component]] +id = "cache" +path = "extensions/cache" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "TTL、缓存和失效" +requires = ["cli", "std-system"] +checks_with = [] +release = "optional" + +[[component]] +id = "security" +path = "extensions/security" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "应用身份、会话及权限模型" +requires = ["cli", "crypto", "http"] +checks_with = [] +release = "optional" + +[[component]] +id = "web" +path = "extensions/web" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "Markdown/GFM 渲染、页面、路由和组件" +requires = ["cli", "http"] +checks_with = [] +release = "optional" + +[[component]] +id = "browser" +path = "extensions/browser" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "浏览器宿主、WASM 适配、DOM 和事件" +requires = ["cli"] +checks_with = [] +release = "optional" + +[[component]] +id = "document" +path = "extensions/document" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "Markdown 结构与显式文档编辑" +requires = ["cli", "std-fs", "std-text"] +checks_with = [] +release = "optional" + +[[component]] +id = "archive" +path = "extensions/archive" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "压缩、安全归档和解包" +requires = ["cli", "std-text", "std-fs"] +checks_with = [] +release = "optional" + +[[component]] +id = "engineering" +path = "extensions/engineering" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "工程操作、文件补丁与产物" +requires = ["cli", "document", "archive"] +checks_with = [] +release = "optional" + +[[component]] +id = "regex" +path = "extensions/regex" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "正则匹配、捕获、扫描和替换" +requires = ["cli", "std-text"] +checks_with = [] +release = "optional" + +[[component]] +id = "datetime" +path = "extensions/datetime" +kind = "extension" +state = "planned" +owner = "cflmy" +scope = "IANA 时区、DST 和高级日历" +requires = ["cli", "std-system"] +checks_with = [] +release = "optional" diff --git a/crates/marqdo-plugin-sdk/Cargo.toml b/crates/marqdo-plugin-sdk/Cargo.toml deleted file mode 100755 index 6cabd42..0000000 --- a/crates/marqdo-plugin-sdk/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "marqdo-plugin-sdk" -version = "2.0.0" -edition = "2021" - -[dependencies] -serde_json = "1" diff --git a/crates/marqdo-plugin-sdk/src/lib.rs b/crates/marqdo-plugin-sdk/src/lib.rs deleted file mode 100755 index f4e9bd6..0000000 --- a/crates/marqdo-plugin-sdk/src/lib.rs +++ /dev/null @@ -1,195 +0,0 @@ -//! Shared ABI plumbing for Marqdo native plugins (`` slimming). -//! -//! Every plugin used to copy the same `MarqdoHostApi` struct, the alloc/free -//! statics, `host_strdup`, `set_out`/`set_err`, `parse_args` and `reply` -//! (about 140 lines each × 5 crates). This crate holds the single copy; the -//! `marqdo_plugin!` macro emits the `#[no_mangle]` exports each `.so` needs. -//! -//! The ABI itself is unchanged: `include/marqdo_abi.h` and the host loader -//! (`src/host/plugin.rs`) still see exactly the same symbols and layout. - -use std::ffi::{CStr, CString}; -use std::os::raw::{c_char, c_int, c_void}; -use std::ptr; - -pub use serde_json::{json, Value}; - -/// Highest ABI version this SDK speaks. -pub const ABI_VERSION: u32 = 2; - -pub type PluginFn = unsafe extern "C" fn( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int; - -pub type HostQueryFn = unsafe extern "C" fn( - userdata: *mut c_void, - name: *const c_char, - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int; - -#[repr(C)] -pub struct MarqdoHostApi { - pub userdata: *mut c_void, - pub register_fn: Option< - unsafe extern "C" fn( - userdata: *mut c_void, - name: *const c_char, - params: *const c_char, - fn_ptr: PluginFn, - ) -> c_int, - >, - pub alloc: Option *mut c_void>, - pub free: Option, - pub host_query: Option, -} - -pub static mut HOST_FREE: Option = None; -pub static mut HOST_ALLOC: Option *mut c_void> = None; -pub static mut HOST_QUERY: Option = None; -pub static mut HOST_USERDATA: *mut c_void = ptr::null_mut(); - -/// Duplicate `s` into host-allocated memory (the host frees it). -pub unsafe fn host_strdup(s: &str) -> *mut c_char { - let alloc = HOST_ALLOC.expect("host alloc"); - let bytes = s.as_bytes(); - let p = alloc(bytes.len() + 1) as *mut u8; - if p.is_null() { - return ptr::null_mut(); - } - std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); - *p.add(bytes.len()) = 0; - p as *mut c_char -} - -pub fn set_out(out: *mut *mut c_char, s: &str) { - if out.is_null() { - return; - } - unsafe { - *out = host_strdup(s); - } -} - -pub fn set_err(err: *mut *mut c_char, s: &str) { - if err.is_null() { - return; - } - unsafe { - *err = host_strdup(s); - } -} - -/// Parse the JSON args object handed to a plugin entry point. -pub fn parse_args(args_json: *const c_char) -> Result { - if args_json.is_null() { - return Ok(json!({})); - } - let s = unsafe { CStr::from_ptr(args_json) } - .to_str() - .map_err(|_| "args not utf-8".to_string())?; - if s.trim().is_empty() { - return Ok(json!({})); - } - serde_json::from_str(s).map_err(|e| e.to_string()) -} - -/// Write a plugin result (or error) back through the ABI pointers. -pub fn reply(out_json: *mut *mut c_char, err_msg: *mut *mut c_char, r: Result) -> c_int { - match r { - Ok(v) => { - set_out(out_json, &v.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &e); - 1 - } - } -} - -/// Ask the host for a builtin with no arguments (`host_query`). -pub fn host_query_json(name: &str) -> Result { - host_query_json_with(name, &json!({})) -} - -/// Ask the host for a builtin, passing `args` as its argument object. -pub fn host_query_json_with(name: &str, args: &Value) -> Result { - let q = unsafe { HOST_QUERY }.ok_or("host_query unavailable")?; - let n = CString::new(name).map_err(|e| e.to_string())?; - let a = CString::new(args.to_string()).map_err(|e| e.to_string())?; - let mut out: *mut c_char = ptr::null_mut(); - let mut err: *mut c_char = ptr::null_mut(); - let rc = unsafe { q(HOST_USERDATA, n.as_ptr(), a.as_ptr(), &mut out, &mut err) }; - if rc != 0 { - return Err(take_host_string(err).unwrap_or_else(|| "host_query failed".into())); - } - let text = take_host_string(out).ok_or("host_query returned nothing")?; - serde_json::from_str(&text).map_err(|e| e.to_string()) -} - -/// Copy a host-allocated C string into a Rust `String` and free the original. -pub fn take_host_string(p: *mut c_char) -> Option { - if p.is_null() { - return None; - } - let s = unsafe { CStr::from_ptr(p) } - .to_string_lossy() - .into_owned(); - if let Some(free) = unsafe { HOST_FREE } { - unsafe { free(p as *mut c_void) }; - } - Some(s) -} - -fn register(host: &MarqdoHostApi, name: &str, params: &str, f: PluginFn) -> c_int { - let Some(reg) = host.register_fn else { - return 1; - }; - let n = CString::new(name).unwrap(); - let p = CString::new(params).unwrap(); - unsafe { reg(host.userdata, n.as_ptr(), p.as_ptr(), f) } -} - -/// Store the host callbacks and register every entry point. -pub unsafe fn init_plugin(host: *const MarqdoHostApi, regs: &[(&str, &str, PluginFn)]) -> c_int { - if host.is_null() { - return 1; - } - let host = &*host; - HOST_ALLOC = host.alloc; - HOST_FREE = host.free; - HOST_QUERY = host.host_query; - HOST_USERDATA = host.userdata; - for (name, params, f) in regs { - if register(host, name, params, *f) != 0 { - return 1; - } - } - 0 -} - -/// Emit the four `#[no_mangle]` exports every plugin `.so` must provide, -/// wiring `marqdo_plugin_init` to the given registration table. -#[macro_export] -macro_rules! marqdo_plugin { - ($version:expr, [ $( ($name:expr, $params:expr, $f:expr) ),* $(,)? ]) => { - #[no_mangle] - pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 { - $version - } - - #[no_mangle] - pub unsafe extern "C" fn marqdo_plugin_shutdown() {} - - #[no_mangle] - pub unsafe extern "C" fn marqdo_plugin_init( - host: *const $crate::MarqdoHostApi, - ) -> i32 { - $crate::init_plugin(host, &[ $( ($name, $params, $f as $crate::PluginFn) ),* ]) - } - }; -} diff --git a/crates/marqdo-wasm/Cargo.toml b/crates/marqdo-wasm/Cargo.toml deleted file mode 100644 index b49a8e3..0000000 --- a/crates/marqdo-wasm/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "marqdo-wasm" -version = "2.9.1" -edition = "2021" -license = "Apache-2.0" -description = "Marqdo interpreter as WebAssembly (browser host bridge)" -repository = "https://github.com/cflmy/marqdo" -publish = false - -[lib] -crate-type = ["cdylib", "rlib"] - -[dependencies] -marqdo = { path = "../..", default-features = false, features = ["wasm-core"] } -serde_json = "1" diff --git a/crates/marqdo-wasm/README.md b/crates/marqdo-wasm/README.md deleted file mode 100755 index 41cb1aa..0000000 --- a/crates/marqdo-wasm/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Marqdo browser WASM (route C) - -Raw `cdylib` exports — no `wasm-bindgen` CLI required. - -| Export | Role | -|--------|------| -| `mq_alloc` / `mq_dealloc` | linear memory | -| `mq_run` | one-shot `# main` (C1) | -| `mq_boot` / `mq_call` | session + handlers (C3) | -| `mq_version` | version C string | - -```bash -# from repo root (C5 size profile) -marqdo call skills/marqdo-dev/index.mq.md build_browser --effects plugin,process.exec,fs.write --fs-root . --json -# or: -cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-wasm -``` - -Prints size in KiB; runs `wasm-opt -Oz` when Binaryen is on `PATH`. - -See [doc/design/browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md). - -Use the maintained [browser-app](../../examples/browser-app/index.mq.md) for a runnable native Document and browser program. The ABI counter fixture lives in tests/wasm/counter.mq.md, with no independent HTML demo host. The former browser-hello and browser-media directories were retired in 2.7.0; their host capabilities remain documented in lib/browser.mq.md. diff --git a/crates/marqdo-wasm/js/marqdo-bridge.js b/crates/marqdo-wasm/js/marqdo-bridge.js deleted file mode 100755 index d24d1c6..0000000 --- a/crates/marqdo-wasm/js/marqdo-bridge.js +++ /dev/null @@ -1,1460 +0,0 @@ -/** - * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. - * Authors write .mq.md only; this file may grow host mechanisms freely. - * - * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, - * focus, blur, scroll_into, set_html, replace_children, render_list, - * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval - */ - -export function readCString(memory, ptr) { - const bytes = new Uint8Array(memory.buffer); - let end = ptr; - while (bytes[end] !== 0) end += 1; - return new TextDecoder().decode(bytes.subarray(ptr, end)); -} - -function decodePacked(exports, outPtr) { - if (!outPtr) throw new Error("null wasm result pointer"); - const view = new DataView(exports.memory.buffer); - const jsonLen = view.getUint32(outPtr, true); - const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen); - const text = new TextDecoder().decode(jsonBytes); - exports.mq_dealloc(outPtr, 4 + jsonLen); - return JSON.parse(text); -} - -function writeUtf8(exports, text) { - const encoded = new TextEncoder().encode(text); - const ptr = exports.mq_alloc(encoded.length || 1); - if (!ptr) throw new Error("mq_alloc failed"); - new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded); - return { ptr, len: encoded.length }; -} - -export function runSource(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_run(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function boot(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_boot(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function call(exports, name, argsObj = {}) { - const n = writeUtf8(exports, name); - const a = writeUtf8(exports, JSON.stringify(argsObj ?? {})); - const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len); - exports.mq_dealloc(n.ptr, n.len || 1); - exports.mq_dealloc(a.ptr, a.len || 1); - return decodePacked(exports, outPtr); -} - -export async function loadWasm(url = "./marqdo_wasm.wasm") { - const res = await fetch(url); - if (!res.ok) { - throw new Error( - `failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`, - ); - } - const { instance } = await WebAssembly.instantiateStreaming(res, {}); - return instance.exports; -} - -function isPlainObject(v) { - return v != null && typeof v === "object" && !Array.isArray(v); -} - -function asSelList(v) { - if (v == null) return []; - if (Array.isArray(v)) return v.map(String); - return [String(v)]; -} - -/** Normalize mount options from plain object or DOM dataset. */ -export function normalizeMountOptions(raw = {}) { - const o = raw && typeof raw === "object" ? raw : {}; - const dataset = o.dataset || {}; - const wasmUrl = - o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; - const sourceUrl = - o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; - let source = o.source != null ? o.source : dataset.mqSource || ""; - if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; - const ready = o.ready || o.readySel || dataset.mqReady || ""; - const enable = o.enable || dataset.mqEnable || ""; - const noBoot = - o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; - return { - wasmUrl: String(wasmUrl), - sourceUrl: sourceUrl ? String(sourceUrl) : "", - source: source ? String(source) : "", - playground: playground ? String(playground) : "", - ready: ready ? String(ready) : "", - enable: enable ? String(enable) : "", - noBoot, - onError: typeof o.onError === "function" ? o.onError : null, - }; -} - -export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { - if (!doc) return []; - const out = []; - const bootEl = doc.getElementById("marqdo-boot"); - if (bootEl) { - try { - out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); - } catch (e) { - console.error("marqdo-boot JSON:", e); - } - } - const scripts = doc.querySelectorAll( - "script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]", - ); - for (const el of scripts) { - if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; - const hasWork = - el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; - if (!hasWork) continue; - out.push( - normalizeMountOptions({ - dataset: el.dataset, - wasmUrl: el.dataset.mqWasm, - sourceUrl: el.dataset.mqSourceUrl, - source: el.dataset.mqSource, - playground: el.dataset.mqPlayground, - ready: el.dataset.mqReady, - enable: el.dataset.mqEnable, - }), - ); - } - return out; -} - -export function eventArgsFromDom(ev, valueFromSel) { - const t = ev && ev.target; - const args = { event: ev && ev.type ? ev.type : "click" }; - if (t && typeof t === "object") { - if ("value" in t && t.value != null && t.type !== "file") args.value = String(t.value); - if ("checked" in t) args.checked = !!t.checked; - if (t.id) args.id = String(t.id); - if (t.getAttribute) { - const did = t.getAttribute("data-id"); - if (did != null) args.data_id = did; - const drag = t.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - if (typeof t.textContent === "string" && !("value" in t)) { - args.text = t.textContent; - } - if (ev.key != null) args.key = String(ev.key); - if (ev.code != null) args.code = String(ev.code); - if (t.files && t.files.length) { - const f = t.files[0]; - args.file_name = f.name; - args.file_size = f.size; - args.file_type = f.type || ""; - args.file_count = t.files.length; - } - } - if (ev && ev.type === "popstate") { - args.url = typeof location !== "undefined" ? location.href : ""; - args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; - args.state = ev.state; - } - if (ev && ev.dataTransfer) { - try { - const txt = ev.dataTransfer.getData("text") || ev.dataTransfer.getData("text/plain"); - if (txt) args.drop_text = txt; - } catch (_) { - /* ignore */ - } - } - if (valueFromSel && typeof document !== "undefined") { - const src = document.querySelector(valueFromSel); - if (src) { - if ("value" in src && src.type !== "file") args.value = String(src.value); - else args.value = src.textContent != null ? String(src.textContent) : ""; - } - } - if (ev && ev.type === "submit" && t) { - const form = typeof t.closest === "function" ? t.closest("form") : t; - if (form && typeof FormData !== "undefined") { - try { - ev.preventDefault(); - } catch (_) { - /* ignore */ - } - const fields = {}; - for (const [k, v] of new FormData(form)) fields[k] = String(v); - args.fields = fields; - } - } - if (ev && (ev.type === "scroll" || ev.type === "resize")) { - try { - const doc = typeof document !== "undefined" ? document.documentElement : null; - const body = typeof document !== "undefined" ? document.body : null; - const scrollTop = (doc && (doc.scrollTop || 0)) || (body && body.scrollTop) || 0; - const height = doc ? (doc.scrollHeight - doc.clientHeight) || 1 : 1; - const ratio = Math.max(0, Math.min(1, scrollTop / height)); - args.scroll_top = scrollTop; - args.scroll_max = height; - args.scroll_ratio = ratio; - } catch (_) { - /* ignore */ - } - } - return args; -} - -function applyStyle(el, styleVal) { - if (typeof styleVal === "string") { - el.setAttribute("style", styleVal); - return; - } - if (isPlainObject(styleVal)) { - for (const [k, v] of Object.entries(styleVal)) { - if (v === null || v === false) el.style.removeProperty(k); - else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); - } - } -} - -export function renderListItems(spec) { - const rootTag = String(spec.tag || "li"); - const items = Array.isArray(spec.items) ? spec.items : []; - let count = 0; - const render = (item, fallbackTag, depth) => { - if (depth > 32 || ++count > 10000) throw new Error("render_list: structural limit exceeded"); - if (item == null) return ""; - if (typeof item !== "string" && typeof item !== "number" && !isPlainObject(item)) return ""; - const record = isPlainObject(item) ? item : { text: String(item) }; - const tag = String(record.tag || fallbackTag); - if (!/^[a-z][a-z0-9-]*$/i.test(tag) || - /^(script|style|iframe|object|embed|link|meta|base)$/i.test(tag)) { - throw new Error("render_list: unsupported element name"); - } - let attrs = record.class != null ? ` class="${escapeAttr(String(record.class))}"` : ""; - if (isPlainObject(record.attrs)) { - for (const [key, value] of Object.entries(record.attrs)) { - if (!/^[a-z_:][a-z0-9_.:-]*$/i.test(key) || /^on/i.test(key)) { - throw new Error("render_list: invalid attribute name"); - } - if (value === null || value === false) continue; - if (!["string", "number", "boolean"].includes(typeof value)) throw new Error("render_list: attributes must be scalar"); - if (/^(href|src|action|formaction)$/i.test(key) && - /^[\s\u0000-\u0020]*(javascript|vbscript|data)[\s\u0000-\u0020]*:/i.test(String(value))) { - throw new Error("render_list: unsupported URL"); - } - attrs += ` ${key}="${escapeAttr(String(value))}"`; - } - } - let inner; - if (record.children != null) { - if (!Array.isArray(record.children) || record.text != null || record.html != null) { - throw new Error("render_list: children must be an unambiguous record list"); - } - inner = record.children.map(child => render(child, "span", depth + 1)).join(""); - } else { - // Preserve the existing explicit HTML escape hatch. Ordinary business - // values use text/children and never become source or markup. - inner = record.html != null ? String(record.html) : escapeHtml(String(record.text ?? "")); - } - if (/^(input|img|br|hr|area|col|source|wbr)$/i.test(tag)) { - if (inner) throw new Error("render_list: void elements cannot have content"); - return `<${tag}${attrs}>`; - } - return `<${tag}${attrs}>${inner}`; - }; - return items.map(item => render(item, rootTag, 0)).join(""); -} - -function escapeHtml(s) { - return s - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """); -} - -function escapeAttr(s) { - return escapeHtml(s).replace(/'/g, "'"); -} - -function qsAll(sel) { - if (typeof document === "undefined") return []; - try { - return [...document.querySelectorAll(sel)]; - } catch (_) { - return []; - } -} - -function qsOne(sel) { - const all = qsAll(sel); - return all[0] || null; -} - -/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ -export function applyDomPatch(value) { - if (!value || typeof value !== "object") return; - if (typeof document === "undefined") return; - - const setText = value.set_text || value.setText; - if (isPlainObject(setText)) { - for (const [sel, text] of Object.entries(setText)) { - for (const el of qsAll(sel)) el.textContent = String(text); - } - } - - const setValue = value.set_value || value.setValue; - if (isPlainObject(setValue)) { - for (const [sel, v] of Object.entries(setValue)) { - for (const el of qsAll(sel)) { - if ("value" in el) el.value = String(v); - } - } - } - - const setAttr = value.set_attr || value.setAttr; - if (isPlainObject(setAttr)) { - for (const [sel, attrs] of Object.entries(setAttr)) { - if (!isPlainObject(attrs)) continue; - for (const el of qsAll(sel)) { - for (const [name, raw] of Object.entries(attrs)) { - if (raw === null || raw === false) el.removeAttribute(name); - else el.setAttribute(name, String(raw)); - } - } - } - } - - const setClass = value.set_class || value.setClass; - if (isPlainObject(setClass)) { - for (const [sel, cls] of Object.entries(setClass)) { - for (const el of qsAll(sel)) el.className = String(cls); - } - } - - const addClass = value.add_class || value.addClass; - if (isPlainObject(addClass)) { - for (const [sel, cls] of Object.entries(addClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.add(c); - } - } - - const removeClass = value.remove_class || value.removeClass; - if (isPlainObject(removeClass)) { - for (const [sel, cls] of Object.entries(removeClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.remove(c); - } - } - - const toggleClass = value.toggle_class || value.toggleClass; - if (isPlainObject(toggleClass)) { - for (const [sel, cls] of Object.entries(toggleClass)) { - for (const el of qsAll(sel)) { - if (cls) el.classList.toggle(String(cls)); - } - } - } - - const setStyle = value.set_style || value.setStyle; - if (isPlainObject(setStyle)) { - for (const [sel, st] of Object.entries(setStyle)) { - for (const el of qsAll(sel)) applyStyle(el, st); - } - } - - for (const sel of asSelList(value.focus)) { - const el = qsOne(sel); - if (el && el.focus) el.focus(); - } - for (const sel of asSelList(value.blur)) { - const el = qsOne(sel); - if (el && el.blur) el.blur(); - } - for (const sel of asSelList(value.scroll_into || value.scrollInto)) { - const el = qsOne(sel); - if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); - } - - const setHtml = value.set_html || value.setHtml; - if (isPlainObject(setHtml)) { - for (const [sel, html] of Object.entries(setHtml)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const appendHtml = value.append_html || value.appendHtml; - if (isPlainObject(appendHtml)) { - for (const [sel, html] of Object.entries(appendHtml)) { - for (const el of qsAll(sel)) el.insertAdjacentHTML("beforeend", String(html)); - } - } - - const replaceChildren = value.replace_children || value.replaceChildren; - if (isPlainObject(replaceChildren)) { - for (const [sel, html] of Object.entries(replaceChildren)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const renderList = value.render_list || value.renderList; - if (isPlainObject(renderList)) { - for (const [sel, spec] of Object.entries(renderList)) { - if (!isPlainObject(spec)) continue; - const html = renderListItems(spec); - for (const el of qsAll(sel)) el.innerHTML = html; - } - } - - const removeSel = value.remove || value.remove_nodes || value.removeNodes; - if (removeSel) { - for (const sel of asSelList(removeSel)) { - for (const el of qsAll(sel)) el.remove(); - } - } - - const nav = value.navigate; - if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { - const url = String(nav.url); - if (nav.replace) history.replaceState(nav.state ?? null, "", url); - else history.pushState(nav.state ?? null, "", url); - } - - const clip = value.clipboard || value.copy; - if (clip != null && typeof navigator !== "undefined" && navigator.clipboard?.writeText) { - const text = isPlainObject(clip) ? String(clip.text ?? "") : String(clip); - navigator.clipboard.writeText(text).catch(() => {}); - } - - const dl = value.download; - if (isPlainObject(dl) && dl.body != null) { - const mime = String(dl.mime || "text/plain;charset=utf-8"); - const name = String(dl.filename || "download.txt"); - const blob = new Blob([String(dl.body)], { type: mime }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = name; - a.click(); - URL.revokeObjectURL(url); - } - - const canvasSpec = value.canvas; - if (isPlainObject(canvasSpec) && canvasSpec.sel) { - runCanvasCommands(canvasSpec); - } - - const audioSpec = value.audio; - if (isPlainObject(audioSpec) && audioSpec.op) { - runAudioEffect(audioSpec); - } -} - -const intervalHandles = new Map(); -const wsHandles = new Map(); -const audioHandles = new Map(); -const observeHandles = new Map(); -let wsSeq = 0; -let observeSeq = 0; - -/** @param {{ sel: string, commands?: object[], clear?: boolean }} spec */ -export function runCanvasCommands(spec) { - if (typeof document === "undefined") return; - const el = qsOne(String(spec.sel)); - if (!el || typeof el.getContext !== "function") return; - const ctx = el.getContext("2d"); - if (!ctx) return; - if (spec.clear) ctx.clearRect(0, 0, el.width || 0, el.height || 0); - const cmds = Array.isArray(spec.commands) - ? spec.commands - : isPlainObject(spec.commands) - ? Object.keys(spec.commands) - .sort() - .map((k) => spec.commands[k]) - : []; - for (const raw of cmds) { - if (!isPlainObject(raw)) continue; - const op = String(raw.op || raw.cmd || "").toLowerCase(); - try { - if (op === "clear" || op === "clearrect") { - ctx.clearRect( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? el.width) || 0, - Number(raw.h ?? raw.height ?? el.height) || 0, - ); - } else if (op === "fillstyle") { - ctx.fillStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "strokestyle") { - ctx.strokeStyle = String(raw.value ?? raw.color ?? "#000"); - } else if (op === "linewidth") { - ctx.lineWidth = Number(raw.value ?? raw.width) || 1; - } else if (op === "font") { - ctx.font = String(raw.value || "16px sans-serif"); - } else if (op === "fillrect") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "strokerect") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.strokeRect(Number(raw.x) || 0, Number(raw.y) || 0, Number(raw.w ?? raw.width) || 0, Number(raw.h ?? raw.height) || 0); - } else if (op === "beginpath") { - ctx.beginPath(); - } else if (op === "closepath") { - ctx.closePath(); - } else if (op === "moveto") { - ctx.moveTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "lineto") { - ctx.lineTo(Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "arc") { - ctx.arc( - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.r ?? raw.radius) || 0, - Number(raw.start ?? 0), - Number(raw.end ?? Math.PI * 2), - !!raw.ccw, - ); - } else if (op === "stroke") { - if (raw.stroke != null) ctx.strokeStyle = String(raw.stroke); - ctx.stroke(); - } else if (op === "fill") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fill(); - } else if (op === "filltext") { - if (raw.fill != null) ctx.fillStyle = String(raw.fill); - ctx.fillText(String(raw.text ?? ""), Number(raw.x) || 0, Number(raw.y) || 0); - } else if (op === "drawimage" && raw.src) { - const img = new Image(); - img.src = String(raw.src); - // sync only if already loaded; else fire-and-forget draw on load - const draw = () => { - ctx.drawImage( - img, - Number(raw.x) || 0, - Number(raw.y) || 0, - Number(raw.w ?? raw.width ?? img.width) || img.width, - Number(raw.h ?? raw.height ?? img.height) || img.height, - ); - }; - if (img.complete) draw(); - else img.onload = draw; - } - } catch (_) { - /* skip bad cmd */ - } - } -} - -function runAudioEffect(spec) { - const op = String(spec.op || "").toLowerCase(); - const id = String(spec.id || spec.sel || "default"); - try { - if (op === "play") { - // Optional beep via Web Audio (no external file). - if (spec.freq != null || spec.frequency != null || String(spec.src || "") === "beep") { - const AC = window.AudioContext || window.webkitAudioContext; - if (!AC) return; - let ctx = audioHandles.get(`${id}:ctx`); - if (!ctx) { - ctx = new AC(); - audioHandles.set(`${id}:ctx`, ctx); - } - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = String(spec.wave || "sine"); - osc.frequency.value = Number(spec.freq ?? spec.frequency ?? 440); - const vol = spec.volume != null ? Math.min(1, Math.max(0, Number(spec.volume))) : 0.15; - gain.gain.value = vol; - osc.connect(gain); - gain.connect(ctx.destination); - const dur = Number(spec.ms ?? spec.duration ?? 280) / 1000; - osc.start(); - gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + Math.max(0.05, dur)); - osc.stop(ctx.currentTime + Math.max(0.05, dur) + 0.02); - return; - } - let audio = audioHandles.get(id); - if (spec.sel) { - const el = qsOne(String(spec.sel)); - if (el && el.tagName === "AUDIO") audio = el; - } - if (!audio) { - audio = new Audio(spec.src != null ? String(spec.src) : undefined); - audioHandles.set(id, audio); - } else if (spec.src != null) { - audio.src = String(spec.src); - } - if (spec.volume != null) audio.volume = Math.min(1, Math.max(0, Number(spec.volume))); - if (spec.loop != null) audio.loop = !!spec.loop; - const p = audio.play(); - if (p && p.catch) p.catch(() => {}); - return; - } - const audio = spec.sel ? qsOne(String(spec.sel)) : audioHandles.get(id); - if (!audio) return; - if (op === "pause") audio.pause(); - else if (op === "stop") { - audio.pause(); - try { - audio.currentTime = 0; - } catch (_) { - /* ignore */ - } - } - } catch (_) { - /* ignore */ - } -} - -/** - * Run sync DOM patches then schedule async effects. - */ -export function applyEffects(exports, value, { onError } = {}) { - applyDomPatch(value); - if (!value || typeof value !== "object") return Promise.resolve(); - - const tasks = []; - - const fetchSpec = value.fetch; - if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) { - tasks.push(runFetchEffect(exports, fetchSpec, onError)); - } - - const fetchAll = value.fetch_all || value.fetchAll; - if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { - tasks.push(runFetchAllEffect(exports, fetchAll, onError)); - } - - const afterSpec = value.after; - if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { - tasks.push(runAfterEffect(exports, afterSpec, onError)); - } - - const intervalSpec = value.interval; - if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { - runIntervalEffect(exports, intervalSpec, onError); - } - - const clearIv = value.clear_interval || value.clearInterval; - if (clearIv && typeof clearIv === "object") { - const id = String(clearIv.id || "default"); - const h = intervalHandles.get(id); - if (h != null) { - clearInterval(h); - intervalHandles.delete(id); - } - } - - const storageSpec = value.storage; - if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { - tasks.push(runStorageEffect(exports, storageSpec, onError)); - } - - const wsSpec = value.ws; - if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { - tasks.push(runWsEffect(exports, wsSpec, onError)); - } - - const readFile = value.read_file || value.readFile; - if (readFile && typeof readFile === "object" && readFile.then) { - tasks.push(runReadFileEffect(exports, readFile, onError)); - } - - const observe = value.observe; - if (observe) { - const specs = Array.isArray(observe) - ? observe - : observe && typeof observe === "object" && observe.then - ? [observe] - : []; - for (const spec of specs) runObserveEffect(exports, spec, onError); - } - - const unobserve = value.unobserve; - if (unobserve) { - const specs = Array.isArray(unobserve) - ? unobserve - : unobserve && typeof unobserve === "object" - ? [unobserve] - : []; - for (const spec of specs) { - const id = String(spec.id || ""); - const h = observeHandles.get(id); - if (h) { - try { - h.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - } - } - - return Promise.all(tasks); -} - -async function runReadFileEffect(exports, spec, onError) { - const thenFn = spec.then; - const sel = String(spec.sel || ""); - const as = String(spec.as || "text").toLowerCase(); - const input = qsOne(sel); - if (!input || !input.files || !input.files.length) { - const result = call(exports, thenFn, { ok: false, error: "no file", sel }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - return; - } - const file = input.files[Number(spec.index) || 0]; - try { - let body = ""; - let data_url = ""; - if (as === "data_url" || as === "dataurl") { - data_url = await new Promise((resolve, reject) => { - const r = new FileReader(); - r.onload = () => resolve(String(r.result || "")); - r.onerror = () => reject(r.error || new Error("read failed")); - r.readAsDataURL(file); - }); - } else { - body = await file.text(); - } - const result = call(exports, thenFn, { - ok: true, - name: file.name, - size: file.size, - type: file.type || "", - body, - data_url, - as, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - try { - const result = call(exports, thenFn, { ok: false, error: String(e), name: file.name }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - } - } -} - -function runObserveEffect(exports, spec, onError) { - const kind = String(spec.kind || spec.type || "intersect").toLowerCase(); - const sel = String(spec.sel || ""); - const thenFn = spec.then; - const baseId = String(spec.id || `obs${++observeSeq}`); - const nodes = qsAll(sel); - if (!nodes.length || (!thenFn && !spec.add_class)) return; - - nodes.forEach((el, idx) => { - const id = nodes.length === 1 ? baseId : `${baseId}_${idx}`; - const prev = observeHandles.get(id); - if (prev) { - try { - prev.disconnect(); - } catch (_) { - /* ignore */ - } - } - - const fire = (payload) => { - try { - const result = call(exports, thenFn, payload); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }; - - if (kind === "resize" && typeof ResizeObserver !== "undefined") { - const ro = new ResizeObserver((entries) => { - const en = entries[0]; - const cr = en?.contentRect; - fire({ - ok: true, - kind: "resize", - id, - width: cr ? cr.width : 0, - height: cr ? cr.height : 0, - }); - }); - ro.observe(el); - observeHandles.set(id, ro); - return; - } - - if (typeof IntersectionObserver !== "undefined") { - const opts = { threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 }; - if (spec.rootMargin != null) opts.rootMargin = String(spec.rootMargin); - const io = new IntersectionObserver( - (entries) => { - const en = entries[0]; - if (!en) return; - if (en.isIntersecting && spec.add_class) { - for (const c of String(spec.add_class).split(/\s+/).filter(Boolean)) { - el.classList.add(c); - } - } - if (thenFn) { - fire({ - ok: true, - kind: "intersect", - id, - intersecting: !!en.isIntersecting, - ratio: en.intersectionRatio, - target_id: el.id || "", - }); - } - if (spec.once && en.isIntersecting) { - try { - io.disconnect(); - } catch (_) { - /* ignore */ - } - observeHandles.delete(id); - } - }, - opts, - ); - io.observe(el); - observeHandles.set(id, io); - } - }); -} - -function buildFetchInit(spec) { - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; - if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { - const fd = new FormData(); - for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); - init.body = fd; - } else if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } - return init; -} - -async function runFetchEffect(exports, spec, onError) { - const thenFn = spec.then; - try { - const res = await fetch(String(spec.url), buildFetchInit(spec)); - const body = await res.text(); - const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - try { - const result = call(exports, thenFn, { - ok: false, - status: 0, - body: "", - error: String(e), - }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - else console.error(e2); - } - } -} - -async function runFetchAllEffect(exports, spec, onError) { - const thenFn = spec.then; - const reqs = Array.isArray(spec.requests) - ? spec.requests - : isPlainObject(spec.requests) - ? Object.keys(spec.requests) - .sort() - .map((k) => spec.requests[k]) - .filter((r) => r && typeof r === "object") - : []; - try { - const results = await Promise.all( - reqs.map(async (r) => { - try { - const res = await fetch(String(r.url), buildFetchInit(r)); - const body = await res.text(); - return { ok: res.ok, status: res.status, body, url: String(r.url) }; - } catch (e) { - return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; - } - }), - ); - const result = call(exports, thenFn, { ok: true, results }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runAfterEffect(exports, spec, onError) { - const ms = Math.max(0, Number(spec.ms) || 0); - const thenFn = spec.then; - return new Promise((resolve) => { - setTimeout(() => { - try { - const result = call(exports, thenFn, { ok: true }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - resolve(); - return; - } - Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - resolve(); - } - }, ms); - }); -} - -function runIntervalEffect(exports, spec, onError) { - const ms = Math.max(1, Number(spec.ms) || 1000); - const thenFn = spec.then; - const id = String(spec.id || "default"); - if (intervalHandles.has(id)) { - clearInterval(intervalHandles.get(id)); - intervalHandles.delete(id); - } - const handle = setInterval(() => { - try { - const result = call(exports, thenFn, { ok: true, id }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }, ms); - intervalHandles.set(id, handle); -} - -const memoryKV = new Map(); - -function storageStore(scope) { - if (scope === "cookie") return null; - if (scope === "memory" || scope === "mem" || scope === "内存") { - return { - getItem(key) { - return memoryKV.has(key) ? memoryKV.get(key) : null; - }, - setItem(key, value) { - memoryKV.set(key, String(value)); - }, - removeItem(key) { - memoryKV.delete(key); - }, - }; - } - if (typeof localStorage === "undefined") return null; - return scope === "session" ? sessionStorage : localStorage; -} - -function cookieGet(key) { - if (typeof document === "undefined") return null; - const prefix = encodeURIComponent(key) + "="; - for (const part of document.cookie.split(";")) { - const s = part.trim(); - if (s.startsWith(prefix)) return decodeURIComponent(s.slice(prefix.length)); - } - return null; -} - -function cookieSet(key, value, days) { - if (typeof document === "undefined") return; - let extra = "; path=/"; - if (days != null && Number(days) > 0) { - const d = new Date(); - d.setTime(d.getTime() + Number(days) * 864e5); - extra += "; expires=" + d.toUTCString(); - } - document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + extra; -} - -function cookieRemove(key) { - if (typeof document === "undefined") return; - document.cookie = encodeURIComponent(key) + "=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; -} - -async function runStorageEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - const key = String(spec.key || ""); - const scope = String(spec.scope || "local"); - try { - if (scope === "cookie") { - if (op === "set") { - cookieSet(key, spec.value != null ? String(spec.value) : "", spec.days); - } else if (op === "remove" || op === "delete") { - cookieRemove(key); - } else if (op === "get") { - const value = cookieGet(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - return; - } - if (spec.then && op !== "get") { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - - const store = storageStore(scope); - if (!store) { - if (onError) onError("storage unavailable"); - return; - } - if (op === "set") { - store.setItem(key, spec.value != null ? String(spec.value) : ""); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "remove" || op === "delete") { - store.removeItem(key); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "get") { - const value = store.getItem(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - } - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runWsEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - return new Promise((resolve) => { - try { - if (op === "open") { - if (typeof WebSocket === "undefined") { - if (onError) onError("WebSocket unavailable"); - resolve(); - return; - } - const id = String(spec.id || `ws${++wsSeq}`); - const sock = new WebSocket(String(spec.url)); - wsHandles.set(id, sock); - sock.addEventListener("open", () => { - if (spec.then_open || spec.thenOpen) { - try { - const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - resolve(); - }); - sock.addEventListener("message", (ev) => { - const thenMsg = spec.then_message || spec.thenMessage; - if (!thenMsg) return; - try { - const result = call(exports, thenMsg, { - ok: true, - id, - data: typeof ev.data === "string" ? ev.data : String(ev.data), - }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }); - sock.addEventListener("close", () => { - wsHandles.delete(id); - const thenClose = spec.then_close || spec.thenClose; - if (thenClose) { - try { - const result = call(exports, thenClose, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - sock.addEventListener("error", () => { - const thenErr = spec.then_error || spec.thenError; - if (thenErr) { - try { - const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - return; - } - if (op === "send") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock && sock.readyState === WebSocket.OPEN) { - sock.send(spec.data != null ? String(spec.data) : ""); - } else if (onError) onError(`ws send: no open socket ${id}`); - resolve(); - return; - } - if (op === "close") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock) sock.close(); - wsHandles.delete(id); - resolve(); - return; - } - resolve(); - } catch (e) { - if (onError) onError(String(e)); - resolve(); - } - }); -} - -function bindTarget(sel) { - if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; - if (sel === "document" || sel === "@document") - return typeof document !== "undefined" ? document : null; - return null; -} - -/** - * Wire events from `# main` return value (list or `{ wire: [...] }`). - */ -export function wireEvents(exports, bootValue, { onError } = {}) { - let rows = []; - if (Array.isArray(bootValue)) rows = bootValue; - else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire; - - for (const row of rows) { - const sel = row["选择器"] || row.selector || row.sel; - const ev = row["事件"] || row.event || "click"; - const fn = row["调用"] || row.call || row.fn; - const valueFrom = - row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; - const delegate = - row["委托"] || row.delegate || row.delegation || ""; - if (!sel || !fn) continue; - - const special = bindTarget(sel); - const roots = special - ? [special] - : typeof document !== "undefined" - ? [...document.querySelectorAll(sel)] - : []; - - roots.forEach((node) => { - node.addEventListener(ev, (domEv) => { - try { - if (delegate) { - const hit = - typeof domEv.target?.closest === "function" - ? domEv.target.closest(delegate) - : null; - if (!hit || (node.contains && !node.contains(hit))) return; - } - // Drag/drop hosts need preventDefault on dragover/drop; dragstart can set payload. - if ( - ev === "dragover" || - ev === "dragenter" || - ev === "drop" || - ev === "dragstart" - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - if (ev === "dragstart" && domEv.dataTransfer) { - try { - const payload = - (domEv.target && - typeof domEv.target.getAttribute === "function" && - domEv.target.getAttribute("data-drag")) || - (typeof domEv.target?.textContent === "string" - ? domEv.target.textContent.trim() - : "") || - ""; - if (payload) { - domEv.dataTransfer.setData("text/plain", payload); - domEv.dataTransfer.setData("text", payload); - domEv.dataTransfer.effectAllowed = "copyMove"; - } - } catch (_) { - /* ignore */ - } - } - if ( - ev === "click" && - typeof domEv.target?.closest === "function" && - domEv.target.closest("a[href]") - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - const args = eventArgsFromDom(domEv, valueFrom); - if (delegate && domEv.target) { - const hit = domEv.target.closest?.(delegate); - if (hit?.getAttribute) { - const did = hit.getAttribute("data-id"); - if (did != null) args.data_id = did; - if (hit.id) args.id = hit.id; - const drag = hit.getAttribute("data-drag"); - if (drag != null) args.drag = drag; - } - } - const result = call(exports, fn, args); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }); - }); - } - return rows.length; -} - -function markReady(opts, message) { - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.remove?.("err"); - el.textContent = message; - } - } - if (opts.enable && typeof document !== "undefined") { - for (const sel of String(opts.enable).split(",")) { - const s = sel.trim(); - if (!s) continue; - document.querySelectorAll(s).forEach((n) => { - n.disabled = false; - n.removeAttribute("disabled"); - }); - } - } -} - -function markError(opts, err) { - const msg = String(err); - if (opts.onError) opts.onError(msg); - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.add?.("err"); - el.textContent = msg; - } - } else { - console.error(msg); - } -} - -function wirePlayground(exports, playgroundSpec, { onError } = {}) { - const parts = String(playgroundSpec) - .split(",") - .map((s) => s.trim()) - .filter(Boolean); - const sourceSel = parts[0] || "#src"; - const runSel = parts[1] || "#run"; - const outSel = parts[2] || "#out"; - const runBtn = document.querySelector(runSel); - const src = document.querySelector(sourceSel); - const out = document.querySelector(outSel); - if (!runBtn || !src) return 0; - runBtn.disabled = false; - runBtn.removeAttribute("disabled"); - runBtn.addEventListener("click", () => { - try { - const result = runSource(exports, src.value || ""); - if (out) { - out.classList?.toggle?.("err", !result.ok); - out.textContent = result.ok - ? (result.stdout || "(empty stdout)") + - (result.value != null && result.value !== "None" - ? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}` - : "") - : result.error || "error"; - } - } catch (e) { - if (onError) onError(String(e)); - else if (out) { - out.classList?.add?.("err"); - out.textContent = String(e); - } - } - }); - return 1; -} - -export async function mount(rawOpts = {}) { - const opts = normalizeMountOptions(rawOpts); - const onError = (err) => markError(opts, err); - - let exports; - try { - exports = await loadWasm(opts.wasmUrl); - } catch (e) { - onError(e); - throw e; - } - - const ver = readCString(exports.memory, exports.mq_version()); - - if (opts.playground) { - const n = wirePlayground(exports, opts.playground, { onError }); - markReady(opts, `marqdo-wasm ${ver} · playground ready`); - return { exports, boot: null, wired: n }; - } - - let source = opts.source; - if (!source && opts.sourceUrl) { - const res = await fetch(opts.sourceUrl); - if (!res.ok) { - const err = `failed to load ${opts.sourceUrl} (${res.status})`; - onError(err); - throw new Error(err); - } - source = await res.text(); - } - if (!source) { - const err = "mount: need source, sourceUrl, or playground"; - onError(err); - throw new Error(err); - } - - const result = boot(exports, source); - if (!result.ok) { - onError(result.error || "boot failed"); - throw new Error(result.error || "boot failed"); - } - - if (result.value && !Array.isArray(result.value)) { - await applyEffects(exports, result.value, { onError }); - } - - const n = wireEvents(exports, result.value, { onError }); - const srcLabel = opts.sourceUrl || "(inline)"; - markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`); - return { exports, boot: result, wired: n }; -} - -export async function autoMount(doc) { - const configs = collectMountConfigs(doc); - const results = []; - for (const cfg of configs) { - if (cfg.noBoot) continue; - results.push(await mount(cfg)); - } - return results; -} - -const g = typeof globalThis !== "undefined" ? globalThis : undefined; -if (g && g.document) { - // Defer WASM boot until after first paint / load so LCP images are not - // contending with a ~1.6MB wasm download on the critical path. - const start = () => { - const run = () => { - autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e)); - }; - const schedule = () => { - if (typeof g.requestIdleCallback === "function") { - g.requestIdleCallback(() => run(), { timeout: 1500 }); - } else { - g.setTimeout(run, 0); - } - }; - if (g.document.readyState === "complete") { - schedule(); - } else { - g.addEventListener("load", schedule, { once: true }); - } - }; - start(); -} diff --git a/crates/marqdo-wasm/js/package.json b/crates/marqdo-wasm/js/package.json deleted file mode 100755 index 5df6ffd..0000000 --- a/crates/marqdo-wasm/js/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "marqdo-bridge", - "private": true, - "type": "module" -} diff --git a/crates/marqdo-wasm/src/lib.rs b/crates/marqdo-wasm/src/lib.rs deleted file mode 100755 index 0b12333..0000000 --- a/crates/marqdo-wasm/src/lib.rs +++ /dev/null @@ -1,232 +0,0 @@ -//! Browser export surface for Marqdo (ADR 0002 / C1–C3). -//! -//! Raw `cdylib` ABI (no wasm-bindgen CLI): -//! - `mq_alloc` / `mq_dealloc` -//! - `mq_run` — one-shot `# main` (C1) -//! - `mq_boot` — start session; return value often a `wire` table (C3) -//! - `mq_call` — `(name_ptr, name_len, args_ptr, args_len) ->` JSON result (C3) -//! - `mq_version` -//! -//! Packed results: little-endian `u32` length + UTF-8 JSON -//! `{ ok, stdout, error, value }`. - -use std::alloc::{alloc, dealloc, Layout}; -use std::cell::RefCell; -use std::ptr; -use std::slice; - -use marqdo::{run_source, value_as_json, BrowserSession, RunOptions}; -use serde_json::json; - -thread_local! { - static SESSION: RefCell> = const { RefCell::new(None) }; -} - -/// Allocate `size` bytes in WASM linear memory (alignment 1). -#[no_mangle] -pub extern "C" fn mq_alloc(size: usize) -> *mut u8 { - if size == 0 { - return ptr::null_mut(); - } - let layout = match Layout::from_size_align(size, 1) { - Ok(l) => l, - Err(_) => return ptr::null_mut(), - }; - unsafe { alloc(layout) } -} - -/// Free a buffer previously returned by [`mq_alloc`], [`mq_run`], [`mq_boot`], or [`mq_call`]. -#[no_mangle] -pub extern "C" fn mq_dealloc(ptr: *mut u8, size: usize) { - if ptr.is_null() || size == 0 { - return; - } - let layout = match Layout::from_size_align(size, 1) { - Ok(l) => l, - Err(_) => return, - }; - unsafe { dealloc(ptr, layout) } -} - -/// One-shot run (C1). Does not keep a session. -#[no_mangle] -pub extern "C" fn mq_run(ptr: *const u8, len: usize) -> *mut u8 { - let source = match read_utf8(ptr, len) { - Ok(s) => s, - Err(e) => return pack_json(&err_json(&e)), - }; - pack_json(&run_to_json(&source)) -} - -/// Boot a session: run `# main`, keep entry env. Replaces any prior session. -#[no_mangle] -pub extern "C" fn mq_boot(ptr: *const u8, len: usize) -> *mut u8 { - let source = match read_utf8(ptr, len) { - Ok(s) => s, - Err(e) => return pack_json(&err_json(&e)), - }; - match BrowserSession::boot(&source) { - Ok((sess, value)) => { - let stdout = String::new(); - let value_json = match value_as_json(&value) { - Ok(j) => j, - Err(e) => return pack_json(&err_json(&e)), - }; - SESSION.with(|s| *s.borrow_mut() = Some(sess)); - pack_json(&json!({ - "ok": true, - "stdout": stdout, - "error": null, - "value": value_json, - })) - } - Err(e) => { - SESSION.with(|s| *s.borrow_mut() = None); - pack_json(&err_json(&format!("{e:#}"))) - } - } -} - -/// Call a function in the current session. -/// `args` is UTF-8 JSON object of named arguments (may be `{}`). -#[no_mangle] -pub extern "C" fn mq_call( - name_ptr: *const u8, - name_len: usize, - args_ptr: *const u8, - args_len: usize, -) -> *mut u8 { - let name = match read_utf8(name_ptr, name_len) { - Ok(s) => s, - Err(e) => return pack_json(&err_json(&e)), - }; - let args = match read_utf8(args_ptr, args_len) { - Ok(s) => s, - Err(e) => return pack_json(&err_json(&e)), - }; - SESSION.with(|cell| { - let mut guard = cell.borrow_mut(); - let Some(sess) = guard.as_mut() else { - return pack_json(&err_json("no session — call mq_boot first")); - }; - match sess.call(&name, &args) { - Ok(value) => { - let stdout = sess.take_stdout(); - let value_json = match value_as_json(&value) { - Ok(j) => j, - Err(e) => return pack_json(&err_json(&e)), - }; - pack_json(&json!({ - "ok": true, - "stdout": stdout, - "error": null, - "value": value_json, - })) - } - Err(e) => pack_json(&err_json(&format!("{e:#}"))), - } - }) -} - -/// Package version (NUL-terminated C string in static memory — do not free). -#[no_mangle] -pub extern "C" fn mq_version() -> *const u8 { - concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() -} - -fn read_utf8(ptr: *const u8, len: usize) -> Result { - if ptr.is_null() || len == 0 { - return Ok(String::new()); - } - let bytes = unsafe { slice::from_raw_parts(ptr, len) }; - String::from_utf8(bytes.to_vec()).map_err(|e| format!("not utf-8: {e}")) -} - -fn run_to_json(source: &str) -> serde_json::Value { - let mut opts = RunOptions::default(); - opts.allow_fs_write = false; - opts.allow_exec = false; - opts.allow_net = false; - opts.sleep_limit_ms = Some(0); - - match run_source(source, &opts) { - Ok(cap) => match value_as_json(&cap.value) { - Ok(value) => json!({ - "ok": true, - "stdout": cap.stdout, - "error": null, - "value": value, - }), - Err(e) => err_json(&e), - }, - Err(e) => err_json(&format!("{e:#}")), - } -} - -fn err_json(msg: &str) -> serde_json::Value { - json!({ - "ok": false, - "stdout": "", - "error": msg, - "value": null, - }) -} - -fn pack_json(v: &serde_json::Value) -> *mut u8 { - let s = v.to_string(); - let bytes = s.as_bytes(); - let total = 4 + bytes.len(); - let out = mq_alloc(total); - if out.is_null() { - return ptr::null_mut(); - } - unsafe { - let len = bytes.len() as u32; - ptr::copy_nonoverlapping(len.to_le_bytes().as_ptr(), out, 4); - ptr::copy_nonoverlapping(bytes.as_ptr(), out.add(4), bytes.len()); - } - out -} - -/// getrandom `custom` backend for wasm32 — no wasm-bindgen / JS glue imports. -/// Preferable to the `js` feature which pulls `__wbindgen_*` and breaks raw mq_* ABI. -#[cfg(target_arch = "wasm32")] -#[no_mangle] -unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 { - // xorshift64* seeded once; fine for uuid/non-crypto browser host helpers. - use std::cell::Cell; - thread_local! { - static STATE: Cell = const { Cell::new(0x4d51_5241_4e44_4f21) }; - } - if dest.is_null() || len == 0 { - return 0; - } - let mut s = STATE.with(|c| { - let mut v = c.get(); - if v == 0 { - v = 0x4d51_5241_4e44_4f21; - } - v - }); - let buf = unsafe { std::slice::from_raw_parts_mut(dest, len) }; - for b in buf.iter_mut() { - s ^= s << 13; - s ^= s >> 7; - s ^= s << 17; - *b = (s >> 8) as u8; - } - STATE.with(|c| c.set(s)); - 0 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn run_hello_json() { - let v = run_to_json("# main\n\n> print text=Hello World!\n"); - assert_eq!(v["ok"], true); - assert_eq!(v["stdout"], "Hello World!\n"); - } -} diff --git a/debian/README.Debian b/debian/README.Debian deleted file mode 100755 index 0e508a5..0000000 --- a/debian/README.Debian +++ /dev/null @@ -1,22 +0,0 @@ -Marqdo for Ubuntu (PPA) -======================= - -This package installs the marqdo CLI (/usr/bin/marqdo). - -Official language extensions are not bundled. After install: - - marqdo ext add web - marqdo ext add quantum - -Extension packs download from https://ext.marqdo.com (then GitHub / proxy). - -Install this package from: - - sudo add-apt-repository ppa:cflmy/marqdo - sudo apt update - sudo apt install marqdo - -Also available: GitHub Releases (Windows/Linux zips) and building from source. - -Documentation: https://github.com/cflmy/marqdo -PPA notes: doc/design/ubuntu-ppa.md in the upstream repository. diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index 802d6d2..0000000 --- a/debian/changelog +++ /dev/null @@ -1,307 +0,0 @@ -marqdo (2.9.1-1ppa1) noble; urgency=medium - - * Release 2.9.1; see the reviewed upstream CHANGELOG. - - -- Marqdo Maintainers Wed, 18 Nov 2026 18:43:10 +0800 - -marqdo (2.8.0-1ppa1) noble; urgency=medium - - * Release 2.8.0; see the reviewed upstream CHANGELOG. - - -- Marqdo Maintainers Wed, 18 Nov 2026 10:24:08 +0800 - -marqdo (2.7.1-1ppa2) noble; urgency=medium - - * Release 2.7.1; see the reviewed upstream CHANGELOG. - * Stop reapplying the engineering compatibility fix already in upstream. - * Include cached orig bytes until publication is confirmed by Launchpad. - - -- Marqdo Maintainers Wed, 11 Nov 2026 00:03:29 +0800 - -marqdo (2.7.0-1ppa2) noble; urgency=medium - - * Repair engineering plugin compatibility for this 2.7.0 release. - * Keep the accepted upstream orig archive; carry the fix as a quilt patch. - - -- Marqdo Maintainers Tue, 10 Nov 2026 17:53:03 +0800 - -marqdo (2.7.0-1ppa1) noble; urgency=medium - - * Release 2.7.0; see the reviewed upstream CHANGELOG. - - -- Marqdo Maintainers Tue, 10 Nov 2026 16:40:29 +0800 - -marqdo (2.6.0-1ppa1) noble; urgency=medium - - * Executable standard/extension handbooks and practical file/data/task tools. - * Readable View action notes, knowledge contracts and offline reader support. - * Preserve effect, platform and source compatibility boundaries. - - -- Marqdo Maintainers Sun, 08 Nov 2026 23:01:35 +0800 - -marqdo (2.5.1-1ppa1) noble; urgency=medium - - * Marqdo 2.5.1: exact source anchors, flowing annotation curves, - staggered margin notes, connector avoidance and a labeled toolbar. - - -- Marqdo Maintainers Sat, 07 Nov 2026 13:05:55 +0800 - -marqdo (2.5.0-1ppa1) noble; urgency=medium - - * Marqdo 2.5.0: redesigned document reader, margin execution annotations, - offline math/assets, navigation/search, and consistent live result refresh. - - -- Marqdo Maintainers Sat, 07 Nov 2026 10:00:00 +0800 - -marqdo (2.4.0-1ppa1) noble; urgency=medium - - * Marqdo 2.4.0: oracle journal as language values (foreign.oracle_journal / - replay_check), bytecode/frontend hardening, MSRV 1.81 OnceLock wait fix. - - -- Marqdo Maintainers Fri, 06 Nov 2026 15:15:00 +0800 - -marqdo (2.3.0-1ppa1) noble; urgency=medium - - * Marqdo 2.3.0: Strong foreign session — opaque Handle, affine close, - replay_check vs oracle journal, table arity refuse, Omega V_safe gate. - - -- Marqdo Maintainers Sat, 01 Nov 2026 14:45:00 +0800 - -marqdo (2.2.2-1ppa1) noble; urgency=medium - - * Marqdo 2.2.2: V_safe JSON integer contract on foreign/json bridge — - refuse integers outside +/- (2^53-1); wide ints via decimal string. - - -- Marqdo Maintainers Sat, 01 Nov 2026 09:45:00 +0800 - -marqdo (2.2.1-1ppa1) noble; urgency=medium - - * Marqdo 2.2.1: fix view/static-export outline rail under document - (occlusion doc-block close + panel container query layout). - - -- Marqdo Maintainers Fri, 30 Oct 2026 11:45:00 +0800 - -marqdo (2.2.0-1ppa1) noble; urgency=medium - - * Marqdo 2.2.0: marqdo call runs one named function in any .mq.md. - The same file stays the document, the knowledge and the program. - Tree and bytecode both execute that function. External calls stay - pure: write, process, network and plugin stay off by default. - - -- Marqdo Maintainers Fri, 30 Oct 2026 09:20:00 +0800 - -marqdo (2.1.5-1ppa2) noble; urgency=medium - - * Rebuild 2.1.5 against Launchpad (previous 1ppa1 failed with no build log). - - -- Marqdo Maintainers Tue, 27 Oct 2026 09:35:49 +0000 - -marqdo (2.1.5-1ppa1) noble; urgency=medium - - * Marqdo 2.1.5: agent reliability workbench — ResourceView / ToolSpec / - CheckpointV2 / EffectLedger; EKC ir.json warm-load; web short/read lanes. - - -- Marqdo Maintainers Tue, 27 Oct 2026 07:39:08 +0000 - -marqdo (2.1.4-1ppa1) noble; urgency=medium - - * Marqdo 2.1.4: default isolated HTTP execute (ADR 0009) — Supervisor - worker pool for execute/sse-live/stream, /_runtime/* control plane, - MR-01 dual 60s SSE gold sample, runtime.isolated_execution=1. - - -- cflmy Mon, 26 Oct 2026 10:00:00 +0000 - -marqdo (2.1.3-1ppa1) noble; urgency=medium - - * Marqdo 2.1.3: workbench M00–M06 runtime contracts (ModelSelection, - RunContext, DocumentView, usage null≠0, LLM selection/cancel, - agent.step selection e2e, view document CLI, live smoke). - - -- cflmy Sun, 25 Oct 2026 15:20:00 +0000 - -marqdo (2.1.2-1ppa1) noble; urgency=medium - - * Marqdo 2.1.2: executable-knowledge F0–F3 + View V0–V3 release bar - (evidence/closure, verify gates, bind/reuse_execute, document.extract, - KnowledgePresentation, SSE page_token, upload max_bytes). - - -- cflmy Sat, 24 Oct 2026 14:50:00 +0000 - -marqdo (2.1.1-1ppa1) noble; urgency=medium - - * Marqdo 2.1.1: executable-knowledge spine (BoundCall, NarrativeRef, - sources/applicability, generation CURRENT + closure digests). - - -- cflmy Fri, 23 Oct 2026 15:40:00 +0000 - -marqdo (2.1.0-1ppa1) noble; urgency=medium - - * Marqdo 2.1.0: file-scoped Occlusion is the default syntax; migrated - standard/extension libraries and executable-knowledge projections. - - -- cflmy Fri, 23 Oct 2026 12:00:00 +0000 - -marqdo (2.0.0-1ppa1) noble; urgency=medium - - * Marqdo 2.0.0: Occlusion syntax — [description](payload), where the - bracketed label is inert prose and the parenthesized payload is the - only executed part. Adds paren-call arguments, access() element - access, occlusion loops, marqdo labels (two-tier search + debt - ratchet), marqdo migrate labels, and label.missing / empty_payload / - ref_dangling diagnostics; view renders labels as prose, payloads as - code, stubs with a badge. 80 corpus files migrated. - - -- cflmy Thu, 22 Oct 2026 16:30:00 +0800 - -marqdo (1.5.2-1ppa1) noble; urgency=medium - - * Marqdo 1.5.2: Foreign v3 P0/P1 — raw stdin with per-cell inputs and - interrupt, plan generation/add/remove/value API, snapshot - export/import/replay, view capture for static export, explicit Persist - button, nested plan boundary. - - -- cflmy Sun, 18 Oct 2026 15:00:00 +0800 - -marqdo (1.5.1-1ppa1) noble; urgency=medium - - * Marqdo 1.5.1: View static/live execution path unified; foreign value - passing into multi-kernel sessions; cell stdin for live/static/persistent - kernels; build-time execution with stdout injection in static exports; - runnable foreign writeback example; writeback block grouping. - - -- cflmy Sun, 18 Oct 2026 22:00:00 +0800 - -marqdo (1.5.0-1ppa1) noble; urgency=medium - - * Marqdo 1.5.0: Foreign kernels v2 (structured invoke, JSON calls, - parallel fan-out, persistent Python/Node kernels, explicit state - bridge) and document-native notebooks in view; high-contrast - light/dark view themes, resizable code/output panes, OKF/EKC and - Python examples on the user site. Fixes branch-local variables - leaking into required constructor parameters. - - -- cflmy Sun, 18 Oct 2026 03:30:00 +0800 - -marqdo (1.4.6-1ppa1) noble; urgency=medium - - * Marqdo 1.4.6: Promote a bare self-increment to a required parameter. - The first bold assignment LHS is a declaration (design §8.2); a missing - argument reports missing argument for parameter, not undefined variable. - - -- cflmy Fri, 16 Oct 2026 23:56:00 +0800 - -marqdo (1.4.5-1ppa1) noble; urgency=medium - - * Marqdo 1.4.5: Streamable HTTP MCP (agent_mcp_serve transport=http); - web invoke Bearer/X-Api-Key inject + unauthorized→401; openai/agent - field access via json.get (no footnote hard-fail). - - -- cflmy Fri, 16 Oct 2026 17:40:00 +0800 - -marqdo (1.4.4-1ppa1) noble; urgency=medium - - * Marqdo 1.4.4: Soft LLM transport errors (structured status=error); - ext/ai table-first refactor (no json.set glue). - - -- cflmy Fri, 16 Oct 2026 14:40:00 +0800 - -marqdo (1.4.2-1ppa1) noble; urgency=medium - - * Marqdo 1.4.2: Agent/LLM optimize O1–O5 — sandbox trial opt-in, - promote sandbox proof, step_route/EFI/cost, style lint, quarantine. - - -- cflmy Fri, 16 Oct 2026 11:51:05 +0800 - -marqdo (1.4.1-1ppa1) noble; urgency=medium - - * Marqdo 1.4.1: View annot leaders — SVG mid-to-mid (mark bottom-center - to chip top-center), unify frame chip ids, L-to-R chip density. - - -- cflmy Thu, 15 Oct 2026 20:40:00 +0800 - -marqdo (1.4.0-1ppa1) noble; urgency=medium - - * Marqdo 1.4.0: Prose-unified control flow — block formula % marqdo: var=, - arm/loop narrative + foreach sugar, image writeback ![marqdo-out](...), - view inferred-param values; welcome pages on v0.3 prose surface. - - -- cflmy Wed, 15 Oct 2026 15:53:00 +0800 - -marqdo (1.3.3-1ppa1) noble; urgency=medium - - * Marqdo 1.3.3: Browse document-surface Structure — narration-preserving - markers, branch/loop frame pickers, ViewExecutionReport JSON; static - view output / gh-pages share the same render path as live view. - - -- cflmy Wed, 15 Oct 2026 13:20:00 +0800 - -marqdo (1.3.0-1ppa1) noble; urgency=medium - - * Marqdo 1.3.0: Engineering Knowledge Compiler (EKC) — L0–L4 catalog, - marqdo knowledge/find/reuse/duplicate/verify, Agent preflight - (REUSE→ADAPT→CREATE), graph + context packs. - - -- cflmy Mon, 28 Sep 2026 16:50:00 +0800 - -marqdo (1.2.0-1ppa1) noble; urgency=medium - - * Marqdo 1.2.0: Web Artifact rewrite (ADR 0007) — Document/Endpoint/Resource, - type:web|endpoint, web.serve/render/inspect, ext/data|security|net split, - compose_* author surface removed; marqdo-blog Artifact example. - - -- cflmy Mon, 28 Sep 2026 11:39:04 +0800 - -marqdo (1.1.1-1ppa1) noble; urgency=medium - - * Marqdo 1.1.1: AI stack closure — llm ask/stream/collect, Metadata Binding, - Skill Compilation + Adaptive Routing, MCP stdio client + resume checkpoints, - optional plugins/llm Transport ABI (fallback lib/net). - - -- cflmy Thu, 24 Sep 2026 20:32:00 +0800 - -marqdo (1.1.0-1ppa1) noble; urgency=medium - - * Marqdo 1.1.0: core surface guard + progressive contracts + MLSP for AI. - New `marqdo check` (static contract drift) and `marqdo mlsp` (language - server for AI: locate/syntax/validate/repair_targets/schema/repair_apply); - `run --json` unified structured diagnostics; contract tables - (参数/返回/字段/集合) with four validation boundaries; anchored repair - guardrails (bounded line edits, out-of-scope refused). - - -- cflmy Wed, 23 Sep 2026 13:30:00 +0800 - -marqdo (1.0.7-1ppa1) noble; urgency=medium - - * Marqdo 1.0.7: WS/net boundary hardening (same-origin handshake, - require_auth/需要登录, message caps, empty-room GC); HTTP 8 MiB cap - enforced while reading; url_encode space -> %20. - - -- cflmy Tue, 22 Sep 2026 15:40:00 +0800 - -marqdo (1.0.3-1ppa2) noble; urgency=medium - - * Fix Launchpad build: dh_clean -Xvendor/ so cargo vendor checksums keep - Cargo.toml.orig (debian-only; reuse published 1.0.3.orig.tar.xz). - - -- cflmy Thu, 17 Sep 2026 21:28:00 +0800 - -marqdo (1.0.3-1ppa1) noble; urgency=medium - - * Marqdo 1.0.3: PPA + ext CDN; unbound GFM tables; bundled Rust for noble. - - -- cflmy Thu, 17 Sep 2026 10:35:00 +0800 - -marqdo (1.0.2-1ppa2) noble; urgency=medium - - * Bundle Rust toolchain in orig (third_party/rust) so noble can build - Cargo.lock v4 offline; drop distro cargo/rustc Build-Depends. - * Architecture: amd64 (bundled toolchain is x86_64). - - -- cflmy Thu, 17 Sep 2026 10:20:00 +0800 - -marqdo (1.0.2-1ppa1) noble; urgency=medium - - * Initial Ubuntu PPA packaging for Marqdo 1.0.2. - * CLI only; extensions via "marqdo ext add" / ext.marqdo.com. - - -- cflmy Thu, 17 Sep 2026 09:55:00 +0800 diff --git a/debian/control b/debian/control deleted file mode 100755 index 3d96f4f..0000000 --- a/debian/control +++ /dev/null @@ -1,29 +0,0 @@ -Source: marqdo -Section: devel -Priority: optional -Maintainer: cflmy -Build-Depends: - debhelper-compat (= 13), - build-essential, - pkg-config, - libssl-dev, - ca-certificates -Standards-Version: 4.7.0 -Homepage: https://github.com/cflmy/marqdo -Vcs-Git: https://github.com/cflmy/marqdo.git -Vcs-Browser: https://github.com/cflmy/marqdo -Rules-Requires-Root: no - -Package: marqdo -Architecture: amd64 -Depends: ${shlibs:Depends}, ${misc:Depends}, ca-certificates -Description: Markdown markers as an interpreted programming language - Marqdo treats Markdown markers as executable syntax (code / return / - control flow). This package installs the marqdo CLI. - . - Official extensions (web, quantum, …) are installed separately via - "marqdo ext add" and download from https://ext.marqdo.com . - . - Launchpad builds use a bundled Rust toolchain under third_party/rust - (Ubuntu noble cargo is too old for Cargo.lock v4). Rebuilds on newer - series may use distro rustc if cargo ≥ 1.78. diff --git a/debian/copyright b/debian/copyright deleted file mode 100755 index a548a8a..0000000 --- a/debian/copyright +++ /dev/null @@ -1,24 +0,0 @@ -Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: marqdo -Upstream-Contact: cflmy -Source: https://github.com/cflmy/marqdo - -Files: * -Copyright: 2024-2026 cflmy -License: Apache-2.0 - -License: Apache-2.0 - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - . - http://www.apache.org/licenses/LICENSE-2.0 - . - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - . - On Debian systems, the complete text of the Apache License version 2 - can be found in "/usr/share/common-licenses/Apache-2.0". diff --git a/debian/patches/engineering-stable-option.patch b/debian/patches/engineering-stable-option.patch deleted file mode 100755 index b2dd935..0000000 --- a/debian/patches/engineering-stable-option.patch +++ /dev/null @@ -1,18 +0,0 @@ -Description: Use stable Option map_or in the engineering release boundary -Author: Marqdo Maintainers -Forwarded: not-needed -Last-Update: 2026-11-10 - -diff --git a/plugins/engineering/src/lib.rs b/plugins/engineering/src/lib.rs -index 6891f01..f0c5ffc 100644 ---- a/plugins/engineering/src/lib.rs -+++ b/plugins/engineering/src/lib.rs -@@ -283,7 +283,7 @@ fn r2_settings(root:&Path)->Result,String> { - } - } - for k in ["R2_ENDPOINT","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY"] { -- if settings.get(k).is_none_or(String::is_empty) {return Err(format!("missing {k}; configure ~/.marqdo/r2.env"));} -+ if settings.get(k).map_or(true, String::is_empty) {return Err(format!("missing {k}; configure ~/.marqdo/r2.env"));} - } - Ok(settings) - } diff --git a/debian/patches/series b/debian/patches/series deleted file mode 100755 index bf5a926..0000000 --- a/debian/patches/series +++ /dev/null @@ -1,2 +0,0 @@ -# engineering-stable-option.patch -# The fix is already in upstream 2.7.1. diff --git a/debian/rules b/debian/rules deleted file mode 100755 index 1de3704..0000000 --- a/debian/rules +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/make -f - -export DH_VERBOSE = 1 -# Offline builds on Launchpad: vendored crates + optional bundled Rust toolchain. -export CARGO_HOME = $(CURDIR)/debian/cargo_home -export CARGO_NET_OFFLINE = true - -# Noble (and older) distro cargo cannot read Cargo.lock v4 / modern crates. -# Prefer third_party/rust from the orig tarball when present (see ppa-build-source.sh). -BUNDLED_RUST = $(CURDIR)/third_party/rust -ifneq ($(wildcard $(BUNDLED_RUST)/bin/cargo),) -export PATH := $(BUNDLED_RUST)/bin:$(PATH) -endif - -%: - dh $@ - -override_dh_auto_configure: - mkdir -p debian/cargo_home - @if [ -x "$(BUNDLED_RUST)/bin/cargo" ]; then \ - echo "Using bundled Rust: $$($(BUNDLED_RUST)/bin/rustc --version)"; \ - else \ - echo "Using system Rust: $$(rustc --version 2>/dev/null || echo missing)"; \ - fi - @if [ -f "$(CURDIR)/.cargo/config.toml" ] || [ -d "$(CURDIR)/vendor" ]; then \ - echo "Using vendored Cargo dependencies"; \ - else \ - echo "WARNING: no vendor/ — online cargo fetch required (not for Launchpad)"; \ - fi - -override_dh_auto_build: - mkdir -p debian/cargo_home - @command -v cargo >/dev/null || { echo "error: cargo not found (bundle third_party/rust or install rustc/cargo)" >&2; exit 1; } - if [ -d "$(CURDIR)/vendor" ]; then \ - CARGO_NET_OFFLINE=true cargo build --release --locked --offline \ - -p marqdo; \ - else \ - cargo build --release --locked -p marqdo; \ - fi - -override_dh_auto_test: - @echo "Skipping full test suite on package build (run cargo test in CI)." - -override_dh_auto_install: - install -d $(CURDIR)/debian/marqdo/usr/bin - install -m 0755 $(CURDIR)/target/release/marqdo \ - $(CURDIR)/debian/marqdo/usr/bin/marqdo - -# dh_clean deletes *.orig by default; cargo vendor checksums require -# vendor/**/Cargo.toml.orig. Exclude the vendored tree from that purge. -override_dh_clean: - dh_clean -Xvendor/ - -override_dh_auto_clean: - dh_auto_clean - rm -rf debian/cargo_home - # keep vendor/ and third_party/rust (part of source package) - -cargo clean diff --git a/debian/source/format b/debian/source/format deleted file mode 100755 index 163aaf8..0000000 --- a/debian/source/format +++ /dev/null @@ -1 +0,0 @@ -3.0 (quilt) diff --git a/debian/source/options b/debian/source/options deleted file mode 100755 index 88a6d9f..0000000 --- a/debian/source/options +++ /dev/null @@ -1,2 +0,0 @@ -# Ignore temporary files while editing patches -extend-diff-ignore = "^vendor/" diff --git a/doc/README.md b/doc/README.md deleted file mode 100755 index 4d81fda..0000000 --- a/doc/README.md +++ /dev/null @@ -1,153 +0,0 @@ -# Marqdo 开发文档 - -本目录存放各阶段设计、选型与路线图。 - -## 目录约定 - -| 路径 | 用途 | -|------|------| -| [`research/`](research/) | 外部标准与调研 | -| [`design/`](design/) | 语言设计(语法映射等) | -| [`adr/`](adr/) | 架构决策记录 | -| [`roadmap/`](roadmap/) | 实现路线与里程碑 | - -## 当前文档 - -> **可执行知识下一阶段的阅读顺序**:[原始意图 009](next/009.md) → [文档原生开发指导](design/document-native-development-guide.md)(作者体验、语法审查结论、AI 工作协议)→ [详细开发规范](next/Marqdo_Executable_Knowledge_Development.md)(目标语义与工程约束)→ [缺口与交付路线](roadmap/executable-knowledge-gaps-2026-10-23.md)(现状证据、S0–S6)。指导文档修订作者负担、场景政策和交付次序;不得把所有内部治理字段变成作者必填项。与之冲突的早期设计只作历史参考,设计目标不等于已实现能力。 -> -> **可执行知识门禁**:[tests/executable_knowledge/](../tests/executable_knowledge/README.md) — S0–S2 BoundCall / 效应 / MLSP bind,以及后续 NarrativeRef、来源与整代投影子集;`cargo test --test executable_knowledge --locked`(CI:`.github/workflows/executable-knowledge.yml`)。`status: design` / 预期失败与已实现分开报告。 - -| 文档 | 摘要 | -|------|------| -| [design/prove-cli.md](design/prove-cli.md) | **Proposed:`marqdo prove` 设计**;SKILL 控制平面 → Lean 4、函数级定理表与语言习惯审查、离线判定片段、`proved`/`checked` 诚实性契约、无公理 TCB | -| [roadmap/prove.md](roadmap/prove.md) | **Proposed:`marqdo prove` 实施路线**;P0–P3 周计划、8 类测试矩阵(单调性/一致性/不执行/子集/定理表/CLI/缓存/编码)、CI 与验收证据 | -| [adr/0010-skill-proof-boundary.md](adr/0010-skill-proof-boundary.md) | **ADR 0010**:定理表作为契约表第四角色、可证子集封闭、Lean 为唯一 `proved` 来源、顾问式不强制 | -| [roadmap/agent-reliability-crossrepo-2026-10-27.md](roadmap/agent-reliability-crossrepo-2026-10-27.md) | **Proposed:跨仓 Agent 可靠性开发计划**;M-A0–M-A6 ∥ Q-A0–Q-A7 排期、依赖图、F01–F20 映射、MA-T*/QA-* 验收与第一刀切片;协议真源仍见下方设计文档 | -| [design/agent-reliability-tools-resources-2026-10-27.md](design/agent-reliability-tools-resources-2026-10-27.md) | **Proposed:智能体能力补足**;基于 `16f26d7`,增量设计错误恢复、检查点/效应账本、结构化工具、输出通道、上下文与只读资源视图;含跨仓边界、阶段计划和故障验收 | -| [research/agent-capabilities-2026-10-27.md](research/agent-capabilities-2026-10-27.md) | **官方能力调研与源码复核**;OpenAI/Claude/Gemini/LangGraph/Deep Agents/MCP,求道当前问题 F01–F20;区分现有能力、设计推导与待实测项 | -| [design/isolated-web-runtime-development-2026-10-26.md](design/isolated-web-runtime-development-2026-10-26.md) | **隔离执行与响应式 Web 运行时**:进程池、控制/读取分离、取消、事件恢复、发布一致性;实现见 `src/runtime/` | -| [adr/0009-isolated-web-runtime.md](adr/0009-isolated-web-runtime.md) | **ADR 0009**:隔离 Web 运行时决策;金样例通过后替代 ADR 0008 的并行性结论 | -| [跨库缺陷复核(2026-10-26)](../../qdagent/doc/gaps/04-workbench-runtime-and-product-audit-2026-10-26.md) | **最新源码与测试证据**:实际 HTTP 路由、知识发布/阅读断点、旧缺陷处置及 1000 单元编译性能失败;需同级 qdagent checkout | -| [design/qdagent-workbench-runtime-and-view-2026-10-25.md](design/qdagent-workbench-runtime-and-view-2026-10-25.md) | **qdagent 知识工作台框架支持**:M00–M05 合同落地中(`src/workbench/`、MLSP `capabilities` / `view.document` / `view.reference_resolve`、`tests/workbench_contracts.rs`);完整 verified 以切片验收证据为准 | -| [design/view-knowledge-reading-experience-2026-10-24.md](design/view-knowledge-reading-experience-2026-10-24.md) | **View 知识阅读体验重设计(建议)**:正文优先、结构导航、就地知识说明、来源与运行状态、响应式线框、实现契约与验收;含当前呈现和 no-exec 反例 | -| [design/view-readable-actions.md](design/view-readable-actions.md) | **View 阅读优化实现**:动作留在正文、实际逻辑引到侧注、空逻辑明确标识;语法阅读指南、输入输出与依据卡片、单文件依赖分析及浏览器验收 | -| [roadmap/qdagent-knowledge-support-gaps-2026-10-24.md](roadmap/qdagent-knowledge-support-gaps-2026-10-24.md) | **求道知识沉淀与文档编译支撑缺口**:2.1.1 源码复核、来源/依赖失效反例、验证与 Agent 协议、语法提示词、导入底座及跨库分工 | -| [design/document-native-development-guide.md](design/document-native-development-guide.md) | **下一阶段开发指导**:语法审查裁决、正文→命名→复用工作流、AI 上下文与局部编辑、渐进严格、作者成本及 S0–S6 验收 | -| [design/core-surface.md](design/core-surface.md) | **核心构造清单**:v2.1 默认链接/循环说明与构造守卫;不是全部实现状态清单 | -| [design/markdown-mapping.md](design/markdown-mapping.md) | **历史 v0.2 映射**:不再代表现行默认链接语义 | -| [design/markdown-mapping-v0.3.md](design/markdown-mapping-v0.3.md) | **v0.3 设计背景**:叙述统一 · 粗体代码 · 斜体返回 · 形参体推断;链接语义以 v2.1 规范和测试为准 | -| [adr/0005-prose-unified-markup.md](adr/0005-prose-unified-markup.md) | **Proposed:采纳 mapping v0.3** | -| [roadmap/markup-v0.3.md](roadmap/markup-v0.3.md) | **Markup v0.3 实现路线(M0–M5)** | -| [design/objects.md](design/objects.md) | **`#` 对象 / `##` 函数与方法** | -| [design/ai-skill.md](design/ai-skill.md) | **AI 接入 Skill**([`skills/marqdo/`](../skills/marqdo/)) | -| [design/code-vs-comment.md](design/code-vs-comment.md) | 叙述 / 可执行 / 外联 | -| [design/return-hr-and-code-surface.md](design/return-hr-and-code-surface.md) | 语句/返回/输出决议 | -| [design/generated-yaml-manifest.md](design/generated-yaml-manifest.md) | 生成式 OKF 清单(早期方向) | -| [design/okf.md](design/okf.md) | **Marqdo OKF 实现规范**(catalog v0 + 任务知识包) | -| [design/engineering-knowledge.md](design/engineering-knowledge.md) | **Engineering Knowledge Compiler(EKC)**:L0–L4、reuse、EFI | -| [design/catalog-cli.md](design/catalog-cli.md) | **`marqdo catalog` / `sync` OKF 清单命令** | -| [design/tech-stack.md](design/tech-stack.md) | 实现栈对比 | -| [adr/0001-implementation-language.md](adr/0001-implementation-language.md) | **Accepted:Rust 参考解释器;不用 Flex/Bison** | -| [design/dependencies.md](design/dependencies.md) | 依赖详单(无 Flex/Bison) | -| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置函数** | -| [design/keywords-i18n.md](design/keywords-i18n.md) | **内核中英双名(无需导入;少而精)** | -| [design/module-namespace.md](design/module-namespace.md) | **模块命名空间:导入绑定库名、`库.成员` / `use`(M1+M2 已落地)** | -| [library-development.mq.md](library-development.mq.md) | **可执行库开发指南**:单文件标准库、多文件拓展库、叙述超过 50%、标题下参数与返回表、句中赋值/返回和遮蔽调用;含真实调用及失败场景 | -| [design/stdlib.md](design/stdlib.md) | **标准库:内置 + `lib/` + 错误约定** | -| [design/stdlib-i18n.md](design/stdlib-i18n.md) | **标准库中英命名:靠库文件名区分,无 lang 开关** | -| [design/stdlib-modules.md](design/stdlib-modules.md) | **L1:文件/系统/时间/JSON/网络/数学/外联/插件** | -| [design/stdlib-mid.md](design/stdlib-mid.md) | **中层 Mid M1–M6(已落地)** | -| [design/stdlib-mid2.md](design/stdlib-mid2.md) | **中层 Mid2:datetime / url / toml / html / fs++** | -| [design/stdlib-datetime.md](design/stdlib-datetime.md) | **`lib/datetime`(Mid2 M7)** | -| [design/stdlib-url.md](design/stdlib-url.md) | **`lib/url`(Mid2 M7)** | -| [design/stdlib-toml.md](design/stdlib-toml.md) | **`lib/toml`(Mid2 M8)** | -| [design/stdlib-html.md](design/stdlib-html.md) | **`lib/html`(Mid2 M8)** | -| [design/stdlib-fs-mid2.md](design/stdlib-fs-mid2.md) | **`lib/fs` Mid2 M9 加厚** | -| [design/stdlib-stats-log.md](design/stdlib-stats-log.md) | **`lib/stats` + log.fields(Mid2 M10)** | -| [research/stdlib-gaps-after-mid.md](research/stdlib-gaps-after-mid.md) | **Mid 之后缺口盘点**(对照 Python/Go) | -| [roadmap/stdlib-mid.md](roadmap/stdlib-mid.md) | **Mid M1–M6 路线(done)** | -| [roadmap/stdlib-mid2.md](roadmap/stdlib-mid2.md) | **Mid2 M7–M10 路线(规划)** | -| [design/stdlib-math.md](design/stdlib-math.md) | **数学库(数值/随机/作图/轻量求解)** | -| [design/stdlib-foreign.md](design/stdlib-foreign.md) | **外联胶水(\`\`\`lang 具名块)— v1 已落地** | -| [design/foreign-kernel.md](design/foreign-kernel.md) | **外联内核:持久内核 / JSON 桥 / 状态桥 / 安全** | -| [design/notebook-session.md](design/notebook-session.md) | **文档会话:cell / kernel / step / journal / 状态面板** | -| [design/notebook-syntax.md](design/notebook-syntax.md) | **文档原生 notebook 语法:内核表 / 会话表** | -| [research/foreign-notebook-decisions.md](research/foreign-notebook-decisions.md) | **外联 / notebook 决策记录(逐问逐答)** | -| [roadmap/foreign-v2.md](roadmap/foreign-v2.md) | **外联内核 v2 路线(F0–F4)** | -| [roadmap/notebook-session.md](roadmap/notebook-session.md) | **文档会话路线(D0–D5)** | -| [design/ext-abi.md](design/ext-abi.md) | **原生插件 C ABI v1**(`lib/plugin`) | -| [design/ext-llm.md](design/ext-llm.md) | **官方扩展 `ext/llm`(OpenAI 兼容)** | -| [design/ext-agent.md](design/ext-agent.md) | **官方扩展 `ext/agent`(文档驱动:单步 / 多步工作簿 + 自写回;废弃 thin TOOL 循环)** | -| [design/ext-agent-plan.md](design/ext-agent-plan.md) | **`## 多步` / `## plan` 锁定设计**(工作簿文件、subtask 执行、修订循环、`step` 默认写回) | -| [design/ext-cli.md](design/ext-cli.md) | **`marqdo ext list/add/remove` 官方扩展安装器** | -| [design/ext-cdn.md](design/ext-cdn.md) | **扩展 CDN(R2 / ext.marqdo.com)与分开发版** | -| [design/ubuntu-ppa.md](design/ubuntu-ppa.md) | **Ubuntu PPA 打包与上传** | -| [design/ext-web.md](design/ext-web.md) | **官方扩展 `ext/web`(页面/库表/绑定/后台;ABI + CLI;设计锁定)** | -| [design/ext-web-go-rewrite.md](design/ext-web-go-rewrite.md) | **`plugins/web` Go 全量重写**(多语言 ABI · 网页制备完备 · 独立工作流验收) | -| [adr/0004-web-plugin-go.md](adr/0004-web-plugin-go.md) | **Accepted:web 原生插件实现语言为 Go** | -| [research/ext-web-customization-limits.md](research/ext-web-customization-limits.md) | **`ext/web` 定制限制踩坑盘点**(路由/壳 CSS/鉴权/样式/部署) | -| [design/ext-web-customization/](design/ext-web-customization/) | **对应解决设计**(C0–C4:前缀可让出、shell_css、gate、布局…) | -| [design/web-assets-and-images.md](design/web-assets-and-images.md) | **W8:favicon / Head 资源表 / 图片装配**(一次补齐) | -| [design/web-asgi-servers-and-marqdo.md](design/web-asgi-servers-and-marqdo.md) | **Daphne/Uvicorn 等 vs Marqdo**:不能直接托管;反代 + axum `listen` | -| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** | -| [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** | -| [design/view.md](design/view.md) | **`marqdo view` / `view output` 黑白极简 + 静态文档** | -| [design/user-site.md](design/user-site.md) | **用户站:`public/` → `gh-pages`** | -| [design/view-debug.md](design/view-debug.md) | **`marqdo debug` 独立调试页** | -| [design/vscode-extension.md](design/vscode-extension.md) | **VS Code 扩展:分支 `vscode-extension`(main 不跟踪源码)** | -| [design/vscode-extension-commit.md](design/vscode-extension-commit.md) | **扩展提交约定(禁止在 main 提交 `vscode-extension/`)** | -| [design/bytecode.md](design/bytecode.md) | **M5 字节码 / 双后端** | -| [design/pipeline-debug.md](design/pipeline-debug.md) | **流水线 `--dump-*` 可视调试** | -| [dev-setup.md](dev-setup.md) | 开发环境配置(Rust M0) | -| [roadmap/interpreter.md](roadmap/interpreter.md) | 正经解释器路线图 | -| [roadmap/next-phase.md](roadmap/next-phase.md) | **下一阶段:input / 诊断 / 标准库 / view 调试** | -| [roadmap/okf-near-match.md](roadmap/okf-near-match.md) | **规划:OKF 相近任务命中**(精确 sig 之外的可选软复用) | -| [roadmap/agent-streaming.md](roadmap/agent-streaming.md) | **流式输出**(SSE + `complete`/`step` stream;S0–S1 已落地) | -| [roadmap/object-inheritance.md](roadmap/object-inheritance.md) | **对象继承**(`# 子类 = > 父类`;I0–I2 已落地) | -| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **表格语义**(竖表 / 横表字典 / 脚注取元 / 行向记录 / **单元格表达式 T5**) | -| [design/table-cell-expressions.md](design/table-cell-expressions.md) | **表数据单元格 = 表达式**(同调用实参值语法;Accepted) | -| [roadmap/browser-wasm.md](roadmap/browser-wasm.md) | **浏览器 WASM 路线 C(C0–C5 Completed)** | -| [roadmap/browser-wasm-d.md](roadmap/browser-wasm-d.md) | **路线 D:作者零 JS 前端(Completed)** | -| [roadmap/browser-wasm-e.md](roadmap/browser-wasm-e.md) | **路线 E:前端能力补齐(Completed)** | -| [roadmap/browser-wasm-f.md](roadmap/browser-wasm-f.md) | **路线 F:媒体/文件/Canvas 等(Completed,F1–F5;v0.3.3)** | -| [design/browser-marqdo-wasm.md](design/browser-marqdo-wasm.md) | **浏览器 Marqdo(WASM)设计** | -| [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) | -| [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 | -| [research/agent-frameworks-and-marqdo.md](research/agent-frameworks-and-marqdo.md) | 主流智能体框架 vs Marqdo 优势 | -| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点** | -| [research/agent-framework-2026-09.md](research/agent-framework-2026-09.md) | **2026-09 刷新:宪法优先 Wave B** | -| [research/ai-agent-sandbox.md](research/ai-agent-sandbox.md) | **AI 扩展沙盒调研**:Wasm / OS / CoW / symlink 对比与 Marqdo 分层推荐 | -| [design/ext-ai-sandbox.md](design/ext-ai-sandbox.md) | **`ext/ai/sandbox` 设计锁定**:CoW · 能力表 · agent ABI(非 stdlib) | -| [roadmap/ext-ai-sandbox.md](roadmap/ext-ai-sandbox.md) | **`ext/ai/sandbox` 实现里程碑** S0–S4 | -| [research/ai-agent-llm-optimize-2026-10.md](research/ai-agent-llm-optimize-2026-10.md) | **2026-10 调研**:代码即文档×OKF×沙盒下的 Agent/LLM 优化与问题分析 | -| [design/ext-ai-optimize.md](design/ext-ai-optimize.md) | **Accepted**:Agent/LLM 优化 O1–O5 locked | -| [roadmap/ext-ai-optimize.md](roadmap/ext-ai-optimize.md) | **O1–O5 实现路线**(沙盒接入→证明晋升→路由/成本→lint→隔离) | -| [research/ext-hosting-gaps.md](research/ext-hosting-gaps.md) | **宿主集成缺口**:同域 SSE 中继 · HTTP→`##` · MCP Server · 副端口 · 跨模块 db/corpus | -| [design/ext-hosting-fill.md](design/ext-hosting-fill.md) | **宿主缺口补齐设计**(`ext/web` proxy/invoke · `ext/ai` mcp_server) | -| [roadmap/ext-hosting.md](roadmap/ext-hosting.md) | **宿主集成 H0–H4**(规划) | -| [design/code-volume-audit.md](design/code-volume-audit.md) | **代码体量审计**:53k 行的构成 · 已清 14.5k 冗余 · 剩余是特性面 · 可精简项与风险 | -| [design/link-syntax.md](design/link-syntax.md) | **链接语法(v2.1 设计声明)**:链接即调用 · `()` 与 `**代码**` 同权 · `类.函数` 跨文档 · LinkInfo · view 调用点 · 图边 · lock · L0–L5 开发指导 | -| [design/executable-knowledge-system.md](design/executable-knowledge-system.md) | **可执行知识系统(v2.1 重构草案)**:每个 `[]()` 都是命名的可执行知识步骤 · 取元/推导/循环/调用/叙述统一建图 · 跨文件稳定寻址 · check/view/verify/impact 闭环 | -| [next/Marqdo_Executable_Knowledge_Development.md](next/Marqdo_Executable_Knowledge_Development.md) | **可执行知识系统详细开发规范**:以 `next/009.md` 及两份附属文档为真实意图基线,冻结统一语义 IR、稳定寻址、绑定/验证/锁定、EKC/Agent 集成、迁移路线与验收矩阵 | -| [next/Marqdo_Executable_Knowledge_Testing.md](next/Marqdo_Executable_Knowledge_Testing.md) | **可执行知识语法测试与兼容性规程**:标准库、扩展库、CLI、Tree/Bytecode 的仓库级门禁 | -| [roadmap/executable-knowledge-gaps-2026-10-23.md](roadmap/executable-knowledge-gaps-2026-10-23.md) | **v2.1 现状与规划缺口审计(方向修订)**:保留 G01–G12 代码证据,以可读步骤、确定执行、早期 AI 复用和局部修改重排 S0–S6,严格治理按场景增加 | -| [../tests/executable_knowledge/README.md](../tests/executable_knowledge/README.md) | **S0 作者基线门禁**:六类任务语料、作者成本计数、预期失败与 Bytecode 同名误连缺陷指纹 | -| [design/knowledge-layers.md](design/knowledge-layers.md) | **知识分层(语法评审)**:原始语料 / 本体 / 可执行知识 / 调用面 · 单体知识类 vs 运行时实例 · `# 李白 = > 诗人` · 出处/还原验证 · EKC 映射 | -| [design/occlusion-description-and-search.md](design/occlusion-description-and-search.md) | **遮蔽描述与两级检索**:内置词表=范例/默认,参数=扩展 · 空载荷一律 warning · 申报习惯 | -| [design/occlusion-syntax.md](design/occlusion-syntax.md) | **遮蔽语法总纲(实施依据)**:`[描述](实现)` 的目的/语义/新鲜度校验 + M0–M8 计划 | -| [design/label-freshness-and-repair.md](design/label-freshness-and-repair.md) | 标签过期检测:L1 引用一致性 · 指纹台账 · LLM 复核 · MLSP 修复回路 | -| [design/warning-fatigue-control.md](design/warning-fatigue-control.md) | 防警告疲劳:stale 是变更报告而非扫描报告 · 分级/聚合/会话末汇总 | -| [design/staleness-providers.md](design/staleness-providers.md) | 变更检测不依赖 git:T0/T1 零依赖 + T2/T3 可选 provider | -| [design/t1-session-staleness.md](design/t1-session-staleness.md) | 会话内陈旧检测:为何模型在结构上收不到重复警告 | -| [tutorial/15-常见陷阱.md](tutorial/15-常见陷阱.md) | **使用向陷阱手册**:行首数字、跨函数作用域、空格函数名、导入路径、`table.put` 非原地(1.5.2 实测) | -| [research/qdagent-refactor-defects-2026-10.md](research/qdagent-refactor-defects-2026-10.md) | **qdagent 重构期缺陷实录 D1–D7**(沙箱 profile 不生效 · 全角 CALL 静默丢失 …) | -| [research/occlusion-vs-executable-knowledge-2026-10.md](research/occlusion-vs-executable-knowledge-2026-10.md) | **遮蔽 vs 可执行知识复核**:v2.0.0 的 `[]()` 只做了呈现层 · 两文档例子实测不可执行 · `check`/`labels`/图边工程漂移证据 · 原始设计=类-函数调用(见 link-syntax) | -| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** · 后续优化见 [ext-ai-optimize](roadmap/ext-ai-optimize.md) O 波次 | - -金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。 - -## 写作原则 - -1. 先宪法与路线图,再实现。 -2. 金样例不过 = 未完成。 -3. 示例统一 `.mq.md`。 diff --git a/doc/adr/0001-implementation-language.md b/doc/adr/0001-implementation-language.md deleted file mode 100755 index 9c3949e..0000000 --- a/doc/adr/0001-implementation-language.md +++ /dev/null @@ -1,53 +0,0 @@ -# ADR 0001:参考实现语言与前端工具 - -| | | -|---|---| -| 状态 | **Accepted**(修订:实现语言 = Rust) | -| 日期 | 2026-08-04 | -| 决策者 | chaungming + 协作 | -| 相关 | [dependencies.md](../design/dependencies.md) · [interpreter 路线图](../roadmap/interpreter.md) · [spike/REPORT.md](../../spike/REPORT.md) | - ---- - -## 背景 - -语法宪法 v0.1 已定;Python Spike 已验证 GFM/行扫描风险。产品目标是正经**解释器**(`marqdo run index.mq.md`),实现语言需兼顾安全与可维护性。 - ---- - -## 决策 - -1. **参考解释器实现语言:Rust(stable)** - - 内存安全、单静态二进制、适合长期演进到字节码 VM。 - - Python Spike **保留为算法原型/对照**,不是运行时依赖。 - -2. **词法 / 语法:不使用 Flex、Bison** - - **主因是 Marqdo 的 Markdown 语法形态**,不是「因为选了 Rust」。换成 C++ 同样不建议用 Flex/Bison 做整语言前端。 - - 解释器需要词法·语法**阶段**;采用自研行分类 + GFM 库 + **手写递归下降** → AST。 - - 详见 [dependencies.md](../design/dependencies.md)。 - -3. **架构分期不变** - - Phase I:树遍历解释器 - - Phase II:字节码 + VM - - 见 [interpreter.md](../roadmap/interpreter.md) - -4. **Markdown 库** - - `pulldown-cmark` 或 `comrak` 二选一(建包前短 Spike 钉死)。 - ---- - -## 后果 - -- 正式代码以 Cargo 工程生长;不把 Flex/Bison/LLVM 列入 v1 依赖。 -- 金样例仍为 `tests/`;行为与宪法一致。 -- 此前「Python 作参考实现」的倾向由本修订取代;Spike 结论(行扫描等)仍然有效并迁入 Rust。 - ---- - -## 否决 - -| 方案 | 原因 | -|------|------| -| Flex + Bison 作主前端 | 与 Markup-as-Syntax / Rust 栈错配;解释器非必需 | -| v1 上 LLVM | 产品是解释执行文档,不是机器后端 | -| 仅 Python 正则玩具 | 达不到安全与长期目标 | diff --git a/doc/adr/0002-browser-marqdo-wasm.md b/doc/adr/0002-browser-marqdo-wasm.md deleted file mode 100755 index 68474d5..0000000 --- a/doc/adr/0002-browser-marqdo-wasm.md +++ /dev/null @@ -1,57 +0,0 @@ -# ADR 0002:浏览器内 Marqdo = WASM 解释器(路线 C) - -| | | -|---|---| -| 状态 | **Accepted** | -| 日期 | 2026-09-01 | -| 决策者 | chaungming + 协作 | -| 相关 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) · [interpreter.md](../roadmap/interpreter.md) · [0001](0001-implementation-language.md) | - ---- - -## 背景 - -`ext/web` 已把站点装配成「源码以 `.mq.md` 为主、服务端 Rust 解释执行」。作者面仍缺**浏览器内**的同一语言:事件、局部状态、客户端 fetch/WS 回调今天要么手写 JS,要么完全不做。 - -候选路线: - -| 代号 | 做法 | -|------|------| -| **A** | 服务端驱动 + 极薄固定增强(类 HTMX) | -| **B** | 把 Marqdo **编译/翻译成 JavaScript** | -| **C** | 把 **Rust 解释器/字节码 VM 编成 WASM**,浏览器跑同一套语义 | - -产品叙事目标:**网络项目源码树可以只有 `.mq.md`**(JS/WASM 为生成或发行物,不是第二作者语言)。 - ---- - -## 决策 - -1. **选定路线 C**:浏览器内运行 **与主机同构的 Marqdo 语义**(parse → tree 和/或 bytecode VM),制品为 `marqdo.wasm` + 极薄 JS 宿主桥。 -2. **不选定 B 作为主路径**:翻译到 JS 易语义漂移,长期要维护两套后端;B 至多作实验,不替代 C。 -3. **A 不对立**:内容站 / SSR / 表单 POST 仍以服务端 `ext/web` 为主;C 负责「必须在客户端执行的 Marqdo」。 -4. **同一内核、两套宿主**:`server`(今日 CLI + axum 插件)与 `browser`(DOM / `fetch` / 定时器 / storage);**不是**把 axum、`plugins/web`、SQLite 服务端塞进浏览器。 -5. **另开设计与路线图**(见相关链接);实现按 **C0→C5** 切片,金样对齐主机行为。 -6. **与「编译 mq.md → WASM 机器码」区分**:本 ADR 是 **解释器/VM 上 WASM**;把 `.mq.md` 直接编译成独立 wasm 模块仍属 `interpreter.md` Phase III 可选项,**另案**,不替代本决策。 - ---- - -## 后果 - -- 核心库必须可 **feature-gate** 掉 `libloading` / `ureq` / `tiny_http` / TTY `libc` 等,以便 `wasm32-unknown-unknown` 链接。 -- 新增公共 API:`run_source`(内存源码 + 可选导入图),供 WASM 与测试共用。 -- 浏览器侧宿主 API 以表驱动「交互装配」暴露(对称于 `样式装配`);`ext/**` 仍不直接调 `host_*`。 -- 发行物可包含 `.wasm` / 生成的 loader;**作者仓库可不提交手写业务 JS**。 -- view 断点 / 静态文档站调试可复用同一 WASM 解释器(与 `next-phase.md` 所述一致)。 - ---- - -## 否决 / 非目标(本 ADR) - -| 方案 / 目标 | 原因 | -|-------------|------| -| 以 B(编译到 JS)为主交付 | 语义双轨;与「一种语言」冲突 | -| 浏览器内完整复刻 `plugins/web` 服务器 | 协议与权限模型不同;服务端仍 axum | -| 浏览器 `dlopen` 原生插件 | WASM 无 POSIX 动态库模型 | -| v1 消灭一切 JS 字节 | 胶水与发行 loader 允许存在;禁止的是**业务手写 JS** | -| 用 Daphne/ASGI 托管 Marqdo | 已否决,见 [web-asgi-servers-and-marqdo.md](../design/web-asgi-servers-and-marqdo.md) | diff --git a/doc/adr/0003-browser-async-effects.md b/doc/adr/0003-browser-async-effects.md deleted file mode 100755 index e3f7fa1..0000000 --- a/doc/adr/0003-browser-async-effects.md +++ /dev/null @@ -1,48 +0,0 @@ -# ADR 0003:浏览器异步 I/O(fetch / 定时)— 效应表 + 续体回调 - -| | | -|---|---| -| 状态 | **Accepted** | -| 日期 | 2026-09-01 | -| 决策者 | chaungming + 协作 | -| 相关 | [0002-browser-marqdo-wasm.md](0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) | - ---- - -## 背景 - -Marqdo 调用面今日以**同步**为主。浏览器 `fetch` / `setTimeout` 是异步的;若在 WASM 里阻塞等待,会卡死 UI,且 `wasm32-unknown-unknown` 无真实阻塞 HTTP。 - -C3 已有:`mq_call` 返回 Map(如 `set_text`)由官方 bridge 执行。C4 在同一通道上扩展异步效应。 - ---- - -## 决策 - -1. **不**在语言内核引入 async/await 关键字或假同步 `fetch`。 -2. 处理器返回值可含**效应字段**(与 `set_text` 并列),由 **JS bridge** 执行: - - `fetch`: `{ url, method?, then, headers?, body? }` - - `after`: `{ ms, then }`(定时续体) -3. 异步完成后 bridge 调用 `mq_call(then, payload)`: - - fetch 成功/失败:`{ ok, status, body, error? }` - - after:`{ ok: true }` -4. 能力默认关网络语义仍由**返回效应**显式开启(站点作者主动返回 `fetch`);CORS / 鉴权仍是浏览器与服务端责任。 -5. 服务端 `lib/net` / `plugins/web` **不变**;本 ADR 仅浏览器 WASM 宿主。 - ---- - -## 后果 - -- 作者用表格/Map 声明「请求谁、完成后调谁」,无手写业务 JS。 -- Bridge 必须串行处理效应(先 `set_text`,再调度 `fetch`/`after`)。 -- 深层 Promise 链靠多次 `then` 回调;不在 C4 做通用 async 运行时。 - ---- - -## 否决 - -| 方案 | 原因 | -|------|------| -| WASM 内同步阻塞 `fetch` | 卡死主线程;平台不支持 | -| 编译期把 Marqdo 译成 async JS | 回到路线 B | -| 在核心加 `await` 关键字 | 违反 Markup-as-Syntax / 关键字纪律 | diff --git a/doc/adr/0004-web-plugin-go.md b/doc/adr/0004-web-plugin-go.md deleted file mode 100755 index 7e178b4..0000000 --- a/doc/adr/0004-web-plugin-go.md +++ /dev/null @@ -1,30 +0,0 @@ -# ADR 0004:网络拓展库原生实现改为 Go - -历史说明(2026-11-10):下文业务站点仅记录当时决策背景,相关工程已移出本仓库;当前验收使用维护中的完整站点、网络站点及隔离测试,见 [当前工作流](../design/ext-web-go-rewrite.md#8-独立工作流与隔离验收)。 - -| | | -|---|---| -| Status | **Accepted** | -| Date | 2026-09-10 | -| Related | [ext-web-go-rewrite.md](../design/ext-web-go-rewrite.md) · [ext-abi.md](../design/ext-abi.md) · [0001-implementation-language.md](0001-implementation-language.md) | - -## Context - -- Marqdo **宿主/解释器**仍为 Rust(ADR 0001 不变)。 -- 官方插件契约是稳定 **C ABI**(`include/marqdo_abi.h`),不绑定 Rust ABI。 -- `plugins/web`(Rust/axum)已具备 W0–W8 等能力,但迭代成本高;且需验证多语言插件生态。 -- 产品目标:网络拓展库支撑完整网页制备,并以暗恋见君(外接 PostgreSQL + Redis)验收;应用层前后端均为 Marqdo 脚本。 - -## Decision - -1. **重写** `plugins/web` 为 **Go** 共享库(`-buildmode=c-shared`),产物名仍为 `libweb.so` / `web.dll` / `libweb.dylib`。 -2. **ABI 全量兼容**(函数名、参数、语义);`ext/web` 作者面默认不动。 -3. 施工图:[ext-web-go-rewrite.md](../design/ext-web-go-rewrite.md)。禁止在旧 Rust 插件上继续打补丁演进(ext-web C5)。 -4. 其它官方插件(agent / quantum / linalg)**暂不**强制改语言;Go web 作为多语言样板。 - -## Consequences - -- 构建与发版需安装 Go;CI/`marqdo ext add web` 增加 `go build` 回退。 -- 根 Cargo workspace 不再包含 `plugins/web` Rust crate(切换完成后)。 -- cgo/共享库生命周期与 `shutdown` 需严格测试。 -- 金样例 `tests/ext/web-*` 为门禁。 diff --git a/doc/adr/0005-prose-unified-markup.md b/doc/adr/0005-prose-unified-markup.md deleted file mode 100755 index 196041f..0000000 --- a/doc/adr/0005-prose-unified-markup.md +++ /dev/null @@ -1,53 +0,0 @@ -# ADR 0005:叙述统一的 Markup 映射(粗体即代码 · 斜体即返回 · 形参体推断) - -| | | -|---|---| -| Status | **Accepted** | -| Date | 2026-09-13 | -| Related | [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md) · [markdown-mapping.md](../design/markdown-mapping.md) · [return-hr-and-code-surface.md](../design/return-hr-and-code-surface.md) · [roadmap/markup-v0.3.md](../roadmap/markup-v0.3.md) | - -## Context - -- Marqdo 的产品承诺是「代码即文档 / 文档即代码」:`.mq.md` 打开是文章,运行是程序。 -- v0.2([markdown-mapping.md](../design/markdown-mapping.md))为消歧做了硬隔离:无标记 = 注释;`*…*` = 语句;`**…**` = 返回;调用必须 `>`;形参必须 `` + `名` ``。 -- 该隔离使叙述与程序**视觉割裂**;且与 AI/Markdown 习惯相反(模型偏好用 `**` 强调「要做的事」)。 -- 产品方重新审视后,希望合法化如下写法: - -```markdown -## 加一函数 -对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。 - -# main -> 加一函数 37 -或者可以直接这么调用**加一函数 37** -``` - -## Decision - -1. 采纳 **Markup 映射 v0.3** 为下一版语言宪法草案,全文见 [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md)。 -2. **角色对调**:`**…**` = 代码段(含可省略 `>` 的调用);`*…*` = 返回值。 -3. **叙述中的** `` `名` ``:**首次未赋值 = 声明变量**;未使用不报错;**仅当可执行面读取时升为形参**(见设计 §4.4 · §8.2)。不设「提及性」专用语法。 -4. **形参默认由函数体/叙述推断**(升参);`` + `名` `` 仅作迁移兼容。 -5. **`>` 调用面保留**(可选)。 -6. **空返回**用标记而非关键字:推荐 `---` / `***`;显式 `*None*` / `*无*`;整行 `**`;兼容 `****`(设计 §7.2)。 -7. **不做 v0.2 双模式兼容**(摸索阶段允许破坏性变更);旧 `.mq.md` 须改写。 -8. 金样例门禁:`tests/markup-v03/`;存量 suite 随后迁移。 - -## Consequences - -### Positive - -- 叙述与代码共用 Markdown 习惯,文档可读性上升。 -- 更贴合 AI 生成粗体「操作」的偏好,降低错用标记。 -- 去掉形参表仪式,函数更像「带名字的说明段落」。 - -### Negative / Risks - -- **破坏性**:与 v0.2 金样例、Skill、教程、大量 `lib/`/`ext/` 源码不兼容,必须分波迁移或双模式。 -- 段内扫描与形参推断增加解析/语义复杂度——空返回与升参规则已在设计 §7.2 / §8.2 钉死;其余 §12 项用金样例收口。 -- view/catalog/LSP 高亮规则需同步。 - -### Neutral - -- `#` / `##` 对象体系、标准库、插件 ABI、关键字最小集不变。 -- 输出仍是 `print` / `打印`,不是粗体/斜体。 diff --git a/doc/adr/0006-artifact-metadata-binding.md b/doc/adr/0006-artifact-metadata-binding.md deleted file mode 100755 index 05ab969..0000000 --- a/doc/adr/0006-artifact-metadata-binding.md +++ /dev/null @@ -1,42 +0,0 @@ -# ADR 0006:Artifact Metadata Binding(`${…}` 进核心 · Metadata-only) - -| | | -|---|---| -| Status | **Accepted** | -| Date | 2026-09-24 | -| Related | [binding.md](../design/binding.md) · [core-surface.md](../design/core-surface.md) · [layers.md](../design/layers.md) · [doc/next/006.md](../next/006.md) | - -## Context - -- Executable Document 需要声明「依赖哪些外部运行时资源」(模型名、API 密钥、base URL),而不是在 `ext/*` 里各自 `sys.env_get`。 -- [doc/next/006.md](../next/006.md) 提出 **Marqdo Binding**(`${namespace.name}`)与 Artifact Metadata 统一解析。 -- [layers.md](../design/layers.md):Language 层变更须 ADR;核心构造计数只许持平或下降;默认进 ext。 -- 正文插值会与 `$$…$$` 公式面冲突,且会新增内联构造压力。 - -## Decision - -1. 采纳 **Artifact Metadata Binding** 为 Language 层能力;正式规范见 [binding.md](../design/binding.md)。 -2. **`${…}` 仅**在文件头 `---` Metadata 中生效;正文 / 粗体 / 调用 / 表 / 叙述 **永不**写 Binding Expression(否决 [006 §17](../next/006.md))。 -3. **不**把 Binding 记入 [core-surface.md](../design/core-surface.md) 的 19 构造守卫表——与 `import` 同属 §4「其它语言面」。 -4. 核心只做声明与解析;扩展(如 `ext/ai/llm`)消费已绑定的 `Module.metadata` / `sys.meta*` / 入口提升变量。 -5. 第一版 namespace:`env` · `arg` · `sys` · `secret`。`config` / `file` 推迟。 -6. 加载期一次 resolve → Bound Artifact;`Value::Secret` 遮掩展示;`sys.env_get` 保留为逃逸口。 -7. **Phase 2**:入口执行前把 metadata 键提升为普通变量(形参/赋值可覆盖);正文用 `` `model` ``,不再 `${env…}`。 - -## Consequences - -### Positive - -- 配置成为文档的一部分;LLM / agent / 其它 ext 共用同一套 Binding,避免各写一套 getenv。 -- 缺失 `!` 在加载期失败,而不是运行到 HTTP 401。 -- 不膨胀 CORE_CONSTRUCTS;与公式 `$$` 无冲突。 -- 正文保持普通变量语义,不引入第二套环境变量语法。 - -### Negative / Risks - -- Secret 在 `Text + Secret` 拼接时会揭示明文(供 Authorization);须约束日志面。 -- metadata 键与业务变量同名时依赖「形参/赋值覆盖」规则,作者需注意命名。 - -### Neutral - -- `#` / `##` / `**` / `*` 等核心标记不变;frontmatter `import` 句法不变。 diff --git a/doc/adr/0007-web-document-endpoint.md b/doc/adr/0007-web-document-endpoint.md deleted file mode 100755 index 478cdd8..0000000 --- a/doc/adr/0007-web-document-endpoint.md +++ /dev/null @@ -1,54 +0,0 @@ -# ADR 0007:Web Document / Endpoint / Resource(破坏性 · 代码即文档) - -| | | -|---|---| -| Status | **Accepted** | -| Date | 2026-09-28 | -| Related | [ext-web-artifact.md](../design/ext-web-artifact.md) · [ext-web.md](../design/ext-web.md) · [binding.md](../design/binding.md) · ADR [0006](0006-artifact-metadata-binding.md) · [layers.md](../design/layers.md) · [doc/next/007.md](../next/007.md) | - -## Context - -- [`ext/web/web.mq.md`](../../ext/web/web.mq.md) 已膨胀为小型 Web Framework(Page God Object、`configure` 垃圾抽屉、碎片 Table DSL、隐式路由),与 Marqdo「代码即文档」冲突。 -- [doc/next/007.md](../next/007.md) 提出 Document / Endpoint / Resource 三原语与拆分 `ext/web` · `ext/net` · `ext/data` · `ext/security`。 -- 现行 [ext-web.md](../design/ext-web.md) **C1** 禁止为 web 改核心;Document/Endpoint 装载识别需要 Language/Runtime 参与(复用 Artifact Metadata `type`,**不**新增 CORE_CONSTRUCTS 标记)。 -- Binding(ADR 0006)已提供文件级 Metadata;`type: prompt` 先例在扩展侧消费 metadata。 - -## Decision - -1. **采纳** Document / Endpoint / Resource 为 Web 模型一等公民;正式规范见 [ext-web-artifact.md](../design/ext-web-artifact.md)。 -2. **修订 ext-web C1**:允许核心在装载期识别 `type: web|endpoint`(及中文 `类型: 网页|端点`)并暴露 artifact 分类;**装配 / HTTP / DB 语义仍在 ext + plugin**。单元格求值、import 句法、CORE_CONSTRUCTS 计数不变。 -3. **文件级 Artifact only**:不在 `##` 函数体嵌套 `---` frontmatter(与 Binding Phase 1 / 解析器一致)。 -4. **破坏性重写作者面**:删除 `compose_*` 碎片 DSL、god `# page` 变异堆、`app.configure` 多参数抽屉、作者 `ensure_plugin`;examples 与 `tests/ext/web*` 同步重写。 -5. **目录定稿**(007 §三十五 + §四十): - - `ext/web/` — page · route · component · dom · client · facade - - `ext/net/` — http · websocket · url - - `ext/data/` — db · cache · storage - - `ext/security/` — auth · oidc · rbac -6. **统一 View 表**:`| type | slot | value | attrs | style |`;Table = Data,禁止每函数私有方言。 -7. **declared vs system routes**:用户 route 须声明;`/_part` · `/_form` 等为 system,经 `web.inspect` 可见。 -8. **import = capability**:`import web:…` 由 facade 自动加载 native plugin;作者程序不写 `ensure_plugin` / `host_*`。 -9. **Metadata v1 锁定(原 007 未决项)**: - - 发现:`web.serve root=` 扫描 `root/**/*.mq.md`,仅注册 `type`/`类型` ∈ {web,网页,endpoint,端点} 的文件;无 type 的库文件忽略。 - - Data:仅 flat 键 `data_source` · `data_order` · `data_where`(text;where 为 `col=val` 逗号分隔)。嵌套 YAML `data:` 推迟。 - - Result:`{ok: bool, value: any, error: text|None}`。 - - Realtime 模块名:`ext/net/websocket.mq.md`(ZH:`实时.mq.md`)。 - - ZH metadata:`类型`←type,`路由`←route,`方法`←method,`路径`←path,`请求`←request,`响应`←response,`鉴权`←auth,`数据源`←data_source,`排序`←data_order,`条件`←data_where。 - -## Consequences - -### Positive - -- `.mq.md` 同时是文档、路由、实现与鉴权声明。 -- 与 LLM/Agent Artifact Metadata 统一心智。 -- 职责边界清晰,可独立演化 data/security/net。 - -### Negative / Risks - -- 破坏性:全部现有 web 作者程序与 smokes 必须改写。 -- Endpoint 热路径仍经 plugin → `CallLibPath` / 文件装载回调;须保持 ABI 稳定演进。 -- flat data 键表达力弱于嵌套 YAML;后续另 ADR。 - -### Neutral - -- 不新增 Markdown 核心标记;`${…}` 仍仅 Metadata。 -- Go `plugins/web` 可分波删除死 compose ABI;作者面先断。 diff --git a/doc/adr/0008-web-invoke-serialization.md b/doc/adr/0008-web-invoke-serialization.md deleted file mode 100755 index b28ea64..0000000 --- a/doc/adr/0008-web-invoke-serialization.md +++ /dev/null @@ -1,68 +0,0 @@ -# ADR 0008:Web 热路径单解释器串行化(设计缺陷与缓解) - -| | | -|---|---| -| Status | **Accepted**(缺陷已记录;缓解已落地;真并行见 [ADR 0009](0009-isolated-web-runtime.md)) | -| Date | 2026-10-26 | -| Related | [web-invoke-serialization.md](../design/web-invoke-serialization.md) · [ADR 0009](0009-isolated-web-runtime.md) · ADR [0004](0004-web-plugin-go.md) · ADR [0007](0007-web-document-endpoint.md) · [ext-abi.md](../design/ext-abi.md) · [ext-web-go-rewrite.md](../design/ext-web-go-rewrite.md) | - -## Context - -- Go `plugins/web` 的 HTTP 服务是**多 goroutine** 的:每个请求可并发进入 `handleInvoke` / `handleInvokeLiveSSE`。 -- 每个 Endpoint 最终经 C ABI `host_query("call_lib_path", …)` 回到 Rust 宿主,在**同一个** `HostContext`(Marqdo 解释器状态)上执行作者 `.mq.md`。 -- `HostContext` **不是** `Sync`:共享可变会话、库装载、写回、事件总线等状态不能安全地被多线程同时求值。 -- 因此宿主用进程级 `INVOKE_LOCK`(`src/host/plugin.rs`)串行化所有来自 worker 线程的 `call_lib_path`。 - -### 常见误解 - -> 「web 都是单线程的吗?不能多线程吗?」 - -| 层 | 并发模型 | -|----|----------| -| Go HTTP / SSE flush / 取消 | **多线程(多 goroutine)** | -| Marqdo 解释器 `call_lib_path` | **单飞(一把全局锁)** | -| 浏览器 UI | 与后端锁无关;但若短 API 同步阻塞等待锁,会表现为「整页卡死」 | - -**缺陷不在「HTTP 单线程」,而在「多 HTTP 工作线程共享一个非 Sync 解释器」。** -真并行需要多解释器实例(或可共享的隔离运行时),不是去掉 Go 侧并发。 - -### 事故形态(已观测) - -长对话(`return=sse-live` / `stream:true`)在 `CallLibPath` 期间一直持有 `INVOKE_LOCK`。并发的短路由(如 `/v1/models`、设置页探测)在旧实现里对锁 **无限期** `lock()`,HTTP 挂起 → 前端 `fetch` 无超时 → 页面无响应。重启进程可恢复,但属于运维掩盖,不是正确错误处理。 - -## Decision - -1. **承认并文档化**本限制为宿主架构缺陷(单 `HostContext` + 全局 `INVOKE_LOCK`),不得再被表述为「web 插件只能单线程」。 -2. **缓解(已实现,非根治)**: - - `call_lib_path` 从 worker 进入时用 **限时 try-lock**(默认 `MARQDO_INVOKE_WAIT_MS=1500`),超时返回错误串 `interpreter busy: …`。 - - Go `handleInvoke` 将含 `interpreter busy` 的错误映射为 **HTTP 503**,并设 `Retry-After: 2`。 - - **禁止**在 SSE 期间把进程级 `MARQDO_INVOKE_WAIT_MS` 拉长:那会让并发短请求重新卡死。 - - 长 SSE 在启动时用同一短预算争锁;一旦拿到则持有至调用结束(对话本来就要跑完)。 -3. **客户端契约**:短 API 必须有超时与 503 文案;不得假设「任意时刻都能同步进入解释器」。 -4. **根治(未决,另案)**:解释器池 / per-request isolate / 可 `Send` 的会话切片。未落地前,产品行为以本 ADR 的 503 语义为准。 - -## Consequences - -### Positive - -- 对话进行中,设置/模型列表等短请求约 1.5s 内失败并可读,UI 不再无限挂起。 -- 缺陷有名有姓,后续多解释器工作不会被「修好了」的假象挡住。 - -### Negative / Risks - -- 同一进程仍无法真正并行跑两个 Marqdo Endpoint 体;第二个长 SSE 也会在短预算后失败。 -- 极短窗口内,短请求若正好撞上锁交接,可能偶发 503(可重试)。 -- `MARQDO_INVOKE_WAIT_MS` 是进程环境变量;误设过大仍会复现卡顿。 - -### Neutral - -- Go 多 goroutine、SSE 桥(`MARQDO_EVENT_FORWARD`)、取消令牌(`MARQDO_CANCEL_TOKEN`)保持不变。 -- 不改变 Document / Endpoint 作者面(ADR 0007);只约束宿主与 web 插件错误语义。 - -## Implementation pointers - -| 位置 | 职责 | -|------|------| -| `src/host/plugin.rs` → `acquire_invoke_lock` | 限时争锁;失败 `set_err("interpreter busy…")` | -| `plugins/web/.../routes_invoke.go` → `handleInvoke` | `interpreter busy` → 503 + `Retry-After` | -| 设计长文 | [web-invoke-serialization.md](../design/web-invoke-serialization.md) | diff --git a/doc/adr/0009-isolated-web-runtime.md b/doc/adr/0009-isolated-web-runtime.md deleted file mode 100755 index 8efcb6d..0000000 --- a/doc/adr/0009-isolated-web-runtime.md +++ /dev/null @@ -1,33 +0,0 @@ -# ADR 0009: Isolated Web Runtime (worker process pool) - -| 项目 | 约定 | -|---|---| -| 状态 | **Accepted**;HTTP **execute** 路径正式替代 [ADR 0008](0008-web-invoke-serialization.md) 的并行性结论。`legacy_serial`(未声明且非流式)仍引用 0008 单飞 / 父进程 `CallLibPath`。 | -| 日期 | 2026-10-26(修订 2026-10-27:disconnect≠cancel;control/read/short 无父锁) | -| 设计 | [isolated-web-runtime-development-2026-10-26.md](../design/isolated-web-runtime-development-2026-10-26.md) | -| 金样例 | `tests/isolated_execute_mr01.rs`(MR-01 双 60s SSE + short reads;同文件 MR-02 槽满拒绝;disconnect-keeps-running;control-under-dual-execute) | - -## 背景 - -ADR 0008 确认:Go HTTP 多线程,但所有 Endpoint 共享一把解释器锁与进程级 SSE 桥环境变量。1500ms busy → 503 只是缓解,不是并行。 - -## 决策 - -1. **首选架构**:预热的一次性 Marqdo worker 进程池;每个租约独占一个进程与 HostContext。 -2. **HTTP 默认**:`class=execute` 或 `return=sse-live` / body `stream:true` → `admit` → `dispatch`(`--call-lib-path` worker);**禁止**父进程 `CallLibPath` / `Setenv` / `legacySSEBridgeMu`。声明的 `short`/`read`/`control` 走父进程短路径(execute 已离进程,父锁通常空闲);未声明非流式 → `legacy_serial`。 -3. **控制/读取分离**:`/_runtime/*`(cancel、events、task get)不进入解释器锁。短读勿挤占 execute worker 槽(池默认 2);产品 cancel 优先 `/_runtime`。 -4. **订阅 ≠ 取消**:`sse-live` 观察者 `ctx.Done()` 默认**只结束订阅**,不 `runtime.cancel`;后台仍 reap worker 以释放槽。仅显式 header `X-Marqdo-Cancel-On-Disconnect: 1` 才 disconnect=cancel。同步 `waitIsolatedJSON` 可保留 disconnect 取消。重连:`GET /_runtime/tasks/{id}/events` + `Last-Event-ID` / `after_seq`。 -5. **协议**:`InvokeRequestV2` / worker env + NDJSON `MARQDO_EVENT_FORWARD` + `--emit-result`(首期);`/_runtime/*` 控制面。 -6. **能力探测**:`runtime.isolated_execution=1`、`runtime.task_control_v2`、`runtime.event_replay`、`view.analysis_cache_v2`、`runtime.read_lane=1`(短读不与 execute 抢父锁)。 -7. **发布**:`expected_generation` CAS + publish journal;逻辑文档 ID 与物理 generation 路径解耦。 - -## 后果 - -- Execute / live SSE 不再抢进程级 SSE 桥;双流可并行(MR-01)。 -- 短读走父进程:在 dual execute 下通常仍 200(父锁空闲);勿把 short/read/control 塞进 2 槽 execute 池。 -- Legacy 未声明非流式路径仍可走父进程锁(ADR 0008)。 -- 产品(qdagent)`turn_events` / Last-Event-ID / cancel CAS 接线由 qdagent 验收;框架侧 disconnect≠cancel 与 `/_runtime` 无锁控制面已落地。 - -## 验收(摘要) - -MR-01 绿:双假上游 60s 流不混字、短读全 200、两 worker `--call-lib-path`、第三路槽满 429/503、`runtime.isolated_execution=1`、`runtime.read_lane=1`。观察者断连后任务仍跑完并可经 `/_runtime` 重放。其余见设计文档 §12。 diff --git a/doc/adr/0010-skill-proof-boundary.md b/doc/adr/0010-skill-proof-boundary.md deleted file mode 100755 index ed7a93b..0000000 --- a/doc/adr/0010-skill-proof-boundary.md +++ /dev/null @@ -1,79 +0,0 @@ -# ADR 0010: SKILL 证明边界:定理表、可证子集与顾问式判定 - -| 项目 | 约定 | -|---|---| -| 状态 | **Accepted(决策已定)**;实现未开始,路线见 [roadmap/prove.md](../roadmap/prove.md) | -| 日期 | 2026-11-13 | -| 设计 | [design/prove-cli.md](../design/prove-cli.md) | -| 相关 | [core-surface.md](../design/core-surface.md)(不新增标记)· [layers.md](../design/layers.md)(Language 层扩表角色)· [contract.rs](../../src/contract.rs)(既有契约表提取)· [replay-policy](../../verification/replay-policy/README.md)(Lean 伴随判定先例) | - -## 背景 - -Agent 改写 SKILL 后,人需要逐行确认"分支是否绕开审核、失败是否被吞掉"。这类**控制平面**性质适合形式化:编排是带条件的有限 DAG,没有死循环、没有指针。同时,把整个 Marqdo 当通用语言编译到 Lean 会立刻撞上字符串/JSON/浮点/IO 的语义鸿沟,收益被稀释。 - -项目已有一条 Lean 纪律:`verification/replay-policy` 用 Lean 做唯一判定,Rust 不保留第二份实现,缺伴随进程时失败关闭。本 ADR 决定把同样的纪律用于 SKILL 编排,但**降级为顾问式**:证明用于减少审核量,不作为发布门禁。 - -## 决策 - -1. **定理是契约表的第四种角色**,不是新标记。 - 函数体首条可执行语句之前可放一张「定理表」(`定理 | 结论 | 前提 | 策略`),与 `参数`/`返回`/`字段` 表同槽位;解析期提取进 `Function.claims`,从 body 移除,不参与运行。核心标记计数不变,`CORE_CONSTRUCTS` 不增行;`layers.md` 的 Language 清单补记该角色。 - -2. **可证子集显式封闭**:无 `while`、无递归、无动态派发(插件、变量函数名、`code` 值调用)。越界函数被跳过(`rejected`),不降级成不透明块。外部操作是 `Env := Op → Val` 参数,不是公理;后置条件只能来自 `假设` 表并成为定理前提。 - -3. **Lean 是唯一能产生 `proved` 的判定器**。离线判定只到 `checked`,且被限制在一个极小的片段(路径枚举、轨迹、字面结果、命题组合、单变量区间),凡是离线判定为真的定理都必须同时生成 Lean 脚本。运行期若 Lean 可用则复核;离线 `checked` 而 Lean 未关闭视为内部错误(`proof.divergence`),以 Lean 为准并退出非零。 - -4. **顾问式,不强制**。默认退出码只对"作者写下的定理未被关闭"(`unproved`)与工具错误非零;缺工具链、`rejected`、`unverified` 默认 0。需要严格覆盖的调用方显式传 `--require-lean`。规范与技能手册**推荐**在发布 SKILL 前运行,但不设为门禁。 - -5. **`prove` 不执行被证程序**。只读源码、写缓存与 `--emit` 目录;这一点由测试夹具(带 `fs.write` 的函数)守住。 - -## 备选与取舍 - -| 备选 | 否决理由 | -|---|---| -| frontmatter `proof:` 块 | 丢函数作用域与行级锚点;多函数文件无法分派;诊断指不回具体行 | -| `# 证明` 标题 | `#` 是对象、`##` 是函数;新增"标题=命题"破坏"标题即可调用单元"的既有习惯,还会进命名空间 | -| ` ```proof ` 围栏 | 代码围栏必须跟在空赋值后,为写定理先造死变量,比表更别扭;且会被当作可执行值 | -| 普通注释承载定理 | 注释不参与语义,无法可靠区分说明与定理,拿不到行锚点 | -| 旁挂 `.proof.md` | 把真理拆成两份,违背"文档与代码同一份"的项目前提 | -| 细化类型(refinement types) | 语义增量过大,且与既有契约表形成两份作者真相 | -| 强制门禁(proved 才能发布) | 与"降低审核难度"的目标冲突;无 Lean 的团队会绕过工具 | - -## 后果 - -**正面** - -- 作者在一个地方写清"这条编排保证什么",机器可判定、行号可定位; -- 定理表与契约表同一提取路径,`check` / `view` / `catalog` 可逐步接入,不产生第二套声明; -- 外部依赖以假设形式显式化,证书是本项目一贯的"可复核证据"; -- 不新增核心标记,守卫测试与文档计数不膨胀。 - -**负面 / 代价** - -- 新增一个语言层语义角色与一个 CLI 命令,需要 ADR + 测试 + 文档(本 ADR 即准入材料); -- 离线判定器是新代码,必须长期用 Lean 语料护栏,防止"过度自信"; -- 作者可能误以为定理会在运行时生效——需要文档、`view` 与 `check` 三处反复澄清; -- `proved` 容易被读成"整份 SKILL 安全"——README 必须写死"只对陈述负责"。 - -## 语义增量清单 - -| 新增 | 是否进运行时 | 说明 | -|---|---|---| -| `Function.claims` | 否 | 与 `Function.contract` 同类的声明元数据 | -| `结果` / `轨迹` 与 `包含` / `长度` / `下标` | 否 | 仅定理作用域;与普通表达式作用域隔离 | -| `check --proof` | 否 | 静态校验,默认关 | - -不新增:求值规则、作用域规则、调用约定、核心标记、类型系统扩展。同名遮蔽(参数或局部变量叫 `结果`/`轨迹`)一律报 `proof.name_shadow`,不做隐式优先。 - -## 验收(摘要) - -- 核心表面:`cargo test --test core_surface` 不变红;`CORE_CONSTRUCTS` 计数不变。 -- 单调性:语料中每条离线 `checked` 的定理,Lean 均 `proved`;分歧为 0。 -- 不执行:带 `fs.write` 的夹具在 `prove` 后无副作用。 -- 确定性:同输入两次 `emit` 字节一致。 -- 诚实性:文本、JSON、证书三处对 `checked`/`proved` 的措辞一致。 - -## 未决(不阻塞实现) - -- `假设` 表是否需要扩展列(`来源`、`责任方`)。 -- `--all` 的聚合粒度(按文件/按函数)。 -- 证书是否需要签名,以及签名由谁持有。 diff --git a/doc/design/agent-reliability-tools-resources-2026-10-27.md b/doc/design/agent-reliability-tools-resources-2026-10-27.md deleted file mode 100755 index a567e0d..0000000 --- a/doc/design/agent-reliability-tools-resources-2026-10-27.md +++ /dev/null @@ -1,348 +0,0 @@ -# Marqdo 智能体能力补足:恢复、工具、上下文与资源视图 - -| 项目 | 约定 | -|---|---| -| 状态 | **Proposed**;本次交付设计,不代表以下新接口已实现 | -| 日期 / 基线 | 2026-10-27(Asia/Shanghai);Marqdo `16f26d7` / 2.1.4;qdagent `68b757e` | -| 调研与现状 | [官方资料与源码证据 F01–F20](../research/agent-capabilities-2026-10-27.md) | -| 产品配套 | [qdagent 智能体能力与预览设计](../../../qdagent/doc/design/agent-capabilities-and-preview-2026-10-27.md)(同级 checkout) | -| 继承 | [ext/agent](ext-agent.md)、[隔离 Web 运行时](isolated-web-runtime-development-2026-10-26.md)、[工作台合同](qdagent-workbench-runtime-and-view-2026-10-25.md) | - -## 1. 目标与架构边界 - -让同一套文档原生 Agent 在模型错误、工具失败、网络中断后有界恢复;让工具可发现、可验证、可审计;让结果同时服务模型上下文与用户阅读。保留 `.mq.md` 工作簿、EKC 与验证证据的权威地位,不把框架改成第二套产品聊天服务。 - -现有 `src/runtime/` 已实现隔离进程、任务/事件与控制通道,本设计在其上补 Agent 步骤语义。现有 `ext/ai/agent.mq.md` 已有 step/plan/run、CALL/READ、观察压缩,继续扩展。框架不持有求道“笔记”业务表、中文按钮、默认回答字数或具体供应商账户。 - -| 议题 | Marqdo 所有 | qdagent 所有 | -|---|---|---| -| 恢复 | 错误分类、预算、检查点、工具效应、运行/事件语义 | 恢复按钮、会话关联、凭证修复入口、产品政策 | -| 工具 | ToolSpec/Call/Result、schema、权限执行、并发、MCP 传输 | 业务工具、默认集合、连接配置、用户授权范围 | -| 回答 | 结果分通道、输出预算、角色消息、finish reason | 简洁/标准/详细策略、摘要与产物卡、ASK/BUILD 行为 | -| 资源 | ResourceRef、只读内容/派生预览、定位、转换插件接口 | 笔记/文件/产物 ID 映射、owner 权限、预览组件和布局 | -| 知识 | preflight/reuse/verify/compile、记忆原语 | 何时提议沉淀、用户画像与可见管理 | -| 调试 | span、结构化事件、用量与错误码 | 可读过程、运行详情、产品评测语料 | - -```mermaid -flowchart LR - APP[qdagent 产品策略与授权] --> RUN[ext/ai/agent step / plan / run] - RUN --> CTX[ContextPack 与预算] - RUN --> LLM[LLM Adapter] - RUN --> DISPATCH[Tool Dispatcher] - DISPATCH --> LOCAL[受控 Marqdo 函数] - DISPATCH --> MCP[MCP Client] - DISPATCH --> RES[资源读取 / 转换] - RUN --> REC[Checkpoint / Effect Ledger] - REC --> RT[既有 runtime task store / event log] - RUN --> OUTPUT[answer / artifact / progress / diagnostic] - RES --> VIEW[DocumentView / ResourceView] - OUTPUT --> APP - VIEW --> APP -``` - -## 2. 现状与增量 - -| 已有能力 | 本轮不能误判为缺失 | 要补的具体语义 | -|---|---|---| -| runtime.task_control_v2/event_replay/read_lane | 不再新建一套队列与 SSE 框架 | Agent 步骤恢复与传输重放的边界 | -| resume_save/load | 不再新建平行 checkpoint 命名空间 | 原子提交、版本摘要、作用域、效应关联 | -| CALL、ARGS、READ、plan patch | 不废弃文档式编排 | 类型化 schema、校验错误、有限修复、稳定 call_id | -| MCP stdio client | 不从零重写连接器 | timeout/cancel、resource、远程 transport 的能力探测 | -| DocumentViewV1 / Locator | 不另写 `.mq.md` 解析器 | 普通资源类型、明确 renderer、历史与相对资源处理 | -| LLM messages/usage | 不把 provider 行为交给产品猜测 | 输出预算、原生工具适配探测、角色边界与分通道 | - -新模块路径及协议名以下均是**建议落点**。首批开发先固化 schema 与 fixture,再开放 feature bit;不得只更新 capabilities 把未实现能力标真。 - -## 3. 错误和恢复合同 - -### 3.1 ErrorV1 - -现有字符串错误保留兼容适配,新工具与 Agent 结果返回: - -```json -{ - "schema": "AgentErrorV1", - "code": "tool.timeout", - "category": "transient", - "stage": "tool", - "message": "读取资源超时", - "retryable": true, - "retry_after_ms": 1200, - "effect_state": "none", - "recovery_action": "retry_step", - "call_id": "call_01", - "details_ref": "resource:diagnostic_01" -} -``` - -`retryable` 仅是候选信息,最终动作由可信策略结合效应、截止时间、预算、取消状态决定。远端工具声称 readOnly/idempotent 不构成授权依据。凭证和原始堆栈不进入公开 message。 - -| 错误类别 / 例子 | 框架动作 | 不允许的动作 | -|---|---|---| -| transient:429、部分 5xx、连接失败 | 只在安全步骤重试,遵守 Retry-After | 无限重试、复用同一流片段直接追加 | -| invalid_arguments:schema 不匹配 | 把字段级错误作为 observation,最多 1 次参数修复 | 启动工具后才校验;静默丢弃字段 | -| validation_failed:编译/文档校验 | 保留候选与诊断,局部修复后重新验证 | 将未验证草稿标为成功 | -| context_overflow | 压缩可重建上下文,保留任务/限制/未决效应 | 丢失最新用户指令、授权或版本 | -| auth / forbidden | 直接 needs_input/blocked,交应用处理 | 换身份、扩大范围或匿名绕过 | -| conflict / stale_revision | 重新读取版本并重新规划 | 覆盖用户修改、对写操作盲重试 | -| capability_unavailable | 返回可行替代操作清单 | 假称已搜索、已渲染或已执行 | -| policy_denied | 显式拒绝该动作 | 把限制当工具错误让模型规避 | -| budget_exhausted | 保存状态与已完成结果,返回 partial | 自动增预算或伪造 completed | -| unknown_effect / worker_crash | 对账、查询外部状态,不能判断则 needs_reconciliation | 重跑整个工作簿 | -| cancelled | 停止新调用、保留可读产物、传播取消 | 在后台悄悄修复或恢复 | - -初始建议:传输最多 2 次重试(总 3 次尝试),指数退避基准 0.5/1 秒并加 jitter;有 Retry-After 时使用服务端建议并受总 deadline 限制。参数修复最多 1 次,内容修复最多 2 次。预算由应用传入,框架只提供默认上限与执行机制。所有重试、修复和摘要模型调用计入同一成本账本。 - -错误指纹 `hash(tool_id, normalized_arguments, error_code, relevant_revision)` 连续出现 2 次且没有新证据时中止该策略,允许一次有依据的替代路径;不能通过改写错误文本绕过循环检测。 - -### 3.2 四类“恢复”必须分开 - -1. **续订事件**:客户端从 cursor 重放和订阅同一个 task,不发起新推理。 -2. **重试步骤**:相同逻辑 operation、同幂等键;新 invocation attempt,复用成功的前序结果。 -3. **恢复工作流**:从兼容 checkpoint 建立新 runtime task / attempt,关联 `resumed_from`,不把旧终态改回 running。 -4. **重新生成答案**:新的输出版本;已有成功工具结果可复用,用户明确重新执行才重新产生效应。 - -当前 TaskState 把 interrupted/needs_reconciliation 视为终态,沿用此约定。新增 `AgentRun` 逻辑关联只管理目标和 attempt 链;调度权仍在原 runtime。恢复请求带 `expected_revision`、checkpoint digest 与幂等键,相同请求返回同一新 attempt,冲突返回 409 对应的框架错误。 - -执行失败不必丢掉有用内容:`outcome.status = succeeded | partial | failed | needs_input | cancelled`,伴随 `answer_ref/artifacts/error/recovery_options`。HTTP 调用成功与 Agent 业务 succeeded 不再混为同一字段。 - -## 4. 检查点与工具效应 - -### 4.1 CheckpointV2 - -在 `plugins/agent/src/resume.rs` 扩展已有实现,统一根目录由宿主提供,客户端不能传任意绝对路径。保留 legacy load,但旧 checkpoint 无效应信息时默认 `manual_review`,不能自动重做写操作。 - -| 字段组 | 内容 | -|---|---| -| 身份 | schema、checkpoint_id、logical_run_id、task_id、attempt_id、step_id、parent_checkpoint_id | -| 作用域 | principal_ref、workspace_id、session_id、授权 scope digest | -| 输入 | task revision、workbook revision/hash、输入资源 revisions、knowledge generation | -| 运行配置 | ModelSnapshot public ref、tool registry digest、policy revision、runtime compatibility | -| 进度 | completed_steps、pending_operation、observation refs、context summary ref | -| 约束 | 剩余 token/tool/time/cost 预算、deadline、cancel epoch | -| 一致性 | effect ledger watermark、event seq、manifest digest、committed_at | - -写入协议:写唯一临时文件→flush/fsync→原子 rename→提交 checkpoint 指针;持久化配置下目录 fsync 按平台支持实现。所有引用 blob 在指针提交前落盘。损坏记录报 `checkpoint.corrupt` 并尝试上一个完整版本,不能读取半个 JSON 当无历史。 - -恢复前校验身份/授权、源版本、工具 schema 与模型兼容性。权限撤销立即生效;checkpoint 不是永久授权。源文件改变返回 `checkpoint.input_changed`,重新计划受影响步骤,不能偷偷使用最新文件继续旧验证结果。 - -### 4.2 Effect ledger - -```text -prepared → started → committed - ↘ failed_no_effect - ↘ unknown → reconciled_committed | reconciled_no_effect | needs_input -``` - -每个 operation 持久记录 `operation_id/idempotency_key/args_digest/resource_scope/expected_revision/effect_class/result_ref`。幂等键作用域是 principal + workspace + logical_run + step + operation,不用随机 attempt ID 替换稳定 operation key。对同 key 不同 payload 拒绝。 - -读工具可重试;确定幂等写由服务端去重;可补偿写仅在补偿明确安全时执行;未知写先查询 receipt/版本。对外部系统不能承诺通用 exactly-once。关键 crash 窗口是“远端已成功、本地尚未记账”,必须返回 unknown 并对账。 - -本地文件使用 expected revision + staging + atomic replace;变更提交后检查点失败也靠 operation receipt 恢复。`tool.completed` 必须在结果与 receipt 可读取后提交,再对外发事件。事件发送失败不回滚已发生的业务效应。 - -不要复制 runtime 事件存储:Agent ledger 与 artifact manifest 是步骤事实,现有 runtime event log 是传输/调度事实;以 ID 关联,采用可重建投影与 outbox。跨 DB/文件不能声称一个事务完成,使用 manifest 提交点和恢复扫描补齐索引。 - -## 5. 结构化工具与调度 - -### 5.1 ToolSpecV1 - -```json -{ - "schema": "ToolSpecV1", - "id": "workspace.read", - "version": "1", - "description": "读取授权资源的指定行范围", - "input_schema": { - "type": "object", - "properties": { - "resource_id": {"type": "string"}, - "revision": {"type": "string"}, - "start_line": {"type": "integer", "minimum": 1}, - "max_lines": {"type": "integer", "minimum": 1, "maximum": 500} - }, - "required": ["resource_id"], - "additionalProperties": false - }, - "output_schema_ref": "ResourceReadV1", - "effect": "read", - "scopes": ["workspace:read"], - "timeout_ms": 10000, - "max_result_bytes": 65536, - "idempotency": "safe", - "concurrency_group": "resource-read", - "availability": "ready" -} -``` - -定义由宿主/可信模块注册;用户认证、scope 与资源根由宿主注入,不接受模型提供 principal 或任意 root。`read`、`write`、`execute`、`external_write` 是策略分类,不是靠工具命名推断。 - -ToolCallV1:`call_id/tool_id/tool_version/arguments/operation_id/parent_span_id`。ToolResultV1:`ok/status/summary/structured_content/resources/citations/error/usage/truncated/next_cursor/effect_receipt_ref`。超限结果先写 artifact,再返回摘要和范围读取句柄;不把几十 MB 文本送进 prompt。 - -### 5.2 一条执行通道 - -```text -发现 → 加载 schema → schema 校验 → 授权与范围解析 → 预算/取消检查 -→ 幂等查询 → 执行 → 结果 schema/大小校验 → receipt/结果提交 → 事件 → observation -``` - -provider 原生 function call 与文档 `CALL:name + ARGS:{...}` 都归一到该通道。保留旧白名单适配,已有 `.mq.md ##` 可根据形参推导初始 schema,再允许显式描述收紧。转换不允许调用未暴露的框架内部函数。禁止对模型参数使用 eval/任意代码反序列化。 - -`tools.search` 返回已授权且当前可用的工具摘要;`tools.describe` 按 ID 返回完整 schema。核心 5–8 个工具可常驻,其余按需加载;此数量是产品起始配置,不写死框架。每次真正调用仍重新检查授权;搜索索引可列 unavailable 原因供诊断,但不能让未授权工具名字泄露私有连接信息。 - -初始支持 JSON Schema 的明确子集并公开能力;不支持的 schema 拒绝注册,不静默放宽。原生工具能力、并行工具调用、图片输入、结构化输出分别探测;纯文本兼容 provider 继续走 CALL,但并发和可靠性承诺按测试能力开放。 - -### 5.3 并发、MCP 与程序化执行 - -独立只读调用可并发,默认最多 4 个;修改同一资源的调用串行且用 revision CAS。依赖链、审批与取消检查保持顺序。一个并发调用失败不丢弃其他已成功结果。 - -MCP 扩展现有 client:先完善 timeout/cancel、错误映射、工具分页与 schema、resource read/link,再按 capability 增加远程 Streamable HTTP 与连接认证。stdio 不应允许模型选择任意宿主可执行文件。连接元数据归应用,凭证通过 secret handle 注入 worker,工具输出和 trace 不记录密钥。 - -工具 annotations 只是提示,可信策略确定真实效应。外部结果全部为数据,不能提升为 standing/system。MCP resource URI 转成宿主授权 ResourceRef,不允许前端直接请求任意 file:// 或内部网地址。 - -程序化工具编排和子 Agent 为后续切片:在沙箱中仅暴露注册 dispatcher,逐次执行同样的授权、预算和效应日志;禁止通过一段脚本绕过逐工具控制。子任务继承更小权限和共享总预算,不默认开放写同一资源。 - -## 6. 输出通道与上下文 - -### 6.1 AgentOutputV1 - -```json -{ - "schema": "AgentOutputV1", - "status": "succeeded", - "answer": {"format": "markdown", "text": "已整理为三点,完整笔记见右侧。"}, - "artifacts": [{"resource_id": "res_note_01", "revision": "sha256:example"}], - "citations": [], - "validation": {"status": "passed", "report_ref": "resource:verify_01"}, - "finish_reason": "completed", - "recovery_options": [] -} -``` - -这是结果传输协议,不要求模型每次逐字生成这张 JSON。文档式编排仍可产出 `.mq.md`,框架把稳定产物、摘要与事件归一化。普通文本回答可没有 artifact 和 validation;未运行的内容标 `not_applicable/not_run`,不能填 passed。 - -channel 至少区分 `answer/artifact/progress/diagnostic`。只有 answer delta 可追加到聊天正文;工作簿 token 和工具日志进入其他通道。进度是可观察动作摘要,不要求或泄露模型内部思维链。 - -应用传 `ResponsePolicy`:detail level、目标长度、最大输出 tokens、是否允许 artifact、用户显式需求。框架负责 budget 和 finish_reason,中文字符数与最终文案由应用决定。达到 token 上限返回 `length_limited` 和完整/不完整标记,不能裁剪 JSON/代码后假装成功。 - -优先从已验证产物结构投影摘要。必要时增加一次受预算控制的摘要模型调用;摘要不得新增未经证据支持的结论。修复成功后 accepted candidate、结果正文、artifact revision 与 verification digest 必须全部一致。 - -### 6.2 ContextPackV2 - -按优先级组装:可信运行规则→最新用户目标/约束→用户选中资源范围→未决操作/成功步骤摘要→检索证据→近期对话→可回读历史。保持角色结构,不把用户/工具文本简单拼进系统指令。 - -每个 item 携带 `origin/trust/resource_ref/revision/token_estimate/priority`。预算初值建议保留模型窗口 20% 给输出与协议开销;上下文使用达到可用预算 70% 时触发整理,具体比例配置化。优先剔除可重读的完整工具输出,保留摘要、引用和失败恢复锚点。 - -Compaction 必须保留:目标、用户限制、当前计划、已完成步骤、待决写入、授权范围、输入版本、已接受产物与引用、余量。summary 绑定其 source event range 和 digest,不能当成新的已验证知识。工具输入过时须重读,不能依赖压缩摘要执行写入。 - -已有 EKC/agent memory 继续提供知识发现和复用。长期用户记忆的创建/修改/删除政策归 qdagent;网页中的指令不能自动变成长期偏好。 - -## 7. 统一资源与只读视图 - -### 7.1 ResourceRefV1 / ResourceViewV1 - -ResourceRef 统一携带 `resource_id/workspace_id/kind/media_type/revision/digest/title/size/origin/locator`;opaque ID 由宿主映射,不将浏览器 path 直接当文件权限。revision 是内容版本,generation 是知识发布代,两者不混用。 - -```json -{ - "schema": "ResourceViewV1", - "resource": { - "resource_id": "res_01", "workspace_id": "ws_01", "kind": "file", - "revision": "sha256:example", "media_type": "text/markdown", "title": "设计说明" - }, - "renderer": {"id": "markdown", "version": "1", "trust": "sanitized"}, - "render": {"format": "sanitized_html", "fragment": "

正文

"}, - "outline": [], - "locators": [], - "completeness": "complete", - "no_exec": true, - "diagnostics": [], - "next_cursor": null -} -``` - -继续把 `.mq.md` 交 `view.document`,ResourceView 只包装/扩展,不能另解释一套 Marqdo 语义。普通 `.md/.txt/代码/JSON/CSV` 走媒体类型处理,避免全仓语义编译。浏览器组件由 qdagent 实现,框架只提供可读内容、受控片段或短期授权 blob 引用。 - -`fragment`、`text`、`blob_ref` 是互斥载荷,按严格 format enum 解码。未知格式返回 unsupported,不能用 `format.includes('html')` 猜测 HTML。为空与加载失败必须有独立状态。 - -### 7.2 格式矩阵 - -| 格式 | 框架提供 | 前端消费 | 未具备能力时 | -|---|---|---|---| -| `.mq.md` | 静态 DocumentView、outline、节点/引用 | 正文、语义链接、源码切换 | 只读源码 + 明确诊断,不执行 | -| Markdown / 笔记正文 | 共享静态 Markdown→受控结构/HTML、相对资源引用 | 标题、列表、表格、代码、链接 | 纯文本 | -| 文本/代码 | 分页行片段、编码信息、行定位 | 行号与语法高亮 | 编码提示/下载 | -| JSON / CSV | 有界解析、路径/行列定位、分页 | 树/表/源码 | 原始文本,标格式错误 | -| 图片 | 授权 blob、尺寸/元信息 | 缩放/旋转/替代文本 | 下载,不暗示已做 OCR | -| PDF | blob、页元信息,可选提取插件 | PDF.js 页渲染与定位 | 文件卡;提取不可用不阻止支持的视觉预览 | -| DOCX/XLSX/PPTX | 受限转换插件,可选 PDF/HTML 派生物 | 按派生格式预览 | 未安装转换器,保留下载 | -| HTML/SVG | 默认源码;允许时经严格清洗或受限派生物 | 隔离预览 | 不以内联可执行页面显示 | -| 未知二进制/压缩包 | 元数据 | 下载卡 | 不自动解压/执行 | - -提取、预览、执行各有独立 capability。办公转换、OCR 使用受限 worker,禁宏与网络、限制时间/内存/页数/解压膨胀比;结果绑定原件 digest、转换器版本和参数。首期不承诺保真编辑。 - -### 7.3 安全、定位、缓存 - -所有读取先校验宿主授予的 workspace/resource scope,canonicalize 并处理 symlink 逃逸;读取句柄与校验对象一致,防路径检查后替换。读取原件的身份权限不可被缓存绕过。 - -预览绝不调用 `run/verify` 或有执行副作用的 view 路径;正文中的 Marqdo 调用链接只展示语义与导航,执行需单独工具调用与授权。远程图片、相对链接、资源 URL 经受控解析;下载入口不允许任意内网 fetch。 - -HTML 清洗在框架产出侧和浏览器插入侧都有明确边界;用成熟 allowlist 实现而非正则。禁止 script/event handler、危险 URI、任意 style/form/嵌入对象。前端配 CSP;对需要交互的产物另建无权限 sandbox,不复用文档渲染器。 - -缓存 key:workspace + resource ID + revision + renderer version + render options + policy version;命中前重新授权。历史 revision 不存在就返回 `version_unavailable`,不能默默展示当前版。locator 支持 node/span/line/page/cell,失效时标 stale 并提供用户主动查看最新版的操作。 - -建议首期限制:文本片段 256 KiB、代码单次 500 行、CSV 单次 200 行;更大内容分页,完整文件保留。数值需压测校准,不作为现有系统性能声明。 - -## 8. 事件、可观测性与能力协商 - -复用 RuntimeEventV2 的 task/run/attempt/seq/event_id。拟增加事件类型:`agent.step.started/completed`、`tool.started/completed/failed`、`recovery.scheduled/exhausted`、`checkpoint.committed`、`artifact.updated`、`answer.delta/committed`、`context.compacted`。现有 `message.delta` 由兼容适配映射 answer channel,不能同时重复消费两套事件。 - -终态提交包含 accepted output manifest、last_seq、result digest;断流客户端能通过快照补齐最终答案。stream delta 是预览,最终 committed revision 是权威。统计每次尝试的 usage,摘要和修复调用分别标 purpose;未知计量保持 unknown。 - -拟新增 capability:`agent.error_v1`、`agent.checkpoint_v2`、`agent.tool_schema_v1`、`agent.output_channels_v1`、`agent.context_pack_v2`、`resource.view_v1`,以及各 media renderer 的独立版本/可用状态。保持现有 probe,新增字段向后兼容;未知 feature 当不可用。 - -trace 记录因果 ID、耗时、错误类别、参数摘要、资源版本和 effect receipt。正文与密钥按配置脱敏,不默认把用户全文件复制进日志。输出中不包含模型私有推理;可审计的是实际动作与结果。 - -## 9. 分阶段实现与文件落点 - -| 包 | 修改/新增建议 | 交付内容 | 依赖 / 退出条件 | -|---|---|---|---| -| M-A0 | `src/workbench/capabilities.rs`、`tests/workbench_contracts.rs`、新增合同 fixtures | 上述协议、旧适配、状态映射 | 先冻结跨仓字段,未知字段/版本可降级 | -| M-A1 | `ext/ai/agent.mq.md`、`plugins/agent/src/resume.rs`、新 recovery/effects 支撑模块 | 分类错误、有界修复、accepted candidate、原子检查点 | M-A0;故障注入不重复写、旧记录不冒险自动恢复 | -| M-A2 | `plugins/agent/src/lib.rs`、`mcp_client.rs`、新 tool registry/dispatcher | schema 工具、调用统一、分页与结果资源 | M-A0;未授权调用为 0,失败结果结构正确 | -| M-A3 | `src/workbench/document_view.rs`、新 resource_view、媒体适配模块 | ResourceRef/View、普通格式静态阅读、no-exec | M-A0;资源定位与安全语料通过 | -| M-A4 | `ext/ai/agent.mq.md`、`plugins/llm/src/lib.rs`、`src/workbench/run_context.rs` | 输出分通道、预算、ContextPackV2 | M-A1/2;原生和纯文本 provider fixture 都可用 | -| M-A5 | `src/runtime/` 的既有存储/事件适配、MCP 与转换插件 | 恢复对账、PDF/Office 插件、远程 MCP | M-A1/2/3;持久模式 crash/restart 通过 | -| M-A6 | plan/subtask/sandbox 扩展 | 程序化工具、有界委派与可选浏览器 | 后置;须证明任务收益和预算/效应可控 | - -先交 M-A0 与 qdagent P0 的静态阅读/错误结果修复;不要让完整 checkpoint v2 阻塞笔记预览。M-A1 可先上只读重试,写恢复待 ledger 通过再开放。新特性默认关闭直到对应合同实测通过,旧路径继续可读。 - -## 10. 验收与评测 - -所有目标是 proposed gate,尚未实测。基础机制用确定性 fake provider/tool;真实 provider 做少量单独 smoke 并记录费用,不能把随机模型输出作为唯一门禁。 - -| 编号 | 故障/任务 | 必须观察到的结果 | -|---|---|---| -| MA-T01 | 第一次 429、第二次成功 | 尊重退避、计量 2 次、最终只有一个 accepted answer | -| MA-T02 | 连续 schema 参数错误 | 一次修复后停止;工具未在无效参数下执行 | -| MA-T03 | 工具写成功但 receipt 提交前杀 worker | unknown_effect→查询对账;写计数不增加 | -| MA-T04 | checkpoint 写一半杀进程 | 读取上个完整 checkpoint 或明确 corrupt,不产生伪成功 | -| MA-T05 | 终态事件丢失、cursor 重放 | 最终快照恢复完整消息,工具执行次数不增加 | -| MA-T06 | 恢复请求重复/并发 | 同一幂等键只产生一个恢复 attempt | -| MA-T07 | 用户取消与重试定时器竞争 | 取消生效后无新工具调用,旧任务不复活 | -| MA-T08 | 执行中资源/权限改变 | stale/conflict/forbidden,不覆盖新版本 | -| MA-T09 | 恶意文本伪造 CALL/system | 不跨越工具白名单和授权范围 | -| MA-T10 | `.mq.md` 预览含写文件/联网语句 | 哨兵文件/网络计数不变;只读渲染成功或安全降级 | -| MA-T11 | 资源格式、超长输出、路径逃逸 | 正确 renderer/分页;越界拒绝;无 HTML 注入 | -| MA-T12 | 修复原文 A 得到通过验证的 B | answer/artifact/verification 都绑定 B digest | -| MA-T13 | 上下文压缩后继续 | 最新约束、待决效应、资源版本与剩余预算不丢失 | -| MA-T14 | 旧 CALL、旧 DocumentView 消费端 | 基础行为可用,能力缺失有明确返回 | - -先运行受影响的 Rust/Go/Marqdo 合同与既有隔离 runtime 金样例,再做跨仓 HTTP/browser gate。性能目标:已缓存 100 KiB 文本视图服务端 p95 < 300 ms、核心工具发现 p95 < 100 ms,基准机器/并发/冷暖缓存必须记录;第三方网络延迟单独列出。 - -## 11. 迁移、回滚与未决项 - -兼容迁移按“新增协议→双读→新写→验证→逐步移除旧适配”推进。`.mq.md` 源码与旧运行产物不批量重写;旧 resume JSON 可读取但不能自动升级成带副作用保证的检查点。v2 checkpoint/ledger 保留 schema 版本,新老版本不并发写同一运行。 - -回滚关闭新工具自动发现、输出通道或转换器时,已提交资源和最终答案仍可读;执行恢复中的任务先 drain/停止接纳,不能切回会盲重做写操作的旧路径。迁移前备份可变索引与 manifest,回滚不删除用户产物。 - -实现前验证项:现有 runtime 持久存储可提供的原子提交边界、各平台 fsync/rename 行为、LLM adapter 原生 tool call 流式兼容、转换插件部署体积。协议优先按本文保守语义实现,验证不能满足则 feature 保持不可用,不阻塞已经完成的只读预览切片。 diff --git a/doc/design/ai-skill.md b/doc/design/ai-skill.md deleted file mode 100755 index a354c54..0000000 --- a/doc/design/ai-skill.md +++ /dev/null @@ -1,29 +0,0 @@ -# Marqdo AI Skill - -| | | -|---|---| -| 状态 | 已提供 | -| 日期 | 2026-08-05(初版)· 2026-08-28(ext/web 完结复核 · ext/quantum Q8) | -| 路径 | [`skills/marqdo/`](../../skills/marqdo/)(权威);Cursor 镜像 [`.cursor/skills/marqdo/`](../../.cursor/skills/marqdo/) | - ---- - -## 目的 - -让接入方(Cursor Agent、其它支持 Agent Skills 的模型宿主)在**加载本 skill 后**即可按 v0.2 语法正确编写 / 修改 `.mq.md`,并在使用 **`ext/web` 动态站** 或 **`ext/quantum` 电路/可视化** 时遵循官方作者面(不混中英 API、不写 JSON 袋胶水;量子绘图须引用 `kind=`/`theme=` 字符串)。 - -## 内容 - -| 文件 | 用途 | -|------|------| -| `SKILL.md` | 必读:硬规则、标记表、**ext/web**、**ext/quantum(Q7/Q8)**、工作流、反模式 | -| `reference.md` | 按需:CLI、stdlib/ext 索引、web/quantum API 摘要 | -| `examples.md` | 按需:可复制样例(§13 最小站点 · §14 纠缠实验) | - -## 使用 - -- **本仓库 Cursor**:项目 skill 已在 `.cursor/skills/marqdo/`;描述含 `.mq.md` / Marqdo 触发词,可自动选用。 -- **其它 AI**:将 `skills/marqdo/` 整目录作为 skill 包导入,或把 `SKILL.md` 贴进系统/项目说明并允许模型按需打开 `reference.md` / `examples.md`。 -- **校验**:生成后执行 `marqdo run .mq.md`,按 `path:line:col` 诊断迭代。 - -语法真相仍以 [markdown-mapping.md](markdown-mapping.md) 与 [keywords.md](keywords.md) 为准;skill 是面向模型的压缩操作手册。 diff --git a/doc/design/ambient-parameters-evaluation.md b/doc/design/ambient-parameters-evaluation.md deleted file mode 100755 index 2d6bb31..0000000 --- a/doc/design/ambient-parameters-evaluation.md +++ /dev/null @@ -1,252 +0,0 @@ -# 语义评估:参数能否从上下文推断(含叙述式调用) - -> **2026-10-23 审阅裁决**:保留参数来源可见、避免隐藏调用者环境的边界;下文已被否决的 L0 建议不可重新启用。自然语言只连接和解释,不能成为隐式执行触发器;当前指导见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓)。 - -| | | -|---|---| -| 状态 | **§3 的 L0 方案已被否决**(违反「只执行标记」原则);L1/L2 结论仍有效 | -| 日期 | 2026-10-22 | -| 提出 | 「让函数参数从上下文推断,`对**n=31**执行**加一函数**` 这种写法可能吗」 | -| 方法 | 运行时实测 8 组 + 全仓库语料扫描(1322 个函数)+ 源码比对 | -| 相邻 | [call-syntax-from-marks.md](call-syntax-from-marks.md)(**接替本文 §3 的设计**)· [paren-call-and-readable-invocation.md](paren-call-and-readable-invocation.md) | - -> **后续更正**:本文 §3 提出的 L0「叙述式调用」用**未标记的词**(`执行`)触发调用, -> 这会破坏「叙述默认安全、只有标记才执行」的底层原则,已被否决。 -> 在「只执行标记」约束下重新设计的调用语法见 -> [call-syntax-from-marks.md](call-syntax-from-marks.md) -> (含树遍历 vs 字节码 3.8× 实测、叙述顺序导致位置绑定翻转的实验)。 - ---- - -## 0. 结论:你的示例其实**不需要**隐式推断 - -先把一个关键事实摆出来:**你的例子里 `n=31` 明明写在那儿**。 - -```markdown -# main - -对**n=31**执行**加一函数** -``` - -`n` 的绑定**就写在句子里**,这不是「从上下文推断」,这是**具名实参换了语序**。 -所以这个写法需要的是**新的叙述式调用语法**,不是新的作用域语义。 - -它今天跑出来的结果很能说明问题:**无输出、无报错、退出码 0**。 -不是参数推断失败,而是 `执行**加一函数**` 里的裸名字**只是被求值然后丢弃**, -从来没被当成一次调用。 - -三层拆解: - -| 层 | 写法 | 需要什么 | 裁决 | -|----|------|---------|------| -| **L0 叙述式调用** | `对**n=31**执行**加一函数**` | 只要语法糖(绑定仍在句中) | ✅ **可做,且安全** | -| **L1 就近绑定** | 上一行 `**n=31**`,下一行 `执行**加一函数**` | 段落级隐式作用域 | ⚠️ 能做但危险,不建议 | -| **L2 真隐式** | 只写 `执行**加一函数**`,n 全靠上下文 | 动态作用域 | ❌ **不建议**,见 §4 | - ---- - -## 1. 实测:今天到底发生了什么 - -| # | 用例 | 实测 | 说明 | -|---|------|------|------| -| 1 | 你的示例原样 | **无输出、无报错、exit 0** | 静默 no-op | -| 2 | 同样写法 + `> print text=`n`` | `main里的n=31` | **散文行里的 `**n=31**` 真的执行了** | -| 3 | 只写 `对`加一函数`执行` | `done`,无报错 | 裸名字只被求值丢弃,**未调用** | -| 4 | `**n = 31**` + `> 加一函数`(不传参) | `missing argument for parameter n` | **函数看不见调用者的 `n`** | -| 5 | `> 加一函数 n=31` | `32` | 显式写法今天就能做 | -| 6 | `# main` 读 frontmatter `税率` | `0.1` ✅ | 入口可见 | -| 7 | `## 函数` 读同一个 `税率` | `undefined variable` ❌ | 函数不可见 | -| 8 | 浏览器 WASM 入口调用函数 | metadata + `entry_bindings` **都会传** | 见 §5,**与 CLI 不一致** | - -**第 2 与第 3 条合起来是关键**:散文行里的粗体确实会执行,但一个裸函数名在粗体里 -只是一个**表达式语句**(值算了就丢),不会变成调用。所以「看起来该调用」的句子, -实际什么也没做——又是一次静默失败(与 D9 同一类)。 - -**第 4 条是语义基石**:Marqdo 现在的作用域是**严格分离**的, -函数只能看到自己的形参与局部变量。你想要的 L2,就要拆掉这块基石。 - ---- - -## 2. 你自己的担心是对的:数据在这里 - -你提到「大项目变量名会难以使用」。我把仓库里 `lib/ ext/ examples/ tests/` 全扫了一遍: - -| 指标 | 数值 | -|------|------| -| 扫描函数数 | **1322** | -| 不同形参名 | 819 | -| **被 ≥5 个函数共用的形参名** | **130 个** | - -撞车最严重的一批: - -| 形参名 | 用它的函数数 | -|--------|-------------| -| `path` | **70** | -| `value` | 59 | -| `text` | 53 | -| `id` | 47 | -| `list` | 38 | -| `内容` | 38 | -| `路径` | 35 | -| `a` / `b` | 各 32 | - -结论很直接:**如果参数靠上下文推断,那么每次调用一个读 `text` 的函数, -它都会去捡当前作用域里的 `text` 是什么**。53 个函数在等这个值—— -撞车是常态,不是例外。这不是「大项目才有」的问题,中型项目就已经不可控。 - ---- - -## 3. L0:叙述式调用(推荐做) - -### 3.1 目标写法 - -```markdown -## 加一函数 - -对`n`我们让**n=n+1**之后返回*n* - -# main - -**结果 = 对 n=31 执行 加一函数** -> print text=`结果` # → 32 -``` - -### 3.2 语义映射(零模型改动) - -``` -对 <绑定子句> 执行 <函数名> ≡ Call { callee: <函数名>, args: [<绑定子句>…] } -``` - -也就是**纯粹换语序**的语法糖。它与今天的 - -```markdown -**结果 = > 加一函数 n=31** -``` - -产出**同一个 `CallExpr`**。因此: - -| 面 | 影响 | -|----|------| -| 契约校验(T2.1/T2.2) | **不变**(实参照常绑定与校验) | -| EKC 指纹 `collect_calls` | **不变**(callee 仍是静态名) | -| 字节码 `Op::Call(fid, argc)` | **不变** | -| 序列化 / 沙箱 | **不变** | -| `view` 渲染 | 需决定回显哪一种语序 | - -这正是它与「一等函数」「动态作用域」的本质区别:**只改写法,不改调用模型。** - -### 3.3 设计细节要定的三件事 - -1. **动词**:`执行` 目前**不是**关键字;而 `调用` **已经是**关键字(`src/aliases.rs:39` - 把 `调用` 映射到内建 `call_fn`)。两个近义词并存会混乱,需要二选一或明确分工。 -2. **绑定子句的边界**:`对 n=31 执行 …` 里 `n=31` 到 `执行` 之间是参数区; - 多参数写 `对 n=31 m=2 执行 …`。 -3. **与散文的冲突**:`对` 起头的行今天是叙述(CJK 开头 = 注释)。 - 要让这行变成代码,得给「叙述里出现 `执行 <函数名>`」一个可判定的规则, - 否则又是一处「看起来是代码、实际是注释」的静默陷阱。 - ---- - -## 4. L2:真隐式参数(不建议) - -### 4.1 它到底是什么 - -L2 = **动态作用域**(dynamic scoping):被调函数在**调用者的环境**里查找自由变量。 -历史上被反复试过、也反复放弃:早期 Lisp 改成词法作用域、Shell 的动态作用域被视为坑。 - -### 4.2 七条硬伤(每条都是具体后果,不是理论洁癖) - -| # | 问题 | 具体后果 | -|---|------|---------| -| 1 | **同名捕获** | `加一函数` 调 `记录日志`,两者都读 `text` → 日志函数静默拿到加一的局部值,输出错内容而不报错 | -| 2 | **递归自毁** | `n=n+1` 后调自身:内层看到的是**已被改过的** n(还是副本?)——必须新增一套遮蔽规则,而规则本身又会成为新的坑 | -| 3 | **无法复用** | 同一函数两次不同入参,只能反复改外部变量并祈祷调用顺序,等于把「参数」退化成全局可变状态 | -| 4 | **契约报废** | `call_arg_diag` 在**调用边界**校验实参类型;如果不传实参,就没有校验点。T2.1/T2.2 契约体系直接失效 | -| 5 | **指纹/arity 失真** | `collect_calls` 记录被调名,arity 由形参推断;隐式调用在 AST 上看起来是零参调用 → 复用预检、`plan` 能力匹配、查重全都失真 | -| 6 | **沙箱与序列化** | `sandbox.run` 以隔离方式执行文档;隐式依赖外部作用域会破坏隔离语义;环境也必须可序列化 | -| 7 | **不可审计** | 函数行为依赖看不见的上下文——这就是「全局可变状态」的经典问题,与「文档即程序、可被人读懂」直接冲突 | - -再叠加 §2 的数据(130 个名字被 ≥5 函数共用),第 1 条不是边角情况,而是默认情况。 - -### 4.3 但有一个**受限版**值得考虑 - -如果你真正想要的是「短脚本读起来顺」,那么下面这个版本是安全的: - -> **常量默认值**:允许函数在**未传入**某形参时,从**文件级常量**取值。 - -```markdown ---- -title: 报价 -税率: 0.1 ---- - -## 含税 - + `金额` - -*`金额` * (`税率`)* # 税率 未传入 → 取 frontmatter 常量 - -# main - -**a = > 含税 金额=100** # 10 -**b = > 含税 金额=100 税率=0.06** # 6,显式覆盖 -``` - -为什么它安全而 L2 不安全: - -| 维度 | L2 动态作用域 | 常量默认值 | -|------|--------------|-----------| -| 取值来源 | 调用者的**任意**变量 | 文件顶部**写一次**的常量 | -| 静态可判定 | ❌ 取决于运行路径 | ✅ 打开文件就能看到 | -| 随调用者变化 | ✅ 会变(最危险) | ❌ 不会 | -| 契约 | 失效 | 仍可校验(实参照常声明) | -| 序列化/沙箱 | 破坏隔离 | 可序列化(常量是数据) | -| 复用 | 破坏 | 不受影响 | - -**关键差别**:常量是**文档的一部分**(frontmatter 就在文件开头,人读得到), -而动态作用域的值是**运行路径的一部分**(人读不到)。 - ---- - -## 5. 顺带发现的真问题:CLI 与 Web 的环境不一致 - -实测 §1 第 6/7/8 条时发现: - -| 路径 | 函数可见环境 | 源码 | -|------|-------------|------| -| `# main`(CLI 运行) | frontmatter metadata ✅ | `src/interp.rs:473` `Env::with_metadata` | -| **普通函数调用** | 只有实参 ❌ | `eval_call` 用 `Env::new()` | -| **浏览器 WASM 入口** | metadata ✅ + `# main` 的 `entry_bindings` ✅ | `invoke_in_entry`(`src/interp.rs:365`) | - -也就是说:**同一份文档,在浏览器里函数能读到 frontmatter 常量、还能读到 `# main` -的绑定;在 CLI 里读不到。** 行为随运行面不同而不同。 - -这是一个**真实缺陷**,已记入 [D11](../research/qdagent-refactor-defects-2026-10.md): - -- 对使用者:同一文件在 Web 能跑、在 CLI 报 `undefined variable`,极难排查 -- 对设计:说明「受控环境通道」其实已经存在(只是没在 CLI 打开), - 这既是 L2 受限版的现成基础,也是必须先统一的地方 - ---- - -## 6. 建议 - -| 优先级 | 事项 | 性质 | -|--------|------|------| -| 1 | **先统一 CLI/Web 的函数环境**(D11) | 修缺陷,消除行为分裂 | -| 2 | **做 L0 叙述式调用**(`对 X 执行 F`) | 纯语法糖,零模型改动,554 回归可守 | -| 3 | 若要「少写参数」,做**常量默认值**(§4.3) | 受控隐式,静态可判定 | -| 4 | **不做 L2 动态作用域** | 七条硬伤 + 130 个撞车名 | - -关于「代码即文档」的取向,我的理解是: - -> 文档化的是**写法**(句子怎么读),不是**语义**(值从哪来)。 -> 让句子更像人话是值得的;让值从看不见的地方来,是把可读性换成不可预测性。 - ---- - -## 7. 待你决策 - -1. **L0 是否采纳?** 若采纳,动词用 `执行` 还是复用已有的 `调用`? -2. **`对…执行…` 的行如何与散文区分**(§3.3 第 3 点)?这决定它会不会变成新的静默陷阱。 -3. **常量默认值**(§4.3)要不要做? -4. **D11(CLI/Web 环境不一致)** 是否现在就修?我建议先修它,因为它会影响 L0/L2 的所有验证结论。 diff --git a/doc/design/binding.md b/doc/design/binding.md deleted file mode 100755 index f21566d..0000000 --- a/doc/design/binding.md +++ /dev/null @@ -1,187 +0,0 @@ -# Marqdo Binding · Artifact Metadata - -| | | -|---|---| -| 状态 | **Accepted · Phase 1 + Phase 2(scope lift)** | -| 日期 | 2026-09-24 | -| ADR | [0006-artifact-metadata-binding.md](../adr/0006-artifact-metadata-binding.md) | -| 讨论稿 | [doc/next/006.md](../next/006.md) | -| 实现 | `src/binding/` · `Module.metadata` · entry env lift · `sys.meta` / `sys.meta_get` · `marqdo run --bind` | - -> **边界**:核心负责「声明与解析配置」;扩展负责「解释配置的语义」。 -> **`${…}` 只出现在文件头 Artifact Metadata**——正文 / 粗体 / 调用 / 表 **永不**写 `${env…}`(否决讨论稿 §17)。正文使用已绑定的普通名字。 - ---- - -## 1. Artifact Metadata - -文件开头成对 `---` 之间为 **Artifact Metadata**(声明式元信息环境),不是「随便贴的 YAML」。 - -```text -.mq.md -├── Metadata ← Identity / Configuration / Dependencies / Bindings -└── Executable Body -``` - -- `import bind:…` / `导入` 行:模块依赖(既有语义不变)。 -- 其它 `key: value` 行:元信息;值可为字面量或 **Binding Expression**。 -- Phase 1 仅支持 **flat** 键(同级 `key: value`);块标量 `>` / `|` 收成 Text。 - -例: - -```yaml ---- -title: demo -type: llm -model: ${env.OPENAI_MODEL ?? "gpt-4o-mini"} -api_key: ${secret.OPENAI_API_KEY!} -base_url: ${env.OPENAI_BASE_URL ?? "https://api.openai.com/v1"} -import: - sys: lib/sys.mq.md ---- -``` - -加载后内部为已绑定的 `Module.metadata`(确定性快照),执行期不再对同一键反复 `getenv`。 - ---- - -## 2. Binding Expression - -外形: - -```text -${expression} -``` - -### 2.1 路径 - -```text -${namespace.name} -``` - -| Namespace | 意义 | Phase 1 | -|-----------|------|---------| -| `env` | 进程环境变量 | ✅ | -| `arg` | CLI / Runtime 绑定(`marqdo run --bind KEY=VALUE`) | ✅ | -| `sys` | 系统信息:`cwd` · `platform` | ✅ | -| `secret` | 敏感环境变量 → `Value::Secret` | ✅ | -| `config` | 配置 Artifact | 推迟 | -| `file` | 外部文件内容 | 推迟 | - -### 2.2 默认与必需 - -```text -${env.OPENAI_MODEL ?? "gpt-4o-mini"} -${secret.OPENAI_API_KEY!} -``` - -- `A ?? B`:A 缺失(未设置 / 空)则用 B。 -- `A!`:A 必须存在,否则加载失败(`config.required_binding_missing`)。 - -### 2.3 类型转换 - -```text -${int(env.MAX_TOKENS ?? "4096")} -${float(env.TEMPERATURE ?? "0.2")} -${bool(env.STREAM ?? "false")} -``` - -### 2.4 独占 value vs 插值 - -| 形态 | 语义 | -|------|------| -| `model: ${env.OPENAI_MODEL}` | **Value binding** — 保留解析后的类型(含 Secret) | -| `title: "Hello ${env.USER}"` | **Interpolation** — 结果为 Text | -| `model: gpt-4o-mini` | **Literal** — 字面量;**不会**被环境变量静默覆盖 | - ---- - -## 3. Resolution Policy - -对每个 metadata 键: - -1. 解析该键的字面量 / Binding / 插值(字面量定稿后不受 env 覆盖)。 -2. 若 CLI 提供了同名 `--bind KEY=VALUE`,**覆盖**该键的最终值(Text)。 -3. Binding 内部查找顺序(仅当表达式写出时):`arg` / `env` / `secret` / `sys` 按表达式 namespace;`??` 链从左到右。 - -推荐作者意图: - -```text -CLI --bind - → Artifact 字面量 / 已写死的 Binding 结果 - → Binding 源(env / secret / …) - → ?? 默认 -``` - ---- - -## 4. Secret - -`${secret.NAME}` → `Value::Secret`。 - -- `print` / `str` / Display → ``(不泄露)。 -- `type` → `secret`。 -- 与 Text 拼接(如 `bearer + api_key`)时**揭示**明文,供 HTTP Authorization。 -- 不得进入普通 episode / 错误信息明文(扩展作者责任;核心 Display 已遮掩)。 - ---- - -## 5. Runtime API - -| API | 语义 | -|-----|------| -| `sys.meta` / `系统.元信息` | 入口模块已绑定 metadata(map) | -| `sys.meta_get` / `系统.取元信息` | `key=` → 值或 `None` | -| `marqdo run FILE --bind KEY=VALUE` | 可重复;写入 `arg` 并覆盖同名 metadata 键 | -| `sys.env_get` | **保留**逃逸口;新代码优先 Metadata Binding | - ---- - -## 6. 错误 - -| code | 何时 | -|------|------| -| `config.required_binding_missing` | `${ns.name!}` 且源缺失 | -| `config.unknown_binding_ns` | 未知 namespace | -| `config.bad_binding` | 表达式非法 / cast 失败 | - -诊断尽量带 frontmatter 行号。 - ---- - -## 7. 与扩展的分工 - -- **核心**:解析 Metadata、resolve Binding、暴露 `Module.metadata` / `sys.meta*`,并在入口把 metadata **提升为普通变量**。 -- **`ext/ai/llm`**:构造次序为 **显式实参 → 入口作用域同名变量 / `sys.meta_get` → `sys.env_get` 回退 → 默认**。 - ---- - -## 8. Phase 2 · Metadata scope lift(Accepted) - -加载期绑定完成后,入口执行(`# main` 或唯一无参顶层对象)前,把 `Module.metadata` 的每个键注入 entry 环境,成为**普通变量**: - -```yaml ---- -model: ${env.ModelName ?? "gpt-4o-mini"} ---- -``` - -```marqdo -# main - -> print text=`model` -``` - -### 规则 - -1. 注入时机:进入入口函数之前。 -2. 冲突:形参 / 调用实参 **覆盖** 同名 metadata;程序内赋值亦然。metadata **不**覆盖已存在的绑定。 -3. `sys.meta` / `sys.meta_get` 仍可用(显式通道)。 -4. **拒绝** 正文 / 粗体 / 表 / 叙述中的 `${…}`(讨论稿 006 §17 否决)。普通语言也不在语句里 `${ENV}`。 - -### 仍推迟(P3+) - -- `config` / `file` namespace -- 嵌套 YAML map -- 显式 `override:` 糖 -- 计入 `CORE_CONSTRUCTS` diff --git a/doc/design/bracket-as-label-evaluation.md b/doc/design/bracket-as-label-evaluation.md deleted file mode 100755 index 64a6bc5..0000000 --- a/doc/design/bracket-as-label-evaluation.md +++ /dev/null @@ -1,302 +0,0 @@ -# 评定:`[描述](语句)` —— 方括号读作「人话」,圆括号读作「机器话」 - -> **2026-10-23 审阅裁决**:本文的 Classic 冲突统计和兼容取舍属于迁移历史;v2.1 默认采用描述包裹 payload,不能据旧冲突恢复默认 `[键](集合)`。保留标签的阅读/检索/步骤价值,不强制所有子表达式命名,也不把标签当作目标或权限依据。参见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓)。 - -| | | -|---|---| -| 状态 | **已决策:走「路线二 纯度」**(落地见 [label-freshness-and-repair.md](label-freshness-and-repair.md)) | -| 日期 | 2026-10-22 | -| 提案 | 「`[]()` 不是两个部分两个含义,而是 `[描述性显示文字](实际执行的简短语句)`」 | -| 方法 | 语料实测(索引 506 / 循环 44 / 方括号调用 0)+ 渲染器源码核对 + 设计史对照 | -| 相邻 | [label-freshness-and-repair.md](label-freshness-and-repair.md)(后续:纯度落地 + 标签过期检测)· [function-as-naming-philosophy.md](function-as-naming-philosophy.md) · [collection-access-link.md](collection-access-link.md) · [call-syntax-from-marks.md](call-syntax-from-marks.md) | - -> **决策**:用户选择**路线二(纯度)**——`()` 只装机器语句,取元搬进 `()`; -> 标签可省略书写但**编译器必须报错**;循环写法不追求统一,`()` 内自洽即可。 -> 落地细节、普通取元形态,以及**标签过期检测(L1 引用一致性 / L2 指纹台账 / L3 LLM 复核)** -> 见 [label-freshness-and-repair.md](label-freshness-and-repair.md)。 - ---- - -## 0. 先把提案精确化 - -你的话可以解析出三种读法,差别很大,必须先分清: - -| 读法 | `[]` 是什么 | `()` 是什么 | 语义是否变 | -|------|------------|------------|-----------| -| **A 标签化(你的原意,本文主评)** | 这个值的**人话名字**(纯描述) | 算出它的**机器语句** | **变** | -| B 命名规范化 | 更好的键名(描述取出的东西) | 仍是集合 | 不变 | -| C 内联命名 | 同时引入可引用的名字 | 算出它的语句 | 新增绑定 | - -你说「`[]()` 函数也有了落脚地」「括号里面可以写长一些」,指向的是 **A**: -**`[]` 只负责说人话,`()` 负责说准话;两者合起来才是一条完整语句。** - ---- - -## 1. 为什么我们会下意识觉得这个写法"美" - -你的直觉不是审美偏好,它对应三个**真实存在**的设计同构: - -### 1.1 超链接:可见文本 ↔ 目标 - -`` / `[可见文字](目标地址)` 的全部意义就是**给机器一个目标,给人类一个说法**。 -这是人类最早、最成功的"双面文本"。 - -### 1.2 文学编程的 chunk 名(Knuth) - -Knuth 的 `<>` 就是"可执行片段的人话名字"。 -而**文学编程的整个出发点,正是你前面说的"代码要像文章"**——这个类比不是巧合。 - -### 1.3 Marqdo 自己已经有这个形态 - -```markdown -![marqdo-out](图片路径) -``` - -- `[]` 里是**指令/说明**(`marqdo-out`、可带 key) -- `()` 里是**负载**(图片 URL / data URI) - -**语言里已经有一个"方括号说意图、圆括号放负载"的地方。** 你的提案是把这个模式提升为通则。 - -### 1.4 一个经验证据:`[]` 在实践里本来就偏"给人看" - -| 用法 | 数量 | 谁读 | -|------|------|------| -| `[键](集合)` 取元 | 506 | 机器 | -| `- [项](集合)` 循环 | 44 | 机器 | -| `[函数] 参数` 调用 | **0(可执行)** | — | -| `[函数.名] 参数` 用法说明(`lib/*` 的 `Caller:` 行) | **189** | **人** | - -**可执行的方括号调用从未被使用**;`[]` 在文档里出现最多的地方,恰恰是"给人看的用法示例"。 -这支持你的判断:`[]` 的天性更接近"描述",而不是"标识符"。 - ---- - -## 2. 提案的三个真实收益(这部分我完全同意,而且比你说的更强) - -### 2.1 收益一:两条规则变一条 —— 这是最大的价值 - -现在 `[x](y)` 是**两个部分、两个含义**(键 + 集合)。这导致前几轮那个死结: - -> `[f](args)` 想当调用,但它和 `[k](c)` **同形**;按名字消歧会打断 2 个真实文件。 - -你的重读**直接解散了这个死结**:如果 `[x](y)` 一律是"标签 + 语句", -那么**根本不存在"取元独占外形"这件事**——取元只是"`()` 恰好是个取值语句"的特例。 - -> 这是本提案最硬的结构收益:**它把一条只能容纳一种语义的外形,改造成能容纳任意语句的外形。** -> 前几轮我们反复撞墙,是因为一直默认 `()` 只能是集合。你换了默认。 - -### 2.2 收益二:嵌套取元终于可读 - -现在是: - -```markdown -**第一 = [1]([苹果](货架))** -``` - -两层嵌套,人类读者要在"货架→苹果→第1项"之间跳三次。 - -改成标签后: - -```markdown -**第一 = [货架里苹果的第一项](…机器语句…)** -``` - -**人读标签,机器读嵌套。** 你点出的"嵌套难以描述"问题被真正解决了。 - -### 2.3 收益三:循环的"来源"可见 —— 但要说清它成立的范围 - -你的原话:`- [果](篮子)` 在 Markdown 渲染里看不出"果是从篮子拿的"。 - -**这一点需要精确化,因为它决定这块值不值得改**: - -| 阅读场合 | `- [果](篮子)` 的表现 | -|---------|---------------------| -| 通用 Markdown(GitHub / VSCode 预览 / 编辑器) | 渲染成**名为「果」的链接指向「篮子」**——看不出是遍历,你的批评成立 | -| **Marqdo 自己的 `view`** | 已渲染成带 `foreach` 徽章的 `loop-card`(`src/view/render.rs:1354`)——已经看得出 | - -而取元在 `view` 里仍渲染成字面 `[键](集合)`(`render.rs:1502`),和 Markdown 链接同形。 - -**结论**:循环的"来源不可见"在**通用 Markdown 阅读器**里成立,而这恰好是大多数人的阅读场合 -(`marqdo view` 需要额外一步)。所以这条收益真实,但它其实在说另一件事: - -> **Marqdo 的语义正确性,不应该依赖读者是否用了 `marqdo view`。** -> 文档的第一载体是 `.mq.md` 本身,它在任何 Markdown 渲染器里都该读得通。 - -这比你原本的表述更有力——它把"渲染不好看"升级成"语义不可自解释"。 - -### 2.4 附带收益:标签是天然的锚点 - -你提到"点击之后跳转到对应位置"。这件事可行性很高,而且价值不小: - -- `view` 已经保留每个语句的 span(`stmt_start`),标签可以让锚点从"行号"升级为"人话定位" -- 报错信息可以说「在 **货架里苹果的第一项** 处出错」,而不是 `foo.mq.md:118` -- 对 agent 尤其有用:模型用自然语言描述定位,比用行列号稳得多 - ---- - -## 3. 结构性弱点:`()` 要变成"语句",就必须再发明一套取元 - -这是本提案**代价最大、也最容易被忽略**的一点,必须摊开。 - -若 `[]` 只是标签,那 `(菜单)` 就只表示"整个菜单",**不再表示取成员**。要取成员,`()` 内需要新语法: - -| 方案 | 形态 | 问题 | -|------|------|------| -| 点号 | `(菜单.拿铁)` | 与库路径 `txt.str_trim`、对象方法 `obj.m` 三者同形,容易混淆 | -| 函数式 | `(取 菜单 拿铁)` | 需要新内建;与自然语言"取"字冲突多 | -| 保留方括号 | `([拿铁](菜单))` | **嵌套方括号**,正是标签想消除的东西 | -| 英文式 | `(get(菜单, 拿铁))` | 破坏中文叙述风格 | - -**这就是核心张力**: - -> 你想用 `()` 装"任意机器语句",来换取 `[]` 的纯粹描述性; -> 但"取值"本身就需要一个语法,而这个语法要么是新的(增规则), -> 要么就是旧的 `[k](c)`(则 `[]` 仍然兼任键,两义仍在)。 - -换句话说:**收益一(一条规则)能不能兑现,取决于你愿不愿意新增一条取元规则。** -这不是否决理由,但必须算进成本——因为 Marqdo 的宪法是「标记即语法,少而精」, -**用一条新规则换掉一条旧规则,不必然是净简化**。 - ---- - -## 4. 描述漂移:我认为不能轻描淡写 - -你说「从语言设计上这好像又不是特别重要」。我不同意,理由三条: - -### 4.1 它是"注释"的回归 - -Marqdo 用「叙述 + 标记」取代了注释:叙述在外面说意图,标记在里面说事实。 -而标签是**贴在执行体上的、可说谎的、必须短的文本**——这正是注释的老问题。 -Marqdo 花了很大力气让"文档即程序",标签会把"文档可能是假的"重新引进来。 - -### 4.2 一旦标签成为锚点,漂移就有操作后果 - -你在 §2.4 里期望标签用于跳转与定位。那么: - -- 报错说「在 **安全读取** 处失败」,而实际代码是写入 → **错误信息也撒谎** -- agent 用标签定位 bug → 被标签误导 -- 点击跳转跳到一段与描述不符的代码 → 读者信任崩塌 - -**标签的可信度必须与它的用途匹配。** 纯装饰可以漂移;一旦用于定位,就必须可校验。 - -### 4.3 安全面:标签是 agent 可读的攻击面 - -Marqdo 是 agent 框架。标签是**作者可控的自然语言**,而模型天然倾向相信自然语言。 -「标签写:只读校验;`()` 里:删除文件」这类不一致,从"文档瑕疵"升级为**误导 agent 的通道**。 - -**所以我建议把漂移当成一条可检查的不变量,而不是接受它的存在**: - -| 缓释手段 | 说明 | 成本 | -|---------|------|------| -| ① 标签永不参与绑定 | 纯显示,不进符号表、不进作用域 | 零 | -| ② 词重叠校验 | `check` 检查"标签里提到的名字"是否至少有一个出现在 `()` 里;全不重叠 → warn | 低 | -| ③ trace 双输出 | 错误/trace 同时给标签与 `()` 原文 | 低 | -| ④ 策略不看标签 | 沙箱/权限判定只读 `()` 的语义,绝不读标签 | 设计约束 | - -其中 ② 最划算:它能抓住**最恶劣的一类漂移**(标签说 A,代码做 B), -而对"标签写得更细"这种正常情况不误报。 - ---- - -## 5. 采用风险:可能重演 v0.3 废除的"仪式感" - -v0.3 废除 `+ \`名\`` 形参表的原话理由是:**「仪式感强;函数头像另一套签名语言,与正文脱节」**。 - -强制每个访问都配一段人话标签,是**同一类仪式**。两种可预测的退化: - -1. **凑数**:作者写 `[x](…)`、`[价格](…)`——标签退化成变量名,等于没有 -2. **噪音**:标签越写越长,正文被切碎,扫描性下降 - -这不是反对,而是提醒:**标签的价值只在"写得比键更有信息"时成立**。 -所以设计上应当考虑"**可以省略**",但一旦可省略,`[]` 就又变成可选键 → 歧义回归。 - -**这个矛盾必须在设计里正面解决,不能靠自觉。** - ---- - -## 6. 迁移面(实测) - -| 受影响的写法 | 数量 | 文件 | -|------------|------|------| -| `[键](集合)` 取元 | **506 处** | 136 个文件 | -| `- [项](集合)` 循环 | **44 处** | 24 个文件 | -| `[函数] 参数` 可执行调用 | **0** | (189 处是 `lib/*` 的 `Caller:` 说明行,不执行) | - -**危险点**:如果 `[]` 改为"纯标签",那 506 处取元的**含义会变**(`(菜单)` 变成整个菜单), -而且是**同形换义**——同一段文本含义变了、还不报错。这是最坏的一类变更(参见 D9)。 - -所以若走这条路,**必须硬报错 + 版本门**:旧写法在新版本下直接报 -「`[键](集合)` 已改为 `[描述](语句)`,请写成 X」。 -另有一个好消息:**可执行方括号调用量为 0**,所以"把 `[f] args` 收编进新形式"是零迁移成本。 - ---- - -## 7. 两条落地路线 - -### 路线一:双层(推荐,兼容) - -> **规则一句话:`[]` 永远是「这个值的人话名字」;`()` 永远是「怎么算出它」。** - -- **长形(新增)**:`[描述](语句)` —— 承载调用、复杂取元、循环 -- **短形(现状保留)**:`[键](集合)`、`- [项](集合)` 定义为长形的**缩写** -- 文档里显式承认:短形是历史妥协,`[]` 在短形中兼任键 - -| 优 | 劣 | -|----|----| -| 零迁移(506 处不动) | 短形的"两义"仍在(但被定义为可解释的缩写) | -| 调用终于有落脚地(且 0 成本收编) | 规则仍是"一条 + 一个特例",不是纯一条 | -| 嵌套可读、循环可写清来源 | | -| 标签可以逐步引入,不强迫 | | - -### 路线二:纯度(一条规则到底) - -> `()` 只装机器语句,取元必须搬进 `()`。 - -必须同时决定:**`()` 内取元用什么形式**(§3 表),然后迁移 506 处 + 版本门。 - -| 优 | 劣 | -|----|----| -| 语义最纯,教学最简 | 需新增取元规则(可能不是净简化) | -| `[]` 完全自由,可写很长的描述 | 506 处迁移,同形换义风险 | -| 与 Markdown 链接语义完全一致 | 新取元语法与库路径/方法调用需要消歧设计 | - ---- - -## 8. 我的评定 - -**这是本系列里结构上最强的一个提案**,因为它第一次正面回答了"为什么 `[]()` 一直不肯就范": -不是我们选错了语义,而是我们把一个"双面文本"当成了"两段语义"。 - -| 维度 | 评分 | 说明 | -|------|------|------| -| 哲学自洽性 | ★★★★★ | 与超链接、文学编程、`![alt](src)` 三处同构;且"文档自解释"优于"依赖 view 渲染" | -| 解决问题 | ★★★★☆ | 解散 link-call 死结、治嵌套可读性、治循环来源——三个真问题 | -| 规则净简化 | ★★★☆☆ | 收益是"两规则→一规则",但代价可能是"新增一条取元规则" | -| 迁移风险 | ★★☆☆☆ | 506 处同形换义,必须硬报错;但可执行方括号调用为 0 是利好 | -| 漂移风险 | ★★★☆☆ | 比你估计的重(注释回归 + 锚点说谎 + agent 攻击面),但可用 ② 词重叠校验兜住 | -| 采用风险 | ★★★☆☆ | 有重演 v0.3"仪式感"的可能,需正面解决"可省略 vs 歧义" | - -**我的建议**:走 **路线一(双层)**,但把"长形"作为**推荐写法**、把文档里的示例全部改成长形, -让短形成为"读得懂但不必写"的兼容层。这样: - -- 你今天就能拿到全部三个收益(描述性、嵌套可读、循环来源) -- 506 处零迁移 -- 调用终于有家,且成本为零 -- 未来若要纯度,可以在长形已被广泛使用后,再决定是否废弃短形 - -**一条具体建议**:先把 §4 的 ②(词重叠 warn)做出来。 -它让"标签"从"可能说谎的装饰"变成"**可被机器轻度核验的描述**"—— -这一步做完,标签才配得上你要给它加的"AI 定位锚点"和"点击跳转"这两个职责。 - ---- - -## 9. 待你决策 - -1. **路线一(双层)还是路线二(纯度)?** -2. 若路线二:`()` 内的取元用哪种形式(点号 / 函数式 / 其他)?——这决定要不要新增规则。 -3. **标签可否省略?** 若可,省略时算"以 `()` 的文字为标签",还是要额外标记? -4. **是否采纳 §4.2 的"词重叠校验"**?我认为它是这套设计能否安全的支点。 -5. 循环的新写法你倾向哪一种: - - `- [从篮子取出的每个果子](遍历 篮子 为 果)` - - `- [篮子里的果子](篮子 → 果)` - - 保留 `- [果](篮子)` 作短形 diff --git a/doc/design/bracket-call-modifiers.md b/doc/design/bracket-call-modifiers.md deleted file mode 100755 index db1d058..0000000 --- a/doc/design/bracket-call-modifiers.md +++ /dev/null @@ -1,54 +0,0 @@ -# 方括号标记调用与前置修饰语 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-09-14 | -| 相关 | [call-arguments.md](call-arguments.md) · [collection-access-link.md](collection-access-link.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) | - ---- - -## 1. 动机 - -无标记时,修饰语+函数名与函数名+实参都是词列,**无法消歧**。消歧标记必须来自 Marqdo 语法,**不能**依赖任一自然语言词法(「的」、形容词位置等)。 - -## 2. 形状 - -```text -修饰语… [函数名] 实参… -``` - -| 例子 | 含义 | -|------|------| -| `[问候] marqdo` | 调用 `问候`,位置实参 | -| `礼貌 [问候] marqdo` | 另加 `礼貌=True` | -| `正式 礼貌 [问候] marqdo` | `正式=True` `礼貌=True` | -| `[结账摘要] 品名="拿铁" 杯数=2` | 仅具名实参 | -| `[问候] ([格式化] `名字`)` | 嵌套:内层整段用 `()` | - -旧形保留:`> 问候 …`、`**问候 …**`、`礼貌=True` 显式具名。 - -## 3. 与取元 / foreach - -| 形状 | 语义 | -|------|------| -| `[X](Y)`(`]` 后**紧邻** `(`) | 取元 | -| `[X]`(`]` 后不是 `(`) | 函数名标记 | -| `- [X](Y)` | foreach | - -## 4. 修饰语绑定 - -- `[` 前按空白切开;每段为标识(可 `` `名` ``)。 -- 降为 `Named(名, Bool(true))`,再与 `]` 后实参合并。 -- 与显式同名具名冲突 → 诊断。 -- **核心不剥语言词缀**;形参叫 `礼貌` 则写 `礼貌 [问候]`。 - -## 5. AST - -`CallExpr.pre_modifiers: Vec`;求值/字节码在绑参前展开。 - -## 6. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-14 | 初稿并落地 | diff --git a/doc/design/browser-marqdo-wasm.md b/doc/design/browser-marqdo-wasm.md deleted file mode 100755 index 2bc693b..0000000 --- a/doc/design/browser-marqdo-wasm.md +++ /dev/null @@ -1,401 +0,0 @@ -# 浏览器 Marqdo(WASM 解释器)设计 - -> 2.7.0 维护说明:独立的 browser-hello 与 browser-media 演示已删除。下文保留既有能力设计与宿主边界,当前可运行工程使用 browser-app;底层计数器冒烟夹具位于 tests/wasm/counter.mq.md。Canvas、音频等仍是 lib/browser 的宿主能力,不宣称当前 browser-app 演示包含这些交互。 - - -| | | -|---|---| -| 状态 | **Accepted(设计锁定)** · 实现见路线图 C0–C5 | -| 日期 | 2026-09-01 | -| ADR | [0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) | -| 路线图 | [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) | -| 相关 | [ext-web.md](ext-web.md) · [bytecode.md](bytecode.md) · [web-assets-and-images.md](web-assets-and-images.md) · [table-cell-expressions.md](table-cell-expressions.md) | - ---- - -## 0. 一句话 - -**源码只有 `.mq.md`;浏览器跑与 CLI 同构的 Marqdo VM(WASM);JS 只做宿主桥与加载器,不做业务语言。** - ---- - -## 1. 目标与非目标 - -### 1.1 目标 - -| # | 目标 | -|---|------| -| G1 | 浏览器内执行合法 `.mq.md`(至少 `# main` + 打印/绑定/分支/循环/表/调用) | -| G2 | 与主机 **tree**(及后续 **bytecode**)金样在共享子集上 stdout/返回值一致 | -| G3 | 作者用 GFM 表声明交互(选择器 / 事件 / 调用),对称于 `样式装配` | -| G4 | 仓库源码树可不含业务 `.js`;允许提交或由工具生成 `marqdo.wasm` + 官方 loader | -| G5 | `import lib/…` 在浏览器可用(嵌入式 `lib/` 或打包进 wasm) | - -### 1.2 非目标(本波 / C0–C3) - -| # | 非目标 | -|---|--------| -| N1 | 在浏览器复刻 axum、`web_listen`、SQLite 服务端、admin UI | -| N2 | `plugin.load` 加载原生 `.so` / 浏览器内 dlopen | -| N3 | 把整站 `plugins/web` ABI 原样搬进 WASM | -| N4 | 把 `.mq.md` 编译成独立机器码 WASM(异于「解释器上 WASM」) | -| N5 | 强制内容站必须加载 WASM(纯 SSR 站可继续零客户端逻辑) | - ---- - -## 2. 架构 - -``` -┌─────────────────────────────────────────────────────────┐ -│ Page (HTML shell from ext/web SSR or static) │ -│ ┌──────────────┐ ┌─────────────────────────────────┐ │ -│ │ DOM / CSS │ │ Official JS loader (thin) │ │ -│ └──────▲───────┘ │ - WebAssembly.instantiate │ │ -│ │ bridge │ - marqdo_run_source / on_event │ │ -│ │ └──────────────┬──────────────────┘ │ -│ │ │ │ -│ │ ┌──────────▼──────────┐ │ -│ │ │ marqdo.wasm │ │ -│ │ │ parse → load → │ │ -│ └──────────────│ Interpreter | Vm │ │ -│ host_dom_* │ HostContext(browser)│ │ -│ host_fetch_* │ embedded lib/ │ │ -│ └─────────────────────┘ │ -└─────────────────────────────────────────────────────────┘ - -Server (unchanged): - marqdo run / plugins/web (axum) — SSR, DB, auth, full site -``` - -**原则:** 一套语言语义;**HostContext 分型**(`native` vs `browser`),不是两套语法。 - ---- - -## 3. 与现有流水线对齐 - -主机今日(见 `src/lib.rs`): - -``` -path → fs::read → load_module → Interpreter|Vm → HostContext(native) -``` - -浏览器目标: - -``` -source: &str (+ optional import map) - → load_module_from_memory - → Interpreter|Vm (capture stdout) - → HostContext(browser caps) - → { ok, stdout, value_json, error } -``` - -公共库 API(C0/C1 必须落地): - -| API | 职责 | -|-----|------| -| `run_source(source, opts) -> Result` | 无路径入口;cwd/fs_root 虚拟 | -| `RunOptions` 浏览器默认 | `allow_fs_write=false`, `allow_exec=false`, `allow_net=false`(net 经显式 bridge 再开) | -| `load` 导入 | `lib/**` → `embedded_lib`;用户模块 → JS 注入的 `HashMap` | - -后端优先级: - -1. **C1:tree**(与默认 CLI 一致,调试简单) -2. **C2+:bytecode** 可选(体积/性能;金样双后端) - ---- - -## 4. Cargo / 制品布局 - -### 4.1 Feature 门(核心 crate `marqdo`) - -| Feature | 默认(native) | `wasm-core` | 作用 | -|---------|----------------|-------------|------| -| `cli` | on | off | `main` / clap 仅 bin | -| `view` | on | off | `tiny_http` 文档浏览器 | -| `net-host` | on | off | `ureq` HTTP 客户端 | -| `plugin-host` | on | off | `libloading` 原生插件 | -| `exec-host` | on | off | `std::process` / foreign | -| `fs-host` | on | off | 真实磁盘读写(可读可后续经 VFS 桥) | -| `wasm-core` | off | on | 浏览器子集编译开关 | - -`wasm32-unknown-unknown` 构建:**不得**链接 `libloading`、`ureq`、`tiny_http`、TTY `libc`。 - -### 4.2 包 - -| 路径 | 角色 | -|------|------| -| `marqdo`(根) | 核心;feature-gate | -| `crates/marqdo-wasm` | `cdylib`:`mq_*` ABI + `js/marqdo-bridge.js` | -| `ext/web` 或 `web/browser` | L1:`浏览器.运行` / `交互装配`(C3+) | -| `examples/browser-app/` | 静态页 + wasm 冒烟 | -| `tests/browser/` 或金样脚本 | Node/wasmtime 跑 `run_source` 对齐 | - -发行:`marqdo wasm build`(C2 CLI 糖)或 `wasm-pack build crates/marqdo-wasm`。 - ---- - -## 5. 宿主能力矩阵 - -| 能力 | Native | Browser C1 | Browser C3+ | -|------|--------|------------|-------------| -| `print` / 捕获 stdout | ✓ | ✓ → 可镜像 `console` | ✓ | -| `input` | stdin / preset | **仅 preset / JS 喂入** | 可选 prompt 桥 | -| builtins / 表 / 算术 | ✓ | ✓ | ✓ | -| `lib/math` `lib/json` `lib/collection` | ✓ | ✓(embedded) | ✓ | -| `lib/fs` 真磁盘 | ✓ | ✗ 明确报错 | 可选 OPFS/VFS 桥 | -| `lib/net` ureq | ✓ | ✗ | `fetch` 桥(异步模型见 §7) | -| `plugin.load` | ✓ | ✗ | ✗(改 L1 浏览器专用) | -| `exec` / foreign | ✓ | ✗ | ✗ | -| DOM / 事件 | ✗ | stub | **交互装配** | -| `sleep` | thread | 0 或 JS timer(异步) | timer | - -错误策略:**显式失败**(诊断字符串含 `unavailable in browser wasm`),禁止静默空成功。 - ---- - -## 6. 交互装配(C3,对称样式装配) - -### 6.1 作者面(示例) - -```markdown ---- -import: - json: lib/json.mq.md ---- - -# main - -*`count` = 0* - -`wire` = - -| @ | 选择器 | 事件 | 调用 | -|---|--------|------|------| -| 1 | "#bump" | click | bump | - -**`wire`** - -## bump -*`count` = count + 1* -*`label` = > str count* -*`patch` = > json.set map=None key="#count" value=label* -**> json.set map=None key="set_text" value=patch** -``` - -`# main` 的返回值是 **wire 表**(`@` 行向记录列表)。Loader 调用 `mq_boot`,再 `wireEvents`。 - -### 6.2 桥约定 - -| 步骤 | API | -|------|-----| -| 启动 | `mq_boot(source)` → `{ ok, value }`;`value` = wire 列表或 `{ wire: [...] }` | -| 事件 | Loader `addEventListener` → `mq_call(fn, {"event":"click"})` | -| 回写 | 返回 Map 可含 `set_text`: `{ "#sel": "text" }`(仅 `textContent`) | - -行键名认:`选择器`/`selector`、`事件`/`event`、`调用`/`call`。 - -含 `/` 的 CSS 等单元格仍 **引号优先**(见 [table-cell-expressions.md](table-cell-expressions.md))。 - -L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表即可验收。 - ---- - -## 7. 异步模型(C4) - -锁定:[ADR 0003](../adr/0003-browser-async-effects.md)。 - -处理器返回 Map 可含(与 `set_text` 并列): - -| 字段 | 含义 | 完成后 `mq_call` 实参 | -|------|------|----------------------| -| `fetch` | `{ url, method?, then, headers?, body? }` | `{ ok, status, body, error? }` | -| `after` | `{ ms, then }` | `{ ok: true }` | - -Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**在 WASM 内阻塞。 - -示例见 `examples/browser-app/static/app.mq.md`。 - ---- - -## 8. 安全 - -| 项 | 规则 | -|----|------| -| 默认能力 | 无磁盘写、无 exec、无任意 net | -| 源码来源 | 同源或构建时嵌入;不默认 `eval` 远程不可信脚本除非站点显式开启 | -| DOM | 仅经装配表/白名单 API;不暴露任意 `innerHTML` 字符串执行第三方脚本 | -| CSRF / Cookie | 浏览器 Marqdo **不替代**服务端鉴权;cookie 仍走 HTTP | - ---- - -## 9. 与 `ext/web` 分工 - -| 层 | 负责 | -|----|------| -| 服务端 `plugins/web` | 路由、DB、会话、SSR HTML、样式/头/图装配 | -| 页面壳 | `头装配` 挂 `module` → `marqdo-bridge.js`;`static` 提供 `.wasm` | -| 浏览器 L1 | `客户端挂载` / `client_embed`;效应约定见 ADR 0003 | -| 核心 / crate | `run_source`、`BrowserSession`、`marqdo-wasm` ABI | - -挂载示例: - -```markdown -`头` = - -| 关系 | 地址 | -|------|------| -| module | /static/marqdo-bridge.js | - -*p = > page.头装配 表=头* -``` - -```bash -marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js -# app.static dir=static -``` - -业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-app/`)。 - ---- - -## 10. 测试与验收 - -| 级 | 内容 | -|----|------| -| 单元 | `run_source("…# main\n> print…")` native 与 wasm 同测 | -| 金样子集 | `tests/structure/hello.mq.md` 等无 fs/net/plugin 的样例 | -| 浏览器冒烟 | `examples/browser-app`:按钮点击 → Marqdo 函数 → 改 DOM 文本 | -| 回归 | CI:`cargo test` native;另 job `wasm-pack build` / `cargo check --target wasm32-unknown-unknown --no-default-features --features wasm-core` | - ---- - -## 11. 文档与技能同步 - -- ADR 0002、本文、路线图 C0–C5。 -- `.cursor/skills/marqdo/SKILL.md`:补充「浏览器 WASM / 交互装配 / 引号 CSS」。 -- `CHANGELOG`:Unreleased 记录设计锁定与各 C 完成项。 - ---- - -## 12. 风险 - -| 风险 | 缓解 | -|------|------| -| wasm 体积过大 | `release-wasm` profile(`opt-level=z` + LTO + strip);`marqdo wasm build` 打印 KiB,有则跑 `wasm-opt -Oz` | -| 异步拖垮语言 | ADR 0003 效应表;不阻塞 WASM | -| Feature-gate 伤 native | 默认 features = 今日行为;CI 全绿再合 | -| 作者误以浏览器替代服务器安全 | 文档强调鉴权在服务端 | -| 会话要 bytecode | **未做**:`BrowserSession` 固定 tree(缺 entry-env invoke);`run_source` 已支持 bytecode | - ---- - -## 14. C5 硬化(已落地) - -| 项 | 状态 | -|----|------| -| `profile.release-wasm` + `marqdo wasm build` 体积报告 | done(~0.9 MiB) | -| 可选 `wasm-opt` | done | -| `run_source` bytecode 金样 | done | -| 规范 bridge + 构建拷贝 | done(`crates/marqdo-wasm/js/`) | -| Node ABI 冒烟 | done(`tests/wasm`) | -| 站点 `头装配` / L1 `client_embed` | done | -| 会话 bytecode / view 断点复用 | **非本版目标** | - ---- - -## 16. 路线 D — 作者零 JS(Active) - -路线图:[browser-wasm-d.md](../roadmap/browser-wasm-d.md)。 - -**原则:** 业务与交互 100% `.mq.md`;`marqdo-bridge.js` 仅宿主胶。作者仓库可不含自写 `.js`。 - -### 16.1 一键挂载 - -| API | 含义 | -|-----|------| -| `mount({ wasmUrl, source \| sourceUrl, … })` | `loadWasm` → `boot` → `wireEvents` → 初始效应 | -| `script[data-mq-source-url]` / `data-mq-wasm` | 模块脚本属性自启 | -| `#marqdo-boot` | `application/json` 配置块 | -| `data-mq-playground` | 官方 playground(`#src,#run,#out`),仍非业务 JS | - -`ext/web`:`client_embed` / `客户端挂载` 参数 `bridge`、`wasm`、`source`、`boot`(默认 true)。 - -```bash -marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js -# app.static dir=static -# intro 或主区嵌入 > web.client_embed source="/static/client.mq.md" -``` - -### 16.2 DOM / 表单效应(D3) - -与 `set_text` / `fetch` / `after` 并列(白名单;**默认无**任意脚本注入): - -| 字段 | 作用 | -|------|------| -| `set_text` | `textContent` | -| `set_value` | input/textarea/select 的 `value` | -| `set_attr` | 属性;值为 `null`/`false` 则 `removeAttribute` | -| `set_class` | `className` 字符串 | -| `toggle_class` | `{ "#sel": "cls" }` 切换 class | -| `set_html` | **仅**键前缀 `#trusted` 的选择器才写 `innerHTML`;其它键忽略 | - -Wire 行可选 `值选择器` / `value_from`:事件触发时把该节点内容写入实参 `value`。 -事件实参默认含:`event`、`value`、`checked`、`id`(来自 event.target);`submit` 另含 `fields` 表单字典。 - -L1:`web.dom_patch` / `网页.DOM补丁` 合并效应键;`web.text_patch` / `网页.文本补丁` 快捷 `set_text`。 - -### 16.3 非目标(D) - -| # | 非目标 | -|---|--------| -| D-N1 | 用 Marqdo 重写 bridge 自身 | -| D-N2 | 作者手写业务 JS / TS(官方桥内机制允许) | -| D-N3 | ~~开放无前缀的 set_html~~(E 已允许任意选择器;内容由 MQ 产出) | - ---- - -## 17. 路线 E — 前端能力补齐(Active) - -路线图:[browser-wasm-e.md](../roadmap/browser-wasm-e.md)。 - -**原则:** 唯一硬禁是**作者手写业务 JS**。官方 bridge 可实现列表装配、路由、storage、WebSocket、内部模板/轻量 VDOM 等;作者只写 `.mq.md` + 效应表。 - -| 波 | 要点 | -|----|------| -| E1 | `set_style` / `focus` / `blur` / `scroll_into`;wire `委托`;键盘事件 | -| E2 | `set_html` / `replace_children` / `render_list` | -| E3 | `navigate` + `popstate`(选择器 `window`) | -| E4 | `storage` `{ op, key, value?, scope?, then? }` | -| E5 | `ws` `{ op: open\|send\|close, … }` | -| E6 | `fetch_all` / `interval` / `clear_interval` / fetch `fields` | - -### 17.1 效应速查(E) - -| 字段 | 含义 | -|------|------| -| `set_style` | `{ "#sel": { color: "red" } }` 或 `{ "#sel": "color:red" }` | -| `focus` / `blur` | `"#sel"` 或选择器数组 | -| `scroll_into` | `"#sel"` | -| `set_html` / `append_html` / `replace_children` | 写/追加 HTML(MQ 产出;XSS 自负) | -| `render_list` | `{ "#sel": { tag, items } }` | -| `remove` | 选择器或数组,删除节点 | -| `add_class` / `remove_class` | classList | -| `navigate` | `{ url, replace?: bool }` | -| `storage` | `{ op, key, value?, scope?: local\|session\|cookie, days?, then? }` | -| `ws` | `{ op: open\|send\|close, … }` | -| `fetch_all` | `{ requests: []\|map, then }` | -| `interval` / `clear_interval` | 定时 | -| `clipboard` / `download` | 剪贴板 / 触发下载 | -| `fetch.fields` | → FormData | - -Wire 列:`委托` / `delegate` = 在容器上监听,目标须 `closest(delegate)`;选择器 `window` 绑 `window`。 - -## 15. 决策摘要 - -| 问题 | 答案 | -|------|------| -| 路线? | **C**:解释器/VM → WASM | -| 作者语言? | 仅 `.mq.md` | -| JS 角色? | Loader + 宿主桥 | -| 服务端? | 保留;不塞进浏览器 | -| 第一步实现? | C0 门控可编译 + C1 `run_source` 打印闭环 | diff --git a/doc/design/bytecode.md b/doc/design/bytecode.md deleted file mode 100755 index 2ddd86a..0000000 --- a/doc/design/bytecode.md +++ /dev/null @@ -1,90 +0,0 @@ -# Marqdo 字节码(M5 原型) - -| | | -|---|---| -| 状态 | 进行中(原型) | -| 日期 | 2026-08-04 | -| 相关 | [roadmap/interpreter.md](../roadmap/interpreter.md) · Phase I 树遍历 | - ---- - -## 1. 目标 - -在保留树遍历后端(`--backend tree`,默认)的同时,提供栈式字节码 VM(`--backend bytecode`),使**核心金样例** stdout 与树遍历 bit 一致。 - -``` -.mq.md → load/parse → Module AST - ├─ tree-walk - └─ compile → Chunk → VM -``` - ---- - -## 2. 指令集(草案 / 原型已实现子集) - -| Op | 栈效应 | 说明 | -|----|--------|------| -| `Constant i` | → v | 常量池 | -| `True` / `False` / `None` | → b | | -| `Pop` | v → | | -| `GetLocal i` / `SetLocal i` | | 当前帧槽 | -| `GetGlobal i` / `SetGlobal i` | | 名字在常量池(文本) | -| `Add` `Sub` `Mul` `Div` `Negate` `Not` | | | -| `Equal` `NotEqual` `Greater` `GreaterEqual` `Less` `LessEqual` | | | -| `Jump a` / `JumpIfFalse a` / `JumpBack a` | | 相对/绝对跳转(原型用绝对 u16) | -| `Print` | v → | 弹出并写 stdout | -| `BuildList n` | v… → list | | -| `GetIndex` | list, i → v | foreach 用 | -| `Call f argc` | args… → ret | 用户函数(按形参序压栈) | -| `Return` | | 返回 / 结束帧 | -| `Interp n` | parts… → text | n 个交错 Lit/Var 标记后的拼接(简化:编译期展开为常量+拼接) | - -原型实现以 `src/bytecode/` 为准;未列出的 Op 不存在于当前构建。 - ---- - -## 3. 编译约定 - -- 每个 Marqdo `Function` → 一个 `FnChunk`(含 `name`、`params`、`code`、`constants`)。 -- 模块级 `Program`:函数表 + 入口名(`main` 或唯一无参 level-1)。 -- 局部变量:函数体内首次赋值/形参分配槽位。 -- 嵌套 `##`:编入同一 `Program`,按名 `Call`;查找规则对齐树遍历(子树优先,再顶层)。 -- `and` / `or`:短接跳转。 -- 分支 / while:`JumpIfFalse` + `Jump` / `JumpBack`。 -- foreach:`BuildList` 或已有 list 全局/局部 → 索引循环。 - ---- - -## 4. 覆盖表(M5 原型) - -| 金样例 | tree | bytecode | -|--------|------|----------| -| `structure/hello` | ✅ | ✅ | -| `structure/branch` | ✅ | ✅ | -| `structure/loop` | ✅ | ✅ | -| `structure/collection` | ✅ | ✅ | -| `keywords/print` | ✅ | ✅ | -| `keywords/bool-logic` | ✅ | ✅ | -| `structure/nested-call` | ✅ | ✅ | -| `structure/positional-call` | ✅ | ✅ | -| `structure/import/*` | ✅ | ✅(导入模块树后编译) | -| `structure/ns/*` | ✅ | ✅ | -| `tests/errors/*` | ✅(非零退出) | 同 tree 语义(编译期/运行期诊断) | - -核心金样例双后端已对齐;后续可扩展 Op、优化与更好的调试信息。 - ---- - -## 5. CLI - -```bash -marqdo run FILE --backend tree # 默认 -marqdo run FILE --backend bytecode -marqdo run FILE --dump-bytecode # 反汇编后仍可按 backend 执行 -``` - ---- - -## 6. 非目标(本原型) - -优化、寄存器分配、GC、与树遍历指令级调试对齐、独立 sema IR。 diff --git a/doc/design/call-arguments.md b/doc/design/call-arguments.md deleted file mode 100755 index 57899dc..0000000 --- a/doc/design/call-arguments.md +++ /dev/null @@ -1,65 +0,0 @@ -# 调用实参:具名与位置 - -> **2026-10-23 适用范围校正**:本文保留早期调用尾部规则和历史示例,不是 v2.1 全部调用语法。当前已有 `f(args)` 及具名实参;默认紧邻 `](` 是描述包裹 payload,不再是下文所述的 Classic 取元。语法审阅与开发取舍见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓),当前行为须由默认模式测试复核。 - -| | | -|---|---| -| 状态 | 已定(v0.1 增补;2026-09-14:方括号标记调用) | -| 日期 | 2026-08-07 | -| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords.md](keywords.md) · [module-namespace.md](module-namespace.md) · [bracket-call-modifiers.md](bracket-call-modifiers.md) | - ---- - -## 1. 目标 - -`>` 调用同时支持: - -| 形式 | 示例 | 说明 | -|------|------|------| -| **具名**(保留) | `> 问候 谁=Marqdo` | `名=值`;值可含空格(至下一 `名=`) | -| **位置**(新增) | `> 问候 Marqdo` | 按形参声明顺序绑定 | -| **方括号标记**(增补) | `礼貌 [问候] Marqdo` | `[函数名]` 消歧;`[` 前裸词 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md) | - -二者可混用:位置实参按「尚未被具名绑定的形参」从左到右填充。具名不可绑定同一形参两次;位置实参不得出现在「已出现具名实参」之后(对齐常见「位置在前、关键字在后」习惯)。前置修饰语与显式同名具名冲突则报错。 - ---- - -## 2. 文法(调用尾部) - -``` -call_tail ::= bracket_call | classic_call -bracket_call ::= modifier* '[' callee ']' arg* -classic_call ::= callee arg* -arg ::= named | positional -named ::= ident '=' value -positional ::= value_token | '(' call_tail ')' -modifier ::= ident # 展开为 ident=True;核心不剥语言词缀 -``` - -- `]` 后**紧邻** `(` → **取元** `[key](collection)`,不是 callee 标记(见 [collection-access-link.md](collection-access-link.md))。 -- 嵌套调用:把内层整段放进 `()`,例如 `[问候] ([格式化] "x")`。 -- `value`(具名右侧):可含空格与 `` `var` `` 插值,直到下一个 `ident=` 边界。 -- `value_token`(位置):空白分隔的一个词法单元——数字、`` `名` ``、标识/文本词;**不含空格**。多词字符串请用具名,例如 `> print text=Hello World!`。 -- 实参值中 `` `变量` `` 后**紧跟** `[^…]` 时按**脚注取元**解析(可链式),而非文本:`> print text=苹果单价:`水果价格`[^苹果]`、`> print text=`订单`[^2][^品名]`。 -- **独立 `>` 调用**:裸词 = 文本字面量。 -- **`*…*` / `**…**` 段内的调用**(如 `*x = > text.split value=src sep=","*`):裸词 = **变量**(Python 统一命名空间),文本字面量必须加引号(`value="a,b"`);`` `名` `` 变量形式仍合法。 -- 内置 `print` / `打印` 形参:`text` ≡ `内容`。 -- `input` / `输入`:`prompt` ≡ `提示`。 -- `len` / `长度`、`str` / `文本`、`int` / `整数`:`value` ≡ `值`。 -- 完整中英双名见 [keywords-i18n.md](keywords-i18n.md)。 - ---- - -## 3. 绑定算法 - -1. 将前置修饰语展开为 `名=True` 具名(与显式具名冲突则报错)。 -2. 收集具名 → 映射;冲突则报错。 -3. 按函数形参表顺序:若具名已提供则用之,否则取下一个位置实参。 -4. 位置实参有余、或必填形参仍缺 → 报错(内置 `input` 的 `prompt` 可缺省)。 -5. 用户函数:额外具名键仍写入调用环境(便于扩展);位置实参不可超过形参数目。 - ---- - -## 4. 金样例 - -见 `tests/structure/positional-call.mq.md`、`tests/structure/bracket-call.mq.md`、`tests/structure/ns/`(点号路径 / `use`)与 `tests/structure/import/`(导入解析)。 diff --git a/doc/design/call-syntax-from-marks.md b/doc/design/call-syntax-from-marks.md deleted file mode 100755 index fdfaf25..0000000 --- a/doc/design/call-syntax-from-marks.md +++ /dev/null @@ -1,289 +0,0 @@ -# 语法设计:标记如何构成调用(在「只执行标记」原则下) - -> **2026-10-23 审阅裁决**:保留显式标记和正文默认安全;性能数值是旧实验,不作为当前基准。持久跨文档接口优先具名参数,但不禁止位置参数;反引号声明与顺序改变可能是接口变化。当前调用与开发方向见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓)。 - -| | | -|---|---| -| 状态 | **Proposed · 待决策**(未改代码) | -| 日期 | 2026-10-22 | -| 前置纠正 | 用户否决上一轮的「叙述式动词」方案:**未标记词承载语义 = 破坏「叙述默认安全」** | -| 方法 | 实测 6 组(含双后端性能对比、叙述顺序实验)+ 源码比对 | -| 相邻 | [ambient-parameters-evaluation.md](ambient-parameters-evaluation.md) · [paren-call-and-readable-invocation.md](paren-call-and-readable-invocation.md) | - ---- - -## 0. 先接受纠正:错在哪 - -我上一轮提的 `对**n=31**执行**加一函数**`,靠**未标记的词「执行」**来触发调用。这确实违背底层原则: - -> **叙述(未标记)= 默认安全,不执行;标记 = 才进编译器。** - -一旦「执行」这种词能改变语义,那么: - -- 作者改一句措辞("执行" → "运行" / "调用" / 换个说法)就可能改变程序行为; -- 读者无法只看标记判断哪句是代码——必须逐字读叙述; -- 与 D9 同类的静默风险:语义藏在叙述里。 - -**所以本文的设计约束是硬的**: - -> **调用的每一个语义成分(被调者、每个实参、绑定关系)必须落在标记内; -> 叙述词只能起连接与解释作用,永不改变语义。** - ---- - -## 1. 先盘清「标记字母表」 - -要设计调用,先得知道手上只有哪些字。 - -| 标记 | 现行语义 | 可否参与构成调用 | -|------|---------|-----------------| -| `**…**` | 执行段(赋值 / 调用 / 表达式) | ✅ 主载体 | -| `*…*` | 返回 | ✅ 终止 | -| `` `x` `` | 变量引用;首次出现即声明 | ✅ 槽名 | -| `` `x` = `` | 叙述中的绑定 | ✅ 槽赋值 | -| `**x = …**` | 赋值 | ✅ | -| `> …`(行首) | 调用语句 | ✅ 已是调用标记 | -| `[callee] args` | 方括号调用(消歧 / 前置修饰) | ✅ 已是调用标记 | -| `[k](coll)` | 取元 | ⚠️ 与调用抢外形(已否) | -| `- [x](coll)` | 遍历 | — | -| `#` / `##` | 对象 / 函数声明 | — | -| 表格 | 数据 / 契约 | — | -| ```lang | 外联代码 | — | - -**关键观察**:调用载体其实只有三种标记:`> 行`、`**…**`、`[callee]`。 -而 `[k](coll)` 这个外形已被取元独占(前几轮结论),不能用。 - -所以问题收敛为: - -> **在 `**…**` 或 `> …` 内部,用哪些标记把「函数名」和「槽赋值」连起来?** - ---- - -## 2. 可读性从哪来(这是设计的核心) - -Marqdo 的叙述与代码是**两层**:叙述解释「为什么」,标记表达「做什么」。 -所以可读性不是靠把叙述词变成语法,而是靠: - -1. **标记本身足够像自然记号**(`=`, `(`, `)`, `→` 都是跨语言的); -2. **叙述与标记紧邻**,人一句一码地读; -3. **同一件事只写一遍**(叙述不要复述代码)。 - -一句话: - -> **叙述负责「说人话」,标记负责「说准话」;两者相邻即高可读,混在一起即两败。** - ---- - -## 3. 三个候选设计 - -### 设计 A — 括注具名调用:`**加一函数(n=31)**` - -**读法**:`加一函数(n=31)` —— 与数学/几乎所有语言的函数调用同构。 - -```markdown -## 加一函数 - -对 `n` 让 **n = n + 1**,返回 *n* - -# main - -**结果 = 加一函数(n=31)** -``` - -| 维度 | 评价 | -|------|------| -| 完全由标记构成 | ✅ 整段在 `**…**` 内 | -| 无歧义 | ✅ 圆括号紧跟名字 = 调用;取元需方括号,不冲突 | -| 与叙述结合 | ✅「把 n 设为 31 后**加一函数(n=31)**」 | -| 多参数 | ✅ `f(a=1 b=2)` | -| 编译器 | ✅ 具名 → 编译期映射到槽下标(见 §4) | -| 实现成本 | ⚠️ 需改参数分词器:`)` 作终止符、逗号、嵌套(原型已验 554/0,但 `f(1 2)` 的末参数会吞 `)`) | - -### 设计 B — 箭头槽赋值:`**n=31 → 加一函数**` - -**读法**:「n 设为 31,交给加一函数」——最贴合汉语「先条件、后动作」语序。 - -```markdown -# main - -**n=31 → 加一函数** -``` - -| 维度 | 评价 | -|------|------| -| 完全由标记构成 | ✅ `→` 是符号标记,不是词 | -| 可读性 | ✅✅ 流水线极顺:`**订单 → 计税 → 汇总**` | -| 无歧义 | ⚠️ 需定义优先级;`**x = a=1 → f**` 有歧义,得靠括号 | -| 求值结果 | ⚠️ 箭头式天然是语句式;要拿返回值还得包一层 | -| 实现成本 | 中:新增运算符 + 优先级 + 与 `=`/`*…*` 的交互 | - -### 设计 C — 现成空格式:`**加一函数 n=31**`(今天就可用) - -| 维度 | 评价 | -|------|------| -| 完全由标记构成 | ✅ | -| 实现成本 | **零**(实测 `**r = 加 1 2**` 已可跑) | -| 可读性 | ⚠️ 参数边界靠空格;函数名含空格时不可用(D8) | -| 编译器 | ✅ 具名同样可映射槽位 | - -### 三者的取舍 - -| | A 括注 | B 箭头 | C 空格 | -|---|---|---|---| -| 像通用函数调用 | ✅✅ | ⚠️ | ✅ | -| 中文语序自然 | ⚠️ | ✅✅ | ✅ | -| 参数边界清晰 | ✅✅ | ✅ | ❌(空格切分) | -| 链式组合 | ⚠️ | ✅✅ | ❌ | -| 改动成本 | 中 | 中高 | **零** | -| 与取元冲突 | 无 | 无 | 无 | - ---- - -## 4. 「不分实参形参」:编译器视角的真实收益 - -你问的是:不再区分实参/形参,是否意味着变量总在某个固定位置、能否减少 IO。 -这一节用实测回答,结论会有点意外。 - -### 4.1 现状:两条执行路径,差异 3.8 倍 - -| 路径 | 参数如何绑定 | 200k 次调用(1 个 int 实参) | 2000 次调用(500 元素列表) | -|------|-------------|------------------------------|------------------------------| -| **树遍历**(默认 `Backend::Tree`) | `Env { HashMap }`,每个实参 `k.clone()` + `v.clone()`(**深拷贝**) | 167 ms | 66 ms | -| **字节码**(`--backend bytecode`) | `slots: Vec`,`pop` 后**按位置移动**入槽(**无克隆、无哈希**) | **44 ms** | **23 ms** | - -源码依据: - -```rust -// src/bytecode/vm.rs Op::Call(fid, argc) -let mut slots = vec![Value::None; callee.locals.len().max(argc).max(1)]; -for i in (0..argc).rev() { - slots[i] = pop(&mut stack)?; // 移动,不克隆 -} -frames.push(Frame { fn_idx: fid, ip: 0, slots, .. }); -``` - -### 4.2 三个结论 - -**结论一:「变量始终在某个位置」已经是字节码的现实。** -形参按下标落槽,实参按位置移动入槽。这正是你说的模型——它已经存在。 - -**结论二:收益是真的,3.8×。** -每次调用 0.83µs → 0.22µs;大实参 33µs → 11.5µs(省掉了深拷贝)。 - -**结论三(关键):这与「不分实参形参」的语法无关。** -槽位化只需要「编译期知道形参顺序」,而形参顺序今天就有(v0.3 体推断给出确定顺序)。 -真正的瓶颈是**树遍历解释器用名字哈希 + 深拷贝**,以及**默认后端是 Tree**。 - -> **所以:不要用性能去论证语义变更。** -> 想省 IO,把默认后端切到字节码、或把树遍历解释器槽位化即可—— -> 这是一条与语法正交的工程路径,收益确定、风险可控。 -> 而改语义(动态作用域)换来的性能,等于用正确性买速度。 - -### 4.3 但有一个真实的语法—性能耦合点:具名 vs 位置 - -这是本节最有价值的发现。**在「形参由体推断」的世界里,形参顺序 = 叙述里首次声明的顺序** -(v0.3 §8.2:顺序按升参名字的首次声明事件出现序)。而叙述是可以自由改写的。 - -我用两个只差一句话序的文件做了实验: - -```markdown -## 减 -对于`a`和`b`。 ← 叙述顺序 a, b -*`a` - `b`* -``` - -```markdown -## 减 -对于`b`和`a`。 ← 只把叙述顺序改成 b, a -*`b` - `a`* -``` - -| 调用写法 | 叙述 a 在前 | 叙述 b 在前 | -|---------|------------|------------| -| 具名 `a=10 b=3` | 7 | -7(语义随函数体改变,符合预期) | -| **位置 `10 3`** | 7(a=10,b=3) | **7(b=10,a=3)** ← **绑定翻转了** | - -**同一行调用代码 `> 减 10 3`,只因为作者改了前面的叙述语序,实际绑定就变了,而且不报错。** - -这在「实参形参不分」的模型下是致命的:既然只有槽、槽序来自叙述, -那么**位置传参等于把程序语义挂在叙述的可改写顺序上**。 - -**推论**:调用应当**以具名为准**,位置实参在体推断世界里是脆弱语法。 -这一点与编译器优化正好同向——具名调用让编译期把 `n` 静态映射到 `slots[0]`, -既稳又快(不需要运行期哈希,也不需要猜顺序)。 - ---- - -## 5. 我的设计建议 - -### 5.1 主形态:括注具名调用 - -```markdown -## 加一函数 - -对 `n` 让 **n = n + 1**,返回 *n* - -# main - -**结果 = 加一函数(n=31)** -``` - -理由: - -1. **全部语义在标记内**(满足你的核心原则); -2. 与通用函数调用同构,零学习成本; -3. 具名 → 编译期静态映射槽位(对接字节码已有的 `slots[]`); -4. 不碰取元 `[k](coll)`,不碰遍历 `- [x](c)`; -5. 参数边界显式,顺带解决函数名含空格的调用难题(D8)。 - -### 5.2 位置实参:降级而非禁止 - -| 情形 | 建议 | -|------|------| -| 单参数 | 允许 `f(31)`(无歧义、写法自然) | -| 多参数 | **要求具名**;位置仅保留给 `> f 1 2` 这种旧写法,并在 `check` 里 **warn** | -| 理由 | §4.3:顺序来自叙述,可被改写而不报错 | - -### 5.3 箭头(设计 B)作为可选补充 - -如果后续确实需要「流水线可读性」,再引入 `→`,定位为**语句式组合子**: - -```markdown -**订单 → 计税 → 汇总** -``` - -但它是增量特性,不是本设计的前提。优势是链式,代价是优先级与返回值语义。 - -### 5.4 明确不做 - -| 方案 | 理由 | -|------|------| -| 未标记动词触发调用(上轮 L0) | 违背「叙述默认安全」 | -| `[f](args)` | 与取元同形,已实测 2 个真实冲突文件 | -| 动态作用域(参数从上下文推断) | 七条硬伤 + 130 个撞车形参名 | -| 位置实参作为主流 | §4.3 叙述顺序会静默改变绑定 | - ---- - -## 6. 优劣总表 - -| 设计 | 标记完备 | 可读性 | 无歧义 | 编译器友好 | 改动 | 结论 | -|------|---------|--------|--------|-----------|------|------| -| **A 括注具名 `f(n=31)`** | ✅ | 高 | ✅ | ✅ 静态槽映射 | 中 | **推荐主形态** | -| C 空格式 `f n=31` | ✅ | 中 | ✅ | ✅ | 零 | 今天可用,作兼容 | -| B 箭头 `n=31 → f` | ✅ | 最高(流水线) | ⚠️ 优先级 | ✅ | 中高 | 可选增量 | -| `[f](args)` | ✅ | 高 | ❌ 撞取元 | — | — | 不做 | -| 未标记动词 | ❌ | 高 | ❌ | — | — | 不做 | -| 动态作用域 | ✅ | 最高 | ❌ | ❌ 契约/指纹失效 | 高 | 不做 | - ---- - -## 7. 待你决策 - -1. **主形态选 A(括注具名)吗?** 若选,我按 B 档实现:`f(k=v)` 必通、`f(x)` 单参、多参数求具名。 -2. **位置实参**:多参时"要求具名 + 旧写法 warn"(§5.2),还是保持现状不动? -3. **箭头**现在做还是留作后续? -4. **顺带**:默认后端要不要切字节码(实测 3.8×,但需先验证 554 用例在 `--backend bytecode` 下全绿)?这条与语法无关,但可能是最划算的性能改进。 - -> 若你同意 A,我下一步会:改分词器(`)` 终止、逗号、嵌套)→ 补金样例 → -> 跑双后端 554 回归 → 写变更文档。 diff --git a/doc/design/catalog-cli.md b/doc/design/catalog-cli.md deleted file mode 100755 index da6e320..0000000 --- a/doc/design/catalog-cli.md +++ /dev/null @@ -1,132 +0,0 @@ -# OKF 兼容清单:`marqdo catalog` - -| | | -|---|---| -| 状态 | 已定(O1 + O3:工程目录包 + agent-kb 概念并入) | -| 日期 | 2026-08-07 | -| 取代 | [generated-yaml-manifest.md](generated-yaml-manifest.md) 中「待决:sync/doc 命令」的命令名部分 | -| 相关 | [okf.md](okf.md)(**实现规范总览**)· [generated-yaml-manifest.md](generated-yaml-manifest.md) · [view.md](view.md) · [okf-and-marqdo.md](../research/okf-and-marqdo.md) | - ---- - -## 1. 决策(重申) - -YAML / OKF 风格清单是**从 `.mq.md` 派生的生成物**,不是手写配置。完整词汇、任务知识包与路线图见 [**okf.md**](okf.md)。生成式方向见 [generated-yaml-manifest.md](generated-yaml-manifest.md)。 - -本文件规定 **CLI 与工程目录包落盘格式**(含 O3:扫入本地 `agent-kb` 概念,供人与工具同览)。 - ---- - -## 2. CLI - -```bash -marqdo catalog [PATH] -o OUT_DIR -# 别名(与早期草案一致) -marqdo sync [PATH] -o OUT_DIR -# 跳过 Engineering Knowledge 投影(仅旧式 catalog) -marqdo catalog [PATH] -o OUT_DIR --no-knowledge -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `PATH` | `.` | 工程根或含 `.mq.md` 的目录(递归扫描) | -| `-o` / `--out` | `.marqdo` | 生成目录(写入前创建;**覆盖**同名生成文件;扫描时跳过该目录) | -| `--no-knowledge` | off | 不跑 EKC;默认在 catalog 成功后编译 L0–L4 / graph | - -退出码:成功 0;无可扫描文件或 IO/解析失败非 0(单文件解析失败时写入 `diagnostics` 并继续其余文件,最终若有失败则非 0)。 - -Engineering Knowledge 命令见 [engineering-knowledge.md](engineering-knowledge.md)(`find` / `reuse` / `duplicate` / …)。 - ---- - -## 3. 生成物 - -``` -OUT_DIR/ - catalog.yaml # 机器向总清单(OKF 风格字段) - index.md # 人可读总览:Modules + Agent knowledge - modules/ - .md # 每个工程 .mq.md 一个 Module 页 - concepts/ # 从 **/.marqdo/agent-kb/concepts/ 复制(O3) - tasks/… - skills/… -``` - -路径中的目录层级拍扁为文件名时用 `__` 连接,例如: - -`structure/import/main.mq.md` → `modules/structure__import__main.md` - -`.marqdo/agent-kb/` 下的可执行 `.mq.md` **不**进 Module 表(由 Task/Skill 概念页的 `resource` 指向)。 - -### 3.1 `catalog.yaml`(示意) - -```yaml -# GENERATED by marqdo — do not edit by hand -type: Marqdo Catalog -title: marqdo-project -generated: - by: marqdo/0.1.2 -modules: - - id: structure/hello - resource: structure/hello.mq.md - title: Hello World - imports: [] - exports: - - name: Hello World - kind: fn - - id: structure/import/main - resource: structure/import/main.mq.md - imports: - - utils.mq.md - exports: - - name: main - kind: fn -concepts: [] # 有 agent-kb 时为 Task/Skill 条目列表 -``` - -| 字段 | 含义 | -|------|------| -| `type` | 固定 `Marqdo Catalog`(OKF:未知 type 可降级) | -| `modules[].resource` | 相对 `PATH` 的源路径 | -| `modules[].imports` | 源 frontmatter 中的 `> *.mq.md` | -| `modules[].exports` | 顶层 `#` 函数名(`kind: fn`) | -| `modules[].verified` / `sources` | 源 frontmatter 有则透传(O3) | -| `concepts[]` | 本地 agent-kb 概念摘要(`id`/`type`/`page`/…) | -| `generated.by` | `marqdo/` | - -不在现行范围:版本锁定哈希、跨仓 URL、完整符号类型、`log.md`(见 okf O4)。 - -### 3.2 模块概念页 - -Frontmatter 仍用 `depends` 字符串列表(机器可读);**正文 Dependencies** 链到同包其它 Module 页(人可点)。源若带 `verified` / `sources` 则写入页头。 - -### 3.3 Agent knowledge - -`index.md` 的 **Agent knowledge** 节列出扫到的 Task/Skill,链到 `concepts/…`。概念页内容从本地 `agent-kb` **复制**,与 Agent 运行时包同源,便于人审阅晋升结果。 - ---- - -## 4. 与 `view output` 的分工 - -| 命令 | 产物 | 受众 | -|------|------|------| -| `marqdo view output` | 静态 HTML(结构 + 运行结果) | 人类读程序文档站 | -| `marqdo catalog` | OKF 风格 YAML + Markdown 索引(含 agent-kb) | 人浏览依赖/技能 · 工具 / Agent | - -二者都从同一源树生成,互不替代。发布用户文档时可同时: - -```bash -marqdo view output public -o public -marqdo catalog tests -o .marqdo -``` - ---- - -## 5. 验收 - -1. `marqdo catalog tests -o /tmp/mq-cat` 写出 `catalog.yaml`、`modules/`、`concepts:` 键。 -2. `catalog.yaml` 含 `structure/hello` 与 import 模块的 `imports: [utils.mq.md]`。 -3. 模块页 Dependencies 对已解析导入为 Markdown 链接。 -4. 若扫描根下有 `.marqdo/agent-kb/concepts/`,则复制进 `OUT_DIR/concepts/` 且 `index.md` 有 Agent knowledge 条目。 -5. 文件头或 `generated` 标明 GENERATED;文档声明勿手改。 -6. `marqdo sync` 与 `catalog` 行为一致。 diff --git a/doc/design/change-d9-unterminated-string.md b/doc/design/change-d9-unterminated-string.md deleted file mode 100755 index d20272c..0000000 --- a/doc/design/change-d9-unterminated-string.md +++ /dev/null @@ -1,231 +0,0 @@ -# 变更记录:D9 未闭合引号不再静默吞行 - -| | | -|---|---| -| 状态 | **Implemented**(待合入) | -| 日期 | 2026-10-22 | -| 缺陷 | [D9](../research/qdagent-refactor-defects-2026-10.md) | -| 设计 | [parser-diagnostics-d8-d9.md](parser-diagnostics-d8-d9.md) §1 | -| 改动文件 | `src/lex/mod.rs` · `src/parse/mod.rs` | -| 影响面 | 行分类 + 语句解析(仅影响**畸形**输入) | - ---- - -## 1. 修了什么 - -**修复前**:`**s = "abc`(引号未闭合)被静默当成叙述丢弃,退出码 0。 - -```bash -$ marqdo run u.mq.md -$ echo $? -0 # 没有输出、没有报错,s 这一行凭空消失 -``` - -**修复后**:解析期报错,退出码非 0。 - -```bash -$ marqdo run u.mq.md -error: u.mq.md: 7:1: unterminated string: this line starts bold code but -contains an odd number of `"` -- close the string and the trailing `**` -(line: **s = "abc) -$ echo $? -1 -``` - -(实测记录:报错回显中 `unterminated` 前的空格与行号格式由 -`Diagnostic` 的 span 渲染决定,与其它语法错一致。) - ---- - -## 2. 根因 - -问题**不在**解析器——`parse_quoted_string` 里的 -`bail!("unterminated {quote} string")` 一直都在,措辞也对。 -问题是这一行**根本到不了解析器**: - -``` -"**s = \"abc" - ↓ classify_line - ↓ 首字符 '*' → is_marqdo_star_line? - matching_bold_close() 扫描时遇到 '"' → in_str = true - 之后再也没有 '"' 来关闭 → 后续所有 '*' 都被当作字符串内容跳过 - → 找不到收尾 '**' → 返回 None - ↓ is_marqdo_star_line = false - ↓ 落入 `Some('*') if !is_marqdo_star_line` → LineKind::Comment - ↓ 成为「叙述」,解析器看不到 -``` - -**这是分类层的静默降级,不是解析层的缺陷。** - -它比一般的解析错误更危险,因为: - -| 场景 | 后果 | -|------|------| -| 手写漏一个引号 | 该行消失 → 别处报 `undefined variable`,排查方向被引偏 | -| LLM 生成文档 | 少一段内容,但 `exit 0`、`check` 通过,**文档看起来完整却缺节** | -| CI / 文档门禁 | 门禁试跑通过 → 残缺文档被沉淀入库 | - ---- - -## 3. 怎么改的 - -两层,缺一不可。 - -### 3.1 分类层:把畸形行留在 Code 类 - -`src/lex/mod.rs` - -```rust -if trimmed.starts_with("**") { - if trimmed.trim() == "** **" { - return true; - } - if matching_bold_close(trimmed).is_some() { - return true; - } - // D9: 粗体起始但引号永不闭合 → 找不到收尾 `**` - // 判为 Comment 会静默丢行;判为 Code 让解析器报错 - return has_unterminated_string(trimmed); -} -``` - -新增辅助函数: - -```rust -pub fn has_unterminated_string(line: &str) -> bool { - // 统计未被 \ 转义的双引号个数,奇数即「开了没收」 -} -``` - -### 3.2 解析层:给出精确报错 - -`src/parse/mod.rs`,紧跟既有粗体分支之后: - -```rust -// D9: 粗体起始但引号未闭合 —— 走到这里说明没有收尾 `**`, -// 通用 "unrecognized statement" 会掩盖真正原因。 -if trimmed.starts_with("**") && has_unterminated_string(trimmed) { - bail!("{span}: unterminated string: ... (line: {trimmed})"); -} -``` - -没有这一层,用户会看到 `unrecognized statement: **s = "abc`—— -能定位到行,但不知道是引号没闭合。 - ---- - -## 4. 影响面(改前量化过) - -对仓库内全部 `.mq.md`(`target/` 除外)做静态扫描,正确跳过 `\` 转义: - -| 指标 | 数值 | -|------|------| -| `.mq.md` 文件总数 | 845 | -| 含 `**` 起始代码行的文件 | 620 | -| **引号计数为奇数的代码行** | **0** | - -**结论:不改变任何现有文件的解析结果。** 这条修复只作用于畸形输入。 - ---- - -## 5. 测试 - -### 5.1 新增单元测试(`src/lex/mod.rs`,4 个) - -| 测试 | 断言 | -|------|------| -| `unterminated_quote_inside_bold_is_code_not_comment` | 未闭合引号的粗体行 → `Code`(修复前失败,修复后通过) | -| `balanced_quote_inside_bold_still_code` | 闭合引号仍是 `Code` | -| `prose_with_quotes_stays_comment` | 叙述里提引号 → 仍是 `Comment` | -| `prose_bold_emphasis_with_quote_stays_comment` | 叙述里含孤立引号 → 仍是 `Comment` | - -**先写测试确认失败**(TDD): - -``` ----- lex::tests::unterminated_quote_inside_bold_is_code_not_comment -panicked: expected Code (so parser reports the error), - got [ClassifiedLine { kind: Comment, text: "**s = \"abc" }] -``` - -修复后 14/14 通过。 - -### 5.2 回归 - -| 范围 | 结果 | -|------|------| -| `cargo test --release --lib` | **237 passed, 0 failed**(基线 233 + 新增 4) | -| `cargo test --release --test gold` | 276 passed, 8 failed | -| ↑ 上述 8 个失败是否本次引入 | **否**。`git stash` 后基线同样 8 failed | -| 8 个失败的原因 | 全部 `ext_web_*`,依赖 Go 插件 `libweb` 构建,本机环境不具备 | - ---- - -## 6. 已知边界 - -| 情形 | 行为 | 说明 | -|------|------|------| -| `**s = "a` + 下一行 `b"**` | 报错 | 字符串不跨行,符合现状 | -| 单引号 `'...'` 未闭合 | **仍是旧行为**(静默) | 本次只处理双引号;单引号在 Marqdo 里使用频率低,留作后续 | -| 叙述行含孤立 `"` | 不受影响 | 判定入口是 `starts_with("**")`,叙述行不进入 | - -> 单引号的情况建议后续按同样思路处理,但需要单独评估 -> (单引号也用于英文撇号,误判风险高于双引号)。 - ---- - -## 7. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/lex/mod.rs` | `is_marqdo_star_line` 增加未闭合引号分支;新增 `pub fn has_unterminated_string`;新增 4 个测试 | -| `src/parse/mod.rs` | import 辅助函数;`parse_simple_stmt` 增加精确报错分支 | -| `doc/design/parser-diagnostics-d8-d9.md` | 新增(设计依据 + 影响面 + 方案评判) | -| `doc/design/spaced-function-names-d8.md` | 新增(D8 方案评估,待审阅) | -| `doc/design/change-d9-unterminated-string.md` | 本文件 | - ---- - -## 8. 附:本机测试环境(2026-10-22 装好) - -修复过程中发现本机缺两样东西,导致基线本来就有失败。补环境后全量测试 **554 passed / 0 failed**。 - -### 8.1 两个非直觉约束 - -| 约束 | 表现 | 解法 | -|------|------|------| -| `$HOME` 不可写 | zig 报 `error: AccessDenied`(全局缓存无处可写) | `ZIG_GLOBAL_CACHE_DIR` / `ZIG_LOCAL_CACHE_DIR` 显式指向工作区 | -| **`/tmp` 是 noexec tmpfs** | Go 链接报 `running gcc failed: signal: aborted`;zig 链接报 `AccessDenied` | `TMPDIR` 指向可写**且可执行**目录 | - -第二条最隐蔽:`/tmp` 挂载为 `rw,nosuid,nodev,noexec`,构建工具会把产物写到那里再执行, -于是「文件能写、却执行不了」。错误信息完全指向不了这一点。 - -### 8.2 Go 插件(`libweb.so`) - -`gold` 测试里 8 个 `ext_web_*` 失败全因缺 `libweb.so`: - -```bash -source scripts/dev-env.sh # 提供 go 1.25 + gcc shim(zig) + TMPDIR -./scripts/build-web-plugin.sh # 产出 plugins/web/build/libweb.so -cp plugins/web/build/libweb.so target/release/ target/debug/ -``` - -Go 的 cgo 要 `gcc`,本机没有,用 zig cc 充当: -`/workspace/qdagent/.tools/zigcc/bin/gcc`(会过滤 Go 传入的 `-Qunused-arguments`, -该参数会让 zig 驱动 abort)。 - -### 8.3 一键复用 - -新增 `scripts/dev-env.sh`,`source` 后即具备完整工具链: - -``` -marqdo dev-env: rust=1.81.0 go=go1.25.0 python=3.12.15 cc=zig-glibc2.36 -``` - -### 8.4 环境修复前后的测试对比 - -| 阶段 | lib 测试 | gold 测试 | -|------|----------|-----------| -| 无 python3 | 231 / 2 failed | — | -| 加 python3 | 233 / 0 failed | 276 / 8 failed | -| 加 go + libweb | — | **284 / 0 failed** | -| **全量** | | **554 passed / 0 failed** | diff --git a/doc/design/change-hostfn-table.md b/doc/design/change-hostfn-table.md deleted file mode 100755 index 92e63cb..0000000 --- a/doc/design/change-hostfn-table.md +++ /dev/null @@ -1,99 +0,0 @@ -# 变更记录:HostFn 五张表合一(`HOST_FN_TABLE` 单一来源) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 来源 | [code-volume-audit.md](code-volume-audit.md) §4 第 4 项 | -| 改动 | `src/host/dispatch.rs`:**−404 行**(639 删 / 235 增) | -| 行为 | **零变化**(203 项逐字节一致) | - ---- - -## 1. 原来有五张并行表 - -202 个宿主函数的元数据分散在五个手写 match 里: - -| 表 | 行数 | 作用 | -|----|------|------| -| `from_u16` | ~215 | id → 变体 | -| `from_name` | ~215 | 名字/别名 → 变体(**保留**,见 §4) | -| `name` | ~210 | 变体 → 规范名 | -| `required_params` | ~145 | 变体 → 必填参数 | -| `optional_params` | ~90 | 变体 → 可选参数 | - -五张表必须同步维护,而 [code-volume-audit.md](code-volume-audit.md) 记录过 -`from_name` 接受 `http_get` 而 `name()` 只输出 `host_http_get` 的一类漂移。 - -## 2. 现在只有一张 - -```rust -pub struct HostFnDef { - pub id: u16, - pub f: HostFn, - pub name: &'static str, - pub required: &'static [&'static str], - pub optional: &'static [&'static str], -} - -pub const HOST_FN_TABLE: &[HostFnDef] = &[ - HostFnDef { id: 1, f: HostFn::ReadText, name: "host_read_text", - required: &["path"], optional: &[] }, - … -]; -``` - -四个函数改为查表(`from_u16` 按 id 查,其余按判别值查); -`call_host` 保留它那 202 个一行臂——**分派逻辑不动**,只把元数据集中。 - -## 3. 怎么保证没改坏 - -迁移采用**快照比对**: - -1. 先在旧实现上导出全部 203 项的 `(id, name, required, optional)` 到 TSV -2. 合并成表后,用同一段代码再导出一份 -3. `diff` 两份文件 → **完全一致** - -``` -$ diff /tmp/host_fns_baseline.tsv /tmp/host_fns_new.tsv && echo IDENTICAL -IDENTICAL -``` - -快照测试是一次性的,比对通过后删除;长期守护交给四个不变量测试: - -| 测试 | 内容 | -|------|------| -| `every_assigned_id_round_trips` | 每个已分配 id → `as_u16()` 往返(id 空间稀疏是**退役 id**,不复用) | -| `every_id_has_a_name_that_round_trips` | `name()` → `from_name()` 回到同一变体 | -| `names_are_unique` | 规范名唯一 | -| `required_and_optional_params_are_disjoint` | 必填/可选不重叠、`all_params` 无重复 | - -## 4. 为什么 `from_name` 没有并进表 - -它是**别名注册表**(`http_get`、`get`、中文别名…),语义与"规范名"不同; -并进表会让 `name()` 与 `from_name` 又变成一对映射。 -现在它保留原样,由上面的往返测试保证不与表漂移。 - -## 5. 收益 - -| 指标 | 前 | 后 | -|------|----|----| -| `dispatch.rs` | 2,052 行 | **1,648 行** | -| `src/` 合计 | 53,040 | **52,668** | -| 需同步维护的表 | 5 | **1** | - -## 6. 验证 - -| 项 | 结果 | -|----|------| -| `cargo build --release` | 零警告 | -| `cargo test --release` | **609 passed / 0 failed** | -| 快照 diff | 203 项逐字节一致 | -| 四个不变量测试 | 全绿 | - -## 7. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/host/dispatch.rs` | 新增 `HostFnDef` / `HOST_FN_TABLE`(203 项);`from_u16` / `name` / `required_params` / `optional_params` 改为查表;删除对应四个 match | -| `doc/design/change-hostfn-table.md` | 本文件 | diff --git a/doc/design/change-m1-paren-call.md b/doc/design/change-m1-paren-call.md deleted file mode 100755 index a1f060e..0000000 --- a/doc/design/change-m1-paren-call.md +++ /dev/null @@ -1,134 +0,0 @@ -# 变更记录:M1 `()` 内调用语法(`)` 终止 / 逗号 / 嵌套 / 空格 callee) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M1([occlusion-syntax.md](occlusion-syntax.md) §13) | -| 改动文件 | `src/parse/expr.rs` | -| 影响面 | **共享参数分词器**(所有调用都会经过) | - ---- - -## 1. 修了什么 - -四件事,一句概括:**`(…)` 现在是一等调用外形**。 - -| # | 前 | 后 | -|---|----|----| -| 1 | `加(31)` 报 `unknown function 加(31` | ✅ 调用,返回 32 | -| 2 | 末个位置实参会吞掉 `)` | `)` 是**参数终止符** | -| 3 | 只支持空白分隔 | 支持 `,` / `,` 可选分隔 | -| 4 | 嵌套 `加(加(1 2), 3)` 不可用 | ✅ 递归解析 | -| 5 | `加一 号(31)` 不可用(D8) | ✅ **callee 可含空格** | - -实测(1.5.2 本地构建,tree 与 bytecode 双后端结果一致): - -``` -空格参=3 加(1 2) -逗号=3 加(1, 2) -嵌套=13 加(加(1 2), 10) -带空格callee=32 加一 号(31) ← 缺陷 D8 的结构性解法 -库函数=x txt.str_trim(" x ") -具名=3 加(a=1, b=2) -``` - ---- - -## 2. 实现要点 - -### 2.1 参数扫描:深度感知 + `)` 终止 - -`split_first_token` 与 `find_next_arg_boundary` 改为**通用扫描器**: - -- 跟踪 `()` `[]` `{}` 嵌套、`"…"` 字符串、`` `…` `` 反引号 -- **顶层** `)` / 空白(以及括号形里的 `,`)终止当前 token,且**不吞掉终止符** -- 字符串内的逗号不受影响(`拼接("a,b", "c")` 仍是 2 个参数) - -### 2.2 `try_paren_call`:callee = 第一个 `(` 之前的全部文本 - -```rust -let Some(open) = s.find('(') else { return Ok(None) }; -let callee_tok = s[..open].trim(); // 允许空格 -``` - -**安全护栏**(否则会误判): - -| callee 里出现 | 判定 | -|--------------|------| -| `=` | 不是括号调用(那是 `text=a(b)` 具名实参) | -| `[` `]` `(` `)` `"` `'` | 不是括号调用(那是 `trim [stdout](…)` 方括号实参) | -| 以 `[` `]` `"` `'` 开头 | 不是括号调用 | -| 反引号 | **允许**(保留 `` `obj`.方法(…) `` 接收者写法) | - -### 2.3 表达式级 postfix 调用 - -`parse_primary` 的裸词分支:**紧跟** `(` 时按调用解析。 - -```rust -if self.allow_paren_call && self.rest().starts_with('(') { … } -``` - -要求"紧跟"(不隔空格),使 `加 (1)` 仍是原来的"文本 + 括号"行为。 - -### 2.4 方括号形也允许空格 callee - -`is_bracket_callee_inner` 不再拒绝空白:`[加一 号] 31` 可用。 -(仓库内可执行的方括号调用用量为 0,风险极低。) - ---- - -## 3. 关键设计决策:括号形 vs 空格形的参数**值**语义不同 - -这是本里程碑唯一有争议的点,必须写清。 - -| 形态 | 参数值 | 例子 | -|------|--------|------| -| **括号形** `f(…)` | 表达式(**允许** `name(args)` 调用) | `加(加(1 2), 3)` | -| **空格形** `> f k=v` | 文本(**不允许**裸 `name(args)` 变成调用) | `source=print(2+2)` 仍是文本 | - -**为什么必须区分**:`source=print(2+2)` 在 Marqdo 里历来是**文本**(未加引号的实参按文本处理)。 -若不区分,它会变成对 `print` 的调用,`foreign.run_lang` 直接报 `source must be text` -—— 这正是本次回归测试抓到的 3 个失败。 - -实现:`Parser` 增加 `allow_paren_call` 字段;`parse_call_arg_value_mode(input, prefer_var, allow_call)` -统一两种值解析(`allow_call=false` 即旧行为)。 - ---- - -## 4. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 单元 | 新增 11 个(单参/多参/逗号/具名/空格 callee/零参/库路径/嵌套/引号内逗号/旧写法不回归/方括号形) | ✅ | -| 全量 | `cargo test --release` | **565 passed / 0 failed**(基线 554 + 11) | -| 双后端 | tree 与 `--backend bytecode` 跑同一文档 | 输出一致 | -| 端到端 | `marqdo run` 六个用例 | 输出符合预期 | - -**TDD 过程**:先写 11 个测试 → 10 个失败(红灯确认)→ 实现 → 全绿。 - ---- - -## 5. 顺带移除的死代码 - -`end_of_quoted_string`:新扫描器取代其唯一用途后变成 `never used`,删除(编译器警告清零)。 - ---- - -## 6. 边界(本里程碑不做) - -| 项 | 说明 | -|----|------| -| 逗号仅在括号形生效 | 空格形 `text=a,b` 的逗号仍是文本(兼容) | -| `加 (1)`(空格后跟括号) | 不视为调用,保持旧行为 | -| 遮蔽语法 `[描述](…)` | M2 才引入,本里程碑不解析 | -| 位置实参顺序脆弱性 | 与叙述顺序绑定,M7/M8 再处理(诊断) | - ---- - -## 7. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/parse/expr.rs` | 参数扫描器重写(`)`/逗号/嵌套);新增 `try_paren_call` + `split_callee` 抽取;表达式级 postfix 调用;`Parser.allow_paren_call`;`parse_call_arg_value_mode` 统一两种值语义;方括号 callee 允许空格;删除 `end_of_quoted_string` | -| `doc/design/change-m1-paren-call.md` | 本文件 | diff --git a/doc/design/change-m10-engineering-habits.md b/doc/design/change-m10-engineering-habits.md deleted file mode 100755 index 6572590..0000000 --- a/doc/design/change-m10-engineering-habits.md +++ /dev/null @@ -1,73 +0,0 @@ -# 变更记录:M10 工程化落点(README + agent 提示词) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M10([occlusion-description-and-search.md](occlusion-description-and-search.md) §5) | -| 改动文件 | `ext/ai/agent.mq.md`(README 一节已在文档阶段落地) | - ---- - -## 1. 改了什么 - -把「接不了就申报,别假装完成」写进 **agent 的默认提示词**,两处: - -### 1.1 `how-to-act` 协议段(每轮都会带) - -``` -Call ONLY names listed under --- tools --- (whitelist). … -If a capability cannot truly be wired, do NOT fake it silently and never claim it works: -write an occlusion with an explicit status, e.g. [按关键词检索,接口未接,待开发](None). -Stubs must run without error and must state their return value (None is acceptable). -Before finishing, check your own declarations with labels.search. -Tools run via Marqdo subtask (spawn fn / wait). -``` - -### 1.2 默认 standing(`p`) - -``` -You are a Marqdo agent. Code is documentation: … not a hidden system prompt. -When you cannot wire a capability, declare it in the description (待开发 / 模拟) -instead of faking success. -``` - -**为什么这两处**:standing 定基调(每次对话开头),how-to-act 定动作(每轮)。 -只写 standing 容易被长上下文冲淡;只写 how-to-act 又缺"为什么要申报"。 - ---- - -## 2. 设计要点 - -| 要点 | 说明 | -|------|------| -| 给**范式**而不是规则 | 直接给出可抄的 `[按关键词检索,接口未接,待开发](None)`,模型不必发明措辞 | -| 给**返回值**要求 | "必须写清返回什么(None 也行)"——对应 `label.empty_payload` 的 warning | -| 给**自查**动作 | `labels.search` 让模型收尾时能自己盘点,而不是靠人提醒 | -| 用**英文**写 | 与既有 standing / 协议段语言一致(模型对英文指令更稳) | - ---- - -## 3. 验证 - -| 项 | 结果 | -|----|------| -| `marqdo check ext/ai/agent.mq.md`(occlusion 模式) | `contract check OK` | -| 提示词文本落入模块 | `grep` 命中 2 处(standing 与 how-to-act 各 1) | -| 全量回归 | 587 passed / 0 failed(与 M9 相同,本改动不动逻辑) | - ---- - -## 4. 边界 - -- 提示词是**建议**,不是门禁;违反不会被拒绝,但会在描述/诊断里暴露。 -- `labels.search` 需要 M7 翻转默认后对 classic 文档才有意义;提示词先就位。 - ---- - -## 5. 变更清单 - -| 文件 | 变更 | -|------|------| -| `ext/ai/agent.mq.md` | how-to-act 协议段与默认 standing 各追加申报约定 | -| `doc/design/change-m10-engineering-habits.md` | 本文件 | diff --git a/doc/design/change-m2-occlusion.md b/doc/design/change-m2-occlusion.md deleted file mode 100755 index 85fdccc..0000000 --- a/doc/design/change-m2-occlusion.md +++ /dev/null @@ -1,126 +0,0 @@ -# 变更记录:M2 遮蔽语法 `[描述](实现)` - -| | | -|---|---| -| 状态 | **Implemented**(模式开关默认仍是 classic) | -| 日期 | 2026-10-22 | -| 里程碑 | M2([occlusion-syntax.md](occlusion-syntax.md) §13) | -| 改动文件 | `src/ast.rs` · `src/parse/expr.rs` · `src/parse/mod.rs` · `src/interp.rs` · `src/bytecode/compile.rs` · `src/view/render.rs` · `src/main.rs` · `tests/occlusion.rs` | -| 影响面 | 语法(新节点)+ 两个后端 + 渲染 | - ---- - -## 1. 新增语法 - -```markdown -[描述](实现) -``` - -- `[]` = **描述**(自由文本,**永不执行**;仅用于检索、统计、过期校验) -- `()` = **实现**(唯一执行体) -- `[]` 为空 → `label.missing`(error,M2.5 落诊断) -- `()` 为空 → 值为 `None`(空载荷桩,M2.5 落 warning) - -实测(`MARQDO_MARKUP=occlusion`): - -``` -a=2 [加一之后的值](1 + 1) -b=42 [外层]([内层](40 + 2)) ← 嵌套遮蔽 -c=True [某某功能开发中]() ← 空载荷 → None -``` - ---- - -## 2. 关键决策:**模式开关,暂不切换语义** - -`[键](集合)` 与 `[描述](实现)` **外形完全相同**。若 M2 直接改语义,全仓 506 处取元 -会**静默变成"遮蔽整个集合"** —— 这正是文档里点名的最坏一类变更(同形换义)。 - -因此 M2 只**实现能力**,不动默认: - -| 模式 | `MARQDO_MARKUP` | `[a](b)` 的语义 | -|------|-----------------|-----------------| -| `Classic`(默认) | 未设 / 其他值 | 取元(今天的行为) | -| `Occlusion`(纯度) | `occlusion` / `purity` / `1` / `on` | 遮蔽(描述 + 实现) | - -**M7 才迁移语料并翻转默认**,同时对旧形报 `syntax.legacy_index` 硬错误。 -这样 M2 可独立验证,且不会出现"半迁移的静默错义"。 - ---- - -## 3. 实现要点 - -### 3.1 AST - -```rust -Occluded { - label: String, - payload: Option>, // None = 空载荷桩(值 None) -} -``` - -### 3.2 解析 - -- `Parser` 增加 `markup: Markup` 字段;`parse_expr_markup(input, prefer_var, markup)` - 供测试/迁移显式指定;CLI 通过 `MARQDO_MARKUP` 设置进程默认。 -- 描述扫描:读到 `]` 为止;`\]` 转义字面方括号;跨行即报未闭合。 -- 之后必须紧跟 `(`;`()` 内若无内容 → `payload: None`;否则 `parse_or()` 后要求 `)`。 -- 嵌套自然成立:payload 是完整表达式,可再含遮蔽。 - -### 3.3 求值(两个后端一致) - -| 位置 | 处理 | -|------|------| -| `interp.rs` `eval_expr` | 有 payload → 求值 payload;无 → `Value::None` | -| `bytecode/compile.rs` | 有 payload → 编译 payload;无 → `Op::None_` | -| `collect_decl_reads` / `collect_reads_expr` | 递归 payload(描述不产生读引用) | -| `view/render.rs` `expr_prec` | 渲染成 `[描述](payload)` / `[描述]()` | - -**描述永不参与求值**——守住铁律 1。 - ---- - -## 4. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 单元(8) | 值直通 / 空载荷 / 描述含空格与标点 / `\]` 转义 / 嵌套 / classic 仍是取元 / 缺括号报错 | ✅ | -| 集成(3) | `MARQDO_MARKUP=occlusion` 跑通三个值;不设该变量时旧取元不变;occlusion 模式下旧形**不再**是取元 | ✅ | -| 全量 | `cargo test --release` | **575 passed / 0 failed**(M1 后 565 + 10) | -| 双后端 | tree 与 `--backend bytecode` | 一致 | - ---- - -## 5. 顺带重构 - -- `Markup` 枚举与 `parse_expr_markup` 抽为显式参数,避免测试依赖全局可变状态 - (全局只由 CLI 入口设置一次)。 -- `parse::expr` 由 `mod` 改 `pub mod`,供 `main.rs` 设置模式。 - ---- - -## 6. 边界 - -| 项 | 说明 | -|----|------| -| 描述不参与作用域/类型 | 写什么都不影响执行 | -| 描述里的 `` `实体` `` | M4 才做引用一致性校验 | -| 空载荷 warning | M2.5 落诊断(本提交只有语义) | -| 跨行描述 | 不支持(v1) | -| 旧取元 | 仍可用;M7 迁移后改为硬错误 | - ---- - -## 7. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/ast.rs` | 新增 `Expr::Occluded { label, payload }` | -| `src/parse/expr.rs` | `Markup` 枚举 + 全局默认 + `parse_expr_markup` + `parse_occluded` + `Parser.markup` | -| `src/parse/mod.rs` | `pub mod expr`;`collect_reads_expr` 递归 payload | -| `src/interp.rs` | 求值 + 读引用收集 | -| `src/bytecode/compile.rs` | 编译为 payload(或 `None_`) | -| `src/view/render.rs` | 表面渲染 + 输入提示收集 | -| `src/main.rs` | `MARQDO_MARKUP` 环境变量 | -| `tests/occlusion/value.mq.md` · `tests/occlusion/classic-index.mq.md` · `tests/occlusion.rs` | 新增集成测试 | -| `doc/design/change-m2-occlusion.md` | 本文件 | diff --git a/doc/design/change-m25-label-diagnostics.md b/doc/design/change-m25-label-diagnostics.md deleted file mode 100755 index b7b6696..0000000 --- a/doc/design/change-m25-label-diagnostics.md +++ /dev/null @@ -1,91 +0,0 @@ -# 变更记录:M2.5 遮蔽标签诊断(`label.missing` / `label.empty_payload`) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M2.5([occlusion-syntax.md](occlusion-syntax.md) §13,诊断规范 §10) | -| 改动文件 | **新增 `src/label.rs`** · `src/check.rs` · `src/lib.rs` · `tests/occlusion.rs` | -| 影响面 | `marqdo check`(新增两类诊断) | - ---- - -## 1. 两条诊断 - -| code | 级别 | 触发 | 文案要点 | -|------|------|------|---------| -| `label.missing` | **error** | `[](实现)` 描述为空 | 「给这段实现写一句人话,或改用不带遮蔽的写法」 | -| `label.empty_payload` | **warning** | `[描述]()` 载荷为空 | 「这里没有可执行内容」,建议写 `(None)` 或补实现 | - -实测: - -``` -$ MARQDO_MARKUP=occlusion marqdo check empty-label.mq.md -empty-label.mq.md:3:1: 遮蔽缺少描述:`[](…)` —— 给这段实现写一句人话,或改用不带遮蔽的写法 -contract check: 1 条诊断(1 error) # exit 1 - -$ MARQDO_MARKUP=occlusion marqdo check empty-payload.mq.md -empty-payload.mq.md:3:1: 空载荷遮蔽:`[某某功能开发中]()` —— 这里没有可执行内容 -contract check: 1 条诊断(0 error) # exit 0(warning 不影响退出码) -``` - -JSON 出口(自动继承既有 schema,含 `doc_quote`): - -```json -{"code":"label.empty_payload","severity":"warning","span":{"line":3,"col":1}, - "doc_quote":"某某功能开发中","message":"空载荷遮蔽:…","suggestion":"写清桩的返回值(如 `(None)` 或 `(0)`)…"} -``` - ---- - -## 2. 实现 - -### 2.1 新增 `src/label.rs` - -- `OcclusionSite { label, has_payload, line, unit }` -- `collect(module)`:遍历函数体与嵌套语句/表达式,收集所有遮蔽点 - (描述只读,**不产生任何读引用**) -- `check(module, path)`:产出上面两条诊断 - -### 2.2 接入 `check_module` - -```rust -walk(module, &module.functions, path, &known, &mut out); -out.extend(crate::label::check(module, path)); // M2.5 -``` - -设计上把"标签诊断"独立成模块,M4(引用一致性)与 M9(检索)都往这里加, -`check` 只做一行汇总。 - ---- - -## 3. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 集成(3 新) | 空描述 → exit 1 + 文案;空载荷 → exit 0 + 文案;干净样例 → 无诊断 | ✅ | -| 全量 | `cargo test --release` | **578 passed / 0 failed**(M2 后 575 + 3) | - -反向验证:三条断言分别验证"会响"与"不会误响"(干净样例必须无输出)。 - ---- - -## 4. 边界 - -| 项 | 说明 | -|----|------| -| 描述内容不校验 | 写什么都可以;M4 才校验反引号引用 | -| 空载荷仅在 occlusion 模式可能出现 | classic 模式下 `()` 空是语法错 | -| warning 不影响退出码 | 与既有 `Severity` 语义一致 | - ---- - -## 5. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/label.rs` | **新增**:遮蔽点收集 + 两类诊断 | -| `src/lib.rs` | `pub mod label;` | -| `src/check.rs` | `check_module` 追加 label 诊断 | -| `tests/occlusion.rs` + `tests/occlusion/{empty-label,empty-payload,clean}.mq.md` | 新增 3 个集成测试与样例 | -| `doc/design/change-m25-label-diagnostics.md` | 本文件 | diff --git a/doc/design/change-m3-access-and-loop.md b/doc/design/change-m3-access-and-loop.md deleted file mode 100755 index 70b86e6..0000000 --- a/doc/design/change-m3-access-and-loop.md +++ /dev/null @@ -1,89 +0,0 @@ -# 变更记录:M3 `access` 与遮蔽循环 - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M3([occlusion-syntax.md](occlusion-syntax.md) §4 / §13) | -| 改动文件 | `src/interp.rs` · `src/ast.rs` · `src/parse/mod.rs` · `src/bytecode/compile.rs` · `tests/occlusion.rs` | -| 影响面 | 新增内建 `access`;`Stmt::ForEach` 增可选标签 | - ---- - -## 1. `access(集合, 键)` - -旧取元 `[键](集合)` 的语义是**多态**的:Map 按键、List 按 1-based 下标、缺键报错。 -纯度路线把取元移进 `()`,因此需要一个与之**完全等价**的调用形式: - -```markdown -**a = [取表项](access(`表`, "键"))** -**b = [取列表第二项](access(`列`, 2))** -``` - -- 别名:`取` / `取值` / `access` -- 缺键 → `missing map key …`(**与旧取元同一错误**,不静默返回 None) -- 用途:M7 迁移把 `[k](c)` 机械改写成 `access(c, k)`,语义零漂移 - -实现:`interp.rs` 的 special-callee 分派里直接复用 `builtin_footnote_get`, -**不新增平行实现**(避免两套索引语义)。 - ---- - -## 2. 遮蔽循环 - -```markdown -- [篮子里的每个果子](遍历 `列` 为 `果`) - > print text=`果` -``` - -- 只在 occlusion 模式识别(classic 模式下 `- [x](c)` 仍是旧 foreach) -- 接受 `遍历`/`for` 与 `为`/`as`/`in` -- 描述存入 `Stmt::ForEach.label`(`Option`),供 M8 渲染/诊断使用 - -实测: - -``` -a=值 -b=二 -果子=一 -果子=二 -``` - ---- - -## 3. 为什么先做 M3 再做 M7 - -迁移(M7)要把 506 处 `[k](c)` 改写掉,而改写目标必须**先存在且等价**。 -先有 `access` 与循环新形,迁移才是"机械替换",而不是"边迁移边发明语义"。 - ---- - -## 4. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 集成(2) | `access` 表/列表 + 循环遍历输出正确;缺键报 `missing map key`(与旧取元一致) | ✅ | -| 全量 | `cargo test --release` | **595 passed / 0 failed**(M5 后 593 + 2) | - ---- - -## 5. 边界 - -| 项 | 说明 | -|----|------| -| `access` 不做缺省值 | 缺省语义请用 `get(表, 键, 默认)`;两者并存 | -| 循环描述暂只存不用 | M8 在 `view` 与诊断里使用 | -| 旧 foreach 仍可用 | M7 迁移并加门禁后才变成错误 | - ---- - -## 6. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/interp.rs` | `access` / `取` / `取值` 分派(复用 `builtin_footnote_get`) | -| `src/ast.rs` | `Stmt::ForEach.label: Option` | -| `src/parse/mod.rs` | `parse_occluded_foreach`;occlusion 模式下优先识别 | -| `src/bytecode/compile.rs` / `src/ast.rs` / `src/interp.rs` | 穷举模式补 `label: _` | -| `tests/occlusion.rs` + `tests/occlusion/access-and-loop.mq.md` | 2 个集成测试 | -| `doc/design/change-m3-access-and-loop.md` | 本文件 | diff --git a/doc/design/change-m4-label-refs.md b/doc/design/change-m4-label-refs.md deleted file mode 100755 index 46ab1eb..0000000 --- a/doc/design/change-m4-label-refs.md +++ /dev/null @@ -1,84 +0,0 @@ -# 变更记录:M4 L1 引用一致性(`label.ref_dangling`) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M4([label-freshness-and-repair.md](label-freshness-and-repair.md) §3.1 / [occlusion-syntax.md](occlusion-syntax.md) §11.1) | -| 改动文件 | `src/label.rs` · `tests/occlusion.rs` · `tests/occlusion/ref-*.mq.md` | -| 影响面 | `marqdo check`(新增一条 error) | - ---- - -## 1. 规则 - -> 描述里用反引号写出的名字 = **断言**:它必须能解析 -> —— 要么 `()` 的实现用到它,要么文档里定义了它,要么它是内置函数。 - -```markdown -**a = [按 `税率` 计算](100 * 0.1)** # ❌ label.ref_dangling(税率为空悬) -**b = [按 `税率` 算](100 * `税率`)** # ✅ 实现里用到 -**c = [取长度](len("abc"))** # ✅ 内置函数 -**d = [用 `加` 求和](> 加 1 2))** # ✅ 模块内函数 -``` - -实测: - -``` -dangling.mq.md:3:1: 描述引用了不存在的实体:`税率` —— 本段实现没有用到它,模块里也没有定义 -contract check: 1 条诊断(1 error) # exit 1 -``` - ---- - -## 2. 为什么只认反引号(可证伪原则) - -| 写法 | 是否检查 | 原因 | -|------|---------|------| -| `` `税率` `` | ✅ | 显式引用,可证伪 | -| 普通汉字"税率" | ❌ | 自然语言无法机械判定,检查必然假阳性 | - -代价:作者不写反引号就得不到保护。这是刻意的——**机器只校验它看得懂的断言**, -同时反向抑制"为凑数写废话"。 - ---- - -## 3. 实现 - -| 环节 | 做法 | -|------|------| -| 抽取 | `refs(label)`:扫描成对反引号,取内部去空白;未闭合/空串忽略 | -| 作用域 | `payload_idents(payload)`(Var / callee / path / receiver / `[k]` 的变量键 / 插值变量)∪ `module_symbols(module)`(函数与子函数、参数、import/use 绑定、frontmatter 键)∪ `HostFn::from_name` | -| 诊断 | `label.ref_dangling`,**error**,带 `doc_quote`(描述原文)与可执行建议 | - -`OcclusionSite` 增加 `payload_idents` 字段,在 `collect` 阶段一次算好,`check` 只做集合查找。 - ---- - -## 4. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 单元(3) | 单引用 / 多引用与散文混排 / 无引用与未闭合反引号不 panic | ✅ | -| 集成(2) | 悬空引用 exit 1 + 文案;三类可解析引用(payload 变量 / 内置 / 模块函数)零诊断 | ✅ | -| 全量 | `cargo test --release` | **583 passed / 0 failed**(M2.5 后 578 + 5) | - ---- - -## 5. 边界与后续 - -| 项 | 说明 | -|----|------| -| 只查"能否解析" | 不查"语义是否仍成立"——那是 T1(M6)与人工/LLM 复核的活 | -| 不查"能解析但实现没用到" | 该情形在模块级符号时无法区分误报,留待 T1 变更驱动 | -| 描述里的反引号不是变量绑定 | 只是断言,不进入任何作用域 | - ---- - -## 6. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/label.rs` | `refs()` · `payload_idents()` · `module_symbols()` · `OcclusionSite.payload_idents` · `check` 增 `label.ref_dangling` · 3 个单测 | -| `tests/occlusion.rs` + `tests/occlusion/{ref-dangling,ref-ok}.mq.md` | 2 个集成测试 | -| `doc/design/change-m4-label-refs.md` | 本文件 | diff --git a/doc/design/change-m5-implicit-occlusion.md b/doc/design/change-m5-implicit-occlusion.md deleted file mode 100755 index 81addde..0000000 --- a/doc/design/change-m5-implicit-occlusion.md +++ /dev/null @@ -1,103 +0,0 @@ -# 变更记录:M5 隐式遮蔽(`>` 调用上方的叙述) - -| | | -|---|---| -| 状态 | **Implemented**(**默认关闭**,`--implicit-labels` 开启) | -| 日期 | 2026-10-22 | -| 里程碑 | M5([occlusion-syntax.md](occlusion-syntax.md) §11.2) | -| 改动文件 | `src/label.rs` · `src/check.rs` · `src/main.rs` · `tests/occlusion.rs` | -| 影响面 | `marqdo check` 新增可选检查(默认不改变输出) | - ---- - -## 1. 规则 - -> **`>` 调用上方的叙述段**就是它的"描述";段内的反引号实体必须被这次调用用到 -> (或能解析到模块/内置)。 - -```markdown -按 `税率` 与 `档位` 计算应缴税额: ← 描述 - -> 计税 档位=2 金额=100 ← 实现用到了 `档位`,但没有 `税率` -``` - -``` -impl.mq.md:5:1: 调用上方的描述提到 `税率`,但这次调用没有用到它 -``` - -段落边界:紧邻上一行起,遇空行(允许**一个**分隔空行,因为 blockquote 前通常空一行)、 -标题、代码行(`**`/`>`/`-`/`|`/数字开头)即止。 - ---- - -## 2. 关键决策:**默认关闭** - -这不是洁癖,是实测结论: - -| 阶段 | lib + ext/ai 上的警告数 | -|------|------------------------| -| 初版(任何反引号都算断言) | **6 条**(全部误报:`` `## open` ``、`` `{ path, kind }` ``、`` `source=` ``、`` `exec` ``/`` `net` ``) | -| 加"实体名形状"过滤 | 2 条 | -| **再加默认关闭** | **0 条** | - -理由:**描述一个调用可以用任意措辞**,这比"遮蔽"松散得多; -机械校验必然模糊,默认开启就会制造疲劳(违背 [warning-fatigue-control.md](warning-fatigue-control.md))。 -所以它和 L1 不同:L1 是"能证明才报",隐式检查是"觉得可疑就报"——后者必须 opt-in。 - ---- - -## 3. 实体名过滤(降低误报) - -反引号内容必须**像实体名**才算断言: - -```rust -首字符:字母 / `_` / 非 ASCII(不能是数字) -其余:字母数字 / `_` / `.` / 非 ASCII 且非空白 -``` - -于是 `` `## open` ``、`` `{ path, kind }` ``、`` `source=` ``、`` `path=` `` 全部被排除。 - ---- - -## 4. 用法 - -```bash -marqdo check 文件.mq.md # 默认:不含隐式检查(零噪音) -marqdo check 文件.mq.md --implicit-labels # 开启 -``` - -MLSP 侧留了同义参数位(`validate` 的 `implicit_labels`),M8 一并接。 - ---- - -## 5. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 集成(3) | 默认静默;opt-in 报不一致;opt-in 对一致描述仍静默 | ✅ | -| 全量 | `cargo test --release` | **593 passed / 0 failed**(M6 后 590 + 3) | - -**反向验证**:`implicit_labels_off_by_default` 与 `..._stays_quiet_when_consistent` -两条都在证明"不乱响"。 - ---- - -## 6. 边界 - -| 项 | 说明 | -|----|------| -| 只查 `>` 语句调用 | 表达式内调用没有"上方叙述"这回事 | -| 只认反引号 + 实体形状 | 普通散文永远不参与 | -| 不查 payload 语义 | 只查"提到的实体是否被用到" | - ---- - -## 7. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/label.rs` | `CallSite` · `call_sites` · `paragraph_above` · `is_entity_ref` · `check_implicit` | -| `src/check.rs` | `check_path_opts(path, implicit_labels)`(`check_path` 保持默认关闭) | -| `src/main.rs` | `check --implicit-labels` | -| `tests/occlusion.rs` + `tests/occlusion/implicit-*.mq.md` | 3 个集成测试 | -| `doc/design/change-m5-implicit-occlusion.md` | 本文件 | diff --git a/doc/design/change-m6-t1-session.md b/doc/design/change-m6-t1-session.md deleted file mode 100755 index 5cd421e..0000000 --- a/doc/design/change-m6-t1-session.md +++ /dev/null @@ -1,109 +0,0 @@ -# 变更记录:M6 T1 会话内陈旧检测 + 会话末汇总 - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M6([t1-session-staleness.md](t1-session-staleness.md) · [staleness-providers.md](staleness-providers.md) T1) | -| 改动文件 | `src/label.rs` · `src/mlsp.rs` · `src/view/mod.rs` · `tests/occlusion.rs` | -| 影响面 | MLSP `repair_apply` 新增可选字段;新增 `session.summary` 方法 | - ---- - -## 1. 机制 - -`repair_apply` 内部同一作用域里同时有 `source`(改前)与 `new_source`(改后), -所以「描述是否还成立」可以**纯内存**判定: - -``` -stale ⟺ 标签文本未变 ∧ payload 指纹变了 -``` - -配对按 `(标签文本, 出现序号)`,因此**移动代码不会误报**。 - -请求: - -```json -{"method":"repair_apply","params":{ - "source":"…","ranges":[[3,3]], - "edits":[{"op":"replace","line":3,"text":"**a = [按税率算总价](100 * 0.2)**"}], - "check_labels":true}} -``` - -响应: - -```json -{"id":1,"ok":true,"result":{ - "source":"…","edits_applied":1, - "labels":{"newly_seen":1,"stale":[ - {"label":"按税率算总价","line":3, - "code_past":"100 * 0.1","code_now":"100 * 0.2"}]}}} -``` - -**同一份 `source` / `new_source` 就是"前一状态"**——不需要 git、不需要台账、 -不需要沙箱里的 exec 权限。这是"agent 回路不需要 VCS"的落地。 - ---- - -## 2. 会话末汇总(你要求做) - -`session.summary` 返回并**重置**计数: - -```json -{"ok":true,"labels_stale_seen":1,"labels_fixed":0, - "labels_outstanding":1,"items":["按税率算总价"]} -``` - -| 字段 | 含义 | -|------|------| -| `labels_stale_seen` | 本次会话累计发现过多少条(去重按标签) | -| `labels_fixed` | 曾经 outstanding、现在不再 stale 的条数 | -| `labels_outstanding` | 仍未处理 | -| `items` | 未处理的标签文本(只给文本,不重复诊断细节) | - -设计:客户端在收尾时调用一次即可闭合;**不主动打屏**,不污染协议。 - ---- - -## 3. 关键取舍 - -| 取舍 | 理由 | -|------|------| -| `check_labels` 默认 **false** | 零开销、零噪音;agent 框架在修复回路里显式打开 | -| 标签变了 → **不报** | 作者改描述本身就是"已复核"的信号 | -| 新标签 → 不报 | 无历史可比 | -| 指纹用 `Debug` | **只需进程内一致**;跨版本稳定指纹是 T2/T3 的事 | -| payload 渲染用 `view::expr_display` | 让 `code_past/code_now` 是人能读的表面语法,而非 AST 调试串 | - ---- - -## 4. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 集成(3) | 只改 payload → `stale` 含 `code_past`/`code_now`;同时改标签 → `stale: []`;`session.summary` 计数正确 | ✅ | -| 全量 | `cargo test --release` | **590 passed / 0 failed**(M10 后 587 + 3) | - -**反向验证**:`t1_silent_when_label_also_changes` 证明"改描述即复核"不会误报。 - ---- - -## 5. 边界 - -| 项 | 说明 | -|----|------| -| 只看本次编辑 | 跨会话漂移是 T2/T3 的职责(可选 provider) | -| 解析失败则跳过 | 修复后的源码可能语法错误,此时不评测标签,交给 `validate` | -| 会话状态是进程级 | 一条 MLSP 连接(一个进程)即一个会话;`session.summary` 后清零 | - ---- - -## 6. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/label.rs` | `StaleItem` · `payload_fingerprint` · `compare` · `SessionSummary`(含 `record`)· `OcclusionSite.payload_fp/payload_src` | -| `src/mlsp.rs` | `repair_apply` 的 `check_labels`;`session.summary`;进程级 `SESSION` | -| `src/view/mod.rs` | `pub use render::expr_display`(供诊断渲染 payload) | -| `tests/occlusion.rs` | 3 个 T1 集成测试 | -| `doc/design/change-m6-t1-session.md` | 本文件 | diff --git a/doc/design/change-m7-migration.md b/doc/design/change-m7-migration.md deleted file mode 100755 index 61c37c1..0000000 --- a/doc/design/change-m7-migration.md +++ /dev/null @@ -1,127 +0,0 @@ -# 变更记录:M7 迁移与版本门(per-file 标记 + `migrate labels` + 全仓迁移) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M7([occlusion-syntax.md](occlusion-syntax.md) §13) | -| 改动文件 | **新增 `src/migrate.rs`** · `src/load.rs` · `src/parse/mod.rs`(expr) · `src/host/dispatch.rs` · **80 个语料文件** · 测试 | -| 影响面 | 语法模式按文件切换;全仓 256 处索引 + 23 处循环已迁移 | - ---- - -## 1. 原计划的问题:同形换义 - -原设计想"翻转默认 + 对旧形硬报错"。但 `[键](集合)` 与 `[描述](实现)` **外形完全相同**: - -- 翻转默认 → 506 处取元**静默变成**"遮蔽整个集合",正是文档点名的最坏变更 -- 硬报错 → 无法实现:解析器拿不到"这是旧写法"的证据(两种读法都合法) - -**结论:模式不能全局翻转,必须按文件声明。** - -## 2. 新方案:per-file `markup:` - -```markdown ---- -markup: occlusion ---- -``` - -| 文件 | 解析模式 | `[a](b)` 的含义 | -|------|---------|----------------| -| 无 `markup:` | classic(进程默认) | 取元 | -| `markup: occlusion` | 纯度 | 遮蔽 | - -实现:`load.rs` 先读 frontmatter 取出模式,用 `parse::expr::with_markup(m, …)` -(线程局部覆盖,压栈/出栈)包住解析。**同一进程里可以同时加载两种模式的文件** -(imports!),且 `MARQDO_MARKUP=occlusion` 仍可作为进程默认。 - -好处:迁移是**逐文件、可增量、可回滚**的;不存在"半迁移的静默错义"。 - -## 3. 迁移工具 `marqdo migrate labels` - -```bash -marqdo migrate labels . # 干跑:列出将改什么 -marqdo migrate labels . --write # 实际写入 -marqdo migrate labels . --json # 机器可读 -``` - -### 3.1 改写规则 - -| 旧 | 新 | -|----|----| -| `[键](集合)` | `[键](access(集合, "键"))` | -| `` [`名`](集合) `` | `` [名](access(集合, `名`)) `` | -| `- [项](集合)` | `- [项](遍历 集合 为 项)` | - -`access` 是新增宿主函数(`host_access`,id 212),语义与旧取元**逐字一致** -(Map 按键 / List 1-based / 缺键 `missing map key`)。它进 `HostFn` 是有意的: -**两个后端共用同一实现**,不再有特例分支。 - -### 3.2 安全模型:改写 → 重解析 → 证明等价 → 才写 - -1. 原文件按 classic 解析,得到 AST-A -2. 文本改写后,按 occlusion 解析,得到 AST-B -3. **反归一化** B:把"标签与键同名 + payload 为 `access(x, k)`"的遮蔽还原成 `Index` -4. 比较 `Debug(A)` 与 `Debug(反归一化(B))`(抹掉行号,因为插入了 marker 行) -5. 只有相等才写入;否则**原文件一字不动**并报告 `equivalence check failed` - -这条校验是真干活的:它先后抓出 4 类改写 bug(表格散文链接、payload 继承文本模式、 -链式索引、`[问候] (…)` 与遮蔽混淆),每一类都是**先被拦下、再修工具**,没有污染文件。 - -### 3.3 只改代码行 - -用词法层的 `LineKind::Code` 限定范围;表格行只改 `**…**` 单元格 -(散文里的 markdown 链接 `[docs](https://…)` 必须原样保留)。 - -### 3.4 由内向外 - -链式索引 `[content]([1]([messages](req)))` 必须**最内层先改**, -否则外层改写会让内层的位置失效;已迁移的 `[k](access(…))` 有守卫,不会二次改写。 - -## 4. 全仓迁移结果 - -``` -migrate labels: 256 index, 23 loop, 80 file written -``` - -- 覆盖 `lib/ ext/ examples/ public/ cli/ tests/` -- **0 文件被等价性检查拒绝** -- 迁移后 `cargo test --release` → **604 passed / 0 failed** -- 再跑一次迁移 → **幂等**(只剩刻意保留的 classic 测试样例) - -## 5. 顺带修的两处真实语义缺陷 - -| 缺陷 | 现象 | 修法 | -|------|------|------| -| payload 继承外层"文本模式" | `f text=[k](access(c,k))` 里 `access(...)` 不被当调用 → 退化成插值文本 | `()` 内**永远**允许 `callee(args)`(`parse_occluded` 临时置位) | -| 遮蔽形状判定过宽 | `[问候] ([格式化] "Bo")` 被误判为遮蔽 | 要求 `]` 后**紧跟** `(`;否则落回方括号调用 | - -## 6. 版本门 - -- 旧写法**不再**被硬报错——因为无法与遮蔽区分;真正的门是 **per-file 声明**: - 没写 `markup: occlusion` 的文件按 classic 解析,行为不变。 -- 需要"禁止新写旧形"的仓库可用 `migrate labels` 干跑做 CI 门禁(有改动即失败)。 - -## 7. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 单元(6) | 静态键 / 动态键 / 嵌套三层 / 已迁移不重写 / 循环 / 非循环 | ✅ | -| 集成(3) | 干跑不写盘;写入后**运行输出不变**且幂等;等价失败则文件不动 | ✅ | -| 全量 | `cargo test --release` | **604 passed / 0 failed**(M3 后 595 + 9) | -| 双后端 | gold 套件含 bytecode 变体 | ✅ | - -## 8. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/migrate.rs` | **新增**:改写器、等价性证明、`migrate_file` / `migrate_path` | -| `src/load.rs` | `frontmatter_markup` + `with_markup` 包裹两处 `parse_source` | -| `src/parse/expr.rs` | `with_markup` 线程局部覆盖;`()` 内强制允许调用;`occlusion_shape_ahead` 严格判定 | -| `src/host/dispatch.rs` | `HostFn::Access`(enum / from_u16 212 / from_name / name / required_params / call_host) | -| `src/main.rs` | `migrate labels` 子命令 | -| `src/interp.rs` | 移除 access 特例(改用 HostFn,单一实现) | -| 80 个语料文件 | 索引与循环迁移 + `markup: occlusion` 标记 | -| `tests/migrate.rs` + `src/migrate.rs` 单测 | 9 个测试 | -| `doc/design/change-m7-migration.md` | 本文件 | diff --git a/doc/design/change-m8-ratchet.md b/doc/design/change-m8-ratchet.md deleted file mode 100755 index c0bc97f..0000000 --- a/doc/design/change-m8-ratchet.md +++ /dev/null @@ -1,81 +0,0 @@ -# 变更记录:M8 债务棘轮与呈现 - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M8([warning-fatigue-control.md](warning-fatigue-control.md) §4 棘轮 · [occlusion-syntax.md](occlusion-syntax.md) §13) | -| 改动文件 | `src/main.rs` · `tests/ratchet.rs` | -| 影响面 | `labels` 新增 `--baseline` / `--fail-on-increase` | - ---- - -## 1. 棘轮规则 - -```bash -# CI:未完成项只许减少,不许增加 -marqdo labels . --baseline .marqdo/pending.json --fail-on-increase -``` - -| 情形 | 行为 | 退出码 | -|------|------|--------| -| 台账不存在 | **建立**(写入当前计数),提示 `已建立 N` | 0 | -| 当前 > 台账 | 失败,提示 `未完成项增加了 K` | **1** | -| 当前 ≤ 台账 | 通过;若减少则**收紧**台账(`N → M`) | 0 | - -**为什么"减少即收紧"**:否则债务可以先降后升,棘轮形同虚设。 -收紧后台账记住新的低水位,回退到旧数量同样会失败(测试第 4 步验证)。 - -台账格式: - -```json -{"count": 1, "words": ["待开发", "未开发", "…"]} -``` - -记录词集是为了让"口径变了"可被审计——换词集时会看到 `words` 变化。 - ---- - -## 2. 为什么用棘轮而不是硬门禁 - -| 方案 | 老债 | 新债 | 结论 | -|------|------|------|------| -| 硬门禁(必须为 0) | 阻塞一切 | 拦住 | 存量债立刻红一片,逼人关检查 | -| **棘轮(只拦增量)** | 不阻塞 | 拦住 | ✅ 债务可见且不恶化 | -| 无门禁 | 不阻塞 | 不拦 | 债务无声增长 | - -这与 [warning-fatigue-control.md](warning-fatigue-control.md) 的结论一致: -**老账不追、新账必拦**。 - ---- - -## 3. 呈现(已具备) - -| 面 | 表现 | -|----|------| -| `expr_display` / `view` | 遮蔽渲染为 `[描述](实现)`,桩渲染为 `[描述]()`,实测 `view output` 页面含 `access(` | -| `labels` | 人类行 `文件:行 [函数] 描述 ← 命中词`;`--json` 一个数组 | -| `check` | `label.*` 三类诊断(missing / empty_payload / ref_dangling) | -| MLSP | `labels.search` · `session.summary` | - -**没有做桩徽章**:桩已经是 `[描述]()` 这个显眼形状,再加装饰是噪音; -需要计数时用 `labels --count`。 - ---- - -## 4. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 集成(1 个四步用例) | 建账 → 增加失败 → 减少收紧 → 回退再次失败 | ✅ | -| 全量 | `cargo test --release` | **605 passed / 0 failed**(M7 后 604 + 1) | - ---- - -## 5. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/main.rs` | `labels --baseline` / `--fail-on-increase`;建账/收紧/违约逻辑 | -| `tests/ratchet.rs` | 四步棘轮用例 | -| `doc/design/change-m8-ratchet.md` | 本文件 | diff --git a/doc/design/change-m8-view-occlusion.md b/doc/design/change-m8-view-occlusion.md deleted file mode 100755 index feac109..0000000 --- a/doc/design/change-m8-view-occlusion.md +++ /dev/null @@ -1,89 +0,0 @@ -# 变更记录:M8 view 遮蔽呈现(+ 修一个真实回归) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 来源 | [occlusion-syntax.md](occlusion-syntax.md) §13 M8「view 徽章/呈现」 | -| 改动 | `src/load.rs` · `src/view/{document,render,html,mod,debug_page}.rs` | -| 影响 | 只影响呈现;顺带修了 **view 无法解析遮蔽文件** 的回归 | - ---- - -## 1. 先修回归:view 用错解析模式 - -`view` 内部多处直接用 `crate::parse::parse_source(source)` 重新解析文件, -而 per-file `markup:` 是在 `load` 层生效的(M7)。结果: - -``` -
parse/load error: expected ')' after link-index collection
-``` - -任何带 `markup: occlusion` 的文档在 view 里**结构区直接报错**,只能退化成源码视图。 -用户看到的"粗体里的 `[描述](实现)` 没渲染"其实是这个错误的表象。 - -**修法**:`load::parse_source_auto(source)` —— 先读 frontmatter 的 `markup:`, -用 `with_markup` 包住 `parse_source`,view 的五处解析点全部改用它。 - -## 2. 遮蔽呈现 - -### 2.1 浏览视图(`document.rs`,`/file`) - -```html -
- 留存 = - 客户留存率,模拟数据 - 0.42 -
-``` - -- 空载荷 → `桩`(琥珀色徽章,title 说明"未接通或待补返回值") -- 前缀里的反引号/`**` 都剥掉(与其它行 `mq-anchor` 的处理一致) -- 只在词法上切分,不改语义:解析器早已验证结构,这里只决定怎么画 - -### 2.2 卡片视图(`render.rs`,`/debug`) - -按 AST 直接匹配 `Expr::Occluded`(`Assign` / `Expr` / `Return` 三种语句), -渲染成 `card occl-card`:徽章「遮蔽」+ 变量名 + 描述 + 代码片/桩徽章。 - -### 2.3 样式(`html.rs`) - -```css -.doc-occl { display:flex; align-items:baseline; flex-wrap:wrap; gap:.4rem; } -.occl-pre { font-family:var(--mono); font-size:.86em; color:var(--muted); } -.occl-label { color:var(--ink); } -.occl-code { font-family:var(--mono); background:var(--fill); border:1px solid var(--line); - border-radius:6px; padding:.02rem .38rem; } -.occl-stub { background:rgba(255,159,10,.18); color:#9a5b00; border-radius:999px; } -``` - -刻意**不加**虚线下划线:容易被读成链接/缩写。描述就是正文,靠代码片的边框与之区分。 - -## 3. 验证 - -| 项 | 结果 | -|----|------| -| 结构区解析错误 | **消失**(`/file` 页面 0 处 `parse/load error`) | -| 七个遮蔽行 | 全部渲染为 `doc-occl`:6 个代码片 + 1 个桩徽章 | -| 文本抽取 | `留存 = 客户留存率,模拟数据 [0.42]` / `待接 = 搜索接入,接口未接,待开发 [桩]` | -| 单元(4) | 裸赋值 / 粗体赋值 / 空载荷+嵌套 payload / 非遮蔽行不误判 | -| 全量 | `cargo test --release` **613 passed / 0 failed**(609 + 4) | - -## 4. 未能做到的:截图 - -本机没有任何浏览器(`chromium`/`chrome`/`firefox` 均不存在), -`npm i puppeteer` 装上了包但 Chromium 下载被网络阻断(`storage.googleapis.com` -TLS 断连,两次重试均失败)。所以无法自动截图比对,改为: -DOM 结构断言 + 提供 `/.preview/occlusion.html` 方案对照页由作者目视确认。 - -## 5. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/load.rs` | 新增 `parse_source_auto`(按 frontmatter `markup:` 解析) | -| `src/view/mod.rs` | 3 处解析改 `parse_source_auto` | -| `src/view/debug_page.rs` | 1 处同上 | -| `src/view/document.rs` | `split_occlusion` / `match_delim` / `render_occlusion_line` + 4 个单测 | -| `src/view/render.rs` | `occl_card` + 三个 `Expr::Occluded` 语句分支 | -| `src/view/html.rs` | `.doc-occl` / `.occl-*` 样式 | -| `doc/design/change-m8-view-occlusion.md` | 本文件 | diff --git a/doc/design/change-m9-label-search.md b/doc/design/change-m9-label-search.md deleted file mode 100755 index 472ef65..0000000 --- a/doc/design/change-m9-label-search.md +++ /dev/null @@ -1,113 +0,0 @@ -# 变更记录:M9 两级词表检索(`labels` CLI + MLSP `labels.search`) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 里程碑 | M9([occlusion-description-and-search.md](occlusion-description-and-search.md) §3 · [occlusion-syntax.md](occlusion-syntax.md) §13) | -| 改动文件 | `src/label.rs` · `src/main.rs` · `src/mlsp.rs` · `tests/occlusion.rs` | -| 影响面 | 新增 CLI 子命令与 MLSP 方法(**不改语法**) | - ---- - -## 1. 两级词表 - -| 级 | 在哪 | 作用 | -|----|------|------| -| **第一级:内置** | `label::BUILTIN_GROUPS`(数据常量) | 默认查询 + LLM 范例 + 跨项目可比 | -| **第二级:参数** | `--grep` / `grep` | 替换或并集,项目自己的说法照样能搜 | - -内置六组:`未完成`(待开发/未开发/开发中/未实现/待实现/未接/接口未接/TODO)、 -`假数据`(模拟/假数据/桩/占位/stub/mock)、`示例`、`实验`、`废弃`、`待校验`。 -`pending` = `未完成 ∪ 假数据`。 - -**词表是数据不是语法**:扩充它不改任何解析规则。 - ---- - -## 2. CLI - -```bash -marqdo labels . # 默认:pending 口径(内置两组) -marqdo labels . --grep "联调" # 替换为自定义词 -marqdo labels . --grep "联调" --also-builtin # 自定义 ∪ 内置 -marqdo labels . --group 示例,实验 # 选内置组 -marqdo labels . --count # 只给数字(CI/棘轮用) -marqdo labels . --json # 一个 JSON 数组 -``` - -输出(人类): - -``` -a.mq.md:3 [main] 按关键词检索,接口未接,待开发 ← 待开发,未接,接口未接 -a.mq.md:4 [main] 客户留存率,模拟 ← 模拟 -label search: 2 命中(1 文件,词=[…]) -``` - -`--json`: - -```json -[{"file":"a.mq.md","line":3,"unit":"main","label":"…","words":["待开发"],"has_payload":true}] -``` - ---- - -## 3. MLSP - -```json -{"id":1,"method":"labels.search", - "params":{"source":"…"|"path":"…","grep":["联调"],"also_builtin":true}} -``` - -返回: - -```json -{"ok":true,"words":[…],"count":2,"hits":[{"line":3,"unit":"main","label":"…", - "words":["待开发"],"has_payload":true}]} -``` - -语义与 CLI 完全一致(同一份 `label::search`)。 - ---- - -## 4. 检索语义(v1) - -| 项 | 规则 | -|----|------| -| 匹配 | **子串**(CJK 无词边界,子串最稳) | -| 多词 | OR | -| 大小写 | 英文不敏感(`TODO`/`todo` 等价) | -| 误判 | 必然存在(`[不属于待开发范围]` 会命中)——只影响计数,输出带描述原文可人工判断 | - -不做否定语法;留作 v1.1 可选项。 - ---- - -## 5. 测试 - -| 层 | 内容 | 结果 | -|----|------|------| -| 集成(4) | pending 计数=2;`--grep` 替换=1;`--also-builtin` 并集=3;MLSP `labels.search` 返回 hits | ✅ | -| 全量 | `cargo test --release` | **587 passed / 0 failed**(M4 后 583 + 4) | - ---- - -## 6. 边界 - -| 项 | 说明 | -|----|------| -| 只在 occlusion 模式产生命中 | classic 模式下没有 `Expr::Occluded`;M7 翻转默认后自然可用 | -| 解析失败的文件跳过 | 那是 `check` 的职责,检索不应因一个坏文件整体失败 | -| 不做棘轮 | `--baseline` / `--fail-on-increase` 留给 M8(门禁) | - ---- - -## 7. 变更清单 - -| 文件 | 变更 | -|------|------| -| `src/label.rs` | `WordGroup` / `BUILTIN_GROUPS` / `PENDING_GROUPS` / `group_words` / `parse_words` / `matched_words` / `Hit` / `search` | -| `src/main.rs` | `labels` 子命令 + `collect_mq_files` 递归扫描 | -| `src/mlsp.rs` | `labels.search` 方法 + 分发 | -| `tests/occlusion.rs` + `tests/occlusion/labels.mq.md` | 4 个集成测试 | -| `doc/design/change-m9-label-search.md` | 本文件 | diff --git a/doc/design/change-plugin-sdk.md b/doc/design/change-plugin-sdk.md deleted file mode 100755 index edf7651..0000000 --- a/doc/design/change-plugin-sdk.md +++ /dev/null @@ -1,103 +0,0 @@ -# 变更记录:插件 ABI 共享 crate(`marqdo-plugin-sdk`) - -| | | -|---|---| -| 状态 | **Implemented** | -| 日期 | 2026-10-22 | -| 来源 | [code-volume-audit.md](code-volume-audit.md) §4 第 1 项 | -| 改动 | **新增 `crates/marqdo-plugin-sdk`** · 5 个插件改为依赖它 | -| ABI | **不变**(`include/marqdo_abi.h`、`src/host/plugin.rs` 看到的符号与布局完全一致) | - ---- - -## 1. 问题 - -5 个原生插件各自复制同一套 ABI 前言(约 140 行/个): - -| 复制的内容 | 说明 | -|-----------|------| -| `type PluginFn` / `HostQueryFn` / `struct MarqdoHostApi` | 布局必须逐字一致,抄错就是 UB | -| `static mut HOST_ALLOC/FREE/QUERY/USERDATA` | 同上 | -| `host_strdup` / `set_out` / `set_err` / `parse_args` / `reply` | 语义必须一致 | -| `register` + `#[no_mangle]` 四导出 | 样板 | - -一共 5 份,任何一份漂移都会在运行期表现为"某插件偶发崩"。 - -## 2. 方案 - -新增工作区成员 `crates/marqdo-plugin-sdk`,持有唯一一份实现,并提供一个宏生成各 `.so` 必需的导出: - -```rust -marqdo_plugin!(marqdo_plugin_sdk::ABI_VERSION, [ - ("llm_ping", "", llm_ping), - ("llm_chat_completions", "base_url,api_key,...", llm_chat_completions), -]); -``` - -宏展开为 `marqdo_plugin_abi_version` / `marqdo_plugin_shutdown` / `marqdo_plugin_init`, -其中 init 调 `init_plugin(host, &[…])`(保存回调 + 逐个注册)。 - -`demo` 是 ABI **v1**,宏接受版本参数:`marqdo_plugin!(1, [...])`,语义不变。 - -## 3. 安全措施:注册项逐一核对 - -迁移时把每个插件的 `register(...)` 调用抽取成表。**第一次抽取漏了 11 项**—— -正则是 `[a-z_0-9]+`,匹配不到 `mcp_server::agent_mcp_serve`、`sandbox::*` 这类 -**路径限定**的函数名。编译能过(表少几行),运行时才会 `unknown function`。 - -补救:正则允许 `::`,并把新旧两张表逐项比对: - -| 插件 | HEAD 注册项 | 迁移后 | 差异 | -|------|------------|--------|------| -| agent | 63 | 63 | **0** | -| quantum | 41 | 41 | 0 | -| linalg | 31 | 31 | 0 | -| llm | 2 | 2 | 0 | -| demo | 2 | 2 | 0 | - -比对脚本同时校验 `(名称, 参数串, 函数)` 三元组完全一致,不只比数量。 - -另外两次由"编译通过但语义已变"暴露的问题: - -| 问题 | 现象 | 处理 | -|------|------|------| -| `mcp_client` 被误判为死模块 | 我删掉 327 行后发现 `agent_mcp_client` 正注册它 | 恢复模块(教训:先查注册表,再判死) | -| 量子插件两个"未使用"函数 | 删除时连带吃掉 `density_from_amps`/`flat_to_nested` | 恢复并加 `#[allow(dead_code)]` 注释 | - -## 4. 收益 - -| 插件 | 迁移前 | 迁移后 | 变化 | -|------|--------|--------|------| -| agent | 1,237 | 929 | −308 | -| quantum | 1,045 | 835 | −210 | -| linalg | 688 | 524 | −164 | -| llm | 405 | 278 | −127 | -| demo | 170 | 73 | −97 | -| 新增 SDK | — | 232 | +232 | - -净减 **≈ 906 − 232 = 674 行**,且 ABI 前言从 5 份变 1 份。 - -## 5. 验证 - -| 项 | 结果 | -|----|------| -| `cargo build --release`(含 5 个插件) | 零警告 | -| `cargo test --release` | **609 passed / 0 failed** | -| 金样实跑(量子) | `p00-ok` / `p11-ok` / `ping-ok` | -| 注册项三元组比对 | 5 个插件全部 0 差异 | - -## 6. 边界 - -- ABI 版本号、`#[no_mangle]` 符号、结构体布局**一律未变**;旧 `.so` 与新宿主仍可互操作。 -- 插件私有逻辑(HTTP、矩阵、量子态、agent 工具)一行未动。 -- 后续新增插件只需依赖 SDK + 一行宏调用。 - -## 7. 变更清单 - -| 文件 | 变更 | -|------|------| -| `crates/marqdo-plugin-sdk/{Cargo.toml,src/lib.rs}` | **新增**:ABI 类型、静态回调、`host_strdup/set_out/set_err/parse_args/reply/host_query_json(_with)/take_host_string/init_plugin`、`marqdo_plugin!` 宏 | -| `Cargo.toml` | workspace 增加 `crates/marqdo-plugin-sdk` | -| `plugins/{agent,quantum,linalg,llm,demo}/Cargo.toml` | 增加 SDK 依赖 | -| `plugins/*/src/lib.rs` | 删除本地 ABI 前言与四导出,改用宏;注册表改为数组 | -| `doc/design/change-plugin-sdk.md` | 本文件 | diff --git a/doc/design/code-as-docs-gaps.md b/doc/design/code-as-docs-gaps.md deleted file mode 100755 index faf1734..0000000 --- a/doc/design/code-as-docs-gaps.md +++ /dev/null @@ -1,119 +0,0 @@ -# 代码即文档 · 叙述面摩擦(v0.3 实测) - -| | | -|---|---| -| 状态 | **Done** | -| 日期 | 2026-09-14 | -| 触发 | `examples/code-as-docs/index.mq.md` 试跑 | -| 宪法 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) | -| 路线 | [code-as-docs-gaps.md](../roadmap/code-as-docs-gaps.md) | - ---- - -## 0. 原则 - -修复必须同时服务: - -1. **代码即文档**:人读 Markdown 时自然段落、分隔线、强调不应被误伤。 -2. **适配 LLM 输出**:模型习惯写 `---` 分段、`**加粗强调**`、`0.85` 小数、`` map[^`key`] `` 动态键——运行时应尽量「写出来就能跑」。 -3. **可执行标记仍清晰**:真正的赋值 / 调用 / 返回不被误判成装饰。 - ---- - -## 1. 四个问题(实测) - -### G1 — 模块级 `---` 被当成结构错误 - -| | | -|---|---| -| 现象 | 文件标题段落后写 Markdown 分隔线 `---`,报 `expected heading … got: ---` | -| 根因 | 词法上整行 `-`/`*` 为 Code;旧实现把函数体内 `---` 当收束,模块顶却当非法。现统一为叙述跳过 | -| 人/LLM 期望 | 任意处 `---` = GFM thematic break = **叙述噪音** | -| 决议 | **处处** frame 行 skip;副作用收束用 `*None*` / `**` / `****`(返回即结束函数体解析) | - -### G2 — 叙述里的 `**强调**` / `*斜体强调*` 被当成代码/返回 - -| | | -|---|---| -| 现象 | 「本文件既是**说明**也是**程序**」→ 粗体 `说明` 不是赋值/调用,解析失败;`*only*` 类英文强调升成返回/`only` 变量 | -| 根因 | v0.3 叙述扫描凡 `**…**` / `*…*` 一律可执行([prose.rs](../../src/parse/prose.rs));Skill 曾禁止强调,但与 LLM/Markdown 习惯冲突 | -| 人/LLM 期望 | 装饰性强调可出现;**像代码的**粗体/斜体仍执行 | -| 决议 | **形状启发式**(见 §2):像代码则执行,否则当作叙述装饰(不产生 Stmt,不升参) | - -### G3 — 小数面量 `0.85` 不可用 - -| | | -|---|---| -| 现象 | `**x = 0.85**` → `trailing input: ".85"`;`28 * 0.85` 解析错乱;即便进到求值,`*` 仍只接受 int | -| 根因 | 表达式主词只吃整数字面量(`Literal` 无 `Num`);运行时已有 `Value::Num`,二元运算未接浮点 | -| 人/LLM 期望 | `0.85`、`3.14`、`折扣=0.85` 可写可算 | -| 决议 | 解析 `数字.数字` → `Literal::Num`;`*` `/` `+` `-` 及比较在 `Int`/`Num` 间提升(与已有 `cmp_ord` 一致) | - -### G4 — 动态脚注键 `` 菜单[^`名`] `` - -| | | -|---|---| -| 现象 | `` 菜单[^`名`] `` → `missing map key ``名`` `(把字面 `` `名` `` 当键,或解析失败) | -| 根因 | `[^label]` 的 label 仅为**静态字符串**;AST `Expr::Index { label: String }` 无变量槽 | -| 人/LLM 期望 | 表/映射按变量取键:`` `菜单`[^`品名`] `` 或 `菜单[^`品名`]` | -| 决议 | 支持 `` [^`ident`] `` → 运行时用变量值作键(文本化后走现有 footnote get);静态 `[^拿铁]` 不变 | - ---- - -## 2. 粗体/斜体「像代码」启发式 - -### 粗体 `**inner**` → 可执行,当且仅当 - -满足任一: - -- 含 `=`(赋值 / 命名参数调用);或 -- 以 `>` 开头(显式调用);或 -- 含运算符 / 索引 / 调用形:`+ - * / ( ) [ ]`;或 -- 空白分词 ≥2 段,且其后段含数字面量、引号串、或 `=`(如 `**加一 37**`、`**print text="hi"**`) - -否则(如 `**说明**`、`**代码即文档**`)→ **装饰,忽略**。 - -### 斜体 `*inner*` → 返回,当且仅当 - -满足任一: - -- 空 / `None` / `无` / `空` / bool 字面;或 -- 以 `>` 开头;或 -- 含 `=` 或运算符 / 索引;或 -- **整行**仅为 `*…*`(含缩进)——整行返回 `*总额*` / `*n*`;或 -- 行内且前方紧邻「返回」二字(叙述「接着返回*n*」) - -否则行内简单词(如 `*only*`、`*named*`)→ **装饰,忽略**。 - -> 整行 `*n*` 仍是返回;行内「返回*n*。」仍是返回。英文强调词在句中被忽略。 - ---- - -## 3. 非目标 - -- 不恢复 v0.2 双模式 -- 不引入 `if`/`return` 关键字 -- 不把任意 `**任意自然语言句子**` 都当代码(必须过 §2) -- 动态键第一期只做 `` [^`ident`] ``,不做完整表达式 `[^a+b]` - ---- - -## 4. 验收 - -| 用例 | 期望 | -|------|------| -| 顶层段落之间的 `---` | 可解析、可运行 | -| 「既是**说明**也是**程序**」 | 可解析;无 Stmt | -| `**应付 = 原价 * 0.85**` / `折扣`=0.85 | 数值正确(浮点) | -| `` **价 = 菜单[^`名`]** ``(`名` 已绑定) | 取到对应价 | -| `examples/code-as-docs/index.mq.md` | 用回浮点折扣与动态键后仍绿 | -| 既有 `tests/markup-v03/*` 与 gold | 不回归 | - ---- - -## 5. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-14 | 初稿:四缝 + 启发式 + 验收 | -| 2026-09-14 | 落地:G1–G4 实现 + 金样;顶层 Comment 引言 skip | diff --git a/doc/design/code-volume-audit.md b/doc/design/code-volume-audit.md deleted file mode 100755 index d6e01b7..0000000 --- a/doc/design/code-volume-audit.md +++ /dev/null @@ -1,103 +0,0 @@ -# 代码体量审计:53k 行里哪些是特性、哪些是冗余 - -| | | -|---|---| -| 状态 | **实施记录**(精简依据与进度) | -| 日期 | 2026-10-22 | -| 结论 | 冗余已清 ~14.5k 行;**剩余体量主要是特性面**,不是废弃物 | - ---- - -## 1. 当前账目 - -| 部分 | 行数 | 说明 | -|------|------|------| -| `src/` | **52,668** | 其中约 **5,200** 是内联测试(`#[cfg(test)]`) | -| `plugins/` + `crates/` | **14,700** | 5 个 ABI 插件(含共享 SDK)+ wasm crate | -| 合计 Rust | **67,368** | | - -最大的 10 个文件: - -| 行数 | 文件 | 性质 | -|------|------|------| -| 4,451 | `src/view/html.rs` | 3,861 行是 CSS/HTML 字符串(页面皮肤) | -| 2,691 | `src/parse/mod.rs` | 解析器主体 + 412 行内联测试 | -| 2,194 | `src/parse/expr.rs` | 表达式解析 + 465 行内联测试 | -| 2,063 | `src/host/foreign_doc.rs` | 外部语言内核(python/node 文档执行) | -| 1,648 | `src/host/dispatch.rs` | 202 个宿主函数的元数据表(已合一) | -| 1,968 | `src/host/foreign.rs` | 外部进程/会话管理 | -| 1,925 | `src/interp.rs` | 树遍历求值器 | -| 1,913 | `src/view/render.rs` | 渲染 | -| 1,309 | `src/formula/mod.rs` | `$$…$$` 公式求值 | -| 1,168 | `src/view/annot.rs` | 注解/映射 | - ---- - -## 2. 已清除的冗余(14.5k 行) - -| # | 项 | 行数 | 提交 | -|---|----|------|------| -| 1 | `plugins/web-rust-archive/`(31 文件,非 workspace 成员、默认不构建、被 Go `libweb` 取代) | **14,235** | `13012ca` | -| 2 | `as_text` × 18 份复制(两种措辞)→ 一个 `host::as_text` | ~100 | `8b0ea9e` | -| 3 | `catalog.rs` 的 4 个助手(与 `knowledge::util` 逐字相同) | ~70 | `8b0ea9e` | -| 4 | `view` 路由 34 臂 → 2 张表(`handle` / `handle_debug`) | 99 | `8b0ea9e` | -| 5 | 无调用点死代码 ×5(`parse_italic_assign` 等) | ~50 | `a14a6e2` | -| 6 | 转义重复:URL 编码器 2 份、`escape_js_string` 2 份(debug 副本漏 U+2028/2029) | ~40 | `9324032` | -| 7 | AST 遍历器 3 份 → `ast::walk_stmts` / `ast::stmt_line` | ~50 | `deac53d` | - -**顺带修出的真实缺陷**(不是行数问题,是正确性问题): - -| 缺陷 | 发现方式 | -|------|---------| -| `Access` 变体只有隐式判别值(重排即错位) | 新加的一致性测试 | -| HOST id 空间稀疏——不是 bug,但此前无测试守护 | 同上(测试先报"不连续",核实后改成"稀疏但可还原") | -| `escape_js_string` 的 debug 副本漏转义 U+2028/2029(JS 里是换行符) | 对比两份实现 | -| `view` 路由分布在两个 handler,只改一个会让 debug 路由全 405 | 改完实测 HTTP | - ---- - -## 3. 剩余体量为什么不是"冗余" - -逐项核过,剩下的都是**功能**,删掉就是砍特性: - -| 区域 | 行数 | 为什么保留 | -|------|------|-----------| -| `view/` 合计 | ~12,000 | live server + notebook UI:路由、渲染、注解、调试面板、执行报告;审计确认是 feature-gated 的一等 CLI 面 | -| `host/foreign*` | ~5,100 | 外部语言内核(python/node 持久会话、快照、中断);qdagent 的沙箱执行依赖 | -| `parse/` | ~4,900 | 词法/语法主体 + 内联测试 | -| `bytecode/` | 1,921 | 第二后端;72 处测试引用(含双后端一致性) | -| `knowledge/` | ~4,000 | catalog / EKC / 指纹;`marqdo catalog` 的输出有 golden 测试 | -| `formula/` | 1,741 | `$$…$$` 公式;与 `ast::Expr` 是**不同类型**的两套求值器(不可合并) | -| `host/dispatch.rs` | 2,052 | 202 个宿主函数的元数据 + 分派;`call_host` 是 202 个一行臂 | -| `view/html.rs` | 4,451 | 其中 3,861 是页面皮肤字符串 | - ---- - -## 4. 剩余可精简项(已定位,未做) - -| 项 | 结论 | -|----|------| -| ~~插件 ABI 前言共享 crate~~ | **已完成**:[change-plugin-sdk.md](change-plugin-sdk.md),净减 674 行,注册项 0 差异 | -| ~~HostFn 五表合一~~ | **已完成**:[change-hostfn-table.md](change-hostfn-table.md),−404 行,203 项逐字节一致 | -| `view/html.rs` 皮肤"重复声明基础 CSS" | **审计判断不成立**:实测基础样式 312 条规则、notebook 128 条,**选择器零重叠**,无重复可删 | -| `debug_page.rs` "复刻 shell" | **判断基本不成立**:只在 head/favicon 上有约 10 行相似;它没有 nav/topbar,是独立极简页 | -| 内联测试迁到 `tests/` | 不减总量,只让 `src` 变薄;不做 | - -**结论(修正后)**:可机械消除的重复**已经清完**。剩余体量全是特性实现, -要再压只能砍功能(例如 `view` 调试面板、`formula` 引擎),不是"找重复"。 - -**判断**:这些加起来约 1.3k 行(总量的 2%),收益边际递减;其中插件 SDK 最值得做(消除 5 份漂移), -其余属于"可以但不必"。 - ---- - -## 5. 与设计的关系 - -精简的目的不是数字好看,而是**不让冗余掩盖设计**: - -- 已消除的都是**重复实现**(同一逻辑多份 → 必然漂移) -- 保留的都是**单一实现的特性能耐** -- 每一条删改都跑全量测试:`605 → 609 passed / 0 failed`,编译零警告 - -如果后续还要压体量,正确的方向是**砍特性**(例如 `view` 的调试面板、`formula` 引擎), -而不是继续在特性内部找"重复"——那已经找完了。 diff --git a/doc/design/code-vs-comment.md b/doc/design/code-vs-comment.md deleted file mode 100755 index 523269d..0000000 --- a/doc/design/code-vs-comment.md +++ /dev/null @@ -1,41 +0,0 @@ -# 可执行面与叙述面 - -| | | -|---|---| -| 状态 | 与 mapping **v0.3** 对齐(现行运行时) | -| 日期 | 2026-09-14 | -| 取代 | 本文曾按 v0.2(`*语句*` / `**返回**`)叙述;旧对照见 [markdown-mapping.md](markdown-mapping.md) | -| 相关 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) §4 | - -「Markup」在此仓库 = Marqdo **把 Markdown 标记映射成语法** 的那一层,不是另一个语言。 - ---- - -## 三层 - -| 层 | 形态 | 角色 | -|----|------|------| -| **叙述面** | 普通段落 | 注释;行内 `` `名` `` 可声明/引用;装饰性 `**强调**` / `*斜体*` 不执行 | -| **Marqdo 可执行面** | 结构标记 + **`**代码**`** + **`*返回*`** | 本语言程序 | -| **外联面** | ` ```lang ` | 其它语言(FFI) | - -输出属于可执行面里的**函数调用**(`> print …` / `**print …**`),见 [keywords.md](keywords.md)。 - -### 成段注释 - -- 以**空行**划分段落。 -- 段首行:首字符非标记 → 注释段;段内续行一律叙述(即使以 `` ` `` / `-` 开头)。 -- 段内仍扫描行内可执行位:`` `名` ``、代码形 `**…**`、返回形 `*…*`。 -- 叙述段与独立结构行(`>` `#`)之间**建议空一行**,否则 `> print` 可能被吞进注释段。 - ---- - -## 语句 vs 返回 vs 输出 - -| 标记/形式 | 角色 | 是否架构级 | -|-----------|------|------------| -| `**…**` | 代码(赋值 / 调用 / 表达式语句) | 是 | -| `*…*` | 返回值(整行、`返回*n*`、或表达式形) | 是 | -| `****` / 整行 `**` / `*None*` | 空返回 + 结束函数体 | 是 | -| `> print …` | 打印副作用 | 否(内置函数) | -| 函数体 `---` / `***` | 叙述分隔(跳过,**不**结束函数体) | 否 | diff --git a/doc/design/collection-access-link.md b/doc/design/collection-access-link.md deleted file mode 100755 index 8d0494e..0000000 --- a/doc/design/collection-access-link.md +++ /dev/null @@ -1,64 +0,0 @@ -# 集合取元:GFM 链接形 - -| | | -|---|---| -| 状态 | **Active(运行时)** | -| 日期 | 2026-09-14 | -| 相关 | [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) | - ---- - -## 1. 决议 - -表达式取元的**主语法**为 Markdown 链接外形,与 foreach 同构: - -| 角色 | 写法 | -|------|------| -| **取元(表达式)** | `[键](集合)` | -| **遍历(语句)** | `- [项](集合)`(不变) | -| **脚注取元(过渡)** | `` 集合[^键] `` 仍解析,新代码勿写 | - -心智:**方括号 = 取出的名字,圆括号 = 从哪取。** - -```markdown -**价 = [拿铁](菜单)** -**价 = [`名`](菜单)** -**第一 = [1](篮子)** - -- [行](今日订单) - **名 = [品名](行)** -``` - -## 2. 细则 - -| 写法 | 语义 | -|------|------| -| `[拿铁](菜单)` | 静态键;`菜单` 为变量(粗体/斜体内) | -| `` [`名`](菜单) `` | 动态键(求值 `名` 再作键) | -| `[1](篮子)` | List **1-based** 下标(同脚注约定) | -| `[1]([苹果](货架))` | 嵌套链式 | - -与 `- [项](集合)` 消歧:仅 **表达式位置** 的 `[…](…)` 为取元;`-` 行头仍为 foreach。 - -## 3. 迁移 - -`` `菜单`[^拿铁] `` / `菜单[^拿铁]` → `[拿铁](菜单)`(**基与键左右对调**)。 - -| 区域 | 约定 | -|------|------| -| 新代码 / examples / public | **只用**链接形 | -| `tests/structure/footnote*` · `interp-footnote*` | 脚注兼容门禁(保留) | -| 其余 structure / ext / lib 金样 | 已迁链接形 | - -脚注路径保留至另行决定移除之日;Skill / 教程 / 新示例只用链接形。 - -## 4. 非目标 - -- 点号 map 访问、`在`、箭头取元、`(键)[集合]` -- 循环语法糖(`←` / `in` / 自然语言) - -## 5. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-14 | 初稿并落地主语法 | diff --git a/doc/design/core-surface.md b/doc/design/core-surface.md deleted file mode 100755 index c9718cd..0000000 --- a/doc/design/core-surface.md +++ /dev/null @@ -1,49 +0,0 @@ -# 核心表面清单(core-surface) - -| | | -|---|---| -| 状态 | **Accepted · 核心语法封闭集合(CI 守卫锁定)** | -| 日期 | 2026-09-22;2026-10-23 校正 v2.1 默认链接语义 | -| 守卫 | `tests/core_surface.rs` ⇄ `src/parse/mod.rs` `CORE_CONSTRUCTS`(改动任一侧不同步 → CI 红) | -| 相关 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)(语义宪法)· [layers.md](layers.md)(准入戒律)· [three-problems.md](../roadmap/three-problems.md) 问题一 · [three-problems-plan.md](../roadmap/three-problems-plan.md) T1.1/T1.3 | - -> **戒律总纲**:核心标记是**封闭集合**(约 19 个构造)。新增任何一行必须走 ADR(见 [layers.md](layers.md) 准入戒律)并回答「为什么现有标记不够」;生态需求的默认答案是**进 ext**。本表 id 列与守卫测试强一致:改表不同步 `CORE_CONSTRUCTS`(或反之)、样例文件缺失,一律 CI 红。 - -> **版本边界**:构造 ID 是历史守卫标识,不是固定不变的语义说明。`link-index` ID 暂保留以匹配注册表,但默认 `[]()` 已是描述包裹 payload;旧索引语义仅属于显式 Classic 兼容路径。未来步骤/知识投影见[文档原生指导](document-native-development-guide.md),不要把目标能力当作当前已实现。核心数量之外,还要审查上下文例外和作者负担。 - -## 1. 行构造 - -| id | 外形 | 语义 | 戒律 | 样例 | -|----|------|------|------|------| -| `narrative` | 无标记文字 | 叙述(不执行) | 段落内延续到空行;普通叙述不触发执行;未来知识引用投影也不改变此权限边界 | `tests/markup-v03/soft-emphasis.mq.md` | -| `blank` | 空行 | 段落边界 | 叙述分段的唯一手段;不得被赋予其它语义 | `tests/markup-v03/inc-prose.mq.md` | -| `heading-unit` | `#` / `##` | 对象 / 函数单元 | 标题即单元边界,按深度嵌套;正文禁止用 `##` 做版式(会变成函数) | `tests/markup-v03/decl-ident-only.mq.md` | -| `call-line` | `>` | 调用行 | 输出等副作用 = **普通函数**,不是架构标记 | `tests/markup-v03/dual-call.mq.md` | -| `branch-list` | 体内 `1.` 递增 | 分支 | 自 `1.` 起序号递增构成一个判断;重出 `1.` 开新判断;`N. *` = else;**不是所有有序列表都是 if** | `tests/markup-v03/greet-default.mq.md` | -| `loop-list` | `-` | 循环 | 条件形 `` - `条件` `` 或遍历形 `- [说明](遍历 集合 为 项)`;描述不是绑定变量名 | `tests/structure/loop.mq.md` | -| `param` | `` + `名` `` | 形参(兼容形) | 首选叙述 `` `名` `` 升参(宪法 §8);`+` 形仅兼容保留 | `tests/markup-v03/greet-default.mq.md` | -| `table` | GFM 表 | 集合 | 几何即类型([tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md));**绑定 = 数据,未绑定 = 文档表** | `tests/structure/collection.mq.md` | -| `fence` | ` ```lang ` | 外联 | 语言块原样外联,不进 Marqdo 语义 | `tests/lib/foreign-python.mq.md` | -| `hr` | 单行 `---` 或 `***` | 叙述分隔 | **不收束函数**(返回才收束) | `tests/markup-v03/module-hr.mq.md` | -| `writeback` | `` | 持久化输出 | 只读回放,不执行 | `tests/lib/writeback-get.mq.md` | - -## 2. 内联标记 - -| id | 外形 | 语义 | 戒律 | 样例 | -|----|------|------|------|------| -| `ident` | `` `名` `` | 声明 / 引用 | 首次未赋值 = 声明;叙述与程序共用同一视觉习惯 | `tests/markup-v03/decl-ident-only.mq.md` | -| `bold-code` | `**…**` | 代码(赋值 / 调用 / 表达式) | 粗体内代码判别序:赋值 → 调用 → 表达式;不取消调用行、返回等其它显式执行入口 | `tests/markup-v03/multi-bold.mq.md` | -| `italic-return` | `*…*` | 返回 | 改变控制流(**返回是架构**);返回即结束函数体 | `tests/markup-v03/inc-prose.mq.md` | -| `empty-return` | `*None*` / `****` | 空返回 | 返回 `None` 并结束函数体 | `tests/markup-v03/empty-return-none.mq.md` | -| `link-index` | `[描述](表达式)` | 描述包裹 payload(历史 ID) | 默认 Occlusion;取元可写 `[说明](access(集合, 键))`,不按描述取键;循环载荷见上 | `tests/occlusion/access-and-loop.mq.md` | -| `bracket-call` | `修饰… [函数] 实参…` | 方括号标记调用 | 前置修饰 → `名=True`;紧邻 `](` 的默认语义为 payload 遮蔽,不是旧索引 | `tests/structure/bracket-call.mq.md` | -| `footnote-index` | `集合[^键]` | 兼容取元 | 保留既有能力;新代码优先 `access(...)`,需要解释时包裹描述,不再推荐旧 `[键](集合)` | `tests/structure/footnote-index.mq.md` | -| `soft-emphasis` | `*仅*` / `**说明**` | 忽略 | 非代码形强调**不执行**——默认安全的关键消歧规则 | `tests/markup-v03/soft-emphasis.mq.md` | - -## 3. 词法大类(LineKind,`src/lex/mod.rs`) - -行级入口只有四个大类:`Blank` / `Comment`(叙述段落,含软强调与行内 `` `名` ``)/ `Writeback` / `Code`(`# * > + - | ~ $` 或数字开头)。本清单第 1 节的行构造是在 `Code`(及 `Comment`/`Writeback`)内部的**语义细分**;第 2 节内联标记由 `src/parse/prose.rs` 行内扫描产出。两层合起来 = 核心表面全集。 - -## 4. 范围外(进 Language 层,但不在本守卫) - -frontmatter / Artifact Metadata(元信息)、`import` 行(模块装载)、以及 Metadata 内的 **Binding Expression**(`${ns.name}`,见 [binding.md](binding.md) · [ADR 0006](../adr/0006-artifact-metadata-binding.md))属于 Language 层的其它语言面,随 [layers.md](layers.md) 准入流程登记,**暂不进本清单守卫**(不增 CORE_CONSTRUCTS 计数)。Phase 2 将已绑定 metadata **提升为入口普通变量**(仍非新标记)。如需一并守卫,走 ADR 扩表。 diff --git a/doc/design/dependencies.md b/doc/design/dependencies.md deleted file mode 100755 index 5330dc6..0000000 --- a/doc/design/dependencies.md +++ /dev/null @@ -1,178 +0,0 @@ -# Marqdo 实现依赖说明(Rust 参考解释器) - -| | | -|---|---| -| 状态 | 已定 | -| 日期 | 2026-08-04 | -| 相关 | [ADR 0001](../adr/0001-implementation-language.md) · [interpreter 路线图](../roadmap/interpreter.md) | - ---- - -## 1. 要不要 Flex / Bison? - -### 结论:**不需要。** 主因不是「用了 Rust」,而是 **Marqdo 的语法形态 + 解释器并不绑定生成器。** - -把两件事分开: - -| 问题 | 答案 | -|------|------| -| 因为 Rust 才不用 Flex/Bison? | **否。** Flex/Bison 生成的是 C(也可接 C++)。若实现改成 **C++**,**仍然不建议**用它们做 Marqdo 主前端。 | -| 因为是解释器才不用? | **部分相关,但不是全部。** 解释器**需要**词法/语法阶段,但**不规定**必须用 Flex/Bison;手写递归下降是主流。即便将来做「编译到字节码/原生」,Marqdo 也因 Markdown 外壳而不适合整语言 Bison 化。 | -| 真正主因 | **Markup-as-Syntax**:源是 GFM 文档结构(标题/列表/强调/表格/行分类),不是 Cminusf 那种纯字符流文法。 | - -| 工具 | 典型用途 | Marqdo 为何不用(与宿主语言无关) | -|------|----------|----------------------------------| -| **Flex** | 正则 → C 词法分析器 | 「词法」是 **行分类 + Markdown 标记**,不是经典 `id\|num\|op` 字符流 | -| **Bison** | Yacc 文法 → C LR 分析器 | 整体语法绑在 **GFM 块结构**上,硬写成单一 Bison 文法别扭且难与预览器对齐 | - -[USTC 编译课 Lab1](https://ustc-compiler-2025.github.io/homepage/) 用 Flex/Bison,是因为对象语言是 **C 式源码的编译器**;换 C++ 写那个编译器也合理。 -Marqdo 换 **Rust 或 C++** 都不改变「主前端不该是 Flex/Bison」这一判断。 - -**解释型语言同样需要词法与语法分析**,要的是阶段,不是这两个具体程序。 - ---- - -## 2. Marqdo 前端应怎样做(替代 Flex/Bison) - -拆成三层,比「一个大 lexer/parser」更贴合宪法: - -``` -.mq.md 文本 - │ - ├─① 行分类(自研) 无标记 → 注释;有标记 → 代码行 - ├─② GFM 块/行内(库) 标题、表、强调、列表结构 - ├─③ 行扫描补强(自研) 保留 '-' / '+';frontmatter `import file:file.mq.md` - └─④ Marqdo 语法(自研) 递归下降:Module/Fun/Stmt/Expr → AST - └─ 表达式子语言 可手写,或仅对 Expr 用 pest/nom -``` - -| 阶段 | 做法 | 对应编译学 | -|------|------|------------| -| ①③ | Rust 手写扫描 | 词法 / 扫描器 | -| ② | `pulldown-cmark` 或 `comrak` | 复用 GFM,避免自研表格/强调 | -| ④ | **手写递归下降**(推荐主路径) | 语法分析 | -| Expr(可选) | `pest`(PEG)或 `nom`(组合子) | 仅迷你表达式,不是整门语言 | - -**不推荐**整门语言上 LALRPOP / rusty_lr / Bison 等价物作为 v1 主前端:Markdown 外壳 + 行语义会让文法极度别扭。若将来有「纯文本 Marqdo 方言」,再另议生成器。 - ---- - -## 3. 详细依赖清单(Rust) - -### 3.1 工具链(开发机) - -| 依赖 | 用途 | 安装 | -|------|------|------| -| **Rust**(stable,建议 ≥ 1.75) | 编译实现 | [rustup](https://rustup.rs/):`rustup default stable` | -| **Cargo** | 包与构建 | 随 rustup | -| **rustfmt / clippy** | 格式与静态检查 | `rustup component add rustfmt clippy` | -| **Git** | 版本管理 | 已有 | - -**不要安装:** Flex、Bison、LLVM(v1 解释器不需要)。 -(日后若做原生后端再开 ADR;与当前解释器无关。) - -### 3.2 Cargo crate(建议写入根 `Cargo.toml` / workspace) - -#### 必选(Phase I 树遍历解释器) - -| Crate | 角色 | 说明 | -|-------|------|------| -| **pulldown-cmark** *或* **comrak** | GFM 事件/AST | 标题、列表、表格、emphasis/strong;Spike 已证明「库 + 行扫描」可行。二选一做 Spike 对比后钉死 | -| **thiserror** / **anyhow** | 错误类型 | 诊断与 CLI 报错 | -| **clap** | CLI | `marqdo run [path]` | -| **serde** + **serde_yaml** | 元信息 | 仅解析 frontmatter 中的 YAML **键值**;嵌套 `import:` 映射与其它 YAML 键一并解析 | -| **ureq** (=2.9.7) | HTTP(S) | `lib/net`;为 Cargo 1.81 另钉 `idna_adapter`/`zeroize`(见根 `Cargo.toml`) | -| **regex** (=1.13.1) | 正则 | Mid M1 `lib/re`;`default-features=false` + `std`/`unicode`;无回溯引用 | -| **sha2** (=0.10.9) / **sha1** (=0.10.6) / **md-5** (=0.10.6) / **hmac** (=0.12.1) | 摘要 | Mid M3 `lib/hash` | -| **getrandom** (=0.2.17) | OS 熵 | Mid M3 `lib/secrets` | - -#### 强烈建议 - -| Crate | 角色 | -|-------|------| -| **camino** 或标准 `PathBuf` | 路径 | -| **indexmap** | 保序 map(模块导出等) | - -#### 测试 - -| Crate | 角色 | -|-------|------| -| **rust 自带** `#[test]` | 单元测试 | -| **insta** 或手写金文件 | tests 期望 stdout 快照(可选) | -| **assert_cmd** / **predicates** | CLI 集成测试(可选) | - -#### Phase II(字节码 VM,后加) - -无强制新依赖;VM 以自研为主。可选: - -| Crate | 角色 | -|-------|------| -| **num_enum** 等 | opcode 枚举(可选) | - -#### 明确不引入(v1) - -| 东西 | 原因 | -|------|------| -| flex / bison / lemon | 见 §1 | -| lalrpop / rusty_lr 作**整语言**前端 | 与 MD 外壳冲突;递归下降更合适 | -| llvm-sys / inkwell | 非解释器 v1 | -| 完整 Python 运行时嵌入 | 参考实现已定为 Rust,避免双运行时 | - -### 3.3 表达式子语言(可选增强) - -若手写 Expr 递归下降过痛,**仅**对 `` `a` + 1 == `b` `` 这类表达式引入其一: - -| 选项 | 类型 | 何时用 | -|------|------|--------| -| **手写递归下降** | 无新依赖 | 默认;与全书一致、错误信息最好控 | -| **pest** | PEG 生成器 | 文法清晰、想要 `.pest` 文件时 | -| **nom** | 解析组合子 | 要零拷贝/细控时 | - -整文件 `.mq.md` **不要**整份丢给 pest/nom。 - ---- - -## 4. 仓库布局(与依赖对应) - -``` -Cargo.toml # workspace 或单包 -crates/marqdo/ # 或根包 marqdo - src/ - main.rs / lib.rs - lex/ # 行分类、Token(自研,无 flex) - parse/ # 递归下降(自研,无 bison) - ast/ - sema/ - interp/ # Phase I - bytecode/ # Phase II - runtime/ - tests/ # gold.rs + structure|keywords|errors -public/ # 用户可执行文档 -spike/ # Python 风险探测存档(可保留,非运行时依赖) -``` - -开发命令示例: - -```bash -cargo build -cargo test -cargo run -- run tests/structure/nested-call.mq.md -``` - ---- - -## 5. 与 Python Spike 的关系 - -| | Python `spike/` | Rust 参考实现 | -|--|-----------------|---------------| -| 角色 | 已验证 S1–S5 风险 | **正式**词法/语法/语义/解释器 | -| 是否运行时依赖 | 否 | 是 | -| 算法可迁移 | 行扫描、`split_front_matter`、导入正则 | 用 Rust 重写同算法 | - ---- - -## 6. 一句话对照 - -- **需要:** 词法(行分类+标记)、语法(递归下降→AST)、语义、解释器/日后 VM。 -- **不需要:** Flex、Bison、LLVM(v1)。 -- **外部库只需:** Rust 工具链 + GFM crate(pulldown-cmark/comrak)+ CLI/错误/测试若干;表达式可选 pest/nom。 diff --git a/doc/design/document-native-development-guide.md b/doc/design/document-native-development-guide.md deleted file mode 100755 index 06a037d..0000000 --- a/doc/design/document-native-development-guide.md +++ /dev/null @@ -1,284 +0,0 @@ -# Marqdo 文档原生开发指导:让知识的表达、执行与复用成为同一件事 - -| 项目 | 约定 | -|---|---| -| 状态 | 下一阶段开发指导与规划修订;不表示下述目标接口已经实现 | -| 日期 / 审阅基线 | 2026-10-23 / `main`,`7674ebb`;继承缺口审计的 `434be9f` 代码证据 | -| 原始意图 | [009](../next/009.md)、[附属设计](../next/Marqdo_Executable_Knowledge_Design.md)、[附属示例](../next/Marqdo_Executable_Knowledge_Example.md) | -| 配套实施文件 | [详细开发规范](../next/Marqdo_Executable_Knowledge_Development.md)、[缺口与交付路线](../roadmap/executable-knowledge-gaps-2026-10-23.md) | -| 本轮边界 | 校正开发方向、作者体验、AI 工作协议和验收;不新增语法,不宣称实现新能力 | - -## 1. 审阅结论与规范关系 - -Marqdo 的优势不在于给传统程序换一套 Markdown 符号,而在于:**读者解释知识、作者修改知识、程序执行知识、AI 查找并复用知识,能够指向同一份有结构的文档和其中的同一步。** 标题、叙述、表格、链接描述、输入输出、来源及执行行为不应分散在彼此手工同步的系统中。 - -现有规划没有放弃这一目标,但工程排序存在偏移:把身份、图、证据、锁、句柄、晋升全部铺完,再验证人和 AI 是否更容易使用。这样可能交付一个功能齐全的制品管理系统,却让文档作者承担另一套注册、声明、审核和配置工作。需要改变交付方法,不必推翻确定性编译、绑定和权限机制。 - -本指导规定**为何开发、作者维护什么、怎样证明值得开发**;详细规范规定语义模型与执行约束;路线图规定当前缺口、切片与完成证据。三者不是三套平行设计。遇到冲突,依次采用:`009` 的产品意图 → 本指导对作者负担、场景分级和交付次序的修订 → 详细规范的工程规则 → 附属概念示例。当前代码与测试证明“已实现什么”,不能把代码局限升级为永久语言禁令;原始讨论保留,不据其重新引入已被否决的方案。 - -### 1.1 方向修订清单 - -| 容易偏移的做法 | 修订后的要求 | 必须保留的技术约束 | -|---|---|---| -| 先做完整知识治理平台,再给作者使用 | 从一篇可读、可运行、可定位步骤的文档交付,逐层扩展 | 每个已支持路径都有准确的目标和效应边界 | -| 为进入知识库再写 YAML、注册表和索引 | 从源码推导;只有不能推导的领域事实才需作者补充 | 生成物有版本,可重建,可检查来源 | -| 所有逻辑先封装成可登记函数/类 | 一次性逻辑直接写;需要命名、解释或复用时逐步提取 | 作用域、形参、返回与副作用明确 | -| 所有调用先审核、锁定、签发远程凭据 | 本地探索、项目复用、严格业务、远程执行分级 | 精确目标、运行时权限不能被标签或模型绕过 | -| AI 只能搜文档、填工具参数 | AI 可以读步骤、组合、选择候选、局部修改、提取和验证 | 模型的选择必须转成显式目标,由编译器校验 | -| 为“独特”拒绝普通调用或新增更多标记 | 保留简单 payload;让 Markdown 结构提供程序之外的信息 | 无第二套表达式文法,无裸词隐式执行 | -| 核心构造数量不增长就是简单 | 同时检查上下文例外、记忆负担和诊断成本 | 新构造需 ADR;不靠把新规则藏进旧构造绕过审查 | - -### 1.2 四个不能互相替代的完成条件 - -1. **读得懂**:不打开生成图,也能从源文件看出目的、关键步骤、参数角色和限制。 -2. **执行同一件事**:标签表达意图,payload 决定计算;运行 trace 能回到源码步骤,不能执行另一个同名目标。 -3. **改得动**:人或 AI 能修改一个明确步骤,看到影响与验证结果,不必重写整份文档或同步多份签名。 -4. **复用得对**:找到已有能力后实际调用它;不满足条件时给出具体拒绝原因,而非用复制源码掩盖失败。 - -“更适合 AI”是待验证的产品假设,不是 Markdown 文件后缀自动赋予的性质。正确性和作者成本优先于 token 下降;错误复用更便宜不算优化。 - -## 2. 语法审查的保留、修正与暂缓 - -以下裁决针对审查结论的适用范围,不重写历史实验记录。旧文档中的原型、性能数值和当时的 `Value`/AST 限制,不能直接当作 v2.1 的规范或测试结果。 - -| 审查材料 | 保留的洞见 | 需要修正的外推 / 本轮处置 | -|---|---|---| -| [函数即命名](function-as-naming-philosophy.md) | 从正文计算出发,命名应降低理解和复用成本;避免无意义包装 | “具名给值缺失”是历史观察,当前有具名参数;替换模型是教学解释,不意味着禁止递归、前向引用或必须文本展开 | -| [方括号作为标签](bracket-as-label-evaluation.md) | 描述与 payload 共址;标签帮助解释、检索和拆步骤 | Classic 冲突是迁移历史,不据此恢复默认 `[键](集合)`;不强制每个常量或子表达式都有标签 | -| [圆括号与可读调用](paren-call-and-readable-invocation.md) | 调用标记应明确;保留 `f(args)` 的局部可读性 | 原型撤回不代表现有版本缺少该能力;Marqdo 的独特性不依赖消灭熟悉的表达式形式 | -| [从标记推导调用](call-syntax-from-marks.md) | 语义成分有明确标记;自然语言是连接与解释,不参与猜测调用 | 持久跨文档接口优先具名实参;短而稳定的位置参数仍合法。推断参数的声明次序变化属于接口变化,不承诺任意润色都无影响 | -| [环境参数](ambient-parameters-evaluation.md) | 参数来源应可见,避免调用者隐式环境影响复用 | 文档顶部已否决 L0 裸“执行”触发,正文旧建议不能重新生效;文件级常量也须有明确绑定与依赖,不变成动态作用域 | -| [函数作为值](functions-as-values-evaluation.md) | 区分名称数据、一等函数、有限查表;避免无需求增加核心复杂度 | “匿名函数必不能索引”“动态调用必然破坏契约”不是普遍定理。将来可研究稳定节点身份与运行时契约;本轮不引入闭包,也不永久禁止 | -| [函数作为表格](function-as-table-semantics.md) | 数据表几何有既定含义;契约表不可另造一份参数声明 | 不把表格全部变成函数,也不把“现有实现不支持”写成“表格不能计算”;有限决策表先评估库方案,只有明确角色和歧义测试后才讨论语言扩展 | -| [核心表面](core-surface.md)、[分层](layers.md) | 核心小、标记可解释、构造有测试与准入流程 | 清单中的旧取元/循环说明需随迁移更新;固定数量不等于低认知成本,守卫通过也不证明文档语义正确 | -| [链接设计](link-syntax.md)、[告警疲劳](warning-fatigue-control.md) | 单一 payload 文法;标签漂移可提示;默认安静、按需严格 | 标签不是纯粹可丢弃的注释,也不是事实证明;不做每次运行重复的批准仪式,不靠词汇相似度证明描述与代码一致 | - -### 2.1 继续冻结的语法边界 - -- 默认 `[]()` 是描述包裹 payload;旧取元只能在显式历史兼容路径下解释。现行取元用 `access(...)` 等已支持形式;循环使用明确遍历载荷。 -- `[]()` 不等于“仅函数调用”:计算、取元、调用、遍历、叙述引用都需要各自语义角色,不能只收集 call 边就宣称完成知识步骤。 -- 正文引用与可执行位置有不同调度权限。普通句子不因出现“执行”“发送”或工具名而运行;正文解析成引用也不自动求值。 -- 不把所有 `#` 解释成某种知识对象,或把继承悄悄变成实例关系。标题的既有语义必须兼容,IR 可区分 Type、Entity、Fact、Function。 -- 不给同一参数增加正文声明、签名表、工具 schema 三套作者真相。规范签名和工具 schema 是投影;契约表补充类型、约束和说明,不偷偷增加形参。 -- 可读源文件是硬要求;普通 Markdown 渲染器是否把含空格/嵌套表达式的链接渲染成可点击链接是另一件事。不能承诺全部标准渲染器理解执行语义。 - -### 2.2 哪些编辑不能当成“只是改文案” - -不含语义标记的普通叙述润色,应保持执行结果和实现摘要;标签改名应保留 payload 行为,但更新展示/检索内容。反引号声明、首次出现顺序、标题名称/层级、粗斜体、表格几何、契约、来源和适用范围的改变则可能影响程序或知识可信性。编辑器必须展示真实差异,不能统一标为 prose-only。 - -标签漂移诊断应说明“描述或实现可能需要复核”,不能自动替作者改写业务意图。自然语言一致性检查可作辅助建议,确定性检查仍需可定位的符号、类型、契约或测试证据。 - -## 3. 作者工作流:先写清楚,再获得复用能力 - -### 3.1 一次性计算不需要预先建知识模型 - -下面是当前默认语法的完整最小程序。无模式开关、无项目注册、无知识 ID、无锁文件。 - -```markdown -# main - -这是演示订单,单价与数量直接写在计算处。 - -**小计 = [两件商品的小计](2 * 30)** -> print text=`小计` -``` - -可读意图和精确计算共址。这个标签值得保留,因为它说明本次计算的业务角色;不要求把 `2`、`30`、乘法分别命名。 - -### 3.2 需要解释或复用时才提取命名能力 - -```markdown -## 商品小计 - -根据购买数量`数量`和商品单价`单价`计算小计。 - -*[按数量与单价计算](数量 * 单价)* - -# main - -计算同一笔演示订单。 - -**小计 = [两件商品的小计](商品小计(数量=2, 单价=30))** -> print text=`小计` -``` - -两个完整程序在本轮本地现有 `target/debug/marqdo` 上分别以 Tree 和 Bytecode 执行,均输出 `60`。这仅验证基础语法,不证明步骤身份、重构工具或 Agent 闭环已经实现;也不是全仓测试报告。可将各块保存为 `.mq.md` 后用 `marqdo run 文件 --backend tree` / `--backend bytecode` 复核。 - -**后续工具目标**:从选中表达式提取为标题单元,推导自由变量为参数、保持求值顺序与 effect 次数、生成具名调用,并给出可审阅补丁。反向内联也应保留契约和来源关联;无法证明安全的捕获变量、递归、控制流、动态目标或有副作用表达式,先拒绝自动变换并说明原因,不伪称等价。 - -### 3.3 跨文档复用与事实说明分别增长 - -当第二篇文档需要这段计算,才提取模块并显式 import;不要为十行单文件强制创建 `corpus/knowledge/apps` 目录树。项目索引按约定发现,明确边界或外部来源时再加入配置。 - -当“商品小计”依赖政策、时间、币种等条件,再就地补契约与来源。简单乘法不要求假造现实来源;“某商店当前折扣为九折”则不能仅凭函数返回 `0.9` 声称真实。 - -正文可以说明结果为何成立,目标是引用同一能力和同一次受控执行的结果,而非手抄另一份公式。正文引用 AST、结果投影和绑定身份尚需开发;完整业务链使用[目标示例](../next/Marqdo_Executable_Knowledge_Example.md)验收,不把它冒充当前全部可运行的教程。 - -### 3.4 维护时看到知识变化,而不只是文件变化 - -目标维护流程:修改上游规则 → 显示受影响的计算、正文陈述和消费者 → 执行相关测试 → 展示结果/证据/接口各自变化 → 按使用策略接受更新。普通显示文案变更不应触发全库业务审批;证据过期也不必使无关纯工具全部失效。 - -## 4. 人维护语义,编译器维护机械关联 - -| 信息 | 作者责任 | 编译器 / 工具责任 | -|---|---|---| -| 目的与步骤 | 有帮助的标题、叙述、标签;避免空泛重复 | 保留源位置和层级,生成步骤投影,不要求手工节点注册 | -| 输入输出 | 一份参数来源和必要契约;领域单位不能靠猜 | 推断规范签名、检查调用、生成 schema 和签名视图 | -| 目标与依赖 | 显式 import、可读名称、必要消歧 | 绑定唯一 SymbolId,生成依赖边与闭包;不要求手写 ID | -| 效应 | 扩展作者声明宿主能力;业务作者必要时收窄允许范围 | 汇总直接及传递效应;未知不得推断 pure;运行时执行能力上限 | -| 事实与来源 | 原始资料、范围、有效期、人工审阅等不可推导信息 | 关联来源、记录验证事件、传播失效;不将文件路径视为事实证明 | -| 身份与版本 | 有意移动/更名时确认必要迁移 | 区分身份与内容摘要;报告歧义,不靠猜测维持假稳定 | -| view / AI 索引 | 不维护第二份可执行描述 | 同一语义模型投影;显示生成代、验证政策和缺失字段 | - -生成信息不等于免费:首次编译、缓存修复、错误定位都要可理解。失败时应回到源文档中可修改的位置,而不是只报内部 Artifact 字段名。 - -稳定身份要诚实:同一次编译内引用和 trace 必须一致;普通文本编辑不应打乱无关节点;复制相似步骤、跨文件移动等无法唯一识别时,要求确认迁移或明确生成新身份。禁止用文本相似度悄悄继承已审核的知识身份。 - -## 5. AI 原生工作协议:读步骤、改步骤、验证步骤 - -本节是**待实现的协议约束**,不是新增 CLI 命令清单。优先扩展现有 MLSP、view、EKC 和 Agent 工作簿,不另造一套 Agent 框架或知识库。 - -### 5.1 发现后的最小上下文包 - -一次检索返回可展开的上下文卡,而非强制倾倒整个文件或只给函数 schema: - -1. 标题路径、任务相关叙述、标签和精确源码片段; -2. SymbolId/步骤节点、source span、源码摘要、生成代; -3. 输入角色、返回、单位、默认值和适用条件; -4. 直接依赖、效应、必要来源及分层验证状态; -5. 支持该能力的例子/测试,相关失败经验、禁用条件和替代能力; -6. 还缺哪些检查、能否在当前 policy 下运行、为何被拒绝。 - -来源不可用、字段未推导、上下文被截断都须显式标识。按预算可展开依赖,但不能悄悄省略改变适用性或权限的重要信息。原始资料及标签是内容,不是可以覆盖 Agent 策略的指令。 - -### 5.2 复用、适配、新建的分界 - -- **REUSE**:AI 可根据任务选候选,提交精确目标与输入;resolver 确认目标、契约、适用性、版本和 effect,执行既有制品。复用不靠“没有生成文件”推断,必须有实际调用 trace。 -- **ADAPT**:已有能力接近但不适用;说明差异,保留依赖/来源关联,在局部副本或补丁中改变必要部分,再验证。不为了通过测试改写原始来源或放宽全局策略。 -- **CREATE**:没有合适候选或明确需要新语义;记录检索范围和失败原因,在任务预算及写权限允许时新建。不能把检索服务故障当作“仓库没有能力”。 -- **ASK / STOP**:缺业务决策、权限或关键证据时报告具体缺口。编译器无法决定的真实意图不交给近似匹配默默补全。 - -AI 并非只能发现和解释。它可以提出精确目标、组合已有能力、改进表达、重构及补测试;不能以自然语言自报正确来替代执行验证,也不能把含糊名称传给后端任意选一个目标。 - -### 5.3 局部修改的事务边界 - -编辑请求至少携带目标文件/节点、期望源码摘要、补丁范围和预期行为变化。应用前检查摘要,源已变化则重新定位和审阅,不覆盖用户改动。应用后重新解析受影响文档,生成语义 diff:参数/返回、目标、effect、控制流、证据与依赖是否改变。 - -对“只改措辞”请求,检测到接口或实现改变时停止自动合并;对“改计算”请求,运行相关正负例并展示影响。原始文本、格式与未知 metadata 尽量保留,不通过整篇重生成来完成一行修改。禁止修改生成图伪装修复源码。 - -首个试点只支持可确定定位的纯计算步骤与普通函数,不等待通用 AST 编辑器、跨项目事务或完整知识治理。安全拒绝超范围输入也属于验收。 - -### 5.4 解释和负知识必须有落点 - -解释结果应关联到“哪一步、用了哪个目标、哪些输入、哪份来源、哪次验证”,区分已执行观察和模型推断。运行 trace 可以证明程序路径,不能证明任意自然语言论证正确。 - -失败经验需要保存适用范围、触发条件、关联能力、原因与失效时间/版本。例如“此折扣不适用于退款”应在查询定价能力时可见,而不是埋在另一份聊天记录里。先由普通文档与结构化关联承载,不先新增通用推理语言;过期负知识也要撤销,不能永久拦截修复后的能力。 - -## 6. 渐进严格:不把治理门槛塞进每一行正文 - -下面是目标政策分级,不是当前已有四种 CLI 模式。政策由项目/宿主配置和调用上下文选定,源文档保持同一种语法。 - -| 场景 | 必需条件 | 默认不要求 | -|---|---|---| -| 本地探索、单文件运行 | 明确语法与目标、已有运行时契约、宿主能力限制;如实显示未知状态 | lock、来源、ready 晋升、远程签名句柄 | -| 项目内自动复用 | 精确绑定、输入/适用性检查、效应许可、状态满足所选政策、执行 trace | 所有纯工具都有人审证据、每次独立确认 | -| 严格业务/可复现任务 | 相关依赖与证据锁定、必要验证新鲜度、受控环境和审计;明确不可重放部分 | 对无关文案变化重审整个项目 | -| 远程/多租户/不受信调用方 | 上述相关约束,加可信授权主体、范围、服务端能力上限、撤销/期限与防伪设计 | 把客户端提交的 `allow_effects` 当授权本身 | - -`ready` 是“对某项 policy 和输入/上下文已具备复用条件”,不是永久万能认证。未验证的本地草稿可以被检索、查看和按明确权限试跑;不能冒充满足严格政策的可复用事实。测试通过与事实证实分别报告。 - -正文 `check/view static` 不执行外部效应。用户主动打开的纯预览可复用项目或会话已有政策,不要求每个链接弹窗;effectful 运行始终受宿主能力和明确执行上下文控制。锁和摘要是完整性机制,不自动等于远程授权;可信本地引用无需先搭建凭据服务。 - -## 7. 交付切片:每片都有文档作者与 AI 能看见的结果 - -编号与[缺口路线图 §7](../roadmap/executable-knowledge-gaps-2026-10-23.md#7-依赖顺序与可合并切片)一致;G 编号沿用现状证据,M0–M6 保留为工程能力映射,不再被理解为必须全部串行完成的墙。 - -### S0 作者基线与最小语料 - -- 选定单文件计算、提取函数、两文档引用、表格取元/遍历、业务政策及拒绝复用六类任务;记录当前写法、输出、诊断和作者重复维护项。 -- 优先整理 `doc/README`、核心语法卡片、教程与运行示例的版本状态;不要先扩展通用库数量。 -- 为最小样例建立无网络门禁。100 单元及更大语料逐步增长,不阻塞首个可读文档切片。 -- 完成证据:别人按当前入口能写出正确默认语法;已实现与预期失败分开报告,不能把待实现测试跳过计为成功。 - -### S1 可读步骤与唯一目标 - -- 主要落点:`src/parse/`、`src/ast.rs`、`src/sema/`、`src/knowledge/compile.rs`、`src/view/`。 -- 在最小故事内联合完成 G01/G03:保留 label、payload、上下文和跨度;每类步骤有输入输出与依赖投影;旧 EKC 查询索引不再覆盖语义图。 -- 普通导航、正文引用、可执行表达式、循环分别处理,正文保持惰性。先确保支持范围内同一引用在源码、view、图中是同一个目标,再扩展覆盖范围。 -- 完成证据:作者能从渲染步骤返回对应源码;同名目标不误连;计算/取元/循环不是伪造的 call;重复构建可对照;未支持上下文明示。 - -### S2 确定执行与早期 AI 复用试点 - -- 主要落点:`src/sema/`、`src/interp.rs`、`src/bytecode/`、`src/mlsp.rs` 与现有 Agent 入口。 -- 完成静态普通函数、显式 import、关联函数的 BoundCall 主链;G02 与 G06 的效应安全下限不可延期。小范围可先用明确纯操作白名单,未知路径必须拒绝纯证明,而非猜 pure。 -- 实现最小上下文卡与本地绑定引用;以 stub/no-LLM 测试验证协议,然后用现有 Agent 跑相同故事。无需先完成远程鉴权平台或全面来源审核。 -- 完成证据:同一需求实际调用既有函数,不新增同义实现;两个后端 trace 对上图中目标;改目标、错误输入、未知效应、权限不足不能静默执行。 - -### S3 局部编辑、提取与库可读性 - -- 主要落点:MLSP 编辑/定位、相关 sema/检查入口、`lib/`、`ext/`、教程与测试。 -- 按 §5.3 实现受摘要保护的局部修改和语义 diff;实现受限纯表达式提取,或明确标为待实现,不用人工演示冒充工具能力。 -- 迁移标准库/扩展时删掉重复包装与噪音标签,保留有意义的业务步骤、契约和负例;中英镜像含义一致。兼容旧调用接口,不用增加旧语法解释救迁移遗漏。 -- 完成证据:同义润色不改执行;改反引号声明能检测签名变化;表达式提取前后结果/effect 次数一致;冲突补丁拒绝;CLI、库、扩展与 view 既有能力继续通过。 - -### S4 业务知识的来源与适用性 - -- 主要落点:契约、SourceRef/VerificationRecord、验证事件、Agent 候选解释;完成 G05 与 G07 的项目政策部分。 -- 选定书店案例的币种、数量边界、会员范围与政策有效期;给 schema、拒绝诊断及可运行负例,不泛化为全能业务规则语言。 -- 同步补齐传递效应与相关负知识;生成契约/状态展示,减少作者重复填写。 -- 完成证据:同一计算因输入或证据不同而正确通过/拒绝;来源过期不被 `tests=passed` 覆盖;普通纯工具无需虚构 SourceRef。 - -### S5 变化传播与严格复用 - -- 主要落点:`src/sema/lock.rs`、图/impact、产物提交与消费者;完成 G04/G08 和严格 handle 复核。 -- 区分身份/接口/实现/证据/闭包,给出可读升级 diff;整代快照保证消费者不会读取混代数据。并发读写一旦开放,该一致性就是前置条件,不能等到此片才承认风险。 -- 完成证据:修改依赖政策后,下游计算和正文解释进入影响集合;文案变化不误判实现变化;并发编辑或构建崩溃不导致错目标执行;锁不声称重放网络/随机/LLM。 - -### S6 生态验收与发布 - -- G10/G11 从 S0 起每片执行;S6 汇总兼容矩阵、真实工作流和打包后冒烟,不把测试留到最后。 -- G12 随实际规模需求推进;远程凭据/多租户是有条件的独立交付。它们不阻塞受信本地试点,也不得被本地通过的测试覆盖为“已安全支持”。 -- 完成证据:当前默认语法的 lib/ext/CLI/MLSP/view/WASM 等受影响消费者有明确结果;目标示例中的已发布子集实际可运行,未发布部分保留状态;发布声明与证据一一对应。 - -## 8. 验证 Marqdo 优势,而不只验证组件存在 - -### 8.1 必须收集的产品指标 - -| 维度 | 记录方法 | 失败信号 | -|---|---|---| -| 作者负担 | 完成同一任务所需手写声明、重复字段、配置、跳转和确认次数 | 简单本地算式也必须填写制品清单 | -| 阅读与定位 | 给定问题,定位正确步骤/限制的准确率、耗时与上下文量 | 只看 label 会误导,必须打开生成 JSON 才理解源文档 | -| 可修改性 | 修改范围、无关 diff、语义变化检测率、冲突覆盖数 | 为改一步而重生成全文件;措辞调整偷偷改变接口 | -| 复用质量 | 已有能力发现率、实际调用率、重复实现率、误用率 | 检索命中却重新写代码;正确拒绝算成任务失败而被优化掉 | -| 知识可追溯性 | 结果关联目标、步骤、输入、来源和验证的覆盖率 | `tested` 被当作事实正确;解释引用未执行的步骤 | -| 总成本 | 正确完成任务的 token、工具调用、轮次、总耗时及编译成本 | 只报模型 tokens,隐藏额外注册/审核/修复成本 | - -### 8.2 对照实验与门槛 - -1. 固定任务、可访问能力、输入数据、模型版本、工具能力、预算与超时;比较普通 Markdown+代码/RAG、当前 EKC 和新方案。不能给新方案更多现成实现再声称语法更优。 -2. 任务包括成功复用、同名冲突、近似但不适用、未知 effect、过期来源、正文不执行、局部修改及库升级。加入自然语言诱导绕过 policy 的负例。 -3. 先测确定性协议,再测多次 AI 运行,保留种子(支持时)、原始 trace、版本、失败样本与分布;小样本不夸大收益。 -4. 正确目标、无越权和正文无外部 effect 是硬门槛。原有兼容测试不得降低;效率阈值先测基线再登记,不捏造提升百分比。 -5. 若作者负担增加或误用率上升,回到交互/语义设计分析原因,不能只用“更多治理更安全”或“模型更便宜”解释过去。 - -### 8.3 发布声明分层 - -- “支持新语法”需语法、迁移、双后端与库兼容证据,不意味着完整知识复用已经交付。 -- “本地确定性知识复用”需 S1/S2 支持范围内的端到端与拒绝用例;范围外路径显式不支持,不能回落为模糊执行。 -- “严格业务知识复用”还需相关 S4/S5 来源、适用性、失效、锁和一致性证据。 -- “安全远程知识执行”需额外的授权、能力上限、凭据/撤销及隔离测试;本地 JSON handle 不等于远程安全。 - -## 9. 每个开发变更必须回答的问题 - -提交设计或实现时给出一份短而具体的审阅记录: - -- 用户要读/写/改/复用的知识是什么?附源文档前后对照,不只给内部结构图。 -- 利用了哪种文档原生信息?若只增加通用框架能力,与主线的必要关系是什么? -- 新增了哪些作者必须手工维护的信息?为什么不能从现有语义推导? -- 是否改变标记、作用域、求值顺序、形参顺序、表格几何或正文安全?分别有哪些测试? -- 人、CLI、view、图和 Agent 是否看到同一目标与状态?失败能否回到源码修复? -- AI 的正确复用/局部编辑如何证明?哪些部分仍需模型判断,哪些由编译器决定? -- 标准库和扩展是否先迁移?是否保住既有公开接口、输出与 effect? -- 这是已实现、受限试点还是设计目标?文档和发布声明是否一致? - -**准入原则**:内部可以使用成熟编译器、数据库和协议技术;外部必须减少知识在“说明、程序、索引、工具描述”之间的重复翻译。独特性由这条链的实际收益体现,不由新符号数量或与其他语言不同的程度体现。 diff --git a/doc/design/engineering-knowledge.md b/doc/design/engineering-knowledge.md deleted file mode 100755 index 3cf8495..0000000 --- a/doc/design/engineering-knowledge.md +++ /dev/null @@ -1,100 +0,0 @@ -# Engineering Knowledge Compiler(EKC) - -| | | -|---|---| -| 状态 | **Accepted(v1 已落地)** | -| 日期 | 2026-09-28 | -| 提案 | [next/008.md](../next/008.md) | -| 相关 | [okf.md](okf.md) · [catalog-cli.md](catalog-cli.md) · [ext-agent.md](ext-agent.md) | - -## 1. 定位 - -Marqdo 把仓库投影为 **可查询、可验证、可复用** 的工程知识系统。Source of Truth 仍是 `*.mq.md`;`.marqdo/**` 是 GENERATED 投影。 - -```text -.mq.md ──► EKC ──► Executable + Catalog L0–L4 + Graph + Context Pack - │ - ▼ - Agent preflight (REUSE → ADAPT → CREATE) -``` - -**Engineering First Information (EFI)**:生成代码前先获得已有能力、约束、决策、失败经验与推荐复用。 - -## 2. 五层 Catalog - -| 层 | 内容 | 落盘 | -|----|------|------| -| L0 Repository | 语言/规模 | `.marqdo/catalog/repository.mq.md` | -| L1 Module | imports/exports/responsibility | `.marqdo/catalog/modules/` | -| L2 Symbol | signature/calls/fingerprint | `.marqdo/catalog/symbols/` | -| L3 Capability | 工程能做什么 | `.marqdo/catalog/capabilities/` | -| L4 Knowledge | Decision/Constraint/Failure/… | `.marqdo/knowledge/{decisions,constraints,…}/` | - -既有 `marqdo catalog` 根级 `catalog.yaml` / `index.md` / `modules/` / `concepts/` **保留**;`catalog` 成功后默认再跑 EKC(`--no-knowledge` 可关)。 - -## 3. 知识类型(OKF `type`) - -| type | 含义 | -|------|------| -| `Capability` / `Function` | 能力与符号投影 | -| `Decision` | 为什么这样做 | -| `Constraint` | 必须/禁止 | -| `Failure` / `AntiPattern` | 负面知识 | -| `Pattern` / `Migration` / `Fact` | 模式、迁移、事实 | -| `Marqdo Context Pack` | Agent 上下文制品 | -| `Marqdo Policy` | 复用决议编译结果 | -| `Marqdo Engineering Knowledge` | 总览 / `engineering.yaml` | - -未知 type 优雅降级(可读,不专属逻辑)。 - -## 4. 图边 - -`implements` · `uses` · `depends_on` · `tested_by` · `documented_by` · `constrained_by` · `decided_by` · `supersedes` · `conflicts_with` · `deprecated_by` · `derived_from` · `failed_by` · `related_to` - -落盘(G01 分离后): -- **权威语义图**:`.marqdo/graph/edges.json` · `nodes.json`(`SemanticProject`,含 `authority` 字段)· `steps.json` -- **EKC 检索投影**(非执行依据):`.marqdo/ekc/graph/graph.json` · `edges.json` · `index.json` · **`ir.json`**(完整 IR 快照,供查询热路径) - -## 5. CLI - -```bash -marqdo knowledge [PATH] -o .marqdo # compile(默认;写投影 + ir.json) -marqdo knowledge preflight "task" # 暖机读 ir.json;缺图才 compile -marqdo knowledge preflight "task" --refresh # 强制全量重编译后再预检 -marqdo knowledge record REUSE -marqdo knowledge learn --task ... --failure ... -marqdo find "authentication" # 同上:缺图才 compile;--refresh 强制 -marqdo reuse "implement oauth login" -marqdo impact path/to/file.mq.md -marqdo conflicts | stale | duplicate [--fail] | verify -``` - -统一 `--json`。查询类命令(`preflight` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify`)默认 **读已编译投影**;CI 或源变更后应先 `marqdo knowledge` 或加 `--refresh`。`duplicate` 默认阈值 `0.75`;`--fail` 作 CI Gate。 - -## 6. Reuse 协议 - -三态:**REUSE → ADAPT → CREATE**(硬顺序)。Reuse budget:`min_candidates` / `allow_create_after`。仅 `create_allowed: true` 时允许盲生成。 - -## 7. Context Pack - -`.marqdo/agent/contexts/task-.mq.md`:Task / Existing Capabilities / APIs / Constraints / Decisions / Failures / Recommended / Forbidden。 - -## 8. Agent - -- Plugin:`agent_eng_preflight` / `agent_eng_reuse` / `agent_eng_record` -- Facade:`agent.preflight` · `agent.eng_reuse` · `agent.eng_record` -- `agent.plan … eng_preflight=True` 在 agent-kb 之前跑 EFI;缺知识图时 `missing_knowledge` 放行(兼容纯 agent-kb 测试) - -## 9. 指标 - -`.marqdo/agent/episodes/reuse_metrics.json`:`reuse_ratio` / `adapt_ratio` / `novel_ratio` / `duplication_rate`。 - -## 10. 原则(五条) - -1. Discover before Create -2. Reuse before Adapt -3. Adapt before Duplicate -4. Verify before Promote -5. Code changes update knowledge - -**不做**:以向量库为知识模型;embedding 仅可选检索实现,默认关闭。Hybrid = lexical + symbol + capability + graph。 diff --git a/doc/design/examples-and-tests.md b/doc/design/examples-and-tests.md deleted file mode 100755 index 767fc1d..0000000 --- a/doc/design/examples-and-tests.md +++ /dev/null @@ -1,67 +0,0 @@ -# 示例与测试布局 - -| | | -|---|---| -| 状态 | 已定 | -| 日期 | 2026-08-07 | -| 原则 | **夹具即金样例**:`tests/{structure,keywords,errors}/**/*.mq.md` 由 `cargo test` / CI 跑通;`marqdo view tests` 也可浏览 | - ---- - -## 1. 目录 - -只保留 **`tests/`**,用子目录区分类别(不再另设 `examples/`): - -``` -tests/ - README.md - gold.rs # 集成测试入口 - structure/ # 代码基础结构(Markup 架构 · v0.2) - … - keywords/ # 关键字与内置名 - … - markup-v03/ # Markup 映射 v0.3 草案金样例(实现前 ignore) - README.md - inc-prose.mq.md - … - ext/ - … - errors/ # 期望失败(诊断文案稳定后再加金样例) - … -``` - -面向访客的可执行介绍在 [`public/`](../../public/)(无 `errors/`),见 [user-site.md](user-site.md)。 -开发设计文稿在 [`doc/`](../)(单数)。 - ---- - -## 2. 分类职责 - -| 类别 | 测什么 | 不测什么 | -|------|--------|----------| -| **structure** | `#`/`##`、形参 `+`、`1.` 分支、`-` 循环、表、导入、点号路径 / `use`、位置/具名实参 | 关键字边角 | -| **keywords** | `True`/`False`/`None`、`and`/`or`/`not`、`print`/`input` 约定 | 复杂控制流(可极简) | -| **markup-v03** | v0.3:叙述声明、粗体代码、斜体返回、升参、空返回、双调用面(见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)) | 在 `--markup v0.3` 落地前 `#[ignore]` | -| **errors** | 未定义名、实参错误、语法错误的诊断 | 成功路径 | - -未单独建夹、但应覆盖的其它测试(`src/**` 单测或日后 `tests/runtime/`): - -- **流水线调试**:`--dump-lines` / `--dump-ast` / `--trace-eval` -- **CLI**:默认 `index.mq.md`、退出码 -- **view**:目录扫描、单文件页、执行区(见 [view.md](view.md)) -- **模块图**:循环导入拒绝;`errors/ns-instance-method`(实例方法路径) -- **ext live**:`ext/agent-run-live`(需 `.env` + `libagent`) - ---- - -## 3. 金样例约定 - -每个可执行 `.mq.md` 在 `tests/gold.rs` 登记期望 stdout。 -`errors/` 内文件登记期望 stderr 子串与非零退出码。 - ---- - -## 4. 与 `view` / `public` 的关系 - -- `marqdo view tests`:开发者浏览金样例(含 errors)。 -- `marqdo view public`:用户文档站源;**不要**把 `tests/errors` 编进 `public/`。 diff --git a/doc/design/executable-knowledge-system.md b/doc/design/executable-knowledge-system.md deleted file mode 100755 index 6f4aad2..0000000 --- a/doc/design/executable-knowledge-system.md +++ /dev/null @@ -1,206 +0,0 @@ -# 可执行知识系统:`[]()` 的统一语法与跨文件闭环 - -| | | -|---|---| -| 状态 | **Design Draft · v2.1 语义重构** | -| 核心判断 | `[]()` 不是“普通代码”与“知识链接”的分界;每一个 `[]()` 同时是代码、文档和知识图节点。 | -| 关联 | [link-syntax.md](link-syntax.md) · [knowledge-layers.md](knowledge-layers.md) · [module-namespace.md](module-namespace.md) · [engineering-knowledge.md](engineering-knowledge.md) | -| 示例 | [examples/executable-knowledge/](../../examples/executable-knowledge/) | - ---- - -## 0. 一句话 - -> **`[名称](载荷)` 是一个命名的可执行知识步骤:`()` 做原有的任何事,`[]` 说明这一步对人意味着什么;编译器把它们一起编入知识图。** - -它不增加、替代或限制 payload 语法。字典取元、表操作、算术、函数调用、嵌套调用、遍历/循环、 -甚至受控副作用,都保留原有解释器语义。差别只在于:原来不可见的一步现在获得一个稳定的人话名字、 -源位置、输入/输出、依赖和影响范围。 - -```text -代码投影: eval([名称](载荷)) = eval(载荷) -文档投影: 读者看到 名称,必要时展开载荷、输入与输出 -知识投影: 编译器生成 KnowledgeStep(名称, 载荷, 依赖, 类型, 效果, 来源位置) -``` - -这三种投影缺一不可。只保留前两者是“带标签的代码”;只保留后两者会牺牲可运行性; -三者同源,才是代码即文档、文档即知识、知识即可执行。 - ---- - -## 1. 统一节点:`Named` - -`[]()` 的正确抽象不是“链接调用”,而是泛型 AST 装饰器: - -```text -Named { label, inner: T, span } -``` - -`T` 是它出现位置原有的语法节点,绝不另造“知识表达式” parser: - -| 既有位置 | `T` | 示例 | 知识角色 | -|---|---|---|---| -| 表达式 | `Expr` | `[收件人](at(订单, "收件人"))` | 观测/取值 | -| 表达式 | `Expr` | `[含税价](金额 * (1 + 税率))` | 推导 | -| 表达式 | `Expr` | `[适用税率](税率.查询(地区, 品类))` | 复用/查询 | -| 遍历位置 | `LoopSpec` | `[逐个订单行](遍历 订单.行 为 行)` | 过程/展开 | -| 正文位置 | `InlinePayload` | `订单总额为[含税总价](定价.总额(订单))。` | 叙述中的可执行槽 | -| URL/路径 | `NavigationLink` | `[税率原文](corpus/tax.md)` | 导航/证据定位 | - -运行时只执行 `inner`;`label` 不进符号表、不改变作用域、不重复计算。与此同时, -parse/check/catalog 保留整个 `Named`。所以循环不会被误判成“返回一个事实”,取元也不会 -被迫拥有来源表;但两者都能在图中被看见、被搜索、被影响分析。 - -### 1.1 每个节点都有角色,而不是两套语法 - -角色由既有 AST、类型、效果和依赖推导,必要时由所在 `#`/`##` 的契约约束: - -| role | 如何识别 | `check` 应问什么 | -|---|---|---| -| `observe` | 取元、读取字段、读取表/文档 | 读什么、类型是什么、是否可用 | -| `derive` | 纯计算、聚合、映射 | 输入、输出、公式/依赖是否完整 | -| `reuse` | 调用已解析的 `##` / 模块能力 | 调用到哪个稳定符号、参数/返回是否匹配 | -| `iterate` | 已有遍历/循环载荷 | 遍历什么、绑定什么、循环体依赖什么 | -| `act` | 写入、请求、打印等副作用 | 权限、幂等性、影响目标 | -| `narrate` | 正文中的命名载荷 | 它在句中替代什么值、依赖是否可解析 | - -一个节点可以有多个 role,例如 `[同步并记录](写入(...) + 记录(...))` 是 `act`,也依赖 -若干 `observe`/`reuse` 节点。角色是编译结果,不是作者需要记忆的关键字。 - ---- - -## 2. 知识层不是目录隔离,而是同一图的不同投影 - -“几层知识”不应把语法和项目切断。它们是同一个 `Named` 图中不同职责的节点; -同一份 `.mq.md` 可以同时有多层节点。 - -| 投影层 | 在统一图中的节点 | 由什么语法产生 | 它回答的问题 | -|---|---|---|---| -| **E 证据** | 原文、数据、文件/表读取节点 | Markdown 链接、`at(...)`、读取调用 | 事实从哪里来? | -| **C 概念** | 类型、字段、术语、约束 | `#`、字段/契约表 | 这些值是什么意思、能否组合? | -| **K 原子知识** | 命名个体、事实、规则 | `# 个体`、`##`、`Named` | 哪个可调用单元给出什么知识? | -| **D 推导知识** | 聚合、计算、决策、工作流步骤 | 任意 `Named` / `Named` | 如何从已有知识得到新结论/行动? | -| **N 叙述知识** | 段落与正文调用槽 | 正文 `Named` | 如何把结论说给人或 agent? | - -同一条边可以跨层:`[出生年份](at(人物表, "出生年份"))` 同时是 E 的观测、K 的事实值和 -可被 N 层引用的节点。`[逐个订单行](遍历...)` 是 D 的过程知识,也为其内部每个推导提供上下文。 -这正是通用语法本身兼容知识体系的含义。 - -### 2.1 `#` / `##` 的位置 - -- `#` 给一组知识步骤提供可读命名空间、类型/个体语义和文档边界; -- `##` 给可复用步骤提供稳定的公开入口、参数与返回契约; -- `[]()` 给入口内部的**每一小步**命名,并将它们暴露给文档、图和工具; -- `> 类型` 仍只构造运行时实例;知识个体不等于运行时 map。 - -因此 `## 含税总额` 不是黑盒函数:其函数体中的 `[订单行](...)`、`[逐行计税](遍历...)`、 -`[汇总](sum(...))` 都是可检索、可解释、可追踪的知识步骤。函数是知识单元的边界, -`[]()` 是知识单元的内部结构。 - ---- - -## 3. 大项目的寻址:可读短名与稳定身份同时成立 - -全局只靠 `# 李白` 寻址在大项目中不可行:同名、重命名和加载顺序都会让图不稳定。 -但这不意味着作者要失去 `李白.出生年份` 的自然语言体验。 - -1. 文件的既有 frontmatter `id` 是稳定身份; -2. 现有 `import bind:target` 是代码中的规范加载/寻址; -3. `#` / `##` 是人可读的路径段; -4. 正文短地址由 catalog 发现,解析成功后写入 LinkInfo/lock 的稳定 `symbol_id`;歧义必须报错。 - -```markdown ---- -id: knowledge.people.li-bai -import: - li_bai: knowledge/people/li-bai.mq.md ---- - -# 回答 - -**year = [李白的出生年份](li_bai.李白.出生年份)** -李白出生于[公元 701 年](李白.出生年份)。 -``` - -第一处是可运行代码,使用显式 import;第二处是正文的发现地址。它们编译后都指向 -`knowledge.people.li-bai::李白.出生年份`。短地址从来不是“按项目扫描第一个名字”, -而是可读的查询,必须由 lock 固化。 - ---- - -## 4. 每个 `[]()` 产生统一的知识记录 - -不要把 LinkInfo 固定成单一的 `target`。任意载荷都可能含有多个读、写、调用和循环依赖: - -```json -{ - "label": "逐个订单行", - "payload_kind": "loop", - "roles": ["iterate"], - "source": {"file": "capabilities/order-pricing.mq.md", "line": 22}, - "inputs": ["订单.行"], - "outputs": ["行"], - "dependencies": [ - {"kind": "local_value", "path": "订单.行"}, - {"kind": "symbol", "id": "capability.order-pricing::订单定价.含税价"} - ], - "effect": "pure", - "fingerprint": "sha256:…" -} -``` - -此记录就是统一知识图节点: - -- 本地取元有输入/类型边; -- 纯计算有输入/输出/公式边; -- 循环有集合、变量绑定和循环体边; -- 调用有 `calls`/`uses` 边; -- 有来源的事实再增加 `derived_from` 边; -- 正文节点有 `narrates` 边,连接它所在句子和计算结果; -- 副作用节点有权限/影响目标边,不能被 `view` 或 `verify` 静默执行。 - -来源不是每个节点的前提,而是图中的一种边。没有来源的字典取元仍是知识步骤; -若它最终支撑对外事实,沿依赖链应能找到来源,否则在“发布/验证事实”时才报证据不足。 - ---- - -## 5. 闭环:写、跑、看、查、变 - -```text -作者写 Named - │ - ├─ run:擦除 label,按原语义执行 - ├─ view:显示 label,可展开值、输入、步骤和来源 - └─ check:解析所有依赖,编译统一知识图 - │ - catalog / lock / context pack - │ -来源、规则、代码任一变化 ── impact / verify ──> 所有受影响 Named 与叙述句子 - │ - 作者或 agent 修复后重新 check/verify -``` - -### 5.1 命令边界 - -| 操作 | 做什么 | 不做什么 | -|---|---|---| -| `run` | 执行代码位置的原 payload | 不因为正文出现 `[]()` 而执行副作用 | -| `check` | 建图、解析类型/符号/依赖、检查 label 漂移 | 不求值、不伪造运行结果 | -| `view` | 呈现命名步骤及可选值/来源 | 静态模式不执行;live 模式遵守 effect 权限 | -| `verify` | 在沙箱中重算 pure 节点、核对来源/指纹 | 不执行 `act` 节点 | -| `impact` | 从变更节点反查依赖、函数、文档 span | 不按文本猜测关系 | - -这样,任意通用代码一开始就属于知识图;只有在执行/验证权限上分级,而不是在语法上被分裂。 - ---- - -## 6. 实施顺序 - -1. 在表达式、遍历和正文三处统一保留 `Named`;payload 复用各自现有 parser。 -2. 为任意 `Named` 提取 `inputs`、`outputs`、`dependencies`、`effect`、`roles`;从单 target 演进为依赖集合。 -3. 让 `#`/`##` 契约为内部步骤提供类型/公开边界;让 frontmatter `id` + import 提供跨文件稳定解析。 -4. 把现有 EKC 图扩展为步骤图:`observes`、`derives`、`iterates`、`calls`、`acts`、`narrates`、`derived_from`。 -5. 接入 `check`、`view`、`verify`、`impact` 与 lock;让一次变更能回到具体的 `[]()` 和具体句子。 - -验收不是“能把一个类函数链接出来”,而是:**改一处表字段、来源、规则或函数,系统能列出受影响的 -取元、循环、推导、调用和正文;其中每一步既可展开为代码,也可读成文档。** diff --git a/doc/design/ext-abi.md b/doc/design/ext-abi.md deleted file mode 100755 index ab8c0b5..0000000 --- a/doc/design/ext-abi.md +++ /dev/null @@ -1,106 +0,0 @@ -# Native plugin ABI (v2) - -| | | -|---|---| -| Status | Accepted | -| Date | 2026-08-07 | -| Header | [`include/marqdo_abi.h`](../../include/marqdo_abi.h) | -| Related | [ext-agent.md](ext-agent.md) · [stdlib-modules.md](stdlib-modules.md) | - -## Goals - -- Optional **native** extensions as shared libraries (`.dll` / `.so` / `.dylib`). -- **Not** linked into the `marqdo` binary; load at runtime. -- Stable **C** ABI only (no cross-compiler Rust ABI for plugins). -- Official / local paths only — **no** third-party package registry. -- **v2**: allowlisted `host_query` so plugins can read entry source / call site / skill without baking agent logic into the core. - -## Contract - -`MARQDO_ABI_VERSION = 2` (host accepts plugins with version `1..=2`). - -Every plugin exports: - -| Symbol | Role | -|--------|------| -| `marqdo_plugin_abi_version` | `1` or `2` | -| `marqdo_plugin_init` | Register functions via `MarqdoHostApi` | -| `marqdo_plugin_shutdown` | Teardown | - -Host provides `register_fn`, `alloc`, `free`, and (v2) `host_query`. - -### Wire format - -Arguments and results are **UTF-8 JSON**: - -- Args: JSON object keyed by parameter names (from `params` CSV at registration). -- Result: any JSON value mappable to Marqdo `Value` (same rules as `lib/json`). - -Plugin fn returns `0` + `*out_json` on success; non-zero + optional `*err_msg` on failure. Host frees both strings with the host `free`. - -### `host_query` allowlist (v2) - -| name | Result JSON | Notes | -|------|-------------|--------| -| `module_source` | string | Entry `.mq.md` text | -| `call_site` | `{path,function,line}` | Active call site | -| `marqdo_skill` | string | Skill pack text | -| `cwd` | string | Host `cwd` (entry file directory) for path resolution | -| `record_plot` | `{ok:true}` | Args `{svg}` + optional `path`; push SVG into host plots (view embed / CLI auto-write), same channel as math plots | - -Unknown names fail. Queries are only valid during a plugin function call (host sets thread-local context). - -## Marqdo surface (`lib/plugin` / `lib/插件`) - -| English | Chinese | Host | -|---------|---------|------| -| `## load` (`path`) | `## 加载` (`路径`) | `host_plugin_load` | -| `## unload` | `## 卸载` | `host_plugin_unload` | -| `## list` | `## 列出` | `host_plugin_list` | -| `## native_path` (`name`) | `## 原生路径` (`名`) | `host_ext_native_path` | - -```markdown ---- -import: - plugin: lib/plugin.mq.md ---- - -# main - -> load path=demo.dll - -*`sum` = > demo_add a=1 b=2 * -> print text=`sum` -``` - -After `load`, registered names are callable like other functions (plugin registry lookup after fixed host fns, before user `#`/`##` defs). - -**Path sandbox:** `path` resolves under the program’s cwd / `fs_root` (same as `lib/fs`). Absolute paths outside the root are rejected unless trusted (`MARQDO_EXT` / `MARQDO_AGENT_PLUGIN` / built `libagent.*`). Prefer `native_path name=agent` for the official agent plugin. - -## Demo / agent - -```bash -cargo build -p marqdo_plugin_demo -cargo build -p marqdo_plugin_agent -``` - -- Demo (ABI v1): `demo_add`, `demo_echo` — [`tests/lib/plugin-demo.mq.md`](../../tests/lib/plugin-demo.mq.md). -- Agent (ABI v2): … **OKF agent-kb** … -- Web (ABI v2): HTTP listen + SQLite/Postgres + page render (`web_listen`, `web_render`, `web_db_*`, …) — [`plugins/web`](../../plugins/web)(**Go 全量重写**,见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md) · [ADR 0004](../adr/0004-web-plugin-go.md));作者面 [`ext/web/web.mq.md`](../../ext/web/web.mq.md)。Lookup: `plugin.native_path name=web` / `MARQDO_WEB_PLUGIN` / `marqdo ext add web`. - -## Layering - -| Layer | May call `host_*` | -|-------|-------------------| -| `lib/*` | Yes (only L1 wrappers of generic L0.5) | -| `ext/*` | **No** — compose `lib/*` or ABI plugin names via `lib/plugin` | -| Application `.mq.md` | Prefer same as ext; do not add agent/OKF originals to `src/host` | - -**Hard rule:** agent / OKF domain primitives live in `plugins/agent`, never in `HostFn` / `src/host/kb.rs`. - -## Non-goals - -- Embedding plugins in the release exe by default -- Callbacks from plugin into arbitrary Marqdo evaluation -- Arbitrary HostFn passthrough via `host_query` -- **Third-party** plugin / package registry diff --git a/doc/design/ext-agent-parent.md b/doc/design/ext-agent-parent.md deleted file mode 100755 index 5ce9bc7..0000000 --- a/doc/design/ext-agent-parent.md +++ /dev/null @@ -1,150 +0,0 @@ -# 父智能体 Plan-and-Move(`## plan` 行动面) - -| | | -|---|---| -| 状态 | **Accepted** | -| 日期 | 2026-08-11 | -| 父文档 | [ext-agent-plan.md](ext-agent-plan.md) · [ext-agent.md](ext-agent.md) | -| 相关 | [stdlib-subtask.md](stdlib-subtask.md) · [okf.md](okf.md) · [ai-skill.md](ai-skill.md) | - ---- - -## 1. 一句话 - -**父智能体 = Plan-and-Move 控制器**:观察工作簿与子任务结果 → 规划下一步 → 行动(读 / 调工具 / 补丁 / 再跑 / 停);Marqdo「文档即代码」让工具、记忆与程序都落在 `.mq.md` 上。 - ---- - -## 2. 为何需要强化 - -单靠 `DECISION: DONE|CONTINUE|RUN` 时,父侧几乎没有「手」: - -| 缺口 | 后果 | -|------|------| -| 看不到子源码 / 报错 / stdout | 空想 FIND/REPLACE,输出又臭又长 | -| 标准库未进入行动表 | 无法在规划环内用 `fs` / `json` / `subtask` 等 | -| 不能用 Marqdo 造工具 | 无法把可复用步骤沉淀为 `##` | -| 提示词过长且互相打架 | 模型「继续帮忙」而不停机 | - -业界对 agent 回环的共识:成功标准、停机动作、**确定性行动面**三者必须写清;停机最终靠代码护栏,不只靠 prompt。 - ---- - -## 3. Marqdo 赋予的特性(相对通用 Plan-and-Move) - -| 特性 | 含义 | -|------|------| -| 工作簿即程序 | 子执行物是可 `spawn path=` 的 `.mq.md`,不是隐式任务图 | -| 固化即记忆 | `DECISION: DONE` → `agent_workbook_solidify` + OKF 晋升 | -| `lib/*` 即工具 | 标准库是父可调度能力;经父 helper 或写入工作簿/`tools/` 后调用 | -| 补丁即改代码 | `CONTINUE` + 精确 FIND/REPLACE;禁止整文件 LLM 重写 | -| 文档即提示 | 站立提示、Skill 摘要、观察切片都是可读 Markdown,而非黑盒 system blob | - ---- - -## 4. 循环形状(锁定) - -```text - ┌──────────────┐ - │ Plan (LLM) │ - └──────┬───────┘ - │ 协议回复 - ┌─────────────┼─────────────┐ - ▼ ▼ ▼ - READ:/CALL: DECISION: (无效 → error) - │ DONE/RUN/ - │ CONTINUE - ▼ ▼ - Act 工具 Move(固化/补丁/spawn) - │ │ - └──────┬──────┘ - ▼ - Observe(有界) - │ - └──► 回到 Plan 或终止 -``` - -优先级(解析父回复时): - -1. **`CALL:` / `调用:`** — 跑父侧工具,结果并入 observation,再 Plan -2. **`READ:` / `读取:`** — 加深某一观察切片,再 Plan -3. **`DECISION:`** — Move(含运行时 solidify / apply_patch / spawn) - ---- - -## 5. 观察面(有界、可加深) - -`inspect_workbook` / `await_workbook` 在磁盘上可持有全文;**注入父 prompt 的默认紧凑观察**必须可行动且短: - -| 字段 | 默认 | `READ:` 加深 | -|------|------|----------------| -| `source_excerpt` | 去 `` 后的结构摘录,硬顶 ~4KiB / ~80 行 | `READ:source` → 更大但仍有硬顶的摘录 | -| `stderr_tail` / `stdout_tail` | 子任务捕获尾部 ~2KiB | `READ:stderr` / `READ:stdout` | -| `value` | ≤200 字;否则 `value_preview` + `value_len` | (一般不必加深) | -| `slots` | `{key,line,body_len}`;`error` 槽可带短预览 | `READ:slots` | -| `skill_brief`(父 / 子) | ~1.2KiB(`skill_brief`) | `READ:skill` → ~4KiB | -| `has_worker_step` / `solidify_on_done` | 布尔提示 | — | - -`## step` 同样默认注入 **预算后的** `source_brief` + `skill_brief`(非全文);截断处带 `[truncated …; emit READ:…]` 标记,子轮最多 `max_reads` 次加深后再 CALL/作答。 - -`quiet=True` **只表示不污染父 TTY**;file `wait` 仍返回截断后的 `stdout` / `stderr` 供父观察。 - ---- - -## 6. 工具面 - -### 6.1 父侧内建 helper(`CALL:` 首批) - -写在 `ext/ai/agent.mq.md`,由 plan 循环直接调度(**不用** OpenAI function calling): - -| 名称 | 作用 | -|------|------| -| `workbook_read` | 按 depth 读工作簿摘录 | -| `workbook_excerpt` | 结构摘录(默认观察同源) | -| `lib_catalog` | 枚举 `lib/*.mq.md` 能力摘要 | -| `scratch_tool_write` | 写入 `.marqdo/agent-runs/tools/.mq.md` | -| `corpus_search` | 本地语料关键词检索(RAG-lite;`ARGS.query` / `root`) | -| `mcp_list_tools` / `mcp_call` | MCP 形 JSON fixture 列工具 / 调用(离线证据) | - -以上 **corpus / mcp** 返回一律带 `authority=workbook`:检索与外置工具只是证据,**可跑的 `.mq.md` 工作簿 / OKF 技能仍是权威真相**。 - -### 6.2 标准库与造工具 - -- **标准库直调(白名单)**:`CALL:lib.fs.read_text`(及 `exists` / `list_dir` / `json.parse` / `json.stringify` / `sys.cwd`)+ 可选 `ARGS:{…}` JSON 行;拒绝 `net.*` / `sys.exec` / 写删类。 -- **目录**:`lib_catalog` 列出可 CALL 的 dotted 名。 -- **造工具**:优先 `CONTINUE` + 短 PATCH 在工作簿内新增 `##`;或 `CALL:scratch_tool_write` 沉淀独立工具文件。 -- **流式**:父 CALL/READ 发 `tool_start` / `tool_end`(view Tool 卡)。 -- **非目标**:全量 `lib/*` JSON schema 反射;OpenAI function calling。 - ---- - -## 7. 输出纪律(停机规则) - -父回复**只允许**协议行 + 一行 `SUMMARY` + 短 PATCH(`<20` 行)。禁止长独白 / 行程散文 / 把 observation 粘进 REPLACE。 - -修订阶段硬规则(自上而下): - -1. `exit_code==0` 且 `has_value` → **立刻** `DECISION: DONE`(运行时 solidify);`has_worker_step` **不是** CONTINUE 的理由。 -2. 仅失败 / 无值 / 明确未达目标时才 `CONTINUE`。 -3. 代码护栏:非 `improve` 时,子已返回值则 **跳过父 LLM**,直接 solidify + DONE。 - ---- - -## 8. 与 `## step` 的关系 - -| | `step`(子) | `plan`(父) | -|---|-------------|-------------| -| 协议 | `CALL:` 或最终答案 | `CALL:` / `READ:` / `DECISION:` | -| 工具来源 | 工作簿 / 调用方 allowlist | 父 helper + 写入的 Marqdo `##` | -| 成功出口 | 返回答案文本 | `DONE` + solidify / promote | - ---- - -## 9. 实现落点 - -| 组件 | 路径 | -|------|------| -| 设计(本文) | `doc/design/ext-agent-parent.md` | -| 多步总设计增量 | `doc/design/ext-agent-plan.md` §4.1 / 协议 | -| 子任务 I/O | `src/host/subtask.rs`、`lib/subtask.mq.md` | -| 父循环 / 观察 / 提示 | `ext/ai/agent.mq.md` | diff --git a/doc/design/ext-agent-plan.md b/doc/design/ext-agent-plan.md deleted file mode 100755 index db4b13f..0000000 --- a/doc/design/ext-agent-plan.md +++ /dev/null @@ -1,357 +0,0 @@ -# 智能体多步(`## 多步` / `## plan`) - -| | | -|---|---| -| 状态 | **Accepted;D2a–D2f 已落地;父 Plan-and-Move / OKF 软命中见配套文档** | -| 日期 | 2026-08-11 | -| 父文档 | [ext-agent.md](ext-agent.md) | -| 相关 | [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move 行动面**) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [module-namespace.md](module-namespace.md) · [ai-skill.md](ai-skill.md) · [objects.md](objects.md) · [调研:主流框架与 Marqdo](../research/agent-frameworks-and-marqdo.md) | - ---- - -## 1. 动机 - -单步(`## 单步` / `## step`)适合原子任务。复杂目标需要: - -1. **把分解与执行过程落成一份可运行的 `.mq.md`**(工作簿),而不是藏在进程内的任务图。 -2. **用子任务真正跑这份工作簿**,与主推理隔离。 -3. **父智能体作为「智能体开发大师」**:结构化读取执行结果与写回,再二次规划;用**精确补丁**改工作簿代码,并把确定步骤**固化为普通 Marqdo `##`**。 -4. **允许工作簿演化**——代码与 `` 均可更新,但**禁止**以整文件 LLM 重写作为修订主路径。 -5. 子智能体只做不确定的 `单步`;能写成代码的就不要再问模型。 - -本文锁定 **`## 多步` / `## plan`** 的语义。总览与分层见 [ext-agent.md](ext-agent.md);实现以 D2 为准。 - ---- - -## 2. 一句话 - -**多步 = 父智能体(开发大师)生成并演进一份子 Marqdo 程序:经 `lib/subtask` 运行它,结构化观察写回与源码,再二次规划并精确打补丁;子 `# 智能体` 只跑 `单步`,确定步骤固化为代码。** - ---- - -## 3. 角色与产物 - -| 角色 | 职责 | -|------|------| -| **父智能体** | 持有目标;创建 / 改写工作簿;`spawn path=` 运行工作簿;读执行结果与写回块;决定改代码还是改提示;汇总并写回父文档 | -| **工作簿 `.mq.md`** | 任务实现的**详细步骤文档兼程序**:导入、工具、一个或多个子智能体、可固化的普通函数与 `# main` 编排 | -| **子智能体** | 工作簿内的 `# 智能体` / `# agent`;走 `单步`(默认);工具表白名单可收窄 | -| **子任务通道** | `lib/subtask`:`spawn path=<工作簿>` → `wait`;与工具 `spawn fn=` 同一套能力 | - -| 产物 | 说明 | -|------|------| -| 工作簿路径 | 默认目录 `.marqdo/agent-runs/`(可参数覆盖);文件名含时间 / 短 id | -| 父侧返回值 | 结构化 map:`status`、`goal`、`workbook`(路径)、`result`(子 `# main` 返回值优先)、`summary` / `error`;可选 `observation` | -| 写回 | 工作簿内各 `单步` 默认落盘;父 `多步` 调用行亦可汇总写回 | - ---- - -## 4. 调用流水线(锁定) - -```text -父:`助手`.多步 目标=… - ▼ -① 解析参数(目录、深度、是否确认分解、是否覆盖已有工作簿…) - ▼ -② 创建(或打开)工作簿 .mq.md - - frontmatter:导入 ext/ai/llm|agent、json、writeback、subtask… - - **大模型配置与父智能体一致**(见 §5) - - 正文:总目标叙述 + 子智能体骨架 / 或父模型生成的首版步骤 - ▼ -③ 父模型「分解」(非 OKF 命中路径必跑):`phase=decompose`,尚未 spawn;可 `DECISION: RUN` / `CONTINUE`+补丁 / 固化后 `DONE` - ▼ -④ lib/subtask:spawn path=<工作簿绝对或相对路径> - ▼ -⑤ wait → 收集 `{code, value}`(`# main` 返回)+ 工作簿内写回块;TTY 默认静默 - ▼ -⑥ 父智能体 **结构化观察**(工作簿最新源码 + 写回槽 + 退出码 + `value`) - - 充分 → 汇总,写回父文档,返回 - - 不足 / 失败 → **二次规划** → 对工作簿打**精确补丁**(禁止整文件重写)→ 回到 ④ - ▼ -⑦ 触达最大修订轮次或深度 → 以 error / 部分摘要返回 -``` - -要点: - -- **创建文件发生在 `多步` 内**,不是调用方手写脚手架(调用方可传已有 `工作簿=` 路径以续跑)。 -- **执行工作簿 = 子任务跑整文件**(入口 `# main`),不是父进程内嵌解释子 AST。 -- **父是智能体开发大师**:读真实执行结果再规划;修订靠精确补丁与代码固化,不靠整文件重生。 -- **修订循环属于父智能体职责**:同一 `多步` 调用内可多轮「观察 → 规划 → 补丁 → 再 spawn」。 - ---- - -## 4.1 观察面与补丁(锁定) - -父每次二次规划前必须拿到观察 map(`inspect_workbook` / `await_workbook`)。磁盘可持全文;**注入父 LLM 的默认观察为有界紧凑面**(摘录 + I/O 尾部)。完整语义与 `READ:` / `CALL:` 行动面见 [ext-agent-parent.md](ext-agent-parent.md)。 - -| 字段 | 含义 | -|------|------| -| `path` | 工作簿路径 | -| `source` | 最新全文(磁盘);prompt 默认用 `source_excerpt` | -| `exit_code` | 上一轮子任务退出码 | -| `value` | 子 `# main` 返回值(经 `await_workbook` / `wait.value`) | -| `stdout` / `stderr` | 子任务捕获(`quiet` 仅静音 TTY,不丢弃数据) | -| `slots` | 命名写回列表(`key` + `body`) | -| `last_ok` / `last_error` | 便捷字段 | - -二次规划输出协议(机器可解析;**禁止**只输出整份 `.mq.md`;**禁止**长独白): - -```text -CALL: -READ:source|stderr|stdout|slots - -DECISION: DONE -SUMMARY: <一行> - -DECISION: RUN - -DECISION: CONTINUE -PATCH: -<<< -FIND -<确切旧片段> -=== -REPLACE -<新片段> ->>> -``` - -解析优先级:`CALL` → `READ` → `DECISION`。应用器对文件做**精确** FIND→REPLACE;找不到则报错。`DONE` 时运行时 `agent_workbook_solidify` 固化答案(不必靠长 REPLACE 粘贴子散文)。 - ---- - -## 4.2 多轮哲学:仅子智能体接力(模式 C) - -复杂 / 多轮目标 = **多份可执行 `.mq.md` 接力**,经 OKF 索引与复用;父 `plan` 聚合各子 `wait.value` 为 `result`。 - -| 做 | 不做 | -|----|------| -| 每主题 / 子目标一份工作簿(`resources/` / `explore/`) | 单文件无限追加「对话日志」 | -| OKF task/skill 做索引与命中 | 单文件状态机表冒充流程 UI | -| `# main` **返回**答案;`quiet` 只管 TTY | 依赖子 `print` 把答案刷到父终端 | ---- - -## 5. 大模型配置与父保持一致 - -工作簿内构造子智能体时: - -| 从父继承 | 说明 | -|----------|------| -| `model` / `大模型` 句柄字段 | `api_key`、`base_url`、`model`、`suffix`、`bearer` 及拼装前缀等与父相同 | -| 默认站立提示基调 | 可追加「只负责本工作簿内子任务」等收窄句;不得更换供应商端点 | - -实现约定(D2): - -1. 父把当前 llm 句柄 **序列化进工作簿**(例如构造段直接写 `> llm.llm` 前先 `load_env`,或写入由父生成的配置表 / 环境约定)。 -2. 优先:**工作簿与父共享同一套 `OPENAI_*` / `.env` 加载路径**,子文件内 `> llm.load_env` + `> llm.llm`(或中文面),避免把密钥明文写进工作簿。 -3. 若父句柄来自非默认 env,父须在生成工作簿时写出等价构造(仍禁止把密钥写进 git 跟踪路径;工作簿目录应默认被 ignore)。 - -**禁止**:子工作簿默默改用另一 `base_url` / 另一模型名,除非调用方显式参数允许覆盖(v1 不提供覆盖;一律继承)。 - ---- - -## 6. 工作簿内容形态 - -### 6.1 推荐:多个子智能体 - -面对多种情形时,**多个 `# 智能体`(或一个类型多次构造)** 优于单一巨型提示: - -```markdown ---- -title: agent-run-… -import: - llm: ext/ai/llm.mq.md - agent: ext/ai/agent.mq.md - json: lib/json.mq.md - writeback: lib/writeback.mq.md - subtask: lib/subtask.mq.md ---- - -# 总目标 - -(父写入的目标叙述) - -## 工具甲 -… - -# main - -> llm.load_env path=… - -*`模型` = > llm.llm * - -*`调研` = > agent.agent model=`模型` tools=`表甲` standing=… * -*`撰写` = > agent.agent model=`模型` tools=`表乙` standing=… * - -*`a` = > `调研`.step task=… * -*`b` = > `撰写`.step task=… * -``` - -### 6.2 也可:一个智能体多次单步 - -适合线性流水线;每次 `step` 仍默认写回,便于中断续跑。 - -### 6.3 固化为代码(强烈推荐) - -一旦某步输入输出稳定(例如「取今日日期」「解析固定 JSON」),父智能体应把该步 **改写成普通 `##` 函数 + 直接调用**,不再经子智能体推理: - -| 不确定 | 已确定 | -|--------|--------| -| `` > `子`.step task=… `` | `` *`x` = > 本地函数 … `` | -| 宽工具表 + 长 standing | 窄函数、表驱动、分支 `1.` / `2.` | - -**多步的价值之一就是把「试出来的正确步骤」沉淀成工作簿里的代码**,而不仅是 chat 痕迹。 - -### 6.4 持续更新的两类内容 - -| 更新 | 含义 | -|------|------| -| **代码更新** | 增删 `##`、改 `# main` 编排、改工具表、把 step 换成固化调用、修分支 | -| **写回注释更新** | `` 被单步 / 父汇总刷新;替换时**不得累积空行**(见 writeback 实现约定) | - -工作簿是活文档:子任务跑完后磁盘上的 `.mq.md` 应比创建时更「像最终报告」。 - ---- - -## 7. 单步自动写回(服务多步) - -### 7.1 决议 - -| | | -|---|---| -| **默认** | `单步` / `step` **自动写回** 本步结果(命名槽) | -| **开关** | 参数 `写回` / `writeback`(布尔,默认 `真` / `True`) | -| **槽** | 成功 → `key=ok`;失败 → `key=error`;正文为结构化 map 的 JSON(或与现 live 样例一致的 stringify) | -| **锚点** | 本步调用行(与现 `writeback.record` 锚点规则一致) | - -这样: - -- 父 / 工作簿**不必**靠提示词强迫模型「请记得写回」。 -- 编排方仍可 `写回=假` 拿到纯 map,自行 `writeback.record`(测试、嵌套去重时有用)。 - -### 7.2 与父写回的分工 - -| 层级 | 写什么 | -|------|--------| -| 子 `step`(默认开) | 该步 decision / tool / result 或 error | -| 父 `plan` | 工作簿路径、轮次、汇总摘要;可选把关键子 ok 块索引写在父调用行下 | - -**推荐**:载荷以子 `# main` 返回值(`wait.value` → `plan.result`)为准;写回作审计与 step 缓存。避免只靠 stdout(默认静默会丢弃)。 - -### 7.3 返回值 - -`step` 仍返回结构化 map(与现 D1 一致)。自动写回是**附加副作用**,不取代返回值。 - ---- - -## 8. 父智能体上下文(每次修订 / 汇总前) - -父在多步循环中每次「想下一步」时,注入不得弱于单步,且额外包含工作簿: - -| 片段 | 来源 | -|------|------| -| 站立提示 | 父构造 | -| 总目标 | `多步` 实参 | -| **父文件源码** | `agent_module_source` | -| **调用位置** | `agent_call_site` | -| **Marqdo Skill** | `agent_marqdo_skill` | -| 工作簿全文 / 写回 / 子返回 | `inspect_workbook`(源码 + slots + 退出码 + `value`) | -| 子任务退出码 | `subtask.wait` | -| 对话 / 历史 | 父 session;真相以写回为准 | - -父模型输出必须是 **DONE / CONTINUE+精确补丁** 协议(见 §4.1),禁止整文件重写。 - ---- - -## 9. 公开 API(D2 契约) - -### 9.1 `## 多步` / `## plan` - -| 参数 | 中 / 英 | 默认 | 说明 | -|------|---------|------|------| -| 目标 | `目标` / `goal` | 必填 | 复杂任务描述 | -| 工作簿目录 | `工作簿目录` / `workbook_dir` | `.marqdo/agent-runs` | 新建文件所在目录 | -| 工作簿 | `工作簿` / `workbook` | 空 | 若给路径则**续跑 / 修订**该文件,跳过空白创建 | -| 最大深度 | `最大深度` / `max_depth` | `2` | 工作簿内再调 `多步` 的嵌套上限;叶强制单步 | -| 最大轮次 | `最大轮次` / `max_rounds` | 实现选定(如 `4`) | 父「改文件 → 再执行」循环上限 | -| 确认分解 | `确认分解` / `confirm` | `假` | `真` 时首版工作簿生成后暂停(返回 pending + 路径),不自动 spawn | -| 写回 | `写回` / `writeback` | `真` | 父侧汇总写回 | -| 骨架 | `骨架` / `skeleton` | `single` | `single` 单 worker;`dual` 为 research→writer 两子智能体 | - -返回 map(字段名英文字段,中文面可读同一结构): - -| 字段 | 含义 | -|------|------| -| `status` | `ok` / `error` / `pending`(待确认) | -| `goal` | 回显目标 | -| `workbook` | 工作簿路径 | -| `rounds` | 实际执行轮次 | -| `summary` | 成功时的汇总 | -| `error` | 失败信息 | - -### 9.2 `## 单步` / `## step`(修订) - -在 D1 参数上增加: - -| 参数 | 默认 | 说明 | -|------|------|------| -| `写回` / `writeback` | `真` | 是否自动 `record` 到 ok/error 槽 | - -### 9.3 内部辅助(非稳定对外) - -工作簿模板渲染、从父句柄生成子文件 frontmatter、解析子写回摘要等——可随实现调整。 - ---- - -## 10. 安全与边界 - -| 风险 | 对策 | -|------|------| -| 无限修订 / 嵌套 | `最大轮次`、`最大深度`;叶任务禁止再 `plan` | -| 工作簿写爆仓库 | 默认目录 `.marqdo/agent-runs/` + gitignore;禁止默认写到 `lib/` / `ext/` | -| 密钥进工作簿 | 继承 env / load_dotenv,不写明文 key | -| 子文件乱改父仓 | 子任务 cwd / fs_root 落到工作簿目录;工具表白名单 | -| 写回空行膨胀 | 替换跨度含 `-->` 行尾换行(已实现) | -| 并发写同一工作簿 | writeback 全局锁;同一 plan 内串行 spawn 为 v1 默认 | - ---- - -## 11. 与旧 §3.2 叙述的差异(显式) - -| 旧粗述 | 本文锁定 | -|--------|----------| -| 分解表 + 每行一个子智能体实例 | **整文件工作簿**可含多智能体与固化代码;表只是可选骨架 | -| 子任务默认单步,写回在流水线步骤里点到为止 | **单步默认自动写回**;父负责修订循环与汇总 | -| 缓存命中略写 | **以 OKF 任务知识包为准**([okf.md §7](okf.md)):Task→Skill→resource 命中则跳过父模型;D2 + O2 已落地;人读目录见 O3 `marqdo catalog` | -| 父上下文未强调工作簿全文 | 父每次修订前必须能读**最新工作簿 + 写回** | - ---- - -## 12. 实现路线(D2) - -| 项 | 内容 | -|----|------| -| D2a | `step` 增加 `writeback=`(默认真);金样例改默认行为并保留 `writeback=False` 测例 | **done** | -| D2b | 工作簿模板 + 创建路径 + 父 llm 继承;`inspect_workbook` 观察面 | **done** | -| D2c | `plan`:生成 → `spawn path` → wait → **观察** → 返回;`confirm` | **done** | -| D2d | 二次规划 + **精确补丁**循环(`max_rounds`);禁止整文件重写 | **done**(主路径) | -| D2e | 多子智能体模板与固化提示 | **done**(`skeleton=dual` + Solidify 段 + 父规划优先级) | -| D2f | 离线骨架金样例 + 可选 live 多步 | **done**(decision 离线 + `agent-plan-live`) | - ---- - -## 13. 决议摘要 - -1. **`多步` 自动创建(或续跑)工作簿 `.mq.md`**,内容为任务的详细可执行步骤。 -2. **子文件大模型配置与父一致**(共享 env / 等价句柄;v1 无静默换模)。 -3. **经 `lib/subtask` 启动该文件**;可多轮执行。 -4. **工作簿内推荐多个智能体**;也允许单智能体多 `step`;**确定步骤固化为代码**。 -5. **工作簿持续更新**:代码 + `marqdo-out`。 -6. **`单步` 默认自动写回**(`写回=` 可关);父维护汇总写回。 -7. **父具备源码、Skill、位置、历史与工作簿观察面**,二次规划后以**精确补丁**修改再执行(禁止整文件重写主路径)。 - ---- - -## 14. 一句话 - -**多步不是更长的聊天,而是父智能体编写、运行、修订一份子 Marqdo 程序——程序里的智能体可多可少,写回默认打开,能写成代码的就不要再问模型。** diff --git a/doc/design/ext-agent.md b/doc/design/ext-agent.md deleted file mode 100755 index d3da398..0000000 --- a/doc/design/ext-agent.md +++ /dev/null @@ -1,366 +0,0 @@ -# Official agent development framework (`ext/ai/agent`) - -| | | -|---|---| -| Status | **Accepted · redesign**(取代「thin TOOL: loop」方案) | -| Date | 2026-08-07 | -| Related | [ext-llm.md](ext-llm.md) · [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md) · [**ext-agent-plan.md**](ext-agent-plan.md)(**多步锁定设计**) · [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move**) · [**okf.md**](okf.md)(**OKF / 任务知识包**) · [**engineering-knowledge.md**](engineering-knowledge.md)(**EKC / EFI preflight**) · [**调研:主流框架与 Marqdo 优势**](../research/agent-frameworks-and-marqdo.md) · [**缺口:A0–A4 之后**](../research/agent-framework-gaps-after-a4.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [markdown-mapping.md](markdown-mapping.md) | - -## 0. 为什么要改掉旧方案 - -旧版把智能体做成「黑盒对话循环」:隐藏提示拼装、`TOOL:` 协议、host 历史袋、一次(或几次)模型往返。这是对 LangChain 类框架的平移,**背离了 Marqdo 的初衷**。 - -Marqdo 的宪法是 **代码即文档、文档即知识库**: - -| 旧方案的问题 | Marqdo 应有的形态 | -|--------------|-------------------| -| 提示词藏在框架字符串里,与编排源码分离 | 提示、工具、任务、结果都在 `.mq.md` 里,人与模型同读同写 | -| 执行过程是不透明的 chat transcript | 思考与行动写回文档;`view` / `debug` 可跟可审 | -| 复杂任务与简单任务同一套循环 | **单步**与**多步(工作簿)**两级模型 | -| 成功经验留在进程内存 | **自写回**做成果缓存与失败知识;同类任务可复用 | - -本文件锁定新方向。仓库里现有的 `ext/ai/agent.mq.md` / `智能体.mq.md`(TOOL: 薄循环)视为 **待替换实现**,以本文为准。 - ---- - -## 1. 我们在建什么 - -一个 **文档驱动的智能体开发框架**:编排本身就是可读的 `.mq.md`;模型吃的是这份文档与调用位置;写回让思考过程可控、可调试、可沉淀。 - -**不是** 外挂任务队列、**不是** 官方捆绑领域工具、**不是** 第二套聊天栈(模型 I/O 仍用 `ext/ai/llm`)。 - -| 在范围内 | 在范围外(应用 / runbook) | -|----------|---------------------------| -| `# 智能体` / `# agent` 构造 | 领域工具:`## 查天气`、`## 分配任务` … | -| `## 单步` / `## step` | 业务表格、队列、工单流程 | -| `## 多步` / `## plan`(生成并驱动工作簿) | 具体分解策略模板库(可放用户仓) | -| 上下文:源码、调用位置、工作簿路径、Skill | 第二套 HTTP / 聊天协议 | -| 与 `lib/writeback`、**`lib/subtask`(工具执行通道)**、**`lib/plugin` + ABI v2 `plugins/agent`** 协作 | 把领域技能塞进官方 `ext/ai/`;在 `ext` 内直调 `host_*` | - ---- - -## 2. 核心理念:编排可读,过程可写回 - -1. **提示词与代码不分离** - 站立提示、工具表、任务叙述都写在 `.mq.md` 里。框架把**当前模块源码**与**调用位置**交给模型,而不是另起一套 system prompt 黑盒。 - -2. **把 Marqdo 源码交给智能体** - 每次推理可注入:入口 / 工作簿 `.mq.md` 全文(或相关切片)、`host_call_site`(路径、函数、行)、`skills/marqdo`(写 / 读 `.mq.md` 的语法纪律)。模型输出应优先是 **可解释的决策** 与 **对文档的结构化改动意图**,而不是私有 JSON 协议。 - -3. **自写回 = 思考轨迹 + 成果缓存** - 成功或失败都写回文档(见 [stdlib-writeback.md](stdlib-writeback.md))。成功块可被后续同类任务命中,避免重复失败;失败块成为可读的「避坑记录」。`marqdo view` 在语句下展示 output-card,调试面可对齐同一份真相。 - -4. **相对其他框架的优势** - 无需外挂向量库 / 状态机才能「记住」某次子任务已成功:记忆就是仓库里的 Markdown。审计、合规、复盘 = `git log` + 打开工作簿。 - ---- - -## 3. 两级执行模型 - -### 3.1 模式 A — 单步(原子任务) - -| | | -|---|---| -| **输入** | 小任务描述 + 必要上下文(工具表、站立提示、源码切片) | -| **过程** | 一次(或有限次)推理;可选调用 **runbook 内** 的工具函数;结果写回 | -| **输出** | 原子结果(文本 / 表 / 句柄字段) | -| **适用** | 问答、单一工具、确定性一步 | - -公开方法(中 / 英):`## 单步` / `## step`。 - -示意(语法外形;实现以落地代码为准): - -```markdown ---- -导入: - 智能体: ext/ai/智能体.mq.md - 大模型: ext/ai/大模型.mq.md - 自写回: lib/自写回.mq.md - 时间: lib/时间.mq.md ---- - -## 获取时间 - -*`u` = > 时间.此刻秒 * -**> 时间.格式化 秒=`u` 格式=%Y-%m-%d** - -# main - -*`模型` = > 大模型.大模型 * -`工具表` = -| 工具 | -|------| -| 获取时间 | - -*`助手` = > 智能体 大模型=`模型` 工具=`工具表` 站立提示=你是可调试的 Marqdo 助手。 * - -*`结果` = > `助手`.单步 任务=今天日期是什么?请在需要时调用工具。 * -> 打印 内容=`结果` -``` - -单步约定: - -- 模型看到的上下文 **包含本文件源码与调用位置**,因此「有哪些 `##` 工具」对模型是可见的;行动约定写在提示里(人可读),例如单独一行 `CALL:<工具名>` / `调用:<工具名>`,最终答案则直接正文回复。 -- 工具仍是 **runbook 里的 `##` 函数**(v1 以零参为主;可经 `args=` 扩展)。 -- **调用工具走 [`lib/subtask`](stdlib-subtask.md)**:白名单校验通过后 `spawn fn=<名>`(中文面 `启动 函数=`)→ `wait` / `等待`,而不是进程内直接 `call_fn`。这样工具与主推理隔离在子任务语义下,并可与并行、超时、探测同一套主机能力对齐。 -- 结束后用自写回记录:任务摘要、选用工具、结果或错误。 - -### 3.2 模式 B — 多步 / 复杂执行(工作簿) - -> **完整锁定设计**见 [**ext-agent-plan.md**](ext-agent-plan.md)。以下为摘要。 - -| | | -|---|---| -| **输入** | 复杂目标 | -| **过程** | 父智能体**创建(或续跑)工作簿** →(非命中)**父先分解** → **`lib/subtask` spawn** 跑子文件 → 观察写回 → **父修订补丁后再执行**(有轮次上限) | -| **输出** | 汇总 map(含 `result`)+ 磁盘上的工作簿(代码与 `marqdo-out` 均可演化) | -| **适用** | 需分解、多情形、可固化步骤、可复用子成果的任务 | - -公开方法:`## 多步` / `## plan`。 - -流水线要点: - -1. **创建工作簿** — 默认 `.marqdo/agent-runs/`;内容为任务的详细可执行步骤(导入、工具、`# main`、子智能体)。 -2. **模型配置继承父智能体** — 共享 env / 等价 llm 句柄;v1 不静默换模。 -3. **子任务执行整文件** — 不是父进程内嵌解释。 -4. **工作簿内推荐多个 `# 智能体`**;也允许一个智能体多次 `单步`;**已确定步骤应固化为返回答案的普通代码**(多轮 = 多文件接力 + OKF,见 [ext-agent-plan.md §4.2](ext-agent-plan.md))。 -5. **持续更新** — 代码修订 + 写回注释刷新(替换不累积空行)。 -6. **`单步` 默认自动写回**(`写回=` / `writeback=` 可关),父侧再汇总写回。 -7. **父上下文** — 与单步同级的源码 / Skill / 调用位置 / 历史,外加工作簿全文与子写回。 - -示意: - -```markdown -*`报告` = > `编排`.多步 目标=调研并汇总三篇资料的要点 * -> 打印 内容=`报告` -``` - -工作簿概念形状与修订循环细节 → [ext-agent-plan.md](ext-agent-plan.md)。 -## 4. 分层与仓库布局 - -```text -ext/ - ai/ - llm.mq.md / 大模型.mq.md # 模型 I/O - agent.mq.md / 智能体.mq.md # 本框架(按本文重写) -``` - -| 层 | 职责 | -|----|------| -| **应用 runbook** | 领域 `##` 工具、任务表、是否人工确认分解 | -| **`ext/ai/agent`** | 单步 / 多步、工作簿生成、子智能体编排、写回约定 | -| **`ext/ai/llm`** | 补全 / 聊天 | -| **`lib/writeback`** | 持久化输出块 | -| **`lib/subtask`** | **工具调用与(多步时)子智能体并行的执行通道**;见 [stdlib-subtask.md](stdlib-subtask.md) | - -安装:[`ext-cli.md`](ext-cli.md) — `marqdo ext add agent` / `add llm`(`.mq.md` + `native/libagent.so`)。导入:`导入 智能体:ext/ai/智能体.mq.md`。 - -**原生插件(ABI v2)**:`ext/ai/agent` 经 `lib/plugin` 加载;优先 `> plugin.native_path name=agent`,否则按序查找: - -1. `MARQDO_AGENT_PLUGIN`(显式 `.so` / `.dylib` 路径) -2. `CARGO_TARGET_DIR/{debug,release}/libagent.so`(或 `.dylib`) -3. cwd `target/{debug,release}/` -4. 可执行文件旁 `libagent.*` 或 `target/debug/` -5. `MARQDO_EXT/native/libagent.*`(`marqdo ext add agent` 安装) - -本地开发须先 `cargo build -p marqdo_plugin_agent`(或 `ext add agent` / 设 `MARQDO_AGENT_PLUGIN`)。详见 [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md)。 - -**分层纪律(硬规则,勿破)**: - -1. `ext/**/*.mq.md` **禁止**出现任何 `host_*` / `host_` 调用。 -2. Agent 专属能力(含 OKF agent-kb:`agent_goal_sig` / `agent_kb_lookup` / `agent_kb_promote` / …;以及 EKC:`agent_eng_preflight` / `agent_eng_reuse` / `agent_eng_record`)只进 **`plugins/agent` 注册名**,由 `ext/ai/agent` 在 `plugin.load` 后调用。 -3. **禁止**向 `src/host/`(`HostFn` 表)添加 agent / OKF / EKC 领域原语,以免核心包体膨胀。通用 L0.5 仅保留 fs/json/subtask 等标准库底层。 -4. **Engineering preflight**:`agent.preflight` / `plan … eng_preflight=True` 在 agent-kb 之前解析 REUSE/ADAPT/CREATE(见 [engineering-knowledge.md](engineering-knowledge.md))。缺 `.marqdo` 知识图时返回 `missing_knowledge` 并放行,以兼容纯任务包测试。 -4. 进程退出用 `sys.exit` / `系统.退出`,不用裸 `exit`。 - -官方 `ext/ai/` 用 `lib/*` 包装或插件注册名;见 [module-namespace.md](module-namespace.md) §8 · [ext-abi.md](ext-abi.md)。 - ---- - -## 5. 公开 API(目标契约) - -| 中文 | 英文 | 角色 | -|------|------|------| -| `# 智能体` | `# agent` | 构造:`大模型`/`model`,`工具`/`tools`,可选 `站立提示`/`standing` | -| `## 运行` | `## run` | **v2 主入口**:Adaptive `route` → execute → record episode → maybe_learn(技能 + 策略) | -| `## 单步` | `## step` | 原子执行;注入源码 + 位置;可选工具;返回结构化 map;**默认自动写回**(`写回=` / `writeback=` 可关) | -| `## 多步` | `## plan` | 建/续工作簿 → subtask 跑文件 → 修订循环 → 汇总(见 [ext-agent-plan.md](ext-agent-plan.md)) | -| `## 解析` | `## resolve` | 技能解析:exact → alias → canonical → near | -| `## 路由` | `## route` | **P4 Adaptive Routing**:`marqdo` \| `small-llm` \| `llm` \| `auto`(`jev` 为 `small-llm` 兼容别名) | -| `## 应用路由` | `## route_apply` | 将小模型/大模型路由回复(`SKILL:` / `EXPLORE`)落到 kb 技能 | -| `## 编译策略` | `## compile_policy` | Policy Compilation → `policies/router.mq.md` | -| `## 记录情景` | `## record_episode` | 每次执行沉淀为 `.mq.md` episode(`.marqdo/agent-memory/`) | -| `## 尝试学习` | `## maybe_learn` | 情景足够时归纳 → 合成 → 编译技能,并尝试编译策略 | -| `## 编译` | `## compile` | 候选技能 → 版本化 `skills//vN.mq.md` + 可选 OKF promote | -| `## 指标` | `## metrics` | Reasoning amortization(`avg_llm_calls` / `compiled_runs`) | -| `## 分解` | `## decompose` |(可公开或内部)目标 → 子任务表 | -| `## 清空历史` | `## clear_history` | 若仍保留会话式辅助状态则清空;**不以隐藏 chat 袋为真相源**——真相在文档写回 | - -**Skill Compilation(v2)**:Agent 的记忆不是向量袋,而是可执行 `.mq.md`。路径:`episodes/` → `experiences/` → `candidates/` → `skills/vN.mq.md` → OKF `agent-kb`(`llm_free`)。编译技能正文为合法 Marqdo(`**result = …**` + 斜体返回);金样 `tests/ext/agent-zero-llm.mq.md` 验收 policy+skill 全路径 `execution.llm_calls=0`。`plan` 对已存在的 `resources/.mq.md` **不覆盖**(`agent-plan-preserve`)。 - -**LLM 成本**:`model_turn` 走 `model.ask` / `stream`+`collect`,把 `LLMResult.tokens` 写入 episode / `execution`。 - -**Adaptive Routing(P4)**:Router 是抽象能力,backend = `marqdo`(已编译 `policies/router.mq.md`)/ `small-llm`(`router_model` 任意 llm 句柄)/ `llm` / `auto` 级联。`jev` 仅为 `small-llm` 兼容别名,**不进入框架专属设计**。热路径在 **`plugins/agent`**(`route.rs`);**禁止**向 `src/host/` 加领域原语。设计:[doc/next/003.md](../next/003.md) · [doc/next/004.md](../next/004.md)。 - -构造参数(v1): - -| 参数 | 说明 | -|------|------| -| `大模型` / `model` | `ext/ai/llm` 句柄 | -| `工具` / `tools` | 工具名表(单列文本,或多列且含 `工具`/`tools`/`name`) | -| `站立提示` / `standing` | 写在文档里的常驻说明(可空) | - -`## 单步` 参数:`任务` / `task`;可选 `写回` / `writeback`(默认真)、深度、是否强制不用缓存等。 -`## 多步` 参数:`目标` / `goal`;可选 `工作簿目录`、`工作簿`(续跑路径)、`最大深度`、`最大轮次`、`确认分解` —— 详见 [ext-agent-plan.md §9](ext-agent-plan.md)。 - -模块内辅助函数(组装上下文、解析模型回复、匹配写回缓存)**不是**稳定对外契约,可随实现调整。 - ---- - -## 6. 工具表与子任务调用 - -工具 **不是** 框架内置能力。在 runbook 定义 `##`,再用表登记名称: - -```markdown -`工具表` = -| 工具 | -|------| -| 获取时间 | -| 读取摘要 | -``` - -- 单列表 → 名称列表。 -- 多列表 → 从列 `工具` / `tools` / `name` 取名。 -- 名称须对应当前模块(或导入可见)的 `##`。 -- **不要** 用 `parse text=["fn"]` 列工具(未加引号的标识符会被当成调用)。 - -### 6.1 调用路径(锁定) - -```text -模型回复含 CALL:<名> / 调用:<名> - ▼ -host_tool_allowed(工具表白名单) - ▼ -lib/subtask:spawn fn=<名> → wait - ▼ -工具返回值写回上下文 / 自写回 -``` - -| | | -|---|---| -| 英文面 | `> spawn fn=`名`` → `> wait id=`…`` | -| 中文面 | `> 启动 函数=`名`` → `> 等待 id=`…`` | -| 可选 | `args=` / `参数=` 传给带形参的工具;多工具并行时多次 `spawn` 再 `wait_all` / `等待全部` | - -**非目标:** 以裸 `call_fn` 作为框架默认工具通道(应用仍可直接 `call_fn`,但官方智能体走子任务库)。 - -领域逻辑永远留在应用文件,不进官方 `ext/ai/`。 - ---- - -## 7. 上下文注入(每次单步 / 子步) - -必须可注入(实现可切片,但不得默默丢掉「代码即文档」): - -| 片段 | 来源 | -|------|------| -| 站立提示 | 构造参数 / 文档正文 | -| 任务 / 目标 | 方法实参 | -| 工具表(人可读) | 构造参数 | -| **当前 `.mq.md` 源码** | 插件 `agent_module_source`(经 ABI v2 `host_query`) | -| **调用位置** | 插件 `agent_call_site` | -| **Marqdo skill** | 插件 `agent_marqdo_skill` | -| Marqdo Skill | `skills/marqdo/`(`MARQDO_SKILL` 可覆盖) | -| 相关写回块 | `lib/writeback` 的 `get` / `list` | - -禁止:把整份 Skill + 全文源码藏进不可审查的二进制提示且不在文档中留迹。框架拼装的提示应能在调试时落盘或写回(至少摘要)。 - ---- - -## 8. 自写回与缓存语义 - -依赖 [stdlib-writeback.md](stdlib-writeback.md):`record` / `写回` → ``。 - -### 8.1 单步返回值与默认写回 - -`单步` / `step` 返回结构化 map,并在 **`写回` / `writeback` 默认真** 时自动 `record` 到命名槽(成功 `ok` / 失败 `error`)。关闭写回则行为与早期「纯返回值」一致,由编排方自行 `writeback.record`。 - -| 字段 | 何时 | 含义 | -|------|------|------| -| `status` | 总是 | `ok` / `error` | -| `task` | 总是 | 本步任务 | -| `decision` | 总是 | 模型首轮输出(含 CALL 行等) | -| `tool` / `tool_result` | 成功且调了工具 | 工具名与子任务返回 | -| `result` | 成功 | 最终答复 | -| `error` | 失败 | 错误信息 | - -```markdown -*`out` = > `助手`.step task=… * -*`回复` = > json.get value=`out` key=result * -# 默认已写回;若 writeback=False 则需自行 record: -# > writeback.record value=`body` key=ok -``` - -命名槽 `ok` / `error` 互不覆盖;锚点为调用行。多步工作簿内依赖此默认写回,避免靠提示词强制落盘 —— 见 [ext-agent-plan.md §7](ext-agent-plan.md)。 - -**命中规则(后续缓存)**:读 `key=ok` 且非占位时可复用。失败知识读 `key=error`。 -用户可 `clear key=ok` / `clear key=error` 强制重跑。 - -复杂执行中,子结果写回优先落在 **工作簿** 文件;父 `多步` 维护汇总写回。 - -### 8.2 Live 金样例 - -[`tests/ext/agent-run-live.mq.md`](../../tests/ext/agent-run-live.mq.md):`agent.step`(**默认写回** `ok`/`error`)+ 子任务工具。凭证:`tests/ext/.env`;`> llm.load_env path=.env` 相对**源文件目录**。需已构建 agent 原生库(见 §4)。 ---- - -## 9. 安全与边界 - -| 风险 | 对策 | -|------|------| -| 无限多步递归 | `最大深度`(默认小,如 2);叶任务强制单步 | -| 工具越权 | 仅工具表白名单;子智能体可传更窄的表 | -| 工作簿爆炸 | 统一目录、命名含时间 / id;可选总超时 | -| 缓存过期 | 签名 + 时间戳;手动清块 | -| 模型乱改仓库 | 写回 API 约束写入形态;多步生成文件限于工作簿目录 | - ---- - -## 10. 相对旧 API 的迁移 - -| 旧(废弃方向) | 新 | -|----------------|----| -| 唯一的 `## 执行` / `## run` + 隐藏 TOOL: 循环 | `## 单步` / `## 多步` | -| host 历史袋为真相 | 文档写回 + 工作簿为真相;历史袋至多辅助 | -| 提示全在框架字符串 | 站立提示与任务在 `.mq.md`;源码注入 | -| `tests/ext/agent-smoke` 测 TOOL 上下文拼接 | 重写为单步离线 / 写回 / 工作簿骨架测试 | - -兼容:可短期保留 `## 执行` 作为 `## 单步` 的别名,但文档与金样例迁到新名后删除别名。 - ---- - -## 11. 实现路线(文档锁定后) - -| 阶段 | 内容 | 状态 | -|------|------|------| -| D0 | 本文 Accepted;废弃 thin TOOL 设计叙述 | **本文件** | -| D1 | 重写 `ext/ai/agent.mq.md` / `智能体.mq.md`:`单步` + 源码/位置注入 + **子任务调工具** + **结构化返回值**;运行时经 **ABI v2 agent 插件**(禁 ext 直调 host) | **done** | -| D2 | `多步`:按 [ext-agent-plan.md](ext-agent-plan.md)(观察→精确补丁;禁止整文件重写);**D2a–D2f 主路径已落地** | **done** | -| D3 | 金样例:离线单步 / 写回;**live 单步**(`tests/ext/agent-run-live.mq.md`);多步骨架(可不打网) | **live done** | -| D4 | `view` / `debug` 对工作簿与写回块的导航体验 | done(workbook 链到 `/file?path=`;写回槽 `ok`/`error`/`trace` 徽章 + `#wb-{line}`;plan 结果卡) | -| O2 | OKF 任务知识包:`plan` reuse/promote([okf.md §7](okf.md)) | **done** | - -### 非目标 - -- 在官方 `ext/ai/` 捆绑领域工具或工单技能 -- 在 `ext/` 根目录摊平 `.mq.md` -- 平行再造一套 LLM HTTP 栈 -- 以不可读的私有二进制协议作为编排主界面 - ---- - -## 12. 一句话 - -**智能体框架必须让编排看起来像文档、跑起来像程序、留痕像知识库。** -单步解决原子问题(默认写回);多步让父智能体编写并修订子 Marqdo 工作簿、经子任务执行、把确定步骤固化为代码——详见 [ext-agent-plan.md](ext-agent-plan.md)。 - -流式:`## step` / `## plan` 支持 `stream=True` / `echo=True`(SSE 增量;返回 map 不变;`plan` 另附 `events`,可选 `trace` 写回)。非命中时先流式父分解再 spawn 子任务。见 [agent-streaming.md](../roadmap/agent-streaming.md)。 diff --git a/doc/design/ext-ai-optimize.md b/doc/design/ext-ai-optimize.md deleted file mode 100755 index bd2a19e..0000000 --- a/doc/design/ext-ai-optimize.md +++ /dev/null @@ -1,142 +0,0 @@ -# 方案:智能体 / 大模型优化方向(代码即文档 · OKF · 沙盒) - -| | | -|---|---| -| 状态 | **Accepted · O1–O5 locked** | -| 日期 | 2026-10-16 | -| 调研 | [ai-agent-llm-optimize-2026-10.md](../research/ai-agent-llm-optimize-2026-10.md) | -| 路线 | [ext-ai-optimize.md](../roadmap/ext-ai-optimize.md) | -| 相关 | [ext-ai-sandbox.md](ext-ai-sandbox.md) · [ext-agent.md](ext-agent.md) · [okf.md](okf.md) · [engineering-knowledge.md](engineering-knowledge.md) · [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) · [ai-stack.md](../roadmap/ai-stack.md) | - ---- - -## 0. 方案立场 - -1. **强化差异化**:可执行 `.mq.md` 为权威;OKF 为复用;沙盒为证明;LLM 为探索。 -2. **不向隐藏 TOOL: 循环 / 向量权威回退。** -3. 下列方向均为**可行**;推荐波次见 §3,最终裁剪由你选型。 -4. **不改** `doc/next/*`;落地时另开 roadmap 切片。 - ---- - -## 1. 架构愿景(闭环) - -```text -目标 / 任务 - │ - ▼ -EFI / OKF lookup ──hit──► llm_free / marqdo 执行 ──► writeback - │ miss - ▼ -small-llm 路由 / 父分解 - │ - ▼ -生成或修补 .mq.md(代码即文档风格) - │ - ▼ -sandbox.open → sandbox.run(caps)→ diff - │ - ├─ 失败 → writeback error / 隔离,不 promote - └─ 成功 → 人审或策略 → commit → solidify / OKF promote - │ - ▼ - 下次 REUSE(降本) -``` - ---- - -## 2. 可行方向全集 - -每个方向标注:解决的问题(Pn)、依赖、风险、粗粒度成本。 - -### A. 沙盒 × Agent 闭环 - -| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 | -|----|------|------|--------|------|------|------| -| **A1** | `step`/`plan` 默认经 sandbox 试跑再写实树 | P1 | 生成落 upper;绿才 `commit` | sandbox | 破坏现有金样默认 | 中 | -| **A2** | Promote / solidify 强制 sandbox proof | P1 | OKF 写入前要求 proof fixture 绿 | sandbox+OKF | 过严挡复用 | 中 | -| **A3** | Sandbox profile 表(caps 宣告) | P1/P3 | GFM 表声明 net/plugin/fs | sandbox | 表方言膨胀 | 低 | -| **A4** | Guest 风格门禁(表优先、禁 json 胶水) | P5 | commit 前 lint / preflight | sandbox+parser | 误杀合法 json.parse | 中 | -| **A5** | 会话 diff → view 审阅卡 | P1/P4 | HITL 看 CoW diff | view+sandbox | UI 工时 | 中高 | -| **A6** | 多会话并行 CoW(fan-out 实验) | — | 每假设一 session | sandbox | 隔离/合并复杂 | 高 | - -### B. OKF / EKC / 技能层 - -| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 | -|----|------|------|--------|------|------|------| -| **B1** | OKF 技能元数据:适用条件 / fixtures / sandbox_profile | P2 | frontmatter + 目录约定 | okf | 与 catalog 字段冲突 | 中 | -| **B2** | Progressive disclosure(索引轻、正文按需 READ) | P2/P6 | 对齐 Anthropic Skills 层级 | agent A3 | 实现重复 | 中 | -| **B3** | Skill Lift 评测(有/无技能配对) | P4 | harness 指标 | B1 评测 | 样本少噪声大 | 中 | -| **B4** | 失败技能隔离(quarantine)+ 回归用例跟随血缘 | P1 | ForgeAgent 式 | OKF | 状态机复杂 | 中高 | -| **B5** | near-match / soft_match 产品化默认开 | P6 | 已有 roadmap | okf-near | 误复用 | 低中 | -| **B6** | EKC preflight 默认硬门槛(REUSE→ADAPT→CREATE) | P6 | step 前强制 EFI | EKC | 拖慢探索 | 中 | -| **B7** | Capability 包与 `llm_free` 资源双向链接 | P2 | catalog L3↔任务包 | EKC+OKF | 图维护 | 中 | - -### C. 大模型 / 路由 / 成本 - -| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 | -|----|------|------|--------|------|------|------| -| **C1** | 步骤级路由(lookup / patch / sandbox_run / net) | P3 | 扩展 route policy 表 | routing | 策略过拟合 | 中 | -| **C2** | 总成本计量(含推理 token 膨胀)写回文档 | P7 | usage→writeback/metrics | llm result | 噪声 | 低中 | -| **C3** | 用强模型「反思」优化 standing / policy `.mq.md`(类 GEPA) | P3/P5 | 离线优化环,产物仍是文件 | llm | 需评测集 | 高 | -| **C4** | 高频 OKF 技能蒸馏/微调小模型(编译进权重) | — | 长期研究 | 数据+算力 | 运维重;偏离「源码权威」 | 很高 | -| **C5** | Named model 绑定任务类型(fast=路由,reasoning=分解) | P3 | 已有 named handles 加深 | llm | 配置漂移 | 低 | -| **C6** | Prompt document 强制:无参 ask 必须来自 type:prompt 文件 | P5 | 硬化 005 | llm | 破坏脚本式调用 | 低 | - -### D. 代码即文档(产出质量) - -| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 | -|----|------|------|--------|------|------|------| -| **D1** | 官方「可读 Marqdo」Skill 强化(表/链接取元/禁混名) | P5 | skills/marqdo 加厚 | skill | 模型仍违规 | 低 | -| **D2** | AST/结构 lint:json.set 链、混 EN/ZH API | P5 | `marqdo lint` 或 sandbox 钩子 | parser | 误报 | 中 | -| **D3** | 工作簿补丁只允许表驱动 / 命名槽写回 | P5 | 收紧 A0 补丁面 | agent | 表达力下降 | 中 | -| **D4** | 示例库:sandbox+OKF+表风格 canonical demos | P4/P5 | examples/ | 文档 | 维护 | 低 | - -### E. 评测与产品化 - -| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 | -|----|------|------|--------|------|------|------| -| **E1** | 完成 Wave B1 harness(constitution / writeback / call_site) | P4 | 已规划 | agent | — | 中 | -| **E2** | 指标面板:ReuseRate / ProofRate / TokenCost | P4/P7 | metrics 写回或 catalog | agent | 虚荣指标 | 中 | -| **E3** | Live 金样矩阵(sandbox 开/关 × 路由后端) | P4 | CI optional | CI | flaky | 中 | -| **E4** | 教程:「只读一份 .mq.md 理解 Agent」 | — | doc/tutorial | 文档 | — | 低 | - -### F. 明确不优先 / 需单独论证 - -| ID | 方向 | 理由 | -|----|------|------| -| **F1** | 第二套 Agent Framework(Python/TS 对象图权威) | 违宪 | -| **F2** | 向量库升为记忆权威 | 违宪;可作证据工具 | -| **F3** | 默认通用 shell Agent | 与 Marqdo-only 沙盒战略冲突 | -| **F4** | 整库 `ext/web` 进默认沙盒 | 已否决 | -| **F5** | 人人 microVM 本地默认 | DX 过重;留给 hosted | - ---- - -## 3. 执行顺序(O1→O5 locked) - -| 波次 | 方向组合 | 为何先做 | -|------|----------|----------| -| **O1** | A1 轻量(opt-in `sandbox=True`)+ A3 + D1 + D4 | 立刻接上刚落地的沙盒,风险可控 | -| **O2** | A2 + B1 + B3 + E1 | 验证→晋升→可度量 Skill Lift | -| **O3** | C1 + C2 + B6 | 降本与 EFI 硬门槛 | -| **O4** | A4 + D2 + A5 | 质量门禁与人审 | -| **O5** | B4 + C3 | 失败隔离与离线提示优化 | -| **O∞** | C4 / A6 | 研究项,单独立项 | - -切片实现见 [ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。 - ---- - -## 4. 验收原则(任一波次) - -- 金样:有/无沙盒、有/无 OKF hit、路由后端切换。 -- 指标:至少报告 ReuseRate 或 TokenCost 之一相对基线变化。 -- 文档:`.mq.md` 示例仍可读为 Markdown(表/链接取元,少 json 胶水)。 -- 红线:不改 `doc/next/*`;ext 不调 `host_*`。 - ---- - -## 5. 落地 - -O1–O5 已锁定;实现见 [roadmap/ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。**仍不改** `doc/next/*`。 diff --git a/doc/design/ext-ai-sandbox.md b/doc/design/ext-ai-sandbox.md deleted file mode 100755 index 4605e2b..0000000 --- a/doc/design/ext-ai-sandbox.md +++ /dev/null @@ -1,104 +0,0 @@ -# Official AI sandbox (`ext/ai/sandbox`) - -| | | -|---|---| -| Status | **Accepted · implementing** | -| Date | 2026-10-16 | -| Related | [research/ai-agent-sandbox.md](../research/ai-agent-sandbox.md) · [roadmap/ext-ai-sandbox.md](../roadmap/ext-ai-sandbox.md) · [ext-agent.md](ext-agent.md) · [ext-abi.md](ext-abi.md) · [browser-marqdo-wasm.md](browser-marqdo-wasm.md) · [ai-stack.md](../roadmap/ai-stack.md) · [stdlib-writeback.md](stdlib-writeback.md) | - ---- - -## 0. One-liner - -**Agent-only Marqdo trial runtime:** capability-isomorphic to browser Wasm defaults, CoW workspace until explicit `commit`, author surface under `ext/ai` (not stdlib). - ---- - -## 1. Goals / non-goals - -### Goals - -| # | Goal | -|---|------| -| G1 | Open a CoW session over a workspace root; edits stay in upper until `commit` | -| G2 | `run` executes `.mq.md` (or in-memory source) under deny-by-default caps with core `lib/*` usable | -| G3 | `diff` / `discard` / `inspect` for review gates | -| G4 | Stable `unavailable in sandbox` for plugin.load, exec foreign/subtask path|code|lang, net (default), `ext/web` server APIs | -| G5 | Author API in `ext/ai/sandbox` via `plugins/agent` — **no** public `lib/sandbox` | - -### Non-goals (this wave) - -| # | Non-goal | -|---|----------| -| N1 | Embed wasmtime in CLI | -| N2 | True Wasm ABI plugins (linalg/quantum) | -| N3 | bwrap / microVM | -| N4 | Full `ext/web` listen/DB/WS inside sandbox | -| N5 | Symlink-forest workspace isolation | -| N6 | Default host-proxy of all native ABI plugins | -| N7 | Wire `agent.step`/`plan` through sandbox automatically (later) | - ---- - -## 2. Layering - -```text -ext/ai/sandbox.mq.md → plugin.load agent → sandbox_* ABI - ↓ host_query - HostContext + CowSession - (fs / writeback see upper) -``` - -| Layer | May call `host_*` | Role | -|-------|-------------------|------| -| `ext/ai/sandbox` | **No** | Author facade | -| `plugins/agent` | via `host_query` only | Register `sandbox_*`; forward to host | -| `src/host` | — | CoW session store; fs/writeback intercept; nested `run` | - ---- - -## 3. Author API - -EN: `ext/ai/sandbox.mq.md` · ZH: `ext/ai/沙盒.mq.md` (separate files, no mixed names in one module). - -| Method | Params | Result | -|--------|--------|--------| -| `open` | optional `root=` (default entry dir / cwd) | map `{ id, root }` | -| `write` | `id=`, `path=`, `text=` | none | -| `read` | `id=`, `path=` | text | -| `remove` | `id=`, `path=` | none (whiteout) | -| `diff` | `id=` | list of `{ path, kind: write\|remove }` | -| `commit` | `id=` | `{ ok, applied }` | -| `discard` | `id=` | `{ ok }` | -| `run` | `id=`, `path=` **or** `source=` | `{ ok, value, stdout?, error? }` | -| `inspect` | `id=` | caps, root, change count, notes | - -Default `run` caps: `fs_write=true` (CoW only), `exec=false`, `net=false`, `plugin=false`. - ---- - -## 4. CoW semantics - -- **lower** = real workspace root (read-through). -- **upper** = session map path → bytes. -- **whiteout** = logical deletes; reads miss; commit unlinks lower. -- No symlink-as-isolation; resolve paths under root; reject `..` escape. -- Until `commit`, host tree unchanged (verifiable with `git status` / file mtime). - ---- - -## 5. Hard bans - -1. No public `lib/sandbox`. -2. No symlink forest as the isolation story. -3. No silent success when capability missing — diagnose `unavailable in sandbox`. -4. `ext/**` must not call `host_*`. -5. Do not treat empty `# main` as sandbox completeness. - ---- - -## 6. ABI / host_query - -Plugin exports (registered on agent plugin): `sandbox_open`, `sandbox_write`, `sandbox_read`, `sandbox_remove`, `sandbox_diff`, `sandbox_commit`, `sandbox_discard`, `sandbox_run`, `sandbox_inspect`. - -Implementation: each forwards to allowlisted `host_query` names of the same stem (e.g. `sandbox_open`), which mutate the process-local CoW store and (for `run`) invoke nested capture with a sandboxed `HostContext`. diff --git a/doc/design/ext-cdn.md b/doc/design/ext-cdn.md deleted file mode 100755 index 96c2019..0000000 --- a/doc/design/ext-cdn.md +++ /dev/null @@ -1,41 +0,0 @@ -# Extension CDN: native publication and byte parity - -This page describes storage. The executable tasks are in [the release entry](../../skills/marqdo-release/index.mq.md), [assets.mq.md](../../skills/marqdo-release/assets.mq.md) and [asset_io.mq.md](../../skills/marqdo-release/asset_io.mq.md). Read the source contracts before calling them. Version, mode and publication authorization come from the user; inspecting an existing release grants no new remote write. - -## Versioned packs - -Extension versions come from ext/VERSION and can advance independently of the interpreter. An extension release uses its own ext-vX.Y.Z tag and three packs. A full release also includes the CLI, source, WASM and editor deliverables listed in model.mq.md. - -| Object | Meaning | -|---|---| -| vX.Y.Z/marqdo-X.Y.Z-ext.zip | Readable extension sources | -| vX.Y.Z/marqdo-X.Y.Z-native-x86_64-pc-windows-msvc.zip | Windows plugins | -| vX.Y.Z/marqdo-X.Y.Z-native-x86_64-unknown-linux-gnu.zip | Linux plugins | -| vX.Y.Z/VERSION | Version echo for this pack set | -| latest/marqdo-X.Y.Z-*.zip | Identical current pack bytes | -| latest/VERSION | Recommended current extension version | - -Public reads use https://ext.marqdo.com. [src/ext_cli.rs](../../src/ext_cli.rs) is authoritative for client override variables, version resolution and download fallback order. Ordinary installation does not need storage credentials. - -## Callable publication - -After GitHub contains every required asset, download to dist/release-X.Y.Z. Validation checks names, GitHub size/SHA256, archive CRCs, versions and native capabilities. Source-declared plugins require matching libraries on both native platforms. Independently valid ZIPs cannot hide a missing DLL or shared library. - -Run from the checkout root with the version already chosen by the user; use the actual full or ext mode: -```sh -marqdo call skills/marqdo-release/assets.mq.md download 'version="X.Y.Z"' 'mode="ext"' --require-ok --effects plugin,net,fs.write --fs-root . --json -marqdo call skills/marqdo-release/assets.mq.md publish 'version="X.Y.Z"' 'mode="ext"' --require-ok --effects plugin,net,fs.write --fs-root . --json -marqdo call skills/marqdo-release/index.mq.md finish 'version="X.Y.Z"' 'mode="ext"' --require-ok --effects plugin,net,fs.write --fs-root . --json -``` - -Publication rechecks all three packs and their combined capability matrix before the first PUT. All three versioned ZIPs and three latest ZIPs are written before either VERSION pointer. A failed ZIP stops the sequence. Historical versions are retained. - -Finish reads both public pointers and compares downloaded versioned/latest bytes with GitHub SHA256 values. HTTP 200 or one sample URL is insufficient. Edge propagation may leave verification incomplete; repeat observation rather than rebuilding unrelated archives or claiming completion from an upload response. - -## Explicit boundaries - -Filesystem operations, hashing, public HTTP downloads, release decisions and upload order are Marqdo code. The engineering extension supplies bounded ZIP inspection and private R2 Signature V4 transport. No Python uploader is part of this path; older standalone scripts remain compatibility utilities. - -The native boundary resolves credentials privately from existing stores or environment. Missing credentials fail explicitly. Never put access keys or secrets in tool parameters, source or reports. A plugin grant has normal OS authority; --fs-root does not sandbox native plugins or child processes. - -Isolated loopback tests use fake credentials to verify ZIP-before-VERSION ordering and failure stops. Read-only verification of the published 2.6.0 release has also exercised the actual GitHub/CDN parity path without republishing its assets. diff --git a/doc/design/ext-cli.md b/doc/design/ext-cli.md deleted file mode 100755 index d7bcf2f..0000000 --- a/doc/design/ext-cli.md +++ /dev/null @@ -1,118 +0,0 @@ -# Official extension installer (`marqdo ext`) - -| | | -|---|---| -| Status | **Accepted (v0.3.5 prep)** — prebuilt native download | -| Date | 2026-09-04 | -| Related | [ext-llm.md](ext-llm.md) · [ext-agent.md](ext-agent.md) · [ext-abi.md](ext-abi.md) · [08-ext-deploy-coupling.md](ext-web-customization/08-ext-deploy-coupling.md) | - -## Commands - -```text -marqdo ext list -marqdo ext add llm -marqdo ext add agent -marqdo ext add web -marqdo ext remove llm -``` - -## Install root - -1. `MARQDO_EXT` if set -2. Else `~/.marqdo/ext` - -Imports use paths like `import llm:ext/ai/llm.mq.md` (see [`load.rs`](../../src/load.rs)). - -## Goal: no local Rust required - -End users who install Marqdo from **GitHub Releases** should run: - -```bash -marqdo ext add web -``` - -and get both L1 `.mq.md` **and** the matching native plugin (`.dll` / `.so`) **without** `cargo build`. - -### Resolution order (`add` with native crate) - -1. Local artifact (`MARQDO_*_PLUGIN`, `plugins/web/build` for **web**, `target/{debug,release}`, beside `marqdo`, `MARQDO_EXT_SOURCE/native`, …) -2. **Download** `marqdo-{VER}-native-{target}.zip` from the GitHub Release for this CLI version → cache under `~/.marqdo/cache/` -3. Local rebuild fallback: - - **web** → `./scripts/build-web-plugin.sh` (Go c-shared `libweb`; requires Go 1.22+ / cgo) - - other plugins → `cargo build -p marqdo_plugin_*` when Rust/`cargo` is available -4. Else fail with a clear message pointing at the Release assets - -L1 sources: - -1. `MARQDO_EXT_SOURCE` / repo `./ext` / beside binary -2. Else download `marqdo-{VER}-ext.zip` into `~/.marqdo/cache/ext-src-v{VER}/` - -### Env knobs - -| Variable | Meaning | -|----------|---------| -| `MARQDO_EXT_VERSION` | Override **extension pack** SemVer (default: CDN `latest/VERSION` → embedded `ext/VERSION` → CLI version) | -| `MARQDO_EXT_CDN` | Public CDN base (default `https://ext.marqdo.com`) | -| `MARQDO_EXT_NO_DOWNLOAD=1` | Never hit the network (CI / air-gap); local/cargo only | -| `MARQDO_EXT_DOWNLOAD_BASE` | Optional extra base tried **before** CDN | -| `MARQDO_WEB_PLUGIN` / `MARQDO_AGENT_PLUGIN` / `MARQDO_QUANTUM_PLUGIN` | Explicit native path | - -Download order for each Release asset: `MARQDO_EXT_DOWNLOAD_BASE` → **CDN `ext.marqdo.com`** → `github.com` → **`proxy.cflmy.top`**. Connect timeout 20s; read timeout 10min. - -See [ext-cdn.md](ext-cdn.md) for R2 layout, separate ext releases, and `scripts/upload-ext-r2.py`. - -Windows Release **zip** also ships `ext/` + `ext/native/*.dll` next to `marqdo.exe` so a portable unzip works offline after one download. - -## Source for `add` (developers) - -1. `MARQDO_EXT_SOURCE` — directory containing `ai/llm.mq.md` … -2. Else repo `./ext` near cwd / binary -3. Else Release `marqdo-*-ext.zip` (see above) - -## Layout (`ext/`) - -```text -ext/ - ai/ # llm + agent L1 - web/ - quantum/ -``` - -Installed tree (`~/.marqdo/ext` or `MARQDO_EXT`): - -```text -web/web.mq.md -web/网页.mq.md -native/libweb.so # or web.dll / libweb.dylib -web.plugin # absolute path hint -``` - -## Catalog - -| Id | Installs under `MARQDO_EXT` | -|----|-----------------------------| -| `llm` | `ai/llm.mq.md`, `ai/大模型.mq.md` | -| `agent` | `ai/agent.mq.md`, `ai/智能体.mq.md`, **native `agent`** | -| `web` | `web/index.mq.md` + facade/modules + `layout/` · `布局/` + `网页.mq.md`, **native `web`** | -| `quantum` | `quantum/`(含 `量子/` 中文树), **native `quantum`** | - -## Release assets (native) - -| Asset | Platform | -|-------|----------| -| `marqdo-VER-native-x86_64-pc-windows-msvc.zip` | Windows x64 (`native/*.dll`) | -| `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` | Linux x64 (`native/lib*.so`) | - -macOS: use local `cargo build` until CI adds Darwin natives (same zip naming pattern reserved). - -## Tests - -`tests/gold.rs`: `ext_cli_add_list_remove_llm`, `ext_cli_add_agent`, `ext_cli_add_web` (local build path; set `MARQDO_EXT_NO_DOWNLOAD=1` in sandboxes if needed). - -Unit: `ext_fetch` URL / triple tests. - -## Non-goals - -- Third-party registry -- Merging domain helpers into `lib/` -- Guaranteeing plugin **source** ABI stability (author `.mq.md` API is the contract) diff --git a/doc/design/ext-hosting-fill.md b/doc/design/ext-hosting-fill.md deleted file mode 100755 index 7829bc1..0000000 --- a/doc/design/ext-hosting-fill.md +++ /dev/null @@ -1,306 +0,0 @@ -# 设计:宿主集成缺口补齐(`ext/web` · `ext/ai`) - -| | | -|---|---| -| 状态 | **Accepted · H1–H4 stdio 已落地**(H4b HTTP 可选) | -| 日期 | 2026-09-07 | -| 缺口盘点 | [ext-hosting-gaps.md](../research/ext-hosting-gaps.md) | -| 路线图 | [ext-hosting.md](../roadmap/ext-hosting.md) | -| 边界 | [ext-web-net.md](ext-web-net.md) · [ext-abi.md](ext-abi.md) · [ext-agent.md](ext-agent.md) | -| 目标 | 用**扩展库一等 API**关闭 GAP-01–05,取代下游 Python 旁路 | - ---- - -## 0. 一句话 - -**服务器中继与「请求→`##`」进 `ext/web`;MCP Server 与 corpus 可发现进 `ext/ai`;标准库只保留已有客户端 SSE。** 作者用 GFM 表声明路由/工具,不写 JS、不启第二语言运行时。 - ---- - -## 1. 分层与禁止项 - -| 层 | 职责 | 落点 | -|----|------|------| -| 作者面 | 声明路径、上游、函数名、工具表 | `ext/web/web.mq.md` · `ext/ai/agent.mq.md`(+ 中文对偶) | -| ABI | axum 流式代理、每请求 interp 调用、MCP 传输 | `plugins/web` · `plugins/agent` | -| 标准库 | 不变:缓冲客户端 SSE / 解析 | `lib/net`(**不**加中继) | -| 核心 host | **禁止**新增 agent/web 领域 `host_*` | 见 Skill 硬规则 9 | - -**禁止:** - -1. 为中继在浏览器手写业务 JS。 -2. `json=` 继续塞「任意 `##`」语义(保持 DB-only;新能力用独立装配名)。 -3. MCP Server 把向量库升为权威真相(工具结果可带 `authority=workbook`)。 -4. 无白名单的「任意文件系统路径 + 任意 `##`」远程触发。 - ---- - -## 2. GAP-01 · `app.proxy` 流式反向代理 - -### 2.1 作者 API - -```markdown -*应用 = > `应用`.proxy path="/v1/chat/completions" upstream=$OPENAI_BASE_URL* -*应用 = > `应用`.proxy path="/llm/stream" upstream="https://api.example.com" strip_prefix="/llm" stream=True* -``` - -或装配表(一次挂多条): - -```markdown -*应用 = > `应用`.configure proxy=`代理表`* - -| path | upstream | stream | strip_prefix | headers_from_env | -|------|----------|--------|--------------|------------------| -| /proxy/chat | $OPENAI_BASE_URL | True | | OPENAI_API_KEY=Authorization | -``` - -| 参数 | 默认 | 含义 | -|------|------|------| -| `path` | 必填 | 浏览器同域路径 | -| `upstream` | 必填 | 上游根或完整 URL;支持 `$ENV` | -| `stream` | `True` | `True`:响应按上游 `Content-Type` 管道转发(含 `text/event-stream`) | -| `strip_prefix` | 空 | 转发前去掉本站前缀 | -| `methods` | `POST` | 允许方法 | -| `headers_from_env` | 空 | `ENV=Header-Name` 注入(密钥不进前端) | -| `timeout_ms` | 插件默认 | 上游超时 | - -中文:`## 代理` / `流式=` / `上游=` / `去前缀=`。 - -### 2.2 ABI / 插件行为 - -| 步骤 | 行为 | -|------|------| -| 注册 | `web_app_proxy` 写入 `AppState` 路由表 | -| 请求 | 读 body + 过滤危险 hop-by-hop 头;合并 env 注入头 | -| 上游 | `reqwest`/`hyper` 流式客户端(插件内,不进核心) | -| 响应 | 复制状态码与 `content-type`;`body` 为 stream;SSE 不整段缓冲 | -| CORS | 仍走既有 `configure cors=`(同域调用时浏览器不依赖上游 CORS) | - -### 2.3 与 `lib/net.http_post_sse` 关系 - -| API | 角色 | -|-----|------| -| `http_post_sse` | **出站消费者**(CLI/agent 侧收齐 events) | -| `app.proxy` | **入站中继**(浏览器 ← Marqdo ← 上游) | - -二者互补,不互相替代。 - -### 2.4 验收 - -- 金样:mock 上游发两帧 SSE,浏览器侧(或 `curl -N`)收到两帧且中间无全缓冲延迟门槛。 -- 密钥仅出现在服务端 env 注入头。 -- 金样名建议:`tests/ext/web-proxy-sse-smoke.mq.md`。 - ---- - -## 3. GAP-02 · `app.invoke` / `configure invoke=`(HTTP → `##`) - -### 3.1 作者 API - -```markdown -*应用 = > `应用`.invoke path="/api/沉淀" method=POST fn="run.沉淀"* -``` - -表形式: - -```markdown -*应用 = > `应用`.configure invoke=`调用表`* - -| path | method | fn | body | return | -|------|--------|-----|------|--------| -| /api/note | POST | run.写出 | json | json | -| /api/search | GET | db.recent | query | json | -``` - -| 列 / 参数 | 含义 | -|-----------|------| -| `path` / `method` | HTTP 路由 | -| `fn` | `库.成员`(入口模块已 `import`)或 `模块路径##标题`(白名单前缀内) | -| `body` | `json` \| `form` \| `query` \| `raw` → 映射到 `##` 形参(同名优先;其余进 `payload` 袋) | -| `return` | `json`(默认)\| `text` \| `status` | - -中文:`## 调用` / `函数=` / `正文=` / `返回=`。 - -### 3.2 安全默认(锁定) - -1. **仅**解析入口 workbook 已导入的 `bind` 路径,或 `invoke_allow=` 显式前缀列表。 -2. 单请求超时 + 可选并发上限(防 listen 线程饿死)。 -3. 默认不启;作者显式 `invoke` / `configure invoke=`。 -4. 错误:`{ok:false, error}` + HTTP 4xx/5xx;不把内部路径栈默认回传生产模式。 - -### 3.3 ABI / 插件行为 - -| 步骤 | 行为 | -|------|------| -| 注册 | `web_app_invoke` 存 `(path, method, FnRef)` | -| 命中 | 解析 body → Value 袋;`call_lib_path` / 等价「同步调用已加载模块的 `##`」 | -| 返回 | Value → JSON(复用现有 host JSON 通路);侧效(写盘)在同一解释器事务语义内尽最大努力 | - -**不**把 `json=` DB 路由改语义;`invoke` 是平行装配。 - -### 3.4 与 compose 期 `call_lib_path` 关系 - -| 时机 | API | -|------|-----| -| 装配页 | 现有 compose / `call_lib_path` | -| **每个 HTTP 请求** | 本设计 `invoke` | - -### 3.5 验收 - -- `POST` JSON → 用户 `##` 写入临时文件 + 返回 `{ok:true,…}`。 -- 未导入路径 → 4xx,不执行。 -- 金样:`tests/ext/web-invoke-smoke.mq.md`。 - ---- - -## 4. GAP-03 · MCP Server(`ext/ai`) - -### 4.1 作者 API - -```markdown -*服务 = > agent.mcp_server name="marqdo-qd"* -*服务 = > `服务`.tool name="qd_search" fn="求道.搜索" description="关键词检索"* -*服务 = > `服务`.tool name="qd_capture" fn="求道.捕捉"* -*服务 = > `服务`.serve transport=stdio* -# 或 -*服务 = > `服务`.serve transport=http host=127.0.0.1 port=7433* -``` - -工具表: - -| name | fn | description | -|------|-----|-------------| -| qd_search | 求道.搜索 | … | -| qd_list | 求道.列出 | … | - -### 4.2 传输 - -| transport | 用途 | -|-----------|------| -| `stdio` | Cursor / Claude Desktop 拉起 | -| `http` | Streamable HTTP(与官方 MCP 演进对齐;首版可先 SSE+POST 子集) | - -### 4.3 与 A4 fixture 客户端关系 - -| API | 方向 | -|-----|------| -| `mcp_list_tools` / `mcp_call` | **出站**(Agent 调外部 MCP;现 fixture) | -| `mcp_server` + `serve` | **入站**(外部调 Marqdo) | - -客户端「真 MCP」仍见 agent 缺口文;本设计先交 Server,fixture 可保留测客户端。 - -### 4.4 ABI - -- `plugins/agent`:`agent_mcp_server_*`(注册工具、stdio loop、可选 HTTP)。 -- 工具实现:复用 GAP-02 同款「调用 `##`」内核(可抽共享 `invoke_fn`),避免两套分发。 -- 返回包装:可含 `authority=workbook`。 - -### 4.5 验收 - -- 金样:stdio 夹具发 `tools/list` + `tools/call`,断言 JSON-RPC 形结果。 -- 可选:`tests/ext/agent-mcp-server-smoke.mq.md`。 - ---- - -## 5. GAP-04 · 同寿副端口 - -### 5.1 关闭策略(优先) - -GAP-01 + GAP-02 挂在**同一** `app.listen` → **不实现副端口**,文档宣布 GAP-04 关闭。 - -### 5.2 备选 API(仅当必须隔离) - -```markdown -*应用 = > `应用`.listen host=127.0.0.1 port=18081 also_port=7432 also_routes=`中继表`* -``` - -`also_routes` 仅允许 `proxy` / `invoke` 已注册子集。实现成本高,**默认不做**。 - ---- - -## 6. GAP-05 · 跨模块 `db` 与 corpus 可发现 - -### 6.1 `db` 句柄(扩展约定 + 运行时) - -**作者约定(立即文档化):** - -1. 跨模块优先传 **`url` 字符串**,调用方 `*store = > web.db url=…*` 再 `select`。 -2. 若传对象:必须保留 `_type` 为插件注册名(与 `web.db` 构造一致)。 - -**运行时修补(H 波次):** - -| 选项 | 做法 | 选用 | -|------|------|------| -| A | 跨模块返回插件对象时规范 `_type` + 全局方法表查找 | **首选**(一次修好所有插件对象) | -| B | `db.open` 只返回 `{url}` 朴素 map,禁止「裸 select」跨文件 | 文档契约;体验较差 | - -金样:模块 A `open` → 返回 → 模块 B `select` 成功。 -`tests/ext/web-db-cross-module-smoke.mq.md`。 - -### 6.2 `corpus_search` 可发现 - -```markdown -## corpus_search -+ `query` -+ `root`=".marqdo/agent-kb" - -* > plugin.load name=agent * -** > agent_corpus_search query=`query` root=`root` ** -``` - -或在 `# agent` / `## corpus_search` 入口统一 `ensure_plugin`(与现 `agent` 构造对齐),保证 **纯 `marqdo run` + import agent** 即可用。 - -**不**把 `agent_corpus_search` 搬进 `src/host/`。 - -### 6.3 验收 - -- 无显式手工 ABI 名的情况下,`marqdo run` 金样调用 `agent.corpus_search` 成功。 -- 跨模块 `db.select` 金样绿。 - ---- - -## 7. 扩展库表面清单(落地时改这些文件) - -| 文件 | 增补 | -|------|------| -| `ext/web/web.mq.md` · `网页.mq.md` | `## proxy` / `## invoke`;`configure` 增 `proxy`/`invoke` 列 | -| `plugins/web/src/http.rs` · `middleware.rs` · 新 `proxy.rs` / `invoke.rs` | 路由注册与流式/调用 | -| `ext/ai/agent.mq.md` · `智能体.mq.md` | `# mcp_server` · `## tool` · `## serve`;`corpus_search` ensure_plugin | -| `plugins/agent/` | MCP Server 传输 + 共享 invoke | -| `tests/ext/web-proxy-sse-smoke.mq.md` 等 | 见上 | -| `doc/roadmap/ext-web.md` | 链到 H 波次(不重开 W0–W7) | -| `public/` / Skill | 发版时补「同域 LLM 代理 / HTTP 调用 ##」短节 | - -**不**新增 `lib/run` 作为核心依赖:用户业务 `##` 仍在其自己的 `lib/*.mq.md`;Marqdo 只提供 **invoke 管道**。 - ---- - -## 8. 迁移:下游旁路 → 扩展 API - -| 旁路(下游) | 替换为 | -|--------------|--------| -| `llm_proxy.py` `/proxy/stream` | `app.proxy` / `configure proxy=` | -| `llm_proxy.py` `/store/*` + `marqdo run` | `app.invoke` → 用户 `##` | -| `mq_bridge.py` 仅过滤 | 用户 `##` 内 `table`/`re` 过滤,或修复后的 `corpus_search` | -| `qdagent_mcp.py` | `agent.mcp_server` + `serve` | -| `mq.sh` 双进程 | 单 `marqdo run index.mq.md`(proxy+invoke 同端口) | - ---- - -## 9. 开放点(实现前拍板) - -| # | 问题 | 默认倾向 | -|---|------|----------| -| 1 | `invoke` 的 `fn` 是否允许 `path.mq.md##标题` 字面量 | 允许但必须 `invoke_allow` 前缀 | -| 2 | MCP HTTP 首版范围 | stdio 先交;HTTP 跟一波 | -| 3 | 代理是否缓冲「非 SSE」大 body | 非流式可限长缓冲;SSE 禁止整段缓冲 | -| 4 | GAP-05 选项 A vs B | **A** | - ---- - -## 10. 完成定义(整包) - -1. 无 Python 旁路即可:浏览器同域 SSE 对话 + HTTP 触发沉淀 `##` +(可选)MCP stdio 暴露同一批 `##`。 -2. 金样覆盖 proxy / invoke / cross-db / corpus / mcp-server(stdio)。 -3. `doc/research/ext-hosting-gaps.md` 各 GAP 标为关闭或降级为「备选副端口不做」。 -4. 发版说明指向 `ext/web` · `ext/ai` 新作者面,不指向 `scripts/*.py`。 diff --git a/doc/design/ext-index-skill-tools.md b/doc/design/ext-index-skill-tools.md deleted file mode 100755 index a4f8b4c..0000000 --- a/doc/design/ext-index-skill-tools.md +++ /dev/null @@ -1,91 +0,0 @@ -# 扩展库:index 即代码 · 文档 · SKILL · tools - -| | | -|---|---| -| 状态 | **Active**(契约卡;完整开发范式见下行) | -| 日期 | 2026-11-06 | -| 愿景 | [doc/next/012.md](../next/012.md)(手写真相源,本文不修改它) | -| 范式长文 | [ext-skill-tools-paradigm.md](ext-skill-tools-paradigm.md)(布局、陷阱、验收清单、推广顺序) | -| 试点 | `ext/quantum/`;[手册闭环与当前契约位置修正](ext-quantum-handbook.md) | -| 相关 | [ext-abi.md](ext-abi.md) · [ext-quantum.md](ext-quantum.md) · [lib-code-as-docs.md](lib-code-as-docs.md) · [function-as-table-semantics.md](function-as-table-semantics.md) | - ---- - -## 0. 一句话 - -扩展包里**每一份** `.mq.md` 同时是可执行代码、可读 SKILL、以及可 `marqdo call` 的 tools 面;**函数即工具**,`###` 即子工具;禁止第二套 catalog / OpenAPI 真相源。开发新包或迁包时以 [ext-skill-tools-paradigm.md](ext-skill-tools-paradigm.md) 的验收清单为准。 - ---- - -## 1. 整包统一作者契约(无例外) - -适用于包内全部 `.mq.md`(含 `index`、子依赖、`_capability`、兼容层、中英镜像): - -| 要求 | 含义 | -|------|------| -| 代码 | 标记可执行;实现可薄委托 ABI / 兄弟模块 | -| SKILL | `#` 下写清领域、何时用、**For AI agents → `marqdo call` 本文件** | -| tools | `##` / `###` 即工具树;无旁路 schema | -| 版式 | **形参契约表紧贴标题下**;**返回契约表也在首条执行语句之前**(当前解析器只在此提取契约) | -| 叙述 | 每个函数单元叙述占比 **≥ 50%**;公式与约定写进人话 | -| 禁止 | `+` 清单当主表面;ABI 名罗列充文档;「内部文件免检」 | - -形参仍由叙述/体中的 `` `名` `` 推断 arity;`| 参数 | 类型 | 说明 |` 为契约表(见 `tests/contracts/`)。 - ---- - -## 2. 包布局(quantum 试点) - -```text -ext/quantum/ - index.mq.md # EN 根 SKILL:无上下文也能照抄 marqdo call - circuit/index.mq.md # call 工具 + 作者 # circuit - gate/ · simulate/ · state/ · density/ · viz/ - _capability/index.mq.md - 量子/ # ZH 同包(勿再把 量子/ 抬到 ext/ 顶层) - 索引.mq.md - 电路/ · 门/ · 模拟/ · 态/ · 密度/ · 可视化/ · 能力/ -``` - -`index` = 总图与编排,必须写明 FILE/FUNCTION/`--effects plugin`;每个子目录的 `index.mq.md` 单独拿到也要能执行。无单独「兼容层」文件。 - ---- - -## 3. `marqdo call` 与会话 - -```text -marqdo call [k=v…] - [--json] [--backend tree|bytecode] - [--effects none|plugin] # 默认 none - [--session ] - [--toget ] # 或尾部 toget -``` - -- 默认:仅纯函数(今日行为)。 -- `--effects plugin`:允许 `plugin.call`(及附属的 `output.write`);仍拒绝 fs.write / network / process.exec / llm 等。 -- `toget` + `--session`:绑定写入 `.marqdo/call-sessions/.json`;参数 `$name` 引用会话值;跨进程 **plugin 句柄经 journal 重放** 重建。 -- 嵌套子工具:`parent.child`(`###` 路径)。 - -值字面量:整数/小数/引号文本/True|False|None;以 `[` / `{` 开头时按 JSON 解析为 List/Map。 - ---- - -## 4. 叙述 ≥ 50% - -`marqdo check --narrative-ratio`(及 `lib/lint/narrative.mq.md` skill)按函数单元统计叙述字符占比;`ext/quantum/**/*.mq.md` **全量零豁免**。 - ---- - -## 5. 与 ADR 0007 - -作者程序与业务路径仍不写 `ensure_plugin` / `host_*`;插件经 `_capability` / facade 加载。Agent 用 `--effects plugin` 调用 facade,不把 capability 当日常工具(文件本身仍须达标 skill)。 - ---- - -## 6. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-11-06 | 初稿:012 试点契约、call effects/toget、quantum 模块树 | -| 2026-11-06 | quantum 中文树收进 `ext/quantum/量子/`;根 skill 增加「选哪条路」;`ext add` 拒绝装进源码树 | -| 2026-11-06 | 链到 [ext-skill-tools-paradigm.md](ext-skill-tools-paradigm.md) 作为开发范式长文 | diff --git a/doc/design/ext-linalg-formula-doc.md b/doc/design/ext-linalg-formula-doc.md deleted file mode 100755 index 61ff3fd..0000000 --- a/doc/design/ext-linalg-formula-doc.md +++ /dev/null @@ -1,236 +0,0 @@ -# `ext/linalg` — 公式文档面(跑通即正确) - -| | | -|---|---| -| 状态 | **Draft · 锁定作者面哲学与分期** | -| 日期 | 2026-09-07 | -| 父设计 | [ext-linalg.md](ext-linalg.md) | -| 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) | -| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) | -| 对照 | [stdlib-math.md](stdlib-math.md)(高中标量公式) | - ---- - -## 0. 一句话 - -**`.mq.md` 里的线性代数应当读起来像一份可运行的公式讲义**:式子能跑通,就在库承诺的规则与维数下代表正确;`lib/math` 守高中边界,大学符号矩阵与更深层计算由 **`ext/linalg` 正当承担**。 - ---- - -## 1. 产品哲学 - -### 1.1 与 Marqdo 总原则对齐 - -| Marqdo | 在线性代数上的含义 | -|--------|-------------------| -| 代码即文档 | 矩阵代数段落用数学式书写,而不是 API 调用清单 | -| 标记即语法 | `$$`、中缀、`# matrix` 方法都是可读标记,不是「库胶水」 | -| 跑通可验收 | 金样 / 课堂作业:文件 exit 0 + 断言化简结果 = 式子合法 | - -### 1.2 「跑通即正确」的精确定义 - -**不是**「任意高深定理自动证明」。 -**是**在声明的能力边界内,下列任一成立则文档该段视为正确: - -1. **形状层**:不相容维数的乘加在构造时硬错误(写不出可运行的坏式)。 -2. **恒等式层**:文档断言的规范形(如 `(AB)^\top → B^\top A^\top`)经规则集得到。 -3. **数值核对层**(可选):小 `$$` 数值阵 `explicit` 后与手算一致——验算,不是符号证明。 - -更高深主题(矩阵微积分、表示、特殊函数矩阵等)通过**扩展同一公式面的规则表**分期加入,而不是另起一套函数库叙事。 - -### 1.3 与 `lib/math` 的边界(再次锁定) - -| | `lib/math` | `ext/linalg` | -|--|------------|--------------| -| 教育边界 | 高中标量公式 | 大学经典线性代数及更深(官方 ext) | -| 值类型 | `Value::Formula`(标量 AST) | `_type=matrix` / `矩阵`(MatExpr + 稠密) | -| 作者感觉 | `$$sin(x)+x$$` + `diff` / `plot` | `A*B`、`(AB)^T`、分块、分解图 | -| 是否「数学库」 | 是(stdlib) | **是数学库的官方扩展**,不是旁路工具箱 | - -把大学 LA 塞进 `lib/math` ❌;在 `ext/linalg` 做大学符号计算乃至更深 ✅。 - ---- - -## 2. 两面模型:代数面 vs 计算面 - -文档里应能一眼分清「推导」与「动手算」。 - -### 2.1 代数面(默认;公式文档) - -| 意图 | 写法(目标) | 语义 | -|------|--------------|------| -| 引入符号阵 | 见 §3 | 惰性 `MatrixSymbol` | -| 加减乘 | `` `C` = `A` + `B` `` · `` `P` = `A` * `B` `` | 建树 + 形状检查 | -| 转置 / 逆 | `` `At` = > `A`.T `` · `` `Ai` = > `A`.inv `` | 惰性节点 | -| 化简 / 展示 | 见 §4(默认化简策略) | 规则不动点 → ASCII / KaTeX | -| 分块 / Kronecker | 表或 `block` / `kron`(可保留具名,但结果仍是公式) | 惰性 | - -**读者感受**:像在抄黑板,而不是在调 `la.mul`。 - -### 2.2 计算面(显式步骤;可单独成段) - -| 意图 | 写法 | 语义 | -|------|------|------| -| 稠密求值 | `` `E` = > `A`.explicit `` / `la.explicit` | 展开数值 | -| 分解 | `` `f` = > la.factorize matrix=`A` kind="svd" `` | `linalg_factor` | -| 求解 / 最小二乘 | `solve` / `lstsq` | 数值解 | -| 度量 | `norm` / `cond` / `rank` / `det`(数值路径) | 标量或条件对象 | -| 作图 | `draw` / `show` | SVG / 公式卡 | - -**读者感受**:「于是我们计算 / 画出…」——与纯代数叙述分段书写。 - ---- - -## 3. 目标作者语法(公式文档优先) - -### 3.1 已落地(v1 中缀 / 方法) - -```markdown -*`A` = > la.symbol name="A" rows=2 cols=2* -*`B` = > la.symbol name="B" rows=2 cols=2* -*`C` = `A` + `B`* -*`P` = `A` * `B`* -*`Pt` = > `P`.T* -*`s` = > `Pt`.simplify* -*`t` = > `s`.ascii* -``` - -数值 `$$` 矩阵可直接参与 `+` / `*`(经插件吸收为稠密叶)。 - -### 3.2 目标形态(文档感更强;分期实现) - -**叙事理想(不必一次做完):** - -```markdown -# 正规方程 - -令 \(A\) 为 \(m\times n\) 设计矩阵,\(b\) 为观测。 - -*`AtA` = > `A`.T * `A`* # 或未来更紧凑的 postfix / 混合写法 -*`xty` = > `A`.T * `b`* -*`xhat` = > `AtA`.solve b=`xty`* # 计算面 -``` - -**符号引入(减少 `la.symbol` 噪音)——候选(F2 选定一种):** - -| 候选 | 例 | 利 | 弊 | -|------|----|----|-----| -| A. 构造糖 | `` `A` = > la.matrix name=A rows=m cols=n `` | 已有 `# matrix` | 仍是调用 | -| B. 维数表 | GFM 表声明符号与形状,一行绑定 | 很「文档」 | 需新约定 | -| C. `$$` 符号方言 | `$$A_{m\times n}$$` → MatExpr | 最像讲义 | 解析歧义;勿污染标量 formula | -| D. 保持 `symbol` + 短别名 | `` `A` = > la.A rows=m cols=n `` | 实现便宜 | 文档感一般 | - -**锁定倾向:** 短期 **A + 默认化简(F1)**;**F2 采用 B(GFM `@` 表 + `la.declare`)**;受限 C(`$$` 符号方言)仍待评估且不得污染核心 formula。 - -### 3.3 明确不做(本波语法) - -- 把符号 MatExpr 塞进核心 `formula::Expr` -- 发明与 Markdown 列表冲突的行首 `+` 矩阵语法 -- 用未定义的 `$$矩阵A$$` 伪方言冒充已实现语义 - ---- - -## 4. 默认化简与「写出即规范」 - -### 4.1 策略 - -| 操作 | 是否自动 `simplify` | 理由 | -|------|---------------------|------| -| `ascii` / `latex` / `show` | **是(F1 done)** | 展示面应接近讲义规范形;`raw=True` 可关 | -| 中缀 `+` `*` `-` 的构造结果 | **否** | 保留用户书写结构;需要时再化简 | -| `.simplify` | 显式不动点 | 文档断言 / 金样 | -| `explicit` 前 | 可选先 simplify(F1.1) | 减少无效稠密路径 | - -### 4.2 验收句式(金样) - -```markdown -*`P` = `A` * `B`* -*`Pt` = > `P`.T* -*`t` = > `Pt`.ascii* # F1:无需再 .simplify 即得 B^T*A^T -1. `t` == "B^T*A^T" - > print text=ok -``` - -「跑通 + 断言」= 这段公式文档正确。 - ---- - -## 5. 正确性分层与错误体验 - -| 层 | 失败时 | 作者应看到 | -|----|--------|------------| -| 形状 | `A*B` 列行不配 | 含双方 shape 的硬错误,指向调用点 | -| 规则 | 无法化到文档期望形 | 金样失败;或 `ascii` 仍为未化简形(需补规则) | -| 插件未加载 | 中缀矩阵运算 | 提示 `ext add linalg` / `ensure_plugin` | -| 超维 | `explicit` / 分解 | 护栏错误,建议保持符号 | - ---- - -## 6. 与实现现状的对照 - -| 能力 | 状态 | -|------|------| -| MatExpr 惰性树 + R1–R5 / 分块 / kron | done(L1–L3) | -| 稠密 / 分解 / 度量 / draw theme | done(L2–L6) | -| 中缀 `+` `-` `*` + `# matrix` 方法 | done(v1) | -| `ascii`/`latex`/`show` 默认 simplify | **done(F1)** | -| 更少噪音的符号引入 | **done(F2:`declare` + 表)** | -| 更紧凑转置 / 混合公式书写 | **done(F3:`T_ascii`)** | -| `explicit` 前可选 auto-simplify | **done(F3,默认开)** | -| public「如何写公式文档」 | **done(F3)** | -| 矩阵微积分等 | L7+ / 规则表扩展 | - ---- - -## 7. 分期(公式文档面) - -| 阶段 | 内容 | 出口 | -|------|------|------| -| **F1** | 展示路径默认 simplify;金样「`.T` + `ascii` → 规范形」;设计本文落地 | **done** | -| **F2** | 符号引入降噪(选定 §3.2 候选);更新 examples 使其读起来像讲义 | **done**(`declare` + `linalg-transpose`) | -| **F3** | 可选 postfix / 链式糖;`explicit` 前可选 auto-simplify;public 短文「如何写公式文档」 | **done** | -| **F4+** | 新规则(伴随、多项式矩阵…);矩阵微积分仅当明确需要 | 规则表可测 | - ---- - -## 8. 示例叙事(目标文档骨架) - -````markdown ---- -import: - la: ext/linalg/linalg.mq.md ---- - -# 转置反序 - -*`A` = > la.symbol name="A" rows=2 cols=3* -*`B` = > la.symbol name="B" rows=3 cols=2* -*`P` = `A` * `B`* -*`Pt` = > `P`.T* - -叙述:\((AB)^\top = B^\top A^\top\)。 - -*`t` = > `Pt`.ascii* -1. `t` == "B^T*A^T" - > print text=identity-ok -2. * - > print text=identity-fail -```` - -计算面示例保持 `examples/linalg-least-squares/`(`lstsq` + heatmap),与代数面示例分目录或分章节。 - ---- - -## 9. 开放问题 - -1. **自动 simplify 是否改变 `ascii` 金样**——凡依赖「未化简乘积串」的测试需改期望或改调 `repr_raw`(若提供)。 -2. **中文 `_type=矩阵` 与展示**——方法链已 retag;view 是否统一显示英文 kind。 -3. **`$$` 符号方言**——若做,必须经 `from_formula` 扩展,禁止改核心高中 formula 语义。 - ---- - -## 10. 收束 - -`ext/linalg` 的北极星不是「功能最多的矩阵库」,而是: - -> **让大学线性代数(及更深)以可运行公式文档的形式存在于 Marqdo;跑通即在规则集内正确;计算与作图是显式步骤,不淹没代数叙述。** diff --git a/doc/design/ext-linalg.md b/doc/design/ext-linalg.md deleted file mode 100755 index dcd557a..0000000 --- a/doc/design/ext-linalg.md +++ /dev/null @@ -1,346 +0,0 @@ -# `ext/linalg` — 公式优先的线性代数扩展 - -| | | -|---|---| -| 状态 | **Draft · L0–L6 + 中缀 v1 · 公式文档面见专文** | -| 日期 | 2026-09-07 | -| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) | -| **公式文档面** | [ext-linalg-formula-doc.md](ext-linalg-formula-doc.md)(跑通即正确 · 代数面/计算面) | -| 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) | -| 相关 | [stdlib-math.md](stdlib-math.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [view.md](view.md) · [ext-quantum-q7.md](ext-quantum-q7.md) | -| 安装(规划) | `marqdo ext add linalg`(`linalg` / `线性代数`) | - ---- - -## 0. 一句话 - -**经典线性代数以「矩阵公式」为一等公民**:抽象表达式可化简、可展示、可选求值;稠密数值与分解图走 ABI 插件——**不**并入 `lib/math`,**不**挂在 `ext/quantum` 作者面。 - -作者面北极星见 **[ext-linalg-formula-doc.md](ext-linalg-formula-doc.md)**:跑通即正确;代数面像讲义,计算面是显式步骤。 - ---- - -## 1. 目标与非目标 - -### 1.1 目标 - -1. **公式类扩展**:在现有标量 `formula` 之上,引入 **矩阵表达式(MatExpr)**——`MatrixSymbol`、乘加、转置、逆、迹、行列式、分块、Kronecker——默认**不展开**。 -2. **大规模优化**:形状检查 + 重写规则 + 惰性求值 + 分解对象复用(见 §5)。 -3. **易于展示**:KaTeX 公式卡、结构 SVG(SVD/QR/消元/特征)、数值热力图;CLI 可断言的 ASCII。 -4. **文档即实验**:GFM 表声明矩阵 / 步骤;`.mq.md` 可读可跑。 - -### 1.2 非目标(首版) - -| 不做 | 原因 | -|------|------| -| 塞进 `lib/math` | 高中标量范围已锁定;大学 LA 属官方 ext | -| 复用 `quantum.*` 作者 API | 领域混淆;量子 Q7 保持量子语义 | -| 完整 SymPy / Mathematica | 规则表可控子集即可 | -| 稀疏格式 / GPU / 分布式 | 超出文档语言定位 | -| 矩阵微积分闭式(Jacobian 积木) | 记入路线图远期 | -| 在 `ext/**` 调 `host_*` | 硬约束;数值走插件名 | - ---- - -## 2. 分层架构 - -```text -作者 .mq.md - │ import la:ext/linalg/linalg.mq.md - ▼ -L1 官方 ext(GFM + ## 包装,中英分文件) - │ plugin.load name=linalg - ▼ -plugins/linalg(ABI v2) - ├── matexpr:符号树构造 / 重写 / latex - ├── dense:稠密 f64(可选复数)运算与分解 - └── draw:结构 SVG / heatmap - │ - ▼(可选) -核心 Value::Formula 仅保留「数值矩阵字面量」现状; -符号 MatExpr 以 **map `_type=matrix`(中文构造为 `矩阵`)** 承载,避免撑爆高中 formula AST;遗留标签 `linalg_expr` / `linalg_dense` 仍可解析。 -``` - -### 2.1 为何 MatExpr 不直接塞进 `formula::Expr` - -| 方案 | 利 | 弊 | 决策 | -|------|----|----|------| -| 扩展 `formula::Expr` | 与 `$$` 一体 | 核心膨胀;高中/大学边界糊 | ❌ | -| 插件侧表达式 + L1 对象 | 核心干净;可独立发版 | 需稳定 `_type` 与 latex 桥 | ✅ **采用** | -| 仅 list-of-list 数值 | 简单 | 无法公式优化与符号展示 | ❌ 仅作 `explicit` 结果 | - -**既有** `formula::Expr::Matrix`(数值 `$$`)继续服务量子门 / 小例子;`ext/linalg` 通过 `la.matrix` / `la.from_formula` 吸收为稠密叶子。 - -### 2.2 与量子的边界 - -| | `ext/linalg` | `ext/quantum` Q7 | -|--|--------------|------------------| -| 域 | 经典实/复矩阵 | 态 / 密度 / Pauli | -| Kronecker | 经典 ⊗ | 复合量子系统 | -| 图 | SVD/QR/GE/heatmap | hinton/city/qsphere/… | -| 复用 | 插件**私有**可共享 Jacobi/SVD 代码 | 作者面 API **分离** | - ---- - -## 3. 运行时对象(锁定草案) - -全部经插件构造,L1 返回 **map**(`_type` 稳定,金样可断言): - -| `_type`(英) | 中文标签 | 字段(最小) | 含义 | -|---------------|----------|--------------|------| -| `linalg_expr` | `线性式` | `repr`(S-expr 或内部 id)、`shape`=`[m,n]` 或符号维、`latex`、`ascii` | 抽象矩阵公式 | -| `linalg_dense` | `稠密阵` | `rows`, `cols`, `data`(行主 list[list])、`dtype`=`real`\|`complex` | 显式数值 | -| `linalg_factor` | `分解` | `kind`=`lu`\|`qr`\|`svd`\|`eig`\|`chol`,因子字段,`latex`,可选 `svg` | 分解结果 | -| `linalg_svg` | — | `kind`, `svg` 文本 | 与 quantum_svg 同构展示约定 | -| `linalg_solve` | `求解` | `x`, `residual`, `method` | 线性系 / 最小二乘 | - -形状:`shape` 允许整数或符号维名(字符串 `"n"`);不相容 → 硬错误。 - ---- - -## 4. 作者面 API(英文 `ext/linalg/linalg.mq.md`) - -中文镜像:`ext/linalg/线性代数.mq.md`(`矩阵` / `化简` / `求值` / `绘图`…)。 - -### 4.1 构造 - -```markdown -# matrix - -## symbol - + `name` - + `rows` - + `cols` -# → linalg_expr MatrixSymbol - -## eye / zeros / ones / diag - + … - -## from_list - + `data` # list[list] 或 table - -## from_formula - + `formula` # 吸收 Value::Formula Matrix 字面量 - -## block - + `blocks` # 表或嵌套 list of expr -``` - -文档写法偏好: - -````markdown -`A` = > la.symbol name=A rows=n cols=n - -`b` = -$$ -\begin{pmatrix}1\\0\\0\end{pmatrix} -$$ - -*`b` = > la.from_formula formula=`b` * -```` - -作者面优先顶层 `la.symbol` / `la.mul`(`la.matrix.symbol` 无接收者会硬错误,见 [module-namespace.md](module-namespace.md) §4.3)。 -### 4.2 公式代数(返回 `linalg_expr`,惰性) - -| 英文 | 中文 | 语义 | -|------|------|------| -| `mul` / `add` / `sub` | `乘` / `加` / `减` | 形状检查后建树 | -| `transpose` / `T` | `转置` | | -| `inv` | `逆` | 符号逆;不立即求数值 | -| `pow` | `幂` | 整数幂 | -| `trace` / `det` | `迹` / `行列式` | 可得到标量 expr 或数值 | -| `kron` | `克罗内克` | **禁止**默认 expand | -| `simplify` | `化简` | 应用 §5 规则集 | -| `collapse` | `分块化简` | 对标 `block_collapse` | -| `latex` / `ascii` | `乳胶` / `文本` | 展示字符串 | -| `shape` | `形状` | | - -链式 / 中缀(v1 已落地): - -```markdown -*`C` = `A` + `B`* -*`P` = `A` * `B`* -*`Pt` = > `P`.T* -*`s` = > `Pt`.simplify* -``` - -运行时对双方为 `matrix` / `矩阵` / 数值 `$$` 矩阵 / 遗留 `linalg_expr` 的 `+` `-` `*` 分派到插件;结果保留左操作数 `_type` 以便中英方法链。 -### 4.3 求值与分解(热路径 → 稠密) - -| 英文 | 说明 | -|------|------| -| `eval` / `explicit` | 符号树 + 绑定表 → `linalg_dense`;超维硬错误 | -| `factorize` | `kind=lu\|qr\|svd\|eig\|chol` → `linalg_factor` | -| `solve` | `A`,`b`;或 `factor` + `b` | -| `lstsq` | 最小二乘 | -| `rank` / `norm` / `cond` | 数值度量 | -| `matmul` | 稠密乘(已 explicit 时) | - -维数上限(草案,可配置): - -| 操作 | 默认上限 | -|------|----------| -| `explicit` 稠密元素总数 | \(n\cdot m \le 10^4\)(如 100×100) | -| SVD / eig 方阵边长 | \(\le 64\)(与 quantum 密度同级) | -| 结构 SVG(无元素) | 边长示意可达数百(只画框) | -| KaTeX 完整数字阵 | \(\le 8\times 8\);更大只出摘要 + 结构图 | - -### 4.4 展示 - -| 英文 | `kind` | 说明 | -|------|--------|------| -| `show` | — | 写入 view:优先 `latex` 公式卡 | -| `draw` | `structure` | 形状/分块矩形(drawmatrix 风格) | -| `draw` | `heatmap` / `hinton` | 数值幅度 | -| `draw` | `svd` / `qr` / `ge` / `eig` | 分解结构图(对标 LAFigureSpecs) | -| `draw` | `path`= | 可选落盘 SVG | - -`show` 应对符号式**始终可用**(无需 `eval`)。 - -### 4.5 最小可运行示例(设计验收叙事) - -````markdown ---- -import: - la: ext/linalg/linalg.mq.md - table: lib/table.mq.md ---- - -# main - -*`A` = > la.symbol name=A rows=3 cols=3 * -*`x` = > la.symbol name=x rows=3 cols=1 * -*`b` = > la.mul a=`A` b=`x` * - -*`s` = > la.simplify expr=`b` * -> la.show expr=`s` - -`M` = -$$ -\begin{bmatrix}2&0\\0&3\end{bmatrix} -$$ - -*`M` = > la.from_list data=[[2,0],[0,3]] * -*`f` = > la.factorize matrix=`M` kind=eig * -> la.draw factor=`f` kind=eig path=eig.svg -```` ---- - -## 5. 公式重写与「大规模优化」(核心) - -### 5.1 原则 - -1. **构造便宜,展开昂贵**——乘加只分配节点。 -2. **形状是类型系统**——`(m×k)·(k×n)` 合法;否则错误指向调用点。 -3. **化简是规则不动点**——有限规则表,可测、可文档化。 -4. **expand 显式开启**——`expand=True` 才对 Kronecker / 多项式矩阵做爆炸性展开。 -5. **数值路径旁路符号**——已 `explicit` 的叶子用稠密核,不再走规则。 - -### 5.2 v1 规则集(最小够用) - -| ID | 规则 | 例 | -|----|------|-----| -| R1 | 单位元 | `I*A → A`,`A*I → A`,`A+0 → A` | -| R2 | 双逆 | `(A^{-1})^{-1} → A` | -| R3 | 转置反序 | `(AB)^\top → B^\top A^\top`,`(A^\top)^\top → A` | -| R4 | 逆转置 | `(A^{-1})^\top → (A^\top)^{-1}` | -| R5 | 结合扁平 | `MatMul` 链扁平化 | -| R6 | 分块塌缩 | 对标 `block_collapse`(乘/加在块级分配) | -| R7 | Kronecker 结合 | `(A⊗B)⊗C → A⊗B⊗C`;**不**展开成元素 | -| R8 | 标量提出 | `c*(A+B) → c*A+c*B`(可选;默认关以免树变宽) | - -### 5.3 数值侧优化 - -| 策略 | 说明 | -|------|------| -| `factorize` 一次 | 多 RHS `solve` 复用 | -| 小阵专用核 | 2×2 / 3×3 闭式逆 / det(教学友好、可对照公式) | -| 复杂度护栏 | 超限错误信息建议「保持符号 / 降维 / 分块」 | -| 禁止静默降精度 | 病态 `cond` 可警告(stderr 或结果字段) | - ---- - -## 6. 展示设计(效果) - -### 6.1 通道 - -| 通道 | 符号 MatExpr | 稠密 | 分解 | -|------|--------------|------|------| -| view Structure | KaTeX `latex` 卡 | 小阵 KaTeX;大阵摘要 | 公式 + 可选 SVG | -| view Execution plots | — | heatmap SVG | `kind=svd|…` SVG | -| CLI `print` | `ascii` | `[[…],…]` 或摘要 | `svd(U,S,V)` 摘要 | -| writeback | 可选记录 latex | 可选 | 可选 | - -### 6.2 LaTeX 约定 - -- 符号:`A`,`A^{\top}`,`A^{-1}`,`AB`,`A \otimes B` -- 数值小阵:`\begin{bmatrix}…\end{bmatrix}` -- 分块:`\begin{bmatrix} A & B \\ C & D \end{bmatrix}` -- 喂给既有 view:与 `formula-card` / KaTeX 同源路径(L1 `show` → `host_query("record_plot")` 或扩展「record_math」若已有;无则复用 writeback + plot 列表) - -### 6.3 结构 SVG(教学主视觉) - -对标 LAFigureSpecs / drawmatrix,**不**依赖 Matplotlib: - -| `kind` | 画什么 | -|--------|--------| -| `structure` | 矩形块 + 标签(零块灰色) | -| `svd` | \(U\Sigma V^{\top}\) 块布局 + 秩分隔 | -| `qr` | 瘦/胖 QR 示意 | -| `ge` | 消元后上三角高亮 | -| `eig` | \(A=PDP^{-1}\) 或谱列表 + 对角 | -| `heatmap` | 单元填色(实数蓝红;复数幅值) | - -主题:`theme=light|dark|bw`(与 quantum Q8 令牌对齐;默认 `light`)。 - ---- - -## 7. L1 / 插件 / CLI 约定 - -1. **`ext/linalg/**` 禁止 `host_*`**;只调 `plugin.*` 注册名(如 `linalg_simplify`)。 -2. **中英分文件**,CATALOG 双 id:`linalg` / `线性代数`。 -3. **`marqdo ext add linalg`**:与 web/agent/quantum 相同——优先 Release 预编译 native zip。 -4. **金样**:离线、确定性;SVG 断言含关键子串或稳定 hash 前缀。 -5. **依赖**:插件内自研稠密核(或慎重引入单一 crate,如 `nalgebra`——**实现期再议**;设计默认「可自研小维 + 可选 crate」)。 - ---- - -## 8. 分期(摘要;细节见路线图) - -| 阶段 | 交付 | -|------|------| -| **L0** | CATALOG + ping + L1 `ensure_plugin` | -| **L1** | `matrix.symbol` / dense 构造 / `mul`·`T`·`inv` 树 + `simplify` R1–R5 + `latex`/`show` | -| **L2** | `explicit` / 小阵运算 / `solve` / `det`·`trace` 数值 | -| **L3** | 分块 + `collapse`;Kronecker 惰性 | -| **L4** | `factorize` LU/QR/SVD/eig + 结构 SVG | -| **L5** | heatmap/hinton;examples + public 文档 + skill 摘要 | -| **L6+** | 矩阵微积分 / 更大 BLAS(仅当用户明确要求);复数全路径算子 | - ---- - -## 9. 验收标准(设计级) - -1. 符号式 `(AB)^\top` 经 `simplify` 得 `B^\top A^\top`,**不**产生稠密数据。 -2. 不相容形状在符号 `mul` 即失败。 -3. `$$` 数值阵 → `from_formula` → `factorize kind=eig` → view 含 SVG 或 latex。 -4. Kronecker 默认不 expand;显式 `expand` 受维数护栏。 -5. 中英 L1 金样各至少一条;`ext add linalg` 路径文档化。 -6. 与 `ext/quantum` 无作者面符号冲突。 - ---- - -## 10. 风险与开放问题 - -| 项 | 备注 | -|----|------| -| MatExpr 序列化 | 金样 / write:倾向可打印 S-expr 或稳定 latex+shape,避免不透明指针跨进程 | -| 与标量 `formula` 混运算 | v1:标量只作 `c*A` 系数;`det` 结果若符号则另型或降为 `formula` 文本 | -| nalgebra 等依赖 | 实现 L2 时评估二进制体积与 ABI 体积 | -| record_math vs plot | 若仅 SVG/KaTeX 字符串,可先复用 plot/writeback | - ---- - -## 11. 一句话(收束) - -**`ext/linalg` 让线性代数公式保持可优化的表达式,用规则与结构图服务文档阅读,用受控稠密核服务验算——公式优先,数值可选,展示分层。** diff --git a/doc/design/ext-llm.md b/doc/design/ext-llm.md deleted file mode 100755 index 65800ba..0000000 --- a/doc/design/ext-llm.md +++ /dev/null @@ -1,109 +0,0 @@ -# Official extensions (`ext/`) — LLM - -| | | -|---|---| -| Status | **Accepted · v0.3 semantic**(005:Intelligence Primitive) | -| Date | 2026-09-24 | -| Related | [objects.md](objects.md) · [ext-agent.md](ext-agent.md) · [ext-cli.md](ext-cli.md) · [ai-stack.md](../roadmap/ai-stack.md) · [doc/next/005.md](../next/005.md) | - -## Scope - -`ext/ai/llm` is Marqdo’s **intelligence primitive**, not an OpenAI SDK wrapper. - -```text -Author surface: ask / stream / collect / create / fast / reasoning / prompt_load -Transport: ext/ai/llm/openai.mq.md (+ ollama defaults) -Compat: complete / chat -``` - -Import: - -```markdown ---- -import: - llm: ext/ai/llm.mq.md ---- -``` - -## Public API - -| English | Chinese | Role | -|---------|---------|------| -| `## load_env` | `## 加载环境` | Load `.env` | -| `## create` | `## 创建` | Factory → LLM handle | -| `## fast` / `## reasoning` | `## 快速` / `## 推理` | Named handles | -| `## prompt_load` / `## prompt` / `## prompt_body` | `## 加载提示` / `## 提示` / `## 提示正文` | Prompt artifacts (`type: prompt` → body) | -| `## ask` (module) | `## 提问` | Convenience → **text** (`prompt=` or `path=`) | -| `## collect` | `## 收集` | Events → text | -| `## stream_result` | `## 流式结果` | Alias of `collect` | -| `# llm` | `# 大模型` | Handle ctor (`backend=` openai-compatible \| ollama) | -| `## ask` (method) | `## 提问` | → **LLMResult** map | -| `## stream` | `## 流式` | → event list | -| `## complete` / `## chat` | `## 运行` / `## 聊天` | Compat / transport primitive | - -### Preferred - -```markdown -**answer = > llm.ask prompt="What is Marqdo?"** -*answer* - -**model = > llm.create** -**result = > `model`.ask prompt=`prompt`** -*[text](result)* - -**fast = > llm.fast** -**events = > `fast`.stream prompt=`prompt`** -**text = > llm.collect events=`events`** - -**body = > llm.prompt path="fixtures/prompt-marqdo.md"** -**body2 = > llm.prompt text=`raw`** -``` - -### LLMResult - -| Field | Meaning | -|-------|---------| -| `text` | Answer string | -| `model` | Model id | -| `finish` | Finish reason (`stop`, …) | -| `backend` | e.g. `openai-compatible` / `ollama` | -| `usage` | `{prompt_tokens,completion_tokens,total_tokens}` | -| `tokens` | Alias of `usage.total_tokens` (agent metrics) | -| `name` | Optional handle tag (`fast` / `reasoning`) | -| `llm_calls` | `1` per ask | -| `tool_calls` | List of OpenAI-shaped tool call objects (empty when none) | - -### Compat - -`complete` / `chat` still return a bare string (or event list when `stream=True`) so `ext/ai/agent` and older runbooks keep working. **New code should use `ask` / `stream` / `collect`.** - -## Environment - -```env -OPENAI_API_KEY=sk-... -OPENAI_BASE_URL=https://api.openai.com/v1 -OPENAI_MODEL=gpt-4o-mini -MARQDO_LLM_FAST_MODEL=... -MARQDO_LLM_REASONING_MODEL=... -OLLAMA_HOST=http://127.0.0.1:11434/v1 -``` - -Fallbacks: `MARQDO_LLM_API_KEY`, `MARQDO_LLM_BASE_URL`, `MARQDO_LLM_MODEL`. Ctor also accepts `api_key=` / `base_url=` / `model=` / `backend=`. - -## Backends - -| `backend=` | Module | Notes | -|------------|--------|-------| -| `openai-compatible` (default) | `ext/ai/llm/openai.mq.md` | Chat Completions HTTP + SSE | -| `ollama` | defaults in ctor + same transport | Key defaults to `ollama`; host from `OLLAMA_HOST` | - -## Tests - -- `tests/ext/llm-import.mq.md` -- `tests/ext/llm-ctor-offline.mq.md` -- `tests/ext/llm-ask-offline.mq.md` (create + collect) -- `tests/ext/llm-stream-offline.mq.md` -- `tests/ext/llm-named-offline.mq.md` (fast/reasoning + prompt_load) -- `tests/ext/llm-tool-calls-offline.mq.md` (`tool_calls_from` / Result field) -- `tests/ext/llm-meta-offline.mq.md` · `llm-entry-prompt-offline.mq.md` -- Live: `llm-complete.mq.md` · `llm-stream-live.mq.md` diff --git a/doc/design/ext-quantum-custom-gate.md b/doc/design/ext-quantum-custom-gate.md deleted file mode 100755 index 6c89413..0000000 --- a/doc/design/ext-quantum-custom-gate.md +++ /dev/null @@ -1,49 +0,0 @@ -# `ext/quantum` — 自定义酉门(公式矩阵 → 可施加) - -| | | -|---|---| -| 状态 | **Accepted · 已落地** | -| 日期 | 2026-08-12 | -| 父设计 | [ext-quantum.md](ext-quantum.md) | - ---- - -## 1. 目标 - -作者用 `$$…$$`(或嵌套 list)写出酉矩阵 → `quantum.gate matrix=…` 得到可复用门句柄 → `` `qc`.apply gate=… qubits=… `` 施加到电路。 - ---- - -## 2. 公式矩阵 - -`$$` 围栏若含 `[[…]]` 或 `\begin{pmatrix}` / `\begin{bmatrix}`,在**解析期**求值为嵌套数值 list(非整棵 `Formula` 标量树)。 - -支持: - -- ASCII:`[[1,0],[0,-1]]`、`(1/sqrt(2))*[[1,1],[1,-1]]` -- LaTeX 子集:`\frac{…}{…}`、`\sqrt{…}`、`pmatrix` / `bmatrix`(`&` / `\\`) - -复数:list 路径仍可用 `{re,im}` 或 `[re,im]`;公式路径本切片以实矩阵为主。 - ---- - -## 3. API - -```markdown -*`U` = > quantum.gate matrix=`H_matrix` name=U * -# 或构造参数 matrix=;name 可选(默认 U) - -*`qc` = > `qc`.apply gate=`U` qubits=0 * -# qubits= 标量或 list;矩阵维数须为 2^k -``` - -中文:`量子.门 矩阵=` / `` `qc`.施加 门= 比特= ``。 - -具名门仍可用 `name=H`;`matrix` / `matches_matrix` / `draw` 对自定义门同样有效。 - ---- - -## 4. 验收 - -- 公式(或 list)定义的 H 与内置 `H` 概率一致 -- EN/ZH 金样 diff --git a/doc/design/ext-quantum-handbook.md b/doc/design/ext-quantum-handbook.md deleted file mode 100755 index a4c08c7..0000000 --- a/doc/design/ext-quantum-handbook.md +++ /dev/null @@ -1,71 +0,0 @@ -# Quantum:从「拆分过的库」到可执行开发手册 - -| 项目 | 内容 | -|------|------| -| 日期 | 2026-11-08 | -| 使用与开发真相源 | [英文根入口](../../ext/quantum/index.mq.md) · [中文根入口](../../ext/quantum/量子/索引.mq.md) | -| 回归门禁 | [quantum_handbook.rs](../../tests/quantum_handbook.rs) | -| 思想来源 | [next/010](../next/010.md) · [next/011](../next/011.md) · [next/012](../next/012.md) | -| 本文定位 | 记录本次修正的原因与边界;日常使用无需先读本文 | - -上一轮把量子库拆成了模块树,也加入了 `call` 与叙述比例,但没有形成「只沿 index 就能使用和开发」的闭环。问题出在验收标准:目录、工具和叙述存在,并不能证明一个陌生开发者能完成实验、理解结果,再正确扩展它。 - -## 已确认的缺口 - -| 缺口 | 后果 | 本轮修正 | -|------|------|----------| -| `## For AI agents`、`## Package layout` 等说明标题 | 解析成无业务意义的真实函数,污染工具树 | 说明用自然段,标题保留给工具/对象 | -| 裸 `$qc`、缺会话或只有消费者没有生产者 | 照抄命令失效,Rust argv 测试发现不了 shell 展开 | 每页完整实验;引用和文本字面量用 shell 单引号 | -| 字符串 `kind="bitflip"` 的双引号被 shell 去掉 | CLI 拒绝未带字面量引号的文本 | 使用 `'kind="bitflip"'`,通过真实 shell 测试 | -| 默认值后紧贴英文标点,如容差后的问号 | 标点被叙述扫描器纳入默认值,number 变成 text | 标点与默认值分隔,实跑覆盖省略参数 | -| 旋转、自定义门应用、追加、矩阵导出藏在对象方法里 | 命令行只能走很窄的 Bell 演示路径 | 补齐自由工具,保留既有作者对象方法 | -| 重复「本方法返回句柄」等通用套话 | 满足比例却没有解释科学语义 | 移除旧填充,加入来源、单位、边界、预期和下一步 | -| 缺源码归属与验证方式 | AI 知道怎么调用,却不知道怎么开发 | 各模块写新增配方/原语的修改位置、镜像和既有金样 | - -## 同一个入口承担四个职责 - -使用路径是「打开根入口 → 根据科学问题选模块 → 复制完整实验 → 核对独立期望」。每个子入口也能单独冷启动,包括输入生产者、参数、结果形状、何时转到兄弟模块。 - -开发路径从最小必要变化开始:新实验组合已有工具;新酉矩阵使用 `gate.custom`;只有真实能力缺口才改原生实现。每个模块给出它负责的 Rust 文件、ABI 导出、中英镜像及应保留的测试。根入口的 `bell_analysis` 是这种开发方式的具体配方。 - -`bell_circuit` 返回可继续组合的电路;原有 `bell_phi_plus` / `贝尔态` 保留概率结果;新增 `bell_analysis` / `纠缠分析` 返回整体纯度、约化纯度、ZZ 关联和 Schmidt 数据。相同概率的经典混合不能冒充 Bell 纯态,所以不能只验证 00/11 概率。 - -工具入口继续是普通 `.mq.md` 函数。没有添加 Skill 编译器、MCP 包装、额外工具 manifest 或另一套 schema。符号与契约依靠现有解析和 `knowledge inspect`;符合 next/011 的简洁核心。 - -## 契约位置必须符合当前解析器 - -旧范式要求「返回表放在体末、返回标记前」,但 `src/parse/mod.rs::extract_function_contract` 只在首条可执行语句前提取参数与返回契约。放到 `cap.load` 之后的返回表会成为普通表,无法承担预期校验。 - -本轮以实现为准:参数表紧跟标题;返回表也位于首条执行语句之前;意图叙述仍可与后续执行步骤交错。对象构造器和方法同样补齐契约。叙述声明承载默认值,表说明类型和含义,不把 `any` 句柄伪装成新增的领域类型系统。 - -`check --narrative-ratio` 仍是最低门槛,但不再充当手册完成的唯一证据。测试同时检查每个可调用单元具有真正提取出的返回契约、参数无漂移,根符号只有三个实际实验工具。 - -## 只承诺已有能力 - -手册明确以下区别,而不把 next 的愿景写成已经实现的功能: - -- `call`、跨进程 journal 会话、双后端和稳定符号查询已有实现。 -- 状态向量默认 12 比特、硬上限 16;密度和 Schmidt 最多六比特。 -- 理想态与概率忽略教学噪声;只有 `run` 采样施噪。 -- 密度矩阵构造检查形状和厄米性,不认证半正定与归一化。 -- Schmidt 熵使用自然对数;局部纯度和关联需要结合整体态解释。 -- `draw_state` / `画态` 补上现有 qsphere、multibloch 能力;高级态图换肤仍是 Q8c 规划。 -- `call --effects plugin` 允许绘图返回 SVG,但宿主仍禁文件写入;实际落盘走作者程序的 `run`。 -- 插件 journal 重放可能重复插件效果;会话不是无副作用的永久对象仓库。 -- 智能体决定持久交互分支和复杂自我改进并非本轮实现。 - -## 验证与推广条件 - -先构建 `marqdo_plugin_quantum`,再执行: - -```bash -cargo test --locked --test quantum_handbook -cargo test --locked --test call_cli quantum_ -cargo test --locked --test gold ext_quantum -- --test-threads=1 -``` - -手册门禁直接提取双语源码中的 `sh` 围栏,经过 bash 执行原命令,逐次检查退出码与 JSON,不抄写另一份命令目录。作者程序也从 `marqdo` 围栏提取执行。两类示例都验证 Tree/Bytecode,并比较独立数学期望与中间结果;会话放在临时目录隔离。 - -组合工具另覆盖具名旋转门、矩阵导出、应用、追加和密度矩阵观察。既有 gold 继续覆盖公式、自定义门、噪声、振幅阻尼、作者方法与 SVG。 - -向其他扩展推广时,复用的是这些验证问题:陌生人能否独立启动、能否解释结果、能否找到修改归属、示例是否来自源码且持续执行。无需把 Quantum 的具体物理工具或新的模板套到每个库。 diff --git a/doc/design/ext-quantum-q5.5.md b/doc/design/ext-quantum-q5.5.md deleted file mode 100755 index 7f600eb..0000000 --- a/doc/design/ext-quantum-q5.5.md +++ /dev/null @@ -1,48 +0,0 @@ -# `ext/quantum` Q5.5 — 振幅阻尼(教学轨迹) - -| | | -|---|---| -| 状态 | **Accepted · 已落地** | -| 日期 | 2026-08-12 | -| 父设计 | [ext-quantum.md](ext-quantum.md) · [ext-quantum-q5.md](ext-quantum-q5.md) | -| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | - ---- - -## 1. 目标 - -在 Q5 的 `bitflip` / `depolarizing` 之外,补一种**耗散**教学噪声:`amplitude_damping`(中文 `振幅阻尼`),仍只影响 `run` 轨迹;`simulate` / `probabilities` 忽略。 - -**刻意不做:** 完整 Kraus 表 API、任意算符噪声、密度矩阵引擎、相位阻尼完整 Lindblad。 - ---- - -## 2. 作者面 - -```markdown -*`qc` = > `qc`.noise kind=amplitude_damping p=0.1 * -# 中文 -*`qc` = > `qc`.噪声 种类=振幅阻尼 概率=0.1 * -``` - -别名:`amp_damp` / `amplitude-damping`。 - ---- - -## 3. 模拟语义 - -与 Q5 相同:每个改态门后,对涉及比特独立掷骰。 - -对每个比特,以概率 `p` 施加**跳跃**算符 \(E_1 = |0\rangle\langle 1|\)(只作用该比特),再归一化: - -- 若态在该比特上几乎全为 `|0⟩`(范数 ≈ 0),跳跃无效,态不变。 -- 否则振幅从 `|…1…⟩` 搬到对应 `|…0…⟩` 并归一化。 - -金样:`X` 后 `amplitude_damping p=1` → 全部 shot 落在 `|0⟩`。 - ---- - -## 4. 验收 - -- `tests/ext/quantum-amp-damp-smoke.mq.md`(+ 中文对称) -- L1 EN/ZH 文档列出第三种 `kind` diff --git a/doc/design/ext-quantum-q5.md b/doc/design/ext-quantum-q5.md deleted file mode 100755 index 3c5176d..0000000 --- a/doc/design/ext-quantum-q5.md +++ /dev/null @@ -1,69 +0,0 @@ -# `ext/quantum` Q5 — 最小噪声(教学用) - -| | | -|---|---| -| 状态 | **Accepted · 最小实现已落地** | -| 日期 | 2026-08-12 | -| 父设计 | [ext-quantum.md](ext-quantum.md) | -| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | - ---- - -## 1. 目标 - -在 **不** 引入完整开放系统 / 云后端的前提下,让教学文档能写「带噪声的采样」,金样可复现。 - -**刻意不做(本 Q5 切片):** 任意 Kraus 组、振幅阻尼完整表、>12 qubits 张量网络、噪声参数学习。振幅阻尼教学轨迹见 [ext-quantum-q5.5.md](ext-quantum-q5.5.md)。 - ---- - -## 2. 作者面 - -电路上可选噪声字段(方法链设置,返回新句柄): - -```markdown -*`qc` = > `qc`.noise kind=bitflip p=0.05 * -# 或 -*`qc` = > `qc`.noise kind=depolarizing p=0.02 * -``` - -| 参数 | 含义 | -|------|------| -| `kind` | `bitflip` \| `depolarizing`(中文:`比特翻转` / `退极化`) | -| `p` | 每比特、每个非 `barrier`/`measure` 门后的错误概率,`0…1` | - -`simulate` / `probabilities`:**忽略噪声**(仍为理想酉演化),避免概率图被蒙特卡洛抖动。 -`run shots= seed=`:**启用噪声**(若 `p>0`):按轨迹采样,结果可复现。 - ---- - -## 3. 模拟语义(轨迹) - -每个 shot: - -1. 从 `|0…0⟩` 施电路门(跳过 `BARRIER`;`MEASURE` 不改变酉演化)。 -2. 每施一个会改态的门后,对**该门涉及的每个比特**独立: - - `bitflip`:以概率 `p` 施 `X`; - - `depolarizing`:以概率 `p` 均匀随机施 `X`/`Y`/`Z` 之一。 -3. 若电路含 `MEASURE` 标记:只对标记比特做计算基采样;否则测全部比特。 - -RNG:与现有 `run seed=` 同一 SplitMix64 流(门后噪声与最终采样共用)。 - ---- - -## 4. 与作者面补齐的关系 - -| API | 行为 | -|-----|------| -| `barrier` | 仅可视化;模拟跳过 | -| `measure` | 可视化测量符号;决定 `run` 读出哪些比特 | -| `append` | 追加另一 `circuit` 的 `ops`(或单门) | -| `state` | 等价于当前理想 `simulate` 结果(`quantum_state`) | - ---- - -## 5. 验收 - -- 金样:理想 Bell `run` 不变;`noise kind=bitflip p=1` 在已知电路上计数偏离理想(`seed=` 固定)。 -- `barrier`/`measure` 出现在 `draw kind=circuit` SVG。 -- 中英 L1 对称;仍无 `host_*` 于 `ext/**`。 diff --git a/doc/design/ext-quantum-q7.md b/doc/design/ext-quantum-q7.md deleted file mode 100755 index 3042988..0000000 --- a/doc/design/ext-quantum-q7.md +++ /dev/null @@ -1,230 +0,0 @@ -# `ext/quantum` Q7 — 高阶线性代数 + 高级可视化 - -| | | -|---|---| -| 状态 | **Accepted · Q7a/Q7b/Q7c 已落地** | -| 日期 | 2026-08-28 | -| 父设计 | [ext-quantum.md](ext-quantum.md) | -| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | -| 对照 | [IBM Quantum state plots](https://quantum.cloud.ibm.com/docs/en/guides/plot-quantum-states) · [QuTiP visualization](https://qutip.readthedocs.io/en/latest/guide/guide-visualization.html) · Cirq `plot_density_matrix` | - ---- - -## 0. 一句话 - -在 **Q0–Q6 态向量教学模拟**之上,补齐两块「教科书级」能力: - -1. **高阶线性代数**(密度矩阵、Kronecker、部分迹、Hermitian 谱分解、Schmidt / SVD、Pauli 期望值) -2. **高级静态 SVG 展示**(Hinton / City / Pauli 向量 / QSphere 风格 / 多比特布洛赫) - -全部经 **`plugins/quantum` ABI**;`ext/quantum/**` 只做 L1 表包装,**禁止** `host_*`。 - ---- - -## 1. 动机与业界对照(联网调研 2026-08) - -### 1.1 为何现在做 - -| 已有(Q0–Q6) | 缺口 | -|---------------|------| -| 纯态态向量 + 施门 + 采样 | 混态 / 约化子系统无法一等公民表达 | -| `bloch` 单比特约化 | 纠缠与多比特关联只能猜 | -| `gate.draw kind=matrix` 热力图 | 无密度矩阵 / Pauli 分解 / 球面振幅布局 | -| 内部 `apply_unitary` / Kronecker | **未**暴露为作者面 API | - -教学文档写「贝尔态纠缠」时,读者需要:**约化密度矩阵 → 纯度 < 1 → Schmidt 系数 → Hinton/QSphere 图**。这些正是 Qiskit / QuTiP / Cirq 的标配。 - -### 1.2 可视化对标(只取可静态 SVG 落地的子集) - -| 业界 | 含义 | Q7 决策 | -|------|------|---------| -| Qiskit `plot_state_hinton` | 元大小表示幅值,色表示正负 | ✅ `kind=hinton` | -| Qiskit `plot_state_city` | Re/Im 三维条 | ✅ **2.5D 等轴测 SVG**(非 Matplotlib) | -| Qiskit `plot_state_paulivec` | Pauli 串期望值柱 | ✅ `kind=paulivec` | -| Qiskit `plot_state_qsphere` | 振幅点在球面上,色=相位 | ✅ `kind=qsphere`(教学投影) | -| Qiskit `plot_bloch_multivector` | 每比特一球 | ✅ `kind=multibloch` | -| Cirq density Argand 格 | 每元幅值圆 + 相位针 | ✅ 并入 `kind=density`(默认) | -| QuTiP Wigner / 过程层析 | 连续相空间 / χ 矩阵 | ❌ 本切片不做 | - -### 1.3 线性代数对标(经典模拟侧,非量子算法) - -| 能力 | 教学用途 | Q7 | -|------|----------|-----| -| ρ = \|ψ⟩⟨ψ\| | 纯→密度 | ✅ | -| Kronecker / 张量积 | 复合系统 | ✅ | -| 部分迹 | 约化、纠缠证据 | ✅ | -| Hermitian 本征分解 | 谱 / 测量可观测量 | ✅(小维) | -| Schmidt(纯态二分)= 整形 SVD | 纠缠熵入口 | ✅ | -| Pauli 期望 ⟨P⟩ | 布洛赫 / paulivec 数据源 | ✅ | -| 纯度 Tr(ρ²)、保真度 | 混态度量 | ✅ 最小 | -| 量子奇异值变换 / VQSVD / 云后端 | 算法研究 | ❌ | - ---- - -## 2. 硬约束(沿用 + 本切片追加) - -1. **仅 ABI**:新 FFI 全部注册在 `marqdo_plugin_init`;L1 经 `plugin.load`。 -2. **`ext/**` 无 `host_*`**。 -3. **中英分文件**,禁止混 API。 -4. **维数上限**: - - 态向量模拟:仍 ≤ 12 qubits(既有)。 - - **密度矩阵稠密运算**(部分迹结果展示、谱分解、Hinton/City):默认 **≤ 6 qubits**(dim ≤ 64);超限显式报错。 -5. **无新核心依赖**:插件内手写复数矩阵 + Jacobi / 薄 SVD;**不**捆绑 BLAS / nalgebra(可后续再议)。 -6. **view**:仍走 `host_query("record_plot")` + `quantum_svg`;无外链字体/CDN。 - ---- - -## 3. 新运行时类型 - -| `_type`(英) | 中文 | 字段(锁定) | -|---------------|------|----------------| -| `quantum_state` | `量子态` | 既有:`qubits`, `amplitudes:[{re,im}]` | -| `quantum_density` | `密度矩阵` | `qubits`, `dim`, `matrix`(dim×dim 嵌套 `{re,im}`) | -| `quantum_spectrum` | `谱` | `eigenvalues:[f64]`, `eigenvectors`(列向量嵌套 list) | -| `quantum_schmidt` | `施密特` | `coeffs:[f64]`, `ua`, `ub`(局域基),`entropy`(可选) | -| `quantum_svg` | — | 既有;`kind` 扩展见 §5 | - ---- - -## 4. 作者面 API - -### 4.1 英文(`ext/quantum/circuit/index.mq.md`) - -在既有 `# circuit` / `# gate` 之外增加(或扩展方法): - -```markdown -# density - + `state`=None # quantum_state 或 circuit(先 simulate) - + `matrix`=None # 直接给定 ρ - -## matrix # → 嵌套 list -## purity # Tr(ρ²) -## expect - + `obs` # Pauli 串 "ZI" / "XX" 或门矩阵 -## partial_trace - + `keep` # 保留的比特列表(LSB=0) -## eig # Hermitian 谱 → quantum_spectrum -## draw - + `kind`=hinton # hinton|city|density|paulivec - + `path`=None - -# linop # 自由线性代数(也可挂在 quantum.* 模块函数) -## kron - + `a` - + `b` # 矩阵或态 → 张量积 -## schmidt - + `state` - + `cut`=1 # 前 cut 个比特为 A,其余为 B -## fidelity - + `a` - + `b` # 两态或两密度(纯态公式优先) -``` - -**电路侧便捷方法**(返回新句柄,不改旧对象): - -```markdown -## density # simulate 后 ρ=|ψ⟩⟨ψ| -## expect - + `obs` -## schmidt - + `cut`=1 -## draw - + `kind`=… # 扩展:hinton|city|density|paulivec|qsphere|multibloch -``` - -### 4.2 中文对称 - -| 英文 | 中文 | -|------|------| -| `density` | `密度` | -| `partial_trace` | `部分迹` | -| `purity` | `纯度` | -| `expect` | `期望` | -| `eig` | `本征` | -| `kron` | `张量积` | -| `schmidt` | `施密特` | -| `fidelity` | `保真度` | -| `hinton` / `city` / `paulivec` / `qsphere` / `multibloch` | 同音译或 `欣顿`/`城市`/`泡利向量`/`球`/`多布洛赫`(L1 锁定中英别名表) | - -### 4.3 ABI 函数名(稳定英文) - -| FFI | 作用 | -|-----|------| -| `quantum_density_from_state` | 态 / 电路 → `quantum_density` | -| `quantum_density_from_matrix` | 校验 Hermitian / 维数 → 句柄 | -| `quantum_density_matrix` | 取出嵌套矩阵 | -| `quantum_density_purity` | Tr(ρ²) | -| `quantum_density_partial_trace` | keep 列表 | -| `quantum_density_eig` | Jacobi Hermitian | -| `quantum_density_expect` | Pauli 串或矩阵 | -| `quantum_density_draw` | hinton/city/density/paulivec | -| `quantum_kron` | 两矩阵或两态振幅 | -| `quantum_schmidt` | 纯态二分 | -| `quantum_fidelity` | 两态 | -| `quantum_draw_circuit` | **扩展** kind 枚举(向后兼容) | - ---- - -## 5. 高级绘图语义 - -| `kind` | 输入 | SVG 要点 | -|--------|------|----------| -| `hinton` | ρ | 网格方块;边长 ∝ √\|ρᵢⱼ\|;正 Re 浅 / 负深;小 dim 可标数值 | -| `city` | ρ | 等轴测「楼宇」:左 Re、右 Im 两城,或单城双色柱 | -| `density` | ρ | Cirq 风格:每格幅值圆 + 相位线段;对角概率矩形 | -| `paulivec` | 态或 ρ | 全 Pauli 基(n≤3)或用户 `ops=` 列表;柱高 = ⟨P⟩ | -| `qsphere` | 纯态 | 基矢点映射到球/圆;半径∝振幅,色相∝arg;n≤4 推荐 | -| `multibloch` | 纯态 | 每比特约化布洛赫并排 | - -既有 `circuit|probs|bloch|gate|matrix` **不变**。 - ---- - -## 6. 数值语义(锁定) - -| 项 | 规则 | -|----|------| -| 比特序 | **qubit 0 = LSB**(与既有概率标签一致) | -| `partial_trace keep=` | 保留比特升序组成新系统的 LSB…MSB | -| Pauli 串 | 左→右 = **高位→低位** 或文档写死「左=qubit n-1」——**锁定:字符串左端 = 最高比特(qubit n−1)**,与 Qiskit 习惯一致;文档 + 金样双锁 | -| Hermitian 检查 | ‖ρ−ρ†‖_F < 1e-8,否则报错 | -| 谱 | 实特征值降序;特征向量列归一 | -| Schmidt | 将 \|ψ⟩ 整形为 `2^cut × 2^(n-cut)` 复矩阵做薄 SVD;奇异值 = Schmidt 系数 | -| 纯度 | 纯态 ≈ 1;最大混态 = 1/dim | - ---- - -## 7. 分期交付 - -| 子阶段 | 内容 | 验收 | -|--------|------|------| -| **Q7a** | density / kron / partial_trace / eig / schmidt / expect / purity / fidelity + L1 中英 | `tests/ext/quantum-linalg-smoke.mq.md`(+ zh) | -| **Q7b** | draw kinds:hinton, city, density, paulivec, qsphere, multibloch | `tests/ext/quantum-viz-advanced-smoke.mq.md`(SVG 含关键标记) | -| **Q7c** | 示例页 + 用户站短页 + skill/reference 摘要 | `examples/quantum-entanglement/` 或扩展 bell | - ---- - -## 8. 刻意不做(本 Q7) - -- 任意 Kraus / 完整 CPTP 通道库(仍用 Q5 轨迹噪声) -- >6 qubit 稠密 ρ 的谱 / Hinton(请用态向量 API) -- Matplotlib / WebGL / 交互拖拽 -- 量子线性系统算法(HHL)、QSVT 电路构造 -- 把线性代数并入 `lib/math`(经典公式优先的 LA 见规划 [ext-linalg.md](ext-linalg.md),作者面与 quantum 分离) - ---- - -## 9. 评审清单 - -1. 密度矩阵上限 6 qubits 是否可接受? -2. Pauli 串左右端比特约定是否锁定为「左=高比特」? -3. City 用 2.5D SVG 而非真 3D 是否足够? -4. `# density` 独立类 vs 仅 `circuit.density` —— **两者都提供**(类用于给定矩阵;电路方法便捷)? - -评审默认:**全部锁定为上文**;实现按 Q7a → Q7b → Q7c。 - ---- - -## 10. 一句话 - -**Q7 让 Marqdo 量子文档能「算清纠缠、画清态」:线性代数在 ABI 里跑,高级图用自绘 SVG 进 view——仍是代码即文档。** diff --git a/doc/design/ext-quantum-viz-style.md b/doc/design/ext-quantum-viz-style.md deleted file mode 100755 index efedfc4..0000000 --- a/doc/design/ext-quantum-viz-style.md +++ /dev/null @@ -1,153 +0,0 @@ -# `ext/quantum` Q8 — 可视化美学升级(科技感电路图) - -| | | -|---|---| -| 状态 | **Accepted · Q8a/Q8b landed · Q8c pending** | -| 日期 | 2026-08-28 | -| 父设计 | [ext-quantum.md](ext-quantum.md) · [ext-quantum-q7.md](ext-quantum-q7.md) | -| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | -| 对照 | [IBM Quantum Composer](https://quantum.cloud.ibm.com/docs/guides/composer) · [Qiskit `iqp` / `iqp-dark`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.visualization.circuit_drawer) · Cirq / Quirk 视觉习惯 | - ---- - -## 0. 一句话 - -修复 view 内嵌量子 SVG 的**文字–导线粘连**,并把电路 / 概率 / 布洛赫 / 密度类图统一到一套**量子实验室科技感**视觉令牌(深底、门族分色、清晰留白)——仍只输出自包含 SVG,无外链字体/CDN。 - ---- - -## 1. 问题诊断(对照用户截图) - -| 现象 | 根因(`plugins/quantum/src/draw.rs`) | -|------|----------------------------------------| -| `q0`/`q1` 与导线穿过文字 | 导线从 `x=8` 起画满宽;标签 `x=4` 且基线对齐导线中心 → 线穿字 | -| 「不好看 / 无科技感」 | 单色 `#1a1a1a` + 浅灰盒;无门族色、无背景板、无线宽层次 | -| 门盒贴线、略挤 | `COL_W=56`、盒 28×28、标签栏与第一列无独立 gutter | -| 测量/控点辨识弱 | 与单比特门同色同描边,缺少语义色 | - -**不在本切片**:交互拖拽、WebGL、外链字体、第二套 view 皮肤。 - ---- - -## 2. 业界对照(联网 2026-08) - -| 来源 | 可借鉴点 | 本仓取舍 | -|------|----------|----------| -| **Qiskit `iqp` / `iqp-dark`** | 门族 `displaycolor`(面色+字色);深色底;线色弱于门 | 移植**色板与分类**,不绑 matplotlib | -| **IBM Composer** | 经典门深蓝、相位门浅蓝、非酉灰;导出 light/dark | 默认 **dark tech**(view 卡片上更醒目);可选 `theme=light` | -| **Quirk** | 高对比栅格、测量仪表清晰 | 测量盒保留仪表符号,加强描边/填充对比 | -| **教科书 bw** | 印刷友好 | 保留为 `theme=bw` 后备,非默认 | - -**刻意避开**:紫白渐变「AI 默认皮肤」;过重 glow 光晕(打印/浅底卡片会糊)。科技感靠:**深 slate 底 + 青/靛门色 + 清晰层级 + 留白**,而非堆霓虹。 - ---- - -## 3. 视觉令牌(锁定 `marqdo-iqp`) - -### 3.1 主题 - -| `theme` | 用途 | -|---------|------| -| `dark`(**默认**) | view / 教学演示科技感 | -| `light` | 浅底文档打印 | -| `bw` | 无彩色、高对比 | - -作者面: - -```markdown -*`svg` = > `qc`.draw kind="circuit" theme="dark"* -*`svg` = > `qc`.draw kind="probs" theme="light"* -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `kind` | `circuit` | 既有枚举不变 | -| `theme` | `dark` | 新增;非法值报错 | -| `path` | — | 既有 | - -中文:`主题=dark|light|bw`。ABI:`quantum_draw_circuit` 增可选 `theme`(circuit/probs/bloch 已生效;gate/density 高级图见 Q8c)。 - -### 3.2 Dark 色板(默认) - -| 令牌 | 色 | 用途 | -|------|-----|------| -| `bg` | `#0a0e14` → `#141c28` 渐变 | SVG 圆角底板 | -| `wire` | `#6b7f96` | 比特线(双层描边) | -| `label` / `chip` | `#e8eef6` / `#1e2a3a` | `q0` 芯片标签(线不穿字) | -| `gate.clifford` | 面 `#4c6fff` / 字 `#f2f6ff` | H、X、Y、CX、SWAP… | -| `gate.phase` | 面 `#2de2e6` / 字 `#042024` | S、T、Rz、CZ… | -| `gate.rotation` | 面 `#3dd6c6` / 字 `#041a18` | Rx、Ry | -| `gate.measure` | 面 `#8fa3b8` / 字 `#0a1018` | MEASURE | -| `barrier` | `#9aafc0` 虚线 | BARRIER | -| `ctrl` | `#f0f5ff` | 控制点 / ⊕ | - -Light / bw 在实现里各给一套平行表;金样以 dark 主断言(SVG 含 `data-theme="dark"` 与背景色)。 - -### 3.3 布局(消灭粘连) - -```text -| pad | label_col | gutter | col0 | … | colN | pad | - ^q0 芯片标签 ^导线从此开始(不穿过文字) -``` - -| 常量 | 实现值 | -|------|--------| -| `LABEL_W` | 52 | -| `GUTTER` | 20 | -| `PAD_X` / `PAD_Y` | 24 / 36 | -| `COL_W` | 80 | -| `ROW_H` | 64 | -| 门盒 | 40×40,`rx=8` | -| 线宽 | 导线双层 3.2+1.8;门描边 ~1.1;控制竖线 2.25 | - -标签:圆角芯片 + 居中文字;导线 `x1 = PAD_X + LABEL_W + GUTTER`。 - -### 3.4 门族映射 - -| 族 | 门名(归一化后) | -|----|------------------| -| clifford | I X Y Z H CX CNOT SWAP | -| phase | S T RZ CZ | -| rotation | RX RY | -| measure | MEASURE M | -| barrier | BARRIER | -| custom / U | clifford 色或中性 `#546e7a` | - ---- - -## 4. 作者面(增量,向后兼容) - -见 §3.1。字符串参数须加引号:`kind="circuit"`、`theme="dark"`(中文 `种类=` / `主题=`)。改插件后须 `marqdo ext add quantum` 再开 view,否则仍加载旧 `.so`。 - ---- - -## 5. 分期 - -| 子阶段 | 内容 | 验收 | -|--------|------|------| -| **Q8a** | 电路轨线:布局 gutter + dark/light/bw 令牌 + 门族分色 | 标签不与线相交;SVG 含 `data-theme`;更新 draw smoke | -| **Q8b** | probs / bloch / gate heatmap 共用令牌 | 柱/球/热力与电路同族色 | -| **Q8c** | hinton / city / qsphere / paulivec / multibloch 换肤 | 高级图不「脱节」;viz-advanced smoke 仍绿 | - ---- - -## 6. 实现约束 - -1. 仅改 `plugins/quantum` 绘图 + L1 透传 `theme`;**不**改 Marqdo 核心。 -2. SVG **内联**颜色与字体栈(`ui-sans-serif, system-ui, …`);无 `@import` / CDN。 -3. view 仍走 `record_plot`;底板自带圆角矩形,避免白底卡片上「漂浮黑线」。 -4. 金样:断言结构标记(`data-theme`、`data-gate-family`)+ 既有 kind;不像素比对。 - ---- - -## 7. 非目标 - -- 复制 Qiskit matplotlib 像素级一致 -- 动画 / 3D 电路 -- 用户自定义完整 JSON 主题文件(可 Q9) - ---- - -## 8. 一句话 - -**先把字从线上挪开,再给门族涂上实验室色——默认 dark tech,打印用 light,论文用 bw。** diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md deleted file mode 100755 index f2bbd56..0000000 --- a/doc/design/ext-quantum.md +++ /dev/null @@ -1,425 +0,0 @@ -# 官方扩展:`ext/quantum` 量子计算模拟 - -| | | -|---|---| -| 状态 | **Accepted · Q0–Q7 完结 · Q8a/Q8b 完结**([ext-quantum-q7.md](ext-quantum-q7.md) · [ext-quantum-viz-style.md](ext-quantum-viz-style.md);Q8c 高级态图换肤待做) | -| 日期 | 2026-08-12(初版)· 2026-08-28(Q7 · Q8 viz) | -| 相关 | [stdlib-math.md](stdlib-math.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [ext-web.md](ext-web.md) · [view.md](view.md) · [stdlib-i18n.md](stdlib-i18n.md) · [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | -| 安装(目标) | `marqdo ext add quantum`(中英:`quantum` / `量子`) | -| 当前手册 | [根入口](../../ext/quantum/index.mq.md) · [中文入口](../../ext/quantum/量子/索引.mq.md) · [2026-11-08 优化记录](ext-quantum-handbook.md) | -| 本文目的 | 锁定**作者面**、**模拟语义**、**view 可视化**与**分期**;指导 ABI 插件实现 | - ---- - -## 0. 一句话 - -`ext/quantum` 用 **GFM 表格 + 类方法 +(可选)`$$` 狄拉克/矩阵公式** 描述量子门与电路;**经典状态向量模拟**给出概率与采样。 -文档能跑通,公式与电路约定就成立——这是 Marqdo「代码即文档」在量子教学上的最强展示位。 - -**不改 Marqdo 核心语法**;热路径只在 ABI 插件;**禁止**把量子核链进 `marqdo` 主二进制或在 `ext/**` 里调用 `host_*`。 - ---- - -## 1. 为何做量子扩展(与 math 的关系) - -### 1.1 与 `lib/math` 的相似处 - -| math | quantum | -|------|---------| -| `` `f` = `` + `$$…$$` → `formula` | 门矩阵 / 态矢量可用 `$$` **展示与核对** | -| 库函数对公式求值、求导、作图 | 类方法对电路施门、模拟、画图 | -| view 内嵌 SVG;CLI 可 `path=` | view 内嵌**电路图 / 概率条 / 布洛赫**;CLI 可落盘 | -| 金样例失败 = 文档/公式错 | 金样例失败 = 门定义或电路叙述错 | - -math 是**高中符号与曲线**;quantum 是**离散希尔伯特空间上的可执行电路文档**。两者都是「写出公式 → 跑通 → 证明文档正确」。 - -### 1.2 与 math 的刻意分界 - -| 做 | 不做 | -|----|------| -| 量子在 **`ext/quantum`**,经 `plugin.load` | **不**并进 `lib/math`(避免 stdlib 膨胀) | -| 复数振幅用 `{re, im}` map(与现有 `Value` 兼容) | **不**为量子在核心新增 `Value::Complex`(可二期) | -| 角度可用 `math.pi` 等常量 | **不**在 quantum 插件内重写 CAS | - -### 1.3 「代码即文档」在这里的作用 - -典型教学页: - -```markdown -# 贝尔态 |Φ+⟩ - -对 qubit 0 施 H,再 CNOT(0→1)。理想测量:`00` 与 `11` 各约 1/2。 - -# main - -`steps` = - -| 步 | 门 | 比特 | -|----|----|------| -| 1 | H | 0 | -| 2 | CX | 0,1 | - -*`qc` = > quantum.circuit qubits=2 steps=`steps` * -*`p` = > `qc`.probabilities * -``` - -- 叙述与表格是**给人看的电路说明**; -- 同一文件是**可执行程序**; -- gold / CI 断言概率 → **文档与物理约定同步**,无需另维护「幻灯片公式」。 - ---- - -## 2. 硬约束(评审锁定) - -1. **仅 ABI 插件接入**:`plugins/quantum` → `libquantum.so`;L1 在 `ext/quantum/*.mq.md`。 -2. **`ext/quantum/**` 禁止 `host_*`**;经 `plugin.native_path` + `plugin.load`(同 web/agent)。 -3. **中英分文件**:同一包 `ext/quantum/` 内英文模块树 + `量子/` 中文树,**禁止**混排 API([stdlib-i18n.md](stdlib-i18n.md))。 -4. **不改核心语法**;电路表单元格保持字面量;门名/比特下标由类方法解析。 -5. **模拟器有硬上限**(默认 ≤ 12 qubits);超限报错,不静默截断。 -6. **view 必须有专项展示**(结构卡 + 执行区 SVG),禁止只 dump JSON。 - ---- - -## 3. 布局与安装 - -Skill / tools 树(012 试点;契约 [ext-index-skill-tools.md](ext-index-skill-tools.md),范式 [ext-skill-tools-paradigm.md](ext-skill-tools-paradigm.md)): - -```text -ext/quantum/ # 一个扩展包(同 web/ai:中英同目录) - index.mq.md # EN 根 SKILL - circuit/ · gate/ · simulate/ · state/ · density/ · viz/ - _capability/index.mq.md - 量子/ # ZH 根与模块(同等 skill 标准) - 索引.mq.md - 电路/ · 门/ · 模拟/ · 态/ · 密度/ · 可视化/ · 能力/ -plugins/quantum/ - Cargo.toml - src/lib.rs # ABI v2 -examples/quantum-bell/ -tests/ext/quantum-*.mq.md -``` - -安装产物(`~/.marqdo/ext` 或 `MARQDO_EXT`,**不是**仓库 `ext/` 源码树): - -```text -quantum/... -native/libquantum.so -quantum.plugin # 绝对路径提示;勿提交 -``` - -```bash -cargo build -p marqdo_plugin_quantum -marqdo ext add quantum -``` - -导入: - -```markdown ---- -import: - quantum: ext/quantum/circuit/index.mq.md ---- -``` - -或中文:`导入 量子:ext/quantum/量子/电路/索引.mq.md`(根 skill:`ext/quantum/量子/索引.mq.md`)。 - ---- - -## 4. 核心模型 - -### 4.1 运行时句柄(JSON map + `_type`) - -| `_type`(英) | 中文类名 | 含义 | -|---------------|----------|------| -| `quantum_gate` | `量子门` | 具名门或自定义酉矩阵 | -| `quantum_circuit` | `量子电路` | n qubits + 有序门列表 | -| `quantum_state` | `量子态` | 状态向量(振幅列表) | -| `quantum_result` | `量子结果` | 概率 / 采样 / 可选坍缩态 | -| `quantum_svg` | (产物) | 带 `svg` 字段的可视化结果 | - -插件返回 map;Marqdo 对象系统挂 `_type` 后可用方法链。 - -### 4.2 状态表示 - -- **纯态**状态向量:长度 `2^n`,每元 `{re, im}`(f64)。 -- 默认初态:`|0…0⟩`(仅 index 0 振幅为 1)。 -- 门作用后可选重归一化(阈值误差阈值,默认开)。 - -### 4.3 公式面(对齐 math 精神,不抢 math 实现) - -允许用 `` `G` = `` + `$$…$$` 书写门矩阵(**可执行**,见 [ext-quantum-custom-gate.md](ext-quantum-custom-gate.md)): - -````markdown -`H_matrix` = -$$ -\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix} -$$ - -*`U` = > quantum.gate matrix=`H_matrix` * -*`qc` = > `qc`.apply gate=`U` qubits=0 * -*`ok` = > `H`.matches_matrix matrix=`H_matrix` * -```` - -- v1:**具名门**以插件内置酉矩阵为准;`matrix=` 可从嵌套 list / `$$` 矩阵围栏构造自定义门。 -- `$$` 含 `[[…]]` 或 `\begin{pmatrix}` 时解析期求值为数值 list;标量公式仍为 `Formula`。 -- `matches_matrix` 仍可用于核对。 ---- - -## 5. 作者面 API(锁定草图) - -### 5.1 英文 `ext/quantum/circuit/index.mq.md` - -```markdown -# gate - + `name`=None # H X Y Z S T I CX CZ SWAP … - + `theta`=None # Rx/Ry/Rz - -## matrix # → 振幅表 / 嵌套 list(文档与调试) -## draw # → quantum_svg(`kind=gate|matrix` 符号 / 热力图) -## matches_matrix - + `matrix` - + `tol`=1e-9 - -# circuit - + `qubits` - + `steps`=None # 可选:GFM 门序列表 - -## h / x / y / z / s / t - + `qubit` -## rx / ry / rz - + `qubit` - + `theta` -## cx / cz - + `control` - + `target` -## swap - + `a` - + `b` -## barrier # 仅可视化分隔,不改变态 -## measure # 标记测量(模拟时按计算基) - + `qubits`=None # 默认全部 -## append # 追加另一电路或门 - + `op` -## simulate # → quantum_state(不坍缩) -## probabilities # → map 基矢标签 → 概率 -## run - + `shots`=1024 - + `seed`=None # → quantum_result(计数直方图) -## draw - + `path`=None # SVG;无 path 时仍可进 view 产物 - + `kind`=circuit # circuit|probs|bloch|hinton|…(见 Q7) - + `theme`=dark # dark|light|bw(Q8;电路/概率/布洛赫) -## state # 当前缓存态(若已 simulate) -``` - -门方法返回**更新后的 circuit 句柄**(与 web `compose_*` 相同:`` `qc` = > `qc`.h qubit=0 *``)。 - -### 5.2 中文 `ext/quantum/量子/`(根 `索引.mq.md`) - -| 英文 | 中文 | -|------|------| -| `gate` | `门` | -| `circuit` | `电路` | -| `h` | `哈达玛` | -| `x` / `y` / `z` | `泡利X` / `泡利Y` / `泡利Z` | -| `cx` | `控非` | -| `cz` | `控相` | -| `rx`/`ry`/`rz` | `绕X`/`绕Y`/`绕Z` | -| `simulate` | `模拟` | -| `probabilities` | `概率` | -| `run` | `运行` | -| `draw` | `绘图` | -| `kind` | `种类` | -| `theme` | `主题` | -| `measure` | `测量` | -| `qubits` | `比特数` | -| `steps` | `步骤` | -| `shots` / `seed` | `次数` / `种子` | - -插件 FFI 名稳定英文:`quantum_circuit_new`、`quantum_h`、`quantum_cx`、`quantum_simulate`、`quantum_draw_circuit`… - -### 5.3 电路表(文档优先写法) - -```markdown -`steps` = - -| 步 | 门 | 比特 | 参数 | -|----|----|------|------| -| 1 | H | 0 | | -| 2 | CX | 0,1 | | -| 3 | RZ | 1 | pi/4 | -``` - -列名中英兼容:`步|step`、`门|gate`、`比特|qubits|qubit`、`参数|theta|params`。 - -*`qc` = > quantum.circuit qubits=2 steps=`steps` *` 与方法链**等价**;表更适合「整页即电路说明书」。 - -### 5.4 返回值形态 - -| 方法 | 返回 | -|------|------| -| `simulate` | `{_type, qubits, dim, amplitudes:[{re,im},…]}` | -| `probabilities` | `{ "00": 0.5, "11": 0.5 }`(标签为小端比特串,文档写死) | -| `run` | `{ counts: {…}, shots, seed }` | -| `draw` | `{_type: quantum_svg, kind: circuit\|gate\|probs\|bloch, svg: "…" }` | - ---- - -## 6. 模拟器语义 - -| 项 | 锁定 | -|----|------| -| 模型 | 封闭系统纯态;计算基测量 | -| 默认上限 | **12 qubits**;`MARQDO_QUANTUM_MAX_QUBITS` 可下调(不可暗中上调超过编译期硬顶,硬顶建议 16) | -| 超限 | 错误信息含当前 n 与上限 | -| `simulate` / `probabilities` | **无 RNG**、确定性 | -| `run` | 多项式采样;`seed=` 可复现(金样必用) | -| 数值 | f64;门后 ‖ψ‖ 偏离阈值则重归一化并可选 warning 字段 | - -实现:插件内 Kronecker / 按比特作用稀疏更新;可用 `nalgebra` 或手写,**不**捆绑外部量子云。 - ---- - -## 7. view 模式支持(专项) - -对齐 [view.md](view.md) 与 math 作图:**Structure / Execution / Source 共用渲染**;禁止第二套皮肤。 - -### 7.1 Structure(结构区) - -| 源形态 | 展示 | -|--------|------| -| `` `qc` = `` + 电路表 | **circuit-card**:比特数、门序列时间线(文本/紧凑 SVG) | -| `` `G` = `` + `$$` 门矩阵 | 沿用 **formula-card**(KaTeX);徽章可标 `gate`(若绑定来自 quantum.gate) | -| 方法链语句 | 普通调用行;不强制每步展开 | - -### 7.2 Execution(执行区) - -| 产物 | 展示 | -|------|------| -| `quantum_svg` | 与 math `plots` 同级:**内嵌 SVG**(电路轨线图 / 概率直方图 / 单比特布洛赫) | -| `probabilities` / `counts` | 表格 + 可选自动条形 SVG | -| `quantum_state` | 默认折叠振幅表;小 n(≤3)可并排显示基矢 | - -### 7.3 产物如何进入 view(实现锁定) - -插件**不能**直接碰核心 `HostContext.plots`。采用其一(实现时二选一,优先 A): - -| 方案 | 做法 | -|------|------| -| **A(推荐)** | ABI `host_query("record_plot")`:参数 JSON `{svg}`;写入与 math 相同的 plots 列表([ext-abi.md](ext-abi.md) allowlist 增补一条) | -| **B** | 仅返回 `quantum_svg`;view 在渲染执行值时识别 `_type`/`svg` 字段并内嵌(不扩 ABI) | - -CLI:`draw path=bell.svg` 写沙箱文件;无 path 时不把整段 SVG 灌 stdout(同 math §5)。 - -### 7.4 可视化内容(v1 必须 / 可后) - -| 图 | v1 | 说明 | -|----|----|------| -| 电路轨线(qubit 线 + 门盒 + 控点) | **必须** | `circuit.draw`;Q8 默认 `theme=dark`(标签芯片 + 门族分色) | -| 测量概率条形图 | **必须** | `probabilities` / `run` 后可 `draw kind=probs` | -| 单比特布洛赫球(SVG) | 应有 | 仅 n=1 或指定 qubit 约化(纯态投影) | -| 门矩阵热力图 | **必须** | `gate.draw kind=matrix`(幅值热图 + 小数标注) | -| 高级态图(hinton/city/…) | Q7 | 见 [ext-quantum-q7.md](ext-quantum-q7.md);换肤见 Q8c | -| 交互拖拽编辑电路 | **不做** | 静态文档足够 | - -视觉:内联 SVG 色与字体栈;**无外链**字体/CDN(同 view 硬规则)。主题令牌与布局:[ext-quantum-viz-style.md](ext-quantum-viz-style.md)。view 对 `svg[data-theme=dark]` 使用深色图框。 - ---- - -## 8. 分期(开发计划) - -```text -Q0 脚手架:CATALOG + plugins/quantum Hello + L1 ensure_plugin -Q1 态向量 + I/X/H/CX + simulate/probabilities;贝尔态 gold -Q2 Y/Z/S/T/Rx/Ry/Rz/CZ/SWAP + run(seed) + 中英 API 对齐 -Q3 电路表 steps= + draw 电路 SVG + view record_plot/识别;examples/ -Q5 教学噪声 + barrier/measure/append/state — 见 [ext-quantum-q5.md](ext-quantum-q5.md) ← **done(最小)** -``` - -| 阶段 | 交付物 | 验收 | -|------|--------|------| -| **Q0** | `marqdo_plugin_quantum` 注册 `quantum_ping`;L1 加载失败可读 | `ext add quantum` 路径通 | -| **Q1** | 贝尔态 `probabilities` ≈ 0.5/0.5 | `tests/ext/quantum-bell-smoke.mq.md` | -| **Q2** | 旋转门 + `run seed=` 计数稳定 | 中英双金样 | -| **Q3** | `steps=` 表;`draw` SVG 在 `view` HTML 含 ` quantum.circuit qubits=2 steps=`steps` * -*`p` = > `qc`.probabilities * -*`svg` = > `qc`.draw * - -> print text=`p` -``` - -中文面对称:`量子.电路`、`哈达玛`、`控非`、`概率`、`绘图`。 - ---- - -## 10. 刻意不做(本 Accepted 范围) - -- 真机 / 云后端(IBM、Braket…) -- 开放系统、完整噪声模型(可 Q5+) -- 符号电路编译优化器 -- 交互式电路编辑器 -- 把量子并入 `lib/math` 或核心 opcode -- 无上限比特的「生产级」模拟 - ---- - -## 11. 开放点(已收敛 / 剩余) - -| 议题 | 结论 | -|------|------| -| 对象面 vs 自由函数 | **主推对象/方法链**;自由函数不平行提供 | -| 电路表 | **v1 纳入**(Q3),与方法链等价 | -| 振幅过大 | v1 全进 Value;n≤12 可接受;超限已挡 | -| view 产物 | **优先** `host_query("record_plot")` | -| 与 web | **不依赖** web 做可视化;SVG 自绘 | - ---- - -## 12. 评审清单 - -1. ABI-only + 中英分文件是否认可? -2. 默认 12 qubits 上限是否合适? -3. 电路表列设计(步/门/比特/参数)是否够用? -4. view:电路轨线 + 概率条为 v1 必须,是否同意? -5. `$$` 矩阵核对放 Q4,是否同意先表驱动? - -评审通过后:本文冻结为 Accepted → 按 §8 从 Q0 实现。 - ---- - -## 13. 一句话 - -**表格写出电路,类方法模拟与绘图;跑通金样即证明文档中的量子公式与步骤成立——math 管曲线,quantum 管希尔伯特空间上的可执行说明书。** diff --git a/doc/design/ext-skill-tools-paradigm.md b/doc/design/ext-skill-tools-paradigm.md deleted file mode 100755 index e9d6482..0000000 --- a/doc/design/ext-skill-tools-paradigm.md +++ /dev/null @@ -1,227 +0,0 @@ -# 扩展库开发范式:code = document = skill = tools - -| | | -|---|---| -| 状态 | **Active**(quantum 试点已落地;其它官方扩展按本范式推广) | -| 日期 | 2026-11-06 | -| 愿景 | [doc/next/012.md](../next/012.md)(手写真相源,本文不修改它) | -| 契约摘要 | [ext-index-skill-tools.md](ext-index-skill-tools.md) | -| 试点 | [`ext/quantum/`](../../ext/quantum/)(完成)· [`ext/web/`](../../ext/web/)(迁移中,含[布局范式](ext-web-layout-paradigm.md)) | -| 相关 | [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md) · [ext-quantum.md](ext-quantum.md) · [lib-code-as-docs.md](lib-code-as-docs.md) · [stdlib-i18n.md](stdlib-i18n.md) | - ---- - -## 0. 一句话 - -一份 `.mq.md` **同时是**可执行代码、给人读的文档、给智能体的 SKILL、以及可 `marqdo call` 的 tools 面。 -**函数即工具**(`##`),**子函数即子工具**(`###`)。禁止旁路 catalog / OpenAPI / MCP 包装成为第二真相源。 - ---- - -## 1. 为什么这样设计 - -| 传统拆法 | 本范式 | -|----------|--------| -| README + SDK + tool schema 三套漂移 | 同一文件既可跑又可讲 | -| Agent 调 MCP,作者调库 API | 智能体与作者共读同一路径;智能体默认 `marqdo call` | -| 扩展 = 功能清单 | 扩展 = 可执行知识包:根 skill 先教会「怎么调」 | - -智能体冷启动时只应:打开根 `index.mq.md` → 按「选哪条路」→ 照抄 `marqdo call`。不必发明第二套 API。 - ---- - -## 2. 包布局(强制形态) - -一个官方扩展 **一个目录**(与 `web` / `ai` 一致)。中英 **同包分文件**,不要把中文树抬到 `ext/` 顶层变成「第二个包」。 - -```text -ext// - index.mq.md # EN 根 SKILL(先读) - /index.mq.md # 模块:## call 工具 + 可选 # 作者对象 - _capability/index.mq.md # 仅插件加载(日常勿当业务工具) - <中文名>/ # ZH 镜像树(同等标准) - 索引.mq.md - <模块>/索引.mq.md -``` - -试点现状: - -```text -ext/quantum/ - index.mq.md · circuit/ · gate/ · simulate/ · state/ · density/ · viz/ - _capability/ - 量子/索引.mq.md · 电路/ · 门/ · 模拟/ · 态/ · 密度/ · 可视化/ · 能力/ -``` - -安装后落在 `~/.marqdo/ext`(或 `MARQDO_EXT`),**不是**仓库源码 `ext/`: - -```text -~/.marqdo/ext/ - quantum/... - native/libquantum.so - quantum.plugin # 路径提示;勿提交源码树 -``` - ---- - -## 3. 根 skill 怎么写 - -根 `index.mq.md` / `索引.mq.md` 是冷启动入口,须按顺序包含: - -1. **选哪条路**(表格,勿用 `1.` 列表——在 Marqdo 里 `1.` 是分支语法) - - 只要演示结果 → 根上的编排工具(如 `bell_phi_plus` / `贝尔态`) - - 要句柄继续 → 贴出分步 `call`(同一 `--session` + `--toget`) - - 换语言 → 指向另一语言树,禁止混用 EN/ZH 工具名 -2. **如何执行任意工具**:固定 CLI 形状、`--effects plugin`、`--json`、`$name` -3. **包布局**:每个模块路径 + 一句用途 -4. **可选一键编排工具**(如贝尔态):无参或极少参,便于验收 - -智能体默认路径是 `##` + `marqdo call`。`# circuit` / `# 电路` 等对象是 **作者程序** import 用的,须在根 skill 写明,避免代理误走方法链。 - ---- - -## 4. 模块文件怎么写 - -每个 `index.mq.md` 单独拿到也要能用: - -| 块 | 要求 | -|----|------| -| 开篇叙述 | 领域是什么、何时打开本文件 | -| For AI agents / 给智能体 | 可照抄的 `marqdo call`;缺能力时 **写明下一步打开哪个兄弟模块**(例如 circuit 造线后概率在 simulate) | -| `##` 工具 | 形参契约表紧贴标题下;返回契约表也在首条执行语句前(当前解析器边界);叙述 ≥ 50% | -| `#` 对象(可选) | 作者链式 API;加载插件走 facade(如 `cap.load` / `能力.加载`),禁止作者面 `host_*` | - -薄实现:工具体调用 ABI(`*> quantum_…*`)或转发兄弟模块即可,真相在叙述与契约表。 - ---- - -## 5. `marqdo call` 与会话 - -```text -marqdo call [k=v…] - [--json] - [--effects none|plugin] # 默认 none;ABI 扩展必须 plugin - [--session ] - [--toget ] # 或尾部 toget -``` - -| 机制 | 用途 | -|------|------| -| `--effects plugin` | 允许 `plugin.call`;仍拒 fs/network/process/llm 等 | -| `--session` + `--toget` | 跨进程保存返回值;`$name` 引用;plugin 句柄经 journal 重放 | -| `parent.child` | 嵌套 `###` 子工具 | - -参数字面量:数字、引号文本、True/False/None、以 `[`/`{` 开头的 JSON、或 `$name`。 - ---- - -## 6. 叙述 ≥ 50% - -```bash -marqdo check --narrative-ratio ext//path/index.mq.md -``` - -- 按函数单元计;契约表计为叙述;语言代码围栏计为代码。 -- 试点包 `ext/quantum/**` **零豁免**(含 `_capability` 与中文树)。 -- 狗粮 skill:`lib/lint/narrative.mq.md`。 - ---- - -## 7. ABI 与 capability - -- 原生能力只经 `plugin.native_path` + `plugin.load`(集中在 `_capability` / `能力`)。 -- 领域模块在工具开头调用 `cap.load` / `能力.加载`,**不**把 capability 当日常业务工具。 -- 遵守 ADR 0007:作者程序与 `ext/**` 业务面不写 `host_*` / `ensure_plugin` 垃圾抽屉。 - ---- - -## 8. 中英与导入 - -| 规则 | 做法 | -|------|------| -| 分文件 | EN 与 ZH 两套树;禁止同一文件混排 API 名 | -| 同包 | `ext//` 内放中文子树,勿 `ext/<中文包名>/` 顶层并列 | -| 作者导入 | `import: circuit: ext/quantum/circuit/index.mq.md` → `circuit.circuit` | -| 中文导入 | `导入 量子:ext/quantum/量子/电路/索引.mq.md` → `量子.电路` | -| 智能体 | 打开对应语言的根 skill,工具名与路径保持同语言 | - ---- - -## 9. 安装与源码卫生 - -```bash -cargo build -p marqdo_plugin_ # 若有原生插件 -MARQDO_EXT_SOURCE=/path/to/repo/ext \ - marqdo ext add # 装到 ~/.marqdo/ext -``` - -| 禁止 | 原因 | -|------|------| -| `MARQDO_EXT` 指向仓库 `ext/` 再 `ext add` | 同文件 `fs::copy` 会清空源码;并写入 `*.plugin` / `native/` | -| 提交 `ext/*.plugin`、`ext/native/` | 安装产物;已 gitignore | - -`marqdo ext add` **拒绝**把安装根设成源码 `ext/`(防再踩坑)。 - ---- - -## 10. 常见陷阱 - -| 陷阱 | 正确做法 | -|------|----------| -| 正文写 `1. xxx` 当条目 | 用表格或项目符号;`1.` 是分支 | -| 漏 `--effects plugin` | 根 skill 与模块 For AI 段反复写明 | -| 只发 `circuit` 文件却找 `probabilities` | 在 circuit 的智能体段贴出 simulate 的完整 call | -| 智能体去调 `#` 对象方法 | 根 skill「选哪条路」声明默认走 `##` call | -| 中英混用 `新建` + `ext/quantum/circuit` | 选定一棵树用到底 | -| 用「兼容层」大文件双挂 API | 删除;模块树即唯一面 | - ---- - -Quantum 的完整实验、开发路线与源码示例门禁,见 [2026-11-08 手册修正](ext-quantum-handbook.md)。叙述比例是最低门槛,不能替代照抄执行与独立期望验证。 - -## 11. 开发验收清单 - -新扩展或把旧包迁到本范式时,逐项打勾: - -- [ ] `ext//index.mq.md`:选哪条路 + call 形状 + 布局 +(可选)一键编排 -- [ ] 每个模块 `index.mq.md`:For AI agents 可单独照抄;缺能力时指向兄弟模块 -- [ ] 全部 `.mq.md`:`marqdo check --narrative-ratio` 通过 -- [ ] 需要 ABI:`_capability` 唯一加载;领域只调 facade -- [ ] 中文:同包子树,路径与 ## 名全中文 -- [ ] `ext_cli` catalog 的 `mq_files` 列全 EN+ZH 源文件 -- [ ] 金样:`marqdo call` 一键工具 +(若有句柄)分步 `--session`/`--toget` -- [ ] 作者 smoke:import 模块后的 `#` 对象链仍绿 -- [ ] 未把安装产物写进仓库 `ext/` - ---- - -## 12. 智能体视角(试点自检) - -任务「制备 Bell 态」时,合格根 skill 应使代理: - -1. 打开 `ext/quantum/index.mq.md`(或中文 `量子/索引.mq.md`) -2. 只要结果 → `bell_phi_plus` / `贝尔态` -3. 要句柄 → 照抄 circuit→simulate 四条 call,同一 session - -不必阅读 gate/density,不必发明 Python/MCP。 - ---- - -## 13. 推广顺序(建议) - -1. **已完成试点**:`ext/quantum/`(含 `量子/`) -2. **进行中**:`ext/web/` — 根 `index` + `layout` + 模块树 `page|route|…/index.mq.md` + 中文 `网页/`;作者门面 `web.mq.md`/`网页.mq.md` 保持兼容;call 金样与站点示例对齐继续补齐 -3. **下一优先**:`linalg` 公式面、`ai` agent 面 -4. **`ext/net` / `ext/data` / `ext/security`**:随 web 站点场景补根 skill,勿把 DB/鉴权 API 塞回 `web` facade - -每迁一包:更新本文件「试点/推广」表与该包 `doc/design/ext-*.md` 布局节,并加 call 金样。 -**Web 特有**:布局工程必须写进包内 skill(见 [ext-web-layout-paradigm.md](ext-web-layout-paradigm.md)),不能只放在外部 README。 - ---- - -## 14. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-11-06 | web:模块树 + `网页/` 镜像 + page session call 金样推进 | -| 2026-11-06 | 初版:由 quantum 试点归纳的整包开发范式与验收清单 | diff --git a/doc/design/ext-web-artifact.md b/doc/design/ext-web-artifact.md deleted file mode 100755 index ed49056..0000000 --- a/doc/design/ext-web-artifact.md +++ /dev/null @@ -1,209 +0,0 @@ -# 官方扩展:Web Artifact(Document / Endpoint / Resource) - -| | | -|---|---| -| 状态 | **Accepted · 破坏性(取代 page/app God Object 作者面)** | -| 日期 | 2026-09-28 | -| ADR | [0007-web-document-endpoint.md](../adr/0007-web-document-endpoint.md) | -| 讨论稿 | [doc/next/007.md](../next/007.md)(superseded) | -| 安装 | `marqdo ext add web`(`web` / `网页`) | -| 相关 | [binding.md](binding.md) · [ext-web.md](ext-web.md) · [ext-web-layout-paradigm.md](ext-web-layout-paradigm.md) · [ext-skill-tools-paradigm.md](ext-skill-tools-paradigm.md) · [stdlib-i18n.md](stdlib-i18n.md) · [layers.md](layers.md) | - ---- - -## 0. 一句话 - -> **Document describes the page. Table describes the data. Endpoint describes the interaction. Metadata describes the runtime. Marqdo executes all of them.** - ---- - -## 1. 三原语 - -| Artifact | Metadata `type` / `类型` | 含义 | -|----------|--------------------------|------| -| **Document** | `web` / `网页` | Markdown 正文 + View → HTML;`route`/`路由` 注册 declared HTTP | -| **Endpoint** | `endpoint` / `端点` | 可执行正文为 handler;`path`+`method` 注册 API | -| **Resource** | (绑定/导入) | `ext/data` · `ext/security` · 未来 LLM 等,经 metadata / import 声明 | - -核心装载识别 `type`/`类型`(见 `src/artifact/`);渲染与 listen 在 `ext/web` + `plugins/web`。 - ---- - -## 2. 目录 - -```text -ext/web/ - index.mq.md · 网页.mq.md # 根 skill(智能体先读;含布局铁律) - layout/ · 布局/ # 文件划分布局工程 tools - web.mq.md # EN facade: page route serve render inspect - page.mq.md · route.mq.md · component.mq.md · dom.mq.md · client.mq.md -ext/net/ http.mq.md · websocket.mq.md · url.mq.md -ext/data/ db.mq.md · cache.mq.md · storage.mq.md -ext/security/ auth.mq.md · oidc.mq.md · rbac.mq.md -``` - -**布局工程**(反 HTML/CSS 注入):见 [ext-web-layout-paradigm.md](ext-web-layout-paradigm.md);包内 `ext/web/layout/index.mq.md`。 - -作者入口通常: - -```text -site/ - index.mq.md # type: web · route: / · 或 # main → web.serve - pages/*.mq.md # type: web - api/*.mq.md # type: endpoint - data/ # sqlite runtime (gitignore) -``` - ---- - -## 3. Document(`type: web`) - -```markdown ---- -type: web -title: Marqdo Blog -route: / -method: GET -data_source: posts -data_order: -created_at -import: - web: ext/web/web.mq.md - data: ext/data/db.mq.md ---- - -# Marqdo - -Welcome to the executable web. -``` - -| 键 (EN) | 键 (ZH) | 说明 | -|---------|---------|------| -| `type` | `类型` | `web` / `网页` | -| `route` | `路由` | 路径,可含 `{param}` | -| `method` | `方法` | 默认 `GET` | -| `view` | `视图` | 可选 main:启动时执行主程序,返回递归 View 节点;不与自动 data_source 绑定混用 | -| `title` | `标题` | 文档标题 / `` | -| `data_source` | `数据源` | 表名 | -| `data_order` | `排序` | 如 `-created_at` | -| `data_where` | `条件` | `col=val,col2=val2` | - -正文 Markdown 经 `dom` 变为 DOM Artifact,再 `web.render`。可选 View 表: - -```markdown -`nodes` = - -| type | slot | value | attrs | style | -|------|------|-------|-------|-------| -| text | kicker | AI Native | | eyebrow | -| title | title | Marqdo | | title | -``` - -2026-11-08:View 已支持 row/column 容器与 markdown 叶子,容器值保持子表;显式 `view: main` Document 通过普通函数装配。 - -2026-11-10:同一五列 View 可放置具型 Resource 节点;结构仍只在启动时装配,数据查询、已挂载表单与会话导航在请求期间解析。无新增 frontmatter 或核心标记;见 [请求资源](web-view-resources.md)。普通离线渲染缺少请求上下文时明确报错,不伪造动态内容。完整工程见[布局实践](ext-web-layout-paradigm.md),实现边界见[优化说明](ext-web-handbook.md)。 - -`page.render nodes=` 是**唯一**主装配路径。禁止 `compose_main` / `compose_intro` 等碎片 DSL。 - ---- - -## 4. Endpoint(`type: endpoint`) - -```markdown ---- -type: endpoint -method: POST -path: /api/posts -request: json -response: json -auth: member -import: - data: ext/data/db.mq.md ---- - -**post = > data.db.insert …** - -*post* -``` - -| 键 (EN) | 键 (ZH) | 说明 | -|---------|---------|------| -| `type` | `类型` | `endpoint` / `端点` | -| `path` | `路径` | URL | -| `method` | `方法` | GET/POST/… | -| `request` | `请求` | `json` / `form` / `none` | -| `response` | `响应` | `json` / `text` / `html` / `sse`(`text/event-stream`) | -| `auth` | `鉴权` | 角色名或 `none`;`bearer` / `api_key` = 不要求 cookie,把 `Authorization` / `X-Api-Key` 注入 payload 由 `# main` 校验 | - -正文在请求时执行;返回值按 `response` 序列化。Result 协议见 §8。 - -**Handler 约定(锁定)**:Endpoint 文件用 `# main` 作为请求处理器。请求体/query/path 参数经 `run_artifact` 以 Metadata Binding 覆盖注入(与 `--bind` 同源),正文用已提升的普通变量名。无 `# main` 时返回 Artifact Result 摘要(`ok`/`value`/`error`),适合作文档型 ping。 - ---- - -## 5. Facade API(EN / ZH) - -| EN | ZH | 作用 | -|----|-----|------| -| `web.page` | `网页.页面` | 从 metadata/正文/nodes 构造 Document 句柄 | -| `web.route` | `网页.路由` | 注册 declared Document 或 Endpoint | -| `web.serve` | `网页.服务` | `root=` 扫描注册 + listen | -| `web.render` | `网页.渲染` | Document → HTML(离线/预览) | -| `web.inspect` | `网页.检视` | `{declared, system}` 路由表 | - -Middleware 一等:`web.use` / `route.use`,表驱动;**禁止** `configure(cors, security, …)` 垃圾抽屉。 - ---- - -## 6. 发现算法(锁定) - -`web.serve root=DIR host=… port=…`: - -1. 递归枚举 `DIR` 下 `*.mq.md`(跳过 `data/`、隐藏目录、`node_modules`)。 -2. 解析文件头 Metadata;无 `type`/`类型` 或非 web/endpoint → 跳过。 -3. Document → declared route(缺 `route` 则相对 `root` 的路径映射,`index.mq.md` → `/`)。 -4. Endpoint → declared path+method(`path`/`路径` 必需)。 -5. System routes(`/_part/*`、`/_form/*`、静态等)由 runtime 挂载,仅出现在 `inspect.system`。 -6. 调用 native listen。 - ---- - -## 7. Table 规则 - -- **View**:仅 `|type|slot|value|attrs|style|`(及列名 ZH 别名:`类型|槽|值|属性|样式`)。 -- **Resource schema**:`|字段|类型|可空|` 等 — 专用且文档化,不是函数私有方言。 -- **禁止** `|属性|值|样式|` / `|front|back|css|` / `|组件|样式|` 作为页面主装配(已删除)。 -- Raw HTML/CSS = escape hatch(`dom.raw` / `page.css`),不是默认语言。 - ---- - -## 8. Result - -所有易失败的 Resource / Endpoint 边界返回 map: - -| 键 | 类型 | 说明 | -|----|------|------| -| `ok` | bool | 成功 | -| `value` | any | 成功载荷 | -| `error` | text \| None | 失败信息 | - ---- - -## 9. 硬约束(取代旧 C1–C7 作者面) - -| # | 约束 | -|---|------| -| A1 | Document/Endpoint 由核心识别 `type`;装配在 ext(ADR 0007) | -| A2 | 禁止 `json.set` 袋胶水;Table = Data | -| A3 | 中英分文件;同文件禁止混 API | -| A4 | 禁止作者 `ensure_plugin` / `host_*` | -| A5 | 禁止隐式用户 route;system 须 `inspect` 可见 | -| A6 | 禁止恢复 `compose_*` / `app.configure` / god page 变异堆 | -| A7 | 能力只许迁移/提升;删除须本设计明示 + tests 同步 | -| A8 | 设计未锁定处停工提问,禁止自行发明 DSL | -| A9 | **文件划分布局**:页面拆到简单组件文件为止;默认禁止整页 HTML/CSS 注入(`dom.raw`/`page.css` 仅逃逸舱) | - ---- - -## 10. 与旧 ext-web.md - -旧「页面表 + compose_* + app.route」作者面 **废止**。历史能力矩阵见 [web-net-capabilities.md](web-net-capabilities.md);迁移后以本文件与 ADR 0007 为准。 diff --git a/doc/design/ext-web-collab.md b/doc/design/ext-web-collab.md deleted file mode 100755 index a8e4de8..0000000 --- a/doc/design/ext-web-collab.md +++ /dev/null @@ -1,19 +0,0 @@ -# Collaborative document MVP - -| | | -|---|---| -| 状态 | **Accepted · MVP (LWW)** | -| 日期 | 2026-09-17 | - -## Approach - -Not a full CRDT. Peers sync plain text over `route_ws mode=room` with: - -- Client → server: `DOC\\t<body>` -- Server fan-out (existing G-WS1/2) -- Apply remote if body ≠ local; `applying` flag suppresses echo -- Presence JSON on `room.presence` (`presence=True`) - -## Demo - -`examples/web-collab-doc/` — open two browsers on the same room. diff --git a/doc/design/ext-web-customization/01-routes-and-admin-prefix.md b/doc/design/ext-web-customization/01-routes-and-admin-prefix.md deleted file mode 100755 index 8fd2a4e..0000000 --- a/doc/design/ext-web-customization/01-routes-and-admin-prefix.md +++ /dev/null @@ -1,74 +0,0 @@ -# 解决 1:路由与 `/admin` 前缀可让出 - -| | | -|---|---| -| 问题 | [研究 §1](../../research/ext-web-customization-limits.md#1-路由与路径被框架强占) | -| 优先级 | **P0** · 波次 **C0** | -| 触点 | `plugins/web/src/lib.rs`(`normalize_route_path`、`web_app_new`、redirect)· `plugins/web/src/http.rs`(admin 路由挂载、login redirect)· `ext/web/web.mq.md` / `网页.mq.md` | - ---- - -## 1. 目标 - -1. 关闭内置后台后,**整段前缀可被站点路由占用**(含自研 `/admin`)。 -2. 开启内置后台时,前缀**可配置**(默认仍 `/admin`),登录成功/登出落地页可配置。 -3. `app.route` / `app.redirect` 只禁止**当前生效**的框架保留段,不再永久霸占 `/admin`。 - ---- - -## 2. 作者 API(草案) - -```markdown -*应用 = > web.app page=`首页` db=`库` admin=False* - -# 或:仍用内置 CRUD,但挂到旁路前缀 + 自定义回跳 -*应用 = > web.app page=`首页` db=`库` admin=True* -*应用 = > `应用`.auth users=`用户表` admin_prefix="/desk" login_redirect="/desk" logout_redirect="/desk/login"* -``` - -| 参数 | 默认 | 含义 | -|------|------|------| -| `admin` / `后台` | `False` | `False`:**不注册**任何内置 admin HTTP 路由 | -| `admin_prefix` / `后台前缀` | `"/admin"` | 内置 CRUD + 登录页挂载根;仅 `admin=True` 时生效 | -| `login_redirect` / `登录回跳` | `{admin_prefix}` | 登录成功 303 目标 | -| `logout_redirect` / `登出回跳` | `{admin_prefix}/login` | 登出后目标 | - -中文别名与英文一一对应,写进 `网页.mq.md`。 - ---- - -## 3. 插件改动点 - -| 改动 | 说明 | -|------|------| -| `normalize_route_path(app)` | reserved 列表改为:`/_form`、`/_part`、`/static` + **当前** `admin_prefix`(仅当 `admin=True`) | -| `listen` 路由表 | `admin=False` → **不** `.route("/admin…")`;为真则用 `admin_prefix` 拼路径 | -| `admin_login_post` / `admin_logout` | 使用配置的 redirect,禁止写死 `"/admin"` | -| `web_app_redirect` | 校验目标时用同一套动态 reserved,允许指向已让出的 `/admin` | -| disabled 文案路径 | 删除「挂路由但只显示 Admin is disabled」;无路由则 404 或落入站点自定义页 | - ---- - -## 4. 兼容策略 - -- 缺省参数下:现有 `examples/web-site`、`web-net-site`、`marqdo-blog` 行为不变(仍 `/admin` + 跳 `/admin`)。 -- 文档明确:`admin=False` 后若仍要登录能力,用 §3 的通用 `auth`/`gate`,不必再依赖内置 admin 壳。 - ---- - -## 5. 验收 - -| 金样 / 手工 | 期望 | -|-------------|------| -| `admin=False` + `route path="/admin/news"` | 注册成功;GET 渲染站点页,**不是** Admin is disabled | -| `admin_prefix="/desk"` | 内置登录在 `/desk/login`;成功跳 `login_redirect` | -| 默认 `admin=True` 无新参数 | 与现网一致 | -| `redirect` 到已让出的 `/admin` | 允许 | - ---- - -## 6. 过渡期 → 已落地 - -~~继续用 `/desk` 旁路 + JS 调 `/admin/login`。~~ - -**C0 已落地(2026-09):** `admin=False` 可直接 `route path="/admin/…"`;或 `admin=True` + `admin_prefix="/desk"` + `login_redirect` / `logout_redirect`。见金样 `tests/ext/web-c0-admin-prefix.mq.md`。 diff --git a/doc/design/ext-web-customization/02-shell-css.md b/doc/design/ext-web-customization/02-shell-css.md deleted file mode 100755 index 7577f70..0000000 --- a/doc/design/ext-web-customization/02-shell-css.md +++ /dev/null @@ -1,72 +0,0 @@ -# 解决 2:`SHELL_CSS` 可关 / 可分层 - -| | | -|---|---| -| 问题 | [研究 §2](../../research/ext-web-customization-limits.md#2-内置-shell_css-难以彻底覆盖) | -| 优先级 | **P1** · 波次 **C2** | -| 触点 | `plugins/web/src/render.rs`(`SHELL_CSS`、`<style>` 拼接)· page/app 元数据 · `ext/web` 样式装配 | - ---- - -## 1. 目标 - -1. 站点主题可选择:**不要**框架栅格/卡片默认,或只要 reset 级变量。 -2. 壳 CSS 与主题 CSS 的级联顺序**可声明、可文档化**。 -3. 默认仍注入完整壳(兼容旧站);新主题显式 `shell_css=off` 即可干净起步。 - ---- - -## 2. 作者 API(草案) - -```markdown -*应用 = > web.app page=`首页` … shell_css="minimal"* -# 或页面级覆盖 -*页 = > `页`.meta …* # 或 page 选项 shell_css= -``` - -| 值 | 行为 | -|----|------| -| `full`(默认) | 现网 `SHELL_CSS` 全文 | -| `minimal` | 仅 `:root` 变量 + `body` margin/字体;**不含** `has-sidebar` 双列栅格与卡片表单皮肤 | -| `off` / `none` | 不注入框架壳样式;只输出站点 `style` / 外链 CSS | - -级联顺序锁定为文档约定: - -1. (可选)框架 `SHELL_CSS` -2. 站点全局 style 表 / `site.css` -3. 页面级 style - -禁止再出现「主题写在 extra,却被同特异性壳规则在小屏打穿且无媒体查询」而无开关可关的情况。 - ---- - -## 3. 插件改动点 - -| 改动 | 说明 | -|------|------| -| 拆分 `SHELL_CSS` | `SHELL_VARS` / `SHELL_LAYOUT` / `SHELL_WIDGETS` 三段;`full`=`all`,`minimal`=vars(+极简 layout) | -| `render` 读 `app.shell_css` / `page.shell_css` | 页面覆盖应用 | -| 为 `has-sidebar` 布局加基础媒体查询 | 即使 `full`,小屏改为单列(减轻幽灵双列);`minimal`/`off` 不负责响应式 | - ---- - -## 4. 兼容策略 - -- 默认 `full`:视觉与现网一致。 -- Tutorial 增加一节「品牌主题请用 `shell_css=minimal|off`」。 - ---- - -## 5. 验收 - -| 场景 | 期望 | -|------|------| -| `shell_css=off` + 站点只写单列 grid | 响应里**无** `grid-template-columns:14rem` | -| `minimal` | 有 CSS 变量;无 `.content.cards article` 边框默认(或等价皮肤段) | -| 默认示例站 | HTML 仍含完整壳 CSS | - ---- - -## 6. 过渡期 → 已落地 - -**C2 已落地(2026-09):** `shell_css=full|minimal|off`;页面/应用可设;`full` 含 `@media (max-width:720px)` 单列。金样 `tests/ext/web-c2-shell-layout.mq.md`。 diff --git a/doc/design/ext-web-customization/03-auth-gates.md b/doc/design/ext-web-customization/03-auth-gates.md deleted file mode 100755 index d74d236..0000000 --- a/doc/design/ext-web-customization/03-auth-gates.md +++ /dev/null @@ -1,72 +0,0 @@ -# 解决 3:鉴权 / 门禁可配置且行为一致 - -| | | -|---|---| -| 问题 | [研究 §3](../../research/ext-web-customization-limits.md#3-鉴权--门禁模型偏固定) | -| 优先级 | **P0** · 波次 **C1**(依赖 [01](01-routes-and-admin-prefix.md) 的 prefix) | -| 触点 | `plugins/web/src/http.rs`(`rbac_middleware`、`path_matches`、login 表单)· `lib.rs`(`web_app_auth` / `web_app_gate`)· `ext/web` | - ---- - -## 1. 目标 - -1. **未登录策略一致**:可配置 `redirect`(303 登录)或 `forbid`(403),对任意 gate 路径生效,不再「仅 `/admin*` 会跳登录」。 -2. **匹配语义清晰**:支持精确路径、前缀、以及排除列表;`/desk` 默认**不**误伤 `/desk/login`。 -3. 默认 admin gate 使用 **路径段边界**(`/admin` 与 `/admin/…`),不匹配 `/admin-publish`。 -4. 登录 URL、表单 `action`、成功/失败回跳均可配置(与 C0 对齐)。 - ---- - -## 2. 作者 API(草案) - -```markdown -*应用 = > `应用`.auth users=`用户表` login_path="/desk/login" login_redirect="/desk"* -*应用 = > `应用`.gate path="/desk" roles="admin" match="prefix" on_deny="redirect" exclude="/desk/login"* -``` - -| 字段 | 说明 | -|------|------| -| `login_path` | 登录页 URL(GET 表单 + POST 处理);默认 `{admin_prefix}/login` | -| `match` | `exact` \| `prefix`(默认对自定义 gate 建议 `prefix` + `exclude`) | -| `on_deny` | `redirect` \| `forbid`;`redirect` 时跳 `login_path`(可带 `?next=`) | -| `exclude` | 逗号分隔或表列:匹配前缀时放行的路径 | - -`auth` 注册默认 gate 时: - -- 使用 `{admin_prefix}` + 段边界,**不要** `starts_with("/admin")` 裸前缀。 -- 自动把 `login_path` 加入放行列表。 - ---- - -## 3. 插件改动点 - -| 改动 | 说明 | -|------|------| -| `path_matches` | 增加 `exact`;`prefix` 要求下一字符为 `/` 或结尾;可选 exclude | -| `rbac_middleware` | 按 gate 的 `on_deny` 分支;通用放行 `login_path`,不写死 `/admin/login` | -| 登录 HTML | `action={login_path}`;hidden `next` 可选 | -| Session/CSRF | 短期仍用框架实现;文档标明字段名;中期再开放 `login_form` 自定义字段映射(非本波次必做) | - ---- - -## 4. 兼容策略 - -- 未传新字段:行为对齐现网(`/admin*` → redirect 登录;其它自定义 gate → 403)。 -- 新增金样:`/desk` gate + `/desk/login` 可匿名打开。 - ---- - -## 5. 验收 - -| 场景 | 期望 | -|------|------| -| visitor 访问 `/desk`(`on_deny=redirect`) | 303 → `/desk/login`,不是 403 | -| visitor 访问 `/desk/login`(exclude) | 200 登录页 | -| `/admin-publish` 无显式 gate | **不**被默认 admin gate 拦住 | -| 旧站仅 `app.auth` | 仍保护 `/admin*` | - ---- - -## 6. 过渡期 → 已落地 - -**C1 已落地(2026-09):** `auth` 默认段边界 prefix + `on_deny=redirect` + 排除 `login_path`;自定义 `gate` 可设 `match` / `on_deny` / `exclude`。金样 `tests/ext/web-c1-gates.mq.md`;单元测试 `http::gate_tests`。 diff --git a/doc/design/ext-web-customization/04-stylesheet-authoring.md b/doc/design/ext-web-customization/04-stylesheet-authoring.md deleted file mode 100755 index 98cb3c3..0000000 --- a/doc/design/ext-web-customization/04-stylesheet-authoring.md +++ /dev/null @@ -1,69 +0,0 @@ -# 解决 4:样式表作者体验 - -| | | -|---|---| -| 问题 | [研究 §4](../../research/ext-web-customization-limits.md#4-样式作者体验受限) | -| 优先级 | **P2** · 波次 **C3** | -| 触点 | 表单元格表达式(T5)· `ext/web` style 装配 · 教程 / Skill · 可选校验 | - ---- - -## 1. 目标 - -1. 含 `/`、`,`、括号的 CSS 值**不易被静默算坏**。 -2. 复杂选择器 / `@keyframes` / 多层 media 有**官方推荐写法**(表内 vs 外链 vs raw 块)。 -3. 与壳 CSS 的层叠关系在文档中一句话写清(并链到 [02](02-shell-css.md))。 - ---- - -## 2. 作者 API / 约定(草案) - -### 2.1 立即固化的文档约定(可不改代码) - -| 规则 | 说明 | -|------|------| -| 含 `/` 的值必须引号 | `"1 / 5"`、`"image/png"`(已有;Skill/教程加醒目反例) | -| 复杂皮肤优先外链 | `static/theme.css` + `page.head` / `app.icons` 同类资源表 | -| `@keyframes` / 长 media | 放外链 CSS,不塞进 GFM 单元格 | -| 调试 | `shell_css=off` 后只看主题文件,避免同页双源 | - -### 2.2 产品增强(C3) - -| 能力 | 说明 | -|------|------| -| `style` 装配时对可疑单元格告警 | 未加引号且含 `/` → listen/assemble 警告或硬错误(可开关) | -| 可选 `##` raw CSS 块绑定 | 例如页面附属 ````css` 具名块,**不经**表表达式求值 | -| 文档示例 | `min-width` + `max-width` 外链表;引用 [table-cell-expressions.md](../table-cell-expressions.md) | - ---- - -## 3. 插件 / 核心改动点 - -| 改动 | 说明 | -|------|------| -| web style 编译 | 可选 `strict_css_cells=True`:裸 `/` 报错 | -| (可选)`web_page_css_raw` | 把文本 CSS 追加到页面,跳过 T5 | -| Skill `marqdo` / tutorial 14 | 增加「样式踩坑」小节 | - ---- - -## 4. 兼容策略 - -- 默认不硬错误(避免打碎旧表);新 scaffold 默认 `strict_css_cells` 或文档强制引号。 -- 不把完整 CSS 语法塞进表格方言——复杂内容走文件。 - ---- - -## 5. 验收 - -| 场景 | 期望 | -|------|------| -| 文档反例 `grid-column` 裸 `1 / 5` | 在 strict 模式下失败或警告 | -| 外链 `theme.css` + `shell_css=off` | 无壳栅格串扰 | -| 现有 web 示例 | 默认模式仍绿 | - ---- - -## 6. 过渡期 workaround - -全部敏感值加引号;响应式与 keyframes 只写在 `static/*.css`;小屏问题优先关壳([02](02-shell-css.md))再调主题。 diff --git a/doc/design/ext-web-customization/05-page-shell-slots.md b/doc/design/ext-web-customization/05-page-shell-slots.md deleted file mode 100755 index 8b466a5..0000000 --- a/doc/design/ext-web-customization/05-page-shell-slots.md +++ /dev/null @@ -1,85 +0,0 @@ -# 解决 5:页面壳与插槽松绑 - -| | | -|---|---| -| 问题 | [研究 §5](../../research/ext-web-customization-limits.md#5-页面壳与插槽约定僵硬) | -| 优先级 | **P1** · 波次 **C2/C4** | -| 触点 | `plugins/web/src/render.rs`(body class、四区 HTML)· page 槽位装配 · nav 组件表 | - ---- - -## 1. 目标 - -1. 作者可选**非侧栏栅格**布局,而不必用 CSS 硬怼掉 `has-sidebar`。 -2. 侧栏存在 ≠ 强制桌面双列;提供 stacked / bare 等预设。 -3. 为「条件导航」留扩展点(先文档 + 简单 hook,完整运行时条件可后置)。 - ---- - -## 2. 作者 API(草案) - -```markdown -*首页 = > web.page … layout="stacked"* -*应用 = > web.app page=`首页` … layout="bare"* -``` - -| `layout` | DOM / class | 说明 | -|----------|-------------|------| -| `sidebar`(默认,有 side 槽时) | `body.has-sidebar` | 现网行为 | -| `stacked` | `body.layout-stacked`;side 在 main 上或折叠区 | 单列流式,适合杂志/营销 | -| `bare` | 无 top/side/foot 强制栅格;只渲染 `main`(+ 显式槽) | 登录页、落地页 | -| `rail`(可选) | 保留站点已有 `has-rail` 约定并文档化 | 避免「只有首页有 class」 | - -规则:**有 side 组件但 `layout=stacked|bare` 时,不自动加 `has-sidebar`。** - ---- - -## 3. 插件改动点 - -| 改动 | 说明 | -|------|------| -| `render` 读 `page.layout` / `app.layout` | 决定 body class 与 HTML 骨架 | -| `SHELL_LAYOUT`(见 [02](02-shell-css.md)) | 为 `layout-stacked` / `layout-bare` 提供最小样式;`shell_css=off` 时不注入 | -| Nav 表 | 短期保持声明式;文档说明「条件项用两套 nav 组件 + 媒体查询隐藏」 | -| 中期 hook(非阻断) | `navigate` 已有字段可扩展 `when`/`media` 列(单独 RFC) | - ---- - -## 4. 兼容策略 - -- 未设 `layout`:有 side → 与现网 `has-sidebar` 相同。 -- 金样增加 `layout=bare` 登录页(可与 C0 自研 `/desk/login` 共用)。 - ---- - -## 5. 验收 - -| 场景 | 期望 | -|------|------| -| 有 side + `layout=stacked` | body **无** `has-sidebar`;无 `14rem` 双列(在 full 壳下用 stacked 规则) | -| `layout=bare` | 输出不含 `<aside class="side">`(或 empty 不占栅格) | -| 默认站 | 不变 | - ---- - -## 6. 过渡期 → 已落地 - -**C2 已落地(2026-09):** `layout=sidebar|stacked|bare|rail`;有 side 时 `stacked`/`bare` 不再强制 `has-sidebar`。金样 `web-c2-shell-layout`。 - -**C4 已落地(2026-09):** 导航 / 侧栏 / 页脚绑定表可选列: - -| 列 | 说明 | -|----|------| -| `媒体` / `media` | CSS media;不匹配时 `display:none`(生成 `nav-mq-*` + `@media not …`) | -| `当` / `when` | `hide` 省略;`auth` / `guest` 按登录态过滤;空 = 总是显示 | - -```markdown -| 属性 | 值 | 样式 | 媒体 | 当 | -|------|-----|------|------|-----| -| Home | / | | | | -| Menu | /m | | (max-width: 720px) | | -| Admin | /admin | | | auth | -| Login | /login | | | guest | -``` - -Listen 渲染时写入 `_logged_in` / `_nav_user`(来自 session)。离线 `page.render` 可自行 `table.put` `_logged_in`。金样 `web-c4-nav-when`。 diff --git a/doc/design/ext-web-customization/06-admin-crud-forms.md b/doc/design/ext-web-customization/06-admin-crud-forms.md deleted file mode 100755 index 43a1834..0000000 --- a/doc/design/ext-web-customization/06-admin-crud-forms.md +++ /dev/null @@ -1,67 +0,0 @@ -# 解决 6:后台 CRUD 与表单能力边界 - -| | | -|---|---| -| 问题 | [研究 §6](../../research/ext-web-customization-limits.md#6-后台-crud-与表单能力边界) | -| 优先级 | **P3** · 随 C0 文档化;增强可选 | -| 触点 | `plugins/web/src/http.rs` / `form.rs`(内置 admin)· 站点自研页 + `db.*` · `/_form` | - ---- - -## 1. 目标 - -1. **产品叙事澄清**:内置 `/admin`(或可配置前缀)= 通用表浏览器,**不是** CMS;关则彻底让路(见 [01](01-routes-and-admin-prefix.md))。 -2. 自研后台的推荐路径写清楚:`page` + `form` + `db` + gate,而不是改插件壳。 -3. 对「链接前缀 / new / edit」给出约定或薄辅助,减少前端状态机拼装。 - ---- - -## 2. 作者 API / 文档(草案) - -### 2.1 推荐架构(文档为主) - -| 需求 | 做法 | -|------|------| -| 产品级编辑器、专栏联动 | 自研 `# page` + 组件;写库用 `db.insert`/`update`;鉴权用 `gate` | -| 简单表维护 | 开 `admin=True`(可换前缀) | -| 关内置仍要 CRUD | 自研列表/编辑页;**不要**依赖 disabled 壳 | - -### 2.2 可选薄增强(非 CMS) - -| 能力 | 说明 | -|------|------| -| `form` 支持 `mode=new\|edit` 查询参数约定 | 文档 + 示例;必要时 `web.form` 读 `id`/`new` | -| `list` 组件 `link_prefix` | 已有则补示例;缺失则加一列「详情路径模板」 | -| Markdown 字段 | 继续「存库 + 前台渲染」;分栏编辑器保持外挂 JS(明确不做进 ABI) | - ---- - -## 3. 插件改动点 - -| 改动 | 优先级 | -|------|--------| -| C0:disabled 不占路径 | 必需(属 [01](01-routes-and-admin-prefix.md)) | -| 示例 `examples/web-custom-desk/` | 展示自研列表/编辑,零内置 admin | -| form 查询参数助手 | 可选 | - ---- - -## 4. 兼容策略 - -- 不扩展内置 admin 成 CMS(避免范围爆炸)。 -- Tutorial 增加「何时用内置 admin / 何时自研」。 - ---- - -## 5. 验收 - -| 场景 | 期望 | -|------|------| -| 文档 + 示例 desk | 无 `/admin` 也能完成一文增删改 | -| 内置 admin 金样 | 仍绿 | - ---- - -## 6. 过渡期 workaround - -自研 `/desk` + 调用 `/_form` 或直接 DB API;复杂编辑器继续外挂 JS。 diff --git a/doc/design/ext-web-customization/07-assets-script-lifecycle.md b/doc/design/ext-web-customization/07-assets-script-lifecycle.md deleted file mode 100755 index d590412..0000000 --- a/doc/design/ext-web-customization/07-assets-script-lifecycle.md +++ /dev/null @@ -1,71 +0,0 @@ -# 解决 7:静态资源与脚本生命周期 - -| | | -|---|---| -| 问题 | [研究 §7](../../research/ext-web-customization-limits.md#7-静态资源与脚本生命周期) | -| 优先级 | **P2** · 波次 **C3** | -| 触点 | `web_page_head` / `web_head` · `render.rs` head 输出 · static 挂载 · [web-assets-and-images.md](../web-assets-and-images.md) | - ---- - -## 1. 目标 - -1. 默认脚本加载方式**不假设**作者手写 IIFE 抢在 DOM 前执行成功;提供 `defer` / `module` 一等约定。 -2. 静态资源变更可发现:文档化 `?v=`,并提供可选自动指纹或 listen 时 mtime 查询参数。 - ---- - -## 2. 作者 API(草案) - -Head 资源表扩展列(向后兼容): - -| 列 | 说明 | -|----|------| -| `rel` / `关系` | 已有;`script` / `module` | -| `defer` / `推迟` | `真` → `<script defer>`(**建议默认对 script 为真**) | -| `async` / `异步` | 可选 | -| `version` / `版本` | 非空则自动追加 `?v=` | - -```markdown -`头` = -| 关系 | 地址 | 推迟 | 版本 | -|------|------|------|------| -| script | /static/theme.js | 真 | 2026-09-04 | -| module | /static/desk.js | 真 | 3 | -``` - -全局:`app.asset_version="2026-09-04"` 为所有 static 链接统一 bump(可选)。 - ---- - -## 3. 插件改动点 - -| 改动 | 说明 | -|------|------| -| head 渲染 | 尊重 defer/async;`module` → `type="module"`(已有则核对) | -| 默认 | 新建 scaffold 的 script 行带 `defer` | -| (可选)`asset_version` | listen 时重写 head / 页面内 static URL | -| 文档 | 「禁止在同步 head 脚本里直接 `getElementById` 主节点;用 defer 或 `DOMContentLoaded`」 | - ---- - -## 4. 兼容策略 - -- 旧表无 `defer` 列:保持现网同步行为(或仅对 scaffold/新文档默认 defer,避免静默改变旧站时序)。 -- 更安全:缺省仍同步;**Skill 与 scaffold 默认写 defer=真**。 - ---- - -## 5. 验收 - -| 场景 | 期望 | -|------|------| -| defer 脚本读 DOM | 登录跳转逻辑在 DOM 就绪后执行 | -| `version` 列 | HTML 中出现 `theme.js?v=…` | -| 旧示例无新列 | 仍通过 | - ---- - -## 6. 过渡期 workaround - -脚本改 `type=module` 或放 body 末;手动 `?v=` bump;登录逻辑用 `DOMContentLoaded`。 diff --git a/doc/design/ext-web-customization/08-ext-deploy-coupling.md b/doc/design/ext-web-customization/08-ext-deploy-coupling.md deleted file mode 100755 index 3a9c6e5..0000000 --- a/doc/design/ext-web-customization/08-ext-deploy-coupling.md +++ /dev/null @@ -1,68 +0,0 @@ -# 解决 8:扩展与部署耦合 - -| | | -|---|---| -| 问题 | [研究 §8](../../research/ext-web-customization-limits.md#8-扩展与部署耦合) | -| 优先级 | **P3** · 文档 + 发布流程 | -| 触点 | `marqdo ext add web` · ABI 版本 · Docker/发布说明 · [ext-cli.md](../ext-cli.md) · [marqdo-release](../../../.cursor/skills/marqdo-release/SKILL.md) | - ---- - -## 1. 目标 - -1. 站点作者**不必 fork 插件**才能完成 P0/P1 定制(把能力收进官方参数,见 01–05)。 -2. 版本耦合可预期:changelog / 扩展清单标明「web 插件需 ≥ x.y.z」。 -3. 升级路径文档化:二进制、`.marqdo-ext`、Docker 镜像三者对齐检查。 - ---- - -## 2. 作者 / 运维约定(草案) - -| 约定 | 说明 | -|------|------| -| 定制优先走 `.mq.md` 开关 | `admin_prefix`、`shell_css`、`layout`、`gate`… 进官方 API 后,禁止文档再教「改 plugins/web」 | -| 兼容性矩阵 | 在 [web-net-capabilities.md](../web-net-capabilities.md) 或本目录维护「Marqdo ↔ libweb 最低版本」表 | -| `marqdo ext add web` | 安装后打印当前插件路径与版本;与 CLI 版本不符时警告 | -| Docker | 示例 Dockerfile 注释:升级需同时换 `marqdo` 与 `ext add` 产物 | -| 样式引号等行为变更 | 写入 CHANGELOG **Breaking / migration** 小节(如 0.3.2 T5) | - ---- - -## 3. 工程改动点 - -| 改动 | 说明 | -|------|------| -| 插件/Crate 版本可见 | `web_listen` 或 `ext list` 显示 web ABI/包版本 | -| CI | 金样使用仓库内 `plugins/web`;发布技能检查 VSIX/CLI/插件三件套 | -| 研究→设计→路线图 | C0–C4 进 [ext-web roadmap](../../roadmap/ext-web.md),避免只活在私有 fork | - ---- - -## 4. 兼容策略 - -- 不承诺插件源码级稳定 API;承诺 **`.mq.md` 作者 API** 在小版本尽量兼容,破坏性变更进 CHANGELOG。 -- Fork 插件仅作为「官方尚未交付」的临时手段,并在 issue/路线图留归还项。 - ---- - -## 5. 验收 - -| 场景 | 期望 | -|------|------| -| 升级说明文档 | 运维按清单升级后 web 金样通过 | -| C0–C2 落地 | 自研后台场景**无需**改 `plugins/web` 源码 | -| `ext list` / 文档 | 能核对版本 | - ---- - -## 6. 过渡期 → 预编译路径(进行中) - -**目标:** 用户 `marqdo ext add web` **不必**本机 Rust。 - -| 交付 | 说明 | -|------|------| -| Release `marqdo-*-native-*.zip` | Windows / Linux 预编译 `web`/`agent`/`quantum` | -| Windows portable zip | 内含 `ext/` + `ext/native/*.dll` | -| `ext add` 下载回退 | 本地无 `.so`/`.dll` 时从 GitHub Release 拉取(`MARQDO_EXT_NO_DOWNLOAD=1` 可关) | - -仍保留开发者 `cargo build -p marqdo_plugin_*` 路径。详见 [ext-cli.md](../ext-cli.md)。 diff --git a/doc/design/ext-web-customization/README.md b/doc/design/ext-web-customization/README.md deleted file mode 100755 index 7fe4a4f..0000000 --- a/doc/design/ext-web-customization/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# `ext/web` 定制修复:解决文档索引 - -| | | -|---|---| -| 状态 | **C0–C4 done** | -| 日期 | 2026-09-04 | -| 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) | -| 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) | - -对应研究文 §1–§8,每项一份解决文档:**目标 → 作者 API → 插件改动点 → 兼容策略 → 验收**。 - -实现时优先 **不破坏现有金样**(`tests/ext/web-*`、`examples/web-*`);新能力用显式 opt-in 参数打开。 - ---- - -## 文档一览 - -| # | 主题 | 文档 | 建议优先级 | -|---|------|------|------------| -| 1 | 路由与 `/admin` 前缀可让出 | [01-routes-and-admin-prefix.md](01-routes-and-admin-prefix.md) | P0 | -| 2 | `SHELL_CSS` 可关 / 可层 | [02-shell-css.md](02-shell-css.md) | P1 | -| 3 | 鉴权门禁可配置且行为一致 | [03-auth-gates.md](03-auth-gates.md) | P0 | -| 4 | 样式表作者体验 | [04-stylesheet-authoring.md](04-stylesheet-authoring.md) | P2 | -| 5 | 页面壳与插槽松绑 | [05-page-shell-slots.md](05-page-shell-slots.md) | P1 | -| 6 | 后台 CRUD / 表单边界 | [06-admin-crud-forms.md](06-admin-crud-forms.md) | P3 | -| 7 | 静态资源与脚本生命周期 | [07-assets-script-lifecycle.md](07-assets-script-lifecycle.md) | P2 | -| 8 | 扩展与部署耦合 | [08-ext-deploy-coupling.md](08-ext-deploy-coupling.md) | P3 | - ---- - -## 波次建议(实现用) - -| 波次 | 内容 | 依赖 | -|------|------|------| -| **C0** | 可配置 `admin_prefix`;`admin=False` 时不挂内置路由;`login_redirect` / `logout_redirect` | — | -| **C1** | gate:统一未登录策略;精确/前缀匹配;登录页自动放行;默认 gate 不再误伤 `/admin-*` | C0 | -| **C2** | `shell_css=off\|minimal\|full`;主题在壳前或隔离层;可选 `layout=bare` | — | -| **C3** | 样式:校验警告 / `strict`;`page.css` raw;脚本 `defer`/`async`/`version` + `asset_version` | **done** | -| **C4** | 壳:`layout` 预设(C2);条件导航 `when` / `media` | **done** | - -路线图入口可在 [ext-web.md](../../roadmap/ext-web.md) 增补「定制波次 C0–C4」行,落地后再改状态。 - ---- - -## 产品原则(解法共同约束) - -1. **`.mq.md` 仍是真相源** — 能声明的不进隐藏默认;新开关写在 `app` / `page` / `listen` 参数表。 -2. **内置 admin 是可选产品**,不是不可替换的内核路由命名空间。 -3. **默认行为保持兼容** — 现有 tutorial / 示例零改动仍能跑;新站显式打开定制。 -4. **禁止**为单站需求永久硬编码第二套旁路(如永远推荐 `/desk` + JS fetch 登录)。 diff --git a/doc/design/ext-web-drivers.md b/doc/design/ext-web-drivers.md deleted file mode 100755 index 11977d1..0000000 --- a/doc/design/ext-web-drivers.md +++ /dev/null @@ -1,125 +0,0 @@ -# `ext/web` 驱动:Postgres · Redis · S3 - -| | | -|---|---| -| 状态 | **Accepted · 已落地** | -| 日期 | 2026-08-28 | -| 相关 | [ext-web.md](ext-web.md) · [roadmap/ext-web.md](../roadmap/ext-web.md) · [ext-abi.md](ext-abi.md) | -| 目标 | 在**不改作者面 CRUD 心智**的前提下,用 URL 方案切换数据库;另增缓存与对象存储两类驱动。贯彻「表格 + 类方法」:配置即数据,装配即函数。 | - ---- - -## 0. 一句话 - -**`# db` 的 `url=` 决定后端**:`sqlite:` 默认;`postgres://` / `postgresql://` 走 Postgres,作者面 API 不变。 -**缓存**与**对象存储**是独立类(`# cache` / `# storage`),不塞进 `# db`。 - ---- - -## 1. 边界 - -| 能力 | 归属 | 理由 | -|------|------|------| -| SQLite / Postgres CRUD | `plugins/web` + `ext/web` `# db` | 同一套 `init/select/insert/…`;热路径 ABI | -| Redis 缓存 | `plugins/web` + `ext/web` `# cache` | 键值语义,不是表 CRUD | -| S3 / MinIO 对象 | `plugins/web` + `ext/web` `# storage` | 对象键 + 字节/路径,不是行 | -| 禁止 | 核心 `src/host/` | 驱动依赖重,只进 ABI 插件 | - ---- - -## 2. URL 方案(锁定) - -| 方案 | 含义 | 例 | -|------|------|-----| -| `sqlite:` / 裸路径 | SQLite 文件(既有) | `sqlite:data/site.db` | -| `postgres://` / `postgresql://` | Postgres | `postgres://user:pass@127.0.0.1:5432/app` | -| `redis://` / `rediss://` | Redis | `redis://127.0.0.1:6379/0` | -| `memory:` | **进程内** Redis 兼容后端(金样/离线) | `memory:` | -| `s3://bucket` + 查询参数 | S3 兼容(含 MinIO) | `s3://mybucket?endpoint=http://127.0.0.1:9000®ion=us-east-1` | -| `file:` | **本地目录**对象存储(金样/离线) | `file:data/blobs` | - -凭证:优先 URL 内嵌;S3 亦读环境变量 `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`(或 `S3_ACCESS_KEY` / `S3_SECRET_KEY`)。 - ---- - -## 3. 作者面(代码即文档) - -### 3.1 数据库 — 只换 URL - -英文: - -```markdown -import: - web: ext/web/web.mq.md - -# main - -*store = > web.db url="postgres://marqdo:marqdo@127.0.0.1:5432/site"* -*store = > store.init name="posts" fields=`schema`* -``` - -中文:`网页.数据库` + `url=` 同形。`init` / `select` / `insert` / `paginate` / `事务` **API 不变**。 - -Postgres 差异(实现层消化,作者尽量无感): - -- `id INTEGER PRIMARY KEY` → `SERIAL PRIMARY KEY`(或 `GENERATED …`) -- 占位符 `?` → `$1,$2,…` -- 标识符双引号规则对齐 - -### 3.2 缓存 `# cache` / `# 缓存` - -```markdown -*c = > web.cache url="memory:"* -*c = > c.set key="k" value="v" ttl=60* -*v = > c.get key="k"* -*c = > c.del key="k"* -``` - -方法:`get` · `set`(可选 `ttl` 秒)· `del` · `exists` · `ttl`。 - -配置表可选(装配时合并进 url / 默认 TTL): - -| 键 | 值 | -|----|-----| -| url | redis://127.0.0.1:6379/0 | -| ttl | 3600 | - -### 3.3 对象存储 `# storage` / `# 存储` - -```markdown -*blob = > web.storage url="file:data/blobs"* -> `blob`.put key="avatar/1.png" path="local.png" content_type="image/png" -*got = > `blob`.get key="avatar/1.png"* -> `blob`.delete key="avatar/1.png" -*keys = > `blob`.list prefix="avatar/"* -``` - -方法:`put`(`path=` 本地文件或 `body=` 文本)· `get`(返回 `{ok, body|path, content_type}`)· `delete` · `list`。 - ---- - -## 4. ABI 名 - -| ABI | 说明 | -|-----|------| -| 既有 `web_db_*` | 内部按 `url` 方案分发 SQLite / Postgres | -| `web_cache_new/get/set/del/exists/ttl` | 缓存 | -| `web_storage_new/put/get/delete/list` | 对象存储 | - ---- - -## 5. 测试 - -| 金样 | 内容 | -|------|------| -| `tests/ext/web-drivers-smoke.mq.md` | `memory:` 缓存往返;`file:` 存储 put/get/list/delete;`web_db_new` 接受 `postgres://` 句柄形状(不要求本机有库) | -| 可选 live | `MARQDO_TEST_POSTGRES` / `MARQDO_TEST_REDIS` / `MARQDO_TEST_S3` 非空时跑真实连通(CI 默认关) | - ---- - -## 6. 非本波次 - -- 连接池大小 / 读写分离配置表 -- Redis 集群 / Sentinel -- S3 预签名 URL 作者面糖(可后续加方法) -- 把 session 默认改存 Redis(仍默认 SQLite 表;可选后续) diff --git a/doc/design/ext-web-go-rewrite.md b/doc/design/ext-web-go-rewrite.md deleted file mode 100755 index d5d1902..0000000 --- a/doc/design/ext-web-go-rewrite.md +++ /dev/null @@ -1,452 +0,0 @@ -# `plugins/web` Go 全量重写(多语言 ABI 生态 · 网页制备完备) - -| | | -|---|---| -| 状态 | **Completed(W-G0…W-G14 · v0.4.0)** | -| 日期 | 2026-09-10 | -| 相关 | [ext-web.md](ext-web.md) · [ext-web-net.md](ext-web-net.md) · [web-net-capabilities.md](web-net-capabilities.md) · [ext-web-drivers.md](ext-web-drivers.md) · [web-assets-and-images.md](web-assets-and-images.md) · [ext-hosting-fill.md](ext-hosting-fill.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md) | -| 实现目录 | `plugins/web/`(**Go module**;产物仍为 `libweb.so` / `web.dll` / `libweb.dylib`) | -| 作者面 | `ext/web/web.mq.md` · `ext/web/网页.mq.md`(**ABI 名与方法面保持兼容**;非另起一套 API) | -| 当前验收 | 仓库内独立示例与临时夹具;完整站点、网络站点、浏览器与数据资源分别验证 | - -本文件记录 Go 原生层重写时期的 ABI 与实施背景。2026-11-10 起不再以外部业务工程作为仓库交付项;当前作者规范与可调用入口以 [Web Artifact 设计](ext-web-artifact.md)、[网页手册](../../ext/web/index.mq.md)和[编程规范](../library-development.mq.md)为准。下方旧 compose/类链清单是历史对照,不能当作当前推荐 API。 - ---- - -## 0. 一句话 - -用 **Go** 重写官方网络拓展库原生层(`plugins/web`),在 **C ABI v2 全量兼容** 前提下提供「网页制备」所需的全部服务端能力;`ext/web` 继续用 GFM 表 + `#` 类做作者面;应用的前后端脚本全部用 Marqdo 书写。此举同时验证 **多语言 ABI 插件生态**(首个非 Rust 官方插件)。 - -**不是**最小 hello 插件;**不是**在旧 Rust 代码上打补丁(对齐 [ext-web.md](ext-web.md) **C5**)。 - ---- - -## 1. 动机与目标 - -### 1.1 为何重写 - -| 动机 | 说明 | -|------|------| -| 开发/编译节奏 | Rust 插件迭代慢,网络域能力长期「半成品感」来自堆叠依赖与慢反馈,而非语言绝对性能 | -| 多语言生态 | ABI 已是稳定 C 契约;需要第一个 **Go** 官方插件证明「宿主 Rust ≠ 插件必须 Rust」 | -| 网页制备完备 | 目标是支持 **完整动态站点制备**(装配、CRUD、鉴权、实时、上传、SEO、代理、驱动…),并以真实论坛项目验收 | -| 性能与拉起 | Go `net/http` 生态成熟、单二进制友好;论坛级 IO 密集负载下足够「极致可用」 | - -### 1.2 成功标准(全部满足才算完成) - -1. **ABI 全量对等**:下文 §5 列出的每一个已注册 `web_*` 符号,参数 CSV、JSON 形、语义与现网 gold 一致(中英参数别名保留)。 -2. **作者面可用**:现有 `ext/web` 示例与 `tests/ext/web-*`(含 live-server)在换 Go `.so` 后通过;无需作者改业务脚本(除非文档标明的 **G 增强**)。 -3. **网页制备完备**:单站点可完成页面装配、样式/头/图、库表、表单、路由、中间件、鉴权/RBAC、上传下载、SEO/RSS/sitemap、WS、缓存、对象存储、反代、invoke——即 W0–W8 + P3 + C0–C4 + H1/H2 能力面。 -4. **驱动外接**:`postgres://`、`redis://`、`s3://` 为正式一等能力(与 [ext-web-drivers.md](ext-web-drivers.md) 一致);SQLite / memory / file 仍支持本地与测试。 -5. **通用工作流可验证**:使用仓库内独立站点和临时夹具覆盖数据、鉴权、表单与实时能力(见 §8);SQLite 提供本地验收,PostgreSQL、Redis 和对象存储按各自可用环境另行验证。 -6. **安装路径不变**:`marqdo ext add web`、`plugin.native_path name=web`、`MARQDO_WEB_PLUGIN`、产物文件名 `libweb.so` 等与 [ext-cli.md](ext-cli.md) 兼容。 - -### 1.3 非目标 - -| 非目标 | 说明 | -|--------|------| -| 改 Marqdo 核心语法 | 仍遵守 ext-web **C1** | -| 把服务器搬进浏览器 WASM | 仍遵守 ADR 0002 | -| 进程内 TLS | HTTPS 由反代;`cookie_secure` 保留 | -| 第三方插件市场 | 仍无 registry | -| 把论坛业务写进 Go 插件 | 帖子/新闻/聊天室规则在 `.mq.md`;插件只提供原语 | -| 强制嵌入式替代 PG/Redis | 本项目明确 **允许并依赖外接** PG/Redis | - ---- - -## 2. 分层架构(锁定) - -```text -┌──────────────────────────────────────────────────────────────────┐ -│ 应用(独立业务站点) │ -│ · 后端 .mq.md:路由、业务、装配、invoke 处理函数 │ -│ · 前端 .mq.md:WASM + lib/browser(作者零业务 JS) │ -└────────────────────────────┬─────────────────────────────────────┘ - │ import web / 网页 -┌────────────────────────────▼─────────────────────────────────────┐ -│ ext/web(L1 · Marqdo) │ -│ # page # db # app # form # auth # cache # storage # media # ws │ -│ make_style / make_head / make_images / client_embed … │ -└────────────────────────────┬─────────────────────────────────────┘ - │ lib/plugin → dlopen -┌────────────────────────────▼─────────────────────────────────────┐ -│ plugins/web(L0 · Go · C ABI v2) ← 本文件重写对象 │ -│ net/http + 驱动适配 + HTML 装配 + WS hub + 中间件 … │ -└──────────┬─────────────────┬─────────────────┬───────────────────┘ - │ │ │ - PostgreSQL Redis S3/MinIO/RustFS - (外接) (外接) (可选外接) -``` - -| 层 | 语言 | 职责 | -|----|------|------| -| 应用脚本 | Marqdo | 前后端业务、页面表、领域模型 | -| `ext/web` | Marqdo | 双语作者 API;禁止直接 `host_*` | -| `plugins/web` | **Go** | 全部 `web_*` ABI;高性能网络与驱动 | -| `lib/net` | Marqdo + Rust host | **仅**客户端 HTTP / cookie / multipart / markdown **解析**;不进本重写范围(边界不变) | -| 宿主 | Rust | `dlopen`、JSON Value、`host_query`(`entry_dir` / `call_lib_path` …) | - ---- - -## 3. 硬约束(继承 + 本重写追加) - -### 3.1 继承 ext-web C1–C7 - -| ID | 约束 | -|----|------| -| C1 | 不为 web 改核心语法 | -| C2 | 作者面禁止 json 袋胶水拼装页面 | -| C3 | 中英 API 分文件;禁止混排 | -| C4 | 首页 `index.mq.md`;组件可拆 | -| C5 | **禁止在旧 Rust 插件上打补丁演进**;清空/替换后用 Go 重写 | -| C6 | `# db` 完整 CRUD;`select`/`查询`;admin 与表单共用写库 API | -| C7 | 表单字段+规则;**写库前服务端校验** | - -### 3.2 本重写追加(G 系列) - -| ID | 约束 | -|----|------| -| **G1** | 产物仍为 C ABI v2;`MARQDO_ABI_VERSION = 2`;导出符号名与 [include/marqdo_abi.h](../../include/marqdo_abi.h) 一致 | -| **G2** | **ABI 函数名与参数名向后兼容**:§5 清单中每个 `web_*` 必须注册;参数 CSV 与现 Rust 插件一致(含中文别名) | -| **G3** | Go 使用 `-buildmode=c-shared`;**禁止**把 Go runtime 假设成唯一线程——跨 FFI 调用必须可重入或明确串行化文档 | -| **G4** | `marqdo_plugin_shutdown` 必须停止 HTTP/WS、关闭 DB/Redis 连接、释放 hub | -| **G5** | 字符串跨界:成功时 `*out_json` / 失败时 `*err_msg` 必须用 **host `alloc`** 分配(与现插件相同),由宿主 `free` | -| **G6** | 相对路径(sqlite 文件、静态目录、上传根)一律相对 `host_query("entry_dir")` | -| **G7** | 多语言样板:仓库内保留可复用的 Go ABI 脚手架注释/包结构,供后续其它语言插件参考 | -| **G8** | 金样例不过 = 未完成;切换默认 `libweb` 到 Go 后,既有 `tests/ext/web-*` 必须绿 | - ---- - -## 4. 技术选型(Go) - -| 能力 | 选型 | 备注 | -|------|------|------| -| HTTP 服务器 | 标准库 `net/http` | 路由可用轻量自研 mux 或 `chi`/`http.ServeMux`(Go 1.22+ 模式) | -| 中间件 | 自研链式 `func(http.Handler) http.Handler` | 对等 CORS / 安全头 / gzip / body limit / access_log / cache-control | -| WebSocket | `gorilla/websocket` 或 `coder/websocket` | 对等 echo / broadcast / drain;**G 增强**:命名房间(§7) | -| SQLite | `modernc.org/sqlite`(纯 Go)或 `mattn/go-sqlite3`(cgo) | 优先纯 Go 以便交叉编译;FTS5/migrate 行为对齐 | -| PostgreSQL | `jackc/pgx/v5` | `postgres://` / `postgresql://` | -| Redis | `redis/go-redis/v9` | `# cache`;**G 增强**:可选 session/WS 后端 | -| S3 | `aws-sdk-go-v2` 或 MinIO SDK | `s3://`;兼容 RustFS | -| 密码 | `golang.org/x/crypto/argon2` | argon2id 参数对齐现实现 | -| Markdown | `goldmark`(GFM 扩展) | 对等 `pulldown-cmark` 用途(正文 HTML) | -| JSON | `encoding/json` | ABI 边界 | -| 构建 | `go build -buildmode=c-shared -o libweb.so` | 见 §9 | - -**不引入**完整 Web 框架(Gin/Echo 业务层)以免作者面旁路;框架能力用 Marqdo `# app` 表达。 - ---- - -## 5. ABI 全量清单(必须注册 · 兼容) - -> 参数列为注册时 `params` CSV(英;实现须同时接受设计中已有的中文键别名,与现 `lib.rs` 一致)。 -> 状态列:`P0` = 首波必须与 gold 对齐;实现顺序见 §10。 - -### 5.1 Page / compose / assets / render - -| ABI | params(摘要) | 域 | -|-----|----------------|-----| -| `web_page_new` | (空或 title 等,对齐现实现) | page | -| `web_compose_components` | page, components, … | compose | -| `web_compose_main` | page, main, … | compose | -| `web_page_query` | page, query | page | -| `web_page_order` | page, order | page | -| `web_page_link_prefix` | page, prefix | page | -| `web_page_css` | page, css | page | -| `web_page_detail` | page, … | page | -| `web_page_meta` | page, meta | SEO | -| `web_page_head` | page, head | W8 | -| `web_page_images` | page, images | W8 | -| `web_page_paginate` | page, … | content | -| `web_head` | table / … | W8 | -| `web_images` | table / … | W8 | -| `web_app_icons` | app, icons | W8 | -| `web_style` | table, strict? | CSS | -| `web_compose_form` | page, form, target? | form embed | -| `web_render` | page | HTML | - -### 5.2 SEO / ops routes - -| ABI | 域 | -|-----|-----| -| `web_rss_build` | RSS | -| `web_app_route_rss` | app | -| `web_app_redirect` | app | -| `web_app_error_page` | app | -| `web_app_sitemap` | app | -| `web_app_robots` | app | -| `web_sitemap_build` | sitemap | - -### 5.3 Upload / media - -| ABI | 域 | -|-----|-----| -| `web_app_upload` | app | -| `web_app_download` | app | -| `web_upload_validate` | media | -| `web_upload_save` | media | -| `web_media_new` | media | -| `web_app_gallery` | app | - -### 5.4 Database - -| ABI | 备注 | -|-----|------| -| `web_db_new` | `sqlite:` / `postgres://` | -| `web_db_init` | unique / index / fk / 审计时间戳 | -| `web_db_insert` / `select` / `get` / `update` / `delete` / `exec` | CRUD | -| `web_db_query` / `count` | 原生 / 计数 | -| `web_db_migrate` | **SQLite only**(对等) | -| `web_db_fts_create` / `web_db_search` | **SQLite only** | -| `web_db_begin` / `commit` / `rollback` | 事务句柄 | -| `web_db_list_tables` / `web_db_table_info` | admin 内部 | - -Where 语义:等值 map、filter 表、OR / IN / BETWEEN、分页 offset/limit——行为对齐现 `db.rs` / `db_pg.rs`。 - -### 5.5 Cache / storage - -| ABI | URL | -|-----|-----| -| `web_cache_new` / `get` / `set` / `del` / `exists` / `ttl` | `memory:` / `redis://` | -| `web_storage_new` / `put` / `get` / `delete` / `list` | `file:` / `s3://` | - -### 5.6 App / HTTP / hosting - -| ABI | 域 | -|-----|-----| -| `web_app_new` | app | -| `web_app_route` | 动态 `{param}` + `/_part` | -| `web_app_mount_form` | `/_form` | -| `web_app_static` | 静态目录 | -| `web_app_middleware` | `configure`:CORS、安全头、gzip、body_limit、JSON API、access_log、cache_control | -| `web_app_proxy` | 流式反代 / SSE(H1) | -| `web_app_invoke` | HTTP → `lib.member`(H2;经 `host_query call_lib_path`) | -| `web_listen` | 阻塞监听;组装全部路由 | -| `web_app_route_ws` | WS 端点 | -| `web_ws_connect` | 客户端单次请求-响应式 | -| `web_app_auth` | `/admin` 门禁 | -| `web_app_gate` | RBAC 段前缀 | - -### 5.7 Form - -| ABI | -|-----| -| `web_form_new` / `fields` / `rules` / `validate` / `render` / `submit` / `from_schema` | - -规则:`required`、`min:N`、`max:N`、`email`、`url`、`match:field`、`in:a,b,c`。 - -### 5.8 Session / auth - -| ABI | -|-----| -| `web_session_new` / `set` / `get` / `del` / `destroy` | -| `web_auth_new` / `login` / `check` / `logout` | -| `web_password_hash` | - -安全对等:argon2id、CSRF、登录限速、CSPRNG session id、cookie Secure(配置)、滑动 TTL、持久化会话(默认 SQLite 会话表;见 §7 Redis 可选)。 - -### 5.9 HTTP 挂载面(`web_listen` 必须复现) - -- `GET /`,`GET /_part/{id}`,`GET|POST /_form/{id}` -- 可选 admin:`{prefix}/`、`/login`、`/logout`、`/{table}`、`/new`、`/{id}/edit`、`/{id}/delete`(C0:`admin=False` 让出 `/admin`) -- 作者 `route` 页 + `{path}/_part/{id}`;动态路径参数 -- WS;RSS;upload POST;download GET;gallery;sitemap;`/robots.txt` -- 301/307 重定向;自定义 404/500;proxy;invoke -- 静态与 icons;约定 `/favicon.ico` -- 保留名:`/_form`、`/_part`、静态挂载冲突检测 - -### 5.10 `host_query` 依赖 - -| name | 用途 | -|------|------| -| `entry_dir` | 路径沙箱根 | -| `call_lib_path` | invoke / 嵌套 lib 调用(含 `args`) | -| (其它已允许项) | 与 ABI v2 allowlist 一致;不得扩展任意 HostFn | - ---- - -## 6. 作者面(保持 · 不另起炉灶) - -英文 `ext/web/web.mq.md` / 中文 `ext/web/网页.mq.md` 现有 `#` 类与 `##` 方法 **保持**: - -| 类 | 职责 | -|----|------| -| `# page` / `# 页面` | 装配、meta、head、images、paginate、render | -| `# db` / `# 数据库` + `# txn` | CRUD、事务、migrate/FTS(SQLite) | -| `# form` / `# 表单` | 字段、规则、校验、渲染、提交 | -| `# app` / `# 应用` | route、configure、listen、auth、gate、upload… | -| `# auth` / `# 鉴权` | login/check/logout/hash | -| `# cache` / `# 缓存` | memory/redis | -| `# storage` / `# 存储` | file/s3 | -| `# media` / `# 媒体` | validate/save | -| `# ws` / `# 实时` | connect | -| 模块函数 | `ensure_plugin`、`make_style`、`make_head`、`make_images`、`client_embed`、`text_patch`、`dom_patch`、`list_html` | - -**重写默认策略**:先 **只换原生 `.so`**,L1 不动;仅当 §7 G 增强需要新方法时,再 **追加**(不破坏旧方法)。 - ---- - -## 7. G 增强(完备网页制备;兼容之上增量) - -> 以下为 **新增能力**,不替代 §5。作者面用新方法/新 configure 键;旧脚本不受影响。 - -| ID | 能力 | 动机 | 作者面草案 | -|----|------|------|------------| -| **G-WS1** | **命名房间** WS:`join`/`leave`/`publish`;组名 ASCII(如 `chat.room.{id}`) | 独立聊天室 | `app.route_ws` 增 `mode=room` + `room_key`;或 `ws.room_*` ABI | -| **G-WS2** | 房间消息钩子:先 `invoke`/落库再广播 | 「先写 PG 再推送」 | configure 或 route 表 `on_message=lib.member` | -| **G-SESS1** | Session 后端可选 `redis://` | 多进程/多实例 | `web_session_new` url 或 auth 配置 `session=redis://` | -| **G-CACHE1** | Redis pub/sub 可选作 WS 扇出后端 | 多进程 WS | `configure ws_backend=redis` | -| **G-API1** | Bearer API Key 校验原语(hash+pepper+scopes) | API 密钥资源 | `web_api_key_check` + `# auth` 或独立小类;**业务 scopes 仍在 .mq.md** | -| **G-MAIL0** | (可选后续)SMTP 发送原语 | 邮箱验证码 | 不阻塞首版对等;另列后续能力 | - -**明确仍属应用层(不进插件)**:反垃圾策略、草稿定时发布约定、好友关系、专题 `topic_bundles` 静态交互内容(静态挂载 + 前端 Marqdo/既有 JS 资产)。 - ---- - -## 8. 独立工作流与隔离验收 - -仓库交付不依赖某个外部业务工程的源码或个人数据库。各能力保留在原生实现与领域资源中,通过维护中的独立示例验证;移出业务工程不构成删除通用功能的理由。 - -| 工作流 | 当前来源 | 实际核对 | -|---|---|---| -| 完整动态站点 | examples/web-site、examples/web-site-zh | 原主题规则、摘要与详情、当前记录、表单重试、会话导航及后台门禁 | -| 网络资源 | examples/web-net-site、examples/web-net-site-zh | Cookie/multipart、WebSocket 回显、真实表单与后台 | -| 客户端状态 | examples/web-spa-app、examples/web-collab-doc | 当前 WASM、历史记录、编辑、多标签实时协作 | -| 数据与租户 | tests/example_databases.rs、tests/web_handbook.rs | 独占临时数据库、已有记录保留、租户条件 | -| 原生插件 | plugins/web 内部测试 | 独立夹具下验证数据库、会话、运输、资源及渲染边界 | - -开发与验收由 skills/marqdo-dev/index.mq.md 编排,使用 marqdo call。完整示例的浏览器用例和 HTTP 用例不能替代 Postgres、Redis、OIDC 或外部服务的真实环境证据;未运行的边界仍需明确保留为未验证。 - ---- - -## 9. 仓库布局与构建 - -### 9.1 目录(目标) - -```text -plugins/web/ # Go module(替换原 Rust crate) - go.mod - go.sum - README.md - abi/ - marqdo_abi.h # 从 include/ 拷贝或 cgo 引用 - bridge.go # //export marqdo_plugin_* ;register;alloc/free - internal/ - page/ compose/ render/ form/ - db/ # sqlite + postgres driver - cache/ storage/ upload/ - session/ auth/ password/ ratelimit/ - httpx/ # listen、router、middleware、admin、proxy、invoke - ws/ # hub、rooms、client connect - assets/ rss/ sitemap/ markdown/ - table/ # GFM 表 JSON 形态辅助 - cmd/ # 可选:非 c-shared 的本地自测 -scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so -``` - -原 Rust 源码:曾置于 `plugins/web-rust-archive/`(已移出 Cargo workspace,参考用); -该目录已于 v1.6 精简时从工作树移除,历史保留在 git 中。 - -### 9.2 产物与解析 - -| 平台 | 文件名 | -|------|--------| -| Linux | `libweb.so` | -| macOS | `libweb.dylib` | -| Windows | `web.dll` | - -解析顺序仍走 `installed_native_path` / `MARQDO_WEB_PLUGIN`;`find_native_plugin` 增加查找: - -- `plugins/web/build/libweb.so`(Go 构建输出) -- `target/{debug,release}/libweb.so`(兼容旧路径,可选 copy) - -### 9.3 宿主 / CI 变更要点 - -| 组件 | 变更 | -|------|------| -| 根 `Cargo.toml` workspace | 移除 `plugins/web` / `web-rust-archive` Rust member | -| `tests/gold.rs` | `ensure_web_plugin_built()` → `scripts/build-web-plugin.sh` | -| `marqdo ext add web` | 构建回退:`scripts/build-web-plugin.sh`(Go);Release 仍下发预编译 native zip | -| Release 脚本 | Go:`scripts/build-web-plugin.sh`;其它插件仍 `cargo build -p …` | -| [ext-cli.md](ext-cli.md) / [ext-abi.md](ext-abi.md) | 注明 web 插件实现语言为 Go | - -### 9.4 cgo / runtime 注意 - -- `marqdo_plugin_init` 内 `register_fn` 注册全部符号;保存 host `alloc`/`free`/`host_query`。 -- 长时间 `web_listen`:在独立 goroutine 跑 `http.Server`,ABI 调用阻塞至 shutdown 或按现语义阻塞(**对齐现 Rust:listen 阻塞当前插件调用**)。 -- 禁止在 FFI 回调里长时间持有阻碍 GC 的错误模式;JSON 尽快拷贝到 Go string。 -- Windows 导出需 `.def` 或 `//export` 完整三个符号。 - ---- - -## 10. 实现波次(按文档开发顺序) - -| 波次 | 内容 | 退出条件 | -|------|------|----------| -| **W-G0** | 文档(本文)+ ADR + 目录骨架 + ABI bridge 能 `plugin.load` + `demo` 注册探测 | ✅ `tests/ext/web-go-abi-smoke.mq.md`;`web_go_ready` + `web_page_new`;`scripts/build-web-plugin.sh` → `libweb.so` | -| **W-G1** | table 辅助 + `web_style` + page new/compose/render(无 listen) | ✅ `web-smoke` / `web-zh-smoke`(含 compose_form / app_new / app_route 袋) | -| **W-G2** | SQLite db CRUD + where + txn + init | ✅ `web-db-w2-smoke` / `web-db-w6-smoke`(txn·migrate·FTS) | -| **W-G3** | form + mount_form + CSRF 基础 | ✅ `web-form-smoke`(validate/submit/render;CSRF 字段已接,listen 侧硬化见 W-G4/G5) | -| **W-G4** | `web_listen` + route + static + part + middleware + JSON API | ✅ offline:`web-route` / `web-static` / `web-middleware` / `web-part`;`web_listen` 已接线(live 随 W-G5+ hardening) | -| **W-G5** | session/auth/password/rate limit/gate/admin | ✅ offline:`web-security` / `web-c0` / `web-c1`;login rate limit 包已就位(HTTP 接线随 listen hardening) | -| **W-G6** | upload/download/gallery/ETag + assets W8 | ✅ `web-upload` / `web-assets` / `web-p3` | -| **W-G7** | SEO RSS sitemap robots redirect error paginate markdown | ✅ `web-content` / `web-w7-*` | -| **W-G8** | WS echo/broadcast + access_log | ✅ `web-ws-broadcast-*` | -| **W-G9** | Postgres + Redis cache + file/S3 storage | ✅ `web-drivers-smoke` | -| **W-G10** | proxy + invoke + nested plugin | ✅ `web-proxy-invoke` / hosting live | -| **W-G11** | 定制 C2–C4 shell/layout/style/nav | ✅ `web-c2`–`c4` | -| **W-G12** | G 增强 WS rooms + Redis session/pubsub + API key 原语 | ✅ 单测 + `web-g12-api-key-smoke` | -| **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | ✅ 离线+live gold(7 个 `*_live`)对 Go 全绿;`ext add`/`gold`/`release` 走 `scripts/build-web-plugin.sh`;Rust 移出 workspace;gold 强制 `MARQDO_WEB_PLUGIN` 避免 `~/.marqdo` 旧 so | -| **W-G14** | 历史业务站点主路径演示 | 历史演示工程已移出仓库;当前独立验收见 §8 | - -每波次:**先补 Go 实现 → 跑对应 gold → 再进入下一波**。禁止跨波次留下「注册了但返回 stub 错误」的 ABI(除 W-G0 明确的未实现探测)。 - ---- - -## 11. 测试策略 - -| 类型 | 做法 | -|------|------| -| 单元 | Go `go test ./internal/...`(db where、form rules、middleware) | -| 金样例 | 现有 `tests/ext/web-*.mq.md`;构建脚本产出 `libweb.so` 后跑 | -| Live | 现有 `*-live-server.mq.md` + curl | -| 回归门禁 | CI:安装 Go → `scripts/build-web-plugin.sh` → `cargo test` 相关 web 项 | -| 独立站点 | 登录、表单、WebSocket 与 API 使用可控夹具分别验收 | - ---- - -## 12. 风险与缓解 - -| 风险 | 缓解 | -|------|------| -| cgo/共享库与宿主线程 | 文档化;listen 独立 goroutine;shutdown 明确 | -| JSON ABI 开销 | 热路径减少往返;装配结果缓存;不在此用「换语言」幻想消除 | -| 行为微差异(HTML/Markdown) | 用同一批 gold HTML 片段断言;差异列 changelog | -| 交叉编译 | 优先 `modernc.org/sqlite`;Release 矩阵 Linux/Windows 先 | -| 双实现并存混乱 | W-G13 前用 `MARQDO_WEB_PLUGIN` 显式指向;文档写清默认 | - ---- - -## 13. 文档与索引更新清单 - -实现推进时同步: - -- [x] 本文状态行随波次更新 -- [x] [ext-abi.md](ext-abi.md) Demo/Web 节:实现语言 Go -- [x] [ext-cli.md](ext-cli.md):构建回退含 `go build` / `scripts/build-web-plugin.sh` -- [x] [ext-web.md](ext-web.md):链到本文;C5 落实说明 -- [ ] [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md):axum → Go `net/http` -- [ ] [doc/README.md](../README.md) 索引行(若尚未链到本文) -- [x] ADR:`doc/adr/0004-web-plugin-go.md`(Accepted) -- [x] `plugins/web/README.md` 开发者构建说明 - ---- - -## 14. 决议摘要 - -1. **全量重写** `plugins/web` 为 Go,**不是**最小闭环。 -2. **既有网络拓展能力(§5)重写后必须仍可用**;作者面默认兼容。 -3. **PostgreSQL / Redis 外接** 为一等公民;Marqdo 承担应用前后端脚本。 -4. 完备性通过独立工作流和原生测试验证,不以外部业务工程缩小插件能力范围。 -5. **多语言 ABI 生态** 以本插件为样板(G7)。 -6. 开发严格按 **§10 波次** 推进;本文件为唯一施工图。 diff --git a/doc/design/ext-web-handbook.md b/doc/design/ext-web-handbook.md deleted file mode 100755 index 85f09dc..0000000 --- a/doc/design/ext-web-handbook.md +++ /dev/null @@ -1,71 +0,0 @@ -# Web:可执行手册与递归布局工程 - -| 项目 | 内容 | -|------|------| -| 日期 | 2026-11-08 | -| 使用与开发入口 | [英文 index](../../ext/web/index.mq.md) · [中文索引](../../ext/web/网页/索引.mq.md) | -| 工程规范 | [布局拆分](ext-web-layout-paradigm.md) | -| 参考工程 | [英文](../../examples/web-layout-handbook/index.mq.md) · [中文](../../examples/web-layout-handbook-zh/index.mq.md) | -| 自动验收 | [源手册与活站点](../../tests/web_handbook.rs) · [浏览器布局](../../tests/web/layout.browser.cjs) | -| 思想来源 | [next/010](../next/010.md) · [next/011](../next/011.md) · [next/012](../next/012.md) · [Quantum 优化](ext-quantum-handbook.md) | - -## 原有规范为什么没有落实 - -原有 Web skill 已写「拆到简单」,但缺少可沿着文件树复现的工程。原生 `RenderNodes` 仅渲染平面 title/text/link/html;拼接两张表只产生兄弟节点,不会产生双栏。`serve` 又只把 Document 正文当 Markdown,没有执行文档里的组件装配。只加强口头禁止 HTML,无法补上这些实际缺口。 - -本轮以一个完整首页检验规范:导航、主体、页脚分开;页脚拆品牌与链接;链接再拆文档与社区。所有末端 content.md 都是普通 Markdown。每个父 index.mq.md 只负责其下一层排列关系。 - -## 使用同一份 View 表表示父与叶 - -沿用 `type | slot | value | attrs | style`,不新增核心语法、不建立第二套布局方言: - -| 类型 | 值列 | 含义 | -|------|------|------| -| markdown / 正文 | Markdown 文本 | 内容叶子 | -| row / 横排 | 子节点列表 | 响应式分栏 | -| column / 纵排 | 子节点列表 | 上下排列 | -| nav/header/footer/section/aside | 子节点列表 | 语义区域 | -| 既有 title/text/link/html | 兼容原值 | 保留旧节点行为;html 为显式兼容边界 | - -纯 `component.markdown` / `正文` 与 `component.wrap` / `包裹` 构造节点,`layout.stack` / `纵排` 和 `layout.columns` / `分栏` 声明几何。`merge` 接受 @ 记录列表,确定兄弟顺序并保留嵌套值;不再声称它会自动归一化所有列式表或把平面表变成双栏。 - -递归渲染保留节点类型,不把子表转成 `map[...]` 字符串。原生渲染器诊断无效子节点、列长不等和过深嵌套。运行时固定的布局样式提供基础响应式几何,样式列继续是类名引用,并非 CSS 编译器。叶子正文经过既有 Markdown 渲染器。 - -## 显式 Document 装配 - -普通 `type: web` 保留既有 Markdown/数据源路径。需要结构化页面时显式增加 `view: main`(中文 `视图: main`),普通 `# main` 返回 View 节点列表。`serve` 在启动时通过已有 `run_artifact` 回调执行装配,用与离线预览相同的渲染器生成文档,不再套入旧站点的另一份导航/页脚壳。 - -这是启动时装配,修改内容后重启;不声称具备自动请求期模板绑定。装配函数不再次调用渲染器或启动服务器。请求期业务仍用 Endpoint。自动 `data_source` 绑定使用普通 Document;与 `view: main` 混用会明确报错,避免静默忽略数据源。 - -`web.inspect root=...` / `网页.检视 根=...` 新增离线扫描入口,不启动进程也不执行组件。空应用的新进程无法读取另一个活进程的私有路由;手册不再将此作为活站点检视方法。检视结果加入 `_type: web_inspection`,使不同长度的 declared/system 列表保持对象语义,而不被 JSON 边界当作列式表。 - -## 手册与工具一致 - -另修复既有元数据型 Endpoint 在 Bytecode 没有函数时误报编译错误的问题:与 Tree 共用声明摘要路径,普通无入口程序仍然拒绝执行。 - -全部 Web 模块清理说明性伪函数,参数和返回契约均放在执行前;对象 API 保留。纯 DOM 构造与客户端描述不再无故加载插件。命令示例保护文本引号与会话美元引用。布尔/数字默认值与相邻标点分开,保证真正省略参数时仍符合契约。 - -原 `accept_component` 仅根据名称和职责就返回 ok=True,无法代表实际验收。现在返回明确的 checklist 状态,实际验收依据源码职责、渲染结构和运行结果。`site_playbook` 讲流程,`preview_markdown` / `preview_nodes` 给真实预览,不再把增加叙述字数当作完成指标。 - -## 验证 - -```bash -bash scripts/build-web-plugin.sh -cargo test --locked --test web_handbook -cargo test --locked --test call_cli web_ -cargo test --locked --test gold ext_web -- --test-threads=1 -``` - -手册门禁直接执行 18 份包内入口的双语 sh 围栏,在 Tree/Bytecode 共执行 80 次命令;同样执行根手册的作者程序。参考工程的双语双后端检查实际预览、启动服务,核对首页与预览相同、关于页仍走普通 Document、API 正常返回 JSON;不把路由声明误当作已经监听。 - -浏览器检查可对参考预览或活站点执行,按环境指定现有 Playwright 模块和 Chromium: - -```bash -node tests/web/layout.browser.cjs /absolute/path/to/preview.html -``` - -它测量 1440px 下的外层与内层双栏、390px 下的两层纵向折叠,并检查无横向溢出。无需外部资源或业务 JavaScript。Go 单元测试覆盖递归 Markdown、顺序、带类型列式表、错误形状与 Document 显式执行边界。 - -通用数据文档渲染测试已从硬编码个人数据库改为临时目录建表并注入已知数据,使完整 Go 套件无需个人站点状态。 - -Web 提交时,全库 Rust 为 436 通过、25 项既有策略/回放失败,基线失败集合相同。后续已单独修复 Rust→Lean 命令缺字段的问题:所有操作发送完整的 op、steps、value,进程错误保留退出码与 stderr。原 25 项失败全部消除,新增诊断回归后库级测试为 462 通过、0 失败。策略判定仍由 Lean 执行。 diff --git a/doc/design/ext-web-layout-paradigm.md b/doc/design/ext-web-layout-paradigm.md deleted file mode 100755 index 27122ab..0000000 --- a/doc/design/ext-web-layout-paradigm.md +++ /dev/null @@ -1,65 +0,0 @@ -# Web 布局工程:先拆布局,直到 Markdown 叶子 - -| 项目 | 内容 | -|------|------| -| 状态 | Active,2026-11-08 可执行参考工程与浏览器门禁已落地 | -| 包内手册 | [英文根入口](../../ext/web/index.mq.md) · [中文根入口](../../ext/web/网页/索引.mq.md) | -| 布局工具 | [layout](../../ext/web/layout/index.mq.md) · [布局](../../ext/web/布局/索引.mq.md) | -| 实现与边界 | [Web 手册优化](ext-web-handbook.md) · [Artifact](ext-web-artifact.md) · [ADR 0007](../adr/0007-web-document-endpoint.md) | - -## 先建立区域树,再写内容 - -首页先拆成导航、主体、页脚。页脚若有左右两栏,拆成品牌与链接;链接区若还有双栏,再拆成文档与社区。继续按内部独立布局拆分,直到叶子只剩简单 Markdown 可以直接表达的内容。 - -```text -index.mq.md → components/index.mq.md(纵排) - ├─ nav/index.mq.md → content.md - ├─ main/index.mq.md → content.md - └─ footer/index.mq.md(分栏) - ├─ brand/index.mq.md → content.md - └─ links/index.mq.md(分栏) - ├─ docs/index.mq.md → content.md - └─ community/index.mq.md → content.md -``` - -父文件只导入子块、合并兄弟节点并声明一层排列。叶子文件只说明一种内容职责;内容较长时,使用相邻的普通 content.md,避免字符串转义。拆分终点不是行数或文件数量,更不是每句话建一个文件。 - -## 何时继续拆、何时停止 - -| 观察 | 决定 | -|------|------| -| 导航、正文、页脚混在一个内容块 | 拆成父级装配和三个职责块 | -| 页脚内部仍同时负责品牌与链接排布 | 再拆左右子块 | -| 链接子块内部仍包含两个独立栏目 | 继续拆到各栏目 Markdown | -| 叶子只包含标题、段落、列表、链接、表格、图片 | 停止;已可用普通 Markdown 表达 | -| 父文件含大量正文、HTML 标签、CSS 字符串 | 职责或表达方式仍未收敛,继续拆解 | -| 结构已经简单,只为减少行数而再拆 | 不必拆;以可读职责为准 | - -表单、数据源、交互各有自己的领域职责,应调用对应模块,不以“Markdown 不表达交互”为由恢复整页 HTML 壳。只有确实需要兼容宿主能力时,才在隔离边界使用已有 raw/css 接口并说明原因。 - -## 同一表结构贯穿所有层 - -公共列是 `type | slot | value | attrs | style`,中文可用 `类型 | 槽 | 值 | 属性 | 样式`。使用 @ 记录表产生节点列表。 - -- `component.markdown` / `组件.正文`:叶子值为普通 Markdown。 -- `component.wrap` / `组件.包裹`:值中保留子节点列表,可标记 nav/footer/section 等语义区域。 -- `layout.stack` / `布局.纵排`:声明上下关系。 -- `layout.columns` / `布局.分栏`:声明响应式横向栏目。 -- `merge`:只确定兄弟顺序,不会自动产生双栏,也不提前渲染 HTML。 - -原生运行时提供基本布局几何,窄屏自动折叠。style 列引用类名,不承载 CSS 源码,也不会自动定义主题。父块始终保留结构值;先渲染子块再拼 HTML 会丢失这条统一路径。 - -## 从文件走到真正页面 - -[英文参考工程](../../examples/web-layout-handbook/index.mq.md)与[中文参考工程](../../examples/web-layout-handbook-zh/index.mq.md)实现上面的整个拆分树。先运行 preview.mq.md 检查真实渲染,再进入工程目录运行 serve.mq.md。 - -结构化 Document 显式声明 `view: main` / `视图: main`,main 返回节点;服务启动时装配一次。普通 Markdown Document 保留既有行为,Endpoint 单独处理请求期互动。改动结构或叶子内容后重启。自动数据源绑定继续使用普通 Document,避免与启动装配混用。 - -验收同时检查源码和产物:叶子只含普通 Markdown,父文件只表达其一层关系;桌面页脚出现真正的两层分栏,手机两层都折叠;关于页、API 仍能工作。规则清单本身不是“已经通过”的证明。 - -```bash -cargo test --locked --test web_handbook -node tests/web/layout.browser.cjs /absolute/path/to/preview.html -``` - -详细测试方式和当前能力边界见[优化记录](ext-web-handbook.md)。 diff --git a/doc/design/ext-web-net.md b/doc/design/ext-web-net.md deleted file mode 100755 index 9b12758..0000000 --- a/doc/design/ext-web-net.md +++ /dev/null @@ -1,285 +0,0 @@ -# 网络扩展波次:`ext/web` 鉴权 · WebSocket · 标准库网络原语 - -| | | -|---|---| -| 状态 | **Draft(本波次锁定设计)** | -| 日期 | 2026-08-24 | -| 相关 | [ext-web.md](ext-web.md) · [ext-abi.md](ext-abi.md) · [stdlib-modules.md](stdlib-modules.md) · [ext-cli.md](ext-cli.md) | -| 目标 | 补齐 `ext/web` 登录鉴权(session/cookie)、WebSocket 端点;为网络扩展所需的**基础设施解析原语**适当补强 `lib/net`(标准库)。 | - ---- - -## 0. 一句话 - -**领域能力(鉴权、WebSocket 服务器)全部走 ABI 插件 `plugins/web`;纯解析基础设施(cookie / multipart 解析、WS 客户端)按需进入标准库 `lib/net`,因为标准库需要支撑扩展库开发。** - ---- - -## 1. 边界判定:什么进标准库 `lib/net`,什么进扩展 - -### 1.1 跨语言调研结论 - -| 语言 | 标准库 | 扩展/生态 | 边界准则 | -|------|--------|----------|---------| -| Python | `urllib`(URL/基础 HTTP)、`http.cookies`(**cookie 解析器在标准库**) | `requests`/`httpx`(session/连接池/便利层) | 标准库 = 基础设施原语(解析器);便利层 = 第三方 | -| Node.js | `http`/`https`/`http2`(低层流式,不解析 body) | express、ws、formidable | 足够 fancy 就不进核心;核心只放几乎人人要用的低层原语;**先 userland 验证再拉进 core** | -| Go | `net/http`(服务器+客户端都在标准库)、`net/http/cookiejar`(**RFC 6265 cookie jar 在标准库**) | `golang.org/x/net`(publicsuffix 等演进性) | HTTP 是「与 stdin 同级」的核心能力;**cookie 解析/管理进标准库**;持久化等演进性能力在外 | -| Rust | 极小 std(无 HTTP) | `http`(词汇)→ `hyper`(传输)→ `reqwest`(便利) | 分层;HTTP 因生态多样不进 std | - -**共识**: -1. **cookie 解析/管理(RFC 6265)**在 Python/Go 都是**标准库**(`http.cookies`、`net/http/cookiejar`)。 -2. **multipart/form-data 解析**在 Go 是标准库(`net/http`),在 Python 是第三方 `multipart`。 -3. **WebSocket** 几乎总在扩展/第三方(Node `ws`、Python `websockets`、Go `gorilla/websocket`),**很少进语言标准库**。 -4. **session 是领域级便利**,几乎所有语言都在框架层(express-session、Django session),不在语言标准库。 - -### 1.2 Marqdo 判定(锁定) - -| 能力 | 类型 | 归属 | 理由 | -|------|------|------|------| -| `cookie.parse` / `cookie.parse_response` | 基础设施解析 | **`lib/net`(标准库)** | 对齐 Go/Python 标准库;`ext/web` 鉴权依赖 | -| `multipart.parse` | 基础设施解析 | **`lib/net`(标准库)** | 对齐 Go 标准库;`ext/web` 文件上传依赖 | -| `ws.connect`(客户端) | 基础连接 | **`plugins/web`(ABI)+ `ext/web`** | WS 栈(tokio-tungstenite)已在 web 插件依赖链;核心 `Cargo.toml` 锁定 rustc 1.81 不宜再引入 WS 栈;符合「尽量只 ABI」 | -| `web.session_*`(session 管理) | 领域 | **`plugins/web`(ABI)+ `ext/web`** | session 是框架层便利,不进标准库 | -| `/admin` 登录鉴权 | 领域 | **`plugins/web`(ABI)+ `ext/web`** | 网站领域能力 | -| `web_ws`(服务器端点) | 领域 | **`plugins/web`(ABI)+ `ext/web`** | WebSocket 服务器是网站能力 | - -**实现约束(用户要求)**: -- 标准库新增的**解析原语**(cookie/multipart)是纯函数、无网络 I/O,作为 L0.5 宿主原语进 `src/host/`(与 `url_encode` 同模式),由 `lib/net` 薄包装——这符合「标准库需要支持扩展库开发」。 -- **涉及网络 I/O 的 WS 能力**(客户端 + 服务器端点)一律进 `plugins/web`(ABI v2),由 `ext/web` / `ext/web/网页.mq.md` 包装。核心运行时(rustc 1.81 锁定)**不再新增** WS 栈依赖。 -- **网站领域能力**(session、鉴权中间件)一律进 `plugins/web`(ABI v2),由 `ext/web` 包装。 -- **禁止**:为这些能力修改核心语法;禁止在 `src/host/` 塞领域逻辑。 - ---- - -## 2. 标准库 `lib/net` 新增(基础设施原语) - -### 2.1 `cookie.parse` / `解析Cookie` -- 形参:`text`(`Cookie:` 请求头或 `Set-Cookie:` 响应头) -- 结果:`[{name, value, path, domain, expires, max_age, secure, http_only, same_site}]` -- 行为:RFC 6265 解析;`Set-Cookie` 多 cookie 分条;无属性则字段为空。 - -**英文(`lib/net.mq.md`):** -```markdown -## cookie_parse - + `text` - -**> host_cookie_parse text=`text`** -``` - -**中文(`lib/网络.mq.md`):** -```markdown -## 解析Cookie - + `内容` - -**> host_cookie_parse text=`内容`** -``` - -### 2.2 `multipart.parse` / `解析多部分` -- 形参:`body`(文本)、`boundary` -- 结果:`[{name, filename, content_type, value}]`(`value` 为字段值;文件字段用 `filename` + `content_type` + `value`(base64 或文本)) -- 行为:解析 `multipart/form-data` 正文;字段名 → value;文件字段带 filename。 - -**英文:** -```markdown -## multipart_parse - + `body` - + `boundary` - -**> host_multipart_parse body=`body` boundary=`boundary`** -``` - -**中文:** -```markdown -## 解析多部分 - + `正文` - + `边界` - -**> host_multipart_parse body=`正文` boundary=`边界`** -``` - -### 2.3 WebSocket 客户端 — 见 §3.4(`plugins/web` ABI) - -WS 客户端为领域能力,放 `plugins/web`(ABI)而非标准库,理由见 §1.2。`lib/net` 不新增 WS 客户端包装,避免标准库依赖 ext 插件。 - ---- - -## 3. `plugins/web`(ABI v2)新增:领域能力 - -### 3.1 Session 存储(`web_session_*`) -插件进程内 `static` 内存存储(`HashMap<session_id, HashMap<String,Value>>`),与 `web_listen` 同生命周期。 - -| ABI 名 | 形参 | 结果 | -|--------|------|------| -| `web_session_new` | 可选 `ttl_sec` | `{id}`(新 session id) | -| `web_session_set` | `id`, `key`, `value` | `{ok:true}` | -| `web_session_get` | `id`, `key` | 值或 `{ok:false}` | -| `web_session_del` | `id`, `key` | `{ok:true}` | -| `web_session_destroy` | `id` | `{ok:true}` | - -### 3.2 `/admin` 登录鉴权(`web_auth_*`) -- 作者面:`web.auth` 类(`网页.鉴权`),形参 `admin_users`(`|用户名|密码|` 表)、可选 `session_ttl`。 -- `listen` 时若配置了 auth:`/admin*` 未登录 → 跳转 `/admin/login`;登录页 `POST` → 校验 `admin_users` 表 → 写 session cookie → 重定向。 -- 登出:`/admin/logout` → 销毁 session。 - -| ABI 名 | 形参 | 结果 | -|--------|------|------| -| `web_auth_login` | `username`, `password`, `users`, `session_ttl` | `{ok:true, session_id}` 或 `{ok:false}` | -| `web_auth_check` | `session_id`, `users` | `{ok:true}` 或 `{ok:false}` | -| `web_auth_logout` | `session_id` | `{ok:true}` | - -### 3.3 WebSocket 服务器端点(`web_ws_route`) -- 作者面:`app.route_ws` / `应用.路由实时`,形参 `path`、可选 `echo=True`。 -- `listen` 时 `{path}` 升级为 WS:`echo=True` 回发原文;否则接收并丢弃(扩展点)。 - -| ABI 名 | 形参 | 结果 | -|--------|------|------| -| `web_app_route_ws` | `app`, `path`, `echo` | `{app}`(登记 WS 端点) | - -### 3.4 WebSocket 客户端(`web_ws_connect`) -- 作者面:`web.ws` / `网页.实时`,形参 `url`、`message`、可选 `headers`、`timeout_sec`。 -- 行为:客户端连接一次 WS,发 `message`,收**全部**服务器回文后关闭。**单请求-响应式**(非长驻),与 Marqdo 同步模型一致。 - -| ABI 名 | 形参 | 结果 | -|--------|------|------| -| `web_ws_connect` | `url`, `message`, `headers`(map), `timeout_sec` | `{ok:true, messages:[…]}` 或 `{ok:false, error}` | - -**英文(`ext/web/web.mq.md`):** -```markdown -# ws - + `timeout_sec`=30 - -## connect - + `url` - + `message` - + `headers`=None -``` - -**中文(`ext/web/网页.mq.md`):** -```markdown -# 实时 - + `超时秒`=30 - -## 连接 - + `地址` - + `消息` - + `headers`=None -``` - -> `plugins/web` 用 `tokio-tungstenite`(与 axum WS 同栈,版本兼容 rustc 1.81)。 - ---- - -## 4. `ext/web` 作者面新增 - -### 4.1 英文面(`web.mq.md`) - -```markdown -# auth - + `users` # |用户名|密码| 表 - + `session_ttl`=3600 - -## login - + `username` - + `password` - -## check - + `session_id` - -## logout - + `session_id` -``` - -`# app` 新增 `## route_ws`: -```markdown -## route_ws - + `path` - + `echo`=True -``` - -### 4.2 中文面(`网页.mq.md`) - -```markdown -# 鉴权 - + `用户表` - + `会话时长`=3600 - -## 登录 - + `用户名` - + `密码` - -## 校验 - + `会话id` - -## 登出 - + `会话id` -``` - -`# 应用` 新增 `## 路由实时`: -```markdown -## 路由实时 - + `路径` - + `回显`=真 -``` - -### 4.3 用法示例(英文) - -```markdown -# main - -`admins` = -| 用户名 | 密码 | -|--------|------| -| admin | secret | - -*store = > db.open * -*page = > web.page title="Site" * -*app = > web.app page=`page` db=`store` admin=True host=127.0.0.1 port=18081 * -*app = > `app`.route_ws path="/live" echo=True * -*app = > web.auth users=`admins` * -> `app`.listen - -*echo = > web.ws.connect url="ws://127.0.0.1:18081/live" message="hi" * -``` - ---- - -## 5. form 完善(现有功能验证 + 补测试) - -现状已具备(无需改代码,需验证): -- `action=update`:hidden `id` + `db.update`(form.rs `from_schema`/`submit` 已实现) -- 校验失败页级回显:`submit_and_respond` → `render_page_ex`(http.rs 已实现) - -本波次为 update 流程和页级回显补 gold 测试,确认端到端可用。 - ---- - -## 6. 测试与验收 - -| 测试 | 内容 | -|------|------| -| `tests/ext/web-net-smoke.mq.md` | session new/set/get/del + auth login/check/logout + `route_ws`/`app.auth` 登记 + ws 连接失败路径(离线) | -| `tests/lib/net-cookie.mq.md` | `cookie_parse` 解析 | -| `tests/lib/net-multipart.mq.md` | `multipart_parse` 解析 | -| `tests/ext/web-admin-smoke.mq.md` | form `action=update` 全流程 + 校验失败 `errors` 回显 | -| 现有 gold | 全量回归(树遍历 + 字节码) | - -验收:`cargo test --test gold` 全绿(除网络 live),双后端一致。 - -### 6.1 字典操作约束(作者面) - -Marqdo 原生字典操作:GFM 横表**构造**、脚注取元 `变量[^键]` **读取**。`ext/web` 作者面**不使用** `json.get` / `json.set` 做字典读取/改写——所有字段读取一律 `self[^键]`(或实例变量 `[^键]`),避免"用 json 标准库做字典操作"的反模式。`json.parse` / `json.stringify` 仅用于文本 ↔ 结构化数据的序列化转换(如 HTTP body 解析),不用于本地字典读写。 - -### 6.2 相对路径按入口脚本解析(host_query `entry_dir`) - -`static_dir`(如 `public`)与相对 db 路径(如 `sqlite:data/site.db`)此前按**进程 cwd** 解析——从仓库根目录跑 `examples/*/index.mq.md` 时,`/static` 404、db 会建到根目录,这是错误行为。 - -本波次修复:宿主新增 `host_query("entry_dir")`(返回入口 `.mq.md` 所在目录的绝对路径,回退 cwd),`plugins/web` 的 `web_listen` 将相对 `static_dir`、`db_url_of` 将相对 db 路径统一 `entry_dir().join(...)` 到绝对路径。于是无论从仓库根目录还是示例目录运行,静态资源与数据库都落在**脚本目录**下。绝对路径不受影响;`host_query` 不可用时回退旧 cwd 行为。 - ---- - -## 7. 非本波次 - -- Postgres / Redis / S3 驱动(roadmap W4,另行) -- WS 广播房间、多客户端(先 echo 单连接) -- session 持久化到 SQLite / 文件(先内存) -- 复杂权限 / RBAC \ No newline at end of file diff --git a/doc/design/ext-web-rbac.md b/doc/design/ext-web-rbac.md deleted file mode 100755 index 887dc46..0000000 --- a/doc/design/ext-web-rbac.md +++ /dev/null @@ -1,81 +0,0 @@ -# `ext/web` 可配置 RBAC(角色 ⊥ 权限) - -| | | -|---|---| -| 验收 | qdqc:门禁 `desk:access` + 评论权限;`tests/ext/web-rbac-*-smoke.mq.md` | -| 状态 | **Accepted · 已落地核心**(gate permissions;`/_rbac/*` 管理台 **opt-in** `管理台=真`) | - ---- - -## 0. 一句话 - -权限是原子能力(`resource:action`);角色是权限包;用户通过 `user_roles` 获得角色。门禁与业务都问 `can(user, permission)`。管理员可在后台新建角色、勾选权限、赋给用户——**禁止**只靠写死的 `role=admin|user` 字符串作为唯一模型(兼容期仍可读旧 `roles=` gate)。 - ---- - -## 1. 表结构(SQLite / Postgres 同构) - -| 表 | 列 | -|----|-----| -| `web_permissions` | `code` PK, `resource`, `action`, `description` | -| `web_roles` | `id` PK, `name` UNIQUE, `is_system` INT, `tenant_id` TEXT NULL | -| `web_role_permissions` | `role_id`, `permission_code` PK(role_id, permission_code) | -| `web_user_roles` | `user_id`, `role_id`, `tenant_id` TEXT NULL, PK(user_id, role_id, tenant_id) | -| `web_users` | `id` PK, `username` UNIQUE, `password_hash`, `created_at` | - -命名带 `web_` 前缀,避免与业务表冲突。站点也可映射自定义表名(后期);首版固定。 - ---- - -## 2. 权限码约定 - -形如 `comments:create`、`desk:access`、`roles:manage`。内置种子见 `DefaultCatalog`。`*` 或角色名 `superadmin` / 兼容 `admin`:登录时展开为目录全集。 - ---- - -## 3. 作者 API - -```markdown -**`应用` = > `应用`.权限 确保结构=真 目录=`权限目录`** -**`应用` = > `应用`.门禁 路径="/desk" 权限="desk:access" 匹配="prefix" 拒绝="redirect"** -**`应用` = > `应用`.鉴权 用户表=`管理员` 注册=真 注册路径="/register" …** -``` - -| 方法 | ABI | 说明 | -|------|-----|------| -| `app.rbac` / `启用权限` | `web_app_rbac` | ensure schema;可选 `目录`;`管理台=真` 才挂 `/_rbac/*` | -| `app.gate` | `web_app_gate` | 新增 `permissions`/`权限`(CSV);与 `roles` 可并存:有 permissions 时按权限判定 | -| `rbac.can` | `web_rbac_can` | `{ok, allowed}` | -| `rbac.assign_role` | `web_rbac_assign_role` | 用户←角色 | -| `rbac.set_role_permissions` | `web_rbac_set_role_permissions` | 角色←权限列表 | - -防提权:`set_role_permissions` / `assign_role` 在 HTTP 管理面检查操作者 `roles:manage` 且不能授予自身没有的 permission。 - ---- - -## 4. 运行时 - -1. `listen`:若 `auth.rbac=true` 或调用过 `app.rbac`,对 `db` URL `EnsureSchema` + 种子。 -2. 仅当 `auth.rbac_desk=true`(`启用权限 管理台=真`)时挂载 `/_rbac/*` API 与 desk。 -3. 登录成功:解析角色 → DB `user_roles` ∪ GFM 角色展开 → session `permissions`(CSV)+ 兼容 `role`。 -4. `withRBAC`:gate 含 `permissions` 则 `PermissionAllowed`;否则旧 `RoleAllowed`。 -5. 注册:`POST /register` 写入 `web_users`,默认赋 `member` 角色。 - ---- - -## 5. qdqc 映射 - -| 产品 | 权限码 | -|------|--------| -| 发评论 | `comments:create` | -| 删任意评论 | `comments:delete` | -| 进 desk | `desk:access` | -| 管角色 | `roles:manage` | - -首个 GFM `admin` 用户登录后视为 `superadmin`(全权限);DB 迁移后绑定 `superadmin` 角色。 - ---- - -## 6. 非目标(本切片) - -对象级 ACL 全图、ABAC;租户列先可空,多租户波次再启用。 diff --git a/doc/design/ext-web-request-context.md b/doc/design/ext-web-request-context.md deleted file mode 100755 index 3fbf236..0000000 --- a/doc/design/ext-web-request-context.md +++ /dev/null @@ -1,91 +0,0 @@ -# ext/web:请求上下文与表单字段来源 - -| | | -|---|---| -| 状态 | **Accepted** | -| 日期 | 2026-09-18 | -| 相关 | [ext-web.md](ext-web.md) §5.5 · 对照 Django `request.user` / URL kwargs | -| 动机 | 禁止扩展库按业务表名(如 `comments`)特判填字段;身份与路由键属于请求上下文 | - ---- - -## 0. 原则 - -1. **扩展库提供机制,站点表达领域** — 不得出现 `if table == "comments"`。 -2. **身份只从 session 来,且服务端盖戳** — 客户端提交的 `author` 等不可信。 -3. **资源键从路由参数来** — 页面已在 `/post/{slug}` 时,表单继承该页 `params`,不解析 Referer 猜 slug。 -4. **非 `client` 来源的字段默认不渲染** — 服务端在校验前写入;若 POST 带同名键,一律覆盖丢弃。 - ---- - -## 1. 请求上下文(Request) - -每次处理 HTTP 请求时,框架逻辑上持有: - -| 键 | 含义 | -|----|------| -| `user` / `username` | 登录名;访客为空 | -| `params` | 动态路由捕获(如 `{slug}`) | -| `path` | 请求路径 | -| `method` | GET / POST / … | -| `query` | URL 查询(可选) | - -与 Django 对应:`request.user`、`request.resolver_match.kwargs`、`request.path`。 - -页面渲染时已有 `page.params`(`injectParams`)。表单提交时通过隐藏字段 `_mq_params`(JSON)与 `_mq_return`(回跳路径)把**渲染该表单时的页上下文**带回 POST,避免依赖 Referer。 - ---- - -## 2. 字段表「来源」列 - -字段表增加可选列 `来源` / `source`(缺省 = `client`): - -```markdown -| 字段 | 标签 | 类型 | 必填 | 默认 | 来源 | -|------|------|------|------|------|------| -| body | 写下你的想法 | textarea | true | | client | -| author | | | true | | session.username | -| post_slug | | | true | | route.slug | -| created_at | | | false | | now | -``` - -| 来源值 | 含义 | 渲染 | -|--------|------|------| -| `client` / 空 | 用户填写 | 正常控件 | -| `session.username` / `session.user` / `user` | 当前登录用户名 | 不渲染 | -| `route.NAME` / `param.NAME` / `params.NAME` | `params[NAME]` | 不渲染 | -| `now` / `utc.now` / `server.now` | UTC `YYYY-MM-DD HH:MM:SS` | 不渲染 | - -`类型=hidden` 仍可显式使用;与 `来源≠client` 叠加时仍不依赖客户端值(服务端覆盖)。 - ---- - -## 3. 提交管线 - -``` -ParseForm → 去掉来源≠client 的 POST 键 - → 按字段来源从 Request 写入 - → validate → insert/update - → 回跳:优先 _mq_return(同站路径),否则 form.redirect -``` - -伪造 `author` / `post_slug` 无效。 - ---- - -## 4. 页面列表装配(副绑定) - -详情页可附加与主主体**不同查询条件**的列表绑定(如评论): - -```markdown -**post = > post.列表装配 主体=`评论卡片` 条件=`评论条件` 排序="-created_at"** -``` - -条件值同样支持 `{slug}`。渲染在主文章/卡片区之后,无需为子资源单独写 JSON API + 前端过滤。 - ---- - -## 5. 非目标 - -- 不在扩展库内实现「评论」领域类型。 -- 不把 Referer 解析当作正式 params 来源(仅兼容期可作 `_mq_params` 缺失时的弱回退,金样不依赖)。 diff --git a/doc/design/ext-web-spa.md b/doc/design/ext-web-spa.md deleted file mode 100755 index e0b97d0..0000000 --- a/doc/design/ext-web-spa.md +++ /dev/null @@ -1,24 +0,0 @@ -# Native SPA(Marqdo WASM 全页客户端) - -| | | -|---|---| -| 状态 | **Accepted · MVP** | -| 日期 | 2026-09-17 | -| 相关 | [browser-marqdo-wasm.md](browser-marqdo-wasm.md) · route D/E | - -## 约定 - -| 表 | 列 | 用途 | -|----|-----|------| -| 客户端路由 | `路径` / `面板` / `标题` | 文档化视图;运行时用 `path` + `set_attr(hidden)` 切换 | -| 客户端状态 | `browser.store_set` / `store_get` `scope=memory` | 页内状态(列表 JSON、当前 id) | - -作者零业务 JS:`web.client_embed` + `static/client.mq.md` + `lib/browser`。 - -## Bridge - -`storage` effect 支持 `scope=memory`(进程内 `Map`),与 `local` / `session` / `cookie` 并列。 - -## Demo - -`examples/web-spa-app/` — 列表 → 详情 → 编辑,全客户端路由。 diff --git a/doc/design/ext-web-tenant.md b/doc/design/ext-web-tenant.md deleted file mode 100755 index ee59b77..0000000 --- a/doc/design/ext-web-tenant.md +++ /dev/null @@ -1,23 +0,0 @@ -# ext/web multi-tenant (path / subdomain / header) - -| | | -|---|---| -| 状态 | **Accepted · MVP** | -| 日期 | 2026-09-17 | -| 相关 | [ext-web-rbac.md](ext-web-rbac.md) · full-ambition plan | - -## Author API - -```markdown -**应用 = > `应用`.tenant mode="path" param="t" column="tenant_id" default_scope=False** -``` - -JSON route table may set `tenant_scope` / `租户作用域` = true so `GET /api/items?t=acme` only returns rows with `tenant_id=acme`. - -## Runtime - -1. `withTenant` resolves id into request context. -2. Scoped JSON selects `AND tenant_id=?`; missing tenant → 400. -3. `default_scope=True` also stamps form POST bodies. - -Demo: `examples/web-tenant-saas/`. diff --git a/doc/design/ext-web.md b/doc/design/ext-web.md deleted file mode 100755 index 8fa70ce..0000000 --- a/doc/design/ext-web.md +++ /dev/null @@ -1,610 +0,0 @@ -# 官方扩展:`ext/web` 动态网站 - -| | | -|---|---| -| 状态 | **Superseded(作者面)· 历史能力档案** — 现行作者面见 **[ext-web-artifact.md](ext-web-artifact.md)** · ADR [0007](../adr/0007-web-document-endpoint.md) | -| 日期 | 2026-08-11(W8:2026-08-29;请求上下文:2026-09-18;Artifact 重构:2026-09-28) | -| 相关 | [ext-web-artifact.md](ext-web-artifact.md) · [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) · **[ext-web-request-context.md](ext-web-request-context.md)** | -| 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) | -| 本文目的 | **历史**类 API 与能力矩阵;新站请勿按本文 `compose_*` / `app.configure` 写作 | - -> **2026-09-28**:作者面迁移到 Document / Endpoint / Resource。C1 已由 ADR 0007 修订。下文保留作迁移对照,**不是**现行推荐 API。 - ---- - -## 0. 一句话 - -**现行**:`.mq.md` Artifact(`type: web|endpoint`)描述页面与交互;见 [ext-web-artifact.md](ext-web-artifact.md)。 - -**历史(废止)**:`ext/web` 曾用 GFM 表格 + `# page`/`# app` 类方法拼装站点。该模型因 God Object / 碎片 DSL / 隐式路由被破坏性替换。 - ---- - -## 1. 为何要做网络扩展库 - -### 1.1 问题 - -若没有专用扩展,作者只能: - -- 手写 JSON 袋、`json.set` 拼装组件/样式;或 -- 要求改语言(让表格单元格求值、点号取值等)。 - -二者都破坏 Marqdo 的「代码即文档」。 - -### 1.2 答案 - -在 **`ext/web/web.mq.md`(英文)** 与 **`ext/web/网页.mq.md`(中文)** 中各提供一套 **`#` 类**: - -- 作者只写**表** + **少量实例方法调用**; -- 表单元格保持**字面量**; -- **寻址字符串**由类方法解析; -- **导入英文文件 → 只用英文 API;导入中文文件 → 只用中文 API**(见 [stdlib-i18n.md](stdlib-i18n.md))。 - -### 1.3 硬约束(评审锁定) - -| # | 约束 | -|---|------| -| C1 | **修订(ADR 0007)**:核心可识别 Artifact `type: web\|endpoint`(及 ZH);**不**新增 CORE_CONSTRUCTS 标记;单元格求值 / import 句法不变;装配语义仍在 ext + plugin。旧文「禁止为 web 改核心」作废 | -| C2 | 作者面**禁止** `json.parse` / `json.set` 袋胶水(现行见 ext-web-artifact A2) | -| C3 | 中英分文件;同文件禁止混 API(现行 A3) | -| C4 | **废止**「页面表 + compose」心智 → Document Artifact + `pages/` · `api/` | -| C5 | 破坏性重写作者面(ADR 0007);原生 Go 演进见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md) | -| C6 | DB 迁至 **`ext/data`**;CRUD 仍须完整(`select` / `查询`) | -| C7 | 表单校验仍须在写库前执行;挂载经 declared Endpoint / system `/_form`(inspect 可见) | -| A1–A8 | **现行硬约束**见 [ext-web-artifact.md](ext-web-artifact.md) §9 | - ---- - -## 2. 作者心智与目录 - -```text -myapp/ - index.mq.md # 入口 + 首页:页面表 +(可选)就地主体表 + 类方法 + listen - pages/ # 子页:同形的页面表(导出布局表或由入口再装配) - components/ # 可复用组件:导出与路径同名的 ##,体为 |属性|值|样式| - styles/ # 样式模块:每个样式一个 ##,体为 |属性|值| - db/ # 库:schema 表 +(可选)open/种子 - data/ # sqlite 等运行时数据(gitignore) -``` - -| 表种 | 列 | 一句话 | -|------|-----|--------| -| **页面表** | `组件` \| `样式` | 本页用哪些组件、各套哪套样式 | -| **组件 / 主体表** | `属性` \| `值` \| `样式` | 前端属性 ↔ 取值(库字段或字面量)↔ 样式名 | -| **样式表** | `属性` \| `值` | CSS 声明 | -| **库结构表** | `字段` \| `类型` \| `可空` | schema | - ---- - -## 3. 表内寻址约定(单元格仍是字符串) - -单元格**不求值**。下列写法是 **web 扩展约定的路径文本**,由 `# 页面` / `# 样式` / `# 数据库` 的方法解析。 - -### 3.1 反引号与裸名 - -| 含义 | 写法 | 例 | -|------|------|-----| -| 要「去导入树 / 定义里解析」的名字 | 反引号 `` `名` `` | `` `nav` ``、`` `title` ``、`` `topnav` ``、`` `articles` ``(表名) | -| 字面量(文案、URL、CSS 属性名/值、SQL 类型、**列名**) | **裸**或 `"…"` | `首页`、`/about`、`font-size`、`integer`、`title`(作为列名时) | - -### 3.2 路径形态(锁定) - -| 场景 | 形态 | 例 | 方法内语义 | -|------|------|-----|------------| -| 引用导入模块的导出 | `模块.`导出`` | `nav.`nav``、`shell.`topnav`` | 在**站点入口模块**的 import 树上调用 `模块.导出`(零参 `##`),取回表 Value | -| 引用库字段 | `模块.`表`.列` | `articles.`articles`.title` | 模块名 = 命名空间(对应导入的 db 文件);`` `表` `` = 库表名;**列名裸写**(列不是变量)→ 运行时绑定 `表.列` | -| 前端属性名 | `` `title` `` | 组件表「属性」列 | 解析为字段名 `title` | -| 样式引用 | 同「模块.导出」或纯样式名 | `shell.`card-title`` | 取回 `|属性|值|` 表并编译为 CSS 类 | - -**刻意不做的事:** - -- 不把「组件变量名」魔法等同于「库表名」; -- 不要求作者写 `json.set` 才能把 `nav` 放进袋; -- 不把 `articles.`articles`.title` 做成语言级表达式。 - -### 3.3 与模块命名空间的关系 - -- 库名来自 frontmatter 导入(茎名或 `as`),**裸名**,见 [module-namespace.md](module-namespace.md)。 -- `nav.`nav`` 中:前段 `nav` = 导入库名;`` `nav` `` = 该库上的 `## nav` 导出。 -- 组件/样式文件应导出 **与路径第二段同名的 `##`**,直接返回表(不要 `## bag` / `## bind` 袋)。 - ---- - -## 4. 规范示例:`index.mq.md`(作者面唯一样板) - -**语言与导入绑定(锁定,纠正手写混用):** - -| 导入 | 库名(默认茎) | 类 / 方法 / 形参 | -|------|----------------|------------------| -| `import web:ext/web/web.mq.md` | `web` | **仅英文**:`page` · `compose_components` · `db` · `app` · `components=` … | -| `导入 网页:ext/web/网页.mq.md` | `网页` | **仅中文**:`页面` · `组件装配` · `数据库` · `应用` · `组件=` … | - -禁止:`import web:ext/web/web.mq.md` 后写 `web.页面` / `` `页`.组件装配 ``(英文库混中文成员)。 -禁止:在 `web.mq.md` 文件内定义中文 `## 组件装配` 别名。中英对等靠**两个文件**,不靠同一文件双份导出。 - -### 4.1 英文面(导入 `web.mq.md`) - -```markdown ---- -title: web-site -description: Home = page table; main may be inline; class methods assemble. -import: - web: ext/web/web.mq.md - shell: styles/shell.mq.md - nav: components/nav.mq.md - side: components/side.mq.md - foot: components/foot.mq.md - articles: db/articles.mq.md - db: db/index.mq.md ---- - -# main - -`home` = - -| 组件 | 样式 | -|------|------| -| nav.`nav` | shell.`topnav` | -| side.`side` | shell.`side-panel` | -| foot.`foot` | | - -Main content is not a reusable component, so it is authored here. - -`index` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| `title` | articles.`articles`.title | shell.`card-title` | -| `body` | articles.`articles`.body | shell.`card-body` | - -*`store` = > db.open * -*`page` = > web.page title="Marqdo Web Site" intro="<h1>Web Site</h1>" * -*`page` = > `page`.compose_components components=`home` * -*`page` = > `page`.compose_main main=`index` * -*`app` = > web.app page=`page` db=`store` admin=True host=127.0.0.1 port=18081 * -> `app`.listen -``` - -说明:表头列名可用中文(`组件`/`样式`/`属性`/`值`)——那是**表约定词汇**,不是库成员名;库成员必须与导入语言一致。 - -### 4.2 中文面(导入 `网页.mq.md`) - -```markdown ---- -title: 站点 -导入: - 网页: ext/web/网页.mq.md - shell: styles/shell.mq.md - nav: components/nav.mq.md - side: components/side.mq.md - foot: components/foot.mq.md - articles: db/articles.mq.md - db: db/index.mq.md ---- - -# main - -`首页` = - -| 组件 | 样式 | -|------|------| -| nav.`nav` | shell.`topnav` | -| side.`side` | shell.`side-panel` | -| foot.`foot` | | - -主体不是可复用组件,因此就地撰写。 - -`index` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| `title` | articles.`articles`.title | shell.`card-title` | -| `body` | articles.`articles`.body | shell.`card-body` | - -*`库` = > db.open * -*`页` = > 网页.页面 标题="站点" 引言="<h1>站点</h1>" * -*`页` = > `页`.组件装配 组件=`首页` * -*`页` = > `页`.主体装配 主体=`index` * -*`应用` = > 网页.应用 页面=`页` 数据库=`库` 后台=True 主机=127.0.0.1 端口=18081 * -> `应用`.监听 -``` - -**允许出现在 index 的非表内容:** frontmatter 导入、开库一行、构造页面/应用并装配、`listen` / `监听`。 -**不允许:** `json.*` 袋、手写 `/_part` 注册、中英 API 混用。 - ---- - -## 5. 类 API(分文件 · 分语言) - -依据 [stdlib-i18n.md](stdlib-i18n.md):**导入哪个文件,就用哪套名字。** -`ext/web/web.mq.md` = 全英文;`ext/web/网页.mq.md` = 全中文。中文实现可委托插件同一套原语,或薄封装英文库,但**对外导出的 `#` / `##` / 形参名必须是中文**。 - -### 5.1 页面 · `page` / `页面` - -**英文(`web.mq.md`):** - -```markdown -# page - + `title`=… - + `intro`=… - -## compose_components - + `components` # page table |组件|样式| - -## compose_main - + `main` # bind table |属性|值|样式| -``` - -**中文(`网页.mq.md`):** - -```markdown -# 页面 - + `标题`=… - + `引言`=… - -## 组件装配 - + `组件` - -## 主体装配 - + `主体` -``` - -| 行为 | 说明 | -|------|------| -| compose_components / 组件装配 | 解析组件·样式路径 → 填 nav/sidebar/footer → CSS → 登记 part | -| compose_main / 主体装配 | 解析库字段与样式路径 → 填 main → 登记 part(如 id=`index`) | -| compose_list / 列表装配 | 副绑定(独立 query/order);可选 target 注入引言元素;见 [ext-web-request-context.md](ext-web-request-context.md) | - -**槽位推断:** 由组件导出名决定(`nav`→顶栏,`side`→侧栏,`foot`→底栏;其余→main)。 - -### 5.2 样式 · `style` / `样式` - -**英文:** `# style` · `## process` · `+ style=` / `name=` / `path=` -**中文:** `# 样式` · `## 样式处理` · `+ 样式=` / `名=` / `路径=` - -页面装配可内部调用;作者一般不必在 index 显式调。 - -### 5.3 数据库 · `db` / `数据库` - -完整**增删改查**;页面绑定、种子、`/admin`、表单提交共用。 - -**英文(`web.mq.md`):** - -```markdown -# db - + `url`=… - -## init - + `name` - + `fields` # or table= schema - -## insert - + `table` - + `rows` - -## select - + `table` - + `where`=None # optional simple filters - + `limit`=200 - -## get - + `table` - + `id` - -## update - + `table` - + `id` - + `row` - -## delete - + `table` - + `id` - -## exec - + `sql` - + `args`=None # escape hatch: raw SQL (not everyday authoring) -``` - -**中文(`网页.mq.md`):** - -```markdown -# 数据库 - + `地址`=… - -## 初始化 - + `数据库表` # 或 名= + 字段= - -## 插入 - + `表` - + `行` # 或 多行= - -## 查询 - + `表` - + `条件`=None - + `上限`=200 - -## 获取 - + `表` - + `id` - -## 更新 - + `表` - + `id` - + `行` - -## 删除 - + `表` - + `id` - -## 执行 - + `sql` - + `参数`=None -``` - -| 中文 | 英文 | 职责 | -|------|------|------| -| 初始化 | `init` | 建表;登记表名 | -| 插入 | `insert` | 增 | -| 查询 | `select` | 查列表(可带简单条件 / limit) | -| 获取 | `get` | 按主键一行 | -| 更新 | `update` | 改 | -| 删除 | `delete` | 删 | -| 执行 | `exec` | 可选原始 SQL(进阶) | - -`table=` / `表=` 接受表名或句柄;行数据优先 GFM 表。 -**命名锁定:** 列表查询用 `select` / `查询`,**不用** `all`;原始 SQL 用 `exec` / `执行`,避免与 `select` 混淆。 - -### 5.4 应用 · `app` / `应用` - -**英文:** `# app` · `## route` · `## static` · `## listen` · 形参 `page` `db` `admin` `host` `port` -**中文:** `# 应用` · `## 路由` · `## 静态` · `## 监听` · 形参 `页面` `数据库` `后台` `主机` `端口` - -`listen` / `监听`:加载插件、注入 `db_url`、按页面 part 提供 `/_part/{id}`(首页)与 `{path}/_part/{id}`(`app.route` 页)、可选 `static` 目录挂载、启动 HTTP。作者不必手写 part 注册。 - -`static` / `静态`:`dir=`(或 `目录=`)+ 可选 `mount=`(默认 `/static`);`listen` 时用 `tower-http` 提供只读文件服务。 - -### 5.5 表单 · `form` / `表单`(规划锁定) - -用户输入也走「表 + 类方法」,与页面/库同一心智;**提交最终调用 `# db` 的 insert/update**,不另开旁路。 - -**英文(`web.mq.md`):** - -```markdown -# form - + `table`=None # bound db table name (optional until submit) - + `action`=insert # insert | update - + `id`=None # required when action=update - -## fields - + `fields` # |字段|标签|类型|必填|默认|… - -## validate - + `rules`=None # |字段|规则|消息|… (optional extra rules) - + `data` # submitted row / map - -## render - # → HTML form (or form descriptor for page slot) - -## submit - + `data` - + `db` # db handle -``` - -**中文(`网页.mq.md`):** - -```markdown -# 表单 - + `表`=None - + `动作`=插入 # 插入 | 更新 - + `id`=None - -## 字段 - + `字段` - -## 校验 - + `规则`=None - + `数据` - -## 渲染 - -## 提交 - + `数据` - + `数据库` -``` - -#### 5.5.1 字段表(作者面) - -```markdown -`文章表单` = - -| 字段 | 标签 | 类型 | 必填 | 默认 | -|------|------|------|------|------| -| title | 标题 | text | true | | -| body | 正文 | textarea | false | | -``` - -| 列 | 含义 | -|----|------| -| `字段` | 对应库列名(裸名或 `` `列` ``,与 schema 对齐) | -| `标签` | 展示文案(字面量) | -| `类型` | 控件/值类型:`text` `textarea` `number` `email` `url` `checkbox` `select` … | -| `必填` | 是否必填 | -| `默认` | 可选默认值 | -| `来源` / `source` | 可选;见 [ext-web-request-context.md](ext-web-request-context.md):`client`(默认)/ `session.username` / `route.NAME` / `now`;非 client 不渲染且服务端盖戳 | - -#### 5.5.2 校验表(作者面) - -```markdown -`文章校验` = - -| 字段 | 规则 | 消息 | -|------|------|------| -| title | required | 标题不能为空 | -| title | max:120 | 标题过长 | -| body | max:8000 | 正文过长 | -``` - -| 规则(初版) | 含义 | -|--------------|------| -| `required` | 非空 | -| `min:N` / `max:N` | 字符串长度或数值范围 | -| `email` / `url` | 格式 | -| `match:字段` | 与另一字段相等(如确认密码) | -| `in:a,b,c` | 枚举 | - -schema 上的「可空 / 类型」在 **submit 时自动并入校验**(不必重复写 `required`,但校验表可覆盖消息)。 - -#### 5.5.3 行为流程 - -```text -render → 按字段表出 HTML(或嵌入 page 主区) -用户填写 → POST /_form/{id} 或同页提交 -validate → 合并 schema + 校验表;失败则带回字段级错误、不写库 -submit → action=insert → db.insert;action=update → db.update - → 成功后刷新槽位或跳转(由 form 选项约定) -``` - -| 层 | 校验 | -|----|------| -| **服务端(必须)** | `validate` 在写库前执行;唯一可信边界 | -| **浏览器(可选增强)** | 同源规则可生成 `required`/`maxlength` 等 HTML 属性;**不能**替代服务端 | - -`/admin` 的新建/编辑页 = 内置 form:字段来自 schema,校验来自类型/可空;与站点自定义 form **同一套** `validate` + `db.insert`/`update`。 - -#### 5.5.4 与页面的关系 - -- 表单可以是独立路由页,或页面表里的一个「组件」导出(仍用 `|属性|值|样式|` 描述展示,提交走 form 类)。 -- **`page.compose_form id=… form=…`**:把 form 嵌入该页主区;`listen` 从首页与路由页收集表单并挂载 `/_form/{id}`(`app.mount_form` 仍可用)。校验失败时若表单有所属页,则带回该页壳重渲染。 - -### 5.6 文件职责 - -| 文件 | 内容 | -|------|------| -| `ext/web/web.mq.md` | 英文 `# page` `# style` `# db` `# form` `# app` | -| `ext/web/网页.mq.md` | 中文 `# 页面` `# 样式` `# 数据库` `# 表单` `# 应用`(可包装英文实现,**不得**把中文名写进 `web.mq.md`) | - ---- - -## 6. 模块导出形状(配合寻址) - -### 6.1 组件 `components/nav.mq.md` - -```markdown -## nav - -`nav` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| `title` | `nav`.`title` | | -| `href` | `nav`.`href` | | - -**`nav`** -``` - -说明:组件**内部**绑定仍可用 `` `表`.`列` ``(表名+列名皆引用)。与 index 主体里「模块命名空间 + 裸列名」的 `articles.`articles`.title` 分工: - -- **跨文件、带导入命名空间** → `模块.`表`.列`; -- **组件文件内、表已明确** → `` `表`.`列` `` 即可。 - -(若评审希望全站统一为一种形态,可在评审意见中二选一;默认允许上述两种。) - -### 6.2 样式 `styles/shell.mq.md` - -每个样式一个 `##`,**禁止** `## bag` + `json.set`: - -```markdown -## topnav -… |属性|值| … -**`topnav`** - -## card-title -… -``` - -### 6.3 库 `db/articles.mq.md` / `db/index.mq.md` - -- `articles`:`## schema`(或同名导出)返回结构表; -- `index`:`## open` → 确保插件、建库、init、幂等种子,返回 `# 数据库` 句柄。 - ---- - -## 7. 运行时职责划分 - -```text -作者 .mq.md 表(字面量单元格) - │ - ▼ - ext/web 类方法(Marqdo) - │ 解析路径;需要时经 ABI host_query - │ 调用入口模块 import 树上的 lib.member - ▼ - plugins/web(HTTP / SQL / HTML 壳) - │ - ▼ - 浏览器:四区布局 + /_part 局部刷新 + /admin(可选) -``` - -| 层 | 做 | 不做 | -|----|----|------| -| Marqdo 核心 | 表→Value、类/方法、import | 不识别 web 路径语法 | -| `ext/web/*.mq.md` | 作者 API、中英面、委托插件 | 不直接 `host_*` | -| `plugins/web` | **Go** `libweb`(HTTP / SQL / HTML 壳;见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md)) | 不要求作者写袋 | - -**实现要点(评审通过后再做):** - -1. ABI `host_query("call_lib_path")`:在**站点入口模块**上执行 `lib.member`; -2. 插件函数由类方法调用(如 compose_components / compose_main); -3. `listen` 合并页面内 part,注入 `db_url`。 - ---- - -## 8. 全部废弃 · 从头开发(锁定) - -**旧有网络扩展库内容一律作废**,包括但不限于: - -| 范围 | 处理 | -|------|------| -| [`plugins/web/`](../../plugins/web/) | 评审通过后**删除或清空**,按本文重写 cdylib | -| [`ext/web/`](../../ext/web/)(`web.mq.md` / `网页.mq.md` / templates) | 同上,**不**在旧 L1 上打补丁 | -| 依赖旧 API 的示例(如当前 `examples/web-site`、`web-demo`、`man-write-site` 可跑胶水版) | 按 §4 规范重写或暂时移除 | -| 依赖旧 API 的 gold / 单测 | 删除后按新 API 重写 | -| 本文之前的袋式 / assemble / wire / `## bag` 等作者面 | 永久移出正典 | - -**禁止**:在遗留代码上「修到能跑」再文档化。 -**允许**:实现时参考旧代码中的 HTTP/SQLite 技术经验,但**新树另起**,不以 ABI 表面或作者面兼容为目标。 - -历史摸索中明确不再回归的作者面模式: - -- `json.parse` / `json.set` 拼 components/styles 袋; -- 手写 `web.assemble` + 袋参数; -- 手写 part JSON + `` `app`.part ``; -- `|前端变量|后端数据库|` 填路由; -- 「变量名即表名」魔法默认表; -- 样式 `## bag`;掏空 index 只留 `wire.boot`。 - ---- - -## 9. 非本波次(可记入路线图) - -- Postgres / Redis / S3 驱动细节(SQLite 已落地); -- ~~复杂权限与多租户~~ → **可配置 RBAC** 见 [ext-web-rbac.md](ext-web-rbac.md);**多租户** 见 [ext-web-tenant.md](ext-web-tenant.md)(path/subdomain/header + `tenant_scope`); -- ~~重客户端 SPA~~ → **Native SPA** 见 [ext-web-spa.md](ext-web-spa.md)(WASM + 路由表 + `store_set` memory); -- ~~实时协同编辑~~ → **Collab MVP** 见 [ext-web-collab.md](ext-web-collab.md)(WS room LWW 文本 + presence); -- 子页路由糖的更多约定(`# 应用.route` 已够用)。 - ---- - -## 10. 评审清单 - -请确认或批注: - -1. **§3 路径**:`模块.`导出`` 与 `模块.`表`.列`(列裸名)是否定为唯一正典?组件内 `` `表`.`列` `` 是否保留? -2. **§4 index**:开库是否允许单独一行 `` db.open ``,还是必须进一步藏进 `web.应用`? -3. **§5 分文件**:英文 `web.mq.md` / 中文 `网页.mq.md` 是否严格分语言、禁止混排? -4. **§5.3**:列表查询用 `select` / `查询`、原始 SQL 用 `exec` / `执行` 是否认可? -5. **§5.5 表单/校验**:字段表、校验表、服务端必校、admin 共用是否认可? -6. **§5 槽位**:仅由组件导出名推断,是否足够? -7. **§8 废弃**:是否确认**全部推倒重来**、不兼容旧实现? - -评审通过后:冻结本文为 Accepted → **清空旧 web 扩展代码** → 按本文从零实现(骨架 → db CRUD/`select` → form/validate → 页面装配 → app listen → 规范示例 → gold)。 diff --git a/doc/design/fence-meta-and-control-prose.md b/doc/design/fence-meta-and-control-prose.md deleted file mode 100755 index 3e5c478..0000000 --- a/doc/design/fence-meta-and-control-prose.md +++ /dev/null @@ -1,60 +0,0 @@ -# 块公式元数据绑定 · 控制流叙述统一 - -| | | -|---|---| -| 状态 | Active | -| 日期 | 2026-10-15 | -| 相关 | [stdlib-math.md](stdlib-math.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) | - ---- - -## 1. 块公式 `% marqdo: var=` - -在 `$$…$$` 块内用 **TeX 行注释**声明绑定名(渲染通常不可见;运行时剥离后解析公式体): - -```markdown -$$ -% marqdo: var=f -x^2 - 2 -$$ -``` - -- 指令:`% marqdo:` + 空白 + `var=<ident>`;未知键 → Error。 -- 可无前置 `` `f` = ``;若同时写空 RHS 与 `var=`,**同名允许、异名 Error**。 -- **保留**旧空 RHS + 后随 `$$`。 -- **不做**:行内 `$% marqdo:…$`;\`\`\` 代码围栏内语言注释 meta(本波)。 -- 行内公式继续传统绑定:`` `g` = $x+1$ ``(单 `$…$` → `formula`)或 `` `g` = $$x+1$$ ``。 - -无名叙述区 `$$` 仍仅展示;可执行区裸块既无空 RHS 又无 `var=` → Error。 - ---- - -## 2. 臂 / 循环体叙述(与函数体同权) - -`parse_indented_body` 与函数体相同:消费 `` `名` `` / `**代码**` / `*返回*`;纯叙述跳过。 -斜体返回结束**当前臂或当前循环体**,不结束外层函数。 - ---- - -## 3. 循环头 - -| 面 | 写法 | 说明 | -|----|------|------| -| **推荐** | `- [项](xs)` / `- [`项`](`xs`)` | 支持嵌套 | -| 中文糖 | `- 对`xs`的每一项`项`` | 可选后缀「遍历」 | -| 英文糖 | `- for each `item` in `xs`` | 大小写不敏感 `for each` / `in` | - -糖与链接头语义相同,可混用嵌套。 - ---- - -## 4. 分支条件行叙述 - -结构行仍以 `1.` / `2.` 开头。条件提取顺序: - -1. 整段可解析为表达式(现状); -2. 行内粗体代码条件 `**`n` > 0**`; -3. 剥离「当/若/如果/when/if」与「时/则」后,将「大于/小于/等于…」映射为运算符再解析。 - -else:`N. *`(可夹「否则」等叙述,条件位仍为 `*`)。 -禁止无标记自然语言整句当条件。 diff --git a/doc/design/foreign-kernel.md b/doc/design/foreign-kernel.md deleted file mode 100755 index e8ee6fa..0000000 --- a/doc/design/foreign-kernel.md +++ /dev/null @@ -1,453 +0,0 @@ -# 外联内核(Foreign Kernel) - -| | | -|---|---| -| 状态 | **F0–F3.5 已实现** | -| 日期 | 2026-10-17 | -| 层 | Runtime(`src/foreign/` · `src/host/foreign*` · `lib/foreign.mq.md`) | -| 相关 | [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [notebook-syntax.md](notebook-syntax.md) · [notebook-session.md](notebook-session.md) · [stdlib-foreign.md](stdlib-foreign.md) · [stdlib-subtask.md](stdlib-subtask.md) | -| 核心表面 Δ | 无 | - -> 外联内核 = 一个长期存活的外部语言进程 + 生命周期 + 类型桥 + 记录。它既能被 `marqdo run` 里的显式调用使用,也能被 view 的 notebook 会话使用。 - ---- - -## 1. 定位与边界 - -### 1.1 负责 - -- 解释器发现、注册、配置、探测。 -- 一次性执行:临时脚本、stdin/stdout/stderr、超时、输出上限。 -- 持久内核:启动、求值、状态、关闭、列表。 -- 状态桥:`session_set` / `session_get` / `session_names`。 -- JSON 值桥:Marqdo `Value` ↔ JSON。 -- 结构化记录:`ok/code/stdout/stderr/ms/timed_out/truncated/result/error`。 -- 安全:`exec` 门禁、`cwd` 沙箱、进程组、并发/输出上限。 -- 视图诊断:代码卡片 Run 的完整结果。 - -### 1.2 不负责 - -- 文档语法(`内核表` / `会话表`)→ [notebook-syntax.md](notebook-syntax.md)。 -- 文档会话 / cell 顺序 / journal / view UI → [notebook-session.md](notebook-session.md)。 -- Foreign → Marqdo 函数回调(v2 不做)。 -- 依赖安装(pip/npm)。 -- 远程 / 容器执行。 - -### 1.3 与相邻模块的区别 - -| 模块 | 生命周期 | 用途 | -|---|---|---| -| `foreign` | 一次性或持久 | 调外部语言;状态可选 | -| `subtask` | 一次性并发 | 后台任务、文件子任务、函数子任务 | -| `plugin` | 进程内 | 原生 C ABI 扩展 | -| `writeback` | 文档级 | 把输出写回 `.mq.md` | - -`subtask` 不管理持久状态;`foreign` 不管理文档执行顺序。 - ---- - -## 1.4 实施状态(2026-10-17) - -| 阶段 | 状态 | 关键文件 | -|---|---|---| -| F0 安全执行 / `invoke` 记录 | ✅ | `src/host/foreign.rs` | -| F1 预设 / probe / register / config | ✅ | `src/foreign/registry.rs` · `src/host/foreign.rs` | -| F2 JSON 桥 / run_many / call_many | ✅ | `src/host/foreign.rs` | -| F3 Python/Node 持久内核 | ✅ | `src/host/foreign_session.rs` | -| F3.5 session_set/get/names | ✅ | 同上 | -| F4 history / view 打磨 / 发布 | 部分 | — | - -测试:`cargo test --lib foreign`(11+)、`cargo test --test gold lib_foreign`(12,python 条件跳过)、`tests/notebook/shared.mq.md` 手工 view 验证。 - ---- - -## 2. 语言与内核模型 - -### 2.1 语言预设 - -| lang | 别名 | 默认命令 | 扩展名 | 版本探测 | 会话 | -|---|---|---|---|---|---| -| `python` | `python3`, `py` | `python3`(Windows `python`) | `.py` | `--version` | ✅ | -| `node` | `javascript`, `js` | `node` | `.js` | `-v` | ✅ | -| `deno` | — | `deno run` | `.ts` | `--version` | ❌ | -| `bun` | — | `bun` | `.js` | `--version` | ❌ | -| `ruby` | — | `ruby` | `.rb` | `--version` | ❌ | -| `perl` | — | `perl` | `.pl` | `--version` | ❌ | -| `php` | — | `php -r {inline}` | `.php` | `--version` | ❌ | -| `lua` | — | `lua` | `.lua` | `-v` | ❌ | -| `r` | `rscript` | `Rscript` | `.R` | `--version` | ❌ | -| `julia` | — | `julia` | `.jl` | `--version` | ❌ | -| `go` | — | `go run {file}` | `.go` | `version` | ❌ | -| `bash` | `sh`, `shell` | `bash` | `.sh` | `--version` | ❌ | -| `powershell` | `pwsh`, `ps1` | `pwsh`(Windows `powershell`) | `.ps1` | `--version` | ❌ | -| `sqlite` | `sqlite3` | `sqlite3` | `.sql` | `--version` | ❌ | -| `tsx` | `typescript` | `tsx` | `.ts` | `--version` | ❌ | - -说明: - -- 预设只是默认值;注册 / 配置 / 环境变量整体覆盖。 -- 会话能力首批只有 Python / Node;其它语言一次性执行。 -- `php` 用 `{inline}`,围栏里直接写 PHP,不需要 `<?php`。 -- `deno` 默认不给权限;需要时通过配置追加 `--allow-*`。 - -### 2.2 解析优先级 - -从高到低: - -1. 调用级 `cmd`(整行 argv,shell-like 切分)+ `args`(追加)。 -2. 进程内注册:`register` / `set_cmd`。 -3. 环境变量 `MARQDO_FOREIGN_<LANG>`(整行或 JSON 数组)。 -4. 项目配置 `.marqdo/foreign.toml` / `MARQDO_FOREIGN_CONFIG`。 -5. 内置预设。 -6. 都没有 → 带修复建议的诊断。 - -Python 额外发现顺序(在预设层内): - -1. `VIRTUAL_ENV/bin/python`(Windows `Scripts/python.exe`); -2. `<cwd>/.venv` / `venv` / `env`; -3. 入口目录与 `fs_root` 向上查找; -4. PATH 的 `python3` / `python`。 - -`MARQDO_FOREIGN_NO_VENV=1` 关闭 venv 探测;显式 `cmd` / `set_cmd` / `MARQDO_FOREIGN_PYTHON` 优先。 - -相对路径:配置里的 `cmd` 相对配置目录;注册 / `set_cmd` / 环境变量里的 `cmd` 相对 `cwd`。 - -### 2.3 注册与模板 - -`register(lang, cmd?, args?, template?, ext?, env?, version_args?)`。 - -模板占位符: - -| 占位符 | 展开 | -|---|---| -| `{file}` | 临时脚本绝对路径 | -| `{dir}` | 临时目录 | -| `{base}` | 脚本文件名 | -| `{inline}` | 源码作为一个 argv;不写临时文件 | -| `{lang}` | 语言 id | -| `{cwd}` | 实际工作目录 | - -规则: - -- `cmd` 与 `template` 至少一个;都给 → 报错。 -- `{file}` 与 `{inline}` 不能同时出现。 -- 都没有时自动追加 `{file}`。 -- `{inline}` 超过 60 KiB → 报错并建议 `{file}`。 -- 模板不做 shell 转义;需要 shell 时显式写 `bash -c`,路径由引擎生成(安全字符)。 - -配置示例: - -```toml -[python] -cmd = ".venv/bin/python" -args = ["-u"] - -[go] -template = ["go", "run", "{file}"] - -[rust] -template = ["bash", "-c", "rustc -O {file} -o {dir}/main && {dir}/main"] - -[php] -template = ["php", "-r", "{inline}"] -``` - ---- - -## 3. 一次性执行 - -### 3.1 API - -| 英文 | 中文 | 形参 | 结果 | -|---|---|---|---| -| `run` | `运行` | `code`, 可选 `stdin` `env` `cwd` `timeout` `args` `max_output` | stdout 文本(v1 兼容) | -| `run_lang` | `按语言运行` | `lang`, `source`, 可选同上 | stdout 文本 | -| `invoke` | `执行` | 可选 `code` / `lang`+`source` / `stdin` / `input` / `env` / `cwd` / `timeout` / `args` / `output` / `max_output` / `cmd` / `keep` / `cache` | 记录 map | -| `call` | `调用` | 可选 `code` / `lang`+`source` / `input` / `stdin` / `env` / `cwd` / `timeout` / `args` | 解析后的 JSON 值 | -| `run_many` | `批量运行` | `runs`, 可选 `concurrency` | 记录列表 | -| `call_many` | `批量调用` | `inputs`, 可选 `code` / `lang`+`source` / `cmd` / `env` / `cwd` / `timeout` / `args` / `max_output` / `concurrency` | 结果值列表 | - -### 3.2 记录结构 - -`invoke` / `run_many` / `session_eval` 共用: - -| 键 | 类型 | 含义 | -|---|---|---| -| `ok` | Bool | exit=0 且未超时 | -| `code` | Int | 退出码;未启动 / kill → -1 | -| `stdout` | Text | 原始 stdout(可能截断) | -| `stderr` | Text | 原始 stderr(可能截断) | -| `ms` | Int | 墙钟毫秒 | -| `lang` | Text | 实际语言 | -| `cmd` | Text | 实际 argv | -| `timed_out` | Bool | 是否超时 | -| `truncated` | Bool | stdout/stderr 是否截断 | -| `result` | 任意 / None | 按 `output` 解析 | -| `result_error` | Text | json 解析失败原因 | -| `error` | Text | 启动 / 超时 / 策略原因 | -| `script` | Text | `keep=True` 的脚本路径 | -| `cached` | Bool | 缓存命中(P4) | - -`session_eval` 额外:`id`、`alive`。 - -### 3.3 输出模式 - -| `output=` | `result` | -|---|---| -| `auto`(默认) | 尝试 JSON;失败 → None | -| `text` | None | -| `json` | 解析;失败 → `result_error` | -| `lines` | 行列表 | -| `bytes` | stdout 原始字节的 base64 | - -`call` 固定 JSON:空 stdout → None;非空非法 JSON → 错误。 - -### 3.4 失败语义 - -- `run` / `call`:执行失败 → `Err`;错误包含语言、argv、退出码、stderr(截 4 KiB)、stdout 头。 -- `invoke` / `run_many`:执行失败 → 记录;只有参数非法 / 策略拒绝 → `Err`。 -- 输出过大:截断 + `truncated=true`,不再 OOM / 报错。 - ---- - -## 4. JSON 状态桥 - -### 4.1 值映射 - -Canonical integer contract: [`v-safe-json.md`](v-safe-json.md) (Lean \(V_{\mathsf{safe}}\): `|n| ≤ 2^{53}-1`). - -| Marqdo | JSON | -|---|---| -| None | null | -| Bool | bool | -| Int | number **仅当** `|n| ≤ 2^{53}-1`;越界 → 显式失败(禁止静默扭曲) | -| Num | number(NaN/Inf → null);float 为宿主扩展,∉ mechanized \(V_{\mathsf{safe}}\) | -| Text | string(宽整数用十进制字符串过桥,对端 `BigInt` / Python `int`) | -| List | array(子树递归;任一越界整数使整体失败) | -| Map | object(同上) | -| Formula | 矩阵 → 二维数组;其它 → 数字或字符串 | -| Code | 源码字符串 | -| Secret | JSON 中 `<secret>`;`env` 显式交付时取真实值 | - -错误前缀:`json: integer outside V_safe (±(2^53-1)): <n>`。 - -### 4.2 输入 - -- `input=` → JSON;写 stdin;同时提供 `MARQDO_INPUT`(≤8 KiB)与 `MARQDO_INPUT_FILE`(任意大小)。 -- `stdin=` 文本与 `input=` 互斥。 -- 都不给 → stdin EOF。 -- 大输入走文件,避免环境变量大小限制。 - -### 4.3 输出 - -- `result` 按 `output` 解析。 -- 原始 stdout/stderr 始终保留(截断到上限)。 -- `call` 返回解析值;`invoke` 返回记录。 - -### 4.4 类型限制 - -v2 是**值拷贝**,不是对象引用: - -- Python DataFrame / NumPy / Node 对象 → 需要先 `to_dict` / `to_json` / `JSON.stringify`。 -- 大对象传输成本高;后续考虑 Arrow / Parquet / 文件句柄。 -- Secret 不默认进入 JSON;需要 env 显式交付。 - ---- - -## 5. 持久内核与会话 - -### 5.1 API - -| 英文 | 中文 | 形参 | 结果 | -|---|---|---|---| -| `session_open` | `会话开启` | `lang`, 可选 `cmd` `env` `cwd` `timeout` | 会话 id(Text) | -| `session_eval` | `会话求值` | `id`, 可选 `code` / `source` / `input` / `timeout` | 记录(含 id/alive) | -| `session_set` | `会话设值` | `id`, `name`, `value` | None | -| `session_get` | `会话取值` | `id`, `name` | JSON 值 / None | -| `session_names` | `会话变量` | `id` | 名称列表 | -| `session_close` | `会话关闭` | `id` | Bool | -| `session_list` | `会话表` | — | map 列表 | - -### 5.2 支持语言 - -| 语言 | 方式 | -|---|---| -| python | `python3 -u -c <bootstrap>` | -| node | `node -e <bootstrap>` | -| 其它 | 报错:`lang=… has no session bootstrap; use run/invoke` | - -### 5.3 线路协议 - -stdin 每行一个 JSON 请求;原始 stdout 每行一个 JSON 响应: - -```json -{"id":1,"code":"x = 41","input":null} -{"id":2,"code":"x + 1","input":null} -``` - -```json -{"id":1,"ok":true,"stdout":"","stderr":"","result":null,"error":""} -{"id":2,"ok":true,"stdout":"","stderr":"","result":42,"error":""} -``` - -- 同一会话严格串行:等到匹配响应后才发下一条。 -- 响应单行;JSON 转义换行。 -- 崩溃 / EOF → `alive=false`,会话移除。 -- 超时 → kill 会话(状态不可信)。 - -### 5.4 Python bootstrap - -- 保留原始 `sys.stdout` 写协议;用户输出用 `redirect_stdout/stderr` 捕获。 -- `ast.parse`:最后一条是表达式 → 先 exec 前面,再 eval 最后,作为 result。 -- 异常 → `traceback.format_exc(limit=8)`,`ok=false`;会话继续。 -- `input` → 全局 `marqdo_input`。 -- 不可序列化 → `default=str`。 - -### 5.5 Node bootstrap - -- 保存原始 `process.stdout.write` 写协议。 -- eval 期间替换 `console.*` 与 `process.stdout/stderr.write`;结束后恢复。 -- `vm.runInThisContext` 保留全局状态;`require` 挂到 `globalThis`。 -- Promise → await;顶层 await 需用户包 `(async()=>{…})()`。 -- 序列化失败 → `String(result)`。 - -### 5.6 状态桥 - -- `session_set`:值 → JSON → 请求 `{"set": name, "value": ...}` 或执行一段赋值。 -- `session_get`:请求 `{"get": name}` → JSON → Marqdo Value。 -- `session_names`:请求变量名列表。 -- 与 `session_eval` 同一线路协议;严格串行。 -- 名称必须是合法标识符;保留名(`marqdo_input` 等)另行文档。 - -### 5.7 生命周期 - -- id 为 `s1`、`s2`…。 -- 每会话独立进程、cwd、env。 -- `HostContext` drop → 全部 kill + wait。 -- `subtask` 不继承会话。 -- 不跨文档共享。 - ---- - -## 6. 环境契约 - -| 变量 | 值 | -|---|---| -| `MARQDO_FOREIGN` | `1` | -| `MARQDO_FOREIGN_LANG` | 语言 id | -| `MARQDO_FOREIGN_SCRIPT` | 脚本路径(文件模式) | -| `MARQDO_FOREIGN_DIR` | 脚本目录 | -| `MARQDO_FOREIGN_CWD` | 实际 cwd | -| `MARQDO_ENTRY` | 入口 `.mq.md` 路径 | -| `MARQDO_ENTRY_DIR` | 入口目录 | -| `MARQDO_INPUT` | input JSON(≤8 KiB) | -| `MARQDO_INPUT_FILE` | input JSON 文件(任意大小) | - -语言默认: - -- Python:`PYTHONUNBUFFERED=1`、`PYTHONIOENCODING=utf-8`、`PYTHONUTF8=1`;`PYTHONPATH` 前插 cwd。 -- Node:`NODE_PATH` 前插 cwd(可选)。 - -`env` 是 map;值 `as_display()`;Secret 取真实值(显式交付)。不主动清空父环境。 - ---- - -## 7. 临时文件与 cwd - -- 默认 `<cwd>/.marqdo/tmp/foreign-<pid>-<nanos>/`;不可写 → 系统临时目录。 -- `MARQDO_FOREIGN_TMPDIR` 覆盖。 -- 脚本 `main.<ext>`;Python 加 utf-8 声明。 -- 默认 cwd = 入口目录;调用级 cwd 经 `resolve_path` + `fs_root` 校验。 -- 成功/失败/超时都清理;`keep=True` 保留并回填 `script`。 -- Node 相对 `require('./x')` 相对脚本目录;需要项目相对路径时用 `MARQDO_FOREIGN_CWD` 或 `{inline}` 模板。 - ---- - -## 8. 超时、IO、进程组 - -- `timeout`:秒,可小数;默认 10s;上限 3600s;`<=0` 报错。 -- 超时 kill 进程组: - - Unix:`process_group(0)` + `kill(-pid, SIGKILL)`; - - Windows:`taskkill /PID <pid> /T /F`。 -- `max_output`:每流默认 1 MiB;范围 1 KiB–64 MiB;保留前 N 字节,余下丢弃并继续排空;`truncated=true`。 -- stdin 独立写线程,避免双向管道死锁;EPIPE 忽略。 -- stdout/stderr 两个读线程;UTF-8 lossy。 -- 记录原始字节(至上限)以支持 `bytes` 输出。 - ---- - -## 9. 安全 - -| 项 | 策略 | -|---|---| -| 能力门禁 | `run` / `invoke` / `probe` / `session_*` 全部检查 `allow_exec()`;沙箱 → 拒绝 | -| shell | 默认不经 shell;模板显式 `bash -c` 才走 | -| cwd | `resolve_path` + `fs_root`;越界拒绝 | -| 输出 | 有界读取 + 丢弃式排空 | -| 时间 | 上限 + 进程组 kill | -| 并发 | 默认 4,上限 32 | -| 会话 | 每文档独立;关闭/drop 清理;超时即杀 | -| Secret | JSON 不默认暴露;env 显式;面板打码 | -| wasm | `exec-host` 关闭时全部返回清晰错误;`langs` 返回 [] | - ---- - -## 10. 兼容性 - -- `run` / `run_lang` / `set_cmd` / `langs` 既有调用可用。 -- `run` 成功仍返回 stdout(去一个尾换行);非 0 仍报错。 -- `set_cmd` 增加可选 `args`。 -- `langs` 扩展为「预设 ∪ 注册 ∪ 配置」;原集合是子集。 -- `subtask` 的 `spawn code=` / `lang=` 仍返回 stdout 文本。 -- HostFn id 只追加;字节码参数 < 255。 -- 无核心表面 Δ。 - ---- - -## 11. 测试矩阵 - -| 测试 | 依赖 | 断言 | -|---|---|---| -| 既有 `foreign-python` / `run-lang` / `外联-python` | python | 兼容 | -| `foreign-invoke` | node | ok/code/stdout/stderr/ms | -| `foreign-env-cwd` | node | env/cwd/MARQDO_* | -| `foreign-timeout` | node | timed_out, 无遗留进程 | -| `foreign-call-json` | node | 嵌套 list/map 往返 | -| `foreign-call-many` / `run-many` | node | 顺序/隔离/并发 | -| `foreign-session` | node(python 可选) | 跨 eval 状态、异常不杀 | -| `foreign-session-set-get` | node | 变量推拉 | -| `foreign-session-timeout` | node | alive=false | -| `foreign-probe` | node | path/version/ok | -| `foreign-register` | node | 模板 `{inline}` | -| `foreign-config` | node | `MARQDO_FOREIGN_CONFIG` | -| `foreign-caps` | 无 | exec=false 拒绝 | -| 单元测试 | 无 | shell 切分/模板/别名/JSON | - -当前环境无 Python:node + bash 为主;python 条件跳过;Windows 用 `python_available()` / `bash_available()` 守卫。 - ---- - -## 12. 实现落点 - -| 文件 | 内容 | -|---|---| -| `src/foreign/registry.rs` | 预设/别名/模板/venv/PATH/配置/shell 切分(纯逻辑) | -| `src/host/foreign.rs` | Job/Execution/ForeignEnv;run/invoke/call/run_many/call_many;probe/register/unset/langs/load_config | -| `src/host/foreign_session.rs` | Python/Node bootstrap;会话生命周期;set/get/names | -| `src/host/dispatch.rs` | HostFn 追加 | -| `src/aliases.rs` | 参数别名 | -| `lib/foreign.mq.md` / `lib/外联.mq.md` | L1 API + 文档 | -| `src/view/mod.rs` / `html.rs` / `debug_page.rs` | Run 诊断;后续接文档会话 | -| `tests/gold.rs` / `tests/lib/foreign-*.mq.md` | 测试 | - ---- - -## 13. 明确不做 - -- Foreign line-level step。 -- Foreign → Marqdo 函数 callback。 -- 自动镜像变量。 -- 跨语言共享对象引用。 -- 全进程快照。 -- 自动安装依赖。 -- 浏览器 wasm 外联。 diff --git a/doc/design/foreign-library-paper-direction-2026-11-05.md b/doc/design/foreign-library-paper-direction-2026-11-05.md deleted file mode 100755 index fb159d3..0000000 --- a/doc/design/foreign-library-paper-direction-2026-11-05.md +++ /dev/null @@ -1,24 +0,0 @@ -# 外联库论文的研究方向 - -作者于 2026-11-05 将论文主线明确为:**叙述本身是程序,外部代码是值**。 -Marqdo 的外联库用于在这一宿主模型中组合既有语言的计算能力,统一说明、控制流、 -代码复用、状态与显式数据交换。论文应先解释 Notebook/文学编程中的实际设计问题, -再给出解决方案、可核验的收益、形式化依据和应用实验。 - -后续实现工作围绕绑定的代码值、参数化调用、持久会话、复制值和文档计划展开。 -生命周期、值域和重放机制为这个统一设计提供保证;不能将重放检查器重新提升成 -取代外联库与叙述式编程的论文主题。不得把未测的人因优势或未证明的实现正确性 -写成既成事实。 - -完整方向文件在论文工作区: - -- 方向(当前):`MarqdoThesis/PLDI/design/V7-NARRATIVE-FIRST-DIRECTION-2026-11-05.md` -- v6 方向(历史):`MarqdoThesis/PLDI/design/V6-NARRATIVE-FIRST-DIRECTION-2026-11-05.md` -- 证据映射:`MarqdoThesis/PLDI/design/V6-EVIDENCE-MAP-2026-11-05.md` -- 章节与页预算:`MarqdoThesis/PLDI/design/V6-OUTLINE-2026-11-05.md` - -当前稿位于 `MarqdoThesis/PLDI/paper-v7`;v6 保留,历史 v5 及其证据保留。方向文件取代了 -此前把论文缩成“外联会话值 + 因果重放”的 N3 路线:重放是支撑机制,不是主线。 - -2026-11-05 交付:`MarqdoThesis/PLDI/paper-v7/main.pdf`,正文(含 AI Use)20 页。 -v6 保留为上一版尝试;更早的 v6 草稿保留在 `paper-v6-draft-2026-11-05/`。 diff --git a/doc/design/foreign-strong-correspondence.md b/doc/design/foreign-strong-correspondence.md deleted file mode 100755 index 11bb5f0..0000000 --- a/doc/design/foreign-strong-correspondence.md +++ /dev/null @@ -1,44 +0,0 @@ -# Foreign Strong: Lean ↔ host correspondence - -2026-11-02 补充:`ForeignSource.lean` 对显式局部环境、返回、函数调用/递归、 -分支和有界 while 的源解释器与独立 effect 编译器证明一般精化,并推出安全 -观察和旧句柄不可复活。`CheckForeignSource.lean` 消费真实加载后 AST 的显式 -适配格式,用独立 counter oracle 对照 tree/bytecode 的返回、journal、fault -与故障后 n。它已用于发现并修复 tree 的父词法作用域查找缺陷。 -这是源控制流层的证明与实现 translation validation;Rust parser/adapter、 -全部 AST 构造、机器数值运算和物理调度的完整 refinement 仍须完成。 -模型中的 fuel 是分析界限,不能称为真实程序必然终止或有界取消。 - -Pinned with PLDI Strong / paper-v5 (sessions as values; three gates). -Marqdo **2.3.0** host implements the same objects the Lean development decides. - -| Lean / paper rule | Host surface | Evidence | -|---|---|---| -| `SessionReg` + `sessionOpen` / `Close` / `sessionEval` | `HostContext.foreign_sessions` + `Value::Handle` | `DocCalc.lean` S1–S6, `requires_live`; `foreign_session.rs` | -| `Ω(s, τ, c)` | Persistent kernel + process order | Oracle journal `(cell, source_hash, stdout, result)` | -| `SafeVal` / Encode / Decode | `src/host/json.rs` + bootstrap sanitize | `ForeignJSON.lean`; gold `foreign-*-vsafe-*` | -| Handle ∉ \(V_{\mathsf{safe}}\) | `value_to_json(Handle) → Err` | `foreign-session-handle-no-serialize.mq.md` | -| Closed / Closed-Close | use-after-close / double-close `Err` | gold misuse; `sessionClose_then_eval_none_w` | -| Oracle-Domain | Ω OOD integer → host `Err` | `foreign-session-result-vsafe-refuse.mq.md` | -| Table arity stuck | Parse refuse unequal GFM; JSON unequal columns | `Surface.lean`; `tests/errors/table-arity.mq.md` | -| Snapshot hash match/mismatch | `view/output.rs` `snapshot_page` | unit snapshot hash tests | -| **Thm. corr** (`corr_fresh_functional`) | Cold `evaldoc`; step values = Ω | `corr_step_eq_omega`; `corr_doc_fresh_foreign`; foreign-session gold | -| `OracleJournal` / `replayCheck` | `oracle_journal` + `DocumentSession::replay_check` | `replayCheck_*`; fate R1–R3 | -| `corr_fail_warm_store` / `corr_fail_reordered_plan` | cold vs warm / schedule order | DocCalc witnesses; Table corr-fail | -| Dual-backend differential | `tests/gold.rs` tree + bytecode | 308 × 2; foreign session/V_safe subset | - -## Scope (not distance) - -- SafeVal mechanization covers the **integer** fragment; finite floats are admitted by the host under the same refuse-not-coerce bridge policy for non-integers already in SafeVal. -- Session discipline is a **dynamic registry** (affine close + borrow-use). Static linear types over OS-killable processes are out of scope by design, not an unfinished host feature. -- Correspondence is mechanized for the **closed / fresh-open / functional-Ω** fragment (`corr_fresh_functional`): per-step interactive value = Ω answer, interactive runner = normative runner, `replayCheck` on the journal. Broken hypotheses are `corr_fail_*`. Host discharge is foreign-session gold plus R1–R3, not R1–R3 alone. - -## Reviewer-driven implementation update (2026-11-01) - -The independent live cursor and multisession action-plan simulation are in -`DocCalc.runForeignLive_simulation` and `MarqdoProof.ForeignTrace`. The language -now exposes oracle observations and pure journal comparison through -`foreign.oracle_journal` / `foreign.replay_check`. Strict interactive snapshot -replay uses the full oracle history with source identity and per-step input. -See `oracle-journal-values.md` for the API and the research experiment manifest -under `PLDI/experiments/reviewer-v5/` for exact source hashes and actual runs. diff --git a/doc/design/foreign-v3.md b/doc/design/foreign-v3.md deleted file mode 100755 index 374a9b3..0000000 --- a/doc/design/foreign-v3.md +++ /dev/null @@ -1,654 +0,0 @@ -# 外联运行时 v3 — 能力缺口与深化设计(Proposed) - -| | | -|---|---| -| 状态 | **Proposed;尚未实现** | -| 日期 | 2026-10-18 | -| 层 | Runtime(foreign)· Document(`foreign.session`)· View(投影) | -| 相关 | [foreign-kernel.md](foreign-kernel.md) · [notebook-session.md](notebook-session.md) · [foreign-v2.md](../roadmap/foreign-v2.md) · [stdlib-writeback.md](stdlib-writeback.md) · [view-static-interactive.md](view-static-interactive.md) | -| 核心表面 Δ | **无增删**:不新增 Markdown 标记、不新增 notebook CLI | - -> 本文只定义设计,不承诺已实现。当前基线是 v1.5.0 之后的本地工作:`foreign.session` 句柄、多内核、values 初始化、view 控制、静态执行与显式 writeback 已可用;本文处理仍然缺失的能力。 - ---- - -## 1. 设计约束 - -v3 必须继续满足以下约束,否则不进入实现: - -1. **外联库拥有内核与状态**:`foreign` 管理内核、会话、cell 计划、输入、输出、journal 和生命周期。`view` 只消费句柄,不拥有第二套运行时。 -2. **表与围栏是值**:`内核表`、`单元表`、`输入表`、`值表` 都是普通 Marqdo 值;没有保留表名,没有新增标记。 -3. **单一执行语义**:`run` 是规范执行;`view` 是同一文档的交互投影;静态导出是同一会话的快照,不另写解释器。 -4. **没有 Notebook 模式**:没有 `marqdo notebook`,没有 `In/Out`,没有“普通 view / notebook view”两套布局。 -5. **显式 I/O**:Marqdo 值通过 `values` / `session_set` 传递;程序 stdin 是单独概念,不能伪装成 `marqdo_input`。 -6. **显式持久化**:默认不改源码;writeback 必须由文档显式调用,或由用户显式选择策略。 -7. **安全默认值**:执行受 capability 控制;输入/输出有界;不反序列化任意对象;跨文档共享必须显式开启。 - ---- - -## 2. 基线:现在已经有什么 - -| 能力 | 状态 | -|---|---| -| `foreign.run` / `run_lang` / `invoke` / `probe` | 已实现 | -| `foreign.call` / `call_many` / JSON 进出 / 并行 | 已实现 | -| `session_open` / `eval` / `set` / `get` / `names` / `close` / `list` | 已实现 | -| `foreign.session kernels= cells= values=` | 已实现 | -| 多内核 view 会话、cell 顺序、内核归属 | 已实现 | -| Marqdo 表通过 `values` 传入多个内核 | 已实现 | -| 无 `会话` 时无状态 cells | 已实现 | -| view 每 cell 内核选择 / Clean / Run | 已实现 | -| 静态导出执行 cells 并嵌入真实输出 | 已实现 | -| 静态页 session summary、内核归属、多内核展示 | 已实现 | -| 显式 `writeback.record` | 已实现(库能力) | -| 静态页按钮的“不可执行”提示 | 已实现 | - ---- - -## 2.1 实施状态(2026-10-18) - -| ID | 状态 | 备注 | -|---|---|---| -| G1/G2 | ✅ 已实现 | session eval raw stdin;`foreign.session inputs=`;per-cell UI;Python/Node 测试 | -| G5 | ✅ 基本实现 | `session_interrupt` + view Interrupt;Python SIGINT 保留会话;Node 进程可能被终止 | -| G4 | ✅ 已实现(API) | add/remove/set-value + generation;view 尚未提供 add/remove UI | -| G6 | ✅ 已实现(API) | export/import/replay JSON snapshot;view/CLI 尚未做文件封装 | -| G9 | ✅ 已实现(CLI/API 基础) | `view capture` + `view output --snapshot`;source hash 校验 | -| G3 | ✅ 边界已实现 | 顶层 plan;嵌套 plan 诊断 | -| G10 | ✅ 显式 persist | `/api/session/cell/persist` + view Persist;不自动写源码 | -| G7/G8 | 📌 已移出当前目标 | 设计保留,后续版本再开发 | - -## 3. 缺口清单 - -| ID | 缺口 | 优先级 | 当前行为 | 目标 | -|---|---|---|---|---| -| G1 | 持久内核 raw stdin | P0 | 持久内核只有 `marqdo_input` | 程序 stdin 与控制协议分离 | -| G2 | 每 cell 独立 stdin | P0 | 页面级 Cell stdin,Run All 共用一个输入 | cell 级输入表 + UI | -| G3 | 动态 plan | P2 | 只读顶层 `会话` | 明确边界,或受控动态 | -| G4 | 运行时更新 plan | P1 | values 只在打开时初始化 | 显式 session 变更 API | -| G5 | kernel interrupt | P0 | 只能等超时/杀进程组 | 可中断当前 eval | -| G6 | 状态持久化 / replay | P1 | journal/dirty 只在内存 | 导出/恢复/replay | -| G7 | 跨文档内核 | P2 | 每文档独立 | 显式 scope/空间 | -| G8 | 非 Python/Node 持久内核 | P3 | Go 等一次性执行 | LangSpec 会话适配器 | -| G9 | live → static 输入捕获 | P0 | 静态构建不捕获临时 stdin | 显式 snapshot 捕获 | -| G10 | 自动 writeback | P2 | 必须显式调用 | 显式策略下的“运行后写回” | - ---- - -## 4. 统一模型 - -### 4.1 会话句柄 - -`foreign.session` 返回的句柄是一个普通 Marqdo 值,建议稳定形状: - -```text -{ - kind: "foreign-session", - id: "<session-id>", - document: "<entry-source-hash>", - status: "created | ready | running | interrupted | dirty | closed", - kernels: [...], - cells: [...], - inputs: [...], - values: [...], - generation: 1 -} -``` - -`view` 只读这些字段;任何执行操作都通过 `foreign` 的 host API。句柄不是第二套运行时。 - -### 4.2 三种输入 - -必须严格区分: - -| 输入 | 目标 | 形态 | 当前 | -|---|---|---|---| -| `values` | 内核变量 | Marqdo 值 → JSON copy | 已实现 | -| `input` | `marqdo_input` | JSON 值 | 已实现(低层) | -| `stdin` | 程序 stdin | 原始文本/字节 | 仅无状态 cell 有 | - -v3 不允许把 raw stdin 偷偷塞进 `marqdo_input`;两者语义不同。 - -### 4.3 每 cell 输入表 - -不新增标记,仍然使用普通表: - -```mq.md -`单元输入` = -| 单元 | stdin | input | -|------|-------|-------| -| 计算 | hello | {rate: 0.08} | -| 复核 | | {check: true} | -``` - -`foreign.session` 增加可选参数: - -```text -foreign.session kernels=... cells=... values=... inputs=`单元输入` -``` - -规则: - -- `stdin` 只给该 cell 的程序 stdin; -- `input` 只给该 cell 的 `marqdo_input`; -- 空值表示不提供; -- 输入大小有上限,超限显式报错; -- 静态导出使用同一张表,因此 view 与静态快照可以一致。 - -### 4.4 执行流水线 - -```text -evaluate 会话 handle - → open kernels - → apply values - → apply cell inputs - → run cell - → record {stdout, stderr, input_echo, result} - → next cell -``` - -失败不终止整个 Run All;错误写入 cell record,journal 保留。 - ---- - -## 5. G1/G2:持久内核 stdin 与每 cell 输入 - -### 5.1 问题 - -当前持久内核的 worker 用 stdin 传输 JSON 控制协议,因此程序自己的 stdin 不可用;`marqdo_input` 只是 JSON 变量,不是 stdin。 - -### 5.2 方案 A(推荐):控制通道与程序 stdin 分离 - -- Unix:父进程创建 **socketpair**(或两个 pipe),worker 通过 fd 3/4 读写控制帧;程序 stdin 使用单独的 pipe。 -- Windows:named pipe 或可继承的匿名 pipe 作为控制通道;程序 stdin 单独 pipe。 -- worker 协议升级为 `protocol: 2`: - - 控制帧:`eval` / `set` / `get` / `interrupt` / `close` - - eval 帧可带 `stdin`(UTF-8)或 `stdin_b64`(二进制,后续) -- Python worker:每次 eval 前把 `sys.stdin` 替换为 `io.TextIOWrapper`/`StringIO`,eval 后恢复控制通道;用户代码读到的是真正的 stdin。 -- Node worker:控制 readline 移到控制 pipe;每次 eval 把 `process.stdin` 替换为 `PassThrough`/`Readable`,eval 后恢复。 -- 超时/中断关闭该次 stdin,不污染下一次 eval。 - -### 5.3 方案 B(降级):只支持 `input` - -如果控制通道暂不实现,持久内核只支持 `input`,并显式拒绝 raw stdin: - -```text -persistent kernel stdin is unavailable; use input= or stateless cells -``` - -不能静默把 stdin 变成 `marqdo_input`。 - -### 5.4 方案 C:stdin cell 降级为一次性 - -持久会话中遇到 raw stdin 时,用一次性进程执行该 cell;明确标记 `state: none`,不假装内核态连续。 - -### 5.5 UI 与静态 - -- `view`:每个代码卡提供 **Cell stdin** 小输入框,或者页面级输入表;推荐每 cell,因为它们经常不同。 -- 静态:读取 `inputs` 表;没有输入时显示“requires stdin”说明,而不是 traceback。 -- Run All 使用每 cell 的输入;不再把一个页面级 stdin 复制给所有 cell。 - -### 5.6 验收 - -- Python 与 Node 持久内核都能读取真实 stdin; -- 同一个 cell 连续 eval 不串输入; -- 超时/中断后下一次 eval 仍可读 stdin; -- 无状态 cell 行为不变; -- 静态快照使用相同输入表,结果与 live 一致(在相同输入下)。 - ---- - -## 6. G3:动态 plan 的边界 - -### 6.1 问题 - -`foreign.session` 目前只识别 entry 顶层的 `会话` 绑定。分支、函数、运行时循环中定义的 plan 不会被 view 发现。 - -### 6.2 设计决定(建议) - -**v3 不支持任意控制流中的 plan。** 这是有意的语义边界: - -- plan 是文档的声明,不是程序运行时的副作用; -- view 不应为了找 plan 而执行 `# main`; -- 避免 view 再次长出一套“运行程序再猜计划”的隐式逻辑。 - -允许的动态形式: - -- 顶层赋值右侧的纯表达式,包括引入的纯函数; -- `foreign.session` 的 tables/values 可以由顶层表函数计算; -- 运行时变化通过 G4 的显式 session API 完成。 - -**不支持**: - -- `##` 函数内部的 plan; -- `if`/`while` 分支里的 plan; -- 依赖 `# main` 副作用才能得到的 plan。 - -### 6.3 诊断 - -如果源码中出现非顶层 `foreign.session`,给出: - -```text -foreign.session: plan must be a top-level binding (会话 = > foreign.session ...) -``` - -而不是静默降级为无状态。 - ---- - -## 7. G4:运行时更新 plan - -### 7.1 目标 - -已打开的 view session 允许用户显式修改 cell 归属、增加/移除 cell、更新内核变量;所有修改都要可追踪。 - -### 7.2 API - -```text -foreign.session_assign session=<handle> cell="计算" kernel="复核" -foreign.session_add_cell session=<handle> cell="新单元" kernel="分析" -foreign.session_remove_cell session=<handle> cell="旧单元" -foreign.session_set_value session=<handle> kernel="分析" name="rate" value=0.08 -``` - -所有操作: - -- 校验 cell/kernel 语言; -- 递增 `generation`; -- 写入 journal(kind=plan_change / value_change); -- 标记受影响 cell 为 `dirty`; -- 失败不改变 handle。 - -### 7.3 View - -- 内核下拉复用 `session_assign`; -- 增加/删除 cell 放在显式菜单,不做隐式拖拽写入源码; -- UI 显示 generation / dirty 状态。 - -### 7.4 静态 - -静态快照不执行变更;它记录变更后的 plan,或在构建时执行一次并固化。 - ---- - -## 8. G5:kernel interrupt - -### 8.1 API - -```text -foreign.session_interrupt id=<session-id> -``` - -### 8.2 行为 - -- 控制通道发送 `interrupt`; -- worker 取消当前 eval,返回 `{ok:false, interrupted:true}`; -- 保留已完成的值和 journal; -- 状态从 `running` → `interrupted`; -- 下一次 eval 可以继续使用内核(除非进程已损坏); -- 超时继续作为最后一道防线。 - -### 8.3 View - -- 工具栏增加 Interrupt;执行中的 cell 显示 interrupted; -- 不自动重跑; -- 静态导出没有 interrupt(快照不执行)。 - -### 8.4 跨平台 - -Unix:进程组信号 + 控制帧;Windows:控制帧 + `taskkill /T` fallback。两者都必须有测试。 - ---- - -## 9. G6:状态持久化与 replay - -### 9.1 不做的事 - -- 不做 Python pickle / Node 堆快照; -- 不做任意对象反序列化; -- 不把内核内存默认写进 `.mq.md`。 - -### 9.2 显式快照 - -```text -foreign.session_export session=<handle> path=".marqdo/sessions/doc-1.json" -foreign.session_import path=".marqdo/sessions/doc-1.json" -``` - -快照只包含: - -```text -{ - version: 1, - document_hash: "...", - plan_hash: "...", - kernels: [{name, lang, cmd, values: {...}}], - cells: [{name, kernel, status, last_ok, last_error}], - journal: [...], - inputs: [...] -} -``` - -值只允许 JSON 可表达的 Marqdo 值;不可序列化的值显式失败。 - -### 9.3 replay - -```text -foreign.session_replay path="..." verify=True -``` - -按 journal 顺序重放 cell + inputs,比较 stdout/status;差异写入 report。replay 不覆盖原 journal,除非显式 `append`。 - -### 9.4 存储 - -- 默认目录 `.marqdo/sessions/`(gitignore 可选); -- 用户可通过 path 放到受控目录; -- 不默认提交,不默认写源码。 - ---- - -## 10. G7:跨文档内核(Deferred / future) - -> **状态:已移出 v3 当前实现目标。** 本节设计保留,作为后续版本(v4 或独立 session-scope 工作)的输入;当前不承诺 API 或兼容性。 - -### 10.1 原则 - -- 默认每文档独立; -- 跨文档必须显式 `scope=` / `space=`; -- 不自动按变量名或路径共享。 - -### 10.2 API - -```text -foreign.session_open lang="python" scope="shared:analytics" -foreign.session_list scope="shared:analytics" -foreign.session_close id=... scope=... -``` - -- scope 注册表由 foreign runtime 管理; -- 同名冲突报错,不覆盖; -- view 只能打开当前文档声明允许的 scope; -- 生命周期由 owner/refcount 管理,最后一个引用关闭时清理。 - -### 10.3 安全 - -- 跨文档共享可能违反文档隔离,必须 capability + 显式配置; -- journal 标记 scope; -- 静态导出默认不打开跨文档 scope。 - ---- - -## 11. G8:非 Python/Node 持久内核(Deferred / future) - -> **状态:已移出 v3 当前实现目标。** 本节设计保留,等待目标语言与 worker 适配器确定后再实现;当前不承诺 API。 - -### 11.1 模型 - -不是所有语言都需要持久内核。`LangSpec` 增加能力标志: - -```text -session: none | protocol_v2 -``` - -- `none`:只能 `run` / `invoke` 一次性; -- `protocol_v2`:实现控制通道与 eval 协议,可以 `session_open`。 - -### 11.2 适配器 - -Go 等语言通过一个薄 worker 实现: - -```text -control frame: eval {code, stdin, input} -result frame: {ok, stdout, stderr, result, error} -``` - -不允许“看起来像持久内核、实际每次重启”的假实现。 - -### 11.3 失败语义 - -- `session_open` 对 `session: none` 的语言明确报错; -- `foreign.session` 的 plan 只能使用支持 session 的语言; -- 静态/无状态仍可使用一次性执行。 - ---- - -## 12. G9:live → static 输入捕获 - -### 12.1 问题 - -静态构建在构建环境执行,无法知道用户在 live view 中临时输入的 stdin;同一文档的结果可能不同。 - -### 12.2 设计 - -增加显式的“捕获快照”: - -```text -view → Capture snapshot → .marqdo/snapshots/<doc>.view.json -``` - -快照内容: - -- document source hash; -- session plan(kernels/cells/values); -- 每 cell 的 stdin/input; -- 每 cell 的 stdout/stderr/status; -- journal 摘要、语言/解释器版本; -- 捕获时间。 - -静态导出: - -```text -marqdo view output --snapshot .marqdo/snapshots/doc.view.json -``` - -优先使用快照中的记录,校验 source hash,不重新执行;若 hash 不匹配,显式失败或 `--execute` 重跑。 - -### 12.3 安全/隐私 - -- 快照可能包含 secrets;默认不提交、不发布; -- 提供 `redact` 字段/正则; -- 静态页面只发布脱敏后的快照。 - -### 12.4 验收 - -- live 中成功的结果可以在静态页面原样显示; -- 不捕获内核内存,只捕获输入/输出/状态; -- 没有快照时回退到构建时执行,行为明确。 - ---- - -## 13. G10:自动 writeback - -### 13.1 原则 - -**“自动”必须是用户显式选择的策略,不是默认副作用。** - -### 13.2 API - -```text -foreign.session persist=`写回策略` -``` - -策略表: - -```mq.md -`写回策略` = -| 单元 | key | -|------|-----| -| 计算 | total | -| 复核 | check | -``` - -或 view 的 **Persist results** 按钮:将当前 cell 结果写到 `writeback.record key=...`。 - -### 13.3 语义 - -- 默认不写源码; -- 显式策略只在 **用户点击 Persist** 或 `marqdo run --writeback` 时执行; -- 静态构建默认不写回;`--writeback` 必须显式; -- writeback 只支持 JSON 可表达值; -- 写入位置/格式仍由 `writeback` 库决定。 - -### 13.4 与静态快照的关系 - -- 静态快照是只读发布; -- writeback 是源码内的活结果; -- 两者可以共存,但不能互相隐式触发。 - ---- - -## 14. API / 端点汇总 - -### 14.1 新增 foreign 函数 - -```text -foreign.session inputs= -foreign.session_assign -foreign.session_add_cell -foreign.session_remove_cell -foreign.session_set_value -foreign.session_interrupt -foreign.session_export -foreign.session_import -foreign.session_replay -foreign.session_open scope= -foreign.session_list scope= -``` - -### 14.2 View API - -```text -POST /api/session/cell/run { cell, stdin } -POST /api/session/run_all { restart, inputs? } -POST /api/session/cell/clear -POST /api/session/plan/assign -POST /api/session/plan/add -POST /api/session/plan/remove -POST /api/session/plan/value -POST /api/session/interrupt -POST /api/session/snapshot/capture -``` - -所有端点只操作 foreign 句柄;view 不直接读写内核。 - -### 14.3 CLI - -```text -marqdo view output --snapshot FILE -marqdo view output --execute -marqdo view output --no-exec -marqdo run --writeback -``` - -不新增 `marqdo notebook`。 - ---- - -## 15. 语义矩阵 - -| 能力 | run | view | static | -|---|---|---|---| -| `foreign.session` plan | 作为普通值执行 | 消费句柄 | 可执行或快照 | -| raw stdin | 支持(一次性/session) | 每 cell | inputs 表/快照 | -| interrupt | 无 UI | 可调用 | 不可用 | -| state export | 可调用 | 可显式导出 | 不导出或快照 | -| cross-doc(deferred) | 设计保留 | 设计保留 | 设计保留 | -| writeback | `--writeback` | 显式按钮 | 默认不写 | - ---- - -## 16. 实施顺序 - -### P0(先做,直接影响真实使用) - -1. **G1/G2 stdin**:控制通道 + 每 cell 输入表 + UI。 -2. **G5 interrupt**:避免只能等超时。 -3. **G9 snapshot capture**:解决 live/static 不一致。 - -### P1 - -4. **G4 runtime plan updates**。 -5. **G6 export/replay**。 - -### P2 - -6. **G3 dynamic plan 边界**:按第 6 节,只做顶层纯表达式;任意控制流不承诺。 -7. **G10 explicit writeback policy**。 - -### Deferred(不在当前目标) - -- **G7 cross-document scope**:设计保留,后续版本再开发。 -- **G8 non-Python/Node persistent adapters**:设计保留,等待目标语言与 worker。 - ---- - -## 17. 测试设计 - -### 单元 - -- `stdin` 协议:空输入、大输入、超时、中断、连续 eval; -- 每 cell 输入隔离; -- 返回值锚定在调用点(已修复的 CallFrame.call_line); -- 表格不产生 call chip(已修复); -- plan top-level 诊断; -- session generation / dirty; -- export/import/replay 校验。 - -### 集成 - -- Python 持久内核读 `sys.stdin`; -- Node 持久内核读 `process.stdin`; -- view Run All 使用每 cell 输入; -- interrupt 后下一次 eval 正常; -- static snapshot 与 live 结果一致; -- snapshot hash 不匹配显式失败; -- cross-doc scope 冲突/清理; -- Go 一次性 vs 持久能力诊断; -- writeback 只显式写入。 - -### 静态 - -- 输出无 traceback; -- 没有输入时显示说明而非伪造; -- 多内核 controls 显示; -- writeback slot 单块、暗色主题; -- 静态按钮提示。 - ---- - -## 18. 兼容与迁移 - -- 现有 `foreign.session kernels= cells= values=` 保持兼容; -- 新 `inputs=` 可选; -- `session_open` 旧协议继续可用;v2 控制通道通过 handshake 协商; -- 旧页面没有 `inputs` 时仍按空 stdin 执行/显示说明; -- 不修改已发布的 v1.5.0 tag;v3 以新版本发布。 - ---- - -## 19. 需要拍板的决策 - -1. **G1**:是否接受控制通道与程序 stdin 分离的协议改造?否则只能保留 `input`,不能宣称 raw stdin。 -2. **G3**:是否接受“plan 必须是顶层声明”的边界?若不接受,需要定义 view 可安全调用的 plan 入口,风险更高。 -3. **G6**:状态快照只允许 JSON 值,是否可接受?不做任意对象序列化。 -4. **G9**:快照文件是否默认放在 `.marqdo/snapshots/` 且不提交?涉及 secrets。 -5. **G10**:自动 writeback 是否只允许显式按钮/flag,而不是每次运行自动写源码? - ---- - -## 20. 当前目标范围 - -v3 当前实现目标为:**G1、G2、G3、G4、G5、G6、G9、G10**。 - -**G7、G8 已移出当前目标**,但设计文档保留在本文件第 10、11 节,供后续开发;它们不计入 v3 完成条件,也不影响现有 API 的兼容性承诺。 - -## 21. 非目标 - -- 不新增 Markdown 标记; -- 不新增 notebook CLI/模式; -- 不把任意内核内存序列化; -- 不默认修改 `.mq.md`; -- 不自动镜像变量; -- 不把 view 变成第二套解释器; -- 不把“未实现”伪装成支持。 - diff --git a/doc/design/frontend-call-semantics-2026-11-03.md b/doc/design/frontend-call-semantics-2026-11-03.md deleted file mode 100755 index 362a973..0000000 --- a/doc/design/frontend-call-semantics-2026-11-03.md +++ /dev/null @@ -1,336 +0,0 @@ -# Executable call and integer semantics - -This describes the implementation contract exercised by -`src/frontend_elaboration_tests.rs`; it is not a claim of a verified parser. - -All explicit actual arguments evaluate once in authored order, including extra -named arguments whose values the callee does not read. Binding then permutes -already computed values into parameter slots. Named arguments take precedence -over positional filling; duplicate names and excess positional arguments fail. -A duplicate-actual binding fault occurs only when its call is reached, after -all explicit actuals have evaluated; it cannot reject an unused function at -compile time or erase an earlier argument effect. -Local calls and imported calls use the same order. Builtins and host primitives -must not reorder expression evaluation when selecting their parameter values. - -All supplied parameters are available before defaults. Missing defaults execute -in parameter declaration order, once per call, in the target definition's -module and lexical scope. A default can see supplied parameters, earlier -computed defaults, and an explicitly bound method receiver. It cannot capture -the caller's locals. A still omitted later parameter is unbound. Explicit None -is a supplied value and never triggers a default. Required-argument validation -precedes default execution. Default expressions participate in receiver -classification, dependency analysis and transitive effect inference. - -A dynamic method's signature belongs to the resolved receiver and selected -method; a different object's same-named method cannot supply its parameter -list. Imported definitions retain their module scope. A compiled document's -entry is selected only from its own module; an imported `main` is not an entry. - -The bytecode retains argument names and explicit presence bits. Callee -prologues evaluate defaults in their own frame. Local slots distinguish an -unbound slot from a slot holding None. Local, constant, call-layout and jump -indices use container-sized indices rather than unchecked 8/16-bit casts. -Scratch slots are reused across sequential calls while pending outer actuals -remain live. Scalar constant interning uses a hash table; floating constants -are keyed by their exact bits. - -Host integers are signed 64-bit values. Add, subtract, multiply, divide and -negation report a language error on overflow in every build profile; division -by zero is a separate error. Division truncates toward zero. The negative -endpoint has a valid signed literal. Float-to-int conversion rejects nonfinite -or out-of-range inputs instead of silently saturating. This local integer -domain is distinct from the narrower continuous foreign-copy domain. - -The Lean call-combinator proof preserves complete interaction programs for -arbitrary argument evaluators, including failure and reply-dependent requests. -The integer model specifies exact arithmetic followed by representability -checking. Native documents, independently derived Python expectations, a Lean -arithmetic consumer and isolated source mutations validate the implementation -links. These do not prove the entire Rust parser, binder, object representation -or adapter. The research coverage ledger must keep those obligations explicit. - -## Module identity, entry inputs and source-bound invocation - -Instances retain the existing map representation and safe-copy domain. The -reserved `_type_module` field is a list of import binding names, paired with -`_type`. Class selection uses that module instance within the active import -tree; inherited methods resolve their bases in the defining module. Equal -class names in different imports remain distinct. These fields are ordinary, -forgeable data, not capabilities or globally portable nominal identities. -Round trips through Python/Node preserve these descriptors in the same module -context. Opaque session handles remain outside the copy domain. - -Entry metadata is passed to `Vm::run`, never compiled into `main`'s body. -Explicit named/recursive invocations of `main` therefore keep their own inputs. -Defaults run with the invocation's actual registry; a session-valued default -must not be evaluated in a separate interpreter and then injected into a VM. -Reads appearing only in explicit/prose defaults participate in input inference -and effect analysis. Default failures use the parameter declaration's span. -Source-bound APIs preserve the selected declaration's source identity and -span, even when two declarations have the same dotted path. Textual path calls -retain the existing first-declaration rule. Duplicate parameter names are -rejected because they cannot define distinct binding slots. - -Both backends retain parameter, return and local field contracts. Bytecode -checks supplied/defaulted inputs before the body, explicit returns before -returning, table bindings before writing a local and direct footnote accesses -before/after lookup. Unknown fields report the contract error before a generic -missing-key error. Entry/raw invocations also check their completed inputs. -Contract diagnostics retain the declaration quote and the failure location. - -## Refinement obligations and current evidence - -| Link | Mechanized result or implementation evidence | Remaining obligation | -|---|---|---| -| Raw Markdown to executable AST | Native explicit/prose defaults, source snapshots, parameter spans, inference and duplicate-parameter diagnostics | Prove the actual Rust classifier/parser and extraction rules; the older abstract grammar is not that proof | -| Loaded module tree to flattened declarations | Independent inventories of source digests, module instances, lexical parents, class/method ownership and resolved bases | Connect the actual resolver to the Lean namespace lookup model, including failed/ambiguous resolution | -| Effectful actual evaluation to parameter values | `FrontendCalls` proves interaction-program equality for arbitrary expression evaluators; native authored-order/unused-actual/builtin/foreign probes | Prove Rust scratch allocation, every expression case and its stack invariant against that combinator | -| Default evaluation and invocation inputs | Native callee-scope, presence, receiver, entry/raw/metadata, inference, error-span and stateful-session cases | A complete default-binding semantics and universal compiler refinement, including errors and host context | -| Module-qualified object dispatch | `ModularObjects` proves namespace flattening lookup, resolved-parent dispatch and safe descriptor round trips | Connect every real object constructor, resolver and copied descriptor to the model; justify Rust module-root lifetimes | -| Machine integers | `MachineInts` exact signed-64 model, checked boundary implementation, independent Python and Lean consumers | Connect Rust checked arithmetic and every conversion to the mathematical evaluator; floats remain an extension | -| Progressive contracts | Four real source boundary failures preserve codes, anchors and failure spans; valid contract execution | Universal contract-preservation theorem and imported declaration/call-site attribution | -| Source-bound external calls | Two same-path declarations execute their separately selected source lines on both backends | Full external argument validation, effect-policy and environment-injection refinement | - -The ledger deliberately does not turn a new model lemma, a finite passing -corpus, or independent reconstruction into a complete frontend theorem. Those -remaining proof links are required to discharge the full frontend objective. - -## Default prologue proof and imported contract attribution (November 4) - -`DefaultPrologue.default_prologue_refines` relates source default binding, which -rechecks the current environment for omission, to a guarded block machine with -an immutable initial presence mask. It proves whole interaction-program equality -for arbitrary effectful evaluators, assuming distinct parameter slots and an -initially faithful presence mask. Earlier default stores preserve that invariant -for later parameters. The duplicate-slot counterexample issues two requests in -the machine versus one in the source, demonstrating why slot uniqueness matters. -Explicit None skips and immediate failure stopping are separately checked. -This is a model of guard/evaluate/store blocks, not a proof of the Rust emitter, -flat instruction stepping, actual expression compilation or parser. - -The generated implementation family crosses all 27 omitted/int/None states for -three parameters with all six declaration orders. An independent environment -model checks 162 documents and 324 executions, including 34 faults when a default -reads a later omitted parameter. Source text is reconstructed independently; -expected traces are not derived from either backend. This finite family does -not prove arbitrary defaults. Imported argument-contract diagnostics now retain -the caller's failure span and source revision while pointing the declaration -anchor and suggestion at the actual library. Supplied and defaulted invalid -arguments both refuse before entering the callee body. - -## Concrete name and flat-code interfaces - -The compiler now borrows each original declaration and owning module while -flattening. Bare-call selection uses the same source `lookup_local` operation -as Tree, then maps the selected declaration identity to its flat index. This -removes a second, subtly different lookup algorithm: repeated top-level names -previously selected the first declaration in Tree but failed compilation in VM. -It does not prove the source lookup operation itself. - -`NameSlots` proves reads, writes and the complete named-argument binding fold -commute with an injective local-name vector. Unknown names and repeated raw -API names are covered; repeated raw names retain last-write semantics. A -presence mask computed from initialized slots is faithful by construction. -The Rust raw entry and argument binder now derive their mask from the actual -initial logical slots. Method receiver aliases are overlaid only for default -evaluation, and restored into the body frame after logical argument checks. -`ReceiverDefaults` supplies the additional environment reasoning for explicitly -declared self/自 parameters; the slot theorem alone does not cover that case. - -Every compiled Program is structurally verified before return, and the VM -verifies even publicly constructed/mutated Programs before any instruction. -All current opcode variants are handled exhaustively. Checks include operand -bounds, parameter/local prefix and injectivity, declaration and inheritance -forests, call-layout and function references, spans, reachable stack underflow, -branch/loop join heights and absence of leaked stack values on return. Missing -variable values remain language faults; this checker does not prohibit them. - -Rust exports the computed per-PC heights alongside the real emitted opcode -text. `CheckFlatCertificate.lean` independently decodes that text and applies -an executable checker whose soundness is proved in `FlatCertificate`. Accepted -certificates preserve heights along every finite path and guarantee a valid -fetch with sufficient operands on each reachable PC, including loop prefixes. -The independent reader rejects unmodeled opcodes. Rust debug serialization and -opcode-to-concrete-VM-step correspondence remain interfaces to justify; a -structural certificate does not establish source/bytecode functional equality. - -Neither this ordinary bytecode verification technique nor reuse of a resolver -is an originality claim. Complete functional lowering, parser semantics and the -Rust implementation correspondence remain open proof obligations. - -## Functional expression checks and receiver views (November 4) - -The emitter now records source-directed expression rules before emission, with -child order and exact instruction intervals. The mandatory native verifier -checks literal identity (including floating-point bits), local names, unary and -binary operators, short-circuit targets, interpolation, collections, indexing -and occlusion. Calls delegate staging and selection checks to `bytecode/call.rs`; -resolution and dispatch semantics remain explicit boundaries. -All seven statement forms have source-directed templates; a separate forest -check covers the entire default prologue, statement body and implicit return. -These checks detect stack-preserving semantic corruption, including Add to Sub, -and refuse it before host effects. A forged source witness remains outside this -check's guarantee; the recorder and actual AST correspondence need justification. - -`ExpressionLowering` proves postfix expression compilation preserves complete -interaction programs for arbitrary effectful leaves and operator interpretations, -including faults and an arbitrary caller stack and continuation. `ShortCircuit` -proves the exact absolute-PC AND/OR macros under arbitrary effectful child -evaluation. `CheckExpressionLowering.lean` independently reads actual emitted -operators, constants and local names, and applies the proved core checker. -It counts call, collection, index and interpolation boundaries explicitly. -Child inlining, Rust VM stepping, leaf interpretation and source-witness fidelity -remain obligations; none of these results is whole-frontend functional refinement. - -`ReceiverDefaults` proves that the source's separately maintained default -environment equals the machine's receiver view after every successful prefix. -The mask describes logical argument slots, while omitted self/自 defaults may -replace the evaluation view. Supplied None remains present. The real receiver -is restored before entering the body; argument contracts check both the logical -arguments at the call site and the restored frame at the declaration, preserving -source identity and diagnostic frames. The theorem composes this view invariant -with `DefaultPrologue` for arbitrary effectful defaults and distinct slots. - -Concrete repairs also share scalar/unary semantics across evaluators, stringify -every interpolation part, allocate fresh loop temporaries, restrict dynamic -calls to their defining module scope, and enforce the existing one-million -truthy-iteration limit in VM as well as Tree. Regression evidence records each -repair separately from proof claims. These compiler techniques are not new -originality claims. - -## Actual call staging and bounded control-flow macros - -Every emitted call now has a separate source obligation captured before actuals -are replaced with scratch reads. The checker covers authored actual order, -evaluate/store/pop triples, source-local and loop-slot separation, nested-call -scratch separation, argument reloads, layouts, builtin selection/defaults, host -primitive identity, plugin name/pair ordering, method name/receiver and resolved -user target/tag. Every call expression must have exactly one obligation. The -reserved source-local prefix is established before any synthetic slots are -allocated. Disjoint nested calls may reuse scratch slots after their lifetimes. - -`CallStaging` proves the flat evaluate/save/pop program restores an arbitrary -caller stack and has the same effects and failures as authored-order collection. -It proves outside slots unchanged and unique staged slots read back the exact -actual vector. The dispatch continuation is arbitrary and effectful, so binding, -defaults and receiver effects can follow collection without commuting effects. -`CheckCallStaging.lean` decodes real stores and reloads, applies the proved stage -checker and independently checks the complete selection/dispatch template. -Source-expression callback correspondence, name resolution and the semantics of -each dispatch continuation remain proof interfaces. Host parameter metadata is -an exported registry interface, not an independently verified registry theorem. - -`WhileLowering` proves the condition/JF/check/body/backedge macro preserves the -complete interaction program for a bounded loop, including a final false -condition, condition/body faults, the truthy-iteration limit and early returns. -It relates an increasing native counter to a decreasing model budget and proves -admitted increments below one million fit u32. Model machine-step fuel is -distinct from this language-visible iteration budget. -`CheckStatementLowering.lean` checks actual default prologues, all seven statement -templates, forests and implicit returns, including the exact while macro layout. -The while theorem uses condition/body callbacks; concrete child inlining and the -full Rust state machine are not discharged by checking those layouts. Branches -and foreach currently have independent template evidence, not new functional -refinement theorems. No ordinary compiler-checking technique is a novelty claim. - -## Loaded executable AST and coherent witness corruption - -`SourceFunction` now captures parameters, defaults, executable bodies and complete -contract data directly from the loaded declaration before emission. The native -source checker walks that snapshot separately from the rule recorder, checks -ordered expression/statement correspondence and complete witness ownership, -and accounts for the generated scratch reloads explicitly. It also compares -full contracts with structural Rust equality, including types, nullable fields, -descriptions, source lines and declaration quotes. Contract presence alone would -not detect a Number-to-Any weakening. - -The evidence exports the executable AST separately from the original module and -from the compiled snapshot. `CheckSourceWitness.lean` matches declaration -identities and applies `SourceWitness`'s proved ordered-tree reconstruction -checker. Interpolation parts, index labels, code payloads and formula structure -are retained; all formula floats and matrix entries retain their exact bits. -The old Debug formula text was insufficient for NaN payload identity. Inert -occlusion prose and pre-inference parser metadata are not execution-tree nodes. - -Ten native coordinated-corruption cases change code together with its witness, -including operators, constants, variables, assignments, callees, NaN payloads, -index keys, interpolation, contract metadata and an orphan expression record. -Eight independent source-witness negatives include changing the compiled snapshot -as well. A coordinated wrong operator is a positive acceptance control for all -four earlier independent consumers and a rejection control for the AST checker. -This distinguishes trusted source correspondence from agreement among emitted -metadata fields. - -The theorem proves exact correspondence of the supplied executable trees, hence -preservation under any interpretation of those trees. The native and JSON AST -adapters, normalization helpers and snapshot capture remain trusted interfaces. -No theorem here verifies the actual Markdown classifier/parser/inference or -connects every concrete Rust operation to the semantic models. A caller who -changes both the reference AST and its program has supplied a different -translation-validation input; this is not source authentication. - -## Runtime argument-preparation faults - -The expanded AST audit exposed a concrete acceptance mismatch: Tree can execute -main while an unused function contains a conflicting bracket modifier, whereas -VM compilation previously rejected the entire module. Modifier preparation now -lowers its failure to `RejectArgumentExpansion` before actual evaluation. A -provided default parameter, including explicit None, skips that fault; reaching -it preserves prior output and stops before actual effects or a suffix. The -error's message, span, source revision and diagnostic frames match Tree. - -`CallExpr::for_evaluation` normalizes bare aliases before modifier expansion, -matching Tree's existing order. The expression checker validates an effect-free -fault leaf and the independent decoder handles its actual terminal opcode. -The AST adapter explicitly represents that executable fault without children; -unexecuted actual expressions are not falsely counted as evaluated code. -Two independent fault-opcode/message negatives and a positive AST-identity-only -control keep representation checking distinct from instruction interpretation. - -The independent Python oracle now compares JSON values with exact recursive -types and requires integer arithmetic inputs to be actual integers. Python's -True==1 and 1==1.0 equalities must not erase language-visible value distinctions. -Four type-corruption controls are added. These improvements do not discharge -other call-error timing, parser, resolver, dispatch or Rust-step proof obligations. - -## Native binding and declaration graph validation - -Builtins, host primitives and plugins retain authored labels in native bytecode. -The shared value-independent binding plan selects named parameters before -positionals, preserves omitted optional bindings and unknown named extras, and -reports duplicate, missing and surplus positional arguments after actual effects. -Plugin lookup precedes signature binding. Eighteen reached/unreached error cases -check explicit expected output, messages, spans, source revisions and frames. -A registered C ABI echo probe checks mixed and extra named arguments. Execution -uses the native VM and plugin bridge throughout. - -The source and flat declaration views share ordered resolution. A loaded snapshot -captures ordinal declaration paths, levels, child/root counts, imports and ordered -use aliases before emission. Verification checks identity, parent/child/root order, -module scopes and object/method names, then derives call targets independently of -emitted target records. Two-component paths check runtime receiver presence before -static fallback; an unbound reserved slot differs from a supplied None. Imports -retain priority. Resolution failures are native terminal instructions after actuals. - -`NameResolution` proves first-match, path and lexical commutation under an -ordered embedding. Its rank checker proves sufficient depth and connects a -well-founded total source policy to flat lookup. Rust uses the same parent-chain -policy; parent-view extraction remains a trusted adapter. The finite checkers consume actual AST/flat evidence in -`CheckNameResolution.lean`. Nine native corruptions and seven independent graph -negatives test this boundary. A coordinated wrong target remains a positive control -for the older stack, staging and AST-shape consumers. Ordinary compiler correctness -ingredients are not novelty claims. Snapshot/JSON adapters, primitive registries, -parent-view extraction and concrete Rust -instruction refinement remain explicit obligations; universal frontend verification -and overall paper readiness are not established by these results. - -`ArgumentBinding` separately models per-parameter omission permission and proves -value substitution preserves selections and faults. A successful index plan has -a finite-index witness. `CheckArgumentBinding.lean` checks actual static call -plans and an independently enumerated mask/label corpus. User VM calls now use -the shared planner with the callee default mask, correcting their surplus-count -diagnostic and preserving missing-required-before-default priority. Default -evaluation, contracts, dynamic signature selection and concrete Rust/JSON steps -remain separate interfaces. The mathematical planner is not a proof of the -entire native binding implementation. diff --git a/doc/design/function-as-naming-philosophy.md b/doc/design/function-as-naming-philosophy.md deleted file mode 100755 index 75b34ee..0000000 --- a/doc/design/function-as-naming-philosophy.md +++ /dev/null @@ -1,306 +0,0 @@ -# 语法设计哲学:函数在「代码即文档」里为何水土不服,以及用什么语义取代 - -> **2026-10-23 审阅裁决**:保留“正文优先、按需命名”的方向;下文语料统计和“具名给值缺失”等判断属于当时快照。当前已有具名实参;“调用即代入”不规定文本展开实现,也不禁止递归。下一阶段以[文档原生指导 §2–3](document-native-development-guide.md#2-语法审查的保留修正与暂缓)的范围和验收为准,本文不是替换整个函数模型的已批准语法提案。 - -| | | -|---|---| -| 状态 | **Proposed · 哲学层讨论**(不涉及实现,不含语法提案细节) | -| 日期 | 2026-10-22 | -| 命题来源 | 用户:「函数是复用、是对高度凝练内容的提炼加工;正常人不会说『计算 37 的两倍需要抽象一个函数』,而是直接说乘二」 | -| 定位 | 本文只谈**语义表示**与**自然语言映射**,不谈编译器与语法糖 | - ---- - -## 0. 把你的观察写成三条命题 - -**命题一(现象)**:函数是一种**预先抽象**装置——必须在使用之前先把内容提炼并命名,还要声明它需要哪些输入。 - -**命题二(对照)**:自然语言是**即席描述**——先把事说清楚,只有在内容确实要反复出现时,才顺手给它一个名字("以上做法,我们称为…"),而且命名之后它可以像普通名词/动词一样被使用。 - -**命题三(结论)**:因此「函数」这套仪式与「代码即文档」错位。要解决的不是调用写法,而是**用什么语义表示来承担"复用"这件事**。 - -本文的答案先给出来: - -> **Marqdo 需要的不是更好的"函数",而是把「函数」还原成「命名」,把「调用」还原成「代入」。** -> 函数 = **一段被命名的正文**;参数 = **那段正文里尚未确定的量**;调用 = **把这些量代入后重述一遍**。 - ---- - -## 1. 语料给出的证据:Marqdo 的 `##` 其实不是"过程" - -统计 `lib/ ext/ examples/ tests/` 全部 1322 个 `##`: - -| 指标 | 数值 | -|------|------| -| 函数总数 | 1322 | -| **纯返回式**(零可执行语句,只有一个返回表达式) | **765(57.9%)** | -| 一行式(可执行行 ≤1 且返回 ≤1) | 935(70.7%) | -| 极短(可执行行 ≤2) | 1162(87.9%) | -| 较长(可执行行 ≥10) | 62(4.7%) | -| 可执行语句数**中位数** | **0** | -| 平均 | 2.2 | - -典型代表:`## str_trim`、`## contains`、`## to_upper`——**一个名字包一个表达式**。 - -这说明:**人们用 `##` 在做"命名",语法却要求他们按"过程抽象"的仪式来做。** -签名(`+ n`)、祈使式调用(`> f 1 2`)、返回值约定(`*…*`)全是过程语言的行头, -而实际内容是"给这个式子起个名字"。 - -**水土不服不是感受,是可以量化的形式错配。** - -### 1.1 按「语义功能」再分一次类 - -把 1322 个函数按内容形态归类(同一函数可能重叠,故按主特征优先): - -| 形态 | 判据 | 数量 | 占比 | 自然语言对应 | -|------|------|------|------|-------------| -| **纯命名式** | 零语句、零副作用、零分支、零循环,只有一个返回式 | **754** | **57.0%** | 「所谓 X,是指…」 | -| **条款式** | 有分支、无副作用 | 103 | 7.8% | 「凡…则…」 | -| **遍历式** | 有循环、无副作用 | 26 | 2.0% | 「对每一项…」 | -| **命令式** | 含 `print` 等副作用 | **83** | **6.3%** | 「打印…」祈使句 | -| 线性计算(其余) | 有语句但无控制流/副作用 | 356 | 26.9% | 「先…再…」 | - -两个结论: - -1. **命名 + 条款 = 64.8%** —— 三分之二的 `##` 落在"定义"与"条款"两种自然语言形态里, - 而这两种恰好不需要"过程"语义(§4 立场甲、乙)。 -2. **真正的副作用只有 6.3%** —— 也就是说"命令/祈使"语义只是少数派, - 完全可以隔离成一小块(§8.1),不必让它污染整体读法。 - ---- - -## 2. 为什么"抽象"在文档里格外别扭:复用经济学 - -抽象不是免费的。它有三项成本: - -| 成本 | 内容 | -|------|------| -| **定义成本** | 要写一次定义(名字、输入、边界) | -| **跳转成本** | 读者看到名字,必须回到定义处才能理解(文档尤其致命:要翻页/滚动) | -| **维护成本** | 定义改了,所有使用处语义随之变化 | - -收益只有一项:**同一内容被复用 N 次时省下的重复**。 - -于是有: - -> **抽象值得做 ⟺ 复用次数 × 内容复杂度 > 定义成本 + N × 跳转成本** - -在**代码**里,N 往往很大、跳转成本低(IDE 跳转、同屏),所以抽象划算。 -在**文档**里,N 常常是 **1**,跳转成本高(读者在阅读流里被打断),于是: - -> **文档中大量"函数"是负收益的**——它们只被用一次,却强迫读者回头查定义。 - -这解释了为什么你会有"正常人不会这么说话"的直觉:**说话的默认假设是对方不知道你的定义**, -所以人话倾向于**就地展开**;而函数默认假设读者愿意跳转。 - ---- - -## 3. 自然语言里「复用」到底有几种形态 - -程序语言只承认其中一种(命名+参数化),这是错配的第二层。 - -| 形态 | 自然语言的样子 | 对应的程序装置 | Marqdo 现状 | -|------|---------------|---------------|------------| -| **重复** | 再说一遍 | 复制粘贴 | ✅ 允许 | -| **指称** | 如上所述 / 同前 / 该金额 | 变量、引用 | ✅ `` `名` `` | -| **命名** | 所谓 X,是指…;以下称 X | 定义 / 函数 | ✅ `## X` | -| **条款** | 凡…则…;若…应… | 条件分支、规则 | ✅ `1. 2. 3.` | -| **范例** | 以 37 为例 | 样例/测试 | ⚠️ 仅测试目录 | -| **表格/清单** | 见下表;用料如下 | 数据、查表 | ✅ 表格 | - -**关键发现**:命名只是六分之一,但程序语言把它变成了**唯一的复用入口**。 -而文档写作里,**指称("该金额")与条款("凡…则…")比命名更常用**。 - ---- - -## 4. 三种候选语义表示(哲学立场) - -要"代替水土不服",必须给出**语义模型**,而不只是换个写法。三个候选: - -### 立场甲:定义—代入(Definition & Substitution) - -**语义**:一段正文被命名 → 成为一个**定义**。使用它 = 把定义里的自由量按**角色**代入,再重述。 - -```markdown -## 加倍 - -把 `x` 乘以二,得 *y* -``` - -使用(语义读法):**按「加倍」代入 x=37,得 74。** - -| 维度 | 评价 | -|------|------| -| 自然语言对应 | ✅ 「依定义」「按…计算」「所谓…是指…」——学术与说明文的主力 | -| 与 Marqdo 契合 | ✅ `##`/`#` 本来就是标题(文档结构),天然是"定义"的载体 | -| 参数观 | ✅ 角色(具名),不是位置占位符 | -| 复用单位 | ✅ **文本段落本身**(文档即单位,符合"代码即文档") | -| 71% 的现有一行式函数 | ✅ 直接就是"命名的表达式",无需过程仪式 | -| 缺点 | 定义与使用分离,仍有跳转成本(但可用"就地展开"缓解,见 §5) | - -### 立场乙:条款—援引(Clause & Citation) - -**语义**:条件 → 结论。使用 = 援引条款并给出适用的事实。 - -```markdown -## 计费规则 - -若 `里程` 超过 100 公里,则 `费用` 按 8 折计。 -``` -使用(语义读法):**本单里程 120 公里,依「计费规则」,费用按 8 折。** - -| 维度 | 评价 | -|------|------| -| 自然语言对应 | ✅✅ 「凡…则…」是中文说明文/法条/规章的骨架 | -| 与 Marqdo 契合 | ✅ `1. 2. 3.` 分支已经就是条款形式 | -| 缺点 | 数值计算写成条款别扭("把 37 乘以二"不是条款) | - -### 立场丙:配方—配料(Recipe & Ingredients) - -**语义**:一张用料表 + 一段做法。参数 = 配料表中的行。 - -| 维度 | 评价 | -|------|------| -| 自然语言对应 | ✅ 菜谱、工艺卡、表单 | -| 与 Marqdo 契合 | ✅✅ 表格优先正是 Marqdo 的特色;契约表已是雏形 | -| 缺点 | 表达力弱;无法递归、无法组合;"给值"变成填表 | - -### 取舍 - -| | 甲 代入 | 乙 条款 | 丙 配料 | -|---|---|---|---| -| 覆盖"命名表达式"(58% 的现状) | ✅✅ | ⚠️ | ❌ | -| 覆盖"条件规则" | ⚠️ | ✅✅ | ❌ | -| 覆盖"数值流程" | ✅ | ❌ | ⚠️ | -| 可读性 | 高 | 最高 | 最高(但最弱) | -| 与 `##` 结构一致 | ✅ | ✅ | ⚠️ 表为主 | - -**推荐:以甲为主,乙作为甲内部的一种段落形态。** 理由见 §6。 - ---- - -## 5. 「代入」为什么比「调用」更贴自然语言 - -这不是文字游戏,三处实质差异: - -| 维度 | 调用(invocation) | 代入(substitution) | -|------|-------------------|---------------------| -| 读者的心理动作 | "跳过去,看它做什么,再回来" | "把这个式子代进去" | -| 输入的意义 | 实参 → 形参(两套名字) | 角色 → 定义里的同一个名字(**一套名字**) | -| 结果的意义 | 函数返回了一个值 | 式子变成了具体结果 | -| 出现位置 | 必须是独立语句或表达式 | 可以**嵌在叙述里**("加倍后为 74 件") | -| 一次性使用 | 仍要付出定义+跳转成本 | 可以**不定义,直接展开**(§5.1) | - -### 5.1 关键:抽象要能被"取消" - -自然语言的强大在于**可省略**:能一句话说清就不起名字。 -所以语义模型必须允许同一件事有**两种粒度**,并可以随时在两者之间移动: - -| 粒度 | 写法(示意) | 何时用 | -|------|-------------|--------| -| **就地描述** | 把 37 乘以二,得 74 | 只用一次 | -| **命名后代入** | 按「加倍」代入 x=37,得 74 | 复用多次 | - -而且**提升与展开都是作者的编辑动作,不是必须的入口**。 -这正是"抽象可选"——今天的函数是"必须先抽象",这是错配的第三层。 - -### 5.2 与 58% 纯表达式函数的对应 - -`## to_upper` 这类函数,用"代入"读就是: - -> 「to_upper 的定义是:把 `s` 变成全大写。」使用:`to_upper` 代入 s="abc" 得 "ABC"。 - -它读起来是一个**定义 + 一次代入**,而不是"调用一个过程"。这与它的实际内容(一个表达式)一致。 - ---- - -## 6. 这套语义如何落到 Marqdo 已有的东西上 - -| 自然语言的成分 | Marqdo 已有载体 | 需不需要新东西 | -|---------------|----------------|---------------| -| 命名(给出定义) | `#` / `##` 标题 | ❌ 已有 | -| 正文(定义的内容) | 叙述 + 标记代码 | ❌ 已有 | -| 未确定的量(角色) | 体推断出来的形参(v0.3 已有) | ❌ 已有 | -| 角色的**具名给值** | (缺失) | ✅ **这是唯一真正缺的一环** | -| 结论(得…) | `*…*` 返回 | ❌ 已有 | -| 条款(凡…则…) | `1. 2. 3.` 分支 | ❌ 已有 | -| 配料表 | GFM 表格 + 契约表 | ❌ 已有 | -| 引用(依…) | (缺失) | ⚠️ 与"具名给值"是同一件事 | - -**结论:缺的只有一件事——「具名给值」的形式。** - -也就是说:语义模型(代入)几乎不用改,语法只缺一个"把角色填上"的最小约定。 -这把问题从"要不要重新设计函数"缩小到"这一个小约定怎么长得最不刺眼"。 - ---- - -## 7. 不可回避的哲学难题:自然性 vs 可判定性 - -自然语言判断"哪些量要代入"靠**语境**(前文、常识、指代)。 -编译器不能。所以必须有一条**显式约定**,无法省掉。 - -三种可能的约定形态(只列哲学性质,不列语法细节): - -| 形态 | 自然的程度 | 可判定的程度 | 风险 | -|------|-----------|-------------|------| -| **角色必须具名给出** | 中(像"按定义,其中 x=37") | ✅ 完全可判定 | 略啰嗦 | -| **靠语序(位置)** | 高 | ✅ 可判定 | ❌ 已实测:叙述顺序一变,绑定就翻转(见 call-syntax-from-marks.md §4.3) | -| **靠语境(隐式)** | 最高 | ❌ 不可判定 | ❌ 130 个形参名撞车 | - -**这是整件事的硬边界**:越像人话,越难判定。Marqdo 必须选"具名"这一档—— -它是**唯一同时可读且可判定**的点。 - -而这也解释了为什么"叙述式动词"(`执行`)不可取:它把判定交给了一个**未标记的词**, -既没有自然的程度优势,又破坏了"叙述安全"。 - ---- - -## 8. 三个尚未解决的哲学问题 - -这些是真问题,需要后续立场,不宜草率定: - -1. **副作用怎么办?** - "把 37 乘以二"是纯代入;"打印 74"呢?打印**改变世界**,不是代入。 - → 副作用可能必须停留在"命令"语义(今天的 `> print`), - 而这会让文档里同时存在"代入"与"命令"两套读法。这是否可接受? - -2. **递归与自引用怎么办?** - 代入是有限展开;递归是无限展开。若坚持代入选义,递归就不可表达。 - → 是否接受"Marqdo 不支持递归"?还是给递归单独一套"过程"语义? - -3. **定义的时序怎么办?** - 自然语言允许先使用后定义("如上,我们称之为…")。代入语义要求定义先存在。 - → 是否允许前向引用(读者先看到 `加倍`,后面才看到定义)? - ---- - -## 9. 一句话总结与建议 - -> **Marqdo 的问题不是"函数不好用",而是"函数是过程语言留给文档的遗产"。** -> 文档需要的不是过程,是**命名**;不是**调用**,是**代入**。 - -建议的语义立场(待你裁决): - -| 项 | 建议 | -|----|------| -| 复用单位 | **一段被命名的正文**(而非过程) | -| 参数观 | **正文中未确定的量**(角色,具名) | -| 调用观 | **代入**(可读作"按…代入…") | -| 抽象时机 | **可选提升**:默认就地展开,需要复用时才命名 | -| 唯一新增约定 | **具名给值**(形态待定,但必须具名,理由见 §7) | -| 保留"命令"语义 | 仅用于副作用(`print` 等),与"代入"分层 | -| 条款 | 作为定义的一种段落形态(`凡…则…`),不另设机制 | - ---- - -## 10. 待你裁决 - -1. **是否接受"函数→命名 / 调用→代入"这个总重构?** - 若接受,后续所有语法讨论都在这条轴上做取舍。 -2. **§8 的三个难题**你的倾向是什么(尤其"是否接受不支持递归")? -3. **"具名给值"的最小形态**:你更接受哪一种读感? - - `**加倍(x=37)**`(像函数调用) - - `按**加倍**,`x`=37`(像句子,但需要判定规则) - - 表格给出角色(像配料表) -4. 是否需要我把这份哲学立场,反向校验一遍**现有 1322 个函数**—— - 看有多少在"命名表达式"框架下会更自然、多少必须保留"过程"语义? diff --git a/doc/design/function-as-table-semantics.md b/doc/design/function-as-table-semantics.md deleted file mode 100755 index 7ebb193..0000000 --- a/doc/design/function-as-table-semantics.md +++ /dev/null @@ -1,337 +0,0 @@ -# 语义探析:代码函数能否解释为一张 GFM 表 - -> **2026-10-23 审阅裁决**:下文 v1.5.2 实验不替代当前回归。保留现有数据表几何与契约表角色,不重复声明参数;“现有实现不支持函数表”不等于表格不能表达计算。有限决策表和生成式签名视图按真实用例评估,见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓)。 - -| | | -|---|---| -| 状态 | **Proposed · 待决策**(未修改任何代码) | -| 日期 | 2026-10-22 | -| 提出 | 「`## 函数名` + `+ 参数` + 函数体,从某种角度能否解释成 GFM 表」 | -| 方法 | 11 组运行时实验(1.5.2)+ 5 份设计/路线图文档考古 | -| 相邻 | [functions-as-values-evaluation.md](functions-as-values-evaluation.md) · [link-style-call-evaluation.md](link-style-call-evaluation.md) | -| 关键前置 | [collection-access-link.md](collection-access-link.md) · [call-arguments.md](call-arguments.md) · [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) · [objects.md](objects.md) | - ---- - -## 0. 一句话答案 - -**你的命题在 Marqdo 里已经实现了——但它实现的是「关于函数的表」,不是「函数本身」。** - -``` -## 加一 - -| 参数 | 类型 | 说明 | -|------|------|------| -| n | number | 输入值 | - -*n+1* -``` - -这张表**今天就能跑**,是既有特性(契约表,`tests/contracts/ok_contract.mq.md`)。 -它证明了:函数参数**确实可以**是一张 GFM 表。 - -但它只能**描述**参数,不能**声明**参数;它不含函数体,不决定 arity,也不能被调用。 -一句话划界: - -> **表能描述外延(输入→结果)与签名(元数据),不能描述内涵(怎么算)。** -> 而「调用」恰恰是内涵操作。 -> `[k](集合)` 是**投影已有数据**,`f(x)` 是**计算新数据**—— -> 只有 f 本身已经是「预先枚举好的表函数」时,两者才重合。 - ---- - -## 1. 先固定事实:Marqdo 的表格几何(实测) - -讨论前必须先把「表」的语义钉死,否则会建在错觉上。 - -| 形状 | 绑定结果 | 实验 | -|------|---------|------| -| 1 列 N 行 | `List`(列值) | 文档锁定 + 实测 | -| ≥2 列 **1 行** | `Map`(表头→标量,即「记录」) | `{"档位":[1,2]}` 反例 → 单行才是记录 | -| ≥2 列 **N 行** | `Map`(表头→**列列表**,列向聚合) | 实测 `{"档位":[1,2],"税率":[0.03,0.1]}` | -| 首列标头为 `行` / `@` / `row` | `List[Map]`(**行向记录**,显式开启) | [tables-maps-footnotes](../roadmap/tables-maps-footnotes.md) §3.5 | - -**关键点**:Marqdo 的默认是**列向**。多行多列表不是「一组记录」, -而是「一列一个列表」。行向记录是**显式标记**才能开的形态, -文档原话:「**不得**与默认列向字典静默混用」。 - -这一条直接决定了「行 = 参数」在 Marqdo 里**不是自然形态**: -按默认几何,`| 参数 | 类型 |` 两行参数会变成 -`{"参数":["a","b"], "类型":["number","number"]}` —— 列向。 - ---- - -## 2. 你的命题已经存在:契约表 - -`src/contract.rs:308` 的注释写得很清楚: - -``` -/// 未绑定文档表(`Expr::Map`)→ 契约块。 -/// - `None`:非契约形状(普通数据/说明表,原样保留)。 -/// - `Some(Err)`:契约形状但畸形 —— 必产诊断。 -/// - `Some(Ok)`:合法契约(`参数`/`返回`/`字段` 三形状之一,须含 `类型` 列)。 -``` - -三条规则(`src/contract.rs:260-334`): - -| 规则 | 实现 | -|------|------| -| 表头含 `参数`/`形参`/`param`/`arg` → 形参契约 | `PARAM_HEADERS` | -| 表头含 `返回`/`return`/`result` → 返回契约 | `RETURN_HEADERS` | -| **必须含 `类型` 列**,否则视为普通说明表 | `TYPE_HEADERS` 缺失 → `return None` | - -也就是说:**「函数参数表」不仅可能,而且已经是正式语法**。 -第一列标头(`参数` / `返回` / `字段`)扮演的正是 -[tables-maps-footnotes](../roadmap/tables-maps-footnotes.md) §3.5 里 -`行`/`@`/`row` 那种**形态标记**的角色:显式声明「这张表是干什么用的」。 - ---- - -## 3. 但它是「关于参数的表」,不是「参数本身」 - -11 组实验里最关键的 6 组(全部实跑): - -| # | 写法 | 实测结果 | 说明 | -|---|------|---------|------| -| E1 | 参数表列 `n`,函数体不读 `n` | `> f` 无参调用**成功**,`n` 不是形参 | 表不能声明形参 | -| E3 | 叙述声明 `n` + 参数表 + 传 `"七"` | `参数 n 期望 number,实际 text(契约校验)` | **表能校验** | -| E4 | 叙述声明 `n`,**无表** + 传 `"七"` | `七1` | 无表则不校验 | -| E5 | `+ \`n\`` 旧式形参行 + 参数表 + 传 `"七"` | 同 E3,报契约错 | **你的草图形态可用** | -| E6 | 表写 2 行(`a`,`b`),体只读 `a` | `too many positional arguments` | **表 ≠ arity** | -| E7 | 单列参数表 `\| 参数 \|` + `\| n \|` | `七1`,**契约静默失效** | 1 列 = List,不成契约 | -| E8 | 表里重复两行 `n` | 取**首行**类型,无诊断 | 表内重复静默 | -| E9 | 表里有 `ghost`(体里没有) | 静默忽略 | 幽灵行静默 | -| E10 | 同一张表加 `` `tc` = `` 绑定 | `七1`,契约**消失** | 绑定 → 变数据 | - -**E10 揭示了一条隐含且优雅的规则**: - -> **未绑定的表 = 声明/元数据(契约);绑定的表 = 数据。** - -这正是语言对「表可以是声明吗」给出的既有答案:可以,**但前提是它不是一个值**。 -一旦你给它起名字(`` `tc` = ``),它就从「关于函数的声明」降级为「一个普通数据值」。 - -E6 + E7 + E8 + E9 合起来说明:**表与真实签名之间今天就可能漂移,而且是静默的** -(`marqdo check e7.mq.md` 输出「无契约问题」)。 - ---- - -## 4. 若让表成为「定义」,运行时会发生什么 - -把上面的静默漂移从「少个校验」升级成「少个参数」,风险等级完全不同。 - -| 风险 | 今天(表=注解) | 若表=定义 | -|------|----------------|-----------| -| 漏写 `类型` 列 | 契约静默失效(E7) | **参数静默消失**,调用直接错 arity | -| 表行数 ≠ 体读取数 | 表多余行被忽略(E6/E9) | **接口由表决定**,体重构后表未改 → 运行期崩 | -| 重复行 | 取首行(E8) | **参数重复定义**,行为取决于解析器取舍 | -| 表行重排 | 无影响(顺序由声明序决定) | **改变位置参数绑定顺序** → `> f 1 2` 含义变了 | -| 加名字绑定 | 变数据(E10) | 语义分叉:什么时候是函数、什么时候是数据? | - -最后一条最致命。**表是「可自由编辑的文档」**:调整行序、增删说明列、 -甚至把两张表合并,都是正常的写作行为。一旦表的行序决定位置参数绑定, -「把 `b` 那行移到 `a` 上面」这个无害的编辑动作就**改变了程序行为**。 - -而 Marqdo 的核心承诺是「**文档即程序,且文档可被人阅读与维护**」。 -让排版顺序携带语义,等于给每张表埋一颗静默的雷。 - -对比一下:`[键](集合)` 之所以安全,是因为**键是显式的**, -取元不依赖顺序。而位置参数天然依赖顺序——所以**签名不该用表承载顺序**。 - ---- - -## 5. 为什么链接式调用 `[f](args)` 走不通(第三次论证,这次有史料) - -前两轮已从「与取元同形」论证过。这次找到了设计层的原始决议。 - -[collection-access-link.md](collection-access-link.md) §1: - -> 心智:**方括号 = 取出的名字,圆括号 = 从哪取。** - -```markdown -**价 = [拿铁](菜单)** # 取出的名字 = 拿铁;从哪取 = 菜单 -``` - -§4「非目标」明确排除:点号 map 访问、`在`、箭头取元、`(键)[集合]`。 -[call-arguments.md](call-arguments.md) §2 同样锁定: - -> `]` 后**紧邻** `(` → **取元** `[key](collection)`,不是 callee 标记。 - -所以 `[f](x)` **不是「还没决定的语法」,而是已被明确分配给取元**。 -让它兼作调用,就是把「从哪取」这个心智反转成「调用谁」——两套直觉会打架。 - -而且这与 §4 的表问题**同源**:都是「同一个外形要承载两种语义」, -只不过一个在值层面(表 vs 函数),一个在语法层面(取元 vs 调用)。 - ---- - -## 6. 历史:这条路走过,而且是被**反向**走过的 - -这是本轮考古最有价值的发现。四条史料: - -### 6.1 v0.2 要求手写形参表 → v0.3 明确废除 - -[markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) §1 把 v0.2 的做法列为**代价**: - -| v0.2 | 代价 | -|------|------| -| 形参必须 `` + `名` `` | **仪式感强;函数头像「另一套签名语言」,与正文脱节** | - -§2 P4 直接给出新方针: - -> **P4 — 形参由体推断(Body-inferred params)** -> **不再要求**作者手写 `` + `名` `` 形参表(v0.3 默认关闭;过渡期可兼容) - -§5 对照表把 `+ 名` 标为「**过渡兼容**:显式形参;**新代码不推荐**」。 - -**结论**:Marqdo 的发展方向是**离「声明式签名」越来越远**,转向「叙述即签名」。 -把参数改写成表,是在这条已经走反了的路上再走一遍。 - -### 6.2 「用表声明 schema」是明文非目标 - -[objects.md](objects.md) §6 非目标: - -> - 用表格声明字段 schema(**表格仍表示数据集合**;见 tables-maps-footnotes.md) - -路线图里同样列为非目标: - -> 用表声明对象字段 schema(仍见 objects 非目标;**与数据集合分开**) - -**结论**:语言已明确决定「表管数据,不管声明」。契约表是这一原则的**受控例外**—— -它只提供注解与校验,不提供绑定。 - -### 6.3 行向记录必须显式标记,且「不得静默混用」 - -[tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) §3.3: - -> **备选语义(不默认):行向记录列表** …… 若未来需要,用显式标记区分, -> **不得**与默认列向字典静默混用。 - -§3.5 落地了 `行`/`@`/`row` 标记。 - -**结论**:凡是「形态会改变语义」的地方,Marqdo 一律要求**显式标记**。 -「函数签名表」如果真要参与绑定,属于同类形态变化,必须同样显式—— -而契约表的 `参数`/`返回` 头,正是这个显式标记的现成形态。 - -### 6.4 取元曾被反复挑选,最后选定链接形 - -[collection-access-link.md](collection-access-link.md) §3 记录了迁移史: -脚注形 `` 集合[^键] ``(左键右基)→ 链接形 `[键](集合)`(左键右基,更好读)。 - -**结论**:`[…](…)` 这块语法是被**反复权衡后定下来的**,不是随手占用。 - ---- - -## 7. 诚实的收益清单 - -不能只讲风险。这条路确实有真收益: - -| 收益 | 现状 | 潜力 | -|------|------|------| -| **人读** | 契约表已能带类型+说明,比 `+ 名` 可读得多 | 正是 v0.3 批评 `+` 行「仪式感」的解药 | -| **调用边界校验** | 已实现(E3) | 可扩展到更多类型(枚举、范围) | -| **机器读:tool schema** | ⚠️ 半成品:`tools` 已能写成记录行(`tool_names` 接受含 `name`/`工具` 字段的对象),但 `agent_format_tools` **只渲染名字**(`- name`),说明与参数被丢弃 | 若函数暴露签名,工具可带 schema 与说明,实参可校验 | -| **机器读:CLI/表单** | ❌ 无 | 签名即表 → 直接生成命令行参数解析、Web 表单 | -| **文档一致性** | ❌ 表与体可静默漂移(E6/E9) | 可做成「漂移即报错」 | - -最后三行是**最有价值的**。最典型的是 tool schema:`tools` 的数据形态**已经允许**每行带说明, -但渲染器只取名字——也就是说**能力已经在那儿,只差把签名接上去**。 -这不需要把表变成定义,只需要让签名**可被投影成表**。 - ---- - -## 8. 建议:表做声明,不做定义(并补三件事) - -### 8.1 结论 - -| 主张 | 裁决 | -|------|------| -| 函数参数可以用 GFM 表**描述** | ✅ **已经是特性**,继续用 | -| 函数参数可以由 GFM 表**声明**(表即真相) | ❌ 不建议:顺序携带语义、静默漂移、与 v0.3 方向相反 | -| 函数**本身**(含函数体)= 表 | ❌ 不可行:体是代码不是数据(见 functions-as-values §4.2) | -| `[f](args)` 链接式调用 | ❌ 已被明确分配给取元 | - -**保持现有分工**: - -> 未绑定的表 = 声明(契约);绑定的表 = 数据;**函数体与 arity 是唯一真相**。 - -### 8.2 该补的三件事(都低成本,且都是「消灭静默」) - -**① 让漂移显式化(最高价值)** - -现状:表写 2 行、体只读 1 个 → 静默忽略(E6/E9);1 列 → 静默失效(E7)。 -建议 `marqdo check` 增加诊断: - -| 情形 | 现在 | 应改为 | -|------|------|--------| -| 契约表缺 `类型` 列 | 静默视为普通表 | 若表头含 `参数`/`返回` 则 **warn**:缺 `类型` 列,已按说明表忽略 | -| 契约表列数不齐 | 有诊断(`Some(Err)`) | 保持 | -| 表里的参数名不在真实 arity 内 | 静默忽略 | **warn**:`ghost` 不是本函数的形参 | -| 表头重复参数名 | 取首行 | **warn**:重复声明 | - -这与本轮 D9「未闭合引号静默吞行」是同一类问题——**静默类缺陷**优先修。 - -**② 反向生成:签名 → 表(满足「语法很美」)** - -既然表是好的**呈现**,就让工具来生成它,而不是让人手写: - -``` -marqdo view --signature 文件.mq.md # 从体推断的签名生成契约表草案 -``` - -单一真相仍是函数体,表是**投影**。这样既拿到「签名即表」的可读性, -又不引入第二真相。人也可以手写表,`check` 负责校验它与体一致(即 ①)。 - -**③ 让签名可供机器消费** - -把 `Function` 的签名(名、参数、类型契约)暴露成结构化数据(如 -`marqdo knowledge` 的能力条目里带上参数 schema), -`ext/ai` 的工具即可从「只渲染名字」升级为「带 schema 与说明的工具」。 -这是 §7 里最实的收益,且**零语法改动**。 - ---- - -## 9. 一个可以试的新写法(示例,供你评判) - -如果你想保留「表 + 函数体」的书写快感,最安全的形态是**双写 + 一致性校验**: - -```markdown -## 税率 - + `档位` - -| 参数 | 类型 | 说明 | -|------|------|------| -| 档位 | number | 1/2/3 档 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| | number | 适用税率 | - -- [行](`税率表`) - **hit = [档位](`行`)** - 1. `hit` - ... - *[税率](`行`)* -``` - -| 优点 | 缺点 | -|------|------| -| 人读极好(表 + 正文) | 与真实签名可能漂移(需 ① 的校验兜住) | -| 已经是**今天可跑**的语法(E5 验证) | `+ 行` 是 v0.3 标注「新代码不推荐」的旧形态 | -| 类型校验已生效(E3) | 表不能替代体推断,参数仍要声明 | - -**要点**:这张表**不是**函数的定义,而是它的**仪表盘**。 -真正的接口由 `+ 档位`(或叙述声明)决定,表负责类型与说明。 -只要两者不一致就报错,这套写法就既美又安全。 - ---- - -## 10. 待你决策 - -1. **裁决**:是否接受「表做声明、不做定义」(§8.1)? -2. **优先级**:§8.2 的三件事(① 漂移诊断 / ② 反向生成 / ③ 签名可供机器消费) - 先做哪个?我建议 ①(消灭静默)→ ③(tool schema 是刚需)→ ②。 -3. **是否要我把 `+ 行` 加契约表的组合**写成教程样例(§9), - 并明确标注「`+` 是兼容形态、新代码优先叙述声明」? -4. 若你仍想推进「表即签名」,我可以做一次**限定实验**: - 要求显式标记(如 `| 签名 | 参数 | 类型 |`)+ 与体推断不一致即报错, - 在小范围金样里验证是否可控。要我做吗? diff --git a/doc/design/functions-as-values-evaluation.md b/doc/design/functions-as-values-evaluation.md deleted file mode 100755 index 8d01ff2..0000000 --- a/doc/design/functions-as-values-evaluation.md +++ /dev/null @@ -1,471 +0,0 @@ -# 方案评估:函数能否作为变量的一种(函数即表) - -> **2026-10-23 审阅裁决**:以下是旧实现约束与方案权衡,不是“匿名函数无法索引”或“动态调用无法检查契约”的普遍结论。一等函数/闭包本轮暂缓而非永久禁止;有限决策表先评估现有库表达,文中建议的新辅助函数不因此成为已实现能力。参见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓)。 - -| | | -|---|---| -| 状态 | **Proposed · 待决策**(未修改任何代码) | -| 日期 | 2026-10-22 | -| 提出 | 用户:「函数本身可以理解为 `` `函数名` = `` + 参数/函数体表;此时和表格取元有极大相似性」 | -| 相邻 | [link-style-call-evaluation.md](link-style-call-evaluation.md) · [spaced-function-names-d8.md](spaced-function-names-d8.md) · [function-as-table-semantics.md](function-as-table-semantics.md)(后续:函数与表格的语义考古,11 组实验) | -| 影响面 | 值模型 / 调用语义 / 契约 / EKC 指纹 / 字节码 / 序列化 | - ---- - -## 0. 一句话结论 - -**你的直觉在数学上是对的,但在语言上要拆成三种强弱不同的主张**: - -| 主张 | 是否已成立 | 代价 | -|------|-----------|------| -| 弱:函数**名**可当数据传递 | ✅ **今天就能做**(字符串 + `call_fn`),但零参、不可静态检查 | 无 | -| 中:函数是**一等值**(可存、可传、可返回) | ❌ 需要新值类型 + 动态 callee | 中高:契约、指纹、字节码、序列化全都要动 | -| 强:函数**就是表**(结构性、可遍历、可序列化) | ❌ 需要把代码降格为数据 | **高**:与「代码即文档」的静态可索引性冲突 | - -**建议**:把你草图里真正有价值的那部分(**有限域决策表**)作为一等公民支持——它今天就成立、 -且极其契合 Marqdo 的表格优先哲学;而「函数即表」的强主张不建议采纳,理由见 §4、§6。 - ---- - -## 1. 先把「函数是变量」拆开 - -这四个概念经常被混为一谈,必须分开,否则讨论会滑。 - -### 1.1 外延观(extensional)——函数是「图」 - -数学上函数就是一组有序对 $f = \{(a,1),(b,2)\}$,即它的**图像**。 -按这个观点,函数**确实是一张表**,调用就是**查表**。 - -**但这里有一个必须先说清的实测事实**(我最初也想当然写错了): - -GFM **两列表绑定成「列映射」,不是「按首列键控的映射」**: - -```markdown -`税率` = - -| 档位 | 税率 | -|------|------| -| 1 | 0.03 | -| 2 | 0.10 | -``` - -```json -{"档位":[1,2],"税率":[0.03,0.1]} -``` - -所以 `[2](`税率`)` **不是**取税率,而是: - -``` -error: missing map key `2` -``` - -真正能「键 → 值」查表的形态是 **Map**(来自 JSON 或库函数),实测两条可用配方: - -**配方 A(推荐,最简)** - -```markdown -**税率 = > json.parse text={"1":0.03,"2":0.10}** -**t = [2](`税率`)** # → 0.1 -``` - -**配方 B(保留 GFM 表格可读性,但需显式索引)** - -```markdown -**ks = [档位](`税率`)** # [1, 2] -**vs = [税率](`税率`)** # [0.03, 0.1] -**i = > table.index_of list=`ks` item=2** # 1 -**r = > table.at xs=`vs` i=`i`** # 0.1 -``` - -两条都在 1.5.2 上跑通了。**结论**:外延观的「函数=表」在 Marqdo 里不是 -`[k](表)` 一句话就能实现,而是「**取到键值对**」这件事本身需要配方。 -这恰好是一个可补的库缺口(见 §8.1)。 - -### 1.2 内涵观(intensional)——函数是「规则」 - -`f(x) = x² + 1` 无法写成有限表(定义域无穷)。此时函数是**代码**,调用是**执行**。 - -### 1.3 闭包观——函数是「代码 + 环境」 - -参数之外还要捕获外部变量。这需要运行时的环境快照。 - -### 1.4 名字观——函数是「命名空间里的一条」 - -今天 Marqdo 就是这一种:函数存在于 `Module.functions`,按名字解析。 - -**你的草图 `|参数|函数体|` 属于哪一种?** 它是**混合体**:行是参数声明(§1.4 的味道), -单元格放函数体(§1.2 的味道)。而「和表格取元相似」的直觉来自 §1.1。 -**三种东西被一句话连起来了**——这正是评估要解开的结。 - ---- - -## 2. 现状实测(全部在 1.5.2 上跑过) - -### 2.1 值模型里没有函数 - -`src/value.rs:15` 的 `Value` 枚举:`None / Bool / Int / Num / Text / List / Map / Formula / Code / Secret`。 -**没有 `Func`。** 函数是 AST 节点(`src/ast.rs:58 Function`),挂在 `Module.functions`(`src/ast.rs:27`)。 - -`src/contract.rs:104` 的 `type_of` 同样是十种,穷举无函数。 - -### 2.2 调用的 callee 是静态名字,不是表达式 - -`src/ast.rs:130 CallExpr { callee: String, path, receiver, args }` —— -`callee` 是 **`String`**,不是 `Expr`。所以**语法上无法写出「对计算出来的值发起调用」**。 - -运行期 `src/interp.rs:1119 eval_call` 最终走到 `lookup_function`(`src/interp.rs:1774`), -按名字在 AST 树里查找。 - -### 2.3 对象已经是「表」 - -`src/interp.rs:1509 instance_type_name` 要求 method receiver 是**带 `_type` 键的 Map**: - -``` -error: method receiver needs a map with `_type` -``` - -也就是说 **Marqdo 里「用户定义的结构」本来就是普通 map + 一个标签**。 -对象与表之间没有鸿沟——**这与你的直觉一致,而且已经是既成事实**。 - -但函数不是。对象是值,函数不是。这个不对称值得注意。 - -### 2.4 已存在按名字间接调用:`call_fn` - -`src/interp.rs:1295`: - -```rust -"call_fn" => { - // name 必须是 text - let target = lookup_function(module, fun, name)...; - if !target.params.is_empty() { - return Err("call_fn: `{name}` must have no parameters"); - } - self.run_function(module, target, Env::new(), &[], false) -} -``` - -这是**今天最接近「函数可传递」的机制**,但有三道硬限制:零参、限当前模块、只在运行期校验。 - -### 2.5 六组实验 - -| # | 写法 | 结果 | 结论 | -|---|------|------|------| -| 1 | `**f = > greet**` | `missing argument for parameter who` | `> 名字` 是**调用**语法,**无法引用函数本身** | -| 2 | `> call_fn name="hello"`(无参函数) | `world` | 按名字调用可行 | -| 3 | `> call_fn name="add"`(有参) | `call_fn: `add` must have no parameters` | 不能传参 | -| 4 | 表里存函数名 + `[h](reg)` 取名 + `call_fn` | `dispatch=world` | **动态派发今天就能做**(名字即数据) | -| 5 | `> call_fn name="txt.str_trim"` | `unknown function` | **不能跨模块** | -| 6 | `> call_fn name="no_such_fn"` | `unknown function` | 拼错只能在**运行期**发现 | - -**实验 4 是关键**:它已经是「函数作为表成员」的可用原型,只是把函数表示成**名字字符串**而不是函数值。 - ---- - -## 3. 你的类比中成立的部分 - -必须明确肯定,否则会低估这个想法。 - -### 3.1 「有限域函数 = 表」是完全成立的范式 - -这类函数在工程里非常常见,而且用它表达比写代码更清楚: - -| 场景 | 适合表格 | 为什么 | -|------|---------|--------| -| 税率 / 费率档位 | ✅ | 有限、离散、常改动 | -| 状态机转移表 | ✅ | 二维查表一目了然 | -| 错误码 → 处理动作 | ✅ | 业务方直接维护 | -| 路由分发 | ✅ | 键即路径 | -| 配置映射 | ✅ | 本来就是数据 | - -而且 Marqdo 的 `[键](集合)` 取元**在语义上就是函数应用** —— -前提是这个集合是 **Map**(键→值): - -```markdown -**rate = [2](`税率`)** # 读作:税率(2) -``` - -只要 `税率` 是 Map,这行**无需任何语言改动**就是一个查表函数。你已经拥有它了。 - -唯一的坑是**数据形态要对**:GFM 两列表绑定的是**列映射**(§1.1 实测), -`[2](两列表)` 会报 `missing map key`。所以「表 = 函数」成立, -但**哪种表**有讲究——这正是 §8.1 要补 `table.by_column` / `table.lookup` 的原因。 - -### 3.2 表格对「参数边界」天然友好 - -上一轮讨论 `[函数名](参数)` 时,痛点是参数边界(空格切词)。表格完全绕开这个问题: -键是**显式**的,不需要切词。 - -### 3.3 对象已证明「结构即表」不会损害语言 - -§2.3 说明对象本来就是 map。既然对象能这样,把**数据的**函数化交给表格是自洽的。 - ---- - -## 4. 类比的断裂点 - -三个,每一个都是硬约束。 - -### 4.1 断裂点一:表格是有限的,函数通常是无限的 - -外延观只对**有限定义域**成立。`f(x)=x²+1` 写成表需要无限行。 -所以「函数即表」只能覆盖**查表能解决的那部分**,不能作为函数的通用表示。 - -一旦你承认这一点,「函数即表」就从「函数的定义方式」降级为「一种特殊函数(图表函数)」。 -这仍然有用,**但不是语言的核心函数机制**。 - -### 4.2 断裂点二:函数体是**代码**,不是数据 - -你的草图把「函数体」放进单元格。但函数体在 Marqdo 里是 `Vec<Stmt>`(AST),不是 `Value`。 -要让函数体成为单元格内容,必须先让「代码」成为值——即 `Value::Code` 那种东西。 - -而 `Value::Code` 目前**只表示外联语言源码**(```lang 围栏),是交给外部执行器跑的, -不是 Marqdo 自己的代码。让 Marqdo 代码变成值 = 引入 `eval`,这会带来: - -- 静态检查失效(代码在运行期才成形,`marqdo check` 看不见) -- EKC 指纹失效(§6.2) -- 契约失效(§6.1) - -### 4.3 断裂点三:调用不是取元——`[k](x)` 会被语义重载 - -这是最要命的一条,**与上一轮 `[函数名](参数)` 的冲突同源**。 - -若「函数是表」且「调用 = `[参数](函数表)`」,那么: - -```markdown -[a](m) # m 是普通 Map → 取成员 a -[参数](f) # f 是「函数表」→ 执行?还是取成员「参数」? -``` - -**形状完全一致,含义取决于值的类型**。这正是上一轮我们判定「不可靠消歧」的同一类问题, -只不过从「语法层歧义」升级成了「类型层重载」。 - -Marqdo 的 `[k](coll)` 目前是**唯一且清晰**的取元语义。让它兼职「调用」, -会让最常用的读表操作变得需要思考「这个表是不是函数」。 - ---- - -## 5. 五条设计路径 - -### 路径 A — `Value::Func` 闭包(一等函数) - -```rust -Value::Func(Rc<FuncVal>) // params + body + captured Env -``` - -调用点需支持「对表达式求值后再调用」,即 `CallExpr.callee` 从 `String` 变成 `Callee::Name(String) | Callee::Expr(Expr)`。 - -**代价**: - -| 面 | 影响 | -|----|------| -| 契约(T2.1/T2.2) | `call_arg_diag(c, &target.name, …)` 依赖静态 `target: &Function`;动态调用**拿不到**,契约检查只能退化为运行期 | -| 字节码 | `Op::Call(fid, argc)` 用**编译期函数 id**(`src/bytecode/compile.rs:709`),动态 callee 需要新指令或回退树遍历 | -| EKC 指纹 | `collect_calls` 读 `c.callee`(`src/knowledge/fingerprint.rs:76`),动态调用只剩字面 `call_fn`,**复用/查重能力下降** | -| 序列化 | `value_to_json`(`src/host/json.rs:98`)对 `Value` 穷举,函数值必须定义 JSON 语义(丢弃?报错?) | -| 沙箱 | 函数值无法跨沙箱边界,`sandbox.run` 的接口要加限制 | -| 闭包捕获 | 需要环境快照与生命周期管理;`Env` 目前是每次调用新建(`Env::new()`) | - -**适用于**:确有高阶需求(回调、map/filter、事件处理)。属于**新语言特性**,应走 ADR。 - -### 路径 B — 函数即表(你的草图,强主张) - -**代价**:A 的全部,**外加** §4.3 的语义重载,以及: - -- 表可以 `table.put` 被修改 → 函数可变?还是只读? -- 表可以遍历 → 遍历函数会看到什么?参数名?函数体 AST? -- 表可以 `json.stringify` → 函数体以什么形式序列化? -- 宏展开式的能力(代码即数据)会引入**自修改程序**,与「可静态审计」直接冲突 - -**结论**:**不建议**。它把 Marqdo 从「可静态索引的文档程序」推向「运行期构造的代码」, -是在削弱自己最强的差异点(§6)。 - -### 路径 C — 对象可调用(复用 `_type` + 约定方法) - -让 `# 类名` 实例在 `_type` 之外带一个约定的 `## 应用` 方法,`f(x)` 时若 `f` 是 map 且 `_type` 有该方 -法则走方法调用。 - -**优点**:不新增 `Value` 变体;复用既有 method 机制。 -**缺点**:仍需要「`f(x)` 里 f 是表达式」这一语法能力(同 A 的调用点改造); -且引入「有的 map 可调用」的隐式规则,可读性下降。 - -### 路径 D — 名字即函数(扩展现有 `call_fn`) - -不引入函数值,而是把**名字**这条路径做完整: - -```markdown -> call_fn name="add" args=[1, 2] # 支持传参 -> call_fn name="txt.str_trim" args=[…] # 跨模块路径 -> invoke table=`注册表` key="h" args=[…] # 从表里按名派发 -``` - -**优点**: -- 零值模型改动 → 契约、字节码、指纹、序列化**全部不动** -- 保持「函数永远有名字」→ EKC 能索引,代码可审计 -- 与实验 4 的现有用法完全兼容(只是补齐能力) - -**缺点**:不是真正的一等函数(不能返回闭包);名字拼错仍要运行期发现 -(但**可以**加静态检查:`call_fn name="字面量"` 时校验目标存在——见 §8.2)。 - -### 路径 E — 决策表作为一等公民(**推荐方向**) - -不叫它「函数即表」,而明确它是什么:**有限域查表函数**。 - -```markdown -**税率 = > json.parse text={"1":0.03,"2":0.10}** # Map:键 → 值 -**t = [2](`税率`)** # 今天就能跑 → 0.1 -``` - -**优点**:**零语言改动**,只需文档与库函数支持(例如 `table.lookup` 带默认值, -把 §1.1 配方 B 的「列取 + 索引」四步压成一步)。 -**定位诚实**:它是数据,不是代码;能被 EKC 索引、能序列化、能进沙箱、能被非程序员维护。 - ---- - -## 6. 对 Marqdo 特有机制的冲击面 - -这一节是决策的关键:Marqdo 不是通用语言,它的价值在**可静态索引的工程知识**。 - -### 6.1 契约系统(T2.1 / T2.2) - -现有实现把契约挂在 `Function` 上(`src/ast.rs:71`),并在调用点用**静态 target**校验: - -```rust -if let Some(c) = &target.contract { - if let Some(d) = contract::call_arg_diag(c, &target.name, &bound, …) { … } -} -``` - -动态 callee 拿不到静态 `target`,**契约检查必然退化到运行期**——而契约是 Marqdo -「渐进式契约」卖点的核心。 - -### 6.2 EKC 指纹与复用 - -`collect_calls` 把调用目标名字写进指纹(`src/knowledge/fingerprint.rs:76`)。 -指纹用于**查重、复用预检、相似任务召回**。动态调用使指纹丢失真实目标, -`marqdo duplicate` / `preflight` 的准确率会下降——这直接影响智能体复用飞轮。 - -### 6.3 「函数必须有名字」是特性,不是限制 - -EKC 按符号名索引(`marqdo knowledge` 输出 `59 modules, 346 symbols`)。 -匿名函数/表构造的函数**无法被索引**,也就无法被复用、被审计、被智能体发现。 - -> 对 Marqdo 而言,**函数有名字**不是妥协,而是「代码即文档」的必然: -> 文档里的每一段代码都得有一个可被引用的标题。 - -### 6.4 序列化与沙箱 - -`value_to_json` 穷举所有 `Value`。函数值需要 JSON 语义; -沙箱(CoW + 禁 exec/net/plugin)跨边界传值时,函数**无法表示**。 -一旦函数成为值,`sandbox.run` 的入参约束必须收紧。 - -### 6.5 确定性与可审计 - -表格是**静态可读**的:非程序员能改税率表。代码构造的函数则要求读者在脑中执行程序。 -Marqdo 面向的是「文档作者也能维护」的场景,这一点权重很高。 - ---- - -## 7. 方案对比 - -| 维度 | A 闭包 | B 函数即表 | C 可调用对象 | D 扩展 call_fn | E 决策表 | -|------|--------|-----------|-------------|---------------|----------| -| 值模型改动 | **需新变体** | 需新变体+代码即值 | 无 | **无** | **无** | -| 保持静态可索引 | 部分(匿名不可) | ❌ | ✅ | ✅ | ✅ | -| 契约检查 | **退化** | 退化 | 保持 | 保持 | 保持 | -| EKC 指纹 | 退化 | 退化 | 保持 | 保持 | 保持 | -| 序列化/沙箱 | 需特殊处理 | 需特殊处理 | 保持 | 保持 | 保持 | -| 解决参数边界 | ✅ | ✅ | ✅ | ✅ | ✅ | -| 支持无限定义域 | ✅ | ❌ | ✅ | ✅ | ❌(本质限制) | -| 实现成本 | 高 | 很高 | 中 | **低** | **零** | -| 风险 | 中高 | **高** | 中 | 低 | 无 | - ---- - -## 8. 建议(分阶段) - -### 8.1 立即可做:决策表(路径 E) - -零语言改动。补三件事即可让它好用: - -1. **补库缺口**:新增 `table.lookup map=`key=`default=`(键→值,缺键返回 default)与 - `table.by_column rows=`key_col=`value_col=`key=`(把 §1.1 配方 B 的四步压成一步)。 - **这是当前最实的缺口**——GFM 两列表无法直接键查表,用户会反复手写索引逻辑。 -2. **文档**:在教程里明确「有限域映射怎么表达」,并给出三种形态的取舍: - - 键→值查表 → `json.parse` 的 Map + `[键](map)` - - 需要保留表格可读性 → 两列表 + `table.by_column` - - 缺键行为 → 用 `table.get` / `default=`,避免缺陷 D5 的 `missing map key` 硬崩 -3. **命名**:明确它叫「决策表 / 查表」而不是「函数」——避免与 §1.2 的内涵观混淆。 - -**价值**:把用户已有的直觉固化成推荐用法,不付任何架构代价。 - -### 8.2 短期可做:扩展 `call_fn`(路径 D) - -补齐三件事,都不触及值模型: - -| 补充 | 说明 | -|------|------| -| `args=` | 允许传参,按目标签名绑定 | -| 跨模块路径 | `name="lib.fn"` 走 import 解析 | -| 字面量静态校验 | `call_fn name="字面量"` 在 `check` 期就校验目标存在(消灭实验 6 的类错误) | - -**收益**:动态派发能力完整,且完全保留契约/指纹/序列化。 - -### 8.3 中期评估:一等函数(路径 A) - -只有当出现**确实无法用名字表达**的需求时才做(例如回调、策略模式、事件处理器)。 -届时必须写 ADR,并明确回答: - -- 匿名函数如何进入 EKC 索引?(可能需要要求「赋给变量的函数字面量必须有名字」) -- 契约在动态调用下如何降级? -- 字节码是否引入 `Op::CallValue`? -- 函数值的 JSON 语义是什么? - -### 8.4 不建议:路径 B(函数即表,强主张) - -理由汇总:§4.3 语义重载 + §6 全面削弱静态可索引性 + §5 自修改程序风险。 - ---- - -## 9. 如果你想保留「函数即表」的形态,有一个折中 - -把「表」用于**参数与分发**,而不用于函数体: - -```markdown -`税率表` = - -| 档位 | 税率 | -|------|------| -| 1 | 0.03 | -| 2 | 0.10 | - -## 税率 - + `档位` - -**ks = [档位](`税率表`)** -**vs = [税率](`税率表`)** -**i = > table.index_of list=`ks` item=`档位`** -**r = > table.at xs=`vs` i=`i`** -*r* -``` - -(若 §8.1 的 `table.by_column` 落地,函数体可缩成一行: -`**r = > table.by_column rows=`税率表` key_col="档位" value_col="税率" key=`档位`**`。) - -这里: - -- **数据**在表里(可被非程序员维护、可序列化、可进沙箱、可被 EKC 索引) -- **逻辑**在命名函数里(可契约、可指纹、可审计) -- 调用仍是一等清晰的 `> 税率 档位=2` - -这其实是**最好的分工**:表格承担「知识」,函数承担「行为」。 -它同时满足你的类比直觉(表驱动)和 Marqdo 的静态可索引性。 - ---- - -## 10. 待你决策 - -1. **方向**:选 E(决策表,零改动)、D(扩展 call_fn)、还是 A(一等函数,需 ADR)? -2. 若倾向 D:`args=` 的参数形式用 `[1, 2]`(列表)还是 `a=1 b=2`(具名)? -3. 是否要我把 §9 的「数据在表、逻辑在函数」写成教程规范? -4. 是否存在**具体用例**驱动一等函数?(例如某个 ext 需要回调) - 若有真实用例,评估会完全不同——请给我场景,我按场景重新评估。 diff --git a/doc/design/generated-yaml-manifest.md b/doc/design/generated-yaml-manifest.md deleted file mode 100755 index 67bc290..0000000 --- a/doc/design/generated-yaml-manifest.md +++ /dev/null @@ -1,163 +0,0 @@ -# 设计草案:机器生成的 YAML 清单(OKF 风格) - -| | | -|---|---| -| 状态 | 草案(已采纳方向;修正「配置文件」误解) | -| 日期 | 2026-08-04 | -| 相关 | [OKF 调研](../research/okf-and-marqdo.md) · **实现规范 [okf.md](okf.md)** | -| 取代 | 此前「YAML = 人手写的编译器配置 / frontmatter 契约」的表述 | -| 说明 | 原则仍有效;**类型表、任务知识包、路线图以 [okf.md](okf.md) 为准** | ---- - -## 决策 - -Marqdo 项目中的 **YAML(及由其组成的 OKF 风格知识包)是工具自动生成的产物,不是给人填的配置文件。** - -它的角色接近其它语言里由工具维护的**依赖与包元数据**,例如: - -| 生态 | 类比(职责相近,不是语法相同) | -|------|--------------------------------| -| Rust | `Cargo.toml` / 解析后的依赖图(由源与清单共同推导,工具可改写) | -| Python | `requirements.txt`(常由解析/冻结生成) | -| Go | `go.mod` + `go.sum`(`go mod tidy` 维护) | - -我们选择 **OKF 的形态**(Markdown + YAML frontmatter 的概念目录)来承载这份生成结果,从而一举两得: - -1. **给编译器 / 包管理**:依赖图、模块身份、导出符号、版本锁定等可查询元数据 -2. **给本项目文档**:同一份生成物可直接渲染为「项目知识目录」——模块说明、依赖关系、API 索引等**自动生成本项目文档内容** - -**唯一手写真相**仍是 `.mq.md` 源文件正文。YAML 清单是派生工件;过时则重新生成,禁止当成第二套权威配置去手改(除非工具链明确支持的「生成后微调」流程,且须可复现)。 - -**与源 frontmatter 的分工**(见 [markdown-mapping.md](markdown-mapping.md)):源文件 `---` 块可含 `title` 等元信息,以及人手声明的跨文件导入行 `import other:other.mq.md`。那是**源上的导入声明**,不是工程依赖锁。工具仍应据此(及正文 `>` 调用)**生成** OKF 风格依赖/模块目录;不要把生成目录手改成权威。 - ---- - -## 纠正:它不是什么 - -| ❌ 不是 | ✅ 是 | -|--------|------| -| 人手维护的 `run` / `target` / 路径配置 | 从源码 **推导** 出的依赖与模块元数据 | -| 编译器「怎么跑」的 ini/配置替代品 | 解析、链接、文档站共用的 **生成清单** | -| 与正文平行的第二套程序描述 | 正文的 **投影**(projection):结构化、可查询、可渲染 | - -执行方式(解释 / 检查 / 编译到某后端)由 **CLI、子命令或工程约定** 决定,不塞进这份 YAML 让人配置。 - ---- - -## 数据流 - -``` -手写 .mq.md 源 - (叙事 + 类型 + 函数 + 正文中的引用/导入) - │ - ▼ - marqdo 工具链 - · 解析正文 AST - · 收集 import / 链接 / 导出 - · 解析依赖、锁定版本 - │ - ├──────────────────────────────┐ - ▼ ▼ - 生成 OKF 风格清单 编译 / 类型检查 / 运行 - (YAML + 概念 Markdown) (消费清单加速解析) - │ - ▼ - 自动生成本项目文档 - (模块索引、依赖图、API 目录……) -``` - -- **源 → 清单**:单向派生;清单不得反向成为「唯一写依赖的地方」。 -- **清单 → 文档**:OKF 包本身即可浏览;也可再生成站点/目录页。 -- **清单 → 编译**:编译器可读生成结果以跳过重复发现,但语义仍以源为准;清单缺失时应能从源重建。 - ---- - -## 生成物长什么样(示意) - -工程在构建或 `marqdo sync` 类命令后,可得到类似 OKF bundle 的目录(路径未定): - -``` -.marqdo/ # 或 docs/catalog/ 等 — 待 ADR - index.md # 生成:项目总览 - modules/ - cart.md # 生成:每个模块一个概念文档 - prelude-list.md - deps/ - lock.yaml # 生成:依赖锁定(机器向) -``` - -单个生成的概念文件可呈 OKF 形: - -```yaml ---- -type: Marqdo Module # 生成 -title: cart -description: 购物车:行项目与总额 -resource: src/cart.mq.md # 指向源文件 -depends: - - prelude/list - - math/sum -exports: [Line, total] -generated: - by: "marqdo/0.1" - at: 2026-08-04T01:00:00Z ---- - -# cart - -> 本页由 Marqdo 工具链根据 [`src/cart.mq.md`](../../src/cart.mq.md) **自动生成**,请勿手改。 - -## 依赖 - -- [prelude/list](../modules/prelude-list.md) -- [math/sum](../modules/math-sum.md) - -## 导出 - -| 符号 | 种类 | -|------|------| -| `Line` | type | -| `total` | fn | -``` - -人要改行为或说明 → 改 `src/cart.mq.md`;再生成,文档与依赖清单一起更新。 - ---- - -## 与「代码即文档」的关系 - -Marqdo 有两层「文档」,不要混为一谈: - -| 层 | 谁写 | 是什么 | -|----|------|--------| -| **源文档** | 人(及协助编写的 Agent) | `.mq.md`:程序本身,打开即读、即可跑 | -| **项目目录文档** | 机器 | OKF 风格 YAML/Markdown:从全项目源 **汇总** 的依赖、模块图、索引 | - -前者消灭「实现与说明漂移」;后者消灭「仓库级总览靠手维护 README 目录」——总览从源自动长出,格式还对 Agent / 搜索友好(OKF)。 - ---- - -## 原则 - -1. **源为唯一权威** — 依赖与导出以 `.mq.md` 正文中的语言构造为准;YAML 是提取结果。 -2. **生成、可复现** — 同一源树 + 同一工具版本 → 同一清单(允许时间戳等字段除外或规范化)。 -3. **勿手改生成物** — 生成文件应带头注释或 `generated` 字段;CI 可校验「未提交脏生成」或「提交的生成与源一致」。 -4. **OKF 形、Marqdo 义** — 文件形态对齐 OKF(`type`、链接、目录),词汇服务模块/依赖/导出,而不是照搬 BigQuery 概念类型。 -5. **清单可删可再生** — 没有清单时,编译器仍须能直接从源工作(可能更慢);清单是缓存与文档面,不是语言语义的一部分。 - ---- - -## 待决问题(后续 ADR) - -- [x] 生成物默认路径:`.marqdo/`(`-o` 可改)— 见 [catalog-cli.md](catalog-cli.md) -- [x] `marqdo catalog` / `sync`;静态用户文档:`marqdo view output` — 见 [view.md](view.md) -- [ ] 是否提交生成物进 git(项目自定;CI 可校验干净生成) -- [ ] 与「可手写包身份 name/version」的边界 -- [ ] 是否沿用 OKF v0.2 的 `sources` 等溯源字段 - ---- - -## 结论 - -**YAML(OKF 风格清单)= 机器从 `.mq.md` 自动生成的依赖与项目元数据,并可据此自动生成本项目文档;不是人手填写的配置文件。** -人写源,工具写清单与目录文档;编译器与文档站共同消费生成物,语义始终回到源。 diff --git a/doc/design/isolated-web-runtime-development-2026-10-26.md b/doc/design/isolated-web-runtime-development-2026-10-26.md deleted file mode 100755 index 15afe16..0000000 --- a/doc/design/isolated-web-runtime-development-2026-10-26.md +++ /dev/null @@ -1,326 +0,0 @@ -# 隔离执行与响应式 Web 运行时:详细开发设计 - -| 项目 | 约定 | -|---|---| -| 状态 | **Verified**(execute 路径);HTTP `execute` / `sse-live` / `stream:true` 默认走 Supervisor worker 池(不再经父进程 `CallLibPath` / `INVOKE_LOCK`);`runtime.isolated_execution=1`;MR-01 金样例 `tests/isolated_execute_mr01.rs`;未声明非流式仍 `legacy_serial`(ADR 0008) | -| 基线 | Marqdo `1b11fe0` / 2.1.3;qdagent `64b97e5`;2026-10-26 | -| 问题依据 | [单解释器缺陷](web-invoke-serialization.md)、[ADR 0008](../adr/0008-web-invoke-serialization.md)、[本轮跨库复核 R01–R14](../../../qdagent/doc/gaps/04-workbench-runtime-and-product-audit-2026-10-26.md) | -| 产品配套 | [qdagent 可靠工作台开发设计](../../../qdagent/doc/design/reliable-workbench-development-2026-10-26.md) | -| 继承合同 | [工作台 M00–M06](qdagent-workbench-runtime-and-view-2026-10-25.md) 中 ModelSelection、ModelSnapshot、Usage、DocumentView、Locator;保留文档原生作者面 | - -## 1. 目标、边界与不变量 - -目标是让用户在长对话、导入和构建过程中持续打开模型列表、读取来源、修改下一轮设置并可靠停止任务。高并发容量按资源预算显式限制;不能让所有请求进入一把解释器锁再超时。 - -Marqdo 负责通用执行隔离、资源调度、事件/取消、语义分析和制品校验。qdagent 负责用户/工作区授权、业务状态与发布政策。产品仍通过 `.mq.md` 调用 Marqdo Agent,不增加第二套模型循环或知识编译器。 - -必须保持的系统不变量: - -1. 同一个可变 HostContext 同时最多一个求值者;不删除锁、不增加虚假的 `unsafe impl Sync` 来获得并行。 -2. 一个执行租约只属于一个 run/attempt;凭证、事件、取消、cwd、权限和模型选择不可流入另一请求。 -3. 控制与读取具有独立容量,不被 LLM 等待占满;停止不需要重新进入正在执行的解释器。 -4. 事件可以重投,外部副作用不默认重做;不宣称跨网络 exactly-once。 -5. 已确认终态不能被晚到完成/取消覆盖;取消不回滚已经完成的外部写入。 -6. 阅读不执行 `.mq.md`,缓存不绕过授权或版本校验;缓存命中必须实际复用结果。 -7. 正文、依赖、证据和编译代属于同一不可变快照;不会把两个代的结果拼成一次阅读或执行。 -8. 任何能力开关都以实际探测和测试为依据;新 API/schema 在落地前都属于本文提案。 - -## 2. 架构选择 - -| 方案 | 优点 | 当前代价 | 本轮选择 | -|---|---|---|---| -| 继续全局锁,只增加 Go handler | 改动小 | 长任务依然阻塞所有 Endpoint,串扰变量也未消失 | 只保留作兼容模式 | -| 同进程多 HostContext | 潜在内存复用较好 | GLOBAL_HOST、插件回调、环境、cwd、事件 sink 生命周期需系统重做 | 后续优化,不是首个交付门槛 | -| 独立 Marqdo worker 进程 + 控制/读取通道 | 隔离现有全局状态,可强制回收卡死任务,复用现有语言与 Agent | IPC、进程启动、内存、发布写协调 | **首选实现** | -| 引入外部通用队列和新业务 Runtime | 容易扩到集群 | 运维复杂度及第二套编排风险 | 单机阶段不引入 | - -首期采用**预热的一次性执行进程池**:进程可预装运行时和非用户特定模块,分配任务后独占,结束即退出并异步补充。这样不用假设清空部分字段就能安全复用 HostContext。长寿命多租约 worker 只有通过状态泄漏、插件资源与 RSS 回归后才开启。只读分析服务可以长寿命运行,但不得加载有副作用的求值插件。 - -```mermaid -flowchart TD - UI[浏览器 / CLI / MCP] --> WEB[Go HTTP / 认证入口 / 限流] - WEB --> CTRL[任务控制与事件服务] - WEB --> SHORT[短业务请求容量] - WEB --> READ[只读分析服务] - SHORT --> POLICY[qdagent .mq.md 授权与业务规则] - POLICY --> CTRL - CTRL --> DB[(任务索引 / outbox / 事件日志)] - CTRL --> SUP[Rust Supervisor / 有界调度] - SUP --> A[Marqdo worker A / 一个租约] - SUP --> B[Marqdo worker B / 一个租约] - A --> AGENT[既有 Marqdo Agent / LLM / sandbox] - B --> AGENT - A --> STAGE[每任务暂存目录] - B --> STAGE - STAGE --> COMMIT[按资源串行提交与 revision CAS] - COMMIT --> SNAP[(不可变知识代 / 发布 manifest)] - READ --> SNAP - A --> CTRL - B --> CTRL - CTRL --> UI -``` - -“短业务请求容量”依旧可执行产品 `.mq.md`,但有独立 worker 预算和短 deadline。控制服务只做通用接纳、状态 CAS、取消与日志投递,不把模型选型、知识晋升等业务逻辑搬进 Go。读取服务接收经过授权的资源句柄;不得直接相信浏览器提交的绝对路径。 - -## 3. 路由分类与接纳 - -### 3.1 执行类别 - -在 Endpoint 装配中新增可选 metadata(字段名待 schema 固定): - -| 类别 | 示例 | 资源预算与规则 | -|---|---|---| -| `control` | 任务查询、事件订阅、取消、health | 不执行用户代码;认证后访问任务存储/租约注册表 | -| `read` | view.document、引用解析、已发布模型列表投影 | 只读快照;不写用户源码;可缓存 | -| `short` | 保存设置、创建导入、接纳任务 | 无 LLM 长等待;默认 deadline 2s,较慢动作转为任务 | -| `execute` | ASK/BUILD/生成/验证 | 有界队列、专属进程、显式任务 deadline | -| `commit` | 切换知识代、合并受控文件变更 | 按 workspace/kb 的短临界区;执行前检查 revision | - -旧 Endpoint 未声明时仍走 legacy_serial;不能自动猜测任意函数是纯读。纯度来自静态能力和注册配置,实际写权限仍由宿主限制。文件上传字节传输不占解释器,应先落隔离存储,再进入短接纳路径。 - -### 3.2 接纳步骤 - -1. HTTP 层解析受限请求,验证身份、格式、速率与连接数量。 -2. 产品短入口解析 workspace/model/policy;授权版本与模型配置 revision 一并冻结。返回规范化任务请求,不执行 Agent。 -3. 控制服务在同一数据库事务中登记作用域化 idempotency key、payload hash、task 和 dispatch outbox;重复请求读回已有 task,同键异内容返回 409。 -4. 提交事务后才返回 202/Location。调度器消费 outbox 分配租约,租约带 attempt/epoch。 -5. 对同步兼容 API,先完成接纳,再挂接结果;等待客户端超时不等于安全重做。 - -队列入库前容量不足返回 429 + Retry-After;服务不可用返回 503;接纳失败不发送 started。控制通道须保留槽位,不能因为数据流连接占满而无法取消。 - -## 4. Supervisor、生命周期与调度 - -### 4.1 Worker 生命周期 - -`starting → ready → leased → running → draining → exited`;启动失败/心跳丢失走 `unhealthy → terminating → exited`。任务状态由控制服务维护,进程状态不能直接当作业务成功。 - -- worker 启动握手报告 CLI/ext/native、protocol_version、能力、构建摘要;不匹配不进入 ready。 -- 预热阶段不读取用户凭证、不挂载工作区写权限。分配租约后挂载当前任务的 capability roots、只读快照和独立 staging。 -- 每任务具有随机 lease_id、run_id、attempt_id、epoch、绝对 deadline 和资源限制。 -- Supervisor 持有进程句柄、子进程组、事件通道与取消句柄。worker 不能自行修改其他 worker 状态。 -- 返回业务结果后仍须 drain 事件/用量并提交最终 checkpoint,控制服务持久化终态后确认 ACK,之后释放租约。 -- 超时或断连清理不能遗留孤儿子任务;正常优雅退出后再删除临时文件。异常由独立 janitor 按租约过期回收。 - -### 4.2 有界、公平与资源预算 - -初始验证配置建议 4 vCPU/8 GiB、执行槽 2、短请求槽 1、读取服务 1。具体容量由每类任务的 RSS p95 和 CPU profile 决定,不能把这个数当所有机器的默认。执行槽上限: - -`min(CPU约束, floor((可用内存 - 系统/控制/缓存预留) / worker_RSS_p95))`。 - -运行队列按 workspace 轮转,再按 session FIFO;一个 session 默认只允许一个活动 turn,跨 session 可并行。相同知识库的生成可并行,发布只占短提交锁。interactive 优先于后台索引,但后台使用老化提升或最低服务配额,防永久饥饿。 - -全局队列初始上限 64、单工作区 16、单会话待处理 4,均可配置;队列超限及时返回,不能悄悄丢任务。显示队列位置或“前方有任务”,没有可靠完成时间估计时不显示虚构倒计时。 - -### 4.3 副作用与重试 - -任务声明 `read_only / staged_write / external_effect`,由工具权限校验而非模型自报。read_only 可按政策重试;staged_write 丢弃未提交 staging 后重试;external_effect 出现超时/失联时标记 `effect_unknown`,等待核对,不自动重复支付、发信或写入。 - -稳定的操作键使用 `task_id + logical_step_id`,attempt_id 只标记传输尝试,不应导致同一外部动作生成新的去重键。工具不支持幂等查询时,只能明确报告不确定。工作簿记录已完成与未知副作用;“已停止”不意味着“全部撤销”。 - -## 5. IPC 与请求上下文 - -首期使用本机 Unix socket 或匿名管道,采用长度前缀 JSON 控制帧与独立事件通道。协议禁止无上限 JSON/单行日志;控制帧初始上限 1 MiB,大文档通过授权 blob handle 传递。普通 stdout/stderr 仅诊断,不与协议混流。当前 NDJSON 文件桥保留为 legacy fallback。 - -新增 `InvokeRequestV2` 示例(提案): - -```json -{ - "schema": "InvokeRequestV2", - "schema_version": 2, - "task_id": "task_01", - "run_id": "run_01", - "attempt_id": "attempt_01", - "lease": {"id": "lease_01", "epoch": 3}, - "entry": {"module": "agent/qdagent.mq.md", "function": "run"}, - "args_ref": "blob:sha256:...", - "context": { - "workspace_id": "ws_01", - "snapshot_id": "generation_01", - "selection_ref": "model-snapshot_01", - "capabilities_ref": "grant_01", - "deadline_at": "2026-10-26T08:10:00Z" - } -} -``` - -`grant_01` 是服务端验证的短寿命授权句柄,内容包括 principal、scope、根目录、允许效应、授权 revision、失效时间。worker 不使用浏览器任意传入的 fn/path。权限撤回后,新的工具调用必须重新验证 lease/grant,已开始的外部调用记录撤回时间与实际结果。 - -`RunContextV1` 保留原有字段与序列化兼容,内部增补显式 Context 对象;扩展 V2 由能力协商启用。event_sink、usage_sink、cancel_token 使用句柄,不使用外部可控路径。子任务通过 IPC/Command.env 显式继承,禁止父进程 `setenv`/`set_current_dir` 承担请求状态。 - -凭证在租约启动时通过受保护 IPC 或继承 FD 注入;不落任务 JSON、argv、日志或通用事件。模型快照可含 credential_ref,不含 api_key。即使选择相同 provider,不同请求的授权也不得合并。 - -## 6. 取消协议与状态 CAS - -任务基础状态:`accepted → queued → running → finalizing → succeeded/failed`;queued/running 可进入 `cancel_requested → cancelled`;worker 失联进入 `interrupted`,副作用不明时进入 `needs_reconciliation`。这些是提案,产品可以将 succeeded 映射为 completed。 - -取消顺序: - -1. 验证调用者对 task 的权限,CAS 写 cancel_requested、revision 与 requested_at;终态返回原状态,未知 ID 返回 404。 -2. 向匹配 lease/epoch 的控制通道发送 Cancel;不经任务解释器锁。queued 任务原子移出待派发队列。 -3. worker 在每次 LLM/工具调用、重试、子任务启动和提交之前检查 token;网络请求使用可中断句柄,不能仅在一行输出结束后才检查。 -4. 收到 ACK 仍不等于任务停止。等待 worker 报 stopped、落未完成副作用和用量,再 CAS 到 cancelled。 -5. 默认 2s 协作宽限、额外 3s 进程退出宽限,之后回收进程组。强制退出记 interrupted/needs_reconciliation,不能伪造干净 cancelled。 - -完成与取消竞争的线性化点是控制存储的 CAS:终态先提交则 cancel 返回 already_terminal;取消先提交则晚到 result 只可作为证据追加,不能重新变 succeeded。若外部动作已发生但响应晚到,记录 effect outcome,不撤销取消事实。 - -兼容文件 token 统一:不存在/空/`0` 为未取消,`1`/`cancelled` 为取消;读取失败返回诊断并按明确策略处理。删除 token 只能发生在持有者退出之后。移除全局 `MARQDO_CANCEL` 对多个任务的隐式作用域。 - -## 7. 事件、SSE 与背压 - -### 7.1 事件权威 - -生产者发出 `(run_id, attempt_id, local_seq)`,控制服务去重、持久化并分配 task 内单调 seq/event_id;客户端游标来自持久化日志,不是 handler 重连后从 1 开始计数。终态事件唯一,usage 可以在终态后以更高 usage revision 补录,但不能再次结束任务。 - -```json -{ - "schema": "RuntimeEventV2", - "schema_version": 2, - "event_id": "task_01:42", - "seq": 42, - "task_id": "task_01", - "run_id": "run_01", - "attempt_id": "attempt_01", - "type": "message.delta", - "payload": {"message_id": "msg_01", "offset": 24, "text": "结果"} -} -``` - -不要直接破坏 RuntimeEventV1;新增字段/新版本由能力协商确定。普通用户可见 progress 只描述工具、阶段、文件等结构化事实;模型内部 reasoning 不作为完成证据,也不默认写入公开事件。 - -### 7.2 App SSE - -新增任务 API 的事件订阅用 `GET /tasks/{id}/events`(最终产品前缀见配套设计),发送 SSE `id`/`event`/`data`;每个 data 是一个完整 JSON。客户端支持 Last-Event-ID、CRLF、多行 data、任意 UTF-8 分块和 EOF 未完成帧。重复事件按 ID 去重;message offset 检查缺口,缺口时恢复快照。 - -心跳 15s,客户端空闲探测建议 45s;二者可配置。事件保留建议 24h,最终结果/审计按项目政策更长保留。游标早于保留边界返回 410 `event.cursor_expired` 和快照入口,不能默默从最新开始丢字。 - -订阅断开默认只关闭订阅。App 显式停止通过 cancel API,切页/移动网络重连可恢复同一任务。传统同步 OpenAI 调用可保持 disconnect=cancel 的兼容策略,但必须显式区分,不能统一把所有浏览器断流当取消。 - -### 7.3 OpenAI 兼容流 - -`/v1/chat/completions stream=true` 输出 OpenAI chunk 与 `[DONE]`;App 运行事件由独立入口或协商的协议提供。禁止仅凭任意 JSON body 中 stream=true 将不相关路由自动改为 RuntimeEvent 协议。已发 header 后的错误使用该协议允许的错误帧;发 header 前可用 429/503/401 等正确状态码。 - -token delta 与最终完整答复分开:最终事件持有结果引用/摘要和 finish reason,不再次追加整篇正文。无 token 能力的适配器报告 `evented_batch`,界面用阶段状态,不把整包人为拆字伪装成实时。 - -### 7.4 背压和旧桥修复 - -worker→事件服务与服务→订阅者均有界。建议每订阅者 256 KiB 待发送内存,超出后断开慢消费者并允许按游标重连;事件正文已持久化所以不能静默丢 token。允许合并短时间 delta,必须保留 message offset;usage/终态/错误不丢弃。磁盘压力时停止接纳新任务,已有任务使用保留终态空间并按策略中断,不能无限写事件。 - -legacy NDJSON tailer 只消费换行已完整到达的字节;保留残片,offset 按真实消费字节移动。超长行、I/O error、文件旋转显式报协议错误。测试至少分三次写一个 JSON、中文多字节边界、恰好 EOF、超过上限、取消与尾帧竞争。禁止吞掉 Scanner.Err() 继续宣告成功。 - -## 8. 只读快照与真正有效的缓存 - -### 8.1 快照一致性 - -分析服务构建 SnapshotKey:规范化 project identity、允许扫描范围、源文件闭包摘要、依赖/来源/配置摘要、compiler/lib/ext 版本、policy/schema、解析选项。输入由编译器枚举,不另造“前 200 个根目录文件”规则。 - -读取一次快照内的正文、语义和来源,完成后复核输入 manifest;文件在分析中发生变化则重试一次或返回 `snapshot.changed`。对不可变发布代直接读其 manifest。mtime/size 只用于快速发现候选变更,不能代替内容摘要;watcher 丢事件后以完整扫描修复。 - -### 8.2 缓存结构 - -- `AnalysisCache<SnapshotKey, Arc<Compilation>>`:实际编译结果。 -- `DocumentCache<(SnapshotKey, document_digest, renderer_version, view_options), DocumentView>`:安全 fragment、outline、nodes。 -- 同 key single-flight 的 follower 等待同一个 Result,不再次 compile。 -- RAII guard 在 error/panic/cancel 时清除 inflight 并唤醒 waiters;等待者有自己的 deadline。 -- compile 失败只返回给当前等待者,短暂错误缓存需显式 TTL;不得调用“finish_success”标记失败结果可复用。 -- LRU 按字节而非条数上限管理;初始预算按部署内存的 10% 且设硬上限,长文档超限不缓存或分页;记录淘汰原因。 -- 每次读取先授权再查缓存;权限敏感的响应按 scope/policy 分区。全局缓存只共享不含用户秘密且访问已验证的不可变语义数据。 - -性能证据必须统计 `compile_invocations`、输入字节、缓存结果命中、leader/follower、wait_ms、evictions;现有 hit counter 不能证明减少编译。 - -### 8.3 HTML 与来源定位 - -沿用 DocumentViewV1,明确 `render.format=plain_text|sanitized_html`。HTML 通过解析器白名单清洗标签/属性/URL scheme,剥离脚本、事件属性、危险 CSS/嵌入与可执行 SVG;相对资源经受限资源端点解析。纯文本始终转义,不以 `<` 字符判断类型。 - -node_id、revision、generation 必须从定位到读取到浏览器滚动完整传递。不存在历史快照返回 version_unavailable;返回当前版是用户显式操作且标明版本变化。no_exec 测试分别验证“无语言副作用”和“浏览器无脚本执行”,二者不能互相替代。 - -### 8.4 首次编译的性能改造 - -本轮 `v3_corpus_1000_compile_smoke` 在 debug 下 243.012s,超过既有 180s 门禁;缓存不能缩短一个全新项目的第一次编译。先为 `knowledge::compile` 的语义编译、语义落盘、检索 extract、检索落盘、manifest 分别加 span,再细分 `ProjectIndex::build`、源枚举/解析、导入挂接、绑定、效应传播、闭包摘要。记录文件数/总字节、节点/边数、parse 次数与序列化字节量。 - -源码中 `sema::compile_project` 在每个文件查找 module path、每个 module 过滤全量 symbols,属于值得测量的重复扫描;未取得 profile 前不将其认定为 243s 的唯一根因。优化候选按证据选择:建立 path→module 与 module→symbols 索引;同一输入快照共享 parsed module;绑定/依赖图用稳定索引;效应传播用 worklist;闭包按 SCC DAG 计算并保留循环依赖语义;减少每制品重复序列化和小文件写入。 - -任何优化须保持排序确定性、SymbolId/ArtifactId 与证据摘要规则,禁止通过跳过来源校验、删掉复杂 fixture 或改大超时过关。用 100/1000/10000 单元、无依赖/链/菱形/循环四种图分别测时间与 RSS;给出随 V/E 增长的曲线。release 和 debug 分开;已有 debug 门禁恢复通过只是第一步,§12 的 release 预算仍须独立验收。 - -## 9. 写入、发布与数据库边界 - -执行 worker 只写任务 staging;需要写工程时通过沙箱产生文件 diff。发布以 kb 资源锁 + expected_generation CAS 提交。锁只覆盖校验当前版本和切换 manifest,不覆盖 LLM、全文编译或网络调用。 - -完整发布代先写临时目录、校验摘要、完成必要 fsync,再原子 rename 到不可变 generation 目录;最后在同一文件系统原子替换 CURRENT。源码、编译投影和证据在该 manifest 下对齐。SQLite 中的产品“published”是投影,不参与虚构的文件/数据库跨系统原子事务。通过 publish journal + outbox 恢复:CURRENT 已切换但 DB 未更新时重放;未切换时旧代继续有效。 - -project_id 与逻辑文档 ID 不随 staging/generation 的物理目录名变化。manifest 保存稳定 project identity、逻辑相对路径和实际 blob/generation 映射;导入引用按项目规则解析,不能因复制到发布目录而重新生成全部符号身份。框架若尚不能区分逻辑身份与物理根,先补该能力,再启用 generation 目录发布;迁移 fixture 必须断言未修改的知识 ID 和跨文档绑定保持稳定。 - -任务表/幂等/CAS/outbox 需要通用事务能力:先审计 `ext/data` 是否支持事务、条件更新、受影响行数、复合唯一键;缺少则在 Marqdo 数据层补齐,不能用 `.mq.md` 的先读后写模拟原子性。SQLite 使用短事务和有界 busy timeout;WAL/连接池是否开启需按现有插件适配测试确认。单主本地盘为首期部署范围,跨主机共享 SQLite/NFS 不在首期承诺内。 - -## 10. 临时缓解与迁移 - -### 10.1 进程池完成前 - -- 保留 1500ms busy 预算和 Retry-After;展示繁忙,而非无限 spinner。 -- 在接纳任何 SSE 之前取得覆盖整个 bridge 生命周期的 legacy 单飞许可,第二条流在修改环境变量/发送 200 前失败;普通请求不得绕过许可观察被污染的状态。 -- 断连只标记该任务取消,清理由监督者等待执行结束后负责;无法确认停止时报告 stopping/interrupted。 -- 上述步骤只降低 R02/R03 风险,仍不算并行 Endpoint。 - -### 10.2 功能开关(新增提案) - -`runtime.isolated_execution`、`runtime.task_control_v2`、`runtime.event_replay`、`view.analysis_cache_v2`、`runtime.read_lane`。探测返回 feature version 和限制。二进制版本相同不等于所有 native 插件都有该能力。 - -先离线 fixture → 本地假模型 → 新 workspace → 只读 ASK → staging BUILD → 真正发布。禁止对有副作用的请求做双执行 shadow;允许 shadow 只读分析并比较摘要。 - -回滚先停接新任务、drain 已接纳任务、保留任务/事件和新 schema;不能将活动任务交给不认识 lease 的旧进程。只读当前发布代可以保留,写入能力按版本协商关闭。ADR 0008 仅在并行金样例与回滚演练通过后由新 ADR 正式替代。 - -## 11. 开发包与依赖 - -下列新模块路径是建议,不代表文件已存在。 - -| 包 | 建议落点与改动 | 前置 | 验收 | -|---|---|---|---| -| M-R0 基线/缓解 | `host/plugin.rs`、`httpx/routes_invoke.go`;固定并发屏障、旧桥许可、取消清理 | 无 | 双流 busy 不改写 A 的桥;断连无提前清理 | -| M-R1 请求上下文 | `workbench/run_context.rs`、`host/subtask.rs`、LLM 插件;统一 token 与显式 sink | M-R0 | 父子运行模型/事件/取消不串;空 token 不取消 | -| M-R2 Worker/IPC | 新 `runtime/{supervisor,worker,protocol,lease}.rs`;独立进程与握手 | M-R1 | 两任务并行、超时回收、子进程无孤儿 | -| M-R3 接纳/控制 | 新 `runtime/{task_store,scheduler,control}.rs` 与 ext/data 事务 primitives | M-R2 | 原子幂等、队列公平、取消与结果 CAS | -| M-R4 事件协议 | `workbench/event_sink.rs`、Web stream/IPC、协议适配器 | M-R3 | 断点恢复/去重/半帧/慢消费/磁盘错误 | -| M-R5 读服务/缓存 | `analysis_cache.rs`、`document_view.rs`、`locator.rs`、MLSP transport | M-R1,可独立推进 | 100 同 key 真正只编译一次;嵌套变更正确失效 | -| M-R5b 首次编译性能 | `knowledge/compile.rs`、`sema/ir.rs`、ProjectIndex;分阶段 profile 与按热点优化 | 基线语义回归 | 现有 1000 单元门禁恢复;release 与规模曲线报告,身份和语义不变 | -| M-R6 提交底座 | `knowledge` generation/manifest、publish journal、条件更新 | M-R3 | 崩溃点恢复,旧代不被半发布污染 | -| M-R7 整合与发布 | 版本探测、CI、release、文档/ADR | M-R4–R6 + 产品接入 | §12 全部必要门禁与回滚演练 | - -先以本地文件和单机进程解决明确缺陷;不要把集群、远程 worker、复杂 Actor 系统设为第一阶段依赖。 - -## 12. 验收、性能预算与可观测性 - -### 12.1 正确性矩阵 - -| 编号 | 场景 | 必须观察到的结果 | -|---|---|---| -| MR-01 | A/B 两个 60s 假模型流 + 20 次/s 模型/设置读取 | 两流不混字、不混模型;短请求 200;无 interpreter busy | -| MR-02 | B 在 A 运行时接纳失败/断连 | A 事件和取消句柄完全不变 | -| MR-03 | 同时取消 A、完成 B;取消重复/晚到 | A 正确停;B 成功;终态不回退;审计只结算一次 | -| MR-04 | 帧拆字节、多行、EOF 半帧、重连 | 无丢字/重字;协议错误可见;游标恢复精确 | -| MR-05 | 慢消费者、磁盘满、worker 崩溃 | 内存有界;事件不静默丢失;状态可恢复 | -| MR-06 | 100 个相同读取并发 | 实际编译一次;后续结果复用;失败 leader 不挂死 follower | -| MR-07 | 改子目录依赖、第 201 个文件、配置、来源 | SnapshotKey 改变;缓存失效;旧业务句柄拒绝 | -| MR-08 | 上传有写文件/网络代码、HTML 事件属性 | 阅读不求值;浏览器脚本不执行;正文可读 | -| MR-09 | 发布每个持久化边界 kill | 仅旧完整代或新完整代可见;DB 投影最终追上 | -| MR-10 | 并发幂等请求、取消队列、权限撤回 | 单一 task;同键异内容 409;无越权派发 | -| MR-11 | kill 后副作用未知 | 不自动重放,显示 needs_reconciliation | -| MR-12 | 降级/升级、混合 CLI/ext/native | 缺能力明确禁用,不报已支持 | - -### 12.2 性能目标(待测验收预算) - -基准机:Linux 4 vCPU/8 GiB SSD;release 构建;1000 个知识单元、文档总量 10 MiB、500 条历史 run;假上游固定 60s、每秒 20 个增量;30s 预热、5min 采样、3 轮,报告 p50/p95/p99、错误率、CPU、RSS、磁盘。另测 10k 单元和 100 MiB 以确定容量上限,不能直接沿用小数据阈值。 - -| 指标 | 初始预算 | 说明 | -|---|---|---| -| 短读/任务接纳 | p95 ≤200ms,p99 ≤500ms | 两个长任务运行时;过载拒绝另统计 | -| 取消受理 | p95 ≤200ms | 独立于任务停止耗时 | -| 协作取消收敛 | p95 ≤2s | 假上游/可中断工具;不可中断外部动作按不确定处理 | -| 已就绪 worker 调度 | p95 ≤100ms | 不含排队、模型首 token 时间 | -| 事件到订阅者新增延迟 | p95 ≤100ms | 从已收到 provider delta 计,不承诺上游 TTFT | -| 1000 单元首次分析 | p95 ≤2s | 候选目标,超标先剖析,不降低正确性 | -| 热 DocumentView | p95 ≤100ms | 真实复用结果;长文档另测分页 | -| 慢消费者缓冲 | 每订阅 ≤256 KiB | 总连接数也必须受限 | -| 压测结束内存 | 稳态可回收、无持续增长 | 记录每次重复轮次 RSS;不能只看一次峰值 | - -新指标至少有 queue_depth/wait、worker_active/recycle、admission_rejected、cancel_ack/stop、orphan_count、event_lag/replay/duplicate、compile_invocations/cache_result_hit、publish_conflict/recovery。指标标签禁止 task_id、原始路径、prompt 等高基数/敏感值;trace 中可记录脱敏 task/attempt/lease 与构建摘要。 - -现有测试继续保留:`cargo test --offline --locked --test workbench_contracts --test executable_knowledge`、LLM 插件单测、Go httpx 测试。新增集成门禁必须启动真实 HTTP→IPC→worker 路径并使用本地假模型;不能以手写 fixture 或写 token 文件代替端到端行为。本轮执行结果统一记录在[跨库复核 §5](../../../qdagent/doc/gaps/04-workbench-runtime-and-product-audit-2026-10-26.md)。 diff --git a/doc/design/keywords-i18n.md b/doc/design/keywords-i18n.md deleted file mode 100755 index d2cf329..0000000 --- a/doc/design/keywords-i18n.md +++ /dev/null @@ -1,137 +0,0 @@ -# 内置关键字 / 函数:中英双名(草案) - -| | | -|---|---| -| 状态 | **已定(已实现)** | -| 日期 | 2026-08-05 | -| 原则 | **无需导入**;中英为**同一语义的别名**,不是语言模式开关 | -| 相关 | [keywords.md](keywords.md) · [stdlib-i18n.md](stdlib-i18n.md) · [call-arguments.md](call-arguments.md) | - ---- - -## 1. 动机 - -Marqdo 要中英文都能自然书写。标准库已约定「**库文件名区分语言**」(见 [stdlib-i18n.md](stdlib-i18n.md));对**不必导入**的一层——字面量关键字与极少内置函数——也要对等提供中文名。 - -正因为每增加一个内置名,就要同时维护中英(及日后更多语言)别名,所以: - -> **关键字 / 内置必须少而精**——体积在「名字 × 语言」上放大,而不是在功能清单上堆满。 - -更多能力进可导入的 `lib/`,用中英**不同库文件、不同函数名**扩展,不膨胀解释器内核。 - ---- - -## 2. 分层(与标准库对齐) - -| 层 | 是否导入 | 中英怎么区分 | -|----|----------|--------------| -| **L0 内核** | 否 | **同一文件内双名**:`print` ≡ `打印`;`True` ≡ `真` | -| **L1 标准库** | 是(`import …:lib/…`) | **不同文件**:`text.mq.md` vs `文本.mq.md`(见 i18n 草案) | - -L0 **不做** `lang:`、不做「当前语言模式」;写英文名就用英文,写中文名就用中文,可在同一程序里混用。 - ---- - -## 3. 范围:哪些要双名 - -### 3.1 字面量 / 逻辑关键字(词法保留) - -控制流仍靠 Markdown(`#` `1.` `-` `*` `**`),**不**为 `if`/`while`/`def` 做中英关键字。形参用 `+`。 - -| 英文 | 中文(提案) | 备注 | -|------|--------------|------| -| `True` | `真` | 布尔真 | -| `False` | `假` | 布尔假 | -| `None` | `空` | 空值 | -| `and` | `且` | 逻辑与 | -| `or` | `或` | 逻辑或 | -| `not` | `非` | 逻辑非 | - -中英文名均**不可作变量名**(同一保留集)。 - -### 3.2 内置函数(可调用、无需导入) - -**仅**下列核心五项做中英双名(与「少而精」一致): - -| 英文 | 中文(提案) | 作用 | -|------|--------------|------| -| `print` | `打印` | 写 stdout | -| `input` | `输入` | 读一行 | -| `len` | `长度` | 文本/表长度 | -| `str` | `文本` | 转为显示文本 | -| `int` | `整数` | 转为整数 | - -形参名也提供中英别名(便于纯中文调用): - -| 英文形参 | 中文形参 | 用于 | -|----------|----------|------| -| `text` | `内容` | `print` / `打印` | -| `prompt` | `提示` | `input` / `输入` | -| `value` | `值` | `len`/`str`/`int` 及对应中文名 | - -示例(等价): - -```markdown -> print text=Hello -> 打印 内容=你好 - -*`n` = > len `s`* -*`n` = > 长度 值=`s`* -``` - -### 3.3 明确不进 L0 双名表 - -下列若已在解释器中实现,视为**宿主原语 / 过渡 API**,**不**再批中文内核别名;应迁入或仅通过标准库暴露(中英分文件): - -| 英文名 | 去向 | -|--------|------| -| `type` | L1 或维持实现细节,不进「关键字最少集」宣传 | -| `trim` `split` `join` | L1:`lib/text.mq.md` / `lib/文本.mq.md` | -| `at` | L1:`lib/table.mq.md` / `lib/表.mq.md` | - -这样 L0 公开面 ≈ **6 个关键字词 ×2 + 5 个函数 ×2**,而不是「每个工具函数都 ×2」。 - ---- - -## 4. 语义规则 - -1. **别名等价**:中英文名绑定同一实现;诊断文案可用英文稳定串(金样例已有),用户文档中英均可举例。 -2. **可混用**:同一文件可同时出现 `print` 与 `打印`、`True` 与 `真`。 -3. **遮蔽**:用户 `# 打印` 与 `# print` 均会遮蔽对应内置名(实现阶段应警告)。 -4. **大小写**:英文关键字保持 Python 风格(`True`/`False`/`None`);中文无名感大小写问题。 -5. **扩语言**:日后日文等 → 再为 L0 增加第三个别名列;仍无「名字表」而非语言开关。标准库继续用**文件名**区分(见 i18n 草案)。 - ---- - -## 5. 与旧决议的关系 - -- 旧文「中文 `print` 废弃、统一为 `print`」:**废止**;改为正式双名 `print` / `打印`。 -- [keywords.md](keywords.md) 原则条「英文标识」改为「**内核双名;标准库分文件**」——实现阶段改正文。 -- 不引入中文控制流关键字(`如果`/`循环` 等);分支用 `1.` …,循环用 `-`。 - ---- - -## 6. 文档与金样例义务(实现时) - -| 项 | 要求 | -|----|------| -| `keywords.md` | L0 表改为中英并列;砍掉对 `trim`/`split`/… 的「内核关键字」宣传 | -| `public/` | 英 / 中文件同目录并列(拉丁名 vs 中文名) | -| `tests/` | 中文关键字 / `打印`·`长度` 等金样例;与英文样例对等 | -| 诊断 | 位置格式不变;message 可暂维持英文,或中英均可接受(另开小节) | - ---- - -## 7. 实现备忘(暂不开发) - -1. 词法 / 解析:字面量与 `and`/`or`/`not` 识别中文别名。 -2. 调用解析:内置表按别名归一到同一 `BuiltinId`。 -3. 形参绑定:`text`≡`内容`,`prompt`≡`提示`,`value`≡`值`。 -4. **不要**加 `lang:` 或全局「中文模式」。 -5. 与 [stdlib-i18n.md](stdlib-i18n.md) 一并落地时:先收束 L0 公开面,再铺 `lib/text` ↔ `lib/文本`。 - ---- - -## 8. 一句话 - -**内核:中英别名、无需导入、必须少;标准库:中英分文件、靠导入路径选择——这样 Marqdo 才能中英文通用而不把解释器撑爆。** diff --git a/doc/design/keywords.md b/doc/design/keywords.md deleted file mode 100755 index 8f0ec95..0000000 --- a/doc/design/keywords.md +++ /dev/null @@ -1,97 +0,0 @@ -# Marqdo 关键字与内置名(v0 最小集) - -| | | -|---|---| -| 状态 | 已定(中英双名) | -| 日期 | 2026-08-05 | -| 原则 | **少而精**;控制流靠 Markdown;内核中英**别名等价**(见 [keywords-i18n.md](keywords-i18n.md)) | -| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords-i18n.md](keywords-i18n.md) · [stdlib-i18n.md](stdlib-i18n.md) | - ---- - -## 1. 设计原则 - -1. **标记承担架构**:函数=`#`,**形参=`+`**,**分支=`1.`…**,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。 -2. **内核双名**:字面量 / 逻辑词 / 五个核心内置函数均有中英别名,**无需导入**,可混用。 -3. **学 Python 的边界**:区分 **关键字** vs **内置函数名**。 -4. **宁少勿多**:扩展能力进可导入标准库(中英分文件,见 [stdlib-i18n.md](stdlib-i18n.md))。 - ---- - -## 2. 关键字(词法保留,不可作变量名) - -| 英文 | 中文 | 含义 | -|------|------|------| -| `True` | `真` | 布尔真 | -| `False` | `假` | 布尔假 | -| `None` | `空` | 空值 | -| `and` | `且` | 逻辑与 | -| `or` | `或` | 逻辑或 | -| `not` | `非` | 逻辑非 | - -**不引入:** `if` `else` `while` `for` `def` `return` …(分支臂 `*` 不是单词 `else`。) - ---- - -## 3. 内置函数(可调用,无需导入) - -| 英文 | 中文 | 作用 | -|------|------|------| -| `print` | `打印` | 写 stdout | -| `input` | `输入` | 读一行;capture / view 用 frontmatter `stdin:` / `输入:`、表单或 `--stdin-file` 预置 | -| `len` | `长度` | 文本/表长度 | -| `str` | `文本` | 转为显示文本 | -| `int` | `整数` | 转为整数 | - -**文本**:裸 token 按字面量;需 `\n` 等转义时用 `"..."`(见 [markdown-mapping.md](markdown-mapping.md) §7)。 - -形参别名: - -| 英文 | 中文 | 用于 | -|------|------|------| -| `text` | `内容` | `print` / `打印` | -| `prompt` | `提示` | `input` / `输入` | -| `value` | `值` | `len`/`str`/`int` 及其中文名 | - -```markdown -> print text=Hello -> 打印 内容=你好 - -*`n` = > 长度 值=`s`* -``` - -宿主原语 `type` / `trim` / `split` / `join` / `at` **无**内核中文别名;文本/表扩展走标准库文件(见 [stdlib-i18n.md](stdlib-i18n.md))。转换错误见 [stdlib.md](stdlib.md)。 - ---- - -## 4. 与 Markup 调用的关系 - -```markdown -# main - -> 打印 内容=Hello World! - -*`n` = 1* - -1. `n` > 0 - > print text=positive -2. * - > 打印 内容=other -``` - -- `>` 是调用标记;`print` / `打印` 是同一内置的别名。 -- 用户 `# print` 或 `# 打印` 会遮蔽对应名字。 - ---- - -## 5. 标识符规则(摘要) - -- 变量:`` `name` ``;不可为上表任一中英文关键字。 -- 函数名:`#` 标题;中英文均可。 -- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and`/`且`、`or`/`或`、`not`/`非`。 - ---- - -## 6. 后续可增(未批准) - -`float`、`range`;以及 `break`/`continue`。增加前开短 ADR,并同步考虑是否值得占用双名配额。 diff --git a/doc/design/knowledge-layers.md b/doc/design/knowledge-layers.md deleted file mode 100755 index acf1d03..0000000 --- a/doc/design/knowledge-layers.md +++ /dev/null @@ -1,443 +0,0 @@ -# 知识分层:原始语料、可执行知识、调用面 - -| | | -|---|---| -| 状态 | **Design Review · Recommended(v2.1 语法设计评审)** | -| 日期 | 2026-10-23 | -| 问题 | 「诗人类 → 用李白知识实例化 → `[]()` 调用」的三/四层模型,从**语法设计**上是否自洽? | -| 推荐 | **单体知识类(singleton knowledge class)**:`# 诗人` 是类,`# 李白 = > 诗人` 是知识个体;`李白.出生年份` 是类调用;零新语法 | -| 关联 | [link-syntax.md](link-syntax.md) · [objects.md](objects.md) · [module-namespace.md](module-namespace.md) · [engineering-knowledge.md](engineering-knowledge.md) · [okf.md](okf.md) | -| 示例 | [examples/knowledge-layers/](../../examples/knowledge-layers/) | - ---- - -## 0. 结论先行 - -### 0.1 一句话 - -> **分层逻辑是自洽的;不自洽的是「实例化」这个词与当前 `#`/`= >` 语法。** -> 如果「实例化」指**知识个体**,用 `# 李白 = > 诗人` 编码即可,零新语法; -> 如果「实例化」指**运行时对象**,就需要新的可寻址实例声明/注册表,语法成本明显更高。 - -### 0.2 三层 / 四层:推荐四层 - -| 层 | 名称 | 内容 | 语法载体 | -|----|------|------|---------| -| **L0** | 原始语料 | 原文、出处、引用、版本 | `.md` / `.mq.md` 叙述 + `来源` 表 | -| **L1** | 本体 / 模式 | 类、字段、类型、约束 | `# 诗人` + 字段/类型表 | -| **L2** | 可执行知识 | 知识个体、事实、返回值、出处 | `# 李白 = > 诗人` + `## 出生年份` + `*701*` | -| **L3** | 调用面 | 链接、类调用、view、LinkInfo、EKC、agent | `[出生年份](李白.出生年份)` | - -三层版可以把 L1/L2 合并为「可执行知识体系」;四层版把**本体**与**个体**分开,正好对应 EKC 的 schema/knowledge 分层。 - -### 0.3 核心判断 - -| 判断 | 结论 | -|------|------| -| 原始语料 → 可执行知识 → 调用面,逻辑成立 | ✅ | -| 可执行知识能还原/验证回原始语料 | ✅ 需要出处/校验约定,语法上可行 | -| `# 诗人` 是类 | ✅ 现有 `#` 语义 | -| `# 李白 = > 诗人` 是「实例化」 | ⚠️ **语法上是继承/特化,不是运行时实例化** | -| `李白.出生年份` 是类调用 | ✅ 需要类函数 + 项目类索引(v2.1 目标) | -| `[]()` 是调用面,不新增语法 | ✅ `[描述](类.函数)` = 描述 + 已有调用 | - ---- - -## 1. 你的模型(精确复述) - -1. 有一个**诗人**类(`# 诗人`),定义诗人应该有什么字段/函数; -2. 用**李白的知识**把这个类「实例化」: - - 李白是诗人; - - 李白有姓名、出生年份等事实; -3. 通过 `[]()` 链接语法调用这个知识: - - `[出生年份](李白.出生年份)`; -4. 整个体系分层: - - 原始语料; - - 改写/抽象后的可执行知识(可还原验证回原始知识); - - 智能体回答/思考时的调用面。 - -这个模型在**知识架构**上没有问题;问题只在第 2 步的「实例化」如何落到语法。 - ---- - -## 2. 当前语法事实 - -| 语法 | 当前语义 | 对模型的影响 | -|------|---------|-------------| -| `# 诗人` | 类/类型;正文是构造体 | ✅ 可做本体 | -| `# 李白 = > 诗人` | **继承/子类**;不是实例 | ⚠️ 与「实例化」字面不符 | -| `## 李白的出生年份` | 方法;可用 `self`/`自` | ⚠️ 当前是实例方法 | -| `> 李白` | 构造实例(map + `_type`) | ✅ 运行时实例 | -| `李白.李白的出生年份` | 当前被当变量/实例方法路径 | ❌ 类调用未实现 | -| `[描述](...)` | 描述 + 表达式 | ✅ 调用面 | -| `import` | 跨文档绑定 | ⚠️ 当前跨文档继承/调用需 import | - -**实测**(`marqdo 2.0.0`): - -- `# 李白 = > 诗人` 在**另一个文档**定义 `# 诗人` 时,未 import 会报 `unknown base type 诗人`; -- import 后可以继承,但调用仍需 `> libai.李白` 构造实例,再 `` `li`.李白的出生年份() `` → `701`; -- `李白.李白的出生年份` 直接调用报 `undefined variable`; -- 跨文档类索引不存在。 - -所以「诗人类 → 李白实例 → 链接调用」在**目标模型**上成立,在**当前语法**上只完成了「类 + 继承 + 实例方法」,缺「类调用 + 类索引」。 - ---- - -## 3. 自洽性检查:逐层 - -### 3.1 L0 原始语料 - -| 问题 | 结论 | -|------|------| -| 原始语料是否可执行? | 否;它是出处,不是程序 | -| 能否被引用? | ✅ 现有 Markdown 相对链接/`来源` 表 | -| 能否保留原文? | ✅ 叙述、引用块、表格 | -| 语法负担 | 零:就是现有文档 | - -**要点**:原始语料必须保持「不可执行」的独立身份;一旦把原文改写成代码,就失去了「还原验证」的基准。所以 L0 与 L2 要**物理/逻辑分离**(`corpus/` vs `knowledge/`)。 - -### 3.2 L1 本体 / 模式 - -```markdown -# 诗人 - -| 字段 | 类型 | 说明 | -|------|------|------| -| 姓名 | text | 诗人姓名 | -| 出生年份 | number | 公元年份 | -``` - -| 问题 | 结论 | -|------|------| -| `# 诗人` 能否表达类? | ✅ `#` 就是类/类型 | -| 字段/类型能否表达? | ✅ 现有表格 + 契约表 | -| 是否需要新语法? | ❌ 不需要;用字段/类型表的列名约定 | -| 是否能被检查? | 需要新增 `knowledge.schema_*` 检查(工具,不是语法) | - -**语法结论**:L1 完全用现有 `#` + 表格;只需要约定「字段表」的列名与语义。 - -### 3.3 L2 可执行知识:关键歧义 - -「用李白的知识实例化诗人」有两种落法: - -#### A. 单体知识类(推荐) - -```markdown -# 李白 = > 诗人 - -## 李白的出生年份 - -*701* -``` - -- 语法:`# 李白 = > 诗人` = 继承/特化; -- 语义:李白是诗人(is-a),并且 `# 李白` 是一个**命名的知识个体**; -- 调用:`李白.李白的出生年份` = 类调用(不使用 `self` 的函数); -- 地址:`# 李白` 是文档里的稳定类名,可被项目类索引解析; -- 运行时:如果需要 map,仍可 `> 李白` 构造实例; -- 代价:**术语上不是「实例」**,是「单体类/知识个体」。 - -#### B. 运行时实例(不推荐作为 v2.1 语法) - -```markdown -# 诗人 - -## 李白 - -*> 诗人 姓名="李白" 出生年份=701* -``` - -- 语法:`## 李白` 是函数,返回一个实例 map; -- 调用:`李白().出生年份`(函数返回实例,再取方法); -- 地址:`李白` 是函数名,不是实体;跨文档要函数索引/缓存; -- 代价:每次调用可能新构造实例;没有稳定的知识实体地址;EKC 节点是函数,不是个体; -- 需要:实例注册表/导出机制,或函数级索引;这比 A 多一层运行时概念。 - -#### C. 显式个体声明(未来可选) - -```markdown -# 李白 : 诗人 -``` - -- `:` 明确「李白是诗人个体」; -- 语法更贴近本体(instance-of),但**新增一个标记**; -- 与 `# Child = > Parent` 形成两种关系,需要决定何时用哪种; -- 不建议 v2.1 引入;可作为 v2.2 的候选。 - -### 3.4 L3 调用面 - -```markdown -[出生年份](李白.李白的出生年份) -``` - -| 问题 | 结论 | -|------|------| -| `[]` 是描述、`()` 是调用? | ✅ 现有语义 | -| `()` 与 `**` 同权? | ✅ 同一 parser/evaluator | -| 跨文档类名能否解析? | 需要项目类索引(v2.1) | -| 正文链接是否执行? | view/check 解析;run 不执行(安全) | -| 终端输出? | 代码链接 + `print` | -| 编译器能否返回 LinkInfo? | 需要新增(工具,不是语法) | -| view 能否显示调用点? | 需要新增(工具,不是语法) | - -**语法结论**:L3 不需要新语法;缺的是**解析器/类索引/视图/编译器输出**。 - ---- - -## 4. 推荐模型:单体知识类 - -### 4.1 定义 - -> **单体知识类**:一个 `# 名称 = > 父类` 的类,代表一个知识个体;它的 `##` 函数是该个体的知识字段/事实;它不需要运行时实例即可被 `类.函数` 调用。 - -```markdown -# 诗人 - -| 字段 | 类型 | 说明 | -|------|------|------| -| 姓名 | text | 诗人姓名 | -| 出生年份 | number | 公元年份 | - -# 李白 = > 诗人 - -## 李白的出生年份 - -| 返回 | 类型 | 来源 | -|------|------|------| -| 701 | number | corpus/libai.md#出生年份 | - -*701* -``` - -调用: - -```markdown -# main - -**year = [李白的出生年份](李白.李白的出生年份)** -> print text=`year` -``` - -输出:`701`。 - -### 4.2 为什么推荐 A - -| 维度 | A 单体类 | B 运行时实例 | -|------|---------|-------------| -| 语法新增 | **零** | 需要实例导出/注册/函数索引 | -| 地址稳定 | ✅ 类名 | ❌ 函数返回值 | -| 跨文档 | ✅ 项目类索引 | ❌ 需要实例注册表 | -| EKC 映射 | ✅ 文档/类/函数节点 | ❌ 实例不是文档节点 | -| 可还原 | ✅ 类/函数 + 来源表 | ⚠️ 实例是运行时值 | -| 可检查 | ✅ 类/函数/契约 | ⚠️ 实例状态难静态检查 | -| 术语 | ⚠️ 叫「个体」不叫「实例」 | ✅ 叫实例 | -| 多实例 | ⚠️ 每个个体一个类 | ✅ 自然 | - -**结论**:在「文档即知识库」的约束下,A 的语法成本最低、可检查性最好;B 的「实例」语义更纯,但需要新的运行时/注册表,和「零新语法」冲突。 - -### 4.3 术语约定 - -| 术语 | 含义 | 语法 | -|------|------|------| -| **类 / 本体** | 诗人的模式 | `# 诗人` | -| **知识个体(单体类)** | 李白这个知识实体 | `# 李白 = > 诗人` | -| **知识字段 / 事实** | 李白的出生年份 | `## 李白的出生年份` + `*701*` | -| **类调用** | 读取知识个体的字段 | `李白.李白的出生年份` | -| **运行时实例** | 代码里 `> 李白` 得到的 map | `> 李白` / `_type` | -| **知识链接** | 描述 + 类调用 | `[出生年份](李白.李白的出生年份)` | - -> **重要**:语法文档里不要再用「实例化」描述 `# 李白 = > 诗人`;用「知识个体化/单体类」。 -> 「实例」保留给运行时 `> 诗人` 产生的 map。这样语法、文档、EKC 三者才一致。 - -### 4.4 多诗人怎么办 - -```markdown -# 李白 = > 诗人 -# 杜甫 = > 诗人 -# 王维 = > 诗人 -``` - -- 每个个体是一个单体类;项目类索引登记它们; -- `李白.出生年份` / `杜甫.出生年份` 分别解析; -- 这是「命名个体注册表」,不是运行时实例集合; -- 如果个体成千上万,类索引会变大;v2.2 可引入表驱动的个体注册(但不改变调用语法)。 - ---- - -## 5. 与 EKC 的映射 - -| 层 | EKC 层 | 节点/边 | -|----|--------|---------| -| L0 原始语料 | Repository / sources | `documented_by` / `derived_from` | -| L1 本体 | Capability / Schema | `# 诗人` class 节点 | -| L2 知识个体 | Knowledge / Symbol | `# 李白` class 节点 + `##` fact 节点;`specializes` 边 → `诗人` | -| L3 调用面 | Symbol / Capability | `[]()` 链接 → `calls` 边;LinkInfo | -| L4 Agent | Agent / Context Pack | `find`/`reuse`/`link.resolve` | - -**新增边(建议)**: - -- `specializes`:`# 李白 = > 诗人`(语法上是继承;知识语义上是 is-a); -- `derived_from`:fact → 原始语料; -- `calls`:调用文档 → `李白.出生年份`; -- `has_fact`:`# 李白` → `## 出生年份`。 - -EKC 现有 `depends_on`/`uses`/`implements`/`documented_by` 可以复用;`specializes` 建议新增。 - ---- - -## 6. 还原 / 验证(L2 → L0) - -「可执行知识能还原验证回原始知识」需要三件事: - -### 6.1 出处是数据,不是注释 - -```markdown -## 李白的出生年份 - -| 返回 | 类型 | 来源 | -|------|------|------| -| 701 | number | corpus/libai.md#出生年份 | - -*701* -``` - -- `来源` 列指向原始语料(路径 + 标题/锚点); -- 也可以放 frontmatter `sources:`; -- `check` 验证来源存在;`verify` 验证值/引文一致(能自动化的部分)。 - -### 6.2 可还原的渲染 - -- `view` 把 `# 李白` 渲染成「知识文档」:字段 + 值 + 来源; -- `catalog` 生成 OKF `Fact` 页,`resource:` 指向 `.mq.md`; -- 渲染结果与原始语料可人工/机器对照; -- 这不是新语法,是 view/catalog 的输出。 - -### 6.3 漂移检查 - -| 诊断 | 触发 | -|------|------| -| `knowledge.source_missing` | 事实没有来源 | -| `knowledge.source_dangling` | 来源路径/锚点不存在 | -| `knowledge.value_mismatch` | 事实值与来源引文不一致(可自动判断时) | -| `knowledge.schema_mismatch` | `# 李白` 字段与 `# 诗人` 不匹配 | -| `knowledge.fact_drift` | 原始语料变了,知识未复核 | - -这些是**工具诊断**,不是语法。 - ---- - -## 7. 调用面:智能体如何使用 - -```markdown -# main - -用户想知道李白的出生年份,我们回答:[李白的出生年份](李白.李白的出生年份) -``` - -- `view` 显示:`李白.李白的出生年份` → `701` → 来源 `corpus/libai.md#出生年份`; -- `check --json` 返回 LinkInfo(class/function/value/source); -- agent 通过 `link.resolve` / `find` 取到值 + 出处,回答时可引用来源; -- `run` 加 `print` 才输出;正文链接不执行,保证叙述安全。 - -**这就是「调用面」**:不是自然语言猜,而是可解析、可验证、可引用的类调用。 - ---- - -## 8. 反例与边界 - -| 场景 | 用 A 单体类 | 说明 | -|------|-----------|------| -| 李白、杜甫、王维 | 三个单体类 | 类索引;命名个体 | -| 同一诗人的多个版本 | 多个事实/来源,或子个体 | 版本是事实维度,不是实例 | -| 需要运行时状态(可变对象) | `> 李白` 构造实例 | 运行时实例仍存在,但与知识个体分离 | -| 上千个诗人 | 类索引/表驱动注册 | v2.2 优化;语法不变 | -| 需要 `instanceof` | `# 李白 = > 诗人` 的 `specializes` 边 | 知识语义;不是运行时 `_type` | -| 需要多继承 | 现有不支持 | 不在本设计范围 | - ---- - -## 9. 决策建议 - -1. **v2.1 采用 A(单体知识类)**:`# 诗人` + `# 李白 = > 诗人` + `##` 事实 + `[]()` 类调用;零新语法。 -2. **术语冻结**:`# 李白 = > 诗人` 叫「知识个体/单体类」,不叫「实例」;`> 诗人` 才是运行时实例。 -3. **补类函数与类索引**:不使用 `self` 的 `##` 是类函数;项目类索引解析跨文档 `李白`。 -4. **补出处/验证**:`来源` 列或 `sources:`;`check`/`verify`;`view`/`catalog` 可还原。 -5. **EKC 边**:`specializes` / `derived_from` / `calls` / `has_fact`。 -6. **保留 B/C 作为未来**:如果真需要运行时实例/个体声明,再评估 `# 李白 : 诗人` 或实例注册表;不在 v2.1 引入。 - -### 9.1 备选:frontmatter 个体声明(零语法,但换元数据) - -如果不想把 `= >` 的继承语义借给「个体」,可以用 frontmatter 标记: - -```markdown ---- -type: Individual -class: 诗人 -id: libai ---- - -# 李白 - -## 出生年份 - -*701* -``` - -| 维度 | 单体类 A | frontmatter 个体 | -|------|----------|------------------| -| 可见性 | `# 李白 = > 诗人` 一眼可见 | 类型在 frontmatter,正文只看到 `# 李白` | -| 语法 | 现有 `= >` | 现有 frontmatter,无新标记 | -| 语义纯度 | 继承/特化 | 明确 individual-of | -| EKC | class + specializes | individual + instance_of | -| 代价 | 术语「个体」不是「实例」 | 两套 is-a 表达(`= >` 与 `class:`)需要约定 | - -**建议**:v2.1 先用 A(可读、零语法);如果 EKC/本体需要严格区分 class/individual,再启用 frontmatter `type: Individual`,并规定「`= >` 只用于类-类,个体用 frontmatter」。 - ---- - -## 10. 结论 - -> **三层/四层模型自洽;「实例化」是唯一需要修正的词。** -> 在 Marqdo 的语法里,`# 李白 = > 诗人` 是**继承/特化**,不是运行时实例; -> 把它用作**单体知识类**,就能在不新增语法的情况下得到「李白是诗人、李白有出生年份、`李白.出生年份` 可调用」。 -> 这正是 EKC 的「文档即知识、知识可执行」:**类是本体的地址,单体类是知识个体的地址,`[]()` 是调用面。** - ---- - -## 附录 A:一页对照 - -```markdown -# L1 本体 -# 诗人 -| 字段 | 类型 | 说明 | -| 姓名 | text | ... | -| 出生年份 | number | ... | - -# L2 知识个体(单体类) -# 李白 = > 诗人 -## 李白的出生年份 -| 返回 | 类型 | 来源 | -| 701 | number | corpus/libai.md#出生年份 | -*701* - -# L3 调用面 -[李白的出生年份](李白.李白的出生年份) -``` - -| 层 | 语法 | 语义 | -|----|------|------| -| L0 | `.md` 原文 + 来源 | 不可执行 | -| L1 | `# 诗人` + 字段表 | 类/模式 | -| L2 | `# 李白 = > 诗人` + `##` + `*701*` | 知识个体/事实 | -| L3 | `[描述](类.函数)` | 类调用/链接 | -| 运行时 | `> 诗人` / `> 李白` | map 实例(可选) | - -## 附录 B:与现有文档的关系 - -| 文档 | 关系 | -|------|------| -| [link-syntax.md](link-syntax.md) | 调用面的语法;本文补知识分层与单体类 | -| [objects.md](objects.md) | `#`/`##`/`= >` 的对象模型;本文把 `= >` 用于知识个体 | -| [module-namespace.md](module-namespace.md) | 跨文档解析;本文用项目类索引 | -| [engineering-knowledge.md](engineering-knowledge.md) | EKC L0–L4;本文映射到四层 | -| [okf.md](okf.md) | Fact/Concept/路径即身份;本文的 L2 与 Fact 对应 | diff --git a/doc/design/knowledge-proof-2.9.md b/doc/design/knowledge-proof-2.9.md deleted file mode 100644 index 13943c5..0000000 --- a/doc/design/knowledge-proof-2.9.md +++ /dev/null @@ -1,260 +0,0 @@ -# Marqdo 知识锚点与证明制品(2.8 → 2.9) - -> 实现状态:PR #2 第一阶段。保持解释器和原有 `[]()` 求值语义不变,复用 2.8.0 `prove` 与既有 SemanticProject。以下明确区分**已经写入分支的功能**和**尚未完成的跨模块证明**。 - -## 核心语义 - -- AST 内部步骤仍有原来的 `#step-N` 序号,供旧查询、调试与执行日志使用。 -- 在**同一个函数内名称唯一**的标记步骤,获得独立的 `anchor_id = SymbolId#anchor-sha256(normalized_label)`;在前面插入其他步骤不会改变地址。 -- 同函数重复的标记名称**不产生公共锚点**;必须重命名,不得静默采用首个。 -- `definition_digest` 来自该语句源码位置的内容,与稳定身份分开;语句内容更改时身份保留、定义指纹改变。 -- 两种文档引用不执行目标:同函数的 `[阅读依据](#@演算)` 和跨模块绝对地址 `[阅读依据](mq://...#anchor-<sha256>)`。后者应从编译生成的 anchors.json 拿完整 ID,不应凭空手写。 -- 2.8.0 定理表每条唯一声明生成稳定 `ClaimId = SymbolId#claim-sha256(定理名称)`;正文 `[阅读定理](#@定理名称)` 可以定位**声明**,但不会读取或伪造证明状态;同一名称同时匹配知识步骤和定理声明时标记 `ambiguous_anchor`,不猜测。\n- 普通 `[说明](https://...)` 仍为导航,原来表达式位置的 `[描述](payload)` 仍依照原 Marqdo 执行规则求值。 -- **链接不意味着执行权**:解析到知识锚点只生成引用边,不自动调用函数、加载插件或赋予权限。 - -## 制品 - -`marqdo knowledge` 所用的 SemanticProject 原子生成目录下新增: - -| 路径 | 内容 | -|---|---| -| `steps.json` / `refs.json` | 增量字段 `anchor_id`、`definition_digest`、`link_target`、`target_anchor` | -| `claims.json` | 定理声明索引,初始状态固定为 `declared_unverified`,不等同于证明通过 |\n| `anchors.json` | 稳定公共步骤索引,附所有者、标记文本、源码、效应、定义指纹 | -| `graph/edges.json` | `defines_anchor`、`references_anchor`、知识步骤到已解析调用目标的 `calls` | -| `proof-index.json` | 可用或过期的证明收据索引;它不是可执行授权,也不自动证明步骤 | - -`marqdo prove` 在原本的证明目录附带 `knowledge-links.json`: -每个定理通过文件 + 函数全名唯一绑定到 `SymbolId`,稳定 `claim_anchor_id` 附带前提、结论、来源、函数的 interface/implementation/closure digest 与可用时的 Lean 证书摘要。 -无法安全绑定时输出 `unresolved`,不匹配别的同名函数。 -`related_anchor_ids` 仅是 **defined_in_same_function_not_individually_proved** 导航关系,绝不意味着 Lean 已分别证明这些内部锚点的性质。 - -## 证据有效性 - -1. 离线 `checked` 不能当作 `proved`。 -2. 只有 `ClaimReport` 显示真实 Lean 判定,且匹配当前报告的原始 `certificate.json`、命题、文件、Lean 工具链与证明库,才可输出 `proved` 关联。 -3. 在知识编译时复核文件源码 SHA、函数接口、实现指纹、传递依赖 closure 指纹及证书字节摘要;失败 => `stale` / `unverified`,`usable=false`。 -4. 同一个声明出现多份可见报告时 => `ambiguous`,不能随意取旧证书或新证书。 -5. 当前证明文件是**本地缓存收据**,不是经过签名的远程授权凭证。对抗性环境必须在可信 CI 中再次用 Lean 验证,不能仅相信 JSON 内的 `status`。 - -## 下一阶段:跨模块 assume–guarantee - -这是比单纯增加更多 Lean tactic 更重要的方向,但 **本 PR 第一阶段尚未实现**: - -- 将函数可复用契约分成 `requires / ensures / effects`,全部有已解析 SymbolId 作为身份; -- 在调用方生成 “调用前提满足” 的证明义务,并以被调者的已验证后置条件作为假设,**明确记录假设链**; -- 若被调者实现改变、但同一契约被重新证明支持,允许复用不受影响的调用方证明; -- 若契约失效、闭包改变或假设不能满足,所有受影响证明回退 `stale`,不能保持 `proved`; -- 对外部 ABI 插件调用,必须给出明确 effect 契约、来源和可信主体,不能把不透明调用宣告为纯函数; -- 保留 Lean 与解释器对 i64 溢出、除零/模零行为的差异护栏,在证明模型不等价时不给出无限定的成功保证。 - -## 验收指标 - -1. 在任意步骤前插入不相关语句,公共锚点地址不漂移;旧内部编号可以变化。 -2. 只修改锚点表达式,定义 digest 必须变化,锚点地址保持;同名重复拒绝公开。 -3. `#@标签` 与完整 `mq://...` 必须精确解析;不存在锚点报告 unresolved,且不能变成 BoundCall。 -4. `prove` 的函数证明只能关联函数知识,不能将所有带标记步骤标成 proved。 -5. 更改源码、契约、传递依赖或证书后,知识索引拒绝使用过期证明。 -6. 与 2.8.0 原有 CLI / SemanticProject / Lean 测试保持兼容。 - - - -## M4:模块化证明内核与当前信任边界 - -本工作在 `src/knowledge/modular.rs` 增加证明义务图,输出于 -`proof-obligations.json`;可通过命令: - -```sh -marqdo knowledge proof-deps --json --strict . -``` - -`--strict` 在缺少来源校验、证明收据或契约时非零退出。这个 -`audit_passes` **不是**一个 Lean 证明的调用方定理,也不能发布 -`proved`。它只说明当前本地可见的证明收据与契约引用是否完整。 - -T3 声明采用既有 GFM 表格(不增加解释器语法): - -| 假设 | 前置 | 后置 | -|---|---|---| -| rates.lookup | 金额 > 0 | 返回 = 2 | - -函数开头的此表现在被 parser 提取进 `Function.assumptions`,映射到 -`FnPlan.assumptions`,由 `SemanticProject` 生成 `assumptions.json`; -不参与运行时执行、也不赋予事实可信度。重复、未找到、前置条件待验证 -均应 fail closed。 - -`doc/verification/skill-proof/MarqdoModularProof.lean` 定义参数化的 -`Contract`、`Implements` 和 `compose_sound`: - -- 被调函数真正满足其前后置条件; -- 调用方/前一个函数真正满足其前后置条件; -- 显式桥接引理证明前一个函数的后置条件足以满足后一个函数的前置条件; - -Lean 才能得出组合契约成立。文件含一个缺少桥接前提时组合错误的反例, -以防未来实现将“被调者 proved”直接等价于“调用者 proved”。 - -### 尚未完成的关键项(不得标记 done) - -1. **参数绑定**:从真实 Marqdo `BoundCall` 的表达式实参生成 - 调用点前置条件的 Lean 目标。不能直接复用未绑定实参的 `前置` 文本。 -2. **模块化执行语义**:在 Lean 中准确表示 import / 调用 / 返回 / 效应, - 并与原解释器的数值和异常行为建立等价性。 -3. **证明组合与导出**:仅在被调证明证书经过受信核验、桥接义务 - 由 Lean 消除且调用方自己的 Lean 定理成立时,输出新的模块化证明证书。 -4. **可靠的跨实现复用**:不能因为后置条件文字未改变就绕过重新核验; - 必须要有新实现支持同一契约的证明,且证明/模块 ABI 版本匹配。 -5. **安全与正确性测试**:成功与失败调用、条件前置、不透明调用、效应、 - 多版本证书、循环依赖、证书篡改、解释器/Lean 差分一致性与崩溃恢复。 - -所以目前 **已经实现的是可寻址知识编译、证明绑定和保守的模块依赖审计**; -**没有实现完整跨模块自动推理并生成 `proved` 的系统**,不应声称后者已完成。 - - -## M5:跨模块纯叶函数的受限源码透明证明 - -`src/prove/lower.rs` 新增第一条**真实跨文件执行语义**通路。 -`Target::Import` 仅对以下情形将导入函数源码透明降级入调用方 Proof IR: - -- 被调函数体只有一个 `Return`;表达式由字面量、形参、无副作用一元/二元表达式和遮蔽表达式构成,不得依赖全局状态或其他函数; -- 调用实参全部显式传入、位置匹配且与参数数目一致,不能通过默认参数或任意命名重排来隐式猜测绑定; -- 展开深度有严格上界;不支持分支、循环、递归、动态分派、ABI 效应或未知调用; -- 当导入表达式包含算术操作时,必须通过实际实参的静态整数求值确保 `i64` 不溢出、不除零。包含变量或非整数的未知算术保持不透明,绝不因 Lean 的无界 `Int` 语义而自动升级。 - -这条通路设计的真实 Lean 正例分别是无参数的跨文件纯返回,以及带实际参数绑定的加一计算;`tests/knowledge_proof.rs` 包含导入文件产生副作用和 `i64` 溢出的反例。 - -**该特性是源码透明的跨模块证明(有限展开),不是抽象契约复用。** -只有独立证明调用点前置条件、将已证被调契约接入调用方而无需展开实现,并由 Lean 校验接口桥接,才算真正完成通用 assume–guarantee 模块化证明。 - - -## M6:真实 Lean 的封闭调用前置条件(2026-11-18) - -模块化校验现在有两种不同的操作: - -```sh -# 纯分析:不会冒充 Lean 已检查 -marqdo knowledge proof-deps --json . - -# 要求真实 Lean:先重放被调函数证明,再检查可闭合的调用点前提 -marqdo knowledge proof-deps --verify --json . - -# 审计严格退出码;不是“整个程序的模块化定理已被证明” -marqdo knowledge proof-deps --verify --strict --json . -``` - -工作过程: - -1. `BoundCall` 保留精确的 caller/target 知识身份,以及**按解释器执行约定归一化后的实参**(名称、顺序、保守静态整数值、源表达式摘要)。 -2. `knowledge/vc.rs` 用被调方函数签名,将受限前提(整数比较/加减乘/布尔连接)绑定到**真实实参**。拒绝除法、溢出、动态变量、不匹配的命名/顺序参数及无法解释的谓词。 -3. 先校验原 `certificate.json` 的复合缓存键、`plan.json`、嵌入证明库哈希、生成 Lean 文件 SHA、源码和语义闭包。 -4. `--verify` 额外使用现有 Lean 工具链**重新检查被调方生成的 Lean 定理**。仅当重放后的确具有精确匹配的 proved 定理时,才承认该条 callee 收据。 -5. 从验证过的收据与闭合前提生成 `closed-goals.lean`,对每个目标使用 `theorem vc_i : ... := by decide`;调用 Lean 4 核验。Rust 计算的布尔结果只能用于提前拒绝,不能独立充当证据。 -6. `proof-obligations.json` 与实时 JSON 审计报告分别记录 `precondition_pending` / `precondition_refuted` / `lean_kernel_verified` 等状态。无工具链、超时、证书篡改、Lean 不接受、源变更全部拒绝进入成功状态。 - -两个严格区分的边界: - -- `lean_kernel_verified` 表示**当前闭合调用点的条件命题已被核验**,而非调用方的完整结论定理。 -- `proof_completion` 仍为 `not_established_by_dependency_analysis`。目前缺少通用符号实参、分支路径条件、任意效应 ABI 的正式组合证明与可重放的跨模块结论证明证书。**不得将依赖图审计通过升级为完整模块化 proved。** - -新增 `tests/prove_lean.rs` 场景验证被调定理与调用前置条件**双重重放**,且实参不满足前置条件时必然退出非零;新增单元测试覆盖实际工程导入、整数溢出和未绑定实参。此处描述的是提交的实现及其预期测试,最终验收仍以最新提交 CI 结果为准。 - - -## M7:路径敏感符号证明和独立组合证书(限定子集) - -### 路径条件 - -`SemanticProject.BoundCall` 保存调用身份、归一化实参、直接变量、 -进入该调用点的分支条件(包括 else 否定条件)以及无法证明时的 -`control_blocker`。副作用条件、循环、迭代和未知运算不作为已证前提。 - -`src/knowledge/symbolic.rs` 对纯整数比较和布尔条件产生带 -`(v0 : Int)` 等量词绑定与路径假设的 Lean 定理;调用 Lean 核验后仅为 -`symbolic_path_lean_model_proved`,不等于运行时契约通过。数学 Int 与 -Marqdo 动态值、有界 i64 语义对应仍需独立证明。 - -### 独立 Lean 组合证明(首个真正闭环) - -```sh -marqdo knowledge compose --json --strict . -marqdo knowledge replay .marqdo/modular/composed/{proof-id}/composition-certificate.json --json . -``` - -`compose` 仅接受:不同文件间的唯一静态调用;纯整数函数; -调用方直接返回或一次局部赋值再返回被调结果;被调方只有一条整数常量返回; -参数均有明确 int 契约、无默认参数;实参仅为调用方参数或安全整数常量; -双方具有相同的无条件结果定理;无分支、循环、递归、异常、ABI 效应。 - -分别生成 `CalleeModule.lean` 和 `CallerModule.lean`: - -- 被调方源码生成定义,其契约由 Lean 证明。 -- 调用方 `import CalleeModule`,只使用被调方证明的契约,不展开其函数体。 -- 两模块独立生成 .olean 并通过真实 Lean 4 核验。 -- `composition-certificate.json` 绑定符号、源码闭包、Lean 版本、Lean 源文件 - 和编译模块哈希,证明作用域限定为 - `typed_int_pure_forwarder_constant_postcondition`。 -- `replay` 必须从**当前项目**重新编译出相同的 Lean 源,匹配依赖闭包, - 然后独立重新执行两个 Lean 模块并校验产物哈希;源码/证书有变即失效。 - -此证书状态是 `lean_kernel_proved_model`,**不是** Marqdo 运行时全部语义已证。 - -### 异常、循环、递归与 ABI 的保守边界 - -`MarqdoModularProof.lean` 用 `Exit.ok / Exit.error / Exit.diverged` -显式区分成功、异常、不终止;`total_sequence_sound` 证明包含异常和 -发散结果的总正确性契约只有在前置条件桥接被证明后才能组合。 -异常结果和发散结果不能等同于正常返回。 - -这是经过 Lean 检查的**抽象组合规则**,并非已证明所有插件、循环与递归 -实现满足这一模型。遇到 ABI 不透明效应、无法验证的异常处理、缺失循环 -不变式/终止性或递归下降变元时,编译器保守拒绝组合。 - -### 未达到完整通用系统的部分 - -动态类型语义保持、复杂算术的安全条件、任意路径的 WP、 -循环不变式与终止性、递归归纳证明、插件状态转换可信契约、 -并发效应,以及一般性参数化后置条件的源码无关组合,目前仍不完整。 -不能将已完成的限定子集扩大宣传为完整的通用模块化证明系统。 - -### 2026-11-18 类型安全修正 - -目前类型表源文本中的 `int` 被契约解析器归一化为 `number`,它也允许 Num 和 Formula。因此**不能**把 `number` 的证明自动解释为任意 Marqdo 运行时输入均为 i64。组合证书作用域改为 `number_contract_int_model_pure_forwarder_constant_result`,且根报告固定标注 `full_marqdo_runtime_semantics_proved: false`。这仅证明整数抽象模型上的独立模块组合。完整运行时证明必须新增可执行类型收窄及类型保持定理。 - -另新增 `MarqdoEffects.lean`:把状态、插件异常、未决结果和耗尽 fuel 的循环统一建模,证明异常与未决结果不能充当成功返回;该抽象 ABI 契约仍须具体插件的实现见证,不能由表格声明自动授予。 - - -## M8:组合证书闭包与调用身份加固(2026-11-18) - -`knowledge replay` 现在要求证明证书的 identity 在当前语义工程中**恰好对应一个**可组合的 BoundCall;禁止采用 `find first` 策略选择多个候选中的第一个。调用方与被调用方的 closure 收据必须与重编译得到的**两个精确身份与哈希**集合完全一致:重复、额外注入、缺失、替换记录均拒绝重放。 - -`composition.rs` 新增单元回归测试 `certificate_closures_must_be_exact_and_unique`。这仅加固证书来源绑定,不扩大已证明的运行时语义范围。CI 需以分支最新 head 为准;不同提交上曾经成功的检查不等于本提交已验证。 - - -## M9:合约声明歧义与同模块伪组合防护 - -组合候选现在要求被调函数和调用方各自恰好拥有 **一条** 符合目标常量结果的无条件定理声明。此前使用 `any` 的逻辑可能让两个不同名称、同一结论的声明被当成唯一证据;现在这种情况按歧义处理并拒绝出证。测试在真实的 `.mq.md` 表格中构造两个同结论声明。 - -此外,当前受限组合证明只面向不同源文件的静态导入调用,显式拒绝同文件以及自调用,避免将本地调用伪装成可复用跨模块契约证书。此项是准入安全性改进,不表示抽象插件、分支、循环和递归已经实现具体语义证明。 - -验证仍须以最终提交的 GitHub Actions 为准,尤其关注 `modular-proof-smoke`、`proof` 和 `knowledge-proof-integration`。工作流无作业失败不应解释为单元测试失败或测试成功,必须另行定位 YAML / GitHub Actions 工作流事件层面问题。 - - -## M10:带符号实参的独立模块组合证书(受限整数投影) - -`src/knowledge/projection.rs` 现实现一条**源码驱动、Lean 内核证明、证书可重放**的参数化调用路径: - -- 被调函数在单一返回语句中返回唯一的形参,且该函数必须是无副作用的静态目标; -- 调用方仅直接返回被调调用结果,或将该调用赋给局部变量后立刻返回; -- 支持多个形参及重排后的实参,实参只能是调用方形参或已通过安全静态求值的 i64 常量; -- 被调方声明唯一无条件契约 `结果 = 被投影形参`,调用方声明唯一无条件契约 `结果 = 对应实际形参或常量`; -- 正式构建 `CalleeModule.lean`,以真实返回源生成 `callee_contract`;`CallerModule.lean` 导入前者,经实际实参实例化、以 `simpa [caller]` 得出调用方定理,**不在调用方展开被调实现**; -- `composition-certificate.json` 与源码的唯一符号、精确双依赖闭包、工具链版本、Lean 源和编译产物摘要绑定;重放时从当前 `.mq.md` 重新生成两份 Lean 源并重新执行 Lean; -- 重复函数名、重复语义实体、重名合同结论、未知或不匹配实参、路径条件、控制阻碍、效应函数、同文件调用、动态调度、源码漂移全部拒绝出证或重放。 - -使用既有接口: - -```sh -marqdo knowledge compose --strict --json . -marqdo knowledge replay .marqdo/modular/composed/projection-*/composition-certificate.json --json . -``` - -新增真实 Lean 测试 `projection_composition_proves_symbolic_caller_and_replays_from_source`,以及参数重排/错误结论/重复声明单元测试。专项 CI `modular-proof-smoke` 运行这条路径。 - -**严守边界**:这里的后置条件组合是抽象 Lean `Int` 模型中的`返回等于某个形参`关系,而不是任意谓词、循环不变式、递归归纳或有状态插件契约。Marqdo 的 `int` 声明会归一化到可容纳非整数值的 `number`,故证书显式只给出 `lean_kernel_proved_model`,不能声称动态运行时完全对应。用户定义的插件效应、异常、循环和递归仅有抽象逻辑,不得提升为源码级已证明执行。实现仍处于实验性 Draft,未达到完整通用模块化证明标准。 diff --git a/doc/design/label-freshness-and-repair.md b/doc/design/label-freshness-and-repair.md deleted file mode 100755 index 78e9c66..0000000 --- a/doc/design/label-freshness-and-repair.md +++ /dev/null @@ -1,414 +0,0 @@ -# 纯度路线细化 + 标签过期检测:面向可执行知识体系的一致性机制 - -| | | -|---|---| -| 状态 | **Accepted**(含语法落地、诊断 schema、分阶段计划) | -| 日期 | 2026-10-22 | -| 决策来源 | 用户:取**纯度**;标签**可省略但编译器须报错**;循环写法不重要;**重点:标签过期与 agent 误导** | -| 前置 | [bracket-as-label-evaluation.md](bracket-as-label-evaluation.md) | -| 依托设施 | `src/diagnostics.rs`(`doc_anchor`/`doc_quote`/`contract_ref`)· `src/mlsp.rs`(`validate`/`repair_targets`/`repair_apply`)· `src/repair.rs`(有界修复)· `src/knowledge/fingerprint.rs` · `src/knowledge/lifecycle.rs`(已有 `find_stale`) | - ---- - -## 0. 决策记录与一个推论 - -**已定**: - -1. **纯度**:`()` 只装机器语句,`[]` 只装人话;取元搬进 `()`。 -2. **标签可省略,但编译器报错**:写空方括号是可能的,但那是一个**错误**。 -3. **循环写法从简**:`[]` 已是描述,`()` 内部只要自洽即可。 - -**由此得到一个必须先说清的推论**: - -> **纯度强制两件东西同时存在**: -> ① 一个**不带标签**的普通表达式写法(否则每个访问都被迫配一段人话 = 仪式感复辟); -> ② 带标签的形式作为一个**可选包装**。 - -也就是说 `[标签](表达式)` 不是"唯一的表达式语法",而是"**当你想做断言时才用的包装**"。 -这一条同时解决了我在上一份文档里担心的"标签凑数"退化: -**不想断言,就别用这个形式**——而不是"必须写标签但可以写废话"。 - ---- - -## 1. 纯度路线下的语法落地 - -### 1.1 形式 - -``` -带标签表达式 ::= '[' 人话 ']' '(' 表达式 ')' -``` - -- `表达式` = **现有 Marqdo 表达式文法**(不新增语言) -- `人话` = 任意自然语言,必须是**关于这个值的断言**(§2) -- 出现位置:表达式位置、语句位置、循环位置 - -### 1.2 关键缺口:普通取元怎么写 - -纯度之后 `[键](集合)` 不再是取元,所以必须给出**不带标签的取元写法**。四个候选: - -| 方案 | 写法 | 优 | 劣 | -|------|------|----|----| -| **A 现有内建** | `[第一项](at value=篮子 index=1)` | 零新语法,今天就能实现 | 啰嗦;`value=`/`index=` 是机器腔 | -| **B 后置方括号** | `[第一项](篮子[1])` | 最像通用语言;`篮子[拿铁]` 读起来自然 | `[]` 出现两种角色(前置=人话,后置=索引),视觉易混 | -| **C 函数式 + 逗号参数** | `[第一项](at(篮子, 1))` | 与 `加一函数(31)` 统一;顺带解决前几轮想要的 `f(args)` | 需支持逗号分隔实参(要改参数分词器) | -| D 点号 | `[拿铁价格](菜单.拿铁)` | 短 | 与库路径 `txt.str_trim`、对象方法 `obj.m` 三者同形 | - -**我的建议**:**C**。 - -理由:你前面想要 `f(args)` 这种"人读友好"的调用,而 C 与它**同一个改动**—— -一次性把 `()` 内的表达式升级为「可带括号实参」的形式, -`at(篮子, 1)`、`加一函数(31)`、`get(菜单, 拿铁)` 全部成立,且不新增第二种方括号角色。 -代价是参数分词器要支持 `)` 终止与逗号(前几轮原型已验证方向可行,全量 554/0 回归)。 - -若你希望**零实现风险**,选 A:今天就能用,只是啰嗦,后续可再收窄成 C。 - -### 1.3 空标签 = 硬错误 - -```markdown -[](at(篮子, 1)) # ❌ label.missing -``` - -诊断:`code: "label.missing"`,`severity: error`,`doc_quote: "[]"`,建议: -「给这段语句写一句人话描述,或改用不带标签的普通表达式」。 - -**这一条是整套设计的门槛**:它把"标签"从可选装饰变成"用了就得负责"的承诺。 -也正好落实你说的「可以省略,但编译器应当报错」。 - -### 1.4 循环 - -你说不重要,那我给最省事、且与纯度一致的一条: - -```markdown -- [从篮子取出的每个果子](foreach 篮子 为 果) -``` - -- `[]` 是描述(人读) -- `()` 是机器语句:遍历什么、绑定给谁 -- 循环变量名从 `[]` **搬进 `()`**——因为 `[]` 不再承担绑定职责 - -若嫌 `foreach 篮子 为 果` 太新,可就近用现有词: -`- [从篮子取出的每个果子](遍历 篮子 绑定 果)`。 -**关键是别再让 `[]` 兼任变量名**——否则"描述"与"标识符"又会打架。 - ---- - -## 2. 标签是什么:**可校验断言的载体** - -标签不是注释。三者区别: - -| | 注释 | 标签 | -|---|------|------| -| 位置 | 游离于代码之外 | **锚定在 AST 节点上**(有 span,可定位) | -| 可核验 | 不能 | **能**(§3) | -| 可进修复协议 | 不能 | **能**(随诊断导出给 LLM) | -| 变更感知 | 无 | **能**(代码变了会撞上旧断言) | - -一句话:**标签 = 贴在可执行片段上、可被机器复核的断言。** -这正是 Marqdo 相对传统"文档 + 注释"的核心增量。 - ---- - -## 3. 过期检测:三层机制 - -你问的核心是:**`()` 改了,怎么让 `[]` 的旧描述"叫起来"。** -这需要三种能力,缺一不可,且分属不同层。 - -### 3.1 L1 引用一致性(无状态、确定性、零成本) - -**规则**:标签内用反引号写出的名字 = **实体断言**。 - -```markdown -[按 `税率` 计算总价](...) -``` - -可核验的断言: - -1. `` `税率` `` 必须**可解析**(在当前作用域/模块里存在) -2. 它必须**出现在 `()` 的实际内容中**(或经调用链可达) - -任一条不成立 → `label.stale`(引用已腐烂)。 - -**为什么低假阳性**:只有**显式反引号**才算断言,普通汉字不参与判定。 -这复用了 Marqdo 已有的 `` `名` `` = 实体 的约定,**没有新增记号**。 - -**局限(必须承认)**:它只查"引用",查不出"语义"。 -`税率` 还在,但操作从"乘"改成"除",L1 看不见。 - -### 3.2 L2 指纹台账(有状态、能查语义腐烂) - -**做法**:把「标签写下时,它描述的那段代码」记一份指纹。 - -`.marqdo/labels.json`(与 EKC 产物同目录,视为**缓存**): - -```json -{ - "按税率计算总价#1": { - "code_fingerprint": "9f2a…", - "code_quote": "at(税率表, 档位) * 金额", - "confirmed_at": "2026-10-22T09:00:00Z" - } -} -``` - -- `code_fingerprint`:复用 `src/knowledge/fingerprint.rs`(已有 `collect_calls` / `ops_hint` / `fingerprint_hash`) - → **调用与运算变了,指纹就变** -- `code_quote`:**旧代码的文本快照**——这就是你说的"保留内容用于校验"的对称物: - `doc_quote` 保留 `[]`,`code_quote` 保留 `()`,两者一起导出给 LLM 对比 -- 键 = `规范化标签文本 + 同文本序号`(按标签键而不是按行号,**移动代码不会误报**) - -**命中规则**: - -| 变化 | 判定 | -|------|------| -| `()` 指纹变 | **stale**:标签描述的代码已变,需复核 | -| 标签文本变 | **新断言**:无历史,首次确认即可 | -| 两者都没变 | 通过 | - -**局限**:需要状态文件;合并冲突要处理(§8.2)。 - -### 3.3 L3 LLM 复核(修复协议闭环) - -诊断被导出时同时携带三方信息: - -- `doc_quote`:`[]` 里的原话 -- `code_past`:`()` 当时的文本(来自台账) -- `code_now`:`()` 现在的文本 - -模型据此判定三选一: - -1. **改标签**(代码意图是对的,描述过期了) -2. **改代码**(描述是对的,实现跑偏了) -3. **确认无害**(改动不影响断言,写回台账 `confirmed`) - -这正好接进**已有的修复回路**(`src/repair.rs`):`validate` → `repair_targets` → 模型行编辑 → -`repair_apply`(越界必拒)→ 复验。 - -### 3.4 为什么三层都要 - -| 层 | 查什么 | 能否查"乘改除" | 需要状态 | 假阳性 | -|----|--------|--------------|---------|--------| -| L1 | 引用腐烂(改名/删除) | ❌ | 无 | 极低 | -| L2 | 语义腐烂(同引用、不同操作) | ✅ | 需台账 | 中(无害改动也报) | -| L3 | 谁错了(标签 or 代码) | ✅ | 复用 L2 | 由模型判 | - -**L1 是地基**(确定性、零成本、可先上),**L2 是覆盖**(能查语义),**L3 是裁决**(谁改)。 - ---- - -## 4. 与现有设施的对接(这决定了落地成本) - -### 4.1 诊断字段:**已经齐备,不需要新造** - -`src/diagnostics.rs` 的 `to_json` 已输出: - -```json -{ - "code": "…", "severity": "…", "message": "…", - "span": {"file":…, "line":…, "col":…}, - "doc_anchor": …, ← 标签位置 - "doc_quote": …, ← 标签原文 - "contract_ref": {"unit":…, "kind":…, "name":…, "declared":…}, - "suggestion": … -} -``` - -**`contract_ref.declared` 就是"声明"这一侧的先例**: -契约诊断说的是「**declared** number,actual text」, -标签诊断说的是「**declared(标签里的人话)**,actual(`()` 现在的代码)」—— -**同一个模式,只是从类型层下沉到散文层。** - -> 这也回答了你的问题:"导出时能否保留 `[]` 的内容用于校验"—— -> **能,而且字段已经在协议里了**:`doc_quote` 就是它。 - -### 4.2 契约诊断是现成的范式 - -`src/contract.rs:203` 的 `Contract::diagnostic(...)` 一次性装配 -`code + severity + suggestion + doc_anchor + doc_quote + contract_ref`。 -标签诊断可以照抄这套装配,只是 `kind` 从 `"contract"` 换成 `"label"`。 - -### 4.3 修复范围:允许"标签行 ∪ 代码行" - -现在 `repair_apply` 的形状是 `ranges: [[起, 止], …]`,**天然支持多个区间**。 -`label.stale` 只需把两段都放进 ranges: - -| 允许范围 | 原因 | -|---------|------| -| 标签所在行 | 修法 1:改描述 | -| `()` 所在行 | 修法 2:改实现 | - -护栏不变:**越界改动一律拒绝(abstain)**——这正是 `src/repair.rs` 已经强制的语义。 - -### 4.4 知识层:`stale` 概念已经存在 - -`src/knowledge/lifecycle.rs` 已有 `find_stale` / `stale_json` / `verify`。 -标签过期可以走**同一条 stale 通道**,进入 EKC/OKF 的 -`marqdo verify` / `marqdo stale` 报告,成为知识库的健康指标。 - -> 这一点很重要:**标签过期 = 知识腐烂**,而 Marqdo 已经有"知识会腐烂"的机制, -> 标签只是给它增加了一种新的腐烂类型(文档断言 vs 实现)。 - ---- - -## 5. 诊断 schema 草案 - -```json -{ - "code": "label.stale", - "severity": "warning", - "message": "标签可能过期:标签提到 `税率`,但当前语句已不再引用它", - "span": { "file": "报价.mq.md", "line": 42, "col": 12 }, - "doc_anchor": { "file": "报价.mq.md", "line": 42, "quote": "按 `税率` 计算总价" }, - "doc_quote": "按 `税率` 计算总价", - "label_ref": { - "kind": "label", - "text": "按 `税率` 计算总价", - "refs": ["税率"], - "missing_refs": ["税率"], - "code_past": "at(税率表, 档位) * 金额", - "code_now": "at(税率表, 档位) / 金额", - "fingerprint_past": "9f2a…", - "fingerprint_now": "3c71…", - "layer": "L2" - }, - "suggestion": "若意图是乘,请还原 `*`;若意图改为除,请把标签改成「按档位折算比例」", - "ranges": [[42, 42]] -} -``` - -要点: -- 复用 `doc_anchor` / `doc_quote`,**不新造字段名** -- `label_ref` 仿 `contract_ref`(`kind: "label"`) -- `code_past` / `code_now` 并置 → 模型一眼看出差异 -- `layer` 标明是 L1 还是 L2 检出(便于分级治理) - ---- - -## 6. 工作流 - -``` -作者 / agent 改代码 - ↓ -marqdo check 或 MLSP validate - ↓ -label.stale / label.missing 诊断(带 doc_quote + code_past + code_now) - ↓ -MLSP repair_targets(ranges = 标签行 ∪ 代码行) - ↓ -LLM 三选一:改标签 / 改代码 / 确认无害 - ↓ -repair_apply(越界必拒) - ↓ -复验 → 通过后写回 .marqdo/labels.json(confirmed_fingerprint 更新) -``` - -**CI 用法**: -- 普通项目:`label.stale` 默认 **warning**(不阻塞) -- 知识库项目(OKF/EKC 仓):可配置为 **error**,把"断言必须新鲜"作为门禁 - ---- - -## 7. 反幻觉:这一步到底解决了什么 - -必须把话说准,否则容易过度承诺。 - -### 7.1 它解决的**具体一类** - -> **文档断言与实现不一致**(doc–code drift at the claim level)。 - -传统文档的失败模式: - -| 失败模式 | 传统文档 | Marqdo(本设计) | -|---------|---------|-----------------| -| 注释过期 | 无声腐烂 | L1/L2 检出 | -| 签名漂移 | 靠类型检查(有) | 契约已有 | -| **散文描述与实现不符** | **完全无解** | **本设计**(新能力) | -| 知识库引用失效 | 靠人工审阅 | 可机械化 | - -### 7.2 它**不解决**什么 - -- 模型凭空编造(幻觉的另一种) -- 代码本身写错 -- 标签写得含糊但"不算错"(L1 查不到,L2 只能报"变了") - -**所以正确的表述是**: -> 它把"**文档可信度**"从"靠人自觉"提升到"**可被机械复核 + 可被 LLM 裁决**"。 - -### 7.3 为什么这对"可执行知识体系"是决定性的 - -一个知识库的价值 = **断言的密度 × 断言的可信度**。 -传统知识库只能提高密度(多写),无法保证可信度(写完就腐)。 -Marqdo 若能把"断言→复核"闭环,就第一次让**知识库有了保鲜机制**—— -这也正好接上 EKC 已有的 `stale` / `verify` 体系。 - ---- - -## 8. 风险与反对意见(诚实清单) - -### 8.1 误报疲劳(最危险) - -如果 `label.stale` 天天响,用户会在三天内学会忽略它。 -**对策**: -- L1 **只在能证明冲突时报**(引用了不存在的实体 / 引用的实体不在语句里) -- L2 **默认只报 warning**,且同一标签同一指纹只报一次(台账记录"已复核") -- 诊断里必须给**可执行建议**(改哪一行、改成什么),否则就是噪音 - -### 8.2 台账的腐烂与合并冲突 - -`.marqdo/labels.json` 是缓存,不是真相。对策: -- 语义上**可丢弃**:删掉后重建,最多一次全量确认 -- 合并冲突策略:**重算优先**(以代码指纹为准,冲突时保留 `confirmed_at` 较新者) -- 不放进版本库时(`.gitignore`),退化为"本地提示";放进版本库时,成为团队级门禁 - -### 8.3 语义鸿沟 - -L1 只能查引用;标签写"算总价"而代码改成了"算单价",若两者都引用 `税率`,L1 沉默。 -**这是 L2 存在的理由**,也是必须承认的能力边界。 - -### 8.4 LLM 修标签可能引入新幻觉 - -"用幻觉修幻觉"是真风险。对策: -- 护栏:**只允许改标签行或代码行**(`repair_apply` 已强制) -- 修改必须**双向可逆**:诊断里给出"过去/现在"两侧,让模型做**判定**而不是**创作** -- 知识库仓建议:L2 级修改需人工确认(`--confirm`) - -### 8.5 标签不得参与安全判定 - -这是我在上一份文档里提的、也是你关心的"agent 误导"的另一面: -**如果沙箱/权限判定读标签,那标签就成了攻击面。** -硬约束:**策略、沙箱、工具白名单只读 `()` 的语义,永不读 `[]`。** -标签只服务于"人读"与"AI 复核",不服务于"机器授权"。 - -### 8.6 成本 - -每标签一次指纹计算与比对。可增量:只对**本次变更的文件**做 L2 校验 -(与 EKC 的增量编译一致)。 - ---- - -## 9. 分阶段落地 - -| 阶段 | 内容 | 依赖 | 风险 | -|------|------|------|------| -| **P0** | 纯度语法:`[标签](表达式)` + `label.missing` + 普通取元(A 或 C) | 解析器 | 中(506 处迁移) | -| **P1** | L1 引用一致性 + `label.stale` 诊断(无状态) | 诊断字段已有 | 低 | -| **P2** | 诊断 schema + MLSP ranges 并集 + 修复回路 | `mlsp.rs` / `repair.rs` | 低 | -| **P3** | L2 指纹台账 + 增量校验 | `fingerprint.rs` | 中 | -| **P4** | L3 LLM 复核 + `confirmed` 写回 + CI 门禁 | P2+P3 | 中 | - -**建议先做 P1**:它零状态、确定性、能立刻抓住"引用了不存在的东西"这类最硬的腐烂, -且不依赖纯度迁移——可以在旧语法上先验证"标签断言"这个概念是否好用。 - ---- - -## 10. 待你决策 - -1. **普通取元选 A(`at value=… index=…`,零新语法)还是 C(`at(篮子, 1)`,需逗号参数)?** -2. **L1 的断言规则**:只认标签内的反引号 `` `名` ``,还是也认"与代码标识符同名"的中文词? - (只认反引号更准;认中文词更聪明但假阳性高) -3. **台账位置**:`.marqdo/labels.json`(默认忽略)还是纳入版本库(团队门禁)? -4. **`label.stale` 默认级别**:warning(推荐)还是 error? -5. **是否先只做 P1**(在旧语法上验证"标签断言"概念),再决定纯度迁移? - -> 我的建议顺序:**P1 → P2 → P0 → P3 → P4**。 -> 先在旧语法上把"断言 + 复核 + 修复回路"这条链路跑通(它不依赖纯度), -> 再动 506 处迁移——这样即使纯度路线最后要调整,一致性机制也已经沉淀下来了。 diff --git a/doc/design/layers.md b/doc/design/layers.md deleted file mode 100755 index 84185d9..0000000 --- a/doc/design/layers.md +++ /dev/null @@ -1,29 +0,0 @@ -# 三层归属与准入戒律(layers) - -| | | -|---|---| -| 状态 | **Accepted · 准入制度(问题一落地)** | -| 日期 | 2026-09-22 | -| 相关 | [core-surface.md](core-surface.md)(核心表面守卫)· [three-problems.md](../roadmap/three-problems.md) 问题一 · [three-problems-plan.md](../roadmap/three-problems-plan.md) T1.2 | - -> **目的**:语言核心保持小——**Language / Runtime / Document 三层分明,生态功能不淹没语言身份**。本制度是机制不是宣言:违反即 CI 红 / PR 不评审。 - -## 1. 三层归属表 - -| 层 | 内容 | 仓库位置 | -|----|------|----------| -| **Language** | 标记映射、词法/行分类、AST、语义、升参、契约检查器、诊断 | `src/lex/` `src/parse/` `src/ast.rs` `src/interp.rs` `src/diagnostics.rs`(及 `contract`/`check`)· 宪法 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [core-surface.md](core-surface.md) | -| **Runtime** | stdlib、插件 ABI、WASM、debugger、view、catalog / schema / mcp CLI、字节码后端 | `lib/` `plugins/` `crates/` `src/catalog.rs` `src/view/` `src/debug/` `src/builtin.rs` `src/bytecode/` | -| **Document** | 知识单元、AI skills、示例、官方扩展、用户站 | `*.mq.md` `skills/` `ext/` `public/` `examples/` `doc/` | - -## 2. 准入戒律 - -1. **先填层归属**:任何新特性提案(issue / PR / 设计文档)必须先声明进哪层;未填 = 不评审。 -2. **Language 层变更 = ADR**:新增核心标记必须有 `doc/adr/` 编号 + 「为什么现有标记不够」+ [core-surface.md](core-surface.md) 增行 + 样例 + `CORE_CONSTRUCTS` 同步(缺任一 → CI 守卫红)。 -3. **核心计数只许持平或下降**:每个 release 的核心标记计数不得增长;确需增长即触发 Language 层复盘(ADR 里写明不可替代理由)。 -4. **默认进 ext**:能用扩展、stdlib、插件解决的,一律不进核心。 -5. **CHANGELOG 单列「核心表面 Δ」**:每个 release 写明增删(无 Δ 写「无」);发版 checklist(`.cursor/skills/marqdo-release/SKILL.md`)含此步。 - -## 3. PR 模板 - -`.github/PULL_REQUEST_TEMPLATE.md` 含「层归属」必填项与「核心表面」勾选——与本制度一一对应。 diff --git a/doc/design/lib-code-as-docs.md b/doc/design/lib-code-as-docs.md deleted file mode 100755 index ab3fd17..0000000 --- a/doc/design/lib-code-as-docs.md +++ /dev/null @@ -1,69 +0,0 @@ -# 标准库 / 扩展库:代码即文档 - -当前可执行开发规范见[库开发指南](../library-development.mq.md),其中的真实函数示范叙述内赋值、遮蔽调用、表格数据与返回。本页保留设计背景与历史波次。 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-09-14 | -| 相关 | [code-as-docs-gaps.md](code-as-docs-gaps.md) · [bracket-call-modifiers.md](bracket-call-modifiers.md) · [collection-access-link.md](collection-access-link.md) · [stdlib.md](stdlib.md) · [marqdo-dev skill](../../.cursor/skills/marqdo-dev/SKILL.md) · [roadmap](../roadmap/lib-ext-code-as-docs.md) | - ---- - -## 1. 目标 - -`lib/*` 与 `ext/*` 的 `.mq.md` 应**可当说明书读、可当程序跑**。薄库用充分且具体的叙述解释短实现;厚领域库(web / quantum / …)仍用叙述承载意图,但数据与调用面与用户程序同一套标记。 - -## 2. 单文件标准库模板 - -标准库通常是一个 `lib/*.mq.md` 文件,源码自身承担使用手册、开发说明与 SKILL。 -直接阅读、导入或调用此文件,不增加强制 `index.mq.md` 或平行模块手册。 -多文件拓展库才用 `index.mq.md` 组织模块与开发路线。 - -每个函数依次提供:标题、参数表(名称、类型、默认值、含义)、返回契约、效应说明、 -叙述形参、用途与真实调用例子、简短实现。无参数函数直接放返回表。 -参数和返回契约位于第一条执行语句之前;标准库不再保留旧 `+` 形参清单。 - -叙述形参使用正文中的反引号名称,默认值紧跟等号;表格说明与实际默认值必须一致。 -例如正文写「输入路径 `path`」,调用时即可提供 path。含标点的文本默认值使用完整引号。 -不透明类型保留渐进式 any,并说明其产生途径和限制。 - -## 3. 可读性与调用规范 - -每个函数单元的叙述比例必须超过 50%,同时说明真实用途和边界;不能靠重复套话凑比例。 -参数和返回契约表属于文档面,绑定的数据表仍须表达真实数据。 - -宿主等不透明调用用遮蔽语法表达动作:`[]` 写做什么,`()` 写实际执行代码。 -返回和赋值仍遵循原有标记;标签不执行,也不替代失败处理。 - -```markdown -## read_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | 必填 | 授权根目录内的文件路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | UTF-8 文本;无效编码或读取失败产生诊断 | - -输入路径 `path`。此操作读取整个文件;大文件应改用分块读取。 -文件根目录由调用方授权,不能通过传入路径绕过权限。 - -读取完成后,我们返回*[读取授权范围内的 UTF-8 文本](> host_read_text path=`path`)*,供调用方继续处理。 -``` - -集合读取使用 access(collection, key),不使用旧链接取元;循环使用显式遍历。 -用 GFM 表和具名助手表达结构化数据,避免 json.set/json.append 链。 -说明中的调用示例放在未绑定代码围栏内,不能让示例意外成为函数执行步骤。 -中英文源码保持语义、默认值与行为一致;检查叙述比例、契约并执行真实示例。 - -## 4. 波次 - -见 [roadmap/lib-ext-code-as-docs.md](../roadmap/lib-ext-code-as-docs.md):先稳定调用表面,再 M1 试点 table/text/json,其后批次 lib → ext。 - -## 5. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-14 | 初稿(随括号调用落地) | diff --git a/doc/design/link-style-call-evaluation.md b/doc/design/link-style-call-evaluation.md deleted file mode 100755 index c244380..0000000 --- a/doc/design/link-style-call-evaluation.md +++ /dev/null @@ -1,218 +0,0 @@ -# 方案评估:Markdown 链接式调用 `[函数名](参数…)` - -| | | -|---|---| -| 状态 | **Proposed · 已被 [paren-call-and-readable-invocation.md](paren-call-and-readable-invocation.md) 取代** | -| 日期 | 2026-10-22 | -| 提出 | 用户:「markdown 的链接语义似乎很适合做这种操作」 | -| 相邻 | [spaced-function-names-d8.md](spaced-function-names-d8.md)(方括号调用 + 空格) | -| 影响面 | **核心解析**:`[key](coll)` 链接索引与调用语法冲突 | - -> **后续更正**:本文的 L1–L4 方案列表把问题当成「表/语义」来讨论,偏离了用户原意。 -> 用户问的是**调用写法**本身。最新评估(含原型实测 554/0 回归)见 -> [paren-call-and-readable-invocation.md](paren-call-and-readable-invocation.md): -> 方括号确实不可行(2 个真实冲突文件),但**去掉方括号的 `f(args)` 是空闲语法且可行**。 - ---- - -## 0. 一句话结论 - -**语法本身很优雅,但它与既有特性「链接索引 `[key](map)`」正面冲突。** -冲突不是「难实现」,而是「同一个写法要表示两种语义」。 -建议**不要**把它做成调用的主形式;若要引入,只能作为**受限变体**(见 §4)。 - ---- - -## 1. 现状事实(实测) - -### 1.1 `[…](…)` 目前是链接索引 - -```markdown -**m = > json.parse text={"a":1}** -**v = [a](m)** # 取 map 的 a 成员 -> print text=`v` # → 1 -``` - -这是 v0.3 的**正式特性**,文档里写作「集合取元优先 `[键](集合)`」。 -实现有专门入口 `parse_link_index`,并由 `link_index_shape_ahead` 判定: - -> `[` … `]` 后面紧跟 `(` → **链接索引** - -### 1.2 提议的写法今天会怎样 - -```markdown -## greet - + `who` - -*"hi " + `who`* - -# main - -**r = [greet](alice)** -``` - -实测: - -``` -error: l2.mq.md:12:1: undefined variable `alice` -``` - -因为它被当作链接索引 `[greet](alice)`:拿 `alice` **当变量名**去查, -查不到就报错。也就是说**链接索引已经把这块语法占满了**。 - -### 1.3 歧义判定只有一行 - -```rust -fn link_index_shape_ahead(s: &str) -> bool { - // '[' … ']' 后紧跟 '(' → 链接索引 -} -``` - -任何 `[X](Y)` 都会走链接索引,没有例外。 - ---- - -## 2. 为什么这个提议有吸引力 - -先说我认可的部分,避免低估它: - -1. **视觉语义准确**。Markdown 里 `[文本](目标)` 的直觉是「链接一个东西到另一个」。 - 调用 `[greet](alice)` 读作「调用 greet,指向 alice」,对非程序员也直观。 -2. **参数在括号里,边界清晰**。相比 `> greet alice`(空格切词), - `(alice bob)` 的边界是**显式**的 —— 这恰好是 D8「带空格函数名」痛点的天然解药。 -3. **与 Markdown 完全兼容**。`[a](b)` 是合法链接写法,编辑器不会标红。 - -**但**:这些优点必须在「不破坏链接索引」的前提下才能兑现。 - ---- - -## 3. 冲突分析 - -### 3.1 根本矛盾 - -| 写法 | 链接索引语义 | 调用语义 | 能否并存 | -|------|-------------|---------|---------| -| `[a](m)` | 取 `m` 的成员 `a` | 用参数 `m` 调用 `a` | **看内容才知道** | -| `[greet](alice)` | 取 `alice` 的成员 `greet` | 用 `alice` 调用 `greet` | 同上 | - -**两者形状完全一致**,区别只在「`greet` 是函数还是键名」「`alice` 是集合还是实参」—— -这需要**符号表信息**,而语法判定发生在解析期(此时未必知道有哪些函数)。 - -### 3.2 用「函数表已知」来消歧能行吗 - -理论上:若 `greet` 是已定义函数 → 调用;否则 → 链接索引。 - -**问题**: -1. **跨模块不可知**:`[lib.greet](x)` 需要 import 结果,词法/语法期拿不到。 -2. **名字冲突**:如果既有 `greet` 函数,又有 map 里叫 `greet` 的键,语义就靠猜。 -3. **错误信息会变差**:本意是链接索引但键不存在时,会被误判成调用, - 报 `unknown function` 而不是 `missing map key` —— 把清晰错误变成误导错误。 -4. **修改即破坏**:今天所有 `[键](集合)` 写法都要进符号表做一次判定, - 这是**全量语义变更**,不是增量特性。 - -### 3.3 冲突的严重度 - -链接索引是 v0.3 **明确推广**的写法(「集合取元优先 `[键](集合)`」), -仓库里大量使用。让调用去抢这块语法,等于**用新特性侵蚀既有特性**。 - ---- - -## 4. 可选的受限方案 - -### 方案 L1 — 参数列表必须「非单个标识符」(不可靠,不推荐) - -仅在 `(…)` 内含**分隔符**时判为调用,如 `[greet](alice, bob)`。 - -- 优点:`[a](m)` 单参数时保留链接索引语义 -- **致命缺陷**:`[greet](alice)` 这种最常见的单参数调用无法表达; - 而 `[greet](a, b)` 又和「链接索引 + 逗号」冲突。**语义随参数个数漂移**,最坏的一类设计。 - -### 方案 L2 — 独立标记前缀(可行,但失去「链接感」) - -```markdown -> [call]greet(alice) # 或 @greet(alice) -``` - -- 优点:零歧义 -- 缺点:前面多了标记,就不再是「Markdown 链接」了,失去了提议的全部吸引力 - -### 方案 L3 — 方括号调用 + 括号参数(**推荐**) - -保留既有的方括号调用形式,但允许**参数写在括号里**: - -```markdown -> [加一 号](n=1) # 具名参数 -> [加一 号](1) # 位置参数 -> [greet](alice bob) # 多参数 -``` - -关键:**`]` 后面跟 `(` 时仍优先判为链接索引**—— -除非方括号内是「已知的函数名形状」且**调用上下文**成立。 - -等等,这与 §3 的矛盾相同。**所以 L3 的真正形态是**: - -```markdown -> [加一 号] (n=1) # 方括号与括号之间有空格 → 调用+参数组,不是链接 -``` - -用「`]` 与 `(` 之间是否有空格」消歧: -- `[key](coll)`(紧贴)→ 链接索引(**既有语义完全不变**) -- `[callee] (args)`(有空格)→ 调用,参数为一组 - -- 优点:**零歧义**、**零回归**(紧贴形式完全不动)、保留了「括号包参数」的可读性、 - 顺带解决 D8 的空格函数名 -- 缺点:视觉上 `] (` 有个空格,略不自然;但 Markdown 渲染不受影响 - -### 方案 L4 — 不在语法层做,在文档层说明(保守) - -明确「链接索引是取元,不是调用」,调用一律用 `> callee args` 或 `> [callee] args`。 -`[函数名](参数)` 留作**不做**。 - ---- - -## 5. 方案对比 - -| 方案 | 歧义 | 回归风险 | 保留「链接感」 | 解决 D8 | 推荐 | -|------|------|---------|--------------|---------|------| -| L1 参数需含分隔符 | **高**(随参数个数漂移) | 中 | 部分 | 否 | ❌ | -| L2 独立前缀 | 无 | 无 | **否** | 是 | 备选 | -| **L3 空格消歧** | **无** | **无** | 大部分 | **是** | ✅ | -| L4 不做 | 无 | 无 | 否 | 否 | 退路 | -| 直接抢 `[x](y)` | **不可解** | **高** | 是 | 是 | ❌ | - ---- - -## 6. 我的建议 - -1. **不要**把 `[函数名](参数)` 直接定为调用——它和链接索引形状相同,无法可靠消歧。 -2. 采纳 **L3**:`[callee] (args)`(中间有空格)作为「带括号参数组的调用」, - 紧贴的 `[key](coll)` 语义**一字不动**。 -3. 这样同时满足: - - 「完全兼容 Markdown」(`[x](y)` 仍是链接语义) - - 参数边界显式(括号括起来) - - D8 的空格函数名(方括号内允许空格) -4. 若你觉得 `] (` 的空格不好看,退一步选 **L2**(`> callee(args)` 这种函数式写法), - 牺牲链接感换取零歧义。 - ---- - -## 7. 若采纳 L3 的验证计划 - -| 编号 | 用例 | 期望 | -|------|------|------| -| L3-1 | `[a](m)` 紧贴 | 链接索引,取成员(**不变**) | -| L3-2 | `[greet] (alice)` 有空格 | 调用,`alice` 作为位置参数 | -| L3-3 | `[加一 号] (n=1)` | 调用带空格名函数,返回 2 | -| L3-4 | `[greet] (a b)` | 两个位置参数 | -| L3-5 | `[a](m)` 中 `a` 恰好也是函数名 | **仍走链接索引**(紧贴优先) | -| L3-6 | `> print text=(礼貌 [问候] x)` | 内嵌方括号不受影响 | -| L3-7 | 全量 `cargo test` | 554 全绿 | -| L3-8 | 全仓库 `.mq.md` 回归 | 无变化(紧贴形式未动) | - ---- - -## 8. 待你决策 - -1. **选 L3、L2、还是 L4?** -2. 若选 L3:`] (` 的空格你能接受吗?(渲染上无差别,源码里能看见) -3. 是否同时支持全角 `【函数名】(参数)`?与 D2 全角冒号问题一致考虑。 diff --git a/doc/design/link-syntax.md b/doc/design/link-syntax.md deleted file mode 100755 index e9fb3dc..0000000 --- a/doc/design/link-syntax.md +++ /dev/null @@ -1,799 +0,0 @@ -# 链接语法:命名载荷、类-函数调用与可执行知识 - -| | | -|---|---| -| 状态 | **Design Review · v2.1 语义重构(v2.0.0 仅实现本地表达式链接)** | -| 日期 | 2026-10-23 | -| 定位 | `[]()` **不新增语法**:它是 Markdown 链接 + 已有表达式 + 已有 `#`/`##` 类/函数模型的组合;它为任意既有载荷附上人话名称,并产出 view/compiler/知识图元数据 | -| 取代/扩展 | 取代 [occlusion-syntax.md](occlusion-syntax.md) 的「遮蔽」单一框架;把「遮蔽」保留为**显示属性** | -| 证据复核 | [occlusion-vs-executable-knowledge-2026-10.md](../research/occlusion-vs-executable-knowledge-2026-10.md) | -| 示例 | [examples/link-syntax/](../../examples/link-syntax/) | -| 关联 | [knowledge-layers.md](knowledge-layers.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [engineering-knowledge.md](engineering-knowledge.md) · [view.md](view.md) | - ---- - -## 0. 设计声明 - -### 0.1 一句话 - -> **`[]()` 本身不制作新语法。** -> `[]` 是 Markdown 链接的可见文本;`()` 是**已经存在的 Marqdo 代码**,与 `**代码**` 同权。 -> `#` 是类,`##` 是函数;`类.函数` 就是类调用。 -> 链接把「一次已有载荷」写进文档,并为它附上一个人话名称;view 显示步骤与依赖,编译器返回链接信息。 - -### 0.1.1 还缺的一步:链接是「命名的可执行步骤」 - -`()` 可以是任意既有语法:取元、计算、调用、表操作、嵌套表达式或遍历/循环载荷。 -所以 `[]()` 不能只被定义成“事实主张 + 函数调用”;那会把通用语法割裂在知识体系之外。 - -> **`[名称](载荷)` 是命名的可执行步骤:`()` 按原语义执行,`[]` 说明这一步对人意味着什么;编译器把整个步骤写入知识图。** - -它始终同时有三种投影: - -| 投影 | 规则 | 目的 | -|------|------|------| -| **代码投影** | `execute([label](payload)) = execute(payload)` | 与裸 payload 共用 parser/evaluator,结果、效果和执行代价不变 | -| **文档投影** | 保留 `label` 与所在句子/代码块 | 读者先读每一步的意图,必要时再展开实现 | -| **知识投影** | 产出 `KnowledgeStep { label, kind, inputs, outputs, dependencies, effect, span }` | 让取元、计算、循环、调用和叙述都可检索、解释、验证和影响分析 | - -`label` 不进符号表、不改变作用域,也不替 `payload` 背书为“事实”;但它绝不是可丢弃的显示文字。 -它是这段代码的人话接口。`payload` 提供操作,`label` 提供意图,二者共同形成可执行知识步骤。 - -例如: - -```markdown -**name = [订单收件人](at(订单, "收件人"))** -**gross = [含税金额](金额 * (1 + 税率))** -- [逐个订单行](遍历 订单.行 为 行) -订单总额为[含税总价](定价.订单定价.含税总价(订单))。 -``` - -它们分别是观测、推导、过程和叙述调用;四者使用同一个 `[]()`,在运行时都复用已有载荷语义, -但在图中拥有不同的输入/输出/依赖/效果边。只有一条步骤最终支撑对外事实时,才沿其依赖链要求来源; -不能要求每一次取元或循环都伪造来源表。 - -这才同时实现三件事: - -- **代码即文档**:函数内部的每一步都有可读意图,不是一个黑盒; -- **文档即代码**:正文中的命名步骤能解析到实际依赖和可选值; -- **知识即可执行**:项目中任意代码步骤都是统一知识图的一部分,来源/规则/函数变化可反查到具体步骤和句子。 - -完整的跨文件闭环、稳定寻址和层次投影见 -[executable-knowledge-system.md](executable-knowledge-system.md)。 - -### 0.2 三个「不新增」 - -| 不新增 | 说明 | -|--------|------| -| **不新增链接专用协议前缀 / 别名** | `()` 里就是普通表达式/调用;跨文档代码复用现有 `import bind:target`,正文可用唯一短地址发现 | -| **不新增执行开关 / 模式关键字** | 不引入 frontmatter 别名或执行开关;解析靠已有类/函数/文档结构 | -| **不新增括号 / 标记** | 不引入 `[[...]]` / `@[...]` / `link:`;`[]()` 仍是 Markdown 链接形 | - -**本文定义四件事**: - -1. **语义**:`#`/`##` 如何形成类/函数,`类.函数` 如何成为类调用;`label` 如何命名任意既有载荷并形成知识步骤; -2. **解析**:`()` 与 `**代码**` 共用 parser/evaluator;跨文档按类索引解析; -3. **校验**:步骤的输入、输出、依赖、效果与来源边分开记录;变更后能定位受影响的代码和句子; -4. **呈现**:view 显示调用点与证据;编译器返回 LinkInfo;EKC 建边;lock 可选。 - -> **作者不需要学习新标记**:正文链接仍是 `[描述](...)`;`view`/`check` 多了一项「把 payload 解析成类/函数」的能力,而不是要求作者写协议前缀、别名或执行开关。 - -### 0.3 原始意图 - -第一个可执行文档: - -```markdown -# 李白 - -这个文档存储了李白的信息。 - -## 李白的出生年份 - -李白出生于*某年* -``` - -在 Marqdo 里: - -- `# 李白` = **类**; -- `## 李白的出生年份` = 该类下的**函数**; -- `李白.李白的出生年份` = **类调用这个函数**。 - -> 注意:正文「李白出生于*某年*」是**叙述**;函数要可调用,需要显式返回值(`*701*` 或表,见 §2.6)。 - -第二个文档: - -```markdown -# main -用户想要知道李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) -``` - -`[]` 是描述,`()` 是已有调用 `李白.李白的出生年份`。它不需要 `print`: -**view 模式天然显示 `()` 的调用信息**。如果要终端输出,加一行 `print` 即可: - -```markdown -**year = [李白的出生年份](李白.李白的出生年份)** -> print text=`year` -``` - -这不是两套语法,而是同一套语法的两种呈现: - -- `**year = 李白.李白的出生年份**` 是代码; -- `[李白的出生年份](李白.李白的出生年份)` 是**带描述的同一段代码**; -- `[描述](...)` 唯一新增的是「描述」与「view/compiler 元数据」,不是执行规则。 - -### 0.4 当前实现的偏差 - -v2.0.0 把「类-函数」收窄成了「实例方法」: - -| 设计意图 | 当前实现 | 后果 | -|----------|---------|------| -| `# 李白` 是类 | `# 李白` 是对象/类型 | 可以,但 `##` 被当成实例方法 | -| `## 李白的出生年份` 是函数 | `##` 是实例方法,需要 `self`/接收者 | `李白.李白的出生年份` 被拒绝 | -| `类.函数` 是类调用 | 必须 `> 李白` 构造实例,再 `obj.函数()` | 多一步实例化,知识不能直接调用 | -| 跨文档按类名链接 | 裸类名不解析,必须 `import` + 绑定 | 第二个文档的链接是 `undefined variable` | -| 链接是「命名载荷 + 已有语义」 | 被收窄成「遮蔽/本地表达式」 | 取元/循环/调用的步骤图、跨文档链接、view 依赖信息缺失 | - -这正是「功能被阉割」的地方:**不是 `[]()` 不够,而是 `#`/`##` 的调用语义被实现成了实例方法,跨文档类索引没有建立。** - -### 0.5 三个统一 - -| 统一 | 链接语法的作用 | -|------|---------------| -| **代码即文档** | 调用写在文档里;`**` 是代码,`[]()` 是同一段代码 + 人话描述 | -| **文档即知识库** | `#` 类是知识命名空间,`##` 函数是知识单元;`类.函数` 是地址 | -| **知识即可执行** | 链接解析到类/函数并求值;view 显示调用点;编译器返回 LinkInfo | - -形式化: - -> **`[label](expr) ≡ expr`;`expr` 可以是 `类.函数`。** -> 链接不改变求值;它增加 label/上下文所形成的命名步骤,以及 view 呈现、编译器元数据和图关系。 - ---- - -## 1. 术语 - -| 术语 | 定义 | -|------|------| -| **链接语法** | `[描述](载荷)`;描述在运行时 inert、在知识层是步骤名称;载荷复用所在位置的已有代码/结构语法 | -| **描述 / 名称(label)** | `[]` 内自由文本;不参与运行时求值,但用于显示、检索、诊断、LinkInfo、意图漂移校验与新鲜度复核 | -| **载荷(payload)** | `()` 内的表达式;与 `**代码**` 同权;唯一执行体 | -| **类(class)** | `# 名称`;知识命名空间/类型 | -| **函数(function)** | `## 名称`(及更深);类下或模块顶层的可调用单元 | -| **类调用(class call)** | `类.函数`;不构造实例,直接调用类函数 | -| **实例调用(instance call)** | `对象.函数`;对象是局部变量/实例,函数可使用 `self`/`自` | -| **知识链接** | 目标为类/函数的 `[]()`;view 显示目标与值 | -| **代码链接** | 出现在 `**...**` / `*...*` / 调用实参/表格单元格里的 `[]()`;参与表达式 | -| **正文链接** | 出现在叙述里的 `[]()`;view/check 解析,`run` 不执行(除非加 `print` 或代码链接) | -| **LinkInfo** | 编译器返回的命名步骤信息:描述与上下文、源位置、payload 类型、输入/输出、依赖、效果、值/来源/指纹 | -| **链接图** | 文档/类/函数/命名步骤为点,读、推导、遍历、调用、效果、叙述、来源为边;EKC/catalog/view 共用 | -| **遮蔽** | 链接的显示属性:`()` 的代码在 Markdown 里被折叠,读者只看描述与结果 | - ---- - -## 2. 语义 - -### 2.1 描述永不执行,载荷唯一执行 - -```text -[label](expr) ≡ expr -``` - -- `[]` 不进符号表、不参与运行时求值、不改变作用域;但它进入 LinkInfo,作为命名步骤的人话接口; -- `()` 是唯一执行体;空 `()` 值为 `None`; -- `label.missing` / `label.empty_payload` 仍是结构诊断; -- 链接的**可执行性**来自 `payload` 的原有语法;链接的**知识性**来自 `label`、位置以及编译器提取的输入/输出/依赖/效果。任意载荷都可成为知识步骤,不以是否类调用为前提。 - -### 2.2 `#` 是类,`##` 是函数 - -| 标记 | 语义 | -|------|------| -| `# 名称` | 类/知识命名空间;正文是构造体 | -| `## 名称` | 类下的函数;可被 `类.函数` 调用 | -| `###` … | 更深层函数/子命名空间 | -| 顶层 `## 名称` | 模块级自由函数;可被 `模块.函数` 调用 | - -**函数与实例的关系**: - -- 函数体使用 `self` / `自` → **实例函数**,只能通过实例调用(`obj.函数`); -- 函数体不使用 `self` / `自` → **类函数**,可被 `类.函数` 直接调用; -- 类函数不执行 `# 类` 的构造体,不产生实例; -- 实例函数保留现有 `> 对象.函数` / `obj.函数()` 语义。 - -这条规则只用已有语法(`#`、`##`、`self`/`自`、`.`),不新增标记。 - -### 2.3 `类.函数` 是类调用 - -| 写法 | 语义 | -|------|------| -| `李白.李白的出生年份` | 类 `李白` 的零参函数 `李白的出生年份`;**隐式调用** | -| `李白.问候("世界")` | 类 `李白` 的函数 `问候`,带位置参数 | -| `李白.计税(档位=2, 金额=100)` | 具名参数,复用现有实参文法 | -| `obj.李白的出生年份()` | 实例调用;`obj` 是局部变量/实例 | -| `文档.李白.李白的出生年份` | 文档限定;用于同名类消歧 | - -**隐式调用规则**:当点号路径解析到一个**零参函数**时,路径表达式就是调用,值为函数返回值; -带参数时必须写 `(...)`;解析到类名本身(无函数段)时,仍是类型/构造,不隐式调用。 - -> 这条规则不是新语法:它只规定「点号路径解析到函数」时的语义。 -> 它让 `李白.李白的出生年份` 与 `**李白.李白的出生年份**` 同权,也让链接与代码同权。 - -### 2.4 跨文档:模块身份优先,类索引只做发现 - -链接目标可以跨文档。可运行代码的解析顺序: - -1. **局部变量/对象**:第一段是当前作用域变量 → 实例调用; -2. **当前文档类/函数**:`# 类` / `## 函数`; -3. **已 import 的模块**:现有 `import bind:target` 绑定; -4. **内置/插件**。 - -文件 frontmatter 的 `id` + 现有 `import bind:target` 是规范地址;例如 -`li_bai.李白.出生年份`。项目类索引仍是**编译器/链接器的发现索引**,不是运行时的 -按名加载机制: - -- 索引 `id`、`# 类` 名、`## 函数` 名、签名、文件位置; -- 排除 `# main`; -- 正文短地址同名 → `link.ambiguous`;解析成功后 LinkInfo/lock 固化 `id`、文件与指纹; -- 索引只在项目根内(`--fs-root`),不访问网络; -- 索引可缓存(按文件 mtime)。 - -> 正文可以直接写 `李白.出生年份`,由 catalog 唯一发现并 lock; -> 代码仍应使用显式 import,避免同名、重命名和加载顺序使大型项目失去可复现性。 - -### 2.5 `()` 与 `**代码**` 同权 - -| 能力 | `**代码**` | `[描述](载荷)` 的 `()` | -|------|-----------|----------------------| -| 算术/比较/布尔 | ✅ | ✅ 同一 parser | -| 变量/插值 | ✅ | ✅ | -| 本地调用 `callee(args)` | ✅ | ✅ | -| 类调用 `类.函数` | ✅ | ✅ | -| 实例调用 `obj.函数` | ✅ | ✅ | -| 表/列/映射 | ✅ | ✅ | -| 返回值 | Value | Value(同类型系统) | -| 副作用 | 可 | 可(受沙箱限制) | - -**实现约束**:表达式位置的 `[label](payload)` 必须复用 `**代码**` 的表达式入口;遍历位置的 -`[label](payload)` 必须复用既有 LoopSpec 入口;禁止另造「简化知识表达式」或「知识循环」。 - -**代码链接 vs 正文链接**: - -| 上下文 | `[]()` 行为 | -|--------|-------------| -| `**...**` / `*...*` / 调用实参 / 表格单元格 | 代码链接:求值,参与表达式 | -| 正文(叙述) | 正文链接:view/check 解析并显示;`run` 不执行 | -| 标题 / frontmatter | 不执行;按普通文本处理 | - -正文链接不执行,是为了保持「叙述默认安全」;它由 view 呈现、由 check 解析。 -要终端输出,就把同一段代码放进代码链接并加 `print`。 - -**正文链接的识别**:`view`/`check` 扫描正文里的 Markdown 链接;payload 先按所在位置的既有 -载荷文法解析,再提取其依赖与角色。URL/相对路径为导航;任意可解析的表达式、调用或遍历 -都是命名步骤;解析歧义 → `link.ambiguous`。这仍是语义分类,不是新语法。 - -### 2.6 输出:值知识必须有值,过程知识必须声明效果 - -当一个 `##` 作为可被叙述或计算使用的值知识时,目标函数必须返回一个值: - -```markdown -## 李白的出生年份 - -*701* -``` - -或者用表格/契约声明返回值。**正文叙述可以保留**(例如「李白出生于某年」),但**叙述不是值**;值知识要的是返回值/表。只有叙述、没有返回的函数: - -- `run` 得到 `None`; -- `check` 报 `link.no_value`(warning/error,视知识链接用途); -- view 显示「无返回值」; -- 这不是语法问题,是值知识单元没有编码值。遍历、写入、请求等过程知识不必伪造返回值, - 但 LinkInfo 必须记录输入、输出绑定和 `effect`,以便 view、权限检查与影响分析。 - -### 2.7 view 显示调用信息 - -**代码链接**: - -```text -┌─ 链接 ─────────────────────────────┐ -│ `year` = [李白的出生年份] │ -│ → 李白.李白的出生年份 │ -│ class 李白 · function · () -> number │ -│ value 701 · ok │ -└────────────────────────────────────┘ -``` - -**正文链接**: - -```text -用户想要知道李白的出生年份,我们要告诉用户 701。 - ↑ - 悬浮:李白的出生年份 → 李白.李白的出生年份 - class 李白 · () -> number · value 701 -``` - -- Structure 模式:显示 label + 目标类/函数 + 状态 + 源位置; -- Execution 模式:显示值; -- 点击目标:跳到目标文档/类/函数; -- 错误:错误 chip + 诊断码 + 修复建议; -- 无返回值:显示「无返回值」,不伪造值。 - -**这就是「示例不带 print」的原因**:view 显示调用信息;`run` 才需要 `print` 才有终端输出。 - -### 2.8 编译器返回 LinkInfo - -每个 `[]()` 产出: - -```json -{ - "label": "逐个订单行", - "payload_kind": "loop", - "roles": ["iterate"], - "source": {"file": "pricing.mq.md", "line": 18, "col": 3}, - "inputs": [{"path": "订单.行", "type": "list<订单行>"}], - "outputs": [{"name": "行", "type": "订单行"}], - "dependencies": [ - {"kind": "local_value", "path": "订单.行"}, - {"kind": "symbol", "id": "capability.pricing::订单定价.含税价"} - ], - "effect": "pure", - "value": null, - "fingerprint": "sha256:…" -} -``` - -- `payload_kind`:`expr` / `loop` / `inline` / `navigation`;复用所在位置的已有文法; -- `roles`:`observe` / `derive` / `reuse` / `iterate` / `act` / `narrate`,由 AST、效果和依赖推导; -- `dependencies` 是集合而非单一 target;任意复杂表达式都可同时读表、调用多个知识函数和产生副作用; -- `value` 在 `check` 中为 `null`(不执行);在 `view`/`run` 中可填; -- `fingerprint` 是 label、payload、依赖解析及契约的指纹;用于意图漂移与 lock 检查。 - -### 2.8.1 LinkInfo 是统一知识步骤记录,不只是调用记录 - -`LinkInfo` 至少要区分三类状态: - -| 层 | 要回答的问题 | 典型状态 | -|------|-------------|----------| -| **载荷状态** | `()` 能否按它原有语法解析/执行? | `ok` / `unresolved` / `arg_mismatch` / `type_mismatch` | -| **步骤状态** | 输入、输出、依赖和效果能否被提取? | `resolved` / `partial` / `ambiguous` | -| **证据状态** | 一个发布事实沿依赖链是否能抵达来源? | `supported` / `needs_review` / `unsupported` | - -三者不能混为一谈:字典取元可以 `ok` 且完全不需要来源;但当它被一个事实函数或 -正文结论使用时,最终的证据链仍可为 `unsupported`。反过来,来源充足也不能掩盖 -`link.unresolved` 或副作用越权。 - -来源是统一步骤图上的 `derived_from` 边,不是只属于一种“知识链接”的特殊 payload。 -这不是新增语法,而是让既有 `#`/`##`、表、表达式和 `[]()` 共同产生同一张图。 - -### 2.9 链接既是步骤节点,也是图边 - -```text -定价.订单定价 --contains--> step#逐个订单行 -step#逐个订单行 --observes--> 订单.行 -step#逐个订单行 --calls--> 定价.订单定价.含税价 -定价.订单定价.含税价 --derived_from--> corpus/tax.md#税率 -``` - -- 每个 `[]()` 都保留为步骤节点;`calls` 只是 `observes`/`derives`/`iterates`/`acts`/ - `narrates` 等边的一种; -- EKC `graph.json` 增加 class/function/步骤节点和上述关系边; -- `catalog` 模块页显示「链接到/被链接」; -- `find`/`impact`/`verify` 沿步骤、调用和来源边遍历;表字段、循环、函数或来源变更时, - 都可精确找出受影响的代码步骤和句子; -- view 的 Structure 面板显示上下游。 - -### 2.10 安全 - -| 风险 | 规则 | -|------|------| -| 类名歧义 | `link.ambiguous`;要求 `文档.类.函数` | -| 实例函数被类调用 | `link.instance_only`;提示用实例 | -| 构造副作用 | 类调用不执行构造体;不会隐式构造实例 | -| 函数副作用 | 目标函数可能写文件/发请求;`run`/live view 受沙箱限制;`check` 不执行 | -| 循环 | 链接图检测环;运行时深度/步数上限 | -| 路径逃逸 | 项目类索引只在根内;`--fs-root` 限制;不访问网络 | -| 标签欺骗 | 标签不可信;解析/权限只看 target,不看 label | -| view | 静态模式不执行;live 执行需用户操作;错误不吞 | - -### 2.11 可复现(可选,生成物) - -- LinkInfo 带 label、payload、依赖解析、效果与可用来源边的指纹; -- `marqdo links lock` 生成 `.marqdo/links.lock.yaml`; -- `check --locked` 校验;载荷、依赖、契约或来源边变化 → `link.stale` / `knowledge.needs_review`; -- 这是生成物/工具,不是新语法。 - -### 2.12 知识分层:类、知识个体、调用面 - -链接语法是**调用面**;它上面还有两层知识结构(详见 [knowledge-layers.md](knowledge-layers.md)): - -```markdown -# 诗人 # L1 本体:类/模式 -| 字段 | 类型 | 说明 | -| 姓名 | text | ... | -| 出生年份 | number | ... | - -# 李白 = > 诗人 # L2 知识个体:单体知识类 -## 李白的出生年份 -| 返回 | 类型 | 来源 | -| 701 | number | corpus/libai.md#出生年份 | -*701* - -# L3 调用面 -[李白的出生年份](李白.李白的出生年份) -``` - -**术语**: - -- `# 李白 = > 诗人` 是**知识个体/单体类**(语法上是继承/特化),不是运行时实例; -- `> 李白` 才是运行时实例(map + `_type`); -- `李白.李白的出生年份` 是类调用; -- `[]()` 是调用面,不新增语法。 - -**为什么不在 v2.1 引入运行时实例作为知识实体**: - -- 运行时实例是值,不是文档里的稳定地址;跨文档链接需要实例注册表/导出; -- EKC 的节点是文档/类/函数,不是运行时 map; -- 单体类已经能表达「李白是诗人,李白有出生年份」,且零新语法。 - ---- - -## 3. 当前实现 vs 目标 - -### 3.1 已具备(v2.0.0) - -| 能力 | 状态 | 证据 | -|------|------|------| -| `[描述](表达式)` 解析 | ✅ | `Expr::Occluded` / `markup: occlusion` | -| `()` 内 `callee(args)` | ✅ | M1;`加一 号(31)` | -| 本地表达式透明求值 | ✅ | `interp.rs:1117` | -| view 本地链接卡 | ✅ | `render.rs:1227` | -| 标签诊断/检索 | ✅ | `label.*` / `marqdo labels` | -| 实例调用 | ✅ | `obj.method()` / `> obj.method` | - -### 3.2 缺失(v2.1 目标) - -| 能力 | 状态 | 影响 | -|------|------|------| -| `类.函数` 类调用 | ❌ | `李白.李白的出生年份` 被当成变量/实例方法 | -| 跨文档类索引 | ❌ | 裸类名不解析;必须 import + 实例 | -| 统一 `[]()` 分类 | ❌ | 默认 Classic 下 `[]()` 是取元;需 `markup` | -| LinkInfo | ❌ | 编译器不返回链接信息 | -| view 目标/类/函数/值 | ⚠️ 只有本地卡片 | 没有跨文档目标信息 | -| 链接图边(EKC) | ❌ | 知识图不从链接取边 | -| 正文链接解析 | ❌ | 第二个文档的链接不解析 | -| 类函数契约/返回校验 | ❌ | 无返回值也不报 | - -### 3.3 为什么旧例子失败 - -| 层 | 旧例子 | 设计要求 | -|----|--------|---------| -| 上下文 | 正文普通链接 | 正文链接由 view/check 解析(run 不执行) | -| 类索引 | 无 import | 项目类索引解析 `李白` | -| 调用 | `李白.李白的出生年份` 被当变量 | 解析为类函数,隐式调用 | -| 分派 | `##` 是实例方法 | 不使用 `self` 的函数是类函数 | -| 值 | 方法体无返回 | 知识函数必须返回 `701` | -| 静态检查 | 不解析 | `check` 报 `link.*` | - ---- - -## 4. 编译器 / view / CLI 表面 - -### 4.1 `check --json` - -- 解析所有 `[]()`(表达式、遍历、代码与正文),输出带载荷/步骤/证据状态的 LinkInfo 与 `link.*` / `knowledge.*` 诊断; -- 不执行目标函数; -- `link.ok` 可作 info,不阻断; -- `link.unresolved` / `link.ambiguous` / `link.instance_only` / `link.no_value` 按级别报。 - -### 4.2 MLSP - -| method | 作用 | -|--------|------| -| `link.resolve` | 解析一个链接 → LinkInfo | -| `links.list` | 列出文件/项目所有链接 | -| `links.graph` | 返回链接图 | -| `link.check` | 校验一个链接 | - -AI 闭环:`locate` → `link.resolve` → 构造/修复 → `check` → `view`/`run`。 - -### 4.3 `catalog` / EKC - -- `catalog` 增加 `links:` 段与链接图; -- EKC `graph.json` 增加 class/function、命名步骤节点与 `observes`/`derives`/`iterates`/`calls`/`acts`/`narrates`/`derived_from` 边; -- `find`/`impact` 能按类/函数/步骤检索,也能从变更的字段、规则或来源反查受影响的代码与文档句子。 - -### 4.4 `links` CLI(可选) - -```bash -marqdo links list [PATH] --json -marqdo links resolve FILE:LINE:COL -marqdo links graph [PATH] --json -marqdo links lock [PATH] # 可选,生成指纹锁 -``` - -### 4.5 诊断 - -| code | 级别 | 触发 | 建议 | -|------|------|------|------| -| `link.unresolved` | error | 类/函数/文档不存在 | 检查类名/文档名/拼写 | -| `link.ambiguous` | error | 同名类/函数 | 用 `文档.类.函数` 限定 | -| `link.instance_only` | error | 类调用命中实例函数 | 用实例 `obj.函数`,或去掉 `self` | -| `link.no_value` | warning | 知识函数无返回 | 加 `*值*` 或表/契约 | -| `link.arg_mismatch` | error | 参数数量/名称不匹配 | 按签名补/删 | -| `link.type_mismatch` | error | 返回/参数类型不匹配(可静态判断) | 修契约/转换 | -| `link.cycle` | error | 链接图成环 | 拆分事实/减少互引 | -| `link.stale` | warning | 目标指纹变化(lock 模式) | 更新 lock 并复核 | -| `knowledge.unsupported` | warning | 对外发布的事实/结论沿步骤依赖链没有来源支撑 | 补来源边或将其标明为未验证推导 | -| `knowledge.needs_review` | warning | payload、依赖、规则或来源变化,受影响步骤/句子待复核 | 复核步骤与叙述后更新 lock | -| `label.missing` | error | 空描述 | 写一句人话 | -| `label.empty_payload` | warning | 空载荷 | 写 `None` 或真实目标 | - ---- - -## 5. 开发指导 - -### 5.1 里程碑 - -| 阶段 | 目标 | 交付 | -|------|------|------| -| **L0** | 统一 `[]()` 节点 | `Bracket { label, payload }`;代码/正文两处解析;不新增语法 | -| **L1** | 步骤索引 + 解析 | `Named<T>` 的输入/输出/依赖/效果提取;类/模块解析;`link.*`/`knowledge.*` 诊断 | -| **L2** | 类调用运行时 | `类.函数` 隐式调用;参数;实例函数拒绝;双后端 | -| **L3** | view | 链接卡;正文链接信息;目标跳转;值/状态/源位置 | -| **L4** | 图 + lock | EKC 步骤节点/读写推导遍历调用来源边;catalog;可选 lock/stale | -| **L5** | 默认/迁移/文档 | 统一解析替代 `markup` 方言;旧取元迁移;README/示例 | - -**顺序**:L0 → L1 → L2 → L3 → L4 → L5。 -L1 完成后 AI 就能静态查链接;L2/L3 才是执行与呈现。 - -### 5.2 文件级改动 - -| 文件 | 改动 | -|------|------| -| `src/ast.rs` | `Bracket { label, payload }`(可由 `Occluded` 演进);不新增语法节点族 | -| `src/parse/expr.rs` | `[]()` 统一解析;payload 复用 `**` 表达式入口;保留 `markup` 兼容 | -| `src/parse/mod.rs` | 正文 `[]()` 扫描;行/列定位;表格单元格 | -| `src/link.rs`(新增) | 模块/类解析、`Named<T>` 步骤记录、依赖/效果提取、诊断、指纹、图边 | -| `src/load.rs` | 项目扫描/类索引缓存;`--fs-root`;循环检测 | -| `src/check.rs` | 链接解析集成;`link.*`;`--links/--no-links/--locked` | -| `src/interp.rs` | `类.函数` 类调用;隐式零参调用;实例函数拒绝;正文链接不执行 | -| `src/bytecode/compile.rs` + `vm.rs` | 类调用编译/执行;双后端一致 | -| `src/view/render.rs` | 链接卡;正文链接信息;目标/值/状态/跳转 | -| `src/view/document.rs` / `output.rs` | 正文链接扫描/渲染 | -| `src/knowledge/graph.rs` | class/function/命名步骤节点;读/推导/遍历/调用/效果/叙述/来源边 | -| `src/knowledge/extract.rs` | 类/函数/命名步骤提取;依赖与来源关系 | -| `src/catalog.rs` | links 段/图 | -| `src/mlsp.rs` | `link.resolve` / `links.list` / `links.graph` | -| `src/main.rs` | `links` 子命令;check 选项 | -| `README.md` | 链接语法章节(不新增语法) | -| `doc/README.md` | 登记本文/示例 | -| `examples/link-syntax/` | 用户原始示例 + compat | - -### 5.3 关键实现点 - -1. **类函数判定**:扫描函数体是否出现 `self` / `自`;出现 → 实例函数;不出现 → 类函数。 -2. **隐式调用**:点号路径解析到零参函数时,求值为调用;带参必须 `(...)`;解析到类名不调用。 -3. **类索引**:只索引 `#`/`##` 名、签名、文件、行;排除 `# main`;同名报歧义。 -4. **`[]()` 分类**: - - payload 是类/函数路径 → 知识链接; - - payload 是表达式(运算符/字面量/调用)→ 本地表达式链接; - - payload 是单标识符且解析为集合 → 旧取元(兼容;`markup` 模式可强制链接); - - 正文 `[]()` → 正文链接(view/check)。 -5. **正文链接不执行**:`run` 不改行为;`view`/`check` 解析;要输出用代码链接 + `print`。 -6. **LinkInfo**:check/view/catalog 共用;任意 `[]()` 都记录 payload kind、输入/输出、依赖、效果与步骤状态;无需执行即可得到结构图。 -7. **图**:每个 `[]()` 是步骤节点;按角色建 `observes`/`derives`/`iterates`/`calls`/`acts`/`narrates` 边,来源只是其中一种边。 -8. **安全**:类调用不构造实例;沙箱;根目录;标签不可信。 - -**最小改动原则**(证明「不新增语法」): - -| 层 | 现状 | v2.1 改动 | -|----|------|-----------| -| parser | `[label](payload)` → `Occluded { label, payload }` | **不改 grammar**;可把节点改名为 `Bracket` 便于阅读 | -| payload | 已是表达式,`callee(args)` 已支持 | 不改;`类.函数` 是现有 dot path | -| AST | `Occluded { label, payload }` | 不新增 `Ref`/`Class` 节点;类/函数用现有 `Function`/`is_object` | -| resolver | 无 | **新增**:类索引 + `类.函数` 解析 + `self` 判定 | -| interp | 透明求值 payload | **新增**:dot path 解析到类函数时隐式调用 | -| view/check | 本地卡片/契约 | **新增**:正文 `[]()` 扫描 + LinkInfo | -| 语法 | — | **零新增**:没有协议前缀、别名、执行开关、模式关键字 | - -> 当前 `李白.李白的出生年份` 在 AST 里是 `Var("李白.李白的出生年份")`(v2.0.0 实测报 `undefined variable`)。 -> **不要依赖 parser 生成新节点**:resolver 按 `.` 拆分这个变量名,先找类 `李白`,再找函数 `李白的出生年份`; -> 找到后按类调用求值。若 parser 已生成 `Call { path: ["李白","李白的出生年份"] }`,同样按 path 解析。 - -### 5.4 测试 - -| 层 | 用例 | -|----|------| -| 单元 | `类.函数` 解析;零参隐式调用;带参;`self` 判定;同名歧义 | -| 集成 | 用户两文档:正文链接 view 显示 701;代码链接 + print 输出 701 | -| 诊断 | unresolved / ambiguous / instance_only / no_value / arg/type/cycle | -| view | 链接卡/正文链接/目标跳转/错误/无返回值 快照 | -| 图 | EKC 观测/推导/遍历/调用/效果/叙述/来源边;catalog;impact | -| 双后端 | tree + bytecode 一致 | -| 回归 | 现有 605 测试不减;实例调用不变;旧 `markup` 兼容 | -| 安全 | 根目录逃逸、循环、副作用、标签注入 | - -### 5.5 迁移 - -- `#`/`##` 的实例调用保持; -- 不使用 `self` 的现有方法自动获得类调用能力(增量); -- `类.函数` 是新增解析,不改变旧调用; -- `[]()` 在 `markup: occlusion` 下继续是链接;在 Classic 下按 payload 分类,单标识符/集合仍是旧取元; -- 目标:v2.2 移除 `markup` 方言,统一按 payload 分类。 - ---- - -## 6. 示例 - -完整见 [examples/link-syntax/](../../examples/link-syntax/)。 - -### 6.1 用户原始示例(目标) - -`libai.mq.md`: - -```markdown -# 李白 - -这个文档存储了李白的信息。 - -## 李白的出生年份 - -李白的出生年份是公元 701 年。 - -*701* -``` - -`main.mq.md`: - -```markdown -# main -用户想要知道李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) -``` - -- `view`:正文链接显示 `李白.李白的出生年份`、类 `李白`、函数、签名、值 `701`; -- `run`:无输出(正文链接不执行);加 `print` 才有终端输出; -- `check --json`:LinkInfo(target/class/function/signature/status); -- `catalog`:`main.mq.md --calls--> libai.mq.md::李白.李白的出生年份`。 - -### 6.2 加 print(终端输出) - -```markdown -# main - -**year = [李白的出生年份](李白.李白的出生年份)** -> print text=`year` -``` - -输出:`701`。 - -### 6.3 带参数 - -```markdown -# main - -**greeting = [问候](李白.问候("世界"))** -> print text=`greeting` -``` - -### 6.4 当前兼容写法(v2.0.0) - -```markdown ---- -markup: occlusion -import: - libai: libai.mq.md ---- - -# main - -**li = > libai.李白** -**year = [李白的出生年份](li.李白的出生年份())** -> print text=`year` -``` - -输出 `701`。这只是**当前实现**的等价写法;v2.1 的目标是去掉 `import`/实例两步。 - ---- - -## 7. 验收标准 - -| # | 验收 | 判定 | -|---|------|------| -| 1 | 用户原始示例的 `view` 显示 `701` 与调用信息 | view 快照 | -| 2 | `**year = [..](李白.李白的出生年份)**` + `print` 输出 701 | run | -| 3 | `check --json` 返回 LinkInfo(class/function/signature/status) | link.ok | -| 4 | 类名改成不存在 → `link.unresolved` | 反例 | -| 5 | 同名类 → `link.ambiguous` | 反例 | -| 6 | 实例函数被类调用 → `link.instance_only` | 反例 | -| 7 | 无返回值 → `link.no_value` | 反例 | -| 8 | EKC 出现 `calls` 边 | graph.json | -| 9 | 正文链接 `run` 不执行;`view` 解析 | 行为 | -| 10 | 旧 605 测试不减;实例调用不变 | 回归 | -| 11 | 表字段、规则或来源变化后,受影响的取元/循环/推导/句子变为 `knowledge.needs_review` | impact 反例 | - -**一句话验收**: - -> **`[李白的出生年份](李白.李白的出生年份)` 不新增任何语法;`view` 能显示它,`check` 能解析它,`run` 加 `print` 能输出 701,`catalog` 能建边。** -> 四者缺一,说明 `#`/`##` 的类-函数语义还没补齐。 - ---- - -## 8. 风险与开放问题 - -| 风险 | 说明 | 缓解 | -|------|------|------| -| 类名歧义 | 多个 `# 李白` | `link.ambiguous`;`文档.类.函数` | -| 实例/类判定 | 依赖 `self`/`自` 扫描 | 明确规则;无法判定时 `link.instance_only` | -| 构造副作用 | 类调用不应构造实例 | 类调用不执行构造体;实例函数拒绝 | -| 无返回值 | 知识函数只有叙述 | `link.no_value`;要求 `*值*`/表 | -| 正文链接 | run 不执行 | view/check 解析;print 用代码链接 | -| 旧取元歧义 | `[key](collection)` | 单标识符/集合按旧取元;`markup` 兼容;逐步迁移 | -| 性能 | 大项目类索引 | 缓存;只索引签名;增量 | -| 安全 | 类函数执行副作用 | 沙箱;check 不执行;标签不可信 | -| 跨项目 | 类索引只在根内 | 用 import/模块;不引入新语法 | - -**开放问题**: - -1. 类函数是否允许访问类级常量/字段?v1 只允许函数体自包含;v1.1 再定义。 -2. `# 类` 的构造体与类函数的关系?v1 类调用不构造;实例函数用 `self`。 -3. 同名类跨文档是否允许?v1 报歧义;用 `文档.类.函数`。 -4. 正文链接是否要在 `run` 中渲染?v1 不执行;view 显示;v1.1 可加 `--render-links`。 -5. `[]()` 与旧取元的自动分类是否足够稳定?先保留 `markup` 兼容;v2.2 再移除。 -6. 是否需要函数作为一等值?v1 不需要;`类.函数` 解析即调用。 - ---- - -## 9. 结论 - -> **`[]()` 不是新语法,它是「命名载荷 + 已有语义」的组合。** -> `#` 是类,`##` 是函数,`类.函数` 是类调用;`()` 与 `**` 同权。 -> 链接不改变载荷;它把取元、计算、循环、调用和正文槽统一提升为能被读、查、验和追溯的知识步骤。 - -v2.0.0 把 `##` 实现成了实例方法,把跨文档链接实现成了 import + 实例,把 `[]()` 收窄成了本地遮蔽。 -v2.1 要补的是**语义**,不是语法: - -1. `#`/`##` → 类/函数;不使用 `self` 的函数是类函数; -2. `类.函数` → 类调用;跨文档用项目类索引; -3. `[]()` → 命名载荷 + 已有语义;表达式/循环按原规则执行,正文由 view/check 解析; -4. LinkInfo / view / EKC 的步骤节点与读、推导、遍历、调用、效果、来源边 —— 让代码与文档可查、可看、可验、可建图。 - -**一句话**: - -> **不是给 `[]()` 加语法,而是让 `#`/`##` 真正成为类/函数,让 `类.函数` 真正可调用;`[]()` 只是把这次调用写成一句人话。** - ---- - -## 附录 A:一页速查 - -```markdown -# 类 -## 函数 -*701* - -# 代码链接(求值) -**year = [出生年份](李白.李白的出生年份)** -> print text=`year` - -# 正文链接(view/check 解析,run 不执行) -李白出生于 [李白的出生年份](李白.李白的出生年份)。 - -# 带参类调用 -**g = [问候](李白.问候("世界"))** -``` - -| 写法 | 执行 | 用途 | -|------|------|------| -| `**类.函数**` | ✅ | 普通代码/调用 | -| `[描述](类.函数)`(代码内) | ✅ | 带描述的类调用 | -| `[描述](类.函数)`(正文) | ❌ run / ✅ view/check | 知识链接 | -| `[描述](expr)`(代码内) | ✅ | 本地表达式链接 | -| `[描述](url)` | ❌ | 普通导航 | - -## 附录 B:与旧文档的关系 - -| 旧文档 | 关系 | -|--------|------| -| [occlusion-syntax.md](occlusion-syntax.md) | 旧文把 `[]()` 定义为「遮蔽」;本文把它定义为「命名载荷 + 已有语义」;遮蔽只是显示属性 | -| [occlusion-description-and-search.md](occlusion-description-and-search.md) | 标签/桩/检索仍适用;本文把标签归入 LinkInfo | -| [change-m7-migration.md](change-m7-migration.md) | 旧取元迁移保留;v2.1 统一按 payload 分类,逐步移除 `markup` | -| [objects.md](objects.md) | 扩展:`#` 类是命名空间;`##` 不使用 `self` 时是类函数 | -| [module-namespace.md](module-namespace.md) | `import` 仍用于代码模块;链接额外支持项目类索引 | -| [engineering-knowledge.md](engineering-knowledge.md) | 链接边接入 EKC 图 | diff --git a/doc/design/markdown-mapping-v0.3.md b/doc/design/markdown-mapping-v0.3.md deleted file mode 100755 index 69784a2..0000000 --- a/doc/design/markdown-mapping-v0.3.md +++ /dev/null @@ -1,621 +0,0 @@ -# Marqdo 语法映射 v0.3(叙述统一 · 粗体即代码) - -| | | -|---|---| -| 状态 | **Accepted · 现行运行时目标(实现中)** | -| 日期 | 2026-09-13 | -| 取代 | [markdown-mapping.md](markdown-mapping.md) **v0.2(已废止为运行时宪法)** | -| ADR | [0005-prose-unified-markup.md](../adr/0005-prose-unified-markup.md) | -| 路线 | [markup-v0.3.md](../roadmap/markup-v0.3.md) | -| 相关 | [code-vs-comment.md](code-vs-comment.md) · [return-hr-and-code-surface.md](return-hr-and-code-surface.md) · [call-arguments.md](call-arguments.md) · [objects.md](objects.md) · [keywords.md](keywords.md) | - -> **名词:** 本文「Markup」指 Marqdo **如何把 Markdown 标记映射成语法**(`**` 代码、`*` 返回、`` `名` `` 声明),不是另一个语言。产品仍是 Marqdo。 -> **v0.3 为唯一映射。** 不做 v0.2 双模式 / `--markup` 版本身份。摸索阶段允许破坏性变更;旧 `.mq.md`(`*语句*` / `**返回**`)须改写。金样例见 `tests/markup-v03/`。 - ---- - -## 0. 一句话 - -让 **Markdown 叙述本身成为程序的一部分**:普通文字里用 `` `名` `` 出现变量(首次未赋值 = 声明);用 **`**…**` 粗体** 包裹可执行代码(含调用,不必再写 `>`);用 **`*…*` 斜体** 表示返回值。函数形参**不再手写 `+` 列表**,由函数体内的声明/赋值自行推断。 - ---- - -## 1. 动机(为何推翻 v0.2 的部分定论) - -v0.2 为了「标记即语法」的清晰边界,做了这些硬隔离: - -| v0.2 | 代价 | -|------|------| -| 无标记行 = 纯注释;变量只能写在 `*…*` / 结构行里 | 叙述与代码割裂,「文档即代码」读起来像两套语言叠在一起 | -| `*…*` = 语句,`**…**` = 返回 | 与常见 Markdown/AI 习惯相反:模型更爱用 `**` 强调「要执行的东西」,读者也更易看见粗体 | -| 调用必须 `>` | 行间调用要另起结构行,叙述中夹调用不自然 | -| 形参必须 `` + `名` `` | 仪式感强;函数头像「另一套签名语言」,与正文脱节 | - -古早示例(当时不能跑,正是本文要合法化的目标面): - -```markdown -## 加一函数 - -对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。 - -# main - -我要调用加一函数可以采用这样的办法: - -> 加一函数 37 - -或者可以直接这么调用**加一函数 37** -``` - -目标:上述文件在 v0.3 下应能解析、求值,且**读起来仍是一篇正常中文说明**。 - ---- - -## 2. 哲学(设计原则) - -### P1 — 叙述统一(Prose-unified) - -- Marqdo 注释采用 **Markdown 叙述**(段落、列表中的说明文字),不是第二种注释语法。 -- **变量可以出现在正常文字之间**:用 Markdown 行内代码 `` `n` `` 标识标识符。 -- **第一次出现且未赋值 = 声明变量**;之后的出现 = 引用。赋值发生在粗体代码段内(或兼容的结构赋值形)。 -- **未使用的变量无害**(不报错、不升参);真正的输入由「可执行面读取」升为形参(§8)。 -- 这样「说明文字」与「程序名字」共用同一套 Markdown 视觉习惯,整体更和谐。 - -### P2 — 粗体即代码(Bold-as-code) - -- **`**…**` = 代码段**(可执行):赋值、表达式、函数/方法调用、可内联的短语句。 -- 选择粗体的原因: - 1. **AI 输出偏好**:模型天然爱用 `**` 强调「重要操作」;把粗体定为可执行,降低「模型写了强调却被当成返回」的错配。 - 2. **行间显眼**:在长段落里,粗体比斜体更容易被扫到。 -- 粗体代码段内的调用 **允许不写 `>`**:`**加一函数 37**` 与 `> 加一函数 37` 语义等价(见 §6)。 -- **`>` 保留为可选调用面**(blockquote 风格、独立行、兼容 v0.2 迁移与 AI 已学会的形态)。 - -### P3 — 斜体即返回(Italic-as-return) - -- **`*…*` = 返回值**(架构级),与粗体代码形成对立、易读的一对: - - 做了什么 → 粗体 - - 结果是什么 → 斜体 -- **空返回 / 无值收束**(已决议,见 §7.2):推荐 `*None*` / `*无*`;整行 `**`;兼容 `****`。`---` / `***` 仅为叙述分隔(跳过),**不再**结束函数体。 -- **输出仍不是返回**:打印继续用内置 `print` / `打印`(副作用函数),不把粗体或斜体当成「打印到终端」的语法。 - -### P4 — 形参由体推断(Body-inferred params) - -- **不再要求**作者手写 `` + `名` `` 形参表(v0.3 默认关闭;过渡期可兼容,见 §8)。 -- 函数体内: - - **只声明、未赋默认** → **必选形参**(调用时必须提供)。 - - **声明同时赋值**(含默认值字面量)→ **可选形参**(带默认值)。 -- 推断顺序与绑定规则见 §8;与位置/具名实参规则对齐 [call-arguments.md](call-arguments.md) 的精神(可修订附录)。 - -### P5 — 标记仍承载控制流(不变) - -- **不引入** `if` / `else` / `while` / `for` / `def` / `return` 关键字。 -- `#` = 对象/类型,`##`+ = 函数/方法([objects.md](objects.md) 不变)。 -- 分支仍用 `1.` `2.` …;循环仍用 `-`;结构行不必再包粗体(见 §5)。 - -### P6 — 其它「代码即文档」补强(本版一并采纳) - -| 思路 | 说明 | -|------|------| -| **渐进披露** | 读者可只读叙述;运行时只执行标记与推断出的声明。同一文件服务人与机器。 | -| **最小仪式** | 能从正文看出的签名,就不在函数头重复写一遍。 | -| **双调用面** | 独立行 `>` 适合「步骤清单」;行间 `**f …**` 适合「嵌在句子里的动作」。 | -| **标识符视觉统一** | 叙述、代码、形参一律优先 `` `名` ``;粗体/斜体内部允许裸名(与 v0.2 斜体/粗体内规则同类)。 | -| **段落仍可整段注释** | 不含任何可执行标记、且无「声明性 `` `名` ``」义务的纯说明段,行为与注释相同(见 §4 消歧)。 | -| **迁移可观测** | `--dump-lines` / `--dump-ast` 必须能区分「叙述中的声明」与「粗体代码」与「斜体返回」。 | - ---- - -## 3. 与 v0.2 对照(角色对调摘要) - -| 概念 | v0.2 | v0.3 | -|------|------|------| -| 程序语句 / 代码段 | `*…*` | `**…**` | -| 返回值 | `**…**` | `*…*` | -| 独立调用 | 必须 `>` | `>` **或** `**callee …**` | -| 形参 | 标题下 `` + `名` `` | **体推断**(`+` 过渡兼容) | -| 叙述中的变量 | 一般为注释,不可声明 | `` `名` `` 可声明/引用 | -| 无标记纯文字 | 成段注释 | 仍为叙述;**若含声明性反引号则参与绑定图**(见 §4) | - -这是一次 **架构级标记对调**,不是局部糖。金样例、教程、Skill、扩展库需按路线图分波迁移。 - ---- - -## 4. 叙述、声明与注释 - -### 4.1 三层模型(修订) - -| 层 | 形态 | 角色 | -|----|------|------| -| **叙述面** | 普通 Markdown 段落、列表说明 | 给人读;其中的 `` `名` `` 可进入**绑定图** | -| **可执行面** | 结构标记(`#` `>` `+` `-` `1.` 表…)+ **`**代码**`** + **`*返回*`** | 求值 | -| **外联面** | ` ```lang ` | FFI(不变) | - -### 4.2 变量在叙述中的出现 - -语法:Markdown **行内代码** `` `标识符` ``。 - -| 出现形态 | 语义 | -|----------|------| -| 全文(当前函数/对象作用域)**首次**出现 `` `n` ``,且此前/同句无对 `n` 的赋值 | **声明变量**(进入绑定图;是否升为形参见 §8) | -| 已声明之后再次 `` `n` `` | **引用**(不生成新绑定) | -| 粗体内 `**n = …**` / `**n=n+1**` | **赋值**(若首次赋值且未见声明,则声明+赋值一并发生) | -| 叙述中 `` `n`=1 ``(反引号名紧贴 `=`,无粗体) | **带初值的声明**(形参默认或局部初值;见 §8) | - -推荐作者写法(与动机示例一致): - -```markdown -对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。 -``` - -- `` `n` `` → 声明变量;因随后在代码中**读取**未先由局部独力定义 → 升为必选形参(§8) -- `**n=n+1**` → 代码段(赋值) -- `*n*` → 返回 - -### 4.3 何为「纯注释」 - -满足下列**全部**条件的段落,不产生绑定、不求值: - -1. 不含结构标记行; -2. 不含 `**…**` / 作为返回的 `*…*`(见 §7); -3. 不含任何 `` `标识符` ``。 - -仍建议:**叙述段与独立结构代码行之间空一行**,降低人读与差分时的视觉粘连(解析器在 v0.3 下不再依赖「空行分段注释升级」作为唯一边界,但空行仍是作者卫生习惯)。 - -### 4.4 提及性反引号:一律视作变量(已决议) - -**不另设「仅提及、不声明」语法。** 叙述里凡出现合法标识符 code span `` `名` ``,一律按 **变量** 处理(首次 = 声明,其后 = 引用)。 - -| 情况 | 处理 | -|------|------| -| 谈到某名但可执行代码**从未读写**它 | 仍是绑定图中的变量;**对求值无影响**(死绑定) | -| 与其它语言对照 | 类似 Python 写了未用局部、JS 未用 `let`——默认可忽略;实现可对「从未读写」发**可选 lint**,**不得**因此报错或拒绝运行 | -| 是否变成函数形参 | **否**(仅声明、从未在可执行面被读取)——见 §8.2「升参条件」 | -| 是否需要 `` 提及`n` `` 等前缀 | **不需要**;避免第二套反引号方言 | - -例(合法、无副作用): - -```markdown -## 说明性函数 - -本文顺便提到`Markdown`与`GFM`,但真正的输入只有`题干`。 -**print text=题干** ---- -``` - -- `` `Markdown` `` / `` `GFM` `` → 变量声明,未使用 → 不进形参表、不改行为 -- `` `题干` `` → 声明且在粗体中读取 → 必选形参 - -**否决**:为「提及」单独做转义/前缀(曾列于开放点);若将来作者强烈需要「叙述中的等宽字但不进绑定图」,另开增强案,不阻塞 v0.3 核心。 - -### 4.5 成段规则相对 v0.2 的变化 - -v0.2:「段首无标记 → 整段注释,续行永不升级」。 -v0.3: - -- 叙述段落**可以**内含可执行粗体/斜体返回;解析器做**段内扫描**,抽出 `` `名` ``、`**…**`、`*…*`。 -- 独立结构行(行首 `#` `>` `-` `1.` `|` 等)仍整行分类为代码。 -- **否决维持**:「整行无标记 = 默认可执行代码」。无标记且无反引号声明的文字永不单独变成语句。 - ---- - -## 5. 映射总表(v0.3) - -| 标记 | 语义 | -|------|------| -| `#` … `######` | `#` = 对象/类型;`##`+ = 函数/方法(同 [objects.md](objects.md)) | -| 叙述中 `` `名` `` | 声明或引用(§4) | -| `**…**` | **代码段**(赋值、表达式、调用) | -| `*…*` | **返回值**(含显式空值,见 §7.2) | -| `>` 行 | **调用**(可选面,与粗体内调用等价) | -| `` + `名` `` | **过渡兼容**:显式形参;新代码不推荐 | -| 体内 `1.` `2.` … | 分支 | -| 体内 `-` | 循环 | -| `N. *` | else 臂(此处 `*` 仍是「空条件」标记,**不是**返回值;见 §7.3) | -| GFM 表格 | 集合;`` `名` = `` 后绑定,或**未绑定**时求值后丢弃(文档中可写表) | -| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) | -| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) | -| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) | -| ` ```lang ` | 外联(不变;绑定仍用 `` `名` = `` + 围栏) | -| `$$` 内 `% marqdo: var=名` | 块公式绑定([fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)) | -| `- 对`集`的每一项`项`` / `for each` | foreach 叙述糖;推荐 `- [项](集)` | -| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) | -| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) | - -### 结构行与粗体 - -行首已是结构标记的构造(`#` `>` `+` `-` `|`、`1.`)**不必**再包 `**…**`。 -粗体用于:**嵌在叙述中的代码**,以及「我想把这一小段标成可执行」的行间片段。 - ---- - -## 6. 调用 - -### 6.1 调用表面 - -```markdown -> 加一函数 37 - -**加一函数 37** - -礼貌 [问候] marqdo -``` - -前两种解析为对 `加一函数` 的调用;第三种为**方括号标记调用**(`[` `]` 标出函数名,前置裸词展开为 `名=True`)。实参位置或具名绑定;详见 [call-arguments.md](call-arguments.md) · [bracket-call-modifiers.md](bracket-call-modifiers.md)。 - -| 形式 | 典型用途 | -|------|----------| -| `> …` | 步骤列表、独立可执行行、与 v0.2/AI 习惯兼容 | -| `**…**` | 嵌在句子中:「或者可以直接这么调用**加一函数 37**」 | -| `**x = 加一 37**` | 粗体赋值右侧为调用时**可省略 `>`**(代码即文档首选;`> 加一 37` 仍合法) | -| `修饰… [函数] 实参…` | 叙述里需要「形容词 + 动词」时消歧;与 `[键](集合)` 取元靠 `]` 后是否紧邻 `(` 区分 | - -### 6.2 粗体内调用的判别 - -粗体内容在去掉外层 `**` 后,按下列优先级分类: - -1. 含 `=` 且左侧为可赋值目标(标识符 / 脚注左值等)→ **赋值语句**(可含右侧调用)。 -2. 否则,若首词为已知函数/方法/内置/导入成员(Pass 名表可见)→ **调用**。 -3. 否则 → **表达式语句**(求值后丢弃,或在语句位置非法则诊断)。 - -示例: - -| 粗体内容 | 分类 | -|----------|------| -| `n=n+1` | 赋值 | -| `加一函数 37` | 调用 | -| `加一函数 n=37` | 调用(具名) | -| `n + 1` | 表达式(单独出现时;作返回应写 `*n + 1*`) | -| `print text=hi` / `打印 内容=你好` | 调用(内置) | - -### 6.3 方法调用 - -- 独立行:`` > `对象`.方法 … ``(兼容)或 `> 对象.方法 …`(若接收者规则允许)。 -- 粗体内:`**对象.方法 …**` / `**p = page.主体装配 组件=home**`。 -- 粗体/斜体内裸名 = 变量(延续 v0.2「段内统一命名空间」精神)。 - -### 6.4 实参 - -具名 + 位置混用规则继承 [call-arguments.md](call-arguments.md);v0.3 仅把「形参列表来源」从 `+` 行改为**推断签名**(§8)。独立 `>` 行上裸词仍为文本字面量;粗体内调用的裸词为变量(与 v0.2「段内调用」一致)。 - ---- - -## 7. 返回 - -### 7.1 斜体返回 - -```markdown -*n* -*n + 1* -*"ok"* -``` - -斜体内部值语法与 v0.2 粗体返回内部相同(裸词 = 变量;文本须引号)。 - -### 7.2 空返回与收束(已决议) - -Marqdo **不引入** `return` 关键字;「无值结束」用标记表达。对照常见语言: - -| 语言 | 无值 / 空返回 | Marqdo v0.3 对应 | -|------|----------------|------------------| -| Python | `return` / `return None` | 显式 `*None*`·`*无*` | -| Go | 无结果函数里的 `return` | `*None*` / 整行 `**` / `****` | -| Rust | `()` 或函数末尾隐式 unit | 同上;或下一标题 / EOF 自然结束 | -| JavaScript | `return;` → `undefined` | 同上 → 运行时 `None` | -| Marqdo 历史 | `---` 收束;`****` | `---` 已改为叙述跳过;`****` 仍兼容 | - -#### 形式层级(推荐自上而下) - -| 优先级 | 形式 | 语义 | 说明 | -|--------|------|------|------| -| **1. 显式空值** | `*None*` 或 `*无*`(整段或行内返回位) | 返回 `None` **并结束本函数体解析** | 对齐 Python `return None`;副作用函数首选;外层续写依赖此收束 | -| **2. 空斜体标记** | **整行** trim 后恰为两个星号:`**` | 同上 | 词法钉死:`^\s*\*\*\s*$` → **空斜体返回**,**不得**当成粗体开闭 | -| **3. 兼容** | 整行 `****`(四个星号) | 同空返回 | 迁移期识别 | -| **(非收束)** | 整行 `---` / `***` | **仅叙述分隔**,跳过 | 不再结束函数;见 [code-as-docs-gaps.md](code-as-docs-gaps.md) | - -```markdown -## 只打印 -**print text=hi** -*None* - -## 空斜体行 -**print text=hi** -** - -## 分割线不收束(下一标题才结束) -**print text=hi** ---- -``` - -#### 词法消歧(空斜体 vs 粗体) - -1. **整行恰好 `**`(两个 `*`)** → 空返回(规则 2),不是未闭合粗体。 -2. **粗体代码**至少包住一个非空内容:`**x**`、`**n=1**`;不允许「空粗体代码段」作为语句。 -3. **四个星号整行 `****`** → 兼容空返回(规则 3),不解释为「空粗体代码」。 -4. 行内出现的 `**…**`(两侧还有叙述文字)按正常粗体代码扫描,不走「整行空返回」。 - -#### 与「有返回值」的关系 - -- 需要把值交回调用方 → 用非空斜体:`*n*`、`*n + 1*`(返回即结束本函数体解析)。 -- 只做副作用、不要值 → 优先 `*None*` / `*无*` / 整行 `**`。 -- 下一标题或 EOF 也可结束体;**不要**再靠 `---` 收束。 - -### 7.3 与 else 臂 `N. *` 的消歧 - -有序列表臂头 `2. *` 中的 `*` 表示 **else**,不是返回。判别:行匹配 `^\s*\d+\.\s+\*\s*$`(可带尾注)→ 分支 else;不进入返回扫描。 - -### 7.4 输出 - -```markdown -**print text=Hello** -> print text=Hello -``` - -打印是调用,不是返回。禁止把 `*Hello*` / `**Hello**` 解释为「打印 Hello」(延续 v0.2 决议精神,仅对调标记)。 - ---- - -## 8. 形参推断 - -### 8.1 目标签名 - -对每个 `## 函数`(及方法),在 Pass1 收集体之后得到: - -```text -params: Vec<{ name, default: Option<Expr>, span }> -``` - -### 8.2 收集规则(函数作用域) - -扫描该函数标题之下、下一同级/更高级标题之前的所有节点,维护**绑定图**与**形参表**(二者分离): - -#### A. 绑定图(所有变量) - -1. **声明事件**:叙述或代码中的首次 `` `名` ``,或粗体内首次对 `名` 的赋值左值。 -2. **默认/初值事件**:叙述 `` `名`=默认表达式 ``;或符合 §8.3 的「形参默认」赋值。 -3. **排除出绑定图**(不建变量): - - 循环变量 `` - [项](集合) `` 中的 `项`(循环自有绑定); - - `self` / `自`(方法自动注入)。 - -凡进入绑定图的名字都是**变量**——包括「只在叙述里出现、可执行代码从未读写」的名字(§4.4)。未使用 → **不报错**。 - -#### B. 升为形参的条件(升参) - -名字已在绑定图中,且满足下列之一,才进入 `params`: - -| 升参种类 | 条件 | -|----------|------| -| **必选形参** | 在可执行面(`**…**` / `*…*` / `>` / 结构语句)中存在对 `名` 的**读取**,且该读取无法单靠「不依赖外部输入的局部赋值」满足——典型:先声明、后 `n=n+1` / `*n*` / `**print text=n**` 等读到未先行赋成纯局部常量 | -| **可选形参** | 有默认/初值事件(`` `名`=… `` 或 §8.3 默认赋值),供调用方覆盖 | - -**不升参**:仅叙述声明、可执行面零读取(死绑定)→ 留在绑定图,**不进** `params`,调用签名不变。 - -**顺序**:按升参名字的**首次声明事件**在源码中的出现序。 - -**仍排除**:分支/块内纯局部(金样例钉启发式);显式 `+` 合并见 §8.4。 - -### 8.3 「形参默认」与「函数体赋值」的区分 - -```markdown -## 问候 -对`谁`打招呼,默认`礼貌`=False。 - -**print text=谁** -``` - -- `` `谁` `` → 必选 -- `` `礼貌`=False `` → 可选,默认 `False` -- 体里的 `**print …**` 不是给 `谁` 赋默认值 - -```markdown -## 加一函数 -输入`n`。**n=n+1**返回*n*。 -``` - -- `` `n` `` 先声明 → 必选 -- `**n=n+1**` 是**体语句**(对已声明形参赋值),**不是**默认值 - -判别启发式(实现契约): - -- 若赋值右值**依赖同名左值**(如 `n=n+1`)→ 体语句。 -- 若赋值出现在「该名被当作输入读取」之前,且右值不依赖未绑定的同名 → 可作为默认值候选。 -- 叙述形 `` `名`=字面量 `` 优先视为默认值声明。 - -### 8.4 显式 `+` 形参(过渡) - -- 若函数标题下仍有 `` + `名` `` 行:与推断结果**合并**;冲突时 **显式 `+` 胜出**并诊断警告。 -- 迁移完成后(路线图 M4)可改为:存在 `+` 则关闭推断,或直接废弃 `+`。 - -### 8.5 调用绑定 - -与现有一致:具名优先,位置按「尚未绑定的形参」从左到右填充。缺必选形参 → 语义错误。 - ---- - -## 9. 完整示例(规范金样意向) - -### 9.1 加一(动机例) - -```markdown -## 加一函数 - -对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。 - -# main - -我要调用加一函数可以采用这样的办法: - -> 加一函数 37 - -或者可以直接这么调用**加一函数 37** -``` - -期望: - -- 签名:`加一函数(n)` -- `# main` 两次调用均返回 `38`(第二次若未绑定到打印,至少 AST/求值结果为 38;可用 `**print text=…**` 观测)。 - -### 9.2 带默认值 - -```markdown -## 问候 - -向`谁`问好;`礼貌`=False 时用短句。 - -1. 礼貌 - **print text=您好,** - **print text=谁** -2. * - **print text=嗨,** - **print text=谁** - ---- - -# main - -**问候 谁=Marqdo 礼貌=True** -> 问候 Marqdo -``` - -### 9.3 对象方法(不变骨架) - -```markdown -# 计数器 - ## 加 - 将`self`的`值`增加`delta`(`delta`=1)。 - **值 = 值 + delta** - *self* - -# main -*c = > 计数器* -**c.加 3** -``` - -(方法形参推断含 `delta`;`self` 自动。) - ---- - -## 10. AST / 管线变更要点(设计约束) - -详细里程碑见 [markup-v0.3.md](../roadmap/markup-v0.3.md)。此处只钉**语义 → 树**的约束,供实现对照: - -### 10.1 行分类(lex / line-class) - -新增或调整类别: - -| 类别 | 说明 | -|------|------| -| `Prose` | 叙述行;需**内联扫描** | -| `BoldCode` | 整行或片段 `**…**` | -| `ItalicReturn` | 整行或片段 `*…*`(非 else 臂) | -| `CallLine` | `>` 调用(保留) | -| … | 原有 Heading / List / Table / Fence / Hr | - -**内联扫描**产出 `InlineBit`:`Text` | `IdentDecl/Ref` | `BoldCode` | `ItalicReturn`。 - -### 10.2 AST 节点调整(建议) - -```text -Param { name, default?, inferred: bool, span } // inferred=true 表示来自体推断 - -Stmt:: - Assign { … } // 多由 BoldCode 解析 - Call { … } // CallLine 或 BoldCode 判别为调用 - Return { value } // 由 ItalicReturn 解析(原由 Bold) - ExprStmt { … } // 可选:纯表达式粗体 - Prose { bits } // 可选:保留叙述结构供 view/catalog;求值阶段只消费 Decl - -FnDef.params: - 由 InferParams(body + prose bits) 填充,再合并显式 + -``` - -`Stmt::Return` 的**语法来源**从粗体改为斜体;dump 文本应写 `return←italic`。 - -### 10.3 Pass1 / Pass2 - -- Pass1:收集 `#`/`##` 结构;建绑定图;跑 **ParamInfer(升参)**;登记名表。 -- Pass2:粗体内调用名解析;叙述 Decl 不重复建参。 -- 诊断:**必选缺失**、`+` 与推断冲突、空返回词法歧义(非整行 `**` 的残缺粗体)。 -- Lint(可选、默认关或降级为 hint):绑定图中「从未读写」的死变量——**不得**当错误。 - -### 10.4 双后端 - -树遍历与字节码均消费同一 AST;字节码发射仅跟随 `Stmt`/`Expr` 变化,不感知 Markdown 标记。 - ---- - -## 11. 破坏性切换(无双模式) - -**产品决定(2026-09-13):** 直接以 v0.3 为唯一运行时映射;**不**保留 `--markup v0.2` / 双 edition。旧语法金样例与库文件在迁移完成前可能失败——可接受。 - -| 阶段 | 行为 | -|------|------| -| 现在 | 解析器切到 v0.3;`tests/markup-v03/` 为门禁 | -| 随后 | 批量改写 `tests/structure|keywords`、`lib/`、`ext/`、Skill、`public/` | -| 文档 | `markdown-mapping.md` 改为指向本文;ADR 0005 → Accepted | - -**机械改写:** - -- 语句 `*a = 1*` → `**a = 1**` -- 返回 `**x**` → `*x*` -- 粗体内文本字面量须引号:`**print text="hi"**`(裸词 = 变量) -- 调用可保留 `>` 或改为粗体 -- `` + `n` `` 可删,改为叙述 `` `n` `` + 升参 - ---- - -## 12. 开放问题 / 已决议 - -| # | 议题 | 状态 | 决议摘要 | -|---|------|------|----------| -| 1 | 空返回词法 | **已决议** | §7.2:推荐 `*None*`/`*无*`;整行 `**`;兼容 `****`;`---` 仅叙述跳过 | -| 2 | 提及性反引号 | **已决议** | §4.4:一律视作变量;未使用不报错、不升参;不设提及前缀 | -| 3 | 粗体内调用 vs 赋值 | **已落地** | §6.2:可赋值左值 → 赋值;否则表达式优先、再裸调用;`**n + 1**` = ExprStmt | -| 4 | `` `n`+1 `` 误声明 | **已落地** | Decl 名须为标识符;`` `n+1` `` 不升 Decl | -| 5 | 叙述强调斜体 vs 返回 | **已落地** | 整行 / `返回*…*` / 表达式形才当返回;`*only*` `*very important*` `*foo.bar*` 为叙述 | -| 6 | 一行多 `**…**` | **已落地** | 允许,按出现序执行(`tests/markup-v03/multi-bold.mq.md`) | -| 7 | view 展示 prose Decl | **已落地** | Structure / Functions 大纲:`inferred` 形参标注(`chip inferred`) | - ---- - -## 13. 非目标 - -- 不把整篇无标记 Markdown 变成可执行程序。 -- 不引入 `def` / `return` 关键字(空返回用标记,见 §7.2)。 -- 不改变 `#` / `##` 对象体系与 ext 插件 ABI。 -- 不在本文阶段修改解释器代码(见路线图)。 -- 不为「提及」另发明一套反引号方言(§4.4)。 - ---- - -## 14. 验收标准(设计完成 ≠ 实现完成) - -设计稿验收: - -- [x] 哲学 P1–P6 成文 -- [x] 与 v0.2 对照表 -- [x] 形参推断规则可实现(含升参 vs 死绑定) -- [x] 动机示例在语义上闭合 -- [x] AST/管线约束与路线图挂接 -- [x] ADR 记录决策意向 -- [x] **空返回**对照其它语言并钉死词法 -- [x] **提及/未使用变量**政策钉死 - -实现验收: - -- [x] 金样例夹具 `tests/markup-v03/`(`gold.rs` `markup_v03_*`) -- [x] 动机示例金样例通过(`inc-prose.mq.md`) -- [x] `--dump-ast` 可见 inferred params 与死绑定;`--dump-lines` 标注 `[decl]` / `[bold]` / `[italic]` -- [x] 空返回四种形式金样例通过 -- [x] 无 v0.2 双模式(默认即 v0.3) - ---- - -## 15. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-13 | 初稿:叙述统一、粗体代码、斜体返回、形参体推断;Proposed | -| 2026-09-13 | 决议空返回(§7.2)与提及性反引号(§4.4);形参改为「升参」与绑定图分离(§8.2) | -| 2026-09-14 | §7.2:`---` 不再收束;返回语句结束函数体解析;空返回首选 `*None*` | -| 2026-09-14 | 取元主语法改为 `[键](集合)`;脚注取元过渡保留 | -| 2026-09-24 | Artifact Metadata Binding(`${…}` Phase 1,仅 frontmatter):见 [binding.md](binding.md) · ADR 0006 | diff --git a/doc/design/markdown-mapping.md b/doc/design/markdown-mapping.md deleted file mode 100755 index d54dfbe..0000000 --- a/doc/design/markdown-mapping.md +++ /dev/null @@ -1,356 +0,0 @@ -# Marqdo 语法映射 v0.2(Markup-as-Syntax) - -| | | -|---|---| -| 状态 | **历史文档(v0.2 · 已废止为运行时)** — 现行见 **[markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)** | -| 日期 | 2026-08-07 | -| 取代 | v0.1 中「函数头 `-` 形参 / 裸名形参与遍历变量 / `+` 分支」 | -| 被取代 | **[markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)**(粗体即代码 · 斜体即返回 · 无双模式兼容) | -| 相关 | [objects.md](objects.md) · [code-vs-comment.md](code-vs-comment.md) · [return-hr-and-code-surface.md](return-hr-and-code-surface.md) · [module-namespace.md](module-namespace.md) | - -Markdown **标记即语法**。输出**不是**语言架构原语,而是内置函数 **`print`**(英文;见 [keywords.md](keywords.md))。 - ---- - -## 1. 哲学 - -1. `.mq.md`:打开即文档,运行即程序。 -2. **叙述注释**以空行分段:段首无标记 → 注释;段内续行一律注释(见 §2)。 -3. **可执行**靠标记:结构标记(`#` `>` `+` `-` `1.` 表…)与 **斜体语句** / **粗体返回**。 -4. **`#` = 对象/类型**,**`##`+ = 函数/方法**(嵌套按标题深度);入口优先 `# main`(见 [objects.md](objects.md))。函数体可用 `---` / `***` 或空返回收束(见 §11)。 -5. **标识符默认反引号**:形参、绑定、引用写作 `` `名` ``,与 Markdown 无序列表/链接脱钩。 - **豁免:** - - foreach 头 `` - [项](集合) `` 允许裸名或反引号(可混用),推荐裸名;循环体内引用仍用 `` `名` ``。 - - 脚注取元 `` 名[^键] ``:基名在紧跟 `` [^…] `` 时可省略反引号(`` `名`[^键] `` 仍合法);链式同理。 - - **斜体语句 / 粗体返回内部**:裸标识符默认是**变量**(含调用实参与方法接收者);文本字面量须 `"…"` 或 `'…'` 或引号实参(`key="文本"`);`` `名` `` 仍合法。这是 **Python 统一命名空间**:裸点号 `a.b` 在 `a` 为局部变量时为方法调用,否则为库路径。 - ---- - -## 2. 行首判别与成段注释 - -跳过前导空白后,对**段首行**(空行之后的第一行,或文件起始): - -| 首字符 | 分类 | -|--------|------| -| 普通文字 / 空 | **注释** | -| 标记字符 | **代码** | - -标记含:`#` `*` `>` `+` `-` `` ` `` `|`、有序数字 `1.`、围栏 `` ` ``、以及函数体内的结束分割线 `---` / `***`(见 §11)。 - -**成段注释(空行分段)**:段首一旦判定为注释,则直至下一空行之前的所有非空行一律为注释——即使续行以 `` ` `` / `-` / `*` 等开头也不升级为代码。叙述与可执行代码之间**必须空一行**。例外:单独一行的 `---` / `***` / `****`(函数结束或 frontmatter 闭合)始终为代码,并打断注释段。 - ---- - -## 3. 映射总表(v0.2) - -| 标记 | 语义 | -|------|------| -| `#` … `######` | **`#` = 对象/类型**(可 `# Child = > Parent`);**`##`+ = 函数/方法**(层差=嵌套)。见 [objects.md](objects.md) | -| 函数头下 `+ `` `名` `` ` | 形参 / 构造参数(可选 `` `名`=默认值 ``) | -| 体内 `1.` `2.` … | **分支**(有序列表臂;条件行或 else) | -| 体内 `-` | **循环**(`while` 条件,或 `[项](集合)` / `` [`项`](`集合`) `` 遍历) | -| 分支臂头整行恰为 `*`(在 `N.` 后) | else,如 `2. *` | -| `> 函数 形参=实参` 或 `> 函数 实参` | 调用(具名 / 位置,见 [call-arguments.md](call-arguments.md)) | -| `` > `对象`.方法 … `` | 方法调用(独立 `>`;实例 map 须含 `_type`)。`*…*` 段内接收者裸名:`*x = > 对象.方法 …*` | -| frontmatter `import bind:path.mq.md` / `导入` | 导入文件并绑定库名 | -| frontmatter `import bind:lib.member` / `导入` | 将库路径成员绑为本地短名(与文件导入同形) | -| `> lib.member …` / `> lib.Type.member …` | 点号路径调用(路径段裸名、无反引号) | -| `*…*` | **程序语句**(绑定、表达式句、可写的调用句等) | -| `**…**` | **返回值**(架构级;函数结果) | -| `****` / `**` + 空白 + `**` | **空返回**(`None`),并结束本函数体 | -| 无标记行 / 成段续行 | 注释(空行分段,见 §2) | -| GFM 表格 | 集合 | -| 空 RHS 赋值 + 后随 `$$…$$`(或同行 `$$…$$`) | **公式赋值** → 运行时 `formula`(见 [stdlib-math.md](stdlib-math.md));叙述面无名 `$$` 仅展示 | -| ` ```lang ` | 外联异种代码 | -| 函数体内 `---` / `***` | **结束本函数体**(无返回值函数的收束;见 §11) | - -### `+` / `-` / `1.` 消歧 - -| 位置 | `+` | `1.` … | `-` | -|------|-----|--------|-----| -| 函数标题后、**首条体语句前** | 形参:`` + `名` `` / `` + `名`=默认 `` | (非法) | (非法作形参) | -| 函数体内 | (非法作分支) | 分支臂:`1. `条件`` / `2. *` | 循环 | - -**分支从未使用 `+`。** 自 v0 起即采用 GFM 有序列表;`+` 在 v0.2 专用于形参,与 `-` 循环彻底分离。 - -### 输出不是架构 - -| 错误(旧) | 正确(v0.2) | -|------------|--------------| -| `**Hello**` 表示打印 | `> print text=Hello` | -| `+ `x` > 0` 作分支 | `1. `x` > 0` | -| `- 谁` 作形参 | `` + `谁` `` | -| `[果](篮子)` 裸名遍历 | **仍合法**(foreach 豁免);亦可用 `` [`果`](`篮子`) `` | - -`print` / `input` 为内置函数,完整表见 [keywords.md](keywords.md)。 - ---- - -## 4. 语句、返回、调用 - -### 程序语句(斜体) - -```markdown -*x = 1* -*y = x + 2* -*answer = ev[^message]* -*亦可用 = 1* -``` - -斜体内部:裸标识符 = 变量;字符串写 `"…"` / `'…'`。行首已是结构标记的构造(`#` `>` `+` `-` `|`、`1.`)**不必**再包一层斜体;斜体用于「一般语句」槽位。 - -### 返回值(粗体) - -```markdown -## 加一 - + `n` - -**n + 1** -**"ok"** -**`n` + 1** -``` - -粗体内部与斜体相同的值语法(裸词 = 变量;文本须引号)。 - -### 输出(内置函数 `print`) - -```markdown -# main - -> print text=Hello World! -``` - -### else 与斜体消歧 - -- 分支臂有序行 `N. *`(或 `N.` 后仅 `*`)→ else。 -- `*中间有内容*` → 程序语句。 -- `**…**` → 返回(与 else 无关)。 - ---- - -## 5. Frontmatter 与跨文件 - -文件头 `---` 对为 **Artifact Metadata**。其中 `import bind:path.mq.md` / `导入` 为**文件导入**;`import bind:lib.member` 为**短名**(废除独立 `use` 与 frontmatter `>` 导入)。其它 `key: value` 可为字面量或 **Binding**(`${env.NAME}` 等,加载期解析);见 [binding.md](binding.md)。调用经裸点号路径(`time.parse`、`agent.agent`);实例方法在独立 `>` 调用须 `` > `var`.method ``(`*…*` 段内接收者裸名)。详见 [module-namespace.md](module-namespace.md)。 - -**函数体内的** `---` / `***` 不解释为 frontmatter(见 §11)。 - ---- - -## 6. 对象、函数、形参 - -- `# Name`:对象(构造体);`# main` 为入口对象。 -- `# Child = > Parent`:单继承(基类须为已定义对象名;方法沿链查找,子类可覆盖)。见 [objects.md](objects.md) §5。 -- `##` / `###` …:函数或方法;挂在对象下则为方法。 -- 标准库顶层 API 使用自由函数 `## name`(见 [objects.md](objects.md))。 - -```markdown -# main - -> print text=Hello World! - -## 加问候 - + `谁` - -**你好,`谁`** -``` - -可选形参: - -```markdown -## 问候 - + `谁` - + `礼貌`=False -``` - -方法体内自动绑定 `` `自` `` / `` `self` ``。 - ---- - -## 7. 绑定、比较与字符串 - -| 写法 | 含义 | -|------|------| -| `*`x` = 1*` 或行首 `` `x` = 1 `` | 绑定 | -| `` `x` == 1 `` | 相等比较 | -| `"text"` | **双引号字符串**(复杂文本;见下) | -| `hello` / `路径` | **裸 token**(无转义,按字面量) | - -### 双引号字符串(复杂文本) - -需要转义或嵌入变量时用 `"..."`;**裸 token 不转义**,保持文档简洁: - -```markdown -> input prompt="你叫什么名字\n" -*`msg` = "Hello, `name`!\n"* -``` - -| 转义 | 含义 | -|------|------| -| `\n` | 换行 | -| `\t` | 制表 | -| `\r` | 回车 | -| `\\` | `\` | -| `\"` | `"` | -| `\'` | `'` | -| `\xHH` | 十六进制字符(如 `\x22` → `"`) | -| `\u{...}` | Unicode 码点(如 `\u{4e2d}` → `中`) | - -引号内仍可用 `` `变量` `` 插值。字面反斜杠+n 写 `\\n`(裸 token `\\n` 则就是两个字符)。未知转义(如 `\q`)按字面保留,不报错。 - ---- - -## 8. 分支与循环 - -分支(**有序列表** `1.` `2.` …),循环(`-`): - -```markdown -*`x` = 0* - -1. `x` > 0 - > print text=正数 -2. `x` < 0 - > print text=负数 -3. * - > print text=零 -``` - -```markdown -*`bool_value` = True* - -1. `bool_value` == True - > print text=True -2. * - > print text=False -``` - -**一条分支语句 = 从 `1.` 起、序号递增的一段有序列表。** 同级缩进上**再次出现 `1.`**(无论中间有无空行)开启**下一条**独立分支语句,不得并入上一段的臂列表: - -```markdown -1. `a` - > print text=A -2. * - > print text=not-A - -1. `b` - > print text=B -2. * - > print text=not-B -``` - -上例为两次独立判断(先 `a` 再 `b`),不是「四个臂的一个分支」。臂序号在同一分支内递增(`1.` → `2.` → `3.` …);**不要**在同一分支中途把序号重置为 `1.`。 - -```markdown -- [果](篮子) - > print text=今天吃`果` -``` - -反引号形式等价:`` - [`果`](`篮子`) ``。两侧可混用。 - -`while`: - -```markdown -- `n` > 0 - > print text=`n` - *`n` = `n` - 1* -``` - ---- - -## 9. 集合(表格) - -`` `名` = `` 后接 GFM 表;几何决定值类型(详见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md)): - -| 形状 | 值 | -|------|-----| -| **1 列**(竖表) | `List`(表头 = foreach 元素名,不进入元素) | -| **≥2 列 + 1 行数据**(横表) | `Map`:键 = 表头,值 = 该列标量 | -| **≥2 列 + ≥2 行数据** | `Map`:键 = 表头,值 = 该列 `List`(列向) | -| **≥2 列 + 0 行数据** | `Map`:键存在,值为空列表 | -| **首列表头 `@` / `行` / `row`** | **行向** `List` of `Map`(标记列不进入字段;任意数据行数) | -| 重复表头 | 诊断错误 | - -**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本;含 `/` 的 CSS 比率等请用引号 `"1/5"`,裸 `1/5` 为除法)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。 - -```markdown -*`k` = secret * - -`cfg` = - -| api_key | model | -|---------|-------| -| `k` | gpt-4o-mini | -``` - -行向示例: - -```markdown -`订单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | -| 2 | 梨 | 3 | - -*`名` = `订单`[^1][^品名] * -``` - -**脚注取元**(表达式级;可链式): - -```markdown -*`第一` = 篮子[^1] * # 基名可省略反引号(`[^` 已标明取元) -*`种` = 分类[^苹果] * -*`第一种苹果` = 货架[^苹果][^1] * -*`亦可用` = `分类`[^苹果] * # 反引号形式并存 -``` - -- **List**:标签须为纯数字(1-based);`[^0]` / 越界 → 报错。 -- **Map**:标签为键文本(含 `"00"` 这类数字串键);缺键 → 报错。同一外形按接收值类型分派,不把 map 上的 `[^1]` 当成「第 1 个条目」。 -- 基名:`` `名`[^键] `` 与 `` 名[^键] `` 等价;无 `` [^ `` 时裸词仍是**文本字面量**(不是变量)。 -- **插值中的取元**:在调用实参值 / 引号字符串里,`` `变量` `` 后**紧跟**(无空白)`` [^…] `` 时按取元解析,而不是字面文本:`> print text=苹果单价:`水果价格`[^苹果]`;链式 `` `货架`[^苹果][^1] `` 同理。`` `变量` [^…] ``(有空白)则 `` [^…] `` 仍是文本。 -- 文末 `[^1]: …` 定义块仍是注释,与取元无关。 -- foreach:`List` 遍历元素;`Map` 遍历**键**(值用脚注取)。 - ---- - -## 10. 求值入口 - -1. 加载 `index.mq.md` + 导入。 -2. Pass1 收集定义。 -3. Pass2 执行 `# main`。 -4. `*` 语句、`**` 返回、`>` 调用、`1.` 分支、`-` 循环、表绑定按语义执行;`> print` 写 stdout。 - ---- - -## 11. 函数体结束(`---` / `***` / 空返回) - -```markdown -# main - -> 问候 谁=World - -## 问候 - + `谁` - -> print text=Hello `谁`! - ---- -``` - -| 约定 | 说明 | -|------|------| -| `---` 或 `***` | 函数体**顶层**单独一行 → **结束本函数** | -| `****` / 空粗体 | 空返回(`None`),并结束本函数体 | -| Frontmatter | 仅**文件开头**成对 `---` = 元信息 | - ---- - -## 12. v0.2 非目标 - -- break/continue、完整错误模型、静态类型、完整 FFI -- `+` 作分支、`+`/`-` 作形参(**不保留**) - ---- - -## 13. 示例索引 - -见 [`tests/`](../../tests/)。 diff --git a/doc/design/module-namespace.md b/doc/design/module-namespace.md deleted file mode 100755 index ec74cb2..0000000 --- a/doc/design/module-namespace.md +++ /dev/null @@ -1,233 +0,0 @@ -# 模块命名空间(import / 点号寻址) - -| | | -|---|---| -| 状态 | **Accepted;嵌套 YAML `import:` / `导入:` 映射已锁定** | -| 日期 | 2026-08-13 | -| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-i18n.md](stdlib-i18n.md) · [markdown-mapping.md](markdown-mapping.md) · [objects.md](objects.md) · [call-arguments.md](call-arguments.md) · [ext-agent.md](ext-agent.md) | - ---- - -## 1. 动机 - -加载器曾把每个导入文件的顶层 `#` / `##` **扁平合并**进同一全局函数表;同名则**后导入静默覆盖**。 - -后果: - -- `lib/json` 的 `parse` 与 `lib/time` 的 `parse` 不能共存。 -- 官方 ext / 多库编排无法按大型语言习惯书写 `time.parse` / `json.parse`。 -- 旧 frontmatter 一行式 `import bind:target` 在 YAML 里会变成带空格的键,与正规元信息不兼容。 - -**结论**:模块命名空间 + 点号寻址;frontmatter 导入统一为嵌套 YAML 映射 `import:\n bind: target`。 - ---- - -## 2. 目标与非目标 - -### 2.1 目标 - -1. **导入绑定库名**:导入一个 `.mq.md` 得到一个**库(模块)绑定**,成员不倒进全局。 -2. **点号寻址调用**:`库.成员`、`库.对象.成员`;`.` 表示定义树寻址。 -3. **库名不是变量**:路径段为**裸标识符**,不加反引号。 -4. **短名与文件导入同形**:同在 `import:` 映射下写 `fmt: time.format`,废除独立 `use` 关键字。 -5. **中英对等**:`import:` / `导入:`。 - -### 2.2 非目标 - -- 第三方包管理 / 版本求解。 -- 旧 `> path.mq.md` / `> use` 双轨兼容。 -- `` `time`.parse ``(库名加反引号)。 -- `import fmt:time.*` 通配。 - ---- - -## 3. 核心语义 - -### 3.1 模块 / 库 - -| 内容 | 归属 | -|------|------| -| 顶层 `##` 自由函数 | 库根下的**函数** | -| 顶层 `#` 对象 | 库根下的**类型(对象)** | -| 类型下的 `##` 方法 | 该对象节点下的**成员函数** | -| 被导入文件的 `# main` | **不**作为入口执行 | - -### 3.2 导入句法(frontmatter) - -仍只出现在文件头成对 `---` 内。**调用**仍用 `> print`(不变)。键为合法 YAML:`import:` / `导入:`,值为嵌套映射。 - -```yaml ---- -import: - utils: utils.mq.md - json: lib/json.mq.md - fmt: time.format ---- -``` - -| 含义 | 英文 | 中文 | -|------|------|------| -| 导入文件 | `import:` → `utils: utils.mq.md` | `导入:` → `utils: utils.mq.md` | -| 标准库 | `json: lib/json.mq.md` | 同左(或中文库路径) | -| 短名(成员) | `fmt: time.format` | `fmt: 时间.格式化` | - -规则: - -- **绑定名必填**,为映射键(裸名,无反引号);冒号后须有空格(正规 YAML)。 -- 映射值 `target`: - - 以 `.mq.md` 结尾 → **文件导入**; - - 否则为 **点号路径**(≥2 段),把该成员绑为本地短名(须先有对应文件导入)。 -- 同一文件内绑定名不得冲突(文件库名与短名共用命名空间)→ 硬错误。 -- 同一文件不得同时出现 `import:` 与 `导入:`。 -- 旧写法一行式 `import bind:target`、`> ….mq.md`、`> use …` → **硬错误**;可用 `marqdo migrate imports --write` 迁移。 - -### 3.3 废除的旧规则 - -不再支持: - -- 一行式 `import bind:target` / `导入 bind:target`; -- 省略绑定名时用文件名茎作库名; -- 导入侧 `as` / `作为`; -- 独立关键字 `use` / `使用`。 - -### 3.4 调用解析顺序 - -1. **点号路径 callee**(§4)→ 按段在导入库 / 类型树上寻址。 -2. **当前文件**顶层 `#` / `##` 与 frontmatter **短名绑定**。 -3. **L0 内置**。 -4. **插件注册名**。 -5. 否则 → 未知 callee。 - ---- - -## 4. 点号寻址(核心外形) - -### 4.1 文法 - -```text -path_callee ::= ident ('.' ident)+ -``` - -### 4.2 二段:`库.成员` - -```markdown ---- -import: - time: lib/time.mq.md - json: lib/json.mq.md ---- - -# main - -*t = > time.now_unix* -*s = > time.format unix=`t` pattern="%Y-%m-%d"* -*obj = > json.parse text={"a":1}* -*a = > json.get value=`obj` key="a"* -> print text=`s` -``` - -### 4.3 三段:`库.对象.成员` - -```markdown -> agent.agent # 库 → 类型:构造 -``` - -实例方法须 `` > `var`.method ``;无接收者的 `库.类型.方法` → 硬错误。 - -### 4.4 变量 / 实例 vs 库路径(Python 统一命名空间) - -| 写法 | 含义 | -|------|------| -| `time.parse` | 库路径(裸名,第一段非变量) | -| `` > `助手`.step `` | 独立 `>` 调用:实例方法(接收者反引号) | -| `*回复 = > 助手.step …*` | `*…*` 段内:若 `助手` 是变量 → 实例方法;否则 → 库路径 | - -**统一规则**(与 Python 一致):对裸点号 `a.b`,当 `a` 是当前作用域**局部变量**时解释为**方法调用**(`a` 为接收者);否则解释为**库路径**(`lib.a.b`)。此规则同时应用于树遍历与字节码两后端。 - -- 在**独立 `>` 调用**中裸词 = 文本,故方法接收者仍须反引号:`` > `助手`.step ``。 -- 在 **`*…*` / `**…**` 段内**裸词 = 变量,接收者不加反引号:`*回复 = 助手.step …*`。 - -### 4.5 短名示例 - -```markdown ---- -import: - time: lib/time.mq.md - fmt: time.format ---- - -# main - -*t = > time.now_unix* -*s = > fmt unix=`t` pattern="%Y-%m-%d"* -``` - -### 4.6 应用侧完整示例 - -```markdown ---- -import: - time: lib/time.mq.md - writeback: lib/writeback.mq.md - agent: ext/ai/agent.mq.md - json: lib/json.mq.md ---- - -# main - -*`助手` = > agent.agent model=… tools=… * -*`out` = > `助手`.step task=… * -*`body` = > json.stringify value=`out` * -> writeback.record value=`body` key=ok -``` - ---- - -## 5. 导出面 - -默认:库内顶层 `#` / `##` 均可被路径访问。本版不引入 `private`。 - ---- - -## 6. 与旧行为的关系(破坏性变更) - -| 旧 | 新 | -|----|----| -| `import time:lib/time.mq.md` | `import:` → `time: lib/time.mq.md` | -| `import fmt:time.format` | `import:` → `fmt: time.format` | -| 茎名默认库名 | 绑定名始终显式 | -| 扁平合并进全局 | 仅库绑定 + 可选短名 | - -不提供旧一行式 / `>` 导入过渡开关;`marqdo migrate imports --write` 可机械迁移。 - ---- - -## 7. 对分层与 ext 的影响 - -| 层 | 影响 | -|----|------| -| L0 内置 | 仍为全局短名 | -| L1 / 官方 ext | 经库路径调用;**`ext/**/*.mq.md` 严禁 `host_*`** | -| ABI 插件 | 插件注册表 | - ---- - -## 8. 实现要点 - -1. frontmatter 解析嵌套 `import:` / `导入:` 映射;子项分流文件 / 成员。 -2. AST 仍用 `Import`(文件)与 `Use`(短名)存储,对外无 `use` 关键字。 -3. 金样例:`tests/structure/import/`、`tests/structure/ns/`。 - -| 阶段 | 内容 | -|------|------| -| M1+M2 | 点号路径 + 短名 — 已落地 | -| **Import 句法** | 嵌套 YAML `import:` — **本波次** | - ---- - -## 9. 决议摘要 - -1. 导入 = 嵌套 `import:` / `导入:` 映射(`bind: target`)。 -2. target = `.mq.md` 文件 **或** `库.成员` 点号路径。 -3. 调用以裸名点号路径寻址;实例方法用反引号接收者(仅独立 `>` 调用;`*…*`/`**…**` 段内接收者不加反引号)。 -4. 裸点号 `a.b`:`a` 为局部变量 → 方法调用,否则 → 库路径(Python 统一命名空间)。 diff --git a/doc/design/native-agent-flow-v3.md b/doc/design/native-agent-flow-v3.md deleted file mode 100644 index ce85b0c..0000000 --- a/doc/design/native-agent-flow-v3.md +++ /dev/null @@ -1,140 +0,0 @@ -# Marqdo native agent flow — implementation contract - -Status: **incremental, draft**. The core orchestration now has a plugin-only -alternative to interpreter-stack suspension: a durable finite step state machine -with explicit safe commit boundaries. Do not claim arbitrary stack-level -continuation or exactly-once external writes based on a checkpoint file. - -## Author surface (implemented in this branch) - -| Module | Function | Contract | -|---|---|---| -| ext/ai/context.mq.md | scope | Select a bounded source excerpt using parsed Markdown headings; ambiguous names fail closed | -| ext/ai/context.mq.md | pack | Compact caller-provided file/class/function text via ContextPackV2 | -| ext/ai/flow.mq.md | ask/choose/parse_choice | One short decision, allowed-choice verification, at most one format repair | -| ext/ai/flow.mq.md | input/reply | Durable step-boundary user-input gate keyed by id + source revision and scope | -| ext/ai/flow.mq.md | start/wait/parallel | Existing Marqdo subtask scheduler, failure-preserving parallel result aggregation | -| ext/ai/flow.mq.md | enter | Resolve only author-supplied registered skill name, run via standard subtask path | -| ext/ai/recovery.mq.md | decide/save/load | Native error policy and CheckpointV2; no implicit unsafe re-execution | -| ext/ai/workflow.mq.md | open/next/commit/cancel | Durable forward-only step machine with per-step commit boundaries | -| ext/ai/workflow.mq.md | inspect/list | Read-only progress summary and checkpoint discovery scoped by session/principal | -| ext/ai/workflow.mq.md | tick/retry_plan/retry_commit/retry_failed | One-step execution and failed-only read-only recovery | - -The native agent plugin provides `agent_choice_parse`, `agent_context_scope`, -`agent_input_open`, `agent_input_resume`, `agent_parallel_report`, and the -`agent_workflow_*` primitives including `inspect` and `list`. -Plugin errors must be visible, never converted into a fabricated successful answer. -All workflow wrappers accept a host-relative `resume_dir`, so tests and callers -can isolate checkpoints instead of sharing the default `.marqdo/agent-resume`. - -## Invariants - -- A model choice is untrusted data until verified against an explicit option list. -- An imported module is **not** automatically part of a model prompt. -- The requested heading scope, not the entire source file, is the prompt source. -- A pending user-input gate owns a persistent checkpoint, not a blocked interpreter thread. -- The same answer may be returned repeatedly; a competing answer or stale revision conflicts. -- A completed subtask wait is distinct from a successful child exit. -- Existing successful siblings remain visible when one subtask fails. -- Writes, executable effects and external writes remain under ToolSpec permissions, - the EffectLedger and source-version checks. -- No component may silently broaden a tool's authorization on failure. - -## Important limitations in this branch - -The input/reply gate stores an explicit **step boundary**. It does not yet persist -an arbitrary bytecode interpreter frame. Applications must choose and re-enter -their next Marqdo function explicitly after receiving a verified input answer. -The current source selector relies on a Markdown parser plus Marqdo heading -conventions, not on the compiler's resolved module/class/function AST and symbols. -Host identity inputs are supplied by the caller; production applications must -attest them from their authenticated session, never use model-generated identity. -The parallel wrapper reuses `subtask.run_many` and does not add durable child -lease orchestration. Live provider tests and real 1B-model benchmarking remain open. - -## Required VM/runtime completion: suspended execution - -1. Introduce `WaitingInput` as a scheduler state, distinct from terminal failure. - Save the logical run, program counter at a safe suspension boundary, bound - inputs, variable snapshot, module and tool digests, and effect watermark. -2. Resume via a new attempt linked to the original logical run, but never - automatically repeat committed effects. Preserve cancellation and budget. -3. The resume endpoint must be atomic (revision CAS), authenticate principal - and workspace, verify source and tool schema revisions, and deduplicate - repeated reply requests. Do not trust IDs inside model text. -4. Handle interrupted worker, partial snapshot, stale input, invalid choice and - unknown external write as separate outcomes. Treat unknown writes as - reconciliation-required; do not invent exactly-once guarantees. -5. Persist only serializable language values at declared safe points. If a - foreign kernel, socket or native handle is live, explicitly refuse - transparent frame recovery and preserve a safe step-level restart option. - -## Required durable parallel execution - -A parent dispatches child `.mq.md` functions using registered paths, grants -minimal capabilities, shares budget and rate limits, and persists a child task -manifest. Child completion records a status, value ref, output digest and ledger -watermark before the parent merges results. For same-resource writes, use -serialized revisions and explicit commit order. On parent cancellation, stop -new children and request child cancellation; do not assume remote writes rolled -back. On recovery, reconcile child attempts and reuse successful results. - -## Release gates - -| Test | Required observation | -|---|---| -| compiler/import check | All new `.mq.md` functions pass contract checks and execute via ABI | -| small model outputs | Exact, labeled, fenced and numeric options normalize; mixed options fail | -| input gate crash | After checkpoint, reply is committed once; alternate reply conflicts | -| source drift | Original gate cannot resume against changed source revision | -| context isolation | Class/function selectors reject ambiguity and ignore fenced headings | -| concurrent partial | Failed/uncertain child never discards successful siblings | -| unknown write | Neither retry nor recovered child duplicates an unconfirmed effect | -| long-run cancellation | Worker/child task termination preserves usable artifacts and receipts | -| compatibility | Existing `agent.step/plan/run` and workbooks remain callable | -| model evaluation | Tokens/decision, semantic validity, end-to-end completion, recovery overhead | - -Do not merge the branch as a completed runtime refactor until the relevant -runtime gates, including crash injection and multi-worker concurrency, pass. - - -## Plugin-only workflow (November 18 revision) - -The Agent ABI plugin implements -`agent_workflow_open/next/inspect/list/commit/cancel` plus the failed-only -retry primitives. The small `ext/ai/workflow.mq.md` library wraps these -primitives and provides `tick` to execute exactly one safe decision or document -task per call. `inspect` and `list` are strictly read-only: they report progress -or discover checkpoints without advancing a cursor or running a step. -Source definitions have only five step kinds: `model`, `input`, `skill`, -`parallel` and `return`. Model text is verified against declared options. -`input` intentionally returns a waiting status; the UI supplies an answer -through `commit` on a later invocation. There is no interpreter thread to -hold and no need for a separate qdagent orchestration server. - -The checkpoint records the source revision, caller-provided session and -principal scope, next step index and the completed outputs. The same step -cannot be silently committed twice. Mixed child outcomes preserve completed -siblings in the checkpoint and **block** further automatic execution until -the unknown/failed child operations are reconciled. - -The state engine does not execute arbitrary unregistered tools directly: -`tick` delegates to existing Marqdo ABI-backed SKILL/subtask functions. -This is an implementation of **durable step-state recovery**, not a claim -of transparent recovery for a suspended foreign function or native call. -It provides the practical workflow needed for short qdagent SKILLs without -altering the Marqdo interpreter. - -### Security/reliability boundary still required for production - -- The host must attest source digest, principal, session, permissions and - registry, rather than accepting values copied from an LLM response. -- Effectful child tools must use the existing EffectLedger and external - receipt reconciliation; no automatic re-dispatch after an uncertain write. -- Cancelling a workflow checkpoint does not automatically cancel previously - spawned external children; the supervisor must propagate cancellation. -- The current task runner is step-atomic, not a durable parallel child lease - scheduler. A future plugin-only child manifest may use the host's existing - `runtime` query API, but must not bypass process.exec or file-root grants. -- Cross-process locks need a lease/owner-aware stale-lock recovery path; - a stale lock currently fails closed and requires operator review. diff --git a/doc/design/notebook-session.md b/doc/design/notebook-session.md deleted file mode 100755 index ad29913..0000000 --- a/doc/design/notebook-session.md +++ /dev/null @@ -1,561 +0,0 @@ -# 文档会话(View Cells) - -## 2026-11-02:并发控制与完整历史 v5 - -以下为当前实现;后文保留首版设计与当时的状态表。 - -- HTTP `kernel/interrupt` 查找已存在的会话,经独立控制器发送请求,不等待单元执行锁或其他文档的初始化。未打开、尚在初始化的会话返回错误,不启动新内核。已加载文档的源码文件被删除后仍可取消正在执行的单元。 -- 内核的中断能力绑定其持有的子进程,并在回收前撤销;旧能力不能指向后来启动的内核。引导阶段的取消被暂存,收到 ready 后投递。逻辑取消输入会合并重复信号;投递错误明确返回。Windows 尚无对应的保状态中断实现。 -- 取消使 Run All 在当前单元结束后停止,返回实际 `ran`、`remaining` 和 `cancelled`;不会继续运行后续单元。内核没有退出时,取消前已发生的状态修改保留。close 撤销 API 会话,重新打开不会激活旧引用。 -- 完整历史 v5 将并发取消作为所在操作的 `controls` 输入记录:操作起点之后的微秒偏移及各内核的真实接收结果。严格回放按输入重新投递并重新观察回执;操作先结束时撤销剩余定时请求,不能流入下一操作。实际回执或观察不匹配就报告差异。v4 无控制输入的历史仍可检查;v4 中出现 controls 字段会被拒绝。 -- 严格检查先完成纯验证,再启动回放内核。实际执行中,每次协议请求必须先与预期请求一致;实际回复和每个单元的观察、批次结果也立即比较。首个差异后停止依赖后缀,包括同一个 Run All 内的后续单元。未执行的观察标记 `compared=false`,不冒充已比较的第二个差异。 - -快照导出支持可选 `compact:true`。默认仍为完整 JSON;紧凑格式 -`marqdo.history.dag` v1 对相同子值做自底向上共享,整数使用十进制文本、 -浮点数保存 IEEE 位模式,保留映射顺序和全部历史字段。导入和严格回放会自动 -识别格式。SHA-256 校验只检测内容一致性,不提供来源认证。 -解码要求规范节点、向后引用、全部可达和唯一键,并在展开前检查最多 -1,000,000 个节点、8,000,000 个展开值、512 MiB 保守展开预算、128 层深度; -展开后再次检查安全值域。此格式减少导出字节数,尚未减少录制时内存,也不保证更快。 - -实际取消实验覆盖 Unix 上同步 Python/Node 持久会话;不能推导任意外部代码均有界停止。 -[Python 3.14 信号文档](https://docs.python.org/3.14/library/signal.html#execution-of-python-signal-handlers) -说明纯 C 计算可延迟信号处理; -[Node 22.22.1 vm 文档](https://nodejs.org/download/release/v22.22.1/docs/api/vm.html#timeout-interactions-with-asynchronous-tasks-and-promises) -说明异步任务可能逃出同步求值的中断范围。完整源码 elaboration、控制适配器、 -真实时钟与信号调度到形式模型的 refinement 仍需完成,不能以这些测试代替。 - -相关实现:`foreign_session/control.rs`、`foreign_doc/control.rs`、 -`foreign_doc/packing.rs`、`foreign_doc/replay.rs` 与 `view/notebook_api.rs`。 -真实 TCP/HTTP 取消、逐单元副作用屏障和独立快照消费记录位于论文 -`PLDI/experiments/reviewer-v5/`。 - -| | | -|---|---| -| 状态 | **D1–D3 首版已实现;D4/D5 待做** | -| 日期 | 2026-10-17 | -| 层 | Runtime + Document(view 服务端 / 交互单元) | -| 相关 | [notebook-syntax.md](notebook-syntax.md) · [foreign-kernel.md](foreign-kernel.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [view.md](view.md) · [view-debug.md](view-debug.md) · [stdlib-subtask.md](stdlib-subtask.md) | -| 核心表面 Δ | 无(读取既有 AST 与表格) | - -> 文档会话是 view 背后的交互单元运行时:它记住哪些 cell、在哪个内核、按什么顺序执行、状态是什么、结果是否过期。它不是第二个 CLI 模式——`marqdo view` 是唯一的交互面,`marqdo run` 是规范执行。 - ---- - -## 1. 目标 - -1. **像 Jupyter 一样即时**:点一个 cell 就执行,状态保留。 -2. **不像 Jupyter 一样隐藏**:执行顺序、内核归属、状态、过期情况都可查。 -3. **不破坏 Marqdo 程序语义**:`marqdo run` 仍是规范执行;view 会话是交互镜头。 -4. **Git 友好**:状态/输出不默认写进 `.mq.md`。 -5. **多语言**:命名内核 + 显式状态桥。 -6. **可复现**:Run All / journal / dirty / stale / replay。 - ---- - -## 1.1 实施状态(2026-10-18) - -| 能力 | 状态 | 位置 | -|---|---|---| -| `foreign.session` 句柄(kernels/cells 表参数) | ✅ | `lib/foreign.mq.md` · `src/host/foreign_doc.rs` | -| cell plan 求值 | ✅ 解释器求值 `会话` 绑定;不扫描源码行、不认保留表名 | `src/interp.rs` · `src/host/foreign_doc.rs` | -| cell index(绑定名 / 行号 / source hash) | ✅ | 同上 | -| 命名内核 + 默认内核 + 语言校验 | ✅ | 同上 | -| 同内核共享 / 跨内核隔离 | ✅ | Node 金样例 + 单测 | -| `run_cell` / `step` / `run_all(restart)` | ✅ | `DocumentSession` | -| `restart_kernel` / `assign_kernel` | ✅ | 同上 | -| `kernel/interrupt` | 待做 | — | -| 状态桥 `push` / `pull` / `state_list` | ✅ | `DocumentSession` + `foreign_session` | -| journal(记录 + API + Journal 按钮) | ✅ | `DocumentSession::journal_json` · view | -| view 工具栏 / 状态徽标 / 内核下拉 / 状态表单 | ✅ | `src/view/html.rs` | -| `POST /api/session/*` | ✅(含 `reload`) | `src/view/notebook_api.rs` | -| cell step | ✅ | 同上 | -| Marqdo statement step | ✅(view 工具栏 Debug → 同一 view 服务的 `/debug`;`/api/debug/*`) | `src/debug` · `src/view/debug_api.rs` | -| dirty/stale 自动检测 | 部分(reload → dirty;assign → dirty;stale 传播待做) | `src/host/foreign_doc.rs` | -| writeback 集成 | 待做 | `writeback` | -| replay / 持久化 | 待做 | — | -| Python 会话 | ✅(本机无 python,CI/用户机条件测试) | `src/host/foreign_session.rs` | -| Node 会话 | ✅ | 同上 | - -首版刻意不做:把状态写进 `.mq.md`、自动镜像变量、foreign 行级 debug、跨文档共享内核。 - ---- - -## 2. 两个执行面(不是两个 CLI 模式) - -### 2.1 Program execution(规范) - -- 入口:`marqdo run doc.mq.md` / CI / `view` 的 `Run document`。 -- 执行:`# main` 程序语义;外联通过显式 `foreign.session_open/eval/call` 编排。 -- 状态:一次运行内有效;运行结束进程退出(除非显式持久内核)。 -- 结果:可复现;是文档的“真理”。 - -### 2.2 View cells(交互) - -- 入口:`marqdo view doc.mq.md` → 文档单元(cell)控制。 -- 执行:按 `会话表`(或自动顺序)逐 cell 执行。 -- 状态:内核持久;可切换、重启、单步。 -- 结果:默认临时显示;可显式 writeback。 -- 不是“真理”:是探索界面;需要复现时用 Run All 或把编排写进 `# main`。 - -### 2.3 两者关系 - -```text - .mq.md - / \ - Program run View cells - (canonical) (interactive) - \ / - Document Session - ├── cell index - ├── kernel registry - ├── journal - └── state panel -``` - -- 共享 cell index 与 kernel registry。 -- `run` 不消费视图会话;`view` 只在文档绑定 `会话 = > foreign.session ...` 时提供持久 cell 控制;无 `会话` 时 cells 无状态一次性执行。 -- 冲突时以 `run` 的程序语义为准;view cells 不改变文档语义。 - ---- - -## 3. 文档会话模型 - -```text -DocumentSession -├── doc_path / doc_hash -├── cells: Vec<Cell> -│ ├── id (name / anon@line) -│ ├── name (binding) -│ ├── lang -│ ├── line_start / line_end -│ ├── source_hash -│ ├── kernel (resolved) -│ └── status: never | clean | dirty | stale | error | running -├── kernels: KernelRegistry -│ ├── name → ForeignSession -│ └── default per language -├── value_store: HashMap<String, Value> // Marqdo 侧会话值 -├── journal: Vec<ExecutionRecord> -├── created_ms / last_active_ms -└── surface: program | view -``` - -### 3.1 Cell - -- 只有**绑定名**的代码围栏才是 cell: - ```markdown - `加载` = - ```python - ... - ``` - ``` -- 未绑定围栏仍是叙述,不是 cell。 -- `id`:优先绑定名;匿名围栏用 `anon@<line>`(不进入会话表)。 -- 同名 cell 重复 → 诊断;会话表按名字引用。 -- `source_hash` 用于 dirty 判断。 -- `line_start/line_end` 用于定位;编辑后重建索引。 - -### 3.2 Cell index 构建 - -1. 读取/解析文档(现有 `parse_source` / `load_module`)。 -2. 遍历 AST,找 `Stmt::Assign { name, value: Expr::Code(c) }`。 -3. 记录 name、lang、source、span、source hash。 -4. 通过解释器求值 `会话` 绑定(`foreign.session` 返回的句柄,含简单依赖);不扫描源码行、不认保留表名(见 [notebook-syntax.md](notebook-syntax.md))。 -5. 解析 kernel 声明与 cell 归属;校验;生成诊断。 -6. 生成执行顺序: - - 有会话表 → 行顺序; - - 无 → 文档顺序。 -7. 未入会话的 cell → 状态 `unlisted`,UI 显示徽标。 - -### 3.3 Kernel registry - -- key:`<document_id>:<kernel_name>`。 -- 默认:`default:python`、`default:node`,按需启动。 -- 命名:来自 `内核表`,首次执行时启动。 -- 状态:`idle | starting | ready | busy | dead`。 -- 同一 kernel 的 cell 严格串行;不同 kernel 可并行。 -- 重启:kill + 清空状态 + 重新启动;cell 状态变 `never`。 -- 关闭:kill + 移除。 - -### 3.4 Value store(Marqdo 侧会话值) - -- 保存可从 Marqdo 推入内核的值(来自最近一次 Program run 的 bindings,或用户手动输入)。 -- 也保存从内核取回的值(`session_get` / 状态面板 Pull)。 -- 不是解释器 Env 的实时镜像;它是会话层的**值缓存**。 -- 注入解释器:未来通过 `SessionEnv` 或显式变量赋值;v2 不做隐式注入。 -- 用途: - - 状态面板显示; - - Push 到内核; - - 作为 `session_set` 的值来源; - - journal 记录。 - -### 3.5 Journal - -每次执行追加一条: - -```json -{ - "seq": 3, - "cell": "汇总", - "kernel": "分析", - "lang": "python", - "ok": true, - "code": 0, - "ms": 42, - "source_hash": "…", - "stdout_hash": "…", - "result_hash": "…", - "started_ms": 1760000000000, - "error": "" -} -``` - -用途: - -- 执行序号 / 顺序; -- dirty/stale 判断; -- replay; -- 视图显示; -- 调试(“为什么这个 cell 有值”)。 - -存储:内存 + 可选 `.marqdo/sessions/<doc-hash>.json`(默认 git 忽略)。 - ---- - -## 4. 执行语义 - -### 4.1 操作 - -| 操作 | 语义 | -|---|---| -| **Run cell** | 执行选中的 cell;必要时启动/复用 kernel | -| **Run above** | 按会话顺序执行到选中 cell(含) | -| **Run all** | 按会话顺序执行全部;可选 `restart` | -| **Step next cell** | 执行会话顺序中的下一个未执行/选中 cell | -| **Step next statement** | Marqdo 语句级单步(DebugController) | -| **Restart kernel** | kill + 重建;cell 状态 `never` | -| **Interrupt** | kill 当前 cell 进程组;kernel 标记 dead 或重启 | -| **Reset session** | 关闭所有 kernel,清 journal / value store | - -### 4.2 执行一个 cell - -```text -resolve cell -> resolve kernel - -> ensure kernel ready - -> [送入?] 显式 bridge 由文档代码/UI 负责 - -> foreign.session_eval(kernel, source, input?) - -> record -> update cell status - -> [取回?] 由文档代码/UI 负责 - -> journal append - -> view update -``` - -- 默认 cwd = 文档目录;env = kernel env。 -- 输出:stdout / stderr / result / ms / truncated。 -- 失败:cell 状态 `error`;journal 记录;不自动重试。 -- 同一 kernel 串行;UI 禁用并发 Run。 - -### 4.3 Step 语义 - -| 类型 | 行为 | -|---|---| -| **Cell step** | 执行下一个会话 cell;状态保留 | -| **Marqdo statement step** | 执行下一条 Marqdo 语句;遇到 `foreign.session_eval` 时整个外联调用原子完成 | -| **Foreign line step** | 不做;未来 DAP | - -- Cell step 是 view cells 的主单步。 -- Statement step 复用 `DebugController`;需要把 debug session 与 DocumentSession 关联。 -- 两者可以互相切换:cell step 到某个 Marqdo cell 后可 statement step;语句执行完回到 cell 边界。 - -### 4.4 中断 - -- `Interrupt`:向当前 kernel 进程组发 SIGINT/SIGKILL;记录 `interrupted`。 -- 若 kernel 状态不确定 → 标记 dead;建议 restart。 -- 不允许“中断后继续用同一 kernel”除非确认状态。 - -### 4.5 并发 - -- 同一 kernel:一次一个 cell。 -- 不同 kernel:可并行(例如 Python 分析与 Node 前端)。 -- `Run all` 默认按会话顺序串行;可配置“按 kernel 并行、按依赖串行”(后续)。 -- 并发上限沿用 foreign(32)。 - ---- - -## 5. 状态桥(会话层) - -### 5.1 显式 API - -文档代码: - -```markdown -把 `数值表` 送进 `分析` 内核: -**> foreign.session_set id="分析" name="xs" value=`数值表`** - -从 `分析` 内核取回 `mean`: -**`均值` = > foreign.session_get id="分析" name="mean"** -``` - -### 5.2 状态面板 - -- 左侧:Marqdo 侧值(最近 Program run bindings + value store)。 -- 右侧:每个 kernel 的变量(`session_names` + 按需 `session_get`)。 -- 操作: - - Push:选 Marqdo 值 → kernel 变量; - - Pull:选 kernel 变量 → value store / 显示; - - Refresh; - - 复制名称/值。 -- Secret 打码;大对象显示摘要(类型/长度/repr 截断)。 - -### 5.3 自动镜像 - -- v2 不做。 -- 后续 `mirror`:`mq_` 前缀、白名单、按值拷贝、默认关。 -- 原因见 [decisions](../research/foreign-notebook-decisions.md) §1-F。 - -### 5.4 类型 - -- JSON 拷贝;复杂对象需 `to_dict` / JSON。 -- 大对象:v2 显示摘要;传输用文件/DB。 -- 未来:Arrow / Parquet / 共享文件句柄。 - ---- - -## 6. Dirty / Stale / Run All - -### 6.1 定义 - -| 状态 | 条件 | -|---|---| -| `never` | 未执行 | -| `clean` | 上次执行成功后源码未变 | -| `dirty` | 源码 hash 变了 | -| `stale` | 上游 cell 变了(依赖图;v2 先按会话顺序近似) | -| `error` | 上次执行失败 | -| `running` | 正在执行 | -| `unlisted` | 不在会话表 | - -### 6.2 依赖 - -- v2:会话表行顺序 + 简单规则: - - 若上游 cell 的 source_hash 变了,下游标 `stale`; - - 若 kernel 重启,全部 `never`。 -- v2.1:变量级依赖图(静态分析 + bridge 表),精确 stale。 -- 不假装 Jupyter 的“隐藏顺序”:顺序就是表/文档顺序。 - -### 6.3 Run All - -- 默认:按会话顺序执行;可选 `restart=true`。 -- 规范执行:**restart + run all**;UI 明确按钮 `Restart & Run All`。 -- 未重启时:显示“当前 kernel 有历史状态”警告。 -- 执行后:生成 session summary(ok/fail/耗时/跳过的 cell)。 - -### 6.4 Replay - -- 用 journal 的顺序和输入 hash,在新 kernel 上重放; -- 比较 stdout/result hash; -- 输出 divergence 报告。 -- v2 可选;至少保留 journal 以便未来实现。 - ---- - -## 7. 输出与文档 - -### 7.1 默认 - -- View cells 输出只在 view 中显示;不写 `.mq.md`。 -- 关闭/刷新后可通过 journal 恢复最近结果(若 session 持久化)。 -- 不写 execution_count 到文档。 - -### 7.2 显式 writeback - -- 复用 `lib/writeback` 的 `<!-- marqdo-out … -->`。 -- cell 输出锚点:cell 名 + 行号;写入位置在围栏之后,或文档末尾的“输出”区。 -- 可选: - - 单 cell 写回; - - 全部写回; - - 只写回文本/数值,不写复杂对象。 -- Git 友好:输出是普通 Markdown 注释块;可 diff、可忽略。 - -### 7.3 不写回 - -- 避免 Jupyter 的 `.ipynb` 输出噪声。 -- 需要分享结果时,导出 HTML / 静态 view,而不是改源文件。 - ---- - -## 8. View 交互 - -### 8.1 工具栏 - -```text -[Run All] [Restart & Run All] [Step Cell] [Step Statement] -Kernel: [分析 ▾] Status: ready [Restart] [Interrupt] -[State] [Journal] [Writeback ▾] -``` - -### 8.2 每个 code card - -```text -`加载` python · kernel 分析 · run #3 · 42ms · clean -[Run] [Step] [Kernel ▾] [State] [Copy output] -``` - -- 状态徽标:`never` / `clean` / `dirty` / `stale` / `error` / `running` / `unlisted`。 -- 输出区:stdout / stderr / result / 截断提示。 -- 内核下拉:切换归属;不迁移状态;提示需要重跑。 -- `Step` = 执行此 cell(cell step)。 - -### 8.3 状态面板 - -- Marqdo / kernel 分栏。 -- Push/Pull。 -- Secret 打码。 -- 大对象摘要 + 复制 JSON。 - -### 8.4 Journal 面板 - -- 表格:seq / cell / kernel / ok / ms / 时间 / 错误。 -- 点击跳转 cell。 -- 导出 JSON。 - -### 8.5 键盘 - -- `Ctrl/Cmd + Enter`:Run cell。 -- `Shift + Enter`:Run cell + 下一个。 -- `Alt + Enter`:Run cell + 插入?不做。 -- `F10`:Step statement(与 debug 一致)。 -- `F5`:Run All。 - ---- - -## 9. 服务端 API - -所有 API 以文档相对路径 + session id 定位;session 内存驻留,进程退出即失。 - -| 方法 | 路径 | 作用 | -|---|---|---| -| POST | `/api/session/open` | 打开文档会话,返回 cells / kernels / journal | -| POST | `/api/session/close` | 关闭会话,kill 所有 kernel | -| POST | `/api/session/reload` | 重新解析文档,保留 kernel(标记 dirty) | -| POST | `/api/session/cell/run` | 执行指定 cell | -| POST | `/api/session/cell/step` | 执行下一个 cell | -| POST | `/api/session/run_all` | 按会话顺序执行;`restart` 可选 | -| POST | `/api/session/kernel/restart` | 重启指定 kernel | -| POST | `/api/session/kernel/interrupt` | 中断当前 cell | -| POST | `/api/session/kernel/assign` | 改 cell 的 kernel 归属(会话内) | -| POST | `/api/session/state/list` | Marqdo / kernel 变量列表 | -| POST | `/api/session/state/push` | Marqdo 值 → kernel | -| POST | `/api/session/state/pull` | kernel 变量 → value store | -| POST | `/api/debug/*` + `/debug` | Marqdo 语句单步(Debug 按钮,复用 debugger) | -| POST | `/api/session/writeback` | 显式写回 cell 输出 | -| POST | `/api/session/journal` | 执行日志 | -| GET | `/api/session` | 当前会话摘要 | - -响应统一:`{ok, session, ...}`;错误 `{ok:false, error, code?}`。 - ---- - -## 10. 生命周期与持久化 - -- Session key:`<root>/<doc_rel>`;每个文档一个。 -- 打开:解析、建 cell index、按需启动 kernel。 -- 空闲超时:默认 30 分钟关闭(可配置)。 -- 文档关闭 / 服务退出:kill 所有 kernel。 -- 文件变更:view 刷新时 `reload`;cell hash 变化 → dirty;kernel 保留。 -- 持久化(可选): - - `.marqdo/sessions/<doc-hash>.json`:kernel 名称/语言、cell 归属、journal、value store 摘要; - - 默认 git 忽略; - - 不持久化进程状态 / 大对象。 -- 不把 session 状态写进 `.mq.md`。 - ---- - -## 11. 安全 - -| 项 | 策略 | -|---|---| -| exec | 所有 kernel 启动/执行检查 `allow_exec`;沙箱拒绝 | -| 生命周期 | 每文档;关闭/drop kill;不跨文档 | -| cwd | 文档目录 / `fs_root`;越界拒绝 | -| 输出 | 有界;截断标记 | -| 超时 | cell 级;进程组 kill | -| 中断 | 杀进程组;kernel 标记 dead | -| Secret | 状态面板打码;JSON 不默认暴露 | -| 未信任文档 | 不自动打开会话;必须显式 Run | -| 并发 | 同 kernel 串行;不同 kernel 上限 32 | -| writeback | 显式;路径沙箱;不自动改文档 | - ---- - -## 12. 测试 - -### 12.1 服务端 - -- cell index:绑定名/行号/lang/source hash;未绑定围栏排除。 -- 会话解析:foreign.session 句柄/自动模式/重复/未知/语言不匹配。 -- 会话:open/close/reload;kernel 启动/重启/中断。 -- cell run:状态机 never→running→clean/error;dirty/stale。 -- step:cell step 顺序;statement step 与 debug 联动。 -- state:push/pull/list;Secret 打码;大对象摘要。 -- journal:顺序、hash、失败。 -- 并发:同 kernel 串行;不同 kernel 并行。 -- 安全:exec=false 拒绝;cwd 越界;超时。 - -### 12.2 金样例 - -- `tests/notebook/kernels.mq.md`:foreign.session 句柄。 -- `tests/notebook/shared-state.mq.md`:两个 Python cell 共享 `x`。 -- `tests/notebook/step.mq.md`:cell step 顺序。 -- `tests/notebook/state-bridge.mq.md`:Marqdo ↔ Python 推拉。 -- `tests/notebook/invalid-*.mq.md`:诊断。 -- 依赖:node 为主,python 条件跳过。 - -### 12.3 UI - -- 手工冒烟:Run cell / Step / Run All / Restart / State Push/Pull / Journal。 -- 不引入前端测试框架;用服务端 API + 静态检查。 - ---- - -## 13. 与 Jupyter 对照 - -| 维度 | Jupyter | Document Session | -|---|---|---| -| 源 | `.ipynb` | `.mq.md` | -| 执行顺序 | 隐藏的 `In[n]` | 会话表 / 文档顺序 / journal | -| 状态 | 隐藏 kernel | kernel + value store + 状态面板 | -| 多语言 | 一文档一 kernel | 命名内核 + 每 cell 归属 | -| 单步 | cell | cell + statement | -| 复现 | 手动 | Restart & Run All + journal + replay | -| Git | 输出/计数噪声 | 源码干净;输出显式 | -| 知识 | 无 | OKF / catalog | -| 调试 | 语言 pdb | Marqdo 断点 + cell 级;行级后续 | - ---- - -## 14. 实现顺序(D 层) - -| 阶段 | 内容 | -|---|---| -| D0 | 设计/语法/决策文档(本文件) | -| D1 | `src/host/foreign_doc.rs`:cell index、foreign.session 句柄、session 结构、诊断 | -| D2 | 服务端 API:open/close/cell run/step/run_all/restart/interrupt | -| D3 | view UI:工具栏、cell 徽标、kernel 下拉、状态面板、journal | -| D4 | statement step 接入;dirty/stale;writeback | -| D5 | replay / 持久化 / 并发优化 / 测试补全 | - -依赖 F 层:F3 持久内核、F3.5 状态桥先完成,D2 才能工作。 - ---- - -## 15. 明确不做(v2) - -- Foreign line-level step。 -- 自动镜像变量。 -- 跨文档共享 kernel。 -- 全进程快照。 -- 自动执行 cell。 -- 把 session 状态写进 `.mq.md`。 -- 前端 SPA 框架重写;沿用现有 HTML/JS。 diff --git a/doc/design/notebook-syntax.md b/doc/design/notebook-syntax.md deleted file mode 100755 index dc5cee1..0000000 --- a/doc/design/notebook-syntax.md +++ /dev/null @@ -1,305 +0,0 @@ -# 文档原生 view cells 语法 - -| | | -|---|---| -| 状态 | **Decided;D1 解析已实现** | -| 日期 | 2026-10-17 | -| 层 | Document(读取约定) + Runtime(校验) | -| 相关 | [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [notebook-session.md](notebook-session.md) · [foreign-kernel.md](foreign-kernel.md) · [core-surface.md](core-surface.md) · [layers.md](layers.md) | -| 核心表面 Δ | **无**——不新增标记;只用既有 `# main` / 赋值 / 表格 / 反引号 | - -> 目标:让“这段代码在哪个内核里、按什么顺序执行、和谁共享状态”像目录一样可读,而不是像 IDE 配置一样可读。 - ---- - -## 1. 为什么不用围栏元数据 - -Jupyter 的 cell 元数据、VS Code 的 `kernel=`、YAML 的 `kernels:` 都属于**代码/编辑器思维**: - -- 读者看到的是一行属性,不是一段知识; -- 属性藏在围栏 info string 或 JSON 里,Markdown 预览看不见意图; -- 一旦加 `kernel=`,它就是 Language 层语法,需要 ADR、core-surface 增行; -- 同一个文档的执行计划被拆散到每个围栏,无法一眼总览。 - -Marqdo 的选择: - -> **执行计划本身是一张表。表是文档的一部分,人先读表,机器再读表。** - -这不是新语法。GFM 表已经是集合,`` `名` = `` + 表已经是数据绑定;我们只约定两个**数据表的名字**。 - ---- - -## 2. 两个约定数据表 - -它们放在 `# main`(或唯一入口对象)的体内,和代码单元并列: - -```markdown -# main - -`内核表` = - -| 名称 | 语言 | 命令 | 说明 | -|------|------|------|------| -| 分析 | python | | 读取与清洗数据 | -| 绘图 | python | | 独立环境 | - -`会话表` = - -| 单元 | 内核 | 说明 | -|------|------|------| -| 加载 | 分析 | 读取原始数据 | -| 清洗 | 分析 | 处理缺失值 | -| 汇总 | 分析 | 按城市聚合 | -| 绘图 | 绘图 | 输出 SVG | -``` - -为什么是“绑定的表”,不是 `# 外联内核` 对象: - -- `#` 是对象/函数;把元数据做成顶层对象会把文档拆成多个作用域,code fence 会被困在对象里。 -- 绑定表是入口体内的**数据**,与 cell 同一作用域;不执行、不改变控制流。 -- View / 文档会话读取 AST 中的绑定值,不需要执行文档。 -- 解析器零改动。 - -### 2.1 `内核表` / `kernels` - -| 列 | 必填 | 含义 | -|---|---|---| -| `名称` / `Name` | ✅ | 内核名,供 `会话表` 引用;建议用领域词(分析/绘图/前端) | -| `语言` / `Language` | ✅ | 预设 id 或已注册语言:`python` / `node` / … | -| `命令` / `Command` | 可选 | 覆盖解释器命令;空白 = 预设 / `set_cmd` / 配置 / 环境变量 | -| `说明` / `Notes` | 可选 | 给人读的一句话;不影响执行 | - -规则: - -- 名称在文件内唯一;重复 → 诊断。 -- 语言不支持会话时,内核仍可声明,但只能执行一次性 cell;`session_*` 报错。 -- `命令` 只写可执行文件;参数请用 `.marqdo/foreign.toml` 或 `session_open`。 -- 没有 `内核表`:每种语言自动一个 `default` 内核。 -- 声明了内核但 `会话表` 没引用:允许,只是没有被使用。 - -### 2.2 `会话表` / `session` - -| 列 | 必填 | 含义 | -|---|---|---| -| `单元` / `Cell` | ✅ | 代码围栏的绑定名(`` `加载` = `` 后面的名字),表格里**不写反引号** | -| `内核` / `Kernel` | ✅ | `内核表` 中的名称,或语言 id(`python` / `node`)表示该语言默认内核 | -| `说明` / `Notes` | 可选 | 给人读的一句话 | - -规则: - -- **行顺序 = 执行顺序**。这是 `Run All`、`Step`、`Run Above` 的规范顺序。 -- 只有列出的 cell 参与会话;未列出的代码围栏仍然显示,但标记为“未入会话”,Run All 不执行。 -- 没有 `会话表`:所有绑定名的代码围栏按**文档出现顺序**自动入会话,每种语言用默认内核。 -- `单元` 必须对应一个已绑定名的代码围栏;找不到 → 诊断。 -- 同名 cell 重复出现 → 诊断;建议一个名字只绑一个围栏。 -- `内核` 未声明且不是语言 id → 诊断,列出已声明内核。 -- cell 的语言与内核语言不一致 → 诊断;别名等价(`python3`/`py` ↔ `python`)。 -- 表可以出现在 `# main` 体内任意位置;读者可以从表一眼看到执行计划。 - -### 2.3 为什么放在 `# main` 体内 - -- `# main` 是入口;cell 绑定与元数据表同一作用域。 -- `marqdo run` 会正常求值这两个表(得到 `List of Map`),没有副作用。 -- 文档会话从 AST / 最近一次运行的 bindings 读取它们;不需要新的解析路径。 -- 如果文档没有 `# main` 而是唯一 `#` 对象,同样适用。 - ---- - -## 3. 完整示例 - -````markdown -# main - -这份文档演示一个最小 view cells 文档:两个 Python 单元共享 `分析` 内核, -一个绘图单元在隔离的 `绘图` 内核里运行。 - -`内核表` = - -| 名称 | 语言 | 命令 | 说明 | -|------|------|------|------| -| 分析 | python | | 数据读取与聚合 | -| 绘图 | python | | 独立绘图环境 | - -`会话表` = - -| 单元 | 内核 | 说明 | -|------|------|------| -| 加载 | 分析 | 读取原始数据 | -| 清洗 | 分析 | 处理缺失值 | -| 汇总 | 分析 | 按城市聚合 | -| 绘图 | 绘图 | 输出 SVG | - -`加载` = -```python -import json - -rows = [ - {"city": "上海", "value": 3}, - {"city": "北京", "value": 5}, -] -print(json.dumps(rows, ensure_ascii=False)) -``` - -`清洗` = -```python -rows = [r for r in rows if r["value"] > 0] -``` - -`汇总` = -```python -from collections import Counter - -counts = Counter(r["city"] for r in rows) -print(dict(counts)) -``` - -`绘图` = -```python -print("plot-ready") -``` - -`汇总` 和 `绘图` 分属两个内核;`绘图` 看不到 `rows`。 -需要共享时,用 Marqdo 显式把值送过去: - -**> foreign.session_set id="绘图" name="rows" value=`rows`** -```` - -读者即使不运行,也能从 `会话表` 读出:先加载、再清洗、再汇总,最后绘图;前三个共享 `分析`,绘图在 `绘图`。 - ---- - -## 4. 自动模式(没有表) - -### 4.1 没有任何约定表 - -````markdown -# main - -`分析` = -```python -x = 41 -``` - -`结论` = -```python -print(x + 1) -``` -```` - -解释: - -- 两个 cell 都是 `python`; -- 自动使用 `default:python` 内核(一个); -- 按文档顺序执行; -- 共享 `x`。 - -现有文档不需要改一行就能在 view 里 cell-by-cell 运行。 - -### 4.2 只有内核表 - -- 所有 cell 按文档顺序; -- 每种语言解析到该语言的 `default` 内核; -- 命名内核只有被 `会话表` 引用时才使用。 - -### 4.3 只有会话表 - -- `内核` 列只能写语言 id; -- 每个语言 id 解析到该语言默认内核; -- 未列出的 cell 不入会话。 - ---- - -## 5. 可读性规则(语法评审标准) - -新增/修改任何 cell 表约定,必须满足: - -1. **先读人话**:去掉执行语义后,表格仍像目录/清单。 -2. **不使用属性串**:不写 `kernel=…`、`class=…`、JSON/YAML 元数据。 -3. **不隐藏意图**:执行顺序、内核归属必须在一处可见。 -4. **不引入新标记**:只用 `#` / 表格 / 反引号 / 既有代码面。 -5. **默认安全**:表格只声明,不自动执行;只有 Run / Step 触发。 -6. **命名用领域词**:`分析`、`绘图`、`前端`,不用 `k1`、`default`、`stage2`(除非确实是默认)。 -7. **说明列可选但推荐**:给未来的读者/LLM 一点上下文。 -8. **错误可读**:诊断要指出“哪个单元、哪个内核、哪一行、怎么修”。 -9. **中英对称**:中文用中文列名,英文用英文列名;语义一一对应。 -10. **无表也能跑**:约定表是增强,不是前置条件。 - ---- - -## 6. 诊断规范 - -| 情况 | 诊断(中文示例) | 修复建议 | -|---|---|---| -| 内核名重复 | `内核表: 内核名「分析」重复(第 12、20 行)` | 改名或合并 | -| 会话引用未知内核 | `foreign.session: cell「汇总」引用了未声明的内核「分析」` | 在 kernels 表声明,或改用语言 id | -| 会话引用未知单元 | `会话表: 找不到名为「清洗」的代码单元` | 检查 `` `清洗` = `` 绑定 | -| 单元重复 | `会话表: 单元「汇总」重复出现` | 每个单元只列一次 | -| 语言不匹配 | `会话表: 单元「前端」(node) 不能使用 python 内核「分析」` | 换内核或换语言 | -| 未入会话 | (非错误)view 徽标:`未入会话` | 需要时加一行 | -| 内核表为空 | `内核表: 至少声明一个内核,或删除该表使用默认内核` | 删除表或补行 | -| 会话表为空 | `会话表: 至少列出一个单元,或删除该表使用自动顺序` | 删除表或补行 | - -原则:**不静默忽略**。读者必须知道为什么某个 cell 没跑。 - ---- - -## 7. 与 program execution 的关系 - -- `内核表` / `会话表` 只是传递给 `foreign.session` 的普通表变量,不是保留名。 -- `marqdo run` 仍然执行 `# main` 的程序语义;这两个表会被求值为普通数据。 -- `run` 的外联编排用显式 API(`foreign.session_open` / `session_eval` / `call`);`foreign.session` 句柄服务 `view` 的 cells 与一键 Run All。 -- 两者可以并存: - - 文档用表描述“交互时怎么跑”; - - `# main` 用显式调用描述“CI 时怎么跑”。 -- 如果两者冲突,以 `run` 的程序语义为准;cell 表只影响 `view`。 - -这样避免把“执行计划”变成第二套程序语义。 - ---- - -## 8. 状态桥的语法边界 - -v2 **不**为状态交换新增表格/注释。原因: - -- “什么时候送、什么时候取、送到哪个内核、赋值给哪个 Marqdo 变量”需要精确语义; -- 若做成隐式表格动作,容易产生隐藏状态与顺序歧义; -- v2 先用显式 API,把时序讲清楚: - ```markdown - 把 `数值表` 送进 `分析` 内核: - **> foreign.session_set id="分析" name="xs" value=`数值表`** - - 从 `分析` 内核取回 `mean`: - **`均值` = > foreign.session_get id="分析" name="mean"** - ``` -- view 提供状态面板与 Push/Pull 按钮,减少手写 API 的需要; -- 声明式 `共享表` 作为 v2.1 提案,等 session value store 与“每次单元执行前后”的时序稳定后再引入。 - -这不是降级:v2 的功能完整(可读可写、可推可拉),只是不用隐式语法承载时序。 - ---- - -## 9. 未来扩展(不承诺进 v2) - -1. `共享表`: - `| 内核变量 | Marqdo 变量 | 方向 | 说明 |`,每次单元执行前送入、后取回。 -2. 每个 cell 的“运行条件/依赖”列:`依赖` 列声明上游单元。 -3. 内核别名:`内核表` 的 `名称` 可被 `use` 或短名引用。 -4. 多文件会话:跨 `.mq.md` 的共享内核(默认仍隔离)。 -5. 语言特定的“会话能力”列(是否支持持久、是否支持行级调试)。 - -任何一项都要先过 §5 的可读性规则与 `core-surface` 检查。 - ---- - -## 10. 实现落点 - -| 逻辑 | 位置 | -|---|---| -| 识别 `会话` 的 foreign.session 句柄 | `src/host/foreign_doc.rs` | -| 读取绑定值 | AST `Stmt::Assign` + `Expr::Table` / `Expr::List`;或最近一次 run 的 bindings | -| 校验名称/语言/重复/未入会话 | 同上;错误进入现有 Diagnostic | -| cell index(绑定名/行号/语言/source hash) | 解析后的 `Module` 遍历 | -| 只读展示 | view Structure:表渲染成普通表格 + 徽标 | -| 执行 | Document Session API(见 [notebook-session.md](notebook-session.md)) | - -解析器本身**不需要改**。这是本设计最重要的约束:语法是既有标记的组合,不是新构造。 diff --git a/doc/design/objects.md b/doc/design/objects.md deleted file mode 100755 index af1a50d..0000000 --- a/doc/design/objects.md +++ /dev/null @@ -1,104 +0,0 @@ -# Objects(`#`)与函数(`##`+) - -| | | -|---|---| -| 状态 | Accepted | -| 日期 | 2026-08-06 | -| 相关 | [markdown-mapping.md](markdown-mapping.md) · [ext-llm.md](ext-llm.md) | - -## 1. 约定 - -| 标题层 | 含义 | -|--------|------| -| `#`(恰好一层) | **对象 / 类型**。正文 = 构造体;调用类型名 = 构造实例。 | -| `##` 及更深 | **函数**(自由函数或方法)。层数差表示嵌套,与 v0.1 相同。 | - -`# main` 是**入口对象**:运行文件 = 执行其构造体。若无 `main`,且文件恰好只有一个无参顶层 `#` 对象(如 `# Hello World`),则把它当作入口。 - -## 2. 实例句柄 - -构造返回值若为 `map`,运行时写入 `_type`(文本,值为类型名),形成句柄。 -方法调用通过 `_type` 找到定义对象,再解析其下的 `##` 方法。 - -方法体内自动绑定: - -- `自`(中文) -- `self`(英文) - -二者同一接收者。 - -## 3. 调用外形 - -```markdown -# 大模型 - + `模型名` - -*自 = …配置 map…* -**自** - -## 运行 - + `提示` - -…使用 `自` … -**内容** - -# main - -*模型 = > 大模型 模型名="gpt-4o-mini"* -*回复 = > 模型.运行 提示="你好"* -> print text=`回复` -``` - -- `> 大模型 …` — 构造 -- `` > `模型`.运行 … `` — 方法(接收者 + `.` + 方法名;**独立 `>` 调用**需反引号接收者 `` `模型` ``;**在 `*…*` / `**…**` 段内**接收者不加反引号:`*回复 = > 模型.运行 提示="你好"*`) -- `## 自由函数` 挂在模块顶层(非某对象子标题)— 与旧版顶层 `# http_get` 对等,现写为 `## http_get` - -## 4. 标准库 - -官方 `lib/*.mq.md` 以**顶层自由函数**为主:全部为 `##`(不再使用 `#` 冒充类型)。 -真正的类型化扩展(如 `ext/llm`)使用 `# 类型` + `##` 方法。 - -## 5. 继承(`# 子类 = > 父类`) - -```markdown -# Greeter - -## hello - + `who` - -*msg = "Hello, `who`!"* -**msg** - -# Loud = > Greeter - -## hello - + `who` - -*msg = "HELLO, `who`!"* -**msg** -``` - -| 规则 | 说明 | -|------|------| -| 语法 | `# Child = > Parent`(右侧必须是 `>` + 简单类型名;无路径) | -| `_type` | 构造后仍为**最具体子类名** | -| 方法查找 | 先子类 `##`,未命中再沿基类链;同名则子类覆盖 | -| 构造 | **不**隐式调用父构造(无 auto-super)。需要父字段时在子类正文首行显式 `` `self` = > Parent … ``,再改字段并 `**`self`**`;返回 map 的 `_type` 仍为子类名 | -| 多继承 | 不支持 | -| 诊断 | 未知基类、循环继承、非法 RHS(如 `# Foo = 1`) | - -详见 [object-inheritance.md](../roadmap/object-inheritance.md)。 - -## 6. 非目标(本波) - -- 接口 / 可见性 / 多继承 -- 无 `_type` 的「鸭子」方法分发 -- 用表格声明字段 schema(表格仍表示数据集合;见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md)) - -## 7. 迁移摘要 - -| 旧 | 新 | -|----|----| -| 库顶层 `# http_get` | `## http_get` | -| `# main` + `## 嵌套` | 不变(main = 入口对象) | -| `ext` 顶层 `# complete` | `# llm` / `# 大模型` 构造 + `## complete` / `## 运行` | diff --git a/doc/design/occlusion-description-and-search.md b/doc/design/occlusion-description-and-search.md deleted file mode 100755 index ce5fcc0..0000000 --- a/doc/design/occlusion-description-and-search.md +++ /dev/null @@ -1,426 +0,0 @@ -# 遮蔽描述与两级检索:内置词表做范例,参数做扩展 - -| | | -|---|---| -| 状态 | **Accepted · 实施中**(与 [occlusion-syntax.md](occlusion-syntax.md) 同步) | -| 日期 | 2026-10-22 | -| 关键决策 | ①`[]` 是自由描述,不执行 ②**两级词表**:内置=范例/默认,参数=扩展 ③空载荷**一律 warning** ④工程化写进 README,提示词同步更新 | -| 前置 | [occlusion-syntax.md](occlusion-syntax.md) | - ---- - -## 0. 五条定调 - -1. **`[]` 里是纯粹的描述文字,对执行没有任何作用。** 编译器**不解析**,只做**检索**。 -2. **两级词表**: - - **内置词表 = 范例 + 默认检索集**(零配置可用;给 LLM 一个稳定范式) - - **参数 = 扩展/覆盖**(`--grep 任意词`,项目自己的说法照样能搜) -3. **空载荷一律 warning**:`()` 为空说明"这段遮蔽里没有可执行内容",写 `None` 即消除。 -4. **强力推荐 LLM 申报**:写不了真接口就"申报",别"假装"。提示词同步更新。 -5. **工程化实践写进 README**,不另造文档。 - -一句话: - -> **描述给人读;内置词给个范式;参数给自由;空着不写会被提醒。** - ---- - -## 1. 为什么要允许「假接通」 - -模型被要求"接入搜索"时,最省力的是写个返回固定值的函数,然后声称已接通。 - -| 处理方式 | 结果 | 问题 | -|---------|------|------| -| **A 禁止**("不许伪造") | 模型改用更隐蔽的伪造 | 不可检测、不可计数 | -| **B 放任** | 静默假功能 | 文档撒谎,没人知道欠了多少 | -| **C 申报**(本方案) | 允许,但写进描述 | 代码照跑;欠据可数、可查 | - -C 的关键:**不改道德要求,改激励**——申报比伪造省力,且申报后代码照样跑。 - ---- - -## 2. `()` 内部语法定稿 - -### 2.1 取元 - -| 语义 | 写法 | -|------|------| -| Map 取成员 | `at(表, 键)` | -| List 第 n 项(1-based) | `at(列表, 1)` | -| 缺键取默认(不崩) | `get(表, 键, 默认值)` | - -### 2.2 调用 - -| 形态 | 写法 | -|------|------| -| 位置实参 | `加一函数(31)`(逗号可选:`加一函数(31 2)`) | -| 具名实参 | `计税(档位=2, 金额=100)` | -| **带空格 callee** | `加一 号(31)` → callee = 第一个 `(` 之前的全部文本 | -| 库路径 / 方法 | `txt.str_trim(s)` / `obj.方法(x)` | - -实测:`加一 号(31 )` → `32`;`> 加一 号 31` → `unknown function 加一`。 -**`(` 是明确分隔符**——这是缺陷 D8 的结构性解法。 - -### 2.3 循环 - -```markdown -- [从篮子里取出的每个果子](遍历 篮子 为 果) -``` - -### 2.4 空载荷:**一律 warning** - -| 写法 | 结果 | -|------|------| -| `[功能,开发中]()` | ⚠️ `label.empty_payload` | -| `[功能,开发中](None)` | ✅ 无警告 | -| `[功能,开发中](json.parse text="[]")` | ✅ 无警告 | - -**为什么一律报**:空 `()` 就是"什么都没写"。哪怕桩也该说明返回什么—— -`None` 也是答案,下游能据此判断。 -**为什么不会造成存量噪音**:遮蔽语法是新形式,**今天仓库里一处都没有**。 - -> 可调旋钮(**非默认**):若实际使用中觉得"已申报的桩也报警"太吵, -> 可开启「命中内置词表则降为 hint」。默认关闭——遵守"空载荷必须被看见"。 - ---- - -## 3. 两级词表 - -### 3.1 第一级:内置词表(范式 + 默认检索集) - -**它是什么**:编译器内置的一张**小词表**,用途三个—— - -| 用途 | 说明 | -|------|------| -| **范式** | 给 LLM 一个稳定写法:不知道怎么写状态,就照这个词表写 | -| **默认检索集** | `marqdo labels pending` 零配置即可用;跨项目可比 | -| **默认豁免集** | 命中这些词的遮蔽默认跳过 stale(见 §6.1) | - -**它不是什么**:**不是语法**。写不写、怎么写都不影响解析与执行。 - -### 3.2 内置词表(v1) - -| 组 | 关键词(子串任一命中即算) | 计入 | -|----|--------------------------|------| -| **未完成** | `待开发` `未开发` `开发中` `未实现` `待实现` `未接` `接口未接` `TODO` | pending | -| **假数据** | `模拟` `假数据` `桩` `占位` `stub` `mock` | pending | -| **演示** | `示例` `样例` `demo` | demo | -| **不稳** | `实验` `试验` `experimental` | experimental | -| **将删** | `废弃` `弃用` `deprecated` | deprecated | -| **待核** | `待校验` `未验证` `待确认` | unverified | - -- 组间**独立计数**,不合并 -- `pending` = 未完成 ∪ 假数据(默认口径,最常用) -- 词表版本随编译器走;扩词表**不动语法** - -### 3.3 第二级:参数(扩展与覆盖) - -```bash -# 默认:内置 pending 集 -marqdo labels pending - -# 覆盖:只用我给的词 -marqdo labels search --grep "接口未联调,联调中" - -# 合并:我给的 + 内置 -marqdo labels search --grep "联调中" --also-builtin -``` - -| 参数 | 语义 | -|------|------| -| `--grep A,B` | **替换**为 A、B(子串、OR、英文大小写不敏感) | -| `--also-builtin` | 与内置词表**取并集** | -| `--group pending,demo` | 用内置的某几组(不带 `--grep` 时) | - -MLSP 对应: - -```json -{ "method": "labels.search", - "params": { "grep": ["联调中"], "also_builtin": true, "json": true } } -``` - -### 3.4 为什么保留内置词表 - -| 理由 | 说明 | -|------|------| -| **LLM 有范本** | 模型不必发明措辞,照着写即可,稳定性显著提高 | -| **跨项目可比** | 大家用同一套词,"还有多少没做"才有统一含义 | -| **零配置可用** | CI 不必先写一份词表才能统计 | -| **失败模式可控** | 词不全时用参数补,而不是每个项目各自发明一套 | - -**代价**:内置词表是一种"语义偏见"。缓解方式是**两级**—— -内置只做默认值,参数永远可覆盖/扩展;且词表不参与语法,写别的措辞完全合法。 - -### 3.5 识别规则:纯子串,无位置/分隔符要求 - -```rust -// 语义示意 -for (group, words) in TABLE(words_from_params_or_builtin) { - if words.iter().any(|w| label_text.contains(w)) { hits.insert(group) } -} -``` - -| 写法 | 命中 | -|------|------| -| `[某某功能开发中]` | ✅ 无分隔符 | -| `[搜索接入,待开发]` | ✅ 逗号 | -| `[搜索接入-待开发]` | ✅ 连字符 | -| `[【待开发】搜索接入]` | ✅ 括号 | -| `[这段还没写完]` | ❌ 无词(合法,不计数) | - -- **识别不到不报错、不提示**——描述自由 -- **误判必然存在**(`[不属于待开发范围]` 会命中):只影响计数,不影响执行; - 输出带描述原文,人可判断;否定词窗口留 v1.1 可选 - ---- - -## 4. 桩的语义 - -### 4.1 三条规则 - -| # | 规则 | 原因 | -|---|------|------| -| 1 | **桩必须能跑**(不得报错) | 否则整篇文档被阻断 | -| 2 | **桩必须写明返回什么** | 空载荷 → warning;写 `None` 也行,但不能什么都不写 | -| 3 | **桩不得被当成已完成** | 描述里申报;检索能查到;`view` 有徽章 | - -### 4.2 桩返回什么 - -| 手段 | 写法 | -|------|------| -| 显式空值 | `[某某功能开发中](None)` | -| 常量占位 | `[税率预报,模拟](0.1)` | -| 假数据 | `[搜索结果,模拟](json.parse text="[]")` | -| **桩 + 契约(推荐)** | 配合返回契约声明类型 → 桩是"有类型的洞" | - -```markdown -## 搜索 - -| 返回 | 类型 | 说明 | -|------|------|------| -| | list | 命中列表(当前未接) | - -[按关键词检索,接口未接,模拟](json.parse text="[]") -``` - -### 4.3 惯例(不强制):桩返回值带 `stub: true` - -```markdown -[ERP 推送,模拟](json.parse text={"ok":true,"stub":true}) -``` - ---- - -## 5. 工程化:写进 README,提示词同步更新 - -### 5.1 README 增补(`README.md` 新节) - -> **工程习惯:允许申报未完成,但不允许假装完成** -> -> ```markdown -> [按关键词检索,接口未接,待开发](None) -> ``` -> -> - 桩必须能跑,并写清返回值(写 `None` 也比空着好) -> - 描述是自由文本;内置词表只是推荐用词与默认检索集 -> - 盘点:`marqdo labels pending`;自定义:`--grep 你的词 --also-builtin` -> - 门禁:`--baseline` + `--fail-on-increase`(棘轮:只拦新增,不追旧账) -> - LLM:接不了就申报;提示词见 `ext/ai/agent.mq.md` - -### 5.2 提示词更新(`ext/ai/agent.mq.md`) - -| 位置 | 现状 | 增补 | -|------|------|------| -| `:48` 默认 standing(`You are a Marqdo agent…`) | 只讲"源码是真相" | 追加一句申报约定 | -| `:39` how-to-act 协议段 | 只讲 CALL/READ | 追加"未完成必须申报" | - -**建议追加文本**(英文,与现有 standing 一致): - -```text -When you cannot truly wire a capability, do not fake it silently and never claim it works. -Write it as an occlusion with an explicit status instead: - [按关键词检索,接口未接,待开发](None) -Stubs must run without error and must state their return value (None is acceptable). -Before finishing, check your own declarations with labels.pending. -``` - -**为什么这条对 LLM 有效**:把"编造"变成"填表"——模型不必判断算不算伪造, -只需写出状态词并给一个返回值。 - -### 5.3 工具面 - -| 工具 | 用途 | -|------|------| -| `labels pending` | 内置词表口径的未完成清单 | -| `labels search --grep … [--json/--count/--also-builtin]` | 任意词盘点 | -| `labels search … --changed` | 只看本次变更涉及的 | -| MLSP `labels.search` | 协议内同上 | - -### 5.4 指标 - -| 指标 | 算法 | -|------|------| -| `pending_count` | `labels pending --count` | -| `unlabeled_empty` | `label.empty_payload` warning 数 | -| `stub_ratio` | pending / 遮蔽总数 | -| `stub_age` | 需 VCS(可选,不进默认路径) | - ---- - -## 6. 生命周期 - -``` -① 写桩 [按关键词检索,接口未接,待开发](None) - ↓ -② 盘点 labels pending → 列出它 - ↓ -③ 开发 换成真实 HTTP 调用 - ↓ -④ 复核 去掉"待开发"字样、改写描述 - ↓ -⑤ 数字-1 检索结果自动减少 -``` - -### 6.1 stale 豁免(默认用内置集) - -| 情形 | stale 行为 | -|------|-----------| -| 描述命中**内置 pending 组**(未完成/假数据) | **豁免** | -| 命中 `将删`(废弃) | **豁免** | -| 命中 `示例` / `实验` / `待核` | 正常报 | -| 空载荷 | **豁免**(它就是桩) | -| 无命中、有实现 | 正常报 | -| `check --stub-words "A,B"` | **覆盖**内置集,用 A,B 判定豁免 | - -理由:桩本来就是"未完成",描述已明说。若桩一被改动就报 stale, -12 个桩会变 12 条常驻警告——**正好制造我们要消灭的疲劳**。 - -### 6.2 防"做完了忘去掉申报" - -- `labels search --grep … --changed`:本次变更中被改过的桩 -- 会话末汇总带一行 `pending_touched: 2`(只给数字,不逐条) - ---- - -## 7. 与防疲劳机制的协同 - -| 机制 | 作用 | -|------|------| -| 桩豁免 stale(默认内置集) | 12 个桩不会变成 12 条常驻警告 | -| 债务用**棘轮**(`--baseline` + `--fail-on-increase`) | 老债不阻塞、新债立刻拦 | -| 检索是**按需命令**,不进 `check` 人类输出 | 零噪音 | -| 搜不到**不报错** | 描述自由,机器不纠正用词 | -| 空载荷 warning 仅作用于新语法 | 不可能产生历史债 | - ---- - -## 8. 编译器实现点 - -| 位置 | 要做的事 | -|------|---------| -| `src/parse` | 解析 `[描述](实现)`,**原样保存描述**(不解析、不分类) | -| `src/ast.rs` | `Expr::Occluded { label: String, inner: Option<Box<Expr>> }` | -| `src/label.rs`(新增) | **内置词表常量** + 描述索引/检索(子串、OR、大小写不敏感)+ L1 引用一致性 + T1 前后对比 | -| `src/check.rs` | 三条:`label.missing`(error)、`label.ref_dangling`(error)、`label.empty_payload`(**warning,一律**) | -| `src/interp.rs` | 描述**不影响求值**;空载荷 → `None` | -| `src/main.rs` | `labels pending/search --grep … [--also-builtin/--json/--count/--changed]`;`check --stub-words …` | -| `src/mlsp.rs` | `labels.search`(含 `also_builtin`)、`validate.stub_words`、会话汇总 `pending_touched` | -| `src/view/render.rs` | 遮蔽渲染:描述为正文、实现可折叠;桩徽章 | -| `README.md` | 新增「工程习惯」一节(§5.1) | -| `ext/ai/agent.mq.md` | `:48` standing 与 `:39` 协议段追加申报约定(§5.2) | - -**分层**:内置词表是**数据**(常量表),检索是**纯函数**,语法**零依赖**—— -扩词表不改语法,改语法不动词表。 - ---- - -## 9. 示例 - -### 9.1 无分隔符申报 - -```markdown -[某某功能开发中](None) -``` - -```bash -marqdo labels pending # 命中(内置「开发中」) -``` - -### 9.2 假算指标 - -```markdown -本季度 **[客户留存率,待开发](0.0)**,环比变化 **[留存环比,模拟](0.0)**。 -``` - -### 9.3 假接通外部系统 - -```markdown -[ERP 推送,模拟](json.parse text={"ok":true,"stub":true}) -``` - -### 9.4 该报 warning 的空载荷 - -```markdown -[应纳税额]() # ⚠️ label.empty_payload -``` - -### 9.5 项目自己的说法(参数层) - -```markdown -[接口还在联调,先返回空](json.parse text="[]") -``` - -```bash -marqdo labels search --grep "联调" --also-builtin # 内置 + 自定义一起数 -``` - -### 9.6 任意措辞(合法、不被自动分类,但可被搜) - -```markdown -[这段还没写完](0) -``` - -```bash -marqdo labels search --grep 还没写完 # LLM 自己挑的词,照样搜到 -``` - ---- - -## 10. 风险与取舍 - -| 风险 | 说明 | 缓解 | -|------|------|------| -| 子串误判 | `[不属于待开发范围]` 会命中 | 只影响计数;输出带原文;否定词窗口留 v1.1 | -| 内置词表是语义偏见 | 规定了"什么算未完成" | **两级**:内置只做默认,参数可覆盖/扩展 | -| 空载荷 warning 偏多 | 作者爱留空 | 修法极简(写 `None`);仅影响新语法;可留降级旋钮 | -| 桩腐化 | 忘去掉申报 | `--changed` + 会话汇总,不做常驻警告 | -| 假功能上生产 | 最坏情况 | `view` 显著标记;CI 可 `--count` 门禁 | -| LLM 滥用申报逃避检查 | 把真实现标成待开发 | 申报只增加可见性、不减少检查;豁免 stale 的代价是计入债务 | - ---- - -## 11. 已定 vs 待定 - -**已定(本文即规范)** - -| 项 | 结论 | -|----|------| -| 描述性质 | 自由文本,不执行,不参与类型/作用域 | -| 词表 | **两级**:内置范例/默认 + 参数扩展 | -| 空载荷 | **一律 warning**(写 `None` 消除) | -| 检索语义 | 子串 + OR + 英文大小写不敏感 | -| stale 豁免 | 默认内置 pending/将删组;`--stub-words` 覆盖 | -| 棘轮 | `--baseline` + `--fail-on-increase` | -| 工程化落点 | README 一节 + `ext/ai` 提示词两处 | - -**待你点头** - -| # | 问题 | 建议 | -|---|------|------| -| 1 | 内置词表就 §3.2 这六组 | 是 | -| 2 | `pending` = 未完成 ∪ 假数据 | 是 | -| 3 | `--grep` 替换、`--also-builtin` 合并 | 是 | -| 4 | 空载荷"降级旋钮"先不做 | 是(先按一律 warning 跑一段看噪音) | -| 5 | 提示词追加文本按 §5.2 写 | 是 | - -> 点头后即按 M1 → M2 → M4 → M9 → M6 开工;首批金样用 §9 的六个例子。 diff --git a/doc/design/occlusion-syntax.md b/doc/design/occlusion-syntax.md deleted file mode 100755 index 87a5d68..0000000 --- a/doc/design/occlusion-syntax.md +++ /dev/null @@ -1,624 +0,0 @@ -# 遮蔽语法(Occlusion Syntax):`[描述](实现)` 设计与实施总纲 - -| | | -|---|---| -| 状态 | **Accepted · 实施中**(M0 起,本文档为实施依据) | -| 日期 | 2026-10-22 | -| 决策 | 纯度;标签可省略书写但**编译器报错**;新鲜度校验**不依赖 git**;**会话末做一次性汇总** | -| 定位 | 本文把 `[]()` 从「若干语法的集合」重新定义为**一种语法、一个目的:遮蔽** | -| 前置 | [bracket-as-label-evaluation.md](bracket-as-label-evaluation.md) · [label-freshness-and-repair.md](label-freshness-and-repair.md) · [warning-fatigue-control.md](warning-fatigue-control.md) · [staleness-providers.md](staleness-providers.md) · [t1-session-staleness.md](t1-session-staleness.md) | -| 增补 | [occlusion-description-and-search.md](occlusion-description-and-search.md) — **两级词表(内置=范例/默认;参数=扩展)**;空载荷一律 warning;桩语义;工程化落点(README + `ext/ai` 提示词);**`()` 内部语法定稿见该文 §2** | - ---- - -## 0. 术语(后文一律按此使用) - -| 术语 | 含义 | -|------|------| -| **遮蔽(occlusion)** | 用一段人话盖住一段实现:读者看人话,机器看实现 | -| **描述(label)** | `[]` 里的文本。**不可执行**,只给人读,是可被机器核验的断言 | -| **实现(payload)** | `()` 里的表达式。**唯一执行**的部分 | -| **显式遮蔽** | `[描述](实现)` —— 描述与实现写在同一处 | -| **隐式遮蔽** | 叙述段落 + 紧接的 `>` 调用 —— 描述是上方那段散文 | -| **新鲜(fresh)** | 描述与实现仍然相符 | -| **过期(stale)** | 实现变了、描述没变 —— 描述可能已不再成立 | - -## 0.1 开发环境前置(实施前必须就绪) - -本机(glibc 2.36、无系统 gcc/go/python3)已验证过的完整环境: - -```bash -source scripts/dev-env.sh # rust 1.81 + go 1.25 + python 3.12 + zig(gcc shim, glibc 2.36) -./scripts/build-web-plugin.sh # 产出 libweb.so,否则 gold 测试会失败 -``` - -两个非直觉约束(踩过的坑,写进文档免得后人重踩): - -| 约束 | 现象 | 处理 | -|------|------|------| -| `$HOME` 不可写 | zig 报 `AccessDenied` | `ZIG_GLOBAL_CACHE_DIR` / `ZIG_LOCAL_CACHE_DIR` 指向工作区 | -| **`/tmp` 是 noexec tmpfs** | Go 链接 `signal: aborted`、zig `AccessDenied` | `TMPDIR` 指向可写且**可执行**目录 | - -基线(改动前必须先跑通):`cargo test --release` → **554 passed / 0 failed**; -`marqdo check` 对 `lib/` + `ext/ai/`(59 文件)→ **0 warning / 0 error**。 -任何里程碑都不得让这两个数字变差。 - ---- - -# Part I · 示例先行 - -## 1. 六个示例 - -### 1.1 嵌套取值:不可读 → 可读 - -**今天**(读者要在三层括号间来回跳): - -```markdown -**单价 = [1]([苹果]([水果类](货架)))** -``` - -**遮蔽之后**: - -```markdown -**单价 = [水果类里苹果的第 1 项价格](at(at(at(货架, 水果类), 苹果), 1))** -``` - -人读方括号,机器读圆括号。**嵌套再深,读者也只看一句人话。** - -### 1.2 长表达式打断叙述 - -**今天**: - -```markdown -本季度应缴税额为 **金额 * 税率 * (1 - 减免比例) + 附加费**,请注意申报期限。 -``` - -一句话被一串符号劈成两半。 - -**遮蔽之后**: - -```markdown -本季度应缴税额为 **[应缴税额](金额 * 税率 * (1 - 减免比例) + 附加费)**,请注意申报期限。 -``` - -叙述仍然是句子;复杂算式被折进 `()`。 - -### 1.3 抽象层次混杂:把实现藏到读者不需要看的地方 - -**今天**(读者被迫读实现细节): - -```markdown -价格随会员等级浮动,具体为 **基础价 * 会员折扣[等级](折扣表) * (1 + 旺季系数)**。 -``` - -**遮蔽之后**(论证留在叙述里,算法藏起来): - -```markdown -价格随会员等级浮动:**[会员最终价](基础价 * at(折扣表, 等级) * (1 + 旺季系数))**。 -``` - -### 1.4 循环:来源从此可见 - -**今天**(渲染成「名为果的链接指向篮子」,看不出是遍历): - -```markdown -- [果](篮子) - **总重 = 总重 + [重量](果)** -``` - -**遮蔽之后**: - -```markdown -- [从篮子里取出的每个果子](遍历 篮子 为 果) - **总重 = 总重 + [重量](at(果, 重量))** -``` - -「从哪来」写进了人话——**不再依赖读者是否用了 `marqdo view` 才能看懂。** - -### 1.5 带空格的函数名(**已实测验证**) - -**今天**(`>` 调用无法表达,这是缺陷 D8): - -```markdown -> 加一 号 31 # ❌ unknown function `加一` —— 空格把名字切断了 -``` - -**遮蔽之后**(`(` 成为明确分隔符,空格不再是切词依据): - -```markdown -**结果 = [加一之后的值](加一 号(31))** -``` - -**实测证据**(1.5.2 原型): - -| 写法 | 结果 | -|------|------| -| `> 加一 号 31` | ❌ `unknown function 加一` | -| `加一 号(31 )`(括号调用) | ✅ **32** | -| `问候("世界")` | ✅ `你好 世界` | - -> **因为 `()` 里的 callee 取「第一个 `(` 之前的全部文本」,空格不再有任何歧义。** -> 这正是你说的「`()` 内部对带空格的函数名处理方式很多样」——而且它不只是"很多样", -> 它是**结构上唯一正确**的处理:用括号做边界,而不是用空白。 - -### 1.6 反例:什么时候**不该**遮蔽 - -```markdown -# 反例:为遮蔽而遮蔽 - -**总计 = [总计](a + b)** # ❌ 描述等于代码,白加一层 -**[价格](price)** # ❌ 描述等于变量名,无信息增量 -``` - -**判据**:如果描述不能比实现**多提供信息**(意图、来源、单位、why),就不要遮蔽。 -遮蔽的收益是"读者不用读实现",若描述只是把实现读了一遍,收益为零、成本照付。 - ---- - -## 2. 定义:遮蔽语法 - -```markdown -[ 描述 ] ( 实现 ) - └─ 人读 ─┘ └─ 机读 ─┘ -``` - -### 2.1 三条铁律 - -| # | 铁律 | 理由 | -|---|------|------| -| 1 | `[]` **永不执行** | 与「叙述默认安全」一致:只说人话的东西不改变程序行为 | -| 2 | `()` **是唯一执行体** | 语义只有一处,读者不必猜两层 | -| 3 | **遮蔽必须可校验** | 见 §2.2 | - -### 2.2 核心定理:遮蔽创造信任负债 - -> **你把实现藏起来,读者就必须相信描述。** -> 所以:**遮蔽 ⇔ 描述成为承重结构 ⇔ 必须可被机器核验。** - -这条定理把「新鲜度校验」从"附加功能"变成"遮蔽的**代价与前提**": - -- 不遮蔽 → 读者能自己核对代码 → 描述过期无伤大雅(顶多是注释旧了) -- 遮蔽 → 读者看不见代码 → **描述一旦过期,文档就变成了假的** - -所以平台必须提供:**实现一变,描述立刻被质疑**。 -这不是锦上添花,是这套语法的**合法性来源**。 - -### 2.3 为什么必须是「链接外形」 - -| 性质 | 链接(`[]()`) | 其它候选 | -|------|--------------|---------| -| 文本不可执行、目标可执行 | ✅ 天生分离 | 括号内联(`(...)`)做不到"只读文本" | -| 与 Markdown 渲染一致 | ✅ 渲染成超链接,读者熟悉 | 箭头 `→` 是自造符号 | -| 可承载任意长文本 | ✅ | 下标 `x[y]` 放不下长描述 | -| 可被工具定位/跳转 | ✅ 天然锚点 | 注释块不行 | - -**一句话**:链接是唯一"人类文本与机器目标天然分工"的 Markdown 结构, -而 Marqdo 正好需要这个分工。 - ---- - -# Part II · 应用场景(按**动机**分类,不按语法分类) - -**重要**:遮蔽语法**不是**"循环语法""取元语法""调用语法"。 -它没有专属用途——它是**一种处理不可读性的手段**。任何表达式都可被遮蔽。 - -## 3. 五类遮蔽动机 - -| 动机 | 症状 | 遮蔽后得到什么 | -|------|------|---------------| -| **A 不可读** | 嵌套过深、括号堆叠 | 读者只看一句人话 | -| **B 打断叙述** | 长算式把句子劈成两半 | 句子完整,算式退居括号 | -| **C 层次混杂** | 论证与实现细节混排 | 论证在上,实现可折叠 | -| **D 来源不明** | 看不出数据从哪来(如 `- [果](篮子)`) | 来源写进人话 | -| **E 名称受限** | 函数名含空格写不出调用(D8) | `(` 做分隔符,名字自由 | - -> 注意 D 与 E:它们是**遮蔽顺带解决的问题**,不是遮蔽的目的。 -> 若把它们写成"循环语法 / 调用语法",就会限制这套语法的适用面; -> 按动机写,它才能覆盖未来尚未想到的不可读情形。 - -## 4. 什么时候不该遮蔽 - -| 情形 | 说明 | -|------|------| -| 描述 = 实现(§1.6) | 无信息增量 | -| 只用一次且已足够可读 | 遮蔽会**增加**读者的跳转成本 | -| 描述无法具体化 | 笼统的描述不可校验,等于把信任成本转嫁给读者 | -| 性能敏感的热路径 | 遮蔽本身不贵,但过度嵌套的表达式不利于后续优化 | - ---- - -# Part III · 语法规范 - -## 5. 文法 - -``` -遮蔽 ::= '[' 描述 ']' '(' 表达式? ')' -描述 ::= 非空自由文本(可含 `实体`、空格、关键词;v1 不跨行) -表达式 ::= 现有表达式文法(含 §6 的调用形);**可空** → 值为 None - -带括号的调用 ::= callee '(' 实参列表? ')' -callee ::= 非空文本,不含 '('(**允许空格**,见 §6.2) -实参列表 ::= 实参 (分隔 实参)* -实参 ::= 名 '=' 值 | 值 -分隔 ::= 空白 | ',' # 逗号可选、容错 -``` - -出现位置:**表达式位置 / 语句位置 / 循环项位置**(三处形态一致)。 - -> **空载荷 `()`**:合法(值 `None`),但**一律**报 `label.empty_payload`(warning)—— -> 修法是显式写 `None` 或一个真实返回值。描述是自由文本,检索由**调用方传词**(子串匹配,无分隔符要求), -> 详见 [occlusion-description-and-search.md](occlusion-description-and-search.md) §3–§4。 - -## 6. `()` 之内 - -### 6.1 表达式文法不变 - -`()` 里就是今天 Marqdo 的表达式:算术、比较、调用、变量(`` `名` ``)、字面量。 -**不引入第二套表达式语言。** - -### 6.2 callee 可以含空格(解决 D8) - -规则:**callee = 第一个 `(` 之前的全部文本**(去首尾空白)。 - -```markdown -[加一之后的值](加一 号(31)) # callee = "加一 号" -[会员最终价](会员价(等级=2 )) # 具名实参 -``` - -依据实测:`加一 号(31 )` → `32`。 -(当前实现的参数分词器会把 `)` 吞进末个实参,需要 M1 修掉;带尾随空格即可绕过。) - -### 6.3 取元怎么写(纯度要求) - -`[键](集合)` **不再是取元**(见 §9 迁移)。取元改为函数形: - -| 语义 | 写法 | -|------|------| -| 取 Map 成员 | `at(表, 键)` 或 `get(表, 键)` | -| 取 List 第 n 项(1-based) | `at(列表, 1)` | -| 缺键不崩 | `get(表, 键, 默认值)` | - -**理由**:与调用同一外形,读者不必区分"这是取元还是调用"—— -而这正是遮蔽语法要消灭的那种"两套读法"。 - -### 6.4 循环 - -```markdown -- [从篮子里取出的每个果子](遍历 篮子 为 果) -``` - -- `[]` = 人读描述(来源、单位都可写) -- `()` = `遍历 <集合> 为 <变量>` -- **变量名从 `[]` 搬进 `()`**:`[]` 不再兼任标识符(否则"描述"与"名字"又打架) - -## 7. 标签规则 - -| 规则 | 行为 | -|------|------| -| 空标签 `[](…)` | **error `label.missing`**(你说的"可省略书写但编译器报错") | -| 标签内 `` `实体` `` | 视为**断言**:该实体必须可解析且出现在 `()` 中(§10.1) | -| 标签含空格、中文、标点 | 允许 | -| 标签含 `]` | 不允许(转义规则见 §11.3) | -| 标签跨行 | v1 不支持(跨行标签会让定位困难) | - -## 8. 与既有语法的关系 - -| 现有 | 归位 | -|------|------| -| `> 调用` | **保留**,作为"短形调用";同时纳入隐式遮蔽检查(§10.2) | -| `[callee] args` | **保留**为消歧/前置修饰形;仓库实测可执行使用量为 **0**(189 处是 `lib/*` 的 `Caller:` 说明行,不执行) | -| `[键](集合)` | **废止**(改为 `at/get`;复用 `[]()` 外形)→ 需版本门 | -| `- [项](集合)` | **废止**(改为 `- [描述](遍历 …)`)→ 需版本门 | -| `*…*` 返回 | 不变 | - -## 9. 迁移(实测规模) - -| 受影响 | 数量 | 文件 | -|--------|------|------| -| `[键](集合)` 取元 | **506 处** | 136 | -| `- [项](集合)` 循环 | **44 处** | 24 | -| 可执行方括号调用 | **0** | — | -| `Caller:` 说明行(不执行,无需迁移) | 189 | — | - -**危险点:同形换义。** 迁移后 `[键](集合)` 会变成"遮蔽整个集合",语义静默改变。 -因此必须: - -1. **硬报错**:purity 模式下遇到旧形 → `syntax.legacy_index`,附迁移示例 -2. **机械迁移工具**:`marqdo migrate labels --write` -3. **临时标签**:工具生成的标签 = 原键名,并标记为 `label.provisional`(**hint**,不报 error) - —— 不能让 506 处都变成红错,否则没人能开工 - -## 10. 错误信息规范 - -| code | 级别 | 触发 | 建议文案 | -|------|------|------|---------| -| `label.missing` | error | `[](…)` | 「给这段实现写一句人话,或改用不带遮蔽的写法」 | -| `label.ref_dangling` | error | 标签引用的实体不存在 | 「`X` 已不存在;改成 `Y` 或删掉该引用」 | -| `label.stale` | hint/warning | 实现变了、标签没变 | 「标签说 A,实现现在是 B;二者之一需改」 | -| `label.provisional` | hint | 标签 = 原键名 | 「建议把键名改写成读者能懂的一句话」 | -| `syntax.legacy_index` | error | 旧 `[键](集合)` | 「取元请写 `at(集合, 键)`;遮蔽请写 `[描述](at(集合, 键))`」 | - ---- - -# Part IV · 新鲜度校验 - -## 11. 两种遮蔽关系 - -| 类型 | 形态 | 描述在哪 | -|------|------|---------| -| **显式遮蔽** | `[描述](实现)` | `[]` 里 | -| **隐式遮蔽** | 叙述段落 + 紧接 `> 调用` | 上方那一段散文 | - -**两者都要查**——这是你明确要求的:"`>` 这种函数调用其实也应该被检查是否存在过期现象"。 - -### 11.1 L1:引用一致性(零依赖、确定性) - -**规则**:断言 = 标签内的 `` `实体` ``。 - -1. 实体必须可解析(当前作用域/模块存在) -2. 实体必须出现在 `()` 的实际内容中(或经调用链可达) - -不满足 → `label.ref_dangling`(error)。 - -**为什么低假阳性**:只有**显式反引号**才算断言;纯口语不参与判定。 -**为什么能落地**:复用 Marqdo 已有的 `` `名` `` = 实体约定,**零新记号**。 - -### 11.2 隐式遮蔽:`>` 调用的描述从哪来 - -**规则**:取 `>` 行**上方紧邻的叙述段落**(连续非空行,遇空行/标题/代码行即止)作为描述。 - -```markdown -按 `税率` 与 `档位` 计算应缴税额: - -> 计税 档位=2 金额=100 -``` - -检查: -- 段落里 `` `税率` ``、`` `档位` `` 必须**出现在调用实参或 callee 中**,或可解析 -- 若无叙述段 / 叙述里无反引号 → **不检查**(沉默,零噪音) - -**这条规则的价值**:让**存量代码**(今天所有 `>` 调用)**无需改写**就获得新鲜度保护 -——只要作者在调用上方写了一句带反引号的说明。 - -### 11.3 转义 - -| 需求 | 写法 | -|------|------| -| 标签里要写 `]` | `\]` | -| 标签里要写 `` ` ``(字面) | `` \` `` | -| 实现里要写 `)` | 由括号配对规则处理(字符串内 `)` 不算) | - -### 11.4 T1:会话内检测(不依赖 git) - -**机制**:`repair_apply` 内部同时持有 before(`source`)与 after(`new_source`), -解析两版,比较每个标签的 `()` 指纹: - -> `stale ⟺ 标签文本未变 ∧ () 指纹变了` - -- 按**标签文本**配对(不按行号)→ 移动代码不误报 -- 标签文本变了 → 视为作者在更新描述,**不报** -- 新增/删除标签 → 不报 -- 指纹只需**进程内一致**(`Expr` 现为 `Debug`,可用 `format!("{:?}")`;或补 `derive(PartialEq)`) - -**为什么这能消灭疲劳**:作用域 = 模型自己的 diff;投递 = 一次;自包含(下轮不重复)。 - -### 11.5 会话末一次性汇总(**你要求要做**) - -T1 刻意"不重复",因此需要**闭合**: - -- **会话**定义:MLSP 一条连接的生命周期;CLI 为一次 `marqdo check` 运行 -- 会话结束时输出**一次**: - -```json -{ "session": { "labels_stale_seen": 3, "labels_fixed": 1, "labels_outstanding": 2, - "items": ["按 `税率` 计算总价", "篮子里的果子"] } } -``` - -- 只报**数字 + 标签文本**,不重复诊断详情(详情已在各轮给过) -- 若 `outstanding > 0`,可用 `"block"` 模式让客户端不得直接结束任务 - -### 11.6 能力自述与降级 - -| 环境 | 可用层 | 行为 | -|------|--------|------| -| CLI + VCS | L1 + T1 + T2 | 可跨会话 | -| CLI 无 VCS | L1 + T1 | 仅会话内 | -| agent 沙箱(`exec=false`) | L1 + T1 | **不调 git** | -| 浏览器 WASM | L1 + T1 | 无持久状态 | -| 单文件 / zip | L1 + T1 | — | - -**`labels status` 必须显示当前启用了哪几层**,避免"没报 = 没问题"的误判。 - ---- - -# Part V · 实施计划 - -## 12. 里程碑总览 - -| M | 名称 | 产出 | 依赖 | 风险 | -|---|------|------|------|------| -## 13.1 实施进度 - -**全部完成**:M0 · M1 · M2 · M2.5 · M3 · M4 · M5 · M6 · M7 · M8 · M9 · M10 -(每步含变更文档与测试;全量 605 passed / 0 failed;0 编译警告)。 - -| 里程碑 | 变更文档 | -|--------|---------| -| M1 | [change-m1-paren-call.md](change-m1-paren-call.md) | -| M2 | [change-m2-occlusion.md](change-m2-occlusion.md) | -| M2.5 | [change-m25-label-diagnostics.md](change-m25-label-diagnostics.md) | -| M3 | [change-m3-access-and-loop.md](change-m3-access-and-loop.md) | -| M4 | [change-m4-label-refs.md](change-m4-label-refs.md) | -| M5 | [change-m5-implicit-occlusion.md](change-m5-implicit-occlusion.md) | -| M6 | [change-m6-t1-session.md](change-m6-t1-session.md) | -| M7 | [change-m7-migration.md](change-m7-migration.md) | -| M8 | [change-m8-ratchet.md](change-m8-ratchet.md) | -| M9 | [change-m9-label-search.md](change-m9-label-search.md) | -| M10 | [change-m10-engineering-habits.md](change-m10-engineering-habits.md) | - -| **M0** | 语义冻结 | 本文档 Accepted + 术语表进 `doc/design/` | — | 无 | -| **M1** | `()` 内调用增强 | `callee(args)`:`)` 终止、逗号、嵌套、**空格 callee** | M0 | 中(分词器共享) | -| **M2** | 遮蔽语法 | `[描述](表达式)` + 标签节点 + `label.missing` | M1 | 中 | -| **M3** | 普通取元与循环 | `at/get` 落地;`- [描述](遍历 …)` | M2 | 中 | -| **M4** | L1 引用一致性 | `label.ref_dangling`(error) | M2 | 低 | -| **M5** | 隐式遮蔽检查 | `>` 上方叙述 vs 实参 | M4 | 低 | -| **M6** | T1 + 会话汇总 | `repair_apply.check_labels` + 汇总 | M2 | 低 | -| **M7** | 迁移与版本门 | `marqdo migrate labels`、`syntax.legacy_index` | M3 | **高** | -| **M8** | 呈现与门禁 | `view` 徽章、`labels status/review`、CI | M4–M6 | 低 | -| **M9** | 描述检索与桩 | **两级词表**:`labels pending`(内置集)+ `labels search --grep … [--also-builtin]`、MLSP `labels.search`、空载荷 warning | M2 | 低 | -| **M10** | 工程化落点 | `README.md` 工程习惯一节 + `ext/ai/agent.mq.md` 提示词(standing 与 how-to-act)追加申报约定 | M9 | 低 | - -**顺序建议**:M0 → M1 → M2 → (M2.5 空载荷/描述) → M4 → **M9** → **M10** → M6 → M5 → M3 → M7 → M8 - -理由:**先把"断言 + 复核 + 修复回路"跑通(M2/M4/M6),再动 506 处迁移(M7)**。 -迁移一旦开始,中间态很痛;而 L1/T1 在旧语法上就能验证。 - ---- - -## 13. 每个里程碑的详细步骤 - -### M0 · 语义冻结 - -| 项 | 内容 | -|----|------| -| 改动 | 本文档标记 `Accepted`;`doc/README.md` 登记 | -| 要点 | 术语表(§0)作为唯一用词标准;`[]()` 一律称"遮蔽",不称"循环/取元/调用语法" | -| 验收 | 团队评审通过;后续文档一律引用本文术语 | - -### M1 · `()` 内调用增强 - -| 项 | 内容 | -|----|------| -| 目标 | `callee(args)` 可用:`)` 作实参终止、可选逗号、嵌套调用、**callee 允许空格** | -| 改动文件 | `src/parse/expr.rs`(`parse_call_args` / `split_first_token` / `find_next_arg_boundary` / 新增 `try_paren_call`)、`src/parse/mod.rs`(`looks_like_paren_call` 接入两处调用判定) | -| 关键点 | ① `)` 必须是实参终止符(今天会吞进末个实参)② 逗号可容错剥离 ③ 嵌套 `f(g(1))` 需括号深度 ④ `callee = 第一个 '(' 前全部文本`(空格合法) | -| 测试 | 新增金样 `tests/structure/paren-call.mq.md`:单参/多参/具名/字符串/嵌套/空格名/库路径/方法 | -| 验收 | 上述金样全绿;`cargo test --release` **554 全绿不减**;**双后端**(tree + `--backend bytecode`)均通过 | -| 回滚 | 独立提交,可单独 revert(不改既有语义,风险低) | - -### M2 · 遮蔽语法 - -| 项 | 内容 | -|----|------| -| 目标 | `[描述](表达式)` 解析为 `Expr::Occluded { label, inner }` | -| 改动文件 | `src/ast.rs`(新增节点 + `PartialEq`)、`src/parse/mod.rs`(表达式/语句/循环三处入口)、`src/interp.rs`(求值时透明传递 inner)、`src/bytecode/compile.rs`+`vm.rs`(编译为 inner,label 只留在调试信息) | -| 关键点 | ① 遮蔽对语义**完全透明**(`[d](e)` 的值 = `e` 的值)② label 必须存进 AST(供 L1/T1/诊断定位)③ 空 label → `label.missing` | -| 测试 | 金样:三处位置各一例;label 含中文/空格/标点;`label.missing` 反例 | -| 验收 | 双后端一致;554 全绿;`marqdo check` 对空标签报 error | -| 回滚 | 独立提交;新语法是增量的 | - -### M3 · 普通取元与循环 - -| 项 | 内容 | -|----|------| -| 目标 | `at(表, 键)` / `get(表, 键, 默认)` 可用;`- [描述](遍历 集合 为 变量)` 可用 | -| 改动文件 | `src/interp.rs`(`at`/`get` 内建或库函数)、`src/parse/mod.rs`(循环新形)、`lib/table.mq.md`(`get` 带默认值) | -| 关键点 | 1-based 与现有 `at value= index=` 保持一致;`get` 缺键返回默认而非崩(修 D5 的痛点) | -| 测试 | 金样:Map 取元、List 下标、缺键默认、循环 | -| 验收 | 双后端一致;554 全绿 | - -### M4 · L1 引用一致性 - -| 项 | 内容 | -|----|------| -| 目标 | 标签内 `` `实体` `` 校验:可解析 + 出现在 `()` | -| 改动文件 | **新增 `src/label.rs`**(标签模型、引用抽取、校验)、`src/check.rs`(接入)、`src/diagnostics.rs`(复用 `doc_anchor`/`doc_quote`,新增 `label_ref`) | -| 关键点 | ① 只认反引号(不猜中文词)→ 低假阳性 ② `doc_anchor` = 标签 span,`doc_quote` = 标签原文 ③ `code` 字段用 `label.ref_dangling` | -| 测试 | 单元:抽取/解析/缺失;金样:悬空引用的 error、正常引用的通过 | -| 验收 | 554 全绿;对现有仓库跑 `check` 仍为 **0 error**(除非真有悬空) | - -### M5 · 隐式遮蔽(`>` 上方叙述) - -| 项 | 内容 | -|----|------| -| 目标 | `>` 调用的描述 = 上方紧邻叙述段;其反引号实体须出现在实参/callee | -| 改动文件 | `src/label.rs`(段落归属规则)、`src/check.rs` | -| 关键点 | ① 段落边界:空行/标题/代码行即止 ② 无反引号则跳过(零噪音) ③ 默认级别 **hint** | -| 测试 | 金样:三种(有实体且匹配 / 有实体不匹配 / 无叙述) | -| 验收 | 554 全绿;现有仓库不因该规则新增 error | - -### M6 · T1 + 会话汇总 - -| 项 | 内容 | -|----|------| -| 目标 | `repair_apply` 支持 `check_labels`;会话末输出一次性汇总 | -| 改动文件 | `src/mlsp.rs`(`repair_apply` 内比 before/after;新增 `session.summary` 方法或响应字段)、`src/label.rs`(标签配对与指纹) | -| 关键点 | ① 按标签文本配对 ② 标签变则不报 ③ 指纹进程内一致即可 ④ 会话状态按**连接**保存 | -| 测试 | 集成:`repair_apply` 改 `()` 不改 `[]` → 返回 stale;改 `[]` → 不返回;会话末汇总数字正确 | -| 验收 | 双后端;554 全绿;**无 VCS 环境下同样工作**(CI 里用临时目录验证) | - -### M7 · 迁移与版本门 - -| 项 | 内容 | -|----|------| -| 目标 | `[键](集合)` / `- [项](集合)` 在 purity 模式下**硬报错**;提供机械迁移 | -| 改动文件 | `src/parse/expr.rs`(`link_index_shape_ahead` 改为报 `syntax.legacy_index`)、**新增 `src/migrate.rs`** + `src/main.rs` 子命令 `marqdo migrate labels` | -| 关键点 | ① 报错文案必须给"改成什么" ② 迁移生成 `[键](at(集合, 键))`,标 `label.provisional` ③ 一次性完成 506+44 处,避免中间态 ④ 迁移后必须跑全量回归 + 逐文件抽样 `run` | -| 测试 | 迁移前快照→迁移→回归对比;抽样 20 个文件 `run` 输出一致 | -| 验收 | 554 全绿;`marqdo check` 全仓 0 error;抽样输出无变化 | -| 回滚 | **必须整批回滚**(中间态不可用),建议单独分支 | - -### M8 · 呈现与门禁 - -| 项 | 内容 | -|----|------| -| 目标 | `view` 显示遮蔽徽章与新鲜度;`labels status/review/confirm`;CI 可 gate | -| 改动文件 | `src/view/render.rs`(遮蔽渲染:显示 label,折叠 payload)、`src/main.rs`(`labels` 子命令)、`scripts/ci-*.sh` | -| 关键点 | ① `view` 里 label 是正文、payload 可折叠(这正是遮蔽的呈现价值) ② `labels status` 报能力层级与债务数字 | -| 验收 | 渲染截图人工评审;`labels status` 在无 VCS 环境正确降级 | - ---- - -## 14. 测试计划(贯穿全部里程碑) - -| 层 | 内容 | 门禁 | -|----|------|------| -| 单元 | 解析/求值/标签抽取/指纹比较 | `cargo test --lib` 全绿 | -| 金样 | 新增 `tests/structure/occlusion*.mq.md`、`paren-call*.mq.md` | `tests/gold.rs` 全绿 | -| 回归 | 全量 `554`(现基线) | 不得减少 | -| 双后端 | tree 与 `--backend bytecode` 各跑一遍 | 结论一致 | -| 差异 | 迁移前后同文件 `run` 输出逐字节相同 | 抽样 ≥20 文件 | -| 反向 | 故意破坏断言/标签,确认能报 | 每条规则至少一个反例 | -| 环境 | 无 git / 沙箱(`exec=false`)/ WASM 构建 | 不崩、不报依赖错 | -| 性能 | 1000 标签文件的 `check` 耗时 | 不劣化 >10% | - -**反向验证是硬要求**:每个新检查必须证明"它真的会响", -否则就是在写永不触发的代码(本项目已多次遇到"静默通过"的缺陷)。 - ---- - -## 15. 风险登记 - -| 风险 | 概率 | 影响 | 缓解 | -|------|------|------|------| -| M1 分词器改动波及所有调用 | 中 | 高 | 独立提交 + 554 回归 + 双后端 | -| M7 迁移中间态不可用 | 高 | 高 | 整批迁移、单独分支、可整批回滚 | -| 遮蔽被滥用(描述=实现) | 高 | 中 | `label.provisional` hint + §1.6 反例进教程 | -| 标签自然语言无法核验 | 必然 | 中 | 只认反引号断言(可证伪才检查) | -| 误报疲劳 | 中 | **高** | T1 变更驱动 + hint 默认 + 会话末汇总 | -| 旧语法语义静默改变 | 中 | **高** | `syntax.legacy_index` 硬报错 | -| `Expr` 无 `PartialEq` | 确定 | 低 | 先用 `Debug`;或补 derive | - ---- - -# Part VI · 待决策 - -| # | 问题 | 建议 | -|---|------|------| -| 1 | 取元函数名用 `at` 还是 `get`(两者都留?) | 都留:`at` 严格、`get` 带默认 | -| 2 | 实参分隔用逗号还是空白 | 两者都接受(逗号可选、容错) | -| 3 | 循环新形用 `遍历 集合 为 变量` 还是别的 | 先用它,后续可加别名 | -| 4 | `label.stale` 默认级别 | **hint**(会话末汇总再提) | -| 5 | M7 迁移是否在本文档同批做 | **否**:M2/M4/M6 先上线并验证,再动迁移 | -| 6 | 临时标签(`label.provisional`)是否接受 | **接受**,否则 506 处无法开工 | -| 7 | 标签是否允许跨行 | v1 不允许 | -| 8 | 是否把 `[]()` 的官方中文名定为「遮蔽」 | 建议定为**遮蔽语法**,并在教程里替代"取元/循环/调用语法"的说法 | - ---- - -## 附:一句话总结 - -> **遮蔽语法不是给三种句式加糖,而是给"读者不该被迫读的那部分代码"一个体面的出口。** -> 它用链接的天然分工(人话 / 目标)实现这一点, -> 又因为"遮蔽创造了信任负债",所以必须配套可校验的新鲜度机制—— -> 而 `>` 调用同样在负债之列。 diff --git a/doc/design/okf.md b/doc/design/okf.md deleted file mode 100755 index 6a5e215..0000000 --- a/doc/design/okf.md +++ /dev/null @@ -1,503 +0,0 @@ -# Marqdo 的 OKF 实现 - -| | | -|---|---| -| 状态 | **Accepted(规范);实现分层见 §10** | -| 日期 | 2026-08-07 | -| 调研 | [okf-and-marqdo.md](../research/okf-and-marqdo.md) | -| 命令现状 | [catalog-cli.md](catalog-cli.md)(v0 已落地) | -| 生成式清单方向 | [generated-yaml-manifest.md](generated-yaml-manifest.md) | -| 智能体消费面 | [ext-agent.md](ext-agent.md) · [ext-agent-plan.md](ext-agent-plan.md) · 任务知识包见本文 §7 | -| 外部规范 | [OKF SPEC v0.2](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md) | - -本文是 **Marqdo 语言侧 OKF 实现的详细设计**:界定我们借鉴什么、已经实现什么、下一阶段必须补什么。 -**不把 Google OKF 整本照搬进语言语义**;Marqdo 的可执行真相永远是 `.mq.md` 源。 - ---- - -## 1. 定位 - -### 1.1 OKF 是什么(对我们) - -[Open Knowledge Format](https://github.com/GoogleCloudPlatform/knowledge-catalog) 用 **目录中的 Markdown + YAML frontmatter** 表示可交换知识:概念一页一文、路径即 ID、链接成图、最小强制面(几乎只强制 `type`),并在 v0.2 加入信任信号。 - -Marqdo 对齐的判断是: - -> 人类可读的 Markdown 可以成为人与 Agent 的一等交换面;**程序本身也应能投影成同一形态的知识包**。 - -### 1.2 Marqdo 多走的一步 - -| | OKF(通用知识) | Marqdo | -|--|-----------------|--------| -| 正文 | 自由散文 | **可执行语法**(`.mq.md`) | -| 成功标准 | 互通、可策展、可信任 | 能跑 + 能读 + 可被 Agent 索引 | -| 清单角色 | 知识本身 | **从源派生的投影**(非第二套权威配置) | - -一句话: - -**OKF 形、Marqdo 义 — 形态对齐 OKF;词汇与生命周期服务模块、依赖、任务技能与信任,而不是 BigQuery 业务概念表。** - -### 1.3 三层文档(勿混) - -| 层 | 谁写 | 是什么 | -|----|------|--------| -| **源** | 人 / 编码 Agent | `.mq.md`:唯一语义权威,打开即读、即可跑 | -| **工程目录包** | `marqdo catalog` | 模块依赖/导出总览(`Marqdo Module`) | -| **任务知识包** | `plan` 晋升等 | 任务↔技能↔可执行资源(`Marqdo Task` / `Marqdo Agent Skill`) | - -`marqdo view output` 出 HTML 站点,与 OKF 包**分工**:人读程序站 vs Agent/工具读知识包。见 [view.md](view.md)、[catalog-cli.md](catalog-cli.md) §4。 - ---- - -## 2. 设计原则(锁定) - -1. **源为唯一权威** — 依赖、导出、可执行行为以 `.mq.md` 为准;知识包是提取或晋升结果。 -2. **生成、可复现** — 同一源树 + 同一工具版本 → 同一工程目录包(时间戳字段可规范化忽略)。 -3. **勿手改生成物** — 文件头 / `generated` 标明 GENERATED;手改不被承认为权威。 -4. **最小强制面** — 互通只要求:合法 frontmatter、`type` 字段、可解析的 `resource` / 链接;未知 `type` **必须优雅降级**(仍可读正文与已知字段)。 -5. **格式而非平台** — 包可 `cat` / `git clone`;不绑定某一云或某一模型。 -6. **清单可删可再生** — 无 catalog 时解释器仍能直接从源工作;catalog **不是**语言语义的一部分。 -7. **可执行资源显式** — 凡声称「可跑」的概念必须有 `resource:` 指向 `.mq.md`(或等价路径),禁止只靠散文描述冒充程序。 - ---- - -## 3. 概念模型 - -### 3.1 Bundle(知识包) - -一个 OKF 风格 bundle 是目录树: - -```text -<bundle-root>/ - index.md # 可选:人/Agent 总览 - log.md # 可选:变更史(策展用) - catalog.yaml # 可选:机器向总清单 - concepts/… # 或 modules/…:概念页(frontmatter + Markdown) - resources/… # 可选:被引用的可执行 .mq.md(任务包常用) -``` - -**Concept ID** = 相对 bundle 根、去掉扩展名的路径(OKF 惯例)。 -例:`concepts/tasks/a1b2c3d4e5f6.md` → ID `concepts/tasks/a1b2c3d4e5f6`。 - -**联系** = frontmatter 中的路径字段 + 正文中的 Markdown 链接,形成可遍历图。 - -### 3.2 Marqdo 使用的两类 bundle - -| Bundle | 默认根 | 生产者 | 消费者 | -|--------|--------|--------|--------| -| **工程目录包** | `.marqdo/`(`-o` 可改) | `marqdo catalog` / `sync` | 人、CI、未来编译加速、通用 Agent | -| **任务知识包** | `.marqdo/agent-kb/` | `ext/ai` 的 `plan` 晋升等 | 父智能体快路径、策展、复用 | - -二者词汇共享(`type` / `generated` / `verified` / `status`),目录职责分离: -**不要**把探索用的 `agent-runs/` 时间戳文件当成稳定概念 ID。 - ---- - -## 4. Frontmatter 词汇表 - -### 4.1 所有概念页的公共字段 - -| 字段 | 必填 | 含义 | -|------|------|------| -| `type` | **是** | 概念类型字符串(见 §5) | -| `title` | 推荐 | 短标题 | -| `description` | 可选 | 一句话说明 | -| `tags` | 可选 | 字符串列表 | -| `resource` | 视类型 | 指向权威源或可执行 `.mq.md` 的相对路径 | -| `status` | 推荐 | `draft` \| `stable` \| `deprecated` | -| `generated` | 生成物必有 | `{ by, at? }` — 谁生成 | -| `verified` | 可选 | `{ by, at? }` — 谁核验(非 LLM 口述) | -| `sources` | 可选 | 出处列表(OKF v0.2) | -| `stale_after` | 可选 | 绝对日期,过期后消费者应降级信任 | -| 未知字段 | — | **保留、不拒绝** | - -信任档位(推导,不必单独存字段): - -| 条件 | 档位 | -|------|------| -| 无 `verified` | 未验证(机器生成草稿) | -| 有 `verified.by` 为确定性工具(如 `marqdo-agent/spawn`) | 机器确认 | -| 有人工审核约定(未来) | 人工审核 | - -### 4.2 工程模块页额外字段(v0 已用) - -| 字段 | 含义 | -|------|------| -| `depends` | 导入列表(从源 frontmatter `> path` 提取) | -| `exports` | 顶层 `#` 导出名列表 | - -### 4.3 任务 / 技能页额外字段(目标词汇) - -| 字段 | 所在 type | 含义 | -|------|-----------|------| -| `skill` | `Marqdo Task` | 指向 Skill 概念页的相对路径 | -| `goal` 或正文中的规范化 goal | `Marqdo Task` | 匹配材料(规范化规则见 §7.3) | -| `llm_free` | `Marqdo Agent Skill` | 资源是否仍含 `agent.step` / LLM 调用(机器启发) | -| `quality` | `Marqdo Agent Skill` | 整数启发分(长度、llm_free 等),**非**模型打分 | - ---- - -## 5. `type` 注册表(Marqdo 义) - -未知 type **不得**导致解析失败;工具可跳过专用逻辑,仍展示 title/正文/链接。 - -| `type` | 状态 | 含义 | 主要生产者 | -|--------|------|------|------------| -| `Marqdo Catalog` | **已实现** | 包总览(`catalog.yaml` / `index.md`) | `marqdo catalog` | -| `Marqdo Module` | **已实现** | 一个 `.mq.md` 模块的投影 | `marqdo catalog` | -| `Marqdo Task` | **已实现** | 一项可匹配的任务意图 | `plan` 晋升 | -| `Marqdo Agent Skill` | **已实现** | 指向可执行工作簿的技能 | `plan` 晋升 | -| `Capability` / `Function` | **EKC** | 工程能力 / 符号投影 | `marqdo knowledge` | -| `Decision` / `Constraint` / `Failure` / `AntiPattern` / `Pattern` / `Migration` / `Fact` | **EKC** | L4 工程知识 | 源 frontmatter + learn | -| `Marqdo Context Pack` | **EKC** | Agent EFI 上下文制品 | `reuse` / `preflight` | -| `Marqdo Policy` | **EKC** | 复用决议编译 | `marqdo reuse` | -| `Marqdo Engineering Knowledge` | **EKC** | 工程知识总览 | `engineering.yaml` / `index.mq.md` | -| 其他 | 开放 | 第三方/未来扩展 | — | - -完整 EKC 规范见 [engineering-knowledge.md](engineering-knowledge.md)。 - ---- - -## 6. 工程目录包(v0 — 已实现) - -### 6.1 CLI - -```bash -marqdo catalog [PATH] -o OUT_DIR -marqdo sync [PATH] -o OUT_DIR # 别名 -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `PATH` | `.` | 工程根或单文件;目录则递归 `*.mq.md` | -| `-o` | `.marqdo` | 输出根;写入前创建,**覆盖**同名生成文件 | - -实现:[`src/catalog.rs`](../../src/catalog.rs)。金样:`tests/gold.rs` → `catalog_writes_yaml`、`catalog_includes_agent_kb_concepts`。 - -### 6.2 生成物布局 - -```text -OUT_DIR/ - catalog.yaml - index.md - modules/ - <path-with-__>.md - concepts/ # O3:从 **/.marqdo/agent-kb/concepts/ 复制 - tasks/… - skills/… -``` - -路径拍扁:`structure/import/main.mq.md` → `modules/structure__import__main.md`。 -`agent-kb` 下的可执行 `.mq.md` **不**进 Module 表(避免与概念/资源重复);Task/Skill 概念页进 `concepts/` 与 `catalog.yaml` 的 `concepts:`。 - -### 6.3 `catalog.yaml`(现行字段) - -```yaml -# GENERATED by marqdo — do not edit by hand -type: Marqdo Catalog -title: marqdo-project -generated: - by: marqdo/<crate-version> -modules: - - id: structure/hello # resource 去掉 .mq.md - resource: structure/hello.mq.md - title: … # 源 frontmatter title,否则用路径 - imports: [] # 或 ["lib/x.mq.md as x", …] - exports: - - name: Hello World - kind: fn - # 可选(源 frontmatter 有则透传): - # verified: { by: … } - # sources: […] -concepts: [] # 或 Task/Skill 条目(O3) - # - id: concepts/tasks/<sig> - # type: Marqdo Task - # title: … - # status: … - # page: concepts/tasks/<sig>.md - # resource: … - # skill: … -``` - -提取规则: - -- **imports**:源文件 YAML frontmatter 中以 `>` 开头的导入行(经 `parse_import_spec`)。 -- **exports**:解析成功则用 AST 顶层函数名;否则回退扫描 `# ` 标题行。 -- **verified / sources**:源 frontmatter 有则写入 module/concept 条目(O3)。 -- **concepts**:扫描 `**/.marqdo/agent-kb/concepts/**/*.md`,复制到 `OUT_DIR/concepts/`。 -- **不**提取正文 `>` 动态调用图、不写锁哈希、不写跨仓 URL。 - -### 6.4 模块概念页(现行) - -```yaml ---- -type: Marqdo Module -title: … -resource: path/to/file.mq.md -depends: […] -exports: […] -generated: - by: marqdo/<version> -# verified / sources:源有则透传 ---- -``` - -正文含「勿手改」、**可点击依赖链接**(解析到同包其它 Module 页)、导出表。`index.md` 含 Modules 表与 **Agent knowledge** 节(链到 `concepts/`)。 - -### 6.5 仍相对完整 OKF 愿景的缺口 - -| 缺口 | 说明 | -|------|------| -| 无通用 Concept ID 遍历 API | catalog 为生成物;无独立查询命令 | -| 无 `stale_after` / Attested 再现 | 信任信号仅可选 `verified`/`sources` | -| 无 `log.md` | 无策展历史(O4) | -| 运行时不读 catalog | 解释器不依赖生成物(有意为之) | - -O2/O3 已补:Task/Skill 知识包、catalog 扫入 agent-kb、模块页可点依赖、可选信任字段。 - ---- - -## 7. 任务知识包(规范 — 实现路线 O2) - -服务「父智能体优化过的工作簿,同任务应直接执行」:把子 Marqdo / 技能登记为 OKF 概念,用 ID 与链接匹配,而不是私有 `index.json`。 - -### 7.1 布局(锁定) - -```text -.marqdo/ - agent-runs/workbook-<slug>-<ts>.mq.md # 仅当显式 workbook_dir= 时(可 gc) - agent-kb/ # 任务知识包 bundle(默认首次 plan 就写这里) - index.md - log.md # 可选 - catalog.yaml # 可选;可由 promote 或 catalog 刷新 - concepts/ - tasks/<slug>.md # type: Marqdo Task;sig 在 frontmatter - skills/<slug>.md # type: Marqdo Agent Skill - resources/ - <slug>.mq.md # 默认可执行工作簿(探索与晋升同一路径) -``` - -默认根可通过 `plan` 参数 `kb_dir` / `知识库目录` 覆盖。`.gitignore` 已忽略 `**/.marqdo/`。 - -路径用可读 **slug**(由 goal 派生:拉丁小写、CJK 保留、其它变 `-`,最长约 48 字符)。**`sig` 仅写在 frontmatter**,用于精确匹配。同 slug 异 sig 时用 `slug-<sig前4位>`。旧包若仍以 `<sig>` 为文件名,lookup 会回退识别。 - -### 7.2 概念页模板 - -**Task**(匹配入口): - -```yaml ---- -type: Marqdo Task -title: <短摘要> -description: <规范化 goal> -sig: <12hex> -status: stable -tags: [agent-task] -skill: ../skills/<slug>.md -generated: - by: marqdo-agent/plan -verified: - by: marqdo-agent/spawn - at: <ISO8601> ---- - -# Task - -See [skill](../skills/<slug>.md). -``` - -**Skill**(可执行绑定): - -```yaml ---- -type: Marqdo Agent Skill -title: <短名> -sig: <12hex> -resource: ../../resources/<slug>.mq.md -status: stable | candidate | quarantine -llm_free: true | false -quality: <int> -hits: <int> -# O2 optional metadata (from workbook frontmatter; see §7.5): -applies_when: <text condition or tag> -fixtures: <relative .mq.md proof path> -sandbox_profile: default | readonly | <name> -proof: <relative .mq.md> # alias of fixtures for sandbox gate -generated: - by: marqdo-agent/plan - at: <ISO8601> -verified: - by: marqdo-agent/spawn - at: <ISO8601> ---- - -# Skill - -Prefer spawning `resource` over re-planning. -``` - -`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。**O2:** `agent_kb_promote` 默认要求 sandbox proof(`proof` / `fixtures` / workbook 本身经 `sandbox.run` 成功)才写入;失败返回 `promoted: false` / `reason: sandbox_proof_failed`。传 `require_proof=false` 仅用于明确豁免。 - -### 7.3 任务签名 → Concept 路径 - -材料: - -1. `goal`:Unicode NFC → trim → 连续空白折叠为单空格。 -2. 若调用方工具表非空:工具名排序后追加进材料。 -3. **不**把父 `standing` 计入签名(易变导致永不命中)。 - -输出:稳定短哈希 `sig`(`agent_goal_sig`)+ 可读 `slug`(`agent_goal_slug`)。路径: - -- `concepts/tasks/<slug>.md` -- `concepts/skills/<slug>.md` -- `resources/<slug>.mq.md` - -匹配顺序: - -1. **精确**:slug 试探 + frontmatter `sig` → 扫目录 `sig:` → 旧 hex 文件名。 -2. **别名(Accepted)**:精确 miss 后,扫 Task FM `aliases:`(YAML 列表或 `[a, b]`);`normalize_goal(query)` 与某条 alias **精确相等**则命中同一 Skill/resource。lookup 返回 `match: exact|alias`;`plan` 对 alias 写 `cache=soft-hit`。 -3. **规范句(Accepted)**:仍 miss 时对 goal 做轻量 `agent_kb_canonicalize`(剥站立前缀、去尾标点),再精确/别名各试一次;命中返回 `match: canonical`,`cache=soft-hit`。 -4. **近义(Accepted,默认开)**:仍 miss 且 `near_match=True` 时,对 Task `title|description|aliases` 做本地**字符 bigram 词袋 + 余弦**;`best.score >= near_threshold`(默认 `0.78`)则 `match: near` 并带 `score`,`cache=soft-hit`,并可 `agent_kb_add_alias`。这是稀疏词法近邻,**不是** embedding 模型。 -5. **父裁决 soft_match(Accepted,默认关)**:仍 miss 且 `plan soft_match=True` 时,把 `agent_kb_near_match` 排序候选(含 score;空则退回 `list_tasks`)交给父模型:`DECISION: REUSE` + `SLUG:` 或 `DECISION: NEW`;REUSE 后可 `agent_kb_add_alias`。 -6. **不做**默认 dense embedding / 远程向量库。远期 dense 仍见 [okf-near-match.md](../roadmap/okf-near-match.md) E。 - -`agent_kb_promote` 可选 `aliases=`(字符串或列表)写入 Task;再晋升时合并既有 aliases。 - -### 7.4 与 `## plan` 的契约 - -| 参数 | 默认 | 含义 | -|------|------|------| -| `reuse` / `复用` | `True` | 允许知识包快路径 | -| `optimize` / `优化` | `False` | 跳过知识包,强制再规划 | -| `force` / `强制` | `False` | 忽略知识包 | -| `soft_match` / `软命中` | `False` | miss 后父裁决 REUSE/NEW(须显式打开;候选为 near 排序列表) | -| `near_match` / `近义命中` | `True` | lookup 第四趟本地 n-gram;`False` 关闭 | -| `near_threshold` / `近义阈值` | `0.78` | near 自动命中最低余弦分 | -| `promote` / `晋升` | `True` | DONE 后固化并写入/更新概念与 resource | -| `kb_dir` / `知识库目录` | `.marqdo/agent-kb` | bundle 根 | -| `workbook_dir` / `工作簿目录` | `None` | 默认直接写 `kb_dir/resources/<slug>.mq.md`;显式传入则用该目录下的临时 `workbook-<slug>-<ts>.mq.md` | -| `improve_every` / `改进周期` | `3` | candidate 每 N 次命中触发 ≤1 轮改进 | -| `explore_n` / `探索次数` | `3` | 同任务已有文件数 `< N` 且非 `llm_free` 时,强制新建 `explore/<slug>/<k>.mq.md` 尝试不同路径(第 2 次默认 dual 骨架) | - -调用示例(路径可直接写在参数里,无需 `json.parse`): - -```markdown -> `助手`.plan goal=… max_rounds=3 -> `助手`.plan goal=… workbook_dir=".marqdo/agent-runs" -> `助手`.plan goal=… explore_n=3 -``` - -快路径: - -1. lookup 命中且 resource **llm_free**(含现场检测已固化源)→ spawn → `cache=hit`,**父 LLM 不调用**。 -2. 否则若任务相关文件数 `< explore_n` → 写入新的 explore 变体,父 LLM 被提示尝试不同路径;成功则固化并晋升。 -3. 否则走 candidate 命中 / `improve_every` 改进逻辑。 - -`DECISION: DONE` 时先 `agent_workbook_solidify`(把仍含 `worker.step` 的簿固化为 `# main` **返回**答案,而非仅 `print`),再晋升并写 `verified`。 -显式 `workbook=` 续跑优先于知识包查找。 - -质量启发(覆盖 skill 时,不调模型):`llm_free` 优先;源更短优先;同质取较新。更差 `quality` 不覆盖现 skill。 - -### 7.5 自我成长如何落在 OKF 上 - -| 能力 | 机制 | -|------|------| -| 优化 | 规划循环固化代码 → 更优 `resources/<slug>.mq.md` | -| 迭代 | 同 Concept slug/`sig` 覆盖 resource + 刷新 `generated`/`verified` | -| 成长 | 命中快路径;`candidate`/`hits`/`improve_every` 驱动再优化;`log.md` 可审计 | -| 分发 | 整包 `agent-kb/` 可复制(格式即契约) | -| **证明晋升(O2)** | `applies_when` / `fixtures` / `sandbox_profile` / `proof` 写在技能与 workbook frontmatter;promote 前 `sandbox.run` 绿才 `llm_free` | -| **隔离(O5)** | 失败技能 `status: quarantine`;回归 fixture 跟随 slug | - -### 7.5a 技能 frontmatter 约定(O2 B1) - -| 字段 | 含义 | -|------|------| -| `applies_when` | 适用条件(短文本 / 标签);路由与 harness 可读 | -| `fixtures` | 相对路径:sandbox 证明用 `.mq.md` | -| `sandbox_profile` | `default` / `readonly` / 其它 `sandbox.profile` 名 | -| `proof` | 与 `fixtures` 同义;promote 优先读 `proof` 再 `fixtures`,否则跑 workbook 自身 | - ---- - -## 8. 运行时与工具职责 - -| 组件 | 读 OKF? | 写 OKF? | 备注 | -|------|----------|----------|------| -| 解释器 / 字节码 VM | 否(语义) | 否 | 只跑 `.mq.md` | -| `marqdo catalog` | — | 工程目录包 | v0 | -| `plugins/agent`(`agent_kb_*`)+ `ext/ai` `plan` | 任务包 | 晋升时写任务包 | O2;**不**进核心 `src/host` | -| `lib/fs` | 通用文件 | 通用文件 | L1 包装 | -| `marqdo view` | 否 | 否 | HTML 另一轨 | -| 未来 `marqdo kb query` | 是 | 否 | 可选:按 type/tag/链接查询 | - -agent-kb 运行时实现归属 **agent 插件**(`agent_goal_sig` / `agent_kb_lookup` / `agent_kb_promote` / `agent_kb_record_hit` / `agent_workbook_solidify` / `agent_kb_task_files`),由 `ext/ai/agent` 调用;禁止把这些原语加回 `HostFn`。 - -解释器**不得**因缺少 catalog 而拒绝运行源文件。 - ---- - -## 9. 安全与边界 - -| 风险 | 对策 | -|------|------| -| 把生成物当配置手改 | 文档 + GENERATED 头;CI 可选校验 | -| 错误技能被复用 | 快路径必 spawn+inspect;失败标 `draft` 并重规划 | -| 签名过宽 | tools 指纹;文档强调 exact goal | -| 密钥进入知识包 | 继承 env;禁止把 key 写入 resource/概念正文 | -| 包膨胀 | runs 与 kb 分离;仅 DONE 晋升 | -| 与语言语义耦合 | catalog/kb 失败不影响 `marqdo run` 源文件 | - ---- - -## 10. 实现路线 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **O0** | 调研 + 生成式清单方向 + `.mq.md` 后缀 | **done** | -| **O1** | `marqdo catalog` / `sync`:Module + Catalog YAML | **done**(v0) | -| **O2** | 本文锁定的任务知识包:`Marqdo Task` / `Agent Skill`;`plan` reuse/promote | **done**(host kb_* + plan 快路径) | -| **O3** | catalog 增强:`verified`/`sources` 可选;模块页可点击依赖;扫入 `agent-kb` 概念供人浏览 | **done** | -| **O4** | `log.md` 策展、可选 `kb query`、Attested-style「再现跑通」收据(非 BigQuery) | 远期 | -| **O5** | 相近任务软命中:aliases + canonicalize + 本地 n-gram `near` + `soft_match` 父裁决已落地;dense embedding 仍见 [okf-near-match.md](../roadmap/okf-near-match.md) E | **A/B/C/D-near done** | - -O2 设计落盘后,智能体侧实现文档可薄化为指向本文 §7,避免两套真理。 - ---- - -## 11. 非目标 - -- 在 Marqdo 内核实现完整 OKF 验证器产品或云托管知识库。 -- 用 OKF 清单替代模块命名空间 / 导入语义([module-namespace.md](module-namespace.md))。 -- 强制用户提交 `.marqdo/` 进 git。 -- **默认**语义相似检索 / 向量库(可选软命中见 O5 / [okf-near-match.md](../roadmap/okf-near-match.md);不进内核)。 -- 跨仓技能市场(可后续在概念图上扩展)。 -- 照搬 OKF `Attested Computation` 的 BigQuery executor 模型。 - ---- - -## 12. 与既有文档的关系 - -| 文档 | 关系 | -|------|------| -| [okf-and-marqdo.md](../research/okf-and-marqdo.md) | 调研;产业背景与借鉴边界 | -| [generated-yaml-manifest.md](generated-yaml-manifest.md) | 早期「生成式清单」方向;**词汇与原则并入本文,命令细节见 catalog-cli** | -| [catalog-cli.md](catalog-cli.md) | O1 CLI 与 v0 落盘的操作说明 | -| [ext-agent-plan.md](ext-agent-plan.md) | 多步执行;缓存/复用应引用本文 §7 | -| [ext-agent.md](ext-agent.md) | 框架总览;自写回 ≠ 跨调用 OKF 知识包 | - ---- - -## 13. 决议摘要 - -1. Marqdo 的 OKF 实现 = **形态对齐 + Marqdo 类型词汇 + 生成/晋升管道**,不是语言换皮。 -2. **O1–O3 已落地**(工程目录包、任务知识包、catalog 扫入 agent-kb + 人读链接图);**O4** 策展/查询为远期。 -3. 可执行真相是 `.mq.md`;概念页负责**寻址、信任与联系**——人与 Agent 都是闭环里的一环。 -4. 父智能体复用优化结果,应走 **Task → Skill → resource → spawn**,而不是私有 JSON 缓存主路径。 -5. 未知 `type` 降级;无清单亦可运行源码。 - ---- - -## 14. 一句话 - -**Marqdo 用 OKF 风格的知识包索引程序与任务技能:源负责跑,概念负责找与信,catalog 与 agent-kb 分管工程目录与自我成长。** diff --git a/doc/design/oracle-journal-values.md b/doc/design/oracle-journal-values.md deleted file mode 100755 index 2125f8e..0000000 --- a/doc/design/oracle-journal-values.md +++ /dev/null @@ -1,131 +0,0 @@ -# Document oracle observations and strict replay - -`foreign.oracle_journal` returns a copy of this evaluation's observations as -ordinary `index/channel/value` records. Successful admitted `session_eval`, -`session_get`, and document `json.parse` operations append `eval`, `get`, and -`decode`, respectively. Set/open/close do not append. An observation is -validated recursively before append; handles and code objects cannot enter. -Each new HostContext starts with an empty observation list. - -`foreign.replay_check expected=J observed=J2` is a pure comparison, with no -foreign execution. It validates contiguous zero-based indices, channel tags -and crossing-domain membership. Records compare structurally by field name, -independent of field order. The result contains `ok`, the least mismatching -`index`, and both records (None for a missing entry). Two empty journals -match. Failure to provide a valid journal is an error, not a match. - -The interactive `DocumentSession::replay_check(snapshot)` is a different layer: -it executes a recorded trace from fresh state. Version-2 snapshots contain the -full chronological oracle trace, recorded stdin per step, its declared count, -the plan and source identity. Preflight validates every step before any foreign -execution. Every step is compared; none is skipped. Repeated cell executions -are distinct observations. Execution timing logs and cell display summaries -are not comparison inputs. Matching input values in a supplied snapshot is -consistency checking, not cryptographic authentication of the recording. - -Snapshots carry the SHA-256 of the loaded document text. Import checks it -before restoring foreign bindings, and preflights all crossing payloads before -mutation. Reload retains prior oracle observations with their original source -hashes, so a later checker can reject an incompatible trace. - -Lean: DocCalc's independent `runForeignLive` cursor simulates `runForeignAcc` -for arbitrary prefixes, observation accumulators and code sequences, including -oracle failures. `ForeignTrace` composes the registry's open/eval/close -judgments using independent normative and interactive execution control; -`trace_simulation`, `trace_correspondence`, and `trace_replay` quantify arbitrary -multisession action sequences, also when a run faults. These supplement the -existing theorems without removing them. - -Tests: `tests/oracle_journal.rs` runs the public document API on both evaluators; -`host::oracle::tests` covers journal equality and length localization; -`host::foreign_doc::tests` covers the live trace preflight and actual replay; -`host::foreign_session::tests` includes generated two-session model checks and -Python/Node boundary and process-failure experiments. The research runner is -`MarqdoThesis/PLDI/experiments/reviewer-v5/run.py`. - -## Stateful requests and semantic projection - -`HostContext.foreign_protocol_steps` records internal request attempts and -replies, including set values, copied eval input and raw stdin. It is separate -from the admitted language journal: rejected inbound responses belong to the -protocol evidence, while only admitted values belong to the oracle journal. -An input refused before send produces no protocol request. A response refused -after execution does not undo kernel effects; the post-state is retained. - -Language observations are recorded at the document API boundary and by live -cell evaluation. Low-level get/names used during snapshot export do not append -language observations. A successful eval projects to its result. A failed eval -projects to a record of stable status, output and diagnostics. Process timing, -commands and handles are not semantic values. The exact source path allocated -for one-shot execution is alpha-renamed only in diagnostic fields; raw stderr -and stdout remain available unchanged, and ordinary paths/error differences -are still compared. Live oracle records carry this same projected `value`. - -Python/Node replies mark serialization-domain failure with `domain_error`. -Error text is not used to infer this flag. Python refuses non-string object -keys; Node sanitizes objects with a null prototype to preserve special keys. -The common strict JSON decoder checks duplicate keys before materializing a -map, rather than losing them through overwrite. - -`ForeignState.lean` refines the earlier eval-only fragment with opaque kernel -state, complete request histories, set/get/eval input/decode, monotonic handle -allocation and fault outcomes carrying the admitted prefix. An adaptive -Program has continuations on actual observations; its correspondence theorem -covers data-dependent next actions, not just a fixed schedule. Mapping actual -document elaboration and host bindings to this program is a further proof -obligation recorded in the research status file. - -## Complete history, snapshot version 4 (2026-11-02) - -Strict interactive replay now records operations, not just successful cells. -Each public execution/mutation boundary records typed arguments, success or -failure, admitted observations, cell-oracle records, and stable resulting -state. Nested implementation calls are grouped under the user's operation. -The history includes set/get, run/step/run-all, restart, reload, plan edits, -clear, snapshot inspection and imported values. Failed attempts remain in the -history; rejected handles and secrets have only non-capability/redacted tags. -Clearing display outputs cannot erase the history's oracle projection. - -The snapshot stores the materialized initial plan and historical reload plans. -Entry text is parsed at its original path, retaining relative imports without -rewriting the user's document. Initial bindings are reapplied when a kernel is -reopened; unchanged reload kernels retain state, whereas changed language or -command retires the incompatible process. Loaded source/metadata and cached -cell outputs are updated consistently. - -Preflight checks the entire operation stream, all source revisions, plan edits, -binding/cursor/generation transitions, and oracle projections before starting -any replay kernel. Executing the trace compares each result, admitted value, -cell result and stable state. The first mismatch stops its dependent suffix; -`executed_actions` and `remaining_actions` make this explicit. `matched` counts -admitted observations and `matched_actions` counts operations. No missing -record is silently accepted or skipped. - -The HTTP replay-check endpoint performs an isolated comparison and retains an -existing warm session. It validates malformed input before starting even a -seed kernel; duplicate JSON fields are refused before overwrite. Verification -can still run recorded foreign work and its external effects: isolation is of -the document session, not a process sandbox. `replay_snapshot` remains the -separate legacy cell re-run API and makes no strict-history comparison claim. -Older version-2/3 snapshots may be used by legacy restoration/re-run surfaces; -they cannot prove a complete action history and strict checking requires v4. - -`ForeignHistory.lean` models explicit command boundaries. A fault terminates -its command, a later command receives the actual retained registry, and the -history retains all command faults and admitted observations. It proves -command-history correspondence, journal membership and no alias resurrection -through arbitrary recovery histories. This extends the adaptive Program -results; the general source-elaboration refinement is a separate outstanding -proof obligation. - -Experiment source inputs are frozen before running, checked again afterward, -and archived with their hashes. The current passing bundle is identified by -`MarqdoThesis/PLDI/experiments/reviewer-v5/LATEST-PASSING.json`. - -Each operation also retains its internal protocol attempts/replies, including -refused inspection results. Those records are compared even when an inspector -could not return a value. They are control evidence and do not admit rejected -payloads into the language journal. An explicit document session_names request -adds its admitted array on the decode channel; internal names/get probes do not. -Reload records either a historical source/plan input or its input-read error; -replay consumes that captured version input and does not rewrite past files. diff --git a/doc/design/paren-call-and-readable-invocation.md b/doc/design/paren-call-and-readable-invocation.md deleted file mode 100755 index 2184de8..0000000 --- a/doc/design/paren-call-and-readable-invocation.md +++ /dev/null @@ -1,231 +0,0 @@ -# 调用写法评估:`[函数名](参数)` 与更接近人读的调用形式 - -> **2026-10-23 审阅裁决**:“原型回退”仅描述当时实验,当前 payload 已支持 `f(args)` 和具名实参。旧 Classic 索引冲突不再决定默认语法;保留熟悉的调用形态与文档原生描述并不矛盾。参见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓),不要把本文备选形式当作已批准的新语法。 - -| | | -|---|---| -| 状态 | **Proposed · 待决策**(原型已验证并已回退,未合入代码) | -| 日期 | 2026-10-22 | -| 提出 | 「`[函数名](参数1 参数2)` 这种写法有没有可能成立;调用能否更符合人读习惯」 | -| 更正 | 本文替代前两轮对用户意图的误读(前两轮在讨论「表 / 函数即值」,不是调用语法) | -| 相邻 | [link-style-call-evaluation.md](link-style-call-evaluation.md) · [function-as-table-semantics.md](function-as-table-semantics.md) · [collection-access-link.md](collection-access-link.md) · [call-arguments.md](call-arguments.md) | - ---- - -## 0. 结论 - -| 问题 | 答案 | -|------|------| -| `[函数名](参数1 参数2)` 能否成立 | **技术上能,但代价在方括号**:它撞的是取元 `[键](集合)`,而命名空间里确有 2 个真实文件以函数名作键,任何「按名字消歧」都会静默改语义 | -| 更人读的调用能否成立 | **能,而且更干净**:`函数名(参数1 参数2)`(**不带方括号**)目前是**完全空闲的语法**,原型实测全量 **554 passed / 0 failed**,零回归 | - -一句话:**想要「参数进括号」这个美感,不需要方括号——去掉方括号反而没有任何冲突。** - -```markdown -**税率 = 查询税率(档位=2)** # 具名,读起来像函数调用 -**合计 = 加(1 2)** # 位置,读起来像数学 -**名 = txt.str_trim(" x ")** # 库函数同样适用(原型已验证) -``` - ---- - -## 1. 现状:今天的调用写法盘点(全部实测) - -| 写法 | 位置 | 实测 | -|------|------|------| -| `> 加 1 2` | 语句 | ✅ 位置参数 | -| `> 加 a=1 b=2` | 语句 | ✅ 具名参数 | -| `[加] 1 2` | 语句 | ✅ 方括号标记 + 位置参数(用于消歧/前置修饰) | -| `**r = > [加] 1 2**` | 粗体赋值 | ✅ 返回 3(方括号调用**已支持空格参数**) | -| `**r = 加 1 2**` | 粗体赋值 | ✅ **不带 `>` 也能调用,已可用**(打印 3) | -| `**r = > 加 a=1**` | 粗体赋值 | ✅ 显式 `>` 形态 | -| `**r = 加(1)**` | 粗体赋值 | ❌ `trailing input in expression: "(1)"` | -| `**r = [加](1 2)**` | 粗体赋值 | ❌ `unknown function `[加](1`` | -| `> [加](1 2)` | 语句 | ❌ `unknown function `[加](1`` | - -也就是说:**「参数放在括号里」这件事今天完全不存在**。 - ---- - -## 2. `[函数名](参数)` 为什么碰壁 - -### 2.1 方括号 + 圆括号 = 取元,这是**已定的语义** - -[collection-access-link.md](collection-access-link.md) §1 写的是心智模型: - -> **方括号 = 取出的名字,圆括号 = 从哪取。** - -```markdown -**价 = [拿铁](菜单)** # 从菜单里取出「拿铁」 -``` - -[call-arguments.md](call-arguments.md) §2 进一步锁定: - -> `]` 后**紧邻** `(` → **取元** `[key](collection)`,不是 callee 标记。 - -所以 `[f](x)` 不是「还没被用的语法」,而是**已经被取元占用**。 - -### 2.2 靠「名字是函数还是键」消歧,会真的打断现有代码 - -这是本轮新增的硬证据。我把全仓库扫了一遍: - -| 指标 | 数值 | -|------|------| -| `.mq.md` 文件 | 851 | -| `##` 级函数名 | 2367 | -| `[键](…)` 出现次数 | 983 | -| **键名与同文件函数名相同的冲突** | **5(去重后 2 个真实文件)** | - -两个真实冲突(不是构造出来的): - -``` -ext/data/db.mq.md:122 *[count](r)* # 函数名 ## count,同时 r 里有 count 列 -examples/code-as-docs/index.mq.md:79 价=[单价](行) # 函数名 ## 单价,同时 行 里有 单价 字段 -``` - -**这说明任何「函数名优先」的规则都会改变这两处的行为**:它们本意是取元,却会被解释成调用。 -反过来「数据优先」则永远无法用 `[f](1)` 调用。**两条路都走不通**——这不是实现难度问题, -而是同一外形承载两种语义的固有代价。 - -### 2.3 但有一个「无歧义子集」确实存在 - -`[f](1 2)` 与 `[f](a=1)` 里的括号内容**不是合法表达式**(实测 `x=1` 报 -`unknown function`、`1 2` 报 `unknown function`),所以理论上可判为参数列表: - -| 括号内容 | 能否是取元 | 可否判为调用 | -|---------|-----------|-------------| -| `(1 2)` 多 token | 否(非单一表达式) | ✅ 无歧义 | -| `(a=1)` 具名 | 否 | ✅ 无歧义 | -| `(1)` 单 token | **能** | ❌ 与 `[1](篮子)` 冲突 | -| `(m)` 单变量 | **能** | ❌ 与 `[a](m)` 冲突 | - -于是 `[f](1)`(最常见的单参调用)**永远无法**与取元区分。 -一个「多参数能用、单参数不能用」的语法,对使用者是最难记的一类。 - ---- - -## 3. `函数名(参数)`:空闲语法,原型验证通过 - -### 3.1 它是空闲的 - -实测 `**r = 加(1)**`(原型前)报 `trailing input in expression: "(1)"` —— -说明 `名字(` 今天既不表示取元,也不表示任何别的含义。**没有既有语义要保护。** - -### 3.2 原型做了什么 - -改了两处(**已回退,仅作验证**): - -1. `src/parse/expr.rs`:新增 `try_paren_call` —— 紧随其后的 `(` 视为参数列表; - 在 `parse_call_tail` 里优先尝试。 -2. `src/parse/mod.rs`:粗体赋值与 `>` 两条路径的「像调用」判定加上 - `looks_like_paren_call`(让单 token 的 `加(1)` 也能进入调用分支)。 - -### 3.3 原型实测结果 - -| 用例 | 结果 | -|------|------| -| `加(1)` | ✅ 返回 2(单参) | -| `加(1 2 )` | ✅ 返回 3(多参) | -| `加("1" "2")` | ✅ 返回 `12`(字符串参数) | -| `加(1 2)` | ❌ 末参数把 `)` 吞了 | -| `加(a=1 b=2)` | ❌ 具名参数值把 `)` 吞了 | -| `加(1, 2)` | ❌ 逗号不是分隔符 | -| `加(加(1 2) 3)` | ❌ 嵌套未支持 | -| `txt.str_trim(" x ")` | ✅ 返回 `x`(**库函数路径可用**) | -| **全量测试** | ✅ **554 passed / 0 failed** | - -**两条关键结论**: - -1. **零回归**:新语法是纯增量,没有破坏任何既有用例(含 4 个 `[k](c)` 取元金样)。 -2. **真正的落点在参数分词器,不在语法**:`加(1 2)` 失败、`加(1 2 )` 成功, - 差别只是 `)` 前多一个空格——说明 `parse_call_args` 的分词把 `)` 当成了 token 的一部分。 - 要修就得动 `parse_call_args` / `split_first_token` / `find_next_arg_boundary`, - 而这个分词器是**所有调用**(含今天在用的 `> f a=1`)共享的。 - -这解释了为什么这件事「看起来 10 行、实际一次核心改动」。 - ---- - -## 4. 人读性对比 - -同一个意思,五种写法: - -| 写法 | 读起来 | 现状 | -|------|--------|------| -| `> 加 1 2` | 「调用加,1 和 2」 | ✅ | -| `**合计 = 加 1 2**` | 同上,无 `>` | ✅ | -| `**合计 = 加(1 2)**` | 「加(1, 2)」,**像数学/函数调用** | 原型通过 | -| `**合计 = 加(a=1 b=2)**` | 「加,a=1、b=2」,自解释 | 原型通过 | -| `**[加](1 2)**` | 像链接,但与取元同形 | ❌ 不建议 | - -我的判断:**`f(args)` 是这几种里最符合人读习惯的**,理由有三: - -1. **与数学记号同构**:`税率(2)`、`sin(x)` 是跨语言、跨学科的通用写法,不需要学。 -2. **参数边界显式**:括号天然划定起止,解决了 `> f a b` 里「参数到哪结束」的模糊 - (这也是 D8「函数名含空格」难题的天然解药)。 -3. **不占用 Markdown 的链接语义**:渲染出来是普通文本 `f(1)`, - 不会像 `[f](1)` 那样在预览里变成超链接。 - ---- - -## 5. 要走完这条路,需要做什么(评估工作量) - -原型只验证了「方向可行」,要合入还缺这些: - -| # | 事项 | 位置 | 风险 | -|---|------|------|------| -| 1 | `)` 作为参数终止符 | `parse_call_args` / `split_first_token` / `find_next_arg_boundary` | **中高**:所有调用共享 | -| 2 | 逗号分隔 `f(1, 2)` | 同上 | 中:逗号在文本参数里合法(`"a,b"` 已加引号则无碍) | -| 3 | 嵌套 `f(g(1) 2)` | `parse_call_args` 递归 | 中:需要括号深度跟踪 | -| 4 | 方法 `obj.m(1)` / 库 `lib.fn(1)` | `try_paren_call` 已有基础(库路径实测通过) | 低 | -| 5 | 位置/具名混用规则 | 复用 [call-arguments.md](call-arguments.md) §3 | 低 | -| 6 | 空参 `f()` | 需定义语义(零参调用) | 低 | -| 7 | EKC 指纹 | `collect_calls` 已读 `c.callee`,`CallExpr` 不变 → 自动兼容 | 无 | -| 8 | `view` 渲染 | `[callee]` 已有 `bracket_marked` 标记,需决定是否回显括号形式 | 低 | -| 9 | `marqdo check` | 需新增「`名字(` 但不是函数」的诊断 | 低 | - -**注意第 7 条**:因为 `f(args)` 最终仍产出 `CallExpr { callee, args }`, -EKC 指纹、契约、字节码 `Op::Call(fid, argc)` **全部自动兼容**—— -这正是它与「一等函数」方案([functions-as-values-evaluation.md](functions-as-values-evaluation.md) §5 路径 A)的本质区别: -**它只是换了一种写法,没有改变调用模型。** - ---- - -## 6. 建议 - -### 6.1 推荐路线 - -1. **不做 `[f](args)`**:与取元同形,且已证明按名消歧会打断 2 个真实文件; - 而「多参能用、单参不能用」的规则不可教。 -2. **做 `f(args)`**:空闲语法、零回归、人读性好、不动调用模型。 -3. 先落**具名**形态 `f(k=v)`(最无争议、自解释),再补位置 `f(1 2)`,最后考虑逗号与嵌套。 - -### 6.2 若你想保留方括号的「链接感」 - -有一个不碰取元的位置:**语句位置**。 - -```markdown -> [加](1 2) # 今天报 unknown function;语句位置的 [k](c) 无实际用途 -``` - -`[k](c)` 作为**独立语句**今天只会算出值然后丢弃。全仓库扫描(851 文件): -以 `[` 起行且形如 `[k](c)` 的独立行只有 **2 处**,且都是样式示例文件里的 -普通 Markdown 链接文本(`[海上花开](https://…)`),并非取元代码。 -所以在**语句调用**里允许 `[f](args)` 几乎无成本,表达式里则不允许。 -代价是「同一写法在两种位置含义不同」,可教性差;我倾向不做。 - ---- - -## 7. 待你决策 - -1. **是否采纳 `f(args)`**(不带方括号)作为新调用写法? -2. 若采纳,**先做哪一档**: - - A 只做具名 `f(k=v)`(最小、最稳) - - B 具名 + 位置 `f(1 2)`(需改分词器,价值最大) - - C 再加逗号与嵌套(一次做全) -3. **`[f](args)` 是否彻底放弃**(我建议放弃,理由 §2.2); - 还是只允许在语句位置(§6.2)? -4. 是否需要我按 B 档做一次完整实现(含分词器改造 + 金样例 + 变更文档), - 做完再走 554 回归? - -原型代码已全部回退,工作区干净。等你定档我再动手。 diff --git a/doc/design/parser-diagnostics-d8-d9.md b/doc/design/parser-diagnostics-d8-d9.md deleted file mode 100755 index 176c305..0000000 --- a/doc/design/parser-diagnostics-d8-d9.md +++ /dev/null @@ -1,208 +0,0 @@ -# 设计:解析器诊断缺陷修复(D8 / D9) - -| | | -|---|---| -| 状态 | **Accepted** | -| 日期 | 2026-10-22 | -| 来源 | [qdagent-refactor-defects-2026-10.md](../research/qdagent-refactor-defects-2026-10.md) D8 / D9 | -| 影响面 | **核心解析**(`src/lex/mod.rs` 行分类 + `src/parse/expr.rs` 函数调用) | -| 关联 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-vs-comment.md](code-vs-comment.md) | - ---- - -## 0. 为什么这两条要先做调研 - -D8 与 D9 都落在**行分类**这一层:它决定一行是「叙述」还是「代码」。 -改错的代价是**整类文档解析结果变化**,而不是某个函数行为变化。 -所以本文先量化影响面、列出候选方案并逐条否决,再动手。 - -一句话结论: - -- **D9** 的根因是分类层把「引号未闭合的粗体行」降级为叙述, - 导致解析层精心准备的 `unterminated " string` 报错**永远走不到**。 - 修法是在分类层补一条「粗体起始但闭合搜索失败」的判定,让它进入解析层报错。 - 语料实测 620 个文件 0 处受影响,风险可控。 -- **D8** 的根因是函数名解析按空格切词,与定义侧不对称。 - 修法是在**定义期**拒绝含空格的函数名(fail fast), - 而不是在调用期做贪婪匹配(那会改变所有多词行的语义)。 - ---- - -## 1. D9 — 未闭合引号静默吞行 - -### 1.1 现状链路 - -``` -源码行 "**s = \"abc" - ↓ classify_source → classify_line - ↓ 首字符 '*' → is_marqdo_star_line? - trimmed.starts_with("**") → matching_bold_close(trimmed) - → matching_bold_close_opts(require_eol=true) - 扫描时遇 '"' → in_str = true - 之后没有任何 '"' 关闭它 → 后续 '*' 全部被当作字符串内容跳过 - 返回 None(找不到收尾 **) - → is_marqdo_star_line = false - ↓ classify_line 落到 `Some('*') if !is_marqdo_star_line` → LineKind::Comment - ↓ 该行成为**叙述**,parser 根本看不到它 - ↓ parse_quoted_string 里 `bail!("unterminated {quote} string")` 不可达 -``` - -**结论**:这不是解析器的 bug,是**分类器的静默降级**。 -解析层已经把错误信息写好了,却没有人把这一行送到它面前。 - -### 1.2 影响(为什么算高严重度) - -| 场景 | 后果 | -|------|------| -| 手写漏一个引号 | 该行消失;变量未定义 → 在别处报 `undefined variable`,方向被引偏 | -| LLM 生成文档 | 少一段内容,但 `exit 0`、`marqdo check` 通过,**文档看起来完整却缺节** | -| CI/门禁 | 门禁试跑通过 → 错误文档被沉淀入库 | - -对「文档即程序」而言,这属于最危险的一类:**静默产出错误结果**。 - -### 1.3 候选方案与评判 - -#### 方案 A:分类层补判定(采纳) - -在 `is_marqdo_star_line` 中,当 `trimmed.starts_with("**")` 且 -`matching_bold_close` 返回 `None` 时,再判断「这一行是否**像**粗体代码」: - -- 行内含有 `=`(赋值)或 `>` 前导(调用)等强代码信号 -- 且引号计数为奇数 - -满足则**仍判为 Code**,让解析层去报 `unterminated " string`。 - -**优点** -- 改动局限在分类层,不动解析语义 -- 复用解析层已有的、措辞准确的报错 -- 对「正常叙述中含 `**` 强调」零影响(那些行引号是配对的) - -**风险**:叙述里恰好出现 `**…"…` 这种畸形组合会被判成代码 → 报错。 -但实测语料 0 例,且这种组合本身就是写法错误,报错是**期望行为**。 - -#### 方案 B:解析层预扫描(否决) - -在 `parse_classified` 前加一遍全文引号配对检查。 - -**否决理由**:引号可以合法地出现在叙述、围栏代码块、行内代码里。 -全文扫描无法区分上下文,会制造大量假阳性(例如叙述里写「他说 "你好」)。 -逐行判断需要的是**分类**信息,而这正是方案 A 在做的事。 - -#### 方案 C:放宽 `matching_bold_close`,引号未闭合时也认 `**` 收尾(否决) - -**否决理由**:会改变「粗体闭合」的语义。`**s = "a ** b"` 这类行 -会提前在中间 `**` 处闭合,把字符串拆断,产生更难理解的错误。 -这是把静默错误换成**更混乱的错误**,不是改进。 - -### 1.4 影响面实测 - -对仓库内全部 `.mq.md`(`target/` 除外)做静态扫描: - -| 指标 | 数值 | -|------|------| -| `.mq.md` 文件总数 | 845 | -| 含 `**` 起始代码行的文件 | 620 | -| **引号计数为奇数的代码行** | **0** | - -扫描时正确跳过了 `\` 转义(`\"` 不算引号开合)。 -结论:修复不会改变任何现有文件的解析结果。 - -### 1.5 验收 - -| 用例 | 期望 | -|------|------| -| `**s = "abc`(未闭合) | 报 `unterminated " string`,退出码非 0 | -| `**s = "abc"`(闭合) | 正常运行 | -| 跨行 `**s = "a` + `b"**` | 报错(不跨行拼接,符合现状) | -| 叙述 `他说 "你好"` | 仍是叙述,不受影响 | -| 全量 `cargo test` | 233 全绿 | -| 全仓库重跑 `marqdo check` | 无新增错误 | - ---- - -## 2. D8 — 函数名含空格:定义成功、调用必崩 - -> **⚠️ 本节方案已作废。** 原主张「定义期拒绝空格」违背了「完全兼容 Markdown」: -> `## 用户 登录流程` 是合法标题,不该为了可调用而改写。 -> 现行评估见 [spaced-function-names-d8.md](spaced-function-names-d8.md)(Proposed · 待审阅)。 -> 本文其余部分(D9)仍然有效。 - -### 2.1 现状链路 - -``` -定义侧:## 加一 号 → 标题整体作为函数名 "加一 号"(允许空格) - -调用侧:> 加一 号 n=1 - ↓ 按空白切词 - token[0] = "加一" → 当作函数名 - token[1..] = ["号", "n=1"] - ↓ "号" 无 `=` → 按位置参数/变量插值处理 - ↓ 变量 "号" 不存在 → undefined variable `号` -``` - -两侧不对称:定义时把整串当名字,调用时只取第一个词。 - -### 2.2 候选方案与评判 - -#### 方案 A:定义期拒绝空格(**已否决**) - -解析 `## 函数名` 时,若函数名含空白则报错: - -``` -error: 文件:行: function name may not contain spaces: `加一 号` - (write `加一_号`, or quote the call as `> "加一 号"`) -``` - -**优点** -- fail fast:错误在定义处暴露,与调用处报 `undefined variable` 相比指向明确 -- 不改变任何合法程序的语义 -- 与「标识符不含空格」的通行约定一致 - -**风险**:可能已有文件用了空格函数名且**只定义不调用**(今天能跑)。 -需先扫描语料确认。 - -#### 方案 B:调用侧贪婪匹配已知函数名(否决) - -按「已知函数名的最长前缀」匹配。 - -**否决理由**: -1. 需要把「所有已定义函数名」带进表达式解析上下文,跨越模块边界后不可判定 -2. `> print text=hello world` 里 `hello world` 会被尝试拼成函数名,语义歧义 -3. 改变所有多词行的解析路径,属于核心语义变更,收益远小于风险 - -#### 方案 C:只警告不报错(否决) - -**否决理由**:D8 的危害正是「check 通过、运行崩」。继续给警告等于维持现状。 - -### 2.3 影响面实测 - -统计仓库内**定义侧含空格**的 `##`/`###` 标题(仅可调用的层级): - -| 指标 | 数值 | -|------|------| -| 含空格的二级及以下标题 | 4 | -| 其中位于源码(非运行时目录)的 | **0** | -| 分布 | 全部在 `.marqdo/agent/contexts/*.mq.md` 运行时生成物,且是叙述性标题("Existing Capabilities"),从未被调用 | - -结论:源码中不存在含空格的函数名,加定义期校验不会破坏任何现有模块。 -运行时生成的 context 文件不受影响——它们不被 import。 - -### 2.4 验收 - -| 用例 | 期望 | -|------|------| -| `## 加一 号` | 报 `function name may not contain spaces` | -| `## 加一_号` + 调用 | 正常 | -| `## 断言干净`(中文连写) | 正常 | -| 方法 `### 名字 带空格` | 同样拒绝 | -| 全量测试 | 233 全绿 | - ---- - -## 3. 实施顺序 - -1. D9(分类层,影响面已量化)→ 测试 → 文档 -2. D8(定义期校验)→ 测试 → 文档 -3. 两条都做完后跑全仓库回归(`cargo test` + 抽样 `marqdo run`) - -每一步独立提交,便于回滚。 diff --git a/doc/design/pipeline-debug.md b/doc/design/pipeline-debug.md deleted file mode 100755 index b2fa25f..0000000 --- a/doc/design/pipeline-debug.md +++ /dev/null @@ -1,75 +0,0 @@ -# 解释器流水线可视调试 - -| | | -|---|---| -| 状态 | 已定(开发期强制友好) | -| 日期 | 2026-08-04 | -| 参考 | [Crafting Interpreters — Scanning](https://www.craftinginterpreters.com/scanning.html)(先打 token)· [AstPrinter](https://craftinginterpreters.com/representing-code.html) · CLI `--dump-ast` 类实践 | - ---- - -## 1. 目标 - -开发 `marqdo` 时,对任意 `.mq.md` 应能**分阶段看见**中间结果,避免黑盒;正式 `run` 默认安静,仅输出程序 `print` 的内容。 - ---- - -## 2. CLI 开关 - -```bash -marqdo run FILE [dumps...] -marqdo dump FILE --stage lines|tokens|ast|sema|all -``` - -| 标志 | 阶段 | 输出内容 | -|------|------|----------| -| `--dump-lines` | 行分类 | 每行:`kind=Comment\|Code\|Blank` + 原文;v0.3 行内位 `[decl n]` / `[bold …]` / `[italic …]` | -| `--dump-tokens` | 词法 | Token 流:`type lexeme line:col` | -| `--dump-ast` | 语法 | 模块/函数/语句;形参带 `inferred`;叙述死绑定 `dead=[…]` | -| `--dump-sema` | 语义 | 作用域、导入图、提升后的符号表 | -| `--trace-eval` | 求值 | **JSON 行**(stderr):语句级事件,含 `path` / `span`(`line:col`) | -| `--dump-bytecode` | 字节码 | 反汇编 `Program`(指令旁带 `@line:col`;见 [bytecode.md](bytecode.md)) | -| `--backend tree\|bytecode` | 执行后端 | 默认 `tree`;`bytecode` 走栈式 VM | -| `--dump-all` | 以上全部 | 按管道顺序打印,段之间用横幅分隔 | - -格式约定: - -- dump 人类可读优先;段首统一:`=== marqdo: <stage> ===` -- `--trace-eval`:每条事件一行 JSON,例如 - `{"event":"stmt","path":"…","span":"5:1","kind":"call","callee":"print"}` - 树遍历:`enter_fn` / `stmt` / `leave_fn`;字节码:`op`(`print`/`input`/`call`/`return`)。 -- 有 dump 时:若求值未实现,仍打印已实现阶段再以非 0 退出(便于 M1 只测 lines) - ---- - -## 3. 横幅示例 - -``` -=== marqdo: lines (tests/structure/hello.mq.md) === - 1 Blank - 2 Comment | # Hello World - 3 Blank - 4 Comment | 本程序调用... - 5 Blank - 6 Code | > print text=Hello World! -=== marqdo: end lines === -``` - ---- - -## 4. 实现要点 - -- dump 逻辑放在 `src/debug/`(或各阶段 `fmt`),**不**与安静求值路径搅在一起。 -- 每个阶段纯函数:`input → (artifacts, diagnostics)`,CLI 负责打印。 -- 单测可断言 dump 字符串包含关键行(稳定子集),避免绑死全文格式。 - ---- - -## 5. 与里程碑 - -| 里程碑 | 必须可用的 dump | -|--------|-----------------| -| M1 | `--dump-lines`(及可选 tokens 雏形) | -| M2 | `--dump-ast` | -| M3–M4 | `--dump-sema`、`--trace-eval` | -| 全程 | `--dump-all` 随阶段增长自动变完整 | diff --git a/doc/design/prove-cli.md b/doc/design/prove-cli.md deleted file mode 100755 index ff5450c..0000000 --- a/doc/design/prove-cli.md +++ /dev/null @@ -1,925 +0,0 @@ -# `marqdo prove`:SKILL 编排的 Lean 编译与顾问式证明 - -| | | -|---|---| -| 状态 | **已实施(Implemented · 2.8.0)**:P0–P3 落地记录见 §12;遗留项(foreach、跨模块 assume-guarantee、假设表 T3)显式延期至 2.9,理由见 §12.4。路线图:[roadmap/prove.md](../roadmap/prove.md) | -| 日期 | 2026-11-13 | -| 层归属 | **Language**:定理表角色 + `check --proof`(§7,[ADR 0010](../adr/0010-skill-proof-boundary.md))· **Runtime**:`prove` 管线(§4–§6、§8)· **Document**:`verification/skill-proof` 证据 | -| 相关 | [core-surface.md](core-surface.md)(复用 `table` 构造,不新增标记)· [layers.md](layers.md)(准入)· [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [ADR 0010](../adr/0010-skill-proof-boundary.md) · [verification/replay-policy](../../verification/replay-policy/README.md)(Lean 伴随判定的先例) | -| 目标版本 | CLI **2.8.0**(wasm / ext 不随动:`prove` 不进 wasm) | - ---- - -## 0. 一句话与三条契约 - -`prove` 把一份 `.mq.md` 的**控制平面**(参数 → 分支 → 外部操作 → 返回值)降级成 Lean 4 定义,把作者声明的**定理**变成 Lean 定理,并尽最大努力自动关闭它们;同时输出一份可供人复核的证据(证书、假设、被拒清单)。它**不**是发布门禁,也**不**声称"过了 Lean 就绝对正确"。 - -三条契约,按优先级排列: - -1. **诚实**:`proved` 只表示"Lean 内核接受了这条形式化陈述"。它不表示陈述写对了意图、不表示外部 API 会守约、更不表示整份 SKILL 安全。反过来,`unproved` 只表示"这次没有关闭它"——可能是定理不成立,也可能只是策略不够。 -2. **单调**:离线判定(没有 Lean 时)**只能**给出 Lean 也能给出的结论。若两者分歧,以 Lean 为准并报内部错误,绝不放绿。`checked` 永远弱于 `proved`。 -3. **不执行**:`prove` 从头到尾不运行被证程序,不产生任何效应;它只读源码、写缓存与 `--emit` 目录。 - -> 一句话给论文:*给编排文档配一张可复核的证明收据*,而不是给整个语言发一张正确性证书。 - ---- - -## 1. 定位:降低审核量,不取代审核 - -### 1.1 为什么是顾问而不是门禁 - -Agent 改写 SKILL 后,人要看的是"这一步会不会绕开审核""失败分支会不会吞掉错误"。这些恰好是控制平面命题,Lean 能帮我们把"逐行读代码"压缩成"读几条定理 + 看一眼反例"。但: - -- 真实 SKILL 里有字符串、JSON、外部服务;把这些都形式化,成本远高于收益; -- 形式化陈述与业务意图之间永远隔着"作者写得对不对"; -- 大多数团队没有 Lean,强制门禁只会让人绕过工具。 - -所以 `prove` 的默认行为是**报告**,不是**拦截**。规范与手册**推荐**在发布 SKILL 前跑一次,但不强求;要不要把某个状态当失败,由调用方用 `--require-lean` / `--report-only` 自己决定。 - -### 1.2 三种"绿"和两种"红" - -| 状态 | 含义 | 由谁产生 | 能不能当"已证明" | -|---|---|---|---| -| `proved` | 全部定理被 Lean 内核接受 | Lean | **能**(且仅限陈述本身) | -| `checked` | 全部定理在离线片段(§5)内判定为真,已生成对应 Lean 脚本但未运行 | 离线判定 | **不能**,只能说"离线判定通过" | -| `unverified` | 有定理超出离线片段,且没有跑 Lean | 离线判定 | 不能 | -| `unproved` | 至少一条定理未被关闭;若能给出反例则附见证 | Lean / 离线 | 不能;这是红灯 | -| `rejected` | 有函数不在可证子集(`while`/递归/动态派发),已跳过 | 降级器 | 不能;这是"未覆盖",不是"错误" | - -`rejected` 与 `unproved` 的区别很重要:前者是**工具够不着**,后者是**命题没过**。把它们混成一个红,会让"文件里有个循环"看起来像"业务逻辑错了"。 - -此外还有 `error`(编码/类型/效应/IO/超时):它不是判定结果,而是**工具或程序本身出错**,退出 1。五种判定(proved/checked/unverified/unproved/rejected)与 `error` 在 JSON 里共用 `status` 字段,但语义分组不同,报告会分开统计。 - -### 1.3 诚实性词汇表(写进 README 与 `--json`) - -- `proved` ≠ 正确:它只对**写下来的陈述**负责,且假设 `Env` 的返回值任意、`假设` 表成立。 -- `unproved` ≠ 错误:策略失败、超时、片段外都可能;只有带 `counterexample` 字段时才是"确实不成立"。 -- `rejected` ≠ 不安全:只表示这部分没被形式化覆盖。 -- 证书不替代代码评审:它是**缩小**评审范围的工具,`audit` 会明确列出"哪些外部操作完全未知"。 - -### 1.4 非目标 - -- 不形式化解释器、字符串库、JSON、浮点、`formula`。 -- 不证明外部服务与网络;这些由 `假设` 表显式承担。 -- 不在 Agent 每次运行时跑 Lean;运行期只读证书。 -- 不自动安装 Lean;只探测并给出可执行提示。 -- 不追求"零人工":目标是让人从"读 200 行"变成"读 5 条定理 + 1 张假设表"。 - ---- - -## 2. 证明范围 - -### 2.1 义务分级 - -| 级别 | 义务 | 作者要写什么 | 谁保证 | 离线可做 | -|---|---|---|---|---| -| **T0 类型** | 生成的 Lean 通过内核;字段、元数、分支同型 | 无 | Lean | 部分(Rust 类型检查) | -| **T1 结构** | 终止(无 `while`/递归 ⇒ 结构递归)、分支出口完整、返回类型符合 `返回` 契约、效应不越权(给了 `--effects` 时) | 无 | 降级器 + Lean | 是 | -| **T2 声明** | 定理表里的业务命题 | 定理表 | Lean / 离线片段 | 是(F1–F5) | -| **T3 契约** | 外部操作前置/后置假设下的组合推理 | `假设` 表 | Lean | 部分 | -| **T4 一致性** | 生成语义与解释器在纯片段上同值 | 测试语料 | 差分测试 | 是 | - -### 2.2 三条硬边界(拒绝,不降级) - -| 构造 | 处理 | 诊断码 | -|---|---|---| -| `while`(`-` + 条件行) | 跳过该函数 | `proof.while` | -| 直接/间接递归(调用图有环) | 跳过该环 | `proof.recursion` | -| 动态派发(插件调用、变量函数名、`code` 值调用) | 跳过该调用点 | `proof.dynamic_call` | - -被跳过的函数不参与定理,其余函数照常出证。整体状态按固定优先级合成(差者胜):`error` > `unproved` > `rejected` > `unverified` > `checked` > `proved`。`--allow-opaque <FN>` 可把某个被跳过的函数**整体**降级为不透明操作,让调用它的编排仍可证——此时它的行为完全未知,`audit` 必须列出来。 - ---- - -## 3. 命令面 - -### 3.1 命令与别名 - -```bash -marqdo prove [PATH] # 降级 → 生成 → 离线判定 →(有 Lean 时)Lean 判定 -marqdo prove emit [PATH] -o DIR # 只生成 Lean,不判定(离线/论文/AI 取用) -marqdo prove audit [PATH] # 只报降级结论:内联了什么、不透明了什么、拒了什么、假设了什么 -marqdo prove clean # 清 .marqdo/prove 缓存 -``` - -`prove` 带 `visible_alias = "lean"`;文档与 CI 统一写 `prove`。它与既有 `verify` 不重叠:`verify` 查知识一致性,`prove` 查控制平面命题。 - -### 3.2 参数 - -| 参数 | 默认 | 含义 | -|---|---|---| -| `PATH` | `index.mq.md` | 单个 `.mq.md`;目录需 `--all` | -| `--all` | off | 目录递归(跳过 `target`/`dist`/`node_modules`/`.git`/`.marqdo`);`--max-files <N>` 默认 200 | -| `--entry <FN>` | `main` | 入口与报告分组;不限制文件内全量证明 | -| `--only <FN>` | — | 只证这些函数(可重复),用于增量 | -| `--emit <DIR>` | `.marqdo/prove/<key>/Generated` | 保留生成的 Lean | -| `--json` | off | stdout 一个 JSON 对象(§3.5);诊断走 stderr | -| `--lean <PATH>` / `--lake <PATH>` | 探测 | 显式工具链 | -| `--library <DIR>` | 探测 | `MarqdoProof` 库目录 | -| `--timeout <SEC>` | 120 | 单次 Lean 调用上限 | -| `--heartbeats <N>` | 400000 | `maxHeartbeats` | -| `--no-cache` | off | 绕过证书与 olean 缓存 | -| `--no-offline` | off | 跳过离线判定,只用 Lean(CI 复现/调试用) | -| `--require-lean` | off | 严格模式:`checked`/`unverified`/`rejected` 一律返回 2 | -| `--report-only` | off | 除工具错误外恒返回 0 | -| `--allow-opaque <FN>` | — | 把被跳过的函数降级为不透明操作 | -| `--effects <LIST>` | — | 与 `marqdo call --effects` 同格式;给出时检查实际调用是否越权 | -| `--strict-types` | on | 类型无法推断即报错;`--no-strict-types` 落 `Val`(证明力下降,报告标注) | -| `--tactic <T>` | `auto` | 定理表未写 `策略` 时的默认策略 | - -### 3.3 状态与退出码 - -| 状态 | 退出码 | `--require-lean` | `--report-only` | -|---|---|---|---| -| `proved` | 0 | 0 | 0 | -| `checked` | 0 | **2** | 0 | -| `unverified` | 0 | **2** | 0 | -| `rejected` | 0 | **2** | 0 | -| `unproved` | 1 | 1 | 0 | -| `error` / `timeout` | 1 | 1 | 1 | - -设计理由: - -- 缺工具链、有循环、定理在片段外,都**不是**程序的错,默认不返回非零——否则没装 Lean 的机器上 `prove` 等于不可用。 -- 默认情况下只有两种非零来源:**你写下的定理未被关闭**(1),或**工具出错**(1)。不写定理就不会有第一类失败。 -- 想要严格覆盖的团队用 `--require-lean`,把"未判定"升级成 2;CI 里加这一个参数即可。 -- 全局开关 `--report-only` 让 Agent 在探索期只看报告。 - -### 3.4 文本输出 - -```text -$ marqdo prove skills/marqdo-release/index.mq.md -审批 2/2 定理 proved Lean 0.8s -plan 1/1 定理 checked 离线判定 12ms(附 Lean 脚本,未运行) -预检 — rejected 离线 3ms proof.while L88 -prove: proved 1 · checked 1 · rejected 1 - 说明: checked 不代表 Lean 已验证;安装 Lean 或传 --lean 可交由 Lean 判定。 - 提示: `marqdo prove audit …` 查看降级细节与假设清单。 -``` - -失败时: - -```text -error[proof.claim_failed]: 定理「不该自动放行」未被关闭 - --> examples/approval.mq.md:31:3 - = 目标: (run env p).1.ok = false - = 上下文: h : p.amount > 10000 - = 反例: 金额 = 10001 时走「人工审核」分支,结果 ok = true - = 说明: 可能是命题不成立,也可能是策略不够;补 `策略` 或改判据后重跑。 -``` - -### 3.5 JSON(面向智能体的稳定契约) - -一个对象,`schema` 版本化;永不交互、stdout 只有结果、诊断在 stderr、路径为相对工作目录: - -```json -{ - "schema": 1, - "status": "checked", - "file": "skills/example/index.mq.md", - "source_sha256": "…", - "artifact_id": "mq://…", - "functions": [{ - "name": "审批", - "status": "checked", - "tier": "offline", - "claims": [ - {"id": "大额必经人工", "status": "checked", "decided_by": "trace", "ms": 3}, - {"id": "退款必须留痕", "status": "unverified", "reason": "out_of_fragment"} - ], - "obligations": [{"id": "terminates", "status": "passed"}, - {"id": "effects_subset", "status": "skipped", "reason": "no --effects"}] - }], - "lean": null, - "assumptions": [], - "diagnostics": [], - "emitted": [".marqdo/prove/ab12…/Generated/Approval.lean"], - "duration_ms": 15 -} -``` - -`lean` 为 `null` 表示没跑;跑了则是 `{"toolchain": "...", "library_sha256": "...", "module_sha256": "...", "cache": "hit|miss"}`。`tier` ∈ `{lean, offline, none}`,标明该函数的结论来自哪一层。`status` 的取值集合固定(§1.2),Agent 可按它分支,不需要解析自然语言。 - -### 3.6 面向智能体的使用契约 - -`prove` 的主要调用者不是人,是 Agent 的循环。因此: - -- **一次调用一个结论**:不做交互式提问,不读 TTY,不依赖环境变量之外的隐藏状态。 -- **只解析 JSON**:`--json` 的键与状态词是稳定契约(`schema` 升级才变);stdout 不混入程序输出或进度条。 -- **失败即数据**:每条诊断都有 `code` / `file` / `line` / `column` / `message`,能定位的还带 `goal`、`context`、`counterexample`、`hint`。Agent 不需要从自然语言里猜。 -- **可增量**:`--only <FN>` 只证受影响函数;证书命中让第二轮降到毫秒级。 -- **先审计再证明**:Agent 应先 `prove audit --json` 看"有多少内联、多少不透明、多少被跳过",再决定是否值得为该文件写定理。 -- **推荐循环**:写 SKILL → `check` → `prove --json` → 读 `claims[].status` → 改代码/定理/策略 → 重跑 → 把证书附进交付说明。 - -### 3.7 选择规则 - -- **文件**:显式路径;目录必须 `--all`(否则 `proof.need_all`)。 -- **函数**:文件内全部 `##` 函数默认参与;`# main` 只作分组。 -- **导入**:默认内联可判定的纯函数(§4.5),其余成为不透明操作;不递归证明被导入文件。 -- **`--all` 聚合**:逐文件出状态,整体取最差;`--json` 输出 `files: [...]`。 - ---- - -## 4. 管线 - -### 4.1 六段 - -```text -.mq.md - ① 装载 load_module(只读,不执行) - ② 降级 AST → Plan IR:子集验收、拒绝码、span - ③ 定型 contract::Ty 驱动;未定 ⇒ 报错或 Val - ④ 生成 IR → Lean(确定性:稳定排序、无时间戳、相对路径) - ⑤ 离线判定 符号执行 + 片段判定(§5),产出 checked / 反例 / unverified - ⑥ Lean 判定 有工具链时运行;以它为准,与 ⑤ 分歧即 error -``` - -⑤ 永远在 ⑥ 之前:离线先给快速反馈,Lean 随后确认。`--no-offline` 可只跑 ⑥。 - -### 4.2 Plan IR - -`src/prove/ir.rs`,`serde` 序列化为 `plan.json`(版本化,缓存键的一部分,论文工具可直接消费): - -```jsonc -{ - "schema": 1, - "module": "skills/example/index.mq.md", - "source_sha256": "…", - "functions": [{ - "name": "审批", - "params": [{"name": "金额", "ty": {"kind": "int"}}], - "result_ty": {"kind": "map", "fields": [["ok","bool"],["value","any"],["error","any"]]}, - "ops": [{"id": "人工审核", "effect": "network.read", "params": [["金额","int"]]}], - "steps": [ - {"kind": "if", "cond": {"op": "gt", "args": [{"var": "金额"}, {"int": 10000}]}, - "then": [{"kind": "bind", "var": "审核", "expr": {"call": "人工审核", "args": [{"var": "金额"}]}}, - {"kind": "return", "expr": {"ctor": "result.ok", "args": [{"var": "审核"}]}}], - "else": [{"kind": "return", "expr": {"ctor": "result.ok", "args": [{"text": "auto"}]}}], - "span": {"line": 21, "col": 1}}], - "claims": [{"id": "大额必经人工", "premise": null, "conclusion": "…", "tactic": null}], - "effects": ["network.read"], - "assumptions": [] - }] -} -``` - -表达式分两层:`PureExpr`(字面量、变量、算术/比较/布尔、字符串拼接与插值、列表/映射字面量、`access`、`len`、类型转换)可翻译成 Lean 项;其余一律 `Call`(不透明操作),或按 §4.3 拒绝。**没有"猜"的回退。** - -### 4.3 接受 / 拒绝矩阵 - -| Marqdo | 处理 | 备注 | -|---|---|---| -| `**x = 纯表达式**` | `bind` | 类型由右值推断 | -| `**x = [标签](调用)**` | `bind` + `Op` + `trace` | 效应来自 sema | -| `**x**`(粗体无赋值) | `return` | 纯表达式或已内联构造器 | -| `*语句*` / `> 调用` | 语句形式,值丢弃 | 丢弃的调用仍进 trace | -| `1. 条件 / 2. *` | `if/else` | 条件必须是纯布尔表达式 | -| `- [项](遍历 列表 为 项)` | `foreach`(P3) | 只接受有限列表;此前 `proof.foreach_pending` | -| `-` + 条件 | **跳过** `proof.while` | | -| 递归 | **跳过** `proof.recursion` | 调用图环检测 | -| 方法调用 `` `recv`.方法 `` | 不透明操作 | 接收者不展开 | -| `code` 值 / 插件调用 | **跳过** `proof.dynamic_call` | 不在纯片段 | -| GFM 表绑定 | `list`/`map` 字面量 | 列长不一致已在解析期拒绝 | -| `$$` 公式 | 不透明值(`Formula`) | 不翻译 TeX,不做推理 | - -### 4.4 类型推断 - -起点:`参数` 表 + `返回` 表(`contract::Ty`)。合一规则: - -- 字面量给最具体类型;`+ - * /` 要求两侧 `int`;`and/or/not` 要求 `bool`。 -- 分支合流:两臂同名变量类型必须相容,否则 `proof.type_mismatch`(带两处行号)。 -- 映射字段:返回表达式是映射字面量时得到 `structure`;是内联的 `result.ok/error`(lib/result 真实 API)时沿用 Result 形状;否则落 `Val`,此时 `结果.ok` 报 `proof.result_untyped`(提示:返回映射字面量或包成 Result)。 -- `--no-strict-types` 时未知类型落 `Val`;定理里只能做等式/成员判断,报告标注"弱类型"。 - -### 4.5 内联与不透明化 - -1. 建调用图(本文件 + 导入文件);有环即跳过该环。 -2. **内联**:被调函数(含 `lib/result` 一类纯库)满足 ①契约 `Effects: pure` ②语句数 ≤ 24 ③不含被跳过构造 ④非递归 → 展开函数体。这样 `result.ok(...)` 在 Lean 里就是 Val 映射构造(`mqResultOk`),`结果.ok` 变成可判定字段。 -3. **不透明化**:其余调用生成 `Op` 构造器 + 效应,由 `Env` 参数处理;`--allow-opaque` 可强制。 -4. `audit` 逐条列出:内联 / 不透明 / 跳过,以及每个不透明操作的效应与参数类型。 - ---- - -## 5. 离线判定(没有 Lean 也能给结论) - -### 5.1 为什么需要 - -- 大多数开发机与 CI 没有 Lean;没有离线路径,`prove` 就只是"生成器"。 -- Agent 迭代需要毫秒级反馈,Lean 一次数百毫秒到数十秒。 -- 反例("金额 = 10001 时轨迹里没有人工审核")比 tactic 失败更有用。 - -但离线**绝不能**比 Lean 强。做法不是"相信我们的判定器",而是把它关进一个**极小的片段**,并让每条离线结论都附带 Lean 脚本。 - -### 5.2 片段 F1–F5(保守,超出即 `unverified`) - -| 片段 | 能判定什么 | 为什么安全 | -|---|---|---| -| **F1 路径枚举** | 控制流是有限树(无循环/递归)⇒ 返回路径有限 | 由 §2.2 的拒绝保证 | -| **F2 轨迹** | 每条路径的 `Op` 序列由分支决定;`包含/长度/下标` 逐路径求值 | 轨迹是语法产物,不依赖 `env` 返回值 | -| **F3 字面结果** | 返回表达式只由字面量、参数、内联构造器组成时按结构求值 | 与 Lean 的 `mqResultOk` 形状一一对应 | -| **F4 命题** | `and/or/not`、`=/≠` 作用于 F2/F3 的布尔结果;外部返回值上的**布尔判定**(如 `access(回执,"ok") == False`)视为自由原子,可分叉 | 自由原子只做二分、不假设原子间关系;两条分支都关闭才 `checked`,因此证明是对任意 `env` 成立的 | -| **F5 单变量区间** | 原子 `x ⋈ c`(`c` 为整数字面量,`⋈ ∈ {<,≤,>,≥,=,≠}`);用路径条件 + 前提的上下界判定蕴含 | 单变量区间推理是线性整数算术的子集,`omega` 必然也能证 | - -明确**不**离线判定(直接 `unverified`,不猜):多变量线性组合、非线性算术、字符串比较、外部返回值的非布尔字段(`.value` 之类)、任何需要归纳的命题。 - -### 5.3 判定过程 - -1. 符号执行函数体:状态 `Var → SymVal`(`Const` / `Param` / `OpResult` / `Unknown`),路径条件为原子列表,轨迹为 `Op` 列表。 -2. 每个 `if` 分叉两支(条件 / 其否定);每个 `Op` 调用产生一个 `OpResult` 符号(值未知,但**出现**已知)。 -3. 每个 `return` 收集 `(路径条件, 结果 SymVal, 轨迹)`。 -4. 对每条路径检查 `前提 ∧ 路径条件 ⊢ 结论`:把 `结果/轨迹` 代入后按 F2–F5 求值或判定。 -5. 全部路径关闭 ⇒ 该定理 `checked`;任一原子超出片段 ⇒ `unverified`;某条路径可满足且结论为假 ⇒ `unproved` + 反例。 - -### 5.4 证书与"单调性" - -每条 `checked` 定理同时产出: - -- **情形证书**:`(路径 id, 路径条件, 规范化目标, 关闭理由 ∈ {literal, hypothesis, interval, atom})`,写进 `certificate.json`; -- **Lean 脚本**:`unfold run` 后按同一棵 `if` 树 `split_ifs`,每个叶子 `simp_all <;> omega`。离线情形树与 Lean 的 `if` 树来自同一份 IR,叶子一一对应;某个叶子离线关闭而 Lean 关不掉,就是 `proof.divergence`。 - -因此"离线判定 ⊂ Lean 判定"不是口头承诺,而是三件事: - -1. **构造上**:F5 的推理是 `omega` 的子集,F1–F4 是 `simp`/`decide` 的子集; -2. **运行期**:只要有 Lean,就在 ⑥ 复核;`checked` 但 Lean 未关闭 ⇒ `error[proof.divergence]`,退出 1,永不落绿; -3. **测试上**:语料库强制 `offline_checked ⊆ lean_proved`(roadmap 测试矩阵 A1)。 - -**不夸大**:我们不说"离线判定器已被证明正确"。我们说它片段极小、保守、每条结论都带 Lean 脚本,且有运行期复核与 CI 语料强制。 - -### 5.5 反例 - -当某条路径可满足、且结论在该路径上求值为假时,从区间端点取一组参数值作为见证: - -```text -反例: 金额 = 10001 -路径: 金额 > 10000 → 人工审核 -结论: 结果.ok = False -实际: 结果.ok = True(人工审核的返回值被包进 result.ok) -``` - -反例只承认**确定性否定**:结论必须是字面 `false`,路径必须由区间证明可满足,且路径条件里**不含自由布尔原子**(否则可能凑出真实语义下不存在的组合)。任何一条不满足就退回 `unproved`(无见证)或 `unverified`,不编故事。 - ---- - -## 6. Lean 编码 - -### 6.1 产物布局 - -```text -verification/skill-proof/ # 入仓:语义库 + 论文样例(人工评审) - lean-toolchain # 与 replay-policy 同钉(v4.35.0) - lakefile.lean - MarqdoProof.lean - MarqdoProof/{Basic,Result,Tactic}.lean - examples/{approval,false-claim}.lean - README.md # TCB 与"证了什么"的边界声明 - LIBRARY-SHA256 # 由构建脚本写入 - -.marqdo/prove/ # 生成物(.marqdo/ 已 gitignore) - pkg/ # 一次性 Lake 包(库副本 + Generated/) - <key>/plan.json module.lean certificate.json lean.log - index.json # key → 指纹/状态/耗时 -``` - -### 6.2 无公理:操作是参数,假设是前提 - -```lean --- 库提供(MarqdoProof/Basic.lean,节选) -inductive Val | none | int : Int → Val | str : String → Val | bool : Bool → Val - | list : List Val → Val | map : List (String × Val) → Val - -structure Err where code : String; message : String; operation : String -structure Result where ok : Bool; value : Val := .none; error : Option Err := none - --- lib/result 的真实构造器(ok/error/value_or)映射: -def Result.success (v : Val) : Result := { ok := true, value := v } -def Result.failure (e : Err) : Result := { ok := false, error := some e } -``` - -生成文件里**不出现 `axiom`,也不出现 `opaque`**:外部操作是 `Env := Op → Val` 参数,后置条件是定理的假设 `h_post`。于是 `#print axioms` 为空,定理陈述本身就把"信任了什么"写清楚。 - -### 6.3 直接风格降级(无 monad、无 `do`) - -`StateM`/`do` 在证明里要额外展开 monad 定律,早返回的语义也容易踩坑。改用**续延式直接风格**:`compile_stmts(stmts, k)` 在 Rust 里把后续语句当续延,早返回就是"把 `k` 换成函数出口"。产出的 Lean 是纯 `let`/`if`/`pair`,`simp`/`split`/`omega` 直接可用。 - -输入(`verification/skill-proof/examples/approval.mq.md` 节选): - -```markdown -## 审批 -+ `金额` - -| 参数 | 类型 | 说明 | -|---|---|---| -| 金额 | int | 申请金额(元) | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result | - -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | - -1. `金额` > 10000 - **审核 = [提交人工审核](人工审核(金额=`金额`))** - **结果 = [保留人工审核结论](result.ok(value=`审核`))** -2. * - **结果 = [自动通过](result.ok(value="auto"))** - -**结果** -``` - -输出: - -```lean -import MarqdoProof -open MarqdoProof - -namespace Generated.Approval - -structure Params where - 金额 : Int - deriving Repr, DecidableEq - -inductive Op where - | 人工审核 (金额 : Int) - deriving Repr, BEq - -def Op.name : Op → String - | .人工审核 _ => "人工审核" - -abbrev Env := Op → Val - -def run (env : Env) (p : Params) : Result × List Op := - if p.金额 > 10000 then - let v := env (.人工审核 p.金额) - (Result.success v, [.人工审核 p.金额]) - else - (Result.success (.str "auto"), []) - -theorem 大额必经人工 (env : Env) (p : Params) (h : p.金额 > 10000) : - (run env p).2.any (fun o => o.name == "人工审核") = true := by - unfold run - split_ifs <;> simp_all <;> omega - -end Generated.Approval -``` - -要点:每步带 `-- mq: line:col` 注释;中文标识符直接可用,含点/空格的用 `«…»`;命名冲突在生成前消解。 - -### 6.4 义务与定理 - -| 项 | 形状 | 来源 | -|---|---|---| -| 类型检查(T0) | 文件通过内核:字段、元数、分支同型 | Lean,编译结果即证据 | -| 终止(T1) | 无 `while`/递归 ⇒ Lean 接受为 `def` | 同上;需要 `partial` 的一律已跳过 | -| `effects_subset` | 实际 `Op` 集合 ⊆ `--effects` 授权 | Rust 判定,写证书 `obligations` | -| 作者定理(T2) | `∀ p, pre p → post p (run env p)` | 定理表 | -| 假设(T3) | `h_* : ∀ …, Post …` 作为定理前提 | 假设表 | - -违反 `effects_subset` 不是 `rejected` 而是 `error[proof.effects_exceeded]`:前者是"够不着",后者是"够得着且越权",必须区分。未给 `--effects` 时该义务记为 `skipped`,不假装通过。 - -### 6.5 策略 - -```lean -macro "mq_auto" : tactic => - `(tactic| first - | decide - | omega - | simp_all - | (split <;> simp_all) - | (split_ifs <;> simp_all <;> omega) - | aesop) -``` - -定理表 `策略` 列可写 `auto` / `omega` / `simp [run]` / 任意 tactic 片段;写 `none` 表示只生成不证(论文留人工证明钩子),状态记 `unverified` 而不是失败。 - -### 6.6 源码映射 - -每个语句前放 `-- mq: <line>:<col>`;`module.lean` 与 `plan.json` 同缓存。Lean 报 `Generated/X.lean:41:7: error: …` 时,驱动把 41 映射回 `.mq.md` 行,诊断指回源码,`lean_line` 放在 JSON 细节里。映射表进证书。 - ---- - -## 7. 作者面:定理表与语言习惯 - -### 7.1 语法与位置 - -表格构造**已有**(不新增核心标记),这里只给它一个新的**语义角色**: - -```markdown -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | -``` - -规则(与 `参数/返回/字段` 契约表同构): - -1. 表头别名:`定理/证明/claim/theorem`;列名 `结论/conclusion`、`前提/premise`(可缺省)、`策略/tactic`(可缺省)。 -2. 位置:函数体**首条可执行语句之前**,与契约表同一槽位;提取后从 body 移除,**不参与运行**。出现在别处仍是普通表,`check --proof` 报 `proof.claim_misplaced`。 -3. 一行一条;`定理` 列是函数内唯一 id,重复即 `proof.claim_duplicate`。 -4. 结论/前提是**受限表达式**:参数、`结果`、`轨迹`、`包含/contains`、`长度/length`、`下标/index`,以及算术/比较/布尔。其他名字 → `proof.claim_unknown_symbol`(带最近建议)。 -5. 一张表如果既像契约表(有 `类型` 列)又像定理表(有 `结论` 列)→ `proof.claim_ambiguous`,不猜。 - -### 7.2 语义 - -一条定理展开为: - -```lean -theorem <id> (env : Env) (p : Params) (h : <前提>[p]) : - <结论>[p, (run env p)] := by … -``` - -- 前提在**入口状态**求值(参数),结论可引用参数、`结果`、`轨迹`。 -- 没有前提就是全称命题;`结果.ok = True` 天然表示"所有成功终止都满足"。 -- `轨迹` 有序;`包含/长度/下标` 三个谓词够表达"存在/顺序/计数",不再长大。 -- 定理是**声明**,不是代码:没有求值顺序、没有副作用、不能调用任意函数。 - -### 7.3 语言习惯审查(是否引入了多余语义) - -这是这次设计最需要交代清楚的一节。逐条回答"会不会破坏语言习惯"。 - -#### 7.3.1 实际新增了什么 - -| 新增项 | 性质 | 是否影响运行 | -|---|---|---| -| `Function.claims` 元数据 | 声明(与 `Function.contract` 同类) | **否**,提取后从 body 移除 | -| 定理作用域的两个保留名(`结果/轨迹`)与三个谓词 | 只在定理内可见的绑定 | **否**,不在普通表达式作用域 | -| 假设表作用域的 `返回` | 只在假设表内可见的绑定 | **否** | -| `check --proof` | 静态校验开关,默认关 | 否 | - -除此之外没有新语法、没有新标记、没有新求值规则、没有新类型系统。 - -#### 7.3.2 没有新增什么(逐项对照) - -| 风险项 | 结论 | 依据 | -|---|---|---| -| 新核心标记? | 否 | 用的是既有 GFM 表(`core-surface.md` 的 `table`);`CORE_CONSTRUCTS` 计数不变 | -| 新求值顺序/作用域? | 否 | 定理表与契约表一样,在解析期提取,不进 AST body | -| 新调用约定/形参? | 否 | 不要求调用者传证明参数,不给函数加隐藏形参 | -| 新类型系统(refinement/依赖类型)? | 否 | 只在表里写命题;不做类型层扩展 | -| 影响叙述比例/可读性? | 否 | 表是 code 构造;GitHub 渲染正常;`labels`/`narrative_ratio` 行为不变 | -| 影响 `check` 既有诊断? | 否 | 新表头不命中 `参数/返回/字段`,`parse_contract_table` 不认领;新增校验默认关 | - -#### 7.3.3 为什么不是别的写法 - -| 备选 | 为什么不用 | -|---|---| -| frontmatter `proof:` 块 | 丢函数作用域与行级锚点;一个函数一条定理时锚点落在文件头,诊断无法指回具体行;多函数文件无法分派 | -| `# 证明` 标题 | `#` 是对象、`##` 是函数,标题即单元——新增"标题=命题"会破坏"标题即可调用单元"这条既有习惯,且会进命名空间 | -| 围栏块(` ```proof ` 语言标签) | 代码围栏必须跟在空赋值后(`x =` + fence),否则解析器直接报错;为了写定理先造一个死变量,比表更别扭,且该值会被当作可执行值 | -| 注释里写定理(`<!-- -->`) | 注释不参与语义,也拿不到行锚点;工具无法可靠区分"说明"与"定理" | -| 单独 `.proof.md` 旁挂文件 | 真理被拆成两份,正是这个项目一直在避免的事("代码与文档同一份") | -| 类型即契约(refinement) | 语义增量太大,且现有契约表已经承担类型声明;再来一套会形成"两份作者真相" | - -函数级表格是最符合本项目习惯的:**声明与函数同址、可定位、可校验、不可执行**——这正是 `参数/返回/字段` 表已经建立的模式。 - -#### 7.3.4 命名冲突与遮蔽 - -- 定理作用域里 `结果`/`轨迹`、假设作用域里 `返回` 是保留名。若函数有形参或局部变量同名,`check --proof` 报 `proof.name_shadow`(错误),要求改名——**不**做隐式优先,避免"同名不同义"。 -- 谓词名 `包含/长度/下标` 若与用户函数同名,同样报 `proof.name_shadow`,不做静默覆盖。 - -#### 7.3.5 仍然存在的风险与护栏 - -| 风险 | 说明 | 护栏 | -|---|---|---| -| "定理像代码"的错觉 | 作者可能以为 `结果.ok = False` 会在运行时求值 | 文档措辞统一为"声明";`view` 渲染成定理卡片;`check` 提示不可运行位置 | -| 定理表长出第二门语言 | 有人想写量词、自定义谓词、调用函数 | 谓词集合封闭(3 个);超出即 `proof.claim_unsupported`;ADR 改集合需重新评审 | -| 定理与代码漂移 | 改了分支但没改定理 | 定理锚定行号;`check --proof` 校验引用的变量仍存在;`prove` 每次重证 | -| 定理变成装饰 | 写了 `策略 none` 或永远 `unverified` | `audit` 统计"声明/已判定/未判定";证书只记录实际判定结果 | -| 表被误当数据表 | 普通文档表恰好叫 `定理` | 只有表头命中且列形正确才认领;两列的"定理/说明"表仍是普通表 | - -结论:**语义增量被压到三条声明级绑定,且不进入运行时**。它没有引入新的编程习惯,只是把"契约表"这一既有习惯扩展到"命题"。 - -### 7.4 假设表(T3) - -外部操作默认完全未知。要让"只要银行返回失败,我们就不会记账"这类推理成立,把假设写成表: - -```markdown -| 假设 | 前置 | 后置 | -|---|---|---| -| 银行.转账 | 金额 > 0 | 返回.ok = True | -``` - -- 表头 `假设/assumption`;`操作` 列是调用显示名(`库.成员`)。 -- 前置在实参上求值;后置在 `返回`(操作返回值)上求值;支持 `=/≠/包含/长度` 与 `返回.ok`(映射字段读取的语法糖)。 -- 生成 Lean 时不是公理,而是**定理前提**:`h_转账 : ∀ a, a > 0 → (env (.转账 a)).field? "ok" = some (.bool true)`。 -- 无法定型的后置 → `proof.assumption_untyped`(提示改成等式或补返回契约)。 -- `audit` 与证书 `assumptions` 一一对应。 - -### 7.5 与 `check` / `view` / `catalog` - -- `check`:新增 `--proof`(**默认关**,保持既有性能),校验表形、名字、片段;不跑 Lean。 -- `view`:定理表渲染成"已声明定理"卡片;有证书时附状态徽标(`proved`/`checked`/`unverified`)。不触发证明。 -- `catalog`/`knowledge`:`Artifact` 增可选 `proof:` 摘要(证书哈希 + 状态 + 定理数),供 EKM 与 `reuse` 过滤;不改变现有 schema 必填项。 - ---- - -## 8. 工程落点 - -### 8.1 新增 / 修改文件 - -| 文件 | 变更 | -|---|---| -| `src/prove/mod.rs` | API、状态机、报告聚合 | -| `src/prove/ir.rs` | Plan IR + 规范化 JSON + 指纹 | -| `src/prove/lower.rs` | AST → IR、子集验收、拒绝码、内联 | -| `src/prove/types.rs` | 类型推断与合一 | -| `src/prove/emit.rs` | IR → Lean(确定性、命名消解、span 注释、脚本生成) | -| `src/prove/offline.rs` | 符号执行、F1–F5 判定、反例 | -| `src/prove/driver.rs` | 工具链探测、Lake 包、`lean` 调用、超时、诊断映射 | -| `src/prove/cache.rs` | 证书、`index.json`、失效判定 | -| `src/prove/report.rs` | 文本 / `--json` 渲染 | -| `src/ast.rs` | `Function.claims: Vec<Claim>` | -| `src/claim.rs`(或并入 `contract.rs`) | 定理表提取与校验 | -| `src/parse/mod.rs` | 定理表提取入口(首条可执行语句前) | -| `src/check.rs` | `--proof` | -| `src/main.rs` | `Commands::Prove`、`ProveAction`、json_errors | -| `src/lib.rs` | `pub mod prove;` | -| `verification/skill-proof/**` | Lean 库、样例、`LIBRARY-SHA256`、README | -| `tests/prove.rs` + `tests/prove/**` + `tests/prove_lean.rs` | 集成测试、夹具、Lean 语料(独立目标) | -| `.github/workflows/proof.yml` | elan + `lake build` + 语料门禁 | - -不新增 crate 依赖(`serde_json`、`sha2`、`anyhow` 已在);Lean 侧零依赖(只用 Std)。 - -### 8.2 API - -```rust -pub struct ProveOptions { - pub entry: Option<String>, - pub only: Vec<String>, - pub allow_opaque: Vec<String>, - pub emit_dir: Option<PathBuf>, - pub effects: Option<String>, - pub strict_types: bool, - pub offline: bool, - pub timeout: Duration, - pub heartbeat: u64, - pub require_lean: bool, - pub report_only: bool, - pub no_cache: bool, - pub lean: Option<PathBuf>, - pub library: Option<PathBuf>, -} - -pub enum Verdict { Proved, Checked, Unverified, Unproved, Rejected, Error } - -pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report>; -pub fn emit_path(path: &Path, out: &Path) -> Result<EmitReport>; // 不判定 -pub fn audit_path(path: &Path) -> Result<AuditReport>; // 不判定 -``` - -`main.rs` 只做参数搬运与退出码映射(与 `Commands::Verify` 同风格)。 - -### 8.3 缓存与证书 - -缓存键:`sha256(源码 ⊕ plan.json ⊕ schema ⊕ 库 sha256 ⊕ lean --version ⊕ marqdo 版本)`。证书: - -```jsonc -{ - "schema": 1, - "key": "…", - "status": "proved", - "tier": "lean", - "source": {"path": "skills/…", "sha256": "…", "artifact_id": "mq://…"}, - "lean": {"toolchain": "…", "library_sha256": "…", "module_sha256": "…", "axioms": []}, - "claims": [{"id": "…", "status": "proved", "decided_by": "omega"}], - "offline": {"claims": [{"id": "…", "status": "checked", "cases": 3}]}, - "obligations": [{"id": "effects_subset", "status": "passed"}], - "assumptions": ["银行.转账: 前置 金额 > 0;后置 返回.ok = True"], - "span_map": {"41": "21:1"}, - "created": "2026-11-13T09:00:00Z", - "marqdo": "2.8.0" -} -``` - -- 命中即跳过判定(报告标 `cache: hit`)。 -- 源文件、库、工具链任一变化即失效;暂不做部分重证。 -- 证书是**复核收据**,不是发布许可:推荐附在发布说明里,不强制。 -- `prove clean` 删 `.marqdo/prove`(`--emit` 目录不动)。 - -### 8.4 工具链与库发现 - -1. `--lean`/`--lake`;2. `MARQDO_PROOF_LEAN`/`MARQDO_PROOF_LAKE`;3. `PATH` 上的 `lake`,再 `lean`;4. 都没有 → 只跑离线,`lean: null`。 - -显式给出(flag 或环境变量)但路径不存在/不可执行 → `error[proof.lean_missing]`,**不**回退到离线:避免"我以为在跑 Lean,其实没有"。 - -库发现:`--library` → `MARQDO_PROOF_LIB` → 仓库内 `verification/skill-proof` → 安装根 `share/marqdo/proof/` → 相邻 `marqdo-proof/`。首次使用按 `LIBRARY-SHA256` 复制进 `.marqdo/prove/pkg` 并 `lake build` 一次(缓存);库哈希进证书。 - -### 8.5 环境变量 - -| 变量 | 作用 | -|---|---| -| `MARQDO_PROOF_LEAN` / `MARQDO_PROOF_LAKE` | 工具链路径 | -| `MARQDO_PROOF_LIB` | 语义库目录 | -| `MARQDO_PROOF_TIMEOUT` | 默认超时(秒) | -| `MARQDO_PROOF_CACHE` | 缓存根(默认 `.marqdo/prove`) | -| `MARQDO_PROOF_NO_CACHE` | 等价 `--no-cache` | -| `MARQDO_PROOF_REQUIRE_LEAN` | 等价 `--require-lean`(CI/测试用) | - ---- - -## 9. 测试与证据(摘要) - -完整矩阵见 [roadmap/prove.md](../roadmap/prove.md) §6。四类必须守住的证据: - -1. **单调性**(用户硬要求):语料库里每条离线 `checked` 的定理,Lean 都必须证出来;任何分歧 → `error[proof.divergence]`。 -2. **不执行**:带 `fs.write`/`exec` 的夹具在 `prove` 后不产生任何副作用。 -3. **确定性**:同输入两次运行,`module.lean` / `plan.json` / 证书键全等。 -4. **诚实性文案**:`checked` 与 `proved` 在文本、JSON、证书三处措辞一致,不允许出现"已验证"字样描述离线结果。 - ---- - -## 10. 已定事项 - -| # | 事项 | 结论 | 备注 | -|---|---|---|---| -| 1 | 命令名 | `marqdo prove` | 别名 `lean` | -| 2 | 是否强制 | **不强制**;规范与手册推荐 | 无 `--require-lean` 时缺工具链不失败 | -| 3 | 离线能否给结论 | 能,但只到 `checked` | 严格弱于 Lean(§5) | -| 4 | 定理写法 | 函数级 `定理` 表 | [ADR 0010](../adr/0010-skill-proof-boundary.md) | -| 5 | `check --proof` | 加,默认关 | | -| 6 | 首版 `foreach` | 不做,P3 再加 | 之前 `proof.foreach_pending` | -| 7 | 状态词 | `proved` / `checked` / `unverified` / `unproved` / `rejected` | 只有 `proved` 能说"已证明" | - -遗留(不阻塞开工,P2 前定):`假设` 表是否也认领 `前置/后置` 之外的列(如 `来源`);`--all` 的聚合粒度(按文件还是按函数);证书是否需要签名。 - ---- - -## 11. 文档与发布清单 - -- [ ] 本文件转 `Implemented`(分阶段勾) -- [ ] `doc/roadmap/prove.md`:里程碑、周计划、测试矩阵 -- [ ] `doc/adr/0010-skill-proof-boundary.md`:定理表角色 + 子集边界 + 顾问式定位 -- [ ] `doc/design/skill-proof-theory.md`:语义映射、定理形态、TCB 表 -- [ ] `verification/skill-proof/README.md`:构建、身份哈希、与 replay-policy 的关系 -- [ ] `README.md`:CLI 三行示例 + 状态表 + "推荐但不强制" -- [ ] `doc/tutorial/13-命令行工具.md`:先 `emit`,再 `prove` -- [ ] `skills/marqdo-dev/index.mq.md`:新增 `prove` 任务(推荐在发布前跑) -- [ ] `skills/marqdo/reference.md`:定理表语法速查 -- [ ] `CHANGELOG.md`:2.8.0;「核心表面 Δ:无(表格新增语义角色:定理)」 -- [ ] `.github/workflows/proof.yml`;`.gitignore` 已含 `.marqdo/` -- [ ] 发版手册:推荐附证书哈希,不设为硬门禁 - ---- - -## 12. 实现状态与偏差记录(P0/P1 落地时修订) - -| 状态 | 内容 | -|---|---| -| **P0 已落地** | `src/prove/`:`ir.rs`(Plan IR + 稳定 JSON)、`lower.rs`(子集验收/内联/不透明化/效应标签)、`types.rs`(字面量推断 + 分支合流 + `proof.type_mismatch`)、`emit.rs`(确定性 Lean 生成)、`mod.rs`(Report/Verdict/ProveOptions + `prove/emit/audit/clean`)。测试:`tests/prove.rs` 12 例 + 模块单元测试,全部不依赖 Lean。 | -| **P1(Rust 侧)已落地** | 定理表提取(`ast::Function.claims` + `contract::parse_claim_table`,首条可执行语句之前,提取后移出 body);`check --proof`(默认关):`proof.claim_malformed` / `claim_ambiguous` / `claim_misplaced` / `claim_duplicate` / `claim_unknown_symbol` / `claim_unsupported` / `name_shadow`;定理脚手架生成(受限文法 → Lean `theorem` 陈述 + §7.2 策略脚本)。Lean 判定(lake/driver/cache/CI)按 roadmap P1 第 2 周继续。 | - -### 与本文前面章节的偏差(以本表为准) - -1. **`result.ok/error/value_or`,不是 `result.success/failure`**:设计起草时假设的库名与 `lib/result.mq.md` 真实 API 不一致,实现以真实库为准(§4.5/§6.2 示例已同步修正)。Lean 侧库提供 `Result.success/failure` 作为映射目标。 -2. **P0/P1 的 `run` 返回 `Val × List Op`**:`result.ok(...)` 内联为 Val 字面映射构造(`mqResultOk`),而非单独的 `Result` 结构。P2 起按返回契约提升为类型化 `structure Params`/`Result`(§6.2 的形态),届时定理表可直接做字段级推理。 -3. **Op 构造器带元数**:`inductive Op` 的每个构造器按首现实参个数声明 `参数1..参数N : Val`(§6.2 示例省略了这一点)。 -4. **`--allow-opaque` 的效应标签恒为 `opaque`**:即便函数声明了契约效应也不沿用——行为完全未知时引用其声明只会误导 `audit` 读者(§2.2)。 - -### 审查修复(同日代码审查发现,均有回归测试) - -| 缺陷 | 后果 | 修复 | -|---|---|---| -| 表格单元格里的调用被静默丢弃 | 含副作用调用的函数在 Lean 里伪装成"无操作"——违反诚实性契约 | `lower_expr` 回退分支检测容器内的调用 → `proof.unsupported` 拒绝整个函数 | -| 同名不同元数的调用点共享一个 Op | 构造器按首现声明元数,另一调用点生成非法 Lean(无法编译) | `register_op` 对不同元数加 `/N` 后缀,各自独立声明(轨迹名诚实区分) | -| `name_shadow` 每层遍历重复报告 | 模块有 N 个函数就报 N 次,噪声淹没真实问题 | 谓词名检查只跑一次(模块级事实);形参检查只看自带定理表的函数 | -| `长度(轨迹) = 2` 生成 `mqEq (Nat) (Val)` | Nat 与 Val 类型不匹配,Lean 无法编译 | Nat 语境检测:轨迹长度与整数字面量的比较走原生 Nat 运算;不可译形状 → 注释占位 | - -另有防护加固:`lean_ident` 保留 `轨迹₀`/`h_前提`(定理 binder 撞名防御);emit 对重复定理 id 去重(`check --proof` 未跑时也不产出重复声明)。 - -### 审查时的业务级验证(/tmp/biz,电商大额订单审批流) - -- `审批.mq.md`(审批单 + 人工审核)+ `风控.mq.md`(风险分级)+ `lib/工单.mq.md`(建单):三条定理(大额必经人工 / 恰两步轨迹 / 必有回执)提取成功 -- 真实解释器三场景交叉验证:5000 元 → `auto`(1 步轨迹);20000/60000 元 → 人工建单 `T-20000`/`T-60000`(`需人工 → 创建` 恰两步)——与定理表逐条吻合 -- 负例:破坏定理表(未知符号 + 重复 id + 谓词元数错)→ `check --proof` 各报一码且默认关静默;emit 仍 advisory 可用;双次 emit 字节一致 - -### Lean 环境实装与真机证明(2026-11-16,Lean 4.35.0 / lake 5.0.0) - -工具链:`lean-4.35.0-linux.tar.zst` 解包至 `target/toolchain/lean-4.35.0-linux/`(无 elan, -直接 PATH);语义底座 `MarqdoProof`(`Val` + `mq*` 辅助 + 矛盾引理,无 `axiom`/`opaque`) -经 lake 构建于 `target/proof/skill-proof/`(库源同步在 `doc/verification/skill-proof/`, -发布时装入 `verification/skill-proof/`——checkout 中该目录属 root)。 - -实测发现并修正的发射器缺陷(均有测试覆盖): - -| 缺陷 | Lean 行为 | 修复 | -|---|---|---| -| `namespace Generated.审批_mq` | `namespace` 命令只接受 ASCII 名(`namespace 审批` 直接语法错误) | 非 ASCII 字符确定性编码 `uXXXX`:`Generated.u5BA1u6279_mq` | -| 裸中文标识符 `def 审批单`、`(h_前提 : …)`、`v_结果` | Lean 标识符仅 ASCII,全部语法错误 | 非 ASCII 一律 guillemet `«…»`;改名形式走同一编码(`v_u7ED3u679C`) | -| Op 构造器 `«调用:人工审核»` | guillemet 记号内 `:` 截断记号 | 标识符内 `:` → `_`;`Op.name` 字符串显示保持原 id | -| 多参构造器模式 `.«调用:x» =>` | 模式未绑定实参,类型不匹配 | `Op.name` 臂补 `_ _` | -| 占位构造器裸中文 `无操作` | 语法错误 | 占位构造器也走 `op_ctor` | -| `h_run : … = (结果, 轨迹)` 反向等式 | simp_all 不做反向替换,输出值进不了目标 | 定理陈述翻转:`((结果, 轨迹) = run env [] …)` | -| 分支互斥假设(`mqGt=true ∧ mqLe=true`) | simp_all 不链式应用蕴含引理 | 库中矛盾引理 + 脚本显式 `.elim`(`exact (mqGt_mqLe_false ‹…› ‹…›).elim`) | -| 无分支函数上 `split at h_run` | 硬报错(无 if/match 可拆),挡住本可证明的平凡断言 | `try split at h_run` | - -驱动脚本 `target/proof/run-lean-check.sh`(P1 第 2 周 `--require-lean` 集成雏形): -prove 生成 → `lake env lean` → `proved / unproved / lean-error` 三态分类。 - -真机证明结果: - -| 目标 | 结果 | -|---|---| -| 业务样例 `审批.mq.md`(3 定理:大额必经人工 / 恰两步轨迹 / 必有回执) | `lake env lean` 0 error,全部 **proved** | -| 6 个带定理的测试夹具 + 业务样例 | **7/7 全部 proved**(`p2_len` 夹具的断言已修正:纯函数轨迹恒空,`长度(轨迹) = 2` 是作者笔误,改为 `长度(轨迹) = 0`——Nat 比较路径覆盖不变) | -| 全量 Rust 测试 | 499 通过;仅剩 2 个已记录的环境受限失败(python3 缺失 / playwright root 属主),与 prove 改动无关 | - -诚实性核对(首轮实测发现后修正):`p2_len` 曾因断言写错(纯函数却断言两步轨迹) -被 Lean 如实拒绝——生成侧把语义为假的断言原样交给 Lean、判定侧不虚报 proved, -正是"绝不 lean 无法证明的 marqdo 可以证明"的落实;修复方向是改对断言,不是放宽判定。 - -生成文件头部带 `set_option linter.unusedVariables false` / -`set_option linter.unusedSimpArgs false`:机器生成产物不应被人写代码的 linter -刷屏( simp 参数是固定词汇表,个别文件用不到属正常)。 - -### P1 Lean 判定落地(2026-11-17,commit 见 git log) - -新增 `src/prove/driver.rs` + `src/prove/cache.rs`,判定接进 `prove` 默认动作: - -| 组件 | 实现 | 与设计的偏差 | -|---|---|---| -| 工具链发现(§8.4) | `--lean` → `MARQDO_PROOF_LEAN` → `PATH`;显式给路径但不可执行 → `error[proof.lean_missing]` **不回退**;都找不到 → 状态保持 `unverified`(`--require-lean` 时退 2) | 一致 | -| 底座构建 | `MarqdoProof.lean` **内嵌**进 marqdo 二进制(`include_str!`),按内容 sha256 前 8 位落盘缓存,`lean -o MarqdoProof.olean` 直接构建 + `LEAN_PATH` 指给被检模块 | **不经 lake**:运行时只依赖 `lean` 一个二进制(无 elan/lake 也判定);lakefile 保留给人/CI 用。`scripts/check-proof-library.sh` 校验内嵌源与 `doc/verification/skill-proof/` 逐字节一致并输出库 sha256 | -| 判定调用 | `lean <模块>` + 超时(默认 120s,`--timeout`;try_wait 轮询,超时杀进程判 `error`);`--heartbeats` 透传 `-DmaxHeartbeats` | 一致 | -| 结果解析 | `unsolved goals` → `unproved`;其它 `error` → `error`;干净编译 → `proved`;`sorry`(策略 `none`)→ `unverified` | 一致(§4.4 E4) | -| 证据映射 | 生成文件 `-- mq: LINE:COL` + 定理头 `-- 定理 <id>(策略 …;mq: N)` → 证书 `span_map`;unproved 定理的诊断指回定理表行,附 Lean 原始目标上下文 | 一致(§8.5) | -| 证书缓存(§8.3) | 键 = sha256(源码 ⊕ plan ⊕ 库 sha256 ⊕ lean 版本 ⊕ marqdo 版本);命中 → 跳过判定,`lean.cache: "hit"`;`--no-cache` / `MARQDO_PROOF_NO_CACHE` 绕过 | plan.json schema 即结构化 plan(无独立 schema 文件) | -| 状态/退出码(§3.3) | E1 假定理 unproved 退 1;F2 `--report-only` 恒 0 不判定;F3 `--require-lean` 无工具链退 2;`prove emit` 子命令只生成不判定 | 一致 | - -**实测抓出的判定层缺陷**(均有回归测试,tests/prove_lean.rs + driver 单元测试): - -| 缺陷 | 后果 | 修复 | -|---|---|---| -| 错误头 `<file>:47:62: error` 解析取了**列号** 62 | unsolved 目标错配到下一个定理(相邻 61–76 区间),甲定理的失败记到乙定理头上 | 取倒数第二个数字段为行号 | -| 干净编译时 driver 不产出逐定理记录 | 所有定理停留在 `unverified`,证书 `claims: []` | 无错定理一律补 `proved`(或 sorry → `unverified`) | -| 函数全名含点(`台账.记录.记过即记`)按第一个点切分 | claim id 拼错(`记录.记过即记`),匹配不上报告 | 从定理头注释直接取 claim id,函数名 = 定理名剥掉 claim 后缀 | -| 无定理函数把文件状态拖成 unverified | 没有义务的函数(纯编排胶水)使整体永远到不了 proved | 文件状态只聚合**有定理**与**被拒绝**的函数;无定理函数自身行仍如实 `unverified` | -| 测试夹具 `长度(轨迹) = 0` 断言写错(函数体有一次调用) | Lean 如实拒绝——生成侧诚实、判定侧不虚报 | 修正夹具断言为 `= 1`(不是放宽判定) | - -测试矩阵(`tests/prove_lean.rs`,独立测试目标,`required-features = ["cli"]`): -A1 真定理 proved · E1 假定理 unproved 退 1 · E4 策略 none → unverified 退 0 · -F2 report-only 恒 0 · F3 require-lean 无工具链退 2 · F4 emit 子命令不判定 · -G1 假 lean 计数器证"命中跳判定"(含 `--no-cache` 复判) · G2 真证书命中 · -G2b `--no-cache` 强制 miss。无工具链时自动 SKIP,`MARQDO_PROOF_REQUIRE_LEAN=1` -(CI)则缺失即失败。 - -CI:`.github/workflows/proof.yml` —— 装 Lean 4.35.0 → 底座校验 → -`MARQDO_PROOF_REQUIRE_LEAN=1` 跑判定矩阵(CI 不许静默降级)→ prove 主套件。 - -### P2 离线判定落地(2026-11-17) - -新增 `src/prove/offline.rs`(片段 F1–F5 的符号执行)+ `tests/prove_corpus.rs` -(40 夹具单调性语料库): - -| 组件 | 实现 | -|---|---| -| 符号执行(§5.3) | 状态 `Var → SymVal`(Const/Struct/OpResult/Param/Unknown);If 逐分支克隆状态并**接续 If 之后的语句**(Return 常在外层);每个 Return 收集 (路径条件, 结果, 轨迹, 变量快照) | -| 可行性 | 前提区间 ∩ 路径条件为空 → 路径不可行,空真关闭(Lean 侧对应假设矛盾,simp 可消) | -| F2 轨迹 | 包含/长度逐路径求值(Op.name 显示名与 Lean 一致) | -| F3 字面 | `result.ok/error/value_or` 结构求值(与 mqResultOk/mqError/mqValueOr 语义一致) | -| F4 自由原子 | 外部返回值布尔判定只二分;路径条件里出现同键原子才可关闭(hypothesis);反例路径含自由原子 → 保守放弃见证 | -| F5 区间 | **收紧后的诚实范围**:字面重述(同原子)→ hypothesis 关闭;区间违反 → 确定性否定 + 区间端点见证(反例);区间**蕴含**(10000 ⊢ 9999)数学上真,但当前 Lean 脚本无 Val 比较传递引理,simp+omega 关不掉——离线同样保守 unverified(等库补引理再放开),否则必触发 divergence | -| 状态 | 离线 closed → `checked`(decided_by=trace,**不是 proved**);反例 → `unproved` + `proof.claim_failed` 诊断(指回定理表行 + 见证如 `金额 = 10001`) | -| 单调性护栏(§5.4) | 有 Lean 时逐定理复核:离线 checked 但 Lean unproved,或离线反例被 Lean 证出 → `error[proof.divergence]` 退 1,永不落绿;`MARQDO_PROOF_INJECT_DIVERGENCE=1` 测试注入验证护栏咬人 | -| 语料库 | `tests/prove/fixtures/` 8 类 × 5 = 40 夹具(literal/trace/interval/free-bool/branches/composition/counterexample/beyond);`corpus_monotonicity_offline_subset_of_lean` 强制 offline ⊆ lean;`corpus_offline_never_claims_proved` 无 Lean 时禁 proved | - -**实测抓出并修复的缺陷**(均有测试): - -| 缺陷 | 修复 | -|---|---| -| If 分支后丢弃剩余步骤(Return 在 If 外层的常见编排全部丢结果) | 两支克隆状态并接续后续语句 | -| `negated` 字段与 op 翻转双重否定,取反原子被收集函数丢弃 | 移除字段,否定一律折进 op/expected | -| 嵌套分支(else 里再嵌 if)Lean 只拆一层 | `try split at h_run` 按最大 if 深度重复发射 | -| simp 清单缺 `mqResultError`/`mqValueOr`/`mqAnd/mqOr/mqNot` | 全部补入(l2/l5/f1 由分歧护栏暴露) | - -**已记录的文法限制**:分支条件尚不支持字段访问(`access(审核, "ok")` 作条件 -解析失败)——F4 的"路径条件含自由原子"场景目前由单元测试覆盖,语料库中以 -分支后的结构化结论代替;文法放开后 prove 侧无需改动(offline.cond_atom 已支持)。 - -### P3 组合与产品化(2026-11-17) - -| 任务 | 状态 | 实现 | -|---|---|---| -| `--all` 目录模式 + `--max-files` | ✅ | 递归收集(跳过 target/dist/node_modules/.git/.marqdo,上限 200);目录不带 --all → 拒绝;聚合 JSON `{"kind":"prove-all","status":…,"files":[…]}`;整体状态差者胜(A6 测试:假 lean 分歧在目录模式同样触发护栏、整体退 1) | -| 差分一致性 T4(B 组) | ✅ | `tests/conformance.rs`:5 个纯函数语料(算术/中文标识符/分支比较/字符串拼接/i64 边界)解释器求值 == Lean `example … = Val.… := by simp`;B4 result.ok 结构字段读取两侧一致。B2(除零/模零)保持已记录偏差:解释器为运行时错误,P1 库模型返回 `.int 0`(MarqdoProof.lean 注释) | -| 调试注入 `--fault-inject offline-claim` | ✅ | 等价于 `MARQDO_PROOF_INJECT_DIVERGENCE=1`(A3 分歧护栏验证入口) | -| 跨函数组合 | 部分 | 同模块直线纯函数**内联**(≤24 语句、无分支、effect=pure)已落地;跨模块调用=不透明操作(效应未知,护栏兜底);**assume-guarantee 后置条件复用 → 2.9**(依赖假设表 T3) | -| `foreach` | 延期 | 维持 `proof.foreach_pending` 拒绝;有限列表 fold 编码需要库级归纳引理,冒进会先于 Lean 关闭路径、破坏单调性护栏可信度(§12.4) | -| 文档 | ✅ | 教程 §13.8(prove 章节)、skills/marqdo/reference.md(定理表)、本设计文档状态行、roadmap 落地记录;README/CHANGELOG/doc/releases 因仓库权限(root 属主)待人工合入,内容已在 §12.5 | - -#### §12.4 延期理由(2.9) - -1. **foreach**:可证子集刻意无循环(返回路径有限性是反例枚举与 Lean 分支 - 拆解的共同根基)。fold 编码需 `List.length` 归纳引理入 MarqdoProof.lean, - 且离线判定器需要"有限列表"的证据语法——两件事都没有通过 40 夹具语料库 - 的单调性验证,不该在发布版里冒险。 -2. **跨模块 assume-guarantee**:需要假设表(T3)承载被调者后置条件,并把 - 假设作为 `hypothesis` 关闭理由暴露给证书。当前跨模块调用是不透明操作, - 诚实且护栏可兜底;半吊子假设复用会制造"看起来证了其实靠假设"的绿灯。 -3. **分支条件字段访问**(`access(审核, "ok")` 作条件):解析器文法限制, - prove 侧已就绪(offline cond_atom 支持任意键),放开即生效。 - -#### §12.5 待仓库权限合入的内容(已于 2026-11-18 合入) - -`CHANGELOG.md`(v2.8.0 条目)、`README.md`(版本行 + 愿景第 6 条)、 -`doc/releases/v2.8.0.md`(双语发版说明)、`skills/marqdo-dev/index.mq.md` -(`prove` 任务)——权限放开后已全部合入原文,见各自文件。 diff --git a/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md b/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md deleted file mode 100755 index 2e96f38..0000000 --- a/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md +++ /dev/null @@ -1,435 +0,0 @@ -# qdagent 知识工作台所需的多模型运行与 View 嵌入支持 - -日期:2026-10-25。状态:Partial / in progress(M00–M06 合同门禁 + F02 agent.step/resume 假模型 e2e + USTC live selection smoke + DocumentView 浏览器只读核对已落地;F 矩阵未全绿,不得整文宣称 Verified;原生非兼容适配器仍 unavailable)。 - -源码基线:Marqdo `dc853fb`(2.1.2),qdagent `643dd31`,已同步远端。应用侧配套:[qdagent 多提供商与知识工作台](../../../qdagent/doc/design/multi-provider-and-knowledge-workbench-2026-10-25.md)。跨仓相对链接以兄弟仓库工作区布局为准。 - -沿用 [文档原生开发指导](document-native-development-guide.md)、[可执行知识规范](../next/Marqdo_Executable_Knowledge_Development.md) 与 [View 阅读体验设计](view-knowledge-reading-experience-2026-10-24.md)。本规格补充嵌入、调用身份和运行观测,不另造语言或第二套知识真相。 - -## 1. 框架目标与责任边界 - -让任何宿主应用可以按请求构造模型、追踪所有真实模型调用、以只读 View 展示知识文档,并从引用定位到版本一致的知识与来源。qdagent 的设置页、模型目录持久化、账单展示、会话导航、工作区授权和画像管理由应用实现。 - -| 能力 | Marqdo 拥有 | qdagent 拥有 | -|---|---|---| -| 多提供商 | 协议适配、模型 handle、能力协商、调用参数、归一化错误 | 提供商账户/端点/模型 CRUD、默认选择、凭证管理 | -| 模型路由 | Runtime 执行显式选择和允许的辅助模型策略 | 用户选择、工作区模型允许列表、路由授权 | -| 用量 | 每次请求/重试的身份、usage 来源与完整性、子任务传播 | 持久化账本、价格版本、费用估算、筛选/导出/预算策略 | -| 实时运行 | 逐事件输出、取消传播、背压、终态 | HTTP 会话鉴权、轮次映射、持久化事件重放、断线 UX | -| View | 文档语义、正文/目录/步骤、纯读取、稳定定位、可嵌入输出 | 容器/主题/深链/阅读历史/产品操作 | -| 知识引用 | 解析/歧义/版本/来源定位、验证多维事实 | 消息引用标识、授权、历史资料保存与入口 | -| 工作区 | 按显式 project 编译/查询,缓存及输出隔离 | 工作区 registry、root 解析、用户权限、文件管理 | -| 画像与笔记 | 通用文档渲染、来源关联、验证/编译原语 | 内容策略、提案/确认、生命周期、展示和上下文选择 | - -不在语言核心添加 provider/workspace/profile 关键字;沿用 `.mq.md` 函数、结构化参数、扩展插件和 MLSP。不得让“可读”取决于用户手填 hash、node id、source span 等机器字段。 - -## 2. 2.1.2 已完成的基础与剩余缺口 - -### 2.1 当前可复用基础 - -| 源码 | 已有内容 | 本规格的增量 | -|---|---|---| -| [ext/ai/llm](../../ext/ai/llm.mq.md) | `create(model,base_url,api_key,backend,name)`、命名 handle、ask/stream | 无需重做基础 handle;增加隔离策略、协议能力、完整消息与调用身份 | -| [LLM plugin](../../plugins/llm/src/lib.rs) | 兼容 chat completions HTTP、SSE 文本读取、非流 usage 三项 | SSE usage/异常终态/每次调用观测、可取消持续输出 | -| [Agent](../../ext/ai/agent.mq.md) | Agent 唯一 loop、router_model、EFI、绑定/发布门闩 | 主/路由/修复/生成工作簿的模型及计量上下文传播 | -| [语义 IR](../../src/sema/ir.rs) | Artifact、KnowledgeStep、KnowledgeRef、SourceLocation、BoundCall | View 面向阅读的完整投影及 ID/版本映射 | -| [MLSP](../../src/mlsp.rs) | `artifact.inspect`、`link.resolve`、verify/bind/execute、document.extract | 只读 document/引用解析及 capabilities 版本握手 | -| [KnowledgePresentation](../../src/view/knowledge_present.rs) | schema v1,artifact nodes、依赖、generation/page token | 保留兼容,新增正文/目录/refs/source spans/结构化诊断 | -| [View output](../../src/view/output.rs) | `--no-exec` 在构建前跳过 capture | 将纯读取能力暴露给嵌入客户端,不复用会执行的 live 默认路径 | -| [document extract](../../src/document_extract.rs) | TXT/MD,partial,PDF/DOCX/OCR 显式不支持 | 能力查询及稳定来源定位;不要求本阶段重造 OCR | -| [数据资源](../../ext/data/db.mq.md) | SQLite migrate/exec/事务、唯一/索引声明 | 应用可直接承载 registry/账本/索引;不需另加产品专用数据库框架 | - -2.1.2 已把知识辅助块移到正文后并折叠,跳过 module/type 卡片,显示“结构步骤非实际执行时序”。旧 View 截图中的最初顺序问题已有改进;但这不意味着已提供能直接放进 qdagent 右栏的独立阅读 SDK。 - -### 2.2 直接影响集成的事实 - -1. `llm.complete_result` 当前仍走 `openai.chat_completions`,Ollama 也是兼容路径;`backend` 名称不是任意原生协议适配器。 -2. `plugins/llm::chat_completions` 从 `prompt` 构造一条 user 消息,没有完整消息列表契约;不能靠模型选择 UI 弥补历史丢失。 -3. `usage_from` 缺字段填零;Agent `model_turn(stream=True)` 直接 `tokens=0`,最终 `token_cost=tokens`。现有输出无法支撑准确货币或流式用量显示。 -4. 原生 LLM SSE parser 返回事件数组;`ext/ai` 有流事件机制,但应用所用 [web invoke](../../plugins/web/internal/httpx/routes_invoke.go) 在 `CallLibPath` 返回后才写 `{sse}`。需要打通实际增量路径,不能只换 Content-Type。 -5. Agent 生成子工作簿的模板仍能构造默认 `llm.llm`;只传主 agent handle 不足以证明嵌套调用沿用了用户选定模型。 -6. `build_file_view` 默认传 `execute=true`;live GET 路径使用它。嵌入阅读绝不能直接暴露这个入口。 -7. Presentation 目前按 artifacts 投影,缺全量 prose/heading/step/ref 的统一阅读树;`render_knowledge_html` 另从 steps/refs 渲染,容易与 JSON 事实发生覆盖差异。 -8. `source_digest` 当前由语义 artifact hashes 汇总,`semantic_generation` 是语义散列截短,`page_token` 来自原文件。它们不能直接分别冒充原文 revision、`.marqdo/CURRENT` generation 和跨请求完整版本。 -9. `sse_accepts_packet` 对缺 token 的 legacy 包放行;正式嵌入客户端必须采用严格版本匹配,而不是继承这项兼容宽容。 -10. `artifact.inspect/link.resolve` 每次走当前 semantic_project;现有入口不保证可以读任意历史 generation。历史引用需要明确的保留与解析合同。 - -## 3. 共用合同、版本与能力发现 - -合同名字固定为 `ModelSelectionV1`、`ModelCallUsageV1`、`RuntimeEventV1`、`DocumentViewV1`、`KnowledgeLocatorV1`;它们是这次扩展的 v1,与当前 KnowledgePresentation `schema_version:1` 不混用。新增 read model 不强行给已有 JSON 改含义。 - -新增 MLSP `capabilities`(拟议): - -```json -{ - "schema_version": 1, - "runtime_version": "implementation-version", - "features": { - "llm.explicit_selection": 1, - "llm.call_usage": 1, - "runtime.event_stream": 1, - "runtime.cancel": 1, - "view.document": 1, - "view.reference_resolve": 1 - }, - "adapters": [{"id": "openai-compatible", "available": true}], - "extract_formats": [{"format": "text", "available": true}], - "loaded_plugins": [{"name": "llm", "capabilities": ["call_usage_v1"]}] -} -``` - -只返回实际探测且加载可用的功能。不能仅从 CLI 版本推断 native plugin 符号存在;字段未知时应用降级或解释不支持。协议允许新增可选字段;删除/改变状态语义必须提升 major contract version。能力查询不调用供应商、不执行项目代码。 - -MLSP 继续使用现有 `{id,ok,result|error}` envelope;qdagent `/api/app` 转为自己的 `{ok,schema_version,data|error}`,不要要求它们共享同一层 envelope。所有合同提供成功、partial、unknown、unsupported、stale、cancelled、错误 fixtures 与 JSON Schema;应用和框架从相同样本跑消费测试。 - -## 4. M01:请求级模型身份与适配器 - -### 4.1 显式选择合同 - -应用将配置解析成可信 `ModelSelectionV1` 后传入 runtime,核心字段: - -```json -{ - "schema_version": 1, - "selection_id": "sel-1", - "provider_id": "provider-1", - "model_id": "model-2", - "provider_revision": 3, - "model_revision": 5, - "adapter": "openai-compatible", - "endpoint_ref": "endpoint-local-1", - "credential_ref": "credential-local-1", - "credential_version": 2, - "upstream_model_id": "example-model", - "parameters": {"max_output_tokens": 2048}, - "fallback_policy": "disabled" -} -``` - -endpoint/credential 引用由宿主 resolver 解析为调用局部配置;短期直接向现有 `llm.create` 传参数亦可,但这不是可序列化的 public snapshot。API key 不能出现在 events、debug JSON、生成工作簿、prompt、错误 URI 或持久化模型对象中。 - -当前显式 args 优先的能力保留;新增 strict selection 模式:字段缺失报错,不回退 process env/frontmatter。无凭证端点通过 `auth_mode:none` 显式表达,避免 falsy key 触发环境 fallback。legacy 命令行未传 selection 时仍可沿用原有 env 行为;本地便利兼容不扩散到应用请求。 - -每个运行绑定 selection snapshot,后续设置改变不修改它。主模型与 router_model 分开但同属受控 selection 集;manual 模式所有需要 LLM 的步骤固定选择,REUSE 无模型调用仍允许。fallback 必须由宿主明确授予、列出允许目标,不能因额度/网络错误静默转到另一个供应商。 - -### 4.2 子任务和工作簿传播 - -统一 `RunContextV1 = run_id,parent_run_id?,turn_id?,workspace_scope,selection_context,usage_sink,event_sink,cancellation_token`。进入 ask/step/plan、repair、summary、learn、子工作簿时显式继承;新 run/call id 关联父节点。 - -生成工作簿只包含不可重放滥用的运行上下文引用,不写密钥;执行时宿主注入/解析。独立导出工作簿在缺凭证/选择时清晰要求配置,不偷偷取默认模型。在任何 child/spawn/resume 路径遗漏 selection 都应由 strict 模式拒绝并给出定位诊断。 - -同时审查环境变量不只是凭证:project root、temp request、输出目录、event sink 也必须请求局部,不能在并发运行中依靠进程可变状态串联。 - -### 4.3 适配器与消息 - -适配器最小职责:验证 selection、报告能力、序列化请求、解析增量结果、usage 归一化、取消传输、错误归一化。可选 discovery/probe;无模型列表 API 仍允许手工配置。 - -V1 消息包含 role 和 content parts,parts 最低 text,附件通过受控引用;tool call/result 要保持配对及 role。不支持的 part/parameter 返回 `llm.unsupported_input/parameter`,不能悄悄转成空字符串。适配器决定协议格式,Agent 决定行为;qdagent 不拥有供应商协议代码。 - -阶段一验证两个不同兼容端点,分别至少两个模型,以及无密钥本地兼容服务。阶段二增加原生非兼容协议:每个适配器需具名能力、流式/非流式/错误/取消/usage fixtures 和独立接入说明后才能在 capabilities 中置 available。不能把所有厂商默认走兼容接口后统称全支持。 - -统一参数采用 `max_output_tokens,temperature?,stop?,reasoning?` 等语义键,能力不支持时明确拒绝;不随意透传客户端未知参数。实际 upstream model 若与请求 id 不同,在 result 中保留 requested/resolved 两者。供应商版本与价格随时变化,本文仅锁定内部合同;实施原生适配器时另附当时官方协议核验记录。 - -## 5. M02:用量、事件流与取消 - -### 5.1 ModelCallUsageV1 - -```json -{ - "schema_version": 1, - "call_id": "call-1", - "attempt_id": "attempt-1", - "parent_call_id": null, - "run_id": "run-1", - "turn_id": "turn-1", - "workspace_scope": "ws-1", - "purpose": "answer", - "selection_id": "sel-1", - "provider_id": "provider-1", - "model_id": "model-2", - "requested_model": "example-model", - "resolved_model": "example-model", - "status": "succeeded", - "usage_state": "final", - "measurement_source": "provider", - "input_tokens": 1200, - "output_tokens": 300, - "total_tokens": 1500, - "cached_input_tokens": 800, - "reasoning_output_tokens": null, - "revision": 2, - "provider_request_id": "opaque-provider-id", - "started_at": "2026-10-25T01:00:00Z", - "finished_at": "2026-10-25T01:00:03Z" -} -``` - -字段要求:tokens 非负整数或 null;`usage_state = pending|partial|final|unknown`;`measurement_source = provider|estimated|none`。估算可作为单独 estimate 字段返回,不能覆盖实测字段。供应商没有报告时用 null/unknown,传输失败不能自动解释成零消耗。 - -`status = started|succeeded|failed|cancelled|interrupted`,status 和 usage_state 独立。每个真实发出的 HTTP attempt 一个唯一 id;预检拒绝只产生 call-rejected 事件,不伪造已发送请求。框架重试必须可观测:所有 attempts 包括失败/有部分输出的 attempt;重复 delivery 的 usage revision 不算新请求。 - -累计 SSE usage 在同 attempt 内按 revision 发布完整快照,不让上层猜是 delta 还是 total。provider 总量与 input/output 不一致时保留原始读数及 `usage.inconsistent` 诊断,不自行强制改账;细分字段要标 inclusion 关系以避免缓存、reasoning 与总量重复相加。只保留脱敏的必要 provider usage 扩展字段,不把完整原始响应当 public usage。 - -纯知识复用用 run summary 中 `llm_calls=0`、`measurement_source=none` 表示,而不是伪造一条耗费为零的模型请求。框架输出 `call_count,known_tokens,unknown_call_count`,宿主据此显示覆盖程度。 - -### 5.2 事件流合同 - -```text -run.started - → model.resolved - → model.call.started - → message.delta / tool.progress / usage.updated(零到多次) - → model.call.finished(每个 attempt 各一条) - → document.produced / citation.produced(仅有真实对象时) - → run.completed | run.failed | run.cancelled | run.interrupted -``` - -`RuntimeEventV1` 公共字段:`schema_version,event_id,seq,run_id,parent_run_id?,turn_id?,workspace_scope,timestamp,type,payload`。seq 每个 run 单调;不同子 run 可以并发,宿主按所属 turn 另分配产品流序号。runtime terminal 事件仅一次;后续补全计量用有 revision 的 `usage.updated`,不能改变内容终态。 - -事件 sink 支持有界队列和背压;慢客户端不能无限堆积 token。丢弃可合并 progress 时记录 gap;内容与终态事件不可无声丢失。连接终止不会自动重跑;持久化/重放由应用,但框架需在实时回调后仍提供可核对的 final result/call summaries。 - -同一真实调用所有数据使用同一 run/call identity,不能流与最终结果各生成一套 id。工具参数/结果按 policy 脱敏,不把 secret、完整私有文件、模型内部推理链写入默认进度事件。 - -### 5.3 打通传输而不重造 Agent - -需要同时打通 LLM provider reader → Agent event sink → host callback → web streaming handler → 浏览器。现有 `sys.stream_publish` 可以作为底座,但要验证它是否绑定正确请求且在 `CallLibPath` 返回前可写出;不能用进程全局事件广播混流。 - -可实施路径:新增 web 流式 invoke/job primitive,由框架注册 run handle 和 event sink;调用返回 handle 后宿主可订阅/取消。采用插件 ABI 增量接口及能力检测,旧 ABI 未支持时拒绝新 streaming 模式,保留旧完整返回。qdagent 只挂产品鉴权、event id 持久化和 HTTP 端点,不添加另一个推理循环。 - -SSE parser 必须处理任意 TCP 分块、UTF-8 跨块、CRLF、多行 data、注释 heartbeat、尾帧、usage-only 帧、[DONE]、连接在结束前关闭。未知可选事件可忽略且记诊断;已知事件无效、异常截断不能静默当成功完成。公共 framing 不包含供应商私有认证信息。 - -### 5.4 取消与重试 - -取消 token 传到 HTTP reader、循环、工具边界、子任务。取消后不得启动新模型调用/新工具;正在进行的不可抢占操作返回 `cancelling` 和是否仍运行,结束后才报告 cancelled。明确“停止生成”不能撤销已经完成的外部写入。 - -调用超时、连接错误、鉴权失败、限流、协议错误分开;错误字段包含 `code,retryable,retry_after_ms?,call_id,attempt_id,usage_state`。不要将原始包含密钥/完整 prompt 的错误直接传到 UI。限流/短暂网络错误按有界策略重试;已产生输出的重试不能接在同一条文字后假装连续,也不能把未知结果的外部工具操作自动重做。 - -费用价格由应用管理。框架保留 legacy `tokens/token_cost` 并标注 deprecated/单位为 token,新功能只消费 ModelCallUsageV1,避免破坏旧脚本的同时停止误用。 - -## 6. M03:无执行的嵌入式 View - -### 6.1 新入口与纯度约束 - -新增内部公共服务 `analyze_document → project_read_model → render_fragment`;MLSP 暴露 `view.document`,可选 CLI `view document --json --no-exec` 与它共享实现。不要让新入口先进入 `build_file_view` 再隐藏按钮/清空输出。 - -读取允许:授权范围内原文/已编译快照/已有验证记录。读取禁止:运行模块入口、加载文档声明插件、执行外国代码、LLM、自动抓取 URL、写回、重新验证执行测试、隐式发布/重编译写盘。静态分析/内存投影允许;缺完整依赖时明确 partial。任何需要执行的行为必须另走显式 execute/verify 产品流程。 - -当前 `compile_project` 声明不加载插件/不求值/不抓取来源,可复用;缓存写入若需要,作为单独的宿主管理路径,不能把“读文档”隐含写项目目录。 - -### 6.2 DocumentViewV1 结构 - -请求由宿主传入受控 project 和文档定位,宿主必须已授权;框架仍做路径边界校验。 - -```json -{ - "method": "view.document", - "params": { - "project": "/authorized/project", - "document": "knowledge/example.mq.md", - "revision": "sha256:requested-source", - "generation": "generation-id-or-null", - "mode": "read", - "node_id": "optional-node", - "include": ["fragment", "outline", "nodes", "refs", "diagnostics"] - } -} -``` - -```json -{ - "schema": "DocumentViewV1", - "schema_version": 1, - "document": { - "id": "project-relative-document-id", - "title": "知识标题", - "source_revision": "sha256:raw-bytes-digest", - "semantic_digest": "sha256:semantic-facts", - "generation_id": null, - "presentation_token": "opaque-token" - }, - "execution": {"state": "not_run", "run_id": null}, - "render": {"format": "sanitized_html", "fragment": "<article class=\"mq-document\">…</article>", "renderer_version": "1"}, - "outline": [], - "nodes": [], - "refs": [], - "diagnostics": [], - "completeness": "complete", - "capabilities": {"read_only": true, "has_semantics": true} -} -``` - -`generation_id` 来自实际编译投影;即时分析但未编译发布时为 null,同时给 semantic_digest。`source_revision` 是原始文件字节摘要,不能复用当前基于 artifacts 的 `source_digest`;`presentation_token` 覆盖 source revision、generation/semantic digest、依赖版本、renderer/schema、读取策略与请求范围。应用缓存还必须含用户授权范围。 - -`completeness = complete|partial`;语法损坏时允许返回原文与结构化诊断,但不能展示猜测出来的正常知识图。失败用 error envelope,不能空字符串伪装“文档无内容”。大文档 response 支持 section cursor 和 truncated 标识,限制要可配置并在响应中标明。 - -### 6.3 统一正文、目录、节点与引用 - -节点包含 `id,parent_id,kind,label,order,source_span,artifact_id?,ref_ids[],children[]`。kind 包括 heading/prose/table/code/observe/derive/call/iterate/narrate/navigation;正文树来自 parser/classifier/sema 的共同投影,不能只枚举 functions 后把每个步骤标 call。 - -outline 描述读者文档层级,不简单把函数和对象全铺成同一级。HTML 中节点带 `data-mq-node`,引用带 `data-mq-ref`;实现 payload 按需展开,说明作为正文。动态调用/无法解析引用保持原文并解释原因,不虚构执行边。 - -首批 renderer 共享 `src/view/document.rs` 的文档表面,standalone/full page 和嵌入模式调用同一 read model;只改变容器和导航外观,不产生第二种语义解释。替换当前 `KnowledgePresentation` 与 `render_knowledge_html` 双路径重复组装。 - -稳定 ID 的保证范围要写明: - -- 同一 revision 再次读取,node/ref id 必须相同。 -- 仅前插空行/叙述时,已有命名符号保持 symbol id;步骤 id 由结构身份映射,不能只靠行号。 -- 同一行多个节点需要 column/offset/span 区分,不能都映射成 `stmt-N`。 -- 匿名步骤重排/重复同名内容可能无法唯一映射;返回 unmapped/ambiguous,不能声称任意编辑下永恒稳定。 -- source span 明确 1-based line/column 和 UTF-8 byte offset;JavaScript UTF-16 偏移不直接当 Rust 字节偏移。 - -旧 `#stmt-{line}` 可保留为当前版本兼容锚点,但不得作为跨版本唯一身份。 - -### 6.4 嵌入渲染、主题与访问性 - -fragment 不包含 html/body、应用导航、运行按钮、内联可执行 script、全局 CSS;CSS 以 `.mq-document` namespace 限定。主题暴露 `--mq-bg/surface/text/muted/border/accent/font-body/font-code`,宿主映射自己的设计 tokens;不把独立 View 的全局 `*`/body 样式注入 qdagent。 - -首批推荐 fragment + 结构化引用 + 宿主事件代理;无需为 iframe 和 React 各重做 parser。可选 iframe embedded shell 必须只读、无重复导航,宿主/子页通信校验 origin/source/nonce/schema,仅允许 open-reference/selection/ready 等已定义消息,不能从内容发任意运行指令。 - -所有文本/属性转义,允许的 Markdown HTML 白名单净化;链接 scheme 限制;外部资源不默认跨网加载;代码/公式不得执行。静态导出、独立页面、嵌入三者都测试恶意文本/闭合标签/危险 URL。不要把 KnowledgePresentation 内 JSON 的转义当作所有正文 XSS 防护。 - -标题/列表/表格用语义 HTML;说明链接有可访问名称,焦点可见,视觉排序和键盘顺序一致。折叠只隐藏技术细节,不隐藏理解结论所需的正文。320–720px 容器宽、暗色、200% 缩放和 print 都要能读,不出现遮住正文的关系连线。无 JS 时仍能读正文和普通链接。 - -## 7. M04:知识、来源与历史引用定位 - -### 7.1 KnowledgeLocatorV1 - -统一 locator:`project_id,document_id,source_revision,generation_id?,artifact_id?,node_id?,source_ref_id?,span?,relation`。relation 区分 cites/supports/derived_from/executes。普通链接导航、NarrativeRef 和 BoundCall 都能定位,但语义不同;点击说明永不成为 BoundCall 的执行。 - -新增 `view.reference_resolve`:接受 locator 或当前文档 ref_id,返回 `resolution = resolved|stale|unresolved|ambiguous|version_unavailable|unsupported`、目标 locator、候选(若有)、定位精度、诊断、读者标签。框架内部路径不作为浏览器 href,应用根据授权映射为 document/source route。 - -扩展 `artifact.inspect` 的版本参数,旧无版本调用仍查当前;新调用带 expected source/generation mismatch 时不能自动降到当前。来源读取接口可由宿主取实际文件,再调用框架 locator 映射;框架不自动 fetch 外部网页。`mq://` 必须按框架规则解析,不能交给浏览器或把 URI 直接当文件路径。 - -### 7.2 历史版本与保留责任 - -生成 artifact/generation 元数据不等于保存了原文历史。框架须输出可保存的 snapshot manifest:原文 revision、依赖 revision、source refs、artifact hashes、renderer/schema version;应用决定哪些源版本随引用保留及保留周期。已有 Git 或内容寻址存储可提供 snapshot resolver;不强制应用部署 Git。 - -source revision 定位到存储快照后,框架基于该快照解析;缺失任何必要版本时返回 version_unavailable/partial,不读取最新文件填充旧快照。如果只留 artifact 元数据、原始资料已删除,仍可展示历史元数据但明确“原文不可读取”。 - -知识改名、移动或 source anchor 改变可返回候选映射,只有唯一可靠匹配才自动导航;否则用户选择最新版/候选。保持旧引用与新引用两个对象,防止历史回答证据在后台悄悄改变。 - -### 7.3 验证和运行事实 - -节点详情至少携带 purpose/description、signature、applicability、provenance、effects、dependencies,以及 parse/resolve/contract/tests/evidence/execution 各自状态与记录来源。sourced 只能说“已关联来源”;static verify 成功不表示执行成功或适用业务正确。 - -真实执行证据独立结构 `run_id,artifact_digest,closure_digest,source_revision,generation_id,inputs_digest,executed_at,result_state,evidence_ref`,展示时匹配版本。旧运行结果不涂成当前文档的绿色通过。知识复用必须存在实际 bind/execute trace,不能凭 find 命中显示“已执行”。 - -View 不运行验证测试以填满状态。若用户点“验证”,应用走已有 verify/policy 门禁并记录新 evidence,之后读取才刷新详情。 - -### 7.4 错误与授权协作 - -| 内部结果 | 应用建议呈现 | 不能做 | -|---|---|---| -| unresolved | 无法定位该知识,可读原引用 | 跳转到第一个同名 artifact | -| ambiguous | 显示已授权候选和位置 | 自动选择或暴露不可见候选 | -| stale | 该知识/来源已变化,提供版本选择 | 静默替换旧引用 | -| version_unavailable | 回答所用版本不可用,可查看最新版 | 用最新版伪装历史证据 | -| partial | 部分依赖或来源缺失,说明范围 | 默认绿色通过 | -| permission denied(应用) | 无权访问 | 在错误中泄漏标题、路径、片段 | - -用户权限归应用;框架服务在调用边界接受 scoped project/source resolver,不把传来一个 root 视为可遍历整个服务器。所有路径经过 canonicalize/symlink 检查;缓存的语义事实可共享,带原文的响应必须按权限复核,不能只靠 artifact id 缓存授权。 - -## 8. M05:工作区、笔记与导入所需的通用底座 - -不为 qdagent 画像加语言特殊节点。通用能力应支持普通文档元信息读取、来源范围、内容修订、diff/patch 的 expected digest、提取格式 capability。 - -document.extract 继续使用 DocumentSource→ExtractedDocument,报告 format/status/segments/source locator/diagnostics。TXT/MD 可支持;PDF/DOCX/OCR 没有适配器时明确 unsupported/failed,不能将空文本当成功。partial 保留已提取片段及原文范围、遗漏原因;发布政策由应用决定。 - -同一资料可产生多个知识单元,provenance 必须到具体片段,不能所有函数只指向文件根。原始资料 digest 改动的失效由现有 provenance/closure 保证;应用用户画像也可用普通来源引用,但不自动进入公共知识发布。 - -ProjectRoot/CompileOptions 显式传递,工作区 A/B 的 source id、输出 generation、缓存、临时目录必须隔离。避免每读一个节点就全项目编译:引入按 project snapshot 复用的分析服务,针对来源/依赖变化失效;并发同 snapshot 请求合并,不能分别写同一个 CURRENT。 - -上传 multipart/大小限制已有 web 底座,框架只提供安全提取和可消费结果;浏览器上传、作业生命周期、发布确认、权限和历史保存仍在 qdagent。多文件任务桥接采用结构化参数,禁止拼接用户文件名进 shell/JSON 或共用固定请求临时文件。 - -## 9. 实现落点与兼容策略 - -| 模块 | 改动方向 | 兼容要求 | -|---|---|---| -| `plugins/llm/src/lib.rs` | adapter boundary、消息数组、usage、event sink、取消 | 保留已有符号;新能力有 probe 和合同版本 | -| `ext/ai/llm.mq.md` 与 `ext/ai/llm/*` | strict selection、结构化 result、public snapshot | 无 selection 的旧调用仍可运行;不得回显密钥 | -| `ext/ai/agent.mq.md` | run context、子工作簿传播、逐调用观测 | 不复制 Agent loop,EFI/verify/publish_gate 不被绕过 | -| `plugins/agent/src/*` | 子任务/恢复上下文、cancel、event identity | resume 不重发已结算请求;不可恢复说明 interrupted | -| `src/host/*`、插件 SDK、web invoke | 请求局部 event/cancel 桥接 | ABI 旧宿主不伪支持;并发请求不混流 | -| `src/view/knowledge_present.rs` | DocumentView read model/兼容 adapter | 旧 presentation v1 不被新字段语义污染 | -| `src/view/document.rs,render.rs,html.rs,mod.rs,output.rs` | 共享纯读取、fragment、scope CSS、定位 | live/debug 与 read 明确分离;旧 no-exec 门禁保留 | -| `src/mlsp.rs` | capabilities、view/document/reference、版本 inspect | 使用现有 envelope;未知 feature 可探测 | -| `src/sema/ir.rs,provenance.rs` | span、snapshot/locator、依赖与来源失效 | 不改变核心语法,不把读请求变为执行 | -| `src/document_extract.rs` | capability 和片段定位完整性 | 保留不支持格式的显式失败 | - -测试分层对应 plugin HTTP fixtures、Agent 假模型、MLSP read contracts、web 持续流集成、独立/嵌入 DOM 和浏览器交互。应用共享样本文件必须注明 schema 版本;两仓 PR 在各自文档索引相互链接对应实现说明。 - -迁移顺序为新增合同/接口 → 旧输出 adapter → qdagent 按 capability 接入 → 切默认 → 后续版本再考虑弃用。不要同时移除 legacy 行为且要求应用一次完成全链升级。发布包对 CLI/ext/native 插件做组合测试,缺插件给功能不可用诊断而非 unknown function 直到用户点击才暴露。 - -## 10. 交付切片与验收门槛 - -| 切片 | 前置 | 验收输出 | 支撑应用任务 | -|---|---|---|---| -| M00 合同冻结/探测 | 无 | schemas、fixtures、capabilities、版本和插件清单 | Q00、所有升级探测 | -| M01 多模型隔离 | M00 | 兼容适配器、strict handles、history、子任务选择一致 | Q01/Q02 | -| M02 调用观测与流 | M01 | 每 attempt usage、真流式、取消、错误/重放一致 | Q03/Q06 | -| M03 只读嵌入 View | M00,可与模型线独立 | DocumentViewV1、fragment、目录/节点、无执行证明 | Q04 | -| M04 引用与快照 | M03 | 历史 locator、来源详情、版本失效/歧义 | Q05 | -| M05 文档工作区底座 | M03/M04 + 已有 extract | 范围隔离、提取定位、并发与缓存 | Q07/Q08 | -| M06 集成与性能 | 全部所选切片 | 旧门禁 + 新 contracts + 浏览器与负载报告 | Q09 | - -M01 支持多个兼容提供商不等待原生协议全做完;但原生适配器需另列完成状态。M03 不等待计费系统。M04 未完成历史快照前,应用可以显示当前文档,但必须把历史引用标“版本不可用”,不能宣布引用链闭合。 - -每个切片的 Definition of Done:实际接口可调用、失败合同覆盖、无副作用/隔离测试、文档示例由测试消费、版本能力可探测、qdagent integration fixture 通过。只有可运行的验收证据才可将 proposed 改为 verified。 - -## 11. 框架测试矩阵 - -| 编号 | 用例 | 断言 | -|---|---|---| -| F01 | 两端点各两模型、并行 A/B、无密钥本地端点 | 请求 payload/端点/鉴权正确,环境不串扰 | -| F02 | step/plan/router/repair/child/resume | strict selection 和 parent identity 完整,不退回默认模型 | -| F03 | multi-turn、system/tool roles、超限/不支持模态 | 顺序和边界完整,不吞最新 user,不静默降级 | -| F04 | 非流/流式/usage-only/缺 usage/错误后部分 usage | null 与 0 区分,终态和用量独立 | -| F05 | 相同累计 usage 多次、重放、新重试 | 同 attempt revision 覆盖,不重复相加;真重试新增 attempt | -| F06 | 慢供应商、慢消费者、断连、取消、超时 | 完成前有 delta;队列有界;取消不启动后续工具/模型 | -| F07 | 外部工具已写后取消、恢复未知状态 | 不声称撤销,不自动重做可能有副作用的动作 | -| F08 | 带写文件/网络/foreign/插件的文档被阅读 | read API 不加载/运行这些效果,无项目写回 | -| F09 | prose/heading/6 类步骤、同一行多引用、中文 span | HTML/outline/节点/ref 同源,定位唯一准确 | -| F10 | 仅说明变化、依赖变化、旧 SSE 包、无 token | token 正确失效,嵌入 strict 拒绝过期/无身份包 | -| F11 | 来源改删、历史 generation 未留原文、同名歧义 | 明确 stale/unavailable/ambiguous,无猜测替代 | -| F12 | no-js/390px/暗色/长表格/键盘 | 正文可读,可返回,有清晰标题和焦点 | -| F13 | 原始 HTML/危险 URL/闭合 script/越界路径 | 无脚本执行/越权读取/泄漏;不靠应用猜净化 | -| F14 | 两项目同相对路径/并发 100 读取 | scope 缓存隔离,同 snapshot 合并分析 | -| F15 | 编译成功但验证/证据未知、旧执行记录 | 各状态独立;不把 static/sourced 标 verified | -| F16 | CLI/ext/native 版本错配 | capability 早发现不可用,而非运行时静默失败 | - -性能目标需实测而非发版文字:固定机器与 release/debug 分开记录,1000 单元分析冷/热、单文档 fragment 体积/时间、并发读取 P95/内存、UI 首屏。应用目标见 Q 文档;如果全量 compile 超时,优先分析重复全库扫描、依赖计算与缓存,不通过删除 fixture 或抬高阈值宣布可用。 - -## 12. 本次验证结果与已知阻碍 - -### 12.1 M00–M06 落地证据(2026-10-25 续) - -命令(本机): - -```bash -cargo test --offline --locked --test workbench_contracts -cargo test --offline --locked -p marqdo_plugin_llm -cargo test --offline --locked --test executable_knowledge f1_agent_eng_bind_gate_mq_offline -- --exact -``` - -已交付并通过自动化子集(**非** F01–F16 全绿): - -| 切片 | 证据 | -|---|---| -| M00 | fixtures + JSON Schema 消费;`capabilities`;`force_unloaded` / `force_*_off`(F16) | -| M01 | strict selection;`RunContextV1` 并行不串扰;llm plugin messages/roles;workbook 禁 `llm.llm`;**F02** `m01_f02_agent_step_selection_and_resume`(mock HTTP + `llm.create` 抗 env poison + resume save/load) | -| M02 | usage null≠0;revision 替换(F05);cancel token(F06/F07);event_sink;web `sse-live` 断连 cancel | -| M03 | `view.document`;CJK outline/nodes;path escape;静态 a11y 子集;F08 无副作用标记;**浏览器** `workbench-docview.html`(`article.mq-document`、0 script、无 `javascript:`) | -| M04 | stale / version_unavailable / **ambiguous**;`SnapshotManifestV1` 输出(retention=application);`artifact.version_mismatch`;embed strict SSE | -| M05 | extract `:B`;analysis_cache begin/finish;**F14 并发 100** 同 snapshot + 跨 project 隔离 | -| M06 | CI 预构建 agent+llm + `workbench_contracts`;Go `drainForward` / cancel-token 桥 | -| Live | `tests/workbench_live.rs`:USTC OpenAI-compatible(`OPENAI_*` env only)`qwen3.8-chat` / `deepseek-flash` selection ask → `pong` + usage;`MARQDO_EXT` 指向仓内 `ext/` 避免 `~/.marqdo/ext` 陈旧遮蔽 | - -已知限制(发版前须书面接受或继续补): - -- F02 repair/plan **全路径**假模型仍薄于 step+resume;RunContext 三级继承 + skeleton 禁 `llm.llm` + 子任务 env 已有。 -- 历史正文由应用按 SnapshotManifest 保留;框架缺快照 → `version_unavailable`(不静默降级)。 -- 完整宿主嵌入 F12 / 产品鉴权留给 qdagent;原生适配器 / PDF/OCR 仍 unavailable。 - -### 12.2 历史基线记录(设计起草时) - -起草时 `executable_knowledge` 曾出现 `f1` 缺插件与 `v3_corpus_1000` debug 超时;其后 `ensure_agent_plugin_built` + CI 预构建已修复 f1 路径。1000 单元性能仍按剖面单独记录。 diff --git a/doc/design/return-hr-and-code-surface.md b/doc/design/return-hr-and-code-surface.md deleted file mode 100755 index 529859a..0000000 --- a/doc/design/return-hr-and-code-surface.md +++ /dev/null @@ -1,37 +0,0 @@ -# 记录:返回 / 语句 / 输出 / 分割线(决议) - -| | | -|---|---| -| 状态 | **v0.2 已决议**(现行实现);**v0.3 拟对调 `*` / `**` 角色**(见下) | -| 日期 | 2026-08-04 | -| 修订 | 2026-09-13:挂接 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) | - ---- - -## 决议(v0.2 · 现行) - -1. **`*…*` = 程序语句**。 -2. **`**…**` = 返回值**(架构级);空粗体 `****` / `** **` = 空返回(`None`)并结束函数体。 -3. **输出**用内置函数 **`print`**(英文),不是粗体,不是中文名。 -4. **`---` / `***`**:Markdown 叙述分隔(跳过);**不再**结束函数体。无值收束用 `*None*` / 整行 `**` / `****`(见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) §7.2)。 -5. **成段注释**:空行分段;段内续行不因首字符升级为代码。 -6. **否决**:无标记行 = 默认代码。 - -详见 [keywords.md](keywords.md)、[markdown-mapping.md](markdown-mapping.md)、[code-vs-comment.md](code-vs-comment.md)。 - ---- - -## v0.3 意向(Proposed · 未实现) - -产品方重新审视后,拟在 [ADR 0005](../adr/0005-prose-unified-markup.md) 下**对调**架构标记,并放宽叙述面: - -| 概念 | v0.2 | v0.3 草案 | -|------|------|-----------| -| 代码段 / 语句 | `*…*` | `**…**` | -| 返回值 | `**…**` | `*…*` | -| 空返回 | `****` / 空粗体;或 `---` | **推荐 `*None*`/`*无*`**;整行 `**`;兼容 `****`;`---` 仅叙述 | -| 输出 | 仍为 `print` / `打印` | 不变 | -| 无标记 = 默认代码 | 否决 | **仍否决** | -| 叙述中 `` `名` `` | 通常无绑定义 | 一律变量;未使用 OK;升参需可执行面读取 | - -完整规则与迁移见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)。**v0.3 已为运行时;本文件历史决议中「`---` 收束」已废止。** diff --git a/doc/design/spaced-function-names-d8.md b/doc/design/spaced-function-names-d8.md deleted file mode 100755 index 76e8d06..0000000 --- a/doc/design/spaced-function-names-d8.md +++ /dev/null @@ -1,216 +0,0 @@ -# 方案评估:函数名含空格的调用(D8) - -| | | -|---|---| -| 状态 | **Proposed · 待审阅**(未实施任何代码改动) | -| 日期 | 2026-10-22 | -| 来源 | [qdagent-refactor-defects-2026-10.md](../research/qdagent-refactor-defects-2026-10.md) D8 | -| 前置 | [parser-diagnostics-d8-d9.md](parser-diagnostics-d8-d9.md)(该文方案 A「禁止空格」**已被否决**,见 §0) | -| 影响面 | 核心解析:`src/parse/expr.rs` 调用切词 / `src/lex` 行分类 / 名称解析 | - ---- - -## 0. 为什么原方案被否决 - -原方案 A 主张「定义期拒绝含空格的函数名」。这是**错的**,理由是我此前忽略的一句话: - -> Marqdo 的立身之本就是**完全兼容 Markdown**。 - -`## 用户 登录` 是一个**完全合法的 Markdown 二级标题**。真实文档里这类标题极多: - -```markdown -## 用户 登录流程 -## 第三阶段 数据校验 -## Appendix A Results -``` - -如果禁止这些标题当函数名,等于强迫作者为了「能调用」而改写标题措辞—— -这恰恰把「代码即文档」降级成「代码迁就文档」。作者写的标题首先应当是**他自己想写的标题**。 - -**结论:空格必须被支持,问题只在于「怎么把带空格的名字准确传给调用」。** - ---- - -## 1. 事实基础(全部实测,1.5.2) - -先固定真实行为,避免方案讨论建立在猜测上。 - -### 1.1 定义侧 - -| 输入 | 结果 | -|------|------| -| `## 加一 号` | ✅ 定义成功,函数名**原样**为 `加一 号`(`parse_object_decl` 走 `Ok((raw.to_string(), None))`) | -| `## 用户 登录流程` | ✅ 同上 | - -**定义侧完全支持空格**,不需要任何改动。 - -### 1.2 调用侧 - -| 输入 | 结果 | 原因 | -|------|------|------| -| `> 加一 号 n=1` | ❌ `undefined variable 号` | `parse_call_tail` 用 `split_whitespace().next()` 只取首词 | -| `> [加一_号] n=1` | ✅ 正常(返回 2) | 方括号标记调用**已存在**且工作 | -| `> [加一 号] n=1` | ❌ `unknown function [加一` | `is_bracket_callee_inner` 第 1248 行**显式拒绝含空白** | -| `` `加一 号` `` 作为表达式 | ❌ `undefined variable 加一 号` | 反引号名走变量解析,找不到函数 | - -### 1.3 关键发现 - -> **方括号标记调用(`[callee]`)已经存在且实现完整**, -> 挡住带空格名字的是 `is_bracket_callee_inner` 里的**两处**校验, -> 而不是一处(首轮评估低估了)。 - -这是本次评估最重要的发现:**不需要发明新语法**,只需要让既有机制接受空格。 - -### 1.4 可行性实测(已做,未保留改动) - -为回答「放开后运行时到底能不能查到含空格的函数名」,做了受控实验: -临时放开两处校验 → 编译 → 跑用例 → **立即回退**(`src/parse/expr.rs` 已恢复原样)。 - -| 关卡 | 位置 | 原逻辑 | 放开后 | -|------|------|--------|--------| -| 1 | `is_bracket_callee_inner` | `t.chars().any(is_whitespace)` → 拒绝 | 删除该检查 | -| 2 | 同函数末尾 bare-name 白名单 | `is_alphanumeric() \| '_' \| '.' \| !is_ascii()` | 追加 `\| c == ' '` | - -**实验结果** - -| 用例 | 结果 | -|------|------| -| `## 加一 号` + `> [加一 号] n=1` | ✅ **返回 `2`**(运行时函数表正确命中含空格名) | -| `## 加一_号` + `> [加一_号] n=1`(对照) | ✅ 仍返回 `2`,既有行为不变 | -| 全量 `cargo test --lib` | ✅ **237 passed, 0 failed** | - -**结论**:方案 1 技术上完全成立,且**不破坏既有测试**。 -(237 = 基线 233 + 本轮 D9 新增的 4 个分类测试。) - -> 注意:实验只证明「可行」,未固化。正式实施需要补 §4 的全部 V1–V9 用例, -> 特别是 V3–V7 的歧义排除,再决定是否合入。 - ---- - -## 2. 候选方案 - -### 方案 1 — 放开方括号内的空格(推荐) - -**做法**:把 `is_bracket_callee_inner` 的「含空白即拒绝」改为「允许空白, -但需与既有歧义守卫共存」;并确认调用链后续不再按空格切词。 - -**用法**: - -```markdown -## 用户 登录流程 - + `账号` - -*"已登录 " + `账号`* - -# main - -> [用户 登录流程] 账号=alice -*"" -``` - -**优点** -- 不新增语法:`[…]` 标记调用是**既有**的正式特性,只是被一行校验挡住 -- 向后兼容:所有现有调用(含 `[加一_号]`)行为不变 -- 与 Markdown 完全兼容:标题怎么写都行,调用时用方括号「引用这个名字」 -- 语义清晰:方括号本身就是「这里是一个整体名字」的视觉标记 -- 可推广:方法调用 `[obj.方法 名]`、库函数 `[lib.函数 名]` 一并受益 - -**风险与缓解** -| 风险 | 缓解 | -|------|------| -| `[…]` 也被用于链接索引 `[key](map)` | 已有守卫:`]` 后紧跟 `(` 则不是 callee(第 981 行),保持 | -| JSON 数组 `[1, 2]` 被误认为 callee | 既有守卫:含 `,` `:` `{` `}` `[` `]` 一律拒绝,保持 | -| `print text=(礼貌 [问候] x)` 类内嵌方括号 | 既有守卫:前缀含 `=` `(` `"` `'` `:` 则不当 callee,保持 | -| 运行时按下标查函数表,`加一 号` 能否命中 | **需实测验证**(见 §4 验证计划 V1) | - -**工作量**:改 2 处校验 + 补 6–9 个测试 + 更新教程与陷阱手册。**最小可验证改动**。 - ---- - -### 方案 2 — 调用侧最长前缀匹配(否决) - -**做法**:拿到 `加一 号 n=1` 后,尝试用「已知函数名」做最长前缀匹配。 - -**否决理由** -1. **上下文不可达**:调用发生在表达式解析阶段,此时只有本模块符号表; - 跨模块 `lib.函数 名` 需要 import 解析结果,不可在词法期判定。 -2. **歧义爆炸**:`> print text=hello world` 中,若存在名为 `print text` 的函数, - 本来正确的调用会突然变成别的函数。所有多词行语义都可能改变。 -3. 属于**核心语义变更**,收益(省掉方括号)远小于风险。 - ---- - -### 方案 3 — 主张「标题即函数名,调用用完整标题」(不改代码,只改文档) - -**做法**:明确官方立场——带空格的名字**不自称可调用**,需要调用就请写 -一个无空格的 `## 别名` 转发,或直接把标题写成无空格形式。 - -```markdown -## 用户 登录流程 ← 给人读的标题,不被调用 - -## 用户登录流程 ← 真正被调用的函数 - + `账号` -... -``` - -**优点**:零代码改动;鼓励「标题给人、标识符给机器」的清晰分层。 - -**缺点**:与「完全兼容 Markdown」仍有张力——作者得写两遍。 - -**适用**:如果审计认为方括号放开会牵连过多,可作为**保守退路**。 - ---- - -### 方案 4 — 反引号名解析到函数(否决) - -允许 `` `加一 号` `` 在**调用位**解析成函数引用(`> `加一 号` n=1`)。 - -**否决理由**:反引号在 Marqdo 中统一表示**变量**引用。让它有时指变量、有时指函数, -会让「反引号=变量」这条最基础的约定失效,错误更难排查。 - ---- - -## 3. 方案对比 - -| 维度 | 方案 1 放开方括号 | 方案 2 前缀匹配 | 方案 3 文档立场 | 方案 4 反引号 | -|------|------------------|----------------|----------------|--------------| -| 兼容 Markdown | ✅ 完全 | ✅ | ⚠️ 需写两遍 | ✅ | -| 新增语法 | 无(复用既有) | 无 | 无 | 有歧义 | -| 改动范围 | 1 处校验 + 测试 | 核心语义 | 0 代码 | 核心语义 | -| 回归风险 | 低 | **高** | 无 | **高** | -| 可验证性 | 高(可枚举用例) | 低 | — | 低 | -| 推荐 | **首选** | 否决 | 备选 | 否决 | - ---- - -## 4. 若采纳方案 1:验证计划 - -必须全部通过才可合入。 - -| 编号 | 用例 | 期望 | -|------|------|------| -| V1 ✅| `## 加一 号` + `> [加一 号] n=1` | 返回 `2`(**已实测通过**,见 §1.4) | -| V2 | `## 加一_号` + `> [加一_号] n=1` | 返回 `2`(**既有行为不变**) | -| V3 | 链接索引 `[k](m)` | 仍解析为索引,不被当 callee | -| V4 | `> print text=(礼貌 [问候] x)` | 内嵌方括号不被当 callee | -| V5 | 方括号内 JSON `[1, 2]` / `["a"]` | 仍被拒绝为 callee | -| V6 | 跨模块 `[lib.函数 名]` | 正确解析到库函数 | -| V7 | 方法 `[obj.方法 名]` | 正确解析 receiver | -| V8 | 全量 `cargo test` | 233 全绿(+ 新增用例) | -| V9 | 全仓库 `.mq.md` 回归 | 无新增解析错误 | - -**V1 是决定性的**:如果运行时函数表以 `加一 号` 为键能正常查到, -方案 1 就成立;如果查不到(比如符号表内部也做了归一化),需要再评估。 - ---- - -## 5. 待你决策的问题 - -1. **选哪个方案?** 我倾向 **方案 1**(放开方括号空格):不新增语法、 - 完全兼容 Markdown、改动可控、可验证性强。 -2. **若选方案 1,调用书写是否需要中文别名?** 例如同时接受 `【加一 号】`(全角方括号), - 与全角冒号问题(D2)一致。 -3. **是否要保留方案 3 的文档立场作为补充说明?** 即「标题可自由书写; - 需要调用时用 `[完整名]` 引用」——这句话本身就很适合写进教程。 - -在你确认前,我不会改动 D8 相关代码。 diff --git a/doc/design/staleness-providers.md b/doc/design/staleness-providers.md deleted file mode 100755 index 0971b8a..0000000 --- a/doc/design/staleness-providers.md +++ /dev/null @@ -1,223 +0,0 @@ -# 修订:变更检测不该依赖 git —— 「前一状态」的 provider 分层 - -| | | -|---|---| -| 状态 | **Accepted · 修订**(取代 [warning-fatigue-control.md](warning-fatigue-control.md) §2 的 M5a) | -| 日期 | 2026-10-22 | -| 触发 | 用户:不是所有开发都用 git,依赖 git 是否是好设计 | -| 结论 | **不是好设计**。保住「变更驱动」原则,把「前一状态」抽象为可插拔 provider;核心能力零依赖 | -| 前置 | [label-freshness-and-repair.md](label-freshness-and-repair.md) · [warning-fatigue-control.md](warning-fatigue-control.md) | - ---- - -## 0. 直接回答:不该依赖 git - -三条理由,一条比一条硬: - -### 0.1 环境覆盖不到 - -| 环境 | 能调 git 吗 | 依据 | -|------|------------|------| -| 浏览器 WASM | ❌ | `marqdo-wasm`(wasm32-unknown-unknown),无进程能力 | -| **沙箱内执行** | ❌ | `src/host/sandbox_fs.rs`:`allow_exec: false` | -| 单文件分发 / zip 工件 | ❌ | 没有 `.git` | -| CI 容器(浅克隆/无 VCS) | ⚠️ 常常没有 | 取决于流水线 | -| 非 git 用户(hg / svn / fossil / 无) | ❌ 或需另写适配 | — | - -### 0.2 语言不该绑定某个 VCS - -Marqdo 是**语言与运行时**。把"断言是否过期"的判定建立在"某个工具的目录是否存在"上, -等于把语言的语义正确性外包给环境。今天 git 是主流,明天不是;语言不能跟着换。 - -### 0.3 最要命的:最重要的消费者恰在不能调 git 的地方 - -标签过期检测的**最高价值场景**是 agent 修复回路—— -模型改了代码,Marqdo 提醒它"你改的这处描述可能不成立了"。 - -而这个回路: -- 常在沙箱里跑(`exec=false`,**调不了 git**) -- 编辑目标是内存中的文本(`repair_apply` 的 `source`),不一定落在 git 工作区 - -**如果核心机制依赖 git,那它恰好在最需要它的地方失灵。** 这是设计错误的铁证。 - ---- - -## 1. 但 M5 的原则要保住 - -上一份文档的 M5 有两个部分,必须分开看: - -| 部分 | 判定 | -|------|------| -| **原则**:stale 是"变更报告",不是"扫描报告"(没有新信息就不说话) | ✅ **保留**,这是防疲劳的根 | -| **实现**:用 `git diff` 提供"前一状态" | ❌ **降级为可选 provider** | - -也就是说: - -> **判定逻辑只有一份:`stale ⟺ fingerprint(()) 变了 ∧ label 没变`。 -> 变的只是「前一个 `()` 从哪来」。** - -这一步抽象之后,git 只是**四种来源之一**。 - ---- - -## 2. 四层能力(provider 分层) - -### T0 — 引用一致性(零依赖,永远可用) - -纯文档分析:标签里的 `` `实体` `` 必须可解析、且出现在 `()` 中。 - -- 需要:只读当前文件(甚至只需文本) -- 能力:查**引用腐烂**(改名、删除、错引) -- 查不了:语义腐烂(`*` 改 `/`) - -### T1 — 会话内前后对照(零依赖,最高性价比) - -**任何"编辑前 + 编辑后"都在手的场合**都能算 stale: - -| 场合 | 前一状态从哪来 | -|------|---------------| -| `MLSP repair_apply` | 调用方传入的 `source` + `edits` → 前/后两版都在内存里 | -| `view`(保存后检查) | 保存前的模块 AST | -| 编辑器保存钩子 | 编辑器持有的旧缓冲 | -| agent 的 diff | 它自己的编辑集 | - -**关键**:只看「本次会话改了哪些标签的 `()` 且没改 `[]`」。 -天然变更驱动、天然零台账、天然带 before/after——**而且不需要 git**。 - -### T2 — 外部历史源(可选,自动探测) - -`git` / `hg` / `svn` / 任意"能取到上一版文件内容"的适配器。 - -- 检测:工作区存在 `.git` / `.hg` 且二进制可用 -- 用途:**跨会话**漂移(昨天改了代码,今天才检查) -- 缺失时:**静默关闭**,不报错、不提示、不产生噪音 - -### T3 — 台账(可选,无 VCS 时的持久化) - -`.marqdo/labels.json`:`{标签键 → {code_fingerprint, code_quote, confirmed_at}}` - -- 用途:没有 VCS 的环境(沙箱长期任务、编辑器插件)+ 严格模式的"确认"状态 -- 语义:**可丢弃缓存**(删了重建,最多一次全量确认) -- 已知代价:合并冲突、需要 bootstrap(因此作为 opt-in,不做默认) - ---- - -## 3. 环境能力矩阵 - -| 环境 | T0 引用 | T1 会话内 | T2 历史源 | T3 台账 | -|------|--------|----------|----------|--------| -| CLI + git 仓库 | ✅ | ✅ | ✅ | ✅ | -| CLI + hg/svn(有适配) | ✅ | ✅ | ✅ | ✅ | -| CLI 无 VCS | ✅ | ✅ | ❌ | ✅ | -| **agent 沙箱(exec=false)** | ✅ | ✅ | ❌ | ⚠️ CoW 内可写但不持久 | -| **浏览器 WASM** | ✅ | ✅ | ❌ | ❌ 无持久 fs | -| 单文件 / zip 工件 | ✅ | ✅ | ❌ | ❌ | -| 数据库/对象存储里的 `.mq.md` | ✅ | ✅ | ❌ | 由宿主提供 | - -**读法**:矩阵里**没有一行全 ❌**。T0+T1 在所有环境都成立—— -这两层就足以支撑"agent 改动即时提醒"这个最高价值场景。 - ---- - -## 4. 各层的能力边界(必须诚实) - -| 层 | 能查 | 查不了 | -|----|------|--------| -| T0 | 引用了不存在的实体;引用的实体不在语句里 | 语义腐烂(乘改除) | -| T1 | **本次会话内**的 `()` 变化 | 跨天/跨机器的漂移 | -| T2 | 跨会话、跨机器的漂移(若 VCS 有历史) | 未提交历史之外的变化;跨仓库移动 | -| T3 | 持久化的漂移(若台账被维护) | 台账未覆盖的标签;合并后需重算 | - -**组合起来的语义**: -- 有 T2 → 严格(能查历史) -- 只有 T0+T1 → **会话级严格**(够 agent 用) -- 什么都没有(WASM 首次打开) → 只查引用(T0),且**明确告知能力级别** - ---- - -## 5. 最关键的一条:agent 回路不需要任何 VCS - -`MLSP repair_apply` 的参数里**已经同时有前后两版**: - -```rust -// src/mlsp.rs:repair_apply 收到 source + ranges + edits -let source = source_text(params)?; -// → 应用 edits 得到 after -``` - -所以只要给协议补一个字段 `base_code`(或让 `repair_apply` 自己在内部保留 before), -Marqdo 就能在**同一次调用内**算出: - -> 哪些标签的 `()` 指纹变了、而 `[]` 没变 → 输出 stale 提示。 - -**零外部状态、零依赖、零 git。** 而这正是"模型改了代码别忘了改描述"的场景。 - -**具体协议建议**(只需一个可选字段): - -```json -{ "method": "repair_apply", - "params": { "source": "…", "ranges": [[42,42]], "edits": [...], - "check_labels": true } } -``` - -返回里附: - -```json -{ "labels": [{ "stale": 1, "items": [{ "text": "按 `税率` 计算总价", - "code_past": "…* 金额", "code_now": "…/ 金额", "span": {...} }] }] } -``` - -这样 agent 每轮只看到**自己刚弄脏的那几条**,且带前后对照。 - ---- - -## 6. provider 契约(五条硬规则) - -1. **核心不依赖**:T0/T1 必须在任何环境可用,不得引入 provider 前置条件。 -2. **缺失即降级**:provider 不可用 → 静默关闭该层能力,**绝不报错、绝不提示**。 -3. **能力必须自述**:`labels status` 必须显示"当前启用 T0/T1/T2/T3 中的哪些"。 - ——否则用户会误以为"没报 = 没问题",这是比噪音更坏的失败。 -4. **判定单一定义**:`stale` 的定义只有一处实现;provider 只提供 `prev`,不参与判定。 - ——否则不同环境会给出不同结论,语言就没有统一语义了。 -5. **不写进文档**:provider 的状态、指纹、抑制**一律不进 `.mq.md`**。 - 文档里只允许有人的语言与代码。 - -> 第 3 条是我这次最想强调的:**宁可少报,也不能假装"检查过了"。** - ---- - -## 7. 被否决的方案 - -| 方案 | 否决理由 | -|------|---------| -| **强制 git 作为核心** | 环境覆盖不到(§0.1);语言绑定 VCS(§0.2);最关键场景失灵(§0.3) | -| 文档内嵌指纹 | 污染文档;作者一改就失效;与"文档即散文"冲突 | -| 零宽字符隐藏指纹 | 不可见 = 不可审计;复制粘贴即损坏;工具链噩梦 | -| mtime 启发式 | 不可靠(checkout、touch、云同步都会变) | -| `# noqa` 抑制 | 已否(污染 + 不可审计 + 会永久化) | -| 只做全量扫描 + 静音清单 | 静音清单就是台账,且首次即爆炸 | - ---- - -## 8. 对上一份文档的修订 - -| 原条目 | 修订后 | -|--------|--------| -| M5a「git 结构化 diff」为核心机制 | 降级为 **T2 的一个适配器**;核心改为 **T0 + T1** | -| 严格模式依赖台账 | 严格模式 = 任意 T2 **或** T3 可用即可;无 provider 时按 T0/T1 运行 | -| 验收指标「无变更时输出 = 0」 | 保留,且补一条:**provider 缺失时也必须为 0,并在 `labels status` 里说明** | - ---- - -## 9. 待你决策 - -1. **接受「T0+T1 为核心,T2/T3 可选」这个分层吗?** -2. **T1 是否足够**作为 agent 回路的默认能力?(我认为够——它覆盖了"刚改完"这个主场景) -3. **能力自述**要不要做成 `labels status` 的固定输出 - (含"本次无法检测历史漂移"这类明确提示)? -4. **T2 的适配范围**:只做 git,还是留一个通用接口(返回"某文件的上一版文本")由宿主实现? -5. **T3 台账**是否推迟到有明确需求再做?(我建议推迟——先把 T0+T1 做扎实) - -> 我的建议:**先只做 T0 + T1**,把「变更驱动 + 零依赖 + 能力自述」这条骨架立住。 -> 这样无论用户在 git、hg、WASM 还是沙箱里,Marqdo 的标签保鲜都成立, -> 只是"能看多远"不同——而这一点会被明确告知,不会假装。 diff --git a/doc/design/stdlib-csv.md b/doc/design/stdlib-csv.md deleted file mode 100755 index b3bfff8..0000000 --- a/doc/design/stdlib-csv.md +++ /dev/null @@ -1,29 +0,0 @@ -# `lib/csv` — 逗号表(Mid M4) - -| | | -|---|---| -| 状态 | **已落地(M4)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-text-mid.md](stdlib-text-mid.md) · [stdlib-mid.md](stdlib-mid.md) | -| 导入 | `lib/csv.mq.md` · `lib/逗号表.mq.md` | -| Host | `host_csv_*`(RFC4180 最小集,无第三方 crate) | - ---- - -## 1. API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `parse` | `解析` | `text` | **list of maps**:首行为表头 | -| `stringify` | `序列化` | `rows` | CSV 文本(表头 = 首行 map 的键顺序) | - -## 2. 方言(v1) - -- 分隔符 `,`;引号 `"`;`""` 转义。 -- 换行 `\n` / `\r\n`;忽略末尾空行。 -- 字段内可含逗号与换行(须加引号)。 -- **不**支持自定义分隔符 / 无表头模式(可后续加)。 - -## 3. 刻意不做 - -流式大文件、类型推断、Excel 方言。 diff --git a/doc/design/stdlib-datetime.md b/doc/design/stdlib-datetime.md deleted file mode 100755 index 6b7e9ce..0000000 --- a/doc/design/stdlib-datetime.md +++ /dev/null @@ -1,40 +0,0 @@ -# 设计:`lib/datetime` / `lib/日期时间`(Mid2 M7) - -| | | -|---|---| -| 状态 | **已落地** | -| 日期 | 2026-09-09 | -| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §2.1 | -| 宿主 | `src/host/datetime.rs` · `host_datetime_*` | - ---- - -## 1. 时刻形状 - -每次返回 **map**: - -| 键 | 含义 | -|----|------| -| `unix` | 秒级 Unix 戳(int) | -| `zone` | 固定偏移文本,如 `+08:00` / `+00:00` | -| `iso` | RFC3339(秒精度) | - -`to_unix` 也接受裸 int 或 ISO 文本。 - -## 2. API - -| EN | ZH | 说明 | -|----|-----|------| -| `now` | `现在` | UTC 此刻(wasm 无时钟桥则失败) | -| `from_unix` | `自戳` | `unix` + 可选 `zone` | -| `to_unix` | `成戳` | | -| `parse` | `解析` | 默认 RFC3339 / `YYYY-MM-DD[ HH:MM:SS]`;`pattern=` | -| `format` | `格式化` | `rfc3339`/`date`/`time` 或 strftime | -| `add` | `加` | `days`/`hours`/`minutes`/`seconds` | -| `in_zone` | `时区` | 同瞬间换区 | - -**区名**:`+HH:MM` / `UTC` / `Z`,以及少量固定偏移别名(如 `Asia/Shanghai`)。**不做**完整 tzdb / DST。 - -## 3. 与 `lib/time` - -`lib/time` 保留极简 unix/format/parse/sleep。日历语义用本库。 diff --git a/doc/design/stdlib-encoding.md b/doc/design/stdlib-encoding.md deleted file mode 100755 index 842ee4e..0000000 --- a/doc/design/stdlib-encoding.md +++ /dev/null @@ -1,32 +0,0 @@ -# `lib/encoding` — 编解码(Mid M1) - -| | | -|---|---| -| 状态 | **已落地(M1)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-mid.md](stdlib-mid.md) · [stdlib-re.md](stdlib-re.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) | -| 导入 | `lib/encoding.mq.md` · `lib/编码.mq.md` | -| Host | `host_encoding_*`(无第三方 crate:标准 Base64 / hex) | - ---- - -## 1. API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `base64_encode` | `基64编码` | `text` | 文本(UTF-8 字节 → 标准 Base64,含 `=` 填充) | -| `base64_decode` | `基64解码` | `text` | 文本(解码后须为合法 UTF-8) | -| `hex_encode` | `十六进制编码` | `text` | 小写 hex | -| `hex_decode` | `十六进制解码` | `text` | 文本(偶数字节;合法 UTF-8) | - -## 2. 与 `net.url_encode` 的边界 - -| 能力 | 归属 | -|------|------| -| `application/x-www-form-urlencoded` 风格 | `net.url_encode` | -| Base64 / hex | **本库** | -| 百分号编解码通用版 | 可日后加 `encoding.percent_*`;本波不做 | - -## 3. 刻意不做(v1) - -URL-safe Base64 变体开关、忽略空白的宽松解码、二进制 `bytes` 类型(仍经 UTF-8 文本往返)。 diff --git a/doc/design/stdlib-foreign.md b/doc/design/stdlib-foreign.md deleted file mode 100755 index 1d0977b..0000000 --- a/doc/design/stdlib-foreign.md +++ /dev/null @@ -1,49 +0,0 @@ -# 外联 / 胶水标准库 - -| | | -|---|---| -| 状态 | **v1 已落地**;v2 设计见 [foreign-kernel.md](foreign-kernel.md) · [notebook-session.md](notebook-session.md) · [notebook-syntax.md](notebook-syntax.md) | -| 日期 | 2026-08-06 | -| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-math.md](stdlib-math.md)(公式同构绑定) · [foreign-kernel.md](foreign-kernel.md) · [notebook-session.md](notebook-session.md) · [roadmap/foreign-v2.md](../roadmap/foreign-v2.md) | - ---- - -## 1. 原则 - -**导入即用**:`lib/foreign` / `lib/外联`。解释器来自用户本机(PATH / `set_cmd` / `MARQDO_FOREIGN_*`)。live view 可点 Run;静态导出展示源码,Run 禁用。 - ---- - -## 2. 绑定语法(与公式同构) - -```markdown -`hi` = -```python -print("hello") -``` - -*`out` = > run code=`hi` * -``` - -得到运行时类型 **`code`**(`lang` + `source`)。未绑定的 \`\`\` 围栏仍是叙述注释。 - -曾用的 \`\`\`python name=hi **已移除**。 - ---- - -## 3. API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `set_cmd` | `设置命令` | `lang`, `cmd` | None | -| `run` | `运行` | `code`(code 值) | 文本 stdout | -| `run_lang` | `按语言运行` | `lang`, `source` | 文本 | -| `langs` | `语言表` | | 列表 | - -live view:Structure 中 code 卡片带命令框 + Run → `POST /api/foreign-run`。 - ---- - -## 4. 一句话 - -**`name` = + \`\`\`lang 围栏 → code 值;显式 run;本机解释器可配置。** diff --git a/doc/design/stdlib-fs-mid.md b/doc/design/stdlib-fs-mid.md deleted file mode 100755 index 76f7f0c..0000000 --- a/doc/design/stdlib-fs-mid.md +++ /dev/null @@ -1,24 +0,0 @@ -# `lib/fs` 加厚 — 复制 / 移动 / 临时文件(Mid M2) - -| | | -|---|---| -| 状态 | **已落地(M2)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-path.md](stdlib-path.md) · [stdlib-mid.md](stdlib-mid.md) | -| 边界 | **文本与普通文件**;不引入 `bytes` 类型(`read_bytes` 延后) | - ---- - -## 1. 新增 API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `copy_file` | `复制文件` | `src`, `dest` | `None`(覆盖已存在的目标文件) | -| `move` | `移动` | `src`, `dest` | `None`(rename;跨设备失败则报错) | -| `make_temp` | `建临时` | 可选 `prefix` | 相对 `cwd`/`fs_root` 的新空文件路径文本 | - -均走现有 `resolve_path` 沙箱;写操作受 `fs_write` 策略约束。 - -## 2. 刻意不做 - -目录树 `copy_tree`、原子替换、`read_bytes`、权限 chmod。 diff --git a/doc/design/stdlib-fs-mid2.md b/doc/design/stdlib-fs-mid2.md deleted file mode 100755 index 4c77b97..0000000 --- a/doc/design/stdlib-fs-mid2.md +++ /dev/null @@ -1,25 +0,0 @@ -# 设计:`lib/fs` Mid2 加厚(M9) - -| | | -|---|---| -| 状态 | **已落地** | -| 日期 | 2026-09-09 | -| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §4 · [stdlib-fs-mid.md](stdlib-fs-mid.md)(M2) | -| 宿主 | `src/host/fs.rs` · `host_make_dirs` / `host_remove_tree` / `host_stat` / `host_walk` | - ---- - -## API - -| EN | ZH | 行为 | -|----|-----|------| -| `make_dirs` | `建目录树` | 递归创建(与既有 `make_dir` 同为 `create_dir_all`;显式命名) | -| `remove_tree` | `删目录树` | 仅删目录树;路径为文件则报错 | -| `stat` | `状态` | `{size, mtime_unix, is_file, is_dir}` | -| `walk` | `遍历` | **深度优先**;相对路径列表(正斜杠);含目录项;同级按名排序 | - -既有 `remove` 对目录仍递归删除;`remove_tree` 拒绝文件,语义更窄。 - -## 刻意不做 - -ACL、watch、硬链接、`copy_tree`、惰性迭代器协议。 diff --git a/doc/design/stdlib-handbook.md b/doc/design/stdlib-handbook.md deleted file mode 100755 index 729c180..0000000 --- a/doc/design/stdlib-handbook.md +++ /dev/null @@ -1,130 +0,0 @@ -# 标准库:代码、文档、SKILL 与 tools 同源 - -标准库通常是单文件:直接阅读并调用 [fs.mq.md](../../lib/fs.mq.md)、[文件.mq.md](../../lib/文件.mq.md)、[table.mq.md](../../lib/table.mq.md) 或其他任务所需源码。 -31 个模块族对应 61 份公开标准库单文件;源码本身承担手册与 SKILL,不设强制总入口或模块 index。 -多文件拓展库的 index 用于组织多文件,标准库沿用其可读性和调用规范。 - -## 源码就是手册 - -每个函数标题下立即放参数表(名称、类型、默认、含义),随后是返回契约、效应、叙述形参、 -用途和边界、实际调用例子及短实现。无参数函数直接放返回表。旧 `+` 形参已移除。 -契约表位于首条执行语句之前;默认值和参数顺序保持兼容。 - -叙述比例逐函数超过 50%;既检查比例,也检查真实契约、调用和错误语义。 -不透明宿主指令使用遮蔽调用,例如 `` *[读取 UTF-8 文本](> host_read_text path=`path`)* ``: -方括号说明目的,圆括号执行真实代码;赋值语句同样采用描述标签。 -标签不替代参数与权限,也不能用空标签或重复模板代替说明。调用与返回自然写入正文; -行内表达式仍计作代码,绑定数据表不冒充叙述。125 份库源码的统一验收见 -[本轮记录](../roadmap/library-authoring-refactor.md),公共标准库当前为 650 个函数。 -键值行记录可用 table.from_pairs / 表.键值转记录生成具名记录,保留空值和重复键更新语义。 - -## 接口事实来自编译器 - -现有 call、catalog、MLSP 与编译器读取同一份标准库源码,不额外包装一层目录函数或示例函数。 -`examples/stdlib_catalog.rs` 使用实际装载、签名和效应结果检查源码中的效应说明; ---json 输出接口事实,--write 仅刷新效应说明,不生成第二套手册。 -人工维护用途、参数含义、失败处理和工程实践。不透明值保留渐进式 any,并说明来源和限制。 - -```sh -cargo run --example stdlib_catalog -- --json -cargo run --example stdlib_catalog -- --check -marqdo check lib/文件.mq.md --narrative-ratio -cargo test --test stdlib_tasks -``` - -测试直接读取 61 份公开源码中的实际命令,在 Tree 与 Bytecode 执行 126 次。 -验证每个函数的参数/返回契约、标题下表格、无旧形参声明以及逐函数叙述比例。 - -## 能力与兼容性 - -| 任务 | 新的公共入口 | 关键契约 | -|---|---|---| -| 文件整理 | fs.find/read_lines/write_lines/read_json/write_json/read_csv/write_csv | 明确根目录、格式和资源上限 | -| 文件修改 | atomic_write/write_changed/write_checked | 单文件原子替换;摘要检查不是内核 CAS,竞争写入仍需协调 | -| 批量文件 | copy_tree/sync_tree/rename_many | 先预检冲突,覆盖需选择;不承诺多文件事务;目录复制面向普通文件,不复制权限、链接与空目录 | -| 临时文件 | make_temp/temp_dir | 在授权根目录创建,由调用方明确清理;真实工程演示清理 | -| 二进制 | bytes 与 fs.read_bytes/write_bytes/read_chunk/append_bytes/file_hash | 普通 bytes 记录,Base64 跨 CLI/JSON/插件传递,字节偏移从零起 | -| 集合 | range/enumerate/pluck/project/where/find/any/all | 不增加回调字符串求值或新的查询方言 | -| 表数据 | group_by/aggregate/summarize/join/rename/unique_by/sort_keys | 行记录、分组键和字段含义明确;批量汇总避免作者循环反复复制列表 | -| 数据形态 | from_columns/to_columns/cast/try_cast/validate | 不猜测列式表与普通对象;列长、字段及类型错误有明确结果 | -| 集合运算 | union/intersection/difference | 返回保序列表,沿用运行时值相等规则 | -| 网络 | net.get/request/download/header_values | 超时、响应上限、重复响应头、字节响应;失败下载保留原文件 | -| 配置与日期 | toml.parse/stringify、datetime.parse_local/add_calendar | 标准 TOML;内嵌 IANA 规则;夏令时缺口和重叠明确失败或选择 | -| 子任务 | wait_timeout/cancel_all/run_many | 文件任务并发上限、超时终止回收、父权限与根目录继承 | -| 文档维护 | document.sections/section/tables/links/code_blocks/replace_section/replace_table | 与渲染共用 Markdown 解析器,不执行文档,保留周围源码 | -| 归档 | archive.pack/unpack | 可选 ZIP,预检路径、链接、重复项和展开上限,目标必须不存在 | - -旧 remove 保持递归删除行为,公开文档已纠正;新代码用 remove_file/remove_empty_dir。 -access 与 put 的整数路径从一开始;旧 at/slice/insert/remove_at 等接口从零开始,不能混用。 -更新返回新集合,原值保留;单次追加仍有复制成本。规模任务使用批量变换,去重使用分桶并保留原相等语义。 -混合排序采用明确类型顺序,修复数字与文本混排造成非传递比较的问题。 -大下标在 32/64 位目标上保持一致:取元越界为空,更新越界为诊断,巨大分块大小不会截断成零或导致死循环。 - -## 权限与错误 - -宿主身份声明效应,编译器沿解析后的依赖传播,不依据 fs、net 等导入别名猜测。 -函数、BoundCall 和步骤共享最终效应,外部标准库和中英文别名也使用同一逻辑。 - -```sh -marqdo call lib/fs.mq.md read_text 'path="notes.md"' --effects fs.read --fs-root /absolute/project --json -marqdo call lib/fs.mq.md atomic_write 'path="notes.md"' 'text="updated"' --effects fs.write --fs-root /absolute/project --json -``` - -默认 none 只准纯函数;fs.write 包含读取授权,其余能力仍需明确选择。 -plugin 保留加载提示所需的既有能力,不增加文件写入、网络或进程执行授权。 -根目录检查覆盖新文件的最近已存在父路径与符号链接越界。 -会话保存规范化根目录与可持久化结果;重建会话不重复文件、网络或进程写操作。 -不可重放写操作缺少快照时明确拒绝,不能为了重建句柄偷偷重做。 - -可恢复操作统一返回 `{ok,value,error}`,错误含 code/message/operation,校验错误可附 details。 -代码来自明确错误标签与 IO 错误种类,不扫描任意路径文本猜类别。Result 不授权操作,也不捕获任意语言错误。 -CLI 外层 ok 表示调用成功;函数值的 Result.ok 表示操作协议成功;HTTP status、子进程 code 仍需按领域判断。 -语法、契约与不可恢复运行错误继续使用原有结构化 Diagnostic,保留库来源和调用点。 - -## 平台与资源边界 - -| 能力 | 原生 | WebAssembly 浏览器目标 | CoW 试运行 | -|---|---|---|---| -| 集合、文本、JSON/CSV/TOML、字节数据、文档结构、静态时区计算 | 支持 | 纯计算可构建;具体浏览器熵/时钟依赖桥接 | 支持 | -| 原生文件与分块 IO | 支持 | 未接入浏览器文件系统时明确不可用 | 文件内容经覆盖层;已有目录枚举/元数据为宿主快照,试运行变更用 sandbox.diff/inspect | -| 文件复制、移动、追加与文本补丁 | 支持 | 无原生 FS | 经覆盖层;复制最多 64 MiB,不绕过试运行写入真实文件 | -| 目录状态、目录树批处理、归档、流式下载 | 支持 | 原生专属能力不可用 | 未建模的目录/原生任务明确拒绝 | -| HTTP、进程、动态插件 | 按构建特性支持 | 原生接口不可用;浏览器使用 browser 效果与桥接 | 依 profile/caps,不以库包装绕过 | -| 子任务取消 | 进程可终止并回收 | 不提供原生子进程 | 函数线程仅逻辑取消;有界批处理只接收文件任务 | - -新增有界读取默认 8 MiB、上限 64 MiB;旧 read_text 及其格式组合接口保留整文件读取语义,大文件使用 read_chunk/file_hash;原生文件摘要和下载使用 64 KiB 缓冲区。 -查找最多十万条目;序列和连接最多一百万结果;文件批处理最多一万任务、六十四并发。 -HTTP 时限与字节上限由调用方明确设置;不自动重试可能修改远端状态的请求。 -TOML 日期转换为 ISO 文本;写出不保留注释,None 和非有限数没有支持的表示。 -IANA 数据随锁定依赖交付,不声称总是最新政策数据。ZIP 不提供完整备份语义。 - -## 真实工程与验收 - -[标准库工程](../../examples/stdlib-handbook/index.mq.md)和[中文入口](../../examples/stdlib-handbook/索引.mq.md)同时完成: - -1. 扫描 Markdown,保留逐文件读取结果;坏 UTF-8 不阻止其他记录。 -2. 读取 CSV,转换字段,筛选并批量分组汇总,输出 CSV。 -3. 精确替换章节,以读取文本的摘要检查来源,保留其他叙述并原子写入。 - -`tests/stdlib_tasks.rs` 验证公开文档和双后端,而非只测私有宿主调用。 -附加测试覆盖 CoW 不落盘、写入快照不重放、超时后继续等待、网络参数预检、重复响应头、 -失败下载保留目标、ZIP 越界与链接、夏令时、TOML、混合排序和十万项去重。 -旧诊断测试从编译器 AST 定位库指令,继续严格检查独立调用点;不再因添加文档而依赖固定行号。 - -## 构建验证 - -原生默认特性、精简 wasm-core 特性、真实 wasm32 交叉编译均已验证。 -浏览器 ABI 与 `tests/wasm/stdlib.mjs` 在当前 wasm 产物上由 Node 执行,覆盖集合、字节、 -文档、TOML、IANA/DST、32 位大下标与嵌套路径诊断。Node 验收不是浏览器 DOM 布局验收。 - -发行版 rustc 与官方 wasm 标准库的构建元数据不能混用;本次使用同版本匹配的官方组件, -校验后在临时目录构建并执行,不依赖修改系统工具链。复现时使用已安装对应 wasm32 标准库的工具链: - -```sh -cargo check --no-default-features --features wasm-core -cargo build -p marqdo-wasm --target wasm32-unknown-unknown -node tests/wasm/smoke.mjs target/wasm32-unknown-unknown/debug/marqdo_wasm.wasm -node tests/wasm/stdlib.mjs target/wasm32-unknown-unknown/debug/marqdo_wasm.wasm -``` -单文件结构修正后,全量 970 项测试通过,0 失败,2 个原有忽略项;其中包括 17 项标准库工程测试。 -完整命令、分轮计数和交叉目标结果见[实施验收记录](../roadmap/stdlib-executable-handbook.md)。 diff --git a/doc/design/stdlib-hash.md b/doc/design/stdlib-hash.md deleted file mode 100755 index 3502428..0000000 --- a/doc/design/stdlib-hash.md +++ /dev/null @@ -1,26 +0,0 @@ -# `lib/hash` — 摘要与 HMAC(Mid M3) - -| | | -|---|---| -| 状态 | **已落地(M3)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-mid.md](stdlib-mid.md) · [stdlib-secrets.md](stdlib-secrets.md) | -| 导入 | `lib/hash.mq.md` · `lib/哈希.mq.md` | -| Host | `host_hash_*`(`sha2` / `sha1` / `md-5` / `hmac`) | - ---- - -## 1. API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `sha256` | `哈希256` | `text` | 小写 hex | -| `sha1` | `哈希1` | `text` | 小写 hex | -| `md5` | `md5` | `text` | 小写 hex | -| `hmac_sha256` | `密钥哈希256` | `key`, `text` | 小写 hex | - -输入按 **UTF-8 字节**摘要。文档标明:用于完整性标识 / 缓存键,**不是**密码存储(无 Argon2/bcrypt)。 - -## 2. 刻意不做 - -密码哈希、流式大文件哈希 API、非 UTF-8 二进制类型。 diff --git a/doc/design/stdlib-html.md b/doc/design/stdlib-html.md deleted file mode 100755 index d79d306..0000000 --- a/doc/design/stdlib-html.md +++ /dev/null @@ -1,19 +0,0 @@ -# 设计:`lib/html` / `lib/超文本`(Mid2 M8) - -| | | -|---|---| -| 状态 | **已落地** | -| 日期 | 2026-09-09 | -| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §3.2 | -| 宿主 | `src/host/html_ops.rs` · `host_html_escape` / `host_html_unescape` | - ---- - -## API - -| EN | ZH | 行为 | -|----|-----|------| -| `escape` | `转义` | `& < > " '` → 实体(`'` → `'`) | -| `unescape` | `还原` | 上述实体(含 `'` / `'`) | - -**不做** DOM / 模板引擎。 diff --git a/doc/design/stdlib-i18n.md b/doc/design/stdlib-i18n.md deleted file mode 100755 index 3c664ba..0000000 --- a/doc/design/stdlib-i18n.md +++ /dev/null @@ -1,148 +0,0 @@ -# 标准库多语言命名(草案) - -| | | -|---|---| -| 状态 | **草案(先文档、后实现)** | -| 日期 | 2026-08-04 | -| 原则 | **不指定语言**;靠**库文件名**区分中英(及日后其它语言) | -| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [keywords.md](keywords.md) · [keywords-i18n.md](keywords-i18n.md) · [user-site.md](user-site.md) | - ---- - -## 1. 要解决什么 - -- 内置(解释器里的名字)必须**少而精**;更多能力放进可 `>` 导入的标准库。 -- 标准库需要**中英两套 API**(函数名不同),并方便以后再加日文、西班牙文等。 -- **不要**用 frontmatter `lang:`、环境变量默认语言、或「同一导入路径再解析语言」——那是负累,也不符合「文档即代码」的直观性。 - ---- - -## 2. 方案(采用) - -**导入哪个库文件,就用哪套函数名。** -文件名本身表达语言;解释器只做路径解析,不做语言推断。 - -### 2.1 推荐:库名用目标语言书写 - -| 导入 | 库内函数名(示例) | -|------|-------------------| -| `import text:lib/text.mq.md` | `trim` · `split` · `join` | -| `导入 文本:lib/文本.mq.md` | `去空白` · `拆分` · `拼接` | -| `import table:lib/table.mq.md` | `put` · `rows` · `row_at` · list/map(见 [stdlib-table.md](stdlib-table.md)) | -| `导入 表:lib/表.mq.md` | `行数` · `取行` | - -示例: - -```markdown ---- -import: - text: lib/text.mq.md ---- - -# main -*`xs` = > split value=a,b,c sep=,* -``` - -```markdown ---- -导入: - 文本: lib/文本.mq.md ---- - -# main -*`xs` = > 拆分 s=a,b,c sep=,* -``` - -读者看到导入路径就能知道后面该用英文还是中文函数名——**无需再声明语言**。 - -### 2.2 可选:同概念用后缀区分(同目录、同「概念」) - -若希望「同一概念」在文件名上仍共享拉丁词根,可用: - -| 导入 | 含义 | -|------|------| -| `import text-en:lib/text-en.mq.md` | 英文 API | -| `import text-zh:lib/text-zh.mq.md` | 中文 API | - -这与 §2.1 **等价可选**,不是第二套解析器:仍然是「写哪个路径就加载哪个文件」。 -**优先推荐 §2.1**(`text` / `文本`),后缀形式留给需要 ASCII-only 路径的环境。 - -### 2.3 明确不做 - -| 不做 | 原因 | -|------|------| -| `lang: zh` / `MARQDO_LANG` | 隐式状态,难读、难测 | -| `> std/text` 再按语言展开 | 多一次魔法 | -| 同一文件内中英函数双份导出 | 遮蔽与文档混乱 | -| 强制用户只许用中文或只许用英文 | Marqdo 本就多语言友好 | - ---- - -## 2.4 特例:JSON - -`JSON` 为专有缩写,**不强求**中文库名或中文 API 翻译。官方只提供: - -```text -lib/json.mq.md # 中英文档均 `import json:lib/json.mq.md`;函数 parse / stringify / get / keys -``` - -不设 `lib/数据.mq.md` 等平行文件。其余模块仍遵守 §2.1。详见 [stdlib-modules.md](stdlib-modules.md) §3.4。 - ---- - -## 3. 与「少而精内置」的边界 - -| 层 | 内容 | 如何获得 | -|----|------|----------| -| **内置(L0)** | 极少:`print` `input` `len` `str` `int`(及语言字面量关键字) | 直接调用,无需导入 | -| **标准库(L1)** | 文本/表等扩展 API;**通常**中英各一套文件、各一套函数名(**JSON 例外**:仅 `lib/json.mq.md`) | frontmatter `import …:lib/…` | -| **宿主原语(实现细节)** | 若 `trim`/`split` 等暂由解释器实现 | 仅供标准库包装调用;**文档与用户站引导走 L1**,不鼓励当「关键字」堆砌 | - -日后若某能力足够「核心」,可再升格为 L0;升格前先留在 L1。 - ---- - -## 4. 目录与扩展约定 - -```text -lib/ - text.mq.md / 文本.mq.md - table.mq.md / 表.mq.md - # 本波:fs/文件 · sys/系统 · time/时间 · json(中英同文件)· net/网络 - # 暂缓:math/数学 · foreign/外联 - # 其它语言:texte.mq.md / テキスト.mq.md … -``` - -扩展新语言时: - -1. **新加一个库文件**(文件名用该语言或 `概念-xx`)。 -2. 库内函数名用该语言习惯。 -3. 文档表增加一行映射;**无需改解释器语言开关**。 - -导入解析仍沿用现有规则:相对路径 → 官方 `lib/` 根(`MARQDO_LIB` / 工作区 `lib/` 等),**不增加语言分支**。 - ---- - -## 5. 文档与示例义务 - -- 用户站:英/中库各一页(或同页两小节),导入路径与调用名并排;**JSON** 可共用一页、同一导入。 -- 金样例:分文件模块中英导入至少各一条;JSON 测 `lib/json.mq.md` 即可。 -- [keywords.md](keywords.md) 只列 L0;L1 指向本文 + [stdlib.md](stdlib.md) + [stdlib-modules.md](stdlib-modules.md)。 - ---- - -## 6. 实现备忘(暂不开发) - -实现阶段仅需: - -1. 落地 `lib/text.mq.md` 与 `lib/文本.mq.md`(及 table / 表)两套文件与函数名。 -2. 更新导入示例与金样例;删除「仅中文库名」的单轨示例。 -3. **不要**实现 `lang:`、默认语言、或 `std/text` 自动选语言。 - -若历史上加过 `Module.lang` / `lang:` 解析,应撤回,与本草案对齐。 - ---- - -## 7. 一句话 - -**标准库用文件名区分语言(导入即选择);JSON 为缩写特例,中英共用 `lib/json.mq.md`——无语言开关。** diff --git a/doc/design/stdlib-list-cli.md b/doc/design/stdlib-list-cli.md deleted file mode 100755 index 95195d6..0000000 --- a/doc/design/stdlib-list-cli.md +++ /dev/null @@ -1,36 +0,0 @@ -# `lib/table` 集合加厚 + `lib/cli`(Mid M5) - -| | | -|---|---| -| 状态 | **已落地(M5)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) | -| 集合 | 加厚现有 `lib/table` / `lib/表`(不另开 `listx`) | -| CLI | `lib/cli.mq.md` / `lib/命令行.mq.md` | - ---- - -## 1. 集合新增 - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `sort` | `排序` | `list` | 升序列表(int/num/text 优先;其它按显示文本) | -| `sort_by` | `按键排序` | `list`, `key` | 对 **map 列表**按键值排序 | -| `unique` | `去重` | `list` | 保序去重 | -| `chunk` | `分块` | `list`, `size` | 列表的列表 | -| `zip` | `拉链` | `a`, `b` | `[[a0,b0], …]`(取较短长度) | -| `flatten` | `展平` | `list` | 一层展平 | - -`reverse` 已有。 - -## 2. CLI - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `parse` | `解析` | 可选 `args` | map:`--k v` / `--k=v` → 文本;裸 `--flag` → `True`;位置参 → 键 `_` 列表 | - -`args` 缺省时用 `sys.args`(经宿主 `argv`)。 - -## 3. 刻意不做 - -稳定自定义比较器、惰性迭代器、完整 argparse 互斥组。 diff --git a/doc/design/stdlib-log-uuid.md b/doc/design/stdlib-log-uuid.md deleted file mode 100755 index a168572..0000000 --- a/doc/design/stdlib-log-uuid.md +++ /dev/null @@ -1,30 +0,0 @@ -# `lib/log` + `lib/uuid`(Mid M6) - -| | | -|---|---| -| 状态 | **已落地** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) | - ---- - -## 1. 日志 `lib/log` / `lib/日志` - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `set_level` | `设级别` | `level`(`debug`/`info`/`warn`/`error`) | `None` | -| `debug` / `info` / `warn` / `error` | `调试` / `信息` / `警告` / `错误` | `text` | 达级别则 `print` 一行 `LEVEL message`;否则无输出 | - -默认级别:`info`(隐藏 `debug`)。中文级别别名:`调试`/`信息`/`警告`/`错误`。 - -实现:宿主记最小级别;`host_log_line` 返回待打印文本或 `None`;L1 再 `print`(接入现有 stdout / capture)。 - -## 2. UUID `lib/uuid` / `lib/标识` - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `v4` | `版本4` | (无) | 标准 8-4-4-4-12 小写 hex(`getrandom`) | - -## 3. 刻意不做 - -结构化 JSON 日志、远程 sink、UUID v1/v7、yaml。 diff --git a/doc/design/stdlib-math.md b/doc/design/stdlib-math.md deleted file mode 100755 index ba0e719..0000000 --- a/doc/design/stdlib-math.md +++ /dev/null @@ -1,241 +0,0 @@ -# 数学标准库(方案) - -| | | -|---|---| -| 状态 | **已实现(M1–M4)** | -| 日期 | 2026-08-05 | -| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-i18n.md](stdlib-i18n.md) · [markdown-mapping.md](markdown-mapping.md) · [view.md](view.md) · 大学线性代数见规划 [ext-linalg.md](ext-linalg.md) | -| 导入 | `lib/math.mq.md`(英)· `lib/数学.mq.md`(中) | -| 范围 | **高中数学**(初等函数、导数、圆锥曲线、简单方程);非大学 CAS | - ---- - -## 1. 目标 - -1. **公式类型**:解析 `$$…$$`(及行内 `$…$` 的可选支持),得到可绑定、可传递的 **`formula` 值**——语义上像「公式常量 / 公式变量」。 -2. **数学库对 `formula`(及文本表达式)做操作**:求值、化简、求导、求解、作图等。 -3. **数值 + 随机**:日常算术与可复现随机。 -4. **作图**:view / 静态页内嵌 SVG;CLI 写本地文件(可指定 `path`)。 - -**难度自觉:** 只覆盖高中知识面,自研小型表达式 AST + 规则即可,**不**追求 Mathematica / SymPy 完备性。 - ---- - -## 2. 核心模型:`formula` 类型 - -### 2.1 运行时 - -| 类型 | `type` 标签 | 说明 | -|------|-------------|------| -| `Value::Num(f64)` | `num` | 浮点 | -| `Value::Formula(…)` | `formula` | 已解析的表达式树(或等价内部表示) | - -`print` / `str` 对 `formula`:输出规范 ASCII(如 `2*x + 1`)或保留源 LaTeX 的一种(实现时写死并文档化;建议 **ASCII 规范式** 便于测试)。 - -### 2.2 文档中的 `$$` = 公式赋值(与表格同构) - -**推荐(块内元数据)**:在 `$$` 体内用 TeX 注释声明变量(见 [fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)): - -````markdown -$$ -% marqdo: var=f -sin(x) + x -$$ -```` - -**兼容**:空 RHS 赋值后跟展示数学块(与 `` `xs` = `` 后跟表格一致): - -````markdown -# main - -`f` = -$$ -sin(x) + x -$$ - -*`df` = > diff formula=`f` var=x * - -> plot formula=`f` var=x min=-3 max=3 path=f.svg -```` - -也支持: - -- 单行围栏:下一行 `$$x^2 - 2$$` -- 同行 compact:`*`f` = $$x^2 - 2$$ *`(历史面) -- 行内:`` `g` = $x+1$ `` 或 `` `g` = $$x+1$$ `` - -**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。 - -**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区裸 `$$` 若既无空 RHS 又无 `% marqdo: var=` → 报错。 - -**行内 `$…$`:** 传统绑定 `` `名` = $…$ `` → `formula`;**不**使用 `$% marqdo:…$`(会破坏 Markdown/TeX 识别)。 - -### 2.3 从文本构造 - -| 英文 | 中文 | 说明 | -|------|------|------| -| `formula` | `公式` | `text=` 解析为 `formula`(ASCII 或简单 LaTeX 子集) | - -数学库函数形参统一接受:**`formula` 值**,或能解析的 **文本**(内部先 `formula` 化)。 - -### 2.4 与叙述面的关系 - -- `` `f` = `` + `$$…$$`:代码面赋值,得到 `formula` 值。 -- 成段注释里的 `$$`:仍是注释,不解析为公式。 -- view:公式赋值在 Structure 中显示为绑定,不是 comment。 - -(见 [markdown-mapping.md](markdown-mapping.md):空 RHS + `$$` → 公式赋值。) - ---- - -## 3. 知识范围(高中) - -### 3.1 表达式与符号(S) - -| 纳入 | 例子 | -|------|------| -| 多项式 | `x^2 - 3*x + 2` | -| 初等函数 | `sin` `cos` `tan` `ln` `exp` `sqrt` `abs` | -| 四则、幂 | `+ - * / ^` | -| 化简 / 展开 | 合并同类项、基本三角恒等(小集合) | -| 求导 | 单变元,初等函数求导法则 | -| 代入求值 | `subs` → `num` 或公式 | -| 求解 | 一元一次 / 二次闭式;其它用数值求根并标明 | - -**不做(本波):** 多元方程组、极限 ε-δ、级数、积分保证、**大学线性代数**(符号矩阵表达式 / 分解 —— 见 [ext-linalg.md](ext-linalg.md))、复数完备、任意证明。数值小矩阵字面量可在 `$$` 中解析为 `formula::Matrix`,但符号 MatExpr 与分解不在 `lib/math`。 - -### 3.2 作图(P) - -| 纳入 | 说明 | -|------|------| -| 显函数 `y=f(x)` | 采样折线 SVG | -| 导数曲线 | 对 `formula` 先 `diff` 再画,或 `plot` 选项 `derivative=true` | -| 圆锥曲线 | 标准形:圆、椭圆、双曲线、抛物线(参数方程或隐式采样) | -| 点列 | `plot_points` | - -**不做:** 三维、隐函数通用求解器、交互缩放(静态 SVG 足够)。 - -### 3.3 数值与随机(N) - -常数、四则、三角、对数、取整、`num` 转换、`random` / `random_int` / `seed`(同前稿)。 - ---- - -## 4. API 草图(对 `formula` 操作) - -### 4.1 构造与数值 - -| 英文 | 中文 | 要点 | -|------|------|------| -| `formula` | `公式` | 文本 → formula | -| `pi` `e` | `圆周率` `自然底数` | → num | -| `add`… / `sin`… | `加`… / `正弦`… | 对 num;若传入 formula 则返回 formula(符号)或报错——**v1 建议:算术函数只接 num;符号用 simplify/diff/subs** | -| `eval` | `求值` | `formula` + 变量赋值 → num | -| `random` / `random_int` / `seed` | `随机` / `随机整数` / `设种子` | 见前 | - -### 4.2 符号 - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `simplify` | `化简` | `formula` | formula | -| `expand` | `展开` | `formula` | formula | -| `diff` | `求导` | `formula`, `var` | formula | -| `subs` | `代入` | `formula`, `var`, `value` | formula 或 num | -| `solve` | `求解` | `formula`, `var`,可选区间 | list(num 或公式根) | - -### 4.3 作图 - -| 英文 | 中文 | 形参 | -|------|------|------| -| `plot` | `绘图` | **`formula`**(或 `expr` 文本), `var`, `min`, `max`;可选 `steps`, `path`, `derivative`, **`grid`**(默认开;`False`/`假` 关) | -| `plot_conic` | `绘圆锥` | `kind`(circle/ellipse/hyperbola/parabola)+ 系数;可选 `path`, `grid` | -| `plot_points` | `绘点列` | `xs`, `ys`;可选 `path`, `grid` | - -返回 **SVG 文本**;坐标轴带箭头与刻度,默认网格;写文件与 view 嵌入规则同前(§5)。 - -`diff` / `simplify` / `expand` / 未完全数值化的 `subs` 返回 **`formula`**,可继续链式调用。 - -示例: - -```markdown -# main - -`f` = -$$ -x^2 - 2 -$$ - -*`roots` = > solve formula=`f` var=x * - -> print text=`roots` - -*`svg` = > plot formula=`f` var=x min=-3 max=3 path=parabola.svg * -``` - ---- - -## 5. 作图:CLI / view / 静态(不变精神) - -| 场景 | 行为 | -|------|------| -| 带 `path=` | 写 SVG 到该路径(沙箱内) | -| CLI 无 path | 自动 `{stem}-plot-{n}.svg` + 一行 `plot: …` | -| view / 导出无 path | 不强制写盘;加入 **plots 产物列表**,Execution 内嵌 | -| view / 导出有 path | 写盘 + 内嵌 | - -不把整段 SVG 默认灌进 CLI stdout。 - ---- - -## 6. 分期 - -| 期 | 交付 | -|----|------| -| **M1** | `Num` + 数值/随机;`Formula` AST + `` `name` = `` + `$$…$$` 赋值绑定 | -| **M2** | `simplify` / `diff` / `subs` / `eval` / 二次 `solve`(高中子集) | -| **M3** | `plot` / `plot_points` / `plot_conic` + view 内嵌 + path 写盘 | -| **M4** | 用户文档 `public/stdlib/math*` · 金样例 · mapping 文档补丁 | - -M1–M3 可在同一发版列车上连续落地;验收以「公式赋值 → 求导 → 作图」一条龙为准。 - ---- - -## 7. 实现要点 - -```text -src/formula/ # 词法/AST/化简/求导/求值(高中规则表) -src/host/math.rs # 数值、随机、对 formula 的 host 入口 -src/host/plot.rs # SVG -lex/parse:空 RHS 赋值 + $$ 围栏 → Expr::Formula -Value::Num / Value::Formula -Interpreter.plots: Vec<Stringimport math:lib/math.mq.md · lib/数学.mq.md -``` - -依赖:纯 Rust;不绑 SymPy。公式复杂度、采样点、SVG 大小设硬上限。 - ---- - -## 8. 刻意不做 - -- `$$:name` 模块级具名绑定(已废除)。 -- 无名 `$$` 自动进运行时。 -- 大学级数 / 完备积分 / 定理证明。 -- **大学线性代数扩展**(见 [ext-linalg.md](ext-linalg.md);不在本库做符号 MatExpr)。 -- 通用隐函数作图引擎。 -- 3D、交互式图表库。 - ---- - -## 9. 验收 - -1. `` `f` = `` + `$$…$$` + `diff` / `solve` / `plot` 金样例(中英库)。 -2. 固定 `seed` 的随机金样例。 -3. `plot` + `path` 在 CLI 落盘;view HTML 含 `<svg`。 -4. `type` 对公式为 `formula`,对浮点为 `num`。 -5. view Structure 将公式赋值显示为绑定,而非 comment。 - ---- - -## 10. 一句话 - -**`` `f` = `` + `$$…$$` 产出 `formula` 值;数学库对它做高中范围的符号运算、求解与作图——数值与随机并行,图在 view 内嵌、在 CLI 写文件。** diff --git a/doc/design/stdlib-mid.md b/doc/design/stdlib-mid.md deleted file mode 100755 index bf79291..0000000 --- a/doc/design/stdlib-mid.md +++ /dev/null @@ -1,172 +0,0 @@ -# 中层标准库(Mid Stdlib) - -| | | -|---|---| -| 状态 | **M1–M6 已落地** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [ext-abi.md](ext-abi.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) · **后续** [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) | -| 目标 | 在接下来数个发版周期内,把「通用编程」能力沉到 **L0.5 宿主 + L1 `.mq.md`**,减少「凡是稍有能力就必须 ABI 插件」的路径依赖 | - ---- - -## 1. 为什么现在做 - -现状分层(已落地): - -```text -L0 内置 print / len / split / … -L0.5 宿主原语 src/host/*(供 L1 包装,作者原则上不直调) -L1 官方库 lib/*.mq.md(嵌入二进制 / 可覆盖) -ext 官方扩展 .mq.md + 可选 cdylib(web / agent / quantum / linalg) -``` - -痛点: - -1. **通用语言能力缺口**:`lib/text` 几乎只是 `trim/split/join`;无正则、无编解码、无哈希、无路径代数、无 CSV……日常脚本要么外联 Python,要么新开插件。 -2. **插件路径过重**:ABI 插件适合**领域热路径**(量子核、公式矩阵、HTTP 服务+SQLite),不适合「再来一个 base64」。每加一个插件都要:crate、Release 资产、`ext add`、CI、WASM 缺口。 -3. **扩展作者被逼进插件**:`ext/**` 禁止 `host_*`。若 L1 没有正则 / 哈希 / 路径,扩展只能 `plugin.load`,导致「库」与「原生模块」边界模糊。 -4. **对照成熟语言**:Go 的 `strings` / `regexp` / `encoding/*` / `crypto` / `path/filepath`、Python 的「难写对才进 stdlib」标准——都把**通用原语**留在语言自带层,把**领域产品**留给第三方。Marqdo 的「通用」应对齐前者;`ext/` 对齐后者。 - -中层标准库 = **在现有 L1 之上、在官方 ext 之下**,专门补「写通用程序必备、又不该做成插件」的那一档。 - ---- - -## 2. 分层命名(本波约定) - -| 名称 | 位置 | 用户导入 | 实现形态 | -|------|------|----------|----------| -| **核心 L1** | 已有 `lib/{fs,sys,time,json,net,math,…}` | 是 | 薄包装 → 已有 `host_*` | -| **中层 L1(Mid)** | 新增 / 加厚 `lib/{re,encoding,hash,path,…}` | 是(仍属 `lib/` / `std/`) | **优先**薄 `host_*` + L1;能纯 `.mq.md` 则纯库 | -| **官方 ext** | `ext/{web,agent,quantum,linalg,ai}` | 显式 `ext/` | `.mq.md`;**仅**领域热路径允许 ABI 插件 | -| **catalog / 用户库** | 发版外收录 | 各自约定 | 应能主要靠 Mid + 核心 L1 写成,**默认无插件** | - -> **不**新开第三棵目录树。中层仍落在 `lib/`,用文档与路线图分期交付,避免 `lib/` vs `lib-mid/` 分裂。 - ---- - -## 3. 准入 / 不准入(宪法) - -### 3.1 进入中层的条件(须同时满足多数) - -| # | 条件 | 说明 | -|---|------|------| -| 1 | **跨领域高频** | 脚本、站点、智能体、教学示例都会用到 | -| 2 | **难写对或不可移植** | 正则、Unicode、密码学、路径跨平台——纯 Marqdo 成本过高 | -| 3 | **解锁「无插件写库」** | 有了它,更多 `ext/` / catalog 可用纯 `.mq.md` | -| 4 | **宿主面积极小** | 一个或少数 `host_*` + 稳定 crate;不把巨型框架链进主二进制 | -| 5 | **API 可长期冻住** | 宁可窄接口,也不提前做成第二个 Requests | - -参考(外部): - -- Python:[stdlib 准入](https://devguide.python.org/developer-workflow/stdlib/) 与 [Language Summit:stdlib 何用](https://blog.python.org/2023/05/the-python-language-summit-2023-what-is.html)——偏「启动器 / 新手脚本 / 难写对的协议」,而非「万物入 std」。 -- Go:日常几乎离不开的 `strings`、`regexp`、`encoding/*`、`crypto`、`path/filepath`、`slices`——对标我们的 Mid 候选,而非 `database/sql` 驱动全家桶。 -- 反面:PEP 594「死电池」——过窄协议、过时格式、与生态脱节的模块不要进 Mid。 - -### 3.2 明确不准入(继续走 ext + 可选插件) - -| 领域 | 原因 | -|------|------| -| HTTP **服务端** / ASGI / 路由框架 | 产品面;已有 `ext/web` | -| SQLite / ORM / 管理后台 | 同上 | -| LLM / 智能体编排 / OKF | `ext/ai` · `ext/agent` | -| 量子线路 / 密度矩阵核 | `ext/quantum` | -| 大学线性代数 CAS / 分解可视化 | `ext/linalg`(公式文档面) | -| 完整图像 / 音视频 / ML | 体积与依赖爆炸 | -| 任意第三方云 SDK | 不属于语言 | - -### 3.3 插件仍保留的边界 - -ABI 插件 **不废除**。规则收紧为: - -```text -若能力可用「少量 host_* + lib/*.mq.md」表达 → 必须走中层,禁止新开官方插件。 -若能力是领域数值核 / 长生命周期服务 / 可选重依赖 → 才允许官方插件。 -``` - -`lib/plugin` 继续服务:本地实验、第三方原生、官方领域包。 - ---- - -## 4. 实现分工(怎么长) - -```text -用户 / catalog / 官方 ext(纯 mq 优先) - │ import re:lib/re.mq.md - ▼ -中层 L1(.mq.md,中英分文件,除 json 类共用外) - │ **> host_re_find …** - ▼ -L0.5 宿主(Rust:regex / sha2 / …) - │ - ▼ -OS / 算法库(精选 crate,默认 features 最小化) -``` - -| 规则 | 说明 | -|------|------| -| `ext/**` 仍禁止 `host_*` | 中层补齐后,ext 经 `lib/re` 等调用 | -| 每个新 `host_*` | 必须有 L1 包装 + 金样 + 中英对称(见 [stdlib-i18n.md](stdlib-i18n.md)) | -| 能纯 mq 的 | 例如在 `table` 上的 `sort_by` 若性能可接受,可先纯库;热路径再下沉 host | -| WASM | 新 host 须标注是否进浏览器构建;不能 WASM 的在文档标 `host-only` | -| 依赖 | 新增 crate 写进 [dependencies.md](dependencies.md) 动机;禁止「顺手」拉大型框架 | - ---- - -## 5. 模块候选总表(按优先级波次) - -完整排期与验收见 [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md)。摘要: - -| 波次 | 模块(英 / 中) | 典型能力 | 主要形态 | -|------|-----------------|----------|----------| -| **M1** | `re` / `正则` · `encoding` / `编码` | match / find / replace;base64 / hex | **done** | -| **M2** | `path` / `路径` · `fs` 加厚 | join / normalize;copy / move / temp | **done** | -| **M3** | `hash` / `哈希` · `secrets` / `机密` | sha256 / hmac;token | **done** | -| **M4** | `csv` / `逗号表` · `text` 加厚 | parse / stringify;contains / replace | **done** | -| **M5** | `table` 加厚 · `cli` / `命令行` | sort / zip;flags | **done** | -| **M6** | `log` / `日志` · `uuid` / `标识` | level 日志;v4 | **done** | -| **可选(Mid1)** | `yaml` | 默认 **不做** | 见 Mid2:优先 TOML | - -**Mid1 刻意延后、现已升格到 Mid2:** 日历/时区、URL 解析 —— 见 [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md)。 - -**仍不准入 Mid:** 连接池、异步 runtime、模板引擎、完整 `collections` 类型系统、HTTP 服务端 / SQLite(`ext/`)。 - ---- - -## 6. 与现有库的关系 - -| 现有 | 中层策略 | -|------|----------| -| `lib/text` | **加厚**,不另起 `strings` 英文名(保持 Marqdo 习惯);中文 `文本` | -| `lib/table` | Mid 集合算法优先挂这里或薄 `listx`;避免与 GFM 表语义打架 | -| `lib/net` | HTTP 客户端保留;编解码类能力与 `encoding` 边界写清(url 组件归谁) | -| `lib/math` | 保持**高中**;哈希 / 安全随机不进 math | -| `lib/json` | 仍只 parse/stringify/quote;CSV/YAML 另库 | -| `lib/plugin` | 不变;文档写明「通用能力请先查 Mid」 | -| `ext/*` | 逐步**改写依赖**:能改用 `lib/re` 的路由/校验,去掉不必要的原生 | - ---- - -## 7. 文档与工程节奏 - -每个 Mid 波次固定流水线(与现有发版习惯对齐): - -1. 本设计不变的前提下,在 roadmap 勾选该波次工作项。 -2. `doc/design/stdlib-<module>.md`(可短)→ `host_*` → `lib/` 中英 → `tests/lib/*` 金样 → `public/features` 短文。 -3. 更新 [stdlib-modules.md](stdlib-modules.md) 模块表。 -4. **不**为 Mid 单开 SemVer 故事;随正常产品发版收进 CHANGELOG「标准库」小节。 -5. 发版技能 / Release 资产:仅当新增 **必须** 随 CLI 分发的东西时改 release 脚本——Mid 默认已嵌入 stdlib,**无** native zip。 - ---- - -## 8. 成功标准(数个版本后) - -1. 用 Mid + 核心 L1 **不加载任何插件**,能写:日志采集脚本、CSV 清洗、带正则的文本管线、带哈希校验的下载器、简单 CLI 工具。 -2. 新的官方 **非领域** 能力默认进 `lib/`,评审时问:「能否不做成插件?」 -3. `ext/web` / `ext/agent` 等仍可有插件,但依赖面写进文档:哪些能力已改走 Mid。 -4. 主二进制体积与依赖可解释;WASM 可用性有清单。 - ---- - -## 9. 一句话 - -**中层标准库把「通用原语」沉回语言自带层,让插件专属于真正的领域引擎——这样 Marqdo 才像一门通用语言,而不是「Markdown + 一堆 .so」。** diff --git a/doc/design/stdlib-mid2.md b/doc/design/stdlib-mid2.md deleted file mode 100755 index d02269e..0000000 --- a/doc/design/stdlib-mid2.md +++ /dev/null @@ -1,139 +0,0 @@ -# 设计:中层标准库第二波(Mid2 · M7–M10) - -| | | -|---|---| -| 状态 | **Accepted · M7–M10 已落地(zip 跳过)** | -| 日期 | 2026-09-09 | -| 缺口盘点 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) | -| 路线图 | [stdlib-mid2.md](../roadmap/stdlib-mid2.md) | -| 宪法 | [stdlib-mid.md](stdlib-mid.md) §3(准入 / 不准入 **不变**) | -| 目标 | 在 M1–M6 之上补「日历 · URL · 配置 · HTML 安全 · fs 再厚」,仍保持宿主面积极小 | - ---- - -## 0. 一句话 - -**Mid2 = 第二档通用原语,不是第二套 stdlib。** 仍落在 `lib/` + 薄 `host_*`;禁止借机引入 YAML 全家桶、HTTP 服务端、数据库。 - ---- - -## 1. 分层与禁止 - -| 允许 | 禁止 | -|------|------| -| 新 `lib/*.mq.md` 中英对偶 | 新开 `lib-mid2/` 目录树 | -| 少数 `host_datetime_*` / `host_url_*` / `host_toml_parse` | 为 Mid 新增 ABI 插件 | -| 加厚既有 `fs` / `encoding` / `net` / `text` | 把 `ext/web` 能力下沉进 `lib/net` 服务端 | -| TOML **只读** | 完整 YAML 1.2、任意对象反序列化 | -| HTML **转义** | 模板引擎 / CSS 选择器引擎 | - ---- - -## 2. M7 — `datetime` + `url` - -### 2.1 `lib/datetime.mq.md` / `lib/日期时间.mq.md` - -| 函数(英) | 中文建议 | 行为 | -|------------|----------|------| -| `now` | `现在` | 返回结构化时刻(见下)或 ISO 文本(二选一,实现时锁定) | -| `from_unix` / `to_unix` | `自戳` / `成戳` | 秒级;可选 `ms` | -| `parse` | `解析` | 支持 RFC3339 / 常见 `YYYY-MM-DD[ HH:MM:SS]` | -| `format` | `格式化` | strftime 子集或命名样式 `rfc3339`/`date`/`time` | -| `add` | `加` | `days`/`hours`/`minutes`/`seconds` 具名 | -| `in_zone` | `时区` | IANA 名或 `+08:00`;失败 → 诊断 | - -**结构化时刻(建议 map)**:`{unix, zone, iso}` 或宿主不透明柄 + `_type=datetime`。优先 **map + 稳定字段**,便于 GFM/table 协作。 - -**刻意不做**:农历、营业日、完整 tzdb 热更新 UI、闰秒政治。 - -### 2.2 `lib/url.mq.md` / `lib/地址.mq.md`(或并入 `net`) - -| 函数 | 行为 | -|------|------| -| `parse` | → `{scheme, userinfo, host, port, path, query, fragment}` | -| `query_parse` | `a=1&b=2` → map(多值用列表) | -| `query_stringify` | map → query | -| `join` | base + relative(可选,可二期) | - -既有 `net.url_encode` **保留**;文档写清:编码单段用 `net`/`encoding`,解析整 URL 用 `url`。 - -**验收**:金样解析带 query 的 HTTPS URL;往返 query。 - ---- - -## 3. M8 — `toml` + `html` + `encoding` 加厚 - -### 3.1 `lib/toml.mq.md` / `lib/Toml.mq.md`(或 `配置表`) - -| 函数 | 行为 | -|------|------| -| `parse` | TOML 文本 → Marqdo map/list(只读) | - -**不做** `stringify`(首版);需要写出时继续用 JSON。动机对齐 PEP 680:配置引导,而非通用文档格式战争。 - -### 3.2 HTML 转义 - -二选一(实现时定一): - -- A:`lib/html.mq.md` · `escape` / `unescape` -- B:`text.html_escape` / `text.html_unescape` - -推荐 **A**(安全语义独立可见)。 - -### 3.3 `encoding` 加厚 - -| 函数 | 行为 | -|------|------| -| `base32_encode` / `base32_decode` | RFC 4648 | -| (可选)`percent_decode` | 与 `url` 协作 | - ---- - -## 4. M9 — `fs` 加厚 - -| 函数 | 行为 | -|------|------| -| `make_dirs` | 递归创建 | -| `remove_tree` | 递归删除(目录) | -| `stat` | `{size, mtime_unix, is_file, is_dir}` | -| `walk` | 返回路径列表(深度优先或广度;文档锁定) | - -**不做**:权限 ACL、watch/inotify、硬链接全家桶。 - ---- - -## 5. M10 — 收口糖(可选) - -| 项 | 说明 | -|----|------| -| `lib/stats` 或 `math.mean`/`median`/`stdev` | 极薄;非 pandas | -| `log` 结构化字段 | 可选 `fields=` map;非完整 slog 生态 | -| `zip` 读写 | **默认跳过**;有明确 Release 需求再开 | - ---- - -## 6. 宿主与 WASM - -| Host | WASM | -|------|------| -| `datetime` / `url` / `toml` / `html` / `fs.stat` | 尽量可进;IANA tz 数据体积需评估(可 host-only + 文档标注) | -| `fs.walk` / `remove_tree` | host-only 可接受 | - -新 crate 写进 [dependencies.md](dependencies.md);禁止顺手拉大型框架。 - ---- - -## 7. 作者面风格 - -- 中英分文件;形参表声明全部可选并转发 `host_*`。 -- 数据优先 GFM / `table`;`json` 仍只 parse/stringify/quote。 -- 每波:设计短文 → host → lib → `tests/lib/*` → `public/features` 短页。 - ---- - -## 8. 完成定义(Mid2 整包) - -1. 作者可用 `datetime` + `url` + `toml.parse` + `html.escape` 写配置驱动脚本,无需 foreign。 -2. `fs.stat` / `make_dirs` 金样绿。 -3. 研究文高优先级缺口标 closed;YAML/模板/sqlite 仍标明 won't。 -4. [stdlib-modules.md](stdlib-modules.md) 总表更新;`stdlib.md` 状态改为 Mid2 进行中/完成。 diff --git a/doc/design/stdlib-modules.md b/doc/design/stdlib-modules.md deleted file mode 100755 index 0f2b6cf..0000000 --- a/doc/design/stdlib-modules.md +++ /dev/null @@ -1,216 +0,0 @@ -# 标准库 L1 模块 - -直接阅读并导入标准库单文件,例如 [文件](../../lib/文件.mq.md)和[表](../../lib/表.mq.md)。每个文件自身就是手册,函数标题下给出参数表、返回契约和动作说明;不要求额外 index。模块分层与历史波次见下表,当前规范见[标准库说明](stdlib-handbook.md)。 - -| | | -|---|---| -| 状态 | **核心已落地**;**Mid M1–M6 已落地**;**Mid2 规划中** · [stdlib-mid2.md](stdlib-mid2.md) / [roadmap/stdlib-mid2.md](../roadmap/stdlib-mid2.md) | -| 日期 | 2026-09-08 | -| 原则 | 全部经 frontmatter **导入**;除 JSON 外中英分文件;内核保持少而精;**通用能力优先 Mid,插件留给领域核** | -| 相关 | [stdlib.md](stdlib.md) · [stdlib-i18n.md](stdlib-i18n.md) · [stdlib-mid.md](stdlib-mid.md) · [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) · [ext-abi.md](ext-abi.md) · [ext-llm.md](ext-llm.md) · [ext-agent.md](ext-agent.md) · [**module-namespace.md**](module-namespace.md)(导入命名空间;**M1/M2 已落地**:`库.成员` / `库.对象.成员` / `use`) | - ---- - -## 1. 目标 - -在 `lib/text`·`lib/文本`、`lib/table`·`lib/表` 之上,把 Marqdo 推进到可写日常脚本与可选原生扩展。标准库**必须导入**才可用。 - -| 模块族 | 英文库 | 中文库 | 状态 | -|--------|--------|--------|------| -| 文本 | `lib/text.mq.md` | `lib/文本.mq.md` | 已有 + **Mid M4** 加厚 | -| **正则** | `lib/re.mq.md` | `lib/正则.mq.md` | **Mid M1** | -| **编解码** | `lib/encoding.mq.md` | `lib/编码.mq.md` | **Mid M1** + Mid2 M8 base32 | -| **路径** | `lib/path.mq.md` | `lib/路径.mq.md` | **Mid M2** | -| **哈希** | `lib/hash.mq.md` | `lib/哈希.mq.md` | **Mid M3** | -| **机密** | `lib/secrets.mq.md` | `lib/机密.mq.md` | **Mid M3** | -| **逗号表** | `lib/csv.mq.md` | `lib/逗号表.mq.md` | **Mid M4** | -| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有 + Mid M4/M5:`sort`/`unique`/`zip`/… | -| **命令行** | `lib/cli.mq.md` | `lib/命令行.mq.md` | **Mid M5** | -| **日志** | `lib/log.mq.md` | `lib/日志.mq.md` | **Mid M6** + Mid2 M10 `fields=` | -| **标识** | `lib/uuid.mq.md` | `lib/标识.mq.md` | **Mid M6** | -| **日期时间** | `lib/datetime.mq.md` | `lib/日期时间.mq.md` | **Mid2 M7** | -| **地址** | `lib/url.mq.md` | `lib/地址.mq.md` | **Mid2 M7** | -| **配置表** | `lib/toml.mq.md` | `lib/配置表.mq.md` | **Mid2 M8** | -| **超文本** | `lib/html.mq.md` | `lib/超文本.mq.md` | **Mid2 M8** | -| **统计** | `lib/stats.mq.md` | `lib/统计.mq.md` | **Mid2 M10** | -| 浏览器效应 | `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM 客户端效应助手(GFM + helpers;勿用 `json.set` 链) | -| 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 + Mid M2 + **Mid2 M9**:`make_dirs` / `remove_tree` / `stat` / `walk` | -| 系统 | `lib/sys.mq.md` | `lib/系统.mq.md` | 已有(含 `load_dotenv`) | -| 时间 | `lib/time.mq.md` | `lib/时间.mq.md` | 已有 | -| JSON | `lib/json.mq.md` | **同文件** | **仅** parse / stringify / quote;集合请用 table / GFM | -| 网络 | `lib/net.mq.md` | `lib/网络.mq.md` | 已有(HTTPS + headers) | -| 数学 | `lib/math.mq.md` | `lib/数学.mq.md` | 已有 | -| 外联 | `lib/foreign.mq.md` | `lib/外联.mq.md` | 已有 | -| **插件** | `lib/plugin.mq.md` | `lib/插件.mq.md` | **已有**(加载 C ABI 共享库) | -| **自写回** | `lib/writeback.mq.md` | `lib/自写回.mq.md` | **已有**(Jupyter 式输出写回) | -| **子任务** | `lib/subtask.mq.md` | `lib/子任务.mq.md` | **已有**(OS 子进程 + KillOnDrop) | - -官方可选扩展(**非** stdlib):`ext/llm` · `ext/agent` · `ext/web` · `ext/quantum` · `ext/linalg` — 见各 `ext-*.md`。 - -**中层已落地:** M1–M6(含 log / uuid)— 见 [stdlib-mid.md](stdlib-mid.md) · [stdlib-log-uuid.md](stdlib-log-uuid.md)。 - -**Mid2:** **M7–M10 done**(datetime / url / toml / html / base32 / fs++ / stats / log.fields;zip 跳过)— [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-stats-log.md](stdlib-stats-log.md)。 - -设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。 - ---- - -## 2. 分层与实现分工 - -```text -用户 .mq.md - │ import fs:lib/fs.mq.md / import llm:ext/llm.mq.md - ▼ -L1 官方库 / 官方 ext(.mq.md) - │ - ▼ -L0.5 宿主原语(Rust)或 原生插件(ABI v1) - │ - ▼ -OS / HTTP / 时钟 / 共享库 … -``` - -| 层 | 谁实现 | 用户是否直接调用 | -|----|--------|------------------| -| **L0** | 解释器内置 | 是(`print`/`len`/…) | -| **L0.5 宿主原语** | Rust(`src/host/`) | **原则上否**;供 L1 包装;ABI v2 `host_query` 仅插件可调 | -| **L1 官方库** | `lib/*.mq.md` | **是** | -| **官方 ext** | `ext/*.mq.md`(+ 可选 ABI 插件) | **是**(需显式导入 `ext/`);**禁止** `host_*`,经 `lib/*` 或插件注册名 | - -> **已变更(M1+M2)**:[module-namespace.md](module-namespace.md) — 取消跨文件扁平合并;L1/ext 经**裸名点号路径**调用(`time.parse`、`agent.agent`;M2:`库.对象.成员` + `use`),库名不加反引号;实例方法须 `` `var`.method ``;不再靠 import 顺序覆盖同名。 - -### 2.1 L1 薄包装 → 宿主(命名空间后必读) - -点号路径 `net.http_post` / `json.stringify` 等解析到 **`lib/*.mq.md` 的 `##` 函数**,再转发 `host_*`。未在包装形参表声明的可选实参会被**静默丢弃**(曾导致 live agent 401:`Authorization` 等 `headers` 从未到达宿主)。 - -| 规则 | 说明 | -|------|------| -| 每个 `host_*` 包装 | 须在 `+` 形参表声明**全部**宿主可选参数,默认 `None`,并在 `**> host_…**` 中**原样转发** | -| `http_post` / `提交` | `content_type=None` 时宿主按默认 JSON charset 处理 | -| 已对齐(2026-08-07) | `net`/`网络`(headers、content_type、body)、`sys`/`系统`(load_dotenv、exec)、`ext/ai/llm`(load_env / 加载环境 path)、`json.stringify` indent、`foreign`/`外联` stdin、`math`/`数学` plot*/solve 可选项 | - -**无**扁平合并回退;**无**裸名双轨兼容。 - ---- - -## 3. 核心模块 API(摘要) - -文件 / 系统 / 时间 / JSON / 网络 API 见下文历史草图(已实现)。补充: - -### 3.2 系统 — 已含 dotenv - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `load_dotenv` | `加载环境` | 可选 `path` | 新写入的键数量;缺文件 → `0`;不覆盖已有环境变量 | - -### 3.4 JSON — 已含 `quote` - -| 函数 | 形参 | 结果 | -|------|------|------| -| `quote` | `text` | JSON 字符串字面量(含引号) | - -### 3.5 网络 — HTTPS - -仅 **HTTP / HTTPS**(ureq);可选 `headers=`(map)、`content_type=`。 - -### 3.6 插件 — `plugin` / `插件` - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `load` | `加载` | `path` / `路径` | 注册函数个数 | -| `unload` | `卸载` | (无) | `None` | -| `list` | `列出` | (无) | 已注册名列表 | - -契约:[ext-abi.md](ext-abi.md)。路径受 cwd/fs_root 沙箱约束。 - -### 3.1–3.5 历史 API 草图 - -#### 文件 — `fs` / `文件` - -| 英文 | 中文 | 形参(英 / 中) | 结果 | -|------|------|-----------------|------| -| `read_text` | `读文本` | `path` / `路径` | 文本 | -| `write_text` | `写文本` | `path`, `text` / `路径`, `内容` | `None` | -| `append_text` | `追加文本` | 同上 | `None` | -| `exists` | `存在` | `path` / `路径` | 布尔 | -| `list_dir` | `列目录` | `path` / `路径` | 文本列表 | -| `make_dir` | `建目录` | `path` / `路径` | `None` | -| `remove` | `删除` | `path` / `路径` | `None` | - -#### 系统 — `sys` / `系统` - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `env_get` | `取环境` | `name` / `名` | 文本或 `None` | -| `env_set` | `设环境` | `name`, `value` / `名`, `值` | `None` | -| `load_dotenv` | `加载环境` | 可选 `path` | 见上 | -| `args` | `参数表` | (无) | 文本列表 | -| `cwd` | `工作目录` | (无) | 文本 | -| `exit` | `退出` | `code` / `码` | 不返回 | -| `exec` | `执行` | `cmd`, 可选 `args` | 退出码 | - -#### 时间 — `time` / `时间` - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `now_unix` | `此刻秒` | (无) | 整数(Unix 秒) | -| `now_ms` | `此刻毫秒` | (无) | 整数 | -| `format` | `格式化` | `unix`, `pattern` / `秒`, `格式` | 文本 | -| `sleep_ms` | `睡眠毫秒` | `ms` / `毫秒` | `None` | -| `parse` | `解析时间` | `text`, `pattern` / `内容`, `格式` | 整数秒或诊断失败 | - -#### JSON — `json` - -| 函数 | 形参 | 结果 | -|------|------|------| -| `parse` | `text` | 值 | -| `stringify` | `value`, 可选 `indent` | JSON 文本 | -| `get` | `value`, `key` | 值或 `None` | -| `keys` | `value` | 文本列表 | -| `quote` | `text` | JSON 字符串字面量 | - -#### 网络 — `net` / `网络` - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `http_get` | `获取` | `url` / `地址` | 响应文本 | -| `http_post` | `提交` | `url`, `body`, 可选 `content_type` / `headers` | 同上 | -| `url_encode` | `编码地址` | `text` / `内容` | 文本 | - -**路径字面量:** 具名实参里 `path=a/b` 会被解析成除法。请用无斜杠文件名,或先赋给变量再传入。 - ---- - -## 4. 中英路径总表 - -```text -lib/ - text.mq.md / 文本.mq.md - table.mq.md / 表.mq.md - fs.mq.md / 文件.mq.md - sys.mq.md / 系统.mq.md - time.mq.md / 时间.mq.md - json.mq.md # 中英共用 - net.mq.md / 网络.mq.md - math.mq.md / 数学.mq.md - foreign.mq.md / 外联.mq.md - plugin.mq.md / 插件.mq.md - -ext/ # 非 stdlib - llm.mq.md / 大模型.mq.md - agent.mq.md / 智能体.mq.md -``` - -别名:`std/…` ≡ `lib/…`。扩展解析:`MARQDO_EXT` / `./ext` / 二进制旁 `ext/`。 - ---- - -## 5. 安全与 view / 静态导出 - -`marqdo run`、live `view`、`view output` 对标准库 **默认同一套能力**。差异仅在软退出 / sleep 钳制。相对路径落在源文件目录(或 view 根)下,防止 `..` 逃逸。插件路径同沙箱。 - ---- - -## 6. 一句话 - -**L1 含文件 / 系统 / 时间 / JSON / 网络 / 数学 / 外联 / 插件;`ext/` 为可选官方扩展(llm、agent)。** diff --git a/doc/design/stdlib-path.md b/doc/design/stdlib-path.md deleted file mode 100755 index 11b61eb..0000000 --- a/doc/design/stdlib-path.md +++ /dev/null @@ -1,33 +0,0 @@ -# `lib/path` — 路径代数(Mid M2) - -| | | -|---|---| -| 状态 | **已落地(M2)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) | -| 导入 | `lib/path.mq.md` · `lib/路径.mq.md` | -| Host | `host_path_*`(`std::path`;无 I/O、不经 `fs_root`) | - ---- - -## 1. API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `join` | `拼接` | `a`, `b` | 文本路径 | -| `split` | `拆分` | `path` | 组件文本列表(去空段) | -| `file_name` | `文件名` | `path` | 最后一段;根路径可为空文本 | -| `parent` | `父目录` | `path` | 父路径文本;无父则 `"."` | -| `extension` | `扩展名` | `path` | 不含点;无扩展名为 `""` | -| `normalize` | `规范化` | `path` | 清理 `.` / `..`(纯字符串,不访问磁盘) | -| `is_absolute` | `是绝对` | `path` | 布尔 | - -## 2. 语义 - -- 分隔符与绝对路径判定跟随 **宿主 OS**(Linux CI 为 `/`)。 -- **不做** I/O;逃逸检查仍由 `lib/fs` 在读写时执行。 -- `join`:若 `b` 为绝对路径,结果为 `b`(同 `Path::join`)。 - -## 3. 刻意不做(v1) - -`glob`、符号链接解析、`relative_to`、Windows UNC 专项文档。 diff --git a/doc/design/stdlib-re.md b/doc/design/stdlib-re.md deleted file mode 100755 index 7a91ed1..0000000 --- a/doc/design/stdlib-re.md +++ /dev/null @@ -1,33 +0,0 @@ -# `lib/re` — 正则(Mid M1) - -| | | -|---|---| -| 状态 | **已落地(M1)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) | -| 导入 | `lib/re.mq.md` · `lib/正则.mq.md` | -| Host | `host_re_*`(`regex` crate,默认 Unicode) | - ---- - -## 1. API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `is_match` | `匹配` | `text`, `pattern` | 布尔 | -| `find` | `查找` | `text`, `pattern` | 首个匹配文本,或 `None` | -| `find_all` | `查找全部` | `text`, `pattern` | 文本列表 | -| `replace` | `替换` | `text`, `pattern`, `with`, 可选 `count` | 文本(`count` 缺省 = 全部) | -| `split` | `拆分` | `text`, `pattern` | 文本列表 | - -非法 pattern → 诊断失败(含 crate 错误信息)。 - -## 2. 语义 - -- 引擎:Rust [`regex`](https://docs.rs/regex)(无回溯引用;与 RE2 同族限制)。 -- 按 **UTF-8 文本**匹配,不做字节模式。 -- `find` / `find_all` 返回整段匹配(不含捕获组拆分;捕获组 v1 不做)。 - -## 3. 刻意不做(v1) - -命名捕获、替换回调、`Regex` 对象缓存 API、字节模式。 diff --git a/doc/design/stdlib-secrets.md b/doc/design/stdlib-secrets.md deleted file mode 100755 index d047d34..0000000 --- a/doc/design/stdlib-secrets.md +++ /dev/null @@ -1,24 +0,0 @@ -# `lib/secrets` — 安全随机令牌(Mid M3) - -| | | -|---|---| -| 状态 | **已落地(M3)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-hash.md](stdlib-hash.md) · [stdlib-mid.md](stdlib-mid.md) | -| 导入 | `lib/secrets.mq.md` · `lib/机密.mq.md` | -| Host | `host_secrets_*`(`getrandom`) | - ---- - -## 1. API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `token_hex` | `十六进制令牌` | 可选 `n`(字节数,默认 16) | 小写 hex,长度 `2*n` | -| `token_urlsafe` | `网址安全令牌` | 可选 `n`(字节数,默认 16) | URL-safe Base64(无填充) | - -**不要**用 `math.random` / `math.seed` 生成令牌。 - -## 2. 刻意不做 - -密钥派生、加密/解密、密码哈希。 diff --git a/doc/design/stdlib-stats-log.md b/doc/design/stdlib-stats-log.md deleted file mode 100755 index 5307efa..0000000 --- a/doc/design/stdlib-stats-log.md +++ /dev/null @@ -1,30 +0,0 @@ -# 设计:`lib/stats` / `lib/统计` 与 `log.fields`(Mid2 M10) - -| | | -|---|---| -| 状态 | **已落地** | -| 日期 | 2026-09-09 | -| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §5 | -| 宿主 | `src/host/stats.rs` · `host_stats_*`;`log::line` 可选 `fields` | - ---- - -## 1. `lib/stats` - -| EN | ZH | 行为 | -|----|-----|------| -| `mean` | `均值` | 算术平均 → Num | -| `median` | `中位数` | 排序后中位;偶数取两中点平均 | -| `stdev` | `标准差` | **样本**标准差(n≥2) | - -**不做** dataframe、分位数全家桶、加权统计。 - -## 2. `log` `fields=` - -各级别函数可选 `fields`(map)。宿主拼到行尾:`INFO msg key=val …`(map 插入序)。 - -**不做** 远程 sink、结构化 JSON 日志协议。 - -## 3. zip - -按路线图 **默认跳过**。 diff --git a/doc/design/stdlib-subtask.md b/doc/design/stdlib-subtask.md deleted file mode 100755 index 3b635b3..0000000 --- a/doc/design/stdlib-subtask.md +++ /dev/null @@ -1,29 +0,0 @@ -# 子任务标准库(subtask) - -| | | -|---|---| -| 状态 | v2 | -| 库 | `lib/subtask.mq.md` · `lib/子任务.mq.md` | - -## 定位 - -**并发**执行单元。`spawn` 四选一: - -| 参数 | 执行方式 | `join` / `wait` 返回值 | -|------|----------|------------------------| -| `path=` | `marqdo run <file> --emit-result <tmp>` 子进程 | map `{ code, value, stdout?, stderr? }`(`# main` 返回值;quiet 时 piped 捕获 I/O 尾部,不 inherit TTY) | -| `fn=` + 可选 `args=` | 当前入口模块中的函数(进程内线程) | 函数返回值 `Value` | -| `code=` | 外联代码块(`Value::Code`)子进程 | stdout `Text` | -| `lang=` + `source=` | 外联源码子进程 | stdout `Text` | - -`args=`:文件子任务为 `List`(命令行参数);函数子任务为 `Map`(形参绑定)或 `List`(按 `arg0`… 命名)。 - -`quiet=` / `静默=`(默认 `True`):仅影响 **文件** 子任务的 **TTY**。默认 **piped 捕获** stdout/stderr(父终端不被污染,`wait` map 带截断后的 `stdout`/`stderr` 供父智能体观察);`False` 时继承父进程 stdout/stderr(map 中 I/O 字段为空)。**答案载荷仍以 `# main` 返回值为主**(经 `--emit-result` 旁路)。外联子任务仍经管道收集 stdout 供 `join` 返回,不受此参数影响。 - -**事件转发(文件子任务)**:spawn 时设置 `MARQDO_EVENT_FORWARD=<临时 ndjson>`;子进程内 `EventBus.publish` 追加写入该文件;父在 `wait` 阻塞期间 tail 并 republish(加 `source=child`)。这样子 LLM `stream=True` 的 token 能进 `marqdo view` SSE,而不破坏 quiet TTY 契约。函数子任务在同进程内,本来就共享 EventBus。 - -父进程结束(含 panic)时 **KillOnDrop** 终止所有文件/外联子进程;函数线程标记为 killed 并 detach(无法强杀 OS 线程)。 - -`poll` → `{ status: running | done | failed, … }`;函数 done 时含 `value`,进程/外联 failed 时含 `code` 或 `error`。 - -Host:`host_subtask_*`(`src/host/subtask.rs`)。 diff --git a/doc/design/stdlib-table.md b/doc/design/stdlib-table.md deleted file mode 100755 index d4be13e..0000000 --- a/doc/design/stdlib-table.md +++ /dev/null @@ -1,84 +0,0 @@ -# `lib/table` / `lib/表` — 列表与字典 - -| | | -|---|---| -| 状态 | **已落地**(可用级集合 API) | -| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [table-cell-expressions.md](table-cell-expressions.md) · [roadmap/tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) | - ---- - -## 1. 读写对 - -| 读 | 写 | -|----|----| -| 链接取元 `[key](xs)` / `[key](m)` / 嵌套 `[1]([a](m))`(脚注 `` `m`[^k] `` 仍兼容) | **`table.put` / `表.改`** | - -`put` / `改` 的 `at=`(`于=`)与取元同构:文本键、**1-based** 整数下标,或键/下标组成的路径列表。 - -```markdown ---- -import: - table: lib/table.mq.md ---- - -# main - -**`h` = [table.put] in=None at="Authorization" value="Bearer-x"** - -`xs` = - -| v | -|---| -| a | -| b | - -**`xs` = [table.put] in=`xs` at=1 value="A"** -**打印 内容=[Authorization](h)** -``` - -`in=None` 且 `at=` 为单个文本键 → 新建单键字典。值一律不可变更新(返回新集合)。 - ---- - -## 2. 索引约定 - -| API | 基数 | -|-----|------| -| `put` / `改` 路径中的整数;脚注 `[^n]` | **1-based** | -| `at` / `row_at` / `set_at` / `insert` / `remove_at` / `slice` / `index_of` | **0-based** | - ---- - -## 3. API 摘要(EN ↔ ZH) - -| EN | ZH | 说明 | -|----|----|------| -| `put` | `改` | 按路径改一元(首选写入) | -| `len` / `rows` | `长度` / `行数` | 长度 | -| `at` / `row_at` | `取` / `取行` | 0-based 取元 | -| `append` / `prepend` / `concat` | `追加` / `前插` / `拼接` | 列表 | -| `insert` / `set_at` / `remove_at` / `pop` | `插入` / `改位` / `删位` / `弹出` | 列表位操作 | -| `first` / `last` / `slice` | `首` / `末` / `切片` | | -| `contains` / `index_of` / `reverse` | `含有` / `下标` / `反转` | | -| `clear` | `清空` | 列表或字典 | -| `get` / `set` / `delete` / `has` | `取键` / `设` / `删键` / `有键` | 浅层字典 | -| `keys` / `values` / `items` / `merge` / `size` | `键表` / `值表` / `项表` / `合并` / `键数` | | -| `empty_list` / `empty_map` | `空表` / `空字典` | | - -嵌套改写优先 `put`/`改`;`set`/`set_at` 仅浅层。 - ---- - -## 4. 与 `lib/json` - -| 用途 | 用 | -|------|----| -| 解析 / 序列化 / `quote` | `json.parse` · `json.stringify` · `json.quote` | -| 集合读写 | **`table.*` / `表.*`** | -| 兼容 | `json.set` / `json.append` / `json.get` / `json.keys` 仍为别名,新代码勿依赖 | - ---- - -## 5. 宿主 - -`host_collection_put` + list/map 原语(见 `src/host/collection.rs`)。作者面经 `lib/table` / `lib/表` 调用,不直接写 `host_*`。 diff --git a/doc/design/stdlib-text-mid.md b/doc/design/stdlib-text-mid.md deleted file mode 100755 index 1cc8715..0000000 --- a/doc/design/stdlib-text-mid.md +++ /dev/null @@ -1,30 +0,0 @@ -# `lib/text` 加厚(Mid M4) - -| | | -|---|---| -| 状态 | **已落地(M4)** | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-csv.md](stdlib-csv.md) · [stdlib-mid.md](stdlib-mid.md) | -| 导入 | `lib/text.mq.md` · `lib/文本.mq.md` | -| Host | `host_text_*`(Unicode 大小写 / 子串;非正则替换) | - ---- - -## 1. 新增 API - -| 英文 | 中文 | 形参 | 结果 | -|------|------|------|------| -| `contains` | `包含` | `text`, `sub` | 布尔 | -| `starts_with` | `开头是` | `text`, `prefix` | 布尔 | -| `ends_with` | `结尾是` | `text`, `suffix` | 布尔 | -| `replace` | `替换` | `text`, `old`, `new`, 可选 `count` | 文本(字面替换,非正则) | -| `to_upper` | `大写` | `text` | 文本(Unicode) | -| `to_lower` | `小写` | `text` | 文本 | -| `repeat` | `重复` | `text`, `n` | 文本 | -| `pad` | `填充` | `text`, `width`, 可选 `fill`=`" "`,可选 `align`=`left`/`right`/`center` | 文本 | - -保留原有 `str_trim` / `str_split` / `str_join`(及中文去空白/拆分/拼接)。 - -## 2. 刻意不做 - -正则替换(用 `lib/re`)、完整 `format` 模板引擎。 diff --git a/doc/design/stdlib-toml.md b/doc/design/stdlib-toml.md deleted file mode 100755 index 261900b..0000000 --- a/doc/design/stdlib-toml.md +++ /dev/null @@ -1,24 +0,0 @@ -# 设计:`lib/toml` / `lib/配置表`(Mid2 M8) - -| | | -|---|---| -| 状态 | **已落地** | -| 日期 | 2026-09-09 | -| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §3.1 | -| 宿主 | `src/host/toml_ops.rs` · `host_toml_parse`(手写子集,无 `toml` crate) | - ---- - -## 1. API - -| EN | ZH | 行为 | -|----|-----|------| -| `parse` | `解析` | TOML 文本 → map/list | - -**不做** `stringify`;写出继续用 JSON。 - -## 2. 子集 - -支持:`#` 注释、基本/字面字符串、int/float/bool、标量数组、`[table]` 与 dotted key。 - -**不支持:** `[[array of tables]]`、内联表、TOML datetime、多行字符串。 diff --git a/doc/design/stdlib-url.md b/doc/design/stdlib-url.md deleted file mode 100755 index e1beeed..0000000 --- a/doc/design/stdlib-url.md +++ /dev/null @@ -1,24 +0,0 @@ -# 设计:`lib/url` / `lib/地址`(Mid2 M7) - -| | | -|---|---| -| 状态 | **已落地** | -| 日期 | 2026-09-09 | -| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §2.2 | -| 宿主 | `src/host/url_ops.rs` · `host_url_*`(手写子集,无 `url` crate) | - ---- - -## 1. 与 `net.url_encode` - -| API | 用途 | -|-----|------| -| `net.url_encode` | **单段** form 编码(空格→`+`) | -| `url.parse` | 整 URL → `{scheme,userinfo,host,port,path,query,fragment}` | -| `url.query_parse` / `query_stringify` | 查询串 ↔ map(重复键→列表;空格→`%20`) | - -## 2. 解析子集 - -`scheme://[userinfo@]host[:port]/path[?query][#fragment]`,含 IPv6 `[addr]`。缺 path 时规范为 `/`。 - -**不做**:相对 URL join、完整 WHATWG 边角、IDNA 规范化(host 原样保留)。 diff --git a/doc/design/stdlib-writeback.md b/doc/design/stdlib-writeback.md deleted file mode 100755 index 44da73c..0000000 --- a/doc/design/stdlib-writeback.md +++ /dev/null @@ -1,76 +0,0 @@ -# 自写回标准库(writeback) - -| | | -|---|---| -| 状态 | v1 已落地 | -| 日期 | 2026-08-07 | -| 库 | `lib/writeback.mq.md` · `lib/自写回.mq.md` | - -## 定位 - -**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` → `marqdo view`(及静态 `view output`)在对应语句下显示 **output-card**,并在源码面用 **writeback** 样式标出块本身。 - -## 存储格式(两种,可并存) - -### 1. HTML 注释(文本 / 结构化输出) - -```markdown -*`n` = > len value=`xs` * -<!-- marqdo-out -42 ---> -``` - -命名槽(智能体成功/失败互不覆盖): - -```markdown -<!-- marqdo-out ok -status=ok result=… ---> -<!-- marqdo-out error -pending ---> -``` - -### 2. Markdown 图片(生成图 / 审计友好) - -当 `value` **看起来像图片引用**(扩展名 `.png` / `.jpg` / `.jpeg` / `.gif` / `.webp` / `.svg` / …,或 `data:image/…`)时,`record` **自动**写成: - -```markdown -![marqdo-out](plots/out.svg) -![marqdo-out ok](plots/ok.png) -``` - -- 普通 Markdown 预览即可看见图;view / 静态站额外加 writeback 标记与 output-card 中的 `<img>`。 -- 非图片路径仍走注释块;把非图片硬写成 `![marqdo-out](…)` 时扫描会忽略(校验失败)。 -- `list` / `scan_path` 结果带 `kind`: `comment` | `image`。 - -### 共用规则 - -- 标记字为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号** -- 默认在**调用行下方**插入或替换紧邻**无键**块 -- `at_end=true`:替换文件末尾的**无键**块 -- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽;`ensure` 在缺失时写入占位且不覆盖已有正文 -- `line=` / `行=`:显式锚点行号;主机侧有全局互斥锁 - -### 替换跨度与空行 - -替换 `<!-- marqdo-out … -->` 时,被替换跨度**包含**注释块结束 `-->` 后的**单个**换行符(不把该换行留在文件里)。这样多次 `record` **不会**在块下方累积多余空行。 - -命名槽仍锚在调用行(如 `step` / `写回`)下方;整簇结束后保留**一条**有意空行即可,且应稳定。 - -## API - -| EN | ZH | 说明 | -|----|-----|------| -| `record` | `写回` | `value=`;可选 `at_end`、`key`、`line` | -| `get` | `取` | 可选 `at_end`、`key`、`line` | -| `clear` | `清除` | 可选 `at_end`、`key`、`line` | -| `ensure` | `确保` | `key=` + 可选 `placeholder=`、`line=`;槽已存在则不动 | -| `list` | `列出` | 全文所有输出块(命名槽含 `key` 字段) | - -可选参数语法:`` + `参数名`=默认值 ``(与现有参数列表兼容)。 - -Host:`host_writeback_*`(`src/host/writeback.rs`);智能体侧经 `lib/subtask` 异步调用写回,避免阻塞推理主路径。 - -**与 `ext/ai/agent`:** `## step` / `## 单步` 在 D2 起 **默认自动** `record` 到 `ok`/`error` 槽(参数 `writeback=` / `写回=` 可关)。多步工作簿依赖此默认,见 [ext-agent-plan.md](ext-agent-plan.md) · [ext-agent.md](ext-agent.md)。 diff --git a/doc/design/stdlib.md b/doc/design/stdlib.md deleted file mode 100755 index b8157eb..0000000 --- a/doc/design/stdlib.md +++ /dev/null @@ -1,112 +0,0 @@ -# 标准库(P2) - -| | | -|---|---| -| 状态 | **S0–S3 + 核心 L1 + Mid M1–M6 + Mid2 M7–M10 已落地** | -| 日期 | 2026-09-09 | -| 相关 | [keywords.md](keywords.md) · [objects.md](objects.md) · [call-arguments.md](call-arguments.md) · [lib-code-as-docs.md](lib-code-as-docs.md) · [stdlib-i18n.md](stdlib-i18n.md) · [stdlib-modules.md](stdlib-modules.md) · [**stdlib-mid.md**](stdlib-mid.md) · [**stdlib-mid2.md**](stdlib-mid2.md) · [module-namespace.md](module-namespace.md) · [ext-abi.md](ext-abi.md) | - -> **库写法(代码即文档)**:[lib-code-as-docs.md](lib-code-as-docs.md) · [roadmap/lib-ext-code-as-docs.md](../roadmap/lib-ext-code-as-docs.md)。 -> **多语言库命名**:见 [stdlib-i18n.md](stdlib-i18n.md)(不设 `lang:`;中英分文件)。 -> **L1 模块清单**(含 math/foreign/plugin):见 [stdlib-modules.md](stdlib-modules.md)。 -> **中层标准库 Mid(M1–M6)**:已落地——[stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md)。 -> **中层第二波 Mid2(M7–M10)**:已落地——[stdlib-mid2.md](stdlib-mid2.md) · [roadmap/stdlib-mid2.md](../roadmap/stdlib-mid2.md) · 缺口 [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md)。 -> **`ext/` 不是 stdlib**:官方可选扩展见 [ext-llm.md](ext-llm.md) / [ext-agent.md](ext-agent.md)。 - ---- - -## 1. 分层 - -| 层 | 内容 | -|----|------| -| **L0 内置** | 解释器内:`print` `input` `len` `str` `int` `type` `trim` `split` `join` `at`(`type` 可含 `map`) | -| **L1 核心** | 已有 [`lib/`](../../lib/):fs/sys/time/json/net/math/foreign/plugin/table/text/… | -| **L1 中层(Mid)** | **已落地** re / encoding / path / hash / secrets / csv / text++ / table++ / cli / log / uuid — [stdlib-mid.md](stdlib-mid.md) | -| **L1 Mid2** | **已落地** datetime / url / toml / html / fs++ / stats / log.fields — [stdlib-mid2.md](stdlib-mid2.md) | -| **官方 ext** | [`ext/`](../../ext/)(`.mq.md` + 可选原生插件);`MARQDO_EXT`;**不属于** L1;插件仅领域热路径 | -| **L2** | catalog / 用户站收录(随发版);应主要靠核心+中层、默认无插件 | - ---- - -## 2. 内置一览(S0 + S1) - -| 名 | 形参 | 结果 | -|----|------|------| -| `len` | `value` | 文本标量数或列表长度 | -| `str` | `value` | 显示文本 | -| `int` | `value` | 整数(失败 → 诊断) | -| `type` | `value` | `none`/`bool`/`int`/`text`/`list`/`map` | -| `trim` | `value` | 去首尾空白 | -| `split` | `value`, `sep` | 文本列表 | -| `join` | `value`, `sep` | 拼接文本 | -| `at` | `value`, `index` | 列表下标(越界 → `None`) | - -表(单列表格)在运行时是 `list`:行数用 `len`,取行用 `at`。 - ---- - -## 3. 官方库导入(S2) - -Frontmatter 导入**绑定库名**(默认 = 文件名茎;`as` / `作为` 可改)。成员经点号路径调用(`time.parse`、`json.get`),不倒进全局短名。完整语义见 [module-namespace.md](module-namespace.md)。 - -```markdown ---- -import: - text: lib/text.mq.md - table: lib/table.mq.md ---- -``` - -调用示例:`> time.now_unix`、`> json.parse text=…`。需要本地短名时用 `导入 format`(冲突:time.format`(冲突 → 硬错误)。 - -`std/text.mq.md` 等价于 `lib/text.mq.md`。解析顺序: - -1. 相对当前文件 -2. `MARQDO_LIB`(可指向 `lib` 目录或仓库根) -3. 当前工作目录的 `lib/` -4. 可执行文件附近的 `lib/`(含 `cargo run` 的相对路径) -5. **内嵌 stdlib**(v0.1.2+,编译进二进制;无磁盘 `lib/` 时自动使用) - -当前模块(API 多为 `##` 自由函数;见 [objects.md](objects.md)): - -| 路径 | 导出 | -|------|------| -| `lib/fs.mq.md` / `lib/文件.mq.md` | `read_text`… / `读文本`… | -| `lib/time.mq.md` / `lib/时间.mq.md` | `now_unix`… / `此刻秒`… | -| `lib/sys.mq.md` / `lib/系统.mq.md` | `env_get`…、`load_dotenv`… / `取环境`…、`加载环境`… | -| `lib/json.mq.md` | `parse` `stringify` `get` `keys` `quote`(中英同文件) | -| `lib/net.mq.md` / `lib/网络.mq.md` | `http_get`…(HTTPS)/ `获取`… | -| `lib/math.mq.md` / `lib/数学.mq.md` | 数值 / 随机 / 公式 / 绘图 | -| `lib/foreign.mq.md` / `lib/外联.mq.md` | 具名围栏外联 | -| `lib/plugin.mq.md` / `lib/插件.mq.md` | `load` / `unload` / `list`(原生 ABI) | -| `lib/writeback.mq.md` / `lib/自写回.mq.md` | `record` `get` `clear` `list` | -| `lib/subtask.mq.md` / `lib/子任务.mq.md` | `spawn` `poll` `wait` `kill` `wait_all` | -| `lib/text.mq.md` | `str_trim` `str_split` `str_join` | -| `lib/文本.mq.md` | `去空白` `拆分` `拼接` | -| `lib/table.mq.md` | `put` 为首选写入;`rows`/`row_at` 及完整 list/map API — 见 [stdlib-table.md](stdlib-table.md) | -| `lib/表.mq.md` | `改` 为首选写入;`行数`/`取行` 及完整 list/map API | - -完整清单见 [stdlib-modules.md](stdlib-modules.md)。 - ---- - -## 4. 转换错误约定(S3) - -用户可见失败统一为: - -```text -path:line:col: message -``` - -内置转换相关文案(稳定子集,金样例断言): - -| 情况 | message | -|------|---------| -| 非法整数文本 | `cannot convert to int: "…"` | -| `int` 类型不对 | `int needs int, bool, or text` | -| `len` 类型不对 | `len needs text or list` | -| `trim` 非文本 | `trim needs text` | -| `split`/`join` 参数类型 | `split needs text value` 等 | -| 空分隔符 | `split sep must not be empty` | - -不引入独立异常类型对象;一律走 `Diagnostic`。 diff --git a/doc/design/t1-session-staleness.md b/doc/design/t1-session-staleness.md deleted file mode 100755 index dc6207e..0000000 --- a/doc/design/t1-session-staleness.md +++ /dev/null @@ -1,233 +0,0 @@ -# T1 会话内陈旧检测:为什么模型不会收到重复警告 - -| | | -|---|---| -| 状态 | **Accepted · 机制说明**(M6 落地) | -| 日期 | 2026-10-22 | -| 回答 | 「在不改变的情况下,能让模型免于多次警告疲劳吗?」——**能,而且几乎不用改什么** | -| 前置 | [staleness-providers.md](staleness-providers.md) · [warning-fatigue-control.md](warning-fatigue-control.md) | - ---- - -## 0. 一句话 - -> **警告的作用域 = 模型自己刚改的那几行;投递次数 = 一次;附着在造成它的那次编辑的返回里。** - -不是"我们让它少报",而是**同一件事在结构上不可能被报第二次**。 - ---- - -## 1. 机制为什么成立:前后两版本来就在手里 - -看现有 `repair_apply`(`src/mlsp.rs:233`)的实现: - -```rust -let source = source_text(params)?; // ← 改动前(before) -... -match crate::repair::apply_edits(&source, &ranges, &edits) { - Ok(new_source) => { // ← 改动后(after) - Ok(json!({"source": new_source, "edits_applied": edits.len()})) - } - ... -} -``` - -**`source` 和 `new_source` 在同一个函数作用域里同时存在。** -所以"比较改动前后"不需要任何外部东西: - -| 需要的东西 | 从哪来 | -|-----------|--------| -| 改动前的 AST | `parse(source)` | -| 改动后的 AST | `parse(new_source)` | -| 标签配对 | 两份 AST 里的标签节点(按标签文本 + 序号) | -| `()` 是否变了 | 比较两边的 AST 指纹 | -| `[]` 是否变了 | 比较标签文本 | - -**零 git、零台账、零缓存文件、零环境依赖。** 这就是"agent 回路根本不需要 VCS"的含义。 - -### 1.1 指纹怎么做(T1 只需要「进程内一致」) - -这一点让实现变得很轻: - -- `Expr` 目前 `#[derive(Debug, Clone)]`,**没有 `PartialEq`**(`src/ast.rs:184`)。 -- 但 T1 只在**同一个进程内**比较前后两版,**不需要跨版本、跨机器稳定的指纹格式**。 - 于是最简做法是:把 `()` 的比较键取为 `format!("{:?}", expr)`——同一次运行内确定即可。 -- 若想更严谨,可给 `Expr` 及其成员补 `#[derive(PartialEq)]`(纯机械改动;`Literal` 含 `f64`, - 只可 `PartialEq` 不可 `Eq`),然后直接结构比较,不产生字符串。 -- 反过来,**T2/T3 才需要稳定指纹**(跨会话要能对上),那时才动用 - `knowledge/fingerprint.rs` 那套。 - -> 也就是说:T1 的实现成本 ≈ "解析两次 + 比较两棵子树",没有版本化指纹的负担。 - ---- - -## 2. 一次修复轮次的完整时序 - -``` -第 N 轮 - ┌─ validate → 语法/契约诊断(不含标签扫描) - ├─ repair_targets → 靶点 + 允许范围 - ├─ 模型产出 edits (例如:把 `* 金额` 改成 `/ 金额`) - └─ repair_apply(source, ranges, edits) - │ - ├─ before = source - ├─ after = apply_edits(...) - ├─ 解析两版 → 比较每个标签的 () 指纹 - └─ 返回: - { "source": after, - "edits_applied": 1, - "labels": { "stale": [ {标签, code_past, code_now, span} ] } } -``` - -模型在自己这次编辑的**响应里**看到: - -```json -{ - "labels": { - "stale": [{ - "text": "按 `税率` 计算总价", - "code_past": "at(税率表, 档位) * 金额", - "code_now": "at(税率表, 档位) / 金额", - "span": {"line": 42, "col": 12} - }] - } -} -``` - -它只需要回答一个问题:**"你刚才动了这段实现,描述还成立吗?"** - ---- - -## 3. 为什么「重复」在结构上消失了 - -三个性质,缺一不可: - -| 性质 | 内容 | 效果 | -|------|------|------| -| **作用域 = 自己的 diff** | 只看这次 `apply` 触及的标签 | 全仓库/全文件的旧债永远不进模型的上下文 | -| **投递 = 一次** | 只在造成它的那次响应里出现 | 不会在后续 `validate` 里重复出现 | -| **自包含** | 下一轮的 diff 是新的 | 模型不改那处 → 那条标签不再出现 | - -**注意第三条的含义(也是代价)**:模型若忽略了提示,它**不会**在下一轮被再提醒—— -因为它没碰那处。这是刻意的取舍:**宁可漏一次,也不反复骚扰**。 - -> 对比扫描式:一个 20 处标签的文件,5 轮修复里模型可能累计看到上百条重复提示; -> T1 下最多看到 **自己这几行涉及的 0–2 条**,且每条只出现一次。 - ---- - -## 4. 关键重构:它在性质上**不是 warning,而是编辑期诊断** - -这是我认为最重要的一点。 - -| | Lint 警告 | 编译器错误 | **T1 stale** | -|---|---|---|---| -| 出现时机 | 常在后台/每次保存 | 你按下构建那一刻 | **你改完那一刻** | -| 数量 | 与存量成正比 | 与你这次写的错成正比 | **与你这次改的成正比** | -| 是否重复 | 反复出现 | 不重复(改了就消失) | **不重复** | -| 用户态度 | 容易忽略 | 必须处理 | **天然要处理** | - -没有人抱怨"编译器又报语法错了"——因为它是**一次性的、可归因的、改动驱动的**。 -T1 的 stale 正好落在这个类别里。 - -**所以疲劳问题不是靠压制解决的,是靠把 stale 从"lint 类别"搬到"编译错误类别"解决的。** - ---- - -## 5. 「不改变」到什么程度 - -你的问法是"在不改变的情况下"。精确回答: - -| 项 | 要不要变 | -|----|---------| -| `.mq.md` 文档内容 | **不变**(不嵌指纹、不加 `noqa`、不加标记) | -| 写代码 / 读代码的工作流 | **不变**(还是 validate → repair_targets → 编辑 → repair_apply) | -| 项目状态文件 | **不新增**(无台账、无基线、无 `.marqdo/labels.json`) | -| 对 VCS 的依赖 | **无**(沙箱 `exec=false`、WASM 无进程,照样可用) | -| 环境要求 | **无**(纯内存计算) | -| **MLSP 协议** | **加一个可选参数 + 一个响应字段**(这是唯一的改动) | - -唯一的协议改动小到可以忽略: - -```json -{ "method": "repair_apply", - "params": { "source": "…", "ranges": [[42,42]], "edits": [...], - "check_labels": true } } -``` - -- `check_labels` 缺省 = 不做(**默认零开销、零噪音**) -- 客户端(agent 框架)在修复回路里打开它 -- 返回里多一个 `labels` 字段;无 stale 时为空数组 - ---- - -## 6. 配对规则(哪些算"同一条标签") - -比较两份 AST 时: - -| 情形 | 判定 | -|------|------| -| 标签文本未变、`()` 指纹变 | ✅ **stale**(核心场景) | -| 标签文本变了 | 不报——作者在更新描述,这就是"确认" | -| `()` 与标签都没变 | 不报 | -| 新插入的标签 | 不报——新断言无历史 | -| 被删掉的标签 | 不报——没有东西可比 | -| 标签移动位置(同文件) | 不报——按标签文本配,不按行号 | - -**"按标签文本配对"很关键**:它让"把这段代码挪个位置"不会误报, -而"把这段代码的计算改了"一定报警。 - ---- - -## 7. 模型会不会漏掉?三种兜底 - -T1 的代价是"不重复",所以要设计"漏了怎么办": - -| 兜底 | 做法 | 代价 | -|------|------|------| -| **循环预算** | `labels.stale` 非空时,客户端允许下一轮(现有 `max_attempts: 2` 直接可用) | 无 | -| **可选阻塞** | `check_labels: "block"`:apply 成功但返回 `needs_attention: true`,客户端不得结束任务 | 小 | -| **会话末汇总** | 最后一轮给一次总数(只一次,不逐条) | 小 | - -**建议默认**:`check_labels: true` + 循环预算。也就是"提示一次,允许一轮修,不强制"。 -知识库仓可以用 `"block"`。 - ---- - -## 8. 边界(必须说清) - -| 问题 | T1 能不能 | -|------|----------| -| 模型刚改完,描述还成立吗 | ✅ 能(核心场景) | -| 昨天有人改了代码,今天打开才发现描述过期 | ❌ 不能(`diff` 里没有,那是 T2 的活) | -| 从别处复制粘贴一段代码带来的旧标签 | ❌ 不能(无历史) | -| 描述写得笼统、无法证伪 | ❌ 不能(L1 也不查) | - -**T1 的定位**:保证"**改动者当场被问一次**"。 -它不保证"整个仓库始终新鲜"——后者需要 T2/T3,是可选增强,不进默认路径。 - ---- - -## 9. 与你担心的「疲劳」对照 - -| 场景 | 扫描式(每轮全量) | **T1(本机制)** | -|------|------------------|-----------------| -| 模型一轮看到几条 | 全仓库 N 条 | **0–2 条** | -| 5 轮累计 | N × 5 | **≤ 2** | -| 同一标签重复 | 每轮重复 | **一次** | -| 未修复的旧债 | 每轮都提 | 不再提(等它被改到时再说) | -| 模型需要记住"我之前看过" | 需要 | **不需要**(自包含) | -| 需要 VCS / 台账 | 常需要 | **不需要** | - ---- - -## 10. 待你确认 - -1. **接受"T1 = 编辑期诊断,不是 lint 警告"这个定位吗?**(这是整个防疲劳论证的支点) -2. `check_labels` 默认值:`false`(零开销)还是 `true`(修复回路默认开)? -3. 漏掉的兜底:用**循环预算**(不强制)还是**可选阻塞**(`"block"`)为默认? -4. 会话末汇总要不要做?(一次性总数,不逐条) - -> 若你确认,P1 的第一步就很小:给 `repair_apply` 加 `check_labels`, -> 在 `apply_edits` 之后解析两版、比较标签指纹,把结果挂在响应里。 -> 文档零改动、状态零新增、不依赖 git——**第一天就不会有任何存量警告**。 diff --git a/doc/design/table-cell-expressions.md b/doc/design/table-cell-expressions.md deleted file mode 100755 index d9cb69e..0000000 --- a/doc/design/table-cell-expressions.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: table cell expressions -status: Accepted -date: 2026-08-12 -related: markdown-mapping.md · roadmap/tables-maps-footnotes.md · call-arguments.md ---- - -# 表单元格表达式(T5) - -| | | -|---|---| -| 状态 | **Accepted** | -| 日期 | 2026-08-12 | -| 相关 | [markdown-mapping.md](markdown-mapping.md) · [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) · [call-arguments.md](call-arguments.md) | - ---- - -## 1. 问题 - -v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结果虽是 `Map` / `List`,却不能写: - -```markdown -`h` = - -| api_key | model | -|---------|-------| -| `api_key` | `model` | -``` - -作者只好用 `json.set` 链或 JSON 字符串拼接——这是**实现缺口**,不是「字典只能装字面量」的语义必然。 - ---- - -## 2. 锁定规则 - -### 2.1 数据单元格 = 与调用实参相同的值语法 - -每个**数据**单元格(非表头、非分隔行)按 [`parse_call_arg_value`](../../src/parse/expr.rs) 解析,再在绑定求值时执行: - -| 单元格写法 | 含义 | -|------------|------| -| `苹果` / `Alpha` | 裸词 → 文本字面量(与今日竖表兼容) | -| `42` | 整数 | -| `` `api_key` `` | 变量引用 | -| `` `a` + `b` `` | 普通表达式 | -| `True` / `假` / `None` | 布尔 / 空 | -| `"https://…"` / `".marqdo/x"` / `"1/5"` / `"16/9"` | 引号字符串(可含 `/`、插值;**CSS 比率等含 `/` 的值请用引号**,勿依赖空格消歧) | -| `https://api.openai.com/v1` | **路径折叠**:无空格的 `Text/Text/…` 除法链收成整段文本(同调用实参) | -| `gpt-4o-mini` | **连字符散文**:不拆成减法(同调用实参) | -| `` /about ``、`` /chat/completions `` | 以 `/` 开头的路径散文 → 整段文本 | -| `1/5` | **整数除法**(同表达式 / 调用实参;今日整除得 `0`)——要文本请写 `"1/5"` | -| 空单元格 | 空文本 `""` | - -### 2.2 表头仍是键名文本 - -表头单元格**不**求值:键 = trim 后的表头字符串(与今日一致)。不允许 `` | `k` | `` 当动态键(v1 非目标;需要时另文)。 - -### 2.3 几何语义不变 - -竖表 / 横表单行 Map / 多行列向 Map / `@`·`行`·`row` 行向记录——**形状规则不变**;只把「单元格 → `Expr::Literal`」换成「单元格 → 完整 `Expr`」。 - -求值已由解释器对 `Expr::List` / `Expr::Map` 递归完成,字节码后端已发射列表/字典,**无需新 AST 节点**。 - -### 2.4 求值时机 - -表出现在 `` `名` = `` 右侧时,在**该绑定语句**求值:单元格内变量读**当时**环境。构造函数体里的表与语句表规则相同。 - -### 2.5 错误 - -- 单元格表达式非法 → 与别处表达式相同的 `path:line:col` 诊断(行号取该表行)。 -- 变量未定义 → 求值期报错。 -- 不引入「单元格静默当字面量」的回退(除 §2.1 已列的路径/连字符折叠,与调用实参对齐)。 - ---- - -## 3. 作者示例(目标体验) - -```markdown -*`api_key` = > sys.env_get name=OPENAI_API_KEY * -*`model` = "gpt-4o-mini" * - -`handle` = - -| api_key | base_url | model | suffix | -|---------|----------|-------|--------| -| `api_key` | https://api.openai.com/v1 | `model` | /chat/completions | -``` - -`handle` 为含运行时 `api_key` / `model` 的字典;静态 URL 与 suffix 仍可裸写(路径折叠)。 - -嵌套: - -```markdown -*`prompt` = hello * - -`msg` = - -| role | content | -|------|---------| -| user | `prompt` | - -*`messages` = > json.append list=None item=`msg` * -``` - -(列表字面量表仍可用竖表;需要「单行记录」时用横表或 `@` 行向表。) - ---- - -## 4. 兼容性 - -| 旧写法 | 行为 | -|--------|------| -| 纯中文/英文词、整数 | **不变** | -| `gpt-4o-mini`、URL、`/path` | **不变**(折叠规则与调用实参一致) | -| 真正要做除法 / 减法 | 裸写 `1/5` 或空格/括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 | -| CSS / 含 `/` 的散文值 | **引号优先**:`"1/5"`、`"16/9"`、`"image/png"`(不靠空格把算术「关掉」) | - -破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧;含 `/` 的**文本**一律用引号。 - ---- - -## 5. 非目标(本阶段) - -- 表头动态键 -- 单元格内 `>` 调用(可用表外算完再引用) -- 单元格内多语句 / 分支 -- 把叙述区(注释段)里的 GFM 表当成可执行(仍为注释) - ---- - -## 6. 验收 - -| 项 | 标准 | -|----|------| -| 金样 | 横表单元格 `` `var` `` 读环境;竖表旧金样全绿 | -| 路径 | `https://…`、`/chat/completions`、`gpt-4o-mini` 仍为文本 | -| 含 `/` 文本 | 表单元格用引号:`"1/5"`、`"16/9"`;裸 `1/5` 为除法 | -| 扩展 | `ext/ai/llm` 构造可用表写入运行时字段,去掉无必要的 `json.set` 链 | -| 文档 | 本页 + roadmap T5 + markdown-mapping §9 同步 | - -实现跟踪见 [roadmap/tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) **T5**。 diff --git a/doc/design/tech-stack.md b/doc/design/tech-stack.md deleted file mode 100755 index a6b49f5..0000000 --- a/doc/design/tech-stack.md +++ /dev/null @@ -1,152 +0,0 @@ -# 参考实现:技术选型分析(尚未拍板) - -| | | -|---|---| -| 状态 | **分析中 — 未定案** | -| 日期 | 2026-08-04 | -| 说明 | 对比候选与约束;**不在本文直接开写实现仓库脚手架** | - -上一版曾草率写「就用 TypeScript」——信息不足,已作废为定论。本文只做选型框架与对比,**最终实现语言须单开 ADR 确认后再动工。** - ---- - -## 1. 我们在选什么 - -参考实现至少包含: - -1. **读入** `.mq.md`(含 frontmatter 混合行) -2. **对齐 GFM** 的结构:标题、列表(`-`/`+`/`1.`)、强调、表格、围栏、链接 -3. **Lower**:行首判别、标题树作用域、列表符语义、注释剥离 -4. **两遍**:收集定义 + 导入 → 求值 -5. **CLI** + **金样例测试**(`tests/`) - -可选后期:字节码/编译、LSP、格式化。首版目标是**验证语法宪法**,不是上生产编译器。 - ---- - -## 2. 选型准则(按权重) - -| 权重 | 准则 | 说明 | -|------|------|------| -| 高 | GFM 忠实度 | 表格、列表符、强调边界与 GitHub 预览一致,减少「能渲染不能跑 / 能跑不能渲染」 | -| 高 | 与宪法同构 | 易于表达「先 mdast/事件流,再 Marqdo AST」 | -| 高 | 测试与迭代速度 | 改语法宪法时能快速改测试 | -| 中 | 静态类型 / 可维护 AST | 长期改解释器不疼 | -| 中 | CLI 与打包 | 单二进制或 `npx`/等价体验 | -| 低 | 极致性能 | v0 样例很小 | -| 低 | 浏览器内运行 | **已后置落地规划**:见 [ADR 0002](../adr/0002-browser-marqdo-wasm.md)(WASM 解释器) | - -非准则:跟风、先写再选、与「生成 OKF」强绑某一云厂商。 - ---- - -## 3. 架构共性(与语言无关) - -无论选哪门实现语言,流水线应一致: - -``` -.mq.md 文本 - → 前端:GFM 友好解析(或事件扫描) - → Middle:Marqdo lower(行类、标题树、- / +、表、围栏) - → Marqdo AST - → 语义:导入图、提升、作用域 - → 后端:解释器(v0)/日后编译 - → 测试:tests 金样例 → 期望 stdout -``` - -**前端可复用成熟 GFM 库,也可自研**;Middle/后端必须自研(这是语言本体)。 - ---- - -## 4. 候选对比 - -### A. TypeScript / Node + remark(mdast) - -| 利 | 弊 | -|----|----| -| remark-gfm 与预览器语义接近;mdast 节点齐全 | 运行时依赖 Node;发行 CLI 需打包 | -| 迭代快、Vitest 方便 | 性能与「系统级编译器」形象偏软 | -| 与 Markdown 工具链同生态 | 需纪律:避免把业务写进插件泥潭 | - -**适合:** 验证宪法、快速金样例。 -**不自动等于最终生产编译器。** - -### B. Rust + pulldown-cmark / comrak - -| 利 | 弊 | -|----|----| -| 单静态二进制、性能好、适合日后正式编译器 | GFM 表格/细节与 GitHub 仍可能有差异,要对齐测试 | -| 类型与代数数据类型适合 AST | 前期迭代比 TS 慢 | -| 无 GC、可嵌入 | MD 生态碎片,选库要论证 | - -**适合:** 中长期「真编译器」或与 TS 原型双轨。 -**风险:** 首版就上 Rust 可能拖慢语法验证。 - -### C. Python + markdown-it-py / mistune - -| 利 | 弊 | -|----|----| -| 原型极快 | 类型与工程化偏弱;双实现时易弃 | -| 文本处理友好 | 打包 CLI 体验一般 | - -**适合:** 一次性语法实验。 -**不推荐**作为唯一长期实现,除非团队强约束。 - -### D. Go + goldmark - -| 利 | 弊 | -|----|----| -| 单二进制、部署简单 | 泛型/AST 表达力一般;MD 库选 goldmark 需 GFM 扩展评估 | -| 并发与工具链成熟 | 与 MD 研究生态联系弱于 JS | - -**适合:** 工具型 CLI 优先的团队。 - -### E. 自研扫描器(任意语言)+ 仅用 GFM 做对照测试 - -| 利 | 弊 | -|----|----| -| 完全控制行首判别与 `+`/`-` 语义 | 重复实现表格/强调,易与渲染不一致 | -| 可强制「行分类优先于块解析」 | 工作量大 | - -**适合:** 证明「行首判别」与 CommonMark 块结构冲突时的研究分支。 -可与 A/B 组合:自研 lower,块结构仍喂给现成解析器。 - ---- - -## 5. 关键技术风险(与选语言正交) - -1. **行首判别 vs 块解析器** — CommonMark 先成块再看内容;Marqdo 先看行类。可能需「行预分类再喂解析器」或「解析后按源位置重分类」。选型时要让候选语言/库能拿到**源行映射**。 -2. **frontmatter 非纯 YAML** — `>` 导入行是扩展;不能整块丢给严格 YAML 解析器。 -3. **`+` 与 `-` 列表** — 多数解析器都认,但 lower 必须保留**项目符字符**,不能只得「unordered list」。选库时验证 AST 是否保留 bullet type。 -4. **`*` else vs `*返回*` vs 强调** — 依赖 inline 解析与「整行恰好一个 `*`」的行级规则并存。 - -以上 4 点应作为**选型验收用例**,写进 ADR:用最小样例在候选栈上 Spike,再定案。 - ---- - -## 6. 建议的决策流程(尚未执行) - -1. **Spike(各 ≤0.5–1 日)** - - 候选 A:TS + remark-gfm — 能否区分 `-`/`+` bullet、解析单列表格、读 strong/emphasis。 - - 候选 B:Rust + comrak/pulldown — 同上。 - - (可选)C 或 D 若团队有偏好再做。 -2. **对照验收用例**(固定):`tests/structure/hello.mq.md`、`branch.mq.md`(`+`)、`collection.mq.md`(表)、含 `import x:x.mq.md` 的 frontmatter 行。 -3. **出 ADR**:选定「验证期实现」与(可选)「生产目标实现」是否同一语言。 -4. **再**建仓库脚手架与测试——禁止在 ADR 前默认生成 `package.json` / `Cargo.toml` 当既成事实。 - ---- - -## 7. 当前态度(非正式投票) - -| 阶段 | 倾向(待 Spike 验证) | -|------|------------------------| -| 语法验证期 | 更可能是 **TypeScript + remark**(快、GFM 近) | -| 长期生产编译器 | **开放** Rust / Go,不与验证期绑定 | - -**本文不授权开始实现。** 确认 Spike 计划或直接指定语言后,再写 `adr/0001-implementation-language.md`。 - ---- - -## 8. 与「无标记 = 注释」的关系 - -实现必须先做**行分类**(见 [code-vs-comment.md](code-vs-comment.md)),再谈用何种语言写分类器。选型不能假设「整文件都是可执行代码」。 diff --git a/doc/design/ubuntu-ppa.md b/doc/design/ubuntu-ppa.md deleted file mode 100755 index 74db6a1..0000000 --- a/doc/design/ubuntu-ppa.md +++ /dev/null @@ -1,49 +0,0 @@ -# Ubuntu PPA: executable packaging and publication - -The maintained entry is [the release handbook](../../skills/marqdo-release/index.mq.md). [ubuntu.mq.md](../../skills/marqdo-release/ubuntu.mq.md) provides publication and observation tasks; [package.mq.md](../../skills/marqdo-release/package.mq.md) owns native metadata and staged file preparation. Their source contracts replace a separate command playbook. - -The PPA is ppa:cflmy/marqdo. Apt installs the interpreter; extensions remain independently installed by marqdo ext add. Upload acceptance alone is incomplete: the exact source must be published, its amd64 build must succeed and apt must expose the same Debian version. - -## Exact version and artifact - -| Value | Meaning | -|---|---| -| X.Y.Z | Cargo package.version and the authorized upstream | -| 1ppaN | Reviewed debian/changelog packaging revision | -| ~SERIES | Explicit Ubuntu target, normally noble | -| marqdo_X.Y.Z-1ppaN~SERIES_source.changes | Exact signed source artifact | -| ext/VERSION | Independent extension-pack version | - -Native upstream and debian_version tasks parse the actual files. The latter retains the reviewed revision, removes its old series suffix and selects the current upstream/target series. A packaging-only reupload needs an explicit changelog revision edit. Upload selects the exact computed filename, never the newest unrelated package from a previous release or another series. - -## Callable workflow - -Run from the checkout root after the user has authorized this CLI/full release. Replace X.Y.Z with that version: -```sh -marqdo call skills/marqdo-release/ubuntu.mq.md ship 'version="X.Y.Z"' 'series="noble"' --require-ok --effects plugin,fs.read --fs-root . --json -marqdo call skills/marqdo-release/ubuntu.mq.md status 'version="X.Y.Z"' 'series="noble"' --require-ok --effects plugin,net --fs-root . --json -marqdo call skills/marqdo-release/index.mq.md finish 'version="X.Y.Z"' 'mode="full"' --require-ok --effects plugin,net,fs.write --fs-root . --json -``` - -Status is observational: inspect complete as well as Result.ok. Finish turns incomplete publication into a failed Result, allowing --require-ok to stop automation while keeping evidence. A green GitHub run does not establish Launchpad completion or apt availability. - -## Native files and existing tools - -Marqdo reads version metadata and writes the staged Cargo configuration, Debian changelog and vendor-checksum repairs. Native filesystem, TOML and JSON functions carry the data. No generated Python reader or writer is used. Vendor repair removes backup entries that Debian cleaning would delete while retaining package digests and ordinary source hashes. - -The existing Debian boundary uses Cargo vendor, tar/xz, the configured Rust installation, debuild, GPG and dput. The source archive includes vendored crates and the selected Rust toolchain for an offline build. Its script chooses a fixed default toolchain and exposes the existing override; it does not assume the build host compiler is sufficient. - -A new upstream may create an orig archive. Once Launchpad accepts that upstream, reuse the identical bytes and upload only the Debian revision. Never rebuild an accepted orig archive to work around a checksum rejection. A failed stage remains available for inspection. - -## Recovery evidence - -| Failure | Required action | -|---|---| -| sudo/GPG interaction unavailable | Complete the same concrete Debian boundary in the user's terminal, keeping version and series | -| Complete package version already used | Review and increment the Debian revision before another authorized upload | -| orig bytes differ | Retrieve and reuse the previously accepted archive | -| Offline vendor checksum failure | Inspect sanitize_vendor evidence and the retained staged tree | -| Source accepted, build pending/failed | Inspect the actual Launchpad build | -| Build green, apt metadata stale | Repeat apt observation for the exact version | - -Public apt observation reads Packages.gz with native HTTP bytes and the bounded gzip boundary, then inspects actual package records. Isolated fixtures cover metadata selection, configuration writing and vendor-checksum preservation without uploading to a PPA. diff --git a/doc/design/user-site.md b/doc/design/user-site.md deleted file mode 100755 index bbcc34b..0000000 --- a/doc/design/user-site.md +++ /dev/null @@ -1,66 +0,0 @@ -# 用户静态文档站(public / gh-pages) - -| | | -|---|---| -| 状态 | 已定 | -| 日期 | 2026-08-04 | -| 相关 | [view.md](view.md) · [view-static-interactive.md](view-static-interactive.md)(静态交互 / 公式代码视觉 · Proposal) · 源目录 [`public/`](../../public/) | - ---- - -## 1. 分工 - -| 路径 | 是否入库 | 职责 | -|------|----------|------| -| `doc/` | 是 | 开发者设计 / ADR / 路线图(单数 `doc`,勿再造 `docs/`) | -| `public/**/*.mq.md` | 是 | 用户可读、可执行、可下载的介绍(结构 / 关键字 / **stdlib** / 特性迭代);**双语**:拉丁文件名 = 英文,中文文件名 = 中文编程,同目录并列。stdlib 含 `plugin`;特性页覆盖对象与 `ext/`(llm / agent) | -| `public/index.html`、`public/pages/` | **否**(ignore) | `marqdo view output` 生成的 HTML | -| `tests/{structure,keywords,errors}/` | 是 | 金样例与失败夹具(含 errors) | -| 远程分支 `gh-pages` | 发布产物 | 发布整个 `public/`(源文件 + 生成 HTML) | - -**禁止**把 `tests/errors/` 编进用户站。 - ---- - -## 2. 生成 - -```bash -cargo run --release -- view output public -o public -# 或 -./scripts/build-public.sh -powershell -File ./scripts/build-public.ps1 -``` - -产物写在源旁: - -``` -public/ - *.mq.md / structure/ / … # 入库源 - index.html # 生成(ignore) - pages/… # 生成(ignore) -``` - ---- - -## 3. 发布分支 - -将构建后的 `public/` 推到 **`gh-pages`**。CI:`.github/workflows/pages.yml`。 - -仓库 Settings → Pages → Source = Deploy from branch → `gh-pages` / root。 - ---- - -## 4. 内容分层(用户站) - -| 目录 | 内容 | -|------|------| -| `public/stdlib/` | L1 模块页(含 `plugin` / `插件`);概述注明 `ext/` 非 stdlib | -| `public/features/` | 迭代特性:树遍历、字节码、view、**对象**、**官方扩展** | - -设计文档仍在 `doc/design/`(`objects.md`、`ext-llm.md`、`ext-abi.md`、`ext-agent.md`)。 - -## 5. 验收 - -1. `public/` 下每个 `.mq.md`(除纯工具模块外)`marqdo run` 退出码 0。 -2. `view output public -o public` 后首页为欢迎页,侧栏无 errors。 -3. 主分支跟踪 `public/**/*.mq.md`;不提交 `public/index.html` / `public/pages/`。 diff --git a/doc/design/v-safe-json.md b/doc/design/v-safe-json.md deleted file mode 100755 index aff0b5c..0000000 --- a/doc/design/v-safe-json.md +++ /dev/null @@ -1,90 +0,0 @@ -# \(V_{\mathsf{safe}}\) JSON integer contract (host ↔ Lean) - -Canonical Lean model: `MarqdoThesis/PLDI/proofs/MarqdoProof/MarqdoProof/ForeignJSON.lean`. -Host mapper: `src/host/json.rs` (`json_to_value` / `value_to_json`). - -This document freezes **runtime conformance** of the Marqdo JSON bridge to the -mechanized \(V_{\mathsf{safe}}\) integer domain. It is **not** a verified -compilation of the Rust interpreter. - -## Domain - -``` -MAX_SAFE = 9007199254740991 # 2^53 - 1 -``` - -\(V_{\mathsf{safe}}\) values (mechanized): - -| JSON | Marqdo | -|---|---| -| `null` | `None` | -| `bool` | `Bool` | -| integer with `\|n\| ≤ MAX_SAFE` | `Int` | -| `string` | `Text` | -| `array` | `List` | -| `object` | `Map` | - -**Host extension (not in Lean `SafeVal`):** JSON non-integer numbers → `Value::Num(f64)`. Non-finite numbers (NaN/Inf) are refused on encode and in Python/Node oracle responses, including nested payloads. Floats are documented host behavior; they are **not** claimed as mechanized \(V_{\mathsf{safe}}\) fidelity. - -## Encode (`value_to_json`) - -- `Value::Int(n)` with `|n| ≤ MAX_SAFE` → JSON number. -- `Value::Int(n)` with `|n| > MAX_SAFE` → **refuse** (error). -- `Value::Handle(_)` → **refuse** (`json: session handle cannot be serialized`). -- Column-table `Map` whose fields are all `List` with **unequal lengths** → - **refuse** (`json: table column arity mismatch`). -- Nested `List` / `Map`: any child refuse fails the whole tree. -- GFM table **parse** also refuses unequal row width - (`table row arity mismatch`) before a value is built. -- Wide integers that must cross a language boundary: author converts to a - **decimal string** (∈ \(V_{\mathsf{safe}}\)); the foreign program may use - `BigInt` / Python `int` on that string. - -## Foreign oracle (`session_eval` / `session_get`) - -Python/Node session bootstraps sanitize results with the same integer gate -before JSON emission. An Ω response containing an OOD integer is a **fault** -(host `Err`), not a soft `ok:false` cell record. Stdout text that authors -`json.parse` themselves is still gated by host `json_to_value`. - -## Decode (`json_to_value`) - -- JSON integer with `|n| ≤ MAX_SAFE` → `Int`. -- JSON integer with `|n| > MAX_SAFE` → **refuse**. -- JSON unsigned integer `> i64::MAX` → **refuse** (do **not** coerce via `f64` or `Text`). -- Nested array/object: any child refuse fails the whole tree. -- Decimal-string encodings of wide integers → `Text` (in domain). - -## Error prefix - -All refuse messages use a fixed prefix for probes and diagnostics: - -``` -json: integer outside V_safe (±(2^53-1)): <n> -``` - -## In-domain roundtrip - -`±MAX_SAFE`, bool, null, string, array, and object roundtrips through -`encode → decode` must succeed. Integers `MAX_SAFE+1`, `-MAX_SAFE-1`, `2^53`, -`2^60`, `2^60+1` (and nested forms) must refuse. - -## Non-claims - -- Not verified Rust ↔ Lean compilation. -- Not arbitrary host-object fidelity (DataFrame, functions, heap sharing). -- Not automatic BigInt promotion inside Node/Python bootstraps. -- Document-level `Value::Int` may still hold i64 values that are OOD for JSON; - the gate fires when those values enter JSON encode/decode. - -## Strict request boundary update - -The numeric gate applies to the represented value, including integer-valued -floats and exponent notation. `9007199254740992.0` and -`9.007199254740992e15` are refused; fractions such as `1.5` remain in the host -extension. `serde_json` uses `float_roundtrip` to avoid endpoint decoding loss. -The strict text decoder rejects duplicate object keys and unequal column maps -before information is lost. One-shot, call_many and persistent input paths -use recursive domain admission; code, handle and secret values are not copied -implicitly. Auto-detection may leave non-JSON output as text, but valid JSON -outside the domain is a refusal, including in batch results. diff --git a/doc/design/verified-knowledge-compiler-boundaries.md b/doc/design/verified-knowledge-compiler-boundaries.md deleted file mode 100644 index 4bb6187..0000000 --- a/doc/design/verified-knowledge-compiler-boundaries.md +++ /dev/null @@ -1,179 +0,0 @@ -# Marqdo 可验证知识编译器:目标、可信边界与阶段性验收 - -> 状态:设计决策 + 当前实现对应。形成于 2026-11-18 关于知识编译、Lean 自动证明边界、AI 智能体知识沉淀与模块化组合的讨论。 -> -> 本文规定目标边界,不以“任意 Marqdo 程序都能被 Lean 证明”为目标。具体实现应以当前源代码、真实 Lean 证书与 CI 结果为准;不能通过修改文档把尚未验证的语义宣布为已证明。 - -## 1. 问题与共同认识 - -Marqdo 的核心目标不是取代 Lean,也不是成为全自动程序验证器: - -> 代码即文档,文档即知识库,知识即可执行。 - -更严格的工程定位: - -> 将人类可读文档编译为**可寻址、可验证、可执行、可复用的知识制品**的语言与编译系统。 - -其中,“可验证”不是“所有性质都能被形式化证明”;“知识即可执行”也不是“所有外部世界事实都有数学定理”。 - -形式证明必然面临不可判定性、求解器资源上限、环境非确定性、外部依赖以及不完整的语义模型。即使 Lean 内核确认一个命题正确,它确认的也是**给定 Lean 定义及假设下的命题**。如果 Marqdo 源码到 Lean 定义的映射未建立可信性,该证明不能无条件提升为 Marqdo 运行时正确性。 - -因此,整个设计遵守四条约束: - -1. **证明精确标注作用域**:明确对象、输入域、效应、数值模型及前提;不要将模型证明冒充完整运行时证明。 -2. **可证明则证明**:在受支持且能建立可信模型的子集内,由真实 Lean 内核验证;失败不得降级成虚假的 proved。 -3. **不能证明仍可成为知识**:保留测试、执行轨迹、实验数据、来源与未经验证的假设;这些证据不等价于逻辑证明。 -4. **不会静默取得执行权**:锚点引用、知识收据、定理声明或插件假设都不自动执行工具、授权访问环境或改变运行时行为。 - -## 2. 三层可信性,不由一个 Lean 布尔值代替 - -### L1:结构与来源验证——基础必需 - -对象包括 Markdown/Marqdo AST、唯一锚点、符号和模块解析、精确调用绑定、源码与契约指纹、引用有效性、依赖闭包、过期证据识别。 - -主要由解析器、SemanticProject、知识图谱、哈希与回放机制验证,无须假装数学证明。 - -### L2:形式证明——限定作用域 - -对象包括函数前/后置条件、调用前提、符号路径、算术结论、可组合的跨模块性质。 - -Lean 执行核验;Rust 只能生成目标、提前拒绝以及绑定真实源码,不能凭主机端的计算结果自行宣称定理成立。 - -### L3:执行和经验验证——不可省略 - -对象包括插件和 API 调用、量子硬件实验、非确定性智能体决策、实际数据质量与第三方网络服务。 - -应携带可复现测试、日志、测量、环境版本和来源,不应自动转化为 Lean proof。 - -量子科研例子:门矩阵幺正性可以有形式证明,具体设备的实验保真度必须由观测数据和校准记录支持;两种证据可组合引用,但不能互相冒充。 - -## 3. 证据等级(Proof is not a Boolean) - -知识制品采用与旧版 \`status\` **正交**的 \`evidence.grade\`。已在 \`src/knowledge/evidence.rs\` 建立类型化模型: - -| 证据等级 | 含义 | 禁止的推断 | -|---|---|---| -| \`proved\` | 目标语言、输入域及其运行时语义对应已得到可信证明 | 不覆盖未纳入证明的插件、浮点或硬件 | -| \`model_proved\` | Lean 核验了明示抽象模型下的命题 | 不得称为全部 Marqdo 运行时正确 | -| \`tested\` | 存在真实、可追溯的测试/实验结果 | 通过测试不等于数学证明 | -| \`assumed\` | 明示的外部假设、作者/插件契约 | 不得自动变成 proved | -| \`unknown\` | 未建立证据、超时、求解失败或超出可证子集 | 不等价于“命题错误” | -| \`refuted\` | 已提供可信反例 | 单纯 Lean proof 失败不能判为 refuted | -| \`stale\` | 当前源码、依赖或证明环境改变导致证据失效 | 不得复用旧证书 | - -**关键规则**: - -- \`proved\` 必须同时要求具体语义对应与内核证明,不能通过修改 JSON 证据字段获得。 -- 目前整数算术的 Lean \`Int\` 定理通常属于 \`model_proved\`。Marqdo 的 \`number\` 契约可能包含 \`Num\`、\`Formula\` 等,且 i64 溢出、动态类型转换与异常行为尚未普遍与 \`Int\` 对齐。 -- \`tested\`、\`assumed\`、\`refuted\` 的证据需要**相应来源**;不能因为某个测试通过、表格声明或求解失败就随意升级。 -- 证据等级用于解释保证性质;\`usable\`、\`kernel_replayed\` 和 \`current_source_verified\` 是独立的可用性/核验状态,不能混淆。 -- 知识检索、智能体与工具链看到 \`unknown\` 或 \`assumed\` 时,可以请求额外验证、执行测试、询问外部系统或拒绝高风险动作,但不能修改证明结论。 - -## 4. 统一契约组合:通用的是机制,不是自动化证明能力 - -函数契约规范化为 \`requires / ensures / effects / evidence\`,每个契约绑定明确的 \`SymbolId\`、源码来源和依赖身份。 - -一般调用 \(g(x)=f(a(x))\) 的组合义务: - -1. **被调函数确实满足自己的已声明契约**:有可信的源码与证据绑定。 -2. **调用点满足前提**:从调用方条件和实参绑定证明 \`requires_f(a(x))\`;不得把任意声明当成假设。 -3. **组合后调用方结论成立**:使用被调函数的已证保证、调用方实际执行流和路径条件,向 Lean 提交调用方定理。 -4. **失效传播**:源码、签名、接口、契约或依赖证明改变,旧证书不可继续使用,除非新的实现已经重新满足相应保证。 - -\`src/knowledge/unified.rs\` 是统一入口,逐个从当前 Marqdo AST 降级受支持的纯函数,按静态导入 DAG **自底向上**生成独立 Lean 模块。每个模块定义源派生函数并证明该函数自己的契约;调用方导入已经编译的下游模块,以其契约定理为假设链的可验证依据,既不添加 \`axiom\`,也不内联下游源码。生成的每个模块均单独通过 Lean 内核,证书绑定: - -- 精确的源语义身份与传递依赖闭包; -- 受支持的源码表达式及控制结构; -- 模块生成次序、导入关系、源码摘要和已编译 Lean 摘要; -- 工具链版本及受限证明作用域。 - -\`marqdo knowledge replay\` 必须重读当前源文件,重新生成这些模块与依赖,再独立编译并逐项比较,不能仅仅读取带有 \`proved\` 标记的本地 JSON。 - -旧有常量、参数投影、表达式后端的证书仍可重放;新证明优先走统一管线,避免把多个实现拼成互相矛盾的证明状态。 - -### 当前统一后端的精确定义 - -当前实现接受: - -- 静态、无副作用、跨文件的纯函数调用与有限、无环调用图; -- 参数完整、必要且无默认值;源代码参数、签名和调用点均匹配; -- 整数字面量、形参/局部变量、加减、一元负号,以及在支持的片段内由常数参与的乘法; -- 顺序局部赋值、直接返回、具有显式 \`else\` 且每条分支都返回结果的普通条件分支; -- 每个函数一个可识别、无条件、以 \`结果\` 为左侧的受限数值比较契约(等于或简单大小比较); -- 多次静态调用与递归依赖**图上的多层模块**,由证明模块的拓扑顺序组合。 - -当前实现**不接受**: - -- 循环、递归、非终止、并发、隐式/动态分派、插件副作用、没有可信模型的异常; -- 任意表达式值、除法/浮点/公式数值、未核验的运行时整数范围、缺省或非位置实参; -- 需要证明前置条件却没有调用方路径桥接证据的**条件契约**(可先由 \`proof-deps --verify\` 生成/检验独立义务;不能直接用无条件契约代替); -- 非穷尽分支、分支后复杂状态合并、无法静态绑定的调用、未覆盖的语句类型; -- 任何企图把 \`model_proved\` 直接提升为全语言 \`proved\` 的操作。 - -这个子集提供真正的**组合机制**,不宣称任意 WP 自动求解、全部 Marqdo 运行时对应、完整 Hoare Logic 或未限制的程序正确性。 - -## 5. 还需要开发哪些内容、哪些明确不需要 - -### 当前阶段必需(完成后可停止无界扩张) - -1. 所有源文件上的可寻址索引、定理证据与版本来源绑定有效。 -2. 一个可用的静态契约组合通路,而非恒定返回、形参返回、算术返回三套互不兼容的证明规则。 -3. 在明示纯函数子集中支持符号实参、顺序组合、基本条件分支、多层静态模块组合。 -4. 真 Lean 证书独立重放与完整负例护栏(假结论、来源变化、未解义务、插件、溢出风险)。 -5. 可查询的 \`evidence.grade\`,让智能体区分证明、模型证明、测试、外部假设、未知与过期。 -6. 编译、知识索引、原有运行命令和解释器不发生回归。 - -### 扩展按需求逐步添加 - -- 对实际量子算法或标准库有价值的归纳、循环不变式、递归终止、特殊数据类型、插件实现见证; -- 更大范围的契约谓词、复杂路径 WP、数值类型收窄和溢出条件; -- 与真实外部测量、实验数据和 agent 轨迹对接的可复现证据。 - -### 当前明确不作为完成门槛 - -- Lean 对所有 Marqdo 代码自动证明; -- 为每个外部 API、未知插件、远程服务或量子硬件建立形式语义; -- 完整并发语义、全部递归及任意循环的自动终止证明; -- 把不可判定问题或自动证明超时当成系统故障; -- 把抽象模型的可证明性与真实环境事实的真实性混为一谈。 - -**阶段完成**指有明确的支持清单、严格的拒绝行为、自动 CI 与不夸大的证据等级,而不是新增语言特性就继续追逐无限泛化。 - -## 6. 智能体视角:知识制品应怎样使用 - -对 agent 的安全接口不应只返回 \`true/false\`,而应返回: - -- 地址:\`SymbolId\` / 锚点; -- 执行接口:签名、前置条件、效应权限; -- 逻辑保证:受支持契约及其 \`proof_scope\`; -- 证据:\`grade\`、来源、版本、独立重放状态; -- 未解决义务:待证谓词、未建模效应、需要测试/实验的事实; -- 依赖闭包与失效原因。 - -智能体可以优先选择 \`model_proved\` 且输入满足限制的算法片段;在真实科研设备/外部系统调用上,同时查询 \`tested\` 证据与 \`assumed\` 的安全边界。过期制品不得直接复用。 - -这体现 Marqdo 的原创价值:**文档直接成为知识身份、工具接口、形式契约和执行证据的共同承载体**,而不是简单把 Markdown 文字翻译成另一种程序语言。 - -## 7. 验收清单与真实 CI - -核心命令: - -\`\`\`bash -marqdo knowledge compose --strict --json . -marqdo knowledge replay <generated-certificate> --json . -marqdo knowledge proof-deps --verify --json . -\`\`\` - -\`.github/workflows/modular-proof-smoke.yml\` 用真实 Lean 核验统一契约的模块组合和独立重放;\`.github/workflows/knowledge-proof-full-gate.yml\` 跑旧版证明、知识关联、可执行知识和差分测试。 - -正例至少包含:跨文件纯函数证明、符号参数、两次连续调用、三层静态模块导入、穷尽分支以及调用方不等式结论。反例至少包含:假契约、修改传递依赖、重放过期证明、模糊签名、未支持运算、动态/外部调用、非穷尽分支,以及错误的证据等级提升。 - -任何失败、缺少 Lean、证书与源码不一致、依赖过期或不支持的语义都必须显式拒绝出证或返回未核验状态。运行中的 CI 和缓存报告不能代替最新提交的核验结果。 - -## 8. 结论 - -Marqdo 知识编译的合理完成形态是 **Verified Knowledge Compiler(可验证知识编译器)**: - -> 能证明的知识生成可复用的形式证明;不能证明的知识保留明确证据与假设;所有知识均可统一寻址、依赖追踪、组合与执行,永不把未证明的内容伪装成已证明。 - -证明的是**明确作用域中的性质**,可信性依靠**证据分级、语义对应、来源追踪与受控执行**共同建立。这个目标可验收、可维护,也适合智能体与量子科研应用的发展方向。 diff --git a/doc/design/view-debug.md b/doc/design/view-debug.md deleted file mode 100755 index cfd2304..0000000 --- a/doc/design/view-debug.md +++ /dev/null @@ -1,42 +0,0 @@ -# View 调试(`marqdo debug`) - -| | | -|---|---| -| 状态 | **v1(独立 debug 页)** | -| 日期 | 2026-08-05 | -| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [view-document-annotations.md](view-document-annotations.md) · [pipeline-debug.md](pipeline-debug.md) | - -## 分工 - -| 命令 | 角色 | -|------|------| -| `marqdo view` | 文档浏览器:**叙述保真文档面** Structure + Execution + Source;函数大纲与搜索;跑后引出标注;**无断点**(见 [view-document-annotations.md](view-document-annotations.md)) | -| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;AST Structure + BP;**仅 live** | - -静态 `gh-pages` / `view output` **不能**真断点。 - -## Debug 布局(对齐常见调试器) - -参考 VS Code / Chrome DevTools / Jupyter debugger: - -``` -┌ Toolbar: Start · Continue (F5) · Step (F10) · Stop · status ─┐ -├ Files ─┬─ Structure (gutter BP) + outline ─┬─ Variables ┤ -│ │ ├─ Breakpoints │ -│ │ └─ Call stack │ -├────────┴────────────────────────────────────┴────────────────┤ -│ Debug Console (session stdout) │ -└──────────────────────────────────────────────────────────────┘ -``` - -- 暂停粒度:语句起点(树遍历)。 -- 无断点时 Start 停在第一句。 -- Structure 为断点面(非 Source 行)。 - -## API - -与此前相同:`POST /api/debug/start|continue|step|stop|breakpoints`(仅 debug 服务)。 - -## View 大纲 - -Structure 旁(或窄屏下方)函数树:`#fn-{line}` 锚点 + 搜索框过滤 `data-fn` / `data-fn-path`。 diff --git a/doc/design/view-document-annotations.md b/doc/design/view-document-annotations.md deleted file mode 100755 index a148c69..0000000 --- a/doc/design/view-document-annotations.md +++ /dev/null @@ -1,113 +0,0 @@ -# View:文档面与结果引出标注 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-10-15 | -| 相关 | [view.md](view.md) · [view-debug.md](view-debug.md) · [view-markup-surface.md](view-markup-surface.md) · [view-execution-trace.md](view-execution-trace.md) · [view-frame-selection.md](view-frame-selection.md) · [view-prose-annot-gaps.md](view-prose-annot-gaps.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) | - ---- - -## 1. 动机 - -`.mq.md` 是叙述与程序的同一载体。`marqdo view` 的 Structure 必须**保真叙述**,并在可执行标记旁展示运行结果。 - -旧 Browse Structure 用 AST 卡片重建语句,并用 `emit_comments` 只插入**语句行之前**的注释。当叙述与 `**…**` / `*…*` / `` `名` `` 在同一行时,该行被 Stmt 占用,叙述被丢弃——信息密度接近 debug,不适合文档浏览。 - -## 2. 模式分工 - -| 命令 | Structure | 叙述 | 结果 | -|------|-----------|------|------| -| `marqdo view`(Browse) | **文档面** | 保留并为主 | 跑后引出标注(callout + CSS L-leader) | -| `marqdo debug` | AST 卡片 + BP gutter | 弱化/可折叠 | Variables / 步进;不做文档 callout | - -断点与逐步执行**仅**在 debug。静态 `view output` 与 live view **共用** Browse 文档面渲染。 - -## 3. 视觉语法 - -``` -文本段…… `变量` …… **语句** …… *返回* - ━━━━━ - │ - └──→ 结果标注 -``` - -1. 叙述正文正常排版(Markdown)。 -2. 可执行片段高亮,并带底部分割线(underline)。 -3. 段落下方 **annotation band** 放结果 callout。 -4. **CSS L-leader**(绝对定位小盒 + `border-left` + `border-bottom`)连接锚点与 callout。**不使用 SVG。** -5. 拥挤 / 极窄屏 / `prefers-reduced-motion`:取消长横折,改为编号 keyed 列表。 - -关联强度(递减):同色 underline + callout 色条 + label → CSS L-leader → keyed 编号。 - -对齐 [view.md](view.md) HIG:系统字体、无外链、浅色、克制装饰。 - -## 4. 文档面渲染 - -实现:`src/view/document.rs`;Browse 入口经 `render_module_structure` 调用。 - -| 源内容 | 呈现 | -|--------|------| -| 纯叙述段 | Markdown HTML;无 `comment` badge / 厚卡片 | -| 含 `ProseBit` 的行 | 原文保留;Decl / BoldCode / ItalicReturn 包 `mark.mq-anchor`(字节偏移来自 `scan_prose_line`) | -| 整行结构(`#` / `>` / `-` / `1.` / 表) | 表面语法保真(见 [view-markup-surface.md](view-markup-surface.md));整句可作锚点 | -| 函数标题 | 轻量 heading + `id="fn-{line}"`(大纲跳转不变) | - -Debug 仍走 `render_module_structure_mode(..., Debug)` 的 AST 卡片路径。 - -## 5. ViewAnnot - -跑后(或 `--no-exec` 时为空)组装标注集,嵌入文档面 `data-*` 与 band HTML。 - -| 字段 | 含义 | -|------|------| -| `id` | 稳定短 id(页内唯一) | -| `kind` | `bind` · `return` · `call` · `expr` · `branch` · `loop` · `writeback` | -| `anchor_line` | 1-based 源行 | -| `anchor_byte_start` / `anchor_byte_end` | 行内字节范围(可选;整行锚点可省略 end) | -| `label` | 短标题(名 / return / arm / loop) | -| `value` | 截断显示 | -| `detail` | 完整文本(inspect) | - -| kind | 数据来源 | 锚点 | -|------|----------|------| -| `bind` | **StmtEvent post-stmt**(赋值执行后的值);禁止用入口终态回填初始化行 | 该赋值行 | -| `return` | 返回事件或入口返回 | ItalicReturn / Return | -| `call` / `expr` / `writeback` | writeback 槽、调用摘要 | 语句行或 BoldCode | -| `branch` | `ViewTrace`:命中 arm、次数 | 条件 / arm | -| `loop` | `ViewTrace`:迭代次数、末次 item | While / ForEach 头 | - -标记面、结构块、多调用帧与 AI JSON 见 [view-execution-trace.md](view-execution-trace.md)。 - -`ViewTrace` 由 tree 解释器在 capture 时静默收集,**不**写入 stderr;与 `trace_eval` 调试轨迹分离。Bytecode 后端可暂无 trace(标注降级为 writeback)。 - -## 6. 布局与密度 - -- 每段默认最多 **4** 个常显 callout;其余 hover / 「show more」。 -- Leader:按锚点 x 排序 callout,避免交叉;窄屏改为短竖线 + 堆叠。 -- 客户端:`ResizeObserver` 重算 leader 盒的 `left/top/width/height`。 -- 静态导出:页载 JS 跑一次布局。 - -右侧 **Variables** 仍为全集绑定;callout 为就地摘要,点击可打开同一 inspect。 - -## 7. 非目标 - -- 不在 view 内做断点 / 单步(见 [view-debug.md](view-debug.md))。 -- 不新增作者侧标注 DSL / frontmatter 指令。 -- 不引入外链字体、npm 组件或 SVG leader。 -- 不把 DB/auth 等塞进 view 壳层。 - -## 8. 验收 - -1. `inc-prose.mq.md`:叙述「对于输入变量…」完整可见;`n` / `n=n+1` / 返回高亮。 -2. 跑完后:值经 underline + CSS L-leader 连到下方标注(无 SVG)。 -3. 分支/循环样例:可见命中 arm 与迭代次数(有 ViewTrace 时)。 -4. `marqdo debug` 仍为 AST + 断点;叙述不抢主视觉。 -5. 无外链字体/新依赖;`view output` 可离线打开。 - -## 9. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-10-15 | 初稿:文档面、ViewAnnot、CSS L-leader、与 debug 分工 | -| 2026-10-15 | bind = post-stmt;交叉链 view-execution-trace | diff --git a/doc/design/view-execution-trace.md b/doc/design/view-execution-trace.md deleted file mode 100755 index cd07304..0000000 --- a/doc/design/view-execution-trace.md +++ /dev/null @@ -1,103 +0,0 @@ -# View:执行轨迹与文档面保真 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-10-15 | -| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [view.md](view.md) · [view-markup-surface.md](view-markup-surface.md) | - ---- - -## 1. 目标 - -`marqdo view` Browse Structure 必须同时做到: - -1. **标记面**:变量名 / 可执行语句 / 返回值按表面渲染(无源码定界符字面量)。 -2. **结构块**:GFM 表、循环(`-`)、分支(`1.`)有正确 HTML 与缩进。 -3. **语句后值**:赋值行标注该语句执行后的值,不用入口终态回填。 -4. **执行臂**:高亮实际走的分支臂。 -5. **多调用帧**:同函数多次调用可用下拉切换经历。 -6. **AI 可读**:与 HTML 同源的 `ViewExecutionReport` JSON。 - -Debug 仍用 AST 卡片 + 断点;不做文档 callout。 - -## 2. 标记面 - -| 源标记 | 显示(无定界符) | class | -|--------|------------------|-------| -| `` `名` `` / `` `名`=默认 `` | `名`(默认次要后缀) | `mq-anchor mq-decl` | -| `**…**`(可执行) | 内层文本 | `mq-anchor mq-code` | -| `*…*`(返回) | 内层文本 | `mq-anchor mq-return` | - -`data-byte-start/end` 仍为源码字节偏移(供 CSS L-leader)。软强调不进 anchor。 - -## 3. 结构块 - -| 块 | 呈现 | -|----|------| -| GFM 表 | `<table class="doc-table">` | -| `-` 循环 | `<ul class="doc-loop">`,体按源缩进 `--doc-indent` | -| `1.` 分支 | `<ol class="doc-branch">`;命中 `arm-taken`,未走 `arm-miss` | -| 公式 / 外联代码 | 现有 formula-card / code-card | -| `>` 调用 | 表面高亮,非整行灰 code | - -## 4. StmtEvent / CallFrame - -解释器 capture 时静默采集(非 `trace_eval` stderr): - -```text -StmtEvent { - line, kind, // assign | return | call | branch | loop | bind_ref - name?, value_after?, // post-stmt 或求值结果 - arm_index?, iter?, - call_id // 当前用户函数调用帧 -} - -CallFrame { - call_id, fn_name, fn_line, ordinal, - args_brief, // 短摘要供下拉 - events[] // 或全局 events 用 call_id 过滤 -} -``` - -- Assign → 写入后的值挂在**该行**。 -- 循环内多次写入:UI 默认末次;可带次数。 -- Branch → taken `arm_index` + 条件摘要。 -- 进入用户函数分配 `call_id`;`# main` 单帧无下拉。 - -## 5. ViewExecutionReport(AI) - -```json -{ - "version": 1, - "path": "…", - "ok": true, - "calls": [{ "call_id": 1, "fn": "等级说明", "ordinal": 1, "args_brief": "等级=及格" }], - "events": [{ "line": 24, "kind": "assign", "name": "总分", "value_after": "0", "call_id": 0 }], - "bindings_final": { "均分": "73", "等级": "及格" } -} -``` - -产出:页内 `#mq-view-trace` JSON;live `GET /api/view-trace?path=`;SSE `done.trace_json`。 - -## 6. UI - -- 函数标题旁 `<select class="call-picker">`(调用数 ≥ 2)。 -- 循环头旁 `<select class="loop-picker">`(迭代数 ≥ 2);默认最后一轮;摘要 `分 = 分数表[i] · value`。 -- **源码常显**:切换帧只改 chip / 臂高亮,不 `hidden` 结构节点。详见 [view-frame-selection.md](view-frame-selection.md)。 -- CSS L-leader(非 SVG);拥挤 keyed 降级。 - -## 7. 验收 - -1. 无字面 `**` / 返回定界 `*` / 变量外层 `` ` ``(Source 除外)。 -2. 表为真表格;循环/分支有缩进列表;未选中臂源码仍可见。 -3. `总分 = 0` 标注 `0`,非终态累加。 -4. 命中臂可视化;多调用下只显示当前帧的 taken。 -5. 循环可按迭代切换;JSON 含 `loops`;单测覆盖。 - -## 8. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-10-15 | 初稿:标记面、结构块、StmtEvent、CallFrame、AI 报告 | -| 2026-10-15 | 帧选择保真:call_id 分支、LoopFrame、源码常显 | diff --git a/doc/design/view-frame-selection.md b/doc/design/view-frame-selection.md deleted file mode 100755 index cae399d..0000000 --- a/doc/design/view-frame-selection.md +++ /dev/null @@ -1,123 +0,0 @@ -# View:调用帧 / 循环帧选择与结构保真 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-10-15 | -| 相关 | [view-execution-trace.md](view-execution-trace.md) · [view-document-annotations.md](view-document-annotations.md) | - ---- - -## 1. 问题(对照实测) - -1. **结构缺失**:切换函数调用下拉时,JS 按 `data-call-id` **隐藏** `.doc-exec`。未在本帧执行的分支臂体(赋值/返回)只有其它帧的 call_id,或仅有执行帧的 id → **未选中臂的源码被藏掉**,看起来像「臂消失 / 代码没渲染」。 -2. **调用记录混叠**:`Branch` 标注未带 `call_id`;`taken_arms` 按行号只保留最后一次命中。多帧下同一分支同时出现 `arm 1 taken` 与 `arm 2 taken`。 -3. **循环无帧**:循环只有总次数摘要;无法按迭代查看;`` - [分](分数表) `` 不能展示「当前是集合第几个元素」。 - -## 2. 定稿原则 - -| 原则 | 含义 | -|------|------| -| **源码常显** | 表 / 列表 / 分支臂 / 语句源码**永不**因帧选择 `hidden` | -| **轨迹随帧** | 标注 chip、臂高亮、变量值随「当前调用帧 / 当前迭代」变化 | -| **默认末帧** | 函数默认最后一次调用;循环默认最后一次迭代 | -| **一帧一真相** | 同时只展示一个 call_id(函数)或一个 (loop_id, iter)(循环)的轨迹 | - -## 3. 函数调用帧 - -### 数据 - -`BranchHit` / 相关 `StmtEvent` 必须带 `call_id`。`ViewAnnot` 的 branch/bind/return 同样带 `call_id`。 - -### UI - -- 函数标题旁 `<select class="call-picker" data-fn="…" data-scope="fn">` -- 选项:`1: 等级=及格` / `2: 等级=优秀` -- 默认选中最后一次 - -### 客户端(`applyCallFrame`) - -1. 读 `#mq-view-trace` JSON。 -2. 过滤 `events` where `call_id == selected`。 -3. **不**设置结构节点 `hidden`。 -4. 更新该函数作用域内: - - `.annot-chip[data-call-id]`:仅显示匹配帧;无 call_id 的结构说明类可保留 - - `.doc-branch[data-line]`:按该帧的 branch 事件设置 `arm-taken` / `arm-miss`(全部臂仍可见) - - 绑定 chip 的 `.annot-value`:用该帧 assign/return 事件刷新(同名同行取末次) - -## 4. 循环迭代帧 - -### 数据 - -```text -LoopFrame { - loop_id, line, - item_name?, // "分" - collection?, // "分数表" - iterations: [{ index, item_value, call_id }] // index 0-based -} -``` - -`StmtEvent` 增加可选 `loop_id`;循环体内事件带 `iter`(1-based 或 0-based,JSON 内统一 **0-based index**)。 - -### UI - -- 循环头(`- [分](分数表)`)旁:`<select class="loop-picker" data-loop-id="…">` -- 选项:`迭代 1: 分=92` … `迭代 4: 分=88` -- 默认最后一次 -- 头旁摘要 chip:`分 = 分数表[3] · 88`(下标 0-based 显示为 `[i]`) - -### 客户端(`applyLoopFrame`) - -1. **只显示当前迭代**:带 `data-iter` 的 chip 仅保留选中项;其余 `hidden` + `is-frame-hidden`(SSR 默认已按末轮预隐藏)。 -2. 更新头摘要 chip(无 `data-iter`)为当前选项文案。 -3. 不隐藏循环体源码。 - -## 5. 分支臂渲染 - -- 所有臂(含 else)**始终**渲染完整头 + 体(含 `*返回*` / 赋值)。 -- `arm-miss` 仅降低不透明度,**不** `display:none` / `hidden`。 -- 高亮仅反映**当前帧**的 taken `arm_index`。 - -## 6. AI JSON 增量 - -`ViewExecutionReport` 增加: - -```json -"loops": [{ - "loop_id": 1, - "line": 27, - "item": "分", - "collection": "分数表", - "iters": [{ "index": 0, "value": "92" }, { "index": 3, "value": "88" }] -}] -``` - -`events[].call_id` 必填;循环体内事件带 `loop_id` + `iter`(index)。 - -## 7. 验收 - -1. 未选中分支臂源码始终可见(含返回句)。 -2. 切换「等级说明」调用:只显示该帧的 arm taken;变量/返回值对应该帧。 -3. 循环下拉默认最后一轮;`分 = 分数表[3] · 88`;切换迭代后体内累加值变化。 -4. `#mq-view-trace` 含 `loops` 与带 `call_id` 的 branch 事件。 -5. `cargo test --lib view::` 全绿。 - -## 8. 开发计划(已执行) - -| 阶段 | 内容 | 状态 | -|------|------|------| -| D0 | 本文档 + `view-execution-trace.md` 交叉引用 | ✅ | -| D1 | `BranchHit.call_id`;`LoopFrame` / `LoopIter`;`StmtEvent.loop_id` | ✅ | -| D2 | 解释器:foreach/while 推栈;BindRef `分=分数表[i]`;assign 带 iter | ✅ | -| D3 | `build_view_annots`:分支带 call_id;LoopFrame 选项;报告 JSON `loops` | ✅ | -| D4 | 文档面:源码不贴 `data-call-ids`;call picker `value=call_id`;loop picker;SSR taken=末帧 | ✅ | -| D5 | JS:`applyCallFrame` / `applyLoopFrame` — 只滤 chip + 重算 arm,不 hidden 结构 | ✅ | -| D6 | 单测:多调用不同臂、loop 末项、HTML 三臂返回 + picker | ✅ | - -## 9. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-10-15 | 初稿:源码常显、帧过滤、循环迭代 picker | -| 2026-10-15 | 按计划落地 D1–D6 | diff --git a/doc/design/view-knowledge-reading-experience-2026-10-24.md b/doc/design/view-knowledge-reading-experience-2026-10-24.md deleted file mode 100755 index bb6036a..0000000 --- a/doc/design/view-knowledge-reading-experience-2026-10-24.md +++ /dev/null @@ -1,463 +0,0 @@ -# View 可执行知识阅读体验重设计 - -| 项目 | 说明 | -|---|---| -| 日期 | 2026-10-24 | -| 状态 | 详细设计建议,待实施;不是已交付能力声明 | -| 审计基线 | `b8a4ddd` / Marqdo 2.1.1;使用当前源码构建的 debug CLI 复核 | -| 输入 | 用户提供的 view 截图:Executable Knowledge 在 Structure 前,Steps、Target、Kind、Signature、Effects、Verification、Lock digest 等字段大量铺开 | -| 范围 | Live view、静态导出、正文结构、知识说明、运行结果、来源与状态呈现;不改语言语义,不增加作者必填的展示 DSL | -| 关联 | [文档原生开发指导](document-native-development-guide.md)、[View 总体设计](view.md)、[文档面与标注](view-document-annotations.md)、[求道相关框架缺口](../roadmap/qdagent-knowledge-support-gaps-2026-10-24.md) | - -## 1. 设计决策 - -**View 首先呈现知识文档本身,结构帮助读者理解和定位,机器信息解释当前所读内容。** 正文、程序结构、知识关系与执行证据应由同一份源文档关联起来,而不是顺序展示几份互相脱节的报告。 - -确定以下方向: - -1. 移除正文之前整块展开的 Executable Knowledge。主阅读流首先出现作者的标题、介绍和内容;不把完整机器报告简单搬到正文后继续平铺。 -2. 保留并改进现有 Structure 的叙述保真文档面,面向读者命名为“文档”。正文、表格、公式、函数和可执行步骤在原位置阅读,不生成一份模型改写的平行说明书。 -3. 右侧“本文结构”负责章节与知识单元定位;选中知识片段后,在同一辅助栏展示它的解释、输入输出、来源和验证依据。源码标识、摘要与完整协议放在可展开的技术详情中。 -4. 运行结果就地关联到对应步骤,明确运行实例与输入;完整日志、运行控制和源码放在正文后。看见一个数值时,读者必须能知道它是文档声明、计算结果还是历史快照。 -5. 静态分析、程序运行、测试断言、来源关联和领域确认分别表达。不能用一个 `ok`、`pure` 或绿色“已验证”覆盖不同事实。 -6. 功能渐进增强:无 JavaScript、静态导出、移动端、打印时仍能读完文档、定位知识和查看必要依据。普通短文不变成复杂仪表盘。 - -这些决策恢复 [view.md](view.md) 原有“文档面为主、Browse 与 Debug 分工”的方向,同时修订过度依赖引出线和默认展开技术面板的呈现方式。 - -## 2. 现状审计:为什么截图难读 - -### 2.1 可定位的实现依据 - -| 观察 | 当前代码 | 对阅读的影响 | -|---|---|---| -| 知识面板位于正文前 | [html.rs / page_file](../../src/view/html.rs) 的模板顺序为 notebook → knowledge → Structure → Execution → Source | 必须先越过辅助资料才能看到文档;模块越多越严重 | -| 所有制品一律展开 | [render.rs / render_knowledge_html](../../src/view/render.rs) 按文件筛选 artifacts,并逐项输出完整 `<dl>` | module/type/function 同等突出,容器元信息挤占知识内容 | -| Steps 脱离所属结构 | 同函数把当前文件所有 steps 放在单一 `<ol>` 中,展示 kind、label、完整目标 ID | 静态步骤容易被误读为实际执行顺序;调用/循环/正文引用混在一起 | -| 内部字段未经阅读转译 | URI、签名、effects、verification 拼接文本、完整 sha256 默认可见 | 读者仍不知道这项知识解决什么问题、怎样用、依据在哪里 | -| “Lock digest”名实不符 | 该字段实际显示 `artifact.hashes.artifact`;[mod.rs](../../src/view/mod.rs) 编译使用 `LockMode::Off` | 制品摘要被误读为已经锁定且通过复现检查 | -| 静态说明与运行脱节 | 每张卡固定输出 `Not executed by knowledge preview.`;实际 run capture 在另一条路径 | 即使页面有运行结果,也很难理解“未执行”到底指什么 | -| 分析失败静默消失 | `build_file_view` 对语义编译结果使用 `unwrap_or_default` | 无知识、分析失败、尚未分析在界面上都可能表现为空 | -| 标题与层级表达较弱 | `page_file` 标题取文件名;[document.rs / render_fun_heading](../../src/view/document.rs)统一用 h3 | 作者 frontmatter 标题未用于页标题,嵌套结构主要靠其它线索判断 | -| 知识组件缺少专用布局 | `knowledge-*` 在 HTML 中有类名,但 `html.rs` 没有与面板匹配的专用样式规则 | 大量使用默认列表/定义列表排版,空白多、关系弱,和正文主题缺少一致约束 | -| 新旧皮肤叠加 | `html.rs` 内基础 view CSS 与 `notebook_ui` 大块 notebook 主题共存 | 正文、注释、知识区的字号和密度不一致;不能只修一个卡片颜色 | -| 验收主要看元素存在 | [executable_knowledge.rs](../../tests/executable_knowledge.rs) 的 view 用例检查 step 类名、kind 和 `#stmt-` 链接 | 没检查正文优先、跳转目标存在、可读文案和实际布局 | - -已有能力应保留:[document.rs](../../src/view/document.rs) 的叙述/表格保真、Occlusion 描述与实现分离、函数大纲、调用帧/循环帧选择、[annot.rs](../../src/view/annot.rs) 的真实执行标注。重新设计应基于这些能力,而不是退回 AST 卡片浏览器。 - -### 2.2 对截图的解释边界 - -截图可直接确认:机器字段先于正文、Steps 只有 `call print`、长 URI/摘要显著占位、英文状态串缺少解释,以及深色底上的孤立黑色短线。 - -黑色短线的具体来源尚未在浏览器中复现。代码中存在 annotation leader、布局重算和主题覆盖,可能需要检查,但本文件不把它们断言为唯一根因。实施时应使用用户截图对应页面复现,检查实际 DOM、computed style 和几何位置;不能用全局隐藏所有 SVG/边框来掩盖问题。 - -### 2.3 本轮实际复核 - -把 [public/features/01-phase-i-treewalk.mq.md](../../public/features/01-phase-i-treewalk.mq.md) 复制到临时目录,使用 debug 2.1.1 执行静态导出并检查生成 HTML:knowledge 确实在 structure 前,共 3 个 `knowledge-card`(含 Steps)和 2 个完整 sha256。该短文的核心只是介绍 tree-walk 流程并打印一句话,当前辅助内容明显过重。 - -另用隔离临时文件复核 `view output --no-exec`:嵌入的 `fs.write_text` 仍创建了临时标记文件。原因是 [output.rs / write_static](../../src/view/output.rs) 先调用会执行的 `build_file_view`,再在 `opts.no_exec` 分支清空结果。**这是已复现的执行/呈现不一致,必须修复,不能仅把标签改成“未运行”。** §9 给出新的构建边界。未执行线上浏览器像素比对,本文线框为目标设计。 - -## 3. 读者任务与设计成效 - -| 读者任务 | 默认应看到 | 按需展开 | 成功判据 | -|---|---|---|---| -| 理解这篇文档 | 作者标题、介绍、正文和核心表格/步骤 | 完整源码 | 不滚过机器报告就能开始阅读 | -| 看懂文档结构 | 章节、类/规则/函数的真实层级,当前位置 | 参数和局部步骤树 | 能判断一个步骤属于哪个知识单元 | -| 理解某项知识 | 描述、简洁公式/调用、条件、返回含义 | payload、契约、精确目标 | 能解释它做什么、需要什么、产生什么 | -| 判断结果是否可信 | 来源状态和所选运行的明确结果 | 测试、来源片段、版本和诊断 | 能区分“可以运行”和“事实成立” | -| 跟踪跨文档复用 | 友好目标名、所属文档、输入输出 | 依赖关系、完整标识 | 能到达定义并返回原阅读位置 | -| 检查某次运行 | 本次输入、选中调用/迭代、对应结果 | 日志、历史帧 | 不把不同运行的值混在一起 | - -不要求所有读者理解 SymbolId、IR、hash 或 effect 协议。开发者仍能找到这些信息,但它们不再成为阅读的前置条件。 - -## 4. 页面信息架构 - -### 4.1 默认桌面布局 - -```text -┌ Marqdo 项目 / 文档路径 搜索 主题 ┐ -├───────────┬───────────────────────────────┬────────────┤ -│ 文件目录 │ Phase I — tree-walk interpreter│ 本文结构 │ -│ │ Lex · parse · check … │ 介绍 │ -│ 当前文件 │ [运行记录:尚未运行] [详情] │ main 入口 │ -│ │ │ │ -│ │ Milestone: Phase I … │ │ -│ │ Pipeline: load → … → eval │ 选中后: │ -│ │ │ 当前知识 │ -│ │ main · 入口 │ 作用 │ -│ │ 输出说明 print text=… [说明] │ 输入/返回 │ -│ │ │ 来源/条件 │ -│ │ ▸ 运行与结果 │ 检查/运行 │ -│ │ ▸ 完整源码 │ 技术详情 ▸ │ -└───────────┴───────────────────────────────┴────────────┘ -``` - -布局是文件导航、主文档、一个辅助栏,不能增加第四条永久侧栏。右栏上部保留可收起的“本文结构”;用户选中片段后,下部显示“当前知识”。空间不足时以当前知识替换下部内容,并提供“返回目录”操作。打开/关闭详情不改变正文宽度,避免重排导致阅读位置跳动。 - -主文档的默认顺序: - -1. 文档标题、已有 description、简短状态入口;title 缺失时退回文件名。 -2. 源文档的正文、结构和轻量就地知识说明,保持作者顺序。 -3. “运行与结果”:运行按钮、输入、所选运行结果、输出图形/日志;已有重要失败有就地入口。 -4. “完整源码”及“文档技术信息”,默认折叠。 - -不在顶部强制生成内容摘要、全量函数清单、巨大状态矩阵或知识关系图。没有 description 时不调用 LLM 补写。结构大纲始终可达,正文不因折叠辅助栏而变成无结构的文章。 - -### 4.2 尺寸与响应式规则(设计目标) - -| 可用宽度 | 布局 | -|---|---| -| ≥1280 CSS px | 文件栏约 220–260px;正文弹性;辅助栏约 280–320px;正文中文行长约 32–44 字 | -| 900–1279px | 文件栏可收起;正文优先,辅助栏可切换为有标题的侧抽屉 | -| <900px | 单列文档;“目录”“当前知识”作为明确按钮打开抽屉或块内 details | -| 320–390px 手机 | 标题、正文、状态不横向溢出;长表格/代码局部滚动,整页不左右拖动 | -| 打印 | 正文展开,必要来源/验证摘要转为节后附注;交互按钮和导航隐藏;技术原始字段按导出选项包含 | - -在 1440×900、100% 缩放的短文验收样例中,首屏应包含至少一段正文和首个主要结构单元;状态头不得因每个 artifact 增长而把正文推出首屏。此约束不截断作者自己的长标题或介绍。 - -### 4.3 普通文档与复杂知识文档采用同一布局 - -- 普通说明页只有 main/print:显示原文与输出操作,技术区保留模块信息;不强制展示“1 项可执行知识”卡。 -- 可复用函数库:目录列出函数;函数标题下出现紧凑签名和“说明”入口;即使无 main,也能正常阅读。 -- 事实/规则文档:来源、条件与验证紧邻相应知识;来源问题不能藏进页尾。 -- 教程/Notebook:保留源文档的代码单元与结果;全局单元运行条收进运行区域或显式工作模式,不能把所有文章永久变为 notebook 工具台。 -- 大文档:目录按真实层级和顺序组织,可搜索;正文不因知识数量膨胀为另一份报告。 - -## 5. 文档与结构呈现规范 - -### 5.1 标题、类与函数层级 - -页标题优先来自解析后的 frontmatter `title`,其次使用合适的源文档标题,再回退文件名;不要自行用正则重解析 YAML。保留原文标题内容,不擅自把技术名称改成模型生成的名称。 - -“本文结构”同时服务阅读和程序定位,但明确区分: - -- 作者章节按实际文档关系展示。 -- 可执行的类/类型、函数、入口附轻量类型词,例如“规则”“函数”“入口”;类型词来自编译结果或已声明元数据,不由标题猜业务类型。 -- 同一节点既是章节又是函数时只有一个目录项,旁边标类型,避免两棵树重复。 -- 嵌套函数、分支、循环在对应父节点下展开;语义归属与 Markdown 可视层级分别保留,不把所有内容都扁平化为 h3。 -- 普通段落引用不提升为函数;module 容器不自动成为一张与业务函数同权的卡。 - -DOM 标题使用连续、可访问的层级;实际语法的 `#`/`##` 层数在源码面保留。用户复制源码时取得原始合法语法,而非为了 HTML 标题级别改写过的内容。 - -### 5.2 可执行步骤:就地解释并保留上下文 - -| 编译器步骤 | 默认阅读文案 | 展开后 | -|---|---|---| -| observe | “读取:商品单价” | 集合、取元表达式、字段说明、当前调用下的值 | -| derive | “计算:商品小计” | 公式、输入来源、计算条件、当前结果 | -| call | 优先作者标签;无标签时“调用 商品小计” | 目标、所属文档、实参映射、返回和运行记录 | -| iterate | “逐项处理:订单商品” | 集合、循环体、迭代数、所选迭代 | -| narrate | 正文保留作者描述,附“知识引用”入口 | 定义与来源;不当作已执行步骤 | -| navigation | 标准文档链接 | 正常导航,不显示虚构的执行结果 | -| 空 payload / stub | 作者描述 + “待实现” | 缺失的实现和已有诊断,不能展示成功数值 | - -名称来自当前节点的 label、声明说明、目标可读名,依次回退;没有业务描述时就显示“调用 print”,不得自动声称它是“验证知识”或“输出最终结论”。普通 print 在所属文档位置解释输出作用,放在“输出”类信息中,不作为高价值知识卡突出。 - -“步骤”列表只在当前知识详情中显示,标为“文档中的步骤”或“结构步骤”。静态序号不能暗示实际执行时序;实际轨迹另按运行事件呈现,分支和循环保留嵌套。 - -### 5.3 描述、实现与结果的三层关系 - -以 `**总价 = [计算订单小计](pricing.小计(数量, 单价))**` 为说明示意: - -```text -计算订单小计 [说明] - 总价 = pricing.小计(数量, 单价) ← 简短实现,次一级视觉 - 本次示例:数量 2,单价 30 → 60 ← 仅有匹配运行记录时出现 -``` - -作者的上下文句、返回说明、单位和条件仍在原位。短公式/实现可次级显示,长 payload 默认折叠到详情;显式“展开实现”控制可对当前知识单元生效。不得把所有代码完全藏掉,使“代码即文档”退化成只有自然语言标签。 - -复制操作区分“复制说明”和“复制源码”;源码来自源 span,保留必要定界符、参数和 import 依赖提示。显示为漂亮文本的结果不能被复制成伪造的可执行代码。 - -### 5.4 表格、条件与关系 - -数据表按作者结构呈现,表头固定语义,单位与列说明常显;契约表按输入/返回/约束组织。显示层不能把 Marqdo 列向集合悄悄换成行向记录;需要另一种预览时明确标为预览,并能查看真实形状。 - -前提条件与失败分支不得因“简洁”隐藏。默认显示全部分支结构,所选运行只突出实际命中的分支,继续遵守 [调用帧与结构保真](view-frame-selection.md)。 - -跨文档关系默认用可读链接,例如“使用:标准税率 · tax.mq.md”,而非 `mq://…`。直接依赖与被引用者各列前几项并可展开;可选局部关系图放在详情层,不作为默认阅读画布。关系图必须有等价文字列表,并显示未知/动态关系,不能补画不存在的边。 - -## 6. 当前知识详情:回答问题,而非列出字段 - -### 6.1 内容顺序 - -```text -商品小计 函数 -根据数量与单价计算商品金额。 ← 仅引用已有描述 - -输入 数量:整数;单价:金额 ← 类型/单位未知则明确未知 -返回 金额 -条件 数量非负 ← 仅当已声明且可定位 -实现 数量 × 单价 - -来源 定价说明 / 第 2 节 [打开] -检查 契约未检查;测试未运行 [查看依据] -运行记录 示例 #2:2 × 30 → 60 [定位输出] -使用 … [查看定义] - -▸ 技术详情:精确标识、完整签名、效应、摘要、诊断 JSON -``` - -此处“金额”“数量非负”等只用于解释布局,不宣称当前样例具有这些元数据。没有信息就省略非关键行或写“未声明”,不得推断成“无限制”“没有来源也可靠”。缺失影响可用性时常显;纯工具没有业务来源并不自动是错误。 - -### 6.2 当前字段的去向 - -| 当前字段 | 新的主要位置与文案 | -|---|---| -| Target / `mq://…` | 标题处可读定义链接;完整 ID 在技术详情,可复制 | -| Kind / callable | 标题旁简短类型词;module 信息进入文档技术信息 | -| Signature | 输入/返回紧凑表;完整规范签名可展开 | -| Effects | “涉及的操作”,说明文件读写、网络等;未知明确显示,非纯不等于失败 | -| Verification 长串 | 分项检查和证据表,见 §7 | -| Lock digest | 更名“制品摘要”,技术详情内显示;锁状态单独来自真实 lock report | -| Depends on | 可读目标列表,指向定义与引用位置;未分析不能写“无依赖” | -| Execution 固定句 | 匹配运行记录,或“尚无该知识的运行记录” | -| SourceRef / applicability | 当前遗漏的关键内容:放入“来源”和“适用条件” | - -默认不铺完整 hash。技术详情可显示缩略摘要并提供全值/复制;缩略值不用于识别唯一性。没有读取锁报告时写“未检查锁定状态”,不能把拥有摘要显示成“已锁定”。 - -### 6.3 交互、跳转与返回 - -1. 点击正文的“说明”或目录知识项,选中同一 `node_id`;正文轻量高亮,右栏同步。键盘和触屏具有等价入口,不依赖 hover。 -2. 跳转到定义时保留来源文件、锚点、滚动位置和所选运行;返回恢复阅读位置。 -3. 文件、符号与语句不能只靠显示名称匹配。同名函数的详情显示所在文档和父结构。 -4. 默认不自动抢焦点、不因滚动不停替换用户正在阅读的详情。滚动只更新目录当前位置;点击选择才改变详情。 -5. 手机抽屉有标题、关闭、返回焦点和滚动管理;无 JS 时使用正文附近的原生 details 或页尾知识附注锚点。 -6. 当前 URI 不在导出范围内时显示“定义未包含在此次导出”,提供可读路径和复制引用;禁止输出必然失效的 `mq://` 或 live `/file` 链接。 - -## 7. 状态设计:读者必须知道什么被证明了 - -### 7.1 分离三个状态来源 - -| 状态来源 | 可以说明 | 不能说明 | -|---|---|---| -| 编译/静态分析 | 结构解析、目标绑定、契约检查结果、已建模效应 | 程序已运行、答案正确、资料真实 | -| 运行记录 | 指定输入、环境、源码版本下的执行与输出 | 覆盖所有输入、测试通过、来源可信 | -| 证据/验证记录 | 哪个断言/测试/来源核验通过,何时失效 | 未执行或未核验的其它部分也可靠 | - -顶部仅给紧凑事实,例如“静态分析完成 · 尚无运行记录”,或“有 1 项来源问题 · 查看”。普通 unknown/unchecked 不应制造全页红色警报;与当前结论直接相关的失败、过期、未解析必须就地提示且可定位。 - -### 7.2 分项文案映射 - -| 机器状态 | 阅读文案 | -|---|---| -| parse=passed | 文档结构可解析 | -| resolve=passed | 此项检查报告目标已解析;覆盖范围见详情 | -| contract=unchecked | 契约尚未检查 | -| execution=not_run | 尚无执行记录 | -| tests=unknown | 尚无测试记录 | -| evidence=sourced | 已关联来源,内容尚未核验 | -| evidence=unverified | 来源内容尚未核验;结合来源列表判断是否已关联 | -| missing_source / expired | 来源缺失 / 已过适用期 | -| domain=unreviewed | 尚无领域审阅记录 | -| effects=pure | 静态分析未发现已建模的外部操作;展开可看范围 | -| effects=unknown | 涉及的操作尚不能完全确定 | -| 无对应字段 | 未提供该项检查结果 | - -分项取值不能自动升级成综合“可信”。只有宿主选定的政策实际给出聚合结论,才显示“满足 ×× 政策”,同时附政策名称、版本与证据;业务条件还须明确展示。 - -### 7.3 结果来源与失效 - -每个运行值绑定 `run_id + source_digest + node_id + call_id + loop/iteration` 中适用的字段,展示本次输入或简短上下文。无节点映射时只展示整次运行输出,不硬塞到某个函数旁边。 - -静态导出有快照时标“导出快照”,附生成时间/输入;读者切换调用帧是在看历史结果,不叫“重新计算”。源码、依赖或来源与记录不匹配时标“历史结果,版本已变化”,不继续用成功样式绑定到新正文。 - -正文里的字面量可以显示为“文档声明值”;解释器实际执行得到的值才叫“运行结果”。没有值、返回 None、stdout 为空、尚未运行、执行失败必须分开,不能统一成 `(no stdout)`。 - -### 7.4 空态与错误态 - -| 情况 | 处理 | -|---|---| -| 没有可识别知识单元 | 正常显示文档,不插空知识面板 | -| 语义分析失败 | 保留可读正文/源码,显示“知识关系暂不可用”及可定位诊断 | -| 局部未解析 | 仅对应片段显示问题,保留其它已知结果 | -| 无运行或 no-exec | 运行区说明原因,使用中性状态,无绿色运行成功标记 | -| 运行失败 | 错误摘要定位到源片段;日志在运行区,静态知识仍可读 | -| 证据过期/冲突 | 相关知识常显问题、来源与影响;不静默选择一个结论 | -| 分析被截断/超过扫描范围 | 显示范围和未覆盖项;“未发现”不能替代“没有” | - -## 8. 视觉、密度与可访问性 - -### 8.1 排版与主题 - -正文建议 16–18px、行高约 1.65;辅助说明 13–14px、行高约 1.5;代码使用等宽字体,全文不因进入 notebook 主题缩为密集工具面板。主次依赖字号、间距和位置共同表达,不能仅靠颜色。 - -使用现有系统字体和主题机制,建立统一的 view tokens:正文/辅助文字、背景、细分隔、焦点、成功/警告/错误。知识组件只依赖 tokens,不硬编码黑色线条或白底。支持明暗主题,首次尊重系统/显式设置,不为这次改版再写第三套皮肤。 - -表格与长公式允许局部滚动;ID、路径在详情中可换行;主文无整页水平滚动。重要来源和适用条件不使用极浅灰隐藏。对比度验收目标:普通文字至少 4.5:1,大字和必要非文本边界至少 3:1;这些是实现验收目标,尚非本轮测量结果。 - -### 8.2 注释和连线 - -默认使用紧邻内容的短结果行或有标签的注释块,优先通过“同一节点名 + 明确位置”关联。长 L-leader 不再是默认必需元素;复杂节点可保留短连线,必须满足端点存在、在同一块内、不交叉、不覆盖文字。 - -当目标折叠、帧过滤、元素隐藏或几何测量失败时,不绘制连线。主题/字体/容器宽度变化后只重算当前可见块;采用可取消的局部布局更新,不全页不断测量。窄屏、打印、reduced-motion 下直接使用有编号的注释。截图中的孤立线条归入专门视觉回归场景。 - -### 8.3 键盘、屏幕阅读器与退化 - -- 目录用 nav,正文用 main/article,详情用有名字的 aside/section;标题层级连续。 -- 展开按钮有 `aria-expanded/controls`;选中状态、失败和待验证都有文字,不依赖颜色或图标。 -- 深链接滚动有 `scroll-margin-top`,聚焦目标不被固定工具条遮住;关闭详情后焦点回到触发点。 -- 不使用只有鼠标悬停才能看到的来源、代码或错误。大表格有标题与表头关系,日志可复制。 -- 无 JS 时正文、目录锚点、来源链接、原生 details 和静态结果仍工作;只失去实时联动与运行操作。 -- 选择帧不隐藏源结构;隐藏实现也不能删除文档含义和必需条件。 - -## 9. 技术设计与数据契约 - -### 9.1 从预拼 HTML 改为可关联的展示模型 - -当前 `FileViewModel.knowledge_html` 是独立 HTML 字符串,难以与正文、trace、诊断同步。建议新增结构化 `KnowledgePresentation`,在 Rust 端形成同一份模型,由正文、目录、详情共同消费。兼容阶段可保留旧字段,但不让它继续成为唯一知识接口。 - -```text -ViewDocument - document_id, source_digest, semantic_generation, title, description - blocks[] 保真正文结构及 source span - outline[] 标题/知识单元父子关系 - knowledge_nodes[] 对应 artifact/ref/step,不复制语义解释器 - diagnostics[] 范围、严重性、可读说明、定位 - execution_state 明确未运行/运行中/成功/失败/快照 - run_records[] 与文档版本相匹配的证据 - -KnowledgeNode - node_id, artifact_id?, symbol_id?, ref_id?, step_id? - owner_id?, source_span, display_name, authored_description? - kind, signature?, payload?, dependencies[], provenance[] - applicability?, verification[], effects, coverage - execution_refs[] -``` - -这些字段为建议契约,未承诺当前 IR 已提供所有信息。语义事实来自 `SemanticProject`,文档叙述来自解析后的源结构,执行事实来自 capture;缺少关系时展示 unknown,不让 UI 用名称模糊匹配或调用模型编造。 - -### 9.2 数据流 - -```mermaid -flowchart LR - S[源文档与项目边界] --> P[解析与语义分析] - P --> B[正文块与结构] - P --> K[知识节点与诊断] - R[显式运行或匹配的历史快照] --> T[执行记录] - B --> V[统一展示模型] - K --> V - T --> V - V --> D[正文与就地说明] - V --> O[目录与当前知识] - V --> E[运行区域与技术详情] -``` - -知识模型不通过“render HTML → 再抓取文本”生成。页面分析失败不可用空字符串吞掉,应保留有状态的结果;部分成功与整体失败分开。 - -### 9.3 源位置、稳定身份与锚点 - -目前 step 跳转用 `#stmt-{line}`,函数用 `#fn-{line}`。一行多个表达式、正文段落合并、同名函数、源码插行都会使单纯行号不够。 - -新增内部节点锚点注册表,将文档块、函数、语义 step/ref 与真实 DOM id 映射;使用 artifact/node 身份和源 span 生成页内唯一 ID,不把未经编码的 URI 当 DOM id。当前编译器没有稳定 SyntaxNodeId 的地方,退化为“源码版本 + span”,明确跨版本不可保证稳定;不能只把行号哈希一下就宣称稳定身份。 - -兼容现有 `#structure`、`#fn-N`、`#stmt-N` 链接,保留别名或定位映射;所有生成链接都验目标存在。跨文件 href 复用 [html.rs 的 LinkMode/href_file](../../src/view/html.rs),静态导出保持相对路径;路径展示解码与 URL 安全编码分离。 - -### 9.4 分离分析与执行,修正 no-exec - -将当前 `build_file_view` 拆成可组合路径(名称为建议): - -1. `analyze_document`:读取、解析、语义检查、生成静态展示数据,不执行目标程序。 -2. `capture_execution`:只有执行策略明确允许时调用 run/cell runtime,返回真实状态与源版本。 -3. `assemble_view`:关联正文、语义和匹配的结果,生成同一个展示模型。 - -`--no-exec` 必须在第 2 步之前分支,不能先跑后清空;snapshot 模式使用匹配快照,不为了构造 UI 又运行一次。Live 现有自动执行兼容行为在首轮不静默改变,必须通过显式 execution policy 传入并如实标注;若后续将 live 默认改为阅读时不执行,作为独立 CLI 行为变更发布和迁移。点击详情、查看来源、展开关系等阅读操作绝不能触发执行。 - -知识详情不要求通过运行得出静态信息。实现参数预览/试跑时,使用既有受控执行路径,不因“pure”字样绕过宿主能力边界。本文不新增一套求值器或权限系统。 - -### 9.5 Live 更新一致性 - -当前 SSE 会替换 structure_html/bindings_html/trace_json,而知识面板来自另一次静态编译,容易新旧混用。建议更新包包含文档摘要、语义代、run_id 和变更节点;前端仅合并兼容版本的数据。 - -运行写回导致源码变化时,重新分析后一次更新相互关联的正文、目录、知识与运行映射。原选中节点仍存在则保留选择/焦点/滚动;已消失则明确提示,不能悄悄指向同名节点。旧请求返回晚于新请求时按版本丢弃,不覆盖较新阅读状态。 - -### 9.6 性能与导出体积 - -避免每个页面重复编译整个项目。一次静态导出共享同一项目语义结果,逐页投影;live 按项目源指纹、编译器版本、配置和适用性时钟缓存,读取使用一致的语义代。来源/有效期变化必须使相关状态失效,不能无限缓存 sourced。 - -正文服务端生成,不等待 JS 初始化或全部知识图完成才出现。默认只嵌入当前文档必要知识,深层依赖按需取;静态导出则包含保证离线可用的局部数据与明确范围。大量结果采用折叠/分页,但不能让屏幕阅读器和查找失去正文。 - -性能验收目标:100 个知识单元的本地选择/展开交互 p95 ≤100ms;1000 单元目录可搜索而不阻塞正文滚动;导出项目的语义编译次数不随页面数线性重复。记录硬件、样例和体积,目标未达时先优化数据重复和布局测量,不以截断关键来源达标。 - -## 10. 实施文件与兼容策略 - -| 位置 | 建议变更 | -|---|---| -| [src/view/render.rs](../../src/view/render.rs) | 提取知识展示模型;替换全量 dl 面板;关联步骤归属、友好名称与诊断 | -| [src/view/document.rs](../../src/view/document.rs) | 源块/知识节点映射、正文就地入口、层级标题、可复制原始 span | -| [src/view/html.rs](../../src/view/html.rs) | 正文优先布局、辅助栏、详情/目录交互、状态组件、统一 tokens;保留 LinkMode | -| [src/view/mod.rs](../../src/view/mod.rs) | 分离分析/执行、保留诊断、组装统一模型、项目分析缓存 | -| [src/view/output.rs](../../src/view/output.rs) | 提前应用 no-exec/snapshot 策略、共享项目分析、静态详情与相对跳转 | -| [src/view/annot.rs](../../src/view/annot.rs) | 运行标注与节点/帧/版本关联,减少重复输出;缺映射不伪绑定 | -| [src/view/debug_page.rs](../../src/view/debug_page.rs) | 仅回归检查共享组件;不把阅读布局强加给 debug | -| [tests/executable_knowledge.rs](../../tests/executable_knowledge.rs)、view 单测 | 从字符串存在升级到顺序、锚点、状态和执行边界断言 | -| 文档与 public 示例 | 更新旧 View 布局说明、截图和行为描述,区分历史默认与新设计 | - -默认展示不要求作者补特殊 frontmatter;title/description、函数说明、契约和来源已有时直接受益。尚无信息的旧文档保真显示,并在详情中如实缺省。 - -与现有文档的关系:保留 [view-document-annotations](view-document-annotations.md) 的叙述主导和真实结果,修订“长 L-leader 为默认”;保留 [view-frame-selection](view-frame-selection.md) 的源码常显与帧隔离;[view-markup-surface](view-markup-surface.md) 的历史 Classic 例子需按当前默认语法同步,不能在新 UI 继续教授旧取元。外联/WASM 交互沿既有独立路线发展,不作为完成本次阅读改版的前置。 - -## 11. 分阶段交付 - -### V0:先纠正顺序、误导状态和执行边界 - -正文提前;完整知识报告收进明确的辅助入口,module/type 容器默认不铺卡;“Lock digest”改为准确的摘要标签;状态不再共用一个 ok。修复 no-exec 先执行问题,分析错误可见。暂不等待完整节点模型,就能显著改善截图场景。 - -V0 不算最终完成:仅把面板搬到后面/折叠,仍未解决正文与知识的关联。 - -### V1:完成阅读与结构理解的主闭环 - -统一展示模型、标题/目录层级、就地说明、当前知识详情、友好定义跳转与返回。完成函数、计算、来源、空态与基本运行结果的正负例;live/static 共用。 - -### V2:贯通运行、来源和跨文档关系 - -匹配运行实例与版本、调用/循环帧、来源定位/失效、局部依赖关系、SSE 原子更新。上游证据能力尚不完整的地方明确显示未知,不能以 UI 补出“验证通过”。 - -### V3:移动端、离线和规模验收 - -完成键盘/读屏、无 JS、打印、暗色/浅色、100/1000 单元性能、视觉回归与读者测试。发布前同步 public 示例与说明,保留旧锚点兼容。 - -## 12. 验收矩阵 - -### 12.1 必测文档 - -| 样例 | 必须验证 | -|---|---| -| 截图对应 Phase I 页 | 正文先出现;无 full URI/hash 瀑布;print 在所属正文解释;无孤立线条 | -| 纯叙述/少量 Markdown 页 | 阅读无知识空卡、无误导运行徽章 | -| 单个纯函数,无 main | 参数/返回与调用方式清楚,不因无入口标全文失败 | -| 订单定价、多文档 import | 小计/税率/总额归属和依赖可追踪;输入和结果可对应 | -| 带来源的事实与过期/缺失来源 | sourced 不显示已证实;问题在对应知识旁可见 | -| 同名函数、多次调用和循环分支 | 定义唯一;切换帧只改结果和高亮,不隐藏结构 | -| 空 payload、动态调用、未解析引用 | 待实现/动态/未解析准确可辨,不能展示虚构结果 | -| 一行多个链接、嵌套表达式、中英文/长路径 | span 对应、锚点唯一、文本不丢失、不水平溢出 | -| 运行失败、分析失败、快照过期 | 三种情况分开,仍能读到正文与具体诊断 | -| 外联单元、变量大表、长日志 | 单层主体与对应结果,不重复三份输出;局部滚动 | - -### 12.2 自动化判据 - -1. DOM 中文档主体先于全量知识技术详情,标题来自既有元数据;短文没有隐藏正文的默认展开报告。 -2. 每个知识/目录链接都能定位真实节点;一行多节点和同名跨模块不冲突;live/static 路径均有效。 -3. 验证、运行、来源状态按固定真值表渲染;无证据时绝不输出综合已验证。 -4. no-exec 用隔离目录的副作用计数测试证明没有执行;snapshot 不重跑;展开详情也不执行。 -5. 帧选择和 SSE 更新保留正文结构、选中身份与焦点,拒绝过期结果包。 -6. 明暗主题/320、390、1024、1440 宽度/200% 缩放下无遮挡、截断关键条件和整页横向溢出;孤立 leader 数为零。 -7. 无 JS、file 静态打开、打印预览都保留正文、定义/来源导航和必要证据说明。 -8. 输出中的作者内容、label、URI/属性与嵌入 JSON 按原上下文转义;资料中的 HTML/脚本不能因为新详情组件被直接执行。 - -字符串断言只能覆盖结构,不能替代浏览器布局验收;需截图基线和真实键盘交互测试。可复用现有测试基础,避免测试只镜像组件实现。 - -### 12.3 读者任务测试 - -建议用至少 5 位未参与实现的读者,分别完成三个任务,并与当前页面对照: - -- 在 30 秒内说清文档目的并找到主要规则/函数。 -- 在 60 秒内找到某个结果的输入、定义和原始来源。 -- 正确区分“来源已关联但未核验”“本次运行成功”“未运行/历史结果”,不得误认为都已验证。 - -目标为至少 4/5 完成前两项,第三项无误导性判断;小样本仅作为可用性门槛,不声称统计显著。记录失败位置并修正信息架构,不能只问“是否好看”。 - -## 13. 完成定义与本次交付边界 - -完成的 view 应让读者先读懂文档,再自然看到其中的知识与执行结构;需要深入时能沿着一个具体片段追到实现、输入、结果和证据。全量技术字段仍可查,但不要求读者先理解编译器才能读文档。 - -本次只提交设计文档与索引,不修改渲染实现。实证包括用户截图、当前模板/渲染路径、静态 HTML 顺序检查和临时 no-exec 反例;布局尺寸、交互、性能和读者任务结果均为待实施的验收目标。 diff --git a/doc/design/view-markup-surface.md b/doc/design/view-markup-surface.md deleted file mode 100755 index 66eac91..0000000 --- a/doc/design/view-markup-surface.md +++ /dev/null @@ -1,40 +0,0 @@ -# View:Markup 表面保真 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-09-14 | -| 相关 | [view.md](view.md) · [bracket-call-modifiers.md](bracket-call-modifiers.md) · [collection-access-link.md](collection-access-link.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) | - ---- - -## 1. 目标 - -`marqdo view` 的 Structure / 表达式展示应**贴近作者写出的 Markup**,而不是内部 AST 的旧拼法。读者从 view 抄回源文件时,应仍是合法、推荐的表面。 - -## 2. 表面对照 - -| AST / 概念 | View 优先显示 | 备注 | -|------------|---------------|------| -| `Expr::Occluded` | 正文只读动作说明,实际实现进入侧注 | 每个片段独立关联,不把整句改成一次赋值 | -| 空遮蔽 `()` | 待补充实际逻辑 | 当前空遮蔽返回 None,不伪装成已接通工具 | -| `Expr::Index` / `InterpPart::Index` | 保留经典或脚注取元的兼容说明 | 当前作者程序优先用 access 读取集合;默认链接形是遮蔽 | -| `CallExpr` + `bracket_marked` / `pre_modifiers` | `修饰 [callee] 实参…` 或 `[callee] 实参…` | 仅经典 `>` 解析时仍显示 `> callee …` | -| 赋值 / 返回 | 保留原叙述句子,在真实执行片段上标明语句或返回 | 普通链接与字面量不冒充执行遮蔽 | -| foreach | `- [动作](遍历 集合 为 项)` | 正文显示动作,控制逻辑见侧注;迭代选择器只切换已有运行记录 | - -## 3. 非目标 - -- 不把 view 做成第二语法;解析真相仍在 mapping / call-arguments。 -- 不删除对脚注取元、旧 `>` 调用的兼容显示需求时,可用次要提示,但默认推荐面优先。 - -当前阅读器的实现与验收见 [view-readable-actions.md](view-readable-actions.md)。 -可执行知识先展示输入、返回、调用边界、依赖和各项依据;摘要和机器身份按需展开。 -源码说明与运行标注分开,展开侧注或知识卡片不会执行代码。 - -## 4. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-14 | 初稿;Index 链接形 + 括号调用修饰表面 | -| 2026-09-14 | `bracket_marked`:无修饰的 `[callee]` 也保真显示 | diff --git a/doc/design/view-prose-annot-gaps.md b/doc/design/view-prose-annot-gaps.md deleted file mode 100755 index 7d33d1f..0000000 --- a/doc/design/view-prose-annot-gaps.md +++ /dev/null @@ -1,145 +0,0 @@ -# View:叙述面标注缺口(prose annot gaps) - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-10-15 | -| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [view-frame-selection.md](view-frame-selection.md) · [view-execution-trace.md](view-execution-trace.md) | - -> **定位**:对既有文档面设计的**缺口专章**——写清用户可见的四类问题、根因(文件:行)与验收口径。不改写 ADR;不发明作者侧标注 DSL。 - ---- - -## 1. 为何「改了却几乎没变化」 - -| 原因 | 说明 | -|------|------| -| 错二进制 | PATH 上的 `marqdo` 可能仍是旧版(如 1.3.0);改动在源码 / `./target/debug/marqdo`。验收必须用 `cargo build && ./target/debug/marqdo view …` | -| Chip 被溢出藏掉 | 同 band 堆多帧 return/print/who;`MAX_VISIBLE_ANNOTS=4` 把当前帧的 `who` 打成 `annot-chip-overflow`(`display:none`);帧切换不重算溢出 | -| L-leader 几何错位 | `initAnnotLeaders` 里 `y0=0` 只在 `.annot-band` 顶画短折,**连不到**上方 underline;窄屏或 chip>4 时整段关掉 leaders | -| 旧静态快照 | gh-pages / 旧 `view output` 不会自动刷新 | - ---- - -## 2. 目标视觉语法(既有,不新造) - -锚定 [view-document-annotations.md](view-document-annotations.md) §3: - -``` -文本段…… `变量` …… **语句** …… *返回* - ━━━━━ - │ - └──→ 结果标注 chip -``` - -- underline:`mark.mq-anchor.mq-{decl|code|return}` -- band:段落下方 `.annot-band` → leaders + chips -- L-leader:CSS `border-left` + `border-bottom`(禁止 SVG) -- 公式/代码:[view-static-interactive.md](view-static-interactive.md) G3 **一层主视觉**;卡下不叠 Bind dump -- 帧:[view-frame-selection.md](view-frame-selection.md) **源码常显、只滤 chip**;默认末帧 - ---- - -## 3. 管线 - -```mermaid -flowchart LR - CLI["marqdo view / view output"] --> build["build_file_view"] - build --> cap["run_file_capture"] - cap --> annot["build_view_annots"] - annot --> doc["document::render_module_document"] - doc --> page["html.rs page_file"] - page --> js["initAnnotLeaders + initCallPickers"] -``` - -| 步骤 | 位置 | -|------|------| -| CLI / 导出 | `src/main.rs` · `src/view/mod.rs` · `src/view/output.rs` | -| Capture + Call 事件 | `src/interp.rs` | -| Annot 组装 | `src/view/annot.rs` `build_view_annots` | -| 文档面 HTML | `src/view/document.rs` | -| 卡片 chrome | `src/view/render.rs` `render_*_assign_card` | -| CSS / leader JS | `src/view/html.rs` | - ---- - -## 4. 四条用户问题 → 根因 → 验收 - -复现源:`public/00-welcome.mq.md` · `public/00-欢迎.mq.md` -对照金样:`tests/view/document-annot-demo.mq.md` · `tests/markup-v03/inc-prose.mq.md` - -### P1 — 叙述与代码同段时信息不显示 - -| | | -|---|---| -| 现象 | underline 在,chip / 连线弱或无 | -| 根因 | `html.rs` `initAnnotLeaders`:`y0=0` 相对 band;`document.rs` `MAX_VISIBLE_ANNOTS` 把当前帧 chip 溢出;PATH 旧 CLI | -| 目标 | 同 `inc-prose`:underline + L-leader(从锚点底到 chip)+ 可见 chip | -| 验收 | `./target/debug/marqdo view public/00-welcome.mq.md`:主文 `**greet…**` 与 `## greet` 体内均有可见 chip 与接到 underline 的 leader(宽屏) | - -### P2 — 函数内变量不显示 - -| | | -|---|---| -| 现象 | `` `who` `` 有浅蓝 underline,无值 chip | -| 根因 | bind chip 存在但带 `annot-chip-overflow`;`applyCallFrame` 只 `hidden` 非选中帧,不解除当前帧 overflow | -| 目标 | 选中调用帧时常显 `who` · `print` · `return` 各一枚 | -| 验收 | 切换「调用」下拉,三枚 chip 随帧变且默认可见(无需点 +N) | - -### P3 — ` ```text ` 渲染不一致 - -| | | -|---|---| -| 现象 | 变成内联 `text marqdo ext add…`,无卡片 | -| 根因 | Comment 围栏若进 `flush_para` → `join(" ")` → pulldown 当 inline code;应走 `render_narrative_fence` | -| 目标 | 与 bound python 同 `.code-card` chrome(badge + `pre.code-body`),**无** Run/foot | -| 验收 | welcome install 段:`data-lang="text"` + 两行 `marqdo ext add`;无 `<code>text marqdo` | - -### P4 — 函数引用 / 代码卡未渲染 - -| | | -|---|---| -| 现象 | `**greet who=…**` 无结果;或 `hi` python 只见头/Run、不见源码 | -| 根因 | 同行多 Call 未与 BoldCode zip;或 Run 挤在 head;静态假 Run;错看 Debug 路径 | -| 目标 | 主文两 greet 各有 call chip(stdout 摘要);`hi` = `render_code_assign_card` head→body→foot;静态藏 Run | -| 验收 | 两枚 greet mark 均有非空 `data-annot-id`;`code-body` 含 `hello-from-python`;`MARQDO_VIEW_LIVE=false` 无 Run 按钮 | - -### call_id 语义(写死) - -| 位置 | call_id | -|------|---------| -| 主文 `**greet…**` 的 call chip | 入口帧(`# main` 的 call);结果为 stdout/返回摘要 | -| `## greet` 体内 print / who / return | callee 的 CallFrame id;跟函数标题旁 picker | - ---- - -## 5. 修复约定(实现红线) - -1. **帧感知密度**:band 内按选中 `call_id` 计可见 chip;默认末帧;同帧最多 4 枚常显;溢出只藏非当前帧或多余 kind。切换后客户端重算 overflow + `layoutAll()`。 -2. **Leader 容器**:提升到 `.doc-block`(prose + band);`y0` = 锚点底相对 block;按锚点 x 排序再画线。 -3. **卡片**:只复用 Browse `render_*_assign_card` / `render_narrative_fence` + `html.rs` `.code-*` / `.formula-card`;本波不改 Debug AST 路径(除非回归红)。 -4. **静态 Run**:`MARQDO_VIEW_LIVE=false` 时隐藏 Run,不留禁用假按钮(对齐 view-static-interactive D5)。 -5. **非目标**:不做 debug 断点;不发明作者标注 DSL;不用 SVG leader;不单独发版/推 gh-pages(除非另嘱)。 - ---- - -## 6. 验收命令 - -```bash -cargo build -q -./target/debug/marqdo version # 须为当前工作树版本 -./target/debug/marqdo view public/00-welcome.mq.md --no-open -./target/debug/marqdo view tests/view/document-annot-demo.mq.md --no-open -cargo test -q --lib view:: -``` - ---- - -## 7. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-10-15 | 初稿:四问题、错二进制/溢出/leader 根因、帧感知密度与 leader 几何约定 | -| 2026-10-15 | L-leader 拥挤/消失:同跨度多帧 chip **共用 annot id**;可见 chip 按锚点 x 重排;leader 挂 doc-block | -| 2026-10-15 | L-leader 黑线碎段:JS `border*: "1.5px solid"` 无色覆盖 class → 改为 kind 色写入 shorthand;chip SSR/DOM 按锚点 L→R | -| 2026-10-15 | L-leader 改为 SVG:描述底边中点 → 轨道 → 短竖线 → 值 chip 顶边中点;chip 间距加宽 | diff --git a/doc/design/view-readable-actions.md b/doc/design/view-readable-actions.md deleted file mode 100755 index 751e414..0000000 --- a/doc/design/view-readable-actions.md +++ /dev/null @@ -1,47 +0,0 @@ -# View:动作留在正文,逻辑留在侧注 - -本轮针对阅读界面,不改变语言求值和工具权限。阅读示例为 -[view-reading.mq.md](../../examples/view-reading.mq.md)。 - -遮蔽按真实 AST 识别,随后按源片段保留句子:方括号的动作说明留在正文,圆括号中的 -实现进入独立侧注。同一句话可以包含多个调用和返回,不再把整行当成一次赋值。 -文字字面量中的链接、普通 Markdown 导航与 classic 取元不冒充执行遮蔽。 -空圆括号明确显示“待补充实际逻辑”,并说明当前空遮蔽返回 None。 - -宽屏实现侧注与运行标注共用现有的左右避碰及引出线布局,彼此有明确名称区分。 -实现侧注标记“源码说明 · 不是运行结果”,不带调用帧或迭代帧身份。 -密集区域、窄屏和无脚本页面使用可原生展开的 details;动作按钮可按需查看完整逻辑。 -悬停与键盘聚焦关联实际源片段,不触发运行。 - -“怎样读这份可执行文档”沿用核心构造注册表,说明参数、赋值、返回、调用、条件、 -循环、数据表、代码块、公式、写回与兼容标记。公式和外语代码仍使用既有卡片, -不新增语法或作者必填的展示配置。 - -可执行知识按真实源单元分组。默认先读输入、返回、调用边界、依赖和验证依据, -身份、摘要与原始状态收进技术详情。契约说明来自已解析的参数和返回表;缺失时如实说明。 -语法检查、契约检查、测试、来源和领域审阅分别展示,静态分析不代表实际执行或内容正确。 -源码结构步骤与实际运行时序分开;内存面板先展示最终绑定与调用记录,再按需展开原始报告。 - -函数的说明链接和知识卡片使用当前文档源行定位,避免同名方法共用一个 DOM 身份。 -单文件阅读只分析它和实际导入的依赖,避免无关同目录模块重名导致知识区整体失败。 -目录阅读保留项目分析。来源身份及版本匹配沿用现有编译器和页面 token,不另建求值器。 - -验收入口: - -```sh -cargo test --offline --lib view:: -cargo test --offline --test view_readability -cargo test --offline --test gold view_ -cargo test --offline --test executable_knowledge -marqdo view output examples/view-reading.mq.md --no-exec --out /tmp/marqdo-reading -``` - -浏览器验收脚本是 [readability.browser.cjs](../../tests/view/readability.browser.cjs), -接收真实页面 URL,支持 MARQDO_PLAYWRIGHT_MODULE、MARQDO_CHROMIUM 和 MARQDO_SCREENSHOT_DIR。 -覆盖七种宽度、侧注边界与碰撞、多动作句子、空逻辑、知识卡片、正文定位和无脚本回退。 -原有 [reader.browser.cjs](../../tests/view/reader.browser.cjs)继续覆盖曲线、帧选择及实时/静态交互。 - -本轮实际验收(2026-11-08):67 项 view 相关单元测试、2 项新增只读导出测试通过; -全量回归 984 通过、0 失败、2 个原有忽略项。真实 Chromium 验证静态快照、 -只读导出和实时页面,覆盖七种宽度、无脚本阅读、曲线与帧切换、源码定位及实时重新运行。 -GOFLAGS 仅对完整回归命令关闭工作区所有权引起的 Go VCS 盖章失败,不改全局配置。 diff --git a/doc/design/view-reader-botanical.md b/doc/design/view-reader-botanical.md deleted file mode 100755 index de55db1..0000000 --- a/doc/design/view-reader-botanical.md +++ /dev/null @@ -1,64 +0,0 @@ -# View botanical reader - -Implemented 2026-11-07 for the shared `marqdo view` and `marqdo view output` shell. - -The default is warm paper, serif document text, olive runtime notes, gold accents, -and generated transparent blossom/feather ornaments. The M/book logo is embedded -SVG. Navigation and the floating toolbar are code-native SVG icons and CSS. - -`src/view/reader.css` is the final theme layer after notebook component styles; -`src/view/reader.js` owns reader navigation, dialogs and annotation geometry. -Notebook APIs and controls remain available through More → advanced tools. -Welcome files get a larger introduction; ordinary files retain compact titles. - -## Runtime notes - -Annotations keep their existing owner band, stable IDs, source anchor, call frame -and loop iteration data. Chips serialize source line and byte spans so another -call/iteration frame can find the same source mark without guessing by kind. -On viewports wider than 1000px with 180px available on each side, notes use both -page margins, varying horizontal reach and vertical offset with collision -avoidance. Dense bands that would drift more than 170px retain inline notes. -Compact screens, printing, and expanded overflow bands use ordinary document -flow. A shared SVG overlay draws continuously curved connections from the actual -mark's source-facing lower edge to the annotation title. The default is a full -S-curve with restrained gold/olive gradient; candidate sweeps are checked against -visible source text and already drawn connections. Tight prose uses two joined -curves below the text baseline and through the free margin, with no straight rail. -Notes sit closer to the document with varying horizontal/vertical offsets, rather -than stretching every connector across the entire page. Wrapped source marks use -their actual line fragments. Hover/focus highlights the exact source and connector. -Unresolved source anchors retain inline results instead of inventing a connection. -Clicking a note shows its full captured detail. No explanatory prose or runtime -values are invented. - -Layout updates after window/font/structure resize, frame selection and live DOM -replacement. Static HTML includes the same code and embedded assets. All KaTeX -scripts, CSS and fonts are bundled for offline math. Optional syntax highlighting -retains the previous CDN progressive enhancement; code remains readable offline. - -`api/session/run_document` now returns prose HTML, bindings and trace JSON from -its own capture. The reader applies that capture without rerunning the program. -Page tokens prevent a changed source from receiving mismatched annotations. - -## Navigation - -Document returns to prose. Functions/Variables move the real existing panels into -a modal and restore them on close, preserving their existing event handlers. -Memory shows the captured execution report, labeled as a snapshot on exports. -Run navigates to the output section. Search finds document, function and file text. -The floating toolbar labels its icons 刷新 / 设置 / 运行 / 清理 / 更多. -The bottom play button invokes actual live execution; static pages explain how to -start a live view. Static clear hides captured output locally; reload restores it. -Settings control light/dark theme, text size and annotation visibility. More keeps -source, advanced execution controls, file navigation and print within reach. - -## Validation - -Run `cargo test --offline --lib view::` and `cargo test --offline --test gold view_`. -The browser regression is `tests/view/reader.browser.cjs <URL>`; it accepts -`MARQDO_PLAYWRIGHT_MODULE`, `MARQDO_CHROMIUM`, and optional -`MARQDO_SCREENSHOT_DIR`. It blocks HTTPS resources to exercise offline reading, -checks seven viewport widths, note bounds/collisions, source/label curve endpoints, visible curvature and non-crossing paths, -shared-source frame binding, stable redraw, real panel restoration, -search, frame selection, note inspection and live/static run behavior. diff --git a/doc/design/view-static-interactive.md b/doc/design/view-static-interactive.md deleted file mode 100755 index a23dc21..0000000 --- a/doc/design/view-static-interactive.md +++ /dev/null @@ -1,239 +0,0 @@ -# View:静态页交互与公式/代码卡视觉 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-10-15 | -| 相关 | [view.md](view.md) · [user-site.md](user-site.md) · [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [ADR 0002 browser WASM](../adr/0002-browser-marqdo-wasm.md) | - -**已确认(2026-10-15)** - -| 决策 | 选择 | -|------|------| -| 引擎 | **B**(快照 + S1 帧切换 + 可选懒加载 WASM S2) | -| 体验原则 | 静态页与 live view **尽量同构**;控件形态对齐;无服务端时用 WASM/JS 补齐 | -| 视觉原则 | **一层主视觉**;一眼能懂;公式/代码不与 Bind chip / 源残留叠床架屋 | -| 演示参数条 | **要**(历史实参 select + 可编辑;S1 切帧 / S2 重跑) | -| code-card Run | 有 WASM 时可用;否则隐藏(不对齐「假按钮」) | -| 公式 Bind chip | **卡内不显示**;Variables 可留终值 | - ---- - -## 1. 动机(对照 `public/00-欢迎.mq.md` / gh-pages) - -静态导出(`marqdo view output` → `gh-pages`)与 live `marqdo view` 已共用**文档面 Structure** 渲染路径,但用户站实测仍有三类落差: - -1. **交互控件缺失 / 偏弱** - - 函数「问候」仅有参数 chip「谁」,没有可切换的调用帧下拉(即便源里 `> 问候` 写了两次)。 - - 参数行 `+ 谁` 在文档面呈声明高亮,读者无法在静态页改「谁」并看到新输出。 - - 外联 `code-card` 的 Run 在静态模式被禁用(`Run is available in live marqdo view`)。 - - 静态 stdin 仅在有 preset 时显示只读提示,**不能**再跑。 - -2. **无服务端时仍可交互的预期** - 用户站是纯静态托管:没有 `/api/run`。合理路径是 **页内 JS** 和/或 **嵌入 Marqdo WASM**,在浏览器里重算 Structure 标注、Execution 区,甚至模拟 `input` / 外联(沙箱约束另定)。 - -3. **公式 / 代码块视觉凌乱** - 同一赋值同时出现多层表象,信息重复、线框错位: - - | 层 | 公式 `f = $$…$$` | 外联 `hi = ```python…``` | - |----|------------------|---------------------------| - | A 卡片 | `formula` badge + KaTeX | `code` badge + 高亮源码 + cmd/Run | - | B 标注 chip | `f` → `x^2 - 2` | `hi` → 整段 fence 摘要 | - | C 源残留 | 卡片外/旁再露 `$$` 或 ASCII | 卡片下再露 `python print…` 明文 | - - 再叠加 CSS L-leader 与卡内边框,首屏显得碎、重复、「坏掉的线」。 - -**本文件只定问题与方案;确认前不改代码。** - ---- - -## 2. 现状解剖 - -### 2.1 静态 vs live(同一 `page_file`) - -| 能力 | Live | Static(`LinkMode::Static`) | -|------|------|------------------------------| -| 文档面 Structure + annot | ✅(跑后) | ✅(导出时跑后写入) | -| call / loop picker JS | ✅(读 `#mq-view-trace`) | ✅(同源 JS;若轨迹未写入则无控件) | -| `/api/run` · Stream | ✅ | ❌ | -| stdin 表单 | ✅ 可再跑 | 只读 hint(或无) | -| code-card Run | ✅ `POST` 外联 | ❌ 禁用按钮 | -| WASM 重算 | ❌(未接) | ❌(未接) | - -结论:**不是「静态另做一套皮肤」**,而是「导出瞬间的快照 + 部分 JS 帧切换」;**没有**浏览器内重执行闭环。 - -### 2.2 欢迎页结构(问题复现源) - -```text -> 问候 谁=marqdo -> 问候 谁=marqdo user -## 问候 - + `谁` -> 打印 内容=欢迎,`谁`! -`f` = $$ x^2 - 2 $$ -`hi` = ```python … ``` -``` - -- 期望:`## 问候` 旁 **调用** 下拉(`1: 谁=marqdo` / `2: 谁=marqdo user`),切换时打印行的绑定/输出随帧变。 -- 现状风险:若导出时 CallFrame < 2、或 picker 未挂上、或读者期望的是「编辑谁」而非「选历史调用」,都会表现为「没有下拉框」。 -- 公式/代码:`SpecialAssign` → formula/code **card**,同时又对同名绑定建 **Bind annot**,文档面还可能保留块源视觉 → 三重展示。 - -### 2.3 已有红线(方案不得破坏) - -- 代码即文档:`.mq.md` 源可读;不发明第二套嵌套 DSL(见 web-artifact / marqdo-dev)。 -- Browse ≠ Debug:静态站不做断点。 -- `public/**/*.html` 不入库;gh-pages 由 CI/`view output` 生成([user-site.md](user-site.md))。 -- 外链字体禁令仍在 [view.md](view.md);WASM/重型资源须 **可选加载**,默认站可降级为纯快照。 - ---- - -## 3. 目标(验收口径) - -### G1 — 帧与参数交互(静态可读、可拨) - -1. 同函数 ≥2 次调用时,静态页 **必有**「调用」下拉;默认末次;切换只改 chip/臂/相关输出,**源码常显**(同 [view-frame-selection.md](view-frame-selection.md))。 -2. 导出保证写入完整 `#mq-view-trace`(含 `calls` / `events` / 可选 `loops`)。 -3. (增强)演示向参数可提供 **受控输入**:默认值来自末次调用或 FM;改参后可触发页内重算(见 §5 引擎选项)。 - -### G2 — 无服务端可重算(可选引擎) - -| 档位 | 能力 | 依赖 | -|------|------|------| -| **S0 快照**(现状加强) | 导出时跑完;帧 picker;只读 Execution | 无 WASM | -| **S1 页内重放轨迹** | 不重跑程序,只切换已序列化帧/标注 | JSON only | -| **S2 WASM 重跑** | `marqdo_wasm` + bridge:改 stdin/实参后重跑,刷新 Structure/Execution | WASM 包(可 CDN/`public/wasm/`) | -| **S3 外联沙箱** | code-card Run:浏览器内 pyodide **或** 明确标「仅 live」 | 可选;默认可关 | - -默认用户站:**S0 + S1 必达**;**S2 为推荐主路径**(与「用 wasm 模拟输出」对齐);S3 单独开关。 - -### G3 — 公式 / 代码视觉单层真相 - -对「特殊赋值」块约定 **一层主视觉 + 至多一层结果**: - -| 块 | 主视觉 | 允许的结果层 | 禁止 | -|----|--------|--------------|------| -| 公式 | KaTeX(formula-card 精简) | 无 Bind chip,或仅在 Variables | 再渲一份 `$$` 明文;annot 与卡重复同一 TeX | -| 外联代码 | 高亮源码(code-card) | 运行输出区 `code-out`;静态可藏 Run 或接 S2/S3 | annot 再贴整段 fence;卡下重复裸源 | -| 普通赋值 | 标记面语句 | Bind chip + L-leader | — | - -Leader:仅连接「主视觉锚点 → 唯一结果 chip」;卡内不用第二套 L 线。 - ---- - -## 4. 问题清单(成文) - -| ID | 问题 | 严重度 | 根因假设 | -|----|------|--------|----------| -| P1 | 静态页看不到调用/循环下拉 | 高 | 轨迹未导出完整 / picker 条件(≥2)未满足 / 读者要的是编辑参而非选帧 | -| P2 | 不能改参/stdin 再看输出 | 高 | Static 禁用 `/api/run`;无 WASM 闭环 | -| P3 | code-card Run 静态无效 | 中 | `initForeignCards` 显式禁用 | -| P4 | 公式卡 + chip + `$$` 三重 | 高 | card 与 Bind annot 叠加;块源未完全被 SpecialAssign 吞掉 | -| P5 | 代码卡 + chip + 明文三重 | 高 | 同 P4 | -| P6 | 卡内/旁碎线、错位 | 中 | leader 锚到错误节点;卡 CSS 与 annot-band 叠层 | -| P7 | 静态 stdin 体验差 | 中 | 仅有只读 hint | - ---- - -## 5. 解决方案(详案,待选) - -### 5.1 引擎策略(三选一,推荐 **B**) - -| 方案 | 做法 | 优点 | 代价 | -|------|------|------|------| -| **A. 纯快照 + S1** | 加强导出轨迹与 picker;不引入 WASM | 体积小、离线稳 | 不能改参真重算 | -| **B. 快照默认 + 可选 WASM(S0/S1/S2)** | `view output` 仍嵌入跑后 HTML;页脚/侧栏「在浏览器中重跑」懒加载 WASM;改参后 patch Structure/Execution | 对齐用户预期;无 WASM 时仍可读 | 打包/加载体积;宿主能力子集 | -| **C. 静态页全面 WASM 首屏** | 打开即 WASM 跑 | 交互最强 | 冷启动慢;gh-pages 带宽;与「文档先可读」冲突 | - -**推荐 B**:文档先可读(S0),帧切换不依赖 WASM(S1),需要改参/演示时再拉 WASM(S2)。 - -### 5.2 交互控件(与文档面一致) - -1. **调用 / 循环 picker**(已有组件) - - 导出验收:欢迎页「问候」必须出现调用下拉。 - - 单测:对 `00-欢迎.mq.md` / `document-annot-demo` 断言 HTML 含 `call-picker` 且 options≥2。 - -2. **演示参数条(新,窄范围)** - - 仅当函数被标记为「可演示」**或**静态页检测到 ≥1 形参且存在 CallFrame 时,在函数标题旁增加: - `谁 [ text input | select(历史实参) ] [应用]` - - **不**改 `.mq.md` 语法;数据来自 trace 的 `args_brief` / 末次绑定。 - - 「应用」:S1 仅切换已有帧;S2 调 WASM `run` 后替换 `#structure` / Execution。 - -3. **stdin** - - 静态:若源含 `input`,渲染与 live 同形的 textarea +「重跑」(S2)或说明「需 WASM」。 - - 无 input 则不显示。 - -### 5.3 公式 / 代码去重(视觉) - -**规则:SpecialAssign 行只走 card,不再为同名同值挂 Bind chip。** - -```text -公式赋值行 - └─ formula-card(badge + 名 + KaTeX) - └─ ✗ 不再 render_annot_band(Bind f) - └─ ✗ 不再在卡外输出 $$ 源 - -外联赋值行 - └─ code-card(badge + 名 + 高亮体 + 可选 Run) - └─ ✗ 不再 Bind chip 贴 fence 全文 - └─ 运行结果只进 .code-out -``` - -静态 Run 策略(与 §5.1 对齐): - -- S0:隐藏 Run,或保留禁用并 tooltip「打开 live view / 启用 WASM」。 -- S2:Run → WASM 宿主 `foreign`(若 WASM 支持)或提示不支持。 -- S3:可选 Pyodide(默认关)。 - -CSS:formula-card / code-card 与 `.annot-band` 垂直节奏统一;禁止对 KaTeX 节点拉 L-leader。 - -### 5.4 导出管线 - -```text -marqdo view output - → build_file_view(跑 + annot + trace_json) // 已有 - → page_file(Static) - + 嵌入 #mq-view-trace - + (可选)data-wasm-url / 懒加载脚本 - + 公式/代码去重后的 structure_html - → public/ + gh-pages -``` - -`--no-exec`:文档面无标注;可提示「本页为结构-only」;S2 仍可尝试 WASM 首跑(可选,默认关以免惊喜执行)。 - -### 5.5 明确不做(本提案) - -- 静态页断点调试(仍属 `marqdo debug`)。 -- 在 `public/*.mq.md` 发明新的「交互表」DSL(除非另开设计并获批)。 -- 默认全站加载 Pyodide。 -- 提交生成 HTML 进 `main`。 - ---- - -## 6. 分阶段开发计划(确认后执行) - -| 阶段 | 内容 | 交付 | 依赖确认 | -|------|------|------|----------| -| **D0** | 本文定稿;选定引擎 **A/B/C**;是否要「演示参数条」 | 状态 → Active | **本次决策** | -| **D1** | P4/P5/P6:SpecialAssign 与 Bind 互斥;卡 CSS;去掉重复源 | 欢迎页公式/代码干净;单测 | D0 | -| **D2** | P1:导出轨迹验收 + 欢迎页 call-picker 金样;修任何「≥2 调用无下拉」bug | HTML 断言 | D0 | -| **D3** | P2/P7 S1 夯实:静态 stdin UI 形态;无 WASM 时文案清晰 | UX | D0 | -| **D4** | (若选 B)S2:静态页懒加载 WASM;「应用参数 / 重跑」刷新 Structure+Execution | `public/wasm` 或 CDN 策略;体积预算 | D0=B | -| **D5** | P3:code-card 与 S2/S3 策略落地;默认隐藏无效 Run | — | D1+D4 | -| **D6** | `build-public` / pages CI 回归;更新 [user-site.md](user-site.md) · [view.md](view.md) 验收条 | gh-pages 抽检欢迎页 | D1–D5 | - -建议默认路径:**D0 选 B → D1 → D2 → D3 → D4 → D5 → D6**。 - ---- - -## 7. 决策记录 - -见文首「已确认」。开发按 §6:D1 → D2 → D3 → D4 → D5 → D6。 - ---- - -## 8. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-10-15 | 初稿:静态交互缺口、公式/代码凌乱、S0–S3 与阶段 D0–D6 | -| 2026-10-15 | Active:引擎 B;对齐 live;干净视觉;演示参数条;Run 接 WASM 否则隐藏 | diff --git a/doc/design/view.md b/doc/design/view.md deleted file mode 100755 index 3bf8fd4..0000000 --- a/doc/design/view.md +++ /dev/null @@ -1,163 +0,0 @@ -# `marqdo view` — 源结构浏览器与静态文档导出 - -| | | -|---|---| -| 状态 | 已定(v0.0.2 方向) | -| 日期 | 2026-08-04 | -| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) | - ---- - -## 1. 动机 - -`.mq.md` 既是文档也是程序。需要: - -1. **本地浏览**:按 AST 展示结构 + 执行结果; -2. **静态导出**:同一套渲染写成 HTML,作为**用户文档站点**(勿手写第二套站点); -3. **启动快**:样式极简,无外链字体/厚主题,避免 view 冷启动慢。 - ---- - -## 2. 视觉(Apple HIG / Docs 极简) - -对齐 [Apple HIG](https://developer.apple.com/design/human-interface-guidelines) 的 **clarity / deference / white space**,并参考常见 docs 布局(sticky 侧栏 + 居中主栏,见 Nextra / Docusaurus 类站点):**系统灰底、白内容面、浅分隔线、系统字体**。作者站 [id.cflmy.cn](https://id.cflmy.cn) 仍作克制感参考,但不强行纯黑描边。 - -| 规则 | 要求 | -|------|------| -| 色板 | 页底 `#f5f5f7`;内容面 `#ffffff`;正文 `#1d1d1f`;次要字 `#6e6e73`;分隔 `#d2d2d7`;选中侧栏项反白 | -| 布局 | 壳层 `max-width ≈ 1680px`;侧栏 ≈280px;主内容 `max-width ≈ 76rem`;Structure 旁函数大纲;**≤800px 侧栏收起** | -| 默认页 | 打开目录时 **直接展示排序后的第一个 `.mq.md`**(实时 `/` 与静态 `index.html` 同),不要求用户先从欢迎页点选 | -| 字体 | 仅系统栈:`-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif`;等宽 `ui-monospace, SFMono-Regular, Menlo, Consolas, monospace` | -| 外链 | **禁止** Google Fonts / CDN 样式;CSS 全部内联于 HTML | -| 装饰 | 无多层阴影、无渐变、无发光;圆角 ≈12px;结构区为分组列表(底部分隔),非堆叠厚卡片 | -| 诊断路径 | 展示时去掉 Windows `\\?\` 前缀,并优先用相对 view 根的路径 | - -验收:首屏无外网字体请求;宽屏主栏明显宽于早期 `58rem` 方案(现约 `76rem` / 壳 `1680px`)。 - ---- - -## 3. CLI - -### 3.1 实时浏览 - -```bash -marqdo view [PATH] [--port PORT] [--host HOST] [--no-open] -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `PATH` | `.` | `.mq.md` 或目录 | -| `--port` | `7429` | | -| `--host` | `127.0.0.1` | | -| `--no-open` | 关 | 不打开浏览器 | - -### 3.2 静态导出(文档生成) - -```bash -marqdo view output [PATH] -o OUT_DIR [--no-exec] -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `PATH` | `.` | 与 `view` 相同扫描范围 | -| `-o` / `--out` | (必填) | 输出目录(不存在则创建) | -| `--no-exec` | 关 | 不跑程序,执行区显示「skipped」 | - -**产物布局:** - -``` -OUT_DIR/ - index.html # 默认 = 排序后第一个 .mq.md 的完整页(侧栏高亮该项) - pages/ - <相对路径>.html # 每个 .mq.md 一页;路径中的 `/` 保留为子目录 - # 例:structure/hello.mq.md → pages/structure/hello.mq.md.html -``` - -- 页内链接一律**相对路径**,可用任意静态服务器或 `file://`(同目录结构下)打开。 -- 用户文档推荐流程:`marqdo view output public -o public`,将生成物发布到 `gh-pages`(见 [user-site.md](user-site.md))。 -- **执行权限**:与 `marqdo run` 一致(导入即用);view/导出仅对 `exit`/`sleep` 做软化,避免拖垮进程。详见 [stdlib-modules.md](stdlib-modules.md) §6。 -- 金样例浏览仍可用:`marqdo view output tests -o /tmp/mq-tests`(含 errors,勿当对外用户站)。 -- 渲染逻辑与实时 `view` **共用**同一路径:`build_file_view` → 文档面 Structure(`document.rs` + annots)→ `page_file`(同一 CSS/JS,含 call/loop picker、`#mq-view-trace`)。禁止第二套皮肤。`--no-exec` 时仍出文档面,但无运行标注。 - -示例: - -```bash -marqdo view output public -o public -marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc -``` - ---- - -## 4. 信息架构 - -侧栏文件索引 + 主区:**文档面 Structure** · 执行 · 源码。Structure(Browse)为叙述保真文档面:标记面(变量/语句/返回无源码定界符)、表/列表/分支结构保真,跑后结果经 **CSS L-leader** 引出——见 [view-document-annotations.md](view-document-annotations.md) · [view-execution-trace.md](view-execution-trace.md)。**不是** AST 卡片栈(那是 debug)。 - -结构旁**右侧栏**(现有 outline 槽)为: - -| 区块 | 内容 | -|------|------| -| **Functions** | 原函数大纲 + 搜索;可折叠(默认展开) | -| **Variables** | 跑完后的入口(`# main`)顶层绑定只读快照;List/Map/`@` 行向渲成 HTML 表;可折叠(默认展开) | - -view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板;终态亦可刷新 Structure 内标注。 - -表达式为表面语法。**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。 - ---- - -## 5. HTTP(实时模式) - -| 方法 | 路径 | 含义 | -|------|------|------| -| `GET` | `/` | 默认打开第一个 `.mq.md`(无文件时为空提示) | -| `GET` | `/file?path=…` | 单文件页 | -| `GET` | `/api/tree` | JSON 树(可选) | -| `GET` | `/api/events?path=…` | 可选长订 EventBus(调试);**Stream 面板默认不用**(避免页载常连导致标签页一直转圈) | -| `POST` | `/api/run` | JSON `{path, stdin?}` → **直接返回** `text/event-stream`(本次 run 的事件);结束后关流 | -| `POST` | `/api/foreign-run` | 外联代码块试跑 | - -根目录锁死;拒绝 `..` 逃逸。默认页加载仍可整页执行;Stream 为增强路径。 - -### 5.1 Stream 面板(对齐主流 LLM 呈现) - -**仅当**当前文件 frontmatter 导入了 `ext/ai/llm` / `大模型` 或 `ext/ai/agent` / `智能体`(及等价路径)时,在 live Execution 区显示;普通脚本页不出现该组件。 - -参考常见助手产品(思考折叠 + 正文流式、工具/子步骤独立卡片):**不要**把所有 SSE 事件打成一条混色终端日志。 - -| 区块 | 事件 | 呈现 | -|------|------|------| -| **Thinking** | `reasoning` | 可折叠;流式追加到同一块;默认展开直至本轮 `delta`/`done` 开始,之后可收起 | -| **Answer** | `delta` | **主文**;token 连续拼进同一段落(禁止每 token 换行);主色正文 | -| **Decision** | `decision` | 时间线条目标记(`RUN` / `CONTINUE` / `DONE` / `REUSE` / `NEW` + 可选 summary) | -| **Tool** | `tool_start` / `tool_end` | 父 Plan-and-Move 的 CALL/READ:名称 + kind;`tool_end` 可带截断 `result` | -| **Phase** | `decompose` | 父 pre-run 分解开始(workbook 链);填补「决策后到首 token」空隙 | -| **Child / Workbook** | `await` → `round` | `await`:Child **running…** 占位卡(quiet 子任务等待中);`round`:升级为完成卡(退出码 + 可选 `result`) | -| **Status** | `run_start` / `done` / `error` | 顶栏状态 + 错误行;嵌套 LLM `done`(无 `run_id`)只冲刷 drip,不改顶栏;终态 `done.result` 仅在无 Answer 时作摘要 | - -**传输与流畅度(对齐 ChatGPT 类产品):** - -1. **Run = 一次 `fetch` POST**,用 `ReadableStream` 读响应体里的 SSE 帧;**不要**页载常驻 `EventSource`。 -2. **「Run with input」拦截表单**:`preventDefault` 后走同一 Stream `/api/run`,**禁止整页重载**;带 `?stdin=` 进入时 live 页也不再阻塞跑完,改为自动开 Stream。 -3. **只改 Stream 对话框 DOM**;token **按动画帧合批一次写入**(rAF coalesce,不人为节流;打字感来自网络到达节奏)。 -4. **Stick-to-bottom**:仅在用户仍贴底时跟随;程序化 `scrollTop` 产生的 scroll 事件忽略;上拉后不抢滚动,可点「↓ Latest」。 -5. **Stop**:`AbortController` 中止 fetch。 -6. **子任务并发进度**:`spawn` 立即返回;`wait` 阻塞父循环期间,子进程经 `MARQDO_EVENT_FORWARD` 把 EventBus 帧实时转发到父 SSE;view 把 `source=child` 的 delta 画进 Child 卡。quiet 仍不污染父 TTY。 - -视觉约束(与 §2 一致): - -- 浅色内容面,不用深色「伪终端」底;Thinking 用次要字色 / 浅底。 -- 一屏只突出 Answer;Thinking 与 Child 是附属。 -- plan 多轮:每一轮 Child 一张卡;父侧 Thinking/Answer 按 decision 分轮,不清空历史。 - -事件字段约定(与 [agent-streaming.md](../roadmap/agent-streaming.md) 一致):`round` 可带 `result`(子 `# main` 返回值摘要);`reasoning`/`delta` 的 `text` 为增量。 - ---- - -## 6. 验收 - -1. 实时 `view`:HIG 风极简、无外链字体、结构与执行正确;打开目录即见首个文件;函数大纲可搜索跳转。 -2. `view output public -o public`(或临时目录)生成可点的 `index.html`(首文件)与各 `pages/…`。 -3. 静态页中执行区与 `marqdo run` 一致(未加 `--no-exec` 时);失败诊断路径无 `\\?\`。 -4. 冷启动无明显外网依赖。 -5. 调试用 `marqdo debug`(默认端口 7430),与 view 页面分离。 -6. Stream:`fetch`+SSE 局部更新;Thinking/Answer 分栏;stick-to-bottom;rAF 合批;页载不常连 EventSource。 diff --git a/doc/design/vscode-extension-commit.md b/doc/design/vscode-extension-commit.md deleted file mode 100755 index ad61a36..0000000 --- a/doc/design/vscode-extension-commit.md +++ /dev/null @@ -1,82 +0,0 @@ -# VS Code 扩展 — 分支与提交约定 - -| | | -|---|---| -| 状态 | **强制约定**(勿在 `main` 提交扩展源码) | -| 扩展分支 | **`vscode-extension`** | -| 设计说明 | [vscode-extension.md](vscode-extension.md) | - ---- - -## 1. 原则(必读) - -| 分支 | 是否跟踪 `vscode-extension/` | -|------|-------------------------------| -| **`main`** | **否** — `.gitignore` 含 `/vscode-extension/` | -| **`vscode-extension`** | **是** — 扩展唯一源码所在分支 | - -**禁止**在 `main` 上: - -- 删除 `.gitignore` 里的 `/vscode-extension/` -- `git add vscode-extension/` -- 把扩展目录「合并进 main」以便发版 - -发版时从 **`vscode-extension` 分支检出**扩展目录打 VSIX(见 §4),**不是**把扩展提交进 `main`。 - ---- - -## 2. 日常开发(扩展) - -```bash -git fetch origin -git checkout vscode-extension -cd vscode-extension && npm ci && npm run compile -``` - -改语法、CLI 检测、扩展版本 → **只在 `vscode-extension` 分支提交**: - -```bash -git add vscode-extension/ -git commit -m "vscode-extension: <简要说明>" -git push origin vscode-extension -``` - ---- - -## 3. 日常开发(CLI / 语言) - -在 **`main`** 上改 `src/`、`lib/`、`public/`、`tests/` 等;**不要**顺带提交 `vscode-extension/`。 - -若本地为了调试 checkout 过扩展目录,工作区里可以有 `vscode-extension/` 文件夹,但应被 ignore,且 **`git status` 不应出现**该目录下文件。 - ---- - -## 4. 发版(CLI tag + VSIX) - -1. **`main`**:打 tag(如 `v0.1.2`),CI 构建 `marqdo.exe` 等。 -2. **VSIX**:Release 工作流在 tag 构建时执行: - ```bash - git fetch origin vscode-extension - git checkout origin/vscode-extension -- vscode-extension - cd vscode-extension && npm ci && npm run compile && npx @vscode/vsce package - ``` -3. 本地脚本 `scripts/release-windows.ps1` 同样假定:先 `git checkout origin/vscode-extension -- vscode-extension`(或已在 `vscode-extension` 分支),再打 VSIX。 - -扩展版本号与最低 CLI 要求写在 **`vscode-extension/package.json`** 与分支 README,**不要**在 `main` 的 CHANGELOG 里冒充已合并扩展源码。 - ---- - -## 5. 给 Agent / 协作者 - -执行「更新 VS Code 插件」类任务时: - -1. **切到或基于 `vscode-extension` 分支**改 `vscode-extension/**` -2. **不要**移除 `main` 上 `.gitignore` 的 `/vscode-extension/` -3. **不要**在 `main` 的 release 提交里包含 `vscode-extension/package-lock.json` 等大文件 -4. 仅需在 `main` 更新时:改 `doc/design/vscode-extension.md`、Release 说明、**本文件** — 指针文档即可 - ---- - -## 6. 历史说明 - -v0.1.2 准备阶段曾误将 `vscode-extension/` 并入 `main`(并删除 ignore),导致推送体积过大。已恢复:**扩展仅 `vscode-extension` 分支**;`main` 只保留本约定与设计指针。 diff --git a/doc/design/vscode-extension.md b/doc/design/vscode-extension.md deleted file mode 100755 index 2aa2214..0000000 --- a/doc/design/vscode-extension.md +++ /dev/null @@ -1,31 +0,0 @@ -# VS Code 扩展(分支指针) - -| | | -|---|---| -| 状态 | **已定分支模型** | -| 代码分支 | **`vscode-extension`**(同仓库) | -| 目录 | 工作区 `vscode-extension/`(**仅在该分支跟踪;`main` 在 `.gitignore` 忽略**) | -| 提交约定 | **[vscode-extension-commit.md](vscode-extension-commit.md)**(必读,避免误提交到 `main`) | - ---- - -## 分工(类比 `public` / `gh-pages`) - -| 分支 | 内容 | -|------|------| -| `main` | Marqdo 语言 / CLI / `public/*.mq.md`;**不**存放扩展实现 | -| `vscode-extension` | VS Code 扩展源码、TextMate 语法、VSIX 发版 | -| `gh-pages` | 用户站生成 HTML | - -```bash -git checkout vscode-extension -cd vscode-extension && npm install -``` - -规范入口(在 **`vscode-extension` 分支**上阅读): - -- `vscode-extension/README.md` — 目标与目录 -- `vscode-extension/DEVELOPMENT.md` — 日常流程 -- `vscode-extension/ARCHITECTURE.md` — 与 CLI 边界 - -扩展是 CLI 的薄宿主;语法真相仍是 [markdown-mapping.md](markdown-mapping.md)。 diff --git a/doc/design/warning-fatigue-control.md b/doc/design/warning-fatigue-control.md deleted file mode 100755 index 417c0b1..0000000 --- a/doc/design/warning-fatigue-control.md +++ /dev/null @@ -1,261 +0,0 @@ -# 防警告疲劳:标签校验必须自带的「静默机制」 - -| | | -|---|---| -| 状态 | **Accepted**(机制基线:stale 是变更报告) | -| 日期 | 2026-10-22 | -| 触发 | 用户:`[]()` 每次报 warning 会导致烦躁与忽略,必须先有机制再开工 | -| 前置 | [label-freshness-and-repair.md](label-freshness-and-repair.md) | -| 结论 | stale **不是"扫描报告",而是"变更报告"**;默认零噪音,严格模式 opt-in | - -> **§2 的 M5 已修订**:原文以 `git diff` 作为核心机制是错的——沙箱 `exec=false` 调不了 git、 -> 浏览器 WASM 无进程能力、非 git 用户无从使用,而**最需要它的 agent 修复回路恰在这些环境里**。 -> 现改为 **「前一状态」provider 分层**:`T0 引用一致性 + T1 会话内前后对照` 为核心(零依赖), -> `T2 外部历史源(git 等)` 与 `T3 台账` 为可选适配器。 -> 见 [staleness-providers.md](staleness-providers.md)。本文其余结论(分级、聚合、去重、 -> 可证伪、节流、三道闸、验收指标)不受影响。 - ---- - -## 0. 为什么标签检查比一般 lint 更容易被忽视 - -三个结构性原因: - -| 原因 | 说明 | -|------|------| -| **高频** | 纯度之后标签密度会接近"每个取值/调用一处"(现有索引 506 处 + 循环 44 处是下限) | -| **主观** | 标签是自然语言,机器只能近似判断;报告天然带"可能"二字,说服力弱 | -| **持续** | 代码天天改,断言天天可能过期 → 报告是**常驻背景音**,不是一次性事件 | - -**而当前基线是零噪音**:实测 `lib/` + `ext/ai/` 共 **59 个文件**跑 `marqdo check`, -**warning = 0、error = 0** -(契约检查只在真错时报 error)。也就是说: - -> 标签校验会成为这个项目**第一个持续的警告源**。 -> 第一次引入就必须做对——一旦用户学会忽略,再想收回就晚了。 - ---- - -## 1. 疲劳的真正根因 - -不是"报得多",也不是"偶尔报错",而是: - -> **同一件已知的事,被反复告知。** - -心理学上这叫 habituation:信号无新信息 → 大脑过滤 → 真警报也被过滤。 - -所以设计目标不是"少报",而是三条更硬的: - -1. **没有新信息就不说话**(变化驱动,而非扫描驱动) -2. **说了就必须能做点什么**(可执行、有定位、有建议) -3. **说过的就不再重复**(确认即静默) - ---- - -## 2. 六个候选机制与评估 - -### M1 分级(hint / warning / error) - -按**证据强度**分级,而不是按"我觉得重要": - -| 级别 | 判据 | 人类可见 | 影响退出码 | -|------|------|---------|-----------| -| **error** | 能证明断裂:引用了不存在的实体、空标签 `label.missing` | ✅ | ✅ | -| **warning** | 能证明变化,但无法判断谁错(L2 指纹漂移) | ✅(默认聚合) | ❌ | -| **hint** | 弱信号:标签提到的实体仍在,但不在当前语句 | ❌(仅 JSON / view / labels) | ❌ | - -**关键**:默认级别取 **hint**,只有项目显式升档才进人类可见输出。 -这让"默认安静"成为语言行为,而不是团队纪律。 - -### M2 聚合(一条汇总,细节下沉) - -`check` 的人类输出**最多一行**: - -``` -contract check OK(另有 3 条标签提示,见 marqdo labels status --json) -``` - -细节走 `--json`(机器)、`view`(徽章)、`labels`(逐条复核)。 -理由:`check` 是 CI 工具,人很少逐条读;真正的阅读界面是 `view` 与编辑器。 - -### M3 基线(bootstrap 静默吸收) - -全量扫描第一次跑时**只写台账、不报告**,把存量债务吸收掉。 -适用:从旧语法迁移到纯度之后的第一次。 - -### M4 确认即静默(ack) - -对某个「标签 + `()` 指纹」组合确认后,记录 `confirmed` → 同样的组合不再报。 -这是最直接的对症药:**说过的就不再说**。 - -### M5 结构化 diff(**已修订:降级为可选 provider T2**,见 [staleness-providers.md](staleness-providers.md)) - -> **stale 只在"`()` 变了、`[]` 没变"时报,且只针对本次变更集。** - -三种实现层次: - -| 层次 | 做法 | 状态 | 噪音 | -|------|------|------|------| -| M5a | 工作区 vs `HEAD`:解析两版本文本,比较同一标签的 `()` AST 指纹 | **零状态** | 无变更即零 | -| M5b | 工作区 vs 「标签文本最后一次被修改的提交」(`git blame` 定位) | 零状态 | 更精确,但依赖 blame 语义 | -| M5c | 台账比对(上一份文档的 L2) | 需台账 | 中(首次需 bootstrap) | - -**M5a 的性质非常关键**: - -- **零台账**:git 就是台账,不需要新文件、不会合并冲突 -- **零基线**:不需要 bootstrap,第一次跑就安静(因为没变更) -- **零重复**:提交之后 diff 清空 → 报告自动消失(除非再次改到同一处) -- **天生带 before/after**:报告直接给旧代码与新代码,正好是 LLM 复核需要的输入 -- **格式化免疫**:比较的是 AST 指纹,不是文本 - -**边界**:不在 git 仓库 / 无 git 时,M5 自动降级为「只做 L1 引用一致性」(仍然确定性、零噪音)。 - -### M6 文档内抑制(`[描述](…) # noqa`)—— **否决** - -理由: -1. **污染文档**:`noqa` 是机器垃圾,与"文档即散文"直接冲突 -2. **不可审计**:抑制理由丢失,后来者不知道当初为什么不查 -3. **永久化**:抑制会累积,最终整个文件静音 - -**替代**:抑制放**台账/配置**(可审计、可过期、可统计),不进文档。 - ---- - -## 3. 推荐组合:默认零噪音 + 严格模式 opt-in - -### 3.1 默认(所有项目) - -| 规则 | 效果 | -|------|------| -| stale 只在 M5a(结构化 diff)时报 | 无变更 → 完全静默 | -| 默认级别 hint | 不进 `check` 人类输出;仅 JSON / view | -| `check` 最多一行聚合 | CI 日志干净 | -| 每条提示必须带:定位、`doc_quote`、`code_past`/`code_now`、一句可执行建议 | 可行动 | -| 同一标签在未处理前只报一次(按变更集去重) | 不重复 | -| 非 git 环境降级为 L1 | 仍然安静 | - -### 3.2 严格模式(知识库仓,opt-in) - -在默认之上加: - -| 规则 | 效果 | -|------|------| -| stale 升为 **warning** 或 **error** | 可作 CI gate | -| 启用 M3 基线 + M4 确认台账 | 存量债务可管理 | -| **棘轮(ratchet)**:允许债务存在,但**禁止增加** | 只拦新增,不清旧账 | -| `labels status` 进 CI 报告 | 债务可见 | - -**棘轮**是我认为最值得抄的机制:`baseline.json` 记 `{"stale": 12}`, -`labels check` 只在 **数量增加** 时失败。这样: -- 老债不阻塞任何人 -- 新债立刻被拦 -- 债务数字可下降,团队有正反馈 - ---- - -## 4. 「确认」的三种语义 - -M4 需要一个"确认"动作,三种可选: - -| 语义 | 操作 | 优 | 劣 | -|------|------|----|----| -| **改标签** | 编辑 `[]` 文本 | 留下真实痕迹,最诚实 | 有时标签确实无需改 | -| **改代码** | 恢复 `()` 的行为 | 守住原意图 | 有时代码才是对的 | -| **显式确认** | `marqdo labels confirm <标签>`,台账记新指纹 | 最省事 | 易被当成"消除警告按钮" | - -**设计建议**:三者都提供,但**显式确认要留痕**—— -台账记录 `confirmed_at` 与 `confirmed_by`(人或模型), -`labels status` 能显示"这条被确认过几次"。 -**被反复确认的标签,本身就是坏味道**(说明描述与实现长期脱节),值得在状态里暴露。 - ---- - -## 5. 可证伪原则:写得越具体,越接受检查 - -这条是从根上减少噪音的机制: - -> **只有能被证伪的断言才被检查。** - -- 标签含 `` `实体` `` 反引号 → 可证伪 → 参与 L1 -- 标签是纯口语("按档位折算")→ 不可证伪 → **L1 完全不检查** - -于是**检查成本由作者的书写具体程度决定**: -写具体的作者获得更强的保鲜保证,也接受更多检查; -写笼统的作者不被检查(但也得不到保护)。 - -这不是漏洞,而是诚实的对齐:**机器只能校验它看得懂的断言。** -同时它反向抑制了"为凑数而写废话"——废话没人查,也就没有价值。 - ---- - -## 6. agent 侧节流:只问它自己刚改的 - -智能体是主要编辑者,最容易被警告淹没。规则: - -| 场景 | 行为 | -|------|------| -| 一次 `repair_apply` 改了 `()` | 只对**它改到的**那些标签做 stale 检查,最多 N 条(如 5) | -| 未触碰的标签 | 一条都不报 | -| 同一修复轮内 | 只报一次,不随每次编辑重报 | -| 超过 N 条 | 只报前 N 条 + 汇总("另有 K 条") | - -这样模型每轮的输入里最多几条相关提示,且都带 before/after—— -**它看到的是"你刚改的这处,描述可能不再成立",而不是"全仓库有 200 处过期"**。 - ---- - -## 7. 防"用忽视解决"的三道闸 - -即使有静默机制,用户仍可能整体忽略。三道闸让它**不可能"无声地"忽略**: - -1. **债务可见**:`labels status` 输出「12 条待复核 / 共 412 条标签」。 - 数字不报警,但每次问就给——忽略变成**有意识的选择**而非无意识。 -2. **可 gate**:知识库仓把 stale 设为 error,CI 红。 -3. **可审计的抑制**:抑制只存在于台账,`labels audit` 能列出所有抑制及其年龄。 - 超过 N 天未复核的抑制 → 提示"这条抑制过期了"。 - ---- - -## 8. 与现有设施的对接 - -| 现有 | 复用方式 | -|------|---------| -| `marqdo check` | 增加**一行**聚合;细节不给 | -| `--json` 诊断输出 | hint 走这里,机器可读 | -| MLSP `validate` | 默认不含 hint,可传 `labels: "strict"` 打开 | -| MLSP `repair_targets` / `repair_apply` | ranges = 标签行 ∪ 代码行(已有能力) | -| `marqdo view` | 标签徽章(新鲜 / 待复核);点击跳到标签与代码 | -| `marqdo verify` / `stale` | 复用已有的知识 stale 通道,进健康报告 | -| 新增 `marqdo labels` | `status` / `review` / `confirm` / `audit` 四个子命令 | - ---- - -## 9. 验收指标(可量化,写进文档以免日后走样) - -上线前必须满足: - -| 指标 | 目标 | -|------|------| -| **默认静默率** | 无代码变更时,`check` 输出中标签相关行 = **0** | -| **报告密度** | 单次变更集中标签提示 ≤ **3 条**,或 ≤ 变更涉及标签数的 **20%** | -| **重复率** | 同一标签在未修改前重复提示 = **0** | -| **可行动率** | 每条提示带定位 + before/after + 建议 = **100%** | -| **误报率** | 人工抽检 50 条,误报 ≤ **10%** | -| **默认可见性** | `check` 人类输出最多 **1 行**;逐条只在 JSON / view / labels | -| **退出码** | hint / warning **不影响**退出码 | - ---- - -## 10. 待你决策 - -1. **核心机制选 M5a(结构化 diff,零状态)吗?** - 我强烈建议选它——它把"疲劳"从设计问题降级为几乎不存在,且不需要台账。 -2. **默认级别**:hint(我建议)还是 warning? -3. **严格模式的棘轮**(禁止新增、允许存量)要不要一并做?我建议要,成本很低。 -4. **显式确认要不要留痕**(`confirmed_by` / 次数)?我建议要——反复确认的标签本身就是坏味道。 -5. **`check` 的聚合行**要不要固定出现("标签 0 待复核"也算信息)? - 我建议**不出现**:零噪音优先,`labels status` 才回答这个问题。 - -> 定了这五条,我就可以按 P1(L1 + 诊断 + MLSP 往返)开工—— -> 因为 P1 只做"能证明断裂"的 error 与 hint,且天然走 M5 的变更口径, -> 不会在第一天就制造出 506 条警告。 diff --git a/doc/design/web-asgi-servers-and-marqdo.md b/doc/design/web-asgi-servers-and-marqdo.md deleted file mode 100755 index cd9df93..0000000 --- a/doc/design/web-asgi-servers-and-marqdo.md +++ /dev/null @@ -1,164 +0,0 @@ -# 调研:Marqdo `ext/web` 能否对接 Daphne / 业界应用服务器 - -| | | -|---|---| -| 状态 | **调研笔记** | -| 日期 | 2026-08-29 | -| 范围 | Daphne、Uvicorn、Gunicorn、Hypercorn 等 ASGI/WSGI 服务器;对照 Marqdo `plugins/web`(axum) | -| 相关 | [web-net-capabilities.md](web-net-capabilities.md) · [ext-web.md](ext-web.md) · [ext-web-net.md](ext-web-net.md) | -| 触发 | `app.listen` 已能本地起站;问「能否像业界一样用 Daphne 等服务器」 | - ---- - -## 0. 一句话结论 - -**不能把 Marqdo 站点「塞进」Daphne / Uvicorn / Gunicorn 当 Python ASGI/WSGI 应用跑。** - -Marqdo 的 HTTP 服务**已经是**应用服务器:`plugins/web` 内嵌 **axum + tokio**,由 `` `app`.listen `` / `` `应用`.监听 `` 绑定端口。这在 Rust 生态里的角色,约等于 Python 里的 **Uvicorn/Daphne**,而不是 Django/Flask「应用代码」。 - -业界生产部署要支持的,通常不是「换成 Daphne」,而是: - -1. **反代 + TLS**(Nginx / Caddy / Traefik)→ 已文档锁定; -2. **进程监督**(systemd / Docker / k8s)→ 运维层,与框架无关; -3. (可选)多进程 / 多副本水平扩展 → 需会话外置等,见下文。 - ---- - -## 1. Daphne「等」服务器是什么 - -| 名称 | 协议面 | 典型搭档 | 角色 | -|------|--------|----------|------| -| **Daphne** | ASGI | Django Channels | Python 异步/WebSocket 参考服务器 | -| **Uvicorn** | ASGI | FastAPI、Django ASGI | 高性能 ASGI(常作 Gunicorn worker) | -| **Gunicorn** | 主要为 WSGI | Django/Flask | 进程管理 + worker;**不能**直接跑 ASGI/WebSocket | -| **Hypercorn** | ASGI | 需 HTTP/2/3 时 | ASGI 另一实现 | -| **Granian** | ASGI(Rust 实现) | Python 应用 | 用 Rust 加速 Python ASGI | - -共同点:它们都假设应用暴露 **Python ASGI/WSGI callable**(`application` / `asgi.py`)。服务器负责 accept、协议解析、生命周期;**业务在 Python 进程里**。 - -2026 常见生产组合示例: - -```text -Internet → Nginx/Caddy (TLS) → Uvicorn/Daphne (ASGI) → Django/FastAPI 应用 -``` - ---- - -## 2. Marqdo 今天怎么起服务 - -```text -.mq.md(ext/web 作者面) - → ABI:web_listen / 路由装配 - → plugins/web:组装 axum::Router - → tokio TcpListener + axum::serve ← 这里就是「应用服务器」 -``` - -关键事实(实现): - -- `plugins/web/src/http.rs`:`TcpListener::bind` + `axum::serve`; -- 依赖:`axum` 0.8、`tokio` multi-thread;含 WS、multipart、中间件层; -- HTTPS:设计上 **进程内 TLS 不作为默认**;生产用反代终止 TLS + `cookie_secure`(见 [web-net-capabilities.md](web-net-capabilities.md) W7)。 - -因此: - -| 问法 | 答案 | -|------|------| -| 能否 `daphne marqdo_app:app`? | **否** — 没有 Python ASGI 入口 | -| 能否 `gunicorn -k uvicorn.workers…`? | **否** — 同上 | -| 能否用 Nginx 反代到 `127.0.0.1:18085`? | **是** — 推荐生产路径 | -| Marqdo 有没有「业界级」HTTP 栈? | **有** — axum/hyper 即 Rust 侧业界默认之一 | - ---- - -## 3. 分层对照(避免角色错位) - -| 层级 | Python 典型 | Marqdo 对应 | -|------|-------------|-------------| -| 应用 / 路由 / 模板 / DB | Django / FastAPI | `ext/web` + `plugins/web` 装配 | -| 应用服务器(accept / HTTP / WS) | Daphne / Uvicorn | **内嵌 axum::serve** | -| 反代 / TLS / 静态边缘 | Nginx / Caddy | **外置反代**(文档已写) | -| 进程管理 | systemd / Gunicorn master | systemd / Docker / k8s | - -把 Daphne 接到 Marqdo,相当于要求「用 Python ASGI 服务器去托管 Rust axum 应用」——协议面不匹配,没有现成插槽。 - ---- - -## 4. 若目标是「生产级部署」,已支持什么 / 还差什么 - -### 4.1 已支持(或已锁定) - -| 能力 | 状态 | -|------|------| -| 本地 / 内网 `listen` | ✅ | -| HTTP + WebSocket | ✅(axum) | -| 反代终止 HTTPS | ✅ 文档路径 | -| 访问日志、限速、CORS、安全头等 | ✅ W1–W7 | -| 会话可 SQLite 持久化 | ✅(单机多启需注意) | - -### 4.2 与「Daphne 集群」对等时仍需注意 - -| 主题 | 说明 | -|------|------| -| **多进程副本** | 每进程各自 `listen` 时,内存会话 / 内存 cache / 内存 WS hub **不共享**;多副本需 sticky session,或会话/缓存外置(Redis 等,驱动面已有雏形) | -| **优雅重启 / 零停机** | axum 可接 signal;未做成一等作者 API(运维可用 systemd + 反代) | -| **HTTP/2 末端** | 多由反代提供;进程内 HTTP/1.1 足够常见场景 | -| **与 Python 生态混部** | 可同机 Nginx 分流:`/api/py` → Uvicorn,`/` → Marqdo;**不是**共用一个 Daphne | - -### 4.3 不建议的路线 - -1. **实现完整 ASGI 适配器让 Daphne 加载 Marqdo** - 成本高、收益低:等于在 Python 进程里再调一层 FFI/子进程,丢掉 axum 直驱优势。 -2. **把 axum 拆掉、改写为「纯应用、外挂任意服务器」** - Rust 没有统一 ASGI;外挂只能是自定义协议或「只当 CGI」,与当前架构相反。 - -### 4.4 可选增强(若要对标「可换服务器」的体验) - -| 方向 | 含义 | 优先级建议 | -|------|------|------------| -| **A. 部署文档 + 示例 Compose** | Nginx/Caddy + `marqdo run` + systemd | **高**(满足绝大多数「业界部署」诉求) | -| **B. listen 运维旋钮** | workers 说明、graceful shutdown、Unix socket | 中 | -| **C. 多副本清单** | 会话/WS/cache 外置检查表 | 中 | -| **D. 反向:Marqdo 作边缘、反代到既有 ASGI** | 已可用 HTTP 客户端/路由外置服务 | 按需 | -| **E. ASGI bridge** | 明确 **非目标** | 不做 | - ---- - -## 5. 推荐生产拓扑(等价于「Nginx + Daphne」) - -```text -客户端 - │ HTTPS - ▼ -Nginx / Caddy / Traefik ← TLS、压缩、限流、静态可旁路 - │ HTTP proxy_pass - ▼ -marqdo run index.mq.md ← 内部 axum::serve(角色 ≈ Uvicorn/Daphne) - (host=127.0.0.1 port=18085,cookie_secure=True) -``` - -要点: - -- Marqdo **只绑回环**;对外只暴露反代。 -- WebSocket:反代需 `Upgrade` / `Connection` 正确转发(与反代 Daphne 相同注意点)。 -- 多机:共享 DB(或 Postgres 驱动)、共享会话存储;WS 广播跨机需外置 pub/sub(当前 hub 为进程内)。 - ---- - -## 6. 结论与建议 - -| 问题 | 结论 | -|------|------| -| 能支持 Daphne 吗? | **不能直接托管**;协议是 Python ASGI,Marqdo 是 Rust axum 自托管。 | -| 能支持「业界服务器」吗? | **能**:用 **Nginx/Caddy 等业界反代** 挂在 `listen` 前面;应用服务器层已由 axum 承担。 | -| 缺的是换 Daphne,还是缺部署体验? | 主要是 **部署文档 / Compose / 多副本约定**,不是再嵌一套 ASGI 运行时。 | - -**建议下一刀(若产品化):** 写一份 `examples/` 或 `doc/design` 下的「反代部署」最小样例(Caddyfile / nginx.conf + `cookie_secure`),而不是调研 ASGI bridge。 - ---- - -## 7. 参考 - -- 本仓:[web-net-capabilities.md](web-net-capabilities.md)(HTTPS 反代锁定)· [ext-web.md](ext-web.md) -- Daphne:Django Channels 参考 ASGI 服务器 -- Uvicorn / Gunicorn worker:当代 Python ASGI 生产主流组合 -- axum:Tokio 生态 HTTP 应用框架(Rust 侧与 Uvicorn 同层) diff --git a/doc/design/web-assets-and-images.md b/doc/design/web-assets-and-images.md deleted file mode 100755 index 426d806..0000000 --- a/doc/design/web-assets-and-images.md +++ /dev/null @@ -1,328 +0,0 @@ -# `ext/web` — 站点图标、Head 资源与图片装配 - -| | | -|---|---| -| 状态 | **Accepted · W8 已落地** | -| 日期 | 2026-08-29 | -| 父设计 | [ext-web.md](ext-web.md) · [web-net-capabilities.md](web-net-capabilities.md) | -| 相关 | [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md)(静态仍由嵌入式 `listen` 提供) | -| 硬约束 | `ext/**` 不调 `host_*`;作者面禁止袋胶水;中英库文件分文件 | - ---- - -## 0. 一句话 - -把 **浏览器默认图标(`/favicon.ico`)**、**`<head>` 里的 link/script**、**正文/品牌图片** 都做成与 `样式装配` 同构的能力:**GFM 表即数据,装配即函数**;由 `plugins/web` ABI 渲染/挂路由,`ext/web` 只做 L1 包装。 - ---- - -## 1. 动机与现状缺口 - -### 1.1 已有 - -| 能力 | 说明 | -|------|------| -| `app.static` / `应用.静态` | 目录挂到 `/static`(或自定义 mount) | -| `page.meta` / `页面.元数据` | `title` / `description` / `canonical` / `og:*` → `<head>` | -| `app.upload` + `gallery` | **运行时**用户上传媒体,不是站点品牌资源 | - -### 1.2 缺口(本设计一次补齐) - -| # | 缺口 | 影响 | -|---|------|------| -| G1 | 浏览器默认请求 **`GET /favicon.ico`**,静态挂在 `/static` 时根路径 404 | 标签页无图标 | -| G2 | `page.meta` 未知键一律变成 `<meta name="…">`,**不能**正确写出 `<link rel="icon">` | 作者写 `icon` 无效 | -| G3 | 无 **Head 资源表**(stylesheet / preload / script / manifest / apple-touch-icon) | 只能手写进 `intro` 或改插件 | -| G4 | 无 **图片装配**(表 → `<figure>`/`<img>`),与样式装配不对齐 | logo / 头图 / 插图只能拼 HTML 字符串 | -| G5 | 无 **站点级图标表 → 根路径文件服务 + 默认 head 注入** | 多页站点要在每页重复声明 | - ---- - -## 2. 设计原则 - -1. **配置即数据、装配即函数** — 与 `web_style` / `应用.装配` 同构。 -2. **应用层管「可达性」**(磁盘文件 → HTTP 路径);**页面层管「声明」**(`<head>` / 正文 HTML)。 -3. **站点图标可自动注入所有页面**,页面仍可用 `头装配` / `元数据` 覆盖或追加。 -4. **约定优于配置**:若已 `静态` 且目录内存在 `favicon.ico`(或 `favicon.png` / `favicon.svg`),未显式配置时仍挂 `GET /favicon.ico`(及对应静态 URL 由作者自选)。 -5. **中英分文件**:`web.mq.md` ↔ `网页.mq.md`,禁止混排。 - ---- - -## 3. 作者面 API(一次交付全集) - -### 3.1 模块级装配(返回字符串,可与主题拼装) - -| EN | ZH | FFI | 输入 | 输出 | -|----|----|-----|------|------| -| `make_style`(已有) | `样式装配` | `web_style` | 样式表 | CSS 文本 | -| **`make_images`** | **`图片装配`** | **`web_images`** | 图片表 | HTML 片段 | -| **`make_head`** | **`头资源装配`** | **`web_head`** | Head 表 | 供调试/预览的 HTML 片段(可选;页面方法主路径不强制调用) | - -### 3.2 `# page` / `# 页面` - -| EN | ZH | FFI | 作用 | -|----|----|-----|------| -| `meta`(增强) | `元数据` | `web_page_meta` | 认 `icon` / `favicon` / `apple-touch-icon` → `<link>`,不再误写成 `<meta name>` | -| **`head`** | **`头装配`** | **`web_page_head`** | 挂 Head 资源表到 `page.head`,渲染时写入 `<head>` | -| **`images`** | **`图片装配`**(方法) | **`web_page_images`** | 图片表 → HTML,写入 `page.images_html`,渲染进主区 | - -### 3.3 `# app` / `# 应用` - -| EN | ZH | FFI | 作用 | -|----|----|-----|------| -| **`icons`** | **`图标`** | **`web_app_icons`** | 站点图标表:根路径文件服务 + 默认 head 链接注入全站 | -| `static`(增强) | `静态`(增强) | `web_app_static` | 约定:目录内 `favicon.ico|png|svg` → 自动注册 `/favicon.ico`(可被 `icons` 显式行覆盖) | - ---- - -## 4. 表形约定 - -单元格仍为**字面量**;列名中英等价(任选一套,勿混列名语义)。 - -### 4.1 站点图标表(`app.icons` / `应用.图标`) - -| 列(ZH) | 列(EN) | 必填 | 说明 | -|----------|----------|------|------| -| `路径` | `path` | ✅* | 磁盘路径(相对进程 cwd 或入口目录解析规则与 `static` 一致) | -| `关系` | `rel` | | 默认 `icon`;常用 `icon` / `apple-touch-icon` / `mask-icon` | -| `类型` | `type` | | 缺省按扩展名推断 | -| `尺寸` | `sizes` | | 如 `16x16`、`180x180`、`any` | -| `地址` | `url` / `href` | | 对外 URL。缺省:首个 `rel=icon` 且扩展名为 `.ico` → `/favicon.ico`;否则 `/icons/{文件名}` | - -\* 若仅提供 `地址` 指向已由 `静态` 提供的 URL、不落盘服务,则 `路径` 可空(只注入 head,不挂新路由)。 - -**Listen 行为** - -1. 规范化为数组 `{path, rel, type, sizes, url}`。 -2. 对每个非空 `path`:注册 **`GET {url}`**,读文件返回,`Content-Type` = `type` 或推断;`Cache-Control` 可用 `public, max-age=86400`。 -3. 若存在至少一个 `rel` 含 `icon` 的行,保证浏览器默认路径:若没有任何 `url=/favicon.ico`,则把**第一行 icon** 额外挂到 `/favicon.ico`(同一文件,可选)。 -4. 将图标行转为默认 head 链接列表,存入 `app.site_head`,listen 时写入 `AppState`,渲染任意页面前 **merge**(页面自有 `head` / meta 图标 **追加且可同 href 去重**)。 - -**`static` 约定自动图标** - -在 `listen` 解析完 `static_dir` 后:若 `app.icons` 为空,且 `{static_dir}/favicon.ico` 或 `.png` / `.svg` 存在,则等价注册: - -```text -path = {static_dir}/favicon.{ico|png|svg} -rel = icon -url = /favicon.ico -``` - -(文件仍可通过 `/static/favicon.*` 访问;根路径额外可达。) - -### 4.2 Head 资源表(`page.head` / `页面.头装配`) - -| 列(ZH) | 列(EN) | 说明 | -|----------|----------|------| -| `关系` | `rel` | `icon` / `apple-touch-icon` / `stylesheet` / `preload` / `modulepreload` / `manifest` / `canonical` / **`script`** / **`module`** | -| `地址` | `href` / `src` / `url` | 资源 URL | -| `类型` | `type` | MIME 或 `module` | -| `尺寸` | `sizes` | icons | -| `媒体` | `media` | CSS media | -| `作为` | `as` | preload `as` | -| `跨域` | `crossorigin` | 空 / `anonymous` / `use-credentials` | -| `推迟` | `defer` | 经典 `script` 为真时输出 `defer`(缺省同步,兼容旧站) | -| `异步` | `async` | 为真时输出 `async` | -| `版本` | `version` / `v` | 非空则自动追加 `?v=`;否则用页面/应用 `asset_version` | - -**渲染规则** - -| `rel` | 输出 | -|-------|------| -| `script` | `<script … src="…"></script>`(可选 `defer`/`async`;`type` 非空则写出) | -| `module` | `<script type="module" src="…"></script>`(浏览器默认 defer 语义) | -| 其他 | `<link rel="…" href="…" …>`(按列附加 `type`/`sizes`/`media`/`as`/`crossorigin`) | - -空 `地址` 的行跳过。 - -### 4.3 元数据表增强(`page.meta`) - -| 键 | 行为 | -|----|------| -| `title` / `description` / `canonical` / `og:*` | **不变** | -| **`icon`** / **`favicon`** | `<link rel="icon" href="{值}"/>`(可选若值含空格后 MIME:本切片仅 href) | -| **`apple-touch-icon`** | `<link rel="apple-touch-icon" href="{值}"/>` | -| 其他 | 仍为 `<meta name="…" content="…"/>` | - -### 4.4 图片表(`make_images` / `page.images`) - -| 列(ZH) | 列(EN) | 说明 | -|----------|----------|------| -| `源` | `src` | 必填,图片 URL | -| `替代` | `alt` | `alt` 文本,默认空 | -| `标题` | `title` | `title` 属性 | -| `类` | `class` | 加在 `<figure>`(无 figure 时加在 `<img>`) | -| `链接` | `href` / `link` | 非空则用 `<a>` 包裹 `<img>` | -| `宽度` | `width` | 像素,可选 | -| `高度` | `height` | 像素,可选 | -| `加载` | `loading` | `lazy` / `eager`;默认 `lazy`(首行可写 `eager`) | -| `图注` | `caption` | 非空则 `<figcaption>` | -| `槽` | `slot` | 预留:`main`(默认)。本切片只支持主区 | - -**输出 HTML(多行)** - -```html -<div class="mq-images" data-slot="main"> - <figure class="mq-img …">…</figure> - … -</div> -``` - -单行且无图注/类时仍包在 `div.mq-images` 内,保证主题可统一选中。 - -**`page.images`**:调用 `web_images` 逻辑,结果写入 `page.images_html`。 - -**渲染位置**:`render_page` 主区中,在 `intro` **之前**插入 `images_html`(品牌图/头图常见需求);`render_fragment` 的 main 槽同样插入。 - -路径与 MIME 单元格若含 `/`,须写成引号字面量(T5 单元格表达式会把裸 `/` 当除法):`"/favicon.ico"`、`"image/png"`。 - ---- - -## 5. 插件 / 状态形状 - -### 5.1 页面对象新增字段 - -```json -{ - "meta": { "title": "…", "icon": "/favicon.ico" }, - "head": [ - { "rel": "stylesheet", "href": "/static/print.css", "media": "print" } - ], - "images_html": "<div class=\"mq-images\">…</div>" -} -``` - -### 5.2 应用对象新增字段 - -```json -{ - "static_dir": "public", - "static_mount": "/static", - "icons": [ - { - "path": "public/favicon.ico", - "rel": "icon", - "type": "image/x-icon", - "sizes": "32x32", - "url": "/favicon.ico" - } - ], - "site_head": [ - { "rel": "icon", "href": "/favicon.ico", "type": "image/x-icon", "sizes": "32x32" } - ] -} -``` - -`site_head` 由 `web_app_icons`(及 static 约定)生成,作者不必手写。 - -### 5.3 `AppState` / `listen` 签名 - -新增: - -- `icon_routes: Vec<IconRoute { url, path, content_type }>` -- `site_head: Vec<HeadLink>` - -在 `home` / 动态与静态 `route` 渲染前:`merge_site_head(&mut page, &state.site_head)`。 - ---- - -## 6. MIME 推断 - -| 扩展名 | Content-Type | -|--------|----------------| -| `.ico` | `image/x-icon` | -| `.png` | `image/png` | -| `.svg` | `image/svg+xml` | -| `.webp` | `image/webp` | -| `.jpg` / `.jpeg` | `image/jpeg` | -| `.gif` | `image/gif` | -| `.webmanifest` / `.json` | `application/manifest+json` | -| 其他 | `application/octet-stream` | - ---- - -## 7. 作者示例(中文) - -```markdown -## 站点图标 - -|路径|关系|类型|尺寸|地址| -|---|---|---|---|---| -|public/favicon.ico|icon|image/x-icon|32x32|/favicon.ico| -|public/apple-touch-icon.png|apple-touch-icon|image/png|180x180|/static/apple-touch-icon.png| - -## 头资源 - -|关系|地址|类型|媒体| -|---|---|---|---| -|icon|/favicon.ico|image/x-icon| -|stylesheet|/static/print.css|text/css|print| -|script|/static/live.js|| - -## 品牌图 - -|源|替代|类|链接|宽度|加载| -|---|---|---|---|---|---| -|/static/logo.svg|Marqdo|brand-logo|/|48|eager| - -# main - -*page = > 网页.页面 标题="博客"* -*page = > page.头装配 表=`头资源`* -*page = > page.图片装配 表=`品牌图`* -*page = > page.元数据 元数据=`seo表`* - -*app = > 网页.应用 页面=`page` …* -*app = > app.静态 目录="public" 挂载="/static"* -*app = > app.图标 表=`站点图标`* -> app.监听 -``` - -英文对称:`web.page` / `head` / `images` / `meta`;`web.app` / `static` / `icons`;模块 `web.make_images`。 - ---- - -## 8. 实现清单(本切片必须全部完成) - -| # | 项 | 归属 | -|---|----|------| -| I1 | `assets.rs`:表解析、MIME、`web_images` HTML、`web_head` HTML、图标规范化 | `plugins/web` | -| I2 | `web_page_head` / `web_page_images` / `web_images` / `web_head` / `web_app_icons` FFI + 注册 | `plugins/web` | -| I3 | `head_html`:meta 图标键 + `page.head` + 合并 `site_head` | `render.rs` | -| I4 | `images_html` 插入主区;fragment main 同理 | `render.rs` | -| I5 | `listen`:图标文件路由 + static 约定 favicon + `AppState` 注入 | `http.rs` / `lib.rs` | -| I6 | `ext/web/web.mq.md` + `网页.mq.md` L1 方法与叙述 | `ext/web` | -| I7 | 金样:离线装配 + live `GET /favicon.ico` + HTML 含 link/img | `tests/ext/` | -| I8 | `examples/marqdo-blog`:真实 favicon + logo 装配 + README | `examples/` | -| I9 | 更新 [web-net-capabilities.md](web-net-capabilities.md)、[ext-web.md](ext-web.md)、[doc/README.md](../README.md)、CHANGELOG Unreleased;Skill 专节一句 | 文档 | - -**非目标(本切片不做)** - -- 服务端图片缩放 / WebP 转码 -- CDN 签名 URL -- 把上传相册(`gallery`)与品牌图混为一谈 -- 进程内 TLS(仍见反代文档) - ---- - -## 9. 验收标准 - -1. `marqdo run tests/ext/web-assets-smoke.mq.md` 离线:icons/head/images 字段与 HTML 片段断言通过。 -2. Live:`GET /favicon.ico` → 200 + 正确 Content-Type;首页 HTML 含 `rel="icon"` 与 `mq-images`。 -3. `examples/marqdo-blog`:`curl /favicon.ico` 与页面源码可见图标与 logo。 -4. 旧金样(`web-static-smoke`、`web-content-smoke` 等)不回归。 -5. `ext/**` 无 `host_*`。 - ---- - -## 10. 与能力矩阵的关系 - -在 [web-net-capabilities.md](web-net-capabilities.md) **类 D** 增补: - -| # | 能力 | 状态 | -|---|------|------| -| **D10** | 站点图标 / `/favicon.ico` / apple-touch-icon | ✅ 本设计 | -| **D11** | Head 资源表(link / script / preload / manifest) | ✅ 本设计 | -| **D12** | 图片装配(GFM → figure/img)+ 主区注入 | ✅ 本设计 | - -波次标签:**W8(站点资源与图片装配)** — 在 W7+P3 完结之上的内容站体验补齐,不推翻既有边界。 diff --git a/doc/design/web-invoke-serialization.md b/doc/design/web-invoke-serialization.md deleted file mode 100755 index c5a2f10..0000000 --- a/doc/design/web-invoke-serialization.md +++ /dev/null @@ -1,163 +0,0 @@ -# Web 热路径:单解释器串行化(设计缺陷说明) - -| | | -|---|---| -| 状态 | **Accepted**(缺陷记录 + 缓解已落地) | -| 日期 | 2026-10-26 | -| 规范决策 | [ADR 0008](../adr/0008-web-invoke-serialization.md) | -| 相关 | [ext-web-go-rewrite.md](ext-web-go-rewrite.md) · [ext-abi.md](ext-abi.md) · [ADR 0004](../adr/0004-web-plugin-go.md) · [ADR 0007](../adr/0007-web-document-endpoint.md) | - -本文把「页面卡死 / 像单线程」拆成可验证的架构事实、错误语义与演进边界。 -**结论先行:HTTP 是多线程的;卡住是因为所有 Endpoint 共享一把解释器锁。** - -增量实施提案见 [隔离执行与响应式 Web 运行时(2026-10-26)](isolated-web-runtime-development-2026-10-26.md):独立进程池、控制/读取容量、请求级事件与取消、缓存和恢复。提案通过验收前,本文件及 ADR 0008 的现行单飞约束不变。 - ---- - -## 1. 问题陈述 - -### 1.1 用户可见症状 - -1. 发起一次长对话(OpenAI 兼容 `POST …/v1/chat/completions` + `stream:true` / `sse-live`)。 -2. 对话尚未结束时,打开设置、拉 `/v1/models`、或其它短 JSON API。 -3. **旧行为**:浏览器请求一直 pending,整页像死机;只能杀 `marqdo run serve…` 恢复。 -4. **目标行为**:短请求在约 1.5s 内得到 **HTTP 503**,错误体标明 `interpreter busy`;对话 SSE 继续;结束后短请求立刻恢复 200。 - -### 1.2 错误归因(不要再说错) - -| 错误说法 | 正确说法 | -|----------|----------| -| 「web 插件是单线程的」 | Go `net/http` 与 SSE 刷写是多 goroutine | -| 「忘记启动进程所以卡死」 | 进程在跑;是 **锁争用** 导致短请求永不返回 | -| 「把 SSE 的等待时间调大就能修好」 | 进程级拉长 `MARQDO_INVOKE_WAIT_MS` 会让短请求一起卡死 | -| 「去掉 INVOKE_LOCK 即可并行」 | `HostContext` 非 Sync,无锁并行会数据竞争 / 未定义行为 | - ---- - -## 2. 调用栈与锁边界 - -``` -Browser - │ GET /v1/models POST /v1/chat/completions (SSE) - ▼ -Go plugins/web (多 goroutine) - handleInvoke / handleInvokeLiveSSE - │ - ▼ C ABI host_query("call_lib_path", {path, args}) -Rust src/host/plugin.rs - ┌─────────────────────────────┐ - │ INVOKE_LOCK (进程级 Mutex) │ ← 同一时刻只允许一个 worker 进入 - └─────────────────────────────┘ - │ - ▼ -HostContext:装载/求值作者 .mq.md、写回、事件总线、LLM 插件回调… -``` - -要点: - -1. **锁在宿主,不在 Go 业务路由表。** 增加更多 Go handler 不会自动并行执行 Marqdo。 -2. **SSE 持锁时间 ≈ 整次 Endpoint 求值时间**(含多次 LLM 往返),可达数十秒到数分钟。 -3. **事件转发**(`MARQDO_EVENT_FORWARD` NDJSON)与 **取消**(`MARQDO_CANCEL_TOKEN`)在持锁期间仍可由其它 goroutine 写文件/读桥;它们不进入解释器,故不受 `INVOKE_LOCK` 保护,也不应误设长等待。 - ---- - -## 3. 为何不能简单「多线程跑 Marqdo」 - -`HostContext` 持有(非穷尽): - -- 当前模块图、函数表、写回缓冲与 FS 根; -- 插件注册与 `CURRENT_HOST` / 全局 host 指针; -- Agent / LLM 运行时与 stream 发布钩子; -- 与文档写回、会话态相关的可变结构。 - -这些状态在实现上按**单线程求值**建模。把它标成 `Sync` 或去掉 `INVOKE_LOCK` 而没有隔离运行时,属于未定义行为,不是性能优化。 - -**真并行的合法方向(未实现):** - -1. **解释器池**:每请求或每会话一个 `HostContext`(或可重置的 isolate),路由层选闲置实例; -2. **只读快照 + 写队列**:热路径只读克隆,写回串行合并(适合纯查询 Endpoint,不适合带写回的 agent); -3. **把长任务移出解释器**:Marqdo 只做编排,重活在独立进程/队列(与「代码即文档」主路径权衡后再定)。 - -在上述任一方案落地并经金样例验收前,**产品必须以「单飞解释器」为约束设计 UX**。 - ---- - -## 4. 缓解契约(已实现) - -### 4.1 宿主:限时争锁 - -文件:`src/host/plugin.rs` - -- 仅当从 worker 线程进入(`CURRENT_HOST` 为空、走全局 host)时争 `INVOKE_LOCK`。 -- `acquire_invoke_lock`:`try_lock` 循环,预算默认 **1500ms**(`MARQDO_INVOKE_WAIT_MS`,最小 1)。 -- 超时:`set_err("interpreter busy: another request holds the Marqdo invoke lock (waited …ms)")`,返回非 0。 -- **不要**在 SSE 入口把该环境变量设成数分钟:它是进程级的,会污染并发短请求。 - -### 4.2 Web 插件:503 - -文件:`plugins/web/internal/httpx/routes_invoke.go` - -- 普通 JSON invoke:错误信息含 `interpreter busy` → **503** + `Retry-After: 2` + `{ok:false, error:…}`。 -- Live SSE:若启动时即 busy,以失败事件/错误结束该流,**不得**无限挂起握手。 - -### 4.3 客户端:超时与文案 - -短 API(模型列表、设置、registry 探测等)必须: - -- 设置合理 `fetch` 超时(秒级,例如 8s); -- 将 503 / `interpreter busy` 展示为「服务正忙(对话进行中)」类可读提示,而不是空白转圈。 - -(qdagent 前端 `frontend/src/lib/api.ts` 已按此契约处理。) - -### 4.4 验收探针 - -在本地 serve 上: - -```bash -# 终端 A:启动长 SSE 对话(持锁) -curl -N -m 120 -H 'Authorization: Bearer …' -H 'Content-Type: application/json' \ - -d '{"stream":true,…}' http://127.0.0.1:PORT/v1/chat/completions - -# 终端 B:对话进行中 -curl -sS -w 'http=%{http_code} time=%{time_total}\n' --max-time 5 \ - -H 'Authorization: Bearer …' http://127.0.0.1:PORT/v1/models -# 期望:http=503,time≈1.5,body 含 interpreter busy - -# 对话结束后再打同一 URL → http=200,time≪1s -``` - ---- - -## 5. 运维与调参 - -| 变量 | 默认 | 含义 | -|------|------|------| -| `MARQDO_INVOKE_WAIT_MS` | `1500` | worker 进入解释器前最长等待;超时 → busy | - -建议: - -- 开发机 / 产品默认保持 1–3s。 -- **禁止**为「让第二个聊天排队」而把默认调到分钟级——那等于恢复卡死。 -- 需要排队时,应在 **应用层**(会话队列、UI 禁用「再发一条」),而不是拉长宿主锁等待。 - ---- - -## 6. 与其它机制的边界 - -| 机制 | 与 INVOKE_LOCK 的关系 | -|------|----------------------| -| `MARQDO_EVENT_FORWARD` | SSE 期间写 NDJSON;不替代争锁;不延长等待 | -| `MARQDO_CANCEL_TOKEN` | 断开连接时可取消 LLM;释放锁仍取决于解释器何时回到 FFI | -| `web.serve` / 静态资源 | 通常不经 `call_lib_path`,不受本锁影响 | -| 插件内部 Tokio/Go 并发 | 可以;只要不再次 `call_lib_path` 进同一 HostContext | - ---- - -## 7. 演进检查清单(根治前勿宣称「已支持并行 Endpoint」) - -- [ ] 多 `HostContext` 或 isolate 的生命周期与 ABI(装载、shutdown、写回冲突)有设计稿与金样例。 -- [ ] 池化后 `call_lib_path` 不再依赖进程级单锁,或锁粒度降到实例级。 -- [ ] 两个并发长 SSE + 一个短 `/v1/models` 的压力测试:短请求稳定 200,长请求互不污染会话写回。 -- [ ] 更新本文件与 ADR 0008 Status(例如改为 Superseded by ADR NNNN)。 - -在清单完成前,对外与文档中应明确:**Marqdo Web Endpoint 求值在单进程内串行;HTTP 层并发,解释器层单飞。** diff --git a/doc/design/web-net-capabilities.md b/doc/design/web-net-capabilities.md deleted file mode 100755 index b519f27..0000000 --- a/doc/design/web-net-capabilities.md +++ /dev/null @@ -1,278 +0,0 @@ -# 网络能力调研:从「能跑」到「完整项目」 - -| | | -|---|---| -| 状态 | **Historical capability matrix** — 作者面以 **[ext-web-artifact.md](ext-web-artifact.md)** / ADR [0007](../adr/0007-web-document-endpoint.md) 为准(2026-09-28) | -| 日期 | 2026-08-26(初稿)· 2026-08-28(完结复核)· 2026-09-28(Artifact 标注) | -| 相关 | [ext-web-artifact.md](ext-web-artifact.md) · [ext-web.md](ext-web.md) · [ext-web-net.md](ext-web-net.md) · [ext-abi.md](ext-abi.md) · [stdlib-modules.md](stdlib-modules.md) | -| 目标 | 盘点 `ext/web` + `plugins/web` + `lib/net` 现状;**下文 API 名多为 W0–W7 历史面**(`compose_*` / `configure` 已废止) | - -> **2026-09-28**:作者面迁移到 Document / Endpoint / Resource。 -> - Document/Endpoint:`type: web|endpoint` + `web.serve` / `web.render` / `web.inspect` -> - DB/cache/storage → `ext/data`;auth/oidc/rbac → `ext/security`;ws → `ext/net` -> - 统一 View:`|type|slot|value|attrs|style|`;中间件:`web.use` -> 本文件保留为**原生能力矩阵**对照,勿再按 `compose_*` / `app.configure` 写作。 - ---- - -## 0. 一句话结论 - -**能力层(plugins/web)**:中间件/JSON API、数据层、安全、内容站点、上传下载、sitemap、WebSocket 等仍在原生实现中。 -**作者面(2026-09-28)**:改为 Artifact Metadata + facade;`compose_*` / `configure` **已删除**。边界不变:**纯解析进 `lib/net`,HTTP 服务器进 `plugins/web`,作者 API 进 `ext/web` + `ext/data` + `ext/security` + `ext/net`**。 - -**宿主集成下一刀**(同域 LLM SSE 中继、HTTP→用户 `##`、与 MCP Server 协作)不在本 W 表内,见 [ext-hosting-gaps.md](../research/ext-hosting-gaps.md) · [ext-hosting-fill.md](ext-hosting-fill.md) · [ext-hosting.md](../roadmap/ext-hosting.md)。 - - ---- - -## 1. 现状盘点(2026-08-26 实测) - -### 1.1 `lib/net`(标准库,L0.5 宿主原语薄包装) - -| 能力 | 归属 | 现状 | -|---|---|---| -| `http_get` / `获取` | host `net.rs` (ureq) | ✅ GET,返回 `{status, body}` | -| `http_post` / `提交` | host `net.rs` | ✅ POST,默认 JSON CT | -| `http_request` / `请求` | host `net.rs` | ✅ 通用 method+body+headers | -| `http_post_sse` / `提交流式` | host `net.rs` | ✅ OpenAI 兼容 SSE 流式消费 | -| `openai_sse_parse` / `解析流式` | host `net.rs` | ✅ 离线 SSE 解析 | -| `url_encode` / `编码地址` | host `net.rs` | ✅ URL 编码 | -| `cookie_parse` / `解析Cookie` | host `net.rs` | ✅ RFC6265 子集(请求头/响应头) | -| `multipart_parse` / `解析多部分` | host `net.rs` | ✅ multipart/form-data 解析 | -| `markdown_parse` / `解析Markdown` | host `net.rs` | ✅ GFM/Markdown → HTML(纯解析,W4c) | - -**标准库网络原语已齐备**:客户端 GET/POST/SSE、URL 编码、cookie、multipart、Markdown 解析。服务器侧上传/下载/ETag 在 `plugins/web`(A5/P3)。 - -### 1.2 `plugins/web`(ABI v2,领域能力) - -**服务器侧已实现:** - -| 域 | ABI | 能力 | -|---|---|---| -| 页面 | `web_page_new` · `web_compose_components` · `web_compose_main` · `web_page_query` · `web_page_order` · `web_page_link_prefix` · `web_page_css` · `web_page_detail` | 页面装配、列表/排序、CSS、详情页 | -| 样式 | `web_style` | GFM 表 → CSS(`make_style`/`样式装配`) | -| 表单 | `web_form_new/fields/rules/validate/render/submit/from_schema` · `web_compose_form` | 字段表、校验表、渲染、提交、schema→form | -| 数据库 | `web_db_new/init/insert/select/get/update/delete/exec/table_info/list_tables` | SQLite CRUD + where + order + limit | -| 应用 | `web_app_new/route/mount_form/static/auth` · `web_app_route_ws` | 路由、静态目录、admin、鉴权、WS 端点 | -| 会话 | `web_session_new/set/get/del/destroy` | 内存 TTL 会话 | -| 鉴权 | `web_auth_login/check/logout/new` · `web_app_auth` | `/admin` 登录门禁 | -| WebSocket | `web_ws_connect`(客户端)· `web_app_route_ws`(服务器) | 单请求-响应式客户端 + echo 服务器 | - -**关键实现事实(2026-08-28 W7+P3 后):** - -- **中间件 + JSON API**(W1):`app.configure` 装配 CORS、安全头、gzip、请求体上限、JSON 端点。 -- **数据层**(W2/W6/W7/P3):连接池、事务、分页、OR/IN/BETWEEN、`db.count`、迁移、FTS5 搜索、init 唯一/索引/外键、审计时间戳。 -- **安全**(W3s/P3):argon2、CSRF、SQLite 会话、CSPRNG session id、登录限速、RBAC(`app.gate` + 用户 `role`)。 -- **内容站点**(W4c/W7):SEO `page.meta`、RSS、Markdown 正文、`page.paginate`、sitemap/robots。 -- **媒体**(W5/P3):multipart 上传、下载、`app.gallery`、ETag/Cache-Control。 -- **运维向**(W6/W7):访问日志、自定义 404/500、301/307 重定向、WS 广播;HTTPS 由反代终止 + `cookie_secure`。 -- **仍属应用层约定**:标签聚合页模板(D6)、评论反垃圾、草稿/定时发布(表+where 即可)。 - ---- - - -## 2. 主流网络栈对照(联网调研 2026-08) - -### 2.1 分层共识(决定「标准库 vs 扩展」边界) - -| 语言 | 标准库网络能力 | 扩展/框架能力 | 边界准则 | -|---|---|---|---| -| Python | `urllib`(HTTP 客户端)、`http.cookies`(cookie 解析器)、`http.server`(简易服务器)、`email` 多部分解析 | `requests`/`httpx`(连接池/session)、`FastAPI`/`Flask`(中间件/校验/模板) | 解析器进标准库;便利层/框架层在第三方 | -| Node.js | `node:http`(低层流式,**不解析 body**)、`node:https` | express、fastify、ws、formidable | 低层原语进核心;fancy 功能 userland 验证后再进 core | -| Go | `net/http`(服务器+客户端**都在标准库**)、`net/http/cookiejar`(RFC6265)、`net/smtp` | `golang.org/x/net`(演进性)、gin/echo | HTTP 与 stdin 同级的核心能力;cookie 解析进标准库 | -| Rust | 极小 std(无 HTTP) | `hyper`→`reqwest`→`axum` | 分层;HTTP 生态多样不进 std | - -**对本项目的三处判定(与 [ext-web-net.md](ext-web-net.md) 一致并延伸):** - -1. **纯解析原语**(cookie / multipart / url)→ `lib/net` 标准库。✅ 已达成。 -2. **HTTP 服务器结构能力**(JSON / 中间件 / 上传下载 / HTTPS / 缓存头)→ `plugins/web`(ABI)。这是 axum 本身就在依赖链里的,不需要新增核心依赖。 -3. **领域能力**(session / auth / 分页 / 搜索 / RSS / SEO / 限流)→ `plugins/web` + `ext/web` 作者面。 - -### 2.2 「完整 Web 框架」能力清单(FastAPI / Express / Flask / axum 共通项) - -> **marqdo 列**反映 **2026-08-28 W7+P3 完结** 后状态(见 §3 差距表)。 - -| 能力 | FastAPI | Express | Flask | axum | marqdo | -|---|---|---|---|---|---| -| 路由(含动态参数) | ✅ | ✅ | ✅ | ✅ | ✅ 动态路由 `/post/{slug}` | -| 中间件管道 | ✅ | ✅ | ✅ | ✅(tower) | ✅ W1 `app.configure` | -| CORS | ✅ 内置 | ✅ 中间件 | ✅ flask-cors | ✅ tower-http | ✅ W1 | -| JSON 请求/响应 | ✅ 原生 | ✅ | ✅ | ✅ | ✅ W1 JSON API 表 | -| 校验(schema/字段) | ✅ Pydantic | 手动(zod) | 手动 | ✅ extractor | ✅ form 校验表 | -| 静态文件 | ✅ Starlette | ✅ | ✅ | ✅ | ✅ `app.static` | -| 模板/渲染 | ✅ Jinja | ✅ | ✅ | ✅ | ✅ GFM 表装配 | -| 会话 | ✅ | ✅ express-session | ✅ | ✅ | ✅ SQLite 持久化(W3s) | -| 鉴权 | ✅ OAuth2/APIKey | ✅ | ✅ | ✅ | ✅ admin + RBAC(P3) | -| 文件上传 | ✅ | ✅ multer | ✅ | ✅ | ✅ W5 upload | -| WebSocket | ✅ | ✅ ws | ✅ Flask-SocketIO | ✅ | ✅ echo + 广播(W6) | -| 安全头 | ✅ | ✅ helmet | ✅ | ✅ tower-http | ✅ W1 | -| 限流 | ✅ | ✅ | ✅ | ✅ | ✅ 登录限速(W3s) | -| 日志 | ✅ | ✅ morgan | ✅ | ✅ | ✅ access_log(W6) | -| gzip 压缩 | ✅ | ✅ | ✅ | ✅ | ✅ W1 | -| 分页 | 手动 | 手动 | ✅ paginate | ✅ | ✅ db + page UI(W2/W4c) | -| 迁移 | ✅ alembic | ✅ | ✅ | ✅ sqlx | ✅ W6 `db.migrate` | -| 测试工具 | ✅ TestClient | ✅ supertest | ✅ | ✅ | gold 测试(`tests/ext/web-*`) | -| HTTPS/TLS | 反代 | 反代 | 反代 | ✅ rustls | 反代 + `cookie_secure`(W7 文档锁定) | - ---- - - -## 3. 差距分析:按「完整项目」四类需求 - -### 3.1 类 A:结构化 HTTP 基础设施(做 API / 前后端分离 / SPA 支撑) - -| # | 缺失能力 | 影响 | 归属 | 优先级 | -|---|---|---|---|---| -| A1 | **JSON 请求/响应**(`Json` extractor、`application/json` 响应、body 大小限制) | ✅ **已实现(W1)**:`接口` 表声明 JSON API 端点;`请求体上限` 配置 body 限制 | `plugins/web` | **P0 ✅** | -| A2 | **中间件管道**(`app.configure` / `应用.装配`:CORS、安全头、压缩、请求体限制统一挂载) | ✅ **已实现(W1)**:`middleware.rs` 装配 GFM 表并 `app.layer` 挂到 axum | `plugins/web` | **P0 ✅** | -| A3 | **CORS 支持**(`Access-Control-Allow-Origin` 可配) | ✅ **已实现(W1)**:`跨域` 表 `|允许来源|方法|头|暴露头|凭证|` | `plugins/web` | P1 ✅ | -| A4 | **安全响应头**(CSP / X-Frame-Options / X-Content-Type-Options / HSTS / Referrer-Policy / 去 `X-Powered-By`) | ✅ **已实现(W1)**:`安全` 表 `|头|值|` | `plugins/web` | P1 ✅ | -| A5 | **文件上传接收**(multipart extractor → 校验类型/大小 → 落盘)与**下载**(`Content-Disposition`) | ✅ **已实现(W5)**:`app.upload` / `app.download`;`file:` storage;离线 + curl live 金样 | `plugins/web` | P1 ✅ | -| A6 | **HTTPS / TLS**(rustls 终止或反代提示) | ✅ **文档锁定(W7)**:进程内 TLS 不启用;反代终止 HTTPS,并设 `cookie_secure=True` | 文档 + `cookie_secure` | P2 ✅ | -| A7 | **gzip / br 压缩** + **ETag / Cache-Control 缓存头** | gzip ✅(W1);Cache-Control ✅(W7);ETag ✅ **已实现(P3,下载/相册 + If-None-Match→304)** | `plugins/web` | P2 ✅ | -| A8 | **访问日志**(请求方法/路径/状态/耗时) | ✅ **已实现(W6b)**:`configure access_log=True` → stderr | `plugins/web` | P2 ✅ | -| A9 | **自定义 404/500 错误页** | ✅ **已实现(W7)**:`app.error_page` / `应用.错误页`;404 fallback + 500 页袋 | `plugins/web` | P2 ✅ | -| A10 | **重定向增强**(permanent/自定义状态码) | ✅ **已实现(W7)**:`app.redirect` → 301/307 | `plugins/web` | P3 ✅ | - -### 3.2 类 B:数据层深化(内容站点/社区的根基) - -| # | 缺失能力 | 影响 | 归属 | 优先级 | -|---|---|---|---|---| -| B1 | **连接池 / busy_timeout / WAL** | 高并发下 `database is locked`、每请求重连开销 | `plugins/web`(db.rs) | **P0 ✅** | -| B2 | **事务 API**(`begin` / `commit` / `rollback`,或 `with_transaction` 包装) | 批量/多表写无原子性 | `plugins/web` | **P0 ✅** | -| B3 | **结果集型裸查询**(exec 返回 rows) | count / join / group / 子查询完全不可用 | `plugins/web` | P1 ✅ | -| B4 | **分页**(db 层 `limit`+`offset`;页面层上一页/下一页) | 列表页只能限量 | `plugins/web` + `ext/web` | P1 ✅(db 层;页面 UI 属 D4) | -| B5 | **查询表达力**:OR / IN / BETWEEN / IS NULL / LIKE 转义 / 括号组合 | where 只能 AND | `plugins/web` | P1 ✅ | -| B6 | **迁移机制**(schema 版本表 + 迁移脚本) | ✅ **已实现(W6)**:`db.migrate` + `_marqdo_migrations`(SQLite) | `plugins/web` + `ext/web` | P2 ✅ | -| B7 | **索引 / 唯一 / 外键声明**(init 表增强) | ✅ **已实现(W7+P3)**:`唯一`/`索引`/`外键`(`posts.id` / `posts`) | `plugins/web` | P2 ✅ | -| B8 | **聚合辅助**:count / group 便捷 API | 统计面板、标签计数 | `plugins/web` | P2 ✅(`db.count`) | -| B9 | **全文搜索**(SQLite FTS5) | ✅ **已实现(W6)**:`db.fts` + `db.search`(bm25) | `plugins/web`(FTS5 现成) | P2 ✅ | -| B10 | **时间戳 / 审计字段自动维护** | ✅ **已实现(P3)**:表含 `created_at`/`updated_at` 时 insert/update 自动写入 | `plugins/web` | P3 ✅ | - -### 3.3 类 C:安全硬化(能上线的前提) - -| # | 缺失能力 | 影响 | 归属 | 优先级 | -|---|---|---|---|---| -| C1 | **密码哈希**(argon2/bcrypt/sha+盐,替代明文) | ✅ **已实现(W3s)**:argon2 | `plugins/web` | **P0 ✅** | -| C2 | **CSRF 防护**(session-bound token,写操作校验) | ✅ **已实现(W3s)** | `plugins/web` | **P0 ✅** | -| C3 | **登录限速/失败锁定**(每 IP/用户名 5 次/15min) | ✅ **已实现(W3s)** | `plugins/web` | P1 ✅ | -| C4 | **会话持久化**(SQLite/文件,替代内存) | ✅ **已实现(W3s)** | `plugins/web` | P1 ✅ | -| C5 | **加密安全 session id**(CSPRNG + 碰撞重试) | ✅ **已实现(W3s)** | `plugins/web` | P1 ✅ | -| C6 | **cookie 增强**:`Secure` 标志、签名、滑动过期 | ✅ **已实现**:`cookie_secure` + 滑动 TTL(touch);cookie 签名未单独做 | `plugins/web` | P2 ✅ | -| C7 | **防暴力破解 / 会话上限 / 后台过期清理** | ✅ 限速 + prune;会话条数硬上限可后续 | `plugins/web` | P2 ✅ | -| C8 | **RBAC / 多角色**(作者/管理员/访客) | ✅ **已实现(P3)**:用户表 `role`/`角色`;`app.gate`;`/admin*` 默认需 `admin` | `plugins/web` + `ext/web` | P3 ✅ | - -### 3.4 类 D:内容站点标配(博客/CMS 特有) - -| # | 缺失能力 | 影响 | 归属 | 优先级 | -|---|---|---|---|---| -| D1 | **SEO**:每页 `<title>`/`meta description`/OG 标签/`canonical`/结构化数据 | ✅ **已实现(W4c)**:`page.meta` | `ext/web` | **P0 ✅** | -| D2 | **sitemap.xml / robots.txt** 生成 | ✅ **已实现(W7)**:`app.sitemap` / `app.robots` | `plugins/web` + `ext/web` | P1 ✅ | -| D3 | **RSS/Atom 输出**(`content_type=application/rss+xml` 路由) | ✅ **已实现(W4c)**:`route_rss` | `ext/web` + 插件 | P1 ✅ | -| D4 | **分页导航 UI**(上一页/下一页,依赖 B4) | ✅ **已实现(W4c)**:`page.paginate` | `ext/web` | P1 ✅ | -| D5 | **Markdown 渲染**(正文存储为 Markdown,渲染为 HTML) | ✅ **已实现(W4c)**:`lib/net` + 页面装配 | `lib/net` | **P0 ✅** | -| D6 | **标签/分类聚合页**(`/tag/{slug}` 动态路由 + 计数) | 可用路由+`db.count` 自建(未内置模板) | `ext/web` | P2 | -| D7 | **评论系统**(表单 + 审核 + 反垃圾) | ✅ 约定:表+表单+where(W6);反垃圾属应用层 | `ext/web` | P2 ✅ | -| D8 | **草稿/发布/定时**(状态字段 + 过滤查询) | ✅ 约定:`status` + where(W6) | `ext/web` + db where | P2 ✅ | -| D9 | **图片/附件库**(依赖 A5 上传 + 相册页) | ✅ **已实现(P3)**:`app.gallery` HTML 相册 + A5 上传/下载 | `ext/web` + `plugins/web` | P3 ✅ | -| **D10** | **站点图标 / favicon**(`/favicon.ico` + apple-touch-icon) | ✅ **已实现(W8)**:`app.icons` / `应用.图标`;`static` 约定 `favicon.*`;设计 [web-assets-and-images.md](web-assets-and-images.md) | `plugins/web` + `ext/web` | W8 ✅ | -| **D11** | **Head 资源表**(link / script / preload / manifest) | ✅ **已实现(W8)**:`page.head` / `页面.头装配`;`meta` 认 `icon`/`favicon` | `plugins/web` + `ext/web` | W8 ✅ | -| **D12** | **图片装配**(GFM → figure/img + 主区注入) | ✅ **已实现(W8)**:`make_images` / `网页.图片装配`;`page.images` | `plugins/web` + `ext/web` | W8 ✅ | - ---- - - -## 4. 补强路线(分波次,按「标准库 vs 扩展」边界) - -### 4.1 波次建议(每波独立可交付、可回归) - -| 波次 | 主题 | 内容 | 对应差距 | -|---|---|---|---| -| **W1** | 服务器基础设施 | 中间件管道(CORS/安全头/压缩/请求体限制)+ JSON API(`application/json` 响应 + DB 查询端点) | A1 A2 A3 A4 A7 ✅ **已完成** | -| **W2** | 数据层深化 | 连接池/busy_timeout/WAL + 事务 API + 结果集裸查询 + 分页(offset) + OR/IN/BETWEEN + 聚合 count | B1 B2 B3 B4 B5 B8 ✅ **已完成** | -| **W3** | 安全硬化 | 密码哈希 + CSRF + 会话持久化 + CSPRNG session id + cookie 增强 + 登录限速/锁定 | C1–C7 ✅ | -| **W4** | 内容站点标配 | SEO 元数据 + sitemap/robots + RSS + Markdown 渲染 + 分页导航 UI + 标签/分类 | D1–D5 ✅;D6 约定 | -| **W5** | 上传与媒体 | multipart 文件上传接收 + 落盘 + 下载 + 图片库 | A5 ✅;D9 相册 P3 ✅ | -| **W6** | 进阶 | 全文搜索(FTS5) + 迁移机制 + 评论系统 + 草稿/发布 + WS 广播 | B6 B9 ✅;WS 广播 + access_log ✅;D7/D8 用表+where ✅ | -| **W7** | 完结打磨 | Cache-Control、自定义 404/500、301 重定向、sitemap/robots、init 唯一/索引、HTTPS 反代文档 | A6 A7 A9 A10 B7 D2 ✅ | -| **P3** | 真·网络扩展补齐 | 审计时间戳、外键、RBAC 门禁、媒体相册、下载 ETag | B10 C8 D9 + ETag/FK ✅ | -| **W8** | 站点资源与图片装配 | favicon 根路由、Head 资源表、图片装配、meta 图标键 | D10 D11 D12 ✅ | - -### 4.2 边界判定要点(严格遵守既有约束) - -1. **进标准库 `lib/net`**(纯解析、无网络 I/O、支持扩展库开发): - - `markdown_parse`(GFM/Markdown → HTML,纯解析)→ D5 ✅。 - - `xml_escape` / RSS/Atom 纯文本装配辅助(如需)→ D3(作者面 `route_rss` 已够用)。 - - **不得**放进标准库:JSON API、中间件、上传接收、事务、会话(均涉 I/O 或领域语义)。 -2. **进 `plugins/web`(ABI)**:A1–A10、B1–B10、C1–C8、D7–D8 的插件侧 — **均已落地**(2026-08-28)。 -3. **进 `ext/web` 作者面(Marqdo)**:D1–D4、A5/D2/D9 等 GFM 表包装 — **均已落地**(中英 `web.mq.md` / `网页.mq.md`)。 -4. **已具备、无需新增**:动态路由、静态文件、表单校验/回显、session、admin/RBAC、WebSocket、SSE 客户端、cookie/multipart/Markdown 解析。 - -### 4.3 作者面示例(示 W4 落地形态,保持「代码即文档」) - -**SEO 元数据(扩展页面表):** - -```markdown -`meta` = - -| 键 | 值 | -|---|---| -| `title` | 文章标题 | -| `description` | 摘要 | -| `og_type` | article | -| `canonical` | /post/{slug} | -``` - -页面装配时并入 `<head>` —— 仍是「表 + 函数装配」,不引入 `json.*` 袋。 - -**RSS(扩展路由,响应头 `content_type=application/rss+xml`):** - -```markdown -*feed = > 页面.列出表 rows=`文章` 分页=20 排序="published desc"* -*xml = > 文本.拼装 xs=`rss 片段们`* -*`app` = > `应用`.路由 路径="/feed.xml" 内容=`xml` 类型="application/rss+xml"* -``` - ---- - -## 5. 结论 - -**W0–W7 + P3 已全部落地**(路线图见 [roadmap/ext-web.md](../roadmap/ext-web.md))。验收覆盖: - -- 离线/在线 gold:`tests/ext/web-*-smoke.mq.md`(含 security、drivers、upload、w6、w7、p3) -- 完整示例:`examples/marqdo-blog/`(列表/详情/标签/RSS/后台/上传/WS) -- 作者面:`ext/web/web.mq.md` · `ext/web/网页.mq.md` -- AI 编写指引:`skills/marqdo/`(§ ext/web) - -**后续可选(非阻塞)**:标签页内置模板(D6)、cookie 签名、会话条数硬上限、应用层反垃圾、进程内 TLS(仍建议反代)。 - -**部署对照(Daphne / Uvicorn / 反代):** 见 [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md) — Marqdo **不能**被 Daphne 托管;生产等价路径是 **反代 → 内嵌 axum `listen`**。 - -**一句话:`ext/web` 已是可上线级别的 Marqdo 动态站扩展;博客/CMS/中小型 API 可在表格 + 类方法作者面上完整实现。** - ---- - -## 6. 附:博客示例能力对照(`examples/marqdo-blog`) - -| 博客功能 | 现状 | -|---|---| -| 文章列表(首页) | ✅ | -| 文章详情(动态路由) | ✅ | -| 标签/分类 | ✅ 路由 + `db.where` + `db.count` | -| 分页 | ✅ `db.paginate` + `page.paginate` | -| 搜索 | ✅ FTS5 `db.search` | -| SEO 元数据 | ✅ `page.meta` | -| RSS | ✅ `app.route_rss` | -| 评论 | ✅ 表 + form + where(反垃圾属应用层) | -| 后台写文章 | ✅ admin CRUD + RBAC | -| 草稿/发布 | ✅ `status` 字段 + where | -| 上传配图 | ✅ `app.upload` + `app.gallery` | -| 用户登录 | ✅ argon2 + CSRF + SQLite 会话 + 限速 | -| sitemap / robots | ✅ W7 | -| 实时终端(WS) | ✅ W6 广播 | - ---- - -## 7. 附:Markdown 正文渲染(D5,已落地) - -博客详情页正文经 `lib/net.markdown_parse`(`host_markdown_parse`)解析为 HTML,由 `plugins/web` 渲染层在页面装配时调用(W4c)。作者存储 Markdown 字符串于 DB,展示侧自动渲染 GFM 子集(标题、列表、链接、代码块等)。纯解析留在标准库;**不得**在 `ext/web` 作者面直接调 `host_*`。 diff --git a/doc/design/web-view-resources.md b/doc/design/web-view-resources.md deleted file mode 100755 index 7ca13e4..0000000 --- a/doc/design/web-view-resources.md +++ /dev/null @@ -1,25 +0,0 @@ -# View 中的请求资源 - -状态:请求资源已实现,后续旧站点迁移继续进行。遵循 ADR 0007;沿用五列 View、普通表值与 Resource,不增加 Markdown 标记或 frontmatter 方言。 - -view: main 仍只在启动时执行一次。它返回的结构保留为 View 节点,服务器在每次请求准备会话、路由参数和 CSRF 后渲染。普通 Markdown、控件和布局没有额外业务执行;只有 type=resource 的节点把 value 中的已声明 Resource 交给对应原生处理器。 - -Resource 的职责明确分开:data_query 查询当前应用数据库;form_ref 引用显式挂载的表单;view_navigation 根据当前会话筛选导航。document_head 是纯文档资源,只贡献 SEO 与原生资源链接,不需要请求上下文。它们不接受任意页面属性,不恢复 compose_*、页面变异链或 app.configure。结构和文字继续递归拆成组件及 Markdown 叶子。 - -启动阶段检查节点和资源契约,不查询数据库、不提交表单。请求渲染失败保留真实诊断。离线纯渲染遇到查询、表单与会话导航时明确要求上下文,不伪造空列表、登录状态或表单提交成功。纯页头资源与普通内容可以直接预览。 - -数据查询使用原有数据库资源与条件格式,路由参数来自实际请求。表单通过原有系统路由处理,字段、规则和提交资源保持一致,并传递真实 CSRF 与返回地址。导航的可见性不能替代服务端鉴权。资源绑定和监听仍是独立步骤。 - -验收覆盖启动无数据查询、请求间新增数据可见、完整正文与摘要区分、动态路由条件、登录前后导航、表单校验与提交、CSRF、未知资源失败,以及原有静态布局和浏览器用例。 - - -已完成的实际证据:web-net-site 与 web-net-site-zh 使用这些资源完整迁移;web_handbook 在两个启动后端中验证请求期间的数据更新、表单错误重试、工具页与后台鉴权。原生 Go 测试验证结构装配不查询缺失数据库、未知资源失败、路径条件不污染保留定义、CSRF 拒绝与错误重试。browser_handbook.mjs 使用当前 WASM 验证连续回显、Enter 与空输入、实际提交与管理后台、窄屏布局。 - -入口与边界:component.resource(中文组件为“请求资源”,保留原“资源”作为脚本/样式引用)、data/view.query、form.reference 与 form.mount、component.navigation。表单挂载可显式保护实际系统提交路径,不能只保护展示页面。服务器回调继承授予的文件根,所选站点根只能收窄该范围;嵌套页面按统一站点根读取共享叶子,Endpoint 同样保留该上下文。 - - -片段沿用 /_part/{slot}:递归选择唯一具名区域,在当前请求上下文中解析其资源;不会把源码当作片段返回。未声明 main 槽时保留整组节点作为 main 的兼容回退,其他未知槽返回 404,重复槽保留歧义诊断。容器遍历与完整渲染共享同一类型表,不进入资源私有数据。 - -检视的 registered 范围复用真实监听的注册过程,捕获处理器路径但不执行处理器;不会初始化数据库、重置会话或调用页面。metadata 范围仅扫描文件声明与运行时模板。两者明确区分,不能把目录扫描当成资源绑定已经完成的证据。监听前使用同一注册校验,冲突以诊断返回。系统和声明清单均去重并稳定排序。 - -页头资源保留现有五列 View:组件只安放 `_type=document_head` 的具型值,原生渲染在离线和真实页面中收集到 head,不在正文或片段中渲染占位。它只有 meta 与 links 两个领域字段,不接受任意页面属性、HTML 壳或应用配置。元数据沿用 key/value 表与原生 SEO 行为,链接复用普通 Document 的资源表及双语字段。相同链接按完整定义去重,同名元数据冲突在启动前报错。元数据按键稳定输出,保证同一结构的预览与服务一致。URL 只允许站内绝对路径与 http(s),不读取或下载地址。charset、viewport、csrf-token 属于运行时,作者不能重声明。对应手册为 ext/web/head.mq.md 与 ext/web/页头.mq.md。 diff --git a/doc/dev-setup.md b/doc/dev-setup.md deleted file mode 100755 index 81926a0..0000000 --- a/doc/dev-setup.md +++ /dev/null @@ -1,134 +0,0 @@ -# 开发环境配置(Rust 参考解释器) - -| | | -|---|---| -| 状态 | M0 | -| 相关 | [dependencies.md](design/dependencies.md) · [interpreter.md](roadmap/interpreter.md) | - ---- - -## 1. 必备软件 - -| 软件 | 要求 | 检查 | -|------|------|------| -| Rust + Cargo | stable,建议 ≥ 1.81(本机验证过 1.81) | `rustc --version` / `cargo --version` | -| Git | 任意近期版本 | `git --version` | -| GCC / Binutils | 原生依赖编译与链接 | `cc --version` / `ld --version` | -| Go | ≥ 1.22(仅构建 `plugins/web` 与 web 扩展测试需要) | `go version` | - -安装 Rust(若尚未安装): - -- 官方:[https://rustup.rs/](https://rustup.rs/) -- Windows:下载 `rustup-init.exe`,按提示安装后**重新打开终端** - -本仓库可选 `rust-toolchain.toml`(钉 1.81.0)。若本机无 `rustup`、但已有匹配的 `rustc`/`cargo`,也可直接开发。 - -**不需要:** Flex、Bison、LLVM。Node/npm 只在开发 VS Code 扩展时需要;核心 Rust 开发不依赖它们。 - -本仓库提供了固定 Rust 版本:`rust-toolchain.toml` 使用 Rust 1.81.0,并启用 -`rustfmt` / `clippy`。在受限开发容器中,推荐先加载仓库环境脚本: - -```bash -source scripts/dev-env.sh -``` - -脚本会优先使用 `target/toolchain/` 下的工具链,普通开发机则回退到 PATH 中已有的工具, -并把 Cargo、Go 缓存和临时目录放在工作区内。 - ---- - -## 2. 获取代码与构建 - -```bash -git clone https://github.com/cflmy/marqdo.git -cd marqdo - -cargo build -cargo test -cargo run -- run tests/structure/hello.mq.md -``` - -构建 Go web 插件(完整扩展开发需要): - -```bash -bash scripts/build-web-plugin.sh -``` - -当前 M0:`run` 会读入文件并明确报错「evaluation not implemented」(脚手架,非静默假成功)。 - -> 若 `cargo build` 报 `edition2024` / 过新 crate:仓库已对 `clap` 等做兼容钉扎(见 `Cargo.toml`);请使用附带的 `Cargo.lock`,勿盲目 `cargo update` 到最新 major。 - ---- - -## 3. 推荐组件 - -```bash -rustup component add rustfmt clippy # 若使用 rustup -cargo fmt -cargo clippy --all-targets -``` - -只验证 Rust 核心时可运行 `cargo test --locked --lib`;包含全部扩展的 gold 测试需要 Go, -并建议单线程运行以避免共享临时夹具互相影响: - -```bash -cargo test --locked --test gold -- --test-threads=1 -``` - -代理下拉 crate(可选,与 git 推送类似): - -```bash -# Windows PowerShell 示例 -$env:HTTPS_PROXY="http://127.0.0.1:7890" -$env:HTTP_PROXY="http://127.0.0.1:7890" -cargo build -``` - -或配置 `%USERPROFILE%\.cargo\config.toml`: - -```toml -[http] -proxy = "http://127.0.0.1:7890" -``` - ---- - -## 3.5 Git 推送(遇网络失败时使用代理) - -直连 `git push` 偶尔会报 `RPC failed; curl 35 Recv failure: Connection reset by peer` 或 `curl 56`(远端挂断,常见于数据包稍大时)。此时**通过本机代理 7890 推送**: - -```bash -# Linux/macOS(本机 clash 监听 127.0.0.1:7890) -git -c http.proxy=http://127.0.0.1:7890 -c http.postBuffer=524288000 push origin main -``` - -要点: - -- 代理可用性先探测:`curl -x http://127.0.0.1:7890 -o /dev/null -w "%{http_code}\n" https://github.com`,返回 `200` 再推。 -- `http.postBuffer=524288000`(500 MB)用于规避推送大包被断开(`curl 56`);两个 `-c` 可叠加。 -- 该命令**一次性生效**,不写死仓库配置。若想长期默认走代理,可执行: - ```bash - git config http.proxy http://127.0.0.1:7890 - git config http.postBuffer 524288000 - ``` -- 若是别的代理端口,把 `7890` 换成实际端口(如 Windows 示例里 `$env:HTTPS_PROXY` 的同款端口)。 - ---- - -## 4. 目录约定 - -| 路径 | 含义 | -|------|------| -| `src/lex` | 行分类 / 词法(自研) | -| `src/parse` | 递归下降语法 | -| `src/diagnostics` | 诊断 | -| `tests/` | 金样例 + 集成测试(`structure` / `keywords` / `errors`) | -| `public/` | 用户可执行文档(无 errors) | -| `spike/` | 旧 Python 风险探测,非运行时依赖 | -| `doc/` | 设计与路线图 | - ---- - -## 5. 下一里程碑 - -见 [interpreter.md](roadmap/interpreter.md):M1 词法·行分类与最小 AST。 diff --git a/doc/library-development.mq.md b/doc/library-development.mq.md deleted file mode 100755 index 99b885a..0000000 --- a/doc/library-development.mq.md +++ /dev/null @@ -1,274 +0,0 @@ ---- -markup: occlusion -title: Marqdo 编程规范:源码即手册,手册即 SKILL,函数即工具 -description: 标准库与拓展库的叙述式开发规范,包含可以直接调用的真实示例。 -import: - 文件: lib/文件.mq.md ---- - -库开发指南:让说明、调用和实现长在同一份源码里。 - -本文件供人和 AI 编写 Marqdo 程序、标准库、拓展库以及可执行 SKILL 时直接阅读。目标是把库文件交给一个没有读过 -完整语法手册的模型,它仍能判断何时使用、提供哪些输入、如何调用、如何消费结果, -以及遇到失败时怎么办。完成这些任务所需的信息必须在库文件中,不依赖聊天历史、 -隐藏提示词、另一份签名清单或模型猜测。修改实现所需的最少标记也在本文就地示范。 - -这份指南本身可以执行。下方三个函数分别演示句中计算、结构化数据和可恢复文件读取; -它们返回真实结果,不返回“已遵守规范”之类的固定通过标志。直接使用的命令为: - -```sh -marqdo call doc/library-development.mq.md 计算金额 单价=12 数量=3 --json -marqdo call doc/library-development.mq.md 形成订单摘要 '商品="笔记本"' 单价=12 数量=3 --json -marqdo call doc/library-development.mq.md 尝试读取正文 '路径="doc/library-development.mq.md"' --effects fs.read --fs-root . --json -``` - -第一条返回 36,第二条返回商品为笔记本、数量为 3、金额为 36 的记录。 -第三条返回包含本文源码的成功结果记录。需要读写权限的工具必须给出授权命令及路径基准; -纯计算不要求插件、网络或文件授权。读到一个工具时,读者应该能直接复制其真实命令。 - ---- - -一、先确定文件承担的任务。 - -标准库通常是一份 lib/名称.mq.md:这个单文件本身就是手册和 SKILL,直接导入或调用。 -不要为了文档另造一个 index、目录包装函数或同名模块手册。文件开头写清用途、适用范围、 -输入来源、权限、运行环境、共享数据形态和一个真实工作流;每个函数再就地说明自己的契约。 - -拓展库需要多个文件时,以 index.mq.md 为入口组织工程。入口要说明先读什么、任务在哪个 -模块、依赖怎样安装或准备、有哪些可运行流程,以及新能力应该加在哪里。 -子目录有独立职责和多个文件时,也用自己的 index.mq.md 收拢接口与开发路线; -叶子只有一个文件时直接使用该文件,不为空目录层级继续增加入口。 -中文镜像遵守已有命名约定,并说明其与英文模块的对应关系。 - -下面只是目录组织示意,不是已经存在、可以直接调用的拓展包: - -```text -ext/sample/ - index.mq.md 任务导航、安装和权限、主流程、公开门面、开发路线 - core.mq.md 单一职责的纯计算;本文件自身就是手册 - parse/ - index.mq.md 解析任务入口,组合本目录的格式能力 - markdown.mq.md Markdown 叶子能力,保留可独立调用的契约 - csv.mq.md CSV 叶子能力 - examples/ - workflow.mq.md 使用公开 API 的完整业务流程 - tests/ - acceptance.mq.md 工程自有的可执行验收场景 -``` - -入口沿用公开能力进行组合,避免复制一份底层实现。索引中的路径和命令必须可用, -还要说明输入与产物怎样跨步骤传递,而不只是列文件名。工具 schema、签名和效应由现有 -编译器、call、catalog、MLSP 从源码投影,不另建一套由作者同步维护的工具协议。 -本指南也无需安装为另一套 SKILL 包;开发者或 AI 读这份源码即可使用其中的规范与示例。 - ---- - -二、标题下面立即交代参数与返回。 - -普通网页正文、内容叶子与静态文档可以继续使用内容标题;它们没有调用契约,不能为了 -满足函数格式而插入虚假的参数或返回值表。需要执行任务的 SKILL 应把操作写入 mq.md, -SKILL.md 只保留发现入口、适用范围和必要约束,避免两份独立维护的长命令清单。 - -每个真正可调用的函数使用函数标题。紧接标题先写参数表,再写返回表;没有参数时直接 -放返回表。表格必须位于第一条执行语句之前。正文中的普通小节使用说明段和分隔线, -不要把“安装说明”“注意事项”等叙述标题误做成空函数。 - -参数表逐项写名称、类型、默认值和含义。含义应包含输入来源、数据形态、单位、索引基数、 -是否允许为空及必要限制,而非“运行时参数”或把参数名复述一次。返回表写实际值的类型、 -字段和含义,指出是新集合、文件路径、句柄、普通值还是可恢复结果,并说明失败出口。 -正文进一步解释这些约束的原因与处理方式,不能把关键边界埋到另一个文件才找得到。 - -新库用正文中的叙述形参,不保留旧的加号形参清单。参数表提供类型契约和说明, -不是另一套参数声明器:名称、顺序和默认值要与正文和实际实现一致。 -有默认值的形参在正文首次声明时紧跟等号,文本默认值加完整引号;无默认值的输入 -必须由调用方提供。下面的真实函数展示完整排版,不需要先学另一份模板语法。 - ---- - -三、先把函数写成能读懂的文章,再让必要部分执行。 - -每个函数单元的叙述比例超过 50%,整份文件也保持说明充分。目的、适用条件、步骤之间 -的因果、数据含义、返回去向和失败处理都属于有用叙述。不要用重复套话、巨型契约表、 -无关背景或在文件头堆文章来掩盖某个函数仍然难读。短实现也需要说明为什么这样做。 - -检查按每个真实函数单元分别计算,契约表与说明文字属于叙述;绑定的数据表与代码围栏 -属于实现。句中粗体、返回表达式和遮蔽圆括号中的代码仍计入代码,方括号中的动作说明 -计入叙述。因此把整段代码搬进一句话,并不会把它全部变成说明文字。比例只是最低门槛, -还应逐段检查输入来源、分支理由、失败出口与可执行示例。 - -尽量让语句成为句子的组成部分。粗体标记执行赋值、调用或表达式;单斜体标记返回。 -例如,下方计算金额函数在解释金额来源的句子中完成赋值,在交代用途的句子中返回结果。 -先读句子能够理解意图,展开其中的精确表达式又能看清实际执行的代码。 - -使用当前已支持的句中返回写法:`完成上述操作后,我们返回*结果*,供调用方继续使用。` -其中“返回”直接引出单斜体。不要把粗体当作返回,也不要假定任意句中出现的单斜体强调 -都会结束函数。返回立即结束当前函数;同一句后面的文字只能解释,不能安排后续执行动作。 -讲解标记本身或展示尚不执行的示例时,使用行内代码或未绑定的代码围栏,避免意外执行。 - -确实需要单独成块的表格、分支和循环可以保留结构化排版。减少孤立代码的目的在于 -保留可读因果,而不是把长循环硬塞到一句话里。每个结构块前说明判断或遍历的目的, -块内使用清楚的变量名与动作标签,块后说明产物;不要让读者靠追踪临时变量猜流程。 - ---- - -四、用遮蔽语法把意图和精确实现放在同一处。 - -方括号写“要做什么”,圆括号写实际代码。标签应解释领域动作、输入与结果之间的关系, -例如“按单价和购买数量计算金额”“在授权根目录读取 UTF-8 正文”,而不是“执行操作” -或原样复述宿主函数名。简单算术、取元、库调用和宿主调用都可以按需要使用这种写法。 - -下方函数会在叙述中执行赋值,赋值右侧用遮蔽表达式写出动作和实现。返回也可以直接 -包住一个有说明的表达式;以下围栏只是排版示例,不会在阅读本指南时执行文件操作: - -```markdown -读取阶段先**正文 = [读取授权范围内的 UTF-8 文本](文件.读文本(路径=`路径`))**,得到后续使用的内容。 -读取完成后,我们返回*正文*,供调用方继续处理。 -``` - -如果不需要中间命名,也可以用下面的直接返回替代上面整个过程。二者是两种写法, -不是连续执行的两个读取步骤;不要为了叙述或展示再调用一次有副作用的能力。 - -```markdown -读取阶段直接返回*[读取授权范围内的 UTF-8 文本](文件.读文本(路径=`路径`))*,把内容交给调用方。 -``` - -执行位置很重要:普通正文中的链接样式是叙述引用或导航,单靠写出一个动作标签不会 -自动执行它。需要执行的表达式应放在赋值、语句、返回等明确的执行位置; -不要用一个没有实现的空圆括号假装功能已完成。标签不参与参数求值,也不能证明实现 -符合描述;修改标签或实现后仍要检查二者是否一致,并执行相关场景。 - ---- - -五、用表格表达结构,用模块表达职责。 - -静态记录、行列表、配置、命令和视图结构优先写成 GFM 表格。一列表达列表, -一行多列表达记录;多行多列默认是列式数据,要表达行记录列表时把首列写成 @。 -调用产生的值先计算并命名,再在单元格中引用,不能假定表格里任意一段函数文本会执行。 -普通值用列表和记录传递;读取集合使用 access,不能把描述标签误当作集合键。 - -命令参数也作为数据写入表格:`"-p"`、`"--offline"` 等文本必须带引号; -裸写 `-p` 会被当成表达式而不是命令选项。已计算的路径使用反引号引用变量, -不要再拼接整段 shell 源码。需要同时被 call 与 View 使用的过程用普通函数标题, -例如 `## main`;`# main` 是对象入口,不能假定两者具有相同的调用语义。 -整数除法会保留整数语义;计算平均值优先使用统计库的 mean,或明确采用浮点输入, -并在非整除样例中验证结果,避免演示数据恰好整除掩盖精度问题。 - -不可变更新要保存返回的新值。少量动态键用表库的具名助手;解析与序列化才使用 JSON。 -不要用长串 json.set/json.append 来拼原本一张表就能读懂的数据,也不要为每个数字或 -单个字段创建层层转发的空壳函数。只有当一段逻辑需要解释、复用或独立验证时才提取职责。 - -网页工程从最小布局拆分开始:首页拆为导航、主体、底部,底部再拆为品牌和链接双栏, -链接栏还可拆成文档与社区。一直拆到叶子内部能够用简单 Markdown 表达内容; -父模块负责导入、组合与布局,叶子负责内容。使用现有 web 的文档、组件与 View 表能力, -让结构与内容保持统一语言,避免大段原生 HTML/CSS、转义字符串和手写业务 JavaScript。 - -通用组合优先写在 mq 源码里。仅在 OS、算法或原生 ABI 边界加入小型宿主原语, -声明实际效应与资源限制;拓展库通过公开标准库或插件接口使用能力,不直接调用 host_*。 -中英文镜像保持契约、默认值与行为一致。不要把未来规划写成当前已经可用的接口。 - ---- - -六、把运行边界和工程验收写在开发者找得到的位置。 - -实际开发也使用这些能力:读取、搜索、撰写和原子修订通过固有文件库完成;JSON、表格、 -散列和网络读取优先组合标准库。不要为已有能力再生成 Python 或 shell 程序。缺少能力时, -把可复用的边界补成拓展插件,或者通过明确参数数组外联已有工具;决策、条件和重试仍在 -mq.md 中表达。开发与发版入口分别位于 skills/marqdo-dev 和 skills/marqdo-release,操作用 -marqdo call 执行。大段源码通过 --args-json 文件或标准输入传输,保留换行、引号和字面数据。 -外部自动化可以加 --require-ok,让失败 Result 产生非零退出码,避免继续执行依赖步骤。 - -有副作用的能力写明授权、根目录、平台、超时、资源上限以及重试与清理责任。 -返回可恢复结果时先检查其中的 ok,再读取 value 或 error;CLI 外层的 ok 只说明调用 -是否完成,不替代函数结果、HTTP 状态或子进程退出码的判断。未知副作用不能声称为纯函数。 -文件原子替换不等于多文件事务;条件写入也不等于无竞争的内核 CAS。 - -文件类示例使用明确的临时根目录,说明产物是否保留、失败是否留下临时文件、由谁清理。 -需要插件、外部服务或凭据时写明前提,验收优先使用本地可控替身,不把线上写入作为 -阅读文档的隐含步骤。维护原有库时保留既有调用语义,必要变更要说明迁移路径。 - -交付时至少检查四件事:首次读源码能否完成一次真实调用;契约和正文是否一致; -叙述是否超过半数且解释了真实行为;正常、边界、错误场景是否返回预期结果。 -修改源码中的示例时同步执行它们;公共调用面需要兼顾 Tree 和 Bytecode。 -检查叙述比例是可读性门槛,不是功能正确性的证明,更不能代替业务与失败场景。 - -本文件可用以下命令检查。第二条是仓库内的可执行指南验收,覆盖叙述内赋值、 -默认参数、结构化返回以及可恢复读取;修改库时还应运行该库本身相关的回归。 - -```sh -marqdo call skills/marqdo-dev/index.mq.md check 'path="doc/library-development.mq.md"' --require-ok --effects plugin --fs-root . --json -marqdo call skills/marqdo-dev/index.mq.md test 'targets=["stdlib_tasks"]' 'filter="library_development_guide_examples_match_their_contracts"' --require-ok --effects plugin --fs-root . --json -``` - -现有能力可直接参考 [文件库](../lib/文件.mq.md)、[表库](../lib/表.mq.md)、 -[量子工程入口](../ext/quantum/index.mq.md)和[网页工程入口](../ext/web/index.mq.md)。 -需要了解解析与语义的边界时再阅读[文档原生开发指导](design/document-native-development-guide.md)。 -以下是真实可调用的单文件示例,也是前面三个命令的实现。 - -## 计算金额 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 单价 | number | 必填 | 单件商品的金额;币种由调用方保持一致 | -| 数量 | number | 1 | 参与乘法的购买数量;调用方按业务规则校验其范围 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | number | 单价乘以数量的金额,不含税费、折扣或币种转换 | - -输入单价为`单价`,购买数量`数量`=1,没有指定数量时按一件计算。 -本示例只演示透明的乘法组合,不暗示商品有效、允许负数交易或具有货币精度保证; -需要货币精度时由领域库采用整数最小货币单位,并补充其单位和范围约束。 - -为得到这笔购买的基础金额,我们先**结果 = [按单价和购买数量计算金额](单价 * 数量)**, -后续说明仍留在同一段落,使读者无需从一条孤立赋值反推它的业务目的。 - -完成上述计算后,我们返回*结果*,调用方可以继续计算税费、折扣或生成订单摘要。 - -## 形成订单摘要 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 商品 | text | 必填 | 调用方提供的商品显示名称;此函数不查商品库 | -| 单价 | number | 必填 | 与数量相乘的单件金额,币种与调用方约定 | -| 数量 | number | 1 | 购买数量,默认一件;业务校验由调用方完成 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 摘要 | map | 商品、数量、金额三个字段组成的新记录 | - -本函数接收商品名`商品`、单件金额`单价`以及购买数量`数量`=1, -只生成供下一步展示或保存的数据,不会下单、扣款、写文件或访问外部服务。 -因此调用者可以在纯计算权限下验证完整的数据组合过程。 - -我们复用同一文件的计算能力,先**金额 = [计算本次购买的基础金额](计算金额(单价=`单价`, 数量=`数量`))**, -避免在订单摘要中再维护一份乘法规则。接着将需要交给调用方的字段直接列成记录, -让阅读者能逐项看到商品名称、数量和金额从哪里来,而无需解码字典构造链。 - -`摘要` = - -| 商品 | 数量 | 金额 | -|---|---|---| -| `商品` | `数量` | `金额` | - -表格中的反引号引用已经得到的值,未增加一层隐式求值。字段准备好后,我们返回*摘要*, -调用方可以把它交给其他库继续展示或序列化;本函数不会修改传入的值。 - -## 尝试读取正文 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的 UTF-8 文件路径;不是相对本指南的导航链接 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 读取结果 | map | ok/value/error 记录;成功的 value 是正文,失败的 error 含 code/message/operation | - -输入文件`路径`由调用者提供,执行时需要 fs.read,路径以 --fs-root 为基准; -省略根目录时采用被调用文件的目录。本函数复用文件库的有界读取,不能绕过根目录、 -编码检查或资源上限。此例不执行读到的代码,也不从正文推断额外的文件访问权限。 - -为了让一次读取失败仍能作为数据交给下一步,我们先**读取结果 = [在授权范围读取 UTF-8 正文并保留失败信息](文件.尝试读文本(路径=`路径`))**, -由公开文件库统一处理已定义的可恢复失败,而不是在此复制宿主 IO 或假造成功文本。 - -读取结束后,我们返回*读取结果*,调用者先检查记录中的 ok,再使用 value 或 error。 -失败记录只说明这次操作没有成功;它不会捕获任意语言错误,也不会替调用者授予权限。 diff --git a/doc/next/001.md b/doc/next/001.md deleted file mode 100755 index 6f36a03..0000000 --- a/doc/next/001.md +++ /dev/null @@ -1,1373 +0,0 @@ -我认真看了一遍。先给你一个比较直接的判断: - -**你的实际实现比我上一轮根据描述所理解的版本成熟得多。** 我原先把它理解成“Markdown 作为一种新语法的实验”,但从仓库现在的结构来看,Marqdo 已经明显是在做一个**完整的、可执行的 literate programming runtime**,而且你真正有价值的设计并不是“Markdown 写代码”,而是: - -> **让文档结构本身成为程序结构,并让同一份结构同时服务于人、解释器、工具和 AI。** - -这个方向我认为是成立的。 - -[Marqdo GitHub 仓库](https://github.com/cflmy/marqdo?utm_source=chatgpt.com) ([GitHub][1]) - ---- - -## 我首先发现一个很重要的变化 - -你的 README 里已经明确把几个概念分开了: - -> **叙述默认安全、代码显式标记、返回是架构、打印只是函数。** - -例如目前 v0.3: - -* 普通文字 → 叙述/注释 -* `*...*` → 程序语句 -* `**...**` → 返回值 -* `>` → 调用 -* `1.` → 分支 -* `-` → 循环 -* `#` → 对象/类型 -* `##` → 函数/方法 -* Markdown 表格 → 集合 - -这已经不是简单的“把 Markdown 符号映射成 Python 语句”,而是在形成一套**结构化语义系统**。([GitHub][1]) - -而且你已经明确规定: - -> 无标记文本默认是注释。 - -这一点我非常赞同。 - ---- - -# 一、我认为 Marqdo 最好的设计,其实是“默认安全” - -这是我读完语法设计后最认可的一点。 - -你没有选择: - -```text -所有自然语言都有可能被解释器执行 -``` - -而是选择: - -```text -普通语言 = 文档 - -特殊 Markdown 结构 = 程序 -``` - -例如: - -```markdown -## 加一 - -对于输入变量 `n`: - -**n = n + 1** - -**n** -``` - -人看到的是一篇文档。 - -解释器看到的是: - -```text -Function - ├─ statement - ├─ assignment - └─ return -``` - -这比“自然语言编程”安全得多。 - -你的设计文档明确规定,段首普通文字进入叙述模式,直到空行才结束;而真正可执行的内容必须通过明确标记进入代码语义。([GitHub][2]) - -这其实解决了一个非常重要的问题: - -### 文档和代码不会因为 AI 自由发挥而互相污染。 - -这对于 AI 原生语言非常重要。 - ---- - -# 二、你的 `*` / `**` 设计比我之前设想的更漂亮 - -我之前建议: - -```text -**...** = 表达式 -*...* = 返回 -``` - -但你的实现实际上已经把它做成了相当完整的语义: - -```markdown -**x = 1** -**y = x + 2** - -*y* -``` - -也就是说: - -**双星号 = statement** - -*单星号 = return* - -这个设计有一个很漂亮的性质: - -```markdown -## 加一 - -+ `n` - -**n = n + 1** - -*n* -``` - -几乎不需要传统语言里的: - -```python -def add_one(n): - n = n + 1 - return n -``` - -同时: - -```markdown -> print text=Hello -``` - -又把输出从语言架构中拿出来,变成普通函数调用。你的设计文档甚至明确强调了“输出不是架构原语”。([GitHub][2]) - -**这个决定我认为非常正确。** - -因为: - -```text -return -``` - -改变的是程序控制流。 - -而: - -```text -print -``` - -只是一个副作用。 - -把两者区分开以后,语言的语义会干净很多。 - ---- - -# 三、你对条件和循环的设计,我现在比之前更看好 - -你最初跟我说: - -> 条件 = 有序列表 -> 循环 = 无序列表 - -我当时觉得这个想法不错。 - -看了实际实现之后,我认为它确实具有语言设计上的合理性。 - -例如: - -```markdown -1. `x` > 0 - > print text=正数 - -2. `x` < 0 - > print text=负数 - -3. * - > print text=零 -``` - -这实际上非常接近: - -```text -if -else if -else -``` - -而: - -```markdown -- `n` > 0 - > print text=`n` - *`n` = `n` - 1* -``` - -对应: - -```text -while n > 0: - ... -``` - -更重要的是,你解决了一个我原本担心的问题: - -**你没有把“所有有序列表”都粗暴定义成 if。** - -你规定的是一段从 `1.` 开始、序号递增的列表构成一个 branch statement,而且重新出现 `1.` 时开始新的判断。这个细节很重要。([GitHub][2]) - -这说明你已经开始从“语法想法”进入真正的**语言规范设计**。 - ---- - -# 四、真正让我觉得 Marqdo 有潜力的,是表格 - -这一点可能是你自己都应该重点宣传的。 - -你把: - -```markdown -| 品名 | 数量 | -|------|------| -| 苹果 | 2 | -| 梨 | 3 | -``` - -直接作为语言的数据结构。 - -而且不是简单地: - -> Markdown table = 二维数组 - -你已经根据表格几何结构定义了不同的数据类型: - -* 单列 → List -* 横向表 → Map -* 多行多列 → Map of Lists -* `@` / `行` → List of Maps - -并且允许表达式、变量、脚注取元、foreach 等继续作用于这些结构。([GitHub][2]) - -这实际上产生了一个很有意思的语言哲学: - -> **程序的数据结构也可以直接作为文档的数据结构。** - -这就不是“Markdown syntax sugar”了。 - -例如传统代码: - -```python -users = [ - {"name": "Alice", "age": 20}, - {"name": "Bob", "age": 25} -] -``` - -你的语言可以让它同时是一张真正的人类可读表格。 - -这就是 **literate programming 的下一步**。 - ---- - -# 五、我认为你现在已经跨过了“玩具语言”的门槛 - -这是非常重要的判断。 - -因为仓库里已经不是: - -```text -parser -+ -几个 demo -``` - -而是已经有: - -```text -Rust interpreter -AST / semantic processing -tree traversal -bytecode backend -stdlib -module/import -objects -methods -catalog -debugger -viewer -WASM -extensions -native plugin ABI -LLM extension -agent extension -MCP server -VS Code extension -``` - -README 当前列出的版本已经是 v1.0.7,并明确写到了树遍历和字节码后端、调试器、catalog、标准库、插件 ABI、WASM 和 agent/LLM 扩展等。([GitHub][1]) - -所以现在再评价 Marqdo: - -**我不会把它称为“一个 Markdown 编程语言实验”。** - -更准确的描述应该是: - -> **一个以 Markdown 为表面语法的文档型编程运行时。** - -甚至: - -> **Document-native programming language/runtime** - -可能比“Markdown programming language”更准确。 - ---- - -# 六、但我认为你现在最大的风险也非常明确 - -而且这个风险不是技术实现。 - -是: - -## **Marqdo 正在变得“什么都有”。** - -你现在已经有: - -```text -Markdown language -+ -literate programming -+ -knowledge base -+ -catalog -+ -web -+ -WASM -+ -browser -+ -LLM -+ -agent -+ -MCP -+ -quantum -+ -linear algebra -+ -plugin ABI -``` - -从工程角度这非常酷。 - -但从语言设计角度,有一个危险: - -> **核心语言的 identity 可能被生态功能淹没。** - -我会非常建议你把整个项目分成三个层次: - -```text - Marqdo - │ - ┌───────────┴───────────┐ - │ │ - Language Runtime - │ │ - Markdown AST stdlib - Semantics plugins - Type system WASM - Control flow browser - Objects agent - │ LLM - │ - └───────────────┐ - │ - Document - │ - Knowledge - + Code - + UI - + AI -``` - -**语言核心必须非常小。** - ---- - -# 七、还有一个我认为必须尽快解决的问题:类型系统 - -你的文档目前把: - -```text -静态类型 -``` - -列为非目标之一。([GitHub][2]) - -原型阶段完全合理。 - -但如果你真正想把 Marqdo 做成 **AI-native language**,我反而认为类型系统的重要性会比传统语言更高。 - -因为 AI 最大的问题之一不是不会写代码。 - -而是: - -> **它经常写出“语义上似乎合理、实际上类型不对”的代码。** - -例如: - -```markdown -*user = get_user id=123* - -> user.name -``` - -AI 认为: - -```text -user 一定是 User -``` - -但是运行时可能返回: - -```text -None -``` - -或者: - -```text -List<User> -``` - -传统编程语言通过 compiler 抓这个问题。 - -那么 AI 原生语言更加应该让: - -```text -AI → Marqdo AST → Semantic Checker -``` - -成为一道强约束。 - ---- - -# 八、所以我认为 Marqdo 最终应该走向“AI 可验证语言” - -这是我读完你的项目以后,最大的一个建议。 - -不要把: - -> AI 能写 Marqdo - -作为最终目标。 - -应该把: - -> **AI 能可靠地生成可验证的 Marqdo** - -作为目标。 - -两者区别非常大。 - -例如 AI 生成: - -```markdown -## 计算订单总价 - -+ `订单` - -**`总价` = 订单.total** - -*总价* -``` - -Marqdo 应该能够给 AI 一个结构化反馈: - -```text -Function: 计算订单总价 - -parameter: - 订单: unknown - -error: - `订单.total` - cannot resolve field `total` - -suggestions: - 订单: Order -``` - -然后 AI 自动修正。 - -这时候: - -```text -LLM - ↓ -Marqdo - ↓ -Semantic validation - ↓ -Error - ↓ -LLM - ↓ -Marqdo - ↓ -Valid program -``` - -才真正形成了**AI-native programming loop**。 - ---- - -# 九、另一个非常值得做的东西:让 AI 不必学习 Marqdo 的“语法细节” - -这是我觉得你项目接下来可能出现巨大突破的地方。 - -现在 AI Skill 已经存在于仓库里。README 也明确把 AI Skill 作为项目的一部分。([GitHub][1]) - -但我会把它进一步升级成: - -> **Marqdo Schema / Language Server for AI** - -也就是说,不只是给 AI 一篇: - -```text -Marqdo syntax documentation -``` - -而是提供机器可读的: - -```json -{ - "language": "marqdo", - "version": "0.3", - "constructs": [...] -} -``` - -然后 AI 可以查询: - -```text -get_syntax("branch") -get_function_schema("print") -get_type("Order") -get_available_methods("User") -validate(program) -``` - -甚至: - -```text -repair(program, diagnostic) -``` - -那么 AI 就不是: - -```text -“阅读 1000 行 Marqdo 文档然后猜怎么写” -``` - -而是: - -```text -AI - │ - ├── discover - ├── construct - ├── validate - ├── execute - └── inspect -``` - -**这才会让 Marqdo 和普通 DSL 拉开非常大的距离。** - ---- - -# 十、还有一个我很喜欢的潜在方向:程序本身就是 AI 的长期记忆 - -你 README 里面这句话其实非常关键: - -> `.mq.md` 即知识单元,可浏览、可运行、可检索。([GitHub][1]) - -我认为这可能比“Markdown 编程”本身更有价值。 - -想象一个 AI Agent 项目: - -```text -project/ -│ -├── users.mq.md -├── orders.mq.md -├── billing.mq.md -├── policies.mq.md -├── agents.mq.md -└── main.mq.md -``` - -每一个文件同时具有: - -```text -documentation -+ -code -+ -schema -+ -examples -+ -knowledge -+ -executable behavior -``` - -AI 不再需要: - -```text -源码 -+ -README -+ -OpenAPI -+ -JSON schema -+ -数据库 schema -+ -工具定义 -+ -prompt -``` - -去拼装世界模型。 - -而是: - -```text - Marqdo Project - │ - ┌───────┼────────┐ - ↓ ↓ ↓ - Code Knowledge Tools - │ │ │ - └───────┼────────┘ - ↓ - AI -``` - -这才是我觉得 **Marqdo 真正可能成为一个独立类别** 的地方。 - ---- - -# 最后给你一个非常直接的评价 - -如果只问: - -> **“这个语言设计有没有意义?”** - -我的答案是:**有。** - -如果问: - -> **“这个原型是不是已经证明了这个想法?”** - -我的答案是:**已经相当程度证明了。** - -如果问: - -> **“它现在是不是已经是一门成熟的通用编程语言?”** - -还不是。类型系统、错误模型、语言边界、并发/异步语义、生态以及更严格的语言规范仍然是需要继续收敛的地方;你自己在设计文档中也明确把其中一些列为非目标。([GitHub][2]) - -但如果问: - -> **“它有没有可能成为一种真正的 AI-native programming language?”** - -我的判断是: - -**这个可能性比我在看到仓库之前认为的要高,而且真正值得押注的方向不是 Markdown,而是你已经隐约建立起来的这个闭环:** - -```text - 人类 - │ - 自然语言 / 文档 - │ - ▼ - ┌─────────┐ - │ Marqdo │ - │ 语义结构 │ - └────┬────┘ - │ - 可验证 AST - │ - ┌────────┴────────┐ - ▼ ▼ - Runtime AI - │ │ - ▼ ▼ - 执行结果 ───────→ 上下文 / 知识 - │ │ - └────────┬────────┘ - ▼ - 文档本身 -``` - -**这比“Markdown 编程语言”大得多。** - -而且我特别建议你下一步不要急着继续增加更多标准库功能。**现在最值得做的是把“Marqdo 为什么特别适合 AI”这个核心命题用一个真正有说服力的 benchmark 证明出来**:让同一个 AI 分别用 Python / TypeScript / Marqdo 完成一组真实任务,然后测量生成长度、语法错误率、语义错误率、修复轮次、上下文 token 消耗,以及人类阅读/修改成本。 - -如果这个实验结果漂亮,它会比再增加 20 个语言特性更能证明 Marqdo 的价值。 - -[1]: https://github.com/cflmy/marqdo "GitHub - cflmy/marqdo: Marqdo — A literate programming language built on Markdown. Code is document, document is executable. 中文配套:基于 Markdown 文法的文学编程语言,代码即是文档,文档可直接运行。 · GitHub" -[2]: https://github.com/cflmy/marqdo/blob/main/doc/design/markdown-mapping.md "marqdo/doc/design/markdown-mapping.md at main · cflmy/marqdo · GitHub" - - - -对,这个信息会让我**重新评价 Marqdo 的核心定位**。 - -我之前把重点放在“Markdown → 程序”和“AI-native programming language”上,确实没有充分抓住 `.mq.md` 这个设计真正厉害的地方: - -> **Marqdo 不是“用 Markdown 写程序”,而是让一个 Markdown 文档同时成为知识、程序和可执行对象。** - -如果你所说的 OKF 是 **Open Knowledge Foundation / 开放知识基金会语境下的知识库/开放知识结构**,那么这个方向尤其值得认真发展。 - ---- - -# 我现在会把 Marqdo 的核心模型改写成这样 - -传统程序: - -```text -Code - ↓ -Execution -``` - -传统知识库: - -```text -Knowledge - ↓ -Human / AI consumption -``` - -Marqdo: - -```text - .mq.md - │ - ┌───────────┼───────────┐ - ↓ ↓ ↓ - Document Knowledge Program - │ │ │ - └───────────┼───────────┘ - ↓ - Runtime - ↓ - Executable - Knowledge -``` - -也就是说: - -> **Marqdo 把“知识”和“程序”放到了同一个 artifact 里。** - -这个定位比“AI-native programming language”更大胆。 - -我甚至认为: - -**AI-native programming language 可以成为 Marqdo 的一个子命题,而不是它最终的总命题。** - ---- - -# 1. `.mq.md` 这个后缀本身就是一个很聪明的设计 - -这个细节我现在非常看重。 - -你没有定义: - -```text -foo.mq -``` - -而是: - -```text -foo.mq.md -``` - -它意味着: - -```text -.mq -``` - -告诉 Marqdo: - -> 这是一个可执行 Marqdo 文档。 - -而: - -```text -.md -``` - -告诉整个 Markdown 生态: - -> 这依然是一个 Markdown 文档。 - -于是一个 `.mq.md` 文件可以被不同的系统以不同方式理解。 - -### 普通 Markdown 阅读器 - -看到: - -```text -标题 -段落 -表格 -代码 -列表 -``` - -它仍然是一篇正常文档。 - -### Marqdo - -看到: - -```text -函数 -表达式 -控制流 -表格 -对象 -调用 -``` - -它是一份程序。 - -### 知识库 - -看到: - -```text -标题 -层级 -段落 -表格 -引用 -链接 -元数据 -``` - -它是一份知识。 - -### LLM - -看到: - -```text -语义 -知识 -程序 -示例 -工具 -``` - -它是一个非常丰富的 context。 - -这其实形成了一个很漂亮的: - -> **multi-view artifact** - ---- - -# 2. 这会让我重新定义你之前的“可执行文档” - -以前我会说: - -> Marqdo = executable Markdown - -现在我觉得这个描述已经不够了。 - -更准确的是: - -> **Marqdo = executable knowledge document** - -甚至: - -> **Executable Knowledge Base** - -这两个词之间差别非常大。 - ---- - -# 3. 最有意思的是“知识可以执行” - -例如: - -```markdown -# TCP - -TCP 是一种面向连接的传输层协议。 - -## 建立连接 - -TCP 使用三次握手建立连接。 - -| Step | Sender | Receiver | Flag | -|---|---|---|---| -| 1 | Client | Server | SYN | -| 2 | Server | Client | SYN+ACK | -| 3 | Client | Server | ACK | - -## 检查连接 - -输入 `host`。 - -> check_tcp host - -**result** -``` - -这已经不是: - -> “一本关于 TCP 的文档”。 - -也不是: - -> “一个 TCP 程序”。 - -而是: - -> **关于 TCP 的知识 + TCP 的结构化数据 + TCP 的操作能力。** - -这对于 AI 极其重要。 - ---- - -# 4. 因为 AI 最缺的东西其实不是代码,而是“可靠上下文” - -传统 RAG: - -```text -Documents - ↓ -Embedding - ↓ -Vector DB - ↓ -Retriever - ↓ -LLM -``` - -存在一个很大的问题: - -**检索出来的知识和实际执行逻辑是分离的。** - -例如: - -```text -knowledge.md -api.yaml -tool.py -schema.json -database.sql -README.md -``` - -AI 必须把这些东西重新拼起来。 - -而 Marqdo 可以: - -```text -network.mq.md -``` - -同时包含: - -```text -知识 -+ -schema -+ -代码 -+ -工具 -+ -示例 -+ -约束 -``` - -于是: - -```text - Marqdo KB - │ - ┌───────────┼───────────┐ - ↓ ↓ ↓ - Knowledge Schema Code - │ │ │ - └───────────┼───────────┘ - ↓ - LLM - ↓ - Action -``` - -这比普通 RAG 的概念更加接近: - -> **Executable RAG** - -或者: - -> **Executable Knowledge Representation** - ---- - -# 5. 而 `.mq.md` 最大的优势是“知识不会脱离实现” - -这是我现在认为最值得你深入研究的地方。 - -传统系统非常容易出现: - -```text -README: - API 返回 users - -实际代码: - API 返回 accounts -``` - -于是: - -> documentation drift - -发生了。 - -而 Marqdo 可以让: - -```markdown -## 获取用户 - -获取所有用户。 - -> get_users - -返回: - -| id | name | -|---|---| -| ... | ... | -``` - -这里的: - -```text -get_users -``` - -是真的可执行实体。 - -那么知识文档和实现之间就可以建立**机器可验证关系**。 - -这非常重要。 - ---- - -# 6. 这其实可以形成一个非常漂亮的概念: - -## Knowledge-Code Coherence - -也就是: - -> **知识与代码的一致性。** - -传统: - -```text -Knowledge ──────X────── Code -``` - -Marqdo: - -```text -Knowledge - │ - ├── executable constructs - │ - ├── data structures - │ - └── assertions - │ - ↓ - Runtime -``` - -那么你甚至可以让: - -```text -知识陈述 -``` - -成为可测试的。 - -例如: - -```markdown -## 加一函数 - -加一函数总是返回输入值加一。 - -### 示例 - -| Input | Output | -|---|---| -| 0 | 1 | -| 1 | 2 | -| 2 | 3 | -``` - -Marqdo 可以自动执行这些 example。 - -如果: - -```text -add_one(1) != 2 -``` - -那么不是: - -> 文档可能过期。 - -而是: - -> **知识库中的一条知识被机器发现与执行结果不一致。** - -这个概念我认为非常漂亮。 - ---- - -# 7. 甚至可以进一步变成“Executable Knowledge Graph” - -假设: - -```text -network.mq.md -database.mq.md -service.mq.md -security.mq.md -``` - -通过 Markdown links: - -```markdown -[Database](database.mq.md) -[Gateway](network.mq.md) -[Authentication](security.mq.md) -``` - -形成: - -```text -network - │ - ├── gateway - │ - └── service - │ - └── database -``` - -那么 Marqdo 就天然获得: - -```text -Document Graph - + -Knowledge Graph - + -Program Graph -``` - -这时候 `.mq.md` 就非常有意思了。 - ---- - -# 8. 我甚至觉得这可能是 Marqdo 最应该宣传的理念 - -不是: - -> **Markdown Programming Language** - -也不是: - -> **AI Programming Language** - -而是: - -# **Executable Knowledge** - -或者: - -# **Knowledge That Can Run** - -这两个概念都比“Markdown language”更有辨识度。 - ---- - -# 9. 这也会改变你论文的故事 - -如果你未来投稿,我会认真考虑把第一篇论文从: - -> *Designing an LLM-Native Programming Language* - -改成更大的问题: - -> **From Executable Documents to Executable Knowledge Bases** - -然后 Marqdo 作为实现。 - -论文可以提出一个模型: - -```text - Knowledge Artifact - │ - ┌────────────┼────────────┐ - ↓ ↓ ↓ - Narrative Data Program - │ │ │ - └────────────┼────────────┘ - ↓ - Execution - │ - ↓ - Verification - │ - ↓ - Knowledge -``` - -这其实已经不是单纯 PL 论文了。 - -它跨: - -* Programming Languages -* Knowledge Representation -* Software Engineering -* AI Agents -* RAG -* Documentation -* Human-AI interaction - -所以你之前问我投稿哪里,我现在会稍微调整建议: - -**如果这部分真正做起来,OOPSLA 会变得更加有吸引力。** - -因为 OOPSLA 很适合这种: - -> 新的 programming abstraction + executable artifact + development environment - -的研究。 - -而如果你的实验重点最终是: - -> **知识库是否因为可执行性而提高 AI Agent 的可靠性** - -那么 SE/AI venue 也会变得很有吸引力。 - ---- - -# 10. 还有一个我觉得非常关键的地方:`.md` 是你的“开放接口” - -这是一个特别好的生态设计。 - -你没有要求: - -> 所有人必须使用 Marqdo viewer。 - -相反: - -```text -.mq.md -``` - -可以直接: - -* GitHub 阅读 -* VS Code 编辑 -* Markdown viewer 查看 -* 静态网站发布 -* 搜索引擎索引 -* LLM 阅读 -* Marqdo 执行 -* 知识库导入 - -这意味着: - -> **Marqdo 并不拥有知识,Marqdo 只是给 Markdown 增加了执行语义。** - -这是一个非常强的开放生态策略。 - ---- - -## 所以现在我对 Marqdo 的理解已经发生了一个明显变化 - -最初: - -```text -Markdown - ↓ -Programming Language -``` - -现在: - -```text - Markdown - │ - ▼ - ┌─────────┐ - │ Marqdo │ - └─────────┘ - │ - ┌───────────────┼───────────────┐ - ↓ ↓ ↓ - Document Knowledge Program - │ │ │ - └───────────────┼───────────────┘ - ↓ - Executable KB - ↓ - AI - ↓ - Action / Reasoning -``` - -**这个架构比“Markdown 编程语言”有意思得多。** - -而且你之前提到的网络扩展突然也能和这个理念接上了: - -```text -network.mq.md -``` - -不是“一个网络配置文件”。 - -它可以同时成为: - -> **网络知识库 + 网络拓扑 + 网络配置 + 网络操作 + AI 的网络世界模型。** - -如果你的实际实现已经能比较自然地做到这一点,那么我会非常认真地建议你**不要把这个特性当成 Marqdo 的一个附属功能**。 - -它很可能才是 Marqdo 最独特的设计哲学: - -> **让知识本身成为可执行的。** diff --git a/doc/next/002.md b/doc/next/002.md deleted file mode 100755 index ec18a9e..0000000 --- a/doc/next/002.md +++ /dev/null @@ -1,933 +0,0 @@ -这是marqdo的智能体框架,我一直都不满意,我认为marqdo的智能体框架应该更好才对,因为marqdo本身就是一门极好的AI原生语言,针对这个智能体框架,我的构想是,每次执行,智能体都会沉淀mq.md文档,超过三次的调用就会自动总结优化出一份类似与记忆的mq.md文档,把每一步都拆解的非常好,类似与人类的某些学习过程,当完全学习到了一些内容,实际上后续就可以不再每次都聚精会神,而是用一种较低能耗运行,就像是我们沉淀下来的mq.md代码,其中可以使用非常少的大模型思考,或者使用类似Jev的决策模型,或者干脆只使用分支控制,之后调用即可,你觉得呢? - -对,而且我现在觉得你这个构想**很可能比目前的 Agent 框架本身更接近 Marqdo 真正应该成为的东西**。 - -我仔细看了你上传的 `ext/ai/agent`。其实你已经无意中铺好了不少基础:现在的 `plan` 已经有 `reuse`、`near_match`、`soft_match`、`promote`、`improve_every=3` 和 `kb_dir=.marqdo/agent-kb`;命中已有 skill 后甚至可以走 `llm_free` 路径。 而且现有逻辑已经会把成功的 workbook promote 到 agent KB。 - -**所以我觉得你现在缺的不是“memory”,而是一个更深的概念:Learning → Compilation。** - ---- - -# 1. 我会把你想做的东西定义成:Agent 的“认知编译” - -你描述的人类学习过程非常准确: - -```text -第一次: - 仔细思考 - ↓ - 尝试 - ↓ - 犯错 - ↓ - 修正 - -第二次: - 仍然需要思考 - ↓ - 但已经有经验 - -第三次: - 开始形成套路 - -多次之后: - “我知道怎么做了” - ↓ - 不再重新思考 - ↓ - 直接执行 -``` - -传统 Agent: - -```text -User - ↓ -LLM - ↓ -Tool - ↓ -LLM - ↓ -Tool - ↓ -LLM -``` - -每次任务都重新付出推理成本。 - -你想让 Marqdo 变成: - -```text - 新任务 - │ - ▼ - 是否已经学会? - / \ - 是 否 - │ │ - ▼ ▼ - 已编译 mq.md LLM 推理 - │ │ - ▼ ▼ - 低成本执行 执行 + 观察 - │ - ▼ - 沉淀 mq.md - │ - ▼ - 验证 / 优化 - │ - ▼ - 编译成 Skill -``` - -我认为这个想法**非常漂亮**。 - ---- - -# 2. 而且这和 Marqdo 的语言设计天然吻合 - -这可能是你整个项目最重要的一次“闭环”。 - -你前面定义: - -> `.mq.md` = Markdown + 可执行程序 + 知识。 - -现在 Agent 又产生: - -> `.mq.md` = Agent 学会的经验。 - -于是: - -```text - Agent - │ - │ 学习 - ▼ - .mq.md - │ - ┌───────┼────────┐ - ↓ ↓ ↓ - 知识 策略 程序 - │ │ │ - └───────┼────────┘ - ▼ - Agent Skill - │ - ▼ - 低成本执行 -``` - -这就非常有意思了。 - -**Agent 的 memory 不再是一段向量 embedding,也不只是聊天历史。** - -它是: - -> **可阅读、可修改、可验证、可执行的知识程序。** - -这才是真正的 **Marqdo-native Agent**。 - ---- - -# 3. 你现在的 Agent 已经有这个雏形,但还没有真正“学习” - -从你现在的代码看,已经存在: - -```text -reuse -near_match -soft_match -promote -improve_every = 3 -llm_free -``` - -这些机制实际上已经在做: - -> **经验复用。** - -例如当前逻辑会查找已有 KB,如果命中 `llm_free` skill,就可以直接运行 resource,而不是再让父 Agent 做一轮 LLM 推理。 - -这是很好的基础。 - -但我认为: - -> **Reuse ≠ Learning。** - -现在更像: - -```text -成功任务 - ↓ -保存 - ↓ -以后查找 - ↓ -复用 -``` - -而你现在构想的是: - -```text -成功任务 - ↓ -观察多次执行 - ↓ -抽象共同结构 - ↓ -去掉偶然信息 - ↓ -形成一般策略 - ↓ -验证 - ↓ -编译 - ↓ -以后低成本执行 -``` - -这两者差距非常大。 - ---- - -# 4. 我甚至建议你不要叫它 Memory - -我会给它一个更有 Marqdo 味道的名字: - -## **Skill Compilation** - -或者: - -## **Experience Compilation** - -甚至: - -## **Cognitive Compilation** - -整个过程: - -```text -Experience - ↓ -Episodic Trace - ↓ -Pattern Extraction - ↓ -Generalization - ↓ -Marqdo Skill - ↓ -Validation - ↓ -Compiled Skill -``` - -然后 Agent 不再只是: - -> “记住我以前做过什么。” - -而是: - -> **“把以前的思考编译成以后不需要思考的程序。”** - -我觉得这是一个非常强的概念。 - ---- - -# 5. 例如真的可以这样工作 - -第一次: - -用户: - -> 把这个 CSV 中年龄大于 18 的用户筛出来,并按照年龄排序。 - -Agent: - -```text -LLM reasoning - ↓ -读取 CSV - ↓ -分析结构 - ↓ -过滤 - ↓ -排序 - ↓ -输出 -``` - -产生: - -```text -.marqdo/agent-runs/xxx.mq.md -``` - -第二次用户: - -> 把另一个 CSV 中年龄大于 18 的用户筛出来,并按照年龄排序。 - -Agent 发现: - -```text -intent similarity = 0.94 -``` - -于是: - -```text -REUSE -``` - -直接调用之前的程序。 - ---- - -第三、第四、第五次: - -Agent 发现: - -```text -same structure -different file -different column names -``` - -这时候不应该继续保存五个: - -```text -task1.mq.md -task2.mq.md -task3.mq.md -task4.mq.md -task5.mq.md -``` - -而应该让 LLM 总结: - -```markdown -# Filter and Sort CSV Users - -## Preconditions - -- Input contains user records. -- An age field exists. - -## Procedure - -1. Read the input table. -2. Keep rows where `age > 18`. -3. Sort by `age` ascending. - -## Variables - -- `input` -- `age_field` -- `output` - -## Exceptions - -- Missing age field -- Invalid age - -## Examples - -| Input | Output | -|---|---| -| ... | ... | -``` - -然后: - -```text -skill_status = compiled -``` - ---- - -# 6. 更关键的是:这个 mq.md 可以逐渐“去 LLM 化” - -这是你刚才说的: - -> “其中可以使用非常少的大模型思考,或者使用类似 Jev 的决策模型,或者干脆只使用分支控制。” - -**我非常赞同。** - -我甚至认为这应该成为 Marqdo Agent 的核心架构。 - -可以设计成一个: - -# Cognitive Cost Ladder - -```text -Level 0 -Deterministic Marqdo - │ - ▼ -Level 1 -Rule / Branch - │ - ▼ -Level 2 -Small decision model - │ - ▼ -Level 3 -Small LLM - │ - ▼ -Level 4 -Full LLM reasoning - │ - ▼ -Level 5 -Multi-agent exploration -``` - -新问题: - -```text - Full LLM - ↓ - learn - ↓ - Marqdo Skill - ↓ - validation - ↓ - Level 2/1 -``` - -于是 Agent 会越来越“便宜”。 - ---- - -# 7. 这甚至给你提供了一个极漂亮的学习曲线 - -假设一个任务第一次需要: - -```text -8 次 LLM calls -``` - -第二次: - -```text -5 次 -``` - -第三次: - -```text -3 次 -``` - -学习完成: - -```text -0 次 -``` - -或者: - -```text -1 次 small model -``` - -这时候你就有一个非常漂亮的指标: - -## Reasoning Amortization - -定义: - -$$ -C_n = -\frac{ -\text{LLM inference cost over first } n \text{ executions} -}{n} -$$ - -随着执行次数增加: - -```text -Cost - │\ - │ \ - │ \ - │ \ - │ \____ - │ ───────── - └─────────────────── - executions -``` - -**这甚至解决了你之前担心的 Marqdo 性能难以证明的问题。** - -你之前不知道怎么证明: - -> Marqdo 比 Python 更适合 AI。 - -但现在你可以研究: - -> **Marqdo Agent 能否把高成本 LLM reasoning 逐渐编译成低成本 executable knowledge?** - -这个是一个非常明确、可测量、而且很有研究价值的问题。 - ---- - -# 8. 但是这里有一个非常重要的危险 - -你说: - -> “超过三次调用就自动总结。” - -我建议: - -**不要真的这么简单。** - -三次可以作为: - -> **触发学习候选** - -但不能作为: - -> **自动认为已经学会。** - -否则会发生: - -```text -第一次:特殊情况 -第二次:特殊情况 -第三次:特殊情况 -``` - -LLM 总结: - -```text -General rule: -... -``` - -然后把偶然性错误“编译”进 Skill。 - -这会非常危险。 - ---- - -# 9. 我建议建立“经验 → 技能”的四阶段 - -## Stage 1 — Episode - -每次任务产生: - -```text -task -context -actions -tool calls -observations -errors -result -cost -``` - -例如: - -```text -episode-001.mq.md -episode-002.mq.md -episode-003.mq.md -``` - ---- - -## Stage 2 — Candidate Skill - -达到阈值之后: - -```text -3+ similar episodes -``` - -让 LLM 总结: - -```text -candidate.mq.md -``` - -但它还是: - -> **candidate** - -而不是正式 skill。 - ---- - -## Stage 3 — Verification - -用历史任务重新运行: - -```text -episode 1 -episode 2 -episode 3 -``` - -测试: - -```text -candidate skill -``` - -如果: - -```text -3 / 3 success -``` - -再加新的 held-out task: - -```text -episode 4 -``` - -如果: - -```text -4 / 4 -``` - -才提高 confidence。 - ---- - -## Stage 4 — Compilation - -最后: - -```text -candidate - ↓ -verified - ↓ -compiled -``` - -此时才允许: - -```text -llm_free = true -``` - -你目前的系统已经有 `llm_free` 命中后直接运行 resource 的机制。 - -我认为未来这个 flag **不应该是人工/静态指定的属性,而应该成为学习系统的产物。** - ---- - -# 10. 甚至可以让 mq.md 自己记录“学习程度” - -比如: - -```yaml ---- -type: skill -status: compiled -confidence: 0.97 -evidence: 17 -success_rate: 0.941 -llm_free: true -created_from: 6c8... -last_validated: 2026-09-23 -avg_reasoning_cost: 0.2 ---- -``` - -然后正文: - -```markdown -# CSV 成人用户筛选 - -## Intent - -筛选年龄大于 18 岁的用户。 - -## Procedure - -- 读取 CSV -- 判断 age -- 过滤 -- 排序 - -## Fallback - -如果无法确定 age 字段: - -> ask_llm - -## Verification - -| Case | Result | -|---|---| -| case-001 | ✓ | -| case-002 | ✓ | -| case-003 | ✓ | -| case-004 | ✓ | -``` - -注意这个设计里非常重要的一点: - -> **Skill 本身可以包含一个 fallback 到 LLM 的路径。** - -所以不是: - -```text -学会 / 不会 -``` - -而是: - -```text -确定部分 → deterministic -不确定部分 → small model -真正未知 → full LLM -``` - -这就非常接近人类的实际认知过程。 - ---- - -# 11. 我甚至会把 Agent 的运行模型改成这样 - -```text - User Task - │ - ▼ - ┌─────────────────┐ - │ Skill Resolver │ - └────────┬────────┘ - │ - ┌────────────┼────────────┐ - ▼ ▼ ▼ - Exact Near Unknown - Hit Hit - │ │ │ - ▼ ▼ ▼ - mq.md execute small model Full LLM - │ │ │ - └────────────┼────────────┘ - ▼ - Result - │ - ▼ - Episode - │ - ▼ - Experience Store - │ - ┌────────┴────────┐ - │ │ - repeated? novel? - │ - ▼ - Skill synthesis - │ - ▼ - Verification - │ - ▼ - Compilation - │ - ▼ - mq.md Skill -``` - -**这就已经不是普通 Agent framework 了。** - -它是一个: - -> **Self-compiling Agent** - ---- - -# 12. 而 Marqdo 在这里有一个其他 Agent framework 很难天然拥有的优势 - -因为“学习结果”不是: - -```json -{ - "memory": "..." -} -``` - -也不是: - -```text -embedding vector -``` - -而是: - -```text -learned_skill.mq.md -``` - -这意味着用户可以: - -```text -打开 -阅读 -修改 -运行 -测试 -分享 -Git commit -diff -fork -``` - -甚至: - -```text -Agent A - ↓ -learned_skill.mq.md - ↓ -Agent B -``` - -**Agent 的经验第一次成为一种真正可移植的软件 artifact。** - -我认为这是你整个 Marqdo 项目里非常值得深入挖掘的东西。 - ---- - -# 13. 而且它和你前面说的“Executable Knowledge”完全闭环 - -你之前提出: - -```text -Executable Document - ↓ -Executable Knowledge Base -``` - -现在再往前一步: - -```text -Executable Knowledge - ↓ -Agent Experience - ↓ -Agent Learning - ↓ -Compiled Knowledge - ↓ -Executable Skill -``` - -于是整个 Marqdo 可以形成: - -```text - ┌───────────────┐ - │ Human │ - └───────┬───────┘ - │ - ▼ - Natural Task - │ - ▼ - AI Reasoning - │ - ▼ - Executable Work - │ - ▼ - .mq.md - │ - ┌───────┴───────┐ - ▼ ▼ - Knowledge Skill - │ │ - └───────┬───────┘ - ▼ - Future Agent - │ - ▼ - Less Reasoning - │ - ▼ - More Execution -``` - -这就是我现在最喜欢 Marqdo 的地方: - -> **Agent 不只是使用知识库;Agent 会把自己的经验沉淀成知识库,然后知识库反过来改变 Agent 的计算方式。** - -这是一个真正的闭环。 - ---- - -## 最后,我会建议你对现有 Agent 做一个非常明确的架构升级 - -你现在已经有: - -```text -reuse -near_match -soft_match -promote -improve_every=3 -llm_free -``` - -所以**完全没必要推倒重来**。 - -我会把它演化成: - -```text - Current Agent - │ - ┌────────┴────────┐ - │ │ - Execution Experience - │ │ - │ ▼ - │ Episode Store - │ │ - │ ≥ N similar - │ │ - │ ▼ - │ Skill Synthesis - │ │ - │ ▼ - │ Skill Validation - │ │ - │ ▼ - │ Skill Compilation - │ │ - └─────────────┬───┘ - ▼ - .mq.md Skill - │ - ┌────────┼────────┐ - ▼ ▼ ▼ - Branch Small LLM Full LLM -``` - -而且你当前已经有一个非常好的“终点”:**当 child 返回 value 时,可以 deterministic 地 solidify,而不是再次让父 LLM 发明 patch。** 当前代码已经明确这么处理。 - -所以我会把你的下一版 Agent 的核心 slogan 直接定成: - -> **Think → Execute → Learn → Compile → Reuse** - -或者更 Marqdo 一点: - -> **Every successful thought can become executable knowledge.** - -这比“Marqdo 有一个 Agent framework”强得多。 - -而且这件事**非常适合做你前面说的论文实验**:你甚至可以测一个 Agent 在重复任务上的 **LLM calls / tokens / latency / success rate 随经验次数变化的曲线**,直接验证“推理成本被 mq.md 技能逐渐摊销”的假设。这样 Marqdo 的 Agent、Executable Knowledge 和你之前苦恼的“性能怎么证明”三个问题,反而被同一个实验串起来了。 diff --git a/doc/next/003.md b/doc/next/003.md deleted file mode 100755 index 66865c6..0000000 --- a/doc/next/003.md +++ /dev/null @@ -1,2626 +0,0 @@ -可以。基于你现在的 `ext/ai/agent` 实现,我建议不要把它继续做成一个“带缓存的 LLM Agent”,而是正式把它定义成: - -> **一个能够把执行经验逐渐编译成 `.mq.md` 可执行知识/技能的自学习智能体运行时。** - -你现在的框架其实已经有不少基础:`step` 负责单步 LLM/tool execution,`plan` 负责多步执行,并且已经有 `exact → alias → canonical → near` 的复用路径、`agent-kb`、`explore_n`、`improve_every`、`llm_free` 和执行事件记录。 - -下面我给你一套可以直接作为 **Marqdo Agent Framework v2 设计文档** 的方案。 - ---- - -# Marqdo Agent Framework v2 - -## 1. 核心目标 - -整个 Agent 不应该只是: - -```text -Task - ↓ -LLM - ↓ -Tool - ↓ -Answer -``` - -而应该变成: - -```text - ┌─────────────────────┐ - │ User Task │ - └──────────┬──────────┘ - ↓ - ┌───────────────┐ - │ Skill Resolver│ - └───────┬───────┘ - │ - ┌───────────────┼────────────────┐ - ↓ ↓ ↓ - Exact Skill Similar Skill Unknown - │ │ │ - ↓ ↓ ↓ - MQ Execution Adaptation Exploration - │ │ │ - └───────────────┼────────────────┘ - ↓ - Verification - ↓ - Result - ↓ - Episode Trace - ↓ - Experience Store - ↓ - Pattern / Skill Mining - ↓ - Candidate Skill - ↓ - Validation - ↓ - Skill Compile - ↓ - Executable .mq.md - │ - └───────────────→ 下一次调用 -``` - -因此 Agent 有两个完全不同的阶段: - -### Online - -解决当前任务: - -```text -Resolve → Execute → Verify → Return -``` - -### Offline / Background - -从历史经验中学习: - -```text -Collect → Cluster → Generalize → Validate → Compile -``` - -这是整个设计最重要的结构。 - ---- - -# 2. Agent 的四种“记忆” - -我建议不要把所有东西都叫 Memory。 - -实际上应该有四层。 - -## 2.1 Episode Memory - -记录: - -> “这一次具体发生了什么?” - -例如: - -```text -episode/ - 20260924-001.mq.md - 20260924-002.mq.md - 20260924-003.mq.md -``` - -它是**情景记忆**。 - -记录: - -```yaml -task -context -decision -actions -tool_calls -observations -errors -result -verification -cost -``` - -它不需要漂亮,也不需要高度抽象。 - ---- - -# 3. Experience Memory - -Episode 多了以后,系统开始发现: - -```text -Episode 1 -Episode 2 -Episode 3 -Episode 4 - ↓ -这些任务其实属于同一个模式 -``` - -于是形成: - -```text -experience/<slug>.mq.md -``` - -例如: - -```text -experience/ - extract-json-from-response.mq.md - search-local-corpus.mq.md - repair-invalid-json.mq.md -``` - -Experience 是: - -> 多次执行中发现的稳定模式。 - ---- - -# 4. Skill Memory - -Experience 进一步经过验证以后,变成: - -```text -skills/<slug>.mq.md -``` - -这个文件已经不是“记录”。 - -它是: - -> **可以直接执行的程序。** - -例如: - -```markdown ---- -type: skill -status: compiled -llm_free: true - -success_rate: 0.96 -confidence: 0.98 -evidence: 31 - -input: - - query - -output: - - result - -fallback: llm ---- - -## main - -1. `query` - > corpus_search query=`query` - -2. `result` - *result* -``` - -这才是 Marqdo 最特别的地方: - -> **Agent 的学习结果最终不是 embedding,而是 `.mq.md`。** - ---- - -# 5. Policy Memory - -这是进一步优化。 - -某些技能虽然不能完全 deterministic,但可以让一个小模型决定: - -```text -if task.kind == "json": - use json-repair -elif task.kind == "search": - use corpus-search -else: - use llm -``` - -于是形成: - -```text -policy/ - router.mq.md - json-router.mq.md -``` - -所以最终可以形成: - -```text -Episode - ↓ -Experience - ↓ -Skill - ↓ -Policy -``` - ---- - -# 6. Agent 的核心状态机 - -我建议 Agent 明确定义以下状态: - -```text -NEW - │ - ↓ -RESOLVE - │ - ├── EXACT HIT ────────→ EXECUTE - │ - ├── NEAR HIT ─────────→ ADAPT - │ - └── MISS ─────────────→ EXPLORE - │ - ↓ - EXECUTE - │ - ↓ - VERIFY - │ - ┌─────────┴─────────┐ - ↓ ↓ - FAIL PASS - │ │ - ↓ ↓ - REPAIR RECORD - │ │ - └───────→ ↓ - EPISODE - │ - enough evidence? - │ │ - no yes - │ │ - ↓ ↓ - DONE LEARN - │ - ↓ - CANDIDATE - │ - ↓ - VALIDATE - / \ - FAIL PASS - │ │ - ↓ ↓ - REJECT COMPILE - │ - ↓ - SKILL -``` - -这个状态机应该成为 `plan()` 的真正语义。 - -现在的 `plan()` 已经在做其中的一部分,例如 reuse、explore、await、revise 和 promote。 - ---- - -# 7. 顶层 Agent API - -我建议把 API 从现在的: - -```text -agent.plan(goal) -``` - -逐渐扩展成: - -```text -agent.run(task) -agent.learn(task) -agent.compile(skill) -agent.verify(skill) -agent.inspect(task) -agent.forget(skill) -``` - -核心接口: - -```text -## run - + `task` - + `context`=None - + `mode`=auto - + `budget`=None - + `learn`=True - + `verify`=True -``` - -语义: - -```text -run() - ↓ -resolve() - ↓ -execute() - ↓ -verify() - ↓ -record_episode() - ↓ -maybe_learn() -``` - ---- - -# 8. `agent.run` - -这是用户唯一需要经常调用的接口。 - -```text -*> agent.run task=`task`* -``` - -返回: - -```json -{ - "status": "ok", - "result": "...", - - "execution": { - "mode": "compiled", - "skill": "json-repair", - "llm_calls": 0, - "tool_calls": 1 - }, - - "learning": { - "episode": "...", - "skill_updated": false - } -} -``` - -或者第一次: - -```json -{ - "status": "ok", - "result": "...", - - "execution": { - "mode": "explore", - "llm_calls": 5 - }, - - "learning": { - "episode": "episode-001", - "candidate": "json-repair" - } -} -``` - ---- - -# 9. `agent.step` - -你现在的 `step` 应该保留。 - -它是 Agent 最基础的 primitive。 - -当前 `step` 已经承担: - -```text -context assembly -→ LLM -→ READ -→ CALL -→ history -→ writeback -``` - -这正适合作为底层执行单元。 - -建议正式定义: - -```text -## step - + `task` - + `context`=None - + `skill`=None - + `tools`=None - + `model`=auto - + `budget`=None - + `mode`=reason -``` - -其中: - -```text -mode = - deterministic - rule - small_model - llm - explore -``` - ---- - -# 10. `agent.resolve` - -这是新版 Agent 最重要的函数之一。 - -```text -## resolve - + `task` - + `kb_dir` - + `near_match`=True - + `threshold`=0.78 -``` - -返回: - -```json -{ - "mode": "near", - "skill": "json-repair", - "resource": ".marqdo/agent-kb/skills/json-repair.mq.md", - "score": 0.91, - "confidence": 0.97 -} -``` - -Resolver 应该按: - -```text -1. exact -2. alias -3. canonical -4. near -5. semantic -6. policy -7. unknown -``` - -寻找技能。 - -你现在已经实现了: - -```text -exact -alias -canonical -near -soft -``` - -所以这一部分可以直接演进,而不是重写。 - ---- - -# 11. `agent.execute` - -Resolver 决定怎么执行之后: - -```text -## execute - + `task` - + `resolution` -``` - -例如: - -```text -resolution.mode == compiled -``` - -直接: - -```text -await_workbook(skill) -``` - -而不是: - -```text -LLM → 再想一遍 -``` - -如果: - -```text -resolution.mode == near -``` - -则: - -```text -skill - ↓ -parameter adaptation - ↓ -execute - ↓ -verify -``` - -如果: - -```text -resolution.mode == unknown -``` - -则: - -```text -LLM exploration -``` - ---- - -# 12. Cognitive Cost Ladder - -我非常建议把它正式加入框架。 - -```text -L0 deterministic - ↓ -L1 Marqdo rule / branch - ↓ -L2 small decision model - ↓ -L3 small LLM - ↓ -L4 full LLM - ↓ -L5 exploration / multi-step reasoning -``` - -每一个任务都应该有: - -```text -cost_level -``` - -例如: - -```yaml -cost_level: 0 -llm_calls: 0 -``` - -或者: - -```yaml -cost_level: 4 -llm_calls: 7 -``` - -学习的本质就是: - -```text -L5 - ↓ -L4 - ↓ -L3 - ↓ -L2 - ↓ -L1 - ↓ -L0 -``` - -这会成为 Marqdo Agent 非常漂亮的研究指标。 - ---- - -# 13. `agent.verify` - -不能: - -```text -成功一次 -→ 自动成为 skill -``` - -否则很容易错误泛化。 - -所以必须有: - -```text -## verify - + `task` - + `result` - + `skill`=None - + `evidence`=None -``` - -验证包括: - -### 13.1 Execution verification - -```text -有没有报错? -``` - -### 13.2 Structural verification - -```text -输出格式是否正确? -``` - -### 13.3 Semantic verification - -```text -结果是否真正解决 task? -``` - -### 13.4 Regression verification - -```text -过去的任务还能不能通过? -``` - ---- - -# 14. Skill 学习不能简单使用“3 次” - -你之前提出: - -> 三次调用之后自动总结。 - -我建议语义上改成: - -> **三次触发 Candidate Learning,而不是三次直接成为 Skill。** - -也就是: - -```text -1 execution - ↓ -episode - -2 execution - ↓ -episode - -3 execution - ↓ -LEARNING TRIGGER - ↓ -candidate skill -``` - -但是: - -```text -candidate - ↓ -historical replay - ↓ -held-out test - ↓ -verification -``` - -成功以后才: - -```text -compiled -``` - ---- - -# 15. `agent.record_episode` - -每次执行都应该记录。 - -```text -## record_episode - + `task` - + `context` - + `actions` - + `observations` - + `result` - + `verification` - + `metrics` -``` - -生成: - -```text -.marqdo/agent-memory/ - episodes/ - 2026/ - 09/ - episode-0001.mq.md - episode-0002.mq.md -``` - -推荐格式: - -```markdown ---- -type: episode -id: episode-0001 -task_hash: ... -timestamp: ... -status: success - -skill: none -mode: explore - -llm_calls: 5 -tool_calls: 2 -tokens: 4210 -latency_ms: 3820 ---- - -# Task - -... - -# Context - -... - -# Decisions - -... - -# Actions - -... - -# Observations - -... - -# Result - -... - -# Verification - -status: passed - -# Errors - -none -``` - ---- - -# 16. `agent.cluster_episodes` - -Episode 太多以后不能每次全量交给 LLM。 - -因此: - -```text -## cluster_episodes - + `episodes` - + `threshold`=0.82 -``` - -目标: - -```text -episode 1 ─┐ -episode 2 ─┤ -episode 3 ─┤→ cluster A -episode 4 ─┘ - -episode 5 ─┐ -episode 6 ─┤→ cluster B -episode 7 ─┘ -``` - -可以先使用: - -```text -canonicalized task -+ -tool sequence -+ -input/output schema -+ -success pattern -``` - -做廉价聚类。 - -不要一开始就让大模型处理所有历史。 - ---- - -# 17. `agent.extract_pattern` - -从 cluster 中提取共同结构: - -```text -## extract_pattern - + `episodes` -``` - -输入: - -```text -A: - parse - validate - repair - return - -B: - parse - validate - repair - return - -C: - parse - validate - repair - return -``` - -输出: - -```text -Pattern: - -1. Parse -2. Validate -3. Repair if invalid -4. Return -``` - -同时识别: - -```text -invariants -variables -exceptions -preconditions -postconditions -``` - ---- - -# 18. `agent.generalize` - -这个函数非常重要。 - -```text -## generalize - + `pattern` - + `episodes` -``` - -例如: - -三个任务: - -```text -修复 JSON -修复 YAML -修复 TOML -``` - -可能共同形成: - -```text -parse structured data -→ validate -→ locate syntax error -→ repair -→ validate again -``` - -但是: - -```text -JSON/YAML/TOML -``` - -应该成为: - -```text -format -``` - -而不是写死。 - -最终: - -```yaml -input: - format - text - -procedure: - parse(format) - validate() - repair() - validate() -``` - -这才叫 **Generalization**。 - ---- - -# 19. `agent.synthesize_skill` - -然后: - -```text -## synthesize_skill - + `pattern` - + `episodes` -``` - -生成: - -```text -candidate/<slug>.mq.md -``` - -例如: - -```markdown ---- -type: skill -status: candidate - -evidence: 7 -confidence: 0.83 ---- - -## inputs - -- text -- format - -## procedure - -1. parse -2. validate -3. repair -4. validate - -## fallback - -CALL:llm -``` - -注意: - -> Candidate 不是正式 Skill。 - ---- - -# 20. `agent.validate_skill` - -然后: - -```text -## validate_skill - + `skill` - + `episodes` - + `test_cases` -``` - -执行: - -```text -candidate - ↓ -historical tests - ↓ -held-out tests - ↓ -edge cases -``` - -得到: - -```json -{ - "passed": true, - "success_rate": 0.96, - "regression_rate": 1.0, - "confidence": 0.94 -} -``` - ---- - -# 21. 为什么一定需要 Held-out Test? - -否则: - -```text -Episode A -Episode B -Episode C - -→ 从 A/B/C 总结 Skill - -→ 再用 A/B/C 测试 -``` - -这会产生: - -> 训练数据泄漏。 - -所以应该: - -```text -A B C D E F G -│ │ │ │ │ │ │ -├─┴─┴── training -│ -└────── validation -``` - -例如: - -```text -5 个 episode -→ 3 个学习 -→ 2 个测试 -``` - -当数据不足时: - -```text -candidate -``` - -而不是: - -```text -compiled -``` - ---- - -# 22. `agent.compile` - -验证成功: - -```text -## compile - + `candidate` - + `validation` -``` - -生成: - -```text -skills/<slug>.mq.md -``` - -并修改: - -```yaml -status: compiled -llm_free: true -``` - -这时候才允许: - -```text -Resolver - ↓ -Skill - ↓ -await_workbook -``` - -而无需 parent LLM。 - -你当前系统已经存在这个思想:命中 `llm_free` skill 后直接执行 workbook,而不是再次调用 parent LLM。 - -所以 v2 实际上是在把现有的 `llm_free` 从一个优化选项提升成: - -> **编译后的技能执行模式。** - ---- - -# 23. `agent.promote` - -建议把: - -```text -promote -``` - -明确分成: - -```text -candidate -experience -validated -compiled -deprecated -``` - -状态: - -```text -candidate - ↓ -validated - ↓ -compiled - ↓ -stable -``` - -失败: - -```text -candidate - ↓ -rejected -``` - -原 skill 变差: - -```text -stable - ↓ -degraded - ↓ -rollback -``` - ---- - -# 24. Skill Versioning - -这是非常重要但容易被忽略的。 - -不要直接覆盖: - -```text -json-repair.mq.md -``` - -而应该: - -```text -skills/ - json-repair/ - v1.mq.md - v2.mq.md - manifest.mq.md -``` - -manifest: - -```yaml -name: json-repair -version: 2 -status: stable - -success_rate: 0.97 -previous: 1 - -created_from: - - episode-001 - - episode-002 - - episode-003 -``` - -这样才能 rollback。 - ---- - -# 25. `agent.rollback` - -```text -## rollback - + `skill` - + `version` -``` - -例如: - -```text -v3 - ↓ -regression - ↓ -rollback - ↓ -v2 -``` - -这是 Agent 自动学习系统必须有的安全阀。 - ---- - -# 26. `agent.observe` - -所有执行都应该产生统一 Event。 - -你现在的 `plan` 已经记录: - -```text -decision -round -done -tool events -``` - -并支持 `stream / trace / echo`。 - -建议升级成统一事件: - -```json -{ - "type": "decision", - "timestamp": "...", - "run_id": "...", - "phase": "resolve", - "decision": "REUSE", - "skill": "json-repair" -} -``` - -事件类型: - -```text -run_start -resolve -decision -llm_start -llm_end -tool_start -tool_end -skill_start -skill_end -verify -episode_record -learning_trigger -candidate_created -validation -compile -promotion -rollback -run_end -``` - ---- - -# 27. `agent.trace` - -最终: - -```text -trace -``` - -应该成为完整的 Agent execution graph。 - -例如: - -```text -run -│ -├── resolve -│ └── near skill=json-repair -│ -├── adapt -│ -├── execute -│ ├── parse -│ ├── validate -│ └── repair -│ -├── verify -│ -└── record_episode -``` - -这样你的 UI 就可以直接展示 Agent 是怎么“学会”的。 - ---- - -# 28. `agent.learn` - -最后把整个学习流程封装: - -```text -## learn - + `episode` - + `threshold`=3 -``` - -内部: - -```text -record_episode - ↓ -cluster - ↓ -pattern - ↓ -generalize - ↓ -synthesize - ↓ -validate - ↓ -compile -``` - -也就是: - -```text -learn() -``` - -不是一个 LLM prompt。 - -它应该是一个完整的 **Learning Pipeline**。 - ---- - -# 29. `agent.maybe_learn` - -`run()` 不应该每次都学习。 - -因此: - -```text -## maybe_learn - + `task` - + `episode` -``` - -判断: - -```text -是否存在类似任务? -是否达到 evidence threshold? -是否出现稳定 tool sequence? -是否成功率足够? -是否值得编译? -``` - -例如: - -```text -episode_count >= 3 -AND -similarity >= 0.85 -AND -success_rate >= 0.90 -``` - -才触发。 - ---- - -# 30. `improve_every` 的重新定义 - -你现在已经有: - -```text -improve_every=3 -``` - -当前语义更接近: - -> 命中一定次数之后进行改进。 - - - -我建议升级成: - -```yaml -learning: - trigger_every: 3 - validation_min: 3 - confidence_min: 0.90 - success_rate_min: 0.92 -``` - -然后: - -```text -trigger_every -``` - -只代表: - -> 什么时候重新检查技能。 - -而不是: - -> 什么时候自动修改技能。 - ---- - -# 31. `explore_n` 重新定义 - -你当前: - -```text -explore_n=3 -``` - -会在任务文件不足时强制探索不同 variant。 - -这个设计其实非常好,但应该明确: - -```text -explore_n = exploration budget -``` - -而不是简单: - -```text -没有 skill → 多跑三次 -``` - -建议: - -```text -exploration strategy: - variant A - variant B - variant C -``` - -比如: - -```text -A: tool-first -B: code-first -C: LLM-first -``` - -然后比较: - -```text -success -latency -tokens -tool calls -robustness -``` - -最终选择。 - ---- - -# 32. Agent 的 Exploration - -我甚至建议单独增加: - -```text -## explore - + `task` - + `n`=3 - + `strategies`=None -``` - -输出: - -```json -{ - "candidates": [ - { - "strategy": "tool-first", - "success": true, - "cost": 2 - }, - { - "strategy": "llm-first", - "success": true, - "cost": 8 - }, - { - "strategy": "code-first", - "success": true, - "cost": 1 - } - ] -} -``` - -然后: - -```text -select_strategy() -``` - -选择未来的执行路径。 - ---- - -# 33. `agent.select_strategy` - -```text -## select_strategy - + `candidates` -``` - -不是简单按照: - -```text -success -``` - -而是: - -```text -utility = - correctness - - λ * token_cost - - μ * latency - - ν * tool_cost -``` - -例如: - -```text -A: -success = 0.96 -tokens = 8000 - -B: -success = 0.94 -tokens = 1000 - -C: -success = 0.99 -tokens = 3000 -``` - -系统可以保存: - -```text -strategy profile -``` - -而不是每次重新思考。 - ---- - -# 34. 这就引出你之前说的 Jev - -你之前提到: - -> “Jev 决策模型” - -我认为它非常适合放在这里。 - -架构变成: - -```text -Task - ↓ -Jev Router - ↓ -┌──────────────┬──────────────┬──────────────┐ -│ deterministic│ small model │ large LLM │ -└──────────────┴──────────────┴──────────────┘ -``` - -Jev 不负责解决问题。 - -它只负责: - -> **决定应该用什么成本解决问题。** - -这是非常关键的职责分离。 - ---- - -# 35. `agent.route` - -```text -## route - + `task` - + `skills` - + `policy` -``` - -输出: - -```json -{ - "mode": "skill", - "skill": "json-repair", - "confidence": 0.96 -} -``` - -或者: - -```json -{ - "mode": "small_model", - "model": "jev-small", - "confidence": 0.71 -} -``` - -或者: - -```json -{ - "mode": "llm", - "model": "large", - "reason": "unknown task" -} -``` - ---- - -# 36. Skill 的 MQ 文件结构 - -这是我最建议你统一下来的部分。 - -每个 Skill: - -```markdown ---- -type: skill - -name: json-repair -version: 1 - -status: compiled - -input: - - text - - format - -output: - - result - -preconditions: - - text != None - -postconditions: - - valid(result) - -confidence: 0.96 -success_rate: 0.97 -evidence: 21 - -cost: - level: 0 - llm_calls: 0 - avg_tokens: 0 - -created_from: - - episode-001 - - episode-002 - - episode-003 - -validated_at: 2026-09-24 ---- - -# Purpose - -... - -# Preconditions - -... - -# Procedure - -1. ... -2. ... -3. ... - -# Exceptions - -... - -# Verification - -... - -# Fallback - -... - -# Main - -... -``` - -这样 `.mq.md` 同时具有: - -```text -Documentation -+ -Knowledge -+ -Program -+ -Execution -+ -Verification -+ -Provenance -``` - -这正好和你整个 Marqdo 的论文方向统一起来。 - ---- - -# 37. Agent Memory 的目录 - -最终建议: - -```text -.marqdo/ -└── agent/ - ├── episodes/ - │ ├── 2026/ - │ │ └── 09/ - │ │ ├── ep-001.mq.md - │ │ └── ep-002.mq.md - │ - ├── experiences/ - │ ├── json-repair.mq.md - │ └── corpus-search.mq.md - │ - ├── candidates/ - │ └── json-repair/ - │ └── candidate.mq.md - │ - ├── skills/ - │ └── json-repair/ - │ ├── manifest.mq.md - │ ├── v1.mq.md - │ └── v2.mq.md - │ - ├── policies/ - │ └── router.mq.md - │ - ├── tests/ - │ └── json-repair/ - │ ├── test-001.mq.md - │ └── test-002.mq.md - │ - └── index.mq.md -``` - ---- - -# 38. `agent.index` - -不应该每次扫描整个目录。 - -所以需要: - -```text -## index -``` - -维护: - -```yaml -skills: - - name: json-repair - version: 2 - status: stable - embedding: ... - keywords: ... - success_rate: 0.97 - -experiences: - - ... -``` - -Resolver 首先查询 index。 - ---- - -# 39. `agent.kb_lookup` - -你当前已经有: - -```text -agent_kb_lookup -``` - -应该升级成统一: - -```text -## kb_lookup - + `task` - + `mode`=auto -``` - -内部: - -```text -exact -→ alias -→ canonical -→ lexical near -→ semantic near -→ policy -``` - -返回统一结构: - -```json -{ - "match": "near", - "resource": "...", - "score": 0.91, - "confidence": 0.95, - "status": "stable", - "llm_free": true -} -``` - ---- - -# 40. Near Match 之后不要直接执行 - -这是一个非常重要的改进。 - -现在: - -```text -near match - ↓ -skill - ↓ -execute -``` - -容易出现: - -```text -相似 ≠ 相同 -``` - -所以应该: - -```text -near match - ↓ -skill applicability check - ↓ -adapt - ↓ -execute -``` - -增加: - -```text -## adapt_skill -``` - -输入: - -```text -task -skill -``` - -输出: - -```text -binding -``` - -例如: - -```yaml -format: yaml -text: ... -``` - ---- - -# 41. Skill Applicability - -Skill 应该有: - -```yaml -applicability: - domain: structured-data - input_types: - - json - - yaml - constraints: - - has_text_input -``` - -Resolver 不仅问: - -> “像不像?” - -还要问: - -> “这个技能能不能合法处理这个输入?” - ---- - -# 42. Failure Learning - -Agent 不应该只保存成功经验。 - -应该记录: - -```text -成功: -A → B → C - -失败: -A → D → C -``` - -这样才能学习: - -```text -不要 D -``` - -因此 Episode: - -```yaml -status: failed - -failure: - phase: validate - reason: invalid_schema -``` - -然后 Learning Pipeline 可以提取: - -```text -negative pattern -``` - ---- - -# 43. `agent.extract_failure` - -增加: - -```text -## extract_failure - + `episodes` -``` - -输出: - -```yaml -avoid: - - call X before validation - - use Y when input is binary -``` - -然后写入: - -```markdown -# Exceptions - -- Do not use X when ... -- If Y fails, fallback to ... -``` - ---- - -# 44. Self-Improvement - -已有 skill: - -```text -Skill v1 -``` - -运行几十次后: - -```text -发现: -98% 成功 -2% 某种边缘输入失败 -``` - -Agent 不应该立即改变 v1。 - -应该: - -```text -v1 - ↓ -failure cluster - ↓ -candidate v2 - ↓ -regression tests - ↓ -benchmark - ↓ -v2 -``` - -这就是: - -> **Skill Evolution** - ---- - -# 45. `agent.evolve` - -最终: - -```text -## evolve - + `skill` -``` - -执行: - -```text -collect failures -↓ -extract pattern -↓ -patch candidate -↓ -run regression -↓ -compare -↓ -promote / reject -``` - -这比简单的: - -```text -improve_every=3 -``` - -更完整。 - ---- - -# 46. 最终函数清单 - -我建议最终把 Agent API 控制在这些核心函数。 - -### Runtime - -```text -agent.run -agent.step -agent.plan -agent.execute -agent.route -``` - -### Resolution - -```text -agent.resolve -agent.kb_lookup -agent.skill_match -agent.adapt_skill -``` - -### Execution - -```text -agent.execute_skill -agent.execute_policy -agent.explore -agent.select_strategy -``` - -### Verification - -```text -agent.verify -agent.verify_output -agent.verify_skill -agent.regression_test -``` - -### Memory - -```text -agent.record_episode -agent.get_episode -agent.cluster_episodes -agent.extract_pattern -agent.extract_failure -``` - -### Learning - -```text -agent.learn -agent.maybe_learn -agent.generalize -agent.synthesize_skill -``` - -### Compilation - -```text -agent.compile -agent.promote -agent.rollback -agent.evolve -``` - -### Observation - -```text -agent.event -agent.trace -agent.inspect -agent.metrics -``` - ---- - -# 47. `plan()` 最终应该变成什么 - -这是最重要的一点。 - -你现在的 `plan()` 实际上已经非常庞大,因为它同时承担: - -```text -reuse -explore -decompose -execute -await -revise -promote -stream -trace -``` - -当前实现中 `plan` 已经包含这些职责,例如 reuse 命中后直接 await workbook、探索新 variant、执行后 revise,以及成功后的 KB promotion。 - -**v2 不应该继续往 `plan()` 里面塞逻辑。** - -应该把: - -```text -plan() -``` - -变成 orchestrator: - -```text -## plan - -resolve -↓ -route -↓ -execute -↓ -verify -↓ -record -↓ -learn -↓ -finish -``` - -真正的逻辑全部下沉到函数。 - -即: - -```text -plan - ├── resolve - ├── route - ├── execute - ├── verify - ├── record_episode - └── maybe_learn -``` - -这样 `plan` 才会重新变得可读。 - ---- - -# 48. 一个完整执行例子 - -假设用户第一次说: - -```text -把这个 JSON 字符串修复成合法 JSON -``` - -第一次: - -```text -run - ↓ -resolve - ↓ -MISS - ↓ -explore - ↓ -LLM - ↓ -tool - ↓ -verify - ↓ -success - ↓ -episode-001 -``` - -第二次: - -```text -run - ↓ -near match - ↓ -explore variant - ↓ -success - ↓ -episode-002 -``` - -第三次: - -```text -run - ↓ -near match - ↓ -explore - ↓ -success - ↓ -episode-003 - ↓ -maybe_learn -``` - -触发: - -```text -cluster - ↓ -pattern extraction - ↓ -generalization - ↓ -candidate skill -``` - -然后: - -```text -historical test -+ -held-out test -``` - -通过: - -```text -candidate - ↓ -compile - ↓ -json-repair/v1.mq.md - ↓ -llm_free=true -``` - -第四次: - -```text -run - ↓ -exact/near - ↓ -compiled skill - ↓ -Marqdo execution - ↓ -verify - ↓ -result -``` - -: - -```text -LLM calls = 0 -``` - -这就是你最开始提出的: - -> **第一次会思考,后来逐渐不需要思考。** - ---- - -# 49. 最重要的指标:Reasoning Amortization - -我认为这个设计真正厉害的地方,不只是 Agent。 - -它可以形成一个非常明确的实验指标: - -```text -Reasoning Cost / Successful Task -``` - -例如: - -| Execution | Mode | LLM Calls | Tokens | Latency | -| --------- | ----------- | --------: | -----: | ------: | -| #1 | Explore | 7 | 8,200 | 6.1s | -| #2 | Explore | 5 | 5,900 | 4.3s | -| #3 | Candidate | 3 | 3,200 | 2.8s | -| #4 | Small Model | 1 | 500 | 0.9s | -| #5 | Compiled | 0 | 0 | 0.1s | -| #10 | Compiled | 0 | 0 | 0.1s | - -于是: - -```text -Experience ↑ -Reasoning Cost ↓ -``` - -这条曲线实际上就是你整个 Agent framework 的核心。 - ---- - -# 50. Marqdo Agent 的最终定义 - -我会把整个系统概括成: - -```text - MARQDO AGENT - │ - ┌───────────┴───────────┐ - │ │ - ONLINE RUNTIME LEARNING RUNTIME - │ │ - ┌─────┴─────┐ ┌─────┴─────┐ - │ │ │ │ - Resolve Execute Episodes Patterns - │ │ │ │ - ↓ ↓ ↓ ↓ - Route Verify Cluster Generalize - │ │ │ │ - └─────┬─────┘ └─────┬─────┘ - │ │ - ↓ ↓ - Result Candidate - │ - ↓ - Validate - │ - ↓ - Compile - │ - ↓ - Executable MQ - │ - └────→ ONLINE -``` - -所以它不是: - -> **Agent + Memory** - -而是: - -> **Agent = Runtime + Experience + Learning + Compiler** - -进一步说: - -> **Marqdo Agent 的“记忆”不是存储过去发生过什么,而是把过去发生过的事情编译成未来可以执行的知识。** - -这句话其实非常适合成为你整个 Agent Framework 的设计核心。 - ---- - -## 51. 我建议的 v2 最小实现路线 - -不要一次实现全部。 - -### Phase 1:Execution Trace - -先实现: - -```text -run -step -plan -record_episode -trace -metrics -``` - -让**每一次执行都产生 `.mq.md` episode**。 - ---- - -### Phase 2:Experience Mining - -增加: - -```text -cluster_episodes -extract_pattern -generalize -synthesize_skill -``` - -实现: - -```text -3+ executions -→ candidate.mq.md -``` - ---- - -### Phase 3:Skill Compiler - -增加: - -```text -verify_skill -compile -promote -rollback -``` - -实现: - -```text -candidate -→ validation -→ compiled -→ llm_free -``` - -这一步完成以后,你的 Agent 才真正具备“学习”。 - ---- - -### Phase 4:Jev Router - -增加: - -```text -route -select_strategy -policy -``` - -形成: - -```text -L0 deterministic -L1 rule -L2 small model -L3 small LLM -L4 large LLM -L5 exploration -``` - -这一步解决的是: - -> **学会以后如何自动降低推理成本。** - ---- - -### Phase 5:Skill Evolution - -最后: - -```text -failure mining -→ candidate v2 -→ regression -→ benchmark -→ promote -→ rollback -``` - -形成真正的: - -> **Self-Evolving Executable Knowledge Base** - ---- - -## 52. 最终我建议把整个模块重新命名 - -现在的: - -```text -ext/ai/agent -``` - -可以继续保留,但内部概念最好从: - -```text -agent -├── step -└── plan -``` - -升级成: - -```text -agent -├── runtime -│ ├── run -│ ├── step -│ ├── plan -│ └── execute -│ -├── resolver -│ ├── resolve -│ ├── kb_lookup -│ ├── route -│ └── adapt -│ -├── memory -│ ├── episode -│ ├── experience -│ └── skill -│ -├── learning -│ ├── cluster -│ ├── extract -│ ├── generalize -│ └── synthesize -│ -├── verifier -│ ├── verify -│ ├── regression -│ └── benchmark -│ -└── compiler - ├── compile - ├── promote - ├── evolve - └── rollback -``` - -这样一来,你原来已经实现的 `agent-kb / reuse / near_match / explore / improve_every / promote / llm_free` 都不是废掉,而是分别归入 **Resolver、Memory、Learning、Compiler** 四个层次。当前代码已经具备这些机制的雏形,所以这是一次架构升级,而不是推倒重写。 - -**我尤其建议下一步直接做一件具体的事:把这个设计进一步落成一份 `ext/ai/agent` v2 的 `.mq.md` 接口规范。** 也就是把上面每个函数具体写成 Marqdo 风格的 `## function`、参数、返回 JSON schema、状态转换以及 `episode.mq.md / skill.mq.md` 的实际格式。这样就可以直接进入实现,而不是停留在架构层。 diff --git a/doc/next/004.md b/doc/next/004.md deleted file mode 100755 index e437ea1..0000000 --- a/doc/next/004.md +++ /dev/null @@ -1,541 +0,0 @@ -有时候可能用户不太好接入Jev,所以阶段4应该要允许用户使用小参数的模型代替,你认为呢? - -我非常赞同,而且我甚至建议**不要把 Jev 作为阶段 4 的必选组件**。 - -更准确的设计应该是: - -> **Jev 是一种可选的决策器(Decision Engine),小参数模型是另一种可选实现;Marqdo Agent 本身只规定“需要一个 Router/Policy”,而不规定 Router 必须由什么实现。** - -这样会让整个框架开放很多。 - -### 1. 阶段 4 应该改成“Adaptive Routing” - -原来的: - -```text -Phase 4 - ↓ -Jev Router -``` - -我建议改成: - -```text -Phase 4: Adaptive Routing - │ - ┌─────────┼─────────┐ - ↓ ↓ ↓ - Marqdo Rule Jev Small LLM - │ │ │ - └─────────┼─────────┘ - ↓ - Route Policy -``` - -甚至还可以允许: - -```text -Rule -Small Model -Jev -Full LLM -``` - -混合使用。 - ---- - -# 2. 为什么这个设计更合理 - -因为用户真正需要的不是: - -> “我要接入 Jev。” - -而是: - -> “我希望 Agent 学会以后,不要每次都调用大模型。” - -这两个概念应该分开。 - -所以 Marqdo 只定义接口: - -```text -agent.route(task, candidates) -``` - -至于内部怎么实现,可以是: - -### A. 纯 Marqdo - -```text -if task.type == "json": - return json-repair - -if task.type == "search": - return corpus-search -``` - -完全不需要模型。 - ---- - -### B. 小参数模型 - -比如用户已经有: - -```text -Qwen 0.5B -Qwen 1.5B -Llama 1B -某个本地模型 -``` - -就可以: - -```text -task - ↓ -small model - ↓ -"json-repair" -``` - -甚至可以让用户直接配置: - -```yaml -router: - type: llm - - provider: openai-compatible - base_url: ... - api_key: ... - model: ... -``` - -这和你之前设计 AI 斗蛐蛐时提出的 **OpenAI-compatible URL + Key** 思路其实也很契合。 - ---- - -### C. Jev - -如果用户安装了 Jev: - -```text -task - ↓ -Jev - ↓ -policy -``` - -那么就用 Jev。 - ---- - -### D. 大模型 - -甚至最开始没有任何 Router: - -```text -task - ↓ -large LLM - ↓ -decide -``` - -也是合法的。 - -所以: - -> **Router 是抽象能力,不是具体模型。** - ---- - -# 3. 更重要的是:Router 本身也可以被学习 - -这里我觉得还能进一步提升你的设计。 - -一开始: - -```text -Task - ↓ -Large LLM - ↓ -选择 skill -``` - -系统观察: - -```text -task A → json-repair -task B → json-repair -task C → json-repair -task D → corpus-search -``` - -之后可以自动生成: - -```text -router.mq.md -``` - -例如: - -```markdown ---- -type: policy -status: compiled ---- - -## route - -1. `task.type` == "json" - *"json-repair"* - -2. `task.type` == "search" - *"corpus-search"* - -3. * - *"llm"* -``` - -那么你甚至不需要 Jev。 - -**Marqdo 自己的控制流就是 Router。** - ---- - -# 4. 所以我会重新设计 Cost Ladder - -之前的: - -```text -L0 deterministic -L1 rule -L2 small model -L3 small LLM -L4 large LLM -L5 exploration -``` - -我建议改成: - -```text - ┌────────────────────────┐ - │ Adaptive Router │ - └───────────┬────────────┘ - │ - ┌─────────────────┼─────────────────┐ - ↓ ↓ ↓ - Deterministic Small Model Large LLM - │ │ │ - ↓ ↓ ↓ - L0/L1 L2/L3 L4 - │ - ↓ - Exploration L5 -``` - -这里最关键的是: - -> **L2/L3 不应该规定具体模型。** - -可以是: - -```text -Marqdo rules - OR -Jev - OR -0.5B model - OR -1B model - OR -3B model -``` - ---- - -# 5. 我甚至建议用户可以配置多个 Router - -例如: - -```yaml -router: - candidates: - - - name: rules - type: marqdo - - - name: local - type: llm - model: qwen-0.5b - - - name: jev - type: jev - - - name: cloud - type: llm - model: ... -``` - -然后 Agent 自己选择: - -```text -Task - ↓ -Router Resolver - ↓ -rules? - ↓ -confidence insufficient - ↓ -small model? - ↓ -confidence insufficient - ↓ -Jev? - ↓ -confidence insufficient - ↓ -large LLM -``` - -这就形成一个**分级决策系统**。 - ---- - -# 6. 最漂亮的地方:Router 也可以被编译 - -最终甚至可以: - -```text -第一次: - -LLM - ↓ -决定调用 Skill A - -第二次: - -LLM - ↓ -决定调用 Skill A - -第三次: - -LLM - ↓ -决定调用 Skill A - -Learning - ↓ -发现稳定模式 - -Compile - ↓ -router.mq.md -``` - -以后: - -```text -Task - ↓ -router.mq.md - ↓ -skill A - ↓ -execute -``` - -**0 LLM。** - -于是整个 Agent 的学习就不只是: - -```text -学习如何解决任务 -``` - -而是同时学习: - -```text -1. 学习如何解决任务 -2. 学习什么时候使用什么技能 -3. 学习什么时候需要大模型 -``` - -这三个层次组合起来,我认为比单纯引入 Jev 更有意思。 - ---- - -# 7. 最终可以形成三级编译 - -我现在反而觉得你的 Agent Framework 可以把整个“学习”定义成三个阶段: - -```text -Experience - ↓ -Skill Compilation - ↓ -Policy Compilation - ↓ -Execution Compilation -``` - -### 第一层:Skill Compilation - -```text -LLM experience - ↓ -skill.mq.md -``` - -解决: - -> **怎么做?** - -### 第二层:Policy Compilation - -```text -many task → skill mappings - ↓ -policy.mq.md -``` - -解决: - -> **什么时候做什么?** - -### 第三层:Execution Compilation - -```text -skill + policy - ↓ -pure Marqdo execution -``` - -解决: - -> **能不能完全不思考直接执行?** - -这时候整个 Agent 就变成: - -```text - Large LLM - │ - Exploration - ↓ - Experience - ↓ - ┌───────────────┐ - │ Skill Compile │ - └───────┬───────┘ - ↓ - Skill MQ - │ - ┌───────┴───────┐ - ↓ ↓ - Policy Compile Direct Execute - ↓ - Router MQ - │ - ↓ - Skill Selection - │ - ↓ - Execute -``` - ---- - -# 8. 因此 Phase 4 我建议正式改名 - -不要叫: - -> Jev Router - -而叫: - -> **Adaptive Policy / Routing Layer** - -然后提供四种 backend: - -```text -router.backend = marqdo -router.backend = small-llm -router.backend = jev -router.backend = llm -``` - -甚至: - -```text -router.backend = auto -``` - -让 Agent 根据可用环境自动选择。 - ---- - -## 9. 用户体验也会好很多 - -用户第一次安装 Marqdo: - -```text -marqdo agent run ... -``` - -没有 Jev,也没有小模型。 - -完全没问题: - -```text -→ 使用配置的大模型 -``` - -用户后来配置: - -```yaml -router: - backend: small-llm - provider: openai-compatible - model: qwen-0.5b -``` - -Agent 就自动变成: - -```text -大模型:负责复杂推理 / 学习 -小模型:负责日常路由 -Marqdo:负责确定性执行 -``` - -如果用户安装 Jev: - -```yaml -router: - backend: jev -``` - -则: - -```text -Jev:负责路由 -大模型:负责复杂任务 -Marqdo:负责执行 -``` - -**用户完全不需要改变 Agent 的上层 API。** - ---- - -我认为这个调整非常重要,因为它让 **Marqdo Agent 的核心创新从“依赖某个新模型”变成“模型无关的认知编译架构”**。 - -最终可以浓缩成一句话: - -> **大模型负责探索,小模型/Jev 负责决策,Marqdo 负责执行;随着经验积累,探索和决策逐渐被编译成可执行的 `.mq.md`。** - -这其实比“接入 Jev”本身更符合你最开始提出的 **Think → Execute → Learn → Compile → Reuse** 路线。 diff --git a/doc/next/005.md b/doc/next/005.md deleted file mode 100755 index 750c1f0..0000000 --- a/doc/next/005.md +++ /dev/null @@ -1,1173 +0,0 @@ -llm框架存在问题,请你阅读给出好的方案。 - -我认真看了一遍。我的判断是: - -> **你现在的 `ext/ai/llm` 已经是一个能工作的 LLM Client,但还不是一个真正符合 Marqdo 哲学的 LLM 抽象。** - -它现在最像: - -```text -Marqdo - ↓ -llm.mq.md - ↓ -OpenAI HTTP API -``` - -而我认为 Marqdo 应该做到: - -```text -Marqdo Document - ↓ - LLM - ↓ -Prompt / Context / Model / Policy - ↓ -Structured Result - ↓ -Executable Knowledge -``` - -也就是说,**OpenAI-compatible HTTP 应该退到最底层,用户在 Marqdo 层根本不应该感受到它。** - ---- - -# 一、你现在这份代码最大的问题 - -你的代码本身没有明显的工程性错误,真正的问题是**抽象泄漏**。 - -例如现在用户最终会写: - -```marqdo -**answer = > llm.complete prompt=`prompt` stream=`stream` echo=`echo`** -``` - -而内部又出现: - -```marqdo -url = [base_url](self) + [suffix](self) -auth = [bearer](self) + [api_key](self) -headers = > table.put ... -messages = -| @ | role | content | -... -body = > json.stringify ... -resp = > net.http_post ... -``` - -这实际上是在把: - -* HTTP -* Authorization -* OpenAI endpoint -* JSON -* messages -* stream -* SSE - -全部暴露给了 Marqdo 的 AI 编程层。 - -这和“代码即文档”是有冲突的。 - -因为用户真正想表达的是: - -> **“请让这个模型回答这个问题。”** - -而不是: - -> “请构造一个 OpenAI Chat Completion HTTP 请求。” - ---- - -# 二、我建议把 `ext/ai/llm` 重新定义成一个「LLM Object」 - -我会把整个设计提升一个抽象层: - -```text - ┌────────────────────┐ - │ Marqdo Document │ - └─────────┬──────────┘ - │ - llm.ask() - │ - ┌────────────┴────────────┐ - │ │ - Context Policy - │ │ - └────────────┬────────────┘ - │ - LLM Runtime - │ - ┌────────────┼────────────┐ - │ │ │ - OpenAI Ollama Other - Compatible Compatible Provider -``` - -然后整个 `ext/ai/llm` 应该分成 **四层**: - -### Layer 1:Semantic API - -用户真正使用: - -```text -llm.ask -llm.generate -llm.stream -``` - -### Layer 2:Conversation / Context - -处理: - -```text -system -context -user -assistant -tools -``` - -### Layer 3:Model abstraction - -处理: - -```text -provider -model -temperature -max_tokens -``` - -### Layer 4:Transport - -才处理: - -```text -HTTP -JSON -SSE -Authorization -/chat/completions -``` - -**第 4 层应该尽可能不可见。** - ---- - -# 三、最重要的变化:`complete` 不应该成为主要 API - -我甚至建议把: - -```text -complete -``` - -降级成内部 primitive。 - -因为: - -> `complete` 是 API Client 的语言,而 `ask` 是 AI-native language 的语言。 - -这是一个非常重要的区别。 - -用户应该看到: - -```marqdo -**answer = > llm.ask prompt=`prompt`** -``` - -而不是: - -```marqdo -**answer = > llm.complete prompt=`prompt`** -``` - -甚至进一步,我希望 Marqdo 最终能够做到: - -```marqdo -**answer = > llm.ask** -``` - -然后让当前文档本身成为 prompt。 - -这样才真正开始出现“代码即文档”的味道。 - ---- - -# 四、我特别建议引入「Prompt = Document」 - -这是我认为这次重构里**最有价值的一步**。 - -现在: - -```marqdo -prompt = "You are an AI assistant..." -``` - -本质上还是传统程序语言思维。 - -但 Marqdo 本身就是 Markdown-native。 - -所以应该允许: - -```markdown -# Task - -Analyze the following data. - -## Requirements - -- Identify the important patterns. -- Explain the reasons. -- Return a concise summary. - -## Data - -... -``` - -直接成为一个 **Prompt Artifact**。 - -也就是说: - -> **Prompt 不再只是字符串,而是 Knowledge Artifact。** - -这和你之前“Executable Document → Executable Knowledge Base”的方向是完全一致的。 - ---- - -# 五、因此我建议引入 `llm.prompt` - -例如设计成: - -```marqdo -**prompt = > llm.prompt** - -# Task - -Analyze the following customer feedback. - -# Requirements - -- Find the major problems. -- Group similar complaints. -- Explain the likely causes. - -# Output - -Return a structured summary. -``` - -然后: - -```marqdo -**answer = > llm.ask prompt=`prompt`** - -*answer* -``` - -这里就非常漂亮了。 - -因为: - -```text -prompt.mq.md -``` - -本身就是: - -```text -Document - ↓ -Prompt - ↓ -LLM Input -``` - -以后甚至可以: - -```text -Prompt - ↓ -Skill - ↓ -Agent - ↓ -Knowledge -``` - -这就开始形成 Marqdo 自己独有的体系。 - ---- - -# 六、甚至可以进一步:让 Document 本身就是 Prompt - -这是我更推荐的最终方向。 - -比如: - -```markdown ---- -type: prompt -model: gpt-4o-mini ---- - -# Analyze Customer Feedback - -Analyze the following customer feedback. - -## Requirements - -1. Identify the major problems. -2. Group similar complaints. -3. Explain possible causes. - -## Input - -{{feedback}} -``` - -调用: - -```marqdo -**answer = > llm.ask prompt=`this` feedback=`data`** - -*answer* -``` - -或者未来进一步做到: - -```marqdo -**answer = > llm.ask** -``` - -让当前 executable document 自动成为上下文。 - -这会非常符合 Marqdo 的设计哲学。 - ---- - -# 七、第二个重大变化:不要让 `llm` 既是 Factory 又是 Client - -你现在: - -```marqdo -**# llm** - -Construct an LLM handle -``` - -然后: - -```marqdo -self.complete -``` - -实际上 `llm` 同时承担: - -```text -LLM configuration -LLM factory -LLM instance -LLM API -``` - -这四个角色。 - -我建议明确分开。 - ---- - -## `llm` = 默认模型 - -例如: - -```marqdo -**model = > llm.create** -``` - -得到: - -```text -LLM Handle -``` - -然后: - -```marqdo -**answer = > model.ask prompt=`prompt`** -``` - -这样对象关系非常清楚: - -```text -llm - │ - ├── create() - │ ↓ - │ model - │ │ - │ ├── ask() - │ ├── stream() - │ └── raw() - │ - └── providers -``` - ---- - -# 八、我会把配置也从代码中拿出来 - -你现在: - -```marqdo -api_key = > sys.env_get ... -base_url = > sys.env_get ... -model = > sys.env_get ... -``` - -这非常工程化,但不够优雅。 - -应该允许 `.mq.md` 自己描述模型: - -```markdown ---- -type: llm -provider: openai-compatible -model: gpt-4o-mini -base_url: ${OPENAI_BASE_URL} -api_key: ${OPENAI_API_KEY} ---- -``` - -于是: - -```marqdo -import llm:ext/ai/llm.mq.md -``` - -之后: - -```marqdo -**answer = > llm.ask prompt=`prompt`** -``` - -就够了。 - -环境变量只是 fallback。 - ---- - -# 九、我甚至建议支持 Named Model - -这是对你后面 Agent Framework 非常重要的一步。 - -例如: - -```markdown ---- -type: llm -name: fast -provider: openai-compatible -model: qwen3-0.6b ---- -``` - -以及: - -```markdown ---- -type: llm -name: reasoning -provider: openai-compatible -model: gpt-5.6 ---- -``` - -然后: - -```marqdo -**answer = > fast.ask prompt=`prompt`** -``` - -或者: - -```marqdo -**answer = > reasoning.ask prompt=`prompt`** -``` - -这样 Agent 就可以: - -```text - Agent - │ - ┌────────┴────────┐ - ↓ ↓ - fast model reasoning model - │ │ - routing exploration -``` - -这正好对应我们前面讨论的: - -> **大模型负责探索,小模型/Jev 负责决策,Marqdo 负责执行。** - -而且不需要把 Jev 写死在 LLM 层。 - ---- - -# 十、第三个重大变化:不要让 `stream` 是一个 Boolean - -你现在: - -```marqdo -stream=False -``` - -这是典型 API Client 设计。 - -我建议把它提升成能力: - -```text -llm.ask -llm.stream -``` - -而不是: - -```text -llm.complete stream=True -``` - -所以: - -```marqdo -**answer = > model.ask prompt=`prompt`** -``` - -表示: - -```text -一次性得到结果 -``` - -而: - -```marqdo -**events = > model.stream prompt=`prompt`** -``` - -表示: - -```text -得到事件流 -``` - -然后: - -```marqdo -**answer = > llm.reduce events=`events`** -``` - -把 stream 转换成最终结果。 - -这样语义非常清晰。 - ---- - -# 十一、你现在的 `stream_result` 也应该重新设计 - -现在: - -```marqdo -## stream_result -``` - -其实是在做: - -```text -Transport Event → Text -``` - -这属于 transport / adapter 层。 - -我建议: - -```text -llm.stream - ↓ -LLM Event Stream - ↓ -llm.collect - ↓ -LLM Result -``` - -例如: - -```marqdo -**events = > model.stream prompt=`prompt`** - -**result = > llm.collect events=`events`** - -*result* -``` - -而 `events` 不应该只是一些 OpenAI 特有的: - -```text -delta -done -error -reasoning -``` - -应该变成 Marqdo 自己定义的统一事件: - -```text -text -reasoning -tool_call -tool_result -done -error -``` - -于是 OpenAI、Anthropic、Ollama、Gemini、国产模型都可以映射到这个协议。 - ---- - -# 十二、第四个重大变化:Result 应该是对象,而不是裸字符串 - -现在: - -```marqdo -*[content](...) -``` - -直接返回文本。 - -这对于最简单的调用很好,但对于 Agent 不够。 - -建议: - -```text -LLMResult -``` - -至少包含: - -```text -result.text -result.model -result.usage -result.finish -result.tool_calls -result.raw -``` - -例如: - -```marqdo -**result = > model.ask prompt=`prompt`** - -*result.text* -``` - -或者: - -```marqdo -**result = > model.ask prompt=`prompt`** - -**tokens = [total_tokens](result.usage)** -``` - -这样 Agent Framework 就可以直接获得: - -```text -cost -latency -tokens -model -reasoning -tool calls -``` - -这对你后面的: - -> Experience → Learning → Compilation - -极其重要。 - -因为**没有结构化 Result,就很难做经验学习。** - ---- - -# 十三、因此你的 LLM API 最终可以非常漂亮 - -我建议核心 API 就保持在下面这几个: - -```text -llm.create -llm.ask -llm.stream -llm.collect -llm.embed -llm.count -``` - -其中真正核心只有: - -```text -create -ask -stream -``` - -其他都是能力扩展。 - ---- - -# 十四、一个我认为非常漂亮的使用方式 - -普通程序: - -```marqdo -import llm:ext/ai/llm.mq.md - -**answer = > llm.ask prompt="Explain Marqdo."** - -*answer* -``` - -已经比现在好很多。 - -但是我真正喜欢的是: - -```marqdo -import llm:ext/ai/llm.mq.md - -**answer = > llm.ask** - -# Explain Marqdo - -Explain Marqdo as an AI-native programming language. - -## Requirements - -- Explain the motivation. -- Explain executable documents. -- Explain executable knowledge. -- Give one concrete example. - -*answer* -``` - -这里已经非常接近: - -> **Executable Document** - -而不是传统意义上的: - -> Python + SDK + Prompt String。 - ---- - -# 十五、再往前一步:让 Prompt 自己可以成为函数 - -这会非常强。 - -例如: - -```markdown -**## explain** - -Explain the concept of **[topic]**. - -Requirements: - -- Be concise. -- Give an example. -- Use Markdown. -``` - -那么: - -```marqdo -**answer = > llm.explain topic="Marqdo"** -``` - -这里 `explain` 本身就是一个: - -```text -Prompt + Program + Knowledge -``` - -以后甚至可以: - -```text -explain.mq.md - ↓ - LLM Skill - ↓ - compiled skill -``` - -这就直接连接到你现在正在重新设计的 Agent Framework。 - ---- - -# 十六、我会把 `llm.mq.md` 的内部结构改成这样 - -不是让它直接变成 200 行 HTTP wrapper,而是: - -```text -ext/ai/llm.mq.md - -├── Configuration -│ -├── Model -│ ├── create -│ ├── ask -│ └── stream -│ -├── Prompt -│ ├── create -│ └── render -│ -├── Result -│ ├── text -│ ├── usage -│ └── metadata -│ -├── Event -│ └── normalize -│ -└── Transport - └── openai-compatible -``` - -其中: - -```text -Transport -``` - -应该是整个文件里最不重要的部分。 - -甚至我建议进一步拆: - -```text -ext/ai/ -├── llm.mq.md -├── llm/ -│ ├── openai.mq.md -│ ├── anthropic.mq.md -│ ├── ollama.mq.md -│ └── compatible.mq.md -``` - -这样: - -```text -llm -``` - -是抽象。 - -```text -openai-compatible -``` - -只是实现。 - ---- - -# 十七、我尤其建议不要把 OpenAI 写死在 `llm` - -你现在实际上: - -```text -llm = OpenAI-compatible -``` - -我认为这个命名应该反过来: - -```text -llm = abstract LLM -``` - -然后: - -```text -openai-compatible = backend -``` - -例如: - -```yaml ---- -type: llm -backend: openai-compatible -model: gpt-5.6 ---- -``` - -或者: - -```yaml ---- -type: llm -backend: ollama -model: qwen3 ---- -``` - -Marqdo 用户根本不需要改变: - -```marqdo -**answer = > llm.ask prompt=`prompt`** -``` - -这才是真正的 abstraction。 - ---- - -# 十八、这会直接解决你 Agent Framework 的一个核心问题 - -你之前的 Agent 设计里有: - -```text -Large LLM -Small LLM -Jev -Marqdo -``` - -如果现在 `llm.mq.md` 设计得好,那么 Agent 根本不需要知道底层是什么: - -```text -Agent - │ - └── Router - │ - ├── llm.fast - ├── llm.reasoning - ├── llm.local - ├── jev - └── marqdo -``` - -甚至: - -```text -Router - ↓ -Policy - ↓ -LLM object - ↓ -Provider -``` - -这就形成了一个非常干净的层次。 - ---- - -# 十九、最终我建议 Marqdo 的 AI 层形成这样的结构 - -我觉得这甚至可以成为你整个 Marqdo AI architecture 的核心图: - -```text - MARQDO - │ - Executable Document - │ - ┌──────────────┼──────────────┐ - │ │ │ - Program Prompt Knowledge - │ │ │ - └──────────────┼──────────────┘ - │ - Agent - │ - ┌───────┴───────┐ - │ │ - Policy Skill - │ │ - └───────┬───────┘ - │ - LLM API - │ - ┌───────────┼───────────┐ - │ │ │ - Large LLM Small LLM Jev - │ │ │ - └───────────┼───────────┘ - │ - Backend - │ - ┌─────────────┼─────────────┐ - │ │ │ - OpenAI Ollama Compatible -``` - -然后随着学习: - -```text -Experience - ↓ -Pattern - ↓ -Skill - ↓ -Policy - ↓ -Marqdo Compilation -``` - -最终: - -```text -Large LLM - ↓ -Small LLM - ↓ -Policy - ↓ -Marqdo - ↓ -Deterministic Execution -``` - -这就和你之前提出的 **“执行沉淀为 `.mq.md`,最终变成低能耗执行”** 完全接起来了。 - ---- - -# 二十、我认为最值得坚持的一个设计原则 - -我会把它总结成一句话: - -> **`ext/ai/llm` 不应该是“如何调用模型”,而应该是“如何在 Marqdo 中表达一次智能”。** - -所以: - -```text -HTTP -JSON -SSE -Authorization -/messages -/chat/completions -``` - -这些全部属于: - -> **Implementation** - -而: - -```text -ask -stream -prompt -context -result -model -skill -policy -``` - -才属于: - -> **Marqdo Language** - ---- - -## 我建议你的下一版 API 最终长这样 - -### 最简单 - -```marqdo -import llm:ext/ai/llm.mq.md - -**answer = > llm.ask prompt="What is Marqdo?"** - -*answer* -``` - -### 文档原生 - -```marqdo -import llm:ext/ai/llm.mq.md - -**answer = > llm.ask** - -# What is Marqdo? - -Explain Marqdo as an AI-native programming language. - -## Requirements - -- Explain the motivation. -- Explain executable documents. -- Explain executable knowledge. -- Give one example. - -*answer* -``` - -### 指定模型 - -```marqdo -**answer = > llm.fast.ask prompt=`prompt`** -``` - -### 强推理 - -```marqdo -**answer = > llm.reasoning.ask prompt=`prompt`** -``` - -### 流式 - -```marqdo -**events = > llm.fast.stream prompt=`prompt`** - -**result = > llm.collect events=`events`** - -*result* -``` - -### Agent - -```marqdo -**result = > agent.run task=`task`** -``` - -而 Agent 内部: - -```text -agent - ↓ -policy - ↓ -llm.fast / llm.reasoning / jev / marqdo - ↓ -skill - ↓ -verification - ↓ -experience -``` - ---- - -**这其实比单纯重构 `llm.mq.md` 更重要:我建议把 `llm` 定义成 Marqdo 的“智能原语(Intelligence Primitive)”,而不是 OpenAI SDK 的包装器。** - -这样 `llm.mq.md`、你现在正在重构的 `agent.mq.md`、未来的 `skill.mq.md` / `policy.mq.md` 就能形成一个统一体系: - -> **Document → Prompt → LLM → Agent → Skill → Policy → Executable Knowledge** - -而这条链,恰好是 Marqdo 和普通“给 Python 加一个 LLM SDK”之间最有辨识度的区别。 diff --git a/doc/next/006.md b/doc/next/006.md deleted file mode 100755 index 7f7b9b7..0000000 --- a/doc/next/006.md +++ /dev/null @@ -1,1335 +0,0 @@ ---- -type: discussion -status: superseded-by-design -formal: doc/design/binding.md -adr: doc/adr/0006-artifact-metadata-binding.md ---- - -> **正式规范已落地**:讨论收敛见 [doc/design/binding.md](../design/binding.md)(Phase 1 Metadata Binding + Phase 2 scope lift)与 [ADR 0006](../adr/0006-artifact-metadata-binding.md)。 -> **否决**:下文 §17「正文也写 `${…}`」——`${}` 只留在 Metadata;正文用已提升的普通名字。 - -你的这个设计我觉得不错,配置信息写进元信息,能够自动的处理一些从环境变量中得到的变量,我觉得这个可以写进核心的语法之中,你认为呢?如果可以给我详细的设计方案 - -我认为**非常可以,而且我会进一步建议:把“环境变量 / 外部配置解析”提升为 Marqdo 核心语法的一部分,而不是 `ext/ai/llm` 自己实现的功能。** - -但有一个关键边界: - -> **核心语法负责“声明与解析配置”,具体扩展负责“解释配置的语义”。** - -这样它不会变成“为了 LLM 发明的配置语法”,而会成为 Marqdo 作为 **Executable Document** 的基础能力。 - ---- - -# 1. 我建议把它定义成:Artifact Metadata Binding - -你现在有: - -```yaml ---- -type: llm -backend: openai-compatible -model: gpt-5.6 ---- -``` - -我建议正式把 `---` 这一块定义为: - -> **Artifact Metadata** - -它不只是 YAML front matter,而是 Marqdo 文档的**声明式元信息环境**。 - -完整模型: - -```text -.mq.md -│ -├── Metadata -│ ├── Identity -│ ├── Configuration -│ ├── Dependencies -│ └── Bindings -│ -└── Executable Body -``` - -于是: - -```yaml ---- -type: llm -backend: openai-compatible -model: gpt-5.6 ---- -``` - -实际上是在声明: - -```text -这个 Document 是一个 LLM Artifact -它使用 openai-compatible backend -默认 model 是 gpt-5.6 -``` - ---- - -# 2. 最重要的设计:Metadata 可以引用外部环境 - -我建议引入一个核心语法: - -```text -${...} -``` - -例如: - -```yaml ---- -type: llm -backend: openai-compatible -model: ${OPENAI_MODEL} -api_key: ${OPENAI_API_KEY} -base_url: ${OPENAI_BASE_URL} ---- -``` - -这样: - -```text -${OPENAI_MODEL} -``` - -不是 YAML 的语法,而是: - -> **Marqdo Binding Expression** - -也就是说: - -```text -Metadata - ↓ -Binding - ↓ -Environment / Secret / File / Argument / System -``` - ---- - -# 3. 但是不要只设计 `${ENV_VAR}` - -如果现在只支持: - -```text -${OPENAI_API_KEY} -``` - -几年以后你一定会发现不够。 - -我建议一开始就设计成**命名空间式 Binding**。 - -例如: - -```text -${env.OPENAI_API_KEY} -${arg.model} -${sys.cwd} -${file.config.model} -${secret.OPENAI_API_KEY} -``` - -这样 Marqdo 的配置系统可以形成: - -```text -binding -├── env -├── arg -├── sys -├── file -├── secret -└── artifact -``` - ---- - -# 4. 最基础的语法 - -我建议: - -```text -${namespace.name} -``` - -例如: - -```yaml ---- -type: llm -model: ${env.OPENAI_MODEL} -api_key: ${env.OPENAI_API_KEY} -base_url: ${env.OPENAI_BASE_URL} ---- -``` - -这比: - -```yaml -model: ${OPENAI_MODEL} -``` - -更值得作为长期语言设计。 - -因为它避免了未来命名冲突。 - ---- - -# 5. 默认值必须支持 - -这是非常重要的。 - -例如: - -```yaml ---- -model: ${env.OPENAI_MODEL | "gpt-5.6"} -base_url: ${env.OPENAI_BASE_URL | "https://api.openai.com/v1"} ---- -``` - -意思是: - -```text -如果 OPENAI_MODEL 存在 - 使用它 - -否则 - 使用 gpt-5.6 -``` - -我甚至建议允许更明确的: - -```text -${env.OPENAI_MODEL ?? "gpt-5.6"} -``` - -也就是: - -```text -A ?? B -``` - -代表: - -> 如果 A 不存在,则使用 B。 - ---- - -# 6. Secret 应该和普通 Environment 区分 - -这是我非常建议你现在就设计进去的。 - -不要让: - -```yaml -api_key: ${env.OPENAI_API_KEY} -``` - -成为唯一方式。 - -应该支持: - -```yaml -api_key: ${secret.OPENAI_API_KEY} -``` - -语义上: - -```text -env - 普通运行环境 - -secret - 敏感运行环境 -``` - -这样以后 Marqdo Runtime 可以控制: - -```text -secret -├── 不写入 episode -├── 不进入普通 trace -├── 不显示在 echo -├── 不进入错误信息 -└── 不进入生成的 knowledge artifact -``` - -这对你未来 Agent Framework 非常重要。 - ---- - -# 7. 我建议增加“必需配置”的语法 - -比如: - -```yaml ---- -type: llm -backend: openai-compatible -model: ${env.OPENAI_MODEL ?? "gpt-5.6"} -api_key: ${secret.OPENAI_API_KEY!} -base_url: ${env.OPENAI_BASE_URL ?? "https://api.openai.com/v1"} ---- -``` - -这里: - -```text -${secret.OPENAI_API_KEY!} -``` - -表示: - -> 这个值必须存在。 - -如果没有: - -```text -ConfigurationError: -required binding secret.OPENAI_API_KEY is missing -``` - -而不是运行到 HTTP 请求才发现: - -```text -401 Unauthorized -``` - -这会让 Marqdo 的错误体验好很多。 - ---- - -# 8. Binding 应该在执行前完成 - -这是一个非常重要的架构决定。 - -不要: - -```text -执行程序 - ↓ -遇到 ${env.X} - ↓ -临时解析 -``` - -而应该: - -```text -Load Artifact - ↓ -Parse Metadata - ↓ -Resolve Bindings - ↓ -Validate Metadata - ↓ -Create Runtime Object - ↓ -Execute -``` - -也就是说: - -```text -.mq.md - ↓ -Artifact - ↓ -Bound Artifact -``` - -例如: - -```yaml ---- -type: llm -model: ${env.OPENAI_MODEL ?? "gpt-5.6"} ---- -``` - -加载以后内部应该变成: - -```text -model = "gpt-5.6" -``` - -而不是每次访问: - -```text -model - ↓ -去环境变量查询 -``` - -这样有三个好处: - -1. 配置确定性更强 -2. 性能更好 -3. Debug 可以知道最终配置是什么 - ---- - -# 9. 但是 Secret 不应该真的被普通内部结构展开 - -这里可以做得非常漂亮。 - -普通变量: - -```text -${env.OPENAI_MODEL} -``` - -解析成: - -```text -Value("gpt-5.6") -``` - -Secret: - -```text -${secret.OPENAI_API_KEY} -``` - -解析成: - -```text -SecretValue(...) -``` - -而不是普通 String。 - -于是 Runtime 可以知道: - -```text -Value -SecretValue -``` - -是两种不同类型。 - -例如: - -```text -print(api_key) -``` - -自动输出: - -```text -<secret> -``` - -而: - -```text -HTTP Authorization -``` - -可以正常得到真正值。 - -这实际上可以成为 Marqdo 类型系统的一部分: - -```text -String -Secret -Number -Boolean -Table -Document -... -``` - ---- - -# 10. Metadata 本身也应该支持类型 - -我建议不要把 front matter 看成: - -```text -YAML → Map<String,String> -``` - -而是: - -```text -Metadata → Marqdo Value -``` - -所以: - -```yaml ---- -type: llm -temperature: 0.2 -stream: false -max_tokens: 2048 -tags: - - ai - - llm ---- -``` - -应该保留类型: - -```text -type String -temperature Number -stream Boolean -max_tokens Number -tags List -``` - -而: - -```yaml -model: ${env.OPENAI_MODEL} -``` - -解析之后也是: - -```text -String -``` - ---- - -# 11. 更进一步:Binding 应该允许转换 - -例如: - -```yaml ---- -max_tokens: ${env.MAX_TOKENS} -temperature: ${env.TEMPERATURE} -stream: ${env.STREAM} ---- -``` - -环境变量天然都是字符串。 - -但 Marqdo 应该允许: - -```text -${env.MAX_TOKENS -> int} -${env.TEMPERATURE -> float} -${env.STREAM -> bool} -``` - -或者更简洁: - -```text -${int(env.MAX_TOKENS)} -${float(env.TEMPERATURE)} -${bool(env.STREAM)} -``` - -我个人更倾向后者: - -```text -${int(...)} -``` - -因为它以后可以扩展。 - ---- - -# 12. 这实际上可以成为 Marqdo 的 Configuration Language - -例如: - -```yaml ---- -type: llm - -backend: openai-compatible - -model: ${env.OPENAI_MODEL ?? "gpt-5.6"} - -base_url: - ${env.OPENAI_BASE_URL ?? "https://api.openai.com/v1"} - -api_key: - ${secret.OPENAI_API_KEY!} - -temperature: - ${float(env.OPENAI_TEMPERATURE ?? "0.2")} - -max_tokens: - ${int(env.OPENAI_MAX_TOKENS ?? "4096")} ---- -``` - -这已经不是简单的 YAML 了。 - -它实际上是: - -> **Marqdo Artifact Declaration Language** - ---- - -# 13. 我建议增加 `config` 命名空间 - -还有一个很重要的场景: - -多个 `.mq.md` 共享配置。 - -例如: - -```text -config.mq.md -``` - -```yaml ---- -type: config - -llm: - model: ${env.OPENAI_MODEL ?? "gpt-5.6"} - base_url: ${env.OPENAI_BASE_URL ?? "..."} ---- -``` - -其他文件: - -```yaml ---- -type: llm -config: ./config.mq.md ---- -``` - -或者: - -```yaml ---- -type: llm -model: ${config.llm.model} -base_url: ${config.llm.base_url} ---- -``` - -于是: - -```text -Environment - ↓ -Config - ↓ -Artifact -``` - -形成配置层级。 - ---- - -# 14. 我甚至建议支持配置覆盖 - -这是 Agent Framework 非常需要的。 - -例如: - -```yaml ---- -type: llm -model: ${config.llm.model ?? "gpt-5.6"} ---- -``` - -运行: - -```text -marqdo run task.mq.md --model=gpt-5.6-mini -``` - -那么: - -```text -arg.model -``` - -可以覆盖: - -```text -config.llm.model -``` - -形成: - -```text -Priority - -explicit argument - ↓ -artifact metadata - ↓ -config - ↓ -environment - ↓ -default -``` - -但这里我要特别建议: - -> **不要让环境变量静默覆盖 Artifact 明确写出的配置。** - -否则: - -```yaml -model: gpt-5.6 -``` - -用户看到的是 gpt-5.6, - -机器却因为: - -```text -OPENAI_MODEL=gpt-5-mini -``` - -实际运行了另一个模型。 - -这是非常危险的可复现性问题。 - ---- - -# 15. 所以我建议明确一个 Resolution Policy - -例如: - -```text -explicit metadata - > -argument - > -config - > -environment - > -default -``` - -或者如果 CLI 参数需要最高优先级: - -```text -CLI argument - > -explicit metadata - > -config - > -environment - > -default -``` - -我更推荐: - -```text -CLI - ↓ -Artifact - ↓ -Config - ↓ -Environment - ↓ -Default -``` - -因为: - -```text -Artifact = 文档作者意图 -Environment = 运行环境 -``` - -这符合“代码即文档”的哲学。 - ---- - -# 16. 但环境变量应该允许显式 opt-in 覆盖 - -有时候部署环境确实需要: - -```text -production - ↓ -覆盖 model -``` - -所以可以提供: - -```yaml ---- -type: llm - -model: - value: gpt-5.6 - override: env.OPENAI_MODEL ---- -``` - -或者更简单: - -```yaml ---- -type: llm -model: gpt-5.6 -model_override: ${env.OPENAI_MODEL} ---- -``` - -这样**覆盖是显式的**,而不是隐式的。 - ---- - -# 17. 一个非常重要的设计:Binding 不应该只能出现在 Metadata - -既然这是核心语言能力,我建议: - -```text -${...} -``` - -可以在整个 Marqdo 中出现。 - -例如: - -```markdown -# Hello ${env.USER_NAME} - -Current model: ${config.llm.model} -``` - -代码中: - -```marqdo -**path = ${env.DATA_PATH}** -``` - -参数中: - -```marqdo -**answer = > llm.ask prompt=${file.prompt}** -``` - -表格中: - -```markdown -| model | ${env.OPENAI_MODEL} | -``` - -所以它真正是: - -> **Marqdo Interpolation / Binding** - -而不是: - -> YAML Environment Variable Feature。 - ---- - -# 18. 但要区分「文本插值」和「值绑定」 - -这是语言设计中很容易踩坑的地方。 - -例如: - -```text -"model=${env.OPENAI_MODEL}" -``` - -这是: - -```text -String interpolation -``` - -而: - -```yaml -model: ${env.OPENAI_MODEL} -``` - -应该是: - -```text -Value binding -``` - -两者不能完全一样。 - -比如: - -```yaml -temperature: ${env.TEMPERATURE} -``` - -如果环境变量是: - -```text -0.2 -``` - -应该得到: - -```text -Number(0.2) -``` - -而不是: - -```text -String("0.2") -``` - -因此我建议: - -```text -${...} -``` - -本身是一个 **Expression**。 - -当它独占一个 value 时: - -```text -Value Binding -``` - -当它出现在字符串内部: - -```text -Interpolation -``` - -例如: - -```text -${env.USER} -``` - -→ 原始值 - -而: - -```text -"Hello ${env.USER}" -``` - -→ String - -这会非常干净。 - ---- - -# 19. Binding 可以进一步支持文件 - -这对于 `.mq.md` 非常有意义。 - -例如: - -```yaml ---- -system_prompt: ${file.system_prompt} -knowledge: ${file.knowledge} ---- -``` - -甚至: - -```text -${file("./knowledge.md")} -``` - -这样: - -```text -Document - ↓ -Metadata - ↓ -External Artifact -``` - -天然形成知识组合。 - -这和你: - -> Executable Documents → Executable Knowledge Bases - -的研究方向又连接起来了。 - ---- - -# 20. 我建议最终定义 6 个核心 Binding Source - -第一版其实不用太多: - -```text -env -arg -sys -file -config -secret -``` - -分别: - -| Namespace | 意义 | -| --------- | ---------------- | -| `env` | 环境变量 | -| `arg` | CLI / Runtime 参数 | -| `sys` | Runtime 系统信息 | -| `file` | 外部文件 | -| `config` | 配置 Artifact | -| `secret` | Secret Provider | - -以后再扩展: - -```text -artifact -context -memory -agent -``` - -但第一版不要过度设计。 - ---- - -# 21. 我还建议把环境变量的“读取”从 `sys` 中移出来 - -你现在: - -```marqdo -sys.env_get -``` - -这是我认为非常值得改的地方。 - -`sys` 应该是: - -```text -sys.cwd -sys.platform -sys.time -sys.argv -``` - -而: - -```text -env -``` - -应该成为语言 Runtime 的 Binding Source。 - -于是用户不应该写: - -```marqdo -**api_key = > sys.env_get name="OPENAI_API_KEY"** -``` - -而应该: - -```yaml -api_key: ${secret.OPENAI_API_KEY!} -``` - -甚至程序里: - -```marqdo -**path = ${env.DATA_PATH}** -``` - -这会让代码明显干净很多。 - ---- - -# 22. 对你的 `llm.mq.md`,最终可以简化成非常漂亮的东西 - -例如: - -```yaml ---- -type: llm - -backend: openai-compatible - -model: ${env.OPENAI_MODEL ?? "gpt-5.6"} - -base_url: - ${env.OPENAI_BASE_URL ?? "https://api.openai.com/v1"} - -api_key: - ${secret.OPENAI_API_KEY!} ---- -``` - -然后下面: - -```marqdo -**## ask** - -Ask the configured language model. - -+ `prompt` - -**result = > self.complete prompt=`prompt`** - -*[text](result)* -``` - -这里 `complete` 只是 backend implementation。 - -用户层: - -```marqdo -**answer = > llm.ask** -``` - -就已经足够。 - ---- - -# 23. 最关键的是:Metadata 本身可以成为可执行配置 - -这一步我认为特别适合 Marqdo。 - -例如: - -```yaml ---- -type: llm - -backend: ${config.llm.backend ?? "openai-compatible"} - -model: ${arg.model ?? env.OPENAI_MODEL ?? "gpt-5.6"} - -temperature: ${float( - arg.temperature ?? - env.OPENAI_TEMPERATURE ?? - "0.2" -)} - -api_key: ${secret.OPENAI_API_KEY!} ---- -``` - -这已经具备: - -```text -Declaration -+ -Configuration -+ -Binding -+ -Default -+ -Type conversion -``` - -因此 `.mq.md` 不再只是: - -```text -Markdown + YAML -``` - -而是: - -> **Self-contained Executable Artifact** - ---- - -# 24. 我建议给这个机制一个正式名字 - -不要叫: - -> Environment Variables - -太窄。 - -我比较推荐: - -### **Marqdo Binding** - -语法: - -```text -${expression} -``` - -文档里可以称: - -> **Binding Expression** - -例如: - -```text -${env.OPENAI_API_KEY} -``` - -是: - -> Environment Binding - -```text -${config.llm.model} -``` - -是: - -> Configuration Binding - -```text -${secret.OPENAI_API_KEY} -``` - -是: - -> Secret Binding - -这套命名以后非常容易扩展。 - ---- - -# 25. 最终 Runtime 架构 - -我建议把它设计成: - -```text - .mq.md - │ - ▼ - ┌──────────────┐ - │ Metadata │ - │ + Body │ - └──────┬───────┘ - │ - ▼ - Binding Resolver - │ - ┌──────────────┼──────────────┐ - ▼ ▼ ▼ - env config secret - │ │ │ - └──────────────┼──────────────┘ - ▼ - Bound Artifact - │ - ┌───────┴────────┐ - ▼ ▼ - Runtime Document - │ - ▼ - Execution -``` - -然后最重要的一条: - -```text -Artifact Source - ↓ -Binding Resolution - ↓ -Execution -``` - -而不是: - -```text -Execution - ↓ -到处 getenv() -``` - ---- - -# 26. 这甚至可以成为 Marqdo 的一个语言卖点 - -如果未来论文里描述,我会把它归到: - -> **Executable Configuration** - -而不是简单的: - -> Environment Variable Support - -因为传统配置通常是: - -```text -Code - + -Config - + -Environment -``` - -三套东西。 - -Marqdo 可以变成: - -```text -Executable Artifact - │ - ├── Logic - ├── Knowledge - ├── Configuration - └── Environment Bindings -``` - -所以一个 `.mq.md` 可以真正做到: - -> **携带自己的执行语义,同时声明自己依赖哪些外部运行时资源。** - -这和你整个“Executable Document → Executable Knowledge Base”的方向是高度一致的。 - ---- - -## 我会把第一版核心规范收敛成这 7 条 - -```text -1. --- ... --- 是 Marqdo Artifact Metadata - -2. Metadata value 可以包含 ${expression} - -3. ${namespace.name} 是 Binding Expression - -4. 第一版 namespace: - env / arg / sys / config / file / secret - -5. Binding 在 Artifact Load 阶段统一解析 - -6. 独占 value 时保留原始类型; - 出现在字符串中时进行 interpolation - -7. Resolution: - CLI → Artifact → Config → Environment → Default -``` - -然后再加: - -```text -${expr ?? default} -${expr!} -${int(expr)} -${float(expr)} -${bool(expr)} -``` - -这就已经是一套相当完整的语言特性了。 - -而且我认为**最值得做的不是“让 LLM 配置更方便”,而是把它正式确立为 Marqdo 的 `Binding` 机制**。这样未来 `llm`、`agent`、`database`、`network`、`skill`、`knowledge` 都能统一使用同一套核心语法,而不会每个扩展自己发明一套环境变量读取方式。 diff --git a/doc/next/007.md b/doc/next/007.md deleted file mode 100755 index f861a2d..0000000 --- a/doc/next/007.md +++ /dev/null @@ -1,2182 +0,0 @@ ---- -type: discussion -status: superseded-by-design -formal: doc/design/ext-web-artifact.md -adr: doc/adr/0007-web-document-endpoint.md ---- - -> **正式规范已落地**:讨论收敛见 [ext-web-artifact.md](../design/ext-web-artifact.md) 与 [ADR 0007](../adr/0007-web-document-endpoint.md)。下文保留为设计推演,**勿**按未收敛的备选目录(§三 `ext/db`)实现。 - -我看完这份 `ext/web/web.mq.md` 后,结论比较明确: - -> **它已经是一个功能非常丰富的 Web Runtime,但从 Marqdo 的“代码即文档”哲学来看,目前最大的风险不是功能不够,而是“功能不断堆叠后,语言抽象开始被实现细节反向塑形”。** - -尤其是你之前刚刚确定的 `llm.mq.md` 重构方向,我认为这份 `web.mq.md` 也应该做同等级别的重新抽象。 - -目前它已经不只是一个“网络扩展库”,而实际上混合了: - -```text -Web UI -HTTP Server -Routing -HTTP API -WebSocket -Database -Transaction -Form -Authentication -OIDC -RBAC -Tenant -Cache -Object Storage -Upload -Static Assets -RSS -Sitemap -Proxy -MCP-ish invoke -``` - -例如 `# db` 已经拥有完整 CRUD、事务、迁移、FTS;`# app` 又包含 route、static、middleware、proxy、invoke、WebSocket、auth 等。 - -这说明它**功能成熟度很高,但架构边界已经开始变模糊**。 - -下面我分层讲。 - ---- - -# 一、先给它一个总体诊断 - -我会把现在的架构画成: - -```text - ext/web/web.mq.md - │ - ┌────────────┬───────┼────────┬──────────┐ - ↓ ↓ ↓ ↓ ↓ - Page App DB Form Auth - │ │ │ │ │ - CSS/HTML Route SQL Validate OIDC - Image Proxy Txn Submit RBAC - Head WS FTS - Client Cache - Storage -``` - -问题不是它不能用。 - -问题是: - -> **`web` 已经变成了一个“小型 Web Framework”,而不是一个清晰的 Marqdo 网络抽象。** - -这两个东西在语言设计上是完全不同的。 - ---- - -# 二、我认为最严重的问题:`web` 的职责边界已经失控 - -现在: - -```text -# page -# style -# db -# txn -# form -# app -# rbac -# auth -# cache -# storage -# media -# ws -``` - -都在一个模块里。 - -尤其是: - -```text -db -txn -form -auth -rbac -cache -storage -``` - -它们本质上都可以独立存在。 - -例如 DB 有自己的: - -```text -init -insert -select -paginate -get -update -delete -exec -query -count -migrate -fts -search -transaction -``` - -这已经完全是一套数据库扩展,而不是 Web 的一个小功能。 - ---- - -# 三、我的第一条重大建议:把 `ext/web` 拆成“协议层 + 应用层” - -不要: - -```text -ext/web/web.mq.md -``` - -承载整个世界。 - -建议最终: - -```text -ext/ -├── net/ -│ ├── http.mq.md -│ ├── ws.mq.md -│ └── url.mq.md -│ -├── web/ -│ ├── request.mq.md -│ ├── response.mq.md -│ ├── route.mq.md -│ ├── page.mq.md -│ └── html.mq.md -│ -├── db/ -│ ├── db.mq.md -│ └── txn.mq.md -│ -├── auth/ -│ ├── auth.mq.md -│ ├── oidc.mq.md -│ └── rbac.mq.md -│ -├── storage/ -│ └── storage.mq.md -│ -└── cache/ - └── cache.mq.md -``` - -然后: - -```text -ext/web/web.mq.md -``` - -只做一个 facade: - -```text -web - ├── request - ├── response - ├── route - └── page -``` - ---- - -# 四、但是这里还有一个更深的问题 - -即使拆文件,你现在的设计思维仍然是: - -```text -Object - ↓ -Method - ↓ -Native Plugin -``` - -例如: - -```text -page - ↓ -compose_main - ↓ -web_compose_main -``` - -```text -db - ↓ -select - ↓ -web_db_select -``` - -```text -app - ↓ -route - ↓ -web_app_route -``` - -这种设计实际上非常接近: - -> Python class wrapper / SDK wrapper。 - -这就是我认为当前网络库最值得改变的地方。 - ---- - -# 五、Marqdo 不应该只是“把 Web Framework API 翻译成 Marqdo” - -应该变成: - -> **Web 本身就是 Marqdo Document 的一种结构。** - -这才是你真正的优势。 - -现在: - -```marqdo -**page = > web.page** -**page.route path="/about"** -**page.compose_main main=`main`** -``` - -还是典型 imperative API。 - -我更希望: - -```markdown ---- -type: web -route: /about ---- - -# About Marqdo - -Marqdo is an executable document language. - -## Features - -- Executable documents -- Executable knowledge -- AI-native programming -``` - -这本身就已经是一个 Web Page。 - -然后: - -```text -.mq.md - ↓ -Artifact - ↓ -Web Page - ↓ -HTTP Route -``` - -这才是: - -> **代码即文档** - -真正开始发挥作用的地方。 - ---- - -# 六、你现在其实已经有这个方向,只是没有彻底贯彻 - -比如 `compose_intro`: - -```text -|属性|值|样式| -``` - -以及: - -```text -kicker -title -lede -claim -step -mount -html -``` - -这些已经明显是在尝试: - -> **用 Markdown Table 描述页面结构。** - -这个方向我认为是对的。 - -但是现在的问题是: - -> **Table 只是输入参数,而不是 Web 的真正声明式 AST。** - ---- - -# 七、这是整个网络库最大的“代码即文档”问题之一 - -例如: - -```text -compose_main(main) -``` - -要求: - -```text -|属性|值|样式| -``` - -或者: - -```text -|front|back|css| -``` - -而: - -```text -compose_intro -``` - -又有: - -```text -|属性|值|样式| -``` - -或者: - -```text -|front|back|style| -``` - -再加: - -```text -kicker -title -lede -claim -step -mount -html -``` - -然后样式还会解析: - -```text -shell.* -``` - - - -这实际上形成了一个**隐藏 DSL**。 - -问题是这个 DSL 并没有成为 Marqdo 的正式语言结构。 - -于是作者必须记: - -```text -compose_main 的 table 是什么形状? -compose_intro 有哪些 slot? -style 怎么解析? -claim 怎么分组? -mount 怎么工作? -``` - -这就是: - -> **代码表面很短,语义实际上很复杂。** - -这是代码即文档最应该避免的情况。 - ---- - -# 八、我的建议:Table 应该成为“数据”,而不是“半隐藏 DSL” - -你之前说: - -> network extension library 使用 table 作为 syntax。 - -这个方向我其实仍然支持。 - -但应该有一个原则: - -> **Table 表达“数据结构”;不要让每个函数自己创造一套 Table 语法。** - -比如: - -```markdown -| slot | text | style | -|------|------|-------| -| kicker | AI Native | eyebrow | -| title | Marqdo | title | -| lede | Executable Documents | lede | -``` - -这很好。 - -因为 schema 是稳定的。 - -但: - -```text -|front|back|css| -``` - -再: - -```text -|属性|值|样式| -``` - -再: - -```text -|src|style| -``` - -再: - -```text -|组件|样式| -``` - -就开始碎片化。 - ---- - -# 九、我建议建立统一的 `View` / `Node` 数据模型 - -例如: - -```text -Web Node -``` - -统一: - -```text -|type|slot|value|attrs|style| -``` - -例如: - -```markdown -| type | slot | value | attrs | style | -|-------|--------|------------------------|-------|---------| -| text | kicker | AI Native | | eyebrow | -| title | title | Marqdo | | title | -| text | lede | Executable Documents | | lede | -| link | action | Read More | /docs | button | -``` - -然后: - -```text -page.render nodes -``` - -而不是: - -```text -compose_main -compose_intro -compose_list -compose_nav_brand -... -``` - -这会大幅降低 API 数量。 - ---- - -# 十、第二个非常严重的问题:`page` 已经开始承担太多状态 - -现在: - -```text -page - ├── title - ├── intro - ├── shell_css - ├── layout - ├── asset_version - ├── components - ├── main - ├── query - ├── order - ├── link_prefix - ├── css - ├── detail - ├── chrome - ├── meta - ├── head - ├── images - ├── paginate - ├── form - ├── client - ... -``` - -这实际上是一个: - -> **God Object** - -`page` 已经同时知道: - -```text -Content -Presentation -Data -Routing -SEO -Assets -Forms -Client Runtime -Database Query -Authentication -``` - -这是未来维护最大的风险之一。 - ---- - -# 十一、建议把 Page 变成纯 Artifact - -理想: - -```text -Page -├── document -├── metadata -├── view -├── data -└── route -``` - -而不是: - -```text -Page - ├── 20+ mutation methods -``` - -例如: - -```markdown ---- -type: page -route: /posts/{slug} - -data: - source: posts - where: - slug: "{slug}" - -view: - layout: article - title: "{title}" ---- -``` - -正文就是: - -```markdown -# {{title}} - -{{body}} -``` - -这比: - -```text -page.query -page.order -page.detail -page.compose_main -page.compose_intro -page.link_prefix -``` - -更符合 Marqdo。 - ---- - -# 十二、第三个问题:Route 设计太弱 - -现在 route: - -```text -app.route - path - page -``` - - - -但真正 Web Route 应该是: - -```text -Route -├── path -├── method -├── handler -├── middleware -├── auth -├── input -├── output -└── errors -``` - -而现在这些能力被拆到了: - -```text -route -invoke -gate -auth -json -proxy -route_ws -mount_form -``` - -于是一个完整 endpoint 需要去多个地方寻找语义。 - ---- - -# 十三、我建议统一成 Endpoint - -这是我认为整个网络库最值得重构的 API。 - -例如: - -```markdown -## get_post - ---- -route: /post/{slug} -method: GET ---- - -**post = > db.posts.get slug={slug}** - -*post* -``` - -或者: - -```markdown -## create_post - ---- -route: /api/posts -method: POST -body: json -return: json -auth: member ---- - -**post = > db.posts.insert body** - -*post* -``` - -于是: - -```text -Endpoint -``` - -本身就是: - -```text -Documentation -+ -Route -+ -Handler -+ -Input schema -+ -Output schema -+ -Authorization -``` - -这才是真正的: - -> **代码即文档。** - ---- - -# 十四、现在的 `invoke` 其实已经暴露出正确方向 - -你现在: - -```text -## invoke - -path -fn -method -body -return -``` - -并且: - -```text -fn must be lib.member -``` - - - -这其实已经很接近我说的 Endpoint。 - -问题是: - -> 它被设计成 `app.configure(invoke=table)` 的一项功能,而不是 Web 的一等公民。 - -应该反过来。 - ---- - -# 十五、第四个问题:`configure()` 太重 - -现在: - -```text -app.configure( - cors - security - compress - body_limit - json - access_log - cache_control - proxy - invoke -) -``` - - - -这在工程上很方便。 - -但在语言设计上非常危险。 - -因为它成为: - -> **“所有没有地方放的 Web 功能都放进去的垃圾抽屉。”** - -今天: - -```text -cors -security -compress -``` - -明天可能: - -```text -rate_limit -csrf -metrics -tracing -gzip -brotli -timeout -upload -webhook -grpc -... -``` - -最终: - -```text -configure(...) -``` - -会变成一个 30 参数函数。 - ---- - -# 十六、建议:Middleware 应该成为一等对象 - -应该: - -```text -app - ↓ -middleware - ↓ -route -``` - -例如: - -```markdown -## security - -| header | value | -|--------|-------| -| X-Content-Type-Options | nosniff | -| Referrer-Policy | strict-origin | -``` - -然后: - -```text -app.use security -``` - -或者: - -```text -route.use auth -route.use cors -``` - -这样: - -```text -Middleware -``` - -本身是可组合 Artifact。 - ---- - -# 十七、第五个问题:大量“隐式路由”破坏代码即文档 - -例如 `listen` 自动提供: - -```text -/ -_/part/{id} -{path}/_part/{id} -_/form/{id} -static -admin -upload -download -WebSocket -RSS -sitemap -robots -redirect -proxy -invoke -404 -``` - - - -这对框架用户很方便。 - -但对 Marqdo 来说有一个问题: - -> **打开一个 `.mq.md`,你无法完全从源码看出它暴露了哪些 HTTP surface。** - -这和: - -> Code is Documentation - -直接冲突。 - ---- - -# 十八、我的建议:区分 `implicit` 和 `declared` - -例如: - -```yaml ---- -type: web -routes: - - / - - /post/{slug} ---- -``` - -Runtime 可以自动生成: - -```text -/_part -/_form -``` - -但这些应该属于: - -```text -system routes -``` - -而用户 route: - -```text -declared routes -``` - -两者在 introspection 中明确区分: - -```text -web.inspect() -``` - -返回: - -```text -declared: - GET / - GET /post/{slug} - -system: - GET /_part/* - GET /_form/* -``` - -这样既保留便利,又保持可解释性。 - ---- - -# 十九、第六个问题:`db` 和 Web 的绑定太紧 - -现在: - -```text -page.query -page.order -page.paginate -compose_list -form.submit -json route -``` - -都直接知道 DB。 - -这让: - -```text -Web -↔ DB -``` - -高度耦合。 - - - -但 Marqdo 应该允许: - -```text -Web - ↓ -Data Source - ├── DB - ├── File - ├── API - ├── Knowledge Base - └── Agent -``` - -例如: - -```text -page.data = posts -``` - -至于: - -```text -posts -``` - -到底来自: - -```text -db -``` - -还是: - -```text -knowledge -``` - -不应该由 page 决定。 - ---- - -# 二十、这和你的 AI-native 方向尤其重要 - -未来很可能出现: - -```text -Page - ↓ -Data - ↓ -Agent - ↓ -Knowledge -``` - -例如: - -```markdown ---- -type: page -data: agent.search ---- -``` - -所以应该抽象: - -> **Data Provider** - -而不是: - -> `page.query` = SQL database query。 - ---- - -# 二十一、第七个问题:DB 的 `exec/query` 破坏了高级抽象 - -你有: - -```text -db.select -db.insert -db.update -... -``` - -同时又: - -```text -db.exec sql -db.query sql -``` - - - -从工程角度这很好,因为 escape hatch 很重要。 - -但在“代码即文档”的语言设计里: - -```text -db.query sql="SELECT ..." -``` - -又退回: - -> “请让我写数据库实现细节。” - -我建议保留,但明确为: - -```text -db.raw.query -db.raw.exec -``` - -这样 API 语义就很清楚: - -```text -db.query -``` - -= declarative data query - -```text -db.raw.query -``` - -= escape hatch - -这非常重要。 - ---- - -# 二十二、第八个问题:事务设计不像一个语言原语 - -现在: - -```text -db.事务 - ↓ -txn - ↓ -insert -select -update -... - ↓ -提交 -回滚 -``` - - - -它是典型数据库 SDK。 - -但 Marqdo 可以做得漂亮很多: - -```text -**transaction** - **db.insert ...** - **db.update ...** -``` - -或者: - -```text -**txn = > db.transaction** - -**txn.insert ...** -**txn.update ...** - -*txn.commit* -``` - -甚至最终: - -```text -**db.transaction** - ... -``` - -让事务成为代码块/执行上下文,而不是用户管理一个 opaque handle。 - ---- - -# 二十三、第九个问题:WebSocket API 还是传统 API - -现在: - -```text -route_ws - path - echo - mode - room_key - on_message - presence - require_auth -``` - - - -这其实已经相当丰富。 - -但: - -```text -echo -broadcast -room -drain -``` - -都是 runtime mode。 - -我建议统一成: - -```text -channel -``` - -例如: - -```markdown -## live - ---- -type: channel -path: /live -mode: broadcast -auth: member ---- -``` - -然后: - -```text -## on_message -... -``` - -于是 WebSocket 不再是 `route_ws` 的特殊 API,而成为: - -> **Realtime Endpoint** - -以后还可以自然扩展: - -```text -SSE -WebSocket -WebTransport -``` - -都属于: - -```text -stream endpoint -``` - ---- - -# 二十四、第十个问题:`storage`、`cache` 其实已经证明你需要统一 Resource 抽象 - -你现在: - -```text -# cache -``` - -支持: - -```text -memory: -redis:// -``` - -以及: - -```text -# storage -``` - -支持: - -```text -file: -s3:// -``` - -这里其实已经非常接近你之前讨论的: - -> **Metadata + Binding** - -我建议以后统一: - -```text -Resource -``` - -例如: - -```yaml ---- -type: storage -backend: s3 -url: ${env.STORAGE_URL} ---- -``` - -或者: - -```yaml ---- -type: cache -backend: redis -url: ${secret.REDIS_URL} ---- -``` - -这和我们刚才设计的 Binding 完美结合。 - ---- - -# 二十五、第十一个问题:中英文 API 混用会伤害语言一致性 - -例如: - -```text -db.paginate -``` - -但参数: - -```text -跳过 -``` - -事务: - -```text -事务 -提交 -回滚 -``` - -同时又有: - -```text -auth -session_ttl -login_redirect -``` - - - -我理解为什么这么设计: - -> Marqdo 希望自然语言友好。 - -这个方向没问题。 - -但我建议: - -### 核心语义只有一个 canonical name - -例如: - -```text -transaction -commit -rollback -offset -``` - -中文可以作为: - -```text -alias -``` - -而不是让底层 ABI 同时拥有两套概念。 - -即: - -```text -提交 → commit -回滚 → rollback -跳过 → offset -``` - -这样: - -```text -AST -IR -Plugin ABI -Documentation -``` - -全都只有一个 canonical vocabulary。 - ---- - -# 二十六、第十二个问题:`ensure_plugin` 重复暴露了 Runtime 边界 - -文件里大量: - -```text -> ensure_plugin -``` - -然后: - -```text -plugin.native_path -plugin.load -``` - -例如 DB、Form、App 等都依赖这个模式。 - -这说明: - -> Native plugin lifecycle 正在侵入 extension language。 - -用户其实不应该关心: - -```text -ABI v2 -native_path -plugin.load -``` - -这应该由: - -```text -import ext:web -``` - -自动处理。 - ---- - -# 二十七、建议:Import 就意味着 Capability - -例如: - -```marqdo -import web:ext/web/web.mq.md -``` - -Runtime 自动: - -```text -resolve - ↓ -load - ↓ -initialize - ↓ -bind -``` - -如果缺插件: - -```text -CapabilityError -web backend unavailable -install: ... -``` - -而不是 extension 自己每个对象调用: - -```text -ensure_plugin -``` - -这样才符合: - -> **import 是声明依赖,不是调用初始化函数。** - ---- - -# 二十八、第十三个问题:Raw HTML/CSS 是一个必要的逃生舱,但现在太容易成为第二套语言 - -例如: - -```text -page.css -``` - -直接接收 raw CSS。 - -以及: - -```text -chrome(nav_html, footer_html) -``` - -直接允许 raw HTML。 - -这当然需要。 - -但是我建议严格分层: - -```text -Declarative HTML - ↓ -Marqdo DOM - ↓ -raw HTML escape hatch -``` - -而不是: - -```text -Marqdo tables - + -raw HTML - + -CSS -``` - -三种并列模式。 - ---- - -# 二十九、建议正式建立 DOM Artifact - -比如: - -```text -node -├── element -├── attrs -├── children -└── text -``` - -那么: - -```markdown -# Hello -``` - -天然可以变成: - -```text -Document - ↓ -DOM -``` - -然后: - -```text -web.render -``` - -负责: - -```text -DOM → HTML -``` - -这样未来: - -```text -SSR -Browser WASM -Email -PDF -Accessibility tree -``` - -都可以复用。 - ---- - -# 三十、你的 `client_embed` 也值得重新设计 - -现在: - -```text -client_embed -bridge -wasm -source -boot -``` - -并且生成: - -```html -<script type="module" ...> -``` - - - -这实际上已经不是简单 Web Server,而是在做: - -> **Marqdo Browser Runtime** - -我建议不要把它藏在 `web` 的一个 helper 里。 - -应该明确: - -```text -ext/browser -``` - -或者: - -```text -runtime/browser -``` - -形成: - -```text -Marqdo - ├── Server Runtime - └── Browser Runtime -``` - -这会比现在清晰得多。 - ---- - -# 三十一、一个非常关键的问题:API 返回值没有统一的 Result 模型 - -例如: - -```text -db.select -``` - -返回 rows。 - -```text -count -``` - -直接返回 number。 - -```text -auth.login -``` - -返回: - -```text -{ok, session_id, username, role} -``` - -```text -storage.put -``` - -又是另一种。 - -```text -websocket -``` - -又是另一种。 - -这种设计在普通 SDK 里没问题。 - -但 Marqdo 要成为: - -> AI-native programming language - -就需要让 Agent 能理解: - -```text -what did this operation produce? -``` - ---- - -# 三十二、建议建立统一的 `Result` - -不是说所有东西都必须包成: - -```text -{ok, value, error} -``` - -而是建立标准 Result protocol: - -```text -Result -├── value -├── error -├── metadata -└── status -``` - -例如: - -```text -db.select - → rows - -HTTP - → response - -LLM - → result - -Storage - → object - -``` - -它们都可以有统一的: - -```text -result.status -result.value -result.error -``` - -这样 Agent、日志、trace、writeback 可以统一处理。 - ---- - -# 三十三、我认为你这份库最大的“隐性问题”是:它在不断制造“特殊情况” - -从代码可以看到很多: - -```text -如果 detail -如果 target -如果 mount -如果 shell_css -如果 layout -如果 media -如果 when -如果 auth -如果 guest -如果 hide -如果 form -如果 client -如果 route param -如果 dynamic route -如果 db -如果 admin -... -``` - -例如 `compose_components` 本身就包含: - -```text -media -when -auth -guest -hide -``` - - - -这说明 API 的核心抽象还不够强。 - -当抽象不够强时,框架就会: - -> 每增加一个需求 → 增加一个 flag。 - -这就是未来最大的技术债。 - ---- - -# 三十四、所以我建议从“Feature API”转成“Composable Artifact” - -这是我认为最关键的重构方向。 - -现在: - -```text -page.compose_intro() -page.compose_main() -page.compose_list() -page.compose_form() -page.compose_nav_brand() -page.compose_client() -``` - -应该逐渐变成: - -```text -page - ├── head - ├── body - │ ├── node - │ ├── list - │ ├── form - │ └── component - └── client -``` - -即: - -> **结构组合,而不是功能函数堆积。** - ---- - -# 三十五、我会重新设计整个 `ext/web` - -最终结构建议: - -```text -ext/web/ -│ -├── web.mq.md -│ -├── page.mq.md -├── route.mq.md -├── component.mq.md -├── dom.mq.md -│ -└── client.mq.md -``` - -然后依赖: - -```text -ext/net/ -├── http.mq.md -├── websocket.mq.md -└── url.mq.md - -ext/data/ -├── db.mq.md -├── cache.mq.md -└── storage.mq.md - -ext/security/ -├── auth.mq.md -├── oidc.mq.md -└── rbac.mq.md -``` - ---- - -# 三十六、最核心的 `web` API 可以缩到非常少 - -我甚至认为: - -```text -web.page -web.route -web.serve -web.render -``` - -已经可以覆盖绝大部分。 - ---- - -# 三十七、理想的 Marqdo Web 应用 - -我希望用户最终能写成: - -```markdown ---- -type: web -title: Marqdo Blog -route: / -data: - source: posts - order: -created_at ---- - -# Marqdo - -Welcome to the executable web. - -## Posts - -| title | href | date | -|-------|------|------| -| ... | ... | ... | -``` - -然后: - -```text -marqdo run site.mq.md -``` - -直接得到: - -```text -Document - ↓ -Data - ↓ -Page - ↓ -Route - ↓ -HTTP Server -``` - -用户不需要理解: - -```text -web_page_new -web_compose_main -web_page_query -web_page_order -web_app_route -web_app_listen -``` - ---- - -# 三十八、Dynamic Route 也可以自然成为文档 - -例如: - -```markdown ---- -type: web -route: /post/{slug} -method: GET -data: - source: posts - where: - slug: "{slug}" ---- - -# {title} - -{body} -``` - -这已经同时表达: - -```text -Route -Query -View -Content -``` - -而现在这些能力分散在: - -```text -route -page.query -page.detail -compose_main -``` - -中。 - ---- - -# 三十九、API Endpoint 更应该成为 `.mq.md` 本身 - -例如: - -```markdown ---- -type: endpoint -method: POST -path: /api/posts -request: json -response: json -auth: member ---- - -**post = > db.posts.insert row=`body`** - -*post* -``` - -这就是我认为真正属于 Marqdo 的 Web API。 - -它同时是: - -```text -Documentation -+ -Implementation -+ -Schema -+ -Route -+ -Authorization -``` - -而这恰恰就是你一直强调的: - -> **代码即文档。** - ---- - -# 四十、最后给你一个我认为比较卓越的整体架构 - -我会把现在的: - -```text -ext/web/web.mq.md -``` - -重构成: - -```text - MARQDO - │ - Executable Document - │ - ┌──────────────┼──────────────┐ - │ │ │ - Document Endpoint Resource - │ │ │ - ↓ ↓ ↓ - DOM HTTP Route DB/Cache - │ │ Storage/LLM - │ │ │ - └──────────────┼──────────────┘ - ↓ - Web Runtime - │ - ┌─────────────┼─────────────┐ - ↓ ↓ ↓ - SSR HTTP Browser - │ │ │ - └─────────────┼─────────────┘ - ↓ - Native Backend -``` - -而核心原则只有几个: - -### ① Document 是第一等公民 - -不是: - -```text -page object -``` - -而是: - -```text -.mq.md → Page -``` - -### ② Endpoint 是第一等公民 - -不是: - -```text -app.route + app.invoke + app.gate -``` - -而是: - -```text -endpoint.mq.md -``` - -### ③ Resource 是第一等公民 - -统一: - -```text -db -cache -storage -llm -``` - -通过 metadata + binding 描述。 - -### ④ Table 是 Data,不是隐藏 DSL - -表格描述结构化数据。 - -不要每个函数再发明一套 table 方言。 - -### ⑤ Raw HTML/CSS 是 Escape Hatch - -不是第二套主要语言。 - -### ⑥ Runtime 自动处理 Native Plugin - -作者只写: - -```text -import web -``` - -不写: - -```text -ensure_plugin -native_path -plugin.load -``` - -### ⑦ Route / Middleware / Auth 都是可组合 Artifact - -而不是 `configure()` 的参数集合。 - ---- - -# 四十一、我对现有版本的评价 - -如果从**工程产品成熟度**来看,这个网络库已经很强:功能覆盖非常广,而且很多地方明显经过实际使用迭代,比如分页、表单 mount、SSE proxy、OIDC、RBAC、tenant、storage 等。 - -但如果从你现在真正想打造的 **Marqdo 语言设计** 来看,我认为它已经到了一个非常关键的节点: - -> **继续往里面加功能,会越来越像 Flask/FastAPI/Next.js 一类框架;现在停下来做一次“语言级抽象重构”,才有机会让它真正成为 Marqdo 的 Web Model。** - -尤其是这几个我认为必须优先解决: - -| 优先级 | 问题 | 建议 | -| --- | --------------------- | ----------------------------- | -| P0 | `web` 职责过度膨胀 | 拆 `net/web/data/security` | -| P0 | Endpoint 被拆成多个 API | 引入 Endpoint Artifact | -| P0 | Page 是 God Object | Page → Document + View + Data | -| P0 | Table DSL 碎片化 | 建立统一 Schema/Data Table | -| P0 | 隐式 route 太多 | declared/system route 分离 | -| P1 | `configure()` 变垃圾抽屉 | Middleware 一等公民 | -| P1 | DB 与 Web 强耦合 | Data Provider 抽象 | -| P1 | raw HTML/CSS 与 DSL 并存 | DOM Artifact + escape hatch | -| P1 | Native plugin 生命周期泄漏 | import 自动加载 | -| P1 | Result 不统一 | Result protocol | -| P2 | 中英文 API 混杂 | canonical English + alias | -| P2 | WebSocket 特殊化 | Realtime/Channel 抽象 | -| P2 | Browser WASM 混在 web | 独立 Browser Runtime | - ---- - -## 最后一个我特别想强调的判断 - -你之前提出: - -> **“表格作为 network extension 的 syntax。”** - -我现在看完这份完整实现以后,我认为**这个想法本身没有问题,甚至很可能是 Marqdo 很漂亮的设计之一;真正的问题是现在“表格是数据”与“表格是隐藏 DSL”之间没有划清边界。** - -我会把整个网络扩展的下一代设计目标定成: - -> **Document describes the page. -> Table describes the data. -> Endpoint describes the interaction. -> Metadata describes the runtime. -> Marqdo executes all of them.** - -这样你前面刚刚确定的: - -```text -${env.OPENAI_API_KEY} -${config.llm.model} -${secret.REDIS_URL} -``` - -也可以统一成为: - -> **Artifact Binding** - -最终 Marqdo 会形成非常漂亮的一套统一模型: - -```text - .mq.md - │ - ┌─────────────┼─────────────┐ - ↓ ↓ ↓ - Metadata Document Tables - │ │ │ - Binding View Data - │ │ │ - └─────────────┼─────────────┘ - ↓ - Artifact - │ - ┌────────────┼────────────┐ - ↓ ↓ ↓ - LLM Agent Web - │ │ │ - └────────────┼─────────────┘ - ↓ - Execution - ↓ - Knowledge Artifact -``` - -**这才真正把你前面 `llm`、`agent`、`network` 三个看似独立的扩展,统一到了 Marqdo 的“代码即文档 / 文档即程序 / 执行即知识”这个核心语言模型里。** diff --git a/doc/next/008.md b/doc/next/008.md deleted file mode 100755 index 0ae9ea2..0000000 --- a/doc/next/008.md +++ /dev/null @@ -1,2818 +0,0 @@ -https://github.com/cflmy/marqdo这是marqdo的仓库链接现在有了最新的变更,我需要你仔细阅读一下和OKF相关的内容,我觉得marqdo的真正优势在大规模工程化的代码生成方面,OKF能够让AI在工程中更快的得到相关工程的第一信息,尤其是现在的AI喜欢重复性造轮子,将功能类似的函数重复性的撰写这样的问题,我认为marqdo有解决这个问题的潜质,但是还不够还要继续开发,请你仔细思考,从工程的角度上,给我一份详细的优雅的方案,充分发挥marqdo代码即文档,文档即知识库的潜力 - -> **实现状态(2026-09-28)**:本文方案已落地为 **Marqdo Engineering Knowledge v1**。 -> 规范见 [`doc/design/engineering-knowledge.md`](../design/engineering-knowledge.md); -> 核心实现 `src/knowledge/`;CLI:`marqdo knowledge|find|reuse|impact|conflicts|stale|duplicate|verify`; -> Agent:`agent.preflight` / `agent_eng_*`。下文保留为设计叙事与动机,勿当作未实现清单。 - -我重新看了现在仓库主线的定位之后,我认为你的判断是对的,而且我想把这个判断再往前推一步: - -> **Marqdo 真正有机会形成差异化的地方,不是“AI 可以用 Markdown 写代码”,甚至也不只是“Markdown 是可执行知识库”,而是:让一个大型工程本身成为 AI 可查询、可验证、可复用、可演化的“可执行知识系统”,从而在代码生成前就知道“工程里已经有什么、应该复用什么、为什么不能重新造”。** - -这比“RAG + Coding Agent”要更深一层。 - -目前仓库 README 已经明确把目标定义为“代码即文档、文档即代码、文档即知识库”,并且已经有 `catalog/sync`、自动生成 `catalog.yaml` / `index.md` / `modules/*.md` 的基础设施。([GitHub][1]) -同时,新的 Agent 设计也已经明确:源码、调用位置、Skill、工作簿和写回结果都应该进入 Agent 上下文,而且成功/失败结果应该沉淀,而不是只存在于 chat transcript。([GitHub][2]) - -**现在真正缺的,是把这两个方向合成一个“工程知识编译器”。** - ---- - -# 一、我先给出我认为 Marqdo 应该最终形成的核心模型 - -我建议不要再把 Marqdo 简单理解成: - -```text -Markdown - ↓ -Programming Language - ↓ -AI Agent -``` - -而应该是: - -```text - Git Repository - │ - ┌───────────┴───────────┐ - │ │ - Source Documents - │ │ - └───────────┬───────────┘ - ↓ - Marqdo Compiler - │ - ┌──────────────┼──────────────┐ - ↓ ↓ ↓ - Executable Knowledge Catalog - Program Graph / Index - │ │ │ - └──────────────┼──────────────┘ - ↓ - Engineering KB - │ - ↓ - Coding Agent - │ - ┌──────────┼──────────┐ - ↓ ↓ ↓ - Search Reuse Generate - │ │ │ - └──────────┼──────────┘ - ↓ - Verified Change - │ - ↓ - Knowledge Update - │ - └──────→ Git -``` - -也就是说: - -> **Marqdo 不应该只是帮助 AI “写代码”,而应该帮助 AI 在写代码之前理解工程。** - -这才是大型工程场景真正困难的事情。 - ---- - -# 二、为什么“大规模工程 AI”真正的问题不是生成能力 - -现在的 Coding Agent 最大的问题往往不是: - -> “AI 不会写这个函数。” - -而是: - -> **“AI 不知道这个函数已经存在。”** - -或者更隐蔽: - -> “AI 知道有类似函数,但不知道哪个才是应该复用的。” - -再进一步: - -> “AI 找到了一个类似函数,但不知道这个函数为什么这样设计。” - -再进一步: - -> “AI 找到了正确函数,但是不知道它有哪些隐含约束。” - -例如一个大型工程里可能已经存在: - -```text -parseConfig() -loadConfig() -resolveConfig() -normalizeConfig() -mergeConfig() -validateConfig() -readConfigFile() -``` - -用户让 AI: - -> “实现一个配置加载功能。” - -普通 Coding Agent 很可能: - -```text -搜索几个文件 -↓ -发现没完全一样 -↓ -写一个新的 load_configuration() -↓ -加 300 行代码 -↓ -测试通过 -``` - -从局部看: - -> 成功。 - -从工程看: - -> **失败。** - -因为真正正确的行为可能是: - -```text -resolveConfig() - + -validateConfig() - + -已有错误处理 -``` - -AI 的核心问题其实是: - -```text -工程知识缺失 - ↓ -无法识别已有能力 - ↓ -重复实现 - ↓ -代码碎片化 - ↓ -维护成本上升 -``` - ---- - -# 三、所以我建议 Marqdo 提出一个非常明确的概念 - -## Engineering First Information - -我会把它定义成: - -> **Engineering First Information(工程第一信息)** - -也就是: - -> AI 在修改/生成代码之前,首先获得关于当前工程中已有能力、约束、依赖、约定、历史决策和可复用实现的最小充分信息。 - -这个概念非常适合成为 Marqdo 的核心论文/产品概念。 - -因为普通 RAG 是: - -```text -query - ↓ -retrieve documents - ↓ -LLM -``` - -而 Marqdo 应该是: - -```text -engineering task - ↓ -understand intent - ↓ -retrieve engineering first information - ↓ -reuse analysis - ↓ -existing capability candidates - ↓ -architecture constraints - ↓ -only then generate -``` - -区别非常大。 - ---- - -# 四、目前 Marqdo 已经走到了哪里? - -现在仓库已经有几个非常重要的基础。 - -### 1. `.mq.md` 已经是 executable artifact - -README 明确把: - -```text -叙述 -代码 -返回 -对象 -函数 -表格 -``` - -都统一在 Markdown 中。([GitHub][1]) - -这意味着 Marqdo 天生拥有: - -```text -Source -+ -Documentation -``` - -的共址关系。 - ---- - -### 2. 已经有自动 Catalog - -当前已经存在: - -```text -marqdo catalog -marqdo sync -``` - -并生成: - -```text -catalog.yaml -index.md -modules/*.md -``` - -而且 README 特别强调这些是从源码自动派生的,而不是手工维护。([GitHub][1]) - -这个非常重要。 - -因为: - -> **不要让 AI 再去“猜”项目有什么。** - -Catalog 就应该成为第一层事实来源。 - ---- - -### 3. Agent 已经开始把源码作为上下文 - -新的 Agent 设计明确要求: - -```text -源码 -调用位置 -Skill -相关写回块 -工作簿 -``` - -进入模型上下文。([GitHub][2]) - -而且新的设计已经放弃“隐藏 chat history 作为真相”,转向: - -> **文档写回 + 工作簿 = 真相。** - -([GitHub][2]) - -这个方向我认为是非常正确的。 - ---- - -# 五、但这里有一个关键缺口 - -现在的系统更接近: - -```text -Task - ↓ -Agent - ↓ -查源码 / Skill / 写回 -``` - -而我要推动它成为: - -```text -Task - ↓ -Engineering Intent - ↓ -Engineering Knowledge Resolution - ↓ -Reuse Gate - ↓ -Generate / Modify - ↓ -Verify - ↓ -Knowledge Update -``` - -也就是说: - -> **“知识检索”不能只是 Agent 的一个上下文增强功能,而应该成为代码生成的强制前置阶段。** - -这是非常重要的架构变化。 - ---- - -# 六、我建议新增一个核心层:Engineering Knowledge Compiler - -可以简称: - -```text -EKC -Engineering Knowledge Compiler -``` - -或者更 Marqdo 一点: - -```text -Marqdo Knowledge Compiler -``` - -职责: - -```text -Source -Document -History -Tests -Interfaces -Examples -Architecture -Execution - ↓ -Knowledge Extraction - ↓ -Knowledge Graph - ↓ -Engineering Catalog - ↓ -Agent Context -``` - ---- - -# 七、它和普通 OKF 有什么区别? - -这里要特别注意。 - -OKF 本身是一个**开放的知识包装格式**:Markdown + YAML frontmatter,强调人和 Agent 都能读、能版本控制、能交换。官方规范刻意保持简单,不要求 schema registry 或特定工具。([GitHub][3]) - -所以: - -> **不要把 Marqdo 做成“另一个 OKF”。** - -应该: - -```text -OKF - ↓ -Knowledge Packaging Layer - -Marqdo - ↓ -Engineering Knowledge Execution Layer -``` - -也就是: - -```text -OKF - ↓ -Marqdo Engineering Profile - ↓ -Executable Engineering Knowledge -``` - -这是我认为最优雅的关系。 - ---- - -# 八、Marqdo 应该在 OKF 上增加“工程知识类型” - -例如: - -```text -Marqdo OKF -``` - -里面不只是: - -```text -Module -Document -Concept -``` - -而应该出现: - -```text -Function -Type -API -Capability -Pattern -Decision -Constraint -Example -Test -Workflow -Error -Dependency -Migration -Deprecated -``` - -例如一个函数: - -```markdown ---- -type: Function -name: resolve_config -module: config -symbol: resolve_config -status: stable -visibility: public ---- - -# resolve_config - -Resolve configuration from: - -- environment -- config file -- defaults - -## Use when - -The caller needs the final normalized configuration. - -## Do not use when - -Only raw configuration should be inspected. - -## Related - -- [validate_config](...) -- [normalize_config](...) - -## Tests - -- [test_resolve_config](...) -``` - -这就不再只是: - -> “这里有一个函数。” - -而是: - -> **“这个函数在工程里的语义是什么。”** - ---- - -# 九、这是解决“AI 重复造轮子”的关键 - -AI 不应该只搜索: - -```text -函数名字 -``` - -而应该搜索: - -```text -Capability -``` - -例如用户: - -> “我要把配置文件加载出来。” - -Agent 首先构造: - -```yaml -intent: - domain: configuration - capability: resolve - input: configuration_source - output: normalized_config - constraints: - - existing architecture - - existing error handling -``` - -然后查: - -```text -Capability Index -``` - -得到: - -```text -Candidate #1 -resolve_config -score: 0.96 -status: stable -reuse: recommended - -Candidate #2 -load_config -score: 0.83 -status: internal - -Candidate #3 -parse_config -score: 0.71 -scope: parser-only -``` - -于是模型不再: - -> “我要写一个 config loader。” - -而是: - -> “工程里已经有 `resolve_config`,我应该调用它。” - ---- - -# 十、所以 Catalog 不能只做“目录” - -这是我认为 Marqdo 下一阶段非常重要的改造。 - -现在: - -```text -catalog -``` - -容易理解成: - -> “项目里有哪些文件。” - -但真正应该是: - -> **Engineering Capability Catalog** - -也就是: - -```text -文件 -模块 -对象 -函数 -类型 -接口 -能力 -关系 -约束 -示例 -测试 -``` - -全部进入 Catalog。 - ---- - -# 十一、建议建立 5 层 Catalog - -## L0:Repository - -```text -repository -``` - -知道: - -```text -语言 -模块 -目录 -依赖 -构建系统 -测试系统 -``` - ---- - -## L1:Module - -```text -module -``` - -知道: - -```text -exports -imports -responsibility -dependencies -public API -``` - ---- - -## L2:Symbol - -```text -function -class -type -constant -endpoint -``` - -知道: - -```text -signature -location -visibility -calls -called_by -tests -``` - ---- - -## L3:Capability - -这是最重要的一层: - -```text -capability -``` - -例如: - -```text -"parse configuration" -"validate JWT" -"retry HTTP request" -"serialize JSON" -"resolve dependency" -``` - -它不等于函数。 - -一个 Capability 可以映射到: - -```text -1 function -3 functions -1 module -1 workflow -``` - ---- - -## L4:Engineering Knowledge - -再往上: - -```text -Decision -Constraint -Pattern -Anti-pattern -Reason -Migration -Failure -``` - -例如: - -> 为什么不能直接调用 `foo()`? - -因为: - -```text -foo() - ↓ -必须先 initialize_context() -``` - -这个信息对 AI 极其重要。 - ---- - -# 十二、我建议把“复用”从搜索升级成一个正式协议 - -新增: - -```text -agent.reuse -``` - -或者: - -```text -knowledge.reuse -``` - -它不是: - -```text -search("foo") -``` - -而是: - -```text -reuse(task) -``` - -返回: - -```json -{ - "decision": "reuse", - "confidence": 0.94, - "capability": "config.resolve", - "symbol": "resolve_config", - "source": "src/config.mq.md", - "reason": [ - "same input semantics", - "same output semantics", - "same error model" - ] -} -``` - -如果没有合适的: - -```json -{ - "decision": "create", - "reason": "no existing capability satisfies constraints" -} -``` - ---- - -# 十三、这一步非常重要:AI 必须允许“证明不存在” - -否则会出现另一个问题: - -AI 搜索了一遍没找到,就自己写。 - -所以应该有: - -```text -Reuse Resolution -``` - -三个结果: - -```text -REUSE -ADAPT -CREATE -``` - -而不是: - -```text -FOUND -NOT FOUND -``` - ---- - -# 十四、三个状态分别代表什么 - -### REUSE - -已有能力满足需求。 - -```text -直接调用 -``` - ---- - -### ADAPT - -存在相近能力。 - -```text -包装 -组合 -参数化 -扩展 -``` - -例如: - -```text -A - + -B - → -新的 capability -``` - -而不是复制 A。 - ---- - -### CREATE - -经过检索和分析确认: - -> 工程中不存在合适能力。 - -才允许生成。 - -这个顺序应该成为 Marqdo Agent 的**硬规则**: - -```text -REUSE - ↓ -ADAPT - ↓ -CREATE -``` - -而不是: - -```text -CREATE - ↓ -maybe reuse -``` - ---- - -# 十五、再进一步:把“重复代码”变成可检测知识 - -这一步我认为会非常有意思。 - -Marqdo Compiler 可以生成: - -```text -symbol fingerprint -``` - -例如: - -```text -function: - normalize_config - -fingerprint: - inputs: - map<string, any> - output: - normalized_config - operations: - parse - merge - validate -``` - -另一个函数: - -```text -normalize_settings -``` - -可能得到: - -```text -semantic similarity: 0.91 -``` - -于是 Catalog 标记: - -```text -possible_duplicate -``` - ---- - -# 十六、于是可以出现一个非常强的命令 - -```bash -marqdo reuse-check -``` - -输出: - -```text -Possible duplicate capabilities - -1. src/a.mq.md::normalize_config - src/b.mq.md::normalize_settings - similarity: 0.91 - -2. src/x.mq.md::parse_user - src/y.mq.md::decode_user - similarity: 0.87 -``` - -这就不再只是 AI 功能。 - -而是: - -> **工程治理工具。** - ---- - -# 十七、甚至可以成为 CI Gate - -例如: - -```yaml -knowledge: - reuse: - required: true - duplicate_threshold: 0.90 -``` - -PR 中新增: - -```text -normalize_settings() -``` - -CI: - -```text -⚠ Potential duplicate capability - -Existing: -config.normalize_config - -New: -settings.normalize_settings - -Similarity: 0.93 - -Recommendation: -REUSE existing capability -``` - -然后: - -```text -marqdo check -``` - -直接失败或者 warning。 - ---- - -# 十八、这会产生一个非常漂亮的工程闭环 - -```text -Human asks feature - ↓ -Agent resolves intent - ↓ -Knowledge Catalog - ↓ -Existing Capability? - / \ - yes no - ↓ ↓ - REUSE CREATE - ↓ ↓ - Execute Generate - ↓ ↓ - Verify Verify - ↓ ↓ - └──────┬────┘ - ↓ - Update Knowledge - ↓ - Update Catalog - ↓ - Git Commit -``` - -下一次: - -```text -同类需求 - ↓ -直接找到上一轮能力 -``` - -这就是你说的: - -> **工程越大,Marqdo 越有价值。** - ---- - -# 十九、但还有一个更大的问题:Knowledge 必须知道“为什么” - -这是很多 RAG 系统做不到的。 - -例如: - -```text -use redis_cache -``` - -只是事实。 - -真正有价值的是: - -```markdown -# Redis Cache - -Use for: - -- cross-process cache -- TTL cache - -Do not use for: - -- durable state - -Reason: - -Redis cache is intentionally disposable in this project. -Persistent state belongs to PostgreSQL. -``` - -这就是: - -> **Engineering Decision Knowledge** - -AI 非常需要这种东西。 - ---- - -# 二十、所以我建议增加一种核心知识:Decision - -例如: - -```markdown ---- -type: Decision -id: ADR-023 -status: accepted ---- - -# Cache is not persistence - -## Decision - -Redis is only used for ephemeral cache. - -## Reason - -The application must remain correct when Redis is unavailable. - -## Consequence - -Do not introduce Redis as the source of truth. - -## Applies to - -- api/* -- worker/* -``` - -这比单纯把代码 embedding 给 AI 有价值很多。 - ---- - -# 二十一、再增加一种:Constraint - -例如: - -```markdown ---- -type: Constraint ---- - -# Database access - -All database access must go through `repository/*`. - -Direct SQL from HTTP handlers is prohibited. -``` - -于是 Agent 搜索: - -```text -"how should I access the database?" -``` - -得到: - -```text -Constraint -+ -Repository capability -+ -Example -``` - -这就是**第一信息**。 - ---- - -# 二十二、再增加一种极其重要的知识:Negative Knowledge - -我认为这是 Marqdo 可以做得非常漂亮的地方。 - -传统知识库主要记录: - -```text -应该做什么 -``` - -但大型工程更需要: - -```text -不要做什么 -``` - -例如: - -```markdown ---- -type: AntiPattern ---- - -# Do not parse JWT manually - -Never decode JWT directly in application code. - -Use: - -`auth.verify_token` - -Reason: - -- key rotation -- issuer validation -- expiry validation -- audit logging -``` - -这能直接阻止 AI 造轮子。 - ---- - -# 二十三、我甚至建议把知识分成四种 - -```text -FACT - ↓ -工程里有什么 - -RULE - ↓ -工程要求怎么做 - -DECISION - ↓ -为什么这样做 - -FAILURE - ↓ -什么东西以前做错过 -``` - -于是: - -```text -Engineering Knowledge -├── Facts -├── Rules -├── Decisions -└── Failures -``` - -这四类东西结合起来,才是真正的工程知识。 - ---- - -# 二十四、失败经验尤其适合你现在的 Agent - -目前 Agent 设计已经强调: - -> 成功和失败都写回文档,失败块成为可读的“避坑记录”。([GitHub][2]) - -我建议把它正式升级成: - -```text -Failure Knowledge -``` - -例如: - -```markdown ---- -type: Failure -task: add_cache_layer -status: resolved ---- - -# Do not cache authorization result - -## Failed approach - -Caching `check_permission(user, resource)` by user only. - -## Failure - -Permissions changed during role update. - -## Correct approach - -Cache by: - -user_id -resource_id -permission_version - -## Introduced by - -commit abc123 -``` - -未来 AI 遇到: - -> “我要缓存权限判断。” - -第一条知识就可能是: - -```text -⚠ Historical failure detected. -``` - -这比一般 RAG 强得多。 - ---- - -# 二十五、然后你会得到一个很漂亮的 Knowledge Graph - -例如: - -```text -Capability - │ - ├── implemented_by → Function - │ - ├── tested_by → Test - │ - ├── constrained_by → Constraint - │ - ├── decided_by → Decision - │ - ├── related_to → Capability - │ - ├── conflicts_with → Capability - │ - ├── failed_by → Failure - │ - └── documented_by → Document -``` - -这样 `.mq.md` 不只是: - -> 一堆 Markdown。 - -而是: - -> **一个可以执行的 Engineering Knowledge Graph。** - ---- - -# 二十六、而 Marqdo 的特殊优势在于:这个 Graph 不是另建的 - -这是最关键的一点。 - -普通系统: - -```text -Code - ↓ -Vector DB - ↓ -Knowledge Graph - ↓ -RAG -``` - -会出现: - -```text -Code ≠ Knowledge -``` - -最终: - -```text -代码改了 -知识没改 -``` - -然后: - -> AI 得到旧信息。 - ---- - -# 二十七、Marqdo 应该做到反过来 - -```text -.mq.md - │ - ├── executable AST - ├── documentation - ├── knowledge - ├── symbol graph - └── catalog -``` - -**一个源头,多个投影。** - -也就是说: - -```text -Source of Truth - │ - ├── Execution - ├── Documentation - ├── OKF - ├── Search Index - ├── Symbol Graph - └── Agent Context -``` - -这才是: - -> **代码即文档,文档即知识库** - -真正有技术含量的地方。 - ---- - -# 二十八、因此 Catalog 不应该被看成“生成出来的 Markdown” - -它应该是: - -> **Marqdo AST 的 Knowledge Projection。** - -例如: - -```text -Marqdo AST - ↓ -Knowledge Extractor - ↓ -Knowledge IR - ↓ -┌────────────────────────────┐ -│ │ -├── catalog.yaml │ -├── index.md │ -├── modules/*.md │ -├── symbols/*.md │ -├── capabilities/*.md │ -├── graph.json │ -└── search index │ -``` - -OKF 是其中的一个**可移植输出格式**。 - ---- - -# 二十九、这会直接解决大规模工程的 Context Window 问题 - -这是另一个非常重要的价值。 - -假设工程: - -```text -5 million lines -``` - -不可能: - -```text -把整个 repo 给 GPT -``` - -也不应该: - -```text -向量搜索 top 20 chunks -``` - -因为 top 20 chunks 经常没有结构。 - -Marqdo 应该做: - -```text -Task - ↓ -Intent - ↓ -Catalog - ↓ -Module - ↓ -Capability - ↓ -Symbol - ↓ -Source -``` - -这是: - -> **Hierarchical Retrieval** - -而不是: - -> flat vector retrieval。 - ---- - -# 三十、我建议采用 Progressive Disclosure - -第一层: - -```text -What exists? -``` - -返回: - -```text -20 candidates -``` - -第二层: - -```text -What are their responsibilities? -``` - -返回: - -```text -5 capabilities -``` - -第三层: - -```text -Which one applies? -``` - -返回: - -```text -2 candidates -``` - -第四层: - -```text -How do I use it? -``` - -返回: - -```text -signature -example -constraints -``` - -第五层: - -```text -Show implementation. -``` - -才打开源码。 - ---- - -# 三十一、这样模型看到的上下文会非常小 - -例如用户: - -> 添加 OAuth 登录。 - -模型首先只看到: - -```text -AUTH CAPABILITY CATALOG - -Existing: -auth.oauth -auth.session -auth.user -auth.csrf - -OAuth providers: -Google -GitHub - -Existing route: -POST /auth/callback - -Existing session implementation: -auth.session.create() - -Constraints: -Do not create another session store. - -Relevant decisions: -ADR-014 -``` - -然后模型才决定: - -```text -REUSE auth.oauth -REUSE auth.session -ADAPT callback -``` - -**它根本没有机会先写一个新的 OAuth 系统。** - -这就是你要解决的问题。 - ---- - -# 三十二、所以我建议 Agent 增加一个“工程前置协议” - -现在: - -```text -agent.step -agent.plan -``` - -我建议最终变成: - -```text -agent.step - ↓ -knowledge.preflight - ↓ -reuse.resolve - ↓ -agent.step -``` - -复杂任务: - -```text -agent.plan - ↓ -knowledge.preflight - ↓ -architecture.resolve - ↓ -reuse.resolve - ↓ -plan -``` - ---- - -# 三十三、可以把它正式设计成: - -```text -## preflight -``` - -输入: - -```text -task -``` - -输出: - -```yaml -status: ready - -intent: - capability: authentication - -existing: - - auth.oauth - - auth.session - -constraints: - - ADR-014 - - Constraint-07 - -decisions: - - Decision-003 - -failures: - - Failure-019 - -recommended: - - reuse: auth.oauth - - reuse: auth.session - -create_allowed: false -``` - -只有: - -```text -create_allowed: true -``` - -才能进入生成阶段。 - ---- - -# 三十四、这里我甚至建议加入“Reuse Budget” - -例如: - -```yaml -agent: - reuse: - min_candidates: 3 - require_preflight: true - require_reason: true - allow_create_after: 2 -``` - -意思: - -> AI 至少分析两个已有候选之后,才能说“工程里没有”。 - -这会非常有效。 - ---- - -# 三十五、再进一步:生成的代码必须声明它复用了什么 - -例如: - -```markdown ---- -type: Function -name: create_session -reuse: - - auth.session - - crypto.token ---- -``` - -这样 Catalog 可以反向建立: - -```text -create_session - ├── reused auth.session - └── reused crypto.token -``` - ---- - -# 三十六、这会产生一个极有价值的指标 - -## Reuse Ratio - -例如: - -```text -Generated functions: 1000 - -Reused existing capability: 730 -Adapted existing capability: 180 -New capability: 90 -``` - -得到: - -```text -Reuse Ratio = 73% -Adapt Ratio = 18% -Novel Ratio = 9% -``` - -这比: - -> “AI 写代码很快” - -更有工程意义。 - ---- - -# 三十七、再进一步,可以衡量 AI 的“重复造轮子率” - -定义: - -```text -Duplication Rate -= -new implementations -that semantically duplicate existing capabilities -/ -all new implementations -``` - -目标: - -```text -越低越好 -``` - -这就是 Marqdo 非常适合做实验的数据。 - ---- - -# 三十八、再进一步:Reasoning Amortization + Reuse - -你之前的 Agent 思路里面已经有: - -> 大模型探索 → 小模型/Jev 决策 → Marqdo 执行 → 逐渐编译。 - -现在可以再加一个: - -> **Knowledge Amortization** - -也就是: - -```text -第一次: -LLM + repo exploration - -第二次: -Catalog + small model - -第三次: -Capability match - -第四次: -Deterministic reuse -``` - -于是: - -```text -Task #1 - 20k tokens - ↓ -Knowledge generated - -Task #2 - 5k tokens - ↓ -Reuse - -Task #10 - 500 tokens - ↓ -Compiled policy - -Task #100 - 0 LLM - ↓ -Direct execution -``` - -这就是非常漂亮的 Marqdo Agent story。 - ---- - -# 三十九、最终形成三个“编译” - -我建议把你之前 Agent 的 Skill Compilation 再升级成: - -```text -1. Knowledge Compilation -2. Policy Compilation -3. Code Compilation -``` - ---- - -## 1. Knowledge Compilation - -```text -Source - ↓ -Fact -Decision -Constraint -Capability -Failure -``` - -↓ - -```text -OKF -``` - ---- - -## 2. Policy Compilation - -```text -Task - ↓ -Which capability? - ↓ -Which module? - ↓ -Which function? -``` - -↓ - -```text -policy.mq.md -``` - ---- - -## 3. Code Compilation - -```text -Capability -+ -Policy -+ -Constraints -``` - -↓ - -```text -Executable Marqdo -``` - ---- - -# 四十、最终形成: - -```text - Human / AI Task - │ - ↓ - ┌─────────────────┐ - │ Knowledge Layer │ - │ What exists? │ - └────────┬────────┘ - ↓ - ┌─────────────────┐ - │ Policy Layer │ - │ What to reuse? │ - └────────┬────────┘ - ↓ - ┌─────────────────┐ - │ Execution Layer │ - │ What to run? │ - └────────┬────────┘ - ↓ - Result - │ - ↓ - Verification - │ - ↓ - Knowledge Update -``` - -这就是我认为 Marqdo 最值得做的 Agent 架构。 - ---- - -# 四十一、我还建议增加一个特别重要的概念:Knowledge Lifecycle - -因为工程知识一定会过期。 - -OKF 本身强调开放、可版本控制的 Markdown 知识包,但当前生态讨论也已经暴露出几个更高层的问题:**时间有效性、信任/来源、冲突与 supersession** 都不是简单的 Markdown packaging 能解决的。([GitHub][4]) - -Marqdo 做工程知识时尤其需要: - -```text -draft - ↓ -verified - ↓ -stable - ↓ -deprecated - ↓ -superseded -``` - ---- - -# 四十二、每个 Capability 都应该有“新鲜度” - -例如: - -```yaml -status: stable -introduced: v2.3 -verified: 2026-09-20 -last_used: 2026-09-28 -last_tested: 2026-09-28 -``` - -这样 Agent 可以知道: - -```text -这个能力存在 -``` - -和: - -```text -这个能力现在还可靠 -``` - -是两个问题。 - ---- - -# 四十三、再加入 Evidence - -例如: - -```yaml -evidence: - source: - - src/auth/session.mq.md - - tests: - - tests/auth/session.mq.md - - executions: - - run-192 - - run-204 - - commits: - - a82fd1 -``` - -这就可以让 Agent 判断: - -> “这是文档里说的,还是代码和测试都证明过的?” - -这和当前 OKF 社区正在讨论的“citation 与 reliability 不是同一件事”也是一致的:引用证明来源,不能自动证明内容可靠。([GitHub][5]) - ---- - -# 四十四、甚至可以引入非常轻量的 Confidence - -例如: - -```yaml -confidence: high -evidence: - implementation: verified - tests: verified - runtime: verified -``` - -而不要只: - -```yaml -confidence: 0.97 -``` - -因为: - -```text -0.97 -``` - -对 Agent 来说没有解释能力。 - ---- - -# 四十五、再解决一个非常大的问题:知识冲突 - -例如: - -```text -A.md: -Redis is source of truth. - -B.md: -Redis is cache only. -``` - -普通 RAG: - -```text -retrieve A -retrieve B -LLM 自己猜 -``` - -Marqdo: - -```text -Conflict detected - ↓ -A ↔ B - ↓ -same capability - ↓ -different claims - ↓ -Decision/Authority resolution -``` - -最终: - -```text -Decision-014 supersedes A -``` - -而不是让模型自己选择。 - ---- - -# 四十六、因此我建议增加 Knowledge Graph Edge - -最重要的几种: - -```text -implements -uses -depends_on -tested_by -documented_by -constrained_by -decided_by -supersedes -conflicts_with -deprecated_by -derived_from -failed_by -``` - -这会让工程知识从: - -```text -文件集合 -``` - -变成: - -```text -关系系统 -``` - ---- - -# 四十七、然后 Catalog 查询就会非常强 - -例如: - -```bash -marqdo knowledge find "authentication" -``` - -得到: - -```text -Capability - auth.session - -Implementation - ext/auth/session.mq.md - -Constraints - C-014 - -Decisions - ADR-023 - -Tests - tests/auth/session.mq.md - -Failures - F-009 - -Related - auth.oauth - auth.rbac -``` - ---- - -# 四十八、Agent 不应该直接访问整个知识库 - -这里我非常赞同当前 Agent 设计里的一个思想: - -> context 应该由框架组装,而且可审计。([GitHub][2]) - -但下一步应该进一步: - -```text -Agent - ↓ -Knowledge Resolver - ↓ -Context Pack -``` - -而不是: - -```text -Agent - ↓ -自己搜索几十个 md -``` - ---- - -# 四十九、Context Pack 应该有固定结构 - -例如: - -```markdown -# Engineering Context - -## Task - -Add OAuth login. - -## Existing Capabilities - -- auth.oauth -- auth.session - -## Relevant APIs - -- auth.oauth.authorize -- auth.oauth.callback -- auth.session.create - -## Constraints - -- ADR-014 -- C-021 - -## Decisions - -- ADR-014 - -## Known Failures - -- F-019 - -## Recommended Reuse - -1. auth.oauth -2. auth.session - -## Forbidden - -Do not implement: -- JWT parsing -- session storage -``` - -这个东西本身又是: - -```text -.mq.md -``` - -于是: - -> **Agent Context 本身也是 Marqdo Artifact。** - -这一步我非常推荐。 - ---- - -# 五十、这就是我认为真正优雅的地方 - -不要让: - -```text -RAG -``` - -成为一个黑盒: - -```text -query → vector db → prompt -``` - -而是: - -```text -Task - ↓ -Knowledge Query - ↓ -Context Artifact - ↓ -Agent -``` - -例如: - -```text -.marqdo/context/ - task-183.mq.md -``` - -里面记录: - -```text -用了哪些知识 -为什么选这些知识 -哪些候选被排除 -哪些约束生效 -``` - -于是 Agent 的上下文也可以: - -```text -view -debug -git diff -review -replay -``` - -这完全符合 Marqdo 的哲学。 - ---- - -# 五十一、这还能解决“AI 为什么这样写”的问题 - -未来代码 review 可以直接问: - -> 为什么这里调用 `resolve_config`? - -Marqdo 可以回答: - -```text -Because: - -Task T-192 - ↓ -Capability: resolve configuration - ↓ -Candidate: -resolve_config (0.96) - ↓ -Constraint: -C-012 requires centralized config resolution - ↓ -Decision: -ADR-022 - ↓ -Selected: -resolve_config -``` - -这比普通 AI Code Review 强很多。 - ---- - -# 五十二、最终你的 PR 甚至可以自动生成“知识影响” - -例如: - -```text -Changed: -src/config/resolve.mq.md -``` - -系统自动告诉 Agent: - -```text -Affected capabilities: - config.resolve - app.bootstrap - -Affected decisions: - ADR-012 - -Affected tests: - tests/config/* - -Affected documentation: - docs/configuration.mq.md - -Potential stale knowledge: - knowledge/configuration.md -``` - -这就是: - -> **Knowledge-aware software engineering。** - ---- - -# 五十三、这也是 Marqdo 真正适合“大型工程”的原因 - -小项目: - -```text -10 files -``` - -这个东西意义有限。 - -但是: - -```text -1000 modules -10000 functions -100000 tests -``` - -以后: - -```text -AI context -``` - -真正的瓶颈不再是模型能力。 - -而是: - -> **工程知识的组织。** - -这恰恰是 Marqdo 可以解决的。 - ---- - -# 五十四、我建议最终形成一个 `.marqdo/` 目录 - -我会设计成: - -```text -.marqdo/ -│ -├── index.mq.md -│ -├── catalog/ -│ ├── repository.mq.md -│ ├── modules/ -│ ├── symbols/ -│ └── capabilities/ -│ -├── knowledge/ -│ ├── facts/ -│ ├── decisions/ -│ ├── constraints/ -│ ├── patterns/ -│ ├── failures/ -│ └── migrations/ -│ -├── graph/ -│ ├── graph.json -│ └── edges.json -│ -├── agent/ -│ ├── policies/ -│ ├── skills/ -│ ├── contexts/ -│ └── episodes/ -│ -└── tests/ - ├── reuse/ - ├── knowledge/ - └── retrieval/ -``` - -注意: - -**这些绝大部分应该是 generated / derived artifacts,不应该成为第二个 source tree。** - -Source of Truth 仍然是: - -```text -*.mq.md -``` - ---- - -# 五十五、最关键的几个命令 - -我建议未来 Marqdo CLI 出现这样一组能力: - -```bash -marqdo catalog -``` - -生成工程目录。 - -```bash -marqdo knowledge -``` - -生成/维护知识。 - -```bash -marqdo find -``` - -找工程能力。 - -```bash -marqdo reuse -``` - -判断是否应该复用。 - -```bash -marqdo impact -``` - -分析修改影响。 - -```bash -marqdo conflicts -``` - -检查知识冲突。 - -```bash -marqdo stale -``` - -检查过期知识。 - -```bash -marqdo duplicate -``` - -检查重复能力。 - -```bash -marqdo verify -``` - -验证代码 + 知识一致性。 - ---- - -# 五十六、其中最重要的是 `marqdo reuse` - -我甚至认为它可以成为 Marqdo 的“杀手级命令”。 - -例如: - -```bash -marqdo reuse "implement oauth login" -``` - -输出: - -```text -Engineering First Information - -Existing capabilities: - auth.oauth 0.97 - auth.session 0.95 - -Relevant constraints: - C-014 - C-027 - -Relevant decisions: - ADR-019 - -Known failures: - F-008 - -Recommended: - REUSE auth.oauth - REUSE auth.session - -New implementation: - NOT REQUIRED -``` - -这就是你说的: - -> AI 不要再重复造轮子。 - ---- - -# 五十七、然后 Agent API 就会自然变成 - -```text -agent.preflight -agent.resolve -agent.reuse -agent.adapt -agent.create -agent.verify -agent.record -agent.learn -``` - -而不是只有: - -```text -agent.step -agent.plan -``` - -这也与现在已有的 `step / plan / writeback / agent-kb` 很自然地衔接。当前 Agent 已经有工作簿、任务复用、写回和 OKF agent-kb 的方向,所以我不建议推翻重来,而是**在前面增加 Engineering Knowledge Resolution 层**。([GitHub][2]) - ---- - -# 五十八、我会特别避免一个坑:不要把它做成“更大的向量数据库” - -这一点非常重要。 - -不要: - -```text -Marqdo -= -Markdown -+ -Embedding -+ -Vector DB -``` - -这会把 Marqdo 的优势毁掉。 - -应该: - -```text -Marqdo -= -Executable Source -+ -Structured Knowledge -+ -Symbol Graph -+ -Capability Graph -+ -Versioned Evidence -+ -Deterministic Retrieval -+ -Semantic Retrieval -``` - -Embedding 只是: - -```text -retrieval implementation -``` - -而不是: - -```text -knowledge model -``` - ---- - -# 五十九、检索最好采用 Hybrid + Graph - -例如: - -```text -Query - │ - ├── lexical - ├── symbol - ├── semantic - ├── capability - └── graph - ↓ - rerank - ↓ - context pack -``` - -而不是: - -```text -embedding(query) - ↓ -top K -``` - -当前 OKF 生态本身也已经在往搜索、图关系、context selection 等方向发展;这说明“Markdown 只是包装,真正困难的是知识检索与上下文组织”这个判断是成立的。([Open Knowledge][6]) - ---- - -# 六十、我认为最重要的工程规则可以只有五条 - -最终我甚至建议把 Marqdo 的 Agent 工程纪律写成: - -### Rule 1 — Discover before Create - -```text -先发现,再创建。 -``` - -### Rule 2 — Reuse before Adapt - -```text -先复用,再适配。 -``` - -### Rule 3 — Adapt before Duplicate - -```text -能组合,不复制。 -``` - -### Rule 4 — Verify before Promote - -```text -验证之后,才能进入知识库。 -``` - -### Rule 5 — Code changes update knowledge - -```text -代码改变,知识必须重新验证。 -``` - -这五条非常适合成为 Marqdo 的核心工程原则。 - ---- - -# 六十一、最终我认为 Marqdo 可以形成一个非常漂亮的闭环 - -```text - ┌─────────────────────┐ - │ Human │ - │ "实现一个功能" │ - └──────────┬──────────┘ - ↓ - Engineering Intent - ↓ - ┌──────────────────┐ - │ Knowledge Resolve│ - └────────┬─────────┘ - ↓ - ┌────────────┼────────────┐ - ↓ ↓ ↓ - Existing Constraint Decision - Capability │ │ - │ └──────┬──────┘ - │ ↓ - └──────────────→ Context - ↓ - Agent - ↓ - REUSE / ADAPT / CREATE - / | \ - / | \ - reuse adapt create - \ | / - └─────────┼────────┘ - ↓ - Verify - ↓ - Knowledge Update - ↓ - Catalog / Graph - ↓ - Git / OKF Bundle - ↓ - 下一次任务直接受益 -``` - -这时候 Marqdo 的价值就不是: - -> “我有一个比 Python 更适合 LLM 的语言。” - -而是: - -> **“我把软件工程项目本身变成了 AI 可以理解、执行、验证和持续学习的知识系统。”** - -这两个命题的战略价值完全不同。 - ---- - -# 六十二、我尤其建议你把论文/项目叙事也往这里移动 - -你以前的: - -> **From Executable Documents to Executable Knowledge Bases** - -现在其实可以进一步变成: - -> **From Executable Documents to Executable Engineering Knowledge** - -或者更强一点: - -> **Executable Knowledge for AI-Native Software Engineering** - -核心研究问题变成: - -> **How can a software repository become an executable, versioned, and queryable knowledge system that prevents redundant code generation by AI agents?** - -这个问题比: - -> “如何设计一种 LLM-native programming language?” - -我认为更有工程问题意识。 - -因为它直接击中了当前 AI Coding Agent 的一个非常实际的问题: - -```text -AI can generate code. -But does AI understand what the project already knows? -``` - -Marqdo 的回答应该是: - -> **Yes — because the knowledge is not maintained beside the code. The knowledge is the code's executable document representation itself.** - ---- - -## 我建议你下一阶段不要继续无边界地给 `agent-kb` 加功能 - -而是直接做一个 **Marqdo Engineering Knowledge v1**。 - -优先级我会这样排: - -| 阶段 | 要做的东西 | 目标 | -| ------ | ------------------------------- | --------------------------------- | -| **P0** | Symbol Catalog | AI 知道工程里有什么 | -| **P0** | Capability Catalog | AI 知道工程能做什么 | -| **P0** | `reuse/preflight` | 生成前强制检查已有能力 | -| **P0** | Context Pack | 给模型第一信息,而不是整个 repo | -| **P1** | Decision / Constraint / Failure | 让 AI 知道为什么、禁止什么、过去错过什么 | -| **P1** | Dependency / Call / Test Graph | 建立工程知识图 | -| **P1** | Duplicate Detection | 检测 AI 新造的重复能力 | -| **P1** | Knowledge Lifecycle | stale / deprecated / superseded | -| **P2** | Policy Compilation | 将复用判断编译成 `.mq.md` | -| **P2** | Knowledge Compilation | 从执行经验自动生成知识 | -| **P2** | Reuse CI Gate | PR 阶段阻止重复造轮子 | -| **P3** | Knowledge-aware Agent | Agent 原生依赖 Engineering Knowledge | -| **P3** | Benchmark | 用重复率、检索召回、token amortization 衡量优势 | - -其中我认为真正的 **P0 只有三个核心组件**: - -```text -Capability Catalog - + -Reuse Preflight - + -Engineering Context Pack -``` - -这三个做出来,Marqdo 就第一次真正开始具备你说的: - -> **“让 AI 在大型工程中获得第一信息,并减少重复造轮子”的能力。** - -而且这条路线并不需要抛弃现在的 OKF、`catalog`、`agent-kb`、`writeback` 和 `plan`;恰恰相反,**它们可以全部成为这个架构的基础设施。** - -官方仓库目前已经明确把自动 Catalog、可执行 `.mq.md`、OKF 风格清单和 Agent 工作簿放在同一条产品主线上。([GitHub][1]) -我认为下一步最重要的不是再增加一个功能,而是把这些东西**正式统一成一个“Engineering Knowledge Compiler”架构**。 - -如果这个方向成立,Marqdo 最终真正独特的东西可能不是 `.mq.md` 这个语法本身,而是: - -> **一个大型代码仓库在 Marqdo 中可以同时作为程序、文档、知识图谱、Agent 上下文和可复用能力目录存在,而且这些视图全部由同一份可执行源代码派生。** - -这才是我认为你现在最值得押注的核心。 [Marqdo GitHub 仓库](https://github.com/cflmy/marqdo?utm_source=chatgpt.com) - -[1]: https://github.com/cflmy/marqdo "GitHub - cflmy/marqdo: Marqdo — A literate programming language built on Markdown. Code is document, document is executable. 中文配套:基于 Markdown 文法的文学编程语言,代码即是文档,文档可直接运行。 · GitHub" -[2]: https://github.com/cflmy/marqdo/blob/main/doc/design/ext-agent.md "marqdo/doc/design/ext-agent.md at main · cflmy/marqdo · GitHub" -[3]: https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md?utm_source=chatgpt.com "knowledge-catalog/okf/SPEC.md at main · GoogleCloudPlatform/knowledge-catalog · GitHub" -[4]: https://github.com/GoogleCloudPlatform/knowledge-catalog/discussions/87?utm_source=chatgpt.com "KCP's production experience with OKF's three open problems — and a bridge command · GoogleCloudPlatform knowledge-catalog · Discussion #87 · GitHub" -[5]: https://github.com/GoogleCloudPlatform/knowledge-catalog/issues/151?utm_source=chatgpt.com "Proposal: graded confidence — an epistemic-reliability axis, distinct from integrity (#140) and citation (#92/#94) · Issue #151 · GoogleCloudPlatform/knowledge-catalog · GitHub" -[6]: https://openknowledge.sh/wiki/changelog/cli.html?utm_source=chatgpt.com "Cli - Open Knowledge" diff --git a/doc/next/009.md b/doc/next/009.md deleted file mode 100755 index 3238406..0000000 --- a/doc/next/009.md +++ /dev/null @@ -1,576 +0,0 @@ -# Marqdo 的 `[]()`:从可读语法走向可验证的知识引用 - -我重新读取了仓库当前 `main` 分支(提交 `1a139892`)的 README、链接语法设计、知识分层设计,以及仓库中针对现有实现的复核报告。 - -这次我认为应当调整之前对 Marqdo 的评价:你提出的 `[]()` 不只是改善语法外观,它确实有机会成为 Marqdo 从“可执行文档”走向“可复用知识系统”的关键入口。 - -但当前设计有一个尚未解决的根本问题: - -它已经尝试统一“可读描述”和“可执行表达式”,却还没有真正统一“知识的身份、知识的含义、知识的实现、知识的证据,以及知识的版本”。 - -仅仅让链接能解析到一个函数,并不能保证 AI 没有用错知识。仅仅让函数有一个确定的编译结果,也不能保证这个结果所表达的知识是真的。 - -这恰恰可能是你不断修改设计,却始终没有得到预期效果的原因。 - -## 一、先区分仓库已经实现了什么 - -当前 README 标明的是 v2.0.0,`doc/design/link-syntax.md` 将跨文档类函数调用列为 v2.1 目标。 - -| 能力 | 仓库当前状态 | -| ---------------- | ---------------------------- | -| `[描述](表达式)` 本地遮蔽 | 已实现,主要通过 `markup: occlusion` | -| `()` 中表达式求值 | 已实现 | -| 用自然语言描述隐藏复杂代码 | 已实现基础能力 | -| `类.函数` 直接调用 | 设计目标,尚未按文档实现 | -| 跨文档自动解析知识目标 | 设计目标 | -| 编译器生成 LinkInfo | 设计目标 | -| 链接进入 EKC 知识图 | 设计目标 | -| 版本指纹和链接锁定 | 设计目标 | - -仓库还有一份很重要的复核报告:[occlusion-vs-executable-knowledge-2026-10.md](https://github.com/cflmy/marqdo/blob/main/doc/research/occlusion-vs-executable-knowledge-2026-10.md?utm_source=chatgpt.com)。 - -它针对 v2.0.0 测试了一个典型案例:在一个文档里定义“李白的出生年份”,再由另一个文档通过链接读取。结果发现,正文链接没有进入执行 AST,跨文档类名没有得到解析,类函数不能直接调用,而且原始知识函数也没有实际返回值。 - -这份报告说明:问题不是 `[]()` 的形式不够优美,而是链接背后的知识语义基础尚未建成。 - -这也解释了为什么你已经设计了链接语法,却还没有获得想象中的知识复用能力。 - -## 二、我建议保留你的两个目标,但增加第三个目标 - -目标一 · Presentation - -自然语言呈现 - -用 `[]` 给复杂、不适合人类直接阅读的可执行表达式一个清楚的描述。 - -目标二 · Executable Reference - -确定性知识引用 - -让 `()` 可以绑定已经编译、可解析、可验证的知识单元,而不仅是临时拼出的表达式。 - -目标三 · Knowledge Integrity - -知识一致性保障 - -当知识定义、实现、版本、证据或适用条件变化时,能检测引用是否仍然有效,阻止 AI 把“能够运行”误认为“知识正确”。 - -第三个目标不是另加一种语法,而是让前两个目标真正成立所必须的编译器能力。 - -我倾向于把它称为 Verified Knowledge Reference(可验证知识引用)。 - -## 三、关键转变:不要把“函数”直接等同于“知识” - -目前 [link-syntax.md](https://github.com/cflmy/marqdo/blob/main/doc/design/link-syntax.md?utm_source=chatgpt.com) 的核心设计是: - -``` -[label](expr) ≡ expr -``` - -它规定标签不改变计算语义,链接只为表达式增加人类描述和编译器元数据。 - -这个规则作为表达式语义是合理的,但作为完整知识模型还不够。 - -原因在于,至少有三种不同的东西可能进入 `()`: - -| 内容 | 例子 | 实质 | -| ---- | ---------------------------- | --------------- | -| 表达式 | `[税额](amount * rate)` | 一次计算 | -| 函数 | `[计算税额](Tax.calculate(100))` | 一种计算能力的调用 | -| 知识事实 | `[适用税率](TaxPolicy.rate)` | 一项具有来源、范围、版本的知识 | - -第三种不能只靠前两种来解释。 - -例如,编译器能确定 `TaxPolicy.rate` 返回 `0.10`,只能证明“目标被正确解析并返回该值”,不能证明“2026 年某个地区、某种业务适用的税率确实是 10%”。 - -确定性执行和知识真实性是两个独立维度。 - -我建议把 Marqdo 的知识模型扩展为以下结构: - -Markdown 文档 - -自然语言叙述、表格、函数与知识定义 - -Semantic Artifact · 语义制品 - -稳定身份、类型、签名、实现、契约、依赖、证据 - -Verified Knowledge Reference - -解析引用、检查约束、固定版本、判定可否复用 - -解释执行 - -知识检索 - -AI 复用 - -这里最重要的新概念不是链接,而是 Semantic Artifact(语义制品)。 - -它应当是 Marqdo 编译器第一次真正统一代码、文档与知识的中间产物。 - -### 一个语义制品应该包含什么? - -建议最小模型如下。这里是我的架构提案,不是当前仓库已经实现的格式。 - -``` -{ - "id": "knowledge://project/TaxPolicy/rate", - "kind": "fact", - "signature": { - "params": [], - "returns": "number" - }, - "implementation": { - "ir": "compiled-reference", - "digest": "sha256:..." - }, - "contract": { - "unit": "ratio", - "scope": "example-policy", - "effects": "pure" - }, - "provenance": { - "source": "policy.md#rate", - "digest": "sha256:..." - }, - "verification": { - "status": "verified", - "methods": ["source-check", "contract-test"] - } -} -``` - -其中 `id` 是符号身份,`implementation.digest` 是编译内容指纹,`provenance` 是来源证据,`verification` 是验证记录。 - -这样一来,AI 复用的对象就不再是“某个名字看起来正确的函数”,而是一个具有明确身份和约束的知识制品。 - -需要注意:这里的 `verified` 只能表示通过了所声明的验证方法,不能凭此宣称该知识在所有现实情境下都正确。 - -## 四、重新定义 `[]()`:统一写法,不强行统一所有行为 - -我建议继续保持你所追求的语法纯度: - -``` -[人类可读的描述](机器可解析的目标) -``` - -不引入额外的 `knowledge:`、`call:` 或 `ref:` 前缀,也不让 AI 记忆复杂的新标记。 - -但编译器必须区分目标的性质,而不是把一切都当作普通表达式立即求值。 - -A · 表达式遮蔽 - -计算 - -``` -**total = [应付总额](price * quantity + shipping)** -``` - -对原有表达式的透明包装。编译后仍是普通表达式,描述不改变值。 - -B · 能力引用 - -复用 - -``` -**total = [计算应付总额](Pricing.total(订单))** -``` - -解析到已编译函数,检查参数、类型、依赖、权限和版本,然后调用。 - -C · 知识事实引用 - -知识 - -``` -用户可以查阅[李白的出生年份](李白.出生年份)。 -``` - -解析到知识制品;view 展示事实、来源和验证状态。正文保持惰性,不自动产生副作用。 - -这种设计保留了 `[label](expr) ≡ expr` 的计算规则,但增加了一个重要条件:编译器首先要解析 `expr` 的目标类型,然后才能决定它应该怎样验证、绑定和使用。 - -这不会使语言多出三套语法,反而能够避免当前设计中“语法统一了,但知识语义仍然散落在工具中”的问题。 - -## 五、你的第二个目标,最关键的是“绑定”而不是“调用” - -假设有这样一份知识文档: - -``` -# 李白 - -## 出生年份 - -| 返回 | 类型 | 来源 | -|---|---|---| -| 701 | number | corpus/libai.md#birth | - -*701* -``` - -另一个文档写: - -``` -李白的[出生年份](李白.出生年份)是 701 年。 -``` - -理想情况下,编译器应该执行一条确定性的处理链: - -Resolve — 查找 `李白.出生年份` 指向哪个知识单元 - -Bind — 绑定稳定 Symbol ID,而不是仅保存字符串 - -Validate — 检查返回类型、来源、契约与依赖 - -Pin — 根据需要固定知识版本和内容指纹 - -Evaluate — 仅在允许执行的上下文中求值 - -Trace — 将引用关系、验证结果与来源写入知识图 - -此时,编译器内部的引用不应该只是: - -``` -"李白.出生年份" -``` - -而应该更接近: - -``` -KnowledgeRef { - target_symbol_id, - resolved_artifact_id, - expected_signature, - pinned_digest, - verification_policy, - source_span -} -``` - -其中的 `target_symbol_id` 解决“引用谁”,`pinned_digest` 解决“引用哪个版本”,`verification_policy` 解决“什么时候可以信任它”。 - -这才是让 AI 不必重新生成已有知识,而是能够确定性地调用已有知识的技术基础。 - -还有一个必须考虑的问题:如果编译器只记录函数源码哈希,而函数内部调用的其他知识已经发生变化,那么源码没有变,实际执行语义也可能已经变化。因此,至少要对调用依赖形成可追踪的版本关系;对需要严格复现的纯函数,还应生成包含传递依赖的制品指纹。对于网络请求、时间、随机数等外部效应,则必须记录环境和执行条件,不能简单承诺重放一定得到相同结果。 - -## 六、仓库当前设计里,我最想修改的三个地方 - -### 1. 不要继续把类当作所有知识的唯一载体 - -[knowledge-layers.md](https://github.com/cflmy/marqdo/blob/main/doc/design/knowledge-layers.md?utm_source=chatgpt.com) 提出用 `# 李白 = > 诗人` 表示知识个体,也就是“单体知识类”。 - -这可以作为兼容实现路径,但我不建议把它提升为最终的知识本体。 - -因为“李白是诗人的一个个体”与“李白是诗人的子类”并不相同。让每一个事实实体都成为一个类,可能在知识库规模扩大后引入继承关系和个体关系的混淆。 - -更理想的是:让编译器内部明确区分 `Type`、`Entity`、`Fact`、`Function`、`Capability` 等制品类型。Markdown 源码可以继续使用现有的标题、表格和 frontmatter 承载这些信息,不要求立即增加新语法。 - -### 2. 不要让 `check` 与 EKC 各自维护一套知识理解 - -目前 EKC 已经有 Symbol、Capability、Knowledge、Graph 和 REUSE→ADAPT→CREATE 等概念。参见 [engineering-knowledge.md](https://github.com/cflmy/marqdo/blob/main/doc/design/engineering-knowledge.md?utm_source=chatgpt.com)。 - -这里完全没有必要再为 `[]()` 平行开发另一套知识注册表。 - -我建议把架构整理成: - -- 编译器负责产出统一 Semantic IR、符号信息和引用关系; -- `check` 消费这些信息进行验证; -- EKC 将它们投影成知识图和上下文包; -- `view` 消费同一份信息展示可读知识; -- Agent 使用同一份引用解析接口,而不是重新理解 `.mq.md` 文本。 - -如此一来,编译器就是事实上的知识系统基础,EKC 不再承担第二次解释源码的职责。 - -### 3. 不要认为“描述过期”和“知识过期”是一回事 - -仓库中的 [occlusion-syntax.md](https://github.com/cflmy/marqdo/blob/main/doc/design/occlusion-syntax.md?utm_source=chatgpt.com) 已经意识到遮蔽会产生信任负债,并设计了标签引用一致性和新鲜度检查。这是有价值的方向。 - -但是,三类变化必须区分: - -| 变化 | 应该检查什么 | -| ------------- | -------------- | -| 实现变了,描述没变 | 描述是否仍与行为一致 | -| 知识来源变了,函数没变 | 知识事实是否仍然有证据支持 | -| 引用目标变了,代码还能运行 | 是否仍满足原始契约和版本要求 | - -尤其是第三种:AI 幻觉可能表现为调用了一个真实存在、类型也正确、但是业务含义完全错误的函数。 - -纯粹的符号解析和类型检查抓不住这种错误。因此,需要让能力契约、适用范围和知识来源成为可检查的制品属性,而不是只依赖 `[]` 中的自然语言。 - -## 七、建议的实施顺序 - -不要一次性实现完整知识图谱、版本锁定、自动修复和复杂本体系统。我建议分成四个阶段,每一阶段都必须有独立的可执行验收。 - -| 阶段 | 核心交付 | 必须通过的测试 | -| ------------ | ------------------------------------- | ---------------------------------- | -| P0 · 统一引用语义 | `[]()` 的统一 AST、目标类型识别、正文/代码上下文区分 | 不再因 Classic/Occlusion 模式造成静默错义 | -| P1 · 稳定寻址 | 项目符号索引、类函数解析、稳定 Symbol ID、静态 LinkInfo | 两文档李白示例无需实例化即可完成解析与引用 | -| P2 · 可验证知识制品 | Semantic Artifact、契约、来源、指纹、统一诊断 | 删除目标、修改签名、改变来源,均得到准确诊断 | -| P3 · 确定性复用 | 依赖图、制品锁定、EKC 集成、Agent 引用优先策略 | AI 不重新生成已存在的能力;错误、过期和不适用的知识被阻止直接复用 | - -我特别建议设置一个不依赖 LLM 的核心验收实验: - -准备 100 个知识单元,包含同名符号、跨文档引用、版本变更、类型不匹配、来源缺失、循环依赖和正常复用。由程序自动生成和验证预期结果。 - -先证明编译器能够正确识别、绑定和诊断这些情况,再引入 AI 测试上下文成本和幻觉率。否则很容易把模型能力、索引召回率与编译器的正确性混在一起。 - -## 八、重新评价 Marqdo 的研究主张 - -过去 Marqdo 的核心叙述是: - -> 代码即文档,文档即知识库,知识即可执行。 - -我认为现在可以把它变得更加严格: - -Marqdo 是一种将人类可读文档编译为可寻址、可验证、可执行、可复用的知识制品的语言与编译系统。 - -这个定位的价值不在于“Markdown 可以运行代码”,也不在于“Markdown 链接能调用函数”。这两点单独来看都不足以形成很强的研究贡献。 - -它真正值得探索的创新组合是: - -一份自然语言与程序混合的源码,经过统一编译后,同时生成可执行程序、语义符号体系、验证证据、版本化知识引用和 AI 可消费的复用接口。 - -当然,这仍然是一个待证明的系统设计目标,而不是当前 v2.0.0 已经达到的状态。 - -## 最终判断 - -你的 `[]()` 方向值得保留,甚至值得作为下一轮 Marqdo 核心架构调整的切入点。但我不建议继续把主要精力投入到如何让 `[]()` 兼容更多语法、更多函数调用形式或更多 Markdown 场景。 - -你现在缺少的不是更漂亮的链接语法,而是一个由编译器负责维护的“知识身份与语义绑定层”。 - -这也是我认为应该优先修正当前 [link-syntax.md](https://github.com/cflmy/marqdo/blob/main/doc/design/link-syntax.md?utm_source=chatgpt.com) 的地方:它现在主要把链接理解为“表达式 + 描述 + 元数据”;下一版应明确规定,表达式可以解析到独立的、具有身份与验证状态的知识制品。 - -当这种绑定成立时,`[]()` 才能够同时实现你的两个愿望:读者看到自然语言,AI 获取确定性知识引用,编译器负责确保引用并非凭空想象。 - -而且,这次改变不必要求用户学习更多语法。真正增加的复杂度应当留在编译器和知识中间表示内部,而不是继续转嫁到 `.mq.md` 的作者身上。 - - -是的。我认为你这个判断是正确的,而且它指出了我上一轮分析中的一个偏差:我把实现可执行知识体系所需要的技术条件,提升成了 Marqdo 的最终目标。 - -实际上,这两者应当区分。 - -你最初提出的: - -> 代码即文档,文档即知识库,知识即可执行。 - -并不只是一句理念性的口号,它本身已经包含了完整的目标链条: - -1. 代码即文档:知识与程序不再被割裂为两套独立的表达体系。 -2. 文档即知识库:文档中的内容不再只是供人阅读的信息,而是可以被组织、定位、理解和关联的知识。 -3. 知识即可执行:知识不再停留在被检索和解释的阶段,而是能够被直接调用、组合和复用。 - -其中,知识复用就是第三阶段最重要的结果之一。 - -因此,我之前提出的“可寻址、可验证、可执行、可复用”,实际上是在描述达成第三阶段需要具备的工程性质,而不是一个比原始理念更高层次的新目标。 - -## 真正需要解决的是:什么才算知识被复用? - -我认为这里才是 Marqdo 当前设计最值得深入的地方。 - -假设 AI 需要计算一笔订单的最终价格。 - -传统方式可能是: - -- 检索价格计算文档; -- 阅读文档中的公式和约束; -- AI 自己理解并重新编写计算逻辑; -- 执行新生成的代码。 - -这个过程中,知识被读取了,但未必真正被复用。AI 仍然可能理解错误、遗漏约束或生成不一致的实现。 - -而你想实现的 Marqdo 应该是: - -``` -订单最终价格为[计算后的价格](订单.最终价格(订单数据))。 -``` - -这里 AI 不需要重新理解定价公式并生成一套新算法,而是引用已经存在的知识实现。 - -如果该实现的身份、依赖、契约和适用条件都能被确定,那么 AI 的任务就从: - -“根据知识重新生成答案或程序” - -转变成: - -“发现知识 → 判断是否适用 → 引用知识 → 执行知识 → 使用结果” - -这才是 Marqdo 的核心价值。 - -## 所以,`[]()` 应该承担什么角色? - -我建议将整个体系理解成: - -代码即文档 - -统一人类叙述与机器可执行内容 - -文档即知识库 - -知识具有结构、身份、关联与约束 - -知识即可执行 - -知识能够被确定性引用、调用和组合 - -知识真正复用 - -AI 优先使用既有知识,而非反复解释和重新生成 - -`[]()` 不需要独自完成这一切。 - -它应该成为整个体系中知识从文档进入使用场景的统一入口。 - -而编译器、符号系统、知识索引、验证系统与 EKC,则共同保证这个入口背后的知识可以可靠使用。 - -这里有一个很重要的区别: - -- `[]()` 负责表达“我要使用这段知识”。 -- 编译器负责确定“究竟是哪段知识”。 -- 验证系统负责判断“这段知识是否满足当前使用条件”。 -- 运行时负责执行知识。 - -这些职责不应该全部压到 `[]()` 的语法设计上。 - -## 我现在更倾向于保留你的原始理念 - -甚至不建议用我之前那段冗长的定义替换它。 - -“代码即文档,文档即知识库,知识即可执行”已经足够准确。 - -真正值得补充的是它背后的一个技术原则: - -> 知识复用应当基于已编译知识的确定性引用,而不是基于自然语言的重复解释与生成。 - -这句话比单纯强调“可寻址、可验证”更接近你真正想解决的 AI 问题。 - -不过还需要保持一个边界:确定性引用能够减少 AI 在重新解释和生成过程中产生的错误,却不能自动保证被引用的知识本身正确。因此验证仍然必要,只是它属于实现可靠复用的手段。 - -我认为 Marqdo 下一步最值得研究的,已经不是“如何让文档变成知识库”,而是一个更具体的问题: - -如何让一个 AI 在面对新任务时,能够像编译器复用已有函数一样,直接复用知识库中已经编译的知识,而不必重新理解和生成它? - -如果 Marqdo 能真正解决这个问题,你原来的三句话就不再只是设计理念,而是一个可以通过实验验证的语言能力。 - -# Marqdo 可执行知识体系:设计规范与完整范例 - -我已经基于 Marqdo 当前仓库的语法规范、`[]()` 设计、知识分层、对象模型和 EKC,整理了两份详细文档。 - -这次设计保留了你的原始理念: - -> 代码即文档,文档即知识库,知识即可执行。 - -核心目标不是让 AI 更容易生成 Marqdo 代码,而是让 AI 尽可能不必重新生成已经存在的知识,转而通过编译器确定性地发现、引用、验证和执行既有知识。 - -第一份:完整架构设计规范 - -涵盖语义制品、知识引用、编译器架构、解析优先级、效应安全、版本管理、EKC 集成、Agent 复用协议和实施验收。 - -阅读设计文档 - -第二份:多文件可执行知识范例 - -以虚构书店定价为例,从原始政策文档开始,逐步构造知识定义、对象、计算能力、业务入口、AI 问答、知识复用和错误验证。 - -阅读完整示例 - -两份文档打包 - -下载 ZIP - -## 一、这份设计最重要的三个决定 - -# Marqdo 可执行知识体系:核心设计纲领 - -**核心理念:代码即文档,文档即知识库,知识即可执行。** - -## 1. 知识是可编译的语义制品 - -文档经过 Marqdo 编译器处理后,不只产生可执行逻辑,还应产生具有稳定身份、类型、签名、契约、依赖关系、来源和验证状态的语义制品(Semantic Artifact)。 - -知识可以表现为事实、函数、能力、约束、数据集或类型。它们无需全部被强制编码为类。 - -## 2. `[]()` 是知识使用的统一入口 - -`[描述](目标)` 保留 Markdown 的可读性。 - -- `[]` 面向人类,描述意图、意义或用途。 -- `()` 面向编译器,包含既有 Marqdo 表达式或者可解析的知识目标。 -- 描述不改变执行结果,也不能作为可信性依据。 -- 编译器负责将目标解析为确定的符号身份,并验证使用条件。 - -既支持隐藏不易阅读的代码,也支持引用已经编译的知识。 - -## 3. AI 复用知识,而不是重新解释知识 - -AI 面对新任务时,应该遵循: - -**Discover → Resolve → Verify → Reuse → Execute → Trace** - -当知识缺失或不适用时,才进入 ADAPT 或 CREATE 流程。 - -检索可以模糊,但最终绑定必须确定。验证必须区分程序可执行性、契约符合性和现实事实正确性。 - -## 4. 编译器是知识系统的基础 - -AST、Semantic IR、符号索引、链接关系和知识验证应当由同一套语义体系产生。 - -解释器、字节码 VM、View、EKC 和 Agent 消费统一的编译结果,而不是各自重新解析文档。 - -## 5. 最终验收标准 - -一个 AI 能够发现现有知识、确定其身份、检查适用条件、直接执行既有能力、引用结果和来源,并在知识发生变化时识别受影响的调用者。 - -只有这条链条成立,Marqdo 才真正实现知识的可执行复用。 - -## 二、示例将展示什么 - -我选择了一个具有明确规则和复用价值的业务案例,而不只是使用“李白出生年份”这样的静态事实。 - -用户购买两件单价 60 元的商品,金卡折扣为 90%,满 100 元免运费。 - -AI 要处理的业务请求 - -> 请计算这笔金卡订单的最终应付款,并解释依据。 - -传统路径 - -检索政策 → AI 阅读规则 → 重新推导计算 → 生成新代码或答案 - -Marqdo 目标路径 - -发现定价能力 → 绑定已编译函数 → 检查输入与政策 → 执行 → 引用结果 - -目标语法示意(v2.1+,不是 v2.0.0 实测) - -``` -**应付 = [订单最终应付款](定价.计算应付金额(60, 2, "金卡"))** -``` - -根据演示政策计算 - -# ¥108 - -这套例子进一步展示了参数和返回值、类与继承、表格、条件分支、循环、跨文档调用、自然语言遮蔽,以及知识来源改变时的影响分析。 - -## 三、与当前版本的兼容边界 - -我特别保留了一个重要区分:设计目标不等于当前已经实现的功能。 - -根据这次读取的仓库内容,v2.0.0 已支持本地表达式遮蔽、对象、方法、控制流、表格集合、导入以及现有 EKC 基础;但无实例类函数调用、跨文档知识自动解析、完整 LinkInfo 和语义制品绑定仍需要进一步开发。 - -因此示例文档明确标注了目标语法和现有兼容写法,没有将尚未验证的代码描述为已经跑通。 - -## 四、我的主要架构建议 - -我认为接下来的开发不应该从 `[]()` 的外观继续扩展,而应该先实现: - -统一符号索引 → 稳定知识身份 → 引用绑定 → 契约验证 → EKC 复用。 - -还有一点值得特别强调:我不赞成为了建立知识系统,再单独实现一个与 Marqdo 解释器并列的“知识编译器”。那样会重新制造你希望消除的表示碎片。 - -更合适的架构是让现有 Marqdo 编译管线产出统一的语义中间表示,然后由运行时、View、EKC 和 Agent 各自消费。 - -这意味着 Marqdo 的知识体系不是一个外挂的 RAG 框架,而是语言本身的语义能力。 - -我认为这才是整个设计中最值得投入资源,也最有可能形成独立研究贡献的部分。 \ No newline at end of file diff --git a/doc/next/010.md b/doc/next/010.md deleted file mode 100755 index da2b4ac..0000000 --- a/doc/next/010.md +++ /dev/null @@ -1,374 +0,0 @@ -请你重新阅读marqdo的官方库,掌握marqdo的最新进度。在我对marqdo项目的仔细审视之下我发现有一点没有闭环,我终于找到了,考虑现在智能体开发最常用的SKILL,这是一个markdown文件写明了智能体该干什么,我想要更推荐一步,因为marqdo使用markdown语法,支持叙述和代码相互混合,这就使得marqdo满足这样一个条件,当分章节的SKILL撰写下来,只要经过调整就能成为一份marqdo代码其中包含若干函数,我打算开发新的CLI命令marqdo > 函数名 函数参数或者marqdo call 函数名 函数参数 此时SKILL的不同章节就变成了不同的函数,智能体就真正的成为了将知识复现的作用,这让代码即文档、文档即知识,知识即可执行推进了一步变成了知识即工具,真正发挥了marqdo的优势,同样这样的执行还以为着智能体能够自行改进SKILL并接受确定的问题后修改而不会出错,这让自我进化的智能体成为了具备理论支撑和清晰边界的可能 - -# Marqdo 从“可执行知识”走向“知识即工具”:最新仓库审查与架构建议 - -我认为你这次找到了 Marqdo 一个非常重要、而且比单纯增加 `marqdo call` 命令更深层的突破口。 - -你实际上提出了一个新的统一关系: - -> SKILL 是人和 AI 都能阅读的操作知识;Marqdo 可以让其中具有确定性执行语义的章节,直接成为可调用的工具。 - -这样,Agent 的职责就有机会从“阅读说明、理解步骤、临时生成实现”,转向“定位已有能力、填入参数、执行和验证结果”。 - -这与 Marqdo 原来的三句话是连续的,不需要推翻原来的定位: - -代码即文档 → 文档即知识库 → 知识即可执行 → 知识即可作为工具使用。 - -不过我建议把“知识即工具”视为可执行知识的对外使用形态,而不是再创造一套与语言、知识库平行的 Skill 运行系统。 - -## 一、重新检查仓库后的最新情况 - -本次核对的是 [cflmy/marqdo](https://github.com/cflmy/marqdo?utm_source=chatgpt.com) 的 `main` 分支,HEAD 为 `4018e992`,`Cargo.toml` 版本为 2.1.5。最近的 v2.1.5 版本记录日期是 2026 年 10 月 27 日。 - -与我们之前讨论 v2.0.0 时相比,项目已经完成了不少与你的构想直接相关的基础建设。 - -| 相关能力 | 最新仓库证据 | 判断 | -| --------------------- | ---------------------------------------------------------------- | -------- | -| 跨文档确定性函数绑定 | `BoundCall`、`SymbolId`,Tree/Bytecode 双后端测试 | 已有核心基础 | -| 已编译知识的执行复用 | MLSP `artifact.bind`、`artifact.execute`、`artifact.reuse_execute` | 已有子集 | -| Agent 复用已有函数 | `agent_eng_bind_execute`、发布门禁 | 已有子集 | -| 指定函数执行 | `marqdo run --call-lib-path`、JSON 参数、隔离 worker | 已有底层入口 | -| 智能体工具规范 | `ToolSpecV1`、效应分类、权限检查与恢复设计 | 已有框架基础 | -| 章节式 SKILL 自动成为 CLI 工具 | 目前没有独立的 `marqdo call` 或 Skill 编译命令 | 待开发 | -| SKILL 自修改、自动测试和受控发布 | 已有局部修改、验证与沙盒组件 | 尚未形成完整闭环 | - -因此,现在不是重新开发一个 Skill 执行器,而是将已存在的 Marqdo 函数、知识制品、工具协议和 Agent 机制统一起来。 - -还有一个与你的新构想直接相关的问题值得先修复: - -最新官方 `skills/marqdo/SKILL.md` 的核心语法说明,与仓库中的现行解析器、v0.3 语法规范和可执行测试存在冲突。 - -目前解析器与测试使用的是: - -- `**…**`:代码、赋值、调用等语句; -- `*…*`:返回值。 - -但官方 Skill 顶部却把两者反过来描述。这不是小的文档笔误:如果 Agent 按照错误规则自我修改 Skill,就可能产生与实际运行时不一致的程序。 - -这个真实存在的不一致,恰好证明了你所说的闭环为什么重要——SKILL 不能仅靠自然语言说明自己的正确性,它需要由语言编译器和实际测试提供独立验证。 - -## 二、你真正提出的是一种新的 Skill 体系 - -我建议把它暂时命名为 Executable Skill(可执行技能)。 - -它不应被理解为“给 Markdown Skill 增加一点代码”,而应当满足一个更严格的定义: - -> Executable Skill 是一份以 Markdown 为人类可读接口、以 Marqdo 函数为确定性执行单元、以编译后的语义制品为工具身份、能够由 Agent 发现、调用、验证和改进的技能文档。 - -传统 Skill 与你的目标之间,存在一个非常重要的区别。 - -| 维度 | 普通 Markdown Skill | Marqdo Executable Skill | -| ---- | ----------------------- | ----------------------- | -| 技能说明 | 自然语言 | 自然语言 | -| 操作步骤 | Agent 阅读后自行实施 | 可以绑定已有 Marqdo 函数 | -| 函数接口 | 通常需要额外编写工具代码 | 从 `.mq.md` 的函数和契约生成 | -| 执行 | 依赖 Agent 选择工具、生成代码或操作软件 | 对已实现的步骤直接执行 | -| 输出验证 | 往往需要单独建立 | 可连接编译器、契约和测试 | -| 改进 | 编辑说明或脚本 | 编辑同源的知识与实现,验证后发布 | -| 可追踪性 | 主要依赖工具日志 | 可关联 SymbolId、源码、版本和执行结果 | - -但不是每个 Skill 章节都应该自动变成可执行函数。 - -比如“适用场景”“注意事项”“禁止操作”是知识或约束;“检查订单”“生成报价”“汇总报告”才可能成为可调用能力。编译器应区分文档章节与可执行章节,不能把所有二级标题不加判断地暴露成工具。 - -### 这实际上使 Agent 的结构发生变化 - -SKILL.md - -目标 · 流程 · 函数 · 契约 · 示例 · 约束 - -Marqdo Skill Compiler - -章节解析 · 符号绑定 · 类型检查 · 效应分析 - -Knowledge View - -Agent 阅读技能与限制 - -Tool Registry - -Agent 调用已编译函数 - -Agent:选择、组合、执行、观察与改进 - -由语言运行时执行确定性部分,由模型处理非确定性判断 - -特别值得注意的是:这不仅是执行接口的统一,还是知识交付接口的统一。 - -同一份 Skill 能够投影成可读说明、CLI 函数、Agent Tool Schema、MCP 工具描述,以及知识库中的能力节点。实现这些投影的系统仍是同一个 Marqdo 编译器。 - -## 三、CLI 应采用 `marqdo call`,不要采用 `marqdo >` - -你提出了两个命令形式: - -``` -marqdo > 函数名 函数参数 -marqdo call 函数名 函数参数 -``` - -我明确建议采用第二种。 - -原因是 `>` 在 Bash、PowerShell、CMD 等 Shell 中已经具有输出重定向语义。`marqdo > xxx` 会被 Shell 先行解释,无法可靠地作为传递给 Marqdo 的函数调用语法。 - -推荐设计为: - -``` -# 按函数名调用 -marqdo call "订单计算.商品小计" \ - --skill ./skills/order-calculator \ - --arg 单价=30 \ - --arg 数量=2 - -# 结构化调用,供 Agent 使用 -marqdo call "订单计算.商品小计" \ - --skill ./skills/order-calculator \ - --args-json inputs.json \ - --output json \ - --policy pure -``` - -上述是建议新增的 CLI 接口,不是 v2.1.5 已支持的命令。 - -我还建议在 CLI 层保留一个便利别名:`marqdo skill call`。它与 `marqdo call` 进入同一个 dispatcher,不应分别实现两套调用逻辑。 - -### 最小必要的 CLI 能力 - -| 命令 | 作用 | -| ---------------------------- | ----------------------- | -| `marqdo skill inspect PATH` | 解析 Skill 文档、章节、可调用函数和依赖 | -| `marqdo skill list PATH` | 列出对 Agent 暴露的工具 | -| `marqdo skill check PATH` | 检查语法、绑定、签名、效应和工具导出规则 | -| `marqdo call TARGET` | 调用指定 Marqdo 函数并返回结果 | -| `marqdo skill test PATH` | 执行 Skill 的测试与契约检查 | -| `marqdo skill export PATH` | 生成通用工具描述或 MCP 暴露接口 | -| `marqdo skill trial PATH` | 对修改后的候选版本进行隔离验证 | -| `marqdo skill promote PATH` | 在门禁通过后发布新版本 | -| `marqdo skill rollback PATH` | 恢复到指定已接受版本 | - -不过不建议一次性实现这九项命令。最小可用产品只需要 `inspect`、`call`、`check`、`test` 四项,版本发布与改进机制可以随后补齐。 - -最重要的技术决策是: - -`marqdo call` 必须调用现有编译器绑定的函数,不得重新用字符串搜索源码、猜测章节位置再执行。 - -当前 [src/mlsp.rs](https://github.com/cflmy/marqdo/blob/main/src/mlsp.rs?utm_source=chatgpt.com) 已有 `artifact.bind` 与 `artifact.execute`,能够检查制品指纹、依赖闭包、来源摘要和效应策略。新的 CLI 应复用相同的应用服务和语义校验,而不是通过进程内调用 MLSP JSON 接口制造另一层重复协议。 - -还有一个现有实现细节:`marqdo run --call-lib-path` 已支持隔离 worker 通过 JSON 参数调用函数,但当前 `src/lib.rs` 的这个入口只在树遍历分支中处理,Bytecode 分支仍按普通程序入口执行。新的公开 `call` 命令需要补齐这一差异,或者明确在第一版只支持 Tree backend,不能静默忽略所选后端。 - -## 四、完整示例:让一份 Skill 同时成为文档、知识和工具 - -我建议第一版尽量保持作者体验简单:人只维护一份 Markdown 源文件,编译器自动生成工具描述、函数索引和知识制品。 - -例如,我们建立一个订单计算 Skill。 - -下面是目标设计示例。其中 `runtime` 和 `tools` 是我建议为 Skill 编译增加的元数据约定,目前不能将这份 `SKILL.md` 直接交给 v2.1.5 的 CLI,期待自动注册工具。 - -``` - ---- -name: order-calculator -description: 订单价格计算,包括商品小计和含税金额 -runtime: marqdo -tools: - - 订单计算.商品小计 - - 订单计算.含税金额 ---- - -# 订单计算 - -这份技能用于计算订单金额。 - -所有金额使用同一货币单位。税率使用小数表示, -例如 0.10 表示 10%。 - -## 商品小计 - -给定商品单价`单价`和购买数量`数量`, -计算未税商品小计。 - -*[商品小计](单价 * 数量)* - -## 含税金额 - -给定商品单价`单价`、购买数量`数量` -和适用税率`税率`,计算含税金额。 - -**小计 = [计算商品小计](订单计算.商品小计(单价=单价, 数量=数量))** - -*[最终含税金额](小计 * (1 + 税率))* - -``` - -这里的计算是演示规则。正式业务技能还需要校验数量范围、金额精度、货币单位、税率适用条件与舍入规则;这些不能由函数名字自动推断为正确。 - -### 这份 Skill 会产生三种投影 - -给人阅读: 它是一份正常的 Markdown 文档。读者能理解每个步骤的目的,以及所需输入和返回值。 - -给 Marqdo 编译器: 两个 `##` 单元构成可解析的函数;第二个函数可以确定性地调用第一个函数;符号索引能够记录它们的依赖关系。 - -给 Agent 使用: 编译器输出两个工具的结构化描述。Agent 不需要重新生成乘法计算程序,只需选择工具并提供参数。 - -例如,编译后的工具描述可以是: - -``` -{ - "id": "order-calculator::订单计算.商品小计", - "description": "计算未税商品小计", - "input_schema": { - "type": "object", - "properties": { - "单价": {"type": "number"}, - "数量": {"type": "number"} - }, - "required": ["单价", "数量"] - }, - "output_schema": { - "type": "number" - }, - "effect": "pure" -} -``` - -但这个 Schema 必须由明确的类型契约和编译器检查生成。若源文件没有足够的类型信息,应标记为未知或要求补全,不能因为变量参加了乘法就无条件断言它一定是 `number`。 - -需要强调:不是 `##` 标题自动等于一个公开工具。 `##` 让章节具备 Marqdo 函数的结构,`tools` 则声明哪些函数允许对外暴露。这样才能避免“安全说明”一类章节被意外注册成工具,也避免内部辅助函数被 Agent 随意调用。 - -### 为什么采用显式的 `runtime: marqdo`? - -因为普通 Skill 的 Markdown 本来就可能包含 `**加粗内容**`、编号列表、代码块和二级标题。这些在现有 Marqdo 中可能具有执行语义。 - -如果直接把所有 `SKILL.md` 当成 `.mq.md` 执行,很可能发生严重的语义误读。 - -所以我建议: - -- 未明确声明 Marqdo 运行时的 `SKILL.md`,仍然是普通 Markdown 文档。 -- 明确声明 `runtime: marqdo` 的 Skill 才进入 Marqdo 编译流程。 -- 内嵌示例代码块不应因展示而执行。 -- 编辑器应对具有执行意义的 Markdown 标记提供可视化提示。 -- 导出的工具必须经过独立检查和授权。 - -未来还可以支持从已有普通 Skill 中自动提取候选函数,但那应当是生成可审阅的转换补丁,而不是默认把自然语言步骤当成已经实现的代码。 - -## 五、这次最有价值的部分:自我改进的 Skill - -你提出的第二层意义,我认为甚至比 `marqdo call` 更值得研究。 - -传统 Agent 修改一个 Skill 时,常见问题是:它修改了一段说明或脚本,却无法可靠判断其他步骤是否受到影响。 - -Marqdo 已经具备一些适合解决这个问题的基础,例如 `SymbolId`、依赖闭包、`artifact.patch`、`artifact.verify` 和知识影响分析。 - -但是,不能由此推出“智能体修改 Skill 就不会出错”。 - -更精确的目标是:智能体可以提出改进,系统能够判定一组明确、可测试的性质是否被保持,并且只有通过门禁的版本才有资格替换原有 Skill。 - -我建议采用以下演化协议: - -已发布 Skill v1 - -现有稳定版本与完整依赖 - -1\. 发现确定的问题 - -失败测试、诊断、复现步骤或用户提出的明确修改要求 - -2\. AI 生成局部修改候选 - -只修改获准的章节或函数,记录版本与修改意图 - -3\. 编译与静态验证 - -语法、符号、参数、返回类型、效应、依赖关系 - -4\. 隔离测试与回归验证 - -目标问题修复、历史行为保持、异常输入、性能与权限边界 - -5\. 发布门禁 - -仅当策略允许且必要验证通过时晋升新版本;否则保留旧版本 - -Skill v2 · 已接受版本 - -可追溯、可回滚、后续调用绑定到明确版本 - -### 举一个真正的自我改进案例 - -原 Skill 中存在: - -``` -## 商品小计 - -商品单价`单价`,购买数量`数量`。 - -*[小计](单价 * 数量)* -``` - -现在发现一个确定的问题:输入 `数量=-1` 时,函数返回负数,但业务要求数量必须大于零。 - -Agent 不应该只是把说明修改成“数量必须大于零”。这不会改变执行行为。 - -它应当在候选版本中增加可执行的校验逻辑,并补充至少三个测试: - -| 测试 | 输入 | 期望 | -| ---- | ----------- | ------------- | -| 正常订单 | 单价 30,数量 2 | 返回 60 | -| 非法数量 | 单价 30,数量 -1 | 返回结构化参数错误 | -| 边界数量 | 单价 30,数量 0 | 根据业务契约决定接受或拒绝 | - -如果 Marqdo 尚不具备合适的语言级错误返回或异常处理方式,这个案例还会暴露一个语言能力缺口:需要一种由 Marqdo 程序自身构造、传递和处理错误的机制,而不是只能依赖 Rust 宿主报错。 - -这与此前我们讨论的通用语言能力重构是直接关联的。 - -### 自我进化的边界必须比普通代码修改更严格 - -我建议把以下约束固定下来: - -1. 修改不能自动扩大权限。 原 Skill 只有纯计算权限,新版本不能因为 Agent 自己添加网络或文件操作就获得这些权限。 -2. 候选版不能直接覆盖运行中的正式版本。 需要隔离工作区、原子发布和固定引用版本。 -3. 必须证明目标问题被修复。 不允许通过删除测试、放宽断言或隐藏失败来宣称成功。 -4. 测试通过不是绝对正确的证明。 未覆盖的业务情况、外部事实和依赖服务仍可能出错。 -5. 高风险修改需要更严格的发布决策。 尤其是支付、外部写入、删除、凭证和安全策略变更,不能由被修改的 Skill 自己批准。 - -最新仓库的 `artifact.patch` 已经提供基于摘要的修改和有限回滚,但它还不是完整的候选版本事务与测试后晋升系统。现有 `HostCaps` 的默认值也允许文件写入、执行、网络和插件,因此新 `call` 的安全默认值应当收紧,不能简单继承普通本地运行的全部宿主权限。 - -这就是“有界自我进化”的含义:不保证 Agent 永不犯错,而是让它能够在可验证、可回滚、可限制权限的范围内持续改进。 - -## 六、我建议如何安排开发 - -| 阶段 | 目标 | 关键验收 | -| ---------------- | ---------------------------------------- | ------------------------ | -| S0 · Skill 语义一致性 | 修复官方 Skill 与解析器的标记冲突,建立 Skill 语法同步测试 | Skill 记载的每条核心语法都有可运行金样例 | -| S1 · 函数调用 CLI | `marqdo call` 调用已绑定的普通函数、类函数和跨文档函数 | JSON 参数正确绑定;错误路径和双后端行为明确 | -| S2 · Skill 编译 | 对显式启用的 `SKILL.md` 解析章节和可执行函数 | 自动产生 SymbolId、签名、依赖、导出清单 | -| S3 · 知识即工具 | 将公开函数编译为 ToolSpec,并接入现有 Agent dispatcher | Agent 不重新生成实现即可调用并取得结果 | -| S4 · Skill 测试 | 增加 `skill check/test`、负例、效应门禁和回归测试 | 未通过验证的 Skill 不得自动发布 | -| S5 · Skill 演化 | 实现候选修改、隔离验证、影响分析、版本晋升与回滚 | 修改失败不影响已发布版本,权限不能自行扩大 | - -这里还需要一项对你的研究目标尤其重要的对照实验。 - -让相同模型分别使用普通 Markdown Skill、Markdown Skill 加外部脚本工具、以及 Marqdo Executable Skill 完成相同的一组任务。分别测量正确率、模型需要重新生成的代码量、工具调用参数错误、修改后的回归失败率、token 消耗和完成时间。 - -只有与“Markdown + 现有工具调用”进行公平对照,才能证明 Marqdo 的优势来自文档、程序与知识的统一,而不只是因为它额外提供了一个执行器。 - -## 七、我对这项构想的最终评价 - -我认为这次构想具有三个非常值得肯定的性质。 - -第一,它有明确的语言基础。`#`、`##`、自然语言叙述、函数参数、`[]()`、契约表和跨文档符号绑定并不是为了 Skill 重新创造的。Skill 可以成为现有语言的一种应用形态。 - -第二,它有真实的工程基础。当前 Marqdo 已经具备部分确定性绑定、制品验证、Agent 复用与隔离运行能力。你需要做的是将这些能力收敛到统一的公开接口,而不是重新实现一套 Agent 框架。 - -第三,它能够引出一个更有研究价值的问题:自然语言描述的操作知识,如何逐步转化为可调用、可检查、可维护,并可由 Agent 在受限条件下自行改进的程序制品? - -但是,“SKILL 章节即函数”本身还不足以证明新的编程范式。Markdown 章节映射函数,与文学编程、文档驱动工作流及现有工具包装有明显的共同点。 - -更有价值的是把三个原本需要单独维护的对象——Skill 说明、函数实现、Agent Tool Schema——统一为一个可编译的源事实,并展示这种统一确实降低了错误、维护成本和重复生成成本。 - -我建议为 Marqdo 保留原来的核心理念,并将这一阶段的技术方向明确为: - -> 知识即工具(Knowledge as Tool):将可执行知识直接编译为 Agent 能够发现、调用和验证的工具,并允许智能体在明确的语义、测试和权限边界内持续改进这些知识。 - -这可能是 Marqdo 从“AI 可以使用的编程语言”,进一步走向“AI 能够使用并维护的可执行知识体系”的关键一步。 - -备注,这里实际上有一点叙述错误,marqdo支持mq.md文件,所以最好针对SKILL也是SKILL.mq.md这样会比较统一。 \ No newline at end of file diff --git a/doc/next/011.md b/doc/next/011.md deleted file mode 100755 index 3917ac7..0000000 --- a/doc/next/011.md +++ /dev/null @@ -1,249 +0,0 @@ -SKILL的名称应该是.mq.md有一点必须提及,SKILL其实命名不一定必须得是SKILL,平常的一个marqdo文件也可以是一份skill这里的设计太复杂了没有抽离出来核心本质,你看对于一个平常的marqdo文件,完全也可以和SKILL一样,这都是没有区别的,所谓的知识即工具作为高度抽象本质就是带参数调用函数,所以你的inspect等等命令其实完全可以对传统的marqdo也生效而不是非要绑定SKILL对吧,而且这样处理还有好处是方面智能体做单元测试,单个函数是否可以带参数直接运行,换句话说,你仔细思考就会发现这些好处是marqdo的设计哲学在增加一点点call自然派生的优势,所以不需要繁复的设计 - -你说得对。这次我认为你抓住了真正的核心,而且我的上一版设计确实把一个本来很自然的语言能力复杂化了。 - -Marqdo 根本不需要引入一种叫作 Executable Skill 的新概念,也不需要专门建立 Skill 编译器。 - -因为在 Marqdo 的设计哲学下: - -> 一个 `.mq.md` 文件本身就是文档、知识与程序。只要允许从外部直接调用其中的函数,它自然也就能够成为 Skill。 - -这不是为 Skill 开发一套新系统,而是为 Marqdo 补齐一个非常基础的语言使用入口。 - -## 一、真正缺少的只有一件事:函数级执行入口 - -Marqdo 当前已经支持函数定义、参数、返回值、模块引用,以及确定性符号绑定。 - -但是日常使用时,我们往往仍然站在“运行整个文件”的角度: - -``` -marqdo run example.mq.md -``` - -你现在提出的是: - -``` -marqdo call example.mq.md 函数名 参数 -``` - -这实际上意味着: - -Marqdo 的最小可执行单位,从文件进一步扩展为文件中的任意可调用函数。 - -而这一点会自然派生大量优势。 - -普通 `.mq.md` 文件 - -自然语言叙述 + 函数 + 参数 + 返回值 - -marqdo call - -指定函数 + 绑定参数 + 直接执行 - -知识复用 - -调用已存在的实现 - -Agent Skill - -直接暴露函数为工具 - -单元测试 - -逐个函数验证结果 - -自我改进 - -修改函数并重新测试 - -这里不存在四套实现,只有一个底层能力的四种使用方式。 - -## 二、一个普通的 Marqdo 文件就足够了 - -比如,文件 `calculator.mq.md`: - -``` -# 计算器 - -这是一个普通的 Marqdo 文档。 - -其中包含一些可以复用的数学计算知识。 - -## 加法 - -计算两个数字`a`和`b`的和。 - -*[计算结果](a + b)* - -## 乘法 - -计算两个数字`a`和`b`的积。 - -*[计算结果](a * b)* -``` - -它既是可阅读的文档,也包含两个函数。 - -现在只需要支持: - -``` -marqdo call calculator.mq.md 计算器.加法 a=2 b=3 -``` - -返回: - -``` -5 -``` - -再比如: - -``` -marqdo call calculator.mq.md 计算器.乘法 a=4 b=6 -``` - -返回: - -``` -24 -``` - -以上 `marqdo call` 是拟新增的命令形式;函数示例遵循当前 `*…*` 返回、`[]()` 遮蔽的语义。 - -这时候,一个 Agent 只要能够读取这个 `.mq.md` 文档,就可以理解函数的用途;只要能够调用 Marqdo CLI,就能执行其中的能力。 - -它根本不需要关心这个文件是不是 Skill,也不需要一份特殊的 `SKILL.md`。 - -如果 Agent 把它当成 Skill 阅读和使用,它就是 Skill;如果开发者把它当成程序库调用,它就是程序库;如果研究者把它作为知识库中的一部分,它就是可执行知识。 - -文件的身份没有变化,变化的是使用方式。 - -## 三、这项能力会自然解决三个问题 - -### 1. 让知识成为工具 - -传统 Skill: - -Agent 阅读操作说明,决定如何完成任务。 - -Marqdo: - -Agent 阅读函数说明,找到适合的函数,传入参数,直接执行。 - -这就将原来的: - -知识 → Agent 理解 → 重新实现 → 执行 - -缩短为: - -知识 → 函数定位 → 参数调用 → 执行 - -但模型仍然需要负责判断应该调用哪个函数、传入哪些参数。确定性的是被调用函数的语言语义,而不是整个 Agent 决策过程。 - -### 2. 让单元测试成为语言的天然能力 - -我非常赞同你提到的单元测试价值。 - -有了 `marqdo call`,可以直接测试: - -``` -marqdo call calculator.mq.md 计算器.加法 a=2 b=3 -# 期望 5 - -marqdo call calculator.mq.md 计算器.加法 a=-2 b=3 -# 期望 1 - -marqdo call calculator.mq.md 计算器.乘法 a=0 b=100 -# 期望 0 -``` - -不必为了测试一个函数,再创建一个 `# main`,再编写调用、打印和结果检查的包装程序。 - -未来即使增加 `marqdo test`,底层仍然可以复用同一个函数调用接口。 - -### 3. 让 Agent 可以针对知识进行局部改进 - -这是你提出的最有意义的延伸。 - -假设一个 Agent 发现 `计算器.乘法` 对某类输入存在错误。 - -它可以: - -1. 阅读相应函数及其上下文。 -2. 修改这个 `.mq.md` 文件中的函数实现。 -3. 直接用 `marqdo call` 传入错误输入验证。 -4. 再运行该函数的历史测试。 -5. 如果检查通过,就提交候选修改;否则保留原有实现。 - -这使得 Agent 的改进对象不再仅仅是自然语言提示词,而是有明确输入、输出和可执行语义的知识单元。 - -当然,测试不能证明函数在所有输入上都正确;正式发布和权限控制仍需要遵循已有的项目验证机制。但不需要为此创造一套 Skill 专属的演化协议。 - -## 四、真正的 CLI 设计可以非常简单 - -我建议第一阶段只做一个命令: - -``` -marqdo call <文件> <函数> [具名参数...] -``` - -比如: - -``` -marqdo call book.mq.md 订单.计算总价 单价=30 数量=2 -``` - -它只需要完成五件事: - -| 步骤 | 职责 | -| -- | -------------------- | -| 1 | 加载指定 `.mq.md` 文件及其导入 | -| 2 | 解析并唯一定位目标函数 | -| 3 | 根据现有函数签名绑定、校验参数 | -| 4 | 使用现有运行时执行该函数 | -| 5 | 返回函数结果和结构化错误 | - -额外提供一个 `--json` 输出选项就足够方便 Agent 调用。 - -如果未来需要 `marqdo inspect`,它也应该针对任何 `.mq.md` 文件,列出其中函数、参数和文档描述,而非限定 Skill。 - -此外,当前仓库已经有 `--call-lib-path` 和 `artifact.execute` 的相关基础,因此实现时应尽量复用现有函数定位与执行机制,而不是重复开发解释器。 - -唯一值得坚持的边界是:外部调用仍必须经过现有权限检查,不能因为新增了 `call` 就默认允许 Agent 对任意函数执行文件删除、网络写入等操作。 - -## 五、我认为你的设计哲学现在更加清晰了 - -你原来的理念: - -> 代码即文档,文档即知识库,知识即可执行。 - -实际上已经足够完整。 - -“知识即工具”不是额外的设计理念,而是“知识即可执行”在函数级调用能力成熟后自然出现的结果。 - -进一步看,这件事还有一个很漂亮的对称性: - -| 参与者 | 对同一个 `.mq.md` 的使用方式 | -| ---------- | ------------------- | -| 人类 | 阅读文档、理解知识 | -| 编译器 | 解析并验证函数 | -| 开发者 | 调用函数、组合程序 | -| Agent | 发现知识、调用工具 | -| 测试系统 | 输入参数、检查结果 | -| 维护者或 Agent | 修改实现、验证改进 | - -这些角色并没有要求作者维护六份不同的东西。 - -同一份文件,同一套语义,同一个函数调用接口。 - -这也恰恰是我认为 Marqdo 相比传统“Markdown 文档 + 外部工具”组合最值得证明的优势:知识描述与执行实现共址,而且能够直接由语言工具链消费,避免维护重复的工具包装和操作说明。 - -所以,我现在的建议与上一轮不同: - -不要开发 Executable Skill 系统。不要设计 Skill 专属语法。不要引入新的 Skill 注册、编译和执行机制。 - -先完成 `marqdo call`,使普通 `.mq.md` 中的可调用函数都能被精确定位、传参执行,并用现有语义系统验证。 - -这是一个相对很小的接口变化,却可能自然打通 Marqdo 的编程、知识复用、Agent 工具调用和函数级测试四个场景。 - -我认为这才是你所说的:让 Marqdo 自己的设计哲学发挥作用,而不是不断增加外部框架来证明它的价值。 \ No newline at end of file diff --git a/doc/next/012.md b/doc/next/012.md deleted file mode 100755 index 1c868f3..0000000 --- a/doc/next/012.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: 作者对于marqdo的价值认识 -author: cflmy ---- - -# main - -诚实的说,作者其实一直都很纠结说marqdo是否具有存在的必要,不过在逐渐的开发和了解中,marqdo -是有价值的,我此时此刻确信这一点。 - -在过去的很长时间中,我一直在思考,marqdo代码即文档,文档即知识库,知识库可执行有什么作用呢? - -## code as document,document as skill,skill is tools - -现在我给出的答案是,code as document,document as skill,skill is tools. - -试想一个.mq.md文件,只需要撰写下来,智能体只需要每次执行: -``` -marqdo call 文件名 函数名 函数参数 -``` -就能直接的得到执行结果,之后进行下一步的判断,更近一步,我们甚至可以在函数内写分支,但是让智能体决定走哪一个分支,让skill和tools不再强行分离。 - -甚至更近一步 - -``` -marqdo call 文件名 函数名 函数参数 toget 返回值 -``` - -得到返回值,在同一个会话进行多次的操作,之后记录下来,我们以后必定能够复现出来。 - -再进一步呢,智能体的输出就是marqdo脚本,只需要单步运行就能够得到结果。 - -## ABI插件 - -除此之外还有编程语言的特色,ABI插件,在deepseek harness中插件被证明是skill、mcp等的极好 -接入方式,那么有没有可能marqdo可以实现每一个插件都是通过ABI接入的? - -我想答案似乎是可以的。 - -这种情况下拓展库应该怎么设计呢? - -我觉得应该按照模块设计 - -index.mq.md - 依赖1 - …… - 依赖2 - …… - -其中index.mq.md就是这个拓展库的SKILL文档,AI只需要阅读这个文档就知道该怎么使用这个拓展库。 - -甚至更近一步的,index.mq.md本身就是一个可执行的文档,包含拓展库的全部功能。 - -## 叙述代码是否足够? - -我想叙述性文字在AI编程中是非常重要的,所以,我在这里提出一个编程规范: - -> 所有的函数叙述性文字必须和实际文字混合且超过50% - -进行**校验**如果通过则**通过**否则**不通过** - -这应该是我写的第一个SKILL即tools吧 - -所有的拓展库都要规划成为这样。 - -skill即tools有一个绝妙的地方那就是tools是函数,函数本身就对应一个操作,这个操作就是一个工具,所以每个skill都只需要调用本身就可以是tools了,同时marqdo的设计中包含有### 更深层的函数,这就是子工具了 \ No newline at end of file diff --git a/doc/next/013.md b/doc/next/013.md deleted file mode 100755 index c17a3db..0000000 --- a/doc/next/013.md +++ /dev/null @@ -1,702 +0,0 @@ -我实际开发了一下,觉得借助外部框架反而会拖累marqdo的特性发挥,应该将marqdo的智能体框架优化一下,方便实际的开发工作。我觉得重点在于以下几个方面: -上下文操作,允许用户方便的进行用户输入和marqdo文件级、类级、函数级的提示词拼接和注入。 -能够等待模型输入进行便捷的模型控制执行流 -能够控制模型开启并发操作,进行多智能体并发执行 -能够便捷的解析模型的输出,对于不是很稳定的模型也能实现交互 -易于拓展 - -我认为这次应该对 Marqdo 的智能体框架进行一次**面向文档原生执行的架构升级**,而不是继续给 qdagent 增加包装层。 - -结合你此前对小模型、极短 SKILL 和递归调用的要求,我认为新的设计目标应该是: - -> **Marqdo 文档负责描述任务,模型负责作出选择,Marqdo Runtime 负责控制执行。** -> -> 模型不必理解整个智能体框架,只需要完成当前函数要求的一个小决策。 - -这与传统 Agent Framework 的区别在于:我们不应让模型不断生成复杂的工具调用协议,也不应要求它理解隐藏的框架状态机。它只需要返回简短结果,后续的判断、等待、路由、并发以及恢复都可以交给 Marqdo。 - -## **一、从现有代码看,真正缺少的是什么** - -我查看了目前 `marqdo/main` 的 `ext/ai/agent.mq.md`、`ext/ai/llm.mq.md`、`lib/subtask.mq.md`,以及相关设计文件。 - -Marqdo 并不是缺少智能体基础设施,而是**已有能力尚未形成面向普通 Marqdo 作者的简洁统一接口**。 - -| 目标能力 | 当前基础 | 需要补充 | -| ------- | ------------------------------------------------- | ------------------- | -| 上下文操作 | `build_step_context`、`ContextPackV2`、`llm.prompt` | 文件/类/函数级的精确提取和组合 | -| 模型控制执行流 | `agent.step`、`model_turn`、`resume` | 简短模型结果驱动的条件分支、等待和恢复 | -| 多智能体并发 | `subtask.spawn`、`wait`、`run_many` | 模型任务级的派发、并发配额、结果汇合 | -| 不稳定输出解析 | `LLMResult`、`CALL:`/`DECISION:` 解析 | 枚举选择、宽容解析、类型验证和有限修复 | -| 易于扩展 | `.mq.md` 函数、插件、MCP、SKILL 编译 | 一套简单、稳定的开发者门面 | - -尤其值得注意的是,当前 `ext/ai/agent.mq.md` 已经增长为约 256 KB 的大型文件,包含大量内部编排函数。这不意味着它一定会被完整送入模型,但说明开发接口和内部机制已经有明显的分离价值。 - -我建议此次重构的原则是: - -**不新增第二种编程语言,不重写 Agent Runtime,不破坏现有 SKILL。只给 Marqdo 增加几个真正必要、可以自然组合的智能体操作。** - -## **二、我建议提供的五项原生能力** - -### **1. 上下文:让函数所在的文档自动成为提示词** - -这是我认为最有 Marqdo 特色、也最应该优先实现的部分。 - -当前已有 `source_brief` 和 `skill_brief`,但开发者仍需要理解智能体的上下文组装机制。我希望把它进一步转化为**编译器可寻址的上下文投影**。 - -**当前用户输入** - -始终保留本轮最新消息 - -文件级 - -全局职责 - -类级 - -当前领域 - -函数级 - -当前动作 - -**ContextPack** - -按需拼接、去重、裁剪,然后交给模型 - -建议默认只注入当前函数和必要的祖先说明,不注入全部兄弟函数。 - -| 范围 | 读取内容 | 典型用途 | -| ---------- | ----------------- | -------- | -| `file` | 文件级说明、约束与能力概述 | 根 SKILL | -| `class` | 当前 `#` 类的说明和继承的约束 | 子领域 | -| `function` | 当前 `##` 函数的说明与契约 | 单次模型决策 | -| `full` | 指定范围的完整源码 | 显式请求深入理解 | - -这里必须使用 Marqdo 的 AST、模块身份和函数作用域来提取内容,不能简单用正则截取标题。 - -进一步建议增加一个可直接调用的 `ai.context`,支持 `scope="function"` 等选择,并允许 `user=` 提供显式输入。普通交互可以从当前调用会话获取最新用户消息;独立的 `marqdo call` 则能够明确传入该消息,便于复现和单元测试。 - -**一个重要细节:文档片段是提示上下文,不代表执行这些片段。** `import` 也不应默认把依赖模块的完整内容注入模型。 - -### **2. 等待模型:让模型返回值直接控制 Marqdo 分支** - -现阶段 Marqdo 已经支持条件分支,真正需要的是一个足够简单、能够阻塞等待模型结果的函数。 - -例如拟增加: - -`ai.choose(options=...)` - -模型只需要从提供的选项中选择一个,Marqdo 负责等待结果、解析结果、验证选项,然后把结果交给原有分支语句。 - -在此基础上保留: - -| 接口(拟议) | 职责 | -| ----------- | ---------------- | -| `ai.ask` | 等待模型生成文本或指定类型的结果 | -| `ai.choose` | 等待模型从给定选项中选择 | -| `ai.start` | 发起非阻塞模型任务 | -| `ai.wait` | 等待任务完成并获取结果 | - -`ask` 和 `choose` 默认是同步的。只有真正需要同时处理多个任务时,作者才使用 `start` 和 `wait`。 - -这意味着控制流无需新增 `if AI`、`await AI` 等语言关键字,也不必为了执行一步模型决策创建完整的工作簿。 - -对于需要用户回答的场景,还应区分 `waiting_model` 和 `waiting_user`。后者必须能持久化当前执行位置,并由会话输入恢复,不能在函数内部长期阻塞一个模型或 HTTP 请求。 - -### **3. 并发:直接并发执行 **`.mq.md`**,而不是另造 Agent 类型** - -当前 `lib/subtask` 的实现已经相当接近目标。 - -它支持创建子任务、等待、轮询,以及 `run_many` 的受限并发执行。因此不需要再做一套独立的 Multi-Agent Framework。 - -我建议新增薄封装: - -`ai.parallel(tasks=..., limit=2)` - -其中每个任务都引用一个实际存在的 `.mq.md` 文件、可调用函数和输入。 - -**父 Marqdo 函数** - -子 SKILL A - -资料检索 - -子 SKILL B - -方案评估 - -子 SKILL C - -风险分析 - -**结果汇合** - -父函数获取三个独立返回值 - -每个子任务是独立的执行上下文,不继承父模型完整历史,只接收明确传入的任务、允许使用的能力与必要文档。 - -还需要统一限制并发数、模型请求配额、超时与取消。尤其在单张 GPU 上运行多个小模型任务时,任务并发不意味着推理一定能并行;Runtime 应允许共享模型服务进行排队,而不是为每个子智能体重复加载模型权重。 - -### **4. 输出解析:优先理解短文本,不强迫小模型生成复杂 JSON** - -这项能力对小模型尤其重要。 - -例如,模型本来只需要回答 `chat`,但实际可能生成以下任意一种结果: - -chat - -chat - -我选择 chat - -chat - -选择:chat,因为用户希望对话 - -chat - -\`\`\`text\ -chat\ -\`\`\` - -chat - -这些结果都可以被确定性地规范化为相同选项;无需再调用一个模型来解释前一个模型。 - -我建议采用递进式解析: - -| 层级 | 行为 | -| ---- | ------------------------ | -| 精确 | 完整匹配合法选项 | -| 规范化 | 处理空白、代码围栏、常见选择前缀 | -| 受限提取 | 从明确的选择字段中提取唯一合法选项 | -| 有界修复 | 无法确定时,只让模型重新输出选项标识 | -| 失败返回 | 仍不确定、多个选项冲突时返回 `invalid` | - -**不能为了追求成功率而随意猜测。** 模型同时提到 `chat` 和 `office`,不意味着可以选择其中第一个。工具执行、文件写入等高风险动作更不能依赖模糊匹配。 - -可以支持模型服务的 constrained decoding,但不应强制所有小模型使用复杂 JSON Schema。2026 年针对小模型的结构化输出研究也指出,格式合法性提高不一定意味着语义决策更正确。 - -[image](https://www.google.com/s2/favicons?domain=https://ijcai.org\&sz=32) - -ijcai.org+1 - - - -### **5. 扩展:把能力沉到 Marqdo 库,而不是产品框架** - -建议新增的接口仍保持 Marqdo 的现有组织习惯: - -``` -ext/ai/ - index.mq.md # 简短导航 - flow.mq.md # 模型控制流 - context.mq.md # 文档上下文 - parse.mq.md # 模型结果解析 - parallel.mq.md # 智能体并发 - agent.mq.md # 现有高级编排,保留兼容 - llm.mq.md # 现有模型抽象 -``` - -这些是拟议的新文件划分,不代表当前仓库已经实现。 - -每份 `.mq.md` 自身仍是一份可以阅读的 SKILL,公开 `##` 函数即工具,不需要再维护独立的 Tool Schema。真正需要操作系统、异步调度或模型推理后端的部分,复用 Rust Runtime 与现有插件。 - -特别是 `flow.mq.md`,我建议它成为日常智能体开发的**极薄门面**,而不是把现有大型 `agent.mq.md` 再复制一遍。 - -## **三、理想中的开发体验:两个函数就能完成根 SKILL** - -这是最重要的验收标准:**经过框架升级,原先的 qdagent 根入口不应该变复杂,反而应该更短。** - -下面展示我希望实现的最终作者体验。注意,这是**拟议的新接口示例**,当前 Marqdo 2.7.1 还不能直接运行这些新函数。 - -``` - ---- -markup: occlusion -title: 求道智能体入口 -import: - ai: ext/ai/flow.mq.md ---- - -# main - -你是求道智能体。 - -每次收到非空用户输入,先提供简短选项, -等待用户确认,再进入对应的 SKILL。 -这里只负责意图确认和路由,不执行具体任务。 - -## 分解意图 - -根据`用户输入`生成两个简短方向, -每个方向说明好处和代价。 - -**选项 = [让模型生成意图选项](ai.ask(input=`用户输入`, output="options", count=2))** - -**确认 = [展示选项并等待用户回复](ai.input(options=`选项`))** - -返回*确认*。 - -## 路由函数 - -根据确认后的`用户意图`选择下一层 SKILL。 - -**目标 = [让模型选择已有的技能](ai.choose(input=`用户意图`, options=["chat", "office"]))** - -返回*[进入对应的 SKILL](ai.enter(skill=`目标`))*。 - -``` - -这份入口只保留两个业务函数。运行时自动提供函数级上下文,模型不需要认识 `ai.input` 的暂停实现,也不需要理解 `ai.enter` 的模块加载机制。 - -其中 `ai.input` 应该由 Marqdo Runtime 原生支持持久化暂停:展示选项后释放执行资源,收到用户回复时从原执行位置恢复。qdagent 只需要实现用户消息和选项卡的传输、展示。 - -`ai.enter` 只能接受已登记的 SKILL 标识,运行时解析为实际文档,并校验权限与函数入口。不能直接执行模型任意返回的文件路径。 - -这样,真正复杂的东西存在于 Marqdo Runtime,而不是每份 SKILL 的正文中。 - -## **四、开发顺序:先做最小闭环,再扩展并发** - -我建议按下面的依赖顺序推进,避免一开始就大规模重构 `agent.mq.md`。 - -**P0 — 文档上下文与模型选择** - -在 `src/frontend` 的 AST/符号定位基础上,建立文档作用域提取;给 `ext/ai` 增加 `context`、`ask`、`choose` 的轻量接口。 - -验收:一个函数能够使用自己的说明与用户输入,完成一次模型选择,不依赖 `agent.plan`。 - -**P1 — 用户等待与跨 SKILL 续执行** - -在现有 Runtime checkpoint、会话和事件基础上增加可持久化的 `input`、`enter`。恢复时检查文档版本、用户回复和调用权限。 - -验收:qdagent 从意图选择卡暂停,用户回复后继续进入聊天 SKILL;服务中断后也可以安全恢复。 - -**P2 — 并发模型与多智能体** - -将 `subtask.run_many` 包装为可接收模型与 SKILL 任务的 `ai.parallel`,加入每个子任务独立上下文、模型选择、取消、超时和结果汇合。 - -验收:三个独立 SKILL 可以同时运行,父函数获得全部成功或失败结果,且不会重复提交有副作用的操作。 - -**P3 — 小模型可靠性与开发工具** - -整合输出解析、自动修复和轻量上下文预算;增加实际调用测试、trace 与 `marqdo view` 中的模型决策展示。 - -验收:测试格式正确率、真实意图命中率、工具执行正确率和 Token 消耗,而不是只检查输出是否符合 JSON 格式。 - -这里还有一个建议:先挑选约 100~200 条实际意图、路由、人格切换、函数调用用例,使用目标 1B 小模型测试,再与当前的 `agent.step` 方式比较。重点测量每次决策输入 Token、输出 Token、有效选择率、修复轮数和最终任务成功率。并发部分还要独立测量吞吐量、等待时延和取消后的资源回收。 - -## **五、这次升级最关键的架构决定** - -我不建议立即修改 Marqdo 的 19 个核心语法构造。现有的 `#`、`##`、`###`、GFM 表格、描述链接、返回值和条件分支,已经足够表达智能体编排。 - -真正值得修改的是 Marqdo 的**执行能力与开发体验**: - -| 层次 | 应承担的职责 | -| ------------------- | ------------------- | -| Marqdo Language | 函数、参数、分支、文档作用域 | -| Marqdo AI Extension | 上下文、模型推理、选择、解析 | -| Marqdo Runtime | 任务等待、恢复、并发、权限 | -| `.mq.md` SKILL | 当前任务的自然语言规则与少量可执行操作 | -| qdagent | 人格、交互界面、模型配置、用户数据 | - -这也直接呼应了 Marqdo 仓库中 [doc/next/012.md](https://github.com/cflmy/marqdo/blob/main/doc/next/012.md?utm_source=chatgpt.com) 提出的构想:*code as document, document as skill, skill is tools*。 - -我的核心建议是将此次升级首先锁定在 **“函数级上下文投影 + 等待模型选择 + 原生用户暂停恢复”** 这个最小闭环。 - -只要这三个能力完成,qdagent 的根 SKILL 就能够独立驱动一次真实的意图确认和递归路由。后续聊天、Office、代码开发、科研等 SKILL 都可以基于同样的简单函数组合构建。 - -**这次改进的价值不在于 Marqdo 能支持多少种 Agent,而在于让一个很小的模型,只阅读几十行文档、输出几个字,就能够可靠地控制一个复杂的可执行系统。** - -一个智能体框架很重要的一点是错误处理和恢复上面展示的内容看上去确实不错但是错误处理和恢复这些写的不够好,我希望达成的目标是减少错误,这依靠框架本身,但是一旦出现无法避免的错误,请你给出框架应该怎么应对这些问题 - -我认为,Marqdo 的智能体框架应该把**错误预防与自动恢复提升为 Runtime 的原生能力**,而不是依靠每份 SKILL 自己编写重试逻辑,更不能依靠大模型不断阅读错误日志、重新思考和重新执行。 - -对于你希望使用的 1B 左右小模型,这一点尤其重要。 - -我建议确立一个核心原则: - -> **能由编译器和运行时避免的错误,不交给模型;能由确定性程序恢复的错误,不重新调用模型;只有必须重新作出语义判断时,才让模型介入。** - -而且恢复必须满足三个条件: - -- **不重复做**:已经成功的步骤不得因为后续失败而无故重新执行。 -- **不丢失结果**:即使最终任务失败,也保留已经完成的工作与验证证据。 -- **不假装成功**:无法确定执行结果时,明确标记为未知,而不是猜测成功或失败。 - -## **一、Marqdo 现有基础与真正的问题** - -我重新检查了 [ext/ai/agent.mq.md](https://github.com/cflmy/marqdo/blob/main/ext/ai/agent.mq.md?utm_source=chatgpt.com)。当前代码已经具备相当一部分可靠性基础: - -| 现有能力 | 当前作用 | 仍需加强 | -| ----------------------------- | ---------- | ----------------------- | -| `error_make` | 构造结构化错误 | 统一所有 AI 调用与 SKILL 的错误出口 | -| `error_decide_retry` | 有界重试判断 | 自动选择具体恢复策略 | -| `resume_save/load` | 保存、恢复检查点 | 与函数执行位置、用户等待和子任务统一 | -| `effects_prepare/transition` | 记录副作用执行状态 | 在所有可能写入的操作前强制应用 | -| `effects_reconcile` | 对账不确定的执行结果 | 自动检测、恢复和阻断不安全的重复执行 | -| `subtask.spawn/wait/run_many` | 子任务和并发 | 失败隔离、部分成功与子任务恢复 | - -此外,源码已经提供 `checkpoint_v2` 选项,但 `resume_save` 的默认值还是 `False`。而 `run_tool` 在缺失原生 Agent 插件时存在能力较弱的兼容执行路径。 - -这些说明 Marqdo **不需要再造一个恢复框架**,但需要把分散的能力统一为可靠的默认执行语义,特别是消除容易绕过严格校验的路径。 - -### **我建议的总体执行模型** - -**Marqdo SKILL 函数调用** - -**执行前预检** - -类型 · 上下文 · 权限 · 预算 · 依赖版本 - -**受控执行** - -模型调用 / 普通函数 / 子 SKILL / 并发 - -**结果验证** - -格式、类型、业务条件、执行证据 - -**成功提交** - -记录结果并继续 - -**恢复控制器** - -分类、恢复或安全中止 - -这里的“恢复控制器”应是 Rust Runtime 的确定性机制,不是另一个依赖 LLM 的智能体。 - -它可以在必要时请求模型作出局部判断,但错误处理本身不能依赖模型是否足够聪明。 - -## **二、先预防:让错误尽可能无法进入执行阶段** - -对于 Marqdo,我建议设置四道防线,但全部由框架自动完成,不要求 SKILL 作者编写额外逻辑。 - -| 防线 | 框架自动完成 | 可以阻止的问题 | -| --- | --------------------- | -------------- | -| 编译前 | 检查函数签名、依赖、参数、类型 | 调用不存在的函数、参数错误 | -| 推理前 | 检查上下文范围、模型能力、Token 预算 | 上下文溢出、错误模型配置 | -| 执行前 | 校验模型输出、工具权限、资源版本 | 幻觉工具、非法路径、过期文件 | -| 提交前 | 验证返回值、操作结果和执行证据 | 错误结果被当作成功、重复写入 | - -这里有两个关键设计。 - -首先,**模型只产生候选值,不直接决定程序是否成功**。例如要求模型选择 `chat` 或 `office`,框架在验证之后才允许结果进入路由函数。模型说“已执行成功”,也不能代替真实的执行回执。 - -其次,**要把模型的不确定性限制在最小的函数范围内**。一次 `ai.choose` 只需要理解当前函数及两个选项,不应该携带整个 qdagent 的执行历史。上下文不够时读取相关内容,而不是无条件扩充系统提示词。 - -这种设计降低的是错误发生概率,不保证模型的语义判断必然正确。语义正确性仍需要任务相关的验证或用户确认。 - -## **三、错误发生后,框架必须先分类,再采取不同动作** - -我不建议把所有错误交给一个通用 `retry()`。 - -因为“模型选项格式错误”和“文件写入后进程崩溃”,虽然都叫失败,但适合的处理方式完全不同。 - -下面是我建议的默认恢复策略。 - -| 错误情况 | 框架应该怎么做 | 是否重新调用模型 | -| -------------- | ------------------- | -------- | -| 模型输出格式不正确 | 规范化、匹配合法值,必要时要求重新输出 | 最多一次 | -| 模型选择不在选项内 | 拒绝非法值,重新请求明确选择 | 必要时一次 | -| 上下文超过限制 | 删除冗余、提取相关函数、重新计算预算 | 通常不需要 | -| 模型请求超时、429 | 检查超时与限流,退避后重试 | 可以 | -| 模型返回错误事实 | 通过验证器识别问题,提供局部修正依据 | 可能需要 | -| Marqdo 函数参数错误 | 根据已知契约检查并修正可确定的问题 | 通常不需要 | -| SKILL 文件或函数不存在 | 重新解析注册目录;不存在则终止 | 不应盲目重试 | -| 权限不足、凭证失效 | 保存现场,要求用户或管理员处理 | 不需要 | -| 文件版本冲突 | 重新读取最新版本,重新计算变更 | 可能需要 | -| 子智能体执行失败 | 保留其他成功结果,仅处理失败子任务 | 视情况 | -| 写入结果不确定 | 查询外部结果和效应账本,不得直接重做 | 不应重新决策 | -| 运行时崩溃 | 恢复检查点,检查未完成操作后继续 | 通常不需要 | - -默认恢复应该有预算,例如传输请求总共最多三次尝试、输出修复一次、代码局部修复一至两次。这些属于初始策略参数,不应该变成语言硬编码的限制。 - -同时必须识别**重复失败循环**:如果同一个输入、同一个错误、同一个版本连续失败两次,且没有新证据,自动终止该恢复路径,避免小模型陷入无限生成。 - -### **恢复策略应当分层** - -**L0 · Runtime 自行修复** - -无需 LLM - -清理格式、重新获取连接、读取检查点、重建缓存、解析已知选项 - -**L1 · 确定性替代路径** - -已注册的备用工具、已有知识命中、只读降级、可验证的本地计算 - -**L2 · 小模型局部修复** - -只给模型失败字段、允许选项和必要证据,不再发送全部上下文 - -**L3 · 安全停止与交接** - -保存成功进度,报告错误、未决操作和能够安全继续的入口 - -L0 到 L2 只在恢复动作被验证为安全、且仍有预算时继续;不可逆写入、权限拒绝等错误可能直接进入 L3。不能把这套层级理解为所有错误都要逐层尝试。 - -**这是最适合小模型的重要改进之一:大部分错误不应该消耗额外的推理 Token。** - -## **四、真正困难的部分:如何做到失败后继续,而不是重新运行** - -这是我认为整个框架最值得投入研发资源的部分。 - -假设一份 Marqdo 文档依次完成: - -读取用户输入 - -已完成 - -分析与确认意图 - -已完成 - -进入 Office SKILL - -已完成 - -生成演示文稿 - -执行中断 - -交付结果 - -尚未执行 - -此时的正确恢复方式,不是重新运行 `# main`,更不是重新询问用户意图。 - -而是从“生成演示文稿”的可恢复边界继续执行,并复用之前的意图确认结果。 - -### **关键机制:函数级 Checkpoint + 执行日志** - -现有 CheckpointV2 已经提供良好的基础,但建议将它从 Agent 的可选机制进一步发展为**支持暂停的 Marqdo 执行会话的默认机制**。 - -每个可恢复边界记录这些信息: - -| 信息 | 作用 | -| ------------------ | ----------------- | -| `run_id / step_id` | 明确是哪次执行、哪一步 | -| 文档与函数 digest | 确保恢复的还是原始逻辑 | -| 参数、局部变量或结果引用 | 保留后续执行需要的数据 | -| 已完成步骤记录 | 跳过已经成功的操作 | -| 当前等待原因 | 等用户、等模型、等子任务或需要对账 | -| 副作用账本位置 | 判断写入是否发生 | -| 权限、资源版本和剩余预算 | 防止旧状态绕过新限制 | - -在实现上,我倾向**优先采用语句/函数边界的持久化续体(continuation)**,而不是一开始就尝试保存任意 Rust 调用栈。 - -如果当前解释器无法序列化整个运行帧,可以先从已提交的步骤边界恢复,再通过执行日志复用此前的结果。这要求可重放部分具有确定性,所有外部效应都由账本管理。 - -特别注意:`ai.input` 等待用户时,应提交暂停状态、释放执行资源。用户恢复时必须匹配原来的 `run_id`、输入请求 ID 和文档版本,不能把回复当作新的根任务重复执行。 - -类似的恢复问题在其他框架中也存在。例如 LangGraph 的部分中断机制会在恢复时重新执行节点,所以特别要求中断前的副作用具备幂等性。Marqdo 可以争取在语句/函数粒度提供更直观的恢复语义。 - -[image](https://www.google.com/s2/favicons?domain=https://github.com\&sz=32) - -GitHub+1 - - - -## **五、最不能出错的地方:副作用执行后崩溃** - -考虑这样一个场景: - -智能体调用“发送邮件”,邮件已经成功发出,但进程在收到确认结果之前崩溃。 - -如果框架简单重试,就可能把同一封邮件发送两次。 - -这个问题无法只靠模型解决。 - -我建议将 Marqdo 已有的 EffectLedger 变成所有带副作用工具的强制执行路径: - -`prepared` · 记录执行意图与幂等标识 - -`started` · 开始真实操作 - -**committed** - -有成功回执,允许复用结果 - -**unknown** - -先对账,不自动重做 - -其处理应当遵循: - -| 状态 | 恢复行为 | -| ------------------ | -------------------- | -| `prepared` | 尚未开始真实效应且有可信证据时,可以开始 | -| `started` | 如果执行中断,先调查,不能推断未生效 | -| `committed` | 直接复用已保存的成功结果 | -| `failed_no_effect` | 确认无效应后,才根据策略决定重试 | -| `unknown` | 查询外部资源、回执、版本;无法确认就阻断 | -| `reconciled_*` | 使用对账后的事实决定是否继续 | - -对接外部工具时,应提供可选的 `reconcile` 查询能力。外部系统支持幂等键就使用稳定幂等键,不支持则尽可能使用状态查询与版本校验。 - -对于已执行的动作,如果存在业务上明确、安全的逆操作,可以进行补偿;但不能把补偿等同于数据库事务回滚。 - -这一点与 Temporal 的可靠任务设计原则一致:外部操作可能在完成后、记录结果前失去连接,所以必须单独处理幂等性和不确定状态。 - -[image](https://www.google.com/s2/favicons?domain=https://github.com\&sz=32) - -GitHub+1 - - - -**Marqdo 不能承诺所有外部操作都严格只执行一次;它应承诺绝不在结果未知时盲目重试不可逆操作。** - -## **六、多智能体错误:允许局部失败,不让整个任务雪崩** - -将来支持 `ai.parallel` 后,可能出现三个子智能体同时工作,其中一个失败。 - -我建议父智能体按照任务依赖与结果完整性决定下一步,而不是默认重新启动全部子任务。 - -| 子任务状态 | 父级处理 | -| ------ | ------------- | -| 成功 | 缓存结果和验证状态 | -| 暂时性错误 | 仅安全重试该子任务 | -| 无法恢复 | 标记失败并保留错误证据 | -| 需要用户输入 | 保存该分支的等待状态 | -| 已取消 | 不再自动重启 | -| 写入状态未知 | 阻断依赖这一写入的后续动作 | - -例如三个子 SKILL 分别负责资料检索、方案分析和风险评估。当资料检索失败时,已经完成的风险评估不应该无条件被抛弃。 - -如果任务要求三份结果必须齐全,父函数进入 `partial` 或 `blocked`;如果允许部分交付,则可以返回两份成功结果,但必须标注缺失项。 - -并发管理还要处理取消传播:父级取消时停止新任务,通知运行中的子任务,并等待它们清理;已经发生的外部副作用不能假定被撤销。 - -## **七、让恢复不破坏极短 SKILL 范式** - -你的根 SKILL 仍然只应有两个函数。 - -例如未来可以继续这样编写(下面的 `ai.choose` 是拟议接口): - -``` - -## 路由函数 - -根据`用户意图`选择下一层 SKILL。 - -**目标 = [选择合适的技能](ai.choose(input=`用户意图`, options=["chat", "office"]))** - -返回*目标*。 - -``` - -注意,这段函数完全没有重试逻辑、异常捕获或状态维护。 - -模型正常时,`ai.choose` 返回一个短字符串;框架校验成功后,`路由函数` 正常返回。 - -模型异常时,由 Runtime 根据错误类别处理。必要时暂停整个可恢复执行会话。对调用方暴露统一的执行结果,而不是要求模型理解复杂的恢复协议。 - -建议的结果结构可以简化为: - -``` - -{ - "status": "waiting_input", - "value": null, - "error": { - "code": "model.invalid_choice", - "stage": "路由函数" - }, - "resume_id": "run-42", - "recovery": "ask_user" -} - -``` - -这是运行时的结果信封,**不是让小模型生成的 JSON**。正常成功时作者仍然得到原本的 Marqdo 返回值。 - -状态建议至少区分 `succeeded`、`partial`、`waiting_input`、`blocked`、`uncertain`、`failed` 和 `cancelled`。 - -这里 `uncertain` 特别重要:它表示外部执行结果尚未确认,不能简单归类为失败。 - -如果错误被框架自动恢复,SKILL 不需要知道细节。只有恢复耗尽、需要外部输入,或者作者显式要求检查错误时,才将结构化诊断提供给上层。 - -同时保留原始错误、每次尝试、模型用量和恢复动作的执行记录,供 `marqdo view` 和 `debug` 检查。 - -## **八、具体应该修改哪些代码** - -我建议在现有能力上进行增量重构。 - -| 优先级 | 修改位置 | 主要工作 | -| --- | ------------------------------ | ------------------------------------------ | -| P0 | `plugins/agent/src/error.rs` | 建立统一错误分类、恢复动作和策略预算 | -| P0 | `plugins/agent/src/tools.rs` | 强制校验和授权,不允许插件缺失时静默降低安全保证 | -| P0 | `ext/ai/llm.mq.md` | 统一模型超时、格式错误与结果验证出口 | -| P1 | `plugins/agent/src/resume.rs` | 让 CheckpointV2 成为可恢复会话默认格式 | -| P1 | `src/runtime/` | 实现等待输入、步骤恢复、取消与恢复调度 | -| P1 | `plugins/agent/src/effects.rs` | 将效应账本强制接入受控写工具 | -| P2 | `lib/subtask.mq.md` | 增强子任务部分成功、取消和结果恢复 | -| P2 | `ext/ai/flow.mq.md`(新) | 提供简洁的 `ask/choose/input/enter/parallel` 门面 | - -我特别建议先检查 `error.rs` 中当前根据错误代码字符串推断类别的路径。作为兼容机制可以保留,但核心调用应该直接从 LLM Adapter、工具执行器、解释器获得结构化错误码,而不是靠字符串包含 `timeout`、`connect` 等词来识别。 - -另外,生产模式下不能让缺失原生 Agent 插件的情况退化成一个不具备同等效应和权限保证的执行路径。只读实验可以降级,涉及写入的生产调用必须显式拒绝。 - -### **最重要的验收测试** - -**可靠性验收清单** - -0/8 已确认 - -模型输出错误 - -只在允许范围内修复,不路由到错误 SKILL - -429 / 网络中断 - -有界退避,正确计算模型调用和成本 - -意图确认后崩溃 - -恢复后不再次询问同一轮意图 - -外部写入后崩溃 - -不重复执行,先查询真实效应 - -三个子智能体中一个失败 - -保留另外两个成功结果 - -SKILL 源码被修改 - -检测版本变化,不静默恢复旧步骤 - -权限被撤销 - -立即阻断,不利用旧检查点继续 - -恢复失败或预算耗尽 - -返回部分结果和可操作的失败信息 - -重置检查 - -这些测试应使用确定性假模型、假工具和故障注入完成,不能只依赖线上模型的偶然成功。特别要测试进程在每一个关键提交点前后崩溃的情况。 - -## **九、最终我希望 Marqdo 达到的标准** - -我认为这次优化的成功,不应该用“重试后最终完成的任务数量”来单独衡量。 - -还应该关注首次执行成功率、自动恢复成功率、恢复额外 Token、重复副作用次数、恢复时延和人工介入率。 - -其中最重要的是: - -**可自动避免的错误越来越少发生;发生错误时只重做必要的部分;无法安全恢复时保留全部可用成果,并明确告诉用户原因。** - -更进一步,我认为 Marqdo 可以把经过验证的失败恢复方案沉淀成可执行知识。比如某个 SKILL 遇到特定格式错误后成功使用了一个确定性修复函数,系统可以将这一规则作为候选知识,在验证和批准后复用。下次遇到相同情况,甚至不需要再次调用模型。 - -这将形成一个很有价值的闭环: - -**执行 → 错误 → 恢复 → 验证 → 知识沉淀 → 下次预防。** - -它与传统框架只强调容错重试的方向相比,更符合 Marqdo 的核心理念:文档不仅描述智能体该怎么做,还能逐渐沉淀成经过验证、可直接执行的处理能力。 - -我建议把这次框架升级的第一阶段明确收敛为 **“统一错误信封 + 自动恢复策略 + CheckpointV2 默认化 + 安全副作用账本”**。这四项比立即增加更多模型控制函数更优先,因为它们决定了后续所有简短 SKILL 能否真正可靠地运行。 \ No newline at end of file diff --git a/doc/next/014.md b/doc/next/014.md deleted file mode 100644 index a2c727d..0000000 --- a/doc/next/014.md +++ /dev/null @@ -1,575 +0,0 @@ -我会在后续继续完成开发,接下来我比较关心marqdo的知识编译的问题,你认为我将marqdo的函数内的语句成为锚点,或者说带标记的内容都成为锚点,方便使用[]()引用,成为知识编译的一种可行吗? - -**我认为完全可行,而且这可能是 Marqdo 实现“知识编译”最有价值的方向之一。** - -但我建议对你的设想做一个关键调整: - -> **所有可执行语句都成为编译器内部可定位的节点;所有具有明确标记的内容,都可以提升为稳定、可引用的知识锚点。** -> -> 锚点不仅用于跳转,还应该具备语义身份、依赖关系、执行能力、版本和验证状态。 - -这样,Marqdo 的函数就不再是一个只能整体调用的黑盒,而是一组能够逐层寻址、复用、验证和追溯的知识节点。 - -## **一、你的设想实际上已经有实现基础** - -我重新查看了 Marqdo `main` 分支的代码,发现你的想法与仓库已有设计高度一致,并不需要从零开始。 - -在 [可执行知识系统设计](https://github.com/cflmy/marqdo/blob/main/doc/design/executable-knowledge-system.md?utm_source=chatgpt.com) 中,你已经提出: - -- `#`:知识命名空间、类或知识实体。 -- `##`:具备参数和返回契约的可复用函数。 -- `[]()`:为函数内部的知识步骤命名,并保留原有执行语义。 -- 编译器将命名步骤转化为 `KnowledgeStep`,关联依赖、类型、来源和效果。 - -更重要的是,这不只是文档构想。目前 `src/sema/ir.rs` 已经实现了 `KnowledgeRef`、`KnowledgeStep` 和 `collect_named_steps`,并且能够识别部分遮蔽表达式、函数调用、循环和正文知识引用。 - -不过,现在的内部步骤 ID 采用类似 `#step-1`、`#step-2` 的序号形式。这种身份适合单次编译,却不适合长期知识引用:在函数前面插入一条新步骤,就可能改变后面所有步骤的编号。 - -因此,我认为下一阶段的重点不是“再增加一种锚点语法”,而是: - -**将已有的 KnowledgeStep 从编译期记录,升级为具备稳定身份的知识制品。** - -## **二、建议采用“两级锚点体系”** - -这比“把每一条语句都暴露为知识”更合理。 - -| 层级 | 生成规则 | 作用 | -| ------ | -------------------------- | ------------------ | -| 内部锚点 | 所有可执行 AST 语句自动生成 | 调试、数据流、执行追踪、增量编译 | -| 公共知识锚点 | `#`、`##`、带标记的表达式、显式标记的知识内容 | 跨函数引用、搜索、依赖分析、知识复用 | - -例如: - -``` - -# 订单定价 - -## 计算税额 - -根据订单地区查询税率,再计算应缴税额。 - -**税率 = [查询适用税率](税率库.查询(地区))** - -**税额 = [计算应缴税额](金额 * 税率)** - -*税额* - -``` - -编译器可以从这段普通 Marqdo 文档中建立以下结构: - -**订单定价** - -Class · 知识命名空间 - -**计算税额** - -Function · 公开可调用知识单元 - -**查询适用税率** - -Observe / Reuse - -**计算应缴税额** - -Derive - -数据依赖:税率 → 税额 - -**返回税额** - -Return · 函数结果 - -在这个结构中,两个标记步骤各有自己的地址,并且可以独立被查询、检查来源、进行影响分析。 - -这和普通代码索引有根本区别:它不仅知道“这个函数在哪里”,还知道**函数为什么得到这个结果,以及结果依赖哪些知识**。 - -## **三、最关键的语义区分:可引用不等于可执行** - -我认为这里必须制定严格的语义规范。 - -假设一个函数内部存在名为“查询适用税率”的锚点。 - -那么,其他文档引用它时,实际上存在三种不同需求: - -| 操作 | 期望行为 | -| ---- | --------------------- | -| 引用知识 | 找到该步骤,读取说明、实现和出处 | -| 获取结果 | 在已知输入和执行环境中取得该步骤的计算结果 | -| 复用执行 | 重新执行该步骤,产生新的计算结果 | - -**不能因为一个锚点存在,就允许它在任何地方被直接执行。** - -例如,函数内部的“计算应缴税额”依赖局部变量 `金额` 和 `税率`。假如其他函数直接引用这个步骤,编译器必须确认它需要哪些输入。 - -有两种合理的处理方式: - -- 默认只允许引用它的定义、来源和契约。 -- 需要独立执行时,必须拥有完整输入绑定;否则将它提取为独立 `##` 函数。 - -后续可以考虑由编译器自动将满足纯度、闭包与输入条件的知识步骤提升为可调用能力。但这应是第二阶段,不能在最初就隐式执行任何锚点。 - -### **不必重新设计 **`[]()`** 的基本语法** - -可以继续保留现有语义: - -``` -**税额 = [计算应缴税额](金额 * 税率)** -``` - -这里 `[]` 提供知识描述,`()` 保留表达式的执行含义。 - -另外,知识定位可以使用编译后的稳定地址,例如以下**拟议形式**: - -``` -[查看税率依据](mq://pricing/订单定价/计算税额#查询适用税率) -``` - -这应当被解释为知识引用,而不是自动重新执行“查询适用税率”。这里的 `mq://` 是建议的地址表示,不是说当前版本已经支持这样的写法。 - -我建议将 `KnowledgeRef` 按所在上下文分为: - -- 正文:解析目标和展示证据,不产生副作用。 -- 可执行表达式:按原有求值语义执行,并附带引用元数据。 -- 工具或智能体调用:额外要求可调用契约、输入闭合与权限验证。 - -这样 `[]()` 就能成为统一引用形式,同时不破坏现有 Markdown 的可读性。 - -## **四、怎样让锚点稳定** - -这是整个方案技术上最难、也最重要的地方。 - -**知识锚点不能用行号或内容哈希直接作为永久身份。** - -因为代码修改时: - -- 插入语句会改变行号。 -- 修改公式会改变哈希,但可能仍是同一个知识概念。 -- 修改描述名称不一定意味着知识实体改变。 -- 两个函数可能有相同的步骤名称。 - -因此,建议将三个概念拆开: - -| 概念 | 意义 | 变化规则 | -| ---------------- | --------- | --------- | -| `AnchorId` | 知识单元的稳定身份 | 尽量跨版本保持 | -| `ContentDigest` | 当前定义与实现 | 实现发生变化就更新 | -| `EvidenceDigest` | 来源与验证证据 | 证据变化时更新 | - -对于自动生成的锚点,可以先根据模块身份、所属函数、局部名称和结构位置确定候选身份,再通过上一版编译产物中的映射记录保持身份连续。 - -对于需要长期跨文档引用的公共知识锚点,可以允许显式稳定 ID,或者由编译器自动登记到知识索引中。**显式 ID 不必强制写在每个 **`[]()`** 中**,这样才能保持 Marqdo 的简洁性。 - -如果两个同级锚点都叫“查询适用税率”,编译器必须报告歧义,要求进一步限定,不能按出现顺序选择。 - -## **五、知识编译的最终产物应该是什么** - -我认为一个知识锚点至少需要这些字段: - -``` - -{ - "anchor_id": "pricing.tax.lookup", - "owner": "订单定价.计算税额", - "label": "查询适用税率", - "kind": "observe", - "inputs": ["地区"], - "outputs": ["税率"], - "dependencies": ["税率库.查询"], - "effects": ["read"], - "source_span": { - "file": "pricing.mq.md", - "line": 8 - }, - "content_digest": "...", - "evidence": [], - "verification": { - "resolved": true, - "tested": false, - "source_verified": false - } -} - -``` - -这是一份拟议的数据结构,`anchor_id` 仅为示例。 - -这里还有一项值得强调的区别:**知识可以编译成功,但并不代表知识在事实上正确。** - -例如读取“某地区税率”,编译器可以验证依赖、参数、数据类型、调用目标,却无法仅凭这些信息证明外部税率数据仍然有效。 - -所以应当把编译状态、测试状态、来源验证状态和领域正确性分别记录,而不能用一个 `verified=true` 概括所有问题。 - -### **推荐的编译流水线** - -1\. Parse - -读取 Markdown 与 Marqdo AST - -2\. Anchor - -为语句与标记内容建立地址和身份 - -3\. Resolve - -绑定函数、变量、知识引用和依赖 - -4\. Verify - -检查类型、契约、权限、来源和版本 - -5\. Emit - -生成知识图、锚点索引、引用锁与执行制品 - -这基本可以落在当前 `src/sema/` 和 `src/knowledge/` 的基础上,不需要开发第二套语言执行器。特别是现有 `SemanticProject` 已能导出 `steps.json`、`refs.json` 和 `artifacts`;真正需要扩展的是步骤的稳定身份、数据依赖、引用绑定以及验证信息。 - -## **六、我建议下一步怎么实现** - -优先做三个阶段,而不是一下将所有 Markdown 内容变成公开知识。 - -| 阶段 | 主要工作 | 验收 | -| ------- | ---------------------------------------- | ------------------ | -| M1:锚点身份 | 扩展 `KnowledgeStep`,建立稳定 `AnchorId` 和增量映射 | 插入其他语句后,原引用不漂移 | -| M2:锚点引用 | 扩展 `KnowledgeRef` 和语义解析,支持跨函数、跨文档的知识定位 | 能解析、检测歧义、建立反向依赖 | -| M3:知识制品 | 生成可查询的知识图、版本锁、验证与影响分析 | 改一条规则,可定位受影响的结果与叙述 | - -之后再增加局部知识步骤的独立执行、缓存、自动提取为函数,以及智能体按需发现知识的能力。 - -## **七、这对 Marqdo 的真正价值** - -我觉得这一方向比单纯强调“Markdown 可以执行”更有研究价值。 - -传统函数提供的是函数级抽象。你现在提出的机制则能够把抽象进一步下沉: - -**文档 → 类 → 函数 → 知识步骤 → 依赖与证据。** - -当智能体发现某个已有知识满足任务需求时,不需要再次生成代码,也不需要复制一段函数实现。它能够先定位知识节点,查询其契约与依据,再决定是引用现有结果、调用已有函数,还是创建新的知识。 - -但需要避免一个研究上的陷阱:**把语句赋予 ID 本身,不足以构成有说服力的知识编译创新。** 它仍可能被认为只是代码索引或细粒度程序分析。 - -真正值得验证的主张是: - -> **Marqdo 能否把自然语言标记与可执行语义编译为统一、稳定、可验证的知识节点,并在知识发生改变时,自动维护其引用、依赖和可信状态?** - -如果能够证明这件事,就形成了一条从可读 Markdown 到可执行知识库的清晰技术路径。 - -因此,我最推荐你的方案是:**函数内所有语句可定位,带标记的内容可公开引用,经过契约验证的知识节点才可独立复用执行。** - -这比让所有语句无差别地成为公共锚点更严谨,也更符合 Marqdo“代码即文档,文档即知识库,知识即可执行”的设计理念。 - -现在的marqdo更新到了2.8.0,我觉得自动证明和上面的知识编译有关系,你怎么看,可以给我什么建议? - -我认为 **Marqdo 2.8.0 的自动证明,与我们此前讨论的知识锚点和知识编译,实际上是同一技术体系中缺失的两块拼图**。 - -而且在重新阅读 2.8.0 的实现之后,我认为可以提出比“把代码变成知识图,再给函数附加证明”更进一步的目标: - -> **将 **`.mq.md`** 编译为可寻址、可执行、可组合,并携带机器可核验证据的知识制品。** - -这与 Marqdo 原来的“代码即文档,文档即知识库,知识即可执行”并不矛盾,而是让“知识”拥有了可以接受形式化检查的语义。 - -不过,我不建议把它直接表述为“Marqdo 自动证明知识正确”。当前 2.8.0 证明的是限定语义模型下的程序性质,而不是自然语言知识的全部真实性。 - -## **一、2.8.0 已经完成了哪些关键基础** - -我检查了 [2.8.0 发布说明](https://github.com/cflmy/marqdo/blob/main/doc/releases/v2.8.0.md?utm_source=chatgpt.com)、`src/prove/`、`src/sema/ir.rs` 和相关测试。 - -| 能力 | 2.8.0 的实际情况 | 与知识编译的关系 | -| ---- | ---------------------------------------------- | ----------------- | -| 语义编译 | 已有 SemanticArtifact、KnowledgeRef、KnowledgeStep | 知识的身份与结构 | -| 自动证明 | `marqdo prove` 将定理表及函数降级为 Lean 4 | 知识的形式化约束 | -| 离线判定 | F1–F5 符号执行;`checked` 不等于 `proved` | 快速、低成本检查 | -| 证明证书 | 记录证明状态、源码与工具链哈希 | 知识的可核验证据 | -| 反例 | 部分假命题能得到路径或区间见证 | 知识修复依据 | -| 组合证明 | 同模块简单纯函数有限内联 | 已有基础,但尚未形成模块化证明体系 | - -当前最值得注意的是:**语义编译器与证明编译器还没有围绕知识锚点形成完整的统一体系。** - -知识编译能够生成步骤和依赖,证明编译能够生成定理和证书,但尚不能自然地表达: - -“这个知识步骤依赖哪些已经证明的知识?证明依赖的知识修改后,哪些证书需要失效?调用者能否直接复用被调用知识的证明,而不必重新展开整个函数?” - -我认为,这就是 Marqdo 2.9 最值得解决的问题。 - -## **二、从知识锚点到可证明知识图** - -我建议让知识编译和证明编译共享同一套稳定的语义身份。 - -**Marqdo **`.mq.md` - -叙述、类、函数、`[]()`、定理表 - -**统一知识语义 IR** - -稳定身份 · 知识锚点 · 数据依赖 · 效果 · 契约 - -**知识编译** - -知识图、引用解析、影响分析、执行绑定 - -**证明编译** - -Proof IR、Lean、反例、证书 - -**可验证知识制品** - -Artifact + Contract + Proof Certificate + Dependencies - -关键变化不是简单地增加几条图上的 `proved_by` 边,而是让编译器能够基于同一份语义结构,分别生成执行内容、知识引用和证明义务。 - -我建议采用这样的分工: - -- `#`、`##` 为知识提供作用域和可调用边界。 -- `[]()` 为内部知识步骤提供可读名称和可寻址身份。 -- 现有契约表定义输入、输出及其他约束。 -- 现有定理表表达需要成立的命题。 -- `prove` 为满足证明条件的命题生成证书。 -- 知识编译器关联上述信息,生成统一知识制品。 - -**不需要为知识证明额外发明一套 Markdown 标记。** - -## **三、最值得实现的功能:证明能够沿知识引用传播** - -假设有三个知识单元: - -**A · 查询适用税率** - -契约:根据地区和时间,返回适用税率 - -证明:在已声明的数据有效性条件下,返回值满足范围约束 - -**B · 计算税额** - -依赖 A,并根据金额和税率进行计算 - -证明:假设 A 的契约成立,B 满足自己的计算性质 - -**C · 订单结算** - -依赖 B,并生成最终金额 - -证明:在 B 的前提与其他结算条件成立时,满足结算约束 - -现在修改 A 的内部实现。 - -传统方式下,B、C 可能要重新进行大量测试,或者依赖开发者人工检查。 - -我希望 Marqdo 能够做到: - -1. 重新编译 A,确认其契约与实现发生了哪些变化。 -2. 如果 A 的实现改变,但原契约仍被新证明支持,B 可以在依赖和证明上下文未变时继续复用已有证明。 -3. 如果 A 的契约不再得到支持,则 B 的相关证明变成 `stale` 或 `unverified`,并进一步影响 C。 -4. 只对受影响的证明义务重新运行 Lean,而不是重新证明所有知识。 - -**这就让知识图成为证明依赖图,同时使证明能够参与增量知识编译。** - -它与 2.8.0 当前的证书缓存有明显区别。当前缓存主要根据源码、Proof IR、库和工具链版本等生成复合键;未来应该进一步细化为: - -- 某个知识锚点的实现指纹。 -- 该锚点的公开契约。 -- 证明依赖的其他知识及其契约指纹。 -- 使用的假设和证明规则。 -- Lean 内核接受的证明及其环境身份。 - -这样才能精确控制哪些结果可以复用。 - -## **四、证明不一定只属于函数,也可以属于知识步骤** - -这是我认为你原先“所有带标记的内容成为锚点”构想最有价值的延伸。 - -2.8.0 的定理表目前属于函数级声明,位于函数首条可执行语句之前。这很合理,也应该保留为默认的公开契约。 - -例如: - -``` -# 审批 - -## 审批订单 - -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | - -1. `金额` > 10000 - **回执 = [提交人工审核](人工审核(金额=`金额`))** -2. * - **回执 = [小额自动处理](自动处理(金额=`金额`))** - -*回执* -``` - -这个示例主要展示已有的定理表与遮蔽表达式如何结合,具体调用仍需要项目中的函数定义和类型契约。 - -现在证明的对象主要是 `## 审批订单` 的行为性质。 - -我认为将来可以增加一步: - -**把函数证明所涉及的知识步骤,映射到相应的锚点与依赖边。** - -例如,“大额必经人工”定理可以关联到“提交人工审核”知识锚点,同时记录证明是在什么输入条件和语义模型下成立的。 - -但是这里必须非常严格: - -- 证明整个函数满足某个性质,不意味着函数内部每个步骤都被单独证明正确。 -- `[提交人工审核]` 这个自然语言标签,不能自动当成形式化命题。 -- 证明轨迹包含“人工审核”,也不能证明外部审核服务真的完成了审核。 - -因此,**先做函数级证明向锚点的精确关联,再考虑锚点级局部证明**,会更稳妥。 - -## **五、建议的统一知识制品结构** - -我建议在现有 `SemanticArtifact`、`KnowledgeStep`、`KnowledgeRef` 之上增加证明关联层,而不是让 `src/prove` 生成第二套互不相认的知识身份。 - -下面是建议结构,并非 2.8.0 已有的完整 Schema。 - -``` - -{ - "anchor_id": "pricing.tax.calculate", - "symbol_id": "mq://project/pricing/function/calculate", - "kind": "derive", - "contract": { - "inputs": ["amount", "rate"], - "outputs": ["tax"] - }, - "dependencies": [ - "pricing.tax.lookup" - ], - "verification": { - "parse": "valid", - "resolve": "valid", - "proof": { - "status": "proved", - "claims": ["tax_formula"], - "certificate": "sha256:...", - "assumptions": [], - "scope": "function" - }, - "source": "unverified" - }, - "hashes": { - "interface": "...", - "implementation": "...", - "proof_dependencies": "..." - } -} - -``` - -一个很重要的设计是:`proof`** 不应该只是一个全局布尔值**。 - -不同知识锚点可能有不同性质:某个命题已经证明,另一个命题尚未证明,还有一个证明依赖不可靠的外部假设。 - -因此最小证明单元应当是: - -`(AnchorId, ClaimId, Assumptions, SemanticDigest, ProofCertificate)` - -而不是: - -`AnchorId → proved: true` - -这样调用者才能明确知道自己究竟复用了什么保证。 - -## **六、2.9 最应该优先实现的四项工作** - -| 优先级 | 工作 | 为什么重要 | -| --- | ----------------------------------------- | -------------- | -| P0 | 统一 `SymbolId`、`AnchorId`、定理身份 | 解决知识与证明的长期稳定绑定 | -| P1 | 将证明证书关联到 SemanticArtifact / KnowledgeStep | 建立知识与证明的直接关系 | -| P2 | 跨模块 assume-guarantee 证明组合 | 使证明可以跨知识引用传播 | -| P3 | 证明依赖图与增量失效分析 | 使大型知识库不必每次全量重证 | - -我尤其强调 P2。 - -因为从 2.8.0 发布说明可以看到,**跨模块调用目前仍视为不透明操作,而 assume-guarantee 后置条件复用明确延期到 2.9**。 - -这恰好是知识编译与自动证明结合的突破点。 - -假设 Marqdo 有两个函数: - -- `A` 已经证明后置条件 \\(Q_A\\)。 -- `B` 调用 `A`,希望证明自己的后置条件 \\(Q_B\\)。 - -那么 B 不必知道 A 的完整实现,只需要建立调用点的输入满足 A 前置条件,并利用 A 已经证明的后置条件完成自己的证明。 - -这正是契约组合推理的基本思路。 - -但证明必须明确依赖:A 的证书、其适用条件、A 与 B 的语义模型是否一致,以及任何外部假设。不能把未经验证的函数描述当作公理。 - -### **还需要优先修复两个证明语义边界** - -2.8.0 有两项已记录的差异,我建议不要在强化知识证明时忽略: - -- **i64 溢出**:解释器按有界整数处理并可能报错,而当前 Lean 模型使用无界 `Int`。 -- **除零/模零**:解释器产生运行时错误,Lean 底座目前存在返回 `.int 0` 的建模差异。 - -这意味着证明证书必须记录实际覆盖的数值范围和语义前提。未修复或没有证明等价的部分,不能被上层知识引用当成无条件可信的计算保证。 - -## **七、与智能体结合后,会产生什么变化?** - -这部分可能最符合你未来做科研智能体的方向。 - -过去智能体调用知识库时,主要依据名字、描述、检索相似度来选择已有能力。 - -未来可以让它先查询知识图,获得知识制品的: - -- 可执行入口与输入契约。 -- 形式化证明过的性质。 -- 来源与版本。 -- 未证明的假设和适用边界。 -- 是否受到近期源码或依赖修改的影响。 - -于是智能体不再只是“找到一个看起来相关的 SKILL”,而是可以选择一个**在当前任务条件下,拥有足够验证依据的知识能力**。 - -例如,量子科研智能体在寻找电路优化方法时,可以优先寻找具有等价性证明的电路变换,而不是每次重新生成并尝试未经验证的优化。 - -当然,这需要专门定义量子电路语义、等价关系和可信的验证过程;现有 2.8.0 的控制流证明还不能直接证明任意量子电路等价。 - -## **八、研究上怎样证明这条路线有价值?** - -我建议至少设计三个实验,不要只展示“Lean 可以证明 Marqdo”。 - -**实验 E1:知识修改与证明增量失效** - -在拥有大量相互引用的知识函数的项目中,修改其中某个函数,对比全量重新证明和基于锚点依赖的增量重新证明。 - -指标:重新证明的命题数、证明耗时、失效检测准确率,以及错误复用证书的次数(目标为零)。 - -**实验 E2:跨函数与跨文档证明复用** - -与 2.8.0 通过内联或不透明调用处理函数的方案相比,验证契约组合是否显著提升可证覆盖率。 - -指标:proved 比例、unverified/rejected 比例、证明时间、需要人工声明的假设数量。 - -**实验 E3:证明感知的智能体知识复用** - -让相同模型完成知识检索、函数复用与程序修改任务,对比普通语义检索、只使用知识图、知识图加证明证书三种方案。 - -指标:错误知识复用率、任务成功率、人工审核量、输入 Token 和总执行成本。 - -这三个实验分别验证“知识编译”、“证明组合”和“智能体使用价值”,能够避免把三个研究主张混成一个难以检验的宏大叙事。 - -## **我的总体判断** - -如果按照技术潜力排序,我会这样看: - -| 方向 | 评价 | -| ----------------- | ---------------- | -| 给所有语句生成锚点 | 必要的基础设施,但单独创新性有限 | -| 让 `[]()` 成为稳定知识引用 | 很有价值,能形成统一知识身份 | -| 让知识锚点携带可验证契约和证书 | 更有研究深度 | -| 让证明沿知识依赖传播并支持增量复用 | 我认为是最值得集中攻关的核心 | - -而且现在你拥有了一个很好的技术条件:**2.8.0 已经实现了真正的 Lean 证明路径,不再只是设计中的设想。** - -我建议将 Marqdo 2.9 的主线收敛成: - -**Proof-Carrying Executable Knowledge(携带证明的可执行知识)** - -但需要注意,Proof-Carrying Code、契约式程序验证和模块化证明本身都是已有研究。Marqdo 真正需要体现的区别,是它如何把 Markdown 原生描述、稳定知识锚点、可执行语义、证明义务与增量知识依赖统一编译为同一个制品体系,而非仅仅给代码加上证明。 - -一句话总结我的建议: - -**2.8.0 实现了“文档中的程序可以被证明”;2.9 应当实现“证明可以成为知识的一部分,并随着知识被引用、组合、验证和复用”。** - -我认为,这比单纯继续扩展 `marqdo prove` 可支持的表达式范围,更符合 Marqdo 的长期方向。 \ No newline at end of file diff --git a/doc/next/Marqdo_Executable_Knowledge_Design.md b/doc/next/Marqdo_Executable_Knowledge_Design.md deleted file mode 100755 index 43a3b2c..0000000 --- a/doc/next/Marqdo_Executable_Knowledge_Design.md +++ /dev/null @@ -1,295 +0,0 @@ -# Marqdo 可执行知识体系:统一语义制品与知识引用设计规范 - -> 状态:设计提案(非当前版本的已实现功能) -> 基线:仓库 main,2026-10-23;README 标记 v2.0.0;跨文档类调用与 LinkInfo 为 v2.1 目标 -> 宗旨:**代码即文档,文档即知识库,知识即可执行。** -> 核心判据:当 AI 遇到任务时,能否先发现已有知识,并以确定性绑定复用,而不是再生成一份“看起来相同”的知识或实现? - -## 1. 决策摘要 - -保持 `[描述](表达式或知识目标)` 的 Markdown 形态,不引入新的前缀或第二套表达式文法。`[]` 是面向读者的陈述,`()` 内的内容进入统一表达式解析器。语言内部建立稳定的 **Semantic Artifact(语义制品)** 和 **Verified Knowledge Reference(可验证知识引用)** 两种核心抽象。前者承载身份、语义、实现、依赖、契约与来源;后者是一个经编译期解析、受上下文约束的引用。它们不必对应新语法标记,而是 `.mq.md` 经语义分析得到的统一中间表示。 - -**三项不变式:** - -1. **表达式透明性**:在求值上下文中 `[L](E)` 与 `E` 取得同一类型和值;`L` 不进入符号绑定或改变结果。引用额外产生诊断与溯源元数据。 -2. **文本安全性**:叙述中的知识链接在 `check/view` 中解析;`run` 不因正文出现链接而隐式执行有副作用的函数。导航链接(HTTP、相对文档路径)仍属于普通 Markdown 链接。 -3. **知识可信边界**:`resolved`、`compiled`、`tested`、`source_verified`、`domain_validated` 是不同状态。能执行不等于事实真;有来源不等于来源仍然适用。没有证据时允许展示,但不得向 agent 宣称为已验证知识。 - -### 1.1 不是要做的事 - -- 不将 Markdown 转成一个独立于解释器的新运行语言。 -- 不把所有知识都强制构建为类,也不等同“知识 = 函数”。 -- 不把自然语言标签作为权限或事实正确性的证明。 -- 不把符号名的字符串匹配当成稳定知识复用。 -- 不要求所有调用都锁版本:本地临时表达式可无锁,跨文档公共知识/关键业务则可选或强制锁定。 - -## 2. 以真实仓库为准的兼容边界 - -| 语法或能力 | 当前已支持 | 目标设计/注意事项 | -|---|---|---| -| `.mq.md` 和 Markdown 叙述 | 是 | 原有叙述默认安全 | -| `#` 对象/类型,`##` 函数/方法 | 是 | 目标:不依赖 `self` 的函数可通过类命名空间直接调用 | -| `**表达式**`、`*返回*` | 是 | 复用现有表达式解析器,不另造链接表达式 | -| `+ \`参数\``/叙述推断参数 | 是 | 签名必须能静态抽取并生成规范化形式 | -| `1.` 条件分支、`-` 循环 | 是 | 新版链接循环形式须通过模式迁移;旧式依赖 Classic | -| Markdown 表格→List/Map/列向表/行向记录 | 是 | 数据语义与契约表应从上下文区别 | -| Frontmatter `import` | 是 | 可作为当前跨文档路径的兼容实现 | -| `[描述](本地表达式)` | v2.0.0 已有,主要需 `markup: occlusion` | 统一后免模式开关;旧 `[键](集合)` 必须避免静默变义 | -| `类.函数` 无实例直接调用 | 未按目标实现 | **新能力**:区分类函数/实例方法、隐式零参调用 | -| 跨文档项目符号索引 | 尚缺 | **新能力**:可控作用域、同名消歧、增量索引 | -| LinkInfo/知识引用图/links.lock | 目标设计 | **新能力**;与已有 EKC 统一,拒绝第二套知识图 | -| 双执行后端(树遍历、字节码) | 是 | 引用语义必须在两个后端一致 | - -项目示例分为:**V2-目标示例**(体现最终范式)与**V2.0-兼容示例**(现有调用方式)。所有目标示例是规范性设计,不宣称已在 v2.0.0 执行验证。 - -## 3. 知识不是代码字符串:规范化语义模型 - -### 3.1 Semantic Artifact - -每个可引用实体编译为 `Artifact`,而非仅落入 AST 一个节点。 - -```text -Artifact { - symbol_id: StableSymbolId, // 跨增量构建稳定的身份(命名空间 + 显式/规范化路径) - kind: Type | Entity | Fact | Function | Capability | Constraint | Policy | Dataset, - visibility: Local | Module | Project | Exported, - source_span: SourceSpan, - signature: CanonicalSignature?, // 参数、返回值、默认值、单位与结构类型 - ir: CompiledIR?, // 运行逻辑或规范化常量;普通叙述可无 - effects: EffectSet, // pure / fs.read / fs.write / network / llm / time / random ... - dependencies: [SymbolId], - contract: [Predicate | Schema | Condition], - provenance: [SourceRef], - hashes: { interface, implementation, dependency_closure, evidence }, - verification: VerificationRecord -} -``` - -区分以下四个概念: - -- **Identity(身份)**:目标属于哪一知识单元;名称调整可使用迁移映射,不允许悄悄重绑定到不同实体。 -- **Content(内容)**:符号当前定义和可执行 IR;代码变更指纹改变。 -- **Applicability(适用性)**:参数、业务前提、单位、时间/地区/场景等约束;匹配才可复用。 -- **Evidence(证据)**:来源、测试与验证结果。证据改变不等同于程序改变,但需要重新评估可信状态。 - -### 3.2 Knowledge Reference - -```text -KnowledgeRef { - label: String, - payload_ast: Expr, - context: Narrative | Code | Return | Argument | Table | Heading, - resolution: ResolvedSymbol | LocalExpression | NavigationURL | Unresolved, - target_symbol_id: SymbolId?, - target_digest: Digest?, - expected_signature: Signature?, - required_verification: VerificationPolicy, - source_span: SourceSpan -} -``` - -`[描述](E)` 在运行语义上是透明的,但其静态解析必须构建 KnowledgeRef。在调用点将地址绑定到 `SymbolId`,不能每次由 AI 重新解释描述。 - -### 3.3 类型 / 知识实体 / 计算能力分别建模 - -- `# 诗人` 是 Type;`# 李白 = > 诗人` 在现有语法中仍是**继承/特化**。作为 v2.1 过渡方案可视为“单体知识类”,但不得默认为真正的 `instance_of`。 -- 事实可以由 `## 出生年份` + 返回值 + 来源表承载;编译器推导为 Fact Artifact。是否是事实要根据可检查的声明/契约,不应仅凭函数名字猜测。 -- 业务函数如 `## 计算应付` 是 Function/Capability;不应因为带中文说明就被误识别成事实。 -- 未来需要大规模实体库时,Entity/Fact 应支持表驱动注册,不为每个实体强制生成 Rust 或 Marqdo 类。 - -## 4. `[]()` 的确定语义 - -### 4.1 一个表面形式、三种解析结果 - -| 表面形式 | 静态解释 | `run` | `check` / `view` | -|---|---|---|---| -| `**总额=[应付](数量*单价)**` | 本地表达式遮蔽 | 求值 | 保存标签、表达式和诊断 | -| `**总额=[计算总额](Pricing.计算总额(订单))**` | 知识能力调用 | 绑定后调用 | 检查签名、效应、依赖和版本 | -| `文中参见[税率](Policy.税率)` | 叙述知识引用 | 不执行 | 解析、展示受信任/未验证状态,纯目标可选择显式求值 | -| `[项目文档](./guide.md)` | 导航链接 | 不执行 | 保持 Markdown 导航 | - -语法上的“同权”是 `()` 与 `**...**` 共用表达式文法;**不是正文和代码拥有相同的执行许可**。 `view` 对具外部效应的目标默认只展示元数据,必须明确授权才允许运行。 - -### 4.2 最小语义规则 - -```text -parse_bracket(label, payload, context) -> KnowledgeRef - -context ∈ executable_context: - verify_resolved_target(); evaluate(payload_ast) -context ∈ narrative_context: - resolve_only(); never_schedule_effects() -payload ∈ ordinary_navigation: - preserve_as_markdown_link() -``` - -### 4.3 唯一性与优先级 - -1. 当前词法作用域的变量/接收者; -2. 当前文档的声明; -3. 显式 `import` 命名空间; -4. 项目导出索引(受 `--fs-root` 和导出策略约束); -5. 内置/已安装扩展。 - -如果两个候选都满足同一级优先规则,报 `link.ambiguous`;不能随文件顺序自动挑一个。解析失败必须有诊断,不能把知识目标悄悄解释成字面字符串或导航路径。 - -### 4.4 类函数 vs 实例方法 - -- 目标函数使用 `self/自` → 实例方法,必须有显式接收者。 -- 函数不使用接收者 → 可由 `类.函数` 调用;不运行类的构造体。 -- 路径解析到零参函数时可以省略 `()`,但**函数作为一等值的语义必须避免与隐式调用冲突**。建议只有被 `[]()` 用作知识目标、或显式值需求时才触发零参隐式调用;直接 `类.函数` 在函数值场景需明确消歧。最终以一致的形式化语义测试冻结。 - -### 4.5 版本策略与效应 - -`interface_digest` 代表签名兼容性,`implementation_digest` 代表实现变化,`dependency_closure_digest` 代表传递依赖;`evidence_digest` 代表证据状态。既存调用在接口未变时不必全部报错,但“严格复现”任务应使用 lock 来禁止目标悄然变化。 - -纯知识事实允许受控求值与缓存;依赖网络、时间、随机数、外部模型的调用即使锁了源码也不天然确定。必须记录输入快照、环境与效应,并明确“不保证结果复现”的状态。 - -## 5. 静态分析、来源与可信性 - -### 5.1 五层验证(必须分层报告) - -1. **Parse**:Markdown 结构/语法可解析。 -2. **Resolve**:目标存在,歧义可消除。 -3. **Type/Contract**:签名、入参与结构类型、单位、前置条件匹配。 -4. **Execution/Test**:纯函数或受控沙箱完成运行与测试。 -5. **Evidence/Domain**:事实来源可访问,内容匹配,满足适用范围;复杂自然语言事实可能需要人工或 LLM 辅助复核,复核结果必须标识非确定性。 - -严禁将 `check OK` 展示成“现实知识已被证明正确”。 - -### 5.2 诊断码草案 - -| Code | 默认级别 | 含义 | -|---|---|---| -| `link.unresolved` | error | 找不到可绑定的目标 | -| `link.ambiguous` | error | 目标符号不唯一 | -| `link.kind_mismatch` | error | 把类型/实例/函数错当为可执行知识 | -| `link.instance_only` | error | 类调用命中实例方法 | -| `link.arg_mismatch` | error | 参数与签名不符 | -| `link.effect_forbidden` | error | 当前位置不允许此类副作用 | -| `link.target_changed` | warning/error | 被锁定或要求稳定的目标发生变更 | -| `knowledge.source_missing` | warning/error | 来源缺失 | -| `knowledge.source_changed` | warning | 来源指纹变化尚未复核 | -| `knowledge.constraint_unmet` | error | 当前输入不满足适用条件 | -| `knowledge.unverified` | info/warning | 可用但未得到所需级别的验证 | -| `label.ref_dangling` | error | 标签中反引号引用无法解析(保留已有规则) | -| `label.possibly_stale` | hint | 代码变更但描述未更新,需要人工检查 | - -标签里提到的自然语言不能被静态类型系统完全证明。所有自动语义比对必须报告置信限制。 - -## 6. 编译器实施架构 - -```text -Markdown Source - │ - ├─ CommonMark/GFM-aware parse + Marqdo lexical context - ▼ -Syntax AST (prose + code + table + heading + bracket) - ▼ -Symbol Index (module, class, function, fact, export) - ▼ -Resolution & Type / Contract / Effect Analysis - ▼ -Semantic Artifact IR + KnowledgeRef IR - ├──────────────┬──────────────────┬───────────────────────┐ - ▼ ▼ ▼ ▼ -Tree Interpreter Bytecode VM View / Debug EKC/Catalog/MLSP - │ │ - └──────────┬────────────┘ - ▼ - Agent deterministic reuse -``` - -**实现优先原则**:统一在语义分析层生成符号与引用元信息。不要在 view、EKC、Agent 中分别重新解析 `.mq.md` 来猜同一段代码代表什么。 - -### 6.1 Markdown 链接兼容性 - -`[描述](含空格或括号的表达式)` 不是任意标准 Markdown 渲染器都可识别的合法 URL 目标。Marqdo 必须定义其**源码级别的上下文语义和渲染行为**:先保留有意义的源码跨度,再由专属 view 转为原生可读的标签及悬浮信息;不能假设 GitHub Markdown 会在所有表达式上正确渲染。代码围栏、行内代码、转义以及普通 URL 链接不能被误识别成可执行引用。 - -### 6.2 旧语法迁移 - -Classic 的 `[键](集合)` 曾用于取元,`- [项](集合)` 曾用于循环。默认统一为遮蔽含义前,需要 AST 辅助迁移: - -```text -[key](table) → [可读描述](at(table, key)) -- [item](list) → - [逐项遍历](遍历 list 为 item) -``` - -避免靠简单正则批量替换;不能把旧代码成功运行但产生不同值视为兼容。迁移应生成审计报告、变更 diff 与双后端对照测试。 - -## 7. EKC 与 Agent 复用协议 - -当前 EKC 已有 Symbol、Capability、Knowledge、Context Pack、REUSE→ADAPT→CREATE。将这些能力变为统一 Semantic Artifact 的**投影/索引**,不要再建第二套符号管理器。 - -Agent 必须按以下状态机处理: - -```text -TASK → DISCOVER → RESOLVE → CONTRACT_CHECK - │ │ - │ ├─ verified + applicable → REUSE → EXECUTE → TRACE - │ ├─ adaptable → ADAPT → VERIFY → PROMOTE - │ └─ absent/unusable → CREATE → VERIFY → PROMOTE - └─ ambiguous → REQUEST_DISAMBIGUATION / FAIL_CLOSED -``` - -- **Discovery 是召回**,可以模糊检索,不等于可信复用。 -- **Resolve 必须精确**,让自然语言意图最终绑定到具体 `SymbolId`。 -- **Reuse 是编译器行为**:Agent 持有可验证引用,并使用明确的输入与契约,不复制代码段。 -- **Promote 是门槛**:新生成内容必须通过所需静态检查、测试与来源规则才可进入已验证知识索引。 -- **Trace 可审计**:保存“这次回答具体用了哪些符号、哪些版本和哪些输入”,不是仅存 LLM 的解释文本。 - -建议新增的 MLSP 读接口:`artifact.find`、`artifact.inspect`、`link.resolve`、`artifact.verify`、`artifact.impact`、`artifact.bind`;后者在编译器确定性解析后返回可调用句柄/引用描述,不应凭自然语言标签直接执行。 - -## 8. 里程碑与硬验收 - -### M0 语义冻结 - -明确新语义与 Classic 的区别,形成机器可读 gold cases,涵盖 URL、嵌套括号、空标签、取元、循环、代码围栏、换行、标题、叙述链接与作用域。所有未经标注的旧语义变化不得静默放行。 - -### M1 符号身份与项目索引 - -构建导出符号表、稳定 `SymbolId`、同名诊断。验收:同仓两个 `李白` 定义应报歧义;限定名可解析;改变目录扫描顺序不影响绑定结果。 - -### M2 统一 Bracket IR 与类函数调用 - -语法识别→表达式解析→目标绑定→双后端执行。验收:含 `self` 与不含 `self` 的函数正确分派,构造不产生意外副作用;正文不自动执行。 - -### M3 Semantic Artifact / 验证 - -签名、effect、contract、provenance、验证记录与指纹。验收:接口修改、依赖修改、证据变化、适用条件不匹配得到不同诊断。 - -### M4 EKC、view、agent 集成 - -整个工具链共享 SymbolId/LinkInfo,生成 links graph、可查看调用与来源、可追踪复用。验收:图边与实际编译的调用目标完全一致;Agent 命中已有能力时不得偷偷生成新实现。 - -### M5 基准实验(对照 Python/Notebook/普通 Markdown+检索) - -同一模型、同一任务集、相当的工具与提示预算;分别统计可执行成功率、知识错误引用率、重复实现比例、文件改动数、调用/修复次数、总 tokens、端到端时延、可复核程度。公开任务、生成器、冻结环境、置信区间和失败样本;不要使用只在 Marqdo 方案可解的夹具,也不要把编译器固有优势等同整个 Agent 的领先。 - -## 9. 设计原则冻结 - -1. **源码可读,编译结果确定**。 -2. **知识是制品,不是文本片段**。 -3. **检索可以模糊,绑定必须确定**。 -4. **知识能够执行,但执行不等于真实**。 -5. **知识可以复用,但必须满足契约与适用条件**。 -6. **显示文字可自由,语义判断不依赖显示文字**。 -7. **默认保持叙述安全,副作用需要明确执行上下文**。 -8. **保持一种语法,一个语义解析器,一套符号索引**。 -9. **双后端与 view/EKC 使用同一份语义中间表示**。 -10. **失败必须可观察,不能因为链接看起来优雅而隐去错误**。 - -## 10. 来源依据 - -仓库:<https://github.com/cflmy/marqdo>。重点阅读: - -- `README.md`(v2.0.0 现状与 v2.1 目标) -- `doc/design/markdown-mapping-v0.3.md`(基本语法) -- `doc/design/objects.md`(类、实例、自/self、继承) -- `doc/design/link-syntax.md`(现有链接设计声明) -- `doc/design/occlusion-syntax.md`(遮蔽与描述新鲜度) -- `doc/design/knowledge-layers.md`(知识分层、过渡型单体类) -- `doc/design/engineering-knowledge.md`(EKC 与复用流程) -- `.cursor/skills/marqdo/reference.md` 与 `examples.md`(参考语法;其部分 Classic 旧写法必须经过迁移) - -附录项目:`Marqdo_Executable_Knowledge_Example.md`。其中对未实现特性逐项标注,所有业务数据均为虚构演示数据。 diff --git a/doc/next/Marqdo_Executable_Knowledge_Development.md b/doc/next/Marqdo_Executable_Knowledge_Development.md deleted file mode 100755 index 0ae1584..0000000 --- a/doc/next/Marqdo_Executable_Knowledge_Development.md +++ /dev/null @@ -1,1479 +0,0 @@ -# Marqdo 可执行知识系统详细开发规范 - -| | | -|---|---| -| 状态 | **目标实施规范;按文档原生指导修订交付与政策分级** | -| 日期 | 2026-10-23 | -| 适用版本 | v2.1 及后续兼容演进 | -| 真实意图来源 | [`009.md`](009.md)、[`Marqdo_Executable_Knowledge_Design.md`](Marqdo_Executable_Knowledge_Design.md)、[`Marqdo_Executable_Knowledge_Example.md`](Marqdo_Executable_Knowledge_Example.md) | -| 核心目标 | **代码即文档,文档即知识库,知识库可执行,可执行知识可确定性复用。** | - -## 0. 文档地位与执行规则 - -本文把上述三份文档中的真实产品意图整理为可编码、可测试、可迁移、可验收的开发规范。2026-10-23 的[文档原生开发指导](../design/document-native-development-guide.md)进一步约束作者负担、AI 编辑与复用、场景分级和交付顺序;本文的内部结构不能反向要求作者重复填写注册表、工具 schema 或知识图。仓库中更早的链接、遮蔽、知识分层、类模型、OKF 或 EKC 文档若与上述方向冲突,不得据其改变本轮设计。 - -优先级从高到低如下: - -1. `009.md` 中确认的产品目标与边界; -2. [文档原生开发指导](../design/document-native-development-guide.md)对作者体验、政策分级和交付排序的修订; -3. 本文的工程决策、数据结构和验收条件; -4. 两份附属文档中的概念设计与完整示例; -5. 其他旧文档,仅可作为历史背景,不是规范依据。 - -本文不宣称目标能力已经实现。未另行标日期的“当前”表格与 §2 缺口保留最初 v2.0.0 审计背景,不能继续当作 v2.1 的实时状态:默认 Occlusion、线程局部解析作用域、关联函数与零参路径等已经演进。当前实现判断见[2026-10-23 缺口审计](../roadmap/executable-knowledge-gaps-2026-10-23.md)及对应源码/测试;代码事实证明实现范围,不自动取代产品目标。任何阶段只有在对应的自动化测试、双后端一致性测试和迁移测试全部通过后,才可改标为“已实现”。CLI/API 示意与结构定义仍是目标协议,使用前须核对实现。 - ---- - -## 1. 产品目标与成功判据 - -### 1.1 目标链条 - -Marqdo 不是“能运行 Markdown 中几段代码”的解释器,也不是“给 RAG 提供更多 Markdown”的资料库。它要建立以下连续链条: - -```text -代码即文档 - └─ 程序、说明、契约和示例共址 - ↓ 编译 -文档即知识库 - └─ 内容拥有稳定身份、类型、关系、来源和适用条件 - ↓ 确定性绑定 -知识库可执行 - └─ 知识不是重新解释的文本,而是可调用的编译制品 - ↓ 发现、校验、执行、追踪 -可执行知识可复用 - └─ 人和 Agent 优先复用既有能力,不重复生成同义实现 -``` - -### 1.2 产品级成功判据 - -最终系统必须同时满足以下条件: - -- 人只维护 `.mq.md`、原始资料和显式配置,不手工同步另一份知识图; -- 同一份源码能够生成运行程序、语义制品、引用图、可读 view 和 Agent 接口; -- `[描述](载荷)` 在可执行位置与裸载荷取得同一值,在叙述位置默认不产生副作用; -- 跨文档引用最终绑定到稳定 `SymbolId`,不能只保留名字字符串; -- 模糊搜索只负责发现候选,真正执行前必须精确解析、校验契约和适用性; -- 代码、依赖、来源或验证状态变化时,影响范围能够被程序找出; -- Tree Interpreter 与 Bytecode VM 对同一已绑定程序产生一致结果和诊断; -- Agent 命中已有且适用的制品时,得到的是可调用句柄,不是让模型复制源码再写一遍; -- 系统从不把 `compiled`、`tested` 或 `source_present` 误报成“现实世界事实已证明正确”; -- 作者能从正文计算开始,按需要提取命名能力与跨文档复用,不先建立知识治理工程; -- 人和 AI 能按标题/步骤获得最小上下文、局部修改并查看语义影响,不必整篇重生成; -- 每个交付切片同时证明阅读、修改或复用的实际收益,而不只证明内部字段存在。 - -### 1.3 不在本轮目标内 - -- 不设计第二套链接专用表达式语言; -- 不增加 `knowledge:`、`call:`、`ref:` 等作者必须记忆的前缀; -- 不把全部知识强制建模为类或函数; -- 不在第一阶段实现通用 OWL/RDF 本体推理; -- 不承诺网络、时间、随机数、LLM 或外部进程可由源码哈希完全重放; -- 不用 LLM 替代确定性的解析、绑定、类型检查和权限检查; -- 不把自然语言标签当作授权、契约或事实正确性的依据; -- 不让 EKC、view、check、Agent 各自再次解析源码并形成不同理解。 - -### 1.4 作者成本与渐进严格 - -标题、叙述、表格、链接描述和执行语句是作者的主要工作面;符号 ID、步骤 ID、规范签名、效应闭包、工具 schema、图和摘要由工具生成。不能推导的领域条件、来源和许可由作者明确补充,不要求每个纯工具函数都填写事实证据。 - -本地探索允许无锁运行草稿,但不绕过宿主能力限制;项目自动复用按所选 policy 校验;严格业务再增加必要证据、版本锁和新鲜度;远程/多租户另有可信授权与隔离门槛。这是同一语法上的政策分级,不是新的语法模式。纯预览可复用已授予的项目/会话政策,不做逐链接重复确认。详情见[指导 §6](../design/document-native-development-guide.md#6-渐进严格不把治理门槛塞进每一行正文)。 - -自然语言标签是发现、解释和局部编辑的重要信息,但不证明 payload 正确。AI 可以选候选、组合、适配、重构及补测试;编译器确定实际绑定、类型和效应,宿主决定能力上限。不得把“不用模型决定语义”误读成“模型只能搜索”。 - ---- - -## 2. 初始实现基线与缺口背景(非 v2.1 实时清单) - -### 2.1 可以复用的现有基础 - -| 位置 | 当前能力 | 本轮处理 | -|---|---|---| -| `src/ast.rs` | `Module`、`Function`、`Stmt`、`Expr::Occluded`、`Span` | 保留 Syntax AST;补正文结构、节点身份和语义映射,不直接塞入全部分析结果 | -| `src/parse/expr.rs` | Classic/Occlusion 两种 `[]()` 解释;payload 复用表达式解析 | 迁移后冻结为统一链接语义,移除运行时全局模式依赖 | -| `src/load.rs` | 递归 import、模块绑定、循环导入检测 | 拆分“源码装载”和“项目编译”;显式 import 仍是可执行代码的规范依赖 | -| `src/contract.rs`、`src/check.rs` | 渐进式契约、类型名、漂移和错位检查 | 接入统一 Sema;扩展为引用、effect、provenance、lock 诊断 | -| `src/interp.rs` | Tree 执行、实例方法、运行时契约 | 改为执行已解析引用;不在运行时重复猜目标 | -| `src/bytecode/` | Bytecode 编译与 VM、函数/实例方法调用 | 消费相同的 Bound IR,新增静态目标调用,不自行解析名字 | -| `src/knowledge/` | EKC、L0–L4、检索、reuse、impact、preflight | 保留用户接口;内部改成 Semantic Artifact/Graph 的投影与查询层 | -| `src/mlsp.rs` | `locate`、`validate`、`schema` 等 JSONL 接口 | 增加 artifact/link/verify/impact/bind 只读接口 | -| `src/view/` | AST 文档、执行捕获、注解 | 显示同一份 LinkInfo、验证状态、来源与依赖,不自行推断目标 | -| `src/artifact/` | Web/Endpoint/Prompt 元数据分类 | 避免命名冲突;迁为 `artifact::web` 或更名,不能冒充统一语义制品 | - -### 2.2 必须修复的结构性缺口 - -1. `Expr::Occluded` 只有标签与 payload,没有上下文、解析目标、制品身份和引用策略。 -2. 正文目前不会完整进入能做知识引用分析的结构化 AST。 -3. Classic/Occlusion 用进程全局状态和 frontmatter 切换,同一形状可能静默表示索引或遮蔽。 -4. `CallExpr.path` 在 Tree 和 Bytecode 中分别解释,绑定不是独立编译阶段。 -5. 当前路径调用把对象下函数统一拒绝为实例方法,未根据 `self/自` 使用情况区分类函数和实例方法。 -6. EKC 的符号、调用和图边主要由名字/文本提取形成,不能保证与实际执行目标一致。 -7. 当前 fingerprint 更偏向相似性检索,不是接口、实现、传递依赖和证据的规范内容摘要。 -8. `check` 主要做契约检查,没有项目级 Resolve、LinkInfo、effect、来源和 lock 校验。 -9. Agent 的 REUSE/ADAPT/CREATE 可以发现相似条目,但没有“已绑定且可调用”的强制交接点。 - -### 2.3 两个必须避免的概念冲突 - -**Artifact 命名冲突**:当前 `src/artifact/mod.rs` 的 `ArtifactKind` 只是 Web/Endpoint/Prompt 分类。统一语义制品应命名为 `SemanticArtifact`,放入新的 `src/sema/`;现有模块迁到 `src/artifact/web.rs` 或改名为 `document_artifact`。 - -**Knowledge IR 重复真相源**:当前 `src/knowledge/ir.rs` 是 EKC 输出模型。它不得升级成第二套编译 AST。编译器先生成 `SemanticProject`,EKC 再无损投影成兼容的 catalog/graph/context pack。 - ---- - -## 3. 冻结的语言语义 - -### 3.1 `[]()` 的唯一表面形式 - -```text -[人类可读描述](机器可解析载荷) -``` - -`[]` 中的 label 是人话接口;`()` 中的 payload 使用所在上下文已有的 Marqdo 语法。二者共同形成一个命名步骤,但只有 payload 决定值、类型、依赖和副作用。 - -在可执行表达式上下文中: - -```text -value([L](E)) = value(E) -type([L](E)) = type(E) -effect([L](E)) = effect(E) -``` - -label 不参与变量绑定,不改变控制流,不赋予权限,也不证明 payload 正确。编译器额外生成 `KnowledgeRef`/`KnowledgeStep`,因此透明不等于丢弃元数据。 - -### 3.2 上下文决定“是否执行”,目标种类决定“如何校验” - -| 上下文 | 编译行为 | 运行行为 | -|---|---|---| -| `**...**`、`*...*`、调用实参、表格表达式 | 解析、绑定、校验并生成 BoundExpr | 正常求值 | -| 循环载荷 | 解析成既有 LoopSpec,生成命名步骤 | 按原循环语义执行 | -| 普通正文 | 解析导航或知识引用,生成 NarrativeRef | `run` 不执行;`view` 仅可按策略预览 pure 目标 | -| 标题、frontmatter、代码围栏、行内代码 | 不识别为可执行链接 | 保持原文本/原结构 | -| HTTP(S)、锚点、相对 `.md` 路径 | NavigationRef | 不执行 | - -禁止通过“目标是函数”推导它在正文中可以执行。执行许可由上下文和 effect policy 共同决定。 - -### 3.3 一个语法,四种语义投影 - -| 示例 | `StepKind` | 核心依赖 | -|---|---|---| -| `[订单行金额](at(行, "金额"))` | `Observe` | 变量、字段 | -| `[折后价](小计 * 折扣)` | `Derive` | 输入表达式 | -| `[计算应付](定价.计算应付金额(...))` | `Invoke` | 目标 SymbolId、实参 | -| `[逐行处理](遍历 订单.行 为 行)` | `Iterate` | 集合、迭代变量 | -| 正文 `[免邮门槛](书店政策.免运费门槛)` | `Narrate` | 知识目标 | - -`StepKind` 由已解析的 payload 和位置推导,不由 label 中的自然语言猜测。 - -### 3.4 类函数与实例方法 - -现有 `#`/`##` 表面语法保持不变,语义分析阶段明确区分: - -- `##` 函数体直接使用 `self/自`,或调用同一类型中依赖接收者的方法:`InstanceMethod`,必须有实例接收者; -- 不使用接收者:`AssociatedFunction`,可由 `类.函数(...)` 调用,且不执行 `# 类` 的构造体; -- `#` 仍可承载类型/命名空间的兼容写法,但这不表示所有知识都是类; -- `Entity`、`Fact`、`Policy`、`Constraint`、`Dataset` 等是 Semantic Artifact kind,不强制增加源码关键字; -- 顶层自由函数和导入模块函数继续存在,不必包装成类。 - -接收者依赖必须在语义分析中递归确定。直接读取 `self/自` 是确定证据;调用同类型实例方法会传播接收者依赖;仅在叙述里出现“自”不算依赖。 - -### 3.5 零参路径 - -零参函数省略 `()` 只允许在以下明确的“需要值”位置: - -- `[]()` payload 的最终路径; -- 赋值、返回、参数、条件或表格单元格中的值表达式; -- 正文知识引用的目标路径。 - -当语法位置允许函数值时,裸路径不做隐式调用;若语言当前没有一等函数值,则在引入一等函数前将此行为冻结为“路径解析到零参函数即调用”。带参数函数省略 `()` 必须报 `link.arg_mismatch`,不能返回函数对象或 `None`。 - -### 3.6 导航链接与知识引用消歧 - -识别顺序如下: - -1. 明确 URI scheme(如 `https:`、`mailto:`)或 `#anchor` → Navigation; -2. 以 `./`、`../`、`/` 开头且指向文档/资源的路径 → Navigation; -3. 其余 payload 尝试使用 Marqdo 语法解析; -4. 解析成功 → Knowledge/Expression Reference; -5. 解析失败且符合普通 Markdown 目标 → Navigation; -6. 两种解释都成立 → 报 `link.ambiguous_syntax`,要求作者改为明确相对路径或合法表达式。 - -不能因为解析失败就无声地把预期知识引用降级成普通 URL。 - ---- - -## 4. 编译管线与模块边界 - -### 4.1 目标管线 - -```text -Source files - ↓ SourceMap + Markdown-aware scan -SyntaxProject - ├─ executable AST - ├─ narrative nodes / links - └─ contracts / metadata / source spans - ↓ Declaration collection -ProjectIndex - ↓ Name resolution -ResolvedProject - ↓ type + contract + effect + provenance analysis -SemanticProject - ├─ SemanticArtifact[] - ├─ KnowledgeRef[] / KnowledgeStep[] - ├─ DependencyGraph - ├─ Diagnostic[] - └─ HashManifest - ↓ lowering -BoundProgram ──→ Tree Interpreter - └─→ Bytecode compiler / VM -SemanticProject ──→ check / view / EKC / MLSP / lock / Agent -``` - -关键约束:运行器和工具链只能消费语义阶段已经确定的目标,不再用字符串搜索复制一套解析规则。 - -### 4.2 建议的源码目录 - -```text -src/ -├─ syntax/ # 后续从 parse/ast 渐进迁移;第一阶段可保持旧位置 -├─ project/ -│ ├─ mod.rs # ProjectRoot、编译入口、缓存 -│ ├─ discover.rs # 文件发现与边界 -│ ├─ module_id.rs # ModuleId 规范化 -│ └─ source_map.rs # FileId、Span、源码摘要 -├─ sema/ -│ ├─ mod.rs -│ ├─ ir.rs # SemanticProject、Artifact、Ref、Step -│ ├─ symbols.rs # 声明收集、SymbolId、索引 -│ ├─ resolve.rs # 名称解析与歧义诊断 -│ ├─ classify.rs # Type/Entity/Fact/Function/Capability... -│ ├─ types.rs # CanonicalSignature、结构类型、单位 -│ ├─ effects.rs # EffectSet 推导 -│ ├─ provenance.rs # SourceRef 与证据解析 -│ ├─ hashes.rs # 四类 digest -│ └─ lock.rs # links.lock 读写校验 -├─ lower/ -│ ├─ tree.rs # Semantic IR → tree 可执行形式 -│ └─ bytecode.rs # Semantic IR → bytecode 输入 -├─ knowledge/ # SemanticProject 的 EKC 投影/检索/复用 -└─ artifact/ - └─ web.rs # 现有 Web Artifact 分类,避免与 SemanticArtifact 混名 -``` - -第一阶段不要求大规模搬文件。可以先新增 `project`/`sema`,让旧 `ast`、`parse` 成为输入;只有测试稳定后再做目录迁移。 - -### 4.3 公开编译入口 - -```rust -pub struct CompileOptions { - pub project_root: PathBuf, - pub entry: Option<PathBuf>, - pub profile: BuildProfile, - pub lock_mode: LockMode, - pub effect_policy: EffectPolicy, -} - -pub struct Compilation { - pub sources: SourceMap, - pub syntax: SyntaxProject, - pub semantics: SemanticProject, - pub diagnostics: Vec<Diagnostic>, -} - -pub fn compile_project(options: &CompileOptions) -> Result<Compilation>; -``` - -`run`、`check`、`view`、`knowledge compile` 和 MLSP 必须最终汇入此入口。针对内存源码的编辑器调用提供 `compile_overlay(project, overlays)`,不能另写简化语义。 - ---- - -## 5. 统一语义中间表示 - -### 5.1 标识类型 - -禁止在核心 API 中混用裸 `String` 表示文件、符号、制品和摘要: - -```rust -pub struct FileId(u32); -pub struct ModuleId(String); -pub struct SymbolId(String); -pub struct ArtifactId(String); -pub struct RefId(String); -pub struct Digest(String); -``` - -序列化采用显式字符串格式;内存中保持 newtype,避免把显示名误当稳定身份。 - -### 5.2 SemanticArtifact - -```rust -pub struct SemanticArtifact { - pub artifact_id: ArtifactId, - pub symbol_id: SymbolId, - pub display_name: String, - pub kind: SemanticArtifactKind, - pub visibility: Visibility, - pub source: SourceLocation, - pub signature: Option<CanonicalSignature>, - pub implementation: Option<BoundBody>, - pub contract: ContractSet, - pub effects: EffectSet, - pub dependencies: Vec<ArtifactDependency>, - pub provenance: Vec<SourceRef>, - pub applicability: Applicability, - pub hashes: ArtifactHashes, - pub verification: VerificationRecord, - pub lifecycle: Lifecycle, -} - -pub enum SemanticArtifactKind { - Module, - Namespace, - Type, - Entity, - Fact, - Function, - Capability, - Constraint, - Policy, - Dataset, - Document, - ExternalCapability, -} -``` - -`SemanticArtifactKind` 是语义分类,不要求每一类都有新的 Markdown 标记。分类信息来源依次为:显式 metadata/type、结构位置与可检查契约、保守推导。无法确定时选择更一般的 `Function`/`Document`,不得根据函数名猜成 `Fact`。 - -### 5.3 KnowledgeRef 与 KnowledgeStep - -```rust -pub struct KnowledgeRef { - pub id: RefId, - pub label: String, - pub context: RefContext, - pub payload: SyntaxNodeId, - pub resolution: Resolution, - pub expected: ExpectedContract, - pub policy: VerificationPolicy, - pub source: SourceLocation, -} - -pub enum Resolution { - LocalExpression, - Navigation(NavigationTarget), - Symbol { - symbol_id: SymbolId, - artifact_id: ArtifactId, - binding: BindingKind, - }, - Ambiguous(Vec<SymbolId>), - Unresolved, -} - -pub struct KnowledgeStep { - pub id: ArtifactId, - pub reference: RefId, - pub kind: StepKind, - pub inputs: Vec<DataDependency>, - pub outputs: Vec<DataOutput>, - pub calls: Vec<SymbolId>, - pub effects: EffectSet, - pub source: SourceLocation, -} -``` - -引用是“绑定关系”,步骤是“本次命名计算/叙述”。调用同一函数的两个位置拥有同一目标 `SymbolId`,但拥有不同 `RefId` 和 Step Artifact,便于回答“哪个句子受影响”。 - -### 5.4 规范签名 - -```rust -pub struct CanonicalSignature { - pub receiver: ReceiverKind, - pub params: Vec<CanonicalParam>, - pub returns: CanonicalType, - pub effects: EffectSet, -} - -pub struct CanonicalParam { - pub name: String, - pub ty: CanonicalType, - pub required: bool, - pub default_digest: Option<Digest>, - pub unit: Option<String>, - pub constraints: Vec<Predicate>, -} -``` - -参数顺序、名称、是否必填、类型、单位、默认值和 receiver 都进入接口摘要。说明文字不进入接口摘要,但进入证据/文档摘要。 - -### 5.5 EffectSet - -第一版固定以下 effect: - -```text -pure -fs.read fs.write -network.read network.write -process.exec -plugin.call -llm.call -time.read -random.read -user.input -output.write -unknown -``` - -规则: - -- 字面量、算术、纯集合操作为 `pure`; -- 内置/扩展注册时声明 effect;未声明的外部能力为 `unknown`; -- 函数 effect 是本体操作与所有调用依赖 effect 的并集; -- 递归 SCC 求不动点; -- `pure` 不与其他 effect 同时保存,出现其他 effect 即移除 `pure`; -- Narrative context 默认只允许 `pure` 的解析和元数据展示,不自动求值; -- lock 锁定代码不能消除运行环境 effect。 - -### 5.6 来源与验证记录 - -```rust -pub struct SourceRef { - pub uri: String, - pub locator: Option<String>, - pub content_digest: Option<Digest>, - pub retrieved_at: Option<DateTime>, - pub relation: SourceRelation, -} - -pub struct VerificationRecord { - pub parse: CheckState, - pub resolve: CheckState, - pub contract: CheckState, - pub execution: CheckState, - pub tests: CheckState, - pub evidence: CheckState, - pub domain: CheckState, - pub checked_at: Option<DateTime>, - pub methods: Vec<VerificationMethod>, -} -``` - -禁止单个 `verified: bool`。API 可以派生 `reuse_readiness`,但必须保留每层状态与方法。 - ---- - -## 6. 稳定寻址与项目符号索引 - -### 6.1 项目边界 - -项目根解析顺序: - -1. CLI 明确 `--project-root`/现有 `--fs-root`; -2. 从入口文件向上寻找 `.marqdo/project.toml`; -3. 从入口文件向上寻找 `.git`,但只作为默认边界; -4. 否则使用入口文件所在目录。 - -索引不得越过项目根,不跟随逃逸根目录的符号链接,不访问网络。`target`、`.git`、`.marqdo/cache`、`node_modules` 等生成目录默认排除,规则集中定义,不能由 EKC 与编译器各维护一份。 - -### 6.2 ModuleId - -优先级: - -1. frontmatter 显式 `id`; -2. 相对项目根的规范路径,移除 `.mq.md`; -3. 内置和扩展使用其注册的 package/module ID。 - -显式 `id` 在项目内必须唯一。fallback 路径移动会改变 ModuleId,属于可观察变更;需要保持身份时应先补 `id` 或生成 alias migration。 - -### 6.3 SymbolId - -建议序列化格式: - -```text -mq://<project-id>/<module-id>#/<kind>/<declaration-path> -``` - -示例: - -```text -mq://bookshop/knowledge.pricing#/capability/定价/计算应付金额 -mq://bookshop/knowledge.policy#/fact/书店政策/金卡折扣 -``` - -`declaration-path` 使用源码声明层级,不使用数组序号;各段做 UTF-8 percent encoding。相同父级下同 kind 同名声明为硬错误。显示名称可以相同,只要规范地址不同。 - -### 6.4 ArtifactId 与 RefId - -- 声明制品:`ArtifactId = SymbolId + artifact schema version`; -- 命名步骤:基于所属 SymbolId、规范 AST 路径和显式 source anchor 形成; -- 引用:基于 source ModuleId、source span anchor、目标 SymbolId 形成。 - -行号不能单独作为长期身份,因为插入文字会导致全文件漂移。第一版使用“所属声明 + 规范节点路径 + payload digest”,行列仅用于显示和重定位。 - -### 6.5 名称解析顺序 - -可执行代码: - -1. 局部变量与显式接收者; -2. 词法父级声明; -3. 当前模块声明; -4. 显式 `use`; -5. 显式 `import` 绑定; -6. 内置和已注册扩展。 - -正文知识引用可以额外使用项目导出索引做发现,但唯一命中后必须写入具体 SymbolId/lock。代码路径默认不得依赖“扫描全项目后恰好唯一”,否则新增同名文件会改变运行结果。若产品决定允许代码短地址,也必须在首次绑定后要求 lock,且无 lock 构建发出诊断。 - -### 6.6 歧义和重命名 - -- 同一优先级两个候选 → `link.ambiguous`; -- 不允许根据目录遍历顺序、最近修改时间或搜索分数选择; -- 正式重命名由 `symbol-aliases.json` 或迁移命令生成旧→新映射; -- alias 只能用于给出迁移建议,严格模式下不能永久静默转发; -- alias 链禁止循环,默认最多一跳。 - ---- - -## 7. Markdown 与解析实现 - -### 7.1 两层解析而非正则扫描 - -第一层用 CommonMark/GFM 解析块与 inline,保留 source offset;第二层仅在 Marqdo 允许的节点和链接 destination 中调用现有表达式解析器。必须正确处理: - -- destination 中的平衡括号; -- 转义的 `\]`、`\(`、`\)`; -- 中文标识符和 Unicode; -- 多个同一行链接; -- 行内代码与 fenced code 中看似链接的文本; -- 图片 `![alt](src)`; -- 普通 URL、锚点与相对文档链接; -- `**`、`*` 与 Markdown emphasis 的冲突; -- 表格单元格中的链接表达式; -- 正文链接与可执行表达式链接的不同上下文。 - -不得用简单正则从全文提取 `[]()`。 - -### 7.2 Syntax AST 的最小变化 - -短期保留 `Expr::Occluded` 以降低回归风险,但重命名计划如下: - -```rust -Expr::Named { - label: String, - payload: Option<Box<Expr>>, - syntax_id: SyntaxNodeId, -} -``` - -正文增加: - -```rust -pub enum NarrativeInline { - Text(String), - Code(String), - Link(NarrativeLink), - Emphasis(Vec<NarrativeInline>), -} -``` - -`Module` 不应保存完整语义结果,只保留解析结构和 `SyntaxNodeId`。Semantic tables 通过 ID 关联,避免 AST 被工具专用字段污染。 - -### 7.3 Classic 迁移 - -统一语义启用前必须先迁移旧 `[键](集合)`: - -```text -[键](集合) → at(集合, "键") -[`键名`](集合) → at(集合, 键名) -- [项](集合) → 旧循环的规范新写法 -``` - -迁移工具必须: - -1. 在 Classic 模式解析旧文件; -2. 根据 AST 节点类型改写,不做正则替换; -3. 输出文件、行、旧 AST、新 AST 和文本 diff; -4. 默认 dry-run; -5. `--write` 前后分别以 Tree/Bytecode 运行可运行样例并对照结果; -6. 无法证明等价时拒绝自动改写并生成待办; -7. 完成仓库迁移后删除进程全局 `MARKUP_DEFAULT`,保留一个版本周期的只读兼容诊断。 - -不能让未声明模式的同一源码在升级后成功运行但产生不同值。 - ---- - -## 8. 绑定、类型、契约与适用性 - -### 8.1 绑定先于执行 - -每个 Call/Path/KnowledgeRef 在 lowering 前必须变成以下之一: - -```rust -pub enum BoundTarget { - Local(SymbolId), - AssociatedFunction(SymbolId), - InstanceMethod { method: SymbolId, receiver: BoundExprId }, - Imported(SymbolId), - Builtin(BuiltinId), - Extension(ExternalSymbolId), -} -``` - -Tree 和 Bytecode 都执行 `BoundTarget`,不再调用各自的 `lookup_function`/`resolve_call` 猜测相同名字。运行时只允许动态语言特性明确要求的 lookup,例如 `call_fn(text)`;这类动态调用必须带 `dynamic.invoke` effect/图边并降低静态可验证程度。 - -### 8.2 渐进式类型 - -保持 Marqdo 动态运行值,但在语义层建立渐进式类型: - -- 有契约:以契约为主,并与推断参数双向互查; -- 无契约:从字面量、表达式、返回点和调用目标推断; -- 无法确定:`Any/Unknown`,不伪造精确类型; -- `number:CNY` 与 `number:ratio` 的运行存储可以相同,静态契约不可随意互换; -- Map/List/记录结构使用规范 schema; -- 参数、返回、字段、单位与枚举约束分别报告,不合并成笼统“类型错误”。 - -### 8.3 适用性 - -`Applicability` 至少支持: - -```text -input predicates -unit / currency -region -valid_from / valid_until -audience / tenant -environment -required capabilities -``` - -第一版仅实现可以确定性验证的表格契约和 metadata;未支持的自由文本条件保存为 `declared_unchecked`,Agent 使用前必须看到该状态。不能因解析不了而丢弃条件。 - -### 8.4 失败关闭边界 - -以下情况禁止直接执行/复用: - -- 目标未解析或歧义; -- 调用实例方法但没有接收者; -- 参数、返回类型或硬约束不匹配; -- 当前上下文禁止目标 effect; -- strict lock 下 digest 不匹配; -- 策略要求 evidence/domain verified 而状态不满足; -- 目标 deprecated/superseded 且策略禁止旧版本。 - -`knowledge.unverified` 在普通浏览可为 warning,但在调用方明确要求 verified 时升级为 error。 - ---- - -## 9. 指纹、锁定与增量构建 - -### 9.1 四类摘要 - -```rust -pub struct ArtifactHashes { - pub interface: Digest, - pub implementation: Digest, - pub dependency_closure: Digest, - pub evidence: Digest, -} -``` - -- `interface`:kind、receiver、规范签名、公开契约、effect 声明; -- `implementation`:去除无语义格式差异后的 Bound IR; -- `dependency_closure`:implementation 加所有静态依赖的 interface/implementation/closure,按 SymbolId 排序; -- `evidence`:规范化来源定位、内容摘要、验证方法和验证结果。 - -哈希输入必须带 schema version 和域分隔符,例如 `marqdo:artifact-interface:v1\0...`,防止不同对象的相同 JSON 偶然共用语义。 - -### 9.2 依赖环 - -先对调用图求 SCC: - -- SCC 内节点先基于各自 implementation 生成 member digest; -- SCC digest 由排序后的成员 SymbolId/member digest 和外部依赖 closure 生成; -- 成员 closure 使用 SCC digest; -- 这样递归不会无限计算,也不依赖遍历顺序。 - -### 9.3 `links.lock` - -默认路径 `.marqdo/links.lock.json`,规范结构: - -```json -{ - "schema": 1, - "project": "bookshop", - "compiler": "marqdo/2.1.0", - "links": [ - { - "ref_id": "...", - "from": "document.invoice-answer", - "target_symbol_id": "mq://bookshop/knowledge.policy#/fact/书店政策/金卡折扣", - "interface_digest": "sha256:...", - "implementation_digest": "sha256:...", - "dependency_closure_digest": "sha256:...", - "evidence_digest": "sha256:...", - "policy": "compatible" - } - ] -} -``` - -LockMode: - -- `off`:只解析,不读写 lock; -- `check`:有条目则校验,无条目提示; -- `strict`:公共/跨文档引用必须存在且完全符合策略; -- `update`:显式更新,生成变更摘要,绝不由普通 `run` 偷偷改写。 - -### 9.4 缓存 - -`.marqdo/cache/sema/` 只保存可再生内容。缓存 key 至少包含:源码 digest、编译器版本、IR schema、项目配置、目标平台、扩展 registry digest。缓存损坏应回退重编译,不影响正确性。 - -文件扫描、索引和序列化必须排序;相同输入在不同机器、线程数和目录枚举顺序下产生相同摘要与 JSON。 - ---- - -## 10. 验证模型与诊断 - -### 10.1 七层状态 - -| 层 | 问题 | 可自动化程度 | -|---|---|---| -| Parse | 源码结构是否有效 | 确定性 | -| Resolve | 名字是否唯一绑定 | 确定性 | -| Type | 类型、参数、单位是否匹配 | 大部分确定性 | -| Contract | 前置条件/结构约束是否满足 | 声明范围内确定性 | -| Execute/Test | 受控执行和测试是否通过 | 取决于 effect/环境 | -| Evidence | 来源是否存在、内容是否变化、声明是否对应 | 部分确定性 | -| Domain | 现实业务/专业语境中是否正确、仍适用 | 人工或受标注的模型辅助 | - -CLI 输出必须逐层展示。`check OK` 只能表示本次启用的检查没有 error。 - -### 10.2 诊断码 - -| Code | 默认等级 | 触发条件 | -|---|---|---| -| `link.unresolved` | error | 无可绑定目标 | -| `link.ambiguous` | error | 同优先级多目标 | -| `link.ambiguous_syntax` | error | 导航和表达式解释冲突 | -| `link.kind_mismatch` | error | 目标 kind 不可用于当前位置 | -| `link.instance_only` | error | 用类路径调用实例方法 | -| `link.arg_mismatch` | error | 参数数量/名称不匹配 | -| `link.type_mismatch` | error | 静态类型或单位不匹配 | -| `link.no_value` | warning/error | 值上下文目标无返回 | -| `link.effect_forbidden` | error | 当前上下文/能力策略不允许 effect | -| `link.target_changed` | warning/error | lock 目标或摘要改变 | -| `link.dynamic_unverified` | warning | 动态调用无法静态绑定 | -| `knowledge.source_missing` | warning/error | 声明来源不存在 | -| `knowledge.source_changed` | warning | 来源摘要变化未复核 | -| `knowledge.constraint_unmet` | error | 硬适用条件不满足 | -| `knowledge.not_yet_valid` | error | 尚未生效 | -| `knowledge.expired` | warning/error | 超出有效期 | -| `knowledge.unverified` | info/warning/error | 未达到调用方所需验证策略 | -| `knowledge.deprecated` | warning/error | 复用过时制品 | -| `label.ref_dangling` | error | label 中结构化反引号引用无目标 | -| `label.possibly_stale` | hint | 实现变化但 label 未复核 | - -每条诊断必须包含 `code`、`severity`、source span、相关声明 span、候选目标(若有)、建议和所依据的 policy。JSON 结构向后兼容现有 `Diagnostic::to_json()`,新增字段不得把旧字段改义。 - -### 10.3 标签语义边界 - -label 与 payload 的自然语言一致性无法由类型系统完全证明。确定性检查仅覆盖: - -- label 内反引号引用存在; -- payload 或目标变更后的 stale 提示; -- 明显单位/返回类型冲突; -- 显式词表规则。 - -LLM 语义复核是可选 provider,结果必须标为 heuristic,不能阻止离线编译,也不能覆盖确定性诊断。 - ---- - -## 11. 执行后端改造 - -### 11.1 Tree Interpreter - -改造目标: - -- `eval_call` 接受 `BoundCall`,不再按字符串顺序尝试 local/path/builtin/plugin; -- AssociatedFunction 直接用目标函数及所属模块执行,不运行对象构造体; -- InstanceMethod 保留 `_type`/继承链行为,但 method 已在语义层确定; -- `Expr::Named` 只透传 payload 值,同时向 trace 记录 `RefId`、ArtifactId、target digest; -- Host/Plugin 调用从 registry 获取签名和 effect; -- 运行时契约继续作为动态防线,不能因静态检查存在而删除。 - -### 11.2 Bytecode - -新增或调整操作码: - -```text -CallBound(symbol_index, argc) -CallMethodBound(symbol_index, argc) -TraceRefEnter(ref_index) -TraceRefExit(ref_index) -``` - -`Program` 增加 symbol/ref tables,disassemble 显示 SymbolId 和来源。旧 `Call(fid, argc)` 可以作为内部 lowering 结果保留,但编译阶段必须来自 BoundTarget,而不是 `resolve_call(name)`。 - -### 11.3 双后端一致性 - -每个 gold case 同时运行 Tree 和 Bytecode,比较: - -- 返回值; -- stdout; -- 结构化错误 code 和 source span; -- 实际调用的 SymbolId 序列; -- KnowledgeRef trace; -- effect 拒绝结果。 - -仅文本错误措辞可允许微小差异;机器字段不得不同。 - -### 11.4 叙述预览 - -`view` 若显示正文 pure 引用的值,应通过单独的 PreviewExecutor: - -- 默认仅允许 `pure`; -- 有输入的函数不自动调用; -- 有未知 effect 不调用; -- 限制步数、递归深度、输出大小和总时间; -- 超限只显示“可解析但未预览”,不影响页面其余部分; -- 预览结果标识输入、digest 和时间,不写回源码。 - ---- - -## 12. EKC、知识图与 Agent 复用 - -### 12.1 EKC 角色调整 - -EKC 从“再次阅读源码并猜测工程知识”调整为: - -```text -SemanticProject - ├─ project_symbols() → L0/L1/L2 - ├─ capabilities() → L3 - ├─ authored_knowledge → L4 - ├─ graph_edges() → graph - └─ search_documents() → lexical/vector optional index -``` - -短期兼容 `KnowledgeGraph`、现有 CLI 和 `.marqdo/catalog/**` 输出;内部字段逐步由 `SemanticArtifact` 填充。旧文本提取只为非 `.mq.md` authored knowledge 保留,不能覆盖编译器确定的符号和调用边。 - -### 12.2 图节点与边 - -节点:Project、Module、SemanticArtifact、KnowledgeStep、Evidence、Test、Execution、AgentEpisode。 - -核心边: - -```text -contains -declares -references -calls -reads -derives -iterates -produces -depends_on -constrained_by -supported_by -tested_by -verified_by -supersedes -conflicts_with -executed_in -reused_in -``` - -`calls/references/depends_on` 必须来自 Bound IR;搜索命中不得直接生成事实图边。 - -### 12.3 Agent 状态机 - -```text -TASK - → DISCOVER 模糊查找候选 - → RESOLVE 精确绑定 SymbolId - → INSPECT 获取签名/effect/适用性/来源/状态 - → CONTRACT_CHECK - ├─ ready → BIND → EXECUTE → TRACE - ├─ adaptable → ADAPT → VERIFY → PROMOTE - ├─ unusable → 继续发现或 CREATE - └─ ambiguous → 请求消歧/失败关闭 - → CREATE 仅在 reuse budget 和 policy 允许时 - → VERIFY → PROMOTE -``` - -REUSE 的判据不是“搜索分数超过阈值”,而是候选已经精确绑定、输入满足契约、effect 获得许可、版本策略通过。搜索分数只用于候选排序。 - -`ready` 是对所选 policy、输入与上下文的判断,不是所有知识必须先获得的全局认证。AI 可以从候选中选择明确目标;歧义不能交给执行器按扫描顺序消解。ADAPT/CREATE 必须遵守任务写权限和预算,缺少业务决策时请求补充,而非擅自改变适用条件。草稿可被发现并在明确权限下探索执行,但不得冒充已通过严格政策的事实。 - -发现结果应按需包含标题/步骤、源码片段、输入角色、契约、效应、来源、验证缺口和相关失败经验。局部编辑须携带期望源码摘要,应用后检查语义 diff 与相关测试;不以重写整份文档作为默认修复方式。协议及受限试点范围见[指导 §5](../design/document-native-development-guide.md#5-ai-原生工作协议读步骤改步骤验证步骤)。 - -### 12.4 BoundArtifactHandle - -```rust -pub struct BoundArtifactHandle { - pub symbol_id: SymbolId, - pub artifact_id: ArtifactId, - pub interface_digest: Digest, - pub dependency_closure_digest: Digest, - pub accepted_effects: EffectSet, - pub verification_policy: VerificationPolicy, - pub expires_at: Option<DateTime>, -} -``` - -Agent 执行必须携带 handle 和显式输入;runtime 再次核对摘要和权限,防止发现后到执行前目标变化。handle 是能力引用,不包含可由模型修改后悄悄执行的源码副本。 - -上述结构表达绑定内容,不独自构成远程授权凭据。受信本地调用可先采用精确引用和摘要复核;不受信/远程调用必须另有服务端认可的主体、能力范围、防伪及撤销/期限机制,客户端自报 `accepted_effects` 不能扩大宿主许可。handle 由工具产生,不要求作者维护;是否检查 lock 和来源新鲜度取决于明确的 policy。 - -### 12.5 Promote 门槛 - -Agent 新建或适配的知识进入**共享自动复用的 ready 集合**前,按目标 policy 至少完成: - -- Parse/Resolve/Type/Contract 通过; -- effect 已由静态绑定与宿主/扩展元数据推导;不能推导时保留 unknown 并按政策拒绝或要求明确能力许可,不要求业务作者抄写闭包; -- pure 逻辑有测试,外部 effect 有 mock/沙箱证明或人工批准; -- 来源型知识附 SourceRef; -- 生命周期从 `draft` 开始; -- 生成者、输入、工具版本、变更 diff 可审计; -- 未达到门槛的内容保持 draft/quarantine 状态;可在同一权威索引中过滤展示,不另造语义身份。 - -这是晋升政策,不是普通 `.mq.md` 文件被索引、查看或本地执行的前置注册流程。简单纯计算不强制现实来源;声称业务事实成立的知识不能用测试通过替代所需证据。 - ---- - -## 13. CLI、MLSP 与文件产物 - -### 13.1 CLI 演进 - -保留现有命令,增加能力而不是平行造新命令族: - -```bash -marqdo check PATH --project-root ROOT --lock check --json -marqdo run FILE --lock strict --trace-knowledge trace.json -marqdo knowledge compile PATH -marqdo knowledge inspect SYMBOL -marqdo knowledge resolve EXPR --from FILE -marqdo knowledge verify SYMBOL --policy POLICY -marqdo knowledge impact SYMBOL_OR_PATH -marqdo knowledge lock [--check|--update] -marqdo migrate labels PATH [--write] -``` - -退出码: - -- `0`:成功且无 error; -- `1`:程序/验证失败; -- `2`:CLI 使用错误; -- `3`:strict lock 不一致; -- `4`:effect/权限拒绝; -- `5`:项目索引或缓存损坏且无法重建。 - -### 13.2 MLSP 方法 - -新增: - -| Method | 输入 | 输出 | -|---|---|---| -| `artifact.find` | query、kind、limit、project | 候选摘要;仅 discovery | -| `artifact.inspect` | SymbolId/ArtifactId | 签名、契约、effect、来源、hash、状态 | -| `link.resolve` | source file、payload/span | Resolution、候选、诊断 | -| `artifact.verify` | SymbolId、policy、可选输入 | 分层 VerificationRecord | -| `artifact.impact` | SymbolId/digest/path | 反向依赖与受影响步骤 | -| `artifact.bind` | SymbolId、expected digest、policy | BoundArtifactHandle;不直接执行 | -| `artifact.execute` | handle、inputs、capabilities | result、trace、更新后的状态 | - -所有方法复用 `compile_project`,支持 overlay,不得自己调用 EKC 字符串搜索来完成 resolve。 - -### 13.3 生成目录 - -```text -.marqdo/ -├─ project.json -├─ symbols.json -├─ artifacts/ -│ └─ <artifact-id>.json -├─ refs.json -├─ graph/ -│ ├─ nodes.json -│ └─ edges.json -├─ links.lock.json -├─ verification/ -│ └─ <artifact-id>.json -├─ traces/ -│ └─ <execution-id>.json -├─ catalog/ # 兼容现有 EKC -├─ knowledge/ # 兼容现有 EKC -└─ cache/ # 可删除、可重建 -``` - -所有生成文件写入前先在临时文件完整生成和校验,再原子替换;编译失败不得留下“半新半旧”的项目图。 - -### 13.4 JSON schema 与版本 - -每类生成物必须有 `schema_version`,schema 文件纳入仓库。新增可选字段为兼容变化;删除、改义或类型变化必须提升 major schema。测试用 JSON 不比较键顺序,但生产输出按固定顺序生成以便 review。 - ---- - -## 14. View 与可解释性 - -### 14.1 每个引用的最小展示 - -View 至少展示: - -- label 和 payload; -- 目标显示名、SymbolId、kind; -- 签名、单位、effect; -- 解析/契约/测试/证据状态; -- 当前值或“未执行”的原因; -- 来源与目标源码跳转; -- interface/implementation 是否与 lock 一致; -- 上游依赖和下游影响入口。 - -### 14.2 状态措辞 - -允许: - -- “已解析到……” -- “契约检查通过” -- “测试于某版本通过” -- “来源存在但尚未完成领域复核” - -禁止: - -- 仅因函数能运行显示“知识正确”; -- 仅因 URL 可访问显示“来源已验证”; -- 仅因搜索命中显示“已复用”; -- 隐藏 effect 或 lock 变化。 - -### 14.3 可达性和静态导出 - -状态不能只靠颜色表达;HTML 使用文本、图标和可访问标签。`view output --no-exec` 仍展示解析与验证元数据,只隐藏运行值。静态导出不得为了显示知识值而放宽运行权限。 - ---- - -## 15. 安全、权限与可信边界 - -### 15.1 能力安全 - -沿用现有 HostCaps,并扩展到细粒度 EffectPolicy。编译期 effect 是预检查,运行时 capability 是最终授权。两者缺一不可。 - -正文链接、view 预览、`check` 和 `knowledge compile` 必须是只读路径,不得因为分析引用而触发: - -- 文件写入; -- 网络写操作; -- 外部进程; -- 插件动态加载; -- LLM 请求; -- 用户输入等待。 - -### 15.2 路径与来源 - -- 项目文件和相对 SourceRef 规范化后必须仍在允许根内; -- symlink 逃逸按真实路径检查; -- 来源摘要读取大小有上限; -- 远程来源默认不在编译时抓取,只使用已有快照/显式 verify; -- URL 凭据、token 和查询机密不得进入 graph、lock 或 trace; -- trace 对参数和值执行现有 secrets/redaction 策略。 - -### 15.3 TOCTOU - -解析、绑定与执行之间,用 source/hash 校验防止目标变化。严格执行时发现 handle digest 与磁盘当前制品不一致,应拒绝并要求重新绑定。 - ---- - -## 16. 迁移与兼容策略 - -### 16.1 版本阶段 - -| 阶段 | 默认行为 | 兼容行为 | -|---|---|---| -| 2.0.x | Classic 默认,Occlusion opt-in | 历史行为 | -| 2.1 preview | 新语义默认;全仓语料具有文件级 `markup: occlusion` | `--legacy-markup` / 显式 `markup: classic` 只读过渡 | -| 2.1 stable | 新语义默认;旧形状必须已迁移 | `--legacy-markup` 只读运行一个周期 | -| 2.2 | 删除全局模式与旧 parser 分支 | 仅保留明确错误和迁移建议 | - -具体版本可随发布计划调整,但顺序不能颠倒。 - -### 16.2 不破坏的能力 - -- 现有显式 import; -- 实例构造与实例方法; -- 当前契约表; -- Tree/Bytecode CLI 入口; -- EKC 的 `find/reuse/impact` 用户命令; -- Web/Endpoint Artifact metadata; -- 无 `[]()` 文件的既有执行结果。 - -### 16.3 必须显式变化的能力 - -- `[键](集合)` 迁为 `access(集合, "键")`; -- 链接不再依赖进程级 markup 模式; -- `类.函数` 对无 receiver 函数成为合法 AssociatedFunction 调用; -- 正文知识链接被解析和诊断,但不自动执行; -- EKC 的 calls/edges 由 Bound IR 取代名字猜测; -- lock 更新从普通编译中分离。 - -### 16.4 迁移报告 - -```json -{ - "file": "...", - "before_mode": "classic", - "changes": [ - { - "span": {"line": 10, "col": 4}, - "kind": "index_to_at", - "before": "[银卡](折扣表)", - "after": "at(折扣表, \"银卡\")", - "semantic_check": "equivalent" - } - ], - "manual_review": [], - "tree_equivalent": true, - "bytecode_equivalent": true -} -``` - ---- - -## 17. 分阶段开发计划 - -M0–M6 保留为工程能力与验收项目,不再作为顺序排期;部分迁移能力已经完成,状态见[现状审计](../roadmap/executable-knowledge-gaps-2026-10-23.md)。实际工作按[文档原生 S0–S6](../design/document-native-development-guide.md#7-交付切片每片都有文档作者与-ai-能看见的结果)形成可独立合并的垂直切片:早期联动 M1/M2/M3/M5 的安全子集,交付可读步骤和真实复用,不能等 M4 全部做完才让作者或 Agent 使用。100 单元生成器逐步增长,不阻塞最小故事;不得先大规模重构再等待最后一次性验收。 - -### M0:语义冻结与测试生成器 - -交付: - -- 本文进入仓库并被文档索引引用; -- `tests/executable_knowledge/` gold case 结构; -- 100 单元项目生成器,固定随机种子; -- 解析上下文、导航链接、旧索引、正文安全的测试矩阵; -- 当前行为快照和预期变化清单。 - -完成条件: - -- 测试可以明确区分“当前失败(expected fail)”与回归; -- 所有新诊断 code、JSON 最小字段和退出码冻结; -- 不依赖 LLM 或网络即可运行核心套件。 - -### M1:ProjectIndex 与稳定身份 - -交付: - -- `project/`、`sema::symbols`; -- FileId/ModuleId/SymbolId; -- 项目范围、确定性扫描、duplicate/ambiguous 诊断; -- 显式 import 与正文项目发现索引; -- `marqdo knowledge inspect/resolve` 最小接口。 - -完成条件: - -- 改变文件扫描顺序不改变绑定或输出; -- 同名李白示例报歧义,限定地址能解析; -- 同一源码连续构建的 SymbolId 完全一致; -- fallback 路径移动被 lock/impact 识别。 - -### M2:统一 Named/Ref IR 与类函数 - -交付: - -- Markdown-aware narrative links; -- `Expr::Named`/兼容 lowering; -- KnowledgeRef/KnowledgeStep; -- AssociatedFunction/InstanceMethod 分类; -- Tree 和 Bytecode 使用 BoundTarget; -- 正文不执行测试。 - -完成条件: - -- 两文档李白示例无需构造实例即可解析; -- 代码上下文可求得 `701`,正文上下文只解析; -- 使用 `self/自` 的方法经类路径调用报 `link.instance_only`; -- 两后端返回值、调用 SymbolId 和错误 code 一致。 - -### M3:SemanticArtifact、契约、effect、来源 - -交付: - -- 完整 Artifact IR 和分类; -- CanonicalSignature、EffectSet、Applicability; -- SourceRef 和分层 VerificationRecord; -- 四类 digest; -- 扩充 `check --json`。 - -完成条件: - -- 参数、类型、单位、适用条件和 effect 分别诊断; -- pure/外部 effect 传递闭包正确; -- 来源删除、内容变化与实现变化产生不同状态; -- 格式化空白不改变 implementation digest,语义变更会改变。 - -### M4:Lock、增量与影响分析 - -交付: - -- links.lock check/update/strict; -- SCC closure digest; -- 原子写入、缓存和确定性序列化; -- 反向引用/依赖/证据影响查询。 - -完成条件: - -- 金卡折扣变化能找到获取折扣、计算应付、结算入口和正文说明; -- interface/implementation/evidence 变化能分别展示; -- strict 模式拒绝未审阅的目标变化; -- 清空缓存后结果与增量构建完全一致。 - -### M5:EKC、View、MLSP 与 Agent - -交付: - -- EKC 消费 SemanticProject; -- view 的引用卡片、来源链和状态; -- MLSP 七个 artifact 方法; -- BoundArtifactHandle 和 Agent 复用 trace; -- draft/quarantine/promote 流程。 - -完成条件: - -- 图中 calls 边与实际运行 trace 的静态目标一致; -- Agent 命中 ready 制品时执行 handle,不生成新函数; -- 只有模糊候选时不能直接执行; -- 不满足所选验证政策、已过相关有效期或 effect 不允许的制品不会被标记为该 policy 下的 REUSE ready;本地探索不冒充严格验证。 - -### M6:迁移默认值与发布 - -交付: - -- 全仓 Classic 语法迁移; -- 默认切换、兼容 flag、弃用说明; -- public/examples/tutorial 更新; -- schema 文档、升级指南和 release notes; -- 100 单元基准与 Agent 对照实验。 - -完成条件: - -- 全部现有 gold tests 加新套件通过; -- 仓库不再依赖全局 Markup 状态; -- 迁移前后无未说明的输出变化; -- 性能、正确性和复用指标达到发布阈值。 - ---- - -## 18. 文件级实施清单 - -下表是目标职责映射,不是“所有文件尚未创建”的任务表。`src/project/`、`src/sema/` 和部分 API 已存在,先检查对应缺口与测试,再增量修改;不要依照旧“新建”措辞重复搭建模块或移走仍被消费者使用的能力。 - -| 文件/模块 | 修改 | -|---|---| -| `src/ast.rs` | 增加 SyntaxNodeId;`Occluded` 迁为 `Named`;承载 Narrative AST 的最小引用 | -| `src/parse/prose.rs` | 用 Markdown event/span 构建正文 inline/link,不执行 | -| `src/parse/expr.rs` | 统一 `[]()`;隔离并最终删除 Classic 分支和全局状态 | -| `src/load.rs` | 保留单模块加载;项目构建改由 `project` 编排;frontmatter mode 进入迁移诊断 | -| `src/project/*` | 新建项目发现、SourceMap、ModuleId、缓存 | -| `src/sema/*` | 新建符号、解析、类型、effect、来源、hash、lock、统一 IR | -| `src/check.rs` | 成为 SemanticProject 诊断聚合器;保留当前契约规则 | -| `src/contract.rs` | 输出规范 CanonicalType/Predicate;运行时校验复用同一声明 | -| `src/interp.rs` | 从 BoundProgram 执行;AssociatedFunction;Ref trace | -| `src/bytecode/compile.rs` | 删除独立名字绑定职责;从 BoundCall 生成 opcode | -| `src/bytecode/vm.rs` | 执行 bound symbol/ref table;统一 trace 与诊断 | -| `src/artifact/mod.rs` | 迁移现有 Web 分类,释放概念命名 | -| `src/knowledge/extract.rs` | `.mq.md` 改从 SemanticProject 投影;普通 `.md` 仍可提取 authored knowledge | -| `src/knowledge/fingerprint.rs` | 相似性 fingerprint 保留作检索;规范 digest 改用 `sema::hashes` | -| `src/knowledge/graph.rs` | 从已绑定依赖生成边;移除“第一个同名符号”策略 | -| `src/knowledge/reuse.rs` | 搜索分数只做 discover;新增 readiness/bind gate | -| `src/mlsp.rs` | 加 artifact API;dispatch 共享 project compiler 与 overlay | -| `src/view/*` | 消费 LinkInfo/VerificationRecord;PreviewExecutor 隔离执行 | -| `src/main.rs` | CLI 参数、lock/trace/inspect/resolve 子命令和退出码 | -| `tests/executable_knowledge/*` | 正负例、双后端、迁移、lock、effect、图、Agent 测试 | -| `examples/executable-knowledge/*` | 以书店示例替换占位目标,标注每阶段可运行状态 | - -实现时每个 PR 只覆盖一个可验收切片;不要在同一提交混合语法迁移、IR 重构和 UI 大改。 - ---- - -## 19. 自动化测试规范 - -### 19.1 单元测试 - -- SymbolId/ModuleId 规范化、Unicode、路径移动; -- Markdown destination 平衡括号与转义; -- 导航/知识引用消歧; -- AssociatedFunction/InstanceMethod 分类和传播; -- CanonicalSignature/类型/单位; -- EffectSet 合并与 SCC; -- 四类 digest 的稳定性; -- lock policy; -- VerificationRecord 状态提升/降级; -- JSON schema round-trip。 - -### 19.2 集成正例 - -- 李白两文档事实; -- 书店政策→定价→结算→客服说明; -- 显式 import 的类函数; -- 本地表达式遮蔽; -- 正文 pure 引用 view 预览; -- 实例继承方法保持行为; -- 表格/循环/取元形成 KnowledgeStep; -- 中文/英文双名与扩展能力; -- Tree/Bytecode 完全一致。 - -### 19.3 集成负例 - -至少覆盖: - -- 目标删除/改名; -- 同级同名; -- 文档发现唯一但代码缺显式 import; -- 漏参、多参、错误具名参数; -- number/text、CNY/ratio 错配; -- 类路径调用实例方法; -- 零参省略作用于有参函数; -- 正文调用网络、写文件、支付或 LLM; -- 来源删除、来源内容变化、有效期过期; -- 实现未变但传递依赖变化; -- lock 的 target/interface/implementation/evidence 分别变化; -- 递归依赖和循环 import; -- symlink 越界; -- label 与代码明显冲突; -- 动态调用无法验证; -- 缓存损坏; -- 目录扫描顺序扰动。 - -### 19.4 100 单元确定性夹具 - -生成器固定包含: - -| 类别 | 数量建议 | -|---|---:| -| 正常跨文档调用链 | 25 | -| 同名/限定名/导入消歧 | 15 | -| 签名/类型/单位错误 | 15 | -| 来源/有效期/验证状态 | 10 | -| effect 与正文安全 | 10 | -| 依赖变化/lock/impact | 15 | -| 递归、循环和动态调用 | 10 | - -每次生成额外随机打乱文件创建顺序。断言绑定结果、诊断集合、digest 和图边与顺序无关。 - -### 19.5 属性与模糊测试 - -- `[L](E)` 与 `E` 在执行上下文的值/type/effect 等价; -- 格式化和无语义叙述变化不改变 implementation digest; -- 任一 Bound call 对应且仅对应一个静态 target; -- graph 的静态 calls 边覆盖所有非动态运行调用; -- lock update 后 strict check 通过; -- parser 对任意输入不 panic; -- view/check 对正文链接永不触发外部 effect。 - ---- - -## 20. 基准、实验与发布门槛 - -### 20.1 编译器指标 - -- 冷构建耗时、峰值内存; -- 单文件变更增量耗时; -- 1k/10k/100k artifact 索引规模; -- 符号解析准确率; -- 影响分析 precision/recall; -- 两后端一致率; -- 缓存命中率; -- 生成物确定性。 - -### 20.2 Agent 复用指标 - -在相同模型、任务、工具、token 预算和超时下比较普通 Markdown+RAG、当前 EKC、Semantic Artifact 方案: - -- 已有能力发现率; -- 正确绑定率; -- 不适用知识误用率; -- 重复函数新增率; -- REUSE/ADAPT/CREATE 分布; -- 首次可运行成功率; -- 总 token、工具调用、修复轮次和耗时; -- 回答能否追溯到 SymbolId、digest、输入和来源。 - -同时记录作者手写声明/重复字段/配置数量、阅读定位准确率、语义步骤修改范围、无关 diff、并发补丁冲突和首次写作成本。比较时各方案应获得同等现有能力与输入信息,不向新方案额外提供答案;将编译和人工准备成本计入总成本。先通过正确性与权限硬门槛,再讨论 token 和速度收益,参见[指导 §8](../design/document-native-development-guide.md#8-验证-marqdo-优势而不只验证组件存在)。 - -### 20.3 发布门槛 - -- 核心确定性套件 100% 通过; -- 双后端目标用例 100% 一致; -- 正文安全测试 0 次外部 effect; -- 符号歧义无静默选择; -- 迁移工具对已自动改写样例 100% 语义等价; -- graph calls 与 bound calls 一致; -- Agent 不适用知识误用率不得高于现有基线; -- 性能退化超过预设阈值必须有明确批准与记录。 - -不要只报告平均值;保存失败样本、任务定义、环境、置信区间和版本摘要。 - -以上按发布宣称的能力范围执行。语法兼容、本地确定性复用、严格业务复用、远程执行分别有独立证据,不以一个总体 `done` 替代。M0–M6 保留为工程能力检查项,实际交付顺序采用[修订路线 S0–S6](../roadmap/executable-knowledge-gaps-2026-10-23.md#7-依赖顺序与可合并切片):早期完成一篇文档的读/执行/复用闭环,再增加治理深度;任何已开放执行路径都不能延后安全门禁。 - ---- - -## 21. 书店示例的最终验收链 - -以附属示例为系统级验收: - -```text -corpus/pricing-policy.md - └─ supported_by -knowledge/policy.mq.md - ├─ 书店政策.金卡折扣 - ├─ 书店政策.银卡折扣 - ├─ 书店政策.免运费门槛 - └─ 书店政策.基础运费 - ↓ calls / depends_on -knowledge/pricing.mq.md - └─ 定价.计算应付金额 - ├─ 计算商品小计 - ├─ 获取折扣 - └─ 计算运费 - ↓ reused_in -apps/checkout.mq.md + apps/assistant.mq.md -``` - -必须验证以下全过程: - -1. 项目编译产生稳定 SymbolId; -2. 所有 `[]()` 产生 Ref/Step; -3. `60 × 2 × 0.90 = 108` 由 Tree/Bytecode 同样计算; -4. assistant 正文不在 `run` 中执行; -5. view 可显示门槛、折扣、来源和验证层级; -6. 修改金卡折扣到 `0.88` 后 implementation 和 closure 改变; -7. 未更新来源时显示 evidence 不一致; -8. impact 找到所有下游引用; -9. strict lock 拒绝静默使用新版; -10. 审阅并 update lock 后 Agent 可重新 bind/execute; -11. 输入数量为 0 时在执行前报 `knowledge.constraint_unmet`; -12. 在正文引用支付能力时拒绝 effect,而不是发起支付。 - ---- - -## 22. 开发过程约束 - -1. **一套语义事实源**:parser 只认语法,sema 决定身份和含义,runtime 执行 bound target,EKC/view/Agent 消费结果。 -2. **先确定性,后智能化**:解析、绑定、契约、effect、hash、lock 不使用 LLM。 -3. **先负例,后演示**:每新增一种成功路径,至少增加一个歧义/权限/变化负例。 -4. **不静默兼容**:旧写法可能改义时必须迁移或报错。 -5. **不伪造可信度**:未知就是 unknown,待复核就是 pending。 -6. **不复制源码复用**:复用结果是 SymbolId/handle/trace,不是代码片段。 -7. **生成物可删除**:`.marqdo` 投影永远可以从源码和显式证据重建。 -8. **产物可审计**:每个值知道由哪个符号、版本、输入和 effect 得到。 -9. **变化可传播**:实现、依赖、证据和适用性分开变更、分开报告。 -10. **文档与代码共同验收**:示例未能由当前版本运行前,必须继续标为目标而不是已实现。 - ---- - -## 23. 最终定义 - -Marqdo 的本轮开发不以“链接语法更漂亮”为终点,而以以下能力闭环为终点: - -> 一份由人维护的可读文档,被编译为具有稳定身份、明确契约、可追踪来源、受控副作用和版本摘要的语义制品;人或 AI 可以先发现它,再精确绑定它,在满足适用条件与权限后直接执行它,并把实际复用关系写回可审计的知识图。 - -`[]()` 是这条链路统一、低负担的作者入口;Semantic Artifact 是编译器的统一事实;Verified Knowledge Reference 是从文档到执行的确定性桥梁;EKC、view、MLSP 和 Agent 是同一语义结果的不同投影与消费者。 - -只有当“发现已有知识 → 确定绑定 → 验证适用 → 执行既有制品 → 追踪复用结果”能够在不重新生成同义实现的情况下完成,Marqdo 才真正达成: - -**代码即文档,文档即知识库,知识库可执行,可执行知识可复用。** diff --git a/doc/next/Marqdo_Executable_Knowledge_Example.md b/doc/next/Marqdo_Executable_Knowledge_Example.md deleted file mode 100755 index b1549bc..0000000 --- a/doc/next/Marqdo_Executable_Knowledge_Example.md +++ /dev/null @@ -1,400 +0,0 @@ -# Marqdo 可执行知识范式:多文件完整示例与对照 - -> **规范性目标示例**:用于描述 v2.1+ 期望语义;并非宣称 v2.0.0 已能运行所有代码。示例内价格、折扣、门槛均为虚构业务数据。 -> 展示:Markdown 叙述、frontmatter 导入、`#` 类型、`##` 函数、继承、表格集合、隐式形参、`**` 代码、`*` 返回、条件有序列表、循环无序列表、变量反引号、带描述的 `[]()`、对象、契约、来源、知识索引与 Agent 复用。 - -## 1. 实际业务场景 - -一家虚构的“云雀书店”需要将定价规则维护为**人类可阅读的运营文档**,由网站、客服机器人、后端结算、审计报告复用,而不是让四个 AI 分别根据文字重新写四次逻辑。业务规则:普通会员 100% 计价,银卡会员 95%,金卡会员 90%;订单满 100 元免 8 元运费;仅处理人民币订单,件数为正整数。所有规则均为示例,没有现实效力。 - -### 项目结构 - -```text -bookshop/ -├─ corpus/ -│ └─ pricing-policy.md # 业务原始资料(不可执行) -├─ knowledge/ -│ ├─ policy.mq.md # 已编译的政策知识 -│ ├─ order.mq.md # 数据类型及订单操作 -│ └─ pricing.mq.md # 定价能力 -├─ apps/ -│ ├─ checkout.mq.md # 业务执行入口 -│ ├─ assistant.mq.md # AI 问答呈现/知识引用 -│ └─ batch.mq.md # 列表与循环 -└─ .marqdo/ # 生成:catalog、symbols、graph、links.lock -``` - -## 2. 原始资料 `corpus/pricing-policy.md` - -```markdown -# 云雀书店价格政策(演示) - -生效范围:2026 年演示订单,人民币;不代表任何真实商店。 - -## 会员折扣 - -普通会员不优惠;银卡会员九五折;金卡会员九折。 - -## 运费 - -商品合计满 100 元免运费,否则运费为 8 元。 - -## 约束 - -商品单价不得为负;数量必须为正整数。会员等级仅允许普通、银卡、金卡。 -``` - -这是原始证据,并非运行时调用目标。它可被查看、引用和版本化,但不能因为被 AI 读到就自动获得 `verified` 状态。 - -## 3. 政策知识 `knowledge/policy.mq.md` - -使用现有类/函数、返回值与契约表,将业务知识拆成稳定的、可发现的编译单元。 - -```markdown ---- -title: 云雀书店演示定价政策 -type: policy ---- - -# 书店政策 - -这是云雀书店的演示业务政策,供结算、客服和审计引用。 - -规则只适用于人民币演示订单,来源为 -[价格政策原文](../corpus/pricing-policy.md)。 - -## 金卡折扣 - -| 返回 | 类型 | 单位 | 来源 | -|---|---|---|---| -| 0.90 | number | ratio | corpus/pricing-policy.md#会员折扣 | - -*0.90* - -## 银卡折扣 - -| 返回 | 类型 | 单位 | 来源 | -|---|---|---|---| -| 0.95 | number | ratio | corpus/pricing-policy.md#会员折扣 | - -*0.95* - -## 免运费门槛 - -| 返回 | 类型 | 单位 | 来源 | -|---|---|---|---| -| 100 | number | CNY | corpus/pricing-policy.md#运费 | - -*100* - -## 基础运费 - -| 返回 | 类型 | 单位 | 来源 | -|---|---|---|---| -| 8 | number | CNY | corpus/pricing-policy.md#运费 | - -*8* - -## 获取折扣 - -根据输入会员等级`等级`确定折扣比例。 - -| 参数 | 类型 | 说明 | -|---|---|---| -| 等级 | text | 普通、银卡、金卡 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 比例 | number | 0 到 1 之间的比例 | - -1. `等级` == "金卡" - *[金卡优惠比例](书店政策.金卡折扣)* -2. `等级` == "银卡" - *[银卡优惠比例](书店政策.银卡折扣)* -3. * - *1* -``` - -**说明**:`书店政策.金卡折扣` 等类函数直接调用属于 v2.1 目标;现有 `#` 类型/`##` 方法和表格、分支是当前语言能力。严格策略下,非法会员等级应报 `knowledge.constraint_unmet` 而不是无条件走默认分支;此处末尾 `3. *` 只是语言分支结构示范,正式实现需要额外拒绝非法等级。 - -## 4. 订单类型与继承 `knowledge/order.mq.md` - -```markdown -# 订单 - -一个订单至少包含数量、单价和会员等级。 - -## 描述 - -本方法使用`自`读取对象字段,属于**实例方法**。 - -*自* - -# 线上订单 = > 订单 - -线上订单是订单类型的一个特化。此处是实际继承语义,不把它误称为“知识实体实例化”。 - -## 渠道 - -*"online"* -``` - -注意:`# 线上订单 = > 订单` 在 Marqdo 中的确代表子类型继承;`> 线上订单` 构造实例,实例方法需要实例接收者。在知识分层中,普通 Fact 不应强制视为类实例。 - -## 5. 核心能力 `knowledge/pricing.mq.md` - -这是“知识直接被复用”的核心,而不是把文字重新交给 AI 算一遍。 - -```markdown ---- -title: 价格计算能力 -import policy:knowledge/policy.mq.md ---- - -# 定价 - -下列函数实现演示书店的结算规则,适用于人民币演示订单。 - -## 计算商品小计 - -输入商品`单价`和`数量`。 - -| 参数 | 类型 | 约束 | -|---|---|---| -| 单价 | number | 大于等于 0;单位 CNY | -| 数量 | number | 大于 0,且为整数 | - -| 返回 | 类型 | 单位 | -|---|---|---| -| 小计 | number | CNY | - -**小计 = [商品小计](单价 * 数量)** -*小计* - -## 计算运费 - -根据商品折扣后的金额`金额`决定是否免运费。 - -1. `金额` >= [免运费门槛](书店政策.免运费门槛) - *0* -2. * - *[基础运费](书店政策.基础运费)* - -## 计算应付金额 - -接受`单价`、`数量`、`等级`;输出应付总金额。 - -**小计 = [商品小计](定价.计算商品小计(单价, 数量))** -**折扣 = [当前会员折扣](书店政策.获取折扣(等级))** -**折后价 = [折扣后商品金额](小计 * 折扣)** -**运费 = [应收运费](定价.计算运费(折后价))** -**应付 = [最终应付人民币金额](折后价 + 运费)** -*应付* -``` - -**目标能力标记**:这一示例使用 `类.函数` 静态调用、跨文档自动类索引以及嵌入条件表达式中的知识引用,这些是计划实现的语义。当前实际版本中,一般需要显式 `import` 和实例句柄。其余 `**代码**`、`*返回*`、契约表、分支为现有基础。 - -这里看得最清楚:对读者,整段代码是一个有清晰描述的计算故事;对编译器,括号内是有类型、依赖、来源的调用图;对 AI,复用的不是价格公式的自然语言解释,而是绑定到已有符号的能力。 - -## 6. 结算入口 `apps/checkout.mq.md` - -```markdown ---- -title: 演示结算 -import pricing:knowledge/pricing.mq.md ---- - -# main - -一位金卡用户购买两件单价 60 元的商品。 - -**单价 = 60** -**数量 = 2** -**等级 = "金卡"** - -**应付 = [本次订单应付款](定价.计算应付金额(单价, 数量, 等级))** - -> 打印 内容=`应付` -``` - -预期:`60 × 2 × 0.90 = 108` 元,达到免运费门槛,输出 `108`。这是目标语义下的预期值,而非当前版本的实测输出。 - -**对照(相对现有版本更接近可执行)**:使用 `import`、构造实例,再调用实例方法。下面的最小兼容样例来自仓库 `examples/link-syntax/main.compat.mq.md`: - -```markdown ---- -markup: occlusion -import libai:libai.mq.md ---- - -# main - -**li = > libai.李白** -**year = [李白的出生年份](li.李白的出生年份())** -> print text=`year` -``` - -此兼容片段是仓库实例,不能直接替代上面的定价案例:它用于说明当前版本与目标引用模型之间的差距。 - -## 7. 文档问答 `apps/assistant.mq.md` - -```markdown -# main - -# 云雀书店结算说明 - -普通会员原价结算;金卡会员使用[已登记的金卡折扣](书店政策.金卡折扣)。 - -当前免运费门槛为[已登记的门槛金额](书店政策.免运费门槛)。 - -关于政策出处,参见[原始价格政策](../corpus/pricing-policy.md)。 -``` - -这展示**知识链接与导航链接共存**:前两条必须由编译器解析知识目标,最后一条仍是传统 Markdown 导航。不应把全文正文都作为主动执行入口。UI 可以显示“来源文件/目标类型/验证状态/必要时的值”;若目标未验证,应明确标注。 - -## 8. 表格几何与循环 `apps/batch.mq.md` - -演示一列 List、横表 Map、`@` 行向记录、无序列表循环和条件分支。根据 v2.0 新语义,旧 `[key](collection)` 取元改为 `at(collection,key)`。 - -```markdown ---- -markup: occlusion ---- - -# main - -`会员等级` = - -| 等级 | -|---| -| 普通 | -| 银卡 | -| 金卡 | - -`折扣说明` = - -| 普通 | 银卡 | 金卡 | -|---|---|---| -| 1 | 0.95 | 0.90 | - -`演示订单` = - -| @ | 客户 | 等级 | 单价 | 数量 | -|---|---|---|---|---| -| 1 | 甲 | 金卡 | 60 | 2 | -| 2 | 乙 | 银卡 | 30 | 2 | - -**银卡比例 = [银卡折扣值](at(折扣说明, "银卡"))** - -- [逐个检查会员等级](遍历 会员等级 为 等级) - 1. `等级` == "金卡" - > 打印 内容="识别到金卡会员" - 2. * - > 打印 内容=`等级` -``` - -表格语义:单列→List;两列以上一数据行→Map;首列 `@`→按行组成的 List of Map。此处只演示集合构造、访问与循环,避免假定尚未验证的嵌套函数语义。`遍历` 链接循环是新设计形式,必须通过现有版本的解析器验收后才能标记为已实现。 - -## 9. 编译后的产物应当长什么样 - -下列均是**建议输出示意**,不是现有 CLI 的真实输出: - -```json -{ - "symbol": "knowledge://bookshop/定价/计算应付金额", - "kind": "capability", - "signature": { - "params": ["单价:number", "数量:number", "等级:text"], - "returns": "number:CNY" - }, - "dependencies": [ - "knowledge://bookshop/定价/计算商品小计", - "knowledge://bookshop/书店政策/获取折扣", - "knowledge://bookshop/定价/计算运费" - ], - "effects": ["pure"], - "verification": {"parse": "ok", "resolve": "ok", "contracts": "ok", "evidence": "pending"} -} -``` - -假设用户把政策金卡折扣由 0.90 改为 0.88,正确行为应该是: - -1. `书店政策.金卡折扣` 的实现摘要变化; -2. `书店政策.获取折扣` 与 `定价.计算应付金额` 的传递依赖指纹变化; -3. 所有引用这些知识的文档都能由 `impact` 找到; -4. 如果使用 lock,校验报告“知识目标变更”,而不是静默引用新版; -5. 修改政策的原始来源还需要单独复核,不把源码更新等同于证据更新; -6. Agent 必须先检查适用性和验证状态,不能拿一个未复核的版本装作确定事实。 - -## 10. AI 原生复用:有无语义制品的差别 - -**传统文档 + RAG**: - -```text -用户问“金卡买两件 60 元的商品多少钱?” -→ 检索到价格政策.md -→ LLM 阅读、复述并临时写计算步骤 -→ 得到 108(本次碰巧正确) -→ 下次又重新解释规则,可能遗漏免运费条件 -``` - -**Marqdo 目标路径**: - -```text -用户请求 -→ EKC.find("计算应付金额") // 发现候选,不等于信任 -→ artifact.inspect(定价.计算应付金额) // 得到签名、适用范围、来源 -→ link.resolve(...) // 确定性绑定具体符号 -→ verify(contract, input) // 单价60、数量2、等级金卡 -→ execute(bound_symbol, input) // 执行编译制品,得到108 -→ trace(symbol+digest+input+result) // 可审计记录 -→ AI 用自然语言解释结果 -``` - -AI 不必记住“满百免运费”的公式,也不用每次生成新的结算代码。它需要做的是找准能力、验证条件并引用它。 - -## 11. 演示必须通过的负例 - -| 变更/攻击输入 | 期待结果 | -|---|---| -| 将 `书店政策.金卡折扣` 改名但未迁移引用 | `link.unresolved` | -| 新增第二个同名 `书店政策` | `link.ambiguous` | -| 对 `定价.计算应付金额` 漏传数量 | `link.arg_mismatch` | -| 数量传入 0 | `knowledge.constraint_unmet` | -| 来源 `pricing-policy.md` 删除 | `knowledge.source_missing` | -| 来源内容变化但知识函数不变 | `knowledge.source_changed` | -| 来源规则仍然正确但业务已过期 | 需要过期/适用期检查,不能自动声称 verified | -| 尝试在正文链接里执行网络支付 | `link.effect_forbidden` 或只解析不执行 | -| 标签写“免费”但表达式仍产生费用 | 结构检查可能通过;标签语义审查需报警或人工审核,不得保证静态证明 | -| 类实例方法经 `类.方法` 直接调用 | `link.instance_only` | - -## 12. 为什么这个范式更强 - -1. **人类维护规则**:读的是 Markdown 业务故事、表格与政策,不是必须遍历全仓源码。 -2. **编译器复用行为**:跨文档引用已绑定语义制品,避免重复造轮子。 -3. **错误能被提前拦截**:同名、失效、类型、契约、来源变化有各自诊断。 -4. **审计能回答“依据是什么”**:结果、符号、版本、输入和来源可追踪。 -5. **AI 只负责不确定环节**:意图匹配、适用性判断、结果解释;确定性的计算留给编译制品。 -6. **上下文可以缩短,但不是无条件保证**:目标是让 Agent 读取能力摘要而非每次粘贴全部实现;是否节省 tokens 需要客观实验。 - -**核心竞争力不是 Markdown 链接本身,而是“自然语言描述 → 精确符号绑定 → 可验证语义制品 → 执行与复用”的完整链条。** - -## 13. 语法覆盖与非目标 - -本示例涵盖语法主干,但“全部语法”还包括外联代码围栏、公式 `$$`、浏览器/WASM、原生插件 ABI、量子与线性代数扩展、MCP/Agent、网络和文件 API 等。它们的具体运行依赖扩展与环境,不能当作知识引用所必需的语言核心;统一 IR 应允许这些能力以受效应约束的 Artifact 注册和复用,而不必将每种扩展硬塞入同一个教学案例。 - -建议另建生态回归套件: - -- foreign/LLM/network 函数注册为 EffectSet 的非纯函数; -- 数学公式与表格按返回类型编译为 Artifact; -- 浏览器和 Web 插件导出的能力经符号索引显式引用; -- Agent 的复用接口通过 MLSP 获得固定签名与效果说明。 - -## 14. 原仓库参考资料 - -- <https://github.com/cflmy/marqdo/blob/main/doc/design/link-syntax.md> -- <https://github.com/cflmy/marqdo/blob/main/doc/design/markdown-mapping-v0.3.md> -- <https://github.com/cflmy/marqdo/blob/main/doc/design/objects.md> -- <https://github.com/cflmy/marqdo/blob/main/doc/design/knowledge-layers.md> -- <https://github.com/cflmy/marqdo/blob/main/doc/design/engineering-knowledge.md> -- <https://github.com/cflmy/marqdo/blob/main/examples/link-syntax/main.compat.mq.md> diff --git a/doc/next/Marqdo_Executable_Knowledge_Testing.md b/doc/next/Marqdo_Executable_Knowledge_Testing.md deleted file mode 100755 index e013504..0000000 --- a/doc/next/Marqdo_Executable_Knowledge_Testing.md +++ /dev/null @@ -1,83 +0,0 @@ -# 可执行知识语法:仓库级测试与兼容性规程 - -本文是 `Marqdo_Executable_Knowledge_Development.md` 的验证规程。它约束稳定符号 URI、零参数知识路径、关联函数/实例方法区分及其 CLI 解析进入标准库、扩展库和发布流程后的测试方式。 - -## 覆盖目标 - -新写法只在需要值的位置把零参数路径解释为调用: - -```marqdo -**pi = math.pi** -**year = facts.Person.birth_year** -``` - -旧的 `**pi = > math.pi**` 和 `> math.pi` 继续兼容。对象子函数不读取 `self` / `自` 时是 `associated_function`;读取接收者时是 `instance_method`,不能由 `Type.method` 直接执行。 - -每项语法变更必须同时证明:新写法正确、旧写法未回归、Tree/Bytecode 一致、CLI 静态解析和运行时规则一致,并且标准库与扩展库仍能加载、运行。 - -## 自动化测试矩阵 - -| 层级 | 覆盖内容 | 命令 | 通过条件 | -|---|---|---|---| -| 解析 | 零参路径降级 Call;带参路径不能静默执行 | `cargo test --locked --lib parse::expr` | AST、参数数与诊断稳定 | -| 语义 | ProjectRoot、ModuleId、SymbolId、关联/实例分类、歧义 | `cargo test --locked --lib sema::` | 扫描顺序不影响结果;分类不改变 SymbolId | -| Tree | 标准库裸路径、关联函数、旧写法 | `cargo test --locked --test gold structure_new_path_stdlib structure_ns_associated_function` | stdout 金样一致 | -| Bytecode | 同一正例的后端一致性 | `cargo test --locked --test gold bytecode_new_path_stdlib bytecode_ns_associated_function` | stdout、退出码一致 | -| 负例 | 接收者依赖路径被拒绝 | `cargo test --locked --test gold error_ns_instance_method knowledge_resolve_rejects_instance_path` | 不构造对象、不执行方法 | -| CLI | `inspect` / `resolve` JSON | `cargo test --locked --test gold knowledge_resolve_new_path` | 返回 URI、source、callable;resolve 不执行代码 | -| 标准库 | 英文/中文零参知识 | `cargo test --locked --test gold lib_log_uuid_smoke lib_log_uuid_zh_smoke` | `uuid.v4` 等裸路径可用 | -| 扩展库 | 改写后的扩展调用和插件加载 | `cargo test --locked --test gold ext_quantum_gates_smoke` | `math.pi` 新写法输出不变 | - -## 每次语法改动的执行顺序 - -```bash -source scripts/dev-env.sh -cargo check --locked -cargo test --locked --lib -cargo test --locked --test gold -- --test-threads=1 -cargo test --locked -cargo build --locked -``` - -发布前再做可观察的 CLI/双后端冒烟: - -```bash -target/debug/marqdo knowledge tests/structure/ns --json resolve \ - helpers.Box.birth_year --from tests/structure/ns/associated.mq.md -target/debug/marqdo run tests/structure/new-path-stdlib.mq.md --backend tree -target/debug/marqdo run tests/structure/new-path-stdlib.mq.md --backend bytecode -``` - -完整 gold 会构建部分原生/Go 扩展,必须单线程执行。网络、真实 LLM 与 ignored 实验不属于离线语法门禁,不能以其失败掩盖核心回归。 - -## 标准库与扩展库改写准则 - -仅改写可机械证明等价的值表达式: - -| 原写法 | 新写法 | 前提 | -|---|---|---| -| `**x = > math.pi**` | `**x = math.pi**` | 目标零参数、值位置 | -| `**id = > uuid.v4**` | `**id = uuid.v4**` | 目标零参数、值位置 | -| `**x = > Type.fact**` | `**x = Type.fact**` | 目标为关联函数 | - -禁止自动改写副作用语句、带必填参数函数、实例方法、文本/围栏/URL/导航链接,以及不能同时通过 Tree/Bytecode 的变更。本轮用 `math.pi`(量子扩展夹具)、`数学.圆周率`(中文标准库夹具)和 `uuid.v4`(标准库夹具)作为真实金样。 - -## CLI 合约 - -```text -marqdo knowledge PATH --json inspect SYMBOL -marqdo knowledge PATH --json resolve REFERENCE --from CALLER.mq.md -``` - -`resolve` 只绑定、不执行。它依据 `--from` 的 frontmatter import 解析第一个路径段,不会在项目中按名字猜测目标。关联函数返回 `resolution: "symbol"`;实例方法返回 `resolution: "instance_only"` 并以退出码 1 拒绝直接路径调用。 - -## 发布门槛 - -1. `git diff --check` 无错误; -2. Rust 核心、gold、完整 `cargo test --locked` 通过; -3. 每个新正例有 Tree、Bytecode 和 CLI(适用时)覆盖; -4. 每个语义拒绝路径有稳定负例; -5. 标准库/扩展库改写保留原 stdout 金样; -6. 不提交 `.marqdo/`、插件构建物或本地凭据。 - -失败报告必须记录命令、后端、夹具、stdout/stderr、插件/网络依赖及与旧写法的差异。 diff --git a/doc/releases/ext-2.8.1.md b/doc/releases/ext-2.8.1.md deleted file mode 100644 index 2f86a4b..0000000 --- a/doc/releases/ext-2.8.1.md +++ /dev/null @@ -1,64 +0,0 @@ -# Ext pack v2.8.1 发布说明 · Release Notes(AI native flow) - -## 1. 一句话 - -独立拓展包 **2.8.1**(CLI 仍为 **2.8.0**):`ext/ai` 交付插件侧持久化工作流——显式 -`open/next/commit/cancel`、有界模型选择、作用域上下文、只读失败恢复,以及 -`inspect/list` 与可隔离的 `resume_dir`。Windows `extension-release` 使用原生 -`path.join` 根路径与 `C:\Windows\System32\tar.exe`(bsdtar)打包。不改解释器栈 -挂起语义,也不宣称外部写的 exactly-once。 - -Independent extension pack **2.8.1** (CLI remains **2.8.0**): `ext/ai` ships a -plugin-only durable workflow — explicit `open/next/commit/cancel`, bounded model -choice, scoped context packing, failed-only read-only recovery, plus -`inspect/list` and isolatable `resume_dir`. Windows `extension-release` packs -with native `path.join` roots and `C:\Windows\System32\tar.exe` (bsdtar). No -interpreter-stack suspension and no exactly-once external-write claim. - -## 2. 亮点(Highlights) - -| | | -|---|---| -| 持久步骤机 | `plugins/agent` `workflow`:`open/next/commit/cancel/retry_*`,CheckpointV2,逐步提交边界 | -| 作者面 | `ext/ai/workflow` · `flow` · `context` · `recovery`;`tick` 单步执行,等待输入不阻塞解释器线程 | -| 选择解析 | 精确 / 编号 / 标签 / 短中英句 / JSON 信封;歧义与未知路径失败关闭 | -| 作用域上下文 | Markdown 感知的 file/class/function 摘录;歧义拒绝;不把整库 import 塞进提示 | -| 安全并行恢复 | 保留成功兄弟结果;仅重试已分类为只读的失败子任务;写/未知效应不自动派发 | -| 可观测性 | `inspect`/`list` 只读进度;测试与调用方可传入 host-relative `resume_dir` | -| Windows CI | engineering root 用 `path.join`;ZIP 用 `System32\tar.exe --format=zip` | - -设计契约:[native-agent-flow-v3.md](../design/native-agent-flow-v3.md)。 - -## 3. 安装(Install) - -```bash -marqdo ext add agent # CDN / Releases → 2.8.1 -# 或:MARQDO_EXT_VERSION=2.8.1 marqdo ext add agent -marqdo ext add llm -``` - -产物:`marqdo-2.8.1-ext.zip` 与双平台 native ZIP(含 agent / llm 等既有原生库)。 - -## 4. 验证(Validation) - -```bash -cargo test -p marqdo_plugin_agent --locked -cargo run --locked -- check ext/ai/flow.mq.md -cargo run --locked -- check ext/ai/context.mq.md -cargo run --locked -- check ext/ai/recovery.mq.md -cargo run --locked -- check ext/ai/workflow.mq.md -cargo run --locked -- run tests/ext/ai-native-flow.mq.md -cargo run --locked -- run tests/ext/ai-native-workflow.mq.md -``` - -CI:`.github/workflows/native-ai-flow.yml` 与 `extension-release.yml`(`ext-v2.8.1`)。 - -## 5. 已知限制(Known limitations) - -- 输入闸门保存的是**步骤边界**,不是任意字节码解释器帧;回复后须显式进入下一 Marqdo 函数。 -- 作用域选择依赖 Markdown 标题约定,不是编译器已解析的 AST 符号表。 -- 调用方提供的 principal/session/source revision 须由已认证宿主证明,不能来自模型文本。 -- 并行复用 `subtask.run_many`;跨进程子任务租约与已在跑外部进程的取消传播仍待专项注入验证。 -- 实时大模型与目标 1B 本地模型评测仍开放;写效应自动重试仍被拒绝,直至 EffectLedger 对账完成。 - -**核心表面 Δ**:无增删——19 个核心构造不变;本包为 Extension / Agent Runtime。 diff --git a/doc/releases/v2.7.0.md b/doc/releases/v2.7.0.md deleted file mode 100755 index eb3e4f4..0000000 --- a/doc/releases/v2.7.0.md +++ /dev/null @@ -1,48 +0,0 @@ -# Marqdo 2.7.0 - -本次 full 发布把源码手册落到实际开发与用户站点:文件操作、开发检查、构建与发版阶段可通过 marqdo call 执行;站点以递归组件、普通 Markdown 和明确的原生资源表达页面与行为。 - -This full release makes executable source handbooks practical for development and user sites. Native file tools and callable development/release tasks replace generated orchestration programs. Recursive View components preserve ordinary Markdown content and explicit runtime resources. - -## 亮点 / Highlights - -- 开发与发版 SKILL 路由到可执行 .mq.md 手册;文件读取、审阅、摘要校验和写入使用固有标准库。工程插件承担有界进程、私密认证、压缩格式和实际编译器检查边界,流程不依赖 Python 编排。 -- Literal JSON file/stdin CLI arguments preserve quotes, newlines and dollar-prefixed text. --require-ok makes a failed Result stop external automation; saved call sessions retain literal argument semantics. -- 中英文网络站点与完整用户站点改为递归 View 布局、Markdown 内容、当前数据查询、表单、真实会话导航与鉴权资源。原有配色、字体、布局、文章详情和管理功能保留。 -- Pure document_head resources carry SEO and resource links into the actual head. Request-time query/form/navigation resources preserve the existing five-column View schema, source context and explicit effect boundaries. Prepared-app inspection follows the real registrar without executing handlers. -- 原生 SQLite 初始化按实际站点授权根定位,保留已有业务记录;嵌套 Document 与 Endpoint 使用一致的站点根。修复表单校验重试中的 CSRF、成功跳转以及嵌套片段选择与路由检查。 -- The browser bridge supports typed nested list/control records. The maintained browser-app demonstrates duplicate-safe identities, literal text, truthful storage/network feedback, real history and local WebSocket echo with no authored business JavaScript. -- 移除与语言仓库无关的暗恋工程及过时的独立浏览器演示;底层 WASM 冒烟夹具与公共回归保留。维护入口收敛到实际可运行的工程。 - -## 核心表面与兼容边界 / Core surface and boundaries - -核心构造仍为 19 个,没有新增 Markdown 标记。改动集中在已有标记解析、CLI 参数传送、Runtime / Document 资源及工程工具;原生插件仍具有调用用户的操作系统权限,--fs-root 不把外部进程变成沙箱。显式 raw HTML 兼容出口不等同于不可信内容清理。编译检查与叙述比例检查不能单独证明运行或视觉正确。 - -The core surface remains 19 constructs. Native-only filesystem, process and authenticated service capabilities do not become browser WASM capabilities. Atomic file replacement is not a multi-file transaction, and digest preflight is not a kernel compare-and-swap. Deployment credentials remain in private stores. - -## 下载 / Downloads - -| 产物 / Asset | 内容 / Contents | -|---|---| -| marqdo-2.7.0-x86_64-pc-windows-msvc.exe | Windows CLI,内嵌标准库 / CLI with embedded standard library | -| marqdo-2.7.0-x86_64-pc-windows-msvc.zip | Windows CLI、标准库、拓展源码与原生插件 / complete Windows bundle | -| marqdo-2.7.0-x86_64-unknown-linux-gnu.zip | Linux CLI、标准库、拓展源码与原生插件 / complete Linux bundle | -| marqdo-2.7.0-stdlib.zip | 可读标准库源码 / readable standard-library sources | -| marqdo-2.7.0-ext.zip | 官方拓展库源码 / official extension sources | -| marqdo-2.7.0-native-x86_64-pc-windows-msvc.zip | Windows web、agent、quantum、linalg、llm、engineering 插件 | -| marqdo-2.7.0-native-x86_64-unknown-linux-gnu.zip | Linux web、agent、quantum、linalg、llm、engineering 插件 | -| marqdo-2.7.0-source.zip | 本标签的源码快照 / tagged source snapshot | -| marqdo-2.7.0.vsix | VS Code / Cursor 扩展,源码独立分支 / separate editor-source branch | -| marqdo-2.7.0-public.zip | 由实际 .mq.md 导出的静态用户站点 / exported public documentation | - -## 安装与使用 / Installation and use - -下载对应平台的完整 ZIP,解压后使用其中的 CLI 与 lib/ext。已有 CLI 可通过 marqdo ext add 安装官方拓展;具体调用从标准库单文件或拓展库 index.mq.md 的参数与返回表开始。Linux 用户也可使用项目现有 Ubuntu noble PPA 安装路径;实际 apt 可用性以发布验证结果为准。 - -Download and unpack the matching platform bundle. Start from each standard-library source or extension index.mq.md. Development tools live in skills/marqdo-dev/index.mq.md; release tasks live in skills/marqdo-release/index.mq.md. A callable task preserves actual failures and grants only its declared effects. See README for the maintained install routes. - -## 验证 / Validation - -本地全量 Rust 验收为 1031 通过、0 失败、2 个原有模型实验忽略项;Go 网络插件完整测试通过。清理后重跑的 21 项 CLI/发版/WASM 测试以及 7 项真实浏览器用例通过,实际用户文档成功导出 102 页。源码审查单独检查标题下契约与超过一半的叙述;普通测试、人工夹具和历史兼容样例保留既有用途。 - -Windows and Linux release builds run in CI for this exact source tag. Final release verification separately checks those jobs, all artifact contents and hashes, GitHub/R2 byte parity and VERSION ordering, and Ubuntu source/build/apt publication. A local Linux test is not evidence of Windows execution or completed package publication. Public documentation export is packaged here; gh-pages deployment is separate. diff --git a/doc/releases/v2.7.1.md b/doc/releases/v2.7.1.md deleted file mode 100755 index 5165175..0000000 --- a/doc/releases/v2.7.1.md +++ /dev/null @@ -1,41 +0,0 @@ -# Marqdo 2.7.1 - -本次为 CLI 修复发布,重点修复 View 中“实际逻辑”展开后立即折叠的问题,并完成描述链接的细节排版。官方拓展库继续使用 2.7.0,不发布新的独立拓展包,也不移动 CDN VERSION。 - -This CLI release fixes implementation disclosures that collapsed immediately after opening and improves typed details for descriptive links. Official extension packs remain at 2.7.0; no independent extension assets or CDN VERSION update are included. - -## 修复与改进 / Fixes and improvements - -- View 布局只记录自己的自动开合,不再覆盖用户选择;鼠标、键盘、窗口变化、嵌套原始写法及同一文档的运行结果刷新均保留手动状态。 -- Disclosure choices survive layout, resize and live DOM replacement. Layout-generated toggle events do not become user intent or trigger another reset loop. -- 函数调用按函数名、命名参数和嵌套调用排版;本页函数可以定位到定义。链接在正文及侧注中保留跳转,相对 mq.md 链接适配实时和离线页面。 -- Lists, records and prose have typed presentation with optional original source. Empty payloads remain explicit placeholders; reading details never runs payloads. -- 手机详情按整行排列,展开卡片不再撑高相邻卡片。新增可执行阅读示例 examples/view-details.mq.md。 - -## 核心表面与范围 / Core surface and scope - -核心构造仍为 19 个,没有新增语法、标准库接口或插件 ABI。变更属于 CLI 内嵌 View 前端、只读渲染与发布产物选择。浏览器不会因查看详情而执行实现或自动抓取链接预览。 - -The core surface stays at 19 constructs. Standard-library and extension APIs are unchanged. CLI and WASM manifest versions are 2.7.1; extension source packs stay 2.7.0. The matching VS Code package is built from its separate source branch. This release does not deploy gh-pages. - -## 下载与安装 / Downloads and installation - -| 产物 / Asset | 内容 / Contents | -|---|---| -| marqdo-2.7.1-x86_64-pc-windows-msvc.exe | Windows CLI,内嵌标准库 / CLI with embedded standard library | -| marqdo-2.7.1-x86_64-pc-windows-msvc.zip | Windows CLI 与配套库及原生插件 / complete Windows bundle | -| marqdo-2.7.1-x86_64-unknown-linux-gnu.zip | Linux CLI 与配套库及原生插件 / complete Linux bundle | -| marqdo-2.7.1-stdlib.zip | 标准库源码,API 未变 / standard-library sources with unchanged APIs | -| marqdo-2.7.1-source.zip | 本标签源码 / tagged source snapshot | -| marqdo-2.7.1.vsix | 独立编辑器分支构建 / editor extension from its separate branch | -| marqdo-2.7.1-public.zip | 使用修复后的 View 导出的用户文档 / public docs exported with the fixed View | - -下载并解压对应平台 ZIP,使用其中的 CLI;独立 Windows EXE 内嵌标准库。Ubuntu noble 用户可使用 ppa:cflmy/marqdo 安装或升级,实际包可用性由发版最终验证单独检查。旧的静态导出需用新 CLI 重新执行 marqdo view output,才能包含修复后的前端。 - -Unpack the matching platform bundle, or use the standalone Windows executable. The maintained Ubuntu noble installation route is ppa:cflmy/marqdo. Regenerate older static exports with marqdo view output to include the fixed reader script. A CLI-only release keeps the existing official extension installation version. - -## 验证范围 / Validation - -本地全量 Rust 验收为 1039 通过、0 失败、2 个原有忽略项;用户文档成功导出 102 页。本地验收覆盖真实详情点击、键盘开合、原始写法、反复布局、窗口变化、实时 DOM 替换,以及静态/实时页面、桌面/手机和无脚本阅读。另验证只读导出不会触发逻辑、现有运行标注与连线、文档间跳转和示例函数调用。 - -Windows and Linux builds, exact-commit Release/EK jobs, archive contents and hashes, and Ubuntu source/build/apt availability are independent final release gates. Local browser tests do not establish Windows build success, and upload acceptance does not establish apt availability. diff --git a/doc/releases/v2.8.0.md b/doc/releases/v2.8.0.md deleted file mode 100644 index ad17fc7..0000000 --- a/doc/releases/v2.8.0.md +++ /dev/null @@ -1,51 +0,0 @@ -# v2.8.0 发布说明 · Release Notes(prove) - -## 1. 一句话 - -`marqdo prove` 正式发布:知识文件的定理表 → Lean 4 证明 → 自动判定。 -没有 Lean 工具链也能跑(离线符号执行,诚实降级);有 Lean 时全链路证明, -假定理给出路径见证反例,离线与 Lean 分歧时显式报错永不落绿。 - -`marqdo prove` ships: theorem tables in knowledge files compile to Lean 4 -and are judged automatically. It runs without a Lean toolchain (offline -symbolic execution, honest degradation); with Lean, fake theorems get -counterexamples and any offline/Lean divergence fails loudly. - -## 2. 亮点(Highlights) - -| | | -|---|---| -| 定理表 | `| 定理 | 结论 | 前提 | 策略 |`,结论文法:`结果.ok`、`包含(轨迹,…)`、`长度(轨迹)`、参数比较,且/或/非组合 | -| 六段管线 | 装载 → 降级 → 定型 → 生成(Lean 4.35)→ 判定(离线先行 + Lean 复核)→ 证书 | -| 离线判定 | F1–F5 片段符号执行:路径枚举、轨迹形状、构造器结构、自由原子二分、区间字面重述与反例见证(毫秒级) | -| 单调性护栏 | 离线 `checked` 但 Lean 证不出(或反例被证出)→ `error[proof.divergence]` 退 1——绝不让离线判定比 Lean 更乐观 | -| 诚实状态 | `proved > checked > unverified > rejected > unproved > error`;`checked ≠ proved`;无 Lean 时状态如实降级(咨询性退 0),`--require-lean` CI 严格模式退 2 | -| 反例 | 假定理给出区间端点见证(如 `金额 = 10001`)并指回定理表行号 | -| 证书缓存 | 复合键(源码⊕计划⊕库⊕Lean 版本⊕CLI 版本),`.marqdo/prove/`,命中跳过判定;`--no-cache` 绕过 | -| 目录模式 | `prove --all 目录`(`--max-files` 默认 200):逐文件出证,整体取最差,聚合 JSON | -| 差分一致性 | T4 语料:解释器求值 == Lean 语义(算术/中文标识符/分支/拼接/i64 边界/结构字段) | -| 工具链 | `--lean` 显式指定 → `MARQDO_PROOF_LEAN` → PATH;内嵌判定库按内容哈希缓存构建,无需 lake/elan | - -## 3. 使用(Usage) - -```bash -marqdo prove 审批.mq.md --json # 判定 + 单个 JSON 报告 -marqdo prove emit 审批.mq.md # 只生成 Lean 模块 + plan.json -marqdo prove audit 审批.mq.md # 只审查可证子集(不写盘) -marqdo prove --all skills/ --json # 目录聚合(整体取最差) -marqdo prove clean # 清空 .marqdo/prove -``` - -测试:`cargo test --test prove`(无 Lean 全绿)· -`MARQDO_PROOF_LEAN=<lean> cargo test --test prove_lean --test prove_corpus --test conformance`(有 Lean 全链路 + 40 夹具单调性 + T4 一致性)。 - -详见 [design/prove-cli.md](../design/prove-cli.md)(命令面、可证子集与判定管线)与 -[skill-proof-theory.md](../verification/skill-proof-theory.md)(库形式化说明)。 - -## 4. 已知限制(Known limitations) - -- `foreach` 维持 `proof.foreach_pending`(可证子集无循环;fold 编码 → 2.9)。 -- 跨模块调用 = 不透明操作;assume-guarantee 后置条件复用 → 2.9(依赖假设表 T3)。 -- 除零/模零:解释器为运行时错误,判定库模型返回 `.int 0`(已记录偏差)。 -- 分支条件暂不支持字段访问(解析器文法限制;prove 侧已就绪,放开即生效)。 -- i64 溢出:解释器报运行时错误;判定库 `Int` 无界(语料只测界内值)。 diff --git a/doc/releases/v2.9.0.md b/doc/releases/v2.9.0.md deleted file mode 100644 index 5a1ae7f..0000000 --- a/doc/releases/v2.9.0.md +++ /dev/null @@ -1,51 +0,0 @@ -# Marqdo v2.9.0 · Full Release / 正式完整版本 - -## 核心更新 · Highlights - -Marqdo 2.9.0 将 Markdown 原生可执行知识库推进为 **可验证知识编译器(Verified Knowledge Compiler)**。这不是全语言自动证明工具:Lean 4 仅证明明确支持的逻辑模型,系统继续保存来源、信任边界与失效原因。 - -- **统一模块契约**:`knowledge compose` 支持静态纯函数的形参、整数表达式、连续赋值、穷尽分支、多次函数调用和多级模块调用 DAG。 -- **独立 Lean 模块证明**:每个受支持函数由源码生成可检查模块;调用方导入被调方定理,而不是将定理声明自动当成公理。 -- **知识锚点**:带标记步骤和定理声明具有稳定身份;`[]()` 用于可寻址引用,绝不自动赋予执行权。 -- **可信证据**:`model_proved`、`proved`、`tested`、`assumed`、`unknown`、`refuted`、`stale` 严格区分;证明收据绑定源码与依赖闭包,支持失效检测和独立重放。 -- **兼容性**:旧版 `marqdo prove`、`marqdo call`、知识视图和旧式简单组合证书继续兼容,Rust 与 Lean 差分测试保护语义边界。 - -**EN:** Marqdo 2.9.0 introduces a Verified Knowledge Compiler for native Markdown knowledge artifacts, stable anchors, source-derived bounded assume/guarantee composition, and independently replayable Lean 4 certificates. The implementation **does not** claim universal program correctness: supported Lean `Int` theorems are labeled `model_proved` until a runtime semantic correspondence is established. - -## 可信边界 · Verification boundaries - -Lean 自动组合仅适用于源码可精确翻译的无副作用、静态纯整数模型片段;有界整数溢出、动态 `number` / `Formula`、插件效应、未知异常、循环和递归不会自动升级为已证明。前置条件未证明、源码漂移、证书篡改、Lean 不可用或超出支持范围时,必须拒绝出证或明确返回未验证状态。 - -Formal logic proves **properties of the declared model**, not empirical facts or the entire runtime. External API responses, quantum hardware measurements and agent behavior require explicit experiment/test/provenance evidence. See [design decision](../design/verified-knowledge-compiler-boundaries.md). - -## 使用 · Usage - -```sh -marqdo knowledge . -marqdo knowledge compose --strict --json . -marqdo knowledge proof-deps --verify --json . -marqdo knowledge replay <path/to/composition-certificate.json> --json . -``` - -A `model_proved` certificate is **not** an unconditional authorization to call plugins or execute side effects. - -## 完整发行产物 · Full distribution - -The `v2.9.0` full packaging workflow produces: -- Windows x86_64 native CLI (standalone EXE and bundled ZIP); -- Linux x86_64 CLI+libraries bundle; -- standard library ZIP, source ZIP and static user-site ZIP; -- editor `marqdo-2.9.0.vsix` from the independent editor branch; -- both Windows and Linux official native plugin packs, plus the versioned extension source pack when `ext/VERSION` matches `2.9.0`. - -**Release completion is determined by actual CI artifacts and publication evidence, not by this note.** In addition to GitHub assets the repository's [release handbook](../../skills/marqdo-release/index.mq.md) requires CDN/R2 byte parity and Ubuntu PPA publication/apt verification. Missing credentials, failed cross-platform builds or unverified publication channels must be reported as incomplete; never invent hashes or success. - -## 质量验收 · Quality gates - -- `modular-proof-smoke` — actual Lean kernel-checkable intermodule source contracts, negative/stale replay tests. -- `knowledge-proof-full-gate` — knowledge, semantic-IR, proof corpus and interpreter/Lean differential tests. -- `executable-knowledge` — backward compatibility and knowledge execution tests. -- `Release` — verify both platform assets were built from the exact immutable tag. -- `release-v2.9` gate — verify metadata, build/test on main and create the immutable tag only when checks pass. - -Version 2.9.0 is a **scoped Verified Knowledge Compiler**, not a theorem that every program or scientific experiment is automatically correct. diff --git a/doc/releases/v2.9.1.md b/doc/releases/v2.9.1.md deleted file mode 100644 index b9550ad..0000000 --- a/doc/releases/v2.9.1.md +++ /dev/null @@ -1,33 +0,0 @@ -# Marqdo v2.9.1 · Library Feature-Gate Fix / 库可选特性修复 - -## 核心更新 · Highlights - -Marqdo 2.9.1 修复 2.9.0 引入的库构建回归:`sema::ir` 在输出 `proof-index.json` 与 `proof-obligations.json` 时无条件使用 `knowledge` 模块,而该模块此前只在 `cli` 特性下编译,导致以 `default-features = false` 依赖本库的下游工程出现 `E0433: could not find knowledge in the crate root`。 - -**EN:** Marqdo 2.9.1 fixes a library-build regression introduced in 2.9.0. `sema::ir` unconditionally emits `proof-index.json` and `proof-obligations.json` through the `knowledge` module, but that module was gated on the `cli` feature, so downstream crates depending on the library with `default-features = false` failed with `E0433: could not find knowledge in the crate root`. - -- `knowledge` 现在是核心编译器的一部分,不再由 `cli` 特性门控;CLI 二进制仍由 `required-features = ["cli"]` 约束。 -- 新增 `feature-matrix` CI:分别用无默认特性、仅 `cli`、默认特性检查库构建,防止特性门控再次回归。 -- 没有运行时语义、文稿格式、插件 ABI(v2)或证明证书格式的变化。 - -## 兼容性 · Compatibility - -- 2.9.0 的 `.mq.md` 文稿、原生插件(ABI v2)和知识证明证书保持兼容,无需迁移。 -- 下游库可继续使用 `default-features = false`;2.9.0 期间为绕过该回归而启用的 `cli` 特性可以撤销。 -- 不可变标签 `v2.9.0` 保持不变,本次是同一主线的补丁版本。 - -## 验证 · Verification - -- `cargo check --locked --lib --no-default-features`、`--no-default-features --features cli` 与默认特性三种配置均通过。 -- `cargo test --locked` 全量通过(Linux x86_64 本地环境)。 -- 下游验证:qdagent 原生插件恢复 `default-features = false` 后重新编译通过,`cargo test` 17 项通过。 -- 限制:Windows 与 Linux 发布产物由标签触发的 Release 流水线构建;本地验证不代表其他平台已通过,最终以实际流水线结果和资产校验为准。 - -## 完整发行产物 · Full distribution - -The `v2.9.1` full packaging workflow produces: -- Windows x86_64 native CLI (standalone EXE and bundled ZIP); -- Linux x86_64 CLI+libraries bundle; -- standard library ZIP, source ZIP and static user-site ZIP; -- editor `marqdo-2.9.1.vsix` from the independent editor branch; -- both Windows and Linux official native plugin packs, plus the versioned extension source pack when `ext/VERSION` matches `2.9.1`. diff --git a/doc/research/agent-capabilities-2026-10-27.md b/doc/research/agent-capabilities-2026-10-27.md deleted file mode 100755 index 144647f..0000000 --- a/doc/research/agent-capabilities-2026-10-27.md +++ /dev/null @@ -1,102 +0,0 @@ -# 智能体能力调研与求道差距复核(2026-10-27) - -| 项目 | 说明 | -|---|---| -| 状态 | Research / 设计输入;不是功能交付声明 | -| 调研日期 | 2026-10-27,Asia/Shanghai | -| 源码基线 | Marqdo `16f26d7d60ce9fbc62feb0e8e83f93951f7b53fe`;qdagent `68b757e02ebfb64833b5262b0c8a683512581e8b` | -| 框架设计 | [Agent 恢复、工具与资源协议](../design/agent-reliability-tools-resources-2026-10-27.md) | -| 产品设计 | [求道智能体能力与预览体验](../../../qdagent/doc/design/agent-capabilities-and-preview-2026-10-27.md)(同级仓库) | - -## 1. 方法与结论边界 - -先以 `git pull --ff-only` 同步两仓,再追踪真实调用链与前端入口;对比公开官方文档,不以营销介绍、工具数量或旧设计中的 done 标签代替实现证据。本次是静态源码复核与官方资料研究,没有启动部署实例,没有调用付费模型,没有进行竞品账号实测。因此,下表“源码确认”仅代表代码路径可见,“设计判断”与“待实测”不能写成已复现或已交付。 - -主流能力的共同方向是:可恢复的执行、结构化工具与资源、按需上下文、可追溯结果、独立产物展示。不同产品和模型支持范围不同;这里不是市场占有率调查,也不声称所有智能体都具备全部能力。求道应保留文档原生、EKC、验证后沉淀的定位,吸收机制,不引入第二套 Agent Runtime。 - -## 2. 官方资料与可借鉴机制 - -以下页面均在调研日实际打开;MCP 特意引用固定 `2025-06-18` 版本,作为兼容基线,不宣称它是最新协议。厂商专有能力必须探测,不能因为端点兼容 `/v1` 就认为全部可用。 - -| 编号 | 官方来源 | 已核实内容 | 对求道的设计启示 | -|---|---|---|---| -| S01 | [OpenAI Agents:集成与可观测性](https://developers.openai.com/api/docs/guides/agents/integrations-observability) | MCP 接入与运行、模型、工具等 tracing | 统一 call/attempt/span 关联;产品只显示阶段摘要,详细事件可展开 | -| S02 | [OpenAI:Memory 与 Compaction](https://developers.openai.com/cookbook/examples/agents_sdk/building_reliable_agents_memory_compaction) | 区分当前任务上下文压缩、跨运行记忆、可审阅产物 | 历史不要无限拼接;完整产物不等于聊天全文 | -| S03 | [LangGraph Persistence](https://docs.langchain.com/oss/python/langgraph/persistence) | checkpointer 保存 thread 状态,store 支撑跨 thread 数据 | 恢复执行状态和用户长期知识是两种生命周期 | -| S04 | [LangGraph Interrupts](https://docs.langchain.com/oss/python/langgraph/interrupts) | 恢复时节点代码可能重新执行 | 检查点不能单独保证写操作只执行一次,必须记录效应与幂等键 | -| S05 | [Claude Tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) | 工具定义按需进入模型上下文 | 工具多不代表每轮注入全部定义;检索后再校验权限 | -| S06 | [Claude Programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) | 在执行环境中编排工具、筛选结果 | 大批量只读处理可减少模型往返;后置于基础工具可靠性 | -| S07 | [Deep Agents overview](https://docs.langchain.com/oss/python/deepagents/overview) | 文件系统、上下文管理、子任务与可选规划能力 | 规划应按任务启用;简单问答不强制复杂工作流 | -| S08 | [Gemini Tools](https://ai.google.dev/gemini-api/docs/tools) | 检索、URL、文件搜索、代码执行等工具面 | 覆盖“找资料—读内容—计算—形成产物”,不能只有工程检索 | -| S09 | [Gemini File search](https://ai.google.dev/gemini-api/docs/file-search) | 文件检索与引用信息 | 命中要能定位原文,检索摘要不能代替源文件版本 | -| S10 | [MCP Tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools) | schema、结构化结果、资源链接;annotations 有信任边界 | 工具结果包含短摘要和资源引用;注解不是权限凭证 | -| S11 | [MCP Resources](https://modelcontextprotocol.io/specification/2025-06-18/server/resources) | URI 资源、读取和应用决定的上下文注入 | “预览”“加入上下文”“执行”必须是独立动作 | -| S12 | [Claude Artifacts](https://support.claude.com/en/articles/17153992-what-are-artifacts-and-how-do-i-use-them) | 产物在会话旁独立打开,可继续查看与编辑 | 右栏应承载正文;不应只提供离开当前会话的入口 | -| S13 | [Mozilla PDF.js](https://mozilla.github.io/pdf.js/) | Web PDF 解析和渲染 | PDF 视觉预览和 OCR/知识提取分开交付 | -| S14 | [DOMPurify 官方仓库](https://github.com/cure53/DOMPurify) | DOM 清洗、标签/属性配置;插入前清洗 | 替换前端正则“清洗器”,配合同源资源代理和 CSP | - -上述设计启示是本次推导,相关性能收益、成本下降比例不照搬厂商基准。工程路线不绑定某个最新模型或套餐。 - -## 3. 源码事实清单 - -下列 qdagent 路径相对该仓库;Marqdo 路径相对本仓库。基线 commit 已固定,后续实现需按符号再定位。 - -| 编号 | 当前实现证据 | 结论与限制 | -|---|---|---| -| F01 | qdagent `agent/qdagent.mq.md::契约提示`、`ask` | ASK 和 BUILD 都要求完整六段式 `.mq.md`,包含 main、验证和元数据;普通回答变长有明确结构性诱因。不能断言这是唯一原因 | -| F02 | 同文件 `ask` 的门禁修复分支 | `r2` 送入第二次门禁后,成功分支仍 `result = raw`;可能展示修复前内容,设计必须绑定同一 accepted candidate | -| F03 | 同文件 `ask` 返回表 | `gated_error` 路径仍可能保留 `status=ok` 且返回 `ok=True`;必须明确业务失败与输送成功的不同含义 | -| F04 | 同文件 `eng_tools` | 默认白名单是 `tool_find/reuse/bind/verify/summarize` 五个工程工具;不是整个框架只有五个工具,也不代表已覆盖网页、笔记、文件编辑 | -| F05 | `ext/ai/agent.mq.md` | 有 step/plan/run、READ、CALL、观察压缩、工作簿和恢复接口;应扩展这些原语,不另造循环 | -| F06 | `plugins/agent/src/resume.rs::resume_save` | JSON 直接 `fs::write`;现有恢复接口不等于具备原子检查点、工具效应对账及任意步骤自动续跑 | -| F07 | `src/runtime/`、`src/workbench/capabilities.rs` | 已有隔离执行、取消、事件回放与读通道;这一轮是 Agent 级恢复补足,不重新规划整个进程池 | -| F08 | qdagent `session-store.ts::resumeTurn` | 终态 completed/failed/interrupted 直接返回;已有事件续订,但终态消息补齐与中断后的执行恢复需分别处理 | -| F09 | qdagent `DesktopFrame.tsx::RightNotesPanel` | 实际只有“查看全部笔记”导航至 `/notes`,没有侧栏笔记正文 | -| F10 | 同文件 `RightFilesPanel`、`WorkspacePage.tsx::openFile` | 文件点击已调 `openTarget`;右栏取首个 workspace,根目录最多 40 个非目录项。不能笼统写“所有按钮都跳转” | -| F11 | `DesktopFrame.tsx` 的 reader/rightbar 条件 | `DocumentReader` 与右侧 tab 容器互斥,且使用两套开关/宽度状态;不是统一的资源浏览面板 | -| F12 | qdagent `NotesPage.tsx` detail | 剥离 frontmatter 后以 `whiteSpace: pre-wrap` 显示文本;没有 Markdown/Marqdo 正文结构渲染 | -| F13 | qdagent `DocumentReader.tsx` | 已有 DocumentView、引用版本传递、请求代数防迟到覆盖;`profile_item` target 未进入读取分支,格式不是通用资源分派 | -| F14 | 同文件 `sanitizeHtmlFragment` | 主要靠正则移除 script/事件/javascript URL;不能当作完整 HTML 白名单安全边界。未在本次做漏洞利用实验 | -| F15 | `src/workbench/document_view.rs` | 有只读文档视图,注释与实现明确避开执行路径;已解析语义应继续复用 | -| F16 | `src/workbench/capabilities.rs` | text/markdown 提取可用,pdf/docx/ocr 标 unavailable;提取能力与浏览器 PDF 预览能力须分别探测 | -| F17 | qdagent `lib/web_search.mq.md` | 既有网页搜索桥使用 legacy 脚本和固定 `last_web_search.json`;存在并发覆盖设计风险,不能直接作为新工具通道 | -| F18 | `plugins/agent/src/mcp_client.rs` | 已有 stdio connect/list/call/close;不能把本轮描述为“从零添加 MCP”,远程连接和资源能力需另验 | -| F19 | qdagent `compose_messages` / `ask` | 对话按角色标记拼成字符串注入 standing;会话语义、上下文预算和外部内容信任层级仍需强化 | -| F20 | qdagent `lib/workbench.mq.md::documents_read` | 临时文件名以秒和环境 RANDOM 构造,RANDOM 缺失又退到秒;设计仍需真正唯一临时文件。workspace 缺省 `.` 不应作为新授权资源接口规则 | - -这些是本轮优先级依据。10-26 release notes 所列修复作为已有基础保留,但“Implemented(本仓)”不能替代浏览器、真实 HTTP、进程中断与模型输出的联合验收。 - -## 4. 能力覆盖与差距优先级 - -| 能力 | 当前基础 | 本轮目标 | 优先级 / 归属 | -|---|---|---|---| -| 自动纠错 | 一次文档门禁修复、plan patch | 分类错误、有限修复、正确结果替换、可恢复失败 | P0 / 两仓 | -| 执行恢复 | 任务隔离、取消、事件回放、JSON checkpoint | 传输续订与执行续跑分离;效应对账 | P0 / Marqdo 原语,qdagent UX | -| 回答长度 | 六段式文档、完整历史 | 直接回答、摘要+产物、显式详述三种表达 | P0 / qdagent 策略,Marqdo 输出通道 | -| 资源阅读 | DocumentView / Locator | 笔记、工作文件、引用、产物统一入口 | P0 / 两仓 | -| 侧栏预览 | 两套状态与导航入口 | 单一右栏,点击即预览,聊天不中断 | P0 / qdagent | -| 工具使用 | 五工具默认白名单、MCP/库原语 | schema 注册、按需发现、资源读取/搜索/写入/验证 | P1 / 两仓 | -| 联网研究 | legacy 搜索脚本 | search+fetch、来源时间、限量正文、可定位引用 | P1 / 两仓 | -| 上下文与记忆 | EFI pack、profile、history | 分层上下文、预算、可编辑记忆、资源 pin | P1 / 两仓 | -| 多格式 | 文档视图、文本提取 | text/md/mq/code/json/csv/image;PDF 后续 | P0→P1 / 两仓 | -| 长任务与计划 | plan 工作簿 | 里程碑、预算、暂停/继续、产物进度 | P1 / 两仓 | -| 多智能体与浏览器 | 不作为当前完成前提 | 有界委派、隔离执行、受控浏览器工具 | P2 / 框架主导 | -| 可观测评测 | usage、事件与既有测试 | 工具/恢复指标、实际任务语料、回归门禁 | P0 起持续 / 两仓 | - -## 5. 采用与暂缓的决策 - -采用:有界失败恢复;工具结果摘要+资源引用;结构化参数;步骤效应账本;产物与聊天投影分离;资源预览与“加入上下文”分离;用户可检查的引用;按需工具发现。原有源码、知识、工作簿与验证证据仍是权威,衍生视图可重建。 - -暂缓:全自动跨站电脑操作、任意外部 MCP 自动信任、默认多智能体协作、所有 Office 格式保真编辑、每次问答都规划/运行代码。它们不能先于当前恢复、工具授权和预览闭环。 - -不采用:把长回答直接 substring 截断、把失败原文当最终成功、前端断流即重发任务、把所有文件当 HTML、用网页内容改写 system 指令、把预览等同于执行可执行文档。 - -## 6. 必须补做的动态验证 - -1. 在真实聊天中验证六段式输出与门禁失败/修复的最终消息和持久产物是否一致。 -2. 丢弃最后一帧、断网、刷新、worker 崩溃分别注入,确认事件重放不重做工具副作用。 -3. 使用真实 HTTP 入口验证右栏笔记、嵌套文件、历史引用、跨 workspace 资源;不只调用兄弟辅助函数。 -4. 用恶意/畸形 HTML、路径与符号链接、过大文件验证预览隔离;no-exec 通过哨兵副作用测试。 -5. 对无凭证模型、text-only provider、不可用转换器做明确降级;记录版本与环境,禁止以 mock 成功声称上线成功。 - -后续设计文档中的时间、轮数、字符数、成功率阈值均为拟定验收目标,需用该语料校准。 diff --git a/doc/research/agent-framework-2026-09.md b/doc/research/agent-framework-2026-09.md deleted file mode 100755 index 949e75e..0000000 --- a/doc/research/agent-framework-2026-09.md +++ /dev/null @@ -1,54 +0,0 @@ -# 调研刷新:2026-09 智能体框架与 Marqdo「代码即文档」 - -| | | -|---|---| -| 状态 | **Wave B1 Active**(B0/B0.5 已完成;宪法优先) | -| 日期 | 2026-09-04 | -| 前置 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) | -| 路线 | [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) | - -## 0. 结论 - -业界框架(LangGraph / Microsoft Agent Framework / CrewAI / OpenAI Agents SDK)在编排、工具、检查点、MCP、评测上继续收敛;**权威真相仍默认在对象图 + transcript + 外置 Store**。 - -Marqdo 的差异化不是「再做一个 loop」,而是: - -1. **代码即文档** — 编排 `.mq.md` = 提示词工作面 -2. **调用位置可见** — `agent_call_site`(路径 / 函数 / 行)是一等上下文 -3. **文档即知识库(OKF)** — 写回 → promote / solidify → 二次命中 / `llm_free` - -Wave B 的目标函数:**证明并硬化上述三点**;产品化示例与评测必须服务差异化,禁止做成无源码上下文的 chatbot demo。 - -## 1. 业界快照(2026) - -| 模式 | 代表 | 状态记忆 | 对 Marqdo | -|------|------|----------|-----------| -| 图 + checkpointer | LangGraph | typed state 持久化 | 续跑应对齐**文件化工作簿**,不造 Python 图 DSL | -| Agent vs Workflow | Microsoft AF | 自主 + 确定性流 | 已有 step / plan,强化即可 | -| 角色班组 | CrewAI | Task 管道 | 多 Agent 低优先;父 CALL + 多工作簿 | -| Handoff + Guardrails | OpenAI Agents SDK | 显式交接 | 可借鉴语义;权威仍在 `.mq.md` | - -## 2. 深远影响(开发硬约束) - -| 约束 | 含义 | -|------|------| -| 提示不黑盒 | standing / 工具 / 任务写在文件;拼装可审查 | -| 位置感知 | 每次推理注入 call_site;示例与评测可断言 | -| 源码工作面 | `source_brief` + `READ:source\|skill`;禁止藏整份 Skill 进不可见提示 | -| 写回即记忆 | ok/error 槽 + view;非默认向量库 | -| OKF 飞轮 | promote / solidify / hit / llm_free | -| 外置工具 | corpus / MCP 仅证据,`authority=workbook` | - -## 3. Wave B 范围 - -| 波次 | 主题 | -|------|------| -| **B0** | 宪法可见示例 + 上下文管道可读性 + Skill/文档 | -| **B0.5** | 本机 live(`.env` → cflmy)验证「模型用上了文档」 | -| **B1** | 评测锁住 call_site / OKF / 写回 / 预算 | - -暂缓:真 MCP、resume/HITL view、kb stats、并行、A2A。 - -## 4. 开发期 LLM - -仓库根目录 `.env`(gitignore):`OPENAI_*` 或 `MARQDO_LLM_*`。模板见 `.env.example`。 diff --git a/doc/research/agent-framework-gaps-after-a4.md b/doc/research/agent-framework-gaps-after-a4.md deleted file mode 100755 index 2488291..0000000 --- a/doc/research/agent-framework-gaps-after-a4.md +++ /dev/null @@ -1,191 +0,0 @@ -# 调研:`ext/agent` 在 A0–A4 之后还差什么 - -| | | -|---|---| -| 状态 | **调研笔记 · 缺口盘点(A0–A4 闭环之后)** | -| 日期 | 2026-08-28 | -| 前置调研 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md)(优势与优化原则) | -| 已落地路线 | [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md)(**A0–A4 done**) | -| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) | -| 邻近规划 | [agent-streaming.md](../roadmap/agent-streaming.md) · [okf-near-match.md](../roadmap/okf-near-match.md) | -| 外部对照(2026) | LangGraph persistence / CrewAI+Flows / MCP 工具协议 / 业界 Agent 评测与记忆层讨论 | - ---- - -## 0. 一句话结论 - -调研驱动的 **A0–A4** 已把 Marqdo 智能体的**差异化内核**补齐:工作簿补丁可靠、OKF 复用飞轮可读可用、过程事件可审、上下文有预算、外置检索/MCP 只作证据。 - -相对 2026 年主流框架(LangGraph、CrewAI、厂商 SDK、MCP 生态),Marqdo **不再缺「能跑的 Agent loop」**;缺口集中在: - -1. **产品化与可发现性**(示例、文档新鲜度、上手路径) -2. **生产配套**(评测 harness、真 MCP、断点续跑、HITL、飞轮指标) -3. **可选扩展面**(并行 fan-out、多 Agent/A2A、trace 外发) - -**不要**用缺口清单去证明应回退到隐藏 TOOL: 循环或把向量库升为权威真相——那与宪法冲突,也抵消已落地的优势。 - ---- - -## 1. 已落地基线(A0–A4) - -| 波次 | 主题 | 验收要点 | -|------|------|----------| -| **A0** | 工作簿补丁 / 固化 | 整文件 FIND 护栏;`soft` 仅 miss;`workbook_solidify`;金样 `agent-workbook-patch-a0` | -| **A1** | OKF 复用飞轮 | `list_tasks` 策展字段;`plan` 暴露 `match`/`score`;金样 `agent-kb-plan-hit` | -| **A2** | 过程可见 | `events` 默认落盘;view plan 过程卡;SSE 仍仅 `stream=True` | -| **A3** | 上下文预算 | `source_brief` / `skill_brief`;`READ:source|skill`;`step max_reads` | -| **A4** | RAG/MCP 证据工具 | `corpus_search`;fixture `mcp_*`;`authority=workbook` | - -原则回顾(见前置调研 §9):强化差异化;资源砸在工作簿 / 写回 / 固化 / OKF / 过程可视;外置 RAG/MCP **只作工具**。 - ---- - -## 2. 相对业界:已经「够格」的部分 - -下列能力若取消「可执行 Markdown 为权威」即消失——这是护城河,不是功能点攀比: - -| 能力 | Marqdo 形态 | 业界常见替代 | -|------|-------------|--------------| -| 单一真相源 | 源码即提示 + 调用点注入 | Prompt Hub / 字符串 system | -| 过程可审 | 写回块 + `events` + view 过程卡 | Langfuse / LangSmith 外挂 | -| 成功可复用 | OKF 任务技能再跑 | transcript 再聊 / 向量片段召回 | -| 复杂任务边界 | 工作簿文件 + `subtask` | 无限加长 chat / 临时工具输出 | -| 确定步骤降本 | solidify → `llm_free` 快路径 | 每轮仍问模型 | - -自评四问(前置调研 §9)粗判: - -| 问 | 现状 | -|----|------| -| 新人能否只读一份 `.mq.md` 理解 Agent? | **部分** — 机制在,缺 canonical 示例教程 | -| 失败后能否在 git + view 复盘、不强制外部 trace? | **基本可以** | -| 成功任务下周能否以同一技能复用? | **可以**(金样已锁二次命中) | -| 确定步骤是否越来越多变成普通 `##`、模型调用下降? | **路径有**(solidify / llm_free),缺量化看板证明 | - ---- - -## 3. 缺口总表(按优先级) - -| 优先级 | 缺口 | 为何还缺 | 建议验收线索 | -|--------|------|----------|--------------| -| **高** | 官方端到端示例 + 文档新鲜度 | 无独立 `examples/agent-*`;Skill/参考里仍有「layout / roadmap」陈旧表述;外人难「照抄即跑通 plan→固化→二次命中」 | `examples/agent-pong`(或同类)+ README;Skill 专节与 A0–A4 对齐 | -| **高** | Agent 评测 / 回归 harness | 有离线金样,缺成本·恢复·命中率·补丁质量的系统评测;业界强调 evaluation 先于上线 | `tests/` 或脚本:命中率、llm_free 占比、失败恢复、可选 live 预算 | -| **高** | 真 MCP(HTTP/SSE)与凭证 | A4 仅 JSON fixture;缺 streamable HTTP、鉴权、resources/prompts | 金样打 mock MCP server;返回仍带 `authority=workbook` | -| **高** | **MCP Server 宿主**(stdio / HTTP) | Agent 只能当客户端 fixture;IDE 无法把 `.mq.md` `##` 暴露为 MCP 工具 | 见 [ext-hosting-gaps.md](ext-hosting-gaps.md) GAP-03 · [ext-hosting-fill.md](../design/ext-hosting-fill.md) | -| **中** | Plan 断点续跑 | 工作簿在盘上,缺显式 checkpoint / resume(对标 LangGraph checkpointer) | `plan resume=` 从第 N 轮 DECISION 继续;进程崩溃可恢复 | -| **中** | 人机协同(HITL)加深 | 仅有 `confirm=True` 建簿即停;缺审批卡、拒绝重开、view 一键继续 | view 审批控件 + 金样 | -| **中** | 飞轮可观测指标 | `hits` / `improve_every` / `llm_free` 有字段,缺汇总与 CLI/view 报表 | `agent_kb_stats` 或 view 面板:命中率、探索浪费 | -| **中** | 受控并行 fan-out | `subtask` 能并行,plan 主路径偏串行 | 父协议允许有界并行调研再合并 | -| **低** | 多 Agent / A2A | dual skeleton 有;缺角色班组、跨进程 A2A | 多数场景可用「多工作簿 + 父 CALL」覆盖;有明确跨组织需求再开 | -| **低** | Trace 外发(OTLP / Langfuse) | 本地复盘已够;外发是集成题 | 可选 adapter;默认不依赖 | -| **刻意不做** | Dense embedding 默认化 | [okf-near-match.md](../roadmap/okf-near-match.md) **E** 仅在 n-gram 证据不足时评估 | 不宣传为默认向量库 | -| **刻意不做** | 私有 JSON TOOL 主路径 / 整文件 LLM 重写 | 与宪法及 parent 设计冲突 | 继续禁止 | - ---- - -## 4. 分项说明 - -### 4.1 产品化(高) - -**问题** -内核能力已超过「能演示」门槛,但**可感知产品体验**仍依赖读设计文档与翻 `tests/ext/`。对照 quantum / web 已有 `examples/`,agent 侧空白最明显。 - -**建议** -1. 一份最小可运行示例:`step` → `plan` → promote → 二次 `plan` 打印 `cache=hit`。 -2. 同步 Skill / `doc/README` / 公开页,删掉「仅 layout」类过时句。 -3. 示例强调「权威在 `.mq.md`」,corpus/mcp 仅作证据旁路。 - -### 4.2 评测 harness(高) - -**问题** -金样锁行为正确性;不锁「飞轮是否在变好」「一次失败后能否恢复」「live 成本是否失控」。2026 多 Agent 讨论普遍把 **evaluation** 列为上线前缺失步骤。 - -**建议** -- 离线:命中路径、补丁护栏、预算截断(已有)再加 **stats 断言**。 -- 半自动 / live:固定小 goal 集,记录 rounds、cache 分布、token 粗估(若可从供应商响应取得)。 -- 明确:评测消费的是工作簿与 kb,而不是外部 transcript 库。 - -### 4.3 真 MCP(高)与「证据≠权威」(不变) - -**问题** -Fixture 证明协议形状与权威字段;生产要接真实 MCP server(工具、资源、鉴权)。 - -**约束** -- 工具结果进入 observation / CALL 回执,**不得**静默写成 OKF 权威技能。 -- 晋升仍走 promote / solidify / 人审(既有路径)。 - -### 4.4 断点续跑与 HITL(中) - -**问题** -LangGraph 类框架的 checkpointer / interrupt 是生产差异点。Marqdo 已有文件化状态(工作簿、写回、events),差的是**一等恢复 API**与**可视审批**。 - -**建议方向** -- Resume:序列化「当前 round、path、last observation、events」到约定槽或旁路文件,重启后跳过已完成子跑。 -- HITL:扩展 `confirm` 语义(建簿 / 危险 PATCH / promote);view 展示 pending 卡。 - -### 4.5 飞轮指标与并行(中) - -**问题** -第四问(模型调用是否下降)需要数字。并行能缩短探索,但须有界,避免工作簿爆炸(见 [ext-agent.md](../design/ext-agent.md) §9)。 - -### 4.6 多 Agent / A2A / 外发 trace(低) - -**问题** -业界热度高(Crews、A2A、共享记忆层)。Marqdo 的「父 + 多工作簿」已覆盖多数单组织编排;跨组织 A2A 与共享记忆库是另一产品层,可用 MCP/证据工具接入,而不必把记忆权威搬出 `.mq.md`。 - ---- - -## 5. 建议的下一波分期(草案 B) - -> 非正式锁定;落地时再写入 [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) 或独立 `ext-agent-productize.md`。 - -| 波次 | 主题 | 验收线索 | -|------|------|----------| -| **B0** | 官方示例 + Skill/文档去陈 | `examples/agent-*` 可 `marqdo run`;Skill 与 A0–A4 一致 | -| **B1** | 评测 harness | 命中率 / llm_free / 恢复用例可一键跑 | -| **B2** | Live MCP 客户端 | mock server 金样;`authority=workbook` 不变 | -| **B3** | Plan resume + HITL | 崩溃可续;view 审批 | -| **B4** | kb stats 面板 | CLI 或 view 展示飞轮数字 | -| **B5** | 有界并行(可选) | fan-out 上限 + 合并观察 | - ---- - -## 6. 明确「不是缺口」的清单 - -避免把差异化优势误判为缺陷: - -1. **没有默认 dense 向量库** — 有意;OKF near 是稀疏词法;corpus 是关键词证据。 -2. **没有隐藏 TOOL: JSON 主协议** — 有意;CALL/READ/DECISION 与文档同构。 -3. **子任务默认 quiet** — 有意;答案走返回值,过程走 events/stream。 -4. **ext 不直调 host_*** — 有意;Agent 域在插件,防核心膨胀。 -5. **不捆绑领域工单技能** — 有意;官方框架保持可教、可审、可扩展。 - ---- - -## 7. 结论与推荐下一刀 - -A0–A4 之后,Marqdo `ext/agent` 在「文档驱动智能体」叙事上已经**自洽且可演示**。相对业界,短板是 **被人用起来的路径** 与 **生产级配套**,不是再堆一条编排 DSL。 - -**推荐下一刀顺序:** - -1. **B0 官方示例 + 文档去陈**(最低成本、最高感知) -2. **B1 评测 harness**(锁住飞轮与质量,防止回退) -3. 按真实用户需求选 **B2 live MCP** 或 **B3 resume/HITL** - -若四问在 B0–B1 后均可回答「是」,再考虑 B4/B5 与低优先级项。 - ---- - -## 8. 参考 - -### 本仓 - -- [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) -- [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) -- [okf-near-match.md](../roadmap/okf-near-match.md)(E dense 仍非默认) -- [agent-streaming.md](../roadmap/agent-streaming.md) - -### 外部(抽样,2026) - -- LangGraph Persistence(checkpointer / store) -- CrewAI Crews + Flows;MCP 作为工具连接层而非编排本体 -- 业界对 Agent evaluation、durable memory / A2A 状态层的讨论(共享记忆 ≠ 应取代可执行文档权威) diff --git a/doc/research/agent-frameworks-and-marqdo.md b/doc/research/agent-frameworks-and-marqdo.md deleted file mode 100755 index f1efc2f..0000000 --- a/doc/research/agent-frameworks-and-marqdo.md +++ /dev/null @@ -1,533 +0,0 @@ -# 调研:主流智能体开发框架与 Marqdo「代码即文档 / 文档即知识库」优势 - -| | | -|---|---| -| 状态 | **调研笔记 · 供 `ext/agent` 深入优化参考** | -| 日期 | 2026-08-28 | -| 范围 | 2025–2026 开源/厂商智能体框架形态;对照 Marqdo `ext/ai/agent` 设计 | -| 相关设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) · [stdlib-writeback.md](../design/stdlib-writeback.md) · [stdlib-subtask.md](../design/stdlib-subtask.md) | -| 姊妹调研 | [okf-and-marqdo.md](okf-and-marqdo.md) · **A0–A4 后缺口** [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) | -| 外部对照(抽样) | [Langfuse 框架对比(2026-07)](https://langfuse.com/blog/2025-03-19-ai-agent-comparison) · [LangGraph persistence](https://docs.langchain.com/oss/python/langgraph/persistence) · [Microsoft Agent Framework / AutoGen 维护模式](https://github.com/microsoft/autogen) · CrewAI / OpenAI Agents SDK / Claude Agent SDK / Google ADK / LlamaIndex 公开文档 | - ---- - -## 0. 一句话结论 - -主流智能体框架几乎都在解决同一组工程问题——**编排、工具、状态、记忆、可观测、人机协同**——但它们的「权威真相」默认落在 **Python/TS 对象图 + 会话 transcript + 外部 Store/向量库** 上。 - -Marqdo 的宪法把权威真相定在 **可执行 Markdown(`.mq.md`)**:人写的程序、模型读的提示、执行后的写回、可复用的任务技能,是**同一份文档的不同生命阶段**。这不是「又一个 Agent SDK」,而是把 **Agent 开发本身做成文档工程**。 - -由此产生的突出优势(后文展开): - -1. **编排可读 = 提示词不再黑盒**(源码即上下文) -2. **过程可审 = 写回进源文件,而不是只进遥测平台** -3. **记忆可 git = 成功经验晋升为任务知识包(OKF),审计=仓库历史** -4. **复杂任务=子程序,而不是无限加长的 chat**(工作簿 + `subtask`) -5. **确定步骤固化为代码,不确定步骤才问模型**(父 Plan-and-Move) -6. **语言与知识形态同构**(与 Google OKF「Markdown 知识包」同向,但多走「可执行」一步) - -**优化 `ext/agent` 时应守住这些差异化,而不是向 LangChain 类「隐藏循环 + TOOL: 协议」回退。** - ---- - -## 1. 调研方法与边界 - -### 1.1 做了什么 - -| 动作 | 说明 | -|------|------| -| 横向扫盘 | 2026 年主流开源框架:LangGraph / LangChain DeepAgents、CrewAI、OpenAI Agents SDK、Claude Agent SDK、Google ADK、Microsoft Agent Framework(AutoGen 继承者)、Pydantic AI、LlamaIndex、Strands、Mastra / Vercel AI SDK、smolagents 等 | -| 结构抽象 | 抽取「框架如何形成」的共性分层,而不是比 GitHub stars | -| 对照本仓 | 精读 `ext-agent*`、`okf`、`writeback`、`subtask`、parent Plan-and-Move;对照旧 TOOL: 薄循环为何被否定 | -| 找优越点 | 只保留 **Marqdo 结构上必然领先**、而非「以后可以加插件追上」的点 | - -### 1.2 不做的 - -- 不宣称 Marqdo 在吞吐、多模态、托管运维上已全面领先(这些不是当前差异化)。 -- 不把「有没有向量检索」当成胜负手——那是应用层可加能力。 -- 不做厂商营销话术复读;优缺点按**开发者体验与系统真相源**评。 - ---- - -## 2. 智能体框架是怎么「形成」的 - -无论品牌如何包装,成熟框架通常收敛为同一条装配线: - -```text -┌─────────────────────────────────────────────────────────────┐ -│ 1. Model I/O │ -│ 补全 / 工具调用 / 流式 / 多模供应商适配 │ -├─────────────────────────────────────────────────────────────┤ -│ 2. Agent 单元 │ -│ 指令(system) + 工具表 + 可选角色/人设 │ -├─────────────────────────────────────────────────────────────┤ -│ 3. 编排(Orchestration) │ -│ 图 / 角色队 / 对话群 / 工作流 API / supervisor │ -├─────────────────────────────────────────────────────────────┤ -│ 4. 状态与记忆 │ -│ 短:thread checkpoint / 会话历史 │ -│ 长:Store / 向量 RAG / 用户偏好库 │ -├─────────────────────────────────────────────────────────────┤ -│ 5. 工具与行动面 │ -│ 函数 schema、MCP、沙箱、权限、CodeAct │ -├─────────────────────────────────────────────────────────────┤ -│ 6. 可观测与治理 │ -│ Trace、评测、护栏、HITL、配额 │ -└─────────────────────────────────────────────────────────────┘ -``` - -### 2.1 三种主流「编排哲学」 - -| 范式 | 核心隐喻 | 代表 | 可预测性 | 原型速度 | -|------|----------|------|----------|----------| -| **图 / 状态机** | 节点=步骤,边=转移,状态显式 | LangGraph、Google ADK workflow、MAF workflows | 高 | 中–慢(先画图) | -| **角色协作** | Agent=工种,Crew=班组 | CrewAI、早期 AutoGen 群聊 | 中 | 快 | -| **薄循环 + 工具** | 「模型自己决定下一步」 | OpenAI Agents SDK、Claude Agent SDK、Strands、smolagents | 低–中(靠护栏) | 最快 | - -2026 年的趋势不是「哪个范式消灭其它」,而是: - -- **生产复杂流** → 图(可控、可恢复、HITL)。 -- **内容/研究班组** → 角色。 -- **编码助手 / 生态绑定** → 厂商 SDK 自带 hardened loop。 -- **LangChain DeepAgents** 等开始把「规划器 + 子代理 + 文件记忆」打包成 opinionated harness——说明业界也意识到:纯 chat 不够,需要**文件与子上下文**。 - -### 2.2 记忆层的行业共识(与 Marqdo 对照的关键) - -以 LangGraph 文档为代表(行业事实上的标准划分): - -| 层 | 行业做法 | 作用 | -|----|----------|------| -| **短时** | Checkpointer / thread_id | 会话续跑、崩溃恢复、time-travel | -| **长时** | BaseStore / 向量库 / Mem0·Zep 等 | 跨会话事实、偏好 | -| **检索知识** | RAG corpus | 领域文档,不与会话状态混用 | - -常见架构错误:把 checkpointer 当成长时记忆——换 `thread_id` 就「失忆」。 - -**这一点对 Marqdo 极关键:** -行业把「记忆」拆成多个后端;Marqdo 默认把**任务级成功经验**落成 **`.mq.md` + agent-kb(OKF)**,用文件系统与 git 当记忆平面——见 §7。 - -### 2.3 框架「形成产品」的路径 - -```text -PoC(脚本循环) - → SDK(Agent + tools) - → 编排(图 / 多代理) - → 持久化(checkpoint / store) - → 平台(托管、评测、护栏、计费) -``` - -越往后,**编排源码与运行时真相越分离**:提示在字符串常量或 Prompt Hub,状态在 DB,轨迹在 Langfuse,知识在向量库。人要复盘一次失败,往往要开四个系统。 - -Marqdo 的赌注是:**尽量把真相拉回单一 `.mq.md` 时间线**。 - ---- - -## 3. 代表框架解剖(如何形成 + 优缺点) - -### 3.1 LangGraph(显式状态图) - -**如何形成** - -- 把 Agent 步骤建模为 **有向图**:节点读/写共享 state,条件边决定下一跳。 -- 编译为可执行应用;挂 checkpointer → 持久化、HITL interrupt、故障续跑。 -- 长时记忆另挂 Store;生态上接 LangChain 工具与 LangSmith/Langfuse 轨迹。 - -**优点** - -- 生产向可控性最强;分支、重试、并行边清晰。 -- 状态类型化后,测试与回放(time-travel)可行。 -- 云中立:图在你自己的进程里跑。 - -**缺点** - -- 上手成本高:先设计图,再写节点。 -- 「提示词 / 业务说明」仍常散落在 Python 字符串;**图代码 ≠ 给人读的说明书**。 -- 记忆与知识仍依赖外置 Store/RAG;审计链路长。 -- DeepAgents 等上层 harness 说明:光有图仍不够「文件化协作」。 - -**对 Marqdo 的启示** - -- 要学其「显式控制与可恢复」;不要学其「状态默认在对象里」。 -- Marqdo 多步的工作簿修订环 ≈ **把图展开成磁盘上的可执行文档**。 - ---- - -### 3.2 CrewAI(角色班组 + Flows) - -**如何形成** - -- Agent = role / goal / backstory;Crew 协调任务;近年加 **Flows** 把确定性业务逻辑包住自治班组。 - -**优点** - -- 多代理叙事直观,原型极快。 -- 适合内容流水线、调研班组。 - -**缺点** - -- 协作转移大量靠描述,**可预测性弱于图**。 -- 过程真相仍是运行时对象与日志;与「文档即程序」无关。 -- HITL / 企业治理相对弱。 - -**对 Marqdo 的启示** - -- 「多角色」可用多个 `# 智能体` / 多个工作簿表达,但应以**可跑文档**为边界,而不是隐式群聊。 - ---- - -### 3.3 AutoGen → Microsoft Agent Framework(MAF) - -**如何形成** - -- AutoGen:对话对 / 群聊驱动;历史在内存。 -- 2026:AutoGen **维护模式**;能力并入 **Microsoft Agent Framework**(与 Semantic Kernel 合流):ChatAgent + 多种编排(sequential / concurrent / handoff / group / Magentic)+ 工作流图 + Azure Foundry 治理面。 - -**优点** - -- 企业栈(.NET / Azure)一体;A2A、MCP、护栏、托管轨迹。 -- CodeAct 等模式:让 Agent **写代码执行**而非只吐 JSON——与「固化为代码」方向有共鸣。 - -**缺点** - -- 生产治理深度常绑定云平台;开源核心与托管能力分层。 -- 编排语言仍是通用编程语言;**业务知识与程序不同构**。 -- 对话范式易导致「无限闲聊」式多代理。 - -**对 Marqdo 的启示** - -- CodeAct / 固化步骤:与 Marqdo「确定步骤写成 `##`」同向,但 MAF 写的是 Python;Marqdo 写的是**人与模型共用的 `.mq.md`**。 - ---- - -### 3.4 OpenAI Agents SDK / Claude Agent SDK / Google ADK / Strands - -**如何形成(共性)** - -- 提供 **hardened agent loop**(工具、handoff、权限、会话)。 -- 深度绑定自家模型或云(OpenAI / Anthropic Claude Code harness / Gemini+ADK / Bedrock)。 - -**优点** - -- 最快接入「能干活的助手」;权限与工具路径经过产品锤炼(尤其 Claude Code 同源 SDK)。 -- 官方 tracing、realtime 等增值。 - -**缺点** - -- 编排与提示仍在宿主语言;**跨团队知识复用靠复制仓库或 Prompt 平台**。 -- 供应商锁定风险;换模时常换范式。 -- 「记忆」默认会话式;企业知识仍外挂。 - -**对 Marqdo 的启示** - -- 模型 I/O 应继续放在 `ext/llm`,**不要**在 agent 里重造聊天栈。 -- 不要把「官方 loop」当哲学:Marqdo 的哲学是文档驱动,不是 SDK 驱动。 - ---- - -### 3.5 LlamaIndex / Haystack(文档与 RAG 优先) - -**如何形成** - -- 以索引、检索、查询引擎为中心;Agent 是检索之上的编排层。 - -**优点** - -- 企业文档智能、多格式摄取成熟。 -- 「知识」有一等公民地位。 - -**缺点** - -- 知识默认是 **被检索的被动语料**,不是 **可执行的任务程序**。 -- Agent 编排能力弱于 LangGraph 系;常需再叠一层框架。 -- 索引与源文档易漂移(双源真相)。 - -**对 Marqdo 的启示(尖锐对比)** - -- LlamaIndex:**文档 → 向量 → 检索 → 回答**。 -- Marqdo:**文档 → 可执行语法 → 运行 → 写回 →(可选)晋升为任务知识包**。 - 同一「Markdown 知识」在 Marqdo 里可以是 **会跑的技能**,而不仅是 chunk。 - ---- - -### 3.6 Pydantic AI / Mastra / Vercel AI SDK - -**如何形成** - -- 强调类型安全(Pydantic)或 TS 全栈 DX(Mastra / Vercel)。 -- 把 Agent 当普通后端组件:校验、otel、耐久执行。 - -**优点** - -- 工程化体验好;与现有 Web/API 栈融合。 - -**缺点** - -- 仍是「代码库里的 Agent」;非技术干系人无法直接打开同一份编排当说明书。 -- 知识沉淀路径仍外置。 - ---- - -### 3.7 横向对比表(开发者真相源) - -| 维度 | 典型框架落点 | Marqdo 落点 | -|------|--------------|-------------| -| 编排定义 | Python/TS 图或类 | `.mq.md` 标题/表/调用 | -| 系统提示 | 字符串 / Prompt Hub | 站立提示写在同一文档 | -| 工具 | 装饰器函数 / MCP | runbook 内 `##` + `subtask` | -| 短时状态 | checkpoint / session | 工作簿文件 + 写回块 + view | -| 长时记忆 | Store / 向量 | agent-kb(OKF)+ git | -| 复杂任务 | 子图 / 子代理上下文窗 | **子 `.mq.md` 程序** `spawn path=` | -| 复盘 | Langfuse trace | `git log` + 打开工作簿 + view output-card | -| 成功复用 | 手工抽 prompt / 存 Store | **固化 + OKF 晋升 / lookup** | - ---- - -## 4. 行业共性痛点(框架越强,痛点越清晰) - -下列痛点在 LangGraph、CrewAI、厂商 SDK 文档与实践文章中反复出现;它们正是 Marqdo 要正面打穿的: - -### 4.1 提示词与编排分离 - -- 行为由 system prompt + 隐藏模板决定;code review 审不到「模型真正看见什么」。 -- Prompt 漂移与代码漂移双轨发生。 - -### 4.2 过程不透明或只对平台透明 - -- 本地只有最终返回值;细节在 SaaS trace。 -- 合规团队要的「这份文档当时怎么决策的」难以直接交付。 - -### 4.3 记忆碎片化 - -- thread / store / RAG / 日志四套系统;「上次同类任务怎么做成的」检索成本高。 -- 成功经验很少自动变成**可再执行资产**。 - -### 4.4 多步任务变成超长 transcript - -- 上下文窗口被工具输出撑爆;DeepAgents 才开始「卸到文件系统」。 -- 说明业界被迫走向 **文件化**——而 Marqdo **一开始就以文件为执行边界**。 - -### 4.5 确定性逻辑仍反复问模型 - -- 已验证的步骤下一轮又被重新「推理」,浪费且不稳。 -- 缺少「晋升为普通代码」的一等路径。 - -### 4.6 Agent 框架与知识格式断裂 - -- Google OKF 等推动「知识用 Markdown 包交换」,但主流 Agent 框架并不把 **可执行程序** 当作知识页。 -- 结果:知识包给人策展,Agent 另跑一套 Python。 - ---- - -## 5. Marqdo 在智能体域的设计思想(必须找准) - -### 5.1 宪法重申 - -| 口号 | 在 Agent 语境下的含义 | -|------|------------------------| -| **代码即文档** | 智能体编排、工具表、站立提示、任务叙述写在同一份 `.mq.md`;打开即读、即可跑 | -| **文档即知识库** | 写回块、工作簿、OKF 任务页都是知识;Agent 与人共用同一交换面 | -| **文档能跑通 = 约定成立** | 金样 / `marqdo run` / view 是验收,不是「旁边另有一份真实现状」 | - -旧「TOOL: 黑盒循环」被官方设计明确否定,正是因为它把 Marqdo **降级成了 LangChain 的薄壳**。 - -### 5.2 两级执行(与业界范式对齐但不抄袭) - -| Marqdo | 业界近似 | 关键差异 | -|--------|----------|----------| -| `## step` 单步 | 薄 Agent loop | 注入**本文件源码 + 调用位置 + Skill**;默认写回 | -| `## plan` 多步 | 规划器 + 子代理 | 产物是 **工作簿 `.mq.md`**;经 `subtask` 整文件执行;父以补丁演进 | -| 父 Plan-and-Move | supervisor / orchestrator | 行动面:READ/CALL/DECISION;**禁止整文件 LLM 重写** | -| OKF agent-kb | long-term store | 命中的是 **可再跑的任务技能**,不是抽象 embedding 片段(可再叠加 soft near) | - -### 5.3 执行与隔离 - -- 工具与子工作簿走 `lib/subtask`(`spawn fn=` / `spawn path=`),与主推理隔离——对应业界「子代理独立上下文」,但边界是 **文件与子进程语义**,不是仅换一个 message list。 - ---- - -## 6. Marqdo 的必要突出优势(核心章节) - -下列优势要求满足:**若取消「可执行 Markdown 为权威」,优势即消失**。这才是「必要」优越点,而不是功能清单攀比。 - -### 6.1 单一真相源:编排 / 提示 / 结果共址 - -**优势陈述** -模型在 `step`/`plan` 中看到的上下文,可以就是**人类正在编辑的那份源码**(及调用点)。站立提示不是隐藏 system blob,而是文档段落。 - -**为何必要** -消除「提示词仓库 vs 代码仓库」双源;code review、教学、合规审计面对同一人造物。 - -**相对框架** -LangGraph/CrewAI/SDK:提示常在字符串或控制台配置;trace 在另一系统。Marqdo:`view` 在语句下挂 output-card,与源同行。 - -### 6.2 写回 = 内建的「Notebook 输出单元」式过程记忆 - -**优势陈述** -`lib/writeback` 把成功/失败写入 `<!-- marqdo-out … -->`,锚在调用行下。智能体默认写回后,**过程留在源文件**,不是只留在遥测。 - -**为何必要** -教学与调试要「看见刚才那一步」;失败成为可读避坑记录;成功可被后续命中。 - -**相对框架** -业界靠 Langfuse/LangSmith;本地仓库往往是空的。Marqdo 仓库本身就是过程库(可再导出到 trace,但不依赖它才能复盘)。 - -### 6.3 复杂任务 = 生成并演进子程序,而不是堆 transcript - -**优势陈述** -`plan` 创建 `.marqdo/agent-runs/*.mq.md`,用 `spawn path=` 跑完整 `# main`。父观察**真实退出码、返回值、写回、源码**,再 FIND/REPLACE 补丁。 - -**为何必要** -上下文窗口有限;长工具输出必须卸出。DeepAgents 用「文件系统抽象」补课;Marqdo **语言层原生就是文件程序**。 - -**相对框架** -子代理多是「新对话 + 摘要」;Marqdo 子任务是 **可独立 `marqdo run` 的文档**,可被人类直接打开修改后重跑。 - -### 6.4 确定步骤固化为代码;模型只处理不确定残差 - -**优势陈述** -父作为「智能体开发大师」:能写成 `##` 的就固化;子智能体只跑不确定的 `step`。`DECISION: DONE` 可 solidify + OKF 晋升。 - -**为何必要** -降本、降方差、形成组织资产。业界常把每次任务重新推理;Marqdo 把「学会的技能」编译回语言。 - -**相对框架** -MAF CodeAct 写出的是通用语言脚本;Marqdo 固化的是 **仍保持文档属性的 `.mq.md` 技能**——人不用会 Python 也能读懂并改。 - -### 6.5 文档即知识库 + OKF:记忆可交换、可策展、可信任 - -**优势陈述** -任务知识包(`.marqdo/agent-kb/`)以 OKF 形承载 `Marqdo Task` / skill,`resource:` 必须指向可执行 `.mq.md`。lookup / near / soft_match 走插件,不进核心 host。 - -**为何必要** -Google OKF 证明行业需要「Markdown 知识包」;Marqdo 多走一步:**知识页声明的可执行资源真能跑**。记忆不是不可解释的向量命中,而是 **带路径的技能复用**。 - -**相对框架** -LlamaIndex 检索散文块;Store 存 JSON 事实。Marqdo agent-kb:**命中 → 再跑同一技能路径**(精确 / 规范化 / near / 父裁决)。 - -### 6.6 审计与协作默认路径 = Git - -**优势陈述** -工作簿演进、写回、晋升都是文件变更 → `git log` / PR / blame。 - -**为何必要** -企业已有代码治理;不必为 Agent 另建「提示治理平台」才能起步。 - -**相对框架** -多数框架的状态在 DB;要审计得接专用平台。Marqdo 从第一天就兼容软件工程工作流。 - -### 6.7 中英双面 API 与「说明书即程序」教学属性 - -**优势陈述** -`# 智能体` / `# agent`、`单步`/`step`、`多步`/`plan` 对称;教程文档可以直接是金样。 - -**为何必要** -智能体开发教育成本高;Marqdo 把教材和运行物合一(与 quantum/math 扩展同一哲学)。 - -### 6.8 分层纪律:扩展不脏核心 - -**优势陈述** -`ext/**` 禁 `host_*`;agent-kb 在 `plugins/agent`;核心保持瘦。 - -**为何必要** -避免「Agent 框架把语言运行时变成巨石」——这是许多 Python Agent 栈的终局病。 - ---- - -## 7. 优势地图(一图看懂定位) - -```text - 可预测性 / 生产控制 - ▲ - │ LangGraph / MAF workflows - │ - │ ★ Marqdo plan - │ (workbook = program) - │ - 角色班组 ──────────┼────────────── 薄循环 SDK - CrewAI │ OpenAI / Claude SDK - │ - │ LlamaIndex (RAG) - │ - └────────────────────────────► - 文档/知识一等公民程度 - -★ Marqdo 同时偏右上:控制来自「可执行文档+补丁环」, - 知识来自「同源 Markdown + OKF」,而非向量库单独称王。 -``` - ---- - -## 8. 诚实边界:什么时候不该硬吹 Marqdo - -| 场景 | 更合适的选择 | 原因 | -|------|--------------|------| -| 超大规模并行图、成熟 Python 数据栈 | LangGraph + 现有 infra | 生态与库广度 | -| 强绑定 Azure 治理 / .NET | MAF | 平台一体 | -| 纯文档问答 / 海量非结构化语料 | LlamaIndex 等 | 摄取与检索成熟;Marqdo 可 **调用** 它们作工具,不必重造 | -| 只要一个 ChatGPT 式助手周末原型 | 厂商 Agents SDK | 启动最快 | -| 需要强实时语音 / 多模原生 | 厂商 SDK | 非 Marqdo 当前主场 | - -Marqdo 的正确叙事不是「取代所有 Agent 框架」,而是: - -> **当你希望智能体开发成果沉淀为组织可维护的文档资产,并且编排本身必须可教、可审、可跑时——选 Marqdo。** - ---- - -## 9. 对 `ext/agent` 深入优化的建议方向(调研导出) - -优化应强化 §6 优势,避免回退到「隐藏 TOOL 循环」。 - -| 优先级 | 方向 | 理由 | -|--------|------|------| -| P0 | **工作簿质量与补丁可靠性**(精确 FIND/REPLACE、固化、观察切片) | 直接决定「子程序演进」是否优于 transcript | -| P0 | **OKF 命中体验**(精确 / near / soft_match 默认真策略、策展 UX) | 落实「文档即知识库」的复用飞轮 | -| P1 | **过程可见**(streaming / view 过程卡,见 [agent-streaming.md](../roadmap/agent-streaming.md)) | 对标 Langfuse,但真相仍写回文档 | -| P1 | **Skill / 源码注入的预算与渐进披露** | 避免上下文爆炸,同时保持「源码即提示」 | -| P2 | **与外部 RAG/MCP 的工具化接入** | 补齐语料检索,但不把向量库升为权威真相 | -| P2 | **评测金样:同类任务二次 plan 应命中 kb 快路径** | 用测试锁住差异化 | -| 避免 | 再引入私有 JSON 工具协议作主路径 | 与宪法冲突 | -| 避免 | 整文件 LLM 重写工作簿 | 已在 parent 设计禁止 | - -验收提问(产品自评): - -1. 新人能否只读一份 `.mq.md` 理解 Agent 在干什么? -2. 失败后能否在 git 与 view 内完成复盘,不强制打开外部 trace? -3. 成功任务下周能否以 **跑同一技能** 的方式复用,而不是「再聊一遍」? -4. 确定步骤是否越来越多地变成普通 `##`,模型调用是否下降? - -若四问皆是——优化方向正确。 - ---- - -## 10. 结论 - -2026 年的智能体框架市场在 **图控、角色班组、厂商 hardened loop、RAG 知识** 四条线上分化;共同短板是 **真相源碎片化** 与 **成功经验难以变成可执行组织资产**。 - -Marqdo 用「代码即文档、文档即知识库」把 Agent 开发收束到 **可执行 Markdown 生命循环**: - -**书写 → 注入模型 → 执行 → 写回 →(多步)补丁演进 → 固化 → OKF 晋升 → 再命中。** - -这不是功能点堆砌,而是架构级选择。深入优化 `ext/agent` 时,应把资源砸在 **工作簿、写回、固化、知识包命中、过程可视** 上,把「文档驱动的智能体开发框架」做成可感知的产品体验——这才是相对 LangGraph / CrewAI / 厂商 SDK **不可替代** 的优越点。 - ---- - -## 11. 参考与延伸阅读 - -### 本仓 - -- [ext-agent.md](../design/ext-agent.md) — 框架总设计(否定 TOOL 薄循环) -- [ext-agent-plan.md](../design/ext-agent-plan.md) — 多步工作簿 -- [ext-agent-parent.md](../design/ext-agent-parent.md) — 父 Plan-and-Move -- [okf.md](../design/okf.md) · [okf-and-marqdo.md](okf-and-marqdo.md) -- [stdlib-writeback.md](../design/stdlib-writeback.md) · [stdlib-subtask.md](../design/stdlib-subtask.md) -- [roadmap/agent-streaming.md](../roadmap/agent-streaming.md) · [roadmap/okf-near-match.md](../roadmap/okf-near-match.md) · [roadmap/ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) -- [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) — A0–A4 之后还差什么 - -### 外部(抽样,2025–2026) - -- Langfuse: *Comparing Open-Source AI Agent Frameworks*(2026-07 更新盘点) -- LangGraph docs: Persistence(checkpointer vs store) -- Microsoft: AutoGen maintenance → Agent Framework migration -- CrewAI: Crews + Flows -- OpenAI Agents SDK / Claude Agent SDK / Google ADK 公开 README -- Google OKF SPEC v0.2(知识包形态;与 Marqdo 可执行源对照) diff --git a/doc/research/agent-llm-transport-soft-2026-10.md b/doc/research/agent-llm-transport-soft-2026-10.md deleted file mode 100755 index 4af6142..0000000 --- a/doc/research/agent-llm-transport-soft-2026-10.md +++ /dev/null @@ -1,58 +0,0 @@ -# 缺陷记录:LLM 传输失败硬中断 Agent Runtime - -| | | -|---|---| -| 状态 | **Fixed(2026-10-16)** — 见 §3;金样 `tests/ext/agent-llm-transport-soft.mq.md` | -| 日期 | 2026-10-16 | -| 发现方 | qdagent(接通 `agent.run` live 路径时) | -| 影响面 | `host/net` · `plugins/llm` · `ext/ai/llm` · `ext/ai/llm/openai` · `ext/ai/agent` | -| 相关 | [agent-run-efi-resolve-bugs-2026-10.md](agent-run-efi-resolve-bugs-2026-10.md) · [ext-agent.md](../design/ext-agent.md) | - ---- - -## 0. 一句话 - -上游 LLM **连接拒绝 / 超时 / 非 200** 时,Runtime 曾以 **硬错误** 终止整个 `marqdo run`;产品(qdagent ASK/BUILD)无法落到结构化 `status=error`。 - ---- - -## 1. 复现 - -```bash -OPENAI_API_KEY=offline OPENAI_BASE_URL=http://127.0.0.1:9 \ - marqdo run tests/ext/agent-llm-transport-soft.mq.md -# 修复前:exit≠0,error: http POST … -# 修复后:exit 0,ask/step/run 均带 finish|status=error + error 文本 -``` - ---- - -## 2. 根因 - -| 层 | 行为 | -|----|------| -| `host_http_post` / SSE | 传输失败 `Err(...)` → VM abort | -| `plugins/llm` `llm_chat_completions` | 同上 `Err` | -| `ext/ai/llm/openai` | HTTP≠200 → `sys.exit 1` | -| `agent.model_turn` / `step` / `plan` | 无软失败臂 | - ---- - -## 3. 修复清单 - -| # | 改动 | 文件 | -|---|------|------| -| 1 | 传输失败 → `{status:0, body}` / SSE error event | `src/host/net.rs` | -| 2 | 插件返回 `{finish:error, error, …}` 而非 `Err` | `plugins/llm/src/lib.rs` | -| 3 | openai 非 200 → 结构化 pack,禁止 `sys.exit` | `ext/ai/llm/openai.mq.md` | -| 4 | `llm.ask` 透传 `error` / `finish` | `ext/ai/llm.mq.md` | -| 5 | `model_turn` / `step` / `plan` 收成 `status=error` | `ext/ai/agent.mq.md` | -| 6 | 金样 | `tests/ext/agent-llm-transport-soft.mq.md` | - -**契约**:Agent Runtime 对 LLM 传输失败必须可捕获;`status=error` + `error` 字符串;进程退出码 0(程序正常返回错误图)。 - ---- - -## 4. 对 qdagent - -`ensure_llm` 有 key 但上游不可达时,`ask`/`build` 可走既有 `mode=error` 臂写 workbook,不再整 CLI 崩。 diff --git a/doc/research/agent-run-efi-resolve-bugs-2026-10.md b/doc/research/agent-run-efi-resolve-bugs-2026-10.md deleted file mode 100755 index 5a4c751..0000000 --- a/doc/research/agent-run-efi-resolve-bugs-2026-10.md +++ /dev/null @@ -1,117 +0,0 @@ -# 缺陷记录:`agent.run` EFI / resolve 在消费方崩溃(qdagent 复现) - -| | | -|---|---| -| 状态 | **Fixed(2026-10-16)** — 见 §3;金样 `tests/ext/agent-run-cold-efi.mq.md` | -| 日期 | 2026-10-16 | -| 发现方 | qdagent(`~/work/qdagent`)接通 Marqdo ≥1.4.2 Agent EFI 全路径时 | -| 影响面 | `ext/ai/agent` · `## run` · `plugins/agent` `agent_resolve` | -| 相关 | [ext-agent.md](../design/ext-agent.md) · [engineering-knowledge.md](../design/engineering-knowledge.md) · [ai-agent-llm-optimize-2026-10.md](ai-agent-llm-optimize-2026-10.md) | - ---- - -## 0. 一句话 - -`agent.run` 在 **空 OKF / 无 skill 命中** 或 **`efi=True`** 时,会以硬错误退出,而不是降级到 `plan` 探索。 -这是 **Agent Runtime 契约不完整**,不是 qdagent 业务写错。 - ---- - -## 1. 复现(qdagent) - -环境:工作区 Marqdo `1.4.2` + `MARQDO_EXT=~/work/marqdo/ext`;qdagent 调用: - -```text -助手 = > agent.agent … -`助手`.run task=… efi=True # 或 efi=False 后仍进 resolve -``` - -本仓几乎没有 `.marqdo/agent-kb` 编译 skill。 - -### Bug A — `efi=True` → `unknown function preflight` - -**位置**:[`ext/ai/agent.mq.md`](../../ext/ai/agent.mq.md) `## run` - -```markdown -1. `efi` - **efi_pf = preflight task=`task`** -``` - -同文件其它同对象方法一律写 `` `self`.route `` / `` `self`.resolve ``。 -裸标识 `preflight` 在导入消费方(如 `cli/求道-构建.mq.md`)里被解析成**全局函数**,找不到 → 硬错。 - -**期望**:`` **efi_pf = > `self`.preflight task=`task`** ``(或等价 method call)。 - -### Bug B — miss resolve → `missing map key llm_free` - -**位置**: - -1. Plugin:[`plugins/agent/src/memory.rs`](../../plugins/agent/src/memory.rs) `resolve_task` - 当 `kb_lookup` 返回 null: - -```rust -Ok(json!({ - "mode": "unknown", - "skill": null, - "resource": null, - "confidence": 0.0, - // 缺 llm_free -})) -``` - -2. Facade:`## run` 在 resolve 之后: - -```markdown -**llm_free = [llm_free](resolved)** -``` - -脚注式取键在缺键时 **硬失败**,无法落到后面的 `plan` 探索臂。 - -**期望**: - -- miss 结果始终带 `"llm_free": false`(与命中路径字段集对齐) -- facade 侧对可选键用 `json.get`(缺省 `False`),防御其它调用方 - ---- - -## 2. 为何金样没拦住 - -| 金样 | 为何漏网 | -|------|----------| -| `tests/ext/agent-zero-llm.mq.md` | 先编译 skill / policy,再 `run`;resolve **命中** | -| `tests/ext/eng-preflight.mq.md` | 只测 `agent_eng_preflight`,**不**走 `agent.run efi=` | -| 多数 `agent-*-live` | 自带 kb 或 `efi=False` / 不经过 cold miss | - -qdagent 是第一个「冷库 + 产品 EFI + `run`」消费方,因此打穿。 - ---- - -## 3. 修复清单(本轮) - -| # | 改动 | 文件 | -|---|------|------| -| 1 | miss resolve 补 `llm_free: false` | `plugins/agent/src/memory.rs` | -| 2 | `` `self`.preflight ``;`llm_free`/`mode` 用 `json.get` | `ext/ai/agent.mq.md` | -| 3 | 回归金样:冷 kb + `run efi=True` 不崩溃,落到 explore/plan | `tests/ext/agent-run-cold-efi.mq.md` | -| 4 | 重建 `marqdo_plugin_agent` 并跑金样 | `cargo build -p marqdo_plugin_agent --release` | - ---- - -## 4. 对 qdagent 的含义 - -修复后 qdagent 可恢复: - -```text -product preflight → latch → agent.run (efi=True|False) / plan -``` - -而不必长期绕开 `agent.run`。 -在插件未装入新 so 前,qdagent 侧 EFI latch + `step`/`plan` 仍是合法降级。 - ---- - -## 5. 非目标 - -- 不改 EKC / `agent_eng_preflight` 语义 -- 不引入第二套 Agent loop -- 不把向量检索升为权威真相 diff --git a/doc/research/ai-agent-llm-optimize-2026-10.md b/doc/research/ai-agent-llm-optimize-2026-10.md deleted file mode 100755 index c9584f1..0000000 --- a/doc/research/ai-agent-llm-optimize-2026-10.md +++ /dev/null @@ -1,136 +0,0 @@ -# 调研:代码即文档 × OKF × 沙盒 下的智能体 / 大模型优化(2026-10) - -| | | -|---|---| -| 状态 | **调研 + 问题分析 · 供方案 [ext-ai-optimize.md](../design/ext-ai-optimize.md) 参考** | -| 日期 | 2026-10-16 | -| 前置 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) · [agent-framework-2026-09.md](agent-framework-2026-09.md) · [ai-agent-sandbox.md](ai-agent-sandbox.md) · [okf-and-marqdo.md](okf-and-marqdo.md) | -| 本仓能力 | [ext-agent.md](../design/ext-agent.md) · [okf.md](../design/okf.md) · [engineering-knowledge.md](../design/engineering-knowledge.md) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) · [ai-stack.md](../roadmap/ai-stack.md) · [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) | -| 外部抽样 | Anthropic Agent Skills · SoK Agentic Skills (arXiv 2602.20867) · ForgeAgent · ACES / Skill Lift · Switchcraft 路由 · DSPy/GEPA ·「工作流编译进权重」· MalSkillBench | - ---- - -## 0. 一句话 - -业界正把 Agent 优化从「更好的 chat loop」转向 **可验证、可复用、可隔离执行的技能层**;Marqdo 已具备 **可执行 Markdown(代码即文档)+ OKF/EKC 复用 + CoW 沙盒** 三件套,优化目标应是把这三件套焊成闭环:**试跑 → 证据 → 晋升 → 零/少 LLM 复用**,而不是追平 LangChain 功能清单。 - ---- - -## 1. 调研方法 - -| 动作 | 说明 | -|------|------| -| 扫业界技能层 | Anthropic Skills(渐进披露 `SKILL.md`);SoK Agentic Skills 生命周期;ForgeAgent「能力铸造」;ACES Skill Lift | -| 扫成本/路由 | Switchcraft 工具调用路由;DSPy+GEPA 提示优化;工作流编译进小模型权重 | -| 扫安全 | MalSkillBench 运行时验证恶意技能;沙盒粒度讨论(per-skill / per-session) | -| 对照本仓 | A0–A4 / Wave B 已落地;沙盒 S0–S4 已落地;OKF + EKC + adaptive routing 现状 | - -**不修改** `doc/next/*`(手写真相源);本文件只进 `doc/research/`。 - ---- - -## 2. 业界态势(与 Marqdo 相关的收敛点) - -### 2.1 技能层取代「纯工具调用叙事」 - -| 来源 | 要点 | 对 Marqdo | -|------|------|-----------| -| Anthropic Agent Skills | 目录 + `SKILL.md`;元数据预载、正文按需;脚本可执行 | 形态近 OKF 任务包,但 Marqdo 技能 **本身可跑** | -| SoK Agentic Skills | 发现→练习→蒸馏→存储→组合→评测→更新;代码技能需沙盒 | 生命周期与 OKF promote / sandbox.run 对齐 | -| ForgeAgent | 生成能力 → 沙盒证明 → 信任复用;失败进回归隔离 | **验证后晋升** 正是 solidify / `llm_free` 缺的硬闸 | -| ACES | 有/无技能配对试验 → Skill Lift | 可作 Marqdo 评测 harness 指标 | - -### 2.2 成本:路由 + 编译 + 小模型 - -| 来源 | 要点 | 对 Marqdo | -|------|------|-----------| -| Switchcraft | 工具调用场景路由到最便宜仍正确的模型;报道大幅降本 | 已有 `marqdo \| small-llm \| llm \| auto`;可加 **工具步/试跑步** 细分 | -| DSPy / GEPA | 用反馈改写指令,小模型追上大模型 | 优化对象应是 **`.mq.md` 提示文档 / standing / 路由策略文件**,不是黑盒字符串 | -| 工作流编译进权重 | 程序化流程进小模型权重,上下文常数级 | 长期对应「高频 OKF 技能 → 专用小模型」;短期优先 **llm_free 源码路径** | - -### 2.3 安全:技能不可信 + 沙盒必验 - -恶意技能基准与 SoK 均强调:**技能说明与代码默认不可信**,须运行时隔离。Marqdo 新沙盒(默认拒 plugin/net/exec)正好是技能晋升前的证明场。 - ---- - -## 3. Marqdo 已有资产(优化起点) - -| 资产 | 现状 | 优化杠杆 | -|------|------|----------| -| 代码即文档 | `.mq.md` = 程序 = 提示工作面;GFM 表 / 链接取元 | 减少 json 胶水;让模型「看见」结构 | -| 写回 | `marqdo-out` 槽;step 默认写回 | 晋升证据、失败避坑 | -| OKF / agent-kb | 命中 / near / promote / solidify / `llm_free` | 复用率、降本主轴 | -| EKC / EFI | L0–L4 catalog;preflight REUSE/ADAPT/CREATE | 生成前先查工程知识 | -| Adaptive routing | marqdo / small-llm / llm / auto + policy 文件 | 再细分 sandbox 试跑 vs 开放推理 | -| Sandbox | CoW + capped `run`;`ext/ai/sandbox` | **试跑闸门**;未 commit 不污染仓库 | -| MCP / corpus | 证据工具,`authority=workbook` | 保持不升权威 | - ---- - -## 4. 问题分析(差距,不是功能羡慕) - -### P1 — 试跑与晋升未焊死 - -沙盒已能 CoW 试跑,但 **`agent.step` / `plan` 默认仍可直接改真实树**;OKF `llm_free` 晋升不强制「沙盒金样绿」。 -→ 风险:未验证技能进入复用池(业界 ForgeAgent / MalSkillBench 已证明此问题)。 - -### P2 — 技能形态双轨 - -Anthropic Skills = 文件夹 + 渐进披露;Marqdo = 可执行 `.mq.md` + OKF 类型。 -→ 机会:用 **OKF frontmatter + 可执行体** 统一,不必引入第二套 SKILL.md 权威;缺的是 **披露层级与验证元数据**(适用条件、fixture、sandbox profile)。 - -### P3 — 路由粒度偏粗 - -现有路由偏「整任务后端」;未区分:查 OKF / 写补丁 / 沙盒 `run` / 对外 HTTP。 -→ Switchcraft 启示:按 **步骤类型** 选模型,且「便宜模型推理 token 爆炸」要计入总成本。 - -### P4 — 评测未锁差异化 - -Wave B1 仍 Active:缺稳定 **Skill Lift / 沙盒证明率 / llm_free 命中率 / 文档可读性** 指标。 -→ 没有指标,优化会滑回「多调几次模型」。 - -### P5 — 代码即文档在 Agent 产出侧仍易腐化 - -模型仍可能吐 `json.set` 链、混用 EN/ZH API、跳过表结构。 -→ 沙盒可跑通语法,但 **风格门禁**(lint / preflight)未默认卡在 commit 前。 - -### P6 — 上下文与 EKC 未默认进每步 - -EFI / catalog 能力在,但 step 默认上下文仍可能偏源码切片,缺少「先 REUSE」硬门槛。 - -### P7 — LLM 表面与 Agent 成本账未统一 - -`llm.ask` / `stream` / usage 已有;Agent 侧缺 **按会话/技能的成本仪表盘** 写回文档(可 git 审)。 - ---- - -## 5. 优化目标函数(建议) - -在固定任务集上最大化: - -\[ -\begin{align*} -& \text{ReuseRate}(\text{OKF hit} + \text{llm\_free}) \\ -&+ \text{SandboxProofRate}(\text{试跑绿再 commit/promote}) \\ -&- \lambda_1 \cdot \text{TokenCost} - \lambda_2 \cdot \text{HostMutationsWithoutCommit} -\end{align*} -\] - -约束:权威真相仍是 `.mq.md`;不引入隐藏 TOOL 主循环;不改 `doc/next/*`。 - ---- - -## 6. 外部资料索引(抽样) - -| 类型 | 链接 | -|------|------| -| Skills | [Anthropic engineering: Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills) · [Claude Code skills](https://code.claude.com/docs/en/skills) · [agentskills / anthropics/skills](https://github.com/anthropics/skills) | -| 论文 | [SoK: Agentic Skills](https://arxiv.org/html/2602.20867) · [Skill Issue (repo SKILL 优化)](https://arxiv.org/html/2609.12742v1) · [ACES Skill Lift](https://arxiv.org/html/2608.20614) · [MalSkillBench](https://arxiv.org/html/2606.07131v3) · [Compiling workflows into weights](https://arxiv.org/html/2605.22502) | -| 开源/产品 | [ForgeAgent](https://github.com/Yashasm18/ForgeAgent) · [DSPy GEPA](https://dspy.ai/current/getting-started/gepa-optimization/) · [Switchcraft](https://www.microsoft.com/en-us/research/publication/switchcraft-ai-model-router-for-agentic-tool-calling/) | - ---- - -## 7. 结语 - -Marqdo 不缺「再一个 Agent SDK」;缺的是把 **文档真相、知识晋升、沙盒证明、模型路由** 收成可度量闭环。下一篇方案文档按问题编号给出可选方向与推荐波次,**不预设唯一银弹**。 diff --git a/doc/research/ai-agent-sandbox.md b/doc/research/ai-agent-sandbox.md deleted file mode 100755 index 0413b06..0000000 --- a/doc/research/ai-agent-sandbox.md +++ /dev/null @@ -1,392 +0,0 @@ -# 调研:AI 扩展库沙盒设计(执行隔离 × 工作区暂存 × 写回) - -| | | -|---|---| -| 状态 | **调研笔记 · 供 `ext/ai/*` 沙盒设计锁定参考**(**2026-10-16 修订**:纳入「AI 只生成 Marqdo」产品约束) | -| 日期 | 2026-10-16 | -| 范围 | 浏览器 WASM / WASI、OS 进程沙盒、容器 / microVM、CoW 叠加工作区、符号链接暂存方案;对照 Marqdo AI 栈 | -| 相关设计 | **[ext-ai-sandbox.md](../design/ext-ai-sandbox.md)** · **[roadmap/ext-ai-sandbox.md](../roadmap/ext-ai-sandbox.md)** · [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [stdlib-writeback.md](../design/stdlib-writeback.md) · [stdlib-subtask.md](../design/stdlib-subtask.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [adr/0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) · [ai-stack.md](../roadmap/ai-stack.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-modules.md](../design/stdlib-modules.md) | -| 姊妹调研 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) · [ai-agent-llm-optimize-2026-10.md](ai-agent-llm-optimize-2026-10.md) · [ext-ai-optimize.md](../design/ext-ai-optimize.md) | - ---- - -## 0. 一句话结论 - -**在「Agent 只生成 / 只执行 Marqdo(`.mq.md`)」这一产品约束下,Marqdo AI 沙盒应以 Wasm 为主沙盒——且必须是「内核 + `lib/*` + `ext/*`」可运行的完整运行时沙盒,而不是只跑光秃解释器。** - -锁定方向: - -1. **执行隔离 = Marqdo Wasm 运行时(与 ADR 0002 同构)** — deny-by-default 能力导入;**默认不授予** shell / 外联 / `dlopen` 原生插件。AI 产出面收窄到 Markdown 程序后,不必为通用 coding Agent 的「任意二进制」付沙盒税。 -2. **库完备性是验收线,不是加分项** — 沙盒内须能 `import lib/…` 与受支持的 `ext/…`;缺能力时 **显式失败**,禁止静默空成功(对齐 [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §5)。 -3. **工作区突变 = CoW / whiteout / 显式 commit**(应用层 VFS,必要时 overlay)— 「修改短暂不生效 → 确认写回」保留;**禁止以符号链接森林作为隔离边界**。 -4. **OS 沙盒 / microVM** — 降为 **逃逸舱 / 托管 Profile**:仅当显式启用 foreign、`subtask` 真子进程、或未来多租户托管时使用;**不是** Marqdo-only Agent 的默认主路径。 - -初稿曾按「通用 coding Agent 还需 shell」把 Wasm 与 bwrap 并列;在 Marqdo-only 约束下,主结论改为 **Wasm-first + 库完备 + CoW 写回**。 - ---- - -## 1. 调研方法与边界 - -### 1.1 做了什么 - -| 动作 | 说明 | -|------|------| -| 厂商/产品文档 | Anthropic Claude Code sandbox / `@anthropic-ai/sandbox-runtime`;VS Code Copilot agent sandboxing;Docker AI Sandboxes;Turso AgentFS CoW overlay;OpenSandbox isolation sessions;WASI / jco preview2-shim;VS Code for the Web WASM webshell | -| 工程对比文 | Northflank / Cosmonic 2026 agent sandbox 指南;gVisor vs Firecracker vs Docker 对比;ContainAI security comparison | -| 学术与标准 | USENIX SEC'22 *Provably-Safe Multilingual Software Sandboxing using WebAssembly*;KTH 论文 *Intra-process Fault Isolation Using WebAssembly*(SFI 通信开销);ACM TOSEM *Research on WebAssembly Runtimes: A Survey*(2025);WASI Design Principles(capability / 无 ambient authority) | -| 安全案例 | brig 项目挂载 symlink 逃逸(CVSS 8.2);Anthropic sandbox-runtime 对 bwrap bind 跟随 symlink 的修复;Docker Sandbox「direct mount vs clone」威胁说明 | -| 对照本仓 | `ext/ai/{llm,agent}`、`lib/writeback`、`lib/subtask`、ADR 0002 浏览器 WASM、`RunOptions.allow_fs_write` 默认关 | - -### 1.2 不做的 - -- 不把「发版用的容器镜像」与「Agent 工具沙盒」混为一谈。 -- 不宣称某一云厂商托管沙盒(E2B / Modal / Daytona)为 Marqdo 默认依赖。 -- 不修改 `doc/next/*`(手写真相源);本文件只进 `doc/research/`。 - -### 1.3 产品约束(修订要点):AI 只生成 Marqdo - -这是相对通用 coding Agent(Claude Code / Codex)的 **结构性好消息**: - -| 通用 Agent | Marqdo AI Agent(本调研采纳) | -|------------|------------------------------| -| 模型可产出 shell / Python / 任意仓库补丁 | 模型产出面收束为 **`.mq.md`(文档即程序)** | -| 沙盒必须兼容「整台开发机能力」 | 沙盒只需跑 **同构 Marqdo 运行时** | -| Wasm 往往只能罩住工具子集 | Wasm **可以**成为主执行边界 | -| 标准库 = 语言运行时 + OS 工具链 | 标准库 / 扩展 = **`lib/*.mq.md` + `ext/**`(+ 受控宿主能力)** | - -硬规则建议(后续 design 应写死): - -1. Agent 工具表 **不提供** 通用 `bash` / 任意语言 `exec`(除非显式 opt-in 逃逸舱,且另套 OS 沙盒)。 -2. Agent 改仓库的权威动作是 **写 / 修订 `.mq.md`(含写回块)**,经 CoW 会话再 `commit`。 -3. 运行 Agent 生成的程序 = 在沙盒里 `run` 该 `.mq.md`,且其 `import` 的 **lib 与 ext 必须可用或显式报不可用**。 - -### 1.4 威胁模型(在 Marqdo-only 下收窄) - -| 威胁 | 典型路径 | Marqdo-only 下的权重 | -|------|----------|----------------------| -| T1 提示注入 | 诱导读密钥、外泄、破坏 `.mq.md` | 仍高 — 靠能力拒绝 + CoW | -| T2 工具侧信道 | `subtask`/`foreign` 子进程 | **默认关闭**;opt-in 才升权 | -| T3 工作区即时破坏 | 直接写穿源树 | 靠 CoW;commit 闸门 | -| T4 挂载逃逸 | symlink / bind 打穿 | 仍相关 — **勿用 symlink 作 W 层** | -| T5 网络外泄 | `lib/net` / llm 出站 | 能力开关 + 域名策略 | -| T6 Wasm 宿主桥过宽 | `host_fs_*` / 插件桥过宽 | **主威胁** — 桥 = 权限表 | -| T7 库残缺假安全 | 沙盒能跑 `# main` 但 `import lib/fs` 怪崩或静默空 | **产品验收威胁** | - -**成功标准:** 失败域止于会话 upper + 已授予能力;真实工作区默认只读直至 commit;**代表性 `lib/*` 与 `ext/*` 金样在沙盒内可跑或得到明确 `unavailable in sandbox` 诊断**。 - ---- - -## 2. 先拆三个「沙盒放哪里」(Marqdo-only 版) - -业界「Harness / Workspace / Execution」三分法仍成立,但 **Execution 的内容变了**: - -```text -┌──────────────────────────────────────────────────────────┐ -│ Pattern H — Harness(编排环) │ -│ ext/ai/agent · parent Plan-and-Move ·(可选)MCP client │ -├──────────────────────────────────────────────────────────┤ -│ Pattern W — Workspace mutation(.mq.md 真相如何变) │ -│ CoW upper / whiteout / diff / commit → writeback │ -├──────────────────────────────────────────────────────────┤ -│ Pattern X — 执行 Agent 产出的 Marqdo 程序 │ -│ Wasm Marqdo runtime + embedded/packaged lib + sandboxed │ -│ ext 能力面(非「任意 shell」) │ -└──────────────────────────────────────────────────────────┘ -``` - -| Pattern | Marqdo 落点 | 沙盒要解决什么 | -|---------|-------------|----------------| -| H | `ext/ai/agent` | 编排是否持有过宽宿主权限;模型 I/O 与执行隔离 | -| W | `lib/writeback` · 工作簿 | 编辑是否立刻污染仓库;人审/父裁决后落盘 | -| X | **Wasm 内 `run` `.mq.md`** | 计算隔离;**lib/ext 能力是否完备且受控** | - -用户提案在 Marqdo-only 下:**Wasm 作 X 主底层是正确方向**;仍须改掉 symlink,并补上 **库完备性** 这一环。 - ---- - -## 3. 方案谱系(横向对比) - -> **读法(修订后):** 下表仍保留通用 Agent 对照。对 **Marqdo-only** 产品,请以 §0 / §5 / §6 的 Wasm-first 结论为准;本节 A/B 升权,F/G/H 降为逃逸舱或托管。 - -评分:● 强 / ◐ 中 / ○ 弱 / — 不适用。维度按「隔离强度」等客观属性;**产品适配**见 §5。 - -| 方案 | 隔离强度 | 启动成本 | 任意二进制 | 工作区暂存语义 | 与 Marqdo 契合 | 主要风险 | -|------|----------|----------|------------|----------------|----------------|----------| -| **A. 浏览器 WASM + 虚拟 FS** | ●(计算)◐(经桥的 FS) | ● | ○ | ◐(需自建 overlay) | ●(已有 ADR 0002) | 宿主桥过宽;无原生 toolchain | -| **B. WASI / Component Model(非浏览器亦可)** | ● | ● | ○(仅 WASI 目标) | ●(preopens + 自建 VFS) | ● | 工具链不全则需降级 | -| **C. 符号链接映射工作区 + 延迟写回** | ○ | ● | —(本身不是执行沙盒) | ◐(似是而非) | ○ | **symlink 逃逸是已知高危类** | -| **D. 应用层 CoW VFS(upper/lower/whiteout)** | ◐(逻辑) | ● | — | ● | ●● | 必须配合 X 层 OS 隔离 | -| **E. OS overlayfs / FUSE / AgentFS 式 CoW** | ●(配合命名空间) | ◐ | ●(在沙盒内) | ●● | ● | Linux/macOS 实现分叉;运维 | -| **F. bubblewrap / Seatbelt(Anthropic SRT 类)** | ● | ● | ● | ○(默认可写 cwd) | ● | 需另加 CoW 才有「暂不生效」 | -| **G. Docker / 硬化容器 / gVisor** | ◐→● | ◐ | ● | ◐(volume 策略) | ◐ | 共享内核或兼容性;重 | -| **H. microVM(Firecracker / Kata)** | ●● | ◐ | ● | ◐ | ○(本地 CLI 过重) | KVM/运维;适合多租户托管 | -| **I. 纯语言沙盒(RestrictedPython 等)** | ○ | ● | ○ | — | ○ | 对 Agent 工具链几乎无用 | - -### 3.1 A — 浏览器 WASM + 虚拟 FS - -**机制:** Wasm 线性内存 + 校验 + 仅经 import 碰宿主;FS 多为内存树 / OPFS / 经 JS bridge 的映射。Marqdo 已锁定「解释器进 WASM」(ADR 0002),默认 `allow_fs_write=false`。 - -**文献支撑:** Wasm 作为 SFI 窄腰(Bosamiya et al., USENIX SEC'22);进程内沙盒跨边界通信可比 IPC 快数量级(KTH Wasm-SFI 论文);WASI 明确 **capability / 无 ambient authority**。 - -**优点:** 与「代码即文档」浏览器运行同构;deny-by-default;适合跑 `.mq.md`、公式库、受控插件。 -**缺点:** 不能原生跑 `cargo test` / `npm` / 任意 shell;安全上限取决于 **bridge 授予了什么**;浏览器场景下「符号链接用户工作区」通常要落到 File System Access API 或服务端中继,**不是** POSIX symlink 语义。 - -**判定:** 在 **Marqdo-only** 约束下,作为 **Pattern X 主沙盒** 与浏览器内 Marqdo 的正解;完备性取决于 **lib 嵌入 + ext 能力桥**(§4.1),不取决于 shell。通用「任意二进制 Agent」场景下仍不够——但那不是本产品默认。 - -### 3.2 B — WASI / Component Model(CLI 宿主) - -**机制:** preopens 显式挂载;`WASIShim({ sandbox: { preopens, enableNetwork: false } })`(Bytecode Alliance jco);Component imports = 权限表。 - -**优点:** 与 Wasm 同族,可在 Node/Wasmtime 跑,不绑浏览器;能力模型清晰。 -**缺点:** 同 A,任意 Linux 工具链需「宿主机再包一层」或改编译目标。 - -**判定:** Marqdo **官方扩展 / 插件中可 Wasm 化的部分**应走这条;与 ADR 0002 一条能力谱。 - -### 3.3 C — 符号链接映射工作区(用户设想的核心) - -**设想:** 沙盒根下用 symlink 指向用户文件;写改暂存别处;确认后写回;删除 = 删 symlink。 - -**表面吸引力:** 零拷贝读、实现「像」有暂存。 - -**为何行业不把它当隔离原语:** - -1. **Bind/mount 跟随 symlink 是经典逃逸。** Anthropic `sandbox-runtime` 明确修复:`allowWrite` 若为指向界外的 symlink,bwrap `--bind` 会把真实目标变成可写(PR #138 类修复)。 -2. **项目挂载未解析 symlink 可致高危。** Endor Labs 披露 brig「project mount symlink traversal」(CVSS 8.2):Agent 在可写项目内把子目录换成指向 `/etc` 的 symlink,下一轮宿主机按字符串挂载即打穿。 -3. **「删除 = 删 symlink」语义错误。** 删链接只去掉别名,**不等于**对 lower 层文件的 whiteout;若链接指向真实文件且曾被打开写穿,删除链接也救不回。 -4. **写穿风险。** 若某路径被解析成真实 inode 且可写,暂存承诺立刻破产。 -5. **跨平台。** Windows junction/reparse、浏览器虚拟 FS、容器 bind,行为不一致。 - -**判定:** **否决作为 Marqdo 默认工作区隔离方案。** 允许在 **只读、已解析、拒绝可写路径上的 symlink 组件** 的前提下作实现细节,但不得当作安全边界叙事。 - -### 3.4 D — 应用层 CoW VFS(推荐作 W 层默认) - -**机制:** - -```text -lower = 真实工作区(只读打开 / 只读能力) -upper = 会话 delta(内存 map / 目录树 / SQLite blob) -whiteout = 逻辑删除集合 -view(path) = upper ?? (!whiteout && lower) -commit() = 把 upper/whiteout 应用到 lower(可经人审) -discard() = 丢弃会话 -diff() = 可审变更集 -``` - -与 Turso AgentFS、OpenSandbox `workspace.mode: overlay` 的 **语义同构**,但不强制 FUSE。 - -**与 Marqdo 对齐点:** - -| VFS 操作 | Marqdo 真相 | -|----------|-------------| -| `diff()` | 父 Agent / 人审材料;可进 view | -| `commit()` 文本结果 | `writeback.record` / 工作簿补丁 | -| `discard()` | 失败回合不污染仓库 | -| 只读 lower | 防止 T3 即时破坏 | - -**优点:** 纯用户态、可测、可嵌入 `plugins/agent`;不依赖 root/FUSE;金样可锁。 -**缺点:** 对 **沙盒内原生工具**(它们走真实 POSIX)不可见,除非再挂 E 或把工具 I/O 也改走 VFS API。 - -**判定:** **Pattern W 的默认实现。** - -### 3.5 E — OS CoW overlay(AgentFS / overlayfs / OpenSandbox) - -**机制(AgentFS 公开设计):** lower=宿主只读;upper=SQLite delta;删除=whiteout;Linux 用 FUSE+user/mount ns;macOS 用 NFS+`sandbox-exec`。OpenSandbox 默认 `overlay`,会话结束可丢 upper。 - -**优点:** 对 **任意 shell 工具**透明;「改了但宿主机 `git status` 仍干净」体验业界已验证。 -**缺点:** 平台依赖;FUSE 权限;与应用层 D 双实现成本。 - -**判定:** **当 Pattern X 需要真实 shell 且要求暂存对工具透明时**启用(Linux 优先);作为 D 的「native 加速后端」,不是替代 Wasm。 - -### 3.6 F — OS 进程沙盒(bwrap / Seatbelt / VS Code Copilot) - -**机制:** Anthropic:文件系统隔离 + **网络隔离(缺一不可)**;Linux bubblewrap + 代理;macOS Seatbelt。VS Code Copilot:同类依赖;路径分 readwrite / readonly / denied;明确「不是 VM,削弱授权即削弱边界」。 - -**优点:** 本地编码 Agent 的事实标准;覆盖子进程;启动轻。 -**缺点:** 默认可写 cwd → **没有**「暂不生效」;必须与 D/E 组合。Symlink 配置路径需解析与拒绝。 - -**判定:** **Pattern X(shell/外联/MCP)本地默认。** - -### 3.7 G / H — 容器与 microVM - -**共识:** 裸 Docker 共享内核,不适合作唯一边界应对不可信代码;gVisor 加强 syscall 拦截;Firecracker/Kata 适合多租户与高威胁(~125ms 级启动)。Docker AI Sandboxes 区分 **direct mount(即时写穿)** vs **clone(只读源 + 私有副本)**——后者才接近「确认后写回」。 - -**判定:** Marqdo **本地 CLI 默认不强制 microVM**;若未来 `ext` 提供托管执行 / 多租户,再把 H 定为服务端 Profile。G 可作为打包/CI Profile。 - -### 3.8 I — 语言级沙盒 - -对「Agent 会跑 shell」场景基本无效;仅作极窄解释器内嵌参考。 - ---- - -## 4. 专门评估:用户提案(修订) - -> 浏览器 WASM 作沙盒底层 + 符号链接用户工作区 + 修改短暂不生效 + 确认后写回 + 删除变删 symlink。 -> **补充约束:** AI 只生成 Marqdo;沙盒须能用标准库与扩展库。 - -| 子命题 | 评价 | 说明 | -|--------|------|------| -| Wasm 作主执行隔离 | **在 Marqdo-only 下正确** | 与 ADR 0002 同构;不必为 shell 全集付税 | -| 沙盒须含 lib + ext | **正确且关键** | 「能跑 `# main`」≠ 好沙盒;见 §4.1 | -| 「短暂不生效」 | **正确** | CoW / staging(方案 D,必要时 E) | -| 「确认后写回」 | **正确且极契合 Marqdo** | 与 writeback、父裁决、workbook 同一哲学 | -| 「symlink 映射工作区」 | **仍错误** | 与是否只用 Marqdo 无关;换 CoW/whiteout | -| 「删除 = 删 symlink」 | **仍错误** | 应为 whiteout;commit 时再对 lower 删除 | -| 「性能最好且安全性最高」 | **Wasm 主路径下接近成立** | 前提是桥最小权限 + CoW;symlink 仍拉低安全 | - -**修订后的正确表述:** - -> **以 Wasm Marqdo 运行时为主沙盒,打包/嵌入 `lib/*`,经能力桥提供受支持的 `ext/*`;工作区用 lower 只读 + upper/whiteout;人审/父裁决后 commit。符号链接不作隔离原语。shell/外联/原生 dlopen 默认关闭,仅作显式逃逸舱。** - -### 4.1 库完备性:什么叫「标准库和扩展库也能用」 - -沙盒若只能跑内置算术、却不能 `import lib/json` 或跑 `ext/ai/llm` 的离线金样,对 Agent 开发几乎无用——模型生成的 `.mq.md` **本来就会依赖 lib/ext**。 - -三类库进沙盒的路径不同: - -| 类别 | 今日形态 | 沙盒策略 | -|------|----------|----------| -| **纯 `.mq.md` 库**(多数 `lib/*`、部分 `ext` 门面) | 源码 import | **嵌入或会话导入图**(已有 `embedded_lib` / import map)— 必须默认可用 | -| **需宿主能力的 lib**(`fs` / `net` / `writeback` / `subtask` / `datetime.now`…) | `host_*` | **经能力表桥接**到会话 VFS / 受控 clock / 受控 fetch;默认最小集 | -| **原生 ABI 扩展**(`plugins/web`、`plugins/agent`、quantum 等 `.so`) | `plugin.load` + dlopen | 浏览器/Wasm **无 dlopen**(ADR 0002 N2)。沙盒内应:**纯 mq 门面 + Wasm 插件**、或 **宿主代执行且权限计入会话**、或 **显式 `unavailable`** — 禁止假装成功 | - -与 [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §5 对齐并扩展为 **Agent 沙盒能力矩阵(草案)**: - -| 能力 | 沙盒默认 | 备注 | -|------|----------|------| -| builtins / 表 / 控制流 / 对象 | ✓ | 内核 | -| `lib/math` `json` `table` `text` `collection`… | ✓ | embedded | -| `lib/fs` | ✓(仅会话 VFS) | 写进 upper;禁越出 root | -| `lib/writeback` | ✓(写会话内 `.mq.md`) | commit 后才进真实树 | -| `lib/net` / llm HTTP | 默认关 / 域名白名单 | 与 T5 | -| `lib/subtask` `fn=` | ✓(同 Wasm 会话) | | -| `lib/subtask` `path=`/`code=`/`lang=` | **默认拒** | 逃逸舱 + OS 沙盒 | -| `lib/plugin` + 原生 `.so` | **默认拒** | 改 Wasm 插件或宿主代执行 | -| `ext/ai/llm` · `ext/ai/agent`(mq 门面) | ✓(能力允许时) | 网络/密钥另授 | -| `ext/web` 服务端 listen/DB | **默认拒或只读 stub** | 完整 axum 不进沙盒;可测「装配/渲染」子集 | -| `ext/quantum` / `ext/linalg` | 目标 ✓ | 优先纯逻辑 / Wasm 插件,避免强依赖宿主机 .so | - -**验收金样建议(S 阶段):** -一套「沙盒烟囱」:`import` 常用 lib → 写会话文件 → writeback → `diff` → `commit`;再各挑一个 **纯逻辑 ext** 与一个 **需网络的 ext**(后者验证拒绝/白名单)。缺能力必须诊断含 `unavailable in sandbox`(或同等措辞)。 - ---- - -## 5. 综合评分(面向 Marqdo-only 产品) - -加权(修订):执行隔离契合 Marqdo-only 30%、**lib/ext 完备** 25%、与 writeback 真相 20%、实现成本 15%、跨端(CLI↔浏览器)10%。 -(「任意 shell 工具完备」不再作为主权重。) - -| 候选架构 | 分(相对) | 备注 | -|----------|------------|------| -| **A/B Wasm-first + D CoW + 库完备能力表** | **100(推荐)** | 主路径 | -| 同上 + 逃逸舱 F(opt-in shell) | 95 | 兼容少数 foreign 需求 | -| D + E + F(通用 coding 向) | 75 | 过重;非 Marqdo-only 默认 | -| 仅 F(可写 cwd) | 55 | 缺 CoW;且鼓励非 mq 工具 | -| 仅 A 但无 CoW、无 lib 嵌入 | 40 | 「半沙盒」 | -| 仅 C(symlink) | 20 | 否决 | -| 仅 H(人人 microVM) | 50 | 托管可选;本地默认过重 | - -**绝对「最硬」单点**仍可以是 microVM(托管 Profile)。 -**Marqdo「最合适」:** **Wasm 完整运行时沙盒(内核+lib+受控 ext)+ CoW 工作区 + commit 闸门**。 - ---- - -## 6. Marqdo 应采用的沙盒设计(推荐锁定草案 · 修订) - -### 6.1 产品形态 - -| Profile | 场景 | 执行(X) | 工作区(W) | -|---------|------|-----------|------------| -| **`mq-sandbox`(默认)** | Agent 生成并试跑 `.mq.md` | **Wasm Marqdo** + embedded `lib/*` + 能力桥 `ext` | 应用层 CoW;commit→真实树 / writeback | -| **`browser`** | 页内同构运行 | 同左(ADR 0002) | 内存/OPFS;无 POSIX symlink | -| **`escape`(显式)** | foreign / 真子进程 | OS 沙盒包一层 | 仍建议 CoW 可见 | -| **`hosted`(可选)** | 多租户 | Wasm 或 microVM | 会话隔离;凭证外置 | - -### 6.2 推荐架构图 - -```text - ┌──────────────────────────────────────┐ - │ ext/ai/agent (Harness) │ - │ 只产出 / 编排 .mq.md · 人审闸门 │ - └──────────────────┬───────────────────┘ - │ - ┌─────────────────────┼─────────────────────┐ - ▼ ▼ - ┌────────────────────┐ ┌────────────────────┐ - │ Workspace CoW (W) │ │ Marqdo Wasm (X) │ - │ lower = RO 工作区 │◄── fs/writeback ───│ 同构解释器/VM │ - │ upper / whiteout │ 能力导入 │ + embedded lib/* │ - │ diff·commit·discard│ │ + ext 能力面 │ - └─────────┬──────────┘ │ 默认: 无 shell/so │ - │ └────────────────────┘ - ▼ - 真实工作区 / <!-- marqdo-out --> - (代码即文档真相源) - - (可选)escape: subtask path|code|lang → OS sandbox -``` - -### 6.3 API 面建议(设计级,非立即实现) - -落点倾向:宿主能力进 `plugins/agent` / Wasm HostContext;作者面经 `ext/ai` 或 `lib`(**禁止** `ext/**` 直调 `host_*`)。 - -| 概念 | 语义 | -|------|------| -| `sandbox.open(root, mode=cow)` | 打开会话;lower 只读 | -| `sandbox.read/write/list/remove` | 经 view;remove → whiteout | -| `sandbox.diff` / `stat` | 供父 Agent / view | -| `sandbox.commit` / `discard` | 闸门;可要求 HITL | -| `sandbox.run(source\|path, caps=…)` | **Wasm 跑 Marqdo**;caps 声明 fs/net/llm/… | -| `sandbox.caps` / `inspect` | 列出已授能力与 lib/ext 可用性(对齐 `web.inspect` 哲学) | -| `sandbox.exec(...)` | **仅 escape Profile**;默认不存在于作者工具表 | - -与现有衔接: - -- `lib/*`:优先 embedded;FS/时间/网络走会话 caps。 -- `ext/*`:mq 门面可加载;原生插件默认不可用并诊断;长期可 Wasm 化的(linalg/quantum 逻辑)优先进 Wasm。 -- `lib/writeback`:写入会话内文件;`commit` 时进入真实树。 -- `lib/subtask`:默认仅 `fn=`;`path`/`code`/`lang` 要 escape。 - -### 6.4 硬禁(写入后续 design 时应保留) - -1. **不以 symlink 森林作为隔离或暂存原语。** -2. **不以「能跑空 `# main`」宣称沙盒完成** — 必须过 lib/ext 完备金样或显式 unavailable。 -3. **默认工具表不提供通用 shell / 任意语言 exec。** -4. **不默认可写 bind 真实工作区。** -5. **宿主桥 = 权限表**:未授能力不得 ambient 成功。 -6. **不静默降级**:缺 Wasm/能力时不得假装已隔离。 -7. **`ext/**` 不调 `host_*`**(既有宪法)。 - -### 6.5 分阶段落地(建议,非 `doc/next`) - -| 阶段 | 交付 | 验收线索 | -|------|------|----------| -| S0 | 威胁模型 + 本调研(含 Marqdo-only) | 本文 | -| S1 | Wasm `run` + embedded 核心 `lib/*` + 会话 VFS 读 | 常用 lib 金样在沙盒绿 | -| S2 | CoW upper/whiteout + diff/commit/discard | 未 commit 时宿主机 `git status` 干净 | -| S3 | writeback / 工作簿在会话内可写;commit 对齐 | agent step 金样 | -| S4 | caps:net/llm 白名单;`subtask` 非 fn 默认拒 | 诊断字符串稳定 | -| S5 | 代表性 ext(纯逻辑 + 需网)沙盒金样 | 完备性验收 | -| S6 | (可选)escape OS 沙盒;hosted microVM | 文档标明非默认 | - ---- - -## 7. 外部资料索引(抽样) - -| 类型 | 引用 | -|------|------| -| 产品 | [Anthropic: Claude Code sandboxing](https://www.anthropic.com/engineering/claude-code-sandboxing) · [sandbox-runtime](https://github.com/anthropic-experimental/sandbox-runtime) · [VS Code agent sandboxing](https://code.visualstudio.com/docs/agents/run/agent-sandboxing) · [Docker AI Sandboxes security](https://docs.docker.com/ai/sandboxes/security/) · [Turso AgentFS overlay](https://turso.tech/blog/agentfs-overlay) · [OpenSandbox isolation sessions](https://open-sandbox.ai/guides/isolation-sessions) | -| 标准 | [WASI Design Principles](https://github.com/WebAssembly/WASI/blob/main/docs/DesignPrinciples.md) · [jco preview2-shim sandbox](https://github.com/bytecodealliance/jco/blob/main/packages/preview2-shim/README.md) | -| 论文 | Bosamiya et al., *Provably-Safe Multilingual Software Sandboxing using WebAssembly*, USENIX Security 2022 · *Intra-process Fault Isolation Using WebAssembly* (KTH) · *Research on WebAssembly Runtimes: A Survey*, ACM TOSEM 2025 | -| 综述 | [Cosmonic: Choosing an AI agent sandbox (2026)](https://cosmonic.com/ai-sandbox/choosing-an-agent-sandbox/) · [Northflank: MicroVMs, gVisor & isolation](https://northflank.com/blog/how-to-sandbox-ai-agents) | -| 安全案例 | [brig symlink traversal / Endor Labs](https://www.endorlabs.com/learn/project-mount-symlink-traversal-in-brig-how-a-sandbox-reaches-host-directories-it-was-never-given) · Anthropic sandbox-runtime symlink bind 修复 | - ---- - -## 8. 结语 - -- **产品好消息:** Agent 只生成 Marqdo → **Wasm 主沙盒设计成立**,不必默认扛通用 shell Agent 的复杂度。 -- **好沙盒的定义:** 不只跑内核,还要 **`lib/*` 可用、`ext/*` 在能力表内可用或显式不可用**;再加 **CoW + commit** 保护仓库真相。 -- **仍要改掉的:** 符号链接当暂存/隔离;默认开放 foreign/dlopen;「空 main 能跑」就算完工。 -- **降级为非默认的:** bwrap/microVM — 留给 escape / hosted,而不是 Marqdo-only 主路径。 - -不急着实现。下一步若继续收敛,再开 `doc/design/ext-ai-sandbox.md` 把 **能力矩阵 + 库完备金样清单** 锁死即可;**仍不要改 `doc/next/*`**。 diff --git a/doc/research/ext-hosting-gaps.md b/doc/research/ext-hosting-gaps.md deleted file mode 100755 index ffc3498..0000000 --- a/doc/research/ext-hosting-gaps.md +++ /dev/null @@ -1,156 +0,0 @@ -# 调研:宿主集成缺口(浏览器中继 · HTTP→`##` · MCP Server · 同寿副端口 · 跨模块 DB/检索) - -| | | -|---|---| -| 状态 | **调研笔记 · 缺口盘点(H1–H4 stdio 已落地;H4b HTTP 可选)** | -| 日期 | 2026-09-07 | -| 触发 | 下游应用(对话站 / 求道类 Agent)在真实集成中被迫旁路 Python 脚本 | -| 基线版本 | **v0.3.6+**(宿主波次 H1–H4 见 [ext-hosting.md](../roadmap/ext-hosting.md)) | -| 相关设计 | [ext-web.md](../design/ext-web.md) · [ext-web-net.md](../design/ext-web-net.md) · [web-net-capabilities.md](../design/web-net-capabilities.md) · [ext-agent.md](../design/ext-agent.md) · [ext-abi.md](../design/ext-abi.md) | -| 邻近缺口 | [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md)(真 MCP **客户端**) | -| 补齐设计 | [ext-hosting-fill.md](../design/ext-hosting-fill.md) | -| 实现路线 | [ext-hosting.md](../roadmap/ext-hosting.md) | - ---- - -## 0. 一句话结论 - -`ext/web` 已能做**内容站 / CRUD / JSON-DB API / WS**;`ext/ai` 已能做**工作簿 Agent + 客户端 SSE 消费**。下游要把「浏览器同域流式 LLM」「请求触发任意 `##`」「MCP Server 被 IDE 拉起」合进**单一 Marqdo 进程**时,现有扩展**没有一等装配**——只能外挂缓冲代理 / CLI 子进程。缺口集中在 **扩展库作者面 + `plugins/web|agent` ABI**,不是语法层,也不是再开一套标准库。 - -**原则:** 旁路脚本只证明需求;关闭缺口必须把能力沉进 `ext/*` + `plugins/*`(可选极薄 `lib/` 编排),禁止把领域逻辑塞进 `src/host/`。 - ---- - -## 1. 已有基线(不是缺口) - -| 能力 | 现状 | 文档 / 金样 | -|------|------|-------------| -| CORS / 安全头 / gzip / body limit | `app.configure` | `tests/ext/web-middleware-smoke.mq.md` | -| JSON **DB select** 路由 | `configure json=` | `plugins/web/src/middleware.rs` | -| `/_form/*` SQL CRUD | `mount_form` | `plugins/web/src/form.rs` | -| 客户端缓冲 SSE | `lib/net.http_post_sse` → `ext/llm.complete stream=` | `tests/lib/net-openai-sse.mq.md` | -| 执行过程 SSE(非 LLM 中继) | `marqdo view` `/api/run` | [view.md](../design/view.md) §5 | -| Agent 证据工具(fixture MCP) | `corpus_search` / `mcp_list_tools` / `mcp_call` | A4;[agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) | -| 同模块 `# db` CRUD | `ext/web` `# db` | `examples/web-site/db/` | - ---- - -## 2. 缺口总表 - -| ID | 缺口 | 需要 | Marqdo 现状 | 典型旁路 | 解除条件 | -|----|------|------|-------------|----------|----------| -| **GAP-01** | 浏览器 → 上游 LLM **同域流式中继** | 绕过对方 CORS;**SSE 原样转发** | **`app.proxy` / `configure proxy=`**(H1) | ~~`llm_proxy.py`~~ | ✅ 已关闭 | -| **GAP-02** | HTTP 处理函数可调用用户 `##` | 请求内执行用户 `##`,返回 JSON | **`app.invoke` / `configure invoke=`**(H2) | ~~外挂 `marqdo run`~~ | ✅ 已关闭 | -| **GAP-03** | **MCP Server** 宿主 | IDE 拉起暴露工具 | **`agent.mcp_server` + `serve` stdio**(H4);HTTP=H4b | ~~`qdagent_mcp.py`~~ | ✅ stdio;HTTP 可选 | -| **GAP-04** | 同寿「第二监听端口」 | 与 `listen` 同寿中继 | 并入主端口(H1+H2) | ~~`mq.sh` 双进程~~ | ✅ won't | -| **GAP-05** | 跨模块 `db`;纯 run 用 corpus | 跨文件 `select`;CLI 检索 | 传递归查找 + `corpus_search` ensure_plugin(H3) | ~~db/index 导出~~ | ✅ 已关闭 | - -旁路脚本名来自下游集成仓库;**本仓库 `scripts/` 不含这些文件**——它们是需求证据,不是上游实现。 - ---- - -## 3. 分项说明 - -### 3.1 GAP-01 · 同域 SSE 中继 - -**问题** -浏览器页面跑在 `ext/web` 源上时,直连 OpenAI 兼容上游会撞 CORS;`lib/net.http_post_sse` 只在 **CLI/宿主侧缓冲整段流**,不能把字节边收边推回浏览器。 - -**现状边界** - -| 已有 | 缺什么 | -|------|--------| -| `app.configure cors=` | 解决的是**本站对外** CORS,不是替上游开 CORS | -| `http_post_sse` → `{status, events}` | **客户端消费**,非服务器中继 | -| `app.download` 对象流 | 存储下载,非上游 SSE | -| view `/api/run` SSE | Marqdo **执行事件**,非 LLM token 流 | - -**解除形态(产品)** -作者声明:`path` + `upstream`(或 env)+ 可选 header 白名单;监听端对浏览器返回 `Content-Type: text/event-stream`,chunk 原样或按 OpenAI SSE 帧转发。 - -### 3.2 GAP-02 · 路由 → `##` - -**问题** -对话沉淀、表单后写 `data/runs/*.mq.md`、触发 `lib/run.沉淀` 等,需要**同进程**执行用户函数。今天只有: - -1. 页面装配期 `call_lib_path`(compose,非每请求); -2. `/_form` / `json=` 的 **DB 专用** handler。 - -**解除形态(产品)** -声明式:`path` · `method` · `fn=lib.member` 或 `file=… ## name` · body→形参映射 · 返回值序列化为 JSON(错误码约定)。安全默认:仅允许入口模块已导入路径;禁止任意路径注入。 - -### 3.3 GAP-03 · MCP Server - -**问题** -A4 解决的是 Agent **调用** MCP 工具(且仍是 fixture)。下游要把 Marqdo 工作簿 **暴露为** MCP Server(stdio / Streamable HTTP),IDE 拉起后调 `qd_*`。 - -与 [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md)「真 MCP 客户端」正交:本缺口是 **Server 宿主**。 - -**解除形态(产品)** -`ext/ai`(或 `ext/mcp`)提供:`server tools=` 表(name → `.mq.md`/`##`);`serve stdio=` / `serve http port=`;工具结果仍可带 `authority=workbook`。 - -### 3.4 GAP-04 · 同寿副端口 - -**问题** -在 GAP-01/02 未并入主端口前,下游用第二端口跑代理。`app.listen` 同步阻塞,无「同进程再绑一个 TcpListener」的作者 API;只能 shell 并起另一运行时。 - -**解除形态(产品)** -优先:GAP-01/02 挂在同一 `listen` → **本缺口关闭**。备选:`app.attach` / `listen also=` 同 tokio 运行时附加服务(仅当必须隔离路径树)。 - -### 3.5 GAP-05 · 跨模块 DB 句柄与 corpus 可发现性 - -**问题** - -1. **类型分发:** 插件对象依赖 `_type` / 方法表;跨模块传回的 store 若丢类型或未注册方法,报 `unknown object type db`。同文件 `db/index.mq.md` 内 `## recent` 再导出 JSON 是现行绕过。 -2. **`agent_corpus_search`:** 注册在 `plugins/agent`;普通 `marqdo run` 未 `plugin.load` / 未构造 `# agent` 时不可用。导入 `ext/ai/agent.mq.md` 文本本身不保证原生插件已加载。 - -**解除形态(产品)** -句柄:跨模块返回值保留 `_type=db` 且方法分发查全局/插件表(修运行时或约定「只返回 url,调用方再 `web.db`」二选一,见补齐设计)。corpus:`plugin.load` 自动路径,或 `ext/ai` 导出独立 `## corpus_search` 并在调用前 `ensure_plugin`。 - ---- - -## 4. 归属判定(标准库 vs 扩展) - -沿用 [ext-web-net.md](../design/ext-web-net.md) / [web-net-capabilities.md](../design/web-net-capabilities.md) 边界: - -| 能力 | 归属 | 理由 | -|------|------|------| -| SSE **中继**路由、HTTP→`##`、副端口 | **`plugins/web` + `ext/web`** | 服务器结构 / 网站领域;axum 已在依赖链 | -| MCP **Server**、corpus 可发现 | **`plugins/agent` + `ext/ai`** | Agent/工具宿主;禁止塞 `src/host/` | -| 缓冲 SSE 客户端、解析 | 已有 **`lib/net`** | 不新增中继到 stdlib | -| 任意路径 shell 出去跑 `marqdo` | **刻意不做进核心** | 旁路脚本可留在下游;上游给一等 API 后废弃 | - ---- - -## 5. 优先级建议 - -| 优先级 | ID | 理由 | -|--------|-----|------| -| **高** | GAP-01 + GAP-02 | 去掉 Python 中继的主路径;浏览器站 + 沉淀闭环 | -| **高** | GAP-03 | IDE 生态入口;与「真 MCP 客户端」可并行设计、分波交付 | -| **中** | GAP-05 | 减少 `db/index` 与 bridge 胶水;影响面偏语言/插件加载 | -| **低(可随 01/02 关闭)** | GAP-04 | 并入主端口后自然消失 | - ---- - -## 6. 明确「不是缺口」 - -| 项 | 说明 | -|----|------| -| 内容站 W0–W7+P3 | 已完结;本清单不重开上传/RSS/RBAC | -| Mid M1–M6 | 通用原语已够;本清单不是再开 `lib/re` 一类 | -| 隐藏 JSON TOOL 主循环 | 与 Agent 宪法冲突 | -| Dense embedding 默认化 | 仍见 [okf-near-match.md](../roadmap/okf-near-match.md) | -| 浏览器手写业务 JS 代理 | 与 WASM 路线「作者零 JS」冲突;中继应在服务端 `ext/web` | - ---- - -## 7. 与其它文档 - -| 文档 | 关系 | -|------|------| -| [ext-hosting-fill.md](../design/ext-hosting-fill.md) | **补齐设计(作者 API + ABI)** | -| [ext-hosting.md](../roadmap/ext-hosting.md) | 实现波次 H0–H4 | -| [ext-web.md](../roadmap/ext-web.md) | 站点主线完结;本缺口为后续宿主波次 | -| [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) | 客户端真 MCP;与 GAP-03 Server 互补 | -| [web-asgi-servers-and-marqdo.md](../design/web-asgi-servers-and-marqdo.md) | 反代模型;中继仍在 Marqdo `listen` 内 | diff --git a/doc/research/ext-linalg-formula.md b/doc/research/ext-linalg-formula.md deleted file mode 100755 index 14cc59f..0000000 --- a/doc/research/ext-linalg-formula.md +++ /dev/null @@ -1,113 +0,0 @@ -# 调研:线性代数 × 公式类 × 展示 - -| | | -|---|---| -| 状态 | 调研纪要(为 [ext-linalg](../design/ext-linalg.md) 供输入) | -| 日期 | 2026-09-07 | -| 相关 | [stdlib-math.md](../design/stdlib-math.md) · [ext-quantum-q7.md](../design/ext-quantum-q7.md) · SymPy MatrixExpr · Symbolics.jl · LAFigureSpecs | - ---- - -## 1. 问题陈述 - -Marqdo 已有: - -- `Value::Formula` + `` `f` = `` + `$$…$$`(高中标量符号) -- `formula::Expr::Matrix`:**数值**稠密矩阵字面量(`[[…]]` / `\begin{pmatrix}`),供量子门核对与 view KaTeX -- `ext/quantum` Q7:**量子语境**下的密度矩阵 / Kronecker / 谱 / SVD 风格图(ABI) - -缺口:一门**经典线性代数**扩展——作者用**公式级矩阵表达式**写 \(A^\top A\)、\((X^\top X)^{-1}X^\top y\)、分块、Kronecker,在**不立刻展开成巨大稠密矩阵**的前提下做重写与化简,并在文档 / view 中**好看地呈现**分解与结构。 - ---- - -## 2. 业界对照 - -### 2.1 符号矩阵表达式(大规模优化的关键) - -| 系统 | 模型 | 对 Marqdo 的启示 | -|------|------|------------------| -| **SymPy `MatrixExpr`** | `MatrixSymbol(name, n, m)` + `MatMul` / `MatAdd` / `Inverse` / `Transpose` / `Trace` / `Determinant` / `BlockMatrix` / `KroneckerProduct`;`as_explicit()` 才展开 | **默认保持抽象**;形状元数据传播;显式求值是可选动作 | -| SymPy `block_collapse` | 分块表达式在块级化简,避免整块稠密展开 | 分块是教学与优化的第一公民 | -| SymPy Kronecker | `KroneckerProduct` 惰性 + `combine_kronecker` 规则 | Kronecker **绝不能**默认 `expand`(维数爆炸) | -| SymPy 矩阵求导 | 经 array expr 再收回 MatrixExpr;闭式导数 | v1 **不做**;记入远期 | -| **Symbolics.jl** | 「数组的符号」vs「符号数组」:后者 O(1) 表示整阵,保留 `A*B` 不展开 | 与 MatrixExpr 同构;强调 **shape / eltype 元数据** | -| NumPy / Eigen / nalgebra | 数值热路径,无公式树 | 对应 Marqdo **插件数值层**,不是文档作者主路径 | - -**结论:** 「公式类线性代数」= **抽象表达式 DAG + 形状检查 + 重写规则**;稠密数值是 `eval` / `as_explicit` 的终点,不是默认形态。 - -### 2.2 教学与展示(效果最好的做法) - -| 做法 | 来源 | 效果 | Marqdo 映射 | -|------|------|------|-------------| -| KaTeX / MathJax 渲染 `bmatrix` / `pmatrix` | SymPy `latex()` + Jupyter `init_printing` | 公式即排版;多式用 `display` 并列 | 既有 view `formula-card` + KaTeX | -| 标签化等式 `A = UΣV^\top` | 教材 / Qiita display+Math | 步骤可读 | `show` / writeback 多卡片 | -| **结构图**(SVD / QR / 消元轨) | [LAFigureSpecs](https://github.com/ea42gh/LAFigureSpecs) + matrixlayout;TeX `drawmatrix` | 比数字表更能讲「秩 / 零空间 / 对角结构」 | SVG `kind=svd|qr|ge|eig` | -| 热力图 / Hinton | Qiskit / QuTiP / 既有 quantum | 稠密数值矩阵的幅度/符号 | `kind=heatmap|hinton`(经典实/复) | -| 分块着色矩形 | CTAN `drawmatrix` | 零块 / 三角 / 带状一目了然 | `kind=structure`(形状示意图,可无元素值) | -| 仅打印 ASCII | CLI 默认 | 金样可断言 | `str` / `print` → 规范 ASCII / LaTeX 源 | - -**展示优先级(锁定建议):** - -1. **符号式**:始终可 `latex` → view KaTeX(不依赖数值) -2. **结构式 SVG**:分解 / 分块 / 秩示意(教学主图) -3. **数值热力图**:仅在 `eval` 后、维数可控时 -4. CLI:短 ASCII;大矩阵默认摘要 `m×n …` + 可选 `preview=` - -### 2.3 一门「够用」的线性代数库需要什么 - -按大学一学期 + 数据科学入门,能力桶: - -| 桶 | 内容 | 符号层 | 数值层 | -|----|------|--------|--------| -| A 构造 | 符号阵、常数阵、单位/零/对角、从 `$$` / 表 / list | ✅ | ✅ | -| B 代数 | 加减乘、转置、逆、伴随、幂、Kronecker、分块 | ✅ 重写 | ✅ | -| C 分解 | LU / QR / 特征 / SVD / Cholesky(对称) | 结果对象 + 结构图 | ✅ | -| D 系统 | `Ax=b`、最小二乘、伪逆 | 公式写法 + 数值解 | ✅ | -| E 度量 | 行列式、迹、秩、范数、条件数 | 部分可符号 | ✅ | -| F 展示 | latex / ASCII / SVG 结构 / heatmap | ✅ | ✅ | -| G 微积分 | 矩阵导数、Jacobian 积木 | 远期 | — | - -**不做(首版):** 稀疏专用格式、GPU、分布式、完整 CAS 证明、通用张量网络、与 `lib/math` 高中标量混成一个巨模块。 - ---- - -## 3. 与现有 Marqdo 的衔接点 - -| 已有 | 用法 | 扩展时注意 | -|------|------|------------| -| `$$` + Matrix 数值字面量 | 小门矩阵、手算核对 | 保留;符号阵用 `MatrixSymbol` 或 `matrix.symbol`,勿与数值 Matrix 混为一谈 | -| `lib/math` formula | 标量 simplify/diff/plot | **不**把大学线性代数塞进 `lib/math`(与 Q7 结论一致) | -| view KaTeX | formula-card | 符号 MatExpr 的 `latex` 字符串直接喂 KaTeX | -| `ext/quantum` Q7 linop | 量子密度 / 纠缠 | **经典 API 不复用 quantum 命名空间**;共享算法可在插件内私有复用,作者面分离 | -| `plugins/*` ABI | 重数值 / SVG | 稠密分解与大图走 `plugins/linalg` | -| GFM 表 | 数据即代码 | 矩阵输入:表或 `$$`;分解步骤:`@` 记录表 | - ---- - -## 4. 「大规模优化」具体指什么 - -在公式类语境下,优化 ≠ BLAS 微内核,而是: - -1. **惰性**:`A*B*C` 保持乘积树,直到 `eval` / `explicit` -2. **形状短路**:不相容维数在符号阶段报错,不跑数值 -3. **代数恒等**:`(A^{-1})^{-1}→A`,`(AB)^\top→B^\top A^\top`,`I*A→A`,分块 `block_collapse` -4. **禁止爆炸展开**:Kronecker / 高维符号积默认不 `expand` -5. **数值批处理**:同形状多 RHS、分解一次多用(`factorize` 对象) -6. **展示成本**:大矩阵不默认内嵌完整 KaTeX 数字阵;结构图 + 摘要 - ---- - -## 5. 推荐产品叙事(一句) - -**线性代数文档用公式写变换,用规则做化简,用结构图讲分解,用可控数值做验算——公式是一等公民,稠密矩阵是可选终点。** - ---- - -## 6. 参考链接 - -- SymPy Matrix Expressions: https://docs.sympy.org/latest/modules/matrices/expressions.html -- SymPy Matrix derivatives (远期): https://docs.sympy.org/dev/explanation/modules/matrices/matrixderivatives.html -- Symbolics.jl Symbolic Arrays: https://docs.sciml.ai/Symbolics/v6.54/manual/arrays/ -- LAFigureSpecs(教学结构图): https://github.com/ea42gh/LAFigureSpecs -- CTAN drawmatrix: 矩阵形状示意 -- 既有:`doc/design/stdlib-math.md` · `doc/design/ext-quantum-q7.md` diff --git a/doc/research/ext-web-customization-limits.md b/doc/research/ext-web-customization-limits.md deleted file mode 100755 index b669220..0000000 --- a/doc/research/ext-web-customization-limits.md +++ /dev/null @@ -1,154 +0,0 @@ -# `ext/web` 定制限制:开发者不易定制的问题盘点 - -| | | -|---|---| -| 状态 | **调研锁定(踩坑整理)** | -| 日期 | 2026-09-04 | -| 相关 | [ext-web.md](../design/ext-web.md) · [ext-web-net.md](../design/ext-web-net.md) · [web-net-capabilities.md](../design/web-net-capabilities.md) | -| 解决索引 | [../design/ext-web-customization/](../design/ext-web-customization/) | - -结合自研后台、样式迁移与响应式改造中的实际踩坑,整理当前 `plugins/web` + `ext/web` 对站点作者的**强占与难定制点**。本文只陈述问题与证据;逐项解法见解决索引。 - ---- - -## 0. 一句话 - -内置 `/admin` 壳、固定鉴权路径、注入式 `SHELL_CSS` 与四区栅格,让「只写 `.mq.md`」的产品路径在**自研后台 / 品牌主题 / 移动端**上反复撞墙;作者被迫旁路前缀 + `!important` + 前端 JS 兜底。 - ---- - -## 1. 路由与路径被框架强占 - -**现象** - -- `/admin` 及 `/admin/*` 整段保留,无法 `app.route` 注册自定义页(错误:`route path … is reserved`)。 -- `app.重定向` / `redirect` 目标若落在 reserved 前缀,同样被校验拒绝。 -- `后台=False`(`admin=False`)后,访问 `/admin/news` 等仍进内置壳,只显示 *Admin is disabled*,**不能**换成自研页。 -- 登录/登出硬绑 `/admin/login`、`/admin/logout`;登录成功硬编码 `Redirect::to("/admin")`,无法配置回跳到 `/desk`。 - -**代码证据** - -| 位置 | 行为 | -|------|------| -| `plugins/web/src/lib.rs` → `normalize_route_path` | `/admin`、`/_form`、`/_part`、`/static` 一律 reserved | -| `plugins/web/src/http.rs` | 始终挂 `/admin…` 路由;disabled 时仍 `admin_shell` + 文案 | -| 同文件 `admin_login_post` | 成功跳转写死 `/admin` | - -**结果** - -自研后台只能用 `/desk` 等旁路前缀;入口与鉴权路径分裂,还要靠前端 JS(`fetch('/admin/login')` 再 `replace('/desk')`)做跳转兜底。 - -→ 解决:[01-routes-and-admin-prefix.md](../design/ext-web-customization/01-routes-and-admin-prefix.md) - ---- - -## 2. 内置 `SHELL_CSS` 难以彻底覆盖 - -**现象** - -- 每个页面都会注入框架壳样式,例如 `body.has-sidebar { grid-template-columns:14rem 1fr; … }`、默认卡片/表单/侧栏色。 -- 规则**无媒体查询**、选择器优先级不低;站点主题选择器不够强时,小屏双列、侧栏占位等「幽灵布局」反复出现。 -- 首页有额外 class(如 `has-rail`)时碰巧盖住,其他页没有同类 class 就暴露——表现为「只修了首页」。 -- 实务上经常要 `!important` + 更高选择器,与「干净主题层」冲突。 - -**代码证据** - -| 位置 | 行为 | -|------|------| -| `plugins/web/src/render.rs` → `SHELL_CSS` | 常量内联进每个 HTML | -| 同文件壳渲染 | `<style>{SHELL_CSS}{extra}</style>`,主题只能接在后面 | - -→ 解决:[02-shell-css.md](../design/ext-web-customization/02-shell-css.md) - ---- - -## 3. 鉴权 / 门禁模型偏固定 - -**现象** - -- 未登录访问受保护路径:对 `/admin*` 会 **303 → 登录页**;对 `/desk` 等自定义路径往往是 **403 HTML**,行为不一致。 -- 门禁匹配偏宽:`path.starts_with` / `path_matches` 使 `/desk` 匹配 `/desk/login`,公开登录页易被误伤。 -- 默认鉴权挂上 `/admin*` → `admin`;`/admin-publish` 这类名字也会被当成 admin 域(`starts_with("/admin")`)。 -- 会话 cookie、CSRF、登录表单字段均固定在框架实现;难换登录 UI 或改成功落地页。 - -**代码证据** - -| 位置 | 行为 | -|------|------| -| `http.rs` → `rbac_middleware` | visitor + `/admin*` → redirect;其它 gate → 403 | -| `http.rs` → `path_matches` | 前缀匹配,无「精确路径 + 子路径排除」DSL | -| `lib.rs` → `web_app_auth` | 默认塞入 `/admin*` gate | - -→ 解决:[03-auth-gates.md](../design/ext-web-customization/03-auth-gates.md) - ---- - -## 4. 样式作者体验受限 - -**现象** - -- 样式表是 GFM 表格;含 `/` 的值必须加引号(如 `"1 / 5"`),否则单元格表达式把 `/` 当除法(曾出现 `grid-column` 变成 `0`)。 -- `@keyframes`、复杂选择器、多层媒体查询(`min-width` and `max-width`)表达能力有限,装配顺序要小心。 -- 主题 CSS 与 `SHELL_CSS` 同页串联,级联顺序不透明,调试成本高。 -- 响应式不能指望框架;壳层几乎不提供移动端抽屉/折叠。 - -→ 解决:[04-stylesheet-authoring.md](../design/ext-web-customization/04-stylesheet-authoring.md) - ---- - -## 5. 页面壳与插槽约定僵硬 - -**现象** - -- 壳结构固定为 `topnav` / `side` / `main` / `foot` 栅格命名区。 -- 侧栏一旦装配,`body` 即 `has-sidebar`,套上框架双列;杂志风单列、抽屉必须自己拆布局。 -- 组件表驱动导航,难做运行时条件导航(小屏合并顶栏+侧栏),通常再补 `theme.js`。 - -→ 解决:[05-page-shell-slots.md](../design/ext-web-customization/05-page-shell-slots.md) - ---- - -## 6. 后台 CRUD 与表单能力边界 - -**现象** - -- 内置 admin 是通用表管理,不是产品级 CMS;**关了又占着 `/admin` 路径**(与 §1 叠加)。 -- 表单以声明式字段表为主;Markdown 分栏、专栏元数据联动等只能外挂 JS。 -- 列表「链接前缀」等约定简单;编辑/新建状态机常靠前端拼(`?id=`、`?new=1`)。 - -→ 解决:[06-admin-crud-forms.md](../design/ext-web-customization/06-admin-crud-forms.md) - ---- - -## 7. 静态资源与脚本生命周期 - -**现象** - -- 头资源脚本常在 `<head>` **同步**加载;若脚本假设 DOM 已就绪会直接失败(登录页曾因此不跳转)。 -- 缓存靠 `?v=` 手动 bump;无构建管线时易出现「改了 JS 浏览器仍用旧文件」。 - -→ 解决:[07-assets-script-lifecycle.md](../design/ext-web-customization/07-assets-script-lifecycle.md) - ---- - -## 8. 扩展与部署耦合 - -**现象** - -- 能力依赖 web 插件 ABI / Marqdo 版本(如 0.3.2 起的样式引号约定);升级要同步 Docker / 本机二进制。 -- 定制若依赖改插件源码(放宽 `/admin` reserved、可配置 login redirect),就脱离「只写 `.mq.md`」的产品路径,维护成本陡增。 - -→ 解决:[08-ext-deploy-coupling.md](../design/ext-web-customization/08-ext-deploy-coupling.md) - ---- - -## 9. 优先级建议(给实现排期) - -| 优先级 | 项 | 理由 | -|--------|-----|------| -| P0 | §1 路由/前缀 + §3 鉴权一致 | 阻塞自研后台产品路径 | -| P1 | §2 SHELL_CSS + §5 壳布局 | 阻塞品牌主题与响应式 | -| P2 | §4 样式作者体验 + §7 脚本生命周期 | 降低日常踩坑,不改架构也能缓解 | -| P3 | §6 CRUD 边界 + §8 部署耦合 | 文档/约定/可选增强为主 | - -详细验收与实现切片见解决索引 README。 diff --git a/doc/research/foreign-notebook-decisions.md b/doc/research/foreign-notebook-decisions.md deleted file mode 100755 index 6cba377..0000000 --- a/doc/research/foreign-notebook-decisions.md +++ /dev/null @@ -1,290 +0,0 @@ -# 外联内核 · 文档会话 · 决策记录 - -| | | -|---|---| -| 状态 | **Decided(由用户授权代为拍板)** | -| 日期 | 2026-10-17 | -| 范围 | 外联库(`lib/foreign`)· 外联内核 · 文档会话 · view notebook 交互 | -| 相关 | [foreign-kernel.md](../design/foreign-kernel.md) · [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-v2.md](../roadmap/foreign-v2.md) · [notebook-session.md](../roadmap/notebook-session.md) | -| 核心表面 Δ | **无**——不新增 Markdown 标记;只使用既有 `#` / `##` / 表格 / 反引号 | - -> 本文件记录「为什么这样设计」。实现细节分别落在设计文档与路线图中;本文件不重复 API 表。 - ---- - -## 0. 背景与授权 - -用户的核心诉求: - -1. Marqdo 的本质是 **代码即文档、文档即知识库**;`.mq.md` 天生兼容 Markdown / OKF 知识库。 -2. 外联库的初衷是**对标 Jupyter**:让文档与代码并行有用;但 Jupyter 有 Git 难跟踪、隐藏状态、execution_count 噪声等问题,Marqdo 要解决并超越。 -3. `view` 模式天然适合这种交互(已有执行按钮、结构视图、writeback、trace)。 -4. 之前外联库功能太单一;接下来必须支持: - - 多个代码块共享外联状态; - - 单步执行; - - 切换哪些外联内核共享状态; - - Marqdo 的状态/变量被外联使用; - - 外联的状态/变量被 Marqdo 使用。 -5. 用户要求:**安全第一、效果最好、功能最强悍、不降级**;充分测试;每份讨论落成详细文档;文档提交并推送后再开发。 -6. 用户强调:**设计语法不要用代码思维**,语法要天然可读。 - -本文档 = 对该授权的决策记录。后续实现若与本文冲突,先改本文并说明理由。 - ---- - -## 1. 关键结论 - -### 结论 A:外联库不是“跑 Python 的函数”,而是多语言内核运行时 - -`lib/foreign` 的定位升级为: - -> **文档运行时与外部语言运行时之间的内核/会话层**:启动内核、执行代码单元、持久化状态、双向类型桥、生命周期与安全。 - -它不等同于 `subtask`(一次性并发任务),也不等同于 `writeback`(输出持久化)。 - -### 结论 B:Jupyter 级体验需要两层,不是一层 - -| 层 | 名称 | 责任 | -|---|---|---| -| **F** | Foreign Kernel Runtime | 内核进程、语言发现/注册、JSON 桥、会话、安全、记录 | -| **D** | Document Session | 文档会话、cell index、kernel 分配、单步、状态面板、执行日志、view 交互 | - -上一版 `foreign-v2` 只覆盖 F。共享状态 / 单步 / 切换内核属于 D。两层分开设计、分开验收。 - -### 结论 C:Hybrid 执行模型 - -- **Program mode(规范模式)**:`marqdo run` / CI / 可复现执行。文档是程序;外联通过显式 `foreign.session_*` / `call` 编排;结果可重复。 -- **View cells(交互面)**:`view` 中按 cell 执行、单步、切换内核、查看状态。适合探索,不默认写入文档;不是第二个 CLI 模式。 -- 两者共享同一个内核运行时与同一套 cell 索引;view cells 是 program execution 的**交互镜头**,不是替代品。 - -理由:如果让 cell 执行取代文档程序语义,Marqdo 就退化成 Jupyter;如果只有 Program mode,就失去 Jupyter 的即时反馈。Hybrid 同时保留两者。 - -### 结论 D:命名内核;同内核共享,跨内核/跨语言显式传值 - -- 一个文档可以有多个命名内核:`py:分析`、`py:绘图`、`js:前端`。 -- 同一内核的 cell 共享全局状态。 -- 不同内核(即使同语言)默认隔离。 -- 不同语言不共享进程内存;只能通过 JSON / 文件 / DB 显式交换。 -- 默认每个文档、每种语言一个 `default` 内核;命名内核按需开启。 -- 跨文档默认隔离;全局内核以后再做。 - -### 结论 E:三种单步,分阶段实现 - -| 单步 | 含义 | 版本 | -|---|---|---| -| **Cell step** | 执行下一个代码单元,状态保留 | v2 必做 | -| **Marqdo statement step** | 逐条执行 Marqdo 语句,查看变量 | v2 复用现有 debugger | -| **Foreign line step** | 进入 Python/Node 逐行 | v2 不做;后续接 DAP/pdb/debugpy | - -- 外联 cell 在 statement step 中是原子操作。 -- “Step into foreign” 是独立项目,不能混入首版。 - -### 结论 F:显式状态桥优先,不做隐式自动镜像 - -- 默认通过 `session_set` / `session_get` / `call input` / `call result` 交换,JSON 拷贝。 -- 不默认把 Marqdo 变量自动注入 Python,也不默认把 Python 变量自动写回 Marqdo。 -- 原因:命名冲突、Secret 泄漏、类型丢失、隐式状态、不可复现、大对象拷贝。 -- 后续可选 `mirror=True`:只同步 `mq_` 前缀、白名单类型、按值拷贝,且默认关闭。 - -### 结论 G:不新增围栏元数据;用文档原生的“内核表 / 会话表” - -- 拒绝 ` ```python kernel=分析 `、`name=`、YAML kernel 配置、魔法注释。 -- 使用既有绑定表 + GFM 表格(放在 `# main` 体内,与 cell 同作用域): - - `内核表` / `kernels` - - `会话表` / `session` -- 表格是**声明**,不是自动执行;只有 Run / Step 触发。 -- 解析器不变,核心表面零增长;view/session 读取这两个约定绑定。 - -理由:`kernel=` 是 IDE 配置思维,破坏“代码即文档”;绑定表是文档目录/执行计划,人可读、机器可解析,且不把文档拆成多个对象作用域。 - -### 结论 H:输出默认临时,writeback 显式;状态不写进 `.mq.md` - -- View cells 的输出默认只在 view 中显示,不修改文档。 -- 需要持久化时显式 writeback(沿用 `<!-- marqdo-out … -->`),可 Git 跟踪、可忽略。 -- 执行日志放 `.marqdo/sessions/…`(默认 git 忽略)。 -- 不把 execution_count / kernel 状态 / base64 输出写进 `.mq.md`。 - -### 结论 I:首批会话语言 Python + Node - -- Python:Jupyter 的主场景,优先支持。 -- Node:v1 已有基础,且当前开发环境可用。 -- 15 个语言预设继续用于**一次性执行**;R / Julia / Ruby 等的持久会话通过自定义 bootstrap 逐步加入,不阻塞首版。 - -### 结论 J:v2 不做“外联回调 Marqdo 函数” - -- 状态/值双向:✅ -- Marqdo 代码作为源码文本传给外联:✅(外联按自己的语言执行) -- 外联代码调用 Marqdo `##` 函数:❌ v2;后续做 callback RPC(控制通道 + 重入 + 死锁处理)。 -- 原因:重入解释器、线程安全、死锁、安全面都远超首版范围;先把数据/状态桥做稳。 - -### 结论 K:安全与测试是一等公民 - -- 所有 spawn / probe / session 入口检查 `allow_exec`。 -- 进程组超时清理;有界 IO;stdin 写线程;输出上限;并发上限。 -- 每文档生命周期,关闭即 kill;跨文档不共享。 -- 测试:node + bash 为最小环境主路径;python 条件覆盖;单元测试覆盖切分/模板/JSON;金样例覆盖记录/超时/会话/并行/状态桥。 - ---- - -## 2. 逐问逐答(保留原始讨论颗粒度) - -### Q1:外联库是做什么的? - -**答**:它是文档的多语言执行总线,负责: - -1. 内核生命周期(启动/重启/中断/关闭/切换); -2. cell 执行(源码 → kernel → stdout/stderr/result); -3. 状态持久化(同一 kernel 的 cell 共享命名空间); -4. 类型桥(Marqdo Value ↔ JSON ↔ 语言对象); -5. 环境发现与配置(probe/register/venv/config); -6. 记录与安全(耗时、退出码、截断、cap、清理)。 - -它不负责:文档语法(Language)、UI 布局(Document)、知识目录(Catalog)。这些由相邻层提供。 - -### Q2:是否支持外联库共享状态? - -**答**:支持,但严格分层: - -- 同一 kernel:共享全局变量。 -- 同一语言不同 kernel:隔离。 -- 不同语言:不共享内存,只能显式传值。 -- Marqdo ↔ kernel:显式桥。 -- 跨文档:默认隔离。 - -### Q3:能否单步执行? - -**答**:能,但要定义清楚: - -- cell step:v2 做。 -- Marqdo statement step:现有 debugger 已有,v2 接入 view。 -- foreign line step:v2 不做;后续 DAP。 - -### Q4:能否切换哪几个外联库共享状态? - -**答**:能,用命名内核: - -- `py:分析` 下所有 cell 共享; -- `py:绘图` 隔离; -- 每个 cell 有 kernel 归属; -- 切换归属不迁移状态,需要重跑; -- 跨语言用显式桥。 - -### Q5:Marqdo 的代码/状态能否被外联使用?外联的状态/变量能否被 Marqdo 使用? - -**答**: - -- Marqdo 值 → 外联:`session_set` / `call input` / `session_eval input`;JSON 拷贝。 -- 外联值 → Marqdo:`session_get` / `call` 返回值;赋值。 -- Marqdo 代码 → 外联:作为源码文本传递;外联按自己的语言执行,不是 Marqdo 语义。 -- 外联代码 → Marqdo 函数:v2 不做,后续 callback RPC。 -- 自动镜像:v2 不做,后续可选。 - -### Q6:如何超越 Jupyter? - -**答**:不是“功能更多”,而是把 Jupyter 的隐藏面变成显式面: - -| Jupyter | Marqdo | -|---|---| -| `.ipynb` JSON 混入输出/execution_count | `.mq.md` 源码干净;输出可选 writeback | -| 隐藏 kernel 状态 | 内核 + 文档会话 + 状态面板 + journal | -| 一个 notebook 一个 kernel | 命名内核 + 每 cell 归属 + 显式桥 | -| 只有 cell step | cell step + statement step | -| 手动 Run All | restart & run all + dirty/stale + replay | -| 无知识目录 | OKF / catalog;cell 是可发现知识单元 | - ---- - -## 3. 被拒绝的方案 - -| 方案 | 为什么拒绝 | -|---|---| -| 围栏元数据 ` ```python kernel=分析 ` | Language 层变更;需 ADR;把文档语法变成 IDE 配置;破坏可读性 | -| YAML `kernels:` 配置 | 代码思维;与“文档即知识”冲突;表格已能表达 | -| 魔法 HTML 注释 `<!-- kernel: 分析 -->` | 不可见、易漂移、读者不可见;违背可读性 | -| 自然语言 prose 解析(“把 xs 送给分析内核”) | 非确定性;误触发;违背“叙述默认安全” | -| 隐式自动镜像变量 | 命名冲突、Secret 泄漏、类型丢失、不可复现 | -| 一个文档一个 kernel | 无法做多语言/隔离实验,正是 Jupyter 的局限 | -| 把状态/输出写进 `.mq.md` | Git 噪声;正是要解决的 Jupyter 问题 | -| cell 自动执行 | 违背“未标记即叙述/未调用即数据”;破坏安全默认 | -| v2 做 foreign→Marqdo callback | 重入/死锁/安全复杂;应先稳定数据桥 | - ---- - -## 4. 已锁定的实现边界 - -### v2 必做 - -- F0 安全执行内核 + `invoke` 记录 + `exec` 门禁 + 有界 IO + 进程组超时。 -- F1 语言注册/发现:15 预设、`probe`、`register`、`unset`、配置、venv。 -- F2 JSON 桥:`call` / `run_many` / `output` / `result`。 -- F3 持久内核:Python / Node `session_open/eval/close/list`。 -- F3.5 状态桥:`session_set/get/names`。 -- D1 文档会话服务端:cell index、kernel registry、journal、open/close。 -- D2 view notebook:内核选择、Run/Step/Run All/Restart、状态面板、dirty/stale。 -- D3 Marqdo statement step 接入 view。 -- D4 语法:`内核表` / `会话表` 解析与校验。 -- D5 测试、文档、catalog、CHANGELOG。 - -### v2 不做(明确记录,避免“降级”误解) - -- Foreign line-level step(接 DAP 是后续项目)。 -- Foreign → Marqdo 函数 callback。 -- 跨语言共享对象引用 / 共享内存。 -- 全进程快照(只做变量级 JSON 快照)。 -- 跨文档全局内核。 -- 自动安装依赖。 -- 浏览器 wasm 外联。 - -这些不是“砍掉”,而是**独立阶段**;v2 先把内核/会话/桥做稳。 - ---- - -## 5. 风险与对策 - -| 风险 | 对策 | -|---|---| -| 会话协议脆弱(原生 fd 输出、缓冲) | bootstrap 用原始 stdout;Python `-u`;Node 保存原始 write;超时 kill;文档标注限制 | -| 状态桥隐式化导致不可复现 | 默认显式;`mirror` 后续且默认关 | -| 多内核进程泄漏 | 每文档生命周期;Drop kill;进程组;session_close;测试 | -| 大对象 JSON 拷贝慢 | v2 明确拷贝语义;后续 Arrow/Parquet/文件句柄 | -| `内核表` / `会话表` 名称冲突 | 文档声明为保留绑定名;后续可用 frontmatter 指针重命名 | -| 表格行/单元不一致 | 明确诊断:未声明内核、重复单元、语言不匹配、未入会话 | -| 交互执行顺序混乱 | journal + dirty/stale + Run All canonical + 执行序号 | -| 安全(Secret/环境) | Secret 不进 JSON;env 显式交付;状态面板打码;exec cap | -| 测试环境无 Python | node/bash 主路径;python 条件测试;协议单测 | - ---- - -## 6. 术语表(统一中英文) - -| 中文 | English | 含义 | -|---|---|---| -| 外联内核 | foreign kernel | 外部语言进程 | -| 外联会话 | foreign session | 内核实例 + 命名空间 | -| 文档会话 | document session | Marqdo 状态 + 内核注册表 + journal | -| 代码单元 | cell | 绑定名的代码围栏 | -| 内核归属 | kernel assignment | cell → kernel | -| 状态桥 | state bridge | Marqdo 值 ↔ 内核变量 | -| 执行日志 | execution journal | 执行顺序/耗时/结果/hash | -| 新鲜 | clean | 源码未变且已成功执行 | -| 过期 | dirty | 源码变了,结果可能过期 | -| 失效 | stale | 上游依赖变了,需要重跑 | -| 规范执行 | canonical run | 重启后按会话表顺序 Run All | - ---- - -## 7. 决策时间线 - -1. 用户提出外联库对标 Jupyter、共享状态、单步、切换、双向使用。 -2. Agent 阅读 `src/host/foreign.rs`、`src/view`、`src/debug`、`src/host/subtask.rs`、`lib/foreign`、设计文档。 -3. Agent 回答:需要 F + D 两层;单步分三种;共享分三层;显式桥。 -4. 用户授权 Agent 拍板:安全、最强、不降级、充分测试、文档先行、提交推送后开发。 -5. Agent 锁定本文件 §1 的 A–K 结论,进入文档编写与实现。 - ---- - -## 8. 后续变更流程 - -- 任何与本文冲突的实现,先改本文并写明「变更理由 / 影响 / 迁移」。 -- 新增核心语法(任何新标记)必须走 `doc/adr/` + `core-surface.md`;本文所有语法均为既有标记的组合。 -- 新增会话语言、跨语言数据平面、callback RPC,各自开独立设计文档,不塞进本文件。 diff --git a/doc/research/occlusion-vs-executable-knowledge-2026-10.md b/doc/research/occlusion-vs-executable-knowledge-2026-10.md deleted file mode 100755 index 3d21fba..0000000 --- a/doc/research/occlusion-vs-executable-knowledge-2026-10.md +++ /dev/null @@ -1,1148 +0,0 @@ -# 遮蔽语法与可执行知识:一次以证据为准的复核 - -| | | -|---|---| -| 状态 | **Research · Open(待决策)** | -| 日期 | 2026-10-23 | -| 复核对象 | `marqdo 2.0.0`(`target/release/marqdo`,2026-10-22 提交 `bcfc763`) | -| 触发 | 用户提出:`[]()` 遮蔽语法可能是「AI 时代编程语言的内化核心能力」的入口,并用「李白文档 + main 文档」的跨文档引用作为证据 | -| 方法 | 设计文档 + 源码 + CLI 实测 + `--dump-ast` + 语料统计;以**可复现行为**优先于文档声明 | -| 关联 | [occlusion-syntax.md](../design/occlusion-syntax.md) · [occlusion-description-and-search.md](../design/occlusion-description-and-search.md) · [bracket-as-label-evaluation.md](../design/bracket-as-label-evaluation.md) · [module-namespace.md](../design/module-namespace.md) · [objects.md](../design/objects.md) · [engineering-knowledge.md](../design/engineering-knowledge.md) · [change-m7-migration.md](../design/change-m7-migration.md) | -| 后续 | **[link-syntax.md](../design/link-syntax.md)** — 把本文的评判落成 v2.1 设计声明(类-函数调用 / 项目类索引 / LinkInfo / view / 图边) | - -**目录**:0 摘要 · 1 问题/方法 · 2 `[]()` 的实现事实 · 3 两文档复现 · 4 逐条评判 · 5 三个概念混淆 · 6 遮蔽的价值与代价 · 7 工程规范硬证据 · 8 能力阶梯与提案 · 9 路线图与验收 · 10 结论 · 附录 A 复现 · B 证据索引 · C 术语 · D 局限 - -> **2026-10-23 补记(用户澄清)**:`[]()` **不新增语法**;`()` 就是已有代码,`#`/`##` 是类/函数,`类.函数` 是类调用。本文 §4.3/§5 的「呈现层」判断针对 **v2.0.0 实现**;原始设计缺的是类函数语义与跨文档类索引,不是新语法。设计声明见 [link-syntax.md](../design/link-syntax.md)。 - ---- - -## 0. 摘要 - -### 0.1 一句话结论 - -**你的方向是对的,但证据不支持「遮蔽语法已经是这个方向的核心」。** - -- **可执行知识**是 Marqdo 值得追求的核心方向; -- **`[]()` 遮蔽**是**呈现层**语法,不是语义层能力:`[描述](实现)` 的值恒等于 `实现`,标签不参与绑定、作用域、类型、求值; -- **你给的两文档例子按现状不可执行**:`run` 退出 0、无输出,`check` 通过;`--dump-ast` 显示 `# main` 是空对象、`# 李白` 的方法体为空; -- 你的第三句话——**「工程规范做得不够好」**——**成立**,而且有可复现的硬证据;但根因不是「遮蔽还不够多」,而是「引用、解析、静态校验」这条闭环没有建立。 - -一句话建议: - -> **把遮蔽降级为表层工效学,把「引用 / 解析 / 校验」升级为语言核心。** -> 知识要可执行,先给它**地址**、**解析器**和**验证器**,再谈链接长什么样。 - -### 0.2 五条判断,先给结论 - -| # | 你的判断 | 证据结论 | 判定 | -|---|---------|---------|------| -| 1 | Marqdo 已经有 AI 时代的东西 | 有 LLM / agent / MCP / WASM / catalog / EKC / view,但大多是**生态层**,不是语言核心 | ✅ 基本成立 | -| 2 | 接下来需要「内化」的核心能力 | 方向正确;缺的确实是核心,但不是遮蔽 | ✅ 成立 | -| 3 | `[]()` 遮蔽可以充当那个核心能力 | 它是透明的文档注解,**不增加可计算性**,也不提供跨文档解析 | ❌ 不成立(层级混淆) | -| 4 | 两文档例子证明可执行知识的威力 | 例子没有进入执行层;方法体为空;目标不是可调用的静态事实 | ❌ 作为证据不成立 | -| 5 | 设计已经到了这一步,只是工程规范不够好 | 默认仍是 Classic;只有 90/886 文件启用;`check` 不做名字解析(只查契约+标签);知识图不从 Markdown 链接取边 | ⚠️ 后半句成立,前半句不成立 | - -### 0.3 四个最重要的发现 - -1. **你的例子实际说明的是「叙述默认安全」,而不是「可执行知识」。** - `[李白的出生年份](李白.李白的出生年份)` 在正文里是 Markdown 链接,不是代码;`--dump-ast` 里 `# main` 完全为空。`run` 的退出码 0 只表示「没有东西可执行」,不表示「链接执行成功」。 - -2. **`[]()` 的语义是恒等式 `[d](e) ≡ e`,它是「呈现层」,不是「语义层」。** - 它解决的是可读性、带空格函数名、循环来源、桩申报和 view 呈现;它不解决命名、寻址、解析、类型、跨文档引用。把这些说成「核心能力」,是把「读者看到什么」误当成「语言能做什么」。 - -3. **工程规范问题确实存在,而且是「契约没有闭环」,不是「文档不够多」。** - README 的 `marqdo labels pending` 实测扫 0 个文件(真实值是 6);README 说 v2.0.0 遮蔽,默认解析仍是 Classic;`check` 对未定义变量、未知函数实测放行;EKC 的运行图不从正文链接取边。一个以「知识-代码一致性」为旗帜的项目,自己的文档和代码先漂移了。 - -4. **迁移把「遮蔽」变成了「键名复述」。** - 全仓 231 处 `[label](access(x, "key"))` 形中,**204 处 label 与 key 完全相同(88%)**;设计文档承诺的 `label.provisional`(提醒「标签退化成键名」)在源码中不存在。语法税交了,信息增量没有。 - ---- - -## 1. 问题、方法与证据等级 - -### 1.1 要回答的三个问题 - -1. `[]()` 遮蔽语法**实际上**做了什么?它是不是「编程语言的核心能力」? -2. 用户给的两文档例子,是否真的展示了「可执行知识」?如果没跑起来,失败在哪一层? -3. 如果目标真是「可执行知识」,Marqdo 还缺什么?应该先补哪一块? - -### 1.2 方法 - -- **读设计**:occlusion / label / module-namespace / objects / EKC 的 Accepted 文档; -- **读实现**:AST、解析模式、求值、字节码、`check`、`mlsp`、`label`、`knowledge::graph`; -- **实测**:在隔离目录 `/tmp/mq-probe` 复现用户的两份文档及其变体,记录退出码、stdout/stderr、`--dump-ast`; -- **统计**:全仓 `.mq.md` 与 `markup: occlusion` 的采用率、`access(` 迁移痕迹、`labels` 命中数。 - -### 1.3 证据等级 - -| 等级 | 含义 | 本文用法 | -|------|------|---------| -| **A** | 本机实测(命令 + 输出) | 结论的主要依据 | -| **B** | 源码事实(可定位到文件/行) | 解释行为为何如此 | -| **C** | 设计文档声明 | 用于对照「说的」与「做的」 | -| **D** | 规范推断(CommonMark / 语言设计) | 明确标注为推断,不冒充实测 | - -> 本文的原则:**文档说过的,不算数;跑出来的,才算数。** - ---- - -## 2. `[]()` 在实现里到底是什么 - -### 2.1 AST:它只是一个「带标签的表达式」 - -来源:[src/ast.rs:261](../../src/ast.rs#L261) - -```rust -Occluded { - label: String, - payload: Option<Box<Expr>>, -} -``` - -- `label`:`[]` 里的自由文本,**不执行**,只被扫描关键词、检查反引号引用、做 T1 指纹; -- `payload`:`()` 里的表达式,**唯一执行**; -- `payload: None`:空载荷桩,值为 `None`。 - -### 2.2 求值:完全透明 - -来源:[src/interp.rs:1117](../../src/interp.rs#L1117) - -```rust -// `<TAB>` M2: the label is inert prose; only the payload evaluates. -Expr::Occluded { payload, .. } => match payload { - Some(inner) => self.eval_expr(module, fun, env, inner), - None => Ok(Value::None), -}, -``` - -字节码后端同样只编译 payload([src/bytecode/compile.rs:831](../../src/bytecode/compile.rs#L831))。 - -**形式化**: - -> 对任意表达式 `e`、任意标签 `d`:`eval([d](e)) = eval(e)`。 -> 标签对求值**零贡献**。 - -这不是「语义能力」,而是「语义透明的包装」。用 PL 的话说,它是 annotation / transparent wrapper / 文档宏,不是新的求值规则。 - -### 2.3 标签被用来做什么 - -| 用途 | 实现 | 说明 | -|------|------|------| -| 关键词检索 | `src/label.rs` + `marqdo labels` | 找「待开发 / 模拟 / 桩」等 | -| 结构诊断 | `label.missing`(error)、`label.empty_payload`(warning) | 空标签 / 空载荷 | -| 引用一致性 | `label.ref_dangling`(error) | **只认反引号实体**,纯口语不检查 | -| T1 过期检测 | MLSP `repair_apply` 的 before/after 指纹 | 只在一次修复会话内;`check` 不报 stale | -| 视图呈现 | `view` 的 `occl-card` | 标签作正文、payload 作 code chip([src/view/render.rs:1227](../../src/view/render.rs#L1227)) | - -注意最后两行:**「过期检测」是会话内、按修复动作触发的**;它不是 CI 级的 `label.stale`。设计文档把它叫「信任负债的代价」,但 CLI 的 `check` 并没有收这笔债。 - -### 2.4 解析模式:默认仍是 Classic - -来源:[src/parse/expr.rs:14](../../src/parse/expr.rs#L14) - -```rust -/// The default is `Classic` until M7 migrates the corpus and flips the gate -/// (otherwise every legacy index would silently change meaning). -pub enum Markup { - #[default] - Classic, - Occlusion, -} -``` - -文件只有在 frontmatter 写 `markup: occlusion`(或 `标记: 遮蔽`)时才按遮蔽解析([src/load.rs:292](../../src/load.rs#L292))。同一进程可以按文件切换,import 也各自保持模式。 - -**这意味着**: - -- 一个普通的 `.mq.md` 里写 `[a](b)`,默认含义仍是**取元**,不是遮蔽; -- 用户例子里的 `[]()` 在正文里连取元都不是,只是 Markdown 链接; -- README 的「v2.0.0 遮蔽语法」是**功能可用**,不是**默认语义**。 - -### 2.5 能力矩阵:它能做什么,不能做什么 - -| 能力 | 由 `[]()` 提供? | 证据 | -|------|----------------|------| -| 求值(等于 payload) | ✅ | `interp.rs:1117` | -| 人话标签(不执行) | ✅ | `ast.rs:261` | -| 可读的嵌套取值 | ✅(写法上) | 设计 §1.1 | -| 带空格函数名调用 | ✅(`callee(args)`) | M1 / `m2` 实测 | -| 循环来源可见 | ✅(`遍历`) | M3 | -| 桩申报 / 债务盘点 | ✅ | `label.rs` / `labels` | -| view 呈现 | ✅ | `render.rs:1227` | -| **跨文档引用** | ❌ | `f4` 实测失败 | -| **名字解析 / 静态检查** | ❌ | `check` 对未定义变量放行 | -| **类型 / 契约求值** | ❌ | `check` 只查契约表/标签,不求值 | -| **知识实体 / 事实模型** | ❌ | `Fact` 是 frontmatter 元数据,不是 `[]()` | -| **知识图边** | ❌ | `knowledge::graph` 不从正文链接取边(边来自 import/call/tests/related/reuse/knowledge) | - -### 2.6 一句话定义 - -> **`[]()` 是「给读者看的描述 + 给机器跑的表达式」的绑定语法。** -> 它让读者少读代码,让机器照常执行;它**不**让语言多算任何东西。 - -这就是为什么它是**表层工效学**,不是**语义核心**。 - ---- - -## 3. 用户两文档的逐层复现 - -### 3.1 原文 - -`libai.mq.md`: - -```markdown -# 李白 - -这个文档存储了李白的信息 - -## 李白的出生年份 - -李白出生于*某年* -``` - -`main.mq.md`: - -```markdown -# main -用户想要直到李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) -``` - -### 3.2 实测结果 - -环境:`marqdo 2.0.0`,两份文件在 `/tmp/mq-probe` 下。 - -| 命令 | 退出码 | stdout | stderr | 解释 | -|------|--------|--------|--------|------| -| `marqdo run main.mq.md` | **0** | 空 | 空 | 没有任何语句执行 | -| `marqdo check main.mq.md` | **0** | `contract check OK: 无契约问题` | 空 | 契约检查通过,不代表程序可运行 | -| `marqdo run libai.mq.md` | **0** | 空 | 空 | 只构造对象,不调用方法 | -| `marqdo run main.mq.md --dump-ast` | 0 | `(object level=1 "main" params=[] @1:1)` | 空 | **`# main` 是空对象;链接不在 AST 里** | -| `marqdo run libai.mq.md --dump-ast` | 0 | 方法 `李白的出生年份` 下无语句 | 空 | **方法体为空,没有返回值** | - -`main.mq.md` 的 AST(关键部分): - -```text -(object level=1 "main" params=[] @1:1 -) -``` - -`libai.mq.md` 的 AST(关键部分): - -```text -(object level=1 "李白" params=[] @1:1 - (fun level=2 "李白的出生年份" params=[] @5:1 - ) -) -``` - -### 3.3 失败在哪五层 - -这不是「一个拼写错误」,而是五个层次的连续缺口: - -| 层 | 期望 | 实际 | 证据 | -|----|------|------|------| -| **1. 上下文层** | 正文链接由 `view`/`check` 解析 | 正文默认是叙述(注释),`run` 不解析、不进入 AST | `--dump-ast` 空 | -| **2. 索引层** | 项目类索引能找到类 `李白` | 没有类索引;裸类名不是绑定名 | `f4` 即使 import 也失败 | -| **3. 表达式层** | `李白.李白的出生年份` 是类调用 | 它被当成点号路径的**变量读取**;类函数语义缺失 | `f3`:`undefined variable` | -| **4. 分派层** | 类 `李白` 直接调用函数 | `# 李白` 是类型,`##` 被实现成实例方法;类调用被拒绝 | `n2`:`is an instance method; call it as var.李白的出生年份` | -| **5. 值层** | 方法返回年份 | 方法体为空(`李白出生于*某年*` 是带斜体的叙述,不是返回语句),返回 `None` | `n1` 输出 `None`;`--dump-ast` 空 | - -> **关键**:即使把第 1 层补上(加 `**`),第 3/4/5 层仍然会失败。 -> 这不是「写法不够甜」,是**语义模型不匹配**。 - -### 3.4 三个最小可运行改写 - -#### A. 顶层自由函数 + `>` 调用(跨文档,但不用遮蔽) - -`k1_lib.mq.md`: - -```markdown -## 李白的出生年份 - -*701* -``` - -`k2_main.mq.md`: - -```markdown ---- -import lb:k1_lib.mq.md ---- - -# main - -**year = > lb.李白的出生年份** -> print text=`year` -``` - -实测:**输出 `701`,退出码 0**。 - -#### B. 对象 + 实例方法 + 遮蔽(跨文档,且用 `[]()`) - -`lib2.mq.md`: - -```markdown -# 李白 - -## 李白的出生年份 - -*701* -``` - -`n3.mq.md`: - -```markdown ---- -markup: occlusion -import lb:lib2.mq.md ---- - -# main - -**li = > lb.李白** -**year = [出生年份](li.李白的出生年份())** -> print text=`year` -``` - -实测:**输出 `701`,退出码 0**;AST 里能看到 `Occluded { label: "出生年份", payload: Call(...) }`。 - -#### C. 纯本地遮蔽(证明它只是表达式包装) - -```markdown ---- -markup: occlusion ---- - -# main - -**x = [二](1 + 1)** -> print text=`x` -``` - -实测:**输出 `2`,退出码 0**;默认 Classic 下同一文件会报 `footnote index needs list or map`。 - -### 3.5 结论 - -- **能跑的是 A/B 的「模块 + 对象 + 调用」系统**,不是「文档链接」; -- B 里的 `[]()` 只是把 `li.李白的出生年份()` 这行代码包了一层人话; -- 用户原始例子缺的正好是 A/B 的核心:**绑定、调用、值**; -- 所以它**不能**作为「可执行知识已经到位」的证据。它最多证明「可执行知识的语法外形可以长成链接」,而这一点设计文档已经说过。 - ---- - -## 4. 对用户判断的逐条评判 - -### 4.1 判断一:Marqdo 已经有 AI 时代的东西 - -**基本成立,但要区分层次。** - -| 层 | 已有 | -|----|------| -| 语言核心 | 表达式、对象、模块、字节码、契约表 | -| 运行时 | stdlib、插件 ABI、WASM、沙箱、子任务 | -| 工具 | view、debug、catalog、EKC、MLSP | -| AI | ext/llm、ext/agent、MCP、Skill | - -这些是**生态层**的 AI 能力。它们能证明 Marqdo 适合做 AI 的工程底座,但不能证明语言核心已经「内化」了知识。**生态丰富 ≠ 语言核心强。** - -### 4.2 判断二:需要内化的核心能力 - -**成立。** 而且这是本文最同意的一句。 - -Marqdo 现在的强项是「文档即代码」的**呈现**和**执行**;弱项是「知识即实体」的**寻址**、**解析**、**验证**。后者才是「可执行知识」的承重结构。 - -### 4.3 判断三:`[]()` 可以充当那个核心 - -**要分两层说。** - -- **v2.0.0 的实现**:不成立。它只做了「标签 + 表达式」;`##` 仍是实例方法,跨文档类名不解析,所以它只是呈现层。 -- **原始设计**:成立,但前提是 `#`/`##` 真正成为类/函数,`类.函数` 可直接调用,项目类索引可用。这时 `[d](e)` 的语义来自 `e`(类调用),链接只增加 label/元数据,不是新语法。 - -`[d](e) ≡ e` 仍然成立。问题不是「链接要不要语义」,而是「`e` 能否解析成类/函数调用」。v2.0.0 的答案是不能;v2.1 要补的是这个解析,不是新语法。 - -**所以:当前实现是「读者的眼镜」;原始设计是「描述 + 地址(类/函数)」。补上类函数语义后,它才是核心。** - -### 4.4 判断四:两文档例子证明可执行知识的威力 - -**作为证据不成立。** 见 §3:例子没有进入 AST,方法体为空,目标不是可调用的静态事实。 - -但**作为需求**它是成立的:它精确地指出了用户想要的东西—— -> 「我在 A 文档里写下一个事实,在 B 文档里用一句人话引用它,B 能执行并拿到值。」 - -这个需求是真实的;只是 `[]()` 不是实现它的语法。 - -### 4.5 判断五:设计已经到了这一步,工程规范不够好 - -**后半句成立,前半句不成立。** - -- 「设计到了这一步」:默认 Classic;90/886 文件启用;`lib/` 0 启用;真正带描述的遮蔽标签只有 6 处(其中 4 处在测试);`check` 不解析名字;知识图不从链接取边。**这不是「到了」,是「有一个可用的原型」**。 -- 「工程规范不够好」:**完全成立**,而且比你说的更严重——不是规范执行不严,而是**规范没有闭环**(见 §7)。 - -### 4.6 总评分 - -| 维度 | 评分 | 理由 | -|------|------|------| -| 愿景(可执行知识) | ★★★★★ | 方向正确,且与 OKF / literate programming 同构 | -| 对 `[]()` 的定位 | ★★☆☆☆ | 把呈现层当语义层 | -| 对现状的判断 | ★★☆☆☆ | 例子不可执行,默认未启用,采用率低 | -| 对工程规范的判断 | ★★★★★ | 有硬证据,且是当前最大瓶颈 | -| 建议的可执行性 | ★★★★☆ | 先补引用/解析/校验,再谈链接外形 | - ---- - -## 5. 三个概念混淆(理论核心) - -这一节解释「为什么这个例子看起来很美,实际却跑不起来」。 - -### 5.1 混淆一:呈现 vs 语义 - -| | 呈现层 | 语义层 | -|---|--------|--------| -| 关心 | 读者看到什么 | 程序能解析/验证/执行什么 | -| 例子 | 标签、注释、doc、view | 变量、作用域、类型、调用、模块 | -| 失败后果 | 读者误解 | 程序报错 / 静默错义 | -| **v2.0.0 的 `[]()`** | ✅ 主要在这里 | ❌ 只做透明传递 | - -把呈现层说成核心,会导致资源投入到「更好看的语法」,而真正的解析器/校验器没人做。**用户例子跑不起来,正是这个错位的直接后果。** - -> **原始设计**:`[]()` 不是纯呈现;`e` 是类/函数调用,语义在 `e`。v2.0.0 没实现类函数解析,所以它**看起来**才像纯呈现。 - -### 5.2 混淆二:变量读取 vs 类调用 - -`()` 里是**表达式**,在当前环境求值。`李白.李白的出生年份` 被解析成「变量读取」,所以报 `undefined variable`。 - -而用户想要的是**类调用**:`李白` 是类,`李白的出生年份` 是函数;解析器应在当前文档/import/项目类索引里找到它并调用。 - -| | 变量读取(当前) | 类调用(目标) | -|---|------------------|----------------| -| 含义 | 当前环境的一个变量 | 类命名空间里的函数 | -| 解析 | 运行时环境 | 当前文档 / import / 项目类索引 | -| 失败 | `undefined variable` | `link.unresolved` / `link.instance_only` | -| 例子 | `x` | `李白.李白的出生年份` | -| 用户目标 | 被当变量 → 失败 | 类调用 → 未实现 | - -**`()` 是表达式槽;类调用是表达式的一种,不需要新的地址语法。** - -### 5.3 混淆三:文档 vs 类型 - -用户的心理模型: - -> `# 李白` 是文档标题,`## 李白的出生年份` 是文档的一节,`李白.李白的出生年份` 是这一节的地址。 - -Marqdo 的实际语义([objects.md](../design/objects.md#L14)): - -> `#` 是对象/类型;`##` 是函数/方法;方法通过 `_type` 分派,需要实例。 - -| 用户以为 | Marqdo 实际 | -|---------|------------| -| `# 李白` = 文档 | `# 李白` = 类型 | -| `## 出生年份` = 一节/一个事实 | `## 出生年份` = 方法 | -| `李白.出生年份` = 事实地址 | 点号路径 = 类/函数;不使用 `self` 的函数可类调用,使用 `self` 的需实例 | -| 文档「存储信息」 | 文档「执行代码」;正文是注释 | - -这不是小差别,是**文档模型 vs 类/函数模型**的差别。原始设计就是 `#` 类 + `##` 函数 + `类.函数` 类调用;不需要新语法,只需要把 `##` 从「实例方法」恢复为「类函数(`self` 时例外)」并建立跨文档类索引。 - -### 5.4 Markdown 链接三难 - -用户想要三件事同时成立: - -1. **L**:它仍是普通 Markdown 链接(`[文本](目标)`,目标是一个 URL/路径); -2. **X**:目标可执行(点一下/引用一下就运行); -3. **S**:叙述默认安全(无标记的正文永远不执行)。 - -| 组合 | 是否可能 | 说明 | -|------|---------|------| -| L + S | ✅ | 当前状态:正文链接是惰性的 URL | -| X + S | ✅ | 只在显式代码标记内(遮蔽);但它不再是「文档链接」 | -| L + X | ✅ | 但正文链接会变成代码入口,破坏 S | -| **L + X + S** | ❌ | **三者不可兼得** | - -用户例子假设了 L + X + S 同时成立;这就是它「看起来该跑、实际不跑」的根源。 - -**结论**:要么接受「正文链接在 `run` 中是惰性的」,要么给「可执行引用」一个显式标记。Marqdo 可以选择前者 + `#`/`##` 类函数解析:**正文链接是 view 的知识调用,代码链接才是 `run` 的执行体**;这样不需要新语法,也不破坏叙述默认安全。 - -### 5.5 「内化」的五条判定标准 - -一个能力算不算「语言核心」,可以拿这五问去测: - -| # | 问题 | 遮蔽 | 跨文档引用 | -|---|------|------|-----------| -| 1 | **可指称**:有稳定地址吗? | ❌ 标签不是地址 | ⚠️ 路径是地址,但未解析 | -| 2 | **可绑定**:进入作用域/导入系统吗? | ❌ 标签不绑定 | ⚠️ import 有,但事实无 | -| 3 | **可组合**:能作为值/参数/返回值吗? | ✅ 透明传递 | ⚠️ 只能调用,不能当值 | -| 4 | **可验证**:工具链能证明它对吗? | ⚠️ 只查反引号/空载荷 | ❌ `check` 不解析 | -| 5 | **可观察**:运行时/诊断能看到吗? | ✅ view / 错误锚点 | ⚠️ 只有运行时错误 | - -遮蔽在 5 问里只拿到 2 个 ✅、1 个 ⚠️;**它不是核心,是表层**。 -跨文档引用拿到 0 个 ✅、3 个 ⚠️;**它有雏形,但不是能力**。 - -### 5.6 结论 - -> **在 v2.0.0 里,`[]()` 只完成了「描述 + 表达式」;在原始设计里,`[]()` 是「描述 + 类/函数调用」。** -> 缺的不是一种新语法,而是 `#`/`##` 的类函数语义与跨文档类索引;补上后,链接的语义来自调用,标签仍只是排版。 - -### 5.7 相关系统对照:它更像什么,不像什么 - -以下为高层对照(C/D),不是对各系统规范的逐条审计: - -| 系统 / 传统 | 人话与代码的关系 | 跨文档引用 | 执行 | 对 Marqdo 的启示 | -|------------|----------------|-----------|------|-----------------| -| **Literate programming(Knuth)** | chunk 名 + 代码;weave/tangle | 文内 `<<chunk>>`,非跨文档事实 | tangle 后执行 | 遮蔽 ≈ chunk 名;chunk 名是宏地址,不是知识事实 | -| **Org-mode + Babel** | 散文 + 显式 `#+begin_src` | ID/链接用于导航 | 只在 src block 内执行 | **显式标记**是可执行的前提 | -| **Jupyter** | Markdown cell + code cell | 无原生文档间引用 | kernel 执行 | cell 边界是显式语法,不是「长得像链接」 | -| **Observable** | 散文 + 响应式 JS cell | cell 名互相引用 | 数据流执行 | 最接近「可执行知识」,但不是 Markdown 原生 | -| **Obsidian / Roam** | wiki link / backlink | ✅ 链接图 | ❌(插件另说) | **链接图 ≠ 执行图** | -| **Notion / Coda** | 文档 + 公式/按钮 | ✅ 跨文档引用 | ✅(专有) | 地址 + 公式模型,不是 Markdown | -| **OKF** | frontmatter + Markdown 链接 | ✅ 路径即 ID、链接即关系 | ❌(元数据) | 可借鉴「路径即身份」 | -| **Marqdo 现在** | `[label](code)`(代码内) | ❌ | ✅ payload | 表面强,类-函数调用缺 | - -**结论**: - -- 遮蔽更像 **literate programming 的 chunk 名**或 **Org-babel 的 prose label**:它服务于「读」和「组织」,不是「跨文档求值」; -- 用户的直觉更像 **Obsidian 的链接** + **Observable 的响应式引用**:那需要**地址**和**解析器**,不是把 `()` 换成代码; -- Obsidian 的链接图之所以有用,是因为它**不执行**;一旦链接执行,安全模型就完全不同了。Marqdo 必须在「链接图」和「执行图」之间划清边界。 - ---- - -## 6. 遮蔽语法的真实价值与代价 - -### 6.1 真实价值(这部分是肯定的) - -1. **可读调用 / 带空格函数名** - `[加一之后的值](加一 号(31))` 解决了 D8:`(` 是明确边界,空格不再切词。 - 实测 `m2`:`[出生年份](lb.李白的出生年份())` → `701`。 - -2. **嵌套取值可读** - `[水果类里苹果的第 1 项价格](at(at(at(货架, 水果类), 苹果), 1))` - 读者只看人话,机器看嵌套。这是真实的认知负担下降。 - -3. **循环来源可见** - `- [从篮子里取出的每个果子](遍历 篮子 为 果)` - 比 `- [果](篮子)` 更能自解释「从哪来」。 - -4. **桩 / 债务申报** - `[搜索接入,接口未接,待开发](None)` - 让「没接」变成可计数、可检索、可门禁的债务,而不是静默假功能。这是设计里最有价值的工程创新之一。 - -5. **view 呈现** - 标签作正文、payload 作 code chip;读者先读人话,需要时再看代码。 - -这些价值都是真的,但都属于**可读性 / 可审查性 / 工程治理**,不是「语言能算得更多」。 - -### 6.2 代价(这部分必须算清) - -| 代价 | 说明 | 证据 | -|------|------|------| -| **同形歧义** | `[a](b)` 可能是 Markdown 链接、旧取元、遮蔽、调用 | 设计文档 §9 / M7 | -| **逐文件方言** | 同一仓库两种语义,靠 frontmatter 区分 | `expr.rs:14` / 90/886 | -| **Markdown 兼容裂缝** | `()` 里是代码,不是 URL;GFM 的链接目标会是代码/非 URL(能否成链接取决于括号/空格),不可导航 | D(CommonMark 推断) | -| **信任负债** | 标签是自然语言,可能说谎;只查反引号 | 设计 §2.2 / `label.rs` | -| **Agent 攻击面** | 标签可能误导 agent(「只读」标签 + 删除 payload) | `bracket-as-label-evaluation.md` §4.3 | -| **迁移语义空壳** | `[key](access(...))` 的标签常等于键,无信息增量 | 231 处形,204 处(88%)label=key;`label.provisional` 未实现 | -| **采用率低** | 90/886 文件启用;`lib/` 0;真正带描述的标签 6 处 | 统计 | - -### 6.3 迁移留下的「语义空壳」 - -迁移工具把旧取元改成了: - -```markdown -**timeout = [timeout_sec](access(self, "timeout_sec"))** -``` - -- 标签 `timeout_sec` 只是键名的重复; -- 设计文档 §1.6 明确说这是**反例**(「描述等于变量名,无信息增量」); -- 设计文档 §9 承诺 `label.provisional`(hint)来提醒这种退化; -- **源码里没有 `label.provisional`**(`grep` 无结果)。 - -结果:对 231 处 `[label](access(x, "key"))` 的机械统计显示,**204 处 label 与 key 完全相同(88%)**。这不是「描述」,是「键名复述」;不是为了读者,是为了让语法通过。这不是「内化」,是「语法税」。 - -### 6.4 采用率:它不是默认,也不是主流 - -| 目录 | `.mq.md` 总数 | `markup: occlusion` | 占比 | -|------|-------------|---------------------|------| -| `lib/` | 53 | 0 | 0% | -| `ext/` | 31 | 8 | 26% | -| `examples/` | 90 | 7 | 8% | -| `public/` | 100 | 26 | 26% | -| `tests/` | 603 | 48 | 8% | -| **合计** | **886** | **90** | **10.2%** | - -(排除 `target/`、`dist/`、`.marqdo/`;统计命令见附录 A。) - -- `lib/` 是标准库,0 启用:说明「遮蔽」不是语言运行时的默认契约; -- 真正带**描述性标签**的遮蔽只有 6 处(`labels --json`),其中 4 处在测试; -- 90 个启用文件里,大多数是迁移后的 `[key](access(...))`,不是人写的「一句人话」。 - -**结论**:遮蔽目前是**一个可用的、局部的、实验性的表面**,不是「全语言的核心能力」。 - -### 6.5 对遮蔽的最终定位 - -| 选项 | 评价 | -|------|------| -| 删除遮蔽 | ❌ 可惜;它确实解决了 D8、嵌套可读、桩申报 | -| 把它当核心 | ❌ 层级错误;会继续把资源投到语法糖 | -| **保留为表层工效学,另建类-函数调用层** | ✅ **推荐** | - ---- - -## 7. 工程规范的硬证据:文档-代码漂移 - -用户的第三句话「工程规范做得不够好」是对的。下面每一条都可复现。 - -### 7.1 总表 - -| 文档说 | 实际做 | 证据等级 | 证据 | -|--------|--------|---------|------| -| README:v2.0.0 遮蔽语法 | 默认仍是 Classic;需 frontmatter | A/B | `run e3` 报 `footnote index`;`expr.rs:14` | -| README:`marqdo labels pending` | 扫 0 个文件(真实 6) | A | 附录 A | -| README:`labels search --grep ...` | 扫 0 个文件(真实 2) | A | 附录 A | -| README:Markdown 链接天然长成知识图 | 运行图不从正文链接取边(来自 import/call/tests/...) | B | `knowledge/graph.rs` | -| README:AI 可验证语言 | `check` 只查契约+标签;未定义变量/函数实测放行 | A/B | `check.rs:1`;`e1/e2` | -| 设计:M0–M10 全部完成 | 默认未翻转;per-file 模式 | C/B | `change-m7:22`;`expr.rs:14` | -| 设计:506 处取元 + 44 处循环 | 实施记录 256 + 23(口径未说明) | C | `occlusion-syntax:318` vs `change-m7:11` | -| 设计:`label.provisional` | 未实现 | B | `grep provisional` 无结果 | -| 测试:项目称 605 全绿 | 没有跨文档 headline 场景 | B | `tests/occlusion.rs` 只有本地用例 | - -### 7.2 `labels pending`:最危险的「假 0」 - -README 把这条命令当作「还有多少未完成」的默认口径: - -```bash -marqdo labels pending # 内置口径:还有多少未完成 -marqdo labels pending --count --baseline .marqdo/pending.json --fail-on-increase -``` - -实测: - -```text -$ marqdo labels --count -6 -$ marqdo labels pending --count -0 -$ marqdo labels --grep 待开发 --count -2 -$ marqdo labels search --grep 待开发 --count -0 -``` - -原因([src/main.rs:631](../../src/main.rs#L631)): - -```rust -// Accept the documented shapes `labels pending` / `labels search` -// as no-op words (the flags carry the real intent). -let paths: Vec<&PathBuf> = paths.iter().filter(|p| { - let s = p.to_string_lossy(); - !(s == "pending" || s == "search") -}).collect(); -``` - -它把 `pending`/`search` 从路径里过滤掉,但**没有回退到 `.`**。于是「文档里最常用的无路径盘点形式」会扫 0 个文件、返回 0。 - -**这是最能说明问题的一条**:一个以「不允许假装完成」为工程习惯的项目,自己的默认盘点命令会报告「没有未完成」。如果 CI 用这个无路径形式做棘轮,它会一直通过。 - -### 7.3 `check`:通过 ≠ 可运行 - -`check` 的文档写的是「静态契约互查」,这本身没错;但它的输出是: - -```text -contract check OK: 无契约问题 -``` - -对下面这个文件: - -```markdown -# main - -**x = > 不存在的函数 n=1** -> print text=`x` -``` - -`check` 退出 0,`run` 才报 `unknown function`。未定义变量同理。 - -`mlsp validate` 也只是 `check_module`([src/mlsp.rs:199](../../src/mlsp.rs#L199)),所以 AI 的「validate」也拿不到名字解析错误。 - -**影响**:AI 生成一个「结构正确、名字全错」的程序,`check` 会说 OK;直到运行时才炸。这与 README 的「AI 可验证语言」叙事有距离。 - -### 7.4 默认 Classic:v2.0.0 的「遮蔽」是 opt-in - -`expr.rs` 的注释写得很清楚:默认 Classic,等 M7 迁移完再翻转。但 M7 文档说「per-file 声明」,README 说「v2.0.0 遮蔽语法」。三者并不完全矛盾,但**读者会误解**: - -- 「v2.0.0 有遮蔽语法」= 你可以用; -- 「默认是遮蔽」= ❌; -- 「全仓已迁移」= ❌(90/886)。 - -一个语言特性的「发布」到底是「可用」还是「默认」,必须在 README 里写清楚。否则用户按 README 写 `[a](b)`,得到的是取元,不是遮蔽。 - -### 7.5 知识图:链接没有变成边 - -README 的愿景 #4: - -> `.mq.md` 之间的 Markdown 链接天然长成文档图 + 知识图 + 程序图(Executable Knowledge Graph)。 - -实际 `knowledge/graph.rs` 的边来自: - -- module 的 `imports` → `depends_on` -- symbol 的 `calls` → `uses` -- tests / related / reuse / knowledge applies_to - -**没有一条代码路径**从正文的 Markdown 链接提取边。`catalog` 会把依赖渲染成链接,但那是「图 → 链接」,不是「链接 → 图」。 - -所以用户例子里的 `[李白的出生年份](李白.李白的出生年份)` 不会成为任何图边;`marqdo catalog` 只会把它当作模块 `main` 的一段叙述。 - -### 7.6 测试没有覆盖 headline 场景 - -`tests/occlusion.rs` 覆盖了: - -- 本地遮蔽值 = payload; -- Classic / Occlusion 双模式; -- 空标签 / 空载荷 / 反引号悬空; -- labels 检索; -- T1 会话内过期。 - -它**没有**覆盖: - -- 跨文档 import + 对象方法 + 遮蔽标签; -- 正文链接的悬空检测; -- 用户两文档的「事实引用」场景; -- `labels pending` 的文档命令形式。 - -所以「605 全绿」不能证明「用户例子能跑」;它只证明了被测的部分能跑。 - -### 7.7 这不是「文档不够多」,是「契约没有闭环」 - -项目已经有大量设计文档、ADR、变更记录、研究文档。问题不是数量,而是: - -1. **文档里的命令没有变成测试**(`labels pending`); -2. **文档里的承诺没有变成诊断**(`label.provisional`、`label.stale` 在 CLI); -3. **文档里的默认值没有和代码对齐**(v2.0.0 vs Classic); -4. **文档里的 headline 例子没有金样**(两文档场景); -5. **发布说明没有采用率/覆盖率指标**(90/886、6 个标签)。 - -对一个以「知识-代码一致性」为旗帜的项目,这五条是**自我指涉的失败**:它没有用自己的方法管理自己。 - ---- - -## 8. 如果要做成核心:能力阶梯与提案 - -### 8.1 能力阶梯 - -| 层 | 能力 | Marqdo 现状 | -|----|------|------------| -| **L0** | 叙述 + 本地表达式 | ✅ | -| **L1** | 变量 / 函数 / 对象 | ✅ | -| **L2** | 模块 / import / 点号路径 | ✅ | -| **L3** | **静态名字解析 / 类型检查 / 悬空引用** | ❌ 缺 | -| **L4** | **知识实体 / 稳定地址 / 图边** | ⚠️ 只有 EKC 元数据,未接执行 | -| **L5** | **可执行知识查询(`类.函数` → 值)** | ❌ 缺 | - -**用户以为在 L5;证据显示在 L2 + 一个 L0.5 的呈现层。** - -### 8.2 四个必需件 - -1. **类/函数语义** - - `#` 是类,`##` 是函数; - - 不使用 `self`/`自` 的函数是**类函数**,可 `类.函数` 调用; - - 使用 `self`/`自` 的是**实例函数**,只能 `obj.函数` 调用。 -2. **项目类索引** - - 扫描项目根 `.mq.md` 的 `#`/`##`、签名、位置; - - 跨文档解析 `类.函数`;同名 `link.ambiguous`; - - 排除 `# main`;只在根内。 -3. **类调用** - - `类.函数` 零参隐式调用;带参 `类.函数(...)`; - - 不构造实例;实例函数拒绝; - - 正文链接由 `view`/`check` 解析;代码链接由 `run` 求值。 -4. **验证** - - `link.unresolved` / `link.ambiguous` / `link.instance_only` / `link.no_value` / `link.arg_mismatch` / `link.type_mismatch`; - - LinkInfo;`check --json`;MLSP; - - 图边。 - -### 8.3 语义提案:不新增语法,补类-函数调用 - -**不要**给 `()` 增加新语法。`()` 就是 `**` 代码;要补的是下面四条语义: - -1. `#` 是类,`##` 是函数;不使用 `self`/`自` 的函数是**类函数**; -2. `类.函数` 是类调用;零参函数隐式调用,带参写 `类.函数(...)`; -3. 项目类索引跨文档解析;同名类 `link.ambiguous`; -4. 代码链接求值;正文链接由 `view`/`check` 解析,`run` 不执行;要终端输出用代码链接 + `print`。 - -| 场景 | 写法 | 语义 | -|------|------|------| -| 本地表达式 | `[描述](表达式)` | 值 = 表达式;标签 inert | -| 类调用 | `[描述](李白.李白的出生年份)` | 解析类/函数并调用 | -| 实例调用 | `[描述](li.李白的出生年份())` | 现有实例方法 | -| 正文链接 | 同上 | view/check 解析;run 不执行 | - -不要新增协议前缀、别名、执行开关;不要靠「内容像路径」来猜语义——靠类索引和解析器。 - -### 8.4 知识文档约定 - -`type: Fact` 是 EKC 元数据,不是新语法;知识文档的「值」仍由 `##` 函数返回: - -```markdown ---- -type: Fact -id: libai.birth_year -title: 李白的出生年份 ---- - -# 李白 - -## 李白的出生年份 - -| 返回 | 类型 | 说明 | -|------|------|------| -| 701 | number | 公元 701 年 | - -*701* -``` - -- `# 李白` = 类;`##` = 函数;`*701*` = 值; -- 类函数不使用 `self`,可 `李白.李白的出生年份` 直接调用; -- `type: Fact` 只影响 catalog/EKC,不影响调用; -- 知识函数必须有返回值;无返回 → `link.no_value`。 - -### 8.5 用户例子的验收形态 - -`libai.mq.md`: - -```markdown -# 李白 - -这个文档存储了李白的信息。 - -## 李白的出生年份 - -*701* -``` - -`main.mq.md`: - -```markdown -# main -用户想要知道李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) -``` - -期望: - -- `view`:显示链接目标 `李白.李白的出生年份`、类/函数、值 `701`; -- `run`:无输出(正文链接不执行);代码链接 + `print` 输出 701; -- `check`:`link.ok`(class/function/signature); -- 类名不存在 → `link.unresolved`; -- 函数不存在 → `link.unresolved`; -- 同名类 → `link.ambiguous`; -- 无返回值 → `link.no_value`。 - -这是「描述 + 已有调用」,不是新语法。 - -### 8.6 安全边界:标签是不可信文本 - -- **策略/权限永远不看标签**,只看 payload / 解析后的类函数; -- agent 提示词要写:标签是自然语言,可能误导;以 payload 与类函数解析结果为准; -- `view` 必须同时显示标签与 payload(当前实现已显示 code chip,这是对的); -- 对「标签说只读、payload 写文件」这类不一致,至少给 hint(设计文档 §4.2 提议过词重叠校验,但未实现)。 - ---- - -## 9. 路线图与验收 - -### 9.0 能力规划总表 - -| 能力 | 层次 | 现状 | 优先级 | 验收 | -|------|------|------|--------|------| -| 名字解析 / 类型检查 | L3 | 缺 | **P0** | `check --strict` 报未定义变量/函数 | -| 正文链接 / 类调用解析 | L3 | 缺 | **P0** | `check --links` 报 `link.*` | -| 类-函数调用 | L4 | 缺 | **P1** | `类.函数` 直接调用 | -| 项目类索引 | L4 | 缺 | **P1** | 跨文档解析类名 | -| 知识文档 / 事实 | L4 | 部分(EKC 元数据) | **P1** | `type: Fact` + 返回值 | -| 图边(链接 → 图) | L4 | 缺 | **P1** | `graph.json` 有 `calls` 边 | -| 执行 / 查询 | L5 | 缺 | **P1** | `run`/`view` 输出 701 | -| AI schema / 修复 | L5 | 部分 | **P2** | MLSP `link.resolve` | - -> **顺序建议**:P0 先让「假成功」消失;P1 再让「类-函数调用」成立;P2 才谈 AI 闭环。不要在 L3 缺失时翻转遮蔽默认。 - -### 9.1 P0:先止血(1–2 周) - -| # | 事项 | 验收 | -|---|------|------| -| P0-1 | 修 `labels` 路径回退:过滤 `pending`/`search` 后若无路径,默认 `.` | `labels pending --count` == `labels --count` == 6 | -| P0-2 | `check` 输出改为「contract check only」;新增 `--strict` 名字解析 | `check --strict e2` 报 `undefined variable`;`e1` 报 `unknown function` | -| P0-3 | 新增 `check --links`:解析正文 `[]()`,校验类/函数 | 用户例子的 `李白.李白的出生年份` 报 `link.*`(或 `link.ok`) | -| P0-4 | 把用户两文档加入金样:要么 `view` 显示 701,要么 `check` 精确报错 | 不允许「exit 0 + 空输出」被当成通过 | -| P0-5 | 修文档:v2.0.0 的「可用 ≠ 默认」;M7 的 per-file 模式;`labels` 命令;506 vs 256 口径 | README / 设计文档与实测一致 | -| P0-6 | `label.provisional` 落地,或迁移时不再生成「键名标签」 | 231 处 `access` 标签(204 处 label=key)有 hint 或被清理 | - -### 9.2 P1:补类-函数调用(核心) - -| # | 事项 | 验收 | -|---|------|------| -| P1-1 | 补齐 `#`/`##` 的类-函数语义:`类.函数` 直接调用;项目类索引解析跨文档 | 正文可写 `[描述](李白.李白的出生年份)` | -| P1-2 | 静态解析器:类 → 函数 → 契约 | `check` 报 `link.unresolved` / `link.type_mismatch` | -| P1-3 | 知识文档:`type: Fact` + 返回值 + 表/函数 | `run`/`view` 取值 701;`find`/`impact` 能用 | -| P1-4 | EKC 从链接取边;`catalog` 图与运行时解析同源 | `graph.json` 有 `calls` / `references` 边 | -| P1-5 | `view` 解析链接并显示 provenance | 点击/展开能看值与来源 | - -### 9.3 P2:AI 原生闭环 - -| # | 事项 | 验收 | -|---|------|------| -| P2-1 | MLSP `link.resolve` / `link.check` / schema | AI 可查「这个链接指向哪个类/函数、类型对不对」 | -| P2-2 | agent 提示词:标签不可信;以 payload/类函数为准 | 注入「只读标签 + 删除 payload」测试 | -| P2-3 | 指标:采用率、解析率、check 覆盖率、stale 标签 | 发布报告可见 | -| P2-4 | 基准:AI 生成带类调用的文档 vs 纯代码 | 错误率/修复轮次/token 对比 | - -### 9.4 总验收(一句话) - -> **用户的两份文档:`view` 显示 701,`check` 返回 `link.ok`;加 `print` 的代码链接输出 701。** -> **不允许「退出 0、无输出、显示 OK」这种假成功。** - ---- - -## 10. 结论 - -### 10.1 直接回答「遮蔽到底有什么用」 - -**v2.0.0 的 `[]()`**: - -- 它让**读者**不必读复杂表达式(嵌套、长算式、循环来源); -- 它让**带空格的函数名**有了明确边界; -- 它让**未完成的桩**变成可检索、可计数、可门禁的债务; -- 它让 **view** 能先显示人话、再显示代码; -- 它**不**提供类-函数调用、跨文档类索引、名字解析、LinkInfo、图边。 - -**原始设计还要加的四件事**(都不需要新语法): - -1. `#`/`##` 的类/函数语义; -2. `类.函数` 类调用; -3. 项目类索引跨文档解析; -4. view/LinkInfo/图边。 - -### 10.2 对你思路的最终评判 - -| 你的话 | 评判 | -|--------|------| -| 「可执行知识是核心」 | ✅ 对 | -| 「工程规范不够好」 | ✅ 对,且有硬证据 | -| 「`[]()` 遮蔽可以充当内化核心」 | ⚠️ **v2.0.0 实现**不成立(只是呈现层);**原始设计**成立,前提是补类-函数语义与类索引 | -| 「两文档例子证明威力」 | ❌ 当前例子跑不起来(正文不解析、类调用未实现、函数无返回值) | -| 「设计已经到了这一步」 | ❌ 到了原型,没到核心;默认未启用,采用率 10% | - -### 10.3 一句话建议 - -> **先把 `#`/`##` 的类-函数语义与项目类索引做进语言核心;`[]()` 只是「描述 + 已有调用」,不需要新语法。** - -当 `[李白的出生年份](李白.李白的出生年份)` 能让 `view` 显示目标/签名/值、让 `check` 返回 `link.ok`、让 `run`(加 print)输出 701、让 EKC 建边时,「可执行知识」才真正展示威力。那时你会发现:**它不需要 `[]()` 变成新语法;它需要 `#`/`##` 真正成为类/函数。** - ---- - -## 附录 A:复现命令 - -以下命令在 `marqdo 2.0.0` 下执行;`M=/workspace/marqdo/target/release/marqdo`。 - -### A.1 用户两文档 - -```bash -mkdir -p /tmp/mq-probe && cd /tmp/mq-probe -cat > libai.mq.md <<'EOF' -# 李白 - -这个文档存储了李白的信息 - -## 李白的出生年份 - -李白出生于*某年* -EOF -cat > main.mq.md <<'EOF' -# main -用户想要直到李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) -EOF - -$M run main.mq.md; echo "exit=$?" -$M check main.mq.md; echo "exit=$?" -$M run main.mq.md --dump-ast -$M run libai.mq.md --dump-ast -``` - -### A.2 遮蔽在代码里才执行 - -```bash -cat > p5_prose.mq.md <<'EOF' -# main - -[运行一个副作用](print("PROSE-RAN")) -EOF -cat > p4_code.mq.md <<'EOF' ---- -markup: occlusion ---- - -# main - -**x = [运行一个副作用](print("CODE-RAN"))** -EOF -$M run p5_prose.mq.md --dump-ast # 空对象 -$M run p5_prose.mq.md # 无输出,exit 0 -$M run p4_code.mq.md # CODE-RAN -``` - -### A.3 跨文档:三种写法 - -```bash -# A. 顶层函数 + > 调用 -cat > k1_lib.mq.md <<'EOF' -## 李白的出生年份 -*701* -EOF -cat > k2_main.mq.md <<'EOF' ---- -import lb:k1_lib.mq.md ---- - -# main - -**year = > lb.李白的出生年份** -> print text=`year` -EOF -$M run k2_main.mq.md # 701 - -# B. 对象 + 实例方法 + 遮蔽 -cat > lib2.mq.md <<'EOF' -# 李白 -## 李白的出生年份 -*701* -EOF -cat > n3.mq.md <<'EOF' ---- -markup: occlusion -import lb:lib2.mq.md ---- - -# main - -**li = > lb.李白** -**year = [出生年份](li.李白的出生年份())** -> print text=`year` -EOF -$M run n3.mq.md # 701 - -# C. 静态调用对象方法(应失败) -cat > n2.mq.md <<'EOF' ---- -markup: occlusion -import lb:lib2.mq.md ---- - -# main - -**year = [出生年份](lb.李白.李白的出生年份())** -> print text=`year` -EOF -$M run n2.mq.md # error: ... is an instance method -``` - -### A.4 静态检查的假通过 - -```bash -cat > e1.mq.md <<'EOF' -# main -**x = > 不存在的函数 n=1** -> print text=`x` -EOF -cat > e2.mq.md <<'EOF' -# main -**x = 未定义变量 + 1** -> print text=`x` -EOF -$M check e1.mq.md; echo "exit=$?" # 0,输出 contract check OK -$M run e1.mq.md; echo "exit=$?" # 1,unknown function -$M check e2.mq.md; echo "exit=$?" # 0 -$M run e2.mq.md; echo "exit=$?" # 1,undefined variable -``` - -### A.5 `labels` 文档命令的假 0 - -```bash -cd /workspace/marqdo -$M labels --count -$M labels pending --count -$M labels --grep 待开发 --count -$M labels search --grep 待开发 --count -``` - -### A.6 采用率统计 - -```bash -cd /workspace/marqdo -for d in lib ext examples public tests; do - t=$(find "$d" -name '*.mq.md' | wc -l) - o=$(grep -rl '^markup: occlusion' --include='*.mq.md' "$d" 2>/dev/null | wc -l) - echo "$d total=$t occlusion=$o" -done -$M labels --json - -# 迁移形中 label 与 key 完全相同的比例 -find lib ext examples public tests -name '*.mq.md' -print0 \ - | xargs -0 perl -ne 'while (/\[([^\]]+)\]\(access\(([^,]+),\s*"([^"]+)"\)\)/g) { $t++; $s++ if $1 eq $3; } END { print "total=$t same=$s\n" }' -# total=231 same=204 -``` - ---- - -## 附录 B:证据索引 - -| 主题 | 文件 | -|------|------| -| AST 节点 | [src/ast.rs:261](../../src/ast.rs#L261) | -| 求值透明 | [src/interp.rs:1117](../../src/interp.rs#L1117) | -| 字节码透明 | [src/bytecode/compile.rs:831](../../src/bytecode/compile.rs#L831) | -| 默认 Classic | [src/parse/expr.rs:14](../../src/parse/expr.rs#L14) | -| frontmatter 模式 | [src/load.rs:292](../../src/load.rs#L292) | -| 标签检查 | [src/label.rs:1](../../src/label.rs#L1) | -| `check` 只查契约+标签 | [src/check.rs:1](../../src/check.rs#L1) | -| `mlsp validate` | [src/mlsp.rs:199](../../src/mlsp.rs#L199) | -| `labels` 路径过滤 | [src/main.rs:631](../../src/main.rs#L631) | -| EKC 图边 | [src/knowledge/graph.rs:1](../../src/knowledge/graph.rs#L1) | -| `type: Fact` | [src/knowledge/extract.rs:313](../../src/knowledge/extract.rs#L313) | -| 遮蔽渲染 | [src/view/render.rs:1227](../../src/view/render.rs#L1227) | -| 遮蔽设计总纲 | [occlusion-syntax.md](../design/occlusion-syntax.md) | -| 信任负债 | [occlusion-syntax.md:173](../design/occlusion-syntax.md#L173) | -| 标签漂移/安全面 | [bracket-as-label-evaluation.md:160](../design/bracket-as-label-evaluation.md#L160) | -| per-file 迁移 | [change-m7-migration.md:22](../design/change-m7-migration.md#L22) | -| 点号寻址 / 实例方法 | [module-namespace.md:117](../design/module-namespace.md#L117) | -| 对象 / 方法 | [objects.md:14](../design/objects.md#L14) | -| 知识类型 | [engineering-knowledge.md:31](../design/engineering-knowledge.md#L31) | -| 遮蔽测试 | [tests/occlusion.rs](../../tests/occlusion.rs) | - ---- - -## 附录 C:术语 - -| 术语 | 本文用法 | -|------|---------| -| **遮蔽(occlusion)** | `[描述](实现)`;标签不执行,payload 执行;`[d](e) ≡ e` | -| **遮蔽(shadowing)** | 编程语言里「内层绑定遮住外层」;**本文不取这个义**,但中文同名,需在文档里区分 | -| **表达式** | 在当前环境求值的语法;`()` 里的东西 | -| **引用(reference)** | 在命名空间里指称实体;应由解析器/链接器处理 | -| **地址(address)** | 稳定 ID / 路径 / 锚点;引用的目标 | -| **解析(resolution)** | 把名字/路径映射到实体,并检查可见性/类型 | -| **呈现层** | 读者看到什么;标签、view、doc | -| **语义层** | 程序能解析/验证/执行什么;作用域、类型、调用、模块 | -| **L0–L5** | 本文的能力阶梯,见 §8.1 | - ---- - -## 附录 D:局限 - -1. **GFM 渲染未在本机实测**:`[]()` 在 GFM 里渲染为 `<a href="...">` 是 CommonMark 规范推断(D),不是本机截图;但设计文档自己也说它「渲染成超链接」。 -2. **未做性能/规模测试**:本文关注语义与工程规范,不评价 1000 标签文件的性能。 -3. **未逐个审计 90 个 occlusion 文件**:采用率是机械计数;「label=key」统计是对 `access(...)` 形做的正则匹配(231/204),没有逐个人工判断语义。 -4. **`type: Fact` 的运行时接入是提案**:当前代码只把它当 EKC 元数据;本文没有实现它。 -5. **用户意图存在两种读法**(遮蔽 vs 引用):本文两种都评估了;如果用户本意只是「遮蔽」,那么 §3 的第 3/4/5 层失败仍然成立,只是「引用」部分不适用。 - ---- - -## 附:一句话总结 - -> **遮蔽让读者不必读代码;引用让知识可以被找到。** -> 前者是排版,后者是语义。 -> Marqdo 现在有一个不错的排版层,但还没有语义层的地址、解析与验证。 -> 把这两件事分开,才是「可执行知识」真正变成核心能力的开始。 diff --git a/doc/research/okf-and-marqdo.md b/doc/research/okf-and-marqdo.md deleted file mode 100755 index 8f25e17..0000000 --- a/doc/research/okf-and-marqdo.md +++ /dev/null @@ -1,215 +0,0 @@ -# 调研:Google Open Knowledge Format(OKF)与 Marqdo - -| | | -|---|---| -| 状态 | 调研笔记 | -| 日期 | 2026-08-04 | -| 对象 | [OKF v0.2](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md) | -| 公告 | [v0.1 介绍](https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing) · [v0.2 trust signals](https://cloud.google.com/blog/products/data-analytics/okf-v0-2-adds-trust-signals) | - ---- - -## 1. OKF 是什么 - -**Open Knowledge Format(开放知识格式)** 是 Google Cloud 于 2026 年 6 月发布的厂商中立开放规范(Apache 2.0)。它把「LLM Wiki」模式形式化为可移植格式:用**目录树中的 Markdown 文件 + YAML frontmatter** 表示组织知识(表结构、指标、API、操作手册等),供人类与 AI Agent 共同阅读、交换与维护。 - -一句话定位: - -> 知识应活在**格式**里,而不是专有服务或散落的非结构化文本里。 - -### 核心形态 - -``` -bundle/ - index.md # 可选:目录索引(渐进披露) - log.md # 可选:变更历史 - concepts/.../*.md # 每个概念一个 Markdown 文件 -``` - -每个概念文件: - -```yaml ---- -type: Metric # 唯一必填 -title: Monthly Active Users -description: ... -tags: [product, growth] -sources: [...] # v0.2:出处 -generated: {...} # v0.2:谁生成的 -verified: {...} # v0.2:谁验证的 -status: stable # v0.2:生命周期 -stale_after: 2026-12-01 # v0.2:过期日 ---- - -# 正文(自由 Markdown) - -指标定义为…… -``` - -- **Concept ID** = 相对路径去掉 `.md` -- **链接** = 普通 Markdown 链接,形成可遍历关系图 -- **无中心 schema registry**;未知 `type` 必须被优雅降级处理 - -### 设计三原则(官方表述) - -1. **Minimally opinionated** — 只强制互通所需的最小公约;其余留给生产者。 -2. **Producer / consumer independence** — 写知识的人(或 Agent)与读知识的 Agent/工具解耦;格式即契约。 -3. **Format, not platform** — 不绑定云、数据库、模型或 Agent 框架;`cat` 能读,`git clone` 能分发。 - -### v0.2 新增:五类信任信号 - -当知识主要由 Agent **持续生成**时,纯 Markdown 不够。v0.2 把下列问题变成 frontmatter 一等字段: - -| 问题 | 机制 | -|------|------| -| 从何而来? | `sources`(出处 + 可信度信号,不作统一打分) | -| 该信多少? | `generated` / `verified` → 推导 trust tier(未验证 / 机器确认 / 人工审核) | -| 是否仍真? | `stale_after`(绝对日期,非相对 TTL) | -| 是否现行? | `status`: `draft` → `stable` → `deprecated` | -| 数字是否按约定算出? | 概念类型 `Attested Computation`:executor 跑计算出 receipt,**非 LLM** 的 attester 核验 | - ---- - -## 2. OKF 与 Marqdo:相邻,但不等同 - -| 维度 | OKF | Marqdo | -|------|-----|--------| -| 本质 | **知识交换格式** | **编程语言** | -| 文件角色 | 描述资产与概念的文档 | 可执行程序 = 可渲染文档 | -| 机器侧 | 解析 metadata、遍历链接、过滤信任 | 解析、类型检查、求值/编译 | -| Markdown 地位 | 载体与呈现层 | **语法表层的一部分**(源即 Markdown) | -| 成功标准 | 跨组织互通、Agent 可策展 | 严肃编程能力 + 阅读体验同时成立 | - -OKF 回答:「人和 Agent 如何**共享与信任知识**?」 -Marqdo 回答:「程序如何**本身就是知识**,且仍能运行?」 - -因此借鉴应落在**表示哲学与工程约束**,而不是照搬「知识目录」产品形态。 - ---- - -## 3. 值得借鉴的设计点 - -### 3.1 后缀与生态搭便车 — 已采纳 - -OKF 坚持「就是 Markdown」:GitHub 渲染、编辑器预览、静态站、搜索索引零摩擦。 - -**Marqdo 对应决策:源文件后缀为 `.mq.md`。** - -- `.md` 确保通用 Markdown 渲染器开箱可用 -- `.mq` 前缀声明这是 Marqdo 源,而非普通文档 -- 与 OKF「格式优先于平台」一致:可读性不依赖自研 viewer - -### 3.2 最小强制面(Minimally opinionated) - -OKF 只强制 `type`;其余可选,未知字段保留不拒绝。 - -**对 Marqdo 的启发:** - -- 语言的「文档面」与「程序面」之间,划清**硬语法**与**散文** -- 第一版语法宜小:标题层级、声明、表达式……先钉死互通/可执行最小集 -- 扩展用约定或可选 frontmatter,避免一上来造完整注解宇宙 - -### 3.3 生成式 YAML / OKF 清单 — 已采纳方向(已修正) - -OKF 用 YAML frontmatter 承载「可查询元数据」。Marqdo **借鉴其形态**,但职责不同: - -**YAML(OKF 风格知识包)由工具从 `.mq.md` 自动生成,不是人手写的配置文件。** - -详见 [`design/generated-yaml-manifest.md`](../design/generated-yaml-manifest.md)。 - -| | | -|--|--| -| 类比 | 其它语言中由工具维护的依赖描述(如 `Cargo.toml` / `requirements.txt` 所承担的那类角色) | -| 形态 | OKF:概念目录 + YAML frontmatter + Markdown 正文 | -| 用途 | ① 编译器/包管理消费依赖图与导出 ② **自动生成本项目文档**(模块索引、依赖关系等) | -| 权威 | 始终是手写 `.mq.md`;清单可删、可重建 | - -``` -.mq.md 源(人写) - → marqdo 工具链 - → 生成 OKF 风格清单(YAML + 概念页) - → 供编译解析,并渲染为项目目录文档 -``` - -执行方式等运行参数不放进该 YAML 当配置;由 CLI / 子命令决定。 -程序本体(类型、函数)只活在源正文里。 - -### 3.4 路径即身份,链接即关系 - -Concept ID = 路径;关系 = Markdown 链接;目录 = 渐进披露(`index.md`)。 - -**对模块系统的启发:** - -- 文件路径可成为模块身份的一部分(类比 OKF concept ID) -- `import` / 交叉引用尽量与 Markdown 链接同构,使「读文档跳转」与「解析依赖」共用一种边 -- 大型程序按「书的章节」组织目录,而不是扁平包名墙 - -### 3.5 生产者 / 消费者分离 - -同一 bundle:人手写、Agent 生成、管道导出,均可被另一 Agent 或 UI 消费。 - -**对 Marqdo 工具链:** - -- 解析器、渲染器、求值器、LSP 都是**消费者**;源格式是唯一契约 -- 允许 Agent 协助编写 `.mq.md`,但语言必须对「纯手写」同样友好 -- 不把语义锁进某一 IDE 或云服务 - -### 3.6 信任与 attestation(中长期) - -OKF v0.2 的 Attested Computation:批准的算法 + 确定性核验,防止 Agent「随口报数」。 - -**远期可借鉴(非 v0 范围):** - -- 文档中嵌入的「可运行示例」是否经过核验执行? -- 渲染出的结果是否带来源与 receipt? -- Agent 生成的 Marqdo 模块如何标注 `generated` / `verified`? - -这强化「文档中的数字/行为与真实执行一致」——与 Marqdo「同一份真相」高度同向。 - -### 3.7 规范本身的克制 - -OKF 规范强调:一页纸能讲清 v0.1 的互通面;v0.2 只**加词汇、不加强制规则**。 - -**对 Marqdo 文档文化:** - -- ADR 记录否决项 -- 语法草案保持短小、可验证的 conformance 描述 -- 版本演进优先加法兼容,避免随意破坏「已是有效程序」的源文件 - ---- - -## 4. 不应照搬之处 - -1. **OKF 不是语言** — 其 body 是自由散文;Marqdo body 必须有严格可执行语义。不能停在「Markdown 知识库」。 -2. **无中心 type 注册** 适合知识目录;编程语言的类型系统需要更强的一致性与检查规则。 -3. **`Attested Computation` 的 executor/attester** 面向数据平台查询核验;Marqdo 若引入类似机制,应长在「测试 / 示例求值 / 再现构建」上,而不是 BigQuery 收据模型。 -4. **保留文件名**(`index.md` / `log.md`)可参考,但是否占用需在模块设计里单独 ADR,避免与源文件约定冲突。 - ---- - -## 5. 建议纳入 Marqdo 设计议程的议题 - -来自本次调研、建议在 `design/` 或 `adr/` 中跟进: - -1. **`.mq.md` 的双重解析模型** — Markdown CST 与 Marqdo AST 如何共享同一文本、何处分叉。 -2. **生成式 OKF 清单的落盘与命令** — 路径、是否提交 git、`sync`/`doc` 行为(方向已采纳;**实现规范见 [okf.md](../design/okf.md)**,命令见 [catalog-cli.md](../design/catalog-cli.md))。 -3. **正文中的依赖声明语法** — import / 链接如何写出,供工具提取进生成清单。 -4. **Agent 友好但不 Agent 绑定** — 源格式对 LLM 可写,语义对确定性工具可检。 -5. **可渲染结果的 attestation(后期)** — 文档内求值结果的可验证性。 - ---- - -## 6. 参考链接 - -- 规范:[okf/SPEC.md](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)(v0.2) -- 仓库:[GoogleCloudPlatform/knowledge-catalog](https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf) -- 博客:[Introducing OKF](https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing) -- 博客:[OKF v0.2 trust signals](https://cloud.google.com/blog/products/data-analytics/okf-v0-2-adds-trust-signals) - ---- - -## 7. 结论 - -OKF 证明了一条与 Marqdo 同向的产业判断:**人类可读的 Markdown 可以成为机器与 Agent 的一等交换面**,前提是约定足够小、足够稳,并把信任做成可查询字段而非口头保证。 - -Marqdo 比 OKF 多走一步:Markdown 不仅是知识的容器,更是**程序的表面语法**。我们借鉴 OKF 的形态,用作**从源自动生成的依赖清单与项目目录文档**(而非人手配置);同时借鉴「格式而非平台」、路径/链接身份、以及(远期)provenance。语言设计必须单独完成——**可渲染不等于可执行,可执行才是 Marqdo 的终点。** diff --git a/doc/research/qdagent-refactor-defects-2026-10.md b/doc/research/qdagent-refactor-defects-2026-10.md deleted file mode 100755 index 6fa21d8..0000000 --- a/doc/research/qdagent-refactor-defects-2026-10.md +++ /dev/null @@ -1,489 +0,0 @@ -# 缺陷实录:qdagent 重构期间发现的 Marqdo 运行时问题 - -| | | -|---|---| -| 状态 | **Open**(D1 待决策 · D2/D3 待修复 · D4–D6 已记录) | -| 日期 | 2026-10-22 | -| 报告者 | qdagent 重构(`/workspace/qdagent`) | -| 运行时 | `marqdo 1.5.2`(本机自建 release,zig cc / glibc 2.36)· Ext pack 1.5.2 | -| 来源 | `execution/docgate.mq.md` 文档门禁开发 · `agent/qdagent.mq.md` 输出契约收紧 | -| 关联 | [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md) · [ext-agent.md](../design/ext-agent.md) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) | - ---- - -## 0. 摘要 - -qdagent 重构把「智能体输出与沉淀笔记必须是可运行 `.mq.md`」设为硬契约,并为此实现了 -机械门禁(提取 → 结构检查 → 沙箱试跑)。该过程把 Marqdo 的一批**行为与文档不一致**、 -**诊断信息不可用**、**静默降级**问题暴露出来。逐条如下。 - -| ID | 主题 | 严重度 | 状态 | -|----|------|--------|------| -| D1 | `sandbox.profile` 仅回显,不改变实际能力 | **高** | Open(安全语义) | -| D2 | `CALL:`/`调用:` 全角冒号无法解析,但提示文案推荐它 | **高** | Open(协议契约) | -| D3 | 行首数字 / `+` 使叙述行被当语句,中文文档解析失败 | 中 | Open(可用性) | -| D4 | `sandbox.run source=` 的报错丢失文件上下文 | 中 | Open(诊断) | -| D5 | 成员式取元 `[key](map)` 在键缺失时硬崩 | 中 | Open(健壮性) | -| D6 | 未绑定 GFM 表不可迭代,但报错不指向根因 | 低 | Open(诊断) | -| D7 | 沙箱内 `subtask spawn path=` 静默不可用(设计如此,需文档明示) | 低 | Documented | -| D8 | 函数名含空格:定义成功、调用必崩 | **高** | Open(不对称) | -| D9 | 未闭合引号静默吞行,退出码 0 | **高** | Open(静默) | -| D10 | `table.put` 非原地修改,累积状态静默失效 | 中 | Open(文档) | -| D11 | 函数可见环境随运行面不同(CLI 无 metadata,Web 有 + 共享 entry_bindings) | **高** | Open(行为分裂) | - ---- - -## D1 — `sandbox.profile` 仅回显,不改变实际能力 - -### 现象 - -`profile="readonly"` 打开沙箱后,`sandbox.inspect` 返回的能力仍是 default 行: - -```json -{"caps_default":{"exec":false,"fs_write":true,"net":false,"plugin":false}, - "profile":{"exec":"false","fs_write":"true","name":"default","net":"false","plugin":"false"}} -``` - -即 `fs_write` 仍为 `true`,`profile.name` 回显为 `default` 而非 `readonly`。 -沙箱内的写操作(CoW upper)照常可用。 - -### 根因 - -- `ext/ai/sandbox.mq.md` 的 `## profile` 是一张**文档用**的能力表,`open root= profile=` - 把 `profile` 透传但原生层不接收(`plugins/agent/src/sandbox.rs` 只转 `root`)。 -- 原生 `sandbox_run` 的 `RunOptions` 中四项能力**硬编码**: - -```rust -// src/host/sandbox_fs.rs -allow_fs_write: true, -allow_exec: false, -allow_net: false, -allow_plugin: false, -``` - -### 影响 - -调用方看到 `profile: readonly` 会合理地认为「沙箱内不能写」,从而把 -「用户数据落在 CoW upper 也不会污染宿主」当成安全保证; -但 `readonly` 与 `default` 实际等价,安全语义**静默失效**。 -qcagent 的门禁依赖「失败绝不落盘」,一旦有人把门禁写成「先写进沙箱再看 profile」, -就会得到错误结论。 - -### 建议 - -二选一,但必须明确: - -1. **实现**:`RunOptions` 接受 profile,`readonly` 置 `allow_fs_write=false`; - `sandbox.write` 在 readonly 下报 `fs_write denied (profile=readonly)`。 -2. **降级为文档事实并改名**:把 `## profile` 标注为「仅回显 · 不执行」, - 并从 `open root= profile=` 的公开签名里移除该参数,避免误用。 - -倾向方案 1:`readonly` 的价值正是「验证型试跑不产生任何 CoW upper」, -这与「门禁只读校验」的语义完全吻合。 - ---- - -## D2 — 全角冒号 `调用:` 无法解析,而提示文案推荐它 - -### 现象 - -`ext/ai/agent.mq.md` 的 `## extract_tool_name` 用半角 `:` 切分: - -```marqdo -**parts = > split value=`t` sep=":"** -``` - -因此只有 `CALL:x` / `调用:x`(半角)能被识别。 -但同一文件给模型的提示文案写的是全角: - -``` -When calling an allowed tool, reply with exactly one line: CALL:<name> -(Chinese ok: 调用:<name>) -``` - -模型按提示输出 `调用:tool_find`(全角)时,`split sep=":"` 不切分, -`head` 变成整行 `调用:tool_find`,匹配失败 → **静默忽略该 CALL**, -模型以为调用已发出,实际没有工具结果,最终答案缺少证据。 - -### 影响 - -这是**协议层**的静默失败:不报错、不提示,只表现为「工具没被调用」。 -对中文模型(尤其国内模型)全角标点是默认习惯,命中率不低。 - -### 建议 - -解析器同时接受全角与半角: - -```marqdo -**t2 = > replace text=`t` old=":" new=":" count=None** -**parts = > split value=`t2` sep=":"** -``` - -同类问题应在 `READ:` / `DECISION:` / `SUMMARY:` / `SLUG:` 一并检查—— -调研显示这些解析器已经支持全半角,唯独 `extract_tool_name` 与 `extract_call_args` 不一致 -(`READ` §900-942 支持全角,`CALL` §130-159 只支持半角)。 - ---- - -## D3 — 行首数字 / `+` 导致中文文档解析失败 - -### 现象 - -按 v0.3 语法,非标记行是叙述(注释)。但某些行首字符会让该行被当成语句。 - -**实测修正(1.5.2,逐条跑过)**——不是所有标记都出问题: - -| 行首 | 叙述区实测 | 说明 | -|------|-----------|------| -| `9 号是数字。` | ❌ `unrecognized statement` | 数字字面量是真语句 | -| `42` / `2026 年发布。` | ❌ `unrecognized statement` | 同上 | -| `+ 加号` | ❌ `unrecognized statement` | `+` 是前导符语法 | -| `- 列表项` | ✅ 安全 | 不构成有效 foreach → 跳过 | -| `> 引用` | ✅ 安全 | 无对应函数时不当调用 | -| `\| a \| b \|` | ✅ 安全 | 未绑定表不算语句 | -| `[{"a":1}]` | ✅ 安全 | 无归属的链接索引 → 跳过 | - -判据是**该行能否被解析成一条完整语句**:能则执行,不能则当叙述跳过。 -所以在函数体内上下文成立时,`- [`x`](`xs`)` 仍是真循环。 - -实测(qdagent 门禁): - -``` -gate.门禁 text="...\n# 结论\n\n9 号是数字。\n\n# main\n..." -→ {"ok":false,"stage":"structure", - "violations":[{"line":6,"rule":"narration_marker","text":"9 号是数字。"}]} -``` - -### 影响 - -对**人类作者**这是设计取舍(执行标记优先于叙述,符合「标记即语法」)。 -但对**LLM 生成的中文文档**是高频陷阱:中文写「2026 年」「42 条」「3 个要点」 -都是默认表达习惯,一旦出现在叙述区,整篇文档解析失败。 - -这是「文档即可运行」与「文档可读」之间的真实张力。 -qdagent 的应对是**在提示词里逐条禁止**并**门禁机械校验**(见 -`doc/design/09-document-contract-and-docgate.md`),但根源在语言层面。 - -补充(实测发现的更隐蔽问题):**未闭合引号会静默吞行**,不报错, -只在别处表现为 `undefined variable`。见使用手册 -[`tutorial/15-常见陷阱.md`](../tutorial/15-常见陷阱.md) §1.4。 - -### 建议 - -不改语义(执行标记优先是 v0.3 的基石),但增强可诊断性: - -1. `unrecognized statement` 报错附一句提示: - 「若此行为叙述,请以文字开头,或用行内代码/围栏包裹」。 -2. `marqdo check` 增加 `narration-marker` 规则,一次性列出全部风险行。 -3. 文档(`markdown-mapping-v0.3.md`)显著位置增加「中文叙述常见陷阱」小节。 - ---- - -## D4 — `sandbox.run source=` 的报错丢失文件上下文 - -### 现象 - -```marqdo -**r = > sb.run id=`id` source="> print text=hello"** -→ {"error":"<memory>: 1:1: expected heading (`#` object or `##` function), got: > print text=hello", - "ok":false,"stdout":"","value":null} -``` - -报错用 `<memory>` 作文件名,且**没有指出**「源文本必须含 `# main`」。 -对 `path=` 运行报错带真实路径,对 `source=` 只有 `<memory>`,两者诊断质量不一致。 - -### 影响 - -门禁类工具需要用 `source=` 直接跑生成的文本(避免先写盘)—— -这正是 qdagent 的用法。诊断不可用时会显著拉长修复轮次。 - -### 建议 - -`source=` 运行使用伪文件名 `sandbox-source.mq.md`(或调用方可传 `name=`), -并在缺少 `# main` 时返回明确错误: -`no # main object in source; add "# main" before statements`。 - ---- - -## D5 — 成员式取元 `[key](map)` 在键缺失时硬崩 - -### 现象 - -```marqdo -**err = [error](r)** # r 来自 sandbox.run -→ error: missing map key 'error' -``` - -`sandbox.run` **成功**时返回 `{ok, stdout, value}`,**没有** `error` 键; -失败时才有 `error`。于是「成功分支里读 error」会直接崩掉整个文档。 - -### 影响 - -同一函数的返回形状随成败变化(成功缺 `error`、失败缺 `value` 之外的键), -按「防御式读取」写的代码极易在成功路径崩溃——而成功路径往往测试覆盖更少。 - -### 建议 - -二选一: - -1. **统一形状**:`sandbox.run` 始终返回 `{ok, value, stdout, error}`(成功时 `error: ""`), - 与 `llm` 的软失败风格一致。 -2. 或在 `markdown-mapping-v0.3.md` 明确 `[key](map)` 是**断言式**取值(缺键即错), - 并提供 `get`/`has` 作为防御式写法(已有 `table.get` / `table.has`)。 - -qdagent 的修法是改用 `table.get map= key=` 取可选键,但这是每个调用方都要踩一次的坑。 - ---- - -## D6 — 未绑定 GFM 表不可迭代,但报错不指向根因 - -### 现象 - -```marqdo -`pres` = # 注意:没有 name =,未绑定 - -| 前缀 | -|------| -| "9" | - -- [p](pres) # 迭代未绑定表 -→ error: foreach needs a list or map -``` - -未绑定表不会进入绑定图,因此不可迭代;但报错只说「需要一个 list 或 map」, -不提示「这张表没有被绑定到变量」。 - -### 建议 - -报错附上下文:「`foreach` 目标未绑定;请写作 `` `name` = `` 绑定 GFM 表」。 - ---- - -## D7 — 沙箱内 `subtask spawn path=` 静默不可用(设计如此) - -`src/host/subtask.rs` 在沙箱内拒绝 `path=` / `code=` / `lang=` 的 spawn -(`subtask spawn disabled (exec capability off)`),只保留 `fn=` 进程内调用。 -这是**能力硬顶的合理结果**,但: - -- 该限制不出现在 `ext/ai/sandbox.mq.md` 的 `## profile` 说明里; -- 工具框架(`run_tool` → `subtask.spawn fn=`)恰好只用 `fn=`,因此**表面上一切正常**, - 直到有人写了基于 `path=` 的工具才发现。 - -建议在 `ext/ai/sandbox.mq.md` 顶部「能力硬顶」清单中补一条,与 exec/net/plugin 并列。 - ---- - -## D8 — 函数名含空格:定义成功,调用必崩 - -### 现象 - -```markdown -## 加一 号 - + `n` - -*`n` + 1* - -# main - -**r = > 加一 号 n=1** -``` - -``` -error: t8.mq.md:13:1: undefined variable `号` -``` - -英文同理:`## my func` 调用时报 `undefined variable func`。 - -### 根因 - -定义侧(`##` 标题)接受空格;调用侧按空格切词, -第一个词当函数名,其余当位置参数或**变量插值**。两侧不对称。 - -### 影响 - -这是**静默不对称**:`marqdo check` 通过(`无契约问题`), -只有真跑才崩,且报错指向「未定义变量」而非「函数名非法」, -排查方向被引偏。中文标识符天然爱加空格(`断言无 main`、`加一 号`), -LLM 生成代码时尤其容易命中。 - -### 建议 - -二选一: - -1. **定义侧拒绝空格**——`##` 名字含空格时报 - `function name may not contain spaces`,定义期即失败。 -2. **调用侧贪婪匹配**——按已知函数名最长前缀匹配,允许空格名(改动大,不推荐)。 - -倾向方案 1:与「标识符不含空格」的通行约定一致,成本最低。 - ---- - -## D9 — 未闭合双引号静默吞行,无任何报错 - -### 现象 - -```markdown -**s = "abc -> print text=hi -*"" -``` - -输出 `hi`,退出码 0,**没有报错**,`s` 那一行凭空消失。 - -### 根因 - -未闭合引号使该行无法解析为语句,于是被当作**叙述**跳过。 -叙述与「解析失败的语句」没有区分。 - -### 影响 - -- 变量「莫名未定义」,后续在别处报 `undefined variable`,根因被掩盖。 -- 生成的文档会少一节内容却不报错——对「文档即程序」而言这是**最危险**的一类: - 文档看起来完整、能跑、退出码 0,但少了一段。 - -### 建议 - -未闭合引号应在解析期报错: -`unterminated string literal at line N`。 -若担心破坏「叙述自由」,至少让 `marqdo check` 检出 -「以 `**` 开头但不以 `**` 结尾」的行并 warn。 - ---- - -## D10 — 取元 `[key](map)` 与非原地 `table.put` 的认知负担 - -已在 [D5](#d5--成员式取元-keymap-在键缺失时硬崩) 记录取元硬崩。 -补充**协同陷阱**:`table.put` **不原地修改**,返回新 map: - -```markdown -**m = > json.parse text={"n":0}** -**r = > table.put in=`m` at="n" value=1** -``` - -`m` 仍是 `{"n":0}`,`r` 才是 `{"n":1}`。 -于是「靠 `> table.put in=`state` ...` 累积计数」**不生效且无报错**—— -计数器永远是 0,自检看起来「全部通过」。 - -建议:在 `lib/table` 的 `put` 文档里用一句话强调「返回新表」, -并考虑提供 `put!` 或 `set!` 的就地版本以匹配直觉。 - ---- - -## D11 — 函数可见环境随运行面不同(CLI vs Web) - -### 现象 - -同一份文档,`# main` 与普通函数看到的变量环境不一致: - -| 路径 | 函数能看到的变量 | 源码 | -|------|-----------------|------| -| `# main`(CLI) | frontmatter metadata ✅ | `src/interp.rs:473` `run(..., Env::with_metadata(module), ...)` | -| **普通函数调用(CLI)** | **只有实参** | `eval_call` 内 `let mut call_env = Env::new();` | -| **浏览器 WASM 入口** | metadata ✅ + `# main` 的 `entry_bindings` ✅ | `invoke_in_entry`(`src/interp.rs:365`) | - -复现(1.5.2 实测): - -```markdown ---- -title: m1 -税率: 0.1 ---- - -## 按税率 - + `金额` - -*`金额` * `税率`* - -# main - -**r = > 按税率 金额=100** -``` - -``` -error: m1.mq.md:9:1: undefined variable `税率` -``` - -但同样在 `# main` 里直接读: - -```markdown -# main - -> print text="main里读到税率=" + `税率` # → 0.1 -``` - -**能读到。** - -### 根因 - -- `Env::with_metadata(module)` 把 frontmatter metadata 注入 env(`src/interp.rs:62`), - 但只在三处使用:`# main` 运行(473/485)、`invoke_in_entry`(365)、以及 - 入口依赖解析(411)。 -- 普通用户函数调用走 `eval_call`,用 `Env::new()` 新建空环境,只写入绑定好的实参。 - -于是「文件级常量」这个概念**只对入口可见**,函数不可见。 - -### 影响 - -1. **行为随运行面变化**:同一 `.mq.md`,在浏览器里函数能读到 frontmatter 常量、 - 还能读到 `# main` 的绑定(`entry_bindings`);在 CLI 里报 `undefined variable`。 - 这类差异极难排查——代码看着一样,结果不同。 -2. **阻断合法用法**:把配置写在 frontmatter、供多个函数共享,是文档化的自然写法, - 但今天在 CLI 下不可用,只能靠每个调用点重复传参。 -3. **掩盖真实能力**:读者会以为「函数能读文件级常量」(因为 Web 能), - 在 CLI 复现时才发现不能。 - -### 建议 - -二选一并写进文档: - -1. **统一为「函数可见 metadata」**:`eval_call` 改用 `Env::with_metadata(module)` - 再写入实参(实参优先覆盖同名 metadata)。这样 frontmatter 成为**受控的只读环境**: - 写一次、文档开头可见、可序列化,且不随调用者变化。 -2. **统一为「函数不可见 metadata」**:把 `invoke_in_entry` 也改成 `Env::new()`, - 只保留 `# main` 可见,并在文档中明确「frontmatter 只供入口使用」。 - -倾向方案 1:它把已存在的机制补成一致的、静态可判定的「常量默认值」通道, -对文档化使用场景价值明显,且不引入动态作用域的风险(见 -[ambient-parameters-evaluation.md](../design/ambient-parameters-evaluation.md) §4.3)。 - ---- - -## 附录:本次开发中确认正常的项 - -避免误报,以下行为经实测**符合文档**,不在缺陷之列: - -| 项 | 实测 | -|----|------| -| 沙箱 CoW 隔离 | 宿主目录在 `commit` 前不变,`diff` 正确列出 write/remove | -| 沙箱能力默认值 | `exec:false` / `net:false` / `plugin:false` / `fs_write:true (CoW only)` | -| `sandbox.run` 成功形状 | `{ok:true, value, stdout}` | -| `agent.run efi=` | EKC preflight 拦截 CREATE,返回 `{status:"error", error:"efi_create_denied"}` | -| `agent.run sandbox=` | CREATE 阶段走 CoW trial,ok 才 commit | -| LLM 软失败 | transport 失败返回 `status:"error"` 而非中断 VM | -| `marqdo check` 契约检查 | 对 qdagent 全部改动文件返回「无契约问题」 | - ---- - -## 复现清单 - -| ID | 复现 | 观察点 | -|----|------|--------| -| D1 | `sb.open root="." profile="readonly"` + `sb.inspect` | `profile.name` 回显 `default`,`fs_write:true` | -| D2 | 模型输出 `调用:tool_find`(全角) | 无工具结果、无报错 | -| D3 | 文档叙述区写 `9 号是数字。` 或 `+ 加号` | `unrecognized statement` / 门禁 `narration_marker` | -| D4 | `sb.run id= source="> print text=x"` | `error` 以 `<memory>` 开头,未提示缺 `# main` | -| D5 | `[error](r)`,`r` 为成功返回 | `missing map key 'error'` | -| D6 | 未绑定 GFM 表后 `- [x](表)` | `foreach needs a list or map` | -| D8 | `## my func` + `> my func n=1` | `undefined variable func`(check 却通过) | -| D9 | `**s = "abc` 不闭合 | 静默吞行,退出码 0 | -| D10 | `> table.put in=`m` at=…` 后读 `m` | 原表未变;计数永远是 0 | -| D11 | frontmatter 写 `税率: 0.1`,函数体读 `` `税率` `` | CLI 报 `undefined variable`;`# main` 里却能读到 | - ---- - -## 变更记录 - -| 日期 | 变更 | -|------|------| -| 2026-10-22 | 首次记录 D1–D7(qdagent 文档门禁开发期) | -| 2026-10-22 | 补 D8–D10;D3 按逐条实测收敛(`-` / `>` / `\|` / `[` 实为安全,只数字与 `+` 报错);配套使用手册 `tutorial/15-常见陷阱.md` | diff --git a/doc/research/stdlib-gaps-after-mid.md b/doc/research/stdlib-gaps-after-mid.md deleted file mode 100755 index 8e92675..0000000 --- a/doc/research/stdlib-gaps-after-mid.md +++ /dev/null @@ -1,146 +0,0 @@ -# 调研:Mid M1–M6 之后标准库还缺什么 - -历史调研快照:以下缺口已由 Mid2 和后续标准库闭环分批解决,不能作为当前缺失清单。当前能力请从[标准库源码](../../lib/文件.mq.md)与[验收说明](../design/stdlib-handbook.md)核对。 - -| | | -|---|---| -| 状态 | **调研笔记 · 缺口盘点(M1–M6 闭环之后)** | -| 日期 | 2026-09-08 | -| 基线 | **v0.3.7+** · Mid M1–M6 **done** | -| 已落地设计 | [stdlib-mid.md](../design/stdlib-mid.md) · [stdlib-modules.md](../design/stdlib-modules.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) | -| 补齐设计 | [stdlib-mid2.md](../design/stdlib-mid2.md) | -| 实现路线 | [stdlib-mid2.md](../roadmap/stdlib-mid2.md) | -| 外部对照 | Python stdlib([use-case 索引](https://www.socratopia.app/library/python-programming-ai-era-en/chapter-15) · [PEP 680 tomllib](https://peps.python.org/pep-0680/))· Go `strings`/`regexp`/`encoding/*`/`crypto`/`path`/`time`/`net/url` · Node 内置 vs userland | - ---- - -## 0. 一句话结论 - -**M1–M6 已把「写日常脚本 / 多数扩展库不再事事插件」的硬缺口补齐。** 相对 Python / Go 的「通用原语层」,Marqdo **不再缺** 正则、编解码、路径、哈希、CSV、集合糖、CLI、日志、UUID。 - -仍缺的是 **第二档通用能力**:日历与时区、URL/查询串、配置格式(优先 TOML)、HTML 安全转义、文件系统再厚一点(`mkdir -p` / 元数据 / 递归删除)、轻量统计。这些**值得开 Mid2(M7+)**,但**不应**再开一轮「事事插件」;也**不要**把 YAML 全家桶、HTTP 服务端、SQLite、图像/ML 塞进 `lib/`。 - ---- - -## 1. 已有基线(不是缺口) - -| 族 | Marqdo | 对标 | -|----|--------|------| -| 文本 / 正则 | `text`++ · `re` | Python `str`/`re` · Go `strings`/`regexp` | -| 编解码 | `encoding`(base64/hex)· `net.url_encode` | Go `encoding/base64`/`hex` · Python `base64`/`binascii` | -| 路径 / 文件 | `path` · `fs`(含 copy/move/temp) | Go `path/filepath` · Python `pathlib`(子集) | -| 完整性 / 机密 | `hash` · `secrets` | Go `crypto` 子集 · Python `hashlib`/`secrets` | -| 表数据 | `csv` · `table`++ · `json` | Go `encoding/csv`/`json` · Python `csv`/`json` | -| CLI / 可观测 | `cli` · `log` · `uuid` | Python `argparse`/`logging`/`uuid`(窄) | -| 时间(极简) | `time`:unix/ms · format · parse · sleep | **远薄于** Python `datetime`/`zoneinfo` · Go `time` | -| 网络客户端 | `net`:HTTP/SSE/cookie/multipart/markdown | Go `net/http` **客户端**侧;服务端在 `ext/web` | -| 数学 | `math`(含公式/作图) | Python `math` + 教学向扩展 | - -准入宪法仍见 [stdlib-mid.md](../design/stdlib-mid.md) §3:跨领域、难写对、解锁无插件写库、宿主面积极小。 - ---- - -## 2. 对照总表(按「脚本作者是否还要 foreign / 自造轮子」) - -| 能力 | Python / Go 常态 | Marqdo 现状 | 缺口级别 | Mid2 建议 | -|------|------------------|-------------|----------|-----------| -| 日历日期 / 时区 / timedelta | `datetime`+`zoneinfo` · `time` | 仅 unix 戳 + 简单 format/parse | **高** | **M7** `datetime` | -| URL 解析 / 查询串 | `urllib.parse` · `net/url` | 仅 `url_encode` | **高** | **M7** `url`(或并入 `net`) | -| 配置 TOML 只读 | `tomllib`(PEP 680) | 无 | **中高** | **M8** `toml`(只读优先) | -| 配置 YAML | 第三方;**故意不进** CPython | 无 | **低 / 慎入** | 默认 **不做**;与 Python 同理(复杂度/安全) | -| HTML / XML 转义 | `html` · `html/template` 转义 | 无(`markdown_parse` ≠ 转义) | **中** | **M8** `html` 或 `text.html_escape` | -| `mkdir -p` / 递归删 / stat | `pathlib`/`shutil` | `make_dir`/`remove` 偏浅 | **中** | **M9** `fs` 加厚 | -| 文件元数据(size/mtime) | `os.stat` · `Path.stat` | 无一等 API | **中** | **M9** | -| base32 / percent 完整 | `base64.b32*` · `url` | 无 base32 | **低–中** | **M8** `encoding` 加厚 | -| 轻量统计 | `statistics` | `math` 无 mean/median | **低–中** | **M10** `stats` 或 `math` 薄加 | -| 计数 / 默认字典 / deque | `collections` | `table` 可凑 | **低** | 优先用 `table`;必要时 M10 `collections` 极薄 | -| 组合迭代 | `itertools` | 无 | **低** | 多数可用 `table`;**延后** | -| 模板引擎 | Jinja / Go `text/template` | 无 | **不准入 Mid** | 应用层 / 未来 ext | -| SQLite 客户端 | `sqlite3` · `database/sql` | **`ext/web` `# db`** | **不准入** | 保持扩展 | -| HTTP 服务端 | — | **`ext/web`** | **不准入** | 已关闭(宿主波次另文) | -| 密码哈希 Argon2 | 第三方 / 框架 | `ext/web` 已有 | **不准入 Mid** | 安全产品面 | -| 完整 TLS/证书 API | `ssl` · `crypto/tls` | 客户端 HTTPS 由 ureq | **不准入** | 宿主实现细节即可 | -| 压缩 zip/tar | `zipfile` · `archive/zip` | 无 | **低** | 可选 M10;体积敏感 | -| 环境 `.env` | 第三方;Go 常自写 | **`sys.load_dotenv` 已有** | 无 | — | - ---- - -## 3. 分项说明(高优先级) - -### 3.1 日历 / 时区(M7 候选之首) - -**问题** -脚本与站点大量需要「今天」「本地日界」「RFC3339」「时区换算」。现有 `time.parse`/`format` 够演示,不够「难写对」的日历语义(闰秒除外,但 DST / offset 已够劝退字符串拼接)。 - -**对照** -Python 强调 **aware datetime + zoneinfo**;Go `time.Location` 是日常依赖。Mid 原文已把「完整 datetime 时区库」标为刻意延后——M1–M6 完成后应升格。 - -**建议窄 API(设计文锁定)** -`now` / `parse` / `format` / `add`(天/时)/ `to_unix` / `from_unix` / 可选 `in_zone`(IANA 或固定 offset)。**不做**完整历法 UI、农历、业务假期库。 - -### 3.2 URL 与查询串 - -**问题** -`url_encode` 只解决「编码一段」;解析 `https://a/b?x=1&y=2#frag`、合并 query、取 path 仍靠 `re` 自造。浏览器代理 / `invoke` / webhook 场景高频。 - -**建议** -`url.parse` → `{scheme,host,path,query,fragment}`;`url.query_parse` / `query_stringify`;与 `url_encode` 边界写进 `net` vs 新 `lib/url`。 - -### 3.3 TOML vs YAML - -**外部事实** -Python 因 **打包引导**(`pyproject.toml`)接受只读 `tomllib`([PEP 680](https://peps.python.org/pep-0680/));YAML 多次被拒:规范复杂、实现难维护、安全面大。 - -**对 Marqdo** -catalog / 工具配置若走向 TOML,只读 `toml.parse` 性价比高。YAML:**默认不准入 Mid**;若 public 强需求,单独 ADR,且优先「JSON 超集子集」而非完整 1.2。 - -### 3.4 HTML 转义 - -**问题** -`ext/web` 与浏览器 WASM 拼 HTML 时,缺 `escape` 易 XSS。这是「难写对 / 安全相关」的经典 stdlib 项(Python `html.escape`)。 - -**建议** -极薄:`html.escape` / `unescape`(或挂 `text`)。**不做** DOM / 模板语言。 - -### 3.5 文件系统再厚 - -**问题** -`make_dir` 是否递归、`remove` 是否递归、无 `stat`(size/mtime)、无 `walk`——脚本仍会 `foreign` 或脆弱字符串。 - -**建议** -`fs.make_dirs` · `fs.remove_tree` · `fs.stat` · 可选 `fs.walk`(返回路径列表,非惰性迭代器协议)。 - ---- - -## 4. 明确「不是缺口」 - -| 项 | 说明 | -|----|------| -| Mid M1–M6 清单本身 | 已收口;不要用本表重开 base64/re | -| HTTP 服务 / DB / Agent | `ext/*`;见 [ext-hosting](ext-hosting-gaps.md) | -| Dense embedding / 向量库默认化 | OKF 路线不变 | -| 完整 `collections` / `itertools` 类型系统 | 语言没有泛型迭代协议;用 `table` | -| 「对齐 Python 模块个数」 | 反模式;对齐**用例与难写对** | - ---- - -## 5. 优先级建议(转入 Mid2) - -| 优先级 | 波次草案 | 内容 | -|--------|----------|------| -| **高** | **M7** | `datetime` + `url` — **done** | -| **高** | **M8** | `toml` 只读 + `html.escape` + `encoding` base32 — **done** | -| **中** | **M9** | `fs` 加厚(dirs/stat/walk) — **done** | -| **低** | **M10** | `stats` 薄 · log 字段 · (zip 默认跳过) — **done**(zip 仍跳过) | -| **won't** | — | 完整 YAML · 模板引擎 · sqlite 进 `lib/` | - ---- - -## 6. 与其它文档 - -| 文档 | 关系 | -|------|------| -| [stdlib-mid2.md](../design/stdlib-mid2.md) | **补齐设计(作者 API + 边界)** | -| [stdlib-mid2.md](../roadmap/stdlib-mid2.md) | 实现波次 M7–M10 | -| [stdlib-mid.md](../design/stdlib-mid.md) | Mid1 宪法;本调研不改准入原则 | -| [web-net-capabilities.md](../design/web-net-capabilities.md) | 网络服务端能力在 ext,不进 Mid2 | diff --git a/doc/roadmap/agent-reliability-crossrepo-2026-10-27.md b/doc/roadmap/agent-reliability-crossrepo-2026-10-27.md deleted file mode 100755 index 6027369..0000000 --- a/doc/roadmap/agent-reliability-crossrepo-2026-10-27.md +++ /dev/null @@ -1,194 +0,0 @@ -# 跨仓 Agent 可靠性开发计划(2026-10-27) - -| 项目 | 约定 | -|---|---| -| 状态 | **Proposed / planning**;本文是排期与验收编排,**不是**已实现声明 | -| 日期 | 2026-10-27(Asia/Shanghai) | -| 基线 | Marqdo `6ffe5ce` / 2.1.4;qdagent `c4c976c`(设计文档基线曾为 `16f26d7` / `68b757e`;排期以当前 HEAD 为准) | -| 协议真源 | [智能体能力补足设计](../design/agent-reliability-tools-resources-2026-10-27.md) | -| 产品真源 | [qdagent 智能体能力与预览](../../../qdagent/doc/design/agent-capabilities-and-preview-2026-10-27.md)(同级 checkout) | -| 证据 | [官方调研与 F01–F20](../research/agent-capabilities-2026-10-27.md) | -| 产品侧镜像 | [qdagent 开发计划镜像](../../../qdagent/doc/roadmap/agent-capabilities-development-2026-10-27.md) | - -本文只编排依赖、落点、门禁与发布次序。**不发明第二套 Agent Framework**;不修改 `doc/next/`;不把 capability bit 在合同实测前标真。协议字段以设计文档为准,路线图只引用不另造 schema。 - -## 1. 目标与架构边界 - -让同一套文档原生 Agent 在模型错误、工具失败、网络中断后有界恢复;工具可发现、可验证、可审计;结果同时服务模型上下文与用户阅读。保留 `.mq.md` 工作簿、EKC 与验证证据的权威地位。 - -| 议题 | Marqdo 所有 | qdagent 所有 | -|---|---|---| -| 恢复 | ErrorV1、预算、CheckpointV2、效应账本、运行/事件语义 | 恢复按钮、会话关联、凭证修复入口、产品政策 | -| 工具 | ToolSpec/Call/Result、schema、权限执行、并发、MCP 传输 | 业务工具、默认集合、连接配置、用户授权范围 | -| 回答 | AgentOutput 分通道、输出预算、ContextPackV2 | 简洁/标准/详细策略、摘要与产物卡、ASK/BUILD | -| 资源 | ResourceRef/View、只读预览、转换插件接口 | 笔记/文件/产物 ID 映射、owner 权限、预览布局 | -| 知识 | preflight/reuse/verify/compile、记忆原语 | 何时提议沉淀、用户画像与可见管理 | -| 调试 | span、结构化事件、用量与错误码 | 可读过程、运行详情、产品评测语料 | - -## 2. 现状(不再重做) - -| 已落地基础 | 说明 | -|---|---| -| Agent A0–A4、O1–O5 | 文档原生 step/plan/run、沙盒与优化波次;扩展 `ext/ai/agent`,不另造循环 | -| 隔离 Web 运行时(ADR 0009) | `src/runtime/` Verified;本轮补 Agent 步骤语义,不重建进程池 | -| Workbench 合同切片 | DocumentView / Locator / capabilities;Partial,随本轮补 F 矩阵 | -| 可执行知识 S0–S6 | 本地确定性子集已门禁;**不重开 S0–S6** | - -本轮增量(设计已锁、代码待做):`AgentErrorV1`、`CheckpointV2` + effect ledger、`ToolSpecV1` 统一调度、`ResourceViewV1`、`AgentOutputV1` 通道、`ContextPackV2`。 - -**产品措辞约束**:本地门禁绿 ≠ 远程/多租户安全;≠「知识验证 + Agent 复用闭环」全产品完成。 - -## 3. 跨仓依赖与日历顺序 - -```mermaid -flowchart TD - MA0[M-A0 contracts] --> QA0[Q-A0 fixtures] - MA0 --> MA3[M-A3 ResourceView] - MA0 --> MA1[M-A1 Error and Checkpoint] - MA0 --> MA2[M-A2 ToolSpec] - QA0 --> QA1[Q-A1 answer outcome] - QA0 --> QA2[Q-A2 right panel] - MA3 --> QA2 - QA1 --> QA3[Q-A3 recovery UX] - MA1 --> QA3 - MA2 --> QA4[Q-A4 product tools] - MA1 --> MA4[M-A4 channels ContextPack] - MA2 --> MA4 - MA4 --> QA4 - MA3 --> QA5[Q-A5 formats] - MA5[M-A5 ledger PDF MCP] --> QA5 - MA4 --> QA6[Q-A6 plan memory] - MA5 --> QA7[Q-A7 connectors] - MA6[M-A6 subagents] --> QA7 -``` - -### 3.1 强制顺序原则 - -1. 先 **M-A0 ∥ Q-A0** 冻结跨仓字段与缺陷 fixtures。 -2. 立刻 **Q-A1 + Q-A2 + M-A3(文本/md/mq)**——**不得**被完整 CheckpointV2 阻塞。 -3. **M-A1** 可先上只读重试 + 原子 checkpoint;**Q-A3** 终态快照可先行,写恢复等 effect ledger。 -4. 再 **M-A2 ∥ Q-A4** → **M-A4 / Q-A6** → **M-A5 / Q-A5** → **M-A6 / Q-A7**。 -5. 四类恢复必须分开:事件续订 / 步骤重试 / 工作流 resume(新 attempt + `resumed_from`)/ 答案再生成。 - -## 4. 阶段包明细 - -### Wave 0 — 合同 - -| 包 | 修改/新增建议 | 交付内容 | 退出门槛 | -|---|---|---|---| -| **M-A0** | `src/workbench/capabilities.rs`、`tests/workbench_contracts.rs`、新增合同 fixtures | Error/Tool/Resource/Output/Context 协议、旧适配、状态映射;capability **默认 false** | 跨仓字段冻结;未知字段/版本可降级 | -| **Q-A0** | 缺陷样例、HTTP 路由清单、answer/resource fixtures;设计入口 | 固化 F01–F20 相关 fixtures;`mock`/`live` 证据区分 | 与 M-A0 字段一致;不把 mock 当 live | - -### Wave 1 — 可见痛点 - -| 包 | 修改/新增建议 | 交付内容 | 退出门槛 | -|---|---|---|---| -| **Q-A1** | `agent/qdagent.mq.md`、`gateway/openai`、api 映射 | accepted candidate;`outcome` ≠ HTTP `ok`;摘要投影;ASK 不强制六节 | 修复后只展示 B;未通过不标成功(F01/F02/F03) | -| **M-A3(首批)** | `src/workbench/document_view.rs`、新 `resource_view`、媒体适配 | ResourceRef/View;md/txt/code/mq 静态阅读;no-exec | 资源定位与安全语料通过(F15) | -| **Q-A2** | `DesktopFrame`、panel store、`DocumentReader`、ResourcePanel/Preview | 统一右栏;笔记/文件点击不导航;同 renderer | 所有入口同预览(F09–F14) | - -### Wave 2 — 恢复 - -| 包 | 修改/新增建议 | 交付内容 | 退出门槛 | -|---|---|---|---| -| **M-A1** | `ext/ai/agent.mq.md`、`plugins/agent/src/resume.rs`、recovery/effects 模块 | ErrorV1、有界修复、accepted candidate 绑定、CheckpointV2 原子写 | 故障注入不重复写;旧记录不冒险自动恢复(F06) | -| **Q-A3** | `execution/turns`、session store、`api.ts` | 终态快照补齐、恢复动作、错误卡 | 事件恢复 0 工具调用;写恢复须 ledger(F08) | - -### Wave 3 — 工具与通道 - -| 包 | 修改/新增建议 | 交付内容 | 退出门槛 | -|---|---|---|---| -| **M-A2** | `plugins/agent/src/lib.rs`、`mcp_client.rs`、tool registry/dispatcher | ToolSpec/Call/Result;CALL+native 单通道;分页与结果资源 | 未授权调用为 0;失败结果结构正确(F04/F05/F18) | -| **M-A4** | `ext/ai/agent.mq.md`、`plugins/llm`、`src/workbench/run_context.rs` | AgentOutput 通道、预算、ContextPackV2 | 原生与纯文本 provider fixture 可用(F01/F19) | -| **Q-A4** | `agent/tools/`、工具目录、ContextAttachment | 业务工具;保留旧五工程工具别名 | 找→读→改→验证→预览真实闭环 | -| **Q-A6** | 计划折叠、预算 UI、profile 忘记、候选沉淀 | ResponsePolicy UX、记忆边界 | 压缩与恢复不丢用户约束 | - -### Wave 4 — 持久与格式 - -| 包 | 修改/新增建议 | 交付内容 | 退出门槛 | -|---|---|---|---| -| **M-A5** | `src/runtime/` 存储/事件适配、MCP 与转换插件 | ledger↔runtime 对账、PDF/Office 插件、远程 MCP | crash/restart 通过;诚实探测(F16–F18) | -| **Q-A5** | JSON/CSV/图片/PDF UI、网页来源与页/行引用 | 格式扩展与转换进度 | 缺插件可读降级;PDF 不假称 OCR | -| **M-A6 / Q-A7** | plan/subtask/sandbox;MCP 配置与委派 | 程序化工具、有界委派、可选浏览器 | **后置**;须证明收益与预算/效应可控 | - -## 5. F01–F20 → 包映射 - -| ID | 摘要 | Marqdo | qdagent | 主要验收 | -|---|---|---|---|---| -| F01 | ASK/BUILD 强制六节 | M-A4 输出通道 | Q-A1 ResponsePolicy | QA-01、MA-T12 | -| F02 | 修复后仍返回 raw | M-A1 accepted 绑定 | Q-A1 | QA-03、MA-T12 | -| F03 | `gated_error` 仍 `status=ok` | M-A0/M-A1 ErrorV1 | Q-A1 envelope | QA-04 | -| F04 | 默认仅五工程工具 | M-A2 registry | Q-A4 目录 | QA-17 | -| F05 | 已有 step/plan/run | **扩展** agent.mq.md | — | 不另造 loop | -| F06 | `resume_save` 裸 `fs::write` | M-A1 CheckpointV2 | Q-A3 UX | MA-T03/T04 | -| F07 | runtime 已有 | 复用,不重建 | 接线恢复 API | — | -| F08 | `resumeTurn` 终态直返 | 事件 vs 再执行分离 | Q-A3 快照补齐 | QA-13、MA-T05 | -| F09–F12 | 右栏/笔记预览缺陷 | M-A3 ResourceView | Q-A2 | QA-06–QA-09 | -| F13 | DocumentReader 非通用分派 | DocumentView 保留 mq;ResourceView 其它 | 预览分派 | QA-09 | -| F14 | 正则 HTML 清洗 | 生产侧 allowlist | DOMPurify + CSP | QA-11、MA-T11 | -| F15 | DocumentView no-exec | 保持;ResourceView 禁 run/verify | — | MA-T10 | -| F16 | pdf/docx/ocr unavailable | M-A5 插件 + 诚实探测 | Q-A5 | QA-10 | -| F17 | legacy web_search 临时文件 | 优先框架 net 工具 | 迁移工具 | QA-17、F20 | -| F18 | MCP stdio 已有 | M-A2/5 timeout/cancel/remote | 连接器配置 | MA-T07 | -| F19 | 历史字符串 standing | M-A4 ContextPackV2 | compose_messages | QA-19、MA-T13 | -| F20 | 弱临时名;workspace `.` | 安全临时文件 + ResourceRef | 资源解析 | QA-08、MA-T11 | - -## 6. 验收与发布 - -### 6.1 Marqdo 门禁(MA-T01–T14) - -以设计文档 §10 为准;基础机制用确定性 fake provider/tool;真实 provider 少量单独 smoke 并记费用。摘要: - -| 编号 | 必须观察到 | -|---|---| -| MA-T01 | 429 后成功:退避、计量、单一 accepted answer | -| MA-T02 | schema 连续错:一次修复后停;无效参数不执行工具 | -| MA-T03 | 写成功但 receipt 前提杀:unknown_effect→对账;写计数不增 | -| MA-T04 | checkpoint 写一半杀进程:完整上一检查点或明确 corrupt | -| MA-T05 | 终态事件丢失:快照恢复完整消息;工具次数不增 | -| MA-T06 | 重复/并发恢复:同一幂等键一个 attempt | -| MA-T07 | 取消 vs 重试:取消后无新工具调用 | -| MA-T08 | 权限/版本变更:stale/conflict/forbidden | -| MA-T09 | 伪造 CALL/system:不越白名单 | -| MA-T10 | `.mq.md` 预览含写/联网:哨兵不变;只读或安全降级 | -| MA-T11 | 格式/超长/路径逃逸:正确 renderer;越界拒绝;无注入 | -| MA-T12 | 修复 A→B:answer/artifact/verification 均绑定 B digest | -| MA-T13 | 上下文压缩后:约束、待决效应、版本、预算不丢 | -| MA-T14 | 旧 CALL/DocumentView:基础可用;缺失能力明确返回 | - -先跑受影响的 Rust/Go/Marqdo 合同与隔离 runtime 金样例,再做跨仓 HTTP/browser gate。性能目标(须记录机器/并发/冷暖缓存):已缓存 100 KiB 文本视图服务端 p95 < 300 ms;核心工具发现 p95 < 100 ms。 - -### 6.2 qdagent 门禁(QA-01–QA-20) - -以产品设计 §13 为准;路径必须 `serve → api → 权威业务函数 →` 真实前端。零容忍:重复写效应、预览执行副作用、跨 workspace 越权。 - -实现时:`python3 scripts/check-contracts.py`、相关 workbench 测试、前端 `npm test` / `npm run build`,再跑 Playwright;无服务时 E2E 须明确 skip/失败原因。 - -### 6.3 Feature flags 与灰度 - -建议开关:`agent_output_v2`、`resource_panel_v2`、`agent_tools_v1`、`agent_recovery_v2`。启用取决于 runtime capability + 服务端政策,不由前端单独决定。 - -灰度:内部单 workspace → 多 workspace → 真 provider/断网 → 默认开启。关闭恢复时必须停止接纳新恢复请求并保留 attempt 状态,**禁止**切回会盲重做写操作的旧路径。 - -兼容迁移:新增协议 → 双读 → 新写 → 验证 → 逐步移除旧适配。旧 resume JSON 可读但不能自动升级成带副作用保证的检查点。 - -## 7. 伴生轨(登记,不阻塞主线) - -| 轨 | 动作 | -|---|---| -| 可执行知识 S0–S6 | **不重开**;消费 BoundCall/EKC;话术保持「本地子集」 | -| 知识支撑 F0(M02/M03/M05) | **并行伴生**:provenance/closure invalidate、真 verify API、Skill 无冲突 | -| Workbench Partial | 随 M-A0/M-A3 补 F 矩阵与 adapters;不重写 M00–M05 | -| 语言 next-phase P3 / Wave B1 评测 | **延后** | -| Web Document/Endpoint | 遵守 ADR 0007;禁止 compose_/json bag 回退 | - -## 8. 下一步开工(第一刀实现切片) - -确认本路线图入库后,**另开实现回合**(本文件仅文档): - -1. **M-A0 + Q-A0**:合同与 fixtures -2. **Q-A1**:raw→accepted、outcome 一致性 -3. **Q-A3 子集**:终态快照补齐 -4. **Q-A2 + M-A3 子集**:右栏真实预览(笔记 / md / mq / txt / code) - -发布判据是 MA-T* / QA-* 与真实 HTTP/browser 证据,不是接口返回 200 或代码中出现某符号名。 diff --git a/doc/roadmap/agent-streaming.md b/doc/roadmap/agent-streaming.md deleted file mode 100755 index 1bdc306..0000000 --- a/doc/roadmap/agent-streaming.md +++ /dev/null @@ -1,181 +0,0 @@ -# 智能体流式输出(未来规划) - -| | | -|---|---| -| 状态 | **S0–S3 已落地**(view SSE) | -| 日期 | 2026-08-10 | -| 相关 | [ext-llm.md](../design/ext-llm.md) · [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md)(父 Plan-and-Move / CALL·READ) · [stdlib-subtask.md](../design/stdlib-subtask.md) · [view.md](../design/view.md) | -| 痛点 | `complete` / `step` / `plan` 均为整段返回;用户看不到思考与中间输出 | - ---- - -## 1. 问题 - -当前体验: - -| 路径 | 行为 | 体验问题 | -|------|------|----------| -| `` `model`.complete `` | 等 HTTP 整包结束再返回字符串 | 长推理「卡住」无反馈 | -| `` `助手`.step `` | 拼提示 → complete → 解析 CALL/答案 | 工具轮次与模型吐字均不可见 | -| `` `助手`.plan `` | 多轮 spawn + 父 LLM;子任务默认 `quiet` | 父侧只有最终 `result` map;过程静默 | - -这与「文档驱动、过程可审计」并不矛盾——**落盘真相**仍可以是工作簿与写回;缺的是**运行时的渐进呈现**(TTY / view / 调用方回调)。 - -约束回顾(不得破坏): - -1. 文件子任务默认静默:答案走 `# main` **返回值**([stdlib-subtask.md](../design/stdlib-subtask.md))。 -2. `ext/**` 不直调 `host_*`;流式原语进 `ext/ai/llm` + 必要时薄 host/net。 -3. 多轮哲学仍是模式 C(子文件接力 + OKF),不是把 transcript 堆进单文件。 - ---- - -## 2. 目标 - -1. **可选**流式看到:模型增量文本、(可选)工具调用开始/结束、plan 轮次边界。 -2. 默认保持今日语义:未开流式 = 整段 `complete` / 整包 `result`。 -3. 流式是**呈现与旁路**,不替代 `**返回**` / `plan.result` / 写回。 -4. CLI、`marqdo view`、嵌入调用方可共用同一事件模型。 - -非目标(本规划): - -- 把 Marqdo 做成聊天产品 UI 框架。 -- 强制所有 `print` 改流式 API。 -- 在 quiet 子进程里把子 `print` 默认真传父 TTY(与返回优先冲突)。 - ---- - -## 3. 分层设计 - -```text -LLM 供应商 SSE / chunked - ↓ -ext/ai/llm stream=True → 事件迭代 / 回调 / 写 channel - ↓ -ext/ai/agent step/plan 订阅事件 → 可选透传或写回「过程槽」 - ↓ -呈现面:TTY | view EventSource | 调用方 foreach 事件表 -``` - -### 3.1 事件模型(锁定方向) - -统一为可 JSON 化的小 map(便于写回与 view): - -| `type` | 含义 | 主要字段 | -|--------|------|----------| -| `reasoning` | 模型思考增量(如 DeepSeek `reasoning_content`) | `text` | -| `delta` | 模型答案增量文本 | `text` | -| `tool_start` / `tool_end` | 工具轮(父 plan CALL/READ 已发;view Tool 卡) | `name`, `kind?`, `result?` | -| `round` | plan 轮次边界(子工作簿跑完) | `round`, `workbook`, `exit_code?`, `result?`(子返回值摘要) | -| `decision` | DONE / CONTINUE / RUN | `decision`, `summary?` | -| `done` | 本调用结束 | `result`(答案正文;不含 thinking) | -| `error` | 失败 | `message` | - -中英键名可在 L1 包装层镜像;插件/wire 先用英文 `type`。 - -### 3.2 `llm`:流式完成 - -```markdown -*`model` = > llm * -*`stream` = > `model`.complete prompt=… stream=True * -- [`ev`](`stream`) - *`t` = > json.get value=`ev` key=type * - 1. `t` == delta - *`chunk` = > json.get value=`ev` key=text * - > print text=`chunk` - 2. `t` == done - *`answer` = > json.get value=`ev` key=result * -``` - -或回调形(若日后支持函数值作实参):`on_delta=` —— v1 优先 **事件列表 / 可迭代句柄**,少发明回调语法。 - -实现要点: - -- `lib/net` 或 llm 插件支持 **读 SSE / chunked body**(今日 `http_post` 偏整包)。 -- `stream=False`(默认)路径零行为变化。 -- 金样:mock SSE fixture,不强制打真网。 - -### 3.3 `agent.step` / `plan`:过程透传 - -| 开关(草案) | 默认 | 行为 | -|--------------|------|------| -| `stream=False` | ✓ | 与今日相同 | -| `stream=True` | | 向**当前进程**呈现面推送事件;返回值仍是最终 map | -| `trace=True` | 可选 | 把事件追加写入调用行写回槽 `trace`(审计);与 TTY 流式可分立 | - -plan 特有: - -- `await_workbook` **前**发 `await`(view Child running 占位);结束后发 `round`。 -- 父 pre-run 分解发 `decompose`。 -- 父 LLM 的 `complete` 若 `stream=True`,`delta` 冒泡到 plan 的 stream。 -- **子文件 quiet 不变(TTY)**;默认骨架 `step stream=True`,子 EventBus 经 `MARQDO_EVENT_FORWARD` **实时转发**到父 SSE(`source=child`)。答案仍以 `# main` 返回为准。 - -### 3.4 呈现面 - -| 面 | 做法 | -|----|------| -| CLI | `delta` 直接写 stdout(无额外 JSON 包装);结构化事件可 `--trace-events` 走 stderr / 旁路文件 | -| `marqdo view` | Execution 区 Stream 面板订阅 SSE(见 [view.md](../design/view.md) §5.1):Thinking / Answer / Child 分栏,非混色日志 | -| 库调用方 | foreach 事件集合,自行决定 UI | - -**view Stream 锁定(S3 UI):** - -1. `reasoning` → 可折叠 Thinking;`delta` → 主文 Answer(连续拼接)。 -2. `round` → 独立 Child/Workbook 卡(路径链 + 可选 `result`);不与父 Answer 混排。 -3. `decision` → 时间线条目标记。 -4. 视觉跟 view HIG 浅色壳,不用深色终端底。 -5. **传输**:`POST /api/run` 直接 SSE;前端 `fetch`+`ReadableStream`(非页载 EventSource);rAF 合批;stick-to-bottom。 - ---- - -## 4. 与「返回优先」的关系 - -| 通道 | 职责 | -|------|------| -| stream / trace | **过程**(体验、调试、审计) | -| `# main` `**…**` / `plan.result` | **结果**(编排、OKF、调用方消费) | -| writeback `ok`/`error` | **落盘摘要**(默认可关) | - -禁止:仅靠 stream 文本当作子任务成功条件;DONE / 固化仍看退出码、返回值与源码形态。 - ---- - -## 5. 推荐落地顺序 - -```text -S0 net/llm:SSE 读 + complete stream=True + 事件 foreach ✅ -S1 step stream=True(echo 增量;返回 map 不变) ✅ -S2 plan stream=True:round + 父 delta;trace 写回可选 ✅ -S3 view 订阅(EventBus + GET /api/events + POST /api/run) ✅ -``` - -### 开放点决议(S0) - -1. **Eager 事件列表**(非惰性句柄):`complete stream=True` 返回 `List` of maps,可用今日 foreach。 -2. **默认不自动 print**:`echo=False`;需要边读边打时传 `echo=True` / `打印增量=真`。 -3. 中文:`## 运行` 用 `流式=` / `打印增量=`。 - -### 开放点决议(S2) - -1. `plan` / `多步` 增加 `stream` / `echo` / `trace`(中文 `流式` / `打印增量` / `轨迹`)。 -2. 事件挂在返回 map 的 `events`;父 `complete` 只冒泡 `delta`/`error`(嵌套 `done` 不进列表)。 -3. `trace=True` → 写回槽 `trace`(与 TTY `echo` 可分立)。 -4. **体验(父先子后)**:非命中路径先 `decompose`(SSE + 可选 TTY `plan:decompose`),再 `await`(SSE 占位 + 可选 TTY `plan:await`),子 quiet。修订轮仍是观察后父决策。SSE 本身用 `tests/ext/llm-stream-live.mq.md`。 - -验收: - -1. 未传 `stream` 的金样零 diff。 -2. `stream=True` 时用户在首包 token 到达前不应长时间无输出(允许短连接建立延迟)。 -3. 最终 `result` 与非流式路径一致(同 prompt fixture)。 -4. quiet 子任务仍不污染父 TTY。 - ---- - -## 6. 开放点 - -1. ~~Eager vs 惰性~~ → S0 选 eager;惰性句柄可后补。 -2. ~~delta 默认 print~~ → 默认关;`echo=True` 可选。 -3. ~~中文面~~ → `流式=` / `打印增量=`。 -4. ~~S2~~ → `plan stream=True`:`round` / 父 delta / `decision` / `done`;可选 `trace`。 -5. ~~**S3**~~ → `marqdo view`:进程内 EventBus;`GET /api/events`(SSE);`POST /api/run` 后台执行;Execution 区 EventSource 面板。CLI 默认不订阅。 - -S0 可与 [okf-near-match.md](okf-near-match.md) 并行,互不阻塞。 diff --git a/doc/roadmap/ai-stack.md b/doc/roadmap/ai-stack.md deleted file mode 100755 index 0e872fe..0000000 --- a/doc/roadmap/ai-stack.md +++ /dev/null @@ -1,78 +0,0 @@ -# Marqdo AI 栈统一开发方案(llm + agent) - -| | | -|---|---| -| Status | **Active** | -| Date | 2026-09-24 | -| Source | [doc/next/002–005](../next/) · [ext-llm.md](../design/ext-llm.md) · [ext-agent.md](../design/ext-agent.md) | - -## 1. 一句话 - -> **Document → Prompt → LLM → Agent → Skill → Policy → Executable Knowledge** - -大模型负责探索,小模型(`router_model` / 任意 llm 句柄)负责决策,Marqdo 负责执行;经验编译进 `.mq.md` 后推理成本下降。 - -## 2. 分层(勿混) - -| 层 | 职责 | 落点 | -|----|------|------| -| **Intelligence primitive** | `ask` / `stream` / `collect`;结果对象 | `ext/ai/llm` | -| **Agent runtime** | `run` / `step` / `plan` / `route` | `ext/ai/agent` | -| **Sandbox (trial)** | CoW workspace + capped `run` | `ext/ai/sandbox` · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) | -| **Memory / compile** | episode → skill → policy | `plugins/agent`(ABI;**不进** `src/host`) | -| **Transport** | HTTP / SSE / provider | `ext/ai/llm/openai` · `ollama`;用户不可见 | - -硬规则:`ext/**` 不调 `host_*`;agent/OKF/路由热路径只进 `plugins/agent`。 - -## 3. LLM(005)— 已/待 - -| 项 | 状态 | -|----|------| -| 语义 API:`ask` / `stream` / `collect`(`complete` 降为兼容原语) | **done** | -| `create` 工厂;handle 带 `backend` | **done** | -| LLMResult:`text` / `model` / `finish` / `backend` / `usage` / `tokens` | **done** | -| Named models(`llm.fast` / `llm.reasoning`) | **done** | -| Prompt document:`prompt` / `prompt_load` + `type: prompt` 正文 | **done**(无参 `ask`/`stream` → `sys.module_source` + `prompt_body`) | -| 拆 `ext/ai/llm/openai.mq.md` + `ollama` 后端 | **done** | -| tool_calls 完整 Result | **done**(`openai.tool_calls_from` + `LLMResult.tool_calls`;`llm-tool-calls-offline`) | -| Transport → 可选 ABI 插件 (`plugins/llm`) | **done** | -| Artifact Metadata Binding(`${env.*}` / `secret` · `sys.meta`) | **done**(Phase 1 Metadata-only + Phase 2 scope lift;[binding.md](../design/binding.md)) | - -作者面优先: - -```marqdo -**answer = > llm.ask prompt="What is Marqdo?"** -**events = > model.stream prompt=`p`** -**text = > llm.collect events=`events`** -**fast = > llm.fast** -**prompt = > llm.prompt path="prompts/task.md"** -``` - -## 4. Agent(002–004)— 已/待 - -| 项 | 状态 | -|----|------| -| Skill Compilation:episode → maybe_learn → `llm_free` | **done** | -| Adaptive Routing:`marqdo` \| `small-llm` \| `llm` \| `auto`(`jev`→`small-llm` 别名) | **done** | -| Policy Compilation → `policies/router.mq.md` | **done** | -| `run` 串联 route → execute → record → learn | **done** | -| Agent 默认走 `model.ask` + Result.usage 记成本 | **done**(`model_turn`) | -| Prompt artifact / document-as-prompt | **done**(经 llm `path=` / `prompt`) | -| 零 LLM 执行(policy+skill → `llm_calls=0`) | **done** | -| `plan` 不覆盖已有 `llm_free` resource | **done** | -| 真 MCP client(stdio) / resume checkpoint / 小模型路由请求面 | **done**(live 路由仍可选 skip) | - -## 5. 联调顺序 - -1. **LLM Result → Agent metrics** — **done** -2. **Named handles** — **done** -3. **Prompt document** — **done**(`type: prompt` 剥 frontmatter;无参 `ask`/`stream` 经 `sys.module_source`) -4. **Backend split** — **done** -5. **Execution compilation** — **done**(`agent-zero-llm` 金样 + harness) -6. **Metadata Binding** — **done**(Phase 1 + Phase 2 scope lift;`llm-meta-offline` · `meta-lift`) - -## 6. 验收金样 - -- Agent:`tests/ext/agent-v2-learn.mq.md` · `agent-p4-route.mq.md` · `agent-zero-llm.mq.md` · `agent-plan-preserve.mq.md` · `agent-mcp-client.mq.md` · `agent-resume.mq.md` · `agent-small-llm-route.mq.md` · `scripts/agent-harness.sh` -- LLM:`tests/ext/llm-ask-offline.mq.md` · `llm-stream-offline.mq.md` · `llm-ctor-offline.mq.md` · `llm-named-offline.mq.md` · `llm-meta-offline.mq.md` · `llm-entry-prompt-offline.mq.md` · `llm-tool-calls-offline.mq.md` -- Binding:`tests/structure/meta-binding.mq.md` · `meta-lift.mq.md` diff --git a/doc/roadmap/blind-experiment-2026-09-23-deepseek-flash.md b/doc/roadmap/blind-experiment-2026-09-23-deepseek-flash.md deleted file mode 100755 index c79f83f..0000000 --- a/doc/roadmap/blind-experiment-2026-09-23-deepseek-flash.md +++ /dev/null @@ -1,34 +0,0 @@ -# 盲测实验(§5.2(b) 查询式 vs 全文档背诵)—— 2026-09-23 - -| | | -|---|---| -| 模型 | `deepseek-flash` @ `https://llm.cflmy.cn/v1` | -| 样本 | 6 任务(业务 3 + QuixBugs 改写 3),oracle = stdout 精确匹配 | -| 协议 | 系统提示词 = 硬规则 12 条 + 契约表三形状(两臂同文);**唯一变量 = 语法来源**:`query` 臂 MLSP 查询通道(≤3 次)vs `docs` 臂完整 markup 参考(背诵) | -| 修复 | validate 诊断 + stderr 回喂,≤2 次修复;temperature=0,max_tokens=8000 | - -## 汇总(判据:Q 通过率不劣于 D;首轮语法错误率 Q≤D;token Q≤70%%D;轮次不升) - -| 臂 | 通过(一轮) | 通过(最终≤3) | 首轮语法错误 | 首轮契约诊断 | 平均修复轮(过例) | token 合计(prompt+completion) | 弃权/基础设施 | -|---|---|---|---|---|---|---|---| -| query | 0/3 | 0/3 | 2/3 | 1/3 | 0.00 | 69771(42478+27293) | 3 | -| docs | 3/6 | 4/6 | 2/6 | 0/6 | 0.50 | 57276(33346+23930) | 0 | - -## 逐例 - -| 例 | 臂 | 结果 | 修复轮 | 首轮语法错 | 首轮契约诊断 | token(p+c) | 查询 | 备注 | -|---|---|---|---|---|---|---|---|---| -| claims_reserve_settle | query | load-fail | 0 | 是 | 否 | 11987+8177 | 3 | {"error":{"code":"mlsp.parse_error","message":"<memory>: trailing input in expression: \"(claim - deductible, 0)\""},"id":1,"ok":false} \| stderr=error: /tmp/marqdo_blind_1694593_query_claims_reserve_settle.mq.md: trailing input in expression: "(claim - deductible, 0)" | -| contract_milestone_pay | query | infra | 0 | 否 | 否 | 3970+4718 | 3 | 非 JSON / 空体: | -| vendor_po_gate | query | load-fail | 0 | 是 | 否 | 9552+3686 | 3 | 回复中无程序 \| 开头: QUERY: 条件分支 写法 | -| qb_gcd | query | run-fail | 0 | 否 | 是 | 9700+8488 | 3 | \| stderr=error: /tmp/marqdo_blind_1694593_query_qb_gcd.mq.md:26:1: unknown function `gcd(48` | -| qb_max_sublist_sum | query | infra | 0 | 否 | 否 | 1253+134 | 3 | 非 JSON / 空体: | -| qb_get_factors | query | infra | 0 | 否 | 否 | 6016+2090 | 3 | 非 JSON / 空体: | -| claims_reserve_settle | docs | pass | 0 | 否 | 否 | 2699+2987 | 0 | queries=0 | -| contract_milestone_pay | docs | pass | 0 | 否 | 否 | 2800+3202 | 0 | queries=0 | -| vendor_po_gate | docs | pass | 0 | 否 | 否 | 2690+1264 | 0 | queries=0 | -| qb_gcd | docs | pass | 2 | 否 | 否 | 8147+6970 | 0 | queries=0 | -| qb_max_sublist_sum | docs | run-fail | 0 | 是 | 否 | 8518+3609 | 0 | \| stderr=error: /tmp/marqdo_blind_1694593_docs_qb_max_sublist_sum.mq.md:3:1: unknown function `[-2,` | -| qb_get_factors | docs | run-fail | 0 | 是 | 否 | 8492+5898 | 0 | \| stderr=error: /tmp/marqdo_blind_1694593_docs_qb_get_factors.mq.md:20:1: missing argument for parameter `value` | - -报告由 `tests/blind_experiment.rs` 生成;材料冻结于 `tests/blind/`(任务书 + docs-bundle),判据见 `doc/roadmap/perf-validation.md` §2。 diff --git a/doc/roadmap/blind-experiment-2026-09-23-mimo-v2.6-pro.md b/doc/roadmap/blind-experiment-2026-09-23-mimo-v2.6-pro.md deleted file mode 100755 index 2278b35..0000000 --- a/doc/roadmap/blind-experiment-2026-09-23-mimo-v2.6-pro.md +++ /dev/null @@ -1,34 +0,0 @@ -# 盲测实验(§5.2(b) 查询式 vs 全文档背诵)—— 2026-09-23 - -| | | -|---|---| -| 模型 | `mimo-v2.6-pro` @ `https://llm.cflmy.cn/v1` | -| 样本 | 6 任务(业务 3 + QuixBugs 改写 3),oracle = stdout 精确匹配 | -| 协议 | 系统提示词 = 硬规则 12 条 + 契约表三形状(两臂同文);**唯一变量 = 语法来源**:`query` 臂 MLSP 查询通道(≤3 次)vs `docs` 臂完整 markup 参考(背诵) | -| 修复 | validate 诊断 + stderr 回喂,≤2 次修复;temperature=0,max_tokens=8000 | - -## 汇总(判据:Q 通过率不劣于 D;首轮语法错误率 Q≤D;token Q≤70%%D;轮次不升) - -| 臂 | 通过(一轮) | 通过(最终≤3) | 首轮语法错误 | 首轮契约诊断 | 平均修复轮(过例) | token 合计(prompt+completion) | 弃权/基础设施 | -|---|---|---|---|---|---|---|---| -| query | 0/1 | 0/1 | 1/1 | 0/1 | 0.00 | 12428(10255+2173) | 5 | -| docs | 0/0 | 0/0 | 0/0 | 0/0 | 0.00 | 0(0+0) | 6 | - -## 逐例 - -| 例 | 臂 | 结果 | 修复轮 | 首轮语法错 | 首轮契约诊断 | token(p+c) | 查询 | 备注 | -|---|---|---|---|---|---|---|---|---| -| claims_reserve_settle | query | infra | 0 | 否 | 否 | 1424+324 | 3 | 非 JSON / 空体: | -| contract_milestone_pay | query | infra | 0 | 否 | 否 | 0+0 | 0 | 非 JSON / 空体: | -| vendor_po_gate | query | infra | 0 | 否 | 否 | 1417+213 | 3 | 非 JSON / 空体: | -| qb_gcd | query | load-fail | 0 | 是 | 否 | 5011+1265 | 0 | {"error":{"code":"mlsp.parse_error","message":"<memory>: unexpected expression input: \"**y**\""},"id":1,"ok":false} \| stderr=error: /tmp/marqdo_blind_1710203_query_qb_gcd.mq.md: unexpected expression input: "**y**" | -| qb_max_sublist_sum | query | infra | 0 | 否 | 否 | 1216+172 | 3 | 非 JSON / 空体: | -| qb_get_factors | query | infra | 0 | 否 | 否 | 1187+199 | 3 | 非 JSON / 空体: | -| claims_reserve_settle | docs | infra | 0 | 否 | 否 | 0+0 | 0 | 非 JSON / 空体: | -| contract_milestone_pay | docs | infra | 0 | 否 | 否 | 0+0 | 0 | 非 JSON / 空体: | -| vendor_po_gate | docs | infra | 0 | 否 | 否 | 0+0 | 0 | 非 JSON / 空体: | -| qb_gcd | docs | infra | 0 | 否 | 否 | 0+0 | 0 | 非 JSON / 空体: | -| qb_max_sublist_sum | docs | infra | 0 | 否 | 否 | 0+0 | 0 | 非 JSON / 空体: | -| qb_get_factors | docs | infra | 0 | 否 | 否 | 0+0 | 0 | 非 JSON / 空体: {"error":{"message":"upstream connection failed","type":"server_error","param":n… | - -报告由 `tests/blind_experiment.rs` 生成;材料冻结于 `tests/blind/`(任务书 + docs-bundle),判据见 `doc/roadmap/perf-validation.md` §2。 diff --git a/doc/roadmap/browser-wasm-d.md b/doc/roadmap/browser-wasm-d.md deleted file mode 100755 index 2f022f5..0000000 --- a/doc/roadmap/browser-wasm-d.md +++ /dev/null @@ -1,35 +0,0 @@ -# 路线图:浏览器 Marqdo 路线 D(作者零 JS) - -| | | -|---|---| -| 状态 | **Completed**(D0–D4 已落地;续作见 [browser-wasm-e.md](browser-wasm-e.md)) | -| 日期 | 2026-09-03 | -| 前置 | [browser-wasm.md](browser-wasm.md)(C0–C5 **Completed**) | -| ADR | [0002](../adr/0002-browser-marqdo-wasm.md) · [0003](../adr/0003-browser-async-effects.md) | -| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §16 | - -## 一句话 - -作者侧**零业务 JS**:页面逻辑与交互只写 `.mq.md`;官方 `marqdo-bridge.js` 仍作不透明宿主胶(加载 WASM / DOM / fetch),由 `mount` + `client_embed` 自动启动。 - -## 阶段 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **D0** | 路线图 + 设计增补 | **done** | -| **D1** | bridge `mount` + data-mq / `#marqdo-boot` 自启;hello 去掉 loader/interact/fetch.js | **done** | -| **D2** | `client_embed` / `客户端挂载`:`wasm` / `source` / `boot` | **done** | -| **D3** | DOM/表单效应 + wire 传 `value`;`dom_patch` L1 | **done** | -| **D4** | `examples/web-client-site` + skill / README | **done** | - -## 非目标 - -- 消灭官方 bridge 文件本身(宿主胶必须存在) -- 任意 `eval(JS)` / React 式 VDOM -- 把 axum / SQLite 搬进浏览器(仍属 C 非目标) - -## 验收 - -- 示例无作者业务 `.js`(允许构建拷贝的 `marqdo-bridge.js`) -- `ext/web` 一行挂载即可 boot + wire -- 点击、表单 input、`fetch` 效应可演示 diff --git a/doc/roadmap/browser-wasm-e.md b/doc/roadmap/browser-wasm-e.md deleted file mode 100755 index 1eb4a08..0000000 --- a/doc/roadmap/browser-wasm-e.md +++ /dev/null @@ -1,32 +0,0 @@ -# 路线图:浏览器 Marqdo 路线 E(前端能力补齐) - -| | | -|---|---| -| 状态 | **Completed** | -| 日期 | 2026-09-04 | -| 前置 | [browser-wasm-d.md](browser-wasm-d.md)(D0–D4 **Completed**) | -| 续作 | [browser-wasm-f.md](browser-wasm-f.md)(媒体 / 文件 / Canvas 等) | -| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §16–§17 | - -## 原则(已修正) - -**禁止的只有:作者手写业务 JS。** -官方 `marqdo-bridge.js` / 构建生成物可以包含任意宿主机制(含轻量列表装配、路由、存储、WebSocket、内部模板等)。 - -## 阶段 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **E0** | 原则修正 + 能力矩阵 | **done** | -| **E1** | `set_style` / `focus` / `blur` / `scroll_into`;键盘;wire `委托`;多节点 `querySelectorAll` | **done** | -| **E2** | `set_html` / `append_html` / `replace_children` / `render_list` / `remove`;L1 `list_html` | **done** | -| **E3** | `navigate` / `replace`;`window`+`popstate` | **done** | -| **E4** | `storage` local/session/**cookie** | **done** | -| **E5** | `ws` open/send/close + callbacks | **done** | -| **E6** | `fetch_all`(数组或 map)/ `interval` / FormData / `clipboard` / `download` | **done** | -| **E7** | `add_class` / `remove_class`;示例列表真删除 + net 面板 | **done** | - -## 验收 - -- [examples/browser-app/](../../examples/browser-app/):列表 CRUD、storage、三页路由、interval、fetch_all、ws、clipboard、download -- 冒烟:`tests/wasm/smoke.mjs` diff --git a/doc/roadmap/browser-wasm-f.md b/doc/roadmap/browser-wasm-f.md deleted file mode 100755 index 3872edd..0000000 --- a/doc/roadmap/browser-wasm-f.md +++ /dev/null @@ -1,29 +0,0 @@ -# 路线图:浏览器 Marqdo 路线 F(进阶宿主能力) - -> 2.7.0 维护说明:独立的 browser-hello 与 browser-media 演示已删除。下文保留既有能力设计与宿主边界,当前可运行工程使用 browser-app;底层计数器冒烟夹具位于 tests/wasm/counter.mq.md。Canvas、音频等仍是 lib/browser 的宿主能力,不宣称当前 browser-app 演示包含这些交互。 - - -| | | -|---|---| -| 状态 | **Completed**(F1–F5;F6 Service Worker 可选未做) | -| 日期 | 2026-09-04 | -| 发布 | **v0.3.3** | -| 前置 | [browser-wasm-e.md](browser-wasm-e.md)(E **Completed**) | -| 写法 | 客户端 `.mq.md`:**GFM 表格 + `lib/browser`**,禁止 `json.set` 链([marqdo-dev](../../.cursor/skills/marqdo-dev/SKILL.md)) | - -## 原则 - -同 E:禁止作者手写业务 JS;官方 bridge 可扩展。作者数据与效应用**可读表格/助手**表达。 - -## 阶段 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **F1** | `read_file` → text / DataURL → `mq_call` | **done** | -| **F2** | Canvas 2D 指令表(`canvas.commands`) | **done** | -| **F3** | Audio play / pause / stop;`src=beep` Web Audio | **done** | -| **F4** | `observe` / `unobserve`(Intersection / Resize) | **done** | -| **F5** | drag/drop wire + `data-drag` / `drop_text` | **done** | -| **F6** | Service Worker / 离线缓存 | optional / skipped | - -示例:[examples/browser-app/](../../examples/browser-app/) · 助手:`lib/browser.mq.md`。 diff --git a/doc/roadmap/browser-wasm.md b/doc/roadmap/browser-wasm.md deleted file mode 100755 index 2b63066..0000000 --- a/doc/roadmap/browser-wasm.md +++ /dev/null @@ -1,43 +0,0 @@ -# 路线图:浏览器 Marqdo(WASM) - -> 2.7.0 维护说明:独立的 browser-hello 与 browser-media 演示已删除。下文保留既有能力设计与宿主边界,当前可运行工程使用 browser-app;底层计数器冒烟夹具位于 tests/wasm/counter.mq.md。Canvas、音频等仍是 lib/browser 的宿主能力,不宣称当前 browser-app 演示包含这些交互。 - - -| | | -|---|---| -| 状态 | **Completed**(路线 C 首版功能完备;续作见 [browser-wasm-d.md](browser-wasm-d.md)) | -| 日期 | 2026-09-01 | -| ADR | [0002](../adr/0002-browser-marqdo-wasm.md) · [0003](../adr/0003-browser-async-effects.md) | -| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) | - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **C0** | feature 门控;`wasm32` check | **done** | -| **C1** | `run_source` + `mq_run` | **done** | -| **C2** | loader + `marqdo wasm build`(含 bridge 拷贝) | **done** | -| **C3** | session wire + `set_text` | **done** | -| **C4** | `fetch` / `after` 效应 | **done** | -| **C5** | `release-wasm` 体积;冒烟;站点挂载文档 / L1 | **done** | - -## 交付物 - -| 产物 | 路径 | -|------|------| -| ABI crate | `crates/marqdo-wasm` | -| 官方 bridge | `crates/marqdo-wasm/js/marqdo-bridge.js` | -| CLI | `marqdo wasm build -o DIR` | -| 示例 | `examples/browser-app/` | -| 冒烟 | `tests/wasm/smoke.mjs` · `tests/wasm_smoke.rs` | -| L1 | `web.client_embed` / `网页.客户端挂载` | - -## 明确非目标(本版不做) - -- 浏览器会话 bytecode(缺 entry-env invoke;一发 `run_source` 已支持 bytecode) -- 把 axum / SQLite 服务端搬进 WASM -- 业务手写 JS 框架 - -## 进度 - -| 日期 | 记录 | -|------|------| -| 2026-09-01 | C0–C5 完结并 push;收口 bridge 规范路径 + 冒烟 + 挂载 L1 | diff --git a/doc/roadmap/code-as-docs-gaps.md b/doc/roadmap/code-as-docs-gaps.md deleted file mode 100755 index 6dd19e4..0000000 --- a/doc/roadmap/code-as-docs-gaps.md +++ /dev/null @@ -1,66 +0,0 @@ -# 路线图:代码即文档叙述面摩擦(G1–G4) - -| | | -|---|---| -| 状态 | **Done**(实现已合入工作树;金样绿) | -| 日期 | 2026-09-14 | -| 设计 | [code-as-docs-gaps.md](../design/code-as-docs-gaps.md) | -| 样例 | `examples/code-as-docs/index.mq.md` | - ---- - -## 里程碑 - -### M1 — 文档与金样夹具 - -- [x] 设计文档记录 G1–G4 与启发式 -- [x] 本路线图 -- [x] `tests/markup-v03/` 四缝金样 + `gold.rs` `markup_v03_*` - -### M2 — G1 模块级 `---` - -- [x] `parse_classified`:顶层 frame 行 skip;顶层 Comment 引言 skip -- [x] 函数体内 `---` / `***` 改为叙述跳过(不再收束;空返回收束) -- [x] 金样:`module-hr.mq.md` - -### M3 — G3 浮点面量与运算 - -- [x] `Literal::Num(f64)` -- [x] `parse_primary` 识别 `digits.digits`(及 `.5` / `3.` 形态) -- [x] `eval_binary` + bytecode Int/Num 提升(Int/Int `/` 仍为整除) -- [x] 金样:`float-discount.mq.md` - -### M4 — G2 叙述强调启发式 - -- [x] `scan_prose_line`:非代码形粗体、非返回形行内斜体 → 丢弃 -- [x] 保持 `**n=n+1**`、`**加一 37**`、整行 `*n*`、「返回*n*」 -- [x] 更新 Skill:允许装饰性强调;可执行仍看形状 -- [x] 金样:`soft-emphasis.mq.md` - -### M5 — G4 动态脚注键 - -- [x] AST:`IndexKey::{Lit,Var}`(`` [^`ident`] ``) -- [x] 解析、求值、bytecode -- [x] 金样:`dynamic-footnote.mq.md` -- [x] 回写 `examples/code-as-docs`(浮点折扣 + 动态键) - -### M6 — 出门 - -- [x] `examples/code-as-docs` 展示四缝修复后的写法 -- [x] `cargo test --test gold` 绿 -- [x] 设计验收覆盖(见金样) - ---- - -## 顺序建议 - -G1(小)→ G3(中,Literal/运算)→ G2(启发式,依赖金样钉行为)→ G4(AST 面)→ 回写样例。 - ---- - -## 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-14 | 初稿 | -| 2026-09-14 | 实现完成并勾选 | diff --git a/doc/roadmap/executable-knowledge-gaps-2026-10-23.md b/doc/roadmap/executable-knowledge-gaps-2026-10-23.md deleted file mode 100755 index 4df69cd..0000000 --- a/doc/roadmap/executable-knowledge-gaps-2026-10-23.md +++ /dev/null @@ -1,230 +0,0 @@ -# Marqdo 现状与规划缺口:从可执行文档到可复用知识 - -| | | -|---|---| -| 状态 | 现状审计与下一阶段规划;不是已实现能力声明 | -| 审计基线 | `main` / `434be9f`,2026-10-23;后续改动须重新核验对应判断 | -| 产品意图 | [009.md](../next/009.md) · [详细开发规范](../next/Marqdo_Executable_Knowledge_Development.md) · [完整示例](../next/Marqdo_Executable_Knowledge_Example.md) | -| 目标 | **代码即文档,文档即知识库,知识库可执行,可执行知识可复用** | -| 方向修订 | 2026-10-23:按[文档原生开发指导](../design/document-native-development-guide.md)重排交付,G01–G12 保留为缺口证据,不等于作者必须经历的治理流程 | - -## 1. 本文解决什么问题 - -仓库已经拥有语言运行时、双后端、标准库、扩展、文档站、EKC、Agent 和一批语义制品结构。现有[详细开发规范](../next/Marqdo_Executable_Knowledge_Development.md)定义了目标架构和 M0–M6,但它主要写于目标能力尚未落地之时;现在照它逐项勾选,容易把“结构存在”“CLI 可调用”“目标闭环成立”混为一谈。本文只补**现状与目标之间尚未被规划成可验证闭环的工作**。语法和产品目标仍以前述意图文档为准;旧文档中的 Classic 链接取元、单体知识类、或另一套知识索引不应反向规定新语义。 - -本轮判断以源码、可定位的测试和文档状态为证据。`done` 表示有可运行入口和回归测试;`partial` 表示有结构或单一路径,仍不满足产品判据;`design` 表示主要存在于文档和目标示例。**不能把能解析、能运行、能检索、能验证事实视作同一个结论。** - -### 1.1 对上一版规划排序的修正 - -上一版把内部工程完整度放在主要位置,直到 S6/S7 才验收 Agent 复用和作者体验,容易造成“先建治理平台,再证明文档有用”的偏差。本版改为从可读步骤、确定执行和早期本地复用向外扩展;每片同时交付源码示例、诊断和消费者可见结果。工程基础按切片所需完成,不降低已开放路径的安全要求。 - -P0/P1/P2 分类改为缺口领域,不再按编号整组串行:G06 的未知效应安全下限必须进入最早执行试点,G09 的本地复用也不再等锁和远程授权全部完成。复杂业务的证据、严格锁和远程凭据按使用场景增加,不能强加给每个单文件程序。每片还须记录作者重复声明数、局部修改范围和实际复用结果,指标见[指导 §8](../design/document-native-development-guide.md#8-验证-marqdo-优势而不只验证组件存在)。 - -## 2. 设计思想落实为四个可证伪承诺 - -| 承诺 | 必须由什么证明 | 当前判定 | -|---|---|---| -| 代码即文档 | 一份 `.mq.md` 的叙述、契约、示例、可执行语句由同一解析结果驱动;改变语义会让说明/示例失配可见 | 运行与 view 已有基础;正文引用尚未进入完整语义 AST(partial) | -| 文档即知识库 | 可寻址的事实、规则、步骤、来源、适用范围和关系由编译器生成;不同消费者读取同一身份和图 | 项目索引与 Artifact 投影已起步;双图和占位字段仍存在(partial) | -| 知识库可执行 | 引用先绑定、检查参数/契约/效应/版本,再由运行时执行**绑定的目标**;正文默认不触发副作用 | CLI 可解析、运行时可执行,但两条路径未闭合(partial) | -| 可执行知识可复用 | Agent 发现候选后取得有条件、可失效的句柄,实际调用既有制品;trace 记录符号、摘要、输入和结果 | MLSP 有初版 handle;EKC/Agent 尚未统一到此协议(partial) | - -这四条有语义依赖,但应在受限故事中逐步贯通,不是四个必须全部做完才能进入下一层的大项目。阅读体验和检索召回不能代替绑定;绑定不能证明知识内容正确;执行成功不能证明已经复用既有知识。 - -## 3. 仓库能力盘点与规范 M0–M6 的真实进度 - -| 既有里程碑 | 可复用成果 | 仍未满足的完成条件 | -|---|---|---| -| M0 语义与测试 | Occlusion 已为默认;[语法测试规程](../next/Marqdo_Executable_Knowledge_Testing.md)和部分金样存在;标准库、扩展库已经迁移 | `tests/executable_knowledge/` 系统夹具、100 单元生成器、导航/正文/效应负例矩阵未形成独立门禁 | -| M1 项目身份 | [`src/project/mod.rs`](../../src/project/mod.rs)确定项目根和扫描顺序;[`src/sema/symbols.rs`](../../src/sema/symbols.rs)产生 ModuleId/SymbolId;CLI `knowledge inspect/resolve` 可用 | 身份保留、移动/重命名、symlink/重复扫描、大项目增量与错误聚合还需完整策略和测试 | -| M2 统一链接与调用 | 裸零参路径和关联函数已有 Tree/Bytecode、CLI 金样;`Expr::Occluded` 已承载标签和 payload | [`src/ast.rs`](../../src/ast.rs)仍无统一 Named/正文引用节点;[`src/sema/ir.rs`](../../src/sema/ir.rs)只提取执行体部分调用;运行时仍独立按名称寻找调用目标 | -| M3 语义制品 | SemanticArtifact、EffectSet、SourceRef、VerificationRecord、JSON 投影已存在 | 适用性、来源证据、单位、真实验证状态、完整效应闭包与规范摘要仍缺;字段存在不代表语义已实现 | -| M4 锁与影响 | `knowledge lock/impact` 可用;[`src/sema/lock.rs`](../../src/sema/lock.rs)支持原子写入和反向依赖查询 | 锁只比较 artifact 摘要;目标、接口、实现、证据、传递闭包变更未独立报告;正文/证据边不在影响闭包内 | -| M5 消费者 | view 显示部分语义信息;MLSP 提供 `artifact.*`;EKC/Agent 有各自检索与复用能力 | 同一图/同一绑定尚未贯通;Agent 对 ready 的判定与执行句柄未被强制;trace 不足以证明实际复用 | -| M6 迁移与发布 | 全仓新语法迁移、`--legacy-markup` 入口、v2.1.0 发布已完成 | 发布不等于 M0–M5 已完成;目标示例仍注明“尚不能完整运行”,100 单元与 Agent 对照实验未过 | - -`examples/executable-knowledge/README.md` 是目标示例,仍明确说明类函数、统一 `Named<T>` 和步骤图的完整运行是设计目标。它不得作为“产品闭环已完成”的发版证据。 - -### 3.1 相邻路线如何进入本规划 - -| 仓库区域 | 当前路线状态 | 与可执行知识主线的连接点 | -|---|---|---| -| Interpreter / 标准库 | Tree、Bytecode、`lib/` 与中英库有大量金样;[Mid2](stdlib-mid2.md)已完成 | 作为 BoundCall、效应声明、签名与迁移回归的基础;不为本路线重做通用库 | -| Web / 浏览器 | [Web](ext-web.md) W 波与 [WASM](browser-wasm.md) C 波已落地 | 作为 view/静态投影和宿主能力消费者;知识引用不能在静态导出或浏览器预览中偷跑服务端 effect | -| Agent / LLM / 沙盒 | [Agent](ext-agent-optimize.md) Wave B 有局部待项;[优化 O 波](ext-ai-optimize.md)已完成 | 工作簿、OKF、沙盒可复用;S2 接本地 bound handle,S4/S5 增强政策;不另建平行知识身份 | -| 外联 / Notebook | [外联 F4](foreign-v2.md)和[会话 D4–D5](notebook-session.md)尚有余项 | 外部内核、持久状态和重放需显式建模为 effect/环境依赖;不能把会话结果当纯制品缓存 | -| 领域扩展 | [Quantum Q8c](ext-quantum.md)等剩余项属领域体验;[宿主 H4b](ext-hosting.md)为可选 HTTP 能力 | 不阻塞语义主链;但扩展元数据与插件调用必须参加 G06/G10 的 effect 和兼容性门禁 | - -这些路线各有自己的完成定义。本文不将其余项全部吸收到下一版核心范围;只规定它们与统一语义层交互时必须遵守的契约。 - -## 4. 语义一致性缺口:消除错误的语义真相 - -### G01 两份图与同名输出路径 - -**证据。** [`src/knowledge/compile.rs`](../../src/knowledge/compile.rs)先调用 `compile_project` 并写语义投影,随后重新用 `extract_graph` 从源码提取旧 EKC 图。后者的 `write_projections` 再写 `graph/edges.json`;[`src/knowledge/graph.rs`](../../src/knowledge/graph.rs)的调用边按短名选首个匹配符号。由此“语义边”和“检索边”既不是同一事实,也会争用同一个文件名。 - -**规划缺口。** 详细规范要求 EKC 是 `SemanticProject` 投影,却未给出**并行迁移期间的文件命名、读取优先级、冲突检测与废弃时点**。只新增语义图不解决消费者继续读旧边的问题。 - -**决策与交付。** 明确一个权威 `SemanticProject`;图边按稳定 `SymbolId/ArtifactId` 生成。旧检索索引仅含查询优化数据,不再自行确定 calls/uses。若迁移期保留旧 JSON,放入独立版本化路径并声明其非执行依据。`knowledge compile`、`view`、`check`、`impact`、MLSP、Agent 对同一引用应报告同一目标及诊断。 - -**验收。** 制造两个模块同名函数并让调用只 import 其中一个;语义图、CLI resolve、Tree/Bytecode trace、view 和 Agent handle 必须指向同一 ID。编译两次输出字节一致;生成物中没有同名文件被后续投影覆盖。 - -### G02 绑定没有成为执行的前置条件 - -**证据。** [`src/main.rs`](../../src/main.rs)的 `knowledge resolve` 走项目索引;[`src/mlsp.rs`](../../src/mlsp.rs)的 `link.resolve` 通过 artifact 名字/后缀匹配;[`src/interp.rs`](../../src/interp.rs)仍有自身的 `eval_path_call` 和函数查找;[`src/bytecode/`](../../src/bytecode/)也有独立调用实现。`compile_project` 目前只将同模块无接收者调用识别为静态依赖,其余记为 `external_or_dynamic`。这几条路径存在真实分叉。 - -**规划缺口。** 现有规范提出 Bound IR,但缺少**最小可合并的执行切面**以及动态调用的明确边界。不能先宣称图边覆盖执行调用,再等待后端改造。 - -**决策与交付。** 先让显式 import、普通函数、关联函数这三个静态路径通过唯一 resolver,生成 `BoundCall { target, signature, source_span, required_effects }`。Tree 和 Bytecode 只消费 BoundCall;确需动态解析的路径使用独立 `DynamicCall`,在图/诊断中显式标记,不能假装已绑定。`run/check/knowledge resolve/MLSP` 使用相同 import 范围和歧义规则。 - -**验收。** 同名跨模块、重命名、缺 import、实例方法误用、动态目标分别有稳定诊断;任一静态 trace 中执行的 SymbolId 与编译图边一致。错误不得因后端不同而变成另一目标。 - -### G03 `[]()` 只有标签,还没有完整知识步骤 - -**证据。** [`src/ast.rs`](../../src/ast.rs)保留 `Expr::Occluded`;[`src/parse/prose.rs`](../../src/parse/prose.rs)扫描粗体、斜体和反引号,但没有完整 Markdown 正文链接 AST。[`src/sema/ir.rs`](../../src/sema/ir.rs)当前 KnowledgeRef/KnowledgeStep 主要由调用点提取,步骤 `kind` 为 `call`;取元、推导、遍历、正文、导航尚未同等进入图。目标示例列出的 observe/derive/iterate/narrate 不能由现有投影证明。 - -**规划缺口。** 缺少正文 inline 的位置、逃逸、代码围栏、标准 URL 与知识引用的**一套无副作用解析协议**,以及 `[]()` 在表达式、循环和正文的统一节点身份。 - -**决策与交付。** 保留现有 payload 表达式解析器;为上下文建立稳定 SyntaxNodeId 与 `Named<T>`/等价 lowering。明确 `NavigationLink`、`NarrativeRef`、`ExecutableNamed`、`LoopNamed` 的互斥分类及 span。正文引用只解析和验证;主动纯预览可使用项目/会话既有政策,不要求逐链接确认;外部 effect 仍需明确执行上下文与宿主能力许可。各类型步骤的输入、输出、依赖和角色由编译器推导;标签是阅读、检索和局部编辑的上下文,但不参与授权和寻址。作者不手工填写步骤 ID 或生成图。 - -**验收。** 一份文档同时含 URL、锚点、带空格/嵌套括号载荷、围栏、行内代码、取元、计算、循环、正文引用;生成的 ref/step 数、分类和跨度稳定,正文 `run/check/view static` 不发生外部 effect。 - -### G04 生成物写入不是整代快照 - -**证据。** [`src/sema/ir.rs`](../../src/sema/ir.rs)将语义文件写到临时目录后,逐个删除并移动 `project.json`、`symbols.json`、`refs.json`、`artifacts/`、`graph/`、`verification/`;[`src/knowledge/compile.rs`](../../src/knowledge/compile.rs)再写旧投影。这不是消费者可原子读取的整代快照,构建中途可能看到混合版本。 - -**规划缺口。** 规范写了“原子写入”,未规定**整代提交、读者快照、失败恢复和旧版本保留**。 - -**决策与交付。** 使用带 schema/build-id 的代目录与原子指针或等价快照机制;所有消费者一次选择一代,读完整个结果后才释放。生成物可删除重建;崩溃后只能看到旧完整代或新完整代。 - -**验收。** 在写每个投影文件时注入故障并并发读取;不得出现 `project` 属于 A 代而 `edges` 属于 B 代,失败后旧代仍可读。 - -## 5. 可信执行缺口:按场景落实验证门槛 - -### G05 来源、适用性和验证状态仍是占位投影 - -**证据。** [`src/sema/ir.rs`](../../src/sema/ir.rs)给函数固定 `"no explicit applicability constraints"`,`SourceRef` 主要指向定义它的源码,`evidence` 摘要来自契约文本;验证记录固定 `contract=unchecked`、`tests=unknown`、`evidence=unverified`、`domain=unreviewed`。现有 [`src/knowledge/lifecycle.rs`](../../src/knowledge/lifecycle.rs)的 `verify` 是另一套 EKC 检查。因此“有 SourceRef”并不表示政策原文被关联或核验。 - -**规划缺口。** 规范列出字段和七层状态,但没有定义**作者如何写来源/适用性、如何证明测试确实覆盖此制品、谁可将 domain 从 unreviewed 提升、何时失效**。不确定现实真假的结论必须保留 unknown。 - -**决策与交付。** 用现有 Markdown/frontmatter/契约表表达可选的 `source`、有效区间、地域/单位/输入前提,形成可解析 schema;把编译、静态检查、实跑测试、来源内容、人工领域审阅作为独立证据事件。定义状态迁移、撤销和失效规则;生成物记录证据文件/测试运行摘要,不允许 CLI/Agent 自报 `verified`。 - -**验收。** 政策原文改变而函数未改时 evidence 状态下降;来源删除、过期、输入不满足分别给不同诊断;无来源的纯工具函数可运行,但不能被宣称为已证实业务事实。 - -### G06 效应识别存在“未知即纯”的漏洞 - -**证据。** [`src/sema/ir.rs`](../../src/sema/ir.rs)的 `effects_for_call` 依据名字前缀猜测 `fs/net/llm` 等,其余返回 `pure`;`direct_effects` 只汇总直接调用。未知插件、别名、包装函数和传递调用可能因此被标作纯。[`src/mlsp.rs`](../../src/mlsp.rs)以该集合做 `artifact.execute` 的效应拒绝。 - -**规划缺口。** 详细规范定义 EffectSet,却没有给出**跨宿主函数、标准库、扩展 ABI、动态调用的权威效应注册表和未知效应策略**。 - -**决策与交付。** 内核/标准库/插件元数据声明 effects,绑定后做调用图闭包;动态或缺元数据为 `unknown`,需要显式能力授予,不得降为 pure。`view` 静态、`verify pure`、Agent ready 门槛使用同一集合。实际宿主能力限制仍在执行时强制。 - -**验收。** 用自定义名字包住写文件/网络/插件调用;静态 effect 必须传递到入口,默认 pure 策略拒绝执行。循环调用图收敛;未知动态调用拒绝 pure 证明。 - -### G07 绑定句柄未表达可复用的授权与适用性 - -**证据。** [`src/mlsp.rs`](../../src/mlsp.rs)的 `artifact.bind` 主要检查目标唯一及可选 digest,返回 `artifact_id/digest/project/policy/effects`;它没有要求 ready、契约、适用性或来源状态。`artifact.execute` 重编译比对摘要后按 `display_name` 最后一段调用解释器;调用者提交的 `allow_effects` 会变为宿主能力。现阶段这是实验性执行接口,不是可信复用协议。 - -**规划缺口。** 缺少句柄的**发行者、主体、策略、输入约束、能力上限、过期/撤销、并发源变更**模型;也缺少“绑定到精确嵌套函数”在 runtime 的保证。 - -**决策与交付。** `bind` 必须验证 SymbolId、签名、输入、已声明适用性、所选验证政策及 effect 上限;政策要求锁时检查 lock。`execute` 复核同一目标与状态并按绑定符号调用。受信本地调用先采用精确绑定引用和摘要复核,不强制搭建签发服务;远程/多租户/不受信调用再加入可信发行者、主体、范围、期限/撤销及防伪机制。客户端参数不是远程授权来源;运行时能力上限始终由宿主强制。响应如实显示政策和未知状态,作者不手写 handle。 - -**验收。** 本地先覆盖改参数、改依赖、改效应策略、同名嵌套函数和并发源码变更,不得错调用或越权;严格政策增加来源与锁变更,远程增加伪造/过期/撤销测试。`ready` 必须注明相应 policy 与条件,不是全局永久认证。 - -### G08 锁定与影响分析未覆盖知识变化 - -**证据。** [`src/sema/lock.rs`](../../src/sema/lock.rs)的 lock 文件虽然写出 interface/implementation/evidence/dependencies,但检查时只比较 `artifact` 摘要。该摘要在 [`src/sema/ir.rs`](../../src/sema/ir.rs)只组合本地 interface/implementation/evidence,没有传递依赖闭包;impact 的边也只来自已识别的本地调用。`knowledge impact` 与语义 impact 是两套命令/图。 - -**规划缺口。** 未定义**锁的审阅单位、变更分类、依赖 SCC、证据变更如何传播到正文、升级冲突处理**。 - -**决策与交付。** 分别持久化 target/interface/implementation/evidence/closure 摘要,SCC 按确定规则求闭包;strict 对未审阅目标变化失败。impact 用同一图沿 calls/depends_on/supported_by/narrates 反向传播,并说明为何被影响。每次 lock update 留下人可审阅的差异报告。 - -**验收。** 本地函数源码不变而下游税率规则变了时 closure 变化;只改描述不混同事实证据变化;来源变更影响客服说明;同一个查询在 CLI、MLSP、view 展示相同受影响 ID 集合。 - -## 6. 作者与生态缺口:从早期切片持续验证 - -### G09 Agent 仍可能把候选当作可执行知识 - -**证据。** [`src/knowledge/reuse.rs`](../../src/knowledge/reuse.rs)、[`plugins/agent/`](../../plugins/agent/)和 `ext/ai/agent.mq.md` 有各自的检索、near-match、工作簿/Skill 固化流程;[`src/mlsp.rs`](../../src/mlsp.rs)另有 artifact handle。现有 [Agent 路线图](ext-agent-optimize.md)主要跟踪工作簿、路由和评测,没有把“发现→精确绑定→验证→调用既有制品→记账”设成强制路径。 - -**规划缺口。** 需要明确 **REUSE、ADAPT、CREATE 的进入条件与失败后分流**,以及“避免重复生成”用什么客观指标衡量。 - -**决策与交付。** near/soft-match 只能供候选发现;Agent 可以选择并提交精确候选,REUSE 前必须经同一 resolver 和 policy 得到 bound handle。不可用则记录原因,按权限进入 ADAPT/CREATE 或请求补充决策。新草稿可被发现、查看和在本地明确权限下试跑,进入共享自动复用的 ready 集合前按政策验证晋升。先提供含步骤、源码、约束、负知识和验证状态的最小上下文卡,再支持带期望摘要的局部补丁和语义 diff,避免整篇再生成。trace 包含任务、候选、选定 SymbolId、所有相关摘要、输入摘要、policy、实际执行结果及因果依赖;私密输入只存可审计脱敏摘要。 - -**验收。** 已有适用能力时实际调用而不新建同义函数;同名未消歧、违反所选政策的过期/未验证候选、权限不足不能自动执行。局部修改不覆盖并发编辑;只改措辞却改变签名必须可见。同样任务与预算下报告重复实现率、错误复用率、发现率、成功率、编辑范围、作者维护成本及失败样本。 - -### G10 标准库、扩展库与发布物缺少跨层一致性门禁 - -**证据。** [语法测试规程](../next/Marqdo_Executable_Knowledge_Testing.md)覆盖了部分零参路径金样;仓库有大量 `lib/`、`ext/`、`public/` 和示例。`.github/workflows/` 目前只有 release/pages,没有对每次提交运行可执行知识项目夹具的 CI;[目标示例](../../examples/executable-knowledge/README.md)仍不可端到端运行。现有 [lib/ext 路线图](lib-ext-code-as-docs.md)的历史“链接取元”已被 v2.1 默认遮蔽语义取代,`done` 不代表今天的知识引用集成已完成。 - -**规划缺口。** 对新语义没有固定的**全仓兼容矩阵、跨平台发布前检查、示例可运行状态标签、回滚规则**。 - -**决策与交付。** 分层门禁:parser/sema → Tree/Bytecode → 标准库中英镜像 → 扩展插件装载 → CLI/MLSP/view/静态导出 → 一体化书店/订单示例。每个负例也断言诊断码和副作用计数。每次语义变化先迁移 `lib/ext` 并保持 stdout 与 effect,不通过扩展旧语义来掩盖库的过时写法。CI 在 main 的 PR/push 执行无网络核心套件;需要插件/浏览器的平台测试单列结果;发布前检查包内标准库/扩展与二进制版本匹配。 - -**验收。** `cargo test --locked`、gold 单线程、可执行知识项目夹具、CLI JSON schema 和每个平台打包后冒烟通过;文档示例一旦标为可运行,CI 每次执行。没有 `skip` 可以充当核心能力成功证据。 - -### G11 文档状态本身缺少统一真相 - -**证据。** [`doc/README.md`](../README.md)仍将较早 mapping 称为“现行运行时”,将 [详细开发规范](../next/Marqdo_Executable_Knowledge_Development.md)的 v2.0.0 基线直接当下一阶段实施依据;多个旧路线图的 `done` 和新语义目标相互交错。README 的 v2.1 链接/投影描述可能被误读为完整可执行知识系统已交付。 - -**规划缺口。** 缺少文档版本、优先级、状态和实现证据之间的**维护协议**。这会让人和 Agent 从旧文档学回被迁移掉的语义。 - -**决策与交付。** 文档顶部标明“目标规范 / 已实现 / 历史兼容 / 被取代”及适用版本;在 `doc/README.md` 提供唯一入口。每项能力把规范段落、代码位置、测试、示例、发布版本关联起来;任何 `done` 必须列出验收命令及结果。旧内容可以保留历史价值,但搜索结果与 Skill/教程默认指向当前规范。制定文档可运行片段的抽取或同步测试,降低“文字与实现分叉”。 - -**验收。** 新贡献者只读 README、doc 索引和 Skill 能写出默认语义的运行样例;旧取元写法在当前教学材料不会以默认形式出现;变更语法时 CI 能发现核心规范与构造卡片失配。 - -### G12 项目规模、缓存与权限边界尚无可量化 SLO - -**证据。** [`src/project/mod.rs`](../../src/project/mod.rs)每次扫描目录;[`src/sema/ir.rs`](../../src/sema/ir.rs)重新读取并解析项目文件;view 和 MLSP 每次查询也可重新编译。`ProjectRoot::source_files` 特别处理 symlink,但没有明确的路径环/别名去重、资源上限与增量失效协议。当前规范虽列 1k/10k/100k 指标,却没有基线值和可接受阈值。 - -**规划缺口。** 项目发现、Symlink、外部 import、生成目录、并发编辑、overlay、缓存一致性和诊断聚合缺少一份可测试的**规模与信任边界规格**。 - -**决策与交付。** 先定义约定式项目发现、源文件唯一性、遍历深度/文件大小上限、外部来源许可和增量失效键;单文件与普通项目免额外注册,只有边界无法由约定表达时才要求显式 manifest。再建立 100/1k/10k 项目生成器、冷/热构建计时和内存基线;超过阈值的操作降级为明确诊断,不能静默跳过或返回旧图。MLSP overlay 要么被安全纳入快照,要么显式拒绝且不宣称即时编辑验证。 - -**验收。** 扫描顺序与重复路径不改变身份;symlink 环不挂起;修改单文件只失效正确下游;缓存损坏后结果与全量构建一致;目标机器上的时间与内存阈值由基准结果确定后固化进 CI。 - -## 7. 依赖顺序与可合并切片 - -| 切片 | 前置 | 作者 / AI 可见交付及工程关联 | 可复核的完成证据 | -|---|---|---|---| -| S0 作者基线与最小语料 | 无 | 六类实际写作/复用任务、当前语法入口、无网络最小门禁(G10/G11) | **已落地**:[tests/executable_knowledge/](../../tests/executable_knowledge/README.md) + `cargo test --test executable_knowledge` | -| S1 可读步骤与唯一目标 | S0 | 一份文档的源码/步骤/view 联动;统一 resolver、图与上下文节点(G01/G03) | **已落地**:G01 双图分离;G03 步骤 kind + NarrativeRef(`11-narrative-ref`)+ view 导航;同名 import resolve | -| S2 确定执行与早期 AI 复用 | S1 | BoundCall 双后端、最小上下文卡、本地 handle 与现有 Agent 试点(G02/G06/G07/G09 的安全子集) | **已落地**:G02 BoundCall;G06 效应;G07 MLSP bind/execute;eng_reuse `bind_required` | -| S3 局部编辑与库可读性 | S1–S2 | 摘要保护的局部补丁、语义 diff、受限纯表达式提取;lib/ext 示例优化(G03/G09/G10/G11) | **已落地**:`artifact.patch` + wording 回滚;`artifact.extract_pure` 纯表达式预览;全库润色仍可选后续 | -| S4 业务知识与适用性 | S2;与 S3 可交错 | 书店契约、来源/验证事件、传递效应及政策、负知识(G05/G06/G07/G09) | **已落地**:来源/过期;`13-bookstore` + `examples/executable-knowledge` 发票链 `113`;负知识文档 | -| S5 变化传播与严格复用 | S1–S2/S4 | 分类摘要、SCC 闭包、整代快照、impact、严格 handle 复核(G04/G08) | **已落地**:`generations/`+`CURRENT`;锁 `classes`+`closure`;impact 含 narrates;依赖变更推动 closure | -| S6 生态验收与发布 | 按发布声明选择 S1–S5 范围 | 全仓兼容矩阵、可运行端到端示例、平台冒烟、作者/AI 指标(G10/G11/G12) | **已落地**:CI;扫描上限;100 单元语料门禁;CLI version/check/knowledge 冒烟 | - -每切片完成时同时更新 [详细开发规范](../next/Marqdo_Executable_Knowledge_Development.md)的实现状态、相关示例及本表;只改文档状态不算完成。S1/S2 先用**无 LLM、无网络、无插件**测试证明确定性协议,随即接现有 Agent 验证实际复用;不等所有治理工程结束。G10/G11 是每片持续门禁,100 单元语料逐片增长;G04 的并发一致性必须在开放并发消费前完成,不能因为列在 S5 就忽略前置风险。 - -G12 大规模优化与远程凭据服务按场景安排;远程执行若开放,其授权测试就是硬前置。H4b MCP HTTP、dense embedding、更多语言糖和全面本体推理均不阻塞本地链。任务拆分、模块落点和作者验收详见[指导 §7](../design/document-native-development-guide.md#7-交付切片每片都有文档作者与-ai-能看见的结果)。 - -## 8. 横向验收场景与发布条件 - -### 8.1 必须固定的四个故事 - -1. **两文档事实**:李白出生年份定义、同名冲突、显式 import、正文惰性引用、来源变更、锁拒绝;验证“文档即知识库”。 -2. **订单定价**:来源政策→税率/折扣→多步计算→正文解释;对每个 `[]()` 生成步骤,修改上游后 `impact` 找全下游;验证“知识可执行”。 -3. **权限反例**:取一个无明显危险词的用户函数,内部经标准库/插件包装写文件或请求网络;静态未知或效应传递阻止静态预览和纯策略执行;验证默认安全。 -4. **Agent 已有能力复用**:先存在 ready 制品,再给相似需求;Agent 发现后精确绑定并执行,trace 中有 SymbolId、摘要与结果,仓库不增加同义函数;再加入过期/不适用候选并验证拒绝。 - -每个故事覆盖成功与拒绝、Tree/Bytecode(执行适用时)、CLI/MLSP、view、生成图及清缓存重建。旧版本迁移另保存输入、输出、诊断和 effect 的对照;不以“测试通过”掩盖输出语义改变。 - -### 8.2 完整可执行知识声明的门槛 - -- 100 单元确定性夹具和四个故事在 CI 全绿;正文静态路径外部 effect 计数为零。 -- 静态调用图与运行 trace 的 target ID 一致;两后端的值、目标、诊断一致;动态调用在结果中明确标记。 -- 任何模糊/同名、unknown effect、无效适用性、过期 lock、缺失必需证据都不能被自动标为 ready。 -- Agent 在已有适用能力的任务上实际执行 bound handle,且错误复用率、重复实现率与当前 EKC 基线同时报告;保存数据和失败样本。 -- `lib/ext/public/examples` 当前语义全仓通过,安装包中的 CLI、标准库、扩展库版本和示例行为一致。 -- README、教程、Skill 与目标示例明确区分已实现、实验性与设计态;运行示例由 CI 执行。 - -这些是完整链的门槛,不要求每次修补版等完整链全部完成。受限本地复用可在 S1/S2 对应正负例和兼容门禁通过后按精确范围发布;严格业务复用增加 S4/S5,远程执行另验授权和隔离,见[分层声明](../design/document-native-development-guide.md#83-发布声明分层)。未完成项不得被笼统“可执行知识已实现”覆盖。目前仍应表述为:**v2.1 已提供文件级新语法、项目索引与语义制品初版;知识验证和 Agent 复用闭环仍在建设。** - -## 9. 明确的非目标 - -- 不要求作者为每个函数写一份重复的机器配置;优先从现有 Markdown、契约表和调用解析推导。 -- 不要求每个取元、循环或纯工具函数都附现实世界证据;只有声称业务事实成立或需要高信任复用时才提高证据门槛。 -- 不以 LLM 的模糊判断替代符号绑定、类型检查或权限授予;LLM 可选择精确候选、组合、编辑、适配和补测试,编译器校验实际目标与语义,宿主执行权限上限。 -- 不把 `Type`、`Entity`、`Fact`、`Function` 强行折叠为“类”;兼容现有 `#`/`##` 表面,语义类型在 IR 中清楚区分。 -- 不把 v2.1 的发布回退为未完成,也不把历史路线图的 `done` 自动推广为本路线的完成。 diff --git a/doc/roadmap/ext-agent-optimize.md b/doc/roadmap/ext-agent-optimize.md deleted file mode 100755 index bb85bcf..0000000 --- a/doc/roadmap/ext-agent-optimize.md +++ /dev/null @@ -1,51 +0,0 @@ -# `ext/agent` 深入优化(调研驱动) - -| | | -|---|---| -| 状态 | **A0–A4 完成**;**Wave B Active**(宪法优先:代码即文档 / call_site / OKF) | -| 日期 | 2026-09-04 | -| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) · **[agent-framework-2026-09.md](../research/agent-framework-2026-09.md)** | -| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) | -| 邻近 | [agent-streaming.md](agent-streaming.md) · [okf-near-match.md](okf-near-match.md) | -| 后续 | 优化波次 O1–O5 见 [ext-ai-optimize.md](ext-ai-optimize.md)(沙盒证明 · Skill Lift · 路由/成本 · lint · 隔离) | - ---- - -## 1. 优化原则(来自调研) - -1. **强化差异化,不向 LangChain 薄循环回退**(禁止隐藏 TOOL: 主路径、禁止整文件 LLM 重写工作簿)。 -2. 把资源砸在:**工作簿质量、写回、固化、OKF 命中、过程可视、源码/调用位置注入**。 -3. 外部 RAG/MCP 只作**工具**,不升为权威真相源。 - -自评四问见调研 §9。A0–A4 之后的缺口见 [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md)。**2026-09 Wave B** 锁定见 [agent-framework-2026-09.md](../research/agent-framework-2026-09.md)。 - ---- - -## 2. A0–A4(已完成) - -| 波次 | 主题 | 验收线索 | -|------|------|----------| -| **A0** | 工作簿补丁 / 固化可靠性 | **done** — 金样 `agent-workbook-patch-a0` | -| **A1** | OKF 复用飞轮 | **done** — 金样 `agent-kb-plan-hit` | -| **A2** | 过程可见 | **done** — events + view plan 卡 | -| **A3** | 上下文预算 | **done** — `source_brief` / `READ:`;金样 `agent-context-budget-a3` | -| **A4** | RAG/MCP 证据工具 | **done** — 金样 `agent-tools-rag-a4` | - ---- - -## 3. Wave B(Active — 宪法优先) - -| 波次 | 主题 | 状态 | -|------|------|------| -| **B0** | 官方示例演示 call_site/源码/OKF;Skill/文档;上下文管道可读 | **done** | -| **B0.5** | 本机 live(`.env` → 开发模型)验证「模型用上了文档」 | **done**(`AGENT_LIVE` / `AGENT_HARNESS_LIVE`) | -| **B1** | 评测 harness 锁差异化指标(constitution / dump / writeback 遮蔽) | **Active** | -| **B1.5** | **Skill Compilation v2(Phase 1–3)**:episode → maybe_learn → compile → `llm_free`;`agent.run` / `resolve` / `metrics`;ABI 在 `plugins/agent`(`memory.rs`);金样 `agent-v2-learn` | **done** | -| **B1.6 / P4** | **Adaptive Routing**(原 Jev Router 更名):`route` backends = `marqdo` \| `small-llm` \| `jev?` \| `llm` \| `auto`;Policy Compilation → `policies/router.mq.md`;金样 `agent-p4-route`;设计 [004.md](../next/004.md) | **done** | -| **L0** | **LLM semantic surface(005)**:`ask` / `stream` / `collect` / `create`;`complete` 降为兼容;统一方案 [ai-stack.md](ai-stack.md) | **done** | -| **B2** | 真 MCP stdio client(`agent_mcp_client` + fixture 仍作离线证据) | **done** | -| **B3** | resume checkpoint(`.marqdo/agent-resume/`;HITL view 仍暂缓) | **done**(HITL 暂缓) | -| **B4–B5** | stats / 并行;小模型 live 路由金样(无 key skip) | 部分 | -| — | LLM named models / prompt-document | **done** | - -示例:`examples/agent-pong/` · `examples/agent-okf-flywheel/`。v2 设计:[doc/next/002.md](../next/002.md) · [doc/next/003.md](../next/003.md) · P4:[doc/next/004.md](../next/004.md) · LLM:[doc/next/005.md](../next/005.md)。 diff --git a/doc/roadmap/ext-ai-optimize.md b/doc/roadmap/ext-ai-optimize.md deleted file mode 100755 index 9d43d6f..0000000 --- a/doc/roadmap/ext-ai-optimize.md +++ /dev/null @@ -1,29 +0,0 @@ -# Roadmap: Agent/LLM 优化波次 O1–O5 - -| | | -|---|---| -| Status | **Active** | -| Date | 2026-10-16 | -| Design | [ext-ai-optimize.md](../design/ext-ai-optimize.md) | -| Research | [ai-agent-llm-optimize-2026-10.md](../research/ai-agent-llm-optimize-2026-10.md) | -| Prior | [ext-agent-optimize.md](ext-agent-optimize.md) (A0–A4 / Wave B) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) | - -## Principles - -1. Executable `.mq.md` remains authority; OKF reuses; sandbox proves; LLM explores. -2. No hidden TOOL: loop; no vector-store memory authority; no default shell Agent. -3. Do not edit `doc/next/*`. - -## Waves - -| Wave | Scope | Gold / deliverable | Status | -|------|-------|--------------------|--------| -| **O1** | A1 opt-in `sandbox=` · A3 profile table · D1 skill · D4 example | `agent-sandbox-optin` · `examples/agent-sandbox-okf` | **done** | -| **O2** | A2 promote proof · B1 OKF meta · B3/E1 harness Skill Lift | `agent-sandbox-promote` · harness subset | **done** | -| **O3** | C1 step route · C2 cost · B6 EFI default | `agent-step-route` · run usage/efi | **done** | -| **O4** | A4/D2 lint · A5 diff review report | `scripts/mq-style-lint.sh` · `sandbox.report` | **done** | -| **O5** | B4 quarantine · C3 offline policy rewrite | `agent-sandbox-quarantine` · `optimize-standing-policy.sh` | **done** | - -## Non-goals - -F1–F5 · wasmtime CLI embed · default `sandbox=True` without ADR · edit `doc/next/*` diff --git a/doc/roadmap/ext-ai-sandbox.md b/doc/roadmap/ext-ai-sandbox.md deleted file mode 100755 index e053bf8..0000000 --- a/doc/roadmap/ext-ai-sandbox.md +++ /dev/null @@ -1,28 +0,0 @@ -# Roadmap: `ext/ai/sandbox` (AI CoW trial runtime) - -| | | -|---|---| -| Status | **Active** | -| Date | 2026-10-16 | -| Design | [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) | -| Research | [ai-agent-sandbox.md](../research/ai-agent-sandbox.md) | - -## Milestones - -| ID | Deliverable | Done when | -|----|-------------|-----------| -| S0 | Design + this roadmap + research cross-links | **done** | -| S1 | CoW open/write/read/remove/diff/commit/discard | **done** (`sandbox-cow`) | -| S2 | `run` + default caps + core lib inside run | **done** (`sandbox-run-lib`) | -| S3 | `inspect` + deny plugin.load | **done** (`sandbox-deny`) | -| S4 | Polish: ai-stack + CHANGELOG | **done** | - -## Gold samples (target) - -- `tests/ext/sandbox-cow.mq.md` -- `tests/ext/sandbox-run-lib.mq.md` -- `tests/ext/sandbox-deny.mq.md` - -## Out of scope this wave - -wasmtime CLI embed · Wasm ABI plugins · bwrap/microVM · full web in sandbox · auto-wire agent.step · edit `doc/next/*` diff --git a/doc/roadmap/ext-hosting.md b/doc/roadmap/ext-hosting.md deleted file mode 100755 index 06c1965..0000000 --- a/doc/roadmap/ext-hosting.md +++ /dev/null @@ -1,102 +0,0 @@ -# 路线图:宿主集成补齐(H0–H4) - -| | | -|---|---| -| 状态 | **Active · 规划** | -| 日期 | 2026-09-07 | -| 缺口 | [ext-hosting-gaps.md](../research/ext-hosting-gaps.md) | -| 设计 | [ext-hosting-fill.md](../design/ext-hosting-fill.md) | -| 相关 | [ext-web.md](ext-web.md)(W/C 完结)· [ext-agent-optimize.md](ext-agent-optimize.md) · [agent-streaming.md](agent-streaming.md) | -| 基线 | v0.3.6+ | - -本文只跟踪**实现波次**。作者 API、ABI 边界、禁止项以设计文为准。 - ---- - -## 0. 目标回顾 - -让 `ext/web` + `ext/ai` 具备:同域 SSE 中继、HTTP→用户 `##`、MCP Server(至少 stdio)、跨模块 db/corpus 可发现——从而下游无需 Python 旁路进程。 - ---- - -## 1. 波次总表 - -| 波次 | 内容 | 关闭缺口 | 状态 | -|------|------|----------|------| -| **H0** | 文档契约:跨模块 `db` 传 `url`;`corpus_search` 调用前 `ensure_plugin` 说明;缺口索引进 `doc/README` | GAP-05 文档侧 | **done** | -| **H1** | `app.proxy` / `configure proxy=`:上游 SSE/HTTP **流式**转发 | GAP-01 | **done** | -| **H2** | `app.invoke` / `configure invoke=`:请求 → 白名单 `##` → JSON | GAP-02 | **done** | -| **H3** | 跨模块插件对象 `_type` 分发修补 + `corpus_search` 自动 `ensure_plugin` | GAP-05 运行时 | **done** | -| **H4** | `agent.mcp_server` + `serve transport=stdio`(HTTP 可选 H4b) | GAP-03 | **done**(stdio) | -| **H4b** | MCP Streamable HTTP | GAP-03 余量 | **todo**(可选) | -| **—** | 副端口 API | GAP-04 | **won't**:H1+H2 同端口关闭 | - -建议顺序:**H1 → H2 → H3 → H4**(H2 的 invoke 内核可被 H4 工具复用,故 H2 不宜晚于 H4)。 - ---- - -## 2. 分波工作项 - -### H1 — 流式代理 - -1. `plugins/web`:`proxy.rs` + `web_app_proxy`;listen 挂流式 handler。 -2. `ext/web`:`## proxy` + `configure proxy=` 表。 -3. 金样 `web-proxy-sse-smoke`(mock 上游)。 -4. 教程/public 短节:「浏览器同域调 LLM」。 - -**完成定义:** `curl -N` 同域 path 收到多帧 SSE;密钥仅 env 注入。 - -### H2 — HTTP invoke - -1. 共享或插件内 `invoke_fn`(解析 `库.成员`、映射 body)。 -2. `web_app_invoke` + 白名单。 -3. 金样:临时 `##` 写文件 + JSON 响应;拒绝未允许路径。 -4. 迁移说明:替换 `/store/*` + 外挂 `marqdo run`。 - -**完成定义:** 单进程 `listen` 下表单/fetch 可触发用户 `##`。 - -### H3 — db / corpus - -1. 复现并修跨模块 `unknown object type db`(设计选项 A)。 -2. `ext/ai` `corpus_search` 路径 `ensure_plugin`。 -3. 金样 `web-db-cross-module-smoke` + corpus CLI run 金样。 - -### H4 — MCP Server - -1. `plugins/agent` stdio JSON-RPC 最小子集:`initialize` / `tools/list` / `tools/call`。 -2. `ext/ai` `# mcp_server` · `## tool` · `## serve`。 -3. 工具调用复用 H2 `invoke_fn`。 -4. 金样夹具;文档对接 Cursor `mcp.json` 示例。 - -**H4b:** Streamable HTTP 与鉴权;不阻塞 H4 stdio 发版。 - ---- - -## 3. 刻意不做 - -| 项 | 原因 | -|----|------| -| 默认开启任意 `##` 远程执行 | 安全 | -| 中继进 `lib/net` / `src/host` | 边界 | -| 重开 W0–W7 内容站清单 | 已完结 | -| 以副端口为推荐架构 | H1+H2 同端口即可 | -| Dense embedding 默认 | OKF 路线不变 | - ---- - -## 4. 与发版 - -- 每波可随小版本发布;H1+H2 建议同一版本对外宣传「可去掉 llm_proxy」。 -- H4 可标 `ext/ai` 能力点,与「真 MCP 客户端」分列 Release notes。 - ---- - -## 5. 进度勾选(落地时改) - -- [x] H0 缺口 + 补齐文档 -- [x] H1 proxy SSE -- [x] H2 invoke -- [x] H3 db/corpus -- [x] H4 mcp_server stdio -- [ ] H4b mcp http(可选) -- [x] 研究文 GAP 状态改为 closed(H4b 除外) diff --git a/doc/roadmap/ext-linalg.md b/doc/roadmap/ext-linalg.md deleted file mode 100755 index 115d9f7..0000000 --- a/doc/roadmap/ext-linalg.md +++ /dev/null @@ -1,126 +0,0 @@ -# 官方扩展:`ext/linalg` 实现路线图 - -| | | -|---|---| -| 状态 | **L0–L6 + 公式文档面 F1–F3 已落地 · L7+ 远期** | -| 日期 | 2026-09-07 | -| **锁定设计** | [design/ext-linalg.md](../design/ext-linalg.md) · [design/ext-linalg-formula-doc.md](../design/ext-linalg-formula-doc.md) | -| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) | -| 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-math.md](../design/stdlib-math.md) · [view.md](../design/view.md) · [ext-quantum-q7.md](../design/ext-quantum-q7.md) | -| 安装(规划) | `marqdo ext add linalg`(`linalg` / `线性代数`) | - -本文只跟踪**实现阶段**。作者面、公式规则、展示以设计文为准。 - ---- - -## 1. 目标回顾(一句) - -**可运行的线性代数公式文档**:矩阵公式可化简、可 KaTeX 展示;跑通即在规则集内正确;需要时再稠密求值与分解,并内嵌结构 SVG。 - ---- - -## 2. 落地阶段 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **L0** | CATALOG + `plugins/linalg` ping + L1 `ensure_plugin`;`ext add` 条目 | **done** | -| **L1** | MatExpr:`symbol` / 稠密叶子 / `mul`·`add`·`T`·`inv`;`simplify` R1–R5;`latex`·`ascii`·`show` | **done** | -| **L2** | `explicit` / 小阵 gemm·解系·`det`·`trace`;维数护栏;金样 `linalg-basic-smoke` | **done** | -| **L3** | `block` + `collapse`;`kron` 惰性 + R7;金样 `linalg-block-kron` | **done** | -| **L4** | `factorize` LU/QR/SVD/eig(+ 可选 chol);结构 SVG `svd|qr|ge|eig`;金样 `linalg-factor-smoke` | **done** | -| **L5** | `heatmap`/`hinton`;examples(最小二乘 / SVD 示意);public + skill 摘要 | **done** | -| **L6** | 复数 dtype;`lstsq`;`norm`/`cond`;主题令牌对齐 | **done** | -| **F1** | 展示路径默认 simplify;公式文档金样 | **done** | -| **F2** | 符号引入降噪;examples 讲义化 | **done** | -| **F3** | 紧凑糖 + public「如何写公式文档」 | **done** | -| **L7+** | 矩阵微积分 / 更大 BLAS 依赖(仅当用户明确要求) | **deferred** | - -验收金样(规划路径):`tests/ext/linalg-*-smoke.mq.md`;示例:`examples/linalg-least-squares/`、`examples/linalg-svd/`。 - ---- - -## 3. 每阶段出口检查 - -### L0 - -- [x] `ext/linalg` CATALOG 含 `linalg` -- [x] 插件 `ping` → ok -- [x] 文档:`marqdo ext add linalg` - -### L1 - -- [x] `(AB)^\top` → `simplify` → `B^T*A^T`(无 dense) -- [x] 形状错误含行列信息 -- [x] CLI `ascii` / `show` SVG 通道 -- [x] 中英 L1 各一 smoke - -### L2 - -- [x] `from_formula` 吸收 `$$` 数值阵 -- [x] `solve` 与手算 2×2 一致 -- [x] 超维 `explicit` 硬错误(单元测护栏) - -### L3 - -- [x] 分块乘 `collapse` 后块级正确 -- [x] Kronecker 默认不膨胀元素个数(惰性 `A⊗B`) - -### L4 - -- [x] SVD/特征结果对象字段稳定 -- [x] SVG 含可断言标记(如 `data-linalg="eig"`) -- [x] `factorize` + 二次 `solve` 复用(LU) - -### L5 - -- [x] 至少 1 个 examples 可 `marqdo run` -- [x] public/features 或 tutorial 短页 -- [x] skill / CHANGELOG Unreleased 条目 - -### L6 - -- [x] `lstsq` / `norm` / `cond` / `rank` 金样 -- [x] `dtype=complex` 基线(Frobenius;分解仍为实数) -- [x] `draw theme=light|dark|bw` 与 quantum Q8 令牌对齐(`data-theme`) - -### F1 - -- [x] `ascii` / `latex` / `show` 默认 simplify -- [x] 金样:`.T` 后直接 `ascii` 得 `B^T*A^T`(无需显式 simplify) -- [x] 设计文 [ext-linalg-formula-doc.md](../design/ext-linalg-formula-doc.md) 落地 - -### F2 - -- [x] 符号引入降噪(选定候选) — GFM `@` 表 + `la.declare` -- [x] 至少 1 个 example 以代数面为主叙述 — `examples/linalg-transpose/` - -### F3 - -- [x] `T_ascii` / `转置文本` 一步展示糖 -- [x] `explicit` 默认先 simplify(`raw=` 可关) -- [x] public `07-linalg` / `07-线性代数`「如何写公式文档」 - ---- - -## 4. 依赖与并行 - -| 依赖 | 说明 | -|------|------| -| ABI v2 + ext CLI | 已有 | -| view KaTeX / plot | 已有;L1 `show` 接现成通道 | -| Release native zip | 随首次含 `plugins/linalg` 的发版接入 | -| quantum 数值核 | **可选**私有复用;不阻塞 L1–L2 | - -不阻塞项:浏览器 WASM 上的 linalg(默认 host/native;WASM 另议)。 - ---- - -## 5. 建议开发顺序(下一手) - -1. **L7+** 仅当用户明确要求更深符号(微积分等)。公式文档面 F1–F3 已收口。 - ---- - -## 6. 一句话 - -**代数面像讲义、计算面是步骤;跑通即在规则集内正确;每阶段都有可跑金样。** diff --git a/doc/roadmap/ext-quantum.md b/doc/roadmap/ext-quantum.md deleted file mode 100755 index 4510fbe..0000000 --- a/doc/roadmap/ext-quantum.md +++ /dev/null @@ -1,64 +0,0 @@ -# 官方扩展:`ext/quantum` 实现路线图 - -| | | -|---|---| -| 状态 | **Q0–Q7 完结 · Q8a/Q8b 完结 · Q8c 待做** | -| 日期 | 2026-08-28 · 2026-11-08 手册闭环 | -| **锁定设计** | [design/ext-quantum.md](../design/ext-quantum.md) | -| 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-math.md](../design/stdlib-math.md) · [view.md](../design/view.md) | -| 安装 | `marqdo ext add quantum`(`quantum` / `量子`) | - -本文只跟踪**实现阶段**。作者面、模拟语义、view 可视化、分期以设计文为准。 - ---- - -## 1. 目标回顾(一句) - -**可运行的量子电路文档**:表声明门序列 → ABI 模拟概率/采样 → view 内嵌电路/概率 SVG;文档跑通即公式约定成立。 - ---- - -## 2. 落地阶段 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **Q0** | CATALOG + `plugins/quantum` ping + L1 `ensure_plugin` | **done** | -| **Q1** | 态向量;I/X/H/CX;`simulate` / `probabilities`;贝尔态 gold | **done** | -| **Q2** | Y/Z/S/T/R\* /CZ/SWAP;`run seed=`;中英 API | **done** | -| **Q3** | `steps=` 电路表;`draw` 轨线 SVG;view `record_plot` 或值识别 | **done** | -| **Q4** | 概率条 / 布洛赫;`matches_matrix`;examples + 用户文档 | **done** | -| **Q5** | 教学噪声 + barrier/measure/append/state — [ext-quantum-q5.md](../design/ext-quantum-q5.md) | **done(最小)** | -| **Q5.5** | `amplitude_damping` 轨迹 — [ext-quantum-q5.5.md](../design/ext-quantum-q5.5.md) | **done** | -| **Q6** | 公式/`matrix=` 自定义门 + `apply` — [ext-quantum-custom-gate.md](../design/ext-quantum-custom-gate.md) | **done** | -| **Q7a** | 密度矩阵 / Kronecker / 部分迹 / Hermitian 谱 / Schmidt / Pauli 期望 / 纯度·保真度 — [ext-quantum-q7.md](../design/ext-quantum-q7.md) | **done** | -| **Q7b** | 高级 SVG:hinton / city / density / paulivec / qsphere / multibloch | **done** | -| **Q7c** | 纠缠示例 + 用户文档 / skill 摘要 | **done** | -| **Q8a** | 电路 SVG:标签 gutter + dark/light/bw 门族分色 — [ext-quantum-viz-style.md](../design/ext-quantum-viz-style.md) | **done** | -| **Q8b** | probs / bloch / heatmap 共用令牌 | **done** (probs/bloch;heatmap → Q8c) | -| **Q8c** | 高级态图(hinton/city/…)换肤 | **pending** | - -验收金样:既有 `tests/ext/quantum-*-smoke.mq.md`;Q7:`quantum-linalg-smoke`、`quantum-viz-advanced-smoke`。示例:`examples/quantum-bell/`、`examples/quantum-entanglement/`。 - ---- - -2026-11-08:双语 index 已补完整实验、开发路线与真实契约;新增手册源示例的双后端测试。使用与开发从[根入口](../../ext/quantum/index.mq.md)开始,修改动机见[手册优化记录](../design/ext-quantum-handbook.md)。 - -## 3. 已收敛的原开放点 - -| 原疑问 | 锁定结论(见设计文) | -|--------|----------------------| -| 并进 math? | **否**,独立 `ext/quantum` | -| 电路表 | **要做**(Q3),与方法链等价 | -| view 图 | 自绘 SVG;优先 `host_query("record_plot")`;不依赖 web | -| 自由函数面 | 普通函数供 `call`,对象方法保留作者链;共用既有 ABI,见[手册修正](../design/ext-quantum-handbook.md) | - ---- - -## 4. 与其它文档 - -| 文档 | 关系 | -|------|------| -| [design/ext-quantum.md](../design/ext-quantum.md) | **真理** | -| [stdlib-math.md](../design/stdlib-math.md) | 公式/作图精神对照;实现分离 | -| [ext-web.md](../design/ext-web.md) | 同属官方 ext + ABI + `ext add` 模板 | -| [view.md](../design/view.md) | 结构卡 + Execution 内嵌 SVG | diff --git a/doc/roadmap/ext-web.md b/doc/roadmap/ext-web.md deleted file mode 100755 index d72836d..0000000 --- a/doc/roadmap/ext-web.md +++ /dev/null @@ -1,72 +0,0 @@ -# 官方扩展:`ext/web` 实现路线图 - -| | | -|---|---| -| 状态 | **W0–W7 + P3 完结**(审计/RBAC/相册/ETag/外键已落地) | -| 日期 | 2026-08-28 | -| **锁定设计** | [design/ext-web.md](../design/ext-web.md) | -| 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [ext-llm.md](../design/ext-llm.md) | -| 安装 | `marqdo ext add web`(`web` / `网页`) | - -本文只跟踪**实现阶段**。类模型、赋值绑定、后台、`.env`、异步边界、ABI 名等以设计文为准。 - ---- - -## 1. 目标回顾(一句) - -**表格完成动态站**:页面表拼组件、组件表绑库与样式、样式表定外观;热路径进 ABI 插件;可选 S3 / Redis。人写目标见设计 §0.1 与 `examples/man-write-site/`。 - ---- - -## 2. 落地阶段 - -| 阶段 | 内容 | 状态 | -|------|------|------| -| **W0** | CATALOG + L1 + `web_listen` Hello | **done** | -| **W1** | env 端口;`page` 四栏;nav 表;static | **done** | -| **W2** | SQLite `define`/`migrate`/`all` | **done** | -| **W3** | 三列绑定;变量名即表名;`/admin` CRUD+日志+布局 | **done** | -| **W3s** | 安全硬化:argon2 密码哈希、CSRF、SQLite 会话持久化、CSPRNG、登录限速 | **done** | -| **W3.5** | 人写面首版:`web.assemble` + `` `表`.`字段` `` + `examples/man-write-site` | **done**(编排袋仍可再瘦) | -| **W4** | Postgres;Redis / S3 驱动(见 [ext-web-drivers.md](../design/ext-web-drivers.md)) | **done** | -| **W4c** | 内容标配:SEO / Markdown / RSS / 分页 UI(见 [web-net-capabilities.md](../design/web-net-capabilities.md)) | **done** | -| **W5** | 上传与媒体:multipart 接收 + 落盘 + 下载(见 [web-net-capabilities.md](../design/web-net-capabilities.md) A5) | **done** | -| **W6** | 迁移 + FTS5 搜索;草稿/评论用既有 where/表;WS 广播 + 访问日志 | **done** | -| **W7** | Cache-Control / 404·500 / 重定向 / sitemap·robots / init 唯一·索引 / HTTPS 反代说明 | **done** | -| **P3** | 审计时间戳 / 外键 / RBAC / 相册 / ETag | **done** | - -### 定制波次(规划中) - -自研后台 / 主题 / 响应式踩坑见 [ext-web-customization-limits.md](../research/ext-web-customization-limits.md);解法索引 [ext-web-customization/](../design/ext-web-customization/)。 - -| 波次 | 内容 | 状态 | -|------|------|------| -| **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **done** | -| **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **done** | -| **C2** | `shell_css` + `layout` 松绑 | **done** | -| **C3** | 样式 strict / 脚本 defer·version | **done** | -| **C4** | 条件导航 when/media(layout 见 C2) | **done** | - -验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`tests/ext/web-db-w6-smoke.mq.md`、`tests/ext/web-w7-finish-smoke.mq.md`、`tests/ext/web-p3-smoke.mq.md`、`ext_cli_add_web`。 - ---- - -## 3. 已收敛的原开放点 - -| 原疑问 | 锁定结论(见设计文) | -|--------|----------------------| -| listen 阻塞 vs 后台任务 | `# main` 内 `listen` **同步阻塞**;插件内部异步 | -| handler 形态 | **不主推**手写 REST;表 href + bind + 自动后台 | -| `marqdo web` 子命令 | scaffold 经 `web.scaffold`;`marqdo web new` 可后续补 | -| Windows + SQLite | 路径用 `DATABASE_URL` | - ---- - -## 4. 与其它文档 - -| 文档 | 关系 | -|------|------| -| [design/ext-web.md](../design/ext-web.md) | **真理** | -| [user-site.md](../design/user-site.md) | 静态站互补 | -| [ext-quantum.md](ext-quantum.md) | 同属官方 ext + ABI + `ext add` | -| [ext-hosting.md](ext-hosting.md) · [ext-hosting-gaps.md](../research/ext-hosting-gaps.md) | **W/C 之后**:同域 SSE 中继、HTTP→`##`(不重开本表 W0–W7) | diff --git a/doc/roadmap/foreign-v2.md b/doc/roadmap/foreign-v2.md deleted file mode 100755 index 05c9dae..0000000 --- a/doc/roadmap/foreign-v2.md +++ /dev/null @@ -1,226 +0,0 @@ -# 外联内核 v2 路线图(F0–F4) - -| | | -|---|---| -| 状态 | **F0–F3.5 已落地;F4 进行中** | -| 日期 | 2026-10-17 | -| 层 | Runtime | -| 相关 | [foreign-kernel.md](../design/foreign-kernel.md) · [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [stdlib-foreign.md](../design/stdlib-foreign.md) · [notebook-session.md](notebook-session.md)(D 层路线) | -| 核心表面 Δ | 无 | - -> 本路线图只覆盖 **F:外联内核运行时**。共享状态 / 单步 / 切换内核的文档侧在 [notebook-session.md](notebook-session.md)(D 层)。 - ---- - -## 0. 现状与目标 - -v1:`set_cmd` / `run` / `run_lang` / `langs`;临时文件 + 子进程 + stdout 文本;无状态、无结构化结果、无 exec 门禁、无有界 IO、无进程组清理。 - -v2 目标:安全、可发现、结构化、可持久、可并行,并成为 D 层文档会话的可靠底座。 - ---- - -## 1. 阶段总览 - -| 阶段 | 内容 | 估算 | 可独立发版 | -|---|---|---|---| -| **F0** | 执行内核与安全:Job/Execution、`exec` 门禁、有界 IO、进程组、`invoke` 记录、view 诊断 | 2–3 天 | 是 | -| **F1** | 语言注册与发现:registry、15 预设、probe、register/unset、配置、venv | 2–3 天 | 是 | -| **F2** | JSON 桥与并行:call/call_many、run_many、output/result | 2–3 天 | 是 | -| **F3** | 持久内核:Python/Node session_open/eval/close/list | 3–4 天 | 是 | -| **F3.5** | 状态桥:session_set/get/names | 1–2 天 | 是 | -| **F4** | 打磨、文档、catalog、CHANGELOG、1.5.0 | 1–2 天 | 1.5.0 | - -D 层(文档会话)从 F3.5 完成后开始;不要把 D 层塞进 F 层。 - ---- - -## 2. F0 — 执行内核与安全 - -### 内容 - -- `src/host/foreign.rs` 重构: - - `Job`:lang/source/stdin/input/env/cwd/timeout/args/output/max_output/cmd/keep。 - - `Execution`:stdout/stderr/raw bytes/exit/ms/timed_out/truncated/error。 - - `ForeignEnv`:cwd/fs_root/specs/caps 快照(供并行)。 -- `exec` 门禁:`run` / `invoke` / `run_many` / `probe` / `session_*` 统一检查。 -- 有界 IO:读线程保留前 N 字节、继续排空;`truncated`。 -- stdin 写线程;EPIPE 忽略。 -- 超时:进程组 kill(Unix `process_group(0)` + `kill(-pid)`;Windows `taskkill /T /F`)。 -- shell-like argv 切分(引号/转义)。 -- `invoke` + 稳定记录。 -- `run` / `run_lang` 增加 `env` / `cwd` / `timeout` / `args` / `max_output`。 -- view `/api/foreign-run` 返回完整记录;JS 显示 stderr / exit / ms。 -- `set_cmd` L1 补 `args`。 - -### 验收 - -- 既有 `lib_foreign_*` / `lib_subtask_foreign` 绿(python 可用时)。 -- 新增 node/bash 金样例:非 0 退出、stderr、超时、env/cwd、截断。 -- `exec=false` 拒绝。 -- `cargo test` 绿;release build;wasm check。 - -### 主要文件 - -`src/host/foreign.rs` · `src/host/mod.rs` · `src/host/subtask.rs` · `src/view/mod.rs` · `src/view/html.rs` · `src/view/debug_page.rs` · `Cargo.toml` · `tests/gold.rs` · `tests/lib/foreign-*.mq.md`。 - ---- - -## 3. F1 — 语言注册与发现 - -### 内容 - -- `src/foreign/registry.rs`(纯逻辑): - - 15 预设、别名、扩展名、版本参数、会话能力。 - - 模板占位符 `{file}` / `{dir}` / `{base}` / `{inline}` / `{lang}` / `{cwd}`。 - - venv 探测、PATH 查找、shell-like 切分、配置解析。 -- `HostContext`: - - `foreign_specs`、`foreign_config_loaded`。 - - `probe` 缓存(可选)。 -- API:`probe` / `langs` / `register` / `unset` / `load_config`。 -- 配置:`.marqdo/foreign.toml` + `MARQDO_FOREIGN_CONFIG`;优先级见设计。 -- `MARQDO_FOREIGN_<LANG>` 支持 JSON 数组与引号。 -- `subtask` 继承注册/配置。 - -### 验收 - -- `probe` 对 node / bash 给出 path + version;缺失语言 `ok=false` 不 panic。 -- 配置可把 `python` 指向 venv;模板可跑 `go run`(若本机有 go)。 -- `langs` 含预设;`unset` 回退预设。 -- 单元测试:切分、模板、别名、扩展名。 - ---- - -## 4. F2 — JSON 桥与并行 - -### 内容 - -- `call` / `call_many`;`invoke` 的 `input` / `output` / `result` / `result_error`。 -- `Value ↔ JSON` 复用 `host::json`;`bytes` base64。 -- `run_many` 并行引擎:`ForeignEnv` 快照、线程上限 32、结果同序、单项 panic 隔离。 -- `call_many` 全跑完再报错(清理所有子进程)。 -- 文档:Python / Node JSON 样板。 - -### 验收 - -- `call` 单列表 → map,mean 为 Num;嵌套 list/map 往返。 -- `run_many` 顺序稳定;单项失败不影响其它项。 -- 大输入(>8 KiB)走 `MARQDO_INPUT_FILE`。 -- 并发上限与超时生效。 - ---- - -## 5. F3 — 持久内核 - -### 内容 - -- `src/host/foreign_session.rs`: - - Python / Node bootstrap(嵌入式常量)。 - - 启动、reader/writer、严格串行、超时、崩溃、drop 清理。 - - `session_open` / `session_eval` / `session_close` / `session_list`。 -- 会话记录:与 invoke 同形 + `id` / `alive`。 -- 会话环境:cwd / env / cmd;`MARQDO_*`。 -- `HostContext` 字段(cfg exec-host)+ Drop。 - -### 验收 - -- Node:`let x=41` → `x+1` → 42;`console.log` 捕获;异常不杀会话。 -- Python:同(有 python 时)。 -- 超时 → kill + `alive=false`;close/drop 无遗留进程。 -- 会话与 `subtask` 边界:不继承。 - ---- - -## 6. F3.5 — 状态桥 - -### 内容 - -- `session_set` / `session_get` / `session_names`。 -- 值:Marqdo → JSON → kernel;kernel → JSON → Marqdo。 -- 名称校验;Secret 规则;错误可读。 -- 与 `session_eval` 同一线路,严格串行。 -- L1 文档 + 金样例。 - -### 验收 - -- Node:`session_set xs=[1,2,3]`,`session_eval sum(xs)` → 6;`session_get` 取回。 -- 复杂嵌套 map/list 往返。 -- 不存在变量 → None + 可读诊断。 -- 非 JSON 可序列化 → 错误说明。 - ---- - -## 7. F4 — 打磨与发布 - -- `history`(可选)/ `cache`(可选,默认关)。 -- view 命令记忆 / Ctrl+Enter / 错误分块。 -- `lib/foreign.mq.md` / `lib/外联.mq.md` 全量。 -- `public/stdlib/*` 示例。 -- catalog 重新生成;CHANGELOG;版本 1.5.0。 -- 性能:空跑、100 次调用、会话 vs 一次性。 - -### 验收 - -- 新函数全部有中文/英文文档与示例。 -- `marqdo catalog`、`public/` 构建通过。 -- 手工 view Run 一个 node 卡片,显示 stdout/stderr/exit/ms。 - ---- - -## 8. 测试矩阵 - -> 当前环境:node / bash / sh / perl 可用,python3 不可用。新金样例以 node + bash 为主;python 用 `python_available()` 条件跳过。 - -| 测试 | 依赖 | 断言 | -|---|---|---| -| 既有 3 个 foreign 用例 | python | 兼容 | -| `foreign-invoke` | node | 记录字段 | -| `foreign-env-cwd` | node | env/cwd/MARQDO_* | -| `foreign-timeout` | node | timed_out | -| `foreign-call-json` | node | 类型往返 | -| `foreign-call-many` / `run-many` | node | 顺序/隔离 | -| `foreign-session` | node | 跨 eval | -| `foreign-session-set-get` | node | 状态桥 | -| `foreign-session-timeout` | node | alive=false | -| `foreign-probe` | node | path/version | -| `foreign-register` | node | 模板 | -| `foreign-config` | node | 配置 | -| `foreign-stdout-stderr` | bash | 成功也有 stderr | -| `foreign-caps` | 无 | 拒绝 | -| 单元测试 | 无 | 切分/模板/别名/JSON | - -Windows:`python_available` / `bash_available` 守卫;进程组 `taskkill` 分支编译通过。 - ---- - -## 9. 兼容性 - -- `run` / `run_lang` / `set_cmd` / `langs` 兼容;只增可选参数。 -- `run` 成功仍返回 stdout;非 0 仍报错。 -- 大输出从“报错”改为“截断 + truncated”(更安全;CHANGELOG 写明)。 -- `langs` 扩展为预设 ∪ 注册 ∪ 配置。 -- HostFn id 末尾追加(196+)。 -- 无核心表面 Δ。 - ---- - -## 10. 风险 - -| 风险 | 缓解 | -|---|---| -| 会话协议脆弱 | 原始 stdout;`-u`;超时 kill;测试;文档限制 | -| 并行进程过多 | 默认 4 / 上限 32;超时;输出上限 | -| 配置优先级难记 | 设计文档固定表;`probe` 显示实际 path | -| 模板 shell 注入 | 默认不 shell;路径引擎生成;文档警示 | -| 大输出截断改变 v1 行为 | CHANGELOG;`truncated` 可检测 | -| wasm 编译 | 新字段 cfg 隔离;registry 纯逻辑 | - ---- - -## 11. 完成定义 - -- F0–F3.5 全部验收。 -- `cargo test` 绿;release build;wasm check。 -- 文档/CHANGELOG/catalog 更新。 -- 提交并推送。 -- 进入 D 层([notebook-session.md](notebook-session.md))。 diff --git a/doc/roadmap/interpreter.md b/doc/roadmap/interpreter.md deleted file mode 100755 index 7ff78c9..0000000 --- a/doc/roadmap/interpreter.md +++ /dev/null @@ -1,179 +0,0 @@ -# Marqdo 参考实现:正经解释器路线图 - -| | | -|---|---| -| 状态 | 已采纳方向 | -| 日期 | 2026-08-04 | -| 目标 | `marqdo run path/to/index.mq.md` 得到真实执行结果;非演示玩具 | -| 相关 | [markdown-mapping.md](../design/markdown-mapping.md) · [ADR 0001](../adr/0001-implementation-language.md) · [USTC 编译课 2025](https://ustc-compiler-2025.github.io/homepage/) | - ---- - -## 1. 为何是解释器,而不是 USTC 式「编译到机器码」 - -[USTC《编译原理与技术》2025](https://ustc-compiler-2025.github.io/homepage/) 的实验链是经典**编译器**路径: - -``` -源码 → 词法(Flex) → 语法(Bison) → AST - → 语义 / Light IR → 优化 → 后端(龙芯汇编等) -``` - -这条路适合 Cminusf 一类「最终变成机器指令」的语言。Marqdo 的产品形态是: - -- 源即 Markdown 文档,**打开即读、运行即算**; -- 首要交付是 **从 `index.mq.md` 得到求值结果**(stdout、返回值、模块图),不是龙芯/ x86 二进制; -- 语法表面是 Markup-as-Syntax,前端与传统正则+Bison 不同,但**中后端的编译学知识仍然全部用得上**。 - -因此: - -| USTC / 龙书阶段 | Marqdo 解释器中的对应 | -|-----------------|------------------------| -| 词法分析 | **行分类 + 标记词法**(无标记=注释;`#`/`*`/`**`/`>`/`+`/`-`/表…) | -| 语法分析 | **结构解析 → Marqdo AST**(可递归下降;不必上 Bison,除非日后自研纯文本方言) | -| 语义分析 | 作用域、提升、导入、形参绑定、类型(可后置) | -| 中间代码 | **可选**:先树遍历;第二期再降到**字节码** | -| 优化 / 目标代码 | **非 v1 目标**;日后若要可另开「编译后端」ADR | - -**结论:做正经解释器 = 把编译前端做扎实 + 把运行时做完整;不是跳过词法语法,也不是一上来 LLVM。** - -权威地图见 [Crafting Interpreters — A Map of the Territory](https://craftinginterpreters.com/a-map-of-the-territory.html):用户眼里的「解释器」内部往往仍含编译到字节码(如 CPython);树遍历是第一期,字节码 VM 是第二期。 - ---- - -## 2. 推荐总体架构 - -``` -index.mq.md (+ 导入的 .mq.md) - │ - ▼ -┌───────────────────┐ -│ 0. 源加载 / 模块图 │ frontmatter `import a:a.mq.md` → 依赖图 -└─────────┬─────────┘ - ▼ -┌───────────────────┐ -│ 1. 词法·行分类 │ 注释行丢弃语义;代码行 → Token 流 -│ (+ MD 块辅助) │ pulldown-cmark/comrak;+/- 靠行扫描 -└─────────┬─────────┘ - ▼ -┌───────────────────┐ -│ 2. 语法分析 │ Token/块 → Marqdo AST -│ (递归下降) │ Module / Fun / Stmt / Expr / Branch / Loop … -│ │ **不用 Flex/Bison**(见 dependencies.md) -└─────────┬─────────┘ - ▼ -┌───────────────────┐ -│ 3. 语义·绑定 │ Pass1: 收集函数(提升)+ 导入模块树(见 module-namespace) -│ │ 作用域链、形参、未定义名诊断 -└─────────┬─────────┘ - ▼ -┌───────────────────┐ -│ 4a. 树遍历解释器 │ ← Phase I(必须先完成,跑通全部 tests 金样例) -│ 或 │ -│ 4b. 字节码编译+VM │ ← Phase II(性能与「更像真语言实现」) -└─────────┬─────────┘ - ▼ - stdout / 返回值 / 退出码 -``` - -Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对齐 **clox(字节码 VM)**(见 [Chunks of Bytecode](https://craftinginterpreters.com/chunks-of-bytecode.html))。这是 Python/Ruby/Lua 主实现走过的正经路径,不是玩具捷径。 - ---- - -## 3. 各阶段「做满」的标准(反玩具清单) - -### Phase 0 — 工程骨架(正式包,不是 `spike/`) - -- 包名:`marqdo`(`src/marqdo/` 或 `marqdo/`) -- CLI:`marqdo run <file.mq.md>`,默认找目录下 `index.mq.md` -- 诊断:带文件名、行号、列号 -- 测试:每个 `tests/{structure,keywords}/*.mq.md` 有期望 stdout(金样例);CI 可跑 - -### Phase I — 可运行的语言核心(树遍历) - -必须全部为真实现,禁止「正则特判 hello」: - -1. **词法 / 行分类**:注释与代码严格分离。 -2. **语法 → AST**:函数、形参、`*` 语句、`**` 返回、`>` 调用、`+` 分支、`-` 循环、表格集合、绑定与 `==`。 -3. **语义**:提升、嵌套作用域、`##` 私有、frontmatter 导入公有顶层。 -4. **运行时**:环境、调用栈、值(文/数/表/记录)、内置 `print`。 -5. **验收**:`tests/structure/*` 与 `tests/keywords/*` 全部 `marqdo run` 通过。 - -### Phase II — 字节码 VM(正经化) - -- AST → 线性字节码(栈式 VM 即可,与 clox / [GoAWK 经验](https://benhoyt.com/writings/goawk-compiler-vm/) 同类) -- 控制流用跳转指令实现分支/循环 -- 同一套金样例必须 bit-同结果(回归) -- 性能与可调试性(反汇编、栈跟踪)优于 Phase I - -### Phase III — 语言完备(按需) - -- 更完整表达式文法、错误模型、外联围栏 FFI -- 生成 OKF 依赖目录 -- (可选)另一后端:编译到 Python/WASM——**另开 ADR**,不替代自研语义 -- **浏览器内运行(路线 C)**:解释器/VM 上 WASM(**非**把 `.mq.md` 译成 JS)——已锁定 [ADR 0002](../adr/0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](browser-wasm.md) - ---- - -## 4. 与 USTC Lab 的知识复用(学什么、不搬什么) - -| 课程内容(摘要) | Marqdo 用法 | -|------------------|-------------| -| Lab1 词法/语法/AST | **直接对标** Phase I 前端;工具可自研递归下降,不必 Flex/Bison | -| Lab2 IR / 访问者 | Phase II 字节码 ≈ 轻量 IR;访问者可用于 AST→字节码 | -| Lab3 后端汇编 | **v1 不做**;解释器 VM 代替机器后端 | -| Lab4 优化 | Phase II 之后可选;解释器也可做常量折叠等 | - -教材仍可读:龙书、陈意云《编译原理》、课主页参考书;解释器专项读 **Crafting Interpreters**(免费:[craftinginterpreters.com](https://craftinginterpreters.com/))。 - ---- - -## 5. 实现语言(本路线图默认) - -**参考解释器:Rust**([ADR 0001](../adr/0001-implementation-language.md))。 - -- 词法/语法:**自研 + GFM crate**,不用 Flex/Bison([dependencies.md](../design/dependencies.md))。 -- Python `spike/` 仅作风险探测与算法草稿。 -- Phase I 树遍历、Phase II 字节码 VM 均在 Rust 中实现。 - ---- - -## 6. 目录规划(正式代码,非 spike) - -``` -Cargo.toml - src/lex/ parse/ ast/ sema/ interp/ bytecode/ runtime/ -tests/ # gold.rs + structure|keywords|errors 夹具 -public/ # 用户可执行文档 -doc/ # 设计文稿 -spike/ # Python 存档,非运行时依赖 -``` - ---- - -## 7. 近期里程碑(可执行顺序) - -| 周序 | 交付 | 完成定义 | -|------|------|----------| -| M0 | 正式包 + CLI 空壳 + 金样例框架 | `marqdo run` 可调用;测试发现「未实现」 | ✅ | -| M1 | 词法·行分类 + 最小 AST | 单测覆盖注释/代码行 | ✅ | -| M2 | 解析:函数、输出调用、返回 | `hello` + `index` 金样例绿 | ✅ | -| M3 | 分支、循环、表格、绑定 | `branch`/`loop`/`collection` 绿 | ✅ | -| M4 | 导入与提升 | `with-import` 绿;**宣称 Phase I 达标** | ✅ | -| M5 | 字节码设计文档 + 原型 opcode | 核心金样例双后端一致;覆盖表见 [bytecode.md](../design/bytecode.md) | ✅ 原型 | - -**Phase I 完成前,不宣称「语言已实现」。** -**仅 hello 特判通过,不算完成。** - ---- - -## 8. 成功判据(产品级) - -在仓库根或任意含 `index.mq.md` 的目录: - -```bash -marqdo run tests/structure/nested-call.mq.md -# 或 -marqdo run tests/structure/import/main.mq.md -``` - -输出与金样例一致;错误带位置;新增语法必须加金样例与单测。这才是「一门解释型语言」的最低合格线。 diff --git a/doc/roadmap/lib-ext-code-as-docs.md b/doc/roadmap/lib-ext-code-as-docs.md deleted file mode 100755 index 62bc55f..0000000 --- a/doc/roadmap/lib-ext-code-as-docs.md +++ /dev/null @@ -1,59 +0,0 @@ -# Roadmap:lib / ext 代码即文档 - -| | | -|---|---| -| 状态 | **Active** | -| 日期 | 2026-09-14 | -| 相关 | [lib-code-as-docs.md](../design/lib-code-as-docs.md) · [view-markup-surface.md](../design/view-markup-surface.md) · [bracket-call-modifiers.md](../design/bracket-call-modifiers.md) · [collection-access-link.md](../design/collection-access-link.md) | - ---- - -## 0. 总序(防返工) - -1. **方括号标记调用**(设计 + AST + 金样)— **已落地** -2. lib / view 设计文档 — **已写** -3. View 表面(Index 链接形、括号调用)— **已落地** -4. 分波改造 `lib/*` → `ext/*` - -旧 `>` / 粗体调用、脚注取元解析均保留。 - -## 1. 里程碑 - -| 波 | 内容 | 状态 | -|----|------|------| -| **Call** | `pre_modifiers`;`tests/structure/bracket-call.mq.md`;mapping / call-arguments | **done** | -| **M0 View** | `InterpPart::Index` → `[k](base)`;`call_display` 修饰表面 | **done** | -| **M1** | 试点 `lib/table` · `lib/text` · `lib/json`(中英)+ public/stdlib | **done** | -| **M2** | 其余 `lib/*` 叙述化;禁新脚注取元 | **done** | -| **M3–M4** | `ext/web`、`ext/ai`:脚注→链接取元;叙述;示例可逐步换括号调用 | **done**(取元迁移) | -| **M5** | quantum / linalg + full gold | **done** | -| **M6** | examples + public/structure + tests/ext·lib 链接取元;cafe 括号调用例 | **done** | -| **M7** | structure collection 金样改链接形;public/stdlib 括号调用例 | **done** | -| **M8** | 教程第 9 章 + Skill examples → 链接取元 / v0.3 标记 | **done** | -| **M9** | 教程其余章节(1–8、10–12、14)全面对齐 v0.3 + 链接取元 | **done** | -| **M10** | public/stdlib 剩余演示统一括号调用;public import 返回面修到 v0.3 | **done** | -| **M11** | View:`bracket_marked` 使无修饰 `[callee]` 也显示括号形 | **done** | - -## 2. 验收(出门) - -- 括号调用与 `[k](c)` 取元金样并存、不回归。 -- 试点库可读:目的句 + 叙述形参 + 一例 + 短实现。 -- `cargo test --test gold` 绿。 -- 脚注取元金样(`tests/structure/footnote*`)仍保留作兼容门禁。 -- 教程与 Skill 示例以链接取元 / `**` 代码 / `*` 返回为准。 - -## 3. 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-14 | 初稿;Call + M0 标 done | -| 2026-09-14 | M1 试点 table/text/json + public/stdlib 标 done | -| 2026-09-14 | M2 其余 lib 叙述化标 done | -| 2026-09-14 | M3–M4 ext/web+ai 脚注→链接取元 | -| 2026-09-14 | M5 quantum/linalg 叙述 + public/features 取元 | -| 2026-09-14 | M6 examples/public/tests 批量链接取元 + cafe 括号调用 | -| 2026-09-14 | M7 structure collection 金样 + stdlib 括号调用例 | -| 2026-09-14 | M8 教程 + Skill examples 同步 | -| 2026-09-14 | M9 教程全书对齐 v0.3 标记与链接取元 | -| 2026-09-14 | M10 public/stdlib 括号调用扫尾 + import 返回面 | -| 2026-09-14 | M11 View `bracket_marked` 无修饰括号调用表面 | diff --git a/doc/roadmap/library-authoring-refactor.md b/doc/roadmap/library-authoring-refactor.md deleted file mode 100755 index ba59303..0000000 --- a/doc/roadmap/library-authoring-refactor.md +++ /dev/null @@ -1,66 +0,0 @@ -# 库源码叙述式重构验收 - -本轮以[可执行开发指南](../library-development.mq.md)为准,覆盖 lib 与 ext 的全部 mq 源码。 -重构前为 117 个文件、1,258 个函数或对象单元;349 个缺少契约,956 条旧显式形参声明。 -完成后为 125 个文件、1,273 个单元。其中 61 份公开标准库保持单文件结构,提供 650 个函数; -另有 lint 库单元。数据、安全、网络、线性代数和 AI 补齐工程入口,独立多文件职责由 index 组织。 -原工作区阅读器改动及本轮之前的功能实现保留。 - -- [x] 标准库保持单文件,赋值、调用与返回融入叙述,宿主调用有动作说明。 -- [x] 量子、网页的契约紧接标题,入口与叶子采用同一叙述规范。 -- [x] 数据、安全、网络、线性代数补齐契约、输入来源、真实工作流与多文件索引。 -- [x] AI 补齐公开与内部单元的职责说明,解释上下文、路由、工具、工作簿和失败处理。 -- [x] 所有单元移除旧形参,参数与返回表对应真实接口;不以占位工具或固定通过标志验收。 -- [x] 逐函数严格检查叙述超过 50%,行内表达式与绑定数据表仍计作代码。 -- [x] 既有接口与实际行为回归;真实工作流和源码示例在 Tree、Bytecode 执行。 -- [x] 扩展安装清单包含新入口及其源文件依赖,精简构建、WASM 与全量回归通过。 - -源码与工程组织 - -标准库不增加强制 index 或平行手册层。每个函数先给参数与返回契约,再说明输入、 -调用效应、用途、边界与实现。新 table.from_pairs / 表.键值转记录将较宽的具名记录改为 -可读的 key/value 行表;空列表、空值、重复键更新、键顺序与输入不可变性均有双后端验证。 - -拓展库入口解释任务选择、依赖、权限、结果跨步骤传递与开发归属。网页继续采用递归布局: -首页拆导航、主体、页脚;页脚与链接的双栏继续拆,直到内部只是单一 Markdown 内容职责。 -父 index 只负责一层关系,叶子保留普通正文。已有双语参考站点验证真实嵌套、预览、服务与 API。 - -AI 中的静态提示、目录与工作簿片段改为普通表格数据,保留原字符、字段顺序和换行; -真正的传输 JSON 仍交给 JSON 库解析。复杂函数解释决策顺序、工具授权、上下文预算、 -事件收集、去重账本和写回责任。中文单步的 sandbox 参数只附加配置行,实际隔离需调用 -CoW 试跑;工具名解析的半角冒号边界也已如实说明。 - -兼容性审核 - -[审核器](../../examples/library_audit.rs)使用真实解析器,对比参数顺序、默认值、对象层级、 -接收者、控制流与计算。遮蔽标签不参与执行;审核只对明确支持的纯常量构造做等价折叠, -重复 JSON 键、不安全数值、非常量与未知调用均不会被当作等价常量。折叠规则有独立测试。 -原始源码快照保留在本次执行环境的临时目录;它不是另一套工具签名或运行时协议。 - -对比只有三项旧缺陷修复产生的八条 AST 差异,其余既有单元的参数、默认值与规范化执行结构一致。 -[精确修复记录](library-authoring-reviewed-fixes.json)保存差异名称、修复前后摘要与原因; -审核器只接受摘要完全匹配的记录,新增差异或失效记录都会失败。 - -| 旧问题 | 实际修复与验证 | -|---|---| -| 中文单步说明中的斜体 map 被当作提前返回,实现错误落入构造器 | 说明恢复为文字,单步真正执行;离线模型替身验证上下文调用与最终结果 | -| 事务构造器返回未绑定的 self | 用实际 txn 与 url 构造句柄;验证提交、回滚及事务外读取,不额外开启事务 | -| 策略说明标题被误认成对象,main 返回未绑定的 routes | 恢复说明与真实 routes 工具,main 调用它;验证 lookup 和默认后端,文件后缀保持文字 | - -执行证据(2026-11-08) - -| 检查 | 结果 | -|---|---| -| `cargo test --offline --test library_authoring` | 5 项通过;覆盖全部 125 份源码与 1,273 单元、包工作流、旧缺陷、双语记录与安装依赖 | -| `cargo test --offline --test stdlib_tasks --test quantum_handbook --test web_handbook` | 18 + 4 + 3 项通过;源码中的真实命令与作者程序在双后端运行 | -| `cargo run --offline --quiet --example stdlib_catalog -- --check` | 650 个公开函数,0 条效应说明需要更新 | -| AST 原始快照对比及精确修复记录检查 | 8 条已审查修复差异,0 条未解释差异,0 条失效记录 | -| `GOFLAGS=-buildvcs=false cargo test --offline --all-targets` | 982 通过、0 失败、2 个原有忽略项,包含千文档编译与 312 项金样例 | -| `cargo check --offline --no-default-features --features wasm-core` | 通过;保留已有未使用代码告警 | -| 版本匹配工具链的实际 wasm32 构建与 Node 验收 | ABI、桥接、标准库、32 位边界、双语记录、转义表格及句中遮蔽计算通过 | -| `git diff --check` | 通过 | - -GOFLAGS 仅用于当前命令绕过工作区所有权引起的 Go VCS 盖章问题,不修改全局配置。 -WASM 使用临时目录中版本匹配的官方工具链;不以本机编译代替真实 wasm 运行。 -网络和身份提供方示例使用离线数据或本机可控服务;没有把构造配置、清单或演示结果 -宣称成生产服务已验证。Node 验收不代表重新完成浏览器 DOM 几何验收。 diff --git a/doc/roadmap/library-authoring-reviewed-fixes.json b/doc/roadmap/library-authoring-reviewed-fixes.json deleted file mode 100755 index 1f8c2ab..0000000 --- a/doc/roadmap/library-authoring-reviewed-fixes.json +++ /dev/null @@ -1,50 +0,0 @@ -[ - { - "after": "74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b", - "before": "754acb518e0d5f0c5c6f6ae6d48c94a1df69ddbdfff13395114786cbe63edf5e", - "difference": "removed ext/ai/policies/step-route.mq.md \"Step class → backend\"", - "reason": "修复说明标题被误认成对象、路由表未绑定且 main 返回未定义 routes;真实 routes 工具返回原策略数据,沙盒行文件后缀显式写为文字。双后端验证 lookup 和默认后端。" - }, - { - "after": "62bd87e62802aeaefbc635715481451d5eee3b918aefe8db9c816039ef91b04f", - "before": "f6c5aecc836c461f7593ffabe9cc2c236a3738a90c49c9c2b5c12a767d97c94c", - "difference": "ext/ai/policies/step-route.mq.md \"main\" changed body", - "reason": "修复说明标题被误认成对象、路由表未绑定且 main 返回未定义 routes;真实 routes 工具返回原策略数据,沙盒行文件后缀显式写为文字。双后端验证 lookup 和默认后端。" - }, - { - "after": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa", - "before": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b", - "difference": "ext/ai/智能体.mq.md \"智能体\" changed receiver", - "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" - }, - { - "after": "888398739b40074de2e2f93943516541eec872cecc284835968650b3ef72a24d", - "before": "a7553f00f8f05c97c2c44299fd2fcd4641c8f5e9acbb6a246874b096a2acdc0a", - "difference": "ext/ai/智能体.mq.md \"智能体\" changed body", - "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" - }, - { - "after": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b", - "before": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa", - "difference": "ext/ai/智能体.mq.md \"智能体.单步\" changed receiver", - "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" - }, - { - "after": "e3853fac627ca88f1557132aabb6b818ecc805ab53e6feacb3b08c77e503ece4", - "before": "aae371909b83bdaec63671897c5581a8ba7f14a5e113bd825fca0576df403e2b", - "difference": "ext/ai/智能体.mq.md \"智能体.单步\" changed body", - "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" - }, - { - "after": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa", - "before": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b", - "difference": "ext/data/db.mq.md \"txn\" changed receiver", - "reason": "事务构造器原来返回未绑定的 self;改为保留调用者传入的真实 txn 和 url 句柄,不额外开始事务。双后端验证构造、提交、回滚与事务外读取。" - }, - { - "after": "0a51bc7e7fe4577f32aae9a76ea461213c3547ea9e937f280e17b6e8075194c5", - "before": "92096850522e76cff3350d582b57ae3124fd400635ad25fd63f208a1994514f0", - "difference": "ext/data/db.mq.md \"txn\" changed body", - "reason": "事务构造器原来返回未绑定的 self;改为保留调用者传入的真实 txn 和 url 句柄,不额外开始事务。双后端验证构造、提交、回滚与事务外读取。" - } -] diff --git a/doc/roadmap/markup-v0.3.md b/doc/roadmap/markup-v0.3.md deleted file mode 100755 index 965241b..0000000 --- a/doc/roadmap/markup-v0.3.md +++ /dev/null @@ -1,111 +0,0 @@ -# 路线图:Marqdo Markdown 语法映射 v0.3(叙述统一) - -「Markup」= Marqdo 把 Markdown 标记当成语法的那一层(不是另一个产品)。v0.3 = 现行映射:粗体代码、斜体返回。 - -| | | -|---|---| -| 状态 | **Done(v1.0.0)** | -| 日期 | 2026-09-13 | -| 设计 | [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md) | -| ADR | [0005-prose-unified-markup.md](../adr/0005-prose-unified-markup.md) | -| 依赖 | 现有管线 [interpreter.md](interpreter.md) · [pipeline-debug.md](../design/pipeline-debug.md) | - ---- - -## 目标 - -把 v0.3 宪法落到词法 → AST → 语义 → 双后端,使动机示例(加一函数)成为金样例,并安全迁移存量代码。 - ---- - -## 里程碑 - -### M0 — 设计冻结与双模式骨架(文档 ✅ / 代码 ⏳) - -- [x] 设计文档 + ADR Proposed + 本路线图 -- [x] **钉死**:空返回词法(设计 §7.2);提及/未使用变量(§4.4);升参 vs 绑定图(§8.2) -- [x] **钉死**:一行多 `**…**` 按序执行(设计 §12 #6) -- [x] **不做双模式** — 直接 v0.3 默认 - -**出门:** 设计评审通过;旗标可切换;无行为默认变化。 - -### M1 — 内联扫描与 AST - -- [x] 金样例目录 `tests/markup-v03/`(夹具 + `gold.rs` `#[ignore]`;见目录 README) -- [x] `Prose` 行内联扫描:`` `ident` `` / `**…**` / `*…*` -- [x] `Stmt::Return` ← italic;`Stmt` ← bold Assign/Call -- [x] `Param.inferred` + 升参 -- [x] `tests/markup-v03/` 金样通过(默认运行时) - -**出门:** `cargo test markup_v03`(无 ignore)绿。 - -### M2 — 形参推断 - -- [x] `InferParams`:首次 `` `名` `` = 必选;`` `名`=默认 `` = 可选 -- [x] 体赋值 `n=n+1` 不误判为默认 -- [x] 与显式 `+` 合并规则 + 警告 -- [x] 方法 `self`/`自` 排除 -- [x] 金样例:默认实参、位置/具名调用、粗体内调用 - -**出门:** 推断签名与 `+` 兼容套件绿。 - -### M3 — 调用面与消歧 - -- [x] `**callee args**` ≡ `> callee args` -- [x] else 臂 `N. *` 与返回斜体消歧 -- [x] 一行多 `**…**` 按序执行 -- [x] 金样例:`---` / `*None*` / 整行 `**` / 兼容 `****`;叙述死绑定不升参 -- [x] 诊断:必选缺失、未知 callee(已有 errors 金样);死变量不报错 -- [x] 残缺粗体:与 GAP-06/07「未闭合后恢复」冲突,保持 Comment 跳过恢复,不硬报错 -- [x] 粗体内表达式语句:`**n + 1**` 求值后丢弃(非误判为调用) -- [x] 叙述斜体:仅整行 / `返回*…*` / 表达式形当返回(`*very important*` 不收束函数) - -**出门:** `tests/markup-v03/*` 覆盖设计 §9 示例。 - -### M4 — 双后端与工具 - -- [x] 字节码发射跟随新 Stmt 源 -- [x] `view` / Structure:推断形参 `chip inferred` + Functions 大纲标注 -- [ ] (可选)`marqdo migrate markup-v03` 机械改写提示/工具 - -**出门:** tree 与 bytecode 后端对 `markup-v03` 金样一致。 - -### M5 — 默认切换与存量迁移 - -- [x] 默认 `MarkupEdition::V03` -- [x] 迁移 `tests/**`、`lib/**`、`ext/**`、`public/**`、教程 -- [x] 更新 `.cursor/skills/marqdo/SKILL.md` 硬规则 -- [x] 修订 [markdown-mapping.md](../design/markdown-mapping.md) 为 v0.3 正式正文(或声明由 v0.3 文件接任) -- [x] ADR 0005 → **Accepted** -- [x] CHANGELOG / 发版说明(破坏性:标记对调)— **v1.0.0** - -**出门:** 全量 gold 默认绿(live LLM 无钥跳过);无 v0.2 双模式。 - ---- - -## 非目标(本路线) - -- 不改插件 ABI / Go libweb -- 不引入 `def`/`return` 关键字 -- M0–M4 不强制改生产 `.mq.md` - ---- - -## 风险 - -| 风险 | 缓解 | -|------|------| -| 标记对调导致海量假失败 | 双模式 + 分目录金样;默认晚切换 | -| 形参推断误伤局部变量 | 金样例钉启发式;允许过渡期写 `+` | -| 空返回 vs `**` 词法 | §7.2 已钉:整行 `**` = 空返回;推荐优先 `---` | -| 叙述反引号误升参 | §8.2 升参需可执行面读取;死绑定不进 params | -| Skill/AI 仍按 v0.2 生成 | M5 同步 Skill;过渡期文档标明版本 | - ---- - -## 修订历史 - -| 日期 | 说明 | -|------|------| -| 2026-09-13 | 初稿与设计/ADR 同步 | -| 2026-09-13 | 空返回与提及性反引号决议合入;M0 文档项勾选 | diff --git a/doc/roadmap/next-phase.md b/doc/roadmap/next-phase.md deleted file mode 100755 index 28818c4..0000000 --- a/doc/roadmap/next-phase.md +++ /dev/null @@ -1,220 +0,0 @@ -# 下一阶段:从玩具到可用语言 - -| | | -|---|---| -| 状态 | **进行中**(P3-D1–D3 live view 断点 v1) | -| 日期 | 2026-08-05 | -| 目标 | 交互 I/O、可信诊断、可生长标准库;view 渐进成为调试宿主 | -| 相关 | [interpreter.md](interpreter.md) · [keywords.md](../design/keywords.md) · [pipeline-debug.md](../design/pipeline-debug.md) · [view.md](../design/view.md) · [view-debug.md](../design/view-debug.md) | - ---- - -## 0. 现状快照(决策依据) - -| 能力 | 现状 | 结论 | -|------|------|------| -| **`print`** | 树遍历 + 字节码均可用 | 够用 | -| **`input`** | CLI 双后端 + `--stdin-file`;frontmatter `stdin:`/`输入:`;live view 表单覆盖;无预置时 capture 提示补线 | **P1a + P1b 完成** | -| **诊断** | 语句级 `path:line:col: message`;字节码指令带 `spans`;errors 金样例双后端断言位置 | **P0 完成** | -| **view** | 结构 + 执行 + 源码 + 函数大纲/搜索;无断点 | 文档浏览器 | -| **debug** | 独立 `marqdo debug`:断点 / 单步 / locals(树遍历) | **P3-D3 v1** | -| **标准库** | 核心 L1 + Mid M1–M6 + Mid2 M7–M10 已完成([stdlib-modules.md](../design/stdlib-modules.md) · [stdlib-mid2.md](../design/stdlib-mid2.md)) | **P2 + Mid1 + Mid2 完成** | -| **模块** | [module-namespace.md](../design/module-namespace.md):**M1+M2 已落地**(库名绑定、`库.成员` / `use`;无扁平合并) | — | - -用户点名的三件事都对,但**不能并行硬开**:断点调试依赖「可信位置 + 可暂停执行」;标准库依赖稳定运行时与 I/O;`input` 在 CLI 与 view 是两条路径。 - ---- - -## 1. 轻重缓急(总序) - -```text -P0 诊断加固(短、撬动后续一切) -P1 输入补完(先 CLI,再 view) -P2 最小标准库(内置 + 可选 .mq.md 库) -P3 view 调试(断点 / 单步)—— 在 P0 之后分期,勿一上来做 DAP -``` - -| 优先级 | 主题 | 为何此刻 | 不做的代价 | -|--------|------|----------|------------| -| **P0** | 诊断完备度 | 便宜;给金样例、字节码、调试打地基 | 断点停错行;双后端错误体验分裂 | -| **P1** | `input` | 「真语言」最低交互面;已有半截实现 | 只能写纯计算/打印 demo | -| **P2** | 标准库 | 无库则用户无法写稍大程序 | 人人自造轮子、示例膨胀 | -| **P3** | 前端调试 | 差异化(文档即调试);成本最高 | view 仍停留在「跑完看 stdout」 | - -**原则:** 先让 **CLI 树遍历**成为完备参考实现;字节码跟进同语义;view 只接「已有事件/钩子」,不单独发明第二套语义。 - ---- - -## 2. P0 — 诊断与错误模型(约 3–7 天) - -### 目标 - -所有用户可见失败统一为: - -```text -path:line:col: message -``` - -树遍历与字节码**同文案、同位置粒度(至少语句级)**;金样例断言位置而不只子串。 - -### 工作项 - -1. **统一出口** - - 解析侧尽量只产 `Diagnostic`(减少裸 `bail!("7:1: …")`)。 - - 字节码编译/VM:错误携带 `Span`(或指令 → 源行映射)。 -2. **位置粒度** - - 短期:保持「语句起点」亦可;中期:为 `Expr`/`CallExpr` 补 `span`,让「未定义名」落在标识符上。 -3. **金样例** - - `tests/errors/*`:断言完整 `path:line:col` 前缀(或相对路径规范化后的形式)。 - - 补:类型错误、除零、循环条件、capture 下 `input` 等。 -4. **文档** - - 更新 [pipeline-debug.md](../design/pipeline-debug.md):错误码/严重级别可列为 P0.5(可选 `E0001` 一类,不阻塞)。 - -### 完成定义 - -- `cargo test`:errors 金样例含位置。 -- 同一 `.mq.md` 在 `--backend tree|bytecode` 下诊断一致(允许实现细节差异写进豁免表)。 -- view 执行失败区仍可读,路径无 `\\?\`。 - -### 刻意不做 - -- IDE DAP、完整堆栈 UI、sourcemap 可视化编辑器。 - ---- - -## 3. P1 — 输入(约 1–2 周) - -分两轨:**CLI 必须先绿**;**view 交互后做**。 - -### P1a — CLI 完备(高优先级) - -| 项 | 说明 | -|----|------| -| 树遍历 | 已实现 stdin;补 `tests/keywords/input.mq.md`(用管道喂入) | -| 字节码 | 增加 `Op::Input`(或等价 host call);与树同语义;capture 下同样拒绝或改走注入 API | -| 文档/用户站 | `public/keywords/input.mq.md`;说明「view 默认无交互 stdin」 | - -完成定义:`echo Alice | marqdo run …` 与字节码后端输出一致;金样例稳定。 - -### P1b — view / 静态站中的输入(中优先级,接在 P1a 后) - -当前 `run_file_capture` **不能**接真实 stdin——这是设计,不是偶然 bug。 - -推荐路径(由易到难): - -1. **脚本化注入(无 UI)** - - `marqdo run --stdin-file answers.txt` 或 frontmatter/`---` 旁测数据。 - - view:执行前提供「预置输入行」文本框,一次性灌入队列。 -2. **实时交互(live view)** - - 执行到 `input` → 暂停 → HTTP/WS 返回 prompt → 用户提交一行 → 继续。 - - 依赖 P3 的「可暂停执行」钩子;可与断点共用会话模型。 -3. **静态 `view output`** - - 无服务器则只支持预置输入或跳过并标明 `input skipped`。 - -完成定义:live `marqdo view` 下至少一个带 `input` 的示例可点按跑通;静态导出行为有文档。 - ---- - -## 4. P2 — 标准库(约 2–3 周,可与 P1b/P3 前半重叠) - -### 分层 - -```text -L0 内置函数(解释器内) len / str / int / float? / type? -L1 标准库模块(.mq.md) 文本、表/集合小工具;官方路径如 lib/ 或 std/ -L2 生态约定 catalog 收录;用户站专章 -``` - -### 建议落地顺序 - -| 迭代 | 内容 | 依据 | -|------|------|------| -| **S0** | `len`(文本/表)、`str`、`int` | keywords.md 已列候选;字节码已有闲置 `Op::Len` 可接线 | -| **S1** | 表工具:取列、行数;字符串 trim/split(先内置或纯 mq 实现二选一) | 文档型语言高频 | -| **S2** | 官方 `lib/` 或 `std/` + 导入约定(仍可用 frontmatter;或日后 `import text:std/text.mq.md`) | 可生长而不破现有导入 | -| **S3** | 错误类型约定(如非法 `int` 文本 → 诊断) | 依赖 P0 | - -### 完成定义(S0) - -- 金样例 + 双后端;`public/` 有对应介绍页。 -- 不引入 `if`/`while` 英文关键字(控制流仍归 Markdown 标记)。 - -### 刻意不做(本阶段) - -- 完整面向对象、包管理器、异步 I/O、HTTP 客户端(可列远期)。 - ---- - -## 5. P3 — 前端成为调试机构(约 3–6 周,分里程碑) - -**不要从 DAP/VS Code 插件开干。** view 已有 Structure / Source / Execution,是天然宿主。 - -```mermaid -flowchart LR - P0loc[P0 可信位置] --> Pause[语句边界暂停钩子] - Pause --> Sess[调试会话 API] - Sess --> UI[view 断点与单步 UI] - UI --> DAP[可选 DAP 适配] -``` - -| 里程碑 | 交付 | 依赖 | -|--------|------|------| -| **D0** | 语句级源映射(树优先;字节码指令→行) | P0 | -| **D1** | 运行时钩子:进入语句前可 pause;`--trace-eval` 结构化事件(JSON 行) | D0 | -| **D2** | 进程内调试会话:设/清断点、continue、step over(先树遍历) | D1 | -| **D3** | **view debug 模式**:源码行点击断点;高亮当前行;侧栏 locals/栈;与文档模式切换 | D2 + 少量 JS 或服务端推进 | -| **D4** | 与 P1b 合流:`input` 暂停复用同一会话 | P1b | -| **D5**(可选) | DAP 薄适配,供外部 IDE | D2 稳定后 | - -### 完成定义(D3 即「可用调试」) - -- 用户能在 `marqdo view` 对某 `.mq.md` 设断点、单步、看变量。 -- 文档站默认模式不变(一次执行);debug 为显式开关。 -- 断点命中行与 P0 诊断行一致(允许文档说明「语句起点」语义)。 - -### 风险与边界 - -- 静态 `gh-pages` **无法**真断点(无常驻 VM);调试仅 **live view**(或 [浏览器 WASM 解释器](browser-wasm.md) C5)。 -- 字节码调试可晚于树遍历一个迭代。 - ---- - -## 6. 推荐排期(可执行流程) - -按「每段都可合并、可演示」切周,避免大爆炸: - -| 周序 | 主题 | 可合并交付 | -|------|------|------------| -| **W1** | P0 诊断统一 + errors 金样例加固 | 双后端错误位置一致 | -| **W2** | P1a `input` 字节码 + 管道金样例 + 用户文档 | CLI 交互闭环 | -| **W3** | P2-S0 `len`/`str`/`int` + 样例 | 「有点像语言」的第一批库 | -| **W4** | P1b 预置输入(view 文本框 / `--stdin-file`) | view 可跑含 input 的 demo | -| **W5–W6** | P3-D0–D2 暂停与会话 | 无 UI 也能用 API/CLI 单步 | -| **W7–W8** | P3-D3 view 断点 UI + D4 与 input 暂停 | **调试机构**第一版 | -| **并行/随后** | P2-S1/S2 扩库;P3-D5 DAP | 按反馈加 | - -若人力紧:**砍掉顺序为 D5 → S2 花活 → 字节码调试**;**不可砍:P0、P1a、P2-S0、D3 之前的 D0–D2。** - ---- - -## 7. 验收总表(「真正可用」最低线) - -1. **I/O**:CLI 上 `print`/`input` 双后端一致;view 至少支持预置或交互输入之一。 -2. **错误**:失败必有稳定位置;常见错误有金样例;用户站不靠「瞎猜 stderr」。 -3. **库**:至少 `len`/`str`/`int` 可用并有文档。 -4. **调试**:live view 可断点 + 单步 + 看当前绑定(树遍历即可宣称 v1)。 -5. **不破坏**:现有 `tests/` 金样例与 `public/` 用户站回归绿。 - ---- - -## 8. 文档与工程动作(开工时) - -1. 本文件定为「下一阶段宪法」;开工后把各 P 拆到 `doc/design/` 子设计(`input-interactive.md`、`stdlib.md`、`view-debug.md`)。 -2. 每个里程碑:金样例 → 实现 → `public/` 更新 →(若行为用户可见)再发版 / 刷 `gh-pages`。 -3. 版本建议:P1a+P0 可打 `v0.0.4`;P2-S0 打 `v0.0.5`;P3-D3 打 `v0.1.0`(「可用调试」语义升级)。 - ---- - -## 9. 一句话路线 - -**先把错误说准、把输入在 CLI 做完,再长出最小标准库;最后把现有 view 升级成可暂停的调试宿主——而不是先做 IDE 插件或大而全标准库。** diff --git a/doc/roadmap/notebook-session.md b/doc/roadmap/notebook-session.md deleted file mode 100755 index 5fbc401..0000000 --- a/doc/roadmap/notebook-session.md +++ /dev/null @@ -1,177 +0,0 @@ -# 文档会话路线图(D0–D5) - -| | | -|---|---| -| 状态 | **D1–D3 已落地(首版);D4–D5 待做** | -| 日期 | 2026-10-17 | -| 层 | Runtime + Document(view 服务端 / 前端) | -| 相关 | [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-kernel.md](../design/foreign-kernel.md) · [foreign-v2.md](foreign-v2.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) | -| 核心表面 Δ | 无 | - -> F 层让“外部语言能持久运行”;D 层让“文档里的多个 cell 像 notebook 一样共享状态、单步、切换内核”。两层分开验收。 - ---- - -## 0. 依赖 - -- **F3**:Python / Node 持久内核。 -- **F3.5**:`session_set/get/names`。 -- 现有 `DebugController`(Marqdo 语句单步)。 -- 现有 `writeback` / `annot` / view 结构。 - -没有 F3/F3.5,D2 只能做一次性 Run,不是共享状态。 - ---- - -## 1. 阶段总览 - -| 阶段 | 内容 | 估算 | -|---|---|---| -| **D0** | 设计/语法/决策文档 | 已完成 | -| **D1** | `src/notebook/`:cell index、表解析、session 结构、诊断 | 2–3 天 | -| **D2** | 服务端 API:open/close/cell run/step/run_all/restart/interrupt | 3–4 天 | -| **D3** | view UI:工具栏、cell 徽标、kernel 下拉、状态面板、journal | 3–4 天 | -| **D4** | statement step、dirty/stale、writeback | 2–3 天 | -| **D5** | replay、持久化、并发优化、测试补全、发布 | 2–3 天 | - ---- - -## 2. D1 — Cell index 与表解析 - -### 内容 - -- 新模块 `src/notebook/`: - - `cell.rs`:从 AST 提取绑定名代码围栏;id/name/lang/line/source hash。 - - `syntax.rs`:读取 `内核表` / `会话表`;中英列名。 - - `session.rs`:`DocumentSession` 结构、kernel registry、value store、journal。 - - `diag.rs`:重复/未知/语言不匹配/未入会话诊断。 -- 自动模式:无表 → 文档顺序 + 默认内核。 -- 解析器不改;只遍历 `Module.functions` + `Stmt::Assign { value: Expr::Code }`。 -- 测试:单元 + `tests/notebook/*.mq.md`。 - -### 验收 - -- 两个 Python cell + 一个会话表 → cells 顺序、kernel 归属正确。 -- 无表 → 自动顺序。 -- 未知内核/未知单元/重复/语言不匹配 → 可读诊断。 -- 未绑定围栏不进入 cell index。 - ---- - -## 3. D2 — 服务端 API - -### 内容 - -- `src/view/notebook_api.rs`(或 `view/session_api.rs`): - - open / close / reload - - cell run / step / run_all - - kernel restart / interrupt / assign - - state list / push / pull - - journal -- Session 存储:`OnceLock<Mutex<HashMap<String, Arc<DocumentSession>>>>`(类似 debug sessions)。 -- 每个文档一个 session;key = 相对路径。 -- 执行线程:cell 执行不阻塞 HTTP;响应返回记录;SSE/EventBus 可选。 -- 错误统一 JSON。 - -### 验收 - -- open 返回 cells/kernels/journal。 -- cell run:never→running→clean/error;状态更新。 -- step:按会话顺序执行下一个。 -- run_all:按顺序;restart 选项。 -- 同 kernel 串行;不同 kernel 可并行。 -- close/drop kill 所有 kernel。 -- API 单测/集成测试。 - ---- - -## 4. D3 — View UI - -### 内容 - -- 工具栏:Run All / Restart & Run All / Step Cell / Step Statement / Kernel 状态 / Restart / Interrupt / State / Journal。 -- Code card: - - 状态徽标(never/clean/dirty/stale/error/running/unlisted) - - kernel 下拉 - - Run / Step - - 输出区(stdout/stderr/result/truncated) - - 执行序号 / 耗时 -- 状态面板: - - Marqdo 值 / kernel 变量分栏 - - Push / Pull / Refresh - - Secret 打码、大对象摘要 -- Journal 面板:表格 + 跳转 + 导出。 -- 键盘:Ctrl/Cmd+Enter、Shift+Enter、F5、F10。 -- 静态导出的 Run 仍隐藏。 - -### 验收 - -- 手工冒烟:两个 Python cell 共享 `x`;切换 kernel 后隔离;Restart 清状态。 -- 状态面板 Push/Pull。 -- 错误 cell 红色徽标 + stderr。 -- 页面刷新后 session 仍在(服务端内存)。 - ---- - -## 5. D4 — Statement step / dirty / writeback - -### 内容 - -- Statement step:复用 `DebugController`,与 DocumentSession 关联;暂停点显示变量。 -- dirty:reload 后 source hash 变化。 -- stale:按会话顺序,上游变更 → 下游 stale(v2 近似)。 -- writeback:单 cell / 全部;`<!-- marqdo-out -->`;不自动。 -- 运行历史 / 执行序号。 - -### 验收 - -- Statement step 在 view 中可用;外联调用原子完成。 -- 编辑 cell → dirty;Run All 后 clean。 -- 上游变更 → 下游 stale。 -- 显式 writeback 写入文档;不自动改文件。 - ---- - -## 6. D5 — Replay / 持久化 / 发布 - -### 内容 - -- Journal replay:新 kernel,按 journal 顺序/输入 hash 重放;比较 stdout/result hash;divergence 报告。 -- 可选持久化 `.marqdo/sessions/<doc-hash>.json`(kernel/cell 归属/journal/value store 摘要;默认 git 忽略)。 -- 并发优化:不同 kernel 并行;同 kernel 串行。 -- 测试补全;文档;catalog;CHANGELOG。 -- 版本:D 层随 1.5.x。 - -### 验收 - -- Replay 能复现 clean 会话;dirty 输入给出 divergence。 -- 关闭/重启服务无进程泄漏。 -- 文档完整;金样例绿。 - ---- - -## 7. 测试矩阵 - -| 测试 | 断言 | -|---|---| -| `notebook/kernels.mq.md` | 内核表/会话表解析 | -| `notebook/auto-session.mq.md` | 无表自动顺序 | -| `notebook/shared-state.mq.md` | 同 kernel 共享变量 | -| `notebook/isolated-kernels.mq.md` | 不同 kernel 隔离 | -| `notebook/step.mq.md` | cell step 顺序 | -| `notebook/state-bridge.mq.md` | Marqdo ↔ kernel 推拉 | -| `notebook/dirty.mq.md` | 编辑 → dirty/stale | -| `notebook/invalid-*.mq.md` | 诊断 | -| API 集成 | open/run/step/run_all/restart/interrupt/close | -| 安全 | exec=false、cwd 越界、超时、Secret 打码 | - -依赖 node 为主;python 条件跳过。 - ---- - -## 8. 完成定义 - -- D1–D4 验收;D5 可选(replay/持久化)。 -- 文档会话与 F 层联调通过。 -- 手工 view 冒烟:共享状态 / 单步 / 切换 / 状态面板 / journal。 -- 测试绿;文档更新;提交推送。 diff --git a/doc/roadmap/object-inheritance.md b/doc/roadmap/object-inheritance.md deleted file mode 100755 index 83bfab0..0000000 --- a/doc/roadmap/object-inheritance.md +++ /dev/null @@ -1,167 +0,0 @@ -# 对象继承语法(未来规划) - -| | | -|---|---| -| 状态 | **I0–I3 已落地**(显式父构造约定;**不做**隐式 auto-super) | -| 日期 | 2026-08-10 | -| 相关 | [objects.md](../design/objects.md) · [markdown-mapping.md](../design/markdown-mapping.md) · [keywords.md](../design/keywords.md) | -| 提案语法 | `# 子类 = > 父类` | - ---- - -## 1. 动机 - -今日 [`objects.md`](../design/objects.md) 明确非目标:**继承 / 接口 / 可见性**。 -实际扩展(如 `# agent` / `# llm`)靠「再写一个对象 + 组合句柄」,缺少: - -- 复用父构造 / 父方法而不复制 `.mq.md` -- 子类型在 `_type` 链上解析方法 -- 与 Markdown 标题体系一致的、可读的继承声明 - -需要一种**不引入 `class`/`extends` 关键字**、且与现有 `=`(绑定)与 `>`(调用)语义兼容的写法。 - ---- - -## 2. 锁定语法(提案) - -```markdown -# 子类 = > 父类 -``` - -| 片段 | 既有含义 | 组合后含义 | -|------|----------|------------| -| `# 子类` | 定义对象 / 类型 | 子类型名 | -| `=` | 绑定 / 赋值 | 类型关系写在「类型定义槽」上 | -| `> 父类` | 调用(此处为类型名) | **基类引用**(不是构造实例) | - -可选带参基类(若基类本身是泛化构造,v1 可暂不支持): - -```markdown -# 特化智能体 = > 智能体 -``` - -中英对称: - -```markdown -# Child = > Parent -# 子类 = > 父类 -``` - -### 2.1 为何不冲突 - -1. **今日** `# 名` 后接的是构造体正文,不是 `` `# 名 = …` `` 标题行。 -2. **语句绑定**是 `*…*` 或行内 `` `x` = ``,不是 ATX `#` 标题。 -3. **`> 父类` 在标题行**出现在 `=` 右侧:解析器可把「`#` 标题含 `=` 与 `>`」识别为**类型声明**,而非执行构造。 -4. 真正构造实例仍是正文或 `# main` 里的 `` `x` = > 子类 … ``。 - -反例(仍是今日语义,不变): - -```markdown -# main - -*`a` = > 父类 * -``` - ---- - -## 3. 运行时语义(草案) - -### 3.1 方法解析 - -实例 map 仍有 `_type` = 构造时的类型名(子类名)。 - -查找 `` `obj`.方法 ``: - -1. 在 `_type` 对应对象上找 `## 方法` -2. 未找到 → 沿 **基类链** 查找 -3. 仍无 → 报错(带类型链) - -构造: - -1. 若子类构造体未显式处理,可先调基类构造(见开放点:是否自动 `super`)。 -2. 返回 map 的 `_type` = **最具体子类名**(不是父类名)。 - -### 3.2 子类正文 - -```markdown -# 工蜂 = > 智能体 - -## 采蜜 - + `花` - -*`out` = > `self`.step task=`花` * -**`out`** -``` - -- 子类可定义新 `##` -- 可覆盖同名 `##`(子类优先) -- 站立提示 / 字段约定:文档层说明,v1 不引入可见性关键字 - -### 3.3 多继承 - -**v1 不支持。** 一个 `# 子 = > 父` 仅一条基类。混入用组合(句柄字段)而非多 `>`。 - ---- - -## 4. 解析与 AST - -标题形态需在 [markdown-mapping.md](../design/markdown-mapping.md) / parse 中新增一种 object decl: - -| 字段 | 值 | -|------|-----| -| `name` | 子类 | -| `base` | 父类(标识符) | -| `body` | 与今日 object body 相同 | - -歧义处理: - -- `# Foo = 1` → **非法**(右侧必须是 `> 类型名`) -- `# Foo = > bar.baz` → v1 **非法**(基类须为已定义对象名,不走任意调用表达式) -- 基类尚未定义 → Pass1 收集后解析;循环继承报错 - ---- - -## 5. 与标准库 / 扩展 - -| 用途 | 例子 | -|------|------| -| 扩展官方智能体 | `# 客服 = > agent` / `# 客服 = > 智能体` | -| 扩展 llm 句柄 | 一般不必要;优先组合 | -| 用户域模型 | `# 订单服务 = > 服务基类` | - -官方 `lib/*` 仍以自由函数为主;继承主要服务 `ext/` 与用户对象。 - ---- - -## 6. 推荐落地顺序 - -```text -I0 语法 + AST + 金样(解析/循环继承错误) ✅ -I1 方法解析沿基类链;构造 _type=子类 ✅ -I2 覆盖方法;文档更新 objects.md ✅ -I3 显式父构造约定(**不做**隐式 auto-super) ✅ -``` - -验收: - -1. 无继承文件行为不变。 -2. 子类实例能调父类 `##`;覆盖后只走子类。 -3. `` # A = > B `` / `` # B = > A `` 诊断清晰。 -4. Skill / 金样:`tests/structure/inherit-*.mq.md`(含显式 `` `self` = > Parent ``)。 - ---- - -## 7. 开放点 - -1. ~~**隐式 super**~~ → **不做**:子类构造体不自动跑父构造。需要父初始化时正文写 `` `self` = > 父类 … `` 再改字段后 `**`self`**`;构造完成时 `_type` 仍为最具体子类名。 -2. 中英基类别名:`> agent` 与 `> 智能体` 是否同一对象(取决于模块导出)。 -3. 继承是否写入 OKF Module 页(catalog 展示 `extends`)——可随 O3/O4 增强。 - ---- - -## 8. 非目标 - -- 接口 / 抽象方法 / 可见性(`public`) -- 多继承、mixin 关键字 -- 用继承替代 `plan` 工作簿接力 -- 把 `# 子 = > 父` 解析成「定义时立即构造父实例」 diff --git a/doc/roadmap/okf-near-match.md b/doc/roadmap/okf-near-match.md deleted file mode 100755 index 7d1c079..0000000 --- a/doc/roadmap/okf-near-match.md +++ /dev/null @@ -1,108 +0,0 @@ -# OKF 相近任务命中 - -| | | -|---|---| -| 状态 | **A 规范句 + B aliases + C 父裁决(soft_match)+ D 本地 n-gram `near` 已落地**;E dense embedding 仍非目标 | -| 日期 | 2026-08-11 | -| 相关 | [okf.md](../design/okf.md) §7 · [ext-agent-plan.md](../design/ext-agent-plan.md) §4.2 · [ext-agent.md](../design/ext-agent.md) | -| 触发观察 | `man-test`:相近 goal 生成两份独立 resource | - ---- - -## 1. 问题 - -v1 agent-kb **精确命中仍是默认快路径**: - -1. `normalize_goal`:去首尾空白、合并连续空白(**不做**近义改写)。 -2. `sig` = 规范化字符串的稳定短哈希;`slug` = 可读路径名。 -3. `agent_kb_lookup`:精确 → aliases → canonicalize → **本地 n-gram `near`(默认开)**;仍 miss 且 `plan soft_match=True` 时父裁决 REUSE/NEW(候选为排序 near 列表)。 - -历史痛点(已由 A/B/C/D 缓解): - -| goal(调用方输入) | 旧行为 | -|--------------------|--------| -| `你是一个智能体,帮我规划明天的行程` | 独立 slug,与下方不命中 | -| `帮我规划明天的行程` | 另一份 resource | -| `帮我规划明天行程` | 又一份(近句碎片) | - -调用方直觉:「这不是同一件事吗?」——现可用 canonicalize、默认 `near_match`,或显式 `soft_match` 父裁决。 - ---- - -## 2. 为何精确指纹仍优先 - -| 理由 | 说明 | -|------|------| -| 假阳性代价高 | 错复用旧工作簿比多建一个文件更糟 | -| 可审计 | `sig` 可复算;`near` 留下 `match`/`score` | -| 哲学 | 多轮 = 子文件接力 + OKF 索引,不是聊天式模糊检索 | - -**结论:** 精确命中长期保留为**默认快路径**;`near` 是可关闭的第四趟(`near_match=False`)。 - ---- - -## 3. 已落地层 - -### A. 规范化后再精确命中 — **已落地** - -`agent_kb_canonicalize`:剥站立前缀、去尾标点;`match: canonical`。 - -### B. 别名 / 标签表 — **已落地** - -Task FM `aliases:`;`match: alias`。 - -### C. 父智能体软裁决 — **已落地(默认关)** - -`plan soft_match=True`:`agent_kb_near_match` 排序候选(含 `score`;空则退回 `list_tasks`)→ 父 `DECISION: REUSE` + `SLUG:` 或 `DECISION: NEW`。 - -### D. 本地字符 bigram + 余弦 — **已落地(默认开)** - -| | | -|--|--| -| 做法 | 稀疏词法向量化(**不是** embedding 模型):canonicalize 后对 goal 与 Task `title\|description\|aliases` 建字符 bigram 词袋,算余弦 | -| API | `agent_kb_near_match`;`agent_kb_lookup` 第四趟 | -| 参数 | `near_match`/`近义命中` 默认 `True`;`near_threshold`/`近义阈值` 默认 `0.78` | -| 痕迹 | `match: near` + `score`;`cache=soft-hit`;可写 alias | - -术语:这是 **sparse lexical near-match**,勿宣传为向量库 / embedding 检索。 - -### E. Dense embedding(可选远期) - -远程 / 本地 dense 向量与 ANN **仍非本仓默认目标**;仅当 D 在真实包体量下证据不足时再评估。 - ---- - -## 4. 演进顺序 - -```text -精确 sig(永不删除) - → A 规范句 + B aliases(已落地) - → C soft_match 父裁决(已落地,默认关) - → D 本地 n-gram near(已落地,默认开) - → E dense embedding(仅有证据再开) -``` - -验收原则: - -1. `near_match=False` 时与无 near 行为一致;`force`/`optimize` 仍跳过 reuse。 -2. 软/近义命中留下 `cache=soft-hit` / `match` / 可选 `score`。 -3. 假阳性可被 `force=True` / 显式 `workbook=` / 调高 `near_threshold` 覆盖。 -4. 实现仍在 **agent 插件 + `ext/ai`**,不进核心 `src/host`。 - ---- - -## 5. 调用方建议 - -- 固定规范 goal;站立语可由 canonicalize 剥掉。 -- 近句碎片依赖默认 `near_match`;字面差更大时开 `soft_match=True`。 -- 策展:合并重复 task,次要措辞写入 `aliases`(O4)。 - ---- - -## 6. 与现有路线图的关系 - -| 条目 | 关系 | -|------|------| -| [okf.md](../design/okf.md) O2 / O5 | 精确 reuse + A/B/C/D;E dense 仍待 | -| [okf.md](../design/okf.md) O4 | `kb query` / 策展可继续扩 aliases | -| [ext-agent-plan.md](../design/ext-agent-plan.md) | 多轮仍只走子文件接力;软命中只影响「选哪个子文件」 | diff --git a/doc/roadmap/perf-validation-report-2026-09-23.md b/doc/roadmap/perf-validation-report-2026-09-23.md deleted file mode 100755 index 5a602c7..0000000 --- a/doc/roadmap/perf-validation-report-2026-09-23.md +++ /dev/null @@ -1,118 +0,0 @@ -# P4 验证汇总报告 — 2026-09-23 - -> 执行 [perf-validation.md](perf-validation.md)(自设计性能验证协议)的结果汇总。 -> 覆盖 three-problems.md 三大问题的**验证矩阵**(§5.2 a–e)。逐例明细见各实验原始报告(文末索引)。 - -| | | -|---|---| -| 协议 | [perf-validation.md](perf-validation.md)(实验 (a)–(e)) | -| 判据源 | [three-problems.md](three-problems.md) §3.7 / 各问题 §2.4 | -| 构建 | marqdo v1.0.7(本仓库工作树;金 20 + 全量回归通过后采样) | -| 端点 | `llm.cflmy.cn/v1`(OpenAI 兼容;temperature=0) | -| 模型 | 修复实验:`cflmy`、`mimo-v2.6-flash`;盲测:`deepseek-flash`、`mimo-v2.6-pro`(按用户指定) | -| 回归 | 全量干净回归(无 API key 基线)**零失败** | - -## 1. 五实验结果与判据对照 - -| 实验 | 判据 | 结果 | 判定 | -|---|---|---|---| -| **(a) 锚点消融**(T3.3,双模型×20例×双臂,三轮) | anchor 臂一轮修复率 ≥ 80%;护栏 0 次越界应用 | cflmy anchor **20/20=100%**(plain 17/20=85%);mimo-v2.6-flash anchor **20/20=100%**(plain 18/20=90%;容错加固中的第二轮 anchor 18/20=90% 亦 ≥80%);越界拒/越界应用 0/0 | ✅ 过 | -| **(b) 盲测**(查询式 vs 全文档背诵,6任务×2臂) | 四判据:最终通过率 Q 不劣于 D(允许 −0 例);首轮语法错误率 Q ≤ D;平均修复轮次 Q ≤ D;token ≤ 70% of D(首轮契约诊断率为观测项) | deepseek-flash:docs 4/6 vs query 0/3(3 例端点 infra 剔除);首轮语法错 2/3 vs 2/6;token 69,771 vs 57,276。mimo-v2.6-pro:两跑均端点 infra(12/12、11/12),**不可评估** | ❌ 四判据未全立 ⇒ 按 §3.7 继续改协议 | -| **(c) 契约消融**(四边界×三情形) | 带契约错值拦截 = 100%;带契约对值误报 = 0%;无契约路径零回归 | 拦截 4/4=**100%**;误报 0/4=**0%**;无契约 4/4 动态语义保持(含 `missing map key` 基线) | ✅ 过 | -| **(d) 防漂移演练**(9 漂移 + 2 负对照) | 故意写错必报 = 100%;对照组误报 = 0% | 必报 9/9=**100%**(`unknown_type`×2、`param_drift`×2、`return_mismatch`、`arg_mismatch`、`unknown_key`、`contract.duplicate`、`contract.unknown_table`);负对照误报 0/2 | ✅ 过 | -| **(e) 核心守卫演练**(3 种变异注入) | 单边改动必红;还原必绿 | 3/3 必红(`CORE_CONSTRUCTS` 私增、`core-surface.md` 私增、金样删除);还原全绿 | ✅ 过 | - -**可复制结论(a/c/d/e 全过)**:锚点臂一轮修复率双模型 100%(判据 ≥80%,增量 +15pp/+10pp——易锚定样本近天花板,区分性留难样本扩展);契约系统"只在声明处拦截、零误报、不碰动态路径"成立;契约/实现互查防漂移 100% 必报;核心面单边膨胀被 CI 守卫机械阻断。 - -## 2. 实验 (c)(d)(e) 明细 - -### (c) 契约消融(tests/contract_ablation.rs,确定性) - -四边界(调用实参 / 返回值 / 表绑定 / 键访问)各测三情形: - -| 情形 | 口径 | 结果 | -|---|---|---| -| ① 带契约 + 错值 | 必须拦截(`contract.arg_mismatch` / `contract.return_mismatch` / `contract.field_mismatch` / `contract.unknown_key`) | 4/4 | -| ② 带契约 + 对值 | 不得报契约错(同路径同形状) | 0/4 误报 | -| ③ 无契约 + 错值 | 保持动态语义(不得出现 `contract.*`;走经典动态错误如 `missing map key`) | 4/4 | - -取元一律用主推的 `[]()` 形(`[键](`集合`)`)验证;`集合[^键]` 过渡形保留兼容金样覆盖。 - -### (d) 防漂移演练(tests/drift_drill.rs,确定性) - -9 个"故意写错"全部必报:类型词拼错、参数名漂移、升参未覆盖、返回越约、实参越约、未知键、重复契约表、错列表头契约表、运行时值越约。负对照 2 例(被绑定的数据表、纯动态程序)零误报。同时验证"契约表一经出现即为完整声明"(新升参未覆盖 ⇒ `contract.param_drift` warning)被按设计触发。 - -### (e) 核心守卫演练(人工变异,tests/core_surface.rs 必红验证) - -| 变异 | 注入点 | 结果 | -|---|---|---| -| 私增 `ghost-construct` | `src/parse/mod.rs` `CORE_CONSTRUCTS` | 🔴 必红 | -| 私增 `ghost-construct` 行 | `doc/design/core-surface.md` | 🔴 必红 | -| 删除金样文件 | `tests/markup-v03/soft-emphasis.mq.md` | 🔴 必红 | - -三次还原后 🟢 全绿。CI 守卫强制"清单与文档双改 + 全部金样存在"。 - -## 3. 实验 (b) 盲测:详况与诚实结论 - -### 协议 - -两臂系统提示词同文 = 硬规则 12 条 + 契约表三形状;**唯一变量 = 语法知识获取**: - -- `query` 臂:MLSP 查询通道(`QUERY: <关键字>` ⇒ `mlsp syntax` 卡片,含戒律原文/样例/文档锚点;≤3 次) -- `docs` 臂:完整 markup 参考背诵(`tests/blind/docs-bundle.md`,背诵式全语法表 + 中文内建面) - -任务 6 例(`tests/blind/tasks/`):业务 3(保险理赔准备金 / 工程进度款 / 采购付款门槛,均出自律所实测任务集)+ QuixBugs 改写 3(gcd / 最大子段和 / 质因数分解);oracle = stdout 精确匹配(任务书自带期望输出,把推理难度控制掉,失败归因于**语言能力**)。修复回路 ≤2 次(validate 结构化诊断 + stderr 回喂)。 - -### deepseek-flash(完成) - -| 臂 | 通过(一轮) | 通过(最终) | 首轮语法错 | 平均修复轮(过例) | token(p+c) | infra 剔除 | -|---|---|---|---|---|---|---| -| query | 0/3 | 0/3 | 2/3 | – | 69,771(42,478+27,293) | 3/6 | -| docs | 3/6 | **4/6** | 2/6 | 0.50 | 57,276(33,346+23,930) | 0/6 | - -- **docs 臂**:业务题 3/3 全部一轮通过(各 ~3k token);`qb_gcd` 修复 2 轮过;`qb_max_sublist_sum`、`qb_get_factors` 暴露真语法滑倒(列表字面量被当调用 `unknown function [-2,`;参数名漂移 `missing argument for parameter value`)。 -- **query 臂**:查询通道**被积极使用**(5/6 例用满 3 次,多词查询如 `条件分支 写法` 也能正确命中卡片——已单独验证查询匹配无缺陷);但 3 例被端点空体吃掉,其余 3 例败于真语法错(Python 式元组 `(a, b)` ⇒ `trailing input in expression`;Python 式调用 `gcd(48, 18)` ⇒ `unknown function gcd(48`)与 1 例查询后未交程序。 - -### mimo-v2.6-pro(两跑均不可评估) - -首跑 **12/12** 全部"非 JSON / 空体"(与 deepseek 并行时段)。三向探针(小提示词×12000/4000、大提示词×12000)证实**网关随机空体**、与 `max_tokens`/提示词体量无稳定关系。加重试(8→12 次、退避 10→15 秒)并**单独**重跑后仍为 **11/12** 端点 infra(含两臂首聊即 `tok=(0,0)` 的空体);唯一执行到的 `qb_gcd` 例暴露真语法错(`**y**` 作语句 ⇒ `unexpected expression input`)。**结论:`mimo-v2.6-pro` 经本网关不可评估**,(b) 判据以 `deepseek-flash` 数据为准。原始报告:[blind-experiment-2026-09-23-mimo-v2.6-pro.md](blind-experiment-2026-09-23-mimo-v2.6-pro.md)。 - -### 判据对照(截至 deepseek-flash) - -| 判据(协议 §2.4 原文口径) | 目标 | 实测(deepseek-flash,非 infra 口径) | 判定 | -|---|---|---|---| -| 最终通过率(≤3 轮)Q 不劣于 D(允许 −0 例) | ≥ D | 0/3 vs 4/6 | ❌ | -| 首轮语法错误率 Q ≤ D | ≤ | 2/3 vs 2/6 | ❌ | -| 平均修复轮次 Q ≤ D | ≤ | query 臂无通过例,不可比 | ⚠️ | -| token 用量 Q ≤ 70% of D | ≤ 40,093 | 69,771(D 的 121.8%) | ❌ | -| (观测项)首轮契约诊断率 Q ≤ D | – | 1/3 vs 0/6 | ➖ 观测 | - -**诚实结论:在 deepseek-flash 上,"查询式"没有跑赢"全背诵"**——三项可判量化判据未达,按协议 §3.7 判定:**四判据未全成立 ⇒「AI 不必学语法」本轮未获实证,继续改协议**(不是证伪——infra 吞掉 query 臂一半样本,非 infra n=3)。要点: - -1. **统计力被端点削弱**:query 臂 6 例中 3 例被空体吃掉(协议无从执行),非 infra 样本 n=3;mimo-v2.6-pro 整组不可用。判据是"有方向的强声明",当前证据**不足以支持也未证伪**其普适性,只能定格为"deepseek-flash × 本任务集 × 本协议版本"下的一次未达标观测。 -2. **失败模式是真发现**:查询臂的败例是**跨语言习惯泄漏**(元组表达式、Python 调用形)——查询卡片能回答"条件分支怎么写",但模型不查询"这里能不能用元组"。说明"AI 不必学语法"的瓶颈不在**查询机制**,而在**模型的自查纪律**(不知道自己不知道)。 -3. **token 判据方向存疑**:查询式省的是**系统提示词常驻**(背诵包),花的是**多轮往返**。6 例短程序任务里往返开销 > 常驻节省;该判据更适用于**长会话多文件**场景(一次背诵包 × N 轮 vs 每轮均摊查询),本轮任务形态低估了查询式的收益面。 -4. **docs 臂的 4/6 说明任务集有区分度**(不是全过/全不过的退化测量)。 - -## 4. 测量端基础设施记录(方法学附注) - -- **LLM 端点不稳定**是本轮最大的干扰源:随机空体、reasoning 模型 `finish=length` 截断(思考吃满额度、正文为空)。对策:空体重试 5→12 次 + 退避 5→15 秒、截断自适应(`max_tokens` 加倍重试,封顶 32k)、infra 例从判据比率中剔除并单列。 -- **harness 缺陷两处**(已修,未污染最终数据):查询额度用满后的续篇被当最终回复(⇒ 假"无程序");程序提取失败不进修复回路(⇒ 少给模型一次标准修复机会)。修复后的协议对两臂完全一致。 -- **模型口径变化留痕**:原定 `cflmy`/`mimo-v2.6-flash` 组合按用户指示弃用,改 `mimo-v2.6-pro`/`deepseek-flash`;修复实验 (a) 的双模型数据仍是原组合(金 20 协议已完成,不重跑)。 - -## 5. 材料与复现 - -```bash -# (a) 锚点消融(需要 API key) -cargo test --test repair_experiment -- --ignored --nocapture # anchor/plain 双臂×20例 -# (b) 盲测(每模型一次;建议单独跑避免并发) -OPENAI_MODEL=deepseek-flash MARQDO_EXP_DATE=2026-09-23 cargo test --test blind_experiment -- --ignored --nocapture -# (c)(d) 确定性 -cargo test --test contract_ablation --test drift_drill -# (e) 核心守卫(变异注入→必红→还原必绿,按 perf-validation.md §5 手法) -cargo test --test core_surface -``` - -- 任务书 / 背诵包(冻结,勿改):`tests/blind/` -- 原始报告:[blind-experiment-2026-09-23-deepseek-flash.md](blind-experiment-2026-09-23-deepseek-flash.md) · [blind-experiment-2026-09-23-mimo-v2.6-pro.md](blind-experiment-2026-09-23-mimo-v2.6-pro.md)(首跑全 infra)· [repair-experiment-2026-09-22.md](repair-experiment-2026-09-22.md) · [repair-experiment-2026-09-22-mimo-v2.6-flash.md](repair-experiment-2026-09-22-mimo-v2.6-flash.md) -- 判据协议:[perf-validation.md](perf-validation.md)(版本化于本仓库,实验前冻结) diff --git a/doc/roadmap/perf-validation.md b/doc/roadmap/perf-validation.md deleted file mode 100755 index 9cb0315..0000000 --- a/doc/roadmap/perf-validation.md +++ /dev/null @@ -1,125 +0,0 @@ -# P4 性能验证设计(实验协议与判据) - -| | | -|---|---| -| 状态 | **Accepted · P4 执行依据** | -| 日期 | 2026-09-23 | -| 授权 | 用户授权**自行设计**本性能验证设计(P4 不再等待外部文档导入;`doc/next/002.md` 与性能验证无关) | -| 上位判据 | [three-problems.md](three-problems.md) §5.1 判据矩阵 + §5.2 实验 (a)–(e);「判据矩阵全绿 + 实验数字可复现之前,三大问题一律视为未解决」 | -| 工程任务 | [three-problems-plan.md](three-problems-plan.md) Phase 1–3(已完成);本文只负责**验证它们** | - -> **本文定位**:把 three-problems.md §5.2 的五个实验操作化——每个实验给出**材料、协议、指标、判据**,全部机器可执行、数字可复现。实验产物 = 报告 [perf-validation-report-2026-09-23.md](perf-validation-report-2026-09-23.md)。**只认行为与数字,不认宣言。** - -## 0. 总览 - -| 实验 | 验证对象 | 判据(全过 = 该问题的实证成立) | 执行方式 | 状态 | -|------|----------|-------------------------------|----------|------| -| (a) 锚点修复消融 | 问题三 · 可靠反馈 | 一轮修复率 ≥ 80%(anchor 臂),护栏 0 越界 | 模型在环 `tests/repair_experiment.rs` | ✅ 已完成(三轮双模型) | -| (b) 盲测 | 问题三 · 不必学语法 | 查询组错误率 ≤ 全文档组;token 显著更少;修复轮次不升 | 模型在环 `tests/blind_experiment.rs` | 见报告 | -| (c) 契约消融 | 问题二 · 语义校验 | 拦截率 = 100%;误报率 = 0%;无契约路径零回归 | 确定性 `tests/contract_ablation.rs` | 见报告 | -| (d) 防漂移演练 | 问题二 · 契约可信 | 故意写错契约必报率 = 100% | 确定性 `tests/drift_drill.rs` | 见报告 | -| (e) 核心守卫演练 | 问题一 · 核心要小 | 三种变异注入各必红 → 还原必绿 | 变异脚本(见 §4) | 见报告 | - -判定口径([three-problems.md](three-problems.md) §5.1):**任何一项判据不成立,对应问题即「未解决」**——不许用文档宣言充数。 - ---- - -## 1. 实验 (a):锚点修复消融(问题三 · 可靠反馈) - -**假设**:诊断带 `doc_anchor`/`doc_quote`/`suggestion`(锚点诊断)比裸诊断显著提高一轮修复率。 - -- **对照**:`anchor` 臂(全量诊断字段)vs `plain` 臂(剥掉 doc_anchor/doc_quote/suggestion)。 -- **材料**:golden 20 例(10 骨架 × 2 变体:arg/ret/field/key/typo/drift/dup),易锚定错误。 -- **协议**:`validate` → `repair_targets` → 模型行编辑 → `repair_apply`(越界必拒/abstain)→ 复验;≤2 轮。 -- **指标**:一轮修复率、最终修复率、平均尝试、越界拒、弃权。 -- **判据**:anchor 臂一轮修复率 ≥ 80%;护栏 0 次越界应用(越界必拒由 `tests/repair_loop.rs` 硬断言兜底)。 -- **执行**:`OPENAI_MODEL=… cargo test --test repair_experiment -- --ignored --nocapture`。 -- **结果**:三轮双模型全过(cflmy anchor 100% / mimo 90%→100%,plain 85%–100%,护栏 0 越界)—— - 详见 [repair-experiment-2026-09-22.md](repair-experiment-2026-09-22.md) 与 - [repair-experiment-2026-09-22-mimo-v2.6-flash.md](repair-experiment-2026-09-22-mimo-v2.6-flash.md)。**✅ PASS**。 -- **诚实注记**:样本为易锚定错误(两臂近天花板),锚点增量的区分性证据留待难样本扩展;不影响本判据达标。 - -## 2. 实验 (b):盲测——查询式 vs 全文档背诵(问题三 · 超级核心) - -**假设**:「零语法文档 + MLSP 查询」组(Q)成绩**不劣于**「全文档背诵」组(D),且 prompt token 显著更少、修复轮次不升([three-problems.md](three-problems.md) §3.7 最终判据)。 - -### 2.1 对照(唯一变量 = 语法知识的获取方式) - -| 臂 | 系统提示词内容 | 语法知识来源 | -|----|----------------|--------------| -| **Q 查询组** | 硬规则(12 条)+ 契约表三形状 + MLSP 查询通道说明 | 按需 `QUERY: <关键字>`(≤3 次,harness 代答 `mlsp syntax` 卡片) | -| **D 全文档组** | 硬规则(12 条)+ 契约表三形状 + **完整 markup 参考**(`tests/blind/docs-bundle.md`:v0.3 全语法表 + 中文内建面) | 上下文预载(背诵) | - -两臂共同点:硬规则与契约表形状**同文**(受控变量,不测契约知识差异);修复回路相同(`mlsp validate` 诊断回喂,≤2 轮);模型 / 温度 / 任务 / 提示词模板相同。 - -### 2.2 材料:任务集(6 例,业务 3 + 算法 3) - -| id | 类型 | 任务 | 功能 oracle(stdout 精确匹配) | -|----|------|------|-------------------------------| -| `claims_reserve_settle` | 业务 | 保险准备金(免赔/共保/分项限额/追偿/地板) | `28000` | -| `contract_milestone_pay` | 业务 | 工程里程碑应付款(保留金/逾期罚/变更/税/地板) | `37354` | -| `vendor_po_gate` | 业务 | 采购 PO 准付闸(折扣/加急/预算帽/合规费/地板) | `814` | -| `qb_gcd` | 算法 | 最大公约数;打印 gcd(48,18) gcd(1071,462) gcd(0,5) gcd(17,5) 各一行 | `6` `21` `5` `1` | -| `qb_max_sublist_sum` | 算法 | 最大子段和;三组输入各打印一行 | `6` `6` `-1` | -| `qb_get_factors` | 算法 | 质因数分解,因数以 `*` 连接;12 / 13 / 60 各一行 | `2*2*3` `13` `2*2*3*5` | - -业务任务书复用 MarqdoThesis `formal/exp3-bizreq/data/tasks/`(权威规则文本原样进入提示词);算法任务书为 QuixBugs 改写(从「修 bug」改「实现 + 固定输出」,消除参考源码变量)。 - -### 2.3 协议(每例) - -1. 提示词 = 任务书 + 「输出完整 `.mq.md` 源码于单个 ```markdown 围栏」; -2. **查询阶段**(仅 Q 臂):模型可输出 `QUERY: <关键字>` 行,harness 以 `mlsp syntax` 卡片作答并继续;累计 ≤3 次; -3. **执行阶段**:`marqdo run` → stdout == oracle 即通过;失败则回喂 `mlsp validate` 结构化诊断 + stderr,允许 ≤2 次修复; -4. 记录每轮 token(API `usage.prompt_tokens + completion_tokens` 累计)。 - -### 2.4 指标与判据 - -| 指标 | 口径 | 判据 | -|------|------|------| -| 功能通过率(一轮 / 最终≤3 轮) | stdout 与 oracle 精确匹配 | Q 最终通过率**不劣于** D(允许 −0 例) | -| 首轮语法错误率 | 首轮 `validate`/run 出现 parse 类失败的例数占比 | Q ≤ D | -| 首轮契约诊断率 | 首轮出现 `contract.*` 诊断的例数占比 | Q ≤ D(观测项) | -| 平均修复轮次 | 通过前的修复次数(含首轮生成记 0) | Q ≤ D | -| token 用量 | 逐例累计 prompt+completion | Q **显著更少**(≤ 70% of D) | - -**判定**:四条判据全成立 ⇒ 「AI 不必学语法」实证成立;否则按 §3.7「继续改协议」,不得以改进文档充数。 -- **执行**:`OPENAI_MODEL=… cargo test --test blind_experiment -- --ignored --nocapture`(每模型一轮)。 - -## 3. 实验 (c):契约消融(问题二 · 语义校验) - -**假设**:契约只在**有契约处**拦截错误值(P1:无契约 = 全动态),且不误报。 - -- **材料**:`tests/contract_ablation.rs` 内联四边界用例(调用实参 / 返回 / 表绑定 / 字段访问)×三形态: - ① 带契约 + 错值 → **必拦**(`contract.*` 诊断);② 带契约 + 对值 → **零误报**(正常产出);③ 同程序**删契约表** + 错值 → **零契约诊断**(动态语义原样)。 -- **指标与判据**: - - 拦截率 = ①被拦 / ①总数 = **100%**; - - 误报率 = ②误报 / ②总数 = **0%**; - - 无契约零回归 = ③零 `contract.*` 诊断且输出 = 动态语义基线;且全量 `cargo test` 绿(441+ 既有测试是无契约路径的主回归面)。 -- **执行**:`cargo test --test contract_ablation`。 - -## 4. 实验 (d):防漂移演练(问题二 · 契约可信) - -**假设**:契约写错**必**被机器抓(不静默信任契约)——three-problems.md §2.8「故意写错契约的金样必红」。 - -- **材料**:`tests/drift_drill.rs`——故意写错契约的 N 例(类型 typo `nubmer`、未知对象类型、契约参数名 ≠ 升参名 ×2、返回契约明显不符、重复契约表、错位契约表)+ **负对照**(被绑定的 `字段|类型` 数据表 = web_db_migration 式,必须**不**被当契约吃掉)。 -- **指标与判据**: - - 必报率 = 漂移例被诊断(`check` 报错/警告或运行时 `contract.*`)/ 漂移例总数 = **100%**; - - 负对照误报 = **0**。 -- **执行**:`cargo test --test drift_drill`。 - -## 5. 实验 (e):核心守卫演练(问题一 · 核心要小) - -**假设**:核心表面任何**单侧**变更(代码/文档/金样不同步)→ CI 必红——three-problems.md §1.5「新增标记不更新清单时 CI 必须红」。 - -- **材料**:`tests/core_surface.rs` 守卫 + 三种变异注入(脚本化,`git checkout` 还原): - 1. `src/parse/mod.rs` `CORE_CONSTRUCTS` 增一行、不改文档 → **必红**; - 2. `doc/design/core-surface.md` 表增一行、不改代码 → **必红**; - 3. 金样文件改名(路径失效)→ **必红**。 -- **指标与判据**:3/3 变异注入后守卫测试红;还原后全绿。**必红率 = 100%**。 -- **执行**:报告内嵌演练记录(命令 + 测试输出摘录)。 - -## 6. 报告与复现 - -- 报告:[perf-validation-report-2026-09-23.md](perf-validation-report-2026-09-23.md)((a) 引用既有两份实验报告;(b)–(e) 本次产出)。 -- 复现命令全部写入报告各节;模型在环实验记录模型名与端点,判据数字允许 ±1 例波动(模型非确定性),**判据线本身不放宽**。 -- 汇总结论回填 [three-problems-plan.md](three-problems-plan.md) 落地记录;§5.1 判据矩阵逐行标注 ✅/❌。 diff --git a/doc/roadmap/prove-release-2.8.0.md b/doc/roadmap/prove-release-2.8.0.md deleted file mode 100755 index 7f2fd73..0000000 --- a/doc/roadmap/prove-release-2.8.0.md +++ /dev/null @@ -1,133 +0,0 @@ -# v2.8.0 发布说明 · Release Notes(prove) - -> 仓库权限说明:本文件由 2.8.0 收口时的自动化会话写入 `doc/roadmap/` -> (`CHANGELOG.md`、`README.md`、`doc/releases/`、`skills/marqdo-dev/` 为 -> root 属主、运行账号不可写)。内容已定稿,合入即可;§4 为待合入原文。 - -## 1. 一句话 - -`marqdo prove` 正式发布:知识文件的定理表 → Lean 4 证明 → 自动判定。 -没有 Lean 工具链也能跑(离线符号执行,诚实降级);有 Lean 时全链路证明, -假定理给出路径见证反例,离线与 Lean 分歧时显式报错永不落绿。 - -`marqdo prove` ships: theorem tables in knowledge files compile to Lean 4 -and are judged automatically. It runs without a Lean toolchain (offline -symbolic execution, honest degradation); with Lean, fake theorems get -counterexamples and any offline/Lean divergence fails loudly. - -## 2. 亮点(Highlights) - -| | | -|---|---| -| 定理表 | `| 定理 | 结论 | 前提 | 策略 |`,结论文法:`结果.ok`、`包含(轨迹,…)`、`长度(轨迹)`、参数比较,且/或/非组合 | -| 六段管线 | 装载 → 降级 → 定型 → 生成(Lean 4.35)→ 判定(离线先行 + Lean 复核)→ 证书 | -| 离线判定 | F1–F5 片段符号执行:路径枚举、轨迹形状、构造器结构、自由原子二分、区间字面重述与反例见证(毫秒级) | -| 单调性护栏 | 离线 `checked` 但 Lean 证不出(或反例被证出)→ `error[proof.divergence]` 退 1——绝不让离线判定比 Lean 更乐观 | -| 诚实状态 | `proved > checked > unverified > rejected > unproved > error`;`checked ≠ proved`;无 Lean 时状态如实降级(咨询性退 0),`--require-lean` CI 严格模式退 2 | -| 反例 | 假定理给出区间端点见证(如 `金额 = 10001`)并指回定理表行号 | -| 证书缓存 | 复合键(源码⊕计划⊕库⊕Lean 版本⊕CLI 版本),`.marqdo/prove/`,命中跳过判定;`--no-cache` 绕过 | -| 目录模式 | `prove --all 目录`(`--max-files` 默认 200):逐文件出证,整体取最差,聚合 JSON | -| 差分一致性 | T4 语料:解释器求值 == Lean 语义(算术/中文标识符/分支/拼接/i64 边界/结构字段) | -| 工具链 | `--lean` 显式指定 → `MARQDO_PROOF_LEAN` → PATH;内嵌判定库按内容哈希缓存构建,无需 lake/elan | - -## 3. 使用(Usage) - -```bash -marqdo prove 审批.mq.md --json # 判定 + 单个 JSON 报告 -marqdo prove emit 审批.mq.md # 只生成 Lean 模块 + plan.json -marqdo prove audit 审批.mq.md # 只审查可证子集(不写盘) -marqdo prove --all skills/ --json # 目录聚合(整体取最差) -marqdo prove clean # 清空 .marqdo/prove -``` - -测试:`cargo test --test prove`(无 Lean 全绿)· -`MARQDO_PROOF_LEAN=<lean> cargo test --test prove_lean --test prove_corpus --test conformance`(有 Lean 全链路 + 40 夹具单调性 + T4 一致性)。 - -## 4. 待合入原文(需 root 属主文件权限) - -### 4.1 `CHANGELOG.md` 追加 - -```markdown -## v2.8.0 — 2026-11-17 - -`marqdo prove` 正式发布:定理表 → Lean 4 证明 → 自动判定。离线符号执行 -(F1–F5)无工具链可用,`checked` 永远弱于 `proved`;单调性护栏让判定器 -缺陷显式失败;假定理给出反例见证;证书缓存与目录模式面向智能体批量出证。 - -`marqdo prove` ships: theorem tables compile to Lean 4 and are judged -automatically. Offline symbolic execution works without a toolchain, -monotonicity guardrails fail loudly on judger defects, fake theorems get -counterexample witnesses, and certificate caching plus directory mode -support agent-scale proving. - -详见 [双语发布说明](../releases/v2.8.0.md)。 -``` - -### 4.2 `README.md` 修改 - -版本行(第 19–21 行)替换为: - -```markdown -当前 CLI **2.8.0** 新增 `marqdo prove`:知识文件的定理表编译为 Lean 4 并自动 -判定真假——没有 Lean 工具链也能离线符号执行(诚实降级,绝不冒充证明), -有 Lean 时全链路证明并给出反例见证。参见[发布说明](../releases/v2.8.0.md)。 - -CLI **2.8.0** adds `marqdo prove`: theorem tables in knowledge files compile -to Lean 4 and are judged automatically — offline symbolic execution without -a toolchain (honest degradation, never impersonating a proof), full proofs -with counterexample witnesses when Lean is available. -``` - -「愿景与期许」清单追加第 7 条: - -```markdown -7. **知识可证明**:知识文件内的定理表 → Lean 4 定理 → 自动判定 - (`marqdo prove`);离线符号执行与 Lean 单调一致,分歧显式报错。 -``` - -### 4.3 `skills/marqdo-dev/index.mq.md` 追加 `prove` 任务 - -```markdown -## prove - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | "." | 单个 `.mq.md` 或目录(目录需要 all=True) | -| all | bool | False | 目录模式:递归收集 .mq.md 逐文件出证,整体取最差状态 | -| max_files | num | 200 | 目录收集上限 | -| require_lean | bool | False | CI 严格模式:未判定状态退 2 | -| json | bool | False | 单个 JSON 对象输出(智能体可读契约) | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:真实 `marqdo prove` 退出状态、标准输出与错误输出 | - -证明知识文件的定理表:先离线符号执行(毫秒级 checked,不是 proved), -有 Lean 工具链时由 Lean 复核升级 proved;假定理给出路径见证反例; -离线与 Lean 分歧触发 proof.divergence 错误并退 1,永不落绿。 -不带 Lean 时状态如实停留在 unverified/checked(咨询性退 0), -require_lean=True 才把未判定当作阻塞。 - -通过只说明所选文件判定完成,不能替代 test 任务的运行时验收; -两者结合才是完整验收。 - -1. len(text.trim(`path`)) == 0 - Return *[要求明确的证明范围](result.error(code="dev.prove_path", message="path is required", operation="prove"))*. -1. `all` - We **argv = ["prove", "--all", `path`, "--max-files", text.num_text(`max_files`)]**. -1. not `all` - We **argv = ["prove", `path`]**. -1. `require_lean` - We **argv = [追加严格模式](table.append(list=`argv`, item="--require-lean"))**. -1. `json` - We **argv = [追加机器可读输出](table.append(list=`argv`, item="--json"))**. -We **checked = [执行真实证明管线](engineering.run(argv=`argv`, timeout_ms=600000, max_output=4194304))**. -验收结束后返回*[按真实退出状态判断结果并保留输出](engineering.check_exit(outcome=`checked`))*。 -``` - -## 5. 已知限制(Known limitations) - -- `foreach` 维持 `proof.foreach_pending`(可证子集无循环;fold 编码 → 2.9)。 -- 跨模块调用 = 不透明操作;assume-guarantee 后置条件复用 → 2.9(依赖假设表 T3)。 -- 除零/模零:解释器为运行时错误,P1 判定库模型返回 `.int 0`(已记录偏差)。 -- 分支条件暂不支持字段访问(解析器文法限制;prove 侧已就绪,放开即生效)。 diff --git a/doc/roadmap/prove.md b/doc/roadmap/prove.md deleted file mode 100755 index 929f17a..0000000 --- a/doc/roadmap/prove.md +++ /dev/null @@ -1,409 +0,0 @@ -# `marqdo prove` 实施路线(P0–P3) - -| | | -|---|---| -| 状态 | **已实施(P0–P3 落地,2.8.0)**——落地记录:[design/prove-cli.md §12](../design/prove-cli.md);foreach / 跨模块 assume-guarantee / 假设表 T3 显式延期 2.9 | -| 日期 | 2026-11-13 | -| 设计 | [design/prove-cli.md](../design/prove-cli.md)(命令面、离线片段、定理表、语言习惯审查) | -| 决策 | [ADR 0010](../adr/0010-skill-proof-boundary.md)(定理表角色、子集边界、顾问式定位) | -| 目标版本 | CLI 2.8.0(已发) | -| 总工期 | 6.5 人周(单人;P0+P1 共 3 周可演示) | - ---- - -## 0. 完成定义 - -| 阶段 | 完成定义(DoD) | -|---|---| -| P0 | `prove emit` / `prove audit` 可跑;确定性生成;12 个夹具的降级结论稳定;`cargo test --test prove` 在**没有 Lean** 的机器上全绿 | -| P1 | 定理表落地;有 Lean 时 `proved`,无 Lean 时至少 `unverified`;证书与源码映射可用;CI 跑通「假定理必须红」 | -| P2 | 离线判定 `checked` 可用;语料库强制 `offline_checked ⊆ lean_proved`;反例可读;`--require-lean` 严格模式 | -| P3 | 跨函数组合、`--all`、差分一致性;文档/教程/技能手册齐;2.8.0 发布 | - -关键指标(P3 收口时复核): - -- 语料 **≥ 40** 个夹具,覆盖 8 类(§6)。 -- 控制平面类定理的**离线覆盖率 ≥ 60%**(其余 `unverified`,不算失败)。 -- 冷启动(50 函数文件)**< 30s**;证书命中 **< 50ms**。 -- **单调性分歧 0 例**(语料 + CI 每次运行)。 - ---- - -## 1. 为什么先 Lean、后离线 - -离线判定器需要一把"标尺":没有 Lean 作为判据,无法知道它会不会"过度自信"。所以顺序是: - -1. P0 先把降级与生成做确定(无判定,不会撒谎); -2. P1 接上 Lean,得到**权威判据**与失败证据格式; -3. P2 才写离线判定,并用 P1 的 Lean 结果做语料护栏(`offline ⊆ lean`)。 - -如果反过来,P2 的判定器会在没有标尺的情况下生长,最后很难证明它保守。 - ---- - -## 2. P0 · 骨架与确定性生成(1 周) - -### 任务 - -| 天 | 任务 | 产物 | -|---|---|---| -| D1 | `Commands::Prove` + `ProveAction::{Emit,Audit,Clean}`;`--json` 外壳;`src/prove/mod.rs` 状态机骨架 | `marqdo prove --help` 正确;未知参数报 clap 错误 | -| D2 | `ir.rs` + `lower.rs`:参数、赋值、返回、调用→`Op`、`if/else`;`while`/递归/动态调用的拒绝码 | 12 个夹具降级到 IR,`plan.json` 可读 | -| D3 | `types.rs`:从契约表起步的推断与合一;`proof.type_mismatch` 等错误码 | 类型错误夹具给出两处行号 | -| D4 | `emit.rs`:确定性 Lean 生成(稳定排序、无时间戳、相对路径)、中文名、`-- mq:` 注释 | 两次运行字节一致 | -| D5 | `report.rs` + `audit`:内联/不透明/跳过三类清单;快照测试;`tests/prove.rs` | `cargo test --test prove` 无 Lean 全绿 | - -### 验收 - -```bash -marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/lean -marqdo prove audit tests/prove/fixtures/approval.mq.md --json | jq '.functions[0].ops, .functions[0].rejected' -# 两次 emit 的 sha256 相同 -``` - -### 明确不做 - -判定、证书、Lean 调用、定理表。P0 的 `prove` 只有 `emit`/`audit` 两个子命令可用,默认命令直接转发到 `emit` 并提示"判定将在 P1 提供"。 - ---- - -## 3. P1 · 定理表 + Lean 判定(2 周) - -### 第 1 周:语言面与工具链 - -| 任务 | 产物 | -|---|---| -| ADR 0010 落定;`Function.claims`;定理表提取(首条可执行语句前,提取后移出 body) | 解析后 `claims` 非空,body 里没有该表 | -| `check --proof`(默认关):表形、名字、片段、遮蔽 | `check` 报 `proof.claim_malformed` / `proof.name_shadow` | -| `verification/skill-proof/`:`lean-toolchain`、`lakefile`、`Basic/Result/Tactic`、`LIBRARY-SHA256` 脚本 | `lake build` 通过 | -| `driver.rs`:工具链探测、Lake 包、`lake env lean`、超时、stderr 解析 | 手工跑通 approval 样例 | -| `cache.rs`:证书、`index.json`、失效 | 二次运行毫秒返回 | - -### 第 2 周:定理语义与失败证据 - -| 任务 | 产物 | -|---|---| -| 结论/前提求值:参数、`结果`、`轨迹`、三个谓词 | 定理编译通过 | -| 脚本生成:`intro` → `unfold run` → `split_ifs <;> simp_all <;> omega` | 正例 `proved` | -| 失败解析:`unsolved goals` → 目标 + 上下文 → 映射回 `.mq.md` 行 | 假定理给出源码行与残余目标 | -| `.github/workflows/proof.yml`:elan 钉版、`lake build`、跑 Lean 用例 | CI 绿;假定理用例必须红 | -| 文本/JSON/退出码对齐设计文档 | 状态表逐项手测 | - -### 验收 - -```bash -marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status # "proved" -marqdo prove tests/prove/fixtures/false-claim.mq.md; echo $? # 1 -PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status -# P1 阶段没有离线判定,因此是 "unverified";P2 起升级为 "checked" -``` - ---- - -## 4. P2 · 离线判定与单调性(2 周) - -### 第 1 周:符号执行与 F1–F4 - -- `offline.rs`:符号状态(`Const/Param/OpResult/Unknown`)、路径条件、轨迹。 -- 分支分叉与返回路径收集;`if` 条件求值到符号原子。 -- F2 轨迹求值(`包含/长度/下标`)、F3 字面结果、F4 命题组合。 -- 结论:`checked` / `unverified` 两态;证书写入情形列表。 - -### 第 2 周:F5 区间、反例、护栏 - -- F5:单变量 `x ⋈ c` 的区间传播与蕴含判定(保守;不可判定即 `unverified`)。 -- 反例:路径可满足 + 结论字面假 → 端点见证值。 -- 分歧护栏:`checked` 但 Lean 未关闭 → `error[proof.divergence]`(含测试专用注入开关,见 §6 A3)。 -- 假设表(T3):前置/后置 → 定理前提;`proof.assumption_untyped`。 -- 单调性脚本:对语料逐条比对离线与 Lean 的定理状态。 - -### 验收 - -```bash -# 无 Lean 也能给出离线结论 -PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status # "checked" -# 单调性:语料中不存在 checked 而 Lean unproved 的定理 -cargo test --test prove_lean # 需工具链 -``` - ---- - -## 5. P3 · 组合与产品化(1.5 周) - -| 任务 | 产物 | -|---|---| -| 跨函数内联 + assume-guarantee(调用者用被调者证书里的后置条件) | 多函数编排证明 | -| `foreach`(有限列表,fold 编码) | Q1 夹具 | -| `--all` 目录模式、聚合报告、`--max-files` | 仓库级报告 | -| 差分一致性(T4):`Conformance.lean` + 解释器期望值 | CI 比对 | -| `view` 徽标、`catalog` `proof:` 字段、MLSP `proof` 方法(可选) | 读侧可见 | -| 文档:README、教程、两个 skill 手册、CHANGELOG、2.8.0 | 发布 | -| 发版手册:推荐附证书(不强制) | 流程更新 | - -### 验收 - -```bash -marqdo prove --all skills/ --json | jq '.status, (.files|length)' -lake build # verification/skill-proof/examples 全部通过 -``` - ---- - -## 6. 测试矩阵(针对性) - -夹具目录 `tests/prove/fixtures/`,集成测试 `tests/prove.rs`;Lean 相关用 `tests/prove_lean.rs`(独立测试目标,不进默认 `cargo test`)。 - -### A · 单调性与诚实性(最高优先级) - -| ID | 夹具 / 操作 | 期望 | 守住什么 | -|---|---|---|---| -| A1 | `approval.mq.md`:`包含(轨迹,"人工审核")` | 离线 `checked`;Lean `proved` | 离线结论被 Lean 确认 | -| A2 | `false-claim.mq.md`:大额时断言 `结果.ok = False` | `unproved`,退出 1;P2 起附反例 `金额=10001` | 假定理不被放绿 | -| A3 | 同一夹具 + 测试注入 `--fault-inject offline-claim`(仅 debug 构建存在) | `error[proof.divergence]`,退出 1,JSON `status=="error"` | 分歧必须显式失败,不许静默以离线为准 | -| A4 | 多变量线性命题(`金额 + 手续费 > 10000`) | 离线 `unverified`;跑 Lean 后 `proved` 或 `unproved` | 片段保守,不越界断言 | -| A5 | 语料全量:`checked` 集合 ⊆ Lean `proved` 集合 | 集合包含成立,0 反例 | 长期单调性回归 | - -### B · 语义一致性(T4) - -| ID | 内容 | 期望 | -|---|---|---| -| B1 | 纯函数语料(算术、比较、布尔、字符串拼接、`access`、`len`) | 解释器输出 == Lean `example : f args = expected := by decide` | -| B2 | 除零、取模零 | 与运行时错误语义一致(生成 `mq_div`/`mq_mod` 返回 Result.failure) | -| B3 | 中文标识符 `计算器.加法`、含空格名 `多 步` | 生成 `«…»`,Lean 接受 | -| B4 | 映射/表字面量:字段顺序、`ok` 字段读取 | Lean 结构与 Marqdo 取值一致 | -| B5 | 负数、大整数(`i64` 边界) | 无溢出漂移;超界按契约拒绝 | - -### C · 不执行(安全) - -| ID | 夹具 | 期望 | -|---|---|---| -| C1 | 函数里调 `fs.write`、`fs.make_dirs` | `prove` 后目标路径不存在 | -| C2 | 函数里调 `print` | stdout **只有** `prove` 的报告;没有程序输出 | -| C3 | `--emit` 到只读目录 | 清晰 IO 错误,退出 1,不 panic | - -### D · 子集与拒绝 - -| ID | 夹具 | 期望 | -|---|---|---| -| D1 | `while` 循环 | `proof.while`,行号准确;整体 `rejected`,退出 0 | -| D2 | 自递归 + 互递归 | `proof.recursion`,列出环上函数名 | -| D3 | 插件/动态调用 | `proof.dynamic_call` | -| D4 | 未定型变量(strict) | `proof.type_mismatch`,两处行号 | -| D5 | 同上 + `--no-strict-types` | 落 `Val`,报告标"弱类型",不报错 | -| D6 | `--allow-opaque 预检` | 该函数列为不透明操作,调用者仍可证 | - -### E · 定理表 - -| ID | 夹具 | 期望 | -|---|---|---| -| E1 | 未知名字 `审批人.ok` | `proof.claim_unknown_symbol` + 最近建议 | -| E2 | 重复 id | `proof.claim_duplicate` | -| E3 | 参数名 `结果` 遮蔽保留名 | `proof.name_shadow` | -| E4 | `策略 none` | 定理生成、不证;状态 `unverified`,不是失败 | -| E5 | 非法策略片段 `策略 nonsense` | `proof.claim_failed` 带 Lean 原始错误,不 panic | -| E6 | 缺 `结论` 列 / 表在语句之后 | `proof.claim_malformed` / `proof.claim_misplaced`(`check --proof`) | -| E7 | 两列「定理 / 说明」普通表 | 不认领,`check --proof` 不报 | -| E8 | `假设` 表:`返回.ok = True` 用于分支判断 | Lean `proved`;证书 `assumptions` 有该条 | - -### F · CLI / JSON / 退出码 - -| ID | 操作 | 期望 | -|---|---|---| -| F1 | 各状态夹具 | 退出码 == 设计表(0/0/0/0/1/1) | -| F2 | `--report-only` on A2 | 退出 0,状态仍 `unproved` | -| F3 | `--require-lean` 且 `PATH` 无 lean | 退出 2,`status=="unverified"` | -| F4 | `--json` | 键集合与类型快照;`schema==1`;无绝对路径 | -| F5 | 目录不带 `--all` | `proof.need_all`,退出 1 | -| F6 | `prove clean` | `.marqdo/prove` 消失;`--emit` 目录保留 | - -### G · 缓存与确定性 - -| ID | 操作 | 期望 | -|---|---|---| -| G1 | 连续两次 `prove emit` | `module.lean`、`plan.json` 字节相同 | -| G2 | 假 `lean` 脚本写日志;连续两次 `prove` | 日志只有 1 行(第二次命中缓存) | -| G3 | 改源码一个字符 | 证书键变化,重新判定 | -| G4 | 改库文件(模拟 `LIBRARY-SHA256` 变化) | 缓存失效 | -| G5 | 手工损坏 `certificate.json` | `proof.cache_corrupt`;重算或退出 1,不读坏证书 | - -### H · 编码边角 - -| ID | 内容 | 期望 | -|---|---|---| -| H1 | 空 else、两臂都早返回 | 生成退化正确,Lean 通过 | -| H2 | 不可达分支(`1. False`) | `audit` 标 warning;不阻塞 | -| H3 | 字符串含引号/换行/中文 | 转义正确,Lean 字面量等值 | -| H4 | 0 参数、0 语句函数 | 生成 `def run := ...` 合法 | -| H5 | 参数默认值 | 与契约默认一致;Lean 用显式值代入 | - ---- - -### 关键夹具草稿(P0 落盘到 `tests/prove/fixtures/`) - -正例(轨迹命题,A1): - -```markdown -## 审批 -+ `金额` - -| 参数 | 类型 | 说明 | -|---|---|---| -| 金额 | int | 申请金额(元) | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result | - -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | - -1. `金额` > 10000 - **审核 = [提交人工审核](人工审核(金额=`金额`))** - **结果 = [保留人工审核结论](result.ok(value=`审核`))** -2. * - **结果 = [自动通过](result.ok(value="auto"))** - -**结果** -``` - -反例(A2):同构文件,只把定理换成 - -```markdown -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 不该自动放行 | 结果.ok = False | 金额 > 10000 | auto | -``` - -期望 `unproved`、退出 1;P2 起附反例 `金额 = 10001`。 - -不执行(C1): - -```markdown -## 落盘 -+ `path` - -**written = [真的写一个文件](fs.write_text(path=`path`, text="证明工具不该执行我"))** - -**written** -``` - -跑 `prove` 后指定路径必须不存在;`prove` 只做降级与生成。 - -拒绝(D1): - -```markdown -## 倒计时 -+ `n` - -- `n` > 0 - **n = n - 1** - -**n** -``` - -期望 `proof.while`,整体 `rejected`、退出 0(若没有别的未关闭定理)。 - -遮蔽(E3): - -```markdown -## 遮蔽 -+ `结果` - -| 定理 | 结论 | -|---|---| -| 读结果 | 结果.ok = True | -``` - -参数名与保留名冲突 → `proof.name_shadow`,要求改名,不做隐式优先。 - ---- - -## 7. 验收证据(可直接粘进 PR) - -```bash -# 1) 离线可用(把 PATH 收窄到没有 lean) -PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq -r .status -# checked - -# 2) 有 Lean 时升级为证明 -target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq -r .status -# proved - -# 3) 假定理必须红,且给出行号 -target/debug/marqdo prove tests/prove/fixtures/false-claim.mq.md; echo "exit=$?" -# error[proof.claim_failed] … --> false-claim.mq.md:31:3 -# exit=1 - -# 4) 单调性(语料) -cargo test --test prove_lean -- --nocapture -# offline_checked=37 lean_proved=37 divergences=0 - -# 5) 不执行 -rm -f /tmp/mq-prove-should-not-exist -target/debug/marqdo prove tests/prove/fixtures/side-effect.mq.md -test ! -e /tmp/mq-prove-should-not-exist && echo "no side effect" - -# 6) 确定性 -a=$(target/debug/marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/a && sha256sum /tmp/a/Generated/Approval.lean) -b=$(target/debug/marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/b && sha256sum /tmp/b/Generated/Approval.lean) -[ "${a%% *}" = "${b%% *}" ] && echo deterministic -``` - ---- - -## 8. CI 设计 - -```yaml -# .github/workflows/proof.yml(示意;action 版本以仓库既有 workflow 为准) -jobs: - corpus: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - name: Install elan (toolchain pinned by verification/skill-proof/lean-toolchain) - run: | - curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain none - echo "$HOME/.elan/bin" >> "$GITHUB_PATH" - - name: Build proof library (cache .lake) - working-directory: verification/skill-proof - run: lake build - - run: cargo build --locked - - run: cargo test --test prove --locked # 不需要 Lean 的部分 - - run: cargo test --test prove_lean --locked - env: { MARQDO_PROOF_REQUIRE_LEAN: "1" } - - run: bash scripts/check-proof-library.sh # LIBRARY-SHA256 与 BUILD-IDENTITY -``` - -原则: - -- `cargo test` **不依赖** Lean;Lean 用例在独立目标里,缺失工具链时打印 `SKIP: lean toolchain not found` 并在 `MARQDO_PROOF_REQUIRE_LEAN=1` 下转为失败。 -- 不使用 `#[ignore]` 作为成功证据(沿用 `executable-knowledge.yml` 的纪律)。 -- Lean 构建缓存 `.lake`,避免每次拉依赖。 - ---- - -## 9. 风险与回滚 - -| 风险 | 触发 | 应对 | -|---|---|---| -| Lean 工具链在 CI 不可用 | action 变更/网络 | 钉版本 + 缓存;`proof.yml` 失败只红该 job,不阻塞其它 | -| 离线判定"过度自信" | 片段实现 bug | 语料 A5 强制包含关系;运行期 A3 分歧即 error | -| 生成不确定 | HashMap 遍历顺序 | 全量 `BTreeMap`;两次 emit 字节比对进 CI | -| 定理表被误用成数据表 | 表头重名 | 只有表头+列形同时命中才认领;`check --proof` 可关 | -| 破坏既有 `check` 性能 | 提取逻辑 | `--proof` 默认关;提取只做一次线性扫描 | -| 范围蔓延(想把整个语言编译过去) | 需求诱惑 | ADR 0010 写死子集;新增构造需重新评审 | - -回滚:`prove` 是**纯增量**(新命令 + 新可选表角色);删除命令与 `Function.claims` 字段即可回到现状,已有 `.mq.md` 不受影响(定理表在无 `prove` 的旧版本里只是普通表格)。 - ---- - -## 10. 不做清单(本版本) - -- `while`、递归、动态派发的形式化(拒绝而非近似)。 -- 字符串/JSON/浮点/公式库的语义建模。 -- 自动修复不成立的定理。 -- 证明缓存的服务端共享。 -- IDE 内联证明状态(先走 `view` 徽标)。 -- 强制门禁:任何"必须 proved 才能发布"的默认行为。 diff --git a/doc/roadmap/qdagent-knowledge-support-gaps-2026-10-24.md b/doc/roadmap/qdagent-knowledge-support-gaps-2026-10-24.md deleted file mode 100755 index c323aa5..0000000 --- a/doc/roadmap/qdagent-knowledge-support-gaps-2026-10-24.md +++ /dev/null @@ -1,250 +0,0 @@ -# Marqdo 支撑求道知识沉淀与文档编译的框架缺口 - -| 项目 | 基线 | -|---|---| -| 日期 | 2026-10-24 | -| 框架源码 | `b8a4ddd`,Cargo 声明 2.1.1 | -| 消费者源码 | 工作区 qdagent,`7f8f19d` | -| 文档性质 | 当前源码复核、实测反例和增量建议;不重开已完成的 S0–S6 工作 | -| 配套文档 | [求道产品侧缺口](../../../qdagent/doc/gaps/03-knowledge-ingestion-and-sedimentation-2026-10-24.md) | -| 设计依据 | [文档原生开发指导](../design/document-native-development-guide.md)、[既有缺口路线](executable-knowledge-gaps-2026-10-23.md) | - -## 1. 核心判断 - -Marqdo 已具备让求道采用文档原生知识的主要语言和执行基础。求道尚未接入的能力,不能统称为“框架不支持”。本轮框架侧优先工作是:**让生成知识的语言指导可信,让来源和验证真正约束发布与复用,让新语义制品进入默认 Agent 链路,并提供文档导入所需的通用适配接口。** - -`knowledge` 编译的是已有源码和声明,不是把任意 PDF/DOCX 自动变成正确知识的转换器。上传、抽取、模型建模、语义编译、验证、发布是不同阶段。语义编译器保证程序和依赖的确定性;来源支撑、业务适用性以及领域审阅需要明确证据,不能由成功退出或 LLM 自述推导。 - -现有 [2026-10-23 路线](executable-knowledge-gaps-2026-10-23.md)的审计基线较早,之后已有多次实现提交。本文件按当前源码重新划分:已实现、有限子集、仍有断点;不照抄旧文档中的“无正文引用”“未知效应全为 pure”“两图互相覆盖”等历史判断。 - -## 2. 当前可直接复用的能力 - -| 能力 | 当前证据 | 给求道的边界说明 | -|---|---|---| -| 默认 Occlusion、`access`、显式遍历 | [核心表面](../design/core-surface.md)、[基线 01–04](../../tests/executable_knowledge/README.md) | 求道须迁移旧取元;无需增加新语法 | -| 函数、契约、表格、import、关联函数 | `src/parse/`、[check.rs](../../src/check.rs)、[sema/bind.rs](../../src/sema/bind.rs) | 支持编写可复用知识;不是所有知识都要塞进 main 或建类 | -| 项目身份、语义制品、绑定调用 | [project](../../src/project/mod.rs)、[symbols](../../src/sema/symbols.rs)、[IR](../../src/sema/ir.rs) | 已有 SymbolId/ArtifactId、BoundCall/DynamicCall;消费方不另造执行身份 | -| 语义图与检索图隔离 | [knowledge/compile.rs](../../src/knowledge/compile.rs) | 权威语义 `graph/` 与检索 `ekc/graph/` 已分开,旧覆盖问题不再作为未实现项 | -| 知识步骤、正文引用、view | `collect_named_steps`、NarrativeRef、现有集成测试 | 已含 observe/derive/iterate/call/narrate/navigation 子集;正文引用保持惰性 | -| 来源与适用期初版 | [provenance.rs](../../src/sema/provenance.rs) | 已解析 `sources` block list、region、valid_until;sourced 不等于事实已经验证 | -| 精确绑定与本地执行 | [mlsp.rs](../../src/mlsp.rs) 的 artifact.find/inspect/bind/execute | 已有摘要及 SymbolId 检查、按源行定位函数、pure 效应门槛;剩余失效问题见 M02/M03 | -| 局部修改 | MLSP artifact.patch / artifact.extract_pure | 已有摘要保护、措辞修改守卫、纯片段提取;不应要求模型每次重写整库 | -| 整代语义投影、锁、影响 | `write_semantic_projections`、[lock.rs](../../src/sema/lock.rs) | 已有 generations/CURRENT 与多类摘要;覆盖边界及实测失败见 M02/M06 | -| Agent 工作簿、技能、沙箱 | [ext/ai/agent](../../ext/ai/agent.mq.md)、[plugins/agent](../../plugins/agent/src/lib.rs) | 可复用 Runtime、CoW、工具协议和诊断修复;求道不另建 Agent loop | -| 文件上传/存储 | [storage.mq.md](../../ext/data/storage.mq.md)、[routes_media.go](../../plugins/web/internal/httpx/routes_media.go) | 已有上传路由、类型/大小验证和保存;不等于文档知识转换已存在 | - -本轮离线执行 `cargo test --offline --locked --test executable_knowledge`:**25 passed / 1 failed / 0 ignored**。通过项包括双后端基线、绑定复用、正文引用、来源状态、局部补丁、100 单元和 CLI 冒烟。失败项为 `s5_closure_digest_moves_with_dependency`,单独重跑仍失败。存在大量有效基础,也存在需要先处理的失效缺口。 - -## 3. 框架缺口与可验收交付 - -### M01 · P1:上传底座尚未形成文档提取与来源映射协议 - -**现状。** Web 插件已注册 `web_upload_validate/save/app_upload`,`handleUpload` 接收 multipart 并存储字节。本轮在 `src/`、`plugins/`、`ext/` 的搜索未找到可供求道直接调用的 PDF/DOCX/OCR → 标准化正文 → 页段来源映射的完整链路。不要把 HTTP 文件保存或 `knowledge compile` 命令包装成已有文档转换器。 - -**建议。** 在扩展/插件层定义通用 `DocumentSource → ExtractedDocument` 协议,字段至少包括原件 URI/摘要、格式、提取器版本、段落/表格/页码定位、可提取文本、缺失部分、置信度及诊断。先支持 text/Markdown;PDF/DOCX/OCR 可通过独立插件或受控外部提取器接入。格式解析留在扩展,语言核心不引入 OCR 或模型业务。 - -知识生成由求道选模式、检索既有知识、调用模型并提供 patch;框架提供 compile/diagnostics/sandbox,而不是默默替作者推断领域真相。转换的外部程序必须服从宿主权限和资源边界。 - -**现有上传实现需补强的具体点。** `handleUpload` 先 `ParseMultipartForm(32 << 20)`、`io.ReadAll`,再按完整字节数做 Validate;32 MiB 是 multipart 内存阈值,不是请求总量硬限。应在解析/读取前限制请求与文件字节数,采用受限流式读取,并测试清理临时文件与失败路径。已有类型/路径验证应复用,不能将此描述为“没有任何上传校验”。 - -**验收。** 对文本、表格、跨页、坏编码、空文档、密码 PDF、扫描件、超限文件分别返回成功/部分/失败;每条抽取事实都可定位回原件;上传 `.mq.md` 不自动执行;相同文件及提取器版本输出可比较,重试不产生不同身份。 - -**责任。** Marqdo 提供提取与存储适配规范;求道负责上传界面、任务进度、知识库选择、发布政策与业务模型。 - -### M02 · P0:来源与依赖变化未完整进入摘要、锁与执行失效 - -**来源反例(实测)。** 2.1.1 下给函数声明 `sources: source.md#missing-anchor`,实际文件存在但锚点不存在,仍得 `evidence=sourced`;business bind 成功。修改 source.md 后 SourceRef.content_digest 变化,artifact.hashes.artifact 不变;旧 handle 继续执行。删除 source.md 后,旧 business handle 仍执行并返回原值。 - -**源码原因与边界。** [provenance.resolve_provenance](../../src/sema/provenance.rs)将 `#anchor` 存为 locator,但没有校验锚点;对来源文件计算哈希后,[IR artifact_for_function](../../src/sema/ir.rs)仍用 `digest(contract_summary(&contract))` 构造 evidence 摘要,没有包含来源内容和适用条件。`artifact.execute` 重编译并比较自身 artifact 摘要,但不重验 handle.policy 对应的证据状态。来源改变、来源删除、时间到期可以不改变函数实现,因此自身摘要检查不足。 - -**依赖反例(实测)。** [现有集成测试](../../tests/executable_knowledge.rs) `s5_closure_digest_moves_with_dependency` 中 `main` 调用 `d.rate()`,仅将被依赖函数返回值从 0.13 改为 0.14;测试读取到的 main closure 摘要未变。已重复验证。这里只确认该夹具失败:需要区分符号/模块同名选择、依赖边和闭包算法各自责任,不据此直接断言所有函数闭包都失效。 - -**其他源码缺口。** bind/execute 传递的是自身 `hashes.artifact`,没有把已有 `hashes.closure` 纳入句柄复核。`lock.impact` 从制品定义文件和依赖/正文边找反向影响,未把 `provenance` 的外部 corpus URI 纳入来源反向边。 - -**交付。** - -1. evidence 摘要包含规范化来源 URI、定位、内容摘要、提取器/验证版本及适用性;锚点不存在返回不同于文件缺失的诊断。读取错误不能以空文件摘要冒充成功。 -2. 修复上述闭包失败,并明确 type/module/function 的身份与测试选择。依赖递归/环用确定的 SCC 或等价闭包摘要规则;无关文件增删不应导致任意漂移。 -3. 句柄记录并复核所需的依赖闭包、证据、政策及有效期;execute 重验 business/pure 等政策,不只相信 bind 时的状态。文件变化与时间变化都能使句柄失效。 -4. 将 corpus → artifact → caller/answer 的影响关系纳入同一编译结果,来源改动能查询受影响对象;报告接口、实现、证据、依赖分别发生了什么变化。 - -**验收。** 仅修改来源、删来源、改锚点、时间越过有效期、改直接/传递依赖都拒绝不再有效的句柄;原有测试恢复通过。不得为让测试变绿删除断言或改成只检查命令成功。普通无业务来源要求的纯函数仍可按相应政策执行。 - -### M03 · P0:验证 API 尚不是可发布知识的完整判据 - -**现状。** `VerificationRecord` 已分 parse/resolve/contract/execution/tests/evidence/domain,但 `semantic_artifact` 的默认值仍包括 `contract=unchecked`、`execution=not_run`、`tests=unknown`、`domain=unreviewed`、`lifecycle=draft`。MLSP `artifact.verify` 主要返回编译记录并附 policy,没有实际执行对应测试或回写证据。不能把它宣传为已经验证业务事实。 - -`artifact.bind(policy=business)` 接受 sourced/verified,尚未检查 region 与本次输入、单位、前提、输入域等;`provenance` 用日期字符串比较有效期,没有完整日期格式校验。当前“business”至多表示来源已关联且未被判过期,不等于适用性或事实成立。unknown policy 字符串也未通过枚举校验形成明确拒绝。 - -`knowledge verify` 检查的是旧 EKC 结构一致性;`conflicts/stale` 是报告命令,`duplicate` 的默认行为也是报告。它们都有价值,但消费方不能从退出码 0 得出“候选可晋升”。求道正存在这种误用。 - -**交付。** 给调用方稳定的验证结果结构:验证对象/摘要、所选政策、每个检查的 passed/failed/unknown/skipped、证据记录、阻断原因、是否允许绑定或发布。测试运行器生成执行/断言事实;来源存在、引文一致、计算正确、领域结论分别报告。政策和结果字段应有版本化 schema,未知政策拒绝。 - -保留报告命令兼容性,提供清晰的机器裁决入口或明确 fail 选项;不要悄悄改变已有 CLI 的退出语义。发布政策可渐进:纯工具先证明程序行为,业务事实额外要求来源与适用条件,领域审阅按场景要求;不为所有函数强加人工审批。 - -**验收。** `sandbox failed`、模型声称“passed”、空证据、无效日期、地区不符、输入越界、测试未运行均不能被标成对应级别的 verified;缺证据与执行失败不同;实际通过的记录绑定内容摘要,修改后自动失效。 - -### M04 · P1:新语义复用协议尚未进入默认 Agent 学习与执行闭环 - -**现状。** [plugins/agent/eng.rs](../../plugins/agent/src/eng.rs) 的 `eng_reuse`、[knowledge/reuse.rs](../../src/knowledge/reuse.rs) 已输出 `discovery_only`、`bind_required`、`bind_targets`。这是真实进展,不再列为完全缺失。 - -但 [ext/ai/agent.mq.md](../../ext/ai/agent.mq.md) 的默认 `run` 仍以 route/resolve、agent-kb workbook、plan 为主;EFI 分支主要检查 create_allowed,未在该编排中找到 artifact.bind/execute 的完整消费。`run verify=True` 依据 `status==ok` 拼接 `verification="status: passed"`;随后可 maybe_learn/promote,并非调用 M03 所需的验证器。求道 BUILD 开启 `learn=True/promote=True` 后才做自己的 docgate,因此两层发布时序有冲突风险。 - -`build_step_context` 的 CALL 白名单只有名字协议;parent CALL 支持 ARGS 的能力与 step 工具路径不同。求道若要调用精确制品与输入,需要正式适配,不能在提示词中虚构已可调用的工具。 - -**交付。** 提供现有 Runtime 内的适配步骤:discover → inspect → bind → execute → record。执行工具使用宿主选择的 project/KB/policy,LLM 只提交候选及输入。REUSE 只有在绑定执行成功且有 trace 后计为实际复用;ADAPT 用现有 patch/extract 形成可审阅修改;CREATE 保留检索范围与原因。 - -提供产品可接入的发布前验证钩子或 candidate-only 模式:产品门禁失败时框架也不能先把技能标为可复用。知识文件、技能、episode 可以保留不同存储职责,但都关联同一版本化 artifact/evidence;不要新增另一套知识语义。 - -**验收。** 用真实 `agent.run` 编排和确定性假模型/工具响应验证,而不只直调 MLSP:已有知识被调用、无同义实现新增;错误来源/错输入被拒绝;验证失败无 promote;trace 对应符号、摘要、输入与输出。不得将 n-gram 高分或字符串 REUSE 当作成功。 - -### M05 · P0/P1:提供给模型的语言 Skill 与当前语法冲突 - -**源码事实。** [skills/marqdo/SKILL.md](../../skills/marqdo/SKILL.md) 前部 Hard rules 2/4 和 v0.2 表仍写“粗体是返回”、斜体是语句,旧 `[key](map)` 取元也仍在前部。后面虽有 v2.1 默认 Occlusion 段落,不能消除同一提示包的冲突。 - -[host/agent_rt.rs](../../src/host/agent_rt.rs) 的 `load_marqdo_skill/read_skill_pack` 加载 Skill/reference/examples;[agent.skill_brief](../../ext/ai/agent.mq.md) 默认只取前 1200 字符/80 行,deep 预算 4000 字符。因此旧规则可能优先进入窗口,新的说明反而被截掉。实际读取哪个包受 MARQDO_SKILL 和搜索路径影响,部署须记录真实来源,不能假定总在读工作区文件。 - -**交付。** 从现行核心表面、解析器与金样例维护一份版本化语法卡片,最前面即当前含义:`**…**` 代码、`*…*` 返回、`[描述](payload)`、`access`、显式 import/遍历、正文惰性。旧语法迁入独立迁移卡片,不继续与默认规则并列。模型可按需取契约、来源、表格、类/函数等卡片;语言核心规则和权限边界不可被预算截掉。 - -使用已有 MLSP syntax/schema/validate/repair 能力,但明确 validate 的范围:当前主要是契约/标签检查,不等于完整事实、所有变量/调用和业务验证。诊断附 span、相关源码、目标语法版本及建议修复范围;优先局部 patch,避免整篇重生成。 - -**验收。** `dump_step_context` 和 plan 上下文的脱敏快照中没有冲突规则;基础/deep 预算均保留必需语法。卡片中可执行示例在当前 CLI 双后端通过;同一批含旧取元、错误返回、表格几何误用、缺 import 的负例给明确诊断。记录实际 skill path/hash、CLI/Ext/schema/prompt 版本。 - -### M06 · P1:整代发布已存在,但扫描范围与消费者一致性仍需约束 - -**现状。** [IR](../../src/sema/ir.rs)已将语义投影写 generations,再原子替换 CURRENT;遵循 `semantic_generation_dir` 的读者可获得完整语义代。但随后还写根目录兼容镜像,[knowledge.compile](../../src/knowledge/compile.rs)另写 engineering.yaml / ekc 等检索投影;不能把语义代原子性推广为“所有消费者、所有索引都属于同一代”。并发构建共用 CURRENT.tmp、.tmp-sema-publish,需明确串行化或独占发布规则。 - -[project 扫描器](../../src/project/mod.rs)与 [EKC extract](../../src/knowledge/extract.rs)的排除集不同,后者遍历子目录时排除 data/docker,前者不排除 data。求道有多个原文、候选和运行目录,导入 `.mq.md` 后可能在不同消费者里出现不同可见性。已有 .marqdo 排除、深度/文件大小/数量限制值得保留,但尚不能替代显式源范围和信任范围。 - -**交付。** 项目配置声明 authored sources、corpus、draft/generated 的范围;语义、EKC、Agent/view 使用同一选择规则。发布 manifest 关联语义代、检索代、源码/证据摘要和 schema;消费者拒绝混代并能回退到旧完整代。多库使用独立项目身份,索引聚合不扩大执行文件范围。 - -**验收。** 暂存上传代码不会进入活动能力;data/ 路径不会因消费者不同而忽隐忽现;并发编译/失败注入期间读者只看到一套可用版本;旧索引可重建,源文档不受损。迁移期明确旧 graph 路径兼容期限。 - -### M07 · P1:来源粒度和知识类型不足以覆盖文档沉淀 - -**现状。** 来源主要来自模块 frontmatter,容易将一整篇资料附给该文件所有函数;SourceRef 有 uri/locator/digest,但缺少标准的“具体断言 → 原文片段/表格单元/页码 → 提取版本”关联。普通 EKC `KnowledgeKind` 有 Fact/Decision/Constraint 等,而语义 artifact 主要是 module/type/function;旧 `.md` Fact 的存在不等于可调用事实函数。作者写来源 inline list 时当前解析器会忽略,未知字段也缺少强诊断。 - -**交付。** 用现有 Markdown/frontmatter/契约表定义轻量知识约定,而不增加求道专属语法:可选的函数/断言级来源、适用范围、单位、负例、冲突/取代关系。明确知识内容类型与运行时类型的区别;事实可以是返回值、规则可以是函数、决策可以是声明性文档,类只用于真实模式复用。 - -由编译器生成身份、图边和 SourceRef,作者只维护实际内容与必要来源。为 plain note → draft fact/rule → verified callable 提供金样例和机器可读投影,不能仅把文本包在一个 print 中。字段不支持或位置错误时给诊断,避免“写了来源,编译却无声忽略”。 - -**验收。** 一文多来源、一事实多来源、原文冲突、缺失字段、单位不同、来源片段变化、声明性决策和可执行规则都能区分;无依据的信息保持 unknown;不要求每个纯工具函数带业务来源。 - -### M08 · P1/P2:生成式知识验收与真实复用评估不足 - -**现状。** 既有 26 项集成测试和 100 单元是有效基础,但不覆盖资料导入/模型沉淀全过程。现有 `eng_reuse` 协议测试证明 JSON 字段,不证明默认 Agent 调用了句柄;MLSP 直调测试证明本地纯函数复用,不证明模型按正确来源建库。测试 README、旧路线和示例中存在历史状态残留;此次 closure 测试失败也说明“done”必须和当前门禁分开。 - -**交付。** 两层评测:确定性 fixtures 验证协议和失败边界,固定任务集验证模型沉淀质量。每个样本保存原文、期望知识、可执行断言、来源定位、错误复用反例、实际上下文及版本;明确事实正确率与程序运行率不同。性能指标包括编译/检索延迟、上下文规模、修复轮次、真实 token、知识重复率和误晋升率。 - -**验收。** 用同一资料完成“首次建库→再次调用→原文更新→旧知识失效→修复发布”的完整故事;包括断网/缺插件/截断/OCR 错误/资料内指令/冲突来源。只统计有目标与结果 trace 的执行复用,不按 REUSE 决策估算零推理成本。核心发布门禁不能以 skip 计成功。 - -## 4. 建议的跨库接口边界 - -下表是待实现或待稳定的契约,不暗示现在已有同名函数/CLI。 - -| 契约 | Marqdo 保证 | 求道负责 | -|---|---|---| -| Document extraction | 原件摘要、标准正文、定位、诊断;扩展层实现格式转换 | 上传、任务、库范围、用户预览 | -| Knowledge draft | 当前语法卡片、检查/修复、可调用元数据 | 事实/规则选择、提示词、冲突与去重决策 | -| Verification report | 每个检查的真实状态、证据/制品摘要、阻断原因 | 项目政策、需要人工处理的歧义、发布编排 | -| Artifact handle | 唯一身份、依赖/证据失效、宿主能力边界 | 提交候选与输入、记录实际使用和解释 | -| Publish manifest | 一致的语义/索引代及可回滚读取 | 知识源码发布、迁移、当前活动版本 | -| Trace | 实际目标、输入、输出、版本与执行结果 | 回答来源展示、知识质量指标、运行记录关联 | - -现有 `artifact.*`、sandbox、knowledge 等接口优先扩展;新增 façade 必须复用它们。工具协议、输出 schema 与提示词版本一起管理。首次本地试点可以使用固定目录与已授权项目政策;远程多租户的身份、凭据和隔离单独验收,不能把本地 MLSP 直接当公网授权协议。 - -## 5. 实施顺序 - -| 阶段 | 工作 | 完成条件 | -|---|---|---| -| F0 正确性基线 | M02/M03/M05:闭包反例、证据失效、验证状态、语法卡片 | 现有测试全过;来源变更/删除拒绝旧 business handle;提示词不含冲突语法 | -| F1 最小生产消费链 | M04 + 求道文本导入:candidate-only、验证钩子、绑定执行 trace | 同一资料第一次生成,第二次实际复用,门禁失败不学习发布 | -| F2 来源与更新 | M06/M07:统一源范围、来源定位/影响、发布 manifest | 改原文能找全受影响对象,发布失败旧版本仍可用 | -| F3 格式覆盖与评测 | M01/M08:PDF/DOCX/OCR 适配、资源限制、模型对照 | 文档可追溯,不完整提取显式报告,效果和失败分布有数据 | - -框架不承担求道的登录界面、笔记列表、项目业务政策;求道不复制框架的 parser、binder、effect、lock 或执行器。无需为了这条主链先完成万能本体、全格式解析或远程授权平台。 - -## 6. 本轮可复核实验 - -### 6.1 当前门禁与失败复核 - -在框架仓库执行: - -```bash -cargo test --offline --locked --test executable_knowledge -cargo test --offline --locked --test executable_knowledge \ - s5_closure_digest_moves_with_dependency -- --exact -``` - -第一条结果为 25 passed、1 failed;第二条仍在 `tests/executable_knowledge.rs:586` 报 `caller closure digest must move with dependency`。两次比较结果相同。这是既有测试的执行结果;本次未修改其实现或断言。 - -审计开始时 `target/release/marqdo --version` 与旧 debug 都是 2.1.0;上述构建生成的 debug 是 2.1.1。后续最小实验使用新 debug,不能把旧 release 输出充当当前源码能力证据。 - -### 6.2 来源变化与旧句柄复现 - -以下程序仅在新建临时目录写测试文件,通过本地 MLSP 调用,不联网、不调用模型。构建当前 debug 后在仓库根运行: - -```python -import json -import subprocess -import tempfile -from pathlib import Path - -binary = str(Path("target/debug/marqdo").resolve()) -root = Path(tempfile.mkdtemp(prefix="mq-source-audit-")) - -def rpc(method, **params): - req = json.dumps({"method": method, "params": params}) + "\n" - proc = subprocess.run([binary, "mlsp"], input=req, text=True, - capture_output=True, check=True) - return json.loads(proc.stdout) - -(root / "source.md").write_text("# rate\n\nrate = 0.13\n") -(root / "facts.mq.md").write_text( - "---\nsources:\n - source.md#missing-anchor\n" - "applicability:\n region: CN\n valid_until: 2099-12-31\n" - "---\n\n## rate\n\n*0.13*\n" -) -first = rpc("artifact.inspect", project=str(root), artifact_id="rate")["result"] -handle = rpc("artifact.bind", project=str(root), artifact_id="rate", - policy="business")["result"]["handle"] -(root / "source.md").write_text("# rate\n\nrate = 0.14\n") -second = rpc("artifact.inspect", project=str(root), artifact_id="rate")["result"] -print("evidence:", first["verification"]["evidence"]) -print("source changed:", first["provenance"][-1]["content_digest"] != - second["provenance"][-1]["content_digest"]) -print("artifact changed:", first["hashes"]["artifact"] != - second["hashes"]["artifact"]) -print("after edit:", rpc("artifact.execute", handle=handle, inputs={})) -(root / "source.md").unlink() -print("after removal:", rpc("artifact.execute", handle=handle, inputs={})) -``` - -本轮观察:`evidence=sourced`、`source changed=True`、`artifact changed=False`;两次 execute 均 `ok=true`、result 为 `0.13`。正确修复后,缺锚点应先阻断相应来源政策;用有效锚点重新绑定后,改/删来源也应拒绝旧句柄或要求重验。不能只修复示例中的缺锚点而遗漏来源内容失效。 - -### 6.3 求道旧取元风险 - -以下代码在默认 2.1.1 中,第一行输出整个 map,第二行输出 False: - -```markdown -# main - -`m` = - -| ok | status | -|---|---| -| False | denied | - -**old = [ok](m)** -**new = access(m, "ok")** -> print text=`old` -> print text=`new` -``` - -这是默认语义变化,不是框架需要回退的新语法错误。求道需迁移;框架应提供一致的迁移指导、诊断和版本信息,而不是在 Skill 中继续教授冲突的旧默认。 - -## 7. 审计限制与后续文档同步 - -本次验证是源码审查、仓库固定测试和临时输入实验;没有执行真实 LLM 的建库质量评估,没有测试线上 Web 上传或真实 PDF/OCR。M01 的“缺少转换链”限定在所审查的主代码区域,不否定外部工具可以接入。M02 的闭包根因仍需按身份、依赖图、摘要计算分层定位。 - -完成后应同步当前 Skill、README、测试 README 和路线进度:分别标记语言能力、协议子集、产品已接入、当前测试结果。优先把失败样例转成稳定回归门禁,再扩大“可验证知识”“业务复用”“上传编译”的能力声明。此次文档提交不表示缺口已修复。 diff --git a/doc/roadmap/repair-experiment-2026-09-22-mimo-v2.6-flash.md b/doc/roadmap/repair-experiment-2026-09-22-mimo-v2.6-flash.md deleted file mode 100755 index 7548ff0..0000000 --- a/doc/roadmap/repair-experiment-2026-09-22-mimo-v2.6-flash.md +++ /dev/null @@ -1,64 +0,0 @@ -# 修复实验(§5.2(a) 锚点消融)—— 2026-09-22 - -| | | -|---|---| -| 模型 | `mimo-v2.6-flash` @ `https://llm.cflmy.cn/v1` | -| 样本 | golden 20 例(易锚定错误) | -| 协议 | `validate` → `repair_targets` → 模型行编辑 → `repair_apply`(越界必拒/abstain)→ 复验;≤2 轮 | -| 对照 | `anchor` = 诊断带 `doc_anchor`/`doc_quote`/`suggestion`;`plain` = 全部剥掉 | - -## 汇总(设计目标:一轮修复率 ≥ 80%) - -| 臂 | 一轮修复率 | 最终修复率(≤2轮) | 平均尝试 | 越界拒(护栏) | 弃权 | -|---|---|---|---|---|---| -| anchor | 20/20(100%) | 20/20(100%) | 1.00 | 0 | 0 | -| plain | 18/20(90%) | 19/20(95%) | 1.05 | 0 | 1 | - -## 逐例 - -| 例 | 臂 | 结果 | 轮次 | 越界拒 | 备注 | -|---|---|---|---|---|---| -| arg-num-a | anchor | 一轮修复 | 1 | 0 | | -| arg-num-a | plain | 一轮修复 | 1 | 0 | | -| arg-num-b | anchor | 一轮修复 | 1 | 0 | | -| arg-num-b | plain | 一轮修复 | 1 | 0 | | -| arg-text-a | anchor | 一轮修复 | 1 | 0 | | -| arg-text-a | plain | 一轮修复 | 1 | 0 | | -| arg-text-b | anchor | 一轮修复 | 1 | 0 | | -| arg-text-b | plain | 一轮修复 | 1 | 0 | | -| drift-cover-a | anchor | 一轮修复 | 1 | 0 | | -| drift-cover-a | plain | 一轮修复 | 1 | 0 | | -| drift-cover-b | anchor | 一轮修复 | 1 | 0 | | -| drift-cover-b | plain | 一轮修复 | 1 | 0 | | -| drift-rename-a | anchor | 一轮修复 | 1 | 0 | | -| drift-rename-a | plain | 一轮修复 | 1 | 0 | | -| drift-rename-b | anchor | 一轮修复 | 1 | 0 | | -| drift-rename-b | plain | 一轮修复 | 1 | 0 | | -| dup-delete-a | anchor | 一轮修复 | 1 | 0 | | -| dup-delete-a | plain | 一轮修复 | 1 | 0 | | -| dup-delete-b | anchor | 一轮修复 | 1 | 0 | | -| dup-delete-b | plain | 一轮修复 | 1 | 0 | | -| field-nullable-a | anchor | 一轮修复 | 1 | 0 | | -| field-nullable-a | plain | 一轮修复 | 1 | 0 | | -| field-nullable-b | anchor | 一轮修复 | 1 | 0 | | -| field-nullable-b | plain | 一轮修复 | 1 | 0 | | -| field-type-a | anchor | 一轮修复 | 1 | 0 | | -| field-type-a | plain | 一轮修复 | 1 | 0 | | -| field-type-b | anchor | 一轮修复 | 1 | 0 | | -| field-type-b | plain | 一轮修复 | 1 | 0 | | -| key-fix-a | anchor | 一轮修复 | 1 | 0 | | -| key-fix-a | plain | 未修复 | 1 | 0 | 模型弃权/输出不可解析: [{"op":"replace","line":13","text":"*`用户`[^name]*"}] | -| key-fix-b | anchor | 一轮修复 | 1 | 0 | | -| key-fix-b | plain | 二轮修复 | 2 | 0 | 修复后仍有诊断: {"code":"marqdo.error","contract_ref":null,"doc_anchor":null,"doc_quote":null,"message":"missing map key `phone`","severity":"error","span":{"col":1,"file":"/tmp/marqdo_repair_1666049_plain_key-fix-b.mq.md","line":14},"suggestion":null} | -| ret-type-a | anchor | 一轮修复 | 1 | 0 | | -| ret-type-a | plain | 一轮修复 | 1 | 0 | | -| ret-type-b | anchor | 一轮修复 | 1 | 0 | | -| ret-type-b | plain | 一轮修复 | 1 | 0 | | -| type-typo-a | anchor | 一轮修复 | 1 | 0 | | -| type-typo-a | plain | 一轮修复 | 1 | 0 | | -| type-typo-b | anchor | 一轮修复 | 1 | 0 | | -| type-typo-b | plain | 一轮修复 | 1 | 0 | | - -## 护栏核对 - -- 每次越界编辑都以 `mlsp.repair_out_of_scope` + `abstain` 被拒,且 `repair_apply` 全有或全无(源零字节不改)——由 `tests/repair_loop.rs` 的确定性断言覆盖;本实验计数仅作记录。 diff --git a/doc/roadmap/repair-experiment-2026-09-22.md b/doc/roadmap/repair-experiment-2026-09-22.md deleted file mode 100755 index 1f5bf1f..0000000 --- a/doc/roadmap/repair-experiment-2026-09-22.md +++ /dev/null @@ -1,64 +0,0 @@ -# 修复实验(§5.2(a) 锚点消融)—— 2026-09-22 - -| | | -|---|---| -| 模型 | `cflmy` @ `https://llm.cflmy.cn/v1` | -| 样本 | golden 20 例(易锚定错误) | -| 协议 | `validate` → `repair_targets` → 模型行编辑 → `repair_apply`(越界必拒/abstain)→ 复验;≤2 轮 | -| 对照 | `anchor` = 诊断带 `doc_anchor`/`doc_quote`/`suggestion`;`plain` = 全部剥掉 | - -## 汇总(设计目标:一轮修复率 ≥ 80%) - -| 臂 | 一轮修复率 | 最终修复率(≤2轮) | 平均尝试 | 越界拒(护栏) | 弃权 | -|---|---|---|---|---|---| -| anchor | 20/20(100%) | 20/20(100%) | 1.00 | 0 | 0 | -| plain | 17/20(85%) | 17/20(85%) | 0.85 | 0 | 0 | - -## 逐例 - -| 例 | 臂 | 结果 | 轮次 | 越界拒 | 备注 | -|---|---|---|---|---|---| -| arg-num-a | anchor | 一轮修复 | 1 | 0 | | -| arg-num-a | plain | 一轮修复 | 1 | 0 | | -| arg-num-b | anchor | 一轮修复 | 1 | 0 | | -| arg-num-b | plain | 一轮修复 | 1 | 0 | | -| arg-text-a | anchor | 一轮修复 | 1 | 0 | | -| arg-text-a | plain | 一轮修复 | 1 | 0 | | -| arg-text-b | anchor | 一轮修复 | 1 | 0 | | -| arg-text-b | plain | 一轮修复 | 1 | 0 | | -| drift-cover-a | anchor | 一轮修复 | 1 | 0 | | -| drift-cover-a | plain | 一轮修复 | 1 | 0 | | -| drift-cover-b | anchor | 一轮修复 | 1 | 0 | | -| drift-cover-b | plain | 一轮修复 | 1 | 0 | | -| drift-rename-a | anchor | 一轮修复 | 1 | 0 | | -| drift-rename-a | plain | 一轮修复 | 1 | 0 | | -| drift-rename-b | anchor | 一轮修复 | 1 | 0 | | -| drift-rename-b | plain | 一轮修复 | 1 | 0 | | -| dup-delete-a | anchor | 一轮修复 | 1 | 0 | | -| dup-delete-a | plain | 一轮修复 | 1 | 0 | | -| dup-delete-b | anchor | 一轮修复 | 1 | 0 | | -| dup-delete-b | plain | 一轮修复 | 1 | 0 | | -| field-nullable-a | anchor | 一轮修复 | 1 | 0 | | -| field-nullable-a | plain | 未修复 | 0 | 0 | LLM 调用失败(重试后): 非 JSON / 空体: | -| field-nullable-b | anchor | 一轮修复 | 1 | 0 | | -| field-nullable-b | plain | 未修复 | 0 | 0 | LLM 调用失败(重试后): 非 JSON / 空体: | -| field-type-a | anchor | 一轮修复 | 1 | 0 | | -| field-type-a | plain | 一轮修复 | 1 | 0 | | -| field-type-b | anchor | 一轮修复 | 1 | 0 | | -| field-type-b | plain | 一轮修复 | 1 | 0 | | -| key-fix-a | anchor | 一轮修复 | 1 | 0 | | -| key-fix-a | plain | 一轮修复 | 1 | 0 | | -| key-fix-b | anchor | 一轮修复 | 1 | 0 | | -| key-fix-b | plain | 未修复 | 0 | 0 | LLM 调用失败(重试后): 非 JSON / 空体: | -| ret-type-a | anchor | 一轮修复 | 1 | 0 | | -| ret-type-a | plain | 一轮修复 | 1 | 0 | | -| ret-type-b | anchor | 一轮修复 | 1 | 0 | | -| ret-type-b | plain | 一轮修复 | 1 | 0 | | -| type-typo-a | anchor | 一轮修复 | 1 | 0 | | -| type-typo-a | plain | 一轮修复 | 1 | 0 | | -| type-typo-b | anchor | 一轮修复 | 1 | 0 | | -| type-typo-b | plain | 一轮修复 | 1 | 0 | | - -## 护栏核对 - -- 每次越界编辑都以 `mlsp.repair_out_of_scope` + `abstain` 被拒,且 `repair_apply` 全有或全无(源零字节不改)——由 `tests/repair_loop.rs` 的确定性断言覆盖;本实验计数仅作记录。 diff --git a/doc/roadmap/stdlib-executable-handbook.md b/doc/roadmap/stdlib-executable-handbook.md deleted file mode 100755 index 2b7eb07..0000000 --- a/doc/roadmap/stdlib-executable-handbook.md +++ /dev/null @@ -1,60 +0,0 @@ -# 标准库:可执行手册与通用能力闭环 - -目标:代码即文档,文档即 SKILL,SKILL 即 tools。AI 直接阅读任务对应的 `lib/*.mq.md` 单文件,理解输入来源、输出形态、效应、失败处理和可执行示例;保持既有导入兼容。 -本清单记录真实交付状态,未完成项不能因文档或接口占位而标为完成。 - -## 阶段与验收 - -- [x] A. 宿主效应作为唯一事实来源;直调、导入别名、中英文和双后端一致。 -- [x] A. `call` 明确授权文件读写及根目录;会话重放保留权限范围。 -- [x] A. 明确递归删除、索引基数、不可变更新、结构化可恢复错误契约。 -- [x] B. 文件筛选、行/JSON/CSV 读写、目录树复制、批量改名/同步及冲突策略。 -- [x] B. 原子/条件写入、临时目录与清理、路径相对化与扩展名替换。 -- [x] C. 序列、投影、筛选、分组/聚合、连接、按键去重/多键排序和表形态转换。 -- [x] C. 字段类型转换与记录校验;避免回调字符串求值及新集合方言。 -- [x] D. 字节与分块 IO、文件哈希、网络下载、压缩归档及明确资源上限。 -- [x] D. HTTP 响应头、可配置超时、一致的错误结果;保留既有入口兼容。 -- [x] E. 子任务超时、并发上限、批量取消与资源回收。 -- [x] E. 日期完整时区/DST、配置读写边界、规模性能。 -- [x] F. 文档章节/表格/代码块/链接提取和保留叙述的受控局部修改,复用解析器。 -- [x] G. 全标准库单文件手册、标题下参数表、叙述形参和遮蔽调用;叙述超过 50%;提供契约与真实示例;不以伪函数或叙述比例代替正确性。 -- [x] G. 三个端到端工程:文件整理、CSV 数据处理、文档维护;示例直接提取执行。 -- [x] G. 相关回归、双后端、默认/最小特性构建及平台能力矩阵。 - -## 实施约束 - -保留工作区已有的 reader 改动。通用组合优先 `.mq.md`,OS/算法边界使用小型宿主原语; -不增加第二套 Skill 编译器、字符串 eval 或应用模板语法。递归删除保留旧入口行为, -新增清晰的窄接口;每次修改都同时写清兼容性和失败语义。 - -## 验证记录 - -按用户澄清修正为 31 个模块族、61 份公开标准库单文件;撤除先前误增的 64 份目录与模块手册。648 个公开函数的名称、参数顺序和默认值 AST 与迁移前逐项一致;不再保留旧 + 形参。源码中的实际调用在 Tree 与 Bytecode 共执行 126 次,并检查操作结果。17 项标准库工程测试通过;所有函数的叙述比例均超过 50%。 - -先前能力实现的验证记录如下;单文件结构与遮蔽调用修正后的全量复验记录在表后追加。 - -| 验证 | 真实结果 | -|---|---| -| `GOFLAGS=-buildvcs=false cargo test --offline --all-targets` | 首次全量 967 通过、0 失败、2 个原有忽略项,包含千文档编译测试 | -| `GOFLAGS=-buildvcs=false cargo test --offline --all-targets -- --skip v3_corpus_1000_compile_smoke` | 结构修正前回归 968 通过、0 失败、2 个原有忽略项;跳过的千文档测试已在首次全量通过,合计覆盖 969 个不同通过项 | -| `cargo check --offline --no-default-features --features wasm-core` | 通过;保留已有未使用代码告警 | -| `cargo run --offline --quiet --example stdlib_catalog -- --check` | 0 条源码效应说明需要更新 | -| `cargo check/build --offline -p marqdo-wasm --target wasm32-unknown-unknown` | 使用临时目录内版本匹配的官方工具链通过 | -| `node tests/wasm/smoke.mjs <wasm产物>` | ABI 与桥接通过 | -| `node tests/wasm/stdlib.mjs <wasm产物>` | 集合、字节、文档、TOML、IANA/DST 与 32 位边界通过 | -| `git diff --check` | 通过 | - -最终全量回归包含 17 项标准库工程测试。`GOFLAGS` 仅对本次命令关闭工作区所有权导致的 Go VCS 盖章失败,不修改全局 Git 配置。wasm 检查和运行使用同一构建产物,Node 验收不代表浏览器 DOM 布局验收。 - -单文件结构与遮蔽调用修正后的复验: - -- `GOFLAGS=-buildvcs=false cargo test --offline --all-targets`:970 通过、0 失败、2 个原有忽略项,包含千文档编译、312 项金样例及 17 项标准库工程测试。 -- 61 份公开源码包含 63 条真实命令,Tree 与 Bytecode 共执行 126 次;操作返回 Result 时同时检查其 ok。 -- 648 个函数的名称、参数顺序与默认值 AST 逐项保持一致;每个函数叙述均超过 50%,标题下有完整契约,且不再保留旧形参。 -- 编译器效应检查:0 条源码效应说明需要更新;--json 直接输出 648 条真实接口记录。 -- 精简 wasm-core 构建通过;当前源码重新构建的 wasm32 产物通过 ABI、桥接和标准库 Node 运行验证。 -- `git diff --check` 通过。保留原有 reader 工作区修改。 - -删除旧形参后,沿用现有叙述形参推断;修复引号内星号、分号、空格被误作默认值边界的问题,并增加扫描回归测试。宿主调用的遮蔽标签不参与执行,诊断测试继续穿过标签定位真实指令和独立调用点。 - -[设计与能力边界](../design/stdlib-handbook.md)记录平台能力矩阵、兼容索引基数、资源上限、CoW 限制、目录复制范围、条件写入并发边界及线程取消语义。这些边界均为明确契约,不以占位实现宣称支持。保留工作区既有 reader 改动。 diff --git a/doc/roadmap/stdlib-mid.md b/doc/roadmap/stdlib-mid.md deleted file mode 100755 index bf9ebf8..0000000 --- a/doc/roadmap/stdlib-mid.md +++ /dev/null @@ -1,200 +0,0 @@ -# 路线图:中层标准库(数个版本) - -| | | -|---|---| -| 状态 | **M1–M6 已落地**(收口) | -| 日期 | 2026-09-07 | -| 设计 | [stdlib-mid.md](../design/stdlib-mid.md) | -| 后续 | [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) | -| 相关 | [stdlib-modules.md](../design/stdlib-modules.md) · [next-phase.md](next-phase.md) · [ext-cli.md](../design/ext-cli.md) | - -> **不预标 SemVer。** 每一波随当时产品发版合入;下文用 **M1…M6** 波次名。每波须可单独演示、可回滚。 - ---- - -## 0. 总序 - -```text -M1 文本与编解码地基 re + encoding ← 最先解锁「无插件写库」 -M2 路径与文件中层 path + fs 加厚 -M3 完整性与机密 hash + secrets -M4 表格数据与文本加厚 csv + text++ -M5 集合与 CLI 糖 table/listx + cli -M6 可观测与标识 log + uuid(+ 可选 yaml) -``` - -原则: - -1. **先原语、后糖**:正则 / 编解码 / 路径先于 CLI 糖与日志格式。 -2. **每波必须有金样 + public 短页**;无文档不算完成。 -3. **并行约束**:不阻塞 `ext/linalg` 等已定领域工作;但新官方能力评审优先问 Mid。 -4. **插件冻结规则**:自 M1 起,官方新增「通用」ABI 插件默认 **拒绝**,除非设计文档论证无法用 host+L1。 - ---- - -## 1. 现状缺口(开工依据) - -| 能力 | 现状 | 后果 | -|------|------|------| -| 正则 | 无 | 校验、替换、简单解析只能 foreign 或插件 | -| base64 / hex | 无(仅有 `url_encode`) | 令牌、摘要、嵌二进制文本困难 | -| 路径代数 | `fs` 只做 I/O | 拼接靠字符串,跨平台易错 | -| 哈希 / HMAC | 无 | 校验、缓存键、签名只能外联 | -| CSV | 无 | 数据脚本推向外联 Python | -| `lib/text` | 3 个包装函数 | 「有 text 库」名不副实 | -| 安全随机 | 仅 `math.random` | 易误用于 token | -| 结构化日志 / flags | 无 | 每个脚本自造 | - -对照:Go 日常高频包(`regexp`、`encoding/*`、`crypto`、`path/filepath`、`slices`)与 Python「难写对才进 stdlib」——正是 M1–M5 的选型来源;**不**把 HTTP 服务端、数据库驱动塞进 Mid(见设计文 §3.2)。 - ---- - -## 2. 波次明细 - -### M1 — 正则与编解码(最高优先) — **done** - -| 交付 | 说明 | -|------|------| -| `lib/re.mq.md` / `lib/正则.mq.md` | `is_match` / `find` / `find_all` / `replace` / `split` | -| `lib/encoding.mq.md` / `lib/编码.mq.md` | `base64_*` / `hex_*` | -| Host | `host_re_*`(`regex`)、`host_encoding_*`(无第三方编解码 crate) | -| 金样 | `tests/lib/re-smoke` · `正则-烟测` · `encoding-smoke` · `编码-烟测` | -| 文档 | [stdlib-re.md](../design/stdlib-re.md) · [stdlib-encoding.md](../design/stdlib-encoding.md) · public `08-re-encoding` | -| 验收 | 无插件:邮箱式校验 + base64/hex 往返 | - -**刻意不做:** 回溯引用极致兼容、替换回调、完整 PCRE 方言文档化——先 RE2/ Rust `regex` 语义并写清。 - ---- - -### M2 — 路径与文件中层 — **done** - -| 交付 | 说明 | -|------|------| -| `lib/path.mq.md` / `lib/路径.mq.md` | `join` / `split` / `file_name` / `parent` / `extension` / `normalize` / `is_absolute` | -| `lib/fs` 加厚 | `copy_file` / `move` / `make_temp`(文本边界;无 `read_bytes`) | -| Host | `host_path_*`、`host_copy_file` / `host_move` / `host_make_temp` | -| 金样 | `path-smoke` · `路径-烟测` · `fs-copy-move` · `文件-复制` | -| 文档 | [stdlib-path.md](../design/stdlib-path.md) · [stdlib-fs-mid.md](../design/stdlib-fs-mid.md) · public `09-path-fs` | -| 验收 | 规范化 + 沙箱内复制/移动 | - -**刻意不做:** 完整 `shutil`、监视 `inotify`、权限 ACL 全家桶。 - ---- - -### M3 — 哈希与机密 — **done** - -| 交付 | 说明 | -|------|------| -| `lib/hash.mq.md` / `lib/哈希.mq.md` | `sha256` / `sha1` / `md5` / `hmac_sha256` | -| `lib/secrets.mq.md` / `lib/机密.mq.md` | `token_hex` / `token_urlsafe` | -| Host | `host_hash_*`、`host_secrets_*`(`sha2`/`sha1`/`md-5`/`hmac`/`getrandom`) | -| 金样 | `hash-smoke` · `哈希-烟测` · `secrets-smoke` · `机密-烟测` | -| 文档 | [stdlib-hash.md](../design/stdlib-hash.md) · [stdlib-secrets.md](../design/stdlib-secrets.md) · public `10-hash-secrets` | -| 验收 | 已知向量 + 令牌长度 | - -**刻意不做:** 密码哈希(Argon2/bcrypt)、完整 TLS、证书管理——仍属服务端/安全产品。 - ---- - -### M4 — CSV 与文本加厚 — **done** - -| 交付 | 说明 | -|------|------| -| `lib/csv.mq.md` / `lib/逗号表.mq.md` | `parse` / `stringify`(首行表头 → list of maps) | -| `lib/text` / `文本` 加厚 | `contains` / `starts_with` / `ends_with` / `replace` / `to_upper`/`to_lower` / `repeat` / `pad` | -| Host | `host_csv_*`、`host_text_*` | -| 金样 | `csv-smoke` · `逗号表-烟测` · `text-mid-smoke` · `文本-加厚-烟测` | -| 文档 | [stdlib-csv.md](../design/stdlib-csv.md) · [stdlib-text-mid.md](../design/stdlib-text-mid.md) · public `11-csv-text` | -| 验收 | CSV 往返 + 文本清洗小例 | - -**可选同波:** 极简 `format`(`{name}` 替换),若与引用语法冲突则延后。 - ---- - -### M5 — 集合算法与 CLI — **done** - -| 交付 | 说明 | -|------|------| -| `lib/table` / `表` 加厚 | `sort` / `sort_by` / `unique` / `chunk` / `zip` / `flatten`(`reverse` 已有) | -| `lib/cli.mq.md` / `lib/命令行.mq.md` | `parse`(`--k v` / `--k=v` / `--flag`;位置参 `_`) | -| Host | `host_list_sort*` / `unique` / `chunk` / `zip` / `flatten`、`host_cli_parse` | -| 金样 | `table-list-mid` · `cli-sort-smoke` · `表-命令行-烟测` | -| 文档 | [stdlib-list-cli.md](../design/stdlib-list-cli.md) · public `12-list-cli` | -| 验收 | CSV 按键排序 + 参数解析 | - -**刻意不做:** 泛型迭代器协议、惰性流、完整 argparse 互斥组。 - ---- - -### M6 — 日志、UUID、收口 — **done** - -| 交付 | 说明 | -|------|------| -| `lib/log.mq.md` / `lib/日志.mq.md` | `debug`/`info`/`warn`/`error`;level 过滤;一行文本 | -| `lib/uuid.mq.md` / `lib/标识.mq.md` | `v4` | -| Host | `host_log_set_level` / `host_log_line`、`host_uuid_v4` | -| 金样 | `log-uuid-smoke` · `日志-标识-烟测` | -| 文档 | [stdlib-log-uuid.md](../design/stdlib-log-uuid.md) · public `13-log-uuid` | -| 文档收口 | `stdlib-modules.md` 总表;设计文状态 → **M1–M6 已落地** | -| 可选未做 | `yaml` 只读子集(默认不做) | - ---- - -## 3. 跨波次工程清单 - -每波共用: - -- [ ] 中英 L1 对称([stdlib-i18n.md](../design/stdlib-i18n.md)) -- [ ] `host_*` 形参在 L1 **全量转发**([stdlib-modules.md](../design/stdlib-modules.md) §2.1) -- [ ] 双后端金样(tree + bytecode,若该 host 已接线) -- [ ] WASM:标注 `host-only` 或实现 stub -- [ ] CHANGELOG「标准库」条目 -- [ ] skill `examples.md` 增加 Mid 惯用写法(GFM 优先) - -宿主膨胀守卫: - -- 新增 crate 须在 PR/设计中写清:**为何不能纯 mq**、**features 如何裁剪**、**许可证**。 -- 禁止借 Mid 把 `ext/web` 的服务端栈链进主二进制。 - ---- - -## 4. 与官方扩展的互动(减插件) - -| 扩展 | Mid 落地后可做的减负 | -|------|----------------------| -| `ext/web` | 路由/校验用 `re`;ETag/缓存键用 `hash`;静态路径用 `path` | -| `ext/agent` | 工具参数校验、密钥材料用 `secrets`/`hash`(领域核仍插件) | -| `ext/ai/llm` | 头/体编解码走 `encoding` | -| `ext/linalg` / `quantum` | **不**迁入 Mid;继续插件;仅共用 `path`/`hash` 等通用面 | - -跟踪方式:某波完成后,开短 issue/清单「ext X 可删除的原生辅助」,不强迫同波大改。 - ---- - -## 5. 建议人力切分(示意) - -| 波次 | 大致体量 | 可演示产物 | -|------|----------|------------| -| M1 | 中 | 「正则替换 + base64 往返」用户页 | -| M2 | 中 | 「安全拼接路径写文件」 | -| M3 | 小–中 | 「下载内容 sha256 校验」 | -| M4 | 中 | 「CSV → 表 → 打印」 | -| M5 | 小–中 | 「零插件数据 CLI」 | -| M6 | 小 | 「带 log level 的脚本」 | - -若只能开一条线:**M1 → M3 → M2 → M4 → M5 → M6**(完整性校验常比路径代数更刚需时,M3 可紧贴 M1)。 - ---- - -## 6. 完成定义(整条 Mid 叙事) - -当 M1–M6 完成时,对外可宣称: - -> Marqdo 自带中层标准库:正则、编解码、路径、哈希、CSV、加厚文本与集合/CLI 糖,以及日志与 UUID;**写通用脚本与多数扩展库不再需要原生插件。** -> 插件保留给 web 运行时、智能体、量子与线性代数等**领域引擎**。 - ---- - -## 7. 一句话 - -**按 M1→M6 把通用原语沉进 `lib/`,用数个发版周期换掉「事事插件」——领域 `ext/` 继续尖,语言本体变宽。** diff --git a/doc/roadmap/stdlib-mid2.md b/doc/roadmap/stdlib-mid2.md deleted file mode 100755 index d7db6bb..0000000 --- a/doc/roadmap/stdlib-mid2.md +++ /dev/null @@ -1,91 +0,0 @@ -# 路线图:中层标准库第二波(M7–M10) - -| | | -|---|---| -| 状态 | **Completed · M7–M10 已落地(zip 跳过)** | -| 日期 | 2026-09-09 | -| 设计 | [stdlib-mid2.md](../design/stdlib-mid2.md) | -| 缺口 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) | -| 前序 | [stdlib-mid.md](stdlib-mid.md)(**M1–M6 done**) | -| 基线 | v0.3.7+ | - -> **不预标 SemVer。** 波次名 **M7…M10**;每波可单独演示、可回滚。 - ---- - -## 0. 总序 - -```text -M7 时间与地址 datetime + url -M8 配置与安全字面 toml(只读) + html.escape + encoding/base32 -M9 文件再厚 fs make_dirs / remove_tree / stat / walk -M10 收口糖(可选) stats 薄 · log 字段 · (zip 默认跳过) -``` - -原则: - -1. 继承 Mid1 宪法:通用、难写对、小宿主、可冻 API。 -2. **TOML 优先于 YAML**(对齐 PEP 680 教训)。 -3. 不阻塞宿主 / ext 产品线;但新「通用」ABI 插件默认拒绝。 - ---- - -## 1. 波次明细 - -### M7 — datetime + url — **done** - -| 交付 | 说明 | -|------|------| -| `lib/datetime` · `日期时间` | now/parse/format/add/unix/zone 子集 | -| `lib/url` · `地址` | parse · query_parse/stringify(手写;无 `url` crate) | -| Host | `host_datetime_*` · `host_url_*` | -| 金样 | `tests/lib/datetime-smoke` · `url-smoke`(中英) | -| public | `14-datetime-url` · `14-日期时间地址` | -| 设计 | [stdlib-datetime.md](../design/stdlib-datetime.md) · [stdlib-url.md](../design/stdlib-url.md) | - -### M8 — toml + html + encoding — **done** - -| 交付 | 说明 | -|------|------| -| `lib/toml` · `配置表` | 只读子集 `parse` | -| `lib/html` · `超文本` | `escape` / `unescape` | -| `encoding` base32 | RFC 4648 | -| 金样 | `toml-html-encoding-smoke`(中英) | -| public | `15-toml-html-encoding` · `15-配置表超文本编码` | -| 设计 | [stdlib-toml.md](../design/stdlib-toml.md) · [stdlib-html.md](../design/stdlib-html.md) | - -### M9 — fs 加厚 — **done** - -| 交付 | 说明 | -|------|------| -| `make_dirs` / `remove_tree` / `stat` / `walk` | 见 [stdlib-fs-mid2.md](../design/stdlib-fs-mid2.md) | -| 金样 | `fs-mid2-smoke`(中英) | -| public | `16-fs-mid2` · `16-文件mid2` | - -### M10 — 可选收口 — **done**(zip 跳过) - -| 交付 | 说明 | -|------|------| -| `lib/stats` · `统计` | mean / median / sample stdev | -| `log` `fields=` | 行尾 `key=val` | -| zip | **跳过** | -| 金样 | `stats-log-smoke`(中英) | -| public | `17-stats-log` · `17-统计日志` | -| 设计 | [stdlib-stats-log.md](../design/stdlib-stats-log.md) | - ---- - -## 2. 进度勾选 - -- [x] M7 datetime + url -- [x] M8 toml + html + base32 -- [x] M9 fs 加厚 -- [x] M10 可选(zip 跳过) -- [x] 研究文高优先级缺口 → closed(M7–M9;M10 为收口糖) -- [x] `stdlib-modules.md` / `stdlib.md` 状态同步 - ---- - -## 3. 成功标准 - -对外可宣称:在 Mid1(文本/路径/哈希/CSV/CLI/日志)之上,**日历、URL、TOML 配置、HTML 转义、实用 fs** 无需外联即可完成常见脚本与 catalog 工具——领域能力仍在 `ext/`。 diff --git a/doc/roadmap/tables-maps-footnotes.md b/doc/roadmap/tables-maps-footnotes.md deleted file mode 100755 index c779763..0000000 --- a/doc/roadmap/tables-maps-footnotes.md +++ /dev/null @@ -1,306 +0,0 @@ -# 表格语义打磨:列表 · 字典 · 嵌套 · 脚注取元(未来规划) - -| | | -|---|---| -| 状态 | **T0–T5 已落地**(单元格表达式见 [table-cell-expressions.md](../design/table-cell-expressions.md)) | -| 日期 | 2026-08-12 | -| 相关 | [markdown-mapping.md](../design/markdown-mapping.md) §9 · [table-cell-expressions.md](../design/table-cell-expressions.md) · [objects.md](../design/objects.md) · [stdlib.md](../design/stdlib.md)(`lib/table`) · [keywords.md](../design/keywords.md) | -| 现状金样 | [tests/structure/collection.mq.md](../../tests/structure/collection.mq.md) | - ---- - -## 1. 问题 - -### 1.1 今日表格 =「竖表 → 列表」 - -```markdown -`篮子` = - -| 果 | -|----| -| 苹果 | -| 梨 | -| 桃 | -``` - -语义(已落地):绑定为**列表**(列值);表头名供 `` [`果`](`篮子`) `` 遍历。 -单列表头是当前唯一一等集合外形;**没有**一等「横表 = 字典」。 - -### 1.2 缺字典外形与嵌套 - -用户期望:GFM 表的两种几何对应两种结构,并允许嵌套——这样「多行表格」才有稳定、可教的含义。 - -### 1.3 不能按下标 / 键直接取元 - -今日要从列表取第 *n* 项,往往只能遍历或走 `lib/table`(`row_at` 等),**语言级**缺少与 Markdown 同构的取元语法。字典亦然。 - ---- - -## 2. 目标 - -1. **竖表**继续表示列表(兼容现有金样)。 -2. **横表**(多列表头 + 数据行)表示字典及「字典 ↔ 列表」嵌套。 -3. 用 **Markdown 脚注外形** 做列表下标 / 字典键的取元(表达式级)。 -4. 不引入 `[]` 下标关键字风暴;少而精,与「标记即语法」一致。 - -非目标: - -- 完整电子表格公式引擎 -- 用表声明对象字段 schema(仍见 objects 非目标;与数据集合分开) -- 破坏现有单列竖表金样 - ---- - -## 3. 表格几何 → 值(锁定提案) - -判定在 **绑定右侧的 GFM 表** 上做(`` `名` = `` 后接表)。 - -### 3.1 竖表 → 列表(现状,保留) - -**形状:** 恰好 **1** 列。 - -```markdown -`篮子` = - -| 果 | -|----| -| 苹果 | -| 梨 | -| 桃 | -``` - -| 结果 | 说明 | -|------|------| -| 值 | `List`:`["苹果","梨","桃"]` | -| 表头 | 元素逻辑名(foreach 绑定名);不进入列表元素 | - -### 3.2 横表单数据行 → 字典 - -**形状:** ≥2 列,且 **恰好 1 行数据**(表头 + 分隔 + 一行)。 - -```markdown -`分类` = - -| 苹果 | 黄瓜 | 鼠标 | -|------|------|------| -| 水果 | 蔬菜 | 数码用品 | -``` - -| 结果 | 说明 | -|------|------| -| 值 | `Map`:`苹果→水果`, `黄瓜→蔬菜`, `鼠标→数码用品` | -| 键 | 表头单元格文本(规范化空白后) | -| 值 | 唯一数据行对应列 | - -### 3.3 横表多数据行 → 字典套列表(默认) - -**形状:** ≥2 列,且 **≥2 行数据**。 - -```markdown -`货架` = - -| 苹果 | 黄瓜 | -|------|------| -| 红富士 | 青瓜 | -| 嘎啦 | 黄瓜条 | -``` - -**默认语义(锁定):列向聚合** - -```text -{ - "苹果": ["红富士", "嘎啦"], - "黄瓜": ["青瓜", "黄瓜条"] -} -``` - -即:**键 = 表头,值 = 该列数据行组成的列表**。 -这与竖表「一列 = 一列表」在多列时自然推广,嵌套外形稳定。 - -**备选语义(不默认):行向记录列表** - -```text -[ - {"苹果":"红富士","黄瓜":"青瓜"}, - {"苹果":"嘎啦","黄瓜":"黄瓜条"} -] -``` - -更像 SQL / CSV。若未来需要,用显式标记区分(见 §3.5),**不得**与默认列向字典静默混用。 - -### 3.4 单列多行 vs 多列 - -| 列数 | 数据行 | 值类型 | -|------|--------|--------| -| 1 | ≥0 | `List` | -| ≥2 | 1 | `Map`(标量值) | -| ≥2 | ≥2 | `Map`(值均为 `List`) | -| ≥2 | 0 | `Map`(键存在,值空列表或错误——开工时锁定为「空列表」) | - -### 3.5 显式形态标记(行向记录)— **已落地** - -首列表头为下列之一时,整表改为**行向**(不静默混用列向默认): - -| 标记 | 说明 | -|------|------| -| `@` | ASCII 短标记 | -| `行` | 中文 | -| `row` | 英文 | - -规则: - -1. 标记列**不进入**记录字段(数据格可写行号给人看)。 -2. 其余列 → 每行一个 `Map`;整体为 `List`。 -3. 须至少有一列字段(仅 `| 行 |` → 诊断)。 -4. 数据行数任意(含 0 → 空列表;1 行仍是 `List` of one `Map`,不是列向 `Map`)。 - -```markdown -`订单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | -| 2 | 梨 | 3 | -``` - -→ `[{品名: 苹果, 数量: 2}, {品名: 梨, 数量: 3}]`。取元:`` `订单`[^1][^品名] ``。 - ---- - -## 4. 脚注取元(历史 · 过渡保留) - -> **主语法已切换为链接形** `[键](集合)`,见 [collection-access-link.md](../design/collection-access-link.md)。 -> 本节 `` 集合[^键] `` 仍由运行时接受;**新代码请写链接形**。 - -### 4.1 为何曾用脚注外形 - -- Markdown 已有 `[^…]` 引用形态,读者不陌生。 -- 避免 `篮子[0]` 与链接 / 图片语法纠缠。 -- 与「标识符反引号」组合清晰:`` `篮子`[^1] ``。 - -### 4.2 列表:按下标 - -```markdown -*`第一` = `篮子`[^1] * -> print text=`第一` -``` - -| 约定 | 选择(提案) | -|------|----------------| -| 下标基准 | **1-based**(与 Markdown / 人类表格行语感一致;脚注 `[^1]` 即第一项) | -| `[^0]` | 报错(保留 0 不用)或日后表示「最后一项」—— v1 **报错** | -| 越界 | 清晰诊断 `path:line:col` | - -### 4.3 字典:按键 - -键为脚注标签文本(推荐与表头一致;**允许纯数字键**,如基矢标签 `00`)。基名可写 `` `概率`[^00] `` 或 `` 概率[^00] ``(紧跟 `[^` 时可省略反引号): - -```markdown -*`种` = `分类`[^苹果] * -*`p00` = `概率`[^00] * -> print text=`种` -``` - -| 规则 | 说明 | -|------|------| -| `[^苹果]` | 键文本 `苹果` | -| `[^00]` / `[^1]` | 键文本 `00` / `1`(**不是**「第 n 个 map 条目」) | -| 含空格的键 | 允许 `[^数码用品]`;极端键用引号策略开工前定 | -| 缺失键 | 报错或 `None`——建议 v1 **报错**(少静默) | - -### 4.4 嵌套取元 - -列向字典套列表: - -```markdown -*`货架` = …多行横表… * -*`第一种苹果` = `货架`[^苹果][^1] * -``` - -从左到右:先键、再下标。 -类型不对(对 List 用非数字键名脚注)→ 诊断。Map 上的纯数字标签按**键名**解析。 - -### 4.5 与 GFM「定义脚注」正文 - -标准 Markdown 文末 `[^1]: 说明` 是**注释/文献**,不是取元。 - -规则: - -- **表达式位置**的 `` `名`[^…] `` → 取元。 -- **文末脚注定义块** → 仍作注释(或不支持,避免混用)。 -- 不要求为每个 `[^1]` 写定义;Marqdo 取元**不依赖**定义块。 - -### 4.6 与 `lib/table` 关系 - -| 层 | 职责 | -|----|------| -| 语言脚注取元 | 一等、短、金样覆盖 | -| `lib/table` | 行列切片、整表变换;可逐步把 `row_at` 文档改为「等价于脚注」 | - ---- - -## 5. foreach 与字典 - -今日:`` [果](篮子) `` / `` [`果`](`篮子`) `` 遍历列表(裸名与反引号均可)。 - -扩展草案: - -| 集合 | 遍历 | -|------|------| -| List | 不变,项为元素 | -| Map | `` [`键`](`映射`) `` 遍历键;或 `` [`对`](`映射`) `` 若引入对类型—— v1 建议 **遍历键**,值用 `` `映射`[^…] `` / 辅助 | - -具体键值对遍历语法开工前写一小段进 mapping;避免与链接外形 `` [`x`](`y`) `` 冲突(今日已是 foreach)。 - ---- - -## 6. 推荐落地顺序 - -```text -T0 横表单行 → Map;金样;竖表回归 ✅ -T1 横表多行 → Map of List(列向);嵌套金样 ✅ -T2 脚注取元:List [^n]、Map [^键]、链式 ✅ -T3 文档:markdown-mapping §9;Skill / examples;table 库 ✅ -T4 行向记录表:首列 `@` / `行` / `row` ✅ -T5 数据单元格 = 表达式(同调用实参值语法) ✅ -``` - -验收: - -1. `tests/structure/collection.mq.md` 行为不变。 -2. 新金样:`collection-map.mq.md`、`collection-map-list.mq.md`、`footnote-index.mq.md`。 -3. 错误下标 / 缺键带 `line:col`。 -4. 双后端(tree / bytecode)一致。 -5. **T5:** 单元格 `` `var` `` / 算术;URL 与 `gpt-4o-mini` 仍为文本;设计见 [table-cell-expressions.md](../design/table-cell-expressions.md)。 - ---- - -## 7. 教学对照(写入 Skill 的素材) - -| 几何 | 含义 | 取元 | -|------|------|------| -| 单列竖表 | 列表 | `` `a`[^1] `` | -| 多列 + 一行 | 字典 | `` `m`[^键] `` | -| 多列 + 多行 | 字典 → 列表 | `` `m`[^键][^1] `` | -| 首列 `@`/`行`/`row` | 记录列表 | `` `r`[^1][^字段] `` | - -竖表表头是「元素名」;横表表头是「键名」——几何决定角色,减少「这张表到底是啥」的歧义。 - ---- - -## 8. 开放点 - -1. 表头重复列名:报错还是后缀 `_2`?建议 **报错**。 -2. 数字表头:字典键为文本 `"1"` 还是整数?建议 **文本**(与单元格一致)。 -3. 脚注 1-based 与宿主语言习惯(0-based)的文档警示。 -4. 字节码:`Index` / `KeyGet` 操作码是否与 T2 同批。 - ---- - -## 9. 与其它规划的关系 - -| 文档 | 关系 | -|------|------| -| [object-inheritance.md](object-inheritance.md) | 正交;表不表示类字段 schema | -| [agent-streaming.md](agent-streaming.md) | 正交;事件列表可用竖表金样演示 foreach | -| [okf-near-match.md](okf-near-match.md) | 正交 | diff --git a/doc/roadmap/three-problems-plan.md b/doc/roadmap/three-problems-plan.md deleted file mode 100755 index a3b488a..0000000 --- a/doc/roadmap/three-problems-plan.md +++ /dev/null @@ -1,225 +0,0 @@ -# 三大问题落地计划(core 收口 · 渐进式契约 · MLSP) - -| | | -|---|---| -| 状态 | **本期开发依据 · 执行中** | -| 日期 | 2026-09-22 | -| 设计 | [three-problems.md](three-problems.md)(解决方向与验证设计;判据矩阵 §5.1) | -| 范围 | **工程任务 = Phase 1–3**;验证实验(three-problems.md §5.2)协议见 [perf-validation.md](perf-validation.md)(2026-09-23 用户授权自行设计并执行) | -| 约定 | 每任务带机器可验证验收;**任务完成 = 验收全绿 + 全量回归绿**;只改宣言不改行为 = 未完成 | - -## 0. 本期范围与依赖 - -| 阶段 | 定位 | 本期 | -|------|------|------| -| **Phase 1** 核心收口 + 诊断地基 | 一切的地基 | ✅ 启动 | -| **Phase 2** 渐进式契约层 | 校验层(schema 源头 = 表格/段落) | ✅ 本期主目标 | -| **Phase 3** MLSP(AI 语言服务) | **下一步的超级核心**(AI 不必学语法 + 可靠反馈闭环) | ⏭ 下期启动,本期只留接口 | -| **Phase 4** 验证实验 | 性能验证(非开发任务) | ❌ 不认领 | - -依赖链(**跳步会倒逼「另造一套错误 / 另写一套 schema」的遮盖式捷径**): - -```text -T1.4 Diagnostic ──是──> T2.x 契约诊断的唯一出口 -T2.x 契约 ───────是──> T3.1 schema 注册表的主数据源 -T1.1 core-surface ─是─> T3.1 语言面 + T1.3 守卫 -``` - ---- - -## Phase 1 · 核心收口 + 诊断地基(本期启动) - -### T1.1 核心表面清单 - -- **产出**:`doc/design/core-surface.md` -- **实现要点**: - - 两张表:**行构造**(heading-unit `#`/`##`、call-line `>`、branch-list `1.`、loop-list `-`、param `+ 名`、table、fence、hr、writeback、narrative、blank)与**内联标记**(ident `` `名` ``、bold-code `**…**`、italic-return `*…*`、empty-return、link-index `[键](集合)`、bracket-call `[函数]`、footnote-index `[^键]` 过渡); - - 每行含:**id**(英文 kebab,守卫用)、Markdown 外形、语义、**戒律**(边界 + 为什么不能是普通 Markdown)、**金样**(`tests/markup-v03/…` 路径); - - 与 [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md) §5 / §10 对齐;词法大类(`src/lex/mod.rs` `LineKind`)另列一节说明与构造表的关系。 -- **验收**:每行金样文件真实存在(T1.3 断言);id 全集 = T1.3 `CORE_CONSTRUCTS` 全集。 - -### T1.2 三层归属与准入戒律 - -- **产出**:`doc/design/layers.md` + `.github/PULL_REQUEST_TEMPLATE.md`(无则新建) -- **实现要点**: - - 归属表(含仓库路径):Language = `src/lex` `src/parse` `src/ast` `src/interp` `src/diagnostics` + 契约检查器;Runtime = `lib/` `plugins/` `crates/` `src/catalog.rs` `src/view` `src/debug` + 未来的 check/schema/mcp;Document = `*.mq.md` `skills/` `ext/` `public/` `examples/`; - - 准入戒律:新特性先填层归属;进 Language 必答「为什么现有标记不够」;默认进 ext;核心标记计数每 release 只许持平或下降; - - 发布 checklist:CHANGELOG 增「核心表面 Δ」栏(写入 `skills/marqdo-release/SKILL.md` 一步)。 -- **验收**:PR 模板含「层归属」必填项;layers.md 与 core-surface.md 互相引用闭合。 - -### T1.3 核心表面守卫(CI) - -- **产出**:`tests/core_surface.rs` + `src/parse/mod.rs` 增 `pub const CORE_CONSTRUCTS: &[(&str, &str)]`(id、外形;**紧邻分类代码维护**) -- **实现要点**:`include_str!` 解析 core-surface.md 表格 id 列 ↔ `CORE_CONSTRUCTS` **双向集合相等**;每行「金样」路径 `Path::exists()` 断言。 -- **验收(反遮盖核心)**: - - 新增 `CORE_CONSTRUCTS` 条目不改文档 → **红**; - - 文档加行不改代码 → **红**; - - 删除/改名金样文件 → **红**。 - -### T1.4 诊断对象扩展(Phase 2/3 的唯一出口) - -- **产出**:`src/diagnostics.rs` 扩展 + `src/main.rs` `run --json` -- **实现要点**: - - `Diagnostic` 增 `code`(如 `parse.*` / `contract.*` / `runtime.*`)、`severity`、`suggestion`、`doc_anchor`、`doc_quote`、`contract_ref`(Phase 2 起填值);`::new/at` 签名不变(全仓调用零改动),新增 builder 方法; - - `serde::Serialize` + `to_json()`;**Display 保持 `path:line:col: message`**(人类输出零回归); - - `run --json`:顶层错误路径把 Diagnostic 序列化输出(stderr JSON 行)。 -- **验收**:现有错误金样文本输出**零变化**;新金样断言 JSON `code`/`span` 非空;`cargo test` 全绿。 - ---- - -## Phase 2 · 渐进式契约层(本期主目标) - -### T2.1 契约 AST + 提取器 - -- **产出**:`src/contract.rs`(`Contract` / `ParamContract` / `FieldContract` + 类型词汇 `text/number/bool/list/map/any/对象名`);`src/parse/`(提取);`src/ast.rs`(挂载,带 span) -- **实现要点**:按 [three-problems.md](three-problems.md) §2.3/§2.4——**未绑定文档表** + 列头关键字(`参数/返回/字段/类型/说明`)+ 允许位置(函数体首个可执行行前 / 绑定前 / 对象体首成员前);**被绑定的表永不视为契约表**。 -- **验收**:三附着面金样 + 「绑定表不吃」反例金样(web_db_migration 式 `字段|类型|可空` 绑定数据表必须原样是数据);未知类型名(`nubmer`)必产诊断。 - -### T2.2 四边界运行时校验 - -- **产出**:`src/interp.rs` 接入四边界——调用实参 / 字段访问(`[键](集合)`、`.field`)/ 表绑定 / `*…*` 返回 -- **实现要点**:只在**该边界有契约**时校验(无契约 = 全动态,P1);诊断一律走 T1.4 出口(`code=contract.*`)。 -- **验收**:有契约 + 错值 → 必产诊断;**无契约路径全量回归零变化**;three-problems.md §5.2(c) 消融材料可产。 - -### T2.3 `marqdo check` + `--json` - -- **产出**:`src/check.rs` + `src/main.rs` `Commands::Check` -- **实现要点**:静态**按需**校验(只查有契约处);不做全局推导。 -- **验收**:契约样例工程 `check` 退出码非 0 且 JSON 合协议;干净工程 0 退出零输出。 - -### T2.4 锚点诊断 - -- **产出**:契约诊断填 `doc_anchor`(契约表行段 `file#Lx-Ly`)+ `doc_quote`(表行原文) -- **验收**:金样断言锚点非空且行号回读命中契约表;three-problems.md §5.2(a) 材料就绪。 - -### T2.5 契约 vs 实现互查(防漂移) - -- **产出**:check + 运行时提示——契约参数名 ≠ 升参名 / 未知类型 / 返回契约明显不符 → 诊断 -- **验收**:故意写错契约的金样**必红**(three-problems.md §5.2(d) 材料就绪)。 - -### T2.6 运行时内省 `get_schema`(可延后,P3) - -- **产出**:`src/builtin.rs` 内省 builtin(契约是数据,P3) -- **验收**:demo 运行中取回自身函数契约并打印。 - ---- - -## Phase 3 · MLSP(下一步的超级核心;本期只留接口) - -### T3.1 `marqdo schema`(schema 注册表,三来源零手写) - -- **产出**:`src/schema.rs` + `Commands::Schema`——语言面(core-surface 机械转 JSON)+ 函数/类型面(**契约** + stdlib/ext 签名)+ 项目面(`catalog.yaml`) -- **验收**:两次生成 byte-identical;stdlib 主函数覆盖率 ≥ 90%。 - -### T3.2 `marqdo mcp`(AI 工具面) - -- **产出**:MCP server(参考 `plugins/agent/src/mcp_server.rs`)——`syntax_list` / `syntax_get` / `fn_schema` / `type_schema` / `validate` / `repair` / `run` -- **验收**:MCP 客户端冒烟:`fn_schema` → `validate` → `repair` 全链路。 - -### T3.3 查询式 AI Skill - -- **产出**:`skills/marqdo/` 改写——十条硬规则 + 查询工作流(construct → validate → 修 → run);细节一律走 `syntax_get` / `fn_schema` -- **验收**:skill 体积减半以上;金样全绿。 - -### T3.4 修复回路 - -- **产出**:repair 规则库 + 语句级 patch(AST span 对齐;预算 N=3;防循环) -- **验收**:注入 bug 金样一轮修复率可测(three-problems.md §5.2(a) 执行就绪)。 - ---- - -## Phase 4 · 验证实验(**协议 = [perf-validation.md](perf-validation.md)**) - -- 2026-09-23 用户授权**自行设计**性能验证设计并执行验证;`doc/next/002.md` 与性能验证无关(此前「待导入」表述已纠正)。 -- five 实验 (a)–(e) 的**材料由 Phase 1–3 的验收金样直接供给**;协议 / 指标 / 判据见 [perf-validation.md](perf-validation.md) §1–§5; - 实验产物 = [perf-validation-report-2026-09-23.md](perf-validation-report-2026-09-23.md)。 - ---- - -## 完成定义 - -| 阶段 | 完成定义 | -|------|----------| -| Phase 1 | T1.1–T1.4 验收全绿 | -| Phase 2 | T2.1–T2.5 验收全绿(T2.6 可延后) | -| Phase 3 | T3.1–T3.4 验收全绿 | -| 三大问题「已解决」 | [three-problems.md](three-problems.md) §5.1 判据矩阵全绿 + 实验数字可复现(Phase 4) | - -## 落地记录 - -### Phase 2 · 渐进式契约层(2026-09-22 完成 T2.1–T2.5;T2.6 按计划延后至 Phase 3) - -- **T2.1** `src/contract.rs`(类型词汇/三形状契约表解析/合并/四边界校验诊断)+ - `src/parse/mod.rs::extract_function_contract`(位置 + 形状双重判定,**在升参推断之前**执行—— - 契约表的单元不会被误升参;契约表从 body 移除,元数据永不执行)。 - 反例守住:**绑定**的 `字段|类型` 数据表(web_db_migration 风格)绝不视为契约。 -- **T2.2** 四边界全接:调用实参(普通/库路径/方法三条调用路径)、返回、表绑定、字段访问 - (键存在性**先于**取值,契约诊断优先于 `missing map key`)。列语义按「几何即类型」:标量或全匹配列向量。 -- **T2.3/T2.5** `marqdo check [FILE] [--json]`:契约行 vs 升参推断形参双向互查 - (错行 ⇒ Error;新升参未覆盖 ⇒ Warning)、未知类型名(附最近建议)、错位契约;Error ⇒ 非零退出。 -- **T2.4** 全部契约诊断带 `doc_anchor`(`file.mq.md#L7-L13`)+ `doc_quote`(契约表原文)+ - `contract_ref`(`declared` = 契约声明摘要);`run --json` / `check --json` 同源输出。 -- **附带修复(错误出口唯一)**:`src/load.rs` 原来把 parse 错误 `anyhow!("{label}: {e}")` 拍平成字符串, - 结构化诊断在 import 装载链路丢失;改为 `label_error` 保留 Diagnostic(补文件标签),任何装载层都不许拍平错误。 -- 验收:`tests/contracts.rs` 12 例(提取 4 + 四边界 4 + check 3 + 正向对照 1)全绿; - 全量回归零失败(含 262 gold)。 -- **T2.6(契约导出 `get_schema`)**:按计划延后至 Phase 3 与 MLSP `schema` 一并实现。 - -### Phase 3 · MLSP(2026-09-22 完成 T3.1–T3.4 全部工程项 + T2.6) - -- **T3.1** `marqdo mlsp` 子命令:行分隔 JSON over stdio,请求 `{"id","method","params"}` → - 响应 `{"id","ok","result"|"error"}`(永不 panic,错误也是结构化 JSON)。 -- **T3.2** 五个 handler 全部实现(`src/mlsp.rs`): - `locate`(构造卡片 / 符号定位 + 契约)、`syntax`(关键字/别名 → 卡片;语法唯一事实来源 = - `parse::CORE_CONSTRUCTS`,MLSP 只加检索别名不定义语法)、`validate`(parse + 契约 check → 结构化诊断数组)、 - `repair_targets`(有界修复靶点:`strategy=anchored-local`、`on_violation=abstain`——越界必拒护栏先行)、 - `schema`(**T2.6 完成**:单元名 → 形参/返回/字段契约 + 升参清单 + 锚点)。 -- 验收:`tests/mlsp.rs` 7 例全绿(语法问答/未知查询/符号定位/漂移校验/schema 导出/有界修复/结构化错误); - stdio 冒烟通过;全量回归零失败。 -- **T3.4(修复回路)**(2026-09-22 完成工程项)——`src/repair.rs` **机械护栏**(有界行编辑 - replace/delete/insert:触碰行必须落在靶点范围内,越界 ⇒ 整体拒绝 + 越界清单 + abstain,源零字节不改; - 表尾追加允许 end+1)+ `mlsp repair_apply` 出口(护栏的 MLSP 面)+ **golden 20 例** - (10 骨架 × 2 变体:arg/ret/field/key/typo/drift/dup;金修复经完整修复循环复现——诊断 → 靶点 → - 行编辑自动推导 → 范围自检(「易锚定」的机器验证)→ 应用 → 复验)+ 护栏负例(越界必拒/部分越界全拒)。 - **模型实验完成(2026-09-22 · `tests/repair_experiment.rs` · 双模型三轮 @ llm.cflmy.cn)**: - §5.2(a) 锚点消融——`anchor` 臂(诊断带 `doc_anchor`/`doc_quote`/`suggestion`)**一轮修复率最高 20/20 = 100%**(目标 ≥80% ✅); - `plain` 臂(去锚)85%–100%。三轮汇总: - - | 轮 | 模型 | anchor 一轮 | anchor 最终 | plain 一轮 | plain 最终 | 护栏越界 | - |---|---|---|---|---|---|---| - | 1 | `cflmy`(Qwen3.8-Flash-Next) | **20/20(100%)** | 100% | 17/20(85%) | 17/20 | 0 | - | 2 | `mimo-v2.6-flash`(容错加固中) | 18/20(90%) | 19/20(95%) | 19/20(95%) | 19/20 | 0 | - | 3 | `mimo-v2.6-flash`(容错补齐后) | **20/20(100%)** | 100% | 18/20(90%) | 19/20(95%) | 0 | - - **"≥80% 一轮修复率"三轮双臂全部达标(最低 85%)**;护栏 0 越界(越界必拒/abstain 由确定性测试 - `tests/repair_loop.rs` 硬断言覆盖)。实验同时是 `validate`→`repair_targets`→`repair_apply` 功能面的真实消费者。 - **"不稳定"定性为三类测量端问题,均已加固**(与 Marqdo 语义无关):① 网关空体抖动 → curl `--retry` + 5s 退避; - ② 推理模型 token 预算被 `reasoning_content` 吃光 → `max_tokens` 2000→8000;③ 模型输出格式畸形 → 解析容错 - (数组/单对象/NDJSON 多对象流/字符串化元素/字符串型行号/围栏/数字后多余引号的确定性修补)。 - 锚点增量观察:易锚定样本两臂都高(天花板效应),cflmy 上 anchor +20pp 明显、mimo 上持平—— - **锚点价值的区分性验证留 Phase 4**(难样本/信息受限消融)。 - 报告:[repair-experiment-2026-09-22.md](repair-experiment-2026-09-22.md)(cflmy)、 - [repair-experiment-2026-09-22-mimo-v2.6-flash.md](repair-experiment-2026-09-22-mimo-v2.6-flash.md)(mimo 终测)。 -- **T3.3(AI Skill 换骨:背语法 → 查 MLSP)**(2026-09-22 完成)——`marqdo` / `marqdo-dev` 两件套改为 - 查询式工作流:写码前 `mlsp syntax/locate`、提交前 `mlsp validate` + `marqdo check`; - 渐进式契约三种表格形状入语法面;错误修复照 `doc_anchor` 局部改(越界必弃权)。 - -## Phase 4 · 验证执行记录(2026-09-23,协议 [perf-validation.md](perf-validation.md)) - -- **(a) 锚点修复消融** ✅ PASS——判据「anchor 一轮 ≥80% + 护栏 0 越界」:cflmy anchor 20/20=100%(plain 85%)、 - mimo-v2.6-flash anchor 20/20=100%(plain 90%),越界拒/越界应用 0/0。易锚定样本近天花板, - 增量区分性留难样本扩展(协议 §1 诚实注记)。 -- **(b) 盲测(查询式 vs 全文档背诵)** ❌ 四判据未全立 ⇒ 按 three-problems.md §3.7 **继续改协议**—— - deepseek-flash:docs 4/6 vs query 0/3(端点 infra 剔除 3/6);首轮语法错 2/3 vs 2/6;token 69,771 vs 57,276。 - mimo-v2.6-pro 两跑均端点 infra(12/12、11/12,**不可评估**;结果回填 [perf-validation-report-2026-09-23.md](perf-validation-report-2026-09-23.md) §3)。 - **真发现**:查询机制本身无缺陷(多词查询亦正确命中卡片),败例是**跨语言习惯泄漏**(元组表达式/Python 调用形) - ——模型"不知道自己不知道"而不去查。协议改进主攻方向:**自查触发机制**(validate 前置自检、 - 陌生构造强制查询),而非继续改进卡片。 -- **(c) 契约消融** ✅ PASS——拦截率 4/4=100%、误报率 0/4=0%、无契约零回归 4/4(四边界:调用实参/返回/表绑定/键访问)。 -- **(d) 防漂移演练** ✅ PASS——必报率 9/9=100%(9 类故意写错全数诊断)、负对照误报 0/2。 -- **(e) 核心守卫演练** ✅ PASS——3/3 变异注入必红(清单私增/文档私增/金样删除)、还原必绿。 -- **判据矩阵回填**:three-problems.md §5.1 逐行标注——问题 1 ✅、问题 2 ✅、**问题 3 ❌(未解决)**。 -- **测量端记录**:LLM 网关随机空体为最大干扰(重试 5→12 次、退避 5→15 秒、截断自适应 max_tokens); - harness 修复两处协议性 bug(查询额度用满误判、提取失败不进修复回路)后采样; - 模型口径按用户指示由 `cflmy`/`mimo-v2.6-flash` 改 `mimo-v2.6-pro`/`deepseek-flash`(实验 (a) 数据为原组合,不重跑)。 -- **全量干净回归**(无 API key 基线)零失败。 diff --git a/doc/roadmap/three-problems.md b/doc/roadmap/three-problems.md deleted file mode 100755 index f0afb67..0000000 --- a/doc/roadmap/three-problems.md +++ /dev/null @@ -1,393 +0,0 @@ -# Marqdo 三大问题:解决方向与验证设计 - -——证明「被解决」,而不是「被遮盖」 - -| | | -|---|---| -| 状态 | **设计 · 已导出本期开发任务:[three-problems-plan.md](three-problems-plan.md);验证实验不属于开发任务** | -| 日期 | 2026-09-22 | -| 来源 | [001.md](../next/001.md) 评审讨论提炼的三大问题;用户决议:**问题二走「渐进式契约 / 标注类型」**(拒绝照搬静态类型,也拒绝放弃语义校验);**问题三(AI 可靠反馈 + AI 不必学语法)是下一步的超级核心** | -| 相关 | [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md)(语法宪法)· [tables-maps-footnotes.md](tables-maps-footnotes.md)(表格几何)· [catalog-cli.md](../design/catalog-cli.md) · [ai-skill.md](../design/ai-skill.md) · [objects.md](../design/objects.md) · [interpreter.md](interpreter.md) | - -> **本文定位:三大问题的解决方向与验证设计。** 给三大问题定义「什么算被解决」(机器可验证判据,见 §5.1)与验证实验(修复率 / 盲测 / 消融 / 防漂移演练,见 §5.2),把「真正解决」与「遮盖过去」区分开。文中的解决步骤(各节 S 表)是**设计方向**;本期开发任务、排期与验收以 [three-problems-plan.md](three-problems-plan.md) 为准。**验证实验(§5.2)协议见 [perf-validation.md](perf-validation.md)**(2026-09-23 用户授权自行设计并执行)。 -> -> **一句话:语言核心收口是地基;渐进式契约是校验层,schema 直接长在表格与说明段落里;AI 语言服务消费这两者形成可靠闭环。** 三个问题必须一起解——契约是 AI 接口的数据源,核心收口是契约语法不膨胀的前提。 - -**贯穿戒律(防止「遮盖式解决」):每个阶段的验收必须是机器可验证的行为变化。只产出宣言文档、不改变工具行为的,一律视为未完成。** - ---- - -## 0. 问题清单与依赖 - -| # | 问题 | 定位 | 一句话方案 | -|---|------|------|-----------| -| 1 | 语言核心正在被生态功能淹没,identity 不清 | **地基** | 三层归属表 + 准入戒律 + 核心表面守卫(CI 断言) | -| 2 | 「静态类型列为非目标」被误读为「不需要语义校验」;但照搬 Java/TS 静态类型会毁掉低摩擦 | **校验层** | **渐进式契约**:schema 写在表格 / 说明段落里;按需契约校验;诊断带文档锚点 | -| 3 | AI 反馈不可靠(只有给人看的文本);AI 还在背千行语法文档 | **超级核心** | **Marqdo Language Server for AI(MLSP)**:结构化诊断协议 + 可查询 schema + 修复回路 | - -依赖链: - -```text -问题 1(核心收口:契约语法不许越界进核心) - └─→ 问题 2(契约层:schema 源头 = 表格 / 说明段落) - └─→ 问题 3(schema 注册表 = 契约 + 核心表面 + catalog) - └─→ 实证(修复实验 + 消融基准 → README 愿景 6) -``` - -共享地基先行项:**统一诊断协议(Diagnostic)**——问题 2 的契约校验与问题 3 的 AI 反馈都以它为出口,因此它排在最前(见 §3.3 与 §4)。 - ---- - -## 1. 问题一:语言核心必须小 - -### 1.1 诊断 - -Marqdo 现在同时是:Markdown 语言 + literate programming + 知识库 + catalog + web + WASM + 浏览器 + LLM + agent + MCP + 量子 + 线代 + 插件 ABI。工程上这很酷;语言设计上的危险是: - -> **核心语言的 identity 被生态功能淹没;新功能随手进核心 → 语法面暗中膨胀。** - -真正缺的不是「收敛宣言」,而是**三样机制**: - -1. 一份穷举的**核心表面清单**——现在「什么算核心」没有唯一明文; -2. 一张**三层归属表**——新提案无处登记,默认哪儿都塞; -3. 一条**越界即可见的守卫**——核心语法暗增长没有任何机器报警。 - -### 1.2 目标 / 非目标 - -**目标**:Language / Runtime / Document 三层分离;核心标记维持**约 15 个**的封闭集合,生态增长不再增加语言面。 - -**非目标**:删掉 web/quantum/agent 等功能(它们不是错,层次混放才是错);重写解释器;给核心加模块可见性等系统编程特性。 - -### 1.3 三层归属表(S1 产出物,此处先锁定语义) - -| 层 | 内容 | 仓库位置 | -|----|------|----------| -| **Language** | 标记映射、词法/行分类、AST、语义、升参、**契约检查器**、诊断 | `src/`(解释器核心)· `doc/design/markdown-mapping-v0.3.md` | -| **Runtime** | stdlib、插件 ABI、WASM、debugger、view、catalog / schema CLI、MCP | `lib/` · `plugins/` · `crates/` · `src/bin` | -| **Document** | 知识单元、skills、示例、public 站、agent 工作流、官方扩展 | `*.mq.md` · `skills/` · `ext/` · `public/` · `examples/` | - -核心表面清单(S1 的枚举基线,来自宪法 §5,逐项进 `core-surface.md`): - -叙述(含 `` `名` `` 声明/引用)· `**…**` 代码 · `*…*` 返回 · 空返回形(`*None*` 等)· `>` 调用 · `#` / `##` 标题单元 · 体内 `1.` 分支 · `-` 循环 · GFM 表格 = 集合 · `[键](集合)` 取元 · `修饰… [函数名]` 方括号调用 · 脚注取元(过渡)· ` ```lang ` 外联 · `---` 叙述分隔 · `` + `名` `` 形参(兼容形)。 - -### 1.4 解决方向(设计 · 任务化见 plan) - -| 步 | 动作 | 产出 | 验收(机器可验证) | -|----|------|------|--------------------| -| S1 | 写 `doc/design/core-surface.md`:穷举核心标记,每个标记一行「戒律」(语义、边界、**为什么不能是普通 Markdown**) | 核心表面唯一清单 | 清单项 ↔ `tests/markup-v03/` 金样逐项有例;缺项即测试红 | -| S2 | 写 `doc/design/layers.md`:§1.3 归属表 + **准入戒律**——任何新特性提案必须先填「进哪层」;进 Language 层必须答「为什么现有标记不够」,默认答案是「进 ext」 | 归属与准入制度 | 仓库 PR 模板加「层归属」必填项 | -| S3 | 核心表面守卫:Rust 测试断言「词法分类枚举 ↔ core-surface.md 表格」一致(脚本解析 markdown 表格比对枚举名) | `tests/core_surface.rs` | 故意加一个新标记不更新清单 → CI 红 | -| S4 | 核心变更强制走 ADR:新增核心标记必须有 `doc/adr/` 编号 + 反例说明;每个 release 的 CHANGELOG 单列「核心表面 Δ」 | ADR 戒律 | 发版 checklist 含「核心表面 Δ」栏 | -| S5 | 文档收口:README/doc 目录按三层重排;`doc/design/` 只收 Language 层决策,Runtime 进 `doc/roadmap/`,生态面进各自 ext 文档 | 重排后的文档树 | README 目录树与三层表一一对应 | - -**观测指标**(不是 KPI,是体检):核心标记计数每个 release 只许持平或下降;连续 3 个版本增长即触发 Language 层复盘。 - -### 1.5 遮盖 vs 解决 - -| 遮盖式做法(禁止) | 本方案的做法 | 判据 | -|--------------------|--------------|------| -| 写一篇「语言核心很重要」的宣言 | 清单 + 归属表 + **CI 守卫** | 新增标记不更新清单时 CI 必须红 | -| 「以后尽量不加语法」的口头约定 | ADR 强制 + CHANGELOG 核心表面 Δ | 没有 ADR 编号的核心变更不允许合并 | -| 把 ext 功能砍掉显得小 | 不砍功能,只**归层** | web/quantum/agent 全部保留且测试通过 | - ---- - -## 2. 问题二:渐进式契约 / 标注类型 - -### 2.1 分歧点澄清(本方案的立场) - -GPT 一侧强调「AI 可验证语言需要强语义校验」,容易被听成「上静态类型」。**这两件事不一样**: - -> 「放弃全程序静态编译类型」**≠** 「放弃语义检查、字段解析、契约校验」。 - -照搬 Java/TS 式静态类型会破坏「自然叙述优先、低摩擦」的体验——Marqdo 会变得笨重,丢掉对业务人员 / agent 即兴脚本的友好性。**目标不是变成静态语言,而是一套附着在文档单元上的可查询契约系统,作为 AI 闭环里的校验层。** - -渐进式契约的四条特征: - -1. **动态默认**——不强制任何标注,保持动态,适合快速原型与 agent 即兴脚本; -2. **契约即文档**——schema 可选地写在**表格、文档段落**里,不引入第二套标注语言; -3. **按需校验**——不做全局类型推导;在调用边界 / 字段访问时校验「当前值 vs 契约」; -4. **诊断即文档链接**——错误不只报类型错,还定位到文档里对应的说明段落,给 AI 的诊断自带文档上下文。 - -**独有优势(TS/Python 做不到)**:契约的 schema 源头就是表格与函数说明段落本身——不是额外写一套 JSON Schema。知识、契约、数据、代码在同一份 `.mq.md` 里,**契约即知识**。这是 Knowledge-Code Coherence 的第一个可落地实证:契约说 `int` 实际来了 `text` 时,被机器抓住的不是「文档过期」,而是**知识不一致**。 - -### 2.2 设计原则 - -| # | 原则 | 含义 | -|---|------|------| -| P1 | 无契约 = 全动态 | 没写契约的单元行为**一字不变**(零回归是硬验收) | -| P2 | 不新增核心标记 | 契约语法全部骑在现有 Markdown 外形上(问题一戒律直接约束本节) | -| P3 | 契约是数据 | 契约表本身就是 Marqdo 集合,运行时可内省(`get_schema` 一类的 lib 函数免费获得) | -| P4 | 双向防漂移 | 不只「值 vs 契约」,还查「契约 vs 实现」(§2.7-S5) | -| P5 | 诊断带锚点 | 凡契约诊断必含:契约表所在文件 + 行段 + 原文引用 | - -### 2.3 契约的三个附着面 - -**A. 函数契约** —— `##` 函数体内、首个可执行行之前的**未绑定文档表**: - -```markdown -## 加一 - -加一函数:把输入加一。 - -| 参数 | 类型 | 说明 | -|------|------|------| -| `n` | number | 输入值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| — | number | n+1 | - -对于输入变量`n`,执行**n=n+1**接着返回*n*。 -``` - -参数仍由 v0.3 升参推断(宪法 §8),契约**不改变**形参机制,只在存在时校验——零摩擦兼容存量代码。 - -**B. 集合 / 表格契约** —— 紧邻 `` `名` = `` 绑定之前的未绑定文档表: - -```markdown -| 字段 | 类型 | 可空 | -|------|------|------| -| id | number | 否 | -| name | text | 否 | - -`用户` = - -| 行 | id | name | -|----|----|------| -| 1 | 1 | 甲 | -``` - -**C. 对象契约** —— `# 对象` 体内首个成员之前的 `| 字段 | 类型 |` 表;同时被 catalog 提取为条目 schema(见 §3.5 项目面)。 - -**先例**:schema 长在表格里今天已经发生——`web_db_migration` 的 `| 字段 | 类型 | 可空 |` 列就是以数据形式传递的 DDL schema。契约系统把这个模式升格为**通用约定**。 - -### 2.4 形态选型(为什么是「契约表」) - -| 候选 | 形态 | 判决 | -|------|------|------| -| **P-A 契约表**(选定) | 列头关键字(`参数`/`返回`/`字段`/`类型`/`说明`)的未绑定文档表 | ✅ 与「GFM 表格即数据」哲学一致;catalog 可提取;人读无负担 | -| P-B 叙述内标注 | `` `n`: int `` 写在散文里 | ❌ **否决**:改动行内 `` `名` `` 词法 = 核心标记变更,违反问题一戒律与 P2 | -| P-C frontmatter | YAML 声明契约 | ⚠️ 仅作文件级汇总的可选补充(serde_yaml 已在解析元信息);函数粒度不够,不作主形态 | - -**消歧规则(防「契约表」误吃数据表)**: - -1. **被绑定的表永不视为契约表**——`名` = 后的表是数据(宪法 §5:未绑定才「求值后丢弃」,即文档表)。`web_db_migration` 的列头恰好叫 `字段|类型|可空` 但它是绑定数据,不受影响; -2. 契约表必须是**未绑定文档表** + 列头命中关键字集,且出现在允许位置(§2.3 A/B/C); -3. 同一位置出现多张契约表:参数表与返回表各认各的列头;其余重复 → 诊断(防两份契约打架)。 - -### 2.5 类型词汇(刻意做小) - -`text` · `number` · `bool` · `list` · `map` · `any` · 对象名(与 `# 对象` / `_type` 对齐)。 - -- 词汇表**只有这一行**;扩展类型词汇 = Language 层变更,走 ADR(问题一 S4)。 -- 类型名拼错(如 `nubmer`)→ **必须报诊断**(§2.7 验收),否则契约本身成为新的漂移源。 - -### 2.6 校验时机(按需四边界,不做全局推导) - -| 边界 | 校验什么 | 时机 | -|------|----------|------| -| 调用实参 | 实参值 vs 参数契约(类型 + 可选 required) | 运行时调用瞬间;`check` 静态可查处一并查 | -| 字段访问 | `[键](集合)` / `obj.field` vs 字段契约(键存在性 + 类型) | 访问瞬间 | -| 表绑定 | `` `名` = `` 表的几何/单元格 vs 集合契约 | 绑定瞬间 | -| 返回 | `*…*` 值 vs 返回契约 | 返回瞬间 | - -无契约 → 该边界直接跳过(P1)。校验器**不是**编译器:不做跨函数全局推导、不要求全程序一致。 - -### 2.7 解决方向(设计 · 任务化见 plan) - -| 步 | 动作 | 产出 | 验收(机器可验证) | -|----|------|------|--------------------| -| S1 | 契约提取器:按 §2.3/§2.4 规则解析未绑定文档表 → `Contract` 对象,挂入 AST 单元(`Param` 已有 `span`,契约同级带 `span`) | AST + 提取器 | 金样:三附着面各一份提取断言(含「绑定表不吃」反例) | -| S2 | 运行时边界校验:§2.6 四边界接入 `Contract` | 运行时校验 | 有契约 + 错值 → **必**产出 §3.3 诊断;无契约金样**全绿零回归** | -| S3 | `marqdo check`:静态按需校验(只查有契约处),`--json` 输出诊断 | CLI | 契约样例工程 `check` 退出码非 0 且诊断 JSON 合协议 | -| S4 | 诊断锚点:契约错误必带 `doc_anchor` + `doc_quote`(契约表原文行) | 诊断增强 | 金样断言诊断 JSON 里锚点字段非空、行号可回读原文 | -| S5 | **契约 vs 实现互查**(P4):契约参数名 ≠ 升参推断名、契约类型名未知、契约返回 vs 语句结构明显不符 → 诊断 | 防漂移检查 | 故意写错契约的金样**必须**红(而不是静默信任契约) | -| S6 | 运行时内省:`lib` 提供 `get_schema 单元=…`(P3:契约是数据) | lib 函数 | demo:运行中取回自身函数契约表并打印 | - -### 2.8 遮盖 vs 解决 - -| 遮盖式做法(禁止) | 本方案的做法 | 判据 | -|--------------------|--------------|------| -| 把「静态类型」继续列为非目标就收工 | 明确「≠ 放弃语义校验」,落**边界校验器** | 运行时行为变化可测(§2.7-S2) | -| 照搬 Java/TS 全程序静态类型 | 渐进式:无标注零摩擦,按需四边界 | 无契约金样零回归 | -| 另写一套 JSON Schema 文件 | schema = 表格 / 说明段落本身 | 仓库里**不允许**出现手写的第二份 schema;契约只能从 `.mq.md` 提取 | -| 契约写了就永远正确 | 契约 vs 升参互查 + 未知类型名必报 | 故意写错契约的金样必红 | -| 错误只报 `type mismatch` 文本 | 诊断带文档锚点 + 原文引用 | 金样断言锚点字段 | - ---- - -## 3. 问题三(超级核心):AI 可靠反馈 + AI 不必学语法细节 - -### 3.1 两个子问题 - -**A. 可靠反馈**:今天解释器诊断是给人看的文本(`path:line:col` + message,见 ai-skill「按诊断迭代」)。AI 拿到它要「猜」哪里错、对应文档哪句话、怎么改。GPT 设想的闭环—— - -```text -LLM → Marqdo → 语义校验 → 结构化 Error → LLM 修复 → 合格程序 -``` - -——的第一块砖就是**结构化诊断**,而且诊断必须自带文档上下文(问题二 §2.1-4 的锚点在这里被 AI 消费)。 - -**B. 不必学语法**:今天 `skills/marqdo` 是「面向模型的压缩操作手册」= **背诵式**。正确形态是**查询式**: - -```text -AI ── discover ─→ construct ─→ validate ─→ execute ─→ inspect -``` - -AI 不阅读一千行文档然后猜,而是按需调 `get_syntax("branch")`、`fn_schema("print")`、`validate(program)`。**这才是 Marqdo 与普通 DSL 拉开距离的地方。** - -### 3.2 总形态:Marqdo Language Server for AI(MLSP) - -一套机器可读的语言服务协议。工具面(首版最小集): - -| 工具 | 入参 | 返回 | 数据源 | -|------|------|------|--------| -| `syntax_list` / `syntax_get` | — / 构造名 | 核心构造表 / 单构造戒律 | core-surface(问题一 S1,机械转 JSON) | -| `fn_schema` | 函数名 | 参数/返回契约 + 说明 + 锚点 | 契约(问题二)+ stdlib/ext 签名 | -| `type_schema` | 对象名 | 字段契约 + 方法表 | `# 对象` 契约 + catalog | -| `validate` | 程序文本/文件 | `Diagnostic[]` | 契约校验器 + 语义检查 | -| `repair` | 程序 + 诊断 | 建议 patch(限定行级) | 诊断规则库 | -| `run` | 入口 | 结果或结构化错误 | 运行时 | - -交付通道(按序):**`marqdo mcp`**(MCP server,复用 agent ext 的 MCP 经验)→ CLI `--json`(任何宿主可用)→ `skills/marqdo` 改造成「教 AI 查询」(§3.6)。 - -### 3.3 先决:统一诊断协议(可靠反馈的地基) - -所有层(解释器、check、契约、插件错误)统一产出: - -```json -{ - "code": "contract.arg_mismatch", - "severity": "error", - "message": "参数 `n` 期望 number,实际 text", - "span": { "file": "demo.mq.md", "line": 12, "col": 3, "heading": ["加一"] }, - "doc_anchor": "demo.mq.md#L4-L7", - "doc_quote": "| `n` | number | 输入值 |", - "contract_ref": { "unit": "加一", "kind": "param", "name": "n", "declared": "number" }, - "suggestion": "把实参改为数字;若契约有误,改契约表的类型列" -} -``` - -规则: - -1. 凡可定位必带 `span`(AST 已有 span,宪法 §10.2); -2. 凡契约错误必带 `doc_anchor` + `doc_quote`——**错误直接定位到文档里对应的说明段落**; -3. 凡可修复建议必带 `suggestion`(给修复回路的原料); -4. 人类文本输出保持现状,`--json` 并行提供——人机同读同写,诊断也一样。 - -### 3.4 修复回路(repair loop) - -```text -validate(p) → diagnose → patch(p, diag) → validate(p') → … (预算 N=3 轮) -``` - -- **限定行级 patch**,不允许整文件重写(防止 AI「修复」时破坏叙述); -- 尝试预算与重复诊断去重,防循环; -- 实验指标:**一轮修复率**(带锚点 vs 不带锚点两组对比)——这是「可靠反馈」的直接证据。 - -### 3.5 Schema 注册表(三来源,零手写第二份) - -| 面 | 来源 | 说明 | -|----|------|------| -| 语言面 | `core-surface.md` 机械转 JSON | 构造戒律原文进 `description` | -| 函数 / 类型面 | **契约**(问题二产物)+ stdlib/ext 签名 | schema 源头 = 表格与说明段落(§2.1 独有优势) | -| 项目面 | `catalog.yaml`(catalog 自动生成) | 知识单元、链接关系(知识图的边) | - -格式 `marqdo-schema.json`(示意): - -```json -{ - "language": "marqdo", - "version": "0.3", - "constructs": [{ "name": "branch", "syntax": "1. … 2. … N. *", "rule": "自 1. 递增;重出 1. 开新判断" }], - "functions": [{ "name": "加一", "params": [{ "name": "n", "type": "number", "desc": "输入值", "anchor": "#L4" }], "returns": { "type": "number" } }] -} -``` - -命令:`marqdo schema [PATH]`(catalog 的兄弟命令,同样**只生成不手改**)。 - -### 3.6 AI Skill:从「背诵」改「查询」 - -`skills/marqdo` 改造原则: - -- `SKILL.md` 只留**十条不可违反的硬规则**(叙述默认安全、`**` 代码 `*` 返回、表格几何、命名/双语约定等)+ MLSP 工具用法; -- 语法细节、API 明细**一律走 `syntax_get` / `fn_schema`**,不再进上下文; -- 工作流改为:construct(凭硬规则写)→ `validate` → 按诊断修 → `run`。 - -### 3.7 解决方向(设计 · 任务化见 plan) - -| 步 | 动作 | 验收(机器可验证) | -|----|------|--------------------| -| S1 | Diagnostic 结构落地(Rust)+ 解释器诊断改造 + `run --json` / `check --json` | 现有错误金样转 JSON 后 `code`/`span` 全非空 | -| S2 | 契约诊断接入(消费 §2.7-S4 的锚点) | §2.8 判据全部成立 | -| S3 | `marqdo schema` 生成器(三来源汇聚) | 生成物 diff 稳定(两次生成 byte-identical);stdlib 主函数覆盖率 ≥ 90% | -| S4 | `marqdo mcp`:暴露 §3.2 工具面 | 用 MCP 客户端冒烟:`fn_schema` → `validate` → `repair` 全链路 | -| S5 | `skills/marqdo` 改造为查询式(保留硬规则十条) | skill 体积减半以上;既有 `marqdo run` 金样仍全绿 | -| S6 | 修复回路 + 实验执行(实验设计见 §5.2) | 实验报告(进 MarqdoThesis,对接 README 愿景 6) | - -**「解决而不是遮盖」的最终判据(问题三)**:盲测组(零语法文档 + 工具)的成绩**不劣于**全文档背诵组,且 token 显著更少、修复轮次不升——达不到就继续改协议,**不许**用「再写一篇更好的文档」充数。 - -### 3.8 遮盖 vs 解决 - -| 遮盖式做法(禁止) | 本方案的做法 | 判据 | -|--------------------|--------------|------| -| 再写一份更全的 AI 语法文档 | 查询协议 + schema 注册表 | 盲测实验成立 | -| 让 AI「多读 reference.md」 | `syntax_get` / `fn_schema` 按需取 | skill 体积减半且成绩不降 | -| 报错文本润色一下 | 统一 Diagnostic JSON + 文档锚点 | 诊断金样断言锚点字段 | -| 主观感觉「AI 好用了」 | 一轮修复率 / 盲测 / token 三组数字 | 实验报告可复现(MarqdoThesis) | - ---- - -## 4. 路线顺序(依赖序 · 排期见 [three-problems-plan.md](three-problems-plan.md)) - -> 本表是**依赖顺序**,不是排期表——任务化与本期范围见 [three-problems-plan.md](three-problems-plan.md)。 - -| 顺序 | 内容 | 产出 | 依赖 | -|------|------|------|------| -| **M0 核心收口** | 问题一 S1–S5 | core-surface.md · layers.md · CI 守卫 | — | -| **M1 诊断地基** | 问题三 S1(Diagnostic + `--json`) | 统一诊断协议 | M0 | -| **M2 契约层** | 问题二 S1–S6 | 提取器 · 四边界校验 · `check` · 锚点 · 防漂移 | M1 | -| **M3 AI 语言服务** | 问题三 S2–S5 | schema 生成 · `marqdo mcp` · 查询式 skill · 修复回路 | M2 | -| **M4 实证** | 问题三 S6 | 修复实验 + 盲测 + 消融(对接 README 愿景 6) | M3 | - -顺序理由:Diagnostic 先于契约(契约诊断是它的第一个消费者);契约先于 MLSP(契约是 schema 注册表的主数据源)——**任何一个跳步都会倒逼「另写一套 schema / 另造一套错误」的遮盖式捷径**。 - ---- - -## 5. 验证矩阵与实验设计(本文核心) - -### 5.1 判据矩阵:什么算「已解决」 - -| 问题 | 解决的定义(机器可验证) | 遮盖式收场(一句话就能写完的,禁止) | 验证手段 | 判定(2026-09-23) | -|------|--------------------------|--------------------------------------|----------|--------------------| -| 1 核心要小 | 新标记不更新 core-surface → **CI 红** | 「我们重视语言核心」 | CI 守卫演练:故意加标记不更新清单,必须红 | ✅ (e) 3/3 必红→还原必绿 | -| 2 语义校验 | 四边界校验器上线;契约写错**必**被机器抓;无契约路径零回归 | 「静态类型是非目标」/照搬 TS 类型/另写 JSON Schema | 契约金样 + 防漂移金样 + 全量回归 | ✅ (c) 拦截 100%/误报 0%/零回归;(d) 必报 9/9 | -| 3 AI 反馈 / 语法 | 盲测组错误率 ≤ 全文档组且 token 显著更少;一轮修复率可复现 | 「再写更好的文档」 | §5.2 实验 (a)(b)(d) | ❌ (a) 过(双模型 100%);**(b) 四判据未全立** ⇒ 按 §3.7 继续改协议 | - -> 2026-09-23 实测数字与判据对照:[perf-validation-report-2026-09-23.md](perf-validation-report-2026-09-23.md)。 -> 按本矩阵口径:**问题 1、2 实证成立;问题 3 未解决**(查询式盲测未跑赢全背诵——详见报告 §3 的四条要点, -> 其中「模型不查自己不知道的语法」是协议改进的主攻方向)。 - -### 5.2 实验设计(性能 / 可靠性验证) - -| 实验 | 对照组 | 指标 | 材料 | -|------|--------|------|------| -| (a) 锚点修复 | 诊断带 `doc_anchor` vs 不带 | 一轮修复率、平均修复轮次 | 注入已知 bug 的金样集 | -| (b) 盲测(零语法文档) | 只给 MLSP 工具 vs 给全文档背诵(现 `skills/marqdo`) | 语法错误率、契约违规率、token 消耗 | 任务集(QuixBugs 类 + 业务逻辑类) | -| (c) 契约消融 | 契约开 / 关 | 契约拦截率、误报率、无契约路径零回归 | 同上 | -| (d) 防漂移演练 | 契约故意写错(类型 typo / 参数名与升参不符) | 必报率 = 100% | 契约金样 | -| (e) 核心守卫演练 | 故意加新标记不更新清单 | CI 红 = 必须 | — | - -实验基建:复用 MarqdoThesis `formal/exp1–3` 的 runner / oracle / 容错重试;报告即 README 愿景 6 的「可靠性基准」材料。**判据矩阵全绿 + 实验数字可复现之前,三大问题一律视为未解决**——这是「不遮盖」的最终保险。 - ---- - -## 6. 未决问题(进 M0/M2 的 ADR 逐条锁定) - -1. 契约表消歧的边界案例:紧邻绑定的未绑定表(注释表)紧贴数据表时的归属规则要不要「隔空行才算分离」?(M2-S1 金样定夺) -2. 参数表与返回表合并成单表(首列 `参数`/`返回` 混排)是否更可读?(M2-S1 对比样例后定) -3. 对象字段契约:与 [objects.md](../design/objects.md) 「不把表当对象定义语言」的非目标如何划界——契约是**可选校验元数据**,不定义对象布局(对象仍是运行时 map);需 ADR 明文,避免与 [tables-maps-footnotes.md](tables-maps-footnotes.md) 非目标条目互相打架。 -4. 类型词汇是否收 `对象名` 之外的复合形(如 `list<number>`)?——默认**不收**,需要时走 ADR(P2 + 问题一 S4)。 -5. `marqdo check` 独立子命令 vs `run --check` 并存?(M2-S3 定,倾向独立 + `run` 默认轻查) -6. `repair` 的 patch 边界:行级 patch 的具体格式(unified diff vs 语句级替换)?(M3-S4 定,倾向语句级——与 AST span 对齐) diff --git a/doc/tutorial/01-入门.md b/doc/tutorial/01-入门.md deleted file mode 100755 index 07ccec6..0000000 --- a/doc/tutorial/01-入门.md +++ /dev/null @@ -1,88 +0,0 @@ -# 第 1 章:Marqdo 是什么 - -## 1.1 一句话介绍 - -**Marqdo = Markdown(Marq)+ 执行(do)**。它把 Markdown 的**标记当作编程语法**:同一个 `.mq.md` 文件,打开给人看是文档,运行给机器看是程序。 - -在大型项目里,说明、示例与实现往往分叉成三份「真相」,改一处忘另一处。Marqdo 让这三者**同源**——你写的文档本身就是可执行的代码。 - -## 1.2 与其他语言的区别 - -传统编程语言(如 Python)需要单独写文档和注释;Marqdo 反过来了——**文档本身就是程序**。 - -| 传统语言 | Marqdo | -|----------|--------| -| 代码在 `.py`,文档在 `.md` | 代码与文档同在 `.mq.md` | -| `def` / `if` / `for` / `return` 是关键字 | 用 Markdown 标记 `##` / `1.` / `-` / `**代码**` / `*返回*` 表达 | -| 注释用 `#` 或 `//` | **无标记的叙述就是注释** | -| 大括号 `{}` 或缩进界定代码块 | 标题层级 `#` / `##` 界定作用域 | - -关键点:**不要**试图写 `if`、`else`、`while`、`for`、`def`、`return` 这些关键字——它们不是 Marqdo 的语法。控制流由 Markdown 承担。 - -## 1.3 安装 - -Marqdo 用 Rust 编写。从以下任一方式获取: - -- **发布包**:从 GitHub Releases 下载预编译二进制(已内置标准库)。 -- **源码构建**: - -```bash -git clone https://github.com/cflmy/marqdo.git -cd marqdo -cargo build --release -# 二进制位于 target/release/marqdo -``` - -验证安装: - -```bash -marqdo --version -``` - -## 1.4 第一个程序 - -创建一个文件 `hello.mq.md`: - -```markdown -# Hello World - -这是叙述文字,也就是注释。 - -> print text=Hello World! -``` - -- `# Hello World` —— 对象标题。`# main` 是入口;当文件只有唯一一个顶层 `#` 对象时,它也可作为入口。 -- 空行后的普通文字是**注释**(叙述)。 -- `> print text=Hello World!` —— 调用内置函数 `print` 输出一行文本。 - -运行: - -```bash -marqdo run hello.mq.md -``` - -输出: - -```text -Hello World! -``` - -## 1.5 中英双语内核 - -Marqdo 内核内置函数都有中英别名,**无需导入,可混用**: - -```markdown -# main - -> 打印 内容=你好,世界! -``` - -`打印` 与 `print` 是同一个内置函数,`内容` 与 `text` 是同一个参数名。 - -## 1.6 文件后缀:`.mq.md` - -Marqdo 程序的**后缀必须是 `.mq.md`**(可执行源文件),不能用普通的 `.md`。一个 `.md` 文件默认只是文档;一个 `.mq.md` 文件既是文档又是程序。 - -## 1.7 下一步 - -你已经能写出并运行第一个程序了。接下来学习[第 2 章:基本语法](./02-基本语法.md)——理解 `.mq.md` 里哪些是代码、哪些是注释,以及标识符的写法。 diff --git a/doc/tutorial/02-基本语法.md b/doc/tutorial/02-基本语法.md deleted file mode 100755 index df96a4c..0000000 --- a/doc/tutorial/02-基本语法.md +++ /dev/null @@ -1,151 +0,0 @@ -# 第 2 章:基本语法 - -## 2.1 文件结构 - -一个 `.mq.md` 文件由以下几部分组成: - -1. **Frontmatter**(可选):文件开头的成对 `---` 之间的元信息,如标题、导入。 -2. **对象 / 函数定义**:以 `#` / `##` 开头的标题。 -3. **叙述注释**:无标记的普通文字段落(可含 `` `名` `` 声明/引用)。 -4. **可执行语句**:粗体代码、独立调用行、标题下的结构行等。 - -```markdown ---- -title: 我的程序 ---- - -# main - -这是叙述段落,整段都是注释。 - -> print text=Hello -``` - -## 2.2 代码 vs 注释:空行分段规则 - -Marqdo 的注释规则很特别:**无标记的叙述就是注释**,靠空行分段。 - -规则: - -- 空行之后的第一行若**无标记**(普通文字)→ 这一段是**注释**。 -- 注释段内的**每一行**(直到下一个空行)都是注释——即使它长得像代码。 - -```markdown -# main - -这段注释里有一行看起来像代码,但它不会执行: -**not_executed = 1** -> print text=这也是注释 - -空行之后,代码开始运行: - -> print text=这行会运行 -``` - -> **注意**:叙述与可执行代码之间**必须空一行**。忘记空行会让本意是注释的文字被当作代码,或让代码被吞进注释段。 - -## 2.3 标记一览表(markup v0.3) - -| 标记 | 含义 | -|------|------| -| `#` | 对象 / 类型(`# main` = 入口) | -| `##` … `######` | 函数 / 方法(嵌套按标题深度) | -| `` + `名` `` | 函数标题下的形参(亦可由正文 `` `名` `` 推断) | -| `1.` `2.` … | 条件分支 | -| `-` | 循环(遍历或 while) | -| `> 函数 参数` | 调用(可选;粗体内可不写 `>`) | -| `修饰 [函数] 实参` | 方括号标记调用(前导词 → `名=True`) | -| `**…**` | **代码**(赋值 / 调用) | -| `*…*` | **返回值** | -| `|` 开头的 GFM 表格 | 集合(列表 / 字典) | -| `[键](集合)` | 链接取元 | -| 单独一行 `---` / `***` | Markdown 分隔线(跳过,**不**结束函数体) | - -## 2.4 标识符与反引号 - -Marqdo 中,**变量、参数名用反引号 `` ` `` 包裹**,这与 Markdown 的代码/链接语法脱钩,避免歧义。 - -```markdown -## 问候 - + `谁` - -> print text=Hello, `谁`! -``` - -- `+ `谁`` —— 声明形参 `谁` -- `> print text=Hello, `谁`!` —— 在字符串中引用变量 `谁` - -> **注意**:在 `**…**`(粗体代码)和 `*…*`(斜体返回)内部,**裸标识符就是变量**,反引号可以省略(详见 [第 3 章](./03-变量与赋值.md))。 - -## 2.5 字面量 - -Marqdo 的字面量: - -| 类型 | 示例 | 说明 | -|------|------|------| -| 数字 | `1` `3.14` `-5` | 整数 / 浮点 / 负数 | -| 布尔 | `True` `False`(`真` `假`) | 布尔值 | -| 空值 | `None`(`空`) | 空值 | -| 文本 | `hello`(裸 token) | 无转义,按字面量 | -| 字符串 | `"Hello\n"` | 双引号,支持转义与变量插值 | -| 列表 | `[1, 2, 3]` | 通过表格构造 | -| 字典 | `{"a": 1}` | 通过表格构造 | - -文本 vs 字符串的区别: - -- **裸 token**(如 `hello`、`路径`):按字面量,不转义,适合简短文本。 -- **双引号字符串**:需要转义(`\n` 等)或嵌入变量时使用。 - -```markdown -> print text=Hello World! # 裸 token,按字面量 -**msg = "Hello, `name`!\n"** # 字符串,可插值、可转义 -``` - -## 2.6 关键字(不可作变量名) - -以下单词是 Marqdo 的**保留关键字**,不能用作变量名: - -| 英文 | 中文 | 含义 | -|------|------|------| -| `True` | `真` | 布尔真 | -| `False` | `假` | 布尔假 | -| `None` | `空` | 空值 | -| `and` | `且` | 逻辑与 | -| `or` | `或` | 逻辑或 | -| `not` | `非` | 逻辑非 | - -**不要**尝试用 `if` / `else` / `while` / `for` / `def` / `return` ——它们不是关键字,也没有意义。 - -## 2.7 一个完整的例子 - -把学到的串起来: - -```markdown -# main - -这是一个完整示例:定义函数、调用、输出。 - -> 问候 谁=Marqdo - -## 问候 - + `谁` - -> print text=你好,`谁`! - -*None* - -## 加一 - + `n` - -*n + 1* -``` - -运行输出: - -```text -你好,Marqdo! -``` - -## 2.8 下一步 - -你已经理解 `.mq.md` 的基本结构了。接下来学习[第 3 章:变量与赋值](./03-变量与赋值.md),掌握 Marqdo 的值存储方式。 diff --git a/doc/tutorial/03-变量与赋值.md b/doc/tutorial/03-变量与赋值.md deleted file mode 100755 index a6decd2..0000000 --- a/doc/tutorial/03-变量与赋值.md +++ /dev/null @@ -1,121 +0,0 @@ -# 第 3 章:变量与赋值 - -## 3.1 什么是变量 - -变量是给数据起的一个名字。Marqdo 中,变量在**粗体代码 `**…**`** 中通过 `=` 绑定: - -```markdown -**x = 1** -**name = "Marqdo"** -**ok = True** -``` - -> **重要**:在 `**…**` / `*…*` 内部,**裸标识符就是变量**——不需要反引号。这是 Marqdo 的关键约定。 - -## 3.2 绑定的三种写法 - -### 写法一:粗体代码 `**…**`(推荐) - -```markdown -**x = 1** -**y = x + 2** -``` - -这是最常用的绑定方式。裸标识符就是变量。 - -### 写法二:行首反引号绑定(无粗体) - -```markdown -`x` = 1 -``` - -不带 `**…**` 的绑定,变量名**需要反引号**。常用于绑定集合(表格)或公式: - -```markdown -`篮子` = - -| 果 | -|----| -| 苹果 | -``` - -### 写法三:绑定调用结果 - -```markdown -**len_s = > len value="hello"** -``` - -粗体内用 `= >` 表示「把调用结果赋给变量」;也可写成无 `>` 的调用形:`**len_s = len value="hello"**`。 - -## 3.3 引用变量 - -在 `**…**` / `*…*` 内部,直接写变量名即可: - -```markdown -**a = 5** -**b = a * 2** -> print text=`b` # 独立 > 调用中,变量要反引号 -``` - -> **关键区别**:在**独立 `>` 调用**(如 `> print …`)里,裸词是**文本**,所以引用变量要加反引号:`> print text=`b``。而在 `**…**` / `*…*` 内,裸词是**变量**:`**b = a * 2**`。 - -## 3.4 字符串与插值 - -### 双引号字符串 - -```markdown -**msg = "Hello, World!"** -``` - -### 转义字符 - -| 转义 | 含义 | -|------|------| -| `\n` | 换行 | -| `\t` | 制表 | -| `\r` | 回车 | -| `\\` | 反斜杠 `\` | -| `\"` | 双引号 `"` | -| `\'` | 单引号 `'` | -| `\xHH` | 十六进制字符(如 `\x22` → `"`) | -| `\u{...}` | Unicode 码点(如 `\u{4e2d}` → `中`) | - -未知转义(如 `\q`)**按字面保留**(`\q` → `\q`),不报错。 - -### 变量插值 - -字符串内用 `` `变量` `` 插值: - -```markdown -**name = "Marqdo"** -**msg = "Hello, `name`!"** -> print text=`msg` # 输出:Hello, Marqdo! -``` - -## 3.5 完整示例 - -```markdown -# main - -**name = "Alice"** -**age = 30** -**next_age = age + 1** - -> print text=名字:`name` -> print text=明年:`next_age` 岁 - -**msg = "你好,`name`!你明年 `next_age` 岁。"** -> print text=`msg` -``` - -输出: - -```text -名字:Alice -明年:31 岁 -你好,Alice!你明年 31 岁。 -``` - -## 3.6 下一步 - -你已经会存取数据了。接下来学习[第 4 章:输出与输入](./04-输出与输入.md),与用户交互。 diff --git a/doc/tutorial/04-输出与输入.md b/doc/tutorial/04-输出与输入.md deleted file mode 100755 index 9b32dd3..0000000 --- a/doc/tutorial/04-输出与输入.md +++ /dev/null @@ -1,95 +0,0 @@ -# 第 4 章:输出与输入 - -## 4.1 输出:`print` / `打印` - -`print`(中文 `打印`)是内置函数,用于向标准输出写一行文本。**输出不是粗体、也不是斜体**——粗体是代码,斜体是返回;打印是普通函数调用。 - -```markdown -# main - -> print text=Hello World! -``` - -中英等价: - -```markdown -> 打印 内容=你好,世界! -``` - -| 英文 | 中文 | 参数 | -|------|------|------| -| `> print text=…` | `> 打印 内容=…` | `text` ≡ `内容` | - -粗体内也可写:`**打印 内容="你好"**`(文本字面量须加引号)。 - -### 输出变量 - -独立 `>` 调用中,变量用反引号: - -```markdown -**x = 42** -> print text=`x` # 输出:42 -``` - -### 输出拼接 - -```markdown -**name = "Marqdo"** -> print text=欢迎使用 `name`! -``` - -## 4.2 输入:`input` / `输入` - -`input`(中文 `输入`)读取一行用户输入: - -```markdown -# main - -> input prompt=你叫什么名字? -``` - -| 英文 | 中文 | 参数 | -|------|------|------| -| `> input prompt=…` | `> 输入 提示=…` | `prompt` ≡ `提示` | - -### 读取并保存输入 - -```markdown -# main - -**name = > input prompt="请输入名字:"** -> print text=你好,`name`! -``` - -> `input` 的 `prompt` 参数可省略(缺省)。 - -## 4.3 完整示例:一个问答程序 - -```markdown -# main - -这是一个人机问答程序。 - -**name = > input prompt="你叫什么名字?\n"** -> print text=你好,`name`! - -**age = > int value=`age_input`** -``` - -> **注意**:上面的示例为了展示 `int` 用法,`age_input` 尚未定义。实际中你需要先从 `input` 得到字符串,再用 `int` 转换。完整可运行版本: - -```markdown -# main - -**name = > input prompt="你叫什么名字?\n"** -> print text=你好,`name`! - -**age_str = > input prompt="你几岁?\n"** -**age = > int value=`age_str`** -**next_age = age + 1** -> print text=`name`,你明年 `next_age` 岁。 -``` - -## 4.4 下一步 - -你已经能与用户交互了。接下来学习[第 5 章:运算符与比较](./05-运算符与比较.md)。 diff --git a/doc/tutorial/05-运算符与比较.md b/doc/tutorial/05-运算符与比较.md deleted file mode 100755 index 1ad4329..0000000 --- a/doc/tutorial/05-运算符与比较.md +++ /dev/null @@ -1,122 +0,0 @@ -# 第 5 章:运算符与比较 - -## 5.1 算术运算符 - -在 `**…**` 表达式内部: - -```markdown -**a = 10** -**b = 3** - -**sum = a + b** # 13 -**diff = a - b** # 7 -**prod = a * b** # 30 -**quo = a / b** # 3.33…(浮点除法) -``` - -| 运算符 | 含义 | -|--------|------| -| `+` | 加法 / 拼接 | -| `-` | 减法 | -| `*` | 乘法 | -| `/` | 除法 | - -> **注意**:在裸表达式里 `/` 是除法;但在**调用实参 / 参数默认值**中,不空格相连的 `a/b` 会被当作路径文本(详见[第 11 章](./11-模块与导入.md))。 - -## 5.2 字符串拼接 - -`+` 也可以拼接字符串: - -```markdown -**first = "Hello, "** -**second = "World!"** -**msg = first + second** -> print text=`msg` # Hello, World! -``` - -> 在 `**…**` 内变量是裸名;若拼接的是字符串字面量,要加引号。 - -## 5.3 比较运算符 - -| 运算符 | 含义 | -|--------|------| -| `==` | 相等 | -| `>` | 大于 | -| `<` | 小于 | -| `>=` | 大于等于 | -| `<=` | 小于等于 | - -```markdown -**n = 5** - -1. `n` > 3 - > print text=大于 3 -2. * - > print text=小于等于 3 -``` - -## 5.4 逻辑运算符 - -| 英文 | 中文 | 含义 | -|------|------|------| -| `and` | `且` | 逻辑与 | -| `or` | `或` | 逻辑或 | -| `not` | `非` | 逻辑非 | - -```markdown -**age = 20** -**has_id = True** - -1. `age` >= 18 and `has_id` - > print text=可以进入 -2. * - > print text=不能进入 -``` - -## 5.5 布尔值 - -布尔值字面量:`True` / `False`(中文 `真` / `假`)。 - -```markdown -**is_admin = False** - -1. `is_admin` == True - > print text=管理员 -2. * - > print text=普通用户 -``` - -也可以直接用布尔变量作条件: - -```markdown -**flag = True** - -1. `flag` - > print text=为真 -2. * - > print text=为假 -``` - -## 5.6 完整示例 - -```markdown -# main - -**score = 85** -**passed = score >= 60** -**bonus = passed and score >= 80** - -> print text=及格:`passed` -> print text=优秀:`bonus` -``` - -输出: - -```text -及格:True -优秀:True -``` - -## 5.7 下一步 - -你已经能计算和判断了。接下来学习[第 6 章:函数](./06-函数.md),把逻辑封装起来复用。 diff --git a/doc/tutorial/06-函数.md b/doc/tutorial/06-函数.md deleted file mode 100755 index 85170de..0000000 --- a/doc/tutorial/06-函数.md +++ /dev/null @@ -1,200 +0,0 @@ -# 第 6 章:函数 - -## 6.1 定义函数 - -在 Marqdo 中,函数用 `##`(及更深)标题定义: - -```markdown -## 加一 - + `n` - -*n + 1* -``` - -- `## 加一` —— 函数名 -- `+ `n`` —— 参数 -- `*n + 1*` —— 返回值(**斜体 = 返回**) - -函数可以挂在 `# main` 之下作为嵌套函数,也可以作为顶层自由函数。 - -## 6.2 调用函数 - -使用 `>` 或粗体内调用(具名参数或位置参数): - -```markdown -# main - -> greet who=World # 具名参数 -> greet World # 位置参数 - -## greet - + `who` - -> print text=Hello, `who`! - -*None* -``` - -### 具名 vs 位置 - -```markdown -> 问候 谁=Marqdo # 具名:名=值 -> 问候 Marqdo # 位置:按形参顺序 -``` - -二者可混用:位置实参按「尚未被具名绑定的形参」从左到右填充。 - -> 具名实参的值可以含空格,直到下一个 `名=` 边界;位置实参是单个词法单元(不含空格)。 - -### 方括号标记调用 - -可用 `[函数名]` 标出被调函数;`[` 前的裸词会变成布尔修饰(`名=True`): - -```markdown -> 问候 谁=小明 礼貌=True -礼貌 [问候] 小明 -``` - -`]` 后**紧邻** `(` 是链接取元,不是调用(见[第 9 章](./09-集合.md))。 - -## 6.3 参数与默认值 - -可选参数用 `=默认值`: - -```markdown -## 问候 - + `谁` - + `礼貌`=False - -1. `礼貌` - > print text=您好,`谁`! -2. * - > print text=嗨,`谁`! -``` - -调用: - -```markdown -> 问候 谁=小明 -> 问候 谁=小明 礼貌=True -礼貌 [问候] 小明 -``` - -## 6.4 返回值:`*…*` - -用 `*…*` 返回表达式结果: - -```markdown -## 加一 - + `n` - -*n + 1* -``` - -调用并绑定结果: - -```markdown -# main - -**b = > 加一 n=1** -> print text=`b` # 2 -``` - -### 返回 None - -推荐 `*None*` / `*无*`;也可整行空粗体 `**` 或 `****`: - -```markdown -## 静默 - + `x` - -*None* -``` - -### 字符串返回 - -```markdown -## 问候语 - + `谁` - -*"你好," + 谁 + "!"* -``` - -## 6.5 结束函数体 - -副作用函数用斜体返回收束,避免后续兄弟语句被吞进本函数: - -```markdown -# main - -> 问候 谁=World - -## 问候 - + `谁` - -> print text=Hello, `谁`! - -*None* - -## 下一个函数 -... -``` - -> 单独一行的 `---` / `***` 只是 Markdown 分隔线(跳过),**不再**表示结束函数体。文件开头的成对 `---` 仍是 frontmatter。 - -## 6.6 完整示例 - -```markdown -# main - -礼貌 [问候] Alice - -## 问候 - + `谁` - + `礼貌`=False - -1. `礼貌` - > print text=您好,`谁`! -2. * - > print text=嗨,`谁`! - -*None* - -## 加一 - + `n` - -*n + 1* -``` - -输出: - -```text -您好,Alice! -``` - -## 6.7 函数嵌套(标题深度) - -嵌套辅助函数用更深的标题: - -```markdown -# main - -> 处理 名字=小明 - -## 处理 - + `名字` - -**上 = > 大写 文本=`名字`** -> print text=`上` - -### 大写 - + `文本` - -*> str `文本`* -``` - -> 深度约定:`##` 是 `#` 的子级,`###` 是 `##` 的子级……按标题深度嵌套。 - -## 6.8 下一步 - -你已经会封装函数了。接下来学习[第 7 章:条件分支](./07-条件分支.md)。 diff --git a/doc/tutorial/07-条件分支.md b/doc/tutorial/07-条件分支.md deleted file mode 100755 index 9a448ea..0000000 --- a/doc/tutorial/07-条件分支.md +++ /dev/null @@ -1,138 +0,0 @@ -# 第 7 章:条件分支 - -## 7.1 基本分支:`1.` `2.` … - -Marqdo 用**有序列表** `1.` `2.` `3.` … 表达条件分支: - -```markdown -# main - -**n = 5** - -1. `n` > 0 - > print text=正数 -2. `n` < 0 - > print text=负数 -3. * - > print text=零 -``` - -- `1. 条件` —— 第一个分支(条件为真时执行其下的缩进行) -- `2. 条件` —— 第二个分支 -- `3. *` —— else 臂(`N. *` = 否则) - -输出: - -```text -正数 -``` - -## 7.2 else 臂:`N. *` - -在 `1.` 之后的任意臂上,**整行恰为 `*`** 表示 else: - -```markdown -**age = 15** - -1. `age` >= 18 - > print text=成年 -2. * - > print text=未成年 -``` - -## 7.3 布尔分支 - -```markdown -**is_admin = False** - -1. `is_admin` - > print text=管理员 -2. * - > print text=普通用户 -``` - -## 7.4 多条件分支 - -```markdown -**score = 85** - -1. `score` >= 90 - > print text=优秀 -2. `score` >= 80 - > print text=良好 -3. `score` >= 60 - > print text=及格 -4. * - > print text=不及格 -``` - -## 7.5 逻辑组合条件 - -```markdown -**age = 25** -**has_id = True** - -1. `age` >= 18 and `has_id` - > print text=可以进入 -2. * - > print text=不能进入 -``` - -## 7.6 多个独立分支语句 - -**一条分支语句 = 从 `1.` 起、序号递增的一段有序列表。** 同级缩进上**再次出现 `1.`** 会开启**下一条**独立分支语句: - -```markdown -# main - -**a = True** -**b = False** - -1. `a` - > print text=A 为真 -2. * - > print text=A 为假 - -1. `b` - > print text=B 为真 -2. * - > print text=B 为假 -``` - -这是**两次独立判断**,不是「四个臂的一个分支」。输出: - -```text -A 为真 -B 为假 -``` - -> 臂序号在同一分支内递增(`1.` → `2.` → `3.` …);不要在同一分支中途把序号重置为 `1.`。 - -## 7.7 完整示例:成绩评级 - -```markdown -# main - -**score = 72** - -1. `score` >= 90 - > print text=评级:A -2. `score` >= 80 - > print text=评级:B -3. `score` >= 70 - > print text=评级:C -4. `score` >= 60 - > print text=评级:D -5. * - > print text=评级:F -``` - -输出: - -```text -评级:C -``` - -## 7.8 下一步 - -你已经能根据条件走不同路线了。接下来学习[第 8 章:循环](./08-循环.md)。 diff --git a/doc/tutorial/08-循环.md b/doc/tutorial/08-循环.md deleted file mode 100755 index d01246e..0000000 --- a/doc/tutorial/08-循环.md +++ /dev/null @@ -1,179 +0,0 @@ -# 第 8 章:循环 - -## 8.1 遍历循环:`- [项](集合)` - -Marqdo 用 `-`(无序列表)表达循环。遍历列表用 `- [项](集合)`: - -```markdown -# main - -`篮子` = - -| 果 | -|----| -| 苹果 | -| 梨 | -| 桃 | - -- [果](篮子) - > print text=今天吃`果` -``` - -输出: - -```text -今天吃苹果 -今天吃梨 -今天吃桃 -``` - -- `[果](篮子)` —— 遍历 `篮子` 列表,每个元素绑定到 `果` -- 循环体内用 `` `果` `` 引用元素(独立 `>` 调用中变量要反引号) - -反引号形式等价(可混用): - -```markdown -- [`果`](`篮子`) - > print text=`果` -``` - -## 8.2 遍历字典:遍历键 - -`Map`(字典)用 `- [键](映射)` 遍历**键**: - -```markdown -# main - -`分类` = - -| 苹果 | 黄瓜 | -|------|------| -| 水果 | 蔬菜 | - -- [键](分类) - > print text=`键` -``` - -输出: - -```text -苹果 -黄瓜 -``` - -> 遍历字典遍历的是键;要取值,用链接取元 `[键](集合)`(见[第 9 章](./09-集合.md))。 - -## 8.3 while 循环:`- 条件` - -`-` 后直接写条件就是 while 循环: - -```markdown -# main - -**n = 3** - -- `n` > 0 - > print text=`n` - **n = n - 1** -``` - -输出: - -```text -3 -2 -1 -``` - -> 循环体内用 `**…**` 语句更新变量。 - -## 8.4 嵌套循环 - -循环可以嵌套: - -```markdown -# main - -`外层` = - -| 项 | -|----| -| A | -| B | - -`内层` = - -| 项 | -|----| -| 1 | -| 2 | - -- [o](外层) - - [i](内层) - > print text=`o``i` -``` - -输出: - -```text -A1 -A2 -B1 -B2 -``` - -## 8.5 循环 + 分支组合 - -```markdown -# main - -`数字` = - -| 值 | -|----| -| 1 | -| 2 | -| 3 | -| 4 | - -- [n](数字) - 1. `n` >= 3 - > print text=`n` 是大数 - 2. * - > print text=`n` 是小数 -``` - -> 循环体里的 `1.` / `2.` 是分支语句(见[第 7 章](./07-条件分支.md)),与 `-` 循环嵌套使用。 - -## 8.6 完整示例:累计求和 - -```markdown -# main - -`数字` = - -| 值 | -|----| -| 1 | -| 2 | -| 3 | -| 4 | -| 5 | - -**sum = 0** - -- [n](数字) - **sum = sum + n** - -> print text=总和:`sum` -``` - -输出: - -```text -总和:15 -``` - -## 8.7 下一步 - -你已经掌握循环了。接下来学习[第 9 章:集合(表格)](./09-集合.md),深入理解列表、字典与记录。 diff --git a/doc/tutorial/09-集合.md b/doc/tutorial/09-集合.md deleted file mode 100755 index 51bc4b2..0000000 --- a/doc/tutorial/09-集合.md +++ /dev/null @@ -1,204 +0,0 @@ -# 第 9 章:集合(表格) - -Marqdo 用 **GFM 表格**直接构造数据集合。表格的**几何形状**决定值的类型——这是 Marqdo 最有特色的部分:你看到的 Markdown 表格就是数据结构。 - -## 9.1 绑定一个集合 - -集合绑定用「空右侧赋值 + 表格」: - -```markdown -`名字` = - -| 表头1 | 表头2 | -|-------|-------| -| 值 | 值 | -``` - -表格绑定变量名**需要反引号**(不在粗体代码 `**…**` 内时)。 - -## 9.2 单列竖表 → 列表(List) - -**恰好 1 列** → 列表: - -```markdown -`篮子` = - -| 果 | -|----| -| 苹果 | -| 梨 | -| 桃 | -``` - -等价于 `["苹果", "梨", "桃"]`。表头 `果` 是元素逻辑名(foreach 绑定名),**不进入列表元素**。 - -```markdown -- [果](篮子) - > print text=`果` -``` - -## 9.3 多列 + 一行 → 字典(Map) - -**≥2 列 + 恰好 1 行数据** → 字典,键 = 表头: - -```markdown -`分类` = - -| 苹果 | 黄瓜 | -|------|------| -| 水果 | 蔬菜 | -``` - -等价于 `{"苹果": "水果", "黄瓜": "蔬菜"}`。 - -## 9.4 多列 + 多行 → 字典套列表 - -**≥2 列 + ≥2 行数据** → 字典,值为该列的列表(列向聚合): - -```markdown -`货架` = - -| 苹果 | 黄瓜 | -|------|------| -| 红富士 | 青瓜 | -| 嘎啦 | 黄瓜条 | -``` - -等价于: - -```text -{"苹果": ["红富士", "嘎啦"], "黄瓜": ["青瓜", "黄瓜条"]} -``` - -## 9.5 行向记录表 → 记录列表 - -首列表头为 `@` / `行` / `row` 时,整表改为**行向**(SQL/CSV 风格): - -```markdown -`订单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | -| 2 | 梨 | 3 | -``` - -等价于: - -```text -[{"品名": "苹果", "数量": 2}, {"品名": "梨", "数量": 3}] -``` - -标记列(`行`)不进入记录字段。 - -## 9.6 表格形状速查 - -| 形状 | 值类型 | -|------|--------| -| 1 列 | `List` | -| ≥2 列 + 1 行 | `Map`(标量值) | -| ≥2 列 + ≥2 行 | `Map`(值均为 `List`) | -| ≥2 列 + 0 行 | `Map`(键存在,值空列表) | -| 首列 `@`/`行`/`row` | `List` of `Map`(行向记录) | - -## 9.7 链接取元:`[键](集合)` - -主语法与 foreach 同形:**方括号 = 取出的名字,圆括号 = 从哪取**(见 [collection-access-link.md](../design/collection-access-link.md))。 - -### 从列表按下标取 - -**下标是 1-based**(与人类读表一致): - -```markdown -**第一 = [1](篮子)** -**打印 内容=`第一`** -``` - -### 从字典按键取 - -```markdown -**种 = [苹果](分类)** -**打印 内容=`种`** -``` - -### 动态键 - -```markdown -**名 = "拿铁"** -**价 = [`名`](菜单)** -``` - -### 嵌套取元 - -```markdown -**第一种苹果 = [1]([苹果](货架))** -``` - -### 插值中的取元 - -在**调用实参值 / 引号字符串**里也可以写链接取元(或过渡期的脚注形): - -```markdown -> print text=苹果单价:[苹果](`水果价格`) -> print text=第一种:[1]([苹果](`货架`)) -``` - -### 过渡:脚注取元 `` 集合[^键] `` - -旧写法 `` 分类[^苹果] `` / `` `分类`[^苹果] `` **仍可解析**;新代码与教程示例请用链接形。脚注兼容金样见 `tests/structure/footnote*`。 - -> 规则: -> - **List**:键须为纯数字(1-based);`[0](…)` 或越界 → 报错。 -> - **Map**:键为键文本;缺键 → 报错。 -> - 文末的 `[^1]: …` 定义块仍是注释,与取元无关。 -> - `]` 后**紧邻** `(` 才是取元;否则 `[名字]` 可能是[方括号标记调用](../design/bracket-call-modifiers.md)。 - -## 9.8 表格单元格是表达式 - -数据单元格支持表达式(与调用实参值语法相同):裸词、数字、`` `var` ``、算术、引号串。URL / `gpt-4o-mini` 等按路径/连字符折叠为文本。 - -```markdown -**k = "secret"** - -`cfg` = - -| api_key | model | -|---------|-------| -| `k` | gpt-4o-mini | -``` - -## 9.9 完整示例 - -```markdown -# main - -`水果价格` = - -| 苹果 | 香蕉 | -|------|------| -| 5 | 3 | - -**打印 内容="苹果单价:" + [苹果](水果价格)** - -`购物单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | -| 2 | 香蕉 | 3 | - -- [行](购物单) - **打印 内容=[品名](行) + " × " + [数量](行)** -``` - -输出: - -```text -苹果单价:5 -苹果 × 2 -香蕉 × 3 -``` - -## 9.10 下一步 - -你已经掌握 Marqdo 的数据组织了。接下来学习[第 10 章:对象与方法](./10-对象与方法.md)。 diff --git a/doc/tutorial/10-对象与方法.md b/doc/tutorial/10-对象与方法.md deleted file mode 100755 index 659ca91..0000000 --- a/doc/tutorial/10-对象与方法.md +++ /dev/null @@ -1,196 +0,0 @@ -# 第 10 章:对象与方法 - -Marqdo 用 `#` 标题定义**对象 / 类型**,用 `##` 定义其下的**方法**。这是一种轻量、可读的面向对象写法。 - -## 10.1 定义对象(类型) - -`#`(恰好一层)定义一个对象 / 类型,其正文是**构造体**: - -```markdown -# 大模型 - + `模型名` - -**配置 = > json.parse text={"model":"gpt-4o-mini"}** -*配置* -``` - -- `# 大模型` —— 类型名 -- `+ `模型名`` —— 构造参数 -- 构造体执行后 `*…*` 返回一个 map,运行时写入 `_type` 字段,形成实例句柄 - -## 10.2 构造实例 - -调用类型名即可构造实例: - -```markdown -# main - -**模型 = > 大模型 模型名="gpt-4o-mini"** -``` - -## 10.3 定义方法 - -对象下的 `##` 标题是方法。读字段优先用链接取元;写字段可用 `json.set` / `table.put`(跨边界序列化时再用 `json.*`): - -```markdown -# 计数器 - + `初始值` - -**状态 = > json.parse text={"n":0}** -**状态 = > json.set map=`状态` key="n" value=`初始值`** -*状态* - -## 加一 - -**n = [n](self)** -**n2 = n + 1** -**t = > json.set map=`self` key="n" value=`n2`** -*t* -``` - -方法体内自动绑定: - -- `self`(英文) -- `自`(中文) - -二者是同一个接收者,指向当前实例。 - -## 10.4 调用方法 - -### 独立 `>` 调用(接收者加反引号) - -```markdown -**计数器 = > 计数器 初始值=3** -**新值 = > `计数器`.加一** -``` - -### 粗体代码段内调用(接收者裸名) - -```markdown -**计数器 = > 计数器 初始值=3** -**新值 = > 计数器.加一** -``` - -> **重要**:在 `**…**` / `*…*` 段内,裸词是变量,所以**方法接收者不加反引号**:`**新值 = > 计数器.加一**`。而在独立 `>` 调用中,裸词是文本,接收者需要反引号:`` > `计数器`.加一 ``。 - -## 10.5 完整对象示例 - -对象(`#`)定义在**顶层**,与 `# main` 平级: - -```markdown ---- -import: - json: lib/json.mq.md ---- - -# main - -**c = > 计数器 初始值=5** -**ty = [_type](c)** -> print text=类型:`ty` - -**c2 = > c.加一** -**n = [n](c2)** -> print text=加一后:`n` - -# 计数器 - + `初始值` - -**状态 = > json.parse text={"n":0}** -**状态 = > json.set map=`状态` key="n" value=`初始值`** -*状态* - -## 加一 - -**n = [n](self)** -**n2 = n + 1** -**t = > json.set map=`self` key="n" value=`n2`** -*t* -``` - -输出: - -```text -类型:计数器 -加一后:6 -``` - -## 10.6 继承:`# Child = > Parent` - -```markdown -# Greeter - -## hello - + `who` - -**msg = "Hello, `who`!"** -*msg* - -# Loud = > Greeter - -## hello - + `who` - -**msg = "HELLO, `who`!"** -*msg* -``` - -规则: - -| 规则 | 说明 | -|------|------| -| 语法 | `# Child = > Parent` | -| `_type` | 构造后仍为**最具体子类名** | -| 方法查找 | 先子类 `##`,未命中再沿基类链;同名则子类覆盖 | -| 构造 | **不**隐式调用父构造(无 auto-super) | -| 多继承 | 不支持 | - -### 显式调用父构造 - -子类需要父字段时,在子类正文首行显式调用父构造: - -```markdown -# Child = > Parent - + `name` - -**self = > Parent name=`name`** -**self = > json.set map=`self` key="role" value="child"** -*self* -``` - -## 10.7 完整继承示例 - -```markdown -# main - -**c = > Child name="Ada"** -**ty = [_type](c)** -**role = [role](c)** -> print text=`ty` -> print text=`role` - -# Parent - + `name` - -**out = > json.parse text={"role":"parent"}** -**out = > json.set map=`out` key="name" value=`name`** -*out* - -# Child = > Parent - + `name` - -**self = > Parent name=`name`** -**self = > json.set map=`self` key="role" value="child"** -*self* -``` - -输出: - -```text -Child -child -``` - -## 10.8 下一步 - -你已经会面向对象编程了。接下来学习[第 11 章:模块与导入](./11-模块与导入.md),组织大型项目。 diff --git a/doc/tutorial/11-模块与导入.md b/doc/tutorial/11-模块与导入.md deleted file mode 100755 index 1fd8e84..0000000 --- a/doc/tutorial/11-模块与导入.md +++ /dev/null @@ -1,183 +0,0 @@ -# 第 11 章:模块与导入 - -大型项目需要把代码拆成多个文件。Marqdo 用 **frontmatter 导入**和**点号寻址**组织模块。 - -## 11.1 Frontmatter 元信息 - -文件开头的成对 `---` 之间是 frontmatter,存放元信息(标题、描述、导入): - -```markdown ---- -title: 我的程序 -description: 描述文字 ---- -``` - -## 11.2 导入文件:`import 绑定:路径.mq.md` - -```markdown ---- -import: - text: lib/text.mq.md - time: lib/time.mq.md ---- -``` - -- `text` —— 绑定名(本地库名) -- `lib/text.mq.md` —— 目标文件路径 - -导入后得到一个**库(模块)绑定**,成员**不会**倒进全局。 - -中文等价:`导入 文本:lib/文本.mq.md`。 - -## 11.3 点号寻址调用:`库.成员` - -导入后用裸点号路径调用库成员: - -```markdown ---- -import: - time: lib/time.mq.md - json: lib/json.mq.md ---- - -# main - -**t = > time.now_unix** -**s = > time.format unix=`t` pattern="%Y-%m-%d"** -> print text=`s` -``` - -- `time.now_unix` —— 调用 `time` 库的 `now_unix` 函数 -- `time.format` —— 调用 `time` 库的 `format` 函数 - -**库名不是变量**:路径段是裸标识符,不加反引号。 - -## 11.4 三段路径:`库.类型.方法` - -```markdown ---- -import: - agent: ext/ai/agent.mq.md ---- - -# main - -**助手 = > agent.agent model="gpt-4o-mini"** # 库 → 类型:构造 -``` - -`agent.agent` —— `agent` 库中的 `agent` 类型(构造)。 - -## 11.5 短名:`import 绑定:库.成员` - -把库路径成员绑为本地短名: - -```markdown ---- -import: - time: lib/time.mq.md - fmt: time.format ---- - -# main - -**t = > time.now_unix** -**s = > fmt unix=`t` pattern="%Y-%m-%d"** -``` - -`fmt` 现在是 `time.format` 的短名。 - -## 11.6 方法调用 vs 库路径(Python 统一命名空间) - -对裸点号 `a.b`,规则是: - -- 若 `a` 是当前作用域的**局部变量** → **方法调用**(`a` 为接收者) -- 否则 → **库路径** - -| 写法 | 含义 | -|------|------| -| `time.parse` | 库路径(裸名,第一段非变量) | -| `` > `助手`.step `` | 独立 `>` 调用:实例方法(接收者反引号) | -| `**回复 = > 助手.step …**` | 粗体代码段内:`助手` 是变量 → 实例方法;否则 → 库路径 | - -```markdown ---- -import: - agent: ext/ai/agent.mq.md ---- - -# main - -**助手 = > agent.agent model="gpt-4o-mini"** -**out = > 助手.step task="你好"** # 助手是变量 → 方法调用 -``` - -## 11.7 完整示例:多模块程序 - -假设项目结构: - -```text -project/ -├── main.mq.md -├── lib/ -│ ├── 数学.mq.md -│ └── 问候.mq.md -``` - -`lib/数学.mq.md`: - -```markdown -## 加倍 - + `n` - -*n * 2* -``` - -`lib/问候.mq.md`: - -```markdown -## 你好 - + `谁` - -> print text=你好,`谁`! - -*None* -``` - -`main.mq.md`: - -```markdown ---- -import: - 数学: lib/数学.mq.md - 问候: lib/问候.mq.md ---- - -# main - -**结果 = > 数学.加倍 n=21** -> print text=`结果` - -> 问候.你好 谁=世界 -``` - -输出: - -```text -42 -你好,世界! -``` - -## 11.8 库路径解析 - -`lib/…` 按以下顺序解析: - -1. 环境变量 `MARQDO_LIB` -2. 当前目录下的 `lib/` -3. `marqdo` 可执行文件旁边的 `lib/`(及几个父目录) - -官方扩展(`ext/`)用 `marqdo ext add llm|agent|web|quantum` 安装,导入仍写 `import llm:ext/llm.mq.md` 等。 - -## 11.9 下一步 - -你已经能组织大型项目了。接下来学习[第 12 章:标准库](./12-标准库.md),使用官方能力。 diff --git a/doc/tutorial/12-标准库.md b/doc/tutorial/12-标准库.md deleted file mode 100755 index e041d04..0000000 --- a/doc/tutorial/12-标准库.md +++ /dev/null @@ -1,176 +0,0 @@ -# 第 12 章:标准库 - -Marqdo 内置函数无需导入即可使用;更丰富的能力通过导入 `lib/` 模块获得。 - -## 12.1 内置函数(无需导入) - -| 英文 | 中文 | 作用 | -|------|------|------| -| `print` | `打印` | 写标准输出(参数 `text` ≡ `内容`) | -| `input` | `输入` | 读一行(参数 `prompt` ≡ `提示`) | -| `len` | `长度` | 文本 / 集合长度(参数 `value` ≡ `值`) | -| `str` | `文本` | 转为显示文本(参数 `value` ≡ `值`) | -| `int` | `整数` | 转为整数(参数 `value` ≡ `值`) | - -```markdown -# main - -> print text=Hello - -**s = "Marqdo"** -**n = > len value=`s`** -> print text=长度:`n` -``` - -## 12.2 标准库模块 - -导入一个 `lib/` 文件,使用**该文件**的函数名: - -| 英文导入 | 中文导入 | 典型功能 | -|----------|----------|----------| -| `lib/text.mq.md` | `lib/文本.mq.md` | 文本处理(去空白、拆分、拼接) | -| `lib/table.mq.md` | `lib/表.mq.md` | 列表 / 字典元素更新 | -| `lib/fs.mq.md` | `lib/文件.mq.md` | 文件系统 | -| `lib/sys.mq.md` | `lib/系统.mq.md` | 进程 / 当前目录 / 加载环境变量 | -| `lib/plugin.mq.md` | `lib/插件.mq.md` | 加载原生 ABI 插件 | -| `lib/time.mq.md` | `lib/时间.mq.md` | 时间 / 格式化 | -| `lib/net.mq.md` | `lib/网络.mq.md` | HTTP(S) | -| `lib/json.mq.md` | — | JSON 解析 / 序列化 | -| `lib/math.mq.md` | `lib/数学.mq.md` | 数值、三角函数、随机、公式、绘图 | -| `lib/foreign.mq.md` | `lib/外联.mq.md` | 运行异种语言代码块 | - -> **语言一致性**:导入英文库文件,就用其英文 API;导入中文库文件,就用其中文 API。不要混用语言。 - -## 12.3 JSON 模块示例 - -`json` 模块负责**文本 ↔ 结构化数据**的序列化转换,以及把文本字符串里的 `\n` 等转义还原: - -| 函数 | 作用 | -|------|------| -| `json.parse` | 解析 JSON 文本 | -| `json.stringify` | 序列化为 JSON 文本 | -| `json.get` | 取字段(键) | -| `json.keys` | 取所有键 | -| `json.set` | 设字段 | -| `json.append` | 向列表追加 | - -```markdown ---- -import: - json: lib/json.mq.md ---- - -# main - -**obj = > json.parse text={"a":1}** -**out = > json.stringify value=`obj`** -> print text=`out` # {"a":1} - -**nl = > json.parse text={"n":"\n"}** -> print text=第一行[n](`nl`)第二行 # 换行还原 -``` - -> **字典操作**:本地字典的读取用链接取元 `[键](变量)`,**不要**用 `json.get`。`json.get` / `json.set` 仅用于跨文本边界的序列化场景(例如与外部 JSON API 交换数据时)。构造字典用 GFM 横表(见[第 9 章](./09-集合.md))。 -`json` 常用函数: - -| 函数 | 作用 | -|------|------| -| `json.parse` | 解析 JSON 文本 | -| `json.stringify` | 序列化为 JSON 文本 | -| `json.get` | 取字段(键) | -| `json.keys` | 取所有键 | -| `json.set` | 设字段 | -| `json.append` | 向列表追加 | - -## 12.4 文本模块示例 - -```markdown ---- -import: - text: lib/text.mq.md ---- - -# main - -**parts = > text.str_split s="a,b,c" sep=","** -> print text=`parts` - -**joined = > text.str_join xs=`parts` sep="-"** -> print text=`joined` # a-b-c -``` - -## 12.5 数学模块:公式与绘图 - -```markdown ---- -import: - math: lib/math.mq.md ---- - -# main - -**值 = > math.num value=3.5** -> print text=`值` -``` - -公式绑定: - -```markdown ---- -import: - math: lib/math.mq.md ---- - -# main - -`f` = -$$ -x^2 - 2 -$$ - -**_svg = > math.plot formula=`f` var=x min=-3 max=3** -``` - -空 RHS 赋值 + 后随 `$$…$$` 绑定一个公式值。 - -## 12.6 官方扩展库(`ext/`) - -扩展库不是 stdlib,需安装: - -```bash -marqdo ext list -marqdo ext add llm -marqdo ext add agent -marqdo ext add web -marqdo ext add quantum -``` - -导入仍写 `import …:ext/….mq.md`: - -```markdown ---- -import: - llm: ext/llm.mq.md ---- - -# main - -**模型 = > llm.llm model="gpt-4o-mini"** -``` -| 扩展 | 功能 | -|------|------| -| `llm` | 大模型对话 | -| `agent` | 文档驱动的智能体框架 | -| `web` | Web 应用 | -| `quantum` | 量子电路模拟 | - -## 12.7 查看库的精确 API - -打开 `lib/` 或 `ext/` 下对应的 `.mq.md` 文件,即可看到精确的 `##` / `#` 名称和参数。例如 `lib/json.mq.md` 顶层就是 `## parse`、`## stringify` 等。 - -## 12.8 下一步 - -你已经会使用标准库了。继续学习: - -- [第 13 章:命令行工具](./13-命令行工具.md) —— 运行、调试、扩展管理 -- [第 14 章:网络与 Web 扩展](./14-网络与Web扩展.md) —— `lib/net` 与 `ext/web` 实战 diff --git a/doc/tutorial/13-命令行工具.md b/doc/tutorial/13-命令行工具.md deleted file mode 100755 index 6d38268..0000000 --- a/doc/tutorial/13-命令行工具.md +++ /dev/null @@ -1,140 +0,0 @@ -# 第 13 章:命令行工具 - -Marqdo 提供一组命令行工具,覆盖运行、浏览、调试、发布全流程。 - -## 13.1 命令总览 - -```text -marqdo --version # 查看版本 -marqdo run 文件.mq.md # 运行程序 -marqdo view 路径 # 文档浏览器(默认端口 7429) -marqdo debug 路径 # 调试界面(默认端口 7430) -marqdo catalog 路径 -o 目录 # 生成 OKF 风格清单 -marqdo sync 路径 -o 目录 # catalog 的别名 -marqdo ext list # 列出扩展 -marqdo ext add llm|agent|web|quantum -marqdo ext remove llm|agent|web|quantum -``` - -## 13.2 运行程序:`run` - -```bash -marqdo run hello.mq.md -``` - -指定后端(树遍历默认 / 字节码): - -```bash -marqdo run hello.mq.md --backend bytecode -``` - -### 错误诊断 - -诊断信息格式:`path:line:col: message`(行 / 列从 1 开始)。 - -```text -error: hello.mq.md:5:1: undefined variable `x` -``` - -根据 `path:line:col` 定位并修复,再重新运行直到退出码为 0。 - -## 13.3 文档浏览器:`view` - -`view` 启动一个本地文档浏览器,把 `.mq.md` 渲染成可浏览的文档站: - -```bash -marqdo view public --no-open -``` - -浏览器打开后可看到: - -- Structure(结构) -- 函数大纲 / 搜索 -- Execution(执行) -- Variables(变量浮窗) - -## 13.4 调试器:`debug` - -```bash -marqdo debug public --no-open -``` - -提供独立调试页面,支持: - -- 断点 -- 单步执行 -- 局部变量查看 - -## 13.5 生成清单:`catalog` / `sync` - -从源码派生 OKF 风格的 YAML / Markdown 知识包: - -```bash -marqdo catalog public -o .marqdo -# 或 -marqdo sync public -o .marqdo -``` - -| 参数 | 默认 | 说明 | -|------|------|------| -| `PATH` | `.` | 工程根或含 `.mq.md` 的目录 | -| `-o` / `--out` | `.marqdo` | 输出目录 | - -产物:`catalog.yaml`、`index.md`、`modules/*.md` 等。 - -## 13.6 扩展管理:`ext` - -```bash -marqdo ext list -marqdo ext add llm -marqdo ext add agent -marqdo ext remove llm -``` - -扩展默认安装到 `~/.marqdo/ext`(或 `MARQDO_EXT`)。 - -## 13.7 标准库与可执行文件解析 - -- **标准库**:内置于二进制;磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。 -- **库路径解析**:`MARQDO_LIB` → 当前目录 `lib/` → 可执行文件旁 `lib/`。 - -## 13.8 证明定理表:`prove` - -知识文件里带定理表(`| 定理 | 结论 | 前提 | 策略 |`)的函数,可以用 -`marqdo prove` 生成 Lean 4 证明并自动判定真假: - -```bash -marqdo prove 审批.mq.md # 生成 Lean 模块 + 判定(有 Lean 时) -marqdo prove 审批.mq.md --json # 智能体可读的单个 JSON 报告 -marqdo prove emit 审批.mq.md # 只生成不判定 -marqdo prove audit 审批.mq.md # 只审查可证子集,不写盘 -marqdo prove --all skills/ # 目录模式:逐文件出证,整体取最差 -marqdo prove clean # 清空 .marqdo/prove -``` - -状态从强到弱:`proved`(Lean 证出)> `checked`(离线符号执行关闭)> -`unverified`(超出可证子集,诚实未知)> `rejected`(子集验收拒绝)> -`unproved`(反例)> `error`(判定层错误)。关键纪律: - -- **没有 Lean 也能跑**:离线符号执行给出 `checked`,但它不是 proved—— - 只是"在受限片段里符号地关掉了"。状态如实降级,绝不冒充证明。 -- **假定理必须红**:断言与执行语义矛盾的定理会得到反例(路径见证, - 如 `金额 = 10001`),退出码 1。 -- **单调性护栏**:离线说 `checked` 但 Lean 证不出(或反过来)→ - `error[proof.divergence]`,判定器缺陷优先于任何绿灯。 -- **证书缓存**:判定结果按源码+计划+库+版本哈希缓存于 `.marqdo/prove/`, - 重复运行毫秒级命中;`--no-cache` 绕过。 - -详见 [design/prove-cli.md](../design/prove-cli.md)(命令面、可证子集与判定管线)。 - -## 13.9 下一步 - -恭喜!你已经完成了 Marqdo 语法教程。你现在可以: - -- 写出带输入输出、函数、分支、循环的程序 -- 用表格组织列表、字典、记录 -- 用对象和方法做面向对象编程 -- 拆分模块、使用标准库和扩展 -- 用命令行工具运行、调试、发布 - -祝你在「代码即文档」的世界里愉快! diff --git a/doc/tutorial/14-网络与Web扩展.md b/doc/tutorial/14-网络与Web扩展.md deleted file mode 100755 index c51e8e4..0000000 --- a/doc/tutorial/14-网络与Web扩展.md +++ /dev/null @@ -1,217 +0,0 @@ -# 第 14 章:网络与 Web 扩展 - -> **现行作者面(2026-09-28 · ADR 0007)**:Document / Endpoint / Resource —— 见 [ext-web-artifact.md](../design/ext-web-artifact.md)。 -> 下文若仍出现 `compose_*` / `app.configure` / `web.db` 同文件混写,视为**历史示例**;DB → `ext/data`,鉴权 → `ext/security`,实时 → `ext/net`。 - -Marqdo 的网络能力分两层:**标准库 `lib/net`**(HTTP 客户端、cookie / multipart 解析)与**官方扩展 `ext/web`**(Document/Endpoint facade + 拆分后的 data/security/net)。分层的依据是「代码即文档」。 - -## 14.1 概览 - -| 能力 | 位置 | 典型 API | -|------|------|----------| -| HTTP(S) 客户端 | `lib/net` | `http_get` / `http_post` / `http_request` | -| Cookie / multipart | `lib/net` | `cookie_parse` / `multipart_parse` | -| Document / Endpoint | `ext/web` | `type: web\|endpoint` · `web.serve` · `web.render` · `web.inspect` | -| View 装配 | `ext/web` | `|type|slot|value|attrs|style|` → `web.render` | -| 数据库 | `ext/data` | `db` CRUD / txn | -| 表单 | `ext/data` | `form` | -| 鉴权 / RBAC / OIDC | `ext/security` | `auth` · `rbac` · `oidc` | -| WebSocket | `ext/net` | `websocket` | - -```bash -# 运行使用 ext/web 的程序前,先安装扩展 -marqdo ext add web -``` - -## 14.2 HTTP 客户端(`lib/net`) - -导入 `lib/net.mq.md`(中文 `lib/网络.mq.md`),用 `http_get` / `http_post` 发请求: - -```markdown ---- -import: - net: lib/net.mq.md ---- - -# main - -**resp = > net.http_get url="https://api.example.com/status"** -> print text=[status](`resp`) -``` - -`http_post` 默认以 JSON 提交,可用 `content_type=` / `headers=` 覆盖: - -```markdown -**body = > net.http_post url="https://api.example.com/echo" body={"msg":"hi"}** -> print text=`body` -``` - -> **字典操作**:返回值是字典(如 `resp`),用链接取元 `[键](resp)`,不要用 `json.get`。 - -### Cookie 解析 - -`cookie_parse` 把 `Cookie` 请求头或 `Set-Cookie` 响应头解析成列表: - -```markdown -**req = > net.cookie_parse text="session=abc123; theme=dark"** -> print text=[name]([1](`req`)) # session -> print text=[value]([1](`req`)) # abc123 - -**resp = > net.cookie_parse text="id=42; Path=/; HttpOnly; SameSite=Lax" is_response=True** -> print text=[http_only]([1](`resp`)) # True -``` - -### multipart 解析 - -`multipart_parse` 解析 `multipart/form-data` 正文(给定 `boundary`): - -```markdown -**parts = > net.multipart_parse body=`body` boundary="----WebKitFormBoundary"** -**field = [1](parts)** -> print text=[name](`field`) -``` - -## 14.3 网页应用(Artifact · ADR 0007) - -站点是一堆 `.mq.md`:**Document**(`type: web`)与 **Endpoint**(`type: endpoint`)。入口调用 `web.serve` 扫描目录并监听。完整设计见 [ext-web-artifact.md](../design/ext-web-artifact.md);示例 [marqdo-blog](../../examples/marqdo-blog/)。 - -### Document 首页 - -```markdown ---- -type: web -title: 我的站点 -route: / -method: GET -data_source: posts -data_order: -created_at -import: - web: ext/web/web.mq.md ---- - -# 我的站点 - -欢迎。下方卡片列表由 `data_source` 在服务时从数据库加载。 -``` - -### Endpoint - -```markdown ---- -type: endpoint -method: GET -path: /api/ping -request: none -response: json ---- - -# main - -`out` = - -| ok | service | -|----|---------| -| True | demo | - -*out* -``` - -### 服务入口 - -```markdown ---- -import: - web: ext/web/web.mq.md - posts: db/posts.mq.md ---- - -# main - -**store = > posts.open url="sqlite:data/site.db"** -> web.serve root="." host="127.0.0.1" port=18081 db=`store` static_dir="public" -``` - -离线预览可用 View 表 + `web.render`: - -```markdown -`nodes` = - -| type | slot | value | attrs | style | -|------|------|-------|-------|-------| -| title | title | Marqdo | | title | - -**html = > web.render nodes=`nodes` title="preview"** -> print text=`html` -``` - -### 数据库(`ext/data`) - -```markdown ---- -import: - data: ext/data/db.mq.md ---- - -# main - -**store = > data.db url="sqlite:site.db"** -> `store`.init name=articles fields=`字段表` -> `store`.insert table=articles rows=`数据` -**rows = > `store`.select table=articles limit=10** -``` - -## 14.4 鉴权(`ext/security`) - -HTTP 门禁与登录走 `ext/security`(`auth` / `rbac` / `oidc`),再用 `web.use` 挂中间件表;勿再写 `app.configure`。独立脚本可用: - -```markdown ---- -import: - rbac: ext/security/rbac.mq.md ---- - -# main - -**gate = > rbac.rbac** -**r = > `gate`.can permissions="desk:access" needed="desk:access"** -> print text=[allowed](`r`) -``` - -## 14.5 WebSocket(`ext/net`) - -实时能力在 `ext/net`(如 `websocket`),与 Document 站点并列导入,不再挂在 `web.app` 的 junk drawer 上。 - -## 14.6 字典操作:用表格与取元,不用 `json.get`/`json.set` - -Marqdo 用 **GFM 表格**构造字典、用 **链接取元 `[键](变量)`** 读取字典——这是语言原生能力,是「代码即文档」的体现。**不要**用 `json.get` / `json.set` 读写本地字典(那只用于文本 ↔ 结构化的序列化,如 `json.parse` / `json.stringify`)。 - -构造字典(横表,≥2 列 + 1 行): - -```markdown -`配置` = - -| 主机 | 端口 | -|------|------| -| 127.0.0.1 | 18081 | -``` - -读取字典(取元): - -```markdown -> print text=[主机](`配置`) # 127.0.0.1 -> print text=[端口](`配置`) # 18081 -``` - -读取函数返回的字典字段,同样直接取元: - -```markdown -**login = > `auth`.login username="admin" password="secret"** -> print text=[ok](`login`) # 而不是 json.get value=`login` key="ok" -``` - -## 14.7 下一步 - -你已经掌握 Marqdo 的网络与 Web 能力。继续探索: - -- [第 13 章:命令行工具](./13-命令行工具.md) —— `marqdo ext` 管理扩展 -- 设计文档:[`doc/design/ext-web-net.md`](../design/ext-web-net.md) —— 本波次网络扩展的完整设计与边界判定 diff --git a/doc/tutorial/15-常见陷阱.md b/doc/tutorial/15-常见陷阱.md deleted file mode 100755 index 268bc8e..0000000 --- a/doc/tutorial/15-常见陷阱.md +++ /dev/null @@ -1,418 +0,0 @@ -# Marqdo 常见陷阱手册 - -| | | -|---|---| -| 状态 | **Accepted · 使用向**(全部条目在 `marqdo 1.5.2` 上实测) | -| 日期 | 2026-10-22 | -| 来源 | qdagent 重构期间(文档门禁 + 输出契约)逐条踩坑复现 | -| 关联 | [02-基本语法.md](02-基本语法.md) · [06-函数.md](06-函数.md) · [11-模块与导入.md](11-模块与导入.md) · [design/markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md) | -| 缺陷来源 | [research/qdagent-refactor-defects-2026-10.md](../research/qdagent-refactor-defects-2026-10.md) | - ---- - -## 0. 怎么用这份文档 - -不是语言教程,而是**避坑清单**。每条都给出: - -- **现象**:你会看到什么(报错原文) -- **原因**:为什么这样 -- **改法**:可直接抄的写法 - -全部结论来自实测,不是推测。文中「✅ 安全」表示实测通过,不要靠猜。 - ---- - -## 1. 写文档(最常见的一类) - -Marqdo 是「文档即程序」,所以**文档写得像正常中文**恰恰是最容易出错的地方。 -门禁类工具(如 qdagent 的 `execution/docgate`)主要就是在防这些。 - -### 1.1 行首数字 → 一定报错 ⚠️ 最高频 - -**现象** - -``` -error: a.mq.md:7:1: unrecognized statement: 2026 年发布。 -error: b.mq.md:7:1: unrecognized statement: 42 -error: c.mq.md:7:1: unrecognized statement: 9 号是数字。 -``` - -**原因** - -行首是数字时,该行被当成**语句**去解析(数字是字面量表达式),而非叙述。 - -**改法** - -以文字开头即可。中文里「2026 年」「42 个」「3 个要点」「1. 第一步」这类写法极常见, -凡是整行以数字起头都会被拦: - -```markdown -# 结论 - -发布年份是 2026 年。 ← 把数字后移 -共收录 42 条。 ← 不要以 42 起行 -有三个要点需要说明。 ← 不要写 "3 个要点…" 起行 -``` - -确需保留行首数字时,包进行内代码或围栏: - -```markdown -`2026` 是发布年份。 - -````markdown -42 -```` - -### 1.2 行首 `+` → 报错 - -**现象** - -``` -error: tmm.mq.md:7:1: unrecognized statement: + 加号 -``` - -**原因**:`+` 是形参声明与列表语法的前导符。 - -**改法**:叙述区不要用 `+ ` 起行做列表;需要列表用 `- `(见下条)。 - -### 1.3 `-` / `>` / `|` / `[` 起行:**多数情况安全** - -这一条要纠正一个常见误解。实测: - -| 行首 | 叙述区 | 说明 | -|------|--------|------| -| `- 列表项` | ✅ 安全 | 不构成有效 foreach → 跳过 | -| `> 引用` | ✅ 安全 | 无对应函数时不当调用 | -| `\| a \| b \|` | ✅ 安全 | 未绑定表不算语句 | -| `[{"a":1}]` | ✅ 安全 | 无归属的链接索引 → 跳过 | -| `9 号是数字。` | ❌ 报错 | 数字字面量是真语句 | -| `+ 加号` | ❌ 报错 | 前导符是真语法 | - -但**在函数体内且上下文成立时**它们会真的执行(例如 `- [`x`](`xs`)` 是真循环)。 -判断标准:**能不能被解析成一条完整语句**。能,就执行;不能,就当叙述跳过。 - -### 1.4 未闭合引号 → 静默吞行 ⚠️ 危险 - -**现象** - -```markdown -**s = "abc -> print text=hi -*"" -``` - -输出 `hi`,**没有报错**,`s` 那一行凭空消失。 - -**原因**:未闭合的双引号让该行被当作叙述而不是语句。 - -**影响**:这类错误不会中断程序,只会让变量「不存在」,随后在别处报 -`undefined variable`,把排查方向引偏。 - -**改法**:写完立即 `marqdo check`,或注意「变量莫名未定义」时先看引号是否配对。 - ---- - -## 2. 变量作用域 - -### 2.1 模块级变量在函数之间**不可见** - -**现象** - -```markdown -# main - -**g = 10** -> show -*"" - -## show - -> print text=`g` -*None* -``` - -``` -error: t1.mq.md:13:1: undefined variable `g` -``` - -兄弟函数之间同样不可见: - -```markdown -## a - -**x = 1** -> b -*None* - -## b - -> print text=`x` ← undefined variable `x` -*None* -``` - -**原因**:每个 `##` 是独立作用域;`# main` 与各函数之间**不共享变量**,只共享参数与返回值。 - -**改法**:一切跨函数数据走**参数与返回值**。 - -```markdown -## show - + `g` - -> print text=`g` -*None* - -# main - -**g = 10** -> show g=`g` -*"" -``` - -### 2.2 顶层不许有裸语句 - -**现象** - -``` -error: e.mq.md: 5:1: expected heading (`#` object or `##` function), got: **x = 1** -``` - -**原因**:文件顶层只能是 frontmatter、叙述、`#` 对象、`##` 函数。 -语句必须放进 `# main` 或某个 `##` 里。 - -**改法**: - -```markdown ---- -title: e ---- - -**x = 1** ← 挪走 - -# main - -**x = 1** -> print text=ok -*"" -``` - -### 2.3 `table.put` **不**原地修改 - -**现象** - -```markdown -**m = > json.parse text={"n":0}** -**r = > table.put in=`m` at="n" value=1** -``` - -之后 `m` 仍是 `{"n":0}`,`r` 才是 `{"n":1}`。 - -**影响**:想靠 `> table.put in=`state` ...` 累积状态**不会生效**, -计数永远是 0,且不报错。 - -**改法**:接住返回值。 - -```markdown -**state = > table.put in=`state` at="ok_n" value=`n2`** -``` - ---- - -## 3. 函数 - -### 3.1 函数名含空格 → 定义成功,**调用必崩** ⚠️ 缺陷 - -**现象** - -```markdown -## 加一 号 - + `n` - -*`n` + 1* - -# main - -**r = > 加一 号 n=1** -``` - -``` -error: t8.mq.md:13:1: undefined variable `号` -``` - -英文同样: - -```markdown -## my func -``` -调用 → `undefined variable func`。 - -**原因**:调用处按空格切分,第一个词当函数名,其余词当位置参数或变量插值。 -定义侧允许空格,**两侧不对称**。 - -**改法**:函数名**不要含空格**。用连字符、下划线或去掉空格: - -```markdown -## 加一_号 -## assert-no-main -## my_func -``` - -命名建议:中文标识符直接连写(`断言干净`、`门禁沉淀`),英文用下划线。 - -### 3.2 函数内变量名别和叙述里的裸词撞车 - -叙述里的裸词一般是安全的(实测 `大约 head 的位置。` 不报错)。 -但**在函数名或调用参数位置**出现未定义标识符会立刻报 `undefined variable`。 -判断标准同上:会被当成语句/表达式的上下文才插值。 - ---- - -## 4. 字符串与拼接 - -### 4.1 引号内 `**`、`|`、`#` 多数安全,不必恐慌 - -实测以下全部 ✅: - -```markdown -**s = "a ** b"** -**s = "a | col | b"** -**s = "abc # main def"** -**s = "sum: total items"** -``` - -只有**引号不配对**才会出问题(回到 §1.4)。 - -### 4.2 拼装文档正文时,`"`、`*`、`|` 仍建议转义 - -当你用字符串拼接**生成一份 `.mq.md`**(而不是自己写)时,字面量容易提前闭合标记。 -稳妥写法是用 Unicode 转义: - -```markdown -**qt = "\u{22}"** -**star = "\u{2a}"** -**pipe = "\u{7c}"** -**nl = "\n"** - -**doc = "---" + `nl` + "title: x" + `nl` + "---" + `nl` + `nl` + "# main" + `nl` + `nl`** -**doc = `doc` + "> print text=" + `qt` + "hi" + `qt` + `nl` + `star` + "None" + `star` + `nl`** -``` - -### 4.3 heredoc 写含 `\n` 的 `.mq.md` 会自毁 - -用 `cat <<'EOF'` 写文件时,若内容本身包含反斜杠转义序列,shell 虽不展开, -但若中间出现 `EOF` 相邻的变体或内容被后续 `sed`/脚本改写,极易截断。 -**建议**:生成 .mq.md 用脚本(Python/Node)或编辑器,别用长 heredoc。 - ---- - -## 5. 导入 - -### 5.1 相对路径以**当前文件**为基准 - -`execution/a.mq.md` 里导入同目录的 `b.mq.md`,写 `import b:b.mq.md`。 -写 `import b:execution/b.mq.md` 或 `../execution/b.mq.md` 都可能失败: - -``` -error: cannot resolve import `../execution/docgate.mq.md` from -``` - -**跨目录**才用 `..`: - -```markdown -import: - ctx: ../knowledge/context.mq.md -``` - -### 5.2 库名必须导入,不能用裸名 - -``` -error: unknown library `json` (import it in frontmatter) -``` - -```markdown -import: - json: lib/json.mq.md -``` - -标准库函数要**带库名前缀**:`json.parse`、`txt.contains`、`table.put`。 -裸 `str_split`、`contains` 会报 `unknown function`。 - ---- - -## 6. 常见函数签名(易记错) - -| 函数 | 参数名 | 备注 | -|------|--------|------| -| `txt.contains` | `text`, `sub` | 是 `sub` 不是 `part` | -| `table.put` | `in`, `at`, `value` | 返回新表,见 §2.3 | -| `table.get` | `map`, `key` | 取可选键,键缺失不崩 | -| `json.get` | `value`, `key` | 同上 | -| `split` | `value`, `sep` | 内置,无库名前缀 | -| `sys.env_get` | `name` | | - -**取元 `[key](map)` 是断言式**:键缺失直接 `missing map key 'error'`。 -取「可能不存在」的键一律用 `table.get` / `json.get`。 - ---- - -## 7. 结构 - -### 7.1 `# main` 的体不会被 `##` 截断 - -```markdown -# main - -> print text=first - -## helper - -*1* - -> print text=last ← 仍属于 main,会执行 -*"" -``` - -输出 `first` `last`。**但可读性差**,建议 `# main` 只做编排,函数都放前面。 - -### 7.2 `1.` `2.` `3.` 是一条 if/elif/else 链 - -```markdown -1. `a` > 10 - ... -2. `a` > 5 - ... -3. * - ... -``` - -两段独立的 `1.` 是**两个** if,不是链。嵌套靠缩进。 -`2. *` 是 else 分支。 - ---- - -## 8. 自查清单 - -提交前跑一遍: - -```bash -marqdo check 你的文件.mq.md # 契约/语法检查 -marqdo run 你的文件.mq.md # 真跑,退出码 0 才算过 -``` - -逐项确认: - -- [ ] 叙述区没有以**数字**或 `+` 起头的行 -- [ ] 所有双引号成对 -- [ ] 函数名不含空格 -- [ ] 没有依赖「函数间共享变量」 -- [ ] `table.put` 的返回值都接住了 -- [ ] import 路径以当前文件为基准 -- [ ] 可选键用 `table.get` / `json.get`,不用 `[key](map)` -- [ ] 文件有 `# main`,且 `# main` 无副作用 - ---- - -## 变更记录 - -| 日期 | 变更 | -|------|------| -| 2026-10-22 | 首次发布;全部条目在 1.5.2 实测 | diff --git a/doc/tutorial/README.md b/doc/tutorial/README.md deleted file mode 100755 index de0e1c4..0000000 --- a/doc/tutorial/README.md +++ /dev/null @@ -1,101 +0,0 @@ -# Marqdo 语法教程 - -> **代码即文档,文档即代码。** Marqdo 把 Markdown 的标记当作编程语法:同一个 `.mq.md` 文件既是给人读的文稿,也是给机器跑的程序。 - -本教程面向所有读者——从没写过代码的文档作者,到熟悉 Python 的工程师。每章都配有可直接运行的完整示例。 - -**现行映射是 markup v0.3**:`**…**` = 代码(赋值 / 调用),`*…*` = 返回;集合取元优先 `[键](集合)`。 - -## 目录 - -### 第一部分 · 入门 - -| 章节 | 内容 | 你能学会什么 | -|------|------|-------------| -| [第 1 章:Marqdo 是什么](./01-入门.md) | 理念、安装、第一个程序、运行 | 写出并运行你的第一个 `.mq.md` 程序 | -| [第 2 章:基本语法](./02-基本语法.md) | 文件结构、注释、标识符、字面量 | 看懂 `.mq.md` 里哪些是代码、哪些是注释 | - -### 第二部分 · 变量与数据 - -| 章节 | 内容 | 你能学会什么 | -|------|------|-------------| -| [第 3 章:变量与赋值](./03-变量与赋值.md) | 绑定、变量引用、字符串 | 存取值,拼接文本 | -| [第 4 章:输出与输入](./04-输出与输入.md) | `print` / `打印`、`input` / `输入` | 与用户交互 | -| [第 5 章:运算符与比较](./05-运算符与比较.md) | 算术、比较、逻辑 | 计算与判断 | - -### 第三部分 · 流程控制 - -| 章节 | 内容 | 你能学会什么 | -|------|------|-------------| -| [第 6 章:函数](./06-函数.md) | 定义、参数、返回值、括号调用 | 封装可复用逻辑 | -| [第 7 章:条件分支](./07-条件分支.md) | `1.` `2.` 分支、else | 让程序根据条件走不同路线 | -| [第 8 章:循环](./08-循环.md) | `-` 遍历、`-` while | 重复执行 | - -### 第四部分 · 数据集合 - -| 章节 | 内容 | 你能学会什么 | -|------|------|-------------| -| [第 9 章:集合(表格)](./09-集合.md) | 列表、字典、记录、链接取元 | 用 Markdown 表格组织数据 | - -### 第五部分 · 面向对象与模块 - -| 章节 | 内容 | 你能学会什么 | -|------|------|-------------| -| [第 10 章:对象与方法](./10-对象与方法.md) | `#` 类型、构造、方法、继承 | 面向对象编程 | -| [第 11 章:模块与导入](./11-模块与导入.md) | frontmatter、import、库路径、短名 | 组织大型项目 | - -### 第六部分 · 进阶 - -| 章节 | 内容 | 你能学会什么 | -|------|------|-------------| -| [第 12 章:标准库](./12-标准库.md) | 内置函数、`lib/` 模块 | 直接使用官方能力 | -| [第 13 章:命令行工具](./13-命令行工具.md) | `run` / `view` / `debug` / `catalog` | 运行、浏览、调试、发布 | -| [第 14 章:网络与 Web 扩展](./14-网络与Web扩展.md) | `lib/net`、`ext/web`、鉴权、WebSocket | 构建 HTTP 客户端与网页应用 | -| [第 15 章:常见陷阱](./15-常见陷阱.md) | 行首数字、作用域、空格函数名、导入路径等实测坑 | 避开高频错误,提交前自查 | - ---- - -## 快速示例 - -一个完整的 Marqdo 程序长这样: - -```markdown -# main - -礼貌 [问候] World - -## 问候 - + `谁` - + `礼貌`=False - -1. `礼貌` - > print text=您好,`谁`! -2. * - > print text=Hello, `谁`! - -*None* - -## 加一 - + `n` - -*n + 1* -``` - -- `# main` —— 入口 -- `礼貌 [问候] World` —— 方括号标记调用(前导词 → `礼貌=True`) -- `## 问候` + `+ `谁`` —— 定义函数及其参数 -- `> print text=…` —— 输出(副作用,是普通函数) -- `*n + 1*` —— 返回值(斜体) -- `*None*` —— 无值收束并结束函数体 - ---- - -## 运行方式 - -```bash -marqdo run 文件.mq.md -``` - -更多运行、浏览、调试、发布方式见 [第 13 章](./13-命令行工具.md)。 - -> **提示**:语法宪法见 [`doc/design/markdown-mapping-v0.3.md`](../design/markdown-mapping-v0.3.md);本教程是它的通俗讲解版。 diff --git a/doc/verification/skill-proof-theory.md b/doc/verification/skill-proof-theory.md deleted file mode 100755 index 6bb212c..0000000 --- a/doc/verification/skill-proof-theory.md +++ /dev/null @@ -1,78 +0,0 @@ -# 判定库 `MarqdoProof.lean` 的形式化说明 - -> 本文是 [design/prove-cli.md](../design/prove-cli.md) §4–§5 的配套理论摘要: -> 生成文件依赖哪些库事实、离线判定凭什么与 Lean 单调一致、边界在哪里。 -> 库本体:[skill-proof/MarqdoProof.lean](skill-proof/MarqdoProof.lean) -> (由 `marqdo prove` 内嵌携带,`scripts/check-proof-library.sh` 校验一致性)。 - -## 1. 语义模型 - -生成文件把每个函数降级为纯 Lean 定义: - -```lean -def «模块.函数» (env : Env) («轨迹» : List Op) («参数» : Val)… : Val × List Op -``` - -- `Val`:8 形状和(none/int/num/bool/text/list/map + formula/code 边界), - 与解释器 `value::Value` 一一对应(T4 差分一致性测试锁定)。 -- `env : Env`:不透明操作的答案函数。**调用者的定理以 env 为全称量词**—— - 证出即"对任意环境实现成立",这正是 assume-guarantee 的保守形态。 -- 不透明操作 = `Op.«调用_显示名»` 构造器 + 追加轨迹;操作名用链接显示文本, - 与定理表里 `包含(轨迹, "显示名")` 的写法一致。 -- 库函数面:`mqAdd/mqSub/mqMul/mqDiv`(int 面,除零→0,已记录偏差)、 - `mqGt/mqGe/mqLt/mqLe/mqEq`(decide 编码)、`mqAccess`(映射字段读取, - 方程友好)、`mqResultOk/mqResultError/mqValueOr`(lib/result 结构)。 - -## 2. 定理形状与判定 - -每条定理表行生成: - -```lean -theorem «模块.函数.定理名» (env : Env) («参数» : Val)… : - (前提 → True) → - ((«结果», «轨迹») = «模块.函数» env [] «参数»…) → - mqTruth «结论的 Lean 编码» := by - intro … h_run - unfold «模块.函数» at h_run - try split at h_run -- 按最大 if 嵌套深度重复 - all_goals (simp_all [域引理]; try omega) -``` - -- `decided_by = "lean"`:Lean 内核接受 ⇒ `proved`;`sorry` ⇒ `unverified`; - 报错 ⇒ `unproved`(错误指回定理表行)。 -- 策略 `none`:定理生成但主体 `sorry`,状态恒 `unverified`——绝不冒充。 - -## 3. 离线判定(F1–F5)与单调性论证 - -离线判定器对同一 IR 做符号执行,路径记录 (路径条件, 结果, 轨迹, 变量)。 -它与 Lean 的对应关系是**逐构造镜像**: - -| 离线闭包理由 | Lean 侧对应 | 单调性依据 | -|---|---|---| -| F1 路径枚举穷尽 | `split at h_run` 产生的同一组目标 | 同一 IR 树,分支集合相同 | -| F2 轨迹形状(包含/长度) | `(轨迹.map Op.name).contains` / `List.length` simp | 字面轨迹的列表运算两侧同构 | -| F3 构造器结构求值 | `mqResultOk/mqResultError/mqValueOr` + `mqAccess` simp 方程 | 同一套库定义;结构字面归约是计算的 | -| F4 自由原子 | split 后假设里的同一原子(`hypothesis` 关闭) | 只承认路径条件中字面出现的原子;路径反例含自由原子时放弃见证(保守) | -| F5 区间字面重述 | split 后假设直接就是结论(`hypothesis`) | 字面匹配,无推理步 | -| F5 区间违反(反例) | 无对应(Lean 同样证不出) | 反例只产生 `unproved`,不产生绿灯;见证 = 区间端点 | -| 不可行路径跳过 | split 后假设矛盾(互斥比较引理 `.elim` + omega) | 前提 ∩ 路径条件为空 ⇒ 该分支假设集 Lean 侧同样矛盾 | - -**单调性护栏**:有 Lean 时逐定理复核。离线 `checked` 而 Lean 关不掉,或 -离线反例被 Lean 证出 ⇒ `error[proof.divergence]`,永不落绿。护栏使 -"离线比 Lean 乐观"成为运行时可见错误而非静默错误;40 夹具语料库 -(`tests/prove_corpus.rs`)在 CI 强制 `offline_checked ⊆ lean_proved`。 - -**已知保守边界**(离线能、Lean 脚本不能,因此离线也必须不做): - -- 区间**蕴含**(`金额 > 10000 ⊢ 金额 > 9999`):数学上真,但当前脚本没有 - Val 比较的传递引理,simp+omega 关不掉 ⇒ 离线同样 `unverified` - (`f5_interval_closure_scope` 单测锁定)。库补传递引理后两侧同时放开。 -- 多变量线性、非线性、文本相等:超出 F5 单变量区间 ⇒ `unverified`; - Lean 侧若能证则升级 `proved`(允许,这是"弱判定被强判定确认")。 - -## 4. 证书与缓存 - -证书记录:claim id、结论、策略、状态、`decided_by`(lean/trace/none)、 -证据(Lean 报错或离线见证)、库与模块 sha256、Lean 版本、CLI 版本。 -缓存键 = 上述全部的 sha256 ⇒ 任何一侧变化自动失效,命中即跳过判定。 -证书是**证据陈述**("这次判定是这样"),不是正确性保证——与设计 §0 契约 1 一致。 diff --git a/doc/verification/skill-proof/MarqdoEffects.lean b/doc/verification/skill-proof/MarqdoEffects.lean deleted file mode 100644 index ff805f3..0000000 --- a/doc/verification/skill-proof/MarqdoEffects.lean +++ /dev/null @@ -1,82 +0,0 @@ -/- Abstract stateful ABI and bounded-loop semantics. - These are proof rules, not an axiom that an arbitrary ABI plugin - satisfies its declared contract. Implementation witnesses are required. -/ -namespace MarqdoEffects - -inductive Outcome (σ α ε : Type) where - | ok : α → σ → Outcome σ α ε - | error : ε → σ → Outcome σ α ε - | unknown : Outcome σ α ε - -def bind {σ α β ε : Type} - (first : Outcome σ α ε) - (next : α → σ → Outcome σ β ε) : Outcome σ β ε := - match first with - | .ok value state => next value state - | .error e state => .error e state - | .unknown => .unknown - -structure AbiContract (σ α β : Type) where - requires : σ → α → Prop - ensures : σ → α → σ → β → Prop - -def Implements {σ α β ε : Type} - (run : σ → α → Outcome σ β ε) - (contract : AbiContract σ α β) : Prop := - ∀ state arg, contract.requires state arg → - ∃ value updated, run state arg = .ok value updated ∧ - contract.ensures state arg updated value - -theorem impl_requires_witness {σ α β ε : Type} - (run : σ → α → Outcome σ β ε) (contract : AbiContract σ α β) - (h : Implements run contract) (state : σ) (arg : α) - (pre : contract.requires state arg) : - ∃ value updated, run state arg = .ok value updated := by - obtain ⟨v, s, hr, _⟩ := h state arg pre - exact ⟨v, s, hr⟩ - --- The plugin's failure case remains observable. A declared contract alone --- never rules out this case, unless a concrete implementation proof exists. -theorem error_not_abi_success {σ α ε : Type} - (reason : ε) (state : σ) : - ¬ (∃ v s, (Outcome.error reason state : Outcome σ α ε) = - Outcome.ok v s) := by - intro h - obtain ⟨v, s, hs⟩ := h - cases hs - -theorem unknown_not_abi_success {σ α ε : Type} : - ¬ (∃ v s, (Outcome.unknown : Outcome σ α ε) = - Outcome.ok v s) := by - intro h - obtain ⟨v, s, hs⟩ := h - cases hs - -theorem bind_preserves_error {σ α β ε : Type} - (next : α → σ → Outcome σ β ε) (reason : ε) (state : σ) : - bind (Outcome.error reason state) next = Outcome.error reason state := by - rfl - -theorem bind_preserves_unknown {σ α β ε : Type} - (next : α → σ → Outcome σ β ε) : - bind Outcome.unknown next = Outcome.unknown := by - rfl - --- Running out of fuel is UNRESOLVED, not a proof of termination or divergence. -def runFuel {σ ε : Type} - (step : σ → Outcome σ σ ε) : Nat → σ → Outcome σ σ ε - | 0, _ => .unknown - | n + 1, state => - match step state with - | .ok _ updated => runFuel step n updated - | .error e updated => .error e updated - | .unknown => .unknown - -theorem fuel_zero_not_success {σ ε : Type} - (step : σ → Outcome σ σ ε) (state : σ) : - ¬ (∃ v s, runFuel step 0 state = Outcome.ok v s) := by - intro h - obtain ⟨v, s, hs⟩ := h - cases hs - -end MarqdoEffects diff --git a/doc/verification/skill-proof/MarqdoModularProof.lean b/doc/verification/skill-proof/MarqdoModularProof.lean deleted file mode 100644 index cf80e9b..0000000 --- a/doc/verification/skill-proof/MarqdoModularProof.lean +++ /dev/null @@ -1,128 +0,0 @@ -/- - Core assume–guarantee composition lemma for Marqdo module contracts. - - This checks the *logic* of composing contracts, NOT that a particular - Marqdo function implements one. The compiler must separately establish - implementation correspondence and the call-site bridge obligation. --/ - -namespace MarqdoModularProof - -structure Contract (α β : Type) where - requires : α → Prop - ensures : α → β → Prop - -def Implements {α β : Type} (f : α → β) (c : Contract α β) : Prop := - ∀ x, c.requires x → c.ensures x (f x) - -def composed {α β γ : Type} - (first : Contract α β) (second : Contract β γ) : Contract α γ where - requires := first.requires - ensures := fun x z => - ∃ y, first.ensures x y ∧ second.ensures y z - --- Caller obligation is explicit. In particular, callee contract validity --- alone does not establish the precondition of the following component. -theorem compose_sound {α β γ : Type} - (f : α → β) (g : β → γ) - (first : Contract α β) (second : Contract β γ) - (hf : Implements f first) - (hg : Implements g second) - (bridge : ∀ x, first.requires x → - first.ensures x (f x) → second.requires (f x)) : - Implements (fun x => g (f x)) (composed first second) := by - intro x hx - have hfirst := hf x hx - have hnext := hg (f x) (bridge x hx hfirst) - exact ⟨f x, hfirst, hnext⟩ - --- Trust-boundary test: the bridge is genuinely needed. Without it, --- the conclusion would fail for suitable partial contracts. -example : - ¬ (∀ (f : Nat → Nat) (g : Nat → Nat) - (first : Contract Nat Nat) (second : Contract Nat Nat), - Implements f first → - Implements g second → - Implements (fun x => g (f x)) (composed first second)) := by - intro h - let f : Nat → Nat := fun _ => 0 - let g : Nat → Nat := fun y => y - let first : Contract Nat Nat := { - requires := fun _ => True - ensures := fun _ _ => True - } - let second : Contract Nat Nat := { - requires := fun y => y = 1 - ensures := fun _ z => z = 1 - } - have hf : Implements f first := by - intro _ _ - trivial - have hg : Implements g second := by - intro y hy - simpa [second, g] using hy - have hcomp := h f g first second hf hg - have target := hcomp 0 True.intro - cases target with - | intro y hpair => - have impossible : (0 : Nat) = 1 := by - simpa [second, g, f] using hpair.right - exact Nat.zero_ne_one impossible - --- Execution is a *partial* result: host/plugin failures and divergence --- must remain visible. Loops/recursion can be reasoned about only after --- separate termination proofs, and ABI effects require a proven contract. -inductive Exit (α ε : Type) where - | ok (value : α) - | error (reason : ε) - | diverged - -def sequence {α β ε : Type} - (first : Exit α ε) (next : α → Exit β ε) : Exit β ε := - match first with - | .ok value => next value - | .error e => .error e - | .diverged => .diverged - -structure TotalContract (α β : Type) where - requires : α → Prop - ensures : α → β → Prop - -def Satisfies {α β ε : Type} - (run : α → Exit β ε) (c : TotalContract α β) : Prop := - ∀ x, c.requires x → ∃ y, run x = .ok y ∧ c.ensures x y - -def combined {α β γ : Type} - (first : TotalContract α β) - (second : TotalContract β γ) : TotalContract α γ where - requires := first.requires - ensures := fun x z => ∃ y, first.ensures x y ∧ second.ensures y z - -theorem total_sequence_sound {α β γ ε : Type} - (f : α → Exit β ε) (g : β → Exit γ ε) - (cf : TotalContract α β) (cg : TotalContract β γ) - (hf : Satisfies f cf) - (hg : Satisfies g cg) - (bridge : ∀ x y, cf.requires x → cf.ensures x y → - cg.requires y) : - Satisfies (fun x => sequence (f x) g) (combined cf cg) := by - intro x hx - obtain ⟨y, hrunF, hpostF⟩ := hf x hx - obtain ⟨z, hrunG, hpostG⟩ := hg y (bridge x y hx hpostF) - refine ⟨z, ?_, ⟨y, hpostF, hpostG⟩⟩ - simpa [sequence, hrunF] using hrunG - --- A crashing plugin and a diverging loop cannot satisfy a total contract. -theorem error_not_success {α ε : Type} (e : ε) : - ¬ (∃ v : α, Exit.error e = Exit.ok v) := by - intro h - obtain ⟨v, hv⟩ := h - cases hv - -theorem diverged_not_success {α ε : Type} : - ¬ (∃ v : α, (Exit.diverged : Exit α ε) = Exit.ok v) := by - intro h - obtain ⟨v, hv⟩ := h - cases hv - -end MarqdoModularProof diff --git a/doc/verification/skill-proof/MarqdoProof.lean b/doc/verification/skill-proof/MarqdoProof.lean deleted file mode 100755 index 852b4e6..0000000 --- a/doc/verification/skill-proof/MarqdoProof.lean +++ /dev/null @@ -1,202 +0,0 @@ -/- -MarqdoProof:`marqdo prove` 生成代码的语义底座(设计 §6.2,无公理)。 - -原则: -- `Val` 是 Marqdo 值的忠实模型;每个 `mq*` 辅助函数对应 Marqdo 运行时语义的一个片段。 -- 不出现 `axiom`、不出现 `opaque`:外部操作是 `Env := Op → Val` 参数(每个生成文件 - 自带 `abbrev Env := Op → Val`,因为 `Op` 构造器集合是每文件独立的)。 -- 定理陈述把"信任了什么"写清楚:对任意 `env` 成立的命题,只依赖这里给出的方程。 --/ - -namespace MarqdoProof - -/-- Marqdo 值模型(§6.2;`text` 是发射器的真实命名,设计文档起草时的 `str` 已修订)。 -/ -inductive Val where - | none : Val - | int : Int → Val - | num : Float → Val - | bool : Bool → Val - | text : String → Val - | list : List Val → Val - | map : List (String × Val) → Val - deriving Repr, BEq - -/-- 定理命题包装:`Bool` 语义上的"为真"。 -/ -def mqTruth (b : Bool) : Prop := b = true - -/-- 映射字段读取(`结果.ok` 等);缺失字段 → `none`(与运行时 access 一致)。 -按表项递归, simp 方程友好(`mqAccess (mqResultOk v) "ok"` 直接化到 `.bool true`)。 -/ -def mqAccess : Val → String → Val - | .map [], _ => .none - | .map ((k, v) :: rest), k' => if k == k' then v else mqAccess (.map rest) k' - | _, _ => .none - --- ---------------------------------------------------------------- 算术 - -/-- 显示串:标量与解释器 `Value::as_display` 对齐(T4 差分一致性)。 -容器做一层显示(值经 mqDisplayScalar),嵌套容器超出 `+` 片段—— -记录为有意简化,语料不依赖嵌套容器拼接。非递归 ⇒ 无终止性负担。 -/ -def mqDisplayScalar : Val → String - | .int n => toString n - | .num x => toString x - | .bool b => if b then "True" else "False" - | .text s => s - | _ => "…" - -def mqDisplay : Val → String - | .int n => toString n - | .num x => toString x - | .bool b => if b then "True" else "False" - | .text s => s - | .list xs => "[" ++ String.intercalate ", " (xs.map mqDisplayScalar) ++ "]" - | .map ps => "{" ++ String.intercalate ", " (ps.map (fun p => p.1 ++ ": " ++ mqDisplayScalar p.2)) ++ "}" - | _ => "None" - -/-- `+`:int 算术 + 文本拼接 + num 混合,与解释器 `eval_binary(Add)` 一致。 -偏差:解释器 i64 溢出报运行时错误;Lean `Int` 无界(语料只测界内值)。 -/ -def mqAdd : Val → Val → Val - | .int a, .int b => .int (a + b) - | .num a, .num b => .num (a + b) - | .int a, .num b => .num (Float.ofInt a + b) - | .num a, .int b => .num (a + Float.ofInt b) - | .text a, .text b => .text (a ++ b) - | .text a, b => .text (a ++ mqDisplay b) - | a, .text b => .text (mqDisplay a ++ b) - | _, _ => .none - -def mqSub : Val → Val → Val - | .int a, .int b => .int (a - b) - | _, _ => .none - -def mqMul : Val → Val → Val - | .int a, .int b => .int (a * b) - | _, _ => .none - -/-- 整除;除以 0 在 Marqdo 运行时是运行时错误,此处 P1 模型按 Int 语义取 0。 -/ -def mqDiv : Val → Val → Val - | .int a, .int b => .int (a / b) - | _, _ => .none - -def mqNeg : Val → Val - | .int a => .int (-a) - | _ => .none - --- ---------------------------------------------------------------- 比较 - -def mqLt : Val → Val → Bool - | .int a, .int b => a < b - | _, _ => false - -def mqLe : Val → Val → Bool - | .int a, .int b => a ≤ b - | _, _ => false - -def mqGt : Val → Val → Bool - | .int a, .int b => a > b - | _, _ => false - -def mqGe : Val → Val → Bool - | .int a, .int b => a ≥ b - | _, _ => false - -/-- 结构化相等(生成定理的 simp 用方程逐构造器化简)。 -/ -def mqEq : Val → Val → Bool - | .none, .none => true - | .int a, .int b => a == b - | .num a, .num b => a == b - | .bool a, .bool b => a == b - | .text a, .text b => a == b - | .list a, .list b => a == b - | .map a, .map b => a == b - | _, _ => false - -@[simp] theorem mqGt_int (a b : Int) : mqGt (Val.int a) (Val.int b) = decide (a > b) := rfl -@[simp] theorem mqGe_int (a b : Int) : mqGe (Val.int a) (Val.int b) = decide (a ≥ b) := rfl -@[simp] theorem mqLt_int (a b : Int) : mqLt (Val.int a) (Val.int b) = decide (a < b) := rfl -@[simp] theorem mqLe_int (a b : Int) : mqLe (Val.int a) (Val.int b) = decide (a ≤ b) := rfl -@[simp] theorem mqEq_int (a b : Int) : mqEq (Val.int a) (Val.int b) = decide (a = b) := rfl -@[simp] theorem mqEq_bool (a b : Bool) : mqEq (Val.bool a) (Val.bool b) = (a == b) := rfl -@[simp] theorem mqEq_text (a b : String) : mqEq (Val.text a) (Val.text b) = (a == b) := rfl - --- ---------------------------------------------------------------- 分支矛盾 - -/-- 同一值对同一阈值既 `> n` 又 `≤ n`:分支矛盾(simp_all 消掉互斥分支)。 -/ -@[simp] theorem mqGt_mqLe_false {v : Val} {n : Int} - (h1 : mqGt v (Val.int n) = true) (h2 : mqLe v (Val.int n) = true) : False := by - cases v with - | int x => - simp only [mqGt, mqLe, decide_eq_true_eq] at h1 h2 - omega - | _ => simp [mqGt] at h1 - -@[simp] theorem mqLe_mqGt_false {v : Val} {n : Int} - (h1 : mqLe v (Val.int n) = true) (h2 : mqGt v (Val.int n) = true) : False := by - cases v with - | int x => - simp only [mqLe, mqGt, decide_eq_true_eq] at h1 h2 - omega - | _ => simp [mqGt] at h2 - -@[simp] theorem mqLt_mqGe_false {v : Val} {n : Int} - (h1 : mqLt v (Val.int n) = true) (h2 : mqGe v (Val.int n) = true) : False := by - cases v with - | int x => - simp only [mqLt, mqGe, decide_eq_true_eq] at h1 h2 - omega - | _ => simp [mqLt] at h1 - -@[simp] theorem mqGe_mqLt_false {v : Val} {n : Int} - (h1 : mqGe v (Val.int n) = true) (h2 : mqLt v (Val.int n) = true) : False := by - cases v with - | int x => - simp only [mqGe, mqLt, decide_eq_true_eq] at h1 h2 - omega - | _ => simp [mqLt] at h2 - --- ---------------------------------------------------------------- 布尔 - -def mqAnd (a b : Bool) : Bool := a && b -def mqOr (a b : Bool) : Bool := a || b -def mqNot (b : Bool) : Bool := !b - --- ---------------------------------------------------------------- 列表 - -/-- Val 列表的 `包含`(谓词;轨迹上的包含由生成文件按 `Op.name` 内联)。 -/ -def mqContains (xs v : Val) : Bool := - match xs with - | .list ys => ys.contains v - | _ => false - -/-- Val 列表的长度(`Val.int` 面)。 -/ -def mqLen : Val → Val - | .list ys => .int ys.length - | _ => .none - -/-- 从 `Val.int` 取 `Nat`(供 `长度` 比较等)。 -/ -def mqNatOf : Val → Nat - | .int n => n.toNat - | _ => 0 - -/-- Val 列表拼接。 -/ -def mqAppend : Val → Val → Val - | .list a, .list b => .list (a ++ b) - | _, _ => .none - --- ---------------------------------------------------------------- lib/result - -/-- `result.ok(v)`:Val 字面映射构造(§12 偏差 2)。 -/ -def mqResultOk (v : Val) : Val := - .map [("ok", .bool true), ("value", v), ("error", .none)] - -/-- `result.error(code, message, operation)`。 -/ -def mqResultError (code message operation : Val) : Val := - .map [("ok", .bool false), ("value", .none), - ("error", .map [("code", code), ("message", message), ("operation", operation)])] - -/-- `result.value_or(r, dflt)`。 -/ -def mqValueOr (r dflt : Val) : Val := - match mqAccess r "ok" with - | .bool true => mqAccess r "value" - | _ => dflt - -end MarqdoProof diff --git a/doc/verification/skill-proof/README.md b/doc/verification/skill-proof/README.md deleted file mode 100755 index d68cc3e..0000000 --- a/doc/verification/skill-proof/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# MarqdoProof — `marqdo prove` 生成代码的语义底座 - -`MarqdoProof.lean` 是生成 Lean 定理所依赖的全部符号(`Val`、`mq*` 辅助函数、 -矛盾引理),无公理、无 `opaque`。发布/校验环境把它作为 lake 项目 -`verification/skill-proof/` 安装(仓库 checkout 中该目录属 root,构建期 -落在 `target/proof/skill-proof/`,两者内容一致)。 - -## 构建与校验(Lean 4.35.0) - -```sh -export PATH=<lean-toolchain>/bin:$PATH # lean 4.35.0 + lake 5.0.0 -cd verification/skill-proof -lake build # 产出 MarqdoProof.olean -lake env lean <generated>.lean # exit 0 且无 error ⇒ 该文件全部定理成立 -``` - -## 生成文件的形状(emit.rs 契约) - -- 命名空间强制 ASCII:`审批.mq.md` → `namespace Generated.u5BA1u6279_mq` - (Lean 的 `namespace` 命令只接受 ASCII 名字)。 -- 非 ASCII 标识符一律 guillemet:`def «审批单»`;guillemet 内 `:` 替换为 `_` - (`«调用_人工审核»`)。`Op.name` 的字符串显示保持原始 id。 -- 定理形如: - ```lean - theorem «审批单.大额必经人工» (env : Env) («金额» : Val) («等级» : Val) - («h_前提» : mqTruth (mqGt «金额» (Val.int 10000))) : - ∀ («结果» : Val) («轨迹» : List Op), - ((«结果», «轨迹») = «审批单» env [] «金额» «等级») → - mqTruth ((«轨迹».map Op.name).contains "人工审核") := by - intro «结果» «轨迹» h_run - unfold «审批单» at h_run - try split at h_run - all_goals - simp_all [mqTruth, Op.name, mqAccess, mqResultOk, mqEq] - try - first - | exact (mqGt_mqLe_false ‹mqGt _ (Val.int _) = true› ‹mqLe _ (Val.int _) = true›).elim - | … - | omega - ``` -- run 等式方向 `(结果, 轨迹) = run env [] …`:输出变量在左,simp_all 才能把 - 输出替换进目标;run 从空轨迹起跑(§2:轨迹是语法产物,函数入口为空)。 - -## 实测结论(2026-11-16,Lean 4.35.0 / lake 5.0.0) - -- 业务样例(审批.mq.md,3 条定理):`lake env lean` 0 error 0 warning,全部证明。 -- 6 个带定理的测试夹具 + 业务样例:**7/7 全部 proved**(驱动脚本三态分类: - proved / unproved / lean-error)。 -- 首轮曾发现 `p2_len` 夹具断言写错(纯函数却断言两步轨迹)被 Lean 如实拒绝—— - 修复方向是改对断言,不是放宽判定:"绝不 lean 无法证明的 marqdo 可以证明"。 - -## 驱动集成(P1,2026-11-17) - -`marqdo prove` 的判定驱动把本库**内嵌**进 marqdo 二进制(`include_str!`), -按内容哈希落盘缓存后直接 `lean -o MarqdoProof.olean` 构建,被检模块经 -`LEAN_PATH` 引用——运行时只依赖 `lean` 一个二进制,不需要 lake/elan。 -本目录的 lakefile 保留给人与 CI 使用;`scripts/check-proof-library.sh` -负责校验内嵌副本与本目录逐字节一致,并输出库 sha256(写入判定证书)。 diff --git a/doc/verification/skill-proof/lakefile.toml b/doc/verification/skill-proof/lakefile.toml deleted file mode 100755 index 25f4ec3..0000000 --- a/doc/verification/skill-proof/lakefile.toml +++ /dev/null @@ -1,6 +0,0 @@ -name = "skill-proof" -version = "0.1.0" -defaultTargets = ["MarqdoProof"] - -[[lean_lib]] -name = "MarqdoProof" diff --git a/doc/verification/skill-proof/lean-toolchain b/doc/verification/skill-proof/lean-toolchain deleted file mode 100644 index a6aff06..0000000 --- a/doc/verification/skill-proof/lean-toolchain +++ /dev/null @@ -1 +0,0 @@ -leanprover/lean4:v4.35.0 diff --git a/doc/verification/skill-proof/run-lean-check.sh b/doc/verification/skill-proof/run-lean-check.sh deleted file mode 100755 index 19562d2..0000000 --- a/doc/verification/skill-proof/run-lean-check.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash -# run-lean-check.sh — 用真实 Lean 4.35.0 校验 `marqdo prove --emit` 的产物。 -# 用法: run-lean-check.sh <file.mq.md>... -# 每个文件: prove 生成 → lake env lean 编译 → 按退出状态分类。 -set -u -ROOT="$(cd "$(dirname "$0")/../.." && pwd)" # /workspace/marqdo -LEAN_BIN="$ROOT/target/toolchain/lean-4.35.0-linux/bin" -PROOF_DIR="$ROOT/target/proof/skill-proof" -MARQDO="$ROOT/target/node/debug/marqdo" -export PATH="$LEAN_BIN:$PATH" - -[ -x "$MARQDO" ] || { echo "marqdo binary missing: $MARQDO" >&2; exit 2; } -[ -f "$PROOF_DIR/.lake/build/lib/lean/MarqdoProof.olean" ] || \ - { (cd "$PROOF_DIR" && lake build) >&2 || exit 2; } - -declare -A RESULT -work="$(mktemp -d)" -trap 'rm -rf "$work"' EXIT -for src in "$@"; do - name="$(basename "$src" .mq.md)" - outdir="$work/$name" - mkdir -p "$outdir" - if ! "$MARQDO" prove "$src" --emit "$outdir" >/dev/null 2>&1; then - RESULT[$src]="emit-failed" - continue - fi - lean_file="$(find "$outdir" -name '*.lean' | head -1)" - [ -n "$lean_file" ] || { RESULT[$src]="no-lean-emitted"; continue; } - cp "$lean_file" "$PROOF_DIR/Generated/_check.lean" - log="$work/$name.leanlog" - (cd "$PROOF_DIR" && lake env lean Generated/_check.lean) >"$log" 2>&1 - rc=$? - rm -f "$PROOF_DIR/Generated/_check.lean" - if [ $rc -eq 0 ] && ! grep -q "error" "$log"; then - RESULT[$src]="proved" - elif grep -q "unsolved goals" "$log"; then - RESULT[$src]="unproved" - else - RESULT[$src]="lean-error" - fi -done - -fail=0 -for src in "$@"; do - status="${RESULT[$src]}" - printf '%-12s %s\n' "$status" "$src" - [ "$status" = "proved" ] || fail=1 -done -exit $fail diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..b42e29b --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,24 @@ +# 架构与所有权 + +自建 Git `git.cflmy.cn/cflmy` 是代码、工单和合并的权威,`ci.cflmy.cn` 是 CI 权威。GitHub 作为镜像或分发渠道。生态主仓库以直接 Git submodule 固定组件提交,`stdlib/`、`extensions/`、`tools/` 是分类目录。 + +| 层 | 所有权 | +| --- | --- | +| CLI | Markdown 映射、AST/IR、Runtime、Value、权限/隔离/预算及 Package、Plugin、Provider、Foreign、Tool、Analysis、Observation 公共契约 | +| 标准库 | 基础安装默认提供的通用低层函数,以及对受控宿主原语的薄封装 | +| 扩展 | 可选算法、领域协议与独立后端。`marqdo-ext-<领域>` 按独立依赖、安全或发行边界命名 | +| Tool | 通过公共 CLI 接口处理文档及制品的独立工具,例如静态知识、证明、观察和质量诊断 | +| 应用 | 具体用户任务和业务流程,例如 qdagent | +| 生态主仓库 | 组件关系、精确组合、跨组件验收、发行与责任治理 | + +CLI 编译只需其自身实现。完整基础发行由 CLI、必需 Worker 和统一标准库 Bundle 构成。标准库组件只依赖 CLI 公共语义和更低层标准库,扩展可以依赖标准库与明确声明的其他扩展。Tools 使用公开协议与自身依赖,各工具的数据格式互操作须由产生者明确发布契约。组件依据各自发版制品独立构建,不依赖主仓库源码。 + +组件的职责、阶段和依赖只在 [components.toml](../components.toml) 维护。子模块远端在 `.gitmodules`,提交在 Git tree,程序依赖仍在现行包清单及锁。`requires` 描述直接构建与制品依赖,`checks_with` 描述协同验收。计划中的依赖在真实接入前以 imports、构建输入和制品核实。依赖图必须无环。 + +## 新增能力与公共边界 + +先复用职责匹配的组件。需要独立维护、依赖、安全或发行边界时,为新仓库发起评审。加入标准库须证明基础发行默认需要、至少三个领域真实复用、依赖闭包受控,并说明错误、授权和预算语义。 + +需要新增 builtin、HostOp、值类型、语法或公共协议字段时,在 CLI 提交 ADR,写明现有机制为何不足、最小复现、三个领域用例、替换及正负例。公开接口破坏性更新按同一候选组合切换产生者和消费者,保留单套现行协议。历史行为通过固定版本的历史发行复现。 + +跨组件测试以真实 CLI/Worker、独立消费者和现行权限配置验证。Native 后端与外部工具按 CLI 安全边界执行,权限、隔离和预算声明以可验证的实际行为为准。 diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md new file mode 100644 index 0000000..3a246e9 --- /dev/null +++ b/docs/DEVELOPMENT.md @@ -0,0 +1,47 @@ +# 开发、验收与发行 + +## 从工单到集成 + +1. 在会修改代码的责任仓库寻找或创建工单。记录复现输入、组件 SHA、平台、公共契约、预期/实际结果,以及可执行正负例。涉及其他仓库时,各仓库保留自己负责的工单,在消费者工单标明依赖和回归条件。例:HTTP 的 SSE 分块错误归 HTTP;模型事件拼接错误归 AI;握手或字节流原语错误先由标准库或 CLI 的所有者定位。 +2. 在组件仓库提交 PR,运行独立 CI。公共协议改动同时验证真实产生者和消费者,附测试命令、制品摘要、平台、CI URL。组件源码审核通过后推送可由 CI 获取的精确提交。 +3. 在主仓库提交集成 PR。先初始化相关组件,再以 detached HEAD 锁定审核过的 SHA 并暂存 gitlink。同一份工具契约或 Stdlib 切换需要同时更新多个组件时,在一个候选中提交整组 gitlink。 +4. 基线移动时重验候选组合。留下真实失败证据并路由责任工单。通过同 SHA 的必需门禁后合并,随后关闭集成追踪及已解决的关联工单。 + +```sh +git submodule update --init +git -C tools/view fetch origin +git -C tools/view checkout --detach <审核通过的提交> +git add tools/view +git diff --cached --submodule=log +``` + +## 验收 + +| 层 | 责任与证据 | +| --- | --- | +| C1 组件 CI | 独立构建与测试、授权负例、固定依赖、打包 smoke,由组件仓库维护 | +| C2 公共契约 | 真实 CLI 和 Worker、独立 Conformance 与消费者,覆盖当前协议、失败和正确身份 | +| C3 生态集成 | 结构、公开冷克隆、精确 gitlink、官方基础发行、CLI Tool 和契约消费回归 | + +本候选先对全部 active 组件运行集成。Woodpecker 的 `layout` 校验 Git tree,随后初始化公开直连子模块。`candidate` 用官方冻结归档验证冷安装、Conformance、View、Knowledge、Prove 和 Lint。View 的集成测试包含安装、静态核验、显式执行、Observation 和移除。C1 的完整构建、View 的全浏览器矩阵、Prove 的 Lean 后端以及 CLI 的 strict VM 和性能门禁沿用各组件独立流程。 + +本地运行需要 Linux x86_64/glibc ≥ 2.39、Python 3.11+、jsonschema、Git、Rust、C 编译器和 curl。 + +```sh +git submodule update --init +python3 scripts/check-layout.py --checkouts +python3 -m unittest discover -s tests/integration +bash scripts/integration.sh +``` + +集成日志记录候选提交、每个 gitlink、二进制摘要及各检查退出码。对产物默认要求 digest 与来源提交一致。当前候选的冻结制品适配器以正式 RC.4 为基线。更新 CLI 基线时须同步修改其可验证制品入口及相关消费者,并同时审查源提交、锁定摘要和发布平台。 + +组件更多后才缩小日常影响范围。算法必须用新旧依赖图并集计算反向闭包,再加测试配对与受影响场景。CLI、Stdlib、未知边或集成策略变更保守全量测试。发布全量验证并绑定精确提交、运行环境、依赖与制品摘要。任何必需 FAIL 或 UNVERIFIED 都阻止对应阶段验收。 + +跨仓候选目前由维护者手动提交。自动化接入时,事件只用于唤醒,记录仓库、完整 SHA、CI URL。服务验证签名、仓库允许列表、真实 CI 结果和提交可达性,按仓库和 SHA 去重。机器人只写候选分支与 PR,维护者负责合并;凭据仅放服务端或平台 Secret,测试任务使用非特权身份。 + +## 发行与回滚 + +先验证完整候选组合,再由组件各自发布不可变制品。基础发行包含同源 CLI、Worker 与单一标准库 Bundle;工具和扩展使用各自权威制品与 CLI 的现行安装机制。主仓库发布记录应从 gitlink 和真实制品生成,包含主仓库 SHA、组件 SHA、各自版本、归档摘要、构建环境、平台和测试记录。 + +发布前在空 HOME、无 checkout 和禁网环境验证基础安装。每个声称支持的平台都要实机证据。失败候选保留日志;发布失败使用新的候选,已有标签和资产保持不可变。回滚用新集成提交恢复上一组通过的 gitlink,安全修复场景先审查回退风险。 diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md new file mode 100644 index 0000000..f22c99d --- /dev/null +++ b/docs/MIGRATION.md @@ -0,0 +1,122 @@ +# 迁移台账 + +## 权威盘点 + +历史主分支最后提交为 `1c55baabd570e18b9da8f9057cef2f848e176690`,v2.9.1 的发布提交为 `ffe06d7afab7acaed87be5ff16edddc37da536a2`。自建 Git 已核验旧标签和主分支。旧实现、文档、示例、测试与工作流以历史提交为迁移资料。[历史主分支末尾](https://git.cflmy.cn/cflmy/marqdo/src/commit/1c55baabd570e18b9da8f9057cef2f848e176690) + +| 已有仓库 | 审计时默认分支 | 发行或证据 | +| --- | --- | --- | +| [marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) | `master` | v3.0.0-rc.4 | +| [marqdo-extension-conformance](https://git.cflmy.cn/cflmy/marqdo-extension-conformance) | `main` | 有独立固定 fixture | +| [marqdo-knowledge](https://git.cflmy.cn/cflmy/marqdo-knowledge) | `master` | v0.1.0-beta.3 | +| [marqdo-lint](https://git.cflmy.cn/cflmy/marqdo-lint) | `main` | v0.2.0 | +| [marqdo-prove](https://git.cflmy.cn/cflmy/marqdo-prove) | `master` | v0.1.0-beta.1 | +| [marqdo-view](https://git.cflmy.cn/cflmy/marqdo-view) | `master` | v0.3.0 | + +CLI gitlink 采用 RC.4 正式发布源码,以匹配冻结归档和现有 View/Lint 契约。 +其文档后续提交曾用于 Knowledge 的独立 CI;生态候选以自身测试判定实际组合。 +Conformance 使用 CLI 已固定的真实 fixture 提交。 + +## 已创建空仓 + +以下仓库已通过自建 Git API 确认存在且为空。责任、预期依赖与状态见 [组件目录](../components.toml)。 + +**标准库** · [core](https://git.cflmy.cn/cflmy/marqdo-std-core) · [collections](https://git.cflmy.cn/cflmy/marqdo-std-collections) · [text](https://git.cflmy.cn/cflmy/marqdo-std-text) · [encoding](https://git.cflmy.cn/cflmy/marqdo-std-encoding) · [data](https://git.cflmy.cn/cflmy/marqdo-std-data) · [io](https://git.cflmy.cn/cflmy/marqdo-std-io) · [fs](https://git.cflmy.cn/cflmy/marqdo-std-fs) · [system](https://git.cflmy.cn/cflmy/marqdo-std-system) · [net](https://git.cflmy.cn/cflmy/marqdo-std-net) + +**扩展** · [math](https://git.cflmy.cn/cflmy/marqdo-ext-math) · [linalg](https://git.cflmy.cn/cflmy/marqdo-ext-linalg) · [quantum](https://git.cflmy.cn/cflmy/marqdo-ext-quantum) · [http](https://git.cflmy.cn/cflmy/marqdo-ext-http) · [websocket](https://git.cflmy.cn/cflmy/marqdo-ext-websocket) · [ai](https://git.cflmy.cn/cflmy/marqdo-ext-ai) · [mcp](https://git.cflmy.cn/cflmy/marqdo-ext-mcp) · [crypto](https://git.cflmy.cn/cflmy/marqdo-ext-crypto) · [database](https://git.cflmy.cn/cflmy/marqdo-ext-database) · [storage](https://git.cflmy.cn/cflmy/marqdo-ext-storage) · [cache](https://git.cflmy.cn/cflmy/marqdo-ext-cache) · [security](https://git.cflmy.cn/cflmy/marqdo-ext-security) · [web](https://git.cflmy.cn/cflmy/marqdo-ext-web) · [browser](https://git.cflmy.cn/cflmy/marqdo-ext-browser) · [document](https://git.cflmy.cn/cflmy/marqdo-ext-document) · [archive](https://git.cflmy.cn/cflmy/marqdo-ext-archive) · [engineering](https://git.cflmy.cn/cflmy/marqdo-ext-engineering) · [regex](https://git.cflmy.cn/cflmy/marqdo-ext-regex) · [datetime](https://git.cflmy.cn/cflmy/marqdo-ext-datetime) + +## 阶段与阻塞 + +| 阶段 | 当前范围 | 后续验收 | +| --- | --- | --- | +| M0 盘点 | 自建 Git、历史标签、已有六组件和新仓位 | 通过真实远端候选持续维护台账 | +| M1 集成骨架 | 六个 gitlink、布局门禁和 RC.4 组合 | 查看候选 Woodpecker 运行及各组件独立 CI | +| M2 标准库切换 | planned,CLI RC.4 提供官方完整 Bundle | [CLI 外部 Bundle](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11) 和 [九组件切换](https://git.cflmy.cn/cflmy/marqdo/issues/2),包括 HTTP、Regex、Archive 迁出与同步删除旧路径 | +| M3 跨仓闭环 | 工单、人工候选、同 SHA 门禁 | [跨仓库 CI](https://git.cflmy.cn/cflmy/marqdo/issues/3) 跟踪真实缺陷闭环、候选通知鉴权、去重和影响分析 | +| 后续领域 | 空仓和预期职责 | 逐组件开展最小真实功能、独立 CI、制品与接入 | + +### 标准库切换顺序 + +1. CLI 打包器与产品测试接受单一显式外部 Bundle 输入。内核独立编译;制品仍附带一个校验过的标准库。 +2. 标准库在各组件维护唯一生产源码和自测。组装拒绝冲突、符号链接或测试污染,调用 CLI 权威打包器。std-io 维护 print/打印 的别名元数据。 +3. HTTP、Regex、Archive 的真实替代和授权回归先行。候选同时移除 CLI 中旧领域宿主服务和旧导入。 +4. 验证同输入两次组装结果、摘要及路径负例、C1/C2/C3、独立冷安装和真实工具集成后,再切换基础发行。当前状态为 UNVERIFIED。 + +## 现行 CLI 标准库迁移归属 + +| 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) | + +## v2 功能历史索引 + +按表中的归属逐项拆分工单,记录来源路径、目标接口、正负例、状态和真实测试提交。 + +| 旧版 lib 模块 | 目标 | 迁移决策 / 主要缺口 | +|---|---|---| +| archive | archive | ZIP/TAR 等安全归档;现有 gzip 迁移,测试路径穿越 | +| browser | browser | 31 个 H2 所涉 DOM、存储、事件、fetch、WS、下载;不复制旧 WASM runtime | +| bytes | std-text / std-encoding | 字节值、slice、UTF-8 归 Text,base64 归 Encoding,单一 byte 表示 | +| cli | std-system | 应用参数 parse,非 CLI 自身 flag parser | +| csv | std-data | 已有 parse/format;补非法输入与多行测试 | +| datetime | std-system / datetime | UTC 基础已有;时区、DST 和高级日历明确拆分 | +| document | document | sections、tables、links、code blocks、replace;通过受支持静态事实与显式文件编辑 | +| encoding | std-encoding | Base64/Base32/Hex 编解码缺失 | +| foreign | CLI 现有 Foreign / 独立可选会话扩展(待 ADR) | one-shot run/call 已有;不恢复 set_cmd/register 等隐式动态机制;session/replay 需真实设计 | +| fs | std-fs / document / engineering | 40 个 H2 涵盖文件操作;新版14个 H2;二进制、递归、原子、临时、读写组合;文本 patch/工程 sync 归相应扩展 | +| hash | crypto | SHA/HMAC 等,密码学不进入内核 | +| html | web | escape/unescape 作为纯 Web 辅助模块 | +| json | std-data | parse/stringify 已有;get/keys/set 等可复用 collections;严格 Result | +| log | std-system | 结构化、level、输出门面,不引入服务框架 | +| math | std-core / math | abs/min/max/clamp 基础归 Core;数值、超越、公式、CAS、绘图归 Math;随机归 System | +| net | std-net / http / ai / document | TCP/TLS 基础归 Net;HTTP/SSE/cookie/multipart/download 归 HTTP;OpenAI 特定 SSE 归 AI;Markdown 解析归 Document 或公开静态事实 | +| path | std-fs | join/normalize 等已有;relative/with_extension 等补齐 | +| plugin | CLI 现行扩展选择机制 | 不迁移 load/unload 自动加载;使用显式 descriptors、lock、grant | +| re | regex | 查找/替换/分割/捕获和现有纯子集、成熟后端,取消宿主 convenience 重复 | +| result | std-core | ok/error/value_or,统一现行可恢复错误约定 | +| secrets | std-system / crypto | token 生成归 System,密钥/密码学安全操作归 Crypto;不泄漏 secret | +| stats | math | mean/median/stdev;定义样本与总体、空集合、精度 | +| subtask | CLI Structured Tasks(待开发) / std-system | spawn/join/cancel 等先验证通用语义;库只薄封装,不移植旧 scheduler | +| sys | std-system / CLI 公共事实 | env/args/process/clock;旧 stream_publish 和 meta 由现行 Observation/Analysis 或真正应用输出处理;不恢复隐式环境写入 | +| table | std-collections / std-data | 60 个 H2 入口(List/Map/Table 混合);值操作归 Collections,GFM/数据格式归 Data | +| text | std-text | trim/split/join、contains/replace、大小写、repeat/pad 等缺口 | +| time | std-system | now/UTC parse 已部分有;sleep 仅在受控原语可用后实现 | +| toml | std-data | parse/stringify/try_parse,实际支持标准及错误边界 | +| url | http | URL parse/query/percent 与同协议归属,std-net 不重复 | +| uuid | std-system | v4 使用 OS entropy;检查版本/variant | +| writeback | document / engineering | 显式有界编辑、来源摘要及冲突检查;不恢复隐式自修改/自动 oracle writeback | +| lint/narrative | lint Tool | 静态诊断与显式修复,不进 CLI runtime | + +### 领域与插件 + +| 旧目录 | 目标及处理 | +|---|---| +| `ext/ai` + `plugins/llm` / `plugins/agent` | AI 模型协议、MCP 独立迁移;agent 97 个 H2 涉及 workflow/memory/工具/恢复等,按真实通用能力拆分,不整体复制。qdagent 应用管理其自己的最小工作流、记忆、意图和 SKILL,不作为通用标准库。知识检索、证明分别由对应 Tool;sandbox 用 CLI 的实际保证,不伪造 OS 隔离。 | +| `ext/linalg` + `plugins/linalg` | Linalg;迁移数值算法、复数及矩阵符号知识;重新适配 ABI,减少重复。 | +| `ext/quantum` + `plugins/quantum` | Quantum;gate/state/circuit/simulate/density/viz,移除与 Linalg 重复的实现或建立经测试的后端共享边界。 | +| `ext/net` | HTTP、WebSocket、URL,低层 TCP/TLS 归 Std Net。 | +| `ext/data` | Database/Cache/Storage;form/admin/api/view 的 Web 部分归 Web,数据验证及查询归唯一相应库。旧 Web Go plugin 的 DB、storage、cache 子模块分别迁移。 | +| `ext/security` | Security + Crypto;旧 Go plugin auth/OIDC/RBAC/tenant/password 按归属拆分,不混入 Host capability。 | +| `ext/web` + `plugins/web` | Web、HTTP、WebSocket、Browser、Database、Security 等拆分;保留原生 GFM 组件与布局表达,删除 monolithic Go plugin 调度与重复模块,重新适配公开协议。 | +| `ext/engineering` + `plugins/engineering` | Engineering;Git 操作、文件、archive 分配给已有权威库,避免重复平台操作。 | +| `crates/marqdo-wasm`、旧 browser examples | Browser 组件参考;语言核心可移植性需要 CLI 工单,而非复制旧执行器。 | +| 旧 `src/knowledge`/proof/view/lint/对应历史 CI 与 examples | 独立 Tool,只迁移所需知识、算法和 fixture;当前公共 Analysis/Observation 优先;新旧协议不并存。 | diff --git a/examples/agent-okf-flywheel/README.md b/examples/agent-okf-flywheel/README.md deleted file mode 100755 index 3d4a8d7..0000000 --- a/examples/agent-okf-flywheel/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# agent-okf-flywheel(Wave B0) - -演示 **文档即知识库(OKF)**:固化工作簿 promote 后,相同 goal 的 `plan` 走 `cache=hit`(`llm_free` 路径),无需再问模型。 - -```bash -cargo build --release -p marqdo -p marqdo_plugin_agent -export MARQDO_EXT="$PWD/.marqdo-ext" -./target/release/marqdo run examples/agent-okf-flywheel/index.mq.md -``` - -期望:`promoted` · `hit` · `flywheel-ok`。 - -见 [okf.md](../../doc/design/okf.md) · [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md)。 diff --git a/examples/agent-okf-flywheel/index.mq.md b/examples/agent-okf-flywheel/index.mq.md deleted file mode 100755 index 116f6ce..0000000 --- a/examples/agent-okf-flywheel/index.mq.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -markup: occlusion -title: agent-okf-flywheel (Wave B0) -description: Promote solidified workbook; second plan is cache=hit — document as knowledge base (OKF). -import: - llm: ext/ai/llm.mq.md - agent: ext/ai/agent.mq.md - fs: lib/fs.mq.md - json: lib/json.mq.md - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -This is an offline knowledge-reuse workflow, not a request to an external model. It loads the agent plugin, promotes the visible workbook for one exact goal and asks the same agent goal again. The expected hit comes from the promoted knowledge base. The dummy key only satisfies model setup; it is not a credential or evidence that a model call succeeded. - -The example uses its own named files under .marqdo and replaces that example knowledge base on rerun. Grant the actual plugin and filesystem effects in a disposable example root. Promotion and execution are separate outcomes: inspect promoted first, then cache, match and the returned result. A hit marker alone does not prove that an unrelated new goal is safe to reuse. - -OKF flywheel offline: promote → plan same goal → `cache=hit` (no live LLM required for the hit path). - -We first **p = [Compute p](plugin.native_path(name="agent"))** for the next step. -1. `p` - We now **[Call plugin.load](> plugin.load path=`p`)**. -2. * - We now **[Display this step's result](> print text="no-agent-plugin")**. - We now **[Call sys.exit](> sys.exit code=1)**. - -We now **[Call sys.env set](> sys.env_set name="OPENAI_API_KEY" value="offline-okf-dummy")**. -We first **model = [Compute model](llm.llm())** for the next step. -We first **tools = [Compute tools](json.parse(text="[]"))** for the next step. -We first **助手 = [Compute 助手](agent.agent(model=`model`, tools=`tools`, standing="offline okf flywheel"))** for the next step. - -We first **kb = ".marqdo/agent-kb-example-flywheel"** for the next step. -We first **wb = ".marqdo/agent-runs/example-pong-solid.mq.md"** for the next step. -We first **goal = "Reply with exactly the word pong and nothing else."** for the next step. -We first **body = "---\ntitle: okf pong\n---\n\n# main\n\n*msg = \"pong\"*\n\n**msg**\n"** for the next step. - -1. > fs.exists path=`kb` - We now **[Call fs.remove](> fs.remove path=`kb`)**. -2. * - --- - -We now **[Call fs.write text](> fs.write_text path=`wb` text=`body`)**. - -We first **prom = [Compute prom](agent_kb_promote(kb_dir=`kb`, goal=`goal`, workbook=`wb`))** for the next step. -We first **okp = [Compute okp](json.get(value=`prom`, key="promoted"))** for the next step. -1. `okp` - We now **[Display this step's result](> print text="promoted")**. -2. * - We now **[Display this step's result](> print text="promote-fail")**. - We now **[Call sys.exit](> sys.exit code=1)**. - -We first **out = [Compute out](> `助手`.plan goal=`goal` max_rounds=2 writeback=False kb_dir=`kb` explore_n=0 promote=False)** for the next step. -We first **cache = [Compute cache](json.get(value=`out`, key="cache"))** for the next step. -We now **[Display this step's result](> print text=`cache`)**. -We first **match = [Compute match](json.get(value=`out`, key="match"))** for the next step. -We now **[Display this step's result](> print text=`match`)**. -We first **val = [Compute val](json.get(value=`out`, key="result"))** for the next step. -We now **[Display this step's result](> print text=`val`)**. - -1. `cache` == "hit" - We now **[Display this step's result](> print text="flywheel-ok")**. -2. * - We now **[Display this step's result](> print text="flywheel-miss")**. - We now **[Call sys.exit](> sys.exit code=1)**. diff --git a/examples/agent-pong/README.md b/examples/agent-pong/README.md deleted file mode 100755 index 71d6f21..0000000 --- a/examples/agent-pong/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# agent-pong(Wave B0) - -演示 Marqdo 智能体宪法:**代码即文档** — 模型上下文含 **call site** 与本文件 **source**;工具是同文件里的 `## 获取时间`。 - -```bash -# 仓库根目录 -cargo build --release -p marqdo -p marqdo_plugin_agent -export MARQDO_EXT="$PWD/.marqdo-ext" # 或: marqdo ext add agent -# 可选 live:仓库根 `.env` + `AGENT_LIVE=1 marqdo run examples/agent-pong/index.mq.md` -./target/release/marqdo run examples/agent-pong/index.mq.md -``` - -期望离线输出含:`call-site-ok` · `source-ok` · `tool-in-source-ok`。 -配置真实 `.env` 时还会跑一次 `step`(CALL 工具)。 - -见 [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md)。 diff --git a/examples/agent-pong/index.mq.md b/examples/agent-pong/index.mq.md deleted file mode 100755 index 4706c92..0000000 --- a/examples/agent-pong/index.mq.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -markup: occlusion -title: agent-pong (Wave B0) -description: >- - Constitution demo — call_site + source in step context; optional live CALL via .env. - Code is documentation; tools are ## in this same file. -import: - llm: ext/ai/llm.mq.md - agent: ext/ai/agent.mq.md - json: lib/json.mq.md - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - time: lib/time.mq.md ---- - -## 获取时间 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -Return today's date string (tool visible in source to the model). - -We first **u = [Compute u](time.now_unix())** for the next step. -After these steps, return *time.format(unix=`u`, pattern="%Y-%m-%d")*. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -This entry first verifies what the agent can read about its own call site. It assembles a step context and checks for the call-site section, source section and the actual time-tool name before considering an optional live step. The tool table points to the real local function; it is not an independently maintained tool description detached from the source. - -Normal demonstration stops at context evidence and does not require a paid model response. AGENT_LIVE and an available key together opt into the separate live branch. Context markers establish prompt content, not the correctness of a future model answer. Keep the tool result and returned status visible when exercising that branch; never replace a missing credential with a fixed successful response. - -We first **p = [Compute p](plugin.native_path(name="agent"))** for the next step. -1. `p` - We now **[Call plugin.load](> plugin.load path=`p`)**. -2. * - We now **[Display this step's result](> print text="no-agent-plugin")**. - We now **[Call sys.exit](> sys.exit code=1)**. - -We now **[Call llm.load env](> llm.load_env path="../../.env")**. - -`工具表` = - -| 工具 | -|------| -| 获取时间 | - -We first **model = [Compute model](llm.llm())** for the next step. -We first **助手 = [Compute 助手](agent.agent(model=`model`, tools=`工具表`, standing="You are a Marqdo agent. Prefer CALL:获取时间 when the task needs today's date."))** for the next step. - -Assert constitution markers in the assembled prompt (call site before how-to-act): - -We first **ctx = [Compute ctx](agent.build_step_context(agent=`助手`, task="What is today's date? Use the tool in this runbook."))** for the next step. - -We first **parts = [Compute parts](split(value=`ctx`, sep="--- call site ---"))** for the next step. -We first **n = [Compute n](len(value=`parts`))** for the next step. -1. `n` > 1 - We now **[Display this step's result](> print text="call-site-ok")**. -2. * - We now **[Display this step's result](> print text="call-site-missing")**. - We now **[Call sys.exit](> sys.exit code=1)**. - -We first **parts2 = [Compute parts2](split(value=`ctx`, sep="--- source (.mq.md) ---"))** for the next step. -We first **n2 = [Compute n2](len(value=`parts2`))** for the next step. -1. `n2` > 1 - We now **[Display this step's result](> print text="source-ok")**. -2. * - We now **[Display this step's result](> print text="source-missing")**. - We now **[Call sys.exit](> sys.exit code=1)**. - -We first **parts3 = [Compute parts3](split(value=`ctx`, sep="获取时间"))** for the next step. -We first **n3 = [Compute n3](len(value=`parts3`))** for the next step. -1. `n3` > 1 - We now **[Display this step's result](> print text="tool-in-source-ok")**. -2. * - We now **[Display this step's result](> print text="tool-in-source-missing")**. - We now **[Call sys.exit](> sys.exit code=1)**. - -We first **site = [Compute site](agent_call_site())** for the next step. -We first **fn = [Compute fn](json.get(value=`site`, key="function"))** for the next step. -We now **[Display this step's result](> print text=`fn`)**. - -Optional live step — set env AGENT_LIVE=1 and put keys in repo-root `.env`: - -We first **live = [Compute live](sys.env_get(name="AGENT_LIVE"))** for the next step. -We first **key = [Compute key](sys.env_get(name="OPENAI_API_KEY"))** for the next step. -1. `live` == "1" - 1. `key` - We first **out = [Compute out](> `助手`.step task="请调用获取时间工具,然后只回复日期字符串。" writeback=False)** for the next step. - We first **status = [Compute status](json.get(value=`out`, key="status"))** for the next step. - We now **[Display this step's result](> print text=`status`)**. - We first **tool = [Compute tool](json.get(value=`out`, key="tool"))** for the next step. - We now **[Display this step's result](> print text=`tool`)**. - We first **result = [Compute result](json.get(value=`out`, key="result"))** for the next step. - We now **[Display this step's result](> print text=`result`)**. - 2. * - We now **[Display this step's result](> print text="live-skipped-no-key")**. -2. * - We now **[Display this step's result](> print text="live-skipped")**. diff --git a/examples/agent-sandbox-okf/README.md b/examples/agent-sandbox-okf/README.md deleted file mode 100755 index c0b6c2a..0000000 --- a/examples/agent-sandbox-okf/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# agent-sandbox-okf(O1) - -演示 **opt-in 沙盒试跑 + 表风格**(少 json 胶水):`agent.trial` 写入先落 upper,`commit=False` 时宿主不变,成功后再 `commit=True`。 - -```bash -cargo build --release -p marqdo -p marqdo_plugin_agent -export MARQDO_EXT="$PWD/ext" -./target/release/marqdo run examples/agent-sandbox-okf/index.mq.md -``` - -期望:`dry-ok` · `host-clean` · `wet-ok` · `proof-visible` · `profile-default`。 - -见 [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md) · 金样 [agent-sandbox-optin.mq.md](../../tests/ext/agent-sandbox-optin.mq.md)。 diff --git a/examples/agent-sandbox-okf/index.mq.md b/examples/agent-sandbox-okf/index.mq.md deleted file mode 100755 index 7640988..0000000 --- a/examples/agent-sandbox-okf/index.mq.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -markup: occlusion -title: agent-sandbox-okf — trial then commit -description: > - O1 example: opt-in sandbox trial with GFM-table returns and link-index reads. -import: - agent: ext/ai/agent.mq.md - fs: lib/fs.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -The two trials intentionally differ only in commit. First inspect a successful dry trial and verify that note.txt has not appeared in the host directory. Then run the committed trial, read the host file and compare its actual content. This separates an observed proposal from an observed filesystem change; neither ok alone nor a proposed path establishes that a commit happened. - -Use a disposable filesystem root: the example replaces its named _example_sbx directory and leaves the committed evidence there for inspection. It does not promise to roll back a committed external effect. Read the returned profile as part of the trial evidence, and keep failures visible rather than manufacturing a success marker when the expected file is absent. - -Short demo: write via `agent.trial`, prove the host is clean until commit. - -We first **had = [Compute had](fs.exists(path="_example_sbx"))** for the next step. -1. `had` - We now **[Call fs.remove](> fs.remove path="_example_sbx")**. -2. * - We first **_ = 0** for the next step. - -We now **[Call fs.make dir](> fs.make_dir path="_example_sbx")**. - -We first **dry = [Compute dry](agent.trial(root="_example_sbx", write_path="note.txt", text="sandbox-okf", commit=False))** for the next step. -We first **dry_ok = [ok](access(`dry`, "ok"))** for the next step. -We first **dry_committed = [committed](access(`dry`, "committed"))** for the next step. -1. `dry_ok` - 1. not `dry_committed` - We now **[Display this step's result](> print text="dry-ok")**. - 2. * - We now **[Display this step's result](> print text="dry-bad-commit")**. -2. * - We now **[Display this step's result](> print text="dry-fail")**. - -We first **leaked = [Compute leaked](fs.exists(path="_example_sbx/note.txt"))** for the next step. -1. `leaked` - We now **[Display this step's result](> print text="host-leaked")**. -2. * - We now **[Display this step's result](> print text="host-clean")**. - -We first **wet = [Compute wet](agent.trial(root="_example_sbx", write_path="note.txt", text="sandbox-okf", commit=True))** for the next step. -We first **wet_ok = [ok](access(`wet`, "ok"))** for the next step. -We first **wet_committed = [committed](access(`wet`, "committed"))** for the next step. -1. `wet_ok` - 1. `wet_committed` - We now **[Display this step's result](> print text="wet-ok")**. - 2. * - We now **[Display this step's result](> print text="wet-no-commit")**. -2. * - We now **[Display this step's result](> print text="wet-fail")**. - -We first **body = [Compute body](fs.read_text(path="_example_sbx/note.txt"))** for the next step. -1. `body` == "sandbox-okf" - We now **[Display this step's result](> print text="proof-visible")**. -2. * - We now **[Display this step's result](> print text="proof-missing")**. - -We first **pname = [name](access([profile](access(`wet`, "profile")), "name"))** for the next step. -1. `pname` == "default" - We now **[Display this step's result](> print text="profile-default")**. -2. * - We now **[Display this step's result](> print text="profile-other")**. diff --git a/examples/browser-app/README.md b/examples/browser-app/README.md deleted file mode 100755 index ca840ae..0000000 --- a/examples/browser-app/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# browser-app:可读源码中的浏览器工程 - -从 [index.mq.md](index.mq.md) 开始阅读和执行,再沿 [组件入口](components/index.mq.md) 查看布局。首页拆成列表与计时,网络页再拆成输出、批量请求和 WebSocket 控件;内容在 content 中保留普通 Markdown,控件叶子使用原生 View 节点。 - -浏览器程序是 [static/app.mq.md](static/app.mq.md)。事件表、参数与返回契约就在回调旁边;操作用可读标签表达,列表文本始终保留为数据。样式入口为 [styles/index.mq.md](styles/index.mq.md),旁边的字面表保留旧页面全部 59 条声明,并给出 View 包装层的几何适配。 - -| 能力 | 实际行为与边界 | -|---|---| -| 列表 | 原生记录保留独立 ID;重复内容可单独删除,特殊字符使用 text,删除按钮使用 children | -| 草稿 | localStorage 保存输入框文本;完成回调确认保存,缺失值与空草稿分别处理;条目不跨刷新保存 | -| 历史 | 三个面板使用真实 pathname;popstate 只反映现有位置,不重复 push;直接打开 /about 或 /net 返回首页 | -| 计时 | 同名计时器替换,停止保留已累计次数 | -| 批量请求 | 两个公开 UUID 请求可能失败;输出每项真实状态、响应体或错误 | -| WebSocket | 本地 /live 原生回声资源;展示实际打开、消息、错误与关闭回调 | -| 剪贴板与下载 | 导出当前列表文本;即时提示仅确认已发起,浏览器策略仍可能阻止完成 | - -在仓库根目录构建当前官方运行时,再启动原生服务器。需要已经可用的 Rust/WASM 工具链和本仓库工程、网络插件;缺少 WASM 标准库时先阅读 [工作区工具链手册](../../skills/marqdo-dev/toolchain.mq.md),并将返回的 compiler 传给 build_browser。生成资源与编译样式不作为业务源码提交。 - -```sh -marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/browser-app/static"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json -marqdo call examples/browser-app/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/browser-app --require-ok --json -``` - -打开 http://127.0.0.1:18095。控件等待实际启动成功后启用;缺失资源返回明确失败,不能把加载说明当作已运行。服务只监听本机,示例不引入数据库、认证或持久条目存储。 - -开发验证同样通过可执行手册完成。下列浏览器任务原生复制当前运行时,并运行真实页面交互;它覆盖重复项、字面文本、草稿、历史、计时、导出内容、受控批量请求失败与本地 WebSocket 收发。Node/Playwright 是自动化测试的外联边界,文件读写与任务编排仍由 Marqdo 执行。 - -```sh -marqdo call skills/marqdo-dev/index.mq.md check 'path="examples/browser-app/index.mq.md"' --effects plugin --require-ok --json -marqdo call skills/marqdo-dev/index.mq.md test_browser --effects plugin,process.exec,fs.write --fs-root . --require-ok --json -``` - -后续修改先阅读 [编程规范](../../doc/library-development.mq.md),再修改一个职责的组件或回调。需要新的浏览器宿主能力时扩充正式 bridge 与标准库契约,保留真实浏览器验收;不在父组件中重新拼接 HTML 或业务 JavaScript。 diff --git a/examples/browser-app/components/about.mq.md b/examples/browser-app/components/about.mq.md deleted file mode 100755 index 756e97a..0000000 --- a/examples/browser-app/components/about.mq.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -markup: occlusion -title: About panel Markdown leaf -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -About is a terminal Markdown leaf, so further layout splitting would add no useful responsibility. Read its content through the native filesystem under the granted site root. The wrapper supplies only its client visibility id and initial hidden state. The page describes official host capabilities without embedding implementation JavaScript or an HTML shell. - -We **source = [Read the literal About content](fs.read_text(path="content/about.md"))** and **children = [Keep it as ordinary Markdown](component.markdown(text=`source`, slot="about-content"))**. - -`attrs` = - -| id | hidden | -|---|---| -| panel-about | True | - -Return *[Describe the initially hidden About panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="about"))*. diff --git a/examples/browser-app/components/controls.mq.md b/examples/browser-app/components/controls.mq.md deleted file mode 100755 index 11813d7..0000000 --- a/examples/browser-app/components/controls.mq.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -markup: occlusion -title: Native browser control leaves -import: - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -## button - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Event target shared with the client wire table | -| label | text | required | Literal visible action | -| secondary | bool | False | Use the retained secondary palette | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One disabled native button awaiting successful runtime boot | - -Use `id`, `label` and `secondary`=False for one leaf. The button starts disabled, carries type button and is enabled only after the official runtime boots successfully. Its label remains plain text. The caller chooses placement; this helper neither binds a click handler nor hides a sibling layout. Keep its id aligned with static/app.mq.md. - -`attrs` = - -| id | type | disabled | -|---|---|---| -| `id` | button | True | - -We **style = ""**. -1. `secondary` - We **style = "secondary"**. -Return *[Describe one literal native action](component.element(kind="button", value=`label`, attrs=`attrs`, style=`style`, slot=`id`))*. - -## input - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Client value target | -| hint | text | required | Plain placeholder text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One disabled text input | - -Use `id` and `hint` for the draft or socket message. A native text input preserves its ordinary editing semantics and starts disabled until WASM is ready. The hint is placeholder text rather than a markup template. The component owns one control; the client selects its value through the wire table when the adjacent action is clicked. - -`attrs` = - -| id | type | placeholder | disabled | -|---|---|---|---| -| `id` | text | `hint` | True | - -Return *[Describe this native value input](component.element(kind="input", attrs=`attrs`, slot=`id`))*. - -## text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable output target | -| value | text | required | Literal initial text | -| kind | text | "text" | Native text or pre output | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One escaped text leaf | - -Use `id`, `value` and `kind`="text" for an output target. Select pre for the runtime log and ordinary text for the path, tick count or network outcome. Initial and later content stays literal: the renderer escapes this value and callbacks use set_text. This leaf declares no timer or network operation; those belong to the browser program. - -We **attrs = [Retain the exact output target](table.put(in=None, at="id", value=`id`))**. -Return *[Describe the literal output leaf](component.element(kind=`kind`, value=`value`, attrs=`attrs`, slot=`id`))*. diff --git a/examples/browser-app/components/home/editor.mq.md b/examples/browser-app/components/home/editor.mq.md deleted file mode 100755 index 34f6019..0000000 --- a/examples/browser-app/components/home/editor.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: Draft and list editor -import: - controls: ../controls.mq.md - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -The editor contains one draft input, three draft actions, the export actions and an initially empty native list. The client owns records, stable identities and delegated deletion; no authored list HTML is stored here. Save persists only the draft under this origin. Copy and Download export current item text while list state remains in browser session memory. - -We **heading = [Read the plain editor heading](component.markdown(text="## 待办"))** and **input = [Describe the exact draft target](controls.input(id="draft", hint="新项…"))** and **children = [Place input after its heading](table.concat(a=`heading`, b=`input`))**. - -`actions` = - -| @ | id | label | secondary | -|---|---|---|---| -| 1 | add | 添加 | False | -| 2 | save | 存草稿 | True | -| 3 | load | 读草稿 | True | -| 4 | copy-log | 复制列表 | True | -| 5 | dl-list | 下载列表 | True | - -- [Describe each native action leaf](for actions as action) - We **button = [Keep this action separate from state](controls.button(id=access(action, "id"), label=access(action, "label"), secondary=access(action, "secondary")))** and **children = [Preserve the authored action order](table.concat(a=`children`, b=`button`))**. -We **empty = [Start the empty native list](table.empty_list())** and **attrs = [Retain the delegated list target](table.put(in=None, at="id", value="items"))** and **list = [Describe the list container](component.wrap(children=`empty`, kind="list", attrs=`attrs`, slot="items"))**. -Return *[Keep the list after its editing controls](table.concat(a=`children`, b=`list`))*. diff --git a/examples/browser-app/components/home/index.mq.md b/examples/browser-app/components/home/index.mq.md deleted file mode 100755 index a13eaf0..0000000 --- a/examples/browser-app/components/home/index.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: Home panel assembly -import: - editor: editor.mq.md - timer: timer.mq.md - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -Home has two independent children: the list editor and the named timer. This parent expresses only that ordering and the panel identity used by the client. Start with Home visible; About and Network are hidden in their own definitions. State and transport do not belong in layout tables, and changing one child does not require copying the entire page. - -We **list = [Assemble the editor responsibility](editor.nodes())** and **clock = [Assemble the timer responsibility](timer.nodes())** and **children = [Keep the two home regions ordered](table.concat(a=`list`, b=`clock`))** and **attrs = [Name the client visibility target](table.put(in=None, at="id", value="panel-home"))**. -Return *[Describe the initially visible Home panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="home"))*. diff --git a/examples/browser-app/components/home/timer.mq.md b/examples/browser-app/components/home/timer.mq.md deleted file mode 100755 index e93f5db..0000000 --- a/examples/browser-app/components/home/timer.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: Named timer controls -import: - controls: ../controls.mq.md - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -This region describes the tick output and its two actions. The client increments retained state only when the named timer actually calls back. Start replaces a timer with the same id; Stop preserves the count. This layout performs no sleeping or counting on the server, and its native text output can be tested independently of timer scheduling. - -We **label = [Describe the timer label](component.markdown(text="计时(秒):"))** and **counter = [Describe the initial count](controls.text(id="tick", value="0"))** and **start = [Describe the explicit start action](controls.button(id="start-tick", label="开始"))** and **stop = [Describe the explicit stop action](controls.button(id="stop-tick", label="停止", secondary=True))** and **content = [Keep label before count](table.concat(a=`label`, b=`counter`))** and **actions = [Keep the two actions together](table.concat(a=`start`, b=`stop`))** and **children = [Place actions beside their output](table.concat(a=`content`, b=`actions`))**. -Return *[Wrap this one timer responsibility](component.wrap(children=`children`, kind="row", slot="timer"))*. diff --git a/examples/browser-app/components/index.mq.md b/examples/browser-app/components/index.mq.md deleted file mode 100755 index a9f7807..0000000 --- a/examples/browser-app/components/index.mq.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -markup: occlusion -title: Browser example recursive page assembly -import: - navigation: navigation.mq.md - home: home/index.mq.md - about: about.mq.md - network: network/index.mq.md - controls: controls.mq.md - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md - table: lib/table.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -Read this root to see the whole page: introduction, path, navigation, three panels, feedback and runtime. Follow one import at a time until a child is a plain Markdown leaf or native control. Business values never become a page HTML string. The official runtime starts only after the server has staged the current built assets and the actual client source. Controls stay disabled until boot succeeds; missing resources therefore remain visible as a loading failure. The readiness target and enable selectors are typed resource metadata, not executable snippets. Styles reference the generated stylesheet produced by serve. Server discovery reads the terminal content leaves under the granted root; the browser receives the same ordered region tree. - -We **source = [Read the plain introduction](fs.read_text(path="content/intro.md"))** and **intro = [Retain its Markdown](component.markdown(text=`source`, slot="intro"))** and **path = [Describe the initial pathname](controls.text(id="path", value="path: /"))** and **nav = [Assemble the authored destinations](navigation.nodes())** and **home = [Assemble list and timer](home.nodes())** and **about = [Read the About leaf](about.nodes())** and **network = [Assemble independent network controls](network.nodes())** and **log = [Describe literal runtime feedback](controls.text(id="log", value="loading…", kind="pre"))** and **style = [Reference the compiled declarative theme](component.asset(url="/static/theme.css", kind="stylesheet"))**. - -`runtime_attrs` = - -| type | data-mq-wasm | data-mq-source-url | data-mq-ready | data-mq-enable | -|---|---|---|---|---| -| module | "/static/marqdo_wasm.wasm" | "/static/app.mq.md" | "#log" | "#draft,#add,#save,#load,#start-tick,#stop-tick,#fetch-all,#ws-open,#ws-msg,#ws-send,#ws-close,#copy-log,#dl-list" | - -We **runtime = [Declare the official module and readiness targets](component.asset(url="/static/marqdo-bridge.js", attrs=`runtime_attrs`, slot="runtime"))**. - -`groups` = - -| rows | -|---| -| `intro` | -| `path` | -| `nav` | -| `home` | -| `about` | -| `network` | -| `log` | -| `style` | -| `runtime` | - -We **children = [Start the complete ordered page](table.empty_list())**. -- [Retain each independently inspectable region](for groups as group) - We **children = [Keep typed children in reading order](table.concat(a=`children`, b=`group`))**. -Return *[Wrap the recursive page once](component.wrap(children=`children`, slot="browser-app", style="browser-app"))*. diff --git a/examples/browser-app/components/navigation.mq.md b/examples/browser-app/components/navigation.mq.md deleted file mode 100755 index 2803473..0000000 --- a/examples/browser-app/components/navigation.mq.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -markup: occlusion -title: Three browser panel destinations -import: - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -Navigation contains three ordinary links with stable ids. Their fragment destinations leave a readable fallback without issuing a server page request. The official wire table intercepts each click and requests one deliberate history entry. Back and Forward only repaint the already selected panel. This component does not own client state or generate navigation JavaScript. - -`destinations` = - -| @ | id | href | label | -|---|---|---|---| -| 1 | nav-home | "#/" | 首页 | -| 2 | nav-about | "#/about" | 关于 | -| 3 | nav-net | "#/net" | 网络 | - -We **links = [Start the ordered native navigation](table.empty_list())**. -- [Declare each independently named destination](for destinations as destination) - We **label = [Read its literal label](access(destination, "label"))** and **id = [Read its stable event target](access(destination, "id"))** and **href = [Read its fallback destination](access(destination, "href"))**. - - `attrs` = - - | id | href | - |---|---| - | `id` | `href` | - - We **link = [Describe this native destination](component.element(kind="link", value=`label`, attrs=`attrs`))** and **links = [Preserve navigation order](table.concat(a=`links`, b=`link`))**. -Return *[Place those links in a navigation region](component.wrap(children=`links`, kind="nav", slot="navigation"))*. diff --git a/examples/browser-app/components/network/index.mq.md b/examples/browser-app/components/network/index.mq.md deleted file mode 100755 index 856ed49..0000000 --- a/examples/browser-app/components/network/index.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: Network panel assembly -import: - socket: socket.mq.md - controls: ../controls.mq.md - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -Network places plain explanatory content, the actual response output, a batch-fetch action and a local echo group. Batch requests retain the original public demonstration endpoint and may fail; ordered callback records show each status and body. Socket transport is local and independent. The panel starts hidden and the browser client alone selects it. - -We **heading = [Describe the network responsibility](component.markdown(text="## 网络\n\n批量请求显示每项的实际状态;WebSocket 使用本机 /live 回声服务。"))** and **output = [Describe literal transport feedback](controls.text(id="net-out", value="idle"))** and **fetch = [Describe the batch request action](controls.button(id="fetch-all", label="fetch_all ×2 uuid"))** and **echo = [Assemble local socket controls](socket.nodes())** and **first = [Place feedback below its explanation](table.concat(a=`heading`, b=`output`))** and **last = [Keep fetch before socket interaction](table.concat(a=`fetch`, b=`echo`))** and **children = [Preserve the two network responsibilities](table.concat(a=`first`, b=`last`))**. - -`attrs` = - -| id | hidden | -|---|---| -| panel-net | True | - -Return *[Describe the initially hidden Network panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="network"))*. diff --git a/examples/browser-app/components/network/socket.mq.md b/examples/browser-app/components/network/socket.mq.md deleted file mode 100755 index 9e88af9..0000000 --- a/examples/browser-app/components/network/socket.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -title: Local echo socket controls -import: - controls: ../controls.mq.md - table: lib/table.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured View rows for this component | - -The echo group contains Open, the message input, Send and Close as separate native leaves. The server binds /live, and the official bridge sends the browser program’s transport instructions. Actual lifecycle callbacks update the network output. This component performs no handshake itself and does not rely on availability of a public echo service. - -We **open = [Describe the connection action](controls.button(id="ws-open", label="WS 打开"))** and **message = [Describe exact message input](controls.input(id="ws-msg", hint="ws 消息"))** and **send = [Describe the explicit send action](controls.button(id="ws-send", label="WS 发送"))** and **close = [Describe the explicit close action](controls.button(id="ws-close", label="WS 关闭", secondary=True))** and **first = [Keep open before message entry](table.concat(a=`open`, b=`message`))** and **last = [Keep send before close](table.concat(a=`send`, b=`close`))**. -Return *[Keep the local echo interaction ordered](table.concat(a=`first`, b=`last`))*. diff --git a/examples/browser-app/content/about.md b/examples/browser-app/content/about.md deleted file mode 100755 index 2c3d352..0000000 --- a/examples/browser-app/content/about.md +++ /dev/null @@ -1,5 +0,0 @@ -## 关于 - -从 `index.mq.md` 阅读工程入口,沿 `components/index.mq.md` 逐层查看布局,再阅读 `static/app.mq.md` 的事件与回调。 - -普通内容使用 Markdown,控件使用原生节点,列表保留带独立 ID 的记录。浏览器执行官方 bridge 提供的 DOM、历史、存储与网络能力,无需作者撰写业务 JavaScript。 diff --git a/examples/browser-app/content/intro.md b/examples/browser-app/content/intro.md deleted file mode 100755 index 3bd163b..0000000 --- a/examples/browser-app/content/intro.md +++ /dev/null @@ -1,3 +0,0 @@ -# Marqdo browser-app - -列表、草稿存储、历史导航、计时、批量请求、WebSocket、剪贴板和下载。页面和业务流程均由 Marqdo 源码表达,浏览器宿主能力由官方 bridge 提供。 diff --git a/examples/browser-app/index.mq.md b/examples/browser-app/index.mq.md deleted file mode 100755 index c7e7fda..0000000 --- a/examples/browser-app/index.mq.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Marqdo browser-app -import: - page: components/index.mq.md - styles: styles/index.mq.md - web: ext/web/web.mq.md - http: ext/net/http.mq.md - socket: ext/net/websocket.mq.md - fs: lib/fs.mq.md - result: lib/result.mq.md ---- - -This is the callable engineering entry. Follow components/index.mq.md for recursive layout, static/app.mq.md for browser state and effects, and styles/index.mq.md for the retained theme. Plain content is Markdown; controls and resources remain native structured values. There is no authored HTML host or business JavaScript. Serve runs from the checkout root with --fs-root examples/browser-app. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Inspectable native page rows | - -The Document delegates page assembly to its component root. Home, About and Network are client panels within this one page, with their own independently readable components. The client controls visibility and history while ordinary content remains Markdown. This function does not start a server, fetch public endpoints or open a socket. Read the returned tree as layout data, and call serve for a real running application. - -Return *[Assemble the recursive browser demonstration](page.nodes())*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/browser-app" | Explicit site directory relative to the checkout | -| port | number | 18095 | Loopback listen port | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking listener or missing-asset failure | - -Use `root`="examples/browser-app" and `port`=18095 with plugin,fs.write,network.write and the site filesystem root. Build current browser assets through the development handbook first. Both generated assets must exist before theme compilation or listening; missing files produce an actionable Result. The native filesystem writes only the explicit compiled stylesheet. No Python static server or generated shell workflow is needed. - -Discovery prepares the Document and the static mount. Direct /about and /net visits redirect to the entry page, matching the transient panel-state model; Back and Forward inside a live page retain their actual history positions. A separate local network resource binds /live for anonymous demonstration echo. This loopback example does not authenticate or persist item records. Keep every returned app value and listen only after binding all resources. - -`assets` = - -| file | -|---| -| static/marqdo_wasm.wasm | -| static/marqdo-bridge.js | - -- [Require current official browser resources](for assets as file) - 1. not [The required runtime asset exists](fs.exists(path=`file`)) - Return *[Expose the actual build prerequisite](result.error(code="browser_app.assets", message="call build_browser and stage its assets in examples/browser-app/static before serve", operation="serve"))*. -We **css = [Compile the retained declarative theme](styles.css())** and **[Write only the generated stylesheet](fs.atomic_write(path="static/theme.css", text=`css`))** and **app = [Discover the native Document and static assets](web.prepare(root=`root`, host="127.0.0.1", port=`port`, static_dir="static"))** and **app = [Retain a direct About entry](http.redirect(app=`app`, from="/about", to="/", permanent=False))** and **app = [Retain a direct Network entry](http.redirect(app=`app`, from="/net", to="/", permanent=False))** and **app = [Bind the actual local echo resource](socket.route(app=`app`, path="/live", mode="echo", require_auth=False))**. -Return *[Listen after the real resources are ready](web.listen(app=`app`))*. diff --git a/examples/browser-app/static/app.mq.md b/examples/browser-app/static/app.mq.md deleted file mode 100755 index a6c4af8..0000000 --- a/examples/browser-app/static/app.mq.md +++ /dev/null @@ -1,568 +0,0 @@ ---- -markup: occlusion -title: Browser effects — native records and explicit completion -description: list CRUD, storage, navigate, interval, fetch_all, ws — GFM + lib/browser -import: - browser: lib/browser.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Initial browser view/state record | - -This entry prepares browser instructions; it does not itself fetch a URL or manipulate a server filesystem. The host page must supply the selectors listed below. List state uses native records with stable ids, keeping duplicate text and literal newlines independent. The wire table maps each UI event to one actual callback, including delegated item buttons, history navigation, timer controls, parallel fetches and a named WebSocket connection. - -Event declarations contain no user values interpolated into code. Input values flow through callback parameters while the server page remains a separate document. - -The returned boot record combines event registration and a storage lookup, without pushing an initial history entry. The browser bridge applies those instructions and dispatches later events into the callbacks. Draft text, tick count, route and socket identifier belong to that browser instance. Storage callbacks complete asynchronously; the initial return is not proof that a saved draft was found. - -We **ticks = 0** as the retained count before the first real timer event. -We **items = [Start native list state](table.empty_list())** and **next_id = 1** for independent record identities. -We **route_path = "/"** as this browser instance’s panel state. -We **ws_id = "echo"** as the one named local connection. - -`wire` = - -| @ | 选择器 | 事件 | 调用 | 委托 | 值选择器 | -|---|--------|------|------|------|----------| -| 1 | "#add" | click | add | | "#draft" | -| 2 | "#save" | click | save_draft | | "#draft" | -| 3 | "#load" | click | load_draft | | | -| 4 | "#start-tick" | click | start_tick | | | -| 5 | "#stop-tick" | click | stop_tick | | | -| 6 | "#nav-home" | click | go_home | | | -| 7 | "#nav-about" | click | go_about | | | -| 8 | "#nav-net" | click | go_net | | | -| 9 | "window" | popstate | on_pop | | | -| 10 | "#items" | click | on_item | "button[data-id]" | | -| 11 | "#fetch-all" | click | do_fetch_all | | | -| 12 | "#ws-open" | click | ws_open | | | -| 13 | "#ws-send" | click | ws_send | | "#ws-msg" | -| 14 | "#ws-close" | click | ws_close | | | -| 15 | "#copy-log" | click | copy_log | | | -| 16 | "#dl-list" | click | dl_list | | | - -`st` = - -| op | key | then | -|----|-----|------| -| get | mq-draft | on_draft | - -`boot` = - -| wire | storage | -|---|---| -| `wire` | `st` | - -After these steps, return *boot*. - -## add - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | "" | Exact draft text supplied by the add control | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native list refresh, input clear and focus; None for empty text | - -Use `value`="" from the input. Retain each nonempty value exactly as one record, including quotes, angle brackets or a literal newline. A monotonically assigned id separates duplicate titles; deleting one must not erase its siblings. This direct callback updates entry state, then passes those records explicitly to the pure renderer. No business value is interpolated into HTML. - -The input clears and regains focus after a real local addition. An empty string returns None without changing records or consuming an id. This list is session memory; only the separately saved draft uses browser storage. - -1. `value` == "" - Return *None* because there is no new item. -We **id = [Assign an independent stable identity](str(next_id))** and **next_id = next_id + 1**. - -`record` = - -| id | text | -|---|---| -| `id` | `value` | - -We **items = [Retain the actual text record](table.append(list=`items`, item=`record`))** and **view = [Render typed labels and delete controls](_list(records=`items`))** and **clear = [Clear the completed input](browser.set_value(sel="#draft", value=""))** and **focus = [Return to the draft control](browser.focus(sel="#draft"))**. -We **view = [Keep the independent list and value effects](browser.merge(a=`view`, b=`clear`))**. -Return *[Keep focus with the completed list update](browser.merge(a=`view`, b=`focus`))*. - -## on_item - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data_id | text | "" | Stable id supplied by the delegated delete button | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Remaining native records and removal feedback, or None for an unknown id | - -Use `data_id`="" from button[data-id]. Compare identities rather than text, so duplicate values and values containing newlines stay independent. Preserve remaining order and do nothing for an empty or unknown id. The renderer receives retained records explicitly; it does not infer client state inside a normal helper call. - -A deletion rebuilds the same list through typed controls and reports the removed id as text. It neither modifies a saved draft nor changes timer, transport or route state. Ids are not recycled after deletion, avoiding a stale event selecting a different later item. - -1. `data_id` == "" - Return *None* for an absent selection. -We **remaining = [Start the retained row order](table.empty_list())**. -- [Keep every record except the selected identity](for items as item) - 1. access(`item`, "id") != `data_id` - We **remaining = [Keep this independent record](table.append(list=`remaining`, item=`item`))**. -1. len(`remaining`) == len(`items`) - Return *None* because no selected identity exists. -We **items = remaining** and **view = [Render the actual retained rows](_list(records=`items`))** and **message = "removed " + data_id** and **status = [Describe the observed local removal](browser.set_text(sel="#log", text=`message`))**. -Return *[Keep list and feedback together](browser.merge(a=`view`, b=`status`))*. - -## save_draft - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | "" | Exact text selected from the draft input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Storage write request; completion arrives at on_saved | - -Use `value`="" from the draft control. The storage record names the local key and its completion callback. Return the request immediately; only on_saved can announce a successful write. An intentionally empty draft is valid and differs from an absent key. Storage belongs to this browser origin, while list records stay in session memory. Returning this record does not write server files or grant process access. - -`request` = - -| op | key | value | then | -|---|---|---|---| -| set | mq-draft | `value` | on_saved | - -Return *[Ask the browser to persist the exact draft](browser.storage(spec=`request`))*. - -## load_draft - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Storage read request with an explicit completion callback | - -Request mq-draft from this browser origin. The callback distinguishes a missing key, an empty saved value and a failed read. No input is cleared while the read is pending, and this operation never replaces the native item list. The same read runs at boot, so a reload restores the saved draft without claiming to persist list records. - -`request` = - -| op | key | then | -|---|---|---| -| get | mq-draft | on_draft | - -Return *[Request the stored draft and its actual outcome](browser.storage(spec=`request`))*. - -## on_draft - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Actual storage-read completion | -| value | text | "" | Stored draft text, including an intentionally empty value | -| found | bool | False | Whether the key actually existed | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Restored value and feedback, or actual missing/failure feedback | - -Use `ok`=True, `value`="" and `found`=False from storage. A missing key differs from a stored empty draft, and an unsuccessful read must not be described as absence. Restore the exact value only after a successful read with found=True. This changes the draft input, not the native item list, and never interprets the stored text as code. - -1. not `ok` - Return *[Keep a failed read visible](browser.set_text(sel="#log", text="draft read failed"))*. -1. not `found` - Return *[Keep an absent draft visible](browser.set_text(sel="#log", text="no draft"))*. -We **value_effect = [Restore exact stored draft text](browser.set_value(sel="#draft", value=`value`))** and **status = [Confirm the observed read](browser.set_text(sel="#log", text="draft loaded"))**. -Return *[Keep the actual value and feedback](browser.merge(a=`value_effect`, b=`status`))*. - -## start_tick - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | One named repeating timer instruction | - -Start tick at one-second intervals. The bridge replaces a timer with the same id, so repeated Start clicks do not accumulate independent clocks. Each callback increments the session counter once. This returns an instruction; it is neither a blocking sleep nor proof that one second has passed. Stop cancels future callbacks and preserves the accumulated display. - -Return *[Start or replace the one named timer](browser.interval(ms=1000, then="on_tick", id="tick"))*. - -## stop_tick - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Cancellation of the named timer | - -Cancel tick through its explicit id. Calling Stop before Start is harmless, and stopping does not reset the visible count or alter other timers. A later Start resumes counting from retained state. The browser owns the timer handle; authors do not keep a JavaScript handle or generate a client program to clear it. - -Return *[Cancel future callbacks for this timer](browser.clear_interval(id="tick"))*. - -## on_tick - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Whether this timer callback is valid | -| id | text | "" | Actual named timer id | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Updated count, or None for a failed/unrelated callback | - -Use `ok`=True and `id`="" from the timer. Count only successful events belonging to tick; unrelated callbacks must not change this counter. Retained ticks belongs to the direct browser callback, rather than being supplied by the event. A manual call to this function constructs the same text effect but does not prove that a real timer fired. - -1. not `ok` or `id` != "tick" - Return *None* for an unrelated timer outcome. -We **ticks = ticks + 1** and **label = [Format the actual accumulated count](str(ticks))**. -Return *[Display that observed timer count](browser.set_text(sel="#tick", text=`label`))*. - -## go_home - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Selected panel effects and one actual navigation request | - -Select / from its authored navigation control. This direct callback updates the retained panel state and requests exactly one history entry. The helper receives the path explicitly rather than assuming an ordinary call captures entry bindings. Back/Forward uses on_pop, which renders without navigation. No server request or page HTML is constructed here. - -We **route_path = "/"**. -Return *[Render and request this one deliberate navigation](_view(route=`route_path`, push=True))*. - -## go_about - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Selected panel effects and one actual navigation request | - -Select /about from its authored navigation control. This direct callback updates the retained panel state and requests exactly one history entry. The helper receives the path explicitly rather than assuming an ordinary call captures entry bindings. Back/Forward uses on_pop, which renders without navigation. No server request or page HTML is constructed here. - -We **route_path = "/about"**. -Return *[Render and request this one deliberate navigation](_view(route=`route_path`, push=True))*. - -## go_net - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Selected panel effects and one actual navigation request | - -Select /net from its authored navigation control. This direct callback updates the retained panel state and requests exactly one history entry. The helper receives the path explicitly rather than assuming an ordinary call captures entry bindings. Back/Forward uses on_pop, which renders without navigation. No server request or page HTML is constructed here. - -We **route_path = "/net"**. -Return *[Render and request this one deliberate navigation](_view(route=`route_path`, push=True))*. - -## on_pop - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | "" | Actual browser pathname, including optional query string | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | History-selected panel effects without pushing history again | - -Use `path`="" from the real popstate callback. Keep its normalized panel route in the differently named entry state, avoiding accidental shadowing of a callback parameter. The browser has already selected this history entry, so returning navigate would add an incorrect new entry. Query text does not choose a different panel; only the known pathname is used. - -We **parts = [Separate the pathname from query text](text.str_split(s=`path`, sep="?"))** and **route_path = [Keep the actual panel path](table.first(list=`parts`))**. -Return *[Reflect the actual history position](_view(route=`route_path`))*. - -## show_path - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Current panel visibility and label without history mutation | - -This direct browser callback reads retained route_path and delegates pure rendering with explicit input. It never pushes another history entry, so a repaint cannot trap Back/Forward. Call the navigation callbacks to request a new route. Server routing and page structure remain separate responsibilities; unknown browser paths select the home panel. - -Return *[Refresh the retained panel without navigating](_view(route=`route_path`))*. - -## do_fetch_all - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -Queue two independent browser fetches and return an immediate loading message together with the request instruction. Results arrive through on_fetch_all; this initial return does not contain either HTTP response. The request table keeps both URLs visible and avoids generating JavaScript to construct the batch. - -The example endpoint is external and may fail or be unavailable. Consumers must inspect the actual callback records rather than count request declarations as successful responses. Browser network policy still applies; no backend file or shell operation is authorized by this instruction. - -`reqs` = - -| @ | url | -|---|-----| -| 1 | "https://httpbin.org/uuid" | -| 2 | "https://httpbin.org/uuid" | - -We **msg = [Describe the pending batch](browser.set_text(sel="#net-out", text="fetch_all…"))** and **requests = [Request both actual HTTP outcomes](browser.fetch_all(requests=`reqs`, then="on_fetch_all"))**. -Return *[Keep pending feedback with its asynchronous requests](browser.merge(a=`msg`, b=`requests`))*. - -## on_fetch_all - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Whether the batch callback itself completed | -| results | any | None | Ordered per-request ok/status/body/error records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Actual per-request outcomes shown as plain text | - -Use `ok`=True and `results`=None from the bridge. A completed batch can still contain failed HTTP or network operations; the outer callback flag does not make each record successful. Show the real ordered records, including status, body and errors, rather than a fixed completion message. Text output cannot become HTML or a browser command. - -A missing result list stays visibly unavailable. Public endpoints remain demonstration dependencies; local tests supply controlled responses and a failure. This callback does not retry a request or replace its body with a predetermined answer. - -1. not `ok` - Return *[Keep batch failure visible](browser.set_text(sel="#net-out", text="fetch_all failed"))*. -1. `results` == None - Return *[Keep absent results distinct](browser.set_text(sel="#net-out", text="fetch_all returned no results"))*. -We **message = [Retain actual request outcomes](str(results))**. -Return *[Display observed successes and failures literally](browser.set_text(sel="#net-out", text=`message`))*. - -## ws_open - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Named local WebSocket request and lifecycle callbacks | - -Open the site’s /live echo resource under the explicit echo id. A relative URL uses the current origin and its transport security, allowing the example to run without a public echo provider. The server separately binds this native network resource. Returning the record only requests a connection; open, message, error and close callbacks describe actual transport outcomes. Subsequent send and close instructions reuse the same id. - -`request` = - -| op | id | url | then_open | then_message | then_error | then_close | -|---|---|---|---|---|---|---|---| -| open | `ws_id` | "/live" | on_ws_open | on_ws_msg | on_ws_err | on_ws_close | - -Return *[Request the local echo connection](browser.ws(spec=`request`))*. - -## on_ws_open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Actual connection completion | -| id | text | "" | Connected socket id | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Confirmed connection text, or None for a failed/unrelated callback | - -Use `ok`=True and `id`="" from the real transport. Accept only the named echo socket; a different resource cannot announce this widget ready. This callback confirms the handshake, while sending still requires a separate user action. It neither invents a received message nor marks a requested connection successful before the bridge reports it. - -1. not `ok` or `id` != `ws_id` - Return *None* for an unrelated connection. -Return *[Confirm the observed handshake](browser.set_text(sel="#net-out", text="ws open"))*. - -## on_ws_msg - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Actual message completion | -| data | text | "" | Exact received text | -| id | text | "" | Receiving socket id | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Literal received message, or None for a failed/unrelated callback | - -Use `ok`=True, `data`="" and `id`="" from the echo connection. Preserve the complete received text, including quotes and angle brackets. Display it through set_text so a message is data rather than page markup. Receipt is independent of the send click: the remote resource may respond later or close without replying. - -1. not `ok` or `id` != `ws_id` - Return *None* for an unrelated message. -We **message = "ws ← " + data**. -Return *[Display the actual echo as plain text](browser.set_text(sel="#net-out", text=`message`))*. - -## on_ws_err - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | False | Failure flag supplied by the bridge | -| error | text | "" | Actual transport failure text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Visible transport failure | - -Use `ok`=False and `error`="" from the transport callback. Keep the actual error text in the output rather than substituting a success message. The callback performs no automatic reconnect and sends no pending message. Reopening is an explicit user operation; failures remain inspectable while the rest of the page can continue operating. - -We **message = "ws error: " + error**. -Return *[Expose the actual connection failure](browser.set_text(sel="#net-out", text=`message`))*. - -## on_ws_close - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Actual close callback flag | -| id | text | "" | Closed socket id | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Observed close text, or None for an unrelated socket | - -Use `ok`=True and `id`="" after the bridge observes closure. The named socket may close because of the user’s request or the server. This is a lifecycle observation and does not itself initiate another close or reopen. Leave list state, draft and timer untouched so transport changes remain independent of local page work. - -1. `id` != `ws_id` - Return *None* for an unrelated socket. -Return *[Report the observed connection closure](browser.set_text(sel="#net-out", text="ws closed"))*. - -## ws_send - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | "" | Exact text selected from the message input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Send request for the existing named socket | - -Use `value`="" as the message payload. Sending preserves literal text and addresses the existing echo socket; it does not create a second hidden connection. Open first and wait for the real connection callback. The request is not an echo result: only on_ws_msg displays a received response, and transport failures remain visible through the bridge. - -`request` = - -| op | id | data | -|---|---|---| -| send | `ws_id` | `value` | - -Return *[Send exact text through the named connection](browser.ws(spec=`request`))*. - -## ws_close - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Close request for the named socket | - -Ask the bridge to close echo, reusing the same identity as open and send. The close callback supplies the observed lifecycle result. Returning this instruction does not delete page records or cancel the independent timer. Closing an absent connection is harmless; opening a later connection remains an explicit user action. - -`request` = - -| op | id | -|---|---| -| close | `ws_id` | - -Return *[Request closure of this connection](browser.ws(spec=`request`))*. - -## copy_log - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Clipboard request and truthful queued feedback | - -Export the retained item texts in their current order, including duplicate values and literal newlines. The native records remain unchanged. This browser capability is a request: policy, user activation or the destination environment may prevent completion. The bridge exposes errors, and the immediate feedback says queued because no completion callback confirms a final clipboard write or saved file. - -We **plain = [Read the current literal list export](_plain(records=`items`))** and **request = [Request clipboard delivery](browser.clipboard(text=`plain`))** and **status = [Describe only the requested operation](browser.set_text(sel="#log", text="clipboard request queued"))**. -Return *[Keep the request and its truthful feedback](browser.merge(a=`request`, b=`status`))*. - -## dl_list - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Download request and truthful queued feedback | - -Export the retained item texts in their current order, including duplicate values and literal newlines. The native records remain unchanged. This browser capability is a request: policy, user activation or the destination environment may prevent completion. The bridge exposes errors, and the immediate feedback says queued because no completion callback confirms a final clipboard write or saved file. - -We **plain = [Read the current literal list export](_plain(records=`items`))** and **request = [Request the plain-text download](browser.download(body=`plain`, filename="items.txt"))** and **status = [Describe only the requested operation](browser.set_text(sel="#log", text="download request queued"))**. -Return *[Keep the request and its truthful feedback](browser.merge(a=`request`, b=`status`))*. - -## _list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| records | list | required | Native id/text records in visible order | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Structured list effect with literal labels and native delete buttons | - -Use `records` from the direct callback's retained state. Each row contains a span label and button as typed children. The button's data-id carries the independent record identity; visible business text stays in text, never html. The official bridge escapes it and preserves delegation without rebuilding the parent page. - -This helper is pure and receives records explicitly. It does not read hidden entry state, delete anything or assume that a returned effect has already reached the DOM. The existing host list and event wiring own those later steps. - -We **rows = [Start the native visible row records](table.empty_list())**. -- [Describe one label and native delete action](for records as record) - We **id = [Retain the exact row identity](access(record, "id"))** and **value = [Retain literal business text](access(record, "text"))**. - - `label` = - - | tag | text | - |---|---| - | span | `value` | - - `attributes` = - - | type | data-id | - |---|---| - | button | `id` | - - `button` = - - | tag | text | attrs | - |---|---|---| - | button | 删 | `attributes` | - - `children` = - - | node | - |---| - | `label` | - | `button` | - - `row` = - - | tag | children | - |---|---| - | li | `children` | - - We **rows = [Retain this typed row](table.append(list=`rows`, item=`row`))**. -Return *[Update only the existing list](browser.render_list(sel="#items", items=`rows`))*. - - -## _view - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| route | text | required | Selected panel pathname | -| push | bool | False | Explicit navigation callback requests one history entry | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Actual boolean panel visibility, path label and optional deliberate navigation | - -Use `route` and `push`=False. Only /about and /net select secondary panels; other paths render Home. Hidden attributes are actual booleans, while False removes the attribute. The pure helper receives its path explicitly and does not pretend to capture the browser entry state. - -History observations use the default without navigation; authored link callbacks opt in once. Keep all three targets inside a single set_attr record because effect merging is shallow and otherwise one target map could overwrite another. This function performs no fetch, storage write or socket operation. - -We **selected = "/"**. -1. `route` == "/about" or `route` == "/net" - We **selected = route**. -We **home = [Describe Home visibility](table.put(in=None, at="hidden", value=(`selected` != "/")))** and **about = [Describe About visibility](table.put(in=None, at="hidden", value=(`selected` != "/about")))** and **network = [Describe Network visibility](table.put(in=None, at="hidden", value=(`selected` != "/net")))**. - -`targets` = - -| #panel-home | #panel-about | #panel-net | -|---|---|---| -| `home` | `about` | `network` | - -We **visibility = [Keep every panel target together](browser.wrap(key="set_attr", value=`targets`))** and **message = "path: " + selected** and **label = [Display the selected path](browser.set_text(sel="#path", text=`message`))** and **effects = [Keep independent visibility and text effects](browser.merge(a=`visibility`, b=`label`))**. -1. `push` - We **navigation = [Request one intentional history entry](browser.navigate(url=`selected`))** and **effects = [Keep navigation with its actual panel effects](browser.merge(a=`effects`, b=`navigation`))**. -Return *effects* after describing the real selected panel. - - -## _plain - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| records | list | required | Native text records in retained order | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Literal newline-joined values for copy or download | - -Use `records` to retain the original plain-text export purpose without turning the client state into a newline-encoded database. Each item's text remains a single native value; newlines are introduced only in this human-readable export. This pure transformation neither writes the clipboard nor starts a download, and it does not encode HTML. - -We **values = [Select actual text fields in order](table.pluck(list=`records`, key="text"))**. -Return *[Form the intended text export](text.str_join(xs=`values`, sep="\n"))*. - -## on_saved - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Actual storage-write completion | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Feedback for the completed write | - -Use `ok`=True from the storage callback. Confirm saving after the browser reports completion, rather than when the user merely clicks Save. A failed callback remains a failure message. Host storage exceptions also appear through the official bridge error channel; this function cannot turn an unavailable storage service into a successful write. - -1. not `ok` - Return *[Expose the failed write](browser.set_text(sel="#log", text="draft save failed"))*. -Return *[Confirm the completed write](browser.set_text(sel="#log", text="draft saved"))*. diff --git a/examples/browser-app/styles/index.mq.md b/examples/browser-app/styles/index.mq.md deleted file mode 100755 index 304ae64..0000000 --- a/examples/browser-app/styles/index.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: Retained browser theme compilation -import: - document: lib/document.mq.md - web: ext/web/web.mq.md - text: lib/text.mq.md ---- - -## css - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Original theme declarations followed by bounded View geometry | - -Call with fs.read and plugin under the site root. The original table retains every declaration from the former host page, including fonts, green palette, panel spacing and feedback surfaces. The geometry table only adapts native View wrappers and long text for a narrow viewport. Compilation returns CSS through the existing native style capability; it neither writes a file nor starts a server. Serve owns the explicit generated output. Review the data leaf when adjusting appearance and verify actual computed styles in the browser. - -We **original = [Read all retained declarations](document.read_table(path="styles/theme.tables.md", title="original"))** and **geometry = [Read explicit native wrapper rules](document.read_table(path="styles/theme.tables.md", title="geometry"))** and **base = [Compile the retained theme](web.make_style(name="original", table=`original`))** and **wrappers = [Compile bounded View adaptation](web.make_style(name="geometry", table=`geometry`))**. -Return *[Keep original cascade before native adaptation](`base` + "\n" + `wrappers`)*. diff --git a/examples/browser-app/styles/theme.tables.md b/examples/browser-app/styles/theme.tables.md deleted file mode 100755 index 87eb0ae..0000000 --- a/examples/browser-app/styles/theme.tables.md +++ /dev/null @@ -1,88 +0,0 @@ -# Browser example theme - -This literal data preserves the original browser-app palette, typefaces, spacing, backgrounds and controls. Region selectors are scoped to the native View frame. Callable compilation is documented in index.mq.md beside this data. - -## original - -Every original declaration appears in its original order. Only selectors gain the known frame address, keeping basic preview defaults from overriding the authored theme. - -| selector | property | value | -|---|---|---| -| ":root" | "--ink" | "#1a1f1c" | -| ":root" | "--paper" | "#e8efe6" | -| ":root" | "--accent" | "#2f6f4e" | -| ":root" | "--muted" | "#5a6b60" | -| "*" | "box-sizing" | "border-box" | -| "body" | "margin" | "0" | -| "body" | "min-height" | "100vh" | -| "body" | "font-family" | "\"IBM Plex Sans\", \"Noto Sans SC\", sans-serif" | -| "body" | "color" | "var(--ink)" | -| "body" | "background" | "linear-gradient(165deg, #f3f7f2, var(--paper))" | -| "body" | "padding" | "2rem clamp(1rem, 4vw, 3rem)" | -| ".mq-document .browser-app h1" | "font-family" | "\"IBM Plex Serif\", \"Noto Serif SC\", serif" | -| ".mq-document .browser-app h1" | "margin" | "0 0 0.35rem" | -| ".mq-document .browser-app .lead" | "color" | "var(--muted)" | -| ".mq-document .browser-app .lead" | "max-width" | "42rem" | -| ".mq-document .browser-app nav a" | "margin-right" | "0.75rem" | -| ".mq-document .browser-app nav a" | "color" | "var(--accent)" | -| ".mq-document .browser-app section" | "margin" | "1.5rem 0" | -| ".mq-document .browser-app section" | "padding" | "1rem 0" | -| ".mq-document .browser-app section" | "border-top" | "1px solid #c5d4c9" | -| ".mq-document .browser-app #path" | "font-family" | "ui-monospace, monospace" | -| ".mq-document .browser-app #path" | "color" | "var(--muted)" | -| ".mq-document .browser-app #items" | "list-style" | "none" | -| ".mq-document .browser-app #items" | "padding" | "0" | -| ".mq-document .browser-app #items" | "margin" | "0.75rem 0" | -| ".mq-document .browser-app #items li" | "display" | "flex" | -| ".mq-document .browser-app #items li" | "align-items" | "center" | -| ".mq-document .browser-app #items li" | "gap" | "0.5rem" | -| ".mq-document .browser-app #items li" | "padding" | "0.4rem 0.6rem" | -| ".mq-document .browser-app #items li" | "margin-bottom" | "0.35rem" | -| ".mq-document .browser-app #items li" | "background" | "rgba(255,255,255,0.65)" | -| ".mq-document .browser-app #items li" | "border" | "1px solid #b7c7bb" | -| ".mq-document .browser-app #items button" | "margin-left" | "auto" | -| ".mq-document .browser-app input[type=\"text\"]" | "padding" | "0.45rem 0.65rem" | -| ".mq-document .browser-app input[type=\"text\"]" | "border" | "1px solid #b7c7bb" | -| ".mq-document .browser-app input[type=\"text\"]" | "width" | "min(16rem, 70%)" | -| ".mq-document .browser-app button" | "padding" | "0.45rem 0.9rem" | -| ".mq-document .browser-app button" | "border" | "0" | -| ".mq-document .browser-app button" | "background" | "var(--accent)" | -| ".mq-document .browser-app button" | "color" | "#f5faf6" | -| ".mq-document .browser-app button" | "font" | "inherit" | -| ".mq-document .browser-app button" | "cursor" | "pointer" | -| ".mq-document .browser-app button" | "margin" | "0.2rem 0.35rem 0.2rem 0" | -| ".mq-document .browser-app button.secondary" | "background" | "#3a4740" | -| ".mq-document .browser-app #tick, #net-out" | "font-variant-numeric" | "tabular-nums" | -| ".mq-document .browser-app #net-out" | "min-height" | "2.5rem" | -| ".mq-document .browser-app #net-out" | "padding" | "0.6rem 0.75rem" | -| ".mq-document .browser-app #net-out" | "background" | "rgba(255,255,255,0.55)" | -| ".mq-document .browser-app #net-out" | "border" | "1px solid #b7c7bb" | -| ".mq-document .browser-app #net-out" | "white-space" | "pre-wrap" | -| ".mq-document .browser-app #net-out" | "word-break" | "break-all" | -| ".mq-document .browser-app pre" | "margin-top" | "1rem" | -| ".mq-document .browser-app pre" | "padding" | "0.85rem 1rem" | -| ".mq-document .browser-app pre" | "background" | "#122018" | -| ".mq-document .browser-app pre" | "color" | "#d7eadc" | -| ".mq-document .browser-app pre" | "font-size" | "0.8rem" | -| ".mq-document .browser-app pre" | "overflow" | "auto" | -| ".mq-document .browser-app pre" | "max-width" | "42rem" | -| ".mq-document .browser-app .err" | "color" | "#ffb4a8" | - -## geometry - -These additions adapt the preview wrappers and keep native controls and literal long text within a narrow viewport. They do not replace the retained palette or typography. - -| selector | property | value | -|---|---|---| -| ".mq-document .mq-view" | "max-width" | "none" | -| ".mq-document .mq-view" | "margin" | "0" | -| ".mq-document .mq-view" | "padding" | "0" | -| ".mq-document .mq-view" | "font-family" | "inherit" | -| ".mq-document .mq-view" | "line-height" | "inherit" | -| ".mq-document .browser-app" | "display" | "block" | -| ".mq-document .browser-app .mq-column" | "display" | "block" | -| ".mq-document .browser-app .mq-row" | "flex-wrap" | "wrap" | -| ".mq-document .browser-app #items span" | "overflow-wrap" | "anywhere" | -| ".mq-document .browser-app button" | "max-width" | "100%" | -| ".mq-document .browser-app pre" | "white-space" | "pre-wrap" | -| ".mq-document .browser-app pre" | "overflow-wrap" | "anywhere" | diff --git a/examples/calculator.mq.md b/examples/calculator.mq.md deleted file mode 100755 index 6d5c841..0000000 --- a/examples/calculator.mq.md +++ /dev/null @@ -1,39 +0,0 @@ -# 计算器 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | - -这是一个普通的 Marqdo 文档。 - -其中包含一些可以复用的数学计算知识。 - -## 加法 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | Left operand supplied to this calculation | -| b | any | 必填 | Right operand supplied to this calculation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -计算两个数字`a`和`b`的和。 - -完成上述步骤后,返回*[计算结果]((`a` + `b`))*。 - -## 乘法 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | Left operand supplied to this calculation | -| b | any | 必填 | Right operand supplied to this calculation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -计算两个数字`a`和`b`的积。 - -完成上述步骤后,返回*[计算结果]((`a` * `b`))*。 diff --git a/examples/code-as-docs/README.md b/examples/code-as-docs/README.md deleted file mode 100755 index 3d0925c..0000000 --- a/examples/code-as-docs/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# 代码即文档 · 周末咖啡手账 - -```bash -marqdo run examples/code-as-docs/index.mq.md -``` - -菜单与订单是表,计价嵌在段落里,结账像写日记。取元用 `[键](集合)`,循环用 `- [行](订单)`,与 [collection-access-link.md](../../doc/design/collection-access-link.md) 一致。 diff --git a/examples/code-as-docs/index.mq.md b/examples/code-as-docs/index.mq.md deleted file mode 100755 index 03ccc8a..0000000 --- a/examples/code-as-docs/index.mq.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -markup: occlusion -title: 代码即文档 · 周末咖啡手账 -description: >- - 一份可读可跑的周末手账:菜单是表,计价写在段落里,结账读起来像日记。 ---- - -周六的咖啡馆手账——下面既是给人看的说明,也是可以 `marqdo run` 的程序。 -**说明**性的加粗只是强调;真正算账的步骤也用粗体写在句子里,算完的值用斜体交回去。 - ---- - -## 单价 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 价 | any | 必填 | 同一币种下单件商品的标价 | -| 杯数 | any | 1 | 参与本次计价的杯数,未提供时使用正文默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 逐行累加得到的订单总额 | - -一杯标价为`价`的饮品,默认`杯数`=1。先把**总额 = 价 * 杯数**算清,再返回*总额*。 - -## 会员折 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 原价 | any | 必填 | 应用折扣之前的原始金额 | -| 折扣 | any | 0.85 | 价格乘数;0.85 表示支付原价的百分之八十五 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -会员单要原价`原价`;店里默认八五折,记作`折扣`=0.85。 -先算**应付 = 原价 * 折扣**,再返回*应付*。 - -## 结账摘要 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 品名 | any | 必填 | 收据或摘要中显示的商品名称 | -| 价 | any | 必填 | 同一币种下单件商品的标价 | -| 杯数 | any | 1 | 参与本次计价的杯数,未提供时使用正文默认值 | -| 会员 | any | False | 是否采用本示例的会员折扣分支 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 包含商品、数量和实付金额的显示文案 | - -客人点了`品名`,单价`价`,杯数`杯数`=1;是否`会员`=False。 - -按杯数问单价:**小计 = 单价 价=`价` 杯数=`杯数`**。 - -1. `会员` - 我们先**实付 = [计算并保存 实付](会员折(原价=`小计`))**,供下一步使用。 - 我们先**标签 = "会员价"**,供下一步使用。 -2. * - 我们先**实付 = `小计`**,供下一步使用。 - 我们先**标签 = "原价"**,供下一步使用。 - -对账时拼成一句人话: - -我们先**文案 = ((((((`品名` + " ×") + `杯数`) + " → ") + `标签`) + " ") + `实付`)**,供下一步使用。 -完成上述步骤后,返回*文案*。 - -## 印章加一 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 印 | any | 必填 | 积分卡当前已有的印章数量 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -积分卡上的`印`,每喝一杯就**印 = 印 + 1**,接着返回*印*。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -这份手账把定价规则放在真正的结账函数里,入口只组织今天的几笔订单。菜单横表是品名到单价的记录,外卖行表则是多条带有数量和会员标记的订单;两者的数据形态不同,因此先按名称取价,再逐行传给同一个摘要函数。 - -会员示例与原价对照使用同一套参数和默认值,避免正文与实现各维护一份优惠规则。金额在本例中使用普通运行时数值,会员折扣可能产生小数;这里没有宣称采用专门的货币舍入模型。需要真实计费精度时应另行规定最小单位与舍入步骤,不能把展示摘要的文本当成准确记账凭证。 - -打印的是已经计算出的摘要,后续业务若要复用它应直接传递该值,而不是解析输出文字。最后给积分卡加一只改变演示中的印章值,不写入用户文件,也不代表某个真实账户已经更新。 - -今日黑板价目——表格给人扫一眼,程序当字典用: - -`菜单` = - -| 美式 | 拿铁 | 燕麦拿铁 | -|------|------|----------| -| 18 | 28 | 32 | - ---- - -上午来了位会员,点两杯拿铁。品名写进`名`,价钱从菜单里取: - -我们先**名 = "拿铁"**,供下一步使用。 -我们先**价 = [名](access(`菜单`, `名`))**,供下一步使用。 -我们先**摘要 = [计算并保存 摘要](结账摘要(品名=`名`, 价=`价`, 杯数=2, 会员=True))**,供下一步使用。 -**打印 内容=`摘要`** - -旁桌只要一杯普通美式,对照一下原价: - -我们先**对照 = [计算并保存 对照](结账摘要(品名="美式", 价=[美式](access(`菜单`, "美式"))))**,供下一步使用。 -**打印 内容=`对照`** - ---- - -下午把外卖单抄成行表,一行一行结: - -`今日订单` = - -| @ | 品名 | 单价 | 杯数 | 会员 | -|---|------|------|------|------| -| 1 | 燕麦拿铁 | 32 | 1 | True | -| 2 | 美式 | 18 | 2 | False | - -- [行](遍历 今日订单 为 行) - 我们先**一行 = [计算并保存 一行](结账摘要(品名=[品名](access(`行`, "品名")), 价=[单价](access(`行`, "单价")), 杯数=[杯数](access(`行`, "杯数")), 会员=[会员](access(`行`, "会员"))))**,供下一步使用。 - **打印 内容=`一行`** - -打烊前给积分卡盖一个章: - -我们先**印 = 41**,供下一步使用。 -我们先**印 = [计算并保存 印](印章加一(印=`印`))**,供下一步使用。 -**打印 内容=`印`** diff --git a/examples/engineering-knowledge/config/resolve.mq.md b/examples/engineering-knowledge/config/resolve.mq.md deleted file mode 100755 index b434e95..0000000 --- a/examples/engineering-knowledge/config/resolve.mq.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -markup: occlusion -title: resolve_config -capability: config.resolve -status: stable ---- - -Use when: final normalized configuration is required. - -# config - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Object/type namespace for the child functions below; call the intended child directly | - -## resolve_config - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Filesystem path under the granted root; this callback's prose identifies URL paths separately | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; this unit completes the operations described below without a data return | -The shared input protocol also accepts `path`. We **[Accept this documented input without changing the result](`path`)**. - -Input `path`, used by the steps below. - -`defaults` = - -| host | port | -|------|------| -| localhost | 8080 | - -* defaults diff --git a/examples/engineering-knowledge/index.mq.md b/examples/engineering-knowledge/index.mq.md deleted file mode 100755 index f00f871..0000000 --- a/examples/engineering-knowledge/index.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: Engineering Knowledge demo -description: Tiny project demonstrating Capability Catalog + reuse + decisions. ---- - -# Engineering Knowledge demo - - -This folder is a miniature “large engineering” slice: config resolution already exists. -Before generating a new loader, run: - -```bash -marqdo knowledge examples/engineering-knowledge -o examples/engineering-knowledge/.marqdo -marqdo reuse "load and resolve configuration" examples/engineering-knowledge -o examples/engineering-knowledge/.marqdo -marqdo duplicate examples/engineering-knowledge -o examples/engineering-knowledge/.marqdo -``` - -Expected: **REUSE config.resolve**, not a new `load_configuration`. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -* "see README via catalog/reuse CLI" diff --git a/examples/engineering-knowledge/knowledge/adr-022.md b/examples/engineering-knowledge/knowledge/adr-022.md deleted file mode 100755 index 1b39083..0000000 --- a/examples/engineering-knowledge/knowledge/adr-022.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -type: Decision -id: ADR-022 -title: Cache is not persistence -status: accepted -applies_to: - - config.resolve ---- - -# Cache is not persistence - -## Decision - -Redis is only used for ephemeral cache. - -## Reason - -The application must remain correct when Redis is unavailable. diff --git a/examples/engineering-knowledge/knowledge/c-014.md b/examples/engineering-knowledge/knowledge/c-014.md deleted file mode 100755 index d30ab5f..0000000 --- a/examples/engineering-knowledge/knowledge/c-014.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -type: Constraint -id: C-014 -title: Centralized config resolution -status: stable -applies_to: - - config.resolve ---- - -# Centralized config resolution - -All configuration resolution must go through `resolve_config`. diff --git a/examples/engineering-knowledge/knowledge/f-008.md b/examples/engineering-knowledge/knowledge/f-008.md deleted file mode 100755 index f0b4b7c..0000000 --- a/examples/engineering-knowledge/knowledge/f-008.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -type: Failure -id: F-008 -title: Do not invent a second config loader -status: resolved ---- - -# Do not invent a second config loader - -## Failed approach - -Added `load_configuration` beside `resolve_config`. - -## Failure - -Divergent defaults and error handling. - -## Correct approach - -Call `resolve_config`. diff --git a/examples/executable-knowledge/README.md b/examples/executable-knowledge/README.md deleted file mode 100755 index 81e3a27..0000000 --- a/examples/executable-knowledge/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# 可执行知识系统示例:订单含税总额 - -这是 [可执行知识系统设计](../../doc/design/executable-knowledge-system.md) 的目标示例, -已按当前 occlusion 语法落地为**可运行**订单链(Tree / Bytecode)。 - -| 文件 | 图中的职责 | 关键步骤 | -|---|---|---| -| `corpus/tax-policy-2026.md` | E:证据 | 税率原文 | -| `schema/order.mq.md` | C:概念 | 订单/订单行字段与单位 | -| `knowledge/tax-2026.mq.md` | K:原子知识 | `标准税率.查询` + `sources:` | -| `knowledge/negative-refund.mq.md` | 负知识 | 折扣不适用于退款 | -| `capabilities/order-pricing.mq.md` | D:推导知识 | 取元、调用、循环、汇总 | -| `docs/invoice-answer.mq.md` | N:叙述知识 | 含税结论 + NarrativeRef | - -## 运行 - -```bash -marqdo run examples/executable-knowledge/docs/invoice-answer.mq.md --backend tree -marqdo run examples/executable-knowledge/docs/invoice-answer.mq.md --backend bytecode -# → 113 -marqdo knowledge examples/executable-knowledge -o /tmp/ek -marqdo knowledge impact "标准税率.查询" examples/executable-knowledge --json -``` - -门禁:`cargo test --test executable_knowledge s4_examples_bookstore_chain_runs_both_backends --locked` - -## 读法 - -`[]()` 的每一次出现都是命名步骤(observe / derive / iterate / call / narrate): - -```markdown -[订单行金额](access(行, "金额")) # observe -[本行含税价](金额 * (1 + 税率)) # derive -[逐个订单行](遍历 行列表 为 行) # iterate -这张订单的含税总额是[含税总价](总额)。 # narrate -``` - -## 运行状态 - -| 子集 | 状态 | 证据 | -|---|---|---| -| 发票含税链双后端 `113` | **可运行** | 上表命令 / EK 门禁 | -| 来源 `sourced` + impact 下游 | **可运行** | knowledge 投影 + impact | -| 负知识文档 | **已收录** | `knowledge/negative-refund.mq.md`(发现层;非执行目标) | diff --git a/examples/executable-knowledge/capabilities/order-pricing.mq.md b/examples/executable-knowledge/capabilities/order-pricing.mq.md deleted file mode 100755 index 0137b56..0000000 --- a/examples/executable-knowledge/capabilities/order-pricing.mq.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -markup: occlusion -id: capability.order-pricing -type: Capability -import: - tax: ../knowledge/tax-2026.mq.md ---- - -# 订单定价 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | - -按订单行取未税金额与品类,套用税率后汇总含税总额。 - -## 含税价 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行 | any | 必填 | 订单行记录;按相邻数据表提供金额、品类等字段 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 本次计算得到的结果 | - -输入`行`,按下方步骤使用这个值。 - -我们先**金额 = [订单行金额](access(`行`, "金额"))**,供下一步使用。 -我们先**品类 = [订单行品类](access(`行`, "品类"))**,供下一步使用。 -我们先**税率 = [计算并保存 税率](tax.标准税率.查询(品类=`品类`))**,供下一步使用。 -我们先**结果 = [本行含税价]((`金额` * (1 + `税率`)))**,供下一步使用。 -完成上述步骤后,返回*结果*。 - -## 含税总额 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 订单 | any | 必填 | 包含行记录集合的订单数据;税率与金额字段由本示例约定 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 逐行累加得到的订单总额 | - -输入`订单`,按下方步骤使用这个值。 - -我们先**行列表 = [订单行列表](access(`订单`, "行"))**,供下一步使用。 -我们先**总额 = 0**,供下一步使用。 -- [逐个订单行](遍历 行列表 为 行) - 我们先**行含税价 = [计算并保存 行含税价](订单定价.含税价(行=`行`))**,供下一步使用。 - 我们先**总额 = [累加]((`总额` + `行含税价`))**,供下一步使用。 -完成上述步骤后,返回*总额*。 diff --git a/examples/executable-knowledge/corpus/tax-policy-2026.md b/examples/executable-knowledge/corpus/tax-policy-2026.md deleted file mode 100755 index dceea99..0000000 --- a/examples/executable-knowledge/corpus/tax-policy-2026.md +++ /dev/null @@ -1,5 +0,0 @@ -# 2026 年标准增值税率 - -本示例的原始证据:标准税率为 13%。 - -此文件只作来源定位,不执行。 diff --git a/examples/executable-knowledge/docs/invoice-answer.mq.md b/examples/executable-knowledge/docs/invoice-answer.mq.md deleted file mode 100755 index b78965d..0000000 --- a/examples/executable-knowledge/docs/invoice-answer.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -id: document.invoice-answer -type: Answer -import: - pricing: ../capabilities/order-pricing.mq.md - json: lib/json.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -发票回答:演示订单一行图书,未税金额 100。 - -We first **订单 = [Compute 订单](json.parse(text="{\"行\":[{\"金额\":100,\"品类\":\"书\"}]}"))** for the next step. -We first **总额 = [Compute 总额](pricing.订单定价.含税总额(订单=`订单`))** for the next step. - -这张订单的含税总额是[含税总价](总额)。 - -We now **[Display this step's result](> print text=`总额`)**. diff --git a/examples/executable-knowledge/knowledge/negative-refund.mq.md b/examples/executable-knowledge/knowledge/negative-refund.mq.md deleted file mode 100755 index 529b024..0000000 --- a/examples/executable-knowledge/knowledge/negative-refund.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -id: knowledge.negative.discount-not-for-refund -type: Failure -title: 折扣不适用于退款 ---- - -# 折扣不适用于退款 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Object/type namespace for the child functions below; call the intended child directly | - -负知识:退款结算不得套用会员折扣。Agent 复用折扣能力时应拒绝该适用面。 - -## 说明 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -After these steps, return *[不适用](`false`)*. diff --git a/examples/executable-knowledge/knowledge/tax-2026.mq.md b/examples/executable-knowledge/knowledge/tax-2026.mq.md deleted file mode 100755 index 8bafa8d..0000000 --- a/examples/executable-knowledge/knowledge/tax-2026.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -id: knowledge.tax.standard-2026 -type: Fact -sources: - - ../corpus/tax-policy-2026.md#2026 年标准增值税率 -applicability: - region: CN - valid_until: 2099-12-31 ---- - -# 标准税率 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Object/type namespace for the child functions below; call the intended child directly | - -当前政策下的标准增值税率。`品类` 预留给差异化税率;本演示固定返回标准税率。 - -## 查询 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -`品类` - -After these steps, return *[标准税率](0.13)*. diff --git a/examples/executable-knowledge/schema/order.mq.md b/examples/executable-knowledge/schema/order.mq.md deleted file mode 100755 index 5c1b97f..0000000 --- a/examples/executable-knowledge/schema/order.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -id: schema.order -type: Schema ---- - -# 订单 - -| 字段 | 类型 | 说明 | -|---|---|---| -| 行 | list | 待计价的订单行;每一项遵守下方独立对象的字段契约 | - -订单只收拢本次计算需要的行记录,不替调用方补缺失金额或品类。 -每一行使用同一金额单位,税率知识由能力模块选择;此处只描述数据形态。 - -# 订单行 - -| 字段 | 类型 | 说明 | -|---|---|---| -| 金额 | number | 未税金额 | -| 品类 | text | 用于选择税率 | - -订单行是独立的顶层对象类型,因此订单中的列表元素可以引用它。 -字段表紧接对象标题,避免将类型声明误写成具有参数和返回值的普通函数。 - -行字段的运行时契约约束列表本身;元素形态按订单行的字段说明提供, -不把尚未支持的泛型类型拼写当成已经执行的逐元素校验。 diff --git a/examples/foreign-native-report/index.mq.md b/examples/foreign-native-report/index.mq.md deleted file mode 100755 index 1a5fbdb..0000000 --- a/examples/foreign-native-report/index.mq.md +++ /dev/null @@ -1,151 +0,0 @@ ---- -markup: occlusion -title: Native report tools and a persistent Intl formatter -import: - foreign: lib/foreign.mq.md - table: lib/table.mq.md - stats: lib/stats.mq.md - math: lib/math.mq.md - result: lib/result.mq.md ---- - -This module keeps order analysis in native Marqdo and uses Node Intl only for -locale-aware currency formatting. Import it from a report page or call its -two public functions separately. There is no executable main in this module; -the English and Chinese public feature pages compose the full callable view. - -From the repository root, call analyze_orders with an orders row list and ---effects none. It returns ordinary report data. Pass that report to -format_summary with --effects process.exec for the bounded persistent formatter. -A missing Node executable is an explicit failed Result; native analysis remains -available without it. No Python interpreter is required. - -## analyze_orders - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| orders | list | required | Order rows with a region and numeric amount; no file or network IO | -| region_key | text | "region" | Field whose value identifies a group | -| amount_key | text | "amount" | Numeric amount field in every row | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Native report with regions, total, count and average | - -Use `orders`, `region_key`="region" and `amount_key`="amount" for the -whole analysis. Grouping, ordering, arithmetic, means and population deviation -all use Marqdo and its standard libraries. Each region retains orders, total, -mean and z_span, so moving the boundary does not remove the analysis. The data -is a row list, not a JSON program or an opaque host dataframe. - -The report has one row per region in sorted key order. Population variance is -the mean squared deviation; a singleton or equal-valued group has zero spread, -for which the normalization denominator is one and z_span is zero. The maximum -normalized deviation is the same statistic the previous kernel example displayed. -Values are ordinary runtime numbers, not a financial decimal model; the formatter -later chooses presentation precision without changing this report. - -Empty input returns no regions and zero totals/average. Missing fields and invalid -amounts preserve native diagnostics; do not replace them with invented zeroes. -The function is pure and needs no interpreter, plugin, process, file or network -grant. Its actual return can be checked with marqdo call before preparing a view. -The native report is also the only analysis value copied into external kernels: -there is no second implementation of grouping or statistics in another language. - -We **groups = [Group native rows and order their original keys](table.sort_by(list=table.group_by(list=`orders`, key=`region_key`), key="key"))** and **regions = [Start native summary rows](table.empty_list())**. -- [Summarize each region through native values](for groups as group) - We **rows = [Read this group's original rows](access(group, "rows"))** and **region = [Retain its region key](access(group, "key"))** and **values = [Read numeric amounts](table.pluck(list=`rows`, key=`amount_key`))**. - We **mean = [Compute the native arithmetic mean](stats.mean(list=`values`))** and **squared = 0.0**. - - [Accumulate population squared deviation](for values as value) - We **squared = squared + (value - mean) * (value - mean)**. - We **sigma = [Compute population spread](math.sqrt(value=`squared` / len(values)))**. - 1. `sigma` <= 0 - We **sigma = 1** so equal-valued groups keep a zero normalized span. - We **count = [Count this region's values](len(values))** and **total = [Sum the region in Marqdo](table.aggregate(list=`values`))** and **maximum = [Read its largest amount](table.aggregate(list=`values`, op="max"))** and **z_span = (maximum - mean) / sigma**. - - `row` = - - | region | orders | total | mean | z_span | - |---|---|---|---|---| - | `region` | `count` | `total` | `mean` | `z_span` | - - We **regions = [Retain this native summary row](table.append(list=`regions`, item=`row`))**. -We **count = [Count all input orders](len(orders))** and **total = [Sum all native amounts](table.aggregate(list=`orders`, key=`amount_key`))** and **average = 0**. -1. `count` > 0 - We **average = [Use the native mean without integer division](stats.mean(list=table.pluck(list=`orders`, key=`amount_key`)))** for a nonempty report. - -`report` = - -| regions | total | count | average | -|---|---|---|---| -| `regions` | `total` | `count` | `average` | - -After the native analysis we return *report*. - -## format_summary - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| report | map | required | Native analyze_orders result with total and average | -| locale | text | "en-US" | Locale understood by Node Intl; currency is CNY | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing localized total and average strings | - -Use `report` and `locale`="en-US" only for the presentation gap: -locale-aware currency formatting is provided here by Node's built-in Intl. -The source makes that external boundary explicit. It does not read or write files, -recalculate the native report, import a package or use Python. Node must already -be installed; probe it before creating a kernel and return a real failure if -it is unavailable. - -One persistent kernel receives JSON copies of the report and locale. The first -evaluation creates a formatter and formats the total; the second reuses that -same formatter for the already-computed native average. A fresh process without -its previous state could not run the second expression successfully. The helper -checks each evaluation's ok field and closes a live kernel before returning, -including handled evaluation errors. A dead kernel has already been retired and -must not be closed a second time. - -This function needs process.exec. Native policy or serialization diagnostics -remain diagnostics, not synthetic currency strings. Kernel values cannot become -guessed handles, and an opaque handle never crosses a CLI JSON boundary. Only -the two actual formatted strings leave this task in its successful Result. - -We **probe = [Check the explicit external interpreter](foreign.probe(lang="node"))**. -1. not access(`probe`, "ok") - Return *[Keep the missing interpreter visible](result.error(code="example.node", message=str(`probe`), operation="format_summary"))*. -We **kernel = [Open one persistent formatter kernel](foreign.session_open(lang="node"))** and **copied = [Copy the native report as ordinary data](foreign.session_set(id=`kernel`, name="report", value=`report`))** and **selected = [Copy the requested display locale](foreign.session_set(id=`kernel`, name="locale", value=`locale`))**. - -`formatter_code` = -```node -var money = new Intl.NumberFormat(locale, {style: "currency", currency: "CNY"}); -money.format(report.total) -``` - -We **first = [Create the formatter and format the native total](foreign.session_eval(id=`kernel`, code=`formatter_code`))**. -1. not access(`first`, "ok") - 1. access(`first`, "alive") - We **closed = [Close a still-live failed formatter](foreign.session_close(id=`kernel`))**. - Return *[Keep the actual formatter failure](result.error(code="example.format", message=str(`first`), operation="format_summary"))*. - -`average_code` = -```node -money.format(report.average) -``` - -We **second = [Reuse the formatter's persistent state](foreign.session_eval(id=`kernel`, code=`average_code`))**. -1. not access(`second`, "ok") - 1. access(`second`, "alive") - We **closed = [Close a live kernel after the second failure](foreign.session_close(id=`kernel`))**. - Return *[Keep the actual reuse failure](result.error(code="example.format", message=str(`second`), operation="format_summary"))*. -We **total = [Read the actual formatted total](access(first, "result"))** and **average = [Read the actual formatted average](access(second, "result"))** and **closed = [Close the consumed formatter kernel](foreign.session_close(id=`kernel`))**. - -`formatted` = - -| total | average | -|---|---| -| `total` | `average` | - -Return *[The real locale-aware strings](result.ok(value=`formatted`))*. diff --git a/examples/knowledge-layers/README.md b/examples/knowledge-layers/README.md deleted file mode 100755 index 65781bb..0000000 --- a/examples/knowledge-layers/README.md +++ /dev/null @@ -1,91 +0,0 @@ -# 知识分层示例:本体 → 知识个体 → 调用面 - -这个目录演示 [知识分层设计](../../doc/design/knowledge-layers.md): - -| 层 | 文件 | 内容 | -|----|------|------| -| **L0 原始语料** | `corpus/libai.md` | 李白原文;不执行,只作出处 | -| **L1 本体 / 模式** | `poet.mq.md` | `# 诗人` + 字段/类型表 | -| **L2 可执行知识** | `libai.mq.md` | `# 李白 = > 诗人` + `##` 事实 + 来源 | -| **L3 调用面** | `main.mq.md` / `main.compat.mq.md` | `[]()` 类调用 | - -> **关键术语**:`# 李白 = > 诗人` 是**知识个体/单体知识类**(语法上是继承/特化), -> 不是运行时实例;`> 李白` 才是运行时 map 实例。 - -## 今天可跑(v2.0.0 兼容) - -```bash -marqdo run examples/knowledge-layers/main.compat.mq.md -# 701 -``` - -`main.compat.mq.md` 用当前能力完成同一件事: - -```markdown ---- -import libai:libai.mq.md ---- - -# main - -**li = > libai.李白** -**year = > `li`.出生年份** -> print text=`year` -``` - -- `import` 绑定知识文档; -- `> libai.李白` 构造实例; -- `` `li`.出生年份 `` 调用实例方法; -- 当前 `libai.mq.md` 还保留 `import poet:poet.mq.md`,因为 v2.0.0 的跨文档继承需要 import; - v2.1 的项目类索引会去掉这个 import。 - -## 目标(v2.1) - -`main.mq.md`: - -```markdown -# main - -诗人李白的出生年份是[出生年份](李白.出生年份)。 -``` - -- `李白` 是项目类索引里的知识个体; -- `出生年份` 是它的类函数; -- 正文链接由 `view`/`check` 解析;`run` 不执行; -- 要终端输出,把同一段代码放进代码链接并加 `print`。 - -期望: - -```bash -$ marqdo run examples/knowledge-layers/main.mq.md -# 无输出(正文链接不执行) - -$ marqdo check examples/knowledge-layers/main.mq.md --json -{"code":"link.ok", ...} -``` - -`view` 期望显示: - -```text -诗人李白的出生年份是 701。 - ↑ - 悬浮:出生年份 → 李白.出生年份 - class 李白 · () -> number · value 701 - 来源:corpus/libai.md#出生年份 -``` - -## 为什么 `# 李白 = > 诗人` 不是「实例化」 - -- `# 诗人` 是类/本体; -- `# 李白 = > 诗人` 是**继承/特化**,表达「李白是诗人」; -- 但它带有一个命名个体的全部事实,所以是**单体知识类**; -- `李白.出生年份` 是类调用,不需要 `> 李白` 构造实例; -- 如果要运行时实例,仍可 `**li = > 李白**`,它是 map + `_type`,和知识个体分离。 - -详见 [doc/design/knowledge-layers.md](../../doc/design/knowledge-layers.md)。 - -## 相关 - -- 链接语法:[doc/design/link-syntax.md](../../doc/design/link-syntax.md) -- 证据复核:[doc/research/occlusion-vs-executable-knowledge-2026-10.md](../../doc/research/occlusion-vs-executable-knowledge-2026-10.md) -- 旧遮蔽设计:[doc/design/occlusion-syntax.md](../../doc/design/occlusion-syntax.md) diff --git a/examples/knowledge-layers/corpus/libai.md b/examples/knowledge-layers/corpus/libai.md deleted file mode 100755 index 6cdff1b..0000000 --- a/examples/knowledge-layers/corpus/libai.md +++ /dev/null @@ -1,5 +0,0 @@ -# 李白 - -李白,字太白,唐代诗人,生于公元 701 年。 - -这段是**原始语料**:它不执行,只作为知识出处。 diff --git a/examples/knowledge-layers/libai.mq.md b/examples/knowledge-layers/libai.mq.md deleted file mode 100755 index 5654ec4..0000000 --- a/examples/knowledge-layers/libai.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -type: Fact -id: libai -title: 李白 -import: - poet: poet.mq.md ---- - -# 李白 = > 诗人 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | - -## 姓名 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -完成上述步骤后,返回*"李白"*。 - -## 出生年份 - -| 返回 | 类型 | 说明 | -|------|------|------| -| 701 | number | 公元 701 年;来源:corpus/libai.md#出生年份 | - -完成上述步骤后,返回*701*。 diff --git a/examples/knowledge-layers/main.compat.mq.md b/examples/knowledge-layers/main.compat.mq.md deleted file mode 100755 index 2cea87c..0000000 --- a/examples/knowledge-layers/main.compat.mq.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -markup: occlusion -import: - libai: libai.mq.md ---- - -# main - -**li = > libai.李白** -**year = > `li`.出生年份** -> print text=`year` diff --git a/examples/knowledge-layers/main.mq.md b/examples/knowledge-layers/main.mq.md deleted file mode 100755 index 8f22ec6..0000000 --- a/examples/knowledge-layers/main.mq.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -markup: occlusion ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -诗人李白的出生年份是[出生年份](李白.出生年份)。 diff --git a/examples/knowledge-layers/poet.mq.md b/examples/knowledge-layers/poet.mq.md deleted file mode 100755 index 42e6aaa..0000000 --- a/examples/knowledge-layers/poet.mq.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -markup: occlusion ---- - -# 诗人 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;本段完成下述操作,不额外返回业务数据。 | - -| 字段 | 类型 | 说明 | -|------|------|------| -| 姓名 | text | 诗人姓名 | -| 出生年份 | number | 公元年份 | diff --git a/examples/knowledge-proof/README.md b/examples/knowledge-proof/README.md deleted file mode 100644 index 8f750cf..0000000 --- a/examples/knowledge-proof/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Marqdo 知识锚点 + 自动证明示例 - -面向 CLI 2.8.0,原 Markdown 语法不变: - -```sh -marqdo knowledge examples/knowledge-proof/ -marqdo prove examples/knowledge-proof/main.mq.md --json -marqdo knowledge examples/knowledge-proof/ -``` - -知识编译后,查看 `.marqdo/anchors.json`、`.marqdo/claims.json`、`.marqdo/refs.json`、`.marqdo/graph/edges.json` 以及 `.marqdo/proof-index.json`(具体输出目录取决于 CLI --out)。 -证明调用另外生成其证明目录下的 `knowledge-links.json`。运行 CLI 时是否有 Lean 决定该定理能否获得真正的 `proved` 状态;没有 Lean 只能是 `checked` 或 `unverified`。在此案例中,`长度(轨迹)=0` 是函数级定理,并非内部的“计算结果”步骤已经独立证明正确。 - -`[计算知识节点](#@计算结果)` 是**同函数内的静态知识引用**。跨文件引用请从 `anchors.json` 拿完整 `mq://...#anchor-...` 地址,不要猜测哈希。两个同名标记不共享地址,会被标记为无公共锚点。 diff --git a/examples/knowledge-proof/main.mq.md b/examples/knowledge-proof/main.mq.md deleted file mode 100644 index bfedb03..0000000 --- a/examples/knowledge-proof/main.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: 可寻址、可验证的知识步骤 ---- - -# main - -## 计算 - -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 无外部操作 | 长度(轨迹) = 0 | | auto | - -这里的 [计算知识节点](#@计算结果) 和 [定理声明](#@无外部操作) 都是可解析的知识引用; -它不会再次执行运算,也不会自动继承函数的形式化证明。 - -**答案 = [计算结果](2 * 3)** - -*答案* diff --git a/examples/library_audit.rs b/examples/library_audit.rs deleted file mode 100755 index 68c8f48..0000000 --- a/examples/library_audit.rs +++ /dev/null @@ -1,803 +0,0 @@ -//! Audit library source with the real parser, and compare executable ASTs across prose refactors. -use anyhow::{Context, Result}; -use marqdo::{ast::*, diagnostics::Span}; -use serde_json::{json, Value}; -use std::{ - fs, - path::{Path, PathBuf}, -}; -fn files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> { - for entry in fs::read_dir(dir)? { - let p = entry?.path(); - if p.is_dir() { - files(&p, out)? - } else if p.to_string_lossy().ends_with(".mq.md") { - out.push(p) - } - } - Ok(()) -} -fn expr(e: Expr) -> Expr { - match e { - Expr::Occluded { payload, .. } => payload - .map(|p| expr(*p)) - .unwrap_or(Expr::Literal(Literal::None)), - Expr::Unary { op, expr: e } => Expr::Unary { - op, - expr: Box::new(expr(*e)), - }, - Expr::Binary { op, left, right } => Expr::Binary { - op, - left: Box::new(expr(*left)), - right: Box::new(expr(*right)), - }, - Expr::Call(c) => { - let c = call(c); - pure_literal_call(&c).unwrap_or(Expr::Call(c)) - } - Expr::List(xs) => Expr::List(xs.into_iter().map(expr).collect()), - Expr::Map(xs) => Expr::Map(xs.into_iter().map(|(k, v)| (k, expr(v))).collect()), - Expr::Index { base, label } => Expr::Index { - base: Box::new(expr(*base)), - label, - }, - other => other, - } -} -fn call(mut c: CallExpr) -> CallExpr { - for a in &mut c.args { - match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => *e = expr(e.clone()), - } - } - c -} -// Only the explicitly supported pure literal-building cases are folded. This is -// a refactor audit, not an evaluator: unknown calls and nonconstant data remain. -fn literal_json_value(v: serde_json::Value) -> Option<Expr> { - use serde_json::Value as J; - Some(Expr::Literal(match v { - J::Null => Literal::None, - J::Bool(b) => Literal::Bool(b), - J::String(s) => Literal::Text(s), - J::Number(n) => { - if let Some(i) = n.as_i64() { - if i.unsigned_abs() > 9_007_199_254_740_991 { - return None; - } - Literal::Int(i) - } else { - let n = n.as_f64()?; - if !n.is_finite() || (n.fract() == 0.0 && n.abs() > 9_007_199_254_740_991.0) { - return None; - } - Literal::Num(n) - } - } - _ => return None, - })) -} -// Read JSON literals without accepting duplicate keys or unsafe numeric coercions. -fn flat_json_record(text: &str) -> Option<Expr> { - struct Constant; - impl<'de> serde::Deserialize<'de> for ConstantExpr { - fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> { - de.deserialize_any(Constant).map(ConstantExpr) - } - } - struct ConstantExpr(Expr); - impl<'de> serde::de::Visitor<'de> for Constant { - type Value = Expr; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("constant JSON in the exact audit numeric domain") - } - fn visit_unit<E: serde::de::Error>(self) -> Result<Expr, E> { - Ok(Expr::Literal(Literal::None)) - } - fn visit_bool<E: serde::de::Error>(self, b: bool) -> Result<Expr, E> { - Ok(Expr::Literal(Literal::Bool(b))) - } - fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Expr, E> { - Ok(Expr::Literal(Literal::Text(s.into()))) - } - fn visit_i64<E: serde::de::Error>(self, n: i64) -> Result<Expr, E> { - literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe integer")) - } - fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Expr, E> { - literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe integer")) - } - fn visit_f64<E: serde::de::Error>(self, n: f64) -> Result<Expr, E> { - let n = serde_json::Number::from_f64(n).ok_or_else(|| E::custom("nonfinite number"))?; - literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe number")) - } - fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Expr, A::Error> { - let mut values = Vec::new(); - while let Some(ConstantExpr(v)) = seq.next_element()? { - values.push(v); - } - Ok(Expr::List(values)) - } - fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Expr, A::Error> { - use serde::de::Error; - let mut fields = std::collections::BTreeMap::new(); - while let Some((key, ConstantExpr(value))) = map.next_entry::<String, ConstantExpr>()? { - if fields.insert(key, value).is_some() { - return Err(A::Error::custom("duplicate key")); - } - } - Ok(Expr::Map(fields.into_iter().collect())) - } - } - let ConstantExpr(value) = serde_json::from_str::<ConstantExpr>(text).ok()?; - Some(value) -} -fn pure_literal_call(c: &CallExpr) -> Option<Expr> { - let name = c - .path - .as_ref() - .map(|p| p.join(".")) - .unwrap_or_else(|| c.callee.clone()); - let get = |key: &str| { - c.args.iter().find_map(|a| match a { - Arg::Named { name, value } if name == key => Some(value), - _ => None, - }) - }; - match name.as_str() { - "json.parse" => { - if let Expr::Literal(Literal::Text(text)) = get("text")? { - flat_json_record(text) - } else { - None - } - } - "table.put" if matches!(get("in")?, Expr::Literal(Literal::None)) => { - if let Expr::Literal(Literal::Text(key)) = get("at")? { - let value = get("value")?; - if matches!(value, Expr::Literal(_)) { - Some(Expr::Map(vec![(key.clone(), value.clone())])) - } else { - None - } - } else { - None - } - } - "table.empty_list" => Some(Expr::List(Vec::new())), - "table.from_pairs" => { - let Expr::List(rows) = get("pairs")? else { - return None; - }; - let mut fields = Vec::new(); - let mut seen = std::collections::BTreeSet::new(); - for row in rows { - let Expr::Map(pairs) = row else { - return None; - }; - let Some((_, Expr::Literal(Literal::Text(key)))) = - pairs.iter().find(|(k, _)| k == "key") - else { - return None; - }; - let Some((_, value)) = pairs.iter().find(|(k, _)| k == "value") else { - return None; - }; - if !constant(value) || !seen.insert(key.clone()) { - return None; - } - fields.push((key.clone(), value.clone())); - } - Some(Expr::Map(fields)) - } - "text.str_join" => { - let Expr::List(rows) = get("xs")? else { - return None; - }; - let Expr::Literal(Literal::Text(separator)) = get("sep")? else { - return None; - }; - let rows = rows - .iter() - .map(|e| { - if let Expr::Literal(Literal::Text(s)) = e { - Some(s.as_str()) - } else { - None - } - }) - .collect::<Option<Vec<_>>>()?; - Some(Expr::Literal(Literal::Text(rows.join(separator)))) - } - _ => None, - } -} -fn constant(e: &Expr) -> bool { - match e { - Expr::Literal(_) => true, - Expr::List(xs) => xs.iter().all(constant), - Expr::Map(xs) => xs.iter().all(|(_, v)| constant(v)), - _ => false, - } -} -fn substitute(e: Expr, temps: &std::collections::BTreeMap<String, Expr>) -> Expr { - let e = match e { - Expr::Var(name) if temps.contains_key(&name) => temps[&name].clone(), - Expr::Call(mut c) => { - for a in &mut c.args { - match a { - Arg::Named { value, .. } | Arg::Positional(value) => { - *value = substitute(value.clone(), temps) - } - } - } - Expr::Call(c) - } - Expr::Map(xs) => Expr::Map( - xs.into_iter() - .map(|(k, v)| (k, substitute(v, temps))) - .collect(), - ), - Expr::List(xs) => Expr::List(xs.into_iter().map(|v| substitute(v, temps)).collect()), - Expr::Occluded { - payload: Some(v), .. - } => substitute(*v, temps), - Expr::Unary { op, expr: v } => Expr::Unary { - op, - expr: Box::new(substitute(*v, temps)), - }, - Expr::Binary { op, left, right } => Expr::Binary { - op, - left: Box::new(substitute(*left, temps)), - right: Box::new(substitute(*right, temps)), - }, - other => other, - }; - expr(e) -} -fn canonical_statements(statements: Vec<Stmt>) -> Vec<Stmt> { - fn block( - statements: Vec<Stmt>, - mut temps: std::collections::BTreeMap<String, Expr>, - ) -> Vec<Stmt> { - let mut out = Vec::new(); - for s in statements { - let s = statement(s); - let s = match s { - Stmt::Assign { - name, - value, - span, - end_line, - } => { - let value = substitute(value, &temps); - if name.starts_with("_literal_") && constant(&value) { - temps.insert(name, value); - continue; - } - Stmt::Assign { - name, - value, - span, - end_line, - } - } - Stmt::Return { value, span } => Stmt::Return { - value: substitute(value, &temps), - span, - }, - Stmt::Expr { value, span } => Stmt::Expr { - value: substitute(value, &temps), - span, - }, - Stmt::Branch { arms, span } => Stmt::Branch { - arms: arms - .into_iter() - .map(|a| BranchArm { - condition: a.condition.map(|e| substitute(e, &temps)), - body: block(a.body, temps.clone()), - }) - .collect(), - span, - }, - Stmt::ForEach { - item, - collection, - label, - body, - span, - } => Stmt::ForEach { - item, - collection, - label, - body: block(body, temps.clone()), - span, - }, - Stmt::While { - condition, - body, - span, - } => Stmt::While { - condition: substitute(condition, &temps), - body: block(body, temps.clone()), - span, - }, - other => other, - }; - out.push(s); - } - out - } - block(statements, std::collections::BTreeMap::new()) -} - -fn statement(s: Stmt) -> Stmt { - let span = Span::new(0, 0); - match s { - Stmt::Assign { name, value, .. } => Stmt::Assign { - name, - value: expr(value), - span, - end_line: 0, - }, - Stmt::Return { value, .. } => Stmt::Return { - value: expr(value), - span, - }, - Stmt::Call { call: c, .. } => Stmt::Expr { - value: Expr::Call(call(c)), - span, - }, - Stmt::Expr { value, .. } => Stmt::Expr { - value: expr(value), - span, - }, - Stmt::Branch { arms, .. } => Stmt::Branch { - arms: arms - .into_iter() - .map(|a| BranchArm { - condition: a.condition.map(expr), - body: a.body.into_iter().map(statement).collect(), - }) - .collect(), - span, - }, - Stmt::While { - condition, body, .. - } => Stmt::While { - condition: expr(condition), - body: body.into_iter().map(statement).collect(), - span, - }, - Stmt::ForEach { - item, - collection, - body, - .. - } => Stmt::ForEach { - item, - collection, - body: body.into_iter().map(statement).collect(), - span, - label: None, - }, - } -} -fn quote(s: &str) -> String { - serde_json::to_string(s).unwrap().replace('`', "\\`") -} -fn render(e: &Expr) -> Result<String> { - Ok(match e { - Expr::Literal(l) => match l { - Literal::None => "None".into(), - Literal::Bool(b) => if *b { "True" } else { "False" }.into(), - Literal::Int(n) => n.to_string(), - Literal::Num(n) => { - let text = n.to_string(); - if text.contains('.') || text.contains(['e', 'E']) { - text - } else { - format!("{text}.0") - } - } - Literal::Text(s) => quote(s), - }, - Expr::Var(n) => format!("`{n}`"), - Expr::Interp(parts) => { - let mut s = String::new(); - for p in parts { - match p { - InterpPart::Lit(t) => s.push_str(&t.replace('`', "\\`")), - InterpPart::Var(v) => s.push_str(&format!("`{v}`")), - InterpPart::Index { .. } => { - anyhow::bail!("legacy interpolated index needs review") - } - } - } - serde_json::to_string(&s)?.replace("\\\\`", "\\`") - } - Expr::Call(c) => render_call(c)?, - Expr::Unary { op, expr: e } => format!( - "({}{})", - match op { - UnaryOp::Not => "not ", - UnaryOp::Neg => "-", - }, - render(e)? - ), - Expr::Binary { op, left, right } => format!( - "({} {} {})", - render(left)?, - match op { - BinaryOp::Add => "+", - BinaryOp::Sub => "-", - BinaryOp::Mul => "*", - BinaryOp::Div => "/", - BinaryOp::Eq => "==", - BinaryOp::Ne => "!=", - BinaryOp::Lt => "<", - BinaryOp::Le => "<=", - BinaryOp::Gt => ">", - BinaryOp::Ge => ">=", - BinaryOp::And => "and", - BinaryOp::Or => "or", - }, - render(right)? - ), - Expr::List(xs) => format!( - "[{}]", - xs.iter() - .map(render) - .collect::<Result<Vec<_>>>()? - .join(", ") - ), - Expr::Map(xs) => format!( - "{{{}}}", - xs.iter() - .map(|(k, v)| Ok(format!("{}: {}", quote(k), render(v)?))) - .collect::<Result<Vec<_>>>()? - .join(", ") - ), - Expr::Occluded { - label, - payload: Some(p), - } => format!("[{}]({})", label.replace(']', "\\]"), render(p)?), - Expr::Occluded { payload: None, .. } => "None".into(), - _ => anyhow::bail!("expression needs manual rendering: {e:?}"), - }) -} -fn render_call(c: &CallExpr) -> Result<String> { - let target = if let Some(r) = &c.receiver { - format!("`{r}`.{}", c.callee) - } else if let Some(p) = &c.path { - p.join(".") - } else { - c.callee.clone() - }; - let c = c.with_modifiers_expanded().map_err(anyhow::Error::msg)?; - let args = c - .args - .iter() - .map(|a| { - Ok(match a { - Arg::Positional(e) => render(e)?, - Arg::Named { name, value } => format!("{name}={}", render(value)?), - }) - }) - .collect::<Result<Vec<_>>>()?; - if c.receiver.is_some() { - Ok(format!("> {target} {} ", args.join(" "))) - } else { - Ok(format!("{target}({})", args.join(", "))) - } -} -fn receiver_call(c: &CallExpr, f: &Function, imports: &[String]) -> CallExpr { - let mut c = c.clone(); - if let Some(path) = &c.path { - if path.len() == 2 - && f.params.iter().any(|p| p.name == path[0]) - && !imports.contains(&path[0]) - { - c.receiver = Some(path[0].clone()); - c.path = None; - } - } - c -} -fn render_value(v: &Expr, f: &Function, imports: &[String]) -> Result<String> { - match v { - Expr::Call(c) => render_call(&receiver_call(c, f, imports)), - Expr::Occluded { - label, - payload: Some(v), - } => Ok(format!( - "[{}]({})", - label.replace(']', "\\]"), - render_value(v, f, imports)? - )), - other => render(other), - } -} -// A qualified call through a parameter and its explicit receiver form resolve -// the same object when that name is not an imported module binding. -fn normalize_receiver_text(mut body: String, params: &Value, imports: &[String]) -> String { - for p in params.as_array().unwrap() { - let name = p["name"].as_str().unwrap(); - if imports.iter().any(|i| i == name) { - continue; - } - let quoted = serde_json::to_string(name).unwrap(); - let pattern = format!( - r#"path: Some\(\[{}, "[^"\n]+"\]\), receiver: None"#, - regex::escape("ed) - ); - let re = regex::Regex::new(&pattern).unwrap(); - body = re - .replace_all(&body, format!("path: None, receiver: Some({quoted})")) - .into_owned(); - } - body -} -fn collect(fs: &[Function], prefix: &str, source: &str, imports: &[String], out: &mut Vec<Value>) { - for f in fs { - let name = if prefix.is_empty() { - f.name.clone() - } else { - format!("{prefix}.{}", f.name) - }; - let mut calls = Vec::new(); - marqdo::ast::walk_stmts(f, &mut |s| { - if let Stmt::Call { call, span } = s { - calls.push(json!({"line":span.line,"rendered":render_call(&receiver_call(call, f, imports)).ok(),"call":format!("{call:?}")})) - } - }); - let mut statements = Vec::new(); - marqdo::ast::walk_stmts(f, &mut |s| { - let (kind, name, value, line, end) = match s { - Stmt::Assign { - name, - value, - span, - end_line, - } => ( - "assign", - Some(name.as_str()), - Some(value), - span.line, - *end_line, - ), - Stmt::Return { value, span } => ("return", None, Some(value), span.line, span.line), - Stmt::Expr { value, span } => ("expr", None, Some(value), span.line, span.line), - Stmt::Call { call, span } => { - statements.push(json!({"kind":"call", "line":span.line, "rendered":render_call(&receiver_call(call, f, imports)).ok(), "callee":call.callee, "path":call.path, "receiver":call.receiver})); - return; - } - _ => return, - }; - let mut inner = value; - while let Some(Expr::Occluded { - payload: Some(p), .. - }) = inner - { - inner = Some(p); - } - let target = match inner { - Some(Expr::Call(c)) => { - Some(json!({"callee":c.callee,"path":c.path,"receiver":c.receiver})) - } - _ => None, - }; - statements.push(json!({"kind":kind,"name":name,"line":line,"end":end,"rendered":value.and_then(|v|render_value(v, f, imports).ok()),"target":target,"value":value.map(|v|format!("{v:?}"))})); - }); - out.push(json!({"name":name,"short_name":f.name,"line":f.span.line,"level":f.level,"base":f.base,"receiver":function_uses_receiver(f),"params":f.params.iter().map(|p|json!({"name":p.name,"line":p.span.line,"default":p.default.as_ref().map(|e|format!("{:?}",expr(e.clone()))),"default_source":p.default.as_ref().and_then(|e|render(e).ok()),"type":f.contract.as_ref().and_then(|c|c.params.iter().find(|x|x.name==p.name)).map(|p|p.ty.name()).unwrap_or("any".into())})).collect::<Vec<_>>(),"returns":f.contract.as_ref().and_then(|c|c.returns.as_ref()).map(|r|r.ty.name()).unwrap_or("any".into()),"contract":f.contract.as_ref().map(|c|format!("{c:?}")),"body":format!("{:?}",canonical_statements(f.body.clone())),"calls":calls,"statements":statements,"narrative":marqdo::narrative_ratio::measure_source_units(source,std::slice::from_ref(f)).first().map(|r|r.ratio)})); - collect(&f.children, &name, source, imports, out); - } -} -fn difference(description: String, before: Value, after: Value) -> Value { - use sha2::Digest; - let digest = |value: Value| { - format!( - "{:x}", - sha2::Sha256::digest(serde_json::to_vec(&value).unwrap()) - ) - }; - json!({"difference":description,"before":digest(before),"after":digest(after)}) -} -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().collect(); - let baseline = args - .iter() - .position(|x| x == "--compare") - .map(|i| fs::read_to_string(&args[i + 1])) - .transpose()? - .map(|s| serde_json::from_str::<Value>(&s)) - .transpose()?; - let original = args - .iter() - .position(|x| x == "--from") - .map(|i| fs::read_to_string(&args[i + 1])) - .transpose()? - .map(|s| serde_json::from_str::<Value>(&s)) - .transpose()?; - let mut paths = Vec::new(); - files(Path::new("lib"), &mut paths)?; - files(Path::new("ext"), &mut paths)?; - paths.sort(); - if let Some(input) = &original { - paths.retain(|p| input.get(p.to_str().unwrap()).is_some()); - } - let mut result = serde_json::Map::new(); - let mut differences = Vec::new(); - for path in paths { - let key = path.to_str().context("UTF-8 library path")?; - let source = if let Some(s) = original - .as_ref() - .and_then(|m| m.get(key)) - .and_then(|m| m["source"].as_str()) - { - s.to_owned() - } else { - fs::read_to_string(&path)? - }; - let module = marqdo::parse::parse_source(&source).with_context(|| key.to_owned())?; - let mut functions = Vec::new(); - let imports: Vec<_> = module - .imports - .iter() - .map(|i| i.bind.clone()) - .chain(module.uses.iter().map(|i| i.bind.clone())) - .collect(); - collect(&module.functions, "", &source, &imports, &mut functions); - let reports = marqdo::narrative_ratio::measure_source_units(&source, &module.functions); - for f in &mut functions { - let report = reports.iter().find(|r| json!(r.line) == f["line"]).unwrap(); - f["narrative_chars"] = json!(report.narrative); - f["code_chars"] = json!(report.total - report.narrative); - f["narrative"] = json!( - reports - .iter() - .find(|r| json!(r.line) == f["line"]) - .unwrap() - .ratio - ); - } - if let Some(old) = baseline.as_ref().and_then(|b| b.get(key)) { - for o in old["functions"].as_array().unwrap() { - match functions.iter().find(|f| f["name"] == o["name"]) { - None => differences.push(difference( - format!("removed {key} {}", o["name"]), - json!({"level":o["level"],"base":o["base"],"receiver":o["receiver"],"params":o["params"].as_array().unwrap().iter().map(|p|json!([p["name"],p["default"]])).collect::<Vec<_>>(),"body":o["body"]}), - Value::Null, - )), - Some(n) => { - for field in ["level", "base", "receiver", "body"] { - let same = if field == "body" { - normalize_receiver_text( - n[field].as_str().unwrap().to_owned(), - &o["params"], - &imports, - ) == normalize_receiver_text( - o[field].as_str().unwrap().to_owned(), - &o["params"], - &imports, - ) - } else { - n[field] == o[field] - }; - if !same { - differences.push(difference(format!("{key} {} changed {field}", o["name"]), o[field].clone(), n[field].clone())); - } - } - let sig = |f: &Value| { - f["params"] - .as_array() - .unwrap() - .iter() - .map(|p| json!([p["name"], p["default"]])) - .collect::<Vec<_>>() - }; - if sig(n) != sig(o) { - differences.push(difference(format!("{key} {} changed parameters", o["name"]),json!(sig(o)),json!(sig(n)))); - } - } - } - } - } - result.insert( - key.to_owned(), - json!({"source": source, "functions": functions}), - ); - } - if let Some(i) = args.iter().position(|x| x == "--snapshot") { - fs::write(&args[i + 1], serde_json::to_vec_pretty(&result)?)?; - } - println!( - "{} library files, {} functions", - result.len(), - result - .values() - .map(|f| f["functions"].as_array().unwrap().len()) - .sum::<usize>() - ); - if let Some(i) = args.iter().position(|x| x == "--differences") { - fs::write(&args[i + 1], serde_json::to_vec_pretty(&differences)?)?; - } - if baseline.is_some() { - let reviewed = args - .iter() - .position(|x| x == "--reviewed-fixes") - .map(|i| fs::read_to_string(&args[i + 1])) - .transpose()? - .map(|text| serde_json::from_str::<Vec<Value>>(&text)) - .transpose()? - .unwrap_or_default(); - let matches = |d: &Value, r: &Value| { - ["difference", "before", "after"] - .iter() - .all(|k| d[*k] == r[*k]) - && r["reason"].as_str().is_some_and(|s| !s.trim().is_empty()) - }; - let unreviewed: Vec<_> = differences - .iter() - .filter(|d| !reviewed.iter().any(|r| matches(d, r))) - .collect(); - let stale: Vec<_> = reviewed - .iter() - .filter(|r| !differences.iter().any(|d| matches(d, r))) - .collect(); - println!("{} executable differences, {} exact reviewed fixes, {} unreviewed, {} stale review records", - differences.len(),differences.len()-unreviewed.len(),unreviewed.len(),stale.len()); - for d in &unreviewed { - println!("{}", d["difference"]); - } - if !unreviewed.is_empty() || !stale.is_empty() { - anyhow::bail!( - "review executable differences; only exact before/after digests are accepted" - ); - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn json_literal_audit_rejects_duplicates_unsafe_numbers_and_trailing_data() { - for text in [ - r#"{"x":1,"x":2}"#, - r#"{"nested":{"x":1,"x":2}}"#, - r#"{"x":9007199254740992}"#, - r#"{} false"#, - r#"{"x":NaN}"#, - ] { - assert!(flat_json_record(text).is_none(), "{text}"); - } - let value = flat_json_record(r#"{"z":[null,true,"a\nb"],"a":1}"#).unwrap(); - assert!(constant(&value)); - let Expr::Map(fields) = value else { - panic!("map expected"); - }; - assert_eq!(fields[0].0, "a"); - assert_eq!(fields[1].0, "z"); - } - #[test] - fn only_supported_constant_builders_are_folded() { - for code in [ - "unknown(text=\"{}\")", - "json.parse(text=`input`)", - "table.put(in=`input`, at=\"key\", value=1)", - "text.str_join(xs=`rows`, sep=\"\\n\")", - ] { - let Expr::Call(call) = marqdo::parse::expr::parse_expr(code).unwrap() else { - panic!("call expected"); - }; - assert!(pure_literal_call(&call).is_none(), "{code}"); - } - let Expr::Call(call) = - marqdo::parse::expr::parse_expr("json.parse(text=\"{\\\"key\\\":null}\")").unwrap() - else { - panic!("call expected"); - }; - assert!(pure_literal_call(&call).is_some()); - } -} diff --git a/examples/linalg-least-squares/README.md b/examples/linalg-least-squares/README.md deleted file mode 100755 index 4048f5c..0000000 --- a/examples/linalg-least-squares/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# linalg-least-squares - -Overdetermined least squares via `ext/linalg`: `factorize kind=qr`, `Qᵀb`, solve `R`, plus a heatmap SVG of `A`. - -```bash -cargo build --release -p marqdo_plugin_linalg -marqdo ext add linalg # once (re-run after rebuilding the plugin) -marqdo run examples/linalg-least-squares/index.mq.md -# optional: marqdo view examples/linalg-least-squares/ -``` - -Design: [ext-linalg.md](../../doc/design/ext-linalg.md) · sibling: [linalg-svd](../linalg-svd/). diff --git a/examples/linalg-least-squares/index.mq.md b/examples/linalg-least-squares/index.mq.md deleted file mode 100755 index a98697f..0000000 --- a/examples/linalg-least-squares/index.mq.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -markup: occlusion -title: Least squares via lstsq -description: Overdetermined Ax≈b with ext/linalg lstsq + heatmap. -import: - la: ext/linalg/linalg.mq.md - math: lib/math.mq.md ---- - -# Least squares from a runnable document - - -Fit a line through three points with an overdetermined `A x ≈ b` using `lstsq` (QR path). A heatmap makes the design matrix visible in `view`. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -`A` = -$$ -\begin{bmatrix}1&0\\1&1\\1&2\end{bmatrix} -$$ - -`b` = -$$ -\begin{pmatrix}1\\2\\2\end{pmatrix} -$$ - -We first **A = [Compute A](la.from_formula(formula=`A`))** for the next step. -We first **b = [Compute b](la.from_formula(formula=`b`))** for the next step. - -We first **_ = [Compute _](la.draw(factor=`A`, kind="heatmap", theme="light", path="ls-heatmap.svg"))** for the next step. - -We first **ls = [Compute ls](la.lstsq(a=`A`, b=`b`))** for the next step. -We first **x = [x](access(`ls`, "x"))** for the next step. -We first **resid = [residual_fro](access(`ls`, "residual_fro"))** for the next step. - -We now **[Display this step's result](> print text=`x`)**. -We now **[Display this step's result](> print text=`resid`)**. -We now **[Display this step's result](> print text="ls-ok")**. diff --git a/examples/linalg-svd/README.md b/examples/linalg-svd/README.md deleted file mode 100755 index 38a788e..0000000 --- a/examples/linalg-svd/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# linalg-svd - -Dense SVD via `ext/linalg`: singular values + structure / hinton SVG. - -```bash -cargo build --release -p marqdo_plugin_linalg -marqdo ext add linalg -marqdo run examples/linalg-svd/index.mq.md -# optional: marqdo view examples/linalg-svd/ -``` - -Design: [ext-linalg.md](../../doc/design/ext-linalg.md) · sibling: [linalg-least-squares](../linalg-least-squares/). diff --git a/examples/linalg-svd/index.mq.md b/examples/linalg-svd/index.mq.md deleted file mode 100755 index ee62db6..0000000 --- a/examples/linalg-svd/index.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: SVD structure demo -description: Diagonal SVD + structure SVG via ext/linalg. -import: - la: ext/linalg/linalg.mq.md ---- - -# SVD from a runnable document - - -A diagonal matrix has singular values on the diagonal. Prefer matrix values and methods; `factorize` / `draw` stay explicit for teaching SVGs. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -`M` = -$$ -\begin{bmatrix}4&0\\0&2\end{bmatrix} -$$ - -We first **M = [Compute M](la.from_formula(formula=`M`))** for the next step. -We first **f = [Compute f](la.factorize(matrix=`M`, kind="svd"))** for the next step. -We first **S = [S](access(`f`, "S"))** for the next step. -We first **_ = [Compute _](la.draw(factor=`f`, kind="svd", theme="light", path="svd-structure.svg"))** for the next step. -We first **hm = [Compute hm](la.draw(factor=`M`, kind="hinton", path="svd-hinton.svg"))** for the next step. - -We now **[Display this step's result](> print text=`S`)**. -We now **[Display this step's result](> print text="svd-ok")**. diff --git a/examples/linalg-transpose/README.md b/examples/linalg-transpose/README.md deleted file mode 100755 index 0927dc6..0000000 --- a/examples/linalg-transpose/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# linalg-transpose - -Formula-document example: declare symbols with a GFM table, check \((AB)^\top = B^\top A^\top\) via `ascii` (auto-simplify). - -```bash -cargo build --release -p marqdo_plugin_linalg -marqdo ext add linalg -marqdo run examples/linalg-transpose/index.mq.md -``` - -Design: [ext-linalg-formula-doc.md](../../doc/design/ext-linalg-formula-doc.md). diff --git a/examples/linalg-transpose/index.mq.md b/examples/linalg-transpose/index.mq.md deleted file mode 100755 index 0e7c73c..0000000 --- a/examples/linalg-transpose/index.mq.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -markup: occlusion -title: Transpose identity (formula document) -description: (AB)^T = B^T A^T as a runnable lecture fragment. -import: - la: ext/linalg/linalg.mq.md ---- - -# Transpose reverses products - - -Declare shapes in a table, form \(P = AB\), then check \((AB)^\top = B^\top A^\top\) by running the document. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -`shapes` = - -| @ | name | rows | cols | -|---|------|------|------| -| 1 | A | 2 | 3 | -| 2 | B | 3 | 2 | - -We first **env = [Compute env](la.declare(table=`shapes`))** for the next step. -We first **A = [A](access(`env`, "A"))** for the next step. -We first **B = [B](access(`env`, "B"))** for the next step. -We first **P = (`A` * `B`)** for the next step. -We first **t = [Compute t](> `P`.T_ascii)** for the next step. -We now **[Display this step's result](> print text=`t`)**. -1. `t` == "B^T*A^T" - We now **[Display this step's result](> print text="identity-ok")**. -2. * - We now **[Display this step's result](> print text="identity-fail")**. diff --git a/examples/link-syntax/README.md b/examples/link-syntax/README.md deleted file mode 100755 index 7596083..0000000 --- a/examples/link-syntax/README.md +++ /dev/null @@ -1,109 +0,0 @@ -# 链接语法示例:两文档,一次类调用 - -这个目录是 [链接语法设计声明](../../doc/design/link-syntax.md) 的**目标示例**: - -> `[李白的出生年份](李白.李白的出生年份)` -> 不是新的语法:`[]` 是 Markdown 链接的描述,`()` 是已有调用; -> `# 李白` 是类,`## 李白的出生年份` 是函数,`李白.李白的出生年份` 是类调用。 - -## 文件 - -| 文件 | 作用 | v2.0.0 可跑 | v2.1 目标 | -|------|------|-------------|-----------| -| `libai.mq.md` | 知识文档:`# 李白` → `## 李白的出生年份` → `*701*` | ✅ | ✅ | -| `main.mq.md` | 用户原始示例:正文链接 + 类调用 | ❌(安静无输出) | ✅ view 显示;`run` 加 print 输出 | -| `main.compat.mq.md` | 当前等价写法:`import` + 实例 + 本地链接 | ✅(输出 `701`) | ✅ | -| `expected-link-info.json` | 目标 `LinkInfo` 形状 | — | — | -| `links.lock.yaml` | 可选锁文件形状 | — | — | - -> **v2.0.0 的 `main.mq.md` 不会报错,也不会有输出**——因为: -> 1. 正文链接默认不执行(叙述默认安全); -> 2. `李白.李白的出生年份` 目前被当成变量/实例方法路径,类调用还没实现。 -> -> v2.1 的目标是:`view` 显示这个链接的目标、类、函数、签名、值;`check` 返回 LinkInfo; -> 要终端输出,就在代码链接里加 `print`。 - -## 今天可跑 - -```bash -marqdo run examples/link-syntax/main.compat.mq.md -# 701 -``` - -`main.compat.mq.md` 用当前能力完成了同一件事: - -```markdown ---- -markup: occlusion -import libai:libai.mq.md ---- - -# main - -**li = > libai.李白** -**year = [李白的出生年份](li.李白的出生年份())** -> print text=`year` -``` - -- `import` 绑定知识文档; -- `> libai.李白` 构造对象(当前 `#` 是对象/类型); -- `li.李白的出生年份()` 调用实例方法; -- `[]()` 把调用包成一句人话。 - -这正是 v2.0.0 的「实例方法」路径;v2.1 要把 `##` 恢复为**类函数**, -让 `李白.李白的出生年份` 直接调用,去掉 `import`/实例两步。 - -## 目标形式 - -`main.mq.md`: - -```markdown -# main -用户想要知道李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) -``` - -v2.1 期望: - -```bash -$ marqdo run examples/link-syntax/main.mq.md -# 无输出(正文链接不执行;加 print 才有输出) - -$ marqdo check examples/link-syntax/main.mq.md --json -{"code":"link.ok", ...} -``` - -`view` 期望: - -```text -用户想要知道李白的出生年份,我们要告诉用户 701。 - ↑ - 悬浮:李白的出生年份 → 李白.李白的出生年份 - class 李白 · function · () -> number · value 701 -``` - -要终端输出: - -```markdown -# main - -**year = [李白的出生年份](李白.李白的出生年份)** -> print text=`year` -``` - -```bash -$ marqdo run examples/link-syntax/main.mq.md -701 -``` - -## 为什么是 `李白.李白的出生年份` - -- `# 李白` 是类; -- `## 李白的出生年份` 是类下的函数; -- `李白.李白的出生年份` 是**类调用**; -- `[]` 是描述,`()` 是已有调用;没有新语法,没有协议前缀,没有别名开关。 - -## 相关 - -- 设计声明:[doc/design/link-syntax.md](../../doc/design/link-syntax.md) -- 证据复核:[doc/research/occlusion-vs-executable-knowledge-2026-10.md](../../doc/research/occlusion-vs-executable-knowledge-2026-10.md) -- 旧遮蔽设计:[doc/design/occlusion-syntax.md](../../doc/design/occlusion-syntax.md) diff --git a/examples/link-syntax/expected-link-info.json b/examples/link-syntax/expected-link-info.json deleted file mode 100755 index 9400aef..0000000 --- a/examples/link-syntax/expected-link-info.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "label": "李白的出生年份", - "source": { - "file": "main.mq.md", - "line": 2, - "col": 26 - }, - "target": { - "class": "李白", - "function": "李白的出生年份", - "doc": "libai.mq.md", - "kind": "class_function", - "signature": { - "params": [], - "returns": "number" - }, - "instance_only": false - }, - "status": "ok", - "value": null, - "fingerprint": "sha256:<target-body-hash>" -} diff --git a/examples/link-syntax/libai.mq.md b/examples/link-syntax/libai.mq.md deleted file mode 100755 index 5106a0c..0000000 --- a/examples/link-syntax/libai.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion -type: Fact -id: libai -title: 李白 -description: 李白知识文档:一个可被其他文档链接调用的知识单元 -status: stable ---- - -# 李白 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | - -这个文档存储了李白的信息。 - -## 李白的出生年份 - -李白的出生年份是公元 701 年。 - -| 返回 | 类型 | 说明 | -|------|------|------| -| 701 | number | 公元 701 年 | - -完成上述步骤后,返回*701*。 diff --git a/examples/link-syntax/links.lock.yaml b/examples/link-syntax/links.lock.yaml deleted file mode 100755 index 279b541..0000000 --- a/examples/link-syntax/links.lock.yaml +++ /dev/null @@ -1,9 +0,0 @@ -version: 1 -generated_by: marqdo/2.1.0 -links: - - from: main.mq.md - label: 李白的出生年份 - to: libai.mq.md::李白.李白的出生年份 - kind: class_function - signature: "() -> number" - fingerprint: sha256:<target-body-hash> diff --git a/examples/link-syntax/main.compat.mq.md b/examples/link-syntax/main.compat.mq.md deleted file mode 100755 index e7bec8b..0000000 --- a/examples/link-syntax/main.compat.mq.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -markup: occlusion -import: - libai: libai.mq.md ---- - -# main - -**li = > libai.李白** -**year = [李白的出生年份](li.李白的出生年份())** -> print text=`year` diff --git a/examples/link-syntax/main.mq.md b/examples/link-syntax/main.mq.md deleted file mode 100755 index c02f938..0000000 --- a/examples/link-syntax/main.mq.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -markup: occlusion ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | -用户想要知道李白的出生年份,我们要告诉用户[李白的出生年份](李白.李白的出生年份) diff --git a/examples/marqdo-blog/README.md b/examples/marqdo-blog/README.md deleted file mode 100755 index 64d1c19..0000000 --- a/examples/marqdo-blog/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# examples/marqdo-blog - -Marqdo **Web Artifact** blog (ADR 0007). - -## Layout - -```text -index.mq.md # type: web · / · data_source: posts -pages/about.mq.md # 类型: 网页 · /about -pages/post.mq.md # type: web · /post/{slug} · data_where -api/ping.mq.md # type: endpoint · GET /api/ping -api/echo.mq.md # type: endpoint · POST /api/echo -db/posts.mq.md # ext/data schema + seed + open -public/ # static (mounted at /static) -serve.mq.md # web.serve + db open -smoke.sh # curl checks against a running serve -``` - -## Run - -从仓库根使用当前 CLI 和开发手册准备原生插件,再调用启动函数: - -```sh -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json -target/debug/marqdo call examples/marqdo-blog/serve.mq.md main --effects plugin,fs.write,network.write --fs-root examples/marqdo-blog --require-ok --json -``` - -默认数据库按授权站点根解析到 data/blog.db,重启保留已有文章。准备工程插件见开发入口的 prepare_engineering;验收使用独占副本,不删除现有数据库。 - - -| Path | Artifact | -|------|----------| -| `/` | Document home + post cards | -| `/about` | ZH Document | -| `/post/{slug}` | Document detail | -| `/api/ping` | Endpoint JSON | -| `/api/echo` | Endpoint JSON echo | -| `/static/*` | public assets | - -Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md). diff --git a/examples/marqdo-blog/api/echo.mq.md b/examples/marqdo-blog/api/echo.mq.md deleted file mode 100755 index 0293fa2..0000000 --- a/examples/marqdo-blog/api/echo.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -type: endpoint -method: POST -path: /api/echo -request: json -response: json -auth: none ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Result or browser effect record assembled below | - -Echo request fields bound via Artifact Metadata (`arg` overlays). - -We first **msg = `message`** for the next step. -1. not `msg` - We first **msg = ""** for the next step. -2. * - -`out` = - -| ok | message | -|----|---------| -| True | `msg` | - -After these steps, return *out*. diff --git a/examples/marqdo-blog/api/ping.mq.md b/examples/marqdo-blog/api/ping.mq.md deleted file mode 100755 index 5b3e1bd..0000000 --- a/examples/marqdo-blog/api/ping.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -type: endpoint -method: GET -path: /api/ping -request: none -response: json -auth: none -description: Health ping — documentation is the API (ADR 0007). ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Result or browser effect record assembled below | - -`out` = - -| ok | service | -|----|---------| -| True | marqdo-blog | - -After these steps, return *out*. diff --git a/examples/marqdo-blog/components/foot.mq.md b/examples/marqdo-blog/components/foot.mq.md deleted file mode 100755 index 811dae5..0000000 --- a/examples/marqdo-blog/components/foot.mq.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -markup: occlusion ---- - -## 页脚 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -站点页脚。放版权与概览链接。 - -`页脚` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| © 2026 Marqdo 博客 | / | | -| 关于 | /about | | -| 后台 | /admin | | - -After these steps, return *页脚*. \ No newline at end of file diff --git a/examples/marqdo-blog/components/nav.mq.md b/examples/marqdo-blog/components/nav.mq.md deleted file mode 100755 index 1bf4b42..0000000 --- a/examples/marqdo-blog/components/nav.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion ---- - -## 导航 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -站点顶部导航。首项是站点名(渐变 Logo 由主题 CSS 处理),`后台` 指向需要登录的 `/admin`。 - -`导航` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| Marqdo 博客 | / | | -| 首页 | / | | -| 标签 | /tags | | -| 关于 | /about | | -| 后台 | /admin | | - -After these steps, return *导航*. \ No newline at end of file diff --git a/examples/marqdo-blog/components/side.mq.md b/examples/marqdo-blog/components/side.mq.md deleted file mode 100755 index cebf8cb..0000000 --- a/examples/marqdo-blog/components/side.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion ---- - -## 侧栏 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -右侧归档面板:文章入口、标签、实时小部件。 - -`侧栏` = - -| 属性 | 值 | 样式 | -|------|-----|------| -| 全部文章 | / | | -| 标签归档 | /tags | | -| 关于本站 | /about | | -| 发布文章 | /admin/new | | -| 实时终端 | /#live | | - -After these steps, return *侧栏*. \ No newline at end of file diff --git a/examples/marqdo-blog/db/posts.mq.md b/examples/marqdo-blog/db/posts.mq.md deleted file mode 100755 index 22459b2..0000000 --- a/examples/marqdo-blog/db/posts.mq.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -markup: occlusion -title: 当前 Artifact 博客数据调用手册 -import: - document: lib/document.mq.md - data: ext/data/db.mq.md - fs: lib/fs.mq.md - text: lib/text.mq.md ---- - -本文件负责可调用的说明与编排,[posts.tables.md](posts.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 - -## schema - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -当前站点的文章字段包括标题、slug、摘要、正文、标签和创建日期。原生数据库初始化器负责 id;本结构保留当前自动列表与详情页所需字段。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [posts.tables.md](posts.tables.md#schema);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取schema的实际 Markdown 常量](document.read_table(path="db/posts.tables.md", title="schema"))*. - -## seed - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -两篇当前站点的起始文章保留稳定 slug、内容与日期。只有调用 open 且文章表为空时才插入;读取种子本身不会改变现有文章。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [posts.tables.md](posts.tables.md#seed);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取seed的实际 Markdown 常量](document.read_table(path="db/posts.tables.md", title="seed"))*. - -## open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | None | None 使用授权站点根内 data/blog.db;验收可传独占绝对 URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 已初始化且保留原有文章的实际数据库资源 | - -使用`url`=None,以 examples/marqdo-blog 为 --fs-root 授予 fs.write 与 plugin。默认路径先通过固有能力创建 data 目录,再解析真实绝对文件地址,避免被插件模块位置或终端工作目录影响。显式 SQLite 路径同样经过根目录和符号链接检查;其他受支持后端按其连接契约执行,文件授权不限制外部数据库服务。 - -字段与种子由原生 Markdown 读取器保留字面类型。初始化只确保文章表存在,再查一行判断是否已有业务数据;只为空表插入原来的两条记录。已有或部分填充的表都原样保留,这不是列迁移器,也不会删除或重排用户文章。连接、结构或插入失败应停止启动,不能继续监听并声称数据库已经准备好。 - -隔离验收使用调用者拥有的临时站点副本,保留同一资源继续查询与写入。进程退出、连接关闭后再清理该目录,不对示例的现有 data 目录执行重置。读取结构或种子本身不写库,写入只发生在这份明确初始化流程里。 - -1. `url` == None - 我们 **[创建本站默认数据目录](fs.make_dirs(path="data"))**、**file = [按原生授权根解析数据库文件](fs.resolve(path="data/blog.db"))** 和 **url = "sqlite:" + file**。 -1. [明确选择 SQLite 后端](text.starts_with(text=`url`, prefix="sqlite:")) - 我们 **file = [取出实际 SQLite 地址](text.replace(text=`url`, old="sqlite:", new="", count=1))**、**file = [检查根目录和符号链接边界](fs.resolve(path=`file`))** 和 **url = "sqlite:" + file**。 -我们 **store = [连接实际选择的数据库](data.db(url=`url`))** 和 **fields = [读取当前文章结构](schema())**。 -接着 **[确保文章结构但不清空数据](> `store`.init name="posts" fields=`fields`)** 和 **existing = [检查是否已有业务文章](> `store`.select table="posts" limit=1)**。 -1. not `existing` - 我们 **rows = [读取空表使用的原始记录](seed())** 和 **[只初始化空表](> `store`.insert table="posts" rows=`rows`)**。 -准备完成后返回 *store*,供当前服务流程继续使用。 diff --git a/examples/marqdo-blog/db/posts.tables.md b/examples/marqdo-blog/db/posts.tables.md deleted file mode 100755 index 669e7a7..0000000 --- a/examples/marqdo-blog/db/posts.tables.md +++ /dev/null @@ -1,25 +0,0 @@ -# 当前 Artifact 博客数据 - -这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 - -## schema - -当前站点的文章字段包括标题、slug、摘要、正文、标签和创建日期。原生数据库初始化器负责 id;本结构保留当前自动列表与详情页所需字段。 - -| 字段 | 类型 | 可空 | -|------|------|------| -| title | text | False | -| slug | text | False | -| summary | text | True | -| content | text | True | -| tag | text | True | -| created_at | text | True | - -## seed - -两篇当前站点的起始文章保留稳定 slug、内容与日期。只有调用 open 且文章表为空时才插入;读取种子本身不会改变现有文章。 - -| title | slug | summary | content | tag | created_at | -|-------|------|---------|---------|-----|------------| -| Hello Marqdo | hello | Welcome | Hello — executable documents. | intro | 2026-09-01 | -| Artifact Web | artifact-web | Document first | Pages are mq.md files. | design | 2026-09-28 | diff --git a/examples/marqdo-blog/db/schema.mq.md b/examples/marqdo-blog/db/schema.mq.md deleted file mode 100755 index e2315f0..0000000 --- a/examples/marqdo-blog/db/schema.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -title: 博客表结构调用手册 -import: - document: lib/document.mq.md ---- - -本文件负责可调用的说明与编排,[schema.tables.md](schema.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 - -## posts - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -文章结构保留 id、标题、slug、摘要、Markdown 正文、主标签和时间字段。slug 对应文章详情路由;可空声明控制存储约束,路由授权仍由端点或门禁负责。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [schema.tables.md](schema.tables.md#posts);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取posts的实际 Markdown 常量](document.read_table(path="db/schema.tables.md", title="posts"))*. - -## tags - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -标签结构保留显示名称与稳定 slug。显示文字可以改动,路由和文章主标签应继续引用稳定标识;唯一索引需要在正式迁移中明确声明。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [schema.tables.md](schema.tables.md#tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取tags的实际 Markdown 常量](document.read_table(path="db/schema.tables.md", title="tags"))*. - -## post_tags - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -关联结构保留文章与标签标识。种子关系依赖空数据库中预期的插入顺序;向已有用户库导入时应先映射真实 id,不能直接复用演示序号。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [schema.tables.md](schema.tables.md#post_tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取post_tags的实际 Markdown 常量](document.read_table(path="db/schema.tables.md", title="post_tags"))*. diff --git a/examples/marqdo-blog/db/schema.tables.md b/examples/marqdo-blog/db/schema.tables.md deleted file mode 100755 index c050211..0000000 --- a/examples/marqdo-blog/db/schema.tables.md +++ /dev/null @@ -1,38 +0,0 @@ -# 博客表结构 - -这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 - -## posts - -文章结构保留 id、标题、slug、摘要、Markdown 正文、主标签和时间字段。slug 对应文章详情路由;可空声明控制存储约束,路由授权仍由端点或门禁负责。 - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| title | text | false | -| slug | text | false | -| summary | text | true | -| content | text | true | -| tag | text | true | -| created_at | text | true | -| updated_at | text | true | - -## tags - -标签结构保留显示名称与稳定 slug。显示文字可以改动,路由和文章主标签应继续引用稳定标识;唯一索引需要在正式迁移中明确声明。 - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| name | text | false | -| slug | text | false | - -## post_tags - -关联结构保留文章与标签标识。种子关系依赖空数据库中预期的插入顺序;向已有用户库导入时应先映射真实 id,不能直接复用演示序号。 - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| post_id | integer | false | -| tag_id | integer | false | diff --git a/examples/marqdo-blog/db/seed.mq.md b/examples/marqdo-blog/db/seed.mq.md deleted file mode 100755 index e793a32..0000000 --- a/examples/marqdo-blog/db/seed.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -title: 博客演示种子调用手册 -import: - document: lib/document.mq.md ---- - -本文件负责可调用的说明与编排,[seed.tables.md](seed.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 - -## posts - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -六篇演示文章覆盖文档、路由、原生集合、实时通信、会话和数据库。日期用于稳定排序,正文保持 Markdown 数据;这些常量不会自行写入数据库。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [seed.tables.md](seed.tables.md#posts);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取posts的实际 Markdown 常量](document.read_table(path="db/seed.tables.md", title="posts"))*. - -## tags - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -演示标签保留原始顺序与 slug,便于在独立空库中验证文章关联。读取这些行没有插入或删除效果;现有用户标签应由显式迁移管理。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [seed.tables.md](seed.tables.md#tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取tags的实际 Markdown 常量](document.read_table(path="db/seed.tables.md", title="tags"))*. - -## post_tags - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -关联行保持文章与标签的演示对应关系。它们适用于按同一顺序初始化的空库;已有数据需要重新映射 id,读取函数不会清空或重建任何表。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [seed.tables.md](seed.tables.md#post_tags);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取post_tags的实际 Markdown 常量](document.read_table(path="db/seed.tables.md", title="post_tags"))*. diff --git a/examples/marqdo-blog/db/seed.tables.md b/examples/marqdo-blog/db/seed.tables.md deleted file mode 100755 index 7acb234..0000000 --- a/examples/marqdo-blog/db/seed.tables.md +++ /dev/null @@ -1,45 +0,0 @@ -# 博客演示种子 - -这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 - -## posts - -六篇演示文章覆盖文档、路由、原生集合、实时通信、会话和数据库。日期用于稳定排序,正文保持 Markdown 数据;这些常量不会自行写入数据库。 - -| 行 | title | slug | summary | content | tag | created_at | updated_at | -|----|-------|------|---------|---------|-----|------------|------------| -| 1 | 你好,Marqdo 博客 | hello-marqdo | 用 Marqdo 的 web 扩展库搭建的第一个博客。表格即组件、文档即代码。 | 这是一篇介绍博客系统的文章。它由 Marqdo 脚本在启动时写入 SQLite,通过 ext/web 的组件装配渲染成页面。 | marqdo | 2026-08-01 | 2026-08-02 | -| 2 | 动态路由与文章详情 | dynamic-routing | 如何用 /post/{slug} 动态路由渲染单篇文章。 | 本文说明动态路由机制:作者面注册带 {slug} 占位符的路由,请求时把路径参数注入页面查询条件。 | web | 2026-08-05 | 2026-08-05 | -| 3 | 用 GFM 表格表达数据 | gfm-tables | Marqdo 的字典操作不依赖 json 库,GFM 表格即可完成。 | 表格即数据、表格即组件。这篇文章展示如何在 .mq.md 里用横向表写种子数据,用脚注索引读取字段。 | tutorial | 2026-08-10 | 2026-08-11 | -| 4 | WebSocket 实时小部件 | websocket-live | 给博客加一个实时回显的 WebSocket 端点。 | 通过 app.路由实时 注册 /live 端点,配合 public/live.js 在首页显示实时连接状态。 | realtime | 2026-08-15 | 2026-08-15 | -| 5 | 会话与登录鉴权 | session-auth | 后台用 session 门禁保护,只有登录用户能发布文章。 | 用 app.鉴权 配置管理员用户表,/admin 下的 CRUD 页面都需要有效会话。 | web | 2026-08-18 | 2026-08-20 | -| 6 | 数据库与 CRUD | database-crud | 博客的文章、标签、关联全部由 SQLite 支撑。 | db.初始化 建表、db.插入 写种子、后台表单增删改。文章与标签通过 post_tags 关联。 | database | 2026-08-20 | 2026-08-21 | - -## tags - -演示标签保留原始顺序与 slug,便于在独立空库中验证文章关联。读取这些行没有插入或删除效果;现有用户标签应由显式迁移管理。 - -| 行 | name | slug | -|----|------|------| -| 1 | Marqdo | marqdo | -| 2 | Web | web | -| 3 | 教程 | tutorial | -| 4 | 数据库 | database | -| 5 | 实时 | realtime | - -## post_tags - -关联行保持文章与标签的演示对应关系。它们适用于按同一顺序初始化的空库;已有数据需要重新映射 id,读取函数不会清空或重建任何表。 - -| 行 | post_id | tag_id | -|----|---------|--------| -| 1 | 1 | 1 | -| 2 | 1 | 2 | -| 3 | 2 | 2 | -| 4 | 3 | 1 | -| 5 | 3 | 3 | -| 6 | 4 | 5 | -| 7 | 4 | 2 | -| 8 | 5 | 2 | -| 9 | 6 | 4 | -| 10 | 6 | 1 | diff --git a/examples/marqdo-blog/index.mq.md b/examples/marqdo-blog/index.mq.md deleted file mode 100755 index 3ad7bee..0000000 --- a/examples/marqdo-blog/index.mq.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -markup: occlusion -type: web -title: Marqdo 博客 -route: / -method: GET -data_source: posts -data_order: -created_at -description: >- - Document Artifact 首页(ADR 0007):正文即文档,列表来自 data_source。 -导入: - 网页: ext/web/网页.mq.md ---- - -# Marqdo 博客 - -可执行文档即网页。本站用 Artifact Metadata 声明路由;文章列表由 `data_source: posts` 在服务时加载。 diff --git a/examples/marqdo-blog/pages/about.mq.md b/examples/marqdo-blog/pages/about.mq.md deleted file mode 100755 index e992925..0000000 --- a/examples/marqdo-blog/pages/about.mq.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -markup: occlusion -类型: 网页 -路由: /about -方法: GET -标题: 关于 ---- - -# 关于 Marqdo - - -Marqdo 是可执行文档语言:文档即程序,程序即知识。 diff --git a/examples/marqdo-blog/pages/post.mq.md b/examples/marqdo-blog/pages/post.mq.md deleted file mode 100755 index 91d09d0..0000000 --- a/examples/marqdo-blog/pages/post.mq.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -markup: occlusion -type: web -title: Post -route: /post/{slug} -method: GET -data_source: posts -data_where: slug={slug} -description: Dynamic Document route — body is the article shell; data from Resource. ---- - -# Post - -Article page for `{slug}`. List and detail data are provided by `ext/data` at serve time when `data_source` is set on the Artifact. diff --git a/examples/marqdo-blog/public/favicon.png b/examples/marqdo-blog/public/favicon.png deleted file mode 100755 index 0dd1608..0000000 --- a/examples/marqdo-blog/public/favicon.png +++ /dev/null @@ -1,2 +0,0 @@ -‰PNG - diff --git a/examples/marqdo-blog/public/favicon.svg b/examples/marqdo-blog/public/favicon.svg deleted file mode 100755 index b361312..0000000 --- a/examples/marqdo-blog/public/favicon.svg +++ /dev/null @@ -1 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#1a5f4a"/><text x="16" y="22" text-anchor="middle" font-size="16" font-family="Georgia,serif" fill="#f4f7f5">M</text></svg> diff --git a/examples/marqdo-blog/public/live.js b/examples/marqdo-blog/public/live.js deleted file mode 100755 index 705753a..0000000 --- a/examples/marqdo-blog/public/live.js +++ /dev/null @@ -1,40 +0,0 @@ -// 实时 WebSocket 小部件(连接 /live 端点)。 -// 连接 ws://host/live,发送输入,展示服务器回显。 -(function () { - var out = document.getElementById("live-out"); - var input = document.getElementById("live-msg"); - var btn = document.getElementById("live-send"); - var status = document.getElementById("live-status"); - if (!out || !input || !btn || !status) return; - - var proto = location.protocol === "https:" ? "wss" : "ws"; - var ws = new WebSocket(proto + "://" + location.host + "/live"); - status.textContent = "connecting…"; - - ws.onopen = function () { - status.textContent = "connected"; - btn.disabled = false; - }; - ws.onmessage = function (ev) { - var p = document.createElement("p"); - p.textContent = "echo: " + ev.data; - out.appendChild(p); - out.scrollTop = out.scrollHeight; - }; - ws.onclose = function () { - status.textContent = "closed"; - btn.disabled = true; - }; - ws.onerror = function () { - status.textContent = "error"; - btn.disabled = true; - }; - - btn.onclick = function () { - var m = input.value.trim(); - if (m) ws.send(m); - }; - input.addEventListener("keydown", function (e) { - if (e.key === "Enter") btn.onclick(); - }); -})(); diff --git a/examples/marqdo-blog/public/logo.svg b/examples/marqdo-blog/public/logo.svg deleted file mode 100755 index b361312..0000000 --- a/examples/marqdo-blog/public/logo.svg +++ /dev/null @@ -1 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#1a5f4a"/><text x="16" y="22" text-anchor="middle" font-size="16" font-family="Georgia,serif" fill="#f4f7f5">M</text></svg> diff --git a/examples/marqdo-blog/serve.mq.md b/examples/marqdo-blog/serve.mq.md deleted file mode 100755 index 36341ac..0000000 --- a/examples/marqdo-blog/serve.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -title: Callable Artifact blog launcher -import: - web: ext/web/web.mq.md - posts: db/posts.mq.md ---- - -This launcher starts the ordinary Markdown/data-source Documents and declared JSON Endpoints. It owns data preparation and listener lifetime; the index remains readable page content. From the checkout use marqdo call examples/marqdo-blog/serve.mq.md main with --effects plugin,fs.write,network.write and --fs-root examples/marqdo-blog. - -## main - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/marqdo-blog" | Explicit discovery root relative to the checkout | -| port | number | 18081 | Local loopback listen port | -| url | any | None | None uses the retained site-root database; tests supply an owned URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking listener after database preparation and declared-route discovery | - -Use `root`="examples/marqdo-blog", `port`=18081 and `url`=None from the checkout. The ordinary callable heading makes this workflow available through call, while Document bodies remain Markdown. Native filesystem resolution keeps SQLite under the actual granted site root, independently of the terminal working directory. Existing articles are retained and only an empty table receives demonstration rows. - -Discovery follows the actual route metadata for Home, About, slug detail, Ping and Echo. Ordinary Documents keep their existing request-time data-source behavior. Starting this workflow is an explicit local network action, not a side effect of reading a library. The listener blocks until the supervising caller stops the process; no detached daemon or database reset is implied. - -We **store = [Prepare the retained current blog data](posts.open(url=`url`))**. -Return *[Discover and listen with the actual site context](web.serve(root=`root`, host="127.0.0.1", port=`port`, db=`store`, static_dir="public"))*. diff --git a/examples/marqdo-blog/smoke.sh b/examples/marqdo-blog/smoke.sh deleted file mode 100755 index c0bd72e..0000000 --- a/examples/marqdo-blog/smoke.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash -# Artifact blog smoke (ADR 0007). Usage: bash examples/marqdo-blog/smoke.sh -# Expects serve.mq.md already listening on BASE (default 18081). -set -uo pipefail -BASE="${BASE:-http://127.0.0.1:18081}" -PASS=0; FAIL=0 -ok() { echo " ok: $1"; PASS=$((PASS+1)); } -bad() { echo " FAIL: $1"; FAIL=$((FAIL+1)); } - -echo "== Document home ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/") -[ "$code" = "200" ] && ok "GET / -> $code" || bad "GET / -> $code" -curl -s "$BASE/" | grep -q '<title>Marqdo 博客' && ok "title" || bad "title" -curl -s "$BASE/" | grep -q 'class="card"' && ok "data_source cards" || bad "cards missing" -curl -s "$BASE/" | grep -q 'Hello Marqdo' && ok "seed title" || bad "seed title missing" - -echo "== Static ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/static/live.js") -[ "$code" = "200" ] && ok "GET /static/live.js -> $code" || bad "static -> $code" - -echo "== Dynamic Document ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/hello") -[ "$code" = "200" ] && ok "GET /post/hello -> $code" || bad "post detail -> $code" -curl -s "$BASE/post/hello" | grep -q 'article-title' && ok "article title" || bad "article title missing" - -echo "== ZH Document ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/about") -[ "$code" = "200" ] && ok "GET /about -> $code" || bad "about -> $code" -curl -s "$BASE/about" | grep -q '关于 Marqdo' && ok "about body" || bad "about body missing" - -echo "== Endpoint ==" -code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/api/ping") -[ "$code" = "200" ] && ok "GET /api/ping -> $code" || bad "ping -> $code" -curl -s "$BASE/api/ping" | grep -q 'marqdo-blog' && ok "ping json" || bad "ping json missing" -code=$(curl -s -o /tmp/mq_blog_echo.json -w "%{http_code}" \ - -H 'Content-Type: application/json' -d '{"message":"hi"}' "$BASE/api/echo") -[ "$code" = "200" ] && ok "POST /api/echo -> $code" || bad "echo -> $code" -grep -q '"message":"hi"' /tmp/mq_blog_echo.json && ok "echo body" || bad "echo body missing" - -echo -echo "通过 $PASS / $((PASS+FAIL))" -[ "$FAIL" = "0" ] || exit 1 diff --git a/examples/marqdo-blog/styles/theme.mq.md b/examples/marqdo-blog/styles/theme.mq.md deleted file mode 100755 index aeee470..0000000 --- a/examples/marqdo-blog/styles/theme.mq.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -markup: occlusion -title: 博客主题字面样式调用手册 -import: - document: lib/document.mq.md - web: ext/web/web.mq.md - text: lib/text.mq.md - table: lib/table.mq.md ---- - -本文件负责可调用的说明与编排,[theme.tables.md](theme.tables.md)负责可独立阅读的 Markdown 常量。调用时把 --fs-root 指向 examples/marqdo-blog,读取需要 fs.read;连接数据库或编译样式时还需要 plugin。 - -## 基础 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -基础段声明纸张、文字和强调色变量,以及字体与页面骨架。返回值仍是原生样式表数据,编译与浏览器加载由各自的明确步骤完成。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#基础);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取基础的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="基础"))*. - -## 顶栏 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -顶栏段保留吸顶导航、磨砂背景、品牌渐变与链接状态。选择器与值都位于数据叶子,调用函数说明用途,避免把整套声明堆进执行流程。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#顶栏);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取顶栏的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="顶栏"))*. - -## 侧栏 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -侧栏段保留归档面板的布局、链接间距和悬停反馈。它只提供样式数据,具体侧栏内容仍由独立组件或 Document 负责。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#侧栏);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取侧栏的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="侧栏"))*. - -## 主体 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -主体段定义内容区留白、标题和导语的排版节奏。数据读取保持原有字段和值;主题编译不会替页面构造布局节点。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#主体);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取主体的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="主体"))*. - -## 卡片 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -卡片段保留文章列表的网格、阴影、封面和悬停状态。样式类名应与页面输出保持一致;此函数只读取声明,不查询文章数据。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#卡片);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取卡片的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="卡片"))*. - -## 页脚 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -页脚段保留页面末尾的留白、分隔线和链接外观。页脚若分为多个布局区域,仍应沿组件目录拆分,样式声明不会代替工程结构。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#页脚);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取页脚的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="页脚"))*. - -## 表单 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -表单段保留输入控件、按钮和管理操作的状态样式。字段校验、保存和鉴权属于数据与安全资源;样式只改变已存在控件的外观。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#表单);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取表单的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="表单"))*. - -## 响应式 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与原字面表一致的数据类型和记录/列式形态 | - -响应式段保留窄屏断点、侧栏流向、内容间距和列表列数。媒体条件仍由原生样式编译器读取,浏览器结果需要实际窄屏验证。 - -从站点根目录授予 fs.read 后调用。实际常量位于 [theme.tables.md](theme.tables.md#响应式);读取过程保留数值、布尔、空值和表格形态,并检查标题与行列结构。数据文件中的说明不会作为程序运行。 - -完成后返回*[读取响应式的实际 Markdown 常量](document.read_table(path="styles/theme.tables.md", title="响应式"))*. - -## _编译段 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名称 | text | 必填 | theme.tables.md 中精确且唯一的样式章节名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 由所选样式声明编译的 CSS | - -使用`名称`选择一个具有独立职责的声明段,授权 fs.read 和 plugin。字面表读取保留原始选择器、属性和值,原生样式编译器负责媒体条件及 CSS 单元格处理。标题错误会保留文档诊断;此步骤不写文件,也不会把样式附加到浏览器。 - -我们 **数据 = [读取这一段的实际样式常量](document.read_table(path="styles/theme.tables.md", title=`名称`))**。 -完成后返回*[编译所选声明段](web.make_style(name=`名称`, table=`数据`))*. - - -## 全局 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 全部声明段按稳定顺序编译的 CSS 文本 | - -从站点根授权 fs.read 与 plugin 后调用。名称表保留基础、导航、侧栏、主体、卡片、页脚、表单和断点的原有顺序;每段通过同一编译步骤读取自己的 Markdown 常量。变量声明因此先于使用它们的组件规则,响应式覆盖放在最后。返回值仍是 CSS 文本,保存与资源引用由明确的后续步骤完成。各命名数据函数也继续保留,方便独立检查某个区域。 - -`names` = - -| 名称 | -|---| -| 基础 | -| 顶栏 | -| 侧栏 | -| 主体 | -| 卡片 | -| 页脚 | -| 表单 | -| 响应式 | - -我们 **parts = [开始有序的 CSS 段列表](table.empty_list())**。 -- [依次编译每个独立声明段](for names as name) - 我们 **css = [编译当前区域](_编译段(名称=`name`))**,并 **parts = [保留覆盖顺序](table.append(list=`parts`, item=`css`))**。 -完成后返回*[按区域顺序连接 CSS](text.str_join(xs=`parts`, sep="\n"))*. diff --git a/examples/marqdo-blog/styles/theme.tables.md b/examples/marqdo-blog/styles/theme.tables.md deleted file mode 100755 index 5e19ba9..0000000 --- a/examples/marqdo-blog/styles/theme.tables.md +++ /dev/null @@ -1,330 +0,0 @@ -# 博客主题字面样式 - -这里保存原生字面 GFM 数据。调用函数通过 document.read_table 读取所选章节;不会执行本文件中的说明或示例。 - -## 基础 - -基础段声明纸张、文字和强调色变量,以及字体与页面骨架。返回值仍是原生样式表数据,编译与浏览器加载由各自的明确步骤完成。 - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| :root | --ink | #1c1917 | -| :root | --ink-soft | #44403c | -| :root | --muted | #78716c | -| :root | --faint | #a8a29e | -| :root | --paper | #f7f5f2 | -| :root | --card | #ffffff | -| :root | --line | #e7e5e4 | -| :root | --accent | #4f46e5 | -| :root | --accent-2 | #7c3aed | -| :root | --accent-ink | #ffffff | -| :root | --radius | 16px | -| :root | --shadow | 0 1px 2px rgba(28,25,23,.05), 0 8px 24px rgba(28,25,23,.06) | -| :root | --shadow-lg | 0 4px 12px rgba(28,25,23,.08), 0 20px 48px rgba(28,25,23,.12) | -| :root | --serif | "Noto Serif SC", Georgia, "Songti SC", serif | -| :root | --sans | "Noto Sans SC", "IBM Plex Sans", system-ui, -apple-system, sans-serif | -| html | scroll-behavior | smooth | -| * | box-sizing | border-box | -| ::selection | background | rgba(79,70,229,.18) | -| body | margin | 0 | -| body | font-family | var(--sans) | -| body | background | var(--paper) | -| body | color | var(--ink) | -| body | display | grid | -| body | min-height | 100vh | -| body | line-height | 1.7 | -| body | grid-template-rows | auto 1fr auto | -| body.has-sidebar | grid-template-columns | 15rem 1fr | -| body.has-sidebar | grid-template-areas | "top top" "side main" "foot foot" | -| body.no-sidebar | grid-template-areas | "top" "main" "foot" | - -## 顶栏 - -顶栏段保留吸顶导航、磨砂背景、品牌渐变与链接状态。选择器与值都位于数据叶子,调用函数说明用途,避免把整套声明堆进执行流程。 - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| header.topnav | grid-area | top | -| header.topnav | position | sticky | -| header.topnav | top | 0 | -| header.topnav | z-index | 20 | -| header.topnav | background | rgba(255,255,255,.82) | -| header.topnav | backdrop-filter | blur(10px) | -| header.topnav | -webkit-backdrop-filter | blur(10px) | -| header.topnav | border-bottom | 1px solid var(--line) | -| header.topnav | padding | .9rem 2rem | -| header.topnav | display | flex | -| header.topnav | align-items | center | -| header.topnav | justify-content | space-between | -| ul.nav | list-style | none | -| ul.nav | margin | 0 | -| ul.nav | padding | 0 | -| ul.nav | display | flex | -| ul.nav | align-items | center | -| ul.nav | gap | .35rem | -| ul.nav li | margin | 0 | -| ul.nav a | display | inline-block | -| ul.nav a | padding | .45rem .9rem | -| ul.nav a | border-radius | 999px | -| ul.nav a | color | var(--ink-soft) | -| ul.nav a | font-weight | 500 | -| ul.nav a | text-decoration | none | -| ul.nav a | transition | background .18s ease, color .18s ease | -| ul.nav a:hover | background | rgba(79,70,229,.1) | -| ul.nav a:hover | color | var(--accent) | -| ul.nav li:first-child a | font-family | var(--serif) | -| ul.nav li:first-child a | font-size | 1.25rem | -| ul.nav li:first-child a | font-weight | 700 | -| ul.nav li:first-child a | background | linear-gradient(120deg, var(--accent), var(--accent-2)) | -| ul.nav li:first-child a | -webkit-background-clip | text | -| ul.nav li:first-child a | background-clip | text | -| ul.nav li:first-child a | -webkit-text-fill-color | transparent | -| ul.nav li:first-child a | color | transparent | -| ul.nav li:first-child a | padding-left | .2rem | -| ul.nav li:first-child a | padding-right | .2rem | - -## 侧栏 - -侧栏段保留归档面板的布局、链接间距和悬停反馈。它只提供样式数据,具体侧栏内容仍由独立组件或 Document 负责。 - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| aside.side | grid-area | side | -| aside.side | padding | 2rem 1.25rem | -| aside.side | border-right | 1px solid var(--line) | -| aside.side | background | linear-gradient(180deg, #fbfaf8, #f3f1ec) | -| ul.side-nav | list-style | none | -| ul.side-nav | margin | 0 | -| ul.side-nav | padding | 0 | -| ul.side-nav | display | flex | -| ul.side-nav | flex-direction | column | -| ul.side-nav | gap | .25rem | -| ul.side-nav li | margin | 0 | -| ul.side-nav a | display | block | -| ul.side-nav a | padding | .55rem .85rem | -| ul.side-nav a | border-radius | 10px | -| ul.side-nav a | color | var(--ink-soft) | -| ul.side-nav a | text-decoration | none | -| ul.side-nav a | font-weight | 500 | -| ul.side-nav a | transition | background .15s ease, transform .15s ease, color .15s ease | -| ul.side-nav a:hover | background | #fff | -| ul.side-nav a:hover | color | var(--accent) | -| ul.side-nav a:hover | transform | translateX(4px) | -| ul.side-nav a:hover | box-shadow | 0 1px 3px rgba(28,25,23,.08) | - -## 主体 - -主体段定义内容区留白、标题和导语的排版节奏。数据读取保持原有字段和值;主题编译不会替页面构造布局节点。 - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| main.main | grid-area | main | -| main.main | padding | 2.5rem 2.5rem 3.5rem | -| main.main | max-width | 76rem | -| main.main | width | 100% | -| .main-intro | margin-bottom | .5rem | -| .main-intro h1 | font-family | var(--serif) | -| .main-intro h1 | margin | 0 0 .5rem | -| .main-intro h1 | font-size | clamp(2rem, 5vw, 2.9rem) | -| .main-intro h1 | line-height | 1.2 | -| .main-intro h1 | font-weight | 700 | -| .main-intro h1 | letter-spacing | -.01em | -| .main-intro p | color | var(--muted) | -| .main-intro p | margin | 0 | -| .main-intro p | font-size | 1.05rem | - -## 卡片 - -卡片段保留文章列表的网格、阴影、封面和悬停状态。样式类名应与页面输出保持一致;此函数只读取声明,不查询文章数据。 - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .content.cards | display | grid | -| .content.cards | gap | 1.5rem | -| .content.cards | margin-top | 2rem | -| .content.cards | grid-template-columns | repeat(auto-fill, minmax(17rem, 1fr)) | -| .content.cards article.card | background | var(--card) | -| .content.cards article.card | border | 1px solid var(--line) | -| .content.cards article.card | border-radius | var(--radius) | -| .content.cards article.card | padding | 1.6rem 1.7rem | -| .content.cards article.card | box-shadow | var(--shadow) | -| .content.cards article.card | transition | transform .22s ease, box-shadow .22s ease, border-color .22s ease | -| .content.cards article.card | display | flex | -| .content.cards article.card | flex-direction | column | -| .content.cards article.card | gap | .55rem | -| .content.cards article.card:hover | transform | translateY(-6px) | -| .content.cards article.card:hover | box-shadow | var(--shadow-lg) | -| .content.cards article.card:hover | border-color | rgba(79,70,229,.35) | -| .content.cards a.card-link | text-decoration | none | -| .content.cards a.card-link | color | inherit | -| .content.cards a.card-link | display | flex | -| .content.cards a.card-link | flex-direction | column | -| .content.cards a.card-link | gap | .55rem | -| .content.cards a.card-link | height | 100% | -| .content.cards a.card-link:hover | color | inherit | -| .content.cards h2 | font-family | var(--serif) | -| .content.cards h2 | margin | 0 | -| .content.cards h2 | font-size | 1.35rem | -| .content.cards h2 | line-height | 1.35 | -| .content.cards h2 | font-weight | 700 | -| .content.cards h2 | transition | color .18s ease | -| .content.cards a.card-link:hover h2 | color | var(--accent) | -| .card-meta | font-size | .82rem | -| .card-meta | color | var(--faint) | -| .card-meta | letter-spacing | .04em | -| .card-meta | text-transform | uppercase | -| .card-tag | align-self | flex-start | -| .card-tag | font-size | .78rem | -| .card-tag | color | var(--accent) | -| .card-tag | background | rgba(79,70,229,.08) | -| .card-tag | padding | .15rem .65rem | -| .card-tag | border-radius | 999px | -| .card-tag | font-weight | 600 | -| .content.cards p | color | var(--muted) | -| .content.cards p | margin | 0 | -| .content.cards p | font-size | .95rem | -| .content.cards p | flex | 1 | - -## 页脚 - -页脚段保留页面末尾的留白、分隔线和链接外观。页脚若分为多个布局区域,仍应沿组件目录拆分,样式声明不会代替工程结构。 - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| footer.foot | grid-area | foot | -| footer.foot | padding | 1.4rem 2rem | -| footer.foot | border-top | 1px solid var(--line) | -| footer.foot | color | var(--muted) | -| footer.foot | background | #fff | -| footer.foot | font-size | .9rem | -| footer.foot | display | flex | -| footer.foot | justify-content | space-between | -| footer.foot | align-items | center | -| footer.foot | flex-wrap | wrap | -| footer.foot | gap | .5rem | -| ul.foot-nav | list-style | none | -| ul.foot-nav | margin | 0 | -| ul.foot-nav | padding | 0 | -| ul.foot-nav | display | flex | -| ul.foot-nav | gap | 1rem | -| ul.foot-nav | flex-wrap | wrap | -| ul.foot-nav li | margin | 0 | -| ul.foot-nav a | color | var(--muted) | -| ul.foot-nav a | text-decoration | none | -| ul.foot-nav a:hover | color | var(--accent) | - -## 表单 - -表单段保留输入控件、按钮和管理操作的状态样式。字段校验、保存和鉴权属于数据与安全资源;样式只改变已存在控件的外观。 - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .site-form | margin-top | 1.75rem | -| .site-form | max-width | 34rem | -| .site-form | background | var(--card) | -| .site-form | border | 1px solid var(--line) | -| .site-form | border-radius | var(--radius) | -| .site-form | padding | 1.8rem | -| .site-form | box-shadow | var(--shadow) | -| .site-form form | display | grid | -| .site-form form | gap | 1rem | -| .site-form label | display | grid | -| .site-form label | gap | .35rem | -| .site-form label | font-size | .92rem | -| .site-form label | font-weight | 600 | -| .site-form label | color | var(--ink-soft) | -| .site-form input | padding | .65rem .8rem | -| .site-form input | border | 1px solid var(--line) | -| .site-form input | border-radius | 10px | -| .site-form input | font | inherit | -| .site-form input | background | #fdfcfb | -| .site-form input | transition | border-color .15s ease, box-shadow .15s ease | -| .site-form textarea | padding | .65rem .8rem | -| .site-form textarea | border | 1px solid var(--line) | -| .site-form textarea | border-radius | 10px | -| .site-form textarea | font | inherit | -| .site-form textarea | background | #fdfcfb | -| .site-form textarea | transition | border-color .15s ease, box-shadow .15s ease | -| .site-form select | padding | .65rem .8rem | -| .site-form select | border | 1px solid var(--line) | -| .site-form select | border-radius | 10px | -| .site-form select | font | inherit | -| .site-form select | background | #fdfcfb | -| .site-form select | transition | border-color .15s ease, box-shadow .15s ease | -| .site-form input:focus | outline | none | -| .site-form input:focus | border-color | var(--accent) | -| .site-form input:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | -| .site-form textarea:focus | outline | none | -| .site-form textarea:focus | border-color | var(--accent) | -| .site-form textarea:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | -| .site-form select:focus | outline | none | -| .site-form select:focus | border-color | var(--accent) | -| .site-form select:focus | box-shadow | 0 0 0 3px rgba(79,70,229,.12) | -| .site-form input[readonly] | background | #f5f5f4 | -| .site-form input[readonly] | color | var(--muted) | -| .site-form textarea | min-height | 10rem | -| .site-form textarea | resize | vertical | -| .site-form .err | color | #b91c1c | -| .site-form .err | font-size | .85rem | -| .site-form .actions | display | flex | -| .site-form .actions | gap | .75rem | -| .site-form .actions | align-items | center | -| .site-form .actions | flex-wrap | wrap | -| .site-form .actions | padding-top | .25rem | -| .site-form button | background | linear-gradient(120deg, var(--accent), var(--accent-2)) | -| .site-form button | color | var(--accent-ink) | -| .site-form button | border | 0 | -| .site-form button | padding | .6rem 1.3rem | -| .site-form button | border-radius | 999px | -| .site-form button | cursor | pointer | -| .site-form button | font-weight | 600 | -| .site-form button | font-size | .95rem | -| .site-form button | transition | opacity .15s ease, transform .15s ease, box-shadow .15s ease | -| .site-form button:hover | opacity | .92 | -| .site-form button:hover | transform | translateY(-1px) | -| .site-form button:hover | box-shadow | 0 6px 18px rgba(79,70,229,.3) | -| .site-form a.btn | display | inline-block | -| .site-form a.btn | padding | .6rem 1.3rem | -| .site-form a.btn | border-radius | 999px | -| .site-form a.btn | border | 1px solid var(--line) | -| .site-form a.btn | color | var(--ink-soft) | -| .site-form a.btn | text-decoration | none | -| .site-form a.btn | font-weight | 500 | -| .site-form a.btn | font-size | .95rem | -| .site-form .meta | color | var(--muted) | -| .site-form .meta | font-size | .9rem | -| .site-form .admin-list | margin | 0 | -| .site-form .admin-list | padding | 0 | -| .site-form .admin-list | list-style | none | -| .site-form .admin-list | display | grid | -| .site-form .admin-list | gap | .5rem | -| .site-form .admin-list li | background | #fdfcfb | -| .site-form .admin-list li | border | 1px solid var(--line) | -| .site-form .admin-list li | border-radius | 10px | -| .site-form .admin-list li | padding | .6rem .9rem | -| .site-form .admin-list li | display | flex | -| .site-form .admin-list li | justify-content | space-between | -| .site-form .admin-list li | align-items | center | -| .site-form .admin-list li | gap | 1rem | -| .site-form .admin-list a | color | var(--accent) | -| .site-form .admin-list a | text-decoration | none | -| .site-form .admin-list a | font-size | .9rem | - -## 响应式 - -响应式段保留窄屏断点、侧栏流向、内容间距和列表列数。媒体条件仍由原生样式编译器读取,浏览器结果需要实际窄屏验证。 - -| 媒体 | 选择器 | 属性 | 值 | -|------|--------|------|-----| -| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | -| (max-width: 860px) | body.has-sidebar | grid-template-areas | "top" "main" "side" "foot" | -| (max-width: 860px) | aside.side | border-right | 0 | -| (max-width: 860px) | aside.side | border-bottom | 1px solid var(--line) | -| (max-width: 860px) | aside.side | padding | 1rem 2rem | -| (max-width: 860px) | ul.side-nav | flex-direction | row | -| (max-width: 860px) | ul.side-nav | flex-wrap | wrap | -| (max-width: 860px) | main.main | padding | 1.75rem 1.25rem 2.5rem | -| (max-width: 860px) | header.topnav | padding | .75rem 1.25rem | -| (max-width: 860px) | footer.foot | padding | 1.2rem 1.25rem | -| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | -| (max-width: 520px) | ul.nav | flex-wrap | wrap | diff --git a/examples/oa2026-showcase/README.md b/examples/oa2026-showcase/README.md deleted file mode 100755 index 0c43278..0000000 --- a/examples/oa2026-showcase/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# oa2026-showcase - -用于 2026 开源项目大赛作品介绍文档的可运行示例。 - -| 文件 | 展示的能力 | 运行 | -|------|------------|------| -| `add.mq.md` | 叙述统一、粗体即代码、斜体即返回 | `marqdo run examples/oa2026-showcase/add.mq.md` | -| `invoice.mq.md` | 表格即数据、循环、分支、断言 | `marqdo run examples/oa2026-showcase/invoice.mq.md` | -| `calculus.mq.md` | 公式即变量、求导、求根、绘图 | `marqdo run examples/oa2026-showcase/calculus.mq.md` | -| `bell.mq.md` | 量子电路、概率、断言、SVG 派生物 | `marqdo run examples/oa2026-showcase/bell.mq.md` | -| `foreign-node.mq.md` | 外联一次性执行、持久会话、显式传值 | `marqdo run examples/oa2026-showcase/foreign-node.mq.md` | - -## 预期输出 - -```text -$ marqdo run examples/oa2026-showcase/add.mq.md -42 - -$ marqdo run examples/oa2026-showcase/invoice.mq.md -960 -912 -966 -within-cap - -$ marqdo run examples/oa2026-showcase/calculus.mq.md -3*x^2 - 3 -9 -[-1.7320508076, 0, 1.7320508076] -plot-ok - -$ marqdo run examples/oa2026-showcase/foreign-node.mq.md -{华东: 420, 华北: 220, 华南: 230} -华东: 420 -华南: 230 -华北: 220 - -华东: 420 -华北: 300 -华南: 230 - -$ marqdo run examples/oa2026-showcase/bell.mq.md -{00: 0.5, 11: 0.5} -0.5 -0.5 -bell-00-ok -bell-11-ok -bell-draw-ok -``` - -`bell.mq.md` 运行后会生成 `bell-circuit.svg` 与 `bell-probs.svg`; -`calculus.mq.md` 运行后会生成 `calculus-plot.svg`。 diff --git a/examples/oa2026-showcase/add.mq.md b/examples/oa2026-showcase/add.mq.md deleted file mode 100755 index 5cd757d..0000000 --- a/examples/oa2026-showcase/add.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion ---- - -## 加一 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | 必填 | Numeric input advanced or calculated by this example | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -对于输入变量`n`,我们执行 **`n` = `n` + 1**,然后把更新后的值作为结果返回 *`n`*。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -从 41 出发调用「加一」,把结果存进`r`并打印。 - -我们先**r = [计算并保存 r](加一(n=41))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> print text=`r`)**。 diff --git a/examples/oa2026-showcase/bell-circuit.svg b/examples/oa2026-showcase/bell-circuit.svg deleted file mode 100755 index 8f37118..0000000 --- a/examples/oa2026-showcase/bell-circuit.svg +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - -q0 - -q1 -H - - - - \ No newline at end of file diff --git a/examples/oa2026-showcase/bell-probs.svg b/examples/oa2026-showcase/bell-probs.svg deleted file mode 100755 index c56c528..0000000 --- a/examples/oa2026-showcase/bell-probs.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - -10000.50110.50 \ No newline at end of file diff --git a/examples/oa2026-showcase/bell.mq.md b/examples/oa2026-showcase/bell.mq.md deleted file mode 100755 index 925bf24..0000000 --- a/examples/oa2026-showcase/bell.mq.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -markup: occlusion -title: 贝尔态:两个量子比特如何一起回答 -description: 从一条假设开始,搭电路、看概率、画图,并用断言验收。 -import: - quantum: ext/quantum/circuit/index.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -贝尔态:一次可读的量子实验。 - -我们先做一个假设:如果对第一个量子比特施加 Hadamard 门,再用它控制第二个量子比特翻转, -那么测量结果不会出现「一个 0、一个 1」,只会出现「00」或「11」。 - -下面的表不是配置,而是实验步骤本身。读者先读实验设计,再读执行结果。 - -`步骤` = - -| 步骤 | gate | qubits | -|------|------|--------| -| 1 | H | 0 | -| 2 | CX | 0,1 | - -We first **电路 = [Compute 电路](quantum.circuit(qubits=2, steps=`步骤`))** for the next step. -We first **概率 = [Compute 概率](> `电路`.probabilities)** for the next step. - -We now **[Display this step's result](> print text=`概率`)**. - ---- - -我们期待什么?如果假设成立,`概率`应该只在「00」与「11」上有值,而且各占一半。 -先把两个关键概率取出来,读者不必在长映射里找: - -We first **p00 = [00](access(`概率`, "00"))** for the next step. -We first **p11 = [11](access(`概率`, "11"))** for the next step. - -We now **[Display this step's result](> print text=`p00`)**. -We now **[Display this step's result](> print text=`p11`)**. - -下面的断言不是装饰:如果电路写错,或者门接错,运行会直接失败。 - -1. `p00` > 0.49 - We now **[Display this step's result](> print text="bell-00-ok")**. -2. * - We now **[Display this step's result](> print text="bell-00-fail")**. - -1. `p11` > 0.49 - We now **[Display this step's result](> print text="bell-11-ok")**. -2. * - We now **[Display this step's result](> print text="bell-11-fail")**. - ---- - -图不是截图,而是这份文档运行后生成的派生物。电路图和概率图都来自同一个`电路`。 - -We first **_ = [Compute _](> `电路`.draw path="bell-circuit.svg" theme="light")** for the next step. -We first **_ = [Compute _](> `电路`.draw kind="probs" path="bell-probs.svg" theme="light")** for the next step. - -We now **[Display this step's result](> print text="bell-draw-ok")**. diff --git a/examples/oa2026-showcase/calculus-plot.svg b/examples/oa2026-showcase/calculus-plot.svg deleted file mode 100755 index d1f8999..0000000 --- a/examples/oa2026-showcase/calculus-plot.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - -xy-3-2-1123-15-10-5510150 - \ No newline at end of file diff --git a/examples/oa2026-showcase/calculus.mq.md b/examples/oa2026-showcase/calculus.mq.md deleted file mode 100755 index 27616a7..0000000 --- a/examples/oa2026-showcase/calculus.mq.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -markup: occlusion -title: 一份可执行的求导讲义 -description: 公式、求导、求根、求值与绘图,在同一条叙述里完成。 -import: - math: lib/math.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -我们从一条曲线开始。下面这个公式既是排版出来的数学对象, -也是运行时可以直接求导、求根与绘图的`f`。 - -`f` = -$$ -x^3 - 3*x -$$ - -对它求导,得到`df`;再让`df`在 x = 2 处取值,得到切线斜率。 - -We first **df = [Compute df](math.diff(formula=`f`, var="x"))** for the next step. -We first **slope = [Compute slope](math.eval(formula=`df`, var="x", value=2))** for the next step. -We now **[Display this step's result](> print text=`df`)**. -We now **[Display this step's result](> print text=`slope`)**. - -曲线与 x 轴的交点同样可以被机器找出来。这里不需要另写一段脚本。 - -We first **roots = [Compute roots](math.solve(formula=`f`, var="x", min=-3, max=3))** for the next step. -We now **[Display this step's result](> print text=`roots`)**. - -最后把公式画成图。图不是截图,而是本文档运行产生的派生物。 - -We first **_svg = [Compute _svg](math.plot(formula=`f`, var="x", min=-3, max=3, path="calculus-plot.svg"))** for the next step. -We now **[Display this step's result](> print text="plot-ok")**. diff --git a/examples/oa2026-showcase/foreign-node.mq.md b/examples/oa2026-showcase/foreign-node.mq.md deleted file mode 100755 index 31753d9..0000000 --- a/examples/oa2026-showcase/foreign-node.mq.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -markup: occlusion -title: 原生订单分析与 Node Intl 展示边界 -import: - native: ../foreign-native-report/index.mq.md - foreign: lib/foreign.mq.md - table: lib/table.mq.md - result: lib/result.mq.md ---- - -订单分析应先使用已经具备的原生能力。只有本地化货币展示交给 Node Intl;一次性执行和持久会话都是明确的外联边界,文件操作与通用数据处理不需要 Python 或外部读取器。 - -从仓库根目录调用:`marqdo call examples/oa2026-showcase/foreign-node.mq.md main --require-ok --effects process.exec --fs-root . --json`。只需原生分析时,可直接 call 共享模块的 analyze_orders,不需要任何进程授权。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:前后两份原生分析、实际排序结果与一次性/持久格式化结果 | - -成功时 value 的字段如下。先检查最外层 ok,再按字段读取;这里列出的数据都是本轮实际计算或执行得到的值。 - -| value 中的字段 | 值的形态 | 直接含义 | -|---|---|---| -| before | 原生分析记录 | 五笔订单的总额 870、数量 5、平均值 174 与按区域保留的统计行 | -| after | 原生分析记录 | 追加八十元订单后,总额 950、数量 6、平均值约 158.3333;不做展示舍入 | -| initial_ranking | 原生行记录列表 | 首轮按区域总额降序排列;每行保留区域、数量、总额、均值与标准化跨度 | -| updated_ranking | 原生行记录列表 | 更新后的区域总额依次为 420、300、230;排序返回新列表 | -| one_shot | 两个展示文本字段 | 一次性进程返回的 total 与 average,只表示首轮报告的本地化展示 | -| persistent_initial | 两个展示文本字段 | 持久格式器对同一首轮报告得到的 total 与 average,可与一次性结果核对 | -| persistent_updated | 两个展示文本字段 | 持久格式器展示更新后的报告;950.00 与 158.33 是展示文本,不覆盖原生数值 | - - -本例先处理五笔订单:总额为八百七十,随后追加一笔华北的八十元订单,总额变为九百五十。分组、计数、平均值、追加和按区域总额排序全部使用 Marqdo 固有能力;不再在 Node 中维护另一份订单分析程序。共享模块中的 analyze_orders 是唯一的分析实现,其参数与字段表可以直接阅读和调用。 - -外联只承担确实缺失的本地化展示。第一次通过本文件的 format_once 演示标准输入上的 JSON 往返;两次共享 format_summary 分别展示原生修改前后的结果。每次共享调用都在同一内核内建立格式器、复用它格式化平均值并关闭资源,实际生命周期写在对应函数中,而不是把一个句柄藏进跨命令的 JSON 字符串。 - -总额排序也保留在原生流程中:先按 total 升序,再反转得到降序记录。排序不会改变原始订单或报告,每个返回行仍包含区域、订单数和总额。追加发生在 Marqdo 集合中,随后将重新计算出的值拷贝给展示边界,避免外部内核与原生数据各保留一份会悄悄分叉的业务状态。 - -调用需要 process.exec 和 Node,不读写用户文件,也不安装包。先检查共享格式化任务的 ok,再使用 value;一次性 JSON 协议失败则保留原生诊断。成功结果携带真正的原生数据和展示字符串,既能继续被其他函数使用,也能核对展示没有替代数值计算。查看返回结果比只读一条“完成”打印更能证明这一轮执行发生了什么。 - -`订单` = - -| @ | 区域 | 金额 | -|---|---|---| -| 1 | 华东 | 120 | -| 2 | 华东 | 300 | -| 3 | 华南 | 90 | -| 4 | 华南 | 140 | -| 5 | 华北 | 220 | - -We **before = [在原生标准库中完成首轮订单分析](native.analyze_orders(orders=`订单`, region_key="区域", amount_key="金额"))** and -**initial_ranking = [保留首轮按区域总额降序的原生行记录](table.reverse(list=table.sort_by(list=access(before, "regions"), key="total")))** and -**one_shot = [只把首轮报告的展示交给一次性进程](format_once(report=`before`))** and -**initial = [用共享持久内核流程展示同一份原生结果](native.format_summary(report=`before`, locale="zh-CN"))**。 -1. not access(`initial`, "ok") - 返回*initial*,保留真实运行失败。 - -`追加` = - -| 区域 | 金额 | -|---|---| -| 华北 | 80 | - -We **orders = [在原生集合中追加新订单](table.append(list=`订单`, item=`追加`))** and -**after = [用同一份原生实现重新计算完整报告](native.analyze_orders(orders=`orders`, region_key="区域", amount_key="金额"))** and -**updated_ranking = [在原生集合中保留更新后的降序记录](table.reverse(list=table.sort_by(list=access(after, "regions"), key="total")))** and -**updated = [把更新后的原生结果交给展示边界](native.format_summary(report=`after`, locale="zh-CN"))**。 -1. not access(`updated`, "ok") - 返回*updated*,保留持久内核的失败出口。 -We **persistent_initial = [保留首轮实际格式化文本](access(initial, "value"))** and **persistent_updated = [保留更新后的实际展示文本](access(updated, "value"))**。 - -`观察` = - -| before | after | initial_ranking | updated_ranking | one_shot | persistent_initial | persistent_updated | -|---|---|---|---|---|---|---| -| `before` | `after` | `initial_ranking` | `updated_ranking` | `one_shot` | `persistent_initial` | `persistent_updated` | - -完成原生分析与明确的展示外联后,我们返回*[本次实际观察到的数据与结果](result.ok(value=`观察`))*。 - -## format_once - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| report | map | required | 原生分析结果,包含 total 与 average 数值 | -| locale | text | "zh-CN" | Node Intl 使用的展示语言区域 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 直接返回 total/average 本地化文本;子进程或 JSON 失败保留原生诊断 | - -使用 `report` 和 `locale`="zh-CN" 补足本地化货币展示。一次性外联只接收已经计算好的总额与平均值,不分组、不排序、不修改订单。传入数据由 Marqdo 的 input 通道编码为 JSON;Node 从标准输入流接收它,不读取任何路径,也不额外生成文件。 - -代码围栏明确写出进程如何消费输入、建立 Intl 格式器以及输出唯一的 JSON 记录。标准输出只承载这个协议值,诊断保留在错误通道;混入其他打印会导致 JSON 解析失败,而不是被当作部分成功。这里选择人民币展示,不声称进行汇率换算或货币精度计算。 - -调用需要 process.exec 与已安装的 Node,超时为五秒。foreign.call 在进程失败或输出不是合法 JSON 时给出原生诊断,因此本函数的成功值就是格式化记录,不再套一个假造的通过标记。这个一次性子进程结束后没有可复用状态;持久会话的创建、两次求值和关闭由共享原生报表手册中的 format_summary 展示。 - -`输入` = - -| report | locale | -|---|---| -| `report` | `locale` | - -`格式化代码` = -```node -let raw = ""; -process.stdin.setEncoding("utf8"); -process.stdin.on("data", chunk => { raw += chunk; }); -process.stdin.on("end", () => { - const input = JSON.parse(raw); - const money = new Intl.NumberFormat(input.locale, {style: "currency", currency: "CNY"}); - console.log(JSON.stringify({total: money.format(input.report.total), average: money.format(input.report.average)})); -}); -``` - -接收完整输入后,我们返回*[执行有界的一次性展示边界并解析真实 JSON 返回](foreign.call(code=`格式化代码`, input=`输入`, timeout=5))*。 diff --git a/examples/oa2026-showcase/invoice.mq.md b/examples/oa2026-showcase/invoice.mq.md deleted file mode 100755 index 741bfc1..0000000 --- a/examples/oa2026-showcase/invoice.mq.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -markup: occlusion -title: 一张订单,一份可执行的业务说明 -description: 叙述、数据、计算与断言共享同一个 .mq.md 源文件。 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -这份文档不是代码旁边的说明,也不是说明里贴的代码。下表既是给人读的订单, -也是运行时直接使用的记录集合;下面的句子既解释业务规则,也参与计算。 - -`订单` = - -| @ | 客户 | 单价 | 数量 | 提前天数 | -|---|------|------|------|----------| -| 1 | 青山实验室 | 120 | 3 | 10 | -| 2 | 远望中心 | 80 | 5 | 4 | -| 3 | 星尘工坊 | 200 | 1 | 14 | - -逐行把「单价 × 数量」累加进`小计`。读者看到的是清单,机器执行的是同一张表。 - -We first **小计 = 0** for the next step. -- [行](遍历 订单 为 行) - We first **小计 = (`小计` + ([单价](access(`行`, "单价")) * [数量](access(`行`, "数量"))))** for the next step. - -业务约定写在叙述里:提前不少于七天,整单按九五折;否则原价。 -本单最早提前 14 天。 - -We first **最早提前 = 14** for the next step. -1. `最早提前` >= 7 - We first **折后 = ((`小计` * 95) / 100)** for the next step. -2. * - We first **折后 = `小计`** for the next step. - -把结果、依据和判断一起写进文档。下面的断言如果跑不通,文档本身就是错的。 - -We first **含税 = ((`折后` * 106) / 100)** for the next step. -We now **[Display this step's result](> print text=`小计`)**. -We now **[Display this step's result](> print text=`折后`)**. -We now **[Display this step's result](> print text=`含税`)**. - -1. `含税` < 10000 - We now **[Display this step's result](> print text="within-cap")**. -2. * - We now **[Display this step's result](> print text="over-cap")**. diff --git a/examples/procurement/README.md b/examples/procurement/README.md deleted file mode 100644 index 2d4a96d..0000000 --- a/examples/procurement/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Procurement skill · reproducible demo - -This is a **local simulation** in one callable `.mq.md` source. It has no external purchase side effects and does not require an LLM API key. - -## What it demonstrates - -- A `¥600` spending limit with a caller-supplied balance. -- An active supplier `SUP_JN`, quoting `¥36` for a sample bearing. -- Eight units total `¥288` with an estimated seven-day delivery. -- Supplier approval, quote comparison, budget check and local work-order generation as direct Marqdo function calls. -- Unconnected capabilities (live quotes, real work orders and receipts, negotiation and supplier switching) explicitly labeled as stubs. - -## Run from the repository root - -```bash -marqdo check examples/procurement/index.mq.md --narrative-ratio -marqdo call examples/procurement/index.mq.md 查询采购商 "采购商状态='正常'" --json -marqdo call examples/procurement/index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=8 有效秒数=300 --json -marqdo call examples/procurement/index.mq.md 查询余额 已花费=120 --json -marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json -marqdo call examples/procurement/index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=360 交付要求天数=7 --effects time.read,process.control --json -marqdo call examples/procurement/index.mq.md 查询采购商价格 "采购商标识符='SUP_YY'" 数量=8 --json -``` - -## Interpret the result - -The return from `向采购商发工单` is a **business-level** `ok/value/error` map. In the low-spend case it should contain `ok=True`, `工单金额=288` and `状态="本地模拟,未发送"`. When already spent reaches `360`, the function should return `ok=False` and a budget rejection reason. The CLI's outer JSON call envelope is separate from this nested domain result. - -These are **expected outcomes**, not independently verified terminal captures. The workflow [procurement-example.yml](../../.github/workflows/procurement-example.yml) exercises the commands using the released Linux CLI. - -## Inspect in View - -```bash -marqdo view examples/procurement --no-open -``` - -Open `向采购商发工单` and expand the annotations for `查询采购商价格`, `查询余额`, and `剩余额度`. Merely reading and expanding details does not execute side effects. - -## Production integration boundaries - -The real supplier quote API, persistent authoritative ledger, concurrent budget reservation, ERP transaction, order receipt, negotiation, and supplier switching are **not connected**. Before any real purchase, integrate server-side budget reservations, quote signatures/evidence, idempotent transactions, durable logs and an explicit human authorization policy. - -The GIF-like animated [SVG storyboard](../../assets/marketing/procurement-flow.svg) and the [View-inspired concept](../../assets/marketing/procurement-view-concept.svg) are illustrations, not instrumented evidence. \ No newline at end of file diff --git a/examples/procurement/index.mq.md b/examples/procurement/index.mq.md deleted file mode 100644 index 531baef..0000000 --- a/examples/procurement/index.mq.md +++ /dev/null @@ -1,469 +0,0 @@ ---- -markup: occlusion -title: 采购智能体 -version: v1.1-demo -description: 600 元采购预算下的供应商筛选、示例询价、预算审核和模拟工单;真实采购接口尚未接通。 -import: - table: lib/table.mq.md - time: lib/time.mq.md ---- - -# main - -这是一份可阅读、可调用的采购工作手册,也是一份开发中的采购 SKILL。 -它把采购制度、供应商知识、模拟数据与操作工具放在同一个 Marqdo 文档里。 -当前版本只支持本地模拟采购,不会向真实供应商发消息、扣款或确认采购。 - -采购目标是在最高 600 元 的预算内,从状态正常、报价可接受且预计交期满足要求的供应商中, -选择总成本最低的方案。价格相同时,应优先考虑交付可靠性,并保留供老板决策的理由。 -所有费用均以人民币元计算;样例不包含税费、运费、折扣及多币种换算。 - -采购工具不是自动取得授权的交易权限。智能体可解释和比较工具返回的数据, -但必须遵守下面的门禁;真实下单、持久化预算占用、实时报价和最终回执都需要后续接入。 - -| 业务能力 | 本地状态 | 可信边界 | -|---|---|---| -| 查询采购商 | 已接通示例名录 | 只反映下文静态目录,不是在线主数据 | -| 查询采购商价格 | 示例数据 | 价格与交期为测试样例,不是实时承诺 | -| 查询余额 | 已接通计算逻辑 | `已花费` 由调用方提供,尚未读取持久账本 | -| 向采购商发工单 | 本地模拟 | 会再次检查供应商、报价和预算,不真正发送 | -| 检查工单 | 模拟回复 | 不能验证真实工单,也不会确认真实下单 | -| 讲价 | 未接通,保留示例请求 | 不代表供应商已收到议价 | -| 更换采购商 | 未接通,保留示例请求 | 不代表已经切换或重新询价 | - -采购工作原则(阅读说明,非函数) - -这里的工作原则是叙述知识,供智能体阅读;不是可调用函数。 -实际调用的函数均在下面的二级标题中定义。需要让规则成为真正的技术门禁时, -必须在相应函数中重复检查,不能认为写在本节的文字会自动执行。 - -| 阶段 | 工具 | 通过条件 | 需要保留的证据 | -|---|---|---|---| -| 1. 准入 | 查询采购商 | 只考虑状态为“正常”的供应商 | 名录快照、筛选结果 | -| 2. 比价 | 查询采购商价格 | 对候选逐家询价,比较相同商品、数量、交期与总额 | 各家报价及数据来源 | -| 3. 预算 | 查询余额 | 每次拟发单前重新查询;剩余额度不小于本单总额 | 已花费、可用余额、本单金额 | -| 4. 工单 | 向采购商发工单 | 准入、报价、交期和预算校验同时通过 | 模拟工单和校验摘要 | -| 5. 回执 | 检查工单 | 只有真实回执和真实下单接口接通后才能确认交易 | 回执、处置决定 | - -不可突破的边界是:黑名单供应商不询价、不发单;已暂停供应商也不参与比价。 -没有报价不得发单,超预算不得发单;回执不清楚时不能擅自认为已经下单。 -如果某家缺货,可以考虑另询一家;议价成功之前,不能用目标价格充当已确认价格。 - -示例演练。 采购 8 件深沟球轴承,假设本轮已花费 120 元、交付要求为 7 天。 -静态目录里,正常供应商的示例单价为江南配件 36 元、粤海精工 39 元、华东金属 42 元。 -在样例条件下江南配件报价总额为 288 元,余额为 480 元,能够生成模拟工单。 -北岭工贸虽然报价更低,但已经暂停;远洋贸易属于黑名单,两者都必须排除。 - -从本文件所在目录调用,建议使用结构化输出,以便把每次调用的入参和返回值另行归档: - -```sh -marqdo call index.mq.md 查询采购商 "采购商状态='正常'" --json -marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" "商品='深沟球轴承'" 数量=8 --json -marqdo call index.mq.md 查询余额 已花费=120 --json -marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 交付要求天数=7 --effects time.read,process.control --json -marqdo call index.mq.md 检查工单 "工单号='MOCK-WO-示例'" "模拟回复='缺货'" --json -``` - -以上第五条是独立的回执模拟,不是第四条工单的真实回执。 -将来接入真实系统以后,应使用实际返回的工单号,并从系统查询实际状态。 -示例中的 `--json` 是输出格式,不会自动建立审计账本;目前由调用方保存记录。 - - -维护约定:以后真正接通报价、ERP、账本与议价通道时,务必把“模拟”状态替换为真实的失败可恢复结果, -并增加后端校验、并发预算占用、幂等与日志持久化。在真实验收之前,不得修改文档宣称已经完成交易。 - -建议使用以下命令对本文件做实际检查;这些命令是待在已安装 Marqdo 的工程环境中执行的验收步骤, -不是本文件声称已经通过的测试结果: - -```sh -marqdo check index.mq.md --narrative-ratio -marqdo call index.mq.md 查询采购商 "采购商状态='正常'" --json -marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_YY'" 数量=8 --json -marqdo call index.mq.md 查询余额 已花费=550 --json -marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=550 --effects time.read,process.control --json -marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_BL'" 数量=8 单价=30 已花费=0 --effects time.read,process.control --json -``` - - ---- - -## 查询采购商 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 采购商状态 | text | "全部" | 按状态筛选;可选“全部 / 正常 / 已暂停 / 黑名单” | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 供应商记录列表;名称、标识符、状态、老板的评价、采购商的喜好;无匹配则为空列表 | - -根据调用者传入的`采购商状态`="全部"筛选供应商目录。这份目录是可执行的本地样例, -将来接入供应商主数据后,应在这里替换数据来源,保留相同的记录字段和筛选契约。 - -“全部”用于名录展示和审计;采购决策必须显式传入“正常”, -不能因为全部名录里列出了黑名单供应商,就把它们作为可采购对象。 -这里的列表包含带首列“行”的 GFM 表格,因此每行都是一条可检索的记录。 - -`采购商名录` = - -| 行 | 名称 | 标识符 | 状态 | 老板的评价 | 采购商的喜好 | -|---|---|---|---|---|---| -| 1 | 华东金属 | SUP_HD | 正常 | 交付稳定,价格较高 | 大批量,账期短 | -| 2 | 江南配件 | SUP_JN | 正常 | 价格较低,偶有拖期 | 小批量,快单 | -| 3 | 北岭工贸 | SUP_BL | 已暂停 | 曾出现质检不合格 | 定制订单 | -| 4 | 粤海精工 | SUP_YH | 正常 | 老合作伙伴,可沟通价格 | 长期协议,年框 | -| 5 | 远洋贸易 | SUP_YY | 黑名单 | 曾收款后失联 | 无 | - -当筛选状态为“全部”时,提供完整目录供查看; -这是查询目录,不代表所有供应商均允许交易。 - -1. `采购商状态` == "全部" - 我们返回*[返回完整示例名录](`采购商名录`)*。 - -其他状态使用表库的相等过滤,不直接手写循环。 - -我们返回*[按状态筛选采购商](table.where(list=`采购商名录`, key="状态", value=`采购商状态`))*。 - -## 查询采购商价格 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 采购商标识符 | text | 必填 | 需要询价的供应商标识,例如 SUP_JN | -| 商品 | text | "深沟球轴承" | 本次询价的品名;样例目录目前只有这一种商品 | -| 数量 | number | 1 | 采购件数,必须为正整数 | -| 有效秒数 | number | 300 | 预留给真实报价接口的有效期参数;模拟价格不产生有效报价凭证 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 示例报价 map,含商品、数量、单价、总额、交期、来源及真实性标记;不允许询价或无数据时为 None | - -使用`采购商标识符`查询`商品`="深沟球轴承"的示例价格,按`数量`=1计算总额。 -`有效秒数`=300只是将来真实询价服务的预留输入;它不会让静态价格自动变成实时价格。 -一个报价必须同时说明价格、来源及是否允许真实交易,不能仅凭生成时间认定报价有效。 - -先检查数量和保留的有效期是否合理。无效输入不应返回看似正常的价格。 - -1. `数量` <= 0 or int(`数量`) != `数量` or `有效秒数` <= 0 - 我们返回*[数量或有效期不合法,拒绝询价](None)*。 - -询价前重新从准入目录检查供应商状态。即使示例价格表里包含已暂停或黑名单商户, -也不能将它们的价格返回给采购智能体,防止“最低价优先”覆盖供应商准入规则。 - -我们先**正常名录 = [只读取可参与询价的供应商](查询采购商(采购商状态="正常"))**, -再**候选 = [匹配当前供应商标识](table.where(list=`正常名录`, key="标识符", value=`采购商标识符`))**。 - -1. table.len(xs=`候选`) == 0 - 我们返回*[供应商不存在或当前不可询价](None)*。 - -以下表格是用于开发与验收的静态价格及交期样例。所有行都不是实时供应商承诺。 -接入线上报价系统时,只替换“取得原始报价”的部分,并保留准入、总额和来源检查。 - -`示例价格目录` = - -| 行 | 采购商标识符 | 商品 | 报价单价 | 预计交付天数 | -|---|---|---|---|---| -| 1 | SUP_HD | 深沟球轴承 | 42 | 3 | -| 2 | SUP_JN | 深沟球轴承 | 36 | 7 | -| 3 | SUP_BL | 深沟球轴承 | 30 | 2 | -| 4 | SUP_YH | 深沟球轴承 | 39 | 5 | -| 5 | SUP_YY | 深沟球轴承 | 20 | 1 | - -取得单家供应商的目录条目,再匹配商品,避免将别的商品的价格用于本次采购。 -我们先**报价目录 = [供应商实时报价接口未接通,暂用本地示例价格](`示例价格目录`)**, -让没有接通的服务状态在可检索标签中明确可见。 - -我们再**同商报价 = [从示例目录查找指定供应商](table.where(list=`报价目录`, key="采购商标识符", value=`采购商标识符`))**, -再**命中报价 = [限定本次询价商品](table.where(list=`同商报价`, key="商品", value=`商品`))**。 - -1. table.len(xs=`命中报价`) == 0 - 我们返回*[没有这件商品的示例报价](None)*。 - -从唯一一条样例记录取得单价和交期,然后计算相同数量的总金额。 -因为目前没有真实接口,返回的数据必须永久带有“模拟”标记,直到服务真正接入并验证。 - -我们先**报价条目 = [取出命中的示例记录](table.first(list=`命中报价`))**, -然后**单价 = [读取单件报价](access(`报价条目`, "报价单价"))**, -以及**交付周期 = [读取样例交付天数](access(`报价条目`, "预计交付天数"))**。 -本次报价的**报价总额 = [单价乘以购买数量](`单价` * `数量`)**。 - -`报价` = - -| 采购商标识符 | 商品 | 单价 | 数量 | 报价总额 | 预计交付天数 | 报价来源 | 报价时间 | 报价生效至 | 可真实下单 | -|---|---|---|---|---|---|---|---|---|---| -| `采购商标识符` | `商品` | `单价` | `数量` | `报价总额` | `交付周期` | 示例目录(未接实时接口) | None | None | False | - -我们返回*[这条可测试、不可用于真实下单的报价](`报价`)*, -供后续比价和本地模拟使用;真实业务必须另外验证供应商提供的报价凭证。 - -## 查询余额 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 已花费 | number | 0 | 调用方已确认的本轮占用金额;不得为负,模拟运行期间不自动累加 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 预算 map,含最高预算、已花费、可用余额、还能下单;负数输入时为 None | - -预算上限固定为 600 元。输入`已花费`=0代表一轮新的采购演练; -后续每次准备发单时,必须传入已经确认或占用的实际累计金额。 -当前没有持久账本,这个数字由调用方维护;工具不会自动记账,也不能防止两个独立进程并发超支。 - -当已花费为负数时,拒绝计算,避免用负债务造出虚假的可用余额。 - -1. `已花费` < 0 - 我们返回*[累计支出不允许为负数](None)*。 - -这次计算先**最高预算 = [读取采购预算上限](600)**, -再**可用余额 = [计算还未占用的额度](`最高预算` - `已花费`)**。 -如果余额已经为零或更少,返回中应明确写“不能”,防止后续误发工单。 - -1. `可用余额` > 0 - `余额` = - - | 最高预算 | 已花费 | 可用余额 | 还能下单 | - |---|---|---|---| - | `最高预算` | `已花费` | `可用余额` | 可以 | - - 我们返回*[预算仍有剩余额度](`余额`)*。 - -`余额` = - -| 最高预算 | 已花费 | 可用余额 | 还能下单 | -|---|---|---|---| -| `最高预算` | `已花费` | `可用余额` | 不能 | - -我们返回*[预算已用尽或已超支](`余额`)*。 - -## 向采购商发工单 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 采购商标识符 | text | 必填 | 接受模拟工单的供应商标识 | -| 数量 | number | 必填 | 拟采购件数,必须为正整数 | -| 单价 | number | 必填 | 本次拟采用的单价,必须与本次重新取得的示例报价一致 | -| 已花费 | number | 必填 | 拟发单时的累计已占用金额;不得遗漏或默认为零 | -| 商品 | text | "深沟球轴承" | 拟采购商品 | -| 交付要求天数 | number | 7 | 最晚可接受交期;以自然日计,本地样例仅作演示 | -| 采购文字 | text | "按标准规格采购" | 本单采购要求与备注 | -| 休息秒数 | number | 0 | 仅用于测试等待效应的模拟延迟;并非真实供应商回执窗口 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 含 ok 状态的结构化结果;成功时 value 为模拟工单,失败时 error 为原因;不代表已真实发送 | - -根据调用者提供的`采购商标识符`、`数量`、`单价`、`已花费`, -以及`商品`="深沟球轴承"、`交付要求天数`=7、`采购文字`="按标准规格采购"、`休息秒数`=0 -尝试创建一份本地模拟工单。这是整个采购流程的最后一道可执行防线; -即使智能体漏做了前面的检查,本函数仍会再次询价并调用查询余额。 - -单次函数调用可以拒绝非法金额,但不能证明调用者传入的已花费真实,也没有跨调用的报价令牌或持久预算锁。 -后续要接通真实 ERP 时,必须增加服务端事务、幂等键、报价凭证核验和权威预算余额。 -在这些能力上线之前,此函数只返回本地模拟数据,不允许被当成真实采购指令。 - -基础输入必须合理。金额或天数为负、数量非正整数、等待时间过长都应在本阶段直接拒绝。 -使用内部失败助手统一构造 `ok=False` 的回执,避免产生半成品工单。 - -1. `数量` <= 0 or int(`数量`) != `数量` or `单价` <= 0 or `已花费` < 0 or `交付要求天数` < 0 or `休息秒数` < 0 or `休息秒数` > 300 - 我们返回*[拒绝无效工单输入](_拒绝模拟工单(原因="数量、单价、金额或期限参数不合法"))*。 - -第一道业务门禁重新读取正常供应商,不信任调用方单独提供的标识符。 - -我们先**正常商户 = [从本地名录获取正常供应商](查询采购商(采购商状态="正常"))**, -再**供应商命中 = [核实供应商仍然处于正常状态](table.where(list=`正常商户`, key="标识符", value=`采购商标识符`))**。 - -1. table.len(xs=`供应商命中`) == 0 - 我们返回*[拒绝黑名单、暂停或不存在的供应商](_拒绝模拟工单(原因="供应商未通过准入审核"))*。 - -第二道门禁在本次调用中重新询价,既避免凭记忆下单,也防止调用方任意填写低价。 -但此阶段重新拿到的是静态示例价格,并不是供应商确认的线上报价。 - -我们先**报价 = [重新查本次商品与数量的模拟报价](查询采购商价格(采购商标识符=`采购商标识符`, 商品=`商品`, 数量=`数量`, 有效秒数=300))**。 - -1. `报价` == None - 我们返回*[未查到报价,禁止生成工单](_拒绝模拟工单(原因="此供应商没有可用的示例报价"))*。 - -报价存在后,核对输入价格与示例单价,以及交货要求;价格不一致时不允许自己改写报价。 - -我们先**询得单价 = [取本次询价单价](access(`报价`, "单价"))**, -再**预计交期 = [取示例预计交期](access(`报价`, "预计交付天数"))**, -同时**本单金额 = [取示例报价总额](access(`报价`, "报价总额"))**。 - -1. `单价` != `询得单价` - 我们返回*[价格未经本次询价确认,拒绝工单](_拒绝模拟工单(原因="拟采用单价与本次示例报价不一致"))*。 - -1. `预计交期` > `交付要求天数` - 我们返回*[预计交期不能满足要求,拒绝工单](_拒绝模拟工单(原因="示例交付周期超过可接受期限"))*。 - -第三道门禁必须在建立工单前调用查询余额,并使用本次输入的累计已花费金额。 -发工单不是先保存成功再补看余额;条件不成立时立即返回拒绝结果。 - -我们先**预算 = [在拟发单时重新查询预算](查询余额(已花费=`已花费`))**。 - -1. `预算` == None - 我们返回*[累计金额不合法,拒绝工单](_拒绝模拟工单(原因="本轮累计支出无效"))*。 - -我们再**剩余额度 = [读取可用于本单的余额](access(`预算`, "可用余额"))**。 - -1. `剩余额度` < `本单金额` - 我们返回*[本单超过剩余额度,拒绝工单](_拒绝模拟工单(原因="采购金额超过 600 元总预算的剩余额度"))*。 - -全部检查通过后才生成可追溯的模拟编号。编号只服务本地演练, -同一秒内的多个调用可能产生相同编号,不能拿它代替生产级幂等键。 - -我们先**当前秒 = [读取本地模拟工单生成时间](time.now_unix())**, -再**模拟工单号 = [生成带模拟前缀的工单号]("MOCK-WO-" + str(`当前秒`) + "-" + `采购商标识符` + "-" + str(`数量`))**。 -同时**预计已占用 = [计算此笔模拟工单对应的累计占用](`已花费` + `本单金额`)**, -该数值只用于展示,不会写入持久账本。 - -只有显式要求演练延迟时才挂起。这种等待不会触发真实发送或获取真实回执。 - -1. `休息秒数` > 0 - 我们先**等待毫秒 = [将模拟等待秒数换算为毫秒](`休息秒数` * 1000)**, - 再**[模拟等待回执窗口](time.sleep_ms(ms=`等待毫秒`))**。 - -`工单` = - -| 工单号 | 采购商标识符 | 商品 | 数量 | 单价 | 工单金额 | 采购文字 | 已花费 | 本单后预计已占用 | 模拟交期天数 | 报价来源 | 状态 | -|---|---|---|---|---|---|---|---|---|---|---|---| -| `模拟工单号` | `采购商标识符` | `商品` | `数量` | `询得单价` | `本单金额` | `采购文字` | `已花费` | `预计已占用` | `预计交期` | 示例目录(未接实时接口) | 本地模拟,未发送 | - -这一记录给智能体下一步检查模拟回执使用;它没有持久保存到任何订单系统, -也没有自动修改预算余额。把`工单`作为 value,连同成功标记一起返回。 - -`成功回执` = - -| ok | value | error | -|---|---|---| -| True | `工单` | None | - -我们返回*[模拟校验通过,但真实发单尚未接通](`成功回执`)*。 - -## 检查工单 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 工单号 | text | 必填 | 待演练的工单编号;本地没有可核验的持久工单仓库 | -| 模拟回复 | text | "不清楚" | 可选:有货 / 缺货 / 不清楚;默认采取保守处置 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 工单号、回执、下一步、理由、来源;任何结果均不等于真实下单完成 | - -读取调用方提供的`工单号`和`模拟回复`="不清楚",生成一份仅供开发的回执解释。 -本工具没有向供应商查询工单状态,也不核对该编号是否真实存在。 -真实环境必须改为用工单系统查回执、核对供应商身份,再按订单状态机处理。 - -有货并不代表已经付款或下单。即使示例回执说“有货”, -当前可以做的也只是标记“模拟可推进”;在真实交易接口接通前必须停止。 - -1. `模拟回复` == "有货" - `结论` = - - | 工单号 | 回执 | 下一步 | 理由 | 数据来源 | - |---|---|---|---|---| - | `工单号` | 有货 | 待真实下单接口接通 | 模拟有货;不得视作已采购或已付款 | 模拟回复 | - - 我们返回*[保留模拟有货的回执结果](`结论`)*。 - -如果模拟回复表示缺货,就停止当前候选,重新筛选其他正常供应商并比价。 -更换采购商工具目前也未接通,所以不能把“准备更换”写成“更换成功”。 - -1. `模拟回复` == "缺货" - `结论` = - - | 工单号 | 回执 | 下一步 | 理由 | 数据来源 | - |---|---|---|---|---| - | `工单号` | 缺货 | 更换采购商(待接通) | 模拟缺货,应返回供应商选择和报价阶段 | 模拟回复 | - - 我们返回*[建议重新筛选采购商](`结论`)*。 - -对于不清楚或不属于约定值的回复,采取更保守的处置:不自动采购, -只生成建议协商的下一步,避免把未定义状态解释为成功。 - -`结论` = - -| 工单号 | 回执 | 下一步 | 理由 | 数据来源 | -|---|---|---|---|---| -| `工单号` | 不清楚 | 讲价或人工核实(待接通) | 回执没有提供足以真实下单的证据 | 模拟回复 | - -我们返回*[回执不明确,停止自动确认](`结论`)*。 - -## 讲价 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 工单号 | text | 必填 | 需要发起议价请求的模拟工单号 | -| 目标单价 | number | 必填 | 期望价格;必须为正数,不代表采购商已经接受 | -| 理由 | text | "报价高于同期均价" | 给供应商看的议价依据,未来接通通道时使用 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 示例议价请求 map;目标单价不合法时为 None | - -针对`工单号`提出`目标单价`,使用`理由`="报价高于同期均价"解释期望。 -议价通道当前尚未接通,这里刻意保留一条可执行的示例请求, -方便开发者以后替换成真实消息投递和回执解析。 - -不能把期望价改写成询得单价,也不能认为发出模拟请求就获得了供应商同意。 -真实成交价必须依赖新的、可验证的报价凭证,再重新执行预算校验。 - -1. `目标单价` <= 0 - 我们返回*[目标价格必须大于零](None)*。 - -`示例议价请求` = - -| 工单号 | 目标单价 | 理由 | 状态 | 通道 | -|---|---|---|---|---| -| `工单号` | `目标单价` | `理由` | 未接通(仅保留模拟请求) | 示例议价通道 | - -我们返回*[保留议价意图,等待接通真实通道](`示例议价请求`)*。 - -## 更换采购商 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 原采购商标识符 | text | 必填 | 已经不再适合本单的供应商标识 | -| 商品 | text | "深沟球轴承" | 要继续寻找供应商的采购品名 | -| 原因 | text | "原供应商缺货" | 记录更换的业务原因 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原供应商、商品、原因、状态与建议动作;不代表真正更换成功 | - -对于`原采购商标识符`、`商品`="深沟球轴承"和`原因`="原供应商缺货", -先保留更换意图,下一步应回到正常供应商名录并重新询价。 -目前没有接入供应商切换系统,不能直接把固定的候选名单解释成已经选定的下一家。 - -后续接通真实通道时,应使用同一份供应商准入规则,排除当前被放弃的供应商, -重新比较报价、交期、预算,并重新生成工单;绝不能直接复用上一家供应商的报价。 - -`示例更换请求` = - -| 原采购商标识符 | 商品 | 原因 | 状态 | 建议动作 | -|---|---|---|---|---| -| `原采购商标识符` | `商品` | `原因` | 未接通(仅保留模拟请求) | 重新查询正常供应商并逐家询价 | - -我们返回*[供应商切换通道未接通,保存模拟更换请求](`示例更换请求`)*。 - -## _拒绝模拟工单 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 原因 | text | 必填 | 预算、供应商、报价、交期或输入不合格的具体原因 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 统一的失败记录,ok=False、value=None、error=失败原因 | - -内部辅助函数使用`原因`说明模拟工单没有通过哪一项门禁。 -所有拒绝出口都必须返回同样形态的结构化结果,便于智能体在读取 `ok` 之后决定是否继续。 -这里不抛异常、不发送工单,也不通过一个虚假的工单号掩盖失败。 - -`失败回执` = - -| ok | value | error | -|---|---|---| -| False | None | `原因` | - -我们返回*[用于拒绝发单的统一失败回执](`失败回执`)*。 \ No newline at end of file diff --git a/examples/procurement/验收与接入说明.md b/examples/procurement/验收与接入说明.md deleted file mode 100644 index 9a3b5f8..0000000 --- a/examples/procurement/验收与接入说明.md +++ /dev/null @@ -1,48 +0,0 @@ -# 采购智能体:验收与真实接口接入说明 - -## 工程放置方式 - -建议把 `index.mq.md` 放入 Marqdo 仓库的 `examples/procurement/`,或可以解析 `lib/table.mq.md` 和 `lib/time.mq.md` 的现有项目中。`import` 中沿用仓库根目录提供的公开标准库。下面命令假设从 `index.mq.md` 所在目录执行。 - -此文件目前是**采购业务 SKILL + 本地模拟工具集合**,不是可执行的真实采购交易系统。它仍需要负责决策的 Agent 调度各工具,并保存独立调用日志。 - -## 建议执行的验收用例(待运行) - -| 场景 | 命令 | 预期 | -|---|---|---| -| 正常供应商 | `marqdo call index.mq.md 查询采购商 "采购商状态='正常'" --json` | 只返回 SUP_HD、SUP_JN、SUP_YH | -| 黑名单询价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_YY'" 数量=8 --json` | 返回 None | -| 暂停供应商询价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_BL'" 数量=8 --json` | 返回 None | -| 正常报价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=8 --json` | 示例单价 36、总额 288、交期 7 天、可真实下单 False | -| 零数量询价 | `marqdo call index.mq.md 查询采购商价格 "采购商标识符='SUP_JN'" 数量=0 --json` | 返回 None | -| 正常预算 | `marqdo call index.mq.md 查询余额 已花费=120 --json` | 可用余额 480 | -| 用尽预算 | `marqdo call index.mq.md 查询余额 已花费=600 --json` | 余额 0、不能下单 | -| 非法预算 | `marqdo call index.mq.md 查询余额 已花费=-1 --json` | 返回 None | -| 模拟工单 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=120 --effects time.read,process.control --json` | ok=True、状态为本地模拟未发送、模拟本单后预计占用 408 | -| 超预算 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=350 --effects time.read,process.control --json` | ok=False,不生成工单 | -| 伪低价 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=35 已花费=0 --effects time.read,process.control --json` | ok=False,不允许自行篡改示例报价 | -| 交期不足 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_JN'" 数量=8 单价=36 已花费=0 交付要求天数=5 --effects time.read,process.control --json` | ok=False,因为样例交期 7 天 | -| 更快供应商 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_YH'" 数量=8 单价=39 已花费=0 交付要求天数=5 --effects time.read,process.control --json` | ok=True,仅模拟 | -| 无效供应商 | `marqdo call index.mq.md 向采购商发工单 "采购商标识符='SUP_YY'" 数量=8 单价=20 已花费=0 --effects time.read,process.control --json` | ok=False | -| 缺货回执 | `marqdo call index.mq.md 检查工单 "工单号='MOCK-WO-test'" "模拟回复='缺货'" --json` | 下一步为更换采购商(未接通) | -| 不明确回执 | `marqdo call index.mq.md 检查工单 "工单号='MOCK-WO-test'" --json` | 不认定下单成功,转人工或议价 | -| 议价占位 | `marqdo call index.mq.md 讲价 "工单号='MOCK-WO-test'" 目标单价=34 --json` | 返回“未接通”的示例议价请求 | -| 切换占位 | `marqdo call index.mq.md 更换采购商 "原采购商标识符='SUP_JN'" --json` | 返回“未接通”的示例切换请求 | - -建议随后执行 `marqdo check index.mq.md --narrative-ratio`,并在仓库的 Tree、Bytecode 两种执行后端跑以上场景。上表是**验收设计和预期结果**,不代表这些命令已经在本环境执行。 - -## 真实系统接入路线 - -1. **供应商主数据**:替换 `查询采购商` 中的示例名录,保持相同字段,并加入供应商状态更新时间与可靠的准入校验。 -2. **报价**:替换 `查询采购商价格` 的静态样例源,增加供应商确认的报价编号、有效期、税运费与币种信息;只有真实服务确认后才允许真实下单。 -3. **预算账本**:把 `已花费` 的调用方输入升级为权威持久账本读数,并在工单提交前做原子预算预占、幂等和失败释放,防止并发超预算。 -4. **真实工单**:真实发送必须以服务端校验的报价、准入、预算预占凭证为依据;保存工单号、状态迁移、外部调用结果和完整审计轨迹。 -5. **真实回执与议价**:把 `模拟回复` 替换为工单服务查询结果;议价后重新获取报价,不能擅自修改原单价格;切换后重新比价。 -6. **Agent 层**:由调用者保存每一步的入参、原始结果、选择理由及关联编号。当前函数调用为无持久状态的模拟,尚不能担保跨进程审计或执行重放。 - -## 重要限制 - -- 本次改写参考了公开仓库源码与规范,但运行环境未提供 `marqdo` 可执行文件,因此没有实际完成 `marqdo check` 或函数调用测试。 -- 表格金额使用示例整数元;生产环境应使用整数分或经过审计的十进制金额库,避免浮点误差。 -- 当前“发工单”返回 `ok=True` 只表示本地演练的门禁通过,不表示真实订单提交成功。 -- 模拟工单号含秒级时间戳,不保证跨调用唯一,也不能充当生产幂等键。 \ No newline at end of file diff --git a/examples/quantum-bell/README.md b/examples/quantum-bell/README.md deleted file mode 100755 index 9aec5b5..0000000 --- a/examples/quantum-bell/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# quantum-bell - -Bell |Φ⁺⟩ via `ext/quantum` circuit table + draw (default `theme=dark` tech lab SVG). - -```bash -cargo build -p marqdo_plugin_quantum -marqdo ext add quantum # after rebuild, so view loads the new .so -marqdo run examples/quantum-bell/index.mq.md -``` - -Writes `bell.svg` next to the program (sandbox cwd). Themes: `theme="dark"|"light"|"bw"` — see [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md). diff --git a/examples/quantum-bell/index.mq.md b/examples/quantum-bell/index.mq.md deleted file mode 100755 index c9e07a0..0000000 --- a/examples/quantum-bell/index.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: Bell state -description: H then CX; probabilities ≈ 1/2; circuit SVG. -import: - quantum: ext/quantum/circuit/index.mq.md - math: lib/math.mq.md - json: lib/json.mq.md ---- - -# Bell |Φ+⟩ - - -H on qubit 0, then CNOT(0→1). Ideal measurement: |00⟩ and |11⟩ each with probability 1/2. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -`steps` = - -| step | gate | qubits | -|------|------|--------| -| 1 | H | 0 | -| 2 | CX | 0,1 | - -We first **qc = [Compute qc](quantum.circuit(qubits=2, steps=`steps`))** for the next step. -We first **p = [Compute p](qc.probabilities())** for the next step. -We first **_ = [Compute _](qc.draw(path="bell.svg"))** for the next step. -We first **_ = [Compute _](qc.draw(kind="probs", path="bell-probs.svg"))** for the next step. - -We now **[Display this step's result](> print text=`p`)**. diff --git a/examples/quantum-entanglement/README.md b/examples/quantum-entanglement/README.md deleted file mode 100755 index 38a387b..0000000 --- a/examples/quantum-entanglement/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# quantum-entanglement - -Bell |Φ⁺⟩ **entanglement lab** via `ext/quantum` Q7/Q8: density matrix, partial trace, Schmidt entropy, and SVG plots (circuit themed dark by default; hinton / qsphere / multibloch / city). - -```bash -cargo build --release -p marqdo_plugin_quantum -marqdo ext add quantum # once (re-run after rebuilding the plugin) -marqdo run examples/quantum-entanglement/index.mq.md -# optional: marqdo view examples/quantum-entanglement/ -``` - -Prints probabilities, full/reduced purity, ⟨ZZ⟩, and Schmidt entropy; writes SVGs next to the program (sandbox cwd). Circuit/probs/bloch accept `theme="dark"|"light"|"bw"`. - -Design: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · sibling: [quantum-bell](../quantum-bell/). diff --git a/examples/quantum-entanglement/index.mq.md b/examples/quantum-entanglement/index.mq.md deleted file mode 100755 index 6788179..0000000 --- a/examples/quantum-entanglement/index.mq.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -markup: occlusion -title: Entanglement lab -description: Bell state — density, partial trace, Schmidt, themed SVG (Q7/Q8). -import: - quantum: ext/quantum/circuit/index.mq.md - math: lib/math.mq.md ---- - -# Entanglement from a runnable document - - -Build |Φ⁺⟩ with H then CX. Full-state purity stays 1; tracing out one qubit yields a mixed state (purity 1/2). Schmidt coefficients and entropy quantify the bipartition. SVG plots (hinton / qsphere / multibloch) make the same facts visible. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Prepare a two-qubit Bell state by applying H and then controlled-X. The full density matrix is pure, while tracing out one qubit leaves a mixed reduced state; these are different questions about the same state. The ZZ expectation and Schmidt entropy give complementary checks, not additional measurements of an evolving physical device. - -The five SVG outputs are real artifacts written through the quantum drawing API, so run in a disposable filesystem root with its required plugin and write effects. Their different views share the calculated state. Keep both numeric observations and generated paths when verifying the example; a successful file write alone does not establish the entanglement values. - -`steps` = - -| step | gate | qubits | -|------|------|--------| -| 1 | H | 0 | -| 2 | CX | 0,1 | - -We first **qc = [Compute qc](quantum.circuit(qubits=2, steps=`steps`))** for the next step. -We first **p = [Compute p](> `qc`.probabilities)** for the next step. - -We first **rho = [Compute rho](> `qc`.density)** for the next step. -We first **pur = [Compute pur](> `rho`.purity)** for the next step. -We first **red = [Compute red](> `rho`.partial_trace keep=0)** for the next step. -We first **rpur = [Compute rpur](> `red`.purity)** for the next step. - -We first **zz = "ZZ"** for the next step. -We first **ezz = [Compute ezz](> `qc`.expect obs=`zz`)** for the next step. - -We first **sch = [Compute sch](> `qc`.schmidt cut=1)** for the next step. -We first **ent = [entropy](access(`sch`, "entropy"))** for the next step. - -We first **_ = [Compute _](> `qc`.draw path="entangle-circuit.svg" theme="dark")** for the next step. -We first **_ = [Compute _](> `qc`.draw kind="hinton" path="entangle-hinton.svg")** for the next step. -We first **_ = [Compute _](> `qc`.draw kind="qsphere" path="entangle-qsphere.svg")** for the next step. -We first **_ = [Compute _](> `qc`.draw kind="multibloch" path="entangle-multibloch.svg")** for the next step. -We first **_ = [Compute _](> `rho`.draw kind="city" path="entangle-city.svg")** for the next step. - -We now **[Display this step's result](> print text=`p`)**. -We now **[Display this step's result](> print text=`pur`)**. -We now **[Display this step's result](> print text=`rpur`)**. -We now **[Display this step's result](> print text=`ezz`)**. -We now **[Display this step's result](> print text=`ent`)**. diff --git a/examples/quantum-ghz/index.mq.md b/examples/quantum-ghz/index.mq.md deleted file mode 100755 index d9e38ef..0000000 --- a/examples/quantum-ghz/index.mq.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -markup: occlusion -title: GHZ state -description: 3-qubit GHZ; |000⟩/|111⟩ ≈ 1/2; probs + H matrix heatmap. -import: - quantum: ext/quantum/circuit/index.mq.md - gate: ext/quantum/gate/index.mq.md ---- - -# GHZ - - -H on qubit 0, CX(0→1), CX(0→2). Ideal: |000⟩ and |111⟩ each with probability 1/2. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -`steps` = - -| step | gate | qubits | -|------|------|--------| -| 1 | H | 0 | -| 2 | CX | 0,1 | -| 3 | CX | 0,2 | - -We first **qc = [Compute qc](quantum.circuit(qubits=3, steps=`steps`))** for the next step. -We first **p = [Compute p](qc.probabilities())** for the next step. -We first **_ = [Compute _](qc.draw(path="ghz.svg"))** for the next step. -We first **_ = [Compute _](qc.draw(kind="probs", path="ghz-probs.svg"))** for the next step. -We first **H = [Compute H](gate.gate(name="H"))** for the next step. -We first **_ = [Compute _](H.draw(kind="matrix", path="ghz-h-matrix.svg"))** for the next step. - -We now **[Display this step's result](> print text=`p`)**. diff --git a/examples/quantum-skill-call/index.mq.md b/examples/quantum-skill-call/index.mq.md deleted file mode 100755 index 9741e9b..0000000 --- a/examples/quantum-skill-call/index.mq.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -markup: occlusion -title: Quantum skill call demo -description: >- - Agent-style flow via ext/quantum index and domain modules (Bell probabilities). -import: - circuit: ext/quantum/circuit/index.mq.md - simulate: ext/quantum/simulate/index.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Build Phi-plus with domain skills, then print ideal probabilities. Prefer the -same steps via marqdo call with --effects plugin and toget when an agent drives -the session. - -We first **qc = [Compute qc](circuit.new(qubits=2, steps=None))** for the next step. -We first **qc = [Compute qc](circuit.hadamard(circuit=`qc`, qubit=0))** for the next step. -We first **qc = [Compute qc](circuit.cnot(circuit=`qc`, control=0, target=1))** for the next step. -We first **p = [Compute p](simulate.probabilities(circuit=`qc`))** for the next step. -We now **[Display this step's result](> print text=`p`)**. diff --git a/examples/stdlib-handbook/index.mq.md b/examples/stdlib-handbook/index.mq.md deleted file mode 100755 index 36ecfcc..0000000 --- a/examples/stdlib-handbook/index.mq.md +++ /dev/null @@ -1,200 +0,0 @@ ---- -markup: occlusion -title: Standard library engineering practice -import: - fs: lib/fs.mq.md - path: lib/path.mq.md - table: lib/table.mq.md - csv: lib/csv.mq.md - document: lib/document.mq.md - hash: lib/hash.mq.md - bytes: lib/bytes.mq.md ---- - -This project demonstrates file inventory, typed CSV aggregation and controlled -Markdown maintenance using the public standard library. No foreign program, -plugin or alternate data syntax is involved. Each operation below is callable. -The demo creates its own directory under the filesystem root and removes it -when successful; it returns the real inventory, report and update outcome. - -Create a disposable directory and set MQ_WORK to its absolute path before the -following command. All relative IO is confined to that directory. The Rust -acceptance test prepares this directory and runs the same source on both runtimes. - -```sh -marqdo call examples/stdlib-handbook/index.mq.md demo --fs-root "$MQ_WORK" --effects fs.write --json -``` - -For production, call inventory on your source directory, summarize_csv on text -from fs.read_text, or update_section with an explicit title and replacement body. -Inspect each operation Result before using its value. File inventory keeps one -unreadable file from aborting other records. Directory cleanup and the update are -separate operations, not a transaction. For high-volume inputs use the batched -collection transforms; this report uses batch transforms, including grouping and aggregation. - -## inventory - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | required | Directory relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One path/ok/characters/error record per Markdown file | - -Use `root` under the explicitly granted filesystem root with fs.read. -Discover Markdown files recursively, then preserve each recoverable read outcome. -A bad UTF-8 file has an error record while other documents still contribute -their actual character counts. Discovery does not execute imported source, -Markdown links, code fences or the main function of a discovered document. - -The paths in the returned records are relative to the selected directory; -joining them for a read does not grant access outside --fs-root. Character counts -measure decoded text, not file byte sizes. This distinction matters for Chinese -and other multibyte content. Missing directories and traversal errors retain -native discovery diagnostics; per-file read failures remain ordinary Result data. - -We **names = [Discover Markdown paths below the selected directory](fs.find(path=`root`, pattern="**/*.md"))** and **out = [Start the observed file records](table.empty_list())**. -- [Retain the actual outcome of each independent read](for names as name) - We **file = [Resolve this discovered path under the selected directory](path.join(a=`root`, b=`name`))** and **read = [Read text without aborting other file records](fs.try_read_text(path=`file`))** and **characters = None**. - 1. [This file decoded successfully](access(`read`, "ok")) - We **body = [Read the decoded UTF-8 source](access(read, "value"))** and **characters = [Count text characters rather than bytes](len(`body`))**. - We **success = [Retain the recoverable read state](access(read, "ok"))** and **error = [Keep the original read diagnostic](access(read, "error"))**. - - `record` = - - | path | ok | characters | error | - |---|---|---|---| - | `name` | `success` | `characters` | `error` | - - We **out = [Retain the successful count or original failure](table.append(list=`out`, item=`record`))**. -After inspecting the selected directory we return *out*. - -## summarize_csv - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Header-based CSV with team, amount and active fields | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | CSV with team/total/count for active rows | - -Use `text` as CSV content, not a filename. Parsing begins with text cells. -The visible schema deliberately converts amount to an integer and active to a -boolean before filtering. Only active rows enter grouping; amounts are summed -per team with the table library's integer checks. Invalid cells retain their -conversion diagnostics instead of silently becoming zero. - -The two-column rename record maps the summarizer's key and value fields to team -and total. The final field list fixes exported column order, including count. -No SQL, foreign interpreter, plugin, file or network operation participates. -If input comes from a file, use the native file library before this pure task. -The output is an actual CSV report that another task can write or transmit; -printing it is not required for later Marqdo functions to consume the value. - -We **rows = [Parse the caller-provided CSV text](csv.parse(text=`text`))**. - -`schema` = - -| amount | active | -|---|---| -| "int" | "bool" | - -We **typed = [Convert the business fields before filtering or arithmetic](table.cast(rows=`rows`, schema=`schema`))** and -**selected = [Select only explicitly active records](table.where(list=`typed`, key="active", value=True))** and -**summary = [Sum checked amounts and count records per team](table.summarize(list=`selected`, key="team", field="amount"))**. - -`names` = - -| key | value | -|---|---| -| "team" | "total" | - -We **renamed = [Name the group key and total for report consumers](table.rename(list=`summary`, fields=`names`))**. - -`fields` = - -| field | -|---| -| "team" | -| "total" | -| "count" | - -We **report = [Keep an explicit exported column order](table.project(list=`renamed`, keys=`fields`))**. -After the native transforms we return *[Serialize the actual row records as CSV](csv.stringify(rows=`report`))*. - -## update_section - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Existing Markdown file under --fs-root | -| title | text | required | Exact unique heading title | -| body | text | required | Replacement section body without its heading | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Recoverable section replacement or checked-write outcome | - -Use `path`, `title` and `body` with fs.write. Read the original UTF-8 -source once and hash that exact text. The document library replaces only the -selected heading body; a missing or ambiguous title remains its failed Result. -The other sections and heading are retained by the structural transform. - -Write only after a successful transform, passing the observed digest to the -native checked writer. A stale source is refused instead of overwriting an -edit that occurred after review. This is a preflight digest check, not a kernel -CAS or a transaction spanning several files. Concurrent writers still need -coordination, and a source-read policy error is a native diagnostic rather -than a fabricated recoverable success. No external text-processing program -participates in reading, section replacement, hashing or writing. - -We **source = [Read the exact reviewed Markdown source](fs.read_text(path=`path`))** and **expected = [Hash that returned source rather than another read](hash.sha256(text=`source`))** and -**changed = [Replace only the explicitly selected section body](document.replace_section(text=`source`, title=`title`, body=`body`))**. -1. [The structural replacement succeeded](access(`changed`, "ok")) - We **next = [Read the successful document transform](access(changed, "value"))**. - Return *[Refuse drift before writing the reviewed document](fs.write_checked(path=`path`, text=`next`, expected_sha256=`expected`))*. -Return *changed* with its original structural failure. - -## demo - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Observed file inventory, CSV report and actual document update | - -Run this complete workflow with fs.write under a disposable --fs-root. -A fresh directory holds one valid Markdown document and one invalid UTF-8 -document. Inventory should preserve both read outcomes. The malformed file is -intentional data for error recovery; it is never imported or executed. - -The CSV sample contains two active team-a amounts and one inactive team-b row. -Its report therefore retains team a with a total of thirty and a count of two. -The section update changes Status while preserving Appendix. After reading -the saved document, normal completion removes this task's own temporary tree; -a failure before cleanup may retain it for diagnosis. Do not remove arbitrary -caller directories to make a test pass. - -The returned record contains these actual values, including the update Result, -so callers can check content and failure details. It is not a fixed compliance -flag and does not claim an atomic transaction across inventory, reporting and -editing. Every operation composes the public native library, with no Python, -shell text processing, JSON construction chain or hidden source-file bridge. - -We **work = [Create a unique directory inside the granted root](fs.temp_dir(prefix="stdlib-demo"))** and -**note = [Name this task own Markdown document](path.join(a=`work`, b="notes.md"))** and **bad = [Name the intentionally invalid text fixture](path.join(a=`work`, b="invalid.md"))**. -We **corpus = "# Notes\n\n## Status\n\nOld status.\n\n# Appendix\n\nKeep this paragraph.\n"** as the complete source that will be edited. -We **[Write the actual starting document](fs.atomic_write(path=`note`, text=`corpus`))** and **binary = [Construct the single invalid UTF-8 byte](bytes.from_base64(text="/w=="))**. -We **[Write the deliberate per-file failure fixture](fs.write_bytes(path=`bad`, data=`binary`))**. -We **files = [Keep both successful and failed native reads](inventory(root=`work`))** and **data = "team,amount,active\na,10,true\nb,4,false\na,20,true\n"**. -We **report = [Run the pure typed aggregation on the visible sample](summarize_csv(text=`data`))** and -**update = [Replace the chosen status section with drift protection](update_section(path=`note`, title="Status", body="Updated through public standard libraries."))** and -**after = [Observe the document that was actually saved](fs.read_text(path=`note`))**. -We **[Remove only this task unique temporary directory](fs.remove_tree(path=`work`))** after the observed results are available. - -`out` = - -| inventory | csv | update | document | -|---|---|---|---| -| `files` | `report` | `update` | `after` | - -After completing these native tasks we return *out*. diff --git a/examples/stdlib-handbook/worker.mq.md b/examples/stdlib-handbook/worker.mq.md deleted file mode 100755 index 436f4da..0000000 --- a/examples/stdlib-handbook/worker.mq.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -markup: occlusion ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -A file task returns its answer; stdout is not the answer channel. - -After these steps, return *17*. diff --git a/examples/stdlib-handbook/索引.mq.md b/examples/stdlib-handbook/索引.mq.md deleted file mode 100755 index b99b6ff..0000000 --- a/examples/stdlib-handbook/索引.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: 标准库工程实践 -import: - practice: index.mq.md ---- - -本工程把文件整理、CSV 数据处理和文档维护连为真实工作流。 -中文入口复用同一份实现,避免双语版本逐渐分叉。准备一个可丢弃目录, -把其绝对路径设为 MQ_WORK,再执行下面的工具;成功后会清理自己的临时子目录。 -返回值包含真实的文件结果、CSV 报表及修改后文档,不以一个通过标志代替验收。 - -```sh -marqdo call examples/stdlib-handbook/索引.mq.md 演示 --fs-root "$MQ_WORK" --effects fs.write --json -``` - -生产使用时先阅读[同源实现](index.mq.md),选择文件清单、汇总报表或更新章节。 -读取失败以每文件错误记录保留;CSV 字段先显式转换类型;章节替换保留周围叙述, -写入前检查来源摘要。根目录、失败结果和并发写入限制都在真实函数旁说明。 - -## 演示 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 三项真实工作流的结果 | - -执行同源工程,保留所有实际返回数据和失败行为。 - -完成上述步骤后,返回*practice.demo()*。 diff --git a/examples/stdlib_catalog.rs b/examples/stdlib_catalog.rs deleted file mode 100755 index 8a8c275..0000000 --- a/examples/stdlib_catalog.rs +++ /dev/null @@ -1,123 +0,0 @@ -//! Inspect real single-file standard library signatures; no index module is required. -//! --json emits compiler metadata; --check validates source effect notes; -//! --write refreshes only effect notes, preserving authored prose and examples. -use anyhow::{bail, Context, Result}; -use std::{ - fs, - path::{Path, PathBuf}, -}; - -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().collect(); - let write = args.iter().any(|arg| arg == "--write"); - let json = args.iter().any(|arg| arg == "--json"); - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut sources: Vec<_> = fs::read_dir(root.join("lib"))? - .map(|entry| entry.map(|e| e.path())) - .collect::>()?; - sources.retain(|p| p.is_file() && p.to_string_lossy().ends_with(".mq.md")); - sources.sort(); - let mut changed = 0; - let mut tools = Vec::new(); - for source in sources { - let module = marqdo::load::load_module(&source)?; - let compilation = marqdo::sema::compile_file_closure(&source)?; - let content = fs::read_to_string(&source)?; - let mut lines: Vec<_> = content.lines().map(str::to_owned).collect(); - let mut edits = Vec::new(); - let zh = source - .file_name() - .unwrap() - .to_string_lossy() - .chars() - .any(|c| !c.is_ascii()); - for (index, function) in module.functions.iter().enumerate() { - let artifact = compilation - .semantics - .artifacts - .iter() - .find(|a| { - a.kind == "function" - && a.source.line == function.span.line - && same_source(&compilation.semantics.root, &a.source.file, &source) - }) - .context("missing compiler function artifact")?; - let signature = artifact - .signature - .as_ref() - .context("missing compiler signature")?; - let effects: Vec<_> = artifact - .effects - .values() - .into_iter() - .filter(|e| *e != "pure") - .collect(); - let effects = if effects.is_empty() { - "pure".to_owned() - } else { - effects.join(",") - }; - let expected = if zh { - format!("调用效应:{effects}。") - } else { - format!("Effects: {effects}.") - }; - let start = function.span.line as usize; - let end = module - .functions - .get(index + 1) - .map(|f| (f.span.line as usize).saturating_sub(1)) - .unwrap_or(lines.len()); - let notes: Vec<_> = (start..end) - .filter(|i| { - lines[*i].starts_with("Effects: ") || lines[*i].starts_with("调用效应:") - }) - .collect(); - if notes.len() != 1 { - bail!( - "{} {} needs one effect note in its source", - source.display(), - function.name - ); - } - if lines[notes[0]] != expected { - changed += 1; - if write { - edits.push((notes[0], expected)); - } else if !json { - eprintln!("stale effect note: {} {}", source.display(), function.name); - } - } - tools.push(serde_json::json!({ - "name": function.name, - "parameters": signature.params.iter().map(|p| serde_json::json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d| &d.0),"unit":p.unit})).collect::>(), - "returns": signature.returns, - "effects": artifact.effects.values(), - "source": source.strip_prefix(&root)?, - "line": function.span.line - })); - } - if !edits.is_empty() { - for (line, text) in edits { - lines[line] = text; - } - fs::write(&source, lines.join("\n") + "\n")?; - } - } - if json { - println!("{}", serde_json::to_string_pretty(&tools)?); - } else if changed > 0 && !write { - bail!("{changed} effect notes differ from compiler metadata; run with --write"); - } else { - println!( - "{} source effect notes {}; {} public functions", - changed, - if write { "updated" } else { "need updating" }, - tools.len() - ); - } - Ok(()) -} -fn same_source(root: &Path, relative: &str, source: &Path) -> bool { - root.join(relative).canonicalize().ok() == source.canonicalize().ok() -} diff --git a/examples/syntax-tour/index.mq.md b/examples/syntax-tour/index.mq.md deleted file mode 100755 index 0448a62..0000000 --- a/examples/syntax-tour/index.mq.md +++ /dev/null @@ -1,240 +0,0 @@ ---- -markup: occlusion -import: - table: lib/table.mq.md -title: Marqdo 可读语法全景 -description: 一页看完全部现行语法:遮蔽、调用、取值、循环、分支、表格、契约 ---- - -从仓库根目录执行:`marqdo call examples/syntax-tour/index.mq.md main --effects output.write --json`。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 本次演示实际得到的名字长度、求和结果、嵌套调用值及空载荷值 | - -从本节开始按顺序执行一份完整程序;命令行可以直接 call 本文件的 main 得到计算记录;View 或 run 另行展示打印步骤。call 需要 output.write 授权,因为本例确实执行打印,但它的业务结果以返回记录为准。下方辅助函数也可以按自己的标题独立调用,不需要先理解一套另外维护的工具签名。执行位置中的变量会保存本轮实际结果,说明文字则交代这些结果为什么出现在这里。 - -变量、参数和字段名有不同职责。变量保存已经得到的值,参数把外部输入交给函数,字段名标识记录中的数据;看见同样的文字不能把三者混为一谈。读取已有值时使用反引号,文本字面值加引号,命令选项也遵守这个规则。表格先说明形态,再绑定为值;字段与返回契约则紧接对应标题,帮助读者在看实现前决定如何调用。 - -本例没有文件写入、网络请求或外联解释器。空载荷是刻意保留的教学桩:它返回空值并给出 warning,用来展示待补充逻辑如何被看见,而不是模拟搜索已经完成。默认分支也只是此例选择的业务规则,不代表库能够自行推断所有未知输入。循环会改变示例中的计数变量,返回会立即结束函数,所以所有后续演示都安排在最终返回之前。 - -一列表是列表,一行多列是记录;行记录集合使用首列标记区分。表头标识业务字段,标记列不成为业务值。需要按列保存多行数据时,应明确选择对应形态,不能只凭视觉排列猜运行时结构。 - -程序最后返回真实中间值,便于调用方逐项验证。打印文字是给人观察的另一条通道,不应再被解析成下一步的输入。要改变演示数据,先检查对应契约和索引约定,再重复实际调用;不能仅凭标签读起来正确就认定其中实现符合描述。 - -—— 1. 变量与插值 —— - -我们先**π = 3.14159**,供下一步使用。 -我们先**名 = "Marqdo"**,供下一步使用。 -我们先**开 = True**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text="名字是`名`,π 约等于 `π`")**。 - -反引号取值,正文里的反引号是插值: - -我们先**长度 = [名字长度](len(`名`))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text="`名` 的长度是 `长度`")**。 - -—— 2. 函数:参数、返回、契约 —— - -税率函数接收档位与金额,返回应缴税额。 - -随后我们**[执行 计税](> 计税 档位=2 金额=100)**。 - -`税率表` = - -| 档位 | 税率 | -|------|------| -| 1 | 0.03 | -| 2 | 0.1 | -| 3 | 0.2 | - -—— 3. 调用形式 —— - -随后我们**[显示当前步骤的结果](> print text="形态一:> 前缀 + 具名实参")**。 - -我们先**甲 = 加(1 2)**,验证空格分隔的位置参数。 -我们先**乙 = [计算并保存 乙](加(1, 2))**,供下一步使用。 -我们先**丙 = [计算并保存 丙](加(加(1, 2), 10))**,供下一步使用。 -**丁 = 加一 号(31)** - -随后我们**[显示当前步骤的结果](> print text="形态二 括号位置实参:`甲`")**。 -随后我们**[显示当前步骤的结果](> print text="形态三 括号逗号:`乙`")**。 -随后我们**[显示当前步骤的结果](> print text="形态四 嵌套:`丙`")**。 -随后我们**[显示当前步骤的结果](> print text="形态五 带空格的函数名:`丁`")**。 - -—— 4. 取值:access / at / get —— - -`篮子` = - -| 果 | -|----| -| 苹果 | -| 梨 | - -`饮品价` = - -| 拿铁 | 美式 | -|------|------| -| 28 | 18 | - -我们先**取第一 = [第一颗](access(`篮子`, "1"))**,供下一步使用。 -我们先**取配置 = [拿铁多少钱](access(`饮品价`, "拿铁"))**,供下一步使用。 -我们先**个数 = [篮子有几颗](table.len(`篮子`))**,供下一步使用。 -我们先**表取 = [用 table.get 读同一个键](table.get(`饮品价`, "美式"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text="access 取列表第 1 项:`取第一`")**。 -随后我们**[显示当前步骤的结果](> print text="access 取 Map 的键:`取配置`")**。 -随后我们**[显示当前步骤的结果](> print text="table.len 数个数:`个数`")**。 -随后我们**[显示当前步骤的结果](> print text="table.get 读键:`表取`")**。 - -—— 5. 遮蔽:把实现藏进括号 —— - -描述给人读,`()` 里才是机器执行的部分。 - -推荐把赋值写进叙述句:`先**值 = [取得需要的结果](实际表达式)**,再使用这个值。` -粗体给出执行位置,方括号解释意图,圆括号保留实际逻辑。三者共同形成可读程序; -普通正文里的导航链接不会因此自动执行。下方也保留表格绑定形式,方便比较数据与操作的职责。 - -我们先**留存 = [客户留存率,模拟数据](0.42)**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text="遮蔽的值:`留存`")**。 - -未接通的功能用空载荷申报(会得到一条 warning,提醒写清返回值): - -我们先**待接 = [搜索接入,接口未接,待开发]()**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text="空载荷桩的值:`待接`")**。 - -—— 6. 循环 —— - -- [篮子里的每个果子](遍历 `篮子` 为 `果`) - 随后我们**[显示当前步骤的结果](> print text="果子:`果`")**。 - -我们先**n = 3**,供下一步使用。 - -- `n` > 0 - 随后我们**[显示当前步骤的结果](> print text="倒数 `n`")**。 - 我们先**n = (`n` - 1)**,供下一步使用。 - -—— 7. 分支 —— - -我们先**分数 = 86**,供下一步使用。 - -1. `分数` >= 90 - 随后我们**[显示当前步骤的结果](> print text="等级 A")**。 -2. `分数` >= 60 - 随后我们**[显示当前步骤的结果](> print text="等级 B")**。 -3. * - 随后我们**[显示当前步骤的结果](> print text="等级 C")**。 - -—— 8. 表格的三态 —— - -竖表(单列)→ List: - -`城市` = - -| 城 | -|----| -| 北京 | -| 上海 | - -横表(1 行)→ Map: - -`配置` = - -| 超时 | 重试 | -|------|------| -| 30 | 2 | - -行向(首列 `行`)→ List of Map: - -`订单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | -| 2 | 梨 | 3 | - -- [每条订单](遍历 `订单` 为 `单`) - 随后我们**[显示当前步骤的结果](> print text="订单:`单`")**。 - -随后我们**[显示当前步骤的结果](> print text="配置超时是 `配置`")**。 - -—— 9. 值类型 —— - -我们先**整数 = 42**,供下一步使用。 -我们先**小数 = 1.5**,供下一步使用。 -我们先**真值 = True**,供下一步使用。 -我们先**空值 = None**,供下一步使用。 -我们先**串 = "引号里的文本"**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text="整数 `整数` 小数 `小数` 真值 `真值` 空值 `空值`")**。 -随后我们**[显示当前步骤的结果](> print text=`串`)**。 - -—— 10. 收尾 —— - -随后我们**[显示当前步骤的结果](> print text="演示结束:执行位置决定是否运行,动作标签说明目的,括号保存实际逻辑。")**。 - -`summary` = - -| name_length | sum | comma_sum | nested_sum | spaced_name | unfinished | -|---|---|---|---|---|---| -| `长度` | `甲` | `乙` | `丙` | `丁` | `待接` | - -完成所有演示后,我们返回*summary*,供调用方直接检查数值与未完成项。 -## 计税 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 档位 | any | required | 税率档位;1 取 3%,3 取 20%,其他值沿用本例 10% | -| 金额 | any | required | 待计税金额;需要支持与选定税率相乘 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 金额乘以本例选定税率;不包含额外舍入 | - -输入`档位`与`金额`,先按明确的分支选择税率,再计算同一份输入的税额。这是教学规则,不读取外部税表,也不把未知档位推断成新的税率。返回值由乘法得到,调用方根据自己的金额单位继续处理。 - -本函数不做货币舍入、不写日志或文件。普通数值可以直接传入;不支持乘法的值保留原生诊断,而不是悄悄当作零。观察选中哪个分支,比只看最后的打印标记更容易核对规则。 - -先**率 = 0.1**作为本例的默认税率。 -1. `档位` == 1 - 此档位使用**率 = 0.03**。 -2. `档位` == 3 - 此档位使用**率 = 0.2**。 -3. * - 其余输入沿用**率 = 0.1**。 -选定税率后,我们返回*[按本例规则计算税额](金额 * 率)*。 - -## 加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | 左操作数;与 b 使用兼容的加法语义 | -| b | any | required | 右操作数;与 a 使用兼容的加法语义 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 两个操作数按原生加法语义得到的新值 | - -输入`a`和`b`,直接组合两个已提供的值。本例用整数调用以展示位置实参、逗号分隔和嵌套调用;函数不会修改调用者变量,也不读取打印输出。需要类型转换时在调用前显式完成,不让这个简单函数猜测字符串是否代表数字。 - -得到两个输入后,我们返回*[按相同规则相加两个操作数](a + b)*。 - -## 加一 号 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | required | 参与加一的输入值;本例以数字演示 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 输入加一的新值,函数名中的空格仍保留 | - -输入`n`之后,按原生加法与一相加。这个函数刻意保留带空格的名称,以展示可读名称与命令行参数引用之间的关系。调用者仍通过完整标题定位它;空格不代表参数,也不需要额外的隐藏入口。 - -完成这次计算后,我们返回*[把输入推进一位](n + 1)*。 diff --git a/examples/view-details.mq.md b/examples/view-details.mq.md deleted file mode 100755 index 2f13656..0000000 --- a/examples/view-details.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: 描述与细节 ---- - -这份文档把意图留在句子中,把细节放在侧注里。阅读和展开详情都不会运行示例中的函数,只有主动调用才会计算。 - -可以先看 [函数与参数](计算费用(单价=12, 数量=2)),再看 [嵌套调用](计算费用(单价=abs(-12), 数量=2)),了解每个输入来自哪里。 - -引用 [列表内容]([1, 2, 3]) 和 [记录内容]({"名称": "茶", "单价": 12}) 时,侧注会按内容的结构排列;[补充说明]("数量以实际购买件数为准。") 则直接呈现文字。 - -[待实现的步骤]() 会明确提示待补充,避免把缺失逻辑当成已经完成的工作。 - -通过 [跳到函数定义](#fn-16) 可以在当前文档中定位,通过 [查看阅读示例](view-reading.mq.md) 可以打开同目录文档;[访问项目仓库](https://github.com/cflmy/marqdo) 保留正常的网页跳转。 - -## 计算费用 - -| 参数 | 类型 | 默认值 | 含义 | -| --- | --- | --- | --- | -| 单价 | number | 0 | 每件商品的价格 | -| 数量 | number | 1 | 本次购买的件数 | - -| 返回值 | 类型 | 含义 | -| --- | --- | --- | -| 费用 | number | 单价与数量的乘积 | - -调用方提供 `单价`=0 和 `数量`=1 后,可以直接按件数计算。这一示例只处理简单乘法,未包含税费、折扣或金额舍入规则,实际项目应根据业务补齐这些约定。 - -在确认输入符合业务要求之后,返回 *[按件数计算](单价 * 数量)*,调用方便得到了本次购买的总费用。 diff --git a/examples/view-reading.mq.md b/examples/view-reading.mq.md deleted file mode 100755 index cd15861..0000000 --- a/examples/view-reading.mq.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -markup: occlusion -title: 在正文里读懂一段程序 -description: 用同一份源码演示动作遮蔽、输入输出、数据表、条件、循环和待补逻辑。 ---- - -这份示例把计算留在文章里。动作说明可以直接阅读,展开侧注才看到实际表达式。 -侧注说明“准备怎样计算”,运行标注说明“这一次得到什么”;两种信息有不同的来源。 - -用 marqdo view examples/view-reading.mq.md 打开实时阅读,或执行下面的离线导出命令。 -导出时的 --no-exec 只分析和排版,不运行示例,也不触发任何动作。 - -```sh -marqdo view output examples/view-reading.mq.md --no-exec --out /tmp/marqdo-reading -``` - -## 计算小计 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 单价 | number | 必填 | 每件商品的价格,使用调用方选定的同一种货币单位 | -| 数量 | number | 1 | 购买的件数;本例由调用方保证非负 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 小计 | number | 单价乘以数量得到的金额,不包含额外税费或优惠 | - -已知商品的`单价`,未指定时购买`数量`=1。这里没有网络请求或文件写入; -价格与数量由调用者提供,不会从屏幕上的说明自动推测。 -完成乘法后,我们返回*[按件数计算金额](单价 * 数量)*,让后面的步骤继续使用。 - -## 预留逻辑 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 当前返回 None;尚未接入实际业务实现 | - -此函数演示空遮蔽的显示。它没有实现业务行为,不能作为“功能已完成”的证据。 -目前返回*[由作者补充具体业务]()*;阅读器会明确标出待补逻辑,而不会假装已有结果。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 两笔金额与遍历计算的总数,均来自这一次实际执行 | - -先**第一笔 = [购买两件商品](计算小计(单价=12, 数量=2))**,再**第二笔 = [使用默认件数](计算小计(单价=8))**。 -两个动作可以在同一句话里出现,各自关联自己的逻辑侧注。金额的实际数值只在运行后产生。 - -下面的单列表是三个数量组成的列表;绑定名让它成为数据,和上面的参数契约表不同。 - -`数量列表` = - -| 数量 | -|---| -| 1 | -| 2 | -| 3 | - -从**总数 = 0**开始累计,每次迭代读取一个值。切换迭代记录只是在查看既有结果,不会重跑循环。 - -- [依次累计数量](遍历 数量列表 为 项) - 把当前项加入已有累计,得到**总数 = 总数 + 项**。 - -下面按计算结果选择分支;未进入的分支仍然属于源码,不会因为查看运行记录而消失。 - -1. `总数` > 0 - 确认这次遍历已有数据后,执行**[输出累计值](print(text=`总数`))**。 -2. * - 没有数量时,执行**[说明输入为空](print(text="没有数量"))**。 - -把已经计算的值整理成一行记录,字段名称说明每一项的来源。 - -`摘要` = - -| 第一笔 | 第二笔 | 总数 | -|---|---|---| -| `第一笔` | `第二笔` | `总数` | - -最后返回*摘要*,调用者得到的是结构化记录;上面的预留函数并未在本流程中调用。 diff --git a/examples/web-client-site/README.md b/examples/web-client-site/README.md deleted file mode 100755 index 32322f8..0000000 --- a/examples/web-client-site/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# examples/web-client-site - -SSR **Document Artifact** + `web.client_embed` auto-mount(零作者 JS)。ADR 0007。 - -```bash -bash scripts/build-web-plugin.sh -export MARQDO_EXT=$PWD/ext # 若本机 ~/.marqdo/ext 未同步 -marqdo wasm build -o examples/web-client-site/static -cargo run -- run examples/web-client-site/serve.mq.md -``` - -- `index.mq.md` — `type: web` 文档页 -- `serve.mq.md` — `web.serve` + `static_dir` -- `static/client.mq.md` — `lib/browser` wire(不变) diff --git a/examples/web-client-site/index.mq.md b/examples/web-client-site/index.mq.md deleted file mode 100755 index f284088..0000000 --- a/examples/web-client-site/index.mq.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -markup: occlusion -type: web -title: Marqdo client site -route: / -method: GET -description: SSR Document + client_embed auto-mount; author zero JS (ADR 0007). -import: - web: ext/web/web.mq.md ---- - -# Marqdo client site - -SSR shell with WASM session. Client logic lives in `static/client.mq.md`. - -To serve with static assets, run `serve.mq.md` in this directory. diff --git a/examples/web-client-site/serve.mq.md b/examples/web-client-site/serve.mq.md deleted file mode 100755 index 5771872..0000000 --- a/examples/web-client-site/serve.mq.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -markup: occlusion -title: web-client-site serve -import: - web: ext/web/web.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **embed = [Compute embed](web.client_embed(source="/static/client.mq.md"))** for the next step. -We now **[Display this step's result](> print text="embed-ready")**. -We now **[Call web.serve](> web.serve root="." host="127.0.0.1" port=18090 static_dir="static")**. diff --git a/examples/web-client-site/static/client.mq.md b/examples/web-client-site/static/client.mq.md deleted file mode 100755 index a65f600..0000000 --- a/examples/web-client-site/static/client.mq.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -markup: occlusion -title: client counter (route D) -description: wired by client_embed auto-mount; GFM + lib/browser -import: - browser: lib/browser.mq.md - table: lib/table.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -This client module starts one counter, registers bump/reset controls and returns a ready message with the wire table. The server-side page supplies #bump, #reset, #count and #log; the client does not build a second page from raw HTML. - -The browser bridge applies the returned instructions and preserves state between callbacks. Initial readiness only shows that mounting occurred. Verify a click and reset separately to check the counter behavior, and keep selector names aligned with the page's Markdown view structure. - -We first **count = 0** for the next step. - -`wire` = - -| @ | 选择器 | 事件 | 调用 | -|---|--------|------|------| -| 1 | "#bump" | click | bump | -| 2 | "#reset" | click | reset | - -We first **ready = [Compute ready](browser.set_text(sel="#log", text="client.mq.md ready"))** for the next step. -We first **boot = [Compute boot](table.put(in=None, at="wire", value=`wire`))** for the next step. -After these steps, return *browser.merge(a=`boot`, b=`ready`)*. - -## bump - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | A plain set_text instruction with the next counter value | - -This click callback reads the count already retained by the browser session. It takes no event input and does not ask the caller to supply the current state. After incrementing the native integer, convert it to text for the existing count target. Returning an instruction still relies on the official bridge to update the visible page. - -We **count = count + 1** and **label = [Convert the updated native count to text](str(count))**. -Return *[Display this session's new count](browser.set_text(sel="#count", text=`label`))*. - - -## reset - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | A plain set_text instruction showing zero | - -Reset changes the same session count used by bump. It takes no argument and does not create a new browser instance. The displayed text and retained integer are set together, so the next bump should show one. The callback describes a DOM effect and performs no direct server or file operation. - -We **count = 0** before describing the visible result. -Return *[Show the reset state](browser.set_text(sel="#count", text="0"))*. diff --git a/examples/web-client-site/static/marqdo-bridge.js b/examples/web-client-site/static/marqdo-bridge.js deleted file mode 100755 index e69d52f..0000000 --- a/examples/web-client-site/static/marqdo-bridge.js +++ /dev/null @@ -1,1009 +0,0 @@ -/** - * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. - * Authors write .mq.md only; this file may grow host mechanisms freely. - * - * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, - * focus, blur, scroll_into, set_html, replace_children, render_list, - * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval - */ - -export function readCString(memory, ptr) { - const bytes = new Uint8Array(memory.buffer); - let end = ptr; - while (bytes[end] !== 0) end += 1; - return new TextDecoder().decode(bytes.subarray(ptr, end)); -} - -function decodePacked(exports, outPtr) { - if (!outPtr) throw new Error("null wasm result pointer"); - const view = new DataView(exports.memory.buffer); - const jsonLen = view.getUint32(outPtr, true); - const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen); - const text = new TextDecoder().decode(jsonBytes); - exports.mq_dealloc(outPtr, 4 + jsonLen); - return JSON.parse(text); -} - -function writeUtf8(exports, text) { - const encoded = new TextEncoder().encode(text); - const ptr = exports.mq_alloc(encoded.length || 1); - if (!ptr) throw new Error("mq_alloc failed"); - new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded); - return { ptr, len: encoded.length }; -} - -export function runSource(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_run(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function boot(exports, source) { - const { ptr, len } = writeUtf8(exports, source); - const outPtr = exports.mq_boot(ptr, len); - exports.mq_dealloc(ptr, len || 1); - return decodePacked(exports, outPtr); -} - -export function call(exports, name, argsObj = {}) { - const n = writeUtf8(exports, name); - const a = writeUtf8(exports, JSON.stringify(argsObj ?? {})); - const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len); - exports.mq_dealloc(n.ptr, n.len || 1); - exports.mq_dealloc(a.ptr, a.len || 1); - return decodePacked(exports, outPtr); -} - -export async function loadWasm(url = "./marqdo_wasm.wasm") { - const res = await fetch(url); - if (!res.ok) { - throw new Error( - `failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`, - ); - } - const { instance } = await WebAssembly.instantiateStreaming(res, {}); - return instance.exports; -} - -function isPlainObject(v) { - return v != null && typeof v === "object" && !Array.isArray(v); -} - -function asSelList(v) { - if (v == null) return []; - if (Array.isArray(v)) return v.map(String); - return [String(v)]; -} - -/** Normalize mount options from plain object or DOM dataset. */ -export function normalizeMountOptions(raw = {}) { - const o = raw && typeof raw === "object" ? raw : {}; - const dataset = o.dataset || {}; - const wasmUrl = - o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; - const sourceUrl = - o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; - let source = o.source != null ? o.source : dataset.mqSource || ""; - if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; - const ready = o.ready || o.readySel || dataset.mqReady || ""; - const enable = o.enable || dataset.mqEnable || ""; - const noBoot = - o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; - return { - wasmUrl: String(wasmUrl), - sourceUrl: sourceUrl ? String(sourceUrl) : "", - source: source ? String(source) : "", - playground: playground ? String(playground) : "", - ready: ready ? String(ready) : "", - enable: enable ? String(enable) : "", - noBoot, - onError: typeof o.onError === "function" ? o.onError : null, - }; -} - -export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { - if (!doc) return []; - const out = []; - const bootEl = doc.getElementById("marqdo-boot"); - if (bootEl) { - try { - out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); - } catch (e) { - console.error("marqdo-boot JSON:", e); - } - } - const scripts = doc.querySelectorAll( - "script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]", - ); - for (const el of scripts) { - if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; - const hasWork = - el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; - if (!hasWork) continue; - out.push( - normalizeMountOptions({ - dataset: el.dataset, - wasmUrl: el.dataset.mqWasm, - sourceUrl: el.dataset.mqSourceUrl, - source: el.dataset.mqSource, - playground: el.dataset.mqPlayground, - ready: el.dataset.mqReady, - enable: el.dataset.mqEnable, - }), - ); - } - return out; -} - -export function eventArgsFromDom(ev, valueFromSel) { - const t = ev && ev.target; - const args = { event: ev && ev.type ? ev.type : "click" }; - if (t && typeof t === "object") { - if ("value" in t && t.value != null) args.value = String(t.value); - if ("checked" in t) args.checked = !!t.checked; - if (t.id) args.id = String(t.id); - if (t.getAttribute) { - const did = t.getAttribute("data-id"); - if (did != null) args.data_id = did; - } - if (typeof t.textContent === "string" && !("value" in t)) { - args.text = t.textContent; - } - if (ev.key != null) args.key = String(ev.key); - if (ev.code != null) args.code = String(ev.code); - } - if (ev && ev.type === "popstate") { - args.url = typeof location !== "undefined" ? location.href : ""; - args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; - args.state = ev.state; - } - if (valueFromSel && typeof document !== "undefined") { - const src = document.querySelector(valueFromSel); - if (src) { - if ("value" in src) args.value = String(src.value); - else args.value = src.textContent != null ? String(src.textContent) : ""; - } - } - if (ev && ev.type === "submit" && t) { - const form = typeof t.closest === "function" ? t.closest("form") : t; - if (form && typeof FormData !== "undefined") { - try { - ev.preventDefault(); - } catch (_) { - /* ignore */ - } - const fields = {}; - for (const [k, v] of new FormData(form)) fields[k] = String(v); - args.fields = fields; - } - } - return args; -} - -function applyStyle(el, styleVal) { - if (typeof styleVal === "string") { - el.setAttribute("style", styleVal); - return; - } - if (isPlainObject(styleVal)) { - for (const [k, v] of Object.entries(styleVal)) { - if (v === null || v === false) el.style.removeProperty(k); - else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); - } - } -} - -export function renderListItems(spec) { - const tag = String(spec.tag || "li"); - const items = Array.isArray(spec.items) ? spec.items : []; - return items - .map((it) => { - if (it == null) return ""; - if (typeof it === "string" || typeof it === "number") { - return `<${tag}>${escapeHtml(String(it))}`; - } - if (!isPlainObject(it)) return ""; - const text = it.text != null ? String(it.text) : it.html != null ? null : ""; - const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; - let attrs = ""; - if (isPlainObject(it.attrs)) { - for (const [k, v] of Object.entries(it.attrs)) { - if (v === null || v === false) continue; - attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; - } - } - const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); - return `<${tag}${cls}${attrs}>${inner}`; - }) - .join(""); -} - -function escapeHtml(s) { - return s - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """); -} - -function escapeAttr(s) { - return escapeHtml(s).replace(/'/g, "'"); -} - -function qsAll(sel) { - if (typeof document === "undefined") return []; - try { - return [...document.querySelectorAll(sel)]; - } catch (_) { - return []; - } -} - -function qsOne(sel) { - const all = qsAll(sel); - return all[0] || null; -} - -/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ -export function applyDomPatch(value) { - if (!value || typeof value !== "object") return; - if (typeof document === "undefined") return; - - const setText = value.set_text || value.setText; - if (isPlainObject(setText)) { - for (const [sel, text] of Object.entries(setText)) { - for (const el of qsAll(sel)) el.textContent = String(text); - } - } - - const setValue = value.set_value || value.setValue; - if (isPlainObject(setValue)) { - for (const [sel, v] of Object.entries(setValue)) { - for (const el of qsAll(sel)) { - if ("value" in el) el.value = String(v); - } - } - } - - const setAttr = value.set_attr || value.setAttr; - if (isPlainObject(setAttr)) { - for (const [sel, attrs] of Object.entries(setAttr)) { - if (!isPlainObject(attrs)) continue; - for (const el of qsAll(sel)) { - for (const [name, raw] of Object.entries(attrs)) { - if (raw === null || raw === false) el.removeAttribute(name); - else el.setAttribute(name, String(raw)); - } - } - } - } - - const setClass = value.set_class || value.setClass; - if (isPlainObject(setClass)) { - for (const [sel, cls] of Object.entries(setClass)) { - for (const el of qsAll(sel)) el.className = String(cls); - } - } - - const addClass = value.add_class || value.addClass; - if (isPlainObject(addClass)) { - for (const [sel, cls] of Object.entries(addClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.add(c); - } - } - - const removeClass = value.remove_class || value.removeClass; - if (isPlainObject(removeClass)) { - for (const [sel, cls] of Object.entries(removeClass)) { - const names = String(cls).split(/\s+/).filter(Boolean); - for (const el of qsAll(sel)) for (const c of names) el.classList.remove(c); - } - } - - const toggleClass = value.toggle_class || value.toggleClass; - if (isPlainObject(toggleClass)) { - for (const [sel, cls] of Object.entries(toggleClass)) { - for (const el of qsAll(sel)) { - if (cls) el.classList.toggle(String(cls)); - } - } - } - - const setStyle = value.set_style || value.setStyle; - if (isPlainObject(setStyle)) { - for (const [sel, st] of Object.entries(setStyle)) { - for (const el of qsAll(sel)) applyStyle(el, st); - } - } - - for (const sel of asSelList(value.focus)) { - const el = qsOne(sel); - if (el && el.focus) el.focus(); - } - for (const sel of asSelList(value.blur)) { - const el = qsOne(sel); - if (el && el.blur) el.blur(); - } - for (const sel of asSelList(value.scroll_into || value.scrollInto)) { - const el = qsOne(sel); - if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); - } - - const setHtml = value.set_html || value.setHtml; - if (isPlainObject(setHtml)) { - for (const [sel, html] of Object.entries(setHtml)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const appendHtml = value.append_html || value.appendHtml; - if (isPlainObject(appendHtml)) { - for (const [sel, html] of Object.entries(appendHtml)) { - for (const el of qsAll(sel)) el.insertAdjacentHTML("beforeend", String(html)); - } - } - - const replaceChildren = value.replace_children || value.replaceChildren; - if (isPlainObject(replaceChildren)) { - for (const [sel, html] of Object.entries(replaceChildren)) { - for (const el of qsAll(sel)) el.innerHTML = String(html); - } - } - - const renderList = value.render_list || value.renderList; - if (isPlainObject(renderList)) { - for (const [sel, spec] of Object.entries(renderList)) { - if (!isPlainObject(spec)) continue; - const html = renderListItems(spec); - for (const el of qsAll(sel)) el.innerHTML = html; - } - } - - const removeSel = value.remove || value.remove_nodes || value.removeNodes; - if (removeSel) { - for (const sel of asSelList(removeSel)) { - for (const el of qsAll(sel)) el.remove(); - } - } - - const nav = value.navigate; - if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { - const url = String(nav.url); - if (nav.replace) history.replaceState(nav.state ?? null, "", url); - else history.pushState(nav.state ?? null, "", url); - } - - const clip = value.clipboard || value.copy; - if (clip != null && typeof navigator !== "undefined" && navigator.clipboard?.writeText) { - const text = isPlainObject(clip) ? String(clip.text ?? "") : String(clip); - navigator.clipboard.writeText(text).catch(() => {}); - } - - const dl = value.download; - if (isPlainObject(dl) && dl.body != null) { - const mime = String(dl.mime || "text/plain;charset=utf-8"); - const name = String(dl.filename || "download.txt"); - const blob = new Blob([String(dl.body)], { type: mime }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = name; - a.click(); - URL.revokeObjectURL(url); - } -} - -const intervalHandles = new Map(); -const wsHandles = new Map(); -let wsSeq = 0; - -/** - * Run sync DOM patches then schedule async effects. - */ -export function applyEffects(exports, value, { onError } = {}) { - applyDomPatch(value); - if (!value || typeof value !== "object") return Promise.resolve(); - - const tasks = []; - - const fetchSpec = value.fetch; - if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) { - tasks.push(runFetchEffect(exports, fetchSpec, onError)); - } - - const fetchAll = value.fetch_all || value.fetchAll; - if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { - tasks.push(runFetchAllEffect(exports, fetchAll, onError)); - } - - const afterSpec = value.after; - if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { - tasks.push(runAfterEffect(exports, afterSpec, onError)); - } - - const intervalSpec = value.interval; - if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { - runIntervalEffect(exports, intervalSpec, onError); - } - - const clearIv = value.clear_interval || value.clearInterval; - if (clearIv && typeof clearIv === "object") { - const id = String(clearIv.id || "default"); - const h = intervalHandles.get(id); - if (h != null) { - clearInterval(h); - intervalHandles.delete(id); - } - } - - const storageSpec = value.storage; - if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { - tasks.push(runStorageEffect(exports, storageSpec, onError)); - } - - const wsSpec = value.ws; - if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { - tasks.push(runWsEffect(exports, wsSpec, onError)); - } - - return Promise.all(tasks); -} - -function buildFetchInit(spec) { - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; - if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { - const fd = new FormData(); - for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); - init.body = fd; - } else if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } - return init; -} - -async function runFetchEffect(exports, spec, onError) { - const thenFn = spec.then; - try { - const res = await fetch(String(spec.url), buildFetchInit(spec)); - const body = await res.text(); - const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - try { - const result = call(exports, thenFn, { - ok: false, - status: 0, - body: "", - error: String(e), - }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - else if (onError) onError(result.error); - } catch (e2) { - if (onError) onError(String(e2)); - else console.error(e2); - } - } -} - -async function runFetchAllEffect(exports, spec, onError) { - const thenFn = spec.then; - const reqs = Array.isArray(spec.requests) - ? spec.requests - : isPlainObject(spec.requests) - ? Object.keys(spec.requests) - .sort() - .map((k) => spec.requests[k]) - .filter((r) => r && typeof r === "object") - : []; - try { - const results = await Promise.all( - reqs.map(async (r) => { - try { - const res = await fetch(String(r.url), buildFetchInit(r)); - const body = await res.text(); - return { ok: res.ok, status: res.status, body, url: String(r.url) }; - } catch (e) { - return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; - } - }), - ); - const result = call(exports, thenFn, { ok: true, results }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runAfterEffect(exports, spec, onError) { - const ms = Math.max(0, Number(spec.ms) || 0); - const thenFn = spec.then; - return new Promise((resolve) => { - setTimeout(() => { - try { - const result = call(exports, thenFn, { ok: true }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - resolve(); - return; - } - Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - resolve(); - } - }, ms); - }); -} - -function runIntervalEffect(exports, spec, onError) { - const ms = Math.max(1, Number(spec.ms) || 1000); - const thenFn = spec.then; - const id = String(spec.id || "default"); - if (intervalHandles.has(id)) { - clearInterval(intervalHandles.get(id)); - intervalHandles.delete(id); - } - const handle = setInterval(() => { - try { - const result = call(exports, thenFn, { ok: true, id }); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }, ms); - intervalHandles.set(id, handle); -} - -function storageStore(scope) { - if (scope === "cookie") return null; - if (typeof localStorage === "undefined") return null; - return scope === "session" ? sessionStorage : localStorage; -} - -function cookieGet(key) { - if (typeof document === "undefined") return null; - const prefix = encodeURIComponent(key) + "="; - for (const part of document.cookie.split(";")) { - const s = part.trim(); - if (s.startsWith(prefix)) return decodeURIComponent(s.slice(prefix.length)); - } - return null; -} - -function cookieSet(key, value, days) { - if (typeof document === "undefined") return; - let extra = "; path=/"; - if (days != null && Number(days) > 0) { - const d = new Date(); - d.setTime(d.getTime() + Number(days) * 864e5); - extra += "; expires=" + d.toUTCString(); - } - document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + extra; -} - -function cookieRemove(key) { - if (typeof document === "undefined") return; - document.cookie = encodeURIComponent(key) + "=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; -} - -async function runStorageEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - const key = String(spec.key || ""); - const scope = String(spec.scope || "local"); - try { - if (scope === "cookie") { - if (op === "set") { - cookieSet(key, spec.value != null ? String(spec.value) : "", spec.days); - } else if (op === "remove" || op === "delete") { - cookieRemove(key); - } else if (op === "get") { - const value = cookieGet(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - return; - } - if (spec.then && op !== "get") { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - - const store = storageStore(scope); - if (!store) { - if (onError) onError("storage unavailable"); - return; - } - if (op === "set") { - store.setItem(key, spec.value != null ? String(spec.value) : ""); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "remove" || op === "delete") { - store.removeItem(key); - if (spec.then) { - const result = call(exports, spec.then, { ok: true, op, key, scope }); - if (result.ok) await applyEffects(exports, result.value, { onError }); - } - return; - } - if (op === "get") { - const value = store.getItem(key); - if (spec.then) { - const result = call(exports, spec.then, { - ok: true, - op, - key, - value: value == null ? "" : value, - found: value != null, - scope, - }); - if (!result.ok) { - if (onError) onError(result.error); - return; - } - await applyEffects(exports, result.value, { onError }); - } - } - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } -} - -function runWsEffect(exports, spec, onError) { - const op = String(spec.op || "").toLowerCase(); - return new Promise((resolve) => { - try { - if (op === "open") { - if (typeof WebSocket === "undefined") { - if (onError) onError("WebSocket unavailable"); - resolve(); - return; - } - const id = String(spec.id || `ws${++wsSeq}`); - const sock = new WebSocket(String(spec.url)); - wsHandles.set(id, sock); - sock.addEventListener("open", () => { - if (spec.then_open || spec.thenOpen) { - try { - const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - resolve(); - }); - sock.addEventListener("message", (ev) => { - const thenMsg = spec.then_message || spec.thenMessage; - if (!thenMsg) return; - try { - const result = call(exports, thenMsg, { - ok: true, - id, - data: typeof ev.data === "string" ? ev.data : String(ev.data), - }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - }); - sock.addEventListener("close", () => { - wsHandles.delete(id); - const thenClose = spec.then_close || spec.thenClose; - if (thenClose) { - try { - const result = call(exports, thenClose, { ok: true, id }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - sock.addEventListener("error", () => { - const thenErr = spec.then_error || spec.thenError; - if (thenErr) { - try { - const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); - if (result.ok) applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); - } - } - }); - return; - } - if (op === "send") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock && sock.readyState === WebSocket.OPEN) { - sock.send(spec.data != null ? String(spec.data) : ""); - } else if (onError) onError(`ws send: no open socket ${id}`); - resolve(); - return; - } - if (op === "close") { - const id = String(spec.id || [...wsHandles.keys()][0] || ""); - const sock = wsHandles.get(id); - if (sock) sock.close(); - wsHandles.delete(id); - resolve(); - return; - } - resolve(); - } catch (e) { - if (onError) onError(String(e)); - resolve(); - } - }); -} - -function bindTarget(sel) { - if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; - if (sel === "document" || sel === "@document") - return typeof document !== "undefined" ? document : null; - return null; -} - -/** - * Wire events from `# main` return value (list or `{ wire: [...] }`). - */ -export function wireEvents(exports, bootValue, { onError } = {}) { - let rows = []; - if (Array.isArray(bootValue)) rows = bootValue; - else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire; - - for (const row of rows) { - const sel = row["选择器"] || row.selector || row.sel; - const ev = row["事件"] || row.event || "click"; - const fn = row["调用"] || row.call || row.fn; - const valueFrom = - row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; - const delegate = - row["委托"] || row.delegate || row.delegation || ""; - if (!sel || !fn) continue; - - const special = bindTarget(sel); - const roots = special - ? [special] - : typeof document !== "undefined" - ? [...document.querySelectorAll(sel)] - : []; - - roots.forEach((node) => { - node.addEventListener(ev, (domEv) => { - try { - if (delegate) { - const hit = - typeof domEv.target?.closest === "function" - ? domEv.target.closest(delegate) - : null; - if (!hit || (node.contains && !node.contains(hit))) return; - } - if ( - ev === "click" && - typeof domEv.target?.closest === "function" && - domEv.target.closest("a[href]") - ) { - try { - domEv.preventDefault(); - } catch (_) { - /* ignore */ - } - } - const args = eventArgsFromDom(domEv, valueFrom); - if (delegate && domEv.target) { - const hit = domEv.target.closest?.(delegate); - if (hit?.getAttribute) { - const did = hit.getAttribute("data-id"); - if (did != null) args.data_id = did; - if (hit.id) args.id = hit.id; - } - } - const result = call(exports, fn, args); - if (!result.ok) { - if (onError) onError(result.error); - else console.error(result.error); - return; - } - applyEffects(exports, result.value, { onError }); - if (result.stdout) console.log(result.stdout); - } catch (e) { - if (onError) onError(String(e)); - else console.error(e); - } - }); - }); - } - return rows.length; -} - -function markReady(opts, message) { - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.remove?.("err"); - el.textContent = message; - } - } - if (opts.enable && typeof document !== "undefined") { - for (const sel of String(opts.enable).split(",")) { - const s = sel.trim(); - if (!s) continue; - document.querySelectorAll(s).forEach((n) => { - n.disabled = false; - n.removeAttribute("disabled"); - }); - } - } -} - -function markError(opts, err) { - const msg = String(err); - if (opts.onError) opts.onError(msg); - if (opts.ready && typeof document !== "undefined") { - const el = document.querySelector(opts.ready); - if (el) { - el.classList?.add?.("err"); - el.textContent = msg; - } - } else { - console.error(msg); - } -} - -function wirePlayground(exports, playgroundSpec, { onError } = {}) { - const parts = String(playgroundSpec) - .split(",") - .map((s) => s.trim()) - .filter(Boolean); - const sourceSel = parts[0] || "#src"; - const runSel = parts[1] || "#run"; - const outSel = parts[2] || "#out"; - const runBtn = document.querySelector(runSel); - const src = document.querySelector(sourceSel); - const out = document.querySelector(outSel); - if (!runBtn || !src) return 0; - runBtn.disabled = false; - runBtn.removeAttribute("disabled"); - runBtn.addEventListener("click", () => { - try { - const result = runSource(exports, src.value || ""); - if (out) { - out.classList?.toggle?.("err", !result.ok); - out.textContent = result.ok - ? (result.stdout || "(empty stdout)") + - (result.value != null && result.value !== "None" - ? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}` - : "") - : result.error || "error"; - } - } catch (e) { - if (onError) onError(String(e)); - else if (out) { - out.classList?.add?.("err"); - out.textContent = String(e); - } - } - }); - return 1; -} - -export async function mount(rawOpts = {}) { - const opts = normalizeMountOptions(rawOpts); - const onError = (err) => markError(opts, err); - - let exports; - try { - exports = await loadWasm(opts.wasmUrl); - } catch (e) { - onError(e); - throw e; - } - - const ver = readCString(exports.memory, exports.mq_version()); - - if (opts.playground) { - const n = wirePlayground(exports, opts.playground, { onError }); - markReady(opts, `marqdo-wasm ${ver} · playground ready`); - return { exports, boot: null, wired: n }; - } - - let source = opts.source; - if (!source && opts.sourceUrl) { - const res = await fetch(opts.sourceUrl); - if (!res.ok) { - const err = `failed to load ${opts.sourceUrl} (${res.status})`; - onError(err); - throw new Error(err); - } - source = await res.text(); - } - if (!source) { - const err = "mount: need source, sourceUrl, or playground"; - onError(err); - throw new Error(err); - } - - const result = boot(exports, source); - if (!result.ok) { - onError(result.error || "boot failed"); - throw new Error(result.error || "boot failed"); - } - - if (result.value && !Array.isArray(result.value)) { - await applyEffects(exports, result.value, { onError }); - } - - const n = wireEvents(exports, result.value, { onError }); - const srcLabel = opts.sourceUrl || "(inline)"; - markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`); - return { exports, boot: result, wired: n }; -} - -export async function autoMount(doc) { - const configs = collectMountConfigs(doc); - const results = []; - for (const cfg of configs) { - if (cfg.noBoot) continue; - results.push(await mount(cfg)); - } - return results; -} - -const g = typeof globalThis !== "undefined" ? globalThis : undefined; -if (g && g.document) { - const start = () => { - autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e)); - }; - if (g.document.readyState === "loading") { - g.document.addEventListener("DOMContentLoaded", start); - } else { - queueMicrotask(start); - } -} diff --git a/examples/web-collab-doc/README.md b/examples/web-collab-doc/README.md deleted file mode 100755 index 937250d..0000000 --- a/examples/web-collab-doc/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# web-collab-doc - -这个工程演示同源 WebSocket 房间中的双浏览器记事本。客户端发送完整文本快照,收到的较新消息覆盖本地内容;它不实现 CRDT、离线合并或持久化历史。服务只在本机演示端口提供匿名房间,部署前应配置真实鉴权。 - -从仓库根目录构建当前浏览器运行时,再启动服务: - -```sh -marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-collab-doc/static"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json -marqdo call examples/web-collab-doc/index.mq.md serve --effects plugin,fs.read,network.write --fs-root . --json -``` - -打开 http://127.0.0.1:18094 两次,在任一窗口编辑文本。另一窗口收到快照后仍可继续本地编辑,空文本也是有效快照。构建缺少兼容 WASM 目标时,先按 [工具链手册](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,把返回的 compiler 传给 build_browser。 - -入口 [index.mq.md](index.mq.md) 负责页面发现与房间绑定;[home.mq.md](home.mq.md) 组合说明、编辑器和状态,末端内容与控件分别可读;[客户端](static/client.mq.md) 直接表达输入、消息和在线状态处理。 - -[开发手册](../../skills/marqdo-dev/index.mq.md) 的 test_browser 使用当前构建运行真实双页交互,覆盖远端更新后的下一次本地输入、空文本与在线状态。设计背景见 [协作设计](../../doc/design/ext-web-collab.md)。 diff --git a/examples/web-collab-doc/editor.mq.md b/examples/web-collab-doc/editor.mq.md deleted file mode 100755 index 97f7aa2..0000000 --- a/examples/web-collab-doc/editor.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -title: Native collaborative editor leaf -import: - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -This intrinsic label/textarea pair contains no socket, page shell or generated HTML. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Accessible native multiline editor rows | - -The label names the same doc id used by the client input binding. Rows and columns are typed native attributes rather than interpolated markup. Initial content is empty and ordinary text; the bridge later changes its value. Geometry outside this intrinsic field pair belongs to the parent page component. - -We **label_attrs = [Associate the visible label with the editor](table.put(in=None, at="for", value="doc"))** and **label = [Describe the plain editor label](component.element(kind="label", value="Shared text", attrs=`label_attrs`, slot="editor-label"))**. - -`attrs` = - -| id | rows | cols | aria-label | -|---|---|---|---| -| doc | 16 | 72 | Shared text | - -We **editor = [Describe the native multiline control](component.element(kind="textarea", attrs=`attrs`, slot="editor"))**. -Return *[Keep the field label before its native control](table.concat(a=`label`, b=`editor`))*. diff --git a/examples/web-collab-doc/home.mq.md b/examples/web-collab-doc/home.mq.md deleted file mode 100755 index 42d1bb0..0000000 --- a/examples/web-collab-doc/home.mq.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -markup: occlusion -title: Collaborative page assembly -import: - component: ext/web/component/index.mq.md - client: ext/web/client/index.mq.md - editor: editor.mq.md - status: status.mq.md - fs: lib/fs.mq.md - table: lib/table.mq.md ---- - -The page composes a terminal Markdown introduction, intrinsic native controls and an official runtime Resource. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Complete structured collaborative page | - -The introduction is read as ordinary Markdown from intro.md within the granted site root. The editor and status are independent control leaves, while the script Resource refers to the actual built bridge and WASM files. This assembly describes one page and starts no server or socket. Transport policy remains in serve and client behavior remains in static/client.mq.md. - -We **text = [Read the terminal Markdown introduction](fs.read_text(path="intro.md"))** and **intro = [Describe the introduction as Markdown](component.markdown(text=`text`, slot="intro"))** and **field = [Assemble the independent native editor](editor.nodes())** and **feedback = [Assemble presence and connection status](status.nodes())** and **runtime = [Reference the official client program](client.nodes(source="/static/client.mq.md"))**. -We **body = [Keep introduction before the editor](table.concat(a=`intro`, b=`field`))** and **visible = [Place independent feedback after the field](table.concat(a=`body`, b=`feedback`))**. -Return *[Retain runtime loading as a separate resource](table.concat(a=`visible`, b=`runtime`))*. diff --git a/examples/web-collab-doc/index.mq.md b/examples/web-collab-doc/index.mq.md deleted file mode 100755 index 57a74b3..0000000 --- a/examples/web-collab-doc/index.mq.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Collaborative document — declared layout and room Resource -import: - home: home.mq.md - web: ext/web/web.mq.md - socket: ext/net/websocket.mq.md ---- - -Open two controlled browser tabs to observe complete text snapshots and room presence. This loopback demonstration explicitly permits anonymous room access. It is not durable storage, a CRDT or a history replay service. Build the current browser assets into static before serving. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Collaborative page View rows | - -The Document delegates to the readable page assembly. Follow its imports to the Markdown introduction, native editor and status leaves; none assembles a raw HTML shell. The bridge is a structured Resource. Page assembly reads the selected site root and returns structure before any listener starts. - -Return *[Assemble the native collaborative page](home.nodes())*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-collab-doc" | Explicit site directory relative to the checkout root | -| port | number | 18094 | Loopback server port | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking listener for the declared page and collaboration room | - -Use `root`="examples/web-collab-doc" and `port`=18094. Prepare the page and static mount, bind the network-owned /live/{id} room and its presence channel, then listen with the retained site context. Anonymous access is deliberate for this localhost demonstration; a deployed application should attach authentication and retain private room defaults. The client uses a relative WebSocket address, so changing this port keeps the same page/client contract. - -We **app = [Discover the page and its static resources](web.prepare(root=`root`, host="127.0.0.1", port=`port`, static_dir="static"))** and **app = [Bind the declared snapshot and presence room](socket.route(app=`app`, path="/live/{id}", mode="room", room_key="doc.{id}", presence=True, require_auth=False))**. -Return *[Listen after layout and transport are ready](web.listen(app=`app`))*. diff --git a/examples/web-collab-doc/intro.md b/examples/web-collab-doc/intro.md deleted file mode 100755 index 0ebd7a1..0000000 --- a/examples/web-collab-doc/intro.md +++ /dev/null @@ -1,5 +0,0 @@ -# Shared notepad - -Open this page in **two browser tabs**. Both join `/live/demo` and display native room presence. - -Each edit sends a complete text snapshot. The last received snapshot wins; this demonstration does not store document history or synchronize edits as a CRDT. diff --git a/examples/web-collab-doc/static/client.mq.md b/examples/web-collab-doc/static/client.mq.md deleted file mode 100755 index 02ef459..0000000 --- a/examples/web-collab-doc/static/client.mq.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -markup: occlusion -title: Collaborative client — native text snapshots and presence -import: - browser: lib/browser.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -This program owns document text and event transitions. The Document supplies the native textarea and status leaves; the network resource supplies a same-origin room. All business state stays in Marqdo. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Client wiring, room connection and initial status effects | - -The client keeps only the last locally observed document text in native entry state. Each edit sends a complete DOC-tab-text snapshot; this is a last-received-message demonstration, not a CRDT, document database or history synchronization service. The relative socket path follows the page's host and port, so a different loopback listen port does not require editing client code. Presence and document messages use separate displayed targets. The official bridge changes textarea.value without emitting a new input event, so applying remote text needs no flag that would discard the next real local edit. BrowserSession retains entry bindings between event callbacks. - -We **ws_id = "doc"** and **doc = ""** before connecting. - -`wire` = - -| @ | 选择器 | 事件 | 调用 | 值选择器 | -|---|---|---|---|---| -| 1 | "#doc" | input | on_edit | "#doc" | - -`open` = - -| op | id | url | then_open | then_message | then_error | then_close | -|---|---|---|---|---|---|---| -| open | `ws_id` | /live/demo | on_open | on_msg | on_err | on_close | - -We **wiring = [Bind the existing native textarea](table.put(in=None, at="wire", value=`wire`))** and **socket = [Describe the same-origin room connection](browser.ws(spec=`open`))** and **boot = [Keep wiring and transport together](browser.merge(a=`wiring`, b=`socket`))** and **ready = [Describe the initial connection status](browser.set_text(sel="#log", text="connecting…"))**. -Return *[Keep initial status with the boot instructions](browser.merge(a=`boot`, b=`ready`))*. - -## on_open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Success flag from the bridge's open callback | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Plain connection status effect | - -Use `ok`=True from the open callback. A successful transport opening says that the room is connected; it does not prove that previous document content was replayed. This callback updates only the log. Presence frames arrive independently through on_msg, and actual editing remains available through the existing textarea binding. - -1. `ok` - Return *[Show that the native room connection opened](browser.set_text(sel="#log", text="ws open · room demo"))*. -Return *[Keep an unsuccessful open visible](browser.set_text(sel="#log", text="ws open failed"))*. - -## on_err - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| error | text | "" | Error text supplied by the browser transport | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Plain error text effect | - -Use `error`="" from the bridge. Preserve its text in the status log rather than treating a failed connection as an empty successful document. This callback neither rewrites shared text nor retries a send, so the caller can observe the actual transport state without a hidden duplicate update. - -We **message = "ws error: " + error**. -Return *[Display the actual transport failure as text](browser.set_text(sel="#log", text=`message`))*. - -## on_close - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Closed connection status effect | - -A close notification updates the log while retaining the last displayed document text. This demonstration does not silently reconnect or persist data elsewhere. Reopening the page starts a fresh client session, and subsequent edits need a live socket before peers can receive them. - -Return *[Keep closure visible beside the editor](browser.set_text(sel="#log", text="ws closed"))*. - -## on_edit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | "" | Current plain textarea contents, including an intentionally empty document | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | One complete snapshot send instruction, or None for unchanged text | - -Use `value`="" from the input binding. A changed value replaces the native observed text and becomes one DOC-tab snapshot; an empty value is a valid deletion, not a missing edit. Identical input produces no send. Incoming set_value effects do not emit input, so the next real user edit after a remote update must be sent immediately. The callback describes a browser WebSocket action and opens no native socket itself. - -1. `value` == `doc` - Return *None* because the observed text is unchanged. -We **doc = [Retain the complete new native text](value)** and **payload = "DOC\t" + value**. - -`send` = - -| op | id | data | -|---|---|---| -| send | `ws_id` | `payload` | - -Return *[Send the complete snapshot through the existing room connection](browser.ws(spec=`send`))*. - -## on_msg - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | text | "" | One text frame from the room or its presence channel | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Presence text, a remote textarea value, or None for ignored/echoed frames | - -Use `data`="" from the transport callback. Presence records are displayed separately and never interpreted as document text. A DOC-tab frame contains the entire replacement document, including a possible empty string. Retain that observed text before returning its set_value instruction; an echoed snapshot equal to local state then becomes a no-op. Unknown messages and empty frames leave content unchanged. No JavaScript, HTML or external interpreter parses the document payload. - -1. `data` == "" - Return *None* for an empty frame. -1. [A native presence record](text.starts_with(text=`data`, prefix="{")) - We **message = "presence: " + data**. - Return *[Display room presence independently](browser.set_text(sel="#presence", text=`message`))*. -1. [A complete document snapshot](text.starts_with(text=`data`, prefix="DOC\t")) - We **remote = [Remove only the leading protocol marker](text.replace(text=`data`, old="DOC\t", new="", count=1))**. - 1. `remote` != `doc` - We **doc = [Retain the received native text](remote)**. - Return *[Apply remote text without manufacturing an input event](browser.set_value(sel="#doc", value=`remote`))*. -Otherwise return *None* for unrelated frames or an already observed snapshot. diff --git a/examples/web-collab-doc/status.mq.md b/examples/web-collab-doc/status.mq.md deleted file mode 100755 index 7a2df21..0000000 --- a/examples/web-collab-doc/status.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: Presence and transport status leaves -import: - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -Presence information and connection diagnostics have separate native text targets. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Ordered presence and log leaves | - -Presence frames update one plain-text region, while connection lifecycle messages update a preformatted log. Their stable ids match client callbacks, and neither contains document text or performs transport operations. The parent places these leaves around the independent editor; messages are escaped by the native renderer and later set_text effects. - -`presence_attrs` = - -| id | role | aria-live | -|---|---|---| -| presence | status | polite | - -`log_attrs` = - -| id | role | -|---|---| -| log | log | - -We **presence = [Describe the plain presence target](component.element(kind="text", value="Waiting for peers.", attrs=`presence_attrs`, slot="presence"))** and **log = [Describe connection feedback separately](component.element(kind="pre", value="connecting…", attrs=`log_attrs`, slot="log"))**. -Return *[Keep presence before transport feedback](table.concat(a=`presence`, b=`log`))*. diff --git a/examples/web-layout-handbook-zh/README.md b/examples/web-layout-handbook-zh/README.md deleted file mode 100755 index 50d2254..0000000 --- a/examples/web-layout-handbook-zh/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Layout decomposition reference - -Read [the page](index.mq.md), then follow [components](components/index.mq.md) to -navigation, main and footer. Footer splits into brand and links; links splits -again into docs and community. Every terminal content.md is plain Markdown. -Parent .mq.md files only load/compose child rows and choose one relationship. - -From the repository root, preview with: - -```bash -marqdo run examples/web-layout-handbook-zh/preview.mq.md -``` - -To serve, change into this directory, then run: - -```bash -marqdo run serve.mq.md -``` - -Check /, /about and /api/ping. Geometry comes from the runtime's row/column -containers. No authored HTML or CSS is needed. view: main is evaluated once at -startup; restart after edits. Request-time interaction belongs in Endpoints. diff --git a/examples/web-layout-handbook-zh/api/ping.mq.md b/examples/web-layout-handbook-zh/api/ping.mq.md deleted file mode 100755 index bee4f0c..0000000 --- a/examples/web-layout-handbook-zh/api/ping.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -类型: 端点 -路径: /api/ping -方法: GET -请求: none -响应: json ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -`result` = - -| ok | ping | -|----|------| -| True | pong | - -After these steps, return *result*. diff --git a/examples/web-layout-handbook-zh/components/footer/brand/content.md b/examples/web-layout-handbook-zh/components/footer/brand/content.md deleted file mode 100755 index 00a8c58..0000000 --- a/examples/web-layout-handbook-zh/components/footer/brand/content.md +++ /dev/null @@ -1,3 +0,0 @@ -### Marqdo - -代码即文档,文档即可执行。 diff --git a/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md b/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md deleted file mode 100755 index e945e6f..0000000 --- a/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -import: - 文件: lib/文件.mq.md - 组件: ext/web/网页/组件/索引.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -此叶子只负责footer/brand 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md, -不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。 - -We first **body = [Compute body](文件.读文本(路径="components/footer/brand/content.md"))** for the next step. -After these steps, return *组件.正文(文本=`body`, 槽="footer-brand")*. diff --git a/examples/web-layout-handbook-zh/components/footer/index.mq.md b/examples/web-layout-handbook-zh/components/footer/index.mq.md deleted file mode 100755 index c264b90..0000000 --- a/examples/web-layout-handbook-zh/components/footer/index.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -import: - 组件: ext/web/网页/组件/索引.mq.md - 布局: ext/web/布局/索引.mq.md - brand: ./brand/index.mq.md - links: ./links/index.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Nested child rows | - -本层只安排品牌内容与链接子树之间的关系,正文仍留在对应 Markdown 叶子中。 -若子块仍含独立分栏,就继续沿对应目录的 index.mq.md 分解。 -不要把渲染后的字符串放回值列,子节点在整个装配过程中保持结构。 - -We first **brand_nodes = [Compute brand_nodes](brand.节点())** for the next step. -We first **links_nodes = [Compute links_nodes](links.节点())** for the next step. -We first **siblings = [Compute siblings](组件.合并(甲=`brand_nodes`, 乙=`links_nodes`))** for the next step. -We first **footer_columns = [Compute footer_columns](布局.分栏(子节点=`siblings`, 槽="footer"))** for the next step. -After these steps, return *组件.包裹(子节点=`footer_columns`, 种类="footer", 槽="footer")*. diff --git a/examples/web-layout-handbook-zh/components/footer/links/community/content.md b/examples/web-layout-handbook-zh/components/footer/links/community/content.md deleted file mode 100755 index c27d443..0000000 --- a/examples/web-layout-handbook-zh/components/footer/links/community/content.md +++ /dev/null @@ -1,5 +0,0 @@ -### 社区 - -[关于项目](/about) - -[返回首页](/) diff --git a/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md deleted file mode 100755 index d2b964e..0000000 --- a/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -import: - 文件: lib/文件.mq.md - 组件: ext/web/网页/组件/索引.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -此叶子只负责footer/links/community 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md, -不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。 - -We first **body = [Compute body](文件.读文本(路径="components/footer/links/community/content.md"))** for the next step. -After these steps, return *组件.正文(文本=`body`, 槽="footer-links-community")*. diff --git a/examples/web-layout-handbook-zh/components/footer/links/docs/content.md b/examples/web-layout-handbook-zh/components/footer/links/docs/content.md deleted file mode 100755 index 7dc424a..0000000 --- a/examples/web-layout-handbook-zh/components/footer/links/docs/content.md +++ /dev/null @@ -1,5 +0,0 @@ -### 文档 - -[开发手册](/about) - -[服务状态](/api/ping) diff --git a/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md deleted file mode 100755 index fd230f6..0000000 --- a/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -import: - 文件: lib/文件.mq.md - 组件: ext/web/网页/组件/索引.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -此叶子只负责footer/links/docs 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md, -不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。 - -We first **body = [Compute body](文件.读文本(路径="components/footer/links/docs/content.md"))** for the next step. -After these steps, return *组件.正文(文本=`body`, 槽="footer-links-docs")*. diff --git a/examples/web-layout-handbook-zh/components/footer/links/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/index.mq.md deleted file mode 100755 index e95bf7c..0000000 --- a/examples/web-layout-handbook-zh/components/footer/links/index.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -import: - 组件: ext/web/网页/组件/索引.mq.md - 布局: ext/web/布局/索引.mq.md - docs: ./docs/index.mq.md - community: ./community/index.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Nested child rows | - -本层只安排文档链接与社区链接之间的关系,正文仍留在对应 Markdown 叶子中。 -若子块仍含独立分栏,就继续沿对应目录的 index.mq.md 分解。 -不要把渲染后的字符串放回值列,子节点在整个装配过程中保持结构。 - -We first **docs_nodes = [Compute docs_nodes](docs.节点())** for the next step. -We first **community_nodes = [Compute community_nodes](community.节点())** for the next step. -We first **siblings = [Compute siblings](组件.合并(甲=`docs_nodes`, 乙=`community_nodes`))** for the next step. -After these steps, return *布局.分栏(子节点=`siblings`, 槽="footer-links")*. diff --git a/examples/web-layout-handbook-zh/components/index.mq.md b/examples/web-layout-handbook-zh/components/index.mq.md deleted file mode 100755 index e407dfc..0000000 --- a/examples/web-layout-handbook-zh/components/index.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion -import: - 组件: ext/web/网页/组件/索引.mq.md - 布局: ext/web/布局/索引.mq.md - nav: ./nav/index.mq.md - content: ./main/index.mq.md - footer: ./footer/index.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Nested child rows | - -本层只安排导航、主体、页脚之间的关系,正文仍留在对应 Markdown 叶子中。 -若子块仍含独立分栏,就继续沿对应目录的 index.mq.md 分解。 -不要把渲染后的字符串放回值列,子节点在整个装配过程中保持结构。 - -We first **nav_nodes = [Compute nav_nodes](nav.节点())** for the next step. -We first **content_nodes = [Compute content_nodes](content.节点())** for the next step. -We first **footer_nodes = [Compute footer_nodes](footer.节点())** for the next step. -We first **upper_regions = [Compute upper_regions](组件.合并(甲=`nav_nodes`, 乙=`content_nodes`))** for the next step. -We first **home_regions = [Compute home_regions](组件.合并(甲=`upper_regions`, 乙=`footer_nodes`))** for the next step. -After these steps, return *布局.纵排(子节点=`home_regions`, 槽="home")*. diff --git a/examples/web-layout-handbook-zh/components/main/content.md b/examples/web-layout-handbook-zh/components/main/content.md deleted file mode 100755 index 1f3fc5a..0000000 --- a/examples/web-layout-handbook-zh/components/main/content.md +++ /dev/null @@ -1,3 +0,0 @@ -# 可执行文档站点 - -先拆布局,再写内容。**叶子只负责 Markdown。** diff --git a/examples/web-layout-handbook-zh/components/main/index.mq.md b/examples/web-layout-handbook-zh/components/main/index.mq.md deleted file mode 100755 index 88c7b74..0000000 --- a/examples/web-layout-handbook-zh/components/main/index.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -import: - 文件: lib/文件.mq.md - 组件: ext/web/网页/组件/索引.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -此叶子只负责main 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md, -不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。 - -We first **body = [Compute body](文件.读文本(路径="components/main/content.md"))** for the next step. -After these steps, return *组件.正文(文本=`body`, 槽="main")*. diff --git a/examples/web-layout-handbook-zh/components/nav/content.md b/examples/web-layout-handbook-zh/components/nav/content.md deleted file mode 100755 index 0f54236..0000000 --- a/examples/web-layout-handbook-zh/components/nav/content.md +++ /dev/null @@ -1 +0,0 @@ -[首页](/) · [关于](/about) · [状态](/api/ping) diff --git a/examples/web-layout-handbook-zh/components/nav/index.mq.md b/examples/web-layout-handbook-zh/components/nav/index.mq.md deleted file mode 100755 index 0e0ad07..0000000 --- a/examples/web-layout-handbook-zh/components/nav/index.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -import: - 文件: lib/文件.mq.md - 组件: ext/web/网页/组件/索引.mq.md ---- - -## 节点 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -此叶子只负责nav 的 Markdown 内容,父组件决定排列。修改文字只改相邻 content.md, -不添加 HTML 标签或内部分栏;出现第二种布局职责时再开子目录。 - -We first **body = [Compute body](文件.读文本(路径="components/nav/content.md"))** for the next step. -After these steps, return *组件.正文(文本=`body`, 槽="nav")*. diff --git a/examples/web-layout-handbook-zh/index.mq.md b/examples/web-layout-handbook-zh/index.mq.md deleted file mode 100755 index d7555ad..0000000 --- a/examples/web-layout-handbook-zh/index.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -类型: 网页 -视图: main -标题: Marqdo 布局实践 -路由: / -import: - home: ./components/index.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -页面只选择布局根,具体拆分沿 components/index.mq.md 继续。 -此主程序返回结构而不是 HTML;view 元数据让服务在启动时执行它。 - -After these steps, return *home.节点()*. diff --git a/examples/web-layout-handbook-zh/pages/about.mq.md b/examples/web-layout-handbook-zh/pages/about.mq.md deleted file mode 100755 index c321ac8..0000000 --- a/examples/web-layout-handbook-zh/pages/about.mq.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -markup: occlusion -类型: 网页 -标题: 关于 -路由: /about ---- - -# 关于 - - -这是普通 Markdown Document,不执行布局函数。 diff --git a/examples/web-layout-handbook-zh/preview.mq.md b/examples/web-layout-handbook-zh/preview.mq.md deleted file mode 100755 index 81304e0..0000000 --- a/examples/web-layout-handbook-zh/preview.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: 可直接调用的布局预览 -import: - home: ./components/index.mq.md - 网页: ext/web/网页.mq.md ---- - -预览从站点组件根开始,不拼接另一份页面。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 与原有运行输出一致的 HTML 文本 | - -本函数既可以用 marqdo call 直接取得 HTML 返回值,也保留 marqdo run 原有的预览输出。组件内容相对站点根目录读取,因此从仓库根调用时应将 --fs-root 指向 examples/web-layout-handbook-zh,并授予 fs.read、plugin 和 output.write。预览不会开启网络监听,也不修改内容文件;线上服务与本函数共享节点渲染器,页脚左右区域和嵌套链接列应保持一致。检查返回的 HTML 不能代替浏览器中的布局和交互验证。 - -我们 **nodes = [沿组件入口装配全部布局](home.节点())**,再 **html = [使用线上相同的节点渲染器](网页.渲染(节点=`nodes`, 标题="Marqdo 布局实践"))**。 -我们 **[为原有运行预览输出页面](打印(内容=`html`))**,随后直接返回 *html*。 diff --git a/examples/web-layout-handbook-zh/serve.mq.md b/examples/web-layout-handbook-zh/serve.mq.md deleted file mode 100755 index f9e12a9..0000000 --- a/examples/web-layout-handbook-zh/serve.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -import: - 网页: ext/web/网页.mq.md ---- - -# main - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 端口 | any | 18081 | 本地 HTTP 监听端口;服务启动后持续运行直到调用方停止 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -端口 `端口`=18081 可通过 --bind 覆盖。启动器不包含页面布局。 - -We first **监听端口 = [Compute 监听端口](整数(值=`端口`))** for the next step. -We now **[Call 网页.服务](> 网页.服务 根="." 主机="127.0.0.1" 端口=`监听端口`)**. diff --git a/examples/web-layout-handbook/README.md b/examples/web-layout-handbook/README.md deleted file mode 100755 index f904aac..0000000 --- a/examples/web-layout-handbook/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Layout decomposition reference - -Read [the page](index.mq.md), then follow [components](components/index.mq.md) to -navigation, main and footer. Footer splits into brand and links; links splits -again into docs and community. Every terminal content.md is plain Markdown. -Parent .mq.md files only load/compose child rows and choose one relationship. - -From the repository root, preview with: - -```bash -marqdo run examples/web-layout-handbook/preview.mq.md -``` - -To serve, change into this directory, then run: - -```bash -marqdo run serve.mq.md -``` - -Check /, /about and /api/ping. Geometry comes from the runtime's row/column -containers. No authored HTML or CSS is needed. view: main is evaluated once at -startup; restart after edits. Request-time interaction belongs in Endpoints. diff --git a/examples/web-layout-handbook/api/ping.mq.md b/examples/web-layout-handbook/api/ping.mq.md deleted file mode 100755 index c788372..0000000 --- a/examples/web-layout-handbook/api/ping.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -type: endpoint -path: /api/ping -method: GET -request: none -response: json ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -`result` = - -| ok | ping | -|----|------| -| True | pong | - -After these steps, return *result*. diff --git a/examples/web-layout-handbook/components/footer/brand/content.md b/examples/web-layout-handbook/components/footer/brand/content.md deleted file mode 100755 index 43904ad..0000000 --- a/examples/web-layout-handbook/components/footer/brand/content.md +++ /dev/null @@ -1,3 +0,0 @@ -### Marqdo - -Code is documentation. Documents are executable. diff --git a/examples/web-layout-handbook/components/footer/brand/index.mq.md b/examples/web-layout-handbook/components/footer/brand/index.mq.md deleted file mode 100755 index 51f36f0..0000000 --- a/examples/web-layout-handbook/components/footer/brand/index.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -import: - fs: lib/fs.mq.md - component: ext/web/component/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -This leaf owns only the footer/brand Markdown content; its parent owns placement. -Edit adjacent content.md to change prose. Add a child directory when a second -layout responsibility appears instead of introducing HTML into the content. - -We first **body = [Compute body](fs.read_text(path="components/footer/brand/content.md"))** for the next step. -After these steps, return *component.markdown(text=`body`, slot="footer-brand")*. diff --git a/examples/web-layout-handbook/components/footer/index.mq.md b/examples/web-layout-handbook/components/footer/index.mq.md deleted file mode 100755 index 783af90..0000000 --- a/examples/web-layout-handbook/components/footer/index.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -import: - component: ext/web/component/index.mq.md - layout: ext/web/layout/index.mq.md - brand: ./brand/index.mq.md - links: ./links/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Nested child rows | - -This parent arranges brand content and the link-region subtree. Content stays -in their Markdown leaves; this file owns their one placement relationship. Continue into each child index when another independent layout -remains. Preserve node lists rather than rendering children into HTML strings. - -We first **brand_nodes = [Compute brand_nodes](brand.nodes())** for the next step. -We first **links_nodes = [Compute links_nodes](links.nodes())** for the next step. -We first **siblings = [Compute siblings](component.merge(a=`brand_nodes`, b=`links_nodes`))** for the next step. -We first **footer_columns = [Compute footer_columns](layout.columns(children=`siblings`, slot="footer"))** for the next step. -After these steps, return *component.wrap(children=`footer_columns`, kind="footer", slot="footer")*. diff --git a/examples/web-layout-handbook/components/footer/links/community/content.md b/examples/web-layout-handbook/components/footer/links/community/content.md deleted file mode 100755 index fef6043..0000000 --- a/examples/web-layout-handbook/components/footer/links/community/content.md +++ /dev/null @@ -1,5 +0,0 @@ -### Community - -[About the project](/about) - -[Return home](/) diff --git a/examples/web-layout-handbook/components/footer/links/community/index.mq.md b/examples/web-layout-handbook/components/footer/links/community/index.mq.md deleted file mode 100755 index b2a15e9..0000000 --- a/examples/web-layout-handbook/components/footer/links/community/index.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -import: - fs: lib/fs.mq.md - component: ext/web/component/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -This leaf owns only the footer/links/community Markdown content; its parent owns placement. -Edit adjacent content.md to change prose. Add a child directory when a second -layout responsibility appears instead of introducing HTML into the content. - -We first **body = [Compute body](fs.read_text(path="components/footer/links/community/content.md"))** for the next step. -After these steps, return *component.markdown(text=`body`, slot="footer-links-community")*. diff --git a/examples/web-layout-handbook/components/footer/links/docs/content.md b/examples/web-layout-handbook/components/footer/links/docs/content.md deleted file mode 100755 index d96f030..0000000 --- a/examples/web-layout-handbook/components/footer/links/docs/content.md +++ /dev/null @@ -1,5 +0,0 @@ -### Documentation - -[Handbook](/about) - -[Service status](/api/ping) diff --git a/examples/web-layout-handbook/components/footer/links/docs/index.mq.md b/examples/web-layout-handbook/components/footer/links/docs/index.mq.md deleted file mode 100755 index 5843b34..0000000 --- a/examples/web-layout-handbook/components/footer/links/docs/index.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -import: - fs: lib/fs.mq.md - component: ext/web/component/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -This leaf owns only the footer/links/docs Markdown content; its parent owns placement. -Edit adjacent content.md to change prose. Add a child directory when a second -layout responsibility appears instead of introducing HTML into the content. - -We first **body = [Compute body](fs.read_text(path="components/footer/links/docs/content.md"))** for the next step. -After these steps, return *component.markdown(text=`body`, slot="footer-links-docs")*. diff --git a/examples/web-layout-handbook/components/footer/links/index.mq.md b/examples/web-layout-handbook/components/footer/links/index.mq.md deleted file mode 100755 index d94bf86..0000000 --- a/examples/web-layout-handbook/components/footer/links/index.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -import: - component: ext/web/component/index.mq.md - layout: ext/web/layout/index.mq.md - docs: ./docs/index.mq.md - community: ./community/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Nested child rows | - -This parent arranges documentation links and community links. Content stays -in their Markdown leaves; this file owns their one placement relationship. Continue into each child index when another independent layout -remains. Preserve node lists rather than rendering children into HTML strings. - -We first **docs_nodes = [Compute docs_nodes](docs.nodes())** for the next step. -We first **community_nodes = [Compute community_nodes](community.nodes())** for the next step. -We first **siblings = [Compute siblings](component.merge(a=`docs_nodes`, b=`community_nodes`))** for the next step. -After these steps, return *layout.columns(children=`siblings`, slot="footer-links")*. diff --git a/examples/web-layout-handbook/components/index.mq.md b/examples/web-layout-handbook/components/index.mq.md deleted file mode 100755 index e48a373..0000000 --- a/examples/web-layout-handbook/components/index.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion -import: - component: ext/web/component/index.mq.md - layout: ext/web/layout/index.mq.md - nav: ./nav/index.mq.md - content: ./main/index.mq.md - footer: ./footer/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Nested child rows | - -This parent arranges navigation, main content and footer. Content stays -in their Markdown leaves; this file owns their one placement relationship. Continue into each child index when another independent layout -remains. Preserve node lists rather than rendering children into HTML strings. - -We first **nav_nodes = [Compute nav_nodes](nav.nodes())** for the next step. -We first **content_nodes = [Compute content_nodes](content.nodes())** for the next step. -We first **footer_nodes = [Compute footer_nodes](footer.nodes())** for the next step. -We first **upper_regions = [Compute upper_regions](component.merge(a=`nav_nodes`, b=`content_nodes`))** for the next step. -We first **home_regions = [Compute home_regions](component.merge(a=`upper_regions`, b=`footer_nodes`))** for the next step. -After these steps, return *layout.stack(children=`home_regions`, slot="home")*. diff --git a/examples/web-layout-handbook/components/main/content.md b/examples/web-layout-handbook/components/main/content.md deleted file mode 100755 index a8c6fa6..0000000 --- a/examples/web-layout-handbook/components/main/content.md +++ /dev/null @@ -1,3 +0,0 @@ -# Executable documents - -Split the layout before writing content. **Leaves own Markdown only.** diff --git a/examples/web-layout-handbook/components/main/index.mq.md b/examples/web-layout-handbook/components/main/index.mq.md deleted file mode 100755 index 80b39c6..0000000 --- a/examples/web-layout-handbook/components/main/index.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -import: - fs: lib/fs.mq.md - component: ext/web/component/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -This leaf owns only the main Markdown content; its parent owns placement. -Edit adjacent content.md to change prose. Add a child directory when a second -layout responsibility appears instead of introducing HTML into the content. - -We first **body = [Compute body](fs.read_text(path="components/main/content.md"))** for the next step. -After these steps, return *component.markdown(text=`body`, slot="main")*. diff --git a/examples/web-layout-handbook/components/nav/content.md b/examples/web-layout-handbook/components/nav/content.md deleted file mode 100755 index b247075..0000000 --- a/examples/web-layout-handbook/components/nav/content.md +++ /dev/null @@ -1 +0,0 @@ -[Home](/) · [About](/about) · [Status](/api/ping) diff --git a/examples/web-layout-handbook/components/nav/index.mq.md b/examples/web-layout-handbook/components/nav/index.mq.md deleted file mode 100755 index e769907..0000000 --- a/examples/web-layout-handbook/components/nav/index.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -import: - fs: lib/fs.mq.md - component: ext/web/component/index.mq.md ---- - -## nodes - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Markdown leaf rows | - -This leaf owns only the nav Markdown content; its parent owns placement. -Edit adjacent content.md to change prose. Add a child directory when a second -layout responsibility appears instead of introducing HTML into the content. - -We first **body = [Compute body](fs.read_text(path="components/nav/content.md"))** for the next step. -After these steps, return *component.markdown(text=`body`, slot="nav")*. diff --git a/examples/web-layout-handbook/index.mq.md b/examples/web-layout-handbook/index.mq.md deleted file mode 100755 index e91d2b9..0000000 --- a/examples/web-layout-handbook/index.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -type: web -view: main -title: Marqdo layout handbook -route: / -import: - home: ./components/index.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -The page selects the layout root; follow components/index.mq.md for decomposition. -This main returns rows rather than HTML; view metadata opts into startup assembly. - -After these steps, return *home.nodes()*. diff --git a/examples/web-layout-handbook/pages/about.mq.md b/examples/web-layout-handbook/pages/about.mq.md deleted file mode 100755 index 630d261..0000000 --- a/examples/web-layout-handbook/pages/about.mq.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -markup: occlusion -type: web -title: About -route: /about ---- - -# About - -An ordinary Markdown Document keeps its original rendering path. diff --git a/examples/web-layout-handbook/preview.mq.md b/examples/web-layout-handbook/preview.mq.md deleted file mode 100755 index 453201a..0000000 --- a/examples/web-layout-handbook/preview.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: Callable preview of the actual layout tree -import: - home: ./components/index.mq.md - web: ext/web/web.mq.md ---- - -Preview begins at the site component root and shares its renderer with the server. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | HTML text identical to the existing printed preview | - -Call this ordinary main function to obtain the actual HTML value; run still prints the same preview for existing callers. Markdown leaves are read relative to the granted site root, so use --fs-root examples/web-layout-handbook from the checkout root, with fs.read, plugin and output.write. Preview opens no listener and changes no content. The same node renderer serves the Document, including both footer regions and the nested link columns. Inspecting this returned HTML does not replace browser geometry or interaction checks. - -We **nodes = [Assemble the complete component tree](home.nodes())**, then **html = [Use the same node renderer as the served Document](web.render(nodes=`nodes`, title="Marqdo layout handbook"))**. -We **[Keep the existing run preview output](print(text=`html`))**, then return *html*. diff --git a/examples/web-layout-handbook/serve.mq.md b/examples/web-layout-handbook/serve.mq.md deleted file mode 100755 index 1930589..0000000 --- a/examples/web-layout-handbook/serve.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -import: - web: ext/web/web.mq.md ---- - -# main - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| port | any | 18081 | Local HTTP listening port; starting the server owns its lifecycle until stopped | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -The `port`=18081 may be overridden with --bind. This launcher owns no layout. - -We first **listen_port = [Compute listen_port](int(value=`port`))** for the next step. -We now **[Call web.serve](> web.serve root="." host="127.0.0.1" port=`listen_port`)**. diff --git a/examples/web-net-site-zh/README.md b/examples/web-net-site-zh/README.md deleted file mode 100755 index 0190205..0000000 --- a/examples/web-net-site-zh/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# web-net-site-zh - -本工程保留文章列表、关于页、文章表单、Cookie/Multipart 工具页、登录后的原生管理后台,以及 /live WebSocket 回显。中文作者使用网页、表单、后台、鉴权和实时资源入口。页面递归组合到 Markdown 和原生控件;浏览器交互由 public/client.mq.md 表达,旧 public/live.js 已被实际验证后的 Marqdo 客户端替代。 - -从仓库根目录准备当前 CLI 与工程插件后,使用同一份开发手册构建 Web 和浏览器运行时: - -```sh -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json -target/debug/marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-net-site-zh/public/generated"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json -target/debug/marqdo call examples/web-net-site-zh/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-net-site-zh --require-ok --json -``` - -打开 http://127.0.0.1:18084。默认数据库位于站点文件根的 data/site-net-zh.db,重启保留已有文章。缺少兼容 WASM 目标时,先按 [工具链任务](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,再把返回的 compiler 传给 build_browser。 - -- [布局入口](components/index.mq.md) 组合导航、侧栏、主体和页脚,叶子在 components/content。 -- [文章表单](forms.mq.md) 统一定义字段与服务端规则;校验失败后保留真实 CSRF,成功回到文章列表。 -- [工具页](pages/tools.mq.md) 展示真实网络解析结果,不请求远端服务。 -- [客户端](public/client.mq.md) 保留按钮与 Enter 发送、去除首尾空白、忽略空输入及连续回显日志。 -- 管理后台登录使用本机演示账号 admin / secret。部署时替换账号与访问策略。 - -请求资源沿用五列 View;数据库查询随每次请求更新,表单引用解析当前会话。详情见 [请求资源设计](../../doc/design/web-view-resources.md)。 - -开发入口的 test_browser 使用实际当前 WASM 验证回显、表单重试、新增文章、后台登录与窄屏布局。HTTP 回归 web_handbook 在 Tree 与 Bytecode 两个后端启动临时站点,验证数据和鉴权,避免操作用户数据库。 diff --git a/examples/web-net-site-zh/components/content/about.md b/examples/web-net-site-zh/components/content/about.md deleted file mode 100755 index cf07779..0000000 --- a/examples/web-net-site-zh/components/content/about.md +++ /dev/null @@ -1,5 +0,0 @@ -# 关于 - -演示网络扩展后的网页库:会话、登录鉴权、WebSocket,以及 multipart 与 Cookie 解析。 - -各个职责都有独立模块:父组件组合布局,叶子使用 Markdown,数据与表单在请求期间读取当前状态。 diff --git a/examples/web-net-site-zh/components/content/foot.md b/examples/web-net-site-zh/components/content/foot.md deleted file mode 100755 index e579e6b..0000000 --- a/examples/web-net-site-zh/components/content/foot.md +++ /dev/null @@ -1 +0,0 @@ -[Marqdo 网络扩展示例](https://github.com) · [文档](/tools) diff --git a/examples/web-net-site-zh/components/content/home.md b/examples/web-net-site-zh/components/content/home.md deleted file mode 100755 index 3fb6ea4..0000000 --- a/examples/web-net-site-zh/components/content/home.md +++ /dev/null @@ -1,3 +0,0 @@ -# 网络扩展站 - -SQLite 文章列表、WebSocket 实时小部件、登录门禁后台,以及标准网络库的解析工具。 diff --git a/examples/web-net-site-zh/components/content/multipart.txt b/examples/web-net-site-zh/components/content/multipart.txt deleted file mode 100755 index f1882fd..0000000 --- a/examples/web-net-site-zh/components/content/multipart.txt +++ /dev/null @@ -1,10 +0,0 @@ ---net-boundary -Content-Disposition: form-data; name="title" - -你好 ---net-boundary -Content-Disposition: form-data; name="cover"; filename="pic.png" -Content-Type: image/png - -<字节> ---net-boundary-- diff --git a/examples/web-net-site-zh/components/content/nav.md b/examples/web-net-site-zh/components/content/nav.md deleted file mode 100755 index 9ea33ac..0000000 --- a/examples/web-net-site-zh/components/content/nav.md +++ /dev/null @@ -1 +0,0 @@ -[首页](/) · [关于](/about) · [发布](/new) · [工具](/tools) · [后台](/admin) diff --git a/examples/web-net-site-zh/components/content/new.md b/examples/web-net-site-zh/components/content/new.md deleted file mode 100755 index 1fb44b9..0000000 --- a/examples/web-net-site-zh/components/content/new.md +++ /dev/null @@ -1,3 +0,0 @@ -# 发布 - -表单按共享规则校验后插入 articles 表,成功返回首页。标题必填,正文可空。 diff --git a/examples/web-net-site-zh/components/content/side.md b/examples/web-net-site-zh/components/content/side.md deleted file mode 100755 index 0fff560..0000000 --- a/examples/web-net-site-zh/components/content/side.md +++ /dev/null @@ -1,7 +0,0 @@ -## 功能导航 - -- [文章](/) -- [WebSocket](/#live) -- [登录鉴权](/admin) -- [表单](/new) -- [lib/net](/tools) diff --git a/examples/web-net-site-zh/components/foot.mq.md b/examples/web-net-site-zh/components/foot.mq.md deleted file mode 100755 index 284ec12..0000000 --- a/examples/web-net-site-zh/components/foot.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: 页脚的 Markdown 内容组件 -import: - 组件: ext/web/网页/组件/索引.mq.md - 文件: lib/文件.mq.md ---- - -页脚保留原示例的项目链接与工具文档入口。本块只有一组简单链接,没有双栏布局;将来出现独立品牌栏与链接栏时再继续拆成两个子组件。 - -## 页脚 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 包含终端 Markdown 的单个语义区域 | - -本组件只拥有本块内容与语义容器。以站点为 --fs-root 授予 fs.read,正文读取相邻内容目录的 Markdown 叶子,不查询记录或启动服务器。父布局决定本块位置;修改文字与链接只编辑叶子。保留稳定槽名与样式类,使片段和主题继续找到本区域,内容不会先被渲染成不透明字符串。 - -我们 **文本 = [读取本区域的终端 Markdown](文件.读文本(路径="components/content/foot.md"))** 和 **叶子 = [保持简单 Markdown 内容](组件.正文(文本=`文本`, 槽="foot-content"))**。 -准备好内容后返回 *[保留这一块的语义与样式](组件.包裹(子节点=`叶子`, 种类="footer", 槽="foot", 样式="foot"))*。 diff --git a/examples/web-net-site-zh/components/home.mq.md b/examples/web-net-site-zh/components/home.mq.md deleted file mode 100755 index 3791127..0000000 --- a/examples/web-net-site-zh/components/home.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: 首页主体的三个独立职责 -import: - 组件: ext/web/网页/组件/索引.mq.md - 视图: ext/data/视图.mq.md - 实时: live.mq.md - 文件: lib/文件.mq.md - 表: lib/表.mq.md ---- - -首页主体继续拆为介绍、原生实时控件和当前文章查询。介绍是静态 Markdown,控件交互归浏览器程序,文章由每个真实请求查询。父模块只保留这三个责任的顺序。 - -## 节点 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 介绍、实时控件与请求期间文章查询的结构节点 | - -只在启动阶段装配页面结构,授予 fs.read 以读取介绍。文章资源使用监听应用绑定的同一个 articles 表,按 id 排序;发布新文章后下一次请求直接查询当前记录,不保留旧的启动列表。查询描述是纯数据,不从猜测的相对文件名另开数据库。回显的运输路由由服务入口绑定,构造控件不会打开连接。 - -我们 **文本 = [读取首页介绍](文件.读文本(路径="components/content/home.md"))**、**介绍 = [保留终端 Markdown](组件.正文(文本=`文本`, 槽="intro"))** 和 **控件 = [组合实时交互区域](实时.节点())**。 -接着 **查询 = [描述当前业务文章](视图.查询(源="articles", 排序="id", 链接前缀=""))** 和 **文章 = [安放动态查询资源](组件.请求资源(值=`查询`, 槽="articles"))**。 -我们 **正文 = [介绍位于交互之前](表.拼接(a=`介绍`, b=`控件`))**,最后返回 *[把当前文章放在交互之后](表.拼接(a=`正文`, b=`文章`))*。 diff --git a/examples/web-net-site-zh/components/index.mq.md b/examples/web-net-site-zh/components/index.mq.md deleted file mode 100755 index ca95e04..0000000 --- a/examples/web-net-site-zh/components/index.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: 网络站点的递归布局入口 -import: - 组件: ext/web/网页/组件/索引.mq.md - 导航: nav.mq.md - 侧栏: side.mq.md - 页脚: foot.mq.md - 表: lib/表.mq.md ---- - -本入口只管理各块的位置关系。先拆导航、侧栏与主体行、页脚,再由子模块读终端 Markdown。请求期间的查询和表单保留在主体内,不把渲染结果拼回 HTML 字符串。调整文案沿子模块找到内容叶子,调整几何只修改本层。 - -## 框架 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 正文 | list | 必填 | 页面自身已经构造的主体节点 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 有序导航、侧栏/主体双栏、页脚与主题资源 | - -输入`正文`,本层不查询数据库、不验证身份,也不负责启动监听。侧栏和主体是行容器的两个子块,窄屏折叠由已有 View 运行时负责。节点始终保留结构值,主题只引用 serve 已编译并写入的文件;纯构造不会读取或下载样式。共享 Markdown 的读取需要 fs.read。 - -我们 **顶部 = [读取导航内容](导航.导航())** 和 **旁栏 = [读取侧栏内容](侧栏.侧栏())**,**主体 = [给页面正文稳定区域名](组件.包裹(子节点=`正文`, 种类="column", 槽="main"))**。 -接着 **双栏 = [保留侧栏与主体的兄弟关系](表.拼接(a=`旁栏`, b=`主体`))**、**中部 = [声明响应式横向几何](组件.包裹(子节点=`双栏`, 种类="row", 槽="page-body"))** 和 **底部 = [读取结束链接](页脚.页脚())**。 -我们 **页面 = [导航位于内容之前](表.拼接(a=`顶部`, b=`中部`))**、**页面 = [页脚位于内容之后](表.拼接(a=`页面`, b=`底部`))** 和 **样式 = [引用明确生成的声明式主题](组件.资源(地址="/static/generated/theme.css", 种类="stylesheet"))**。 -完成布局后返回 *[让结构与样式资源一起保留](表.拼接(a=`页面`, b=`样式`))*。 diff --git a/examples/web-net-site-zh/components/live.mq.md b/examples/web-net-site-zh/components/live.mq.md deleted file mode 100755 index 442b523..0000000 --- a/examples/web-net-site-zh/components/live.mq.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -markup: occlusion -title: 原生 WebSocket 控件叶子 -import: - 组件: ext/web/网页/组件/索引.mq.md - 客户端: ext/web/网页/客户端/索引.mq.md - 表: lib/表.mq.md ---- - -本区域拆到简单 Markdown 与原生控件即停止,不写 HTML 或业务 JavaScript。浏览器客户端负责事件与状态,服务入口负责 /live 运输。控件标识是双方契约,修改文案时保留这些标识。 - -## _状态 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 独立的连接状态文本目标 | - -连接与消息是两个不同的反馈区域。状态使用稳定 live-status 标识及礼貌的辅助通知,初始文字不表示已连接。真实连接的开、错、关由浏览器客户端更新。本构造是纯计算,不加载运行时或尝试网络;状态文字按文本转义,不能变成页面结构。 - -`属性` = - -| id | aria-live | -|---|---| -| live-status | polite | - -我们返回 *[创建独立的连接反馈目标](组件.控件(种类="text", 值="正在连接…", 属性=`属性`, 槽="live-status"))*。 - -## _操作 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 输入与发送按钮组成的响应式行 | - -输入提供消息值,按钮启动时使用真实布尔 disabled,只有连接成功后才移除该属性。字符串 false 仍会让 HTML 布尔属性存在,因此不能用它替代 False。控件 id 和客户端事件绑定一致,标题可改,标识应同步修改。 - -这两个叶子已经无法再拆成 Markdown,因为需要原生输入与点击目标。横向排列仍交给统一 View 行容器,窄屏按运行时规则折叠;这里不固定像素宽度、不安装事件处理器,也不在构造期间发送任何消息。按钮显式 type=button,因此嵌入其他内容时不会意外触发表单提交;placeholder 只提示输入,不作为实际消息值。 - -`输入属性` = - -| id | placeholder | type | -|---|---|---| -| live-msg | 输入一条消息… | text | - -`按钮属性` = - -| id | type | disabled | -|---|---|---| -| live-send | button | True | - -我们 **输入 = [声明原生消息输入框](组件.控件(种类="input", 属性=`输入属性`, 槽="live-input"))** 和 **按钮 = [连接前保持发送禁用](组件.控件(种类="button", 值="发送", 属性=`按钮属性`, 槽="live-send"))**。 -随后 **操作 = [保持输入与发送相邻](表.拼接(a=`输入`, b=`按钮`))**,最后返回 *[声明可折叠的操作行](组件.包裹(子节点=`操作`, 种类="row", 槽="live-controls"))*。 - -## _输出 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 保留纯文本回显的预格式区域 | - -消息由客户端收到真实帧后追加,页面构造不伪造初始回显。pre 保留换行,稳定 live-out 标识供文本效果更新;辅助通知采用 polite,避免将输入误当作实时状态。尖括号、引号与协议内容都应显示字面字符,不能通过设 HTML 展示。 - -`属性` = - -| id | aria-live | -|---|---| -| live-out | polite | - -结构明确后返回 *[创建转义文本消息目标](组件.控件(种类="pre", 属性=`属性`, 槽="live-output"))*。 - -## 节点 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 实时区域的标题、状态、操作、输出与官方桥资源 | - -本层只确定四个子块的顺序,终端控件由上面三个职责提供。标题用普通 Markdown,区域 id 保留侧栏 /#live 目的地。构造无需插件,不连接服务器;监听和网络策略仍归服务入口。 - -官方桥从明确静态地址加载当前 WASM 与 public/client.mq.md。调用前应构建匹配版本并放入 public/generated,构造节点本身不检查存在性。启动时的空日志仅代表尚未收到消息;错误与关闭不能被解释为成功传输。客户端源是 Marqdo,页面不嵌入手写业务 JavaScript。运行时资源与页面内容并列保留,不能先调用旧字符串挂载再塞进正文。页面只有一个客户端源和一条连接,不因为组件拆分而重复启动同一个小部件。 - -我们 **标题 = [说明实时区域](组件.正文(文本="## 实时 WebSocket", 槽="live-heading"))**、**状态 = [独立装配连接反馈](_状态())**、**操作 = [独立装配原生输入与发送](_操作())** 和 **输出 = [独立装配文本消息目标](_输出())**。 -接着 **正文 = [先呈现标题与状态](表.拼接(a=`标题`, b=`状态`))**、**正文 = [再放置输入操作](表.拼接(a=`正文`, b=`操作`))** 和 **正文 = [最后展示真实回显](表.拼接(a=`正文`, b=`输出`))**。 -我们 **属性 = [保留既有页内目的地](表.设(map=None, key="id", value="live"))** 和 **区域 = [组合一个语义区域](组件.包裹(子节点=`正文`, 种类="section", 属性=`属性`, 槽="live"))**。 -随后 **运行时 = [引用官方桥与 Marqdo 客户端](客户端.挂载节点(源="/static/client.mq.md", wasm="/static/generated/marqdo_wasm.wasm", 桥="/static/generated/marqdo-bridge.js"))**。 -完成后返回 *[保留区域与运行时结构](表.拼接(a=`区域`, b=`运行时`))*。 diff --git a/examples/web-net-site-zh/components/nav.mq.md b/examples/web-net-site-zh/components/nav.mq.md deleted file mode 100755 index eb96050..0000000 --- a/examples/web-net-site-zh/components/nav.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: 导航的 Markdown 内容组件 -import: - 组件: ext/web/网页/组件/索引.mq.md - 文件: lib/文件.mq.md ---- - -顶层导航保留首页、关于、发布、工具与后台链接。链接可见不表示目标已获授权,后台实际由服务入口绑定的会话门禁保护。 - -## 导航 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 包含终端 Markdown 的单个语义区域 | - -本组件只拥有本块内容与语义容器。以站点为 --fs-root 授予 fs.read,正文读取相邻内容目录的 Markdown 叶子,不查询记录或启动服务器。父布局决定本块位置;修改文字与链接只编辑叶子。保留稳定槽名与样式类,使片段和主题继续找到本区域,内容不会先被渲染成不透明字符串。 - -我们 **文本 = [读取本区域的终端 Markdown](文件.读文本(路径="components/content/nav.md"))** 和 **叶子 = [保持简单 Markdown 内容](组件.正文(文本=`文本`, 槽="nav-content"))**。 -准备好内容后返回 *[保留这一块的语义与样式](组件.包裹(子节点=`叶子`, 种类="nav", 槽="nav", 样式="topnav"))*。 diff --git a/examples/web-net-site-zh/components/side.mq.md b/examples/web-net-site-zh/components/side.mq.md deleted file mode 100755 index 74695e2..0000000 --- a/examples/web-net-site-zh/components/side.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: 侧栏的 Markdown 内容组件 -import: - 组件: ext/web/网页/组件/索引.mq.md - 文件: lib/文件.mq.md ---- - -侧栏提供文章、实时连接、鉴权、表单与网络解析的任务跳转。WebSocket 的页内锚点保持 /#live,改变文字无需修改连接实现。 - -## 侧栏 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 包含终端 Markdown 的单个语义区域 | - -本组件只拥有本块内容与语义容器。以站点为 --fs-root 授予 fs.read,正文读取相邻内容目录的 Markdown 叶子,不查询记录或启动服务器。父布局决定本块位置;修改文字与链接只编辑叶子。保留稳定槽名与样式类,使片段和主题继续找到本区域,内容不会先被渲染成不透明字符串。 - -我们 **文本 = [读取本区域的终端 Markdown](文件.读文本(路径="components/content/side.md"))** 和 **叶子 = [保持简单 Markdown 内容](组件.正文(文本=`文本`, 槽="side-content"))**。 -准备好内容后返回 *[保留这一块的语义与样式](组件.包裹(子节点=`叶子`, 种类="aside", 槽="side", 样式="side"))*。 diff --git a/examples/web-net-site-zh/db/articles.mq.md b/examples/web-net-site-zh/db/articles.mq.md deleted file mode 100755 index aeb980e..0000000 --- a/examples/web-net-site-zh/db/articles.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: 文章结构与种子调用手册 -import: - document: lib/document.mq.md ---- - -本文件解释各个调用的用途;相邻的 [articles.tables.md](articles.tables.md) 保存可直接阅读的字面表。把 --fs-root 指向站点目录,读取需要 fs.read。字段、样式与正文是数据,读取不会执行文件中的说明。 - -## 结构 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 原生字面表的原始类型与列式数据形态 | - -声明文章的字段、原生类型与可空约束;id 的数值类型和必填字段保持不变。数据库初始化器使用此表保证结构,不负责猜测用户数据的迁移。 - -授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。 - -完成后返回*[读取 结构 的实际字面表](document.read_table(path="db/articles.tables.md", title="结构"))*. - -## 种子 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 原生字面表的原始类型与列式数据形态 | - -提供起始演示文章,保留原来的 id、短链、摘要与正文。只有数据库初始化器确认空表后才应插入;读取本函数不会写入或重置现有文章。 - -授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。 - -完成后返回*[读取 种子 的实际字面表](document.read_table(path="db/articles.tables.md", title="种子"))*. diff --git a/examples/web-net-site-zh/db/articles.tables.md b/examples/web-net-site-zh/db/articles.tables.md deleted file mode 100755 index 0e22139..0000000 --- a/examples/web-net-site-zh/db/articles.tables.md +++ /dev/null @@ -1,23 +0,0 @@ -# Article data - -Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate. - -## 结构 - -Field definitions for the native database initializer; nullable values remain booleans. - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| title | text | false | -| body | text | true | - -## 种子 - -Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. - -| id | title | body | -|----|-------|------| -| 1 | 欢迎来到网络扩展站 | 首页列表来自 SQLite。 | -| 2 | 登录门禁后台 | /admin 页面需要 session 会话。 | -| 3 | WebSocket 实时 | /live 端点会把你的消息实时回显。 | diff --git a/examples/web-net-site-zh/db/index.mq.md b/examples/web-net-site-zh/db/index.mq.md deleted file mode 100755 index b4f4f08..0000000 --- a/examples/web-net-site-zh/db/index.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: web-net-site-zh database lifecycle -import: - data: ext/data/db.mq.md - articles: articles.mq.md - fs: lib/fs.mq.md - text: lib/text.mq.md ---- - -The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory. - -## 打开 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | None | None selects data/site-net-zh.db under the site root; tests provide a disposable explicit URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Initialized articles database resource with existing rows preserved | - -Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions. - -The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving. - -For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory. - -1. `url` == None - We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site-net-zh.db"))** and **url = "sqlite:" + file**. -1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:")) - We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**. -We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.结构())**. -We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**. -1. not `existing` - We **seed = [Read the original demonstration data](articles.种子())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**. -Once the selected database is ready, return *store* for the site's resource bindings. diff --git a/examples/web-net-site-zh/forms.mq.md b/examples/web-net-site-zh/forms.mq.md deleted file mode 100755 index 2c616d9..0000000 --- a/examples/web-net-site-zh/forms.mq.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -markup: occlusion -title: 文章发布表单的唯一规则来源 -import: - 表单: ext/data/表单.mq.md ---- - -服务入口以 article 挂载本资源,发布页只安放该标识的引用。字段、校验与提交因此共用一份定义。它是公开的演示发布表单,原生后台仍保留登录门禁;不要把两者的策略混为一谈。 - -## 文章 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 带标题/正文字段、原始校验规则与返回地址的插入表单 | - -调用需要 plugin。标题必填且最多 120 字符,正文可空且最多 8000 字符,保持原示例的服务器规则。表格逐行表达字段与规则,布尔必填值不是字符串。构造不插入业务记录,也不认证用户;请求提交时才使用应用实际数据库与当前 CSRF。 - -成功提交显式返回首页文章列表;不合格输入保留校验消息供修正。按钮文案留在同一资源,不再手写 form HTML 或另一份客户端校验程序。调用者保留每次更新返回的新资源,再把最终值交给挂载。 - -字段表中的 name 对应数据库列,label 只决定显示,type 选择输入框或多行文本。required 的可见提示不能代替服务器规则;绕过浏览器校验仍会得到“标题不能为空”的原生重试页。表单的成功返回地址为首页,失败时仍留在表单响应中,并继续保留当前 CSRF 供再次提交。 - -`字段` = - -| @ | name | label | type | required | -|---|---|---|---|---| -| 1 | title | 标题 | text | True | -| 2 | body | 正文 | textarea | False | - -`规则` = - -| @ | field | rule | message | -|---|---|---|---| -| 1 | title | required | 标题不能为空 | -| 2 | title | max:120 | 标题太长 | -| 3 | body | max:8000 | 正文太长 | - -我们 **资源 = [构造实际文章插入资源](表单.构造(表="articles"))**、**资源 = [绑定清楚列出的字段](表单.字段(资源=`资源`, 定义=`字段`))** 和 **资源 = [绑定服务器真正执行的规则](表单.规则(资源=`资源`, 定义=`规则`))**。 -准备完成后返回 *[保留提交文案与显式成功返回目标](表单.文案(资源=`资源`, 提交="发布", 取消="取消", 返回地址="/"))*。 diff --git a/examples/web-net-site-zh/index.mq.md b/examples/web-net-site-zh/index.mq.md deleted file mode 100755 index 790f370..0000000 --- a/examples/web-net-site-zh/index.mq.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: 网络扩展站 -import: - 布局: components/index.mq.md - 首页: components/home.mq.md - 数据库: db/index.mq.md - 表单定义: forms.mq.md - 主题: styles/shell.mq.md - 网页: ext/web/网页.mq.md - 表单: ext/data/表单.mq.md - 后台: ext/data/后台.mq.md - 鉴权: ext/security/鉴权.mq.md - 实时: ext/net/实时.mq.md - 文件: lib/文件.mq.md - result: lib/result.mq.md ---- - -从本入口依次阅读组件入口、Markdown 内容叶子、数据库、表单资源与浏览器客户端。首页、关于、发布与工具页都是显式路由 Document;后台保留原生登录门禁,/live 单独归网络资源管理。页面不再依赖已移除的装配接口,启动也不会拼接整页 HTML。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 共享递归布局内的介绍、实时控件与请求期间的文章列表 | - -启动装配只读取终端 Markdown 内容,数据库查询保留为请求资源。发布后下一次访问就能看到新文章,无需重启或重新创建页面。客户端使用原生控件和官方桥;布局本身不初始化数据库或清除业务数据。编辑一块内容时沿组件导入找到对应叶子,不在首页复制导航、侧栏和页脚。 - -我们先 **正文 = [组合首页三个独立职责](首页.节点())**,随后返回 *[安放到共享的递归布局](布局.框架(正文=`正文`))*。 - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-net-site-zh" | 相对仓库的显式站点发现目录 | -| port | number | 18084 | 本机回环监听端口 | -| url | any | None | None 使用站点根的 SQLite;验收指定独占临时 URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 保留文章、表单、鉴权与回显资源的阻塞监听结果 | - -从仓库根使用`root`="examples/web-net-site-zh"、`port`=18084、`url`=None,授予 plugin,fs.write,network.write,并设置 --fs-root examples/web-net-site-zh。先通过开发手册把当前浏览器产物放进 public/generated。缺少运行时文件时停止,不呈现看似可用的空控件。 - -数据库只为空表播种,已有文章保留。主题由原始属性表编译后显式写到生成目录,再发现页面并按顺序启用后台、绑定鉴权、挂载公开文章表单、绑定回显。每一步保留新应用,最后才监听。本地 admin/secret 是演示夹具,真实部署必须替换账户来源与网络策略;公开回显只绑定回环地址。服务阻塞于当前进程,关闭由调用者负责。显式 url 用于隔离验收,SQLite 路径仍经过授权根检查;不能为测试删除示例原有 data 目录。主题是可再生文件,写入失败会阻止后续监听,单文件原子替换不意味着数据库和样式之间存在事务。 - -`产物` = - -| 文件 | -|---| -| public/generated/marqdo_wasm.wasm | -| public/generated/marqdo-bridge.js | - -- [在启动前确认实际运行时文件](for 产物 as 路径) - 1. not [运行时资源确实存在](文件.存在(路径=`路径`)) - 返回 *[指出所需浏览器准备](result.error(code="net_site.browser_assets", message="请先把当前 WASM 与官方桥构建到 public/generated", operation="serve"))*。 -我们 **存储 = [打开并保留文章数据库](数据库.打开(url=`url`))**,**样式 = [编译既有的声明式主题](主题.编译())**,并 **[建立明确的生成目录](文件.建目录(路径="public/generated"))**、**[原生写入本次主题](文件.原子写文本(路径="public/generated/theme.css", 内容=`样式`))**。 -我们 **应用 = [发现已声明页面并保留站点上下文](网页.准备站点(根=`root`, 主机="127.0.0.1", 端口=`port`, 数据库=`存储`, 静态目录="public"))** 和 **应用 = [保留原生后台能力](后台.启用(应用=`应用`))**。 - -`用户` = - -| @ | username | password | role | -|---|---|---|---| -| 1 | admin | secret | admin | - -我们 **应用 = [绑定真实登录会话与后台门禁](鉴权.绑定(应用=`应用`, 用户=`用户`, 登录路径="/admin/login", 登录返回="/admin", 退出返回="/"))**,**文章 = [构造共享校验资源](表单定义.文章())** 和 **应用 = [明确挂载公开发布表单](表单.挂载(应用=`应用`, 标识="article", 资源=`文章`))**。 -接着 **应用 = [绑定本地演示的公开回显资源](实时.绑定(应用=`应用`, 路径="/live", 模式="echo", 需要登录=False))**。 -全部资源就绪后返回 *[在保留的站点根中开始监听](网页.监听(应用=`应用`))*。 diff --git a/examples/web-net-site-zh/pages/about.mq.md b/examples/web-net-site-zh/pages/about.mq.md deleted file mode 100755 index 6892fe3..0000000 --- a/examples/web-net-site-zh/pages/about.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /about -title: 关于 -import: - 组件: ext/web/网页/组件/索引.mq.md - 布局: ../components/index.mq.md - 文件: lib/文件.mq.md ---- - -本 Document 用元数据显式声明 /about 路径。说明留在终端 Markdown,导航、侧栏和页脚归共享布局。解释页不查询数据库、不配置服务,也不会隐式注册其他业务路径。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 共享站点框架中的关于说明 | - -启动阶段只装配结构,授予 fs.read 读取 Markdown 叶子。沿布局导入可以独立修改一个区域,无需在这里重写整页壳。内容是普通 Markdown,不把源码手册的执行标记混进用户页面。 路由来自本页声明,首次阅读即可判断入口与内容来源。 - -我们 **文本 = [读取本页的终端说明](文件.读文本(路径="components/content/about.md"))** 和 **正文 = [保留简单 Markdown 内容](组件.正文(文本=`文本`, 槽="intro"))**。 -最后返回 *[放进共享递归布局](布局.框架(正文=`正文`))*。 diff --git a/examples/web-net-site-zh/pages/new.mq.md b/examples/web-net-site-zh/pages/new.mq.md deleted file mode 100755 index 455b924..0000000 --- a/examples/web-net-site-zh/pages/new.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /new -title: 发布 -import: - 组件: ext/web/网页/组件/索引.mq.md - 布局: ../components/index.mq.md - 文件: lib/文件.mq.md - 表单: ext/data/表单.mq.md - 表: lib/表.mq.md ---- - -本 Document 用元数据显式声明 /new 路径。说明留在终端 Markdown,导航、侧栏和页脚归共享布局。本页只放 article 表单引用,字段、校验与真实提交处理器由独立资源定义。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 共享站点框架中的发布说明与表单请求资源 | - -启动阶段只装配结构,授予 fs.read 读取 Markdown 叶子。服务器在每次请求中才为实际会话准备 CSRF 与返回路径,不能在启动时写死令牌。未知表单标识是真实请求错误;页面可见不替代提交地址的访问策略。 路由来自本页声明,首次阅读即可判断入口与内容来源。 - -我们 **文本 = [读取本页的终端说明](文件.读文本(路径="components/content/new.md"))** 和 **正文 = [保留简单 Markdown 内容](组件.正文(文本=`文本`, 槽="intro"))**。 -我们 **引用 = [引用实际挂载的文章表单](表单.引用(标识="article"))**、**操作 = [安放请求期间解析的表单](组件.请求资源(值=`引用`, 槽="article-form"))** 和 **正文 = [让说明先于填写操作](表.拼接(a=`正文`, b=`操作`))**。 -最后返回 *[放进共享递归布局](布局.框架(正文=`正文`))*。 diff --git a/examples/web-net-site-zh/pages/tools.mq.md b/examples/web-net-site-zh/pages/tools.mq.md deleted file mode 100755 index 0b7c249..0000000 --- a/examples/web-net-site-zh/pages/tools.mq.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /tools -title: 网络解析工具 -import: - 网络: lib/网络.mq.md - 文件: lib/文件.mq.md - 表: lib/表.mq.md - 组件: ext/web/网页/组件/索引.mq.md - 布局: ../components/index.mq.md ---- - -本页对明确的本地夹具执行标准网络解析器,不访问外部 HTTP。Cookie 头是纯文本,multipart 正文是 content 目录中的终端协议数据。预格式文本控件展示实际记录,既不拼 HTML,也不把手抄的预期值当作执行结果。 - -## _面板 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标题 | text | 必填 | 作者控制的观察项标题 | -| 值 | any | 必填 | 解析器实际返回的原生值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | Markdown 标题与转义的预格式文本节点 | - -输入`标题`与`值`,用这个纯构造把含义与观察结果放在一起。标题来自作者,协议输入只作为文本展示,不能变成页面结构或执行表达式。原生值转为显示文本后由 pre 保留字符;即使包含尖括号或引号也不会作为 HTML 解析。本函数不读取文件,也不运行解析器。 - -我们 **标题文本 = "## " + 标题**、**说明 = [用 Markdown 解释观察项目](组件.正文(文本=`标题文本`))** 和 **文本 = [保留原生结构的实际显示值](str(值))**、**数据 = [按纯文本展示观察结果](组件.控件(种类="pre", 值=`文本`))**。 -最后返回 *[将说明与实际数据放在一起](表.拼接(a=`说明`, b=`数据`))*。 - -## _Cookie - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 真实请求 Cookie 与响应 Set-Cookie 两种解析结果 | - -请求模式解析 session 与 theme 键值;响应模式把 Path、HttpOnly 与 SameSite 视为同一个 id Cookie 的属性。两次调用都使用维护中的标准库,结果形态的差异来自真实模式,不是作者拼接的展示。 - -这是确定性的文本夹具,不代表当前浏览器登录,也不会写 Cookie 或把夹具当作有效凭据。面板保留所有返回字段,读者能直接观察名称、值和标志。解析为纯计算,不需要插件或网络授权。 - -我们 **请求 = [解析明确的请求头夹具](网络.解析Cookie(内容="session=abc123; theme=dark"))** 和 **响应 = [按响应头模式解析属性](网络.解析Cookie(内容="id=42; Path=/; HttpOnly; SameSite=Lax", 是响应头=True))**。 -接着 **请求面板 = [展示真实请求键值](_面板(标题="Cookie 请求头", 值=`请求`))** 和 **响应面板 = [展示真实响应属性](_面板(标题="Set-Cookie 响应头", 值=`响应`))**。 -观察完成后返回 *[相邻保留两种解析模式](表.拼接(a=`请求面板`, b=`响应面板`))*。 - -## _多部分 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 实际 multipart 文本字段与文件部分的观察面板 | - -授予 fs.read,从站点根读取 CRLF 协议夹具,边界保持文件声明的 net-boundary。title 部分是“你好”,cover 部分标记 pic.png 与 image/png。文件值仅为字面 <字节>,不声称包含真正的二进制图片或执行上传。 - -解析器返回原生列表,使用从零开始的取项选择两个部分。夹具缺失或格式错误保留真实文件/解析诊断,不能改为固定预期答案。展示协议内容不会提取文件、访问网络或解释其中的 Markdown。 - -我们 **正文 = [原生读取精确的本地协议文本](文件.读文本(路径="components/content/multipart.txt"))** 和 **部分 = [解析边界与内容处置字段](网络.解析多部分(正文=`正文`, 边界="net-boundary"))**。 -接着 **字段 = [读取第一条真实部分记录](表.首(list=`部分`))**、**文件部分 = [读取从零开始的第二条记录](表.取(xs=`部分`, i=1))**、**字段面板 = [展示真实表单字段](_面板(标题="多部分字段", 值=`字段`))** 和 **文件面板 = [展示真实文件元数据](_面板(标题="多部分文件", 值=`文件部分`))**。 -最后返回 *[保留两种实际观察](表.拼接(a=`字段面板`, b=`文件面板`))*。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 共享布局内的四项真实标准库解析观察 | - -装配需要 fs.read 读取 multipart 夹具与共享布局叶子,解析本身是纯计算。四个面板保留请求 Cookie、响应 Cookie、multipart 字段和文件元数据。修改夹具会改变展示结果,因为页面运行真实标准库,而不是显示事先编好的答案。 - -用户仍可从共享导航去发布、后台或实时区域。面板内只展示纯文本,协议中的 <字节> 不会成为标签。这个工具页不代表真实网络流量、登录身份或用户上传。 - -我们 **介绍 = [解释本地解析演示](组件.正文(文本="# 网络工具\n\n由标准网络库提供真实 Cookie 与 multipart 解析结果。"))**、**Cookie = [观察请求与响应两种模式](_Cookie())** 和 **多部分 = [观察实际字段及文件部分](_多部分())**。 -接着 **正文 = [说明位于观察结果之前](表.拼接(a=`介绍`, b=`Cookie`))** 和 **正文 = [保留后续 multipart 结果](表.拼接(a=`正文`, b=`多部分`))**。 -全部观察就绪后返回 *[放进共享站点框架](布局.框架(正文=`正文`))*。 diff --git a/examples/web-net-site-zh/public/client.mq.md b/examples/web-net-site-zh/public/client.mq.md deleted file mode 100755 index eedff0f..0000000 --- a/examples/web-net-site-zh/public/client.mq.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -markup: occlusion -title: 网络站点的 Marqdo 回显客户端 -import: - 浏览器: lib/浏览器.mq.md - 表: lib/表.mq.md - text: lib/text.mq.md ---- - -客户端拥有连接标识和纯文本消息记录,原生控件由 components/live.mq.md 声明,服务端绑定同源 /live 路由。这里只生成官方桥效果,不通过外联脚本操纵页面。连接状态保留旧控件的 connected/closed 文本作为可观察协议。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 事件绑定、套接字打开与初始状态效果 | - -入口使用对象 main 保留后续回调需要的连接标识和消息记录。点击与 Enter 都携带当前输入值,实际收到回显后才追加日志。连接成功启用发送,错误或关闭则禁用。重载重建演示状态,不声称提供持久历史或自动重连。 - -事件表中的调用名对应下面的直接回调,值选择器显式指向输入。浏览器桥负责真正的运输和 DOM 更新;这份代码的纯效果构造无需插件。普通辅助函数显式接收连接标识,避免假定任意嵌套调用都能捕获入口状态。 - -官方桥按事件表传入 value,键盘事件另外携带 key,消息回调携带 data,错误回调携带 error,所以这些公共回调保留实际字段名。声明中的 then_open、then_message 等是既有运输协议,不是新的作者语言。相对 /live 路径跟随页面真实主机与端口,避免把本地验收端口写死在客户端。 - -我们 **连接 = "live"** 和 **消息 = ""**,保留入口状态。 - -`绑定` = - -| @ | 选择器 | 事件 | 调用 | 值选择器 | -|---|---|---|---|---| -| 1 | "#live-send" | click | 发送 | "#live-msg" | -| 2 | "#live-msg" | keydown | 按键 | "#live-msg" | - -`打开` = - -| op | id | url | then_open | then_message | then_error | then_close | -|---|---|---|---|---|---|---| -| open | `连接` | /live | 已打开 | 收到消息 | 出错 | 已关闭 | - -我们 **事件 = [保留原生控件事件](表.设(map=None, key="wire", value=`绑定`))** 和 **运输 = [描述同源实时连接](浏览器.套接字(规格=`打开`))**。 -最后返回 *[将事件与运输效果一起交给官方桥](浏览器.合并(甲=`事件`, 乙=`运输`))*。 - -## _状态 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 文本 | text | 必填 | 显示给用户的纯文本连接反馈 | -| 禁用 | bool | 必填 | 发送按钮真实布尔属性 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 状态文字与按钮属性两种效果的组合 | - -使用`文本`和`禁用`,让连接反馈与按钮可用性保持一致。False 令桥移除 disabled,字符串 false 则仍为存在的布尔属性,不能混用。状态更新不清空消息、不发送重试,也不创建第二个连接;它只描述两个独立效果种类。 - -我们 **属性 = [保留真实布尔禁用值](表.设(map=None, key="disabled", value=`禁用`))**、**状态 = [描述纯文本反馈](浏览器.设文本(选择器="#live-status", 文本=`文本`))** 和 **按钮 = [描述实际发送可用性](浏览器.设属性(选择器="#live-send", 属性=`属性`))**。 -最后返回 *[保留独立效果种类](浏览器.合并(甲=`状态`, 乙=`按钮`))*。 - -## 已打开 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | 官方桥给出的实际打开结果 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 成功时启用发送,否则保留失败状态 | - -使用`ok`=True 接收打开回调。成功只证明运输已就绪,消息交付仍由真实回显观察。打开失败不添加假的欢迎消息,也不悄悄重连。状态和按钮通过同一个辅助函数更新,避免用户看到失败却仍能点击发送。 - -1. `ok` - 返回 *[真实打开后允许发送](_状态(文本="connected", 禁用=False))*。 -否则返回 *[保持打开失败可见](_状态(文本="connection failed", 禁用=True))*。 - -## _发送 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 值 | text | 必填 | 点击或 Enter 交来的输入文本 | -| 通道 | text | 必填 | 入口保留并显式传入的现有连接标识 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 非空消息发送效果;去空白后为空则返回 None | - -使用`值`和`通道`复用原控件的发送策略。先去掉两端空白,空消息不发送。内容只是文本,不能成为命令或 HTML;发送效果不表示已经交付,日志必须等待真实回显。这一普通辅助调用显式接收通道,不依赖直接回调才有的入口状态。 - -我们 **内容 = [保留原有去空白策略](text.str_trim(s=`值`))**。 -1. `内容` == "" - 返回 *None*,表示没有发送。 - -`操作` = - -| op | id | data | -|---|---|---| -| send | `通道` | `内容` | - -准备完成后返回 *[发送一个真实非空消息](浏览器.套接字(规格=`操作`))*。 - -## 发送 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | "" | 点击绑定从输入控件取得的当前文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 共享非空发送策略的结果 | - -使用`value`="" 接收点击值。直接浏览器回调读取保留的连接状态,再显式传给辅助函数。空白输入不会产生发送效果;点击也不能提前追加回显,确保页面只展示观察到的服务端帧。输入仍留在控件里,保留原示例的重复编辑方式。 - -最后返回 *[将点击交给共享发送策略](_发送(值=`value`, 通道=`连接`))*。 - -## 按键 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | "" | 官方桥提供的真实键名 | -| value | text | "" | 该事件值选择器取得的输入文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | Enter 使用共享发送策略,其他键返回 None | - -使用`key`=""与`value`="" 接收键盘回调。只在 Enter 时发送,避免每次编辑键都产生消息。点击和 Enter 共享相同的去空白、空输入忽略行为,既不重复安装处理器,也不创建另一条连接或提前生成本地回显。 - -1. `key` == "Enter" - 返回 *[使用与按钮相同的发送规则](_发送(值=`value`, 通道=`连接`))*。 -普通编辑键返回 *None*。 - -## 收到消息 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | text | "" | 服务器实际发来的回显文本帧 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 包含已保留消息的纯文本更新 | - -使用`data`="" 接收实际消息。每个帧追加原来的 echo: 前缀与换行,保留之前的消息。文本效果通过桥安全展示,尖括号与引号按字面保留;重载才开始新的演示记录,不声称落盘。直接回调更新入口消息状态。 - -我们 **消息 = [保留下一条已观察回显](消息 + "echo: " + data + "\n")**。 -最后返回 *[以纯文本展示完整记录](浏览器.设文本(选择器="#live-out", 文本=`消息`))*。 - -## 出错 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| error | text | "" | 浏览器运输报告的实际错误描述 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 可见错误反馈与禁用发送 | - -使用`error`="",把运输失败放在控件旁边。历史消息仍可阅读,失败不清空记录、不尝试新发送,也不悄悄重连。用户可重载页面建立新会话;这里的效果不等于故障恢复成功,按钮应保持不可用。 - -我们 **文本 = "error: " + error**,最后返回 *[让错误与可用性一致](_状态(文本=`文本`, 禁用=True))*。 - -## 已关闭 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 关闭反馈与禁用发送,保留历史消息 | - -连接关闭后,既有消息仍可阅读,发送按钮需要禁用。此回调不清空入口状态,也不自动创建另一条连接。后续真实发送应由新页面会话中的实际打开事件启用;不能把关闭当作正常消息交付或显示假的重连成功。 - -关闭后返回 *[保留真实结束状态](_状态(文本="closed", 禁用=True))*。 diff --git a/examples/web-net-site-zh/styles/shell.mq.md b/examples/web-net-site-zh/styles/shell.mq.md deleted file mode 100755 index a284355..0000000 --- a/examples/web-net-site-zh/styles/shell.mq.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -markup: occlusion -title: 原始主题属性与显式编译 -import: - 网页: ext/web/网页.mq.md - text: lib/text.mq.md ---- - -主题保留原站的四组属性值,控件与容器只引用类名。它没有大段作者 CSS 或页面字符串。服务入口调用编译,将结果通过原生文件写到明确的生成路径,再让布局引用该资源。 - -## 顶栏 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 导航背景与底部分隔线 | - -导航内容采用白色背景,并以浅色细线与下方内容分开。返回值保留原有颜色和边框,不负责导航链接或几何布局。它是纯属性数据,调用不加载插件、不写文件;编译阶段才把它映射到原生导航类。 - -`属性` = - -| 属性 | 值 | -|---|---| -| background | #ffffff | -| border-bottom | 1px solid #e7e5e4 | - -属性明确后返回 *属性*,供主题编译继续使用。 - -## 侧栏面板 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 侧栏背景属性 | - -侧栏用浅色背景区分任务跳转与主体内容。这里只保留原有背景值,不重复设置父行宽度或移动端折叠行为。纯属性表可以独立阅读和比较,调用不查询数据,也不生成样式文件;父布局继续拥有侧栏位置。 - -`属性` = - -| 属性 | 值 | -|---|---| -| background | #f5f5f4 | - -属性明确后返回 *属性*,供主题编译继续使用。 - -## 卡片标题 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 文章标题字号与间距属性 | - -请求查询资源生成的文章卡片使用这些标题声明,保留原始字号和下边距。标题内容仍由真实记录提供且经过转义,样式不会注入文章文字或链接。属性构造为纯计算,不运行查询;选择器在编译阶段与原生卡片结构对齐。 - -`属性` = - -| 属性 | 值 | -|---|---| -| font-size | 1.15rem | -| margin | 0 0 0.35rem | - -属性明确后返回 *属性*,供主题编译继续使用。 - -## 卡片正文 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 文章正文颜色与间距属性 | - -文章正文保留原站的次级文字颜色和零外边距。此表不截断或替换正文,也不改变 Markdown 与数据字段之间的约定。它只提供纯属性数据,布局、渲染和数据库生命周期都在各自模块,编译后再引用共同的主题文件。 - -`属性` = - -| 属性 | 值 | -|---|---| -| color | #57534e | -| margin | 0 | - -属性明确后返回 *属性*,供主题编译继续使用。 - -## 编译 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | text | 四个原始属性表编译成的有序 CSS | - -调用需要 plugin,按导航、侧栏、卡片标题和正文的顺序编译。选择器直接对应原生组件与查询卡片,避免重复声明一份旧页面绑定布局。所有属性值保留原站定义;通用响应式几何仍由 View 运行时负责。 - -本函数不写文件或挂载资源,调用者收到文本后通过原生文件能力写入明确目标。编译失败应阻止监听,不能退回旧样式假装本轮成功。修改单块属性只改上面的对应函数,验证编译结果与真实窄屏页面,避免颜色保留却丢失结构作用。生成文件可以重建,原始声明仍以本文件为准。 - -我们 **导航 = [读取原有导航属性](顶栏())**、**侧栏 = [读取原有侧栏属性](侧栏面板())**、**标题 = [读取原有标题属性](卡片标题())** 和 **正文 = [读取原有正文属性](卡片正文())**。 -随后 **导航样式 = [编译导航类](网页.编译样式(名称="topnav", 属性=`导航`))**、**侧栏样式 = [编译侧栏类](网页.编译样式(名称="side", 属性=`侧栏`))**、**标题样式 = [编译实际卡片标题选择器](网页.编译样式(名称="content.cards h2", 属性=`标题`))** 和 **正文样式 = [编译实际卡片正文选择器](网页.编译样式(名称="content.cards p", 属性=`正文`))**。 - -`片段` = - -| 样式 | -|---| -| `导航样式` | -| `侧栏样式` | -| `标题样式` | -| `正文样式` | - -编译完成后返回 *[保留声明顺序](text.str_join(xs=`片段`, sep="\n"))*。 diff --git a/examples/web-net-site/README.md b/examples/web-net-site/README.md deleted file mode 100755 index ff64e4d..0000000 --- a/examples/web-net-site/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# web-net-site - -本工程保留文章列表、关于页、文章表单、Cookie/Multipart 工具页、登录后的原生管理后台,以及 /live WebSocket 回显。页面递归组合到 Markdown 和原生控件;浏览器交互由 public/client.mq.md 表达。 - -从仓库根目录准备当前 CLI 与工程插件后,使用同一份开发手册构建 Web 和浏览器运行时: - -```sh -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json -target/debug/marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-net-site/public/generated"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json -target/debug/marqdo call examples/web-net-site/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-net-site --require-ok --json -``` - -打开 http://127.0.0.1:18083。默认数据库位于站点文件根的 data/site-net.db,重启保留已有文章。缺少兼容 WASM 目标时,先按 [工具链任务](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,再把返回的 compiler 传给 build_browser。 - -- [布局入口](components/index.mq.md) 组合导航、侧栏、主体和页脚,叶子在 components/content。 -- [文章表单](forms.mq.md) 统一定义字段与服务端规则;校验失败后保留真实 CSRF,成功回到文章列表。 -- [工具页](pages/tools.mq.md) 展示真实网络解析结果,不请求远端服务。 -- [客户端](public/client.mq.md) 保留按钮与 Enter 发送、去除首尾空白、忽略空输入及连续回显日志。 -- 管理后台登录使用本机演示账号 admin / secret。部署时替换账号与访问策略。 - -请求资源沿用五列 View;数据库查询随每次请求更新,表单引用解析当前会话。详情见 [请求资源设计](../../doc/design/web-view-resources.md)。 - -开发入口的 test_browser 使用实际当前 WASM 验证回显、表单重试、新增文章、后台登录与窄屏布局。HTTP 回归 web_handbook 在 Tree 与 Bytecode 两个后端启动临时站点,验证数据和鉴权,避免操作用户数据库。 diff --git a/examples/web-net-site/components/content/about.md b/examples/web-net-site/components/content/about.md deleted file mode 100755 index 1118d65..0000000 --- a/examples/web-net-site/components/content/about.md +++ /dev/null @@ -1,3 +0,0 @@ -# About - -This example combines database records, server-side form validation, login sessions, WebSocket echo and the standard network library's cookie/multipart parsing. Each responsibility has its own source file; layouts end in plain Markdown leaves. diff --git a/examples/web-net-site/components/content/foot.md b/examples/web-net-site/components/content/foot.md deleted file mode 100755 index 87b488f..0000000 --- a/examples/web-net-site/components/content/foot.md +++ /dev/null @@ -1 +0,0 @@ -[Marqdo web-net example](https://github.com) · [Docs](/tools) diff --git a/examples/web-net-site/components/content/home.md b/examples/web-net-site/components/content/home.md deleted file mode 100755 index fa5dbe7..0000000 --- a/examples/web-net-site/components/content/home.md +++ /dev/null @@ -1,3 +0,0 @@ -# Net Site - -Articles from SQLite, a live WebSocket widget, login-gated administration, and network parsing tools share this readable project. New articles appear on the next request. diff --git a/examples/web-net-site/components/content/multipart.txt b/examples/web-net-site/components/content/multipart.txt deleted file mode 100755 index af081b1..0000000 --- a/examples/web-net-site/components/content/multipart.txt +++ /dev/null @@ -1,10 +0,0 @@ ---net-boundary -Content-Disposition: form-data; name="title" - -Hello ---net-boundary -Content-Disposition: form-data; name="cover"; filename="pic.png" -Content-Type: image/png - - ---net-boundary-- diff --git a/examples/web-net-site/components/content/nav.md b/examples/web-net-site/components/content/nav.md deleted file mode 100755 index c89e156..0000000 --- a/examples/web-net-site/components/content/nav.md +++ /dev/null @@ -1 +0,0 @@ -[Home](/) · [About](/about) · [Publish](/new) · [Tools](/tools) · [Admin](/admin) diff --git a/examples/web-net-site/components/content/new.md b/examples/web-net-site/components/content/new.md deleted file mode 100755 index 3a14311..0000000 --- a/examples/web-net-site/components/content/new.md +++ /dev/null @@ -1,3 +0,0 @@ -# Publish - -This form inserts into the shared articles table. Title is required and limited to 120 characters; body is optional and limited to 8000. A rejected field keeps the actual session token so it can be corrected and submitted again. diff --git a/examples/web-net-site/components/content/side.md b/examples/web-net-site/components/content/side.md deleted file mode 100755 index eece4fe..0000000 --- a/examples/web-net-site/components/content/side.md +++ /dev/null @@ -1,7 +0,0 @@ -## Try the capabilities - -- [Articles](/) -- [WebSocket](/#live) -- [Authentication](/admin) -- [Forms](/new) -- [Network parsing](/tools) diff --git a/examples/web-net-site/components/foot.mq.md b/examples/web-net-site/components/foot.mq.md deleted file mode 100755 index 0302a3b..0000000 --- a/examples/web-net-site/components/foot.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: foot Markdown component -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md ---- - -This leaf module owns foot content and its semantic region. Parent layout only places the returned nodes. Edit the adjacent Markdown leaf to change wording or links; the component does not query records, authenticate users or generate a raw HTML string. - -## foot - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One footer region containing terminal Markdown content | - -Read the Markdown leaf relative to the granted site root with fs.read. Its links keep the original example's destinations; actual routing and access policy remain in the serving entry. This region is already simple enough to express as Markdown, so further wrappers or a custom table dialect would add no responsibility. The semantic container and class preserve its role for the native layout and theme. - -We **text = [Read this region's terminal Markdown](fs.read_text(path="components/content/foot.md"))** and **leaf = [Retain content as native Markdown](component.markdown(text=`text`, slot="foot-content"))**. -Return *[Place that leaf in its semantic region](component.wrap(children=`leaf`, kind="footer", slot="foot", style="foot"))*. diff --git a/examples/web-net-site/components/home.mq.md b/examples/web-net-site/components/home.mq.md deleted file mode 100755 index dba972b..0000000 --- a/examples/web-net-site/components/home.mq.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -markup: occlusion -title: Network-site home content -import: - component: ext/web/component/index.mq.md - query: ext/data/view.mq.md - socket: live.mq.md - fs: lib/fs.mq.md - table: lib/table.mq.md ---- - -The home body has three responsibilities: a Markdown introduction, the original WebSocket widget, and a current article list. Each remains a separate component or resource. The database query is described at startup and executed per request, so publishing an article appears without restarting the site. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Introduction, native live widget and request-time article query nodes | - -Read the terminal introduction with fs.read. The live component owns only native controls and the official bridge reference; network binding belongs to serve. The query uses the application's retained articles resource and stable id ordering. It neither caches startup records nor opens a second database using a guessed relative filename. - -We **text = [Read the home introduction](fs.read_text(path="components/content/home.md"))** and **intro = [Describe it as Markdown](component.markdown(text=`text`, slot="intro"))** and **live = [Assemble the native WebSocket widget](socket.nodes())**. -We **current = [Describe the current article query](query.query(source="articles", order="id", link_prefix=""))** and **articles = [Place the dynamic data resource](component.resource(value=`current`, slot="articles"))**. -We **body = [Keep introduction before interaction](table.concat(a=`intro`, b=`live`))**. -Return *[Keep the actual database list after the live widget](table.concat(a=`body`, b=`articles`))*. diff --git a/examples/web-net-site/components/index.mq.md b/examples/web-net-site/components/index.mq.md deleted file mode 100755 index a3a1acf..0000000 --- a/examples/web-net-site/components/index.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: Network-site recursive layout entry -import: - component: ext/web/component/index.mq.md - nav: nav.mq.md - side: side.mq.md - foot: foot.mq.md - table: lib/table.mq.md ---- - -Read this entry before changing page geometry. Navigation, side rail and footer end in Markdown leaves; the caller supplies main content nodes. Database queries and form references remain resources inside that main region, preserving fresh request behavior without rebuilding layout or concatenating HTML. - -## frame - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| body | list | required | Main content nodes supplied by the page's own component | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Ordered navigation, side/main row, footer and stylesheet resource | - -Use `body` to assemble one page in the same site frame. Each child module owns its content; this parent only declares order and one side-by-side relationship. The native row layout collapses on narrow screens. No child is rendered into a string before composition. The theme URL points to a file explicitly compiled by serve before discovery starts. - -We **top = [Read the navigation component](nav.nav())** and **rail = [Read the side-rail component](side.side())** and **main = [Name the supplied main region](component.wrap(children=`body`, kind="column", slot="main"))**. -We **columns = [Keep side rail and main as sibling components](table.concat(a=`rail`, b=`main`))** and **center = [Declare the shared row geometry](component.wrap(children=`columns`, kind="row", slot="page-body"))** and **bottom = [Read the closing links](foot.foot())**. -We **page = [Keep navigation before content](table.concat(a=`top`, b=`center`))** and **page = [Keep the footer after content](table.concat(a=`page`, b=`bottom`))** and **style = [Reference the compiled declarative theme](component.asset(url="/static/generated/theme.css", kind="stylesheet"))**. -Return *[Retain the style resource with the readable page structure](table.concat(a=`page`, b=`style`))*. diff --git a/examples/web-net-site/components/live.mq.md b/examples/web-net-site/components/live.mq.md deleted file mode 100755 index d925b00..0000000 --- a/examples/web-net-site/components/live.mq.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -markup: occlusion -title: Native WebSocket widget -import: - component: ext/web/component/index.mq.md - client: ext/web/client/index.mq.md - table: lib/table.mq.md ---- - -This component ends at simple Markdown and native controls. It owns no network listener or hand-written HTML. The client program supplies events through the official bridge; serve separately binds the native /live echo resource. Keep control ids stable when editing wording so the client contract stays readable. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | WebSocket heading, status, input/send controls, message log and bridge resource | - -The heading explains the interaction. Status and output use independent plain-text targets, input supplies the send value, and the button starts disabled until a real connection opens. Values and attributes remain typed data. Each echoed message is appended by the Marqdo client state and shown as text, so message content cannot become HTML. This construction does not open a socket. - -The bridge addresses are explicit resources under the site's static mount. Prepare the current WASM and bridge in public/generated before serving; copying an older bridge can change event behavior even when the page still renders. The source at public/client.mq.md is served as UTF-8 client code and runs in the official browser runtime. To inspect construction alone, call this file's nodes function with no effects: it returns typed structure and performs no network request. - -We **heading = [Describe the widget in ordinary Markdown](component.markdown(text="## Live WebSocket", slot="live-heading"))**. - -`status_attrs` = - -| id | aria-live | -|---|---| -| live-status | polite | - -`input_attrs` = - -| id | placeholder | type | -|---|---|---| -| live-msg | type a message… | text | - -`button_attrs` = - -| id | type | disabled | -|---|---|---| -| live-send | button | True | - -`output_attrs` = - -| id | aria-live | -|---|---| -| live-out | polite | - -We **status = [Keep connection state separate from messages](component.element(kind="text", value="connecting…", attrs=`status_attrs`, slot="live-status"))** and **input = [Describe the native message input](component.element(kind="input", attrs=`input_attrs`, slot="live-input"))** and **button = [Describe the initially disabled send action](component.element(kind="button", value="Send", attrs=`button_attrs`, slot="live-send"))**. -We **controls = [Keep the input beside its send button](table.concat(a=`input`, b=`button`))** and **controls = [Declare responsive control geometry](component.wrap(children=`controls`, kind="row", slot="live-controls"))** and **output = [Describe the plain message log](component.element(kind="pre", attrs=`output_attrs`, slot="live-output"))**. -We **body = [Start with the explanatory heading](table.concat(a=`heading`, b=`status`))** and **body = [Place interaction after status](table.concat(a=`body`, b=`controls`))** and **body = [Keep the echoed messages after controls](table.concat(a=`body`, b=`output`))**. -We **id = [Name the widget's existing fragment destination](table.put(in=None, at="id", value="live"))** and **widget = [Keep the terminal pieces in one semantic region](component.wrap(children=`body`, kind="section", attrs=`id`, slot="live"))**. -We **runtime = [Declare the official runtime and Marqdo client source](client.nodes(source="/static/client.mq.md", wasm="/static/generated/marqdo_wasm.wasm", bridge="/static/generated/marqdo-bridge.js"))**. -Return *[Retain widget and runtime as structured nodes](table.concat(a=`widget`, b=`runtime`))*. diff --git a/examples/web-net-site/components/nav.mq.md b/examples/web-net-site/components/nav.mq.md deleted file mode 100755 index 37c95ec..0000000 --- a/examples/web-net-site/components/nav.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: nav Markdown component -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md ---- - -This leaf module owns nav content and its semantic region. Parent layout only places the returned nodes. Edit the adjacent Markdown leaf to change wording or links; the component does not query records, authenticate users or generate a raw HTML string. - -## nav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One nav region containing terminal Markdown content | - -Read the Markdown leaf relative to the granted site root with fs.read. Its links keep the original example's destinations; actual routing and access policy remain in the serving entry. This region is already simple enough to express as Markdown, so further wrappers or a custom table dialect would add no responsibility. The semantic container and class preserve its role for the native layout and theme. - -We **text = [Read this region's terminal Markdown](fs.read_text(path="components/content/nav.md"))** and **leaf = [Retain content as native Markdown](component.markdown(text=`text`, slot="nav-content"))**. -Return *[Place that leaf in its semantic region](component.wrap(children=`leaf`, kind="nav", slot="nav", style="topnav"))*. diff --git a/examples/web-net-site/components/side.mq.md b/examples/web-net-site/components/side.mq.md deleted file mode 100755 index 0c15129..0000000 --- a/examples/web-net-site/components/side.mq.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -markup: occlusion -title: side Markdown component -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md ---- - -This leaf module owns side content and its semantic region. Parent layout only places the returned nodes. Edit the adjacent Markdown leaf to change wording or links; the component does not query records, authenticate users or generate a raw HTML string. - -## side - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One aside region containing terminal Markdown content | - -Read the Markdown leaf relative to the granted site root with fs.read. Its links keep the original example's destinations; actual routing and access policy remain in the serving entry. This region is already simple enough to express as Markdown, so further wrappers or a custom table dialect would add no responsibility. The semantic container and class preserve its role for the native layout and theme. - -We **text = [Read this region's terminal Markdown](fs.read_text(path="components/content/side.md"))** and **leaf = [Retain content as native Markdown](component.markdown(text=`text`, slot="side-content"))**. -Return *[Place that leaf in its semantic region](component.wrap(children=`leaf`, kind="aside", slot="side", style="side"))*. diff --git a/examples/web-net-site/db/articles.mq.md b/examples/web-net-site/db/articles.mq.md deleted file mode 100755 index 7ba5bb6..0000000 --- a/examples/web-net-site/db/articles.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: Article schema and seed handbook -import: - document: lib/document.mq.md ---- - -This file explains callable use; [articles.tables.md](articles.tables.md) holds the readable literal tables. Set --fs-root to the site directory and grant fs.read. Reading returns data without running prose, opening a database or changing a page. - -## schema - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native table value, preserving literal types and column geometry | - -Declare article fields, native types and nullability. The initializer consumes this table to ensure structure; it must not guess a migration or erase existing rows. - -Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. - -Return *[读取 schema 的实际字面表](document.read_table(path="db/articles.tables.md", title="schema"))*. - -## seed - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native table value, preserving literal types and column geometry | - -Provide initial demonstration articles with their original ids, stable slugs and content. Insert only after the database initializer confirms an empty table; this reader never changes existing articles. - -Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. - -Return *[读取 seed 的实际字面表](document.read_table(path="db/articles.tables.md", title="seed"))*. diff --git a/examples/web-net-site/db/articles.tables.md b/examples/web-net-site/db/articles.tables.md deleted file mode 100755 index f45bf3b..0000000 --- a/examples/web-net-site/db/articles.tables.md +++ /dev/null @@ -1,23 +0,0 @@ -# Article data - -Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate. - -## schema - -Field definitions for the native database initializer; nullable values remain booleans. - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| title | text | false | -| body | text | true | - -## seed - -Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. - -| id | title | body | -|----|-------|------| -| 1 | Welcome to the web-net site | Home page lists rows from SQLite. | -| 2 | Login-gated admin | The /admin page requires a session cookie. | -| 3 | WebSocket live | The /live endpoint echoes your message in real time. | diff --git a/examples/web-net-site/db/index.mq.md b/examples/web-net-site/db/index.mq.md deleted file mode 100755 index 20e3294..0000000 --- a/examples/web-net-site/db/index.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: web-net-site database lifecycle -import: - data: ext/data/db.mq.md - articles: articles.mq.md - fs: lib/fs.mq.md - text: lib/text.mq.md ---- - -The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory. - -## open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | None | None selects data/site-net.db under the site root; tests provide a disposable explicit URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Initialized articles database resource with existing rows preserved | - -Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions. - -The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving. - -For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory. - -1. `url` == None - We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site-net.db"))** and **url = "sqlite:" + file**. -1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:")) - We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**. -We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.schema())**. -We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**. -1. not `existing` - We **seed = [Read the original demonstration data](articles.seed())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**. -Once the selected database is ready, return *store* for the site's resource bindings. diff --git a/examples/web-net-site/forms.mq.md b/examples/web-net-site/forms.mq.md deleted file mode 100755 index 13ac172..0000000 --- a/examples/web-net-site/forms.mq.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -markup: occlusion -title: Article form resource -import: - form: ext/data/form.mq.md ---- - -The same form resource supplies the page controls and validates the system submission route. The serving entry mounts it as article. The page only places a reference, so fields, limits and errors cannot drift between two separate form implementations. - -## article - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native insert form with title/body fields and original validation rules | - -Call with plugin before listening. Title is required and limited to 120 characters; body remains optional with an 8000-character limit. These are the original site's server-side rules. Rendering neither inserts a row nor authenticates a user; submission uses the application's actual articles database and current CSRF context. - -The field and rule tables stay immediately visible beside their explanation. No raw form HTML or client validation program is authored. After a valid submission the resource returns to the article list; rejected values retain field errors for correction. This public demonstration form is distinct from the login-gated native administration surface. - -`fields` = - -| name | label | type | required | -|---|---|---|---| -| title | Title | text | True | -| body | Body | textarea | False | - -`rules` = - -| field | rule | message | -|---|---|---| -| title | required | Title is required | -| title | max:120 | Title is too long | -| body | max:8000 | Body is too long | - -We **selected = [Create the actual article insert resource](form.form(table="articles", action="insert"))** and **selected = [Attach the readable field definitions](> `selected`.fields fields=`fields`)** and **selected = [Attach the server validation rules](> `selected`.rules rules=`rules`)**. -Return *[Keep submission and cancellation copy with this resource](> `selected`.labels submit="Publish" cancel="Cancel" cancel_href="/")*. diff --git a/examples/web-net-site/index.mq.md b/examples/web-net-site/index.mq.md deleted file mode 100755 index 551af4b..0000000 --- a/examples/web-net-site/index.mq.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Marqdo Net Site -import: - layout: components/index.mq.md - home: components/home.mq.md - database: db/index.mq.md - forms: forms.mq.md - styles: styles/shell.mq.md - web: ext/web/web.mq.md - form: ext/data/form.mq.md - admin: ext/data/admin.mq.md - auth: ext/security/auth.mq.md - socket: ext/net/websocket.mq.md - fs: lib/fs.mq.md - result: lib/result.mq.md ---- - -Read this entry, then the layout index, content leaves, database entry, form resource and browser client. Home, About, Publish and Tools are declared Documents. Native administration remains enabled and login-gated. The /live socket is a separate network resource. No page uses the removed compose APIs or a raw HTML shell. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Shared recursive frame around introduction, echo controls and current articles | - -This startup function describes structure, reading only the terminal Markdown leaves. The database query remains a typed resource resolved per request, while the client uses native controls and the official bridge. Rendering the page cannot initialize or clear business records. Follow each component import to edit one responsibility instead of reproducing the complete page. - -We **body = [Assemble the three independent home responsibilities](home.nodes())**. -Return *[Place them in the shared recursive site frame](layout.frame(body=`body`))*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-net-site" | Explicit discovery directory relative to the checkout | -| port | number | 18083 | Local demonstration listen port | -| url | any | None | None chooses the site-root SQLite file; tests use an owned temporary URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking listener with retained article data, forms, authentication and echo | - -Use `root`="examples/web-net-site", `port`=18083 and `url`=None from the checkout, with --fs-root examples/web-net-site and plugin,fs.write,network.write. Build current browser assets into public/generated through the development handbook first. Missing runtime assets stop before listening rather than leaving the widget apparently ready. - -Initialization preserves existing articles and seeds only an empty table. Theme compilation uses the original property declarations and writes only the explicit generated stylesheet. Discovery assembles the readable Documents, then the workflow enables native administration, attaches local fixture credentials, mounts the public article form and binds anonymous loopback echo. Real deployment must replace fixture credentials and its network policy. Keep each returned app before listening. - -`assets` = - -| file | -|---| -| public/generated/marqdo_wasm.wasm | -| public/generated/marqdo-bridge.js | - -- [Require the actual runtime resources before serving](for assets as file) - 1. not [The selected runtime asset exists](fs.exists(path=`file`)) - Return *[Explain the required browser preparation](result.error(code="net_site.browser_assets", message="build current browser assets into public/generated before serve", operation="serve"))*. -We **store = [Initialize the retained article database](database.open(url=`url`))** and **css = [Compile the actual declarative theme](styles.css())** and **[Create only the generated resource directory](fs.make_dirs(path="public/generated"))** and **[Write that explicit stylesheet through native IO](fs.atomic_write(path="public/generated/theme.css", text=`css`))**. -We **app = [Discover all declared Documents and the static root](web.prepare(root=`root`, host="127.0.0.1", port=`port`, db=`store`, static_dir="public"))** and **app = [Retain the existing native administration capability](admin.enable(app=`app`))**. - -`users` = - -| @ | username | password | role | -|---|---|---|---| -| 1 | admin | secret | admin | - -We **app = [Attach actual login sessions and the native admin gate](auth.attach(app=`app`, users=`users`, login_path="/admin/login", login_redirect="/admin", logout_redirect="/"))** and **article = [Build the shared validation resource](forms.article())** and **app = [Mount the public creation form explicitly](form.mount(app=`app`, id="article", form=`article`))**. -We **app = [Bind the original local WebSocket echo route](socket.route(app=`app`, path="/live", mode="echo", require_auth=False))**. -Return *[Listen only after data, resources and policy are ready](web.listen(app=`app`))*. diff --git a/examples/web-net-site/pages/about.mq.md b/examples/web-net-site/pages/about.mq.md deleted file mode 100755 index 4452010..0000000 --- a/examples/web-net-site/pages/about.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /about -title: About -import: - component: ext/web/component/index.mq.md - layout: ../components/index.mq.md - fs: lib/fs.mq.md ---- - -This Document declares its actual /about route. Its terminal explanation stays in Markdown and its parent frame owns navigation, side rail and footer. No data query or server setup occurs while reading this explanatory page. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Shared site frame containing this page's explanation | - -The server assembles these nodes once, then resolves request resources only while serving. Reading requires fs.read. Follow the shared layout imports to change one region without reproducing an HTML shell here. The route remains discoverable from metadata rather than an implicit mutation chain. - -We **text = [Read the page's terminal explanation](fs.read_text(path="components/content/about.md"))** and **body = [Describe ordinary Markdown content](component.markdown(text=`text`, slot="intro"))**. -Return *[Place this page within the shared recursive frame](layout.frame(body=`body`))*. diff --git a/examples/web-net-site/pages/new.mq.md b/examples/web-net-site/pages/new.mq.md deleted file mode 100755 index 48f868f..0000000 --- a/examples/web-net-site/pages/new.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /new -title: Publish -import: - component: ext/web/component/index.mq.md - layout: ../components/index.mq.md - fs: lib/fs.mq.md - form: ext/data/form.mq.md - table: lib/table.mq.md ---- - -This Document declares its actual /new route. Its terminal explanation stays in Markdown and its parent frame owns navigation, side rail and footer. The form is referenced by its explicit mounted id; the resource and real submission policy are defined outside this page. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Shared site frame containing this page's explanation and mounted form reference | - -The server assembles these nodes once, then resolves request resources only while serving. Reading requires fs.read. The current session's CSRF token and return path are supplied by the form renderer, so the page cannot embed a stale startup token. Missing form registration is a real request error. The route remains discoverable from metadata rather than an implicit mutation chain. - -We **text = [Read the page's terminal explanation](fs.read_text(path="components/content/new.md"))** and **body = [Describe ordinary Markdown content](component.markdown(text=`text`, slot="intro"))**. -We **selected = [Reference the actual mounted article form](form.reference(id="article"))** and **controls = [Place that request resource](component.resource(value=`selected`, slot="article-form"))** and **body = [Keep instructions before the form](table.concat(a=`body`, b=`controls`))**. -Return *[Place this page within the shared recursive frame](layout.frame(body=`body`))*. diff --git a/examples/web-net-site/pages/tools.mq.md b/examples/web-net-site/pages/tools.mq.md deleted file mode 100755 index 03bfd7d..0000000 --- a/examples/web-net-site/pages/tools.mq.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /tools -title: Network parsing tools -import: - net: lib/net.mq.md - fs: lib/fs.mq.md - table: lib/table.mq.md - component: ext/web/component/index.mq.md - layout: ../components/index.mq.md ---- - -This Document executes the standard network parsers against explicit local fixtures. It makes no external HTTP request. Cookie headers remain text, and the multipart fixture is terminal protocol data in components/content/multipart.txt. The page shows actual returned records as plain preformatted text instead of concatenating raw HTML. - -## _panel - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| title | text | required | Author-controlled heading describing one observed parser value | -| value | any | required | Actual native parser result to display literally | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Markdown heading followed by an escaped native preformatted value | - -Use `title` and `value` to keep each observed value beside its purpose. A parser record is data, not an HTML fragment; convert it to its native display text and let the pre element preserve characters. The author supplies headings, while protocol content never becomes a heading or executable expression. This pure helper performs no IO or parsing itself. - -We **heading = "## " + title** and **label = [Describe the observation in Markdown](component.markdown(text=`heading`))** and **text = [Retain the actual structured parser value](str(value))** and **data = [Show that value literally](component.element(kind="pre", value=`text`))**. -Return *[Keep meaning and actual evidence together](table.concat(a=`label`, b=`data`))*. - -## _cookies - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Actual Cookie request and Set-Cookie response observations | - -The first parser call reads a request Cookie header containing session and theme pairs. The second deliberately enables response-header mode, where Path, HttpOnly and SameSite describe the id cookie rather than becoming independent request cookies. Both results come from the maintained standard library. These are deterministic text fixtures, not real credentials or a browser session lookup. - -Keeping both modes visible preserves the original network-tools capability and explains why their output shapes differ. No cookie is written, accepted for authentication or sent to a remote service. The output panes expose all native fields, so a reader can inspect names, values and flags without decoding a generated HTML string. - -We **request = [Parse the explicit request-cookie fixture](net.cookie_parse(text="session=abc123; theme=dark"))** and **response = [Parse one actual response-cookie fixture](net.cookie_parse(text="id=42; Path=/; HttpOnly; SameSite=Lax", is_response=True))**. -We **request_panel = [Show actual request pairs](_panel(title="Cookie request", value=`request`))** and **response_panel = [Show actual response attributes](_panel(title="Set-Cookie response", value=`response`))**. -Return *[Keep the two parser modes adjacent](table.concat(a=`request_panel`, b=`response_panel`))*. - -## _multipart - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Actual multipart field and file-part observations | - -Read the protocol fixture with fs.read from the site root, then parse it using net-boundary, the delimiter declared by that fixture. The title part contains Hello. The cover part names pic.png with image/png content type; its value is the literal demonstration text , not an uploaded binary image. This distinction keeps the example's claims aligned with the bytes actually parsed. - -The result is a native part list, so the field and file panes select its first and second records through collection helpers. A missing or malformed fixture remains a parser or filesystem diagnostic rather than a hand-authored expected result. No upload, file extraction or network access occurs, and the fixture is not interpreted as Markdown code. - -We **body = [Read the exact local multipart protocol bytes as text](fs.read_text(path="components/content/multipart.txt"))** and **parts = [Parse the real boundary and disposition fields](net.multipart_parse(body=`body`, boundary="net-boundary"))**. -We **field = [Select the first parsed part](table.first(list=`parts`))** and **file = [Select the second parsed part](table.at(xs=`parts`, i=1))** and **field_panel = [Show the actual form field](_panel(title="Multipart field", value=`field`))** and **file_panel = [Show actual file metadata](_panel(title="Multipart file", value=`file`))**. -Return *[Keep both actual parser observations](table.concat(a=`field_panel`, b=`file_panel`))*. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Shared site frame around all four native parser observations | - -This startup assembly requires fs.read only for the terminal multipart fixture and the shared Markdown layout leaves. The standard parser calls themselves are pure. The four panes preserve request cookies, response cookies, a multipart field and multipart file metadata. None represents a request to an external site or a user upload. - -Changing a fixture should change the displayed result because the page runs the real parser, not a copied expected answer. Keep the explanatory heading and the observed values together, and retain the shared navigation to Publish, administration and the live widget. - -We **intro = [Explain the deterministic tools page](component.markdown(text="# Net tools\n\nParsing demonstrations powered by the actual standard network library."))** and **cookies = [Observe both cookie modes](_cookies())** and **parts = [Observe both multipart part types](_multipart())**. -We **body = [Keep the explanation before observations](table.concat(a=`intro`, b=`cookies`))** and **body = [Retain multipart observations after cookies](table.concat(a=`body`, b=`parts`))**. -Return *[Place all observations in the shared site frame](layout.frame(body=`body`))*. diff --git a/examples/web-net-site/public/client.mq.md b/examples/web-net-site/public/client.mq.md deleted file mode 100755 index eee3e21..0000000 --- a/examples/web-net-site/public/client.mq.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -markup: occlusion -title: Network-site echo client -import: - browser: lib/browser.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -The client owns connection state and a plain text message log. Native controls are declared by components/live.mq.md. The relative socket path follows the page's actual host and port, while the server resource owns echo behavior. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Native event wiring, socket opening and initial status effects | - -The button click carries the current input value to send. A connection opening enables the button; closure or error disables it. Incoming text appends to retained entry state and never becomes HTML. This is a live echo demonstration, not durable storage or an automatic reconnection loop. BrowserSession keeps entry bindings for callbacks, so they are state rather than fictitious public parameters. - -We **ws_id = "live"** and **messages = ""** before describing the transport. - -`wire` = - -| @ | 选择器 | 事件 | 调用 | 值选择器 | -|---|---|---|---|---| -| 1 | "#live-send" | click | send | "#live-msg" | -| 2 | "#live-msg" | keydown | on_key | "#live-msg" | - -`open` = - -| op | id | url | then_open | then_message | then_error | then_close | -|---|---|---|---|---|---|---| -| open | `ws_id` | /live | on_open | on_message | on_error | on_close | - -We **bindings = [Bind the existing send control](table.put(in=None, at="wire", value=`wire`))** and **socket = [Describe the same-origin WebSocket connection](browser.ws(spec=`open`))**. -Return *[Keep transport and native control wiring together](browser.merge(a=`bindings`, b=`socket`))*. - -## _status - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Plain connection status to display | -| disabled | bool | required | Actual native disabled state for the send button | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Combined status-text and button-attribute effects | - -Use `text` and `disabled` to keep connection feedback consistent with the send control. The attribute must remain a boolean: the bridge removes disabled when False, while the string "false" would still be a present HTML boolean attribute. These effects describe a DOM update and do not send or retry a message. - -We **attributes = [Keep the actual boolean attribute value](table.put(in=None, at="disabled", value=`disabled`))** and **status = [Describe plain connection feedback](browser.set_text(sel="#live-status", text=`text`))** and **button = [Describe actual send availability](browser.set_attr(sel="#live-send", attrs=`attributes`))**. -Return *[Keep the independent effect kinds together](browser.merge(a=`status`, b=`button`))*. - -## on_open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | bool | True | Actual browser transport opening result | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Connected feedback and enabled send, or failed feedback and disabled send | - -Use `ok`=True from the opening callback. A successful opening proves only the transport is ready; an echoed message is observed separately. Failed opening keeps send disabled and visible as failure. The client does not publish a fake initial echo or silently retry. - -1. `ok` - Return *[Enable sending only after transport opens](_status(text="connected", disabled=False))*. -Return *[Keep failed opening visible](_status(text="connection failed", disabled=True))*. - -## _send - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | required | Input text supplied by a click or Enter callback | -| channel | text | required | Existing socket id retained by the client entry | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | One actual send instruction, or None for empty trimmed input | - -Use `value` and `channel` to share the original widget's send policy. Trim surrounding whitespace and ignore an empty result. A nonempty message remains plain text, never a command or HTML. The official bridge reports transport errors separately. This helper receives its channel explicitly rather than assuming an ordinary nested call automatically captures entry state. - -We **payload = [Keep the original trim-before-send behavior](text.str_trim(s=`value`))**. -1. `payload` == "" - Return *None* because an empty or whitespace-only input performs no send. - -`operation` = - -| op | id | data | -|---|---|---| -| send | `channel` | `payload` | - -Return *[Send one nonempty message through the existing connection](browser.ws(spec=`operation`))*. - -## send - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | "" | Current text supplied by the send-button wiring | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Send effect for nonempty trimmed input, otherwise None | - -Use `value`="" from a button click. The direct browser callback can read retained entry state and passes that socket id explicitly to the pure send helper. The log updates only after an actual echo arrives, so clicking cannot fabricate successful delivery. Whitespace-only input retains the original widget's no-send behavior. - -Return *[Apply the shared send policy to this click](_send(value=`value`, channel=`ws_id`))*. - -## on_key - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | "" | Actual key name supplied by the official bridge | -| value | text | "" | Current message input supplied by this control's value selector | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Enter uses the same send policy as the button; other keys return None | - -Use `key`="" and `value`="" from the keyboard wiring. Preserve the original Enter shortcut without sending on every keydown. Enter and click share trimming and empty-input behavior, and neither appends a local echo before a real frame arrives. This callback does not install another DOM handler or start a second socket. - -1. `key` == "Enter" - Return *[Apply exactly the button's send policy](_send(value=`value`, channel=`ws_id`))*. -Return *None* for an ordinary editing key. - -## on_message - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | text | "" | Actual echoed text frame from the server | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Plain text update containing the retained echo log | - -Use `data`="" from the message callback. Append each real frame and a newline to entry state, preserving earlier messages as the old widget did. set_text escapes content through the bridge; a message containing markup is shown literally. Reloading starts a fresh demonstration log and no durable history is claimed. - -We **messages = [Retain the next observed echo](messages + "echo: " + data + "\n")**. -Return *[Display the complete observed log as text](browser.set_text(sel="#live-out", text=`messages`))*. - -## on_error - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| error | text | "" | Browser transport error description | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Error feedback and disabled sending | - -Use `error`="" to retain the actual transport failure beside the controls. No previous message is erased and no new send is attempted. The page can be reloaded for a fresh connection; this demonstration has no hidden reconnect policy. - -We **message = "error: " + error**. -Return *[Keep failure and send availability consistent](_status(text=`message`, disabled=True))*. - -## on_close - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Closed feedback with disabled send control | - -A close notification keeps the message log readable while marking the socket unavailable. It neither clears entry state nor silently creates another connection. Subsequent sends require a newly opened page session rather than a fabricated successful transport. - -Return *[Keep closure visible](_status(text="closed", disabled=True))*. diff --git a/examples/web-net-site/styles/shell.mq.md b/examples/web-net-site/styles/shell.mq.md deleted file mode 100755 index e8c020b..0000000 --- a/examples/web-net-site/styles/shell.mq.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -markup: occlusion -import: - web: ext/web/web.mq.md - text: lib/text.mq.md ---- - -## topnav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -`topnav` = - -| 属性 | 值 | -|------|-----| -| background | #ffffff | -| border-bottom | 1px solid #e7e5e4 | - -After these steps, return *topnav*. - -## side_panel - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -`side_panel` = - -| 属性 | 值 | -|------|-----| -| background | #f5f5f4 | - -After these steps, return *side_panel*. - -## card_title - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -`card_title` = - -| 属性 | 值 | -|------|-----| -| font-size | 1.15rem | -| margin | 0 0 0.35rem | - -After these steps, return *card_title*. - -## card_body - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -`card_body` = - -| 属性 | 值 | -|------|-----| -| color | #57534e | -| margin | 0 | - -After these steps, return *card_body*. - -## css - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | CSS compiled from the original four declarative property tables | - -Call with plugin before discovery. This task preserves the original top navigation background/border, side-panel background, card title size/spacing and card body color/spacing. The selector names target the native components and query-card markup directly. The property functions remain independently callable, so changing one region does not require editing a raw CSS string. - -The server writes the returned text through native filesystem IO into its explicit generated resource path. Compilation itself neither writes that file nor mounts static content. These four sections keep their original order; the general View runtime still owns responsive row geometry. A compiler diagnostic stops serving instead of substituting an old stylesheet. - -We **nav = [Read the original navigation declarations](topnav())** and **side = [Read the original side-panel declarations](side_panel())** and **title = [Read the original title declarations](card_title())** and **body = [Read the original summary declarations](card_body())**. -We **nav_css = [Compile the navigation selector](web.make_style(name="topnav", table=`nav`))** and **side_css = [Compile the side selector](web.make_style(name="side", table=`side`))** and **title_css = [Compile the native card title selector](web.make_style(name="content.cards h2", table=`title`))** and **body_css = [Compile the native card body selector](web.make_style(name="content.cards p", table=`body`))**. - -`parts` = - -| css | -|---| -| `nav_css` | -| `side_css` | -| `title_css` | -| `body_css` | - -Return *[Keep the compiled sections in order](text.str_join(xs=`parts`, sep="\n"))*. diff --git a/examples/web-site-zh/README.md b/examples/web-site-zh/README.md deleted file mode 100755 index 480728c..0000000 --- a/examples/web-site-zh/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# web-site-zh - -中文作者通过网页、表单与鉴权资源组织站点。首页、关于、写文章、后台与短链详情各自声明路由;父组件组合结构,内容叶子只写 Markdown。主题保留原来的墨色、酒红、金色、字体、粒子、断点和表单状态,不写作者业务 JavaScript 或手写 CSS。 - -从仓库根使用当前源码 CLI,先准备工程与 Web 插件,再调用真实启动流程: - -```sh -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json -target/debug/marqdo call examples/web-site-zh/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-site-zh --require-ok --json -``` - -打开 http://127.0.0.1:18082/ ;默认数据库位于站点文件根的 data/site-zh.db,重启保留现有文章。admin/demo 仅为本机演示账户。服务阻塞当前进程,停止由调用者负责。 - -按职责阅读: - -- [工程入口](index.mq.md) — 声明首页,组合数据、表单、会话、门禁与监听。 -- [布局入口](components/index.mq.md) — 公共侧栏与独立后台结构,终端叶子在 components/content。 -- [文章请求资源](components/articles.mq.md) — 当前摘要卡片与真实短链完整正文。 -- [共享表单](forms.mq.md) — 实际字段和规则在 forms.tables.md,校验失败保留 CSRF。 -- [主题入口](styles/index.mq.md) — 保留原始数据,只映射结构地址并适配包装几何。 -- [原生核对工具](verify.mq.md) — 实际比较 412 条原始布局/动画声明并返回 CSS 身份。 - -```sh -target/debug/marqdo call examples/web-site-zh/verify.mq.md theme_values --effects plugin,fs.read --fs-root examples/web-site-zh --require-ok --json -``` - -主题生成在 public/generated/theme.css;它是可再生产物,源码为相邻声明表,不应手改生成文件。字体链接保留 Google Fonts 地址,离线使用原声明中的后备字体;本地浏览器验收不声称验证远端字体服务送达。 - -公共创建表单继续公开,后台页面则有实际角色门禁。共享表单出现在后台不意味着提交端点自动私有。实际 HTTP 回归在 Tree、Bytecode 中使用独占副本站点;真实浏览器验证样式、发布、详情、会话导航、退出与窄屏顺序,避免操作示例已有数据库。 - -动手流程见英文对应工程的 [DEMO.md](../web-site/DEMO.md)。 diff --git a/examples/web-site-zh/components/articles.mq.md b/examples/web-site-zh/components/articles.mq.md deleted file mode 100755 index 0540861..0000000 --- a/examples/web-site-zh/components/articles.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: 当前文章卡片与短链详情 -import: - 组件: ext/web/网页/组件/索引.mq.md - 视图: ext/data/视图.mq.md - 表: lib/表.mq.md ---- - -两种视图随请求查询应用持有的同一 articles 表。卡片使用摘要和短链,详情使用完整 Markdown 正文。构造描述不另开数据库,也不缓存启动时的旧记录;原生卡片与文章类名供原主题继续使用。 - -## cards - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 通过 /post/短链 打开详情的当前文章卡片 | - -构造不需要副作用。监听应用拥有数据库与实际执行上下文,卡片保留原来的稳定 id 顺序,字段仍为 title、summary 与 slug。标题、摘要按文本转义,完整正文只留给详情。公共发布或后台共享表单新增文章后,下次请求即能看见,不必重启站点。 - -我们 **资源 = [描述实际当前文章列表](视图.查询(源="articles", 排序="id", 链接前缀="/post/"))**。 -最后返回 *[安放一个请求期间的卡片职责](组件.请求资源(值=`资源`, 槽="articles"))*。 - -## detail - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 实际路径捕获选中的首篇完整 Markdown 文章 | - -声明的 /post/{slug} 页面在请求解析资源时提供路径参数,同名查询字符串不能替换它。原生详情即使有摘要也使用完整正文,并且每次复制条件再替换参数,不污染启动时保留的定义。缺少数据库仍是错误;没有匹配记录沿用现有查询资源的空结果约定。 - -条件保留为明确记录,不能把单列表误当字典。父层继续拥有文章区域的位置,本函数不自己拼接标题或渲染 Markdown,以免与卡片规则和当前请求上下文分离。 - -我们 **条件 = [保留实际短链条件记录](表.设(map=None, key="slug", value="{slug}"))** 和 **资源 = [描述匹配短链的完整正文](视图.查询(源="articles", 条件=`条件`, 详情=True, 上限=1))**。 -最后返回 *[安放实际请求的文章](组件.请求资源(值=`资源`, 槽="article"))*。 diff --git a/examples/web-site-zh/components/content/about.md b/examples/web-site-zh/components/content/about.md deleted file mode 100755 index d469ec5..0000000 --- a/examples/web-site-zh/components/content/about.md +++ /dev/null @@ -1,5 +0,0 @@ -> 关于 - -# 关于 - -文档与站点同一 .mq.md 制品。版式与主题是 styles/shell.mq.md 里的 GFM 样式表——无需手写 CSS 或业务 JavaScript。 diff --git a/examples/web-site-zh/components/content/desk-footer.md b/examples/web-site-zh/components/content/desk-footer.md deleted file mode 100755 index 157a171..0000000 --- a/examples/web-site-zh/components/content/desk-footer.md +++ /dev/null @@ -1 +0,0 @@ -[站点](/) · [后台](/admin) · [退出](/admin/logout) diff --git a/examples/web-site-zh/components/content/desk.md b/examples/web-site-zh/components/content/desk.md deleted file mode 100755 index 67997e7..0000000 --- a/examples/web-site-zh/components/content/desk.md +++ /dev/null @@ -1,9 +0,0 @@ -> 管理台 · 已进入后台 - -# 后台 - -这就是管理台(需登录):与前台共用 articles schema,装配成列表 + 创建表单——不是另写一套 SPA。顶栏「站点」回前台,「退出」结束会话。 - -- 登录门禁 -- 表声明 -- 创建 + 列表 diff --git a/examples/web-site-zh/components/content/footer.md b/examples/web-site-zh/components/content/footer.md deleted file mode 100755 index eae8fb2..0000000 --- a/examples/web-site-zh/components/content/footer.md +++ /dev/null @@ -1 +0,0 @@ -[Marqdo](https://www.marqdo.com/) · [Source](https://github.com/cflmy/marqdo) diff --git a/examples/web-site-zh/components/content/home.md b/examples/web-site-zh/components/content/home.md deleted file mode 100755 index bc4e7f2..0000000 --- a/examples/web-site-zh/components/content/home.md +++ /dev/null @@ -1,13 +0,0 @@ -> WWW Demo · 表即全栈 - -# Marqdo - -一份可执行 Markdown 声明路由、表单、后台与样式——作者零业务 JavaScript、零手写 .css。点击卡片打开全文,再按下列三步动手试。 - -- 0 作者 JS -- 0 作者 .css -- GFM 表 - -1. 点击任意卡片 — /post/{slug} 用同一张 articles 表打开详情。 -2. 打开[写文章](/new),空标题提交(规则表校验)。 -3. 点顶栏**登录**(admin / demo),再进**后台** — 门禁管理台:创建表单 + 列表。 diff --git a/examples/web-site-zh/components/content/new.md b/examples/web-site-zh/components/content/new.md deleted file mode 100755 index c93791f..0000000 --- a/examples/web-site-zh/components/content/new.md +++ /dev/null @@ -1,5 +0,0 @@ -> 表单 · 试校验 - -# 写文章 - -空标题提交应失败(规则表,非客户端 JS);填写标题、slug 与摘要后与后台、卡片网格共享一行。 diff --git a/examples/web-site-zh/components/content/post.md b/examples/web-site-zh/components/content/post.md deleted file mode 100755 index 3eea0ff..0000000 --- a/examples/web-site-zh/components/content/post.md +++ /dev/null @@ -1 +0,0 @@ -> 文章 · 表绑定详情 diff --git a/examples/web-site-zh/components/desk.mq.md b/examples/web-site-zh/components/desk.mq.md deleted file mode 100755 index b154266..0000000 --- a/examples/web-site-zh/components/desk.mq.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -markup: occlusion -title: 后台独立导航与页脚 -import: - 组件: ext/web/网页/组件/索引.mq.md - 文件: lib/文件.mq.md ---- - -自定义后台保留自己的品牌与结束链接,不带公共侧栏。实际鉴权仍归服务入口;构造这些节点或隐藏某个链接都不会授权访客进入管理页面。 - -## nav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 按当前会话解析的后台导航 | - -构造无需副作用。首项保持后台上下文,随后提供站点、写文章及退出;与原站一样,只有退出行依赖登录条件。整个页面已由服务入口另行保护,退出目的地仍是原生会话地址。本块返回结构化资源,父层负责位置和外观,不能把可见性判断当成服务器门禁。 - -后台与公共导航分开,避免管理中的品牌仍跳向首页。修改路径应同步检查真实处理器清单,防止链接看似存在却没有声明对应行为。 - -`项目` = - -| @ | label | href | when | -|---|---|---|---| -| 1 | 后台 | /admin | | -| 2 | 站点 | / | | -| 3 | 写文章 | /new | | -| 4 | 退出 | /admin/logout | auth | - -我们 **资源 = [描述后台实际会话导航](组件.导航资源(项=`项目`))**。 -最后返回 *[保持相同导航片段身份](组件.请求资源(值=`资源`, 槽="nav"))*。 - -## foot - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 后台终端 Markdown 返回与退出链接 | - -授予站点文件根的 fs.read。实际路由门禁在渲染本组件之前已决定访问,站点和后台保留返回目标;退出只有被访问时才结束会话,读叶子不产生退出操作。页脚只有一个链接职责,内部无独立几何,不为凑目录再拆一层。父层放置它,主题提供原来的页脚外观。 - -我们 **文本 = [读取后台终端结束链接](文件.读文本(路径="components/content/desk-footer.md"))** 和 **叶子 = [保留普通 Markdown 内容](组件.正文(文本=`文本`, 槽="footer-content"))**。 -最后返回 *[放入后台语义页脚](组件.包裹(子节点=`叶子`, 种类="footer", 槽="footer", 样式="foot"))*。 diff --git a/examples/web-site-zh/components/foot.mq.md b/examples/web-site-zh/components/foot.mq.md deleted file mode 100755 index c244f51..0000000 --- a/examples/web-site-zh/components/foot.mq.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -markup: occlusion -title: 公共页脚的终端 Markdown -import: - 组件: ext/web/网页/组件/索引.mq.md - 文件: lib/文件.mq.md ---- - -公共页脚只有项目与源码链接,内部没有独立双栏,因此简单 Markdown 就是拆分终点。父层决定它出现在何处,主题沿用原来页脚的颜色、间距和字号。 - -## foot - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 保留原始链接的语义页脚 | - -以站点为文件根授予 fs.read。内容叶子保留原项目与源码目的地,不查询业务记录,也不读取凭据。改文案只修改 content/footer.md;改几何回到父布局。组件输出仍是嵌套节点,不先把叶子渲染成不透明 HTML 再拼回页面。 - -我们 **文本 = [读取终端项目链接](文件.读文本(路径="components/content/footer.md"))** 和 **叶子 = [保留普通 Markdown 链接](组件.正文(文本=`文本`, 槽="footer-content"))**。 -最后返回 *[保留页脚语义与主题类](组件.包裹(子节点=`叶子`, 种类="footer", 槽="footer", 样式="foot"))*。 - diff --git a/examples/web-site-zh/components/head.mq.md b/examples/web-site-zh/components/head.mq.md deleted file mode 100755 index 3374a2c..0000000 --- a/examples/web-site-zh/components/head.mq.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -markup: occlusion -title: 首页 SEO、共享字体与主题声明 -import: - 组件: ext/web/网页/组件/索引.mq.md - 页头: ext/web/页头.mq.md ---- - -本叶子保留原站的首页元数据与 Google Fonts 资源地址。装配只声明链接,不下载字体;主题由服务入口从表编译并写到明确静态目录。 - -## nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| homepage | bool | False | 仅首页显式保留原来的首页 SEO | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 进入真正 head 的纯 SEO、字体与主题资源 | - -使用`homepage`=False,在装配阶段纯构造。元数据为 key/value 行记录,字体与样式继续使用 rel/href/crossorigin 原生字段。只有首页显式选择原来的 SEO,其余页面只共享字体与主题,避免把首页描述错误地复制到每篇文章。原生渲染将它们收集到真正 head,去重相同链接,不在正文或片段中输出占位。 - -字体是否成功送达取决于浏览器能否访问外部服务;不可用时仍使用主题声明的后备字体。地址声明不等于生成文件,服务入口须在监听之前编译并写出确切路径。资源构造不加载插件、不验证远端状态、不运行脚本,也不把网络错误当作已经加载成功。 - -字体表中的第一项预连接样式服务,第二项保留字体源的 anonymous 跨域设置,第三项保留原始字体集合与字重。最后的站内样式链接只对应本次生成产物,源头仍是可读属性表。标题与文案保留在各自 Document,页头不承担整页配置或应用变异。离线预览使用同一个元数据收集过程,片段只更新已打开页面,不重复注入字体与 SEO。 - -`元数据` = - -| @ | key | value | -|---|---|---| -| 1 | description | 表即全栈 — Marqdo 网页示例;作者零业务 JavaScript。 | -| 2 | og:type | website | -| 3 | og:title | Marqdo 中文站 | - -`链接` = - -| @ | rel | href | crossorigin | -|---|---|---|---| -| 1 | preconnect | https://fonts.googleapis.com | | -| 2 | preconnect | https://fonts.gstatic.com | anonymous | -| 3 | stylesheet | https://fonts.googleapis.com/css2?family=Great+Vibes&family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;600&display=swap | | -| 4 | stylesheet | /static/generated/theme.css | | - -我们 **选定元数据 = None**,其他页面只保留共享链接。 -1. `homepage` - 我们 **选定元数据 = 元数据**,只给首页保留原 SEO。 -我们 **资源 = [保留实际元数据与原生资源链接](页头.声明(元数据=`选定元数据`, 链接=`链接`))**。 -最后返回 *[把纯页头声明与结构一起保留](组件.请求资源(值=`资源`, 槽="document-head"))*。 diff --git a/examples/web-site-zh/components/index.mq.md b/examples/web-site-zh/components/index.mq.md deleted file mode 100755 index 94b2ab9..0000000 --- a/examples/web-site-zh/components/index.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: 公共与后台递归布局入口 -import: - 组件: ext/web/网页/组件/索引.mq.md - 导航: nav.mq.md - 侧栏: side.mq.md - 页脚: foot.mq.md - 后台: desk.mq.md - 页头: head.mq.md - 表: lib/表.mq.md ---- - -本父模块只决定站点结构。公共页面保留导航、侧栏和主体、页脚;后台采用自己的导航与页脚,不带公共侧栏。各子模块拥有 Markdown 或具型请求资源,父层不渲染子块后再拼 HTML。 - -## frame - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| body | list | 必填 | 页面自己提供并保留资源值的主体节点 | -| management | bool | False | 选择已被实际门禁保护的后台框架 | -| homepage | bool | False | 只有首页保留原来的首页 SEO | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 递归站点结构及真正收集到 head 的纯资源 | - -使用`body`、`management`=False、`homepage`=False。导航按当前请求会话解析,本函数不认证用户;后台路径由服务入口另行保护,选择后台框架不会授予权限。页脚只有一组普通链接,内部已可用简单 Markdown 表示,因此无需人为继续拆分。 - -稳定槽名 nav、sidebar、main 与 footer 保留片段身份。原生资源外层继续留在结构树中,主题让其语义子块参与原来的命名网格。is-desk 类属于这个明确框架,代替旧的整页 body 变异;颜色、动画与属性值仍来自原始声明。纯页头资源不会成为用户正文。 - -我们 **顶部 = [组合公共导航](导航.nav())**、**旁栏 = [组合公共侧栏](侧栏.side())**、**底部 = [读取公共 Markdown 页脚](页脚.foot())** 和 **样式 = "site-layout has-sidebar"**。 -1. `management` - 我们 **顶部 = [使用后台自己的导航](后台.nav())**、**旁栏 = [后台不带公共侧栏](表.空表())**、**底部 = [读取后台返回链接](后台.foot())** 和 **样式 = "site-layout no-sidebar is-desk"**。 -我们 **主体 = [保留页面自身的正文责任](组件.包裹(子节点=`body`, 种类="section", 槽="main", 样式="main"))**、**子块 = [导航位于公共侧栏之前](表.拼接(a=`顶部`, b=`旁栏`))**、**子块 = [放入实际主体](表.拼接(a=`子块`, b=`主体`))** 和 **子块 = [以选定页脚结束](表.拼接(a=`子块`, b=`底部`))**。 -接着 **框架 = [声明稳定的站点区域](组件.包裹(子节点=`子块`, 种类="section", 槽="site", 样式=`样式`))** 和 **资源 = [保留字体、主题与选定 SEO](页头.nodes(homepage=`homepage`))**。 -最后返回 *[让声明与递归框架一并保留](表.拼接(a=`资源`, b=`框架`))*。 diff --git a/examples/web-site-zh/components/intro.mq.md b/examples/web-site-zh/components/intro.mq.md deleted file mode 100755 index e431ba3..0000000 --- a/examples/web-site-zh/components/intro.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion -title: 终端 Markdown 引言组件 -import: - 组件: ext/web/网页/组件/索引.mq.md - 文件: lib/文件.mq.md ---- - -引言终止于普通 Markdown:分类、标题、解释、特性列表与阅读步骤。它们已经能直接用文档层次表达,主题选择这些真实语义元素。页面几何仍归父框架,不恢复旧的引言绑定方言。 - -## nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | 必填 | 作者选择的 home、about、new、desk 或 post 叶子 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 包裹实际终端 Markdown 的语义引言区域 | - -输入`name`,在站点文件根授权 fs.read。路径由作者的 Document 选择,不是请求参数。缺失叶子保留原生文件诊断,不回退到抄写的固定正文。读取内容不会把其中的强调或链接执行成 Marqdo 语句,而是交给既有 Markdown 渲染器解释。 - -叶子内部没有独立的排列职责,只有引用分类、标题、段落、项目符号和编号步骤。若将来出现需要独立几何的子区域,应继续拆分。样式保留原来的字体、徽章与步骤面板,内容仍直接可读。 - -我们 **路径 = "components/content/" + name + ".md"**、**文本 = [读取这段引言的实际内容](文件.读文本(路径=`路径`))** 和 **叶子 = [保留简单的 Markdown 层次](组件.正文(文本=`文本`, 槽="intro-content"))**。 -完成后返回 *[将引言放入明确语义区域](组件.包裹(子节点=`叶子`, 种类="section", 槽="intro", 样式="main-intro"))*。 diff --git a/examples/web-site-zh/components/nav.mq.md b/examples/web-site-zh/components/nav.mq.md deleted file mode 100755 index ffc76c7..0000000 --- a/examples/web-site-zh/components/nav.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: 实际会话中的导航组件 -import: - 组件: ext/web/网页/组件/索引.mq.md ---- - -本模块只拥有这一组导航。文字、目标及顺序保留原站约定,会话相关行必须在每次请求中决定,因此使用具型导航资源,不能把启动时的身份快照当成当前用户。 - -## nav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 保留稳定片段槽名的单个导航请求资源 | - -构造是纯计算,不登录、退出或注册路由。空 when 始终显示,guest 与 auth 按服务器当前会话筛选;原生导航类名继续服务于已有主题。隐藏后台链接不能阻止直接访问,服务入口另行对实际 /admin 地址绑定角色门禁。 - -父模块负责网格位置,本块只解释目标。改文字在这里完成,改路径同时核对声明的 Document。资源值保留结构,不拼 HTML,也不返回已被移除的 front/back 页面绑定表。 - -`项目` = - -| @ | label | href | when | -|---|---|---|---| -| 1 | Marqdo | / | | -| 2 | 关于 | /about | | -| 3 | 写文章 | /new | | -| 4 | 登录 | /login | guest | -| 5 | 后台 | /admin | auth | -| 6 | 退出 | /admin/logout | auth | - -我们 **资源 = [描述当前会话的可见链接](组件.导航资源(项=`项目`, 区域="nav"))**。 -最后返回 *[保留一个具型导航区域](组件.请求资源(值=`资源`, 槽="nav"))*。 diff --git a/examples/web-site-zh/components/side.mq.md b/examples/web-site-zh/components/side.mq.md deleted file mode 100755 index f664be1..0000000 --- a/examples/web-site-zh/components/side.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: 实际会话中的侧栏组件 -import: - 组件: ext/web/网页/组件/索引.mq.md ---- - -本模块只拥有这一组导航。文字、目标及顺序保留原站约定,会话相关行必须在每次请求中决定,因此使用具型导航资源,不能把启动时的身份快照当成当前用户。 - -## side - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 保留稳定片段槽名的单个导航请求资源 | - -构造是纯计算,不登录、退出或注册路由。空 when 始终显示,guest 与 auth 按服务器当前会话筛选;原生导航类名继续服务于已有主题。隐藏后台链接不能阻止直接访问,服务入口另行对实际 /admin 地址绑定角色门禁。 - -父模块负责网格位置,本块只解释目标。改文字在这里完成,改路径同时核对声明的 Document。资源值保留结构,不拼 HTML,也不返回已被移除的 front/back 页面绑定表。 - -`项目` = - -| @ | label | href | when | -|---|---|---|---| -| 1 | 1. 首页 | / | | -| 2 | 2. 写文章 | /new | | -| 3 | 3. 登录 | /login | guest | -| 4 | 3. 后台 | /admin | auth | -| 5 | 关于 | /about | | - -我们 **资源 = [描述当前会话的可见链接](组件.导航资源(项=`项目`, 区域="sidebar"))**。 -最后返回 *[保留一个具型导航区域](组件.请求资源(值=`资源`, 槽="sidebar"))*。 diff --git a/examples/web-site-zh/db/articles.mq.md b/examples/web-site-zh/db/articles.mq.md deleted file mode 100755 index b442585..0000000 --- a/examples/web-site-zh/db/articles.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: 文章结构与种子调用手册 -import: - document: lib/document.mq.md ---- - -本文件解释各个调用的用途;相邻的 [articles.tables.md](articles.tables.md) 保存可直接阅读的字面表。把 --fs-root 指向站点目录,读取需要 fs.read。字段、样式与正文是数据,读取不会执行文件中的说明。 - -## schema - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 原生字面表的原始类型与列式数据形态 | - -声明文章的字段、原生类型与可空约束;id 的数值类型和必填字段保持不变。数据库初始化器使用此表保证结构,不负责猜测用户数据的迁移。 - -授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。 - -完成后返回*[读取 schema 的实际字面表](document.read_table(path="db/articles.tables.md", title="schema"))*. - -## seed - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 原生字面表的原始类型与列式数据形态 | - -提供起始演示文章,保留原来的 id、短链、摘要与正文。只有数据库初始化器确认空表后才应插入;读取本函数不会写入或重置现有文章。 - -授予站点文件根的 fs.read 后可独立调用。章节名精确匹配且必须唯一;表头、行列不齐或动态表达式会保留原生文档诊断。需要实际样式时再调用 css;需要数据库记录时交给数据库资源。返回值不是 HTML,也不是已应用的浏览器效果。 - -完成后返回*[读取 seed 的实际字面表](document.read_table(path="db/articles.tables.md", title="seed"))*. diff --git a/examples/web-site-zh/db/articles.tables.md b/examples/web-site-zh/db/articles.tables.md deleted file mode 100755 index 99e4512..0000000 --- a/examples/web-site-zh/db/articles.tables.md +++ /dev/null @@ -1,30 +0,0 @@ -# Article data - -Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate. - -## schema - -Field definitions for the native database initializer; nullable values remain booleans. - -| 字段 | 类型 | 可空 | -|------|------|------| -| id | integer | false | -| title | text | false | -| slug | text | false | -| summary | text | true | -| body | text | true | - -## seed - -Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. - -| id | title | slug | summary | body | -|----|-------|------|---------|------| -| 1 | 你好 Marqdo | hello-marqdo | 一份可执行 Markdown 既是站点说明,也是上线制品——路由、表单与样式都用表声明。 | "Marqdo 把 .mq.md 当作可执行文档。编辑器里读到的叙述,就是服务器跑起来的同一份制品:GFM 表变成 schema、表单、导航与 CSS。本 Demo 走完这条契约——打开「写文章」、触发规则表校验,再发布一行,首页与后台同时出现,全程无需作者业务 JavaScript。" | -| 2 | 表即全栈 | tables-full-stack | Schema、表单、路由、后台与主题令牌共用一套表方言,而不是 JS/CSS 分家。 | "常见技术栈把关切拆进多种语言:数据用 SQL/ORM,输入用表单库,URL 用路由,外观用手写样式。Marqdo 把这些表面收成作者本来就会写的 GFM 表。字段表、规则表、绑定表、样式表不是比喻,而是运行时。结果是一份既能当散文扫读、又能当程序执行的站点。" | -| 3 | 零作者 JS 与 CSS | zero-author-js-css | 业务留在 Markdown;外观是样式表加宿主壳——无作者业务 JS、无作者 .css。 | "作者业务 JavaScript 从构造上为零:校验来自服务端规则表,列表/详情由绑定表交给宿主渲染。主题令牌写在属性/值表里,经样式装配变成 CSS,作者也不必维护 .css 文件。本 Demo 关闭壳样式,只让声明过的样式上色——方便会议观众当场核对主张。" | -| 4 | 一表打通卡片与详情 | card-to-detail | 列表把 href 绑到 slug;/post/{slug} 加详情=真即可打开全文。 | "点击首页任意卡片。列表绑定用 articles.slug 作为 href,链接前缀补上 /post/。详情页复用同一张表,查询条件 slug = {slug},再页面.详情,首行就渲染成完整文章(标题 + Markdown 正文),而不是卡片网格。这与求道量子等更大的 Marqdo 站同一套路。" | -| 5 | 样式表不是样式文件 | style-tables | 具名样式表(kicker、intro_title、card_title)通过绑定表第三列挂上。 | "引言、卡片与壳层都用属性/值/样式绑定。样式列指向 styles/shell.mq.md 里的具名属性表。引言装配或主体装配时,这些表变成页面上的 CSS 类。改 Demo 外观不必打开 .css——改可读的 Markdown 表,文案与样式仍挨在一起。" | -| 6 | 表单来自字段表与规则表 | forms-from-tables | 「写文章」空标题会因规则表失败;合法提交写入与后台共享的一行。 | "写文章与后台挂载同一表单对象:字段表声明标签与类型,规则表声明 required、max 与提示文案。空标题提交时错误来自服务端,不是客户端脚本。填好标题与 slug 再提交,卡片网格与后台列表都会出现——一张 schema、两个表面、零作者 JS。" | -| 7 | 种子数据就是文档 | seed-is-docs | 这些段落写在 GFM 种子表里——Demo 正文也是程序的一部分。 | "种子行与 schema 同在 db/articles.mq.md。首次启动若表为空,宿主会插入它们。于是 Demo 叙述与代码同版本:卡片用稍长摘要,详情用更长正文,slug 保证深链稳定。审稿人打开种子表,就能看到会场站点将展示的内容。" | -| 8 | 为什么要做这个 Demo | why-demo-matters | WWW Demo 需要审稿人几分钟内能跑、能点、能对照源码的制品。 | "Demo 轨道要的是可运行系统,不是只靠幻灯片。本样站刻意很小:一张 SQLite 表、几条路由、一套文学风壳层——却覆盖论文主张(表即全栈),并配三步操作脚本。克隆仓库,运行样站,点开卡片,弄坏一次表单,再把 index.mq.md 与浏览器对照。这个闭环就是投稿本身。" | diff --git a/examples/web-site-zh/db/index.mq.md b/examples/web-site-zh/db/index.mq.md deleted file mode 100755 index 8d038b3..0000000 --- a/examples/web-site-zh/db/index.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: web-site-zh database lifecycle -import: - data: ext/data/db.mq.md - articles: articles.mq.md - fs: lib/fs.mq.md - text: lib/text.mq.md ---- - -The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory. - -## open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | None | None selects data/site-zh.db under the site root; tests provide a disposable explicit URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Initialized articles database resource with existing rows preserved | - -Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions. - -The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving. - -For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory. - -1. `url` == None - We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site-zh.db"))** and **url = "sqlite:" + file**. -1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:")) - We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**. -We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.schema())**. -We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**. -1. not `existing` - We **seed = [Read the original demonstration data](articles.seed())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**. -Once the selected database is ready, return *store* for the site's resource bindings. diff --git a/examples/web-site-zh/forms.mq.md b/examples/web-site-zh/forms.mq.md deleted file mode 100755 index 5df6ffe..0000000 --- a/examples/web-site-zh/forms.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion -title: 共享文章表单与服务器校验 -import: - 表单: ext/data/表单.mq.md - document: lib/document.mq.md ---- - -写文章与后台引用同一个 article 表单,服务入口只挂载一次。字段、规则、展示和数据库提交因此使用同一资源。原示例的公共发布仍为公开入口,自定义后台路径另有真实角色门禁。 - -## article - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 包含标题、短链、摘要、正文与原始校验上限的插入表单 | - -构造与挂载需要 plugin,并在站点根授予 fs.read 读取相邻的字面字段和规则。标题和短链必填,上限分别是 120 与 80 字符;摘要与正文可空,上限分别是 500 与 8000 字符。浏览器必填提示不能取代这些服务器规则,绕过浏览器校验仍得到实际拒绝消息。构造不会写行或认证用户。 - -输入类型继续为 text 与 textarea,保留原字段行为。拒绝提交后保留字段错误与当前 CSRF,成功返回首页的实时卡片列表。每次更新都保留新资源,否则挂载旧值会丢掉字段或规则。字段表里的 name 是数据库列名,label 只是用户文案;摘要和完整正文分别展示,不相互替代。 - -这个表单并不因为出现在后台就变成私有接口。真正私有的业务应保护它自己的系统提交地址,示例明确保留公共创建能力,避免只保护展示页却错误宣称数据写入已受限。 - -我们 **字段 = [读取实际字面字段契约](document.read_table(path="forms.tables.md", title="fields"))** 和 **规则 = [读取实际字面校验规则](document.read_table(path="forms.tables.md", title="rules"))**。 - -我们 **资源 = [创建实际文章插入资源](表单.构造(表="articles"))**、**资源 = [绑定可读字段记录](表单.字段(资源=`资源`, 定义=`字段`))** 和 **资源 = [绑定实际服务器规则](表单.规则(资源=`资源`, 定义=`规则`))**。 -最后返回 *[保留提交文案与成功返回目标](表单.文案(资源=`资源`, 提交="发布", 取消="取消", 返回地址="/"))*。 diff --git a/examples/web-site-zh/forms.tables.md b/examples/web-site-zh/forms.tables.md deleted file mode 100755 index 6121dc5..0000000 --- a/examples/web-site-zh/forms.tables.md +++ /dev/null @@ -1,27 +0,0 @@ -# 文章表单数据 - -可调用契约在 forms.mq.md。这里保存原始字面行,不是另一份提交实现。字段对应既有 articles schema,原生展示和服务器校验使用同一记录。 - -## fields - -标题与短链必填,摘要和正文可选,输入类型保持原样。 - -| @ | name | label | type | required | -|---|---|---|---|---| -| 1 | title | 标题 | text | True | -| 2 | slug | slug | text | True | -| 3 | summary | 摘要 | textarea | False | -| 4 | body | 正文 | textarea | False | - -## rules - -服务器使用这些原始规则与错误文案,浏览器提示不能替代它们。 - -| @ | field | rule | message | -|---|---|---|---| -| 1 | title | required | 标题不能为空 | -| 2 | title | max:120 | 标题太长 | -| 3 | slug | required | slug 不能为空 | -| 4 | slug | max:80 | slug 太长 | -| 5 | summary | max:500 | 摘要太长 | -| 6 | body | max:8000 | 正文太长 | diff --git a/examples/web-site-zh/index.mq.md b/examples/web-site-zh/index.mq.md deleted file mode 100755 index 9da7cba..0000000 --- a/examples/web-site-zh/index.mq.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Marqdo 中文站 -import: - 布局: components/index.mq.md - 引言: components/intro.mq.md - 文章: components/articles.mq.md - 数据库: db/index.mq.md - 表单定义: forms.mq.md - 主题: styles/index.mq.md - 网页: ext/web/网页.mq.md - 表单: ext/data/表单.mq.md - 鉴权: ext/security/鉴权.mq.md - 文件: lib/文件.mq.md - 表: lib/表.mq.md ---- - -本入口是可执行建站手册。先读组件入口的公共与后台结构,再读终端 Markdown、请求期间文章、表单和数据库。首页、关于、写文章、后台与短链详情各自声明路由。当前会话决定导航,实际访问策略由安全资源执行;自定义后台不启用另一套原生后台首页。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 公共框架内的 Markdown 介绍与当前文章卡片 | - -启动装配只读取内容叶子并构造查询描述,不初始化或清空数据库。监听应用保留的实际资源在请求期间查询文章;发布后下次访问直接看到新记录。共享布局保留导航、侧栏、页脚、首页 SEO、字体与原始文学主题。改一块内容沿导入找到自己的叶子,不能把完整页面壳复制到每个路由。 - -我们 **说明 = [读取首页终端介绍](引言.nodes(name="home"))**、**卡片 = [描述当前文章卡片](文章.cards())** 和 **正文 = [让说明先于业务记录](表.拼接(a=`说明`, b=`卡片`))**。 -最后返回 *[放入共享公共框架并保留首页 SEO](布局.frame(body=`正文`, homepage=True))*。 - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-site-zh" | 相对仓库的明确站点发现目录 | -| port | number | 18082 | 本机回环监听端口 | -| url | any | None | None 保留站点根 SQLite;验收指定独占临时 URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 数据、表单、鉴权及自定义后台门禁齐备后的阻塞监听结果 | - -从仓库根使用`root`="examples/web-site-zh"、`port`=18082、`url`=None,授予 plugin,fs.write,network.write 并设置 --fs-root examples/web-site-zh。初始化只为空表播种,已有文章全部保留。原始主题数据叶子不变,样式入口只把旧壳选择器映射到明确的 View 结构,并恢复原来由装配操作附着的命名属性表。 - -主题在发现页面之前编译并原生写入 public/generated。准备站点不监听;同一文章表单同时供公共发布页与后台引用。随后绑定本地演示会话,并对实际 /admin 路径施加角色门禁,每次更新都保留新应用,最后才监听。admin/demo 只是回环演示账户,部署应替换用户来源与网络策略。服务阻塞当前进程,由调用者负责停止;不要为验收删除示例已有 data 目录。 - -我们 **存储 = [初始化并保留原有文章](数据库.open(url=`url`))**、**样式 = [编译真实 View 主题映射](主题.css())**,并 **[建立明确的生成目录](文件.建目录(路径="public/generated"))**、**[原生写入本次编译的主题](文件.原子写文本(路径="public/generated/theme.css", 内容=`样式`))**。 -接着 **应用 = [发现五个明确声明的页面](网页.准备站点(根=`root`, 主机="127.0.0.1", 端口=`port`, 数据库=`存储`, 静态目录="public"))**、**资源 = [构造共享服务器校验规则](表单定义.article())** 和 **应用 = [明确挂载公开文章表单](表单.挂载(应用=`应用`, 标识="article", 资源=`资源`))**。 - -`用户` = - -| @ | username | password | role | -|---|---|---|---| -| 1 | admin | demo | admin | - -我们 **应用 = [绑定实际登录会话](鉴权.绑定(应用=`应用`, 用户=`用户`, 登录路径="/login", 登录返回="/admin", 退出返回="/"))** 和 **应用 = [保护直接访问自定义后台的请求](鉴权.门禁(应用=`应用`, 路径="/admin", 角色="admin", 匹配="prefix", 拒绝="redirect", 排除="/login"))**。 -资源与策略就绪后返回 *[开始实际监听](网页.监听(应用=`应用`))*。 diff --git a/examples/web-site-zh/pages/about.mq.md b/examples/web-site-zh/pages/about.mq.md deleted file mode 100755 index c563761..0000000 --- a/examples/web-site-zh/pages/about.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /about -title: 关于 · Marqdo 中文站 -import: - 布局: ../components/index.mq.md - 引言: ../components/intro.mq.md - 文章: ../components/articles.mq.md - 组件: ext/web/网页/组件/索引.mq.md - 表单: ext/data/表单.mq.md - 表: lib/表.mq.md ---- - -本 Document 显式声明 /about,介绍留在终端 Markdown,框架按职责共享。请求资源继续拥有自己的数据和提交责任。 页面启动函数不初始化数据库或开启另一个监听进程。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 共享框架内的本页内容与请求资源 | - -装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。这份解释页不需要查询或表单,修改一个布局区域应沿导入找到对应子模块,不在本文件重新拼页面壳。 - -结构保持稳定,请求资源观察当前数据与身份。父层决定位置,终端叶子解释内容,职责不因为文件较短就合并回完整原生 HTML。首次阅读本页就应能判断实际路径、内容来源和运行边界。 - -我们 **正文 = [读取本页终端说明](引言.nodes(name="about"))**。 -最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=False))*。 diff --git a/examples/web-site-zh/pages/desk.mq.md b/examples/web-site-zh/pages/desk.mq.md deleted file mode 100755 index 78326fb..0000000 --- a/examples/web-site-zh/pages/desk.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /admin -title: 后台 · Marqdo 中文站 -import: - 布局: ../components/index.mq.md - 引言: ../components/intro.mq.md - 文章: ../components/articles.mq.md - 组件: ext/web/网页/组件/索引.mq.md - 表单: ext/data/表单.mq.md - 表: lib/表.mq.md ---- - -本 Document 显式声明 /admin,介绍留在终端 Markdown,框架按职责共享。服务入口在渲染后台前执行真实 admin 角色门禁。 页面启动函数不初始化数据库或开启另一个监听进程。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 共享框架内的本页内容与请求资源 | - -装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。服务器在请求期间为真实会话准备表单 CSRF 与返回路径,不把启动时令牌写死到页面。缺少挂载资源应保留诊断,不能显示固定成功的空表单。 - -后台保留自己的导航和页脚,不带公共侧栏。它有意共享公共文章提交端点,页面门禁不会让该端点自动私有;公开创建是示例保留的行为。首次阅读本页就应能判断实际路径、内容来源和运行边界。 - -我们 **正文 = [读取本页终端说明](引言.nodes(name="desk"))**。 -我们 **引用 = [引用同一个实际挂载的表单](表单.引用(标识="article"))**、**操作 = [保留当前请求 CSRF 与提交上下文](组件.请求资源(值=`引用`, 槽="article-form"))** 和 **正文 = [说明位于实际操作之前](表.拼接(a=`正文`, b=`操作`))**。 -我们 **记录 = [描述同一份当前文章列表](文章.cards())** 和 **正文 = [保留真实业务记录资源](表.拼接(a=`正文`, b=`记录`))**。 -最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=True))*。 diff --git a/examples/web-site-zh/pages/new.mq.md b/examples/web-site-zh/pages/new.mq.md deleted file mode 100755 index e5b9358..0000000 --- a/examples/web-site-zh/pages/new.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /new -title: 写文章 · Marqdo 中文站 -import: - 布局: ../components/index.mq.md - 引言: ../components/intro.mq.md - 文章: ../components/articles.mq.md - 组件: ext/web/网页/组件/索引.mq.md - 表单: ext/data/表单.mq.md - 表: lib/表.mq.md ---- - -本 Document 显式声明 /new,介绍留在终端 Markdown,框架按职责共享。请求资源继续拥有自己的数据和提交责任。 页面启动函数不初始化数据库或开启另一个监听进程。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 共享框架内的本页内容与请求资源 | - -装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。服务器在请求期间为真实会话准备表单 CSRF 与返回路径,不把启动时令牌写死到页面。缺少挂载资源应保留诊断,不能显示固定成功的空表单。 - -结构保持稳定,请求资源观察当前数据与身份。父层决定位置,终端叶子解释内容,职责不因为文件较短就合并回完整原生 HTML。首次阅读本页就应能判断实际路径、内容来源和运行边界。 - -我们 **正文 = [读取本页终端说明](引言.nodes(name="new"))**。 -我们 **引用 = [引用同一个实际挂载的表单](表单.引用(标识="article"))**、**操作 = [保留当前请求 CSRF 与提交上下文](组件.请求资源(值=`引用`, 槽="article-form"))** 和 **正文 = [说明位于实际操作之前](表.拼接(a=`正文`, b=`操作`))**。 -最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=False))*。 diff --git a/examples/web-site-zh/pages/post.mq.md b/examples/web-site-zh/pages/post.mq.md deleted file mode 100755 index 9724049..0000000 --- a/examples/web-site-zh/pages/post.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /post/{slug} -title: 文章 · Marqdo 中文站 -import: - 布局: ../components/index.mq.md - 引言: ../components/intro.mq.md - 文章: ../components/articles.mq.md - 组件: ext/web/网页/组件/索引.mq.md - 表单: ext/data/表单.mq.md - 表: lib/表.mq.md ---- - -本 Document 显式声明 /post/{slug},介绍留在终端 Markdown,框架按职责共享。请求资源继续拥有自己的数据和提交责任。 页面启动函数不初始化数据库或开启另一个监听进程。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 共享框架内的本页内容与请求资源 | - -装配授予 fs.read 以读取终端说明,构造描述仍是纯计算。路径捕获在请求期间选择当前数据库记录,查询字符串不能替换短链。详情使用完整 Markdown 正文,摘要只属于列表,空正文也不应被摘要冒充。 - -结构保持稳定,请求资源观察当前数据与身份。父层决定位置,终端叶子解释内容,职责不因为文件较短就合并回完整原生 HTML。首次阅读本页就应能判断实际路径、内容来源和运行边界。 - -我们 **正文 = [读取本页终端说明](引言.nodes(name="post"))**。 -我们 **记录 = [描述当前短链的完整正文](文章.detail())** 和 **正文 = [保留真实业务记录资源](表.拼接(a=`正文`, b=`记录`))**。 -最后返回 *[选择本页的递归框架](布局.frame(body=`正文`, management=False))*。 diff --git a/examples/web-site-zh/styles/index.mq.md b/examples/web-site-zh/styles/index.mq.md deleted file mode 100755 index 4cd16a0..0000000 --- a/examples/web-site-zh/styles/index.mq.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -markup: occlusion -title: 递归 View 的文学主题入口 -import: - document: lib/document.mq.md - 网页: ext/web/网页.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -先读本入口再修改呈现。shell.tables.md 保留每条原始声明,shell.mq.md 仍能编译原来的 CSS。本入口只把选择器投影到明确的 View 树,恢复旧装配附着的命名属性,再加入 view.tables.md 中有界的包装层几何。颜色、属性值、媒体条件、粒子与关键帧正文都来自原始数据,不用简化主题掩盖结构迁移。 - -## _selector - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| selector | text | 必填 | 原主题中由作者控制的单个选择器 | -| mappings | list | 必填 | 从 view.tables.md 读取的明确 old/new 地址行 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 映射到当前递归框架的等效选择器 | - -使用`selector`和`mappings`。旧 body 的侧栏与后台状态已移入 site-layout,主体改为 section,避免在既有文档 main 中再嵌套 main。原来的分类、主标题、徽章容器和阅读步骤分别对应终端 Markdown 的引用、标题、无序与有序列表。 - -文档背景、根令牌、选中文字、重置与关键帧保持全局,局部选择器增加本站作用域,避免基础 View 默认值覆盖明确主题。这是已知组件树的固定迁移,不是通用 CSS 解析器,也不接收访客的重写规则。调用者每个区域只读取一次映射,再显式传给本纯函数,避免逐条声明重复文件读取。 - -- [按本工程明确的结构地址映射处理](for mappings as mapping) - 我们 **selector = [只替换已知的选择器地址](text.replace(text=`selector`, old=access(mapping, "old"), new=access(mapping, "new")))**. -1. `selector` == "*" or `selector` == "::selection" or text.starts_with(text=`selector`, prefix="body") or text.starts_with(text=`selector`, prefix="html") or text.starts_with(text=`selector`, prefix=":root") or text.starts_with(text=`selector`, prefix="@") - 最后返回 *selector* ,使文档规则与关键帧保持原有作用域。 -1. text.starts_with(text=`selector`, prefix=".site-layout") - 最后返回 *[只为布局状态增加一次作用域](".mq-document " + selector)*. -最后返回 *[将区域选择器限定在本站框架内](".mq-document .site-layout " + selector)*. - -## _table - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | 必填 | 原始 vars、motion、layout、responsive、chrome 或 widgets 章节 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 仅选择器字段变化的原始声明行 | - -使用`name`,从站点根授权 fs.read。原生 Markdown 读取保留声明和字面类型,列转行后保持顺序。每条记录的属性、值、可选媒体与原位置都不变,只有选择器经过上面的固定映射;不可变更新不会污染原来的主题表。 - -本函数不编译或写 CSS。保留可调用的投影行,让验收能逐项核对属性、值和媒体条件,再观察浏览器结果。缺失章节、列长不齐或不支持的字面量都应保留真实诊断,不得静默丢弃样式。令牌和关键帧地址自身也保持不变,不能只比较颜色却删掉动画。 - -我们 **mappings = [读取明确的结构迁移表](document.read_table(path="styles/view.tables.md", title="selectors"))**. -我们 **columns = [读取未改变的原始声明叶子](document.read_table(path="styles/shell.tables.md", title=`name`))** 和 **rows = [逐行保留原有声明](table.from_columns(columns=`columns`))** 和 **projected = [开始有序的选择器投影](table.empty_list())**. -- [在原位置保留每条原始声明](for rows as row) - 我们 **selector = [只映射这一行的结构地址](_selector(selector=access(row, "选择器"), mappings=`mappings`))** 和 **record = [保持其余声明字段不变](table.put(in=`row`, at="选择器", value=`selector`))** 和 **projected = [保留原始属性与值](table.append(list=`projected`, item=`record`))**. -最后返回 *projected* ,供实际编译或独立比较。 - -## _property - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | 必填 | 原来的命名属性/值章节 | -| selector | text | 必填 | 新树中明确语义目标;名称不含开头的点 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 原始属性在明确新目标上的实际编译结果 | - -使用`name`与`selector`,授予 fs.read 与 plugin。旧装配曾把这些属性附到生成的字段,现在同一声明直接选择导航、侧栏/页脚、原生卡片和终端 Markdown 元素,值不改变,也不由用户内容推断。 - -目标由主题入口控制,以 mq-document 开头,原生编译器补上类选择器的点。明确目标让旧属性表仍有用,同时不恢复已移除的页面绑定方言。返回只是文本,保存路径和原子写入由服务入口负责;编译不等于文件已经挂载或浏览器已经加载。 - -我们 **properties = [读取原来的命名属性声明](document.read_table(path="styles/shell.tables.md", title=`name`))**. -最后返回 *[编译明确的语义目标](网页.编译样式(名称=`selector`, 属性=`properties`))*. - -## css - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 保留原始值、明确映射与包装层几何的完整 View 主题 | - -从站点文件根授予 fs.read 与 plugin。令牌和关键帧保持原顺序,随后编译布局、响应断点、引言与控件;命名属性恢复旧装配单独附着的字体和区域外观。不会以替代色板或删减主题提高通过率。 - -最后的几何表只处理运行时包装:移除基础预览的固定宽度和字体默认,让导航资源的原生语义子块参与已有命名网格,并保留公共侧栏与后台状态。Markdown 项目符号成为原来的徽章组,首个解释段落使用原有导语属性,正文无需隐藏的 HTML 模板。 - -编译不会写样式表,也不发放浏览器验收结果。服务入口在发现页面之前原生保存确切文件,再测试实际计算颜色、字体尺寸、宽屏侧栏、窄屏堆叠、表单与后台。选择器失效时修正映射,不能删除视觉能力。各区域顺序和命名属性目标都在相邻数据叶子中可直接阅读;缺少任何章节应停止,而不是退回旧生成文件。生成产物可以重建,原声明与迁移表才是编辑入口;不要手改生成 CSS 后误认为源码已经修复。样式变化仍需宽屏和窄屏两个方向的实际观察。 - -我们 **areas = [读取保留的主题区域顺序](document.read_table(path="styles/view.tables.md", title="areas"))**. - -我们 **parts = [开始实际有序的主题编译](table.empty_list())**. -- [编译每个原始主题区域](for areas as name) - 我们 **rows = [保留全部原始值与媒体条件](_table(name=`name`))** 和 **compiled = [编译实际投影后的声明](网页.编译样式(名称=`name`, 属性=`rows`))** 和 **parts = [保留原来的级联顺序](table.append(list=`parts`, item=`compiled`))**. - -我们 **properties = [读取实际命名属性目标](document.read_table(path="styles/view.tables.md", title="properties"))**. - -- [恢复每组原来附着的命名属性](for properties as property) - 我们 **compiled = [编译明确的语义选择器](_property(name=access(property, "name"), selector=access(property, "selector")))** 和 **parts = [保留真实的命名属性组](table.append(list=`parts`, item=`compiled`))**. -我们 **geometry = [读取有界的 View 包装层适配](document.read_table(path="styles/view.tables.md", title="geometry"))** 和 **compiled = [编译原生几何适配](网页.编译样式(名称="view", 属性=`geometry`))** 和 **parts = [以明确的包装规则结束](table.append(list=`parts`, item=`compiled`))**. -最后返回 *[按顺序保留实际编译的各段](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site-zh/styles/shell.mq.md b/examples/web-site-zh/styles/shell.mq.md deleted file mode 100755 index 559364b..0000000 --- a/examples/web-site-zh/styles/shell.mq.md +++ /dev/null @@ -1,277 +0,0 @@ ---- -markup: occlusion -title: 原始文学主题声明的读取与比较 -import: - document: lib/document.mq.md - web: ext/web/web.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -本文件保留原始数据读取与 CSS 编译,用于比较迁移前的声明。当前站点从 styles/index.mq.md 编译 View 映射;不要把本文件输出误当成新树已经适配。数据叶子中每条原始声明保持可阅读、可独立调用。 - -## vars - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -整站色板、字体、间距与阴影令牌。 - -使用这些自定义属性的规则应在令牌之后编译。选中文字颜色与 :root 一样保持全局,不应被框架映射限制在某张卡片中。修改值会影响整站,需核对实际 CSS 与浏览器颜色,不能只在局部重命名引用。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="vars"))*. - -## motion - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -原有入场、漂浮、粒子与辉光关键帧。 - -关键帧地址、属性和值保持全局及原顺序,时长仍归使用它的规则。读到数据不会启动动画,浏览器加载编译主题后才应用。View 投影不能给这些地址加组件前缀,也不能为了静态截图删除运动能力。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="motion"))*. - -## layout - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -文档背景、排版与原有区域网格声明。 - -旧 body 状态描述过去的页面壳,当前样式入口只把已知地址映射到明确 site-layout 区域,属性值不变。背景和粒子层继续属于文档全局,任何修改都应对照真实宽窄屏几何,而不是只比较声明数量。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="layout"))*. - -## responsive - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -原始媒体条件及减少动画偏好的规则。 - -媒体文本保留为独立列。宽度条件收拢公共网格并调整留白,减少动画偏好关闭指定动画而非删除关键帧。核对时保留行顺序、媒体和值,不能仅因为 CSS 中仍出现选择器名就认定断点有效。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="responsive"))*. - -## topnav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -顶部导航外观的命名属性和值。 - -原有吸顶、渐变、模糊、间距与分隔线继续作用于原生 topnav 类。目标链接与实际会话条件归导航资源,属性表不能认证用户或注册路由。编译也不意味着样式文件已保存或挂载,服务入口负责这些后续步骤。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="topnav"))*. - -## side_panel - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -公共侧栏外观的命名属性和值。 - -侧栏背景、留白与分隔线区分任务入口和正文,外部网格位置仍归父框架,后台有意不带该区域。这里不维护另一份链接或会话判断。修改外观后应确认窄屏仍在正文之后显示,不能用隐藏侧栏掩盖布局错误。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="side_panel"))*. - -## footer - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -结束区域外观的命名属性和值。 - -颜色、字号、间距、边框与背景保留原站定义。Markdown 叶子拥有真实链接,本表既不创建目的地也不执行退出。公共与后台页脚可共享相同外观,内容仍分别维护,父层继续决定位置。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="footer"))*. - -## card_title - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -文章卡片标题的命名排版属性。 - -当前查询渲染器转义文章标题并保留原生 h2,View 主题直接选择该结构,不恢复旧 front/back 绑定。读取不查询文章、不截断标题或修改持久数据;应结合真实卡片确认属性到达实际标题。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="card_title"))*. - -## card_body - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -卡片摘要的命名排版属性。 - -摘要来自当前查询,完整 Markdown 正文仍留给详情。本表只改变外观,不选择或替换内容。选择器调整后要同时验证转义摘要和完整正文的独立行为,不能用摘要冒充缺失的正文。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="card_body"))*. - -## chrome - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -原始引言面板、徽章容器、阅读步骤和全文规则。 - -当前引言是终端 Markdown,因此映射选择真实标题、项目符号与编号列表;文章规则继续选择原生详情结构。保留明确映射与原值,不应为恢复旧选择器而把整段内容藏回作者 HTML。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="chrome"))*. - -## kicker - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -引言分类标签的命名排版属性。 - -字距、颜色、小字号和漂浮动画选择分类所用的 Markdown 引用块,分类文字仍是内容叶子中直接可读的一行。编译这些属性不会创建文字或下载字体,加载与实际呈现需另外观察。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="kicker"))*. - -## intro_title - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -引言主标题的命名字体与响应式属性。 - -保留展示字体、响应字号、渐变文字与辉光动画,View 主题选择真实 Markdown h1,避免把字号施加到包装层后又被浏览器标题倍乘。验收检查计算字体和尺寸,读到属性不能证明渲染已正确。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="intro_title"))*. - -## lede - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -引言解释段落的命名排版属性。 - -宽度、行高、颜色、间距和字体选择叶子中的解释段落,与特性徽章和编号步骤保持独立。目标应是实际段落,而非依赖包装层与浏览器默认外边距凑出近似效果;内容仍由终端 Markdown 维护。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="lede"))*. - -## claim - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -单条简短特性徽章的命名属性。 - -Markdown 无序列表对应原来的 flex 徽章容器,列表项使用这里的 inline 徽章属性。容器的间距与换行归 chrome 章节。分别保留两层责任,才能同时得到直接可读的列表内容和原来的视觉分组。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="claim"))*. - -## step - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -单条阅读步骤原有的外边距。 - -这里只有一条属性行,原生结果含标量单元格,而不是列式列表,样式编译器支持这个形态。Markdown 编号列表拥有序号和链接,本值只提供条目留白,不改变阅读顺序或在后台替用户执行步骤。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="step"))*. - -## widgets - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 原始 选择器、属性、值及可选媒体 表,保留列式或单行标量形态 | - -原始卡片、表单、提示和管理状态声明。 - -悬停与焦点、字段宽度、操作行和后台选择器保持原顺序。原生表单资源拥有校验与提交,主题只映射结构地址。可见错误外观不能证明服务器已经拒绝输入,仍需实际失败和成功提交验收。 - -从站点根授权 fs.read;精确章节必须唯一,缺失或格式不支持时保留原生诊断。返回值仍是数据,不写文件、不执行动画或查询业务。 - -读取完成后返回 *[读取这一章实际原始字面表](document.read_table(path="styles/shell.tables.md", title="widgets"))*. - - -## _compile - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | 必填 | shell.tables.md 中精确原始章节 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 按原始选择器编译的单个主题区段 | - -使用`name`,从站点根授予 fs.read 与 plugin。原生读取保留原始值与形态,编译器处理选择器、媒体和关键帧。这个内部工具特意保留旧壳的地址,用于比较迁移前 CSS;当前服务使用 styles/index 的明确 View 映射。缺失章节保留诊断,返回文本既不写文件,也不证明新结构已经适配。 - -我们 **declarations = [读取原始区段的实际声明](document.read_table(path="styles/shell.tables.md", title=`name`))**. -最后返回 *[编译原地址用于保留比较](web.make_style(name=`name`, table=`declarations`))*. - -## css - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 保持原六区段地址与级联的基准 CSS | - -从站点根授权 fs.read 和 plugin,依次编译令牌、关键帧、布局、断点、引言与控件。这六段地址、顺序和连接方式保持原实现,用于原始数据与散列比较。命名属性仍可分别读取,但不额外加入本基准,以免改变原级联;它们由新的 View 入口恢复到实际目标。 - -当前站点不直接加载这个旧壳基准,实际样式见 styles/index。散列相同只能证明原始主题编译保留,不能证明新的选择器匹配、字体送达或移动布局正确。用 verify 的逐行比较加上真实浏览器验证,并由服务入口显式保存实际新主题。 - -`names` = - -| name | -|---| -| vars | -| motion | -| layout | -| responsive | -| chrome | -| widgets | - -We **parts = [Start the ordered compiled sections](table.empty_list())**. -- [Compile each area in the declared cascade order](for names as name) - We **css = [Compile the selected theme area](_compile(name=`name`))** and **parts = [Preserve its original position](table.append(list=`parts`, item=`css`))**. -Return *[Join the compiled sections without changing separators](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site-zh/styles/shell.tables.md b/examples/web-site-zh/styles/shell.tables.md deleted file mode 100755 index c3a64db..0000000 --- a/examples/web-site-zh/styles/shell.tables.md +++ /dev/null @@ -1,602 +0,0 @@ -# Theme declarations - -Literal theme declarations. Callable use and CSS assembly are documented next to this file in shell.mq.md. Each section preserves one native table, including its column names and literal types. - -## vars - -Palette, typefaces, spacing and elevation tokens used by every region. - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| :root | --ink | #0a0809 | -| :root | --ink-lift | #141012 | -| :root | --wine | #6b1e3a | -| :root | --wine-soft | rgba(107,30,58,0.35) | -| :root | --gold | #d4af37 | -| :root | --gold-dim | rgba(212,175,55,0.45) | -| :root | --gold-soft | rgba(212,175,55,0.12) | -| :root | --paper | rgba(255,248,240,0.92) | -| :root | --paper-dim | rgba(255,248,240,0.72) | -| :root | --paper-faint | rgba(255,248,240,0.48) | -| :root | --glass | rgba(20,12,18,0.72) | -| :root | --glass-strong | rgba(20,12,18,0.88) | -| :root | --border | rgba(212,175,55,0.22) | -| :root | --border-soft | rgba(212,175,55,0.12) | -| :root | --danger | #e8a0a8 | -| :root | --radius | 4px | -| :root | --radius-sm | 2px | -| :root | --space-2 | 8px | -| :root | --space-3 | 12px | -| :root | --space-4 | 16px | -| :root | --space-5 | 20px | -| :root | --space-6 | 24px | -| :root | --space-8 | 32px | -| :root | --text | 16px | -| :root | --leading | "1.75" | -| :root | --shadow | "0 24px 80px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.06)" | -| :root | --shadow-card | "0 12px 40px rgba(107,30,58,.35)" | -| :root | --ring | "0 0 0 2px rgba(212,175,55,.35)" | -| :root | --serif | "'Noto Serif SC', 'Source Serif 4', Georgia, serif" | -| :root | --sans | "'Noto Sans SC', 'IBM Plex Sans', system-ui, sans-serif" | -| :root | --display | "'Great Vibes', 'Allura', cursive" | -| :root | --mono | "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" | -| ::selection | background | rgba(212,175,55,0.35) | -| ::selection | color | var(--paper) | - -## motion - -Entrance, floating, particle and glow keyframes; animation timings remain in consuming selectors. - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| @keyframes rise 0% | opacity | "0" | -| @keyframes rise 0% | transform | translateY(14px) | -| @keyframes rise 100% | opacity | "1" | -| @keyframes rise 100% | transform | translateY(0) | -| @keyframes float 0% | transform | translateY(0) | -| @keyframes float 0% | opacity | "0.7" | -| @keyframes float 50% | transform | translateY(6px) | -| @keyframes float 50% | opacity | "1" | -| @keyframes float 100% | transform | translateY(0) | -| @keyframes float 100% | opacity | "0.7" | -| @keyframes goldPulse 0% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes goldPulse 50% | text-shadow | "0 0 48px rgba(212,175,55,.45)" | -| @keyframes goldPulse 100% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes particleDrift 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift 50% | transform | translate3d(-2.5vw, 1.5vh, 0) | -| @keyframes particleDrift 100% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 50% | transform | translate3d(2vw, -2vh, 0) | -| @keyframes particleDrift2 100% | transform | translate3d(0,0,0) | -| @keyframes nebulaPulse 0% | opacity | "0.55" | -| @keyframes nebulaPulse 50% | opacity | "0.9" | -| @keyframes nebulaPulse 100% | opacity | "0.55" | - -## layout - -Page grid, background, typography, navigation and main content rules. - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| * | box-sizing | border-box | -| html | scroll-behavior | smooth | -| html | -webkit-text-size-adjust | 100% | -| body | margin | "0" | -| body | min-height | 100vh | -| body | font-family | var(--sans) | -| body | font-weight | "400" | -| body | font-size | var(--text) | -| body | line-height | var(--leading) | -| body | color | var(--paper) | -| body | background | var(--ink) | -| body | background-image | "radial-gradient(ellipse 90% 55% at 50% -15%, rgba(107,30,58,.5), transparent 58%), radial-gradient(ellipse 55% 45% at 92% 75%, rgba(212,175,55,.14), transparent 55%), radial-gradient(ellipse 40% 35% at 8% 70%, rgba(107,30,58,.22), transparent 60%), linear-gradient(180deg, #0a0809 0%, #120c10 45%, #0a0809 100%)" | -| body | background-attachment | fixed | -| body | display | grid | -| body | grid-template-rows | "auto 1fr auto" | -| body | -webkit-font-smoothing | antialiased | -| body | position | relative | -| body | overflow-x | hidden | -| body::before | content | '""' | -| body::before | position | fixed | -| body::before | inset | "0" | -| body::before | z-index | "1" | -| body::before | pointer-events | none | -| body::before | opacity | "0.1" | -| body::before | background-image | "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")" | -| html::before | content | '""' | -| html::before | position | fixed | -| html::before | inset | "0" | -| html::before | z-index | "0" | -| html::before | pointer-events | none | -| html::before | background-image | "radial-gradient(ellipse 50% 40% at 15% 30%, rgba(107,30,58,.35), transparent 70%), radial-gradient(ellipse 45% 35% at 85% 60%, rgba(212,175,55,.12), transparent 65%), radial-gradient(ellipse 40% 30% at 50% 90%, rgba(107,30,58,.25), transparent 70%)" | -| html::before | animation | "nebulaPulse 12s ease-in-out infinite" | -| body::after | content | '""' | -| body::after | position | fixed | -| body::after | top | "0" | -| body::after | left | "0" | -| body::after | width | "2px" | -| body::after | height | "2px" | -| body::after | z-index | "2" | -| body::after | pointer-events | none | -| body::after | border-radius | 50% | -| body::after | background | transparent | -| body::after | box-shadow | "82vw 15vh 0px 0px rgba(212,175,55,0.55),29vw 18vh 0px 1px rgba(212,175,55,0.25),95vw 70vh 1px 0px rgba(212,175,55,0.55),4vw 12vh 0px 1px rgba(212,175,55,0.35),78vw 4vh 0px 1px rgba(245,230,200,0.5),84vw 90vh 1px 0px rgba(245,230,200,0.5),58vw 76vh 0px 0px rgba(255,248,240,0.4),90vw 55vh 0px 0px rgba(255,248,240,0.4),28vw 98vh 0px 0px rgba(255,248,240,0.4),49vw 13vh 0px 1px rgba(255,248,240,0.4),34vw 6vh 1px 1px rgba(212,175,55,0.25),16vw 49vh 0px 1px rgba(212,175,55,0.55),80vw 47vh 0px 1px rgba(245,230,200,0.5),9vw 6vh 0px 0px rgba(212,175,55,0.25),11vw 30vh 1px 0px rgba(212,175,55,0.55),59vw 82vh 0px 0px rgba(255,248,240,0.4),46vw 27vh 0px 1px rgba(212,175,55,0.25),88vw 83vh 0px 1px rgba(212,175,55,0.55),94vw 32vh 1px 0px rgba(212,175,55,0.35),35vw 82vh 0px 1px rgba(212,175,55,0.25),42vw 99vh 0px 0px rgba(212,175,55,0.55),41vw 52vh 0px 0px rgba(255,248,240,0.4),73vw 92vh 0px 1px rgba(255,248,240,0.4),64vw 51vh 1px 0px rgba(212,175,55,0.25),34vw 18vh 0px 1px rgba(212,175,55,0.35),75vw 55vh 1px 0px rgba(245,230,200,0.5),29vw 18vh 1px 0px rgba(245,230,200,0.5),97vw 7vh 0px 1px rgba(212,175,55,0.55),21vw 88vh 0px 0px rgba(107,30,58,0.45),49vw 77vh 0px 1px rgba(107,30,58,0.45),2vw 88vh 0px 1px rgba(212,175,55,0.25),69vw 97vh 0px 0px rgba(255,248,240,0.4),38vw 56vh 1px 0px rgba(212,175,55,0.35),93vw 93vh 0px 1px rgba(255,248,240,0.4),14vw 81vh 0px 0px rgba(255,248,240,0.4),48vw 98vh 0px 1px rgba(212,175,55,0.35),42vw 63vh 0px 0px rgba(212,175,55,0.55),40vw 31vh 0px 1px rgba(212,175,55,0.55),11vw 11vh 1px 0px rgba(212,175,55,0.25),98vw 69vh 0px 1px rgba(212,175,55,0.35),61vw 71vh 0px 1px rgba(212,175,55,0.35),78vw 55vh 0px 1px rgba(212,175,55,0.35),40vw 52vh 0px 0px rgba(212,175,55,0.25),67vw 58vh 0px 0px rgba(212,175,55,0.55),9vw 44vh 0px 1px rgba(212,175,55,0.55),29vw 1vh 0px 0px rgba(212,175,55,0.55),9vw 5vh 0px 1px rgba(255,248,240,0.4),31vw 36vh 1px 0px rgba(212,175,55,0.25),70vw 17vh 1px 0px rgba(212,175,55,0.25),61vw 53vh 0px 0px rgba(212,175,55,0.35),85vw 56vh 1px 0px rgba(255,248,240,0.4),60vw 94vh 0px 0px rgba(212,175,55,0.55),52vw 94vh 0px 0px rgba(255,248,240,0.4),25vw 25vh 1px 0px rgba(245,230,200,0.5),55vw 24vh 1px 0px rgba(255,248,240,0.4),10vw 57vh 0px 0px rgba(245,230,200,0.5),84vw 70vh 0px 0px rgba(212,175,55,0.55),22vw 53vh 1px 0px rgba(107,30,58,0.45),52vw 8vh 1px 0px rgba(212,175,55,0.35),50vw 34vh 0px 0px rgba(107,30,58,0.45),90vw 94vh 1px 0px rgba(245,230,200,0.5),25vw 38vh 0px 1px rgba(212,175,55,0.35),95vw 70vh 0px 0px rgba(212,175,55,0.55),7vw 75vh 0px 0px rgba(107,30,58,0.45),66vw 11vh 0px 1px rgba(212,175,55,0.35),9vw 87vh 1px 0px rgba(212,175,55,0.35),73vw 32vh 0px 1px rgba(245,230,200,0.5),11vw 54vh 0px 0px rgba(212,175,55,0.25),27vw 86vh 0px 0px rgba(212,175,55,0.25),34vw 51vh 0px 0px rgba(212,175,55,0.35),41vw 97vh 0px 0px rgba(212,175,55,0.55),80vw 73vh 0px 1px rgba(212,175,55,0.55)" | -| body::after | animation | "particleDrift 48s ease-in-out infinite" | -| html::after | content | '""' | -| html::after | position | fixed | -| html::after | top | "0" | -| html::after | left | "0" | -| html::after | width | "1px" | -| html::after | height | "1px" | -| html::after | z-index | "2" | -| html::after | pointer-events | none | -| html::after | border-radius | 50% | -| html::after | background | transparent | -| html::after | box-shadow | "28vw 65vh 0 0 rgba(255,248,240,0.25),17vw 45vh 0 0 rgba(212,175,55,0.3),32vw 48vh 0 0 rgba(255,248,240,0.25),21vw 57vh 0 0 rgba(107,30,58,0.3),91vw 39vh 0 0 rgba(107,30,58,0.3),84vw 68vh 0 0 rgba(212,175,55,0.3),86vw 71vh 0 0 rgba(255,248,240,0.25),85vw 14vh 0 0 rgba(212,175,55,0.3),34vw 15vh 0 0 rgba(212,175,55,0.3),96vw 71vh 0 0 rgba(212,175,55,0.3),35vw 37vh 0 0 rgba(107,30,58,0.3),27vw 92vh 0 0 rgba(255,248,240,0.25),27vw 88vh 0 0 rgba(107,30,58,0.3),34vw 65vh 0 0 rgba(255,248,240,0.25),33vw 7vh 0 0 rgba(212,175,55,0.3),82vw 55vh 0 0 rgba(255,248,240,0.25),6vw 1vh 0 0 rgba(255,248,240,0.25),99vw 17vh 0 0 rgba(107,30,58,0.3),34vw 21vh 0 0 rgba(107,30,58,0.3),57vw 71vh 0 0 rgba(107,30,58,0.3),55vw 72vh 0 0 rgba(212,175,55,0.3),15vw 10vh 0 0 rgba(107,30,58,0.3),20vw 70vh 0 0 rgba(212,175,55,0.3),48vw 75vh 0 0 rgba(107,30,58,0.3),19vw 56vh 0 0 rgba(212,175,55,0.3),6vw 40vh 0 0 rgba(255,248,240,0.25),6vw 46vh 0 0 rgba(212,175,55,0.3),88vw 32vh 0 0 rgba(107,30,58,0.3),14vw 46vh 0 0 rgba(107,30,58,0.3),53vw 80vh 0 0 rgba(107,30,58,0.3),20vw 31vh 0 0 rgba(212,175,55,0.3),23vw 53vh 0 0 rgba(212,175,55,0.3),23vw 95vh 0 0 rgba(255,248,240,0.25),53vw 86vh 0 0 rgba(107,30,58,0.3),32vw 35vh 0 0 rgba(212,175,55,0.3),90vw 14vh 0 0 rgba(255,248,240,0.25),5vw 61vh 0 0 rgba(212,175,55,0.3),26vw 59vh 0 0 rgba(255,248,240,0.25),40vw 30vh 0 0 rgba(212,175,55,0.3),4vw 85vh 0 0 rgba(212,175,55,0.3),52vw 43vh 0 0 rgba(255,248,240,0.25),9vw 99vh 0 0 rgba(255,248,240,0.25),45vw 83vh 0 0 rgba(107,30,58,0.3),52vw 87vh 0 0 rgba(107,30,58,0.3),43vw 4vh 0 0 rgba(212,175,55,0.3),34vw 23vh 0 0 rgba(107,30,58,0.3),34vw 5vh 0 0 rgba(212,175,55,0.3),77vw 56vh 0 0 rgba(255,248,240,0.25)" | -| html::after | animation | "particleDrift2 64s ease-in-out infinite" | -| body.has-sidebar | grid-template-columns | "14rem minmax(0, 1fr)" | -| body.has-sidebar | grid-template-areas | '"top top" "side main" "foot foot"' | -| body.no-sidebar | grid-template-areas | '"top" "main" "foot"' | -| body.layout-stacked | grid-template-areas | '"top" "main" "foot"' | -| body.is-desk | grid-template-areas | '"top" "main" "foot"' | -| header.topnav | grid-area | top | -| aside.side | grid-area | side | -| main.main | grid-area | main | -| footer.foot | grid-area | foot | -| header.topnav | position | relative | -| header.topnav | z-index | "20" | -| aside.side | position | relative | -| aside.side | z-index | "10" | -| main.main | position | relative | -| main.main | z-index | "10" | -| footer.foot | position | relative | -| footer.foot | z-index | "10" | -| main.main | width | "100%" | -| main.main | max-width | "min(78rem, 100%)" | -| main.main | padding | "var(--space-8) var(--space-6) 4rem" | -| main.main | animation | "rise .8s cubic-bezier(.22,1,.36,1) both" | -| a | color | var(--gold) | -| a | text-decoration | none | -| a | transition | color 0.25s ease | -| a:hover | color | #f5e6c8 | -| code | font-family | var(--mono) | -| code | font-size | "0.82em" | -| code | font-weight | "400" | -| code | background | rgba(0,0,0,0.35) | -| code | border | 1px solid var(--border-soft) | -| code | padding | "0.12em 0.45em" | -| code | border-radius | var(--radius-sm) | -| code | color | var(--gold) | - -## responsive - -Media conditions that collapse the side panel and card grid on small screens. - -| 媒体 | 选择器 | 属性 | 值 | -|------|--------|------|-----| -| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | -| (max-width: 860px) | body.has-sidebar | grid-template-areas | '"top" "main" "side" "foot"' | -| (max-width: 860px) | aside.side | border-right | "0" | -| (max-width: 860px) | aside.side | border-top | 1px solid var(--border-soft) | -| (max-width: 860px) | main.main | padding | "var(--space-6) var(--space-4) var(--space-8)" | -| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form form | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form label:nth-child(1) | grid-column | "1 / -1" | -| (max-width: 860px) | .site-form label:nth-child(2) | grid-column | "1 / -1" | -| (max-width: 860px) | header.topnav | padding | "0.85rem var(--space-4)" | -| (max-width: 860px) | .intro_title | font-size | "2.4rem" | -| (prefers-reduced-motion: reduce) | main.main | animation | none | -| (prefers-reduced-motion: reduce) | .kicker | animation | none | -| (prefers-reduced-motion: reduce) | article.card | transition | none | -| (prefers-reduced-motion: reduce) | body::after | animation | none | -| (prefers-reduced-motion: reduce) | html::after | animation | none | -| (prefers-reduced-motion: reduce) | html::before | animation | none | - -## topnav - -Property/value style attached to the top navigation binding. - -| 属性 | 值 | -|------|-----| -| position | sticky | -| top | "0" | -| z-index | "40" | -| display | flex | -| align-items | center | -| justify-content | flex-start | -| gap | var(--space-4) | -| padding | "1rem var(--space-6)" | -| background | "linear-gradient(180deg, rgba(10,8,9,.92) 0%, rgba(10,8,9,.55) 70%, transparent 100%)" | -| backdrop-filter | blur(10px) | -| -webkit-backdrop-filter | blur(10px) | -| border-bottom | 1px solid var(--border-soft) | - -## side_panel - -Property/value style for the secondary navigation and explanatory panel. - -| 属性 | 值 | -|------|-----| -| background | "rgba(10,8,9,.55)" | -| padding | "var(--space-6) var(--space-4)" | -| border-right | 1px solid var(--border-soft) | - -## footer - -Property/value style for the closing navigation and attribution. - -| 属性 | 值 | -|------|-----| -| color | var(--paper-faint) | -| font-size | "0.8rem" | -| letter-spacing | "0.08em" | -| padding | "var(--space-5) var(--space-6)" | -| border-top | 1px solid var(--border-soft) | -| background | "rgba(10,8,9,.75)" | - -## card_title - -Property/value typography for a linked article title. - -| 属性 | 值 | -|------|-----| -| font-family | var(--serif) | -| font-size | "1.15rem" | -| font-weight | "600" | -| margin | "0 0 var(--space-2)" | -| color | var(--gold) | -| letter-spacing | "0.02em" | -| line-height | "1.35" | - -## card_body - -Property/value typography for an article's summary. - -| 属性 | 值 | -|------|-----| -| color | var(--paper-dim) | -| margin | "0" | -| line-height | "1.65" | -| font-size | "0.9rem" | -| font-weight | "400" | -| display | "-webkit-box" | -| -webkit-box-orient | vertical | -| -webkit-line-clamp | "3" | -| overflow | hidden | - -## chrome - -Grouped selectors for introduction panels, claims, reading steps and full article content. - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| .main-intro | background | var(--glass) | -| .main-intro | border | 1px solid var(--border) | -| .main-intro | border-radius | var(--radius) | -| .main-intro | padding | "2.25rem 1.75rem 1.85rem" | -| .main-intro | box-shadow | var(--shadow) | -| .main-intro | backdrop-filter | blur(16px) | -| .main-intro | -webkit-backdrop-filter | blur(16px) | -| .main-intro | margin-bottom | var(--space-8) | -| .main-intro > .claim | display | flex | -| .main-intro > .claim | flex-wrap | wrap | -| .main-intro > .claim | gap | var(--space-2) | -| .main-intro > .claim | margin | "0 0 var(--space-6)" | -| .main-intro > .steps | margin | "0" | -| .main-intro > .steps | padding | "var(--space-5) var(--space-5) var(--space-5) 1.5rem" | -| .main-intro > .steps | color | var(--paper-dim) | -| .main-intro > .steps | background | "rgba(0,0,0,.35)" | -| .main-intro > .steps | border | 1px solid var(--border-soft) | -| .main-intro > .steps | border-left | 2px solid var(--gold-dim) | -| .main-intro > .steps | border-radius | var(--radius) | -| .main-intro > .steps | font-size | "0.95rem" | -| .main-intro > .steps | letter-spacing | "0.02em" | -| .main-intro > .steps a | color | var(--gold) | -| .main-intro > .steps a | font-weight | "500" | -| .main-intro > .steps a:hover | color | #f5e6c8 | -| .article | background | var(--glass) | -| .article | border | 1px solid var(--border) | -| .article | border-radius | var(--radius) | -| .article | padding | "2rem 1.75rem" | -| .article | box-shadow | var(--shadow) | -| .article | backdrop-filter | blur(16px) | -| .article | -webkit-backdrop-filter | blur(16px) | -| .article-title | font-family | var(--serif) | -| .article-title | font-size | "clamp(1.75rem, 4vw, 2.35rem)" | -| .article-title | font-weight | "600" | -| .article-title | color | var(--gold) | -| .article-title | letter-spacing | "0.04em" | -| .article-title | margin | "0 0 var(--space-5)" | -| .article-title | line-height | "1.25" | -| .article-body | color | var(--paper-dim) | -| .article-body | font-family | var(--sans) | -| .article-body | font-size | "1.02rem" | -| .article-body | line-height | "1.85" | -| .article-body.md p | margin | "0 0 1.1rem" | -| .article-body.md a | color | var(--gold) | -| article.card | cursor | pointer | -| a.card-link | color | inherit | -| a.card-link | text-decoration | none | -| a.card-link:hover | color | inherit | - -## kicker - -Property/value typography for the small introductory category label. - -| 属性 | 值 | -|------|-----| -| letter-spacing | "0.32em" | -| text-transform | uppercase | -| font-size | "0.72rem" | -| color | var(--gold-dim) | -| margin | "0 0 var(--space-4)" | -| font-weight | "400" | -| font-family | var(--sans) | -| animation | "float 2.8s ease-in-out infinite" | - -## intro_title - -Property/value typography and responsive size for the main introduction heading. - -| 属性 | 值 | -|------|-----| -| font-family | var(--display) | -| font-size | "clamp(3rem, 10vw, 4.8rem)" | -| font-weight | "400" | -| line-height | "1.15" | -| letter-spacing | "0.04em" | -| margin | "0 0 var(--space-4)" | -| color | transparent | -| background | "linear-gradient(135deg, #f5e6c8 0%, var(--gold) 42%, var(--wine) 100%)" | -| -webkit-background-clip | text | -| background-clip | text | -| animation | "goldPulse 4.5s ease-in-out infinite" | - -## lede - -Property/value typography for the supporting introduction paragraph. - -| 属性 | 值 | -|------|-----| -| color | var(--paper-dim) | -| max-width | "34rem" | -| line-height | "1.85" | -| margin | "0 0 var(--space-5)" | -| font-size | "1.05rem" | -| letter-spacing | "0.02em" | -| font-weight | "400" | -| font-family | var(--sans) | - -## claim - -Property/value style used by the short feature claims. - -| 属性 | 值 | -|------|-----| -| display | inline-flex | -| align-items | center | -| padding | "0.2rem 0.65rem" | -| border-radius | var(--radius-sm) | -| background | var(--wine-soft) | -| color | #f0c9d4 | -| font-size | "0.68rem" | -| font-weight | "500" | -| letter-spacing | "0.14em" | -| border | 1px solid rgba(107,30,58,0.5) | - -## step - -Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. - -| 属性 | 值 | -|------|-----| -| margin | "0.55rem 0" | - -## widgets - -Cards, forms, flash messages and administration controls, including hover and focus states. - -| 选择器 | 属性 | 值 | -|--------|------|-----| -| ul.nav | display | flex | -| ul.nav | flex-wrap | wrap | -| ul.nav | align-items | center | -| ul.nav | gap | "0.35rem 1rem" | -| ul.nav | list-style | none | -| ul.nav | margin | "0" | -| ul.nav | padding | "0" | -| ul.nav a | display | inline-flex | -| ul.nav a | align-items | center | -| ul.nav a | text-decoration | none | -| ul.nav a | color | var(--paper-dim) | -| ul.nav a | padding | "0.35rem 0" | -| ul.nav a | border-radius | "0" | -| ul.nav a | font-weight | "400" | -| ul.nav a | font-size | "0.8rem" | -| ul.nav a | letter-spacing | "0.14em" | -| ul.nav a | transition | color 0.25s ease | -| ul.nav a:hover | background | transparent | -| ul.nav a:hover | color | var(--gold) | -| ul.nav a:hover | text-decoration | none | -| ul.nav a[href="/admin"] | color | var(--gold) | -| ul.nav a[href="/admin"] | letter-spacing | "0.18em" | -| ul.nav a[href="/admin"] | border-bottom | 1px solid var(--gold-dim) | -| ul.side-nav a[href="/admin"] | color | var(--gold) | -| body.is-desk header.topnav | border-bottom | 1px solid rgba(107,30,58,0.55) | -| body.is-desk header.topnav | box-shadow | "0 12px 40px rgba(107,30,58,.18)" | -| body.is-desk .main-intro | border-left | 3px solid var(--wine) | -| body.is-desk .site-form | border-color | rgba(107,30,58,0.45) | -| body.is-desk .site-form | box-shadow | "0 0 0 1px rgba(212,175,55,.12), 0 18px 48px rgba(0,0,0,.35)" | -| body.is-desk .content.cards | margin-top | var(--space-6) | -| ul.nav li:first-child a | font-family | var(--display) | -| ul.nav li:first-child a | font-weight | "400" | -| ul.nav li:first-child a | color | var(--gold) | -| ul.nav li:first-child a | font-size | "1.85rem" | -| ul.nav li:first-child a | letter-spacing | "0.06em" | -| ul.nav li:first-child a | padding | "0.1rem 0.2rem 0.1rem 0" | -| ul.nav li:first-child a:hover | background | transparent | -| ul.nav li:first-child a:hover | color | #f5e6c8 | -| .side-label | display | block | -| .side-label | font-size | "0" | -| .side-label | margin | "0 0 var(--space-4)" | -| .side-label::before | content | '"Path"' | -| .side-label::before | display | block | -| .side-label::before | font-size | "0.68rem" | -| .side-label::before | letter-spacing | "0.28em" | -| .side-label::before | text-transform | uppercase | -| .side-label::before | color | var(--gold-dim) | -| .side-label::before | font-weight | "400" | -| ul.side-nav | list-style | none | -| ul.side-nav | margin | "0" | -| ul.side-nav | padding | "0" | -| ul.side-nav | display | grid | -| ul.side-nav | gap | "2px" | -| ul.side-nav | border-left | 1px solid var(--border) | -| ul.side-nav | padding-left | "0.85rem" | -| ul.side-nav | margin-left | "0.25rem" | -| ul.side-nav a | display | block | -| ul.side-nav a | text-decoration | none | -| ul.side-nav a | color | var(--paper-dim) | -| ul.side-nav a | padding | "0.45rem 0.35rem" | -| ul.side-nav a | border-radius | "0" | -| ul.side-nav a | font-weight | "400" | -| ul.side-nav a | font-size | "0.88rem" | -| ul.side-nav a | letter-spacing | "0.06em" | -| ul.side-nav a | border | "0" | -| ul.side-nav a | position | relative | -| ul.side-nav a:hover | background | transparent | -| ul.side-nav a:hover | border-color | transparent | -| ul.side-nav a:hover | color | var(--gold) | -| ul.side-nav a:hover | text-decoration | none | -| ul.side-nav a:hover | box-shadow | none | -| ul.foot-nav | display | flex | -| ul.foot-nav | gap | var(--space-4) | -| ul.foot-nav | list-style | none | -| ul.foot-nav | margin | "0" | -| ul.foot-nav | padding | "0" | -| ul.foot-nav a | color | var(--paper-faint) | -| ul.foot-nav a | font-weight | "400" | -| ul.foot-nav a | letter-spacing | "0.1em" | -| ul.foot-nav a | font-size | "0.78rem" | -| ul.foot-nav a:hover | color | var(--gold) | -| .content.cards | display | grid | -| .content.cards | gap | var(--space-4) | -| .content.cards | margin-top | "0" | -| .content.cards | grid-template-columns | "repeat(auto-fill, minmax(16rem, 1fr))" | -| article.card | background | "rgba(0,0,0,.35)" | -| article.card | border | 1px solid var(--border-soft) | -| article.card | border-radius | var(--radius-sm) | -| article.card | padding | "1.35rem 1.15rem" | -| article.card | box-shadow | none | -| article.card | transition | "border-color .35s ease, box-shadow .35s ease, transform .35s ease" | -| article.card:hover | transform | "translateY(-3px)" | -| article.card:hover | box-shadow | var(--shadow-card) | -| article.card:hover | border-color | var(--gold-dim) | -| .site-form | background | var(--glass) | -| .site-form | border | 1px solid var(--border) | -| .site-form | border-radius | var(--radius) | -| .site-form | padding | "var(--space-6) var(--space-6) var(--space-7, 1.75rem)" | -| .site-form | margin | "0 0 var(--space-6)" | -| .site-form | max-width | "100%" | -| .site-form | width | "100%" | -| .site-form | box-shadow | var(--shadow) | -| .site-form | backdrop-filter | blur(16px) | -| .site-form | -webkit-backdrop-filter | blur(16px) | -| .site-form .meta | display | none | -| .site-form form | display | grid | -| .site-form form | grid-template-columns | "minmax(0, 1fr) minmax(0, 1fr)" | -| .site-form form | column-gap | var(--space-5) | -| .site-form form | row-gap | var(--space-5) | -| .site-form form | gap | var(--space-5) | -| .site-form form | margin | "0" | -| .site-form form | width | "100%" | -| .site-form form | max-width | "100%" | -| .site-form label | display | grid | -| .site-form label | gap | var(--space-2) | -| .site-form label | margin | "0" | -| .site-form label | min-width | "0" | -| .site-form label | font-weight | "400" | -| .site-form label | color | var(--gold) | -| .site-form label | font-size | "0.78rem" | -| .site-form label | letter-spacing | "0.16em" | -| .site-form label | text-transform | uppercase | -| .site-form label:nth-child(1) | grid-column | "1" | -| .site-form label:nth-child(2) | grid-column | "2" | -| .site-form label:nth-child(n+3) | grid-column | "1 / -1" | -| .site-form .actions | grid-column | "1 / -1" | -| .site-form input | -webkit-appearance | none | -| .site-form textarea | -webkit-appearance | none | -| .site-form input | appearance | none | -| .site-form textarea | appearance | none | -| .site-form input | box-sizing | border-box | -| .site-form textarea | box-sizing | border-box | -| .site-form input | display | block | -| .site-form textarea | display | block | -| .site-form input | width | "100%" | -| .site-form textarea | width | "100%" | -| .site-form input | height | "2.75rem" | -| .site-form textarea | min-height | "10rem" | -| .site-form label:nth-child(4) textarea | min-height | "14rem" | -| .site-form textarea | resize | vertical | -| .site-form input | padding | "0 0.9rem" | -| .site-form textarea | padding | "0.75rem 0.9rem" | -| .site-form input | border | 1px solid var(--border) | -| .site-form textarea | border | 1px solid var(--border) | -| .site-form input | border-radius | var(--radius-sm) | -| .site-form textarea | border-radius | var(--radius-sm) | -| .site-form input | background | "rgba(0,0,0,.4)" | -| .site-form textarea | background | "rgba(0,0,0,.4)" | -| .site-form input | color | var(--paper) | -| .site-form textarea | color | var(--paper) | -| .site-form input | font | inherit | -| .site-form textarea | font | inherit | -| .site-form input | font-size | "0.95rem" | -| .site-form textarea | font-size | "0.95rem" | -| .site-form input | line-height | "1.4" | -| .site-form textarea | line-height | "1.65" | -| .site-form input | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form textarea | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form input:hover | border-color | var(--gold-dim) | -| .site-form textarea:hover | border-color | var(--gold-dim) | -| .site-form input:focus | outline | none | -| .site-form textarea:focus | outline | none | -| .site-form input:focus | border-color | var(--gold) | -| .site-form textarea:focus | border-color | var(--gold) | -| .site-form input:focus | box-shadow | var(--ring) | -| .site-form textarea:focus | box-shadow | var(--ring) | -| .site-form input[readonly] | background | "rgba(0,0,0,.25)" | -| .site-form input[readonly] | color | var(--paper-faint) | -| .site-form .err | color | var(--danger) | -| .site-form .err | font-size | "0.8rem" | -| .site-form .err | font-weight | "500" | -| .site-form .err | letter-spacing | "0.04em" | -| .site-form .actions | display | flex | -| .site-form .actions | align-items | center | -| .site-form .actions | gap | var(--space-4) | -| .site-form .actions | margin-top | var(--space-2) | -| .site-form .actions | flex-wrap | wrap | -| .site-form button | -webkit-appearance | none | -| .site-form button | appearance | none | -| .site-form button | height | "2.75rem" | -| .site-form button | padding | "0 1.35rem" | -| .site-form button | background | "linear-gradient(135deg, #f5e6c8, var(--gold))" | -| .site-form button | color | var(--ink) | -| .site-form button | border | "0" | -| .site-form button | border-radius | 999px | -| .site-form button | font-weight | "600" | -| .site-form button | font-size | "0.85rem" | -| .site-form button | letter-spacing | "0.12em" | -| .site-form button | cursor | pointer | -| .site-form button | box-shadow | "0 8px 28px rgba(212,175,55,.28)" | -| .site-form button | transition | "transform .2s ease, box-shadow .2s ease, filter .2s ease" | -| .site-form button:hover | filter | brightness(1.06) | -| .site-form button:hover | transform | "translateY(-1px)" | -| .site-form button:hover | box-shadow | "0 12px 36px rgba(212,175,55,.4)" | -| .site-form .actions a | color | var(--paper-faint) | -| .site-form .actions a | font-weight | "400" | -| .site-form .actions a | text-decoration | none | -| .site-form .actions a | font-size | "0.85rem" | -| .site-form .actions a | letter-spacing | "0.08em" | -| .site-form .actions a:hover | color | var(--gold) | -| .flash.err | color | var(--danger) | -| .flash.err | font-weight | "500" | diff --git a/examples/web-site-zh/styles/view.tables.md b/examples/web-site-zh/styles/view.tables.md deleted file mode 100755 index f30332e..0000000 --- a/examples/web-site-zh/styles/view.tables.md +++ /dev/null @@ -1,71 +0,0 @@ -# View 几何适配 - -这些字面声明只适配明确的 View 包装。原始色板、动画、排版和组件属性保留在 shell.tables.md;可调用入口说明如何将递归框架连接到这些数据。 - -## geometry - -基础预览层继承本站字体与全宽。资源仍保留结构值,其语义子块参与原来的命名网格;列表使用 Markdown,不增加私有引言方言。 - -| selector | property | value | -|---|---|---| -| .mq-document .mq-view | max-width | none | -| .mq-document .mq-view | margin | 0 | -| .mq-document .mq-view | padding | 0 | -| .mq-document .mq-view | line-height | inherit | -| .mq-document .mq-view | font-family | inherit | -| .mq-document .site-layout | display | grid | -| .mq-document .site-layout | grid-template-rows | auto 1fr auto | -| .mq-document .site-layout | min-height | 100vh | -| .mq-document .site-layout > .slot-nav | display | contents | -| .mq-document .site-layout > .slot-sidebar | display | contents | -| .mq-document .site-layout .main-intro ul | padding | 0 | -| .mq-document .site-layout .main-intro ul | list-style | none | -| .mq-document .site-layout .main-intro li > p | margin | 0 | -| .mq-document .site-layout .main-intro blockquote > p | margin | 0 | - -## selectors - -只有这些结构地址改变,原属性、值、媒体与顺序保留。这是本站迁移表,不是新的页面语言。 - -| @ | old | new | -|---|---|---| -| 1 | body.has-sidebar | .site-layout.has-sidebar | -| 2 | body.no-sidebar | .site-layout.no-sidebar | -| 3 | body.layout-stacked | .site-layout.layout-stacked | -| 4 | body.is-desk | .site-layout.is-desk | -| 5 | main.main | section.main | -| 6 | .main-intro > .claim | .main-intro ul | -| 7 | .main-intro > .steps | .main-intro ol | -| 8 | .intro_title | .main-intro h1 | -| 9 | .kicker | .main-intro blockquote | - -## areas - -按同一级联顺序编译这些原始章节。 - -| name | -|---| -| vars | -| motion | -| layout | -| responsive | -| chrome | -| widgets | - - -## properties - -在实际语义目标上恢复每组命名属性,原生编译器给名称补上开头的类选择器点。 - -| @ | name | selector | -|---|---|---| -| 1 | topnav | mq-document .site-layout .topnav | -| 2 | side_panel | mq-document .site-layout .side | -| 3 | footer | mq-document .site-layout .foot | -| 4 | card_title | mq-document .site-layout .content.cards h2 | -| 5 | card_body | mq-document .site-layout .content.cards p | -| 6 | kicker | mq-document .site-layout .main-intro blockquote | -| 7 | intro_title | mq-document .site-layout .main-intro h1 | -| 8 | lede | mq-document .site-layout .main-intro .slot-intro-content > p | -| 9 | claim | mq-document .site-layout .main-intro ul > li | -| 10 | step | mq-document .site-layout .main-intro ol > li | diff --git a/examples/web-site-zh/verify.mq.md b/examples/web-site-zh/verify.mq.md deleted file mode 100755 index 48e8e42..0000000 --- a/examples/web-site-zh/verify.mq.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -markup: occlusion -title: 主题迁移的原生核对证据 -import: - document: lib/document.mq.md - table: lib/table.mq.md - hash: lib/hash.mq.md - result: lib/result.mq.md - theme: styles/index.mq.md - original: styles/shell.mq.md ---- - -本工具读取实际声明并编译原主题和 View 投影,不发放整个站点的通过证书,也不能替代 HTTP 与浏览器验收。它不初始化或写入业务数据库。路径和数据读取都通过固有能力完成,没有另一种语言搬运源码或计算期望值。 - -```sh -marqdo call examples/web-site-zh/verify.mq.md theme_values --effects plugin,fs.read --fs-root examples/web-site-zh --require-ok --json -``` - -## _row - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| before | map | 必填 | 原始字面声明的单条记录 | -| after | map | 必填 | 相同位置的实际投影记录 | -| keep_selector | bool | False | 令牌和关键帧还须保持地址自身 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 允许的地址变化之外,整条声明是否相同 | - -使用`before`、`after`、`keep_selector`=False。先只排除双方同名的选择器字段,再比较完整记录,因此属性、值、可选媒体和其他已有字段都不能消失。原生字典比较不依赖键的显示顺序;值类型与内容仍必须相同,不用文本格式化掩盖差异。 - -全局令牌与动画关键帧连地址自身也必须保持,这时再比较原始记录中的选择器。本纯函数不读取文件、不编译 CSS,也不宣称相同记录已经呈现在浏览器中。不可变删键返回新记录,输入仍供地址比较和后续诊断使用。 - -我们 **left = [只排除原始结构地址](table.delete(map=`before`, key="选择器"))** 和 **right = [只排除投影结构地址](table.delete(map=`after`, key="选择器"))**。 -1. `left` != `right` - 返回 *False*,因为声明数据本身已经变化。 -1. `keep_selector` - 返回 *[全局声明同时保持地址](access(before, "选择器") == access(after, "选择器"))*。 -返回 *True*,表示只发生允许的局部地址投影。 - -## _area - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | 必填 | 精确的原始主题章节名称 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result,成功值为该区段实际逐行核对数 | - -输入`name`,从站点根授予 fs.read。原表继续使用选择器、属性、值和媒体的中文列名,投影保留这些键,不能为复用代码而重写原始数据。先核对实际行数,再按相同位置逐项比较,因此删除、额外添加和交换不同声明都能保留失败。 - -数据来自原生字面表读取,投影来自当前样式入口。缺失章节或非法列形态保留原生诊断;有变化则返回具体区段的失败 Result,不将空输出当作成功。累计值只来自已完成比较的每一行。令牌和关键帧采用更严格的全局地址规则,其余区段仅允许明确的选择器映射。 - -列表下标从零开始,每次只读取相同位置的投影。不能把记录先排序再比较,因为相同选择器重复声明时,原顺序本身决定 CSS 级联结果。只有一行完整通过后才递增位置,失败不会把已经比较的部分数目包装成整个区段的成功值;上层据此决定是否继续统计。 - -我们 **columns = [读取原始声明章节](document.read_table(path="styles/shell.tables.md", title=`name`))**、**rows = [保留原始行序](table.from_columns(columns=`columns`))** 和 **projected = [运行真实选择器投影](theme._table(name=`name`))**。 -1. len(`rows`) != len(`projected`) - 返回 *[保留声明数量变化](result.error(code="site.theme_rows", message=`name`, operation="theme_values"))*。 -我们 **position = 0**。 -- [按相同位置核对完整声明](for rows as row) - 我们 **actual = [读取对应投影行](table.at(xs=`projected`, i=`position`))** 和 **same = [核对允许地址之外的全部字段](_row(before=`row`, after=`actual`, keep_selector=(`name` == "vars" or `name` == "motion")))**。 - 1. not `same` - 返回 *[保留实际声明差异](result.error(code="site.theme_value", message=`name`, operation="theme_values"))*。 - 我们 **position = position + 1**,只累计真正通过的声明。 -返回 *[交出该区段的实际核对数](result.ok(value=`position`))*。 - -## theme_values - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result,包含已核对行数、原主题及实际 View CSS 的摘要 | - -从站点根授予 plugin 与 fs.read。逐区段运行实际原始表和投影的核对工具,失败时原样返回失败,不继续累加其他结果。六个区段必须全部完成,媒体、值、属性和顺序均由各自完整记录核对,令牌和关键帧还要求地址保持不变。 - -成功值含 preserved_rows、original_sha256、view_sha256,摘要来自原生编译器真实输出。新 View 地址和包装层几何会让两份 CSS 不同,不能把摘要相同当成唯一通过条件。它们只是可追踪产物身份,浏览器仍需验证色板、字体、几何、表单和当前记录。 - -命令中的 --require-ok 让失败 Result 影响进程退出,自动化不能只看外层调用完成就读取成功字段。读取与编译不写文件、不初始化数据库,也不清理用户目录。实际站点行为使用独占副本测试,服务退出后再清理。这个工具不发放整个项目的完成证书,也不会用删除失败规则的方式修复差异。 - -`areas` = - -| name | -|---| -| vars | -| motion | -| layout | -| responsive | -| chrome | -| widgets | - -我们 **count = 0**。 -- [核对每个实际原始主题区段](for areas as name) - 我们 **checked = [运行有界区段比较](_area(name=`name`))**。 - 1. not access(`checked`, "ok") - 返回 *checked*,保留真实失败。 - 我们 **count = [累计实际核对数](count + access(checked, "value"))**。 -我们 **old_css = [编译保留的原主题](original.css())**、**view_css = [编译实际 View 主题](theme.css())**、**original_sha256 = [识别真实原始 CSS](hash.sha256(text=`old_css`))** 和 **view_sha256 = [识别真实 View CSS](hash.sha256(text=`view_css`))**。 - -`evidence` = - -| preserved_rows | original_sha256 | view_sha256 | -|---|---|---| -| `count` | `original_sha256` | `view_sha256` | - -返回 *[交出真实核对和编译证据](result.ok(value=`evidence`))*。 diff --git a/examples/web-site/DEMO.md b/examples/web-site/DEMO.md deleted file mode 100755 index 0eb1b8f..0000000 --- a/examples/web-site/DEMO.md +++ /dev/null @@ -1,27 +0,0 @@ -# Complete-site walkthrough - -Start through the callable workflow in [README](README.md). For a fresh owned database the site seeds eight articles; an existing database retains its actual rows and must not be reset merely to reproduce that count. - -| Step | Actual action | Evidence to inspect | -|---|---|---| -| 1 | Open Home | Original theme, Markdown introduction, badges, reading steps and summary cards | -| 2 | Open a card | Declared /post/{slug} route; full Markdown body rather than its summary | -| 3 | Read index and follow components/index | Actual parent/child tree, terminal Markdown and typed data/form/navigation resources | -| 4 | Submit New with an empty title | Actual server rule message; retry retains current CSRF | -| 5 | Submit title, slug, summary and body | New row appears on Home and in the gated desk without restart | -| 6 | Follow Login, use admin/demo, open Admin | Real route gate; separate desk navigation, no public rail, shared form and current cards | -| 7 | Return Home and log out | Session-specific links switch with the real identity; direct Admin access redirects again | -| 8 | Narrow the browser | The original 860px breakpoint puts main before the side rail without overflow | - -Source responsibilities remain separate. Route metadata lives in each Document, form data is [forms.tables.md](forms.tables.md), current data behavior is [components/articles](components/articles.mq.md), SEO/fonts are [components/head](components/head.mq.md), and theme source plus explicit View mapping begins at [styles/index](styles/index.mq.md). No compose mutation chain or author page HTML is required. - -The callable [verification tool](verify.mq.md) compares 412 original declaration rows and returns actual baseline/projected CSS hashes. It does not replace visual or HTTP acceptance. The real-browser suite deliberately aborts external font requests and verifies declared font families and local fallback rendering; it makes no claim about external service delivery. - -Use native file discovery for author-asset checks, excluding the explicitly generated stylesheet directory: - -```sh -target/debug/marqdo call lib/fs.mq.md find 'path="."' 'pattern="**/*.js"' 'exclude=["public/generated/**"]' --effects fs.read --fs-root examples/web-site --json -target/debug/marqdo call lib/fs.mq.md find 'path="."' 'pattern="**/*.css"' 'exclude=["public/generated/**"]' --effects fs.read --fs-root examples/web-site --json -``` - -Both author-asset lists are empty. This says nothing about generated runtime resources or native rendering internals, which are separate declared boundaries. diff --git a/examples/web-site/README.md b/examples/web-site/README.md deleted file mode 100755 index a2b2cfc..0000000 --- a/examples/web-site/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# web-site - -This is the complete English document-native site: Home, About, New, the gated custom desk and slug detail each declare their own route. Parents compose structure and leaves contain Markdown. The original ink/wine/gold theme, typography, particles, breakpoints and form states remain declarative, with no author business JavaScript or hand-written CSS. - -From the checkout root, use the current source CLI and prepare the engineering and Web plugins, then call the actual serving workflow: - -```sh -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --require-ok --json -target/debug/marqdo call skills/marqdo-dev/index.mq.md prepare_web --effects plugin --fs-root . --require-ok --json -target/debug/marqdo call examples/web-site/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-site --require-ok --json -``` - -Open http://127.0.0.1:18081/ and use admin/demo only as local fixture credentials. Default SQLite belongs to the granted site root; restart preserves existing rows. The listener blocks in this process and the caller owns shutdown. - -Read by responsibility: - -- [Site entry](index.mq.md) — declare Home and compose actual data, form, session, gate and listener resources. -- [Layout entry](components/index.mq.md) — public rail and separate desk tree; terminal leaves live in components/content. -- [Article request resources](components/articles.mq.md) — current summary cards and actual captured-slug full Markdown detail. -- [Shared form](forms.mq.md) — actual fields/rules are in forms.tables.md; failed validation retains CSRF. -- [Theme entry](styles/index.mq.md) — retain original data and project only structural addresses plus wrapper geometry. -- [Native verification tool](verify.mq.md) — actually compare 412 original layout/motion declaration rows and return real CSS identities. - -```sh -target/debug/marqdo call examples/web-site/verify.mq.md theme_values --effects plugin,fs.read --fs-root examples/web-site --require-ok --json -``` - -Theme output is generated at public/generated/theme.css; edit the adjacent source tables rather than that rebuildable artifact. Original Google Fonts links remain declared, with the original fallback families offline. Local browser acceptance does not claim external font-service delivery. - -The public creation form remains public, while the custom desk is role-gated. Rendering the same form in Admin does not make its submission endpoint private. HTTP regression uses owned copied sites on Tree and Bytecode; real-browser cases verify styles, publishing, detail, session navigation, logout and narrow-screen order without modifying the example's existing database. - -For the hands-on sequence see [DEMO.md](DEMO.md)。 diff --git a/examples/web-site/components/articles.mq.md b/examples/web-site/components/articles.mq.md deleted file mode 100755 index ae25228..0000000 --- a/examples/web-site/components/articles.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: Current article list and slug detail -import: - component: ext/web/component/index.mq.md - query: ext/data/view.mq.md - table: lib/table.mq.md ---- - -Both views read the same application-owned articles table for each request. Cards use summaries and slug links; detail uses the complete Markdown body. These pure descriptors do not open a second database or cache startup records. Their renderer retains the native card/article classes consumed by the original theme. - -## cards - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Current article cards linked to /post/slug | - -Construct this query without effects. The serving application owns its database resource and actual request execution. Cards keep the original stable id order and use the existing summary/title/slug projection. Titles and summaries are escaped text, while the full body is intentionally reserved for detail. A publish through either mounted form becomes visible on the next request. - -We **resource = [Describe the actual current article list](query.query(source="articles", order="id", link_prefix="/post/"))**. -Return *[Place one request-time card responsibility](component.resource(value=`resource`, slot="articles"))*. - -## detail - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | First article matching the actual captured slug, rendered with full Markdown body | - -The declared /post/{slug} Document supplies the path parameter when the server resolves this query. A same-named query-string value cannot override that capture. The native renderer uses the body even when a summary is present, and it does not mutate the retained condition between requests. Missing database resources remain errors; a missing record remains an empty result under the existing query contract. - -We **condition = [Keep a native record rather than a one-column list](table.put(in=None, at="slug", value="{slug}"))** and **resource = [Describe full-body slug detail](query.query(source="articles", where=`condition`, detail=True, limit=1))**. -Return *[Place the actual requested article](component.resource(value=`resource`, slot="article"))*. diff --git a/examples/web-site/components/content/about.md b/examples/web-site/components/content/about.md deleted file mode 100755 index d1ddb45..0000000 --- a/examples/web-site/components/content/about.md +++ /dev/null @@ -1,9 +0,0 @@ -> about - -# About - -Documentation and the deployed site stay one .mq.md artifact. Layout and theme are GFM style tables in styles/shell.mq.md — structure without hand-written CSS or business JavaScript. - -- docs = program -- server-side rules -- hands-on diff --git a/examples/web-site/components/content/desk-footer.md b/examples/web-site/components/content/desk-footer.md deleted file mode 100755 index 5c191a2..0000000 --- a/examples/web-site/components/content/desk-footer.md +++ /dev/null @@ -1 +0,0 @@ -[Site](/) · [Admin](/admin) · [Logout](/admin/logout) diff --git a/examples/web-site/components/content/desk.md b/examples/web-site/components/content/desk.md deleted file mode 100755 index 891f89d..0000000 --- a/examples/web-site/components/content/desk.md +++ /dev/null @@ -1,9 +0,0 @@ -> desk · you are in admin - -# Admin - -This is the management desk (login required): same articles schema as the public site, assembled as list + create form — not a separate SPA. Use Site in the topnav to return, or Logout to end the session. - -- login-gated -- table-declared -- create + list diff --git a/examples/web-site/components/content/footer.md b/examples/web-site/components/content/footer.md deleted file mode 100755 index eae8fb2..0000000 --- a/examples/web-site/components/content/footer.md +++ /dev/null @@ -1 +0,0 @@ -[Marqdo](https://www.marqdo.com/) · [Source](https://github.com/cflmy/marqdo) diff --git a/examples/web-site/components/content/home.md b/examples/web-site/components/content/home.md deleted file mode 100755 index fcba3fa..0000000 --- a/examples/web-site/components/content/home.md +++ /dev/null @@ -1,13 +0,0 @@ -> WWW demo · tables as the full stack - -# Marqdo - -One executable Markdown artifact declares routes, forms, admin pages, and styles — no hand-written business JavaScript, no author .css. Click a card for the full article, then try the three steps below. - -- 0 author JS -- 0 author .css -- GFM tables - -1. Click any card — /post/{slug} opens the detail page from the same articles table. -2. Open [New](/new) and submit with an empty title (validation from a rule table). -3. Open top-nav **Login** (admin / demo), then **Admin** — gated desk with create form + list. diff --git a/examples/web-site/components/content/new.md b/examples/web-site/components/content/new.md deleted file mode 100755 index 8863dd1..0000000 --- a/examples/web-site/components/content/new.md +++ /dev/null @@ -1,5 +0,0 @@ -> form · try validation - -# New article - -Leave Title empty and submit — the error comes from the rule table, not client JavaScript. Then fill title, slug, and summary to create a row shared with Admin and the card grid. diff --git a/examples/web-site/components/content/post.md b/examples/web-site/components/content/post.md deleted file mode 100755 index 7ca6af1..0000000 --- a/examples/web-site/components/content/post.md +++ /dev/null @@ -1 +0,0 @@ -> article · table-bound detail diff --git a/examples/web-site/components/desk.mq.md b/examples/web-site/components/desk.mq.md deleted file mode 100755 index 3cffe45..0000000 --- a/examples/web-site/components/desk.mq.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -markup: occlusion -title: Administration navigation and footer -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md ---- - -The custom desk keeps its own brand and closing links, and omits the public side rail. Authentication remains the serving entry's responsibility. Neither constructing these nodes nor hiding their links can authorize a visitor to the administration route. - -## nav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Desk navigation using the real current session | - -Construction needs no effects. The first link preserves Admin as the operator's current context, followed by Site, New and Logout. Only the logout link is conditional, matching the original navigation. The entire desk is separately gated, and the actual logout destination remains a native session route. Returned nodes keep their structured resource value so the parent can place them without HTML strings. - -`items` = - -| @ | label | href | when | -|---|---|---|---| -| 1 | Admin | /admin | | -| 2 | Site | / | | -| 3 | New | /new | | -| 4 | Logout | /admin/logout | auth | - -We **resource = [Describe the desk's current navigation](component.navigation(items=`items`))**. -Return *[Keep the same navigation fragment slot](component.resource(value=`resource`, slot="nav"))*. - -## foot - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Desk footer with terminal Markdown return and logout links | - -Read this leaf with fs.read under the site root. The route gate has already decided access before the renderer resolves this component. Site and Admin retain their return destinations, while Logout ends the session only when followed. The footer has one content responsibility and no internal layout to split further; the parent owns its placement and the original theme owns its appearance. - -We **text = [Read the desk's terminal closing links](fs.read_text(path="components/content/desk-footer.md"))** and **leaf = [Retain ordinary Markdown content](component.markdown(text=`text`, slot="footer-content"))**. -Return *[Place it in the semantic desk footer](component.wrap(children=`leaf`, kind="footer", slot="footer", style="foot"))*. diff --git a/examples/web-site/components/foot.mq.md b/examples/web-site/components/foot.mq.md deleted file mode 100755 index d8c4fd3..0000000 --- a/examples/web-site/components/foot.mq.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -markup: occlusion -title: Public footer Markdown leaf -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md ---- - -The public footer is one simple set of project and source links. It has no independent internal columns, so its terminal Markdown is the stopping point for decomposition. The parent controls where it appears; the theme supplies its existing footer appearance. - -## foot - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Semantic footer containing its terminal Markdown links | - -Read with fs.read relative to the granted site root. The leaf retains the original project and source destinations; it does not query business rows or expose session credentials. Changing wording belongs in content/footer.md, while changing layout belongs in the parent. This module never renders a child to HTML before composition. - -We **text = [Read the terminal project links](fs.read_text(path="components/content/footer.md"))** and **leaf = [Keep the links in Markdown](component.markdown(text=`text`, slot="footer-content"))**. -Return *[Preserve the footer's semantic region](component.wrap(children=`leaf`, kind="footer", slot="footer", style="foot"))*. - diff --git a/examples/web-site/components/head.mq.md b/examples/web-site/components/head.mq.md deleted file mode 100755 index ce4c1b4..0000000 --- a/examples/web-site/components/head.mq.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -markup: occlusion -title: SEO, font and theme resource declarations -import: - component: ext/web/component/index.mq.md - head: ext/web/head.mq.md ---- - -This leaf preserves the original site metadata and Google Fonts resource addresses. It declares links, never fetches them during assembly. Theme CSS is explicitly generated from style tables by serve and mounted at the declared static path. - -## nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| homepage | bool | False | Include the original home-only SEO rows | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Pure head resource for real SEO, fonts and the generated theme | - -Use `homepage`=False without effects during page assembly. Only the home Document opts into its original SEO rows; fonts and the theme remain shared. Metadata remains key/value records and the links retain native rel/href/crossorigin fields. The renderer collects them into the actual head in both preview and HTTP output, deduplicating equal declarations. They do not become body placeholders or fragment markup. - -Font delivery still depends on browser access to the external font service; the page uses its declared fallbacks when unavailable. Declaring the theme path does not build it or prove it exists. The serving workflow compiles and writes that exact file before opening a listener, while a static preview caller owns asset preparation. - -`meta` = - -| @ | key | value | -|---|---|---| -| 1 | description | Tables as the full stack — Marqdo Web demo with zero author business JavaScript. | -| 2 | og:type | website | -| 3 | og:title | Marqdo Web Site | - -`links` = - -| @ | rel | href | crossorigin | -|---|---|---|---| -| 1 | preconnect | https://fonts.googleapis.com | | -| 2 | preconnect | https://fonts.gstatic.com | anonymous | -| 3 | stylesheet | https://fonts.googleapis.com/css2?family=Great+Vibes&family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;600&display=swap | | -| 4 | stylesheet | /static/generated/theme.css | | - -We **selected_meta = None** because non-home pages retain only their originally shared head links. -1. `homepage` - We **selected_meta = meta** to retain the original home-specific SEO. -We **resource = [Retain actual metadata and native head links](head.resource(meta=`selected_meta`, links=`links`))**. -Return *[Place one pure head resource alongside the layout](component.resource(value=`resource`, slot="document-head"))*. diff --git a/examples/web-site/components/index.mq.md b/examples/web-site/components/index.mq.md deleted file mode 100755 index 528080c..0000000 --- a/examples/web-site/components/index.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: Public and desk layout entry -import: - component: ext/web/component/index.mq.md - nav: nav.mq.md - side: side.mq.md - foot: foot.mq.md - desk: desk.mq.md - head: head.mq.md - table: lib/table.mq.md ---- - -This parent declares one site frame. The public tree has navigation, side/main and footer; the desk has its own navigation and footer with no public rail. Children own Markdown or typed request resources. Geometry is declared here and compiled from the original theme tables, never hidden inside a rendered HTML string. - -## frame - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| body | list | required | Page-owned main nodes, retaining nested resources | -| management | bool | False | Select the gated custom desk frame without a public side rail | -| homepage | bool | False | Keep original home SEO scoped to Home | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Recursive site structure and pure head resources | - -Use `body`, `management`=False and `homepage`=False. Child navigation keeps its actual session conditions; this function does not authenticate or authorize a visitor. The desk route is separately gated in serve, so choosing its frame cannot grant access. Footer content is already a simple Markdown responsibility and needs no further internal layout. - -The stable slots nav, sidebar, main and footer retain fragment identities. Native resource wrappers remain in the View tree; the theme transparently places their semantic children in the original grid. The class is-desk is local to this frame, replacing the old whole-body mutation. The theme projection keeps its original rules and values under that explicit scope. Pure head resources are collected into the real document head. - -We **top = [Assemble public navigation](nav.nav())** and **rail = [Assemble the public side rail](side.side())** and **bottom = [Read the public Markdown footer](foot.foot())** and **classes = "site-layout has-sidebar"**. -1. `management` - We **top = [Use the desk's own navigation](desk.nav())** and **rail = [Keep the desk free of the public rail](table.empty_list())** and **bottom = [Read the desk return links](desk.foot())** and **classes = "site-layout no-sidebar is-desk"**. -We **main = [Retain the supplied main responsibility](component.wrap(children=`body`, kind="section", slot="main", style="main"))** and **children = [Keep navigation before the public rail](table.concat(a=`top`, b=`rail`))** and **children = [Keep main content after navigation](table.concat(a=`children`, b=`main`))** and **children = [Finish with the selected footer](table.concat(a=`children`, b=`bottom`))**. -We **frame = [Declare the shared named layout region](component.wrap(children=`children`, kind="section", slot="site", style=`classes`))** and **resources = [Retain actual SEO, fonts and compiled theme](head.nodes(homepage=`homepage`))**. -Return *[Keep head declarations alongside the recursive frame](table.concat(a=`resources`, b=`frame`))*. diff --git a/examples/web-site/components/intro.mq.md b/examples/web-site/components/intro.mq.md deleted file mode 100755 index 7356999..0000000 --- a/examples/web-site/components/intro.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion -title: Terminal introduction component -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md ---- - -The introduction ends in one ordinary Markdown responsibility: category, title, explanation, feature bullets and reading steps. Markdown provides that hierarchy directly; the theme selects those semantic elements. Page geometry stays in the parent frame, and no content row uses an HTML shell or the removed intro-binding dialect. - -## nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Author-selected home, about, new, desk or post Markdown leaf | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One semantic introduction region around the actual Markdown leaf | - -Use `name` under the granted site root with fs.read. The relative leaf path is selected by the authored Document, never a request parameter. Missing leaves retain the native file diagnostic rather than displaying a copied fallback. Reading the leaf does not execute its emphasis or links as Marqdo statements; its content is data for the native Markdown renderer. - -Each leaf is already simple enough for Markdown: blockquote category, heading, paragraphs, bullets and ordered steps. A change that adds independent internal geometry should split again. Style selectors preserve the original typography, badges and step panel while the page still reads as a document. - -We **path = "components/content/" + name + ".md"** and **text = [Read this introduction's actual content](fs.read_text(path=`path`))** and **leaf = [Retain its simple Markdown hierarchy](component.markdown(text=`text`, slot="intro-content"))**. -Return *[Keep the introduction as a semantic region](component.wrap(children=`leaf`, kind="section", slot="intro", style="main-intro"))*. diff --git a/examples/web-site/components/nav.mq.md b/examples/web-site/components/nav.mq.md deleted file mode 100755 index 8cdc28c..0000000 --- a/examples/web-site/components/nav.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: Session-aware nav component -import: - component: ext/web/component/index.mq.md ---- - -This module owns only the selected navigation responsibility. Its labels and destinations retain the original site order. The session-dependent rows are a typed navigation resource because their visibility must follow each request rather than a startup snapshot. - -## nav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One typed navigation resource with stable fragment identity | - -Construction is pure and does not log in, log out or register a route. Empty when values keep links visible; guest and auth use the actual session supplied by the server. The resource renderer retains native navigation classes for the existing theme. Hiding Admin never protects its URL: the serving entry separately binds a real /admin role gate. - -The parent places this region and owns its grid relationship. Edit labels here and update declared routes when changing a destination; do not concatenate an HTML navigation string or return an obsolete front/back binding table. - -`items` = - -| @ | label | href | when | -|---|---|---|---| -| 1 | Marqdo | / | | -| 2 | About | /about | | -| 3 | New | /new | | -| 4 | Login | /login | guest | -| 5 | Admin | /admin | auth | -| 6 | Logout | /admin/logout | auth | - -We **resource = [Describe current-session navigation](component.navigation(items=`items`, region="nav"))**. -Return *[Keep this region as a typed View resource](component.resource(value=`resource`, slot="nav"))*. diff --git a/examples/web-site/components/side.mq.md b/examples/web-site/components/side.mq.md deleted file mode 100755 index a4e1cca..0000000 --- a/examples/web-site/components/side.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: Session-aware sidebar component -import: - component: ext/web/component/index.mq.md ---- - -This module owns only the selected navigation responsibility. Its labels and destinations retain the original site order. The session-dependent rows are a typed navigation resource because their visibility must follow each request rather than a startup snapshot. - -## side - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One typed navigation resource with stable fragment identity | - -Construction is pure and does not log in, log out or register a route. Empty when values keep links visible; guest and auth use the actual session supplied by the server. The resource renderer retains native navigation classes for the existing theme. Hiding Admin never protects its URL: the serving entry separately binds a real /admin role gate. - -The parent places this region and owns its grid relationship. Edit labels here and update declared routes when changing a destination; do not concatenate an HTML navigation string or return an obsolete front/back binding table. - -`items` = - -| @ | label | href | when | -|---|---|---|---| -| 1 | 1. Home | / | | -| 2 | 2. New form | /new | | -| 3 | 3. Login | /login | guest | -| 4 | 3. Admin | /admin | auth | -| 5 | About | /about | | - -We **resource = [Describe current-session navigation](component.navigation(items=`items`, region="sidebar"))**. -Return *[Keep this region as a typed View resource](component.resource(value=`resource`, slot="sidebar"))*. diff --git a/examples/web-site/db/articles.mq.md b/examples/web-site/db/articles.mq.md deleted file mode 100755 index 7ba5bb6..0000000 --- a/examples/web-site/db/articles.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: Article schema and seed handbook -import: - document: lib/document.mq.md ---- - -This file explains callable use; [articles.tables.md](articles.tables.md) holds the readable literal tables. Set --fs-root to the site directory and grant fs.read. Reading returns data without running prose, opening a database or changing a page. - -## schema - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native table value, preserving literal types and column geometry | - -Declare article fields, native types and nullability. The initializer consumes this table to ensure structure; it must not guess a migration or erase existing rows. - -Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. - -Return *[读取 schema 的实际字面表](document.read_table(path="db/articles.tables.md", title="schema"))*. - -## seed - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native table value, preserving literal types and column geometry | - -Provide initial demonstration articles with their original ids, stable slugs and content. Insert only after the database initializer confirms an empty table; this reader never changes existing articles. - -Call independently with fs.read on the site root. The section must match exactly and uniquely. Malformed tables or dynamic expressions retain native document diagnostics. A returned style declaration still needs compilation; returned database data still needs an explicit initializer. This value is neither HTML nor an applied browser effect. - -Return *[读取 seed 的实际字面表](document.read_table(path="db/articles.tables.md", title="seed"))*. diff --git a/examples/web-site/db/articles.tables.md b/examples/web-site/db/articles.tables.md deleted file mode 100755 index 7b62d3f..0000000 --- a/examples/web-site/db/articles.tables.md +++ /dev/null @@ -1,30 +0,0 @@ -# Article data - -Literal article schema and demonstration content. Reading these tables does not open a database or insert rows. Follow articles.mq.md for callable use; the database initializer decides whether seeding is appropriate. - -## schema - -Field definitions for the native database initializer; nullable values remain booleans. - -| name | type | nullable | -|------|------|----------| -| id | integer | false | -| title | text | false | -| slug | text | false | -| summary | text | true | -| body | text | true | - -## seed - -Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. - -| id | title | slug | summary | body | -|----|-------|------|---------|------| -| 1 | Hello Marqdo | hello-marqdo | A runnable Markdown file is both the site docs and the deployed app — tables declare routes, forms, and styles. | "Marqdo treats an .mq.md file as an executable document. The narrative you read in the editor is the same artifact the server runs: GFM tables become schema, forms, navigation, and CSS. This demo shows that contract end-to-end — open New, trigger a rule-table validation error, then publish a row that appears on Home and Admin without any author JavaScript." | -| 2 | Tables as the full stack | tables-full-stack | Schema, forms, routes, admin pages, and theme tokens share one tabular dialect instead of a JS/CSS split. | "Most stacks split concerns across languages: SQL or an ORM for data, a form library for input, a router for URLs, and a stylesheet for look. Marqdo collapses those surfaces into GFM tables with the same geometry authors already use for documentation. Field tables, rule tables, bind tables, and style tables are not metaphors — they are the runtime. The result is a site you can skim as prose and execute as a program." | -| 3 | Zero author JS and CSS | zero-author-js-css | Business logic stays in Markdown; appearance is style tables plus the host shell — no hand-written business JS or author .css. | "Author business JavaScript is zero by construction: validation runs from rule tables on the server, and list/detail pages are bind tables rendered by the host. Author .css files are also unnecessary when theme tokens live in property/value tables assembled by make_style. The demo turns shell_css=off so only those declared styles paint the page — proving the claim for a conference audience." | -| 4 | Card to detail in one bind | card-to-detail | List cards bind href to slug; a /post/{slug} route plus detail=True opens the full article. | "Click any card on the home page. The list bind exposes href from articles.slug, and link_prefix prefixes /post/. The detail page reuses the same table with a query slug = {slug} and page.detail so the first row renders as a full article — title and Markdown body — instead of a card grid. That is the same pattern used by larger Marqdo sites such as 求道量子." | -| 5 | Style tables not stylesheets | style-tables | Named style tables (kicker, intro_title, card_title) bind through the third column of every layout table. | "Intro, cards, and chrome all use the bind shape front/back/style. The style column points at a named property table in styles/shell.mq.md. When compose_intro or compose_main runs, those tables become CSS classes on the page. Authors never open a .css file to tweak the demo look — they edit readable Markdown tables that stay next to the copy they style." | -| 6 | Forms from field and rule tables | forms-from-tables | Empty title on New fails from the rule table; a valid submit inserts a row shared with Admin. | "The New and Admin pages mount the same form object: a field table declares labels and types, a rule table declares required and max constraints with messages. Submit with an empty title and the error is server-side, not a client script. Fill a title and slug, submit again, and the row shows up in the card grid and under Admin — one schema, two surfaces, zero author JS." | -| 7 | Seed data is documentation | seed-is-docs | These paragraphs were written as a GFM seed table — the demo content is part of the program. | "Seed rows live beside the schema in db/articles.mq.md. On first boot the host inserts them when the articles table is empty. That means the demo narrative is versioned with the code: longer summaries for cards, fuller bodies for detail pages, and slugs that make deep links stable. Reviewers can open the seed table and see exactly what the venue site will show." | -| 8 | Why this Demo matters | why-demo-matters | WWW Demo needs a hands-on artifact reviewers can run, click, and compare to source in minutes. | "A Demo track asks for an implemented system, not a slide-only pitch. This sample is intentionally small: one SQLite table, a handful of routes, and a literary shell — yet it covers the paper claim (tables as the full stack) with a three-step script. Clone the repo, run the web-site sample, click a card, break a form, then open index.mq.md beside the browser. That loop is the publication." | diff --git a/examples/web-site/db/index.mq.md b/examples/web-site/db/index.mq.md deleted file mode 100755 index 7b8750f..0000000 --- a/examples/web-site/db/index.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: web-site database lifecycle -import: - data: ext/data/db.mq.md - articles: articles.mq.md - fs: lib/fs.mq.md - text: lib/text.mq.md ---- - -The database entry connects schema and literal seed leaves to the actual data resource. It no longer uses the removed web database constructor. Grant fs.write and plugin with the site directory as --fs-root; the SQLite path is resolved through that native root rather than the process working directory. - -## open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | None | None selects data/site.db under the site root; tests provide a disposable explicit URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Initialized articles database resource with existing rows preserved | - -Use `url`=None to open the site's local database. Create the default data directory through native file operations, then resolve the actual SQLite filename within the granted root. An explicit SQLite path goes through the same root and symlink checks before the native database resource receives it. Other supported database URIs retain their resource-specific backend contract; they are not sandboxed by filesystem permissions. - -The schema reader preserves native field types and nullability. Initialization ensures the table exists, queries one row to distinguish an empty table, and inserts the original demonstration content only into an empty table. An existing or partly populated table is kept unchanged. This is not a column migrator, data repair tool or reason to delete a user's articles. A native connection, schema or insert diagnostic stops the caller before it starts serving. - -For isolated verification choose a caller-owned temporary SQLite file and copy the article data leaf under that granted site root. Keep the returned resource in the same program for subsequent queries. Close the process before cleaning its owned directory; do not run tests against the example's existing data directory. - -1. `url` == None - We **[Create only the site's default data directory](fs.make_dirs(path="data"))** and **file = [Resolve its database filename](fs.resolve(path="data/site.db"))** and **url = "sqlite:" + file**. -1. [The explicit or default URI selects SQLite](text.starts_with(text=`url`, prefix="sqlite:")) - We **file = [Read the selected SQLite path](text.replace(text=`url`, old="sqlite:", new="", count=1))** and **file = [Apply the native file-root policy](fs.resolve(path=`file`))** and **url = "sqlite:" + file**. -We **store = [Open the selected actual database resource](data.db(url=`url`))** and **fields = [Read the documented article schema](articles.schema())**. -We **[Ensure the table without clearing it](> `store`.init name="articles" fields=`fields`)** and **existing = [Check whether business records already exist](> `store`.select table="articles" limit=1)**. -1. not `existing` - We **seed = [Read the original demonstration data](articles.seed())** and **[Seed only the empty article table](> `store`.insert table="articles" rows=`seed`)**. -Once the selected database is ready, return *store* for the site's resource bindings. diff --git a/examples/web-site/forms.mq.md b/examples/web-site/forms.mq.md deleted file mode 100755 index 70dbf59..0000000 --- a/examples/web-site/forms.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: Shared article form and server validation -import: - form: ext/data/form.mq.md - document: lib/document.mq.md ---- - -New and Admin place the same article form reference. The serving entry mounts this resource once at article; rendering, validation and actual database submission therefore share field definitions and rules. The public creation path remains public as in the original demonstration, while direct access to the custom desk is role-gated. - -## article - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Insert form with title, slug, summary, Markdown body and original validation limits | - -Grant plugin and fs.read on the site root before mounting. The adjacent literal leaf keeps field/rule data readable without turning the workflow into a data dump. Title and slug are required, with original maxima of 120 and 80 characters. Summary and body remain optional, limited to 500 and 8000 characters. These are server rules even if a caller bypasses browser constraints. Constructing the resource writes no rows and grants no authentication. - -The field types remain text and textarea, retaining the original schema behavior. A rejected submission returns field messages and current CSRF for retry; success returns to the home list, where the current-query resource observes the new row. Keep every updated resource value before mounting; using an older value would lose attached fields or rules. - -We **fields = [Read the actual literal field contract](document.read_table(path="forms.tables.md", title="fields"))** and **rules = [Read the actual literal validation rules](document.read_table(path="forms.tables.md", title="rules"))**. - -We **selected = [Create the actual article insertion resource](form.form(table="articles"))** and **selected = [Attach the readable field records](> `selected`.fields fields=`fields`)** and **selected = [Attach the actual server rules](> `selected`.rules rules=`rules`)**. -Return *[Keep submission copy and its successful return target](> `selected`.labels submit="Publish" cancel="Cancel" cancel_href="/")*. diff --git a/examples/web-site/forms.tables.md b/examples/web-site/forms.tables.md deleted file mode 100755 index bb62358..0000000 --- a/examples/web-site/forms.tables.md +++ /dev/null @@ -1,27 +0,0 @@ -# Article form data - -The callable contract is forms.mq.md. These are literal records, not another program or a second submission implementation. Fields map to the existing articles schema; native rendering and server validation consume the same records. - -## fields - -Title and slug are required. Summary and body remain optional, with their original input types. - -| @ | name | label | type | required | -|---|---|---|---|---| -| 1 | title | Title | text | True | -| 2 | slug | Slug | text | True | -| 3 | summary | Summary | textarea | False | -| 4 | body | Body | textarea | False | - -## rules - -These are the original server rules and error messages; browser hints do not replace them. - -| @ | field | rule | message | -|---|---|---|---| -| 1 | title | required | Title is required | -| 2 | title | max:120 | Title is too long | -| 3 | slug | required | Slug is required | -| 4 | slug | max:80 | Slug is too long | -| 5 | summary | max:500 | Summary is too long | -| 6 | body | max:8000 | Body is too long | diff --git a/examples/web-site/index.mq.md b/examples/web-site/index.mq.md deleted file mode 100755 index 57d1f25..0000000 --- a/examples/web-site/index.mq.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Marqdo Web Site -import: - layout: components/index.mq.md - intro: components/intro.mq.md - articles: components/articles.mq.md - database: db/index.mq.md - forms: forms.mq.md - theme: styles/index.mq.md - web: ext/web/web.mq.md - form: ext/data/form.mq.md - auth: ext/security/auth.mq.md - fs: lib/fs.mq.md - table: lib/table.mq.md ---- - -This entry is the executable site handbook. Follow components/index for public and administration geometry, then Markdown leaves, current article resources, the form and database. Five declared Documents retain Home, About, New, Admin and slug detail. Session navigation and server access policy remain separate; the custom desk does not enable the unrelated native administration landing page. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Public frame containing the readable introduction and current article cards | - -Startup assembly reads terminal Markdown and constructs a typed query, without querying or initializing a database. The retained application resource supplies current articles at request time. Shared layout preserves navigation, side rail, footer, SEO, fonts and the compiled literary theme. Follow each imported responsibility rather than rebuilding the complete page here. - -We **introduction = [Read the terminal home introduction](intro.nodes(name="home"))** and **cards = [Describe the current article cards](articles.cards())** and **body = [Keep the introduction before the records](table.concat(a=`introduction`, b=`cards`))**. -Return *[Place home inside the shared public frame](layout.frame(body=`body`, homepage=True))*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-site" | Explicit site discovery directory from the checkout | -| port | number | 18081 | Loopback demonstration port | -| url | any | None | None uses retained site-root SQLite; tests supply an owned URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking listener after real data, form, authentication and desk policy bindings | - -Use `root`="examples/web-site", `port`=18081 and `url`=None from the checkout with --fs-root examples/web-site and plugin,fs.write,network.write. Database initialization preserves existing rows and seeds only an empty table. The original declaration leaves remain unchanged; styles/index projects their selectors onto the recursive View layout and restores the named style properties previously attached by removed compose APIs. - -Theme output is explicitly generated under public/generated before discovery. Preparation reads declared Documents but opens no listener. Mount the same public article form used by New and the desk, attach local fixture authentication, and protect the actual /admin path before listening. Keep every returned application. The admin/demo credentials are local demonstration data; replace the user store and network policy for a real deployment. Shutdown belongs to the supervising caller, not a hidden background process. - -We **store = [Initialize the retained article database](database.open(url=`url`))** and **css = [Compile the actual View theme projection](theme.css())** and **[Create only the explicit generated resource directory](fs.make_dirs(path="public/generated"))** and **[Write the compiled theme through native IO](fs.atomic_write(path="public/generated/theme.css", text=`css`))**. -We **app = [Discover the five declared site Documents](web.prepare(root=`root`, host="127.0.0.1", port=`port`, db=`store`, static_dir="public"))** and **article = [Construct one shared server-validation resource](forms.article())** and **app = [Mount the public article submission explicitly](form.mount(app=`app`, id="article", form=`article`))**. - -`users` = - -| @ | username | password | role | -|---|---|---|---| -| 1 | admin | demo | admin | - -We **app = [Attach native login sessions](auth.attach(app=`app`, users=`users`, login_path="/login", login_redirect="/admin", logout_redirect="/"))** and **app = [Protect direct requests to the custom desk](auth.gate(app=`app`, path="/admin", roles="admin", match="prefix", on_deny="redirect", exclude="/login"))**. -Return *[Listen after actual resources and policy are ready](web.listen(app=`app`))*. diff --git a/examples/web-site/pages/about.mq.md b/examples/web-site/pages/about.mq.md deleted file mode 100755 index a28a170..0000000 --- a/examples/web-site/pages/about.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /about -title: About · Marqdo Web -import: - layout: ../components/index.mq.md - intro: ../components/intro.mq.md - articles: ../components/articles.mq.md - component: ext/web/component/index.mq.md - form: ext/data/form.mq.md - table: lib/table.mq.md ---- - -This Document explicitly declares /about. Its introduction ends in a Markdown leaf and its frame is shared. Request resources retain their own data or submission responsibilities. No startup page function initializes the database or starts another listener. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Page-specific content and request resources within the shared frame | - -Assembly reads Markdown with fs.read and creates pure descriptors. This explanation page requires no database query or form reference. Follow the layout imports to change one region without copying a page shell. - -Page structure stays stable while request-dependent resources observe current data and identity. A missing required resource remains a diagnostic rather than a fake successful response. - -We **body = [Read this page's terminal introduction](intro.nodes(name="about"))**. -Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=False))*. diff --git a/examples/web-site/pages/desk.mq.md b/examples/web-site/pages/desk.mq.md deleted file mode 100755 index 3f812dd..0000000 --- a/examples/web-site/pages/desk.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /admin -title: Admin · Marqdo Web -import: - layout: ../components/index.mq.md - intro: ../components/intro.mq.md - articles: ../components/articles.mq.md - component: ext/web/component/index.mq.md - form: ext/data/form.mq.md - table: lib/table.mq.md ---- - -This Document explicitly declares /admin. Its introduction ends in a Markdown leaf and its frame is shared. The serving entry enforces an actual admin role gate before the desk renders. No startup page function initializes the database or starts another listener. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Page-specific content and request resources within the shared frame | - -Assembly reads Markdown with fs.read and creates pure descriptors. The server resolves the mounted form using actual session CSRF and return context. It does not embed a stale startup token or a separate copy of validation rules. - -The desk keeps its own navigation and footer and has no public side rail. Its form intentionally shares the public article submission endpoint; gating presentation alone would not make that endpoint private, and the example does not claim otherwise. - -We **body = [Read this page's terminal introduction](intro.nodes(name="desk"))**. -We **selected = [Reference the same explicitly mounted article form](form.reference(id="article"))** and **controls = [Retain current request CSRF and validation context](component.resource(value=`selected`, slot="article-form"))** and **body = [Keep instructions before the actual form](table.concat(a=`body`, b=`controls`))**. -We **records = [Describe the same current article list](articles.cards())** and **body = [Retain the actual record resource](table.concat(a=`body`, b=`records`))**. -Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=True))*. diff --git a/examples/web-site/pages/new.mq.md b/examples/web-site/pages/new.mq.md deleted file mode 100755 index 0d0aa6e..0000000 --- a/examples/web-site/pages/new.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /new -title: New article · Marqdo Web -import: - layout: ../components/index.mq.md - intro: ../components/intro.mq.md - articles: ../components/articles.mq.md - component: ext/web/component/index.mq.md - form: ext/data/form.mq.md - table: lib/table.mq.md ---- - -This Document explicitly declares /new. Its introduction ends in a Markdown leaf and its frame is shared. Request resources retain their own data or submission responsibilities. No startup page function initializes the database or starts another listener. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Page-specific content and request resources within the shared frame | - -Assembly reads Markdown with fs.read and creates pure descriptors. The server resolves the mounted form using actual session CSRF and return context. It does not embed a stale startup token or a separate copy of validation rules. - -Page structure stays stable while request-dependent resources observe current data and identity. A missing required resource remains a diagnostic rather than a fake successful response. - -We **body = [Read this page's terminal introduction](intro.nodes(name="new"))**. -We **selected = [Reference the same explicitly mounted article form](form.reference(id="article"))** and **controls = [Retain current request CSRF and validation context](component.resource(value=`selected`, slot="article-form"))** and **body = [Keep instructions before the actual form](table.concat(a=`body`, b=`controls`))**. -Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=False))*. diff --git a/examples/web-site/pages/post.mq.md b/examples/web-site/pages/post.mq.md deleted file mode 100755 index 2722abf..0000000 --- a/examples/web-site/pages/post.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: /post/{slug} -title: Article · Marqdo Web -import: - layout: ../components/index.mq.md - intro: ../components/intro.mq.md - articles: ../components/articles.mq.md - component: ext/web/component/index.mq.md - form: ext/data/form.mq.md - table: lib/table.mq.md ---- - -This Document explicitly declares /post/{slug}. Its introduction ends in a Markdown leaf and its frame is shared. Request resources retain their own data or submission responsibilities. No startup page function initializes the database or starts another listener. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Page-specific content and request resources within the shared frame | - -Assembly reads Markdown with fs.read and creates pure descriptors. The actual path capture selects the current database record at request time; full Markdown body is separate from list summary, and query strings cannot replace the route slug. - -Page structure stays stable while request-dependent resources observe current data and identity. A missing required resource remains a diagnostic rather than a fake successful response. - -We **body = [Read this page's terminal introduction](intro.nodes(name="post"))**. -We **records = [Describe the current full-body slug match](articles.detail())** and **body = [Retain the actual record resource](table.concat(a=`body`, b=`records`))**. -Return *[Place the page in its selected recursive frame](layout.frame(body=`body`, management=False))*. diff --git a/examples/web-site/styles/index.mq.md b/examples/web-site/styles/index.mq.md deleted file mode 100755 index b6cf63e..0000000 --- a/examples/web-site/styles/index.mq.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -markup: occlusion -title: Literary theme entry for recursive View Documents -import: - document: lib/document.mq.md - web: ext/web/web.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -Read this entry before changing presentation. shell.tables.md retains every original declaration and shell.mq.md can still compile the original CSS. This entry projects only selectors onto the explicit View tree, restores the named property tables formerly attached by compose, and adds the bounded wrapper geometry in view.tables.md. Colors, property values, media conditions, particles and keyframe bodies remain the original data. - -## _selector - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| selector | text | required | One original author-controlled selector | -| mappings | list | required | Explicit old/new structural addresses read from view.tables.md | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Equivalent selector scoped to the explicit recursive site frame | - -Use `selector` and `mappings` from the actual retained theme and migration leaf. The old body-level sidebar and desk classes now belong to site-layout, while the main region is a section. The mappings preserve Markdown's actual heading, category, badge list and reading steps rather than restoring a private intro-binding dialect. - -Global document backgrounds, root tokens, selection styling, resets and keyframes stay global. Local selectors gain site scope so basic View defaults cannot override the deliberate theme. This is the fixed migration of this known site tree, not a generic CSS parser or visitor-controlled rewrite. The caller reads mappings once per area and passes those rows here, keeping this helper pure and avoiding repeated filesystem reads. - -- [Apply this site's explicit structural address mappings](for mappings as mapping) - We **selector = [Replace only the known selector address](text.replace(text=`selector`, old=access(mapping, "old"), new=access(mapping, "new")))**. -1. `selector` == "*" or `selector` == "::selection" or text.starts_with(text=`selector`, prefix="body") or text.starts_with(text=`selector`, prefix="html") or text.starts_with(text=`selector`, prefix=":root") or text.starts_with(text=`selector`, prefix="@") - Return *selector* because document-level rules and keyframes keep their existing scope. -1. text.starts_with(text=`selector`, prefix=".site-layout") - Return *[Scope the layout-state selector once](".mq-document " + selector)*. -Return *[Keep region selectors within this site's own frame](".mq-document .site-layout " + selector)*. - - -## _table - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Original vars, motion, layout, responsive, chrome or widgets section | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Original declaration rows with only their selector field projected | - -Use `name` with fs.read under the site root. Native Markdown reading preserves the original table and typed cells; from_columns converts its aligned columns to row records. Every row keeps the same property, value, optional media and original position. Only selector changes, and immutable updates preserve the retained source table. - -This function does not compile or write CSS. Keeping the projected rows callable makes migration evidence inspectable: compare them to the original native table, including keyframe values and media, before looking at browser output. A missing section, ragged column or unsupported literal remains a real diagnostic rather than silently dropping a style. The mapping applies to this known site tree, not arbitrary CSS supplied by a visitor. - -We **mappings = [Read the fixed structural migration table](document.read_table(path="styles/view.tables.md", title="selectors"))**. -We **columns = [Read the unchanged declaration leaf](document.read_table(path="styles/shell.tables.md", title=`name`))** and **rows = [Keep each original declaration as a record](table.from_columns(columns=`columns`))** and **projected = [Start the selector projection](table.empty_list())**. -- [Retain every declaration in its original position](for rows as row) - We **selector = [Project only this row's structural address](_selector(selector=access(row, "selector"), mappings=`mappings`))** and **record = [Keep every other declaration field unchanged](table.put(in=`row`, at="selector", value=`selector`))** and **projected = [Retain this original property and value](table.append(list=`projected`, item=`record`))**. -Return *projected* for actual compilation or independent comparison. - -## _property - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Original named property/value section | -| selector | text | required | Known semantic target in the new View tree, without leading dot | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Compiled original properties at their explicit new target | - -Use `name` and `selector` with fs.read and plugin. Removed compose operations used to attach these named properties to generated fields. The same declarations now target the native navigation, side/footer, current card classes and terminal Markdown elements. Their values do not change, and they are not inferred from user content. - -The selector is authored by the theme entry and begins with mq-document so the native style compiler supplies its leading class dot. The explicit target makes old property tables useful without restoring an obsolete page-binding dialect. Compilation returns text only; the serving workflow owns the selected generated path and native write. - -We **properties = [Read the original named property declaration](document.read_table(path="styles/shell.tables.md", title=`name`))**. -Return *[Compile the known semantic target](web.make_style(name=`selector`, table=`properties`))*. - -## css - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Full View theme with original values, explicit selector projection and wrapper geometry | - -Call with fs.read and plugin on the selected site root. Tokens and keyframes keep their original order, followed by layout, responsive, chrome and widget rules. Named property declarations restore the typography and region surfaces that the old compose calls attached separately. The generated CSS contains no replacement palette or abbreviated theme. - -The final geometry table only adapts the existing runtime wrappers: it removes the basic preview width/font defaults, lets native navigation resources participate in the shared grid, and preserves the explicit sidebar/desk class relationship. Markdown feature bullets become the original flex badge group, and the first explanatory paragraph uses the original lede properties. This keeps the content leaf readable without a hidden HTML template. - -Compilation neither writes the stylesheet nor claims browser acceptance. The serving workflow writes the result once before discovery. Verify the real computed colors, type sizes, wide sidebar, narrow stacked order, current cards and gated desk. If a selector no longer reaches its intended node, repair that mapping rather than deleting the original visual capability. - -We **areas = [Read the preserved theme area order](document.read_table(path="styles/view.tables.md", title="areas"))**. - -We **parts = [Start the actual ordered theme](table.empty_list())**. -- [Compile every original theme area](for areas as name) - We **rows = [Retain all original values and media](_table(name=`name`))** and **compiled = [Compile the actual projected declarations](web.make_style(name=`name`, table=`rows`))** and **parts = [Keep the original cascade order](table.append(list=`parts`, item=`compiled`))**. - -We **properties = [Read the actual named-property targets](document.read_table(path="styles/view.tables.md", title="properties"))**. - -- [Restore each originally bound property group](for properties as property) - We **compiled = [Compile its explicit semantic target](_property(name=access(property, "name"), selector=access(property, "selector")))** and **parts = [Retain that real property group](table.append(list=`parts`, item=`compiled`))**. -We **geometry = [Read the bounded View-wrapper adaptation](document.read_table(path="styles/view.tables.md", title="geometry"))** and **compiled = [Compile native geometry adaptation](web.make_style(name="view", table=`geometry`))** and **parts = [Finish with the explicit wrapper rules](table.append(list=`parts`, item=`compiled`))**. -Return *[Keep actual compiled sections in order](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site/styles/shell.mq.md b/examples/web-site/styles/shell.mq.md deleted file mode 100755 index 06e7d72..0000000 --- a/examples/web-site/styles/shell.mq.md +++ /dev/null @@ -1,277 +0,0 @@ ---- -markup: occlusion -title: Retained literary theme declarations -import: - document: lib/document.mq.md - web: ext/web/web.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -This file retains original declaration readers and original CSS compilation for migration comparison. The current site uses styles/index.mq.md for the actual View projection. Do not mistake an unchanged original hash for proof that new selectors reach their intended nodes. Each literal section remains independently callable. - -## vars - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Root palette, typefaces, spacing and elevation tokens. - -Compile these declarations before rules that reference their custom properties. The selection-color rows remain global alongside :root; neither the View migration nor a caller should scope those tokens inside one card. Editing a value changes the shared theme, so compare real compiled CSS and browser colors rather than renaming a property locally. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="vars"))*. - -## motion - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Original entrance, floating, particle and glow keyframes. - -Keyframe selectors and their property values remain global and in their original order. Animation timing belongs to the consuming rule. Reading this data does not schedule an animation; the browser applies the compiled stylesheet. The View projection must not prefix these addresses with a component class. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="motion"))*. - -## layout - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Document background, typography and original region-grid declarations. - -The original body layout classes describe the old page shell. Current View use projects those known addresses to the explicit site-layout region through styles/index; their property values remain unchanged. Keep document-level backgrounds and particle layers global, and compare actual wide/narrow geometry after any edit. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="layout"))*. - -## responsive - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Original media-conditioned layout and reduced-motion rows. - -These rows retain media text as a separate column. Width conditions collapse the public grid and change padding; prefers-reduced-motion disables selected animation without deleting its keyframes. Preserve row ordering and media alongside the value, rather than checking only that a selector name still appears in CSS. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="responsive"))*. - -## topnav - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value declarations for the top navigation surface. - -The original sticky positioning, gradient, blur, spacing and border are still applied to the native topnav class. Links and their current-session conditions belong to the navigation resource. A property table cannot authenticate a visitor or make a route exist, and compiling it does not mount a stylesheet. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="topnav"))*. - -## side_panel - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value declarations for the public side rail. - -The side rail's background, padding and separator distinguish task links from article content. Its external grid position belongs to the parent frame, and the desk intentionally omits it. Keep this visual responsibility separate from the link table and from the native session policy. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="side_panel"))*. - -## footer - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value declarations for the closing region. - -These values retain the original footer color, type size, spacing, border and background. The Markdown footer owns actual destinations; this table neither creates links nor starts logout. The same surface properties can style public and desk footers while their terminal content stays separate. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="footer"))*. - -## card_title - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value typography for article-card headings. - -The current-query renderer escapes article titles and retains its native h2 structure. The View theme targets that structure with these original properties, rather than returning to front/back page bindings. This reader does not query articles, truncate titles or modify their stored text. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="card_title"))*. - -## card_body - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value typography for card summaries. - -Summary data belongs to the current article query, and full Markdown body remains reserved for detail. These properties affect only appearance; they do not choose or replace content. After changing the selector target, verify that both escaped summaries and full article bodies keep their separate behavior. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="card_body"))*. - -## chrome - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Original introduction panels, badge container, reading steps and full-article rules. - -Current introductions are terminal Markdown, so the View mapping addresses real headings, bullets and ordered lists. Article selectors continue to match the native detail renderer. Keep those mappings explicit and retain the original values; do not hide layout inside authored HTML to recover an old selector. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="chrome"))*. - -## kicker - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value typography for the introduction category. - -The original letter spacing, color, small type and floating animation target the Markdown blockquote used for the category. Its content remains an ordinary readable line in the leaf. Compiling these properties does not create that content or make the browser fetch a font. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="kicker"))*. - -## intro_title - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value typography for the primary introduction heading. - -These declarations retain the display font, responsive size, gradient text and glow animation. The View theme applies them to the actual Markdown h1, avoiding an extra heading-size multiplier on a wrapper. Browser validation checks the computed font family and size; reading this table alone cannot prove rendering. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="intro_title"))*. - -## lede - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value typography for supporting introduction prose. - -The original width, line height, color, spacing and typeface target the leaf's explanatory paragraph. It remains separate from claim bullets and numbered steps. Keep the selector on the real paragraph rather than styling a wrapper and relying on browser default margins to approximate the old appearance. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="lede"))*. - -## claim - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Named property/value declarations for each short feature badge. - -The Markdown bullet list is the original flex badge container, while each item receives these original inline badge properties. The container's gap and wrapping belong to the chrome section. This distinction preserves both readable list content and the actual visual grouping without another binding-table language. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="claim"))*. - -## step - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Original margin declaration for one guided-reading step. - -This section has a single property row, so its native result contains scalar cells rather than aligned lists. The same style compiler accepts that shape. The ordered Markdown list owns step numbering and links; this value only supplies the original per-item spacing and does not reorder the reading sequence. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="step"))*. - -## widgets - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Original selector/property/value and optional media table, retaining column or single-row scalar shape | - -Original card, form, flash and administration state declarations. - -Hover and focus rules, field widths, action rows and desk-specific styles remain in their original order. The native form resource owns validation and submission. Theme projection changes only structural addresses; a visual form error is not proof that a server rejected data, so keep real failed and successful submissions in acceptance. - -Grant fs.read on the site root. The exact section must be unique; missing or unsupported content remains a native diagnostic. The result is data, not a written stylesheet, running animation or business query. - -Return *[Read this section's actual original literal table](document.read_table(path="styles/shell.tables.md", title="widgets"))*. - - -## _compile - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Exact original section in shell.tables.md | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | One theme section compiled at its original selectors | - -Use `name` with fs.read and plugin on the site root. Native reading preserves original values and geometry; the style compiler handles selectors, media and keyframes. This retained helper intentionally keeps old-shell addresses for migration comparison. Current serving uses styles/index for explicit View targets. A missing section remains diagnostic, and returned text neither writes a file nor proves the new structure is styled. - -We **declarations = [Read this section's actual original declarations](document.read_table(path="styles/shell.tables.md", title=`name`))**. -Return *[Compile original addresses for retained comparison](web.make_style(name=`name`, table=`declarations`))*. - -## css - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Baseline CSS preserving the six original areas and cascade | - -Grant fs.read and plugin on the site root. Compile tokens, keyframes, layout, responsive, chrome and widgets in their original order and concatenate them exactly as before. Named properties remain independently readable but are not added to this baseline, which would change its original cascade; the View entry restores them at actual semantic targets. - -The current site loads styles/index output rather than this old-shell baseline. Equal hashes prove retained compilation, not selector reach, font delivery or mobile geometry. Pair verify's actual row comparison with browser acceptance, and let the serving workflow explicitly write the actual projected theme. - -`names` = - -| name | -|---| -| vars | -| motion | -| layout | -| responsive | -| chrome | -| widgets | - -We **parts = [Start the ordered compiled sections](table.empty_list())**. -- [Compile each area in the declared cascade order](for names as name) - We **css = [Compile the selected theme area](_compile(name=`name`))** and **parts = [Preserve its original position](table.append(list=`parts`, item=`css`))**. -Return *[Join the compiled sections without changing separators](text.str_join(xs=`parts`, sep=""))*. diff --git a/examples/web-site/styles/shell.tables.md b/examples/web-site/styles/shell.tables.md deleted file mode 100755 index 98fa364..0000000 --- a/examples/web-site/styles/shell.tables.md +++ /dev/null @@ -1,602 +0,0 @@ -# Theme declarations - -Literal theme declarations. Callable use and CSS assembly are documented next to this file in shell.mq.md. Each section preserves one native table, including its column names and literal types. - -## vars - -Palette, typefaces, spacing and elevation tokens used by every region. - -| selector | property | value | -|----------|----------|-------| -| :root | --ink | #0a0809 | -| :root | --ink-lift | #141012 | -| :root | --wine | #6b1e3a | -| :root | --wine-soft | rgba(107,30,58,0.35) | -| :root | --gold | #d4af37 | -| :root | --gold-dim | rgba(212,175,55,0.45) | -| :root | --gold-soft | rgba(212,175,55,0.12) | -| :root | --paper | rgba(255,248,240,0.92) | -| :root | --paper-dim | rgba(255,248,240,0.72) | -| :root | --paper-faint | rgba(255,248,240,0.48) | -| :root | --glass | rgba(20,12,18,0.72) | -| :root | --glass-strong | rgba(20,12,18,0.88) | -| :root | --border | rgba(212,175,55,0.22) | -| :root | --border-soft | rgba(212,175,55,0.12) | -| :root | --danger | #e8a0a8 | -| :root | --radius | 4px | -| :root | --radius-sm | 2px | -| :root | --space-2 | 8px | -| :root | --space-3 | 12px | -| :root | --space-4 | 16px | -| :root | --space-5 | 20px | -| :root | --space-6 | 24px | -| :root | --space-8 | 32px | -| :root | --text | 16px | -| :root | --leading | "1.75" | -| :root | --shadow | "0 24px 80px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.06)" | -| :root | --shadow-card | "0 12px 40px rgba(107,30,58,.35)" | -| :root | --ring | "0 0 0 2px rgba(212,175,55,.35)" | -| :root | --serif | "'Noto Serif SC', 'Source Serif 4', Georgia, serif" | -| :root | --sans | "'Noto Sans SC', 'IBM Plex Sans', system-ui, sans-serif" | -| :root | --display | "'Great Vibes', 'Allura', cursive" | -| :root | --mono | "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" | -| ::selection | background | rgba(212,175,55,0.35) | -| ::selection | color | var(--paper) | - -## motion - -Entrance, floating, particle and glow keyframes; animation timings remain in consuming selectors. - -| selector | property | value | -|----------|----------|-------| -| @keyframes rise 0% | opacity | "0" | -| @keyframes rise 0% | transform | translateY(14px) | -| @keyframes rise 100% | opacity | "1" | -| @keyframes rise 100% | transform | translateY(0) | -| @keyframes float 0% | transform | translateY(0) | -| @keyframes float 0% | opacity | "0.7" | -| @keyframes float 50% | transform | translateY(6px) | -| @keyframes float 50% | opacity | "1" | -| @keyframes float 100% | transform | translateY(0) | -| @keyframes float 100% | opacity | "0.7" | -| @keyframes goldPulse 0% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes goldPulse 50% | text-shadow | "0 0 48px rgba(212,175,55,.45)" | -| @keyframes goldPulse 100% | text-shadow | "0 0 24px rgba(212,175,55,.2)" | -| @keyframes particleDrift 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift 50% | transform | translate3d(-2.5vw, 1.5vh, 0) | -| @keyframes particleDrift 100% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 0% | transform | translate3d(0,0,0) | -| @keyframes particleDrift2 50% | transform | translate3d(2vw, -2vh, 0) | -| @keyframes particleDrift2 100% | transform | translate3d(0,0,0) | -| @keyframes nebulaPulse 0% | opacity | "0.55" | -| @keyframes nebulaPulse 50% | opacity | "0.9" | -| @keyframes nebulaPulse 100% | opacity | "0.55" | - -## layout - -Page grid, background, typography, navigation and main content rules. - -| selector | property | value | -|----------|----------|-------| -| * | box-sizing | border-box | -| html | scroll-behavior | smooth | -| html | -webkit-text-size-adjust | 100% | -| body | margin | "0" | -| body | min-height | 100vh | -| body | font-family | var(--sans) | -| body | font-weight | "400" | -| body | font-size | var(--text) | -| body | line-height | var(--leading) | -| body | color | var(--paper) | -| body | background | var(--ink) | -| body | background-image | "radial-gradient(ellipse 90% 55% at 50% -15%, rgba(107,30,58,.5), transparent 58%), radial-gradient(ellipse 55% 45% at 92% 75%, rgba(212,175,55,.14), transparent 55%), radial-gradient(ellipse 40% 35% at 8% 70%, rgba(107,30,58,.22), transparent 60%), linear-gradient(180deg, #0a0809 0%, #120c10 45%, #0a0809 100%)" | -| body | background-attachment | fixed | -| body | display | grid | -| body | grid-template-rows | "auto 1fr auto" | -| body | -webkit-font-smoothing | antialiased | -| body | position | relative | -| body | overflow-x | hidden | -| body::before | content | '""' | -| body::before | position | fixed | -| body::before | inset | "0" | -| body::before | z-index | "1" | -| body::before | pointer-events | none | -| body::before | opacity | "0.1" | -| body::before | background-image | "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")" | -| html::before | content | '""' | -| html::before | position | fixed | -| html::before | inset | "0" | -| html::before | z-index | "0" | -| html::before | pointer-events | none | -| html::before | background-image | "radial-gradient(ellipse 50% 40% at 15% 30%, rgba(107,30,58,.35), transparent 70%), radial-gradient(ellipse 45% 35% at 85% 60%, rgba(212,175,55,.12), transparent 65%), radial-gradient(ellipse 40% 30% at 50% 90%, rgba(107,30,58,.25), transparent 70%)" | -| html::before | animation | "nebulaPulse 12s ease-in-out infinite" | -| body::after | content | '""' | -| body::after | position | fixed | -| body::after | top | "0" | -| body::after | left | "0" | -| body::after | width | "2px" | -| body::after | height | "2px" | -| body::after | z-index | "2" | -| body::after | pointer-events | none | -| body::after | border-radius | 50% | -| body::after | background | transparent | -| body::after | box-shadow | "82vw 15vh 0px 0px rgba(212,175,55,0.55),29vw 18vh 0px 1px rgba(212,175,55,0.25),95vw 70vh 1px 0px rgba(212,175,55,0.55),4vw 12vh 0px 1px rgba(212,175,55,0.35),78vw 4vh 0px 1px rgba(245,230,200,0.5),84vw 90vh 1px 0px rgba(245,230,200,0.5),58vw 76vh 0px 0px rgba(255,248,240,0.4),90vw 55vh 0px 0px rgba(255,248,240,0.4),28vw 98vh 0px 0px rgba(255,248,240,0.4),49vw 13vh 0px 1px rgba(255,248,240,0.4),34vw 6vh 1px 1px rgba(212,175,55,0.25),16vw 49vh 0px 1px rgba(212,175,55,0.55),80vw 47vh 0px 1px rgba(245,230,200,0.5),9vw 6vh 0px 0px rgba(212,175,55,0.25),11vw 30vh 1px 0px rgba(212,175,55,0.55),59vw 82vh 0px 0px rgba(255,248,240,0.4),46vw 27vh 0px 1px rgba(212,175,55,0.25),88vw 83vh 0px 1px rgba(212,175,55,0.55),94vw 32vh 1px 0px rgba(212,175,55,0.35),35vw 82vh 0px 1px rgba(212,175,55,0.25),42vw 99vh 0px 0px rgba(212,175,55,0.55),41vw 52vh 0px 0px rgba(255,248,240,0.4),73vw 92vh 0px 1px rgba(255,248,240,0.4),64vw 51vh 1px 0px rgba(212,175,55,0.25),34vw 18vh 0px 1px rgba(212,175,55,0.35),75vw 55vh 1px 0px rgba(245,230,200,0.5),29vw 18vh 1px 0px rgba(245,230,200,0.5),97vw 7vh 0px 1px rgba(212,175,55,0.55),21vw 88vh 0px 0px rgba(107,30,58,0.45),49vw 77vh 0px 1px rgba(107,30,58,0.45),2vw 88vh 0px 1px rgba(212,175,55,0.25),69vw 97vh 0px 0px rgba(255,248,240,0.4),38vw 56vh 1px 0px rgba(212,175,55,0.35),93vw 93vh 0px 1px rgba(255,248,240,0.4),14vw 81vh 0px 0px rgba(255,248,240,0.4),48vw 98vh 0px 1px rgba(212,175,55,0.35),42vw 63vh 0px 0px rgba(212,175,55,0.55),40vw 31vh 0px 1px rgba(212,175,55,0.55),11vw 11vh 1px 0px rgba(212,175,55,0.25),98vw 69vh 0px 1px rgba(212,175,55,0.35),61vw 71vh 0px 1px rgba(212,175,55,0.35),78vw 55vh 0px 1px rgba(212,175,55,0.35),40vw 52vh 0px 0px rgba(212,175,55,0.25),67vw 58vh 0px 0px rgba(212,175,55,0.55),9vw 44vh 0px 1px rgba(212,175,55,0.55),29vw 1vh 0px 0px rgba(212,175,55,0.55),9vw 5vh 0px 1px rgba(255,248,240,0.4),31vw 36vh 1px 0px rgba(212,175,55,0.25),70vw 17vh 1px 0px rgba(212,175,55,0.25),61vw 53vh 0px 0px rgba(212,175,55,0.35),85vw 56vh 1px 0px rgba(255,248,240,0.4),60vw 94vh 0px 0px rgba(212,175,55,0.55),52vw 94vh 0px 0px rgba(255,248,240,0.4),25vw 25vh 1px 0px rgba(245,230,200,0.5),55vw 24vh 1px 0px rgba(255,248,240,0.4),10vw 57vh 0px 0px rgba(245,230,200,0.5),84vw 70vh 0px 0px rgba(212,175,55,0.55),22vw 53vh 1px 0px rgba(107,30,58,0.45),52vw 8vh 1px 0px rgba(212,175,55,0.35),50vw 34vh 0px 0px rgba(107,30,58,0.45),90vw 94vh 1px 0px rgba(245,230,200,0.5),25vw 38vh 0px 1px rgba(212,175,55,0.35),95vw 70vh 0px 0px rgba(212,175,55,0.55),7vw 75vh 0px 0px rgba(107,30,58,0.45),66vw 11vh 0px 1px rgba(212,175,55,0.35),9vw 87vh 1px 0px rgba(212,175,55,0.35),73vw 32vh 0px 1px rgba(245,230,200,0.5),11vw 54vh 0px 0px rgba(212,175,55,0.25),27vw 86vh 0px 0px rgba(212,175,55,0.25),34vw 51vh 0px 0px rgba(212,175,55,0.35),41vw 97vh 0px 0px rgba(212,175,55,0.55),80vw 73vh 0px 1px rgba(212,175,55,0.55)" | -| body::after | animation | "particleDrift 48s ease-in-out infinite" | -| html::after | content | '""' | -| html::after | position | fixed | -| html::after | top | "0" | -| html::after | left | "0" | -| html::after | width | "1px" | -| html::after | height | "1px" | -| html::after | z-index | "2" | -| html::after | pointer-events | none | -| html::after | border-radius | 50% | -| html::after | background | transparent | -| html::after | box-shadow | "28vw 65vh 0 0 rgba(255,248,240,0.25),17vw 45vh 0 0 rgba(212,175,55,0.3),32vw 48vh 0 0 rgba(255,248,240,0.25),21vw 57vh 0 0 rgba(107,30,58,0.3),91vw 39vh 0 0 rgba(107,30,58,0.3),84vw 68vh 0 0 rgba(212,175,55,0.3),86vw 71vh 0 0 rgba(255,248,240,0.25),85vw 14vh 0 0 rgba(212,175,55,0.3),34vw 15vh 0 0 rgba(212,175,55,0.3),96vw 71vh 0 0 rgba(212,175,55,0.3),35vw 37vh 0 0 rgba(107,30,58,0.3),27vw 92vh 0 0 rgba(255,248,240,0.25),27vw 88vh 0 0 rgba(107,30,58,0.3),34vw 65vh 0 0 rgba(255,248,240,0.25),33vw 7vh 0 0 rgba(212,175,55,0.3),82vw 55vh 0 0 rgba(255,248,240,0.25),6vw 1vh 0 0 rgba(255,248,240,0.25),99vw 17vh 0 0 rgba(107,30,58,0.3),34vw 21vh 0 0 rgba(107,30,58,0.3),57vw 71vh 0 0 rgba(107,30,58,0.3),55vw 72vh 0 0 rgba(212,175,55,0.3),15vw 10vh 0 0 rgba(107,30,58,0.3),20vw 70vh 0 0 rgba(212,175,55,0.3),48vw 75vh 0 0 rgba(107,30,58,0.3),19vw 56vh 0 0 rgba(212,175,55,0.3),6vw 40vh 0 0 rgba(255,248,240,0.25),6vw 46vh 0 0 rgba(212,175,55,0.3),88vw 32vh 0 0 rgba(107,30,58,0.3),14vw 46vh 0 0 rgba(107,30,58,0.3),53vw 80vh 0 0 rgba(107,30,58,0.3),20vw 31vh 0 0 rgba(212,175,55,0.3),23vw 53vh 0 0 rgba(212,175,55,0.3),23vw 95vh 0 0 rgba(255,248,240,0.25),53vw 86vh 0 0 rgba(107,30,58,0.3),32vw 35vh 0 0 rgba(212,175,55,0.3),90vw 14vh 0 0 rgba(255,248,240,0.25),5vw 61vh 0 0 rgba(212,175,55,0.3),26vw 59vh 0 0 rgba(255,248,240,0.25),40vw 30vh 0 0 rgba(212,175,55,0.3),4vw 85vh 0 0 rgba(212,175,55,0.3),52vw 43vh 0 0 rgba(255,248,240,0.25),9vw 99vh 0 0 rgba(255,248,240,0.25),45vw 83vh 0 0 rgba(107,30,58,0.3),52vw 87vh 0 0 rgba(107,30,58,0.3),43vw 4vh 0 0 rgba(212,175,55,0.3),34vw 23vh 0 0 rgba(107,30,58,0.3),34vw 5vh 0 0 rgba(212,175,55,0.3),77vw 56vh 0 0 rgba(255,248,240,0.25)" | -| html::after | animation | "particleDrift2 64s ease-in-out infinite" | -| body.has-sidebar | grid-template-columns | "14rem minmax(0, 1fr)" | -| body.has-sidebar | grid-template-areas | '"top top" "side main" "foot foot"' | -| body.no-sidebar | grid-template-areas | '"top" "main" "foot"' | -| body.layout-stacked | grid-template-areas | '"top" "main" "foot"' | -| body.is-desk | grid-template-areas | '"top" "main" "foot"' | -| header.topnav | grid-area | top | -| aside.side | grid-area | side | -| main.main | grid-area | main | -| footer.foot | grid-area | foot | -| header.topnav | position | relative | -| header.topnav | z-index | "20" | -| aside.side | position | relative | -| aside.side | z-index | "10" | -| main.main | position | relative | -| main.main | z-index | "10" | -| footer.foot | position | relative | -| footer.foot | z-index | "10" | -| main.main | width | "100%" | -| main.main | max-width | "min(78rem, 100%)" | -| main.main | padding | "var(--space-8) var(--space-6) 4rem" | -| main.main | animation | "rise .8s cubic-bezier(.22,1,.36,1) both" | -| a | color | var(--gold) | -| a | text-decoration | none | -| a | transition | color 0.25s ease | -| a:hover | color | #f5e6c8 | -| code | font-family | var(--mono) | -| code | font-size | "0.82em" | -| code | font-weight | "400" | -| code | background | rgba(0,0,0,0.35) | -| code | border | 1px solid var(--border-soft) | -| code | padding | "0.12em 0.45em" | -| code | border-radius | var(--radius-sm) | -| code | color | var(--gold) | - -## responsive - -Media conditions that collapse the side panel and card grid on small screens. - -| media | selector | property | value | -|-------|----------|----------|-------| -| (max-width: 860px) | body.has-sidebar | grid-template-columns | 1fr | -| (max-width: 860px) | body.has-sidebar | grid-template-areas | '"top" "main" "side" "foot"' | -| (max-width: 860px) | aside.side | border-right | "0" | -| (max-width: 860px) | aside.side | border-top | 1px solid var(--border-soft) | -| (max-width: 860px) | main.main | padding | "var(--space-6) var(--space-4) var(--space-8)" | -| (max-width: 860px) | .content.cards | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form form | grid-template-columns | 1fr | -| (max-width: 860px) | .site-form label:nth-child(1) | grid-column | "1 / -1" | -| (max-width: 860px) | .site-form label:nth-child(2) | grid-column | "1 / -1" | -| (max-width: 860px) | header.topnav | padding | "0.85rem var(--space-4)" | -| (max-width: 860px) | .intro_title | font-size | "2.4rem" | -| (prefers-reduced-motion: reduce) | main.main | animation | none | -| (prefers-reduced-motion: reduce) | .kicker | animation | none | -| (prefers-reduced-motion: reduce) | article.card | transition | none | -| (prefers-reduced-motion: reduce) | body::after | animation | none | -| (prefers-reduced-motion: reduce) | html::after | animation | none | -| (prefers-reduced-motion: reduce) | html::before | animation | none | - -## topnav - -Property/value style attached to the top navigation binding. - -| property | value | -|----------|-------| -| position | sticky | -| top | "0" | -| z-index | "40" | -| display | flex | -| align-items | center | -| justify-content | flex-start | -| gap | var(--space-4) | -| padding | "1rem var(--space-6)" | -| background | "linear-gradient(180deg, rgba(10,8,9,.92) 0%, rgba(10,8,9,.55) 70%, transparent 100%)" | -| backdrop-filter | blur(10px) | -| -webkit-backdrop-filter | blur(10px) | -| border-bottom | 1px solid var(--border-soft) | - -## side_panel - -Property/value style for the secondary navigation and explanatory panel. - -| property | value | -|----------|-------| -| background | "rgba(10,8,9,.55)" | -| padding | "var(--space-6) var(--space-4)" | -| border-right | 1px solid var(--border-soft) | - -## footer - -Property/value style for the closing navigation and attribution. - -| property | value | -|----------|-------| -| color | var(--paper-faint) | -| font-size | "0.8rem" | -| letter-spacing | "0.08em" | -| padding | "var(--space-5) var(--space-6)" | -| border-top | 1px solid var(--border-soft) | -| background | "rgba(10,8,9,.75)" | - -## card_title - -Property/value typography for a linked article title. - -| property | value | -|----------|-------| -| font-family | var(--serif) | -| font-size | "1.15rem" | -| font-weight | "600" | -| margin | "0 0 var(--space-2)" | -| color | var(--gold) | -| letter-spacing | "0.02em" | -| line-height | "1.35" | - -## card_body - -Property/value typography for an article's summary. - -| property | value | -|----------|-------| -| color | var(--paper-dim) | -| margin | "0" | -| line-height | "1.65" | -| font-size | "0.9rem" | -| font-weight | "400" | -| display | "-webkit-box" | -| -webkit-box-orient | vertical | -| -webkit-line-clamp | "3" | -| overflow | hidden | - -## chrome - -Grouped selectors for introduction panels, claims, reading steps and full article content. - -| selector | property | value | -|----------|----------|-------| -| .main-intro | background | var(--glass) | -| .main-intro | border | 1px solid var(--border) | -| .main-intro | border-radius | var(--radius) | -| .main-intro | padding | "2.25rem 1.75rem 1.85rem" | -| .main-intro | box-shadow | var(--shadow) | -| .main-intro | backdrop-filter | blur(16px) | -| .main-intro | -webkit-backdrop-filter | blur(16px) | -| .main-intro | margin-bottom | var(--space-8) | -| .main-intro > .claim | display | flex | -| .main-intro > .claim | flex-wrap | wrap | -| .main-intro > .claim | gap | var(--space-2) | -| .main-intro > .claim | margin | "0 0 var(--space-6)" | -| .main-intro > .steps | margin | "0" | -| .main-intro > .steps | padding | "var(--space-5) var(--space-5) var(--space-5) 1.5rem" | -| .main-intro > .steps | color | var(--paper-dim) | -| .main-intro > .steps | background | "rgba(0,0,0,.35)" | -| .main-intro > .steps | border | 1px solid var(--border-soft) | -| .main-intro > .steps | border-left | 2px solid var(--gold-dim) | -| .main-intro > .steps | border-radius | var(--radius) | -| .main-intro > .steps | font-size | "0.95rem" | -| .main-intro > .steps | letter-spacing | "0.02em" | -| .main-intro > .steps a | color | var(--gold) | -| .main-intro > .steps a | font-weight | "500" | -| .main-intro > .steps a:hover | color | #f5e6c8 | -| .article | background | var(--glass) | -| .article | border | 1px solid var(--border) | -| .article | border-radius | var(--radius) | -| .article | padding | "2rem 1.75rem" | -| .article | box-shadow | var(--shadow) | -| .article | backdrop-filter | blur(16px) | -| .article | -webkit-backdrop-filter | blur(16px) | -| .article-title | font-family | var(--serif) | -| .article-title | font-size | "clamp(1.75rem, 4vw, 2.35rem)" | -| .article-title | font-weight | "600" | -| .article-title | color | var(--gold) | -| .article-title | letter-spacing | "0.04em" | -| .article-title | margin | "0 0 var(--space-5)" | -| .article-title | line-height | "1.25" | -| .article-body | color | var(--paper-dim) | -| .article-body | font-family | var(--sans) | -| .article-body | font-size | "1.02rem" | -| .article-body | line-height | "1.85" | -| .article-body.md p | margin | "0 0 1.1rem" | -| .article-body.md a | color | var(--gold) | -| article.card | cursor | pointer | -| a.card-link | color | inherit | -| a.card-link | text-decoration | none | -| a.card-link:hover | color | inherit | - -## kicker - -Property/value typography for the small introductory category label. - -| property | value | -|----------|-------| -| letter-spacing | "0.32em" | -| text-transform | uppercase | -| font-size | "0.72rem" | -| color | var(--gold-dim) | -| margin | "0 0 var(--space-4)" | -| font-weight | "400" | -| font-family | var(--sans) | -| animation | "float 2.8s ease-in-out infinite" | - -## intro_title - -Property/value typography and responsive size for the main introduction heading. - -| property | value | -|----------|-------| -| font-family | var(--display) | -| font-size | "clamp(3rem, 10vw, 4.8rem)" | -| font-weight | "400" | -| line-height | "1.15" | -| letter-spacing | "0.04em" | -| margin | "0 0 var(--space-4)" | -| color | transparent | -| background | "linear-gradient(135deg, #f5e6c8 0%, var(--gold) 42%, var(--wine) 100%)" | -| -webkit-background-clip | text | -| background-clip | text | -| animation | "goldPulse 4.5s ease-in-out infinite" | - -## lede - -Property/value typography for the supporting introduction paragraph. - -| property | value | -|----------|-------| -| color | var(--paper-dim) | -| max-width | "34rem" | -| line-height | "1.85" | -| margin | "0 0 var(--space-5)" | -| font-size | "1.05rem" | -| letter-spacing | "0.02em" | -| font-weight | "400" | -| font-family | var(--sans) | - -## claim - -Property/value style used by the short feature claims. - -| property | value | -|----------|-------| -| display | inline-flex | -| align-items | center | -| padding | "0.2rem 0.65rem" | -| border-radius | var(--radius-sm) | -| background | var(--wine-soft) | -| color | #f0c9d4 | -| font-size | "0.68rem" | -| font-weight | "500" | -| letter-spacing | "0.14em" | -| border | 1px solid rgba(107,30,58,0.5) | - -## step - -Initial demonstration records in their original column-oriented shape; ids and stable slugs retain their meaning. - -| property | value | -|----------|-------| -| margin | "0.55rem 0" | - -## widgets - -Cards, forms, flash messages and administration controls, including hover and focus states. - -| selector | property | value | -|----------|----------|-------| -| ul.nav | display | flex | -| ul.nav | flex-wrap | wrap | -| ul.nav | align-items | center | -| ul.nav | gap | "0.35rem 1rem" | -| ul.nav | list-style | none | -| ul.nav | margin | "0" | -| ul.nav | padding | "0" | -| ul.nav a | display | inline-flex | -| ul.nav a | align-items | center | -| ul.nav a | text-decoration | none | -| ul.nav a | color | var(--paper-dim) | -| ul.nav a | padding | "0.35rem 0" | -| ul.nav a | border-radius | "0" | -| ul.nav a | font-weight | "400" | -| ul.nav a | font-size | "0.8rem" | -| ul.nav a | letter-spacing | "0.14em" | -| ul.nav a | transition | color 0.25s ease | -| ul.nav a:hover | background | transparent | -| ul.nav a:hover | color | var(--gold) | -| ul.nav a:hover | text-decoration | none | -| ul.nav a[href="/admin"] | color | var(--gold) | -| ul.nav a[href="/admin"] | letter-spacing | "0.18em" | -| ul.nav a[href="/admin"] | border-bottom | 1px solid var(--gold-dim) | -| ul.side-nav a[href="/admin"] | color | var(--gold) | -| body.is-desk header.topnav | border-bottom | 1px solid rgba(107,30,58,0.55) | -| body.is-desk header.topnav | box-shadow | "0 12px 40px rgba(107,30,58,.18)" | -| body.is-desk .main-intro | border-left | 3px solid var(--wine) | -| body.is-desk .site-form | border-color | rgba(107,30,58,0.45) | -| body.is-desk .site-form | box-shadow | "0 0 0 1px rgba(212,175,55,.12), 0 18px 48px rgba(0,0,0,.35)" | -| body.is-desk .content.cards | margin-top | var(--space-6) | -| ul.nav li:first-child a | font-family | var(--display) | -| ul.nav li:first-child a | font-weight | "400" | -| ul.nav li:first-child a | color | var(--gold) | -| ul.nav li:first-child a | font-size | "1.85rem" | -| ul.nav li:first-child a | letter-spacing | "0.06em" | -| ul.nav li:first-child a | padding | "0.1rem 0.2rem 0.1rem 0" | -| ul.nav li:first-child a:hover | background | transparent | -| ul.nav li:first-child a:hover | color | #f5e6c8 | -| .side-label | display | block | -| .side-label | font-size | "0" | -| .side-label | margin | "0 0 var(--space-4)" | -| .side-label::before | content | '"Path"' | -| .side-label::before | display | block | -| .side-label::before | font-size | "0.68rem" | -| .side-label::before | letter-spacing | "0.28em" | -| .side-label::before | text-transform | uppercase | -| .side-label::before | color | var(--gold-dim) | -| .side-label::before | font-weight | "400" | -| ul.side-nav | list-style | none | -| ul.side-nav | margin | "0" | -| ul.side-nav | padding | "0" | -| ul.side-nav | display | grid | -| ul.side-nav | gap | "2px" | -| ul.side-nav | border-left | 1px solid var(--border) | -| ul.side-nav | padding-left | "0.85rem" | -| ul.side-nav | margin-left | "0.25rem" | -| ul.side-nav a | display | block | -| ul.side-nav a | text-decoration | none | -| ul.side-nav a | color | var(--paper-dim) | -| ul.side-nav a | padding | "0.45rem 0.35rem" | -| ul.side-nav a | border-radius | "0" | -| ul.side-nav a | font-weight | "400" | -| ul.side-nav a | font-size | "0.88rem" | -| ul.side-nav a | letter-spacing | "0.06em" | -| ul.side-nav a | border | "0" | -| ul.side-nav a | position | relative | -| ul.side-nav a:hover | background | transparent | -| ul.side-nav a:hover | border-color | transparent | -| ul.side-nav a:hover | color | var(--gold) | -| ul.side-nav a:hover | text-decoration | none | -| ul.side-nav a:hover | box-shadow | none | -| ul.foot-nav | display | flex | -| ul.foot-nav | gap | var(--space-4) | -| ul.foot-nav | list-style | none | -| ul.foot-nav | margin | "0" | -| ul.foot-nav | padding | "0" | -| ul.foot-nav a | color | var(--paper-faint) | -| ul.foot-nav a | font-weight | "400" | -| ul.foot-nav a | letter-spacing | "0.1em" | -| ul.foot-nav a | font-size | "0.78rem" | -| ul.foot-nav a:hover | color | var(--gold) | -| .content.cards | display | grid | -| .content.cards | gap | var(--space-4) | -| .content.cards | margin-top | "0" | -| .content.cards | grid-template-columns | "repeat(auto-fill, minmax(16rem, 1fr))" | -| article.card | background | "rgba(0,0,0,.35)" | -| article.card | border | 1px solid var(--border-soft) | -| article.card | border-radius | var(--radius-sm) | -| article.card | padding | "1.35rem 1.15rem" | -| article.card | box-shadow | none | -| article.card | transition | "border-color .35s ease, box-shadow .35s ease, transform .35s ease" | -| article.card:hover | transform | "translateY(-3px)" | -| article.card:hover | box-shadow | var(--shadow-card) | -| article.card:hover | border-color | var(--gold-dim) | -| .site-form | background | var(--glass) | -| .site-form | border | 1px solid var(--border) | -| .site-form | border-radius | var(--radius) | -| .site-form | padding | "var(--space-6) var(--space-6) var(--space-7, 1.75rem)" | -| .site-form | margin | "0 0 var(--space-6)" | -| .site-form | max-width | "100%" | -| .site-form | width | "100%" | -| .site-form | box-shadow | var(--shadow) | -| .site-form | backdrop-filter | blur(16px) | -| .site-form | -webkit-backdrop-filter | blur(16px) | -| .site-form .meta | display | none | -| .site-form form | display | grid | -| .site-form form | grid-template-columns | "minmax(0, 1fr) minmax(0, 1fr)" | -| .site-form form | column-gap | var(--space-5) | -| .site-form form | row-gap | var(--space-5) | -| .site-form form | gap | var(--space-5) | -| .site-form form | margin | "0" | -| .site-form form | width | "100%" | -| .site-form form | max-width | "100%" | -| .site-form label | display | grid | -| .site-form label | gap | var(--space-2) | -| .site-form label | margin | "0" | -| .site-form label | min-width | "0" | -| .site-form label | font-weight | "400" | -| .site-form label | color | var(--gold) | -| .site-form label | font-size | "0.78rem" | -| .site-form label | letter-spacing | "0.16em" | -| .site-form label | text-transform | uppercase | -| .site-form label:nth-child(1) | grid-column | "1" | -| .site-form label:nth-child(2) | grid-column | "2" | -| .site-form label:nth-child(n+3) | grid-column | "1 / -1" | -| .site-form .actions | grid-column | "1 / -1" | -| .site-form input | -webkit-appearance | none | -| .site-form textarea | -webkit-appearance | none | -| .site-form input | appearance | none | -| .site-form textarea | appearance | none | -| .site-form input | box-sizing | border-box | -| .site-form textarea | box-sizing | border-box | -| .site-form input | display | block | -| .site-form textarea | display | block | -| .site-form input | width | "100%" | -| .site-form textarea | width | "100%" | -| .site-form input | height | "2.75rem" | -| .site-form textarea | min-height | "10rem" | -| .site-form label:nth-child(4) textarea | min-height | "14rem" | -| .site-form textarea | resize | vertical | -| .site-form input | padding | "0 0.9rem" | -| .site-form textarea | padding | "0.75rem 0.9rem" | -| .site-form input | border | 1px solid var(--border) | -| .site-form textarea | border | 1px solid var(--border) | -| .site-form input | border-radius | var(--radius-sm) | -| .site-form textarea | border-radius | var(--radius-sm) | -| .site-form input | background | "rgba(0,0,0,.4)" | -| .site-form textarea | background | "rgba(0,0,0,.4)" | -| .site-form input | color | var(--paper) | -| .site-form textarea | color | var(--paper) | -| .site-form input | font | inherit | -| .site-form textarea | font | inherit | -| .site-form input | font-size | "0.95rem" | -| .site-form textarea | font-size | "0.95rem" | -| .site-form input | line-height | "1.4" | -| .site-form textarea | line-height | "1.65" | -| .site-form input | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form textarea | transition | "border-color .2s ease, box-shadow .2s ease" | -| .site-form input:hover | border-color | var(--gold-dim) | -| .site-form textarea:hover | border-color | var(--gold-dim) | -| .site-form input:focus | outline | none | -| .site-form textarea:focus | outline | none | -| .site-form input:focus | border-color | var(--gold) | -| .site-form textarea:focus | border-color | var(--gold) | -| .site-form input:focus | box-shadow | var(--ring) | -| .site-form textarea:focus | box-shadow | var(--ring) | -| .site-form input[readonly] | background | "rgba(0,0,0,.25)" | -| .site-form input[readonly] | color | var(--paper-faint) | -| .site-form .err | color | var(--danger) | -| .site-form .err | font-size | "0.8rem" | -| .site-form .err | font-weight | "500" | -| .site-form .err | letter-spacing | "0.04em" | -| .site-form .actions | display | flex | -| .site-form .actions | align-items | center | -| .site-form .actions | gap | var(--space-4) | -| .site-form .actions | margin-top | var(--space-2) | -| .site-form .actions | flex-wrap | wrap | -| .site-form button | -webkit-appearance | none | -| .site-form button | appearance | none | -| .site-form button | height | "2.75rem" | -| .site-form button | padding | "0 1.35rem" | -| .site-form button | background | "linear-gradient(135deg, #f5e6c8, var(--gold))" | -| .site-form button | color | var(--ink) | -| .site-form button | border | "0" | -| .site-form button | border-radius | 999px | -| .site-form button | font-weight | "600" | -| .site-form button | font-size | "0.85rem" | -| .site-form button | letter-spacing | "0.12em" | -| .site-form button | cursor | pointer | -| .site-form button | box-shadow | "0 8px 28px rgba(212,175,55,.28)" | -| .site-form button | transition | "transform .2s ease, box-shadow .2s ease, filter .2s ease" | -| .site-form button:hover | filter | brightness(1.06) | -| .site-form button:hover | transform | "translateY(-1px)" | -| .site-form button:hover | box-shadow | "0 12px 36px rgba(212,175,55,.4)" | -| .site-form .actions a | color | var(--paper-faint) | -| .site-form .actions a | font-weight | "400" | -| .site-form .actions a | text-decoration | none | -| .site-form .actions a | font-size | "0.85rem" | -| .site-form .actions a | letter-spacing | "0.08em" | -| .site-form .actions a:hover | color | var(--gold) | -| .flash.err | color | var(--danger) | -| .flash.err | font-weight | "500" | diff --git a/examples/web-site/styles/view.tables.md b/examples/web-site/styles/view.tables.md deleted file mode 100755 index ff958db..0000000 --- a/examples/web-site/styles/view.tables.md +++ /dev/null @@ -1,71 +0,0 @@ -# View geometry adaptation - -These are literal declarations for the explicit View wrappers. The original palette, motion, typography and component properties remain in shell.tables.md. The callable theme entry explains how these small geometry rules connect the recursive frame to that preserved data. - -## geometry - -The basic preview wrapper should inherit this site's own fonts and full width. Resource placeholders remain structural values but their native semantic children participate in the original named grid. Lists use Markdown rather than a private intro binding table. - -| selector | property | value | -|---|---|---| -| .mq-document .mq-view | max-width | none | -| .mq-document .mq-view | margin | 0 | -| .mq-document .mq-view | padding | 0 | -| .mq-document .mq-view | line-height | inherit | -| .mq-document .mq-view | font-family | inherit | -| .mq-document .site-layout | display | grid | -| .mq-document .site-layout | grid-template-rows | auto 1fr auto | -| .mq-document .site-layout | min-height | 100vh | -| .mq-document .site-layout > .slot-nav | display | contents | -| .mq-document .site-layout > .slot-sidebar | display | contents | -| .mq-document .site-layout .main-intro ul | padding | 0 | -| .mq-document .site-layout .main-intro ul | list-style | none | -| .mq-document .site-layout .main-intro li > p | margin | 0 | -| .mq-document .site-layout .main-intro blockquote > p | margin | 0 | - -## selectors - -Only these structural addresses change. The original property, value, media and order remain untouched; this is a site migration table, not a new page language. - -| @ | old | new | -|---|---|---| -| 1 | body.has-sidebar | .site-layout.has-sidebar | -| 2 | body.no-sidebar | .site-layout.no-sidebar | -| 3 | body.layout-stacked | .site-layout.layout-stacked | -| 4 | body.is-desk | .site-layout.is-desk | -| 5 | main.main | section.main | -| 6 | .main-intro > .claim | .main-intro ul | -| 7 | .main-intro > .steps | .main-intro ol | -| 8 | .intro_title | .main-intro h1 | -| 9 | .kicker | .main-intro blockquote | - -## areas - -Compile these original sections in the same cascade order. - -| name | -|---| -| vars | -| motion | -| layout | -| responsive | -| chrome | -| widgets | - - -## properties - -Restore every originally attached named property table at its actual semantic target. The native style compiler adds the leading class dot to each selected name. - -| @ | name | selector | -|---|---|---| -| 1 | topnav | mq-document .site-layout .topnav | -| 2 | side_panel | mq-document .site-layout .side | -| 3 | footer | mq-document .site-layout .foot | -| 4 | card_title | mq-document .site-layout .content.cards h2 | -| 5 | card_body | mq-document .site-layout .content.cards p | -| 6 | kicker | mq-document .site-layout .main-intro blockquote | -| 7 | intro_title | mq-document .site-layout .main-intro h1 | -| 8 | lede | mq-document .site-layout .main-intro .slot-intro-content > p | -| 9 | claim | mq-document .site-layout .main-intro ul > li | -| 10 | step | mq-document .site-layout .main-intro ol > li | diff --git a/examples/web-site/verify.mq.md b/examples/web-site/verify.mq.md deleted file mode 100755 index bbc3ae5..0000000 --- a/examples/web-site/verify.mq.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -markup: occlusion -title: Executable theme migration evidence -import: - document: lib/document.mq.md - table: lib/table.mq.md - hash: lib/hash.mq.md - result: lib/result.mq.md - theme: styles/index.mq.md - original: styles/shell.mq.md ---- - -This verification reads actual source declarations and compiles both the retained original and the View projection. It neither certifies the whole site nor replaces HTTP and browser tests. Call theme_values with plugin,fs.read and --fs-root examples/web-site; use an owned copy when validating other site operations. - -## theme_values - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing verified original row count and real CSS identities | - -Each of the six original areas is read through the native Markdown table reader. Compare every projected record to its original after removing only selector: values, media, properties, ordering and row count must match. Tokens and keyframe selectors themselves must remain unchanged. A mismatch returns an actual failed Result before claiming preservation. - -The original and projected CSS hashes identify actual compiled outputs; a different View hash is expected because its semantic addresses and wrapper geometry changed. They are not a visual acceptance certificate. Browser tests separately inspect the real palette, title typography, grid, form flow and current records. This tool makes the preserved declarations reviewable without hiding the implementation in another language. - -`areas` = - -| name | -|---| -| vars | -| motion | -| layout | -| responsive | -| chrome | -| widgets | - -We **count = 0**. -- [Compare each actual original area to its projection](for areas as name) - We **columns = [Read the source declaration leaf](document.read_table(path="styles/shell.tables.md", title=`name`))** and **rows = [Retain original row order](table.from_columns(columns=`columns`))** and **projected = [Run the actual selector projection](theme._table(name=`name`))**. - 1. len(`rows`) != len(`projected`) - Return *[Keep a dropped declaration visible](result.error(code="site.theme_rows", message=`name`, operation="theme_values"))*. - We **position = 0**. - - [Compare original property, value and media for every row](for rows as row) - We **actual = [Read the same projected position](table.at(xs=`projected`, i=`position`))** and **before = [Set aside only the original selector](table.delete(map=`row`, key="selector"))** and **after = [Set aside only the projected selector](table.delete(map=`actual`, key="selector"))**. - 1. `before` != `after` - Return *[Keep any changed declaration payload visible](result.error(code="site.theme_value", message=`name`, operation="theme_values"))*. - 1. `name` == "vars" or `name` == "motion" - 1. access(`row`, "selector") != access(`actual`, "selector") - Return *[Keep global token/keyframe addresses unchanged](result.error(code="site.theme_global", message=`name`, operation="theme_values"))*. - We **position = position + 1** and **count = count + 1**. -We **old_css = [Compile the retained original theme](original.css())** and **view_css = [Compile the actual View theme](theme.css())** and **original_sha256 = [Identify real original CSS bytes](hash.sha256(text=`old_css`))** and **view_sha256 = [Identify real projected CSS bytes](hash.sha256(text=`view_css`))**. - -`evidence` = - -| preserved_rows | original_sha256 | view_sha256 | -|---|---|---| -| `count` | `original_sha256` | `view_sha256` | - -Return *[Expose real preservation and compilation evidence](result.ok(value=`evidence`))*. diff --git a/examples/web-spa-app/README.md b/examples/web-spa-app/README.md deleted file mode 100755 index 1112175..0000000 --- a/examples/web-spa-app/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# web-spa-app - -这个工程演示列表、详情、编辑和新建之间的浏览器路由。客户端用原生记录保存条目,以稳定 id 选择内容;刷新页面后恢复演示数据,不提供持久化存储。用户输入通过文本效果和结构化列表显示。 - -从仓库根目录先构建浏览器运行时,再启动可调用服务: - -```sh -marqdo call skills/marqdo-dev/index.mq.md build_browser 'out="examples/web-spa-app/static"' --effects plugin,process.exec,fs.write --fs-root . --require-ok --json -marqdo call examples/web-spa-app/index.mq.md serve --effects plugin,fs.read,network.write --fs-root . --json -``` - -打开 http://127.0.0.1:18093。构建需要兼容的 WASM 工具链;缺少时按 [工具链手册](../../skills/marqdo-dev/toolchain.mq.md) 准备工作区编译器,并把返回的 compiler 传给 build_browser。不要用旧版运行时替代当前源码的构建。 - -工程入口 [index.mq.md](index.mq.md) 负责发现和服务;[components/index.mq.md](components/index.mq.md) 逐层组合导航和视图面板;[客户端源码](static/client.mq.md) 说明事件、路由和状态更新。修改内容从 Markdown 叶子开始,修改布局在组件中完成。 - -[开发手册](../../skills/marqdo-dev/index.mq.md) 的 test_browser 使用当前构建验证实际列表编辑、浏览器后退、输入转义和移动端布局。设计背景见 [SPA 设计](../../doc/design/ext-web-spa.md)。 diff --git a/examples/web-spa-app/components/controls.mq.md b/examples/web-spa-app/components/controls.mq.md deleted file mode 100755 index 78c9036..0000000 --- a/examples/web-spa-app/components/controls.mq.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -markup: occlusion -title: Native control leaves -import: - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -These small leaves retain accessible ids and plain text. Parent components decide their arrangement; callbacks use the same ids in the client wiring. - -## button - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable id used by the client event table | -| label | text | required | Plain button text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One native button leaf | - -Use `id` and `label` for one event target. A button has type button so it does not accidentally submit a surrounding form. Its label stays plain text, including quotes and angle brackets. This function describes a control and performs no click, navigation or DOM mutation. The same leaf is reused by navigation, detail actions and editor actions. - -`attrs` = - -| id | type | -|---|---| -| `id` | button | - -Return *[Describe this native action button](component.element(kind="button", value=`label`, attrs=`attrs`, slot=`id`))*. - -## text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable client text target | -| value | text | "" | Initial plain text | -| kind | text | "text" | Native text, title or pre kind | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One native text target | - -Use `id`, `value`="" and `kind`="text" to declare a simple display leaf. Initial content is escaped by the renderer, and later updates use browser set_text rather than HTML. Select pre for a log or title for the page heading. The control carries no sibling layout, state machine or event handler; its parent owns placement. - -We **attrs = [Retain the stable text target](table.put(in=None, at="id", value=`id`))**. -Return *[Describe the native text leaf](component.element(kind=`kind`, value=`value`, attrs=`attrs`, slot=`id`))*. diff --git a/examples/web-spa-app/components/index.mq.md b/examples/web-spa-app/components/index.mq.md deleted file mode 100755 index 9915994..0000000 --- a/examples/web-spa-app/components/index.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: SPA homepage assembly -import: - nav: nav.mq.md - panels: panels/index.mq.md - controls: controls.mq.md - client: ext/web/client/index.mq.md - table: lib/table.mq.md ---- - -The homepage composes navigation, heading, independent panels, status and the official runtime Resource. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Complete structured homepage without raw HTML | - -This root contains component relationships only. Navigation and panels are ordinary child modules; their content and controls are already simple leaves. The official client runtime is a script Resource referencing built static assets, so no page HTML or author JavaScript is needed. The title and log use stable text targets. A valid node tree does not prove the WASM asset exists; build it and mount the static directory before opening the page. - -We **navigation = [Assemble the navigation component](nav.nodes())** and **title = [Describe the changing page heading](controls.text(id="title", value="Items", kind="title"))** and **content = [Assemble the independent panels](panels.nodes())** and **log = [Describe the status text leaf](controls.text(id="log", value="spa ready", kind="pre"))** and **runtime = [Reference the official client program](client.nodes(source="/static/client.mq.md"))**. -We **head = [Keep navigation before the heading](table.concat(a=`navigation`, b=`title`))** and **body = [Keep panels after the heading](table.concat(a=`head`, b=`content`))** and **visible = [Place feedback after the panels](table.concat(a=`body`, b=`log`))**. -Return *[Retain the runtime as a separate Resource](table.concat(a=`visible`, b=`runtime`))*. diff --git a/examples/web-spa-app/components/nav.mq.md b/examples/web-spa-app/components/nav.mq.md deleted file mode 100755 index 7841d24..0000000 --- a/examples/web-spa-app/components/nav.mq.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -markup: occlusion -title: SPA navigation -import: - controls: controls.mq.md - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -Navigation composes reusable native buttons; the client owns their transitions. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Navigation containing Items and New controls | - -The two buttons have independent stable ids and shared accessible button semantics. They contain labels only; selecting an item or opening an editor belongs to the client callbacks. Their parent is a nav region, so this file expresses one placement responsibility without duplicating the surrounding page. - -We **items = [Describe the list action](controls.button(id="nav-list", label="Items"))** and **create = [Describe the creation action](controls.button(id="nav-new", label="New"))** and **children = [Keep their reading order](table.concat(a=`items`, b=`create`))**. -Return *[Place these actions in navigation](component.wrap(children=`children`, kind="nav", slot="navigation"))*. diff --git a/examples/web-spa-app/components/panels/detail.mq.md b/examples/web-spa-app/components/panels/detail.mq.md deleted file mode 100755 index b2a7e42..0000000 --- a/examples/web-spa-app/components/panels/detail.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: Detail panel -import: - controls: ../controls.mq.md - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -Detail separates its changing text from the reusable Edit and Back action leaves. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Initially hidden detail panel | - -The body has id detail-body and receives plain text after selection. Edit retains the selected stable id; Back returns to the list. Neither action's behavior is embedded in markup. The panel starts hidden and the shared client paint function explicitly controls its hidden attribute, using the same ids as the other panels. - -We **body = [Describe the selected record's text target](controls.text(id="detail-body"))** and **edit = [Describe the edit action](controls.button(id="btn-edit", label="Edit"))** and **back = [Describe the list action](controls.button(id="btn-back", label="Back"))**. -We **buttons = [Keep the action order](table.concat(a=`edit`, b=`back`))** and **actions = [Group only these detail actions](component.wrap(children=`buttons`, kind="row", slot="detail-actions"))** and **children = [Keep data before actions](table.concat(a=`body`, b=`actions`))**. - -`attrs` = - -| id | hidden | -|---|---| -| view-detail | True | - -Return *[Describe the independent detail panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="detail-panel"))*. diff --git a/examples/web-spa-app/components/panels/edit.mq.md b/examples/web-spa-app/components/panels/edit.mq.md deleted file mode 100755 index 19f5c33..0000000 --- a/examples/web-spa-app/components/panels/edit.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: Editor panel -import: - controls: ../controls.mq.md - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -The editor is a native input plus reusable action leaves. Saving remains a client transition, not an implicit HTTP form. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Initially hidden editor with accessible label and native input | - -The label's for attribute names edit-title, the same input read by the Save binding. The input keeps a plain text value. Save validates nonempty text in Marqdo before changing the record list; Cancel changes the route without calling that update. This component describes controls only and starts hidden. The parent keeps field content separate from the action row, allowing the existing responsive layout renderer to place them. - -We **label_attrs = [Associate the label with its input](table.put(in=None, at="for", value="edit-title"))** and **label = [Describe the visible field label](component.element(kind="label", value="Title", attrs=`label_attrs`, slot="title-label"))**. - -`input_attrs` = - -| id | name | type | -|---|---|---| -| edit-title | title | text | - -We **input = [Describe the native title input](component.element(kind="input", attrs=`input_attrs`, slot="title-input"))** and **field = [Keep label and input together](table.concat(a=`label`, b=`input`))**. -We **save = [Describe the save action](controls.button(id="btn-save", label="Save"))** and **cancel = [Describe the cancel action](controls.button(id="btn-cancel", label="Cancel"))** and **buttons = [Keep these editor actions ordered](table.concat(a=`save`, b=`cancel`))** and **actions = [Group the action row](component.wrap(children=`buttons`, kind="row", slot="editor-actions"))** and **children = [Place the field before its actions](table.concat(a=`field`, b=`actions`))**. - -`attrs` = - -| id | hidden | -|---|---| -| view-edit | True | - -Return *[Describe the independent editor panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="editor-panel"))*. diff --git a/examples/web-spa-app/components/panels/index.mq.md b/examples/web-spa-app/components/panels/index.mq.md deleted file mode 100755 index fba67b8..0000000 --- a/examples/web-spa-app/components/panels/index.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -title: SPA panel assembly -import: - listing: list.mq.md - detail: detail.mq.md - editor: edit.mq.md - table: lib/table.mq.md ---- - -This parent owns only the three sibling panel relationships. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Ordered list, detail and editor panel rows | - -Each child owns one panel and names its own native controls. This function retains their structured values and stable order; the client independently selects visibility using hidden attributes. It does not render a second page or concatenate HTML. Changes to editor fields therefore remain inside the editor component instead of growing a single application string. - -We **list = [Assemble the listing component](listing.nodes())** and **view = [Assemble the detail component](detail.nodes())** and **edit = [Assemble the editor component](editor.nodes())** and **first = [Retain list and detail order](table.concat(a=`list`, b=`view`))**. -Return *[Keep the editor as the third sibling](table.concat(a=`first`, b=`edit`))*. diff --git a/examples/web-spa-app/components/panels/list.mq.md b/examples/web-spa-app/components/panels/list.mq.md deleted file mode 100755 index 7bc7221..0000000 --- a/examples/web-spa-app/components/panels/list.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -title: List panel -import: - component: ext/web/component/index.mq.md - table: lib/table.mq.md ---- - -The existing list container is populated by the official bridge's structured render_list effect. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Initially visible list panel with its Markdown hint | - -The empty native list provides id items for delegated clicks. Its actual entries come from native client records and use stable data-id attributes. The hint is ordinary Markdown and knows nothing about item data or routing. Only this parent sets the list panel's visibility; detail and editor remain separate components. - -We **empty = [Start with no server-owned item rows](table.empty_list())** and **target = [Name the client-owned list container](table.put(in=None, at="id", value="items"))** and **list = [Describe the native unordered list](component.wrap(children=`empty`, kind="list", attrs=`target`, slot="items"))**. -We **hint = [Keep the instruction as ordinary Markdown](component.markdown(text="Click an item for detail.", slot="list-hint"))** and **children = [Place the hint after its list](table.concat(a=`list`, b=`hint`))**. - -`attrs` = - -| id | hidden | -|---|---| -| view-list | False | - -Return *[Describe the visible list panel](component.wrap(children=`children`, kind="section", attrs=`attrs`, slot="list-panel"))*. diff --git a/examples/web-spa-app/index.mq.md b/examples/web-spa-app/index.mq.md deleted file mode 100755 index 59d3af2..0000000 --- a/examples/web-spa-app/index.mq.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Marqdo SPA — Document layout and native client records -import: - home: components/index.mq.md - web: ext/web/web.mq.md - http: ext/net/http.mq.md ---- - -The Document's main assembles View nodes; serve owns the process lifetime. Build current WASM assets into static before starting. From the checkout root, call serve with plugin,fs.read,network.write and --fs-root examples/web-spa-app. List, detail and edit behavior stays in static/client.mq.md, with native row records and the official bridge's list effect. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Homepage View rows | - -The page delegates layout to the component root. Follow that root into navigation and the three independent panels until reaching plain text, Markdown or a native control leaf. The runtime is a structured Resource. This function neither starts a server nor mixes client state into a page HTML string; serve later mounts the actual assets. - -Return *[Assemble the inspectable homepage](home.nodes())*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-spa-app" | Explicit site directory from the checkout root | -| port | number | 18093 | Loopback listen port | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking site listener result | - -Use `root`="examples/web-spa-app" and `port`=18093. The site prepares declared Documents and Endpoints, mounts static, then binds the existing /item redirect through the network resource. The explicit localhost address matches this demonstration's scope. Browser transitions use history inside the page; the server redirect preserves the old direct /item entry behavior. This function blocks until its supervisor stops it, and missing assets remain a real build prerequisite. - -We **app = [Prepare the declared page and static mount](web.prepare(root=`root`, host="127.0.0.1", port=`port`, static_dir="static"))** and **app = [Preserve the declared direct-entry redirect](http.redirect(app=`app`, from="/item", to="/", permanent=False))**. -Return *[Listen after all resources are bound](web.listen(app=`app`))*. diff --git a/examples/web-spa-app/static/client.mq.md b/examples/web-spa-app/static/client.mq.md deleted file mode 100755 index 4cda98d..0000000 --- a/examples/web-spa-app/static/client.mq.md +++ /dev/null @@ -1,240 +0,0 @@ ---- -markup: occlusion -title: SPA client with native records and structured browser effects -import: - browser: lib/browser.mq.md - table: lib/table.mq.md ---- - -The Document supplies native controls; this client supplies transitions between list, detail and edit. BrowserSession retains the entry state between callbacks. Stable ids keep selection separate from user text, and all dynamic list content is sent as records to the existing official bridge. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Boot bindings, initial list, memory storage and panel effects | - -This client keeps route, selection and records in the browser session's native Marqdo entry state. Titles are text; stable ids select records even when a title contains punctuation or is edited. The initial list is a row table rather than a newline string. Boot binds the existing controls, seeds the memory store and paints the first view immediately. Storage lasts for this client session; it is not a server database or durable reload persistence. Page geometry and labels live in separate Document components. Event callbacks only calculate state changes and return instructions for the official bridge. - -We **route = "/"** and **cur_id = ""** and **next_id = 2** to start with no selected record. - -`items` = - -| @ | id | title | -|---|---|---| -| 1 | "1" | Alpha | -| 2 | "2" | Beta | - -We **bindings = [Read the explicit event wiring](_bindings())** and **wired = [Describe those control bindings](table.put(in=None, at="wire", value=`bindings`))**. -We **painted = [Paint the initial list without changing history](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`, update_url=False))**. -After boot, return *[Keep bindings and initial effects together](browser.merge(a=`wired`, b=`painted`))*. - -## _bindings - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Explicit delegated event rows for existing native controls | - -These rows connect the Document's stable ids to Marqdo callbacks. List clicks are delegated to li[data-id], so replacing list entries does not discard the listener. Save reads the existing input value, and browser back/forward supplies path to on_pop. The bridge owns event dispatch; this table does not contain author JavaScript or page HTML. Every referenced callback below has an actual parameter and return contract. - -`bindings` = - -| @ | 选择器 | 事件 | 调用 | 委托 | 值选择器 | -|---|---|---|---|---|---| -| 1 | "#nav-list" | click | go_list | | | -| 2 | "#nav-new" | click | go_new | | | -| 3 | "#items" | click | open_item | "li[data-id]" | | -| 4 | "#btn-edit" | click | go_edit | | | -| 5 | "#btn-back" | click | go_list | | | -| 6 | "#btn-save" | click | save_item | | "#edit-title" | -| 7 | "#btn-cancel" | click | go_list | | | -| 8 | window | popstate | on_pop | | | - -Return *bindings*. - -## on_pop - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | "" | Location path supplied by the browser's popstate event | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Panel, list and storage effects without pushing a second history entry | - -Use `path`="" from the event payload. Route state uses a different name so assigning the event value changes shared state instead of shadowing a path parameter. An empty payload leaves the current route unchanged. Painting a history event deliberately avoids spa_goto: pressing Back must not create another forward history record. - -1. `path` != "" - We **route = [Retain the location supplied by the browser](path)**. -Return *[Repaint the restored route without another navigation](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`, update_url=False))*. - -## go_list - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | List panel effects and one navigation instruction | - -The Items and Back controls share this transition. Clear the selected id so the list does not retain an editing target, switch the shared route to the list path, then paint through the common function. Stored item data remains unchanged. The browser bridge performs the returned navigation and DOM instructions after the state update. - -We **route = "/"** and **cur_id = ""**. -Return *[Show the current list](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*. - -## go_new - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Empty editor effects and one navigation instruction | - -Creating a record opens the editor without selecting an existing id. Save allocates an id only after nonempty text arrives, so merely opening or cancelling this panel does not insert a blank record. The common paint function puts an empty value in the native input and hides the other panels. - -We **route = "/edit"** and **cur_id = ""**. -Return *[Open the empty editor](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*. - -## go_edit - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Editor effects for the existing selection | - -Editing keeps the selected id and changes only the current panel. The paint function looks up the current title from native rows, so a renamed record is still found by its stable id. Navigation and rendering remain instructions for the bridge; this callback neither writes a file nor calls a server. - -We **route = "/edit"**. -Return *[Show the selected record in the editor](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*. - -## open_item - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data_id | text | "" | Stable data-id from the delegated list item | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Detail effects, or None when no record id was clicked | - -Use `data_id`="" from the delegated event. A click outside a real list entry must not invent a selection. Keep the id separately from its displayed title; quoted text, angle brackets and later renames therefore do not alter the event identity. Actual text is selected when the detail panel is painted. - -1. `data_id` != "" - We **cur_id = [Retain the clicked record identity](data_id)** and **route = "/item"**. - Return *[Show the selected record](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*. -If no record was clicked, return *None*. - -## save_item - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | text | "" | Plain title from the native editor input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Saved detail effects, or a title-required text effect | - -Use `value`="" from the Save binding. Empty text returns a validation message before changing data. For an existing id, replace that row's title while retaining all ids and row order. For a new record, allocate the next native integer id and convert it to event text. The resulting records are kept in the session and mirrored to the memory store by painting. No HTML is generated from a title and no external interpreter performs the array update. Cancel bypasses this function entirely. - -1. `value` == "" - Return *[Explain the required title](browser.set_text(sel="#log", text="title required"))*. -1. `cur_id` != "" - We **updated = [Start the replacement record list](table.empty_list())**. - - [Retain each record or replace only its title](for items as item) - 1. access(`item`, "id") == `cur_id` - We **item = [Update the title without changing its id](table.put(in=`item`, at="title", value=`value`))**. - We **updated = [Retain this row in its original order](table.append(list=`updated`, item=`item`))**. - We **items = [Keep the completed native row list](updated)**. -2. * - We **next_id = next_id + 1** and **cur_id = [Use the stable integer id as event text](str(next_id))**. - - `item` = - - | id | title | - |---|---| - | `cur_id` | `value` | - - We **items = [Append the new native record](table.append(list=`items`, item=`item`))**. -We **route = "/item"** after a successful save. -Return *[Display and mirror the saved record](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*. - -## _list_rows - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| records | list | required | Native rows with id and title | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Bridge list items containing escaped text and stable data-id attributes | - -Use `records` as the only list input. Each output item carries plain text plus an attribute record; the official bridge performs text escaping when it renders the list. The source never interpolates a title into an HTML tag. The delegated click id comes from the original record id, preserving selection independently of the displayed title. - -We **rows = [Start the browser list descriptions](table.empty_list())**. -- [Describe every native record as a text item](for records as record) - We **label = [Read its plain title](access(`record`, "title"))** and **id = [Read its stable identity](access(`record`, "id"))** and **attrs = [Retain the delegated event id](table.put(in=None, at="data-id", value=`id`))**. - - `row` = - - | text | attrs | - |---|---| - | `label` | `attrs` | - - We **rows = [Retain this structured list item](table.append(list=`rows`, item=`row`))**. -Return *rows*. - -## spa_render - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Current panel, list, memory and navigation effects | - -This named entry preserves the common rendering callback used by the demonstration. It delegates to the same paint function as direct transitions so panel selection, item text and memory storage stay consistent. No page string is compiled or evaluated here; the returned value is a normal bridge instruction record. - -Return *[Paint the current native state](spa_paint(records=`items`, path=`route`, selected_id=`cur_id`))*. - -## spa_paint - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| records | list | required | Native item rows to display and mirror | -| path | text | required | Current client route | -| selected_id | text | required | Stable selected id, or empty for a new item | -| update_url | bool | True | False for history events and initial boot; True for user navigation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | One complete structured effect map for the current native state | - -Use `records`, `path`, `selected_id` and `update_url`=True for ordinary user navigation, and False when repainting an existing history entry. The selected row is found by id; all content remains plain text. Three panels receive explicit hidden flags, while title, detail and log text are described together. Browser merge replaces whole top-level effect keys, so combining those text targets first prevents later messages from discarding earlier text updates. List rows go through render_list, and the editor value changes only while that panel is active. Storage uses a record list in the memory scope. This function describes effects and performs no direct DOM, network or file access. - -We **selected = [Find the native record by stable identity](table.find(list=`records`, key="id", value=`selected_id`))** and **body = ""** and **title = "Items"**. -1. `selected` != None - We **body = [Read the current selected title](access(`selected`, "title"))**. -1. `path` == "/item" - We **title = "Detail"**. -1. `path` == "/edit" - We **title = "Edit"**. -We **list_flag = [Hide the list outside its route](table.put(in=None, at="hidden", value=(path != "/")))** and **detail_flag = [Show only the detail route](table.put(in=None, at="hidden", value=(path != "/item")))** and **edit_flag = [Show only the editor route](table.put(in=None, at="hidden", value=(path != "/edit")))**. - -`visibility` = - -| #view-list | #view-detail | #view-edit | -|---|---|---| -| `list_flag` | `detail_flag` | `edit_flag` | - -`texts` = - -| #title | #detail-body | #log | -|---|---|---| -| `title` | `body` | `path` | - -We **ret = [Describe all text updates in one effect](browser.wrap(key="set_text", value=`texts`))** and **flags = [Describe the three panel visibility updates](browser.wrap(key="set_attr", value=`visibility`))** and **ret = [Keep independent text and attribute effects](browser.merge(a=`ret`, b=`flags`))**. -We **rows = [Describe record text without HTML](_list_rows(records=`records`))** and **listing = [Replace the existing list using structured items](browser.render_list(sel="#items", items=`rows`))** and **ret = [Retain the list update](browser.merge(a=`ret`, b=`listing`))**. -1. `path` == "/edit" - We **edit = [Populate the native editor input](browser.set_value(sel="#edit-title", value=`body`))** and **ret = [Retain the input value update](browser.merge(a=`ret`, b=`edit`))**. -1. `update_url` - We **navigation = [Navigate only for a user transition](browser.spa_goto(url=`path`))** and **ret = [Retain this history instruction](browser.merge(a=`ret`, b=`navigation`))**. - -`persist` = - -| op | key | value | scope | -|---|---|---|---| -| set | spa-items | `records` | memory | - -We **storage = [Mirror the native records in memory](browser.storage(spec=`persist`))**. -Return *[Keep the completed paint and memory instructions](browser.merge(a=`ret`, b=`storage`))*. diff --git a/examples/web-tenant-saas/README.md b/examples/web-tenant-saas/README.md deleted file mode 100755 index 21a0124..0000000 --- a/examples/web-tenant-saas/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# web-tenant-saas - -从仓库根目录运行: - -```sh -marqdo call examples/web-tenant-saas/index.mq.md serve --effects plugin,fs.write,network.write --fs-root examples/web-tenant-saas --json -``` - -打开 http://127.0.0.1:18092,比较页面里的 Acme 与 Beta 查询链接。缺少 t 参数时返回 400;返回的 JSON 包含 rows 列表。首次空库初始化两篇笔记,重启保留已有记录。 - -[工程入口](index.mq.md) 串联 [数据库初始化](db/index.mq.md)、[租户选择](../../ext/security/tenant.mq.md) 与 [JSON 查询资源](../../ext/data/api.mq.md)。页面内容位于 [intro.md](intro.md),无原生 HTML 壳。 - -这是允许匿名切换租户的本机过滤演示。生产访问隔离还需要鉴权与成员关系检查。回归测试 web_handbook 覆盖两种后端的租户过滤、缺少参数与用户记录重启保留。 diff --git a/examples/web-tenant-saas/db/index.mq.md b/examples/web-tenant-saas/db/index.mq.md deleted file mode 100755 index 411529b..0000000 --- a/examples/web-tenant-saas/db/index.mq.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -markup: occlusion -title: Tenant demonstration database -import: - db: ext/data/db.mq.md - fs: lib/fs.mq.md ---- - -This initializer owns one demonstration table. It keeps existing rows and seeds only an empty table. Pass a disposable absolute SQLite URI for tests; no caller should need to delete a user's data to repeat initialization. - -## open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | None | None chooses data/tenant-saas.db under the granted site root; otherwise an explicit SQLite URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Initialized database resource containing retained user rows or initial demo notes | - -Use `url`=None with fs.write and plugin on the site root. The default path is resolved through the native filesystem so its location does not change with the process working directory. An explicit SQLite URI belongs to the caller, who must grant and manage that native database boundary. This initializer never deletes rows or resets ids during a restart. - -The schema preserves the title and tenant_id fields used by the scoped query. Check for any existing row before seeding; a nonempty or partially populated database is retained as supplied. Only a completely empty table receives the two notes. This is an idempotent demonstration initializer, not a migration or repair tool. - -1. `url` == None - We **[Create the site's selected data directory](fs.make_dirs(path="data"))** and **path = [Resolve the native database filename](fs.resolve(path="data/tenant-saas.db"))** and **url = "sqlite:" + path**. - -`fields` = - -| name | type | nullable | -|---|---|---| -| id | integer | False | -| title | text | False | -| tenant_id | text | False | - -We **store = [Open the selected database resource](db.db(url=`url`))** and **[Ensure the demonstration table exists](> `store`.init name="items" fields=`fields`)** and **existing = [Observe whether any business rows already exist](> `store`.select table="items" limit=1)**. -1. not `existing` - - `rows` = - - | @ | title | tenant_id | - |---|---|---| - | 1 | Acme note | acme | - | 2 | Beta note | beta | - - We **[Insert both initial notes only into the empty table](> `store`.insert table="items" rows=`rows`)**. -Once the selected database is ready, return *store* for route discovery and binding. diff --git a/examples/web-tenant-saas/index.mq.md b/examples/web-tenant-saas/index.mq.md deleted file mode 100755 index dcd8133..0000000 --- a/examples/web-tenant-saas/index.mq.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Tenant SaaS — explicit database and request resources -import: - component: ext/web/component/index.mq.md - fs: lib/fs.mq.md - web: ext/web/web.mq.md - api: ext/data/api.mq.md - tenant: ext/security/tenant.mq.md - database: db/index.mq.md ---- - -Read the Markdown leaf for the visible demonstration, the database entry for initialization, and the two resource leaves for query and tenant binding. The old startup DELETE is removed: restarting a demo must preserve existing rows. This loopback site intentionally allows choosing a demo tenant; it does not claim authenticated membership. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Native View nodes containing the Markdown explanation and query links | - -The page is a single content leaf because its internal structure is already simple Markdown. No raw HTML shell or browser script is needed. Site discovery reads it relative to the chosen site root; the returned node data is assembled before any listener starts. The API and database lifecycle remain in serve, so rendering the explanation cannot clear or recreate business data. - -We **intro = [Read the terminal content through the granted site root](fs.read_text(path="intro.md"))**. -Return *[Describe the explanation as a Markdown leaf](component.markdown(text=`intro`, slot="tenant-introduction"))*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-tenant-saas" | Explicit site discovery directory relative to the checkout | -| port | number | 18092 | Local listener port | -| url | any | None | None selects the site-root database; tests pass a disposable SQLite URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking listener with explicit tenant-filtered JSON queries | - -Use `root`="examples/web-tenant-saas", `port`=18092 and `url`=None with plugin, fs.write and network.write. Set --fs-root to this site's directory so default database files belong to the site. The discovery root is explicit and independent of that filesystem grant. Preparation initializes retained records, discovers the explanation, then binds request tenant selection and the read-only query table before listening. - -The route explicitly scopes its query by tenant_id. With the resolver attached, missing tenant context is rejected rather than returning both tenants. Selection via t is intentionally open for this local example; real user access requires a separate authentication and membership policy. Keep both bindings together when editing the flow. - -We **store = [Initialize without deleting existing user rows](database.open(url=`url`))** and **app = [Discover the page with its retained database resource](web.prepare(root=`root`, host="127.0.0.1", port=`port`, db=`store`))** and **app = [Resolve the explicit request tenant selector](tenant.attach(app=`app`, mode="path", param="t", default_scope=False))**. - -`routes` = - -| path | method | table | order | limit | tenant_scope | -|---|---|---|---|---|---| -| api/items | GET | items | id | 50 | True | - -We **app = [Bind the explicit tenant-scoped read-only query](api.mount(app=`app`, routes=`routes`))**. -Return *[Listen after data and request policy are ready](web.listen(app=`app`))*. diff --git a/examples/web-tenant-saas/intro.md b/examples/web-tenant-saas/intro.md deleted file mode 100755 index f822603..0000000 --- a/examples/web-tenant-saas/intro.md +++ /dev/null @@ -1,11 +0,0 @@ -# Two-tenant query demonstration - -Compare [Acme notes](/api/items?t=acme) with [Beta notes](/api/items?t=beta). -Each response selects only rows belonging to the chosen tenant. -A [request without a tenant](/api/items) is rejected. - -This local demonstration permits anonymous tenant selection. It demonstrates -query filtering and does not authenticate a user or prove tenant membership. - -Restarting the server retains existing database rows. The initializer adds -the two demonstration notes only when the table is completely empty. diff --git a/examples/web-ws-room/home.mq.md b/examples/web-ws-room/home.mq.md deleted file mode 100755 index 2504311..0000000 --- a/examples/web-ws-room/home.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: Room page components -import: - component: ext/web/component/index.mq.md - table: lib/table.mq.md - fs: lib/fs.mq.md ---- - -The parent contains an introduction and one log control. Ordinary copy lives in intro.md; the control keeps only its event target and plain initial text. Content has no transport setup, server lifetime or generated HTML. - -## nodes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Ordered introduction and log control rows | - -The introduction is a terminal Markdown content block and is read within the granted site root. The event log is a preformatted native leaf with id log; incoming client messages may replace its text without changing the layout. Attribute values remain typed data until rendering, and initial text is escaped. These two independent responsibilities are merged in reading order, without a string of raw HTML or a second layout schema. - -We **intro = [Read the terminal Markdown content](fs.read_text(path="intro.md"))** and **overview = [Describe the introduction as Markdown](component.markdown(text=`intro`, slot="intro"))**. - -`attributes` = - -| id | aria-live | -|---|---| -| log | polite | - -We **log = [Describe the independent event log](component.element(kind="pre", value="Connect a client to /chat/lobby.", attrs=`attributes`, slot="log"))**. -Return *[Keep introduction and event log in reading order](table.concat(a=`overview`, b=`log`))*. diff --git a/examples/web-ws-room/index.mq.md b/examples/web-ws-room/index.mq.md deleted file mode 100755 index afed66f..0000000 --- a/examples/web-ws-room/index.mq.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -markup: occlusion -type: web -view: main -route: / -title: Room transport composed from Documents and Resources -import: - web: ext/web/web.mq.md - socket: ext/net/websocket.mq.md - home: home.mq.md ---- - -This local demonstration serves a Markdown introduction and a native log control. The page is a Document; the room transport is an explicitly bound network resource. From the checkout root, call serve with --effects plugin,fs.read,network.write and --fs-root examples/web-ws-room. It blocks until the supervising process stops it. Connect a WebSocket client to /chat/lobby to join chat.room.lobby; presence uses the same native room protocol as other transports. This loopback-only example explicitly permits anonymous room access; a deployed site should attach authentication and retain the default private route policy. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | The homepage View rows, without starting a server | - -The Document's main function only assembles content. The introduction remains a Markdown leaf and the event log is one native control with a stable id. The parent keeps those responsibilities as separate nodes, so changing the transport does not require rewriting the page as HTML. The View renderer receives structured values, and reading the content requires the granted site root. - -After selecting the homepage components, return *[Assemble the readable room page](home.nodes())*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "examples/web-ws-room" | Explicit site directory relative to the current working directory | -| port | number | 18091 | Loopback server port | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking listener result for the declared page and room route | - -Use `root`="examples/web-ws-room" and `port`=18091 from the checkout root. Preparing the site performs Document discovery and one startup assembly before any socket opens. Then the network resource binds /chat/{id} using the chat.room.{id} room template and publishes presence messages. This intentionally public local demo sets require_auth=False; it is not a recommendation to expose anonymous production rooms. Keep each returned app value because binding updates are immutable. The final listener retains the original site root for callbacks and resources. - -We **app = [Discover the site's Documents and Endpoints](web.prepare(root=`root`, host="127.0.0.1", port=`port`))**. -We **app = [Bind the room and its presence channel](socket.route(app=`app`, path="/chat/{id}", mode="room", room_key="chat.room.{id}", presence=True, require_auth=False))**. -After all bindings are ready, return *[Listen with the complete site resources](web.listen(app=`app`))*. diff --git a/examples/web-ws-room/intro.md b/examples/web-ws-room/intro.md deleted file mode 100755 index de85c9d..0000000 --- a/examples/web-ws-room/intro.md +++ /dev/null @@ -1,5 +0,0 @@ -# WebSocket room - -Join **lobby** through `/chat/lobby`. Messages are shared in `chat.room.lobby`; the native presence channel announces participants. - -Open two controlled clients to observe room messages and presence. This demonstration listens only on the local host and explicitly permits anonymous room access. diff --git a/ext/VERSION b/ext/VERSION deleted file mode 100644 index dedcc7d..0000000 --- a/ext/VERSION +++ /dev/null @@ -1 +0,0 @@ -2.9.1 diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md deleted file mode 100755 index a2c01a9..0000000 --- a/ext/ai/agent.mq.md +++ /dev/null @@ -1,5308 +0,0 @@ ---- -markup: occlusion -title: ext/ai/agent -description: Document-driven agent v2 — step / plan / run; Skill Compilation via ABI plugin (episodes → learn → llm_free). -import: - llm: ext/ai/llm.mq.md - json: lib/json.mq.md - sys: lib/sys.mq.md - fs: lib/fs.mq.md - time: lib/time.mq.md - text: lib/text.mq.md - wb: lib/writeback.mq.md - subtask: lib/subtask.mq.md - plugin: lib/plugin.mq.md - sandbox: ext/ai/sandbox.mq.md - table: lib/table.mq.md ---- - -This file owns agent orchestration: call-site context, explicit tools, routing, workbooks, observations and continuation. Start with [the AI workflows](index.mq.md) for package choices and native dependencies. Use step for one turn, run for reuse and learning, and plan for a bounded workbook lifecycle. Internal helpers are documented for development but are not automatically model-callable tools. Changes must preserve source authority, effect deduplication and the location of writeback. - -## build_step_context - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| agent | any | required | Agent configuration or receiver created by this package | -| task | any | required | Structured task or text supplied to the agent | -| source_depth | any | "default" | Source-context depth; default follows the documented context budget | -| skill_depth | any | "default" | Skill-context depth; default follows the documented context budget | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Assemble a readable prompt: standing, task, call site, tools, budgeted source + skill, and the act protocol. The runbook `.mq.md` is ground truth (code as documentation). Default budgets keep long files from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`. | - -Use `agent`, `task`, `source_depth`="default", `skill_depth`="default" as the inputs for this operation. - -Assemble a readable prompt: standing, task, call site, tools, budgeted source + skill, and the act protocol. -The runbook `.mq.md` is ground truth (code as documentation). Default budgets keep long files from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`. - -The sections have different authority. Standing text sets the agent's role, task text states the current request, and the call site identifies the exact source location that requested it. Source and skill excerpts are bounded evidence for that location. They are not a replacement for the author's runbook. The returned prompt is plain text; constructing it does not call a model or execute any listed tool. - -Tool descriptions come from the supplied whitelist. The act instructions restrict CALL names to that section, so an internal helper mentioned elsewhere is not automatically callable. A truncated excerpt can request a deeper source or skill read through the explicit READ protocol. The caller must enforce its read budget and tool permissions; these instructions alone are not an authorization mechanism. - -We retain **`standing` = [Read the standing field](json.get(value=`agent`, key="standing"))**. -1. `standing` - We retain **up = standing**. -2. * - We retain **up = None**. - -We retain **`tools` = [Read the tools field](json.get(value=`agent`, key="tools"))**. -We retain **`tools_s` = [Format tools](agent_format_tools(tools=`tools`))**. -We retain **`src` = [Source brief](source_brief(depth=`source_depth`))**. -We retain **`site` = [Call site](agent_call_site())**. -We retain **`site_s` = [Encode the structured value as JSON text](json.stringify(value=`site`))**. -We retain **`skill` = [Skill brief](skill_brief(depth=`skill_depth`))**. -We retain **`task_s` = [Encode the structured value as JSON text](json.stringify(value=`task`))**. - -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -`_literal_esc_g_lines` = - -| line | -|---| -| "" | -| "" | -| "--- how to act ---" | -| "Call ONLY names listed under --- tools --- (whitelist). If that section is empty or says none, do NOT emit CALL / 调用 — reply with the final answer only." | -| "Never CALL internal framework helpers (build_step_context, plan, inspect_workbook, etc.)." | -| "Context is budgeted: if you see a [truncated …] marker, you may first emit exactly one line READ:source or READ:skill (Chinese: 读取:source\|skill) to deepen, then you will be re-prompted." | -| "When calling an allowed tool, reply with exactly one line: CALL:" | -| "(Chinese ok: 调用:)" | -| "Otherwise reply with the final answer only." | -| "If a capability cannot truly be wired, do NOT fake it silently and never claim it works: write an occlusion with an explicit status, e.g. [按关键词检索,接口未接,待开发](None). Stubs must run without error and must state their return value (None is acceptable). Before finishing, check your own declarations with labels.search." | -| "Tools run via Marqdo subtask (spawn fn / wait)." | -| "" | - -Join exactly those lines into **_literal_esc_g_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_g_lines`, sep="\n"))**. - -The following record names each literal field without a JSON construction chain. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "a" | "\n\n--- standing ---\n" | -| 2 | "b" | "\n\n--- task ---\n" | -| 3 | "c" | "\n\n--- tools ---\n" | -| 4 | "d" | "\n\n--- call site ---\n" | -| 5 | "e" | "\n\n--- source (.mq.md) ---\n" | -| 6 | "f" | "\n\n--- marqdo skill ---\n" | -| 7 | "g" | `_literal_esc_g_text` | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. -We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. -We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. -We retain **`d` = [Read the d field](json.get(value=`esc`, key="d"))**. -We retain **`e` = [Read the e field](json.get(value=`esc`, key="e"))**. -We retain **`f` = [Read the f field](json.get(value=`esc`, key="f"))**. -We retain **`g` = [Read the g field](json.get(value=`esc`, key="g"))**. - -We retain **p = "You are a Marqdo agent. Code is documentation: this runbook source and call site are your ground truth — not a hidden system prompt. When you cannot wire a capability, declare it in the description (待开发 / 模拟) instead of faking success."**. -We retain **p = p + a + up + b + task_s + d + site_s + c + tools_s + e + src + f + skill + g**. -Return *p*. - ---- - -## model_turn - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | required | Model resource or provider model identifier, as required by this operation | -| prompt | any | required | Prompt text or structured prompt expected by this adapter | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| stream_kind | any | "delta" | Streaming event projection selected by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{text,llm_calls,tokens}` for episode metrics; transport failures set `error` + `llm_calls=0` (never abort). | - -Use `model`, `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. - -One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{text,llm_calls,tokens}` for episode metrics; transport failures set `error` + `llm_calls=0` (never abort). -`stream_kind=plan` publishes protocol tokens onto the process trail (not the answer bubble). - -1. `stream` - We retain **`evs` = [Stream](> `model`.stream prompt=`prompt` echo=`echo` stream_kind=`stream_kind` )**. - We retain **`text` = [Collect](llm.collect(events=`evs`))**. - We retain **`tokens` = [Collect usage](llm.collect_usage(events=`evs`))**. - 1. `tokens` == None - We retain **tokens = 0**. - 2. * - **_ = 1** - We retain **err = None**. - We retain **calls = 1**. - 1. not `text` - We retain **`e0` = [At](at(value=`evs`, index=0))**. - We retain **`e0_s` = [Encode the structured value as JSON text](json.stringify(value=`e0`))**. - We retain **`e0_map` = [Starts with](text.starts_with(text=`e0_s`, prefix="{"))**. - 1. `e0_map` - We retain **`err` = [Read the message field](json.get(value=`e0`, key="message"))**. - 1. `err` - We retain **calls = 0**. - 2. * - **_ = 1** -2. * - We retain **`r` = [Ask](> `model`.ask prompt=`prompt` )**. - We retain **`r_s` = [Encode the structured value as JSON text](json.stringify(value=`r`))**. - We retain **`r_map` = [Starts with](text.starts_with(text=`r_s`, prefix="{"))**. - 1. `r_map` - We retain **`text` = [Read the text field](json.get(value=`r`, key="text"))**. - We retain **`tokens` = [Read the tokens field](json.get(value=`r`, key="tokens"))**. - We retain **`err` = [Read the error field](json.get(value=`r`, key="error"))**. - We retain **`fin` = [Read the finish field](json.get(value=`r`, key="finish"))**. - 1. `tokens` == None - We retain **`usage` = [Read the usage field](json.get(value=`r`, key="usage"))**. - 1. `usage` - We retain **`tokens` = [Read the total_tokens field](json.get(value=`usage`, key="total_tokens"))**. - 2. * - We retain **`text` = [Str](str(value=`r`))**. - We retain **tokens = 0**. - We retain **err = None**. - We retain **fin = None**. - 1. `tokens` == None - We retain **tokens = 0**. - 2. * - **_ = 1** - 1. `err` - We retain **calls = 0**. - 2. `fin` == "error" - We retain **calls = 0**. - 1. not `err` - We retain **err = "llm transport error"**. - 3. * - We retain **calls = 1**. - -`out` = - -| text | llm_calls | tokens | error | -|------|-----------|--------|-------| -| `text` | `calls` | `tokens` | `err` | - -Return *out*. - ---- - -## dump_step_context - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| agent | any | required | Agent configuration or receiver created by this package | -| task | any | "" | Structured task or text supplied to the agent | -| source_depth | any | "default" | Source-context depth; default follows the documented context budget | -| skill_depth | any | "default" | Skill-context depth; default follows the documented context budget | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Inspect what `build_step_context` would send — no LLM. Returns a map: `prompt`, `call_site`, `prompt_chars`, `truncated` (true when budget markers appear). Use for harness / debugging the code-as-doc pipeline. | - -Use `agent`, `task`="", `source_depth`="default", `skill_depth`="default" as the inputs for this operation. - -Inspect what `build_step_context` would send — no LLM. Returns a map: `prompt`, `call_site`, `prompt_chars`, `truncated` (true when budget markers appear). Use for harness / debugging the code-as-doc pipeline. - -We retain **`prompt` = [Build step context](build_step_context(agent=`agent`, task=`task`, source_depth=`source_depth`, skill_depth=`skill_depth`))**. -We retain **`site` = [Call site](agent_call_site())**. -We retain **`chars` = [Len](len(value=`prompt`))**. -We retain **`parts` = [Split](split(value=`prompt`, sep="[truncated"))**. -We retain **`n` = [Len](len(value=`parts`))**. -We retain **truncated = False**. -1. `n` > 1 - We retain **truncated = True**. -2. * - **_ = 1** - -`out` = - -| prompt | call_site | prompt_chars | truncated | -|--------|-----------|--------------|-----------| -| `prompt` | `site` | `chars` | `truncated` | - -Return *out*. - ---- - -## extract_tool_name - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Find a human-readable call line: `CALL:` or `调用:` / `调用:`. | - -Use `reply` as the inputs for this operation. - -Find a human-readable call line: `CALL:` or `调用:` / `调用:`. - -Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`text` = [Trim](trim(value=`reply`))**. -We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. -We retain **found = None**. - -- [line](遍历 `lines` 为 `line`) - We retain **`t` = [Trim](trim(value=`line`))**. - We retain **`parts` = [Split](split(value=`t`, sep=":"))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == CALL - We retain **found = rest**. - 2. `head` == 调用 - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - **_ = 1** - -Return *found*. - ---- - -## run_tool - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| tools | any | required | Explicit tool whitelist or tool-specification records | -| name | any | required | Name registered or looked up by this operation | -| arguments | any | None | Named argument record for the selected registered tool | -| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | -| logical_run_id | any | None | Stable logical execution identifier shared by retries | -| step_id | any | None | Identifier of the current workbook step | -| call_id | any | None | Identifier of this tool invocation | -| operation_id | any | None | Stable idempotent operation identifier | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Allowlist and ToolSpec prepare (M-A2), then invoke the runbook section via lib/subtask. Unauthorized or invalid-args calls return ToolResultV1 failure without spawning (0 executions). Mutating effects (write / execute / external_write) go through EffectLedger (M-A5a). State flow is prepared then started then spawn then committed, failed_no_effect, or unknown. Read tools skip the ledger. Matching idempotency_key and args_digest that already committed skips re-exec. | - -Use `tools`, `name`, `arguments`=None, `ledger_dir`=".marqdo/agent-effects", `logical_run_id`=None, `step_id`=None, `call_id`=None, `operation_id`=None as the inputs for this operation. - -Allowlist and ToolSpec prepare (M-A2), then invoke the runbook section via lib/subtask. -Unauthorized or invalid-args calls return ToolResultV1 failure without spawning (0 executions). -Mutating effects (write / execute / external_write) go through EffectLedger (M-A5a). -State flow is prepared then started then spawn then committed, failed_no_effect, or unknown. -Read tools skip the ledger. Matching idempotency_key and args_digest that already committed skips re-exec. - -Preparation and execution are separate stages. A registered ToolSpec is validated before a child task is created. If preparation fails, its structured failure is returned immediately. The operation identifiers connect retries to the same logical effect; changing arguments under an old identity must not be treated as a successful replay. Supplying these identifiers is the orchestration caller's responsibility. - -For effects that need a ledger, an existing committed record yields a receipt instead of another child execution. A previously started record without a completion record is uncertain: the code marks it unknown and requires reconciliation. It cannot infer that the external write failed merely because the process stopped. Read-only tools follow the shorter path and return the awaited child result. - -The compatibility path when no native agent plugin is found is narrower: it checks the name whitelist and spawns the runbook section. It does not provide ToolSpec validation or durable effect deduplication. Applications that require those guarantees must prepare the native plugin and inspect the returned status and receipt, rather than treating every nonempty value as proof of completion. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - **_ = 1** - -1. not `arguments` - We retain **`arguments` = [Empty map](table.empty_map())**. -2. * - **_ = 1** - -We retain **prepared = None**. -We retain **needs = False**. -We retain **opid = None**. -We retain **digest = None**. -We retain **idem = None**. -We retain **effect = "read"**. -We retain **receipt = None**. -We retain **raw = None**. - -1. not `p` - We retain **`allowed` = [Tool allowed](agent_tool_allowed(tools=`tools`, name=`name`))**. - 1. not `allowed` - We retain **msg = "Tool not allowed:"**. - Return *msg + name*. - 2. * - We retain **`id` = [Spawn](subtask.spawn(fn=`name`))**. - Return *[Wait](subtask.wait(id=`id`))*. - -We retain **`prepared` = [Tools prepare call](agent_tools_prepare_call(tool_id=`name`, tools=`tools`, arguments=`arguments`, call_id=`call_id`, operation_id=`operation_id`, logical_run_id=`logical_run_id`, step_id=`step_id`))**. -We retain **`pok` = [Read the ok field](json.get(value=`prepared`, key="ok"))**. -1. not `pok` - Return *prepared*. -2. * - **_ = 1** - -We retain **`needs` = [Read the needs_ledger field](json.get(value=`prepared`, key="needs_ledger"))**. -We retain **`call` = [Read the call field](json.get(value=`prepared`, key="call"))**. -We retain **`opid` = [Read the operation_id field](json.get(value=`call`, key="operation_id"))**. -We retain **`digest` = [Read the args_digest field](json.get(value=`prepared`, key="args_digest"))**. -We retain **`idem` = [Read the idempotency_key field](json.get(value=`prepared`, key="idempotency_key"))**. -We retain **`tspec` = [Read the spec field](json.get(value=`prepared`, key="spec"))**. -We retain **`effect` = [Read the effect field](json.get(value=`tspec`, key="effect"))**. - -1. `needs` - We retain **`led` = [Effects prepare](agent_effects_prepare(operation_id=`opid`, idempotency_key=`idem`, args_digest=`digest`, effect_class=`effect`, logical_run_id=`logical_run_id`, step_id=`step_id`, ledger_dir=`ledger_dir`))**. - We retain **`rec` = [Read the record field](json.get(value=`led`, key="record"))**. - We retain **`st0` = [Read the state field](json.get(value=`rec`, key="state"))**. - 1. `st0` == "committed" - We retain **`receipt` = [Read the result_ref field](json.get(value=`rec`, key="result_ref"))**. - 1. not `receipt` - We retain **receipt = "effect:" + `opid`**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=True, status="succeeded", summary="deduped committed effect; skipped re-exec", structured_content=`rec`, effect_receipt_ref=`receipt`))*. - 2. * - 1. `st0` == "reconciled_committed" - We retain **`receipt` = [Read the result_ref field](json.get(value=`rec`, key="result_ref"))**. - 1. not `receipt` - We retain **receipt = "effect:" + `opid`**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=True, status="succeeded", summary="deduped reconciled effect; skipped re-exec", structured_content=`rec`, effect_receipt_ref=`receipt`))*. - 2. * - 1. `st0` == "unknown" - We retain **receipt = "effect:" + `opid`**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="unknown_effect", summary="prior effect unknown; reconcile before retry", structured_content=`rec`, effect_receipt_ref=`receipt`))*. - 2. * - 1. `st0` == "started" - We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="unknown", note="retry saw started without commit; mark unknown", ledger_dir=`ledger_dir`))**. - We retain **receipt = "effect:" + `opid`**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="unknown_effect", summary="interrupted after started; reconcile before retry", structured_content=`rec`, effect_receipt_ref=`receipt`))*. - 2. * - 1. `st0` == "needs_input" - We retain **receipt = "effect:" + `opid`**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="needs_input", summary="effect needs_input; will not re-exec", structured_content=`rec`, effect_receipt_ref=`receipt`))*. - 2. * - We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="started", ledger_dir=`ledger_dir`))**. - **_ = 1** -2. * - **_ = 1** - -We retain **`id` = [Spawn](subtask.spawn(fn=`name`))**. -We retain **`raw` = [Wait](subtask.wait(id=`id`))**. -1. `needs` - We retain **`raw_s` = [Encode the structured value as JSON text](json.stringify(value=`raw`))**. - 1. not `raw` - We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="unknown", note="empty tool outcome; reconcile required", ledger_dir=`ledger_dir`))**. - We retain **receipt = "effect:" + `opid`**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="unknown_effect", summary="tool outcome empty after started; ledger=unknown", structured_content=`raw`, effect_receipt_ref=`receipt`))*. - 2. * - We retain **`is_err` = [Starts with](text.starts_with(text=`raw_s`, prefix="Tool not allowed"))**. - 1. `is_err` - We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="failed_no_effect", note="rejected before effect", ledger_dir=`ledger_dir`))**. - We retain **receipt = "effect:" + `opid`**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="failed", summary=`raw_s`, effect_receipt_ref=`receipt`))*. - 2. * - We retain **receipt = "effect:" + `opid`**. - We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="committed", result_ref=`receipt`, ledger_dir=`ledger_dir`))**. - Return *[Tools wrap result](agent_tools_wrap_result(ok=True, status="succeeded", summary="tool executed; effect committed", structured_content=`raw`, effect_receipt_ref=`receipt`))*. -2. * - Return *raw*. - -## tools_register - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| spec | any | None | One structured tool or operation specification | -| specs | any | None | List of structured specifications | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Register ToolSpecV1 document(s). Unsupported schema keywords are refused. | - -Use `spec`=None, `specs`=None as the inputs for this operation. - -Register ToolSpecV1 document(s). Unsupported schema keywords are refused. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Tools register](agent_tools_register(spec=`spec`, specs=`specs`))*. - -## tools_clear - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Clear the in-process ToolSpec registry (tests / reseeding). | - -Clear the in-process ToolSpec registry (tests / reseeding). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Tools clear](agent_tools_clear())*. - -## tools_search - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| query | any | "" | Text used to search the bounded catalog or tool registry | -| tools | any | None | Explicit tool whitelist or tool-specification records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Search authorized registered tools (summaries only). | - -Use `query`="", `tools`=None as the inputs for this operation. - -Search authorized registered tools (summaries only). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Tools search](agent_tools_search(query=`query`, tools=`tools`))*. - -## tools_describe - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| tools | any | None | Explicit tool whitelist or tool-specification records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Return full ToolSpecV1 for an authorized tool id. | - -Use `id`, `tools`=None as the inputs for this operation. - -Return full ToolSpecV1 for an authorized tool id. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Tools describe](agent_tools_describe(id=`id`, tools=`tools`))*. - -## tools_register_eng_defaults - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Seed the five engineering tool specs (`tool_find` … `tool_summarize`). | - -Seed the five engineering tool specs (`tool_find` … `tool_summarize`). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Tools register eng defaults](agent_tools_register_eng_defaults())*. - -## tools_prepare_call - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| tool_id | any | required | Registered tool identifier, not an arbitrary function name | -| arguments | any | None | Named argument record for the selected registered tool | -| tools | any | None | Explicit tool whitelist or tool-specification records | -| call_id | any | None | Identifier of this tool invocation | -| operation_id | any | None | Stable idempotent operation identifier | -| logical_run_id | any | None | Stable logical execution identifier shared by retries | -| step_id | any | None | Identifier of the current workbook step | -| idempotency_key | any | None | Key identifying the same logical effect across retries | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side effects). Also returns `args_digest` / `idempotency_key` / `needs_ledger` for EffectLedger wiring. | - -Use `tool_id`, `arguments`=None, `tools`=None, `call_id`=None, `operation_id`=None, `logical_run_id`=None, `step_id`=None, `idempotency_key`=None as the inputs for this operation. - -Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side effects). -Also returns `args_digest` / `idempotency_key` / `needs_ledger` for EffectLedger wiring. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Tools prepare call](agent_tools_prepare_call(tool_id=`tool_id`, arguments=`arguments`, tools=`tools`, call_id=`call_id`, operation_id=`operation_id`, logical_run_id=`logical_run_id`, step_id=`step_id`, idempotency_key=`idempotency_key`))*. - -## output_build - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| status | any | "succeeded" | Domain status recorded in the structured result | -| text | any | "" | Text supplied to the transformation or adapter | -| format | any | "markdown" | Output representation selected by the caller | -| answer | any | None | Final answer text to project into the output | -| artifacts | any | None | Structured artifact references accompanying the result | -| citations | any | None | Source references accompanying the result | -| validation | any | None | Explicit validation evidence; not a self-reported success flag | -| finish_reason | any | None | Reason the operation stopped | -| recovery_options | any | None | Allowed recovery choices for the caller | -| channels | any | None | Structured output-channel records | -| allow_passed_without_report | any | False | Whether policy permits a passed status without a validation report | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Build an `AgentOutputV1` document (M-A4). `validation.status=passed` requires `report_ref`. | - -Use `status`="succeeded", `text`="", `format`="markdown", `answer`=None, `artifacts`=None, `citations`=None, `validation`=None, `finish_reason`=None, `recovery_options`=None, `channels`=None, `allow_passed_without_report`=False as the inputs for this operation. - -Build an `AgentOutputV1` document (M-A4). `validation.status=passed` requires `report_ref`. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Output build](agent_output_build(status=`status`, text=`text`, format=`format`, answer=`answer`, artifacts=`artifacts`, citations=`citations`, validation=`validation`, finish_reason=`finish_reason`, recovery_options=`recovery_options`, channels=`channels`, allow_passed_without_report=`allow_passed_without_report`))*. - -## output_apply_policy - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| status | any | "succeeded" | Domain status recorded in the structured result | -| text | any | "" | Text supplied to the transformation or adapter | -| format | any | "markdown" | Output representation selected by the caller | -| answer | any | None | Final answer text to project into the output | -| artifacts | any | None | Structured artifact references accompanying the result | -| citations | any | None | Source references accompanying the result | -| validation | any | None | Explicit validation evidence; not a self-reported success flag | -| policy | any | None | Policy data governing this operation | -| schema | any | None | Structured schema used to validate or project output | -| schema_version | any | None | Version of the structured schema | -| finish_reason | any | None | Reason the operation stopped | -| recovery_options | any | None | Allowed recovery choices for the caller | -| channels | any | None | Structured output-channel records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply `ResponsePolicy` (detail / max_chars / max_output_tokens / artifact_allowed) to an AgentOutputV1 or raw text. | - -Use `status`="succeeded", `text`="", `format`="markdown", `answer`=None, `artifacts`=None, `citations`=None, `validation`=None, `policy`=None, `schema`=None, `schema_version`=None, `finish_reason`=None, `recovery_options`=None, `channels`=None as the inputs for this operation. - -Apply `ResponsePolicy` (detail / max_chars / max_output_tokens / artifact_allowed) to an AgentOutputV1 or raw text. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Output apply policy](agent_output_apply_policy(status=`status`, text=`text`, format=`format`, answer=`answer`, artifacts=`artifacts`, citations=`citations`, validation=`validation`, policy=`policy`, schema=`schema`, schema_version=`schema_version`, finish_reason=`finish_reason`, recovery_options=`recovery_options`, channels=`channels`))*. - -## output_channel_event - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| channel | any | required | Output channel identifier | -| delta | any | "" | Incremental text or record update | -| resource_id | any | None | Referenced resource identifier | -| meta | any | None | Metadata associated with the structured item | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Split a stream delta by channel. Only `answer` sets `append_to_chat=true`. | - -Use `channel`, `delta`="", `resource_id`=None, `meta`=None as the inputs for this operation. - -Split a stream delta by channel. Only `answer` sets `append_to_chat=true`. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Output channel event](agent_output_channel_event(channel=`channel`, delta=`delta`, resource_id=`resource_id`, meta=`meta`))*. - -## output_project_conclusion - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| document | any | "" | Document record being packed or projected | -| text | any | "" | Text supplied to the transformation or adapter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Deterministic chat projection from `# 结论` / `# conclusion` (F01 transition). Falls back to the first body paragraph. | - -Use `document`="", `text`="" as the inputs for this operation. - -Deterministic chat projection from `# 结论` / `# conclusion` (F01 transition). Falls back to the first body paragraph. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Output project conclusion](agent_output_project_conclusion(document=`document`, text=`text`))*. - -## context_pack_build - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| items | any | None | Ordered context or output items | -| budget_tokens | any | 8000 | Maximum context token budget | -| output_reserve_pct | any | 20 | Percentage of the context budget reserved for output | -| compact_threshold_pct | any | 70 | Budget usage threshold triggering compaction | -| goal | any | None | Human task goal represented by this operation | -| constraints | any | None | Explicit task constraints | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Assemble `ContextPackV2` with origin/trust/priority. Web/tool items cannot be `trust=trusted`. | - -Use `items`=None, `budget_tokens`=8000, `output_reserve_pct`=20, `compact_threshold_pct`=70, `goal`=None, `constraints`=None as the inputs for this operation. - -Assemble `ContextPackV2` with origin/trust/priority. Web/tool items cannot be `trust=trusted`. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Context pack build](agent_context_pack_build(items=`items`, budget_tokens=`budget_tokens`, output_reserve_pct=`output_reserve_pct`, compact_threshold_pct=`compact_threshold_pct`, goal=`goal`, constraints=`constraints`))*. - -## context_pack_compact - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| items | any | None | Ordered context or output items | -| budget_tokens | any | 8000 | Maximum context token budget | -| output_reserve_pct | any | 20 | Percentage of the context budget reserved for output | -| compact_threshold_pct | any | 70 | Budget usage threshold triggering compaction | -| goal | any | None | Human task goal represented by this operation | -| constraints | any | None | Explicit task constraints | -| schema | any | None | Structured schema used to validate or project output | -| schema_version | any | None | Version of the structured schema | -| available_tokens | any | None | Token budget available to the next turn | -| used_tokens | any | None | Observed token usage, not a guessed count | -| source_event_range | any | None | Event range represented by a compacted context item | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Compact over-threshold packs; retain goal/constraints/pending_write/plan/trusted anchors (F19). | - -Use `items`=None, `budget_tokens`=8000, `output_reserve_pct`=20, `compact_threshold_pct`=70, `goal`=None, `constraints`=None, `schema`=None, `schema_version`=None, `available_tokens`=None, `used_tokens`=None, `source_event_range`=None as the inputs for this operation. - -Compact over-threshold packs; retain goal/constraints/pending_write/plan/trusted anchors (F19). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Context pack compact](agent_context_pack_compact(items=`items`, budget_tokens=`budget_tokens`, output_reserve_pct=`output_reserve_pct`, compact_threshold_pct=`compact_threshold_pct`, goal=`goal`, constraints=`constraints`, schema=`schema`, schema_version=`schema_version`, available_tokens=`available_tokens`, used_tokens=`used_tokens`, source_event_range=`source_event_range`))*. - -## render_workbook_skeleton - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| goal | any | required | Human task goal represented by this operation | -| skeleton | any | "single" | Workbook source template to instantiate | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. On success the parent chooses DONE; runtime `agent_workbook_solidify` freezes the answer. | - -Use `goal`, `skeleton`="single" as the inputs for this operation. - -Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. On success the parent chooses DONE; runtime `agent_workbook_solidify` freezes the answer. - -This function produces source text, not a running worker. The caller owns choosing a destination, writing that text, starting the child, and inspecting the child's exit status and returned value. Generation alone neither proves the task solved nor freezes a reusable skill. The templates are data in this function: their marker characters must remain literal until a later Marqdo process parses the generated workbook. - -The common header names the libraries the generated program imports. Its Goal section explains where the parent goal is embedded, while its Solidify section explains who may freeze the answer. The entry begins by loading environment configuration. This makes the generated program usable by the existing workbook runner without adding a second template interpreter or hidden workflow format. - -The single-worker branch creates one model and an empty tools list, then asks one worker to solve the embedded task. The empty whitelist is intentional: mentioning a capability in the task does not register a callable tool. A worker must answer directly unless the author later adds an actual tool definition and explicitly supplies it. The returned child value is the result field from the worker's structured turn. - -The dual-worker branch uses the same model configuration for two roles. A research worker first returns notes. Those notes are serialized into the writing worker's task, and the writing worker returns the final text. The roles describe sequencing; they do not imply independent evidence collection, browser access, or any permission beyond the configured whitelist and runtime grants. - -The goal is JSON-quoted before it is inserted into either source template. Quotes and line breaks in a user's goal therefore stay data rather than becoming workbook statements. The surrounding fragments retain the exact original newlines, imports and return markers. When changing this generator, review both complete outputs, parse them as ordinary source, and test goals containing quotes, backticks and newlines. - -Environment variables are looked up when the child runs. No credentials are fetched or written by this generator. Missing model configuration consequently belongs to the execution result, not to template construction. A parent should await that result before deciding RUN, CONTINUE or DONE. Successful execution may then be solidified by the existing runtime mechanism; this function does not silently promote its generated text into trusted knowledge. - -We retain **`q` = [Quote the JSON text value](json.quote(text=`goal`))**. -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -`_literal_esc_h_lines` = - -| line | -|---| -| "---" | -| "title: agent workbook" | -| "import:" | -| " llm: ext/ai/llm.mq.md" | -| " agent: ext/ai/agent.mq.md" | -| " json: lib/json.mq.md" | -| " sys: lib/sys.mq.md" | -| " table: lib/table.mq.md" | -| " wb: lib/writeback.mq.md" | -| " subtask: lib/subtask.mq.md" | -| "---" | -| "" | -| "# Goal" | -| "" | -| "Parent goal is embedded as JSON in # main." | -| "" | -| "## Solidify" | -| "" | -| "When the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE)." | -| "" | -| "# main" | -| "" | -| "> llm.load_env" | -| "" | -| "" | - -Join exactly those lines into **_literal_esc_h_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_h_lines`, sep="\n"))**. - -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -`_literal_esc_s1_lines` = - -| line | -|---| -| "**\x60env_model\x60 = > sys.env_get name=\"OPENAI_MODEL\"**" | -| "**\x60env_base\x60 = > sys.env_get name=\"OPENAI_BASE_URL\"**" | -| "**\x60env_key\x60 = > sys.env_get name=\"OPENAI_API_KEY\"**" | -| "**\x60model\x60 = > llm.create model=\x60env_model\x60 base_url=\x60env_base\x60 api_key=\x60env_key\x60 backend=\"openai-compatible\" name=\"workbook\"**" | -| "" | - -Join exactly those lines into **_literal_esc_s1_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_s1_lines`, sep="\n"))**. - -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -`_literal_esc_s3_lines` = - -| line | -|---| -| "**\x60worker\x60 = > agent.agent model=\x60model\x60 tools=\x60tools\x60 standing=\"You are a workbook worker. tools=[] means never CALL. Finish the task with a direct final answer; do not invent tools.\"**" | -| "" | - -Join exactly those lines into **_literal_esc_s3_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_s3_lines`, sep="\n"))**. - -The following record names each literal field without a JSON construction chain. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "d10" | "**\x60wt\x60 = \x60wt\x60 + \x60ns\x60**\n" | -| 2 | "d11" | "**\x60out\x60 = > \x60writer\x60.step task=\x60wt\x60 stream=True**\n" | -| 3 | "d11b" | "**\x60text\x60 = > json.get value=\x60out\x60 key=\"result\"**\n" | -| 4 | "d12" | "*\x60text\x60*\n" | -| 5 | "d3" | "**\x60research\x60 = > agent.agent model=\x60model\x60 tools=\x60tools\x60 standing=\"You gather facts for the goal. Be concise. Do not invent tools.\"**\n" | -| 6 | "d3b" | "**\x60writer\x60 = > agent.agent model=\x60model\x60 tools=\x60tools\x60 standing=\"You write the final answer from research notes. Do not invent tools.\"**\n" | -| 7 | "d4" | "**\x60wrap\x60 = > json.parse text={\"task\":" | -| 8 | "d5" | "}**\n" | -| 9 | "d6" | "**\x60task\x60 = > json.get value=\x60wrap\x60 key=\"task\"**\n" | -| 10 | "d7" | "**\x60notes\x60 = > \x60research\x60.step task=\x60task\x60 stream=True**\n" | -| 11 | "d8" | "**\x60ns\x60 = > json.stringify value=\x60notes\x60**\n" | -| 12 | "d9" | "**\x60wt\x60 = \"Write the final answer. Research notes:\"**\n" | -| 13 | "h" | `_literal_esc_h_text` | -| 14 | "s1" | `_literal_esc_s1_text` | -| 15 | "s2" | "**\x60tools\x60 = > table.empty_list**\n" | -| 16 | "s3" | `_literal_esc_s3_text` | -| 17 | "s4" | "**\x60wrap\x60 = > json.parse text={\"task\":" | -| 18 | "s5" | "}**\n" | -| 19 | "s6" | "**\x60task\x60 = > json.get value=\x60wrap\x60 key=\"task\"**\n" | -| 20 | "s7" | "**\x60out\x60 = > \x60worker\x60.step task=\x60task\x60 stream=True**\n" | -| 21 | "s7b" | "**\x60text\x60 = > json.get value=\x60out\x60 key=\"result\"**\n" | -| 22 | "s8" | "*\x60text\x60*\n" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`h` = [Read the h field](json.get(value=`esc`, key="h"))**. -We retain **`s1` = [Read the s1 field](json.get(value=`esc`, key="s1"))**. -We retain **`s2` = [Read the s2 field](json.get(value=`esc`, key="s2"))**. - -1. `skeleton` == dual - We retain **`s3` = [Read the d3 field](json.get(value=`esc`, key="d3"))**. - We retain **`s3b` = [Read the d3b field](json.get(value=`esc`, key="d3b"))**. - We retain **`s4` = [Read the d4 field](json.get(value=`esc`, key="d4"))**. - We retain **`s5` = [Read the d5 field](json.get(value=`esc`, key="d5"))**. - We retain **`s6` = [Read the d6 field](json.get(value=`esc`, key="d6"))**. - We retain **`s7` = [Read the d7 field](json.get(value=`esc`, key="d7"))**. - We retain **`s8` = [Read the d8 field](json.get(value=`esc`, key="d8"))**. - We retain **`s9` = [Read the d9 field](json.get(value=`esc`, key="d9"))**. - We retain **`s10` = [Read the d10 field](json.get(value=`esc`, key="d10"))**. - We retain **`s11` = [Read the d11 field](json.get(value=`esc`, key="d11"))**. - We retain **`s11b` = [Read the d11b field](json.get(value=`esc`, key="d11b"))**. - We retain **`s12` = [Read the d12 field](json.get(value=`esc`, key="d12"))**. - Return *h + s1 + s2 + s3 + s3b + s4 + q + s5 + s6 + s7 + s8 + s9 + s10 + s11 + s11b + s12*. -2. * - We retain **`s3` = [Read the s3 field](json.get(value=`esc`, key="s3"))**. - We retain **`s4` = [Read the s4 field](json.get(value=`esc`, key="s4"))**. - We retain **`s5` = [Read the s5 field](json.get(value=`esc`, key="s5"))**. - We retain **`s6` = [Read the s6 field](json.get(value=`esc`, key="s6"))**. - We retain **`s7` = [Read the s7 field](json.get(value=`esc`, key="s7"))**. - We retain **`s7b` = [Read the s7b field](json.get(value=`esc`, key="s7b"))**. - We retain **`s8` = [Read the s8 field](json.get(value=`esc`, key="s8"))**. - Return *h + s1 + s2 + s3 + s4 + q + s5 + s6 + s7 + s7b + s8*. - ---- - -## inspect_workbook - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| exit_code | any | None | Child process or tool exit status | -| value | any | None | Value supplied to this operation; immutable transformations return a new value | -| stdout | any | None | Captured standard output | -| stderr | any | None | Captured standard error | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Structured observation for the parent developer-agent: source, named writeback slots, exit code, optional child return value, and quiet-captured I/O. | - -Use `path`, `exit_code`=None, `value`=None, `stdout`=None, `stderr`=None as the inputs for this operation. - -Structured observation for the parent developer-agent: source, named writeback slots, exit code, optional child return value, and quiet-captured I/O. - -We retain **`source` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. -We retain **`slots` = [Scan path](wb.scan_path(path=`path`))**. - -`obs` = - -| path | source | slots | exit_code | -|------|--------|-------|-----------| -| `path` | `source` | `slots` | `exit_code` | - -1. `value` - We retain **`obs` = [Set the value field in the new record](table.put(in=`obs`, at="value", value=`value`))**. -2. * - **_ = 1** -1. `stdout` - We retain **`obs` = [Set the stdout field in the new record](table.put(in=`obs`, at="stdout", value=`stdout`))**. -2. * - **_ = 1** -1. `stderr` - We retain **`obs` = [Set the stderr field in the new record](table.put(in=`obs`, at="stderr", value=`stderr`))**. -2. * - **_ = 1** - -We retain **last_ok = None**. -We retain **last_error = None**. -- [slot](遍历 `slots` 为 `slot`) - We retain **`k` = [Read the key field](json.get(value=`slot`, key="key"))**. - We retain **`body` = [Read the body field](json.get(value=`slot`, key="body"))**. - 1. `k` == "ok" - We retain **last_ok = body**. - 2. `k` == "error" - We retain **last_error = body**. - 3. * - **_ = 1** - -1. `last_ok` - We retain **`obs` = [Set the last_ok field in the new record](table.put(in=`obs`, at="last_ok", value=`last_ok`))**. -2. * - **_ = 1** - -1. `last_error` - We retain **`obs` = [Set the last_error field in the new record](table.put(in=`obs`, at="last_error", value=`last_error`))**. -2. * - **_ = 1** - -Return *obs*. - ---- - -## trial - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| source | any | None | Source text inspected or prepared by this operation | -| root | any | None | Explicit root directory for discovery or isolated execution | -| write_path | any | None | Explicit output path or None | -| text | any | None | Text supplied to the transformation or adapter | -| commit | any | True | Whether to promote trial changes after successful validation | -| profile | any | "default" | Capability profile selected for the trial | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Opt-in CoW trial (O1): open → optional upper write → optional run → diff → commit on success else discard. Host tree unchanged until a successful commit. Return map is a GFM table (link-index readable). | - -Use `path`=None, `source`=None, `root`=None, `write_path`=None, `text`=None, `commit`=True, `profile`="default" as the inputs for this operation. - -Opt-in CoW trial (O1): open → optional upper write → optional run → diff → commit on success else discard. -Host tree unchanged until a successful commit. Return map is a GFM table (link-index readable). - -We retain **`sb` = [Open](sandbox.open(root=`root`, profile=`profile`))**. -We retain **`id` = [Read the id field](json.get(value=`sb`, key="id"))**. -We retain **`prof` = [Read the profile field](json.get(value=`sb`, key="profile"))**. -We retain **ok = True**. -We retain **stdout = ""**. -We retain **stderr = ""**. - -1. `write_path` - 1. `text` - We **[Write](sandbox.write(id=`id`, path=`write_path`, text=`text`))**. - 2. * - **_ = 1** -2. * - **_ = 1** - -1. `source` - We retain **`ret` = [Run](sandbox.run(id=`id`, source=`source`))**. - We retain **`ok` = [Read the ok field](json.get(value=`ret`, key="ok"))**. - We retain **`stdout` = [Read the stdout field](json.get(value=`ret`, key="stdout"))**. - We retain **`stderr` = [Read the stderr field](json.get(value=`ret`, key="stderr"))**. -2. `path` - We retain **`ret` = [Run](sandbox.run(id=`id`, path=`path`))**. - We retain **`ok` = [Read the ok field](json.get(value=`ret`, key="ok"))**. - We retain **`stdout` = [Read the stdout field](json.get(value=`ret`, key="stdout"))**. - We retain **`stderr` = [Read the stderr field](json.get(value=`ret`, key="stderr"))**. -3. * - **_ = 1** - -We retain **`pending` = [Diff](sandbox.diff(id=`id`))**. -We retain **committed = False**. - -1. `ok` - 1. `commit` - We **[Commit](sandbox.commit(id=`id`))**. - We retain **committed = True**. - 2. * - We **[Discard](sandbox.discard(id=`id`))**. -2. * - We **[Discard](sandbox.discard(id=`id`))**. - -**out = ** - -| ok | committed | diff | stdout | stderr | id | profile | -|----|-----------|------|--------|--------|-----|---------| -| `ok` | `committed` | `pending` | `stdout` | `stderr` | `id` | `prof` | - -Return *out*. - -## step_route - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| kind | any | "default" | Operation or factorization kind listed in this function's behavior | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | O3: map step class (`lookup` | `patch` | `sandbox_run` | `net` | `default`) → Adaptive Routing backend. Authority is the GFM table in `ext/ai/policies/step-route.mq.md` (mirrored here for offline reads). | - -Use `kind`="default" as the inputs for this operation. - -O3: map step class (`lookup` | `patch` | `sandbox_run` | `net` | `default`) → Adaptive Routing backend. -Authority is the GFM table in `ext/ai/policies/step-route.mq.md` (mirrored here for offline reads). - -1. `kind` == "lookup" - We retain **backend = "marqdo"**. -2. `kind` == "patch" - We retain **backend = "small-llm"**. -3. `kind` == "sandbox_run" - We retain **backend = "marqdo"**. -4. `kind` == "net" - We retain **backend = "llm"**. -5. * - We retain **backend = "auto"**. - -We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value=`kind`))**. -We retain **`out` = [Set the backend field in the new record](table.put(in=`out`, at="backend", value=`backend`))**. -Return *out*. - -## await_workbook - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| sandbox | any | False | Whether to use the CoW trial path | -| sandbox_root | any | None | Root directory of the CoW trial | -| sandbox_profile | any | "default" | Capability profile for CoW execution | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Spawn a workbook file (quiet by default), wait, and inspect. With `sandbox=True`, run via `## trial` first (commit on ok); host unchanged until that commit. | - -Use `path`, `sandbox`=False, `sandbox_root`=None, `sandbox_profile`="default" as the inputs for this operation. - -Spawn a workbook file (quiet by default), wait, and inspect. -With `sandbox=True`, run via `## trial` first (commit on ok); host unchanged until that commit. - -1. `sandbox` - We retain **`tr` = [Trial](trial(path=`path`, root=`sandbox_root`, profile=`sandbox_profile`, commit=True))**. - We retain **`ok` = [Read the ok field](json.get(value=`tr`, key="ok"))**. - We retain **`stdout` = [Read the stdout field](json.get(value=`tr`, key="stdout"))**. - We retain **`stderr` = [Read the stderr field](json.get(value=`tr`, key="stderr"))**. - 1. `ok` - We retain **code = 0**. - 2. * - We retain **code = 1**. - We retain **value = stdout**. - We retain **`obs` = [Inspect workbook](inspect_workbook(path=`path`, exit_code=`code`, value=`value`, stdout=`stdout`, stderr=`stderr`))**. - **out = ** - - | code | value | observation | sandbox | - |------|-------|-------------|---------| - | `code` | `value` | `obs` | `tr` | - - Return *out*. -2. * - We retain **`id` = [Spawn](subtask.spawn(path=`path`))**. - We retain **`waited` = [Wait](subtask.wait(id=`id`))**. - We retain **`code` = [Read the code field](json.get(value=`waited`, key="code"))**. - We retain **`value` = [Read the value field](json.get(value=`waited`, key="value"))**. - We retain **`stdout` = [Read the stdout field](json.get(value=`waited`, key="stdout"))**. - We retain **`stderr` = [Read the stderr field](json.get(value=`waited`, key="stderr"))**. - We retain **`obs` = [Inspect workbook](inspect_workbook(path=`path`, exit_code=`code`, value=`value`, stdout=`stdout`, stderr=`stderr`))**. - **out = ** - - | code | value | observation | - |------|-------|-------------| - | `code` | `value` | `obs` | - - Return *out*. - ---- - -## text_head_lines - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | any | required | Text supplied to the transformation or adapter | -| max_lines | any | 80 | Maximum retained lines in the text excerpt | -| max_chars | any | 4000 | Maximum retained characters in the text excerpt | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Keep at most the requested leading lines of text when preparing a bounded context excerpt. | - -Use `text`, `max_lines`=80, `max_chars`=4000 as the inputs for this operation. - -Keep at most the requested leading lines of text when preparing a bounded context excerpt. - -Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`raw` = [Str](str(value=`text`))**. -We retain **`lines` = [Split](split(value=`raw`, sep=`nl`))**. -We retain **`acc` = [Empty list](table.empty_list())**. -We retain **chars = 0**. -We retain **count = 0**. -- [line](遍历 `lines` 为 `line`) - 1. `count` < `max_lines` - We retain **`ln` = [Len](len(value=`line`))**. - We retain **next = chars + ln**. - 1. `next` > `max_chars` - We retain **count = max_lines**. - 2. * - We retain **`acc` = [Append this item to the new list](table.append(list=`acc`, item=`line`))**. - We retain **chars = next**. - We retain **count = count + 1**. - 2. * - **_ = 1** -Return *[Join](join(value=`acc`, sep=`nl`))*. - ---- - -## text_tail_lines - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | any | required | Text supplied to the transformation or adapter | -| max_lines | any | 40 | Maximum retained lines in the text excerpt | -| max_chars | any | 2000 | Maximum retained characters in the text excerpt | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Keep at most the requested trailing lines of text when preparing a bounded context excerpt. | - -Use `text`, `max_lines`=40, `max_chars`=2000 as the inputs for this operation. - -Keep at most the requested trailing lines of text when preparing a bounded context excerpt. - -Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`raw` = [Str](str(value=`text`))**. -We retain **`lines` = [Split](split(value=`raw`, sep=`nl`))**. -We retain **`n` = [Len](len(value=`lines`))**. -We retain **start = n - max_lines**. -1. `start` < 0 - We retain **start = 0**. -2. * - **_ = 1** -We retain **`acc` = [Empty list](table.empty_list())**. -We retain **i = 0**. -We retain **chars = 0**. -- [line](遍历 `lines` 为 `line`) - 1. `i` >= `start` - We retain **`ln` = [Len](len(value=`line`))**. - We retain **next = chars + ln**. - 1. `next` > `max_chars` - We retain **i = n**. - 2. * - We retain **`acc` = [Append this item to the new list](table.append(list=`acc`, item=`line`))**. - We retain **chars = next**. - 2. * - **_ = 1** - We retain **i = i + 1**. -Return *[Join](join(value=`acc`, sep=`nl`))*. - ---- - -## strip_html_comments - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | any | required | Text supplied to the transformation or adapter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Drop `` blocks (including marqdo-out bodies) so parent excerpts stay structural. | - -Use `text` as the inputs for this operation. - -Drop `` blocks (including marqdo-out bodies) so parent excerpts stay structural. - -This is a line-oriented removal helper for workbook inspection. It tracks whether a comment span is open across lines, so hidden author notes do not inflate the excerpt. It is not an HTML parser and does not sanitize rendered pages. - -Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`raw` = [Str](str(value=`text`))**. -We retain **`lines` = [Split](split(value=`raw`, sep=`nl`))**. -We retain **`acc` = [Empty list](table.empty_list())**. -We retain **skip = None**. -- [line](遍历 `lines` 为 `line`) - 1. `skip` - We retain **`end_parts` = [Split](split(value=`line`, sep="-->"))**. - We retain **`en` = [Len](len(value=`end_parts`))**. - 1. `en` > 1 - We retain **skip = None**. - 2. * - **_ = 1** - 2. * - We retain **`start_parts` = [Split](split(value=`line`, sep=""))**. - We retain **`en` = [Len](len(value=`end_parts`))**. - 1. `en` > 1 - We retain **skip = None**. - 2. * - We retain **skip = 1**. - 2. * - We retain **`acc` = [Append this item to the new list](table.append(list=`acc`, item=`line`))**. -Return *[Join](join(value=`acc`, sep=`nl`))*. - ---- - -## workbook_source_excerpt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| source | any | required | Source text inspected or prepared by this operation | -| max_lines | any | 80 | Maximum retained lines in the text excerpt | -| max_chars | any | 4000 | Maximum retained characters in the text excerpt | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Select a bounded excerpt from workbook source for the next planning observation. | - -Use `source`, `max_lines`=80, `max_chars`=4000 as the inputs for this operation. - -Select a bounded excerpt from workbook source for the next planning observation. - -We retain **`clean` = [Strip html comments](strip_html_comments(text=`source`))**. -Return *[Text head lines](text_head_lines(text=`clean`, max_lines=`max_lines`, max_chars=`max_chars`))*. - ---- - -## workbook_excerpt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| max_lines | any | 80 | Maximum retained lines in the text excerpt | -| max_chars | any | 4000 | Maximum retained characters in the text excerpt | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read a workbook excerpt using explicit depth and length budgets. | - -Use `path`, `max_lines`=80, `max_chars`=4000 as the inputs for this operation. - -Read a workbook excerpt using explicit depth and length budgets. - -We retain **`src` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. -Return *[Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=`max_lines`, max_chars=`max_chars`))*. - ---- - -## workbook_read - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| depth | any | "default" | Requested context or discovery depth | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read a workbook by path and expose the budgeted view required by the planner. | - -Use `path`, `depth`="default" as the inputs for this operation. - -We retain **`src` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. -1. `depth` == deep - Return *[Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=200, max_chars=12000))*. -2. * - Return *[Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=80, max_chars=4000))*. - ---- - -## lib_catalog - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Callable dotted names (whitelist for `CALL:lib…`) plus static module file list for workbook imports. Parent also exposes evidence tools `corpus_search` / `mcp_list_tools` / `mcp_call` (not authority). | - -Callable dotted names (whitelist for `CALL:lib…`) plus static module file list for workbook imports. Parent also exposes evidence tools `corpus_search` / `mcp_list_tools` / `mcp_call` (not authority). - -The import files are a list of source modules. They are not all enabled as direct parent tools. - -The two lists answer different questions: files can be imported into a workbook, while callable records name the limited actions understood by the parent dispatcher. This is not a complete catalog of the standard library. New source functions remain discoverable through the normal source catalog and MLSP; adding a file here does not grant it execution permission. - -`_literal_files` = - -| file | -|---| -| "fs.mq.md" | -| "json.mq.md" | -| "subtask.mq.md" | -| "sys.mq.md" | -| "writeback.mq.md" | -| "text.mq.md" | -| "time.mq.md" | -| "math.mq.md" | -| "net.mq.md" | -| "table.mq.md" | -| "plugin.mq.md" | -| "foreign.mq.md" | - -Only the following names belong to this parent dispatcher. The description explains the action; -a name still passes through the normal allowlist and its effect boundary at execution. - -`_literal_callable` = - -| @ | desc | name | -|---|---|---| -| 1 | "Read UTF-8 text file" | "lib.fs.read_text" | -| 2 | "Path exists?" | "lib.fs.exists" | -| 3 | "List directory entries" | "lib.fs.list_dir" | -| 4 | "Parse JSON text" | "lib.json.parse" | -| 5 | "Serialize JSON" | "lib.json.stringify" | -| 6 | "Process working directory" | "lib.sys.cwd" | -| 7 | "Local markdown/text keyword search (evidence)" | "corpus_search" | -| 8 | "List tools from MCP JSON fixture" | "mcp_list_tools" | -| 9 | "Call a tool from MCP JSON fixture" | "mcp_call" | - -The note is returned with both lists, so a caller can distinguish an importable file from an -allowed CALL name. Evidence adapters read fixtures here; they do not establish workbook authority. - -`out` = - -| callable | files | note | -|---|---|---| -| `_literal_callable` | `_literal_files` | "Direct CALL:lib.. + optional ARGS:{json} for whitelist only. Or import via frontmatter > lib/.mq.md then PATCH / scratch_tool_write. Evidence tools: CALL:corpus_search \| mcp_list_tools \| mcp_call (fixture RAG/MCP) — workbook .mq.md remains authority." | -Return *out*. - ---- - -## corpus_search - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| query | any | required | Text used to search the bounded catalog or tool registry | -| root | any | ".marqdo/agent-corpus" | Explicit root directory for discovery or isolated execution | -| limit | any | 6 | Maximum returned entries or candidates; this is not a success threshold | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Local keyword search over `.md` / `.mq.md` / `.txt` under `root`. Returns ranked excerpts. Evidence only — runnable workbook / OKF skill stays authority (`authority=workbook`). Ensures the native agent plugin is loaded so plain `marqdo run` (without constructing `# agent`) can call this. | - -Use `query`, `root`=".marqdo/agent-corpus", `limit`=6 as the inputs for this operation. - -Local keyword search over `.md` / `.mq.md` / `.txt` under `root`. Returns ranked excerpts. Evidence only — runnable workbook / OKF skill stays authority (`authority=workbook`). - -Ensures the native agent plugin is loaded so plain `marqdo run` (without constructing `# agent`) can call this. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Corpus search](agent_corpus_search(query=`query`, root=`root`, limit=`limit`))*. - ---- - -## mcp_list_tools - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| fixture | any | required | Deterministic fixture data used for offline behavior | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List tools from an offline MCP-shaped JSON fixture (`tools` array). Evidence only. | - -Use `fixture` as the inputs for this operation. - -List tools from an offline MCP-shaped JSON fixture (`tools` array). Evidence only. - -Return *[Mcp fixture](agent_mcp_fixture(action="list", fixture=`fixture`))*. - ---- - -## mcp_call - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | required | Name registered or looked up by this operation | -| fixture | any | required | Deterministic fixture data used for offline behavior | -| arguments | any | None | Named argument record for the selected registered tool | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Call a named tool from a MCP-shaped fixture (`results` / `calls` map). Optional `arguments` echoed; fixture results are keyed by name. Evidence only. | - -Use `name`, `fixture`, `arguments`=None as the inputs for this operation. - -Call a named tool from a MCP-shaped fixture (`results` / `calls` map). Optional `arguments` echoed; fixture results are keyed by name. Evidence only. - -1. `arguments` - Return *[Mcp fixture](agent_mcp_fixture(action="call", fixture=`fixture`, name=`name`, arguments=`arguments`))*. -2. * - Return *[Mcp fixture](agent_mcp_fixture(action="call", fixture=`fixture`, name=`name`))*. - ---- - -## mcp_connect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| command | any | required | Configured external command | -| args | any | None | Arguments passed to the selected command or operation | -| session | any | "default" | Existing session handle returned by the corresponding connector | -| name | any | "mcp" | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Open a stdio MCP client session (spawn `command` + `args`, JSON-RPC initialize). Evidence only — workbook remains authority. | - -Use `command`, `args`=None, `session`="default", `name`="mcp" as the inputs for this operation. - -Open a stdio MCP client session (spawn `command` + `args`, JSON-RPC initialize). Evidence only — workbook remains authority. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -1. `args` - Return *[Mcp client](agent_mcp_client(action="connect", command=`command`, args=`args`, session=`session`, name=`name`))*. -2. * - Return *[Mcp client](agent_mcp_client(action="connect", command=`command`, session=`session`, name=`name`))*. - -## mcp_client_list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| session | any | "default" | Existing session handle returned by the corresponding connector | -| command | any | None | Configured external command | -| args | any | None | Arguments passed to the selected command or operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List tools from an open MCP session, or one-shot when `command=` is set (no session retained). | - -Use `session`="default", `command`=None, `args`=None as the inputs for this operation. - -List tools from an open MCP session, or one-shot when `command=` is set (no session retained). - -1. `command` - 1. `args` - Return *[Mcp client](agent_mcp_client(action="list", command=`command`, args=`args`))*. - 2. * - Return *[Mcp client](agent_mcp_client(action="list", command=`command`))*. -2. * - Return *[Mcp client](agent_mcp_client(action="list", session=`session`))*. - -## mcp_client_call - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | None | Name registered or looked up by this operation | -| session | any | "default" | Existing session handle returned by the corresponding connector | -| arguments | any | None | Named argument record for the selected registered tool | -| command | any | None | Configured external command | -| args | any | None | Arguments passed to the selected command or operation | -| tool | any | None | Registered tool or tool name selected by policy | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Call a tool on an open MCP session, or one-shot when `command=` is set. Prefer `tool=` for oneshot when `name` would collide with server name. | - -Use `name`=None, `session`="default", `arguments`=None, `command`=None, `args`=None, `tool`=None as the inputs for this operation. - -Call a tool on an open MCP session, or one-shot when `command=` is set. Prefer `tool=` for oneshot when `name` would collide with server name. - -1. `command` - 1. `tool` - We retain **tn = tool**. - 2. * - We retain **tn = name**. - 1. `args` - Return *[Mcp client](agent_mcp_client(action="call", command=`command`, args=`args`, tool=`tn`, arguments=`arguments`))*. - 2. * - Return *[Mcp client](agent_mcp_client(action="call", command=`command`, tool=`tn`, arguments=`arguments`))*. -2. * - Return *[Mcp client](agent_mcp_client(action="call", session=`session`, name=`name`, arguments=`arguments`))*. - -## mcp_disconnect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| session | any | "default" | Existing session handle returned by the corresponding connector | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Close a stdio MCP client session. | - -Use `session`="default" as the inputs for this operation. - -Close a stdio MCP client session. - -Return *[Mcp client](agent_mcp_client(action="close", session=`session`))*. - ---- - -## resume_save - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| goal | any | None | Human task goal represented by this operation | -| task | any | None | Structured task or text supplied to the agent | -| status | any | "running" | Domain status recorded in the structured result | -| round | any | 0 | Current planning round number | -| workbook | any | None | Workbook path or structured workbook reference | -| events | any | None | Ordered semantic or provider stream-event records | -| route | any | None | Selected route or route-policy data | -| result | any | None | Structured result from the preceding operation | -| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | -| checkpoint_v2 | any | False | Versioned continuation checkpoint record | -| attempt_id | any | None | Identifier for this execution attempt | -| effect_ledger_watermark | any | None | Last durable effect-ledger position included by the checkpoint | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Persist a plan/run checkpoint as `.marqdo/agent-resume/.json` (atomic write). Pass `checkpoint_v2=True` for CheckpointV2 schema. `resume_dir` must be host-relative. | - -Use `id`, `goal`=None, `task`=None, `status`="running", `round`=0, `workbook`=None, `events`=None, `route`=None, `result`=None, `resume_dir`=".marqdo/agent-resume", `checkpoint_v2`=False, `attempt_id`=None, `effect_ledger_watermark`=None as the inputs for this operation. - -Persist a plan/run checkpoint as `.marqdo/agent-resume/.json` (atomic write). -Pass `checkpoint_v2=True` for CheckpointV2 schema. `resume_dir` must be host-relative. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Resume save](agent_resume_save(id=`id`, goal=`goal`, task=`task`, status=`status`, round=`round`, workbook=`workbook`, events=`events`, route=`route`, result=`result`, resume_dir=`resume_dir`, checkpoint_v2=`checkpoint_v2`, attempt_id=`attempt_id`, effect_ledger_watermark=`effect_ledger_watermark`))*. - -## resume_load - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load a resume checkpoint (or `{ok:false,found:false}`). Legacy / missing effect ledger → `recovery_mode=manual_review`, `write_auto_resume=false`. | - -Use `id`, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Load a resume checkpoint (or `{ok:false,found:false}`). -Legacy / missing effect ledger → `recovery_mode=manual_review`, `write_auto_resume=false`. - -Return *[Resume load](agent_resume_load(id=`id`, resume_dir=`resume_dir`))*. - -## error_make - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| code | any | required | Stable failure category or bound code value, as stated by this function | -| message | any | None | Outgoing WebSocket or application message | -| category | any | None | Failure category used by recovery policy | -| stage | any | "agent" | Execution stage where the failure occurred | -| retryable | any | None | Whether policy considers this failure eligible for retry | -| effect_state | any | "none" | Observed state of the logical effect | -| recovery_action | any | None | Selected recovery operation | -| call_id | any | None | Identifier of this tool invocation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Build an `AgentErrorV1` document (M-A1). | - -Use `code`, `message`=None, `category`=None, `stage`="agent", `retryable`=None, `effect_state`="none", `recovery_action`=None, `call_id`=None as the inputs for this operation. - -Build an `AgentErrorV1` document (M-A1). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Error make](agent_error_make(code=`code`, message=`message`, category=`category`, stage=`stage`, retryable=`retryable`, effect_state=`effect_state`, recovery_action=`recovery_action`, call_id=`call_id`))*. - -## error_decide_retry - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| error | any | required | Structured failure information supplied by the caller | -| attempts | any | 0 | Retry or exploration attempts already performed | -| effect_class | any | "read" | Declared kind of effect for this operation | -| cancelled | any | False | Whether cancellation has already been requested | -| fingerprint_repeats | any | 0 | Number of repeated identical failure fingerprints | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Bounded recovery decision. Write / unknown effect → `manual_review` (no auto redo). | - -Use `error`, `attempts`=0, `effect_class`="read", `cancelled`=False, `fingerprint_repeats`=0 as the inputs for this operation. - -Bounded recovery decision. Write / unknown effect → `manual_review` (no auto redo). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Error decide retry](agent_error_decide_retry(error=`error`, attempts=`attempts`, effect_class=`effect_class`, cancelled=`cancelled`, fingerprint_repeats=`fingerprint_repeats`))*. - -## resume_clear - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delete a resume checkpoint. | - -Use `id`, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Delete a resume checkpoint. - -Return *[Resume clear](agent_resume_clear(id=`id`, resume_dir=`resume_dir`))*. - -## resume_list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List checkpoint ids under `resume_dir`. | - -Use `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -List checkpoint ids under `resume_dir`. - -Return *[Resume list](agent_resume_list(resume_dir=`resume_dir`))*. - -## resume - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Author entry: load checkpoint for continuation. Returns the checkpoint map (`found`/`round`/`workbook`/…). Callers continue with `plan`/`run` using saved fields; clear when done. | - -Use `id`, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Author entry: load checkpoint for continuation. Returns the checkpoint map (`found`/`round`/`workbook`/…). Callers continue with `plan`/`run` using saved fields; clear when done. - -Return *[Resume load](resume_load(id=`id`, resume_dir=`resume_dir`))*. - -## effects_prepare - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| operation_id | any | required | Stable idempotent operation identifier | -| idempotency_key | any | required | Key identifying the same logical effect across retries | -| args_digest | any | required | Digest of the exact operation arguments | -| effect_class | any | "write" | Declared kind of effect for this operation | -| resource_scope | any | None | Resource boundary to which the operation applies | -| expected_revision | any | None | Revision the controlled update expects | -| result_ref | any | None | Durable reference to an already-produced result | -| logical_run_id | any | None | Stable logical execution identifier shared by retries | -| step_id | any | None | Identifier of the current workbook step | -| attempt_id | any | None | Identifier for this execution attempt | -| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Create (or dedupe) an `EffectLedgerRecordV1` in `prepared`. Same idempotency_key + args_digest returns the existing record; same key with different digest is rejected. | - -Use `operation_id`, `idempotency_key`, `args_digest`, `effect_class`="write", `resource_scope`=None, `expected_revision`=None, `result_ref`=None, `logical_run_id`=None, `step_id`=None, `attempt_id`=None, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. - -Create (or dedupe) an `EffectLedgerRecordV1` in `prepared`. Same idempotency_key + args_digest returns the existing record; same key with different digest is rejected. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Effects prepare](agent_effects_prepare(operation_id=`operation_id`, idempotency_key=`idempotency_key`, args_digest=`args_digest`, effect_class=`effect_class`, resource_scope=`resource_scope`, expected_revision=`expected_revision`, result_ref=`result_ref`, logical_run_id=`logical_run_id`, step_id=`step_id`, attempt_id=`attempt_id`, ledger_dir=`ledger_dir`))*. - -## effects_transition - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| operation_id | any | required | Stable idempotent operation identifier | -| state | any | required | Structured current state | -| result_ref | any | None | Durable reference to an already-produced result | -| note | any | None | Human-readable context associated with the record | -| reconcile_hint | any | None | Hint for reconciling an uncertain effect, not authorization to repeat it | -| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Advance ledger state (`prepared→started→committed|failed_no_effect|unknown→reconciled_*`). | - -Use `operation_id`, `state`, `result_ref`=None, `note`=None, `reconcile_hint`=None, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. - -Advance ledger state (`prepared→started→committed|failed_no_effect|unknown→reconciled_*`). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Effects transition](agent_effects_transition(operation_id=`operation_id`, state=`state`, result_ref=`result_ref`, note=`note`, reconcile_hint=`reconcile_hint`, ledger_dir=`ledger_dir`))*. - -## effects_get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| operation_id | any | required | Stable idempotent operation identifier | -| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load one ledger record. | - -Use `operation_id`, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. - -Load one ledger record. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Effects get](agent_effects_get(operation_id=`operation_id`, ledger_dir=`ledger_dir`))*. - -## effects_list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | -| logical_run_id | any | None | Stable logical execution identifier shared by retries | -| state | any | None | Structured current state | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List ledger records (optional filters). | - -Use `ledger_dir`=".marqdo/agent-effects", `logical_run_id`=None, `state`=None as the inputs for this operation. - -List ledger records (optional filters). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Effects list](agent_effects_list(ledger_dir=`ledger_dir`, logical_run_id=`logical_run_id`, state=`state`))*. - -## effects_watermark - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | -| logical_run_id | any | None | Stable logical execution identifier shared by retries | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Digest committed/open effects for CheckpointV2. `write_auto_resume_safe` is false while unknown or pending writes remain. | - -Use `ledger_dir`=".marqdo/agent-effects", `logical_run_id`=None as the inputs for this operation. - -Digest committed/open effects for CheckpointV2. `write_auto_resume_safe` is false while unknown or pending writes remain. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Effects watermark](agent_effects_watermark(ledger_dir=`ledger_dir`, logical_run_id=`logical_run_id`))*. - -## effects_reconcile - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| operation_id | any | required | Stable idempotent operation identifier | -| outcome | any | required | Observed domain result | -| result_ref | any | None | Durable reference to an already-produced result | -| note | any | None | Human-readable context associated with the record | -| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Reconcile an `unknown` record: `outcome` = committed | no_effect | needs_input. | - -Use `operation_id`, `outcome`, `result_ref`=None, `note`=None, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. - -Reconcile an `unknown` record: `outcome` = committed | no_effect | needs_input. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -Return *[Effects reconcile](agent_effects_reconcile(operation_id=`operation_id`, outcome=`outcome`, result_ref=`result_ref`, note=`note`, ledger_dir=`ledger_dir`))*. - ---- - -## extract_call_args - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | None | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parse `ARGS:{…}` JSON line, or a bare `{…}` line after CALL. | - -Use `reply`=None as the inputs for this operation. - -Parse `ARGS:{…}` JSON line, or a bare `{…}` line after CALL. - -The following record names each literal field without a JSON construction chain. - -Only the explicit ARGS line is parsed as JSON. Other reply prose remains inert, and absent arguments stay absent. This extraction does not validate the selected tool's schema or execute the reply; the dispatcher performs those later checks. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "brace" | "{" | -| 2 | "mark" | "ARGS:" | -| 3 | "nl" | "\n" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`mark` = [Read the mark field](json.get(value=`esc`, key="mark"))**. -We retain **`brace` = [Read the brace field](json.get(value=`esc`, key="brace"))**. -We retain **`empty` = [Empty map](table.empty_map())**. -1. `reply` - We retain **`text` = [Trim](trim(value=`reply`))**. - We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. - We retain **found = None**. - - [line](遍历 `lines` 为 `line`) - 1. `found` - **_ = 1** - 2. * - We retain **`t` = [Trim](trim(value=`line`))**. - We retain **`chunks` = [Split](split(value=`t`, sep=`mark`))**. - We retain **`cn` = [Len](len(value=`chunks`))**. - 1. `cn` > 1 - We retain **`rest` = [At](at(value=`chunks`, index=1))**. - We retain **`found` = [Trim](trim(value=`rest`))**. - 2. * - We retain **`chunks` = [Split](split(value=`t`, sep=`brace`))**. - We retain **`cn` = [Len](len(value=`chunks`))**. - We retain **`prefix` = [At](at(value=`chunks`, index=0))**. - 1. `cn` > 1 - 1. `prefix` - **_ = 1** - 2. * - We retain **found = t**. - 2. * - **_ = 1** - 1. `found` - Return *[Parse the JSON transport text](json.parse(text=`found`))*. - 2. * - Return *empty*. -2. * - Return *empty*. - ---- - -## tool_result_brief - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | None | Value supplied to this operation; immutable transformations return a new value | -| max_chars | any | 1024 | Maximum retained characters in the text excerpt | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Truncate a tool result for `tool_end` events (~1KiB). | - -Use `value`=None, `max_chars`=1024 as the inputs for this operation. - -Truncate a tool result for `tool_end` events (~1KiB). - -1. `value` - We retain **`s` = [Encode the structured value as JSON text](json.stringify(value=`value`))**. - Return *[Text head lines](text_head_lines(text=`s`, max_lines=40, max_chars=`max_chars`))*. -2. * - Return *None*. - ---- - -## plan_append_tool - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | any | required | Ordered semantic or provider stream-event records | -| type | any | required | Structured item or event type | -| name | any | required | Name registered or looked up by this operation | -| kind | any | required | Operation or factorization kind listed in this function's behavior | -| result | any | None | Structured result from the preceding operation | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Always append `tool_start` / `tool_end` to `events` for audit / view process cards. SSE publish only when `stream=True`. | - -Use `events`, `type`, `name`, `kind`, `result`=None, `stream`=False as the inputs for this operation. - -Always append `tool_start` / `tool_end` to `events` for audit / view process cards. SSE publish only when `stream=True`. - -`ev` = - -| type | name | kind | -|------|------|------| -| `type` | `name` | `kind` | - -1. `result` - We retain **`ev` = [Set the result field in the new record](table.put(in=`ev`, at="result", value=`result`))**. -2. * - **_ = 1** -We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. -1. `stream` - We **[Stream publish](sys.stream_publish(event=`ev`))**. -2. * - **_ = 1** - -Return *events*. - ---- - -## run_lib_call - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | required | Name registered or looked up by this operation | -| reply | any | None | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Whitelist `CALL:lib..` (+ ARGS). Rejects net/exec/write/delete. | - -Use `name`, `reply`=None as the inputs for this operation. - -Whitelist `CALL:lib..` (+ ARGS). Rejects net/exec/write/delete. - -We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. -Keep the literal separator as **errs = [Keep the exact separator](table.put(in=None, at="deny", value="Lib CALL not allowed: "))**. - -1. `name` == lib.fs.exists - We retain **`path` = [Read the path field](json.get(value=`args`, key="path"))**. - Return *[Exists](fs.exists(path=`path`))*. -2. `name` == lib.fs.read_text - We retain **`path` = [Read the path field](json.get(value=`args`, key="path"))**. - Return *[Read UTF-8 text from the selected file](fs.read_text(path=`path`))*. -3. `name` == lib.fs.list_dir - We retain **`path` = [Read the path field](json.get(value=`args`, key="path"))**. - Return *[List dir](fs.list_dir(path=`path`))*. -4. `name` == lib.json.parse - We retain **`text` = [Read the text field](json.get(value=`args`, key="text"))**. - Return *[Parse the JSON transport text](json.parse(text=`text`))*. -5. `name` == lib.json.stringify - We retain **`value` = [Read the value field](json.get(value=`args`, key="value"))**. - Return *[Encode the structured value as JSON text](json.stringify(value=`value`))*. -6. `name` == lib.sys.cwd - Return *[Cwd](sys.cwd())*. -7. * - We retain **`deny` = [Read the deny field](json.get(value=`errs`, key="deny"))**. - Return *deny + name*. - ---- - -## scratch_tool_write - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | required | Name registered or looked up by this operation | -| text | any | required | Text supplied to the transformation or adapter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Write a scratch tool workbook under `.marqdo/agent-runs/tools/.mq.md`. | - -Use `name`, `text` as the inputs for this operation. - -Write a scratch tool workbook under `.marqdo/agent-runs/tools/.mq.md`. - -The following record names each literal field without a JSON construction chain. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "a" | ".marqdo/agent-runs/tools/" | -| 2 | "b" | ".mq.md" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. -We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. -We retain **dir = ".marqdo/agent-runs/tools"**. -We **[Make dir](fs.make_dir(path=`dir`))**. -We retain **path = a + name + b**. -We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`text`))**. - -`out` = - -| ok | path | -|----|------| -| True | `path` | - -Return *out*. - ---- - -## skill_core_card - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Protected v2.1 Occlusion card always prepended to skill_brief (M05). Must not be truncated by budget. | - -Protected v2.1 Occlusion card always prepended to skill_brief (M05). Must not be truncated by budget. - -The card is kept as ordered lines so changes to any syntax instruction remain visible in review. - -These rules precede the budgeted skill excerpt so essential marker meanings remain available when a long skill is shortened. The card describes the runtime surface, including legacy explicit parameters; new library authors use narrative parameters as required by the development guide. Keep both explanations consistent when evolving the language. - -`_literal_core_lines` = - -| line | -|---| -| "## CORE SYNTAX (v2.1 Occlusion)" | -| "1. Print with > print / > 打印 — never use bold markers to print." | -| "2. Bold markers = statement; italic markers = return." | -| "3. [desc](payload) = occlusion; brackets never execute." | -| "4. Read with access(coll, key) — never Classic [key](map) index." | -| "5. Foreach: - [desc](for coll as item). import + one language per file." | -| "6. # type · ## function · + params · numbered branches · - loops." | -| "" | - -We preserve **_literal_core_text = [Join the protected instructions with their exact newlines](text.str_join(xs=`_literal_core_lines`, sep="\n"))** -and retain **esc = [Name the complete protected card](table.put(in=None, at="card", value=`_literal_core_text`))**. -Return *[Read the card field](json.get(value=`esc`, key="card"))*. - ---- - -## skill_brief - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| max_chars | any | 1200 | Maximum retained characters in the text excerpt | -| depth | any | "default" | Requested context or discovery depth | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Budgeted marqdo skill text for prompts. Core Occlusion card is always included; remaining budget truncates the rest. `depth=deep` raises the char budget. | - -Use `max_chars`=1200, `depth`="default" as the inputs for this operation. - -Budgeted marqdo skill text for prompts. Core Occlusion card is always included; remaining budget truncates the rest. `depth=deep` raises the char budget. - -1. `depth` == deep - We retain **budget = 4000**. -2. * - We retain **budget = max_chars**. -We retain **`core` = [Skill core card](skill_core_card())**. -We retain **`core_len` = [Len](len(value=`core`))**. -We retain **rest_budget = budget - core_len - 2**. -1. `rest_budget` < 200 - We retain **rest_budget = 200**. -2. * - **_ = 1** -We retain **`skill` = [Marqdo skill](agent_marqdo_skill())**. -We retain **`full` = [Len](len(value=`skill`))**. -We retain **`rest` = [Text head lines](text_head_lines(text=`skill`, max_lines=80, max_chars=`rest_budget`))**. -Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n\n"))**. -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **ex = core + nl + rest**. -We retain **`used` = [Len](len(value=`ex`))**. -1. `used` < `full` + `core_len` - The following record names each literal field without a JSON construction chain. - - `_literal_esc2_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "\n…[truncated skill_len=" | - | 2 | "b" | " budget_chars=" | - | 3 | "c" | "; emit READ:skill to deepen]" | - - We build **esc2 = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc2_fields`))**. - - - We retain **`a` = [Read the a field](json.get(value=`esc2`, key="a"))**. - We retain **`b` = [Read the b field](json.get(value=`esc2`, key="b"))**. - We retain **`c` = [Read the c field](json.get(value=`esc2`, key="c"))**. - Return *ex + a + full + b + budget + c*. -2. * - Return *ex*. - ---- - -## source_brief - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| depth | any | "default" | Requested context or discovery depth | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Budgeted current-module `.mq.md` source for `step` prompts. Default ~80 lines / 4KiB; `depth=deep` ~200 / 12KiB. | - -Use `depth`="default" as the inputs for this operation. - -Budgeted current-module `.mq.md` source for `step` prompts. Default ~80 lines / 4KiB; `depth=deep` ~200 / 12KiB. - -We retain **`src` = [Module source](agent_module_source())**. -We retain **`full` = [Len](len(value=`src`))**. -1. `depth` == deep - We retain **`ex` = [Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=200, max_chars=12000))**. - We retain **budget = 12000**. -2. * - We retain **`ex` = [Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=80, max_chars=4000))**. - We retain **budget = 4000**. -We retain **`used` = [Len](len(value=`ex`))**. -1. `used` < `full` - The following record names each literal field without a JSON construction chain. - - `_literal_esc_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "\n…[truncated source_len=" | - | 2 | "b" | " budget_chars=" | - | 3 | "c" | "; emit READ:source to deepen]" | - - We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - - We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. - We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. - We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. - Return *ex + a + full + b + budget + c*. -2. * - Return *ex*. - ---- - -## extract_plan_read - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parse READ:source|stderr|stdout|slots|skill (Chinese: 读取:…). | - -Use `reply` as the inputs for this operation. - -Parse READ:source|stderr|stdout|slots|skill (Chinese: 读取:…). - -The following record names each literal field without a JSON construction chain. - -A READ request asks the orchestration loop for a bounded excerpt, rather than reading a file directly. The parser extracts the named context kind from a reply line. The caller still chooses which kinds it supports and how many additional turns it permits. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "fw" | ":" | -| 2 | "nl" | "\n" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. -We retain **`text` = [Trim](trim(value=`reply`))**. -We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. -We retain **found = None**. -- [line](遍历 `lines` 为 `line`) - We retain **`t` = [Trim](trim(value=`line`))**. - We retain **`parts` = [Split](split(value=`t`, sep=":"))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == READ - We retain **found = rest**. - 2. `head` == 读取 - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == 读取 - We retain **found = rest**. - 2. `head` == READ - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - **_ = 1** -Return *found*. - ---- - -## extract_plan_act - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Priority: CALL → READ → DECISION. Returns `{kind,name}`. | - -Use `reply` as the inputs for this operation. - -Priority: CALL → READ → DECISION. Returns `{kind,name}`. - -We retain **`tool` = [Extract tool name](extract_tool_name(reply=`reply`))**. -1. `tool` - - `out` = - - | kind | name | - |------|------| - | call | `tool` | - - Return *out*. -2. * - **_ = 1** -We retain **`rk` = [Extract plan read](extract_plan_read(reply=`reply`))**. -1. `rk` - - `out` = - - | kind | name | - |------|------| - | read | `rk` | - - Return *out*. -2. * - **_ = 1** -We retain **`dec` = [Extract plan decision](extract_plan_decision(reply=`reply`))**. -1. `dec` - - `out` = - - | kind | name | - |------|------| - | decision | `dec` | - - Return *out*. -2. * - - `out` = - - | kind | - |------| - | unknown | - - Return *out*. - ---- - -## extract_scratch_tool - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parse NAME: id plus a triple-angle body after CALL:scratch_tool_write. | - -Use `reply` as the inputs for this operation. - -Parse NAME: id plus a triple-angle body after CALL:scratch_tool_write. - -The following record names each literal field without a JSON construction chain. - -The tool name and source body are returned as data. The body starts only at the explicit triple-angle opening line and ends at its matching closing line; surrounding commentary is excluded. This function does not write or run that source. The scratch writer remains responsible for destination checks, and the dispatcher still decides whether the requested tool is allowed. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "close" | ">>>" | -| 2 | "nl" | "\n" | -| 3 | "open" | "<<<" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`open` = [Read the open field](json.get(value=`esc`, key="open"))**. -We retain **`close` = [Read the close field](json.get(value=`esc`, key="close"))**. -We retain **`text` = [Trim](trim(value=`reply`))**. -We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. -We retain **name = None**. -We retain **`body_lines` = [Empty list](table.empty_list())**. -We retain **in_body = None**. -- [line](遍历 `lines` 为 `line`) - 1. `in_body` - We retain **`t` = [Trim](trim(value=`line`))**. - 1. `t` == `close` - We retain **in_body = None**. - 2. * - We retain **`body_lines` = [Append this item to the new list](table.append(list=`body_lines`, item=`line`))**. - 2. * - We retain **`t` = [Trim](trim(value=`line`))**. - We retain **`parts` = [Split](split(value=`t`, sep=":"))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == NAME - We retain **name = rest**. - 2. `head` == 名称 - We retain **name = rest**. - 3. * - **_ = 1** - 2. * - **_ = 1** - 1. `t` == `open` - We retain **in_body = 1**. - 2. * - **_ = 1** -We retain **`body` = [Join](join(value=`body_lines`, sep=`nl`))**. - -`out` = - -| name | text | -|------|------| -| `name` | `body` | - -Return *out*. - ---- - -## run_parent_tool - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | required | Name registered or looked up by this operation | -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| observation | any | None | Tool observation or workbook result retained for the next turn | -| reply | any | None | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`). | - -Use `name`, `path`, `observation`=None, `reply`=None as the inputs for this operation. - -Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`). - -1. `name` == workbook_read -This dispatcher has a fixed set of parent operations. Workbook readers operate on the selected workbook path; catalog lookup returns data; scratch creation first extracts a name and body. The corpus and MCP-shaped evidence branches parse explicit ARGS records and report missing required fields before calling their adapters. Those fixture adapters are not a live MCP transport. - -Arguments are deliberately read only after the value has been recognized as a record. Optional root, limit and argument fields are passed only when present, allowing the target helper to apply its own defaults. An unknown name reaches the restricted library dispatcher; it does not become an arbitrary function call. Editing this branch list therefore changes the parent tool surface and needs an allowlist regression, in addition to a prose update. - - Return *[Workbook read](workbook_read(path=`path`, depth="deep"))*. -2. `name` == workbook_excerpt - Return *[Workbook excerpt](workbook_excerpt(path=`path`))*. -3. `name` == lib_catalog - Return *[Lib catalog](lib_catalog())*. -4. `name` == scratch_tool_write - We retain **`parsed` = [Extract scratch tool](extract_scratch_tool(reply=`reply`))**. - We retain **`parsed_s` = [Encode the structured value as JSON text](json.stringify(value=`parsed`))**. - We retain **`parsed_map` = [Starts with](text.starts_with(text=`parsed_s`, prefix="{"))**. - We retain **tn = None**. - We retain **tt = None**. - 1. `parsed_map` - We retain **`tn` = [Read the name field](json.get(value=`parsed`, key="name"))**. - We retain **`tt` = [Read the text field](json.get(value=`parsed`, key="text"))**. - 2. * - **_ = 1** - The following record names each literal field without a JSON construction chain. - - `_literal_errs_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "scratch_tool_write needs NAME line and fenced body" | - | 2 | "b" | "scratch_tool_write needs NAME id" | - - We build **errs = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_errs_fields`))**. - - - 1. `tn` - 1. `tt` - Return *[Scratch tool write](scratch_tool_write(name=`tn`, text=`tt`))*. - 2. * - Return *[Read the a field](json.get(value=`errs`, key="a"))*. - 2. * - Return *[Read the b field](json.get(value=`errs`, key="b"))*. -5. `name` == corpus_search - We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. - We retain **`args_s` = [Encode the structured value as JSON text](json.stringify(value=`args`))**. - We retain **`args_map` = [Starts with](text.starts_with(text=`args_s`, prefix="{"))**. - We retain **q = None**. - We retain **root = None**. - We retain **limit = None**. - 1. `args_map` - We retain **`q` = [Read the query field](json.get(value=`args`, key="query"))**. - We retain **`root` = [Read the root field](json.get(value=`args`, key="root"))**. - We retain **`limit` = [Read the limit field](json.get(value=`args`, key="limit"))**. - 2. * - **_ = 1** - Keep the literal separator as **cerrs = [Keep the exact separator](table.put(in=None, at="q", value="corpus_search needs ARGS.query"))**. - 1. not `q` - Return *[Read the q field](json.get(value=`cerrs`, key="q"))*. - 2. `root` - 1. `limit` - Return *[Corpus search](corpus_search(query=`q`, root=`root`, limit=`limit`))*. - 2. * - Return *[Corpus search](corpus_search(query=`q`, root=`root`))*. - 3. `limit` - Return *[Corpus search](corpus_search(query=`q`, limit=`limit`))*. - 4. * - Return *[Corpus search](corpus_search(query=`q`))*. -6. `name` == mcp_list_tools - We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. - We retain **`args_s` = [Encode the structured value as JSON text](json.stringify(value=`args`))**. - We retain **`args_map` = [Starts with](text.starts_with(text=`args_s`, prefix="{"))**. - We retain **fx = None**. - 1. `args_map` - We retain **`fx` = [Read the fixture field](json.get(value=`args`, key="fixture"))**. - 2. * - **_ = 1** - Keep the literal separator as **merrs = [Keep the exact separator](table.put(in=None, at="f", value="mcp_list_tools needs ARGS.fixture"))**. - 1. `fx` - Return *[Mcp list tools](mcp_list_tools(fixture=`fx`))*. - 2. * - Return *[Read the f field](json.get(value=`merrs`, key="f"))*. -7. `name` == mcp_call - We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. - We retain **`args_s` = [Encode the structured value as JSON text](json.stringify(value=`args`))**. - We retain **`args_map` = [Starts with](text.starts_with(text=`args_s`, prefix="{"))**. - We retain **fx = None**. - We retain **tn = None**. - We retain **targ = None**. - 1. `args_map` - We retain **`fx` = [Read the fixture field](json.get(value=`args`, key="fixture"))**. - We retain **`tn` = [Read the name field](json.get(value=`args`, key="name"))**. - We retain **`targ` = [Read the arguments field](json.get(value=`args`, key="arguments"))**. - 2. * - **_ = 1** - The following record names each literal field without a JSON construction chain. - - `_literal_xerrs_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "f" | "mcp_call needs ARGS.fixture" | - | 2 | "n" | "mcp_call needs ARGS.name" | - - We build **xerrs = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_xerrs_fields`))**. - - - 1. `fx` - 1. `tn` - 1. `targ` - Return *[Mcp call](mcp_call(name=`tn`, fixture=`fx`, arguments=`targ`))*. - 2. * - Return *[Mcp call](mcp_call(name=`tn`, fixture=`fx`))*. - 2. * - Return *[Read the n field](json.get(value=`xerrs`, key="n"))*. - 2. * - Return *[Read the f field](json.get(value=`xerrs`, key="f"))*. -8. * - We retain **`dots` = [Split](split(value=`name`, sep=".*"))**. - We retain **`head` = [At](at(value=`dots`, index=0))**. - 1. `head` == lib - Return *[Run lib call](run_lib_call(name=`name`, reply=`reply`))*. - 2. * - We retain **msg = "Parent tool not allowed:"**. - Return *msg + name*. - ---- - -## plan_read_deepen - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| observation | any | required | Tool observation or workbook result retained for the next turn | -| kind | any | required | Operation or factorization kind listed in this function's behavior | -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply the requested source or skill depth increase before preparing another planning turn. | - -Use `observation`, `kind`, `path` as the inputs for this operation. - -We retain **obs = observation**. -1. `kind` == source - We retain **`ex` = [Workbook read](workbook_read(path=`path`, depth="deep"))**. - We retain **`obs` = [Set the source_excerpt field in the new record](table.put(in=`obs`, at="source_excerpt", value=`ex`))**. - We retain **`obs` = [Set the read_source field in the new record](table.put(in=`obs`, at="read_source", value=True))**. -2. `kind` == stderr - We retain **`err` = [Read the stderr field](json.get(value=`obs`, key="stderr"))**. - We retain **`tail` = [Text tail lines](text_tail_lines(text=`err`, max_lines=80, max_chars=6000))**. - We retain **`obs` = [Set the stderr_tail field in the new record](table.put(in=`obs`, at="stderr_tail", value=`tail`))**. - We retain **`obs` = [Set the read_stderr field in the new record](table.put(in=`obs`, at="read_stderr", value=True))**. -3. `kind` == stdout - We retain **`out` = [Read the stdout field](json.get(value=`obs`, key="stdout"))**. - We retain **`tail` = [Text tail lines](text_tail_lines(text=`out`, max_lines=80, max_chars=6000))**. - We retain **`obs` = [Set the stdout_tail field in the new record](table.put(in=`obs`, at="stdout_tail", value=`tail`))**. - We retain **`obs` = [Set the read_stdout field in the new record](table.put(in=`obs`, at="read_stdout", value=True))**. -4. `kind` == slots - We retain **`slots` = [Read the slots field](json.get(value=`obs`, key="slots"))**. - We retain **`obs` = [Set the slots_detail field in the new record](table.put(in=`obs`, at="slots_detail", value=`slots`))**. - We retain **`obs` = [Set the read_slots field in the new record](table.put(in=`obs`, at="read_slots", value=True))**. -5. `kind` == skill - We retain **`brief` = [Skill brief](skill_brief(depth="deep"))**. - We retain **`obs` = [Set the skill_brief field in the new record](table.put(in=`obs`, at="skill_brief", value=`brief`))**. - We retain **`obs` = [Set the read_skill field in the new record](table.put(in=`obs`, at="read_skill", value=True))**. -6. * - **_ = 1** -Return *obs*. - ---- - -## compact_plan_observation - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| observation | any | required | Tool observation or workbook result retained for the next turn | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Bounded observation for the parent prompt (actionable, short). Tolerates missing/non-map observation (empty compact) instead of `json get needs map`. Map check via stringify prefix `{` — never hard-get on None / bare text / list. | - -Use `observation` as the inputs for this operation. - -Bounded observation for the parent prompt (actionable, short). -Tolerates missing/non-map observation (empty compact) instead of `json get needs map`. -Map check via stringify prefix `{` — never hard-get on None / bare text / list. - -A child observation can contain a full workbook, process output and slot values. Sending all of that on every parent turn wastes context and can obscure the next decision. This projection retains the execution path and exit status, records source size, and carries selected excerpts or tails for repair. It returns a new record; it neither edits the workbook nor changes the original observation. - -The source marker check is a structural hint: it looks for worker.step in the source text. That hint is not evidence that a model ran or that its answer is correct. Likewise, an exit status of zero is useful execution evidence, but a parent still needs a returned value and task-specific verification before DONE. The compact record's note communicates that decision protocol without granting the helper authority to declare success. - -When an observation already supplies a source excerpt or an output tail, that bounded view is reused. Otherwise the existing excerpt and tail helpers derive it from the full field. This keeps the same repair window available without transporting every log line. Missing source, output or slots simply leave the corresponding optional information absent. - -The initial record test protects None, ordinary text and lists from map-only access. A compact observation is therefore usable even after a child fails before producing its usual record. Consumers should read the available status and diagnostic fields instead of assuming that absence means an empty successful result. To investigate beyond these bounds, request an explicit deeper read through the parent protocol. - -For example, a failed child may provide stderr and source but no value. Keep the diagnostic tail for repair and leave result absent; replacing the missing value with a successful placeholder would destroy that evidence. - -We retain **obs_path = None**. -We retain **obs_code = None**. -We retain **obs_val = None**. -We retain **obs_slots = None**. -We retain **obs_src = None**. -We retain **obs_stdout = None**. -We retain **obs_stderr = None**. -We retain **`obs_s` = [Encode the structured value as JSON text](json.stringify(value=`observation`))**. -We retain **`obs_map` = [Starts with](text.starts_with(text=`obs_s`, prefix="{"))**. -1. `obs_map` - We retain **`obs_path` = [Read the path field](json.get(value=`observation`, key="path"))**. - We retain **`obs_code` = [Read the exit_code field](json.get(value=`observation`, key="exit_code"))**. - We retain **`obs_val` = [Read the value field](json.get(value=`observation`, key="value"))**. - We retain **`obs_slots` = [Read the slots field](json.get(value=`observation`, key="slots"))**. - We retain **`obs_src` = [Read the source field](json.get(value=`observation`, key="source"))**. - We retain **`obs_stdout` = [Read the stdout field](json.get(value=`observation`, key="stdout"))**. - We retain **`obs_stderr` = [Read the stderr field](json.get(value=`observation`, key="stderr"))**. -2. * - **_ = 1** -We retain **src_len = 0**. -We retain **has_step = False**. -1. `obs_src` - We retain **`src_len` = [Len](len(value=`obs_src`))**. - We retain **`step_parts` = [Split](split(value=`obs_src`, sep="worker.step"))**. - We retain **`n_step` = [Len](len(value=`step_parts`))**. - 1. `n_step` > 1 - We retain **has_step = True**. - 2. * - **_ = 1** -2. * - **_ = 1** - -`compact` = - -| note | path | exit_code | source_len | has_worker_step | solidify_on_done | -|------|------|-----------|------------|-----------------|------------------| -| Plan-and-Move: CALL/READ then DECISION. Success (exit 0 + has_value) → DONE. solidify_on_done. No long prose. | `obs_path` | `obs_code` | `src_len` | `has_step` | True | - -1. `obs_map` - 1. `obs_src` - We retain **`ex` = [Read the source_excerpt field](json.get(value=`observation`, key="source_excerpt"))**. - 1. `ex` - We retain **`compact` = [Set the source_excerpt field in the new record](table.put(in=`compact`, at="source_excerpt", value=`ex`))**. - 2. * - We retain **`ex` = [Workbook source excerpt](workbook_source_excerpt(source=`obs_src`))**. - We retain **`compact` = [Set the source_excerpt field in the new record](table.put(in=`compact`, at="source_excerpt", value=`ex`))**. - 2. * - **_ = 1** - - 1. `obs_stderr` - We retain **`tail` = [Read the stderr_tail field](json.get(value=`observation`, key="stderr_tail"))**. - 1. `tail` - We retain **`compact` = [Set the stderr_tail field in the new record](table.put(in=`compact`, at="stderr_tail", value=`tail`))**. - 2. * - We retain **`tail` = [Text tail lines](text_tail_lines(text=`obs_stderr`))**. - We retain **`compact` = [Set the stderr_tail field in the new record](table.put(in=`compact`, at="stderr_tail", value=`tail`))**. - 2. * - **_ = 1** - 1. `obs_stdout` - We retain **`tail` = [Read the stdout_tail field](json.get(value=`observation`, key="stdout_tail"))**. - 1. `tail` - We retain **`compact` = [Set the stdout_tail field in the new record](table.put(in=`compact`, at="stdout_tail", value=`tail`))**. - 2. * - We retain **`tail` = [Text tail lines](text_tail_lines(text=`obs_stdout`))**. - We retain **`compact` = [Set the stdout_tail field in the new record](table.put(in=`compact`, at="stdout_tail", value=`tail`))**. - 2. * - **_ = 1** - - We retain **`val_txt` = [Str](str(value=`obs_val`))**. - We retain **`val_len` = [Len](len(value=`val_txt`))**. - 1. `obs_val` - We retain **`compact` = [Set the has_value field in the new record](table.put(in=`compact`, at="has_value", value=True))**. - We retain **`compact` = [Set the value_len field in the new record](table.put(in=`compact`, at="value_len", value=`val_len`))**. - 1. `val_len` > 200 - We retain **`preview` = [Text head lines](text_head_lines(text=`val_txt`, max_lines=4, max_chars=200))**. - We retain **`compact` = [Set the value_preview field in the new record](table.put(in=`compact`, at="value_preview", value=`preview`))**. - 2. * - We retain **`compact` = [Set the value field in the new record](table.put(in=`compact`, at="value", value=`obs_val`))**. - 2. * - We retain **`compact` = [Set the has_value field in the new record](table.put(in=`compact`, at="has_value", value=False))**. - - We retain **`slots_brief` = [Empty list](table.empty_list())**. - 1. `obs_slots` - - [slot](遍历 `obs_slots` 为 `slot`) - We retain **`sk` = [Read the key field](json.get(value=`slot`, key="key"))**. - We retain **`sl` = [Read the line field](json.get(value=`slot`, key="line"))**. - We retain **`sb` = [Read the body field](json.get(value=`slot`, key="body"))**. - We retain **`sb_txt` = [Str](str(value=`sb`))**. - We retain **`sb_len` = [Len](len(value=`sb_txt`))**. - - `brief` = - - | key | line | body_len | - |-----|------|----------| - | `sk` | `sl` | `sb_len` | - - 1. `sk` == error - We retain **`prev` = [Text head lines](text_head_lines(text=`sb_txt`, max_lines=8, max_chars=400))**. - We retain **`brief` = [Set the body_preview field in the new record](table.put(in=`brief`, at="body_preview", value=`prev`))**. - 2. * - **_ = 1** - We retain **`slots_brief` = [Append this item to the new list](table.append(list=`slots_brief`, item=`brief`))**. - 2. * - **_ = 1** - We retain **`compact` = [Set the slots field in the new record](table.put(in=`compact`, at="slots", value=`slots_brief`))**. - We retain **`detail` = [Read the slots_detail field](json.get(value=`observation`, key="slots_detail"))**. - 1. `detail` - We retain **`compact` = [Set the slots_detail field in the new record](table.put(in=`compact`, at="slots_detail", value=`detail`))**. - 2. * - **_ = 1** - - We retain **`tool_result` = [Read the tool_result field](json.get(value=`observation`, key="tool_result"))**. - 1. `tool_result` - We retain **`tr` = [Str](str(value=`tool_result`))**. - We retain **`tr` = [Text head lines](text_head_lines(text=`tr`, max_lines=40, max_chars=3000))**. - We retain **`compact` = [Set the tool_result field in the new record](table.put(in=`compact`, at="tool_result", value=`tr`))**. - 2. * - **_ = 1** - - We retain **`last_error` = [Read the last_error field](json.get(value=`observation`, key="last_error"))**. - 1. `last_error` - We retain **`err_txt` = [Str](str(value=`last_error`))**. - We retain **`err_len` = [Len](len(value=`err_txt`))**. - 1. `err_len` > 200 - We retain **`prev` = [Text head lines](text_head_lines(text=`err_txt`, max_lines=8, max_chars=400))**. - We retain **`compact` = [Set the last_error_preview field in the new record](table.put(in=`compact`, at="last_error_preview", value=`prev`))**. - We retain **`compact` = [Set the last_error_len field in the new record](table.put(in=`compact`, at="last_error_len", value=`err_len`))**. - 2. * - We retain **`compact` = [Set the last_error field in the new record](table.put(in=`compact`, at="last_error", value=`last_error`))**. - 2. * - **_ = 1** -2. * - We retain **`compact` = [Set the has_value field in the new record](table.put(in=`compact`, at="has_value", value=False))**. - We retain **`empty_slots` = [Empty list](table.empty_list())**. - We retain **`compact` = [Set the slots field in the new record](table.put(in=`compact`, at="slots", value=`empty_slots`))**. - -Return *compact*. - ---- - -## extract_plan_decision - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parse `DECISION: DONE` / `CONTINUE` / `RUN` (Chinese: `决定:完成` / `继续` / `运行`). First matching DECISION / 决定 line wins (ignore later conflicting decisions in the same reply). | - -Use `reply` as the inputs for this operation. - -Parse `DECISION: DONE` / `CONTINUE` / `RUN` (Chinese: `决定:完成` / `继续` / `运行`). -First matching DECISION / 决定 line wins (ignore later conflicting decisions in the same reply). - -The following record names each literal field without a JSON construction chain. - -A decision is extracted from the model's protocol text and returned to the orchestration loop. It is not executed here. The loop must still distinguish RUN, CONTINUE and DONE and verify whether the workbook has a usable result. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "fw" | ":" | -| 2 | "nl" | "\n" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. -We retain **`text` = [Trim](trim(value=`reply`))**. -We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. -We retain **found = None**. - -- [line](遍历 `lines` 为 `line`) - 1. `found` - **_ = 1** - 2. * - We retain **`t` = [Trim](trim(value=`line`))**. - We retain **`parts` = [Split](split(value=`t`, sep=":"))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == DECISION - We retain **found = rest**. - 2. `head` == 决定 - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == 决定 - We retain **found = rest**. - 2. `head` == DECISION - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - **_ = 1** - -1. `found` - Take the first token only (`DECISION: RUN please` → RUN). - We retain **`toks` = [Split](split(value=`found`, sep=" "))**. - We retain **`found` = [At](at(value=`toks`, index=0))**. - We retain **`found` = [Trim](trim(value=`found`))**. -2. * - **_ = 1** - -1. `found` == DONE - Return *"DONE"*. -2. `found` == CONTINUE - Return *"CONTINUE"*. -3. `found` == RUN - Return *"RUN"*. -4. `found` == REUSE - Return *"REUSE"*. -5. `found` == NEW - Return *"NEW"*. -6. `found` == 完成 - Return *"DONE"*. -7. `found` == 继续 - Return *"CONTINUE"*. -8. `found` == 运行 - Return *"RUN"*. -9. `found` == 复用 - Return *"REUSE"*. -10. `found` == 新建 - Return *"NEW"*. -11. `found` == PATCH - Models sometimes invent `DECISION: PATCH` — treat as CONTINUE. - Return *"CONTINUE"*. -12. * - If the reply carries a FIND/REPLACE block, treat unknown labels as CONTINUE. - We retain **`has_find` = [Split](split(value=`text`, sep="<<<"))**. - We retain **`n_find` = [Len](len(value=`has_find`))**. - 1. `n_find` > 1 - Return *"CONTINUE"*. - 2. * - Return *found*. - ---- - -## extract_soft_match_slug - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parse `SLUG: …` / `标识:…` after a soft-match REUSE decision. | - -Use `reply` as the inputs for this operation. - -Parse `SLUG: …` / `标识:…` after a soft-match REUSE decision. - -The following record names each literal field without a JSON construction chain. - -The returned slug identifies a candidate from the proposed knowledge entries. It is a lookup result rather than a filesystem authorization. The later route-application stage must resolve it against the knowledge directory before any workbook is executed. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "fw" | ":" | -| 2 | "nl" | "\n" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. -We retain **`text` = [Trim](trim(value=`reply`))**. -We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. -We retain **found = None**. - -- [line](遍历 `lines` 为 `line`) - We retain **`t` = [Trim](trim(value=`line`))**. - We retain **`parts` = [Split](split(value=`t`, sep=":"))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == SLUG - We retain **found = rest**. - 2. `head` == 标识 - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == 标识 - We retain **found = rest**. - 2. `head` == SLUG - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - **_ = 1** - -Return *found*. - ---- - -## build_soft_match_prompt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| goal | any | required | Human task goal represented by this operation | -| tasks | any | required | Ordered task records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Short parent prompt: REUSE+SLUG or NEW only. Candidates may include lexical `score` (prefer higher). `list_tasks` rows may also carry `description` / `status` / `llm_free`. | - -Use `goal`, `tasks` as the inputs for this operation. - -Short parent prompt: REUSE+SLUG or NEW only. Candidates may include lexical `score` (prefer higher). `list_tasks` rows may also carry `description` / `status` / `llm_free`. - -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -Candidate rows are evidence for a reuse choice, not executable instructions. Their slugs identify existing knowledge; titles and optional metadata help the parent compare task fit. A lexical score measures local text similarity, while llm_free describes whether the selected skill can run without a parent model. Neither alone establishes that its answer satisfies this new goal. - -The output protocol deliberately permits only REUSE with a listed slug or NEW. The caller parses that decision and applies the selected resource through the ordinary route path. Building this prompt does not execute a candidate, alter its status, or add model-generated names to the tool whitelist. - -`_literal_esc_c_lines` = - -| line | -|---| -| "" | -| "" | -| "--- how to act ---" | -| "Exact reuse miss; candidates are ranked by local n-gram score when present. Prefer higher scores and llm_free=true skills. Reply with ONE protocol only:" | -| "DECISION: REUSE" | -| "SLUG: " | -| "or" | -| "DECISION: NEW" | -| "No other prose." | -| "" | - -Join exactly those lines into **_literal_esc_c_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_c_lines`, sep="\n"))**. - -The following record names each literal field without a JSON construction chain. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "a" | "\n\n--- goal ---\n" | -| 2 | "b" | "\n\n--- candidate tasks (slug \| title \| meta) ---\n" | -| 3 | "c" | `_literal_esc_c_text` | -| 4 | "lf" | "llm_free=" | -| 5 | "nl" | "\n" | -| 6 | "sep" | " \| " | -| 7 | "sp" | "score=" | -| 8 | "st" | "status=" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. -We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. -We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`sep` = [Read the sep field](json.get(value=`esc`, key="sep"))**. -We retain **`sp` = [Read the sp field](json.get(value=`esc`, key="sp"))**. -We retain **`st` = [Read the st field](json.get(value=`esc`, key="st"))**. -We retain **`lf` = [Read the lf field](json.get(value=`esc`, key="lf"))**. -We retain **`lines` = [Empty list](table.empty_list())**. -- [t](遍历 `tasks` 为 `t`) - We retain **`slug` = [Read the slug field](json.get(value=`t`, key="slug"))**. - We retain **`title` = [Read the title field](json.get(value=`t`, key="title"))**. - We retain **row = slug + sep + title**. - We retain **`score` = [Read the score field](json.get(value=`t`, key="score"))**. - 1. `score` - We retain **row = row + sep + sp + score**. - 2. * - **_ = 1** - We retain **`status` = [Read the status field](json.get(value=`t`, key="status"))**. - 1. `status` - We retain **row = row + sep + st + status**. - 2. * - **_ = 1** - We retain **`free` = [Read the llm_free field](json.get(value=`t`, key="llm_free"))**. - 1. `free` == True - We retain **row = row + sep + lf + "true"**. - 2. `free` == true - We retain **row = row + sep + lf + "true"**. - 3. `free` == False - We retain **row = row + sep + lf + "false"**. - 4. `free` == false - We retain **row = row + sep + lf + "false"**. - 5. * - **_ = 1** - We retain **`desc` = [Read the description field](json.get(value=`t`, key="description"))**. - 1. `desc` - We retain **row = row + sep + desc**. - 2. * - **_ = 1** - We retain **`lines` = [Append this item to the new list](table.append(list=`lines`, item=`row`))**. -We retain **`catalog` = [Join](join(value=`lines`, sep=`nl`))**. -We retain **p = "Soft-match: same task intent?"**. -Return *p + a + goal + b + catalog + c*. - ---- - -## extract_plan_summary - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | First `SUMMARY:` / `汇总:` / `汇总:` line body, else trimmed reply. | - -Use `reply` as the inputs for this operation. - -First `SUMMARY:` / `汇总:` / `汇总:` line body, else trimmed reply. - -The following record names each literal field without a JSON construction chain. - -The summary is the short human-facing explanation attached to the plan result. It is kept separate from the decision so a sentence that happens to mention DONE does not itself finish a run. Source patches and tool requests are handled by their own extractors. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "fw" | ":" | -| 2 | "nl" | "\n" | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. -We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. -We retain **`text` = [Trim](trim(value=`reply`))**. -We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. -We retain **found = None**. - -- [line](遍历 `lines` 为 `line`) - We retain **`t` = [Trim](trim(value=`line`))**. - We retain **`parts` = [Split](split(value=`t`, sep=":"))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == SUMMARY - We retain **found = rest**. - 2. `head` == 汇总 - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` > 1 - We retain **`head` = [At](at(value=`parts`, index=0))**. - We retain **`head` = [Trim](trim(value=`head`))**. - We retain **`rest` = [At](at(value=`parts`, index=1))**. - We retain **`rest` = [Trim](trim(value=`rest`))**. - 1. `head` == 汇总 - We retain **found = rest**. - 2. `head` == SUMMARY - We retain **found = rest**. - 3. * - **_ = 1** - 2. * - **_ = 1** - -1. `found` - Return *found*. -2. * - Return *text*. - ---- - -## build_plan_context - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| agent | any | required | Agent configuration or receiver created by this package | -| goal | any | required | Human task goal represented by this operation | -| observation | any | required | Tool observation or workbook result retained for the next turn | -| explore_attempt | any | None | Current exploration attempt number | -| explore_n | any | None | Maximum configured exploration attempts | -| phase | any | "revise" | Named execution phase | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parent Plan-and-Move prompt. Short protocol only — no long monologues. | - -Use `agent`, `goal`, `observation`, `explore_attempt`=None, `explore_n`=None, `phase`="revise" as the inputs for this operation. - -Parent Plan-and-Move prompt. Short protocol only — no long monologues. - -The parent receives a decision surface rather than the whole child process. Its goal is serialized as data, standing instructions supply the agent role, and a compact observation conveys the last execution outcome. If the observation carries a skill brief, that already selected context is reused; otherwise the normal budgeted skill brief is loaded. Source remains authoritative even when an evidence adapter contributes useful facts. - -There are two instruction branches. Before the first run, the decompose phase checks whether the generated skeleton can be executed as written. It may request evidence, propose a short patch, or choose RUN. During revision, the parent sees the child's outcome and chooses whether to repair or finish. A successful child with a usable value can lead to DONE; the mere presence of a worker call is not a reason to keep rewriting the workbook. - -The protocol text is stored in visible line tables. Literal examples of CALL, READ, DECISION and patch delimiters are instructions for a later model reply, not commands executed while assembling the prompt. Their exact line breaks matter to the corresponding extractors. Do not replace this representation with a second workflow language, or hide a new tool behind a descriptive label without wiring its implementation. - -The parent-tools section explains the restricted workbook, source and evidence actions. An explicit library CALL uses the dispatcher's whitelist and argument parsing. READ requests deepen context through the caller's budget. Scratch tool creation returns to the ordinary source-and-tool path; a sentence in the prompt cannot bypass filesystem roots, runtime effects or ToolSpec preparation. - -Exploration metadata tells the parent which attempt it is inspecting and how many variants the surrounding planner configured. It does not create a loop here. This function only returns text; the plan loop owns round accounting, child execution, patch application and writeback. When debugging a wrong decision, inspect the returned sections alongside the actual observation and call site before changing model instructions. - -To extend a parent's capabilities, first implement a real dispatcher branch with its input contract and tests. Then update the visible tool instructions. Changing this prompt alone only changes what the model sees and cannot establish a callable implementation. - -We retain **`standing` = [Read the standing field](json.get(value=`agent`, key="standing"))**. -1. `standing` - We retain **up = standing**. -2. * - We retain **up = None**. - -We retain **skill_from_obs = None**. -We retain **`obs_probe` = [Encode the structured value as JSON text](json.stringify(value=`observation`))**. -We retain **`obs_is_map` = [Starts with](text.starts_with(text=`obs_probe`, prefix="{"))**. -1. `obs_is_map` - We retain **`skill_from_obs` = [Read the skill_brief field](json.get(value=`observation`, key="skill_brief"))**. -2. * - **_ = 1** -1. `skill_from_obs` - We retain **skill = skill_from_obs**. -2. * - We retain **`skill` = [Skill brief](skill_brief())**. -We retain **`compact` = [Compact plan observation](compact_plan_observation(observation=`observation`))**. -We retain **`obs_s` = [Encode the structured value as JSON text](json.stringify(value=`compact`))**. -We retain **`goal_s` = [Encode the structured value as JSON text](json.stringify(value=`goal`))**. -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -`_literal_esc_e_dec_lines` = - -| line | -|---| -| "" | -| "" | -| "--- how to act ---" | -| "PRE-RUN decompose. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line." | -| "1) Skeleton OK → DECISION: RUN (preferred). Do not rewrite imports; they are already nested import: (llm/agent/…)." | -| "2) Need evidence → READ:source or READ:skill or CALL:workbook_read / lib_catalog / corpus_search / mcp_call." | -| "3) Reshape body/logic only → DECISION: CONTINUE + short PATCH (<20 lines)." | -| "4) Fixed answer without LLM → PATCH to return, then RUN or DONE." | -| "PATCH must use <<< FIND === REPLACE >>> only (no \x60\x60\x60find / Begin Patch)." | -| "Protocols:" | -| "CALL:name" | -| "READ:kind" | -| "DECISION: RUN" | -| "DECISION: DONE" | -| "SUMMARY: one line" | -| "DECISION: CONTINUE" | -| "" | - -Join exactly those lines into **_literal_esc_e_dec_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_e_dec_lines`, sep="\n"))**. - -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -`_literal_esc_e_rev_lines` = - -| line | -|---| -| "" | -| "" | -| "--- how to act ---" | -| "Plan-and-Move parent. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line." | -| "1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step." | -| "2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted)." | -| "3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE." | -| "4) Do NOT CONTINUE only to rewrite frontmatter imports; skeleton already uses nested import: map (llm/agent/json…)." | -| "PATCH must use triple-angle blocks only:" | -| "<<<" | -| "FIND" | -| "" | -| "===" | -| "REPLACE" | -| "" | -| ">>>" | -| "Do not use \x60\x60\x60find, \x60\x60\x60replace, or *** Begin Patch ***." | -| "Protocols:" | -| "CALL:name" | -| "READ:kind" | -| "DECISION: DONE" | -| "SUMMARY: one line" | -| "DECISION: CONTINUE" | -| "" | - -Join exactly those lines into **_literal_esc_e_rev_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_e_rev_lines`, sep="\n"))**. - -Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. - -`_literal_esc_tools_lines` = - -| line | -|---| -| "" | -| "" | -| "--- parent tools ---" | -| "CALL:workbook_read \| workbook_excerpt \| lib_catalog \| scratch_tool_write" | -| "CALL:corpus_search \| mcp_list_tools \| mcp_call (ARGS:{…}; evidence only — workbook authority)" | -| "CALL:lib.fs.read_text\|exists\|list_dir \| lib.json.parse\|stringify \| lib.sys.cwd (+ ARGS:{json})" | -| "READ:source \| stderr \| stdout \| slots \| skill" | -| "Create tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body." | -| "" | - -Join exactly those lines into **_literal_esc_tools_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_tools_lines`, sep="\n"))**. - -The following record names each literal field without a JSON construction chain. - -`_literal_esc_fields` = - -| @ | key | value | -|---|---|---| -| 1 | "a" | "\n\n--- standing ---\n" | -| 2 | "b" | "\n\n--- goal ---\n" | -| 3 | "c" | "\n\n--- observation ---\n" | -| 4 | "d" | "\n\n--- skill brief ---\n" | -| 5 | "e_dec" | `_literal_esc_e_dec_text` | -| 6 | "e_rev" | `_literal_esc_e_rev_text` | -| 7 | "f" | "\n\n--- explore ---\n" | -| 8 | "tools" | `_literal_esc_tools_text` | - -We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. - - -We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. -We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. -We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. -We retain **`d` = [Read the d field](json.get(value=`esc`, key="d"))**. -We retain **`tools` = [Read the tools field](json.get(value=`esc`, key="tools"))**. -We retain **`f` = [Read the f field](json.get(value=`esc`, key="f"))**. -1. `phase` == decompose - We retain **`e` = [Read the e_dec field](json.get(value=`esc`, key="e_dec"))**. - We retain **p = "Plan-and-Move: decompose before first run."**. -2. * - We retain **`e` = [Read the e_rev field](json.get(value=`esc`, key="e_rev"))**. - We retain **p = "Plan-and-Move: revise after child run."**. -We retain **p = p + a + up + b + goal_s + c + obs_s + tools + d + skill + e**. -1. `explore_attempt` - We retain **p = p + f**. - We retain **p = p + "Attempt"**. - We retain **p = p + explore_attempt**. - We retain **p = p + "of"**. - We retain **p = p + explore_n**. - We retain **p = p + ". Different path; prefer code when fixed."**. -2. * - **_ = 1** -Return *p*. - ---- - -## plan_llm_act_loop - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| agent | any | required | Agent configuration or receiver created by this package | -| goal | any | required | Human task goal represented by this operation | -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| observation | any | required | Tool observation or workbook result retained for the next turn | -| phase | any | "revise" | Named execution phase | -| explore_attempt | any | None | Current exploration attempt number | -| explore_n | any | None | Maximum configured exploration attempts | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| events | any | required | Ordered semantic or provider stream-event records | -| max_acts | any | 6 | Maximum model/tool actions for this planning loop | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,events,llm_calls,tokens}`. | - -Use `agent`, `goal`, `path`, `observation`, `phase`="revise", `explore_attempt`=None, `explore_n`=None, `stream`=False, `echo`=False, `events`, `max_acts`=6 as the inputs for this operation. - -LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,events,llm_calls,tokens}`. - -Each model turn may answer directly, request context, or ask for one allowed parent action. The loop records the resulting observation and rebuilds context before asking again. Its bounded iteration prevents an endless READ or CALL exchange; it does not automatically authorize a tool mentioned by the model. Transport errors and exhausted budgets remain visible to the enclosing planner. - -We retain **`model` = [Read the model field](json.get(value=`agent`, key="model"))**. -We retain **last_obs = observation**. -We retain **left = max_acts**. -We retain **decision = None**. -We retain **last_reply = None**. -We retain **evs_all = events**. -We retain **llm_calls = 0**. -We retain **tokens = 0**. - -We retain **transport_err = None**. - -- `left` > 0 - 1. `decision` - We retain **left = 0**. - 2. `transport_err` - We retain **left = 0**. - 3. * - We retain **`ctx` = [Build plan context](build_plan_context(agent=`agent`, goal=`goal`, observation=`last_obs`, explore_attempt=`explore_attempt`, explore_n=`explore_n`, phase=`phase`))**. - Plan protocol streams as `stream_kind=plan` (process trail). Answer tokens - still come from workbook `worker.step stream=True` (`stream_kind=delta`). - 1. `stream` - We retain **`turn` = [Model turn](model_turn(model=`model`, prompt=`ctx`, stream=True, echo=`echo`, stream_kind="plan"))**. - 2. * - We retain **`turn` = [Model turn](model_turn(model=`model`, prompt=`ctx`, stream=False, echo=`echo`))**. - We retain **`turn_s` = [Encode the structured value as JSON text](json.stringify(value=`turn`))**. - We retain **`turn_map` = [Starts with](text.starts_with(text=`turn_s`, prefix="{"))**. - We retain **terr = None**. - We retain **last_reply = ""**. - 1. not `turn_map` - We retain **transport_err = "model_turn_not_map"**. - We retain **left = 0**. - 2. * - We retain **`terr` = [Read the error field](json.get(value=`turn`, key="error"))**. - 1. `terr` - We retain **transport_err = `terr`**. - We retain **left = 0**. - 2. * - We retain **`last_reply` = [Read the text field](json.get(value=`turn`, key="text"))**. - We retain **`c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. - We retain **`t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. - 1. not `c` - We retain **c = 0**. - 2. * - **_ = 1** - 1. not `t` - We retain **t = 0**. - 2. * - **_ = 1** - We retain **llm_calls = llm_calls + c**. - We retain **tokens = tokens + t**. - 1. `transport_err` - We retain **decision = "TRANSPORT_ERROR"**. - We retain **last_reply = `transport_err`**. - We retain **left = 0**. - 2. * - 1. not `last_reply` - We retain **last_reply = ""**. - 2. * - We retain **`last_reply` = [Trim](trim(value=`last_reply`))**. - Plan replies often embed CALL: inside PATCH bodies — prefer an explicit - DECISION line when present so protocol exit is not stolen by a false CALL. - We retain **`dec_line` = [Extract plan decision](extract_plan_decision(reply=`last_reply`))**. - We retain **kind = "unknown"**. - We retain **name = None**. - 1. `dec_line` - We retain **kind = "decision"**. - We retain **name = `dec_line`**. - 2. * - We retain **`act` = [Extract plan act](extract_plan_act(reply=`last_reply`))**. - We retain **`act_s` = [Encode the structured value as JSON text](json.stringify(value=`act`))**. - We retain **`act_map` = [Starts with](text.starts_with(text=`act_s`, prefix="{"))**. - 1. `act_map` - We retain **`kind` = [Read the kind field](json.get(value=`act`, key="kind"))**. - We retain **`name` = [Read the name field](json.get(value=`act`, key="name"))**. - 2. * - **_ = 1** - Live act marker so the UI never goes silent between plan tokens and the next step. - 1. `stream` - - `act_ev` = - - | type | kind | name | - |------|------|------| - | plan_act | `kind` | `name` | - - We **[Stream publish](sys.stream_publish(event=`act_ev`))**. - 2. * - **_ = 1** - 1. `kind` == call - We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_start", name=`name`, kind="call", stream=`stream`))**. - We retain **`tool_out` = [Run parent tool](run_parent_tool(name=`name`, path=`path`, observation=`last_obs`, reply=`last_reply`))**. - We retain **`brief` = [Tool result brief](tool_result_brief(value=`tool_out`))**. - We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_end", name=`name`, kind="call", result=`brief`, stream=`stream`))**. - We retain **`obs_s` = [Encode the structured value as JSON text](json.stringify(value=`last_obs`))**. - We retain **`obs_map` = [Starts with](text.starts_with(text=`obs_s`, prefix="{"))**. - 1. `obs_map` - We retain **`last_obs` = [Set the tool_result field in the new record](table.put(in=`last_obs`, at="tool_result", value=`tool_out`))**. - 2. * - **_ = 1** - We retain **left = left - 1**. - 2. `kind` == read - We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_start", name=`name`, kind="read", stream=`stream`))**. - We retain **`last_obs` = [Plan read deepen](plan_read_deepen(observation=`last_obs`, kind=`name`, path=`path`))**. - We retain **`brief` = [Tool result brief](tool_result_brief(value=`last_obs`))**. - We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_end", name=`name`, kind="read", result=`brief`, stream=`stream`))**. - We retain **left = left - 1**. - 3. `kind` == decision - We retain **decision = name**. - We retain **`evs_all` = [Plan append decision](plan_append_decision(events=`evs_all`, decision=`decision`, stream=`stream`))**. - We retain **left = 0**. - 4. * - We retain **decision = "unknown"**. - We retain **left = 0**. - -`out` = - -| decision | reply | observation | events | llm_calls | tokens | -|----------|-------|-------------|--------|-----------|--------| -| `decision` | `last_reply` | `last_obs` | `evs_all` | `llm_calls` | `tokens` | - -1. `transport_err` - We retain **`out` = [Set the error field in the new record](table.put(in=`out`, at="error", value=`transport_err`))**. -2. * - **_ = 1** -Return *out*. - ---- - -## plan_echo_decompose - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| workbook | any | required | Workbook path or structured workbook reference | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Pre-run parent decompose marker. With `stream=True`, publish `{type:decompose}` so view is not silent before the first child. | - -Use `workbook`, `stream`=False, `echo`=False as the inputs for this operation. - -Pre-run parent decompose marker. With `stream=True`, publish `{type:decompose}` so view is not silent before the first child. - -1. `stream` - - `ev` = - - | type | workbook | - |------|----------| - | decompose | `workbook` | - - We **[Stream publish](sys.stream_publish(event=`ev`))**. - 1. `echo` - We **[Print the prepared message](print(text="plan:decompose"))**. - 2. * - **_ = 1** - Return *ev*. -2. * - Return *None*. - -## plan_echo_await - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| round | any | required | Current planning round number | -| workbook | any | required | Workbook path or structured workbook reference | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Marker before `await_workbook`. With `stream=True`, publish `{type:await,round,workbook}` so the Stream panel shows progress while the quiet child runs (TTY `echo` optional). | - -Use `round`, `workbook`, `stream`=False, `echo`=False as the inputs for this operation. - -Marker before `await_workbook`. With `stream=True`, publish `{type:await,round,workbook}` so the Stream panel shows progress while the quiet child runs (TTY `echo` optional). - -1. `stream` - - `ev` = - - | type | round | workbook | - |------|-------|----------| - | await | `round` | `workbook` | - - We **[Stream publish](sys.stream_publish(event=`ev`))**. - 1. `echo` - We **[Print the prepared message](print(text="plan:await"))**. - We **[Print the prepared message](print(text=`round`))**. - 2. * - **_ = 1** - Return *ev*. -2. * - Return *None*. - -## workbook_has_worker_step - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | True when source still contains `worker.step` or `.单步`. | - -Use `path` as the inputs for this operation. - -True when source still contains `worker.step` or `.单步`. - -We retain **`src` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. -We retain **`a` = [Split](split(value=`src`, sep="worker.step"))**. -We retain **`na` = [Len](len(value=`a`))**. -We retain **`b` = [Split](split(value=`src`, sep=".单步"))**. -We retain **`nb` = [Len](len(value=`b`))**. -1. `na` > 1 - Return *1*. -2. `nb` > 1 - Return *1*. -3. * - Return *0*. - -## plan_append_round - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | any | required | Ordered semantic or provider stream-event records | -| round | any | required | Current planning round number | -| workbook | any | required | Workbook path or structured workbook reference | -| exit_code | any | required | Child process or tool exit status | -| result | any | None | Structured result from the preceding operation | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Always append a `round` event (child workbook finished) for audit / view. Optional `result` is the child `# main` return. SSE + optional TTY `plan:round` only when `stream` / `echo`. | - -Use `events`, `round`, `workbook`, `exit_code`, `result`=None, `stream`=False, `echo`=False as the inputs for this operation. - -Always append a `round` event (child workbook finished) for audit / view. Optional `result` is the child `# main` return. SSE + optional TTY `plan:round` only when `stream` / `echo`. - -`ev` = - -| type | round | workbook | exit_code | -|------|-------|----------|-----------| -| round | `round` | `workbook` | `exit_code` | - -1. `result` - We retain **`ev` = [Set the result field in the new record](table.put(in=`ev`, at="result", value=`result`))**. -2. * - **_ = 1** -We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. -1. `stream` - We **[Stream publish](sys.stream_publish(event=`ev`))**. -2. * - **_ = 1** -1. `echo` - We **[Print the prepared message](print(text="plan:round"))**. -2. * - **_ = 1** - -Return *events*. - -## plan_append_decision - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | any | required | Ordered semantic or provider stream-event records | -| decision | any | required | Structured planning decision | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| summary | any | None | Summary text or record from the preceding phase | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Always append a `decision` event. SSE publish only when `stream=True`. | - -Use `events`, `decision`, `stream`=False, `summary`=None as the inputs for this operation. - -Always append a `decision` event. SSE publish only when `stream=True`. - -`ev` = - -| type | decision | -|------|----------| -| decision | `decision` | - -1. `summary` - We retain **`ev` = [Set the summary field in the new record](table.put(in=`ev`, at="summary", value=`summary`))**. -2. * - **_ = 1** -We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. -1. `stream` - We **[Stream publish](sys.stream_publish(event=`ev`))**. -2. * - **_ = 1** - -Return *events*. - -## plan_merge_deltas - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | any | required | Ordered semantic or provider stream-event records | -| from | any | required | Source value of the transformation | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Bubble parent `complete stream=True` reasoning/deltas (and errors) into the plan event list. Skip nested `done` so plan owns the final `done`. Always merge into `events` when present; `stream` reserved for callers that also SSE-publish upstream. | - -Use `events`, `from`, `stream`=False as the inputs for this operation. - -Bubble parent `complete stream=True` reasoning/deltas (and errors) into the plan event list. Skip nested `done` so plan owns the final `done`. Always merge into `events` when present; `stream` reserved for callers that also SSE-publish upstream. - -- [ev](遍历 `from` 为 `ev`) - We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**. - 1. `t` == delta - We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. - 2. `t` == reasoning - We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. - 3. `t` == error - We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. - 4. * - **_ = 1** - -Return *events*. - -## plan_finish_stream - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| out | any | required | Structured output accumulated by the operation | -| events | any | required | Ordered semantic or provider stream-event records | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| trace | any | False | Whether to retain the documented execution trace | -| result | any | None | Structured result from the preceding operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Always append `done` and attach `events` on the result map (process audit even when not streaming). SSE publish of `done` only when `stream=True`. Optional `trace=True` writes the event list to writeback slot `trace`. | - -Use `out`, `events`, `stream`=False, `trace`=False, `result`=None as the inputs for this operation. - -Always append `done` and attach `events` on the result map (process audit even when not streaming). SSE publish of `done` only when `stream=True`. Optional `trace=True` writes the event list to writeback slot `trace`. - -We retain **`ev` = [Set the type field in the new record](table.put(in=None, at="type", value="done"))**. -1. `result` - We retain **`ev` = [Set the result field in the new record](table.put(in=`ev`, at="result", value=`result`))**. -2. * - **_ = 1** -1. `events` - We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. -2. * - We retain **`events` = [Append this item to the new list](table.append(list=None, item=`ev`))**. -1. `stream` - We **[Stream publish](sys.stream_publish(event=`ev`))**. -2. * - **_ = 1** -1. not `out` - We retain **`out` = [Empty map](table.empty_map())**. -2. * - **_ = 1** -We retain **`out` = [Set the events field in the new record](table.put(in=`out`, at="events", value=`events`))**. - -1. `trace` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`events`))**. - We **[Record](wb.record(value=`body`, key="trace"))**. -2. * - **_ = 1** - -Return *out*. - ---- - -# agent - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | required | Model resource or provider model identifier, as required by this operation | -| tools | any | required | Explicit tool whitelist or tool-specification records | -| standing | any | required | Standing instructions supplied by the author | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load ABI v2 agent plugin once (session bag + context queries). | - -Use `model`, `tools`, `standing` as the inputs for this operation. - -Load ABI v2 agent plugin once (session bag + context queries). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -We retain **`id` = [Alloc](agent_alloc())**. - -`h` = - -| _type | id | model | tools | -|-------|-----|-------|-------| -| agent | `id` | `model` | `tools` | - -1. `standing` - We retain **`h` = [Set the standing field in the new record](table.put(in=`h`, at="standing", value=`standing`))**. -2. * - **_ = 1** - -Return *h*. - -## clear_history - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Clear the plugin session bag for this agent id. | - -Clear the plugin session bag for this agent id. - -We retain **`id` = [Read the id field](json.get(value=`self`, key="id"))**. -We **[History clear](agent_history_clear(id=`id`))**. -Return *None*. - -## resolve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| near_match | any | True | Whether to consider near-match candidates | -| near_threshold | any | 0.78 | Minimum similarity score for near-match candidates | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Skill resolver (v2): exact → alias → canonical → near. Returns `mode` / `resource` / `llm_free` / `confidence`. Plugin ABI — no core host_* calls. | - -Use `task`, `kb_dir`=".marqdo/agent-kb", `near_match`=True, `near_threshold`=0.78 as the inputs for this operation. - -Skill resolver (v2): exact → alias → canonical → near. Returns `mode` / `resource` / `llm_free` / `confidence`. Plugin ABI — no core host_* calls. - -We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. -Return *[Resolve](agent_resolve(task=`task`, kb_dir=`kb_dir`, near_match=`near_match`, near_threshold=`near_threshold`, tools=`tools`))*. - -## route - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| backend | any | "auto" | Configured execution or provider backend | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | -| threshold | any | 0.78 | Policy threshold required by this operation | -| step_kind | any | None | Class of workbook step | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Adaptive Routing (Phase 4): abstract router — `marqdo` | `small-llm` | `llm` | `auto`. `jev` is accepted as a **compat alias** of `small-llm` (not a first-class backend). `auto` cascades policy → kb → small-llm request. May return `needs_llm=True` + `prompt` for the caller to complete with `router_model` (any llm handle), then `route_apply`. Optional `step_kind=` (O3) selects backend via module `## step_route` before the ABI call. | - -Use `task`, `backend`="auto", `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `threshold`=0.78, `step_kind`=None as the inputs for this operation. - -Adaptive Routing (Phase 4): abstract router — `marqdo` | `small-llm` | `llm` | `auto`. `jev` is accepted as a **compat alias** of `small-llm` (not a first-class backend). `auto` cascades policy → kb → small-llm request. May return `needs_llm=True` + `prompt` for the caller to complete with `router_model` (any llm handle), then `route_apply`. -Optional `step_kind=` (O3) selects backend via module `## step_route` before the ABI call. - -1. `step_kind` - We retain **`sr` = [Step route](step_route(kind=`step_kind`))**. - We retain **`backend` = [Read the backend field](json.get(value=`sr`, key="backend"))**. -2. * - **_ = 1** - -We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. -Return *[Route](agent_route(task=`task`, backend=`backend`, kb_dir=`kb_dir`, memory_dir=`memory_dir`, threshold=`threshold`, tools=`tools`))*. - -## route_apply - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| backend | any | "small-llm" | Configured execution or provider backend | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply a router model line (`SKILL:` / `EXPLORE`) to a kb skill hit. | - -Use `task`, `reply`, `kb_dir`=".marqdo/agent-kb", `backend`="small-llm" as the inputs for this operation. - -Apply a router model line (`SKILL:` / `EXPLORE`) to a kb skill hit. - -Return *[Route apply](agent_route_apply(task=`task`, reply=`reply`, kb_dir=`kb_dir`, backend=`backend`))*. - -## compile_policy - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | -| min_evidence | any | 3 | Minimum evidence count required before promotion | -| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Policy Compilation: stable episode skill selections → `policies/router.mq.md` (deterministic Marqdo rules). | - -Use `memory_dir`=".marqdo/agent-memory", `min_evidence`=3, `force`=False as the inputs for this operation. - -Policy Compilation: stable episode skill selections → `policies/router.mq.md` (deterministic Marqdo rules). - -Return *[Compile policy](agent_compile_policy(memory_dir=`memory_dir`, min_evidence=`min_evidence`, force=`force`))*. - -## maybe_compile_policy - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | -| min_evidence | any | 3 | Minimum evidence count required before promotion | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Learn gate for the Adaptive Router policy layer. | - -Use `memory_dir`=".marqdo/agent-memory", `min_evidence`=3 as the inputs for this operation. - -Learn gate for the Adaptive Router policy layer. - -Return *[Maybe compile policy](agent_maybe_compile_policy(memory_dir=`memory_dir`, min_evidence=`min_evidence`))*. - -## record_episode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| status | any | "ok" | Domain status recorded in the structured result | -| result | any | None | Structured result from the preceding operation | -| mode | any | "explore" | Operation mode listed in the function behavior | -| skill | any | "none" | Skill source or identifier selected for inspection | -| observation | any | None | Tool observation or workbook result retained for the next turn | -| workbook | any | None | Workbook path or structured workbook reference | -| cache | any | None | Whether to use the documented result cache | -| match | any | None | Resolved match or match policy | -| llm_calls | any | 0 | Observed model-call count | -| tool_calls | any | 0 | Observed tool-call count | -| error | any | None | Structured failure information supplied by the caller | -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). Memory is executable documentation, not a vector bag. | - -Use `task`, `status`="ok", `result`=None, `mode`="explore", `skill`="none", `observation`=None, `workbook`=None, `cache`=None, `match`=None, `llm_calls`=0, `tool_calls`=0, `error`=None, `memory_dir`=".marqdo/agent-memory" as the inputs for this operation. - -Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). Memory is executable documentation, not a vector bag. - -Return *[Record episode](agent_record_episode(task=`task`, status=`status`, result=`result`, mode=`mode`, skill=`skill`, observation=`observation`, workbook=`workbook`, cache=`cache`, match=`match`, llm_calls=`llm_calls`, tool_calls=`tool_calls`, error=`error`, memory_dir=`memory_dir`))*. - -## quarantine - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| slug | any | required | Knowledge entry identifier within the configured knowledge directory | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| reason | any | "sandbox_or_harness_failed" | Human-readable explanation for the recorded decision | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | O5: mark OKF skill `status: quarantine` and force `llm_free: false`. Regression fixtures stay with the slug. | - -Use `slug`, `kb_dir`=".marqdo/agent-kb", `reason`="sandbox_or_harness_failed" as the inputs for this operation. - -O5: mark OKF skill `status: quarantine` and force `llm_free: false`. Regression fixtures stay with the slug. - -Return *[Kb quarantine](agent_kb_quarantine(kb_dir=`kb_dir`, slug=`slug`, reason=`reason`))*. - -## maybe_learn - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | -| improve_every | any | 3 | Number of observations between improvement attempts | -| promote | any | True | Whether successful evidence may be promoted | -| candidate_only | any | False | Whether to retain a candidate without publishing it | -| product_gate_ok | any | True | Result of the external product gate | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Offline learn gate: when ≥ `improve_every` successful episodes share a task hash, generalize → synthesize → compile → optional OKF promote (`llm_free`). Also attempts Policy Compilation for Adaptive Routing. O2: promote path requires sandbox proof unless `require_proof=false`. M04: `candidate_only=True` or `product_gate_ok=False` forces promote off via eng_publish_gate. | - -Use `task`, `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `improve_every`=3, `promote`=True, `candidate_only`=False, `product_gate_ok`=True as the inputs for this operation. - -Offline learn gate: when ≥ `improve_every` successful episodes share a task hash, generalize → synthesize → compile → optional OKF promote (`llm_free`). Also attempts Policy Compilation for Adaptive Routing. -O2: promote path requires sandbox proof unless `require_proof=false`. -M04: `candidate_only=True` or `product_gate_ok=False` forces promote off via eng_publish_gate. - -We retain **`gate` = [Eng publish gate](> `self`.eng_publish_gate project="." candidate_only=`candidate_only` product_gate_ok=`product_gate_ok` )**. -We retain **`may_prom` = [Read the may_promote field](json.get(value=`gate`, key="may_promote"))**. -1. not `may_prom` - We retain **promote = False**. -2. * - **_ = 1** -We retain **`skill_learn` = [Maybe learn](agent_maybe_learn(task=`task`, kb_dir=`kb_dir`, memory_dir=`memory_dir`, improve_every=`improve_every`, promote=`promote`))**. -We retain **`policy_learn` = [Maybe compile policy](agent_maybe_compile_policy(memory_dir=`memory_dir`, min_evidence=`improve_every`))**. -We retain **`sl` = [Read the learned field](json.get(value=`skill_learn`, key="learned"))**. - -`out` = - -| learned | skill | policy | promote_allowed | gate | -|---------|-------|--------|-----------------|------| -| `sl` | `skill_learn` | `policy_learn` | `may_prom` | `gate` | - -Return *out*. - -## compile - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | -| min_evidence | any | 3 | Minimum evidence count required before promotion | -| promote | any | True | Whether successful evidence may be promoted | -| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Compile a candidate skill into versioned `skills//vN.mq.md` and optionally promote into agent-kb. | - -Use `task`, `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `min_evidence`=3, `promote`=True, `force`=False as the inputs for this operation. - -Compile a candidate skill into versioned `skills//vN.mq.md` and optionally promote into agent-kb. - -Return *[Compile skill](agent_compile_skill(task=`task`, kb_dir=`kb_dir`, memory_dir=`memory_dir`, min_evidence=`min_evidence`, promote=`promote`, force=`force`))*. - -## metrics - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Reasoning amortization stats over recorded episodes (`avg_llm_calls`, `compiled_runs`, …). | - -Use `memory_dir`=".marqdo/agent-memory" as the inputs for this operation. - -Reasoning amortization stats over recorded episodes (`avg_llm_calls`, `compiled_runs`, …). - -Return *[Metrics](agent_metrics(memory_dir=`memory_dir`))*. - -## run - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | -| learn | any | True | Whether to record or learn from this operation | -| verify | any | True | Whether to run the documented verifier | -| writeback | any | True | Whether to write the observation back to its author document | -| reuse | any | True | Whether to search for reusable knowledge before new work | -| near_match | any | True | Whether to consider near-match candidates | -| near_threshold | any | 0.78 | Minimum similarity score for near-match candidates | -| promote | any | True | Whether successful evidence may be promoted | -| improve_every | any | 3 | Number of observations between improvement attempts | -| explore_n | any | 3 | Maximum configured exploration attempts | -| max_rounds | any | 4 | Maximum workbook planning rounds | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| trace | any | False | Whether to retain the documented execution trace | -| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | -| router | any | "auto" | Router configuration or route-policy resource | -| router_model | any | None | Model resource used for routing | -| resume_id | any | None | Identifier of the stored continuation checkpoint | -| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | -| sandbox | any | False | Whether to use the CoW trial path | -| sandbox_profile | any | "default" | Capability profile for CoW execution | -| efi | any | True | Structured effect and failure information | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) or `plan` → record episode → maybe_learn (skill + policy). `router` = `auto`|`marqdo`|`small-llm`|`llm` (`jev`→`small-llm` alias). Optional `router_model` (llm handle) answers `needs_llm` prompts — small models welcome. | - -Use `task`, `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `learn`=True, `verify`=True, `writeback`=True, `reuse`=True, `near_match`=True, `near_threshold`=0.78, `promote`=True, `improve_every`=3, `explore_n`=3, `max_rounds`=4, `stream`=False, `echo`=False, `trace`=False, `force`=False, `router`="auto", `router_model`=None, `resume_id`=None, `resume_dir`=".marqdo/agent-resume", `sandbox`=False, `sandbox_profile`="default", `efi`=True as the inputs for this operation. - -Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) or `plan` → record episode → maybe_learn (skill + policy). `router` = `auto`|`marqdo`|`small-llm`|`llm` (`jev`→`small-llm` alias). Optional `router_model` (llm handle) answers `needs_llm` prompts — small models welcome. -`sandbox=True` (O1 opt-in): workbook paths run via CoW trial before host commit. `efi=True` (O3): EKC preflight before explore; REUSE short-circuits. Pass `efi=False` to keep legacy golds that skip eng knowledge. - -Use this entry when the application wants the full reuse-and-learning lifecycle. A single conversational turn belongs in step; run first tries existing executable knowledge and can fall back to a workbook plan. The output records which execution mode actually supplied the result, allowing callers to distinguish compiled reuse, router-assisted reuse and exploration instead of inferring that distinction from answer text. - -Routing precedes exploration. A matched resource is awaited as a workbook; a failed child does not count as a reusable success. When a route needs a model, the configured routing model, or the agent's normal model, produces the restricted selection reply. Applying that reply resolves it to an actual knowledge resource. Model words alone never stand in for the child's returned value. - -Engineering preflight supplies an additional reuse gate. A REUSE result can bind and execute an existing engineering capability; a refusal to create is returned as an error rather than ignored. Missing engineering knowledge is distinguished from a positive refusal. The lower resolver then checks reusable skills, including whether an entry is marked llm_free, before a new plan is requested. Preserve this order when extending the method so new capabilities do not quietly skip existing knowledge. - -The workbook await helper owns the execution boundary. With sandbox enabled it uses the configured CoW path; attaching a profile name to an answer is insufficient. Native plugin loading and explicit runtime grants are still required by the selected resource. A successful reused child can therefore avoid parent model calls, while an exploratory result carries the usage reported by its plan. - -After execution, the method extracts task status, result, skill and observation for the episode record. Verification here is a recorded execution-status check; it is not an independent domain proof of the answer. Applications with stronger requirements must validate the returned value using their own task-specific assertions. Do not interpret a status string as evidence that files, network writes or generated source were reviewed. - -Episodes persist the observed outcome for later reuse decisions. Learning is attempted only for successful outcomes when enabled, and promotion follows the existing evidence path. The result attaches execution details, model usage, routing information and the episode reference. An optional resume identifier also saves a checkpoint and effect-ledger watermark. These records describe what happened; they do not make an uncertain external effect safe to repeat. - -For a reproducible investigation, retain the returned workbook reference and observation together. The same goal text can resolve differently after knowledge promotion, so a later rerun of the request is not a substitute for examining the recorded resource. - -We retain **efi_pf = None**. -1. `efi` - We retain **`efi_pf` = [Preflight](> `self`.preflight task=`task` )**. -2. * - **_ = 1** - -We retain **`routed` = [Route](> `self`.route task=`task` backend=`router` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`near_threshold` )**. -We retain **`route_matched` = [Read the matched field](json.get(value=`routed`, key="matched"))**. -We retain **`needs_llm` = [Read the needs_llm field](json.get(value=`routed`, key="needs_llm"))**. -We retain **exec_mode = "explore"**. -We retain **llm_calls = 0**. -We retain **tokens = 0**. -We retain **token_cost = 0**. -We retain **out = None**. -We retain **`route_backend` = [Read the backend field](json.get(value=`routed`, key="backend"))**. - -1. `route_matched` - We retain **`path` = [Read the resource field](json.get(value=`routed`, key="resource"))**. - 1. `path` - We retain **`aw` = [Await workbook](await_workbook(path=`path`, sandbox=`sandbox`, sandbox_profile=`sandbox_profile`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - 1. `code` == 0 - We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`task`, improve_every=`improve_every`))**. - We retain **`lf` = [Read the llm_free field](json.get(value=`routed`, key="llm_free"))**. - 1. `lf` - We retain **exec_mode = "compiled"**. - 2. * - We retain **exec_mode = "routed"**. - We retain **`rmode` = [Read the mode field](json.get(value=`routed`, key="mode"))**. - We retain **`sk` = [Read the skill field](json.get(value=`routed`, key="skill"))**. - **out = ** - - | status | goal | result | workbook | cache | match | skill | observation | summary | route | - |--------|------|--------|----------|-------|-------|-------|-------------|---------|-------| - | ok | `task` | `child_val` | `path` | hit | `rmode` | `sk` | `last_obs` | adaptive route hit | `routed` | - - We retain **llm_calls = 0**. - 1. `stream` - We retain **`_ev` = [Empty list](table.empty_list())**. - We retain **`_ev` = [Plan append decision](plan_append_decision(events=`_ev`, decision="REUSE", stream=True, summary="adaptive route hit"))**. - We retain **`_ev` = [Plan append round](plan_append_round(events=`_ev`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=True))**. - 2. * - **_ = 1** - 2. * - We retain **route_matched = False**. - 2. * - We retain **route_matched = False**. -2. * - **_ = 1** - -1. `route_matched` - **_ = 1** -2. `needs_llm` - 1. `router_model` - We retain **`prompt` = [Read the prompt field](json.get(value=`routed`, key="prompt"))**. - We retain **`turn` = [Model turn](model_turn(model=`router_model`, prompt=`prompt`, stream=`stream`, echo=`echo`))**. - We retain **`reply` = [Read the text field](json.get(value=`turn`, key="text"))**. - We retain **`llm_calls` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. - We retain **`tokens` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. - We retain **`applied` = [Route apply](> `self`.route_apply task=`task` reply=`reply` kb_dir=`kb_dir` backend=`router` )**. - We retain **`am` = [Read the matched field](json.get(value=`applied`, key="matched"))**. - 1. `am` - We retain **`path` = [Read the resource field](json.get(value=`applied`, key="resource"))**. - We retain **`aw` = [Await workbook](await_workbook(path=`path`, sandbox=`sandbox`, sandbox_profile=`sandbox_profile`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - 1. `code` == 0 - We retain **exec_mode = "routed"**. - We retain **`sk` = [Read the skill field](json.get(value=`applied`, key="skill"))**. - **out = ** - - | status | goal | result | workbook | cache | match | skill | observation | summary | route | - |--------|------|--------|----------|-------|-------|-------|-------------|---------|-------| - | ok | `task` | `child_val` | `path` | soft-hit | routed | `sk` | `last_obs` | router model selected skill | `applied` | - - We retain **route_matched = True**. - 2. * - We retain **route_matched = False**. - 2. * - We retain **route_matched = False**. - 2. * - We retain **route_matched = False**. -3. * - **_ = 1** - -1. `route_matched` - **_ = 1** -2. * - 1. `efi_pf` - We retain **`efi_st` = [Read the status field](json.get(value=`efi_pf`, key="status"))**. - We retain **`efi_dec` = [Read the decision field](json.get(value=`efi_pf`, key="decision"))**. - We retain **`efi_allow` = [Read the create_allowed field](json.get(value=`efi_pf`, key="create_allowed"))**. - 1. `efi_st` == "missing_knowledge" - **_ = 1** - 2. `efi_dec` == "REUSE" - We retain **`efi_exec` = [Eng bind execute](agent_eng_bind_execute(project=".", query=`task`, policy="pure", candidate_only=False))**. - We retain **`efi_ok` = [Read the ok field](json.get(value=`efi_exec`, key="ok"))**. - 1. `efi_ok` - We retain **exec_mode = "efi_bound"**. - **out = ** - - | status | goal | result | summary | efi | reuse_trace | - |--------|------|--------|---------|-----|-------------| - | ok | `task` | `efi_exec` | EFI REUSE bound+executed | `efi_pf` | `efi_exec` | - - 2. * - **_ = 1** - 3. `efi_dec` == "ADAPT" - **_ = 1** - 4. `efi_allow` - **_ = 1** - 5. * - **out = ** - - | status | goal | error | summary | efi | - |--------|------|-------|---------|-----| - | error | `task` | efi_create_denied | EKC preflight denied CREATE | `efi_pf` | - - We retain **exec_mode = "efi"**. - 2. * - **_ = 1** - - 1. `out` - **_ = 1** - 2. * - We retain **`resolved` = [Resolve](> `self`.resolve task=`task` kb_dir=`kb_dir` near_match=`near_match` near_threshold=`near_threshold` )**. - We retain **`mode` = [Read the mode field](json.get(value=`resolved`, key="mode"))**. - We retain **`llm_free` = [Read the llm_free field](json.get(value=`resolved`, key="llm_free"))**. - 1. not `llm_free` - We retain **llm_free = False**. - 1. `llm_free` - We retain **`path` = [Read the resource field](json.get(value=`resolved`, key="resource"))**. - We retain **`aw` = [Await workbook](await_workbook(path=`path`, sandbox=`sandbox`, sandbox_profile=`sandbox_profile`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - 1. `code` == 0 - We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`task`, improve_every=`improve_every`))**. - We retain **exec_mode = "compiled"**. - We retain **`sk` = [Read the skill field](json.get(value=`resolved`, key="skill"))**. - **out = ** - - | status | goal | result | workbook | cache | match | skill | observation | summary | - |--------|------|--------|----------|-------|-------|-------|-------------|--------| - | ok | `task` | `child_val` | `path` | hit | `mode` | `sk` | `last_obs` | compiled skill (llm_free) | - - We retain **llm_calls = 0**. - 2. * - We retain **`out` = [Plan](> `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force` )**. - We retain **exec_mode = "explore"**. - We retain **`llm_calls` = [Read the llm_calls field](json.get(value=`out`, key="llm_calls"))**. - We retain **`tokens` = [Read the tokens field](json.get(value=`out`, key="tokens"))**. - 1. `llm_calls` == None - We retain **llm_calls = 1**. - 1. `tokens` == None - We retain **tokens = 0**. - 2. * - We retain **`out` = [Plan](> `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force` )**. - We retain **`cache` = [Read the cache field](json.get(value=`out`, key="cache"))**. - 1. `cache` == "hit" - We retain **exec_mode = "compiled"**. - We retain **llm_calls = 0**. - We retain **tokens = 0**. - 2. `cache` == "soft-hit" - We retain **exec_mode = "near"**. - We retain **llm_calls = 0**. - We retain **tokens = 0**. - 3. * - We retain **exec_mode = "explore"**. - We retain **`llm_calls` = [Read the llm_calls field](json.get(value=`out`, key="llm_calls"))**. - We retain **`tokens` = [Read the tokens field](json.get(value=`out`, key="tokens"))**. - 1. `llm_calls` == None - We retain **llm_calls = 1**. - 1. `tokens` == None - We retain **tokens = 0**. - -We retain **`st` = [Read the status field](json.get(value=`out`, key="status"))**. -We retain **`res` = [Read the result field](json.get(value=`out`, key="result"))**. -We retain **`wb_path` = [Read the workbook field](json.get(value=`out`, key="workbook"))**. -We retain **`obs` = [Read the observation field](json.get(value=`out`, key="observation"))**. -We retain **`sk2` = [Read the skill field](json.get(value=`out`, key="skill"))**. -We retain **`cache2` = [Read the cache field](json.get(value=`out`, key="cache"))**. -We retain **`match2` = [Read the match field](json.get(value=`out`, key="match"))**. -We retain **`err` = [Read the error field](json.get(value=`out`, key="error"))**. - -1. `verify` - 1. `st` == "ok" - We retain **verification = "status: passed"**. - 2. * - We retain **verification = "status: failed"**. -2. * - We retain **verification = "status: skipped"**. - -We retain **`ep` = [Record episode](> `self`.record_episode task=`task` status=`st` result=`res` mode=`exec_mode` skill=`sk2` observation=`obs` workbook=`wb_path` cache=`cache2` match=`match2` llm_calls=`llm_calls` tokens=`tokens` error=`err` memory_dir=`memory_dir` )**. - -We retain **learning = None**. -1. `learn` - 1. `st` == "ok" - We retain **`learning` = [Maybe learn](> `self`.maybe_learn task=`task` kb_dir=`kb_dir` memory_dir=`memory_dir` improve_every=`improve_every` promote=`promote` )**. - 2. * - We retain **learning = None**. -2. * - **_ = 1** - -We retain **token_cost = tokens**. -**usage = ** - -| llm_calls | tokens | token_cost | -|-----------|--------|------------| -| `llm_calls` | `tokens` | `token_cost` | - -**execution = ** - -| mode | llm_calls | tokens | token_cost | skill | router | -|------|-----------|--------|------------|-------|--------| -| `exec_mode` | `llm_calls` | `tokens` | `token_cost` | `sk2` | `route_backend` | - -We retain **`out` = [Set the execution field in the new record](table.put(in=`out`, at="execution", value=`execution`))**. -We retain **`out` = [Set the episode field in the new record](table.put(in=`out`, at="episode", value=`ep`))**. -We retain **`out` = [Set the route field in the new record](table.put(in=`out`, at="route", value=`routed`))**. -We retain **`out` = [Set the usage field in the new record](table.put(in=`out`, at="usage", value=`usage`))**. -We retain **`out` = [Set the token_cost field in the new record](table.put(in=`out`, at="token_cost", value=`token_cost`))**. -1. `learning` - We retain **`out` = [Set the learning field in the new record](table.put(in=`out`, at="learning", value=`learning`))**. -2. * - **_ = 1** - -1. `efi_pf` - We retain **`out` = [Set the efi field in the new record](table.put(in=`out`, at="efi", value=`efi_pf`))**. -2. * - **_ = 1** - -1. `resume_id` - We retain **`_wm` = [Effects watermark](effects_watermark(ledger_dir=".marqdo/agent-effects", logical_run_id=`resume_id`))**. - We retain **`_ckpt` = [Resume save](resume_save(id=`resume_id`, goal=`task`, task=`task`, status=`st`, round=1, workbook=`wb_path`, result=`res`, route=`routed`, resume_dir=`resume_dir`, checkpoint_v2=True, attempt_id="attempt_1", effect_ledger_watermark=`_wm`))**. - We retain **`out` = [Set the resume field in the new record](table.put(in=`out`, at="resume", value=`_ckpt`))**. - We retain **`out` = [Set the effect_ledger_watermark field in the new record](table.put(in=`out`, at="effect_ledger_watermark", value=`_wm`))**. -2. * - **_ = 1** - -Return *out*. - -## step - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| writeback | any | True | Whether to write the observation back to its author document | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| max_reads | any | 2 | Maximum context-deepening reads | -| sandbox | any | False | Whether to use the CoW trial path | -| sandbox_profile | any | "default" | Capability profile for CoW execution | -| resume_id | any | None | Identifier of the stored continuation checkpoint | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | One atomic turn: budgeted context → LLM → optional `READ:` deepen → optional tool via subtask. Returns a *map* (`status`, `task`, `decision`, and on success `result` plus optional `tool` / `tool_result`; on failure `error`). By default (`writeback=True`) persists that map under named slots `ok` / `error` at the call site; pass `writeback=False` to skip. Optional `resume_id` scopes EffectLedger idempotency for mutating tools. With `stream=True`, the model call uses SSE; `echo=True` prints delta text to stdout as it arrives. The returned map is unchanged (final `result` string). Context source/skill start at default budget; up to `max_reads` of `READ:source` / `READ:skill` deepen before CALL/answer. | - -Use `task`, `writeback`=True, `stream`=False, `echo`=False, `max_reads`=2, `sandbox`=False, `sandbox_profile`="default", `resume_id`=None as the inputs for this operation. - -One atomic turn: budgeted context → LLM → optional `READ:` deepen → optional tool via subtask. Returns a *map* (`status`, `task`, `decision`, and on success `result` plus optional `tool` / `tool_result`; on failure `error`). By default (`writeback=True`) persists that map under named slots `ok` / `error` at the call site; pass `writeback=False` to skip. -Optional `resume_id` scopes EffectLedger idempotency for mutating tools. - -With `stream=True`, the model call uses SSE; `echo=True` prints delta text to stdout as it arrives. The returned map is unchanged (final `result` string). Context source/skill start at default budget; up to `max_reads` of `READ:source` / `READ:skill` deepen before CALL/answer. -`sandbox=True` (O1 opt-in): attach the sandbox profile row on the result map (trial via `## trial` / `run sandbox=`). - -We retain **`id` = [Read the id field](json.get(value=`self`, key="id"))**. -We retain **`model` = [Read the model field](json.get(value=`self`, key="model"))**. -We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. - -`user_turn` = - -| role | content | -|------|---------| -| user | `task` | - -We **[Append this item to the new list](agent_history_append(id=`id`, item=`user_turn`))**. - -We retain **source_depth = "default"**. -We retain **skill_depth = "default"**. -We retain **reads_left = max_reads**. -We retain **reply = None**. -We retain **decision = None**. -We retain **llm_calls = 0**. -We retain **tokens = 0**. - -We retain **transport_err = None**. - -- `reads_left` > 0 - 1. `decision` - We retain **reads_left = 0**. - 2. `transport_err` - We retain **reads_left = 0**. - 3. * - We retain **`ctx` = [Build step context](build_step_context(agent=`self`, task=`task`, source_depth=`source_depth`, skill_depth=`skill_depth`))**. - We retain **`turn` = [Model turn](model_turn(model=`model`, prompt=`ctx`, stream=`stream`, echo=`echo`))**. - We retain **`terr` = [Read the error field](json.get(value=`turn`, key="error"))**. - 1. `terr` - We retain **transport_err = `terr`**. - We retain **reads_left = 0**. - 2. * - We retain **`reply` = [Read the text field](json.get(value=`turn`, key="text"))**. - We retain **`c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. - We retain **`t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. - 1. not `c` - We retain **c = 0**. - 2. * - **_ = 1** - 1. not `t` - We retain **t = 0**. - 2. * - **_ = 1** - We retain **llm_calls = llm_calls + c**. - We retain **tokens = tokens + t**. - We retain **`reply` = [Trim](trim(value=`reply`))**. - We retain **`rk` = [Extract plan read](extract_plan_read(reply=`reply`))**. - 1. `rk` == source - We retain **source_depth = "deep"**. - We retain **reads_left = reads_left - 1**. - 2. `rk` == skill - We retain **skill_depth = "deep"**. - We retain **reads_left = reads_left - 1**. - 3. * - We retain **decision = reply**. - We retain **reads_left = 0**. - -1. `transport_err` - - `out` = - - | status | task | error | llm_calls | tokens | - |--------|------|-------|-----------|--------| - | error | `task` | `transport_err` | `llm_calls` | `tokens` | - - 1. `writeback` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. - We **[Record](wb.record(value=`body`, key="error"))**. - 2. * - **_ = 1** - Return *out*. -2. * - **_ = 1** - -We retain **`reply` = [Trim](trim(value=`reply`))**. -We retain **decision = reply**. -We retain **`tool_name` = [Extract tool name](extract_tool_name(reply=`reply`))**. - -`out` = - -| status | task | decision | -|--------|------|----------| -| ok | `task` | `decision` | - -1. `tool_name` - We retain **`tool_out` = [Run tool](run_tool(tools=`tools`, name=`tool_name`, logical_run_id=`resume_id`))**. - We retain **`tool_s` = [Encode the structured value as JSON text](json.stringify(value=`tool_out`))**. - We retain **`deny` = [Split](split(value=`tool_s`, sep="Tool not allowed"))**. - We retain **`deny_n` = [Len](len(value=`deny`))**. - 1. `deny_n` > 1 - We retain **`task_s` = [Encode the structured value as JSON text](json.stringify(value=`task`))**. - We retain **fp = "Tool CALL was rejected (not on the tools whitelist). Do NOT emit CALL. Answer the user task directly with the final answer only.\n\nUser task:\n"**. - We retain **fp = fp + task_s**. - We retain **`turn2` = [Model turn](model_turn(model=`model`, prompt=`fp`, stream=`stream`, echo=`echo`))**. - We retain **`reply` = [Read the text field](json.get(value=`turn2`, key="text"))**. - We retain **`c` = [Read the llm_calls field](json.get(value=`turn2`, key="llm_calls"))**. - We retain **`t` = [Read the tokens field](json.get(value=`turn2`, key="tokens"))**. - 1. not `c` - We retain **c = 0**. - 2. * - **_ = 1** - 1. not `t` - We retain **t = 0**. - 2. * - **_ = 1** - We retain **llm_calls = llm_calls + c**. - We retain **tokens = tokens + t**. - We retain **`out` = [Set the denied_tool field in the new record](table.put(in=`out`, at="denied_tool", value=`tool_name`))**. - We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`reply`))**. - 2. * - We retain **`task_s` = [Encode the structured value as JSON text](json.stringify(value=`task`))**. - We retain **fp = "The user asked:"**. - We retain **fp = fp + task_s**. - We retain **fp = fp + ". Tool"**. - We retain **fp = fp + tool_name**. - We retain **fp = fp + "ran via subtask and returned:"**. - We retain **fp = fp + tool_s**. - We retain **fp = fp + ". Reply to the user briefly."**. - We retain **`turn2` = [Model turn](model_turn(model=`model`, prompt=`fp`, stream=`stream`, echo=`echo`))**. - We retain **`reply` = [Read the text field](json.get(value=`turn2`, key="text"))**. - We retain **`c` = [Read the llm_calls field](json.get(value=`turn2`, key="llm_calls"))**. - We retain **`t` = [Read the tokens field](json.get(value=`turn2`, key="tokens"))**. - 1. not `c` - We retain **c = 0**. - 2. * - **_ = 1** - 1. not `t` - We retain **t = 0**. - 2. * - **_ = 1** - We retain **llm_calls = llm_calls + c**. - We retain **tokens = tokens + t**. - We retain **`out` = [Set the tool field in the new record](table.put(in=`out`, at="tool", value=`tool_name`))**. - We retain **`out` = [Set the tool_result field in the new record](table.put(in=`out`, at="tool_result", value=`tool_s`))**. - We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`reply`))**. -2. * - We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`reply`))**. - -We retain **`out` = [Set the llm_calls field in the new record](table.put(in=`out`, at="llm_calls", value=`llm_calls`))**. -We retain **`out` = [Set the tokens field in the new record](table.put(in=`out`, at="tokens", value=`tokens`))**. - -1. `sandbox` - We retain **`prof` = [Profile](sandbox.profile(name=`sandbox_profile`))**. - We retain **`out` = [Set the sandbox_profile field in the new record](table.put(in=`out`, at="sandbox_profile", value=`prof`))**. -2. * - **_ = 1** - -`as_turn` = - -| role | content | -|------|---------| -| assistant | `reply` | - -We **[Append this item to the new list](agent_history_append(id=`id`, item=`as_turn`))**. - -1. `writeback` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. - We retain **`st` = [Read the status field](json.get(value=`out`, key="status"))**. - 1. `st` == "ok" - We **[Record](wb.record(value=`body`, key="ok"))**. - 2. * - We **[Record](wb.record(value=`body`, key="error"))**. -2. * - **_ = 1** - -Return *out*. - -## preflight - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| root | any | "." | Explicit root directory for discovery or isolated execution | -| marqdo_dir | any | None | Marqdo project directory used for engineering discovery | -| min_candidates | any | 3 | Minimum reusable candidates to seek before adaptation | -| allow_create_after | any | 2 | Number of bounded attempts before new work may be proposed | -| reuse_threshold | any | 0.72 | Score required to choose reuse | -| adapt_threshold | any | 0.45 | Score required to choose adaptation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Engineering First Information gate (008 / EKC). Reads compiled `.marqdo` knowledge. Returns `{status,decision,create_allowed,existing,constraints,decisions,failures,recommended,context_path}`. Hard rule: generate only when `create_allowed` is true (or decision is REUSE/ADAPT). | - -Use `task`, `root`=".", `marqdo_dir`=None, `min_candidates`=3, `allow_create_after`=2, `reuse_threshold`=0.72, `adapt_threshold`=0.45 as the inputs for this operation. - -Engineering First Information gate (008 / EKC). Reads compiled `.marqdo` knowledge. -Returns `{status,decision,create_allowed,existing,constraints,decisions,failures,recommended,context_path}`. -Hard rule: generate only when `create_allowed` is true (or decision is REUSE/ADAPT). - -1. `marqdo_dir` - We retain **`pf` = [Eng preflight](agent_eng_preflight(task=`task`, root=`root`, marqdo_dir=`marqdo_dir`, min_candidates=`min_candidates`, allow_create_after=`allow_create_after`, reuse_threshold=`reuse_threshold`, adapt_threshold=`adapt_threshold`))**. -2. * - We retain **`pf` = [Eng preflight](agent_eng_preflight(task=`task`, root=`root`, min_candidates=`min_candidates`, allow_create_after=`allow_create_after`, reuse_threshold=`reuse_threshold`, adapt_threshold=`adapt_threshold`))**. - -Return *pf*. - -## eng_reuse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| task | any | required | Structured task or text supplied to the agent | -| root | any | "." | Explicit root directory for discovery or isolated execution | -| marqdo_dir | any | None | Marqdo project directory used for engineering discovery | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Alias of `preflight` focused on REUSE / ADAPT / CREATE payload (discovery_only). | - -Use `task`, `root`=".", `marqdo_dir`=None as the inputs for this operation. - -Alias of `preflight` focused on REUSE / ADAPT / CREATE payload (discovery_only). - -1. `marqdo_dir` - Return *[Eng reuse](agent_eng_reuse(task=`task`, root=`root`, marqdo_dir=`marqdo_dir`))*. -2. * - Return *[Eng reuse](agent_eng_reuse(task=`task`, root=`root`))*. - ---- - -## eng_bind_execute - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| project | any | "." | Project root or project metadata | -| query | any | required | Text used to search the bounded catalog or tool registry | -| policy | any | "pure" | Policy data governing this operation | -| inputs | any | None | Structured input record for the bound engineering capability | -| candidate_only | any | False | Whether to retain a candidate without publishing it | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | M04: discover → bind → execute → record. Prefer over treating eng_reuse scores as execution. | - -Use `project`=".", `query`, `policy`="pure", `inputs`=None, `candidate_only`=False as the inputs for this operation. - -M04: discover → bind → execute → record. Prefer over treating eng_reuse scores as execution. - -1. `inputs` - Return *[Eng bind execute](agent_eng_bind_execute(project=`project`, query=`query`, policy=`policy`, inputs=`inputs`, candidate_only=`candidate_only`))*. -2. * - Return *[Eng bind execute](agent_eng_bind_execute(project=`project`, query=`query`, policy=`policy`, candidate_only=`candidate_only`))*. - ---- - -## eng_publish_gate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| project | any | "." | Project root or project metadata | -| artifact_id | any | None | Resolved artifact identifier from the compiler/catalog | -| candidate_only | any | False | Whether to retain a candidate without publishing it | -| product_gate_ok | any | True | Result of the external product gate | -| policy | any | "business" | Policy data governing this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Refuse promote when candidate_only or product/verification gate fails. | - -Use `project`=".", `artifact_id`=None, `candidate_only`=False, `product_gate_ok`=True, `policy`="business" as the inputs for this operation. - -Refuse promote when candidate_only or product/verification gate fails. - -Return *[Eng publish gate](agent_eng_publish_gate(project=`project`, artifact_id=`artifact_id`, candidate_only=`candidate_only`, product_gate_ok=`product_gate_ok`, policy=`policy`))*. - -## eng_record - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| decision | any | required | Structured planning decision | -| root | any | "." | Explicit root directory for discovery or isolated execution | -| marqdo_dir | any | None | Marqdo project directory used for engineering discovery | -| duplicated | any | False | Whether a duplicate capability was detected | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Record REUSE/ADAPT/CREATE into `.marqdo/agent/episodes/reuse_metrics.json`. | - -Use `decision`, `root`=".", `marqdo_dir`=None, `duplicated`=False as the inputs for this operation. - -Record REUSE/ADAPT/CREATE into `.marqdo/agent/episodes/reuse_metrics.json`. - -1. `marqdo_dir` - Return *[Eng record](agent_eng_record(decision=`decision`, root=`root`, marqdo_dir=`marqdo_dir`, duplicated=`duplicated`))*. -2. * - Return *[Eng record](agent_eng_record(decision=`decision`, root=`root`, duplicated=`duplicated`))*. - -## plan - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| goal | any | required | Human task goal represented by this operation | -| workbook_dir | any | None | Directory in which the planner owns its workbook files | -| workbook | any | None | Workbook path or structured workbook reference | -| max_rounds | any | 4 | Maximum workbook planning rounds | -| confirm | any | False | Whether decomposition confirmation is requested | -| writeback | any | True | Whether to write the observation back to its author document | -| skeleton | any | "single" | Workbook source template to instantiate | -| reuse | any | True | Whether to search for reusable knowledge before new work | -| optimize | any | False | Whether to run the documented improvement path | -| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | -| soft_match | any | False | Whether bounded soft matching is enabled | -| near_match | any | True | Whether to consider near-match candidates | -| near_threshold | any | 0.78 | Minimum similarity score for near-match candidates | -| promote | any | True | Whether successful evidence may be promoted | -| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | -| improve_every | any | 3 | Number of observations between improvement attempts | -| explore_n | any | 3 | Maximum configured exploration attempts | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| trace | any | False | Whether to retain the documented execution trace | -| resume_id | any | None | Identifier of the stored continuation checkpoint | -| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | -| eng_preflight | any | False | Whether to run engineering reuse preflight | -| marqdo_dir | any | ".marqdo" | Marqdo project directory used for engineering discovery | -| allow_create_after | any | 2 | Number of bounded attempts before new work may be proposed | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Multi-step with OKF agent-kb. Default workbook is `kb_dir/resources/.mq.md`. While task file count `< explore_n` and skill is not llm_free, force a new explore variant under `kb_dir/explore//`. Code-first: llm_free hits skip parent LLM. File children return via `# main`; `plan` exposes that as `result`. Engineering Knowledge preflight when `eng_preflight=True`: REUSE/ADAPT preferred; CREATE only if `create_allowed`. Production agents should enable this; tests that only exercise agent-kb may leave it false. Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` when `near_match=True` and score ≥ `near_threshold`. Non-hit path: optional `soft_match=True` parent REUSE/NEW over ranked `agent_kb_near_match` candidates; else decompose before first child spawn (`DECISION: RUN` / `CONTINUE`+patch / solidified `DONE`). Then `await` → revise loop. Process events (`decision` / `round` / `done` / tools) are always attached on the result map for audit and view process cards; `stream=True` additionally SSE-publishes them (and parent `delta`). `echo=True` prints `plan:decompose` / `plan:await` / deltas. `trace=True` writes events to writeback slot `trace`. Quiet child subtasks stay quiet. | - -Use `goal`, `workbook_dir`=None, `workbook`=None, `max_rounds`=4, `confirm`=False, `writeback`=True, `skeleton`="single", `reuse`=True, `optimize`=False, `force`=False, `soft_match`=False, `near_match`=True, `near_threshold`=0.78, `promote`=True, `kb_dir`=".marqdo/agent-kb", `improve_every`=3, `explore_n`=3, `stream`=False, `echo`=False, `trace`=False, `resume_id`=None, `resume_dir`=".marqdo/agent-resume", `eng_preflight`=False, `marqdo_dir`=".marqdo", `allow_create_after`=2 as the inputs for this operation. - -Multi-step with OKF agent-kb. Default workbook is `kb_dir/resources/.mq.md`. While task file count `< explore_n` and skill is not llm_free, force a new explore variant under `kb_dir/explore//`. Code-first: llm_free hits skip parent LLM. File children return via `# main`; `plan` exposes that as `result`. - -Engineering Knowledge preflight when `eng_preflight=True`: REUSE/ADAPT preferred; CREATE only if `create_allowed`. Production agents should enable this; tests that only exercise agent-kb may leave it false. - -Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` when `near_match=True` and score ≥ `near_threshold`. Non-hit path: optional `soft_match=True` parent REUSE/NEW over ranked `agent_kb_near_match` candidates; else decompose before first child spawn (`DECISION: RUN` / `CONTINUE`+patch / solidified `DONE`). Then `await` → revise loop. Process events (`decision` / `round` / `done` / tools) are always attached on the result map for audit and view process cards; `stream=True` additionally SSE-publishes them (and parent `delta`). `echo=True` prints `plan:decompose` / `plan:await` / deltas. `trace=True` writes events to writeback slot `trace`. Quiet child subtasks stay quiet. - -This method coordinates a workbook lifecycle. The workbook is an ordinary executable document with a main entry, not a private planner data format. The parent proposes decisions and short repairs; the runtime writes or awaits source, captures an observation and returns the child's actual value. Choose this method when reuse and a bounded revise loop are appropriate. Choose step for a single model turn with an optional tool. - -The first gate can consult engineering knowledge. REUSE and ADAPT are recorded as such; creating new work requires the configured create decision. A missing knowledge store is a separate state from an explicit denial. This gate does not manufacture a candidate merely to satisfy a minimum count. Callers should retain its diagnostics when deciding whether their project has enough reusable context. - -Knowledge lookup then establishes the resource and cache state. Exact, alias and canonical matches are tried before optional near matches. A similarity threshold filters candidates but does not prove semantic equivalence. An llm_free resource can execute through the existing code path without a parent model. The returned cache, match and resource fields let the application explain which path was chosen and inspect the source that ran. - -Exploration uses owned workbook files. With no explicit workbook path, the configured knowledge directory supplies the resource location; bounded variants live under its exploration subtree. The exploration count controls attempts to establish useful reusable evidence. It should not be confused with the maximum revision rounds of one workbook. Keep both directory ownership and attempt accounting intact when changing the planner. - -An optional soft-match turn compares existing candidates and produces either REUSE with a concrete slug or NEW. The reply is parsed and resolved before execution. It cannot authorize an invented slug or silently replace a failed child with model prose. When reuse does not yield a result, the chosen single-worker or dual-worker template provides a starting document, with the goal embedded as quoted data. - -Before the first child execution, decomposition asks whether that starting document is sufficient. RUN accepts the structure. CONTINUE supplies a bounded source patch, and evidence requests go through the restricted parent tool dispatcher. DONE belongs to the existing solidification path and must have a usable value. Rewriting already valid imports is not itself progress toward the user's goal. - -Child execution is awaited before revision. The observation contains process status, returned value, slots and bounded output; the parent prompt uses a compact projection so large logs do not drown out the next repair. If the child fails or its value is unsuitable, a short patch can be applied and another round attempted. Exhausting the round budget is reported by the result path, rather than hidden behind a fabricated successful answer. - -The confirm option concerns the decomposition stage; it is not a substitute for host permissions. File creation, source patches, subprocess execution and model transport retain their own effect boundaries. Quiet subtasks remain quiet. Turning on echo changes incremental terminal output, while stream publishes process events. Neither option changes the requirement to inspect the final structured result. - -Events are retained for audit even when streaming is disabled. Decisions, rounds and completion events describe the work that actually ran. Trace writeback is separately controlled, and normal writeback stores the result at its source call site. Consumers should use these fields to diagnose a plan instead of scraping console messages or assuming every emitted event represents a completed child. - -Successful outcomes may be promoted through the knowledge mechanism when enabled. Promotion preserves the workbook as inspectable source and uses the configured evidence process; generating a file alone is not compilation into a trusted skill. Optimization and force options select existing improvement behavior, while the regular reuse gates remain visible in the outcome. A later author can open the resulting resource and reproduce its invocation. - -With a resume identifier, checkpoint records connect the goal, round, workbook and result to a logical run. The checkpoint is continuation data, not a replay authorization for uncertain external writes. Tools with effects still use their own ledger and reconciliation rules. Preserve these references when integrating a scheduler or another application so continuation does not duplicate work that already committed. - -We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. -We retain **cache = "miss"**. -We retain **path = None**. -We retain **improve = None**. -We retain **explore = None**. -We retain **explore_attempt = None**. -We retain **skel_kind = skeleton**. -We retain **`events` = [Empty list](table.empty_list())**. -We retain **eng = None**. - -1. `eng_preflight` - We retain **`eng` = [Eng preflight](agent_eng_preflight(task=`goal`, marqdo_dir=`marqdo_dir`, allow_create_after=`allow_create_after`))**. - We retain **`eng_status` = [Read the status field](json.get(value=`eng`, key="status"))**. - We retain **`eng_decision` = [Read the decision field](json.get(value=`eng`, key="decision"))**. - We retain **`eng_allowed` = [Read the create_allowed field](json.get(value=`eng`, key="create_allowed"))**. - 1. `eng_status` == missing_knowledge - **_ = 1** - 2. `eng_decision` == REUSE - We **[Eng record](agent_eng_record(decision="REUSE", marqdo_dir=`marqdo_dir`))**. - **_ = 1** - 3. `eng_decision` == ADAPT - We **[Eng record](agent_eng_record(decision="ADAPT", marqdo_dir=`marqdo_dir`))**. - **_ = 1** - 4. `eng_allowed` - We **[Eng record](agent_eng_record(decision="CREATE", marqdo_dir=`marqdo_dir`))**. - **_ = 1** - 5. * - - `out` = - - | status | cache | eng | decision | preflight | events | - |--------|-------|-----|----------|-----------|--------| - | blocked | eng-block | true | BLOCKED | `eng` | `events` | - - Return *out*. -2. * - **_ = 1** - -We retain **`tf` = [Kb task files](agent_kb_task_files(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`))**. -We retain **`nfiles` = [Read the count field](json.get(value=`tf`, key="count"))**. - -1. `force` - **_ = 1** -2. `optimize` - **_ = 1** -3. `reuse` - We retain **`hit` = [Kb lookup](agent_kb_lookup(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, near_match=`near_match`, near_threshold=`near_threshold`))**. - 1. `hit` - We retain **`match_kind` = [Read the match field](json.get(value=`hit`, key="match"))**. - 1. `match_kind` == alias - We retain **cache_label = "soft-hit"**. - 2. `match_kind` == canonical - We retain **cache_label = "soft-hit"**. - We retain **`hit_slug` = [Read the slug field](json.get(value=`hit`, key="slug"))**. - We **[Kb add alias](agent_kb_add_alias(kb_dir=`kb_dir`, slug=`hit_slug`, alias=`goal`))**. - 3. `match_kind` == near - We retain **cache_label = "soft-hit"**. - We retain **`hit_slug` = [Read the slug field](json.get(value=`hit`, key="slug"))**. - We **[Kb add alias](agent_kb_add_alias(kb_dir=`kb_dir`, slug=`hit_slug`, alias=`goal`))**. - 4. `match_kind` == soft - We retain **cache_label = "soft-hit"**. - 5. * - We retain **cache_label = "hit"**. - We retain **`lf` = [Read the llm_free field](json.get(value=`hit`, key="llm_free"))**. - 1. `lf` - We retain **`path` = [Read the resource field](json.get(value=`hit`, key="resource"))**. - We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - 1. `code` == 0 - We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, improve_every=`improve_every`))**. - We retain **cache = cache_label**. - We retain **`hit_score` = [Read the score field](json.get(value=`hit`, key="score"))**. - We retain **`sk` = [Read the skill field](json.get(value=`hit`, key="skill"))**. - We retain **`st` = [Read the status field](json.get(value=`hit`, key="status"))**. - The following record names each literal field without a JSON construction chain. - - `_literal_sum_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "OKF llm_free skill hit (" | - | 2 | "b" | "); spawned resource" | - - We build **sum = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_sum_fields`))**. - - - We retain **`suma` = [Read the a field](json.get(value=`sum`, key="a"))**. - We retain **`sumb` = [Read the b field](json.get(value=`sum`, key="b"))**. - We retain **sum = suma + match_kind + sumb**. - - `out` = - - | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result | - |--------|------|----------|--------|-------|-------|-------|--------------|---------|-------------|--------| - | ok | `goal` | `path` | 1 | `cache_label` | `match_kind` | `sk` | `st` | `sum` | `last_obs` | `child_val` | - - 1. `hit_score` - We retain **`out` = [Set the score field in the new record](table.put(in=`out`, at="score", value=`hit_score`))**. - 2. * - **_ = 1** - We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision="REUSE", stream=`stream`, summary=`sum`))**. - We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. - 1. `writeback` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. - We **[Record](wb.record(value=`body`, key="ok"))**. - 2. * - **_ = 1** - We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`child_val`))**. - Return *out*. - 2. * - We retain **path = None**. - 2. `nfiles` < `explore_n` - We retain **explore = 1**. - We retain **cache = "explore"**. - We retain **path = None**. - We retain **explore_attempt = nfiles + 1**. - 1. `explore_attempt` == 2 - We retain **skel_kind = "dual"**. - 2. * - We retain **skel_kind = skeleton**. - 3. * - We retain **`path` = [Read the resource field](json.get(value=`hit`, key="resource"))**. - We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - 1. `code` == 0 - We retain **`rec` = [Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, improve_every=`improve_every`))**. - We retain **`due` = [Read the improve_due field](json.get(value=`rec`, key="improve_due"))**. - 1. `due` - We retain **improve = 1**. - We retain **cache = "improve"**. - 2. * - We retain **cache = cache_label**. - We retain **`hit_score` = [Read the score field](json.get(value=`hit`, key="score"))**. - We retain **`sk` = [Read the skill field](json.get(value=`hit`, key="skill"))**. - We retain **`st` = [Read the status field](json.get(value=`hit`, key="status"))**. - The following record names each literal field without a JSON construction chain. - - `_literal_sum_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "OKF skill hit (" | - | 2 | "b" | "); spawned resource" | - - We build **sum = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_sum_fields`))**. - - - We retain **`suma` = [Read the a field](json.get(value=`sum`, key="a"))**. - We retain **`sumb` = [Read the b field](json.get(value=`sum`, key="b"))**. - We retain **sum = suma + match_kind + sumb**. - - `out` = - - | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result | - |--------|------|----------|--------|-------|-------|-------|--------------|---------|-------------|--------| - | ok | `goal` | `path` | 1 | `cache_label` | `match_kind` | `sk` | `st` | `sum` | `last_obs` | `child_val` | - - 1. `hit_score` - We retain **`out` = [Set the score field in the new record](table.put(in=`out`, at="score", value=`hit_score`))**. - 2. * - **_ = 1** - We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision="REUSE", stream=`stream`, summary=`sum`))**. - We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. - 1. `writeback` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. - We **[Record](wb.record(value=`body`, key="ok"))**. - 2. * - **_ = 1** - We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`child_val`))**. - Return *out*. - 2. * - We retain **path = None**. - 2. * - 1. `soft_match` - We retain **`near` = [Kb near match](agent_kb_near_match(kb_dir=`kb_dir`, goal=`goal`))**. - We retain **`tasks` = [Read the candidates field](json.get(value=`near`, key="candidates"))**. - We retain **`tn` = [Len](len(value=`tasks`))**. - 1. `tn` < 1 - We retain **`listed` = [Kb list tasks](agent_kb_list_tasks(kb_dir=`kb_dir`))**. - We retain **`tasks` = [Read the tasks field](json.get(value=`listed`, key="tasks"))**. - We retain **`tn` = [Len](len(value=`tasks`))**. - 2. * - **_ = 1** - 1. `tn` > 0 - We retain **`soft_prompt` = [Build soft match prompt](build_soft_match_prompt(goal=`goal`, tasks=`tasks`))**. - We retain **`model` = [Read the model field](json.get(value=`self`, key="model"))**. - 1. `stream` - We retain **`evs` = [Stream](model.stream(prompt=`soft_prompt`, echo=`echo`))**. - We retain **`soft_reply` = [Collect](llm.collect(events=`evs`))**. - We retain **`events` = [Plan merge deltas](plan_merge_deltas(events=`events`, from=`evs`, stream=`stream`))**. - 2. * - We retain **`soft_turn` = [Model turn](model_turn(model=`model`, prompt=`soft_prompt`, stream=False, echo=`echo`))**. - We retain **`soft_reply` = [Read the text field](json.get(value=`soft_turn`, key="text"))**. - We retain **`soft_reply` = [Trim](trim(value=`soft_reply`))**. - We retain **`soft_dec` = [Extract plan decision](extract_plan_decision(reply=`soft_reply`))**. - We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision=`soft_dec`, stream=`stream`))**. - 1. `soft_dec` == REUSE - We retain **`reuse_slug` = [Extract soft match slug](extract_soft_match_slug(reply=`soft_reply`))**. - 1. `reuse_slug` - We retain **`hit` = [Kb lookup](agent_kb_lookup(kb_dir=`kb_dir`, slug=`reuse_slug`, goal=`goal`, tools=`tools`))**. - 1. `hit` - We **[Kb add alias](agent_kb_add_alias(kb_dir=`kb_dir`, slug=`reuse_slug`, alias=`goal`))**. - We retain **cache_label = "soft-hit"**. - We retain **`path` = [Read the resource field](json.get(value=`hit`, key="resource"))**. - We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - 1. `code` == 0 - We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, improve_every=`improve_every`))**. - We retain **cache = "soft-hit"**. - We retain **`sk` = [Read the skill field](json.get(value=`hit`, key="skill"))**. - We retain **`st` = [Read the status field](json.get(value=`hit`, key="status"))**. - We retain **sum = "OKF soft_match REUSE; spawned resource"**. - - `out` = - - | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result | - |--------|------|----------|--------|-------|-------|-------|--------------|---------|-------------|--------| - | ok | `goal` | `path` | 1 | soft-hit | soft | `sk` | `st` | `sum` | `last_obs` | `child_val` | - We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision="REUSE", stream=`stream`, summary=`sum`))**. - We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. - 1. `writeback` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. - We **[Record](wb.record(value=`body`, key="ok"))**. - 2. * - **_ = 1** - We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`child_val`))**. - Return *out*. - 2. * - We retain **path = None**. - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 1. `nfiles` < `explore_n` - We retain **explore = 1**. - We retain **cache = "explore"**. - We retain **explore_attempt = nfiles + 1**. - 1. `explore_attempt` == 2 - We retain **skel_kind = "dual"**. - 2. * - We retain **skel_kind = skeleton**. - 2. * - **_ = 1** -4. * - 1. `nfiles` < `explore_n` - We retain **explore = 1**. - We retain **cache = "explore"**. - We retain **explore_attempt = nfiles + 1**. - 2. * - **_ = 1** - -We retain **`skel` = [Render workbook skeleton](render_workbook_skeleton(goal=`goal`, skeleton=`skel_kind`))**. - -1. `workbook` - We retain **path = workbook**. - We retain **`ex` = [Exists](fs.exists(path=`path`))**. - 1. `ex` - **_ = 1** - 2. * - We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. -2. * - 1. `path` - **_ = 1** - 2. * - We retain **`slug` = [Goal slug](agent_goal_slug(goal=`goal`))**. - 1. `workbook_dir` - We **[Make dir](fs.make_dir(path=`workbook_dir`))**. - We retain **`ts` = [Now ms](time.now_ms())**. - The following record names each literal field without a JSON construction chain. - - `_literal_parts_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "/workbook-" | - | 2 | "b" | "-" | - | 3 | "c" | ".mq.md" | - - We build **parts = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_parts_fields`))**. - - - We retain **`a` = [Read the a field](json.get(value=`parts`, key="a"))**. - We retain **`b` = [Read the b field](json.get(value=`parts`, key="b"))**. - We retain **`c` = [Read the c field](json.get(value=`parts`, key="c"))**. - We retain **path = workbook_dir + a + slug + b + ts + c**. - We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. - 2. `explore` - The following record names each literal field without a JSON construction chain. - - `_literal_parts_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "/explore/" | - | 2 | "b" | "/" | - | 3 | "c" | ".mq.md" | - - We build **parts = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_parts_fields`))**. - - - We retain **`a` = [Read the a field](json.get(value=`parts`, key="a"))**. - We retain **`b` = [Read the b field](json.get(value=`parts`, key="b"))**. - We retain **`c` = [Read the c field](json.get(value=`parts`, key="c"))**. - We retain **path = kb_dir + a + slug + b + explore_attempt + c**. - We retain **`ex` = [Exists](fs.exists(path=`path`))**. - 1. `ex` - **_ = 1** - 2. * - We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. - 3. * - The following record names each literal field without a JSON construction chain. - - `_literal_parts_fields` = - - | @ | key | value | - |---|---|---| - | 1 | "a" | "/resources/" | - | 2 | "b" | ".mq.md" | - - We build **parts = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_parts_fields`))**. - - - We retain **`a` = [Read the a field](json.get(value=`parts`, key="a"))**. - We retain **`b` = [Read the b field](json.get(value=`parts`, key="b"))**. - We retain **path = kb_dir + a + slug + b**. - We retain **`ex` = [Exists](fs.exists(path=`path`))**. - 1. `ex` - **_ = 1** - 2. * - We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. - -1. `confirm` - - `out` = - - | status | goal | workbook | summary | cache | - |--------|------|----------|---------|-------| - | pending | `goal` | `path` | workbook created; confirm to run | bypass | - 1. `writeback` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. - We **[Record](wb.record(value=`body`, key="ok"))**. - 2. * - **_ = 1** - We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`))**. - Return *out*. -2. * - **_ = 1** - -We retain **`model` = [Read the model field](json.get(value=`self`, key="model"))**. -We retain **round = 0**. -We retain **last_obs = None**. -We retain **last_reply = None**. -We retain **child_val = None**. -We retain **done = None**. -We retain **summary = None**. -We retain **status = "error"**. -We retain **err = "max_rounds exhausted"**. -We retain **skip_loop = None**. -We retain **plan_llm_calls = 0**. -We retain **plan_tokens = 0**. - -We **[Plan echo decompose](plan_echo_decompose(workbook=`path`, stream=`stream`, echo=`echo`))**. -We retain **`last_obs` = [Inspect workbook](inspect_workbook(path=`path`))**. -We retain **`turn` = [Plan llm act loop](plan_llm_act_loop(agent=`self`, goal=`goal`, path=`path`, observation=`last_obs`, phase="decompose", explore_attempt=`explore_attempt`, explore_n=`explore_n`, stream=`stream`, echo=`echo`, events=`events`))**. -We retain **`turn_s` = [Encode the structured value as JSON text](json.stringify(value=`turn`))**. -We retain **`turn_map` = [Starts with](text.starts_with(text=`turn_s`, prefix="{"))**. -We retain **dec = None**. -We retain **last_reply = None**. -1. `turn_map` - We retain **`dec` = [Read the decision field](json.get(value=`turn`, key="decision"))**. - We retain **`last_reply` = [Read the reply field](json.get(value=`turn`, key="reply"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`turn`, key="observation"))**. - We retain **`events` = [Read the events field](json.get(value=`turn`, key="events"))**. - We retain **`_c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. - We retain **`_t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. - 1. `_c` != None - We retain **plan_llm_calls = plan_llm_calls + _c**. - 1. `_t` != None - We retain **plan_tokens = plan_tokens + _t**. -2. * - We retain **dec = "TRANSPORT_ERROR"**. - We retain **last_reply = "plan_llm_act_loop_not_map"**. - We retain **err = `last_reply`**. - -1. `dec` == "TRANSPORT_ERROR" - We retain **done = 1**. - We retain **status = "error"**. - We retain **err = `last_reply`**. - 1. `turn_map` - We retain **`e2` = [Read the error field](json.get(value=`turn`, key="error"))**. - 1. `e2` - We retain **err = `e2`**. - We retain **summary = "llm transport error"**. - We retain **skip_loop = 1**. -2. `dec` == CONTINUE - We retain **`n` = [Apply patch blocks](fs.apply_patch_blocks(path=`path`, text=`last_reply`, soft=True))**. - 1. `n` - **_ = 1** - 2. * - We retain **done = 1**. - We retain **status = "error"**. - We retain **err = "no patches applied"**. - We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. - We retain **skip_loop = 1**. -3. `dec` == RUN - **_ = 1** -4. `dec` == DONE - We retain **`has_step` = [Workbook has worker step](workbook_has_worker_step(path=`path`))**. - 1. `has_step` - **_ = 1** - 2. * - We **[Plan echo await](plan_echo_await(round=1, workbook=`path`, stream=`stream`, echo=`echo`))**. - We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - We retain **round = 1**. - We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. - 1. `code` == 0 - We retain **done = 1**. - We retain **status = "ok"**. - We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. - We retain **err = None**. - We retain **skip_loop = 1**. - 2. * - **_ = 1** -5. * - Free-form parent reply with no DECISION/CALL/READ (dec=unknown): accept as DONE - when there is prose — chat soft-recover depends on result/summary surviving. - 1. `dec` == "unknown" - 1. `last_reply` - We retain **done = 1**. - We retain **status = "ok"**. - We retain **err = None**. - We retain **summary = `last_reply`**. - We retain **skip_loop = 1**. - 2. * - We retain **done = 1**. - We retain **status = "error"**. - We retain **err = "unrecognized plan decision"**. - We retain **summary = last_reply**. - We retain **skip_loop = 1**. - 2. * - We retain **done = 1**. - We retain **status = "error"**. - We retain **err = "unrecognized plan decision"**. - We retain **summary = last_reply**. - We retain **skip_loop = 1**. - -1. `skip_loop` - We retain **left = 0**. -2. `improve` - We retain **left = 1**. -3. * - We retain **left = max_rounds**. - -- `left` > 0 - 1. `done` - We retain **left = 0**. - 2. * - We retain **round = round + 1**. - We **[Plan echo await](plan_echo_await(round=`round`, workbook=`path`, stream=`stream`, echo=`echo`))**. - We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. - We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. - We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. - We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=`round`, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. - -Deterministic success stop (loop engineering): when the child already returned a value, do not ask the parent LLM to invent solidify patches — DONE + runtime solidify. - - 1. `code` == 0 - 1. `child_val` - 1. `improve` - We retain **auto_done = None**. - 2. * - We retain **auto_done = 1**. - 2. * - We retain **auto_done = None**. - 2. * - We retain **auto_done = None**. - - 1. `auto_done` - We **[Workbook solidify](agent_workbook_solidify(path=`path`, observation=`last_obs`))**. - We retain **done = 1**. - We retain **status = "ok"**. - We retain **summary = "child returned value; solidified"**. - We retain **err = None**. - We retain **dec = "DONE"**. - We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision=`dec`, stream=`stream`, summary=`summary`))**. - We retain **left = 0**. - 2. * - We retain **`turn` = [Plan llm act loop](plan_llm_act_loop(agent=`self`, goal=`goal`, path=`path`, observation=`last_obs`, phase="revise", explore_attempt=`explore_attempt`, explore_n=`explore_n`, stream=`stream`, echo=`echo`, events=`events`))**. - We retain **`dec` = [Read the decision field](json.get(value=`turn`, key="decision"))**. - We retain **`last_reply` = [Read the reply field](json.get(value=`turn`, key="reply"))**. - We retain **`last_obs` = [Read the observation field](json.get(value=`turn`, key="observation"))**. - We retain **`events` = [Read the events field](json.get(value=`turn`, key="events"))**. - We retain **`_c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. - We retain **`_t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. - 1. `_c` != None - We retain **plan_llm_calls = plan_llm_calls + _c**. - 1. `_t` != None - We retain **plan_tokens = plan_tokens + _t**. - 1. `dec` == DONE - We **[Workbook solidify](agent_workbook_solidify(path=`path`, observation=`last_obs`))**. - We retain **done = 1**. - We retain **status = "ok"**. - We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. - We retain **err = None**. - We retain **left = 0**. - 2. `dec` == CONTINUE - We retain **`n` = [Apply patch blocks](fs.apply_patch_blocks(path=`path`, text=`last_reply`, soft=True))**. - 1. `n` - We retain **left = left - 1**. - 2. * - We retain **done = 1**. - We retain **status = "error"**. - We retain **err = "no patches applied"**. - We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. - We retain **left = 0**. - 3. `dec` == RUN - We retain **left = left - 1**. - 4. * - 1. `dec` == "unknown" - 1. `last_reply` - We retain **done = 1**. - We retain **status = "ok"**. - We retain **err = None**. - We retain **summary = `last_reply`**. - We retain **left = 0**. - 2. * - We retain **done = 1**. - We retain **status = "error"**. - We retain **err = "unrecognized plan decision"**. - We retain **summary = last_reply**. - We retain **left = 0**. - 2. * - We retain **done = 1**. - We retain **status = "error"**. - We retain **err = "unrecognized plan decision"**. - We retain **summary = last_reply**. - We retain **left = 0**. - -1. `status` == "ok" - 1. `promote` - We retain **`prom` = [Kb promote](agent_kb_promote(kb_dir=`kb_dir`, goal=`goal`, workbook=`path`, tools=`tools`))**. - We retain **cache = "refreshed"**. - 2. * - We retain **cache = "miss"**. -2. * - **_ = 1** - -`out` = - -| status | goal | workbook | rounds | cache | llm_calls | tokens | -|--------|------|----------|--------|-------|-----------|--------| -| `status` | `goal` | `path` | `round` | `cache` | `plan_llm_calls` | `plan_tokens` | - -1. `summary` - We retain **`out` = [Set the summary field in the new record](table.put(in=`out`, at="summary", value=`summary`))**. -2. * - **_ = 1** - -1. `err` - We retain **`out` = [Set the error field in the new record](table.put(in=`out`, at="error", value=`err`))**. -2. * - **_ = 1** - -1. `last_obs` - We retain **`out` = [Set the observation field in the new record](table.put(in=`out`, at="observation", value=`last_obs`))**. -2. * - **_ = 1** - -1. `child_val` - We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`child_val`))**. - We retain **plan_result = child_val**. -2. `summary` - We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`summary`))**. - We retain **plan_result = summary**. -3. * - We retain **plan_result = None**. - -1. `writeback` - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. - 1. `status` == "ok" - We **[Record](wb.record(value=`body`, key="ok"))**. - 2. * - We **[Record](wb.record(value=`body`, key="error"))**. -2. * - **_ = 1** - -We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`plan_result`))**. -Return *out*. - ---- - -# mcp_server - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | "marqdo" | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Minimal MCP Server host (stdio JSON-RPC / Streamable HTTP). Tools point at entry-module `lib.member` functions (same bridge as `ext/web` invoke). Evidence/results may carry `authority=workbook`. | - -Use `name`="marqdo" as the inputs for this operation. - -Minimal MCP Server host (stdio JSON-RPC / Streamable HTTP). Tools point at entry-module `lib.member` functions (same bridge as `ext/web` invoke). Evidence/results may carry `authority=workbook`. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -We retain **`tools0` = [Empty list](table.empty_list())**. - -`h` = - -| _type | tools | name | -|-------|-------|------| -| mcp_server | `tools0` | `name` | - -Return *h*. - -## tool - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | required | Name registered or looked up by this operation | -| fn | any | required | Registered function target | -| description | any | "" | Human-readable tool description | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Register one tool. `fn` must be `lib.member` imported on the entry workbook. | - -Use `name`, `fn`, `description`="" as the inputs for this operation. - -Register one tool. `fn` must be `lib.member` imported on the entry workbook. - -We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. -1. not `tools` - We retain **`tools` = [Empty list](table.empty_list())**. - -`row` = - -| name | fn | description | -|------|-----|-------------| -| `name` | `fn` | `description` | - -We retain **`tools` = [Append this item to the new list](table.append(list=`tools`, item=`row`))**. -We retain **`h` = [Set the tools field in the new record](table.put(in=`self`, at="tools", value=`tools`))**. -Return *h*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| transport | any | "stdio" | Connector transport type | -| host | any | "127.0.0.1" | Explicit bind or remote host | -| port | any | 7434 | Explicit server port | -| path | any | "/mcp" | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Block on MCP: `stdio` (line JSON-RPC) or `http` / `streamable-http` (Streamable HTTP, POST JSON-RPC + optional GET SSE). Spec 2025-03-26. | - -Use `transport`="stdio", `host`="127.0.0.1", `port`=7434, `path`="/mcp" as the inputs for this operation. - -Block on MCP: `stdio` (line JSON-RPC) or `http` / `streamable-http` (Streamable HTTP, POST JSON-RPC + optional GET SSE). Spec 2025-03-26. - -We retain **`name` = [Read the name field](json.get(value=`self`, key="name"))**. -We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. -Return *[Mcp serve](agent_mcp_serve(name=`name`, tools=`tools`, transport=`transport`, host=`host`, port=`port`, path=`path`))*. diff --git a/ext/ai/context.mq.md b/ext/ai/context.mq.md deleted file mode 100644 index 375ba07..0000000 --- a/ext/ai/context.mq.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -markup: occlusion -title: AI context — short, explicit source scopes -description: Pack user input and caller-provided file/class/function excerpts. -import: - agent: ext/ai/agent.mq.md - plugin: lib/plugin.mq.md - json: lib/json.mq.md ---- - -Pass only the documentation that the next model decision needs. The supplied -file/class/function snippets are data; they do not execute as Marqdo source. -A future compiler-backed selector can supply these arguments from AST spans. -This helper does not yet infer class/function scopes automatically. - -## pack - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| user | text | required | Latest user input | -| file | text | "" | File-level description excerpt | -| class | text | "" | Current class excerpt | -| function | text | "" | Current function excerpt | -| budget_tokens | number | 2048 | Small-model context budget | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Bounded ContextPackV2 and compaction evidence | - -Use `user`, `file`="", `class`="", `function`="", `budget_tokens`=2048 as the inputs for this operation. - -Keep the latest request and current function first. Low-priority file context -may be dropped under pressure; any important constraint must be in a retained -field, not in a discardable tool transcript. - -`items` = - -| @ | origin | trust | priority | text | retain | -|---|---|---|---|---|---| -| 1 | user | user | 0 | `user` | True | -| 2 | function | unknown | 1 | `function` | True | -| 3 | class | unknown | 2 | `class` | False | -| 4 | file | unknown | 3 | `file` | False | - -Return *[Pack the supplied scopes and compact redundant context](agent.context_pack_compact(items=`items`, budget_tokens=`budget_tokens`, goal=`user`))*. - - -## scope - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| scope | text | "function" | file / class / function / tool | -| class | text | None | Class heading for disambiguation | -| function | text | None | Function/tool heading | -| source | text | None | Source override; otherwise current entry module | -| max_chars | number | 1600 | Maximum Unicode characters | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Exact source excerpt, line range, or explicit ambiguity | - -Use `scope`="function", `class`=None, `function`=None, `source`=None, `max_chars`=1600 as the inputs for this operation. - -The native selector respects Markdown headings and ignores fenced-code heading -lookalikes. Repeated function names require a class; missing/ambiguous scopes -return an error value, never an unrelated or whole-file fallback. - -We retain **p = [Locate native agent plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load native agent plugin](plugin.load(path=`p`))**. -2. * - Return *[No native parser available](json.parse(text="{\"ok\":false,\"status\":\"unavailable\",\"text\":null}"))*. - -Return *[Project the requested document scope](agent_context_scope(source=`source`, scope=`scope`, class=`class`, function=`function`, max_chars=`max_chars`))*. - - -## compose - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| user | text | required | Latest user input | -| class | text | required | Current class name | -| function | text | required | Current function name | -| source | text | None | Override current entry source | -| budget_tokens | number | 2048 | Small-model context budget | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | ContextPackV2 or an explicit failed selector | - -Use `user`, `class`, `function`, `source`=None, `budget_tokens`=2048 as the inputs for this operation. - -Project file, class and function scopes independently. Refuse ambiguous names -rather than silently importing an unrelated class or the entire source. The -latest user input stays in the retained portion of the resulting context pack. - -We retain **f = [Select file preface](scope(scope="file", source=`source`, max_chars=500))**. -We retain **c = [Select current class](scope(scope="class", class=`class`, source=`source`, max_chars=800))**. -We retain **n = [Select current function](scope(scope="function", class=`class`, function=`function`, source=`source`, max_chars=1500))**. -We retain **f_ok = [Check file selection](json.get(value=`f`, key="ok"))**. -We retain **c_ok = [Check class selection](json.get(value=`c`, key="ok"))**. -We retain **n_ok = [Check function selection](json.get(value=`n`, key="ok"))**. -1. not `f_ok` - Return *f*. -2. not `c_ok` - Return *c*. -3. not `n_ok` - Return *n*. -4. * - We retain **ft = [Read file preface](json.get(value=`f`, key="text"))**. - We retain **ct = [Read class explanation](json.get(value=`c`, key="text"))**. - We retain **nt = [Read function explanation](json.get(value=`n`, key="text"))**. - Return *[Compact only the selected scopes](pack(user=`user`, file=`ft`, class=`ct`, function=`nt`, budget_tokens=`budget_tokens`))*. diff --git a/ext/ai/flow.mq.md b/ext/ai/flow.mq.md deleted file mode 100644 index a005f15..0000000 --- a/ext/ai/flow.mq.md +++ /dev/null @@ -1,246 +0,0 @@ ---- -markup: occlusion -title: AI flow — small-model choices and bounded subtasks -description: Short model decisions, verified options and concurrent Marqdo documents. -import: - llm: ext/ai/llm.mq.md - json: lib/json.mq.md - plugin: lib/plugin.mq.md - subtask: lib/subtask.mq.md ---- - -This is the thin author-facing layer. A model returns a candidate; Marqdo checks -it before routing. Invalid choices are not SKILL paths and never execute. -Only the requested function and its inputs need to be in the model prompt. - -## parse_choice - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| reply | text | required | Raw model reply, treated as data | -| options | list | required | Allowed names, not paths or commands | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | {ok,value,status} or {ok:false,error} | - -Use `reply`, `options` as the inputs for this operation. - -Parsing accepts one exact name, a labeled name, a fenced name or a 1-based -index. Ambiguous prose fails closed. Parsing never runs a tool or SKILL. - -We retain **p = [Locate the installed agent plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the agent plugin](plugin.load(path=`p`))**. -2. * - Return *[Missing native parser](json.parse(text="{\"ok\":false,\"status\":\"unavailable\",\"value\":null}"))*. - -Return *[Parse and verify the choice](agent_choice_parse(reply=`reply`, options=`options`))*. - -## choose - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| input | text | required | Current user request or local decision | -| options | list | required | Small list of registered option names | -| model | any | None | Existing provider model identifier | -| repair | bool | True | Allow one format-only repair attempt | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Verified choice result, or explicit failure | - -Use `input`, `options`, `model`=None, `repair`=True as the inputs for this operation. - -Only ask for the option name. A failed first parse can receive one short -format correction; never silently select the nearest-looking option. - -We retain **opts = [Encode allowed values](json.stringify(value=`options`))**. -We retain **prompt = "Choose exactly one of these options. Return its name only, no explanation:\n" + opts + "\nInput:\n" + input**. -We retain **m = [Build one model handle](llm.create(model=`model`))**. -We retain **turn = [Ask the model once](m.ask(prompt=`prompt`))**. -We retain **err = [Check model transport error](json.get(value=`turn`, key="error"))**. -1. `err` - Return *turn*. -2. * - We retain **reply = [Read model answer](json.get(value=`turn`, key="text"))**. - We retain **parsed = [Validate the model reply](parse_choice(reply=`reply`, options=`options`))**. - We retain **ok = [Read validation status](json.get(value=`parsed`, key="ok"))**. - 1. `ok` - Return *parsed*. - 2. `repair` - We retain **fix = "Your answer was not an exact allowed option. Return only ONE option name from:\n" + opts**. - We retain **fixed = [Retry the format only once](m.ask(prompt=`fix`))**. - We retain **repair_error = [Read transport error](json.get(value=`fixed`, key="error"))**. - 1. `repair_error` - Return *fixed*. - 2. * - We retain **again = [Read corrected answer](json.get(value=`fixed`, key="text"))**. - Return *[Validate the repaired reply](parse_choice(reply=`again`, options=`options`))*. - 3. * - Return *parsed*. - -## parallel - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| tasks | list | required | Existing .mq.md file tasks with arguments | -| limit | number | 2 | Maximum simultaneously running tasks | -| timeout_ms | number | 30000 | Execution timeout in milliseconds | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Succeeded, partial, failed or uncertain child outcomes | - -Use `tasks`, `limit`=2, `timeout_ms`=30000 as the inputs for this operation. - -Reuse the built-in subtask scheduler. Each child document returns via its -`# main`, and successful siblings remain visible if another child fails. - -We retain **results = [Run bounded Marqdo document tasks](subtask.run_many(tasks=`tasks`, limit=`limit`, timeout_ms=`timeout_ms`))**. -We retain **p = [Locate native agent plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load native agent plugin](plugin.load(path=`p`))**. - Return *[Preserve success, failure and uncertain child outcomes](agent_parallel_report(results=`results`))*. -2. * - Return *[Native result classifier unavailable](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - - -## input - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable step ID | -| question | text | required | User-visible question | -| options | list | required | User-visible choices | -| source_revision | text | required | Pinned Marqdo source revision | -| session_id | text | None | Host-attested session | -| principal_ref | text | None | Host-attested user scope | -| freeform | bool | True | Allow custom user reply | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | waiting_input or previously committed reply | - -Use `id`, `question`, `options`, `source_revision`, `session_id`=None, `principal_ref`=None, `freeform`=True as the inputs for this operation. - -This does not park an interpreter stack. The caller persists a step-boundary -checkpoint, displays the question, and on a new turn uses reply to continue. -The host, not the LLM, must attest session and principal IDs. - -We retain **p = [Locate native agent plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load native agent plugin](plugin.load(path=`p`))**. -2. * - Return *[No native gate available](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -Return *[Persist one waiting input gate](agent_input_open(id=`id`, question=`question`, options=`options`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, freeform=`freeform`))*. - -## reply - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Existing waiting step | -| reply | text | required | New user response | -| source_revision | text | required | Current pinned source revision | -| session_id | text | None | Host-attested session | -| principal_ref | text | None | Host-attested user scope | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Resolved answer, invalid reply or explicit conflict | - -Use `id`, `reply`, `source_revision`, `session_id`=None, `principal_ref`=None as the inputs for this operation. - -Matching repeated replies are idempotent. A conflicting reply, changed document -or changed session fails without executing any SKILL or side effect. - -We retain **p = [Locate native agent plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load native agent plugin](plugin.load(path=`p`))**. -2. * - Return *[No native gate available](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -Return *[Commit the verified user reply](agent_input_resume(id=`id`, reply=`reply`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`))*. - - -## enter - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| skill | text | required | Model-selected registered name | -| registry | map | required | Trusted name → path mapping | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Subtask result, or blocked unknown skill | - -Use `skill`, `registry` as the inputs for this operation. - -Never execute a raw model-generated path. Resolve a registered skill name to -an author-controlled document, then call its `# main` through the normal Marqdo -subtask and effect permissions. The caller must provide a trusted registry. - -We retain **path = [Resolve registered SKILL](json.get(value=`registry`, key=`skill`))**. -1. not `path` - Return *[Unknown skill is blocked](json.parse(text="{\"ok\":false,\"status\":\"unsupported_skill\"}"))*. -2. * - We retain **task = [Spawn registered Marqdo document](subtask.spawn(path=`path`))**. - Return *[Await the subtask result](subtask.wait(id=`task`))*. - - -## ask - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prompt | text | required | Short local prompt | -| model | any | None | Configured model selection | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Model reply (not yet a verified tool call) | - -Use `prompt`, `model`=None as the inputs for this operation. - -Ask only what the current function needs. The reply remains data until an -explicit verifier accepts it. The LLM adapter owns provider configuration. - -Return *[Ask the configured model](llm.ask(prompt=`prompt`, model=`model`))*. - -## start - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Trusted registered Marqdo document | -| args | list | None | Optional child CLI arguments | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Child task handle | - -Use `path`, `args`=None as the inputs for this operation. - -Start an isolated SKILL document asynchronously, after the calling host has -validated its path and required process.exec permission. No model-generated -raw path is a valid grant. - -Return *[Start one Marqdo document](subtask.spawn(path=`path`, args=`args`))*. - -## wait - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | number | required | Child task handle | -| timeout_ms | number | 30000 | Maximum wait time | -| cancel | bool | False | Cancel on timeout | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Child result, timeout or cancellation | - -Use `id`, `timeout_ms`=30000, `cancel`=False as the inputs for this operation. - -A successful wait protocol is not proof of a successful child execution: -inspect the child exit code before using its result. - -Return *[Wait for the child](subtask.wait_timeout(id=`id`, timeout_ms=`timeout_ms`, cancel=`cancel`))*. diff --git a/ext/ai/index.mq.md b/ext/ai/index.mq.md deleted file mode 100755 index 0015ff9..0000000 --- a/ext/ai/index.mq.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -markup: occlusion -title: AI workflows — model adapters, agents, workbooks and trials -import: - model_api: ext/ai/llm.mq.md ---- - -Start here to choose an AI task. [Model calls](llm.mq.md) own prompts, model configuration, -stream collection and usage; [provider adapters](llm/index.mq.md) describe OpenAI-compatible -and Ollama requests. [Agents](agent.mq.md) own call-site context, the explicit tool registry, -policy routing, observations, workbook planning and continuation. [CoW trials](sandbox.mq.md) -own isolated file changes and promotion. [Native flow](flow.mq.md) provides short, verified model choices and bounded document -concurrency; [workflow](workflow.mq.md) drives a durable forward-only step plan with -`inspect`/`list` progress queries and failed-only read recovery; [context](context.mq.md) -packs explicit source scopes; [recovery](recovery.mq.md) -uses the native error policy and versioned checkpoints. These are lightweight -interfaces, not a second agent runtime. -[Step routing](policies/step-route.mq.md) is readable -policy data, not a second agent language. Chinese users can start at [索引](索引.mq.md). - -Begin with this offline stream example; it does not request credentials, install a plugin or -contact a model. Commands run from the repository root: - -```sh -marqdo call ext/ai/index.mq.md offline_example --json -``` - -For a live model call, configure its provider and credentials before invoking the existing llm -resource. A configured language or adapter does not prove a remote endpoint is available. -Agent operations require the native agent plugin, an explicit model and the permitted tools; -use cargo build -p marqdo_plugin_agent in this checkout. Never let a generated CALL line select -an arbitrary internal function. File, process and network permissions remain bounded by the host. - -Develop one responsibility at a time: provider request shaping belongs under llm/, common model -state in llm.mq.md, planner orchestration in agent.mq.md and trial behavior in sandbox.mq.md. -Keep the agent's call-site and source budgets intact when changing its internal helpers; moving -an operation can affect context and replay. Review effect preparation, transitions and saved -results before adding retries, and do not repeat writes merely to reconstruct a checkpoint. - -Use deterministic stream fixtures and local provider substitutes before live tests. Verify text, -usage, failed tools, lost responses, cancellation, context limits and durable continuation; -model output is data until an authorized tool target and arguments have been resolved. - -## collect_events - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | list | required | Ordered semantic or supported provider stream-event records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Final text assembled by the public stream collector | - -The supplied `events` are an already-observed stream, not instructions to request a new model -response or execute a tool. The shared collector understands delta/text, done.result and its -existing provider-frame conventions. We return *[Collect the existing stream into final text](model_api.collect(events=`events`))* -so offline processing and live transport use the same public assembly behavior. - -## offline_example - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Hello world, assembled from actual semantic events without a model request | - -The event table is a deterministic stream fixture. A delta introduces partial text, then the -final done result supplies the completed answer. Passing these through the public collector -verifies useful behavior; this tool does not manufacture a passed flag or a fake model answer. - -`events` = - -| @ | type | text | result | -|---|---|---|---| -| 1 | delta | "Hello " | None | -| 2 | done | None | "Hello world" | - -We return *[Assemble the final text from the displayed stream](collect_events(events=`events`))*. -A real transport failure still needs its domain error handling; this fixture only demonstrates -stream assembly, and it deliberately performs no network operation. diff --git a/ext/ai/llm.mq.md b/ext/ai/llm.mq.md deleted file mode 100755 index cb99275..0000000 --- a/ext/ai/llm.mq.md +++ /dev/null @@ -1,646 +0,0 @@ ---- -markup: occlusion -title: ext/ai/llm -description: >- - Marqdo LLM intelligence primitive — ask / stream / collect / named handles. - OpenAI-compatible and Ollama HTTP stay behind the semantic surface. -import: - sys: lib/sys.mq.md - json: lib/json.mq.md - table: lib/table.mq.md - fs: lib/fs.mq.md - text: lib/text.mq.md - openai: ext/ai/llm/openai.mq.md ---- - -Choose the public model resource here for ask, stream and collected response behavior. [The AI entry](index.mq.md) provides an offline event workflow; [the adapter entry](llm/index.mq.md) owns provider configuration and transport shapes. Agents and workbook orchestration belong in agent.mq.md. A created handle is configuration, not proof that authentication or a model request succeeded. Keep transport errors, semantic events and usage counters visible when extending this file. - -## load_env - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load `.env` from cwd (optional `path=`). Does not override existing variables. | - -Use `path`=None as the inputs for this operation. - -Load `.env` from cwd (optional `path=`). Does not override existing variables. - -Return *[Load dotenv](sys.load_dotenv(path=`path`))*. - -## collect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | any | required | Ordered semantic or provider stream-event records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Collapse a stream event list to final answer text. Accepts semantic events (`delta` / `text` / `done.result` / `error.message`) and native-plugin raw SSE frames (`type=data` with OpenAI chunk JSON in `data`). Alias: `stream_result`. | - -Use `events` as the inputs for this operation. - -Collapse a stream event list to final answer text. -Accepts semantic events (`delta` / `text` / `done.result` / `error.message`) and -native-plugin raw SSE frames (`type=data` with OpenAI chunk JSON in `data`). -Alias: `stream_result`. - -We retain **answer = ""**. - -- [ev](遍历 events 为 ev) - We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**. - 1. `t` == "done" - We retain **`done_r` = [Read the result field](json.get(value=`ev`, key="result"))**. - 1. `done_r` - We retain **answer = `done_r`**. - 2. * - **_ = 1** - 2. `t` == "error" - We retain **`em` = [Read the message field](json.get(value=`ev`, key="message"))**. - 1. `em` - We retain **answer = `em`**. - 2. * - **_ = 1** - 3. `t` == "delta" - 4. `t` == "text" - We retain **`chunk` = [Read the text field](json.get(value=`ev`, key="text"))**. - 1. `chunk` - We retain **answer = answer + chunk**. - 2. * - **_ = 1** - 5. `t` == "data" - We retain **`raw` = [Read the data field](json.get(value=`ev`, key="data"))**. - 1. `raw` - 1. `raw` == "[DONE]" - **_ = 1** - 2. * - We retain **`parsed` = [Parse the JSON transport text](json.parse(text=`raw`))**. - 1. `parsed` - We retain **`choices` = [Read the choices field](json.get(value=`parsed`, key="choices"))**. - 1. `choices` - We retain **`c0` = [Read 1 field](access(`choices`, "1"))**. - We retain **`delta` = [Read the delta field](json.get(value=`c0`, key="delta"))**. - 1. `delta` - We retain **`piece` = [Read the content field](json.get(value=`delta`, key="content"))**. - 1. `piece` - We retain **answer = answer + piece**. - 2. * - **_ = 1** - 2. * - We retain **`msg` = [Read the message field](json.get(value=`c0`, key="message"))**. - 1. `msg` - We retain **`piece` = [Read the content field](json.get(value=`msg`, key="content"))**. - 1. `piece` - We retain **answer = answer + piece**. - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 6. * - **_ = 1** - -1. not `answer` - We retain **answer = ""**. -Return *answer*. - -## collect_usage - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | any | required | Ordered semantic or provider stream-event records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Best-effort `total_tokens` from stream frames (requires `stream_options.include_usage`). | - -Use `events` as the inputs for this operation. - -Best-effort `total_tokens` from stream frames (requires `stream_options.include_usage`). - -We retain **tokens = None**. -1. `events` - - [ev](遍历 events 为 ev) - We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**. - We retain **raw = None**. - 1. `t` == "data" - We retain **`raw` = [Read the data field](json.get(value=`ev`, key="data"))**. - 2. * - We retain **`u0` = [Read the usage field](json.get(value=`ev`, key="usage"))**. - 1. `u0` - We retain **`tt0` = [Read the total_tokens field](json.get(value=`u0`, key="total_tokens"))**. - 1. `tt0` != None - We retain **tokens = `tt0`**. - 1. `raw` - 1. not `raw` == "[DONE]" - We retain **`parsed` = [Parse the JSON transport text](json.parse(text=`raw`))**. - 1. `parsed` - We retain **`u` = [Read the usage field](json.get(value=`parsed`, key="usage"))**. - 1. `u` - We retain **`tt` = [Read the total_tokens field](json.get(value=`u`, key="total_tokens"))**. - 1. `tt` != None - We retain **tokens = `tt`**. -Return *tokens*. - -## stream_result - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| events | any | required | Ordered semantic or provider stream-event records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Compatibility alias for `collect`. | - -Use `events` as the inputs for this operation. - -Compatibility alias for `collect`. - -Return *[Collect](collect(events=`events`))*. - -## usage_from - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | any | required | Structured input supplied to this adapter or resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map (or empty zeros). | - -Use `data` as the inputs for this operation. - -Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map (or empty zeros). - -Return *[Usage from](openai.usage_from(data=`data`))*. - -## create - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | None | Model resource or provider model identifier, as required by this operation | -| base_url | any | None | Provider API base URL | -| api_key | any | None | Provider credential from trusted runtime configuration | -| backend | any | "openai-compatible" | Configured execution or provider backend | -| name | any | None | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Factory for an LLM handle (same as constructing `# llm`). Env fallbacks apply inside the constructor. Optional `name=` tags the handle (`fast` / `reasoning`). | - -Use `model`=None, `base_url`=None, `api_key`=None, `backend`="openai-compatible", `name`=None as the inputs for this operation. - -Factory for an LLM handle (same as constructing `# llm`). Env fallbacks apply inside the constructor. Optional `name=` tags the handle (`fast` / `reasoning`). - -We retain **`h` = [Llm](llm(model=`model`, base_url=`base_url`, api_key=`api_key`, backend=`backend`, name=`name`))**. -Return *h*. - -## fast - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | None | Model resource or provider model identifier, as required by this operation | -| base_url | any | None | Provider API base URL | -| api_key | any | None | Provider credential from trusted runtime configuration | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Named small/fast handle. Model from arg, else `MARQDO_LLM_FAST_MODEL`, else default create model. | - -Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. - -Named small/fast handle. Model from arg, else `MARQDO_LLM_FAST_MODEL`, else default create model. - -1. `model` - We retain **mdl = `model`**. -2. * - We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_FAST_MODEL"))**. - -Return *[Create](create(model=`mdl`, base_url=`base_url`, api_key=`api_key`, name="fast", backend="openai-compatible"))*. - -## reasoning - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | None | Model resource or provider model identifier, as required by this operation | -| base_url | any | None | Provider API base URL | -| api_key | any | None | Provider credential from trusted runtime configuration | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Named strong/reasoning handle. Model from arg, else `MARQDO_LLM_REASONING_MODEL`, else default create model. | - -Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. - -Named strong/reasoning handle. Model from arg, else `MARQDO_LLM_REASONING_MODEL`, else default create model. - -1. `model` - We retain **mdl = `model`**. -2. * - We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_REASONING_MODEL"))**. - -Return *[Create](create(model=`mdl`, base_url=`base_url`, api_key=`api_key`, name="reasoning", backend="openai-compatible"))*. - -## prompt_body - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| src | any | required | Prompt source or source-reference value | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | If `src` starts with YAML frontmatter declaring `type: prompt` / `类型: 提示`, return the body after the closing `---`; otherwise return `src` unchanged. | - -Use `src` as the inputs for this operation. - -If `src` starts with YAML frontmatter declaring `type: prompt` / `类型: 提示`, return the body after the closing `---`; otherwise return `src` unchanged. - -We retain **`sw` = [Starts with](text.starts_with(text=`src`, prefix="---"))**. -1. not `sw` - Return *src*. -2. * - We retain **`parts` = [Split](split(value=`src`, sep="\n---\n"))**. - We retain **`n` = [Len](len(value=`parts`))**. - 1. `n` < 2 - Return *src*. - 2. * - We retain **`fm` = [At](at(value=`parts`, index=0))**. - We retain **`is_p` = [Contains](text.contains(text=`fm`, sub="type: prompt"))**. - 1. not `is_p` - We retain **`is_p` = [Contains](text.contains(text=`fm`, sub="类型: 提示"))**. - 2. * - **_ = 1** - 1. `is_p` - We retain **`body` = [At](at(value=`parts`, index=1))**. - Return *[Str trim](text.str_trim(s=`body`))*. - 2. * - Return *src*. - -## prompt_load - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load a prompt artifact (`.mq.md` / `.md`) from disk for `ask`. | - -Use `path` as the inputs for this operation. - -Load a prompt artifact (`.mq.md` / `.md`) from disk for `ask`. - -We retain **`raw` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. -Return *[Prompt body](prompt_body(src=`raw`))*. - -## prompt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| text | any | None | Text supplied to the transformation or adapter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Prompt artifact helper: `path=` loads a file; `text=` strips `type: prompt` frontmatter from an in-memory string. | - -Use `path`=None, `text`=None as the inputs for this operation. - -Prompt artifact helper: `path=` loads a file; `text=` strips `type: prompt` frontmatter from an in-memory string. - -1. `path` - Return *[Prompt load](prompt_load(path=`path`))*. -2. `text` - Return *[Prompt body](prompt_body(src=`text`))*. -3. * - We **[Print the prepared message](print(text="ext/ai/llm.prompt: pass", path="or", text=""))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -## ask - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prompt | any | None | Prompt text or structured prompt expected by this adapter | -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| model | any | None | Model resource or provider model identifier, as required by this operation | -| base_url | any | None | Provider API base URL | -| api_key | any | None | Provider credential from trusted runtime configuration | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Module convenience: create a default handle and return **answer text**. Pass `path=` to load a prompt document, `prompt=` text, or omit both to use the entry `.mq.md` as a prompt artifact (`type: prompt` body via `sys.module_source`). | - -Use `prompt`=None, `path`=None, `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. - -Module convenience: create a default handle and return **answer text**. Pass `path=` to load a prompt document, `prompt=` text, or omit both to use the entry `.mq.md` as a prompt artifact (`type: prompt` body via `sys.module_source`). - -We retain **p = `prompt`**. -1. `path` - We retain **`p` = [Prompt load](prompt_load(path=`path`))**. -2. `prompt` - We retain **p = `prompt`**. -3. * - We retain **`raw` = [Module source](sys.module_source())**. - 1. not `raw` - We **[Print the prepared message](print(text="ext/ai/llm.ask: pass", prompt="or", path="(or run a prompt document as entry)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - 2. * - We retain **`p` = [Prompt body](prompt_body(src=`raw`))**. - -We retain **`m` = [Create](create(model=`model`, base_url=`base_url`, api_key=`api_key`))**. -We retain **`r` = [Ask](m.ask(prompt=`p`))**. -We retain **`_ret` = [Read the text field](json.get(value=`r`, key="text"))**. -Return *_ret*. - -# llm - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | None | Model resource or provider model identifier, as required by this operation | -| base_url | any | None | Provider API base URL | -| api_key | any | None | Provider credential from trusted runtime configuration | -| backend | any | "openai-compatible" | Configured execution or provider backend | -| name | any | None | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | LLM handle — intelligence primitive, not an HTTP client. Resolution: explicit args → entry-scope / Artifact Metadata (`sys.meta_get`) → `sys.env_get` → defaults. Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then use the lifted names. | - -Use `model`=None, `base_url`=None, `api_key`=None, `backend`="openai-compatible", `name`=None as the inputs for this operation. - -LLM handle — intelligence primitive, not an HTTP client. - -Resolution: explicit args → entry-scope / Artifact Metadata (`sys.meta_get`) → `sys.env_get` → defaults. -Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then use the lifted names. - -1. `api_key` - We retain **key = `api_key`**. -2. * - We retain **`key` = [Meta get](sys.meta_get(key="api_key"))**. - 1. not `key` - We retain **`key` = [Env get](sys.env_get(name="OPENAI_API_KEY"))**. - 1. not `key` - We retain **`key` = [Env get](sys.env_get(name="MARQDO_LLM_API_KEY"))**. - 2. * - **_ = 1** - 2. * - **_ = 1** - -1. `backend` == ollama - 1. not `key` - We retain **key = "ollama"**. - 2. * - **_ = 1** -2. not `key` - We **[Print the prepared message](print(text="ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY (or pass api_key= / metadata api_key)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -3. * - **_ = 1** - -1. `base_url` - We retain **url = `base_url`**. -2. * - We retain **`url` = [Meta get](sys.meta_get(key="base_url"))**. - 1. `url` - **_ = 1** - 2. `backend` == ollama - We retain **`url` = [Env get](sys.env_get(name="OLLAMA_HOST"))**. - 1. not `url` - We retain **url = "http://127.0.0.1:11434/v1"**. - 2. * - **_ = 1** - 3. * - We retain **`url` = [Env get](sys.env_get(name="OPENAI_BASE_URL"))**. - 1. not `url` - We retain **`url` = [Env get](sys.env_get(name="MARQDO_LLM_BASE_URL"))**. - 2. * - **_ = 1** - 1. not `url` - We retain **url = "https://api.openai.com/v1"**. - 2. * - **_ = 1** - -1. `model` - We retain **mdl = `model`**. -2. * - We retain **`mdl` = [Meta get](sys.meta_get(key="model"))**. - 1. `mdl` - **_ = 1** - 2. * - We retain **`mdl` = [Env get](sys.env_get(name="OPENAI_MODEL"))**. - 1. not `mdl` - We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_MODEL"))**. - 2. * - **_ = 1** - 1. not `mdl` - 1. `backend` == ollama - We retain **mdl = "llama3.2"**. - 2. * - We retain **mdl = "gpt-4o-mini"**. - 2. * - **_ = 1** - -1. `name` - We retain **nm = `name`**. -2. * - We retain **nm = None**. - -`h` = - -| _type | backend | api_key | base_url | model | suffix | bearer | name | -|-------|---------|---------|----------|-------|--------|--------|------| -| llm | `backend` | `key` | `url` | `mdl` | /chat/completions | "Bearer " | `nm` | - -Return *h*. - -## ask - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prompt | any | None | Prompt text or structured prompt expected by this adapter | -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| messages | any | None | Ordered chat message records | -| selection | any | None | Explicit runtime/model selection | -| strict_selection | any | False | Whether an unresolved selection is an error | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `name`, `tool_calls`). Prefer `[text](result)` for the answer string. Omit `prompt=` / `path=` to use the entry document (`sys.module_source` + `prompt_body`). Pass `messages=` for multi-turn history (M01). `selection=` + `strict_selection=True` freeze request identity without env fallback. | - -Use `prompt`=None, `path`=None, `messages`=None, `selection`=None, `strict_selection`=False as the inputs for this operation. - -Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `name`, `tool_calls`). Prefer `[text](result)` for the answer string. Omit `prompt=` / `path=` to use the entry document (`sys.module_source` + `prompt_body`). Pass `messages=` for multi-turn history (M01). `selection=` + `strict_selection=True` freeze request identity without env fallback. - -We retain **p = `prompt`**. -1. `messages` - We retain **p = None**. -2. `path` - We retain **`p` = [Prompt load](prompt_load(path=`path`))**. -3. `prompt` - We retain **p = `prompt`**. -4. * - We retain **`raw` = [Module source](sys.module_source())**. - 1. not `raw` - We retain **p = ""**. - 2. * - We retain **`p` = [Prompt body](prompt_body(src=`raw`))**. -We retain **`pack` = [Complete result](self.complete_result(prompt=`p`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, stream=False, echo=False))**. -We retain **`text` = [Read the text field](json.get(value=`pack`, key="text"))**. -We retain **`usage` = [Read the usage field](json.get(value=`pack`, key="usage"))**. -We retain **`finish` = [Read the finish field](json.get(value=`pack`, key="finish"))**. -We retain **`err` = [Read the error field](json.get(value=`pack`, key="error"))**. -We retain **`tc` = [Read the tool_calls field](json.get(value=`pack`, key="tool_calls"))**. -1. not `tc` - We retain **`tc` = [Empty list](table.empty_list())**. -2. * - **_ = 1** -1. not `text` - We retain **text = ""**. -2. * - **_ = 1** -1. not `finish` - 1. `err` - We retain **finish = "error"**. - 2. * - We retain **finish = "stop"**. -2. * - **_ = 1** - -Hoist receiver fields before the result table — table cells can shadow `self` / -column names (`model`, `usage`), so `[model](self)` / `[total_tokens](usage)` -inside the table is unsafe. - -We retain **`mdl` = [Read the model field](json.get(value=`self`, key="model"))**. -We retain **`b` = [Read the backend field](json.get(value=`self`, key="backend"))**. -We retain **`nm` = [Read the name field](json.get(value=`self`, key="name"))**. -1. `usage` - We retain **`tt` = [Read the total_tokens field](json.get(value=`usage`, key="total_tokens"))**. - We retain **`ustate` = [Read the usage_state field](json.get(value=`usage`, key="usage_state"))**. -2. * - We retain **tt = None**. - We retain **ustate = "unknown"**. -1. `ustate` == "unknown" - Keep null — never coerce missing usage to zero tokens (M02 / F04). - We retain **tt = None**. -2. not `tt` - We retain **tt = None**. -3. * - **_ = 1** -1. `err` - We retain **calls = 0**. -2. * - We retain **calls = 1**. - -`result` = - -| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls | error | selection | -|------|-------|--------|---------|-------|------|-----------|--------|------------|-------|-----------| -| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | `calls` | `tt` | `tc` | `err` | `selection` | - -Return *result*. - -## stream - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prompt | any | None | Prompt text or structured prompt expected by this adapter | -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| echo | any | False | Whether to print the documented incremental output | -| stream_kind | any | "delta" | Streaming event projection selected by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Semantic stream: return the event list (use `llm.collect` to reduce to text). Omit `prompt=` / `path=` to use the entry document. | - -Use `prompt`=None, `path`=None, `echo`=False, `stream_kind`="delta" as the inputs for this operation. - -Semantic stream: return the event list (use `llm.collect` to reduce to text). Omit `prompt=` / `path=` to use the entry document. -`stream_kind=plan` tags EventBus frames for the parent plan protocol (process trail). - -1. `path` - We retain **`p` = [Prompt load](prompt_load(path=`path`))**. -2. `prompt` - We retain **p = `prompt`**. -3. * - We retain **`raw` = [Module source](sys.module_source())**. - 1. not `raw` - We retain **p = ""**. - 2. * - We retain **`p` = [Prompt body](prompt_body(src=`raw`))**. - -Return *[Complete](self.complete(prompt=`p`, stream=True, echo=`echo`, stream_kind=`stream_kind`))*. - -## complete_result - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prompt | any | None | Prompt text or structured prompt expected by this adapter | -| messages | any | None | Ordered chat message records | -| selection | any | None | Explicit runtime/model selection | -| strict_selection | any | False | Whether an unresolved selection is an error | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| stream_kind | any | "delta" | Streaming event projection selected by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Transport pack via `ext/ai/llm/openai` (Ollama uses the same OpenAI-compatible path). Non-stream → `{text,usage,finish}`; stream → `{events}`. Prefer `messages=` for multi-turn; optional `selection=` (ModelSelectionV1) with `strict_selection=True` for request-scoped identity (M01). | - -Use `prompt`=None, `messages`=None, `selection`=None, `strict_selection`=False, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. - -Transport pack via `ext/ai/llm/openai` (Ollama uses the same OpenAI-compatible path). Non-stream → `{text,usage,finish}`; stream → `{events}`. Prefer `messages=` for multi-turn; optional `selection=` (ModelSelectionV1) with `strict_selection=True` for request-scoped identity (M01). - -Return *[Chat completions](openai.chat_completions(base_url=[base_url](access(`self`, "base_url")), api_key=[api_key](access(`self`, "api_key")), model=[model](access(`self`, "model")), prompt=`prompt`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`, suffix=[suffix](access(`self`, "suffix")), bearer=[bearer](access(`self`, "bearer"))))*. - -## complete - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prompt | any | required | Prompt text or structured prompt expected by this adapter | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| stream_kind | any | "delta" | Streaming event projection selected by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Internal / compatibility primitive. Prefer `ask` / `stream` in new code. | - -Use `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. - -Internal / compatibility primitive. Prefer `ask` / `stream` in new code. - -1. `stream` - We retain **`pack` = [Complete result](self.complete_result(prompt=`prompt`, stream=True, echo=`echo`, stream_kind=`stream_kind`))**. - We retain **`_ret` = [Read the events field](json.get(value=`pack`, key="events"))**. - Return *_ret*. -2. * - We retain **`pack` = [Complete result](self.complete_result(prompt=`prompt`, stream=False, echo=`echo`, stream_kind=`stream_kind`))**. - We retain **`_ret` = [Read the text field](json.get(value=`pack`, key="text"))**. - Return *_ret*. - -## chat - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prompt | any | required | Prompt text or structured prompt expected by this adapter | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| stream_kind | any | "delta" | Streaming event projection selected by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Alias for `complete` (compat). | - -Use `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. - -Alias for `complete` (compat). - -Return *[Complete](self.complete(prompt=`prompt`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`))*. diff --git a/ext/ai/llm/index.mq.md b/ext/ai/llm/index.mq.md deleted file mode 100755 index 4431cae..0000000 --- a/ext/ai/llm/index.mq.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -markup: occlusion -title: Provider adapters — requests, configuration and usage -import: - ollama: ext/ai/llm/ollama.mq.md - openai: ext/ai/llm/openai.mq.md ---- - -This directory owns provider adaptation. [OpenAI-compatible requests](openai.mq.md) encode chat -messages, decode replies and usage, and retain streaming/error conventions. [Ollama](ollama.mq.md) -selects its documented local defaults while reusing compatible transport. The parent [model API](../llm.mq.md) -creates author model resources; [the AI root](../index.mq.md) explains agent and trial responsibilities. - -This offline usage example inspects response data only. It does not read credentials, load a -plugin or contact the provider: - -```sh -marqdo call ext/ai/llm/index.mq.md usage 'data={"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}' --json -``` - -For local configuration, resolve_local reads the documented environment fallbacks and therefore -needs environment.read. Sending chat_completions is a real HTTP effect and requires an explicitly -configured endpoint, timeout and credential handling. Do not print a live configuration record -containing secrets merely to prove that an adapter exists. - -When adding a provider, preserve semantic message/event/result shapes at the public model boundary. -Keep provider-specific headers and endpoint paths in the adapter, document supported response -variants and test them against local fixtures before live traffic. A usage fixture does not verify -provider availability, streaming latency or authentication. - -## usage - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | map | required | Already received OpenAI-compatible response record | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Public prompt_tokens/completion_tokens/total_tokens usage projection | - -The `data` record is an observation rather than a request body. Missing counters follow the -public adapter convention; the example above contains two input tokens, three output tokens and -five total tokens. We return *[Read actual usage counters from the supplied response](openai.usage_from(data=`data`))* -without claiming to have measured a new model invocation. - -## resolve_local - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | None | Explicit local model override; None uses the adapter fallback | -| base_url | any | None | Explicit local API base URL; None uses the documented environment/default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Actual Ollama configuration selected by the existing resolver | - -The caller may supply `model`=None and `base_url`=None to use the shared local configuration -rules. Resolving the configuration does not launch a service or ask the model for a response. -We return *[Resolve local model fields with the existing adapter](ollama.resolve(model=`model`, base_url=`base_url`))*. -Treat the resulting configuration as runtime data and only execute a request after granting its effects. diff --git a/ext/ai/llm/ollama.mq.md b/ext/ai/llm/ollama.mq.md deleted file mode 100755 index 4dda90c..0000000 --- a/ext/ai/llm/ollama.mq.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -markup: occlusion -title: ext/ai/llm/ollama -description: >- - Ollama backend defaults. Transport reuses openai-compatible /v1 chat completions. -import: - openai: ext/ai/llm/openai.mq.md - sys: lib/sys.mq.md ---- - -## resolve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| model | any | None | Model resource or provider model identifier, as required by this operation | -| base_url | any | None | Provider API base URL | -| api_key | any | None | Provider credential from trusted runtime configuration | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `ollama`, model `llama3.2`. | - -Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. - -Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `ollama`, model `llama3.2`. - -1. `api_key` - We retain **key = api_key**. -2. * - We retain **key = "ollama"**. - -1. `base_url` - We retain **url = base_url**. -2. * - We retain **`url` = [Env get](sys.env_get(name="OLLAMA_HOST"))**. - 1. not `url` - We retain **url = "http://127.0.0.1:11434/v1"**. - 2. * - **_ = 1** - -1. `model` - We retain **mdl = model**. -2. * - We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_MODEL"))**. - 1. not `mdl` - We retain **mdl = "llama3.2"**. - 2. * - **_ = 1** - -`cfg` = - -| backend | api_key | base_url | model | -|---------|---------|----------|-------| -| ollama | `key` | `url` | `mdl` | - -Return *cfg*. - -## chat_completions - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| base_url | any | required | Provider API base URL | -| api_key | any | required | Provider credential from trusted runtime configuration | -| model | any | required | Model resource or provider model identifier, as required by this operation | -| prompt | any | required | Prompt text or structured prompt expected by this adapter | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Send the prepared chat request through this provider adapter and retain its usage, stream and failure conventions. | - -Use `base_url`, `api_key`, `model`, `prompt`, `stream`=False, `echo`=False as the inputs for this operation. - -Send the prepared chat request through this provider adapter and retain its usage, stream and failure conventions. - -Return *[Chat completions](openai.chat_completions(base_url=`base_url`, api_key=`api_key`, model=`model`, prompt=`prompt`, stream=`stream`, echo=`echo`))*. diff --git a/ext/ai/llm/openai.mq.md b/ext/ai/llm/openai.mq.md deleted file mode 100755 index 7236b96..0000000 --- a/ext/ai/llm/openai.mq.md +++ /dev/null @@ -1,235 +0,0 @@ ---- -markup: occlusion -title: ext/ai/llm/openai -description: >- - OpenAI-compatible chat completions transport (HTTP + SSE). - Prefers optional plugins/llm ABI when present; falls back to lib/net. - Used by ext/ai/llm; authors should prefer llm.ask / llm.stream. - Result packs are GFM tables / table.put (code-as-documentation). -import: - net: lib/net.mq.md - json: lib/json.mq.md - table: lib/table.mq.md - sys: lib/sys.mq.md - plugin: lib/plugin.mq.md ---- - -## usage_from - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | any | required | Structured input supplied to this adapter or resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map. | - -Use `data` as the inputs for this operation. - -Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map. - -We retain **`u` = [Read the usage field](json.get(value=`data`, key="usage"))**. -1. `u` - We retain **`pt` = [Read the prompt_tokens field](json.get(value=`u`, key="prompt_tokens"))**. - We retain **`ct` = [Read the completion_tokens field](json.get(value=`u`, key="completion_tokens"))**. - We retain **`tt` = [Read the total_tokens field](json.get(value=`u`, key="total_tokens"))**. - 1. not `pt` - We retain **pt = 0**. - 2. * - **_ = 1** - 1. not `ct` - We retain **ct = 0**. - 2. * - **_ = 1** - 1. not `tt` - We retain **tt = pt + ct**. - 2. * - **_ = 1** -2. * - We retain **pt = 0**. - We retain **ct = 0**. - We retain **tt = 0**. - -`usage` = - -| prompt_tokens | completion_tokens | total_tokens | -|---------------|-------------------|--------------| -| `pt` | `ct` | `tt` | - -Return *usage*. - -## tool_calls_from - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | any | required | Structured input supplied to this adapter or resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list). | - -Use `data` as the inputs for this operation. - -Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list). - -We retain **`choices` = [Read the choices field](json.get(value=`data`, key="choices"))**. -1. not `choices` - Return *[Empty list](table.empty_list())*. -2. * - We retain **`c0` = [Read 1 field](access(`choices`, "1"))**. - We retain **`msg` = [Read the message field](json.get(value=`c0`, key="message"))**. - 1. not `msg` - Return *[Empty list](table.empty_list())*. - 2. * - We retain **`tc` = [Read the tool_calls field](json.get(value=`msg`, key="tool_calls"))**. - 1. `tc` - Return *tc*. - 2. * - Return *[Empty list](table.empty_list())*. - -## chat_completions - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| base_url | any | required | Provider API base URL | -| api_key | any | required | Provider credential from trusted runtime configuration | -| model | any | required | Model resource or provider model identifier, as required by this operation | -| prompt | any | None | Prompt text or structured prompt expected by this adapter | -| messages | any | None | Ordered chat message records | -| selection | any | None | Explicit runtime/model selection | -| strict_selection | any | False | Whether an unresolved selection is an error | -| auth_mode | any | None | Authentication mode used by the provider adapter | -| stream | any | False | Whether to preserve streaming behavior or emit stream events | -| echo | any | False | Whether to print the documented incremental output | -| stream_kind | any | "delta" | Streaming event projection selected by the caller | -| suffix | any | "/chat/completions" | Provider endpoint suffix | -| bearer | any | "Bearer " | Bearer credential supplied by the configured provider | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_completions`) when the native plugin is resolvable; otherwise `lib/net` HTTP/SSE. Non-stream → `{text,usage,finish,tool_calls}`; stream → `{events,finish}`. Soft transport / HTTP failures return `finish=error` packs (never abort the VM). Pass either `messages=` (role/content list) or legacy `prompt=` (single user message). Optional `selection=` is a ModelSelectionV1 snapshot; `strict_selection=True` refuses env fallbacks inside the plugin. | - -Use `base_url`, `api_key`, `model`, `prompt`=None, `messages`=None, `selection`=None, `strict_selection`=False, `auth_mode`=None, `stream`=False, `echo`=False, `stream_kind`="delta", `suffix`="/chat/completions", `bearer`="Bearer " as the inputs for this operation. - -POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_completions`) when the native plugin is resolvable; otherwise `lib/net` HTTP/SSE. Non-stream → `{text,usage,finish,tool_calls}`; stream → `{events,finish}`. Soft transport / HTTP failures return `finish=error` packs (never abort the VM). - -Pass either `messages=` (role/content list) or legacy `prompt=` (single user message). Optional `selection=` is a ModelSelectionV1 snapshot; `strict_selection=True` refuses env fallbacks inside the plugin. -`stream_kind` tags live EventBus frames: `delta` (answer tokens) or `plan` (parent protocol — UI process trail, not the bubble). - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="llm"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. - Return *[Llm chat completions](llm_chat_completions(base_url=`base_url`, api_key=`api_key`, model=`model`, prompt=`prompt`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, auth_mode=`auth_mode`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`, suffix=`suffix`, bearer=`bearer`))*. -2. * - We retain **url = base_url + suffix**. - We retain **auth = bearer + api_key**. - We retain **`headers` = [Set the Authorization field in the new record](table.put(in=None, at="Authorization", value=`auth`))**. - - 1. not `messages` - - `messages` = - - | @ | role | content | - |---|------|---------| - | 1 | user | `prompt` | - 2. * - **_ = 1** - - `req` = - - | model | messages | - |-------|----------| - | `model` | `messages` | - - 1. `stream` - We retain **`req` = [Set the stream field in the new record](table.put(in=`req`, at="stream", value=True))**. - - `stream_opts` = - - | include_usage | - |---------------| - | True | - - We retain **`req` = [Set the stream_options field in the new record](table.put(in=`req`, at="stream_options", value=`stream_opts`))**. - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`req`))**. - We retain **`resp` = [Http post sse](net.http_post_sse(url=`url`, body=`body`, headers=`headers`, echo=`echo`))**. - We retain **`st` = [Read the status field](json.get(value=`resp`, key="status"))**. - 1. `st` == 200 - We retain **`evs` = [Read the events field](json.get(value=`resp`, key="events"))**. - - `pack` = - - | finish | events | - |--------|--------| - | stop | `evs` | - - Return *pack*. - 2. * - Soft transport / HTTP failure — structured pack, never abort the VM. - We retain **msg = "HTTP " + `st`**. - We retain **`evs` = [Read the events field](json.get(value=`resp`, key="events"))**. - 1. `evs` - We retain **`e0` = [At](at(value=`evs`, index=0))**. - We retain **`m2` = [Read the message field](json.get(value=`e0`, key="message"))**. - 1. `m2` - We retain **msg = `m2`**. - - `pack` = - - | finish | text | error | events | - |--------|------|-------|--------| - | error | "" | `msg` | `evs` | - - Return *pack*. - 2. * - We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`req`))**. - We retain **`resp` = [Http post](net.http_post(url=`url`, body=`body`, headers=`headers`))**. - We retain **`st` = [Read the status field](json.get(value=`resp`, key="status"))**. - 1. `st` == 200 - We retain **`raw` = [Read the body field](json.get(value=`resp`, key="body"))**. - We retain **`data` = [Parse the JSON transport text](json.parse(text=`raw`))**. - We retain **`choices` = [Read the choices field](json.get(value=`data`, key="choices"))**. - We retain **`choice0` = [At](at(value=`choices`, index=0))**. - We retain **`msg` = [Read the message field](json.get(value=`choice0`, key="message"))**. - We retain **`text` = [Read the content field](json.get(value=`msg`, key="content"))**. - 1. not `text` - We retain **text = ""**. - 2. * - **_ = 1** - We retain **`usage` = [Usage from](usage_from(data=`data`))**. - We retain **`fr` = [Read the finish_reason field](json.get(value=`choice0`, key="finish_reason"))**. - 1. not `fr` - We retain **fr = "stop"**. - 2. * - **_ = 1** - We retain **`tc` = [Tool calls from](tool_calls_from(data=`data`))**. - - `pack` = - - | finish | text | usage | tool_calls | - |--------|------|-------|------------| - | `fr` | `text` | `usage` | `tc` | - - Return *pack*. - 2. * - Soft transport / HTTP failure — structured pack, never abort the VM. - We retain **`raw` = [Read the body field](json.get(value=`resp`, key="body"))**. - We retain **msg = "HTTP " + `st`**. - 1. `raw` - We retain **msg = `msg` + ": " + `raw`**. - - `usage0` = - - | prompt_tokens | completion_tokens | total_tokens | - |---------------|-------------------|--------------| - | 0 | 0 | 0 | - - We retain **`empty_tc` = [Empty list](table.empty_list())**. - - `pack` = - - | finish | text | error | usage | tool_calls | - |--------|------|-------|-------|------------| - | error | "" | `msg` | `usage0` | `empty_tc` | - - Return *pack*. diff --git a/ext/ai/policies/step-route.mq.md b/ext/ai/policies/step-route.mq.md deleted file mode 100755 index 896f10f..0000000 --- a/ext/ai/policies/step-route.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -title: step-route policy (O3) -description: > - Table-driven map from step class → Adaptive Routing backend. - Readable authority for agent.step_route; do not invent a second dialect. ---- - -Step class to backend. - -Authors and `agent.step_route` read this table. Backends match Adaptive Routing: -`marqdo` | `small-llm` | `llm` | `auto`. - -## routes - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Return the same readable route table used by the agent policy reader. | - -Return the same readable route table used by the agent policy reader. - -Each column is a list with the same row order. Lookup and sandbox execution prefer Marqdo, patch work prefers the small model, and network-oriented work uses the model route. The default row leaves the final choice to the existing router. Returning these values does not load or invoke a backend. - -**routes = ** - -| kind | backend | note | -|------|---------|------| -| lookup | marqdo | OKF / kb skill hit — no parent LLM | -| patch | small-llm | Local patch / soft match | -| sandbox_run | marqdo | "CoW trial of .mq.md" | -| net | llm | Needs network / toolful turn | -| default | auto | Cascade policy → kb → small-llm | - -Return *routes*. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The entry returns the policy data without creating a second routing dialect. | - -The entry returns the policy data without creating a second routing dialect. - -Return *[Routes](routes())*. diff --git a/ext/ai/recovery.mq.md b/ext/ai/recovery.mq.md deleted file mode 100644 index afe2e47..0000000 --- a/ext/ai/recovery.mq.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -markup: occlusion -title: AI recovery — safe defaults for short SKILL functions -description: Reuse the native error policy, durable checkpoints and effect ledger. -import: - agent: ext/ai/agent.mq.md ---- - -Error handling belongs to Marqdo, not the model's prompt. The native policy -never blindly repeats uncertain writes. Every resume must revalidate the -current permission and source revision; a saved checkpoint is not authorization. - -## decide - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| error | map | required | Structured AgentErrorV1 | -| attempts | number | 0 | Number of attempts already made | -| effect_class | text | "read" | Declared tool effect | -| cancelled | bool | False | Parent cancellation status | -| fingerprint_repeats | number | 0 | Identical failures without new evidence | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Safe recovery action with budget | - -Use `error`, `attempts`=0, `effect_class`="read", `cancelled`=False, `fingerprint_repeats`=0 as the inputs for this operation. - -This returns an action, not an automatic retry or permission to execute. For -write or unknown effect, consult the effect ledger before taking another step. - -Return *[Select a bounded recovery action](agent.error_decide_retry(error=`error`, attempts=`attempts`, effect_class=`effect_class`, cancelled=`cancelled`, fingerprint_repeats=`fingerprint_repeats`))*. - -## save - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable logical run ID | -| task | any | None | Current task or user request | -| status | text | "waiting_input" | Current run status | -| effect_ledger_watermark | any | None | Durable ledger boundary if available | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | CheckpointV2 write result | - -Use `id`, `task`=None, `status`="waiting_input", `effect_ledger_watermark`=None as the inputs for this operation. - -Use the existing atomic checkpoint writer. When ledger evidence is absent, -a resumed writer requires manual review rather than automatic repetition. -This function saves metadata; it does not suspend a Rust execution frame. - -Return *[Save a versioned checkpoint](agent.resume_save(id=`id`, task=`task`, status=`status`, checkpoint_v2=True, effect_ledger_watermark=`effect_ledger_watermark`))*. - -## load - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Previously saved logical run ID | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Checkpoint or missing/unsafe recovery status | - -Use `id` as the inputs for this operation. - -Loading a checkpoint does not execute any saved step. The caller must inspect -recovery_mode and write_auto_resume before dispatching any effectful operation. - -Return *[Inspect the saved checkpoint](agent.resume_load(id=`id`))*. diff --git a/ext/ai/sandbox.mq.md b/ext/ai/sandbox.mq.md deleted file mode 100755 index ddf2bc3..0000000 --- a/ext/ai/sandbox.mq.md +++ /dev/null @@ -1,320 +0,0 @@ ---- -markup: occlusion -title: ext/ai/sandbox -description: >- - CoW trial workspace for AI-generated Marqdo: open / run / diff / commit. - Native work lives in plugins/agent (`sandbox_*` → host_query). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md - fs: lib/fs.mq.md ---- - -Load the agent plugin once per call (same pattern as other `ext/ai` helpers). - -Capability profiles are GFM tables under `## profile` (readable authority; `open` / `inspect` echo them). Do not invent a second table dialect. - -CoW trial operations belong here; attaching a sandbox profile to another result does not isolate execution. [The AI entry](index.mq.md) explains the relation to model and agent resources. A trial produces inspectable changes; promotion is a separate existing operation with its own checks. Keep cancellation, failed execution and explicit promotion visible, and never equate a generated source file with a committed successful outcome. - -## ensure_plugin - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the required native ABI plugin; missing binaries report a diagnostic message and stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/ai/sandbox: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -## profile - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | "default" | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`. Catalog (documentation + authority): | - -Use `name`="default" as the inputs for this operation. - -Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`. - -Catalog (documentation + authority): - -| name | fs_write | exec | net | plugin | -|------|----------|------|-----|--------| -| default | true | false | false | false | -| readonly | false | false | false | false | - -1. `name` == "readonly" - **row = ** - - | name | fs_write | exec | net | plugin | - |------|----------|------|-----|--------| - | readonly | false | false | false | false | - -2. * - **row = ** - - | name | fs_write | exec | net | plugin | - |------|----------|------|-----|--------| - | default | true | false | false | false | - -Return *row*. - -## open_native - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | any | None | Explicit root directory for discovery or isolated execution | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade. | - -Use `root`=None as the inputs for this operation. - -Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade. - -We **[Load the native plugin required by this operation](ensure_plugin())**. - -1. `root` - Return *[Native CoW open (plugin ABI italic return). Prefer ## open for the profile-aware facade.](sandbox_open(root=`root`))*. -2. * - Return *[Native CoW open (plugin ABI italic return). Prefer ## open for the profile-aware facade.](sandbox_open())*. - -## open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | any | None | Explicit root directory for discovery or isolated execution | -| profile | any | "default" | Capability profile selected for the trial | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Open a CoW session. Optional `root=` (directory). Default: entry file directory. | - -Use `root`=None, `profile`="default" as the inputs for this operation. - -Open a CoW session. Optional `root=` (directory). Default: entry file directory. -`profile=` selects the caps row from `## profile` (echoed by `inspect`). - -We retain **`sess` = [Open native](open_native(root=`root`))**. -We retain **`prof` = [Profile](profile(name=`profile`))**. -We retain **`sess` = [Set the profile field in the new record](table.put(in=`sess`, at="profile", value=`prof`))**. -Return *sess*. - -## write - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| text | any | required | Text supplied to the transformation or adapter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Write text into the session upper layer (host tree unchanged until `commit`). | - -Use `id`, `path`, `text` as the inputs for this operation. - -Write text into the session upper layer (host tree unchanged until `commit`). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Write text into the session upper layer (host tree unchanged until commit).](sandbox_write(id=`id`, path=`path`, text=`text`))*. - -## read - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read through CoW (upper, else lower; whiteout misses). | - -Use `id`, `path` as the inputs for this operation. - -Read through CoW (upper, else lower; whiteout misses). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Read through CoW (upper, else lower; whiteout misses).](sandbox_read(id=`id`, path=`path`))*. - -## remove - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Logical delete (whiteout). | - -Use `id`, `path` as the inputs for this operation. - -Logical delete (whiteout). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Logical delete (whiteout).](sandbox_remove(id=`id`, path=`path`))*. - -## diff - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List of `{ path, kind }` pending changes (`write` | `remove`). | - -Use `id` as the inputs for this operation. - -List of `{ path, kind }` pending changes (`write` | `remove`). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[List of { path, kind } pending changes (write | remove).](sandbox_diff(id=`id`))*. - -## commit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply upper / whiteout to the real workspace root. | - -Use `id` as the inputs for this operation. - -Apply upper / whiteout to the real workspace root. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Apply upper / whiteout to the real workspace root.](sandbox_commit(id=`id`))*. - -## discard - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Drop the session without writing the host tree. | - -Use `id` as the inputs for this operation. - -Drop the session without writing the host tree. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Drop the session without writing the host tree.](sandbox_discard(id=`id`))*. - -## run - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| source | any | None | Source text inspected or prepared by this operation | -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW). Pass `source=` or `path=` (relative to session root). | - -Use `id`, `source`=None, `path`=None as the inputs for this operation. - -Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW). -Pass `source=` or `path=` (relative to session root). - -We **[Load the native plugin required by this operation](ensure_plugin())**. - -1. `source` - Return *[Run Marqdo under sandbox caps (exec / net / plugin off; fs via CoW). Pass source= or path= (relative to session root).](sandbox_run(id=`id`, source=`source`))*. -2. `path` - Return *[Run Marqdo under sandbox caps (exec / net / plugin off; fs via CoW). Pass source= or path= (relative to session root).](sandbox_run(id=`id`, path=`path`))*. -3. * - We **[Print the prepared message](print(text="ext/ai/sandbox.run: need", source="or", path=""))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. - -## inspect_native - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Inspect an existing native CoW session without promoting its writes. | - -Use `id` as the inputs for this operation. - -Inspect an existing native CoW session without promoting its writes. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Inspect an existing native CoW session without promoting its writes.](sandbox_inspect(id=`id`))*. - -## inspect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| profile | any | "default" | Capability profile selected for the trial | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native caps / change counts, plus the GFM `## profile` row under key `profile`. | - -Use `id`, `profile`="default" as the inputs for this operation. - -Native caps / change counts, plus the GFM `## profile` row under key `profile`. - -We retain **`raw` = [Inspect native](inspect_native(id=`id`))**. -We retain **`prof` = [Profile](profile(name=`profile`))**. -We retain **`out` = [Set the profile field in the new record](table.put(in=`raw`, at="profile", value=`prof`))**. -Return *out*. - -## report - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| path | any | "sandbox-diff.md" | Explicit filesystem path; honor the documented filesystem root and operation effects | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report file, not a UI rewrite). | - -Use `id`, `path`="sandbox-diff.md" as the inputs for this operation. - -O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report file, not a UI rewrite). - -We retain **`pending` = [Diff](diff(id=`id`))**. -We retain **`n` = [Len](len(value=`pending`))**. -We retain **body = "# Sandbox diff report\n\nPending changes: "**. -We retain **body = body + n**. -We retain **body = body + "\n\n| path | kind |\n|------|------|\n"**. -- [row](遍历 pending 为 row) - We retain **`p` = [Read path field](access(`row`, "path"))**. - We retain **`k` = [Read kind field](access(`row`, "kind"))**. - We retain **body = body + "| "**. - We retain **body = body + p**. - We retain **body = body + " | "**. - We retain **body = body + k**. - We retain **body = body + " |\n"**. -We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`body`))**. - -**out = ** - -| path | count | -|------|-------| -| `path` | `n` | - -Return *out*. diff --git a/ext/ai/workflow.mq.md b/ext/ai/workflow.mq.md deleted file mode 100644 index 8c8137b..0000000 --- a/ext/ai/workflow.mq.md +++ /dev/null @@ -1,330 +0,0 @@ ---- -markup: occlusion -title: Native AI workflow — durable, short, one-step-at-a-time execution -description: Plugin-managed checkpointed decision flow without an external agent runtime. -import: - plugin: lib/plugin.mq.md - json: lib/json.mq.md - flow: ext/ai/flow.mq.md - subtask: lib/subtask.mq.md ---- - -Every step is an explicit commit boundary. The plugin stores accepted outputs, -refuses stale documents and conflicting decisions, and exposes the next action. -The caller must supply trusted session, principal and source revision fields; -model text is never an identity or permission token. `resume_dir` is a -host-relative checkpoint directory, never an absolute client path. - -## open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable run ID | -| steps | list | required | 1–128 ordered step records | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Created, resumed, or explicit conflict | - -Use `id`, `steps`, `source_revision`, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Opening the same ID with the same steps, source revision, session and principal -returns the current action instead of resetting progress. Reusing an ID with a -different plan or identity fails closed. - -We retain **p = [Locate the Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[Open durable workflow](agent_workflow_open(id=`id`, steps=`steps`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Missing ABI plugin](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -## next - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable run ID | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Current action or terminal state | - -Use `id`, `source_revision`, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -`next` is read-only: it does not call a model, run a child document or consume -the current step. Stopped states (`blocked`, `uncertain`, `cancelled`) and -unclassified child effects are reported explicitly. - -We retain **p = [Locate the Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[Find the next committed boundary](agent_workflow_next(id=`id`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Missing ABI plugin](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -## inspect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable run ID | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Progress summary with cursor, step and partial results | - -Use `id`, `source_revision`, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Use inspect for a UI progress panel or an operator audit. It returns the -durable checkpoint `status`, the next `action` (for example `waiting_model`), -cursor, total and completed step counts, the current step, and retained partial -child results without advancing the workflow. - -We retain **p = [Locate the Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[Read workflow progress](agent_workflow_inspect(id=`id`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Missing ABI plugin](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -## list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| session_id | text | None | Trusted session filter | -| principal_ref | text | None | Trusted principal filter | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Workflow summaries, newest metadata included separately | - -Use `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Only native workflow checkpoints are listed; unrelated resume records and -corrupt files are omitted. Pass host-attested filters to keep one session or -principal from seeing another's run identifiers. - -We retain **p = [Locate the Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[List workflow checkpoints](agent_workflow_list(session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Missing ABI plugin](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -## commit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable run ID | -| step_id | text | required | Exact current step | -| response | any | required | Completed step output | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Committed next step or explicit failure | - -Use `id`, `step_id`, `response`, `source_revision`, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -A completed step cannot be committed twice. Replaying the same value returns -the already-committed result; a different value for the same step conflicts. - -We retain **p = [Locate the Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[Validate and commit one step](agent_workflow_commit(id=`id`, step_id=`step_id`, response=`response`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Missing ABI plugin](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -## cancel - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Stable run ID | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Cancelled checkpoint status | - -Use `id`, `source_revision`, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Cancelling prevents future commits. It does not claim that children already -started by the supervisor were rolled back. - -We retain **p = [Locate the Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[Commit cancellation](agent_workflow_cancel(id=`id`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Missing ABI plugin](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - - -## tick - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Running workflow | -| source_revision | text | required | Pinned source revision | -| registry | map | None | Trusted SKILL registry | -| model | any | None | Configured LLM | -| session_id | text | None | Host-attested session | -| principal_ref | text | None | Host-attested principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | New checkpoint state, or waiting_input for the UI | - -Use `id`, `source_revision`, `registry`=None, `model`=None, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Advance at most one step. Model text is a candidate, never direct -execution. Waiting for a user returns immediately without holding a thread. -A caller repeats tick after verified completion; UI replies use commit. - -`tick` is the only wrapper that may execute a document child, and it only does -so after the checkpoint reports a read-only `ready_tool` step. When the action -is `waiting_input`, return the state unchanged so the host can display the -question and commit the attested answer on a later call. A blocked, uncertain -or cancelled checkpoint is returned as-is; recovery must use `retry_plan` or an -operator decision instead of silently ticking again. The returned state always -describes the committed boundary, not an optimistic guess about a running -child. - -We retain **state = [Load the next action](next(id=`id`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))**. -We retain **status = [Read action status](json.get(value=`state`, key="status"))**. -1. `status` == "waiting_model" - We retain **step = [Read model step](json.get(value=`state`, key="step"))**. - We retain **step_id = [Read step identifier](json.get(value=`step`, key="id"))**. - We retain **prompt = [Read local prompt](json.get(value=`step`, key="prompt"))**. - We retain **options = [Read allowed decisions](json.get(value=`step`, key="options"))**. - We retain **answer = [Make a bounded choice](flow.choose(input=`prompt`, options=`options`, model=`model`))**. - We retain **valid = [Check model decision](json.get(value=`answer`, key="ok"))**. - 1. `valid` - We retain **chosen = [Read verified model answer](json.get(value=`answer`, key="value"))**. - Return *[Commit the model choice](commit(id=`id`, step_id=`step_id`, response=`chosen`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. - 2. * - Return *answer*. -2. `status` == "ready_tool" - We retain **step = [Read tool step](json.get(value=`state`, key="step"))**. - We retain **kind = [Read operation kind](json.get(value=`step`, key="kind"))**. - We retain **step_id = [Read step identifier](json.get(value=`step`, key="id"))**. - 1. `kind` == "parallel" - We retain **tasks = [Read child tasks](json.get(value=`step`, key="tasks"))**. - We retain **report = [Run bounded parallel documents](flow.parallel(tasks=`tasks`))**. - Return *[Commit all child outcomes](commit(id=`id`, step_id=`step_id`, response=`report`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. - 2. `kind` == "skill" - We retain **name = [Read registered skill name](json.get(value=`step`, key="skill"))**. - We retain **out = [Run registered SKILL only](flow.enter(skill=`name`, registry=`registry`))**. - Return *[Commit verified child result](commit(id=`id`, step_id=`step_id`, response=`out`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. - 3. * - Return *state*. -3. `status` == "ready_return" - We retain **step = [Read return step](json.get(value=`state`, key="step"))**. - We retain **step_id = [Read step identifier](json.get(value=`step`, key="id"))**. - We retain **value = [Read final value](json.get(value=`step`, key="value"))**. - Return *[Commit the completed workflow](commit(id=`id`, step_id=`step_id`, response=`value`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -4. * - Return *state*. - - -## retry_plan - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Blocked workflow ID | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Failed-only read-task list or manual_review | - -Use `id`, `source_revision`, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Only a parallel step explicitly declared read-only and with no uncertain -effects may return a retry plan. Completed siblings are not included. - -We retain **p = [Locate Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[Select failed read-only children](agent_workflow_retry_plan(id=`id`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Native plugin unavailable](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -## retry_commit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Blocked workflow ID | -| results | list | required | New outcomes for failed children only | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Merged persistent report, or still blocked | - -Use `id`, `results`, `source_revision`, `session_id`=None, `principal_ref`=None, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Re-use successful child results from the checkpoint. New results fill failed -slots only, in original order; a newly uncertain outcome blocks further work. - -We retain **p = [Locate Agent ABI plugin](plugin.native_path(name="agent"))**. -1. `p` - We **[Load Agent ABI plugin](plugin.load(path=`p`))**. - Return *[Merge verified read-only retries](agent_workflow_retry_commit(id=`id`, results=`results`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *[Native plugin unavailable](json.parse(text="{\"ok\":false,\"status\":\"unavailable\"}"))*. - -## retry_failed - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Blocked workflow ID | -| source_revision | text | required | Pinned source revision | -| session_id | text | None | Trusted session | -| principal_ref | text | None | Trusted principal | -| limit | number | 2 | Max concurrent failed children | -| timeout_ms | number | 30000 | Child timeout | -| resume_dir | text | ".marqdo/agent-resume" | Host-relative checkpoint directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Recovered workflow, partial results or manual review | - -Use `id`, `source_revision`, `session_id`=None, `principal_ref`=None, `limit`=2, `timeout_ms`=30000, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. - -Run only the failed read-only tasks returned by the native checkpoint checker. -Unknown external writes never reach this path. - -We retain **plan = [Inspect safe retry manifest](retry_plan(id=`id`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))**. -We retain **can_retry = [Check permitted recovery](json.get(value=`plan`, key="ok"))**. -1. `can_retry` - We retain **tasks = [Read failed-only children](json.get(value=`plan`, key="tasks"))**. - We retain **outcomes = [Execute failed read-only children only](subtask.run_many(tasks=`tasks`, limit=`limit`, timeout_ms=`timeout_ms`))**. - Return *[Merge with preserved completed children](retry_commit(id=`id`, results=`outcomes`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))*. -2. * - Return *plan*. diff --git a/ext/ai/大模型.mq.md b/ext/ai/大模型.mq.md deleted file mode 100755 index 8fe04d7..0000000 --- a/ext/ai/大模型.mq.md +++ /dev/null @@ -1,541 +0,0 @@ ---- -markup: occlusion -title: ext/ai/大模型 -description: >- - Marqdo 大模型智能原语 — 提问 / 流式 / 收集 / 命名句柄。 - OpenAI 兼容与 Ollama HTTP 藏在语义面之后。 -导入: - table: lib/table.mq.md - 系统: lib/系统.mq.md - json: lib/json.mq.md - 文件: lib/文件.mq.md - 文本: lib/文本.mq.md - openai: ext/ai/llm/openai.mq.md ---- - -本文件是中文模型资源门面;从[中文入口](索引.mq.md)可以先运行无需联网的事件收集示例。提供方请求实现位于 llm 子目录,智能体编排位于智能体文件。创建资源只解析配置;真实请求还需插件、服务和授权。修改时同时核对英文模型面、语义事件、用量字段与传输失败,不把空文本当作可靠的成功信号。 - -## 加载环境 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 授权根目录内的文件路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 读取指定 dotenv 文件且保留已有环境变量;它不发送模型请求。 | - -这里使用`路径`=None。 - -读取指定 dotenv 文件且保留已有环境变量;它不发送模型请求。 - -完成后返回*[调用 加载环境](系统.加载环境(路径=`路径`))*。 - -## 收集 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 事件 | any | 必填 | 按顺序排列的流事件记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | Collapse stream events to text. Supports semantic `delta`/`done.result` and native-plugin raw frames (`type=data` + OpenAI chunk JSON). | - -这里使用`事件`。 - -Collapse stream events to text. Supports semantic `delta`/`done.result` and -native-plugin raw frames (`type=data` + OpenAI chunk JSON). - -例如先收到两个 delta 再收到 done 时,以最后非空 result 为准;只收到无内容事件则返回空文本。按事件顺序处理文本:delta 与 text 的 text 字段追加到当前回答;done 中非空的 result 覆盖累积文本;error 中非空的 message 也成为当前文本。因此返回的是收集文本,不是独立的成功状态。调用方若需区分失败,应同时检查原始事件,不能把非空文本当成请求成功。 - -兼容的 data 事件承载提供方 JSON。结束标记 [DONE] 不作为正文;普通数据从首条 choice 的 delta.content 或 message.content 读取。缺失内容不会凭空产生片段,JSON 解码失败仍遵循解析库的诊断。这里不排序、不重试,也不发送模型请求;输入顺序决定最终文字,空事件序列得到空字符串。 - -得到**answer = ""**。 - -- [ev](遍历 事件 为 ev) - 得到**`t` = [读取 type 字段](access(`ev`, "type"))**。 - 1. `t` == "done" - 得到**`done_r` = [读取 result 字段](access(`ev`, "result"))**。 - 1. `done_r` - 得到**answer = `done_r`**。 - 2. * - **_ = 1** - 2. `t` == "error" - 得到**`em` = [读取 message 字段](access(`ev`, "message"))**。 - 1. `em` - 得到**answer = `em`**。 - 2. * - **_ = 1** - 3. `t` == "delta" - 4. `t` == "text" - 得到**`chunk` = [读取 text 字段](access(`ev`, "text"))**。 - 1. `chunk` - 得到**answer = answer + chunk**。 - 2. * - **_ = 1** - 5. `t` == "data" - 得到**`raw` = [读取 data 字段](access(`ev`, "data"))**。 - 1. `raw` - 1. `raw` == "[DONE]" - **_ = 1** - 2. * - 得到**`parsed` = [解析 JSON 传输文本](json.parse(text=`raw`))**。 - 1. `parsed` - 得到**`choices` = [读取 choices 字段](access(`parsed`, "choices"))**。 - 1. `choices` - 得到**`c0` = [读取 1 字段](access(`choices`, "1"))**。 - 得到**`delta` = [读取 delta 字段](access(`c0`, "delta"))**。 - 1. `delta` - 得到**`piece` = [读取 content 字段](access(`delta`, "content"))**。 - 1. `piece` - 得到**answer = answer + piece**。 - 2. * - **_ = 1** - 2. * - 得到**`msg` = [读取 message 字段](access(`c0`, "message"))**。 - 1. `msg` - 得到**`piece` = [读取 content 字段](access(`msg`, "content"))**。 - 1. `piece` - 得到**answer = answer + piece**。 - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 2. * - **_ = 1** - 6. * - **_ = 1** - -1. not `answer` - 得到**answer = ""**。 -完成后返回*answer*。 - -## 流式结果 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 事件 | any | 必填 | 按顺序排列的流事件记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将流事件交给同源收集器,返回最终回答文本。 | - -这里使用`事件`。 - -将流事件交给同源收集器,返回最终回答文本。 - -完成后返回*[调用 收集](收集(事件=`事件`))*。 - -## 用量 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | any | 必填 | 交给本操作处理的结构化数据 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 从提供方响应中提取 token 用量,缺失计数采用公开实现约定。 | - -这里使用`数据`。 - -从提供方响应中提取 token 用量,缺失计数采用公开实现约定。 - -完成后返回*[调用 usage from](openai.usage_from(data=`数据`))*。 - -## 创建 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 模型 | any | None | 已配置的模型资源或模型标识 | -| 基址 | any | None | 提供方 API 基址 | -| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | -| 后端 | any | "openai-compatible" | 明确选择的执行或模型后端 | -| 名 | any | None | 本操作注册或查找的名称 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 按模型、基址和鉴权配置创建可复用的大模型资源;此步骤不请求回答。 | - -这里使用`模型`=None、`基址`=None、`密钥`=None、`后端`="openai-compatible"、`名`=None。 - -按模型、基址和鉴权配置创建可复用的大模型资源;此步骤不请求回答。 - -得到**`h` = [调用 大模型](大模型(模型=`模型`, 基址=`基址`, 密钥=`密钥`, 后端=`后端`, 名=`名`))**。 -完成后返回*h*。 - -## 快速 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 模型 | any | None | 已配置的模型资源或模型标识 | -| 基址 | any | None | 提供方 API 基址 | -| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 创建,保留同源能力的返回值和失败语义。 | - -这里使用`模型`=None、`基址`=None、`密钥`=None。 - -1. `模型` - 得到**mdl = 模型**。 -2. * - 得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_FAST_MODEL"))**。 - -完成后返回*[调用 创建](创建(模型=`mdl`, 基址=`基址`, 密钥=`密钥`, 名="fast", 后端="openai-compatible"))*。 - -## 推理 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 模型 | any | None | 已配置的模型资源或模型标识 | -| 基址 | any | None | 提供方 API 基址 | -| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 创建,保留同源能力的返回值和失败语义。 | - -这里使用`模型`=None、`基址`=None、`密钥`=None。 - -1. `模型` - 得到**mdl = 模型**。 -2. * - 得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_REASONING_MODEL"))**。 - -完成后返回*[调用 创建](创建(模型=`mdl`, 基址=`基址`, 密钥=`密钥`, 名="reasoning", 后端="openai-compatible"))*。 - -## 提示正文 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 源 | any | 必填 | 提示正文或源码来源 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 从指定文本构造提示正文,保留输入内容而不请求模型。 | - -这里使用`源`。 - -从指定文本构造提示正文,保留输入内容而不请求模型。 - -这里只识别源文本开头的前置元数据,且仅对声明为 prompt 或提示的文档提取正文。普通 Markdown、没有结束分隔线的文本和其他类型文档原样保留。正文只取当前分隔实现得到的首段并去掉两端空白,不承担通用 YAML 解析或提示模板插值;需要完整文件时使用文件库读取。 - -得到**`sw` = [调用 开头是](文本.开头是(内容=`源`, 前缀="---"))**。 -1. 非 `sw` - 完成后返回*源*。 -2. * - 得到**`parts` = [调用 split](split(value=`源`, sep="\n---\n"))**。 - 得到**`n` = [调用 len](len(value=`parts`))**。 - 1. `n` < 2 - 完成后返回*源*。 - 2. * - 得到**`fm` = [调用 at](at(value=`parts`, index=0))**。 - 得到**`is_p` = [调用 包含](文本.包含(内容=`fm`, 子串="type: prompt"))**。 - 1. 非 `is_p` - 得到**`is_p` = [调用 包含](文本.包含(内容=`fm`, 子串="类型: 提示"))**。 - 2. * - **_ = 1** - 1. `is_p` - 得到**`body` = [调用 at](at(value=`parts`, index=1))**。 - 完成后返回*[调用 去空白](文本.去空白(s=`body`))*。 - 2. * - 完成后返回*源*。 - -## 加载提示 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权根目录内的文件路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 从指定文件加载提示正文;文件访问仍受宿主文件权限限制。 | - -这里使用`路径`。 - -从指定文件加载提示正文;文件访问仍受宿主文件权限限制。 - -得到**`raw` = [读取指定文件的 UTF-8 正文](文件.读文本(路径=`路径`))**。 -完成后返回*[调用 提示正文](提示正文(源=`raw`))*。 - -## 提示 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 授权根目录内的文件路径 | -| 文本 | any | None | 本操作接收的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 提示正文,保留同源能力的返回值和失败语义。 | - -这里使用`路径`=None、`文本`=None。 - -1. `路径` - 完成后返回*[调用 加载提示](加载提示(路径=`路径`))*。 -2. `文本` - 完成后返回*[调用 提示正文](提示正文(源=`文本`))*。 -3. * - 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型.提示: 请传", 路径="或", 文本=""))**。 - 这里**[调用 退出](系统.退出(码=1))**。 - -## 提问 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 提示 | any | None | 提供给模型的提示内容 | -| 路径 | any | None | 授权根目录内的文件路径 | -| 模型 | any | None | 已配置的模型资源或模型标识 | -| 基址 | any | None | 提供方 API 基址 | -| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | -| p | any | 必填 | Prompt value passed to the selected model | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 | - -这里使用`提示`=None、`路径`=None、`模型`=None、`基址`=None、`密钥`=None、`p`。 - -1. `路径` - 得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。 -2. `提示` - 得到**p = 提示**。 -3. * - 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型.提问: 请传", 提示="或", 路径=""))**。 - 这里**[调用 退出](系统.退出(码=1))**。 - -得到**`m` = [调用 创建](创建(模型=`模型`, 基址=`基址`, 密钥=`密钥`))**。 -得到**`r` = [调用 提问](m.提问(提示=`p`))**。 -完成后返回*[text](access(r, "text"))*。 - -# 大模型 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 模型 | any | None | 已配置的模型资源或模型标识 | -| 基址 | any | None | 提供方 API 基址 | -| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | -| 后端 | any | "openai-compatible" | 明确选择的执行或模型后端 | -| 名 | any | None | 本操作注册或查找的名称 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 运行,保留同源能力的返回值和失败语义。 | - -这里使用`模型`=None、`基址`=None、`密钥`=None、`后端`="openai-compatible"、`名`=None。 - -1. `密钥` -构造器只整理连接配置并返回资源记录,不在此请求回答。显式传入的密钥优先,其后依次读取 OPENAI_API_KEY 与 MARQDO_LLM_API_KEY。兼容后端没有密钥会输出原因并以非零状态结束;本地 ollama 使用占位凭据以维持相同资源结构。记录包含实际凭据,应由调用方保管,避免直接打印整个句柄。 - -基址的选择同样保留显式值。ollama 未配置时使用本机兼容接口;其他后端依次尝试 OPENAI_BASE_URL、MARQDO_LLM_BASE_URL,最后采用公开默认地址。模型名依次来自显式值、OPENAI_MODEL、MARQDO_LLM_MODEL,最后按后端选用默认模型。默认模型名称只是现有运行约定,不保证提供方已开通、服务器已安装或网络可达。 - -返回记录保存后续请求所需的模型、后端、请求后缀、认证前缀和可选名称。实例方法从这个记录读取配置;改变环境不会自动重建已有句柄。需要切换配置时重新构造,不要把资源创建成功等同于鉴权或连通性验证。真实请求还要准备对应原生插件与运行授权;离线读取配置和真实网络调用是两个阶段。 - -例如在没有外部服务的离线配置检查中,可以显式选择 ollama、提供模型名与本地基址,只核对返回字段而不调用提问。在线验收则必须再检查真实请求的结束原因和用量。删除或覆盖环境配置前,也应考虑已有句柄仍保存旧凭据;本构造器不会主动清理其他资源或替调用方撤销密钥。 - - 得到**key = 密钥**。 -2. * - 得到**`key` = [调用 取环境](系统.取环境(名="OPENAI_API_KEY"))**。 - 1. 非 `key` - 得到**`key` = [调用 取环境](系统.取环境(名="MARQDO_LLM_API_KEY"))**。 - 2. * - **_ = 1** - -1. `后端` == ollama - 1. 非 `key` - 得到**key = "ollama"**。 - 2. * - **_ = 1** -2. 非 `key` - 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY"))**。 - 这里**[调用 退出](系统.退出(码=1))**。 -3. * - **_ = 1** - -1. `基址` - 得到**url = 基址**。 -2. `后端` == ollama - 得到**`url` = [调用 取环境](系统.取环境(名="OLLAMA_HOST"))**。 - 1. 非 `url` - 得到**url = "http://127.0.0.1:11434/v1"**。 - 2. * - **_ = 1** -3. * - 得到**`url` = [调用 取环境](系统.取环境(名="OPENAI_BASE_URL"))**。 - 1. 非 `url` - 得到**`url` = [调用 取环境](系统.取环境(名="MARQDO_LLM_BASE_URL"))**。 - 2. * - **_ = 1** - 1. 非 `url` - 得到**url = "https://api.openai.com/v1"**。 - 2. * - **_ = 1** - -1. `模型` - 得到**mdl = 模型**。 -2. * - 得到**`mdl` = [调用 取环境](系统.取环境(名="OPENAI_MODEL"))**。 - 1. 非 `mdl` - 得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_MODEL"))**。 - 2. * - **_ = 1** - 1. 非 `mdl` - 1. `后端` == ollama - 得到**mdl = "llama3.2"**。 - 2. * - 得到**mdl = "gpt-4o-mini"**。 - 2. * - **_ = 1** - -1. `名` - 得到**nm = 名**。 -2. * - 得到**nm = None**。 - -`h` = - -| _type | backend | api_key | base_url | model | suffix | bearer | name | -|-------|---------|---------|----------|-------|--------|--------|------| -| 大模型 | `后端` | `key` | `url` | `mdl` | /chat/completions | "Bearer " | `nm` | - -完成后返回*h*。 - -## 提问 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 提示 | any | None | 提供给模型的提示内容 | -| 路径 | any | None | 授权根目录内的文件路径 | -| p | any | 必填 | Prompt value passed to the selected model | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 | - -这里使用`提示`=None、`路径`=None、`p`。 - -1. `路径` -路径与直接提示同时存在时,先从路径加载提示;否则使用非空提示。两者都缺失时明确结束运行。当前接口还保留历史推断得到的 p 输入,表中如实列出其签名;本方法实际按上述分支重新设置请求正文,调用方不应把这个内部兼容参数当成另一种提示来源。 - -完整结果提供文本、结束原因、工具调用与用量。这里将它们整理为含模型与后端的记录;工具调用缺失时给出空列表。tokens 取 usage 中的 total_tokens,不能由回答字符数推算。llm_calls 是该接口的调用计数字段,并非计费凭据或独立的成功证明。网络失败应按完整结果的 finish 和相关诊断处理,不能只看 text 是否非空。 - -例如消费返回值时,先确认 finish,再取 text 展示;若 tool_calls 非空,则由上层明确决定是否进入受授权的工具流程。本方法只整理模型响应,不会看到工具请求就自动执行,也不会为调用方写入会话记录或文件。 - - 得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。 -2. `提示` - 得到**p = 提示**。 -3. * - 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 提问需要", 提示="或", 路径=""))**。 - 这里**[调用 退出](系统.退出(码=1))**。 - -得到**`pack` = [调用 完整结果](自.完整结果(提示=`p`, 流式=False, 打印增量=False))**。 -得到**`text` = [读取 text 字段](json.get(value=`pack`, key="text"))**。 -得到**`usage` = [读取 usage 字段](json.get(value=`pack`, key="usage"))**。 -得到**`finish` = [读取 finish 字段](json.get(value=`pack`, key="finish"))**。 -得到**`tc` = [读取 tool_calls 字段](json.get(value=`pack`, key="tool_calls"))**。 -1. not `tc` - 没有工具调用时,使用**tc = [创建空工具调用列表](table.empty_list())**,避免将缺失值误作一条调用。 -2. * - **_ = 1** - -表单元格会遮蔽 `自` / 列名,先取出字段再组结果表。 - -得到**`mdl` = [读取 model 字段](access(`自`, "model"))**。 -得到**`b` = [读取 backend 字段](access(`自`, "backend"))**。 -得到**`nm` = [读取 name 字段](access(`自`, "name"))**。 -得到**`tt` = [读取 total_tokens 字段](access(`usage`, "total_tokens"))**。 - -`result` = - -| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls | -|------|-------|--------|---------|-------|------|-----------|--------|------------| -| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` | - -完成后返回*result*。 - -## 流式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 提示 | any | None | 提供给模型的提示内容 | -| 路径 | any | None | 授权根目录内的文件路径 | -| 打印增量 | any | False | 是否输出流式增量文本 | -| p | any | 必填 | Prompt value passed to the selected model | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 运行,保留同源能力的返回值和失败语义。 | - -这里使用`提示`=None、`路径`=None、`打印增量`=False、`p`。 - -1. `路径` - 得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。 -2. `提示` - 得到**p = 提示**。 -3. * - 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 流式需要", 提示="或", 路径=""))**。 - 这里**[调用 退出](系统.退出(码=1))**。 - -完成后返回*[调用 运行](自.运行(提示=`p`, 流式=True, 打印增量=`打印增量`))*。 - -## 完整结果 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 提示 | any | 必填 | 提供给模型的提示内容 | -| 流式 | any | False | 是否使用流式调用 | -| 打印增量 | any | False | 是否输出流式增量文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 使用此大模型资源请求完整响应,保留文本、用量和失败信息。 | - -这里使用`提示`、`流式`=False、`打印增量`=False。 - -使用此大模型资源请求完整响应,保留文本、用量和失败信息。 - -完成后返回*[调用 chat completions](openai.chat_completions(base_url=[base_url](access(`自`, "base_url")), api_key=[api_key](access(`自`, "api_key")), model=[model](access(`自`, "model")), prompt=`提示`, stream=`流式`, echo=`打印增量`, suffix=[suffix](access(`自`, "suffix")), bearer=[bearer](access(`自`, "bearer"))))*。 - -## 运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 提示 | any | 必填 | 提供给模型的提示内容 | -| 流式 | any | False | 是否使用流式调用 | -| 打印增量 | any | False | 是否输出流式增量文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 | - -这里使用`提示`、`流式`=False、`打印增量`=False。 - -1. `流式` - 得到**`pack` = [调用 完整结果](自.完整结果(提示=`提示`, 流式=True, 打印增量=`打印增量`))**。 - 完成后返回*[events](access(pack, "events"))*。 -2. * - 得到**`pack` = [调用 完整结果](自.完整结果(提示=`提示`, 流式=False, 打印增量=`打印增量`))**。 - 完成后返回*[text](access(pack, "text"))*。 - -## 聊天 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 提示 | any | 必填 | 提供给模型的提示内容 | -| 流式 | any | False | 是否使用流式调用 | -| 打印增量 | any | False | 是否输出流式增量文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 使用此资源执行带历史消息的聊天请求,并保留公开实现的返回形态。 | - -这里使用`提示`、`流式`=False、`打印增量`=False。 - -使用此资源执行带历史消息的聊天请求,并保留公开实现的返回形态。 - -完成后返回*[调用 运行](自.运行(提示=`提示`, 流式=`流式`, 打印增量=`打印增量`))*。 diff --git a/ext/ai/智能体.mq.md b/ext/ai/智能体.mq.md deleted file mode 100755 index 1a725a9..0000000 --- a/ext/ai/智能体.mq.md +++ /dev/null @@ -1,522 +0,0 @@ ---- -markup: occlusion -title: ext/ai/智能体 -description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编译经 ABI v2 agent 插件(情景 → 学习 → llm_free)。 -导入: - 大模型: ext/ai/大模型.mq.md - agent: ext/ai/agent.mq.md - sandbox: ext/ai/sandbox.mq.md - table: lib/table.mq.md - json: lib/json.mq.md - 系统: lib/系统.mq.md - 自写回: lib/自写回.mq.md - 子任务: lib/子任务.mq.md - 插件: lib/插件.mq.md ---- - -本文件保留中文智能体的模型运行接口与工具调用流程。[中文入口](索引.mq.md)说明模型、编排与试跑的职责边界。内部函数的存在不代表它已进入模型白名单;工具请求必须由作者明确授权。开发时用离线模型替身核对历史、调用点、结果与写回,再测试真实传输。需要隔离执行时使用实际试跑入口,不能仅向结果附加配置记录。 - -## 构建单步上下文 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 智能体 | any | 必填 | 本库创建的智能体配置或接收者 | -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 源码深度 | any | "default" | 源码上下文读取深度,默认遵循预算 | -| 技能深度 | any | "default" | 技能上下文读取深度,默认遵循预算 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 组装可读提示:站立提示、任务、*调用位置*、工具、*预算*源码 + Skill,以及人可见的行动约定。 编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source|skill` 加深再答或 `调用:`。 实现委托 `agent.build_step_context`(与英文版同源)。 | - -这里使用`智能体`、`任务`、`源码深度`="default"、`技能深度`="default"。 - -组装可读提示:站立提示、任务、*调用位置*、工具、*预算*源码 + Skill,以及人可见的行动约定。 -编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source|skill` 加深再答或 `调用:`。 -实现委托 `agent.build_step_context`(与英文版同源)。 - -完成后返回*[调用 build step context](agent.build_step_context(agent=`智能体`, task=`任务`, source_depth=`源码深度`, skill_depth=`技能深度`))*。 - ---- - -## 提取工具名 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 回复 | any | 必填 | 待解析的模型回复,不直接作为执行授权 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 解析人可读调用行:`CALL:<名>` 或 `调用:<名>` / `调用:<名>`。 | - -这里使用`回复`。 - -解析人可读调用行:`CALL:<名>` 或 `调用:<名>` / `调用:<名>`。 - -这里按行识别工具协议,先去掉行两端空白,再按半角冒号分隔。CALL 或“调用”作为前缀时,后面的片段成为候选工具名;没有匹配则返回空值。当前实现不把任意自然语言中的函数名当作请求,也不在这里执行函数。候选值仍要经过运行工具的白名单判断。 - -注意实际分隔符是半角冒号,全角冒号的示意不能保证被本函数识别。同一回复包含多个有效协议行时,后面的匹配会覆盖前面的候选;工具名中的额外冒号也不作为完整名称保留。生成端应只输出一条明确的 CALL:name,避免依赖这种兼容解析。 - -保留所需的文本分隔符,先**esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**。 -得到**`nl` = [读取 nl 字段](json.get(value=`esc`, key="nl"))**。 -得到**`text` = [调用 trim](trim(value=`回复`))**。 -得到**`lines` = [调用 split](split(value=`text`, sep=`nl`))**。 -得到**found = 空**。 - -- [line](遍历 `lines` 为 `line`) - 得到**`t` = [调用 trim](trim(value=`line`))**。 - 得到**`parts` = [调用 split](split(value=`t`, sep=":"))**。 - 得到**`n` = [调用 len](len(value=`parts`))**。 - 1. `n` > 1 - 得到**`head` = [调用 at](at(value=`parts`, index=0))**。 - 得到**`head` = [调用 trim](trim(value=`head`))**。 - 得到**`rest` = [调用 at](at(value=`parts`, index=1))**。 - 得到**`rest` = [调用 trim](trim(value=`rest`))**。 - 1. `head` == CALL - 得到**found = rest**。 - 2. `head` == 调用 - 得到**found = rest**。 - 3. * - **_ = 1** - 2. * - **_ = 1** - -完成后返回*found*。 - ---- - -## 运行工具 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 工具 | any | 必填 | 明确允许的工具白名单或工具记录 | -| 名 | any | 必填 | 本操作注册或查找的名称 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 白名单校验后,经 `lib/子任务`(`启动 函数=` → `等待`)调用 runbook 中的 `##`。 | - -这里使用`工具`、`名`。 - -白名单校验后,经 `lib/子任务`(`启动 函数=` → `等待`)调用 runbook 中的 `##`。 - -得到**`allowed` = [调用 tool allowed](agent_tool_allowed(tools=`工具`, name=`名`))**。 -1. `allowed` - 得到**`id` = [调用 启动](子任务.启动(函数=`名`))**。 - 完成后返回*[调用 等待](子任务.等待(id=`id`))*。 -2. * - 得到**msg = "Tool not allowed:"**。 - 完成后返回*msg + `名`*。 - -# 智能体 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 大模型 | any | 必填 | 按提供方配置创建的模型资源 | -| 工具 | any | 必填 | 明确允许的工具白名单或工具记录 | -| 站立提示 | any | 必填 | 作者提供的常驻任务说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 加载 ABI v2 agent 插件(会话袋 + 上下文查询)。 | - -这里使用`大模型`、`工具`、`站立提示`。 - -加载 ABI v2 agent 插件(会话袋 + 上下文查询)。 - -创建记录同时注册历史会话;传入的模型应提供运行方法,工具来自作者明确给出的清单。构造成功表示资源就绪,不表示已执行任务。 - -得到**`p` = [定位已安装的原生插件](插件.原生路径(名="agent"))**。 -1. `p` - 这里**[调用 加载](插件.加载(路径=`p`))**。 -2. * - 这里**[输出本步已准备的消息](打印(内容="ext/ai/智能体: 未找到原生 agent 插件(请先 cargo build -p marqdo_plugin_agent 或 marqdo ext add agent)"))**。 - 这里**[调用 退出](系统.退出(码=1))**。 - -得到**`id` = [调用 alloc](agent_alloc())**。 - -`h` = - -| _type | id | model | tools | -|-------|-----|-------|-------| -| 智能体 | `id` | `大模型` | `工具` | - -1. `站立提示` - 得到**`h` = [在新记录中设置 standing 字段](table.put(in=`h`, at="standing", value=`站立提示`))**。 -2. * - **_ = 1** - -完成后返回*h*。 - -## 清空历史 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 清空本智能体 id 的插件会话袋。 | - -清空本智能体 id 的插件会话袋。 - -得到**`id` = [读取 id 字段](json.get(value=`自`, key="id"))**。 -这里**[调用 history clear](agent_history_clear(id=`id`))**。 -完成后返回*None*。 - -## 试跑 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 授权根目录内的文件路径 | -| 源码 | any | None | 本次检查或试跑的源码文本 | -| 根目录 | any | None | 明确选择的工程或试运行根目录 | -| 写入路径 | any | None | 明确的产物路径,或不写出时使用 None | -| 文本 | any | None | 本操作接收的文本 | -| 提交 | any | True | 是否在验证完成后晋升试运行变更 | -| 配置 | any | "default" | 试运行使用的能力配置 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。 | - -这里使用`路径`=None、`源码`=None、`根目录`=None、`写入路径`=None、`文本`=None、`提交`=True、`配置`="default"。 - -O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。 - -完成后返回*[调用 trial](agent.trial(path=`路径`, source=`源码`, root=`根目录`, write_path=`写入路径`, text=`文本`, commit=`提交`, profile=`配置`))*。 - -## 单步 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 写回 | any | True | 是否向任务文档写回观察结果 | -| 流式 | any | False | 是否使用流式调用 | -| 打印增量 | any | False | 是否输出流式增量文本 | -| 沙盒 | any | False | 是否采用 CoW 试运行路径 | -| 沙盒配置 | any | "default" | CoW 试运行能力配置 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 map 记录(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。 流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。 | - -这里使用`任务`、`写回`=True、`流式`=False、`打印增量`=False、`沙盒`=False、`沙盒配置`="default"。 - -原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 map 记录(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。 - -流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。 - -默认会写回调用文档;若只想观察结果,请显式传入写回=False,避免演示修改任务源码。这一轮先把用户任务写入当前会话历史,再用调用点上下文请求模型。流式分支先收集事件得到最终文本,普通分支直接取得回复。随后只把明确的工具协议视作调用候选;其余文字作为回答保留。中文兼容面使用模型的运行方法,并不要求调用方假装它具有英文资源的全部接口。 - -有工具候选时,运行工具负责核对作者白名单并等待子任务。拒绝结果进入 error 字段;成功结果被序列化后提供给模型,再形成面向用户的回答。tool_result 因而保存的是序列化文本,消费它时不要误当原始业务记录。没有工具候选时直接使用本次回复,避免重复请求。 - -这一步会把最终助手回复追加到同一历史,并按写回开关将完整记录放入调用点的 ok 或 error 槽。演示或只读任务应明确关闭写回,生产流程则要为实际文件操作准备权限。返回记录中的 status、decision、result 和工具字段分别说明流程状态、原始决定与最终答案,它们不能相互替代;任务特有的正确性仍由调用方验证。 - -这里的沙盒开关只给返回记录附加所选配置行,不会把上述模型或工具调用迁移到 CoW 环境。需要隔离试运行,应调用试跑入口或使用具有实际 CoW 执行边界的工程运行流程。不要依据 sandbox_profile 字段的存在宣称副作用已经隔离。写回失败、插件失败和传输失败仍沿既有运行诊断报告,函数没有通用事务回滚能力。 - -开发此方法时,先使用只返回固定文本的离线模型替身确认上下文、历史与结果字段,再分别验证工具允许、工具拒绝和写回开关。涉及真实模型的测试还应覆盖流式结束、错误事件和无文本结果。保持这两类验证分开,才能判断错误来自编排还是传输,避免用一次线上回答掩盖未执行的分支。 - -得到**`ctx` = [调用 构建单步上下文](构建单步上下文(智能体=`自`, 任务=`任务`))**。 -得到**`id` = [读取 id 字段](json.get(value=`自`, key="id"))**。 -得到**`model` = [读取 model 字段](json.get(value=`自`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`自`, key="tools"))**。 - -`user_turn` = - -| role | content | -|------|---------| -| user | `任务` | - -这里**[将本项追加到新列表](agent_history_append(id=`id`, item=`user_turn`))**。 - -1. `流式` - 得到**`evs` = [调用 运行](model.运行(提示=`ctx`, 流式=True, 打印增量=`打印增量`))**。 - 得到**`reply` = [调用 流式结果](大模型.流式结果(事件=`evs`))**。 -2. * - 得到**`reply` = [调用 运行](model.运行(提示=`ctx`))**。 - -得到**`reply` = [调用 trim](trim(value=`reply`))**。 -得到**decision = reply**。 -得到**`tool_name` = [调用 提取工具名](提取工具名(回复=`reply`))**。 - -`out` = - -| status | task | decision | -|--------|------|----------| -| ok | `任务` | `decision` | - -1. `tool_name` - 得到**`tool_out` = [调用 运行工具](运行工具(工具=`tools`, 名=`tool_name`))**。 - 得到**`tool_s` = [将结构化值编码为 JSON 文本](json.stringify(value=`tool_out`))**。 - 得到**`deny` = [调用 split](split(value=`tool_s`, sep="Tool not allowed"))**。 - 得到**`deny_n` = [调用 len](len(value=`deny`))**。 - 1. `deny_n` > 1 - 得到**`out` = [在新记录中设置 status 字段](table.put(in=`out`, at="status", value="error"))**。 - 得到**`out` = [在新记录中设置 error 字段](table.put(in=`out`, at="error", value=`tool_s`))**。 - 得到**reply = tool_s**。 - 2. * - 得到**`task_s` = [将结构化值编码为 JSON 文本](json.stringify(value=`任务`))**。 - 得到**fp = "The user asked:"**。 - 得到**fp = fp + task_s**。 - 得到**fp = fp + ". Tool"**。 - 得到**fp = fp + tool_name**。 - 得到**fp = fp + "ran via subtask and returned:"**。 - 得到**fp = fp + tool_s**。 - 得到**fp = fp + ". Reply to the user briefly."**。 - 1. `流式` - 得到**`evs2` = [调用 运行](model.运行(提示=`fp`, 流式=True, 打印增量=`打印增量`))**。 - 得到**`reply` = [调用 流式结果](大模型.流式结果(事件=`evs2`))**。 - 2. * - 得到**`reply` = [调用 运行](model.运行(提示=`fp`))**。 - 得到**`out` = [在新记录中设置 tool 字段](table.put(in=`out`, at="tool", value=`tool_name`))**。 - 得到**`out` = [在新记录中设置 tool_result 字段](table.put(in=`out`, at="tool_result", value=`tool_s`))**。 - 得到**`out` = [在新记录中设置 result 字段](table.put(in=`out`, at="result", value=`reply`))**。 -2. * - 得到**`out` = [在新记录中设置 result 字段](table.put(in=`out`, at="result", value=`reply`))**。 - -`as_turn` = - -| role | content | -|------|---------| -| assistant | `reply` | -这里**[将本项追加到新列表](agent_history_append(id=`id`, item=`as_turn`))**。 - -1. `沙盒` - 得到**`配置行` = [调用 profile](sandbox.profile(name=`沙盒配置`))**。 - 得到**`out` = [在新记录中设置 sandbox_profile 字段](table.put(in=`out`, at="sandbox_profile", value=`配置行`))**。 -2. * - **_ = 1** - -1. `写回` - 得到**`body` = [将结构化值编码为 JSON 文本](json.stringify(value=`out`))**。 - 得到**`st` = [读取 status 字段](json.get(value=`out`, key="status"))**。 - 1. `st` == "ok" - 这里**[调用 写回](自写回.写回(值=`body`, 键="ok"))**。 - 2. * - 这里**[调用 写回](自写回.写回(值=`body`, 键="error"))**。 -2. * - **_ = 1** - -完成后返回*out*。 - -## 工程预检 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 根目录 | any | "." | 明确选择的工程或试运行根目录 | -| 知识目录 | any | None | 检索和写回所用的知识目录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | Engineering First Information 门闩。转发 `agent.preflight`。 | - -这里使用`任务`、`根目录`="."、`知识目录`=None。 - -Engineering First Information 门闩。转发 `agent.preflight`。 - -完成后返回*[调用 preflight](agent.preflight(task=`任务`, root=`根目录`, marqdo_dir=`知识目录`))*。 - -## 多步 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 目标 | any | 必填 | 当前人类任务目标 | -| 工作簿目录 | any | None | 本次规划拥有的工作簿目录 | -| 工作簿 | any | None | 工作簿路径或工作簿引用 | -| 最大轮次 | any | 4 | 允许的工作簿规划轮数上限 | -| 确认分解 | any | False | 是否要求确认任务分解 | -| 写回 | any | True | 是否向任务文档写回观察结果 | -| 骨架 | any | "single" | 用于生成工作簿的源码模板 | -| 复用 | any | True | 是否先检索已有能力 | -| 优化 | any | False | 是否采用已说明的改进路径 | -| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 | -| 软命中 | any | False | 是否考虑有界近似匹配 | -| 近义命中 | any | True | 是否考虑近义能力候选 | -| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 | -| 晋升 | any | True | 是否允许将已验证证据晋升 | -| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | -| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 | -| 探索次数 | any | 3 | 有界探索尝试次数上限 | -| 流式 | any | False | 是否使用流式调用 | -| 打印增量 | any | False | 是否输出流式增量文本 | -| 轨迹 | any | False | 是否保留已说明的执行轨迹 | -| 工程预检 | any | False | 是否进行工程能力复用预检 | -| 工程知识目录 | any | ".marqdo" | 工程检索使用的知识目录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 多步工作簿默认写入 OKF `知识库目录/resources/.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。`工程预检` → `eng_preflight`。 | - -这里使用`目标`、`工作簿目录`=None、`工作簿`=None、`最大轮次`=4、`确认分解`=False、`写回`=True、`骨架`="single"、`复用`=True、`优化`=False、`强制`=False、`软命中`=False、`近义命中`=True、`近义阈值`=0.78、`晋升`=True、`知识库目录`=".marqdo/agent-kb"、`改进周期`=3、`探索次数`=3、`流式`=False、`打印增量`=False、`轨迹`=False、`工程预检`=False、`工程知识目录`=".marqdo"。 - -多步工作簿默认写入 OKF `知识库目录/resources/.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。`工程预检` → `eng_preflight`。 - -得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 -得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 -得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 -完成后返回*[调用 plan](en.plan(goal=`目标`, workbook_dir=`工作簿目录`, workbook=`工作簿`, max_rounds=`最大轮次`, confirm=`确认分解`, writeback=`写回`, skeleton=`骨架`, reuse=`复用`, optimize=`优化`, force=`强制`, soft_match=`软命中`, near_match=`近义命中`, near_threshold=`近义阈值`, promote=`晋升`, kb_dir=`知识库目录`, improve_every=`改进周期`, explore_n=`探索次数`, stream=`流式`, echo=`打印增量`, trace=`轨迹`, eng_preflight=`工程预检`, marqdo_dir=`工程知识目录`))*。 - -## 解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | -| 近义命中 | any | True | 是否考虑近义能力候选 | -| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 技能解析(v2):exact → alias → canonical → near。 | - -这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`近义命中`=True、`近义阈值`=0.78。 - -技能解析(v2):exact → alias → canonical → near。 - -得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 -得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 -得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 -完成后返回*[调用 resolve](en.resolve(task=`任务`, kb_dir=`知识库目录`, near_match=`近义命中`, near_threshold=`近义阈值`))*。 - -## 记录情景 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 状态 | any | "ok" | 当前结构化执行状态 | -| 结果 | any | None | 前一步返回的结构化结果 | -| 模式 | any | "explore" | 本函数说明支持的操作模式 | -| 技能 | any | "none" | 准备检查或调用的技能引用 | -| 观察 | any | None | 保留给后续步骤的工具或工作簿观察 | -| 工作簿 | any | None | 工作簿路径或工作簿引用 | -| 缓存 | any | None | 是否使用已说明的结果缓存 | -| 匹配 | any | None | 已解析的能力匹配结果 | -| 大模型次数 | any | 0 | 实际观测到的模型调用次数 | -| 工具次数 | any | 0 | 实际观测到的工具调用次数 | -| 错误 | any | None | 可恢复失败记录 | -| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将一次执行沉淀为 `.mq.md` 情景记忆。 | - -这里使用`任务`、`状态`="ok"、`结果`=None、`模式`="explore"、`技能`="none"、`观察`=None、`工作簿`=None、`缓存`=None、`匹配`=None、`大模型次数`=0、`工具次数`=0、`错误`=None、`记忆目录`=".marqdo/agent-memory"。 - -将一次执行沉淀为 `.mq.md` 情景记忆。 - -得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 -得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 -得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 -完成后返回*[调用 record episode](en.record_episode(task=`任务`, status=`状态`, result=`结果`, mode=`模式`, skill=`技能`, observation=`观察`, workbook=`工作簿`, cache=`缓存`, match=`匹配`, llm_calls=`大模型次数`, tool_calls=`工具次数`, error=`错误`, memory_dir=`记忆目录`))*。 - -## 尝试学习 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | -| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | -| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 | -| 晋升 | any | True | 是否允许将已验证证据晋升 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 情景足够时:归纳 → 合成候选 → 编译 → 可选晋升为 `llm_free` 技能。 | - -这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`改进周期`=3、`晋升`=True。 - -情景足够时:归纳 → 合成候选 → 编译 → 可选晋升为 `llm_free` 技能。 - -得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 -得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 -得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 -完成后返回*[调用 maybe learn](en.maybe_learn(task=`任务`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, improve_every=`改进周期`, promote=`晋升`))*。 - -## 运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | -| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | -| 学习 | any | True | 是否记录观察或进行学习 | -| 校验 | any | True | 是否运行已说明的校验器 | -| 写回 | any | True | 是否向任务文档写回观察结果 | -| 复用 | any | True | 是否先检索已有能力 | -| 近义命中 | any | True | 是否考虑近义能力候选 | -| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 | -| 晋升 | any | True | 是否允许将已验证证据晋升 | -| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 | -| 探索次数 | any | 3 | 有界探索尝试次数上限 | -| 最大轮次 | any | 4 | 允许的工作簿规划轮数上限 | -| 流式 | any | False | 是否使用流式调用 | -| 打印增量 | any | False | 是否输出流式增量文本 | -| 轨迹 | any | False | 是否保留已说明的执行轨迹 | -| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 | -| 路由 | any | "auto" | 路由配置或已选路由 | -| 路由模型 | any | None | 用于路由决策的模型资源 | -| 沙盒 | any | False | 是否采用 CoW 试运行路径 | -| 沙盒配置 | any | "default" | CoW 试运行能力配置 | -| 工程预检 | any | True | 是否进行工程能力复用预检 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。 | - -这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`学习`=True、`校验`=True、`写回`=True、`复用`=True、`近义命中`=True、`近义阈值`=0.78、`晋升`=True、`改进周期`=3、`探索次数`=3、`最大轮次`=4、`流式`=False、`打印增量`=False、`轨迹`=False、`强制`=False、`路由`="auto"、`路由模型`=None、`沙盒`=False、`沙盒配置`="default"、`工程预检`=True。 - -v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。 - -得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 -得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 -得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 -完成后返回*[调用 run](en.run(task=`任务`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, learn=`学习`, verify=`校验`, writeback=`写回`, reuse=`复用`, near_match=`近义命中`, near_threshold=`近义阈值`, promote=`晋升`, improve_every=`改进周期`, explore_n=`探索次数`, max_rounds=`最大轮次`, stream=`流式`, echo=`打印增量`, trace=`轨迹`, force=`强制`, router=`路由`, router_model=`路由模型`, sandbox=`沙盒`, sandbox_profile=`沙盒配置`, efi=`工程预检`))*。 - -## 路由 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | -| 后端 | any | "auto" | 明确选择的执行或模型后端 | -| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | -| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | -| 阈值 | any | 0.78 | 当前操作要求满足的策略阈值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 自适应路由(阶段 4):`marqdo` / `small-llm` / `llm` / `auto`(`jev`→别名)。 | - -这里使用`任务`、`后端`="auto"、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`阈值`=0.78。 - -自适应路由(阶段 4):`marqdo` / `small-llm` / `llm` / `auto`(`jev`→别名)。 - -得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 -得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 -得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 -完成后返回*[调用 route](en.route(task=`任务`, backend=`后端`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, threshold=`阈值`))*。 - -## 编译策略 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | -| 最少证据 | any | 3 | 允许晋升前所需的证据数量 | -| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 策略编译:稳定的 task→skill 映射 → `policies/router.mq.md`。 | - -这里使用`记忆目录`=".marqdo/agent-memory"、`最少证据`=3、`强制`=False。 - -策略编译:稳定的 task→skill 映射 → `policies/router.mq.md`。 - -得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 -得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 -得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 -得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 -完成后返回*[调用 compile policy](en.compile_policy(memory_dir=`记忆目录`, min_evidence=`最少证据`, force=`强制`))*。 diff --git a/ext/ai/沙盒.mq.md b/ext/ai/沙盒.mq.md deleted file mode 100755 index 724d2ea..0000000 --- a/ext/ai/沙盒.mq.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -markup: occlusion -title: ext/ai/沙盒 -description: >- - AI 试跑 CoW 工作区:打开 / 运行 / 差异 / 提交(中文面,委托英文 sandbox 模块)。 -import: - sandbox: ext/ai/sandbox.mq.md ---- - -本文件提供中文试跑门面,对应[试跑实现](sandbox.mq.md)。先读[中文入口](索引.mq.md)了解模型调用与 CoW 试跑的区别。试跑产生的文件变更和诊断供调用者检查,提升变更必须走已有显式流程;试跑返回不等于宿主工作区已经更新。保持失败、取消和提升的结果可区分,避免复制一份隔离实现。 - -## 打开 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 根 | any | None | 当前会话或工程明确授权的根目录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 按根目录与能力配置打开同源 CoW 试运行会话,不立即修改真实文件树。 | - -这里使用`根`=None。 - -按根目录与能力配置打开同源 CoW 试运行会话,不立即修改真实文件树。 - -完成后返回*[调用 open](sandbox.open(root=`根`))*。 - -## 写入 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | -| 路径 | any | 必填 | 授权根目录内的文件路径 | -| 文本 | any | 必填 | 本操作接收的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 把文本写入试运行会话的覆盖层,提交前不改真实文件。 | - -这里使用`id`、`路径`、`文本`。 - -把文本写入试运行会话的覆盖层,提交前不改真实文件。 - -完成后返回*[调用 write](sandbox.write(id=`id`, path=`路径`, text=`文本`))*。 - -## 读取 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | -| 路径 | any | 必填 | 授权根目录内的文件路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 透过试运行覆盖层读取文本,遵循白化删除和下层读取语义。 | - -这里使用`id`、`路径`。 - -透过试运行覆盖层读取文本,遵循白化删除和下层读取语义。 - -完成后返回*[调用 read](sandbox.read(id=`id`, path=`路径`))*。 - -## 删除 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | -| 路径 | any | 必填 | 授权根目录内的文件路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 在试运行覆盖层标记删除,不直接删除宿主文件。 | - -这里使用`id`、`路径`。 - -在试运行覆盖层标记删除,不直接删除宿主文件。 - -完成后返回*[调用 remove](sandbox.remove(id=`id`, path=`路径`))*。 - -## 差异 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 读取会话中的真实变更清单,供决定提交或丢弃。 | - -这里使用`id`。 - -读取会话中的真实变更清单,供决定提交或丢弃。 - -完成后返回*[调用 diff](sandbox.diff(id=`id`))*。 - -## 提交 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 把明确选择的试运行变更提交到宿主文件树,此操作会产生真实写入。 | - -这里使用`id`。 - -把明确选择的试运行变更提交到宿主文件树,此操作会产生真实写入。 - -完成后返回*[调用 commit](sandbox.commit(id=`id`))*。 - -## 丢弃 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 丢弃会话覆盖层中的变更,保留原始宿主文件。 | - -这里使用`id`。 - -丢弃会话覆盖层中的变更,保留原始宿主文件。 - -完成后返回*[调用 discard](sandbox.discard(id=`id`))*。 - -## 运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | -| 源码 | any | None | 本次检查或试跑的源码文本 | -| 路径 | any | None | 授权根目录内的文件路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 run,保留同源能力的返回值和失败语义。 | - -这里使用`id`、`源码`=None、`路径`=None。 - -1. `源码` - 完成后返回*[调用 run](sandbox.run(id=`id`, source=`源码`))*。 -2. `路径` - 完成后返回*[调用 run](sandbox.run(id=`id`, path=`路径`))*。 -3. * - 这里**[输出本步已准备的消息](print(text="沙盒.运行: 需要", 源码="或", 路径=""))**。 - 这里**[按指定退出码结束本次运行](sys.exit(code=1))**。 - -## 检查 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 检查当前试运行会话及能力配置,不把检查等同于提交成功。 | - -这里使用`id`。 - -检查当前试运行会话及能力配置,不把检查等同于提交成功。 - -完成后返回*[调用 inspect](sandbox.inspect(id=`id`))*。 diff --git a/ext/ai/索引.mq.md b/ext/ai/索引.mq.md deleted file mode 100755 index 19506a5..0000000 --- a/ext/ai/索引.mq.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -markup: occlusion -title: AI 工程入口:模型、智能体与试运行 -import: - 大模型: ext/ai/大模型.mq.md ---- - -从本入口选择任务:[大模型](大模型.mq.md)负责提示、配置、请求和流收集; -[智能体](智能体.mq.md)提供中文使用面,[同源编排实现](agent.mq.md)负责上下文、 -白名单工具、路由、工作簿和继续执行;[沙盒](沙盒.mq.md)管理试运行覆盖层及晋升。 -[提供方适配入口](llm/index.mq.md)解释 HTTP 适配,[路由策略](policies/step-route.mq.md) -保留可读表数据。[英文入口](index.mq.md)给出相同职责划分。 - -可以先运行完全离线的流收集,不需要凭据、模型服务或原生插件: - -```sh -marqdo call ext/ai/索引.mq.md 离线示例 --json -``` - -真实请求前明确模型基址和可信凭据,智能体还需要已构建的 agent 插件与工具白名单。 -生成的调用文本不是执行授权,文件写入、网络和进程仍受宿主限制。工具失败、取消、 -超预算或恢复时应保留观察与效果状态,不因继续工作簿而重复不可逆操作。 - -新增提供方去适配目录,公共模型行为去大模型模块,规划和上下文去智能体模块, -隔离修改去沙盒模块;保持中英文默认值与行为一致。先用本地可控替身验证成功与失败, -再在明确运行配置下测试真实服务。不能用固定完成标记冒充已经调用模型或验证了工具。 - -## 收集事件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 事件 | list | 必填 | 按顺序排列的语义流或公开收集器支持的提供方事件 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | text | 由公共收集器组装的最终回答文本 | - -输入`事件`是已经观测的数据,不会触发新请求或执行其中的工具文本。 -本工具复用公开大模型库的 delta/text 与 done.result 收集约定, -直接返回*[把已有事件组装成最终文本](大模型.收集(事件=`事件`))*, -使离线处理与真实传输复用同一份组装规则。 - -## 离线示例 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | text | Hello world,由下面的实际事件组装得到 | - -下面是一条确定的增量事件和一条完成事件。表格把输入内容完整列出, -读者可以比较局部文本与完成结果,不需要相信一个自报通过的标志。 -此流程只验证流收集,不暗示模型服务或网络已经可用。 - -`事件` = - -| @ | type | text | result | -|---|---|---|---| -| 1 | delta | "Hello " | None | -| 2 | done | None | "Hello world" | - -最后返回*[根据列出的事件得到最终文本](收集事件(事件=`事件`))*,供下一步展示或保存。 diff --git a/ext/data/admin.mq.md b/ext/data/admin.mq.md deleted file mode 100755 index 8513e54..0000000 --- a/ext/data/admin.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: Native administration resource -import: - table: lib/table.mq.md ---- - -This single-purpose resource enables the existing native administration surface on a prepared app. It does not construct a page or configure unrelated middleware. Attach real authentication afterwards so the native runtime adds its administration gate before listening. Custom Document desks remain ordinary declared routes and do not need this switch. - -## enable - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | map | required | Prepared application retaining its native admin_prefix, normally /admin | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Updated app with native administration enabled; no listener starts | - -Use `app` before attaching authentication and before listen. This pure resource composition retains the app's database, discovered Documents and other bindings, and changes only the existing native admin flag. The runtime lists only the business tables associated with explicitly mounted forms, shows up to 100 current rows per table, and links to those actual form resources. It does not enumerate unrelated credential/session tables or expose arbitrary SQL. The native renderer owns this landing page and its reserved route namespace. It does not create a second application configuration API. - -Authentication must be configured separately. When it is attached after enabling this surface, the existing native admin policy installs the default administration gate. The caller keeps the returned application and verifies both denied and accepted requests. Enabling a UI is not proof that credentials or database access have been authorized; the explicit server workflow supplies those dependencies. - -Return *[Enable only the native administration surface](table.put(in=`app`, at="admin", value=True))*. diff --git a/ext/data/api.mq.md b/ext/data/api.mq.md deleted file mode 100755 index d86be11..0000000 --- a/ext/data/api.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -title: Read-only JSON query routes for a database-backed site -import: - plugin: lib/plugin.mq.md ---- - -Use this leaf when a prepared web application needs native read-only database JSON routes. Database connections remain owned by db.mq.md; request tenant selection remains owned by the security tenant resource. This module only binds an explicit query table before listening. It does not introduce a second application configuration language. - -## mount - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared application with its database resource | -| routes | any | required | GFM rows with path, method, table, order, limit and optional tenant_scope | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Updated app containing the selected JSON query route set | - -Use `app` and `routes` with plugin. The table uses site-relative paths, database table names, a native order expression and row limits. This binding replaces the application's JSON query route set; supply all desired query routes in one readable table. Other middleware settings are retained. Keep the returned app for subsequent resource bindings and listen. - -Set tenant_scope to True only together with tenant.attach from ext/security/tenant.mq.md. With tenant resolution enabled, a scoped query requires a resolved tenant and adds an equality filter on its configured column. Tenant selectors do not authenticate users or prove membership. Protect private data through real authentication and trusted tenant selection; a query-string demonstration deliberately permits choosing either demo tenant. - -The native route surface selects rows and returns a JSON object with a rows list; it does not implement arbitrary SQL, write endpoints or form submission. Reading this source grants no network access and mounting does not listen. Extend native query behavior in the existing web middleware implementation, keep database policy visible in the route table, and test missing-tenant as well as cross-tenant responses. - -We **native = [Resolve the maintained database/web boundary](plugin.native_path(name="web"))** and **[Load its existing route implementation](plugin.load(path=`native`))**. -Return *[Bind this explicit JSON query route table](web_app_middleware(app=`app`, cors=None, security=None, compress=None, body_limit=None, json_routes=`routes`, access_log=None, cache_control=None, proxy=None, invoke=None))*. diff --git a/ext/data/cache.mq.md b/ext/data/cache.mq.md deleted file mode 100755 index 4c245b0..0000000 --- a/ext/data/cache.mq.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -markup: occlusion -title: ext/data/cache -description: Cache Resource (ADR 0007). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md ---- - -Cache values belong to the selected backend and process lifetime. Use memory: only for process-local demonstration; choose and configure persistent backends explicitly. [The data entry](index.mq.md) demonstrates set, get and deletion through one receiver. Retain native ok/error fields and expiry behavior when extending this leaf; a cache miss is not evidence that a remote write succeeded. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -# cache - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | "memory:" | Resource connection URL; scheme selects the documented backend | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Key–value cache. Use `memory:` for in-process (tests / single process) or `redis://host:6379/0` for Redis. | - -Use `url`="memory:" as the inputs for this operation. - -Key–value cache. Use `memory:` for in-process (tests / single process) or `redis://host:6379/0` for Redis. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Key–value cache. Use memory: for in-process (tests / single process) or redis://host:6379/0 for Redis.](web_cache_new(url=`url`))*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read the cached value associated with a key; a miss is reported by the cache result. | - -Use `key` as the inputs for this operation. - -Read the cached value associated with a key; a miss is reported by the cache result. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Read the cached value associated with a key; a miss is reported by the cache result.](web_cache_get(url=`url`, key=`key`))*. - -## set - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | -| value | any | required | Value supplied to this operation; immutable transformations return a new value | -| ttl | any | None | Expiry duration in seconds; None uses the backend default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Optional `ttl` is seconds until expiry. | - -Use `key`, `value`, `ttl`=None as the inputs for this operation. - -Optional `ttl` is seconds until expiry. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Optional ttl is seconds until expiry.](web_cache_set(url=`url`, key=`key`, value=`value`, ttl=`ttl`))*. - -## del - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delete a cached key without changing other entries. | - -Use `key` as the inputs for this operation. - -Delete a cached key without changing other entries. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Delete a cached key without changing other entries.](web_cache_del(url=`url`, key=`key`))*. - -## exists - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Test whether the cache currently holds the selected key. | - -Use `key` as the inputs for this operation. - -Test whether the cache currently holds the selected key. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Test whether the cache currently holds the selected key.](web_cache_exists(url=`url`, key=`key`))*. - -## ttl - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read the remaining lifetime of a cached key using the backend TTL convention. | - -Use `key` as the inputs for this operation. - -Read the remaining lifetime of a cached key using the backend TTL convention. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Read the remaining lifetime of a cached key using the backend TTL convention.](web_cache_ttl(url=`url`, key=`key`))*. diff --git a/ext/data/db.mq.md b/ext/data/db.mq.md deleted file mode 100755 index 80e3583..0000000 --- a/ext/data/db.mq.md +++ /dev/null @@ -1,498 +0,0 @@ ---- -markup: occlusion -title: ext/data/db -description: Database Resource — CRUD, txn, migrate, FTS (ADR 0007). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md ---- - -Database receivers own a connection URL. Begin a transaction with the database receiver, use its returned identifier for transaction operations, then commit or roll back explicitly. Read [the data workflow](index.mq.md) for a real isolated SQLite example and temporary-directory ownership. Native URLs resolve differently from filesystem helpers: validate an absolute SQLite path inside the granted root before passing it to the plugin. New query behavior belongs in the native web database implementation; schema and filters remain readable tables here. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -# db - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | "sqlite:site.db" | Resource connection URL; scheme selects the documented backend | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` / `postgresql://…` (same CRUD methods). | - -Use `url`="sqlite:site.db" as the inputs for this operation. - -Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` / `postgresql://…` (same CRUD methods). - -We **[Load the native plugin required by this operation](_load())**. -Return *[Open a database handle. URL schemes: sqlite:path (default), postgres://… / postgresql://… (same CRUD methods).](web_db_new(url=`url`))*. - -## init - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | required | Name registered or looked up by this operation | -| fields | any | required | Readable field definitions with the columns described by this resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present. | - -Use `name`, `fields` as the inputs for this operation. - -Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Create a table from a schema table](web_db_init(url=`url`, name=`name`, fields=`fields`))*. - -## insert - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| rows | any | required | Input row records to insert or process | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Insert the supplied row records, optionally within the selected open transaction. | - -Use `table`, `rows`, `txn`=None as the inputs for this operation. - -Insert the supplied row records, optionally within the selected open transaction. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Insert the supplied row records, optionally within the selected open transaction.](web_db_insert(url=`url`, table=`table`, rows=`rows`, txn=`txn`))*. - -## select - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | -| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold | -| order | any | None | Field order specification, with a leading minus for descending database order | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作|值|` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `|或|` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`. | - -Use `table`, `where`=None, `limit`=200, `order`=None, `txn`=None as the inputs for this operation. - -Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作|值|` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `|或|` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`r` = [Simple filters: one-row map of column→value (AND =), or rows |字段|操作|值| (= != > >= < <= like in between is null; add |或| = 是 to join a row with OR)](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=None, txn=`txn`))**. -Return *[rows](access(r, "rows"))*. - -## paginate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | -| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold | -| order | any | None | Field order specification, with a leading minus for descending database order | -| 跳过 | any | 0 | Number of matching rows skipped before the database page | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10). | - -Use `table`, `where`=None, `limit`=200, `order`=None, `跳过`=0, `txn`=None as the inputs for this operation. - -Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10). - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Like select but returns { rows, total } — the total counts rows matching where regardless of limit/跳过, so you can render 上一页 / 下一页](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=`跳过`, txn=`txn`))*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read a single row by its identifier from the selected database table. | - -Use `table`, `id`, `txn`=None as the inputs for this operation. - -Read a single row by its identifier from the selected database table. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Read a single row by its identifier from the selected database table.](web_db_get(url=`url`, table=`table`, id=`id`, txn=`txn`))*. - -## update - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| row | any | required | Field/value record to apply to the selected row | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Update the supplied fields of the selected row; use update_if when a revision comparison is required. | - -Use `table`, `id`, `row`, `txn`=None as the inputs for this operation. - -Update the supplied fields of the selected row; use update_if when a revision comparison is required. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Update the supplied fields of the selected row; use update_if when a revision comparison is required.](web_db_update(url=`url`, table=`table`, id=`id`, row=`row`, txn=`txn`))*. - -## update_if - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| row | any | required | Field/value record to apply to the selected row | -| expect_col | any | required | Column checked atomically in the conditional database update | -| expect_val | any | required | Expected current value of the comparison column | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Conditional update (CAS) for task/revision control: `UPDATE … WHERE id=? AND expect_col=expect_val`. Returns `{ ok, updated, matched }`; `updated=0` means conflict — do not simulate atomicity with read-then-write in `.mq.md`. | - -Use `table`, `id`, `row`, `expect_col`, `expect_val`, `txn`=None as the inputs for this operation. - -Conditional update (CAS) for task/revision control: `UPDATE … WHERE id=? AND expect_col=expect_val`. Returns `{ ok, updated, matched }`; `updated=0` means conflict — do not simulate atomicity with read-then-write in `.mq.md`. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Conditional update (CAS) for task/revision control: UPDATE … WHERE id=? AND expect_col=expect_val](web_db_update_if(url=`url`, table=`table`, id=`id`, row=`row`, expect_col=`expect_col`, expect_val=`expect_val`, txn=`txn`))*. - -## delete - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delete the selected row, optionally inside the caller-owned transaction. | - -Use `table`, `id`, `txn`=None as the inputs for this operation. - -Delete the selected row, optionally inside the caller-owned transaction. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Delete the selected row, optionally inside the caller-owned transaction.](web_db_delete(url=`url`, table=`table`, id=`id`, txn=`txn`))*. - -## exec - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL | -| args | any | None | Arguments passed to the selected command or operation | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Execute SQL with bound arguments and return the native execution outcome. | - -Use `sql`, `args`=None, `txn`=None as the inputs for this operation. - -Execute SQL with bound arguments and return the native execution outcome. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Execute SQL with bound arguments and return the native execution outcome.](web_db_exec(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*. - -## query - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL | -| args | any | None | Arguments passed to the selected command or operation | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`. | - -Use `sql`, `args`=None, `txn`=None as the inputs for this operation. - -Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Run bare SQL and return the result set — count / join / group / subqueries. Returns { rows, count }.](web_db_query(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*. - -## count - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | -| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Count rows matching a `where` filter (same syntax as `select`). Returns a number. | - -Use `table`, `where`=None, `txn`=None as the inputs for this operation. - -Count rows matching a `where` filter (same syntax as `select`). Returns a number. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`r` = [Count rows matching a where filter (same syntax as select). Returns a number.](web_db_count(url=`url`, table=`table`, where=`where`, txn=`txn`))**. -Return *[count](access(r, "count"))*. - -## migrate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| steps | any | required | Ordered migration or operation records in the documented table shape | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only. | - -Use `steps` as the inputs for this operation. - -Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Apply versioned SQL migrations](web_db_migrate(url=`url`, steps=`steps`))*. - -## fts - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| columns | any | required | Column-name list or column definitions required by this operation | -| name | any | None | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only. | - -Use `table`, `columns`, `name`=None as the inputs for this operation. - -Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Create an FTS5 index on table for the listed content columns (CSV string or list)](web_db_fts_create(url=`url`, table=`table`, columns=`columns`, name=`name`))*. - -## search - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| q | any | required | Full-text search query | -| limit | any | 20 | Maximum returned entries or candidates; this is not a success threshold | -| name | any | None | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only. | - -Use `table`, `q`, `limit`=20, `name`=None as the inputs for this operation. - -Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Full-text search (MATCH) against the FTS5 index from fts. Returns { rows, count } with a rank column (bm25). SQLite only.](web_db_search(url=`url`, table=`table`, q=`q`, limit=`limit`, name=`name`))*. - -## 事务 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Begin a transaction: borrows the pooled connection exclusively and returns a Every statement runs on the same connection, so a batch is atomic. | - -Begin a transaction: borrows the pooled connection exclusively and returns a -`txn` handle. Write inside it, then `提交` (commit) or `回滚` (roll back). -Every statement runs on the same connection, so a batch is atomic. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Begin a transaction: borrows the pooled connection exclusively and returns a Every statement runs on the same connection, so a batch is atomic.](web_db_begin(url=`url`))*. - -# txn - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| txn | any | required | Open transaction returned by the same database resource; None runs outside a transaction | -| url | any | required | Resource connection URL; scheme selects the documented backend | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | A transaction handle from `db.事务`. All CRUD here runs on the transaction's connection; finish with `提交` or `回滚`. The transaction identifier and connection URL remain explicit fields for every method. | - -Use `txn`, `url` as the inputs for this operation. - -A transaction handle from `db.事务`. All CRUD here runs on the transaction's -connection; finish with `提交` or `回滚`. - -The transaction identifier and connection URL remain explicit fields for every method. - -`handle` = - -| txn | url | -|---|---| -| `txn` | `url` | - -Return *handle*. - -## insert - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| rows | any | required | Input row records to insert or process | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior. | - -Use `table`, `rows` as the inputs for this operation. - -Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -Return *[Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior.](web_db_insert(url=`url`, table=`table`, rows=`rows`, txn=`txn`))*. - -## select - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | -| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold | -| order | any | None | Field order specification, with a leading minus for descending database order | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Same filters as `db.select`; runs inside the transaction. | - -Use `table`, `where`=None, `limit`=200, `order`=None as the inputs for this operation. - -Same filters as `db.select`; runs inside the transaction. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -We retain **`r` = [Same filters as db.select; runs inside the transaction.](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=None, txn=`txn`))**. -Return *[rows](access(r, "rows"))*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| id | any | required | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior. | - -Use `table`, `id` as the inputs for this operation. - -Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -Return *[Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior.](web_db_get(url=`url`, table=`table`, id=`id`, txn=`txn`))*. - -## update - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| id | any | required | Identifier produced or selected by the corresponding resource operation | -| row | any | required | Field/value record to apply to the selected row | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior. | - -Use `table`, `id`, `row` as the inputs for this operation. - -Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -Return *[Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior.](web_db_update(url=`url`, table=`table`, id=`id`, row=`row`, txn=`txn`))*. - -## delete - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | -| id | any | required | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior. | - -Use `table`, `id` as the inputs for this operation. - -Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -Return *[Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior.](web_db_delete(url=`url`, table=`table`, id=`id`, txn=`txn`))*. - -## exec - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL | -| args | any | None | Arguments passed to the selected command or operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior. | - -Use `sql`, `args`=None as the inputs for this operation. - -Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -Return *[Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior.](web_db_exec(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*. - -## 提交 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Commit the transaction and return its connection to the pool. | - -Commit the transaction and return its connection to the pool. - -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -Return *[Commit the transaction and return its connection to the pool.](web_db_commit(txn=`txn`))*. - -## 回滚 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Roll the transaction back (undo every write) and return its connection. | - -Roll the transaction back (undo every write) and return its connection. - -We retain **`txn` = [Read txn field](access(`self`, "txn"))**. -Return *[Roll the transaction back (undo every write) and return its connection.](web_db_rollback(txn=`txn`))*. diff --git a/ext/data/form.mq.md b/ext/data/form.mq.md deleted file mode 100755 index 2d4194a..0000000 --- a/ext/data/form.mq.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -markup: occlusion -title: ext/data/form -description: Form Resource — fields, validate, submit (ADR 0007). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md ---- - -This leaf projects form schema and submission operations through the native web runtime. Read [the data entry](index.mq.md) before connecting a form to persistent storage. Schema validation and route authorization are different responsibilities: an accepted field value does not authenticate its submitter. Keep schema rows, validation failures and persistence results visible when changing this resource. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - - -## reference - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | text | required | Exact id explicitly registered with mount | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Pure form_ref Resource for component.resource | - -Use `id` to reference the same mounted form that handles submissions. This constructor does not create a form, load a plugin or register a route. Serving resolves the id after preparing the request's actual CSRF token and return path. An unknown id is a real request error; it cannot become an empty successful form. - -The form's field/rule resource remains the single source for rendering and validation. Error responses retain the current CSRF token so the user can correct a field and resubmit. Authorization belongs to mount's optional role gate and the server's authentication policy, not the visibility of this node. - -`resource` = - -| _type | id | -|---|---| -| form_ref | `id` | - -Return *resource* for explicit placement in the existing View schema. - -## mount - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared web application with its actual database | -| id | text | required | Explicit system-form identifier used by reference | -| form | any | required | Form resource containing fields, rules and submission action | -| roles | any | None | None keeps public form behavior; otherwise gate the actual system form route | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Updated app with this form and optional server role gate | - -Use `app`, `id`, `form` and `roles`=None before listening. Keep the returned app. The native system form route uses the same resource to validate and submit; component.resource only places its reference in the readable page layout. No user route is implicitly registered. System endpoints remain visible through web.inspect. - -For a private form, provide roles explicitly so the actual /_form/id GET and POST path is gated as well as any containing page. Merely hiding a form or gating its presentation URL is insufficient. Configure authentication separately. A public creation example can retain roles=None. Existing sessions must submit the correct CSRF token; field-validation retries keep that token in the response. - -We **[Load the existing form implementation](_load())** and **mounted = [Bind this form to its explicit system id](web_app_mount_form(app=`app`, id=`id`, form=`form`))**. -1. `roles` != None - We **mounted = [Protect the actual system form endpoint](web_app_gate(app=`mounted`, path="/_form/" + id, roles=`roles`, permissions="", match="exact", on_deny="redirect", exclude=None))**. -Return *mounted* after the explicit form resource and policy are attached. - -# form - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | None | Database table name or form submission table | -| action | any | "insert" | Form submission action such as insert or update | -| id | any | None | Identifier produced or selected by the corresponding resource operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Field table + rules table; submit writes through `# db`. | - -Use `table`=None, `action`="insert", `id`=None as the inputs for this operation. - -Field table + rules table; submit writes through `# db`. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Field table + rules table; submit writes through # db.](web_form_new(table=`table`, action=`action`, id=`id`))*. - -## fields - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| fields | any | required | Readable field definitions with the columns described by this resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Attach the readable field definitions to this form and return the updated resource. | - -Use `fields` as the inputs for this operation. - -Attach the readable field definitions to this form and return the updated resource. - -Return *[Attach the readable field definitions to this form and return the updated resource.](web_form_fields(form=`self`, fields=`fields`))*. - -## rules - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rules | any | required | Readable validation-rule records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Attach validation rules to this form without submitting user data. | - -Use `rules` as the inputs for this operation. - -Attach validation rules to this form without submitting user data. - -Return *[Attach validation rules to this form without submitting user data.](web_form_rules(form=`self`, rules=`rules`))*. - -## labels - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| submit | any | "Submit" | Displayed submit-button label | -| cancel | any | "cancel" | Displayed cancel-button label | -| cancel_href | any | "" | Navigation target of the cancel action | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Localized submit / cancel copy for rendered forms. | - -Use `submit`="Submit", `cancel`="cancel", `cancel_href`="" as the inputs for this operation. - -Localized submit / cancel copy for rendered forms. - -Return *[Localized submit / cancel copy for rendered forms.](web_form_labels(form=`self`, submit=`submit`, cancel=`cancel`, cancel_href=`cancel_href`))*. - -## validate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rules | any | None | Readable validation-rule records | -| data | any | required | Structured input supplied to this adapter or resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Validate supplied field values and return the native validation result; this does not submit to the database. | - -Use `rules`=None, `data` as the inputs for this operation. - -Validate supplied field values and return the native validation result; this does not submit to the database. - -Return *[Validate supplied field values and return the native validation result; this does not submit to the database.](web_form_validate(form=`self`, rules=`rules`, data=`data`))*. - -## render - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | "form" | Identifier produced or selected by the corresponding resource operation | -| data | any | None | Structured input supplied to this adapter or resource | -| errors | any | None | Field/error record returned by validation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Render this form using its data and field errors; rendering is separate from database submission. | - -Use `id`="form", `data`=None, `errors`=None as the inputs for this operation. - -Render this form using its data and field errors; rendering is separate from database submission. - -Return *[Render this form using its data and field errors; rendering is separate from database submission.](web_form_render(form=`self`, id=`id`, data=`data`, errors=`errors`))*. - -## submit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | any | required | Structured input supplied to this adapter or resource | -| db | any | required | Database resource created by the public database constructor | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Submit validated form data through the selected database resource and configured action. | - -Use `data`, `db` as the inputs for this operation. - -Submit validated form data through the selected database resource and configured action. - -We retain **`url` = [Read url field](access(`db`, "url"))**. -Return *[Submit validated form data through the selected database resource and configured action.](web_form_submit(form=`self`, data=`data`, url=`url`))*. diff --git a/ext/data/index.mq.md b/ext/data/index.mq.md deleted file mode 100755 index a6bbd25..0000000 --- a/ext/data/index.mq.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -markup: occlusion -title: Data resources — database, cache, storage and forms -import: - cache_api: ext/data/cache.mq.md - db_api: ext/data/db.mq.md - fs: lib/fs.mq.md - path: lib/path.mq.md - result: lib/result.mq.md ---- - -Start here when a program needs persistent records, short-lived values, object storage or forms. -The public resource files remain the implementation: [database](db.mq.md) owns schemas and -transactions, [cache](cache.mq.md) owns expiry, [storage](storage.mq.md) owns blobs and upload -validation, and [forms](form.mq.md) separates validation, rendering and submission. -[View queries](view.mq.md) (中文:[视图](视图.mq.md)) retain current records inside recursive View nodes. -[Native administration](admin.mq.md) exposes only mounted forms and their business tables. -中文作者可以使用[表单](表单.mq.md)构造、定义字段规则、引用与挂载资源,使用[后台](后台.mq.md)启用同一个原生管理入口。 -[JSON query routes](api.mq.md) bind read-only database responses to a prepared site; -pair tenant-scoped queries with the explicit security tenant resource. - -These modules use the native web plugin. In this source checkout build it with -scripts/build-web-plugin.sh; installed packages follow the web package installation route. -Commands below run at the repository root. The cache example uses memory only. The transaction example creates a SQLite file -in an owned temporary directory. Prepare an existing disposable directory and export MQ_WORK to its -absolute path; the transaction report returns work_dir for cleanup after this process exits. -Neither example needs a cloud account, credentials or an external service. - -```sh -marqdo call ext/data/index.mq.md memory_cache 'key="manual"' 'value="ready"' --effects plugin --json -marqdo call ext/data/index.mq.md transaction_roundtrip --effects plugin,fs.write --fs-root "$MQ_WORK" --json -``` - -A resource constructor creates an object; its methods need that actual receiver. Use the free -workflow tools below for a single CLI call, or import the resource file and keep the object in -your program. Do not pass an instance method to call without its receiver or reconstruct a -transaction from guessed fields. Native resource URLs select their own backend: the marqdo -filesystem root does not rewrite a SQLite, S3 or Redis URL. Grant plugin access deliberately. - -For development, keep backend operations in the native web resource implementation and expose -small, documented compositions here. Specify row/filter shapes, transaction ownership, conflicts, -expiry units and cleanup. Add an operation to its responsible leaf file and exercise it through -this facade or a real author program. Run the source-handbook regression and database/cache gold -cases on both backends. A successful transport record is not proof that a business update matched. - -## memory_cache - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | "manual" | Key owned by this short-lived demonstration | -| value | any | "ready" | Value written and then read back from the in-process cache | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Actual cache get result; value contains the stored value | - -Use `key`="manual" and `value`="ready" unless the caller supplies different data. This -workflow uses memory: storage, so values belong to the current native plugin process. -It removes its key after reading; do not use a production key for an illustrative roundtrip. - -First **cache = [Create a process-local cache](cache_api.cache(url="memory:"))**. -We then **[Store the supplied value with a sixty-second expiry](> `cache`.set key=`key` value=`value` ttl=60 )** -and retain **stored = [Read the same cache entry](> `cache`.get key=`key` )**. -Once the value has been captured, **[Remove the demonstration key](> `cache`.del key=`key` )** -so another operation does not inherit it. Return *stored* as observed, including its backend fields. - -## transaction_roundtrip - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "." | Expected filesystem root; the default uses the actual --fs-root context | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | The committed row list and native commit/rollback outcomes; the second insert is rolled back | - -Use `root`="." for the actual --fs-root context, or pass the same absolute root explicitly. This isolated-file example shows the whole ownership sequence: create a schema, begin a transaction, -write through its receiver, finish it, and read outside it. A second transaction is explicitly -rolled back. The standalone txn constructor wraps the actual native identifier and connection URL; -it does not begin another transaction or invent an identifier. - -We **actual_root = [Resolve the actual granted filesystem root](fs.resolve(path="."))** and **expected_root = [Check the optional explicit root](fs.resolve(path=`root`))**. -1. `actual_root` != `expected_root` - Return *[Keep an inconsistent resource root explicit](result.error(code="data.root", message="root must match the granted filesystem root", operation="transaction_roundtrip"))*. -First **directory = [Create an owned temporary directory under the granted root](fs.temp_dir(prefix="data-manual"))**. -The filesystem helper returns a root-relative name. We retain **work_dir = [Resolve the owned name through the actual filesystem context](fs.resolve(path=`directory`))** -and **[Check that this absolute directory is inside the granted filesystem root](fs.stat(path=`work_dir`))** -before giving any path to the native database. We select **database_path = [Choose the SQLite file inside that directory](path.join(a=`work_dir`, b="manual.db"))** -and select **database_url = "sqlite:" + database_path** before creating -the receiver **store = [Open only that explicitly selected SQLite resource](db_api.db(url=`database_url`))**. -The table schema is ordinary readable data; both columns and their nullability remain visible. - -`fields` = - -| 字段 | 类型 | 可空 | -|---|---|---| -| title | text | False | -| body | text | True | - -We **[Create the isolated demonstration table](> `store`.init name="manual_notes" fields=`fields` )** -before borrowing the transaction connection. Next **native = [Begin the first transaction](> `store`.事务 )**. -To retain the exact identifier, **identifier = [Read the returned transaction identifier](access(native, "txn"))** -and **connection = [Read its connection URL](access(native, "url"))**. -Now **transaction = [Wrap those actual fields as a transaction receiver](db_api.txn(txn=`identifier`, url=`connection`))**. - -`row` = - -| title | body | -|---|---| -| committed | kept | - -We **[Insert the first row inside its transaction](> `transaction`.insert table="manual_notes" rows=`row` )** -and keep **committed = [Commit that transaction](> `transaction`.提交 )**. -The second **cancelled = [Begin an independent transaction](> `store`.事务 )** is a native -transaction receiver, which can be used directly because its type and resource fields are retained. -We **[Insert a row that will be discarded](> `cancelled`.insert table="manual_notes" rows=`row` )** -then capture **rolled_back = [Roll back the second transaction](> `cancelled`.回滚 )**. -Finally **rows = [Read the committed state outside a transaction](> `store`.select table="manual_notes" order="id" )**. - -`report` = - -| rows | committed | rolled_back | work_dir | -|---|---|---|---| -| `rows` | `committed` | `rolled_back` | `work_dir` | - -This example ends with one committed row. Real programs must also arrange rollback when a later -operation fails. This plugin pools open connections, so remove the owned work_dir only after this -CLI process exits and the connection is closed, including on failure. Do not assume sqlite::memory: -is in-memory through this ABI: relative resource paths are resolved against the module directory. -Return *report* with the real row data, completion records and cleanup location. diff --git a/ext/data/storage.mq.md b/ext/data/storage.mq.md deleted file mode 100755 index 5c86262..0000000 --- a/ext/data/storage.mq.md +++ /dev/null @@ -1,175 +0,0 @@ ---- -markup: occlusion -title: ext/data/storage -description: Object storage Resource (ADR 0007). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md ---- - -Use this resource for explicitly configured storage URLs; use lib/fs.mq.md for ordinary rooted filesystem operations. [The data entry](index.mq.md) explains resource ownership and the native web dependency. File bodies and byte encodings follow the native storage contract, so callers must inspect the returned operation result before publishing a resource URL. Add backend support in the existing plugin rather than encoding transport logic in callers. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -# storage - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | "file:data/blobs" | Resource connection URL; scheme selects the documented backend | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=…` talks to MinIO / S3. | - -Use `url`="file:data/blobs" as the inputs for this operation. - -Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=…` talks to MinIO / S3. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Object storage. file:dir stores blobs on disk (offline / gold). s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=… talks to MinIO / S3.](web_storage_new(url=`url`))*. - -## put - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | -| body | any | None | Object or request content, as described by the operation | -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| content_type | any | "application/octet-stream" | MIME type associated with the supplied content | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Provide either `body` (text) or `path` (local file to upload). | - -Use `key`, `body`=None, `path`=None, `content_type`="application/octet-stream" as the inputs for this operation. - -Provide either `body` (text) or `path` (local file to upload). - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Provide either body (text) or path (local file to upload).](web_storage_put(url=`url`, key=`key`, body=`body`, path=`path`, content_type=`content_type`))*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read the object selected by its storage key and retain the backend result shape. | - -Use `key` as the inputs for this operation. - -Read the object selected by its storage key and retain the backend result shape. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Read the object selected by its storage key and retain the backend result shape.](web_storage_get(url=`url`, key=`key`))*. - -## delete - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | any | required | Entry or field key within the selected resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Delete the selected object from this storage resource. | - -Use `key` as the inputs for this operation. - -Delete the selected object from this storage resource. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[Delete the selected object from this storage resource.](web_storage_delete(url=`url`, key=`key`))*. - -## list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prefix | any | "" | Object-key or generated-name prefix | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List object entries under the supplied key prefix. | - -Use `prefix`="" as the inputs for this operation. - -List object entries under the supplied key prefix. - -We retain **`url` = [Read url field](access(`self`, "url"))**. -Return *[List object entries under the supplied key prefix.](web_storage_list(url=`url`, prefix=`prefix`))*. - -# media - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| storage | any | None | Storage resource created by the public storage constructor | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Offline helpers for upload validation and saving into `# storage` (also used by HTTP `app.upload`). | - -Use `storage`=None as the inputs for this operation. - -Offline helpers for upload validation and saving into `# storage` (also used by HTTP `app.upload`). - -We **[Load the native plugin required by this operation](_load())**. -Return *[Offline helpers for upload validation and saving into # storage (also used by HTTP app.upload).](web_media_new(storage=`storage`))*. - -## validate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| filename | any | required | Original or suggested filename | -| content_type | any | "application/octet-stream" | MIME type associated with the supplied content | -| size | any | required | Byte size checked by upload validation | -| max_bytes | any | 5242880 | Maximum accepted byte count; exceeding the limit must fail explicitly | -| types | any | None | Allowed MIME types for upload validation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Validate an upload filename, MIME type and byte size against explicit limits before storing anything. | - -Use `filename`, `content_type`="application/octet-stream", `size`, `max_bytes`=5242880, `types`=None as the inputs for this operation. - -Validate an upload filename, MIME type and byte size against explicit limits before storing anything. - -Return *[Validate an upload filename, MIME type and byte size against explicit limits before storing anything.](web_upload_validate(filename=`filename`, content_type=`content_type`, size=`size`, max_bytes=`max_bytes`, types=`types`))*. - -## save - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | -| key | any | None | Entry or field key within the selected resource | -| content_type | any | "application/octet-stream" | MIME type associated with the supplied content | -| prefix | any | "uploads/" | Object-key or generated-name prefix | -| storage | any | None | Storage resource created by the public storage constructor | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Save the selected local upload through the configured storage resource and return its storage result. | - -Use `path`, `key`=None, `content_type`="application/octet-stream", `prefix`="uploads/", `storage`=None as the inputs for this operation. - -We retain **st = storage**. -1. `st` == None - We retain **`st` = [Read storage field](access(`self`, "storage"))**. -2. * - -Return *[Save the selected local upload through the configured storage resource and return its storage result.](web_upload_save(storage=`st`, path=`path`, key=`key`, content_type=`content_type`, prefix=`prefix`))*. diff --git a/ext/data/view.mq.md b/ext/data/view.mq.md deleted file mode 100755 index b345e00..0000000 --- a/ext/data/view.mq.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -markup: occlusion -title: Request-time database View resources ---- - -Use this single-file resource handbook when a recursively composed page needs current database rows on each request. Construction is pure: it records a query without connecting, selecting or rendering HTML. Place the result in component.resource and retain view: main for startup layout assembly. The application supplies its actual database resource when serving. - -Do not combine view: main with automatic data_source metadata. Ordinary Documents keep that metadata path; explicit View pages use this query Resource instead. A missing database, invalid condition or backend failure remains a request error, never a fabricated empty list. See [the request-resource design](../../doc/design/web-view-resources.md). - -## query - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| source | text | required | Existing table on the serving application's database | -| where | any | None | Native condition map or list; route placeholders resolve from actual request params | -| order | text | "" | Native database ordering, such as -created_at | -| limit | number | 50 | Integer from 1 through 1000 | -| detail | bool | False | False renders cards; True renders the first matching full article | -| link_prefix | text | "/post/" | Site-relative prefix applied to row slugs, or empty for no prefix | -| tenant_scope | bool | False | Require an attached tenant policy and current tenant filter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Pure data_query Resource; no query has executed yet | - -Use `source`, `where`=None, `order`="", `limit`=50, `detail`=False, `link_prefix`="/post/" and `tenant_scope`=False. The native renderer validates the contract before listening, then selects current records for each request. Card titles and summaries are escaped; article content uses the existing Markdown renderer. Detail mode prefers the complete body/content even when a summary exists. - -Rows follow the current Document convention: title, slug or href, summary, body or content, optional created_at/meta and tag. This fixed projection preserves the native card/article surface without restoring a private binding-table DSL. Layout remains in parent components; this resource only supplies one dynamic content region. For a different domain projection, keep a separate documented resource rather than passing arbitrary page configuration. - -Conditions are copied before replacing route placeholders, so one request cannot mutate another's retained definition. Path parameters take precedence over query keys. A requested tenant scope requires actual tenant configuration and context; direct selectors do not prove user membership. Link visibility and data filtering do not replace authentication or server authorization. - -This constructor needs no effects. Serving needs the actual web/database plugin and the launcher grants. Rendering the Resource offline without request context reports that requirement explicitly. Reading this file does not authorize a query, write or network listener. - -`resource` = - -| _type | source | where | order | limit | detail | link_prefix | tenant_scope | -|---|---|---|---|---|---|---|---| -| data_query | `source` | `where` | `order` | `limit` | `detail` | `link_prefix` | `tenant_scope` | - -Once its intended request behavior is explicit, return *resource* for placement in a View resource node. diff --git a/ext/data/后台.mq.md b/ext/data/后台.mq.md deleted file mode 100755 index 10f0289..0000000 --- a/ext/data/后台.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: 原生后台资源 -import: - admin: ext/data/admin.mq.md ---- - -本文件与 admin.mq.md 的原生后台开关对应。自定义后台 Document 继续显式声明自己的路由;这里仅启用已有的原生后台。先准备应用,再启用后台、附加鉴权,最后监听。它不承担任意页面配置或数据库管理语言。 - -## 启用 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | map | 必填 | 准备站点返回的应用,保留数据库和后台路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 只改变原生后台标志的新应用;未开始监听 | - -输入`应用`,本操作是纯资源组合,无需插件,不创建路由服务器或新数据库。保留返回的新应用后再附加鉴权,使原生策略安装默认后台门禁。后台只列显式挂载表单关联的业务表,每表展示至多 100 条当前记录,并链接到真实表单。 - -它不枚举其他凭据、会话表,也不开放任意 SQL。启用展示能力不证明用户已经认证,应验证匿名拒绝与已登录访问两个方向。自定义内容布局继续由 View 与 Document 负责;不要为后台添加新的通用配置袋。 - -配置后返回 *[启用已有的原生后台能力](admin.enable(app=`应用`))*。 diff --git a/ext/data/表单.mq.md b/ext/data/表单.mq.md deleted file mode 100755 index c463994..0000000 --- a/ext/data/表单.mq.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -markup: occlusion -title: 表单资源:构造、规则、引用与挂载 -import: - form: ext/data/form.mq.md ---- - -本文件对应英文 form.mq.md 的服务端装配工作流,中文作者直接调用这些具名函数。独立校验、离线表单渲染与直接提交仍使用英文文件对象的 validate、render、submit,不把页面引用当成直接写入工具。字段与规则同属一个原生表单资源,页面只安放引用,服务入口显式挂载它。构造、字段更新、校验与提交需要 plugin;引用是纯计算。以下示例只构造引用,不打开数据库或提交记录。 - -```sh -marqdo call ext/data/表单.mq.md 引用 '标识="article"' --json -``` - -准备真实表单时按构造、字段、规则、文案的顺序保留每次返回的新资源,再挂载到已准备的应用。实际处理请求的是 /_form/标识 系统地址。只保护展示页面不能保护提交入口;私有表单应给挂载指定角色,并另行配置鉴权。 - -## 构造 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 表 | text | 必填 | 已存在的数据库业务表名 | -| 动作 | text | "insert" | 原生提交动作,例如 insert 或 update | -| 标识 | any | None | update 使用的记录标识;插入通常不指定 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 尚未提交的原生表单资源 | - -输入`表`、`动作`="insert"与`标识`=None,调用需要 plugin。这里只创建表单资源,不建表、不插入记录,也不验证一次用户请求。继续调用字段与规则保留完整定义;实际数据库来自服务入口的应用资源。缺少原生插件或不支持的动作应保留真实诊断。 - -构造完成后返回 *[创建指定业务表的原生表单](form.form(table=`表`, action=`动作`, id=`标识`))*。 - -## 字段 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 资源 | any | 必填 | 构造返回的实际表单资源 | -| 定义 | any | 必填 | name、label、type、required 等字段记录表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 带字段定义的新表单资源 | - -输入`资源`和`定义`。name 应对应业务表字段;label 是展示文案,type 选择原生输入类型,required 使用布尔值。记录表用 @ 首列保持逐行结构。更新需要 plugin,返回值供规则或挂载继续使用;不提交用户输入,也不改变数据库结构。 - -完成定义后返回 *[将字段绑定到同一个表单](> `资源`.fields fields=`定义`)*。 - -## 规则 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 资源 | any | 必填 | 已有字段定义的实际表单资源 | -| 定义 | any | 必填 | field、rule、message 记录;例如 required 与 max:120 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 带原生校验规则的新表单资源 | - -输入`资源`和`定义`。规则按字段名关联,message 是拒绝输入时显示的原因。服务端仍执行相同规则,不能只依赖浏览器必填属性。此步需要 plugin,但不会尝试插入或更新记录。保留返回值,避免挂载未携带新规则的旧资源。 - -规则明确后返回 *[绑定实际提交使用的校验规则](> `资源`.rules rules=`定义`)*。 - -## 文案 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 资源 | any | 必填 | 保留字段和规则的实际表单资源 | -| 提交 | text | "提交" | 提交按钮文字 | -| 取消 | text | "取消" | 取消链接文字 | -| 返回地址 | text | "" | 取消目标;也是原生成功提交返回地址 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 带按钮文字和返回目标的新资源 | - -输入`资源`、`提交`="提交"、`取消`="取消"和`返回地址`="",调用需要 plugin。文案是纯文本,不承载 HTML。显式返回地址用于成功后的跳转;没有指定时由原生请求返回路径决定。设置按钮文案本身既不授权提交,也不改变字段校验规则。 - -配置后返回 *[保留提交、取消与成功返回目标](> `资源`.labels submit=`提交` cancel=`取消` cancel_href=`返回地址`)*。 - -## 引用 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标识 | text | 必填 | 服务入口通过挂载显式注册的系统表单标识 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 供组件请求资源节点安放的 form_ref 描述 | - -使用`标识`引用实际挂载的表单。构造无需任何副作用,不加载插件、不注册路由,也不伪造字段或 CSRF。请求时才由原生服务读取当前会话、返回路径和同一份字段规则;未挂载的标识保留错误,不能变成空的成功表单。 - -声明后返回 *[引用请求时的同一个表单](form.reference(id=`标识`))*。 - -## 挂载 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | 必填 | 已准备、保留数据库与路由上下文的应用 | -| 标识 | text | 必填 | 页面引用与系统 /_form/ 路径使用的标识 | -| 资源 | any | 必填 | 保留字段、规则和文案的实际表单 | -| 角色 | any | None | None 保持公开行为;否则保护实际系统表单 GET 与 POST | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 挂载资源与可选角色门禁后的新应用 | - -使用`应用`、`标识`、`资源`与`角色`=None,在监听前授予 plugin 并保留返回的应用。挂载绑定的是明确的系统地址,不暗中注册业务页面。私有表单应指定允许的角色并配置鉴权;仅隐藏控件或保护展示页不足以保护提交。 - -会话存在时提交必须携带真实 CSRF,字段失败的重试页面仍保留该令牌。系统路径可通过网页检视观察,但检视不能证明数据库可写或当前用户获准提交。公开示例可以保持角色为空,生产策略由调用者明确决定。 - -准备就绪后返回 *[绑定实际表单处理器及其访问策略](form.mount(app=`应用`, id=`标识`, form=`资源`, roles=`角色`))*。 diff --git a/ext/data/视图.mq.md b/ext/data/视图.mq.md deleted file mode 100755 index 2dc1b37..0000000 --- a/ext/data/视图.mq.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -markup: occlusion -title: 请求期间查询数据库的视图资源 ---- - -本文件是单文件资源手册。递归页面需要随请求变化的数据库记录时,构造这里的查询资源,再放入组件的资源节点。构造本身是纯计算,不连接数据库,也不生成 HTML;实际查询使用监听应用绑定的数据资源。 - -view: main 仍在启动时装配结构,不能混用自动 data_source 元数据。普通文档可继续使用元数据绑定;显式 View 用本资源表达动态内容。缺少数据库、条件错误或后端故障都保留请求诊断,不伪造空列表。 - -## 查询 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 源 | text | 必填 | 监听应用数据库中已有的业务表 | -| 条件 | any | None | 原生条件记录或列表;路径占位来自实际请求参数 | -| 排序 | text | "" | 数据库排序,例如 -created_at | -| 上限 | number | 50 | 1 至 1000 之间的整数 | -| 详情 | bool | False | False 显示卡片,True 显示首条完整文章 | -| 链接前缀 | text | "/post/" | 加到短链前的站内路径前缀 | -| 租户作用域 | bool | False | 要求显式租户策略及实际租户上下文 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 尚未查询的 data_query 资源,可放入资源节点 | - -使用`源`、`条件`=None、`排序`=""、`上限`=50、`详情`=False、`链接前缀`="/post/"与`租户作用域`=False。服务器先检查资源契约,再在每个请求中查询当前记录。卡片标题与摘要经过转义,完整文章使用已有 Markdown 渲染器;有摘要时,详情仍应显示完整正文,空正文也不会被摘要替换。 - -返回记录沿用文档的数据约定:title、slug 或 href、summary、body 或 content,以及可选的 created_at/meta 与 tag。父组件继续决定布局,本资源只承担一个动态内容区域。它不恢复旧的页面绑定表,也不接受任意页面配置。需要其他领域投影时,应另立职责清楚的资源。 - -每次请求先复制条件,再替换实际路径参数,避免污染启动时保留的定义。路径参数优先于同名查询参数。租户作用域要求已有租户策略和已解析租户;请求中的选择值不证明用户属于该租户,数据过滤也不能替代鉴权。 - -构造不需要副作用权限;服务实际使用插件和监听入口的授权。离线渲染缺少请求上下文时明确报错,不声称已执行查询。阅读源码不会授权数据库访问、写入或启动网络监听。 - -`资源` = - -| _type | source | where | order | limit | detail | link_prefix | tenant_scope | -|---|---|---|---|---|---|---|---| -| data_query | `源` | `条件` | `排序` | `上限` | `详情` | `链接前缀` | `租户作用域` | - -请求行为交代清楚后,返回 *资源*,交给组件资源节点安放。 diff --git a/ext/engineering/index.mq.md b/ext/engineering/index.mq.md deleted file mode 100755 index 1e96cdd..0000000 --- a/ext/engineering/index.mq.md +++ /dev/null @@ -1,371 +0,0 @@ ---- -markup: occlusion -title: Engineering boundaries for executable handbooks -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - paths: lib/path.mq.md - table: lib/table.mq.md - result: lib/result.mq.md ---- - -This extension supplies the small OS and service boundaries used by executable -engineering handbooks. File reads/writes, JSON/TOML, data decisions, retries and -release ordering remain Marqdo code. The native plugin provides bounded argv -process execution, private authenticated GitHub HTTPS, ZIP inspection and R2 -Signature V4 uploads. No Python interpreter or generated shell program is used. - -Read the task contract before calling it. Process children and native plugins -have the calling OS user's authority; a plugin grant is broader than a native -filesystem grant. The root parameter selects a working/artifact directory, not -an OS sandbox. Never treat reading this file as authorization to push refs, -change a release, upload assets or run arbitrary commands. - -Build this repository's marqdo_plugin_engineering crate before first use; the -development handbook's prepare_engineering task performs that bootstrap through -marqdo call. MARQDO_ENGINEERING_PLUGIN may select a locally built library. Installed -packs use the same plugin resolver as other official extensions. This boundary -is native-only; browser WASM cannot start processes or load this library. - -The public operation definitions and private request helper below share one -implementation. For the complete release workflow, read -[the executable release handbook](../../skills/marqdo-release/index.mq.md). -Normal filesystem work uses [the native file tools](../../skills/marqdo-dev/files.mq.md); -this extension is not an alternate file-write API. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load the installed or locally built engineering plugin | - -Resolve the library through the existing extension resolver so an installed -pack and a development build share the same public calls. A missing library -produces the normal plugin diagnostic; build or install it rather than hiding -the failure behind a fixed success result. Repeated loads use the host loader's -existing ownership rules. This private boundary requires plugin effects and -never guesses a Python replacement or invents an external interpreter. - -We **path = [Resolve the engineering native library](plugin.native_path(name="engineering"))**. -After locating it we return *[Load the bounded engineering operations](plugin.load(path=`path`))*. - -## request - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| operation | text | required | command, git_inspect, github, archive, analyze, gzip_text or r2_put | -| payload | map | required | Operation-specific ordinary data; never credential values | -| root | text | "." | Existing working/artifact root for this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result.ok/value/error from the selected boundary | - -Use `operation`, `payload` and `root`="." only at a documented native boundary. -Inputs travel as structured plugin values, not strings containing a generated -program. Failed process setup, HTTP, archive validation or signing remains a -failed Result. A successful command request still requires checking value.code -and value.timed_out. No private credential becomes a tool argument or result; -authentication is resolved inside the plugin from existing stores. - -We **loaded = [Load this package's native boundary](_load())** and -**base = [Read the granted runtime working root](sys.cwd())** and **resolved_root = root**. -1. not [The requested root is already absolute](paths.is_absolute(path=`root`)) - We **resolved_root = [Join the runtime cwd with the relative grant](paths.join(a=`base`, b=`root`))** so Windows and Unix separators stay native. - -`request_data` = - -| operation | payload | root | -|---|---|---| -| `operation` | `payload` | `resolved_root` | - -Return *[Perform the explicit native boundary operation](engineering_request(request=`request_data`))*. - -## run - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| argv | list | required | Executable followed by individual text arguments | -| cwd | text | "." | Existing directory inside root | -| timeout_ms | number | 120000 | Positive limit through 3600000 milliseconds | -| max_output | number | 262144 | Per-stream capture limit through 16777216 bytes | -| stdin | any | None | Optional text sent to child stdin, then closed | -| env | any | None | Optional child-only text environment values | -| root | text | "." | Root used to resolve cwd and local Git identity | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing code/stdout/stderr/timed_out/truncated | - -Use `argv`, `cwd`=".", `timeout_ms`=120000, `max_output`=262144, `stdin`=None, -`env`=None and `root`="." to invoke an existing OS tool. Arguments are passed -individually even when they contain quotes, spaces or shell metacharacters. -Inline shell programs, forced Git updates and hook bypass are rejected; a -checked-in packaging script remains a normal explicit external-tool invocation. - -The return distinguishes transport completion from child success. Inspect code -and timed_out before consuming stdout. Output is drained concurrently and kept -within the requested cap so noisy children cannot deadlock their own pipes. -On Unix, timeout kills the child process group; Windows attempts taskkill's tree -termination. Output retained by surviving descendants cannot cause unbounded -waiting. A process environment is child-local and does not mutate the parent. - -`payload` = - -| argv | cwd | timeout_ms | max_output | stdin | env | -|---|---|---|---|---|---| -| `argv` | `cwd` | `timeout_ms` | `max_output` | `stdin` | `env` | - -Return *[Execute the explicit argument vector with bounded capture](request(operation="command", payload=`payload`, root=`root`))*. - -## github - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | API path under /repos/cflmy/marqdo/ | -| method | text | "GET" | GET, PATCH or POST; mutations need the user's task instruction | -| data | any | None | JSON body; no authentication data | -| missing | bool | False | Treat GET 404 as a successful None | -| root | text | "." | Checkout used by credential helpers | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing service JSON, None or a redacted transport error | - -Use `path`, `method`="GET", `data`=None, `missing`=False and `root`=".". -The plugin resolves GH_TOKEN/GITHUB_TOKEN, Git's configured credential helper or -the checkout owner's existing gh store privately. It tries the configured -GitHub proxy before direct HTTPS. An uncertain POST is not replayed; a caller -must observe whether publication occurred before deciding to retry a mutation. - -Only this repository's API paths are accepted. HTTP errors report their status -without reflecting credentials, signed URLs or arbitrary response bodies. -Missing evidence stays missing; a network failure is not a synthetic empty -release. Test endpoint overrides are explicit environment configuration and -belong only in isolated fixture runs. - -`payload` = - -| path | method | data | missing | -|---|---|---|---| -| `path` | `method` | `data` | `missing` | - -Return *[Request private-authenticated repository service JSON](request(operation="github", payload=`payload`, root=`root`))*. - -## inspect_zip - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Existing ZIP or VSIX inside root | -| root | text | "." | Artifact root; symlink escapes are refused | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with entries and selected UTF-8 package metadata | - -Use `path` and `root`="." to inspect a binary format without extraction. -The plugin caps entry count and total expanded size, rejects escaping paths and -symlinks, and reads every entry to validate its content/CRC. It retains only -bounded VERSION, Cargo and VSIX metadata text for Marqdo's role-specific checks. -Hashing the archive itself remains lib/fs.file_hash, not an alternate Python IO -path. ZIP metadata cannot prove plugin ABI compatibility or execute a program. - -We **payload = [Name the one archive path field](table.put(in=None, at="path", value=`path`))**. - -Return *[Inspect the archive format without writing extracted files](request(operation="archive", payload=`payload`, root=`root`))*. - -## put_file - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Verified upload file inside root | -| key | text | required | Explicit R2 key such as vX.Y.Z/filename.zip | -| sha256 | text | required | Previously verified SHA256; changed bytes are rejected | -| root | text | "." | Root containing the local upload file | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with written key, SHA256 and byte count | - -Use `path`, `key`, `sha256` and `root`="." for an authorized publication. -The plugin transfers this bounded file across the authenticated service boundary -and rechecks its digest before signing; Marqdo decides which files and keys are -required. Credentials stay in existing R2 environment settings or ~/.marqdo/r2.env. -A configured credential home can select the maintainer's store when running under -another OS identity. Key material is never a parameter, result or command argument. - -This is an external write. Successful PUT is evidence for that key only; public -CDN parity is checked separately. The release handbook uploads every pack before -writing VERSION pointers and never sweeps unrelated files from dist. A timeout -remains uncertain publication, so inspect the public object before retrying. - -`payload` = - -| path | key | sha256 | -|---|---|---| -| `path` | `key` | `sha256` | - -Return *[Upload exactly the verified artifact with private R2 signing](request(operation="r2_put", payload=`payload`, root=`root`))*. - -## put_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | required | Explicit VERSION key selected by the release workflow | -| text | text | required | Small UTF-8 pointer body with its intended trailing newline | -| root | text | "." | Checkout used to locate existing credential stores | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with written key, SHA256 and byte count | - -Use `key`, `text` and `root`="." only after all required publication bytes are -verified. This operation signs a small UTF-8 service body; it does not write a -local file or infer which version should become latest. The calling Marqdo -workflow owns that decision and its ordering. Keys remain explicit so a replay -cannot silently publish a different version from environment state. -As with put_file, service completion does not substitute for reading the public -pointer and checking the associated download hashes. - -`payload` = - -| key | text | -|---|---| -| `key` | `text` | - -Return *[Write the explicitly selected publication pointer](request(operation="r2_put", payload=`payload`, root=`root`))*. -## analyze - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| source | text | required | Exact source text already read through lib/fs | -| include_body | bool | False | Include compiler AST debug evidence for migration review | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with compiler functions, contracts, diagnostics and narrative ratios | - -Use `source` and `include_body`=False to inspect an authored document -without executing it. File access belongs to the caller's native filesystem -step; this operation receives text and uses the actual Marqdo parser and checker. -It does not invent a regular-expression grammar, load imports, run main, open -network resources or infer permission from prose. Full dependency checks still -use marqdo check on the real file. - -The returned parameter names, defaults, heading spans and contracts support -editing without guessing the syntax. Narrative ratios come from the same -implementation used by the repository gate. AST debug evidence is optional -because it is large and intended for mechanical migration comparisons, while -the normal result remains a compact source description. - -`payload` = - -| source | include_body | -|---|---| -| `source` | `include_body` | - -Return *[Inspect this text with the real compiler](request(operation="analyze", payload=`payload`))*. - - -## gzip_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | map | required | Portable bytes returned by net.get(response="bytes") | -| max_bytes | number | 16777216 | Positive expanded UTF-8 limit, at most 64 MiB | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing decoded UTF-8 text or bounded format failure | - -Use `data` and `max_bytes`=16777216 at a compressed data boundary. -Native net.get owns the network read and returns portable bytes; this operation -only interprets their gzip format. It accepts concatenated gzip members, validates -their checksums, caps compressed input and expanded output, and rejects non-UTF-8 -text. No temporary file, shell pipeline or Python process is involved. - -This is useful for a published apt Packages.gz index. A successful HTTP response -alone cannot establish its package version; decode and inspect its real stanzas. -Malformed data or an expansion beyond the cap remains an error. Binary payloads -are outside this text contract. Calling requires plugin, while the caller's -earlier download independently requires network.read. - -`payload` = - -| data | max_bytes | -|---|---| -| `data` | `max_bytes` | - -Return *[Decode the bounded compressed text format](request(operation="gzip_text", payload=`payload`))*. - - -## check_exit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| outcome | map | required | Actual Result returned by engineering.run or its command boundary | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Observed process Result; failure retains its complete bounded execution evidence | - -Use `outcome` from an actual process call. Starting a process successfully is -different from that process succeeding: command transport can return ok=true -with a nonzero child code. This pure adapter requires code zero and no timeout. -It never starts or retries a process, changes a command or discards failed output. - -A setup/transport failure is retained unchanged. A nonzero exit or timeout becomes -a failed Result with the original execution record in value, including stdout, -stderr and truncation flags. This makes --require-ok useful for a complete -callable workflow without treating CLI transport success as a passed build. -Bounded output can be truncated even when the command succeeds; inspect that -flag before describing it as a full log. - -This function only classifies supplied observations. It cannot prove that an -arbitrary caller-provided map came from a real command. Development tasks call -run and then this adapter in the same source flow, retaining their actual argv -and result. Release ordering and retry policy remain the caller's responsibility. - -1. not access(`outcome`, "ok") - Return *outcome* with its original native setup failure. -We **execution = [Read the actual bounded process observation](access(outcome, "value"))**. -1. access(`execution`, "code") != 0 or access(`execution`, "timed_out") - We **failed = [Distinguish child failure from successful transport](result.error(code="engineering.process_failed", message="nonzero exit or timeout; inspect the actual execution in value", operation="check_exit"))**. - Return *[Keep all observed process evidence on failure](table.put(in=`failed`, at="value", value=`execution`))*. -Return *outcome* after the observed child exits successfully. - - -## checked - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| argv | list | required | Existing executable and individual text arguments | -| cwd | text | "." | Existing working directory within root | -| timeout_ms | number | 120000 | Positive child duration limit up to one hour | -| max_output | number | 262144 | Bounded bytes retained per stdout/stderr stream | -| stdin | any | None | Optional text sent to child standard input | -| env | any | None | Optional child-only text environment record | -| root | text | "." | Working root matching the intended checkout | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result requiring a zero child exit; actual execution evidence is retained | - -Use `argv`, `cwd`=".", `timeout_ms`=120000, `max_output`=262144, -`stdin`=None, `env`=None and `root`="." to execute one existing tool and require -its success in the same callable workflow. It composes run and check_exit rather -than regenerating process management, credential handling or a shell program. -The parameter vector, directory and resource limits keep their existing meaning. - -A setup failure, nonzero exit or timeout returns ok=false. Its actual stdout, -stderr and truncation state remain available for diagnosis. A successful result -means the observed child exited successfully; interpreting its business output -still belongs to the caller. Use --require-ok when this single call controls a -dependent external automation. No retry or publication is implied. - -This operation requires plugin. Its child retains normal OS authority, and the -native boundary keeps its existing argv guards and private credential rules. -For example, a unit-test task can pass cargo, test, --lib and --offline as four -separate text elements without needing a new generated command script. - -After the bounded execution we return *[Require the actual child outcome and preserve all evidence](check_exit(outcome=run(argv=`argv`, cwd=`cwd`, timeout_ms=`timeout_ms`, max_output=`max_output`, stdin=`stdin`, env=`env`, root=`root`)))*. diff --git a/ext/engineering/索引.mq.md b/ext/engineering/索引.mq.md deleted file mode 100755 index 2123b3a..0000000 --- a/ext/engineering/索引.mq.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -markup: occlusion -title: 工程拓展:让开发与发版操作成为可调用手册 -import: - 工程: ./index.mq.md ---- - -本文件是 [英文工程入口](index.mq.md) 的中文门面,复用同一个原生插件与行为。开发中的文件读取、撰写、哈希与数据处理应先使用标准库;本拓展只补齐进程、私密认证与压缩格式边界。任务的条件、重试和步骤顺序写在 mq.md 中,不再生成 Python 编排器。 - -首次使用前通过 skills/marqdo-dev/index.mq.md 的 prepare_engineering 构建本机开发解释器和插件。读取库文档不代表授权发布;推送、修改发布说明和上传对象必须属于用户已授权的任务。结果沿用 ok/value/error 字段,进程结果还要检查 code 和 timed_out,不能只根据请求成功就继续依赖步骤。 - -可在仓库根目录运行 marqdo call ext/engineering/索引.mq.md 运行 '参数=["git","--version"]' --effects plugin --fs-root . --json。完整发版流程位于 skills/marqdo-release/index.mq.md;普通文件操作位于开发目录的 files.mq.md。本地原生插件与子进程具有当前系统用户的权限,浏览器 WASM 不支持这些边界。 - -## 运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 参数 | list | required | 程序名与逐项文本参数,不是 shell 源码 | -| 目录 | text | "." | 根目录内的实际工作目录 | -| 超时毫秒 | number | 120000 | 1 到 3600000 毫秒 | -| 输出上限 | number | 262144 | 每个输出流的字节上限,最多 16 MiB | -| 输入 | any | None | 写入子进程标准输入后关闭;None 表示无输入 | -| 环境 | any | None | 仅影响子进程的文本环境映射 | -| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:包含 code、stdout、stderr、timed_out 与 truncated | - -使用`参数`,工作`目录`=".",`超时毫秒`=120000,`输出上限`=262144,`输入`=None,`环境`=None,`根目录`="."。参数逐项传递,空格、美元符号和引号不会被再次当作 shell 程序求值。命令入口拒绝内联 shell、强推和跳过钩子。 - -进程启动成功与命令执行成功是两个状态:必须检查 value.code 为零且 timed_out 为 False。输出并发读取并有界保存,避免大量日志堵住子进程。超时会尝试终止进程树,诊断信息保留已知凭据脱敏后的文本。调用需要 plugin;外部工具自己的文件和网络权限仍由操作系统决定。 - -完成该边界调用后返回*[按明确参数执行维护中的工具](工程.run(argv=`参数`, cwd=`目录`, timeout_ms=`超时毫秒`, max_output=`输出上限`, stdin=`输入`, env=`环境`, root=`根目录`))*。 - -## 分析源码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 源码 | text | required | 已经通过固有文件库读取的完整源码 | -| 包含正文 | bool | False | 是否附带大体积 AST 调试证据 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:真实编译器的函数、契约、诊断和叙述比例 | - -接收`源码`和`包含正文`=False,仅分析传入文本,不替调用者读取文件。这里复用解释器的真实解析与检查实现,不建立一套正则表达式语法。分析不会加载导入文件、执行 main 或请求外部服务。 - -参数顺序、默认值和源位置可以支持审阅式迁移;叙述比例采用仓库检查器的相同规则。附加正文仅适合需要逐语句核对的迁移诊断,普通使用先读契约与简要诊断。完整依赖正确性仍需对实际文件执行 marqdo check。调用需要 plugin,并不因源码描述了某个操作就授权执行该操作。 - -读到分析结果后返回*[用真实编译器检查这段文本](工程.analyze(source=`源码`, include_body=`包含正文`))*。 - -## 检查压缩包 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | required | 根目录内实际存在的 ZIP 或 VSIX | -| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:包内条目与有界保存的版本元数据 | - -使用`路径`与`根目录`=".",读取格式并校验每个条目的 CRC,整个过程不解压、不执行文件。插件拒绝越界路径、重复名称、软链接和超限展开量;标准库负责压缩包本身的大小与 SHA256。 - -检查格式通过不代表版本正确、插件 ABI 匹配或业务测试通过。调用者应继续核对具体产物角色、所需条目及 GitHub 提供的摘要。元数据文本有体积与 UTF-8 限制,缺失内容不能被当作已经验证。调用需要 plugin;根目录是工作位置,不能据此推断插件具有文件沙箱。 - -完成格式校验后返回*[检查真实压缩条目及其 CRC](工程.inspect_zip(path=`路径`, root=`根目录`))*。 - -## 解码gzip文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | map | required | 固有网络库返回的 portable bytes | -| 上限 | number | 16777216 | 展开后 UTF-8 字节上限,最多 64 MiB | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:解码文本或真实格式、编码、体积错误 | - -输入`数据`,设置`上限`=16777216。此任务只解释已经读取的 gzip 字节格式,不下载、不创建临时文件。它支持连接的 gzip 成员、校验校验和,并同时限制压缩输入与展开结果;非 UTF-8 数据也会返回失败。 - -Ubuntu 的 Packages.gz 就需要这一格式边界。HTTP 请求成功后仍要解码实际索引并查找目标包,不能把 200 状态直接当作可安装证据。文件与网络读取仍由固有库完成,压缩格式缺口由拓展承接;调用需要 plugin,不需要 Python 或 shell 解压流水线。 - -解码完成后返回*[有界解码已经读取的压缩文本](工程.gzip_text(data=`数据`, max_bytes=`上限`))*。 - -## GitHub请求 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | required | 本项目 /repos/cflmy/marqdo/ 下的 API 路径 | -| 方法 | text | "GET" | GET 只读;PATCH 与 POST 属于外部写入 | -| 数据 | any | None | 结构化 JSON 请求体,不包含凭据 | -| 允许缺失 | bool | False | GET 的 404 是否表示成功的 None | -| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:服务 JSON、允许的 None 或脱敏后的失败 | - -使用`路径`,`方法`="GET",`数据`=None,`允许缺失`=False,`根目录`="."。原生边界私密读取现有 GitHub 认证存储,先尝试已配置代理再直连;凭据不能成为工具参数或返回值。此接口仅用于本项目服务路径。 - -POST 的不确定响应不会自动重放,避免重复发布。调用者需要先观察远端是否已经出现目标资源,再决定恢复操作。网络错误保留错误,只有明确允许的 GET 404 才变成 None。调用需要 plugin;读取本手册本身不授权 PATCH 或 POST,具体写入必须来自用户当前任务。 - -服务请求完成后返回*[通过私密认证边界请求项目服务](工程.github(path=`路径`, method=`方法`, data=`数据`, missing=`允许缺失`, root=`根目录`))*。 - -## 上传文件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | required | 根目录内已经验证的上传文件 | -| 对象名 | text | required | 明确的 R2 对象名 | -| 摘要 | text | required | 预先通过固有文件库计算的 SHA256 | -| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:已写对象、SHA256 与字节数 | - -使用`路径`、`对象名`、`摘要`及`根目录`=".",只上传用户已授权发布的具体文件。插件在签名前再次检查摘要,防止校验后文件已经改变。R2 密钥留在既有环境与私密配置中,不传给模型、不写入源码。 - -此任务只证明这个对象的上传状态,不决定 latest,也不更新 VERSION。发布流程应先验证全部压缩包并上传,再写指针,最后读取公共 CDN 对比实际摘要。超时表示状态不确定,应观察对象而非立即假设没有上传。调用需要 plugin,原生文件整理与摘要计算仍由固有库完成。 - -完成明确对象的上传后返回*[上传仍与预验摘要一致的文件](工程.put_file(path=`路径`, key=`对象名`, sha256=`摘要`, root=`根目录`))*。 - -## 上传文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 对象名 | text | required | 发布流程明确选择的 VERSION 对象名 | -| 正文 | text | required | 包含预期换行的小体积 UTF-8 指针文本 | -| 根目录 | text | "." | 与 --fs-root 一致的工程根目录;插件不提供操作系统沙箱 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:已写对象、SHA256 与字节数 | - -使用`对象名`、`正文`和`根目录`=".",在全部相关压缩包已经验证并上传后更新指定指针。此任务不选择版本,也不判断是否应该成为 latest;这些顺序和决策在发版 mq.md 中公开表达。 - -凭据仍由私密认证边界处理,正文不是本地文件写入的替代接口。请求成功之后还要读取公共指针及其对应压缩包,缓存延迟必须保持未完成状态,不能把另一次上传当作验证。调用需要 plugin,并且必须属于用户授权的发布任务;单纯阅读文档不能触发对象写入。 - -完成该指针写入后返回*[写入流程已经确定的发布指针](工程.put_text(key=`对象名`, text=`正文`, root=`根目录`))*。 - - -## 检查退出 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 结果 | map | required | 运行任务返回的真实 Result 与子进程观察 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:只接受零退出且未超时的观察,失败仍保留输出 | - -接收`结果`之后,按工程边界已有规则检查退出码和超时状态。进程成功启动不代表编译或测试通过,因此这里把非零退出转成失败 Result,标准输出、错误输出和截断标记仍保留在 value 中。启动失败则沿用原来的诊断。 - -这个纯函数不再执行、重试或发布任何东西,也不能证明任意传入记录来自真实命令。需要完整的一次调用流程时,使用下方运行并检查,由它在同一份源码里连接真实执行与状态判断。 - -检查结束后返回*[按实际子进程结果保留成功或失败证据](工程.check_exit(outcome=`结果`))*。 - - -## 运行并检查 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 参数 | list | required | 已维护程序名及逐项文本参数 | -| 目录 | text | "." | 根目录内的实际工作目录 | -| 超时毫秒 | number | 120000 | 正数,最多 3600000 毫秒 | -| 输出上限 | number | 262144 | 每个输出流的有界字节数,最多 16 MiB | -| 输入 | any | None | 可选标准输入文本,发送后关闭 | -| 环境 | any | None | 仅影响子进程的文本环境记录 | -| 根目录 | text | "." | 实际工作根目录;不是操作系统沙箱 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:要求真实子进程成功,失败保留 code/stdout/stderr 等观察 | - -使用`参数`,工作`目录`=".",`超时毫秒`=120000,`输出上限`=262144,`输入`=None,`环境`=None,`根目录`="."。这里复用运行与检查退出两个已经实现的步骤,不再让智能体撰写另一份命令脚本。参数、私密凭据、进程树超时和输出上限都沿用已有原生边界。 - -调用需要 plugin。启动失败、非零退出或超时返回 ok=False;配合 --require-ok 可以阻止后续自动化继续。成功只表示这次子进程按零退出结束,具体业务结果仍由调用者判断。子进程拥有正常操作系统权限,不能把根目录参数当作沙箱,也不能把阅读本文当作发布授权。 - -执行结束后返回*[运行维护中的工具并检查其真实结果](工程.checked(argv=`参数`, cwd=`目录`, timeout_ms=`超时毫秒`, max_output=`输出上限`, stdin=`输入`, env=`环境`, root=`根目录`))*。 diff --git a/ext/linalg/index.mq.md b/ext/linalg/index.mq.md deleted file mode 100755 index d479440..0000000 --- a/ext/linalg/index.mq.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -markup: occlusion -title: Linear algebra — readable matrix workflows -import: - algebra: ext/linalg/linalg.mq.md ---- - -Start here for a complete matrix workflow, then read [the English API](linalg.mq.md) or -[the Chinese API](线性代数.mq.md). Both expose matrix construction, symbolic expressions, -dense evaluation, solving and reusable factorization. Author matrix methods require an actual -receiver; the free functions accept the expression or matrix explicitly. - -Build the native dependency with cargo build -p marqdo_plugin_linalg. This offline workflow -needs plugin permission and no files, network, live services or guessed handles: - -```sh -marqdo call ext/linalg/index.mq.md solve_example --effects plugin --json -``` - -The source matrix and right-hand side below are visible as native matrix formulas. A factorization is a native -structured result, not a string that should be parsed by callers. Reuse a factor only with -compatible dimensions. Rendering is separate: show/draw can write SVG when a path is supplied, -so production examples must state output ownership and cleanup. - -Develop matrix semantics in the native linalg implementation and keep public wrappers readable. -Add a new free operation and its EN/ZH counterpart, then update object conveniences only where -useful. Verify dimensions, singular systems and the numeric tolerance appropriate to the method; -a successful call alone does not prove that a numerical result is accurate. - -## solve_example - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native solve result with x.data equal to [[2], [1]] for the displayed system | - -This example solves two x plus y equals five, and x plus three y equals five. The matrix is -factored once as LU and then reused with the right-hand side. It demonstrates the real data -path without introducing a second formula parser or embedding an external language program. - -`coefficients` = -$$ -\begin{bmatrix}2&1\\1&3\end{bmatrix} -$$ - -`right_hand_side` = -$$ -\begin{pmatrix}5\\5\end{pmatrix} -$$ - -We create **matrix = [Construct the coefficient matrix](algebra.from_formula(formula=`coefficients`))** -and **right = [Construct the right-hand-side column](algebra.from_formula(formula=`right_hand_side`))**. -Next **factor = [Factor the coefficient matrix once](algebra.factorize(matrix=`matrix`, kind="lu"))** -retains the native factor for this system. We return *[Solve using the prepared factor](algebra.solve(b=`right`, factor=`factor`))*. -The expected entries are two and one; use the solve result fields rather than interpreting a display string. diff --git a/ext/linalg/linalg.mq.md b/ext/linalg/linalg.mq.md deleted file mode 100755 index 1b96ef8..0000000 --- a/ext/linalg/linalg.mq.md +++ /dev/null @@ -1,825 +0,0 @@ ---- -markup: occlusion -title: ext/linalg/linalg -description: Formula-first linear algebra (English). MatExpr simplify + display; ABI plugin. -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -Formula-first linear algebra (English). MatExpr simplify + display; ABI plugin. - -Use [the linear-algebra workflow](index.mq.md) to build a matrix from readable formula data, factor it once and solve through its receiver. This leaf owns the shared native matrix expression API. Keep dimensions, tolerance units, lazy expressions and materialized data distinct in new operations. Native ABI changes belong in marqdo_plugin_linalg; numeric validation should compare results and residuals rather than accepting a nonempty handle. - -## ensure_plugin - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Load the ABI v2 `linalg` plugin once. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="linalg"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/linalg: native linalg plugin not found (build marqdo_plugin_linalg or marqdo ext add linalg)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -## ping - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Plugin health check. | - -Plugin health check. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Plugin health check.](linalg_ping())*. - -## mul - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left matrix or numeric operand | -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix product (lazy MatMul; shape-checked). | - -Use `a`, `b` as the inputs for this operation. - -Matrix product (lazy MatMul; shape-checked). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Matrix product (lazy MatMul; shape-checked).](linalg_mul(a=`a`, b=`b`))*. - -## add - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left matrix or numeric operand | -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix / expression addition. | - -Use `a`, `b` as the inputs for this operation. - -Matrix / expression addition. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Matrix / expression addition.](linalg_add(a=`a`, b=`b`))*. - -## sub - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left matrix or numeric operand | -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix / expression subtraction. | - -Use `a`, `b` as the inputs for this operation. - -Matrix / expression subtraction. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Matrix / expression subtraction.](linalg_sub(a=`a`, b=`b`))*. - -## transpose - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Transpose expression. | - -Use `expr` as the inputs for this operation. - -Transpose expression. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Transpose expression.](linalg_transpose(expr=`expr`))*. - -## inv - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Symbolic inverse (lazy). | - -Use `expr` as the inputs for this operation. - -Symbolic inverse (lazy). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Symbolic inverse (lazy).](linalg_inv(expr=`expr`))*. - -## simplify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply MatExpr rewrite rules (R1–R5). | - -Use `expr` as the inputs for this operation. - -Apply MatExpr rewrite rules (R1–R5). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Apply MatExpr rewrite rules (R1–R5).](linalg_simplify(expr=`expr`))*. - -## ascii - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | -| raw | any | False | Whether to keep the unsimplified expression tree while rendering | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Display ASCII (default simplify first). Pass `raw=True` to keep the written tree. | - -Use `expr`, `raw`=False as the inputs for this operation. - -Display ASCII (default simplify first). Pass `raw=True` to keep the written tree. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Display ASCII (default simplify first). Pass raw=True to keep the written tree.](linalg_ascii(expr=`expr`, raw=`raw`))*. - -## latex - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | -| raw | any | False | Whether to keep the unsimplified expression tree while rendering | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | LaTeX display. | - -Use `expr`, `raw`=False as the inputs for this operation. - -LaTeX display. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[LaTeX display.](linalg_latex(expr=`expr`, raw=`raw`))*. - -## shape - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix shape (rows, cols). | - -Use `expr` as the inputs for this operation. - -Matrix shape (rows, cols). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Matrix shape (rows, cols).](linalg_shape(expr=`expr`))*. - -## show - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| raw | any | False | Whether to keep the unsimplified expression tree while rendering | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Record a formula SVG via host plot channel (default simplify). Returns the expr map. | - -Use `expr`, `path`=None, `raw`=False as the inputs for this operation. - -Record a formula SVG via host plot channel (default simplify). Returns the expr map. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Record a formula SVG via host plot channel (default simplify). Returns the expr map.](linalg_show(expr=`expr`, path=`path`, raw=`raw`))*. - -## eye - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | required | Matrix order | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Identity matrix of order n. | - -Use `n` as the inputs for this operation. - -Identity matrix of order n. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Identity matrix of order n.](linalg_eye(n=`n`))*. - -## zeros - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rows | any | required | Input row records to insert or process | -| cols | any | required | Matrix column count | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Zero matrix. | - -Use `rows`, `cols` as the inputs for this operation. - -Zero matrix. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Zero matrix.](linalg_zeros(rows=`rows`, cols=`cols`))*. - -## from_list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | any | required | Structured input supplied to this adapter or resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Dense leaf from nested list. | - -Use `data` as the inputs for this operation. - -Dense leaf from nested list. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Dense leaf from nested list.](linalg_from_list(data=`data`))*. - -## from_formula - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula accepted by the documented parser | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Absorb a `$$` numeric matrix formula (or nested list / dense map) as a dense leaf. | - -Use `formula` as the inputs for this operation. - -Absorb a `$$` numeric matrix formula (or nested list / dense map) as a dense leaf. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Absorb a $$ numeric matrix formula (or nested list / dense map) as a dense leaf.](linalg_from_formula(formula=`formula`))*. - -## explicit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | -| raw | any | False | Whether to keep the unsimplified expression tree while rendering | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Evaluate to dense (default simplify first). | - -Use `expr`, `raw`=False as the inputs for this operation. - -Evaluate to dense (default simplify first). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Evaluate to dense (default simplify first).](linalg_explicit(expr=`expr`, raw=`raw`))*. - -## det - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Determinant. | - -Use `expr` as the inputs for this operation. - -Determinant. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Determinant.](linalg_det(expr=`expr`))*. - -## trace - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Trace. | - -Use `expr` as the inputs for this operation. - -Trace. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Trace.](linalg_trace(expr=`expr`))*. - -## solve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | None | Left matrix or numeric operand | -| b | any | required | Right matrix, right-hand side or numeric operand | -| factor | any | None | Reusable factorization returned by factorize | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Solve `a x = b` (Gaussian elimination), or reuse `factorize kind=lu` via `factor` + `b`. | - -Use `a`=None, `b`, `factor`=None as the inputs for this operation. - -Solve `a x = b` (Gaussian elimination), or reuse `factorize kind=lu` via `factor` + `b`. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Solve a x = b (Gaussian elimination), or reuse factorize kind=lu via factor + b.](linalg_solve(a=`a`, b=`b`, factor=`factor`))*. - -## matmul - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left matrix or numeric operand | -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Dense matrix product → `linalg_dense`. | - -Use `a`, `b` as the inputs for this operation. - -Dense matrix product → `linalg_dense`. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Dense matrix product → linalg_dense.](linalg_matmul(a=`a`, b=`b`))*. - -## kron - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left matrix or numeric operand | -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Lazy Kronecker product (does not expand). | - -Use `a`, `b` as the inputs for this operation. - -Lazy Kronecker product (does not expand). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Lazy Kronecker product (does not expand).](linalg_kron(a=`a`, b=`b`))*. - -## block - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| blocks | any | required | Nested row list of block matrix expressions | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Block matrix from a nested list of expressions. | - -Use `blocks` as the inputs for this operation. - -Block matrix from a nested list of expressions. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Block matrix from a nested list of expressions.](linalg_block(blocks=`blocks`))*. - -## collapse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Block-level collapse (`Block*Block` → block of products). | - -Use `expr` as the inputs for this operation. - -Block-level collapse (`Block*Block` → block of products). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Block-level collapse (Block*Block → block of products).](linalg_collapse(expr=`expr`))*. - -## factorize - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| matrix | any | required | Matrix value supplied for evaluation or factorization | -| kind | any | "lu" | Operation or factorization kind listed in this function's behavior | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Dense factorization → `linalg_factor` (`kind` = `lu` | `qr` | `svd` | `eig` | `chol`). | - -Use `matrix`, `kind`="lu" as the inputs for this operation. - -Dense factorization → `linalg_factor` (`kind` = `lu` | `qr` | `svd` | `eig` | `chol`). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Dense factorization → linalg_factor (kind = lu | qr | svd | eig | chol).](linalg_factorize(matrix=`matrix`, kind=`kind`))*. - -## draw - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| factor | any | required | Reusable factorization returned by factorize | -| kind | any | None | Operation or factorization kind listed in this function's behavior | -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| theme | any | "light" | Rendering theme token supported by the implementation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Structure SVG (`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`). Theme tokens match quantum Q8: `light` | `dark` | `bw`. | - -Use `factor`, `kind`=None, `path`=None, `theme`="light" as the inputs for this operation. - -Structure SVG (`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`). Theme tokens match quantum Q8: `light` | `dark` | `bw`. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Structure SVG (eig | svd | qr | lu | ge | chol | structure | heatmap | hinton). Theme tokens match quantum Q8: light | dark | bw.](linalg_draw(factor=`factor`, kind=`kind`, path=`path`, theme=`theme`))*. - -## lstsq - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left matrix or numeric operand | -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Least squares `min ||a x - b||` (QR if tall, SVD if wide). | - -Use `a`, `b` as the inputs for this operation. - -Least squares `min ||a x - b||` (QR if tall, SVD if wide). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Least squares min ||a x - b|| (QR if tall, SVD if wide).](linalg_lstsq(a=`a`, b=`b`))*. - -## norm - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | -| ord | any | "fro" | Norm order accepted by the native norm implementation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix norm: `fro` | `1` | `inf` | `2`. Complex dense supports `fro` only. | - -Use `expr`, `ord`="fro" as the inputs for this operation. - -Matrix norm: `fro` | `1` | `inf` | `2`. Complex dense supports `fro` only. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Matrix norm: fro | 1 | inf | 2. Complex dense supports fro only.](linalg_norm(expr=`expr`, ord=`ord`))*. - -## cond - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Spectral condition number via SVD (`ord=2`). | - -Use `expr` as the inputs for this operation. - -Spectral condition number via SVD (`ord=2`). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Spectral condition number via SVD (ord=2).](linalg_cond(expr=`expr`))*. - -## rank - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Numerical rank (SVD). | - -Use `expr` as the inputs for this operation. - -Numerical rank (SVD). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Numerical rank (SVD).](linalg_rank(expr=`expr`))*. - -## declare - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | Database table name or form submission table | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Declare several matrix symbols from an `@` record table (`name` / `rows` / `cols`). Returns a map env. | - -Use `table` as the inputs for this operation. - -Declare several matrix symbols from an `@` record table (`name` / `rows` / `cols`). Returns a map env. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Declare several matrix symbols from an @ record table (name / rows / cols). Returns a map env.](linalg_declare(table=`table`, type_tag="matrix"))*. - -## symbol - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | required | Name registered or looked up by this operation | -| rows | any | required | Input row records to insert or process | -| cols | any | required | Matrix column count | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Abstract matrix symbol. Returns a `# matrix` instance (supports `+` / `*` and methods). | - -Use `name`, `rows`, `cols` as the inputs for this operation. - -Abstract matrix symbol. Returns a `# matrix` instance (supports `+` / `*` and methods). - -We **[Load the native plugin required by this operation](ensure_plugin())**. -Return *[Matrix](matrix(name=`name`, rows=`rows`, cols=`cols`))*. - -# matrix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | None | Name registered or looked up by this operation | -| rows | any | None | Input row records to insert or process | -| cols | any | None | Matrix column count | -| data | any | None | Structured input supplied to this adapter or resource | -| formula | any | None | Symbolic formula accepted by the documented parser | -| n | any | None | Matrix order | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix value (`_type=matrix`). Prefer infix `A + B` / `A * B`, or methods `` `A`.T ``. | - -Use `name`=None, `rows`=None, `cols`=None, `data`=None, `formula`=None, `n`=None as the inputs for this operation. - -Matrix value (`_type=matrix`). Prefer infix `A + B` / `A * B`, or methods `` `A`.T ``. - -We **[Load the native plugin required by this operation](ensure_plugin())**. -1. `formula` - Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_from_formula(formula=`formula`))*. -2. `data` - Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_from_list(data=`data`))*. -3. `name` - Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_symbol(name=`name`, rows=`rows`, cols=`cols`))*. -4. `n` - Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_eye(n=`n`))*. -5. `rows` - Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_zeros(rows=`rows`, cols=`cols`))*. -6. * - We **[Print the prepared message](print(text="ext/linalg: matrix needs", name="/", data="/", formula="/", n="/", rows=""))**. - Return *None*. - -## T - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Transpose (method). | - -Transpose (method). - -Return *[Transpose (method).](linalg_transpose(expr=`self`))*. - -## T_ascii - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Transpose then display ASCII (auto-simplified). Handy for lecture identities. | - -Transpose then display ASCII (auto-simplified). Handy for lecture identities. - -We retain **`Pt` = [Transpose then display ASCII (auto-simplified). Handy for lecture identities.](linalg_transpose(expr=`self`))**. -Return *[Transpose then display ASCII (auto-simplified). Handy for lecture identities.](linalg_ascii(expr=`Pt`, raw=False))*. - -## add - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix / expression addition. | - -Use `b` as the inputs for this operation. - -Matrix / expression addition. - -Return *[Matrix / expression addition.](linalg_add(a=`self`, b=`b`))*. - -## sub - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix / expression subtraction. | - -Use `b` as the inputs for this operation. - -Matrix / expression subtraction. - -Return *[Matrix / expression subtraction.](linalg_sub(a=`self`, b=`b`))*. - -## mul - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| b | any | required | Right matrix, right-hand side or numeric operand | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix / expression product. | - -Use `b` as the inputs for this operation. - -Matrix / expression product. - -Return *[Matrix / expression product.](linalg_mul(a=`self`, b=`b`))*. - -## inv - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Inverse. | - -Inverse. - -Return *[Inverse.](linalg_inv(expr=`self`))*. - -## simplify - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Simplify MatExpr. | - -Simplify MatExpr. - -Return *[Simplify MatExpr.](linalg_simplify(expr=`self`))*. - -## ascii - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | ASCII display. | - -ASCII display. - -Return *[ASCII display.](linalg_ascii(expr=`self`, raw=False))*. - -## latex - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | LaTeX display. | - -LaTeX display. - -Return *[LaTeX display.](linalg_latex(expr=`self`, raw=False))*. - -## explicit - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Evaluate to an explicit matrix. | - -Evaluate to an explicit matrix. - -Return *[Evaluate to an explicit matrix.](linalg_explicit(expr=`self`, raw=False))*. - -## det - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Determinant. | - -Determinant. - -Return *[Determinant.](linalg_det(expr=`self`))*. - -## trace - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Trace. | - -Trace. - -Return *[Trace.](linalg_trace(expr=`self`))*. - -## show - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | -| raw | any | False | Whether to keep the unsimplified expression tree while rendering | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Show / export the expression. | - -Use `path`=None, `raw`=False as the inputs for this operation. - -Show / export the expression. - -Return *[Show / export the expression.](linalg_show(expr=`self`, path=`path`, raw=`raw`))*. - -## eye - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | required | Matrix order | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Identity matrix of order n. | - -Use `n` as the inputs for this operation. - -Identity matrix of order n. - -Return *[Identity matrix of order n.](linalg_eye(n=`n`))*. - -## zeros - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rows | any | required | Input row records to insert or process | -| cols | any | required | Matrix column count | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Zero matrix. | - -Use `rows`, `cols` as the inputs for this operation. - -Zero matrix. - -Return *[Zero matrix.](linalg_zeros(rows=`rows`, cols=`cols`))*. - -## from_list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | any | required | Structured input supplied to this adapter or resource | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix from nested list. | - -Use `data` as the inputs for this operation. - -Matrix from nested list. - -Return *[Matrix from nested list.](linalg_from_list(data=`data`))*. - -## from_formula - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula accepted by the documented parser | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matrix from formula text. | - -Use `formula` as the inputs for this operation. - -Matrix from formula text. - -Return *[Matrix from formula text.](linalg_from_formula(formula=`formula`))*. diff --git a/ext/linalg/索引.mq.md b/ext/linalg/索引.mq.md deleted file mode 100755 index c9c78e2..0000000 --- a/ext/linalg/索引.mq.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -markup: occlusion -title: 线性代数工程入口 -import: - 代数: ext/linalg/线性代数.mq.md ---- - -从本入口运行完整矩阵流程,再阅读[中文接口](线性代数.mq.md)中每个工具的契约与说明。 -[英文入口](index.mq.md)与此流程同义,表达式构造、求值、求解与分解复用共用原生实现。 -对象方法必须有真实矩阵接收者;独立函数则明确传入矩阵或表达式。 - -在本源码工作区先用 cargo build -p marqdo_plugin_linalg 构建依赖,再执行: - -```sh -marqdo call ext/linalg/索引.mq.md 求解示例 --effects plugin --json -``` - -本例只做离线计算,不写文件、不连接外部服务。新增能力应在原生 linalg 中实现边界算法, -公开文件补齐中英文契约和错误示例,并验证维度、奇异性及容差。绘图输出是另一种效果, -指定路径时要明确产物归属与清理责任,不把展示字符串当可计算的矩阵数据。 - -## 求解示例 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 原生求解记录;其中 x.data 对应列向量 [[2], [1]] | - -本例求解二乘 x 加 y 等于五、x 加三乘 y 等于五。系数和右端都用原生矩阵公式给出, -先分解一次再求解,不复制另一份矩阵解析或消元程序。分解值只能用于维度兼容的系统。 - -`系数` = -$$ -\begin{bmatrix}2&1\\1&3\end{bmatrix} -$$ - -`右端` = -$$ -\begin{pmatrix}5\\5\end{pmatrix} -$$ - -先**矩阵 = [由系数公式构造矩阵](代数.自公式(公式=`系数`))**, -再**向量 = [由右端公式构造列向量](代数.自公式(公式=`右端`))**。 -接着**分解 = [对系数矩阵进行一次 LU 分解](代数.分解(矩阵=`矩阵`, 类型="lu"))**, -最后返回*[复用分解结果求解本系统](代数.求解(右=`向量`, 分解=`分解`))*。 -调用者应检查实际结果中的数值,不将函数调用成功等同于任意系统都满足精度要求。 diff --git a/ext/linalg/线性代数.mq.md b/ext/linalg/线性代数.mq.md deleted file mode 100755 index 2d674a4..0000000 --- a/ext/linalg/线性代数.mq.md +++ /dev/null @@ -1,833 +0,0 @@ ---- -markup: occlusion -title: ext/linalg/线性代数 -description: 公式优先的线性代数(中文)。矩阵表达式化简与展示;ABI 插件。 -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -公式优先的线性代数(中文)。矩阵表达式化简与展示;ABI 插件。 - -从[求解入口](索引.mq.md)可运行由公式构造矩阵、复用分解并求解的真实示例。本文件是中文数值门面,原生算法位于 marqdo_plugin_linalg。新增操作需说明形状、容差单位、惰性表达式和物化结果的区别;用数值与残差验证算法,不能把非空句柄当成正确结果。保持中英文入口同源,不复制一套矩阵运行时。 - -## 确保插件 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 完成后不返回业务数据;插件缺失会报告原因并结束运行。 | - -加载 ABI v2 `linalg` 插件一次。 - -这里只负责定位并加载现有原生库,不创建矩阵,也不会自动下载或编译插件。缺少插件时结束当前运行,让调用者修复安装路径后重试;不能返回一个伪造的矩阵句柄继续计算。加载成功后返回空值,真实数值结果由后续运算产生。 - -得到**`p` = [定位已安装的原生插件](plugin.native_path(name="linalg"))**。 -1. `p` - 这里**[加载本操作依赖的原生插件](plugin.load(path=`p`))**。 -2. * - 这里**[输出本步已准备的消息](print(text="ext/linalg: 未找到原生 linalg 插件(请 build marqdo_plugin_linalg 或 marqdo ext add linalg)"))**。 - 这里**[按指定退出码结束本次运行](sys.exit(code=1))**。 -完成后返回*None*。 - -## 探测 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 插件探活。 | - -插件探活。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[插件探活。](linalg_ping())*。 - -## 乘 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | any | 必填 | 运算左侧的矩阵或表达式 | -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵乘(惰性;检查形状)。 | - -这里使用`左`、`右`。 - -矩阵乘(惰性;检查形状)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[矩阵乘(惰性;检查形状)。](linalg_mul(a=`左`, b=`右`))*。 - -## 加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | any | 必填 | 运算左侧的矩阵或表达式 | -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵 / 表达式加法。 | - -这里使用`左`、`右`。 - -矩阵 / 表达式加法。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[矩阵 / 表达式加法。](linalg_add(a=`左`, b=`右`))*。 - -## 减 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | any | 必填 | 运算左侧的矩阵或表达式 | -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵 / 表达式减法。 | - -这里使用`左`、`右`。 - -矩阵 / 表达式减法。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[矩阵 / 表达式减法。](linalg_sub(a=`左`, b=`右`))*。 - -## 转置 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。 | - -这里使用`式`。 - -转置。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。](linalg_transpose(expr=`式`))*。 - -## 逆 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 求逆。 | - -这里使用`式`。 - -求逆。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[求逆。](linalg_inv(expr=`式`))*。 - -## 化简 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 应用矩阵表达式重写规则(R1–R5)。 | - -这里使用`式`。 - -应用矩阵表达式重写规则(R1–R5)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[应用矩阵表达式重写规则(R1–R5)。](linalg_simplify(expr=`式`))*。 - -## 文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | -| 原始 | any | False | 渲染时是否保留未化简表达式树 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 展示 ASCII(默认先 化简)。`原始=True` 保留书写树。 | - -这里使用`式`、`原始`=False。 - -展示 ASCII(默认先 化简)。`原始=True` 保留书写树。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[展示 ASCII(默认先 化简)。原始=True 保留书写树。](linalg_ascii(expr=`式`, raw=`原始`))*。 - -## 乳胶 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | -| 原始 | any | False | 渲染时是否保留未化简表达式树 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | LaTeX 展示。 | - -这里使用`式`、`原始`=False。 - -LaTeX 展示。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[LaTeX 展示。](linalg_latex(expr=`式`, raw=`原始`))*。 - -## 形状 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_shape,保留同源能力的返回值和失败语义。 | - -这里使用`式`。 - -形状。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[将当前输入交给 linalg_shape,保留同源能力的返回值和失败语义。](linalg_shape(expr=`式`))*。 - -## 展示 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | -| 路径 | any | None | 授权根目录内的文件路径 | -| 原始 | any | False | 渲染时是否保留未化简表达式树 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 写入公式 SVG(默认化简)。 | - -这里使用`式`、`路径`=None、`原始`=False。 - -写入公式 SVG(默认化简)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[写入公式 SVG(默认化简)。](linalg_show(expr=`式`, path=`路径`, raw=`原始`))*。 - -## 单位 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 阶 | any | 必填 | 方阵阶数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 对比特施加单位门 / 单位矩阵。 | - -这里使用`阶`。 - -对比特施加单位门 / 单位矩阵。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[对比特施加单位门 / 单位矩阵。](linalg_eye(n=`阶`))*。 - -## 零阵 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行 | any | 必填 | 矩阵行数 | -| 列 | any | 必填 | 矩阵列数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 零矩阵。 | - -这里使用`行`、`列`。 - -零矩阵。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[零矩阵。](linalg_zeros(rows=`行`, cols=`列`))*。 - -## 自列表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | any | 必填 | 交给本操作处理的结构化数据 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 由嵌套列表构造矩阵。 | - -这里使用`数据`。 - -由嵌套列表构造矩阵。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[由嵌套列表构造矩阵。](linalg_from_list(data=`数据`))*。 - -## 自公式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 公式 | any | 必填 | 原生矩阵解析器接受的符号公式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 吸收 `$$` 数值矩阵公式为稠密叶。 | - -这里使用`公式`。 - -吸收 `$$` 数值矩阵公式为稠密叶。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[吸收 $$ 数值矩阵公式为稠密叶。](linalg_from_formula(formula=`公式`))*。 - -## 求值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | -| 原始 | any | False | 渲染时是否保留未化简表达式树 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 求成稠密(默认先 化简)。 | - -这里使用`式`、`原始`=False。 - -求成稠密(默认先 化简)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[求成稠密(默认先 化简)。](linalg_explicit(expr=`式`, raw=`原始`))*。 - -## 行列式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。 | - -这里使用`式`。 - -行列式。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。](linalg_det(expr=`式`))*。 - -## 迹 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。 | - -这里使用`式`。 - -迹。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。](linalg_trace(expr=`式`))*。 - -## 求解 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | any | None | 运算左侧的矩阵或表达式 | -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | -| 分解 | any | None | 分解函数返回的可复用分解记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 解 `左 · x = 右`,或复用 `分解`(`kind=lu`)+ `右`。 | - -这里使用`左`=None、`右`、`分解`=None。 - -解 `左 · x = 右`,或复用 `分解`(`kind=lu`)+ `右`。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[解 左 · x = 右,或复用 分解(kind=lu)+ 右。](linalg_solve(a=`左`, b=`右`, factor=`分解`))*。 - -## 稠密乘 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | any | 必填 | 运算左侧的矩阵或表达式 | -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_matmul,保留同源能力的返回值和失败语义。 | - -这里使用`左`、`右`。 - -稠密乘。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[将当前输入交给 linalg_matmul,保留同源能力的返回值和失败语义。](linalg_matmul(a=`左`, b=`右`))*。 - -## 克罗内克 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | any | 必填 | 运算左侧的矩阵或表达式 | -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 惰性 Kronecker 积(默认不展开)。 | - -这里使用`左`、`右`。 - -惰性 Kronecker 积(默认不展开)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[惰性 Kronecker 积(默认不展开)。](linalg_kron(a=`左`, b=`右`))*。 - -## 分块 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 块 | any | 必填 | 按行列排列的分块矩阵表达式列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 由嵌套表达式列表构造分块矩阵。 | - -这里使用`块`。 - -由嵌套表达式列表构造分块矩阵。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[由嵌套表达式列表构造分块矩阵。](linalg_block(blocks=`块`))*。 - -## 分块化简 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 分块级塌缩(`Block*Block` → 块乘加)。 | - -这里使用`式`。 - -分块级塌缩(`Block*Block` → 块乘加)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[分块级塌缩(Block*Block → 块乘加)。](linalg_collapse(expr=`式`))*。 - -## 分解 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 矩阵 | any | 必填 | 本次求值或分解的矩阵值 | -| 类型 | any | "lu" | 本操作说明支持的分解或表示类型 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 稠密分解 → `linalg_factor`(`类型` = `lu` | `qr` | `svd` | `eig` | `chol`)。 | - -这里使用`矩阵`、`类型`="lu"。 - -稠密分解 → `linalg_factor`(`类型` = `lu` | `qr` | `svd` | `eig` | `chol`)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[稠密分解 → linalg_factor(类型 = lu | qr | svd | eig | chol)。](linalg_factorize(matrix=`矩阵`, kind=`类型`))*。 - -## 绘图 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 分解 | any | 必填 | 分解函数返回的可复用分解记录 | -| 类型 | any | None | 本操作说明支持的分解或表示类型 | -| 路径 | any | None | 授权根目录内的文件路径 | -| 主题 | any | "light" | 渲染主题标识 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 结构 SVG(`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`)。主题与 quantum Q8 对齐:`light` | `dark` | `bw`。 | - -这里使用`分解`、`类型`=None、`路径`=None、`主题`="light"。 - -结构 SVG(`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`)。主题与 quantum Q8 对齐:`light` | `dark` | `bw`。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[结构 SVG(eig | svd | qr | lu | ge | chol | structure | heatmap | hinton)。主题与 quantum Q8 对齐:light | dark | bw。](linalg_draw(factor=`分解`, kind=`类型`, path=`路径`, theme=`主题`))*。 - -## 最小二乘 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | any | 必填 | 运算左侧的矩阵或表达式 | -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 最小二乘 `min ||左 · x - 右||`(高瘦用 QR,宽用 SVD)。 | - -这里使用`左`、`右`。 - -最小二乘 `min ||左 · x - 右||`(高瘦用 QR,宽用 SVD)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[最小二乘 min ||左 · x - 右||(高瘦用 QR,宽用 SVD)。](linalg_lstsq(a=`左`, b=`右`))*。 - -## 范数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | -| 范数 | any | "fro" | 范数函数支持的阶数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵范数:`fro` | `1` | `inf` | `2`。复数稠密暂仅 `fro`。 | - -这里使用`式`、`范数`="fro"。 - -矩阵范数:`fro` | `1` | `inf` | `2`。复数稠密暂仅 `fro`。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[矩阵范数:fro | 1 | inf | 2。复数稠密暂仅 fro。](linalg_norm(expr=`式`, ord=`范数`))*。 - -## 条件数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 谱条件数(SVD,`ord=2`)。 | - -这里使用`式`。 - -谱条件数(SVD,`ord=2`)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[谱条件数(SVD,ord=2)。](linalg_cond(expr=`式`))*。 - -## 秩 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 式 | any | 必填 | 本库产生的矩阵表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 数值秩(SVD)。 | - -这里使用`式`。 - -数值秩(SVD)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[数值秩(SVD)。](linalg_rank(expr=`式`))*。 - -## 声明 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 表 | any | 必填 | 可读声明记录表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 用 `@` 记录表一次声明多个符号矩阵(`名` / `行` / `列`)。返回环境 map。 | - -这里使用`表`。 - -用 `@` 记录表一次声明多个符号矩阵(`名` / `行` / `列`)。返回环境 map。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[用 @ 记录表一次声明多个符号矩阵(名 / 行 / 列)。返回环境 map。](linalg_declare(table=`表`, type_tag="矩阵"))*。 - -## 符号 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | any | 必填 | 本操作注册或查找的名称 | -| 行 | any | 必填 | 矩阵行数 | -| 列 | any | 必填 | 矩阵列数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 抽象矩阵符号。返回 `# 矩阵` 实例(可用 `+` / `*` 与方法)。 | - -这里使用`名`、`行`、`列`。 - -抽象矩阵符号。返回 `# 矩阵` 实例(可用 `+` / `*` 与方法)。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -完成后返回*[调用 矩阵](矩阵(名=`名`, 行=`行`, 列=`列`))*。 - -# 矩阵 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | any | None | 本操作注册或查找的名称 | -| 行 | any | None | 矩阵行数 | -| 列 | any | None | 矩阵列数 | -| 数据 | any | None | 交给本操作处理的结构化数据 | -| 公式 | any | None | 原生矩阵解析器接受的符号公式 | -| 阶 | any | None | 方阵阶数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵值(`_type=矩阵`)。优先中缀 `A + B` / `A * B`,或 `` `A`.转置 ``。 | - -这里使用`名`=None、`行`=None、`列`=None、`数据`=None、`公式`=None、`阶`=None。 - -矩阵值(`_type=矩阵`)。优先中缀 `A + B` / `A * B`,或 `` `A`.转置 ``。 - -这里**[加载本操作依赖的原生插件](确保插件())**。 -1. `公式` - 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_from_formula(formula=`公式`))*。 -2. `数据` - 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_from_list(data=`数据`))*。 -3. `名` - 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_symbol(name=`名`, rows=`行`, cols=`列`))*。 -4. `阶` - 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_eye(n=`阶`))*。 -5. `行` - 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_zeros(rows=`行`, cols=`列`))*。 -6. * - 这里**[输出本步已准备的消息](print(text="ext/linalg: 矩阵需要", 名="/", 数据="/", 公式="/", 阶="/", 行=""))**。 - 完成后返回*None*。 - -## 转置 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。 | - -转置。 - -完成后返回*[将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。](linalg_transpose(expr=`self`))*。 - -## 转置文本 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 转置后输出 ASCII(默认化简)。适合讲义恒等式验收。 | - -转置后输出 ASCII(默认化简)。适合讲义恒等式验收。 - -得到**`转` = [转置后输出 ASCII(默认化简)。适合讲义恒等式验收。](linalg_transpose(expr=`self`))**。 -完成后返回*[转置后输出 ASCII(默认化简)。适合讲义恒等式验收。](linalg_ascii(expr=`转`, raw=False))*。 - -## 加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵 / 表达式加法。 | - -这里使用`右`。 - -矩阵 / 表达式加法。 - -完成后返回*[矩阵 / 表达式加法。](linalg_add(a=`self`, b=`右`))*。 - -## 减 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵 / 表达式减法。 | - -这里使用`右`。 - -矩阵 / 表达式减法。 - -完成后返回*[矩阵 / 表达式减法。](linalg_sub(a=`self`, b=`右`))*。 - -## 乘 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 矩阵 / 表达式乘法。 | - -这里使用`右`。 - -矩阵 / 表达式乘法。 - -完成后返回*[矩阵 / 表达式乘法。](linalg_mul(a=`self`, b=`右`))*。 - -## 逆 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 求逆。 | - -求逆。 - -完成后返回*[求逆。](linalg_inv(expr=`self`))*。 - -## 化简 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 化简矩阵表达式。 | - -化简矩阵表达式。 - -完成后返回*[化简矩阵表达式。](linalg_simplify(expr=`self`))*。 - -## 文本 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | ASCII 展示。 | - -ASCII 展示。 - -完成后返回*[ASCII 展示。](linalg_ascii(expr=`self`, raw=False))*。 - -## 乳胶 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | LaTeX 展示。 | - -LaTeX 展示。 - -完成后返回*[LaTeX 展示。](linalg_latex(expr=`self`, raw=False))*。 - -## 求值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 原始 | any | False | 渲染时是否保留未化简表达式树 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 求成显式矩阵。 | - -这里使用`原始`=False。 - -求成显式矩阵。 - -完成后返回*[求成显式矩阵。](linalg_explicit(expr=`self`, raw=`原始`))*。 - -## 行列式 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。 | - -行列式。 - -完成后返回*[将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。](linalg_det(expr=`self`))*。 - -## 迹 - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。 | - -迹。 - -完成后返回*[将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。](linalg_trace(expr=`self`))*。 - -## 展示 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 授权根目录内的文件路径 | -| 原始 | any | False | 渲染时是否保留未化简表达式树 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 展示 / 导出表达式。 | - -这里使用`路径`=None、`原始`=False。 - -展示 / 导出表达式。 - -完成后返回*[展示 / 导出表达式。](linalg_show(expr=`self`, path=`路径`, raw=`原始`))*。 - -## 单位 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 阶 | any | 必填 | 方阵阶数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 对比特施加单位门 / 单位矩阵。 | - -这里使用`阶`。 - -对比特施加单位门 / 单位矩阵。 - -完成后返回*[对比特施加单位门 / 单位矩阵。](linalg_eye(n=`阶`))*。 - -## 零阵 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行 | any | 必填 | 矩阵行数 | -| 列 | any | 必填 | 矩阵列数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 零矩阵。 | - -这里使用`行`、`列`。 - -零矩阵。 - -完成后返回*[零矩阵。](linalg_zeros(rows=`行`, cols=`列`))*。 - -## 自列表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | any | 必填 | 交给本操作处理的结构化数据 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 由嵌套列表构造矩阵。 | - -这里使用`数据`。 - -由嵌套列表构造矩阵。 - -完成后返回*[由嵌套列表构造矩阵。](linalg_from_list(data=`数据`))*。 - -## 自公式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 公式 | any | 必填 | 原生矩阵解析器接受的符号公式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | any | 由公式文本构造矩阵。 | - -这里使用`公式`。 - -由公式文本构造矩阵。 - -完成后返回*[由公式文本构造矩阵。](linalg_from_formula(formula=`公式`))*。 diff --git a/ext/net/http.mq.md b/ext/net/http.mq.md deleted file mode 100755 index bc005ff..0000000 --- a/ext/net/http.mq.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -markup: occlusion -title: ext/net/http -description: HTTP primitives surface for Web Runtime (ADR 0007). Prefer Document/Endpoint Artifacts over raw calls. -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -This file constructs application Result records and binds explicit server redirects; it does not implement an HTTP client. For real HTTP requests, response limits and downloads, import lib/net.mq.md. The [network entry](index.mq.md) distinguishes pure URL transformations from native WebSocket exchanges. Keep these responsibilities explicit when extending the package so a readable tool name never implies a missing capability. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/net: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -## result - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ok | any | required | Whether this application-level operation succeeded | -| value | any | None | Value supplied to this operation; immutable transformations return a new value | -| error | any | None | Structured failure information supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Unified Result map `{ok, value, error}`. | - -Use `ok`, `value`=None, `error`=None as the inputs for this operation. - -Unified Result map `{ok, value, error}`. - -`out` = - -| ok | value | error | -|----|-------|-------| -| `ok` | `value` | `error` | - -Return *out*. - -## redirect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared web application | -| from | text | required | Explicit source route | -| to | text | required | Redirect destination | -| permanent | bool | False | False uses a temporary redirect; True uses the native permanent status | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Updated app with the declared server redirect | - -Use `app`, `from`, `to` and `permanent`=False before web.listen. This is a server route policy owned by the network resource, not a client-side history operation. Keep the returned app because binding produces a new value. Redirecting a legacy entry path can coexist with Document and Endpoint discovery without rebuilding the application through removed configure methods. The native runtime validates declared source paths. No listener starts here, and constructing a redirect does not verify that its destination page exists. - -We **[Load the existing native HTTP runtime](_load())**. -Return *[Bind this declared HTTP redirect](web_app_redirect(app=`app`, from=`from`, to=`to`, permanent=`permanent`))*. diff --git a/ext/net/index.mq.md b/ext/net/index.mq.md deleted file mode 100755 index 9f4f306..0000000 --- a/ext/net/index.mq.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -markup: occlusion -title: Network resources — URL data and WebSocket exchanges -import: - url_api: ext/net/url.mq.md - socket_api: ext/net/websocket.mq.md ---- - -This package provides [URL encoding](url.mq.md), the small [HTTP result constructor](http.mq.md), -and a native [WebSocket request/response resource](websocket.mq.md). For HTTP clients with -status, timeout, response limits and downloads, read the standard library net.mq.md directly. -The HTTP leaf here constructs a result record; its name does not imply an implemented HTTP client. -绑定服务端运输使用 websocket.route;中文入口是[实时绑定](实时.mq.md),它与一次客户端 exchange 的生命周期不同。 - -URL encoding is pure and needs no plugin. This command is ready to run from the repository root: - -```sh -marqdo call ext/net/index.mq.md encode 'text="Marqdo notes/one"' --json -``` - -WebSocket exchanges need the native web plugin and an explicitly chosen server. Build the plugin -with scripts/build-web-plugin.sh, then supply a controlled endpoint to exchange. No example opens -a public socket implicitly. The resource closes after one bounded exchange; it is not a persistent -subscription API. Read the returned ok/error as well as the reply data before using the outcome. - -Develop URL transformations by composing the public standard library; native transport belongs in -the web plugin. Preserve timeout units, byte/reply caps and close behavior. Add controlled local -server tests for transport failures and timeouts instead of treating an empty reply as success. - -## encode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text component to percent-encode; this does not fetch a URL | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Encoded URL component returned by the public encoding helper | - -The input `text` is content for an encoded component, not an already assembled URL to navigate. -Keeping this transformation separate makes it possible to build request data without network -permission. We return *[Percent-encode the selected component](url_api.encode(text=`text`))* -so the caller can place it in the intended path or query according to its own URL structure. - -## exchange - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Explicit ws/wss endpoint controlled by the caller | -| message | text | "" | Single outgoing text message | -| timeout_sec | number | 30 | Positive exchange timeout in seconds | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native exchange result; failures carry ok=false/error instead of an empty successful reply | - -The caller supplies `url`, optionally `message`="" and `timeout_sec`=30. This tool performs a -real exchange, so it needs plugin permission and an available endpoint. The native leaf caps -replies and frame sizes and closes the connection before returning; it does not retry a send. - -We create **socket = [Configure a bounded WebSocket receiver](socket_api.ws(timeout_sec=`timeout_sec`))**, -then return *[Send the message and collect the bounded reply](> `socket`.connect url=`url` message=`message` )*. -Inspect the actual result before deciding whether a follow-up request is appropriate. diff --git a/ext/net/url.mq.md b/ext/net/url.mq.md deleted file mode 100755 index 0d85304..0000000 --- a/ext/net/url.mq.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -markup: occlusion -title: ext/net/url -description: URL helpers (stdlib wrappers). ADR 0007. -import: - net: lib/net.mq.md ---- - -Use this leaf to encode data for a URL component, not to fetch or validate a remote service. The [network entry](index.mq.md) provides a directly runnable encoding example. Whole URLs, path components and query values have different escaping responsibilities; pass the intended component and let the caller assemble the final URL. Prefer composing lib/url.mq.md when adding pure transformations. - -## encode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | any | required | Text supplied to the transformation or adapter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Percent-encode the supplied text using the public standard library URL helper. | - -Use `text` as the inputs for this operation. - -Percent-encode the supplied text using the public standard library URL helper. - -Return *[Url encode](net.url_encode(text=`text`))*. diff --git a/ext/net/websocket.mq.md b/ext/net/websocket.mq.md deleted file mode 100755 index d8790a2..0000000 --- a/ext/net/websocket.mq.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -markup: occlusion -title: ext/net/websocket -description: WebSocket client Resource (ADR 0007). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md ---- - -This resource performs one bounded native WebSocket exchange and closes it. The [network entry](index.mq.md) shows the input contract and the distinction from pure URL encoding. Configure a controlled ws/wss endpoint and inspect ok/error, timeout and reply data before acting. New transport behavior belongs in the web plugin, with local tests for failed connections and oversized replies; this resource is not a persistent subscription service. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/net: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -## route - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared application returned by web.prepare | -| path | text | required | Declared WebSocket path, including optional path captures | -| mode | text | "echo" | echo, drain, broadcast or room | -| room_key | text | "" | Room template required by room mode | -| presence | bool | False | Publish native room presence messages | -| require_auth | any | None | None keeps private broadcast/room defaults; False explicitly opens a local demo | -| on_message | text | "" | Optional declared Marqdo callback member | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Updated app with this explicitly declared WebSocket route | - -Use `app`, `path`, `mode`="echo", `room_key`="", `presence`=False, `require_auth`=None and `on_message`="" to bind a server transport before web.listen. This function belongs to the network resource; it does not change Document layout or start a socket. Retain the returned app because native resource updates produce a new value. Room mode requires a room_key template; captures such as {id} select the room at request time. Broadcast and room routes require login unless the caller explicitly opts out. Public local demos should say why require_auth=False is intentional. Presence and callbacks retain the native transport's bounded message handling; they are not a client subscription object. - -We **[Load the native transport implementation](_load())**. -Return *[Register this declared WebSocket transport](web_app_route_ws(app=`app`, path=`path`, echo=None, mode=`mode`, room_key=`room_key`, on_message=`on_message`, presence=`presence`, require_auth=`require_auth`))*. - - -# ws - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| timeout_sec | any | 30 | Request/response timeout in seconds | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | WebSocket client helper. | - -Use `timeout_sec`=30 as the inputs for this operation. - -WebSocket client helper. - -We **[Load the native plugin required by this operation](_load())**. - -`out` = - -| timeout_sec | _type | -|-------------|-------| -| `timeout_sec` | ws | - -Return *out*. - -## connect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | required | Resource connection URL; scheme selects the documented backend | -| message | any | "" | Outgoing WebSocket or application message | -| headers | any | None | HTTP request header record or None | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply. | - -Use `url`, `message`="", `headers`=None as the inputs for this operation. - -Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply. - -We retain **`timeout` = [Read timeout_sec field](access(`self`, "timeout_sec"))**. -Return *[Single request–response: connect to url, send message, collect up to 256 server text replies (each up to 1 MiB), close](web_ws_connect(url=`url`, message=`message`, headers=`headers`, timeout_sec=`timeout`))*. diff --git a/ext/net/实时.mq.md b/ext/net/实时.mq.md deleted file mode 100755 index 294d43c..0000000 --- a/ext/net/实时.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -title: 服务端 WebSocket 实时资源 -import: - socket: ext/net/websocket.mq.md ---- - -本文件提供 websocket.mq.md 的路由绑定中文入口。客户端持续连接由浏览器标准库负责,服务器只在准备好的应用上声明运输资源。独立的一次连接/响应测试仍使用英文文件的 ws 与 connect,不把两种生命周期混为一谈。 - -## 绑定 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | 必填 | 准备站点返回并保留其他资源的应用 | -| 路径 | text | 必填 | 明确声明的套接字路径,可含路径捕获 | -| 模式 | text | "echo" | echo、drain、broadcast 或 room | -| 房间键 | text | "" | room 模式的房间模板,例如文档路径捕获 | -| 在线通知 | bool | False | 是否发布原生在线人数消息 | -| 需要登录 | any | None | None 保留广播/房间私有默认;False 明确公开 | -| 消息回调 | text | "" | 可选已声明 Marqdo 回调成员 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 附加明确 WebSocket 路由的新应用,尚未监听 | - -使用`应用`、`路径`、`模式`="echo"、`房间键`=""、`在线通知`=False、`需要登录`=None、`消息回调`=""。授权 plugin,在监听前保留返回的新应用。构造不会连接浏览器、修改 Document 布局或创建后台线程。 - -room 模式需要房间键,模板在实际请求中代入路径捕获。广播与房间默认要求登录;本地回显示例显式 False,只用于回环地址的公开演示。隐藏导航不能保护连接,身份策略仍由服务器执行。回调与消息上限沿用原生运输,连接错误不能当作空的成功回复。 - -绑定完成后返回 *[登记同一个应用的实时运输资源](socket.route(app=`应用`, path=`路径`, mode=`模式`, room_key=`房间键`, presence=`在线通知`, require_auth=`需要登录`, on_message=`消息回调`))*。 diff --git a/ext/quantum/_capability/index.mq.md b/ext/quantum/_capability/index.mq.md deleted file mode 100755 index 6829053..0000000 --- a/ext/quantum/_capability/index.mq.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/_capability -description: >- - Quantum ABI load skill. Prefer domain modules; call load when diagnosing plugins. -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -Native capability — diagnose plugin discovery, then return to a domain module. - -This boundary locates and loads the ABI v2 quantum library. Domain tools call -load themselves, so normal experiments do not need a separate setup call. -The Chinese capability file is an equivalent language facade of this boundary. - -```sh -marqdo call ext/quantum/_capability/index.mq.md load --effects plugin --json -``` - -Success returns null. Missing native libraries cause a nonzero exit with an -installation hint; this helper uses sys.exit, so callers must also inspect -process status instead of assuming every failure is a JSON envelope. Install -with marqdo ext add quantum, or build marqdo_plugin_quantum in the source repo. -MARQDO_QUANTUM_PLUGIN may point to a specific shared library for development. - -Only this boundary imports lib/plugin. Do not add plugin loaders or host_* -operations to domain code. If discovery changes, validate both language roots -and tests/call_cli.rs before returning to [circuit](../circuit/index.mq.md). - -## load - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | null after a successful load | - -Locate the ABI v2 quantum shared library through plugin.native_path, then -plugin.load it. If the library is missing, print a short install hint and exit -non-zero so CI and agents fail loudly. After a successful load, later quantum -star names are available in this process. This is the only sanctioned place in -the package that talks to lib/plugin for quantum. Domain skills call load at the -start of each tool that needs the simulator. - -This tool takes no parameters. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="quantum"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. diff --git a/ext/quantum/circuit/index.mq.md b/ext/quantum/circuit/index.mq.md deleted file mode 100755 index df04943..0000000 --- a/ext/quantum/circuit/index.mq.md +++ /dev/null @@ -1,837 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/circuit -description: >- - Quantum circuit skill — wires, step tables, and applying gates. -import: - cap: ext/quantum/_capability/index.mq.md - density: ext/quantum/density/index.mq.md ---- - -Circuit building — start here when you need a reusable quantum program. - -A circuit begins in the all-zero state. Gates return a new circuit value; save -that return value to continue. Qubit zero is the rightmost basis bit. Gate -angles use radians. Width is 1–12 by default; MARQDO_QUANTUM_MAX_QUBITS can raise -or lower the limit, with a hard maximum of 16. State-vector memory grows as 2^n. - -Read → execute → observe - -This complete shell recipe creates a Bell pair and observes it through the -[simulation module](../simulate/index.mq.md). The two nonzero probabilities -should each be 0.5 within floating-point tolerance. Single quotes preserve the -session reference for Marqdo instead of letting the shell expand it. - -```sh -marqdo call ext/quantum/circuit/index.mq.md new qubits=2 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/circuit/index.mq.md hadamard 'circuit=$qc' qubit=0 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/circuit/index.mq.md cnot 'circuit=$qc' control=0 target=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$qc' --effects plugin --session handbook --json -``` - -Which operation belongs here? - -Wires or a declarative steps table: use new; then simulate for results. - -Superposition or basis/phase gates: use hadamard, x, y, z, s, t, i; then simulate.probabilities. - -Continuous control: use rx, ry, rz; then theta is in radians. - -Entangle or route: use cnot, cz, swap; then state.schmidt. - -Compose fragments or custom gates: use append, apply; then gate.custom or gate.named supplies a gate. - -Mark teaching layers or readout: use barrier, measure_mark; then viz.draw_circuit or simulate.run. - -The author object circuit below offers the same operations as methods. Its -simulation, density and drawing methods remain conveniences; their full call -contracts live in the corresponding modules. Do not pass an object method to -call without an explicit receiver; use the free tools above the object. - -Development route - -A new circuit recipe belongs in the [root index](../index.mq.md), composed from -these tools. Add a native gate only when composition and gate.custom cannot -express it: update plugins/quantum/src/sim.rs and src/lib.rs, then add the free -tool and author method here and in the Chinese mirror. Validate both backends -and the existing tests/ext/quantum-steps-smoke.mq.md author example. - -## new - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubits | number | 1 | wire count | -| steps | any | None | optional gate table or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | new circuit handle | - -Use `qubits`=1, `steps`=None as the inputs for this operation. - -Create a state-vector circuit of width `qubits`=1 by default. Optional - -`steps`=None means no preloaded gates; when a table is provided it is parsed -like the author API. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Create a state-vector circuit of width qubits=1 by default. Optional like the author API.](quantum_circuit_new(qubits=`qubits`, steps=`steps`))*. - -## hadamard - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | target wire | -| circuit | any | required | existing circuit | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | updated circuit | - -Use `qubit`=0, `circuit` as the inputs for this operation. - -Apply Hadamard on wire `qubit`=0 of an existing `circuit` by default. Prefer -this when an agent already holds a circuit from new or toget. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply Hadamard on wire qubit=0 of an existing circuit by default. Prefer this when an agent already holds a circuit from new or toget.](quantum_h(circuit=`circuit`, qubit=`qubit`))*. - -## cnot - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | existing circuit | -| control | number | 0 | control wire | -| target | number | 1 | target wire | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | updated circuit | - -Use `circuit`, `control`=0, `target`=1 as the inputs for this operation. - -Controlled-NOT on `circuit` from `control`=0 to `target`=1 by default. Together -with hadamard this prepares a Bell pair on two wires. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Controlled-NOT on circuit from control=0 to target=1 by default. Together with hadamard this prepares a Bell pair on two wires.](quantum_cx(circuit=`circuit`, control=`control`, target=`target`))*. - -## barrier - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | existing circuit | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | circuit with barrier recorded | - -Use `circuit` as the inputs for this operation. - -Insert a visual barrier on `circuit`. The state does not change; drawings show a -separator so lectures can mark logical layers. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Insert a visual barrier on circuit. The state does not change; drawings show a separator so lectures can mark logical layers.](quantum_barrier(circuit=`circuit`))*. - -## measure_mark - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | existing circuit | -| qubits | any | None | wire list or None for all | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | circuit with measure markers | - -Use `circuit`, `qubits`=None as the inputs for this operation. - -Mark computational-basis readout on `circuit` for later simulate.run. This does -not collapse the ideal state used by probabilities. Pass `qubits`=None to mark -every wire. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Mark computational-basis readout on circuit for later simulate](quantum_measure(circuit=`circuit`, qubits=`qubits`))*. - -## x - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `circuit` as the inputs for this operation. - -Apply Pauli X (bit flip) on the chosen wire. Useful for preparing |1⟩ from |0⟩ or sandwiching phase gates. Returns the updated circuit handle for further chaining. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply Pauli X (bit flip) on the chosen wire](quantum_x(circuit=`circuit`, qubit=`qubit`))*. - -## y - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `circuit` as the inputs for this operation. - -Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply Pauli Y on the chosen wire](quantum_y(circuit=`circuit`, qubit=`qubit`))*. - -## z - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `circuit` as the inputs for this operation. - -Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply Pauli Z (phase flip) on the chosen wire](quantum_z(circuit=`circuit`, qubit=`qubit`))*. - -## s - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `circuit` as the inputs for this operation. - -Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply the phase gate S (√Z) on the chosen wire](quantum_s(circuit=`circuit`, qubit=`qubit`))*. - -## t - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `circuit` as the inputs for this operation. - -Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply the phase gate T (π/8) on the chosen wire](quantum_t(circuit=`circuit`, qubit=`qubit`))*. - -## i - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `circuit` as the inputs for this operation. - -Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply the identity on the chosen wire](quantum_i(circuit=`circuit`, qubit=`qubit`))*. - -## rx - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | -| theta | number | required | Required | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `theta`, `circuit` as the inputs for this operation. - -Rotate the chosen wire about the X axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Rotate the chosen wire about the X axis by angle theta in radians](quantum_rx(circuit=`circuit`, qubit=`qubit`, theta=`theta`))*. - -## ry - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | -| theta | number | required | Required | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `theta`, `circuit` as the inputs for this operation. - -Rotate the chosen wire about the Y axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Rotate the chosen wire about the Y axis by angle theta in radians](quantum_ry(circuit=`circuit`, qubit=`qubit`, theta=`theta`))*. - -## rz - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | -| theta | number | required | Required | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `qubit`=0, `theta`, `circuit` as the inputs for this operation. - -Rotate the chosen wire about the Z axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Rotate the chosen wire about the Z axis by angle theta in radians](quantum_rz(circuit=`circuit`, qubit=`qubit`, theta=`theta`))*. - -## cz - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| control | number | 0 | Default 0 | -| target | number | 1 | Default 1 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `control`=0, `target`=1, `circuit` as the inputs for this operation. - -Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply controlled-Z between control and target](quantum_cz(circuit=`circuit`, control=`control`, target=`target`))*. - -## swap - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | number | 0 | Default 0 | -| b | number | 1 | Default 1 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `a`=0, `b`=1, `circuit` as the inputs for this operation. - -Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Exchange the two wires named by a and b](quantum_swap(circuit=`circuit`, a=`a`, b=`b`))*. - -## append - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| op | any | required | Required | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `op`, `circuit` as the inputs for this operation. - -Append another circuit’s operation list, or a gate/qubits record table, onto this circuit. Returns the combined circuit handle so programs can compose fragments. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Append this item to the new list](quantum_append(circuit=`circuit`, op=`op`))*. - -## apply - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| gate | any | required | Required | -| qubits | any | 0 | Default 0 (input) | -| circuit | any | required | Existing circuit; returns a new value | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Updated circuit | - -Use `gate`, `qubits`=0, `circuit` as the inputs for this operation. - -Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining. - -Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list](quantum_apply(circuit=`circuit`, gate=`gate`, qubits=`qubits`))*. - -# circuit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubits | number | 1 | Default 1 | -| steps | any | None | Default None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubits`=1, `steps`=None as the inputs for this operation. - -State-vector circuit on n wires (default all-zero ket). Optional steps= preloads a gate table. Methods append gates and return a fresh handle for chaining. Agents should prefer the ## call tools above; authors use this object for readable method chains in programs. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[State-vector circuit on n wires (default all-zero ket)](quantum_circuit_new(qubits=`qubits`, steps=`steps`))*. - -## h - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0 as the inputs for this operation. - -Apply the Hadamard gate on the chosen wire. This creates equal superposition from computational basis states and is the first step of Bell and GHZ recipes. Returns an updated circuit handle so authors can chain without in-place mutation. - -Return *[Apply the Hadamard gate on the chosen wire](quantum_h(circuit=`self`, qubit=`qubit`))*. - -## x - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0 as the inputs for this operation. - -Apply Pauli X (bit flip) on the chosen wire. Useful for preparing |1⟩ from |0⟩ or sandwiching phase gates. Returns the updated circuit handle for further chaining. - -Return *[Apply Pauli X (bit flip) on the chosen wire](quantum_x(circuit=`self`, qubit=`qubit`))*. - -## y - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0 as the inputs for this operation. - -Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs. - -Return *[Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs.](quantum_y(circuit=`self`, qubit=`qubit`))*. - -## z - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0 as the inputs for this operation. - -Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle. - -Return *[Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle.](quantum_z(circuit=`self`, qubit=`qubit`))*. - -## s - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0 as the inputs for this operation. - -Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. - -Return *[Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits.](quantum_s(circuit=`self`, qubit=`qubit`))*. - -## t - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0 as the inputs for this operation. - -Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. - -Return *[Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits.](quantum_t(circuit=`self`, qubit=`qubit`))*. - -## i - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0 as the inputs for this operation. - -Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle. - -Return *[Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle.](quantum_i(circuit=`self`, qubit=`qubit`))*. - -## rx - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | -| theta | number | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0, `theta` as the inputs for this operation. - -Rotate the chosen wire about the X axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. - -Return *[Rotate the chosen wire about the X axis by angle theta in radians](quantum_rx(circuit=`self`, qubit=`qubit`, theta=`theta`))*. - -## ry - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | -| theta | number | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0, `theta` as the inputs for this operation. - -Rotate the chosen wire about the Y axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. - -Return *[Rotate the chosen wire about the Y axis by angle theta in radians](quantum_ry(circuit=`self`, qubit=`qubit`, theta=`theta`))*. - -## rz - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | Default 0 | -| theta | number | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubit`=0, `theta` as the inputs for this operation. - -Rotate the chosen wire about the Z axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. - -Return *[Rotate the chosen wire about the Z axis by angle theta in radians](quantum_rz(circuit=`self`, qubit=`qubit`, theta=`theta`))*. - -## cx - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| control | number | 0 | Default 0 | -| target | number | 1 | Default 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `control`=0, `target`=1 as the inputs for this operation. - -Apply CNOT from control to target. This is the standard entangling step in Bell and GHZ preparations. Returns the updated circuit handle for chaining. - -Return *[Apply CNOT from control to target. This is the standard entangling step in Bell and GHZ preparations. Returns the updated circuit handle for chaining.](quantum_cx(circuit=`self`, control=`control`, target=`target`))*. - -## cz - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| control | number | 0 | Default 0 | -| target | number | 1 | Default 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `control`=0, `target`=1 as the inputs for this operation. - -Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining. - -Return *[Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining.](quantum_cz(circuit=`self`, control=`control`, target=`target`))*. - -## swap - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | number | 0 | Default 0 | -| b | number | 1 | Default 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `a`=0, `b`=1 as the inputs for this operation. - -Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle. - -Return *[Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle.](quantum_swap(circuit=`self`, a=`a`, b=`b`))*. - -## barrier - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Record a visual barrier only. The ideal state vector is unchanged; use barriers to separate lecture stages when drawing circuit rails. - -Return *[Record a visual barrier only. The ideal state vector is unchanged; use barriers to separate lecture stages when drawing circuit rails.](quantum_barrier(circuit=`self`))*. - -## measure - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubits | any | None | Default None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `qubits`=None as the inputs for this operation. - -Mark computational-basis readout wires for later run sampling. This does not collapse the ideal state used by probabilities. Pass qubits=None to mark every wire. - -Return *[Mark computational-basis readout wires for later run sampling](quantum_measure(circuit=`self`, qubits=`qubits`))*. - -## append - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| op | any | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `op` as the inputs for this operation. - -Append another circuit’s operation list, or a gate/qubits record table, onto this circuit. Returns the combined circuit handle so programs can compose fragments. - -Return *[Append this item to the new list](quantum_append(circuit=`self`, op=`op`))*. - -## apply - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| gate | any | required | Required | -| qubits | any | 0 | Default 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `gate`, `qubits`=0 as the inputs for this operation. - -Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining. - -Return *[Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining.](quantum_apply(circuit=`self`, gate=`gate`, qubits=`qubits`))*. - -## noise - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| kind | any | required | Required | -| p | any | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | New circuit value; keep it to continue | - -Use `kind`, `p` as the inputs for this operation. - -Attach teaching noise of the given kind and strength for run trajectories. Ideal simulate and probabilities paths ignore this channel by design. - -Return *[Attach teaching noise of the given kind and strength for run trajectories. Ideal simulate and probabilities paths ignore this channel by design.](quantum_noise(circuit=`self`, kind=`kind`, p=`p`))*. - -## simulate - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | List of re/im amplitudes | - -Return ideal state-vector amplitudes as re/im pairs for the current circuit. Teaching noise attached to the circuit is ignored on this ideal path. - -Return *[Return ideal state-vector amplitudes as re/im pairs for the current circuit. Teaching noise attached to the circuit is ignored on this ideal path.](quantum_simulate(circuit=`self`))*. - -## state - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_state: qubits, dim, amplitudes | - -Return the ideal state object with the same amplitudes as simulate. Prefer this when later fidelity or density tools expect a state handle rather than raw amplitudes. - -Return *[Return the ideal state object with the same amplitudes as simulate](quantum_state(circuit=`self`))*. - -## probabilities - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Basis label to ideal probability | - -Map basis labels to ideal probabilities. Labels treat qubit 0 as the rightmost bit. Teaching noise is ignored so results match the pure statevector story. - -Return *[Map basis labels to ideal probabilities. Labels treat qubit 0 as the rightmost bit. Teaching noise is ignored so results match the pure statevector story.](quantum_probabilities(circuit=`self`))*. - -## run - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| shots | number | 1024 | Default 1024 | -| seed | number | 1 | Default 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Shot metadata and counts | - -Use `shots`=1024, `seed`=1 as the inputs for this operation. - -Sample computational-basis shots from this circuit. Defaults are shots=1024 and seed=1 for reproducible replays. Applies teaching noise when a noise channel was attached. - -Return *[Sample computational-basis shots from this circuit](quantum_run(circuit=`self`, shots=`shots`, seed=`seed`))*. - -## draw - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Default None | -| kind | any | "circuit" | Default circuit | -| qubit | number | 0 | Default 0 | -| theme | any | "dark" | Default dark | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg with kind and svg | - -Use `path`=None, `kind`="circuit", `qubit`=0, `theme`="dark" as the inputs for this operation. - -Render an SVG figure for circuit rails, probability bars, Bloch spheres, or advanced density kinds. Theme tokens are dark, light, and bw. Optional path writes the file for CLI or view embedding. - -Return *[Render an SVG figure for circuit rails, probability bars, Bloch spheres, or advanced density kinds](quantum_draw_circuit(circuit=`self`, path=`path`, kind=`kind`, qubit=`qubit`, theme=`theme`))*. - -## density - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Density operator handle | - -Build the pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulation of this circuit. Use density-module tools for mixed states and partial traces. - -Return *[Build the pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulation of this circuit. Use density-module tools for mixed states and partial traces.](quantum_density_from_state(state=`self`))*. - -## expect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| obs | any | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | Scalar observation | - -Use `obs` as the inputs for this operation. - -Compute the expectation value of a Pauli string (left end = high bit) or an explicit matrix on this circuit’s ideal density. Teaching noise is ignored. - -Return *[Compute the expectation value of a Pauli string (left end = high bit) or an explicit matrix on this circuit’s ideal density. Teaching noise is ignored.](quantum_density_expect(density=`self`, obs=`obs`))*. - -## schmidt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| cut | number | 1 | Default 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Coefficients, subsystem bases and entropy | - -Use `cut`=1 as the inputs for this operation. - -Perform a bipartite Schmidt decomposition of the ideal state. The cut argument is the number of qubits in subsystem A counted from the low bits. - -Return *[Perform a bipartite Schmidt decomposition of the ideal state. The cut argument is the number of qubits in subsystem A counted from the low bits.](quantum_schmidt(state=`self`, cut=`cut`))*. diff --git a/ext/quantum/density/index.mq.md b/ext/quantum/density/index.mq.md deleted file mode 100755 index 371ef6c..0000000 --- a/ext/quantum/density/index.mq.md +++ /dev/null @@ -1,277 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/density -description: >- - Density-operator skill — mixed states, partial trace, expectations. -import: - cap: ext/quantum/_capability/index.mq.md ---- - -Density operators — inspect a subsystem or a mixed-state matrix. - -Build rho from an ideal circuit/state with from_state, or from a square -Hermitian 2^n matrix with from_matrix. Density operations and Schmidt support -at most six qubits. The matrix constructor checks shape and Hermiticity; it -does not certify positive semidefiniteness or trace one. For physical inputs, -check the trace and eig eigenvalues yourself before interpreting purity. - -An independent mixed-state check - -This one-qubit maximally mixed matrix has trace one, purity 0.5 and Z -expectation zero. The complete example needs no prior circuit or saved handle. -For entanglement, start from a Bell circuit, call from_state, then partial_trace -with keep=[0]; purity of that reduced density is also 0.5. - -```sh -marqdo call ext/quantum/density/index.mq.md from_matrix 'matrix=[[0.5,0],[0,0.5]]' --effects plugin --session handbook --toget rho --json -marqdo call ext/quantum/density/index.mq.md purity 'density=$rho' --effects plugin --session handbook --json -marqdo call ext/quantum/density/index.mq.md expect 'density=$rho' 'obs="Z"' --effects plugin --session handbook --json -marqdo call ext/quantum/density/index.mq.md eig 'density=$rho' --effects plugin --session handbook --json -``` - -partial_trace keeps the listed zero-based wires and discards the others. -Pauli strings put the highest bit on the left; ZZ measures correlation on two -wires. matrix exports nested complex entries, and eig returns eigenvalues and -eigenvectors. Use [viz.draw_density](../viz/index.mq.md) for hinton, city, -density or paulivec plots. from_state ignores attached teaching noise, just -like the ideal simulator; it is not a noisy density evolution engine. - -Development route - -Add mixed-state mathematics to plugins/quantum/src/linalg.rs, export it through -src/lib.rs and update this file plus its Chinese mirror. Keep physical input -validation claims aligned with the constructor. Validate pure-state purity -one, Bell reduced purity one-half and observable expectations against -independent matrices in tests/ext/quantum-linalg-smoke.mq.md. - -## from_state - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| state | any | required | pure state or circuit | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | density handle | - -Use `state` as the inputs for this operation. - -Form rho as the outer product of a pure `state` (or the ideal state of a -circuit). Use this when you trust the pure-state picture and want mixed-state -tools without writing a matrix by hand. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Form rho as the outer product of a pure state (or the ideal state of a circuit)](quantum_density_from_state(state=`state`))*. - -## from_matrix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| matrix | any | required | Hermitian matrix | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | density handle | - -Use `matrix` as the inputs for this operation. - -Build rho from an explicit Hermitian `matrix`. Pair with formula blocks in the -lecture so the matrix on the page is the matrix in the simulator. Size is -limited by the plugin. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Build rho from an explicit Hermitian matrix](quantum_density_from_matrix(matrix=`matrix`))*. - -## purity - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| density | any | required | density operator | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | purity | - -Use `density` as the inputs for this operation. - -Compute the trace of rho squared for `density`. Values near one mean nearly -pure; lower values mean classical mixing or traced-out entanglement. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Compute the trace of rho squared for density. Values near one mean nearly pure; lower values mean classical mixing or traced-out entanglement.](quantum_density_purity(density=`density`))*. - -## partial_trace - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| keep | any | required | qubit index list to keep | -| density | any | required | joint density | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | reduced density | - -Use `keep`, `density` as the inputs for this operation. - -Keep listed qubits in `keep` and trace out the rest of `density`. Indices use -LSB equals zero. The result is generally mixed even when the joint state was -pure. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Keep listed qubits in keep and trace out the rest of density](quantum_density_partial_trace(density=`density`, keep=`keep`))*. - -## expect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| obs | any | required | Pauli string or matrix | -| density | any | required | density operator | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | expectation value | - -Use `obs`, `density` as the inputs for this operation. - -Expectation of observable `obs` on `density`. Pauli strings use left equals -high bit. Pass a matrix when the observable is not a Pauli product. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Expectation of observable obs on density. Pauli strings use left equals high bit. Pass a matrix when the observable is not a Pauli product.](quantum_density_expect(density=`density`, obs=`obs`))*. - -## eig - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| density | any | required | Hermitian density | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | eigenvalues and eigenvectors | - -Use `density` as the inputs for this operation. - -Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a -lecture needs the eigenbasis of rho. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Hermitian spectrum of density as eigenvalues and eigenvectors. Useful when a lecture needs the eigenbasis of rho.](quantum_density_eig(density=`density`))*. - -## matrix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| density | any | required | Density handle / 密度句柄 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Nested complex entries with re and im | - -Use `density` as the inputs for this operation. - -Export the explicit nested complex matrix of `density`. Reading entries does not -change the density operator. Use the exported entries for an independent trace -check or further linear algebra; the caller remains responsible for physicality. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Export the explicit nested complex matrix of density](quantum_density_matrix(density=`density`))*. - -# density - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| state | any | None | Default None | -| matrix | any | None | Default None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Returned value | - -Use `state`=None, `matrix`=None as the inputs for this operation. - -Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=. Density operations support at most six qubits. Pure and mixed states share this object surface for purity, partial trace, and expectation. - -We **[Load the native plugin required by this operation](cap.load())**. -1. `matrix` - Return *[Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=](quantum_density_from_matrix(matrix=`matrix`))*. -2. * - Return *[Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=](quantum_density_from_state(state=`state`))*. - -## matrix - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Nested complex entries with re and im | - -Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package. - -Return *[Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package](quantum_density_matrix(density=`self`))*. - -## purity - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | Scalar observation | - -Compute Tr(ρ²). Values near one mean a pure state; mixed states are strictly less than one. Use this as a quick entanglement or decoherence check after a partial trace. - -Return *[Compute Tr(ρ²)](quantum_density_purity(density=`self`))*. - -## partial_trace - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| keep | any | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Density operator handle | - -Use `keep` as the inputs for this operation. - -Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks. - -Return *[Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks.](quantum_density_partial_trace(density=`self`, keep=`keep`))*. - -## eig - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | eigenvalues and eigenvectors | - -Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors. Handy for lecture plots and for verifying that a constructed rho is physical. - -Return *[Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors](quantum_density_eig(density=`self`))*. - -## expect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| obs | any | required | Required | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | Scalar observation | - -Use `obs` as the inputs for this operation. - -Expectation value of observable obs on this density. obs may be a Pauli string with the left end as the high bit, or an explicit matrix matching the density dimension. - -Return *[Expectation value of observable obs on this density](quantum_density_expect(density=`self`, obs=`obs`))*. - -## draw - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Default None | -| kind | any | "hinton" | Default hinton | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg with kind and svg | - -Use `path`=None, `kind`="hinton" as the inputs for this operation. - -Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density. Optional path writes SVG; kind selects which visual metaphor the lecture uses. - -Return *[Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density](quantum_density_draw(density=`self`, path=`path`, kind=`kind`))*. diff --git a/ext/quantum/gate/index.mq.md b/ext/quantum/gate/index.mq.md deleted file mode 100755 index 0ddbd27..0000000 --- a/ext/quantum/gate/index.mq.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/gate -description: >- - Quantum gate skill — unitaries as formulas, named gates, matrix checks. -import: - cap: ext/quantum/_capability/index.mq.md ---- - -Gates — define the operator before choosing the wires it acts on. - -Use named for I, X, Y, Z, H, S, T, Rx, Ry, Rz, CX, CZ or SWAP. Rotations -require theta in radians. A custom gate is a square 2^k matrix satisfying -U†U = I (construction tolerance 1e-6). Cells may be real numbers or maps with -re and im fields. JSON and a bound Markdown formula reach the same constructor. - -A complete custom-gate experiment - -The matrix below swaps zero and one. matches must return true, and the final -probabilities must put all weight on basis one. This uses the -[circuit module](../circuit/index.mq.md) to apply the operator; constructing a -gate alone never changes a circuit. All references belong to the same session. - -```sh -marqdo call ext/quantum/gate/index.mq.md custom 'matrix=[[0,1],[1,0]]' 'name="X-demo"' --effects plugin --session handbook --toget u --json -marqdo call ext/quantum/gate/index.mq.md matches 'gate=$u' 'matrix=[[0,1],[1,0]]' --effects plugin --session handbook --json -marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/circuit/index.mq.md apply 'circuit=$qc' 'gate=$u' qubits=0 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$qc' --effects plugin --session handbook --json -``` - -Choose hadamard, pauli_x, pauli_z or cnot for a familiar constant; named covers -the other built-ins, custom accepts a formula matrix, matrix exports entries, -and matches checks that the explanation agrees with the implemented operator. -Use [viz.draw_gate](../viz/index.mq.md) for a glyph or matrix heatmap. Prefer -circuit.cnot with explicit control and target for an entangling operation. - -Development route - -For a new user-defined unitary, use custom and an independent expected matrix; -no Rust or ABI change is necessary. For a new built-in, update -plugins/quantum/src/sim.rs::named_gate_matrix and its numerical tests before -exposing it here and in the Chinese mirror. Preserve tests/ext/quantum-custom-gate-smoke.mq.md, -which binds the Hadamard formula directly into the author gate constructor. - -## hadamard - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Hadamard gate handle | - -The Hadamard gate creates equal superposition from computational basis states. -Its matrix in the computational basis is one over square-root two times the -matrix with ones on the first row and one then minus one on the second row. -So H on ket-zero yields an equal plus combination, and H on ket-one yields an -equal minus combination. This tool returns a named gate handle for later apply. - -This tool takes no parameters. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[The Hadamard gate creates equal superposition from computational basis states](quantum_gate_new(name="H", theta=None, matrix=None))*. - -## pauli_x - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Pauli X handle | - -Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and -ket-one. Use it when a lecture needs an explicit NOT on the computational basis. - -This tool takes no parameters. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and ket-one](quantum_gate_new(name="X", theta=None, matrix=None))*. - -## pauli_z - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Pauli Z handle | - -Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone. -Its diagonal matrix is the standard computational-basis Z. - -This tool takes no parameters. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone](quantum_gate_new(name="Z", theta=None, matrix=None))*. - -## cnot - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | CNOT gate handle | - -The controlled-NOT on two qubits flips the target when the control is ket-one. -Wire order and bit-endianness follow the package convention where qubit 0 is the -rightmost label bit. Prefer applying via circuit tools with explicit control and -target indices when building lectures step by step. - -This tool takes no parameters. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[The controlled-NOT on two qubits flips the target when the control is ket-one](quantum_gate_new(name="CX", theta=None, matrix=None))*. - -## custom - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| matrix | any | required | unitary matrix formula or list | -| name | text | "U" | optional label defaulting to U | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | custom gate handle | - -Use `matrix`, `name`="U" as the inputs for this operation. - -Build a gate from an explicit unitary given as `matrix`. Authors usually bind a -formula matrix first, then pass that binding. Optional label `name`="U" marks -drawings when the caller omits a name. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Build a gate from an explicit unitary given as matrix](quantum_gate_new(name=`name`, theta=None, matrix=`matrix`))*. - -## matches - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| gate | any | required | gate handle to test | -| matrix | any | required | expected unitary | -| tol | number | 0.000000001 | absolute tolerance | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | bool | True when matrices match | - -Use `gate`, `matrix`, `tol`=0.000000001 as the inputs for this operation. - -Teaching check: does `gate` match expected `matrix` within absolute tolerance - -`tol`=0.000000001 ? Use after defining a formula so the lecture and the simulator -cannot drift apart. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Teaching check: does gate match expected matrix within absolute tolerance cannot drift apart.](quantum_gate_matches_matrix(gate=`gate`, matrix=`matrix`, tol=`tol`))*. - -## named - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | "H" | Built-in gate name | -| theta | any | None | Rotation angle or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Gate handle for circuit.apply | - -Use `name`="H", `theta`=None as the inputs for this operation. - -Construct built-in `name`="H" with optional `theta`=None . Rx, Ry and Rz require -a numeric angle in radians. The returned gate can be passed to circuit.apply; -creating it never changes a circuit. Supported names are listed above. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Construct built-in name="H" with optional theta=None ](quantum_gate_new(name=`name`, theta=`theta`, matrix=None))*. - -## matrix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| gate | any | required | Gate handle | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Nested complex entries with re and im | - -Use `gate` as the inputs for this operation. - -Export the explicit unitary of `gate`. Each complex entry has re and im fields. -Use this to compare a formula with independent expected entries. Reading a gate -matrix neither modifies its handle nor applies the operator to any circuit. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Export the explicit unitary of gate](quantum_gate_matrix(gate=`gate`))*. - -# gate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | any | None | Default None | -| theta | number | None | Default None | -| matrix | any | None | Default None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Gate handle for circuit.apply | - -Use `name`=None, `theta`=None, `matrix`=None as the inputs for this operation. - -Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence). Custom gates may set name= (default U). Authors and call-style tools share this object surface. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence)](quantum_gate_new(name=`name`, theta=`theta`, matrix=`matrix`))*. - -## matrix - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Nested complex entries with re and im | - -Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula. - -Return *[Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula.](quantum_gate_matrix(gate=`self`))*. - -## matches_matrix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| matrix | any | required | Required | -| tol | any | 0.000000001 | Default 0.000000001 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | bool | Match within absolute tolerance | - -Use `matrix`, `tol`=0.000000001 as the inputs for this operation. - -Check whether this gate matches the given matrix within absolute tolerance tol. Typical after building a custom gate from a Markdown formula fence in a lecture notebook. - -Return *[Check whether this gate matches the given matrix within absolute tolerance tol](quantum_gate_matches_matrix(gate=`self`, matrix=`matrix`, tol=`tol`))*. - -## draw - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Default None | -| kind | any | "gate" | Default gate | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg with kind and svg | - -Use `path`=None, `kind`="gate" as the inputs for this operation. - -Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix). Optional path writes SVG to disk; plots also enter view/CLI through record_plot for the session. - -Return *[Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix)](quantum_gate_draw(gate=`self`, path=`path`, kind=`kind`))*. diff --git a/ext/quantum/index.mq.md b/ext/quantum/index.mq.md deleted file mode 100755 index 5851388..0000000 --- a/ext/quantum/index.mq.md +++ /dev/null @@ -1,290 +0,0 @@ ---- -markup: occlusion -title: ext/quantum -description: Executable quantum handbook and experiment tools. -import: - state: ext/quantum/state/index.mq.md - circuit: ext/quantum/circuit/index.mq.md - simulate: ext/quantum/simulate/index.mq.md - density: ext/quantum/density/index.mq.md ---- - -Quantum handbook — read this index, execute an experiment, then open only the -module responsible for the next question. This is the package's actual program -and developer guide. The callable headings below are the tools; the surrounding -prose explains how and why to use them. No separate skill manifest is required. - -Start with a verifiable result - -These commands are independent and need no session. The Bell probabilities have -00 and 11 near 0.5. bell_analysis adds ZZ correlation near one, reduced purity -near one-half and Schmidt entropy near ln(2). Compare numbers within 1e-9, -rather than comparing a floating-point JSON string with literal 0.5. - -```sh -marqdo call ext/quantum/index.mq.md bell_phi_plus --effects plugin --json -marqdo call ext/quantum/index.mq.md bell_analysis --effects plugin --json -``` - -Choose the next question - -For a circuit to continue editing, call bell_circuit on this file and save its -return with --session and --toget. For a different initial program open -[circuit](circuit/index.mq.md): new, x/y/z/s/t/i, hadamard, rx/ry/rz, cnot/cz/swap, -apply, append, barrier and measure_mark cover construction and composition. - -For a named or formula-defined operator open [gate](gate/index.mq.md). It -constructs gates and exposes matrix comparison. For exact amplitudes, states, -probabilities or noisy shots open [simulate](simulate/index.mq.md). - -For tensor products, fidelity and Schmidt cuts open [state](state/index.mq.md). -For mixed matrices, partial trace, expectations and spectra open -[density](density/index.mq.md). For SVG rails, probabilities, Bloch, qsphere, multibloch, matrix and -density figures open [viz](viz/index.mq.md). Each module starts with a complete -experiment, input/output conventions and a concrete development route. - -Use [the Chinese index](量子/索引.mq.md) for Chinese tool and parameter names. -The two trees share one native plugin and are tested against the same numerical -expectations. [_capability](_capability/index.mq.md) is the plugin diagnostic -boundary, not a prerequisite for every experiment. - -Install and locate the source - -These commands assume the package source tree is visible from the current -working directory. For an installed package replace the first FILE argument by -its actual installed path (by default ~/.marqdo/ext/quantum/index.mq.md). -Imports inside the package resolve through the extension search roots. - -```text -marqdo ext add quantum -marqdo ext list -``` - -For development in this repository, build the local native plugin first. If -several versions are installed, set MARQDO_QUANTUM_PLUGIN to the absolute path -of target/debug/libquantum.so (or the platform's library filename). Never run -ext add with MARQDO_EXT pointing at the repository ext directory: installation -and source editing are different operations. - -```text -source scripts/dev-env.sh -cargo build --locked -p marqdo_plugin_quantum -``` - -What a call means - -The command shape is marqdo call FILE FUNCTION name=value --effects plugin ---json. FUNCTION is the exact callable heading; nested tools use parent.child. -A heading on an author object that reads self is an instance method and needs -an object receiver. Use this package's free tools for command-line work; import -the very same modules when writing an author program. - -Arguments accept numbers, text, True/False/None, JSON lists/maps, or session -references. Protect text literals, JSON and every dollar reference with shell single quotes: -'name="H"' preserves the text quotes for the CLI value parser; -'circuit=$qc' sends a reference to Marqdo. Unquoted circuit=$qc would let the -shell expand an unrelated environment variable first. With --json, inspect both -the process exit status and ok before reading result. A failed call is not a -valid handle, even when stdout contains an error description. - -A complete persistent experiment - -All commands below use session handbook and can be executed in order. A call -stores only its return value under --toget; apply operations preserve the old -value, so save the new circuit after each step. Reading without --toget leaves -the binding unchanged. The final result must be near 0.5: a Bell pair is pure, -but either one-qubit subsystem is maximally mixed. - -```sh -marqdo call ext/quantum/index.mq.md bell_circuit --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$qc' --effects plugin --session handbook --json -marqdo call ext/quantum/density/index.mq.md from_state 'state=$qc' --effects plugin --session handbook --toget rho --json -marqdo call ext/quantum/density/index.mq.md partial_trace 'density=$rho' 'keep=[0]' --effects plugin --session handbook --toget reduced --json -marqdo call ext/quantum/density/index.mq.md purity 'density=$reduced' --effects plugin --session handbook --json -``` - -Session data lives under .marqdo/call-sessions unless MARQDO_CALL_SESSION_DIR -is set. Plugin calls are journaled and replayed across processes. Keep a session -short and use a new session id after changing source or plugin versions; replay -can repeat plugin effects such as plot output. Do not reconstruct a handle by -copying an implementation-specific JSON object into a new session. - -Scientific conventions and limits - -Qubit zero is the least significant, rightmost basis bit; Pauli strings put the -highest bit on the left. Angles are radians. State-vector width defaults to 12, -with an environment-adjustable hard cap of 16. Density and Schmidt stop at six -qubits. Schmidt A owns the low cut bits and entropy is in natural-log nats. - -Exact simulation, probabilities, fidelity and density-from-circuit ignore -teaching noise. Only sampled run uses the attached bitflip, depolarizing or -amplitude_damping channel. Measurement marks choose sampled wires without -collapsing the ideal state. Mixed-matrix construction verifies Hermiticity and -shape, not positivity or trace one. These boundaries determine which scientific -claims an experiment can support; module intros give concrete counterchecks. - -Author a program from the same knowledge - -Save the following as bell.mq.md and run marqdo run bell.mq.md. The steps table -is the circuit specification; frontmatter imports the existing module. The two printed weights should be near 0.5. GFM -record tables begin with @; a comma-separated wire cell names control then target. -A formula can be bound before gate.custom or gate.gate in the same way. - -```marqdo ---- -markup: occlusion -import: - circuit: ext/quantum/circuit/index.mq.md ---- - -# main - -`steps` = - -| @ | gate | qubits | -|---|------|--------| -| 1 | H | 0 | -| 2 | CX | "0,1" | - -**qc = circuit.circuit qubits=2 steps=`steps`** -**p = > `qc`.probabilities** -**p00 = access(p, "00")** -**p11 = access(p, "11")** -> print text=`p00` -> print text=`p11` -``` - -Develop without creating another API - -A new experiment normally belongs in this index as a small orchestration of -existing modules. State its physical question, inputs, expected values and -limitations beside the executable steps, as bell_analysis does below. A new -unitary normally belongs in gate.custom; it needs no new native export. - -A genuinely new primitive belongs in its domain module. Read that module's -development route, add its free tool, preserve the existing author method, and -update the Chinese mirror. Native evolution is in plugins/quantum/src/sim.rs, -algebra in linalg.rs, SVG in draw.rs, and ABI registration in src/lib.rs there. -Keep loading confined to the capability boundary. If adding a new file, update -the package file list in src/ext_cli.rs so installation includes it. - -Use prose declarations for parameter defaults, a parameter contract immediately -after the heading, and a return contract before any executable statement. -Current extract_function_contract reads both only before the first statement; -a return table placed after cap.load is documentation, not an enforced contract. -Use number/text/bool/any from the current type vocabulary; describe handle shape -and origin in prose instead of inventing a type checker. Interleave intent and -operations. Do not pad the narrative ratio with repeated generic sentences. - -Ordinary section titles must stay prose: ## creates an actual callable symbol. -Only executable tools and object methods should appear in the tool tree. For -navigation use source links and the existing knowledge inspect/resolve commands; -stable symbols are compiler output, not a handwritten tool catalog. - -```text -marqdo knowledge ext/quantum --json inspect bell_analysis -marqdo check --narrative-ratio ext/quantum/index.mq.md -cargo test --locked --test quantum_handbook -cargo test --locked --test call_cli quantum_ -cargo test --locked --test gold ext_quantum -- --test-threads=1 -``` - -The handbook test executes the sh blocks and author examples directly from both -language trees, compares independent scientific expectations, and checks both -Tree and Bytecode. An example that cannot be copied and run is a broken public -interface even if the narration ratio is high. Existing quantum golds preserve -noise, formula, SVG and author-object behavior. No network or LLM is needed. -This implements the small call-based core described in next/010–012; richer -self-modifying agents and persistent interactive branches remain future work, -not extra promises of this package. - -Failure recovery - -A missing plugin: inspect _capability, build/install quantum, then retry the -small Bell command. An unknown session binding: keep one session id and rerun -its producer before its consumer. Unexpected ideal results under noise: use run -for noisy samples. A width/shape error: use the limits and matrix conventions -above instead of silently reducing the scientific problem. Never treat an -error envelope as an empty successful result. - -## bell_circuit - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Two-qubit circuit for simulation, density or drawing | - -Prepare a Bell Phi-plus circuit with no arguments, starting from 00. -First create equal superposition on the low wire, then use that wire to -control the other. The resulting amplitudes correlate 00 with 11. -Return the circuit so a caller can apply another gate, attach noise, draw it -or independently test entanglement. Every step keeps the returned new value. - -We retain **`qc` = [New](circuit.new(qubits=2, steps=None))**. - -Make two equal paths on the low wire, then propagate the path label to the other wire. - -We retain **`qc` = [Hadamard](circuit.hadamard(circuit=`qc`, qubit=0))**. -Return *[Cnot](circuit.cnot(circuit=`qc`, control=0, target=1))*. - -## bell_phi_plus - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Basis probabilities; 00 and 11 each near 0.5 | - -This no-argument demonstration reuses the preparation on this page and -returns only ideal probabilities. Expect equal weights on 00 and 11 and zero -elsewhere. Computational-basis correlation alone does not prove entanglement; -use bell_analysis for reduced purity, ZZ expectation and Schmidt evidence. - -We retain **`qc` = [Bell circuit](bell_circuit())**. -Return *[Probabilities](simulate.probabilities(circuit=`qc`))*. - -## bell_analysis - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | probabilities, purity, reduced_purity, zz, schmidt; no file output | - -This no-argument experiment cross-checks the joint system, one subsystem -and their correlation from the same prepared circuit. Both language entries -return the same scientific field names. Callers need no native export names -or persistent session for the intermediate observations. Expect joint purity -one, reduced purity one-half, ZZ one and Schmidt entropy ln(2), within 1e-9. -All paths here describe ideal evolution rather than noisy trajectory averages. - -We retain **`qc` = [Bell circuit](bell_circuit())**. -We retain **`probs` = [Probabilities](simulate.probabilities(circuit=`qc`))**. - -Build the joint density and compute purity. A pure joint state need not -have pure subsystems. Keep only the low wire and test the mixedness that -appears when information about the other wire is discarded. - -We retain **`rho` = [From state](density.from_state(state=`qc`))**. -We retain **`whole` = [Purity](density.purity(density=`rho`))**. - -`kept` = - -| qubit | -|-------| -| 0 | - -We retain **`reduced` = [Partial trace](density.partial_trace(density=`rho`, keep=`kept`))**. -We retain **`local` = [Purity](density.purity(density=`reduced`))**. - -ZZ measures correlation and is not an entanglement witness by itself. -The Schmidt decomposition supplies pure-state coefficients and entropy. -Together these observations distinguish a Bell pure state from a classical -mixture with identical basis probabilities. Keep the measured values in the -return table rather than hiding them behind a pass label with an implicit threshold. - -We retain **`correlation` = [Expect](density.expect(density=`rho`, obs="ZZ"))**. -We retain **`split` = [Schmidt](state.schmidt(state=`qc`, cut=1))**. - -`report` = - -| probabilities | purity | reduced_purity | zz | schmidt | -|---------------|--------|----------------|----|---------| -| `probs` | `whole` | `local` | `correlation` | `split` | - -Return *report*. diff --git a/ext/quantum/simulate/index.mq.md b/ext/quantum/simulate/index.mq.md deleted file mode 100755 index 1f39600..0000000 --- a/ext/quantum/simulate/index.mq.md +++ /dev/null @@ -1,145 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/simulate -description: >- - Quantum simulation skill — amplitudes, probabilities, noisy shots. -import: - cap: ext/quantum/_capability/index.mq.md ---- - -Simulation — choose the observable before choosing the execution path. - -What are the amplitudes? Use simulate (noise: no); returns list of maps with re, im. - -Need a state for tensor/fidelity work? Use state (noise: no); returns quantum_state with qubits, dim, amplitudes. - -What are the exact basis weights? Use probabilities (noise: no); returns basis label → probability. - -What would repeated readout produce? Use run (noise: yes); returns qubits, shots, seed, counts, measure; noise when set. - -Attach one teaching noise channel Use noise (noise: later in run); returns new circuit. - -Noise is bitflip, depolarizing or amplitude_damping, with probability in [0,1]. -It acts after each unitary on that operation's participating wires. Attaching -noise replaces the previous channel; it does not append a gate or change the -ideal state. This is a teaching trajectory model, not a hardware backend. -Measurement marks select sampled wires without collapsing ideal amplitudes. - -A complete noise experiment - -First create a circuit through the [circuit module](../circuit/index.mq.md). -The ideal state after X is one. Full bit-flip noise after X makes every sampled -outcome zero; exact probabilities still describe one. Repeating run with the -same circuit, seed and shots is deterministic for this simulator version. - -```sh -marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/circuit/index.mq.md x 'circuit=$qc' --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/simulate/index.mq.md noise 'circuit=$qc' 'kind="bitflip"' p=1 --effects plugin --session handbook --toget noisy --json -marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$noisy' --effects plugin --session handbook --json -marqdo call ext/quantum/simulate/index.mq.md run 'circuit=$noisy' shots=32 seed=7 --effects plugin --session handbook --json -``` - -Development route - -Put new readouts here rather than duplicating circuit construction. Numerical -evolution and seeded sampling live in plugins/quantum/src/sim.rs; exports live -in src/lib.rs beside it. Preserve ideal/noisy separation in both language trees -and validate tests/ext/quantum-noise-smoke.mq.md plus amplitude-damping golds. -For entanglement go to [state](../state/index.mq.md); for mixed states use -[density](../density/index.mq.md), which currently describes ideal evolution. - -## simulate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | circuit to evolve | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | amplitude list | - -Use `circuit` as the inputs for this operation. - -Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise -channels attached to the circuit are ignored here. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Return ideal state-vector amplitudes for circuit as re/im entries. Noise channels attached to the circuit are ignored here.](quantum_simulate(circuit=`circuit`))*. - -## state - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | circuit to evolve | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | ideal state | - -Use `circuit` as the inputs for this operation. - -Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state -object. Prefer this when later fidelity or density tools expect a state handle. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Same ideal amplitudes as simulate for circuit, packaged as the plugin state object. Prefer this when later fidelity or density tools expect a state handle.](quantum_state(circuit=`circuit`))*. - -## probabilities - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | circuit to read | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | probability map | - -Use `circuit` as the inputs for this operation. - -Map basis label to probability for the ideal state of `circuit`. Labels use -qubit 0 as the rightmost bit. Noise is ignored. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Map basis label to probability for the ideal state of circuit. Labels use qubit 0 as the rightmost bit. Noise is ignored.](quantum_probabilities(circuit=`circuit`))*. - -## run - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | circuit to sample | -| shots | number | 1024 | sample count | -| seed | number | 1 | RNG seed | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | counts or shot result | - -Use `circuit`, `shots`=1024, `seed`=1 as the inputs for this operation. - -Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024 -and `seed`=1 so replays are deterministic. Teaching noise is applied when set. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Sample computational-basis outcomes from circuit. Defaults are shots=1024 and seed=1 so replays are deterministic. Teaching noise is applied when set.](quantum_run(circuit=`circuit`, shots=`shots`, seed=`seed`))*. - -## noise - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| kind | text | required | noise family name | -| p | number | required | strength in the unit interval | -| circuit | any | required | circuit to annotate | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | circuit with noise metadata | - -Use `kind`, `p`, `circuit` as the inputs for this operation. - -Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal -simulate and probability tools ignore it. Keep p small unless demonstrating -decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Attach teaching noise of kind kind with strength p on circuit](quantum_noise(circuit=`circuit`, kind=`kind`, p=`p`))*. diff --git a/ext/quantum/state/index.mq.md b/ext/quantum/state/index.mq.md deleted file mode 100755 index ea22d02..0000000 --- a/ext/quantum/state/index.mq.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/state -description: >- - Quantum state skill — amplitudes, Kronecker products, fidelity, Schmidt. -import: - cap: ext/quantum/_capability/index.mq.md ---- - -Pure states — compare, combine or partition a quantum state. - -Obtain a state with simulate.state. A state is a map with qubits, dim and a -list of amplitudes, each carrying re and im. A raw amplitude list from -simulate.simulate is not a state handle. fidelity and schmidt also accept a -circuit and evolve its ideal state. kron requires two state handles for the -state-vector branch; convert circuits with simulate.state first. - -A self-contained tensor experiment - -Two zero states make a two-qubit zero state. Its fidelity with itself is one. -The first factor is the high-bit subsystem of the tensor product; the second -factor occupies the low bits. For Schmidt, cut counts the low bits in A. - -```sh -marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/simulate/index.mq.md state 'circuit=$qc' --effects plugin --session handbook --toget psi --json -marqdo call ext/quantum/state/index.mq.md kron 'a=$psi' 'b=$psi' --effects plugin --session handbook --toget product --json -marqdo call ext/quantum/state/index.mq.md fidelity 'a=$product' 'b=$product' --effects plugin --session handbook --json -marqdo call ext/quantum/state/index.mq.md schmidt 'state=$product' cut=1 --effects plugin --session handbook --json -``` - -fidelity is squared absolute overlap of equal-size pure states. schmidt returns -coeffs, ua, ub, entropy, cut and qubits. Entropy uses natural logarithms (nats); -a Bell pair has two coefficients near 1/√2 and entropy ln(2). Schmidt currently -shares the density solver's six-qubit limit and requires 0 < cut < qubits. -kron also accepts matrix factors and returns a matrix-bearing handle; this is -an operator product, not an automatic conversion into a normalized pure state. - -Development route - -Keep pure-state algebra here and mixed-state operations in -[density](../density/index.mq.md). Mathematical implementations and independent -numerical tests belong in plugins/quantum/src/linalg.rs, with exports in -src/lib.rs. Add both language contracts and preserve tests/ext/quantum-linalg-smoke.mq.md. -Use known orthogonal/product/entangled states as checks instead of comparing a -new implementation only with itself. Draw a single wire through -[viz.draw_bloch](../viz/index.mq.md) using its source circuit. - -## kron - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | left factor state or matrix | -| b | any | required | right factor state or matrix | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | tensor product | - -Use `a`, `b` as the inputs for this operation. - -The Kronecker product of `a` and `b` builds a larger space from two smaller -ones. For state vectors this writes product states; for matrices it enlarges -operators. - -Pass handles the plugin already understands. For a pure-state product, convert circuits with simulate.state first. Matrix -factors take the operator branch; raw amplitude lists are not accepted as states. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[The Kronecker product of a and b builds a larger space from two smaller ones](quantum_kron(a=`a`, b=`b`))*. - -## fidelity - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | first pure state or circuit | -| b | any | required | second pure state or circuit | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | fidelity in the unit interval | - -Use `a`, `b` as the inputs for this operation. - -Pure-state fidelity between `a` and `b` is the squared absolute overlap. It is -one when the states coincide and zero when they are orthogonal. You may pass a -circuit handle; the plugin uses the ideal simulated state. Teaching noise is -ignored. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Pure-state fidelity between a and b is the squared absolute overlap](quantum_fidelity(a=`a`, b=`b`))*. - -## schmidt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| state | any | required | pure state or circuit | -| cut | number | 1 | qubits in subsystem A low bits | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | singular values and factors | - -Use `state`, `cut`=1 as the inputs for this operation. - -Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest - -`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show -entanglement across the bipartition. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Schmidt decomposition of state across a cut. Subsystem A owns the lowest entanglement across the bipartition.](quantum_schmidt(state=`state`, cut=`cut`))*. diff --git a/ext/quantum/viz/index.mq.md b/ext/quantum/viz/index.mq.md deleted file mode 100755 index 6e65ec9..0000000 --- a/ext/quantum/viz/index.mq.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/viz -description: >- - Quantum visualization skill — circuit rails, probabilities, Bloch, density plots. -import: - cap: ext/quantum/_capability/index.mq.md ---- - -Visualization — turn a scientific result into an inspectable SVG. - -From circuit, use draw_circuit for gate rails. - -From circuit, use draw_probs for ideal probability bars. - -From circuit, use draw_bloch for one wire's reduced Bloch vector. - -From density, use draw_density for hinton, city, density, paulivec. - -From gate, use draw_gate for gate glyph or matrix heatmap. - -From circuit, use draw_state for qsphere or multibloch. - -Circuit figures accept dark, light and bw themes. Gate and density drawing -have no theme parameter on the current public API. Every tool returns a -quantum_svg map including svg and kind. Under call, use path=None to return -and record SVG; --effects plugin permits loading and drawing but the current -call host denies filesystem writes. To save a file, draw in an author program -executed with marqdo run. - -A complete drawing experiment - -Create the circuit first instead of assuming a handle already exists. The -probability result's svg field must contain an SVG document and kind must be -probs; the next results are qsphere and multibloch. Omitting path means None. -To save a file, append the following line to the root index's author example -before running it: - -```text -**img = > `qc`.draw path="bell.svg"** -``` - -Relative paths resolve against the source document's directory. A call with a nonempty path fails under the current host policy. - -```sh -marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/circuit/index.mq.md hadamard 'circuit=$qc' --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/viz/index.mq.md draw_probs 'circuit=$qc' 'theme="light"' --effects plugin --session handbook --json -marqdo call ext/quantum/viz/index.mq.md draw_state 'circuit=$qc' path=None --effects plugin --session handbook --json -marqdo call ext/quantum/viz/index.mq.md draw_state 'circuit=$qc' 'kind="multibloch"' path=None --effects plugin --session handbook --json -``` - -Development route - -Rendering belongs in plugins/quantum/src/draw.rs and the record_plot bridge -in src/lib.rs. Add a named choice to this page and its -Chinese mirror without mixing filesystem work into circuit algebra. Verify SVG -structure and numerical labels, not a screenshot alone. Preserve - tests/ext/quantum-draw-smoke.mq.md and quantum-viz-advanced-smoke.mq.md. -For input preparation follow [circuit](../circuit/index.mq.md), -[gate](../gate/index.mq.md) or [density](../density/index.mq.md). - -## draw_circuit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | circuit to render | -| theme | text | "dark" | dark light or bw | -| path | any | None | optional output path or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | drawing result | - -Use `circuit`, `theme`="dark", `path`=None as the inputs for this operation. - -Render `circuit` as gate rails and barriers. Choose `theme`="dark" by default; -light and bw preserve the same geometry. Optional `path`=None returns SVG -without a file. A nonempty path is available to author programs under run. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Render circuit as gate rails and barriers](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="circuit", qubit=0, theme=`theme`))*. - -## draw_probs - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | circuit to render | -| theme | text | "dark" | dark light or bw | -| path | any | None | optional output path or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | drawing result | - -Use `circuit`, `theme`="dark", `path`=None as the inputs for this operation. - -Plot ideal basis probabilities of `circuit`. Default `theme`="dark" supports -light and bw alternatives. Optional `path`=None returns SVG without a file. -The bars ignore teaching noise, just like simulate.probabilities. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Plot ideal basis probabilities of circuit](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="probs", qubit=0, theme=`theme`))*. - -## draw_bloch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| qubit | number | 0 | which wire | -| circuit | any | required | circuit source | -| theme | text | "dark" | dark light or bw | -| path | any | None | optional output path or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | drawing result | - -Use `qubit`=0, `circuit`, `theme`="dark", `path`=None as the inputs for this operation. - -Show the reduced Bloch sphere of wire `qubit`=0 from `circuit`. Default - -`theme`="dark"; optional `path`=None returns SVG without a file. A multi-qubit -circuit still produces one reduced wire picture, not a joint-state sphere. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Show the reduced Bloch sphere of wire qubit=0 from circuit. Default circuit still produces one reduced wire picture, not a joint-state sphere.](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="bloch", qubit=`qubit`, theme=`theme`))*. - -## draw_density - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| density | any | required | density operator | -| kind | text | "hinton" | hinton city density or paulivec | -| path | any | None | optional output path or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | drawing result | - -Use `density`, `kind`="hinton", `path`=None as the inputs for this operation. - -Plot `density` using `kind`="hinton" by default. Alternatives are city, -density and paulivec. Optional `path`=None returns SVG without a file. -Use the density module to construct the mixed-state input before drawing. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Plot density using kind="hinton" by default](quantum_density_draw(density=`density`, path=`path`, kind=`kind`))*. - -## draw_gate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| gate | any | required | gate handle | -| kind | text | "gate" | gate or matrix | -| path | any | None | optional output path or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | drawing result | - -Use `gate`, `kind`="gate", `path`=None as the inputs for this operation. - -Plot `gate` using `kind`="gate" by default. Choose matrix for a complex-entry -heatmap. Optional `path`=None returns SVG without a file. This observes the -operator rather than applying it or changing any circuit. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Plot gate using kind="gate" by default](quantum_gate_draw(gate=`gate`, path=`path`, kind=`kind`))*. - -## draw_state - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| circuit | any | required | Circuit evolved ideally | -| kind | text | "qsphere" | qsphere or multibloch | -| path | any | None | SVG output path or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg with kind and svg | - -Use `circuit`, `kind`="qsphere", `path`=None as the inputs for this operation. - -Observe the ideal state of `circuit` as a basis-amplitude/phase sphere or one -reduced Bloch sphere per wire. Default `kind`="qsphere"; use multibloch for the -per-wire picture. Default `path`=None avoids explicit file output. A set of -local Bloch vectors alone cannot certify joint entanglement. Both advanced -figures currently use fixed styling; theme support remains Q8c work and is -not offered as a nonfunctional parameter here. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Observe the ideal state of circuit as a basis-amplitude/phase sphere or one reduced Bloch sphere per wire](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind=`kind`, qubit=0, theme="dark"))*. diff --git a/ext/quantum/量子/可视化/索引.mq.md b/ext/quantum/量子/可视化/索引.mq.md deleted file mode 100755 index 3d78f87..0000000 --- a/ext/quantum/量子/可视化/索引.mq.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子/可视化 -description: 量子可视化 skill — 电路轨、概率条、布洛赫、密度图。 -import: - 能力: ext/quantum/量子/能力/索引.mq.md ---- - -可视化:把科学结果变成可检查的 SVG。 - -输入为电路时,用画电路绘制门轨线。 - -输入为电路时,用画概率绘制理想概率条。 - -输入为电路时,用画布洛赫绘制单线约化布洛赫矢量。 - -输入为密度时,用画密度绘制hinton、city、density、paulivec。 - -输入为门时,用画门绘制 gate 门符号或 matrix 热图。 - -输入为电路时,用画态绘制 qsphere 或 multibloch。 - -电路图支持 dark、light、bw;当前门和密度绘图没有主题参数。 -结果为含 svg、kind 的 quantum_svg 映射。命令行 call 使用 路径=None,只返回并记录 -SVG;--effects plugin 允许加载与绘图,但当前 call 宿主禁止文件写入。 -需要落盘时,在作者程序中使用绘图方法,并通过 marqdo run 执行。 - -完整的绘图实验 - -先创建电路,不假设已经存在句柄。画概率的 svg 必须包含 SVG 文档,kind 为 probs; -后两步分别得到 qsphere、multibloch。省略路径等同于 None。 -要保存图片,在根索引的作者程序中追加以下行,再运行该程序: - -```text -**img = > `qc`.绘图 路径="bell.svg"** -``` - -相对路径按源文档目录解析,不一定是 shell 工作目录。 - -```sh -marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 '电路=$qc' --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/可视化/索引.mq.md 画概率 '电路=$qc' '主题="light"' --effects plugin --session handbook --json -marqdo call ext/quantum/量子/可视化/索引.mq.md 画态 '电路=$qc' 路径=None --effects plugin --session handbook --json -marqdo call ext/quantum/量子/可视化/索引.mq.md 画态 '电路=$qc' '种类="multibloch"' 路径=None --effects plugin --session handbook --json -``` - -开发路线 - -渲染实现位于 plugins/quantum/src/draw.rs 和 src/lib.rs 中的 -record_plot 桥接。新增图类时同步本页和英文入口,别把文件系统操作混入电路代数。 -核对 SVG 结构及数值标签,截图不能代替数值校验。保留 - tests/ext/quantum-draw-smoke.mq.md 与 quantum-viz-advanced-smoke.mq.md。 -输入准备见[电路](../电路/索引.mq.md)、[门](../门/索引.mq.md)、[密度](../密度/索引.mq.md)。 - -## 画电路 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 调用方提供的电路 | -| 主题 | text | "dark" | dark light 或 bw | -| 路径 | any | None | 可选输出路径或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 绘图结果 | - -这里使用`电路`、`主题`="dark"、`路径`=None。 - -把 `电路` 的门和屏障画成轨线。默认 `主题`="dark",也可选择 light 或 bw。 -可选 `路径`=None 只返回 SVG,不写文件;非空路径供 run 下的作者程序使用。 -主题选择只改变配色,不改变线路几何与计算含义。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[把 电路 的门和屏障画成轨线。默认 主题="dark",也可选择 light 或 bw。 可选 路径=None 只返回 SVG,不写文件;非空路径供 run 下的作者程序使用。 主题选择只改变配色,不改变线路几何与计算含义。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="circuit", qubit=0, theme=`主题`))*。 - -## 画概率 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 调用方提供的电路 | -| 主题 | text | "dark" | dark light 或 bw | -| 路径 | any | None | 可选路径或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 绘图结果 | - -这里使用`电路`、`主题`="dark"、`路径`=None。 - -绘制 `电路` 的理想基矢概率条。默认 `主题`="dark",可改为 light 或 bw。 -可选 `路径`=None 只返回 SVG,不写文件。图中权重与模拟模块的理想概率一致, -忽略已附加的教学噪声,不能用它替代含噪采样结果。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[绘制 电路 的理想基矢概率条。默认 主题="dark",可改为 light 或 bw。 可选 路径=None 只返回 SVG,不写文件。图中权重与模拟模块的理想概率一致, 忽略已附加的教学噪声,不能用它替代含噪采样结果。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="probs", qubit=0, theme=`主题`))*。 - -## 画布洛赫 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 调用方提供的电路 | -| 比特 | number | 0 | 哪一根线 | -| 主题 | text | "dark" | dark light 或 bw | -| 路径 | any | None | 可选路径或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 绘图结果 | - -这里使用`电路`、`比特`=0、`主题`="dark"、`路径`=None。 - -绘制 `电路` 上 `比特`=0 的约化布洛赫球。默认 `主题`="dark"。 -可选 `路径`=None 只返回 SVG,不写文件。多比特线路也只显示所选一条线的约化态, -不能把这张图解释为整个多比特纯态的完整表示。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[绘制 电路 上 比特=0 的约化布洛赫球。默认 主题="dark"。 可选 路径=None 只返回 SVG,不写文件。多比特线路也只显示所选一条线的约化态, 不能把这张图解释为整个多比特纯态的完整表示。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="bloch", qubit=`比特`, theme=`主题`))*。 - -## 画密度 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 密度 | any | 必填 | 密度算符 | -| 种类 | text | "hinton" | hinton city density 或 paulivec | -| 路径 | any | None | 可选路径或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 绘图结果 | - -这里使用`密度`、`种类`="hinton"、`路径`=None。 - -绘制 `密度`,默认 `种类`="hinton",也可选 city、density 或 paulivec。 -可选 `路径`=None 只返回 SVG,不写文件。先在密度模块构造或约化输入, -再按需要选择图类,本操作不改变密度矩阵或补做物理性认证。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[绘制 密度,默认 种类="hinton",也可选 city、density 或 paulivec。 可选 路径=None 只返回 SVG,不写文件。先在密度模块构造或约化输入, 再按需要选择图类,本操作不改变密度矩阵或补做物理性认证。](quantum_density_draw(density=`密度`, path=`路径`, kind=`种类`))*。 - -## 画门 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 门 | any | 必填 | 门句柄 | -| 种类 | text | "gate" | gate 或 matrix | -| 路径 | any | None | 可选路径或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 绘图结果 | - -这里使用`门`、`种类`="gate"、`路径`=None。 - -绘制 `门`,默认 `种类`="gate",选择 matrix 可观察复数矩阵热图。 -可选 `路径`=None 只返回 SVG,不写文件。图形用于观察算符, -不会把门作用到任何电路,也不会改变算符的数值条目。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[绘制 门,默认 种类="gate",选择 matrix 可观察复数矩阵热图。 可选 路径=None 只返回 SVG,不写文件。图形用于观察算符, 不会把门作用到任何电路,也不会改变算符的数值条目。](quantum_gate_draw(gate=`门`, path=`路径`, kind=`种类`))*。 - -## 画态 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 源电路,作理想演化 | -| 种类 | text | "qsphere" | qsphere 或 multibloch | -| 路径 | any | None | SVG 输出路径或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg,含 kind 和 svg | - -这里使用`电路`、`种类`="qsphere"、`路径`=None。 - -从 `电路` 观察整体纯态的振幅/相位球,或每条线的约化布洛赫球。 -默认 `种类`="qsphere",可改为 multibloch;默认 `路径`=None,不显式落盘。 -qsphere 展示基矢振幅与相位,multibloch 展示各线约化态,不能由单线球图独自证明纠缠。 -这两类高级态图当前使用固定配色,主题换肤仍属 Q8c 规划,不暴露无效主题参数。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[从 电路 观察整体纯态的振幅/相位球,或每条线的约化布洛赫球。 默认 种类="qsphere",可改为 multibloch;默认 路径=None,不显式落盘。 qsphere 展示基矢振幅与相位,multibloch 展示各线约化态,不能由单线球图独自证明纠缠。 这两类高级态图当前使用固定配色,主题换肤仍属 Q8c 规划,不暴露无效主题参数。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind=`种类`, qubit=0, theme="dark"))*。 diff --git a/ext/quantum/量子/密度/索引.mq.md b/ext/quantum/量子/密度/索引.mq.md deleted file mode 100755 index 84590e8..0000000 --- a/ext/quantum/量子/密度/索引.mq.md +++ /dev/null @@ -1,262 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子/密度 -description: 密度算符 skill — 混合态、部分迹、期望值。 -import: - 能力: ext/quantum/量子/能力/索引.mq.md ---- - -密度算符:观察子系统或显式混合态矩阵。 - -从态工具将理想电路或纯态转成密度;从矩阵接受 2^n 阶厄米方阵。密度操作与施密特 -最多支持六比特。矩阵构造器只检查形状和厄米性,不保证半正定或迹为 1。 -解释物理纯度前,应核对迹并用本征工具检查本征值。 - -独立的混合态校验 - -以下最大混合单比特矩阵迹为 1、纯度为 0.5、Z 期望为 0,无需已有电路或会话。 -研究纠缠时,从贝尔电路经过从态,再以 保留=[0] 求部分迹,约化纯度也应为 0.5。 - -```sh -marqdo call ext/quantum/量子/密度/索引.mq.md 从矩阵 '矩阵=[[0.5,0],[0,0.5]]' --effects plugin --session handbook --toget rho --json -marqdo call ext/quantum/量子/密度/索引.mq.md 纯度 '密度=$rho' --effects plugin --session handbook --json -marqdo call ext/quantum/量子/密度/索引.mq.md 期望 '密度=$rho' '可观测量="Z"' --effects plugin --session handbook --json -marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effects plugin --session handbook --json -``` - -部分迹保留列表指定的零起始比特并消去其余。泡利串左端表示高位,ZZ 表示两线关联。 -矩阵工具导出复数嵌套条目,本征返回 eigenvalues 与 eigenvectors。 -[可视化](../可视化/索引.mq.md)画密度支持 hinton、city、density、paulivec。 -从态与理想模拟一样忽略已附加教学噪声,不应当作含噪密度演化。 - -开发路线 - -新增混合态数学放入 plugins/quantum/src/linalg.rs,通过同目录 src/lib.rs 导出, -同步本页与英文镜像。构造器描述必须与真实校验能力相符。用纯态纯度 1、贝尔约化 -纯度 0.5、独立矩阵的期望检验 tests/ext/quantum-linalg-smoke.mq.md。 - -## 从态 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 态 | any | 必填 | 纯态或电路 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 密度句柄 | - -这里使用`态`。 - -由纯态或电路句柄 `态` 的理想态构造 rho。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[由纯态或电路句柄 态 的理想态构造 rho。](quantum_density_from_state(state=`态`))*。 - -## 从矩阵 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 矩阵 | any | 必填 | 厄米矩阵 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 密度句柄 | - -这里使用`矩阵`。 - -由显式厄米 `矩阵` 构造 rho。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[由显式厄米 矩阵 构造 rho。](quantum_density_from_matrix(matrix=`矩阵`))*。 - -## 纯度 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 密度 | any | 必填 | 密度算符 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 纯度 | - -这里使用`密度`。 - -计算 `密度` 的 Tr(rho^2)。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[计算 密度 的 Tr(rho^2)。](quantum_density_purity(density=`密度`))*。 - -## 部分迹 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 密度 | any | 必填 | 联合密度 | -| 保留 | any | 必填 | 保留的比特下标列表 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 约化密度 | - -这里使用`密度`、`保留`。 - -对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对联合密度 密度 保留 保留 所列比特,对其余求迹。](quantum_density_partial_trace(density=`密度`, keep=`保留`))*。 - -## 期望 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 密度 | any | 必填 | 密度算符 | -| 可观测量 | any | 必填 | 泡利串或矩阵 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 期望值 | - -这里使用`密度`、`可观测量`。 - -将当前输入交给 quantum_density_expect,保留同源能力的返回值和失败语义。 - -`密度` 上可观测量 `可观测量` 的期望值。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[将当前输入交给 quantum_density_expect,保留同源能力的返回值和失败语义。](quantum_density_expect(density=`密度`, obs=`可观测量`))*。 - -## 本征 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 密度 | any | 必填 | 密度算符 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 本征值与本征矢 | - -这里使用`密度`。 - -将当前输入交给 quantum_density_eig,保留同源能力的返回值和失败语义。 - -`密度` 的厄米谱。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[将当前输入交给 quantum_density_eig,保留同源能力的返回值和失败语义。](quantum_density_eig(density=`密度`))*。 - -## 矩阵 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 密度 | any | 必填 | Density handle / 密度句柄 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 复数矩阵条目,每项含 re 与 im | - -这里使用`密度`。 - -导出 `密度` 的显式复数嵌套矩阵。观察条目不会改变密度算符, -可用于独立计算迹或交给线性代数模块核对;物理性校验仍由调用者负责。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[导出 密度 的显式复数嵌套矩阵。观察条目不会改变密度算符, 可用于独立计算迹或交给线性代数模块核对;物理性校验仍由调用者负责。](quantum_density_matrix(density=`密度`))*。 - -# 密度 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 态 | any | None | 默认 None | -| 矩阵 | any | None | 默认 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 返回结果 | - -这里使用`态`=None、`矩阵`=None。 - -由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。 - -这里**[调用 加载](能力.加载())**。 -1. `矩阵` - 完成后返回*[由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。](quantum_density_from_matrix(matrix=`矩阵`))*。 -2. * - 完成后返回*[由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。](quantum_density_from_state(state=`态`))*。 - -## 矩阵 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 复数矩阵条目,每项含 re 与 im | - -返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。 - -完成后返回*[返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。](quantum_density_matrix(density=`self`))*。 - -## 纯度 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 标量观察值 | - -计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。 - -完成后返回*[计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。](quantum_density_purity(density=`self`))*。 - -## 部分迹 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 保留 | any | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 密度算符句柄 | - -这里使用`保留`。 - -保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。 - -完成后返回*[保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。](quantum_density_partial_trace(density=`self`, keep=`保留`))*。 - -## 本征 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | eigenvalues 与 eigenvectors | - -计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。 - -完成后返回*[计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。](quantum_density_eig(density=`self`))*。 - -## 期望 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 可观测量 | any | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 标量观察值 | - -这里使用`可观测量`。 - -可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。 - -完成后返回*[可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。](quantum_density_expect(density=`self`, obs=`可观测量`))*。 - -## 绘图 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 默认 None | -| 种类 | any | "hinton" | 默认 hinton | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg,含 kind 与 svg | - -这里使用`路径`=None、`种类`="hinton"。 - -绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。 - -完成后返回*[绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。](quantum_density_draw(density=`self`, path=`路径`, kind=`种类`))*。 diff --git a/ext/quantum/量子/态/索引.mq.md b/ext/quantum/量子/态/索引.mq.md deleted file mode 100755 index 7b530c7..0000000 --- a/ext/quantum/量子/态/索引.mq.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子/态 -description: 量子态 skill — 张量积、保真度、施密特分解。 -import: - 能力: ext/quantum/量子/能力/索引.mq.md ---- - -纯态:比较、组合或划分一个量子态。 - -用模拟模块的态工具取得含 qubits、dim、amplitudes 的句柄。每个振幅是 re、im 映射; -模拟工具返回的裸振幅列表不是态句柄。保真度与施密特分解也接受电路并作理想演化。 -张量积的态分支要求两个态句柄,必须先把电路转换为态。 - -完整的张量积实验 - -两个零态得到两比特零态,自身保真度为 1。张量积第一个因子占高位,第二个占低位。 -施密特分割相反地按低位数定义 A,不要把这两个约定混淆。 - -```sh -marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/模拟/索引.mq.md 态 '电路=$qc' --effects plugin --session handbook --toget psi --json -marqdo call ext/quantum/量子/态/索引.mq.md 张量积 'a=$psi' 'b=$psi' --effects plugin --session handbook --toget product --json -marqdo call ext/quantum/量子/态/索引.mq.md 保真度 'a=$product' 'b=$product' --effects plugin --session handbook --json -marqdo call ext/quantum/量子/态/索引.mq.md 施密特分解 '态=$product' 分割=1 --effects plugin --session handbook --json -``` - -保真度是等维纯态重叠绝对值的平方。施密特返回 coeffs、ua、ub、entropy、cut、qubits; -entropy 单位为自然对数 nats,贝尔态为 ln(2),两个系数各约 1/√2。 -施密特沿用密度求解器的六比特上限,要求 0 < 分割 < 比特数。 -张量积也支持矩阵因子并返回含矩阵的句柄,此时表示算符积,不自动保证归一化纯态。 - -开发路线 - -纯态代数放在本页,混合态操作放在[密度](../密度/索引.mq.md)。数学实现和独立数值 -测试位于 plugins/quantum/src/linalg.rs,导出位于同目录 src/lib.rs。同步双语契约, -保留 tests/ext/quantum-linalg-smoke.mq.md。用已知正交态、积态、纠缠态作独立期望, -不要仅与实现自身比较。单线布洛赫图通过[可视化](../可视化/索引.mq.md)画布洛赫 -并传入源电路。 - -## 张量积 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 左因子 | -| b | any | 必填 | 右因子 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 张量积结果 | - -这里使用`a`、`b`。 - -将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[将 a 与 b 做张量积,得到更大空间上的态或算符。](quantum_kron(a=`a`, b=`b`))*。 - -## 保真度 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一态或电路 | -| b | any | 必填 | 第二态或电路 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 保真度 | - -这里使用`a`、`b`。 - -纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 -教学噪声忽略。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[纯态 a 与 b 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 教学噪声忽略。](quantum_fidelity(a=`a`, b=`b`))*。 - -## 施密特分解 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 态 | any | 必填 | 纯态或电路 | -| 分割 | number | 1 | 子系统 A 比特数 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 施密特数据 | - -这里使用`态`、`分割`=1。 - -对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对纯态或电路 态 做施密特分解。分割=1 表示子系统 A 的比特数(低位)。](quantum_schmidt(state=`态`, cut=`分割`))*。 diff --git a/ext/quantum/量子/模拟/索引.mq.md b/ext/quantum/量子/模拟/索引.mq.md deleted file mode 100755 index 589ca17..0000000 --- a/ext/quantum/量子/模拟/索引.mq.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子/模拟 -description: 量子模拟 skill — 振幅、概率、含噪采样。 -import: - 能力: ext/quantum/量子/能力/索引.mq.md ---- - -模拟:先确定要观察什么,再选择执行路径。 - -振幅是多少:使用 模拟,施噪:否,返回 re、im 映射列表。 - -需要张量积或保真度输入:使用 态,施噪:否,返回 quantum_state,含 qubits、dim、amplitudes。 - -精确基矢权重:使用 概率,施噪:否,返回 基矢标签到概率。 - -重复读出会怎样:使用 运行,施噪:是,返回 qubits、shots、seed、counts、measure,按需含 noise。 - -设置一个教学噪声通道:使用 噪声,施噪:运行时施加,返回 新电路。 - -噪声族为 bitflip、depolarizing、amplitude_damping,概率范围 [0,1]。 -每个酉操作后在该操作涉及的线上施噪;重复设置会替换旧通道,不是追加一扇门。 -这是教学轨迹模型。测量标记仅选择采样线,不坍缩理想振幅。 - -完整的噪声实验 - -先从[电路模块](../电路/索引.mq.md)取得电路。X 后理想态为 1;概率为 1 的比特翻转 -在 X 后把每次采样变为 0,但精确概率仍描述理想态 1。同一模拟器版本下,电路、 -种子与采样数相同时,运行结果可复现。 - -```sh -marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/电路/索引.mq.md 泡利X '电路=$qc' --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/模拟/索引.mq.md 噪声 '电路=$qc' '种类="bitflip"' 强度=1 --effects plugin --session handbook --toget noisy --json -marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$noisy' --effects plugin --session handbook --json -marqdo call ext/quantum/量子/模拟/索引.mq.md 运行 '电路=$noisy' 次数=32 种子=7 --effects plugin --session handbook --json -``` - -开发路线 - -新读出方式放在本模块,复用电路构造。数值演化和种子采样位于 -plugins/quantum/src/sim.rs,导出位于同目录 src/lib.rs。保持中英理想/含噪边界, -验证 tests/ext/quantum-noise-smoke.mq.md 和振幅阻尼金样。纠缠分析转到 -[态](../态/索引.mq.md),混合态转到[密度](../密度/索引.mq.md);从电路构造密度 -目前仍走理想演化,不是噪声密度引擎。 - -## 模拟 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 待演化电路 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 振幅列表 | - -这里使用`电路`。 - -返回 `电路` 的理想态矢量振幅。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[返回 电路 的理想态矢量振幅。](quantum_simulate(circuit=`电路`))*。 - -## 态 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 待演化电路 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 理想态 | - -这里使用`电路`。 - -与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[与模拟相同:取 电路 的理想振幅,打包为态对象,便于后续保真度或密度构造。](quantum_state(circuit=`电路`))*。 - -## 概率 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 待读取电路 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 概率映射 | - -这里使用`电路`。 - -将当前输入交给 quantum_probabilities,保留同源能力的返回值和失败语义。 - -`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[将当前输入交给 quantum_probabilities,保留同源能力的返回值和失败语义。](quantum_probabilities(circuit=`电路`))*。 - -## 运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 待采样电路 | -| 次数 | number | 1024 | 采样次数 | -| 种子 | number | 1 | 随机种子 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 计数或采样结果 | - -这里使用`电路`、`次数`=1024、`种子`=1。 - -对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对 电路 采样。默认 次数=1024、种子=1。若有教学噪声则轨迹含噪声。](quantum_run(circuit=`电路`, shots=`次数`, seed=`种子`))*。 - -## 噪声 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 调用方提供的电路 | -| 种类 | text | 必填 | 噪声族名 | -| 强度 | number | 必填 | 单位区间强度 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 带噪声元数据的电路 | - -这里使用`电路`、`种类`、`强度`。 - -在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[在 电路 上附着种类 种类、强度 强度 的教学噪声。理想概率工具忽略它。](quantum_noise(circuit=`电路`, kind=`种类`, p=`强度`))*。 diff --git a/ext/quantum/量子/电路/索引.mq.md b/ext/quantum/量子/电路/索引.mq.md deleted file mode 100755 index 6fe7e02..0000000 --- a/ext/quantum/量子/电路/索引.mq.md +++ /dev/null @@ -1,821 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子/电路 -description: 量子电路 skill — 造线、施加门;含作者对象「电路」。 -import: - 能力: ext/quantum/量子/能力/索引.mq.md - 密度: ext/quantum/量子/密度/索引.mq.md ---- - -电路构造:需要保留并继续操作一个量子程序时,从这里开始。 - -初态为全零态,每次施加都返回新电路,必须接住返回值才能继续。比特 0 对应基矢标签 -最右位,角度单位为弧度。默认支持 1–12 比特;MARQDO_QUANTUM_MAX_QUBITS 可调整 -限制,硬上限 16。态矢量内存按 2^n 增长,密度和施密特另有限制。 - -读懂 → 执行 → 观察 - -下面的完整 shell 实验造出贝尔态,再交给[模拟模块](../模拟/索引.mq.md)观察。 -00 和 11 的概率应各约 0.5。单引号保护会话引用,避免 shell 提前展开变量。 -所有命令使用同一会话 handbook,每一步覆盖 qc 绑定,不改动旧电路值。 - -```sh -marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=2 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 '电路=$qc' 比特=0 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/电路/索引.mq.md 控非 '电路=$qc' 控制=0 目标=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects plugin --session handbook --json -``` - -创建线路或预载步骤表:使用 新建,下一步为 模拟模块取结果。 - -叠加、基态与相位操作:使用 哈达玛、泡利X、泡利Y、泡利Z、相位S、相位T、单位,下一步为 概率。 - -连续控制:使用 绕X、绕Y、绕Z,下一步为 参数单位为弧度。 - -纠缠与路由:使用 控非、控相、交换,下一步为 态模块施密特分解。 - -组合片段、自定义门:使用 追加、施加,下一步为 门模块提供门。 - -教学分层或读出:使用 屏障、测量标记,下一步为 可视化或运行采样。 - -下方电路对象保留作者方法链;其模拟、密度和绘图方法是便利入口,完整工具契约在 -对应模块。不要尝试无接收者调用实例方法,直接调用对象之前的自由工具即可。 - -开发路线 - -新电路配方优先在[根索引](../索引.mq.md)组合已有工具。只有组合与自定义门都无法 -表达时才扩原生能力:修改 plugins/quantum/src/sim.rs 和同目录 src/lib.rs,随后 -同步本页自由工具、作者方法及英文镜像。验证两个后端,并保留 - tests/ext/quantum-steps-smoke.mq.md 的作者步骤表行为。 - -## 新建 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特数 | number | 1 | 线宽 | -| 步骤 | any | None | 可选门表或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新电路句柄 | - -这里使用`比特数`=1、`步骤`=None。 - -创建宽度为 `比特数`=1 的态矢量电路。可选 `步骤`=None 表示不预载门表。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[创建宽度为 比特数=1 的态矢量电路。可选 步骤=None 表示不预载门表。](quantum_circuit_new(qubits=`比特数`, steps=`步骤`))*。 - -## 哈达玛 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 电路句柄 | -| 比特 | number | 0 | 目标线 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`电路`、`比特`=0。 - -对已有 `电路` 的 `比特`=0 施加哈达玛。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对已有 电路 的 比特=0 施加哈达玛。](quantum_h(circuit=`电路`, qubit=`比特`))*。 - -## 控非 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 电路句柄 | -| 控制 | number | 0 | 控制位 | -| 目标 | number | 1 | 目标位 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`电路`、`控制`=0、`目标`=1。 - -对 `电路` 从 `控制`=0 到 `目标`=1 施加控非。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对 电路 从 控制=0 到 目标=1 施加控非。](quantum_cx(circuit=`电路`, control=`控制`, target=`目标`))*。 - -## 屏障 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 电路句柄 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 带屏障的电路 | - -这里使用`电路`。 - -在 `电路` 上记录可视化屏障(不改态)。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[在 电路 上记录可视化屏障(不改态)。](quantum_barrier(circuit=`电路`))*。 - -## 测量标记 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 电路 | any | 必填 | 电路句柄 | -| 比特 | any | None | 线列表或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 带测量标记的电路 | - -这里使用`电路`、`比特`=None。 - -为后续运行在 `电路` 上标记计算基读出。`比特`=None 表示全部线。不坍缩理想态。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[为后续运行在 电路 上标记计算基读出。比特=None 表示全部线。不坍缩理想态。](quantum_measure(circuit=`电路`, qubits=`比特`))*。 - -## 泡利X - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`电路`。 - -对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_x(circuit=`电路`, qubit=`比特`))*。 - -## 泡利Y - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`电路`。 - -对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_y(circuit=`电路`, qubit=`比特`))*。 - -## 泡利Z - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`电路`。 - -对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_z(circuit=`电路`, qubit=`比特`))*。 - -## 相位S - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`电路`。 - -对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_s(circuit=`电路`, qubit=`比特`))*。 - -## 相位T - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`电路`。 - -对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_t(circuit=`电路`, qubit=`比特`))*。 - -## 单位 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`电路`。 - -对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_i(circuit=`电路`, qubit=`比特`))*。 - -## 绕X - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 参数 | number | 必填 | 必填 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`参数`、`电路`。 - -绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_rx(circuit=`电路`, qubit=`比特`, theta=`参数`))*。 - -## 绕Y - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 参数 | number | 必填 | 必填 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`参数`、`电路`。 - -绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_ry(circuit=`电路`, qubit=`比特`, theta=`参数`))*。 - -## 绕Z - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 参数 | number | 必填 | 必填 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特`=0、`参数`、`电路`。 - -绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_rz(circuit=`电路`, qubit=`比特`, theta=`参数`))*。 - -## 控相 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 控制 | number | 0 | 默认 0 | -| 目标 | number | 1 | 默认 1 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`控制`=0、`目标`=1、`电路`。 - -在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_cz(circuit=`电路`, control=`控制`, target=`目标`))*。 - -## 交换 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特甲 | any | 0 | 默认 0 | -| 比特乙 | any | 1 | 默认 1 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`比特甲`=0、`比特乙`=1、`电路`。 - -交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_swap(circuit=`电路`, a=`比特甲`, b=`比特乙`))*。 - -## 追加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 操作 | any | 必填 | 必填 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`操作`、`电路`。 - -把另一电路的操作列,或门/比特记录表,追加到本电路。返回合并后的句柄,便于组合电路片段。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[将本项追加到新列表](quantum_append(circuit=`电路`, op=`操作`))*。 - -## 施加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 门 | any | 必填 | 必填 | -| 比特 | any | 0 | 默认 0 | -| 电路 | any | 必填 | 已有电路;返回新值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -这里使用`门`、`比特`=0、`电路`。 - -把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 - -电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_apply(circuit=`电路`, gate=`门`, qubits=`比特`))*。 - -# 电路 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特数 | number | 1 | 默认 1 | -| 步骤 | any | None | 默认 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特数`=1、`步骤`=None。 - -状态向量电路,初态为全零。可选步骤表预载门列。方法追加门并返回新句柄,供作者链式写法;智能体更宜用上方 ## 工具配合 marqdo call。测量标记只影响采样,不坍缩概率所用的理想态。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[状态向量电路,初态为全零。可选步骤表预载门列。方法追加门并返回新句柄,供作者链式写法;智能体更宜用上方 ## 工具配合 marqdo call。测量标记只影响采样,不坍缩概率所用的理想态。](quantum_circuit_new(qubits=`比特数`, steps=`步骤`))*。 - -## 哈达玛 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0。 - -对选定线施加哈达玛,把计算基变成等权叠加,是贝尔态与 GHZ 制备的第一步。返回更新后的电路句柄,便于继续链式写法而不原地突变。 - -完成后返回*[对选定线施加哈达玛,把计算基变成等权叠加,是贝尔态与 GHZ 制备的第一步。返回更新后的电路句柄,便于继续链式写法而不原地突变。](quantum_h(circuit=`self`, qubit=`比特`))*。 - -## 泡利X - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0。 - -对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 - -完成后返回*[对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。](quantum_x(circuit=`self`, qubit=`比特`))*。 - -## 泡利Y - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0。 - -对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 - -完成后返回*[对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。](quantum_y(circuit=`self`, qubit=`比特`))*。 - -## 泡利Z - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0。 - -对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 - -完成后返回*[对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。](quantum_z(circuit=`self`, qubit=`比特`))*。 - -## 相位S - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0。 - -对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 - -完成后返回*[对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。](quantum_s(circuit=`self`, qubit=`比特`))*。 - -## 相位T - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0。 - -对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 - -完成后返回*[对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。](quantum_t(circuit=`self`, qubit=`比特`))*。 - -## 单位 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0。 - -对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 - -完成后返回*[对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。](quantum_i(circuit=`self`, qubit=`比特`))*。 - -## 绕X - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 参数 | number | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0、`参数`。 - -绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 - -完成后返回*[绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。](quantum_rx(circuit=`self`, qubit=`比特`, theta=`参数`))*。 - -## 绕Y - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 参数 | number | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0、`参数`。 - -绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 - -完成后返回*[绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。](quantum_ry(circuit=`self`, qubit=`比特`, theta=`参数`))*。 - -## 绕Z - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | 0 | 默认 0 | -| 参数 | number | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=0、`参数`。 - -绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 - -完成后返回*[绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。](quantum_rz(circuit=`self`, qubit=`比特`, theta=`参数`))*。 - -## 控非 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 控制 | number | 0 | 默认 0 | -| 目标 | number | 1 | 默认 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`控制`=0、`目标`=1。 - -从控制位到目标位施加控非。贝尔态与 GHZ 制备中的标准纠缠步骤。返回更新后的电路句柄以便继续链式调用。 - -完成后返回*[从控制位到目标位施加控非。贝尔态与 GHZ 制备中的标准纠缠步骤。返回更新后的电路句柄以便继续链式调用。](quantum_cx(circuit=`self`, control=`控制`, target=`目标`))*。 - -## 控相 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 控制 | number | 0 | 默认 0 | -| 目标 | number | 1 | 默认 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`控制`=0、`目标`=1。 - -在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 - -完成后返回*[在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。](quantum_cz(circuit=`self`, control=`控制`, target=`目标`))*。 - -## 交换 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特甲 | any | 0 | 默认 0 | -| 比特乙 | any | 1 | 默认 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特甲`=0、`比特乙`=1。 - -交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 - -完成后返回*[交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。](quantum_swap(circuit=`self`, a=`比特甲`, b=`比特乙`))*。 - -## 屏障 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -仅记录可视化分隔,不改变理想态矢量。画电路轨线时用来分开讲义阶段。 - -完成后返回*[仅记录可视化分隔,不改变理想态矢量。画电路轨线时用来分开讲义阶段。](quantum_barrier(circuit=`self`))*。 - -## 测量 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 比特 | any | None | 默认 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`比特`=None。 - -为后续运行标记计算基读出线。不坍缩概率所用的理想态。比特=None 表示标记全部线。 - -完成后返回*[为后续运行标记计算基读出线。不坍缩概率所用的理想态。比特=None 表示标记全部线。](quantum_measure(circuit=`self`, qubits=`比特`))*。 - -## 追加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 操作 | any | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`操作`。 - -把另一电路的操作列,或门/比特记录表,追加到本电路。返回合并后的句柄,便于组合电路片段。 - -完成后返回*[将本项追加到新列表](quantum_append(circuit=`self`, op=`操作`))*。 - -## 施加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 门 | any | 必填 | 必填 | -| 比特 | any | 0 | 默认 0 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`门`、`比特`=0。 - -把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 - -完成后返回*[把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。](quantum_apply(circuit=`self`, gate=`门`, qubits=`比特`))*。 - -## 噪声 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 种类 | any | 必填 | 必填 | -| 概率 | any | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 新的电路值,接住返回值以继续 | - -这里使用`种类`、`概率`。 - -附着给定种类与强度的教学噪声,供运行轨迹使用。理想模拟与概率路径按设计会忽略该通道。 - -完成后返回*[附着给定种类与强度的教学噪声,供运行轨迹使用。理想模拟与概率路径按设计会忽略该通道。](quantum_noise(circuit=`self`, kind=`种类`, p=`概率`))*。 - -## 模拟 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | re、im 振幅列表 | - -返回当前电路的理想态矢量振幅(re/im)。此路径忽略已附着的教学噪声。 - -完成后返回*[返回当前电路的理想态矢量振幅(re/im)。此路径忽略已附着的教学噪声。](quantum_simulate(circuit=`self`))*。 - -## 态 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_state,含 qubits、dim、amplitudes | - -返回与模拟相同振幅的理想态对象。后续保真度或密度工具若需要态句柄,优先用本方法。 - -完成后返回*[返回与模拟相同振幅的理想态对象。后续保真度或密度工具若需要态句柄,优先用本方法。](quantum_state(circuit=`self`))*。 - -## 概率 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 基矢标签到理想概率 | - -基矢标签到理想概率的映射;比特 0 在最右侧。忽略教学噪声,结果与纯态矢量叙述一致。 - -完成后返回*[基矢标签到理想概率的映射;比特 0 在最右侧。忽略教学噪声,结果与纯态矢量叙述一致。](quantum_probabilities(circuit=`self`))*。 - -## 运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 次数 | number | 1024 | 默认 1024 | -| 种子 | number | 1 | 默认 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 采样信息与 counts | - -这里使用`次数`=1024、`种子`=1。 - -对本电路做计算基采样。默认次数=1024、种子=1,便于复现。若已附着教学噪声则在轨迹中启用。 - -完成后返回*[对本电路做计算基采样。默认次数=1024、种子=1,便于复现。若已附着教学噪声则在轨迹中启用。](quantum_run(circuit=`self`, shots=`次数`, seed=`种子`))*。 - -## 绘图 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 默认 None | -| 种类 | any | "circuit" | 默认 circuit | -| 比特 | any | 0 | 默认 0 | -| 主题 | any | "dark" | 默认 dark | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg,含 kind 与 svg | - -这里使用`路径`=None、`种类`="circuit"、`比特`=0、`主题`="dark"。 - -绘制电路轨线、概率条、布洛赫或高级密度图种的 SVG。主题为 dark、light、bw。可选路径落盘供 CLI 或 view 嵌入。 - -完成后返回*[绘制电路轨线、概率条、布洛赫或高级密度图种的 SVG。主题为 dark、light、bw。可选路径落盘供 CLI 或 view 嵌入。](quantum_draw_circuit(circuit=`self`, path=`路径`, kind=`种类`, qubit=`比特`, theme=`主题`))*。 - -## 密度 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 密度算符句柄 | - -对本电路理想模拟后构造纯态密度矩阵 ρ=|ψ⟩⟨ψ|。混合态与部分迹请改用密度模块工具。 - -完成后返回*[对本电路理想模拟后构造纯态密度矩阵 ρ=|ψ⟩⟨ψ|。混合态与部分迹请改用密度模块工具。](quantum_density_from_state(state=`self`))*。 - -## 期望 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 可观测量 | any | 必填 | 必填 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 标量观察值 | - -这里使用`可观测量`。 - -在本电路理想密度上计算泡利串(左端=高比特)或矩阵的期望值。忽略教学噪声。 - -完成后返回*[在本电路理想密度上计算泡利串(左端=高比特)或矩阵的期望值。忽略教学噪声。](quantum_density_expect(density=`self`, obs=`可观测量`))*。 - -## 施密特 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 分割 | number | 1 | 默认 1 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 系数、两侧基与熵 | - -这里使用`分割`=1。 - -对理想态做二分施密特分解。分割为子系统 A 的比特数,从低位起算。 - -完成后返回*[对理想态做二分施密特分解。分割为子系统 A 的比特数,从低位起算。](quantum_schmidt(state=`self`, cut=`分割`))*。 diff --git a/ext/quantum/量子/索引.mq.md b/ext/quantum/量子/索引.mq.md deleted file mode 100755 index 77eabe2..0000000 --- a/ext/quantum/量子/索引.mq.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子 -description: 量子库可执行开发手册与实验工具。 -import: - 态: ext/quantum/量子/态/索引.mq.md - 电路: ext/quantum/量子/电路/索引.mq.md - 模拟: ext/quantum/量子/模拟/索引.mq.md - 密度: ext/quantum/量子/密度/索引.mq.md ---- - -量子库开发手册:先读本索引,运行一个可核对的实验,再打开负责下一问题的模块。 -本文件既是包的真实程序,也是使用与开发指引。下方可调用标题就是工具,周围叙述解释 -何时、为何使用它们,不需要另一份 skill manifest。 - -从可核对的结果开始 - -以下命令互相独立,不需要会话。贝尔态 00、11 概率应各约 0.5;纠缠分析还返回 -ZZ 关联约 1、约化纯度约 0.5、施密特熵约 ln(2)。以 1e-9 容差比较数值, -不要把浮点 JSON 字符串与字面量 0.5 作精确文本比较。 - -```sh -marqdo call ext/quantum/量子/索引.mq.md 贝尔态 --effects plugin --json -marqdo call ext/quantum/量子/索引.mq.md 纠缠分析 --effects plugin --json -``` - -根据下一问题导航 - -需要继续编辑电路,调用本页贝尔电路并通过会话保存返回值。需要其他初始程序,打开 -[电路](电路/索引.mq.md):新建、哈达玛、泡利X/Y/Z、相位S/T、单位、绕X/Y/Z、 -控非、控相、交换、施加、追加、屏障、测量标记覆盖构造和组合。 - -定义具名或公式算符,打开[门](门/索引.mq.md),那里还有矩阵导出与比较。 -观察精确振幅、纯态、概率或含噪采样,打开[模拟](模拟/索引.mq.md)。 -计算张量积、保真度、施密特分割,打开[态](态/索引.mq.md)。混合态、部分迹、 -期望与本征谱在[密度](密度/索引.mq.md),SVG 轨线、概率、布洛赫、qsphere、multibloch 和矩阵图在 -[可视化](可视化/索引.mq.md)。每个子入口都给出完整实验、输入输出约定和开发路线。 - -英文工具见[英文根索引](../index.mq.md)。双语目录共用一个插件并用相同科学期望验证, -选好一棵树后按对应参数名调用。[能力](能力/索引.mq.md)用于诊断插件,不是实验的 -前置手动步骤;日常工具会自行加载。 - -安装与定位源码 - -下面示例以当前目录能看见包源码为前提。安装用户把命令第一个文件参数换为实际 -安装路径,默认 ~/.marqdo/ext/quantum/量子/索引.mq.md。包内导入通过扩展搜索根解析。 - -```text -marqdo ext add quantum -marqdo ext list -``` - -在本仓库开发时先构建本地插件。安装过多版本时,将 MARQDO_QUANTUM_PLUGIN 指向 - target/debug/libquantum.so 的绝对路径,其他平台使用对应动态库名。不要把 -MARQDO_EXT 指向仓库 ext 后执行 ext add;安装产物与编辑源码各有自己的位置。 - -```text -source scripts/dev-env.sh -cargo build --locked -p marqdo_plugin_quantum -``` - -理解一次调用 - -基本形式为 marqdo call 文件 函数 名=值 --effects plugin --json。函数名取真实可调用 -标题;嵌套工具使用 parent.child。作者对象内读取 self 的标题是实例方法,需要接收者, -命令行直接使用本包自由工具;写作者程序时导入同一模块即可。 - -参数支持数字、文本、True/False/None、JSON 列表或映射、会话引用。给文本字面量、JSON 和美元引用 -加 shell 单引号:'名="H"' 保留 CLI 所需的文本引号;'电路=$qc' 才是发送给 Marqdo 的引用;裸写 电路=$qc 会先被 shell -展开。带 --json 时,同时检查退出码与 ok,再读取 result;失败说明不是有效句柄。 - -完整的持久实验 - -以下命令可按顺序执行,都使用 handbook 会话。--toget 只保存当前调用返回值。 -施门保留旧值,所以每步必须接住新电路;不带 --toget 的观察不会覆盖已有绑定。 -最后结果应约 0.5:贝尔整体是纯态,任一单比特子系统却是最大混合态。 - -```sh -marqdo call ext/quantum/量子/索引.mq.md 贝尔电路 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects plugin --session handbook --json -marqdo call ext/quantum/量子/密度/索引.mq.md 从态 '态=$qc' --effects plugin --session handbook --toget rho --json -marqdo call ext/quantum/量子/密度/索引.mq.md 部分迹 '密度=$rho' '保留=[0]' --effects plugin --session handbook --toget reduced --json -marqdo call ext/quantum/量子/密度/索引.mq.md 纯度 '密度=$reduced' --effects plugin --session handbook --json -``` - -会话默认保存在 .marqdo/call-sessions,MARQDO_CALL_SESSION_DIR 可改变目录。 -跨进程插件调用通过 journal 重放。保持会话短小,修改源码或插件版本后换新会话, -重放可能重复绘图输出等插件效果。不要复制某个实现版本的 JSON 来手工伪造句柄。 - -科学约定与边界 - -比特 0 在基矢最右位,泡利串最高位在左;角度用弧度。态矢量默认上限 12,比特 -限制可由环境调整但硬上限为 16;密度与施密特上限六比特。施密特 A 占低位分割数, -熵单位为自然对数 nats。 - -精确模拟、概率、保真度、从电路构造密度都忽略教学噪声。只有运行采样使用已附加的 -bitflip、depolarizing、amplitude_damping 通道。测量标记选择采样线,不坍缩理想态。 -混合矩阵构造只核对厄米性与形状,不保证半正定或迹为 1。实验的科学解释必须遵循 -这些边界,各模块入口提供独立反向校验。 - -用同一份知识写作者程序 - -把以下内容存为 bell.mq.md,执行 marqdo run bell.mq.md。步骤表就是线路规格, -程序打印的两个权重应各约 0.5。frontmatter 导入已有模块;GFM 记录表首列为 @,逗号分隔的线号依次表示控制与目标。 -公式也可以绑定后交给门的自定义工具或作者构造器,不必再翻译为另一套结构。 - -```marqdo ---- -markup: occlusion -导入: - 电路: ext/quantum/量子/电路/索引.mq.md ---- - -# main - -`步骤` = - -| @ | 门 | 比特 | -|---|----|------| -| 1 | H | 0 | -| 2 | CX | "0,1" | - -**qc = 电路.电路 比特数=2 步骤=`步骤`** -**p = > `qc`.概率** -**p00 = 取(p, "00")** -**p11 = 取(p, "11")** -> 打印 内容=`p00` -> 打印 内容=`p11` -``` - -开发时复用现有能力 - -新增实验通常只需在本索引组合模块,并把问题、输入、期望和局限写在步骤旁。 -下方纠缠分析展示这种编排。新增酉算符通常使用门的自定义工具,无需新增 ABI。 - -确实需要新原语时,先读归属模块的开发路线,再增加自由工具、保留作者方法,并同步 -英文镜像。数值演化位于 plugins/quantum/src/sim.rs,代数在 linalg.rs,SVG 在 draw.rs, -ABI 注册在同目录 src/lib.rs。插件加载只经过能力边界。新增文件还需更新 -src/ext_cli.rs 的包文件列表,让安装用户能得到它。 - -参数默认值写进叙述,参数契约紧跟标题,返回契约也必须放在首条执行语句之前。 -当前 extract_function_contract 只读取该区域,cap.load 或能力.加载 之后的返回表只是 -说明而非生效契约。类型使用现有 number/text/bool/any;句柄的来源与形状用叙述交代, -不要声称新增了领域类型检查器。把具体意图与操作交错书写,不能靠重复套话凑叙述比例。 - -普通说明节名保持纯叙述:## 会生成真实可调用符号。工具树中只出现可执行工具和 -对象方法。导航使用源码链接与已有 knowledge inspect/resolve,稳定符号由编译器 -产生,不手工维护第二份工具目录。 - -```text -marqdo knowledge ext/quantum --json inspect 纠缠分析 -marqdo check --narrative-ratio ext/quantum/量子/索引.mq.md -cargo test --locked --test quantum_handbook -cargo test --locked --test call_cli quantum_ -cargo test --locked --test gold ext_quantum -- --test-threads=1 -``` - -手册测试直接执行双语文档的 sh 围栏与作者程序,对照独立科学期望,并验证 Tree 与 -Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高也不能替代。既有量子 -金样继续约束噪声、公式、SVG 与对象方法,验证不需要网络或 LLM。 -本轮采用 next/010–012 中由 call 自然派生的简洁能力;更复杂的自我改进智能体和 -持久交互分支仍是未来规划,不作为当前量子库已经具备的承诺。 - -失败后如何恢复 - -插件缺失:检查能力入口,构建或安装 quantum,再重试最小贝尔命令。会话绑定不存在: -使用同一个会话名,先重跑生产者,再运行消费者。设置噪声后理想概率未变:用运行 -观察含噪采样。维数或形状失败:按上面的边界修正输入,不要静默缩小科学问题。 -错误信封不能当作空的成功结果继续传递。 - -## 贝尔电路 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 两比特电路,可交给模拟、密度或绘图 | - -无参数制备贝尔 Φ+ 线路,初态为 00。先在最低位制造等权叠加, -再由该位控制另一位翻转,把振幅关联到 00 和 11。 -工具返回线路而非概率,便于继续施门、设置噪声或独立验证纠缠。 -每一步接住新电路值,原值不被隐式修改。 - -得到**`qc` = [调用 新建](电路.新建(比特数=2, 步骤=None))**。 - -先让最低位具有两条等权路径,再把路径信息传播给第二条线。 - -得到**`qc` = [调用 哈达玛](电路.哈达玛(电路=`qc`, 比特=0))**。 -完成后返回*[调用 控非](电路.控非(电路=`qc`, 控制=0, 目标=1))*。 - -## 贝尔态 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 基矢概率映射;00、11 各约 0.5 | - -无参数演示工具,复用本页贝尔电路的真实制备步骤,只返回理想概率。 -00 和 11 各约一半,其余基矢为零;这是计算基关联,单靠概率还不能证明纠缠, -因此需要纠缠证据时继续调用本页纠缠分析,对照约化纯度与 ZZ 期望。 - -得到**`qc` = [调用 贝尔电路](贝尔电路())**。 -完成后返回*[调用 概率](模拟.概率(电路=`qc`))*。 - -## 纠缠分析 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | probabilities、purity、reduced_purity、zz、schmidt;不写文件 | - -无参数实验,从同一条贝尔线路交叉观察整体、子系统与关联。 -字段保留插件的科学命名,双语入口具有相同结果形状,便于机器比较。 -这是一份可复用实验配方,调用者无需了解原生导出名,也不需要保存中间会话。 -整体纯度应为 1,约化纯度应为 0.5,ZZ 应为 1,施密特熵为 ln(2)。 -所有数值按 1e-9 容差核对;纯态概率与密度构造均使用理想演化。 - -这里分析的是同一次制备的状态,避免分别重建电路导致比较对象不同。 - -得到**`qc` = [调用 贝尔电路](贝尔电路())**。 -得到**`probs` = [调用 概率](模拟.概率(电路=`qc`))**。 - -先构造整体密度并计算纯度。整体纯不意味着每个局部也纯, -接着只保留最低位,检查丢弃另一个比特后出现的混合性。 - -得到**`rho` = [调用 从态](密度.从态(态=`qc`))**。 -得到**`whole` = [调用 纯度](密度.纯度(密度=`rho`))**。 - -`kept` = - -| 比特 | -|------| -| 0 | - -得到**`reduced` = [调用 部分迹](密度.部分迹(密度=`rho`, 保留=`kept`))**。 -得到**`local` = [调用 纯度](密度.纯度(密度=`reduced`))**。 - -ZZ 测量关联,不是单独的纠缠判据。施密特分解独立给出纯态两侧的 -系数与熵;联合这些观察才能解释为何这是贝尔纯态而非经典概率混合。 -返回表将各观察保留原值,便于调用者自行检查,而不是输出一个隐藏阈值的通过标签。 - -得到**`correlation` = [调用 期望](密度.期望(密度=`rho`, 可观测量="ZZ"))**。 -得到**`split` = [调用 施密特分解](态.施密特分解(态=`qc`, 分割=1))**。 - -`report` = - -| probabilities | purity | reduced_purity | zz | schmidt | -|---------------|--------|----------------|----|---------| -| `probs` | `whole` | `local` | `correlation` | `split` | - -完成后返回*report*。 diff --git a/ext/quantum/量子/能力/索引.mq.md b/ext/quantum/量子/能力/索引.mq.md deleted file mode 100755 index 916383a..0000000 --- a/ext/quantum/量子/能力/索引.mq.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子/能力 -description: 量子 ABI 加载 skill。日常请用电路/门/模拟等模块。 -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -原生能力边界:诊断插件发现后,回到领域模块继续工作。 - -本页定位并加载 ABI v2 量子动态库。领域工具自行调用加载,不需要每次先手动初始化。 -英文 _capability 是此边界的等价语言入口,领域代码不应再实现第二套加载过程。 - -```sh -marqdo call ext/quantum/量子/能力/索引.mq.md 加载 --effects plugin --json -``` - -成功返回 null。缺失动态库会提示安装并以非零状态退出;本工具使用 sys.exit,所以 -要同时检查进程状态,不能假定所有失败都有 JSON 信封。安装用 marqdo ext add quantum, -源码开发用 cargo build -p marqdo_plugin_quantum。MARQDO_QUANTUM_PLUGIN 可指定 -开发动态库的绝对路径。 - -仅能力边界导入 lib/plugin,不向领域代码新增加载器或 host_*。修改发现流程时, -同时验证双语根工具与 tests/call_cli.rs,再回到[电路](../电路/索引.mq.md)。 - -## 加载 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 加载成功后为空 | - -通过 plugin.native_path 找到 ABI v2 quantum 共享库,再 plugin.load。若缺失则打印 -安装提示并以非零退出。成功后本进程内可用 quantum_* 符号。本包中只有这里应直接 -接触 lib/plugin。领域模块在需要模拟器的工具开头调用加载。 - -本工具无参数。 - -得到**`p` = [定位已安装的原生插件](plugin.native_path(name="quantum"))**。 -1. `p` - 这里**[加载本操作依赖的原生插件](plugin.load(path=`p`))**。 -2. * - 这里**[输出本步已准备的消息](print(text="ext/quantum/量子: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum)"))**。 - 这里**[按指定退出码结束本次运行](sys.exit(code=1))**。 -完成后返回*None*。 diff --git a/ext/quantum/量子/门/索引.mq.md b/ext/quantum/量子/门/索引.mq.md deleted file mode 100755 index 0876a23..0000000 --- a/ext/quantum/量子/门/索引.mq.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子/门 -description: 量子门 skill — 公式酉矩阵、具名门、矩阵核对。 -import: - 能力: ext/quantum/量子/能力/索引.mq.md ---- - -量子门:先定义算符,再选择它作用的线路。 - -具名工具支持 I、X、Y、Z、H、S、T、Rx、Ry、Rz、CX、CZ、SWAP。旋转参数为弧度。 -自定义门必须是 2^k 阶方阵,并满足 U†U = I,构造容差为 1e-6。元素可为实数或 -含 re、im 的复数映射。JSON 与 Markdown 公式绑定使用同一个构造器。 - -完整的自定义门实验 - -下面矩阵交换零与一,匹配工具应返回 true,最终基矢 1 的概率应为 1。 -仅构造门不会改变电路;必须调用[电路模块](../电路/索引.mq.md)的施加工具。 -所有引用保存在同一会话,不需要手写或解析插件句柄。 - -```sh -marqdo call ext/quantum/量子/门/索引.mq.md 自定义 '矩阵=[[0,1],[1,0]]' '名="X-demo"' --effects plugin --session handbook --toget u --json -marqdo call ext/quantum/量子/门/索引.mq.md 匹配 '门=$u' '矩阵=[[0,1],[1,0]]' --effects plugin --session handbook --json -marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/电路/索引.mq.md 施加 '电路=$qc' '门=$u' 比特=0 --effects plugin --session handbook --toget qc --json -marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects plugin --session handbook --json -``` - -哈达玛、泡利X、泡利Z、控非门提供常用常量,其余内置门使用具名;矩阵工具导出 -条目,匹配用于核对讲义公式与实现。[可视化](../可视化/索引.mq.md)的画门支持 -门符号与矩阵热图。需要纠缠操作时,优先使用控制、目标明确的电路控非工具。 - -开发路线 - -新增用户酉矩阵只需自定义与独立期望矩阵,不必修改 Rust 或 ABI。新增内置门时, -先更新 plugins/quantum/src/sim.rs::named_gate_matrix 及数值测试,再同步中英入口。 -保留 tests/ext/quantum-custom-gate-smoke.mq.md 中公式直接构造哈达玛门的例子。 - -## 哈达玛 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 哈达玛门句柄 | - -哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 - -本工具无参数。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 本工具无参数。](quantum_gate_new(name="H", theta=None, matrix=None))*。 - -## 泡利X - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 泡利 X 句柄 | - -泡利 X 是比特翻转门。 - -本工具无参数。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[泡利 X 是比特翻转门。 本工具无参数。](quantum_gate_new(name="X", theta=None, matrix=None))*。 - -## 泡利Z - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 泡利 Z 句柄 | - -泡利 Z 给 ket-one 乘上负号相位。 - -本工具无参数。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[泡利 Z 给 ket-one 乘上负号相位。 本工具无参数。](quantum_gate_new(name="Z", theta=None, matrix=None))*。 - -## 控非门 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | CNOT 门句柄 | - -两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 - -本工具无参数。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 本工具无参数。](quantum_gate_new(name="CX", theta=None, matrix=None))*。 - -## 自定义 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 矩阵 | any | 必填 | 酉矩阵公式或列表 | -| 名 | text | "U" | 可选标签,默认 U | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 自定义门句柄 | - -这里使用`矩阵`、`名`="U"。 - -用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[用显式酉矩阵 矩阵 构造门。可选标签 名="U"。](quantum_gate_new(name=`名`, theta=None, matrix=`矩阵`))*。 - -## 匹配 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 门 | any | 必填 | 门句柄 | -| 容差 | number | 0.000000001 | 绝对容差 | -| 矩阵 | any | 必填 | 期望酉矩阵 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | bool | 匹配则为 True | - -这里使用`门`、`容差`=0.000000001、`矩阵`。 - -检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[检查 门 是否在容差 容差=0.000000001 内匹配 矩阵。](quantum_gate_matches_matrix(gate=`门`, matrix=`矩阵`, tol=`容差`))*。 - -## 具名 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | text | "H" | 内置门名 | -| 参数 | any | None | 旋转角或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 可交给施加工具的门句柄 | - -这里使用`名`="H"、`参数`=None。 - -构造内置门 `名`="H";可选 `参数`=None,Rx、Ry、Rz 必须给出弧度角。 -返回可交给电路施加的门句柄,创建过程不改变任何线路。支持名称见本页开篇表述。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[构造内置门 名="H";可选 参数=None,Rx、Ry、Rz 必须给出弧度角。 返回可交给电路施加的门句柄,创建过程不改变任何线路。支持名称见本页开篇表述。](quantum_gate_new(name=`名`, theta=`参数`, matrix=None))*。 - -## 矩阵 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 门 | any | 必填 | 门句柄 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 复数矩阵条目,每项含 re 与 im | - -这里使用`门`。 - -导出 `门` 的显式酉矩阵。每个元素含 re、im,可用于公式复核或独立矩阵比较; -本工具仅观察算符,不改变句柄,也不把门应用到任何电路。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[导出 门 的显式酉矩阵。每个元素含 re、im,可用于公式复核或独立矩阵比较; 本工具仅观察算符,不改变句柄,也不把门应用到任何电路。](quantum_gate_matrix(gate=`门`))*。 - -# 门 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | any | None | 默认 None | -| 参数 | number | None | 默认 None | -| 矩阵 | any | None | 默认 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 可交给施加工具的门句柄 | - -这里使用`名`=None、`参数`=None、`矩阵`=None。 - -具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。 - -这里**[调用 加载](能力.加载())**。 -完成后返回*[具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。](quantum_gate_new(name=`名`, theta=`参数`, matrix=`矩阵`))*。 - -## 矩阵 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 复数矩阵条目,每项含 re 与 im | - -返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。 - -完成后返回*[返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。](quantum_gate_matrix(gate=`self`))*。 - -## 匹配矩阵 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 矩阵 | any | 必填 | 必填 | -| 容差 | any | 0.000000001 | 默认 0.000000001 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | bool | 容差内匹配 | - -这里使用`矩阵`、`容差`=0.000000001。 - -检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。 - -完成后返回*[检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。](quantum_gate_matches_matrix(gate=`self`, matrix=`矩阵`, tol=`容差`))*。 - -## 绘图 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 默认 None | -| 种类 | any | "gate" | 默认 gate | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg,含 kind 与 svg | - -这里使用`路径`=None、`种类`="gate"。 - -绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。 - -完成后返回*[绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。](quantum_gate_draw(gate=`self`, path=`路径`, kind=`种类`))*。 diff --git a/ext/security/auth.mq.md b/ext/security/auth.mq.md deleted file mode 100755 index 46ff7cb..0000000 --- a/ext/security/auth.mq.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -markup: occlusion -title: ext/security/auth -description: Auth Resource (ADR 0007). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md ---- - -Read [the security entry](index.mq.md) to distinguish credential/session operations, role checks and OIDC integration. This leaf owns the native authentication resource; endpoint metadata still controls route authorization. Prepare the native web plugin, keep secrets out of examples and logs, and verify both denied and accepted credentials before changing session behavior. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -## attach - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared web application | -| users | any | required | Credential table or native database-backed user configuration | -| session_ttl | number | 3600 | Session lifetime in seconds | -| admin_prefix | text | "/admin" | Native administration prefix | -| login_path | text | "/login" | Declared login route | -| login_redirect | text | "" | Optional successful login destination | -| logout_redirect | text | "" | Optional logout destination | -| register | bool | False | Explicitly enable user registration | -| register_path | text | "/register" | Registration route when enabled | -| default_role | text | "user" | Role assigned to a registered user | -| session_url | text | "" | Optional session backend URL | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Updated app with native login/session policy | - -Use `app`, `users`, `session_ttl`=3600, `admin_prefix`="/admin", `login_path`="/login", `login_redirect`="", `logout_redirect`="", `register`=False, `register_path`="/register", `default_role`="user" and `session_url`="" before web.listen. This resource owns the login/session policy, while Endpoint auth metadata and explicit gates decide which requests need a session or role. Retain the returned app; construction does not authenticate a request or start a server. Credential tables in local examples are fixtures; real user stores should contain the hashes produced by hash_password. Registration is off until deliberately enabled. Session lifetime is in seconds, and external session backends require their own connection configuration. - -We **[Load the native authentication implementation](plugin.load(path=plugin.native_path(name="web")))**. -Return *[Bind the selected login and session policy](web_app_auth(app=`app`, users=`users`, session_ttl=`session_ttl`, admin_prefix=`admin_prefix`, login_redirect=`login_redirect`, logout_redirect=`logout_redirect`, login_path=`login_path`, register=`register`, register_path=`register_path`, default_role=`default_role`, session_url=`session_url`))*. - - -## gate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared application retaining its actual resources | -| path | text | required | Explicit URL path to protect | -| roles | any | "admin" | Allowed role CSV or list | -| permissions | text | "" | Optional permission CSV; native any-match policy | -| match | text | "prefix" | prefix or exact path matching | -| on_deny | text | "forbid" | forbid or redirect anonymous requests to login | -| exclude | any | None | Explicit path exclusions; native login/logout exclusions remain | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Updated app with a server-enforced gate; no listener starts | - -Use `app`, `path`, `roles`="admin", `permissions`="", `match`="prefix", `on_deny`="forbid" and `exclude`=None before listening, with plugin permission. Retain the returned app. This security-owned operation protects real requests; hiding a navigation link does not do that. It reuses the existing native gate and does not mutate Document content or invent routes. - -Prefix matching includes the selected path and its slash descendants. The runtime keeps login and logout available to avoid authentication loops. When permissions are supplied, native permission matching applies instead of the role list; any required permission may match. Redirect applies to anonymous denial, while a signed-in subject without access receives forbidden. Test both direct denied requests and authenticated access, and gate the actual form/API endpoint separately if its data is private. - -We **[Load the native access-policy implementation](_load())**. -Return *[Bind the explicit server access rule](web_app_gate(app=`app`, path=`path`, roles=`roles`, permissions=`permissions`, match=`match`, on_deny=`on_deny`, exclude=`exclude`))*. - - -# auth - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| users | any | required | Configured user store used by authentication | -| session_ttl | any | 3600 | Session lifetime in seconds | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Session/auth helper. Constructs a config object; `login` validates against the users table. To bind native login and protect `/admin`, call attach and gate before listening. | - -Use `users`, `session_ttl`=3600 as the inputs for this operation. - -Session/auth helper. Constructs a config object; `login` validates against the users table. To bind native login and protect `/admin`, call attach and gate before listening. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Session/auth helper. Constructs a config object; login validates against the users table. To bind server login and gates, use this module's attach function before web.listen.](web_auth_new(users=`users`, session_ttl=`session_ttl`))*. - -## login - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| username | any | required | User name in the configured user store | -| password | any | required | Credential supplied for verification or hashing; do not log it | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`. | - -Use `username`, `password` as the inputs for this operation. - -Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`. - -We retain **`users` = [Read users field](access(`self`, "users"))**. -We retain **`ttl` = [Read session_ttl field](access(`self`, "session_ttl"))**. -Return *[Validate credentials against the users table and create a session. Returns {ok, session_id, username, role}.](web_auth_login(username=`username`, password=`password`, users=`users`, session_ttl=`ttl`))*. - -## check - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| session_id | any | required | Session identifier returned by login | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Returns `{ok, username, role}` when the session is valid. | - -Use `session_id` as the inputs for this operation. - -Returns `{ok, username, role}` when the session is valid. - -Return *[Returns {ok, username, role} when the session is valid.](web_auth_check(session_id=`session_id`))*. - -## logout - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| session_id | any | required | Session identifier returned by login | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Destroy the session. | - -Use `session_id` as the inputs for this operation. - -Destroy the session. - -Return *[Destroy the session.](web_auth_logout(session_id=`session_id`))*. - -## hash_password - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| password | any | required | Credential supplied for verification or hashing; do not log it | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Hash a plaintext password for storage in admin user tables (argon2id). Store the returned `hash` in the `password` column; login verifies automatically. | - -Use `password` as the inputs for this operation. - -Hash a plaintext password for storage in admin user tables (argon2id). Store the returned `hash` in the `password` column; login verifies automatically. - -Return *[Hash a plaintext password for storage in admin user tables (argon2id). Store the returned hash in the password column; login verifies automatically.](web_password_hash(password=`password`))*. diff --git a/ext/security/index.mq.md b/ext/security/index.mq.md deleted file mode 100755 index 46c3484..0000000 --- a/ext/security/index.mq.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -markup: occlusion -title: Security resources — authentication, roles and OIDC -import: - permissions_api: ext/security/rbac.mq.md ---- - -Use [auth](auth.mq.md) for credential/session operations, [rbac](rbac.mq.md) for role permissions, -and [OIDC](oidc.mq.md) for attaching an external identity provider to an existing web app. -[Tenant selection](tenant.mq.md) supplies explicit request context for scoped data queries; -it does not authenticate a subject or prove tenant membership. -中文服务工作流使用[鉴权绑定](鉴权.mq.md),与 auth.attach 保持相同策略及默认值。 -Endpoint authorization remains explicit in the web artifact metadata; a script permission check -does not automatically protect an HTTP route. - -The resources use the native web plugin. Build it with scripts/build-web-plugin.sh in this checkout. -This entry's deterministic permission check does not contact an identity provider or change users: - -```sh -marqdo call ext/security/index.mq.md check_permission 'held="notes:read"' 'needed="notes:read"' --effects plugin --json -``` - -Constructors create receivers that are used by resource methods. The free function below makes -that pattern available to CLI callers without copying opaque object fields. For OIDC, configure -registered callback URLs and origin restrictions in oidc.mq.md; never copy production credentials -into a source example. Transport success and authorization success are distinct fields. - -Develop native security policy in the existing web security implementation, then document the -public contract and exercise both allow and deny cases. Keep permission delimiters, wildcard -behavior, session lifetime and credential handling explicit. Use local fixtures for login and -OIDC tests; the reusable source must not require a live identity service merely to be inspected. - -## check_permission - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| held | text | required | Comma-separated permissions held by the subject; wildcard follows the native RBAC policy | -| needed | text | required | Comma-separated required permissions interpreted by the documented RBAC checker | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Native ok/allowed record; inspect allowed to decide authorization | - -The inputs `held` and `needed` describe one explicit permission decision, not a role assignment -or a request to modify the user database. The native checker currently accepts any matching -required permission; held wildcard permits all. Use the leaf API when changing a role catalog. - -The checker is an associated tool: it does not read self, so this workflow calls its definition -path directly rather than pretending it is an instance method. We return *[Evaluate this subject against the requested permission set](permissions_api.rbac.can(permissions=`held`, needed=`needed`))* . -The returned allowed field is the authorization decision; the outer CLI ok only reports whether -this function call completed. A denied decision remains a valid, observable result. diff --git a/ext/security/oidc.mq.md b/ext/security/oidc.mq.md deleted file mode 100755 index 00ba92f..0000000 --- a/ext/security/oidc.mq.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -markup: occlusion -title: ext/security/oidc -description: OIDC attach helper for app handles (ADR 0007). Prefer declared auth metadata on Endpoints. -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -OIDC attaches provider configuration to an existing web application. Read [the security entry](index.mq.md) for the ownership boundaries before configuring a live identity provider. Registered callback URLs, origin checks and credentials require real deployment configuration; constructing a record alone does not validate a login flow. Keep provider failures distinct from permission decisions and exercise callbacks with controlled fixtures. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -## attach - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Existing web application resource | -| issuer | any | None | OIDC issuer URL; None requires explicit provider endpoint configuration | -| client_id | any | required | Client identifier registered with the identity provider | -| client_secret | any | required | Client credential; supply through trusted runtime configuration | -| redirect_uri | any | required | Registered absolute callback URL or callback path | -| redirect_origins | any | None | Comma-separated callback origin allowlist when using a path callback | -| scopes | any | "openid profile email" | Space-separated identity-provider scopes | -| callback_path | any | None | Explicit callback route override or None for the implementation default | -| authorize_url | any | None | Authorization endpoint override | -| token_url | any | None | Token-exchange endpoint override | -| userinfo_url | any | None | User-info endpoint override | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | (`/oidc/callback`). Path mode resolves the absolute callback from the login request Host (`X-Forwarded-Proto` / `X-Forwarded-Host` when behind a reverse proxy) and stores it in the session so token exchange uses the same string. Optional `redirect_origins` is a comma-separated allowlist (`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match. The IdP must still register every absolute callback URL that will be used. | - -Use `app`, `issuer`=None, `client_id`, `client_secret`, `redirect_uri`, `redirect_origins`=None, `scopes`="openid profile email", `callback_path`=None, `authorize_url`=None, `token_url`=None, `userinfo_url`=None as the inputs for this operation. - -`redirect_uri` may be an absolute URL (`https://qdqc.com/oidc/callback`) or a path -(`/oidc/callback`). Path mode resolves the absolute callback from the login request -Host (`X-Forwarded-Proto` / `X-Forwarded-Host` when behind a reverse proxy) and stores -it in the session so token exchange uses the same string. - -Optional `redirect_origins` is a comma-separated allowlist -(`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match. -The IdP must still register every absolute callback URL that will be used. - -We **[Load the native plugin required by this operation](_load())**. -Return *[(/oidc/callback)](web_app_oidc(app=`app`, issuer=`issuer`, client_id=`client_id`, client_secret=`client_secret`, redirect_uri=`redirect_uri`, redirect_origins=`redirect_origins`, scopes=`scopes`, callback_path=`callback_path`, authorize_url=`authorize_url`, token_url=`token_url`, userinfo_url=`userinfo_url`))*. diff --git a/ext/security/rbac.mq.md b/ext/security/rbac.mq.md deleted file mode 100755 index 43fbf8e..0000000 --- a/ext/security/rbac.mq.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -markup: occlusion -title: ext/security/rbac -description: RBAC Resource (ADR 0007). -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - table: lib/table.mq.md ---- - -Role and permission data are explicit inputs to the native web checker. The [security entry](index.mq.md) executes allow and deny cases without an identity provider. The can tool is associated with rbac rather than a receiver method because it reads only its arguments. Held wildcard and any-match needed permissions follow the native policy; do not reinterpret that as an all-permissions check. - -## _load - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | - -Resolve and load the native web plugin before resource operations; missing binaries stop this run. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. - -# rbac - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Offline helpers for role ⊥ permission. Prefer `app.enable_rbac` + gates for HTTP; use these for scripts/tests. | - -Offline helpers for role ⊥ permission. Prefer `app.enable_rbac` + gates for HTTP; use these for scripts/tests. - -## can - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| permissions | any | required | Comma-separated permission names held by the current role or subject | -| needed | any | required | Permission names required by the operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Return `{ok, allowed}` — whether held permission CSV includes any of `needed` (CSV). Held `*` allows all. | - -Use `permissions`, `needed` as the inputs for this operation. - -Return `{ok, allowed}` — whether held permission CSV includes any of `needed` (CSV). Held `*` allows all. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Return {ok, allowed} — whether held permission CSV includes any of needed (CSV). Held * allows all.](web_rbac_can(permissions=`permissions`, needed=`needed`))*. - -## assign_role - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | required | Resource connection URL; scheme selects the documented backend | -| username | any | required | User name in the configured user store | -| role | any | required | Role name within the selected user store | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Bind `username` (in `web_users`) to role name. | - -Use `url`, `username`, `role` as the inputs for this operation. - -Bind `username` (in `web_users`) to role name. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Bind username (in web_users) to role name.](web_rbac_assign_role(url=`url`, username=`username`, role=`role`))*. - -## create_role - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | required | Resource connection URL; scheme selects the documented backend | -| name | any | required | Name registered or looked up by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Create a non-system role; returns `{ok, id, name}`. | - -Use `url`, `name` as the inputs for this operation. - -Create a non-system role; returns `{ok, id, name}`. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Create a non-system role; returns {ok, id, name}.](web_rbac_create_role(url=`url`, name=`name`))*. - -## set_role_permissions - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | any | required | Resource connection URL; scheme selects the documented backend | -| role | any | required | Role name within the selected user store | -| permissions | any | required | Comma-separated permission names held by the current role or subject | -| grantable | any | "" | Permission catalog limiting which permissions may be granted | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Replace permissions on a non-system role (CSV). `grantable` restricts grants (anti-escalation); empty = full catalog. | - -Use `url`, `role`, `permissions`, `grantable`="" as the inputs for this operation. - -Replace permissions on a non-system role (CSV). `grantable` restricts grants (anti-escalation); empty = full catalog. - -We **[Load the native plugin required by this operation](_load())**. -Return *[Replace permissions on a non-system role (CSV). grantable restricts grants (anti-escalation); empty = full catalog.](web_rbac_set_role_permissions(url=`url`, role=`role`, permissions=`permissions`, grantable=`grantable`))*. diff --git a/ext/security/tenant.mq.md b/ext/security/tenant.mq.md deleted file mode 100755 index 4df9786..0000000 --- a/ext/security/tenant.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: Request tenant selection for database-backed web resources -import: - plugin: lib/plugin.mq.md ---- - -Tenant selection identifies a request context; authentication and membership are separate decisions. Pair this leaf with explicit scoped routes in ext/data/api.mq.md. Use it before listening and retain the returned application after every binding. The implementation reuses the existing native tenant resolver. - -## attach - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared application to receive tenant context | -| mode | text | "path" | path, subdomain or header | -| param | text | "t" | Path capture/query key or header name; use X-Tenant-Id explicitly for header mode | -| column | text | "tenant_id" | Database column used by scoped queries | -| default_scope | bool | False | Native default scoping for supported database-backed request handlers | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Updated application with native request tenant resolution | - -Use `app`, `mode`="path", `param`="t", `column`="tenant_id" and `default_scope`=False. Path mode first resolves the named route capture, then its query key, then the documented path segments. Subdomain mode uses the first label of a host with at least three labels. Header mode reads the selected header. The native resolver lowercases and keeps ASCII letters, digits, underscores and hyphens; it is not a general tenant-name codec. - -Grant plugin and keep the returned application. A later scoped JSON route rejects a missing resolved tenant and adds the tenant-column filter. The default flag applies only to native handlers that support it; ordinary direct database calls do not gain automatic request context. Tenant ids arriving from query parameters, headers or hostnames must be checked against authenticated membership by the application's actual policy. - -The local two-tenant example intentionally allows anonymous selection to demonstrate filtering. That behavior cannot establish production access isolation between users. No database row is changed and no socket opens in this binding. Develop resolver behavior in the native tenant package, and verify both selected tenants plus a request without a selector. - -We **native = [Resolve the maintained tenant implementation](plugin.native_path(name="web"))** and **[Load the existing request-context boundary](plugin.load(path=`native`))**. -Return *[Attach the explicit request tenant policy](web_app_tenant(app=`app`, mode=`mode`, param=`param`, column=`column`, default_scope=`default_scope`))*. diff --git a/ext/security/鉴权.mq.md b/ext/security/鉴权.mq.md deleted file mode 100755 index 816a65f..0000000 --- a/ext/security/鉴权.mq.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -markup: occlusion -title: 为准备好的应用绑定鉴权 -import: - auth: ext/security/auth.mq.md ---- - -本文件提供 auth.mq.md 的服务端绑定中文入口。凭据验证、会话和路径门禁是不同责任:本入口配置登录会话,业务端点与表单仍需显式访问策略。它不会把隐藏链接当作授权。账户表中的明文密码只适合本地夹具;真实用户应使用英文资源的 hash_password 生成受支持的口令散列,避免记录秘密。 - -## 绑定 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | 必填 | 已准备并按需启用原生后台的应用 | -| 用户 | any | 必填 | username、password、role 凭据表,或原生用户库配置 | -| 会话时长 | number | 3600 | 会话寿命,单位为秒 | -| 后台前缀 | text | "/admin" | 启用原生后台时安装默认门禁的路径前缀 | -| 登录路径 | text | "/login" | 实际 GET 与 POST 登录地址 | -| 登录返回 | text | "" | 成功登录后的可选目标 | -| 退出返回 | text | "" | 退出后的可选目标 | -| 注册 | bool | False | 明确启用用户注册;默认关闭 | -| 注册路径 | text | "/register" | 启用注册后的系统地址 | -| 默认角色 | text | "user" | 新注册用户的角色 | -| 会话地址 | text | "" | 可选外部会话存储 URI | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 保留原有资源、附加登录和会话策略的新应用 | - -使用`应用`、`用户`、`会话时长`=3600、`后台前缀`="/admin"、`登录路径`="/login"、`登录返回`=""、`退出返回`=""、`注册`=False、`注册路径`="/register"、`默认角色`="user"及`会话地址`=""。在监听前授权 plugin 并保留新应用。这里不认证某一次请求,也不启动监听。 - -原生后台应先启用再绑定鉴权,业务接口的 Endpoint 元数据或显式门禁继续决定所需的身份和角色。注册必须明确启用,外部会话后端另需可用连接。配置成功不能替代拒绝与接受凭据的真实验收;用户数据与口令不要写入检视结果或日志。 - -绑定完成后返回 *[配置原生登录与会话策略](auth.attach(app=`应用`, users=`用户`, session_ttl=`会话时长`, admin_prefix=`后台前缀`, login_path=`登录路径`, login_redirect=`登录返回`, logout_redirect=`退出返回`, register=`注册`, register_path=`注册路径`, default_role=`默认角色`, session_url=`会话地址`))*。 - - -## 门禁 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | 必填 | 已准备且保留实际资源的应用 | -| 路径 | text | 必填 | 需实际保护的服务器路径 | -| 角色 | any | "admin" | 允许的角色逗号文本或列表 | -| 权限 | text | "" | 可选权限逗号文本,沿用原生任一匹配 | -| 匹配 | text | "prefix" | prefix 前缀或 exact 精确匹配 | -| 拒绝 | text | "forbid" | forbid 禁止或 redirect 让匿名访问转登录 | -| 排除 | any | None | 可选路径排除;原生登录和退出仍保持可用 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 附加实际服务器访问策略的新应用,尚未监听 | - -使用`应用`、`路径`、`角色`="admin"、`权限`=""、`匹配`="prefix"、`拒绝`="forbid"及`排除`=None,在监听前授权 plugin 并保留返回值。本安全资源保护实际请求,不因导航隐藏链接就认定地址安全。前缀覆盖本路径及其斜杠子路径,登录和退出按原生规则排除,避免鉴权循环。 - -给出权限时采用原生权限匹配,而不是角色清单;任一所需权限命中即可。redirect 只让匿名拒绝转向登录,已登录但不足权限仍收到禁止。表单与 API 还应按实际数据策略保护自己的提交路径;不能只给展示页面加门禁就宣称所有写入已私有化。 - -绑定完成后返回 *[将明确的访问规则交给安全资源](auth.gate(app=`应用`, path=`路径`, roles=`角色`, permissions=`权限`, match=`匹配`, on_deny=`拒绝`, exclude=`排除`))*。 diff --git a/ext/web/README.md b/ext/web/README.md deleted file mode 100755 index 28cd38a..0000000 --- a/ext/web/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# ext/web — Document / Endpoint / Resource - -Official dynamic site extension (**ADR 0007**). - -| Doc | Link | -|-----|------| -| Artifact model | [`doc/design/ext-web-artifact.md`](../../doc/design/ext-web-artifact.md) | -| **Layout engineering** | [`doc/design/ext-web-layout-paradigm.md`](../../doc/design/ext-web-layout-paradigm.md) | -| skill=tools paradigm | [`doc/design/ext-skill-tools-paradigm.md`](../../doc/design/ext-skill-tools-paradigm.md) | - -| Surface | Path | -|---------|------| -| EN root skill (zero-context site playbook) | `ext/web/index.mq.md` | -| EN author facade | `import web:ext/web/web.mq.md` | -| ZH root skill (zero-context playbook) | `ext/web/网页/索引.mq.md` | -| ZH author facade | `导入 网页:ext/web/网页.mq.md` | -| Modules | `page/` · `route/` · `component/` · `dom/` · `client/` · `layout/` | -| ZH modules | `网页/页面/` · `网页/路由/` · `网页/组件/` · … | -| Layout tools | `ext/web/layout/index.mq.md` · `ext/web/布局/索引.mq.md` | - -**Facade:** `page` · `route` · `serve` · `render` · `inspect` · `use` - -**Layout law:** partition pages into files (nav / sidebar / main / footer / …) until each piece is simple; bind via `|type|slot|value|attrs|style|`. Do **not** build sites by HTML/CSS injection (`dom.raw` is escape hatch only). - -**Related modules:** `ext/data` · `ext/security` · `ext/net` - -```bash -bash scripts/build-web-plugin.sh -marqdo ext add web -marqdo call ext/web/layout/index.mq.md rules --json -marqdo call ext/web/index.mq.md preview_markdown 'body="# Hi"' 'title="Demo"' --effects plugin --json -marqdo run examples/marqdo-blog/serve.mq.md -``` - -Hard rules: no author `ensure_plugin` / `compose_*` / `configure` junk drawer; View schema only; declared vs system routes via `inspect`; no `MARQDO_EXT=repo/ext` self-install. - -The [executable handbook](index.mq.md) and [Chinese handbook](网页/索引.mq.md) -now include recursive layout constructors and tested source examples. Start with -[the reference site](../../examples/web-layout-handbook/index.mq.md): parents -compose one relationship, terminal content.md files stay ordinary Markdown. -The footer splits into brand/links, and links splits again into docs/community. -See [implementation and acceptance](../../doc/design/ext-web-handbook.md). - -Composed Documents explicitly declare `view: main`; main returns nested View -rows for startup assembly. Ordinary Markdown Documents keep their existing path. -Use `web.inspect root=...` to scan disk declarations; empty fresh app state cannot -inspect another process. `call` previews, while `run serve.mq.md` starts a server. diff --git a/ext/web/_capability/index.mq.md b/ext/web/_capability/index.mq.md deleted file mode 100755 index f9a5b13..0000000 --- a/ext/web/_capability/index.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -title: ext/web/_capability -description: >- - Web ABI load skill. Prefer domain modules; call load when diagnosing plugins. -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md ---- - -This boundary loads the native Go web plugin. Domain render/server tools load -it automatically; pure layout and component constructors do not need it. - -```sh -marqdo call ext/web/_capability/index.mq.md load --effects plugin --json -``` - -Build with bash scripts/build-web-plugin.sh, or install with marqdo ext add web. -For local development set MARQDO_WEB_PLUGIN to the built library's absolute path. -Success returns null; missing libraries also require checking process status. -Only this boundary imports lib/plugin, including through the Chinese facade. - -## load - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | null after a successful load | - -Locate the ABI v2 web shared library through plugin.native_path, then -plugin.load it. If the library is missing, print a short install hint and exit -non-zero so CI and agents fail loudly. After a successful load, later web star -names are available in this process. This is the only sanctioned place in the -package that talks to lib/plugin for web. Domain skills call load at the start -of each tool that needs the native server or renderer. - -This tool takes no parameters. - -We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. -1. `p` - We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. -2. * - We **[Print the prepared message](print(text="ext/web: native web plugin not found (build plugins/web or marqdo ext add web)"))**. - We **[End this run with the selected exit status](sys.exit(code=1))**. -Return *None*. diff --git a/ext/web/client/index.mq.md b/ext/web/client/index.mq.md deleted file mode 100755 index bdc1838..0000000 --- a/ext/web/client/index.mq.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -markup: occlusion -title: ext/web/client -description: Browser Runtime helpers (WASM bridge). Prefer lib/browser for effect tables (ADR 0007). -import: - cap: ext/web/_capability/index.mq.md - table: lib/table.mq.md - component: ext/web/component/index.mq.md - html: lib/html.mq.md ---- - -Browser helpers describe the official Marqdo WASM bridge and small effects. -They construct text/maps without a native server. Keep initial page layout in -[layout components](../layout/index.mq.md), and use lib/browser for client logic. - -```sh -marqdo call ext/web/client/index.mq.md embed --json -marqdo call ext/web/client/index.mq.md text_patch 'sel="#status"' 'text="Ready"' --json -``` - -The bridge and WASM assets must actually be hosted at the chosen URLs. embed -returns a loading descriptor; it does not install assets or implement business -JavaScript. Native HTML snippets here are runtime integration, not an invitation -to put complete navigation/footer markup in authored content. Changes require -browser bridge tests and matching Chinese entry points. - -## embed - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| bridge | text | "/static/marqdo-bridge.js" | bridge script URL | -| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL | -| source | text | "" | optional source URL | -| boot | bool | True | auto boot | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | HTML script tag | - -Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="", `boot`=True as the inputs for this operation. - -HTML snippet that loads the official browser Marqdo bridge (route C/D). Defaults: - -`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", - -`source`="", `boot`=True . With boot and non-empty source, auto-mounts. No author -JS. Not a substitute for file-partitioned Document layout. - -We **bridge = [Escape the bridge URL as an attribute value](html.escape(text=`bridge`))** and **wasm = [Escape the WASM URL as an attribute value](html.escape(text=`wasm`))** and **source = [Escape the client source URL as an attribute value](html.escape(text=`source`))**. -1. `boot` - 1. `source` != "" - Return *""*. - 2. * - Return *""*. -2. * - Return *""*. - -## text_patch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | text | required | CSS selector | -| text | text | required | text content | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | effects map | - -Use `sel`, `text` as the inputs for this operation. - -Build a `set_text` effects map for selector `sel` with string `text`. Prefer -lib/browser in client .mq.md programs; this helper is for call-side sketches. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`text`))**. -Return *[Set the set_text field in the new record](table.put(in=None, at="set_text", value=`m`))*. - -## dom_patch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | text | required | CSS selector | -| html | text | "" | optional HTML | -| attrs | any | None | optional attrs map | -| remove | bool | False | remove node | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | effects map | - -Use `sel`, `html`="", `attrs`=None, `remove`=False as the inputs for this operation. - -Build a `dom` effects map for selector `sel`. Optional `html`="", `attrs`=None, - -`remove`=False . Prefer View/Markdown over raw html patches for page shells. - -We retain **`spec` = [Set the html field in the new record](table.put(in=None, at="html", value=`html`))**. -1. `attrs` - We retain **`spec` = [Set the attrs field in the new record](table.put(in=`spec`, at="attrs", value=`attrs`))**. -2. * - **_ = 1** -1. `remove` - We retain **`spec` = [Set the remove field in the new record](table.put(in=`spec`, at="remove", value=True))**. -2. * - **_ = 1** -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`spec`))**. -Return *[Set the dom field in the new record](table.put(in=None, at="dom", value=`m`))*. - -## nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| bridge | text | "/static/marqdo-bridge.js" | URL of the official browser bridge | -| wasm | text | "/static/marqdo_wasm.wasm" | URL of the built WASM artifact | -| source | text | "" | Optional Marqdo client program URL | -| boot | bool | True | Whether the bridge automatically mounts the client | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Structured script Resource rows for a component Document | - -Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="" and `boot`=True in a component tree. The resource references the official bridge as a module and retains the WASM and source addresses as typed attributes. Boot with a nonempty source mounts that Marqdo program; boot=False declares the bridge without automatic mounting. This pure tool creates no server, downloads nothing and writes no JavaScript or HTML. Build the current WASM artifact and mount the actual static directory before serving the page. Prefer these rows to embed when a Document already returns View nodes; embed remains a compatibility string adapter. - -`attributes` = - -| type | data-mq-wasm | -|---|---| -| module | `wasm` | - -1. `boot` and `source` != "" - We **attributes = [Declare the client program to mount](table.put(in=`attributes`, at="data-mq-source-url", value=`source`))**. -1. not `boot` - We **attributes = [Keep automatic mounting disabled](table.put(in=`attributes`, at="data-mq-no-boot", value="1"))**. -Return *[Declare the official bridge as a structured resource](component.asset(url=`bridge`, attrs=`attributes`, slot="marqdo-runtime"))*. diff --git a/ext/web/component/index.mq.md b/ext/web/component/index.mq.md deleted file mode 100755 index ee062cd..0000000 --- a/ext/web/component/index.mq.md +++ /dev/null @@ -1,224 +0,0 @@ ---- -markup: occlusion -title: ext/web/component -description: Pure components: Markdown leaves and nested View rows. -import: - table: lib/table.mq.md ---- - -Components are ordinary functions returning View rows. A leaf contains Markdown; -a parent names its child components and one layout relationship. Stop splitting -when one file expresses one readable content responsibility. If a footer has a -brand area and a link area, split those; if links has two columns, split again. -The executable reference is [web-layout-handbook](../../../examples/web-layout-handbook/index.mq.md). - -Pure construction experiment — no native plugin or session is required: - -```sh -marqdo call ext/web/component/index.mq.md markdown 'text="## A readable leaf"' 'slot="intro"' --json -marqdo call ext/web/component/index.mq.md wrap 'children=[{"type":"markdown","value":"Left"},{"type":"markdown","value":"Right"}]' 'kind="row"' --json -marqdo call ext/web/component/index.mq.md merge 'a=[{"type":"text","value":"First"}]' 'b=[{"type":"text","value":"Second"}]' --json -``` - -Use @ record tables to return lists of node maps. merge concatenates these lists; -it does not turn a flat table into columns. wrap keeps child rows in value; -[layout](../layout/index.mq.md) supplies stack and columns helpers for the same -schema. Only [page.render](../page/index.mq.md) needs the native renderer. - -Development route: add reusable content in the site's component directories; -add a new structural kind only when stack, columns and Markdown cannot express -it. Update the Go artifact renderer and its tests, then both language helpers. -Never put rendered HTML strings in parent value cells to simulate nesting. - -## nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | View table | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | The supplied View table unchanged, preserving its original list or column-table shape | - -Use `table` as the inputs for this operation. - -Return View `table` unchanged. This preserves the existing identity helper for -column tables as well as record lists. Prefer @ record lists for reusable -components, because list composition can retain typed nested value cells. - -Return *table*. - -## merge - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | list | required | First node record list | -| b | list | required | Second node record list | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Ordered sibling rows | - -Use `a`, `b` as the inputs for this operation. - -Concatenate `a` and `b` without rendering or flattening child containers. -Both inputs must be lists of View rows, normally @ record tables. To place -two components side by side, concatenate their wrapped columns then use -layout.columns; concatenation alone only establishes sibling order. - -Return *[Concat](table.concat(a=`a`, b=`b`))*. - -## markdown - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Plain Markdown content | -| slot | text | "" | Stable component name | -| style | text | "" | Optional class name | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | One Markdown leaf | - -Use `text`, `slot`="", `style`="" as the inputs for this operation. - -Make a leaf from Markdown `text`. Default `slot`="" and `style`="" keep -content independent of placement and theme. The returned list contains one -markdown row; the runtime renders headings, links, lists and tables. No native -plugin is loaded here, and no HTML is inserted into the authored component. - -`nodes` = - -| @ | type | slot | value | attrs | style | -|---|------|------|-------|-------|-------| -| 1 | markdown | `slot` | `text` | "" | `style` | - -Return *nodes*. - -## wrap - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| children | list | required | Child node records | -| kind | text | "column" | Container kind | -| slot | text | "" | Stable region name | -| style | text | "" | Optional class name | -| attrs | any | None | Attribute record for the container, such as id or hidden | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | One parent containing its child rows | - -Use `children`, `kind`="column", `slot`="", `style`="", `attrs`=None as the inputs for this operation. - -Wrap `children` in one structural row. Default `kind`="column", `slot`="" -and `style`="" . Use row or column for geometry, nav/header/footer/section/aside; form/list/item/select preserve native controls -for a semantic region. The value cell holds the child list itself, not rendered -HTML. The native renderer diagnoses unknown child shapes at the render boundary; -this pure constructor does not claim to validate a full site. - -`nodes` = - -| @ | type | slot | value | attrs | style | -|---|------|------|-------|-------|-------| -| 1 | `kind` | `slot` | `children` | `attrs` | `style` | - -Return *nodes*. - -## element - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| kind | text | required | Native leaf kind: input, button, textarea, label, pre, option, text or link | -| value | text | "" | Plain control text or initial input value | -| attrs | any | None | Typed attribute record; legacy text href also works for links | -| slot | text | "" | Stable layout slot | -| style | text | "" | Optional CSS class names | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One leaf in the existing five-column View schema | - -Use `kind`, `value`="", `attrs`=None, `slot`="" and `style`="" when Markdown cannot express a native input or client event target. Supply ids and field names as a record, boolean flags as booleans, and labels as plain text. The renderer escapes values and attribute content; value is never interpreted as HTML. For forms, lists and semantic regions, use wrap with child rows. The constructor is pure; supported kinds, scalar attribute values and forbidden event/style attributes are checked when rendering. Client state belongs in data/aria attributes, while style names reference the page's stylesheet. This keeps controls inspectable without embedding a complete page as HTML. - -`nodes` = - -| @ | type | slot | value | attrs | style | -|---|---|---|---|---|---| -| 1 | `kind` | `slot` | `value` | `attrs` | `style` | - -After describing this control we return *nodes*. - - - -## asset - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Explicit script or stylesheet URL served by the application | -| kind | text | "script" | script or stylesheet | -| attrs | any | None | Typed attributes such as module type, integrity or data-mq options | -| slot | text | "" | Optional stable resource slot | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One structured resource leaf in the same five-column View schema | - -Use `url`, `kind`="script", `attrs`=None and `slot`="" for an existing resource that the browser must load. A script leaf carries only a URL, never inline author JavaScript; a stylesheet leaf references a separate CSS artifact. Its address stays in value, while attrs holds scalar metadata. The native renderer escapes the URL and attributes, forbids duplicate src/href/rel attributes and rejects script-protocol URLs. Construction is pure and fetches nothing. Keep resource declarations beside the Document component that needs them, after layout and content have been split. The browser loads the actual files when that Document is opened; a node record is not proof that the resource exists. - -`nodes` = - -| @ | type | slot | value | attrs | style | -|---|---|---|---|---|---| -| 1 | `kind` | `slot` | `url` | `attrs` | "" | - -After declaring this resource we return *nodes*. - - - -## resource - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | map | required | Typed data_query, form_ref, view_navigation or pure document_head Resource | -| slot | text | "" | Stable component slot for this dynamic region | -| style | text | "" | Optional wrapper class names | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One resource node in the existing five-column View schema | - -Use `value`, `slot`="" and `style`="" to place a resource supplied by its responsible module. Database query resources come from ext/data/view.mq.md; form references from ext/data/form.mq.md; navigation uses the helper below; pure head declarations come from ext/web/head.mq.md. The resource remains a typed value in the value cell, preserving readable composition and its actual input contract. - -Construction is pure and does not query data, load a plugin or submit a form. Serving resolves the resource after preparing request parameters, session state and CSRF. Unknown resources fail before listening; missing runtime resources remain request errors. Offline rendering without a request resolver reports missing context for query, form and session navigation. Pure document_head resources are supported by offline preview and collected into the actual head, never shown as body content. - -`nodes` = - -| @ | type | slot | value | attrs | style | -|---|---|---|---|---|---| -| 1 | resource | `slot` | `value` | None | `style` | - -Return *nodes* for the parent layout to place alongside static Markdown and controls. - -## navigation - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| items | any | required | Link records with label, href and optional when, class or media | -| region | text | "nav" | nav, sidebar or footer | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Pure navigation Resource, to be placed with component.resource | - -Use `items` and `region`="nav" for session-aware link presentation. Link rows describe destinations; when=guest or auth uses the request's actual session. Empty conditions keep links visible. The native navigation renderer retains its existing classes and conditional visibility, while the recursive parent component still owns placement and geometry. - -This constructor does not authenticate a user or register a route. Hiding a link cannot protect its destination from direct access. The server must separately attach actual authentication and authorization gates. Reading or constructing navigation never logs in or out; that behavior belongs to the destination's explicit resource and route. - -`resource` = - -| _type | items | region | -|---|---|---| -| view_navigation | `items` | `region` | - -Return *resource* for explicit placement in the same five-column View. diff --git a/ext/web/dom/index.mq.md b/ext/web/dom/index.mq.md deleted file mode 100755 index 4a888bc..0000000 --- a/ext/web/dom/index.mq.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -markup: occlusion -title: ext/web/dom -description: >- - DOM Artifact — Markdown/body to structure; raw HTML is escape hatch only - (ADR 0007). Never use raw as the default homepage method. -import: - cap: ext/web/_capability/index.mq.md - table: lib/table.mq.md ---- - -DOM helpers separate Markdown content from HTML rendering. Prefer -[component.markdown](../component/index.mq.md) for layout leaves. from_markdown -and raw only construct data and need no plugin; render needs --effects plugin. - -```sh -marqdo call ext/web/dom/index.mq.md from_markdown 'text="# Readable"' --session handbook --toget body --json -marqdo call ext/web/dom/index.mq.md render 'dom=$body' --effects plugin --session handbook --json -``` - -raw remains an explicit compatibility escape hatch, not a homepage layout -method. Add content behavior through Markdown/render and preserve the existing -raw path; do not use raw to compensate for missing decomposition. - -## from_markdown - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Markdown source | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | DOM map | - -Use `text` as the inputs for this operation. - -Turn Markdown `text` into a simple DOM map `{kind:"markdown", text}` for -`page.render` / `web.render`. This is the default body path for Document prose. - -We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value="markdown"))**. -Return *[Set the text field in the new record](table.put(in=`out`, at="text", value=`text`))*. - -## raw - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| html | text | required | raw HTML (escape hatch) | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | DOM map kind=raw | - -Use `html` as the inputs for this operation. - -Escape hatch — wrap raw `html`. Prefer Markdown / View nodes. Allowed only when -table-driven layout cannot express a host constraint; document the why next to -the call. Forbidden as the primary implementation of nav/sidebar/footer/home. - -We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value="raw"))**. -Return *[Set the html field in the new record](table.put(in=`out`, at="html", value=`html`))*. - -## render - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dom | any | required | DOM map from from_markdown or raw | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML text | - -Use `dom` as the inputs for this operation. - -Render DOM Artifact `dom` (from from_markdown or raw) to HTML via the native -plugin. When kind is markdown, -the plugin turns Markdown text into HTML for Document preview. When kind is raw, -the stored HTML string is returned unchanged — that path exists only for the -escape hatch documented on raw, not for assembling a full site shell. Prefer -feeding markdown DOM produced by from_markdown, or skip this helper and use -page.render / web.render on View tables from file-partitioned components. - -We **[Load the native plugin required by this operation](cap.load())**. -We retain **`kind` = [Read kind field](access(`dom`, "kind"))**. -1. `kind` == "raw" - We retain **`html` = [Read html field](access(`dom`, "html"))**. - Return *html*. -2. * - We retain **`text` = [Read text field](access(`dom`, "text"))**. - Return *[Render DOM Artifact dom (from from_markdown or raw) to HTML via the native plugin](web_dom_markdown(text=`text`))*. diff --git a/ext/web/head.mq.md b/ext/web/head.mq.md deleted file mode 100755 index 5968bbf..0000000 --- a/ext/web/head.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: Document head Resource — SEO, fonts and resource links ---- - -Use this single-file resource inside the existing five-column View schema. It preserves metadata and native head links when a structured Document owns the page body. Place its returned value through component.resource alongside the layout. The renderer collects it into the actual head, leaving no visible placeholder in body or fragment responses. No new Markdown mark, frontmatter dialect or page mutation chain is involved. - -Construction is pure. Rendering validates the closed contract, escapes metadata and uses the same head-link renderer as ordinary Documents. It does not fetch a font, execute a script or prove an external resource exists. Browsers load the declared URLs only when they open the real page. A local pure construction example is ready from the checkout: - -```sh -marqdo call ext/web/head.mq.md resource 'meta=[{"key":"description","value":"A readable site"}]' --json -``` - -## resource - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| meta | any | None | key/value records or a GFM column table; scalar SEO values | -| links | any | None | Native rel/href link records, including optional type, media, crossorigin, defer and async | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Pure document_head descriptor for component.resource; no IO | - -Use `meta`=None and `links`=None to declare only what this Document needs. Metadata includes description, og: names and other native SEO names. Native title overrides and canonical/icon link keys retain ordinary Document behavior. Charset, viewport and csrf-token remain owned by the runtime and cannot be redeclared here. An empty descriptor contributes no metadata rather than fabricating a page result. - -Links reuse the existing native field aliases, with rel selecting stylesheet, preconnect, preload, icon, script or module behavior. URLs must start with / for site resources or use http(s); protocol-relative URLs, active data schemes and malformed cells fail. Use the official client nodes for the browser bridge rather than inlining business JavaScript. A link does not mount a file or register a server route. - -Nested layout modules can contribute head resources. Equal link declarations are deduplicated; conflicting values for the same metadata key are diagnostics rather than silently replacing each other. Fragments omit these declarations because they update an existing Document, while offline preview supports this pure resource without inventing a request session. Request-dependent data, form and navigation resources still require their actual request renderer. - -`head` = - -| _type | meta | links | -|---|---|---| -| document_head | `meta` | `links` | - -After describing the actual metadata and resource addresses, return *head* for explicit placement by the parent component. diff --git a/ext/web/index.mq.md b/ext/web/index.mq.md deleted file mode 100755 index 8bec5cb..0000000 --- a/ext/web/index.mq.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -markup: occlusion -title: ext/web -description: Executable web handbook: decompose layout down to Markdown leaves. -import: - layout: ext/web/layout/index.mq.md - web: ext/web/web.mq.md ---- - -Web handbook — split page structure first, author content second, then preview, -serve and verify. Ordinary .mq.md functions are the tools; no separate Skill -compiler or manifest is needed. Install with marqdo ext add web. In this source -repo build with bash scripts/build-web-plugin.sh and optionally select its -absolute path with MARQDO_WEB_PLUGIN. Keep installation outside source ext. - -Start with executable evidence - -Run these from the repository root; installed users replace FILE with its actual -installed path. Preserve the inner text quotes and protect dollar references -from shell expansion. Inspect process status and ok before consuming result. - -```sh -marqdo call ext/web/index.mq.md layout_rules --json -marqdo call ext/web/index.mq.md preview_markdown 'body="# Readable page"' 'title="Preview"' --effects plugin --json -marqdo call ext/web/index.mq.md preview_nodes 'nodes=[{"type":"row","value":[{"type":"markdown","value":"## Left"},{"type":"markdown","value":"## Right"}]}]' --effects plugin --json -``` - -The engineering method: recursively decompose to Markdown leaves - -Split home into navigation, main and footer. Split a two-region footer into -brand and links. If links still contains two columns, split it again into docs -and community. Continue while a block needs independent internal layout. Stop -at one simple Markdown responsibility, not at one file per paragraph. - -```text -site/ - index.mq.md Document selects the layout root - components/index.mq.md stack navigation, main, footer - nav/index.mq.md - nav/content.md ordinary Markdown links - main/index.mq.md - main/content.md ordinary Markdown prose - footer/index.mq.md columns: brand, links - brand/index.mq.md - brand/content.md brand and copyright - links/index.mq.md columns: docs, community - docs/index.mq.md - docs/content.md - community/index.mq.md - community/content.md - pages/about.mq.md another declared page - api/ping.mq.md Endpoint - preview.mq.md assemble and render offline - serve.mq.md process launcher, no page content -``` - -A parent index imports children, combines their rows and declares one layout -relationship. A terminal content.md is plain Markdown. Split again if a parent -contains long content, multiple layout responsibilities or HTML tags. A leaf -does not decide its external placement. Cutting a large HTML string into files -still hides the structure in strings. Forms, data sources and interaction need -their own responsibilities; they do not justify restoring an HTML page shell. - -Follow the real project - -The [English reference](../../examples/web-layout-handbook/index.mq.md) implements -this tree. Follow its [component root](../../examples/web-layout-handbook/components/index.mq.md) -to footer grandchildren. The [Chinese reference](../../examples/web-layout-handbook-zh/index.mq.md) -uses the same representation and renderer. Preview from the repo root, then -change into the site directory to start the process: - -```text -marqdo call examples/web-layout-handbook/preview.mq.md main --effects plugin,fs.read,output.write --fs-root examples/web-layout-handbook --json -marqdo call ext/web/web.mq.md serve 'root="examples/web-layout-handbook"' --effects plugin,fs.read,network.write --fs-root examples/web-layout-handbook --json -``` - -Check /, /about and /api/ping. The first is a genuinely nested layout, the second -an ordinary Document, and the third JSON. Wide layouts show columns; narrow -layouts collapse without authored HTML or CSS. - -One View representation for both parents and leaves - -Public columns remain type, slot, value, attrs, style, with Chinese aliases -类型、槽、值、属性、样式. Use @ record tables for lists of node maps. A row/column -container holds child rows in value. nav/header/footer/section/aside supply -semantic regions. A markdown value is content text. Merging defines sibling -order, not geometry: use columns to establish side-by-side placement. A style -cell references class names; it neither defines CSS nor silently compiles a theme. -Runtime defaults supply the basic responsive geometry. - -Short leaves can pass Markdown directly; longer leaves read a content.md as in -the reference. Parents retain structural values rather than rendering children -before composition. This small executable program demonstrates the relationship; -real sites put each responsibility into the files shown above. - -```marqdo ---- -markup: occlusion -import: - component: ext/web/component/index.mq.md - layout: ext/web/layout/index.mq.md - web: ext/web/web.mq.md ---- - -# main - -**left = component.markdown text="### Brand" slot="brand"** -**right = component.markdown text="[About](/about)" slot="links"** -**siblings = component.merge a=`left` b=`right`** -**footer = layout.columns children=`siblings` slot="footer"** -**html = web.render nodes=`footer` title="Column preview"** -> print text=`html` -``` - -Document, Endpoint and lifecycle boundaries - -Ordinary Documents declare type: web, route and title around Markdown body, -retaining the existing Markdown/data-source path. A composed Document also -declares view: main: its ordinary main function returns View rows. serve executes that assembly -once at startup and uses the same renderer as offline preview. Restart after -content changes. Automatic data_source binding uses ordinary Documents and -cannot be mixed with startup assembly. Assembly returns structure; it must not render again or launch -a server. Request-time interaction belongs in Endpoints with type, path, method, -request and response metadata. Startup assembly is not an automatic request-time -template/data-binding system. - -serve is a blocking lifecycle operation callable with marqdo call. Grant -plugin,fs.read,network.write for a site that reads Markdown and listens. For -additional resources, compose web.prepare, resource-owned bindings and -web.listen in an ordinary callable launcher. Keep each returned app value. -For current database rows, forms and session-aware navigation, place the typed resources from -ext/data and component.navigation inside the same View tree. Pure document_head resources -preserve SEO and font links in previews as well as responses; they never become body content. -See [the request-resource design](../../doc/design/web-view-resources.md) and the real -[network site](../../examples/web-net-site/index.mq.md). -The network library owns WebSocket routes; the security library owns login -and session policy. Preparing a site opens no listener. -inspect with root scans disk declarations without listening; an empty app in a -fresh process cannot inspect another process's private state. - -```sh -marqdo call ext/web/web.mq.md inspect 'root="examples/web-layout-handbook"' --effects plugin --json -``` - -Open the module for the next responsibility - -[layout](layout/index.mq.md) supplies decomposition, stack and columns; -[component](component/index.mq.md) supplies Markdown leaves and semantic wrappers; -[page](page/index.mq.md) supplies handles and offline render; -[route](route/index.mq.md) is for explicit advanced registration, while whole -sites normally use Metadata. [dom](dom/index.mq.md) converts content, retaining -raw HTML only at a compatibility boundary. [head](head.mq.md) contributes pure SEO/font/resource declarations to the real document head; -[client](client/index.mq.md) loads -the official Marqdo WASM bridge; business effects stay in lib/browser. -[_capability](_capability/index.mq.md) diagnoses loading. The [facade](web.mq.md) -keeps serve/render/inspect and the app API. Data, auth and HTTP clients belong -to ext/data, ext/security and ext/net. [Chinese handbook](网页/索引.mq.md). - -Develop and accept a change - -Compose Markdown, stack and columns before inventing a primitive. Only genuinely -new structural capability needs plugins/web/internal/artifact and ABI changes; -ordinary pages need no new host primitive. Keep bilingual helpers and the five -columns aligned. Put parameter contracts after headings and return contracts -before execution. ## is a callable heading, not ordinary document sectioning. -Update src/ext_cli.rs if adding package files. Preserve ordinary Documents and -Endpoints when changing startup assembly. - -```text -marqdo call skills/marqdo-dev/index.mq.md test 'targets=["web_handbook"]' --effects plugin,process.exec --require-ok --json -marqdo call skills/marqdo-dev/index.mq.md test 'targets=["call_cli","gold"]' 'filter="web"' --effects plugin,process.exec --require-ok --json -``` - -Handbook tests execute the bilingual sh fences and author examples directly, -then preview and serve the real reference tree to check structure, routes and -API behavior. Narration ratio is a minimum, not proof of usability. A checklist -cannot truthfully accept a component without inspecting its implementation. -This package does not automatically decompose arbitrary pages or implement a -full CSS compiler through the style cell; explicit design remains the author's -responsibility, made followable and testable by these indexes. - -## site_playbook - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Development workflow and stopping rule | - -Return the workflow and stopping rule without creating files or claiming to -accept a particular site. Define the region tree, author parents and Markdown -leaves, then start and test the declared HTTP surface. - -The returned rows are a planning aid, not a generated site or a validation certificate. Start with the component tree, give each parent one placement decision, then write the leaves as ordinary Markdown. Declare request-time handlers separately from startup assembly. Preview the composed result before starting the server, and compare real routes and narrow-screen geometry against that same source tree. - -`workflow` = - -| key | value | -|-----|-------| -| goal | build a site as executable documents | -| step_A | draw region tree before content | -| step_B | recursively split components to Markdown leaves | -| step_C | declare home Document and view main for composed structure | -| step_D | declare more Documents with their own routes | -| step_E | declare Endpoint handlers for request-time work | -| step_F | call the blocking serve function with explicit site root and effects | -| step_G | compare preview and live output; test routes and browser geometry | -| stopping_rule | one Markdown responsibility and no internal layout | - -Return *workflow*. - -## layout_rules - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Development workflow and stopping rule | - -Reuse the layout module convention without a second rule catalog. No -parameters or plugin. Actual acceptance still inspects leaf responsibilities, -parent relationships and the running result. - -Return *[Rules](layout.rules())*. - -## preview_markdown - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| body | text | "" | Markdown content | -| title | text | "Preview" | Document title | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | HTML document | - -Use `body`="", `title`="Preview" as the inputs for this operation. - -Render Markdown `body`="" with default `title`="Preview" . -Return HTML text without writing files or registering routes. For a complex -page split the layout first; raw HTML strings are not the content strategy. -This tool needs the native plugin. - -Return *[Render](web.render(body=`body`, title=`title`))*. - -## preview_nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| nodes | list | required | Nested View rows | -| title | text | "Preview" | Document title | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | HTML document | - -Use `nodes`, `title`="Preview" as the inputs for this operation. - -Render decomposed `nodes` with default `title`="Preview" . -Parent values retain child rows, while leaf values hold Markdown. Returning -HTML starts no server. The same renderer serves composed Documents, so this -preview checks that column relationships survive assembly. - -Return *[Render](web.render(nodes=`nodes`, title=`title`))*. diff --git a/ext/web/layout/index.mq.md b/ext/web/layout/index.mq.md deleted file mode 100755 index 42ced02..0000000 --- a/ext/web/layout/index.mq.md +++ /dev/null @@ -1,172 +0,0 @@ ---- -markup: occlusion -title: ext/web/layout -description: Split structure first, recursively down to simple Markdown leaves. -import: - component: ext/web/component/index.mq.md ---- - -Engineering practice: draw the region tree before writing content. Home splits -into navigation, main and footer. Footer splits into brand and links; if links -has two columns, split again into docs and community. Continue while a region -needs independent internal layout. Stop at one readable Markdown responsibility, -not at an arbitrary number of files or one file per sentence. - -Follow the real [reference site](../../../examples/web-layout-handbook/index.mq.md). -Parent index.mq.md files import children and declare one layout relationship; -leaf content.md files contain ordinary Markdown. Splitting an HTML string into -several files does not make the structure document-native. - -```sh -marqdo call ext/web/layout/index.mq.md rules --json -marqdo call ext/web/layout/index.mq.md columns 'children=[{"type":"markdown","value":"Left"},{"type":"markdown","value":"Right"}]' 'slot="footer"' --json -``` - -columns preserves child rows in value and renders a responsive grid; narrow -screens collapse automatically. stack preserves top-to-bottom region order. -The style column references class names, not raw CSS or a theme definition. -Merging alone creates siblings, not columns. Use component.markdown for content -and component.wrap for semantic regions such as nav or footer. - -Development and acceptance: name each leaf by one content responsibility. If a -parent contains long prose or HTML tags, split further. Preview with page.render, -then serve and verify home, about and the API. New structural kinds belong in -plugins/web/internal/artifact with bilingual helpers and web_handbook tests. - -## rules - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Column table with aligned key/value lists describing layout rules; no source inspection | - -Return the engineering convention and stopping rule. No parameters or plugin. -This is guidance rather than evidence that a particular source file passes; -acceptance also requires reading the leaves and exercising the resulting page. - -Apply the stopping rule to responsibilities rather than file size. A footer with two independent groups still needs child regions even if its text is short. A leaf containing several ordinary paragraphs may remain one Markdown responsibility when it needs no internal geometry. The parent imports those children and places them; the renderer supplies the resulting container structure. This table records that convention but does not inspect your files or certify that a layout works. - -`out` = - -| key | value | -|-----|-------| -| paradigm | recursive file-partitioned layout | -| partition | home to nav/main/footer; footer to brand/links; links to docs/community | -| until_simple | one simple Markdown responsibility with no independent internal layout | -| view_schema | type slot value attrs style; parent value holds child rows | -| parent | import child components and choose one relationship | -| leaf | ordinary Markdown content without an HTML shell | -| geometry | merge gives siblings; stack and columns give placement | -| verify | offline render; live routes; narrow and wide browser geometry | - -Return *out*. - -## view_schema - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Public column names | - -Return the five public View columns. A container value holds more rows of -the same schema; a Markdown value holds content text. This keeps recursive -layout within one representation instead of adding a private fragment dialect. - -`cols` = - -| col | -|-----| -| type | -| slot | -| value | -| attrs | -| style | - -Return *cols*. - -## merge_nodes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | list | required | First node records | -| b | list | required | Second node records | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Ordered sibling nodes | - -Use `a`, `b` as the inputs for this operation. - -Concatenate `a` and `b` as siblings. This helper preserves structure and order -but does not imply geometry; use columns for side-by-side placement or stack -for a vertical page. The @ record lists retain nested values throughout. - -Return *[Merge](component.merge(a=`a`, b=`b`))*. - -## stack - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| children | list | required | Child component records | -| slot | text | "" | Parent region name | -| style | text | "" | Optional class name | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Parent container rows | - -Use `children`, `slot`="", `style`="" as the inputs for this operation. - -Declare one vertical relationship for `children`. Default `slot`="" and - -`style`="" . The parent owns placement while each imported child owns content -or its next decomposition level. Return View rows so another parent can wrap -them without first serializing any HTML. - -Return *[Wrap](component.wrap(children=`children`, kind="column", slot=`slot`, style=`style`))*. - -## columns - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| children | list | required | Child component records | -| slot | text | "" | Parent region name | -| style | text | "" | Optional class name | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Parent container rows | - -Use `children`, `slot`="", `style`="" as the inputs for this operation. - -Declare one responsive multi-column relationship for `children`. Default `slot`="" and - -`style`="" . The parent owns placement while each imported child owns content -or its next decomposition level. Return View rows so another parent can wrap -them without first serializing any HTML. - -Return *[Wrap](component.wrap(children=`children`, kind="row", slot=`slot`, style=`style`))*. - -## accept_component - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Component name | -| duty | text | required | One responsibility | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Checklist record with status, name, duty and check; it does not certify a component | - -Use `name`, `duty` as the inputs for this operation. - -Return a review checklist for component `name` and stated `duty`. Two strings -cannot establish source quality or a working layout, so this tool does not -return an unconditional ok=True. Verify the actual source and rendered page -before accepting the component. It never writes or scans files. - -`row` = - -| status | name | duty | check | -|--------|------|------|-------| -| checklist | `name` | `duty` | one Markdown leaf or one parent relationship; no raw HTML shell | - -Return *row*. diff --git a/ext/web/page/index.mq.md b/ext/web/page/index.mq.md deleted file mode 100755 index 6bb4c50..0000000 --- a/ext/web/page/index.mq.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -markup: occlusion -title: ext/web/page -description: >- - Document → View. Sole compose path is render(nodes=) with unified View schema - (ADR 0007). File-partition layouts; no HTML injection as default. -import: - cap: ext/web/_capability/index.mq.md - table: lib/table.mq.md ---- - -Documents hold body text or nested View rows. For reusable layout follow -[layout](../layout/index.mq.md); render is the shared offline path. A complete -session begins with new, saves the handle, then reads it with a protected reference. - -```sh -marqdo call ext/web/page/index.mq.md new 'title="Preview"' 'body="# Hello"' --effects plugin --session handbook --toget pg --json -marqdo call ext/web/page/index.mq.md render 'page=$pg' --effects plugin --session handbook --json -``` - -For a live structured Document declare view: main and return composed rows from -its main function; serve executes that assembly once at startup. Ordinary web -Documents retain their Markdown path. The reference site demonstrates both. -New behavior belongs here, in the Chinese mirror and the artifact renderer; -preserve tests/ext/web-artifact-render-smoke.mq.md and the handbook tests. - -## new - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| title | text | "" | document title | -| route | text | "/" | path | -| method | text | "GET" | HTTP method | -| body | text | "" | Markdown body | -| nodes | any | None | View table or None | -| data_source | text | "" | table name | -| data_order | text | "" | order key | -| data_where | text | "" | filters | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | page handle | - -Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation. - -Construct a Document handle with `title`="", `route`="/", `method`="GET", - -`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="", - -`data_where`="" keys. Prefer Artifact discovery via serve for production pages; -use this tool for previews and stepwise agent sessions. nodes must be the -unified View schema, never a private dialect or an HTML string shell. - -We **[Load the native plugin required by this operation](cap.load())**. - -`out` = - -| _type | title | route | method | body | nodes | data_source | data_order | data_where | -|-------|-------|-------|--------|------|-------|-------------|------------|------------| -| page | `title` | `route` | `method` | `body` | `nodes` | `data_source` | `data_order` | `data_where` | - -Return *out*. - -## render - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| page | any | required | Document handle | -| nodes | any | None | View table or None | -| db | any | None | optional database handle | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML or render payload | - -Use `page`, `nodes`=None, `db`=None as the inputs for this operation. - -Render Document handle `page` to HTML for preview or response. Optional - -`nodes`=None is the unified View table; when None, uses the page's own nodes or -Markdown body. Optional `db`=None is retained for facade compatibility. This offline renderer -does not populate data_source; automatic row binding belongs to served ordinary -Documents, or callers can materialize their content explicitly. -Prefer assembling nodes from file-partitioned components — do not pass a -handmade HTML string as the page shell. This is the sole compose path (ADR -0007); there is no compose_main or fragment DSL. Agents should call this free -tool (not a method chain) under `--effects plugin`. - -We **[Load the native plugin required by this operation](cap.load())**. -We retain **n = nodes**. -1. `n` == None - We retain **`n` = [Read nodes field](access(`page`, "nodes"))**. -2. * - **_ = 1** -We retain **`title` = [Read title field](access(`page`, "title"))**. -1. `n` - Return *[Render Document handle page to HTML for preview or response](web_render_nodes(page=`page`, nodes=`n`, db=`db`, title=`title`))*. -2. * - We retain **`body` = [Read body field](access(`page`, "body"))**. - Return *[Render Document handle page to HTML for preview or response](web_render_document(page=`page`, body=`body`, db=`db`, title=`title`))*. - -# page - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| title | any | "" | Document title used by preview and page rendering | -| route | any | "/" | Declared URL path at which this Document may be mounted | -| method | any | "GET" | HTTP request method for the declared route | -| body | any | "" | Markdown document content; complex sites use recursively split components | -| nodes | any | None | Nested View records, or None to retain document-body rendering | -| data_source | any | "" | Document data source declaration; empty means no automatic source | -| data_order | any | "" | Ordering declaration for the selected document data source | -| data_where | any | "" | Filter declaration for the selected document data source | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Document handle retaining title, route, method, body, nodes and data declarations | - -Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation. - -Web Document handle for author method chains. Prefer constructing from Artifact -Metadata via `web.page` facade or the free `new` tool above. View tables use -only `|type|slot|value|attrs|style|` (ZH `|类型|槽|值|属性|样式|`). Do not pass a -raw HTML string as the primary `body` for a full site shell. - -We **[Load the native plugin required by this operation](cap.load())**. - -`out` = - -| _type | title | route | method | body | nodes | data_source | data_order | data_where | -|-------|-------|-------|--------|------|-------|-------------|------------|------------| -| page | `title` | `route` | `method` | `body` | `nodes` | `data_source` | `data_order` | `data_where` | - -Return *out*. - -## render - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| nodes | any | None | View table or None | -| db | any | None | optional database handle | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML or render payload | - -Use `nodes`=None, `db`=None as the inputs for this operation. - -Render this Document to HTML for preview or response. Optional `nodes` is the -unified View table (type/slot/value/attrs/style). When `nodes` is None, the -method uses self.nodes if present, otherwise Markdown body. Optional `db` is retained for compatibility; automatic data_source binding -belongs to ordinary served Documents, not this offline renderer. Prefer assembling `nodes` from -file-partitioned components via component.merge — do not pass a handmade HTML -string as the page shell. This is the sole compose path (ADR 0007); there is no -compose_main or fragment DSL. - -We **[Load the native plugin required by this operation](cap.load())**. -We retain **n = nodes**. -1. `n` == None - We retain **`n` = [Read nodes field](access(`self`, "nodes"))**. -2. * - **_ = 1** -We retain **`title` = [Read title field](access(`self`, "title"))**. -1. `n` - Return *[Render this Document to HTML for preview or response](web_render_nodes(page=`self`, nodes=`n`, db=`db`, title=`title`))*. -2. * - We retain **`body` = [Read body field](access(`self`, "body"))**. - Return *[Render this Document to HTML for preview or response](web_render_document(page=`self`, body=`body`, db=`db`, title=`title`))*. - -## css - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| css | text | required | raw CSS (escape hatch) | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | updated page handle | - -Use `css` as the inputs for this operation. - -Escape hatch — append raw CSS string `css` to this page. Named style tables and -the View style column remain the default theme path. Use this only when a host -constraint cannot be expressed as a named style row, and write that reason next -to the call. Forbidden as the primary way to style nav, sidebar, or footer. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Escape hatch — append raw CSS string css to this page](web_page_css(page=`self`, css=`css`))*. diff --git a/ext/web/route/index.mq.md b/ext/web/route/index.mq.md deleted file mode 100755 index 21525e1..0000000 --- a/ext/web/route/index.mq.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -markup: occlusion -title: ext/web/route -description: Declared Endpoint / Document route registration (ADR 0007). -import: - cap: ext/web/_capability/index.mq.md - table: lib/table.mq.md ---- - -Routes declare the HTTP surface. Prefer Document/Endpoint metadata and serve -for whole sites; use route handles only for explicit app assembly. To obtain an -app use web.app on [the facade](../../web/web.mq.md); to discover a site's routes -without a live app use web.inspect with root. A fresh call without app/root -cannot inspect the private state of another running server. - -```sh -marqdo call ext/web/route/index.mq.md new 'app={}' 'path="/hello"' 'page={"title":"Hello","body":"Hi"}' --effects plugin --session handbook --toget route --json -marqdo call ext/web/route/index.mq.md register 'route=$route' --effects plugin --session handbook --json -``` - -The returned registration is a value, not a listening server. Middleware and -Endpoint handlers remain explicit; schema/auth resources live in their own -packages. Update both route facades and HTTP artifact tests for registration -changes; never introduce undeclared user URLs as a hidden convenience. - -## new - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | app handle | -| path | text | required | URL path | -| method | text | "GET" | HTTP method | -| page | any | None | Document or None | -| fn | text | "" | endpoint member | -| request | text | "json" | request kind | -| response | text | "json" | response kind | -| auth | text | "" | auth tag | -| class | text | "" | route class | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | route handle | - -Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation. - -Build a declared route handle for `app` at `path` with `method`="GET" . - -`page`=None holds a Document; `fn`="" names an Endpoint lib.member. - -`request`="json", `response`="json", `auth`="", and `class`="" document the -contract. Optional class values: execute, short, read, control (empty → -heuristic / legacy_serial). This tool does not register yet — call `register` -or use the facade `web.route` which registers in one step. - -We **[Load the native plugin required by this operation](cap.load())**. - -`out` = - -| _type | app | path | method | page | fn | request | response | auth | class | -|-------|-----|------|--------|------|----|---------|----------|------|-------| -| route | `app` | `path` | `method` | `page` | `fn` | `request` | `response` | `auth` | `class` | - -Return *out*. - -## register - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| route | any | required | route handle | -| app | any | None | app or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | registration result | - -Use `route`, `app`=None as the inputs for this operation. - -Register declared route handle `route` on an app. Optional `app`=None falls back -to the app stored on the route object so stepwise agent sessions can omit it. -Page routes call web_app_route; Endpoint `fn` routes call web_app_invoke with -method and body/return contract fields pulled from the handle. User routes must -already be declared on this handle — this tool never invents paths. Prefer this -free tool under `--effects plugin` rather than a method chain when driving -registration from `marqdo call`. Soft-fails with ok=False when neither page nor -fn is present, so callers can detect incomplete declarations early. - -We **[Load the native plugin required by this operation](cap.load())**. -We retain **a = app**. -1. `a` == None - We retain **`a` = [Read app field](access(`route`, "app"))**. -2. * - **_ = 1** -We retain **`page` = [Read page field](access(`route`, "page"))**. -We retain **`fn` = [Read fn field](access(`route`, "fn"))**. -1. `page` - We retain **`path` = [Read path field](access(`route`, "path"))**. - Return *[Register declared route handle route on an app](web_app_route(app=`a`, path=`path`, page=`page`))*. -2. `fn` - We retain **`path` = [Read path field](access(`route`, "path"))**. - We retain **`method` = [Read method field](access(`route`, "method"))**. - We retain **`request` = [Read request field](access(`route`, "request"))**. - We retain **`response` = [Read response field](access(`route`, "response"))**. - We retain **`class` = [Read class field](access(`route`, "class"))**. - Return *[Register declared route handle route on an app](web_app_invoke(app=`a`, path=`path`, method=`method`, fn=`fn`, body=`request`, return=`response`, class=`class`))*. -3. * - Return *[Set the ok field in the new record](table.put(in=None, at="ok", value=False))*. - -## use - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| middleware | any | required | middleware table | -| route | any | required | route handle | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | use result | - -Use `middleware`, `route` as the inputs for this operation. - -Attach middleware table `middleware` to declared route handle `route` -(`|header|value|` or named capability rows). Prefer first-class middleware tables -over configure junk drawers. Call this free tool with `--effects plugin`. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Attach middleware table middleware to declared route handle route (|header|value| or named capability rows)](web_route_use(route=`route`, middleware=`middleware`))*. - -# route - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Application handle created by the public web app constructor | -| path | any | required | URL path declared for this route | -| method | any | "GET" | HTTP request method for the declared route | -| page | any | None | Initial Document/page resource, or None for explicit later route mounts | -| fn | any | "" | Endpoint member path; empty when mounting a Document page | -| request | any | "json" | Request body format passed to the native Endpoint dispatcher | -| response | any | "json" | Response format passed to the native Endpoint dispatcher | -| auth | any | "" | Explicit route authentication policy label | -| class | any | "" | Execution class: execute, short, read or control; empty keeps native heuristics | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Declared route handle retaining app, path, method, page or endpoint and dispatch fields | - -Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation. - -Declared route handle for author method chains. Prefer `web.route` / Artifact -`type: endpoint` discovery via `web.serve`. Optional `class`: `execute` | -`short` | `read` | `control` (empty → heuristic / `legacy_serial`). - -We **[Load the native plugin required by this operation](cap.load())**. - -`out` = - -| _type | app | path | method | page | fn | request | response | auth | class | -|-------|-----|------|--------|------|----|---------|----------|------|-------| -| route | `app` | `path` | `method` | `page` | `fn` | `request` | `response` | `auth` | `class` | - -Return *out*. - -## use - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| middleware | any | required | middleware table | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | use result | - -Use `middleware` as the inputs for this operation. - -Attach middleware table to this route (`|header|value|` or named capability -rows). Prefer explicit tables authors can read; do not restore a configure bag -for headers and cors. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Attach middleware table to this route (|header|value| or named capability rows)](web_route_use(route=`self`, middleware=`middleware`))*. - -## register - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | None | app or None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | registration result | - -Use `app`=None as the inputs for this operation. - -Register this declared route on an app handle. When optional `app` is None, use -the app stored on this route object so author chains can omit the argument after -construction. Document pages call web_app_route with the stored path and page -handle. Endpoint members call web_app_invoke with path, method, and the -request/response/class contract fields from this route. Prefer Artifact -discovery via web.serve for whole sites; use this method when assembling routes -in memory for tests or advanced mounts. Returns a soft failure map when neither -page nor fn is set, so callers can detect an incomplete declaration without a -hard crash. Never invents an undeclared path — registration only publishes what -this handle already carries. - -We **[Load the native plugin required by this operation](cap.load())**. -We retain **a = app**. -1. `a` == None - We retain **`a` = [Read app field](access(`self`, "app"))**. -2. * - **_ = 1** -We retain **`page` = [Read page field](access(`self`, "page"))**. -We retain **`fn` = [Read fn field](access(`self`, "fn"))**. -1. `page` - We retain **`path` = [Read path field](access(`self`, "path"))**. - Return *[Register this declared route on an app handle](web_app_route(app=`a`, path=`path`, page=`page`))*. -2. `fn` - We retain **`path` = [Read path field](access(`self`, "path"))**. - We retain **`method` = [Read method field](access(`self`, "method"))**. - We retain **`request` = [Read request field](access(`self`, "request"))**. - We retain **`response` = [Read response field](access(`self`, "response"))**. - We retain **`class` = [Read class field](access(`self`, "class"))**. - Return *[Register this declared route on an app handle](web_app_invoke(app=`a`, path=`path`, method=`method`, fn=`fn`, body=`request`, return=`response`, class=`class`))*. -3. * - Return *[Set the ok field in the new record](table.put(in=None, at="ok", value=False))*. diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md deleted file mode 100755 index d759d9e..0000000 --- a/ext/web/web.mq.md +++ /dev/null @@ -1,440 +0,0 @@ ---- -markup: occlusion -title: ext/web/web -description: >- - Web Artifact facade (ADR 0007) — page · route · serve · render · inspect · use. - Document/Endpoint first-class. No compose_* / configure / author ensure_plugin. - Agents: read ext/web/index.mq.md first (layout file-partition law). -import: - cap: ext/web/_capability/index.mq.md - page_mod: ext/web/page/index.mq.md - route_mod: ext/web/route/index.mq.md - dom_mod: ext/web/dom/index.mq.md - client_mod: ext/web/client/index.mq.md - table: lib/table.mq.md ---- - -Web facade — [start at the root handbook](index.mq.md), then use this module -for server lifecycle and rendering. Layout assembly remains in pure component -functions; database, security and network clients stay in their own packages. - -```sh -marqdo call ext/web/web.mq.md render 'body="# A Document"' 'title="Preview"' --effects plugin --json -marqdo call ext/web/web.mq.md inspect 'root="examples/web-layout-handbook"' --effects plugin --json -``` - -inspect with root scans declared metadata without starting a server. To inspect -an in-memory app, pass its actual handle; an empty fresh process cannot inspect -another process. serve is a blocking lifecycle operation. Call it directly with explicit effects, -or compose prepare, resource bindings and listen in an ordinary callable launcher. Explicit view: main Documents assemble once at startup -through normal functions and imports. Restart after changing their content. - -Develop layout structure in layout/component and the Go artifact renderer; -keep this facade as orchestration. Preserve the existing app object and manual -route API. Contracts precede execution; ordinary prose titles are not functions. - -## page - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| title | text | "" | document title | -| route | text | "/" | path | -| method | text | "GET" | HTTP method | -| body | text | "" | Markdown body | -| nodes | any | None | View table or None | -| data_source | text | "" | table name | -| data_order | text | "" | order key | -| data_where | text | "" | filters | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | page handle | - -Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation. - -Construct a Document handle with `title`="", `route`="/", `method`="GET", - -`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="", - -`data_where`="" keys. Prefer discovering type: web Artifact files via serve -rather than hand-building every page in memory. nodes must be the unified View -schema, never a private dialect or an HTML string shell. - -Return *[Page](page_mod.page(title=`title`, route=`route`, method=`method`, body=`body`, nodes=`nodes`, data_source=`data_source`, data_order=`data_order`, data_where=`data_where`))*. - -## route - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | app handle | -| path | text | required | URL path | -| method | text | "GET" | HTTP method | -| page | any | None | Document or None | -| fn | text | "" | endpoint member | -| request | text | "json" | request kind | -| response | text | "json" | response kind | -| auth | text | "" | auth tag | -| class | text | "" | route class | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | registration result | - -Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation. - -Register a declared Document page or Endpoint on `app` at `path` with - -`method`="GET" . `page`=None holds a Document; `fn`="" names an Endpoint -lib.member. `request`="json", `response`="json", `auth`="", and `class`="" -document the contract. Optional class values include execute, short, read, -control. User routes must be declared — never implicit. After building the -route object this tool registers it on the app. - -We retain **`r` = [Route](route_mod.route(app=`app`, path=`path`, method=`method`, page=`page`, fn=`fn`, request=`request`, response=`response`, auth=`auth`, class=`class`))**. -Return *[Register](> `r`.register app=`app` )*. - -## render - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| doc | any | None | Document or None | -| nodes | any | None | View table or None | -| body | text | "" | Markdown | -| title | text | "" | title supplied by the caller | -| db | any | None | optional db | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML or payload | - -Use `doc`=None, `nodes`=None, `body`="", `title`="", `db`=None as the inputs for this operation. - -Render a Document or View nodes to HTML for offline preview. Prefer nodes from -file-partitioned components. Optional `doc`=None is a Document handle; when set, -delegates to page.render. Optional `nodes`=None is a View table; when set without -doc, renders that table. Otherwise renders Markdown `body`="" with optional - -`title`="" and `db`=None . Requires the native plugin. Do not treat this as -permission to paste a full HTML homepage — keep using View tables and Markdown. - -We **[Load the native plugin required by this operation](cap.load())**. -1. `doc` - Return *[Render](> `doc`.render nodes=`nodes` db=`db` )*. -2. `nodes` - Return *[Render a Document or View nodes to HTML for offline preview](web_render_nodes(page=`doc`, nodes=`nodes`, db=`db`, title=`title`))*. -3. * - Return *[Render a Document or View nodes to HTML for offline preview](web_render_document(page=`doc`, body=`body`, db=`db`, title=`title`))*. - -## use - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| middleware | any | required | middleware table | -| app | any | required | app handle | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | app handle | - -Use `middleware`, `app` as the inputs for this operation. - -Attach first-class `middleware` to `app`. Pass a GFM table (security headers, -cors row, and similar). This replaces the old configure(...) junk drawer with an -explicit table authors can read. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Attach first-class middleware to app](web_app_use(app=`app`, middleware=`middleware`))*. - -## inspect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | None | Current prepared application after all explicit Resource bindings | -| root | text | "" | Optional metadata-only scan directory; takes precedence over app | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | scope, declared and system; registered reports actual configured handlers, metadata reports file declarations and runtime templates | - -Use `app`=None and `root`="" deliberately. After prepare and Resource bindings, pass the retained app before listen to inspect its current routes. The registrar is shared with the actual HTTP server, so later WebSocket, JSON query, form, login, administration and static bindings appear without using a stale startup snapshot. Duplicate or conflicting registrations retain their native diagnostic. - -Supplying root scans Artifact metadata only. It does not execute the launcher or Documents, so it cannot observe Resource bindings performed by those functions. scope=metadata makes that limitation explicit; scope=registered reports the handler registrations of the supplied app. Neither scope proves that a server is listening, a database is available or authentication succeeds. - -The operation needs plugin. It does not invoke request handlers, create sessions, reset runtime state, open a database or start a listener. Credentials and unrelated app fields are not returned. System routes include the actual configured parameterized form/part paths and session paths; declared routes retain their source identity when available. - -We **[Load the maintained native inspection boundary](cap.load())**. -Return *[Observe the current declarations and registered runtime handlers](web_inspect(app=`app`, root=`root`))*. - -## serve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "." | site root | -| host | text | "127.0.0.1" | bind host | -| port | number | 18081 | Explicit server port | -| db | any | None | optional db | -| static_dir | text | "" | static files | -| middleware | any | None | optional middleware | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | serve result | - -Use `root`=".", `host`="127.0.0.1", `port`=18081, `db`=None, `static_dir`="", `middleware`=None as the inputs for this operation. - -Scan `root`="." for type web or endpoint Artifacts, register declared routes, -attach system routes, and listen on `host`="127.0.0.1" and `port`=18081 . The -site directory should already follow the layout law (components split until -simple). Optional `db`=None, `static_dir`="", and `middleware`=None bind -resources without stuffing them into this facade as author APIs. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Discover the site and listen on its configured address](web_serve_root(root=`root`, host=`host`, port=`port`, db=`db`, static_dir=`static_dir`, middleware=`middleware`))*. - -## client_embed - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| bridge | text | "/static/marqdo-bridge.js" | bridge script URL | -| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL | -| source | text | "" | optional source | -| boot | bool | True | auto boot | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | embed descriptor | - -Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="", `boot`=True as the inputs for this operation. - -Describe WASM bridge embed tags for a page that needs client Marqdo. Defaults: - -`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", - -`source`="", `boot`=True . This is not a substitute for Document layout: still -partition nav and main in files, then embed the bridge where interaction needs -it. - -Return *[Embed](client_mod.embed(bridge=`bridge`, wasm=`wasm`, source=`source`, boot=`boot`))*. - -## text_patch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | text | required | CSS selector | -| text | text | required | new text | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | patch descriptor | - -Use `sel`, `text` as the inputs for this operation. - -Client patch: set text content for CSS selector `sel` to string `text`. Use for -small interactive updates after a Document is already laid out with View tables — -not for building the initial homepage shell. - -Return *[Text patch](client_mod.text_patch(sel=`sel`, text=`text`))*. - -## dom_patch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | text | required | CSS selector | -| html | text | "" | optional HTML fragment | -| attrs | any | None | optional attrs | -| remove | bool | False | remove node | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | patch descriptor | - -Use `sel`, `html`="", `attrs`=None, `remove`=False as the inputs for this operation. - -Client patch for selector `sel` with optional `html`="", `attrs`=None, or - -`remove`=False . Treat html here as a surgical update, never as the primary way -to author nav, sidebar, or footer. Layout law still applies to the Document that -hosts the selector. - -Return *[Dom patch](client_mod.dom_patch(sel=`sel`, html=`html`, attrs=`attrs`, remove=`remove`))*. - -## make_style - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | property table | -| name | text | "" | style name | -| strict | bool | False | strict mode | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | CSS / style handle | - -Use `table`, `name`="", `strict`=False as the inputs for this operation. - -Compile a named style `table` into CSS. Optional `name`="" and `strict`=False . -Styles remain data next to content; this is not a hidden page DSL. Prefer -referencing style names from View style columns after file-partitioned -components define their look. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Compile a named style table into CSS](web_style(name=`name`, table=`table`, strict=`strict`))*. - -## make_images - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | images table | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | images payload | - -Use `table` as the inputs for this operation. - -Build image descriptors from a readable `table` of sources and alts. Keep media -declarations in Markdown tables beside the Document that uses them. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Build image descriptors from a readable table of sources and alts. Keep media declarations in Markdown tables beside the Document that uses them.](web_images(table=`table`))*. - -## make_head - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| table | any | required | head table | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | head payload | - -Use `table` as the inputs for this operation. - -Build head resource rows (link, script, icon) from a `table`. Prefer declaring -head needs as data rather than injecting opaque HTML head strings. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Build head resource rows (link, script, icon) from a table. Prefer declaring head needs as data rather than injecting opaque HTML head strings.](web_head(table=`table`))*. - -## prepare - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "." | Site directory containing declared Documents and Endpoints | -| host | text | "127.0.0.1" | Explicit listen address retained for later listen | -| port | number | 18081 | Port retained for later listen | -| db | any | None | Existing database Resource or None | -| static_dir | text | "" | Optional static directory resolved under the site | -| middleware | any | None | Optional security header table | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Prepared app resource; no socket is opened | - -Use `root`=".", `host`="127.0.0.1", `port`=18081, `db`=None, `static_dir`="" and `middleware`=None to discover the same Documents and Endpoints as serve. Startup View assembly runs once here. Bind additional resources to the returned app, retaining each returned app value, before calling listen. The original absolute site root travels with the app so relative endpoint callbacks and static files keep their site context. This is a lifecycle boundary, not an alternative routing language. Reading metadata or evaluating a Document can fail before any listener starts. - -We **[Load the existing native web implementation](cap.load())**. -Return *[Discover routes without starting a listener](web_prepare_root(root=`root`, host=`host`, port=`port`, db=`db`, static_dir=`static_dir`, middleware=`middleware`))*. - - -## listen - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| app | any | required | Prepared app after explicit resource bindings | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Blocking native listener result | - -Use `app` after prepare and the resource-owned binding functions. This call opens the configured host and port and blocks for the server lifetime. It works in an ordinary callable launcher reached by marqdo call; grant plugin, filesystem and network effects required by that launcher. Returning a resource description does not start the server. A separate terminal or supervised test process owns shutdown; call does not turn this listener into a background daemon. Relative paths use the site root retained by prepare. - -We **[Load the existing native web implementation](cap.load())**. -Return *[Serve the prepared site with its bound resources](web_listen(app=`app`))*. - - -# app - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| page | any | None | Initial Document/page resource, or None for explicit later route mounts | -| db | any | None | Existing database resource used for document data and native application services | -| host | any | "127.0.0.1" | Listen address; the default binds only the local host | -| port | any | 18081 | TCP listen port selected for the application | -| admin | any | False | Whether to enable the native administration routes | -| admin_prefix | any | "/admin" | URL prefix under which native administration routes are mounted | -| shell_css | any | None | Optional native shell stylesheet configuration; None keeps the runtime default | -| layout | any | None | Optional native shell layout configuration; component geometry remains View data | -| asset_version | any | None | Optional resource version used by the native shell for asset URLs | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Native app resource for static mounts, route registration, gates and listening | - -Use `page`=None, `db`=None, `host`="127.0.0.1", `port`=18081, `admin`=False, `admin_prefix`="/admin", `shell_css`=None, `layout`=None, `asset_version`=None as the inputs for this operation. - -Low-level app handle for advanced mounts. Prefer web.serve for Artifact sites -that already follow file-partition layout. Optional page, db, host, port, admin -flags, shell_css, layout, and asset_version configure the runtime without a -configure junk drawer of unrelated kwargs. Authors who need only Document -discovery should stay on serve; agents should not invent HTML shells on this -object. Methods static, listen, and gate hang off the returned handle for -mounts that remain table- and Metadata-driven. - -We **[Load the native plugin required by this operation](cap.load())**. -Return *[Low-level app handle for advanced mounts](web_app_new(page=`page`, db=`db`, admin=`admin`, host=`host`, port=`port`, admin_prefix=`admin_prefix`, login_redirect=None, logout_redirect=None, shell_css=`shell_css`, layout=`layout`, asset_version=`asset_version`))*. - -## static - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dir | text | required | filesystem directory | -| mount | text | "/static" | URL mount | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | app handle | - -Use `dir`, `mount`="/static" as the inputs for this operation. - -Mount static files from `dir` at `mount`=/static on this app. Use for bridge -scripts and assets referenced by Documents — not for dumping an HTML-only site -tree that bypasses Artifact Documents. - -Return *[Mount static files from dir at mount=/static on this app](web_app_static(app=`self`, dir=`dir`, mount=`mount`))*. - -## listen - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | listen result | - -Start listening with the already configured app host and port. Prefer serve for -root scanning; listen is for advanced app handles after manual route setup. - -Return *[Start listening with the already configured app host and port. Prefer serve for root scanning; listen is for advanced app handles after manual route setup.](web_listen(app=`self`))*. - -## gate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | gated path | -| roles | any | "admin" | roles supplied by the caller | -| permissions | text | "" | Comma-separated permission names held by the current role or subject | -| match | text | "prefix" | match mode | -| on_deny | text | "forbid" | deny behavior | -| exclude | any | None | exclusions | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | app handle | - -Use `path`, `roles`="admin", `permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None as the inputs for this operation. - -Attach an authorization gate on `path` for this app. Defaults: `roles`="admin", - -`permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None . Auth -resources live in ext/security; this method only wires the gate onto the web -app surface. - -Return *[Attach an authorization gate on path for this app](web_app_gate(app=`self`, path=`path`, roles=`roles`, permissions=`permissions`, match=`match`, on_deny=`on_deny`, exclude=`exclude`))*. diff --git a/ext/web/布局/索引.mq.md b/ext/web/布局/索引.mq.md deleted file mode 100755 index 2b0105b..0000000 --- a/ext/web/布局/索引.mq.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -markup: occlusion -title: ext/web/布局 -description: 先拆结构,递归到简单 Markdown 叶子。 -import: - layout: ext/web/layout/index.mq.md ---- - -工程实践:先画区域树,再建立对应目录,最后写内容。首页拆成导航、主体、页脚; -页脚拆成品牌和链接;链接如果仍有双栏,就拆成文档与社区。内部还需要独立排布就继续拆, -直到叶子只含简单 Markdown。不是把每个句子拆成文件,而是消除同一个叶子中的多种职责。 - -真实文件树在[参考站点](../../../examples/web-layout-handbook/index.mq.md)。 -父 index.mq.md 只导入、组合子块并选择一层布局;叶子 content.md 是普通 Markdown。 -不要先写 HTML 壳再拆文件,那会把结构依旧藏在字符串里。 - -```sh -marqdo call ext/web/布局/索引.mq.md 规则 --json -marqdo call ext/web/布局/索引.mq.md 分栏 '子节点=[{"type":"markdown","value":"左栏"},{"type":"markdown","value":"右栏"}]' '槽="页脚"' --json -``` - -分栏会在现有五列表的值中保留子节点,渲染为可响应的 CSS 网格;窄屏自动折叠。 -纵排保持区域从上到下的顺序。样式列是类名引用,不是一段 CSS 规则,也不会自动定义主题。 -只用合并工具会得到相邻节点,不会得到双栏。内容叶子使用组件正文,语义包裹使用组件包裹。 - -开发与验收:每个叶子应能以内容职责命名;父文件出现大量正文或 HTML 标签时继续拆。 -先用页面渲染离线检查,再运行参考站点,核对首页、关于页与 API。 -新增结构需修改 plugins/web/internal/artifact 并同步双语工具与 web_handbook 测试。 - -## 规则 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 布局实践约定 | - -返回先拆布局、递归到 Markdown 叶子的工程约定。无参数; -规则是说明,不声称已静态审查某个文件。真正验收需要运行并检查站点。 - -完成后返回*[调用 rules](layout.rules())*。 - -## 视图契约 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | View 列名 | - -返回五个公共列名。子块通过值列继续包含同样的 View 记录; -不增加第二种布局表方言,也不把任意属性名解释为 CSS。 - -完成后返回*[调用 view schema](layout.view_schema())*。 - -## 合并节点 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 甲 | list | 必填 | 第一组节点 | -| 乙 | list | 必填 | 第二组节点 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 兄弟节点 | - -这里使用`甲`、`乙`。 - -拼接 `甲` 与 `乙`,只保留顺序,不增加几何关系。 -需要横向排列时使用分栏,需要上下分区时使用纵排。 - -完成后返回*[调用 merge nodes](layout.merge_nodes(a=`甲`, b=`乙`))*。 - -## 纵排 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 子节点 | list | 必填 | 子块列表 | -| 槽 | text | "" | 父区域名 | -| 样式 | text | "" | 可选类名 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 父容器节点 | - -这里使用`子节点`、`槽`=""、`样式`=""。 - -为 `子节点` 声明一层上下顺序。默认 `槽`=""、`样式`=""。 -父块只负责排列,内容和更深层结构留在导入的子组件。结果仍是 View 节点列表, -可以继续传给祖先组件或页面渲染,无需提前转为 HTML。 - -完成后返回*[调用 stack](layout.stack(children=`子节点`, slot=`槽`, style=`样式`))*。 - -## 分栏 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 子节点 | list | 必填 | 子块列表 | -| 槽 | text | "" | 父区域名 | -| 样式 | text | "" | 可选类名 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 父容器节点 | - -这里使用`子节点`、`槽`=""、`样式`=""。 - -为 `子节点` 声明一层响应式多栏。默认 `槽`=""、`样式`=""。 -父块只负责排列,内容和更深层结构留在导入的子组件。结果仍是 View 节点列表, -可以继续传给祖先组件或页面渲染,无需提前转为 HTML。 - -完成后返回*[调用 columns](layout.columns(children=`子节点`, slot=`槽`, style=`样式`))*。 - -## 验收组件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | text | 必填 | 组件名称 | -| 职责 | text | 必填 | 单一职责描述 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 待人工或测试核对的清单 | - -这里使用`名`、`职责`。 - -为 `名` 与 `职责` 返回待检查的条目。仅依据这两个文本无法证明组件合格, -所以结果明确标注为清单,调用者仍须检查文件内容与渲染结果,不自动发放通过标签。 - -完成后返回*[调用 accept component](layout.accept_component(name=`名`, duty=`职责`))*。 diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md deleted file mode 100755 index a345e64..0000000 --- a/ext/web/网页.mq.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页 -description: >- - Web Artifact 中文作者门面(ADR 0007)— 页面 · 路由 · 服务 · 渲染 · 检视。 - 智能体请先读 ext/web/网页/索引.mq.md。禁止 compose_* / configure / 默认 HTML 注入。 -import: - web: ext/web/web.mq.md - 布局: ext/web/布局/索引.mq.md ---- - -门面模块:从[中文根手册](网页/索引.mq.md)选择业务路径。 -布局先拆成父组件与 Markdown 叶子,默认不写整页 HTML。构造值与启动进程是两件事; -下面示例从生产者开始,所有句柄沿同一会话传递,渲染时才需要原生插件。 - -```sh -marqdo call ext/web/网页.mq.md 渲染 '正文="# 文档"' '标题="预览"' --effects plugin --json -marqdo call ext/web/网页.mq.md 检视 '根="examples/web-layout-handbook"' --effects plugin --json -``` - -页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。 -整站服务可通过 marqdo call 直接调用服务函数,也可在普通启动函数中组合准备、资源绑定与监听;检视磁盘站点请给出根目录,不能从新进程 -读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。 - -开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。 -验证 web_handbook 与既有 Web Artifact 金样,资源、鉴权和网络能力不要塞回门面。 - -## 布局规则 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 布局规则映射 | - -与 `布局.规则` 相同,便于只打开本文件的智能体。 - -完成后返回*[调用 规则](布局.规则())*。 - -## 页面 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标题 | text | "" | 文档标题 | -| 路由 | text | "/" | 路径 | -| 方法 | text | "GET" | HTTP 方法 | -| 正文 | text | "" | Markdown 正文 | -| 节点 | any | None | View 表或 None | -| 数据源 | text | "" | 表名 | -| 排序 | text | "" | 如 -created_at | -| 条件 | text | "" | col=val 列表 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 页面句柄 | - -这里使用`标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、`节点`=None、`数据源`=""、`排序`=""、`条件`=""。 - -构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、 - -`节点`=None、`数据源`=""、`排序`=""、`条件`=""。站点页面优先用 `类型: 网页` -Artifact,由 `服务` 发现;本工具供预览或程序化构造。节点必须是统一 View 表, -不是 HTML。 - -完成后返回*[调用 page](web.page(title=`标题`, route=`路由`, method=`方法`, body=`正文`, nodes=`节点`, data_source=`数据源`, data_order=`排序`, data_where=`条件`))*。 - -## 路由 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | 必填 | 应用句柄 | -| 路径 | text | 必填 | URL 路径 | -| 方法 | text | "GET" | HTTP 方法 | -| 页面 | any | None | Document 或 None | -| 函数 | text | "" | Endpoint lib.member | -| 请求 | text | "json" | 请求体类型 | -| 响应 | text | "json" | 响应类型 | -| 鉴权 | text | "" | 鉴权标签 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 路由结果 | - -这里使用`应用`、`路径`、`方法`="GET"、`页面`=None、`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。 - -在 `应用` 上注册已声明 Document 或 Endpoint:`路径`、`方法`="GET"、`页面`=None、 - -`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。不要隐式注册用户路由。 - -完成后返回*[调用 route](web.route(app=`应用`, path=`路径`, method=`方法`, page=`页面`, fn=`函数`, request=`请求`, response=`响应`, auth=`鉴权`))*。 - -## 渲染 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 文档 | any | None | Document 或 None | -| 节点 | any | None | View 表或 None | -| 正文 | text | "" | Markdown | -| 标题 | text | "" | 调用方提供的标题 | -| 数据库 | any | None | 可选 db | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML 或渲染结果 | - -这里使用`文档`=None、`节点`=None、`正文`=""、`标题`=""、`数据库`=None。 - -把 Document 或 View 节点渲染为 HTML(预览)。可选 `文档`=None、`节点`=None、 - -`正文`=""、`标题`=""、`数据库`=None。输入应来自 Markdown/View,而不是手写 HTML -大字符串。 - -完成后返回*[调用 render](web.render(doc=`文档`, nodes=`节点`, body=`正文`, title=`标题`, db=`数据库`))*。 - -## 使用 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 中间件 | any | 必填 | 中间件表 | -| 应用 | any | 必填 | 应用句柄 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 应用句柄 | - -这里使用`中间件`、`应用`。 - -把 `中间件` 挂到 `应用`(表驱动)。禁止 `configure(...)` 垃圾抽屉。 - -完成后返回*[调用 use](web.use(app=`应用`, middleware=`中间件`))*。 - -## 检视 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | None | 完成显式资源绑定后保留的当前应用 | -| 根 | text | "" | 可选的元数据扫描目录;给出时优先于应用 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | scope、declared 与 system;区分文件声明和当前应用的实际处理器注册 | - -使用`应用`=None、`根`="",应明确选择观察范围。准备应用并绑定资源后,把保留的应用交给检视,再开始监听。清单复用真实服务的路由注册流程,后加的 WebSocket、JSON 查询、表单、登录、后台和静态挂载都会出现,不读取已经过期的启动快照;冲突注册保留原生诊断。 - -给出根目录时只扫描 Artifact 元数据,不执行启动函数或页面,因此不能观察这些函数运行后才绑定的资源。scope 为 metadata 表示文件声明与运行时模板,为 registered 表示传入应用的实际处理器注册。它们都不能证明已经监听、数据库可用或登录成功。 - -需要 plugin。此操作不调用请求处理器、不创建或重置会话、不打开数据库、不启动监听,也不返回凭据和无关应用字段。系统清单包含实际配置的表单、片段及会话路径;已有来源信息的声明仍保留文件身份,便于继续阅读实现。 - -完成后返回 *[观察当前声明及运行时注册](web.inspect(app=`应用`, root=`根`))*。 - -## 服务 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 根 | text | "." | 站点根目录 | -| 主机 | text | "127.0.0.1" | 绑定主机 | -| 端口 | number | 18081 | 调用方提供的端口 | -| 数据库 | any | None | 可选 db | -| 静态目录 | text | "" | 静态资源 | -| 中间件 | any | None | 可选中间件 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 服务结果 | - -这里使用`根`="."、`主机`="127.0.0.1"、`端口`=18081、`数据库`=None、`静态目录`=""、`中间件`=None。 - -扫描 `根`="." 下 `类型: 网页|端点` Artifact,注册声明路由并在 `主机`="127.0.0.1" -与 `端口`=18081 监听。可选 `数据库`=None、`静态目录`=""、`中间件`=None。站点 -目录应已按布局铁律拆好组件文件。 - -完成后返回*[调用 serve](web.serve(root=`根`, host=`主机`, port=`端口`, db=`数据库`, static_dir=`静态目录`, middleware=`中间件`))*。 - -## 客户端挂载 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 桥 | text | "/static/marqdo-bridge.js" | bridge 脚本路径 | -| wasm | text | "/static/marqdo_wasm.wasm" | wasm 路径 | -| 源 | text | "" | 可选源 | -| 启动 | bool | True | 是否自动 boot | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 挂载描述 | - -这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。 - -嵌入 WASM 桥,默认 `桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、 - -`源`=""、`启动`=True。不是用 HTML 字符串拼整页的借口。 - -完成后返回*[调用 client embed](web.client_embed(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*。 - -## 准备站点 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 根 | text | "." | 含网页与端点声明的站点目录 | -| 主机 | text | "127.0.0.1" | 监听地址;准备阶段不开启端口 | -| 端口 | number | 18081 | 交给稍后监听阶段使用的端口 | -| 数据库 | any | None | 已有数据库资源 | -| 静态目录 | text | "" | 站点内的可选静态资源目录 | -| 中间件 | any | None | 可选安全响应头表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 已发现路由并完成启动布局装配的应用资源 | - -这里使用`根`="."、`主机`="127.0.0.1"、`端口`=18081、`数据库`=None、`静态目录`=""和`中间件`=None。准备阶段发现 Document 与 Endpoint,执行一次启动布局,但不启动监听。随后把应用交给网络、鉴权等资源的绑定函数,并保留每次返回的新应用,最后调用监听。原始站点的绝对根目录随应用保留,因此端点回调和静态资源的相对路径仍按站点解析。目录读取和布局执行可能在打开端口之前失败,应保留原始诊断。 - -完成准备后返回*[发现站点并保留其资源上下文](web.prepare(root=`根`, host=`主机`, port=`端口`, db=`数据库`, static_dir=`静态目录`, middleware=`中间件`))*. - - -## 监听 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | 必填 | 准备站点后已完成资源绑定的应用 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 阻塞的原生监听结果 | - -输入`应用`后才启动已配置的主机和端口。可以在普通可调用启动函数中按顺序准备站点、绑定资源、监听,再通过 marqdo call 执行该函数。监听持续占用当前进程,由调用者或测试监督进程负责停止。显式授予启动流程所需的插件、文件读取与网络写入权限;返回一个应用描述本身不会启动后台服务。 - -最后返回*[在保留的站点根目录中启动服务](web.listen(app=`应用`))*. - - - -## 编译样式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名称 | text | 必填 | 原生类选择器名,可含后代选择器尾部 | -| 属性 | any | 必填 | 属性、值两列的声明式主题表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | text | 原生样式编译器输出的 CSS 文本 | - -使用`名称`与`属性`,授权 plugin。该入口对应英文 make_style,把可读属性表交给已有原生编译器;不接收整页 HTML,也不创造另一套布局语言。名称应由作者控制,对应 View 的样式类与原生内容结构。返回文本不会自动写入或挂载文件,调用者需显式选择生成路径并以原生文件能力保存。 - -纯属性构造不需要插件,真正编译才在这里加载原生实现。属性值的格式或选择器错误保留真实诊断,不能替换为旧产物继续声称已构建。动态业务数据不应该用来拼接选择器;测试应比较实际编译结果并查看对应区域的渲染效果。 - -完成编译后返回 *[使用已有主题编译器处理声明](web.make_style(name=`名称`, table=`属性`))*。 diff --git a/ext/web/网页/客户端/索引.mq.md b/ext/web/网页/客户端/索引.mq.md deleted file mode 100755 index 9cbe645..0000000 --- a/ext/web/网页/客户端/索引.mq.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页/客户端 -description: 浏览器 Runtime 辅助(WASM 桥)。效果表优先 lib/browser(ADR 0007)。 -import: - client: ext/web/client/index.mq.md ---- - -客户端模块:从[中文根手册](../索引.mq.md)选择业务路径。 -布局先拆成父组件与 Markdown 叶子,默认不写整页 HTML。构造值与启动进程是两件事; -下面示例从生产者开始,所有句柄沿同一会话传递,渲染时才需要原生插件。 - -```sh -marqdo call ext/web/网页/客户端/索引.mq.md 挂载 --json -marqdo call ext/web/网页/客户端/索引.mq.md 文本补丁 '选择器="#status"' '文本="就绪"' --json -``` - -页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。 -整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程 -读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。 - -开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。 -验证 web_handbook 与既有 Web Artifact 金样,资源、鉴权和网络能力不要塞回门面。 - -## 挂载 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 桥 | text | "/static/marqdo-bridge.js" | bridge 脚本 URL | -| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL | -| 源 | text | "" | 可选源 | -| 启动 | bool | True | 自动启动 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | script 标签 HTML | - -这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。 - -返回加载官方浏览器桥的 HTML 片段。默认 `桥`="/static/marqdo-bridge.js"、 - -`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。不是用 HTML 拼整页的 -借口。 - -完成后返回*[调用 embed](client.embed(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*。 - -## 文本补丁 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | text | 必填 | CSS 选择器 | -| 文本 | text | 必填 | 文本内容 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 效果表 | - -这里使用`选择器`、`文本`。 - -为选择器 `选择器` 构造 `set_text` 效果表,文本为 `文本`。 - -完成后返回*[调用 text patch](client.text_patch(sel=`选择器`, text=`文本`))*。 - -## 节点补丁 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | text | 必填 | CSS 选择器 | -| html | text | "" | 可选 HTML | -| 属性 | any | None | 可选属性表 | -| 移除 | bool | False | 是否移除 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 效果表 | - -这里使用`选择器`、`html`=""、`属性`=None、`移除`=False。 - -为选择器 `选择器` 构造 `dom` 效果表。可选 `html`=""、`属性`=None、`移除`=False。 - -完成后返回*[调用 dom patch](client.dom_patch(sel=`选择器`, html=`html`, attrs=`属性`, remove=`移除`))*。 - -## 挂载节点 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 桥 | text | "/static/marqdo-bridge.js" | 官方浏览器桥地址 | -| wasm | text | "/static/marqdo_wasm.wasm" | 当前构建的 WASM 产物地址 | -| 源 | text | "" | 可选客户端 Marqdo 程序地址 | -| 启动 | bool | True | 是否自动挂载客户端程序 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 组件 Document 可直接组合的脚本资源节点 | - -这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""和`启动`=True。节点引用官方模块资源,把 WASM 和程序地址保留为属性数据。启动关闭时只声明桥,不自动执行客户端。构造无需插件,不访问网络,也不生成业务 HTML;浏览器打开页面后才加载实际文件。应先构建当前 WASM 并挂载静态目录,再把这些节点与内容组件组合。旧的字符串挂载工具保留兼容用途。 - -完成后返回*[将官方运行时作为结构资源声明](client.nodes(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*. diff --git a/ext/web/网页/文档对象模型/索引.mq.md b/ext/web/网页/文档对象模型/索引.mq.md deleted file mode 100755 index 857bfd9..0000000 --- a/ext/web/网页/文档对象模型/索引.mq.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页/文档对象模型 -description: DOM Artifact — Markdown 默认;raw HTML 仅逃逸舱(ADR 0007)。 -import: - dom: ext/web/dom/index.mq.md ---- - -文档对象模型模块:从[中文根手册](../索引.mq.md)选择业务路径。 -布局先拆成父组件与 Markdown 叶子,默认不写整页 HTML。构造值与启动进程是两件事; -下面示例从生产者开始,所有句柄沿同一会话传递,渲染时才需要原生插件。 - -```sh -marqdo call ext/web/网页/文档对象模型/索引.mq.md 自Markdown '文本="# 可读"' --session handbook --toget body --json -marqdo call ext/web/网页/文档对象模型/索引.mq.md 渲染 'dom=$body' --effects plugin --session handbook --json -``` - -页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。 -整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程 -读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。 - -开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。 -验证 web_handbook 与既有 Web Artifact 金样,资源、鉴权和网络能力不要塞回门面。 - -## 自Markdown - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 文本 | text | 必填 | Markdown 源 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | DOM 映射 | - -这里使用`文本`。 - -把 Markdown `文本` 变成 `{kind:"markdown", text}`,供页面渲染。 - -完成后返回*[调用 from markdown](dom.from_markdown(text=`文本`))*。 - -## 原始 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| html | text | 必填 | 原始 HTML | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | DOM 映射 kind=raw | - -这里使用`html`。 - -逃逸舱 — 包装原始 `html`。仅当表驱动无法表达宿主约束时使用,并写明原因。 - -完成后返回*[调用 raw](dom.raw(html=`html`))*。 - -## 渲染 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dom | any | 必填 | 自Markdown 或 原始 的结果 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML 文本 | - -这里使用`dom`。 - -把 DOM 映射 `dom` 渲染为 HTML(须插件)。 - -完成后返回*[调用 render](dom.render(dom=`dom`))*。 diff --git a/ext/web/网页/索引.mq.md b/ext/web/网页/索引.mq.md deleted file mode 100755 index 51741de..0000000 --- a/ext/web/网页/索引.mq.md +++ /dev/null @@ -1,230 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页 -description: 网络库可执行开发手册;先拆布局,直到 Markdown 叶子。 -import: - 布局: ext/web/布局/索引.mq.md - 网页: ext/web/网页.mq.md ---- - -网络扩展手册:先描述页面如何拆分,再写各块内容,最后预览、起站和验证。 -普通 .mq.md 函数就是工具,无需另一套 Skill 编译器或工具目录。 -安装用户先执行 marqdo ext add web;源码开发先用 bash scripts/build-web-plugin.sh 构建 -Go 插件,必要时用 MARQDO_WEB_PLUGIN 指向其绝对路径,不能把安装根覆盖到源码 ext。 - -先看可执行结果 - -以下命令从仓库根运行;安装后把 FILE 换为安装根下对应路径。 -call 的文本字面量需要保留内层双引号,会话引用必须保护美元符号。 -同时检查退出码与 JSON 的 ok,再读取 result。 - -```sh -marqdo call ext/web/网页/索引.mq.md 布局规则 --json -marqdo call ext/web/网页/索引.mq.md 预览正文 '正文="# 可读页面"' '标题="预览"' --effects plugin --json -marqdo call ext/web/网页/索引.mq.md 预览节点 '节点=[{"type":"row","value":[{"type":"markdown","value":"## 左栏"},{"type":"markdown","value":"## 右栏"}]}]' --effects plugin --json -``` - -先拆布局的工程实践 - -首页先拆为导航、主体和页脚。页脚有左右布局,就拆成品牌栏与链接栏;链接栏若还有 -双栏,再拆文档和社区。递归进行,直到内部只是简单 Markdown 能直接表示的内容。 -终点是单一内容职责且不再需要内部排布,不是每段话都新建文件。 - -```text -site/ - index.mq.md Document,选择布局根 - components/index.mq.md 纵排:导航、主体、页脚 - nav/index.mq.md 一个导航职责 - nav/content.md 普通 Markdown 链接 - main/index.mq.md - main/content.md 普通 Markdown 正文 - footer/index.mq.md 分栏:品牌、链接 - brand/index.mq.md - brand/content.md 品牌与版权 - links/index.mq.md 分栏:文档、社区 - docs/index.mq.md - docs/content.md 文档链接 - community/index.mq.md - community/content.md 社区链接 - pages/about.mq.md 另一条声明路由 - api/ping.mq.md Endpoint - preview.mq.md 离线装配并渲染 - serve.mq.md 启动进程,不放页面内容 -``` - -每个父 index 只导入子块、组合子节点、选择一层布局;每个叶子 content.md 只写 Markdown。 -父块出现大段正文、多种布局职责或 HTML 标签就继续拆;叶子不负责外部排列。 -不应先写整页 HTML,再把这个字符串切成几个文件。默认也不靠内联 CSS 对齐。 -复杂表格、表单、数据源和交互按各自职责再分模块,不能以此回填整页 HTML 壳。 - -跟着真实工程做 - -[中文参考站点](../../../examples/web-layout-handbook-zh/index.mq.md)实现完整目录, -沿[组件根](../../../examples/web-layout-handbook-zh/components/index.mq.md)可一直走到页脚孙级叶子。 -[英文工程](../../../examples/web-layout-handbook/index.mq.md)用同一表示与渲染器。 -先从仓库根生成预览,再从站点目录运行服务: - -```text -marqdo call examples/web-layout-handbook-zh/preview.mq.md main --effects plugin,fs.read,output.write --fs-root examples/web-layout-handbook-zh --json -marqdo call ext/web/网页.mq.md 服务 '根="examples/web-layout-handbook-zh"' --effects plugin,fs.read,network.write --fs-root examples/web-layout-handbook-zh --json -``` - -检查 / 首页、/about 普通文档、/api/ping JSON。首页应真的出现父子嵌套与两个页脚区域, -不是把同一组节点平铺。宽屏横排,窄屏自动折叠,无需作者手写 HTML 或 CSS。 - -现有五列怎样表达树 - -公共 View 列仍为 type、slot、value、attrs、style,中文别名为 类型、槽、值、属性、样式。 -记录表首列使用 @,让输出为节点列表。父节点类型 row/column 表示几何,值列保留子表; -nav/header/footer/section/aside 表示语义区域。markdown 的值是正文字符串。 -类型和值没有变成另一种私有 DSL。合并仅生成兄弟顺序,分栏才产生几何关系。 -style 是类名引用,不会凭空定义 CSS;运行时内置默认布局,主题后续按独立资源处理。 - -最小叶子可以直接以 Markdown 文本调用组件正文。文件较长时像参考工程一样从 -content.md 读取,这样原始文件无需转义字符串。父文件不用提前渲染子组件。 - -```marqdo ---- -markup: occlusion -导入: - 组件: ext/web/网页/组件/索引.mq.md - 布局: ext/web/布局/索引.mq.md - 网页: ext/web/网页.mq.md ---- - -# main - -**left = 组件.正文 文本="### 品牌" 槽="brand"** -**right = 组件.正文 文本="[关于](/about)" 槽="links"** -**siblings = 组件.合并 甲=`left` 乙=`right`** -**footer = 布局.分栏 子节点=`siblings` 槽="footer"** -**html = 网页.渲染 节点=`footer` 标题="分栏预览"** -> 打印 内容=`html` -``` - -Document、Endpoint 与运行边界 - -普通 Document 用 类型: 网页、路由、标题和 Markdown 正文,保留原来的静态/数据源路径。 -组件 Document 另外声明 视图: main,其普通 main 函数返回节点列表;服务在启动时执行装配一次, -通过同一渲染器生成 HTML。改内容后重启。自动数据源绑定使用普通 Document,不与此启动装配混用。不要在这个装配函数里再启动服务器或调用渲染; -它返回结构即可。请求期互动放在 Endpoint,声明 类型: 端点、路径、方法、请求、响应, -主程序返回响应值。不要把启动时装配误解为自动的请求期模板绑定。 - -服务是长时间阻塞的生命周期操作,可用 marqdo call 直接调用,并显式授予 -plugin、fs.read、network.write。需要更多资源时,在普通启动函数中顺序组合准备站点、 -各资源的绑定工具与监听,并保留每次更新后的应用。网络库负责 WebSocket,安全库负责 -登录与会话;准备阶段不会打开端口。网页检视给出根目录时可离线扫描声明;新进程中的空应用 -不能检视另一个进程的私有路由状态。 - -```sh -marqdo call ext/web/网页.mq.md 检视 '根="examples/web-layout-handbook-zh"' --effects plugin --json -``` - -按职责打开模块 - -[布局](../布局/索引.mq.md)教会何时继续拆、纵排与分栏;[组件](组件/索引.mq.md)负责 -Markdown 叶子与语义包裹;[页面](页面/索引.mq.md)负责句柄与离线渲染; -[路由](路由/索引.mq.md)用于高级手动声明,整站默认走 Metadata。 -[文档对象模型](文档对象模型/索引.mq.md)提供内容转换,原始 HTML 仅为兼容边界。 -[客户端](客户端/索引.mq.md)挂载 Marqdo WASM,业务交互继续使用 lib/browser; -[能力](能力/索引.mq.md)只诊断原生加载。[门面](../网页.mq.md)保留服务、渲染、检视和应用 API。 -数据库、鉴权、HTTP 客户端分别去 ext/data、ext/security、ext/net。 -[页头资源](../页头.mq.md)保留真实 SEO、字体与资源声明,能用于离线预览;它不会成为正文或片段占位。数据查询、表单引用和会话导航仍在真实请求中解析,继续沿用五列 View。完整中文实践见 [网络站点入口](../../../examples/web-net-site-zh/index.mq.md)。 - -开发路线与验收 - -先尝试组合现有 Markdown、纵排、分栏。新增原语才修改 plugins/web/internal/artifact -与 ABI 导出,普通页面不要新增宿主原语。保持双语入口与五列结构,参数契约紧跟标题, -返回契约也在首条执行语句之前。## 只能用于真正工具,普通说明保持叙述段落。 -新增文件时更新 src/ext_cli.rs 安装清单。修改 Document 启动装配要保留普通文档与 API 的行为。 - -```text -marqdo call skills/marqdo-dev/index.mq.md test 'targets=["web_handbook"]' --effects plugin --fs-root . --require-ok --json -marqdo call skills/marqdo-dev/index.mq.md test 'targets=["call_cli"]' 'filter="web_"' --effects plugin --fs-root . --require-ok --json -marqdo call skills/marqdo-dev/index.mq.md test 'targets=["gold"]' 'filter="ext_web"' --effects plugin --fs-root . --require-ok --json -``` - -手册门禁直接执行本包双语 sh 围栏与作者程序,另外预览并启动参考工程,核对路由、 -嵌套结构和 API。叙述比例只作最低门槛,清单不能无条件发放“通过”。 -当前没有自动把任意网页拆成组件的功能,也没有靠样式列实现完整 CSS 编译器。 -布局仍是作者的显式设计决定,这些入口与运行证据帮助 AI 遵守它。 - -## 建站手册 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Development workflow and stopping rule | - -返回建站流程与拆分终点,不执行文件操作,也不声称已经验收某个站点。 -先建立区域树,再写父组件与 Markdown 叶子,最后按声明路由启动并测试。 - -这张表返回工程步骤与停止条件,供作者安排实现顺序;它不会自动创建目录、拆分现有页面或替站点完成验收。先确定区域树,把首页拆成导航、主体与页脚。若页脚有品牌栏和链接栏,再拆子区域;链接有文档与社区两栏时继续拆分。父文件只表达一层布局,叶子只保留可直接阅读的 Markdown 内容。 - -区域树稳定后,首页用 Document 元数据声明路由并选择装配入口。其他页面各自声明路由,接口逻辑放到 Endpoint,使请求期间的业务计算与启动时的页面装配各有归属。不要在返回组件的函数里启动服务器,也不要把启动时运行一次的装配误当作每次请求都会执行的数据绑定。 - -实现过程中先离线预览,核对实际父子节点和区域内容;再从站点目录启动服务,检查首页、普通文档和 API 的真实响应。浏览器还需验证宽屏分栏与窄屏折叠。只看清单文本、返回固定 ready 或将整页 HTML 分成几个字符串文件,都不能证明已实现统一的文档架构。若某个块仍需独立内部排列,就返回布局拆分阶段继续细化。 - -`workflow` = - -| key | value | -|-----|-------| -| goal | build a site as executable documents | -| step_A | draw region tree before content | -| step_B | recursively split components to Markdown leaves | -| step_C | declare home Document and view main for composed structure | -| step_D | declare more Documents with their own routes | -| step_E | declare Endpoint handlers for request-time work | -| step_F | run serve.mq.md from the site directory | -| step_G | compare preview and live output; test routes and browser geometry | -| stopping_rule | one Markdown responsibility and no internal layout | - -完成后返回*workflow*。 - -## 布局规则 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Development workflow and stopping rule | - -复用布局模块的实践约定,保持一个真相源。无参数,不需要插件。 -规则描述预期做法,实际站点仍需检查叶子、父关系与运行结果。 - -完成后返回*[调用 规则](布局.规则())*。 - -## 预览正文 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 正文 | text | "" | Markdown content | -| 标题 | text | "Preview" | Document title | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | HTML document | - -这里使用`正文`=""、`标题`="Preview"。 - -离线渲染 Markdown `正文`="",默认 `标题`="Preview"。 -此工具只返回 HTML 文本,不写文件、不注册路由。复杂页面先拆布局, -不要用整页原生 HTML 字符串冒充正文。需要原生插件。 - -完成后返回*[调用 渲染](网页.渲染(正文=`正文`, 标题=`标题`))*。 - -## 预览节点 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 节点 | list | 必填 | Nested View rows | -| 标题 | text | "Preview" | Document title | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | HTML document | - -这里使用`节点`、`标题`="Preview"。 - -渲染已经按职责拆分的 `节点`,默认 `标题`="Preview"。 -父节点的值继续持有子节点,叶子值为 Markdown;返回 HTML 不会启动服务。 -与真实 Document 的装配使用同一渲染器,能检查双栏是否确实保留了层级。 - -完成后返回*[调用 渲染](网页.渲染(节点=`节点`, 标题=`标题`))*。 diff --git a/ext/web/网页/组件/索引.mq.md b/ext/web/网页/组件/索引.mq.md deleted file mode 100755 index 33cda06..0000000 --- a/ext/web/网页/组件/索引.mq.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页/组件 -description: 纯组件:Markdown 叶子与嵌套 View 节点。 -import: - component: ext/web/component/index.mq.md ---- - -组件是返回 View 记录列表的普通函数。父文件只表达子块关系,叶子只负责一段 Markdown。 -页脚拆成品牌与链接,链接若仍是双栏就继续拆,直到每个文件只有一个可解释的内容职责。 -完整参考见[拆分站点](../../../../examples/web-layout-handbook/index.mq.md)。 - -以下构造均为纯函数,无需插件或已有句柄: - -```sh -marqdo call ext/web/网页/组件/索引.mq.md 正文 '文本="## 可读的叶子"' '槽="介绍"' --json -marqdo call ext/web/网页/组件/索引.mq.md 包裹 '子节点=[{"type":"markdown","value":"左"},{"type":"markdown","value":"右"}]' '种类="row"' --json -marqdo call ext/web/网页/组件/索引.mq.md 合并 '甲=[{"type":"text","value":"前"}]' '乙=[{"type":"text","value":"后"}]' --json -marqdo call ext/web/网页/组件/索引.mq.md 资源 '地址="/static/generated/theme.css"' '种类="stylesheet"' --json -``` - -复用组件使用 @ 记录表,合并只确定兄弟顺序,不会自动产生双栏。布局请转到 -[布局入口](../../布局/索引.mq.md),渲染交给[页面](../页面/索引.mq.md)。 -新增内容先在站点组件目录实现;新结构类型需同步 Go 渲染器、双语入口与实际页面测试。 -不要先渲染子块再拼 HTML 字符串,值单元格应保留子节点列表本身。 - -## 节点 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 表 | any | 必填 | View 表 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 原样返回输入 View 表,保留记录列表或列式表的实际形态 | - -这里使用`表`。 - -原样返回 `表`,保留已有恒等入口。可接受列式表或记录列表; -需要组合和嵌套时统一选择 @ 记录列表,让子表保持结构值而不是字符串。 - -完成后返回*[调用 nodes](component.nodes(table=`表`))*。 - -## 合并 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 甲 | list | 必填 | 第一组节点记录 | -| 乙 | list | 必填 | 第二组节点记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 有序兄弟节点 | - -这里使用`甲`、`乙`。 - -拼接 `甲` 与 `乙`,保留顺序和内部父子关系。输入均为 @ 记录列表; -本工具不把平面节点变成两栏,需要双栏时再交给布局的分栏工具。 - -完成后返回*[调用 merge](component.merge(a=`甲`, b=`乙`))*。 - -## 正文 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 文本 | text | 必填 | 普通 Markdown | -| 槽 | text | "" | 区域名 | -| 样式 | text | "" | 可选类名 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 单个 Markdown 叶子 | - -这里使用`文本`、`槽`=""、`样式`=""。 - -将 Markdown `文本` 包成叶子,默认 `槽`=""、`样式`=""。 -不加载原生插件,输出仍为结构数据;标题、链接、列表与表格在渲染时处理。 -叶子不关心自己位于页脚左栏还是其他位置,父组件负责几何关系。 - -完成后返回*[调用 markdown](component.markdown(text=`文本`, slot=`槽`, style=`样式`))*。 - -## 包裹 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 子节点 | list | 必填 | 子块记录列表 | -| 种类 | text | "column" | 容器类型 | -| 槽 | text | "" | 区域名 | -| 样式 | text | "" | 可选类名 | -| 属性 | any | None | 容器属性记录,例如 id 与 hidden | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 包含子节点的父块 | - -这里使用`子节点`、`种类`="column"、`槽`=""、`样式`=""、`属性`=None。 - -将 `子节点` 放进一层父容器,默认 `种类`="column"、`槽`=""、`样式`=""。 -几何类型为 row、column;语义类型包括 nav、header、footer、section、aside。 -值单元格保留子表,不承载拼好的 HTML;构造器只生成结构,实际形状由渲染器检查。 - -完成后返回*[调用 wrap](component.wrap(children=`子节点`, kind=`种类`, slot=`槽`, style=`样式`, attrs=`属性`))*。 - -## 控件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 种类 | text | 必填 | input、button、textarea、label、pre、option、text 或 link | -| 值 | text | "" | 控件文字或输入框初值 | -| 属性 | any | None | id、name、布尔标志等属性记录 | -| 槽 | text | "" | 布局区域名 | -| 样式 | text | "" | 可选样式类名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 现有五列 View 结构中的单个控件叶子 | - -这里使用`种类`、`值`=""、`属性`=None、`槽`=""和`样式`=""。当普通 Markdown 无法表示编辑框或客户端事件目标时,才使用原生控件。属性记录中的 required、hidden 等必须是布尔值;控件文字按文本转义,不解释为 HTML。表单、列表和语义区域仍用包裹函数保存子节点关系。构造器本身是纯函数,实际渲染阶段检查类型与属性;事件处理器和内联样式不能混入属性表。客户端状态可用 data 与 aria 属性,外观通过类名引用站点样式表。 - -完成描述后返回*[构造可检查的原生控件](component.element(kind=`种类`, value=`值`, attrs=`属性`, slot=`槽`, style=`样式`))*. - - - -## 资源 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 地址 | text | 必填 | 应用提供的脚本或样式表 URL | -| 种类 | text | "script" | script 或 stylesheet | -| 属性 | any | None | 模块类型、完整性或 data-mq 等属性记录 | -| 槽 | text | "" | 可选资源区域名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 现有五列 View 结构中的单个资源叶子 | - -这里使用`地址`、`种类`="script"、`属性`=None、`槽`=""。脚本节点只引用资源地址,不承载内联业务 JavaScript;样式节点引用独立 CSS 文件。地址保留在值列,其余信息保留在属性记录。构造本身不访问网络,也不验证文件存在;原生渲染器负责转义和属性检查,浏览器打开页面后才加载资源。这样运行时桥和主题可以独立组织,不需要把整个页面写成 HTML 字符串。 - -完成后返回*[声明浏览器需要的独立资源](component.asset(url=`地址`, kind=`种类`, attrs=`属性`, slot=`槽`))*. - - - -## 请求资源 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 值 | map | 必填 | 数据查询、表单引用、导航或纯页头声明的具型资源 | -| 槽 | text | "" | 动态内容区域的稳定名称 | -| 样式 | text | "" | 资源外层的可选类名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | list | 五列 View 中的一个资源节点 | - -使用`值`、`槽`=""与`样式`="",把职责模块提供的资源放进布局。查询来自数据视图模块,表单由表单模块显式挂载,导航由下方工具构造,纯页头来自 ext/web/页头.mq.md。值单元格保留资源本身,父组件不先把子内容渲染成 HTML。 - -构造是纯计算,不查询数据库、不提交表单,也不加载插件。服务器准备请求参数、会话与 CSRF 后才解析资源。未知种类在监听前失败,缺失运行资源保留实际请求诊断。离线渲染不能伪造请求上下文或返回固定成功;纯页头声明可以离线预览,并收集进真正的 head,不作为正文占位。 - -`节点` = - -| @ | 类型 | 槽 | 值 | 属性 | 样式 | -|---|---|---|---|---|---| -| 1 | resource | `槽` | `值` | None | `样式` | - -父布局确定位置后,返回 *节点*,与静态 Markdown 和控件继续组合。 - -## 导航资源 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 项 | any | 必填 | 含 label、href 及可选 when、class、media 的链接记录 | -| 区域 | text | "nav" | nav、sidebar 或 footer | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 由实际会话决定链接可见性的纯导航资源 | - -使用`项`与`区域`="nav"声明链接目的地。when 为 guest 或 auth 时根据当前请求会话筛选;空条件始终显示。父组件仍决定布局,原生导航渲染器保留已有类名和条件显示能力,不在作者源码中拼写整段 HTML。 - -隐藏链接不能保护目标地址。鉴权与角色门禁仍须由服务端资源显式绑定,构造导航不注册隐式路由,也不执行登录或退出。把返回值放入资源节点后,监听期间才读取真实会话;离线读取不会伪造某个用户的登录状态。 - -`资源` = - -| _type | items | region | -|---|---|---| -| view_navigation | `项` | `区域` | - -声明完可见性与目的地后,返回 *资源*,交给相同的五列 View 组合。 diff --git a/ext/web/网页/能力/索引.mq.md b/ext/web/网页/能力/索引.mq.md deleted file mode 100755 index b3c44d5..0000000 --- a/ext/web/网页/能力/索引.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页/能力 -description: Web ABI 加载 skill。日常请走领域模块;诊断插件时再 call 加载。 -import: - cap: ext/web/_capability/index.mq.md ---- - -能力模块:从[中文根手册](../索引.mq.md)选择业务路径。 -布局先拆成父组件与 Markdown 叶子,默认不写整页 HTML。构造值与启动进程是两件事; -下面示例从生产者开始,所有句柄沿同一会话传递,渲染时才需要原生插件。 - -```sh -marqdo call ext/web/网页/能力/索引.mq.md 加载 --effects plugin --json -``` - -页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。 -整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程 -读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。 - -开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。 -验证 web_handbook 与既有 Web Artifact 金样,资源、鉴权和网络能力不要塞回门面。 - -## 加载 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 加载成功后为空 | - -通过 plugin.native_path 定位 ABI v2 web 动态库并 plugin.load。缺失时打印安装提 -示并以非零退出。无参数。 - -完成后返回*[加载本操作依赖的原生插件](cap.load())*。 diff --git a/ext/web/网页/路由/索引.mq.md b/ext/web/网页/路由/索引.mq.md deleted file mode 100755 index 4769097..0000000 --- a/ext/web/网页/路由/索引.mq.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页/路由 -description: 声明式 Endpoint / Document 路由注册(ADR 0007)。 -import: - route: ext/web/route/index.mq.md ---- - -路由模块:从[中文根手册](../索引.mq.md)选择业务路径。 -布局先拆成父组件与 Markdown 叶子,默认不写整页 HTML。构造值与启动进程是两件事; -下面示例从生产者开始,所有句柄沿同一会话传递,渲染时才需要原生插件。 - -```sh -marqdo call ext/web/网页/路由/索引.mq.md 新建 '应用={}' '路径="/hello"' '页面={"title":"Hello","body":"Hi"}' --effects plugin --session handbook --toget route --json -marqdo call ext/web/网页/路由/索引.mq.md 注册 '路由=$route' --effects plugin --session handbook --json -``` - -页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。 -整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程 -读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。 - -开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。 -验证 web_handbook 与既有 Web Artifact 金样,资源、鉴权和网络能力不要塞回门面。 - -## 新建 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 应用 | any | 必填 | 应用句柄 | -| 路径 | text | 必填 | URL 路径 | -| 方法 | text | "GET" | HTTP 方法 | -| 页面 | any | None | Document 或 None | -| 函数 | text | "" | Endpoint 成员 | -| 请求 | text | "json" | 请求体类型 | -| 响应 | text | "json" | 响应类型 | -| 鉴权 | text | "" | 鉴权标签 | -| 类别 | text | "" | 路由类别 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 路由句柄 | - -这里使用`应用`、`路径`、`方法`="GET"、`页面`=None、`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。 - -为 `应用` 在 `路径` 上构造路由句柄,`方法`="GET"。`页面`=None 或 `函数`="" 二 -选一。`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。本工具尚未注册——再 -调 `注册`,或用门面 `路由` 一步完成。 - -完成后返回*[调用 new](route.new(app=`应用`, path=`路径`, method=`方法`, page=`页面`, fn=`函数`, request=`请求`, response=`响应`, auth=`鉴权`, class=`类别`))*。 - -## 注册 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路由 | any | 必填 | 路由句柄 | -| 应用 | any | None | 应用或 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 注册结果 | - -这里使用`路由`、`应用`=None。 - -把路由句柄 `路由` 注册到应用;可选 `应用`=None 时用句柄内保存的应用。 - -完成后返回*[调用 register](route.register(route=`路由`, app=`应用`))*。 - -## 使用 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路由 | any | 必填 | 路由句柄 | -| 中间件 | any | 必填 | 中间件表 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 带 middleware 字段的路由记录;此步骤不注册或启动路由 | - -这里使用`路由`、`中间件`。 - -给路由句柄 `路由` 挂上中间件表 `中间件`。 - -完成后返回*[调用 use](route.use(route=`路由`, middleware=`中间件`))*。 diff --git a/ext/web/网页/页面/索引.mq.md b/ext/web/网页/页面/索引.mq.md deleted file mode 100755 index 72c60bb..0000000 --- a/ext/web/网页/页面/索引.mq.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -markup: occlusion -title: ext/web/网页/页面 -description: Document 句柄与渲染(ADR 0007)。文件划分布局;禁止默认 HTML 注入。 -import: - page: ext/web/page/index.mq.md ---- - -页面模块:从[中文根手册](../索引.mq.md)选择业务路径。 -布局先拆成父组件与 Markdown 叶子,默认不写整页 HTML。构造值与启动进程是两件事; -下面示例从生产者开始,所有句柄沿同一会话传递,渲染时才需要原生插件。 - -```sh -marqdo call ext/web/网页/页面/索引.mq.md 新建 '标题="预览"' '正文="# 你好"' --effects plugin --session handbook --toget pg --json -marqdo call ext/web/网页/页面/索引.mq.md 渲染 '页面=$pg' --effects plugin --session handbook --json -``` - -页面结构用五列 View 记录,父值保留子表。纯布局、DOM 构造和客户端描述无需插件。 -整站服务通过网页.服务或工程入口的 serve 函数用 marqdo call 启动;检视磁盘站点请给出根目录,不能从新进程 -读取另一个进程的私有应用。结构化 Document 使用 视图: main,在启动时执行布局装配。 - -开发时先复用组件和布局模块,再改对应领域实现;保持中英入口与真实契约一致。 -验证 web_handbook 与既有 Web Artifact 金样,资源、鉴权和网络能力不要塞回门面。 - -## 新建 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标题 | text | "" | 文档标题 | -| 路由 | text | "/" | 路径 | -| 方法 | text | "GET" | HTTP 方法 | -| 正文 | text | "" | Markdown 正文 | -| 节点 | any | None | View 表或 None | -| 数据源 | text | "" | 表名 | -| 排序 | text | "" | 排序键 | -| 条件 | text | "" | 过滤 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 页面句柄 | - -这里使用`标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、`节点`=None、`数据源`=""、`排序`=""、`条件`=""。 - -构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、 - -`节点`=None、`数据源`=""、`排序`=""、`条件`=""。节点必须是统一 View 表。 - -完成后返回*[调用 new](page.new(title=`标题`, route=`路由`, method=`方法`, body=`正文`, nodes=`节点`, data_source=`数据源`, data_order=`排序`, data_where=`条件`))*。 - -## 渲染 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 页面 | any | 必填 | Document 句柄 | -| 节点 | any | None | View 表或 None | -| 数据库 | any | None | 可选 db | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML 或渲染结果 | - -这里使用`页面`、`节点`=None、`数据库`=None。 - -渲染 Document 句柄 `页面`。可选 `节点`=None、`数据库`=None。不要把手写 HTML 当 -作页面壳。 - -完成后返回*[调用 render](page.render(page=`页面`, nodes=`节点`, db=`数据库`))*。 diff --git a/ext/web/页头.mq.md b/ext/web/页头.mq.md deleted file mode 100755 index 4166da5..0000000 --- a/ext/web/页头.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: 文档页头资源:SEO、字体与资源链接 -import: - head: ext/web/head.mq.md ---- - -本文件对应 head.mq.md。结构化页面将本资源交给组件的请求资源节点,服务器与离线预览都把它收集到真正的 head,不在正文或片段中留下占位。沿用现有五列 View,不增加新标记、嵌套元数据或页面变异链。 - -```sh -marqdo call ext/web/页头.mq.md 声明 '元数据=[{"key":"description","value":"可读的站点"}]' --json -``` - -## 声明 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 元数据 | any | None | key/value 行记录或 GFM 列式表,值为原生标量 | -| 链接 | any | None | rel/href 原生资源记录,支持媒体、跨域及脚本标志 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 供组件安放的纯 document_head 描述 | - -使用`元数据`=None、`链接`=None,构造不需要任何副作用。元数据保留 description、og: 等 SEO 名称,title、canonical、icon 等沿用普通文档约定;charset、viewport 和 csrf-token 归运行时所有,不在这里重声明。 - -链接复用原生 rel/href 表与中文字段别名,可声明字体预连接、样式、图标或显式脚本资源。地址只允许 / 开头的站内路径与 http(s),不接受活动数据方案或协议相对地址。这里不下载字体、不执行脚本、不挂载静态文件;浏览器打开实际页面后才请求地址。官方桥仍用客户端挂载节点,不在资源里写业务 JavaScript。 - -多个子组件可以贡献资源,相同链接去重,同名元数据有不同值时保留诊断,不静默覆盖。片段不会重复输出页头;离线预览能处理本纯资源,但查询、表单与会话导航仍需真实请求上下文。缺失文件、网络可用性和页面视觉效果须另做实际验证,构造描述不能证明这些条件。 - -声明完成后返回 *[复用同一个文档页头契约](head.resource(meta=`元数据`, links=`链接`))*。 diff --git a/include/marqdo_abi.h b/include/marqdo_abi.h deleted file mode 100755 index c61eec5..0000000 --- a/include/marqdo_abi.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Marqdo plugin ABI v2 — C contract (source of truth). - * - * Plugins are optional shared libraries (.dll / .so / .dylib), never linked - * into the marqdo binary. Values cross the boundary as UTF-8 JSON. - * - * v1: register_fn, alloc, free - * v2: + host_query (allowlisted host introspection for plugins) - */ -#ifndef MARQDO_ABI_H -#define MARQDO_ABI_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MARQDO_ABI_VERSION 2u -#define MARQDO_ABI_VERSION_MIN 1u - -/* Plugin function: args_json is a UTF-8 JSON object whose keys are param names. - * On success: return 0, set *out_json to a heap string (host frees via free). - * On failure: return non-zero; optional *err_msg heap string (host frees). - * out_json / err_msg may be left NULL. - */ -typedef int (*MarqdoPluginFn)(const char *args_json, char **out_json, char **err_msg); - -/* Host → plugin query (v2). `name` is an allowlisted query id. - * Same success/failure convention as MarqdoPluginFn. - */ -typedef int (*MarqdoHostQueryFn)(void *userdata, const char *name, const char *args_json, - char **out_json, char **err_msg); - -typedef struct MarqdoHostApi { - void *userdata; - /* params: comma-separated param names in order, e.g. "a,b". May be "". */ - int (*register_fn)(void *userdata, const char *name, const char *params, - MarqdoPluginFn fn); - void *(*alloc)(size_t n); - void (*free)(void *p); - /* v2: NULL for hosts that only speak v1; required when plugin abi >= 2 */ - MarqdoHostQueryFn host_query; -} MarqdoHostApi; - -/* Required exports from every plugin shared library. */ -uint32_t marqdo_plugin_abi_version(void); -int marqdo_plugin_init(const MarqdoHostApi *host); -void marqdo_plugin_shutdown(void); - -#ifdef __cplusplus -} -#endif - -#endif /* MARQDO_ABI_H */ diff --git a/lib/archive.mq.md b/lib/archive.mq.md deleted file mode 100755 index 57863f3..0000000 --- a/lib/archive.mq.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -markup: occlusion ---- - -Optional ZIP tasks: native defaults include ZIP; minimal/browser builds report unavailable. Returns Result. - -ZIP tasks are optional native capabilities, with no standalone plugin to install. -The pack/unpack contracts below define both operations. Both return -Result and require fs.write. Source and destination paths stay under the granted -root; output must not already exist. Extraction preflights paths, duplicate -entries, symlinks and the uncompressed byte limit before creating its directory. -Failed extraction removes only the newly-created destination. Minimal/browser -builds report unavailable; they never pretend to have written an archive. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. - -Implementation: [src/host/archive.rs](../src/host/archive.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## pack - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| src | text | required | Source path; archive packing expects a directory | -| dest | text | required | Destination path; overwrite is allowed only where documented | -| max_bytes | number | 1073741824 | Maximum bytes read or expanded; exceeding it fails | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Result containing the count of archived regular files, or a structured error | - -Use `src`, `dest`, `max_bytes`=1073741824 as the inputs for this operation. - -Effects: fs.write. - -For this example, set MQ_WORK to an existing disposable directory with regular files in an input subdirectory. bundle.zip and output must not exist. Keep or clean the produced artifacts explicitly. - -```sh -marqdo call lib/archive.mq.md pack 'src="input"' 'dest="bundle.zip"' --fs-root "$MQ_WORK" --effects fs.write --json -marqdo call lib/archive.mq.md unpack 'src="bundle.zip"' 'dest="output"' --fs-root "$MQ_WORK" --effects fs.write --json -``` - -Destination must not exist. Caps total uncompressed bytes and 100000 entries; rejects symlinks and escaping paths. Pack includes regular files; failed unpack removes only its newly-created destination. - -Return *[Pack regular files into ZIP without overwriting an existing destination](> host_zip_pack src=`src` dest=`dest` max_bytes=`max_bytes`)*. - -## unpack - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| src | text | required | Source path; archive packing expects a directory | -| dest | text | required | Destination path; overwrite is allowed only where documented | -| max_bytes | number | 1073741824 | Maximum bytes read or expanded; exceeding it fails | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Result containing the extracted entry count, or a structured error | - -Use `src`, `dest`, `max_bytes`=1073741824 as the inputs for this operation. - -Effects: fs.write. - -Destination must not exist. Caps total uncompressed bytes and 100000 entries; rejects symlinks and escaping paths. Pack includes regular files; failed unpack removes only its newly-created destination. - -Return *[Validate and extract ZIP entries without escaping the root or overwriting a destination](> host_zip_unpack src=`src` dest=`dest` max_bytes=`max_bytes`)*. diff --git a/lib/browser.mq.md b/lib/browser.mq.md deleted file mode 100755 index a4c0c1c..0000000 --- a/lib/browser.mq.md +++ /dev/null @@ -1,735 +0,0 @@ ---- -markup: occlusion -title: lib/browser -description: >- - Readable browser effect helpers for WASM clients. Prefer GFM tables + these - helpers; do not build effects with json.set chains. -import: - table: lib/table.mq.md ---- - -Readable browser effect helpers for WASM clients. Prefer GFM tables + these helpers; do not build effects with json.set chains. - -Build browser effects as ordinary structured values. - -Behavior and limits: Constructing an effect is pure; the official WASM bridge performs it in a browser. Native construction does not prove a DOM update occurred. Keep business logic in Marqdo. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [crates/marqdo-wasm/js/marqdo-bridge.js](../crates/marqdo-wasm/js/marqdo-bridge.js) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## set_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build set_text effect map for the official bridge | - -Use `sel`, `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/browser.mq.md set_text 'sel="#status"' 'text="Ready"' --effects none --json -``` - -Build set_text effect map for the official bridge. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`text`))**. -Return *[Set the set_text field in the new record](table.put(in=None, at="set_text", value=`m`))*. - -## set_html - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| html | any | required | HTML fragment; use set_text for ordinary untrusted text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build set_html effect map | - -Use `sel`, `html` as the inputs for this operation. - -Effects: pure. - -Build set_html effect map. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`html`))**. -Return *[Set the set_html field in the new record](table.put(in=None, at="set_html", value=`m`))*. - -## set_value - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build set_value effect map | - -Use `sel`, `value` as the inputs for this operation. - -Effects: pure. - -Build set_value effect map. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`value`))**. -Return *[Set the set_value field in the new record](table.put(in=None, at="set_value", value=`m`))*. - -## set_class - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| class | any | required | Space-separated CSS class names | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build set_class effect map | - -Use `sel`, `class` as the inputs for this operation. - -Effects: pure. - -Build set_class effect map. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. -Return *[Set the set_class field in the new record](table.put(in=None, at="set_class", value=`m`))*. - -## add_class - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| class | any | required | Space-separated CSS class names | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build add_class effect map (classList.add; space-separated names OK) | - -Use `sel`, `class` as the inputs for this operation. - -Effects: pure. - -Build add_class effect map (classList.add; space-separated names OK). - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. -Return *[Set the add_class field in the new record](table.put(in=None, at="add_class", value=`m`))*. - -## remove_class - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| class | any | required | Space-separated CSS class names | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build remove_class effect map | - -Use `sel`, `class` as the inputs for this operation. - -Effects: pure. - -Build remove_class effect map. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. -Return *[Set the remove_class field in the new record](table.put(in=None, at="remove_class", value=`m`))*. - -## toggle_class - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| class | any | required | Space-separated CSS class names | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build toggle_class effect map | - -Use `sel`, `class` as the inputs for this operation. - -Effects: pure. - -Build toggle_class effect map. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. -Return *[Set the toggle_class field in the new record](table.put(in=None, at="toggle_class", value=`m`))*. - -## set_style - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| style | any | required | CSS property/value record for the target element | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build set_style effect map; style is a map of CSS properties or a cssText string | - -Use `sel`, `style` as the inputs for this operation. - -Effects: pure. - -Build set_style effect map; style is a map of CSS properties or a cssText string. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`style`))**. -Return *[Set the set_style field in the new record](table.put(in=None, at="set_style", value=`m`))*. - -## set_attr - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| attrs | any | required | HTML attribute/value record for the target element | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build set_attr effect map; attrs is usually a small map of attribute names to values | - -Use `sel`, `attrs` as the inputs for this operation. - -Effects: pure. - -Build set_attr effect map; attrs is usually a small map of attribute names to values. - -We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`attrs`))**. -Return *[Set the set_attr field in the new record](table.put(in=None, at="set_attr", value=`m`))*. - -## wrap - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | required | Field name or key required by this operation | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Single-key effect map wrapper | - -Use `key`, `value` as the inputs for this operation. - -Effects: pure. - -Single-key effect map wrapper. - -Return *[Return the updated structured value](table.put(in=None, at=`key`, value=`value`))*. - -## merge - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First browser effect record | -| b | any | required | Browser effect record to merge over a | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Merge two effect maps; right-hand keys win | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Merge two effect maps; right-hand keys win. - -Return *[Merge](table.merge(a=`a`, b=`b`))*. - -## canvas - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| commands | any | required | Ordered list of canvas drawing commands | -| clear | any | True | Whether the canvas is cleared before drawing commands | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build canvas effect; commands is usually an @ GFM table | - -Use `sel`, `commands`, `clear`=True as the inputs for this operation. - -Effects: pure. - -Build canvas effect; commands is usually an @ GFM table. - -`spec` = - -| sel | clear | commands | -|-----|-------|----------| -| `sel` | `clear` | `commands` | - -Return *[Set the canvas field in the new record](table.put(in=None, at="canvas", value=`spec`))*. - -## audio - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| op | any | "play" | Audio command: play, pause or stop | -| id | any | "default" | Audio channel identifier | -| src | text | "" | Audio URL, or beep for a synthesized tone | -| freq | any | None | Oscillator frequency in hertz | -| ms | any | None | Duration or delay in milliseconds | -| sel | any | "" | CSS selector of the target browser element | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build audio effect for the bridge | - -Use `op`="play", `id`="default", `src`="", `freq`=None, `ms`=None, `sel`="" as the inputs for this operation. - -Effects: pure. - -Build audio effect for the bridge. - -This function returns an effect record and plays no sound immediately. The bridge selects a source, synthesized frequency or audio element; browsers may require a prior user gesture. - -We retain **`spec` = [Set the op field in the new record](table.put(in=None, at="op", value=`op`))**. -We retain **`spec` = [Set the id field in the new record](table.put(in=`spec`, at="id", value=`id`))**. -1. `src` != "" - We retain **`spec` = [Set the src field in the new record](table.put(in=`spec`, at="src", value=`src`))**. -1. `freq` != None - We retain **`spec` = [Set the freq field in the new record](table.put(in=`spec`, at="freq", value=`freq`))**. -1. `ms` != None - We retain **`spec` = [Set the ms field in the new record](table.put(in=`spec`, at="ms", value=`ms`))**. -1. `sel` != "" - We retain **`spec` = [Set the sel field in the new record](table.put(in=`spec`, at="sel", value=`sel`))**. -Return *[Set the audio field in the new record](table.put(in=None, at="audio", value=`spec`))*. - -## read_file - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | -| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | -| as | any | "text" | File content representation expected by the browser bridge | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build read_file effect | - -Use `sel`, `then`, `as`="text" as the inputs for this operation. - -Effects: pure. - -Build read_file effect. - -`spec` = - -| sel | as | then | -|-----|----|------| -| `sel` | `as` | `then` | - -Return *[Set the read_file field in the new record](table.put(in=None, at="read_file", value=`spec`))*. - -## observe - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| specs | any | required | Effect specifications; use a record or an @ row-record list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build observe effect; specs is one map or an @ list of maps | - -Use `specs` as the inputs for this operation. - -Effects: pure. - -Build observe effect; specs is one map or an @ list of maps. - -Return *[Set the observe field in the new record](table.put(in=None, at="observe", value=`specs`))*. - -## unobserve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| specs | any | required | Effect specifications; use a record or an @ row-record list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build unobserve effect; specs is a map or @ list with id | - -Use `specs` as the inputs for this operation. - -Effects: pure. - -Build unobserve effect; specs is a map or @ list with id. - -Return *[Set the unobserve field in the new record](table.put(in=None, at="unobserve", value=`specs`))*. - -## focus - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | any | required | CSS selector of the target browser element | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build a focus effect for the selected element; the browser bridge applies it after the handler returns | - -Use `sel` as the inputs for this operation. - -Effects: pure. - -Build a focus effect for the selected element; the browser bridge applies it after the handler returns. - -Build the focus effect record. The browser bridge consumes this record; this function itself does not change the page. - -Return *[Set the focus field in the new record](table.put(in=None, at="focus", value=`sel`))*. - -## navigate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| replace | any | False | Whether navigation replaces the current history entry | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build the navigate effect record | - -Use `url`, `replace`=False as the inputs for this operation. - -Effects: pure. - -Build the navigate effect record. The browser bridge consumes this record; this function itself does not change the page. - -`spec` = - -| url | replace | -|-----|---------| -| `url` | `replace` | - -Return *[Set the navigate field in the new record](table.put(in=None, at="navigate", value=`spec`))*. - -## store_set - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | required | Field name or key required by this operation | -| value | any | required | Value to transform or store, without mutating the input | -| scope | any | "memory" | Storage scope: memory, local or session | -| then | any | "" | Marqdo callback name for the bridge result; empty text omits callback | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | In-memory (or local/session) key write for SPA client state | - -Use `key`, `value`, `scope`="memory", `then`="" as the inputs for this operation. - -Effects: pure. - -In-memory (or local/session) key write for SPA client state. Prefer `scope=memory` for tab-local app state. -Optional `then` is called after the write with `{ok, op, key, scope}`. - -`spec` = - -| op | key | value | scope | -| ---- | ----- | ------- | ------- | -| set | `key` | `value` | `scope` | - -1. `then` != "" - We retain **`spec` = [Set the then field in the new record](table.put(in=`spec`, at="then", value=`then`))**. -Return *[Set the storage field in the new record](table.put(in=None, at="storage", value=`spec`))*. - -## store_get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | required | Field name or key required by this operation | -| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | -| scope | any | "memory" | Storage scope: memory, local or session | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Read a key then call `then` with `{ok, value, found, key, scope}` | - -Use `key`, `then`, `scope`="memory" as the inputs for this operation. - -Effects: pure. - -Read a key then call `then` with `{ok, value, found, key, scope}`. - -`spec` = - -| op | key | then | scope | -| ---- | ----- | ------ | ------- | -| get | `key` | `then` | `scope` | - -Return *[Set the storage field in the new record](table.put(in=None, at="storage", value=`spec`))*. - -## spa_goto - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| replace | any | False | Whether navigation replaces the current history entry | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | SPA navigation: `history.pushState` / `replaceState` via bridge `navigate` effect | - -Use `url`, `replace`=False as the inputs for this operation. - -Effects: pure. - -SPA navigation: `history.pushState` / `replaceState` via bridge `navigate` effect. - -`spec` = - -| url | replace | -|-----|---------| -| `url` | `replace` | - -Return *[Set the navigate field in the new record](table.put(in=None, at="navigate", value=`spec`))*. - -## storage - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| spec | any | required | Storage operation record: op, key, scope and optional value/then | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Wrap one storage specification as a browser effect; the bridge handles op, key, value, scope and then | - -Use `spec` as the inputs for this operation. - -Effects: pure. - -Wrap one storage specification as a browser effect; the bridge handles op, key, value, scope and then. - -Build the storage effect record. The browser bridge consumes this record; this function itself does not change the page. - -Return *[Set the storage field in the new record](table.put(in=None, at="storage", value=`spec`))*. - -## interval - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ms | any | required | Duration or delay in milliseconds | -| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | -| id | any | "default" | Timer identifier, later passed to clear_interval | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build the interval effect record | - -Use `ms`, `then`, `id`="default" as the inputs for this operation. - -Effects: pure. - -Build the interval effect record. The browser bridge consumes this record; this function itself does not change the page. - -`spec` = - -| ms | then | id | -|----|------|----| -| `ms` | `then` | `id` | - -Return *[Set the interval field in the new record](table.put(in=None, at="interval", value=`spec`))*. - -## clear_interval - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | "default" | Identifier returned by the corresponding create/spawn operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build a cancellation effect using the same identifier previously supplied to interval | - -Use `id`="default" as the inputs for this operation. - -Effects: pure. - -Build a cancellation effect using the same identifier previously supplied to interval. - -Build the clear_interval effect record. The browser bridge consumes this record; this function itself does not change the page. - -We retain **`spec` = [Set the id field in the new record](table.put(in=None, at="id", value=`id`))**. -Return *[Set the clear_interval field in the new record](table.put(in=None, at="clear_interval", value=`spec`))*. - -## fetch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | -| method | text | "GET" | HTTP method, for example GET or POST | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build the fetch effect record | - -Use `url`, `then`, `method`="GET" as the inputs for this operation. - -Effects: pure. - -Build the fetch effect record. The browser bridge consumes this record; this function itself does not change the page. - -`spec` = - -| url | then | method | -|-----|------|--------| -| `url` | `then` | `method` | - -Return *[Set the fetch field in the new record](table.put(in=None, at="fetch", value=`spec`))*. - -## fetch_all - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| requests | any | required | Ordered list of browser request specification records | -| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build the fetch_all effect record | - -Use `requests`, `then` as the inputs for this operation. - -Effects: pure. - -Build the fetch_all effect record. The browser bridge consumes this record; this function itself does not change the page. - -`spec` = - -| requests | then | -|----------|------| -| `requests` | `then` | - -Return *[Set the fetch_all field in the new record](table.put(in=None, at="fetch_all", value=`spec`))*. - -## after - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ms | any | required | Duration or delay in milliseconds | -| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build the after effect record | - -Use `ms`, `then` as the inputs for this operation. - -Effects: pure. - -Build the after effect record. The browser bridge consumes this record; this function itself does not change the page. - -`spec` = - -| ms | then | -|----|------| -| `ms` | `then` | - -Return *[Set the after field in the new record](table.put(in=None, at="after", value=`spec`))*. - -## ws - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| spec | any | required | One bridge effect specification record | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Wrap a WebSocket operation specification for the browser bridge; this function opens no native socket | - -Use `spec` as the inputs for this operation. - -Effects: pure. - -Wrap a WebSocket operation specification for the browser bridge; this function opens no native socket. - -Build the ws effect record. The browser bridge consumes this record; this function itself does not change the page. - -Return *[Set the ws field in the new record](table.put(in=None, at="ws", value=`spec`))*. - -## clipboard - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build a clipboard effect from the text; browser permissions and user-gesture requirements apply when consumed | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Build a clipboard effect from the text; browser permissions and user-gesture requirements apply when consumed. - -Build the clipboard effect record. The browser bridge consumes this record; this function itself does not change the page. - -We retain **`spec` = [Set the text field in the new record](table.put(in=None, at="text", value=`text`))**. -Return *[Set the clipboard field in the new record](table.put(in=None, at="clipboard", value=`spec`))*. - -## download - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| body | any | required | Request body, or replacement text for document operations | -| filename | any | "download.txt" | Suggested download filename | -| mime | any | "text/plain;charset=utf-8" | Content MIME type | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Build the download effect record | - -Use `body`, `filename`="download.txt", `mime`="text/plain;charset=utf-8" as the inputs for this operation. - -Effects: pure. - -Build the download effect record. The browser bridge consumes this record; this function itself does not change the page. - -`spec` = - -| body | filename | mime | -|------|----------|------| -| `body` | `filename` | `mime` | - -Return *[Set the download field in the new record](table.put(in=None, at="download", value=`spec`))*. - -## render_list - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| sel | text | required | CSS selector of the existing list container | -| items | list | required | Literal text or records with tag, text or children, class and attrs | -| tag | text | "li" | Element name consumed by the official bridge, normally li | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Pure render_list instruction for the official browser bridge | - -Use `sel`, `items` and `tag`="li" to replace one dynamic list while preserving its parent layout. Each record can keep plain text and a data-id attribute for delegated events. The official bridge already supports this effect and escapes ordinary text, so a title containing quotes or angle brackets need not become an HTML string. Constructing this instruction does not update a DOM or prove that the selector exists. Only pass application-owned element names and attribute keys; the underlying bridge also accepts an explicit html escape hatch for specialized integrations. Initial page structure still belongs in the Document's component tree, and incoming business values should remain text records. - -Records also accept tag and children, a list of the same text/control records. A li can retain a span label beside a button with data-id, so delegated deletion needs no author HTML. Do not combine children with text or html. Nesting is limited to 32 levels and 10000 records; element/attribute names are checked and event attributes or active URL schemes are rejected. Keep business values in text; the existing html field remains an explicit compatibility escape hatch. - -For a row with a delete action, pass children as structured data. This pure call returns the instruction without loading a server plugin or performing browser IO; the real example uses the same shape in [browser-app](../examples/browser-app/static/app.mq.md). Arbitrary attributes, element names and legacy html remain author-controlled capabilities, so application data belongs only in text or scalar values. The renderer's structural checks do not turn explicit raw HTML into untrusted-content sanitization. - -```sh -marqdo call lib/browser.mq.md render_list 'sel="#items"' 'items=[{"tag":"li","children":[{"tag":"span","text":"A & literal"},{"tag":"button","text":"Delete","attrs":{"type":"button","data-id":"1"}}]}]' --effects none --json -``` - -`spec` = - -| tag | items | -|---|---| -| `tag` | `items` | - -We **targets = [Select the existing list container](table.put(in=None, at=`sel`, value=`spec`))**. -Return *[Describe the native bridge list update](table.put(in=None, at="render_list", value=`targets`))*. diff --git a/lib/bytes.mq.md b/lib/bytes.mq.md deleted file mode 100755 index cddaf8b..0000000 --- a/lib/bytes.mq.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -markup: occlusion -title: bytes ---- - -Bytes are ordinary records with `_type: bytes` and `base64`, portable across CLI, JSON, plugins and sessions; no new language type. - -Carry arbitrary binary data through ordinary portable records. - -Behavior and limits: A bytes record contains _type=bytes and canonical Base64. Byte offsets are zero-based; UTF-8 decoding is explicit and strict. read_chunk has no long-lived file handle. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/encoding.rs](../src/host/encoding.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## from_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Encode text as UTF-8 bytes | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/bytes.mq.md from_text 'text="Marqdo"' --effects none --json -``` - -Encode text as UTF-8 bytes. - -Return *[Encode text as UTF-8 bytes](> host_bytes_from_text text=`text`)*. - -## from_base64 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Decode Base64 as arbitrary bytes; no UTF-8 assumption | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Decode Base64 as arbitrary bytes; no UTF-8 assumption. - -Return *[Decode Base64 as arbitrary bytes; no UTF-8 assumption](> host_bytes_from_base64 text=`text`)*. - -## to_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | map | required | Portable bytes record containing _type=bytes and base64 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Decode UTF-8 strictly; invalid byte sequences fail | - -Use `data` as the inputs for this operation. - -Effects: pure. - -Decode UTF-8 strictly; invalid byte sequences fail. - -Return *[Decode UTF-8 strictly; invalid byte sequences fail](> host_bytes_to_text data=`data`)*. - -## to_base64 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | map | required | Portable bytes record containing _type=bytes and base64 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Return canonical padded Base64 | - -Use `data` as the inputs for this operation. - -Effects: pure. - -Return canonical padded Base64. - -Return *[Return canonical padded Base64](> host_bytes_to_base64 data=`data`)*. - -## len - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | map | required | Portable bytes record containing _type=bytes and base64 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | Count bytes, not characters | - -Use `data` as the inputs for this operation. - -Effects: pure. - -Count bytes, not characters. - -Return *[Count bytes, not characters](> host_bytes_len data=`data`)*. - -## slice - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| data | map | required | Portable bytes record containing _type=bytes and base64 | -| start | number | required | Inclusive zero-based slice start | -| end | number | required | Exclusive zero-based slice end; None selects through the end | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Return a zero-based half-open byte slice; endpoints clamp to length | - -Use `data`, `start`, `end` as the inputs for this operation. - -Effects: pure. - -Return a zero-based half-open byte slice; endpoints clamp to length. - -Return *[Return a zero-based half-open byte slice; endpoints clamp to length](> host_bytes_slice data=`data` start=`start` end=`end`)*. diff --git a/lib/cli.mq.md b/lib/cli.mq.md deleted file mode 100755 index d5a021e..0000000 --- a/lib/cli.mq.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -markup: occlusion -title: lib/cli -description: Parse argv flags (Mid M5). --key value / --key=value / --flag; positionals under _. ---- - -Parse process argv into a map. Flags and positionals (under _). - -Convert argv tokens to a small flag/positional map. - -Behavior and limits: Values stay text; bare flags become booleans and positionals live under _. Omitted args use host argv. This is a small parser, not an argparse schema system. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/cli.rs](../src/host/cli.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| args | any | None | List of argv tokens; None reads the current host argv | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Parse --key value / --key=value / --flag | - -Use `args`=None as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/cli.mq.md parse 'args=["report","--count=3","--quiet"]' --effects none --json -``` - -Parse --key value / --key=value / --flag. A bare --flag must not be followed by a non-option token if you need it as boolean (put flags last, or use --flag=true). Positionals land under _. Omit args to use process argv. - -Caller: [cli.parse] - -Return *[Parse --key value / --key=value / --flag](> host_cli_parse args=`args`)*. diff --git a/lib/csv.mq.md b/lib/csv.mq.md deleted file mode 100755 index 7a36592..0000000 --- a/lib/csv.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/csv -description: RFC4180-ish CSV parse/stringify (Mid M4). First row = headers → list of maps. ---- - -CSV parse and stringify. First row is headers; rows become a list of maps. - -Parse and serialize header-based CSV records. - -Behavior and limits: Parsed cells are text; use table.cast for explicit types. stringify follows the first row field order. Use row records, not a column map. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/csv.rs](../src/host/csv.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Parse CSV text into a list of maps | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Parse CSV text into a list of maps. - -Caller: [csv.parse] text=`raw` - -Return *[Parse CSV text into a list of maps](> host_csv_parse text=`text`)*. - -## stringify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rows | list | required | List of row records | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Serialize a list of maps to CSV text | - -Use `rows` as the inputs for this operation. - -Effects: pure. - -Serialize a list of maps to CSV text. - -Return *[Serialize a list of maps to CSV text](> host_csv_stringify rows=`rows`)*. - -## try_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Return {ok,value,error}; parse failures are recoverable data | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/csv.mq.md try_parse 'text="name,n"' --effects none --json -``` - -Return {ok,value,error}; parse failures are recoverable data. - -Return *[Return {ok,value,error}; parse failures are recoverable data](> host_try_csv_parse text=`text`)*. diff --git a/lib/datetime.mq.md b/lib/datetime.mq.md deleted file mode 100755 index 7ea5879..0000000 --- a/lib/datetime.mq.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -markup: occlusion -title: lib/datetime -description: Calendar moments as maps {unix, zone, iso} (Mid2 M7). Fixed offsets and embedded IANA timezone/DST rules. ---- - -Calendar moments as maps {unix, zone, iso} (Mid2 M7). Fixed offsets and embedded IANA timezone/DST rules. - -Convert timestamps, IANA zones and local calendar dates. - -Behavior and limits: zone remains the numeric offset; timezone preserves the IANA identity. add uses elapsed seconds; add_calendar preserves local wall time. DST gaps fail; folds require an explicit policy. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/datetime.rs](../src/host/datetime.rs)、[src/host/data_ops.rs](../src/host/data_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## now - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Read the clock and return the current UTC datetime record | - -Effects: time.read. - -Current UTC moment map. - -Read the clock and return the current UTC datetime record. - -Return *[Read the clock and return the current UTC datetime record](host_datetime_now())*. - -## from_unix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| unix | number | required | Unix timestamp in seconds | -| zone | any | None | Fixed offset or named timezone accepted by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Convert Unix seconds to a datetime record in the selected zone; None means UTC | - -Use `unix`, `zone`=None as the inputs for this operation. - -Effects: pure. - -Convert Unix seconds to a datetime record in the selected zone; None means UTC. - -Return *[Convert Unix seconds to a datetime record in the selected zone; None means UTC](> host_datetime_from_unix unix=`unix` zone=`zone`)*. - -## to_unix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dt | any | required | Datetime record returned by this library, not formatted text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Read unix seconds from a datetime record; formatting and timezone do not change the instant | - -Use `dt` as the inputs for this operation. - -Effects: pure. - -Read unix seconds from a datetime record; formatting and timezone do not change the instant. - -Return *[Read unix seconds from a datetime record; formatting and timezone do not change the instant](> host_datetime_to_unix dt=`dt`)*. - -## parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| pattern | any | None | None for default parsing, rfc3339 or a strftime format | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Parse RFC3339 or YYYY-MM-DD with optional time; an explicit pattern uses strftime or rfc3339 | - -Use `text`, `pattern`=None as the inputs for this operation. - -Effects: pure. - -RFC3339 / `YYYY-MM-DD[ HH:MM:SS]` by default; `pattern=` is strftime or `rfc3339`. - -Parse RFC3339 or YYYY-MM-DD with optional time; an explicit pattern uses strftime or rfc3339. - -Return *[Parse RFC3339 or YYYY-MM-DD with optional time; an explicit pattern uses strftime or rfc3339](> host_datetime_parse text=`text` pattern=`pattern`)*. - -## format - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dt | any | required | Datetime record returned by this library, not formatted text | -| style | any | None | Formatting style accepted by the host date formatter | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Format a datetime record as rfc3339, date, time, or an explicit strftime pattern | - -Use `dt`, `style`=None as the inputs for this operation. - -Effects: pure. - -Styles: `rfc3339` (default), `date`, `time`, or a strftime pattern. - -Format a datetime record as rfc3339, date, time, or an explicit strftime pattern. - -Return *[Format a datetime record as rfc3339, date, time, or an explicit strftime pattern](> host_datetime_format dt=`dt` style=`style`)*. - -## add - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dt | any | required | Datetime record returned by this library, not formatted text | -| days | any | None | Number of elapsed 24-hour days to add | -| hours | any | None | Number of elapsed hours to add | -| minutes | any | None | Number of elapsed minutes to add | -| seconds | any | None | Number of elapsed seconds to add | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Add elapsed days, hours, minutes and seconds; a day here is exactly 24 hours | - -Use `dt`, `days`=None, `hours`=None, `minutes`=None, `seconds`=None as the inputs for this operation. - -Effects: pure. - -Add elapsed days, hours, minutes and seconds; a day here is exactly 24 hours. Named zones recompute their offset after the move. - -Return *[Add elapsed days, hours, minutes and seconds; a day here is exactly 24 hours](> host_datetime_add dt=`dt` days=`days` hours=`hours` minutes=`minutes` seconds=`seconds`)*. - -## in_zone - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dt | any | required | Datetime record returned by this library, not formatted text | -| zone | any | required | Fixed offset or named timezone accepted by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Re-express the same instant in a fixed offset or an IANA zone, retaining its Unix timestamp | - -Use `dt`, `zone` as the inputs for this operation. - -Effects: pure. - -Re-express the same instant in `+08:00` / `UTC` / IANA zones like `Asia/Shanghai`. - -Re-express the same instant in a fixed offset or an IANA zone, retaining its Unix timestamp. - -Return *[Re-express the same instant in a fixed offset or an IANA zone, retaining its Unix timestamp](> host_datetime_in_zone dt=`dt` zone=`zone`)*. - -## parse_local - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | -| zone | text | required | Fixed offset or named timezone accepted by this operation | -| ambiguity | text | "reject" | DST fold policy: reject, earliest or latest | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Parse YYYY-MM-DD HH:MM:SS in an IANA timezone as Result | - -Use `text`, `zone`, `ambiguity`="reject" as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/datetime.mq.md parse_local 'text="2024-11-03 01:30:00"' 'zone="America/New_York"' 'ambiguity="earliest"' --effects none --json -``` - -Parse YYYY-MM-DD HH:MM:SS in an IANA timezone as Result. DST gaps fail; folds require reject/earliest/latest. - -Return *[Parse YYYY-MM-DD HH:MM:SS in an IANA timezone as Result](> host_datetime_local text=`text` zone=`zone` ambiguity=`ambiguity`)*. - -## add_calendar - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| dt | map | required | Datetime record returned by this library, not formatted text | -| days | number | required | Local calendar days to add, preserving wall time across DST | -| ambiguity | text | "reject" | DST fold policy: reject, earliest or latest | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Add local calendar days as Result, preserving wall-clock time across DST | - -Use `dt`, `days`, `ambiguity`="reject" as the inputs for this operation. - -Effects: pure. - -Add local calendar days as Result, preserving wall-clock time across DST. Legacy add uses elapsed duration: one day is 24 hours. - -Return *[Add local calendar days as Result, preserving wall-clock time across DST](> host_datetime_calendar_add dt=`dt` days=`days` ambiguity=`ambiguity`)*. diff --git a/lib/document.mq.md b/lib/document.mq.md deleted file mode 100755 index 68c3cd4..0000000 --- a/lib/document.mq.md +++ /dev/null @@ -1,193 +0,0 @@ ---- -markup: occlusion -import: - fs: lib/fs.mq.md ---- - -Document transforms share the renderer Markdown parser. read_table composes explicit native filesystem reading with literal data selection. - -Inspect and transform Markdown without executing its contents. - -Behavior and limits: Shares the Markdown parser with rendering and recognizes YAML frontmatter. Spans are original UTF-8 byte offsets. Duplicate section names fail. Replacement preserves surrounding source; persist via fs.write_checked. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/document.rs](../src/host/document.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## sections - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | List headings with original UTF-8 byte spans and body text; nested sections end at the next same-or-higher heading | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/document.mq.md sections 'text="# Notes"' --effects none --json -``` - -List headings with original UTF-8 byte spans and body text; nested sections end at the next same-or-higher heading. No execution. - -Return *[List headings with original UTF-8 byte spans and body text; nested sections end at the next same-or-higher heading](> host_document_sections text=`text`)*. - -## section - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | -| title | text | required | Exact, unique Markdown heading title | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Read the body under one exact heading; missing or duplicate headings fail | - -Use `text`, `title` as the inputs for this operation. - -Effects: pure. - -Read the body under one exact heading; missing or duplicate headings fail. - -Return *[Read the body under one exact heading; missing or duplicate headings fail](> host_document_section text=`text` title=`title`)*. - -## replace_section - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | -| title | text | required | Exact, unique Markdown heading title | -| body | text | required | Request body, or replacement text for document operations | -| expected_sha256 | any | None | Digest of the exact prior text; None disables the check where allowed | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Return Result with replaced section body, preserving its heading and surrounding source | - -Use `text`, `title`, `body`, `expected_sha256`=None as the inputs for this operation. - -Effects: pure. - -Return Result with replaced section body, preserving its heading and surrounding source. Optional digest checks the whole source. Pure transform; persist via fs.write_checked. - -Return *[Return Result with replaced section body, preserving its heading and surrounding source](> host_document_replace_section text=`text` title=`title` body=`body` expected_sha256=`expected_sha256`)*. - -## tables - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Extract inert GFM headers and cell text, plus original byte ranges; cells are never evaluated | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Extract inert GFM headers and cell text, plus original byte ranges; cells are never evaluated. - -Return *[Extract inert GFM headers and cell text, plus original byte ranges; cells are never evaluated](> host_document_tables text=`text`)*. - -## replace_table - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | -| index | number | required | Zero-based table index in source order | -| headers | list | required | Ordered list of table header text | -| rows | list | required | List of cell-text lists; each row must match the header width | -| expected_sha256 | any | None | Digest of the exact prior text; None disables the check where allowed | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Replace the zero-based table from text headers and rows, preserving all surrounding source; return Result | - -Use `text`, `index`, `headers`, `rows`, `expected_sha256`=None as the inputs for this operation. - -Effects: pure. - -Replace the zero-based table from text headers and rows, preserving all surrounding source; return Result. - -Return *[Replace the zero-based table from text headers and rows, preserving all surrounding source; return Result](> host_document_replace_table text=`text` index=`index` headers=`headers` rows=`rows` expected_sha256=`expected_sha256`)*. - -## links - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | List Markdown link labels and targets with byte spans; never follow or execute them | - -Use `text` as the inputs for this operation. - -Effects: pure. - -List Markdown link labels and targets with byte spans; never follow or execute them. - -Return *[List Markdown link labels and targets with byte spans; never follow or execute them](> host_document_links text=`text`)*. - -## code_blocks - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | List code fence language and literal source with byte spans; never run foreign or Marqdo code | - -Use `text` as the inputs for this operation. - -Effects: pure. - -List code fence language and literal source with byte spans; never run foreign or Marqdo code. - -Return *[List code fence language and literal source with byte spans; never run foreign or Marqdo code](> host_document_code_blocks text=`text`)*. - -## table - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Markdown containing the literal GFM data table | -| title | any | None | Exact unique section title, or None for the whole document | -| index | number | 0 | Zero-based table index within the selected section | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native literal table value, preserving the source language's record/list/column shape | - -Use `text`, `title`=None and `index`=0 to obtain actual data from a Markdown resource. The existing tables function supplies inert headers and cell text for document inspection; this operation reads the selected table with the same literal cell and shape rules as Marqdo source. Booleans, numbers, None and quoted text therefore retain their types. An @, 行 or row marker selects record rows, one-column tables become lists, and ordinary multi-column tables retain their native map shape. - -The renderer's parser locates real tables and skips fenced examples. Duplicate section titles, missing tables, duplicate headers and row-width mismatches produce diagnostics. Variables, interpolated values and executable expressions are rejected; surrounding prose, imports and code fences are never executed. This keeps large schemas, seed rows and style declarations readable as Markdown data leaves while small callable functions explain their use. Construction is pure and performs no file, process, plugin or network operation. - -Return *[Read the selected literal table with the native language rules](host_document_table(text=`text`, title=`title`, index=`index`))*. - - -## read_table - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | UTF-8 Markdown data path under --fs-root | -| title | any | None | Exact unique section title, or None for the whole document | -| index | number | 0 | Zero-based table index within the selected section | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Actual literal table value loaded through native fs.read | - -Use `path`, `title`=None and `index`=0 for a separate Markdown data leaf. The filesystem reader validates the granted root and UTF-8; table then selects one real data table and preserves its native types and shape. Requires fs.read. A resource file can explain its schema and examples beside the data without being loaded as a program. Missing paths, ambiguous headings, invalid cells and structural mismatches remain diagnostics. This function writes nothing and executes no imports, bold statements or foreign fences from the file. - -We **source = [Read this selected Markdown resource natively](fs.read_text(path=`path`))**. -Return *[Obtain its literal data without running the document](table(text=`source`, title=`title`, index=`index`))*. diff --git a/lib/encoding.mq.md b/lib/encoding.mq.md deleted file mode 100755 index 27f179d..0000000 --- a/lib/encoding.mq.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -markup: occlusion -title: lib/encoding -description: Base64, hex, and base32 encode/decode (Mid M1 + Mid2 M8). UTF-8 text round-trip. ---- - -Base64, hex, and base32 encode/decode. UTF-8 text round-trip. - -Encode and decode UTF-8 text as Base64, hex or Base32. - -Behavior and limits: These historical helpers round-trip text. Use bytes.from_base64 for arbitrary binary; decoding invalid UTF-8 as text is an error. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/encoding.rs](../src/host/encoding.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## base64_encode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Base64-encode text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/encoding.mq.md base64_encode 'text="Marqdo"' --effects none --json -``` - -Base64-encode text. - -Caller: [encoding.base64_encode] text=`s` - -Return *[Base64-encode text](> host_encoding_base64_encode text=`text`)*. - -## base64_decode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Base64-decode text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Base64-decode text. - -Return *[Base64-decode text](> host_encoding_base64_decode text=`text`)*. - -## hex_encode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Hex-encode text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Hex-encode text. - -Return *[Hex-encode text](> host_encoding_hex_encode text=`text`)*. - -## hex_decode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Hex-decode text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Hex-decode text. - -Return *[Hex-decode text](> host_encoding_hex_decode text=`text`)*. - -## base32_encode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Base32-encode text (RFC 4648 alphabet; padding with =) | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Base32-encode text (RFC 4648 alphabet; padding with =). - -Return *[Base32-encode text (RFC 4648 alphabet; padding with =)](> host_encoding_base32_encode text=`text`)*. - -## base32_decode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Base32-decode text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Base32-decode text. - -Return *[Base32-decode text](> host_encoding_base32_decode text=`text`)*. diff --git a/lib/foreign.mq.md b/lib/foreign.mq.md deleted file mode 100755 index 97f64de..0000000 --- a/lib/foreign.mq.md +++ /dev/null @@ -1,545 +0,0 @@ ---- -markup: occlusion -title: lib/foreign -description: Run bound code fences and inline sources via local interpreters -import: - table: lib/table.mq.md ---- - -Run bound code fences and inline sources via local interpreters. - -Bridge explicit values to external language processes and sessions. - -Behavior and limits: Configured languages are not proof that interpreters are installed. invoke exposes exit/timeout/output limits. External execution requires process.exec; close owned persistent sessions. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/foreign.rs](../src/host/foreign.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## set_cmd - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| lang | text | required | Registered interpreter language identifier, such as node | -| cmd | any | required | Executable command or interpreter override | -| args | any | None | Argument list passed to the called command or function | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Bind interpreter command cmd for language lang; optional extra argv | - -Use `lang`, `cmd`, `args`=None as the inputs for this operation. - -Effects: pure. - -Bind interpreter command cmd for language lang; optional extra argv. - -Return *[Bind interpreter command cmd for language lang; optional extra argv](> host_foreign_set_cmd lang=`lang` cmd=`cmd` args=`args`)*. - -## run - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| code | any | required | Bound code-fence value; supply lang and source for inline text | -| stdin | any | None | Text written to the child process standard input | -| env | any | None | Environment variable/value record for the child process | -| cwd | any | None | Child process working directory | -| timeout | any | None | Execution timeout in seconds; None uses the host default | -| args | any | None | Argument list passed to the called command or function | -| max_output | any | None | Maximum captured output bytes; None uses the host default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds), extra argv and output cap | - -Use `code`, `stdin`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `max_output`=None as the inputs for this operation. - -Effects: process.exec. - -Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds), -extra argv and output cap. Returns stdout text; non-zero exit is an error. - -Caller: [foreign.run] code=`block` - -Return *[Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds), extra argv and output cap](> host_foreign_run code=`code` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`)*. - -## run_lang - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| lang | text | required | Registered interpreter language identifier, such as python | -| source | any | required | Source text to run with the selected interpreter | -| stdin | any | None | Text written to the child process standard input | -| env | any | None | Environment variable/value record for the child process | -| cwd | any | None | Child process working directory | -| timeout | any | None | Execution timeout in seconds; None uses the host default | -| args | any | None | Argument list passed to the called command or function | -| max_output | any | None | Maximum captured output bytes; None uses the host default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Run source text with language lang; same options as run | - -Use `lang`, `source`, `stdin`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `max_output`=None as the inputs for this operation. - -Effects: process.exec. - -Run source text with language lang; same options as run. - -Return *[Run source text with language lang; same options as run](> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`)*. - -## invoke - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| code | any | None | Bound code-fence value; supply lang and source for inline text | -| lang | any | None | Registered interpreter language identifier, such as python | -| source | any | None | Source text to run with the selected interpreter | -| stdin | any | None | Text written to the child process standard input | -| input | any | None | Structured value JSON-encoded on stdin; cannot combine with stdin | -| env | any | None | Environment variable/value record for the child process | -| cwd | any | None | Child process working directory | -| timeout | any | None | Execution timeout in seconds; None uses the host default | -| args | any | None | Argument list passed to the called command or function | -| output | any | "auto" | Result decoding mode: auto, text, json or lines | -| max_output | any | None | Maximum captured output bytes; None uses the host default | -| cmd | any | None | Executable command or interpreter override | -| keep | any | False | Whether to retain the generated script for inspection | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Run code or lang+source and return a record map instead of raising on process failure | - -Use `code`=None, `lang`=None, `source`=None, `stdin`=None, `input`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `output`="auto", `max_output`=None, `cmd`=None, `keep`=False as the inputs for this operation. - -Effects: process.exec. - -Run code or lang+source and return a record map instead of raising on process -failure. Fields: ok, code, stdout, stderr, ms, lang, cmd, timed_out, truncated, -result, result_error, error, script, cached. - -`input` is encoded as JSON on stdin (mutually exclusive with `stdin`). `output` -is auto | text | json | lines. `cmd` overrides the interpreter for this call. - -Return *[Run code or lang+source and return a record map instead of raising on process failure](> host_foreign_invoke code=`code` lang=`lang` source=`source` stdin=`stdin` input=`input` env=`env` cwd=`cwd` timeout=`timeout` args=`args` output=`output` max_output=`max_output` cmd=`cmd` keep=`keep`)*. - -## probe - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| lang | any | None | Registered interpreter language identifier, such as python | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Probe one language, or every known language when lang is omitted | - -Use `lang`=None as the inputs for this operation. - -Effects: process.exec. - -Probe one language, or every known language when lang is omitted. Returns -{lang, cmd, path, ok, version, error} (a list when lang is omitted). - -Return *[Probe one language, or every known language when lang is omitted](> host_foreign_probe lang=`lang`)*. - -## register - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| lang | text | required | Registered interpreter language identifier, such as python | -| cmd | any | None | Executable command or interpreter override | -| args | any | None | Argument list passed to the called command or function | -| template | any | None | Interpreter launch template | -| ext | any | None | Temporary script filename extension | -| env | any | None | Environment variable/value record for the child process | -| version_args | any | None | Arguments used to query the interpreter version | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Register a language invocation | - -Use `lang`, `cmd`=None, `args`=None, `template`=None, `ext`=None, `env`=None, `version_args`=None as the inputs for this operation. - -Effects: pure. - -Register a language invocation. Provide cmd (+args) or template (placeholders -{file}, {dir}, {base}, {inline}, {lang}, {cwd}); they are mutually exclusive. - -Return *[Register a language invocation](> host_foreign_register lang=`lang` cmd=`cmd` args=`args` template=`template` ext=`ext` env=`env` version_args=`version_args`)*. - -## unset - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| lang | text | required | Registered interpreter language identifier, such as python | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Remove a process-local registration | - -Use `lang` as the inputs for this operation. - -Effects: pure. - -Remove a process-local registration. Presets/config/env still apply. - -Return *[Remove a process-local registration](> host_foreign_unset lang=`lang`)*. - -## load_config - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load .marqdo/foreign.toml (or an explicit path); returns the number of language tables read | - -Use `path`=None as the inputs for this operation. - -Effects: fs.read. - -Load .marqdo/foreign.toml (or an explicit path); returns the number of language -tables read. - -Return *[Load .marqdo/foreign.toml (or an explicit path); returns the number of language tables read](> host_foreign_load_config path=`path`)*. - -## call - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| code | any | None | Bound code-fence value; supply lang and source for inline text | -| lang | any | None | Registered interpreter language identifier, such as python | -| source | any | None | Source text to run with the selected interpreter | -| input | any | None | Structured value JSON-encoded on stdin; cannot combine with stdin | -| stdin | any | None | Text written to the child process standard input | -| env | any | None | Environment variable/value record for the child process | -| cwd | any | None | Child process working directory | -| timeout | any | None | Execution timeout in seconds; None uses the host default | -| args | any | None | Argument list passed to the called command or function | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | JSON-in / JSON-out call: encode `input` on stdin, parse stdout JSON and return the value (empty stdout -> None) | - -Use `code`=None, `lang`=None, `source`=None, `input`=None, `stdin`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None as the inputs for this operation. - -Effects: process.exec. - -JSON-in / JSON-out call: encode `input` on stdin, parse stdout JSON and return -the value (empty stdout -> None). Raises on process failure or invalid JSON. - -Return *[JSON-in / JSON-out call: encode input on stdin, parse stdout JSON and return the value (empty stdout -> None)](> host_foreign_call code=`code` lang=`lang` source=`source` input=`input` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args`)*. - -## run_many - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| runs | any | required | Ordered per-run code or language/source records | -| concurrency | any | 4 | Maximum number of concurrent operations | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Run a list of code values or invoke-option maps in parallel; returns records in input order | - -Use `runs`, `concurrency`=4 as the inputs for this operation. - -Effects: process.exec. - -Run a list of code values or invoke-option maps in parallel; returns records in -input order. One failing item does not stop the others. - -Return *[Run a list of code values or invoke-option maps in parallel; returns records in input order](> host_foreign_run_many runs=`runs` concurrency=`concurrency`)*. - -## call_many - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| inputs | any | required | Input values for the batched calls | -| code | any | None | Bound code-fence value; supply lang and source for inline text | -| lang | any | None | Registered interpreter language identifier, such as python | -| source | any | None | Source text to run with the selected interpreter | -| cmd | any | None | Executable command or interpreter override | -| env | any | None | Environment variable/value record for the child process | -| cwd | any | None | Child process working directory | -| timeout | any | None | Execution timeout in seconds; None uses the host default | -| args | any | None | Argument list passed to the called command or function | -| max_output | any | None | Maximum captured output bytes; None uses the host default | -| concurrency | any | 4 | Maximum number of concurrent operations | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply one code/function to each input in parallel; returns parsed JSON results in input order | - -Use `inputs`, `code`=None, `lang`=None, `source`=None, `cmd`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `max_output`=None, `concurrency`=4 as the inputs for this operation. - -Effects: process.exec. - -Apply one code/function to each input in parallel; returns parsed JSON results -in input order. Raises with the failing index after all workers finish. - -Return *[Apply one code/function to each input in parallel; returns parsed JSON results in input order](> host_foreign_call_many inputs=`inputs` code=`code` lang=`lang` source=`source` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output` concurrency=`concurrency`)*. - -## session - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| kernels | any | None | Kernel rows: name/language and optional command/environment settings | -| cells | any | None | Cell-to-kernel routing rows; referenced code fences belong to the document | -| values | any | None | Rows naming a kernel, variable name and native value to copy | -| inputs | any | None | Optional declared per-cell input values | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Plain view plan with kind, kernels, cells, values and inputs | - -Use `kernels`=None, `cells`=None, `values`=None and `inputs`=None to -declare a view session from ordinary data tables. The returned map has -kind="foreign-session" and the four supplied specifications. This pure task -does not launch an interpreter, create a live kernel or read another file. -View later consumes the plan and the document's bound code fences. Bind the plan -to `会话` in the entry procedure: View uses this documented binding to distinguish -a declared plan from ordinary maps and low-level live session handles. A normal -`## main` function can be called directly and indexed by View; the separate native -report example shows the complete declarations. - -Kernel rows identify languages explicitly; the native-first public workflow -uses Node only for Intl formatting after Marqdo has computed its data. A values -row copies a JSON-safe native value into a named kernel variable. Cells in the -same kernel share state, while separate kernel rows preserve isolation. -Missing or invalid runtime declarations remain the View/session diagnostic. - -This result is a serializable plan, so it can be returned by marqdo call. -A live session_open handle is a different resource and cannot be reconstructed -from a JSON string. For a low-level multi-evaluation task, open, use and close -that handle within one callable workflow; format_summary in the native report -example demonstrates that lifetime and its real failure exits. - -`plan` = - -| kind | kernels | cells | values | inputs | -|---|---|---|---|---| -| "foreign-session" | `kernels` | `cells` | `values` | `inputs` | - -After declaring the explicit view inputs we return *plan*. - -## session_open - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| lang | text | required | Registered interpreter language identifier, such as python | -| cmd | any | None | Executable command or interpreter override | -| env | any | None | Environment variable/value record for the child process | -| cwd | any | None | Child process working directory | -| timeout | any | None | Execution timeout in seconds; None uses the host default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Start a persistent Python/Node kernel; returns an opaque `handle` value | - -Use `lang`, `cmd`=None, `env`=None, `cwd`=None, `timeout`=None as the inputs for this operation. - -Effects: process.exec. - -Start a persistent Python/Node kernel; returns an opaque `handle` value. -Text fabrications are refused by session ops; handles cannot cross the JSON -bridge. `timeout` is the default per-eval timeout. - -Return *[Start a persistent Python/Node kernel; returns an opaque handle value](> host_foreign_session_open lang=`lang` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout`)*. - -## session_eval - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text | -| code | any | None | Bound code-fence value; supply lang and source for inline text | -| source | any | None | Source text to run with the selected interpreter | -| input | any | None | Structured value JSON-encoded on stdin; cannot combine with stdin | -| stdin | any | None | Text written to the child process standard input | -| timeout | any | None | Execution timeout in seconds; None uses the host default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Evaluation record: ok/code/result/stdout/stderr/alive/timed_out/ms and diagnostic metadata | - -Use `id`, `code`=None, `source`=None, `input`=None, `stdin`=None, `timeout`=None as the inputs for this operation. - -Effects: process.exec. - -Evaluate code (a code value) or source text in session id; returns a record -with ok/code/result/stdout/stderr/alive/timed_out/ms. Inspect ok before result: -code is zero on success and -1 on a kernel failure. stdout and stderr preserve -captured text; error explains a failed evaluation. alive says whether the kernel -can still be used. An ordinary language exception can leave it alive; process -death or timeout may retire it. Close only the live original handle. The record's -text id is diagnostic identity and cannot replace that opaque handle. - -`input` is JSON-encoded for the kernel; `stdin` is raw program stdin for this -evaluation. JSON-unsafe values remain diagnostics, never guessed text. Effects -require process.exec, and the timeout is seconds while ms reports elapsed time. - -Return *[Evaluate code (a code value) or source text in session id; returns a record with id/alive](> host_foreign_session_eval id=`id` code=`code` source=`source` input=`input` stdin=`stdin` timeout=`timeout`)*. - -## session_set - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text | -| name | text | required | Name to resolve, register or look up | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Set one kernel variable from a Marqdo value (JSON copy) | - -Use `id`, `name`, `value` as the inputs for this operation. - -Effects: process.exec. - -Set one kernel variable from a Marqdo value (JSON copy). - -Return *[Set one kernel variable from a Marqdo value (JSON copy)](> host_foreign_session_set id=`id` name=`name` value=`value`)*. - -## session_get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text | -| name | text | required | Name to resolve, register or look up | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read one kernel variable as a Marqdo value | - -Use `id`, `name` as the inputs for this operation. - -Effects: process.exec. - -Read one kernel variable as a Marqdo value. - -Return *[Read one kernel variable as a Marqdo value](> host_foreign_session_get id=`id` name=`name`)*. - -## session_names - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List kernel variable names | - -Use `id` as the inputs for this operation. - -Effects: process.exec. - -List kernel variable names. - -Return *[List kernel variable names](> host_foreign_session_names id=`id`)*. - -## session_close - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Consume (affine close) a live session handle: kill and remove it | - -Use `id` as the inputs for this operation. - -Effects: process.exec. - -Consume (affine close) a live session handle: kill and remove it. Returns -`True` on success. Closing an unknown or already-closed id is a fault -(`foreign session … not found`), matching use-after-close on eval/set/get. - -Return *[Consume (affine close) a live session handle: kill and remove it](> host_foreign_session_close id=`id`)*. - -## session_interrupt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Opaque session_open handle retained in this process; never rebuild it from id text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Interrupt the current evaluation of a persistent kernel | - -Use `id` as the inputs for this operation. - -Effects: process.exec. - -Interrupt the current evaluation of a persistent kernel. The session remains -usable for the next evaluation when the worker supports interruption. - -Return *[Interrupt the current evaluation of a persistent kernel](> host_foreign_session_interrupt id=`id`)*. - -## session_list - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List live sessions with id/lang/cmd/evals/alive/started_ms | - -Effects: process.exec. - -List live sessions with id/lang/cmd/evals/alive/started_ms. - -Return *[List live sessions with id/lang/cmd/evals/alive/started_ms](host_foreign_session_list())*. - -## langs - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | List configured foreign languages | - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/foreign.mq.md langs --effects none --json -``` - -List configured foreign languages. - -Return configured language definitions without launching interpreters. Use probe separately to check executable availability. - -Return *[List configured foreign languages](host_foreign_langs())*. - -## oracle_journal - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Return this document evaluation's admitted eval/get/decode observations as ordinary records with index, channel, value | - -Effects: pure. - -Return this document evaluation's admitted eval/get/decode observations as -ordinary records with index, channel, value. Opening, setting and closing do -not append observations. - -Return *[Return this document evaluation's admitted eval/get/decode observations as ordinary records with index, channel, value](> host_oracle_journal )*. - -## replay_check - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expected | any | required | Expected observation record used for replay comparison | -| observed | any | required | Actual observation record used for replay comparison | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Compare two oracle journals without executing foreign code | - -Use `expected`, `observed` as the inputs for this operation. - -Effects: pure. - -Compare two oracle journals without executing foreign code. Returns ok and -the least mismatching index, with the expected and observed records. - -Return *[Compare two oracle journals without executing foreign code](> host_oracle_replay_check expected=`expected` observed=`observed`)*. diff --git a/lib/fs.mq.md b/lib/fs.mq.md deleted file mode 100755 index 17a9d37..0000000 --- a/lib/fs.mq.md +++ /dev/null @@ -1,787 +0,0 @@ ---- -markup: occlusion -import: - json: lib/json.mq.md - csv: lib/csv.mq.md -title: lib/fs -description: English filesystem wrappers ---- - -English filesystem wrappers - -Read, write, find and organize files under an explicit root. - -Behavior and limits: Legacy remove recursively deletes directories. Prefer remove_file/remove_empty_dir. Atomic operations replace one file; directory batches are not transactions. Native-only operations state their CoW boundary. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. - -Implementation: [src/host/fs.rs](../src/host/fs.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/sandbox_fs.rs](../src/host/sandbox_fs.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## read_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Read UTF-8 text from path | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Read UTF-8 text from path. - -Return *[Read UTF-8 text from path](> host_read_text path=`path`)*. - -## write_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `text` as the inputs for this operation. - -Effects: fs.write. - -Write text to path (overwrite). - -Return *[Write text to path (overwrite)](> host_write_text path=`path` text=`text`)*. - -## append_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `text` as the inputs for this operation. - -Effects: fs.write. - -Append text to path. - -Return *[Append text to path](> host_append_text path=`path` text=`text`)*. - -## exists - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether path exists | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Whether path exists. - -Return *[Whether path exists](> host_exists path=`path`)*. - -## list_dir - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | List directory entries at path | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -List directory entries at path. - -Return *[List directory entries at path](> host_list_dir path=`path`)*. - -## make_dir - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path` as the inputs for this operation. - -Effects: fs.write. - -Create directory at path. - -Return *[Create directory at path](> host_make_dir path=`path`)*. - -## make_dirs - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path` as the inputs for this operation. - -Effects: fs.write. - -Create directories recursively (`mkdir -p`). - -Return *[Create directories recursively (mkdir -p)](> host_make_dirs path=`path`)*. - -## remove - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path` as the inputs for this operation. - -Effects: fs.write. - -Remove a file or recursively remove a directory. Legacy behavior; use remove_file or remove_empty_dir for narrow deletion. - -Remove a file or recursively remove a directory. For narrow deletion use remove_file or remove_empty_dir. - -Return *[Remove a file or recursively remove a directory](> host_remove path=`path`)*. - -## remove_tree - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path` as the inputs for this operation. - -Effects: fs.write. - -Remove a directory recursively. Errors if `path` is a file. - -Return *[Remove a directory recursively](> host_remove_tree path=`path`)*. - -## stat - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Returns `{size, mtime_unix, is_file, is_dir}` | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Returns `{size, mtime_unix, is_file, is_dir}`. - -Return *[Returns {size, mtime_unix, is_file, is_dir}](> host_stat path=`path`)*. - -## walk - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Depth-first listing of relative paths under `path` (forward slashes) | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Depth-first listing of relative paths under `path` (forward slashes). - -Return *[Depth-first listing of relative paths under path (forward slashes)](> host_walk path=`path`)*. - -## copy_file - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| src | text | required | Source path under the granted root | -| dest | text | required | Destination path under the granted root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `src`, `dest` as the inputs for this operation. - -Effects: fs.write. - -Copy a file (overwrites `dest` if it exists). Paths are sandboxed like other fs ops. - -Return *[Copy a file (overwrites dest if it exists)](> host_copy_file src=`src` dest=`dest`)*. - -## move - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| src | text | required | Source path under the granted root | -| dest | text | required | Destination path under the granted root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `src`, `dest` as the inputs for this operation. - -Effects: fs.write. - -Rename / move within the sandbox. - -Return *[Rename / move within the sandbox](> host_move src=`src` dest=`dest`)*. - -## make_temp - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prefix | any | None | Prefix added to the generated name or tested against text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Create an empty temp file under the program directory; return its relative path | - -Use `prefix`=None as the inputs for this operation. - -Effects: fs.write. - -Create an empty temp file under the program directory; return its relative path. - -Return *[Create an empty temp file under the program directory; return its relative path](> host_make_temp prefix=`prefix`)*. - -## text_patch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | -| find | any | required | Exact text to locate before replacement | -| replace | any | required | Replacement text for each exact match | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Exact FIND→REPLACE once in a UTF-8 text file | - -Use `path`, `find`, `replace` as the inputs for this operation. - -Effects: fs.write. - -Exact FIND→REPLACE once in a UTF-8 text file. `find` must match exactly once. - -Return *[Exact FIND→REPLACE once in a UTF-8 text file](> host_text_patch path=`path` find=`find` replace=`replace`)*. - -## apply_patch_blocks - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | -| text | text | required | Text supplied by the caller | -| soft | bool | False | Whether a missing patch match becomes a recoverable outcome | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Apply plan-style triple-angle FIND/REPLACE blocks from `text` to `path` | - -Use `path`, `text`, `soft`=False as the inputs for this operation. - -Effects: fs.write. - -Apply plan-style triple-angle FIND/REPLACE blocks from `text` to `path`. -Also accepts fenced find/replace pairs and minimal Begin Patch hunks. -When `soft=True`, only “FIND not found” returns `0` (run continues). Empty FIND, multi-match, parse errors, and whole-file FIND still abort — whole-file rewrite is forbidden. - -Return *[Apply plan-style triple-angle FIND/REPLACE blocks from text to path](> host_apply_patch_blocks path=`path` text=`text` soft=`soft`)*. - -## try_read_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Read text as {ok,value,error}; file and permission failures are data | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Call this function directly: - -```sh -marqdo call lib/fs.mq.md try_read_text 'path="lib/fs.mq.md"' --effects fs.read --fs-root . --json -``` - -Read at most 8 MiB of UTF-8 text as {ok,value,error}; file, encoding and permission failures are data. The function still requires fs.read. - -Return *[Read at most 8 MiB of UTF-8 text as {ok,value,error}; file, encoding and permission failures are data](> host_fs_try_read_text path=`path`)*. - -## try_write_text - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Overwrite UTF-8 text and return {ok,value,error}; requires fs | - -Use `path`, `text` as the inputs for this operation. - -Effects: fs.write. - -Overwrite UTF-8 text and return {ok,value,error}; requires fs.write. - -Return *[Overwrite UTF-8 text and return {ok,value,error}; requires fs.write](> host_fs_try_write_text path=`path` text=`text`)*. - -## read_bytes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Read binary data as a bytes record | - -Use `path`, `max_bytes`=8388608 as the inputs for this operation. - -Effects: fs.read. - -Read binary data as a bytes record. Default limit is 8 MiB, maximum is 64 MiB; decoding is explicit via lib/bytes. - -Return *[Read binary data as a bytes record](> host_fs_read_bytes path=`path` max_bytes=`max_bytes`)*. - -## write_bytes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| data | map | required | Portable bytes record containing _type=bytes and base64 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `data` as the inputs for this operation. - -Effects: fs.write. - -Atomically replace a file with bytes; no UTF-8 conversion. Requires fs.write. - -Return *[Atomically replace a file with bytes; no UTF-8 conversion](> host_fs_write_bytes path=`path` data=`data`)*. - -## read_chunk - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| offset | number | 0 | Zero-based byte offset of the next chunk | -| size | number | 65536 | Number of bytes to read in this chunk | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Read at most size bytes from offset, returning data/next_offset/eof | - -Use `path`, `offset`=0, `size`=65536 as the inputs for this operation. - -Effects: fs.read. - -Read at most size bytes from offset, returning data/next_offset/eof. Offsets are zero-based bytes; each call closes the file, so no handles escape sessions. - -Return *[Read at most size bytes from offset, returning data/next_offset/eof](> host_fs_read_chunk path=`path` offset=`offset` size=`size`)*. - -## append_bytes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| data | map | required | Portable bytes record containing _type=bytes and base64 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `data` as the inputs for this operation. - -Effects: fs.write. - -Append bytes, creating a file if absent; parent directory must exist. - -Return *[Append bytes, creating a file if absent; parent directory must exist](> host_fs_append_bytes path=`path` data=`data`)*. - -## atomic_write - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `text` as the inputs for this operation. - -Effects: fs.write. - -Replace text through a reserved sibling temporary file and rename; failures remove that temp file. This is one-file replacement, not a multi-file transaction. - -Return *[Replace text through a reserved sibling temporary file and rename; failures remove that temp file](> host_fs_atomic_write path=`path` text=`text`)*. - -## write_changed - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | bool | Write atomically only when content differs; return whether it was written | - -Use `path`, `text` as the inputs for this operation. - -Effects: fs.write. - -Write atomically only when content differs; return whether it was written. - -Return *[Write atomically only when content differs; return whether it was written](> host_fs_write_changed path=`path` text=`text`)*. - -## write_checked - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| text | text | required | Text to read, transform or emit as described by this operation | -| expected_sha256 | text | required | Digest of the exact prior text; None disables the check where allowed | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Check current SHA-256 before atomic replacement, returning Result | - -Use `path`, `text`, `expected_sha256` as the inputs for this operation. - -Effects: fs.write. - -Check current SHA-256 before atomic replacement, returning Result. Detects stale content; concurrent writers still need external coordination. - -Return *[Check current SHA-256 before atomic replacement, returning Result](> host_fs_write_checked path=`path` text=`text` expected_sha256=`expected_sha256`)*. - -## read_lines - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Read bounded UTF-8 lines without terminators; CRLF is accepted and a final newline does not create a phantom row | - -Use `path`, `max_bytes`=8388608 as the inputs for this operation. - -Effects: fs.read. - -Read bounded UTF-8 lines without terminators; CRLF is accepted and a final newline does not create a phantom row. - -Return *[Read bounded UTF-8 lines without terminators; CRLF is accepted and a final newline does not create a phantom row](> host_fs_read_lines path=`path` max_bytes=`max_bytes`)*. - -## write_lines - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| lines | list | required | List of text lines to write | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `lines` as the inputs for this operation. - -Effects: fs.write. - -Atomically write text lines using LF and one final newline for nonempty input. - -Return *[Atomically write text lines using LF and one final newline for nonempty input](> host_fs_write_lines path=`path` lines=`lines`)*. - -## remove_file - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path` as the inputs for this operation. - -Effects: fs.write. - -Delete a file, refusing directories; missing paths fail. Legacy remove remains recursive for compatibility. - -Return *[Delete a file, refusing directories; missing paths fail](> host_fs_remove_file path=`path`)*. - -## remove_empty_dir - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path` as the inputs for this operation. - -Effects: fs.write. - -Delete only an empty directory; refuses nonempty directories. Native filesystem only. - -Return *[Delete only an empty directory; refuses nonempty directories](> host_fs_remove_empty_dir path=`path`)*. - -## temp_dir - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| prefix | text | "mqtmp" | Prefix added to the generated name or tested against text | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Create a directory under the filesystem root and return its relative name | - -Use `prefix`="mqtmp" as the inputs for this operation. - -Effects: fs.write. - -Create a directory under the filesystem root and return its relative name. Caller owns cleanup with remove_tree; never uses a global OS temp directory. - -Return *[Create a directory under the filesystem root and return its relative name](> host_fs_temp_dir prefix=`prefix`)*. - -## file_hash - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Compute SHA-256 with a 64 KiB read buffer; supports binary and large files without loading the whole file | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Compute SHA-256 with a 64 KiB read buffer; supports binary and large files without loading the whole file. - -Return *[Compute SHA-256 with a 64 KiB read buffer; supports binary and large files without loading the whole file](> host_fs_file_hash path=`path`)*. - -## find - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| pattern | text | "**" | Relative path glob supporting *, ** and ? | -| exclude | any | None | Glob pattern list pruned during traversal; None excludes nothing | -| max_depth | number | 64 | Maximum traversal depth | -| kind | text | "file" | Entry kind filter: file, dir or all (files and directories) | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Find sorted relative paths with star, double-star and question-mark globs; exclude patterns prune directories; kind is file/dir/all | - -Use `path`, `pattern`="**", `exclude`=None, `max_depth`=64, `kind`="file" as the inputs for this operation. - -Effects: fs.read. - -Find sorted relative paths with star, double-star and question-mark globs; exclude patterns prune directories; kind is file/dir/all. No symlink traversal; at most 100000 results. Native filesystem snapshot. - -Return *[Find sorted relative paths with star, double-star and question-mark globs; exclude patterns prune directories; kind is file/dir/all](> host_fs_find path=`path` pattern=`pattern` exclude=`exclude` max_depth=`max_depth` kind=`kind`)*. - -## copy_tree - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| src | text | required | Source path; archive packing expects a directory | -| dest | text | required | Destination path; overwrite is allowed only where documented | -| overwrite | bool | False | Whether an existing destination file may be replaced | -| exclude | any | None | Glob pattern list pruned during traversal; None excludes nothing | -| dry_run | bool | False | Whether to return the plan without modifying files | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Copy files between disjoint trees | - -Use `src`, `dest`, `overwrite`=False, `exclude`=None, `dry_run`=False as the inputs for this operation. - -Effects: fs.write. - -Copy files between disjoint trees. Preflight conflicts; overwrite is opt-in. Returns relative changed files; dry_run plans only. Does not copy permissions, symlinks or empty directories. - -Return *[Copy files between disjoint trees](> host_fs_copy_tree src=`src` dest=`dest` overwrite=`overwrite` exclude=`exclude` dry_run=`dry_run`)*. - -## sync_tree - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| src | text | required | Source path; archive packing expects a directory | -| dest | text | required | Destination path; overwrite is allowed only where documented | -| overwrite | bool | False | Whether an existing destination file may be replaced | -| exclude | any | None | Glob pattern list pruned during traversal; None excludes nothing | -| dry_run | bool | False | Whether to return the plan without modifying files | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Copy new or changed files with copy_tree conflict rules | - -Use `src`, `dest`, `overwrite`=False, `exclude`=None, `dry_run`=False as the inputs for this operation. - -Effects: fs.write. - -Copy new or changed files with copy_tree conflict rules. Never deletes destination-only files; execution is not transactional. - -Return *[Copy new or changed files with copy_tree conflict rules](> host_fs_sync_tree src=`src` dest=`dest` overwrite=`overwrite` exclude=`exclude` dry_run=`dry_run`)*. - -## rename_many - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| moves | list | required | List of source/destination rename records | -| dry_run | bool | False | Whether to return the plan without modifying files | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | Preflight src/dest file records, reject existing or duplicate destinations, then rename in input order | - -Use `moves`, `dry_run`=False as the inputs for this operation. - -Effects: fs.write. - -Preflight src/dest file records, reject existing or duplicate destinations, then rename in input order. No cycles or rollback; dry_run reports the planned count. - -Return *[Preflight src/dest file records, reject existing or duplicate destinations, then rename in input order](> host_fs_rename_many moves=`moves` dry_run=`dry_run`)*. - -## read_json - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to filesystem root | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 解析后的数据 | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Read UTF-8 then use the standard parser; errors abort, so batch tasks should first use try_read_text. - -We retain **`body` = [Read UTF-8 text from the selected file](read_text(path=`path`))**. -Return *[Parse the JSON transport text](json.parse(text=`body`))*. - -## write_json - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to filesystem root | -| value | any | required | Data to serialize | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `value` as the inputs for this operation. - -Effects: fs.write. - -Serialize then atomically replace the file; formatting and comments are not preserved. - -We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`value`))**. -Return *[Atomic write](atomic_write(path=`path`, text=`body`))*. - -## read_csv - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to filesystem root | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 解析后的数据 | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Read UTF-8 then use the standard parser; errors abort, so batch tasks should first use try_read_text. - -We retain **`body` = [Read UTF-8 text from the selected file](read_text(path=`path`))**. -Return *[Parse](csv.parse(text=`body`))*. - -## write_csv - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to filesystem root | -| value | list | required | Data to serialize | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | None after completion; filesystem failures produce a diagnostic | - -Use `path`, `value` as the inputs for this operation. - -Effects: fs.write. - -Serialize then atomically replace the file; formatting and comments are not preserved. - -We retain **`body` = [Stringify](csv.stringify(rows=`value`))**. -Return *[Atomic write](atomic_write(path=`path`, text=`body`))*. - -## resolve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root, or an absolute path inside it | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Normalized absolute logical path after the native root and symlink checks | - -Use `path` to obtain an absolute address before giving a local file to another resource, such as a SQLite URL. The host resolves it using the same filesystem context as read_text and temp_dir, so a different process working directory does not change the selected root. The destination may not exist yet; its nearest existing ancestor still undergoes the native root and symlink checks. Requires fs.read and creates no file. The returned path remains logical, including permitted links; external plugins and processes retain their own operating-system authority. - -Return *[Resolve the path through the native filesystem context](host_fs_resolve(path=`path`))*. diff --git a/lib/hash.mq.md b/lib/hash.mq.md deleted file mode 100755 index eae5a5c..0000000 --- a/lib/hash.mq.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -markup: occlusion -title: lib/hash -description: Digests and HMAC (Mid M3). Integrity / cache keys — not password hashing. ---- - -Digests and HMAC. For integrity and cache keys — not password storage. - -Compute content digests and keyed message authentication. - -Behavior and limits: MD5/SHA1 are compatibility checksums, not password storage. Use security auth for passwords and fs.file_hash for bounded-memory binary file hashing. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/hash.rs](../src/host/hash.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## sha256 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | SHA-256 hex digest of text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/hash.mq.md sha256 'text="abc"' --effects none --json -``` - -SHA-256 hex digest of text. - -Caller: [hash.sha256] text=`s` - -Return *[SHA-256 hex digest of text](> host_hash_sha256 text=`text`)*. - -## sha1 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | SHA-1 hex digest of text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -SHA-1 hex digest of text. - -Return *[SHA-1 hex digest of text](> host_hash_sha1 text=`text`)*. - -## md5 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | MD5 hex digest of text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -MD5 hex digest of text. - -Return *[MD5 hex digest of text](> host_hash_md5 text=`text`)*. - -## hmac_sha256 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | required | Field name or key required by this operation | -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | HMAC-SHA256 of text with key | - -Use `key`, `text` as the inputs for this operation. - -Effects: pure. - -HMAC-SHA256 of text with key. - -Return *[HMAC-SHA256 of text with key](> host_hash_hmac_sha256 key=`key` text=`text`)*. diff --git a/lib/html.mq.md b/lib/html.mq.md deleted file mode 100755 index 3015359..0000000 --- a/lib/html.mq.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -markup: occlusion -title: lib/html -description: HTML escape / unescape (Mid2 M8). XSS floor for string assembly. ---- - -HTML escape helpers. Use before stitching untrusted text into markup. - -Escape or unescape HTML text. - -Behavior and limits: Escaping text does not sanitize an arbitrary HTML document. Build web content as Markdown leaves and structured View nodes. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/html_ops.rs](../src/host/html_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## escape - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Escape text for HTML | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/html.mq.md escape 'text="&"' --effects none --json -``` - -Escape text for HTML. - -Caller: [html.escape] text=`s` - -Return *[Escape text for HTML](> host_html_escape text=`text`)*. - -## unescape - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Unescape HTML entities in text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Unescape HTML entities in text. - -Return *[Unescape HTML entities in text](> host_html_unescape text=`text`)*. diff --git a/lib/json.mq.md b/lib/json.mq.md deleted file mode 100755 index 84a8394..0000000 --- a/lib/json.mq.md +++ /dev/null @@ -1,174 +0,0 @@ ---- -markup: occlusion -title: lib/json -description: JSON parse/stringify (shared EN/ZH import). Not a dict builder — use lib/table. ---- - -Parse and stringify JSON. For maps/lists prefer GFM tables and lib/table put; do not chain json.set / json.append in new code. - -Parse and serialize JSON at the data boundary. - -Behavior and limits: Use table for collection operations. JSON boundary rejects unsafe integers, duplicate keys and nonfinite numbers; do not turn opaque handles into guessed records. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/json.rs](../src/host/json.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Parse JSON text into a Marqdo value | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Parse JSON text into a Marqdo value. - -Caller: [json.parse] text="{}" - -Return *[Parse JSON text into a Marqdo value](> host_json_parse text=`text`)*. - -## stringify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | -| indent | any | None | JSON indentation setting; None uses compact output | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Serialize value to JSON text; optional indent | - -Use `value`, `indent`=None as the inputs for this operation. - -Effects: pure. - -Serialize value to JSON text; optional indent. - -Return *[Serialize value to JSON text; optional indent](> host_json_stringify value=`value` indent=`indent`)*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | -| key | text | required | Field name or key required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Shallow get from JSON object value at key | - -Use `value`, `key` as the inputs for this operation. - -Effects: pure. - -Shallow get from JSON object value at key. Prefer link-index get or table.get in new code. - -Return *[Shallow get from JSON object value at key](> host_json_get value=`value` key=`key`)*. - -## keys - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Keys of JSON object value | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Keys of JSON object value. - -Return *[Keys of JSON object value](> host_json_keys value=`value`)*. - -## quote - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | JSON-quote string text (for building request bodies) | - -Use `text` as the inputs for this operation. - -Effects: pure. - -JSON-quote string text (for building request bodies). - -Return *[JSON-quote string text (for building request bodies)](> host_json_quote text=`text`)*. - -## set - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | -| key | text | required | Field name or key required by this operation | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Compatibility shallow set | - -Use `map`, `key`, `value` as the inputs for this operation. - -Effects: pure. - -Compatibility shallow set. Prefer table.put / table.set. - -Return *[Compatibility shallow set](> host_map_set map=`map` key=`key` value=`value`)*. - -## append - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| item | any | required | Element to insert, replace or compare | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Compatibility append | - -Use `list`, `item` as the inputs for this operation. - -Effects: pure. - -Compatibility append. Prefer table.append. - -Return *[Compatibility append](> host_list_append list=`list` item=`item`)*. - -## try_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Return {ok,value,error}; parse failures are recoverable data | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/json.mq.md try_parse 'text="{"name":"Marqdo","n":2}"' --effects none --json -``` - -Return {ok,value,error}; parse failures are recoverable data. - -Return *[Return {ok,value,error}; parse failures are recoverable data](> host_try_json_parse text=`text`)*. diff --git a/lib/lint/narrative.mq.md b/lib/lint/narrative.mq.md deleted file mode 100755 index ad3aee8..0000000 --- a/lib/lint/narrative.mq.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -markup: occlusion -title: lib/lint/narrative -description: >- - Narration-ratio skill (≥50%). Canonical checker: marqdo check --narrative-ratio. ---- - -Narration ratio skill. Every authored function unit should mix narration with -code so narration is more than half the text. This is the first skill-as-tools -example called out in the author vision notes: the page is documentation, and -its headings are tools. The canonical path checker lives in the host as -marqdo check --narrative-ratio so directory dogfood does not need filesystem -effects inside a pure call. - -For AI agents: run marqdo check --narrative-ratio on edited library files. -This is a readability signal; parsing, contracts, executable examples and real -behavior tests provide correctness evidence. Headings name actual tools only. - -## remind - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | rule reminder map | - -Return a small map stating the narration threshold and the CLI to run. Takes no -parameters. Use this when an agent needs a tool-shaped reminder without opening -design docs. The threshold is one half. Contract tables count as narration; -call lines and bold statements count as code. - -`out` = - -| threshold | cli | tables | -|-----------|-----|--------| -| 0.5 | marqdo check --narrative-ratio FILE | narration | - -Return *out*. diff --git a/lib/log.mq.md b/lib/log.mq.md deleted file mode 100755 index 16df35d..0000000 --- a/lib/log.mq.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -markup: occlusion -title: lib/log -description: Level-filtered one-line logs (Mid M6 + Mid2 M10 fields). Default level info. ---- - -Level-filtered one-line logs (Mid M6 + Mid2 M10 fields). Default level info. - -Emit level-filtered diagnostic lines. - -Behavior and limits: set_level changes this run only. Logs are side effects, not return values. call captures stdout separately from its JSON result. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/log.rs](../src/host/log.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## set_level - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| level | any | required | Log threshold: debug, info, warn or error | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | level is debug / info / warn / error | - -Use `level` as the inputs for this operation. - -Effects: pure. - -level is debug / info / warn / error. - -Return *[level is debug / info / warn / error](> host_log_set_level level=`level`)*. - -## debug - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| fields | any | None | Structured field/value record attached to the log event | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Emit a debug log line; optional fields map | - -Use `text`, `fields`=None as the inputs for this operation. - -Effects: output.write. - -Emit a debug log line; optional fields map. - -We retain **`line` = [Log line]([Emit a debug log line; optional fields map](host_log_line(level="debug", text=`text`, fields=`fields`)))**. -1. `line` - We **[Print the prepared message](print(text=`line`))**. -2. * - Return *None*. - -## info - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| fields | any | None | Structured field/value record attached to the log event | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Emit an info log line; optional fields map | - -Use `text`, `fields`=None as the inputs for this operation. - -Effects: output.write. - -Call this function directly: - -```sh -marqdo call lib/log.mq.md info 'text="handbook example"' 'fields={"task":"sample"}' --effects output.write --json -``` - -Emit an info log line; optional fields map. - -We retain **`line` = [Log line]([Emit an info log line; optional fields map](host_log_line(level="info", text=`text`, fields=`fields`)))**. -1. `line` - We **[Print the prepared message](print(text=`line`))**. -2. * - Return *None*. - -## warn - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| fields | any | None | Structured field/value record attached to the log event | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Emit a warn log line; optional fields map | - -Use `text`, `fields`=None as the inputs for this operation. - -Effects: output.write. - -Emit a warn log line; optional fields map. - -We retain **`line` = [Log line]([Emit a warn log line; optional fields map](host_log_line(level="warn", text=`text`, fields=`fields`)))**. -1. `line` - We **[Print the prepared message](print(text=`line`))**. -2. * - Return *None*. - -## error - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| fields | any | None | Structured field/value record attached to the log event | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Emit an error log line; optional fields map | - -Use `text`, `fields`=None as the inputs for this operation. - -Effects: output.write. - -Emit an error log line; optional fields map. - -We retain **`line` = [Log line]([Emit an error log line; optional fields map](host_log_line(level="error", text=`text`, fields=`fields`)))**. -1. `line` - We **[Print the prepared message](print(text=`line`))**. -2. * - Return *None*. diff --git a/lib/math.mq.md b/lib/math.mq.md deleted file mode 100755 index 312c133..0000000 --- a/lib/math.mq.md +++ /dev/null @@ -1,685 +0,0 @@ ---- -markup: occlusion -title: lib/math -description: High-school math — num, random, formula, plot ---- - -High-school math — num, random, formula, plot - -Compute numbers, symbolic expressions and plots. - -Behavior and limits: Number contracts include symbolic formulas. Random values require random.read. Plotting emits an artifact and needs output.write; linear algebra and quantum workloads stay in ext. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/math.rs](../src/host/math.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## pi - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return the mathematical constant pi | - -Effects: pure. - -Return the mathematical constant pi. - -Return *[Return the mathematical constant pi](host_pi())*. - -## e - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return Euler constant e | - -Effects: pure. - -Return Euler constant e. - -Return *[Return Euler constant e](host_e())*. - -## num - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Convert a numeric value or numeric text to a number | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Convert a numeric value or numeric text to a number. - -Return *[Convert a numeric value or numeric text to a number](> host_num value=`value`)*. - -## add - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First operand; its domain is described by this operation | -| b | any | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Add the two numeric or symbolic operands | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Add the two numeric or symbolic operands. - -Return *[Add the two numeric or symbolic operands](> host_math_add a=`a` b=`b`)*. - -## sub - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First operand; its domain is described by this operation | -| b | any | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Subtract b from a | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Subtract b from a. - -Return *[Subtract b from a](> host_math_sub a=`a` b=`b`)*. - -## mul - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First operand; its domain is described by this operation | -| b | any | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Multiply a by b | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Multiply a by b. - -Return *[Multiply a by b](> host_math_mul a=`a` b=`b`)*. - -## div - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First operand; its domain is described by this operation | -| b | any | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Divide a by b; zero divisor is an error | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Divide a by b; zero divisor is an error. - -Return *[Divide a by b; zero divisor is an error](> host_math_div a=`a` b=`b`)*. - -## pow - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First operand; its domain is described by this operation | -| b | any | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Raise a to the power b | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Raise a to the power b. - -Return *[Raise a to the power b](> host_math_pow a=`a` b=`b`)*. - -## neg - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Negate a numeric or symbolic value | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Negate a numeric or symbolic value. - -Return *[Negate a numeric or symbolic value](> host_math_neg value=`value`)*. - -## sin - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute sine; numeric angles are radians | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute sine; numeric angles are radians. - -Return *[Compute sine; numeric angles are radians](> host_math_sin value=`value`)*. - -## cos - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute cosine; numeric angles are radians | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute cosine; numeric angles are radians. - -Return *[Compute cosine; numeric angles are radians](> host_math_cos value=`value`)*. - -## tan - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute tangent; numeric angles are radians | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute tangent; numeric angles are radians. - -Return *[Compute tangent; numeric angles are radians](> host_math_tan value=`value`)*. - -## asin - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute arcsine in radians | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute arcsine in radians. - -Return *[Compute arcsine in radians](> host_math_asin value=`value`)*. - -## acos - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute arccosine in radians | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute arccosine in radians. - -Return *[Compute arccosine in radians](> host_math_acos value=`value`)*. - -## atan - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute arctangent in radians | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute arctangent in radians. - -Return *[Compute arctangent in radians](> host_math_atan value=`value`)*. - -## sqrt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute the square root of value | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/math.mq.md sqrt value=9 --effects none --json -``` - -Compute the square root of value. - -Return *[Compute the square root of value](> host_math_sqrt value=`value`)*. - -## abs - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return absolute magnitude | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Return absolute magnitude. - -Return *[Return absolute magnitude](> host_math_abs value=`value`)*. - -## ln - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute natural logarithm | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute natural logarithm. - -Return *[Compute natural logarithm](> host_math_ln value=`value`)*. - -## exp - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Compute the exponential of value | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Compute the exponential of value. - -Return *[Compute the exponential of value](> host_math_exp value=`value`)*. - -## floor - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Round toward negative infinity | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Round toward negative infinity. - -Return *[Round toward negative infinity](> host_math_floor value=`value`)*. - -## ceil - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Round toward positive infinity | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Round toward positive infinity. - -Return *[Round toward positive infinity](> host_math_ceil value=`value`)*. - -## min - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First operand; its domain is described by this operation | -| b | any | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return the smaller operand | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Return the smaller operand. - -Return *[Return the smaller operand](> host_math_min a=`a` b=`b`)*. - -## max - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First operand; its domain is described by this operation | -| b | any | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return the larger operand | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Return the larger operand. - -Return *[Return the larger operand](> host_math_max a=`a` b=`b`)*. - -## random - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return a pseudo-random number; seed controls reproducibility | - -Effects: random.read. - -Return a pseudo-random number; seed controls reproducibility. - -Return *[Return a pseudo-random number; seed controls reproducibility](host_random())*. - -## random_int - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| min | any | required | Inclusive lower bound or start of the search/plot interval | -| max | any | required | Upper bound or end of the search/plot interval | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return a pseudo-random integer in the documented bounds | - -Use `min`, `max` as the inputs for this operation. - -Effects: random.read. - -Return a pseudo-random integer in the documented bounds. - -Return *[Return a pseudo-random integer in the documented bounds](> host_random_int min=`min` max=`max`)*. - -## seed - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Integer seed for reproducible random sequences | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Set this run pseudo-random generator seed; not suitable for secrets | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Set this run pseudo-random generator seed; not suitable for secrets. - -Return *[Set this run pseudo-random generator seed; not suitable for secrets](> host_seed value=`value`)*. - -## formula - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | any | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Parse expression text into a symbolic formula for later algebra or evaluation; invalid syntax produces a diagnostic | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Parse expression text into a symbolic formula for later algebra or evaluation; invalid syntax produces a diagnostic. - -Return *[Parse expression text into a symbolic formula for later algebra or evaluation; invalid syntax produces a diagnostic](> host_formula value=`text`)*. - -## simplify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Return a simplified formula without changing the input; this is symbolic algebra, not numeric evaluation | - -Use `formula` as the inputs for this operation. - -Effects: pure. - -Return a simplified formula without changing the input; this is symbolic algebra, not numeric evaluation. - -Return *[Return a simplified formula without changing the input; this is symbolic algebra, not numeric evaluation](> host_simplify value=`formula`)*. - -## expand - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Expand algebraic products and powers and return a new symbolic formula | - -Use `formula` as the inputs for this operation. - -Effects: pure. - -Expand algebraic products and powers and return a new symbolic formula. - -Return *[Expand algebraic products and powers and return a new symbolic formula](> host_expand value=`formula`)*. - -## diff - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | -| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Differentiate the formula with respect to the named symbol and return a symbolic derivative | - -Use `formula`, `var` as the inputs for this operation. - -Effects: pure. - -Differentiate the formula with respect to the named symbol and return a symbolic derivative. - -Return *[Differentiate the formula with respect to the named symbol and return a symbolic derivative](> host_diff formula=`formula` var=`var`)*. - -## subs - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | -| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Substitute a symbol with the supplied value; return a number if fully reduced, otherwise a formula | - -Use `formula`, `var`, `value` as the inputs for this operation. - -Effects: pure. - -Substitute a symbol with the supplied value; return a number if fully reduced, otherwise a formula. - -Return *[Substitute a symbol with the supplied value; return a number if fully reduced, otherwise a formula](> host_subs formula=`formula` var=`var` value=`value`)*. - -## eval - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | -| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Evaluate a formula at one numeric variable value; unresolved symbols produce a diagnostic | - -Use `formula`, `var`, `value` as the inputs for this operation. - -Effects: pure. - -Evaluate a formula at one numeric variable value; unresolved symbols produce a diagnostic. - -Return *[Evaluate a formula at one numeric variable value; unresolved symbols produce a diagnostic](> host_eval formula=`formula` var=`var` value=`value`)*. - -## solve - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | -| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | -| min | any | None | Inclusive lower bound or start of the search/plot interval | -| max | any | None | Upper bound or end of the search/plot interval | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Return roots for the named symbol within min and max; omitted bounds use -100 and 100 | - -Use `formula`, `var`, `min`=None, `max`=None as the inputs for this operation. - -Effects: pure. - -Return roots for the named symbol within min and max; omitted bounds use -100 and 100. - -Return *[Return roots for the named symbol within min and max; omitted bounds use -100 and 100](> host_solve formula=`formula` var=`var` min=`min` max=`max`)*. - -## plot - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | -| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | -| min | any | required | Inclusive lower bound or start of the search/plot interval | -| max | any | required | Upper bound or end of the search/plot interval | -| steps | any | None | Number of samples across the plotting interval | -| path | any | None | Path relative to the granted filesystem root | -| derivative | any | None | Whether to include the derivative in the plot | -| grid | any | None | Whether to draw a coordinate grid | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Sample the formula over the interval and return SVG text; an optional path also writes the SVG under the granted root | - -Use `formula`, `var`, `min`, `max`, `steps`=None, `path`=None, `derivative`=None, `grid`=None as the inputs for this operation. - -Effects: output.write. - -Sample the formula over the interval and return SVG text; an optional path also writes the SVG under the granted root. - -Return *[Sample the formula over the interval and return SVG text; an optional path also writes the SVG under the granted root](> host_plot formula=`formula` var=`var` min=`min` max=`max` steps=`steps` path=`path` derivative=`derivative` grid=`grid`)*. - -## plot_points - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | required | Input list or collection, as required by this operation | -| ys | any | required | Y-coordinate list paired with xs | -| path | any | None | Path relative to the granted filesystem root | -| grid | any | None | Whether to draw a coordinate grid | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Plot paired x/y lists and return SVG text; unequal coordinate lengths are rejected | - -Use `xs`, `ys`, `path`=None, `grid`=None as the inputs for this operation. - -Effects: output.write. - -Plot paired x/y lists and return SVG text; unequal coordinate lengths are rejected. - -Return *[Plot paired x/y lists and return SVG text; unequal coordinate lengths are rejected](> host_plot_points xs=`xs` ys=`ys` path=`path` grid=`grid`)*. - -## plot_conic - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| kind | any | required | Conic type accepted by plot_conic | -| a | any | required | First operand; its domain is described by this operation | -| b | any | None | Second operand; its domain is described by this operation | -| h | any | None | Horizontal shift of the conic center | -| k | any | None | Vertical shift of the conic center | -| path | any | None | Path relative to the granted filesystem root | -| grid | any | None | Whether to draw a coordinate grid | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Draw the selected conic with its dimensions and center offsets and return SVG text | - -Use `kind`, `a`, `b`=None, `h`=None, `k`=None, `path`=None, `grid`=None as the inputs for this operation. - -Effects: output.write. - -Draw the selected conic with its dimensions and center offsets and return SVG text. - -Return *[Draw the selected conic with its dimensions and center offsets and return SVG text](> host_plot_conic kind=`kind` a=`a` b=`b` h=`h` k=`k` path=`path` grid=`grid`)*. diff --git a/lib/net.mq.md b/lib/net.mq.md deleted file mode 100755 index de098ee..0000000 --- a/lib/net.mq.md +++ /dev/null @@ -1,295 +0,0 @@ ---- -markup: occlusion -import: - table: lib/table.mq.md - text: lib/text.mq.md -title: lib/net -description: English HTTP(S) wrappers. Optional headers / content_type via host aliases. ---- - -English HTTP(S) wrappers. Optional headers / content_type via host aliases. - -Use HTTP, response parsing and bounded downloads. - -Behavior and limits: get requires network.read; configurable request conservatively requires network.write because its method is dynamic. request/get return Result with response headers; legacy http_* retain their historical contracts. Downloads also require fs.write. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/net.rs](../src/host/net.rs)、[src/host/net_ops.rs](../src/host/net_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## http_get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| headers | any | None | HTTP header name/value record; None sends no extra headers | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | HTTPS supported | - -Use `url`, `headers`=None as the inputs for this operation. - -Effects: network.read. - -HTTPS supported. Optional named arg `headers=` (map). Responses are capped at 8 MiB before decoding, so an upstream cannot exhaust the interpreter's memory. - -Return *[HTTPS supported](> host_http_get url=`url` headers=`headers`)*. - -## http_post - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| body | any | required | Request body, or replacement text for document operations | -| content_type | any | None | HTTP content type override; None uses the helper default | -| headers | any | None | HTTP header name/value record; None sends no extra headers | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Default content type is JSON | - -Use `url`, `body`, `content_type`=None, `headers`=None as the inputs for this operation. - -Effects: network.write. - -Default content type is JSON. Optional `content_type=` / `headers=` (map). - -Return *[Default content type is JSON](> host_http_post url=`url` body=`body` content_type=`content_type` headers=`headers`)*. - -## http_post_sse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| body | any | required | Request body, or replacement text for document operations | -| content_type | any | None | HTTP content type override; None uses the helper default | -| headers | any | None | HTTP header name/value record; None sends no extra headers | -| echo | bool | False | Whether to print streamed SSE text as it arrives | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | POST and consume OpenAI-compatible SSE | - -Use `url`, `body`, `content_type`=None, `headers`=None, `echo`=False as the inputs for this operation. - -Effects: network.write. - -POST and consume OpenAI-compatible SSE. Returns `{status, events}` where `events` is a list of `{type, …}` maps (`delta` / `done` / `error`). Optional `echo=True` prints delta text to stdout as chunks arrive. - -Return *[POST and consume OpenAI-compatible SSE](> host_http_post_sse url=`url` body=`body` content_type=`content_type` headers=`headers` echo=`echo`)*. - -## openai_sse_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| echo | bool | False | Whether to print streamed SSE text as it arrives | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Offline: parse an OpenAI chat SSE body into the same event list (no network) | - -Use `text`, `echo`=False as the inputs for this operation. - -Effects: pure. - -Offline: parse an OpenAI chat SSE body into the same event list (no network). - -Return *[Offline: parse an OpenAI chat SSE body into the same event list (no network)](> host_openai_sse_parse text=`text` echo=`echo`)*. - -## http_request - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| method | text | required | HTTP method, for example GET or POST | -| url | text | required | Target URL; HTTP helpers accept http or https | -| body | any | None | Request body, or replacement text for document operations | -| content_type | any | None | HTTP content type override; None uses the helper default | -| headers | any | None | HTTP header name/value record; None sends no extra headers | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Optional `body=` / `content_type=` / `headers=` | - -Use `method`, `url`, `body`=None, `content_type`=None, `headers`=None as the inputs for this operation. - -Effects: network.write. - -Optional `body=` / `content_type=` / `headers=`. - -Return *[Optional body= / content_type= / headers=](> host_http_request method=`method` url=`url` body=`body` content_type=`content_type` headers=`headers`)*. - -## url_encode - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Percent-encode a URL segment | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Percent-encode a URL segment. Spaces become `%20` (not form/query `+`), so literal `+` remains unambiguous in paths. - -Return *[Percent-encode a URL segment](> host_url_encode text=`text`)*. - -## cookie_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| is_response | any | False | Whether to parse a response header block rather than a request | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Parse a `Cookie` request header (default) or one or more `Set-Cookie` response headers (`is_response=True`) into a list of `{name, value, path, domain, expires, max_age, secure, http_only, same_site}` | - -Use `text`, `is_response`=False as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/net.mq.md cookie_parse 'text="a=1; b=2"' --effects none --json -``` - -Parse a `Cookie` request header (default) or one or more `Set-Cookie` response headers (`is_response=True`) into a list of `{name, value, path, domain, expires, max_age, secure, http_only, same_site}`. - -Return *[Parse a Cookie request header (default) or one or more Set-Cookie response headers (is_response=True) into a list of {name, value, path, domain, expires, max_age, secure,](> host_cookie_parse text=`text` is_response=`is_response`)*. - -## multipart_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| body | any | required | Request body, or replacement text for document operations | -| boundary | any | required | Multipart delimiter from the Content-Type header | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Parse a `multipart/form-data` request body (given its `boundary`) into a list of `{name, filename?, content_type?, value}` parts | - -Use `body`, `boundary` as the inputs for this operation. - -Effects: pure. - -Parse a `multipart/form-data` request body (given its `boundary`) into a list of `{name, filename?, content_type?, value}` parts. - -Return *[Parse a multipart/form-data request body (given its boundary) into a list of {name, filename?, content_type?, value} parts](> host_multipart_parse body=`body` boundary=`boundary`)*. - -## markdown_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Parse Markdown / GFM into HTML (pure transform, no network I/O) | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Parse Markdown / GFM into HTML (pure transform, no network I/O). - -Return *[Parse Markdown / GFM into HTML (pure transform, no network I/O)](> host_markdown_parse text=`text`)*. - -## request - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| method | text | required | HTTP method, for example GET or POST | -| url | text | required | Target URL; HTTP helpers accept http or https | -| body | any | None | Request body, or replacement text for document operations | -| headers | any | None | HTTP header name/value record; None sends no extra headers | -| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | -| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | -| response | text | "text" | Response body representation: text or bytes | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Return Result; value has status, headers and body | - -Use `method`, `url`, `body`=None, `headers`=None, `timeout_ms`=30000, `max_bytes`=8388608, `response`="text" as the inputs for this operation. - -Effects: network.write. - -Body is text, a bytes record or None; serialize JSON with json.stringify first. Request headers are a map; response headers are name/values records. Output options and destinations are checked before network IO. - -Return Result; value has status, headers and body. Timeout is milliseconds; response is text or bytes; headers are name/values records. HTTP error status is a valid response; transport failure is an error. - -Return *[Body is text, a bytes record or None; serialize JSON with json.stringify first](> host_http_request_result method=`method` url=`url` body=`body` headers=`headers` timeout_ms=`timeout_ms` max_bytes=`max_bytes` response=`response`)*. - -## download - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| path | text | required | Path within the granted filesystem root | -| headers | any | None | HTTP header name/value record; None sends no extra headers | -| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | -| max_bytes | number | 67108864 | Maximum bytes read or expanded; exceeding it fails | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Bounded streaming download; atomically replace destination only on successful status and complete transfer | - -Use `url`, `path`, `headers`=None, `timeout_ms`=30000, `max_bytes`=67108864 as the inputs for this operation. - -Effects: fs.write,network.read. - -Bounded streaming download; atomically replace destination only on successful status and complete transfer. Result value has status/headers/size/path; requires network.read and fs.write. - -Return *[Bounded streaming download; atomically replace destination only on successful status and complete transfer](> host_http_download url=`url` path=`path` headers=`headers` timeout_ms=`timeout_ms` max_bytes=`max_bytes`)*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Target URL; HTTP helpers accept http or https | -| headers | any | None | HTTP header name/value record; None sends no extra headers | -| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | -| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | -| response | text | "text" | Response body representation: text or bytes | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Read-only GET as Result, requiring only network | - -Use `url`, `headers`=None, `timeout_ms`=30000, `max_bytes`=8388608, `response`="text" as the inputs for this operation. - -Effects: network.read. - -Read-only GET as Result, requiring only network.read. Headers are name/values records; response is text or bytes. - -Return *[Read-only GET as Result, requiring only network.read](> host_http_get_result url=`url` headers=`headers` timeout_ms=`timeout_ms` max_bytes=`max_bytes` response=`response`)*. - -## header_values - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| headers | list | required | headers records from a response | -| name | text | required | Header name | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | All values for the header | - -Use `headers`, `name` as the inputs for this operation. - -Effects: pure. - -Return all values for a case-insensitive response header; missing yields an empty list. Request headers remain a map; response headers use records to preserve arbitrary names and repeated values. - -We retain **`lower` = [To lower](text.to_lower(text=`name`))**. -We retain **`matches` = [Where](table.where(list=`headers`, key="name", value=`lower`))**. -We retain **`values` = [Pluck](table.pluck(list=`matches`, key="values"))**. -Return *[Flatten](table.flatten(list=`values`))*. diff --git a/lib/path.mq.md b/lib/path.mq.md deleted file mode 100755 index 584b965..0000000 --- a/lib/path.mq.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -markup: occlusion -title: lib/path -description: Path algebra (Mid M2). No I/O; OS separators. ---- - -Path algebra only. No I/O; separators follow the host OS. - -Manipulate paths without accessing the filesystem. - -Behavior and limits: Normalization is lexical, not an authorization check. IO paths are checked by the host filesystem root. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/path.rs](../src/host/path.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## join - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Base path | -| b | any | required | Path segment appended to the base | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Join path segments a and b | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Join path segments a and b. - -Caller: [path.join] a="a" b="b" - -Return *[Join path segments a and b](> host_path_join a=`a` b=`b`)*. - -## split - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Split path into parts | - -Use `path` as the inputs for this operation. - -Effects: pure. - -Split path into parts. - -Return *[Split path into parts](> host_path_split path=`path`)*. - -## file_name - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Final file name of path | - -Use `path` as the inputs for this operation. - -Effects: pure. - -Final file name of path. - -Return *[Final file name of path](> host_path_file_name path=`path`)*. - -## parent - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Parent directory of path | - -Use `path` as the inputs for this operation. - -Effects: pure. - -Parent directory of path. - -Return *[Parent directory of path](> host_path_parent path=`path`)*. - -## extension - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | File extension of path | - -Use `path` as the inputs for this operation. - -Effects: pure. - -File extension of path. - -Return *[File extension of path](> host_path_extension path=`path`)*. - -## normalize - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Normalize path (dot segments) | - -Use `path` as the inputs for this operation. - -Effects: pure. - -Normalize path (dot segments). - -Return *[Normalize path (dot segments)](> host_path_normalize path=`path`)*. - -## is_absolute - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether path is absolute | - -Use `path` as the inputs for this operation. - -Effects: pure. - -Whether path is absolute. - -Return *[Whether path is absolute](> host_path_is_absolute path=`path`)*. - -## relative - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| base | text | required | Base directory for relative path calculation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Compute a lexical path relative to base; both arguments must share absolute/relative form | - -Use `path`, `base` as the inputs for this operation. - -Effects: pure. - -Compute a lexical path relative to base; both arguments must share absolute/relative form. No disk access. - -Return *[Compute a lexical path relative to base; both arguments must share absolute/relative form](> host_path_relative path=`path` base=`base`)*. - -## with_extension - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path within the granted filesystem root | -| extension | text | required | New extension, with or without a leading dot | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Replace the last extension; empty extension removes it | - -Use `path`, `extension` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/path.mq.md with_extension 'path="notes/draft.txt"' 'extension="md"' --effects none --json -``` - -Replace the last extension; empty extension removes it. - -Return *[Replace the last extension; empty extension removes it](> host_path_with_extension path=`path` extension=`extension`)*. diff --git a/lib/plugin.mq.md b/lib/plugin.mq.md deleted file mode 100755 index 0923a92..0000000 --- a/lib/plugin.mq.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -markup: occlusion -title: lib/plugin -description: Load optional native ABI plugins (.dll / .so / .dylib) ---- - -Load optional native ABI plugins (.dll / .so / .dylib). - -Locate and load native capabilities. - -Behavior and limits: An empty list means no plugin is loaded in this process. Loading requires plugin.call. Prefer the relevant domain index for normal work; plugins are native-only. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/plugin.rs](../src/host/plugin.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## load - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load a native plugin from path | - -Use `path` as the inputs for this operation. - -Effects: plugin.call. - -Load a native plugin from path. - -Caller: [plugin.load] path=`so` - -Return *[Load a native plugin from path](> host_plugin_load path=`path`)*. - -## unload - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Unload the current native plugin | - -Effects: plugin.call. - -Unload the current native plugin. - -Return *[Unload the current native plugin](host_plugin_unload())*. - -## list - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | List loaded native plugins | - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/plugin.mq.md list --effects none --json -``` - -List loaded native plugins. - -Return names loaded in this host process. Listing does not load a plugin, and a new process may have an empty list. - -Return *[List loaded native plugins](host_plugin_list())*. - -## native_path - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Installed extension identifier, for example agent | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Resolve installed or local native plugin path (e.g | - -Use `name` as the inputs for this operation. - -Effects: plugin.call. - -Resolve installed or local native plugin path (e.g. agent). - -Return *[Resolve installed or local native plugin path (e.g](> host_ext_native_path name=`name`)*. diff --git a/lib/re.mq.md b/lib/re.mq.md deleted file mode 100755 index baca4b3..0000000 --- a/lib/re.mq.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -markup: occlusion -title: lib/re -description: Regular expressions (Mid M1). Unicode; no backreferences. ---- - -Regular expressions. Unicode; no backreferences. Prefer lib/text for literal replace. - -Match Unicode regular expressions. - -Behavior and limits: The engine has no backreferences. Current find functions return whole matches; capture groups and replacement callbacks are not promised. Literal replacement belongs in text. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/re.rs](../src/host/re.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## is_match - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| pattern | text | required | Regular expression supported by the regex host | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether text matches pattern | - -Use `text`, `pattern` as the inputs for this operation. - -Effects: pure. - -Whether text matches pattern. - -Caller: [re.is_match] text=`s` pattern="a+" - -Return *[Whether text matches pattern](> host_re_is_match text=`text` pattern=`pattern`)*. - -## find - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| pattern | text | required | Regular expression supported by the regex host | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | First match of pattern in text, or None | - -Use `text`, `pattern` as the inputs for this operation. - -Effects: pure. - -First match of pattern in text, or None. - -Return *[First match of pattern in text, or None](> host_re_find text=`text` pattern=`pattern`)*. - -## find_all - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| pattern | text | required | Regular expression supported by the regex host | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | All matches of pattern in text | - -Use `text`, `pattern` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/re.mq.md find_all 'text="a12 b34"' 'pattern="[0-9]+"' --effects none --json -``` - -All matches of pattern in text. - -Return *[All matches of pattern in text](> host_re_find_all text=`text` pattern=`pattern`)*. - -## replace - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| pattern | text | required | Regular expression supported by the regex host | -| with | any | required | Replacement text applied to matched spans | -| count | any | None | Maximum replacement count; None uses the documented default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Replace matches of pattern in text with with; optional count limits replacements (None = all) | - -Use `text`, `pattern`, `with`, `count`=None as the inputs for this operation. - -Effects: pure. - -Replace matches of pattern in text with with; optional count limits replacements (None = all). - -Return *[Replace matches of pattern in text with with; optional count limits replacements (None = all)](> host_re_replace text=`text` pattern=`pattern` with=`with` count=`count`)*. - -## split - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| pattern | text | required | Regular expression supported by the regex host | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Split text on pattern | - -Use `text`, `pattern` as the inputs for this operation. - -Effects: pure. - -Split text on pattern. - -Return *[Split text on pattern](> host_re_split text=`text` pattern=`pattern`)*. diff --git a/lib/result.mq.md b/lib/result.mq.md deleted file mode 100755 index eafefba..0000000 --- a/lib/result.mq.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -markup: occlusion ---- - -Recoverable outcomes use one ordinary record: ok/value/error. A failure's error -contains code/message/operation. Inspect ok before consuming value. Host policy -checks still apply; a Result wrapper never authorizes an effect. - -Compose recoverable outcomes with one data contract. - -Behavior and limits: Check ok before value; HTTP status and child exit code remain domain-level results; errors have code/message/operation. Use try_ operations to recover known IO/parse failures. Result construction does not catch arbitrary runtime errors or grant permission. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/result.rs](../src/host/result.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## ok - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Successful operation value, including None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Successful Result | - -Use `value` as the inputs for this operation. - -Delegate to ok with the supplied inputs, preserving its result and failure behavior. - -Effects: pure. - -`out` = - -| ok | value | error | -|----|-------|-------| -| True | `value` | None | - -Return *out*. - -## error - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| code | text | required | Stable machine-readable category | -| message | text | required | Human-readable explanation | -| operation | text | "application" | Operation that failed | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Failed Result | - -Use `code`, `message`, `operation`="application" as the inputs for this operation. - -Delegate to error with the supplied inputs, preserving its result and failure behavior. - -Effects: pure. - -`failure` = - -| code | message | operation | -|------|---------|-----------| -| `code` | `message` | `operation` | - -`out` = - -| ok | value | error | -|----|-------|-------| -| False | None | `failure` | - -Return *out*. - -## value_or - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| result | map | required | Result from a recoverable operation | -| default | any | None | Explicit fallback on failure | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Successful value or fallback | - -Use `result`, `default`=None as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/result.mq.md value_or 'result={"ok":false,"value":null,"error":{"code":"missing","message":"absent","operation":"example"}}' 'default="fallback"' --effects none --json -``` - -Read value only when ok is true, including a successful None. Use the fallback only on failure; zero and empty text remain valid values. - -1. [operation succeeded](access(`result`, "ok")) - Return *[successful value](access(result, "value"))*. -2. * - Return *default*. diff --git a/lib/secrets.mq.md b/lib/secrets.mq.md deleted file mode 100755 index d60f783..0000000 --- a/lib/secrets.mq.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -markup: occlusion -title: lib/secrets -description: Cryptographic tokens (Mid M3). Do not use math.random for secrets. ---- - -Cryptographic tokens. Do not use math.random for secrets. - -Generate cryptographically random tokens. - -Behavior and limits: n counts input bytes. Do not use math.random for credentials. Browser entropy depends on the runtime bridge; do not silently substitute a pseudo-random generator. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/secrets.rs](../src/host/secrets.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## token_hex - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | None | Requested byte count; None uses the helper default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Byte length n (default 16) | - -Use `n`=None as the inputs for this operation. - -Effects: random.read. - -Call this function directly: - -```sh -marqdo call lib/secrets.mq.md token_hex n=16 --effects random.read --json -``` - -Byte length n (default 16). Returns lowercase hex of length 2*n. - -Caller: [secrets.token_hex] n=16 - -Return *[Byte length n (default 16)](> host_secrets_token_hex n=`n`)*. - -## token_urlsafe - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | None | Requested byte count; None uses the helper default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Byte length n (default 16) | - -Use `n`=None as the inputs for this operation. - -Effects: random.read. - -Byte length n (default 16). URL-safe Base64 without padding. - -Return *[Byte length n (default 16)](> host_secrets_token_urlsafe n=`n`)*. diff --git a/lib/stats.mq.md b/lib/stats.mq.md deleted file mode 100755 index c94bc65..0000000 --- a/lib/stats.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/stats -description: Thin mean / median / sample stdev (Mid2 M10). Not a dataframe library. ---- - -Thin numeric summaries. Not a dataframe library. - -Compute small descriptive statistics. - -Behavior and limits: mean/median require nonempty numeric lists. This is not a dataframe or numerical array runtime; ext/linalg owns matrix operations. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/stats.rs](../src/host/stats.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## mean - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Arithmetic mean of list | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/stats.mq.md mean 'list=[1,2,3]' --effects none --json -``` - -Arithmetic mean of list. - -Caller: [stats.mean] list=`xs` - -Return *[Arithmetic mean of list](> host_stats_mean list=`list`)*. - -## median - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Median of list | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Median of list. - -Return *[Median of list](> host_stats_median list=`list`)*. - -## stdev - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Sample standard deviation; needs at least two values | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Sample standard deviation; needs at least two values. - -Return *[Sample standard deviation; needs at least two values](> host_stats_stdev list=`list`)*. diff --git a/lib/subtask.mq.md b/lib/subtask.mq.md deleted file mode 100755 index 0ab5962..0000000 --- a/lib/subtask.mq.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -markup: occlusion -title: lib/subtask -description: Concurrent subtasks — file, function, or foreign code ---- - -Concurrent subtasks: file, function, or foreign code. - -Run and observe concurrent work with explicit ownership. - -Behavior and limits: File batches inherit parent caps and root. Each Result.ok reports completion of the wait protocol; inspect value.code for child exit success. wait_timeout keeps its handle unless cancel is requested. OS tasks can be killed/reaped; function-thread cancellation is logical only. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. - -Implementation: [src/host/subtask.rs](../src/host/subtask.rs)、[src/host/task_ops.rs](../src/host/task_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## spawn - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Path relative to the granted filesystem root | -| fn | any | None | Marqdo function target used instead of a file task | -| args | any | None | Arguments supplied to the selected task | -| code | any | None | Bound code-fence value; supply lang and source for inline text | -| lang | any | None | Registered interpreter language identifier, such as python | -| source | any | None | Source text to run with the selected interpreter | -| stdin | any | None | Text written to the child process standard input | -| quiet | bool | True | Whether to suppress child output while retaining its result | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Start a subtask | - -Use `path`=None, `fn`=None, `args`=None, `code`=None, `lang`=None, `source`=None, `stdin`=None, `quiet`=True as the inputs for this operation. - -Effects: process.exec. - -Start a subtask. File children are silent by default (quiet=True: piped capture). Set quiet=False to inherit parent stdout/stderr. File wait returns {code, value} plus optional stdout/stderr tails when quiet-captured. value is the child main return (not stdout). - -Caller: [subtask.spawn] path="child.mq.md" - -Return *[Start a subtask](> host_subtask_spawn path=`path` fn=`fn` args=`args` code=`code` lang=`lang` source=`source` stdin=`stdin` quiet=`quiet`)*. - -## poll - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier returned by the corresponding create/spawn operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Non-blocking status for subtask id | - -Use `id` as the inputs for this operation. - -Effects: process.exec. - -Non-blocking status for subtask id. - -Return *[Non-blocking status for subtask id](> host_subtask_poll id=`id`)*. - -## wait - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier returned by the corresponding create/spawn operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Block until subtask id finishes | - -Use `id` as the inputs for this operation. - -Effects: process.exec. - -Block until subtask id finishes. - -Return *[Block until subtask id finishes](> host_subtask_join id=`id`)*. - -## kill - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | required | Identifier returned by the corresponding create/spawn operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Kill subtask id | - -Use `id` as the inputs for this operation. - -Effects: process.exec. - -Kill subtask id. - -Return *[Kill subtask id](> host_subtask_kill id=`id`)*. - -## wait_all - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Wait until every spawned subtask finishes | - -Effects: process.exec. - -Wait until every spawned subtask finishes. - -Return *[Wait until every spawned subtask finishes](host_subtask_wait_all())*. - -## wait_timeout - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | number | required | Identifier returned by the corresponding create/spawn operation | -| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | -| cancel | bool | False | Whether a timeout also cancels the outstanding task | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Wait as Result; timeout retains the handle unless cancel=True | - -Use `id`, `timeout_ms`=30000, `cancel`=False as the inputs for this operation. - -Effects: process.exec. - -Wait as Result; timeout retains the handle unless cancel=True. Cancellation reaps process tasks; function-thread cancellation is logical only. - -Return *[Wait as Result; timeout retains the handle unless cancel=True](> host_subtask_wait_timeout id=`id` timeout_ms=`timeout_ms` cancel=`cancel`)*. - -## cancel_all - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | Cancel all subtasks, reaping process tasks; return count | - -Effects: process.exec. - -Cancel all subtasks, reaping process tasks; return count. Function threads only support logical cancellation. - -Return *[Cancel all subtasks, reaping process tasks; return count](> host_subtask_cancel_all )*. - -## run_many - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| tasks | list | required | Ordered file task records containing path and optional args | -| limit | number | 4 | Maximum simultaneous file tasks, from 1 through 64 | -| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Run path/args file tasks with bounded concurrency; return ordered Results | - -Use `tasks`, `limit`=4, `timeout_ms`=30000 as the inputs for this operation. - -Effects: process.exec. - -Call this function directly: - -```sh -marqdo call lib/subtask.mq.md run_many 'tasks=[{"path":"examples/stdlib-handbook/worker.mq.md"}]' limit=2 --effects process.exec --fs-root . --json -``` - -Run path/args file tasks with bounded concurrency; return ordered Results. Timed-out children are killed and reaped; at most 10000 tasks, 64 workers; inherit parent caps and filesystem root. - -Return *[Run path/args file tasks with bounded concurrency; return ordered Results](> host_subtask_run_many tasks=`tasks` limit=`limit` timeout_ms=`timeout_ms`)*. diff --git a/lib/sys.mq.md b/lib/sys.mq.md deleted file mode 100755 index 44bd623..0000000 --- a/lib/sys.mq.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -markup: occlusion -title: lib/sys -description: English system wrappers (load_dotenv accepts optional path via host alias) ---- - -English system wrappers (load_dotenv accepts optional path via host alias) - -Inspect execution metadata and interact with the host system. - -Behavior and limits: Metadata describes the entry artifact. module_source is entry source, not the imported library. exec needs process.exec; environment operations declare separate effects. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/sys.rs](../src/host/sys.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## env_get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Environment variable name | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Get environment variable name | - -Use `name` as the inputs for this operation. - -Effects: environment.read. - -Get environment variable name. - -Return *[Get environment variable name](> host_env_get name=`name`)*. - -## env_set - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| name | text | required | Environment variable name | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Set environment variable name to value | - -Use `name`, `value` as the inputs for this operation. - -Effects: environment.write. - -Set environment variable name to value. - -Return *[Set environment variable name to value](> host_env_set name=`name` value=`value`)*. - -## load_dotenv - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | any | None | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Load `.env` (optional named arg `path=`) | - -Use `path`=None as the inputs for this operation. - -Effects: environment.write,fs.read. - -Load `.env` (optional named arg `path=`). Existing process env is not overridden. - -Return *[Load .env (optional named arg path=)](> host_dotenv_load path=`path`)*. - -## args - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Process argv list | - -Effects: pure. - -Process argv list. - -Return *[Process argv list](host_args())*. - -## cwd - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Current working directory | - -Effects: pure. - -Current working directory. - -Return *[Current working directory](host_cwd())*. - -## meta - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Bound Artifact Metadata from the entry `.mq.md` (map) | - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/sys.mq.md meta --effects none --json -``` - -Bound Artifact Metadata from the entry `.mq.md` (map). See `doc/design/binding.md`. - -Return *[Bound Artifact Metadata from the entry .mq.md (map)](host_meta())*. - -## meta_get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | required | Field name or key required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Lookup one metadata key; missing → None | - -Use `key` as the inputs for this operation. - -Effects: pure. - -Lookup one metadata key; missing → None. - -Return *[Lookup one metadata key; missing → None](> host_meta_get key=`key`)*. - -## artifact_kind - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Classify entry Artifact Metadata: `web` / `endpoint` / `prompt` / `other`, or None if no `type`/`类型` | - -Effects: pure. - -Classify entry Artifact Metadata: `web` / `endpoint` / `prompt` / `other`, or None if no `type`/`类型`. ADR 0007. - -Return *[Classify entry Artifact Metadata: web / endpoint / prompt / other, or None if no type/类型](host_artifact_kind())*. - -## module_source - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Entry `.mq.md` source text (for document-as-prompt) | - -Effects: pure. - -Entry `.mq.md` source text (for document-as-prompt). Empty string if unset. - -Return *[Entry .mq.md source text (for document-as-prompt)](host_module_source())*. - -## exit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| code | any | required | Process exit status; zero means success | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Exit process with code | - -Use `code` as the inputs for this operation. - -Effects: process.control. - -Exit process with code. - -Return *[Exit process with code](> host_exit code=`code`)*. - -## exec - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| cmd | any | required | Executable command or interpreter override | -| args | any | None | Argument list passed to the called command or function | -| capture | any | False | Whether to return command output instead of forwarding it | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Run a process | - -Use `cmd`, `args`=None, `capture`=False as the inputs for this operation. - -Effects: process.exec. - -Run a process. Default return is the exit code (int). - -With `capture=True`, return a map `{code, stdout, stderr}` (stdout/stderr may be truncated for huge output). - -Inside `**…**` prefer bare `args=args` (variable); `` args=`args` `` is also accepted. - -Return *[Run a process](> host_exec cmd=`cmd` args=`args` capture=`capture`)*. - -## stream_publish - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| event | any | required | Structured event to publish to the active stream | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Publish a stream event map onto the process EventBus (`marqdo view` SSE) | - -Use `event` as the inputs for this operation. - -Effects: output.write. - -Publish a stream event map onto the process EventBus (`marqdo view` SSE). No-op when nothing is subscribed. - -Return *[Publish a stream event map onto the process EventBus (marqdo view SSE)](> host_stream_publish event=`event`)*. diff --git a/lib/table.mq.md b/lib/table.mq.md deleted file mode 100755 index afa0812..0000000 --- a/lib/table.mq.md +++ /dev/null @@ -1,1182 +0,0 @@ ---- -markup: occlusion -title: lib/table -description: >- - List and map helpers. Prefer put (1-based path, same nesting as access reads); - at/set_at/slice are 0-based. Use lib/json only for parse/stringify. ---- - -List and map helpers. Prefer put for nested writes; authors should read with access reads, not new footnote indexes. - -Transform lists, maps and row records using explicit data shapes. - -Behavior and limits: put/access integer paths are one-based; at/slice/insert/remove_at are zero-based. Updates return new values: keep the result. rows is a length alias; from_columns/to_columns perform shape conversion. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/collection.rs](../src/host/collection.rs)、[src/host/collection_ops.rs](../src/host/collection_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## put - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| in | any | required | Input collection; None seeds a new record | -| at | any | required | Text key, one-based index, or nested path of keys and indices | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Update one element of collection in at path at to value | - -Use `in`, `at`, `value` as the inputs for this operation. - -Effects: pure. - -Update one element of collection in at path at to value. - -at is a text key, a 1-based list index, or a list of keys/indices (same nesting as access reads). - -Caller: [table.put] in=None at="Authorization" value="Bearer-x" - -Return *[Update one element of collection in at path at to value](> host_collection_put in=`in` at=`at` value=`value`)*. - -## len - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | required | Input list or collection, as required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Length of list or map xs | - -Use `xs` as the inputs for this operation. - -Effects: pure. - -Length of list or map xs. - -Return *[Len](len(`xs`))*. - -## rows - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | required | Input list or collection, as required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Row count for list xs (alias of len) | - -Use `xs` as the inputs for this operation. - -Effects: pure. - -Row count for list xs (alias of len). - -Return *[Len](len(`xs`))*. - -## at - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | required | Input list or collection, as required by this operation | -| i | number | required | Zero-based element or row index | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Zero-based index into xs at i (same as builtin at) | - -Use `xs`, `i` as the inputs for this operation. - -Effects: pure. - -Zero-based index into xs at i (same as builtin at). Out of range → None. - -Return *[At](at(value=`xs`, index=`i`))*. - -## row_at - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | required | Input list or collection, as required by this operation | -| i | number | required | Zero-based element or row index | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Zero-based row from xs at i | - -Use `xs`, `i` as the inputs for this operation. - -Effects: pure. - -Zero-based row from xs at i. - -Return *[At](at(value=`xs`, index=`i`))*. - -## append - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| item | any | required | Element to insert, replace or compare | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Append item to list | - -Use `list`, `item` as the inputs for this operation. - -Effects: pure. - -Append item to list. - -Return *[Append item to list](> host_list_append list=`list` item=`item`)*. - -## prepend - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| item | any | required | Element to insert, replace or compare | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Prepend item to list | - -Use `list`, `item` as the inputs for this operation. - -Effects: pure. - -Prepend item to list. - -Return *[Prepend item to list](> host_list_prepend list=`list` item=`item`)*. - -## concat - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First list; None is an empty-list seed | -| b | any | required | List appended after a | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Concatenate lists a and b | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Concatenate lists a and b. - -Return *[Concatenate lists a and b](> host_list_concat a=`a` b=`b`)*. - -## insert - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| index | number | required | Zero-based position to insert, replace or remove | -| item | any | required | Element to insert, replace or compare | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Insert item into list at zero-based index (may insert at len to append) | - -Use `list`, `index`, `item` as the inputs for this operation. - -Effects: pure. - -Insert item into list at zero-based index (may insert at len to append). - -Return *[Insert item into list at zero-based index (may insert at len to append)](> host_list_insert list=`list` index=`index` item=`item`)*. - -## set_at - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| index | number | required | Zero-based position to insert, replace or remove | -| item | any | required | Element to insert, replace or compare | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Zero-based replace of list at index with item | - -Use `list`, `index`, `item` as the inputs for this operation. - -Effects: pure. - -Zero-based replace of list at index with item. Prefer put with a 1-based index for author-facing edits. - -Return *[Zero-based replace of list at index with item](> host_list_set_at list=`list` index=`index` item=`item`)*. - -## remove_at - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| index | number | required | Zero-based position to insert, replace or remove | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Remove zero-based index from list | - -Use `list`, `index` as the inputs for this operation. - -Effects: pure. - -Remove zero-based index from list. - -Return *[Remove zero-based index from list](> host_list_remove_at list=`list` index=`index`)*. - -## pop - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Drop the last item of list (errors if empty) | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Drop the last item of list (errors if empty). Use last first when you need the removed value. - -We retain **`n` = [Len](len(`list`))**. -1. `n` > 0 - Return *[Drop the last item of list (errors if empty)](> host_list_remove_at list=`list` index=`n` - 1)*. -2. * - Return *[Drop the last item of list (errors if empty)](> host_list_remove_at list=`list` index=0)*. - -## first - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | First item of list | - -Use `list` as the inputs for this operation. - -Effects: pure. - -First item of list. - -Return *[First item of list](> host_list_first list=`list`)*. - -## last - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Last item of list | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Last item of list. - -Return *[Last item of list](> host_list_last list=`list`)*. - -## slice - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| start | number | required | Inclusive zero-based slice start | -| end | any | None | Exclusive zero-based slice end; None selects through the end | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Zero-based half-open slice of list from start to end | - -Use `list`, `start`, `end`=None as the inputs for this operation. - -Effects: pure. - -Zero-based half-open slice of list from start to end. - -Return *[Zero-based half-open slice of list from start to end](> host_list_slice list=`list` start=`start` end=`end`)*. - -## contains - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| item | any | required | Element to insert, replace or compare | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether list contains item | - -Use `list`, `item` as the inputs for this operation. - -Effects: pure. - -Whether list contains item. - -Return *[Whether list contains item](> host_list_contains list=`list` item=`item`)*. - -## index_of - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| item | any | required | Element to insert, replace or compare | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Zero-based index of item in list, or None | - -Use `list`, `item` as the inputs for this operation. - -Effects: pure. - -Zero-based index of item in list, or None. - -Return *[Zero-based index of item in list, or None](> host_list_index_of list=`list` item=`item`)*. - -## reverse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Reverse list | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Reverse list. - -Return *[Reverse list](> host_list_reverse list=`list`)*. - -## sort - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Stable ascending sort: numbers, text, bool, None, then structured values by type/display | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Stable ascending sort: numbers, text, bool, None, then structured values by type/display. Numeric cross-type comparison preserves large integer order. - -Return *[Stable ascending sort: numbers, text, bool, None, then structured values by type/display](> host_list_sort list=`list`)*. - -## sort_by - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| key | text | required | Field name or key required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Sort a list of maps by field key | - -Use `list`, `key` as the inputs for this operation. - -Effects: pure. - -Sort a list of maps by field key. - -Return *[Sort a list of maps by field key](> host_list_sort_by list=`list` key=`key`)*. - -## unique - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Stable unique of list (first wins) | - -Use `list` as the inputs for this operation. - -Effects: pure. - -Stable unique of list (first wins). - -Return *[Stable unique of list (first wins)](> host_list_unique list=`list`)*. - -## chunk - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | -| size | number | required | Positive number of elements per chunk | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Split list into chunks of size | - -Use `list`, `size` as the inputs for this operation. - -Effects: pure. - -Split list into chunks of size. - -Return *[Split list into chunks of size](> host_list_chunk list=`list` size=`size`)*. - -## zip - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | First list of each pair | -| b | any | required | Second list of each pair | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Pair lists a and b until the shorter ends | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Pair lists a and b until the shorter ends. - -Return *[Pair lists a and b until the shorter ends](> host_list_zip a=`a` b=`b`)*. - -## flatten - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | required | Input list; updates return a new list | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | One-level flatten of list | - -Use `list` as the inputs for this operation. - -Effects: pure. - -One-level flatten of list. - -Return *[One-level flatten of list](> host_list_flatten list=`list`)*. - -## clear - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Empty list or empty map for value (by type) | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Empty list or empty map for value (by type). - -Return *[Empty list or empty map for value (by type)](> host_collection_clear value=`value`)*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | -| key | text | required | Field name or key required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Shallow get from map at key | - -Use `map`, `key` as the inputs for this operation. - -Effects: pure. - -Shallow get from map at key. Missing → None. Prefer access reads in author code. - -Return *[Shallow get from map at key](> host_map_get map=`map` key=`key`)*. - -## set - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | -| key | text | required | Field name or key required by this operation | -| value | any | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Shallow map update | - -Use `map`, `key`, `value` as the inputs for this operation. - -Effects: pure. - -Shallow map update. Prefer put for nested paths. - -Return *[Shallow map update](> host_map_set map=`map` key=`key` value=`value`)*. - -## delete - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | -| key | text | required | Field name or key required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Delete key from map | - -Use `map`, `key` as the inputs for this operation. - -Effects: pure. - -Delete key from map. - -Return *[Delete key from map](> host_map_delete map=`map` key=`key`)*. - -## has - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | -| key | text | required | Field name or key required by this operation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether map has key | - -Use `map`, `key` as the inputs for this operation. - -Effects: pure. - -Whether map has key. - -Return *[Whether map has key](> host_map_has map=`map` key=`key`)*. - -## keys - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Keys of map | - -Use `map` as the inputs for this operation. - -Effects: pure. - -Keys of map. - -Return *[Keys of map](> host_map_keys map=`map`)*. - -## values - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Values of map | - -Use `map` as the inputs for this operation. - -Effects: pure. - -Values of map. - -Return *[Values of map](> host_map_values map=`map`)*. - -## items - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Key/value rows from map | - -Use `map` as the inputs for this operation. - -Effects: pure. - -Key/value rows from map. - -Return *[Key/value rows from map](> host_map_items map=`map`)*. - -## merge - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Base record; None seeds an empty record | -| b | any | required | Record merged over a; later values win | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Merge maps a and b (right-hand keys win) | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Merge maps a and b (right-hand keys win). - -Return *[Merge maps a and b (right-hand keys win)](> host_map_merge a=`a` b=`b`)*. - -## size - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | required | Input string-keyed map | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Key count of map | - -Use `map` as the inputs for this operation. - -Effects: pure. - -Key count of map. - -Return *[Key count of map](> host_map_size map=`map`)*. - -## empty_list - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Empty list | - -Effects: pure. - -Empty list. - -Return *[Empty list](> host_list_concat a=None b=None)*. - -## empty_map - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Return a new empty map as a seed for immutable updates; this is not an empty list | - -Effects: pure. - -Empty map. - -Return a new empty map as a seed for immutable updates; this is not an empty list. - -Return *[Return a new empty map as a seed for immutable updates; this is not an empty list](> host_map_merge a=None b=None)*. - -## range - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| start | number | required | First numeric value of the sequence | -| end | number | required | Exclusive bound of the sequence | -| step | number | 1 | Nonzero range increment; sign must point toward the end | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Generate a half-open integer sequence; negative steps are allowed, zero is rejected, at most 1000000 items | - -Use `start`, `end`, `step`=1 as the inputs for this operation. - -Effects: pure. - -Generate a half-open integer sequence; negative steps are allowed, zero is rejected, at most 1000000 items. - -Return *[Generate a half-open integer sequence; negative steps are allowed, zero is rejected, at most 1000000 items](> host_table_range start=`start` end=`end` step=`step`)*. - -## enumerate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| start | number | 0 | Index value assigned to the first record; default is one | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Return index/value records without modifying the input; index starts at start | - -Use `list`, `start`=0 as the inputs for this operation. - -Effects: pure. - -Return index/value records without modifying the input; index starts at start. - -Return *[Return index/value records without modifying the input; index starts at start](> host_table_enumerate list=`list` start=`start`)*. - -## pluck - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| key | text | required | Field name or storage key to read, compare or update | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Extract one field from every record; a missing field is an error instead of silently becoming None | - -Use `list`, `key` as the inputs for this operation. - -Effects: pure. - -Extract one field from every record; a missing field is an error instead of silently becoming None. - -Return *[Extract one field from every record; a missing field is an error instead of silently becoming None](> host_table_pluck list=`list` key=`key`)*. - -## project - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| keys | list | required | Ordered field-name list | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Keep the requested fields, in keys order; every requested field must exist | - -Use `list`, `keys` as the inputs for this operation. - -Effects: pure. - -Keep the requested fields, in keys order; every requested field must exist. - -Return *[Keep the requested fields, in keys order; every requested field must exist](> host_table_project list=`list` keys=`keys`)*. - -## where - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| key | text | required | Field name or storage key to read, compare or update | -| value | any | required | Value to transform or store, without mutating the input | -| op | text | "eq" | Operation name understood by this helper | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Keep matching records | - -Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. - -Effects: pure. - -Keep matching records. Operators: eq/ne/gt/ge/lt/le/contains/in; these are fixed operations, never code to evaluate. - -Return *[Keep matching records](> host_table_where list=`list` key=`key` value=`value` op=`op`)*. - -## group_by - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| key | text | required | Field name or storage key to read, compare or update | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Return first-seen ordered key/count/rows records; group keys keep their original value types | - -Use `list`, `key` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/table.mq.md group_by 'list=[{"team":"a","n":3},{"team":"b","n":1},{"team":"a","n":2}]' 'key="team"' --effects none --json -``` - -Return first-seen ordered key/count/rows records; group keys keep their original value types. - -Return *[Return first-seen ordered key/count/rows records; group keys keep their original value types](> host_table_group_by list=`list` key=`key`)*. - -## unique_by - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| key | text | required | Field name or storage key to read, compare or update | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Keep the first record per field value; input order is preserved | - -Use `list`, `key` as the inputs for this operation. - -Effects: pure. - -Keep the first record per field value; input order is preserved. - -Return *[Keep the first record per field value; input order is preserved](> host_table_unique_by list=`list` key=`key`)*. - -## aggregate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| key | any | None | Field name or storage key to read, compare or update | -| op | text | "sum" | Operation name understood by this helper | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | Aggregate scalar values or one record field: sum/count/min/max/mean | - -Use `list`, `key`=None, `op`="sum" as the inputs for this operation. - -Effects: pure. - -Aggregate scalar values or one record field: sum/count/min/max/mean. Empty sum/count is zero; empty min/max/mean fails; integer sum checks overflow. - -Return *[Aggregate scalar values or one record field: sum/count/min/max/mean](> host_table_aggregate list=`list` key=`key` op=`op`)*. - -## sort_keys - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| keys | list | required | Ordered field-name list | -| descending | bool | False | Whether the multi-key sort is descending | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Stable lexicographic sort by fields in keys order; descending reverses the comparison, keeping equal-key order | - -Use `list`, `keys`, `descending`=False as the inputs for this operation. - -Effects: pure. - -Stable lexicographic sort by fields in keys order; descending reverses the comparison, keeping equal-key order. - -Return *[Stable lexicographic sort by fields in keys order; descending reverses the comparison, keeping equal-key order](> host_table_sort_keys list=`list` keys=`keys` descending=`descending`)*. - -## rename - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| fields | map | required | Structured field/value record attached to the log event | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Rename fields using an old-name/new-name map; duplicate output names fail | - -Use `list`, `fields` as the inputs for this operation. - -Effects: pure. - -Rename fields using an old-name/new-name map; duplicate output names fail. - -Return *[Rename fields using an old-name/new-name map; duplicate output names fail](> host_table_rename list=`list` fields=`fields`)*. - -## from_columns - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| columns | map | required | Column-name/list record; all columns must have equal length | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Convert a column map to row records | - -Use `columns` as the inputs for this operation. - -Effects: pure. - -Convert a column map to row records. Every column must be a list of equal length; scalar object fields are not inferred as columns. - -Return *[Convert a column map to row records](> host_table_from_columns columns=`columns`)*. - -## to_columns - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rows | list | required | List of row records, rather than an implicit column map | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Convert records with identical field sets into a column map; empty input yields an empty map | - -Use `rows` as the inputs for this operation. - -Effects: pure. - -Convert records with identical field sets into a column map; empty input yields an empty map. - -Return *[Convert records with identical field sets into a column map; empty input yields an empty map](> host_table_to_columns rows=`rows`)*. - -## join - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | list | required | First operand; its domain is described by this operation | -| b | list | required | Second operand; its domain is described by this operation | -| key | text | required | Field name or storage key to read, compare or update | -| right_key | text | required | Matching field in right-hand records | -| mode | text | "inner" | Join mode: inner or left | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Join records by field equality, preserving left and matching-right order | - -Use `a`, `b`, `key`, `right_key`, `mode`="inner" as the inputs for this operation. - -Effects: pure. - -Join records by field equality, preserving left and matching-right order. mode is inner/left; colliding right fields use right_ prefix; unresolved name collisions fail. - -Return *[Join records by field equality, preserving left and matching-right order](> host_table_join a=`a` b=`b` key=`key` right_key=`right_key` mode=`mode`)*. - -## cast - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rows | list | required | List of row records, rather than an implicit column map | -| schema | map | required | Field/type record using the standard contract type vocabulary | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Convert schema fields to text/int/number/bool/any; missing or invalid cells report row and field | - -Use `rows`, `schema` as the inputs for this operation. - -Effects: pure. - -Convert schema fields to text/int/number/bool/any; missing or invalid cells report row and field. Other fields survive. - -Return *[Convert schema fields to text/int/number/bool/any; missing or invalid cells report row and field](> host_table_cast rows=`rows` schema=`schema`)*. - -## union - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | list | required | First operand; its domain is described by this operation | -| b | list | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Stable set union; first occurrences win, using the same type-sensitive equality as unique | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Stable set union; first occurrences win, using the same type-sensitive equality as unique. - -Return *[Stable set union; first occurrences win, using the same type-sensitive equality as unique](> host_table_union a=`a` b=`b`)*. - -## intersection - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | list | required | First operand; its domain is described by this operation | -| b | list | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Stable set intersection; duplicates are removed | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Stable set intersection; duplicates are removed. - -Return *[Stable set intersection; duplicates are removed](> host_table_intersection a=`a` b=`b`)*. - -## difference - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | list | required | First operand; its domain is described by this operation | -| b | list | required | Second operand; its domain is described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Stable values in a but not b; duplicates are removed | - -Use `a`, `b` as the inputs for this operation. - -Effects: pure. - -Stable values in a but not b; duplicates are removed. - -Return *[Stable values in a but not b; duplicates are removed](> host_table_difference a=`a` b=`b`)*. - -## try_cast - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rows | list | required | List of row records, rather than an implicit column map | -| schema | map | required | Field/type record using the standard contract type vocabulary | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Recoverable cast; invalid fields return Result instead of aborting the caller | - -Use `rows`, `schema` as the inputs for this operation. - -Effects: pure. - -Recoverable cast; invalid fields return Result instead of aborting the caller. - -Return *[Recoverable cast; invalid fields return Result instead of aborting the caller](> host_table_try_cast rows=`rows` schema=`schema`)*. - -## validate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| rows | list | required | List of row records, rather than an implicit column map | -| schema | map | required | Field/type record using the standard contract type vocabulary | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Validate required fields using core gradual types, returning Result with error | - -Use `rows`, `schema` as the inputs for this operation. - -Effects: pure. - -Validate required fields using core gradual types, returning Result with error.details row/field diagnostics. int is the core number alias; use cast for strict integer conversion. - -Return *[Validate required fields using core gradual types, returning Result with error.details row/field diagnostics](> host_table_validate rows=`rows` schema=`schema`)*. - -## find - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Ordered row records to test without changing their order | -| key | text | required | Field name whose value is compared in each row | -| value | any | required | Comparison operand; in tests membership in this supplied collection | -| op | text | "eq" | Comparison: eq, ne, gt, ge, lt, le, contains or in; invalid operators fail | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | First matching row, or None when no row matches | - -Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. - -Effects: pure. - -Use the same comparison as where. Missing fields and invalid operators still produce a diagnostic; the input rows remain unchanged. - -We retain **`selected` = [Where](where(list=`list`, key=`key`, value=`value`, op=`op`))**. -Return *[First](first(list=`selected`))*. - -## any - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Ordered row records to test without changing their order | -| key | text | required | Field name whose value is compared in each row | -| value | any | required | Comparison operand; in tests membership in this supplied collection | -| op | text | "eq" | Comparison: eq, ne, gt, ge, lt, le, contains or in; invalid operators fail | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether at least one row matches; false on an empty list | - -Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. - -Effects: pure. - -Use the same comparison as where. Missing fields and invalid operators still produce a diagnostic; the input rows remain unchanged. - -We retain **`selected` = [Where](where(list=`list`, key=`key`, value=`value`, op=`op`))**. -We retain **`matched` = [Len](len(`selected`))**. -Return *matched > 0*. - -## all - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Ordered row records to test without changing their order | -| key | text | required | Field name whose value is compared in each row | -| value | any | required | Comparison operand; in tests membership in this supplied collection | -| op | text | "eq" | Comparison: eq, ne, gt, ge, lt, le, contains or in; invalid operators fail | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether every row matches; true on an empty list | - -Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. - -Effects: pure. - -Use the same comparison as where. Missing fields and invalid operators still produce a diagnostic; the input rows remain unchanged. - -We retain **`selected` = [Where](where(list=`list`, key=`key`, value=`value`, op=`op`))**. -We retain **`matched` = [Len](len(`selected`))**. -We retain **`total` = [Len](len(`list`))**. -Return *matched == total*. - -## summarize - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | list | required | Input list; immutable updates return a new list | -| key | text | required | Field name or storage key to read, compare or update | -| field | text | required | Numeric field to aggregate within each group | -| op | text | "sum" | Operation name understood by this helper | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | Group by key and aggregate one field in a batch, returning first-seen key/count/value records | - -Use `list`, `key`, `field`, `op`="sum" as the inputs for this operation. - -Effects: pure. - -Group by key and aggregate one field in a batch, returning first-seen key/count/value records. Uses aggregate semantics and avoids repeatedly copying a growing output list in author loops. - -Return *[Group by key and aggregate one field in a batch, returning first-seen key/count/value records](> host_table_summarize list=`list` key=`key` field=`field` op=`op`)*. - -## from_pairs - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| pairs | list | required | Ordered row records with text key and arbitrary value fields; extra fields are ignored | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | New record in first-key insertion order; later entries replace an existing key's value | - -Effects: pure. - -The input `pairs` makes a long named record readable as an @ table with key/value columns. -Use this when a horizontal record would become too wide to inspect, such as prompt sections or -configuration fragments. It uses the same ordinary row records and immutable map update as the -rest of this library; no JSON text or alternate schema language is parsed. An empty list returns -an empty record. Invalid keys are rejected by put, rather than silently creating a dummy column. - -We begin with **record = [Create a new record](empty_map())**. Each row contributes one explicit -field; repeated keys update that field while keeping the position of its first occurrence. - -- [Copy each named field into the new record](遍历 pairs 为 pair) - Read **key = [Read this row's field name](access(pair, "key"))** - and **value = [Read this row's field value](access(pair, "value"))**. - We retain **record = [Set this field without changing the input rows](put(in=`record`, at=`key`, value=`value`))**. - -After processing the ordered rows, return *record*. The original pairs remain available to the -caller; this function performs no filesystem, network or plugin operation. diff --git a/lib/text.mq.md b/lib/text.mq.md deleted file mode 100755 index f77a971..0000000 --- a/lib/text.mq.md +++ /dev/null @@ -1,235 +0,0 @@ ---- -markup: occlusion -title: lib/text -description: Text helpers (Mid M4). Literal replace — use lib/re for regex. ---- - -Small text helpers. Prefer these over hand-rolled splits; regex belongs in lib/re. - -Clean and combine Unicode text. - -Behavior and limits: Use re for patterns and bytes for arbitrary binary. split and join use exact separators; no implicit document parsing. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/text_ops.rs](../src/host/text_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## str_trim - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| s | text | required | Input text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Trim ends of string s | - -Use `s` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/text.mq.md str_trim 's=" readable text "' --effects none --json -``` - -Trim ends of string s. - -Return *[Trim](trim(`s`))*. - -## str_split - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| s | text | required | Input text | -| sep | text | required | Text separator used for splitting or joining | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Split string s on separator sep | - -Use `s`, `sep` as the inputs for this operation. - -Effects: pure. - -Split string s on separator sep. - -Return *[Split](split(value=`s`, sep=`sep`))*. - -## str_join - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | required | Input list or collection, as required by this operation | -| sep | text | required | Text separator used for splitting or joining | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Join list xs with separator sep | - -Use `xs`, `sep` as the inputs for this operation. - -Effects: pure. - -Join list xs with separator sep. - -Return *[Join](join(value=`xs`, sep=`sep`))*. - -## contains - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| sub | any | required | Substring to search for | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether text contains substring sub | - -Use `text`, `sub` as the inputs for this operation. - -Effects: pure. - -Whether text contains substring sub. - -Caller: [text.contains] text="hello" sub="ell" - -Return *[Whether text contains substring sub](> host_text_contains text=`text` sub=`sub`)*. - -## starts_with - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| prefix | text | required | Prefix added to the generated name or tested against text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether text starts with prefix | - -Use `text`, `prefix` as the inputs for this operation. - -Effects: pure. - -Whether text starts with prefix. - -Return *[Whether text starts with prefix](> host_text_starts_with text=`text` prefix=`prefix`)*. - -## ends_with - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| suffix | any | required | Text suffix to test | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether text ends with suffix | - -Use `text`, `suffix` as the inputs for this operation. - -Effects: pure. - -Whether text ends with suffix. - -Return *[Whether text ends with suffix](> host_text_ends_with text=`text` suffix=`suffix`)*. - -## replace - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| old | any | required | Exact substring to replace | -| new | any | required | Replacement text | -| count | any | None | Maximum replacement count; None uses the documented default | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Literal replace in text: replace old with new, optional count | - -Use `text`, `old`, `new`, `count`=None as the inputs for this operation. - -Effects: pure. - -Literal replace in text: replace old with new, optional count. - -Return *[Literal replace in text: replace old with new, optional count](> host_text_replace text=`text` old=`old` new=`new` count=`count`)*. - -## to_upper - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Uppercase text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Uppercase text. - -Return *[Uppercase text](> host_text_to_upper text=`text`)*. - -## to_lower - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Lowercase text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Lowercase text. - -Return *[Lowercase text](> host_text_to_lower text=`text`)*. - -## repeat - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| n | number | required | Number of repetitions | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Repeat text n times | - -Use `text`, `n` as the inputs for this operation. - -Effects: pure. - -Repeat text n times. - -Return *[Repeat text n times](> host_text_repeat text=`text` n=`n`)*. - -## pad - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| width | number | required | Target padded character width | -| fill | any | None | Single padding character | -| align | any | None | Padding alignment: left, right or center | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Pad text to width with fill and align (left / right / center) | - -Use `text`, `width`, `fill`=None, `align`=None as the inputs for this operation. - -Effects: pure. - -Pad text to width with fill and align (left / right / center). - -Return *[Pad text to width with fill and align (left / right / center)](> host_text_pad text=`text` width=`width` fill=`fill` align=`align`)*. diff --git a/lib/time.mq.md b/lib/time.mq.md deleted file mode 100755 index 5df4608..0000000 --- a/lib/time.mq.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -markup: occlusion -title: lib/time -description: English time wrappers ---- - -Unix time, format, parse, and sleep helpers. - -Format Unix time and control elapsed waits. - -Behavior and limits: now reads the clock; sleep controls execution and is clamped in capture. Calendar arithmetic and IANA rules live in datetime. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/time.rs](../src/host/time.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## now_unix - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Current Unix time in seconds | - -Effects: time.read. - -Current Unix time in seconds. - -Caller: [time.now_unix] - -Return *[Current Unix time in seconds](host_now_unix())*. - -## now_ms - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Current Unix time in milliseconds | - -Effects: time.read. - -Current Unix time in milliseconds. - -Return *[Current Unix time in milliseconds](host_now_ms())*. - -## format - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| unix | number | required | Unix timestamp in seconds | -| pattern | text | required | strftime date/time format string | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Format unix seconds with pattern | - -Use `unix`, `pattern` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/time.mq.md format unix=0 'pattern="%Y-%m-%d"' --effects none --json -``` - -Format unix seconds with pattern. - -Return *[Format unix seconds with pattern](> host_format_time unix=`unix` pattern=`pattern`)*. - -## sleep_ms - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| ms | any | required | Duration or delay in milliseconds | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Sleep for ms milliseconds | - -Use `ms` as the inputs for this operation. - -Effects: process.control. - -Sleep for ms milliseconds. - -Return *[Sleep for ms milliseconds](> host_sleep_ms ms=`ms`)*. - -## parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | -| pattern | text | required | strftime date/time format string | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | Parse text as time with pattern; returns unix seconds | - -Use `text`, `pattern` as the inputs for this operation. - -Effects: pure. - -Parse text as time with pattern; returns unix seconds. - -Return *[Parse text as time with pattern; returns unix seconds](> host_parse_time text=`text` pattern=`pattern`)*. diff --git a/lib/toml.mq.md b/lib/toml.mq.md deleted file mode 100755 index 9f7dcf1..0000000 --- a/lib/toml.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/toml -description: TOML parse/stringify with inline tables, multiline strings and arrays-of-tables. Dates become ISO text. ---- - -Read and write standard TOML configurations. Datetime scalars become ISO text; serialization does not preserve comments. - -Read and write standard TOML configuration data. - -Behavior and limits: Supports inline tables, multiline strings and arrays-of-tables. TOML dates become ISO text. Serialization rejects None and does not preserve original comments. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/toml_ops.rs](../src/host/toml_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Parse TOML text into maps/lists/scalars | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Parse TOML text into maps/lists/scalars. - -Caller: [toml.parse] text=`cfg` - -Return *[Parse TOML text into maps/lists/scalars](> host_toml_parse text=`text`)*. - -## stringify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | map | required | Value to transform or store, without mutating the input | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | Serialize a map as TOML, rejecting None and unsupported value kinds; does not preserve source comments | - -Use `value` as the inputs for this operation. - -Effects: pure. - -Serialize a map as TOML, rejecting None and unsupported value kinds; does not preserve source comments. - -Return *[Serialize a map as TOML, rejecting None and unsupported value kinds; does not preserve source comments](> host_toml_stringify value=`value`)*. - -## try_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text to read, transform or emit as described by this operation | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | Recoverable TOML parsing supports inline tables, multiline strings and arrays-of-tables; datetime scalars become ISO text | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/toml.mq.md try_parse 'text="name="Marqdo""' --effects none --json -``` - -Recoverable TOML parsing supports inline tables, multiline strings and arrays-of-tables; datetime scalars become ISO text. - -Return *[Recoverable TOML parsing supports inline tables, multiline strings and arrays-of-tables; datetime scalars become ISO text](> host_toml_try_parse text=`text`)*. diff --git a/lib/url.mq.md b/lib/url.mq.md deleted file mode 100755 index b4cac87..0000000 --- a/lib/url.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/url -description: Parse URLs and query strings (Mid2 M7). Segment encoding stays in net.url_encode. ---- - -Parse URLs and query strings. Segment encoding stays in net.url_encode. - -Parse addresses and repeated query parameters. - -Behavior and limits: Repeated query keys become lists; do not assume every map value is scalar. URL encoding is distinct from HTML escaping. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/url_ops.rs](../src/host/url_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Parse URL text into scheme, userinfo, host, port, path, query, fragment | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Parse URL text into scheme, userinfo, host, port, path, query, fragment. - -Caller: [url.parse] text=`u` - -Return *[Parse URL text into scheme, userinfo, host, port, path, query, fragment](> host_url_parse text=`text`)*. - -## query_parse - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | required | Text supplied by the caller | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Parse a=1&b=2 into a map; repeated keys become a list | - -Use `text` as the inputs for this operation. - -Effects: pure. - -Call this function directly: - -```sh -marqdo call lib/url.mq.md query_parse 'text="tag=a&tag=b&name=Marqdo"' --effects none --json -``` - -Parse a=1&b=2 into a map; repeated keys become a list. - -Return *[Parse a=1&b=2 into a map; repeated keys become a list](> host_url_query_parse text=`text`)*. - -## query_stringify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | map | required | Input string-keyed map | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Build a query string from map | - -Use `map` as the inputs for this operation. - -Effects: pure. - -Build a query string from map. - -Return *[Build a query string from map](> host_url_query_stringify map=`map`)*. diff --git a/lib/uuid.mq.md b/lib/uuid.mq.md deleted file mode 100755 index 3c508fa..0000000 --- a/lib/uuid.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: lib/uuid -description: UUID v4 (Mid M6). Cryptographic random via getrandom. ---- - -Random UUID helpers. Prefer this over rolling your own ids. - -Create UUID v4 identifiers. - -Behavior and limits: Identifiers use system entropy and are not reproducible constants. Do not treat UUID strings as authorization tokens. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Implementation: [src/host/uuid_ops.rs](../src/host/uuid_ops.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## v4 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | New UUID version 4 string | - -Effects: random.read. - -Call this function directly: - -```sh -marqdo call lib/uuid.mq.md v4 --effects random.read --json -``` - -New UUID version 4 string. - -Caller: [uuid.v4] - -Return *[New UUID version 4 string](host_uuid_v4())*. diff --git a/lib/writeback.mq.md b/lib/writeback.mq.md deleted file mode 100755 index 4bea4a8..0000000 --- a/lib/writeback.mq.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -markup: occlusion -title: lib/writeback -description: Persist run output in .mq.md (Jupyter-style writeback) ---- - -Persist run output in .mq.md (Jupyter-style writeback) - -Read and maintain persisted execution-output slots. - -Behavior and limits: record/get default to the current entry call site. Named slots isolate outputs. This API does not edit arbitrary document sections; use document for structural transforms. - -This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. - -Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. - -Implementation: [src/host/writeback.rs](../src/host/writeback.rs) - -For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. - -## record - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | required | Value to transform or store, without mutating the input | -| at_end | bool | False | Whether to append to the end of the target block | -| key | any | None | Field name or key required by this operation | -| line | any | None | Text line to add to the managed writeback block | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Write `value` into the entry file | - -Use `value`, `at_end`=False, `key`=None, `line`=None as the inputs for this operation. - -Effects: fs.write. - -Write `value` into the entry file. Image-like values (`.png` / `.svg` / … or `data:image/…`) become `![marqdo-out](…)` (or `![marqdo-out key](…)`); other values use ``. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask). - -Return *[Write value into the entry file](> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`)*. - -## get - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| at_end | bool | False | Whether to append to the end of the target block | -| key | any | None | Field name or key required by this operation | -| line | any | None | Text line to add to the managed writeback block | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Read persisted output for the current call site (adjacent unkeyed block), the unkeyed EOF block when `at_end=true`, or a named slot when `key=` is set | - -Use `at_end`=False, `key`=None, `line`=None as the inputs for this operation. - -Effects: fs.read. - -Read persisted output for the current call site (adjacent unkeyed block), the unkeyed EOF block when `at_end=true`, or a named slot when `key=` is set. - -Return *[Read persisted output for the current call site (adjacent unkeyed block), the unkeyed EOF block when at_end=true, or a named slot when key= is set](> host_writeback_get at_end=`at_end` key=`key` line=`line`)*. - -## clear - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| at_end | bool | False | Whether to append to the end of the target block | -| key | any | None | Field name or key required by this operation | -| line | any | None | Text line to add to the managed writeback block | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Remove the adjacent, EOF, or named output block | - -Use `at_end`=False, `key`=None, `line`=None as the inputs for this operation. - -Effects: fs.write. - -Remove the adjacent, EOF, or named output block. - -Return *[Remove the adjacent, EOF, or named output block](> host_writeback_clear at_end=`at_end` key=`key` line=`line`)*. - -## ensure - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| key | text | required | Field name or key required by this operation | -| placeholder | any | "pending" | Placeholder used when creating the managed block | -| line | any | None | Text line to add to the managed writeback block | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Create a named slot with `placeholder` if missing | - -Use `key`, `placeholder`="pending", `line`=None as the inputs for this operation. - -Effects: fs.write. - -Create a named slot with `placeholder` if missing. Never overwrites an existing slot body. - -Return *[Create a named slot with placeholder if missing](> host_writeback_ensure key=`key` placeholder=`placeholder` line=`line`)*. - -## list - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | List managed output slots from the current entry source without writing or reading another file | - -Effects: fs.read. - -List all output blocks in the entry file (includes `key` when named). - -List managed output slots from the current entry source without writing or reading another file. - -Return *[List managed output slots from the current entry source without writing or reading another file](host_writeback_list())*. - -## scan_path - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Path relative to the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | List writeback slots in any file (HTML comment and `![marqdo-out](…)` image forms; workbook inspection) | - -Use `path` as the inputs for this operation. - -Effects: fs.read. - -Call this function directly: - -```sh -marqdo call lib/writeback.mq.md scan_path 'path="lib/writeback.mq.md"' --effects fs.read --fs-root . --json -``` - -List writeback slots in any file (HTML comment and `![marqdo-out](…)` image forms; workbook inspection). - -Return *[List writeback slots in any file (HTML comment and !marqdo-out(…) image forms; workbook inspection)](> host_writeback_scan_path path=`path`)*. diff --git a/lib/命令行.mq.md b/lib/命令行.mq.md deleted file mode 100755 index 14b848b..0000000 --- a/lib/命令行.mq.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -markup: occlusion -title: lib/命令行 -description: 解析命令行参数(中层 M5)。--键 值 / --键=值 / --开关;位置参在 _。 ---- - -把进程参数解析成映射。开关与位置参(落在 _)。 - -把命令行词元转换为标志和位置参数。 - -能力与边界:参数值保持文本,裸标志变为布尔值,位置参数位于下划线键。省略输入时使用宿主参数;不提供完整的参数约束模式系统。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/cli.rs](../src/host/cli.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 参数 | any | None | 命令行 token 列表;None 读取当前宿主 argv | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 解析 --键 值 / --键=值 / --开关 | - -这里使用`参数`=None。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/命令行.mq.md 解析 '参数=["report","--count=3","--quiet"]' --effects none --json -``` - -解析 --键 值 / --键=值 / --开关。裸 --开关 若当布尔,后面不要紧跟非选项词(开关放最后,或写 --开关=true)。位置参进 _。省略参数时用进程 argv(系统.参数表)。 - -调用例:[命令行.解析] - -完成后返回*[解析 --键 值 / --键=值 / --开关](> host_cli_parse args=`参数`)*。 diff --git a/lib/哈希.mq.md b/lib/哈希.mq.md deleted file mode 100755 index 25a9a40..0000000 --- a/lib/哈希.mq.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -markup: occlusion -title: lib/哈希 -description: 摘要与 HMAC(中层 M3)。完整性 / 缓存键 — 非密码存储。 ---- - -摘要与 HMAC。用于完整性与缓存键 — 不是密码存储。 - -计算内容摘要与消息认证。 - -能力与边界:MD5 和 SHA1 用于兼容性校验,不用于保存密码。密码使用安全扩展;大文件和二进制摘要使用文件库的文件摘要。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/hash.rs](../src/host/hash.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 哈希256 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 内容的 SHA-256 十六进制摘要 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/哈希.mq.md 哈希256 '内容="abc"' --effects none --json -``` - -内容的 SHA-256 十六进制摘要。 - -调用例:[哈希.哈希256] 内容=`s` - -完成后返回*[内容的 SHA-256 十六进制摘要](> host_hash_sha256 text=`内容`)*。 - -## 哈希1 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 内容的 SHA-1 十六进制摘要 | - -这里使用`内容`。 - -调用效应:pure。 - -内容的 SHA-1 十六进制摘要。 - -完成后返回*[内容的 SHA-1 十六进制摘要](> host_hash_sha1 text=`内容`)*。 - -## md5 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 内容的 MD5 十六进制摘要 | - -这里使用`内容`。 - -调用效应:pure。 - -内容的 MD5 十六进制摘要。 - -完成后返回*[内容的 MD5 十六进制摘要](> host_hash_md5 text=`内容`)*。 - -## 密钥哈希256 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 密钥 | any | 必填 | 要读取、比较或更新的字段名或存储键 | -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 用密钥对内容做 HMAC-SHA256 | - -这里使用`密钥`、`内容`。 - -调用效应:pure。 - -用密钥对内容做 HMAC-SHA256。 - -完成后返回*[用密钥对内容做 HMAC-SHA256](> host_hash_hmac_sha256 key=`密钥` text=`内容`)*。 diff --git a/lib/地址.mq.md b/lib/地址.mq.md deleted file mode 100755 index 6f39124..0000000 --- a/lib/地址.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/地址 -description: 解析 URL 与查询串(中层 Mid2 M7)。单段编码仍用网络.网址编码。 ---- - -解析 URL 与查询串。单段编码仍用网络.网址编码。 - -解析地址与重复查询参数。 - -能力与边界:重复查询键返回列表,不应假设所有值都是标量。地址编码和 HTML 转义是不同操作。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/url_ops.rs](../src/host/url_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 把 URL 解析成 scheme / userinfo / host / port / path / query / fragment | - -这里使用`内容`。 - -调用效应:pure。 - -把 URL 解析成 scheme / userinfo / host / port / path / query / fragment。 - -调用例:[地址.解析] 内容=`u` - -完成后返回*[把 URL 解析成 scheme / userinfo / host / port / path / query / fragment](> host_url_parse text=`内容`)*。 - -## 查询解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 把 a=1&b=2 解析成映射;重复键变成列表 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/地址.mq.md 查询解析 '内容="tag=a&tag=b&name=Marqdo"' --effects none --json -``` - -把 a=1&b=2 解析成映射;重复键变成列表。 - -完成后返回*[把 a=1&b=2 解析成映射;重复键变成列表](> host_url_query_parse text=`内容`)*。 - -## 查询串化 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 表 | any | 必填 | 输入记录;操作说明允许时 None 可用作空记录种子 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 把映射编成查询串 | - -这里使用`表`。 - -调用效应:pure。 - -把映射编成查询串。 - -完成后返回*[把映射编成查询串](> host_url_query_stringify map=`表`)*。 diff --git a/lib/外联.mq.md b/lib/外联.mq.md deleted file mode 100755 index 3425bee..0000000 --- a/lib/外联.mq.md +++ /dev/null @@ -1,513 +0,0 @@ ---- -markup: occlusion -title: lib/外联 -description: 通过本机解释器运行绑定的代码围栏与内联源码 -import: - table: lib/table.mq.md ---- - -通过本机解释器运行绑定的代码围栏与内联源码。 - -向外部语言进程与会话明确传递数据。 - -能力与边界:语言已配置不代表解释器已安装。执行接口提供退出码、超时和输出限额,需要 process.exec;持久会话由创建者负责关闭,不透明句柄不能伪造或 JSON 序列化。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/foreign.rs](../src/host/foreign.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 设置命令 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node | -| 命令 | any | 必填 | 可执行命令或解释器覆盖配置 | -| 参数 | any | None | 传给命令或函数的实参列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 为语言绑定解释器命令;可选附加参数 | - -这里使用`语言`、`命令`、`参数`=None。 - -调用效应:pure。 - -为语言绑定解释器命令;可选附加参数。 - -完成后返回*[为语言绑定解释器命令;可选附加参数](> host_foreign_set_cmd lang=`语言` cmd=`命令` args=`参数`)*。 - -## 运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 代码 | any | 必填 | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | -| 标准输入 | any | None | 写入子进程标准输入的文本 | -| 环境 | any | None | 传给子进程的环境变量与值记录 | -| 工作目录 | any | None | 子进程工作目录 | -| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | -| 参数 | any | None | 传给命令或函数的实参列表 | -| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、 附加参数与输出上限 | - -这里使用`代码`、`标准输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`最大输出`=None。 - -调用效应:process.exec。 - -运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、 -附加参数与输出上限。返回 stdout 文本;非 0 退出即报错。 - -调用例:[外联.运行] 代码=`块` - -完成后返回*[运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、 附加参数与输出上限](> host_foreign_run code=`代码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`)*。 - -## 按语言运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node | -| 源码 | any | 必填 | 交给指定解释器执行的源文本 | -| 标准输入 | any | None | 写入子进程标准输入的文本 | -| 环境 | any | None | 传给子进程的环境变量与值记录 | -| 工作目录 | any | None | 子进程工作目录 | -| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | -| 参数 | any | None | 传给命令或函数的实参列表 | -| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 用语言运行源码文本;选项同“运行” | - -这里使用`语言`、`源码`、`标准输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`最大输出`=None。 - -调用效应:process.exec。 - -用语言运行源码文本;选项同“运行”。 - -完成后返回*[用语言运行源码文本;选项同“运行”](> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`)*。 - -## 执行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | -| 语言 | any | None | 已注册的解释器语言标识,例如 node | -| 源码 | any | None | 交给指定解释器执行的源文本 | -| 标准输入 | any | None | 写入子进程标准输入的文本 | -| 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 | -| 环境 | any | None | 传给子进程的环境变量与值记录 | -| 工作目录 | any | None | 子进程工作目录 | -| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | -| 参数 | any | None | 传给命令或函数的实参列表 | -| 输出 | any | "auto" | 结果解码方式:auto、text、json 或 lines | -| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | -| 命令 | any | None | 可执行命令或解释器覆盖配置 | -| 保留 | any | False | 是否保留生成的脚本以便检查 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错 | - -这里使用`代码`=None、`语言`=None、`源码`=None、`标准输入`=None、`输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`输出`="auto"、`最大输出`=None、`命令`=None、`保留`=False。 - -调用效应:process.exec。 - -运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错。 -字段:ok、code、stdout、stderr、ms、lang、cmd、timed_out、truncated、 -result、result_error、error、script、cached。 - -`输入` 会编码为 JSON 写入 stdin(与 `标准输入` 互斥)。`输出` 可取 -auto | text | json | lines。`命令` 仅本次覆盖解释器。 - -完成后返回*[运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错](> host_foreign_invoke code=`代码` lang=`语言` source=`源码` stdin=`标准输入` input=`输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` output=`输出` max_output=`最大输出` cmd=`命令` keep=`保留`)*。 - -## 探测 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 语言 | any | None | 已注册的解释器语言标识,例如 node | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 探测一个语言;省略语言时探测所有已知语言 | - -这里使用`语言`=None。 - -调用效应:process.exec。 - -探测一个语言;省略语言时探测所有已知语言。返回 -{lang, cmd, path, ok, version, error}(省略语言时是列表)。 - -完成后返回*[探测一个语言;省略语言时探测所有已知语言](> host_foreign_probe lang=`语言`)*。 - -## 注册 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node | -| 命令 | any | None | 可执行命令或解释器覆盖配置 | -| 参数 | any | None | 传给命令或函数的实参列表 | -| 模板 | any | None | 解释器启动模板 | -| 扩展名 | any | None | 临时脚本的文件扩展名 | -| 环境 | any | None | 传给子进程的环境变量与值记录 | -| 版本参数 | any | None | 查询解释器版本时使用的参数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 注册语言调用 | - -这里使用`语言`、`命令`=None、`参数`=None、`模板`=None、`扩展名`=None、`环境`=None、`版本参数`=None。 - -调用效应:pure。 - -注册语言调用。提供命令(+参数)或模板(占位符 -{file}、{dir}、{base}、{inline}、{lang}、{cwd});二者互斥。 - -完成后返回*[注册语言调用](> host_foreign_register lang=`语言` cmd=`命令` args=`参数` template=`模板` ext=`扩展名` env=`环境` version_args=`版本参数`)*。 - -## 注销 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 移除进程内注册;预设 / 配置 / 环境变量仍然生效 | - -这里使用`语言`。 - -调用效应:pure。 - -移除进程内注册;预设 / 配置 / 环境变量仍然生效。 - -完成后返回*[移除进程内注册;预设 / 配置 / 环境变量仍然生效](> host_foreign_unset lang=`语言`)*。 - -## 加载配置 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量 | - -这里使用`路径`=None。 - -调用效应:fs.read。 - -加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量。 - -完成后返回*[加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量](> host_foreign_load_config path=`路径`)*。 - -## 调用 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | -| 语言 | any | None | 已注册的解释器语言标识,例如 node | -| 源码 | any | None | 交给指定解释器执行的源文本 | -| 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 | -| 标准输入 | any | None | 写入子进程标准输入的文本 | -| 环境 | any | None | 传给子进程的环境变量与值记录 | -| 工作目录 | any | None | 子进程工作目录 | -| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | -| 参数 | any | None | 传给命令或函数的实参列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回值 (stdout 为空 → None) | - -这里使用`代码`=None、`语言`=None、`源码`=None、`输入`=None、`标准输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None。 - -调用效应:process.exec。 - -JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回值 -(stdout 为空 → None)。进程失败或 JSON 非法时报错。 - -完成后返回*[JSON 进 / JSON 出:把 输入 编码到 stdin,解析 stdout JSON 返回值 (stdout 为空 → None)](> host_foreign_call code=`代码` lang=`语言` source=`源码` input=`输入` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数`)*。 - -## 批量运行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务表 | any | 必填 | 按顺序排列的代码或语言与源码运行记录 | -| 并发 | any | 4 | 最大并发操作数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 并行运行一组代码值或 invoke 选项 map;按输入顺序返回记录 | - -这里使用`任务表`、`并发`=4。 - -调用效应:process.exec。 - -并行运行一组代码值或 invoke 选项 map;按输入顺序返回记录。单项失败不影响其它项。 - -完成后返回*[并行运行一组代码值或 invoke 选项 map;按输入顺序返回记录](> host_foreign_run_many runs=`任务表` concurrency=`并发`)*。 - -## 批量调用 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 输入表 | any | 必填 | 批量调用所用的输入值 | -| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | -| 语言 | any | None | 已注册的解释器语言标识,例如 node | -| 源码 | any | None | 交给指定解释器执行的源文本 | -| 命令 | any | None | 可执行命令或解释器覆盖配置 | -| 环境 | any | None | 传给子进程的环境变量与值记录 | -| 工作目录 | any | None | 子进程工作目录 | -| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | -| 参数 | any | None | 传给命令或函数的实参列表 | -| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | -| 并发 | any | 4 | 最大并发操作数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 把同一段代码并行作用到每个输入;按输入顺序返回解析后的 JSON 结果 | - -这里使用`输入表`、`代码`=None、`语言`=None、`源码`=None、`命令`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`最大输出`=None、`并发`=4。 - -调用效应:process.exec。 - -把同一段代码并行作用到每个输入;按输入顺序返回解析后的 JSON 结果。 -全部结束后若任一项失败,报错并指出下标。 - -完成后返回*[把同一段代码并行作用到每个输入;按输入顺序返回解析后的 JSON 结果](> host_foreign_call_many inputs=`输入表` code=`代码` lang=`语言` source=`源码` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出` concurrency=`并发`)*。 - -## 会话 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内核表 | any | None | 声明内核名称、语言及可选运行设置的普通表格 | -| 单元表 | any | None | 把文档中绑定的代码单元路由到明确内核 | -| 值表 | any | None | 内核、变量名与原生值组成的行记录 | -| 输入表 | any | None | 可选的逐单元输入值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 普通视图计划,含 kind/kernels/cells/values/inputs 五个字段 | - -View 约定把声明计划绑定到入口中的 `会话`,以区分普通记录和低层会话句柄。 -普通 `## main` 函数可同时被 call 调用和 View 索引;完整声明可参照原生报表示例。 - -这里使用`内核表`=None、`单元表`=None、`值表`=None、`输入表`=None,声明后续 View 使用的普通数据。返回记录的 kind 是 foreign-session,另外四个字段保留传入规格。这个纯函数不会启动解释器、创建活内核或读取另一个文件;实际执行由 View 消费计划与绑定代码围栏时发生。 - -内核行显式指定语言。推荐工作流先用 Marqdo 固有库完成计算,再只把真正缺失的本地化展示交给 Node Intl。值表把 JSON 安全的数据拷贝送入命名变量,同一内核中的单元共享状态,不同内核保持隔离。缺失或错误的运行规格仍由实际视图会话给出诊断,不能被一份声明记录证明为已执行成功。 - -返回的是可以被 marqdo call 序列化的计划。会话开启得到的活资源则需要在同一个可调用流程内完成借用和关闭,不能根据字符串标识重建句柄。原生报告例程中的 format_summary 展示了两次持久求值、真实错误出口和关闭责任。 - -`计划` = - -| kind | kernels | cells | values | inputs | -|---|---|---|---|---| -| "foreign-session" | `内核表` | `单元表` | `值表` | `输入表` | - -明确这些视图输入后,我们返回*计划*。 - -## 会话开启 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 语言 | any | 必填 | 已注册的解释器语言标识,例如 node | -| 命令 | any | None | 可执行命令或解释器覆盖配置 | -| 环境 | any | None | 传给子进程的环境变量与值记录 | -| 工作目录 | any | None | 子进程工作目录 | -| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 启动持久的 Python / Node 内核,返回不能跨 JSON 重建的不透明句柄 | - -这里使用`语言`、`命令`=None、`环境`=None、`工作目录`=None、`超时`=None。 - -调用效应:process.exec。 - -启动持久的 Python / Node 内核,返回不能跨 JSON 重建的不透明句柄。`超时` 是每次求值的默认超时。 - -完成后返回*[启动持久的 Python / Node 内核,返回不能跨 JSON 重建的不透明句柄](> host_foreign_session_open lang=`语言` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时`)*。 - -## 会话求值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 | -| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | -| 源码 | any | None | 交给指定解释器执行的源文本 | -| 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 | -| 标准输入 | any | None | 写入子进程标准输入的文本 | -| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 求值状态记录,含 ok/code/result/stdout/stderr/alive/timed_out/ms | - -这里使用`标识`、`代码`=None、`源码`=None、`输入`=None、`标准输入`=None、`超时`=None。 - -调用效应:process.exec。 - -求值状态记录,含 ok/code/result/stdout/stderr/alive/timed_out/ms。 -`输入` 会编码为 JSON 交给内核。 - -完成后返回*[求值状态记录,含 ok/code/result/stdout/stderr/alive/timed_out/ms](> host_foreign_session_eval id=`标识` code=`代码` source=`源码` input=`输入` stdin=`标准输入` timeout=`超时`)*。 - -## 会话设值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 | -| 名称 | any | 必填 | 要解析、注册或查找的名称 | -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 把一个 Marqdo 值写入内核变量(JSON 拷贝) | - -这里使用`标识`、`名称`、`值`。 - -调用效应:process.exec。 - -把一个 Marqdo 值写入内核变量(JSON 拷贝)。 - -完成后返回*[把一个 Marqdo 值写入内核变量(JSON 拷贝)](> host_foreign_session_set id=`标识` name=`名称` value=`值`)*。 - -## 会话取值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 | -| 名称 | any | 必填 | 要解析、注册或查找的名称 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 把一个内核变量读成 Marqdo 值 | - -这里使用`标识`、`名称`。 - -调用效应:process.exec。 - -把一个内核变量读成 Marqdo 值。 - -完成后返回*[把一个内核变量读成 Marqdo 值](> host_foreign_session_get id=`标识` name=`名称`)*。 - -## 会话中断 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 中断持久内核当前求值;worker 支持时,会话仍可用于下一次求值 | - -这里使用`标识`。 - -调用效应:process.exec。 - -中断持久内核当前求值;worker 支持时,会话仍可用于下一次求值。 - -完成后返回*[中断持久内核当前求值;worker 支持时,会话仍可用于下一次求值](> host_foreign_session_interrupt id=`标识`)*。 - -## 会话变量 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 列出内核变量名 | - -这里使用`标识`。 - -调用效应:process.exec。 - -列出内核变量名。 - -完成后返回*[列出内核变量名](> host_foreign_session_names id=`标识`)*。 - -## 会话关闭 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 标识 | any | 必填 | 会话开启返回并保留在本进程内的原始不透明句柄 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 终止并移除会话;返回是否存在 | - -这里使用`标识`。 - -调用效应:process.exec。 - -终止并移除会话;返回是否存在。 - -完成后返回*[终止并移除会话;返回是否存在](> host_foreign_session_close id=`标识`)*。 - -## 会话表 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 列出活动会话的 id/lang/cmd/evals/alive/started_ms | - -调用效应:process.exec。 - -列出活动会话的 id/lang/cmd/evals/alive/started_ms。 - -完成后返回*[列出活动会话的 id/lang/cmd/evals/alive/started_ms](host_foreign_session_list())*。 - -## 语言表 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 列出已配置的外联语言 | - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/外联.mq.md 语言表 --effects none --json -``` - -列出已配置的外联语言。 - -返回当前外联注册表里的语言配置,不会启动解释器;是否安装可执行程序应另用探测接口确认。 - -完成后返回*[列出已配置的外联语言](host_foreign_langs())*。 - -## 观测日志 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 返回本次文档执行中已接纳的 eval/get/decode 观测记录,包含 index、channel、value;开启、赋值和关闭不新增观测。 | - -调用效应:pure。 - -返回本次文档执行中已接纳的 eval/get/decode 观测记录,包含 index、channel、value;开启、赋值和关闭不新增观测。 - -完成后返回*[返回本次文档执行中已接纳的 eval/get/decode 观测记录,包含 index、channel、value;开启、赋值和关闭不新增观测](> host_oracle_journal )*。 - -## 重放检查 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 预期 | list | 必填 | 重放比较所用的预期观测记录 | -| 实际 | list | 必填 | 重放比较所用的实际观测记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 不执行外部代码地比较两份观测日志;返回是否一致、最早差异位置和对应记录。 | - -这里使用`预期`、`实际`。 - -调用效应:pure。 - -不执行外部代码地比较两份观测日志;返回是否一致、最早差异位置和对应记录。 - -完成后返回*[不执行外部代码地比较两份观测日志;返回是否一致、最早差异位置和对应记录](> host_oracle_replay_check expected=`预期` observed=`实际`)*。 diff --git a/lib/子任务.mq.md b/lib/子任务.mq.md deleted file mode 100755 index 69bb190..0000000 --- a/lib/子任务.mq.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -markup: occlusion -title: lib/子任务 -description: 并发子任务 — 文件、函数或外联代码 ---- - -并发子任务:文件、函数或外联代码。 - -以明确所有权管理并发任务。 - -能力与边界:文件批处理继承父权限与根目录。每项 Result.ok 表示等待协议完成,子进程业务成败还须检查 value.code。限时等待默认保留句柄,取消需要明确选择。进程可以终止并回收;函数线程只能逻辑取消。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 - -实现入口:[src/host/subtask.rs](../src/host/subtask.rs)、[src/host/task_ops.rs](../src/host/task_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 启动 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 授权根目录内的文件路径 | -| 函数 | any | None | 调用方提供的函数 | -| 参数 | any | None | 调用方提供的参数 | -| 代码 | any | None | 调用方提供的代码 | -| 语言 | any | None | 调用方提供的语言 | -| 源码 | any | None | 本次检查或试跑的源码文本 | -| 输入 | any | None | 调用方提供的输入 | -| 静默 | any | True | 调用方提供的静默 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 启动子任务 | - -这里使用`路径`=None、`函数`=None、`参数`=None、`代码`=None、`语言`=None、`源码`=None、`输入`=None、`静默`=True。 - -调用效应:process.exec。 - -启动子任务。文件子任务默认静默(静默=真:管道捕获)。静默=假 时继承父终端。文件等待返回 {code, value},静默捕获时另含截断的 stdout/stderr;value 为子 main 返回值。 - -调用例:[子任务.启动] 路径="child.mq.md" - -完成后返回*[启动子任务](> host_subtask_spawn path=`路径` fn=`函数` args=`参数` code=`代码` lang=`语言` source=`源码` stdin=`输入` quiet=`静默`)*。 - -## 探测 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | 对应创建或启动操作返回的标识 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 非阻塞查看子任务 id 状态 | - -这里使用`id`。 - -调用效应:process.exec。 - -非阻塞查看子任务 id 状态。 - -完成后返回*[非阻塞查看子任务 id 状态](> host_subtask_poll id=`id`)*。 - -## 等待 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | 对应创建或启动操作返回的标识 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 阻塞直到子任务 id 结束 | - -这里使用`id`。 - -调用效应:process.exec。 - -阻塞直到子任务 id 结束。 - -完成后返回*[阻塞直到子任务 id 结束](> host_subtask_join id=`id`)*。 - -## 终止 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | 必填 | 对应创建或启动操作返回的标识 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 终止子任务 id | - -这里使用`id`。 - -调用效应:process.exec。 - -终止子任务 id。 - -完成后返回*[终止子任务 id](> host_subtask_kill id=`id`)*。 - -## 等待全部 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 等待全部已启动子任务结束 | - -调用效应:process.exec。 - -等待全部已启动子任务结束。 - -完成后返回*[等待全部已启动子任务结束](host_subtask_wait_all())*。 - -## 限时等待 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 编号 | number | 必填 | 对应创建或启动操作返回的标识 | -| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | -| 取消 | bool | False | 超时后是否同时取消尚未结束的任务 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 限时等待并返回结果记录;默认超时保留句柄。cancel=True 会终止并回收进程;函数线程只进行逻辑取消。 | - -这里使用`编号`、`超时毫秒`=30000、`取消`=False。 - -调用效应:process.exec。 - -限时等待并返回结果记录;默认超时保留句柄。cancel=True 会终止并回收进程;函数线程只进行逻辑取消。 - -完成后返回*[限时等待并返回结果记录;默认超时保留句柄](> host_subtask_wait_timeout id=`编号` timeout_ms=`超时毫秒` cancel=`取消`)*。 - -## 全部取消 - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 取消所有子任务并回收子进程,返回数量;函数线程只能逻辑取消。 | - -调用效应:process.exec。 - -取消所有子任务并回收子进程,返回数量;函数线程只能逻辑取消。 - -完成后返回*[取消所有子任务并回收子进程,返回数量;函数线程只能逻辑取消](> host_subtask_cancel_all )*。 - -## 批量执行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 任务 | list | 必填 | 有序文件任务记录,包含 path 及可选 args | -| 并发上限 | number | 4 | 同时运行的文件任务上限,范围 1 到 64 | -| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按并发上限执行 path/args 文件任务,结果按输入排序,每项是结果记录。超时终止回收对应进程;最多一万任务、六十四并发,继承父权限和文件根目录。 | - -这里使用`任务`、`并发上限`=4、`超时毫秒`=30000。 - -调用效应:process.exec。 - -直接调用此函数: - -```sh -marqdo call lib/子任务.mq.md 批量执行 '任务=[{"path":"examples/stdlib-handbook/worker.mq.md"}]' '并发上限=2' --effects process.exec --fs-root . --json -``` - -按并发上限执行 path/args 文件任务,结果按输入排序,每项是结果记录。超时终止回收对应进程;最多一万任务、六十四并发,继承父权限和文件根目录。 - -完成后返回*[按并发上限执行 path/args 文件任务,结果按输入排序,每项是结果记录](> host_subtask_run_many tasks=`任务` limit=`并发上限` timeout_ms=`超时毫秒`)*。 diff --git a/lib/字节.mq.md b/lib/字节.mq.md deleted file mode 100755 index d17fa23..0000000 --- a/lib/字节.mq.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -markup: occlusion -title: 字节 ---- - -字节是 `_type: bytes` 与 `base64` 字段组成的普通记录,可跨 CLI、JSON、插件和会话保存;不新增语言类型。 - -通过普通可移植记录传递任意二进制数据。 - -能力与边界:字节记录包含 _type=bytes 和标准 Base64。字节偏移从零起;UTF-8 解码明确且严格。读块不会留下跨会话文件句柄。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/encoding.rs](../src/host/encoding.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 从文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 把文本编码为 UTF-8 字节。 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/字节.mq.md 从文本 '内容="Marqdo"' --effects none --json -``` - -把文本编码为 UTF-8 字节。 - -完成后返回*[把文本编码为 UTF-8 字节](> host_bytes_from_text text=`内容`)*。 - -## 从编码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 把 Base64 解码为任意字节,不假设 UTF-8。 | - -这里使用`内容`。 - -调用效应:pure。 - -把 Base64 解码为任意字节,不假设 UTF-8。 - -完成后返回*[把 Base64 解码为任意字节,不假设 UTF-8](> host_bytes_from_base64 text=`内容`)*。 - -## 转文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 严格解码 UTF-8;无效字节序列失败。 | - -这里使用`数据`。 - -调用效应:pure。 - -严格解码 UTF-8;无效字节序列失败。 - -完成后返回*[严格解码 UTF-8;无效字节序列失败](> host_bytes_to_text data=`数据`)*。 - -## 转编码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 返回带填充的标准 Base64。 | - -这里使用`数据`。 - -调用效应:pure。 - -返回带填充的标准 Base64。 - -完成后返回*[返回带填充的标准 Base64](> host_bytes_to_base64 data=`数据`)*。 - -## 长度 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 计算字节数,不是字符数。 | - -这里使用`数据`。 - -调用效应:pure。 - -计算字节数,不是字符数。 - -完成后返回*[计算字节数,不是字符数](> host_bytes_len data=`数据`)*。 - -## 切片 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | -| 起 | number | 必填 | 切片起点,从零开始且包含端点 | -| 止 | number | 必填 | 切片终点,从零开始且不包含端点;None 表示到末尾 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 返回从零起、左闭右开的字节切片;端点截到长度。 | - -这里使用`数据`、`起`、`止`。 - -调用效应:pure。 - -返回从零起、左闭右开的字节切片;端点截到长度。 - -完成后返回*[返回从零起、左闭右开的字节切片;端点截到长度](> host_bytes_slice data=`数据` start=`起` end=`止`)*。 diff --git a/lib/归档.mq.md b/lib/归档.mq.md deleted file mode 100755 index 276a871..0000000 --- a/lib/归档.mq.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -markup: occlusion ---- - -可选 ZIP 任务;原生默认构建支持,精简与浏览器构建不支持。返回统一结果记录。 - -归档是可选原生能力。本文件的打包与解包就是生产接口; -两者需要 fs.write,返回统一结果记录,目标必须不存在。解包先预检路径、 -重复条目、符号链接与总展开字节上限;失败只清理本次新建的目标目录。 -不复制权限、符号链接和空目录;精简或浏览器构建明确返回不支持。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 - -实现入口:[src/host/archive.rs](../src/host/archive.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 打包 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | -| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | -| 字节上限 | number | 1073741824 | 读取或展开的字节上限;超限则失败 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 成功结果的 value 是已归档普通文件数;失败时包含结构化错误 | - -这里使用`来源`、`目标`、`字节上限`=1073741824。 - -调用效应:fs.write。 - -示例先准备可丢弃的目录 MQ_WORK,其中 input 子目录放待归档普通文件;目标 bundle.zip 和 output 必须不存在。解包后自行保留产物或清理目录。 - -```sh -marqdo call lib/归档.mq.md 打包 '来源="input"' '目标="bundle.zip"' --fs-root "$MQ_WORK" --effects fs.write --json -marqdo call lib/归档.mq.md 解包 '来源="bundle.zip"' '目标="output"' --fs-root "$MQ_WORK" --effects fs.write --json -``` - -目标必须不存在;限制总展开字节数和十万条目,拒绝符号链接和越界路径。打包只收集普通文件;解包失败清理新建目标目录。 - -完成后返回*[把普通文件打包为 ZIP,拒绝覆盖已有目标](> host_zip_pack src=`来源` dest=`目标` max_bytes=`字节上限`)*。 - -## 解包 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | -| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | -| 字节上限 | number | 1073741824 | 读取或展开的字节上限;超限则失败 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 成功结果的 value 是解包条目数;失败时包含结构化错误 | - -这里使用`来源`、`目标`、`字节上限`=1073741824。 - -调用效应:fs.write。 - -目标必须不存在;限制总展开字节数和十万条目,拒绝符号链接和越界路径。打包只收集普通文件;解包失败清理新建目标目录。 - -完成后返回*[校验 ZIP 条目后解包,拒绝越界路径及已有目标](> host_zip_unpack src=`来源` dest=`目标` max_bytes=`字节上限`)*。 diff --git a/lib/插件.mq.md b/lib/插件.mq.md deleted file mode 100755 index 50f70da..0000000 --- a/lib/插件.mq.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -markup: occlusion -title: lib/插件 -description: 加载可选原生 ABI 插件(.dll / .so / .dylib) ---- - -加载可选原生 ABI 插件(.dll / .so / .dylib)。 - -定位并加载原生能力。 - -能力与边界:空列表表示本进程尚未加载插件。插件发现与加载需要 plugin.call;普通使用先读对应领域扩展的入口。原生插件不支持浏览器构建。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/plugin.rs](../src/host/plugin.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 加载 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 从路径加载原生插件 | - -这里使用`路径`。 - -调用效应:plugin.call。 - -从路径加载原生插件。 - -调用例:[插件.加载] 路径=`so` - -完成后返回*[从路径加载原生插件](> host_plugin_load path=`路径`)*。 - -## 卸载 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 卸载当前原生插件 | - -调用效应:plugin.call。 - -卸载当前原生插件。 - -完成后返回*[卸载当前原生插件](host_plugin_unload())*。 - -## 列出 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 列出已加载的原生插件 | - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/插件.mq.md 列出 --effects none --json -``` - -列出已加载的原生插件。 - -返回当前宿主进程已加载插件的名称列表;本函数不会加载插件,新进程的列表可能为空。 - -完成后返回*[列出已加载的原生插件](host_plugin_list())*。 - -## 原生路径 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | any | 必填 | 已安装拓展库标识,例如 agent | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 解析已安装或本地原生插件路径(如 agent) | - -这里使用`名`。 - -调用效应:plugin.call。 - -解析已安装或本地原生插件路径(如 agent)。 - -完成后返回*[解析已安装或本地原生插件路径(如 agent)](> host_ext_native_path name=`名`)*。 diff --git a/lib/数学.mq.md b/lib/数学.mq.md deleted file mode 100755 index 8e590f5..0000000 --- a/lib/数学.mq.md +++ /dev/null @@ -1,685 +0,0 @@ ---- -markup: occlusion -title: lib/数学 -description: 高中数学 — 数值、随机、公式、作图 ---- - -高中数学 — 数值、随机、公式、作图 - -计算数字、符号表达式和绘图。 - -能力与边界:number 契约包括符号公式;三角函数使用弧度。随机数需要 random.read,绘图具有输出效应。矩阵和量子计算保留在扩展库。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/math.rs](../src/host/math.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 圆周率 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 返回数学常数圆周率 | - -调用效应:pure。 - -返回数学常数圆周率。 - -完成后返回*[返回数学常数圆周率](host_pi())*。 - -## 自然底数 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 返回自然常数 e | - -调用效应:pure。 - -返回自然常数 e。 - -完成后返回*[返回自然常数 e](host_e())*。 - -## 数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 把数字或数字文本转换为数值 | - -这里使用`value`。 - -调用效应:pure。 - -把数字或数字文本转换为数值。 - -完成后返回*[把数字或数字文本转换为数值](> host_num value=`value`)*。 - -## 加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 将两个数字或符号表达式相加 | - -这里使用`a`、`b`。 - -调用效应:pure。 - -将两个数字或符号表达式相加。 - -完成后返回*[将两个数字或符号表达式相加](> host_math_add a=`a` b=`b`)*。 - -## 减 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 从 a 减去 b | - -这里使用`a`、`b`。 - -调用效应:pure。 - -从 a 减去 b。 - -完成后返回*[从 a 减去 b](> host_math_sub a=`a` b=`b`)*。 - -## 乘 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算 a 与 b 的乘积 | - -这里使用`a`、`b`。 - -调用效应:pure。 - -计算 a 与 b 的乘积。 - -完成后返回*[计算 a 与 b 的乘积](> host_math_mul a=`a` b=`b`)*。 - -## 除 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算 a 除以 b;除数为零时报错 | - -这里使用`a`、`b`。 - -调用效应:pure。 - -计算 a 除以 b;除数为零时报错。 - -完成后返回*[计算 a 除以 b;除数为零时报错](> host_math_div a=`a` b=`b`)*。 - -## 幂 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算 a 的 b 次幂 | - -这里使用`a`、`b`。 - -调用效应:pure。 - -计算 a 的 b 次幂。 - -完成后返回*[计算 a 的 b 次幂](> host_math_pow a=`a` b=`b`)*。 - -## 负 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 对数字或符号值取负 | - -这里使用`value`。 - -调用效应:pure。 - -对数字或符号值取负。 - -完成后返回*[对数字或符号值取负](> host_math_neg value=`value`)*。 - -## 正弦 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算正弦;数值角度使用弧度 | - -这里使用`value`。 - -调用效应:pure。 - -计算正弦;数值角度使用弧度。 - -完成后返回*[计算正弦;数值角度使用弧度](> host_math_sin value=`value`)*。 - -## 余弦 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算余弦;数值角度使用弧度 | - -这里使用`value`。 - -调用效应:pure。 - -计算余弦;数值角度使用弧度。 - -完成后返回*[计算余弦;数值角度使用弧度](> host_math_cos value=`value`)*。 - -## 正切 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算正切;数值角度使用弧度 | - -这里使用`value`。 - -调用效应:pure。 - -计算正切;数值角度使用弧度。 - -完成后返回*[计算正切;数值角度使用弧度](> host_math_tan value=`value`)*。 - -## 反正弦 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算反正弦,结果为弧度 | - -这里使用`value`。 - -调用效应:pure。 - -计算反正弦,结果为弧度。 - -完成后返回*[计算反正弦,结果为弧度](> host_math_asin value=`value`)*。 - -## 反余弦 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算反余弦,结果为弧度 | - -这里使用`value`。 - -调用效应:pure。 - -计算反余弦,结果为弧度。 - -完成后返回*[计算反余弦,结果为弧度](> host_math_acos value=`value`)*。 - -## 反正切 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算反正切,结果为弧度 | - -这里使用`value`。 - -调用效应:pure。 - -计算反正切,结果为弧度。 - -完成后返回*[计算反正切,结果为弧度](> host_math_atan value=`value`)*。 - -## 平方根 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算 value 的平方根 | - -这里使用`value`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/数学.mq.md 平方根 value=9 --effects none --json -``` - -计算 value 的平方根。 - -完成后返回*[计算 value 的平方根](> host_math_sqrt value=`value`)*。 - -## 绝对值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 返回绝对值 | - -这里使用`value`。 - -调用效应:pure。 - -返回绝对值。 - -完成后返回*[返回绝对值](> host_math_abs value=`value`)*。 - -## 对数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算自然对数 | - -这里使用`value`。 - -调用效应:pure。 - -计算自然对数。 - -完成后返回*[计算自然对数](> host_math_ln value=`value`)*。 - -## 指数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 计算自然指数函数 | - -这里使用`value`。 - -调用效应:pure。 - -计算自然指数函数。 - -完成后返回*[计算自然指数函数](> host_math_exp value=`value`)*。 - -## 向下取整 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 向负无穷取整 | - -这里使用`value`。 - -调用效应:pure。 - -向负无穷取整。 - -完成后返回*[向负无穷取整](> host_math_floor value=`value`)*。 - -## 向上取整 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 向正无穷取整 | - -这里使用`value`。 - -调用效应:pure。 - -向正无穷取整。 - -完成后返回*[向正无穷取整](> host_math_ceil value=`value`)*。 - -## 最小 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 返回较小的操作数 | - -这里使用`a`、`b`。 - -调用效应:pure。 - -返回较小的操作数。 - -完成后返回*[返回较小的操作数](> host_math_min a=`a` b=`b`)*。 - -## 最大 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 返回较大的操作数 | - -这里使用`a`、`b`。 - -调用效应:pure。 - -返回较大的操作数。 - -完成后返回*[返回较大的操作数](> host_math_max a=`a` b=`b`)*。 - -## 随机 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 返回伪随机数;可用种子控制复现 | - -调用效应:random.read。 - -返回伪随机数;可用种子控制复现。 - -完成后返回*[返回伪随机数;可用种子控制复现](host_random())*。 - -## 随机整数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| min | any | 必填 | 下界,或搜索与绘图区间的起点 | -| max | any | 必填 | 上界,或搜索与绘图区间的终点 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 在约定区间内返回伪随机整数 | - -这里使用`min`、`max`。 - -调用效应:random.read。 - -在约定区间内返回伪随机整数。 - -完成后返回*[在约定区间内返回伪随机整数](> host_random_int min=`min` max=`max`)*。 - -## 设种子 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 设置本次运行的伪随机种子;不用于机密值 | - -这里使用`value`。 - -调用效应:pure。 - -设置本次运行的伪随机种子;不用于机密值。 - -完成后返回*[设置本次运行的伪随机种子;不用于机密值](> host_seed value=`value`)*。 - -## 公式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| text | text | 必填 | 调用方提供的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 把表达式文本解析为符号公式,供后续代数运算或求值使用;语法无效时返回诊断 | - -这里使用`text`。 - -调用效应:pure。 - -把表达式文本解析为符号公式,供后续代数运算或求值使用;语法无效时返回诊断。 - -完成后返回*[把表达式文本解析为符号公式,供后续代数运算或求值使用;语法无效时返回诊断](> host_formula value=`text`)*。 - -## 化简 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 返回化简后的公式并保留输入;这是符号代数运算,不是数值求值 | - -这里使用`formula`。 - -调用效应:pure。 - -返回化简后的公式并保留输入;这是符号代数运算,不是数值求值。 - -完成后返回*[返回化简后的公式并保留输入;这是符号代数运算,不是数值求值](> host_simplify value=`formula`)*。 - -## 展开 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 展开代数乘积与幂,返回新的符号公式 | - -这里使用`formula`。 - -调用效应:pure。 - -展开代数乘积与幂,返回新的符号公式。 - -完成后返回*[展开代数乘积与幂,返回新的符号公式](> host_expand value=`formula`)*。 - -## 求导 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | -| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 对指定符号求导并返回符号导函数 | - -这里使用`formula`、`var`。 - -调用效应:pure。 - -对指定符号求导并返回符号导函数。 - -完成后返回*[对指定符号求导并返回符号导函数](> host_diff formula=`formula` var=`var`)*。 - -## 代入 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | -| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 用指定值替换公式中的符号;完全化简时返回数字,否则保留公式 | - -这里使用`formula`、`var`、`value`。 - -调用效应:pure。 - -用指定值替换公式中的符号;完全化简时返回数字,否则保留公式。 - -完成后返回*[用指定值替换公式中的符号;完全化简时返回数字,否则保留公式](> host_subs formula=`formula` var=`var` value=`value`)*。 - -## 求值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | -| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 在一个变量取指定数值时计算公式;仍有未绑定符号时返回诊断 | - -这里使用`formula`、`var`、`value`。 - -调用效应:pure。 - -在一个变量取指定数值时计算公式;仍有未绑定符号时返回诊断。 - -完成后返回*[在一个变量取指定数值时计算公式;仍有未绑定符号时返回诊断](> host_eval formula=`formula` var=`var` value=`value`)*。 - -## 求解 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | -| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | -| min | any | None | 下界,或搜索与绘图区间的起点 | -| max | any | None | 上界,或搜索与绘图区间的终点 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 返回指定符号在上下界内的根列表;省略边界时使用 -100 到 100 | - -这里使用`formula`、`var`、`min`=None、`max`=None。 - -调用效应:pure。 - -返回指定符号在上下界内的根列表;省略边界时使用 -100 到 100。 - -完成后返回*[返回指定符号在上下界内的根列表;省略边界时使用 -100 到 100](> host_solve formula=`formula` var=`var` min=`min` max=`max`)*。 - -## 绘图 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | -| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | -| min | any | 必填 | 下界,或搜索与绘图区间的起点 | -| max | any | 必填 | 上界,或搜索与绘图区间的终点 | -| steps | any | None | 绘图区间内的采样数量 | -| path | any | None | 相对已授权文件根目录的路径 | -| derivative | any | None | 是否在图中包含导函数 | -| grid | any | None | 是否绘制坐标网格 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 在区间内采样公式并返回 SVG 文本;指定路径时还会在授权根目录内写出 SVG | - -这里使用`formula`、`var`、`min`、`max`、`steps`=None、`path`=None、`derivative`=None、`grid`=None。 - -调用效应:output.write。 - -在区间内采样公式并返回 SVG 文本;指定路径时还会在授权根目录内写出 SVG。 - -完成后返回*[在区间内采样公式并返回 SVG 文本;指定路径时还会在授权根目录内写出 SVG](> host_plot formula=`formula` var=`var` min=`min` max=`max` steps=`steps` path=`path` derivative=`derivative` grid=`grid`)*。 - -## 绘点列 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | 必填 | 本操作要求的输入列表或集合 | -| ys | any | 必填 | 与 xs 一一对应的 Y 坐标列表 | -| path | any | None | 相对已授权文件根目录的路径 | -| grid | any | None | 是否绘制坐标网格 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 将一一对应的横纵坐标列表绘成 SVG 文本;两列长度不等时拒绝绘制 | - -这里使用`xs`、`ys`、`path`=None、`grid`=None。 - -调用效应:output.write。 - -将一一对应的横纵坐标列表绘成 SVG 文本;两列长度不等时拒绝绘制。 - -完成后返回*[将一一对应的横纵坐标列表绘成 SVG 文本;两列长度不等时拒绝绘制](> host_plot_points xs=`xs` ys=`ys` path=`path` grid=`grid`)*。 - -## 绘圆锥 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| kind | any | 必填 | 圆锥曲线绘制函数接受的曲线类型 | -| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | -| b | any | None | 第二个操作数;适用范围见本操作说明 | -| h | any | None | 圆锥曲线中心的水平偏移 | -| k | any | None | 圆锥曲线中心的垂直偏移 | -| path | any | None | 相对已授权文件根目录的路径 | -| grid | any | None | 是否绘制坐标网格 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 按曲线类型、尺寸和中心偏移绘制圆锥曲线,返回 SVG 文本 | - -这里使用`kind`、`a`、`b`=None、`h`=None、`k`=None、`path`=None、`grid`=None。 - -调用效应:output.write。 - -按曲线类型、尺寸和中心偏移绘制圆锥曲线,返回 SVG 文本。 - -完成后返回*[按曲线类型、尺寸和中心偏移绘制圆锥曲线,返回 SVG 文本](> host_plot_conic kind=`kind` a=`a` b=`b` h=`h` k=`k` path=`path` grid=`grid`)*。 diff --git a/lib/文件.mq.md b/lib/文件.mq.md deleted file mode 100755 index 0f57b89..0000000 --- a/lib/文件.mq.md +++ /dev/null @@ -1,785 +0,0 @@ ---- -markup: occlusion -import: - json: lib/json.mq.md - csv: lib/csv.mq.md -title: lib/文件 -description: 中文文件系统包装 ---- - -中文文件系统包装 - -在明确文件根目录内读写、筛选和整理文件。 - -能力与边界:旧删除会递归删除目录;窄操作请用只删文件或只删空目录。原子操作只替换一个文件,批量目录操作不是事务。字节和文本支持 CoW;目录状态操作的限制见能力矩阵。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 - -实现入口:[src/host/fs.rs](../src/host/fs.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/sandbox_fs.rs](../src/host/sandbox_fs.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 读文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 从路径读取 UTF-8 文本 | - -这里使用`路径`。 - -调用效应:fs.read。 - -从路径读取 UTF-8 文本。 - -完成后返回*[从路径读取 UTF-8 文本](> host_read_text path=`路径`)*。 - -## 写文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`内容`。 - -调用效应:fs.write。 - -把文本写入路径(覆盖)。 - -完成后返回*[把文本写入路径(覆盖)](> host_write_text path=`路径` text=`内容`)*。 - -## 追加文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`内容`。 - -调用效应:fs.write。 - -向路径追加文本。 - -完成后返回*[向路径追加文本](> host_append_text path=`路径` text=`内容`)*。 - -## 存在 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 路径是否存在 | - -这里使用`路径`。 - -调用效应:fs.read。 - -路径是否存在。 - -完成后返回*[路径是否存在](> host_exists path=`路径`)*。 - -## 列目录 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 列出路径下的目录项 | - -这里使用`路径`。 - -调用效应:fs.read。 - -列出路径下的目录项。 - -完成后返回*[列出路径下的目录项](> host_list_dir path=`路径`)*。 - -## 建目录 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`。 - -调用效应:fs.write。 - -创建目录。 - -完成后返回*[创建目录](> host_make_dir path=`路径`)*。 - -## 建目录树 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`。 - -调用效应:fs.write。 - -递归创建目录(等同 `mkdir -p`)。 - -完成后返回*[递归创建目录(等同 mkdir -p)](> host_make_dirs path=`路径`)*。 - -## 删除 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`。 - -调用效应:fs.write。 - -删除指定文件或递归删除目录;旧行为保持兼容,不能用于只允许删除空目录的场景。 - -删除指定文件或递归删除目录。仅删文件请用只删文件,仅删空目录请用只删空目录。 - -完成后返回*[删除指定文件或递归删除目录](> host_remove path=`路径`)*。 - -## 删目录树 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`。 - -调用效应:fs.write。 - -递归删除目录;若路径是文件则报错。 - -完成后返回*[递归删除目录;若路径是文件则报错](> host_remove_tree path=`路径`)*。 - -## 状态 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 返回 `{size, mtime_unix, is_file, is_dir}` | - -这里使用`路径`。 - -调用效应:fs.read。 - -返回 `{size, mtime_unix, is_file, is_dir}`。 - -完成后返回*[返回 {size, mtime_unix, is_file, is_dir}](> host_stat path=`路径`)*。 - -## 遍历 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 深度优先列出相对路径(正斜杠) | - -这里使用`路径`。 - -调用效应:fs.read。 - -深度优先列出相对路径(正斜杠)。 - -完成后返回*[深度优先列出相对路径(正斜杠)](> host_walk path=`路径`)*。 - -## 复制文件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 源 | any | 必填 | 来源路径;归档打包时必须是目录 | -| 目标 | any | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`源`、`目标`。 - -调用效应:fs.write。 - -复制文件(目标已存在则覆盖)。路径沙箱同其他文件操作。 - -完成后返回*[复制文件(目标已存在则覆盖)](> host_copy_file src=`源` dest=`目标`)*。 - -## 移动 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 源 | any | 必填 | 来源路径;归档打包时必须是目录 | -| 目标 | any | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`源`、`目标`。 - -调用效应:fs.write。 - -在沙箱内重命名 / 移动。 - -完成后返回*[在沙箱内重命名 / 移动](> host_move src=`源` dest=`目标`)*。 - -## 建临时 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 前缀 | any | None | 生成名称的前缀,或需要匹配的文本前缀 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 在程序目录下创建空临时文件,返回相对路径 | - -这里使用`前缀`=None。 - -调用效应:fs.write。 - -在程序目录下创建空临时文件,返回相对路径。 - -完成后返回*[在程序目录下创建空临时文件,返回相对路径](> host_make_temp prefix=`前缀`)*。 - -## 文本补丁 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | -| 查找 | any | 必填 | 替换前需要精确查找的文本 | -| 替换 | any | 必填 | 每个精确匹配项的替换文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 对 UTF-8 文本文件做精确 FIND→REPLACE(`查找` 必须唯一匹配一次) | - -这里使用`路径`、`查找`、`替换`。 - -调用效应:fs.write。 - -对 UTF-8 文本文件做精确 FIND→REPLACE(`查找` 必须唯一匹配一次)。 - -完成后返回*[对 UTF-8 文本文件做精确 FIND→REPLACE(查找 必须唯一匹配一次)](> host_text_patch path=`路径` find=`查找` replace=`替换`)*。 - -## 应用补丁块 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | -| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | -| 软失败 | any | False | 补丁未匹配时是否软失败 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 解析规划回复中的 FIND/REPLACE 块并应用到 `路径` | - -这里使用`路径`、`文本`、`软失败`=False。 - -调用效应:fs.write。 - -解析规划回复中的 FIND/REPLACE 块并应用到 `路径`。`软失败=真` 时仅「找不到 FIND」返回 0;空 FIND、多匹配、整文件重写仍报错。 - -完成后返回*[解析规划回复中的 FIND/REPLACE 块并应用到 路径](> host_apply_patch_blocks path=`路径` text=`文本` soft=`软失败`)*。 - -## 尝试读文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 以 {ok,value,error} 返回文本或错误;仍需 fs | - -这里使用`路径`。 - -调用效应:fs.read。 - -直接调用此函数: - -```sh -marqdo call lib/文件.mq.md 尝试读文本 '路径="lib/fs.mq.md"' --effects fs.read --fs-root . --json -``` - -以 {ok,value,error} 返回至多 8 MiB 的 UTF-8 文本或错误;仍需 fs.read 授权。 - -完成后返回*[以 {ok,value,error} 返回至多 8 MiB 的 UTF-8 文本或错误;仍需 fs.read 授权](> host_fs_try_read_text path=`路径`)*。 - -## 尝试写文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 覆盖写入 UTF-8 文本,返回 {ok,value,error};需要 fs | - -这里使用`路径`、`内容`。 - -调用效应:fs.write。 - -覆盖写入 UTF-8 文本,返回 {ok,value,error};需要 fs.write。 - -完成后返回*[覆盖写入 UTF-8 文本,返回 {ok,value,error};需要 fs.write](> host_fs_try_write_text path=`路径` text=`内容`)*。 - -## 读字节 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 读取 bytes 记录;默认上限 8 MiB,最大 64 MiB;解码须明确使用字节库。 | - -这里使用`路径`、`字节上限`=8388608。 - -调用效应:fs.read。 - -读取 bytes 记录;默认上限 8 MiB,最大 64 MiB;解码须明确使用字节库。 - -完成后返回*[读取 bytes 记录;默认上限 8 MiB,最大 64 MiB;解码须明确使用字节库](> host_fs_read_bytes path=`路径` max_bytes=`字节上限`)*。 - -## 写字节 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`数据`。 - -调用效应:fs.write。 - -用字节原子替换文件,不进行 UTF-8 转换;需要 fs.write。 - -完成后返回*[用字节原子替换文件,不进行 UTF-8 转换;需要 fs.write](> host_fs_write_bytes path=`路径` data=`数据`)*。 - -## 读块 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 偏移 | number | 0 | 下一块的字节偏移,从零开始 | -| 大小 | number | 65536 | 本次块读取的字节数 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 从零起字节偏移 offset 读取至多 size 字节,返回 data/next_offset/eof;每次调用关闭文件,不跨会话持有句柄。 | - -这里使用`路径`、`偏移`=0、`大小`=65536。 - -调用效应:fs.read。 - -从零起字节偏移 offset 读取至多 size 字节,返回 data/next_offset/eof;每次调用关闭文件,不跨会话持有句柄。 - -完成后返回*[从零起字节偏移 offset 读取至多 size 字节,返回 data/next_offset/eof;每次调用关闭文件,不跨会话持有句柄](> host_fs_read_chunk path=`路径` offset=`偏移` size=`大小`)*。 - -## 追加字节 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`数据`。 - -调用效应:fs.write。 - -追加字节,不存在则创建文件;父目录必须存在。 - -完成后返回*[追加字节,不存在则创建文件;父目录必须存在](> host_fs_append_bytes path=`路径` data=`数据`)*。 - -## 原子写文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`内容`。 - -调用效应:fs.write。 - -经同目录独占临时文件和重命名替换文本;失败清理临时文件。这是单文件替换,不是多文件事务。 - -完成后返回*[经同目录独占临时文件和重命名替换文本;失败清理临时文件](> host_fs_atomic_write path=`路径` text=`内容`)*。 - -## 变化才写 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | bool | 仅内容变化时原子写入;返回是否发生写入。 | - -这里使用`路径`、`内容`。 - -调用效应:fs.write。 - -仅内容变化时原子写入;返回是否发生写入。 - -完成后返回*[仅内容变化时原子写入;返回是否发生写入](> host_fs_write_changed path=`路径` text=`内容`)*。 - -## 校验后写 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | -| 预期摘要 | text | 必填 | 前次精确文本的摘要;操作允许时 None 表示不检查 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 核对当前 SHA-256 后原子替换,返回结果记录;可发现过期内容,并发写者仍需外部协调。 | - -这里使用`路径`、`内容`、`预期摘要`。 - -调用效应:fs.write。 - -核对当前 SHA-256 后原子替换,返回结果记录;可发现过期内容,并发写者仍需外部协调。 - -完成后返回*[核对当前 SHA-256 后原子替换,返回结果记录;可发现过期内容,并发写者仍需外部协调](> host_fs_write_checked path=`路径` text=`内容` expected_sha256=`预期摘要`)*。 - -## 读行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 有界读取 UTF-8 行,去除行尾;接受 CRLF,末尾换行不产生额外行。 | - -这里使用`路径`、`字节上限`=8388608。 - -调用效应:fs.read。 - -有界读取 UTF-8 行,去除行尾;接受 CRLF,末尾换行不产生额外行。 - -完成后返回*[有界读取 UTF-8 行,去除行尾;接受 CRLF,末尾换行不产生额外行](> host_fs_read_lines path=`路径` max_bytes=`字节上限`)*。 - -## 写行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 行表 | list | 必填 | 待写入的文本行列表 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`行表`。 - -调用效应:fs.write。 - -按 LF 原子写入文本行;非空输入追加一个末尾换行。 - -完成后返回*[按 LF 原子写入文本行;非空输入追加一个末尾换行](> host_fs_write_lines path=`路径` lines=`行表`)*。 - -## 只删文件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`。 - -调用效应:fs.write。 - -删除文件,拒绝目录;不存在则失败。旧删除接口保持递归兼容行为。 - -完成后返回*[删除文件,拒绝目录;不存在则失败](> host_fs_remove_file path=`路径`)*。 - -## 只删空目录 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`。 - -调用效应:fs.write。 - -只删除空目录;非空目录失败。仅原生文件系统支持。 - -完成后返回*[只删除空目录;非空目录失败](> host_fs_remove_empty_dir path=`路径`)*。 - -## 临时目录 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 前缀 | text | "mqtmp" | 生成名称的前缀,或需要匹配的文本前缀 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 在文件根目录内创建临时目录,返回相对名称;调用方负责删目录树清理,不使用系统全局临时目录。 | - -这里使用`前缀`="mqtmp"。 - -调用效应:fs.write。 - -在文件根目录内创建临时目录,返回相对名称;调用方负责删目录树清理,不使用系统全局临时目录。 - -完成后返回*[在文件根目录内创建临时目录,返回相对名称;调用方负责删目录树清理,不使用系统全局临时目录](> host_fs_temp_dir prefix=`前缀`)*。 - -## 文件摘要 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 以 64 KiB 缓冲区计算 SHA-256;支持二进制大文件,不整文件载入内存。 | - -这里使用`路径`。 - -调用效应:fs.read。 - -以 64 KiB 缓冲区计算 SHA-256;支持二进制大文件,不整文件载入内存。 - -完成后返回*[以 64 KiB 缓冲区计算 SHA-256;支持二进制大文件,不整文件载入内存](> host_fs_file_hash path=`路径`)*。 - -## 查找文件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 模式 | text | "**" | 相对路径 glob,支持 *、** 与 ? | -| 排除 | any | None | 遍历时剪枝的 glob 模式列表;None 表示不排除 | -| 深度上限 | number | 64 | 最大遍历深度 | -| 类型 | text | "file" | 条目类型过滤:file、dir 或 all;all 同时包含文件和目录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按 单星号、双星号与问号 模式查找有序相对路径;exclude 可剪除目录,kind 为 file/dir/all;不跟随符号链接,最多十万项。读取原生文件系统快照。 | - -这里使用`路径`、`模式`="**"、`排除`=None、`深度上限`=64、`类型`="file"。 - -调用效应:fs.read。 - -按 单星号、双星号与问号 模式查找有序相对路径;exclude 可剪除目录,kind 为 file/dir/all;不跟随符号链接,最多十万项。读取原生文件系统快照。 - -完成后返回*[按 单星号、双星号与问号 模式查找有序相对路径;exclude 可剪除目录,kind 为 file/dir/all;不跟随符号链接,最多十万项](> host_fs_find path=`路径` pattern=`模式` exclude=`排除` max_depth=`深度上限` kind=`类型`)*。 - -## 复制目录树 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | -| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | -| 覆盖 | bool | False | 是否允许替换已存在的目标文件 | -| 排除 | any | None | 遍历时剪枝的 glob 模式列表;None 表示不排除 | -| 预演 | bool | False | 是否仅返回计划而不修改文件 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 在不相交目录树间复制文件;先检查冲突,覆盖须明确开启。返回相对文件列表;dry_run 仅计划。不复制权限、链接和空目录。 | - -这里使用`来源`、`目标`、`覆盖`=False、`排除`=None、`预演`=False。 - -调用效应:fs.write。 - -在不相交目录树间复制文件;先检查冲突,覆盖须明确开启。返回相对文件列表;dry_run 仅计划。不复制权限、链接和空目录。 - -完成后返回*[在不相交目录树间复制文件;先检查冲突,覆盖须明确开启](> host_fs_copy_tree src=`来源` dest=`目标` overwrite=`覆盖` exclude=`排除` dry_run=`预演`)*。 - -## 同步目录树 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | -| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | -| 覆盖 | bool | False | 是否允许替换已存在的目标文件 | -| 排除 | any | None | 遍历时剪枝的 glob 模式列表;None 表示不排除 | -| 预演 | bool | False | 是否仅返回计划而不修改文件 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按复制目录树的冲突规则复制新增或变化文件;不删除目标独有文件,执行不是事务。 | - -这里使用`来源`、`目标`、`覆盖`=False、`排除`=None、`预演`=False。 - -调用效应:fs.write。 - -按复制目录树的冲突规则复制新增或变化文件;不删除目标独有文件,执行不是事务。 - -完成后返回*[按复制目录树的冲突规则复制新增或变化文件;不删除目标独有文件,执行不是事务](> host_fs_sync_tree src=`来源` dest=`目标` overwrite=`覆盖` exclude=`排除` dry_run=`预演`)*。 - -## 批量改名 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 改名表 | list | 必填 | 来源与目标路径组成的改名记录列表 | -| 预演 | bool | False | 是否仅返回计划而不修改文件 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 预检 src/dest 文件记录,拒绝已有或重复目标,然后按输入顺序改名。不支持环路或回滚;dry_run 返回计划数量。 | - -这里使用`改名表`、`预演`=False。 - -调用效应:fs.write。 - -预检 src/dest 文件记录,拒绝已有或重复目标,然后按输入顺序改名。不支持环路或回滚;dry_run 返回计划数量。 - -完成后返回*[预检 src/dest 文件记录,拒绝已有或重复目标,然后按输入顺序改名](> host_fs_rename_many moves=`改名表` dry_run=`预演`)*。 - -## 读JSON - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 相对文件根目录的路径 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 解析后的数据 | - -这里使用`路径`。 - -调用效应:fs.read。 - -读取 UTF-8 文本后使用同一标准解析器;错误会终止,批处理请先尝试读文本。 - -得到**`body` = [读取指定文件的 UTF-8 正文](读文本(路径=`路径`))**。 -完成后返回*[解析 JSON 传输文本](json.parse(text=`body`))*。 - -## 写JSON - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 相对文件根目录的路径 | -| 数据 | any | 必填 | 待序列化的数据 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`数据`。 - -调用效应:fs.write。 - -序列化后以原子写入替换文件;不保留旧格式与注释。 - -得到**`body` = [将结构化值编码为 JSON 文本](json.stringify(value=`数据`))**。 -完成后返回*[将准备好的文本写入指定文件](原子写文本(路径=`路径`, 内容=`body`))*。 - -## 读CSV - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 相对文件根目录的路径 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 解析后的数据 | - -这里使用`路径`。 - -调用效应:fs.read。 - -读取 UTF-8 文本后使用同一标准解析器;错误会终止,批处理请先尝试读文本。 - -得到**`body` = [读取指定文件的 UTF-8 正文](读文本(路径=`路径`))**。 -完成后返回*[调用 parse](csv.parse(text=`body`))*。 - -## 写CSV - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 相对文件根目录的路径 | -| 数据 | list | 必填 | 待序列化的数据 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 完成后返回 None;文件操作失败时返回诊断 | - -这里使用`路径`、`数据`。 - -调用效应:fs.write。 - -序列化后以原子写入替换文件;不保留旧格式与注释。 - -得到**`body` = [调用 stringify](csv.stringify(rows=`数据`))**。 -完成后返回*[将准备好的文本写入指定文件](原子写文本(路径=`路径`, 内容=`body`))*。 - -## 解析路径 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 相对已授予文件根的路径,或根内的绝对路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 经过原生根目录与符号链接检查的绝对逻辑路径 | - -输入`路径`,在授权 fs.read 后解析绝对地址。它使用读文本与临时目录相同的文件上下文,因此进程工作目录与 --fs-root 不同时也能正确组合本地资源 URI。目标可以尚未创建,最近的已有祖先仍经过根目录和符号链接检查。解析只返回地址,不创建文件;结果保留逻辑路径,外部插件和进程继续按各自操作系统权限执行。 - -完成后返回*[通过原生文件上下文解析实际地址](host_fs_resolve(path=`路径`))*. diff --git a/lib/文本.mq.md b/lib/文本.mq.md deleted file mode 100755 index d6a0cf3..0000000 --- a/lib/文本.mq.md +++ /dev/null @@ -1,235 +0,0 @@ ---- -markup: occlusion -title: lib/文本 -description: 文本库加厚(中层 M4)。字面替换 — 正则请用 lib/正则。 ---- - -常用文本助手。手写拆分不如走这里;正则请用 lib/正则。 - -清理与组合 Unicode 文本。 - -能力与边界:字面替换使用本库,模式匹配使用正则库,任意二进制使用字节库。拆分和拼接使用明确分隔符,不隐式解析文档。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/text_ops.rs](../src/host/text_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 去空白 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| s | text | 必填 | 输入文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 去掉字符串 s 两端空白 | - -这里使用`s`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/文本.mq.md 去空白 's=" readable text "' --effects none --json -``` - -去掉字符串 s 两端空白。 - -完成后返回*[调用 trim](trim(`s`))*。 - -## 拆分 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| s | text | 必填 | 输入文本 | -| sep | text | 必填 | 拆分或连接文本所用的分隔符 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 按分隔符 sep 拆分字符串 s | - -这里使用`s`、`sep`。 - -调用效应:pure。 - -按分隔符 sep 拆分字符串 s。 - -完成后返回*[调用 split](split(value=`s`, sep=`sep`))*。 - -## 拼接 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | 必填 | 本操作要求的输入列表或集合 | -| sep | text | 必填 | 拆分或连接文本所用的分隔符 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 用分隔符 sep 拼接列表 xs | - -这里使用`xs`、`sep`。 - -调用效应:pure。 - -用分隔符 sep 拼接列表 xs。 - -完成后返回*[调用 join](join(value=`xs`, sep=`sep`))*。 - -## 包含 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 子串 | any | 必填 | 需要查找的子串 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 内容是否包含子串 | - -这里使用`内容`、`子串`。 - -调用效应:pure。 - -内容是否包含子串。 - -调用例:[文本.包含] 内容="你好" 子串="好" - -完成后返回*[内容是否包含子串](> host_text_contains text=`内容` sub=`子串`)*。 - -## 开头是 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 前缀 | any | 必填 | 生成名称的前缀,或需要匹配的文本前缀 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 内容是否以前缀开头 | - -这里使用`内容`、`前缀`。 - -调用效应:pure。 - -内容是否以前缀开头。 - -完成后返回*[内容是否以前缀开头](> host_text_starts_with text=`内容` prefix=`前缀`)*。 - -## 结尾是 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 后缀 | any | 必填 | 需要匹配的文本后缀 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 内容是否以后缀结尾 | - -这里使用`内容`、`后缀`。 - -调用效应:pure。 - -内容是否以后缀结尾。 - -完成后返回*[内容是否以后缀结尾](> host_text_ends_with text=`内容` suffix=`后缀`)*。 - -## 替换 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 旧 | any | 必填 | 需要替换的精确子串 | -| 新 | any | 必填 | 替换后使用的文本 | -| 次数 | any | None | 最大替换次数;None 使用操作说明中的默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 在内容里把字面旧换成新,可选次数 | - -这里使用`内容`、`旧`、`新`、`次数`=None。 - -调用效应:pure。 - -在内容里把字面旧换成新,可选次数。 - -完成后返回*[在内容里把字面旧换成新,可选次数](> host_text_replace text=`内容` old=`旧` new=`新` count=`次数`)*。 - -## 大写 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 内容转大写 | - -这里使用`内容`。 - -调用效应:pure。 - -内容转大写。 - -完成后返回*[内容转大写](> host_text_to_upper text=`内容`)*。 - -## 小写 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 内容转小写 | - -这里使用`内容`。 - -调用效应:pure。 - -内容转小写。 - -完成后返回*[内容转小写](> host_text_to_lower text=`内容`)*。 - -## 重复 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 次数 | any | 必填 | 重复次数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 把内容重复次数遍 | - -这里使用`内容`、`次数`。 - -调用效应:pure。 - -把内容重复次数遍。 - -完成后返回*[把内容重复次数遍](> host_text_repeat text=`内容` n=`次数`)*。 - -## 填充 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 宽度 | any | 必填 | 填充后的目标字符宽度 | -| 填充符 | any | None | 单个填充字符 | -| 对齐 | any | None | 填充对齐方式:left、right 或 center | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 把内容填充到宽度,可选填充符与对齐(left / right / center) | - -这里使用`内容`、`宽度`、`填充符`=None、`对齐`=None。 - -调用效应:pure。 - -把内容填充到宽度,可选填充符与对齐(left / right / center)。 - -完成后返回*[把内容填充到宽度,可选填充符与对齐(left / right / center)](> host_text_pad text=`内容` width=`宽度` fill=`填充符` align=`对齐`)*。 diff --git a/lib/文档.mq.md b/lib/文档.mq.md deleted file mode 100755 index 8e34760..0000000 --- a/lib/文档.mq.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -markup: occlusion -import: - document: lib/document.mq.md ---- - -通过渲染器共用的 Markdown 解析器读取文档结构。结构变换为纯函数,读取表值通过原生文件能力加载指定数据。 - -不执行内容地读取与变换 Markdown 结构。 - -能力与边界:复用 Markdown 解析器并识别 YAML 前置信息;区间是原始 UTF-8 字节偏移。不执行文档。重复章节名失败;替换保留周围源码,持久化使用校验后写。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/document.rs](../src/host/document.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 章节列表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 列出标题、原始 UTF-8 字节区间和正文;章节结束于下一个同级或更高级标题。不执行文档。 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/文档.mq.md 章节列表 '内容="# Notes"' --effects none --json -``` - -列出标题、原始 UTF-8 字节区间和正文;章节结束于下一个同级或更高级标题。不执行文档。 - -完成后返回*[列出标题、原始 UTF-8 字节区间和正文;章节结束于下一个同级或更高级标题](> host_document_sections text=`内容`)*。 - -## 读取章节 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | -| 标题 | text | 必填 | 精确且唯一的 Markdown 标题文字 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 按完整标题读取正文;缺失或重复标题失败。 | - -这里使用`内容`、`标题`。 - -调用效应:pure。 - -按完整标题读取正文;缺失或重复标题失败。 - -完成后返回*[按完整标题读取正文;缺失或重复标题失败](> host_document_section text=`内容` title=`标题`)*。 - -## 替换章节 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | -| 标题 | text | 必填 | 精确且唯一的 Markdown 标题文字 | -| 正文 | text | 必填 | 请求正文;文档操作中为替换正文 | -| 预期摘要 | any | None | 前次精确文本的摘要;操作允许时 None 表示不检查 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 返回替换章节正文的结果记录,保留标题和周围源码;可校验整份来源摘要。这是纯转换,持久化使用文件库校验后写。 | - -这里使用`内容`、`标题`、`正文`、`预期摘要`=None。 - -调用效应:pure。 - -返回替换章节正文的结果记录,保留标题和周围源码;可校验整份来源摘要。这是纯转换,持久化使用文件库校验后写。 - -完成后返回*[返回替换章节正文的结果记录,保留标题和周围源码;可校验整份来源摘要](> host_document_replace_section text=`内容` title=`标题` body=`正文` expected_sha256=`预期摘要`)*。 - -## 表格列表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 提取惰性的 GFM 表头、单元格文本和原始字节区间;不求值单元格。 | - -这里使用`内容`。 - -调用效应:pure。 - -提取惰性的 GFM 表头、单元格文本和原始字节区间;不求值单元格。 - -完成后返回*[提取惰性的 GFM 表头、单元格文本和原始字节区间;不求值单元格](> host_document_tables text=`内容`)*。 - -## 替换表格 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | -| 序号 | number | 必填 | 按源码顺序排列的表格下标,从零开始 | -| 表头 | list | 必填 | 按列顺序排列的表头文本列表 | -| 行 | list | 必填 | 单元格文本列表组成的行列表;每行宽度必须与表头一致 | -| 预期摘要 | any | None | 前次精确文本的摘要;操作允许时 None 表示不检查 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 按从零起的表序号,用文本表头和行替换表格,保留周围源码;返回结果记录。 | - -这里使用`内容`、`序号`、`表头`、`行`、`预期摘要`=None。 - -调用效应:pure。 - -按从零起的表序号,用文本表头和行替换表格,保留周围源码;返回结果记录。 - -完成后返回*[按从零起的表序号,用文本表头和行替换表格,保留周围源码;返回结果记录](> host_document_replace_table text=`内容` index=`序号` headers=`表头` rows=`行` expected_sha256=`预期摘要`)*。 - -## 链接列表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 列出 Markdown 链接描述、目标和字节区间;不访问或执行链接。 | - -这里使用`内容`。 - -调用效应:pure。 - -列出 Markdown 链接描述、目标和字节区间;不访问或执行链接。 - -完成后返回*[列出 Markdown 链接描述、目标和字节区间;不访问或执行链接](> host_document_links text=`内容`)*。 - -## 代码块列表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码。 | - -这里使用`内容`。 - -调用效应:pure。 - -列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码。 - -完成后返回*[列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码](> host_document_code_blocks text=`内容`)*。 - -## 表值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 含字面 GFM 数据表的 Markdown | -| 标题 | any | None | 精确且唯一的章节名;None 表示整篇 | -| 索引 | number | 0 | 所选章节中从零开始的表格序号 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 与 Marqdo 字面表相同形态和类型的实际数据 | - -这里使用`内容`、`标题`=None和`索引`=0。常量表中的布尔、数值、空值和引号文本保留原生类型;@、行或 row 首列产生记录列表,单列产生普通列表,其余表保留原有映射形态。定位使用渲染器共用的 Markdown 解析器,会跳过围栏内示例。重复标题、表头冲突、列数不齐和非法索引会给出诊断。变量引用、插值和可执行表达式不能作为数据读取;正文、导入和外联围栏也不会执行。这样可以把模式、种子和样式常量拆成 Markdown 数据叶子,同时让调用函数说明实际用途。 - -完成后返回*[按原生字面规则读取表值](document.table(text=`内容`, title=`标题`, index=`索引`))*. - - -## 读取表值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 文件根内的 UTF-8 Markdown 数据文件 | -| 标题 | any | None | 精确且唯一的章节名;None 表示整篇 | -| 索引 | number | 0 | 所选章节中从零开始的表格序号 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 通过原生 fs.read 加载的字面表数据 | - -这里使用`路径`、`标题`=None和`索引`=0,授权 fs.read 后读取数据叶子。文件读取检查根目录与 UTF-8,表值选择保留字面类型及实际结构。文件可以把字段说明、示例和数据写在一起,读取过程不会运行其中的语句、导入或其他语言围栏。文件缺失、标题重复、单元格动态引用和列数不齐均保留诊断。此函数只读,调用者再按数据库、样式或其他领域的真实契约使用返回值。 - -完成后返回*[原生读取并选择 Markdown 数据](document.read_table(path=`路径`, title=`标题`, index=`索引`))*. diff --git a/lib/日志.mq.md b/lib/日志.mq.md deleted file mode 100755 index 4354514..0000000 --- a/lib/日志.mq.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -markup: occlusion -title: lib/日志 -description: 按级别过滤的一行日志(中层 M6 + Mid2 M10 字段)。默认级别 info。 ---- - -按级别过滤的一行日志(中层 M6 + Mid2 M10 字段)。默认级别 info。 - -输出按等级过滤的诊断日志。 - -能力与边界:日志等级只影响本次运行;日志是输出效应,不是返回值。call 将捕获输出与 JSON 结果分开。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/log.rs](../src/host/log.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 设级别 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 级别 | any | 必填 | 日志阈值:debug、info、warn 或 error | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 级别:debug / info / warn / error(或 调试/信息/警告/错误) | - -这里使用`级别`。 - -调用效应:pure。 - -级别:debug / info / warn / error(或 调试/信息/警告/错误)。 - -完成后返回*[级别:debug / info / warn / error(或 调试/信息/警告/错误)](> host_log_set_level level=`级别`)*。 - -## 调试 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 写出调试日志行;可选字段映射 | - -这里使用`内容`、`字段`=None。 - -调用效应:output.write。 - -写出调试日志行;可选字段映射。 - -得到**`line` = [调用 log line]([写出调试日志行;可选字段映射](host_log_line(level="debug", text=`内容`, fields=`字段`)))**。 -1. `line` - 这里**[输出本步已准备的消息](打印(内容=`line`))**。 -2. * - 完成后返回*None*。 - -## 信息 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 写出信息日志行;可选字段映射 | - -这里使用`内容`、`字段`=None。 - -调用效应:output.write。 - -直接调用此函数: - -```sh -marqdo call lib/日志.mq.md 信息 '内容="handbook example"' '字段={"task":"sample"}' --effects output.write --json -``` - -写出信息日志行;可选字段映射。 - -得到**`line` = [调用 log line]([写出信息日志行;可选字段映射](host_log_line(level="info", text=`内容`, fields=`字段`)))**。 -1. `line` - 这里**[输出本步已准备的消息](打印(内容=`line`))**。 -2. * - 完成后返回*None*。 - -## 警告 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 写出警告日志行;可选字段映射 | - -这里使用`内容`、`字段`=None。 - -调用效应:output.write。 - -写出警告日志行;可选字段映射。 - -得到**`line` = [调用 log line]([写出警告日志行;可选字段映射](host_log_line(level="warn", text=`内容`, fields=`字段`)))**。 -1. `line` - 这里**[输出本步已准备的消息](打印(内容=`line`))**。 -2. * - 完成后返回*None*。 - -## 错误 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 写出错误日志行;可选字段映射 | - -这里使用`内容`、`字段`=None。 - -调用效应:output.write。 - -写出错误日志行;可选字段映射。 - -得到**`line` = [调用 log line]([写出错误日志行;可选字段映射](host_log_line(level="error", text=`内容`, fields=`字段`)))**。 -1. `line` - 这里**[输出本步已准备的消息](打印(内容=`line`))**。 -2. * - 完成后返回*None*。 diff --git a/lib/日期时间.mq.md b/lib/日期时间.mq.md deleted file mode 100755 index 5a71023..0000000 --- a/lib/日期时间.mq.md +++ /dev/null @@ -1,191 +0,0 @@ ---- -markup: occlusion -title: lib/日期时间 -description: 日历时刻 map `{unix, zone, iso}`(中层 Mid2 M7)。固定偏移和内嵌 IANA 时区与夏令时规则。 ---- - -日历时刻 map `{unix, zone, iso}`(中层 Mid2 M7)。固定偏移和内嵌 IANA 时区与夏令时规则。 - -处理时间戳、IANA 时区和当地日历。 - -能力与边界:zone 保留数值偏移,timezone 保留 IANA 身份。加按经过的秒数计算;加日历日保持当地钟点。夏令时缺口失败,重叠时间须明确选择策略。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/datetime.rs](../src/host/datetime.rs)、[src/host/data_ops.rs](../src/host/data_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 现在 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 读取时钟并返回当前 UTC 日期时间记录 | - -调用效应:time.read。 - -读取时钟并返回当前 UTC 日期时间记录。 - -完成后返回*[读取时钟并返回当前 UTC 日期时间记录](host_datetime_now())*。 - -## 自戳 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 秒 | any | 必填 | 以秒为单位的 Unix 时间戳 | -| 区 | any | None | 本操作接受的固定偏移或命名时区 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 把 Unix 秒数转换为指定时区的日期时间记录;未指定时区时使用 UTC | - -这里使用`秒`、`区`=None。 - -调用效应:pure。 - -把 Unix 秒数转换为指定时区的日期时间记录;未指定时区时使用 UTC。 - -完成后返回*[把 Unix 秒数转换为指定时区的日期时间记录;未指定时区时使用 UTC](> host_datetime_from_unix unix=`秒` zone=`区`)*。 - -## 成戳 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 从日期时间记录读取 Unix 秒数;格式与时区表示不改变同一时刻 | - -这里使用`时刻`。 - -调用效应:pure。 - -从日期时间记录读取 Unix 秒数;格式与时区表示不改变同一时刻。 - -完成后返回*[从日期时间记录读取 Unix 秒数;格式与时区表示不改变同一时刻](> host_datetime_to_unix dt=`时刻`)*。 - -## 解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 格式 | any | None | None 使用默认解析,或指定 rfc3339、strftime 格式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 解析 RFC3339 或带可选时分秒的 YYYY-MM-DD 文本;显式格式使用 strftime 或 rfc3339 | - -这里使用`内容`、`格式`=None。 - -调用效应:pure。 - -解析 RFC3339 或带可选时分秒的 YYYY-MM-DD 文本;显式格式使用 strftime 或 rfc3339。 - -完成后返回*[解析 RFC3339 或带可选时分秒的 YYYY-MM-DD 文本;显式格式使用 strftime 或 rfc3339](> host_datetime_parse text=`内容` pattern=`格式`)*。 - -## 格式化 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | -| 样式 | any | None | 宿主日期格式化接口接受的格式样式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 把日期时间记录格式化为 rfc3339、date、time,或显式 strftime 格式的文本 | - -这里使用`时刻`、`样式`=None。 - -调用效应:pure。 - -把日期时间记录格式化为 rfc3339、date、time,或显式 strftime 格式的文本。 - -完成后返回*[把日期时间记录格式化为 rfc3339、date、time,或显式 strftime 格式的文本](> host_datetime_format dt=`时刻` style=`样式`)*。 - -## 加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | -| 天 | any | None | 增加的完整 24 小时时段数量 | -| 小时 | any | None | 增加的小时数 | -| 分钟 | any | None | 增加的分钟数 | -| 秒数 | any | None | 增加的秒数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 增加经过的天、小时、分钟与秒;这里一天固定为 24 小时,命名时区在移动后重新计算偏移 | - -这里使用`时刻`、`天`=None、`小时`=None、`分钟`=None、`秒数`=None。 - -调用效应:pure。 - -增加经过的天、小时、分钟与秒;这里一天固定为 24 小时,命名时区在移动后重新计算偏移。 - -完成后返回*[增加经过的天、小时、分钟与秒;这里一天固定为 24 小时,命名时区在移动后重新计算偏移](> host_datetime_add dt=`时刻` days=`天` hours=`小时` minutes=`分钟` seconds=`秒数`)*。 - -## 时区 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | -| 区 | any | 必填 | 本操作接受的固定偏移或命名时区 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 用固定偏移或 IANA 时区重新表示同一时刻,保留其 Unix 时间戳 | - -这里使用`时刻`、`区`。 - -调用效应:pure。 - -用固定偏移或 IANA 时区重新表示同一时刻,保留其 Unix 时间戳。 - -完成后返回*[用固定偏移或 IANA 时区重新表示同一时刻,保留其 Unix 时间戳](> host_datetime_in_zone dt=`时刻` zone=`区`)*。 - -## 解析当地时间 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | -| 时区 | text | 必填 | 本操作接受的固定偏移或命名时区 | -| 歧义处理 | text | "reject" | 夏令时重叠处理:reject、earliest 或 latest | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 解析 IANA 时区的当地时间并返回结果记录;夏令时缺口失败,重叠须选择 reject/earliest/latest。格式为年-月-日 时:分:秒。 | - -这里使用`内容`、`时区`、`歧义处理`="reject"。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/日期时间.mq.md 解析当地时间 '内容="2024-11-03 01:30:00"' '时区="America/New_York"' '歧义处理="earliest"' --effects none --json -``` - -解析 IANA 时区的当地时间并返回结果记录;夏令时缺口失败,重叠须选择 reject/earliest/latest。格式为年-月-日 时:分:秒。 - -完成后返回*[解析 IANA 时区的当地时间并返回结果记录;夏令时缺口失败,重叠须选择 reject/earliest/latest](> host_datetime_local text=`内容` zone=`时区` ambiguity=`歧义处理`)*。 - -## 加日历日 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 时刻 | map | 必填 | 本库返回的日期时间记录,不是格式化文本 | -| 天数 | number | 必填 | 增加的当地日历天数;跨夏令时保持墙钟时间 | -| 歧义处理 | text | "reject" | 夏令时重叠处理:reject、earliest 或 latest | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 按当地日历增加日期并返回结果记录,跨夏令时保持当地钟点。旧 add 按持续秒数计算,一天为二十四小时。 | - -这里使用`时刻`、`天数`、`歧义处理`="reject"。 - -调用效应:pure。 - -按当地日历增加日期并返回结果记录,跨夏令时保持当地钟点。旧 add 按持续秒数计算,一天为二十四小时。 - -完成后返回*[按当地日历增加日期并返回结果记录,跨夏令时保持当地钟点](> host_datetime_calendar_add dt=`时刻` days=`天数` ambiguity=`歧义处理`)*。 diff --git a/lib/时间.mq.md b/lib/时间.mq.md deleted file mode 100755 index 716b8b2..0000000 --- a/lib/时间.mq.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -markup: occlusion -title: lib/时间 -description: 中文时间包装 ---- - -Unix 时间、格式化、解析与睡眠。 - -格式化时间戳并控制等待。 - -能力与边界:读取当前时间需要时钟效应;等待具有控制效应,在捕获模式下会被限制。日历和 IANA 时区规则由日期时间库负责。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/time.rs](../src/host/time.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 此刻秒 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 当前 Unix 秒 | - -调用效应:time.read。 - -当前 Unix 秒。 - -调用例:[时间.此刻秒] - -完成后返回*[当前 Unix 秒](host_now_unix())*。 - -## 此刻毫秒 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 当前 Unix 毫秒 | - -调用效应:time.read。 - -当前 Unix 毫秒。 - -完成后返回*[当前 Unix 毫秒](host_now_ms())*。 - -## 格式化 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 秒 | any | 必填 | 以秒为单位的 Unix 时间戳 | -| 格式 | any | 必填 | strftime 日期时间格式文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 用格式把秒格式化成文本 | - -这里使用`秒`、`格式`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/时间.mq.md 格式化 '秒=0' '格式="%Y-%m-%d"' --effects none --json -``` - -用格式把秒格式化成文本。 - -完成后返回*[用格式把秒格式化成文本](> host_format_time unix=`秒` pattern=`格式`)*。 - -## 睡眠毫秒 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 毫秒 | any | 必填 | 时长或延迟,单位毫秒 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 睡眠指定的毫秒数 | - -这里使用`毫秒`。 - -调用效应:process.control。 - -睡眠指定的毫秒数。 - -完成后返回*[睡眠指定的毫秒数](> host_sleep_ms ms=`毫秒`)*。 - -## 解析时间 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 格式 | any | 必填 | strftime 日期时间格式文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 按格式解析内容,得到 Unix 秒 | - -这里使用`内容`、`格式`。 - -调用效应:pure。 - -按格式解析内容,得到 Unix 秒。 - -完成后返回*[按格式解析内容,得到 Unix 秒](> host_parse_time text=`内容` pattern=`格式`)*。 diff --git a/lib/机密.mq.md b/lib/机密.mq.md deleted file mode 100755 index 361e17a..0000000 --- a/lib/机密.mq.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -markup: occlusion -title: lib/机密 -description: 安全随机令牌(中层 M3)。勿用 math.random 生成令牌。 ---- - -安全随机令牌。勿用 math.random 生成令牌。 - -生成密码学随机令牌。 - -能力与边界:字节数是输入字节长度,不是输出文本长度。不能用数学伪随机数生成凭证;浏览器熵源依赖运行时桥接,不可悄悄替换为伪随机。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/secrets.rs](../src/host/secrets.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 十六进制令牌 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 字节数 | any | None | 请求的字节数;None 使用接口默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 字节长度(默认 16),返回长度为 2*字节数 的小写 hex | - -这里使用`字节数`=None。 - -调用效应:random.read。 - -直接调用此函数: - -```sh -marqdo call lib/机密.mq.md 十六进制令牌 '字节数=16' --effects random.read --json -``` - -字节长度(默认 16),返回长度为 2*字节数 的小写 hex。 - -调用例:[机密.十六进制令牌] 字节数=16 - -完成后返回*[字节长度(默认 16),返回长度为 2*字节数 的小写 hex](> host_secrets_token_hex n=`字节数`)*。 - -## 网址安全令牌 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 字节数 | any | None | 请求的字节数;None 使用接口默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 字节长度(默认 16),URL-safe Base64(无填充) | - -这里使用`字节数`=None。 - -调用效应:random.read。 - -字节长度(默认 16),URL-safe Base64(无填充)。 - -完成后返回*[字节长度(默认 16),URL-safe Base64(无填充)](> host_secrets_token_urlsafe n=`字节数`)*。 diff --git a/lib/标识.mq.md b/lib/标识.mq.md deleted file mode 100755 index 99738af..0000000 --- a/lib/标识.mq.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -markup: occlusion -title: lib/标识 -description: UUID 版本 4(中层 M6)。经 getrandom 安全随机。 ---- - -随机 UUID。不要自己拼不可靠的标识。 - -生成 UUID v4 标识。 - -能力与边界:使用系统熵生成 UUID v4,不是可复现常量;不能把普通标识当作授权令牌。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口: - -实现入口:[src/host/uuid_ops.rs](../src/host/uuid_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 版本4 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 生成 UUID 版本 4 字符串 | - -调用效应:random.read。 - -直接调用此函数: - -```sh -marqdo call lib/标识.mq.md 版本4 --effects random.read --json -``` - -生成 UUID 版本 4 字符串。 - -调用例:[标识.版本4] - -完成后返回*[生成 UUID 版本 4 字符串](host_uuid_v4())*。 diff --git a/lib/正则.mq.md b/lib/正则.mq.md deleted file mode 100755 index 4a99bd9..0000000 --- a/lib/正则.mq.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -markup: occlusion -title: lib/正则 -description: 正则表达式(中层 M1)。Unicode;无回溯引用。 ---- - -正则表达式。Unicode;无回溯引用。字面替换请用 lib/文本。 - -进行 Unicode 正则匹配。 - -能力与边界:不支持反向引用;当前查找返回完整匹配,不承诺捕获组对象或替换回调。字面字符串替换使用文本库。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/re.rs](../src/host/re.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 匹配 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 内容是否匹配模式 | - -这里使用`内容`、`模式`。 - -调用效应:pure。 - -内容是否匹配模式。 - -调用例:[正则.匹配] 内容=`s` 模式="a+" - -完成后返回*[内容是否匹配模式](> host_re_is_match text=`内容` pattern=`模式`)*。 - -## 查找 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 在内容中查找模式的首个匹配;没有 → None | - -这里使用`内容`、`模式`。 - -调用效应:pure。 - -在内容中查找模式的首个匹配;没有 → None。 - -完成后返回*[在内容中查找模式的首个匹配;没有 → None](> host_re_find text=`内容` pattern=`模式`)*。 - -## 查找全部 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 在内容中查找模式的全部匹配 | - -这里使用`内容`、`模式`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/正则.mq.md 查找全部 '内容="a12 b34"' '模式="[0-9]+"' --effects none --json -``` - -在内容中查找模式的全部匹配。 - -完成后返回*[在内容中查找模式的全部匹配](> host_re_find_all text=`内容` pattern=`模式`)*。 - -## 替换 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | -| 为 | any | 必填 | 替换匹配片段所用的文本 | -| 次数 | any | None | 最大替换次数;None 使用操作说明中的默认值 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 用为替换内容中匹配模式的部分;可选次数限制(缺省 = 全部) | - -这里使用`内容`、`模式`、`为`、`次数`=None。 - -调用效应:pure。 - -用为替换内容中匹配模式的部分;可选次数限制(缺省 = 全部)。 - -完成后返回*[用为替换内容中匹配模式的部分;可选次数限制(缺省 = 全部)](> host_re_replace text=`内容` pattern=`模式` with=`为` count=`次数`)*。 - -## 拆分 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 按模式拆分内容 | - -这里使用`内容`、`模式`。 - -调用效应:pure。 - -按模式拆分内容。 - -完成后返回*[按模式拆分内容](> host_re_split text=`内容` pattern=`模式`)*。 diff --git a/lib/浏览器.mq.md b/lib/浏览器.mq.md deleted file mode 100755 index 8605a19..0000000 --- a/lib/浏览器.mq.md +++ /dev/null @@ -1,718 +0,0 @@ ---- -markup: occlusion -title: lib/浏览器 -description: >- - 浏览器效应助手(WASM 客户端)。优先 GFM 表格 + 本库;勿用 json.set 链拼效应。 -import: - table: lib/table.mq.md - browser: lib/browser.mq.md ---- - -浏览器效应助手(WASM 客户端)。优先 GFM 表格 + 本库;勿用 json.set 链拼效应。 - -使用普通结构化值构造浏览器效果。 - -能力与边界:构造效果是纯数据变换,由官方 WASM 桥接在浏览器中执行。原生进程生成效果记录不表示 DOM 已更新;业务逻辑仍写在 Marqdo 中。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[crates/marqdo-wasm/js/marqdo-bridge.js](../crates/marqdo-wasm/js/marqdo-bridge.js) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 设文本 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 set_text 效应 | - -这里使用`选择器`、`文本`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/浏览器.mq.md 设文本 '选择器="#status"' '文本="Ready"' --effects none --json -``` - -构造 set_text 效应。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`文本`))**。 -完成后返回*[在新记录中设置 set_text 字段](table.put(in=None, at="set_text", value=`m`))*。 - -## 设HTML - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| html | any | 必填 | HTML 片段;普通不可信文本应使用设文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 set_html 效应 | - -这里使用`选择器`、`html`。 - -调用效应:pure。 - -构造 set_html 效应。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`html`))**。 -完成后返回*[在新记录中设置 set_html 字段](table.put(in=None, at="set_html", value=`m`))*。 - -## 设值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 set_value 效应 | - -这里使用`选择器`、`值`。 - -调用效应:pure。 - -构造 set_value 效应。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`值`))**。 -完成后返回*[在新记录中设置 set_value 字段](table.put(in=None, at="set_value", value=`m`))*。 - -## 设类 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 类 | any | 必填 | 以空格分隔的 CSS 类名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 set_class 效应 | - -这里使用`选择器`、`类`。 - -调用效应:pure。 - -构造 set_class 效应。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 -完成后返回*[在新记录中设置 set_class 字段](table.put(in=None, at="set_class", value=`m`))*。 - -## 加类 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 类 | any | 必填 | 以空格分隔的 CSS 类名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 add_class 效应(classList.add;可用空格分隔多个类名) | - -这里使用`选择器`、`类`。 - -调用效应:pure。 - -构造 add_class 效应(classList.add;可用空格分隔多个类名)。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 -完成后返回*[在新记录中设置 add_class 字段](table.put(in=None, at="add_class", value=`m`))*。 - -## 去类 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 类 | any | 必填 | 以空格分隔的 CSS 类名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 remove_class 效应 | - -这里使用`选择器`、`类`。 - -调用效应:pure。 - -构造 remove_class 效应。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 -完成后返回*[在新记录中设置 remove_class 字段](table.put(in=None, at="remove_class", value=`m`))*。 - -## 切类 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 类 | any | 必填 | 以空格分隔的 CSS 类名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 toggle_class 效应 | - -这里使用`选择器`、`类`。 - -调用效应:pure。 - -构造 toggle_class 效应。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 -完成后返回*[在新记录中设置 toggle_class 字段](table.put(in=None, at="toggle_class", value=`m`))*。 - -## 设样式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 样式 | any | 必填 | 目标元素的 CSS 属性与值记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 set_style 效应;样式为属性表或 cssText 字符串 | - -这里使用`选择器`、`样式`。 - -调用效应:pure。 - -构造 set_style 效应;样式为属性表或 cssText 字符串。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`样式`))**。 -完成后返回*[在新记录中设置 set_style 字段](table.put(in=None, at="set_style", value=`m`))*。 - -## 设属性 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 属性 | any | 必填 | 目标元素的 HTML 属性与值记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 set_attr 效应 | - -这里使用`选择器`、`属性`。 - -调用效应:pure。 - -构造 set_attr 效应。 - -得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`属性`))**。 -完成后返回*[在新记录中设置 set_attr 字段](table.put(in=None, at="set_attr", value=`m`))*。 - -## 包装 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 单键效应包装 | - -这里使用`键`、`值`。 - -调用效应:pure。 - -单键效应包装。 - -完成后返回*[返回更新后的结构化值](table.put(in=None, at=`键`, value=`值`))*。 - -## 合并 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 甲 | any | 必填 | 第一个浏览器效果记录 | -| 乙 | any | 必填 | 合入第一个记录的浏览器效果记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 合并两张效应表,右侧优先 | - -这里使用`甲`、`乙`。 - -调用效应:pure。 - -合并两张效应表,右侧优先。 - -完成后返回*[调用 merge](table.merge(a=`甲`, b=`乙`))*。 - -## 画布 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 命令 | any | 必填 | 按执行顺序排列的画布绘制命令列表 | -| 清空 | any | True | 绘制命令前是否清空画布 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 canvas 效应;命令一般为 @ 行表 | - -这里使用`选择器`、`命令`、`清空`=True。 - -调用效应:pure。 - -构造 canvas 效应;命令一般为 @ 行表。 - -`spec` = - -| sel | clear | commands | -|-----|-------|----------| -| `选择器` | `清空` | `命令` | - -完成后返回*[在新记录中设置 canvas 字段](table.put(in=None, at="canvas", value=`spec`))*。 - -## 音频 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 操作 | any | "play" | 音频命令:play、pause 或 stop | -| id | any | "default" | 音频通道标识 | -| 源 | any | "" | 音频 URL;beep 表示合成提示音 | -| 频率 | any | None | 振荡器频率,单位 Hz | -| 毫秒 | any | None | 时长或延迟,单位毫秒 | -| 选择器 | any | "" | 目标浏览器元素的 CSS 选择器 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 audio 效应 | - -这里使用`操作`="play"、`id`="default"、`源`=""、`频率`=None、`毫秒`=None、`选择器`=""。 - -调用效应:pure。 - -构造 audio 效应。 - -本函数只返回效果记录,不会立刻播放声音。播放源、合成频率与音频元素按桥接规则选择;浏览器可能要求用户先交互。 - -得到**`spec` = [在新记录中设置 op 字段](table.put(in=None, at="op", value=`操作`))**。 -得到**`spec` = [在新记录中设置 id 字段](table.put(in=`spec`, at="id", value=`id`))**。 -1. `源` != "" - 得到**`spec` = [在新记录中设置 src 字段](table.put(in=`spec`, at="src", value=`源`))**。 -1. `频率` != None - 得到**`spec` = [在新记录中设置 freq 字段](table.put(in=`spec`, at="freq", value=`频率`))**。 -1. `毫秒` != None - 得到**`spec` = [在新记录中设置 ms 字段](table.put(in=`spec`, at="ms", value=`毫秒`))**。 -1. `选择器` != "" - 得到**`spec` = [在新记录中设置 sel 字段](table.put(in=`spec`, at="sel", value=`选择器`))**。 -完成后返回*[在新记录中设置 audio 字段](table.put(in=None, at="audio", value=`spec`))*。 - -## 读文件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | -| 格式 | any | "text" | 浏览器桥接读取文件所用的内容表示 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 read_file 效应 | - -这里使用`选择器`、`然后`、`格式`="text"。 - -调用效应:pure。 - -构造 read_file 效应。 - -`spec` = - -| sel | as | then | -|-----|----|------| -| `选择器` | `格式` | `然后` | - -完成后返回*[在新记录中设置 read_file 字段](table.put(in=None, at="read_file", value=`spec`))*。 - -## 观察 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 规格 | any | 必填 | 效果规格;使用单条记录或 @ 行记录列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 observe 效应 | - -这里使用`规格`。 - -调用效应:pure。 - -构造 observe 效应。 - -完成后返回*[在新记录中设置 observe 字段](table.put(in=None, at="observe", value=`规格`))*。 - -## 取消观察 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 规格 | any | 必填 | 效果规格;使用单条记录或 @ 行记录列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 unobserve 效应 | - -这里使用`规格`。 - -调用效应:pure。 - -构造 unobserve 效应。 - -完成后返回*[在新记录中设置 unobserve 字段](table.put(in=None, at="unobserve", value=`规格`))*。 - -## 聚焦 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造目标元素的聚焦效果;浏览器桥接在处理函数返回后执行 | - -这里使用`选择器`。 - -调用效应:pure。 - -构造目标元素的聚焦效果;浏览器桥接在处理函数返回后执行。 - -完成后返回*[在新记录中设置 focus 字段](table.put(in=None, at="focus", value=`选择器`))*。 - -## 导航 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 替换 | any | False | 导航时是否替换当前历史项 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 navigate 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | - -这里使用`url`、`替换`=False。 - -调用效应:pure。 - -构造 navigate 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 - -`spec` = - -| url | replace | -|-----|---------| -| `url` | `替换` | - -完成后返回*[在新记录中设置 navigate 字段](table.put(in=None, at="navigate", value=`spec`))*。 - -## 存设 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | -| 作用域 | any | "memory" | 存储范围:memory、local 或 session | -| 然后 | any | "" | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | SPA 客户端状态写入 | - -这里使用`键`、`值`、`作用域`="memory"、`然后`=""。 - -调用效应:pure。 - -SPA 客户端状态写入。优先 `作用域=memory`(页内内存)。 -可选 `然后`:写入后回调,参数含 `{ok, op, key, scope}`。 - -`spec` = - -| op | key | value | scope | -| ---- | ----- | ------- | ------- | -| set | `键` | `值` | `作用域` | - -1. `然后` != "" - 得到**`spec` = [在新记录中设置 then 字段](table.put(in=`spec`, at="then", value=`然后`))**。 -完成后返回*[在新记录中设置 storage 字段](table.put(in=None, at="storage", value=`spec`))*。 - -## 存取 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | -| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | -| 作用域 | any | "memory" | 存储范围:memory、local 或 session | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 读取键并回调 `然后`,参数含 `{ok, value, found, key, scope}` | - -这里使用`键`、`然后`、`作用域`="memory"。 - -调用效应:pure。 - -读取键并回调 `然后`,参数含 `{ok, value, found, key, scope}`。 - -`spec` = - -| op | key | then | scope | -| ---- | ----- | ------ | ------- | -| get | `键` | `然后` | `作用域` | - -完成后返回*[在新记录中设置 storage 字段](table.put(in=None, at="storage", value=`spec`))*。 - -## 页跳 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 替换 | any | False | 导航时是否替换当前历史项 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | SPA 导航(bridge `navigate`) | - -这里使用`url`、`替换`=False。 - -调用效应:pure。 - -SPA 导航(bridge `navigate`)。 - -`spec` = - -| url | replace | -|-----|---------| -| `url` | `替换` | - -完成后返回*[在新记录中设置 navigate 字段](table.put(in=None, at="navigate", value=`spec`))*。 - -## 存储 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 规格 | any | 必填 | 存储操作记录:op、key、scope,以及可选 value 和 then | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 把存储规格包装为浏览器效果;桥接处理 op、key、value、scope 和 then | - -这里使用`规格`。 - -调用效应:pure。 - -把存储规格包装为浏览器效果;桥接处理 op、key、value、scope 和 then。 - -完成后返回*[在新记录中设置 storage 字段](table.put(in=None, at="storage", value=`规格`))*。 - -## 定时 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 毫秒 | any | 必填 | 时长或延迟,单位毫秒 | -| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | -| id | any | "default" | 定时器标识,之后传给清除定时器 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 interval 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | - -这里使用`毫秒`、`然后`、`id`="default"。 - -调用效应:pure。 - -构造 interval 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 - -`spec` = - -| ms | then | id | -|----|------|----| -| `毫秒` | `然后` | `id` | - -完成后返回*[在新记录中设置 interval 字段](table.put(in=None, at="interval", value=`spec`))*。 - -## 清定时 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| id | any | "default" | 对应创建或启动操作返回的标识 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 使用创建定时器时相同的标识,构造取消定时器效果 | - -这里使用`id`="default"。 - -调用效应:pure。 - -使用创建定时器时相同的标识,构造取消定时器效果。 - -得到**`spec` = [在新记录中设置 id 字段](table.put(in=None, at="id", value=`id`))**。 -完成后返回*[在新记录中设置 clear_interval 字段](table.put(in=None, at="clear_interval", value=`spec`))*。 - -## 拉取 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | -| 方法 | any | "GET" | HTTP 方法,例如 GET 或 POST | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 fetch 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | - -这里使用`url`、`然后`、`方法`="GET"。 - -调用效应:pure。 - -构造 fetch 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 - -`spec` = - -| url | then | method | -|-----|------|--------| -| `url` | `然后` | `方法` | - -完成后返回*[在新记录中设置 fetch 字段](table.put(in=None, at="fetch", value=`spec`))*。 - -## 拉取全部 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 请求 | any | 必填 | 按顺序排列的浏览器请求规格记录列表 | -| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 fetch_all 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | - -这里使用`请求`、`然后`。 - -调用效应:pure。 - -构造 fetch_all 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 - -`spec` = - -| requests | then | -|----------|------| -| `请求` | `然后` | - -完成后返回*[在新记录中设置 fetch_all 字段](table.put(in=None, at="fetch_all", value=`spec`))*。 - -## 延后 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 毫秒 | any | 必填 | 时长或延迟,单位毫秒 | -| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 after 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | - -这里使用`毫秒`、`然后`。 - -调用效应:pure。 - -构造 after 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 - -`spec` = - -| ms | then | -|----|------| -| `毫秒` | `然后` | - -完成后返回*[在新记录中设置 after 字段](table.put(in=None, at="after", value=`spec`))*。 - -## 套接字 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 规格 | any | 必填 | 一条桥接效果规格记录 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 把 WebSocket 操作规格包装为浏览器桥接效果;本函数不会打开原生套接字 | - -这里使用`规格`。 - -调用效应:pure。 - -把 WebSocket 操作规格包装为浏览器桥接效果;本函数不会打开原生套接字。 - -完成后返回*[在新记录中设置 ws 字段](table.put(in=None, at="ws", value=`规格`))*。 - -## 剪贴板 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 按文本构造剪贴板效果;消费效果时仍受浏览器权限和用户手势要求约束 | - -这里使用`文本`。 - -调用效应:pure。 - -按文本构造剪贴板效果;消费效果时仍受浏览器权限和用户手势要求约束。 - -得到**`spec` = [在新记录中设置 text 字段](table.put(in=None, at="text", value=`文本`))**。 -完成后返回*[在新记录中设置 clipboard 字段](table.put(in=None, at="clipboard", value=`spec`))*。 - -## 下载 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 正文 | any | 必填 | 请求正文;文档操作中为替换正文 | -| 文件名 | any | "download.txt" | 建议的下载文件名 | -| mime | any | "text/plain;charset=utf-8" | 内容的 MIME 类型 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 构造 download 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | - -这里使用`正文`、`文件名`="download.txt"、`mime`="text/plain;charset=utf-8"。 - -调用效应:pure。 - -构造 download 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 - -`spec` = - -| body | filename | mime | -|------|----------|------| -| `正文` | `文件名` | `mime` | - -完成后返回*[在新记录中设置 download 字段](table.put(in=None, at="download", value=`spec`))*。 - -## 渲染列表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 选择器 | text | 必填 | 已有列表容器的 CSS 选择器 | -| 条目 | list | 必填 | 字面文字或含 tag、text 或 children、class、attrs 的记录列表 | -| 标签 | text | "li" | 官方桥使用的元素名,通常为 li | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 交给官方浏览器桥执行的纯列表更新指令 | - -这里使用`选择器`、`条目`和`标签`="li"。动态数据按记录传入,文字放在 text,委托事件需要的标识放在 attrs 的 data-id;无需手动拼接列表 HTML。官方桥会转义普通文字,但构造指令不表示已经更新页面,也不验证选择器确实存在。标签与属性名由应用决定,业务输入应保留为文字。页面最初的容器布局仍由 Document 组件负责,这个工具只替换已存在列表的条目。 - -记录还可包含 tag 与 children,children 是同样结构的文本/控件记录列表。例如一条 li 内先放 span 文本,再放带 data-id 的 button,删除交互就不需要拼 HTML。text、html 与 children 不混用;嵌套最多 32 层,总记录最多 10000。元素名和属性名经过结构检查,事件属性与活动 URL 被拒绝。用户内容放 text,原有 html 只保留明确的兼容出口。 - -下例直接返回组合指令,不加载服务器插件,也不执行浏览器 IO;真实的 [浏览器工程](../examples/browser-app/static/app.mq.md) 使用同一结构。元素、属性名与兼容 html 都属于作者决定的能力,外部业务值应只进入 text 或标量属性值。结构检查不能替代对显式原生 HTML 的内容清理。 - -```sh -marqdo call lib/浏览器.mq.md 渲染列表 '选择器="#items"' '条目=[{"tag":"li","children":[{"tag":"span","text":"字面 <文字> & 内容"},{"tag":"button","text":"删除","attrs":{"type":"button","data-id":"1"}}]}]' --effects none --json -``` - -完成后返回*[描述已有列表的文字更新](browser.render_list(sel=`选择器`, items=`条目`, tag=`标签`))*. diff --git a/lib/系统.mq.md b/lib/系统.mq.md deleted file mode 100755 index 3fa49ad..0000000 --- a/lib/系统.mq.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -markup: occlusion -title: lib/系统 -description: 中文系统包装(加载环境 可选 路径=) ---- - -中文系统包装(加载环境 可选 路径=) - -读取执行元数据并与宿主系统交互。 - -能力与边界:元信息与模块源码来自入口文档,不是被导入库。执行进程需要 process.exec;读写环境和读取配置具有独立效应。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/sys.rs](../src/host/sys.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 取环境 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | any | 必填 | 环境变量名 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 读取环境变量名 | - -这里使用`名`。 - -调用效应:environment.read。 - -读取环境变量名。 - -完成后返回*[读取环境变量名](> host_env_get name=`名`)*。 - -## 设环境 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 名 | any | 必填 | 环境变量名 | -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 设置环境变量名的值 | - -这里使用`名`、`值`。 - -调用效应:environment.write。 - -设置环境变量名的值。 - -完成后返回*[设置环境变量名的值](> host_env_set name=`名` value=`值`)*。 - -## 加载环境 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | None | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 加载 `.env`(可选具名实参 `路径=`) | - -这里使用`路径`=None。 - -调用效应:environment.write,fs.read。 - -加载 `.env`(可选具名实参 `路径=`)。不覆盖已有进程环境变量。 - -完成后返回*[加载 .env(可选具名实参 路径=)](> host_dotenv_load path=`路径`)*。 - -## 参数表 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 进程参数表 | - -调用效应:pure。 - -进程参数表。 - -完成后返回*[进程参数表](host_args())*。 - -## 工作目录 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 当前工作目录 | - -调用效应:pure。 - -当前工作目录。 - -完成后返回*[当前工作目录](host_cwd())*。 - -## 元信息 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 入口 `.mq.md` 已绑定的 Artifact Metadata(映射) | - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/系统.mq.md 元信息 --effects none --json -``` - -入口 `.mq.md` 已绑定的 Artifact Metadata(映射)。见 `doc/design/binding.md`。 - -完成后返回*[入口 .mq.md 已绑定的 Artifact Metadata(映射)](host_meta())*。 - -## 取元信息 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 按键取一条元信息;缺失 → None | - -这里使用`键`。 - -调用效应:pure。 - -按键取一条元信息;缺失 → None。 - -完成后返回*[按键取一条元信息;缺失 → None](> host_meta_get key=`键`)*。 - -## 工件种类 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 入口 Artifact 分类:`web` / `endpoint` / `prompt` / `other`;无 `type`/`类型` → None | - -调用效应:pure。 - -入口 Artifact 分类:`web` / `endpoint` / `prompt` / `other`;无 `type`/`类型` → None。ADR 0007。 - -完成后返回*[入口 Artifact 分类:web / endpoint / prompt / other;无 type/类型 → None](host_artifact_kind())*。 - -## 模块源码 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 入口 `.mq.md` 全文(供 document-as-prompt) | - -调用效应:pure。 - -入口 `.mq.md` 全文(供 document-as-prompt)。未设置时为空文本。 - -完成后返回*[入口 .mq.md 全文(供 document-as-prompt)](host_module_source())*。 - -## 退出 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 码 | any | 必填 | 进程退出码;零表示成功 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 以代码退出进程 | - -这里使用`码`。 - -调用效应:process.control。 - -以代码退出进程。 - -完成后返回*[以代码退出进程](> host_exit code=`码`)*。 - -## 执行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 命令 | any | 必填 | 可执行命令或解释器覆盖配置 | -| 参数 | any | None | 传给命令或函数的实参列表 | -| 捕获 | any | False | 是否返回命令输出而非直接转发 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 运行子进程 | - -这里使用`命令`、`参数`=None、`捕获`=False。 - -调用效应:process.exec。 - -运行子进程。默认返回退出码(整数)。 - -`捕获=True` 时返回映射 `{code, stdout, stderr}`(过大输出可能截断)。 - -在 `**…**` 内优先写裸变量 `参数=参数`;`` 参数=`参数` `` 亦可。 - -完成后返回*[运行子进程](> host_exec cmd=`命令` args=`参数` capture=`捕获`)*。 - -## 发布流事件 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 事件 | any | 必填 | 发布到当前流的结构化事件 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 向进程内 EventBus 发布流事件(供 `marqdo view` SSE) | - -这里使用`事件`。 - -调用效应:output.write。 - -向进程内 EventBus 发布流事件(供 `marqdo view` SSE)。无订阅者时为空操作。 - -完成后返回*[向进程内 EventBus 发布流事件(供 marqdo view SSE)](> host_stream_publish event=`事件`)*。 diff --git a/lib/结果.mq.md b/lib/结果.mq.md deleted file mode 100755 index 068e21f..0000000 --- a/lib/结果.mq.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -markup: occlusion ---- - -可恢复结果使用普通记录 ok/value/error;error 内含 code/message/operation。 -先判断 ok 再使用 value;结果包装不会绕过宿主权限检查。 - -以统一数据契约组合可恢复结果。 - -能力与边界:先检查 ok,再使用 value;HTTP 状态和子进程退出码仍需按领域规则判断;错误含 code/message/operation。尝试接口处理已定义的可恢复失败,不是捕获任意运行时错误的异常系统,也不会授予权限。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/result.rs](../src/host/result.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 成功 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 值 | any | 必填 | 成功操作的值,包括 None | - -| 返回 | 类型 | 说明 | -|------|------|------| -| 结果 | map | Successful Result | - -这里使用`值`。 - -将当前输入交给 成功,保留同源能力的返回值和失败语义。 - -调用效应:pure。 - -`out` = - -| ok | value | error | -|----|-------|-------| -| True | `值` | None | - -完成后返回*out*。 - -## 失败 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 错误码 | text | 必填 | 供程序判断的稳定错误类别 | -| 消息 | text | 必填 | 供人阅读的错误解释 | -| 操作 | text | "application" | 发生失败的操作名 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| 结果 | map | Failed Result | - -这里使用`错误码`、`消息`、`操作`="application"。 - -将当前输入交给 失败,保留同源能力的返回值和失败语义。 - -调用效应:pure。 - -`failure` = - -| code | message | operation | -|------|---------|-----------| -| `错误码` | `消息` | `操作` | - -`out` = - -| ok | value | error | -|----|-------|-------| -| False | None | `failure` | - -完成后返回*out*。 - -## 值或默认 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 结果 | map | 必填 | 可恢复操作返回的结果记录 | -| 默认值 | any | None | 操作失败时明确采用的替代值 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| 结果 | any | Successful value or fallback | - -这里使用`结果`、`默认值`=None。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/结果.mq.md 值或默认 '结果={"ok":false,"value":null,"error":{"code":"missing","message":"absent","operation":"example"}}' '默认值="fallback"' --effects none --json -``` - -只在 ok 为真时读取 value;成功且值为 None 时仍保留 None。仅在操作失败时使用默认值,不按真假性吞掉零或空文本。 - -1. [operation succeeded](access(`结果`, "ok")) - 完成后返回*[successful value](access(结果, "value"))*。 -2. * - 完成后返回*默认值*。 diff --git a/lib/统计.mq.md b/lib/统计.mq.md deleted file mode 100755 index 48b20bc..0000000 --- a/lib/统计.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/统计 -description: 薄均值 / 中位数 / 样本标准差(中层 Mid2 M10)。非数据框库。 ---- - -薄数值摘要。不是数据框库。 - -计算基础描述统计。 - -能力与边界:均值和中位数要求非空数字列表;这不是数据帧或数值数组运行时。矩阵计算由线性代数扩展负责。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/stats.rs](../src/host/stats.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 均值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | any | 必填 | 输入列表;不可变更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 列表的算术均值 | - -这里使用`列表`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/统计.mq.md 均值 '列表=[1,2,3]' --effects none --json -``` - -列表的算术均值。 - -调用例:[统计.均值] 列表=`xs` - -完成后返回*[列表的算术均值](> host_stats_mean list=`列表`)*。 - -## 中位数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | any | 必填 | 输入列表;不可变更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 列表的中位数 | - -这里使用`列表`。 - -调用效应:pure。 - -列表的中位数。 - -完成后返回*[列表的中位数](> host_stats_median list=`列表`)*。 - -## 标准差 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | any | 必填 | 输入列表;不可变更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 样本标准差;至少两个值 | - -这里使用`列表`。 - -调用效应:pure。 - -样本标准差;至少两个值。 - -完成后返回*[样本标准差;至少两个值](> host_stats_stdev list=`列表`)*。 diff --git a/lib/编码.mq.md b/lib/编码.mq.md deleted file mode 100755 index 4750d43..0000000 --- a/lib/编码.mq.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -markup: occlusion -title: lib/编码 -description: Base64、十六进制与基32编解码(中层 M1 + Mid2 M8)。UTF-8 文本往返。 ---- - -Base64、十六进制与基32编解码。UTF-8 文本往返。 - -在 UTF-8 文本与 Base64、十六进制、Base32 之间转换。 - -能力与边界:这些历史接口用于文本往返。任意二进制应使用字节库的从编码;把无效 UTF-8 解码为文本会失败。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/encoding.rs](../src/host/encoding.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 基64编码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对内容做 Base64 编码 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/编码.mq.md 基64编码 '内容="Marqdo"' --effects none --json -``` - -对内容做 Base64 编码。 - -调用例:[编码.基64编码] 内容=`s` - -完成后返回*[对内容做 Base64 编码](> host_encoding_base64_encode text=`内容`)*。 - -## 基64解码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对内容做 Base64 解码 | - -这里使用`内容`。 - -调用效应:pure。 - -对内容做 Base64 解码。 - -完成后返回*[对内容做 Base64 解码](> host_encoding_base64_decode text=`内容`)*。 - -## 十六进制编码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对内容做十六进制编码 | - -这里使用`内容`。 - -调用效应:pure。 - -对内容做十六进制编码。 - -完成后返回*[对内容做十六进制编码](> host_encoding_hex_encode text=`内容`)*。 - -## 十六进制解码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对内容做十六进制解码 | - -这里使用`内容`。 - -调用效应:pure。 - -对内容做十六进制解码。 - -完成后返回*[对内容做十六进制解码](> host_encoding_hex_decode text=`内容`)*。 - -## 基32编码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对内容做基32编码(RFC 4648;= 填充) | - -这里使用`内容`。 - -调用效应:pure。 - -对内容做基32编码(RFC 4648;= 填充)。 - -完成后返回*[对内容做基32编码(RFC 4648;= 填充)](> host_encoding_base32_encode text=`内容`)*。 - -## 基32解码 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对内容做基32解码 | - -这里使用`内容`。 - -调用效应:pure。 - -对内容做基32解码。 - -完成后返回*[对内容做基32解码](> host_encoding_base32_decode text=`内容`)*。 diff --git a/lib/网络.mq.md b/lib/网络.mq.md deleted file mode 100755 index c3985c0..0000000 --- a/lib/网络.mq.md +++ /dev/null @@ -1,295 +0,0 @@ ---- -markup: occlusion -import: - table: lib/table.mq.md - text: lib/text.mq.md -title: lib/网络 -description: 中文 HTTP(S) 包装。可选 headers / content_type 经宿主别名绑定。 ---- - -中文 HTTP(S) 包装。可选 headers / content_type 经宿主别名绑定。 - -处理 HTTP、响应数据和有界下载。 - -能力与边界:读取只需 network.read;可恢复请求的方法可动态变化,因此保守要求 network.write。响应头是 name/values 行记录,可用响应头值取值。下载还需 fs.write;旧接口保留原契约。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/net.rs](../src/host/net.rs)、[src/host/net_ops.rs](../src/host/net_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 获取 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| headers | any | None | HTTP 头名称与值记录;None 不附加额外头 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 支持 HTTPS | - -这里使用`地址`、`headers`=None。 - -调用效应:network.read。 - -支持 HTTPS。可选具名实参 `headers=`(映射)。 - -完成后返回*[支持 HTTPS](> host_http_get url=`地址` headers=`headers`)*。 - -## 提交 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 内容 | any | 必填 | 请求正文;文档操作中为替换正文 | -| content_type | any | None | HTTP 内容类型覆盖;None 使用接口默认值 | -| headers | any | None | HTTP 头名称与值记录;None 不附加额外头 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 默认 Content-Type 为 JSON | - -这里使用`地址`、`内容`、`content_type`=None、`headers`=None。 - -调用效应:network.write。 - -默认 Content-Type 为 JSON。可选 `content_type=` / `headers=`。 - -完成后返回*[默认 Content-Type 为 JSON](> host_http_post url=`地址` body=`内容` content_type=`content_type` headers=`headers`)*。 - -## 提交流式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 内容 | any | 必填 | 请求正文;文档操作中为替换正文 | -| content_type | any | None | HTTP 内容类型覆盖;None 使用接口默认值 | -| headers | any | None | HTTP 头名称与值记录;None 不附加额外头 | -| 打印增量 | any | False | 是否在接收 SSE 时打印增量文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | POST 并消费 OpenAI 兼容 SSE | - -这里使用`地址`、`内容`、`content_type`=None、`headers`=None、`打印增量`=False。 - -调用效应:network.write。 - -POST 并消费 OpenAI 兼容 SSE。返回 `{status, events}`(`delta` / `done` / `error`)。`打印增量=真` 时边读边打印增量文本。 - -完成后返回*[POST 并消费 OpenAI 兼容 SSE](> host_http_post_sse url=`地址` body=`内容` content_type=`content_type` headers=`headers` echo=`打印增量`)*。 - -## 解析流式 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 打印增量 | any | False | 是否在接收 SSE 时打印增量文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 离线解析 OpenAI 聊天 SSE 正文为事件列表(不联网) | - -这里使用`内容`、`打印增量`=False。 - -调用效应:pure。 - -离线解析 OpenAI 聊天 SSE 正文为事件列表(不联网)。 - -完成后返回*[离线解析 OpenAI 聊天 SSE 正文为事件列表(不联网)](> host_openai_sse_parse text=`内容` echo=`打印增量`)*。 - -## 请求 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 方法 | any | 必填 | HTTP 方法,例如 GET 或 POST | -| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 正文 | any | None | 请求正文;文档操作中为替换正文 | -| content_type | any | None | HTTP 内容类型覆盖;None 使用接口默认值 | -| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 可选 `body=` / `content_type=` / `headers=` | - -这里使用`方法`、`地址`、`正文`=None、`content_type`=None、`表头`=None。 - -调用效应:network.write。 - -可选 `body=` / `content_type=` / `headers=`。 - -完成后返回*[可选 body= / content_type= / headers=](> host_http_request method=`方法` url=`地址` body=`正文` content_type=`content_type` headers=`表头`)*。 - -## 编码地址 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对 URL 段做百分号编码 | - -这里使用`内容`。 - -调用效应:pure。 - -对 URL 段做百分号编码。 - -完成后返回*[对 URL 段做百分号编码](> host_url_encode text=`内容`)*。 - -## 解析Cookie - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | -| 是响应头 | any | False | 是否按响应头而非请求头解析 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 解析 `Cookie` 请求头(默认)或一个/多个 `Set-Cookie` 响应头(`是响应头=真`)为 `{name, value, path, domain, expires, max_age, secure, http_only, same_site}` 列表 | - -这里使用`内容`、`是响应头`=False。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/网络.mq.md 解析Cookie '内容="a=1; b=2"' --effects none --json -``` - -解析 `Cookie` 请求头(默认)或一个/多个 `Set-Cookie` 响应头(`是响应头=真`)为 `{name, value, path, domain, expires, max_age, secure, http_only, same_site}` 列表。 - -完成后返回*[解析 Cookie 请求头(默认)或一个/多个 Set-Cookie 响应头(是响应头=真)为 {name, value, path, domain, expires, max_age, secure, http_only, same_site} 列表](> host_cookie_parse text=`内容` is_response=`是响应头`)*。 - -## 解析多部分 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 正文 | any | 必填 | 请求正文;文档操作中为替换正文 | -| 边界 | any | 必填 | Content-Type 头中的 multipart 分隔标记 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 解析 `multipart/form-data` 请求体(给定 `boundary`)为 `{name, filename?, content_type?, value}` 部件列表 | - -这里使用`正文`、`边界`。 - -调用效应:pure。 - -解析 `multipart/form-data` 请求体(给定 `boundary`)为 `{name, filename?, content_type?, value}` 部件列表。 - -完成后返回*[解析 multipart/form-data 请求体(给定 boundary)为 {name, filename?, content_type?, value} 部件列表](> host_multipart_parse body=`正文` boundary=`边界`)*。 - -## 解析Markdown - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 将 Markdown / GFM 解析为 HTML(纯转换,无网络 I/O) | - -这里使用`文本`。 - -调用效应:pure。 - -将 Markdown / GFM 解析为 HTML(纯转换,无网络 I/O)。 - -完成后返回*[将 Markdown / GFM 解析为 HTML(纯转换,无网络 I/O)](> host_markdown_parse text=`文本`)*。 - -## 可恢复请求 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 方法 | text | 必填 | HTTP 方法,例如 GET 或 POST | -| 地址 | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 正文 | any | None | 请求正文;文档操作中为替换正文 | -| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | -| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | -| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | -| 响应类型 | text | "text" | 响应正文表示:text 或 bytes | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 返回统一结果记录;value 含 status、headers、body。响应头为 name/values 行记录。动态方法需要 network | - -这里使用`方法`、`地址`、`正文`=None、`表头`=None、`超时毫秒`=30000、`字节上限`=8388608、`响应类型`="text"。 - -调用效应:network.write。 - -正文可为文本、字节记录或空值;发送 JSON 前使用 json.stringify。请求头使用字典,响应头使用 name/values 行记录。输出参数和目标路径在联网前预检。 - -返回统一结果记录;value 含 status、headers、body。响应头为 name/values 行记录。动态方法需要 network.write;只读请求使用读取。HTTP 错误状态仍是响应,传输失败是错误。 - -完成后返回*[正文可为文本、字节记录或空值;发送 JSON 前使用 json.stringify](> host_http_request_result method=`方法` url=`地址` body=`正文` headers=`表头` timeout_ms=`超时毫秒` max_bytes=`字节上限` response=`响应类型`)*。 - -## 下载 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 地址 | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | -| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | -| 字节上限 | number | 67108864 | 读取或展开的字节上限;超限则失败 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 有界流式下载至文件;成功后原子替换,失败保留原文件。返回结果记录,value 含 status、headers、size、path;需要 network | - -这里使用`地址`、`路径`、`表头`=None、`超时毫秒`=30000、`字节上限`=67108864。 - -调用效应:fs.write,network.read。 - -有界流式下载至文件;成功后原子替换,失败保留原文件。返回结果记录,value 含 status、headers、size、path;需要 network.read 与 fs.write。 - -完成后返回*[有界流式下载至文件;成功后原子替换,失败保留原文件](> host_http_download url=`地址` path=`路径` headers=`表头` timeout_ms=`超时毫秒` max_bytes=`字节上限`)*。 - -## 读取 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 地址 | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | -| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | -| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | -| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | -| 响应类型 | text | "text" | 响应正文表示:text 或 bytes | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 只读 GET 请求,返回统一结果记录;只需 network | - -这里使用`地址`、`表头`=None、`超时毫秒`=30000、`字节上限`=8388608、`响应类型`="text"。 - -调用效应:network.read。 - -只读 GET 请求,返回统一结果记录;只需 network.read。响应头为 name/values 行记录,响应类型可选 text/bytes。 - -完成后返回*[只读 GET 请求,返回统一结果记录;只需 network.read](> host_http_get_result url=`地址` headers=`表头` timeout_ms=`超时毫秒` max_bytes=`字节上限` response=`响应类型`)*。 - -## 响应头值 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 响应头 | list | 必填 | 响应中的 headers 行记录 | -| 名称 | text | 必填 | 头部名称 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 同名头部的全部值 | - -这里使用`响应头`、`名称`。 - -调用效应:pure。 - -从响应头行记录中按不区分大小写的名称取全部值;不存在返回空列表。请求的 headers 参数仍使用字典,响应 headers 使用行记录以保留任意名称和重复值。 - -得到**`lower` = [调用 to lower](text.to_lower(text=`名称`))**。 -得到**`matches` = [调用 where](table.where(list=`响应头`, key="name", value=`lower`))**。 -得到**`values` = [调用 pluck](table.pluck(list=`matches`, key="values"))**。 -完成后返回*[调用 flatten](table.flatten(list=`values`))*。 diff --git a/lib/自写回.mq.md b/lib/自写回.mq.md deleted file mode 100755 index d881488..0000000 --- a/lib/自写回.mq.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -markup: occlusion -title: lib/自写回 -description: 将运行结果写回 .mq.md(Jupyter 式自写回) ---- - -将运行结果写回 .mq.md(Jupyter 式自写回) - -读取并维护持久化执行输出槽位。 - -能力与边界:记录与读取默认锚定入口的当前调用点;命名槽互相隔离。结构化章节修改使用文档库,而不是把自写回当作任意文档编辑器。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 - -实现入口:[src/host/writeback.rs](../src/host/writeback.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 写回 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | -| 末尾 | any | False | 是否追加到目标区块末尾 | -| 键 | any | None | 要读取、比较或更新的字段名或存储键 | -| 行 | any | None | 加入受管理写回区块的文本行 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 `![marqdo-out](…)`,否则写成 `` | - -这里使用`值`、`末尾`=False、`键`=None、`行`=None。 - -调用效应:fs.write。 - -在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 `![marqdo-out](…)`,否则写成 ``。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。 - -完成后返回*[在入口文件中写入自写回块:若 值 像图片路径/URL(.png / .svg / … 或 data:image/…)则写成 !marqdo-out(…),否则写成 ](> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`)*。 - -## 取 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 末尾 | any | False | 是否追加到目标区块末尾 | -| 键 | any | None | 要读取、比较或更新的字段名或存储键 | -| 行 | any | None | 加入受管理写回区块的文本行 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 读取当前调用处紧邻无键块、无键末尾块,或命名槽 | - -这里使用`末尾`=False、`键`=None、`行`=None。 - -调用效应:fs.read。 - -读取当前调用处紧邻无键块、无键末尾块,或命名槽。 - -完成后返回*[读取当前调用处紧邻无键块、无键末尾块,或命名槽](> host_writeback_get at_end=`末尾` key=`键` line=`行`)*。 - -## 清除 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 末尾 | any | False | 是否追加到目标区块末尾 | -| 键 | any | None | 要读取、比较或更新的字段名或存储键 | -| 行 | any | None | 加入受管理写回区块的文本行 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 删除紧邻块、末尾块或命名槽 | - -这里使用`末尾`=False、`键`=None、`行`=None。 - -调用效应:fs.write。 - -删除紧邻块、末尾块或命名槽。 - -完成后返回*[删除紧邻块、末尾块或命名槽](> host_writeback_clear at_end=`末尾` key=`键` line=`行`)*。 - -## 确保 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | -| 占位 | any | "pending" | 创建受管理区块时使用的占位文本 | -| 行 | any | None | 加入受管理写回区块的文本行 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 若命名槽不存在则创建并写入占位;已存在则不改动 | - -这里使用`键`、`占位`="pending"、`行`=None。 - -调用效应:fs.write。 - -若命名槽不存在则创建并写入占位;已存在则不改动。 - -完成后返回*[若命名槽不存在则创建并写入占位;已存在则不改动](> host_writeback_ensure key=`键` placeholder=`占位` line=`行`)*。 - -## 列出 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 列出当前入口源码中的受管理输出槽位;不写入,也不读取其他文件 | - -调用效应:fs.read。 - -列出当前入口源码中的受管理输出槽位;不写入,也不读取其他文件。 - -完成后返回*[列出当前入口源码中的受管理输出槽位;不写入,也不读取其他文件](host_writeback_list())*。 - -## 扫描路径 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 扫描任意文件中的自写回槽(注释块与 `![marqdo-out](…)` 图片;工作簿观察) | - -这里使用`路径`。 - -调用效应:fs.read。 - -直接调用此函数: - -```sh -marqdo call lib/自写回.mq.md 扫描路径 '路径="lib/writeback.mq.md"' --effects fs.read --fs-root . --json -``` - -扫描任意文件中的自写回槽(注释块与 `![marqdo-out](…)` 图片;工作簿观察)。 - -完成后返回*[扫描任意文件中的自写回槽(注释块与 !marqdo-out(…) 图片;工作簿观察)](> host_writeback_scan_path path=`路径`)*。 diff --git a/lib/表.mq.md b/lib/表.mq.md deleted file mode 100755 index 63e9d53..0000000 --- a/lib/表.mq.md +++ /dev/null @@ -1,1178 +0,0 @@ ---- -markup: occlusion -title: lib/表 -description: >- - 列表与字典。优先用「改」(路径 1-based,与access 取元同构);取/改位/切片为 0-based。 - json 只管解析/序列化。 ---- - -列表与字典。嵌套写入优先「改」;作者程序里读元用access 取元,不要新写脚注取元。 - -用明确的数据形态变换列表、字典和行记录。 - -能力与边界:access 与改的整数路径从一开始;取、切片、插入、删位等旧接口从零开始。更新返回新值,必须保存。行数只是长度别名;列转行、行转列明确转换形态。相等比较沿用运行时的类型和字典顺序规则。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/collection.rs](../src/host/collection.rs)、[src/host/collection_ops.rs](../src/host/collection_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 改 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 入 | any | 必填 | 输入集合;None 用于创建新记录 | -| 于 | any | 必填 | 文本键、从一开始的下标,或由键与下标组成的嵌套路径 | -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 把集合入在路径于上的那一元改成值 | - -这里使用`入`、`于`、`值`。 - -调用效应:pure。 - -把集合入在路径于上的那一元改成值。 - -于可以是文本键、1-based 下标,或键/下标组成的路径列表(与access 取元嵌套同构)。 - -调用例:[表.改] 入=None 于="Authorization" 值="Bearer-x" - -完成后返回*[把集合入在路径于上的那一元改成值](> host_collection_put in=`入` at=`于` value=`值`)*。 - -## 长度 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | 必填 | 本操作要求的输入列表或集合 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 列表或字典 xs 的长度 | - -这里使用`xs`。 - -调用效应:pure。 - -列表或字典 xs 的长度。 - -完成后返回*[调用 len](len(`xs`))*。 - -## 行数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | 必填 | 本操作要求的输入列表或集合 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | 列表 xs 的行数(同长度) | - -这里使用`xs`。 - -调用效应:pure。 - -列表 xs 的行数(同长度)。 - -完成后返回*[调用 len](len(`xs`))*。 - -## 取 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | 必填 | 本操作要求的输入列表或集合 | -| i | number | 必填 | 从零开始的元素或行下标 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 从零起取 xs 的第 i 项(与内置 at 相同) | - -这里使用`xs`、`i`。 - -调用效应:pure。 - -从零起取 xs 的第 i 项(与内置 at 相同)。越界 → None。 - -完成后返回*[调用 at](at(value=`xs`, index=`i`))*。 - -## 取行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| xs | any | 必填 | 本操作要求的输入列表或集合 | -| i | number | 必填 | 从零开始的元素或行下标 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 从零起取 xs 的第 i 行 | - -这里使用`xs`、`i`。 - -调用效应:pure。 - -从零起取 xs 的第 i 行。 - -完成后返回*[调用 at](at(value=`xs`, index=`i`))*。 - -## 追加 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| item | any | 必填 | 要插入、替换或比较的元素 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 在 list 末尾追加 item | - -这里使用`list`、`item`。 - -调用效应:pure。 - -在 list 末尾追加 item。 - -完成后返回*[在 list 末尾追加 item](> host_list_append list=`list` item=`item`)*。 - -## 前插 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| item | any | 必填 | 要插入、替换或比较的元素 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 在 list 开头插入 item | - -这里使用`list`、`item`。 - -调用效应:pure。 - -在 list 开头插入 item。 - -完成后返回*[在 list 开头插入 item](> host_list_prepend list=`list` item=`item`)*。 - -## 拼接 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 第一个列表;None 用作空列表种子 | -| b | any | 必填 | 追加到 a 后面的列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 拼接列表 a 与 b | - -这里使用`a`、`b`。 - -调用效应:pure。 - -拼接列表 a 与 b。 - -完成后返回*[拼接列表 a 与 b](> host_list_concat a=`a` b=`b`)*。 - -## 插入 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| index | number | 必填 | 插入、替换或删除的位置,从零开始 | -| item | any | 必填 | 要插入、替换或比较的元素 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 在 list 的从零起 index 处插入 item | - -这里使用`list`、`index`、`item`。 - -调用效应:pure。 - -在 list 的从零起 index 处插入 item。 - -完成后返回*[在 list 的从零起 index 处插入 item](> host_list_insert list=`list` index=`index` item=`item`)*。 - -## 改位 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| index | number | 必填 | 插入、替换或删除的位置,从零开始 | -| item | any | 必填 | 要插入、替换或比较的元素 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 从零起替换 list 的 index 为 item;日常嵌套改写请用「改」 | - -这里使用`list`、`index`、`item`。 - -调用效应:pure。 - -从零起替换 list 的 index 为 item;日常嵌套改写请用「改」。 - -完成后返回*[从零起替换 list 的 index 为 item;日常嵌套改写请用「改」](> host_list_set_at list=`list` index=`index` item=`item`)*。 - -## 删位 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| index | number | 必填 | 插入、替换或删除的位置,从零开始 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 删去 list 从零起的 index | - -这里使用`list`、`index`。 - -调用效应:pure。 - -删去 list 从零起的 index。 - -完成后返回*[删去 list 从零起的 index](> host_list_remove_at list=`list` index=`index`)*。 - -## 弹出 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 去掉 list 末项(空表报错) | - -这里使用`list`。 - -调用效应:pure。 - -去掉 list 末项(空表报错)。需要末值时先「末」。 - -得到**`n` = [调用 len](len(`list`))**。 -1. `n` > 0 - 完成后返回*[去掉 list 末项(空表报错)](> host_list_remove_at list=`list` index=`n` - 1)*。 -2. * - 完成后返回*[去掉 list 末项(空表报错)](> host_list_remove_at list=`list` index=0)*。 - -## 首 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | list 的首项 | - -这里使用`list`。 - -调用效应:pure。 - -list 的首项。 - -完成后返回*[list 的首项](> host_list_first list=`list`)*。 - -## 末 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | list 的末项 | - -这里使用`list`。 - -调用效应:pure。 - -list 的末项。 - -完成后返回*[list 的末项](> host_list_last list=`list`)*。 - -## 切片 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| start | number | 必填 | 切片起点,从零开始且包含端点 | -| end | any | None | 切片终点,从零开始且不包含端点;None 表示到末尾 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 对 list 做从零起的半开切片,从 start 到 end | - -这里使用`list`、`start`、`end`=None。 - -调用效应:pure。 - -对 list 做从零起的半开切片,从 start 到 end。 - -完成后返回*[对 list 做从零起的半开切片,从 start 到 end](> host_list_slice list=`list` start=`start` end=`end`)*。 - -## 含有 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| item | any | 必填 | 要插入、替换或比较的元素 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | list 是否含有 item | - -这里使用`list`、`item`。 - -调用效应:pure。 - -list 是否含有 item。 - -完成后返回*[list 是否含有 item](> host_list_contains list=`list` item=`item`)*。 - -## 下标 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| item | any | 必填 | 要插入、替换或比较的元素 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | item 在 list 中从零起的下标;没有 → None | - -这里使用`list`、`item`。 - -调用效应:pure。 - -item 在 list 中从零起的下标;没有 → None。 - -完成后返回*[item 在 list 中从零起的下标;没有 → None](> host_list_index_of list=`list` item=`item`)*。 - -## 反转 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 反转 list | - -这里使用`list`。 - -调用效应:pure。 - -反转 list。 - -完成后返回*[反转 list](> host_list_reverse list=`list`)*。 - -## 排序 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 对 list 升序排序(优先 int/num/text) | - -这里使用`list`。 - -调用效应:pure。 - -对 list 升序排序(优先 int/num/text)。 - -完成后返回*[对 list 升序排序(优先 int/num/text)](> host_list_sort list=`list`)*。 - -## 按键排序 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| key | text | 必填 | 本操作需要的字段名或键 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 对 map 列表 list 按字段 key 排序 | - -这里使用`list`、`key`。 - -调用效应:pure。 - -对 map 列表 list 按字段 key 排序。 - -完成后返回*[对 map 列表 list 按字段 key 排序](> host_list_sort_by list=`list` key=`key`)*。 - -## 去重 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 对 list 保序去重(保留首次) | - -这里使用`list`。 - -调用效应:pure。 - -对 list 保序去重(保留首次)。 - -完成后返回*[对 list 保序去重(保留首次)](> host_list_unique list=`list`)*。 - -## 分块 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | -| size | number | 必填 | 每块包含的元素数,必须为正数 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 把 list 按 size 分块 | - -这里使用`list`、`size`。 - -调用效应:pure。 - -把 list 按 size 分块。 - -完成后返回*[把 list 按 size 分块](> host_list_chunk list=`list` size=`size`)*。 - -## 拉链 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 各配对中第一项来自的列表 | -| b | any | 必填 | 各配对中第二项来自的列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 将 a 与 b 配对,取较短长度 | - -这里使用`a`、`b`。 - -调用效应:pure。 - -将 a 与 b 配对,取较短长度。 - -完成后返回*[将 a 与 b 配对,取较短长度](> host_list_zip a=`a` b=`b`)*。 - -## 展平 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| list | any | 必填 | 输入列表;更新返回新列表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 对 list 做一层展平 | - -这里使用`list`。 - -调用效应:pure。 - -对 list 做一层展平。 - -完成后返回*[对 list 做一层展平](> host_list_flatten list=`list`)*。 - -## 清空 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 按类型清空 value(空列表或空字典) | - -这里使用`value`。 - -调用效应:pure。 - -按类型清空 value(空列表或空字典)。 - -完成后返回*[按类型清空 value(空列表或空字典)](> host_collection_clear value=`value`)*。 - -## 取键 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | -| key | text | 必填 | 本操作需要的字段名或键 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 浅取 map 的 key;缺键 → None | - -这里使用`map`、`key`。 - -调用效应:pure。 - -浅取 map 的 key;缺键 → None。作者侧优先access 取元。 - -完成后返回*[浅取 map 的 key;缺键 → None](> host_map_get map=`map` key=`key`)*。 - -## 设 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | -| key | text | 必填 | 本操作需要的字段名或键 | -| value | any | 必填 | 运行时值;具体规则见下方操作说明 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 浅设 map 的 key 为 value;嵌套请用「改」 | - -这里使用`map`、`key`、`value`。 - -调用效应:pure。 - -浅设 map 的 key 为 value;嵌套请用「改」。 - -完成后返回*[浅设 map 的 key 为 value;嵌套请用「改」](> host_map_set map=`map` key=`key` value=`value`)*。 - -## 删键 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | -| key | text | 必填 | 本操作需要的字段名或键 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 从 map 删除 key | - -这里使用`map`、`key`。 - -调用效应:pure。 - -从 map 删除 key。 - -完成后返回*[从 map 删除 key](> host_map_delete map=`map` key=`key`)*。 - -## 有键 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | -| key | text | 必填 | 本操作需要的字段名或键 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | map 是否有 key | - -这里使用`map`、`key`。 - -调用效应:pure。 - -map 是否有 key。 - -完成后返回*[map 是否有 key](> host_map_has map=`map` key=`key`)*。 - -## 键表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | map 的键表 | - -这里使用`map`。 - -调用效应:pure。 - -map 的键表。 - -完成后返回*[map 的键表](> host_map_keys map=`map`)*。 - -## 值表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | map 的值表 | - -这里使用`map`。 - -调用效应:pure。 - -map 的值表。 - -完成后返回*[map 的值表](> host_map_values map=`map`)*。 - -## 项表 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | map 的键值对行表 | - -这里使用`map`。 - -调用效应:pure。 - -map 的键值对行表。 - -完成后返回*[map 的键值对行表](> host_map_items map=`map`)*。 - -## 合并 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | 基础记录;None 用作空记录种子 | -| b | any | 必填 | 合入 a 的记录;后面的值覆盖同名键 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 合并 a 与 b(右侧覆盖左侧) | - -这里使用`a`、`b`。 - -调用效应:pure。 - -合并 a 与 b(右侧覆盖左侧)。 - -完成后返回*[合并 a 与 b(右侧覆盖左侧)](> host_map_merge a=`a` b=`b`)*。 - -## 键数 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| map | any | 必填 | 输入文本键字典 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | number | map 的键数 | - -这里使用`map`。 - -调用效应:pure。 - -map 的键数。 - -完成后返回*[map 的键数](> host_map_size map=`map`)*。 - -## 空表 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 空列表 | - -调用效应:pure。 - -空列表。 - -完成后返回*[空列表](> host_list_concat a=None b=None)*。 - -## 空字典 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 返回新的空字典,作为不可变更新的种子;它与空列表不同 | - -调用效应:pure。 - -返回新的空字典,作为不可变更新的种子;它与空列表不同。 - -完成后返回*[返回新的空字典,作为不可变更新的种子;它与空列表不同](> host_map_merge a=None b=None)*。 - -## 序列 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 起 | number | 必填 | 序列的第一个数值 | -| 止 | number | 必填 | 序列不包含的终止边界 | -| 步长 | number | 1 | 非零序列步长;符号必须朝向终点 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 生成左闭右开的整数序列;允许负步长,拒绝零步长,最多一百万项。 | - -这里使用`起`、`止`、`步长`=1。 - -调用效应:pure。 - -生成左闭右开的整数序列;允许负步长,拒绝零步长,最多一百万项。 - -完成后返回*[生成左闭右开的整数序列;允许负步长,拒绝零步长,最多一百万项](> host_table_range start=`起` end=`止` step=`步长`)*。 - -## 编号 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 起 | number | 0 | 第一条记录所用的索引值;默认从一开始 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 返回 index/value 记录列表;编号从 start 开始,输入不变。 | - -这里使用`列表`、`起`=0。 - -调用效应:pure。 - -返回 index/value 记录列表;编号从 start 开始,输入不变。 - -完成后返回*[返回 index/value 记录列表;编号从 start 开始,输入不变](> host_table_enumerate list=`列表` start=`起`)*。 - -## 提列 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 逐行提取一个字段;缺少字段时报错,不悄悄变为空。 | - -这里使用`列表`、`键`。 - -调用效应:pure。 - -逐行提取一个字段;缺少字段时报错,不悄悄变为空。 - -完成后返回*[逐行提取一个字段;缺少字段时报错,不悄悄变为空](> host_table_pluck list=`列表` key=`键`)*。 - -## 投影 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 键表 | list | 必填 | 按顺序排列的字段名列表 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按 keys 顺序保留字段;每个字段必须存在。 | - -这里使用`列表`、`键表`。 - -调用效应:pure。 - -按 keys 顺序保留字段;每个字段必须存在。 - -完成后返回*[按 keys 顺序保留字段;每个字段必须存在](> host_table_project list=`列表` keys=`键表`)*。 - -## 筛选 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | -| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | -| 操作 | text | "eq" | 本接口支持的操作名 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 筛选匹配记录。op 为 eq/ne/gt/ge/lt/le/contains/in;这是固定操作名,不执行文本代码。 | - -这里使用`列表`、`键`、`值`、`操作`="eq"。 - -调用效应:pure。 - -筛选匹配记录。op 为 eq/ne/gt/ge/lt/le/contains/in;这是固定操作名,不执行文本代码。 - -完成后返回*[筛选匹配记录](> host_table_where list=`列表` key=`键` value=`值` op=`操作`)*。 - -## 分组 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按首次出现顺序返回 key/count/rows 记录;分组键保留原类型。 | - -这里使用`列表`、`键`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/表.mq.md 分组 '列表=[{"team":"a","n":3},{"team":"b","n":1},{"team":"a","n":2}]' '键="team"' --effects none --json -``` - -按首次出现顺序返回 key/count/rows 记录;分组键保留原类型。 - -完成后返回*[按首次出现顺序返回 key/count/rows 记录;分组键保留原类型](> host_table_group_by list=`列表` key=`键`)*。 - -## 按键去重 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 每个字段值保留第一条记录,维持输入顺序。 | - -这里使用`列表`、`键`。 - -调用效应:pure。 - -每个字段值保留第一条记录,维持输入顺序。 - -完成后返回*[每个字段值保留第一条记录,维持输入顺序](> host_table_unique_by list=`列表` key=`键`)*。 - -## 聚合 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 键 | any | None | 要读取、比较或更新的字段名或存储键 | -| 操作 | text | "sum" | 本接口支持的操作名 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | 聚合标量列表或一个字段:sum/count/min/max/mean。空表求和与计数为零;空表最值与均值失败;整数求和检查溢出。 | - -这里使用`列表`、`键`=None、`操作`="sum"。 - -调用效应:pure。 - -聚合标量列表或一个字段:sum/count/min/max/mean。空表求和与计数为零;空表最值与均值失败;整数求和检查溢出。 - -完成后返回*[聚合标量列表或一个字段:sum/count/min/max/mean](> host_table_aggregate list=`列表` key=`键` op=`操作`)*。 - -## 多键排序 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 键表 | list | 必填 | 按顺序排列的字段名列表 | -| 降序 | bool | False | 是否按多键降序排列 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按 keys 的字段顺序稳定排序;descending 改变比较方向,相同键保持顺序。 | - -这里使用`列表`、`键表`、`降序`=False。 - -调用效应:pure。 - -按 keys 的字段顺序稳定排序;descending 改变比较方向,相同键保持顺序。 - -完成后返回*[按 keys 的字段顺序稳定排序;descending 改变比较方向,相同键保持顺序](> host_table_sort_keys list=`列表` keys=`键表` descending=`降序`)*。 - -## 改字段名 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 字段 | map | 必填 | 附加到日志事件的结构化字段与值记录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 用旧名到新名的字典改字段名;输出字段重名时报错。 | - -这里使用`列表`、`字段`。 - -调用效应:pure。 - -用旧名到新名的字典改字段名;输出字段重名时报错。 - -完成后返回*[用旧名到新名的字典改字段名;输出字段重名时报错](> host_table_rename list=`列表` fields=`字段`)*。 - -## 列转行 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列 | map | 必填 | 列名与列表记录;各列长度必须一致 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 把列式字典转为行记录;各列必须是等长列表,不猜测普通对象字段。 | - -这里使用`列`。 - -调用效应:pure。 - -把列式字典转为行记录;各列必须是等长列表,不猜测普通对象字段。 - -完成后返回*[把列式字典转为行记录;各列必须是等长列表,不猜测普通对象字段](> host_table_from_columns columns=`列`)*。 - -## 行转列 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行 | list | 必填 | 行记录列表,不是隐式列式表 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 把字段集合相同的行记录转为列式字典;空输入返回空字典。 | - -这里使用`行`。 - -调用效应:pure。 - -把字段集合相同的行记录转为列式字典;空输入返回空字典。 - -完成后返回*[把字段集合相同的行记录转为列式字典;空输入返回空字典](> host_table_to_columns rows=`行`)*。 - -## 连接 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | -| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | -| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | -| 右键 | text | 必填 | 右侧记录中用于匹配的字段 | -| 模式 | text | "inner" | 连接方式:inner 或 left | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按字段相等连接;保持左表和右表匹配顺序。mode 为 inner/left;右侧重名字段加 right_ 前缀,仍冲突则失败。 | - -这里使用`左`、`右`、`键`、`右键`、`模式`="inner"。 - -调用效应:pure。 - -按字段相等连接;保持左表和右表匹配顺序。mode 为 inner/left;右侧重名字段加 right_ 前缀,仍冲突则失败。 - -完成后返回*[按字段相等连接;保持左表和右表匹配顺序](> host_table_join a=`左` b=`右` key=`键` right_key=`右键` mode=`模式`)*。 - -## 转字段类型 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行 | list | 必填 | 行记录列表,不是隐式列式表 | -| 规则 | map | 必填 | 字段与类型记录,采用标准契约类型词汇 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 按 schema 转换 text/int/number/bool/any 字段;缺失或无效值报告行号和字段,保留其他字段。 | - -这里使用`行`、`规则`。 - -调用效应:pure。 - -按 schema 转换 text/int/number/bool/any 字段;缺失或无效值报告行号和字段,保留其他字段。 - -完成后返回*[按 schema 转换 text/int/number/bool/any 字段;缺失或无效值报告行号和字段,保留其他字段](> host_table_cast rows=`行` schema=`规则`)*。 - -## 并集 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | -| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 保持首次出现顺序的并集;值相等规则与去重一致,区分类型。 | - -这里使用`左`、`右`。 - -调用效应:pure。 - -保持首次出现顺序的并集;值相等规则与去重一致,区分类型。 - -完成后返回*[保持首次出现顺序的并集;值相等规则与去重一致,区分类型](> host_table_union a=`左` b=`右`)*。 - -## 交集 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | -| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 保持输入顺序的交集,去除重复值。 | - -这里使用`左`、`右`。 - -调用效应:pure。 - -保持输入顺序的交集,去除重复值。 - -完成后返回*[保持输入顺序的交集,去除重复值](> host_table_intersection a=`左` b=`右`)*。 - -## 差集 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | -| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 保留左表中不在右表的值,维持顺序并去重。 | - -这里使用`左`、`右`。 - -调用效应:pure。 - -保留左表中不在右表的值,维持顺序并去重。 - -完成后返回*[保留左表中不在右表的值,维持顺序并去重](> host_table_difference a=`左` b=`右`)*。 - -## 尝试转类型 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行 | list | 必填 | 行记录列表,不是隐式列式表 | -| 规则 | map | 必填 | 字段与类型记录,采用标准契约类型词汇 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 可恢复地转换字段;无效字段返回结果记录,不中断调用方。 | - -这里使用`行`、`规则`。 - -调用效应:pure。 - -可恢复地转换字段;无效字段返回结果记录,不中断调用方。 - -完成后返回*[可恢复地转换字段;无效字段返回结果记录,不中断调用方](> host_table_try_cast rows=`行` schema=`规则`)*。 - -## 校验记录 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行 | list | 必填 | 行记录列表,不是隐式列式表 | -| 规则 | map | 必填 | 字段与类型记录,采用标准契约类型词汇 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 按核心渐进式类型校验必需字段,结果错误含 details 行号与字段诊断;int 是核心 number 别名,严格整数转换使用转字段类型。 | - -这里使用`行`、`规则`。 - -调用效应:pure。 - -按核心渐进式类型校验必需字段,结果错误含 details 行号与字段诊断;int 是核心 number 别名,严格整数转换使用转字段类型。 - -完成后返回*[按核心渐进式类型校验必需字段,结果错误含 details 行号与字段诊断;int 是核心 number 别名,严格整数转换使用转字段类型](> host_table_validate rows=`行` schema=`规则`)*。 - -## 查找首项 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 按原有顺序检查的行记录列表,不会就地修改 | -| 键 | text | 必填 | 每行需要读取并比较的字段名 | -| 值 | any | 必填 | 比较右值;in 操作在此集合中测试成员关系 | -| 操作 | text | "eq" | eq、ne、gt、ge、lt、le、contains 或 in;无效操作会失败 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 首个匹配行;没有匹配时为空值 | - -这里使用`列表`、`键`、`值`、`操作`="eq"。 - -调用效应:pure。 - -复用同一筛选规则,保持原行顺序且不修改输入;缺失字段或无效操作仍会产生诊断。 - -得到**`selected` = [调用 筛选](筛选(列表=`列表`, 键=`键`, 值=`值`, 操作=`操作`))**。 -完成后返回*[调用 首](首(list=`selected`))*。 - -## 任一满足 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 按原有顺序检查的行记录列表,不会就地修改 | -| 键 | text | 必填 | 每行需要读取并比较的字段名 | -| 值 | any | 必填 | 比较右值;in 操作在此集合中测试成员关系 | -| 操作 | text | "eq" | eq、ne、gt、ge、lt、le、contains 或 in;无效操作会失败 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 是否至少一行匹配;空列表为假 | - -这里使用`列表`、`键`、`值`、`操作`="eq"。 - -调用效应:pure。 - -复用同一筛选规则,保持原行顺序且不修改输入;缺失字段或无效操作仍会产生诊断。 - -得到**`selected` = [调用 筛选](筛选(列表=`列表`, 键=`键`, 值=`值`, 操作=`操作`))**。 -得到**`matched` = [调用 len](len(`selected`))**。 -完成后返回*matched > 0*。 - -## 全部满足 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 按原有顺序检查的行记录列表,不会就地修改 | -| 键 | text | 必填 | 每行需要读取并比较的字段名 | -| 值 | any | 必填 | 比较右值;in 操作在此集合中测试成员关系 | -| 操作 | text | "eq" | eq、ne、gt、ge、lt、le、contains 或 in;无效操作会失败 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 是否每行都匹配;空列表为真 | - -这里使用`列表`、`键`、`值`、`操作`="eq"。 - -调用效应:pure。 - -复用同一筛选规则,保持原行顺序且不修改输入;缺失字段或无效操作仍会产生诊断。 - -得到**`selected` = [调用 筛选](筛选(列表=`列表`, 键=`键`, 值=`值`, 操作=`操作`))**。 -得到**`matched` = [调用 len](len(`selected`))**。 -得到**`total` = [调用 len](len(`列表`))**。 -完成后返回*matched == total*。 - -## 分组汇总 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | -| 分组键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | -| 字段 | text | 必填 | 各分组内需要聚合的数值字段 | -| 操作 | text | "sum" | 本接口支持的操作名 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | list | 批量按键分组并聚合一个字段,返回 key/count/value 行记录,保持首次分组顺序;操作规则同聚合,避免在作者循环中反复复制增长的结果列表。 | - -这里使用`列表`、`分组键`、`字段`、`操作`="sum"。 - -调用效应:pure。 - -批量按键分组并聚合一个字段,返回 key/count/value 行记录,保持首次分组顺序;操作规则同聚合,避免在作者循环中反复复制增长的结果列表。 - -完成后返回*[批量按键分组并聚合一个字段,返回 key/count/value 行记录,保持首次分组顺序;操作规则同聚合,避免在作者循环中反复复制增长的结果列表](> host_table_summarize list=`列表` key=`分组键` field=`字段` op=`操作`)*。 - -## 键值转记录 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 键值对 | list | 必填 | 有序行记录,每行含文本 key 与任意 value 字段;其他字段不参与构造 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| 结果 | map | 新记录;首次出现的键决定顺序,后续同名键替换其值 | - -调用效应:pure。 - -输入`键值对`采用普通 @ 行记录表,把过宽的横向记录改写成可逐行阅读的 key/value 数据。 -适合提示章节、配置片段和具名字段较多的记录;这里复用本库既有的不可变更新, -不解析 JSON 文本,也不另造表格方言。空列表得到空记录,缺少或无效的键交给改操作报告, -不会为了制造字典而添加一个无意义的占位列。 - -先准备**记录 = [创建新的空记录](空字典())**,再按行读取字段,使每一项的来源都保持可见。 - -- [把每条具名字段写入新记录](遍历 键值对 为 键值行) - 读取**键 = [取出本行的字段名](access(键值行, "key"))**, - 以及**值 = [取出本行的字段值](access(键值行, "value"))**。 - 然后保留**记录 = [设置字段而不修改输入行](改(入=`记录`, 于=`键`, 值=`值`))**。 - -处理完有序行后,返回*记录*。同名字段保留第一次出现的位置并更新其值; -原来的键值对仍可继续使用,本操作没有文件、网络或插件副作用。 diff --git a/lib/超文本.mq.md b/lib/超文本.mq.md deleted file mode 100755 index 4d4484d..0000000 --- a/lib/超文本.mq.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -markup: occlusion -title: lib/超文本 -description: HTML 转义 / 还原(中层 Mid2 M8)。拼装字符串时的 XSS 底线。 ---- - -HTML 转义助手。把不可信文本拼进标记前先转义。 - -转义或还原 HTML 文本。 - -能力与边界:文本转义不等于清洗任意 HTML 文档。站点内容优先采用 Markdown 叶子和结构化视图节点。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/html_ops.rs](../src/host/html_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 转义 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 对内容做 HTML 转义 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/超文本.mq.md 转义 '内容="&"' --effects none --json -``` - -对内容做 HTML 转义。 - -调用例:[超文本.转义] 内容=`段` - -完成后返回*[对内容做 HTML 转义](> host_html_escape text=`内容`)*。 - -## 还原 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 还原内容里的 HTML 实体 | - -这里使用`内容`。 - -调用效应:pure。 - -还原内容里的 HTML 实体。 - -完成后返回*[还原内容里的 HTML 实体](> host_html_unescape text=`内容`)*。 diff --git a/lib/路径.mq.md b/lib/路径.mq.md deleted file mode 100755 index 5becc1c..0000000 --- a/lib/路径.mq.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -markup: occlusion -title: lib/路径 -description: 路径代数(中层 M2)。无 I/O;分隔符随宿主 OS。 ---- - -只做路径代数。无 I/O;分隔符随宿主 OS。 - -不访问磁盘的路径运算。 - -能力与边界:归一化是词法运算,不代表已获得文件访问权限。真正的 IO 路径由宿主按文件根目录检查。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/path.rs](../src/host/path.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 拼接 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 甲 | any | 必填 | 基础路径 | -| 乙 | any | 必填 | 追加到基础路径的路径片段 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 拼接路径段甲与乙 | - -这里使用`甲`、`乙`。 - -调用效应:pure。 - -拼接路径段甲与乙。 - -调用例:[路径.拼接] 甲="a" 乙="b" - -完成后返回*[拼接路径段甲与乙](> host_path_join a=`甲` b=`乙`)*。 - -## 拆分 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 把路径拆成各段 | - -这里使用`路径`。 - -调用效应:pure。 - -把路径拆成各段。 - -完成后返回*[把路径拆成各段](> host_path_split path=`路径`)*。 - -## 文件名 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 路径的末段文件名 | - -这里使用`路径`。 - -调用效应:pure。 - -路径的末段文件名。 - -完成后返回*[路径的末段文件名](> host_path_file_name path=`路径`)*。 - -## 父目录 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 路径的父目录 | - -这里使用`路径`。 - -调用效应:pure。 - -路径的父目录。 - -完成后返回*[路径的父目录](> host_path_parent path=`路径`)*。 - -## 扩展名 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 路径的扩展名 | - -这里使用`路径`。 - -调用效应:pure。 - -路径的扩展名。 - -完成后返回*[路径的扩展名](> host_path_extension path=`路径`)*。 - -## 规范化 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 规范化路径(处理点段) | - -这里使用`路径`。 - -调用效应:pure。 - -规范化路径(处理点段)。 - -完成后返回*[规范化路径(处理点段)](> host_path_normalize path=`路径`)*。 - -## 是绝对 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | any | 必填 | 授权文件根目录内的路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | 路径是否为绝对路径 | - -这里使用`路径`。 - -调用效应:pure。 - -路径是否为绝对路径。 - -完成后返回*[路径是否为绝对路径](> host_path_is_absolute path=`路径`)*。 - -## 相对路径 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 基准 | text | 必填 | 计算相对路径所用的基础目录 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 计算相对 base 的词法路径;两个参数须同为绝对或相对路径,不访问磁盘。 | - -这里使用`路径`、`基准`。 - -调用效应:pure。 - -计算相对 base 的词法路径;两个参数须同为绝对或相对路径,不访问磁盘。 - -完成后返回*[计算相对 base 的词法路径;两个参数须同为绝对或相对路径,不访问磁盘](> host_path_relative path=`路径` base=`基准`)*。 - -## 换扩展名 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 路径 | text | 必填 | 授权文件根目录内的路径 | -| 扩展名 | text | 必填 | 新扩展名,可带或不带开头的点 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 替换最后的扩展名;空扩展名表示去除。 | - -这里使用`路径`、`扩展名`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/路径.mq.md 换扩展名 '路径="notes/draft.txt"' '扩展名="md"' --effects none --json -``` - -替换最后的扩展名;空扩展名表示去除。 - -完成后返回*[替换最后的扩展名;空扩展名表示去除](> host_path_with_extension path=`路径` extension=`扩展名`)*。 diff --git a/lib/逗号表.mq.md b/lib/逗号表.mq.md deleted file mode 100755 index d00e7da..0000000 --- a/lib/逗号表.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/逗号表 -description: CSV 解析/序列化(中层 M4)。首行为表头 → 映射列表。 ---- - -CSV 解析与序列化。首行为表头;各行变成映射列表。 - -解析并序列化带表头的 CSV 行记录。 - -能力与边界:解析后单元格是文本,使用表库明确转换类型;序列化依第一行字段顺序。输入应为行记录,不是列式字典。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口: - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | 把 CSV 文本解析成映射列表 | - -这里使用`内容`。 - -调用效应:pure。 - -把 CSV 文本解析成映射列表。 - -调用例:[逗号表.解析] 内容=`原文` - -完成后返回*[把 CSV 文本解析成映射列表](> host_csv_parse text=`内容`)*。 - -## 序列化 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 行集 | any | 必填 | 行记录列表,不是隐式列式表 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | 把映射列表序列化成 CSV 文本 | - -这里使用`行集`。 - -调用效应:pure。 - -把映射列表序列化成 CSV 文本。 - -完成后返回*[把映射列表序列化成 CSV 文本](> host_csv_stringify rows=`行集`)*。 - -## 尝试解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 返回 {ok,value,error};解析失败是可恢复的数据。 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/逗号表.mq.md 尝试解析 '内容="name,n"' --effects none --json -``` - -返回 {ok,value,error};解析失败是可恢复的数据。 - -完成后返回*[返回 {ok,value,error};解析失败是可恢复的数据](> host_try_csv_parse text=`内容`)*。 diff --git a/lib/配置表.mq.md b/lib/配置表.mq.md deleted file mode 100755 index 89cd416..0000000 --- a/lib/配置表.mq.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -markup: occlusion -title: lib/配置表 -description: 标准 TOML 配置读写,支持数组表、多行文本和内联表;日期转为 ISO 文本。 ---- - -标准 TOML 配置读写;日期转为 ISO 文本,序列化不保留原注释。 - -读写标准 TOML 配置。 - -能力与边界:支持内联表、多行文本和数组表。TOML 日期转换成 ISO 文本;序列化不支持空值,也不保留原注释。 - -本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 - -实现入口:[src/host/toml_ops.rs](../src/host/toml_ops.rs) - -开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 - -## 解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 把 TOML 文本解析成映射/列表/标量 | - -这里使用`内容`。 - -调用效应:pure。 - -把 TOML 文本解析成映射/列表/标量。 - -调用例:[配置表.解析] 内容=`配置` - -完成后返回*[把 TOML 文本解析成映射/列表/标量](> host_toml_parse text=`内容`)*。 - -## 序列化 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 值 | map | 必填 | 待转换或保存的值;不会就地修改输入 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | text | 序列化字典为 TOML,拒绝空值及不支持的数据类型;不保留原注释。 | - -这里使用`值`。 - -调用效应:pure。 - -序列化字典为 TOML,拒绝空值及不支持的数据类型;不保留原注释。 - -完成后返回*[序列化字典为 TOML,拒绝空值及不支持的数据类型;不保留原注释](> host_toml_stringify value=`值`)*。 - -## 尝试解析 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | - -| 返回 | 类型 | 说明 | -|------|------|------| -| result | map | 以结果记录返回 TOML 解析;支持内联表、多行文本、数组表,日期转换为 ISO 文本。 | - -这里使用`内容`。 - -调用效应:pure。 - -直接调用此函数: - -```sh -marqdo call lib/配置表.mq.md 尝试解析 '内容="name="Marqdo""' --effects none --json -``` - -以结果记录返回 TOML 解析;支持内联表、多行文本、数组表,日期转换为 ISO 文本。 - -完成后返回*[以结果记录返回 TOML 解析;支持内联表、多行文本、数组表,日期转换为 ISO 文本](> host_toml_try_parse text=`内容`)*。 diff --git a/man-doc/README.md b/man-doc/README.md deleted file mode 100755 index e092ae5..0000000 --- a/man-doc/README.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: 人工文档 -description: 这是人工写的文档,禁止机器修改 ---- - -对于marqdo这个项目,详细的语法定义为: ---- - -#标识对象,#main不算特殊这是一个项目的传统入口可以视为是一个对象。 ---- -##、### 、####等标识函数,不同数目表示从属关系,例如###是##函数的子函数,作用域不超过 -这个函数,使用-表示函数的变量名 -**** 空返回(None),并结束本函数体 ---- -无标记行表示注释信息,对于无标记行应该这么约定不是说开头没有符合不然就会出现: - -**强调信息**是什么什么 - -上面应该是一个注释 ---- -程序语言使用*程序*也就是斜体表示 ---- -`变量名`表示变量 ---- -> 表示引用函数 ---- -有序列表表示分支语句 ---- -无序列表表示循环语句 ---- -公式由数学库渲染 ---- -代码片段由外联库渲染 ---- -添加一个新的标准库,自写回标准库,自写回的内容必须使用包裹,这个不会被md识别, -但是这个可以被marqdo识别,当作提示信息或生成结果的一律表示,markdo view要能渲染,以某种方式 ---- -添加一个新的标准库,子任务库,能够自由的运行子任务,现在的调用还是顺序化的,但是子任务允许多个 -进程式的调用,子任务库将成为marqdo的护城河项目,子任务要依赖于父任务,父任务结束子任务一定结束,防止出现问题 diff --git a/man-test/ext/agent-plan.mq.md b/man-test/ext/agent-plan.mq.md deleted file mode 100755 index dc4e2ae..0000000 --- a/man-test/ext/agent-plan.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: ext/agent plan live (DeepSeek) -description: Full plan loop — spawn workbook, inspect; simple pong goal. -import: - llm: ext/ai/llm.mq.md - agent: ext/ai/agent.mq.md - json: lib/json.mq.md - fs: lib/fs.mq.md ---- - -# main - -**`goal`=> input "你想完成什么任务?"** - -> llm.load_env path=.env - -**`model` = > llm.llm ** -**`tools` = > json.parse text=[] ** -**`助手` = > agent.agent model=`model` tools=`tools` standing=You are a Marqdo agent-development master. Prefer DONE when the workbook already satisfies the goal. ** - -流式开在 plan 上:非命中先 plan:decompose(父分解增量),再 plan:await(子 quiet),然后父修订轮。 - -**`out` = > `助手`.plan goal=`goal` max_rounds=3 writeback=False stream=True echo=True force=True ** - -**`result` = > json.get value=`out` key=result ** -> print text=`result` diff --git a/man-test/index.mq.md b/man-test/index.mq.md deleted file mode 100755 index 0a42cdf..0000000 --- a/man-test/index.mq.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -markup: occlusion -title: 手工构造的测试样例 -description: AI禁止更改 ---- - -# main - -这是人工构建的用于测试的样例 - -`测试目录` = -|测试文件夹| -|-----| -|structure| -|keyword| -|lib| - - -- [测试文件夹](遍历 `测试目录` 为 `测试文件夹`) - > 打印 `测试文件夹` - diff --git a/man-test/keyword/bool.mq.md b/man-test/keyword/bool.mq.md deleted file mode 100755 index 444a046..0000000 --- a/man-test/keyword/bool.mq.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -markup: occlusion -title: 手工构造的测试样例 -description: AI禁止更改 ---- - -# main - -**`a` = True** -**`b` = False** - -1. `a` and not `b` - > print text=ok -2. * - > print text=fail \ No newline at end of file diff --git a/man-test/keyword/input.mq.md b/man-test/keyword/input.mq.md deleted file mode 100755 index 6093147..0000000 --- a/man-test/keyword/input.mq.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -markup: occlusion -title: 手工构造的测试样例 -description: AI禁止更改 ---- - -# main - -测试输入 - -**`name`=> input "你叫什么名字\n"** - -> print `name` \ No newline at end of file diff --git a/man-test/keyword/print.mq.md b/man-test/keyword/print.mq.md deleted file mode 100755 index 3c480c5..0000000 --- a/man-test/keyword/print.mq.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -markup: occlusion -title: 手工构造的测试样例 -description: AI禁止更改 ---- - -# main - -测试输出 - -> print 欢迎你 \ No newline at end of file diff --git a/man-test/lib/math.mq.md b/man-test/lib/math.mq.md deleted file mode 100755 index 2f98dc9..0000000 --- a/man-test/lib/math.mq.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -markup: occlusion -title: 手工构造的测试样例 -description: AI禁止更改 -import: - math: lib/math.mq.md ---- - -# main - -`f` = -$$ -x^2 + 2 -$$ - -`f` = -$$ -x^2 - 2 -$$ - -**`ty` = > type `f` ** - -> print text=`ty` - -**`df` = > math.diff formula=`f` var=x ** - -> print text=`df` - -**`roots` = > math.solve formula=`f` var=x ** - -> print text=`roots` - -**`y` = > math.eval formula=`f` var=x value=3 ** - -> print text=`y` \ No newline at end of file diff --git a/man-test/lib/writeback.mq.md b/man-test/lib/writeback.mq.md deleted file mode 100755 index 0e0f545..0000000 --- a/man-test/lib/writeback.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: 手工构造的测试样例 -description: AI禁止更改 -import: - writeback: lib/writeback.mq.md ---- - -# main - -测试写回库 - -**`name`=>input "你叫什么名字?\n"** - -> writeback.record `name` - - - - - - - - - - - - - - diff --git a/man-test/structure/branch.mq.md b/man-test/structure/branch.mq.md deleted file mode 100755 index c8db2e3..0000000 --- a/man-test/structure/branch.mq.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: 手工构造的测试样例 -description: AI禁止更改 ---- - -# main - -测试分支语句 - -* `bool_value` = True * - -1. `bool_value` == True - > print True -2. * - > print False \ No newline at end of file diff --git a/man-test/structure/loop.mq.md b/man-test/structure/loop.mq.md deleted file mode 100755 index af3877f..0000000 --- a/man-test/structure/loop.mq.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -markup: occlusion -title: 手工构造的测试样例 -description: AI禁止更改 ---- - -# main - -测试循环语句语句 - -**`n`=0** - -- `n` < 42 - `n`=`n`+1 - -> print `n` \ No newline at end of file diff --git a/plugins/agent/Cargo.toml b/plugins/agent/Cargo.toml deleted file mode 100755 index 4965693..0000000 --- a/plugins/agent/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "marqdo_plugin_agent" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -description = "Marqdo agent plugin (ABI v2 cdylib)" -publish = false - -[lib] -name = "agent" -crate-type = ["cdylib"] - -[dependencies] -marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" } -serde_json = "1" -pulldown-cmark = "0.12" -chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } diff --git a/plugins/agent/src/choice.rs b/plugins/agent/src/choice.rs deleted file mode 100644 index cb63e68..0000000 --- a/plugins/agent/src/choice.rs +++ /dev/null @@ -1,197 +0,0 @@ -//! Fail-closed choice parsing for small-model routing. -//! This module only extracts a value; it never resolves or executes a SKILL. - -use serde_json::{json, Value}; - -fn canonical(s: &str) -> String { - s.trim() - .trim_matches(|c: char| matches!(c, '"' | '\'' | '`' | '“' | '”' | '‘' | '’')) - .trim() - .to_lowercase() -} - -fn strip_fence(s: &str) -> &str { - let s = s.trim(); - if !s.starts_with("```") { - return s; - } - let Some(start) = s.find('\n') else { - return s; - }; - let body = &s[start + 1..]; - let Some(end) = body.find("```") else { - return s; - }; - if !body[end + 3..].trim().is_empty() { - return s; - } - body[..end].trim() -} - -fn strip_label(s: &str) -> &str { - let s = s.trim(); - let Some((head, tail)) = s.split_once([':', ':']) else { - return s; - }; - if matches!( - head.trim().to_lowercase().as_str(), - "choice" | "option" | "selected" | "选择" | "选项" | "答案" - ) { - tail.trim() - } else { - s - } -} - -fn structured_reply(raw: &str) -> Option { - let parsed: Value = serde_json::from_str(raw).ok()?; - if let Some(s) = parsed.as_str() { - return Some(s.to_string()); - } - if let Some(list) = parsed.as_array() { - if list.len() == 1 { - return list[0].as_str().map(str::to_string); - } - return None; - } - let map = parsed.as_object()?; - // Refuse conflicting structured decisions instead of choosing first. - let values: Vec<&str> = ["choice", "selected", "option", "选择"] - .iter() - .filter_map(|key| map.get(*key).and_then(Value::as_str)) - .collect(); - if values.is_empty() || values.iter().any(|s| *s != values[0]) { - return None; - } - Some(values[0].to_string()) -} - -fn single_choice(options: &[String], reply: &str) -> Option { - let raw = strip_label(strip_fence(reply)); - // Structured single-choice replies are accepted only through known fields, - // and then still validated against the caller's exact allowlist. - let decoded = structured_reply(raw); - let raw = decoded.as_deref().unwrap_or(raw); - // Small models often prepend a short selection verb. Accept only the - // verb followed by a complete allowed value; explanations stay invalid. - let raw = raw.trim(); - let raw = ["我选择", "我选", "I choose ", "I pick ", "选中"].iter() - .find_map(|p| raw.strip_prefix(p).map(str::trim)) - .unwrap_or(raw); - let value = canonical(raw); - // Never infer a routing decision from arbitrary prose. - let matches: Vec<&String> = options - .iter() - .filter(|opt| canonical(opt) == value) - .collect(); - if matches.len() == 1 { - return Some(matches[0].clone()); - } - // A bare number denotes a 1-based index into the allowed list. - if let Ok(index) = value.parse::() { - if index > 0 && index <= options.len() { - return Some(options[index - 1].clone()); - } - } - None -} - -/// Parse one permitted option from a small model response. -/// Returns a status rather than treating arbitrary prose as a tool target. -pub fn parse_choice(args: &Value) -> Result { - let reply = args - .get("reply") - .and_then(Value::as_str) - .ok_or_else(|| "missing text `reply`".to_string())?; - let options = args - .get("options") - .and_then(Value::as_array) - .ok_or_else(|| "options must be an array of strings".to_string())?; - if options.is_empty() || options.len() > 64 { - return Err("options must contain 1..=64 entries".to_string()); - } - let mut allowed = Vec::with_capacity(options.len()); - for option in options { - let name = option - .as_str() - .ok_or_else(|| "each option must be a string".to_string())?; - if name.trim().is_empty() || name.len() > 128 { - return Err("each option must contain 1..=128 UTF-8 bytes".to_string()); - } - if allowed.iter().any(|p: &String| canonical(p) == canonical(name)) { - return Err("options must be unique after normalization".to_string()); - } - allowed.push(name.to_string()); - } - if let Some(value) = single_choice(&allowed, reply) { - Ok(json!({"ok": true, "value": value, "status": "accepted"})) - } else { - Ok(json!({ - "ok": false, - "value": null, - "status": "invalid", - "error": { - "code": "model.invalid_choice", - "category": "invalid_output", - "retryable": false, - "recovery_action": "repair_output" - } - })) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn check(reply: &str) -> Value { - parse_choice(&json!({"options": ["chat", "office"], "reply": reply})).unwrap() - } - - #[test] - fn accepts_exact_label_fence_and_number() { - assert_eq!(check("chat")["value"], "chat"); - assert_eq!(check(" CHAT ")["value"], "chat"); - assert_eq!(check("选择:office")["value"], "office"); - assert_eq!(check("```text\nchat\n```")["value"], "chat"); - assert_eq!(check("2")["value"], "office"); - assert_eq!(check("我选择 chat")["value"], "chat"); - assert_eq!(check("I choose office")["value"], "office"); - assert_eq!(check(r#"{"choice":"chat"}"#)["value"], "chat"); - assert_eq!(check("[\"office\"]")["value"], "office"); - assert_eq!(check("```json\n{\"selected\":\"office\"}\n```")["value"], "office"); - } - - #[test] - fn refuses_prose_conflicts_and_out_of_range() { - for reply in ["请选择 chat", "chat 或 office", "choice: chat,因为更合适", "3", ""] { - let result = check(reply); - assert_eq!(result["ok"], false, "accepted {reply:?}"); - assert_eq!(result["value"], Value::Null); - } - } - - #[test] - fn refuses_conflicting_structured_decisions() { - assert_eq!(check(r#"{"choice":"chat","option":"office"}"#)["ok"], false); - assert_eq!(check(r#"{"choice":"../private.mq.md"}"#)["ok"], false); - assert_eq!(check(r#"["chat","office"]"#)["ok"], false); - } - - #[test] - fn rejects_invalid_options_before_parsing() { - for options in [ - json!([]), - json!(["chat", "CHAT"]), - json!(["chat", 10]), - json!([""]), - ] { - assert!(parse_choice(&json!({"options": options, "reply": "chat"})).is_err()); - } - } - - #[test] - fn never_extracts_arbitrary_skill_path() { - assert_eq!(check("../../private.mq.md")["ok"], false); - } -} diff --git a/plugins/agent/src/context_pack.rs b/plugins/agent/src/context_pack.rs deleted file mode 100755 index 099477d..0000000 --- a/plugins/agent/src/context_pack.rs +++ /dev/null @@ -1,266 +0,0 @@ -//! ContextPackV2 assemble + compact (M-A4). - -use serde_json::{json, Value}; - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) -} - -fn item_tokens(item: &Value) -> u64 { - item.get("token_estimate") - .and_then(|v| v.as_u64()) - .unwrap_or_else(|| { - item.get("text") - .and_then(|v| v.as_str()) - .map(|s| (s.chars().count() as u64).div_ceil(2)) - .unwrap_or(32) - }) -} - -fn normalize_item(raw: &Value, default_priority: i64) -> Result { - let origin = raw - .get("origin") - .and_then(|v| v.as_str()) - .unwrap_or("unknown"); - let trust = raw - .get("trust") - .and_then(|v| v.as_str()) - .unwrap_or(match origin { - "system" | "policy" => "trusted", - "user" => "user", - "tool" => "tool", - "web" => "untrusted", - _ => "unknown", - }); - // External / web content must never be trust=trusted. - if matches!(origin, "web" | "tool") && trust == "trusted" { - return Err("tool/web origin cannot have trust=trusted".into()); - } - Ok(json!({ - "origin": origin, - "trust": trust, - "resource_ref": raw.get("resource_ref").cloned().unwrap_or(Value::Null), - "revision": raw.get("revision").cloned().unwrap_or(Value::Null), - "token_estimate": item_tokens(raw), - "priority": raw.get("priority").and_then(|v| v.as_i64()).unwrap_or(default_priority), - "role": raw.get("role").cloned().unwrap_or(json!(origin)), - "text": raw.get("text").cloned().unwrap_or(Value::Null), - "kind": raw.get("kind").cloned().unwrap_or(json!("content")), - "retain": raw.get("retain").and_then(|v| v.as_bool()).unwrap_or(false), - })) -} - -/// Build ContextPackV2 from items + optional budget. -pub fn context_pack_build(args: &Value) -> Result { - let raw_items = args - .get("items") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - let mut items = Vec::new(); - for (i, raw) in raw_items.iter().enumerate() { - items.push(normalize_item(raw, i as i64)?); - } - // Stable priority order: lower priority number first (more important). - items.sort_by(|a, b| { - let pa = a.get("priority").and_then(|v| v.as_i64()).unwrap_or(0); - let pb = b.get("priority").and_then(|v| v.as_i64()).unwrap_or(0); - pa.cmp(&pb) - }); - let budget = args - .get("budget_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(8_000); - let reserve_pct = args - .get("output_reserve_pct") - .and_then(|v| v.as_u64()) - .unwrap_or(20) - .min(50); - let available = budget.saturating_mul(100 - reserve_pct) / 100; - let used: u64 = items.iter().map(item_tokens).sum(); - Ok(json!({ - "schema": "ContextPackV2", - "schema_version": 2, - "items": items, - "budget_tokens": budget, - "available_tokens": available, - "used_tokens": used, - "output_reserve_pct": reserve_pct, - "compact_threshold_pct": args.get("compact_threshold_pct").and_then(|v| v.as_u64()).unwrap_or(70), - "goal": args.get("goal").cloned().unwrap_or(Value::Null), - "constraints": args.get("constraints").cloned().unwrap_or_else(|| json!([])), - })) -} - -/// Compact pack when over threshold; must retain anchors listed in design §6.2. -pub fn context_pack_compact(args: &Value) -> Result { - let mut pack = if args.get("schema").and_then(|v| v.as_str()) == Some("ContextPackV2") { - args.clone() - } else { - context_pack_build(args)? - }; - let available = pack - .get("available_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(6400); - let threshold_pct = pack - .get("compact_threshold_pct") - .and_then(|v| v.as_u64()) - .unwrap_or(70); - let threshold = available.saturating_mul(threshold_pct) / 100; - let used = pack - .get("used_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0); - if used <= threshold { - if let Some(obj) = pack.as_object_mut() { - obj.insert("compacted".into(), json!(false)); - obj.insert("reason".into(), json!("under_threshold")); - } - return Ok(pack); - } - - let items = pack - .get("items") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - // Retain: goal/constraints (pack fields), retain=true, high priority (<=2), - // pending writes, failures — drop bulky tool dumps first (kind=tool_output, low priority). - let mut kept = Vec::new(); - let mut dropped = Vec::new(); - for item in items { - let retain = item.get("retain").and_then(|v| v.as_bool()).unwrap_or(false); - let priority = item.get("priority").and_then(|v| v.as_i64()).unwrap_or(99); - let kind = item.get("kind").and_then(|v| v.as_str()).unwrap_or(""); - let trust = item.get("trust").and_then(|v| v.as_str()).unwrap_or(""); - let must = retain - || priority <= 2 - || matches!(kind, "goal" | "constraint" | "pending_write" | "plan" | "failure") - || trust == "trusted"; - if must { - kept.push(item); - } else if kind == "tool_output" || priority >= 8 { - dropped.push(item); - } else { - kept.push(item); - } - } - // If still over budget, drop lowest-priority non-retain from kept. - let mut kept_tokens: u64 = kept.iter().map(item_tokens).sum(); - if kept_tokens > threshold { - kept.sort_by(|a, b| { - let pa = a.get("priority").and_then(|v| v.as_i64()).unwrap_or(0); - let pb = b.get("priority").and_then(|v| v.as_i64()).unwrap_or(0); - pb.cmp(&pa) // high priority number first for dropping - }); - let mut next = Vec::new(); - for item in kept.into_iter().rev() { - // rebuild ascending later - let retain = item.get("retain").and_then(|v| v.as_bool()).unwrap_or(false); - let priority = item.get("priority").and_then(|v| v.as_i64()).unwrap_or(99); - let t = item_tokens(&item); - if (retain || priority <= 1) || kept_tokens <= threshold { - next.push(item); - } else if kept_tokens > threshold { - kept_tokens = kept_tokens.saturating_sub(t); - dropped.push(item); - } else { - next.push(item); - } - } - next.sort_by(|a, b| { - let pa = a.get("priority").and_then(|v| v.as_i64()).unwrap_or(0); - let pb = b.get("priority").and_then(|v| v.as_i64()).unwrap_or(0); - pa.cmp(&pb) - }); - kept = next; - kept_tokens = kept.iter().map(item_tokens).sum(); - } - - let digest_src = format!( - "kept={} dropped={} used={}", - kept.len(), - dropped.len(), - kept_tokens - ); - let digest = format!("sha256-lite:{}", simple_hash(&digest_src)); - - if let Some(obj) = pack.as_object_mut() { - obj.insert("items".into(), json!(kept)); - obj.insert("used_tokens".into(), json!(kept_tokens)); - obj.insert("compacted".into(), json!(true)); - obj.insert( - "compaction".into(), - json!({ - "dropped_count": dropped.len(), - "source_event_range": args.get("source_event_range").cloned().unwrap_or(Value::Null), - "digest": digest, - "retained": ["goal", "constraints", "pending_write", "plan", "trusted_policy"], - }), - ); - // Goal / constraints fields stay untouched. - if obj.get("goal").map(|v| v.is_null()).unwrap_or(true) { - if let Some(g) = opt_text(args, "goal") { - obj.insert("goal".into(), json!(g)); - } - } - } - Ok(pack) -} - -fn simple_hash(s: &str) -> u64 { - let mut h: u64 = 0xcbf29ce484222325; - for b in s.as_bytes() { - h ^= u64::from(*b); - h = h.wrapping_mul(0x100000001b3); - } - h -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn build_sorts_and_rejects_trusted_web() { - let pack = context_pack_build(&json!({ - "budget_tokens": 1000, - "items": [ - {"origin": "user", "text": "goal", "priority": 0, "kind": "goal", "retain": true}, - {"origin": "tool", "text": "big dump", "priority": 9, "kind": "tool_output", "token_estimate": 500} - ] - })) - .unwrap(); - assert_eq!(pack["schema"], "ContextPackV2"); - assert_eq!(pack["items"][0]["priority"], 0); - - let bad = context_pack_build(&json!({ - "items": [{"origin": "web", "trust": "trusted", "text": "x"}] - })); - assert!(bad.is_err()); - } - - #[test] - fn compact_keeps_goal_drops_tool_output() { - let pack = context_pack_build(&json!({ - "budget_tokens": 200, - "output_reserve_pct": 20, - "compact_threshold_pct": 50, - "goal": "finish task", - "items": [ - {"origin": "user", "text": "do it", "priority": 0, "kind": "goal", "retain": true, "token_estimate": 20}, - {"origin": "tool", "text": "x".repeat(400), "priority": 9, "kind": "tool_output", "token_estimate": 200} - ] - })) - .unwrap(); - let compacted = context_pack_compact(&pack).unwrap(); - assert_eq!(compacted["compacted"], true); - let items = compacted["items"].as_array().unwrap(); - assert!(items.iter().any(|i| i["kind"] == "goal")); - assert!(!items.iter().any(|i| i["kind"] == "tool_output")); - assert_eq!(compacted["goal"], "finish task"); - } -} diff --git a/plugins/agent/src/context_scope.rs b/plugins/agent/src/context_scope.rs deleted file mode 100644 index b970d57..0000000 --- a/plugins/agent/src/context_scope.rs +++ /dev/null @@ -1,207 +0,0 @@ -//! Markdown-heading-backed, bounded context projection for Marqdo SKILLs. -//! This is source selection, not execution: quoted text never becomes tool authority. -//! Markdown events ignore fenced-code headings; ambiguous functions fail closed. - -use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd}; -use serde_json::{json, Value}; - -#[derive(Clone, Debug)] -struct Section { - level: u8, - title: String, - start: usize, -} - -fn level_num(h: HeadingLevel) -> u8 { - match h { - HeadingLevel::H1 => 1, - HeadingLevel::H2 => 2, - HeadingLevel::H3 => 3, - HeadingLevel::H4 => 4, - HeadingLevel::H5 => 5, - HeadingLevel::H6 => 6, - } -} - -fn headings(source: &str) -> Vec
{ - let mut out = Vec::new(); - let mut pending: Option
= None; - for (event, range) in Parser::new(source).into_offset_iter() { - match event { - Event::Start(Tag::Heading { level, .. }) => { - pending = Some(Section { - level: level_num(level), - title: String::new(), - start: range.start, - }); - } - Event::Text(text) | Event::Code(text) => { - if let Some(section) = pending.as_mut() { - section.title.push_str(&text); - } - } - Event::End(TagEnd::Heading(_)) => { - if let Some(mut section) = pending.take() { - section.title = section.title.trim().to_string(); - out.push(section); - } - } - _ => {} - } - } - out -} - -fn class_for(headings: &[Section], index: usize) -> Option<&str> { - headings[..index] - .iter() - .rev() - .find(|h| h.level == 1) - .map(|h| h.title.as_str()) -} - -fn frontmatter_end(source: &str) -> usize { - if !source.starts_with("---\n") { - return 0; - } - let mut pos = 4; - for line in source[4..].split_inclusive('\n') { - pos += line.len(); - if line.trim() == "---" { - return pos; - } - } - 0 -} - -fn truncate_chars(text: &str, max_chars: usize) -> (&str, bool) { - let Some((end, _)) = text.char_indices().nth(max_chars) else { - return (text, false); - }; - (&text[..end], true) -} - -pub fn project(args: &Value) -> Result { - let source = match args.get("source").and_then(Value::as_str) { - Some(s) => s.to_string(), - None => crate::host_query_json("module_source")? - .as_str() - .ok_or_else(|| "module_source unavailable".to_string())? - .to_string(), - }; - let scope = args.get("scope").and_then(Value::as_str).unwrap_or("function"); - let class = args.get("class").and_then(Value::as_str); - let function = args.get("function").and_then(Value::as_str); - let maximum = args - .get("max_chars") - .and_then(Value::as_u64) - .unwrap_or(1600) - .clamp(32, 16000) as usize; - // YAML frontmatter may look like a setext Markdown heading; never treat it - // as a Marqdo class or function boundary. - let front_end = frontmatter_end(&source); - let marks: Vec
= headings(&source) - .into_iter() - .filter(|heading| heading.start >= front_end) - .collect(); - let results: Vec<(usize, usize)> = match scope { - "file" => { - let end = marks.first().map_or(source.len(), |h| h.start); - let start = frontmatter_end(&source).min(end); - vec![(start, end)] - } - "class" | "function" | "tool" => { - let level = match scope { - "class" => 1, - "function" => 2, - _ => 3, - }; - let target = if level == 1 { class } else { function }; - let wanted = target.ok_or_else(|| format!("{scope} selector required"))?; - marks - .iter() - .enumerate() - .filter(|(i, h)| { - h.level == level - && h.title == wanted - && (level == 1 || class.is_none() || class_for(&marks, *i) == class) - }) - .map(|(i, h)| { - let end = marks[i + 1..] - .iter() - .find(|next| next.level <= level) - .map_or(source.len(), |next| next.start); - let end = if level == 1 { - marks[i + 1..] - .iter() - .find(|next| next.level <= 2) - .map_or(end, |next| next.start) - } else { - end - }; - (h.start, end) - }) - .collect() - } - _ => return Err("scope must be file, class, function or tool".to_string()), - }; - if results.len() != 1 { - return Ok(json!({ - "ok": false, - "status": if results.is_empty() { "not_found" } else { "ambiguous" }, - "scope": scope, - "matches": results.len(), - "text": null - })); - } - let (start, end) = results[0]; - let (slice, truncated) = truncate_chars(source[start..end].trim(), maximum); - let line_start = source[..start].bytes().filter(|c| *c == b'\n').count() + 1; - Ok(json!({ - "ok": true, "status": "accepted", "scope": scope, - "text": slice, "truncated": truncated, - "start_byte": start, "end_byte": end, - "start_line": line_start, - "source_kind": "markdown_headings" - })) -} - -#[cfg(test)] -mod tests { - use super::*; - - const DOC: &str = "---\ntitle: example\n---\nEntry instructions.\n\n# main\nClass instructions.\n\n## route\nReal body.\n```md\n## route\nfake\n```\n\n## other\nOther body.\n\n# helper\nHelper prose.\n\n## route\nSecond body.\n"; - - #[test] - fn scope_is_bounded_and_fenced_headings_ignored() { - let v = project(&json!({"source": DOC, "scope": "function", "class": "main", "function": "route"})).unwrap(); - assert_eq!(v["ok"], true); - assert!(v["text"].as_str().unwrap().contains("Real body.")); - assert!(v["text"].as_str().unwrap().contains("fake")); - assert!(!v["text"].as_str().unwrap().contains("Other body.")); - assert!(!v["text"].as_str().unwrap().contains("Second body.")); - } - - #[test] - fn ambiguous_function_fails_closed() { - let v = project(&json!({"source": DOC, "scope": "function", "function": "route"})).unwrap(); - assert_eq!(v["status"], "ambiguous"); - assert_eq!(v["text"], Value::Null); - } - - #[test] - fn file_scope_removes_frontmatter_and_class_prose_excludes_functions() { - let a = project(&json!({"source": DOC, "scope": "file"})).unwrap(); - assert_eq!(a["text"], "Entry instructions."); - let b = project(&json!({"source": DOC, "scope": "class", "class": "main"})).unwrap(); - assert!(b["text"].as_str().unwrap().contains("Class instructions.")); - assert!(!b["text"].as_str().unwrap().contains("Real body.")); - } - - #[test] - fn unicode_truncation_does_not_split_characters() { - let v = project(&json!({"source": "汉".repeat(100), "scope": "file", "max_chars": 32})).unwrap(); - assert_eq!(v["text"].as_str().unwrap().chars().count(), 32); - assert_eq!(v["truncated"], true); - } -} diff --git a/plugins/agent/src/corpus.rs b/plugins/agent/src/corpus.rs deleted file mode 100755 index 289e492..0000000 --- a/plugins/agent/src/corpus.rs +++ /dev/null @@ -1,316 +0,0 @@ -//! Local corpus search + MCP fixture adapter (evidence tools; workbook stays authority). - -use std::fs; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - args.get(key) - .and_then(|v| v.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .ok_or_else(|| format!("missing {key}")) -} - -fn arg_usize(args: &Value, key: &str, default: usize) -> usize { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Number(n)) => n.as_u64().unwrap_or(default as u64) as usize, - Some(Value::String(s)) => s.parse().unwrap_or(default), - _ => default, - } -} - -fn resolve_path(rel: &str) -> PathBuf { - let p = PathBuf::from(rel); - if p.is_absolute() { - return p; - } - // Prefer host cwd (entry file directory) via host_query — same as kb.rs. - let base = (|| { - let q = crate::host_query_json("cwd")?; - q.as_str() - .map(PathBuf::from) - .ok_or_else(|| "cwd not text".to_string()) - })() - .or_else(|_| std::env::current_dir().map_err(|e| e.to_string())) - .unwrap_or_else(|_| PathBuf::from(".")); - base.join(p) -} - -fn is_corpus_file(path: &Path) -> bool { - match path.extension().and_then(|e| e.to_str()) { - Some("md" | "txt" | "mq.md") => true, - Some(ext) if ext.eq_ignore_ascii_case("markdown") => true, - _ => { - // `.mq.md` is two extensions on some platforms → check suffix - path.file_name() - .and_then(|n| n.to_str()) - .map(|n| n.ends_with(".mq.md") || n.ends_with(".md") || n.ends_with(".txt")) - .unwrap_or(false) - } - } -} - -fn query_terms(q: &str) -> Vec { - let mut out = Vec::new(); - let mut buf = String::new(); - let flush = |buf: &mut String, out: &mut Vec| { - if !buf.is_empty() { - out.push(buf.to_ascii_lowercase()); - buf.clear(); - } - }; - for c in q.chars() { - if c.is_alphanumeric() { - buf.push(c); - } else if !c.is_whitespace() && !c.is_ascii() { - // CJK / other letters: treat each char as a term - flush(&mut buf, &mut out); - out.push(c.to_string()); - } else { - flush(&mut buf, &mut out); - } - } - flush(&mut buf, &mut out); - out.retain(|t| !t.is_empty()); - out -} - -fn score_doc(text: &str, terms: &[String]) -> f64 { - if terms.is_empty() { - return 0.0; - } - let lower = text.to_ascii_lowercase(); - let mut hits = 0usize; - for t in terms { - if lower.contains(t) { - hits += 1; - } - } - hits as f64 / terms.len() as f64 -} - -fn best_excerpt(text: &str, terms: &[String], max_chars: usize) -> String { - let lines: Vec<&str> = text.lines().collect(); - let mut best_i = 0usize; - let mut best_score = -1.0f64; - for (i, line) in lines.iter().enumerate() { - let s = score_doc(line, terms); - if s > best_score { - best_score = s; - best_i = i; - } - } - let start = best_i.saturating_sub(1); - let end = (best_i + 2).min(lines.len()); - let mut chunk = lines[start..end].join("\n"); - if chunk.chars().count() > max_chars { - chunk = chunk.chars().take(max_chars).collect(); - chunk.push('…'); - } - chunk -} - -fn walk_corpus(root: &Path, out: &mut Vec, depth: usize) { - if depth > 6 || out.len() >= 400 { - return; - } - let Ok(rd) = fs::read_dir(root) else { - return; - }; - let mut ents: Vec<_> = rd.flatten().collect(); - ents.sort_by_key(|e| e.file_name()); - for ent in ents { - let p = ent.path(); - if p.is_dir() { - walk_corpus(&p, out, depth + 1); - } else if is_corpus_file(&p) { - out.push(p); - } - } -} - -/// Keyword corpus search over local markdown/text. Evidence only — not authority. -pub fn corpus_search(args: &Value) -> Result { - let query = arg_text(args, "query")?; - let root_s = match args.get("root").and_then(|v| v.as_str()) { - Some(s) if !s.trim().is_empty() => s.trim(), - _ => ".marqdo/agent-corpus", - }; - let limit = arg_usize(args, "limit", 6).clamp(1, 40); - let root = resolve_path(root_s); - if !root.is_dir() { - return Ok(json!({ - "hits": [], - "count": 0, - "query": query, - "root": root_s, - "authority": "workbook", - "note": "Corpus miss or missing root. Evidence only — runnable .mq.md workbook remains authority.", - })); - } - let terms = query_terms(query); - let mut files = Vec::new(); - walk_corpus(&root, &mut files, 0); - let mut ranked: Vec<(f64, PathBuf, String)> = Vec::new(); - for path in files { - let Ok(src) = fs::read_to_string(&path) else { - continue; - }; - let score = score_doc(&src, &terms); - if score <= 0.0 { - continue; - } - let excerpt = best_excerpt(&src, &terms, 320); - ranked.push((score, path, excerpt)); - } - ranked.sort_by(|a, b| { - b.0.partial_cmp(&a.0) - .unwrap_or(std::cmp::Ordering::Equal) - .then_with(|| a.1.cmp(&b.1)) - }); - ranked.truncate(limit); - let hits: Vec = ranked - .into_iter() - .map(|(score, path, excerpt)| { - let rel = path - .strip_prefix(&root) - .map(|p| p.to_string_lossy().into_owned()) - .unwrap_or_else(|_| path.to_string_lossy().into_owned()); - json!({ - "path": rel, - "score": (score * 1000.0).round() / 1000.0, - "excerpt": excerpt, - }) - }) - .collect(); - let count = hits.len() as i64; - Ok(json!({ - "hits": hits, - "count": count, - "query": query, - "root": root_s, - "authority": "workbook", - "note": "Corpus hits are external evidence only. Do not treat them as the runnable ground truth — the .mq.md workbook / OKF skill remains authority.", - })) -} - -fn load_fixture(path: &str) -> Result { - let p = resolve_path(path); - let src = fs::read_to_string(&p).map_err(|e| format!("mcp fixture read: {e}"))?; - serde_json::from_str(&src).map_err(|e| format!("mcp fixture json: {e}")) -} - -/// Offline / local MCP-shaped tool surface via a JSON fixture. -/// `action=list` → tools; `action=call` → results[name] (arguments ignored for fixture). -pub fn mcp_fixture(args: &Value) -> Result { - let action = args - .get("action") - .and_then(|v| v.as_str()) - .unwrap_or("list"); - let fixture = arg_text(args, "fixture")?; - let doc = load_fixture(fixture)?; - let note = doc - .get("note") - .and_then(|v| v.as_str()) - .unwrap_or( - "MCP/fixture evidence only. Workbook .mq.md remains authority; do not promote tool prose to ground truth.", - ) - .to_string(); - match action { - "list" => { - let tools = doc.get("tools").cloned().unwrap_or_else(|| json!([])); - Ok(json!({ - "tools": tools, - "fixture": fixture, - "authority": "workbook", - "note": note, - })) - } - "call" => { - let name = arg_text(args, "name")?; - let results = doc.get("results").or_else(|| doc.get("calls")); - let Some(map) = results.and_then(|v| v.as_object()) else { - return Err("mcp fixture missing results/calls object".into()); - }; - let Some(val) = map.get(name) else { - return Ok(json!({ - "ok": false, - "name": name, - "error": "tool not in fixture", - "authority": "workbook", - "note": note, - })); - }; - Ok(json!({ - "ok": true, - "name": name, - "result": val, - "arguments": args.get("arguments").cloned().unwrap_or(Value::Null), - "authority": "workbook", - "note": note, - })) - } - other => Err(format!("mcp fixture unknown action: {other}")), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - #[test] - fn corpus_search_ranks_matching_file() { - let dir = std::env::temp_dir().join("marqdo-corpus-a4-test"); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let mut f = fs::File::create(dir.join("refunds.md")).unwrap(); - writeln!(f, "# Refunds\n\nCustomers may request a refund within 30 days.").unwrap(); - let mut f2 = fs::File::create(dir.join("shipping.md")).unwrap(); - writeln!(f2, "# Shipping\n\nShips in two business days.").unwrap(); - - let args = json!({ - "query": "refund 30 days", - "root": dir.to_string_lossy(), - "limit": 4, - }); - let out = corpus_search(&args).unwrap(); - assert_eq!(out["authority"], "workbook"); - assert!(out["count"].as_i64().unwrap() >= 1); - let hits = out["hits"].as_array().unwrap(); - assert_eq!(hits[0]["path"], "refunds.md"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn mcp_fixture_list_and_call() { - let dir = std::env::temp_dir().join("marqdo-mcp-a4-test"); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join("fixture.json"); - fs::write( - &path, - r#"{"tools":[{"name":"wiki_get","description":"wiki"}],"results":{"wiki_get":{"text":"ok-page"}}}"#, - ) - .unwrap(); - let list = mcp_fixture(&json!({ - "action": "list", - "fixture": path.to_string_lossy(), - })) - .unwrap(); - assert_eq!(list["tools"][0]["name"], "wiki_get"); - let call = mcp_fixture(&json!({ - "action": "call", - "fixture": path.to_string_lossy(), - "name": "wiki_get", - })) - .unwrap(); - assert_eq!(call["ok"], true); - assert_eq!(call["result"]["text"], "ok-page"); - assert_eq!(call["authority"], "workbook"); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/plugins/agent/src/effects.rs b/plugins/agent/src/effects.rs deleted file mode 100755 index 0cc35ed..0000000 --- a/plugins/agent/src/effects.rs +++ /dev/null @@ -1,622 +0,0 @@ -//! EffectLedgerRecordV1 — operation receipts for write-safe resume (M-A5 subset). -//! -//! State machine (design §4.2): -//! prepared → started → committed -//! ↘ failed_no_effect -//! ↘ unknown → reconciled_committed | reconciled_no_effect | needs_input - -use std::fs::{self, File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -const DEFAULT_LEDGER_DIR: &str = ".marqdo/agent-effects"; - -const STATES: &[&str] = &[ - "prepared", - "started", - "committed", - "failed_no_effect", - "unknown", - "reconciled_committed", - "reconciled_no_effect", - "needs_input", -]; - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) -} - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - opt_text(args, key).ok_or_else(|| format!("missing text `{key}`")) -} - -fn now_rfc3339() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) -} - -fn resolve_path(rel: &str) -> PathBuf { - let p = PathBuf::from(rel); - if p.is_absolute() { - return p; - } - if p.exists() { - return p; - } - let base = (|| { - let q = crate::host_query_json("cwd")?; - q.as_str() - .map(PathBuf::from) - .ok_or_else(|| "cwd not text".to_string()) - })() - .or_else(|_| std::env::current_dir().map_err(|e| e.to_string())) - .unwrap_or_else(|_| PathBuf::from(".")); - base.join(p) -} - -fn ledger_root(args: &Value) -> Result { - let rel = opt_text(args, "ledger_dir").unwrap_or(DEFAULT_LEDGER_DIR); - let p = PathBuf::from(rel); - if p.is_absolute() { - return Err( - "ledger_dir must be host-relative; absolute client paths are rejected".into(), - ); - } - if rel.contains("..") { - return Err("ledger_dir must not contain '..'".into()); - } - Ok(resolve_path(rel)) -} - -fn safe_id(id: &str) -> String { - id.chars() - .map(|c| { - if c.is_ascii_alphanumeric() || c == '-' || c == '_' { - c - } else { - '_' - } - }) - .collect() -} - -fn record_path(root: &Path, operation_id: &str) -> PathBuf { - root.join(format!("{}.json", safe_id(operation_id))) -} - -fn ensure_dir(root: &Path) -> Result<(), String> { - fs::create_dir_all(root).map_err(|e| format!("effects mkdir: {e}")) -} - -static EFFECT_TEMP_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - -fn atomic_write_json(path: &Path, doc: &Value) -> Result<(), String> { - let parent = path - .parent() - .ok_or_else(|| "ledger path has no parent".to_string())?; - ensure_dir(parent)?; - let tmp_name = format!( - ".{}.tmp-{}-{}", - path.file_name() - .and_then(|s| s.to_str()) - .unwrap_or("op.json"), - std::process::id(), - format!("{}-{}", now_rfc3339().replace(':', ""), - EFFECT_TEMP_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) - ); - let tmp = parent.join(tmp_name); - let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?; - { - let mut f = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .open(&tmp) - .map_err(|e| format!("effects temp open: {e}"))?; - f.write_all(text.as_bytes()) - .map_err(|e| format!("effects temp write: {e}"))?; - f.flush().map_err(|e| format!("effects temp flush: {e}"))?; - f.sync_all() - .map_err(|e| format!("effects temp fsync: {e}"))?; - } - if let Ok(dir) = File::open(parent) { - let _ = dir.sync_all(); - } - fs::rename(&tmp, path).map_err(|e| { - let _ = fs::remove_file(&tmp); - format!("effects atomic rename: {e}") - })?; - Ok(()) -} - -fn load_record(path: &Path) -> Result, String> { - if !path.is_file() { - return Ok(None); - } - let text = fs::read_to_string(path).map_err(|e| format!("effects read: {e}"))?; - let doc: Value = serde_json::from_str(&text).map_err(|e| format!("effects corrupt: {e}"))?; - Ok(Some(doc)) -} - -fn valid_transition(from: &str, to: &str) -> bool { - matches!( - (from, to), - ("prepared", "started") - | ("started", "committed") - | ("started", "failed_no_effect") - | ("started", "unknown") - | ("unknown", "reconciled_committed") - | ("unknown", "reconciled_no_effect") - | ("unknown", "needs_input") - // Idempotent no-ops / crash retries of the same terminal. - | ("committed", "committed") - | ("failed_no_effect", "failed_no_effect") - | ("reconciled_committed", "reconciled_committed") - | ("reconciled_no_effect", "reconciled_no_effect") - | ("needs_input", "needs_input") - // Re-prepare of same op is handled separately via idempotency. - | ("prepared", "prepared") - ) -} - -fn effect_class_ok(c: &str) -> bool { - matches!(c, "read" | "write" | "execute" | "external_write" | "none") -} - -/// Prepare (or return existing) an EffectLedgerRecordV1. -pub fn effects_prepare(args: &Value) -> Result { - let operation_id = arg_text(args, "operation_id")?; - let idempotency_key = arg_text(args, "idempotency_key")?; - let args_digest = arg_text(args, "args_digest")?; - let effect_class = opt_text(args, "effect_class").unwrap_or("write"); - if !effect_class_ok(effect_class) { - return Err(format!("invalid effect_class={effect_class}")); - } - let root = ledger_root(args)?; - ensure_dir(&root)?; - let path = record_path(&root, operation_id); - - if let Some(existing) = load_record(&path)? { - let same_key = existing - .get("idempotency_key") - .and_then(|v| v.as_str()) - == Some(idempotency_key); - let same_digest = existing.get("args_digest").and_then(|v| v.as_str()) == Some(args_digest); - if same_key && same_digest { - return Ok(json!({ - "ok": true, - "deduped": true, - "record": existing, - })); - } - if same_key && !same_digest { - return Err( - "idempotency_key collision: same key with different args_digest".into(), - ); - } - // Different operation_id path can't collide; same path different key is corrupt reuse. - return Err("operation_id already exists with different idempotency_key".into()); - } - - // Also scan for same idempotency_key under other operation_ids in this ledger dir. - if let Ok(rd) = fs::read_dir(&root) { - for ent in rd.flatten() { - let p = ent.path(); - if p.extension().and_then(|e| e.to_str()) != Some("json") { - continue; - } - if let Ok(Some(doc)) = load_record(&p) { - if doc.get("idempotency_key").and_then(|v| v.as_str()) == Some(idempotency_key) { - let dig = doc.get("args_digest").and_then(|v| v.as_str()); - if dig == Some(args_digest) { - return Ok(json!({ - "ok": true, - "deduped": true, - "record": doc, - })); - } - return Err( - "idempotency_key collision: same key with different args_digest".into(), - ); - } - } - } - } - - let doc = json!({ - "schema": "EffectLedgerRecordV1", - "schema_version": 1, - "operation_id": operation_id, - "idempotency_key": idempotency_key, - "args_digest": args_digest, - "resource_scope": args.get("resource_scope").cloned().unwrap_or(Value::Null), - "expected_revision": args.get("expected_revision").cloned().unwrap_or(Value::Null), - "effect_class": effect_class, - "result_ref": args.get("result_ref").cloned().unwrap_or(Value::Null), - "state": "prepared", - "logical_run_id": args.get("logical_run_id").cloned().unwrap_or(Value::Null), - "step_id": args.get("step_id").cloned().unwrap_or(Value::Null), - "attempt_id": args.get("attempt_id").cloned().unwrap_or(Value::Null), - "prepared_at": now_rfc3339(), - "updated_at": now_rfc3339(), - }); - atomic_write_json(&path, &doc)?; - Ok(json!({ - "ok": true, - "deduped": false, - "record": doc, - "path": path.to_string_lossy(), - })) -} - -/// Transition an existing record to a new state. -pub fn effects_transition(args: &Value) -> Result { - let operation_id = arg_text(args, "operation_id")?; - let to = arg_text(args, "state")?; - if !STATES.contains(&to) { - return Err(format!("invalid state={to}")); - } - let root = ledger_root(args)?; - let path = record_path(&root, operation_id); - let mut doc = load_record(&path)? - .ok_or_else(|| format!("operation_id not found: {operation_id}"))?; - let from = doc - .get("state") - .and_then(|v| v.as_str()) - .unwrap_or("prepared") - .to_string(); - if !valid_transition(&from, to) { - return Err(format!("illegal transition {from} → {to}")); - } - if let Some(obj) = doc.as_object_mut() { - obj.insert("state".into(), json!(to)); - obj.insert("updated_at".into(), json!(now_rfc3339())); - if let Some(r) = args.get("result_ref") { - if !r.is_null() { - obj.insert("result_ref".into(), r.clone()); - } - } - if let Some(n) = args.get("note") { - if !n.is_null() { - obj.insert("note".into(), n.clone()); - } - } - if to == "unknown" || to.starts_with("reconciled") { - obj.insert( - "reconcile_hint".into(), - args.get("reconcile_hint") - .cloned() - .unwrap_or_else(|| json!("check receipt / resource revision")), - ); - } - } - atomic_write_json(&path, &doc)?; - Ok(json!({ - "ok": true, - "from": from, - "to": to, - "record": doc, - })) -} - -pub fn effects_get(args: &Value) -> Result { - let operation_id = arg_text(args, "operation_id")?; - let root = ledger_root(args)?; - let path = record_path(&root, operation_id); - match load_record(&path)? { - Some(doc) => Ok(json!({ - "ok": true, - "found": true, - "record": doc, - "path": path.to_string_lossy(), - })), - None => Ok(json!({ - "ok": true, - "found": false, - "operation_id": operation_id, - "path": path.to_string_lossy(), - })), - } -} - -pub fn effects_list(args: &Value) -> Result { - let root = ledger_root(args)?; - let mut records = Vec::new(); - if root.is_dir() { - let mut paths: Vec<_> = fs::read_dir(&root) - .map_err(|e| e.to_string())? - .flatten() - .map(|e| e.path()) - .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("json")) - .collect(); - paths.sort(); - for p in paths { - if let Ok(Some(doc)) = load_record(&p) { - if let Some(run) = opt_text(args, "logical_run_id") { - if doc.get("logical_run_id").and_then(|v| v.as_str()) != Some(run) { - continue; - } - } - if let Some(st) = opt_text(args, "state") { - if doc.get("state").and_then(|v| v.as_str()) != Some(st) { - continue; - } - } - records.push(doc); - } - } - } - Ok(json!({ - "ok": true, - "count": records.len(), - "records": records, - "ledger_dir": root.to_string_lossy(), - })) -} - -/// Compute a watermark digest over committed / reconciled records for a run. -pub fn effects_watermark(args: &Value) -> Result { - let listed = effects_list(args)?; - let records = listed - .get("records") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - let mut parts = Vec::new(); - let mut open_unknown = 0u64; - let mut pending_writes = 0u64; - for r in &records { - let state = r.get("state").and_then(|v| v.as_str()).unwrap_or(""); - let oid = r.get("operation_id").and_then(|v| v.as_str()).unwrap_or(""); - let cls = r.get("effect_class").and_then(|v| v.as_str()).unwrap_or(""); - parts.push(format!("{oid}:{state}")); - if state == "unknown" || state == "needs_input" { - open_unknown += 1; - } - if matches!(cls, "write" | "external_write" | "execute") - && matches!(state, "prepared" | "started" | "unknown" | "needs_input") - { - pending_writes += 1; - } - } - parts.sort(); - let joined = parts.join("|"); - let digest = format!("sha256-lite:{:x}", fnv64(&joined)); - let write_auto_resume_safe = open_unknown == 0 && pending_writes == 0; - Ok(json!({ - "ok": true, - "schema": "EffectLedgerWatermarkV1", - "schema_version": 1, - "watermark": digest, - "record_count": records.len(), - "open_unknown": open_unknown, - "pending_writes": pending_writes, - "write_auto_resume_safe": write_auto_resume_safe, - "logical_run_id": args.get("logical_run_id").cloned().unwrap_or(Value::Null), - })) -} - -/// Reconcile an `unknown` record after inspecting the external receipt / revision. -pub fn effects_reconcile(args: &Value) -> Result { - let outcome = arg_text(args, "outcome")?; // committed | no_effect | needs_input - let state = match outcome { - "committed" => "reconciled_committed", - "no_effect" => "reconciled_no_effect", - "needs_input" => "needs_input", - other => return Err(format!("invalid reconcile outcome={other}")), - }; - let mut targs = args.clone(); - if let Some(obj) = targs.as_object_mut() { - obj.insert("state".into(), json!(state)); - } - effects_transition(&targs) -} - -fn fnv64(s: &str) -> u64 { - let mut h: u64 = 0xcbf29ce484222325; - for b in s.as_bytes() { - h ^= u64::from(*b); - h = h.wrapping_mul(0x100000001b3); - } - h -} - -#[cfg(test)] -mod tests { - use super::*; - - // Avoid process-global set_current_dir: Rust executes tests concurrently. - // Keep each ledger in its own repository-relative, unique directory. - static SCRATCH_SEQ: std::sync::atomic::AtomicU64 = - std::sync::atomic::AtomicU64::new(0); - - fn scratch(tag: &str) -> PathBuf { - let seq = SCRATCH_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = PathBuf::from("target").join(format!( - "mq-effects-{}-{}-{}", - tag, std::process::id(), seq - )); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn prepare_dedupe_and_collision() { - let dir = scratch("prep"); - let ledger_dir = dir.join("led").to_string_lossy().to_string(); - let a = effects_prepare(&json!({ - "operation_id": "op1", - "idempotency_key": "idem1", - "args_digest": "sha256:a", - "effect_class": "write", - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run1", - })) - .unwrap(); - assert_eq!(a["deduped"], false); - assert_eq!(a["record"]["state"], "prepared"); - - let again = effects_prepare(&json!({ - "operation_id": "op1", - "idempotency_key": "idem1", - "args_digest": "sha256:a", - "ledger_dir": ledger_dir.clone(), - })) - .unwrap(); - assert_eq!(again["deduped"], true); - - let clash = effects_prepare(&json!({ - "operation_id": "op2", - "idempotency_key": "idem1", - "args_digest": "sha256:b", - "ledger_dir": ledger_dir.clone(), - })); - assert!(clash.unwrap_err().contains("collision")); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn transition_and_watermark_gates_write_resume() { - let dir = scratch("wm"); - let ledger_dir = dir.join("led").to_string_lossy().to_string(); - effects_prepare(&json!({ - "operation_id": "op_w", - "idempotency_key": "idem_w", - "args_digest": "sha256:w", - "effect_class": "write", - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run1", - })) - .unwrap(); - effects_transition(&json!({ - "operation_id": "op_w", - "state": "started", - "ledger_dir": ledger_dir.clone(), - })) - .unwrap(); - // Crash window: unknown — write auto-resume must stay closed. - effects_transition(&json!({ - "operation_id": "op_w", - "state": "unknown", - "ledger_dir": ledger_dir.clone(), - })) - .unwrap(); - let wm1 = effects_watermark(&json!({ - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run1", - })) - .unwrap(); - assert_eq!(wm1["write_auto_resume_safe"], false); - assert_eq!(wm1["open_unknown"], 1); - - effects_reconcile(&json!({ - "operation_id": "op_w", - "outcome": "committed", - "ledger_dir": ledger_dir.clone(), - "result_ref": "receipt:1", - })) - .unwrap(); - let wm2 = effects_watermark(&json!({ - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run1", - })) - .unwrap(); - assert_eq!(wm2["write_auto_resume_safe"], true); - assert_eq!(wm2["open_unknown"], 0); - assert!(wm2["watermark"].as_str().unwrap().starts_with("sha256-lite:")); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn ma_t03_unknown_then_reconcile_no_second_commit_path() { - // Write "succeeds" locally only after reconcile; retry while unknown must not - // look write_auto_resume_safe (MA-T03 watermark gate). - let dir = scratch("mat03"); - let ledger_dir = dir.join("led").to_string_lossy().to_string(); - effects_prepare(&json!({ - "operation_id": "op_kill", - "idempotency_key": "run|s|write_probe|sha256-lite:1", - "args_digest": "sha256-lite:1", - "effect_class": "write", - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run_kill", - })) - .unwrap(); - effects_transition(&json!({ - "operation_id": "op_kill", - "state": "started", - "ledger_dir": ledger_dir.clone(), - })) - .unwrap(); - // Crash before commit: - effects_transition(&json!({ - "operation_id": "op_kill", - "state": "unknown", - "ledger_dir": ledger_dir.clone(), - })) - .unwrap(); - let wm = effects_watermark(&json!({ - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run_kill", - })) - .unwrap(); - assert_eq!(wm["write_auto_resume_safe"], false); - - // Idempotent re-prepare returns same unknown record (no new op). - let again = effects_prepare(&json!({ - "operation_id": "op_kill", - "idempotency_key": "run|s|write_probe|sha256-lite:1", - "args_digest": "sha256-lite:1", - "effect_class": "write", - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run_kill", - })) - .unwrap(); - assert_eq!(again["deduped"], true); - assert_eq!(again["record"]["state"], "unknown"); - - effects_reconcile(&json!({ - "operation_id": "op_kill", - "outcome": "committed", - "ledger_dir": ledger_dir.clone(), - "result_ref": "effect:op_kill", - })) - .unwrap(); - let wm2 = effects_watermark(&json!({ - "ledger_dir": ledger_dir.clone(), - "logical_run_id": "run_kill", - })) - .unwrap(); - assert_eq!(wm2["write_auto_resume_safe"], true); - assert_eq!(wm2["pending_writes"], 0); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn illegal_skip_started() { - let dir = scratch("bad"); - let ledger_dir = dir.join("led").to_string_lossy().to_string(); - effects_prepare(&json!({ - "operation_id": "op_x", - "idempotency_key": "idem_x", - "args_digest": "sha256:x", - "ledger_dir": ledger_dir.clone(), - })) - .unwrap(); - let err = effects_transition(&json!({ - "operation_id": "op_x", - "state": "committed", - "ledger_dir": ledger_dir.clone(), - })) - .unwrap_err(); - assert!(err.contains("illegal transition")); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/plugins/agent/src/eng.rs b/plugins/agent/src/eng.rs deleted file mode 100755 index 40dfa65..0000000 --- a/plugins/agent/src/eng.rs +++ /dev/null @@ -1,731 +0,0 @@ -//! Engineering Knowledge preflight / reuse (reads `.marqdo` projections). -//! Does not call host_* — consumes compiled knowledge graph artifacts. - -use std::collections::HashMap; -use std::fs; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - args.get(key) - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("missing string arg `{key}`")) -} - -fn arg_f64(args: &Value, key: &str, default: f64) -> f64 { - match args.get(key) { - Some(Value::Number(n)) => n.as_f64().unwrap_or(default), - Some(Value::String(s)) => s.parse().unwrap_or(default), - _ => default, - } -} - -fn arg_usize(args: &Value, key: &str, default: usize) -> usize { - match args.get(key) { - Some(Value::Number(n)) => n.as_u64().unwrap_or(default as u64) as usize, - Some(Value::String(s)) => s.parse().unwrap_or(default), - _ => default, - } -} - -fn char_bigram_tf(text: &str) -> HashMap { - let chars: Vec = text.chars().filter(|c| !c.is_whitespace()).collect(); - let mut m = HashMap::new(); - if chars.is_empty() { - return m; - } - if chars.len() == 1 { - m.insert(chars[0].to_string(), 1.0); - return m; - } - for w in chars.windows(2) { - let key: String = w.iter().collect(); - *m.entry(key).or_insert(0.0) += 1.0; - } - m -} - -fn cosine_tf(a: &HashMap, b: &HashMap) -> f64 { - let mut na = 0.0; - let mut nb = 0.0; - for v in a.values() { - na += v * v; - } - for v in b.values() { - nb += v * v; - } - if na == 0.0 || nb == 0.0 { - return 0.0; - } - let mut dot = 0.0; - for (k, va) in a { - if let Some(vb) = b.get(k) { - dot += va * vb; - } - } - dot / (na.sqrt() * nb.sqrt()) -} - - -fn resolve_marqdo_root(start: &str) -> PathBuf { - let mut cur = PathBuf::from(start); - if cur.is_file() { - if let Some(p) = cur.parent() { - cur = p.to_path_buf(); - } - } - for _ in 0..8 { - let cand = cur.join(".marqdo"); - if cand.join("engineering.yaml").exists() - || cand.join("ekc/graph/graph.json").exists() - || cand.join("graph/graph.json").exists() - { - return cand; - } - if !cur.pop() { - break; - } - } - PathBuf::from(start).join(".marqdo") -} - -#[derive(Clone)] -struct CapHit { - id: String, - name: String, - score: f64, - implemented_by: Vec, -} - -fn load_capabilities(marqdo: &Path) -> Vec<(String, String, Vec, String)> { - // returns (id, name, implemented_by, material) - let mut out = Vec::new(); - let eng = marqdo.join("engineering.yaml"); - if let Ok(raw) = fs::read_to_string(&eng) { - let mut cur_id = String::new(); - let mut cur_name = String::new(); - let mut impls = Vec::new(); - let mut in_caps = false; - let mut in_impl = false; - for line in raw.lines() { - let t = line.trim_end(); - if t.trim() == "capabilities:" { - in_caps = true; - continue; - } - if in_caps && !line.starts_with(' ') && !line.starts_with('\t') && !t.trim().is_empty() - { - if t.trim() == "knowledge:" { - if !cur_id.is_empty() { - out.push(( - cur_id.clone(), - cur_name.clone(), - impls.clone(), - format!("{cur_name} {cur_id}"), - )); - } - break; - } - } - if !in_caps { - continue; - } - let trimmed = t.trim(); - if let Some(rest) = trimmed.strip_prefix("- id:") { - if !cur_id.is_empty() { - out.push(( - cur_id.clone(), - cur_name.clone(), - impls.clone(), - format!("{cur_name} {cur_id}"), - )); - } - cur_id = rest.trim().trim_matches('"').to_string(); - cur_name.clear(); - impls.clear(); - in_impl = false; - } else if let Some(rest) = trimmed.strip_prefix("name:") { - cur_name = rest.trim().trim_matches('"').to_string(); - } else if trimmed == "implemented_by:" { - in_impl = true; - } else if in_impl { - if let Some(rest) = trimmed.strip_prefix("- ") { - impls.push(rest.trim().trim_matches('"').to_string()); - } else if !trimmed.is_empty() && !line.starts_with(' ') { - in_impl = false; - } - } - } - if !cur_id.is_empty() { - out.push(( - cur_id.clone(), - cur_name.clone(), - impls, - format!("{cur_name} {cur_id}"), - )); - } - } - - // Also scan catalog/capabilities/*.md - let cap_dir = marqdo.join("catalog/capabilities"); - if let Ok(rd) = fs::read_dir(cap_dir) { - for ent in rd.flatten() { - let p = ent.path(); - if !p - .file_name() - .and_then(|s| s.to_str()) - .map(|s| s.ends_with(".md")) - .unwrap_or(false) - { - continue; - } - let Ok(src) = fs::read_to_string(&p) else { - continue; - }; - let id = fm_field(&src, "id").unwrap_or_else(|| { - p.file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("cap") - .to_string() - }); - let name = fm_field(&src, "name").unwrap_or_else(|| id.clone()); - if out.iter().any(|(i, _, _, _)| i == &id) { - continue; - } - out.push((id.clone(), name.clone(), Vec::new(), format!("{name} {id} {src}"))); - } - } - out -} - -fn fm_field(source: &str, key: &str) -> Option { - let prefix = format!("{key}:"); - for line in source.lines() { - let t = line.trim(); - if t == "---" { - continue; - } - if let Some(rest) = t.strip_prefix(&prefix) { - return Some(rest.trim().trim_matches('"').to_string()); - } - } - None -} - -fn load_knowledge_titles(marqdo: &Path, kind_subdir: &str) -> Vec<(String, String)> { - let dir = marqdo.join("knowledge").join(kind_subdir); - let mut out = Vec::new(); - let Ok(rd) = fs::read_dir(dir) else { - return out; - }; - for ent in rd.flatten() { - let p = ent.path(); - let Ok(src) = fs::read_to_string(&p) else { - continue; - }; - let id = fm_field(&src, "id").unwrap_or_else(|| { - p.file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("k") - .to_string() - }); - let title = fm_field(&src, "title").unwrap_or_else(|| id.clone()); - out.push((id, title)); - } - out -} - -fn rank_caps(task: &str, caps: &[(String, String, Vec, String)]) -> Vec { - let qv = char_bigram_tf(task); - let mut hits = Vec::new(); - for (id, name, impls, material) in caps { - let mut score = cosine_tf(&qv, &char_bigram_tf(material)); - if name.to_ascii_lowercase().contains(&task.to_ascii_lowercase()) - || task - .to_ascii_lowercase() - .split_whitespace() - .any(|t| t.len() > 2 && name.to_ascii_lowercase().contains(t)) - { - score = (score + 0.35).min(1.0); - } - if score > 0.12 { - hits.push(CapHit { - id: id.clone(), - name: name.clone(), - score, - implemented_by: impls.clone(), - }); - } - } - hits.sort_by(|a, b| { - b.score - .partial_cmp(&a.score) - .unwrap_or(std::cmp::Ordering::Equal) - }); - hits -} - -fn relevant_knowledge(task: &str, items: &[(String, String)], cap_names: &[String]) -> Vec { - let task_l = task.to_ascii_lowercase(); - items - .iter() - .filter(|(id, title)| { - let m = format!("{id} {title}").to_ascii_lowercase(); - task_l.split_whitespace().any(|t| t.len() > 3 && m.contains(t)) - || cap_names.iter().any(|c| m.contains(&c.to_ascii_lowercase())) - }) - .map(|(id, title)| format!("{title} ({id})")) - .collect() -} - -/// `agent_eng_preflight` — Engineering First Information gate. -pub fn eng_preflight(args: &Value) -> Result { - let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?; - let root = args - .get("root") - .and_then(|v| v.as_str()) - .unwrap_or("."); - let marqdo = args - .get("marqdo_dir") - .and_then(|v| v.as_str()) - .map(PathBuf::from) - .unwrap_or_else(|| resolve_marqdo_root(root)); - - if !marqdo.join("engineering.yaml").exists() - && !marqdo.join("ekc/graph/graph.json").exists() - && !marqdo.join("graph/graph.json").exists() - { - return Ok(json!({ - "status": "missing_knowledge", - "create_allowed": false, - "decision": "CREATE", - "error": "run `marqdo knowledge` first", - "existing": [], - "recommended": [], - })); - } - - let reuse_threshold = arg_f64(args, "reuse_threshold", 0.72); - let adapt_threshold = arg_f64(args, "adapt_threshold", 0.45); - let allow_create_after = arg_usize(args, "allow_create_after", 2); - let min_candidates = arg_usize(args, "min_candidates", 3); - - let caps = load_capabilities(&marqdo); - let ranked = rank_caps(task, &caps); - let existing: Vec = ranked.iter().take(8).map(|c| c.name.clone()).collect(); - let cap_names = existing.clone(); - - let constraints = relevant_knowledge( - task, - &load_knowledge_titles(&marqdo, "constraints"), - &cap_names, - ); - let decisions = relevant_knowledge( - task, - &load_knowledge_titles(&marqdo, "decisions"), - &cap_names, - ); - let failures = relevant_knowledge( - task, - &load_knowledge_titles(&marqdo, "failures"), - &cap_names, - ); - - let best = ranked.first(); - let best_score = best.map(|c| c.score).unwrap_or(0.0); - let analyzed = ranked.len().max(1).min(min_candidates.max(allow_create_after)); - - let (decision, create_allowed, recommended, reason) = if best_score >= reuse_threshold { - let b = best.unwrap(); - ( - "REUSE", - false, - vec![format!("REUSE {}", b.name)], - vec![ - "score meets REUSE threshold".into(), - "same capability semantics".into(), - ], - ) - } else if best_score >= adapt_threshold { - let b = best.unwrap(); - ( - "ADAPT", - false, - vec![format!("ADAPT {}", b.name)], - vec!["near match — wrap/compose/extend".into()], - ) - } else if analyzed >= allow_create_after { - ( - "CREATE", - true, - vec!["CREATE new capability".into()], - vec!["no existing capability satisfies constraints".into()], - ) - } else { - ( - "CREATE", - false, - vec![], - vec![format!( - "insufficient candidates ({analyzed} < {allow_create_after})" - )], - ) - }; - - // Write context pack - let contexts = marqdo.join("agent/contexts"); - let _ = fs::create_dir_all(&contexts); - let mut h: u64 = 5381; - for b in task.as_bytes() { - h = h.wrapping_mul(33).wrapping_add(u64::from(*b)); - } - let tid = format!("{h:016x}")[..12].to_string(); - let ctx_path = contexts.join(format!("task-{tid}.mq.md")); - let pack = format!( - "---\ntype: Marqdo Context Pack\ntitle: Engineering Context\ndecision: {decision}\ncreate_allowed: {create_allowed}\n---\n\n# Engineering Context\n\n## Task\n\n{task}\n\n## Existing Capabilities\n\n{existing}\n\n## Recommended Reuse\n\n{recommended}\n", - existing = existing - .iter() - .map(|e| format!("- {e}")) - .collect::>() - .join("\n"), - recommended = recommended - .iter() - .enumerate() - .map(|(i, r)| format!("{}. {r}", i + 1)) - .collect::>() - .join("\n"), - ); - let _ = fs::write(&ctx_path, pack); - - let status = if create_allowed { - "ready_create" - } else if decision == "REUSE" || decision == "ADAPT" { - "ready" - } else if decision == "CREATE" && !create_allowed { - "blocked" - } else { - "ready" - }; - - Ok(json!({ - "status": status, - "intent": { "capability": best.map(|c| c.name.clone()).unwrap_or_else(|| task.to_string()) }, - "existing": existing, - "constraints": constraints, - "decisions": decisions, - "failures": failures, - "recommended": recommended, - "create_allowed": create_allowed, - "decision": decision, - "confidence": best_score, - "reason": reason, - "context_path": ctx_path.display().to_string(), - "candidates": ranked.iter().take(8).map(|c| json!({ - "id": c.id, - "name": c.name, - "score": c.score, - "implemented_by": c.implemented_by, - })).collect::>(), - })) -} - -/// `agent_eng_reuse` — discovery + REUSE|ADAPT|CREATE decision. -/// -/// Scores and capability names are **not** executable targets (G02/G07). -/// When decision is REUSE/ADAPT, callers must `artifact.bind` a -/// `bind_targets[]` entry before `artifact.execute`. -pub fn eng_reuse(args: &Value) -> Result { - let mut pf = eng_preflight(args)?; - if let Some(obj) = pf.as_object_mut() { - obj.insert("protocol".into(), json!("REUSE|ADAPT|CREATE")); - obj.insert("discovery_only".into(), json!(true)); - let decision = obj - .get("decision") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_ascii_uppercase(); - let bind_required = matches!(decision.as_str(), "REUSE" | "ADAPT"); - obj.insert("bind_required".into(), json!(bind_required)); - let mut targets = Vec::new(); - if let Some(cands) = obj.get("candidates").and_then(|v| v.as_array()) { - for c in cands { - if let Some(impls) = c.get("implemented_by").and_then(|v| v.as_array()) { - for t in impls { - if let Some(s) = t.as_str() { - if !s.is_empty() { - targets.push(json!({ - "query": s, - "via": "implemented_by", - "capability": c.get("name"), - "note": "pass query to artifact.bind then artifact.execute", - })); - } - } - } - } - if let Some(id) = c.get("id").and_then(|v| v.as_str()) { - if id.contains(':') || id.contains('.') { - targets.push(json!({ - "query": id, - "via": "candidate_id", - "capability": c.get("name"), - "note": "pass query to artifact.bind then artifact.execute", - })); - } - } - } - } - // Dedup by query - let mut seen = std::collections::HashSet::new(); - targets.retain(|t| { - t.get("query") - .and_then(|q| q.as_str()) - .map(|q| seen.insert(q.to_string())) - .unwrap_or(false) - }); - obj.insert("bind_targets".into(), json!(targets)); - if bind_required { - let mut reasons = obj - .get("reason") - .cloned() - .unwrap_or_else(|| json!([])); - if let Some(arr) = reasons.as_array_mut() { - arr.push(json!( - "scores are discovery-only; bind SymbolId/handle before execute (G02/G07)" - )); - } - obj.insert("reason".into(), reasons); - } - } - Ok(pf) -} - -/// M04: discover → inspect → bind → execute → record (actual reuse, not n-gram REUSE). -/// -/// Requires host_query `mlsp`. Returns trace with artifact_id, digests, inputs, result. -/// Does **not** promote skills — callers pass `candidate_only=true` to skip learn/promote. -pub fn eng_bind_execute(args: &Value) -> Result { - let project = args - .get("project") - .or_else(|| args.get("root")) - .and_then(|v| v.as_str()) - .unwrap_or("."); - let policy = args - .get("policy") - .and_then(|v| v.as_str()) - .unwrap_or("pure"); - let inputs = args.get("inputs").cloned().unwrap_or(json!({})); - let query = if let Some(q) = args.get("artifact_id").or_else(|| args.get("query")).and_then(|v| v.as_str()) { - q.to_string() - } else { - // Fall back to first bind_target from eng_reuse. - let reuse = eng_reuse(args)?; - let targets = reuse - .get("bind_targets") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - targets - .first() - .and_then(|t| t.get("query").and_then(|q| q.as_str())) - .ok_or_else(|| { - "eng_bind_execute: no artifact_id/query and eng_reuse returned no bind_targets" - .to_string() - })? - .to_string() - }; - - let inspect = crate::host_query_json_args( - "mlsp", - &json!({"method":"artifact.inspect","params":{"project":project,"artifact_id":&query}}), - )?; - if inspect.get("ok") != Some(&json!(true)) { - return Ok(json!({ - "ok": false, - "stage": "inspect", - "error": inspect.get("error").cloned().unwrap_or(json!("inspect failed")), - "query": query, - })); - } - let artifact_id = inspect["result"]["artifact_id"] - .as_str() - .unwrap_or(&query) - .to_string(); - - let bound = crate::host_query_json_args( - "mlsp", - &json!({"method":"artifact.bind","params":{"project":project,"artifact_id":&artifact_id,"policy":policy}}), - )?; - if bound.get("ok") != Some(&json!(true)) { - return Ok(json!({ - "ok": false, - "stage": "bind", - "error": bound.get("error").cloned().unwrap_or(json!("bind failed")), - "artifact_id": artifact_id, - "discovery_only": false, - })); - } - let handle = bound["result"]["handle"].clone(); - - let executed = crate::host_query_json_args( - "mlsp", - &json!({"method":"artifact.execute","params":{"handle":&handle,"inputs":inputs}}), - )?; - if executed.get("ok") != Some(&json!(true)) { - return Ok(json!({ - "ok": false, - "stage": "execute", - "error": executed.get("error").cloned().unwrap_or(json!("execute failed")), - "artifact_id": artifact_id, - "handle": handle, - })); - } - - // Record only after successful bind+execute (actual reuse). - let _ = eng_record(&json!({ - "decision": "REUSE", - "root": project, - "marqdo_dir": args.get("marqdo_dir"), - })); - - Ok(json!({ - "ok": true, - "stage": "executed", - "discovery_only": false, - "bind_required": false, - "actual_reuse": true, - "artifact_id": artifact_id, - "symbol_id": handle.get("symbol_id"), - "digest": handle.get("digest"), - "evidence_digest": handle.get("evidence_digest"), - "closure_digest": handle.get("closure_digest"), - "policy": policy, - "inputs": inputs, - "result": executed.get("result"), - "candidate_only": args.get("candidate_only").and_then(|v| v.as_bool()).unwrap_or(false), - "trace": { - "artifact_id": artifact_id, - "symbol_id": handle.get("symbol_id"), - "digest": handle.get("digest"), - "inputs": inputs, - "stdout": executed["result"]["stdout"], - "value": executed["result"]["result"], - }, - })) -} - -/// Gate promote/learn: when `candidate_only` or may_bind=false, refuse promotion. -pub fn eng_publish_gate(args: &Value) -> Result { - let candidate_only = matches!(args.get("candidate_only"), Some(Value::Bool(true))); - let product_ok = !matches!(args.get("product_gate_ok"), Some(Value::Bool(false))); - let project = args - .get("project") - .or_else(|| args.get("root")) - .and_then(|v| v.as_str()) - .unwrap_or("."); - let policy = args - .get("policy") - .and_then(|v| v.as_str()) - .unwrap_or("business"); - let artifact = args - .get("artifact_id") - .or_else(|| args.get("query")) - .and_then(|v| v.as_str()); - - if candidate_only { - return Ok(json!({ - "ok": true, - "may_promote": false, - "reason": "candidate_only — framework must not promote", - })); - } - if !product_ok { - return Ok(json!({ - "ok": true, - "may_promote": false, - "reason": "product gate failed — framework must not promote", - })); - } - if let Some(id) = artifact { - let adj = crate::host_query_json_args( - "mlsp", - &json!({"method":"artifact.verify","params":{"project":project,"artifact_id":id,"policy":policy}}), - )?; - let may_bind = adj - .pointer("/result/may_bind") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - return Ok(json!({ - "ok": true, - "may_promote": may_bind, - "verification": adj.get("result"), - "reason": if may_bind { "verification allows bind" } else { "verification denied bind" }, - })); - } - Ok(json!({ - "ok": true, - "may_promote": product_ok, - "reason": "no artifact_id; deferred to product_gate_ok", - })) -} - -/// `agent_eng_record` — append reuse metrics under `.marqdo/agent/episodes`. -pub fn eng_record(args: &Value) -> Result { - let decision = arg_text(args, "decision")?; - let root = args - .get("root") - .and_then(|v| v.as_str()) - .unwrap_or("."); - let marqdo = args - .get("marqdo_dir") - .and_then(|v| v.as_str()) - .map(PathBuf::from) - .unwrap_or_else(|| resolve_marqdo_root(root)); - let duplicated = matches!(args.get("duplicated"), Some(Value::Bool(true))); - - let path = marqdo.join("agent/episodes/reuse_metrics.json"); - if let Some(p) = path.parent() { - let _ = fs::create_dir_all(p); - } - let mut m = if let Ok(raw) = fs::read_to_string(&path) { - serde_json::from_str::(&raw).unwrap_or(json!({})) - } else { - json!({}) - }; - let get_u = |v: &Value, k: &str| v.get(k).and_then(|x| x.as_u64()).unwrap_or(0); - let mut reused = get_u(&m, "reused"); - let mut adapted = get_u(&m, "adapted"); - let mut created = get_u(&m, "created"); - let mut dups = get_u(&m, "duplicated"); - match decision.to_ascii_uppercase().as_str() { - "REUSE" => reused += 1, - "ADAPT" => adapted += 1, - "CREATE" => { - created += 1; - if duplicated { - dups += 1; - } - } - _ => {} - } - m = json!({ - "generated_functions": get_u(&m, "generated_functions") + 1, - "reused": reused, - "adapted": adapted, - "created": created, - "duplicated": dups, - }); - let gen = m["generated_functions"].as_u64().unwrap_or(1) as f64; - m["reuse_ratio"] = json!(reused as f64 / gen); - m["adapt_ratio"] = json!(adapted as f64 / gen); - m["novel_ratio"] = json!(created as f64 / gen); - m["duplication_rate"] = json!(if created == 0 { - 0.0 - } else { - dups as f64 / created as f64 - }); - fs::write(&path, serde_json::to_string_pretty(&m).unwrap_or_default()) - .map_err(|e| e.to_string())?; - Ok(m) -} diff --git a/plugins/agent/src/error.rs b/plugins/agent/src/error.rs deleted file mode 100755 index d9a6317..0000000 --- a/plugins/agent/src/error.rs +++ /dev/null @@ -1,311 +0,0 @@ -//! AgentErrorV1 — classified errors and bounded recovery decisions (M-A1). - -use serde_json::{json, Value}; - -/// Build an AgentErrorV1 document from caller fields (compat: missing → defaults). -pub fn make_error(args: &Value) -> Result { - let code = args - .get("code") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| "missing text `code`".to_string())?; - let category = args - .get("category") - .and_then(|v| v.as_str()) - .unwrap_or_else(|| infer_category(code)); - let stage = args - .get("stage") - .and_then(|v| v.as_str()) - .unwrap_or("agent"); - let message = args - .get("message") - .and_then(|v| v.as_str()) - .unwrap_or(code); - let retryable = args - .get("retryable") - .and_then(|v| v.as_bool()) - .unwrap_or_else(|| default_retryable(category)); - let effect_state = args - .get("effect_state") - .and_then(|v| v.as_str()) - .unwrap_or("none"); - let recovery_action = args - .get("recovery_action") - .and_then(|v| v.as_str()) - .unwrap_or_else(|| default_recovery(category, effect_state)); - - let mut out = json!({ - "schema": "AgentErrorV1", - "schema_version": 1, - "code": code, - "category": category, - "stage": stage, - "message": message, - "retryable": retryable, - "effect_state": effect_state, - "recovery_action": recovery_action, - }); - if let Some(obj) = out.as_object_mut() { - if let Some(v) = args.get("retry_after_ms") { - obj.insert("retry_after_ms".into(), v.clone()); - } else { - obj.insert("retry_after_ms".into(), Value::Null); - } - for key in ["call_id", "details_ref", "fingerprint"] { - if let Some(v) = args.get(key) { - if !v.is_null() { - obj.insert(key.into(), v.clone()); - } - } - } - } - Ok(out) -} - -/// Decide whether a step may auto-retry (read-only / no-effect only in M-A1). -/// -/// Returns `{ok, action, reason, attempts_used, max_attempts}`. -pub fn decide_retry(args: &Value) -> Result { - let error = args - .get("error") - .cloned() - .ok_or_else(|| "missing map `error`".to_string())?; - let attempts = args - .get("attempts") - .and_then(|v| v.as_u64()) - .unwrap_or(0) as u32; - let max_transport = args - .get("max_transport_attempts") - .and_then(|v| v.as_u64()) - .unwrap_or(3) as u32; // 1 initial + 2 retries - let max_arg_repair = args - .get("max_arg_repairs") - .and_then(|v| v.as_u64()) - .unwrap_or(1) as u32; - let max_output_repair = args - .get("max_output_repairs") - .and_then(|v| v.as_u64()) - .unwrap_or(1) as u32; - let effect_class = args - .get("effect_class") - .and_then(|v| v.as_str()) - .unwrap_or("read"); - let cancelled = args - .get("cancelled") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let fingerprint_repeats = args - .get("fingerprint_repeats") - .and_then(|v| v.as_u64()) - .unwrap_or(0) as u32; - - if cancelled { - return Ok(decision("stop", "cancelled", attempts, max_transport)); - } - - let category = error - .get("category") - .and_then(|v| v.as_str()) - .unwrap_or("unknown"); - let retryable = error - .get("retryable") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let effect_state = error - .get("effect_state") - .and_then(|v| v.as_str()) - .unwrap_or("none"); - let recovery = error - .get("recovery_action") - .and_then(|v| v.as_str()) - .unwrap_or("none"); - - // Write / unknown effect: never auto-retry in M-A1 (ledger required). - if effect_class != "read" || matches!(effect_state, "unknown" | "started" | "committed") { - return Ok(decision( - "manual_review", - "write_or_unknown_effect_requires_ledger", - attempts, - max_transport, - )); - } - - if fingerprint_repeats >= 2 { - return Ok(decision( - "stop", - "error_fingerprint_loop", - attempts, - max_transport, - )); - } - - match category { - "transient" if retryable && attempts + 1 < max_transport => Ok(decision( - "retry_step", - "transient_read_safe", - attempts, - max_transport, - )), - "invalid_arguments" if recovery == "repair_args" && attempts < max_arg_repair => Ok( - decision("repair_args", "one_arg_repair", attempts, max_arg_repair), - ), - "invalid_output" if recovery == "repair_output" && attempts < max_output_repair => Ok( - decision("repair_output", "one_format_repair", attempts, max_output_repair), - ), - "context_overflow" if recovery == "compact_context" && attempts == 0 => Ok( - decision("compact_context", "one_bounded_compaction", attempts, 1), - ), - "auth" | "forbidden" | "policy_denied" => Ok(decision( - "needs_input", - category, - attempts, - max_transport, - )), - "budget_exhausted" => Ok(decision("partial", category, attempts, max_transport)), - "cancelled" => Ok(decision("stop", "cancelled", attempts, max_transport)), - "unknown_effect" | "worker_crash" => Ok(decision( - "manual_review", - category, - attempts, - max_transport, - )), - _ => Ok(decision("stop", "not_auto_retryable", attempts, max_transport)), - } -} - -fn decision(action: &str, reason: &str, attempts: u32, max_attempts: u32) -> Value { - json!({ - "ok": true, - "schema": "AgentRetryDecisionV1", - "schema_version": 1, - "action": action, - "reason": reason, - "attempts_used": attempts, - "max_attempts": max_attempts, - "auto": matches!(action, "retry_step" | "repair_args" | "repair_output" | "compact_context"), - }) -} - -fn infer_category(code: &str) -> &'static str { - let c = code.to_ascii_lowercase(); - if c.contains("context_overflow") || c.contains("context_length") { - "context_overflow" - } else if c.contains("invalid_choice") || c.contains("invalid_output") { - "invalid_output" - } else if c.contains("timeout") || c.contains("429") || c.contains("5xx") || c.contains("connect") { - "transient" - } else if c.contains("schema") || c.contains("argument") { - "invalid_arguments" - } else if c.contains("auth") { - "auth" - } else if c.contains("forbid") { - "forbidden" - } else if c.contains("policy") { - "policy_denied" - } else if c.contains("budget") { - "budget_exhausted" - } else if c.contains("cancel") { - "cancelled" - } else if c.contains("conflict") || c.contains("stale") { - "conflict" - } else if c.contains("effect") || c.contains("crash") { - "unknown_effect" - } else { - "unknown" - } -} - -fn default_retryable(category: &str) -> bool { - matches!(category, "transient") -} - -fn default_recovery(category: &str, effect_state: &str) -> &'static str { - if effect_state == "unknown" { - return "reconcile"; - } - match category { - "transient" => "retry_step", - "invalid_arguments" => "repair_args", - "invalid_output" => "repair_output", - "context_overflow" => "compact_context", - "auth" | "forbidden" | "policy_denied" | "needs_input" => "needs_input", - "budget_exhausted" => "return_partial", - "cancelled" => "stop", - "unknown_effect" | "worker_crash" => "manual_review", - _ => "stop", - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn make_error_defaults() { - let err = make_error(&json!({"code": "tool.timeout", "message": "t"})).unwrap(); - assert_eq!(err["schema"], "AgentErrorV1"); - assert_eq!(err["category"], "transient"); - assert_eq!(err["retryable"], true); - assert_eq!(err["recovery_action"], "retry_step"); - } - - #[test] - fn read_transient_retries_once() { - let err = make_error(&json!({"code": "tool.timeout"})).unwrap(); - let d = decide_retry(&json!({ - "error": err, - "attempts": 0, - "effect_class": "read" - })) - .unwrap(); - assert_eq!(d["action"], "retry_step"); - assert_eq!(d["auto"], true); - } - - #[test] - fn write_never_auto_retries() { - let err = make_error(&json!({"code": "tool.timeout"})).unwrap(); - let d = decide_retry(&json!({ - "error": err, - "attempts": 0, - "effect_class": "write" - })) - .unwrap(); - assert_eq!(d["action"], "manual_review"); - assert_eq!(d["auto"], false); - } - - #[test] - fn output_repair_is_bounded_and_read_only() { - let err = make_error(&json!({"code": "model.invalid_choice"})).unwrap(); - assert_eq!(err["category"], "invalid_output"); - let first = decide_retry(&json!({"error": err, "attempts": 0})).unwrap(); - assert_eq!(first["action"], "repair_output"); - let next = decide_retry(&json!({"error": err, "attempts": 1})).unwrap(); - assert_eq!(next["action"], "stop"); - let write = decide_retry(&json!({ - "error": err, "attempts": 0, "effect_class": "write" - })).unwrap(); - assert_eq!(write["action"], "manual_review"); - } - - #[test] - fn compaction_is_not_an_unbounded_model_loop() { - let err = make_error(&json!({"code": "model.context_overflow"})).unwrap(); - assert_eq!(decide_retry(&json!({"error": err, "attempts": 0})).unwrap()["action"], "compact_context"); - assert_eq!(decide_retry(&json!({"error": err, "attempts": 1})).unwrap()["action"], "stop"); - } - - #[test] - fn fingerprint_loop_stops() { - let err = make_error(&json!({"code": "tool.timeout"})).unwrap(); - let d = decide_retry(&json!({ - "error": err, - "attempts": 0, - "effect_class": "read", - "fingerprint_repeats": 2 - })) - .unwrap(); - assert_eq!(d["action"], "stop"); - } -} diff --git a/plugins/agent/src/input.rs b/plugins/agent/src/input.rs deleted file mode 100644 index 7e11b1e..0000000 --- a/plugins/agent/src/input.rs +++ /dev/null @@ -1,251 +0,0 @@ -//! Durable input gates for document-native SKILLs. -//! Pausing is a committed *step boundary*, not serialization of a Rust stack. -//! The caller resumes the next documented step with the saved answer. - -use std::fs::{self, OpenOptions}; -use std::path::PathBuf; -use serde_json::{json, Value}; - -use crate::resume; - -struct GateLock(PathBuf); -impl Drop for GateLock { - fn drop(&mut self) { - let _ = fs::remove_file(&self.0); - } -} - -fn text_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - args.get(key) - .and_then(Value::as_str) - .filter(|s| !s.is_empty()) - .ok_or_else(|| format!("missing text `{key}`")) -} - -fn valid_id(s: &str) -> bool { - !s.is_empty() - && s.len() <= 100 - && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') -} - -fn root(args: &Value) -> Result { - let name = args - .get("resume_dir") - .and_then(Value::as_str) - .unwrap_or(".marqdo/agent-resume"); - let path = PathBuf::from(name); - if path.is_absolute() - || path.components().any(|part| matches!(part, std::path::Component::ParentDir)) - { - return Err("resume_dir must be a relative path without '..'".to_string()); - } - fs::create_dir_all(&path).map_err(|e| format!("input gate mkdir: {e}"))?; - Ok(path) -} - -fn lock(args: &Value, id: &str) -> Result { - if !valid_id(id) { - return Err("input gate id must be 1..=100 ASCII letters, numbers, '_' or '-'".into()); - } - let path = root(args)?.join(format!("{id}.input-lock")); - OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - .map_err(|e| format!("input gate is busy or needs reconciliation: {e}"))?; - Ok(GateLock(path)) -} - -fn options(args: &Value) -> Result { - let choices = args.get("options").and_then(Value::as_array) - .ok_or_else(|| "options must be a list of 1..=32 short labels".to_string())?; - if choices.is_empty() || choices.len() > 32 { - return Err("options must contain 1..=32 choices".into()); - } - for v in choices { - let Some(s) = v.as_str() else { - return Err("every option must be text".into()); - }; - if s.is_empty() || s.len() > 256 { - return Err("each option must contain 1..=256 bytes".into()); - } - } - let empty = crate::choice::parse_choice(&json!({ - "options": choices, "reply": "__invalid_choice_probe__" - }))?; - // The parser checks duplicates and option size; the probe must not be accepted. - if empty["ok"] == true { - return Err("invalid reserved choice option".into()); - } - Ok(Value::Array(choices.to_vec())) -} - -/// Create a durable waiting-input checkpoint. Repeated open never resets a -/// previously answered gate. No external effect is performed. -pub fn input_open(args: &Value) -> Result { - let id = text_arg(args, "id")?; - let _lock = lock(args, id)?; - let labels = options(args)?; - let query = text_arg(args, "question")?; - let version = text_arg(args, "source_revision")?; - let read_args = json!({"id": id, "resume_dir": args.get("resume_dir")}); - let existing = resume::resume_load(&read_args)?; - if existing["found"] == true { - let meta = &existing["meta"]; - let same = meta["question"] == query - && meta["options"] == labels - && meta["source_revision"] == version - && meta["session_id"] == *args.get("session_id").unwrap_or(&Value::Null) - && meta["principal_ref"] == *args.get("principal_ref").unwrap_or(&Value::Null); - if same && existing["ok"] == true { - let status = existing["status"].as_str().unwrap_or("unknown"); - return Ok(json!({ - "ok": true, "id": id, "status": status, - "value": existing["result"], "reused": true, - "question": query, "options": labels - })); - } - return Ok(json!({"ok":false,"id":id,"status":"conflict", - "error":{"code":"input.stale_or_reused_gate"}})); - } - let saved = resume::resume_save(&json!({ - "id": id, "resume_dir": args.get("resume_dir"), - "checkpoint_v2": true, - "status": "waiting_input", - "task": query, - "meta": { - "question": query, - "options": labels, - "source_revision": version, - "session_id": args.get("session_id").unwrap_or(&Value::Null), - "principal_ref": args.get("principal_ref").unwrap_or(&Value::Null), - "freeform": args.get("freeform").and_then(Value::as_bool).unwrap_or(true) - } - }))?; - if saved["ok"] != true { - return Err("unable to save input checkpoint".into()); - } - Ok(json!({"ok": true, "id":id, "status":"waiting_input", "value":null, - "question":query,"options":labels,"reused":false})) -} - -/// Resume a specific gate with a user response. Only a committed answer can be -/// replayed: different duplicate replies conflict instead of re-triggering work. -pub fn input_resume(args: &Value) -> Result { - let id = text_arg(args, "id")?; - let _lock = lock(args, id)?; - let reply = text_arg(args, "reply")?; - if reply.len() > 4096 { - return Err("input reply must not exceed 4096 bytes".into()); - } - let version = text_arg(args, "source_revision")?; - let read_args = json!({"id": id, "resume_dir": args.get("resume_dir")}); - let existing = resume::resume_load(&read_args)?; - if existing["ok"] != true || existing["schema"] != "CheckpointV2" { - return Ok(json!({"ok":false,"status":"not_found_or_corrupt","id":id})); - } - let meta = &existing["meta"]; - if meta["source_revision"] != version - || meta["session_id"] != *args.get("session_id").unwrap_or(&Value::Null) - || meta["principal_ref"] != *args.get("principal_ref").unwrap_or(&Value::Null) - { - return Ok(json!({"ok":false,"status":"conflict","id":id, - "error":{"code":"input.scope_or_revision_changed"}})); - } - // Normalize the answer before duplicate detection: the index "2" and - // the selected label "office" must be the same committed response. - let allowed = crate::choice::parse_choice(&json!({ - "options": meta["options"], "reply": reply - }))?; - let normalized = if allowed["ok"] == true { - allowed["value"].clone() - } else if meta["freeform"] == true && !reply.trim().is_empty() { - json!(reply.trim()) - } else { - return Ok(json!({"ok":false,"status":"invalid","id":id, - "error":{"code":"input.invalid_choice"}})); - }; - if existing["status"] == "resumed" { - if existing["result"] == normalized { - return Ok(json!({"ok":true,"status":"resumed","id":id, - "value":normalized,"reused":true})); - } - return Ok(json!({"ok":false,"status":"conflict","id":id, - "error":{"code":"input.already_answered"}})); - } - if existing["status"] != "waiting_input" { - return Ok(json!({"ok":false,"status":"conflict","id":id})); - } - let saved = resume::resume_save(&json!({ - "id": id, "resume_dir": args.get("resume_dir"), - "checkpoint_v2": true, - "status": "resumed", - "task": existing["task"], - "meta": meta, - "result": normalized - }))?; - if saved["ok"] != true { - return Err("unable to commit resumed input".into()); - } - Ok(json!({"ok":true,"status":"resumed","id":id, - "value":normalized,"reused":false})) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicU64, Ordering}; - static SEQ: AtomicU64 = AtomicU64::new(0); - - fn fixture() -> (String, String) { - let id = format!("gate_{}_{}",std::process::id(),SEQ.fetch_add(1,Ordering::Relaxed)); - let dir = format!("target/mq-gate-test-{id}"); - (id, dir) - } - - #[test] - fn persists_answer_without_duplicate_side_effect_or_changed_reply() { - let (id, dir) = fixture(); - let initial = json!({"id":id,"resume_dir":dir,"question":"Choose?", - "options":["chat","office"],"source_revision":"v1", - "session_id":"s1","principal_ref":"u1","freeform":false}); - assert_eq!(input_open(&initial).unwrap()["status"], "waiting_input"); - assert_eq!(input_open(&initial).unwrap()["reused"], true); - let v = json!({"id":id,"resume_dir":dir,"reply":"2", - "source_revision":"v1","session_id":"s1","principal_ref":"u1"}); - assert_eq!(input_resume(&v).unwrap()["value"], "office"); - assert_eq!(input_resume(&v).unwrap()["reused"], true); - assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir, - "reply":"office","source_revision":"v1","session_id":"s1", - "principal_ref":"u1"})).unwrap()["reused"], true); - assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir, - "reply":"chat","source_revision":"v1","session_id":"s1", - "principal_ref":"u1"})).unwrap()["status"], "conflict"); - assert_eq!(input_open(&initial).unwrap()["status"], "resumed"); - } - - #[test] - fn prevents_changed_source_or_unauthorized_session() { - let (id, dir) = fixture(); - let initial = json!({"id":id,"resume_dir":dir,"question":"Proceed?", - "options":["yes","no"],"source_revision":"v1", - "session_id":"s1","principal_ref":"u1"}); - input_open(&initial).unwrap(); - for (rev,session) in [("v2","s1"),("v1","other")] { - assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir,"reply":"yes", - "source_revision":rev,"session_id":session, - "principal_ref":"u1"})).unwrap()["status"], "conflict"); - } - } - - #[test] - fn invalid_choice_keeps_gate_open_and_no_freeform_is_enforced() { - let (id, dir) = fixture(); - input_open(&json!({"id":id,"resume_dir":dir,"question":"Pick", - "options":["a","b"],"freeform":false, - "source_revision":"v1"})).unwrap(); - assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir,"reply":"??", - "source_revision":"v1"})).unwrap()["status"], "invalid"); - assert_eq!(resume::resume_load(&json!({"id":id,"resume_dir":dir})).unwrap()["status"], "waiting_input"); - } -} diff --git a/plugins/agent/src/kb.rs b/plugins/agent/src/kb.rs deleted file mode 100755 index bc375f7..0000000 --- a/plugins/agent/src/kb.rs +++ /dev/null @@ -1,1600 +0,0 @@ -//! OKF agent-kb helpers (plugin-side). No dependency on marqdo `src/host`. - -use std::collections::HashMap; -use std::fs; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -pub fn normalize_goal(raw: &str) -> String { - let t = raw.trim(); - let mut out = String::with_capacity(t.len()); - let mut prev_space = false; - for c in t.chars() { - if c.is_whitespace() { - if !prev_space && !out.is_empty() { - out.push(' '); - prev_space = true; - } - } else { - out.push(c); - prev_space = false; - } - } - out -} - -/// Light rule-based canonicalize (no model): strip standing prefixes, trailing `?`/`?`/`。`. -pub fn canonicalize_goal_str(raw: &str) -> String { - let mut s = raw.trim().to_string(); - const PREFIXES: &[&str] = &[ - "你是一个智能体,", - "你是一个智能体,", - "你是一个智能体:", - "你是一个智能体:", - "你是一个智能体", - "作为一个智能体,", - "作为一个智能体,", - "作为一个智能体:", - "作为一个智能体:", - "作为一个智能体", - "You are an agent, ", - "You are an agent,", - "You are an agent. ", - "You are an agent.", - "You are an agent ", - "You are an agent", - "As an agent, ", - "As an agent,", - "As an agent ", - "As an agent", - ]; - for p in PREFIXES { - if let Some(rest) = s.strip_prefix(p) { - s = rest.trim_start().to_string(); - break; - } - } - while s.ends_with('?') || s.ends_with('?') || s.ends_with('。') { - s.pop(); - while s.ends_with(|c: char| c.is_whitespace()) { - s.pop(); - } - } - normalize_goal(&s) -} - -pub fn goal_sig_hex(material: &str) -> String { - let mut h: u64 = 5381; - for b in material.as_bytes() { - h = h.wrapping_mul(33).wrapping_add(u64::from(*b)); - } - format!("{h:016x}")[..12].to_string() -} - -pub fn goal_slug_str(raw: &str) -> String { - let n = normalize_goal(raw); - let mut out = String::new(); - for c in n.chars() { - if c.is_ascii_alphanumeric() { - out.push(c.to_ascii_lowercase()); - } else if !c.is_ascii() - && !c.is_whitespace() - && !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') - { - if c.is_alphanumeric() { - out.push(c); - } else if !out.is_empty() && !out.ends_with('-') { - out.push('-'); - } - } else if !out.is_empty() && !out.ends_with('-') { - out.push('-'); - } - } - while out.ends_with('-') { - out.pop(); - } - let mut truncated = String::new(); - for c in out.chars() { - if truncated.chars().count() >= 48 { - break; - } - truncated.push(c); - } - while truncated.ends_with('-') { - truncated.pop(); - } - if truncated.is_empty() { - "task".into() - } else { - truncated - } -} - -fn tools_fingerprint(tools: Option<&Value>) -> String { - match tools { - None | Some(Value::Null) => String::new(), - Some(Value::Array(items)) => { - let mut names: Vec = items - .iter() - .filter_map(|v| match v { - Value::String(s) => Some(s.trim().to_string()), - Value::Object(entries) => entries - .get("工具") - .or_else(|| entries.get("name")) - .or_else(|| entries.get("tool")) - .and_then(|v| v.as_str()) - .map(|s| s.trim().to_string()), - _ => None, - }) - .filter(|s| !s.is_empty()) - .collect(); - names.sort(); - names.join("\n") - } - Some(Value::String(s)) => { - let t = s.trim(); - if t.is_empty() { - String::new() - } else { - t.to_string() - } - } - _ => String::new(), - } -} - -fn material_for(goal: &str, tools: Option<&Value>) -> String { - let mut material = normalize_goal(goal); - let fp = tools_fingerprint(tools); - if !fp.is_empty() { - material.push('\n'); - material.push_str(&fp); - } - material -} - -fn resolve_path(rel: &str) -> PathBuf { - let p = PathBuf::from(rel); - if p.is_absolute() { - return p; - } - // Prefer host cwd (entry file directory) via host_query when available. - let base = (|| { - let q = crate::host_query_json("cwd")?; - q.as_str() - .map(PathBuf::from) - .ok_or_else(|| "cwd not text".to_string()) - })() - .or_else(|_| std::env::current_dir().map_err(|e| e.to_string())) - .unwrap_or_else(|_| PathBuf::from(".")); - base.join(p) -} - -fn yaml_escape(s: &str) -> String { - if s.is_empty() - || s.contains(':') - || s.contains('#') - || s.contains('"') - || s.contains('\'') - || s.contains('\n') - || s.starts_with(' ') - { - format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) - } else { - s.to_string() - } -} - -fn extract_fm_field(source: &str, key: &str) -> Option { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return None; - } - let prefix = format!("{key}:"); - for line in lines.iter().skip(1) { - let t = line.trim(); - if t == "---" { - break; - } - if let Some(rest) = t.strip_prefix(&prefix) { - return Some(rest.trim().trim_matches('"').to_string()); - } - } - None -} - -/// Parse Task FM `aliases:` as inline list `[a, b]`, comma string, or YAML `- item` block. -fn extract_fm_aliases(source: &str) -> Vec { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return Vec::new(); - } - let mut out = Vec::new(); - let mut i = 1usize; - while i < lines.len() { - let t = lines[i].trim(); - if t == "---" { - break; - } - if let Some(rest) = t.strip_prefix("aliases:") { - let rest = rest.trim(); - if rest.is_empty() { - i += 1; - while i < lines.len() { - let body = lines[i]; - let bt = body.trim(); - if bt == "---" { - break; - } - if let Some(item) = bt.strip_prefix("- ") { - let a = normalize_goal(item.trim().trim_matches('"')); - if !a.is_empty() { - out.push(a); - } - i += 1; - continue; - } - if bt == "-" { - i += 1; - continue; - } - if !body.starts_with(' ') && !body.starts_with('\t') && !bt.is_empty() { - break; - } - i += 1; - } - break; - } - let inline = rest.trim_matches(|c| c == '[' || c == ']'); - for part in inline.split(',') { - let a = normalize_goal(part.trim().trim_matches('"')); - if !a.is_empty() { - out.push(a); - } - } - break; - } - i += 1; - } - out -} - -fn format_aliases_yaml(aliases: &[String]) -> String { - if aliases.is_empty() { - return String::new(); - } - let mut s = String::from("aliases:\n"); - for a in aliases { - s.push_str(" - "); - s.push_str(&yaml_escape(a)); - s.push('\n'); - } - s -} - -fn set_fm_field(source: &str, key: &str, value: &str) -> String { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return source.to_string(); - } - let prefix = format!("{key}:"); - let mut out = Vec::new(); - let mut replaced = false; - let mut in_fm = true; - for (i, line) in lines.iter().enumerate() { - if i == 0 { - out.push((*line).to_string()); - continue; - } - if in_fm && line.trim() == "---" { - if !replaced { - out.push(format!("{key}: {value}")); - } - in_fm = false; - out.push((*line).to_string()); - continue; - } - if in_fm && line.trim().starts_with(&prefix) { - out.push(format!("{key}: {value}")); - replaced = true; - } else { - out.push((*line).to_string()); - } - } - out.join("\n") + if source.ends_with('\n') { "\n" } else { "" } -} - -fn kb_rel(kb_dir: &str, parts: &str) -> String { - format!("{}/{}", kb_dir.trim_end_matches('/'), parts) -} - -fn resolve_skill_paths( - root: &Path, - sig: &str, - slug_hint: &str, -) -> Option<(PathBuf, PathBuf, PathBuf, String)> { - let tasks_dir = root.join("concepts/tasks"); - let skills_dir = root.join("concepts/skills"); - let res_dir = root.join("resources"); - - let sig4 = if sig.len() >= 4 { &sig[..4] } else { sig }; - for slug in [slug_hint.to_string(), format!("{slug_hint}-{sig4}")] { - let task = tasks_dir.join(format!("{slug}.md")); - if task.is_file() { - if let Ok(src) = fs::read_to_string(&task) { - let fm_sig = extract_fm_field(&src, "sig"); - if fm_sig.as_deref() == Some(sig) || fm_sig.is_none() { - let skill = skills_dir.join(format!("{slug}.md")); - let res = res_dir.join(format!("{slug}.mq.md")); - if skill.is_file() && res.is_file() { - return Some((task, skill, res, slug)); - } - } - } - } - } - - if tasks_dir.is_dir() { - if let Ok(rd) = fs::read_dir(&tasks_dir) { - for ent in rd.flatten() { - let p = ent.path(); - if p.extension().and_then(|e| e.to_str()) != Some("md") { - continue; - } - let Ok(src) = fs::read_to_string(&p) else { - continue; - }; - if extract_fm_field(&src, "sig").as_deref() == Some(sig) { - let stem = p.file_stem()?.to_string_lossy().into_owned(); - let skill = skills_dir.join(format!("{stem}.md")); - let res = res_dir.join(format!("{stem}.mq.md")); - if skill.is_file() && res.is_file() { - return Some((p, skill, res, stem)); - } - } - } - } - } - - let task = tasks_dir.join(format!("{sig}.md")); - let skill = skills_dir.join(format!("{sig}.md")); - let res = res_dir.join(format!("{sig}.mq.md")); - if task.is_file() && skill.is_file() && res.is_file() { - return Some((task, skill, res, sig.to_string())); - } - None -} - -/// Second-pass exact match: `normalize_goal(query)` equals a Task FM alias. -fn resolve_skill_paths_by_alias( - root: &Path, - goal_norm: &str, -) -> Option<(PathBuf, PathBuf, PathBuf, String)> { - if goal_norm.is_empty() { - return None; - } - let tasks_dir = root.join("concepts/tasks"); - let skills_dir = root.join("concepts/skills"); - let res_dir = root.join("resources"); - if !tasks_dir.is_dir() { - return None; - } - let rd = fs::read_dir(&tasks_dir).ok()?; - for ent in rd.flatten() { - let p = ent.path(); - if p.extension().and_then(|e| e.to_str()) != Some("md") { - continue; - } - let Ok(src) = fs::read_to_string(&p) else { - continue; - }; - let aliases = extract_fm_aliases(&src); - if !aliases.iter().any(|a| a == goal_norm) { - continue; - } - let stem = p.file_stem()?.to_string_lossy().into_owned(); - let skill = skills_dir.join(format!("{stem}.md")); - let res = res_dir.join(format!("{stem}.mq.md")); - if skill.is_file() && res.is_file() { - return Some((p, skill, res, stem)); - } - } - None -} - -fn unique_slug(root: &Path, base: &str, sig: &str) -> String { - let tasks = root.join("concepts/tasks"); - let candidate = tasks.join(format!("{base}.md")); - if !candidate.is_file() { - return base.to_string(); - } - if let Ok(src) = fs::read_to_string(&candidate) { - if extract_fm_field(&src, "sig").as_deref() == Some(sig) { - return base.to_string(); - } - } - let sig4 = if sig.len() >= 4 { &sig[..4] } else { sig }; - format!("{base}-{sig4}") -} - -fn llm_free_score(src: &str) -> (bool, i64) { - let lower = src.to_ascii_lowercase(); - let has_step = src.contains(".step") || src.contains(".单步") || src.contains("agent.step"); - let has_llm = lower.contains("llm.llm") - || lower.contains("llm.complete") - || src.contains("大模型") - || src.contains(".complete"); - let free = !has_step && !has_llm; - let len = src.len() as i64; - let quality = if free { - 1_000_000 - len.min(999_999) - } else { - 100_000 - len.min(99_999) - }; - (free, quality) -} - -fn write_task_concept( - path: &Path, - sig: &str, - slug: &str, - goal: &str, - now: &str, - aliases: &[String], -) -> Result<(), String> { - if let Some(p) = path.parent() { - fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}"))?; - } - let title: String = goal.chars().take(48).collect(); - let mut merged: Vec = Vec::new(); - if path.is_file() { - if let Ok(old) = fs::read_to_string(path) { - for a in extract_fm_aliases(&old) { - if !merged.iter().any(|x| x == &a) { - merged.push(a); - } - } - } - } - for a in aliases { - let a = normalize_goal(a); - if a.is_empty() || a == goal { - continue; - } - if !merged.iter().any(|x| x == &a) { - merged.push(a); - } - } - let alias_block = format_aliases_yaml(&merged); - let body = format!( - r#"--- -type: Marqdo Task -title: {title} -description: {goal_e} -sig: {sig} -status: stable -tags: [agent-task] -skill: ../skills/{slug}.md -{alias_block}generated: - by: marqdo-agent/plan - at: {now} -verified: - by: marqdo-agent/spawn - at: {now} ---- - -# Task - -See [skill](../skills/{slug}.md). -"#, - title = yaml_escape(&title), - goal_e = yaml_escape(goal), - sig = sig, - slug = slug, - alias_block = alias_block, - now = now, - ); - fs::write(path, body).map_err(|e| format!("write task: {e}")) -} - -fn write_skill_concept( - path: &Path, - sig: &str, - slug: &str, - goal: &str, - status: &str, - llm_free: bool, - quality: i64, - hits: i64, - now: &str, - meta: &SkillMeta, -) -> Result<(), String> { - if let Some(p) = path.parent() { - fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}"))?; - } - let title: String = goal.chars().take(48).collect(); - let mut extra = String::new(); - if let Some(ref s) = meta.applies_when { - extra.push_str(&format!("applies_when: {}\n", yaml_escape(s))); - } - if let Some(ref s) = meta.fixtures { - extra.push_str(&format!("fixtures: {}\n", yaml_escape(s))); - } - if let Some(ref s) = meta.sandbox_profile { - extra.push_str(&format!("sandbox_profile: {}\n", yaml_escape(s))); - } - if let Some(ref s) = meta.proof { - extra.push_str(&format!("proof: {}\n", yaml_escape(s))); - } - let body = format!( - r#"--- -type: Marqdo Agent Skill -title: {title} -sig: {sig} -resource: ../../resources/{slug}.mq.md -status: {status} -llm_free: {llm_free} -quality: {quality} -hits: {hits} -{extra}generated: - by: marqdo-agent/plan - at: {now} -verified: - by: marqdo-agent/spawn - at: {now} ---- - -# Skill - -Prefer spawning `resource` over re-planning. -"#, - title = yaml_escape(&title), - sig = sig, - slug = slug, - status = status, - llm_free = if llm_free { "true" } else { "false" }, - quality = quality, - hits = hits, - extra = extra, - now = now, - ); - fs::write(path, body).map_err(|e| format!("write skill: {e}")) -} - -#[derive(Default)] -struct SkillMeta { - applies_when: Option, - fixtures: Option, - sandbox_profile: Option, - proof: Option, -} - -fn skill_meta_from_src(src: &str) -> SkillMeta { - SkillMeta { - applies_when: extract_fm_field(src, "applies_when"), - fixtures: extract_fm_field(src, "fixtures"), - sandbox_profile: extract_fm_field(src, "sandbox_profile"), - proof: extract_fm_field(src, "proof"), - } -} - -fn refresh_index(root: &Path, slug: &str, goal: &str) -> Result<(), String> { - let index = root.join("index.md"); - let line = format!( - "- [`{slug}`](concepts/tasks/{slug}.md) — {}\n", - goal.chars().take(60).collect::() - ); - if index.is_file() { - let mut cur = fs::read_to_string(&index).map_err(|e| format!("read index: {e}"))?; - let marker = format!("concepts/tasks/{slug}.md"); - if !cur.contains(&marker) { - if !cur.ends_with('\n') { - cur.push('\n'); - } - cur.push_str(&line); - fs::write(&index, cur).map_err(|e| format!("write index: {e}"))?; - } - } else { - let body = format!( - "---\ntype: Marqdo Catalog\ntitle: agent-kb\ngenerated:\n by: marqdo-agent/plan\n---\n\n# Agent knowledge base\n\n{line}" - ); - fs::write(&index, body).map_err(|e| format!("write index: {e}"))?; - } - Ok(()) -} - -fn now_rfc3339() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) -} - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - args.get(key) - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("missing text `{key}`")) -} - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty()) -} - -fn opt_tools(args: &Value) -> Option<&Value> { - args.get("tools").filter(|t| !t.is_null()) -} - -pub fn goal_sig(args: &Value) -> Result { - let goal = arg_text(args, "goal")?; - Ok(Value::String(goal_sig_hex(&material_for( - goal, - opt_tools(args), - )))) -} - -pub fn goal_slug(args: &Value) -> Result { - let goal = arg_text(args, "goal")?; - Ok(Value::String(goal_slug_str(goal))) -} - -pub fn kb_canonicalize(args: &Value) -> Result { - let goal = arg_text(args, "goal")?; - Ok(Value::String(canonicalize_goal_str(goal))) -} - -fn arg_bool(args: &Value, key: &str, default: bool) -> bool { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Bool(b)) => *b, - Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0, - Some(Value::String(s)) => matches!( - s.trim(), - "1" | "true" | "True" | "TRUE" | "yes" | "Yes" | "on" | "ON" - ), - _ => default, - } -} - -fn arg_f64(args: &Value, key: &str, default: f64) -> f64 { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Number(n)) => n.as_f64().unwrap_or(default), - Some(Value::String(s)) => s.parse().unwrap_or(default), - _ => default, - } -} - -/// Character bigram bag (whitespace stripped). Sparse lexical vectorization — not an embedding model. -pub fn char_bigram_tf(text: &str) -> HashMap { - let chars: Vec = text.chars().filter(|c| !c.is_whitespace()).collect(); - let mut m = HashMap::new(); - if chars.is_empty() { - return m; - } - if chars.len() == 1 { - m.insert(chars[0].to_string(), 1.0); - return m; - } - for w in chars.windows(2) { - let key = format!("{}{}", w[0], w[1]); - *m.entry(key).or_insert(0.0) += 1.0; - } - m -} - -pub fn cosine_tf(a: &HashMap, b: &HashMap) -> f64 { - let mut na = 0.0; - let mut nb = 0.0; - for v in a.values() { - na += v * v; - } - for v in b.values() { - nb += v * v; - } - if na == 0.0 || nb == 0.0 { - return 0.0; - } - let mut dot = 0.0; - if a.len() <= b.len() { - for (k, va) in a { - if let Some(vb) = b.get(k) { - dot += va * vb; - } - } - } else { - for (k, vb) in b { - if let Some(va) = a.get(k) { - dot += va * vb; - } - } - } - dot / (na.sqrt() * nb.sqrt()) -} - -#[cfg(test)] -fn near_score(query: &str, candidate: &str) -> f64 { - let q = canonicalize_goal_str(query); - let c = canonicalize_goal_str(candidate); - if q.is_empty() || c.is_empty() { - return 0.0; - } - cosine_tf(&char_bigram_tf(&q), &char_bigram_tf(&c)) -} - -fn task_near_material(src: &str, slug: &str) -> String { - let title = extract_fm_field(src, "title").unwrap_or_else(|| slug.to_string()); - let desc = extract_fm_field(src, "description").unwrap_or_default(); - let aliases = extract_fm_aliases(src); - let mut parts = vec![title, desc]; - parts.extend(aliases); - parts.join(" ") -} - -#[derive(Clone)] -struct NearCand { - slug: String, - title: String, - score: f64, -} - -fn rank_near_tasks(root: &Path, goal: &str, limit: usize) -> Vec { - let tasks_dir = root.join("concepts/tasks"); - let skills_dir = root.join("concepts/skills"); - let res_dir = root.join("resources"); - if !tasks_dir.is_dir() { - return Vec::new(); - } - let q = canonicalize_goal_str(goal); - let qv = char_bigram_tf(&q); - if qv.is_empty() { - return Vec::new(); - } - let mut out = Vec::new(); - let Ok(rd) = fs::read_dir(&tasks_dir) else { - return Vec::new(); - }; - for ent in rd.flatten() { - let p = ent.path(); - if p.extension().and_then(|e| e.to_str()) != Some("md") { - continue; - } - let Ok(src) = fs::read_to_string(&p) else { - continue; - }; - let slug = p - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - if slug.is_empty() { - continue; - } - if !skills_dir.join(format!("{slug}.md")).is_file() - || !res_dir.join(format!("{slug}.mq.md")).is_file() - { - continue; - } - let title = extract_fm_field(&src, "title").unwrap_or_else(|| slug.clone()); - let material = task_near_material(&src, &slug); - let score = cosine_tf(&qv, &char_bigram_tf(&canonicalize_goal_str(&material))); - if score > 0.0 { - out.push(NearCand { - slug, - title, - score, - }); - } - } - out.sort_by(|a, b| { - b.score - .partial_cmp(&a.score) - .unwrap_or(std::cmp::Ordering::Equal) - .then_with(|| a.slug.cmp(&b.slug)) - }); - out.truncate(limit.max(1)); - out -} - -fn lookup_hit_payload( - kb: &str, - root: &Path, - skill_path: &Path, - slug: &str, - match_kind: &str, - query_sig: &str, - score: Option, -) -> Result { - let skill_src = - fs::read_to_string(skill_path).map_err(|e| format!("kb_lookup read skill: {e}"))?; - let mut status = extract_fm_field(&skill_src, "status").unwrap_or_else(|| "stable".into()); - if status == "deprecated" || status == "draft" { - return Ok(Value::Null); - } - let mut llm_free = extract_fm_field(&skill_src, "llm_free") - .map(|s| s == "true" || s == "True") - .unwrap_or(false); - let mut quality = extract_fm_field(&skill_src, "quality") - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - let hits = extract_fm_field(&skill_src, "hits") - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - let skill_sig = extract_fm_field(&skill_src, "sig").unwrap_or_else(|| query_sig.to_string()); - - let res_path = root.join("resources").join(format!("{slug}.mq.md")); - if res_path.is_file() { - if let Ok(res_src) = fs::read_to_string(&res_path) { - let (res_free, res_q) = llm_free_score(&res_src); - if res_free { - llm_free = true; - status = "stable".into(); - } - if res_q > quality { - quality = res_q; - } - } - } - - let mut out = json!({ - "hit": true, - "match": match_kind, - "sig": skill_sig, - "query_sig": query_sig, - "slug": slug, - "status": status, - "llm_free": llm_free, - "quality": quality, - "hits": hits, - "resource": kb_rel(kb, &format!("resources/{slug}.mq.md")), - "task": kb_rel(kb, &format!("concepts/tasks/{slug}.md")), - "skill": kb_rel(kb, &format!("concepts/skills/{slug}.md")), - }); - if let Some(s) = score { - if let Some(obj) = out.as_object_mut() { - obj.insert("score".into(), json!((s * 1000.0).round() / 1000.0)); - } - } - Ok(out) -} - -fn resolve_skill_paths_by_slug( - root: &Path, - slug: &str, -) -> Option<(PathBuf, PathBuf, PathBuf, String)> { - let slug = slug.trim(); - if slug.is_empty() { - return None; - } - let task = root.join("concepts/tasks").join(format!("{slug}.md")); - let skill = root.join("concepts/skills").join(format!("{slug}.md")); - let res = root.join("resources").join(format!("{slug}.mq.md")); - if task.is_file() && skill.is_file() && res.is_file() { - Some((task, skill, res, slug.to_string())) - } else { - None - } -} - -pub fn kb_lookup(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let root = resolve_path(kb); - let tools = opt_tools(args); - - // Soft-match REUSE: resolve by explicit slug. - if let Some(slug) = args - .get("slug") - .and_then(|v| v.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - { - let Some((_task, skill_path, _res, slug)) = resolve_skill_paths_by_slug(&root, slug) else { - return Ok(Value::Null); - }; - let query_sig = args - .get("goal") - .and_then(|v| v.as_str()) - .map(|g| goal_sig_hex(&material_for(g, tools))) - .unwrap_or_default(); - return lookup_hit_payload(kb, &root, &skill_path, &slug, "soft", &query_sig, None); - } - - let goal = arg_text(args, "goal")?; - let goal_n = normalize_goal(goal); - let query_sig = goal_sig_hex(&material_for(goal, tools)); - let slug_hint = goal_slug_str(goal); - let mut match_kind = "exact"; - let mut near_score_hit: Option = None; - let resolved = resolve_skill_paths(&root, &query_sig, &slug_hint) - .or_else(|| { - match_kind = "alias"; - resolve_skill_paths_by_alias(&root, &goal_n) - }) - .or_else(|| { - let canon = canonicalize_goal_str(goal); - if canon.is_empty() || canon == goal_n { - return None; - } - match_kind = "canonical"; - let sig2 = goal_sig_hex(&material_for(&canon, tools)); - let slug2 = goal_slug_str(&canon); - resolve_skill_paths(&root, &sig2, &slug2) - .or_else(|| resolve_skill_paths_by_alias(&root, &canon)) - }) - .or_else(|| { - if !arg_bool(args, "near_match", false) { - return None; - } - let threshold = arg_f64(args, "near_threshold", 0.78); - let ranked = rank_near_tasks(&root, goal, 8); - let best = ranked.first()?; - if best.score < threshold { - return None; - } - match_kind = "near"; - near_score_hit = Some(best.score); - resolve_skill_paths_by_slug(&root, &best.slug) - }); - let Some((_task, skill_path, _res, slug)) = resolved else { - return Ok(Value::Null); - }; - - lookup_hit_payload( - kb, - &root, - &skill_path, - &slug, - match_kind, - &query_sig, - near_score_hit, - ) -} - -pub fn kb_near_match(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let goal = arg_text(args, "goal")?; - let limit = match args.get("limit") { - None | Some(Value::Null) => 8usize, - Some(Value::Number(n)) => n.as_u64().unwrap_or(8) as usize, - Some(Value::String(s)) => s.parse().unwrap_or(8), - _ => 8, - } - .clamp(1, 40); - let root = resolve_path(kb); - let ranked = rank_near_tasks(&root, goal, limit); - let candidates: Vec = ranked - .iter() - .map(|c| { - json!({ - "slug": c.slug, - "title": c.title, - "score": (c.score * 1000.0).round() / 1000.0, - }) - }) - .collect(); - let best = ranked.first().map(|c| { - json!({ - "slug": c.slug, - "title": c.title, - "score": (c.score * 1000.0).round() / 1000.0, - }) - }); - let score = ranked.first().map(|c| (c.score * 1000.0).round() / 1000.0); - Ok(json!({ - "candidates": candidates, - "count": ranked.len() as i64, - "best": best, - "score": score, - })) -} - -pub fn kb_list_tasks(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let limit = match args.get("limit") { - None | Some(Value::Null) => 40usize, - Some(Value::Number(n)) => n.as_u64().unwrap_or(40) as usize, - Some(Value::String(s)) => s.parse().unwrap_or(40), - _ => 40, - } - .clamp(1, 200); - let root = resolve_path(kb); - let tasks_dir = root.join("concepts/tasks"); - let skills_dir = root.join("concepts/skills"); - let mut tasks: Vec = Vec::new(); - if tasks_dir.is_dir() { - let mut ents: Vec<_> = fs::read_dir(&tasks_dir) - .map_err(|e| format!("list tasks: {e}"))? - .flatten() - .collect(); - ents.sort_by_key(|e| e.file_name()); - for ent in ents { - if tasks.len() >= limit { - break; - } - let p = ent.path(); - if p.extension().and_then(|e| e.to_str()) != Some("md") { - continue; - } - let Ok(src) = fs::read_to_string(&p) else { - continue; - }; - let slug = p - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - if slug.is_empty() { - continue; - } - let title = extract_fm_field(&src, "title").unwrap_or_else(|| slug.clone()); - let description = extract_fm_field(&src, "description").unwrap_or_default(); - let aliases = extract_fm_aliases(&src); - let alias_count = aliases.len() as i64; - let skill_path = skills_dir.join(format!("{slug}.md")); - let (status, llm_free, hits) = if skill_path.is_file() { - match fs::read_to_string(&skill_path) { - Ok(sk) => { - let status = - extract_fm_field(&sk, "status").unwrap_or_else(|| "stable".into()); - let llm_free = extract_fm_field(&sk, "llm_free") - .map(|s| s == "true" || s == "True") - .unwrap_or(false); - let hits = extract_fm_field(&sk, "hits") - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - (status, llm_free, hits) - } - Err(_) => ("unreadable".into(), false, 0), - } - } else { - ("missing_skill".into(), false, 0) - }; - tasks.push(json!({ - "slug": slug, - "title": title, - "description": description, - "aliases": aliases, - "alias_count": alias_count, - "status": status, - "llm_free": llm_free, - "hits": hits, - })); - } - } - let count = tasks.len() as i64; - Ok(json!({ "tasks": tasks, "count": count })) -} - -pub fn kb_add_alias(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let slug = arg_text(args, "slug")?; - let alias = arg_text(args, "alias")?; - let alias_n = normalize_goal(alias); - if alias_n.is_empty() { - return Ok(json!({ "ok": false, "reason": "empty_alias" })); - } - let root = resolve_path(kb); - let path = root.join("concepts/tasks").join(format!("{slug}.md")); - if !path.is_file() { - return Ok(json!({ "ok": false, "reason": "missing_task" })); - } - let src = fs::read_to_string(&path).map_err(|e| format!("read task: {e}"))?; - let sig = extract_fm_field(&src, "sig").unwrap_or_default(); - let goal = extract_fm_field(&src, "description") - .or_else(|| extract_fm_field(&src, "title")) - .unwrap_or_default(); - let now = now_rfc3339(); - write_task_concept(&path, &sig, slug, &goal, &now, &[alias_n.clone()])?; - Ok(json!({ "ok": true, "slug": slug, "alias": alias_n })) -} - -pub fn kb_record_hit(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let goal = arg_text(args, "goal")?; - let goal_n = normalize_goal(goal); - let tools = opt_tools(args); - let sig = goal_sig_hex(&material_for(goal, tools)); - let slug_hint = goal_slug_str(goal); - let root = resolve_path(kb); - let Some((_t, skill_path, _r, slug)) = resolve_skill_paths(&root, &sig, &slug_hint) - .or_else(|| resolve_skill_paths_by_alias(&root, &goal_n)) - .or_else(|| { - let canon = canonicalize_goal_str(goal); - if canon.is_empty() || canon == goal_n { - return None; - } - let sig2 = goal_sig_hex(&material_for(&canon, tools)); - let slug2 = goal_slug_str(&canon); - resolve_skill_paths(&root, &sig2, &slug2) - .or_else(|| resolve_skill_paths_by_alias(&root, &canon)) - }) - else { - return Ok(Value::Null); - }; - let src = fs::read_to_string(&skill_path).map_err(|e| format!("read skill: {e}"))?; - let status = extract_fm_field(&src, "status").unwrap_or_else(|| "stable".into()); - let llm_free = extract_fm_field(&src, "llm_free") - .map(|s| s == "true" || s == "True") - .unwrap_or(false); - let hits = extract_fm_field(&src, "hits") - .and_then(|s| s.parse::().ok()) - .unwrap_or(0) - + 1; - let next = set_fm_field(&src, "hits", &hits.to_string()); - fs::write(&skill_path, next).map_err(|e| format!("write skill hits: {e}"))?; - - let every = match args.get("improve_every") { - None | Some(Value::Null) => 0i64, - Some(Value::Number(n)) => n.as_i64().unwrap_or(0), - Some(Value::String(s)) => s.parse().unwrap_or(0), - _ => 0, - }; - let improve_due = every > 0 - && status == "candidate" - && !llm_free - && hits > 0 - && hits % every == 0; - - Ok(json!({ - "hits": hits, - "slug": slug, - "sig": sig, - "status": status, - "llm_free": llm_free, - "improve_due": improve_due, - })) -} - -/// Run workbook (or FM `proof:` / `fixtures:` path) inside CoW sandbox; discard after. -/// O2: llm_free promote requires this proof to succeed (unless `require_proof=false`). -fn sandbox_proof(workbook: &Path, proof_rel: Option<&str>) -> Result<(bool, String), String> { - let root = workbook - .parent() - .ok_or_else(|| "sandbox_proof: workbook has no parent".to_string())?; - // Always pass an absolute root so host `sandbox_open` does not re-join cwd. - let root_abs = if root.is_absolute() { - root.to_path_buf() - } else { - fs::canonicalize(root).unwrap_or_else(|_| { - std::env::current_dir() - .unwrap_or_else(|_| PathBuf::from(".")) - .join(root) - }) - }; - let root_abs = fs::canonicalize(&root_abs).unwrap_or(root_abs); - let default_name = workbook - .file_name() - .and_then(|s| s.to_str()) - .ok_or_else(|| "sandbox_proof: bad workbook name".to_string())?; - let path = proof_rel.unwrap_or(default_name); - let open = crate::host_query_json_args( - "sandbox_open", - &json!({ "root": root_abs.to_string_lossy() }), - )?; - let id = open - .get("id") - .and_then(|v| v.as_str()) - .ok_or_else(|| "sandbox_proof: open missing id".to_string())? - .to_string(); - let run = crate::host_query_json_args("sandbox_run", &json!({ "id": id, "path": path })); - let _ = crate::host_query_json_args("sandbox_discard", &json!({ "id": id })); - match run { - Ok(r) => { - let ok = r.get("ok").and_then(|v| v.as_bool()).unwrap_or(false); - let detail = r - .get("stderr") - .and_then(|v| v.as_str()) - .or_else(|| r.get("stdout").and_then(|v| v.as_str())) - .unwrap_or("") - .to_string(); - Ok((ok, detail)) - } - Err(e) => Ok((false, e)), - } -} - -pub fn kb_promote(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let goal = arg_text(args, "goal")?; - let workbook = arg_text(args, "workbook")?; - let goal_n = normalize_goal(goal); - let sig = goal_sig_hex(&material_for(goal, opt_tools(args))); - let base_slug = goal_slug_str(&goal_n); - let root = resolve_path(kb); - let slug = unique_slug(&root, &base_slug, &sig); - let src_path = resolve_path(workbook); - let src = fs::read_to_string(&src_path) - .map_err(|e| format!("kb_promote read workbook: {e}"))?; - let require_proof = args - .get("require_proof") - .and_then(|v| v.as_bool()) - .unwrap_or(true); - let proof_rel = extract_fm_field(&src, "proof") - .or_else(|| extract_fm_field(&src, "fixtures")); - if require_proof { - let (ok, detail) = sandbox_proof(&src_path, proof_rel.as_deref())?; - if !ok { - return Ok(json!({ - "promoted": false, - "reason": "sandbox_proof_failed", - "detail": detail, - "sig": sig, - "slug": slug, - "workbook": workbook, - "proof": proof_rel.unwrap_or_else(|| src_path.file_name().and_then(|s| s.to_str()).unwrap_or("").to_string()), - })); - } - } - let (llm_free, quality) = llm_free_score(&src); - let status = if llm_free { "stable" } else { "candidate" }; - - let skill_path = root.join("concepts/skills").join(format!("{slug}.md")); - let mut prev_hits = 0i64; - if skill_path.is_file() { - let old = fs::read_to_string(&skill_path).unwrap_or_default(); - prev_hits = extract_fm_field(&old, "hits") - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - let old_q = extract_fm_field(&old, "quality") - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - if quality < old_q { - return Ok(json!({ - "promoted": false, - "reason": "quality_worse", - "sig": sig, - "slug": slug, - })); - } - } - - let res_path = root.join("resources").join(format!("{slug}.mq.md")); - if let Some(p) = res_path.parent() { - fs::create_dir_all(p).map_err(|e| format!("mkdir resources: {e}"))?; - } - fs::write(&res_path, &src).map_err(|e| format!("write resource: {e}"))?; - - let now = now_rfc3339(); - // Optional extra aliases from caller (JSON array or single string). - let mut extra_aliases: Vec = Vec::new(); - if let Some(Value::Array(items)) = args.get("aliases") { - for v in items { - if let Some(s) = v.as_str() { - extra_aliases.push(s.to_string()); - } - } - } else if let Some(Value::String(s)) = args.get("aliases") { - extra_aliases.push(s.clone()); - } - write_task_concept( - &root.join("concepts/tasks").join(format!("{slug}.md")), - &sig, - &slug, - &goal_n, - &now, - &extra_aliases, - )?; - let meta = skill_meta_from_src(&src); - write_skill_concept( - &skill_path, - &sig, - &slug, - &goal_n, - status, - llm_free, - quality, - prev_hits, - &now, - &meta, - )?; - refresh_index(&root, &slug, &goal_n)?; - - Ok(json!({ - "promoted": true, - "sig": sig, - "slug": slug, - "resource": kb_rel(kb, &format!("resources/{slug}.mq.md")), - "llm_free": llm_free, - "quality": quality, - "status": status, - "hits": prev_hits, - "proof_ok": true, - "applies_when": meta.applies_when, - "fixtures": meta.fixtures, - "sandbox_profile": meta.sandbox_profile, - })) -} - -/// O5: mark a skill concept as `status: quarantine` and keep fixtures path in FM. -pub fn kb_quarantine(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let slug = arg_text(args, "slug")?; - let reason = opt_text(args, "reason").unwrap_or("sandbox_or_harness_failed"); - let root = resolve_path(kb); - let skill_path = root.join("concepts/skills").join(format!("{slug}.md")); - if !skill_path.is_file() { - return Ok(json!({ - "ok": false, - "reason": "skill_not_found", - "slug": slug, - "path": skill_path.to_string_lossy(), - })); - } - let src = fs::read_to_string(&skill_path) - .map_err(|e| format!("kb_quarantine read: {e}"))?; - let mut lines: Vec = Vec::new(); - let mut saw_status = false; - let mut in_fm = false; - for line in src.lines() { - let t = line.trim(); - if t == "---" { - if !in_fm { - in_fm = true; - lines.push(line.to_string()); - continue; - } else { - if !saw_status { - lines.push("status: quarantine".to_string()); - } - lines.push(format!("quarantine_reason: {}", yaml_escape(reason))); - in_fm = false; - lines.push(line.to_string()); - continue; - } - } - if in_fm && t.starts_with("status:") { - lines.push("status: quarantine".to_string()); - saw_status = true; - continue; - } - if in_fm && t.starts_with("llm_free:") { - lines.push("llm_free: false".to_string()); - continue; - } - lines.push(line.to_string()); - } - let body = lines.join("\n") + "\n"; - fs::write(&skill_path, body).map_err(|e| format!("kb_quarantine write: {e}"))?; - Ok(json!({ - "ok": true, - "slug": slug, - "status": "quarantine", - "reason": reason, - "path": skill_path.to_string_lossy(), - })) -} - -fn extract_result_text(observation: Option<&Value>) -> Option { - let obs = observation?; - if let Some(v) = obs.get("value") { - if let Some(t) = value_as_result_text(v) { - return Some(t); - } - } - let last_ok = obs.get("last_ok")?; - let result_val = match last_ok { - Value::Object(_) => last_ok.get("result")?.clone(), - Value::String(s) => { - let parsed: Value = serde_json::from_str(s).ok()?; - match &parsed { - Value::Object(_) => parsed.get("result")?.clone(), - other => other.clone(), - } - } - _ => return None, - }; - value_as_result_text(&result_val) -} - -fn value_as_result_text(result_val: &Value) -> Option { - match result_val { - Value::Null => None, - Value::String(t) => { - let t = t.trim(); - if t.is_empty() { - None - } else { - Some(t.to_string()) - } - } - Value::Number(n) => Some(n.to_string()), - Value::Bool(b) => Some(if *b { "true" } else { "false" }.into()), - _ => None, - } -} - -fn marqdo_quoted_text(s: &str) -> String { - let mut out = String::from("\""); - for c in s.chars() { - match c { - '\\' => out.push_str("\\\\"), - '"' => out.push_str("\\\""), - '\n' => out.push_str("\\n"), - '\t' => out.push_str("\\t"), - c => out.push(c), - } - } - out.push('"'); - out -} - -fn needs_step_solidify(src: &str) -> bool { - src.contains(".step") || src.contains(".单步") || src.contains("worker.step") -} - -pub fn workbook_solidify(args: &Value) -> Result { - let path = arg_text(args, "path")?; - let p = resolve_path(path); - let src = fs::read_to_string(&p).map_err(|e| format!("solidify read: {e}"))?; - if !needs_step_solidify(&src) { - return Ok(json!({ - "solidified": false, - "reason": "already_solid", - })); - } - let Some(result) = extract_result_text(args.get("observation")) else { - return Ok(json!({ - "solidified": false, - "reason": "no_result", - })); - }; - let lit = marqdo_quoted_text(&result); - let body = format!( - "---\ntitle: agent workbook\n---\n\n# main\n\n**`result` = {lit}**\n*`result`*\n" - ); - fs::write(&p, body).map_err(|e| format!("solidify write: {e}"))?; - Ok(json!({ - "solidified": true, - "result": result, - "path": path, - })) -} - -pub fn kb_task_files(args: &Value) -> Result { - let kb = arg_text(args, "kb_dir")?; - let goal = arg_text(args, "goal")?; - let _sig = goal_sig_hex(&material_for(goal, opt_tools(args))); - let slug = goal_slug_str(goal); - let root = resolve_path(kb); - let mut files: Vec = Vec::new(); - - let res = root.join("resources").join(format!("{slug}.mq.md")); - if res.is_file() { - files.push(Value::String(res.to_string_lossy().into_owned())); - } - - let explore = root.join("explore").join(&slug); - if explore.is_dir() { - if let Ok(rd) = fs::read_dir(&explore) { - for ent in rd.flatten() { - let p = ent.path(); - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if name.ends_with(".mq.md") { - files.push(Value::String(p.to_string_lossy().into_owned())); - } - } - } - } - - let runs = match args.get("runs_dir").and_then(|v| v.as_str()) { - None => resolve_path(".marqdo/agent-runs"), - Some(s) => resolve_path(s), - }; - if runs.is_dir() { - let prefix = format!("workbook-{slug}-"); - if let Ok(rd) = fs::read_dir(&runs) { - for ent in rd.flatten() { - let p = ent.path(); - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if name.starts_with(&prefix) && name.ends_with(".mq.md") { - files.push(Value::String(p.to_string_lossy().into_owned())); - } - } - } - } - - let count = files.len() as i64; - Ok(json!({ - "count": count, - "slug": slug, - "files": files, - })) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn slug_readable() { - let s = goal_slug_str("Reply with exactly the word pong and nothing else."); - assert!(s.contains("pong"), "{s}"); - assert!(!s.contains(' ')); - } - - #[test] - fn sig_stable() { - let a = goal_sig_hex("hello"); - assert_eq!(a, goal_sig_hex("hello")); - assert_eq!(a.len(), 12); - } - - #[test] - fn canonicalize_strips_standing_prefix() { - let c = canonicalize_goal_str("你是一个智能体,帮我规划明天的行程"); - assert_eq!(c, "帮我规划明天的行程"); - let c2 = canonicalize_goal_str("你是一个智能体,帮我规划明天的行程?"); - assert_eq!(c2, "帮我规划明天的行程"); - } - - #[test] - fn near_score_trip_near_dupes_high() { - let a = "帮我规划明天行程"; - let b = "帮我规划明天的行程"; - let s = near_score(a, b); - assert!(s >= 0.78, "expected high near score, got {s}"); - let c = "帮我完成明天的行程规划"; - let s2 = near_score(b, c); - let unrelated = near_score(b, "明天做什么好"); - assert!( - s2 > unrelated, - "paraphrase should beat unrelated: paraphrase={s2} unrelated={unrelated}" - ); - } - - #[test] - fn near_score_unrelated_low() { - let a = "帮我规划明天的行程"; - let b = "明天做什么好"; - let s = near_score(a, b); - assert!(s < 0.78, "expected below default threshold, got {s}"); - } - - #[test] - fn workbook_solidify_rewrites_step_workbook() { - let dir = std::env::temp_dir().join(format!( - "marqdo-solidify-{}", - std::process::id() - )); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join("wb.mq.md"); - fs::write( - &path, - "---\ntitle: t\n---\n\n# main\n\n*`r` = > `worker`.step task=hi *\n**`r`**\n", - ) - .unwrap(); - let path_s = path.to_string_lossy().into_owned(); - let args = json!({ - "path": path_s, - "observation": { "value": "pong" } - }); - let out = workbook_solidify(&args).unwrap(); - assert_eq!(out.get("solidified").and_then(|v| v.as_bool()), Some(true)); - let src = fs::read_to_string(&path).unwrap(); - assert!(!needs_step_solidify(&src), "still has step: {src}"); - assert!(src.contains("pong"), "{src}"); - let again = workbook_solidify(&args).unwrap(); - assert_eq!( - again.get("reason").and_then(|v| v.as_str()), - Some("already_solid") - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn workbook_solidify_no_result() { - let dir = std::env::temp_dir().join(format!( - "marqdo-solidify-nr-{}", - std::process::id() - )); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join("wb.mq.md"); - fs::write(&path, "*`r` = > `worker`.step task=hi *\n").unwrap(); - let path_s = path.to_string_lossy().into_owned(); - let args = json!({ "path": path_s }); - let out = workbook_solidify(&args).unwrap(); - assert_eq!(out.get("solidified").and_then(|v| v.as_bool()), Some(false)); - assert_eq!(out.get("reason").and_then(|v| v.as_str()), Some("no_result")); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/plugins/agent/src/lib.rs b/plugins/agent/src/lib.rs deleted file mode 100755 index 9234f45..0000000 --- a/plugins/agent/src/lib.rs +++ /dev/null @@ -1,1113 +0,0 @@ -//! Agent plugin (C ABI v2): layout helpers + session bag + context via host_query + agent-kb + v2 memory + adaptive route. - -mod choice; -mod context_pack; -mod context_scope; -mod corpus; -mod effects; -mod eng; -mod error; -mod input; -mod kb; -mod mcp_client; -mod mcp_server; -mod memory; -mod output; -mod parallel; -mod resume; -mod route; -mod sandbox; -mod tools; -mod workflow; - -use std::collections::HashMap; -use std::ffi::CString; -use std::os::raw::{c_char, c_int}; -use std::path::{Component, Path, PathBuf}; -use std::ptr; -use std::sync::{LazyLock, Mutex}; - -use marqdo_plugin_sdk::*; - -const DEFAULT_MARKERS: &str = "agents,runbooks,marqdo.agent.json"; -const LAYOUT_DIRS: &[&str] = &["agents", "runbooks", "templates", "reports"]; - - -static HISTORIES: LazyLock>>> = - LazyLock::new(|| Mutex::new(HashMap::new())); -static AGENT_SEQ: LazyLock> = LazyLock::new(|| Mutex::new(0)); - -unsafe fn arg_str<'a>(v: &'a serde_json::Value, key: &str) -> Result<&'a str, String> { - v.get(key) - .and_then(|x| x.as_str()) - .ok_or_else(|| format!("missing text `{key}`")) -} - -fn has_parent_escape(rel: &Path) -> bool { - rel.components().any(|c| matches!(c, Component::ParentDir)) -} - -fn find_root(start: &str, markers: &str) -> Result { - let markers: Vec<&str> = markers - .split(',') - .map(|s| s.trim()) - .filter(|s| !s.is_empty()) - .collect(); - if markers.is_empty() { - return Err("empty markers".into()); - } - let mut cur = PathBuf::from(start); - if cur.as_os_str().is_empty() { - cur = std::env::current_dir().map_err(|e| e.to_string())?; - } - if !cur.exists() { - return Err(format!("start path missing: {}", cur.display())); - } - let mut cur = std::fs::canonicalize(&cur).map_err(|e| e.to_string())?; - loop { - for m in &markers { - let p = cur.join(m); - let ok = if m.contains('.') { - p.is_file() - } else { - p.is_dir() - }; - if ok { - return Ok(cur); - } - } - if !cur.pop() { - break; - } - } - Err("agent project root not found".into()) -} - -fn ensure_layout(root: &Path) -> Result { - let root = std::fs::canonicalize(root).map_err(|e| e.to_string())?; - let mut created = 0i64; - for d in LAYOUT_DIRS { - let p = root.join(d); - if !p.exists() { - std::fs::create_dir_all(&p).map_err(|e| e.to_string())?; - created += 1; - } else if !p.is_dir() { - return Err(format!("{} exists and is not a directory", p.display())); - } - } - Ok(created) -} - -fn probe(root: &Path) -> Result { - let root = std::fs::canonicalize(root).map_err(|e| e.to_string())?; - let mut map = serde_json::Map::new(); - map.insert( - "root".into(), - serde_json::Value::String(root.to_string_lossy().into_owned()), - ); - for d in LAYOUT_DIRS { - let key = format!("has_{d}"); - map.insert(key, serde_json::Value::Bool(root.join(d).is_dir())); - } - Ok(serde_json::Value::Object(map)) -} - -fn scaffold(root: &Path, name: &str, template: &str, dest: &str) -> Result { - if name.is_empty() { - return Err("name is empty".into()); - } - let root = std::fs::canonicalize(root).map_err(|e| e.to_string())?; - let tmpl_rel = Path::new(template); - let dest_rel = Path::new(dest); - if has_parent_escape(tmpl_rel) { - return Err("template path escapes project root".into()); - } - if has_parent_escape(dest_rel) { - return Err("dest path escapes project root".into()); - } - let tmpl_path = root.join(tmpl_rel); - if !tmpl_path.is_file() { - return Err(format!("template not found: {}", tmpl_path.display())); - } - let tmpl_can = std::fs::canonicalize(&tmpl_path).map_err(|e| e.to_string())?; - if !tmpl_can.starts_with(&root) { - return Err("template path escapes project root".into()); - } - let dest_path = root.join(dest_rel); - if let Some(parent) = dest_path.parent() { - std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; - let parent_can = std::fs::canonicalize(parent).map_err(|e| e.to_string())?; - if !parent_can.starts_with(&root) { - return Err("dest path escapes project root".into()); - } - } - let body = std::fs::read_to_string(&tmpl_can).map_err(|e| e.to_string())?; - let body = body.replace("{{name}}", name); - std::fs::write(&dest_path, body).map_err(|e| e.to_string())?; - Ok(dest_path.to_string_lossy().into_owned()) -} - -fn map_get_str<'a>(m: &'a serde_json::Value, keys: &[&str]) -> Option<&'a str> { - let obj = m.as_object()?; - for k in keys { - if let Some(v) = obj.get(*k) { - if let Some(s) = v.as_str() { - return Some(s); - } - if let Some(n) = v.as_i64() { - // allow numeric fields to be read as display later - let _ = n; - } - } - } - None -} - -fn map_get_i64(m: &serde_json::Value, keys: &[&str]) -> i64 { - let Some(obj) = m.as_object() else { - return i64::MAX; - }; - for k in keys { - if let Some(v) = obj.get(*k) { - if let Some(n) = v.as_i64() { - return n; - } - if let Some(s) = v.as_str() { - if let Ok(n) = s.parse::() { - return n; - } - } - } - } - i64::MAX -} - -fn skills_text(m: &serde_json::Value) -> String { - map_get_str(m, &["技能", "skills", "skill"]) - .unwrap_or("") - .to_string() -} - -fn match_skill(skill: &str, members: &serde_json::Value) -> Result { - let arr = members - .as_array() - .ok_or_else(|| "members must be a JSON array".to_string())?; - let skill = skill.trim(); - if skill.is_empty() { - return Err("skill is empty".into()); - } - let mut best: Option<&serde_json::Value> = None; - let mut best_load = i64::MAX; - for m in arr { - let sk = skills_text(m); - if sk.split(',').any(|p| p.trim() == skill) || sk.contains(skill) { - let load = map_get_i64(m, &["负载", "load"]); - if load < best_load { - best_load = load; - best = Some(m); - } - } - } - Ok(best.cloned().unwrap_or(serde_json::Value::Null)) -} - -fn bump_load(member: &serde_json::Value, delta: i64) -> Result { - let mut obj = member - .as_object() - .cloned() - .ok_or_else(|| "member must be a JSON object".to_string())?; - let key = if obj.contains_key("负载") { - "负载" - } else if obj.contains_key("load") { - "load" - } else { - obj.insert("负载".into(), serde_json::Value::Number(0.into())); - "负载" - }; - let cur = match obj.get(key) { - Some(serde_json::Value::Number(n)) => n.as_i64().unwrap_or(0), - Some(serde_json::Value::String(s)) => s.parse().unwrap_or(0), - _ => 0, - }; - obj.insert( - key.into(), - serde_json::Value::Number((cur + delta).into()), - ); - Ok(serde_json::Value::Object(obj)) -} - -unsafe extern "C" fn agent_find_root( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_find_root: {e}")); - return 1; - } - }; - let start = match arg_str(&v, "start") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_find_root: {e}")); - return 1; - } - }; - let markers = v - .get("markers") - .and_then(|x| x.as_str()) - .filter(|s| !s.is_empty()) - .unwrap_or(DEFAULT_MARKERS); - match find_root(start, markers) { - Ok(p) => { - let out = serde_json::Value::String(p.to_string_lossy().into_owned()).to_string(); - set_out(out_json, &out); - 0 - } - Err(e) => { - set_err(err_msg, &format!("agent_find_root: {e}")); - 1 - } - } -} - -unsafe extern "C" fn agent_ensure_layout( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_ensure_layout: {e}")); - return 1; - } - }; - let root = match arg_str(&v, "root") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_ensure_layout: {e}")); - return 1; - } - }; - match ensure_layout(Path::new(root)) { - Ok(n) => { - set_out(out_json, &n.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &format!("agent_ensure_layout: {e}")); - 1 - } - } -} - -unsafe extern "C" fn agent_probe( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_probe: {e}")); - return 1; - } - }; - let root = match arg_str(&v, "root") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_probe: {e}")); - return 1; - } - }; - match probe(Path::new(root)) { - Ok(j) => { - set_out(out_json, &j.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &format!("agent_probe: {e}")); - 1 - } - } -} - -unsafe extern "C" fn agent_scaffold( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_scaffold: {e}")); - return 1; - } - }; - let root = match arg_str(&v, "root") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_scaffold: {e}")); - return 1; - } - }; - let name = match arg_str(&v, "name") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_scaffold: {e}")); - return 1; - } - }; - let template = match arg_str(&v, "template") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_scaffold: {e}")); - return 1; - } - }; - let dest = match arg_str(&v, "dest") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_scaffold: {e}")); - return 1; - } - }; - match scaffold(Path::new(root), name, template, dest) { - Ok(p) => { - let out = serde_json::Value::String(p).to_string(); - set_out(out_json, &out); - 0 - } - Err(e) => { - set_err(err_msg, &format!("agent_scaffold: {e}")); - 1 - } - } -} - -unsafe extern "C" fn agent_match_skill( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_match_skill: {e}")); - return 1; - } - }; - let skill = match arg_str(&v, "skill") { - Ok(s) => s, - Err(e) => { - set_err(err_msg, &format!("agent_match_skill: {e}")); - return 1; - } - }; - let members = match v.get("members") { - Some(m) => m.clone(), - None => { - set_err(err_msg, "agent_match_skill: missing members"); - return 1; - } - }; - // members may be a JSON string (from Marqdo stringify) or already an array - let members = if let Some(s) = members.as_str() { - match serde_json::from_str::(s) { - Ok(j) => j, - Err(e) => { - set_err(err_msg, &format!("agent_match_skill: members JSON: {e}")); - return 1; - } - } - } else { - members - }; - match match_skill(skill, &members) { - Ok(j) => { - set_out(out_json, &j.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &format!("agent_match_skill: {e}")); - 1 - } - } -} - -unsafe extern "C" fn agent_bump_load( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_bump_load: {e}")); - return 1; - } - }; - let member = match v.get("member") { - Some(m) => m.clone(), - None => { - set_err(err_msg, "agent_bump_load: missing member"); - return 1; - } - }; - let member = if let Some(s) = member.as_str() { - match serde_json::from_str::(s) { - Ok(j) => j, - Err(e) => { - set_err(err_msg, &format!("agent_bump_load: member JSON: {e}")); - return 1; - } - } - } else { - member - }; - let delta = v.get("delta").and_then(|x| x.as_i64()).unwrap_or(1); - match bump_load(&member, delta) { - Ok(j) => { - set_out(out_json, &j.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &format!("agent_bump_load: {e}")); - 1 - } - } -} -pub(crate) fn host_query_json_args( - name: &str, - args: &serde_json::Value, -) -> Result { - let query = unsafe { HOST_QUERY }.ok_or_else(|| "host_query not available".to_string())?; - let userdata = unsafe { HOST_USERDATA }; - let c_name = CString::new(name).map_err(|e| e.to_string())?; - let args_s = serde_json::to_string(args).map_err(|e| e.to_string())?; - let c_args = CString::new(args_s).map_err(|e| e.to_string())?; - let mut out_ptr: *mut c_char = ptr::null_mut(); - let mut err_ptr: *mut c_char = ptr::null_mut(); - let rc = unsafe { - query( - userdata, - c_name.as_ptr(), - c_args.as_ptr(), - &mut out_ptr, - &mut err_ptr, - ) - }; - let err = take_host_string(err_ptr); - let out = take_host_string(out_ptr); - if rc != 0 { - return Err(err.unwrap_or_else(|| format!("host_query `{name}` failed"))); - } - let out = out.unwrap_or_else(|| "null".into()); - serde_json::from_str(&out).map_err(|e| format!("host_query `{name}` bad JSON: {e}")) -} - -unsafe extern "C" fn agent_alloc( - _args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let mut seq = match AGENT_SEQ.lock() { - Ok(g) => g, - Err(_) => { - set_err(err_msg, "agent_alloc: lock poisoned"); - return 1; - } - }; - *seq = seq.wrapping_add(1); - let id = format!("agent-{seq}"); - drop(seq); - if let Ok(mut map) = HISTORIES.lock() { - map.insert(id.clone(), Vec::new()); - } - let out = serde_json::Value::String(id).to_string(); - set_out(out_json, &out); - 0 -} - -unsafe extern "C" fn agent_history_get( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_history_get: {e}")); - return 1; - } - }; - let id = match arg_str(&v, "id") { - Ok(s) => s.to_string(), - Err(e) => { - set_err(err_msg, &format!("agent_history_get: {e}")); - return 1; - } - }; - let list = HISTORIES - .lock() - .map(|m| m.get(&id).cloned().unwrap_or_default()) - .unwrap_or_default(); - set_out(out_json, &serde_json::Value::Array(list).to_string()); - 0 -} - -unsafe extern "C" fn agent_history_clear( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_history_clear: {e}")); - return 1; - } - }; - let id = match arg_str(&v, "id") { - Ok(s) => s.to_string(), - Err(e) => { - set_err(err_msg, &format!("agent_history_clear: {e}")); - return 1; - } - }; - if let Ok(mut map) = HISTORIES.lock() { - map.insert(id, Vec::new()); - } - set_out(out_json, "null"); - 0 -} - -unsafe extern "C" fn agent_history_append( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_history_append: {e}")); - return 1; - } - }; - let id = match arg_str(&v, "id") { - Ok(s) => s.to_string(), - Err(e) => { - set_err(err_msg, &format!("agent_history_append: {e}")); - return 1; - } - }; - let item = match v.get("item") { - Some(i) => i.clone(), - None => { - set_err(err_msg, "agent_history_append: missing item"); - return 1; - } - }; - let list = match HISTORIES.lock() { - Ok(mut map) => { - let list = map.entry(id).or_default(); - list.push(item); - list.clone() - } - Err(_) => { - set_err(err_msg, "agent_history_append: lock poisoned"); - return 1; - } - }; - set_out(out_json, &serde_json::Value::Array(list).to_string()); - 0 -} - -unsafe extern "C" fn agent_module_source( - _args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - match host_query_json("module_source") { - Ok(j) => { - set_out(out_json, &j.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &e); - 1 - } - } -} - -unsafe extern "C" fn agent_call_site( - _args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - match host_query_json("call_site") { - Ok(j) => { - set_out(out_json, &j.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &e); - 1 - } - } -} - -unsafe extern "C" fn agent_marqdo_skill( - _args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - match host_query_json("marqdo_skill") { - Ok(j) => { - set_out(out_json, &j.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &e); - 1 - } - } -} - -pub(crate) fn tool_names(tools: &serde_json::Value) -> Vec { - let mut out = Vec::new(); - let rows = match tools { - serde_json::Value::Array(a) => a.as_slice(), - serde_json::Value::String(s) => { - if let Ok(serde_json::Value::Array(a)) = serde_json::from_str(s) { - return tool_names(&serde_json::Value::Array(a)); - } - return out; - } - _ => return out, - }; - for row in rows { - match row { - serde_json::Value::String(s) if !s.is_empty() => out.push(s.clone()), - serde_json::Value::Object(m) => { - for key in ["工具", "tools", "name"] { - if let Some(serde_json::Value::String(s)) = m.get(key) { - if !s.is_empty() { - out.push(s.clone()); - break; - } - } - } - } - _ => {} - } - } - out -} - -unsafe extern "C" fn agent_format_tools( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_format_tools: {e}")); - return 1; - } - }; - let tools = match v.get("tools") { - Some(t) => t, - None => { - set_err(err_msg, "agent_format_tools: missing tools"); - return 1; - } - }; - let mut text = - String::from("Available tools (invoke via CALL: or 调用:; runs as subtask):\n"); - for name in tool_names(tools) { - text.push_str("- "); - text.push_str(&name); - text.push('\n'); - } - set_out(out_json, &serde_json::Value::String(text).to_string()); - 0 -} - -unsafe extern "C" fn agent_tool_allowed( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("agent_tool_allowed: {e}")); - return 1; - } - }; - let tools = match v.get("tools") { - Some(t) => t, - None => { - set_err(err_msg, "agent_tool_allowed: missing tools"); - return 1; - } - }; - let name = match arg_str(&v, "name") { - Ok(s) => s, - Err(_) => { - set_out(out_json, "false"); - return 0; - } - }; - let ok = tool_names(tools).iter().any(|n| n == name); - set_out(out_json, if ok { "true" } else { "false" }); - 0 -} - -macro_rules! kb_ffi { - ($fn_name:ident, $call:expr, $label:expr) => { - unsafe extern "C" fn $fn_name( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, - ) -> c_int { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("{}: {e}", $label)); - return 1; - } - }; - match $call(&v) { - Ok(out) => { - set_out(out_json, &out.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &format!("{}: {e}", $label)); - 1 - } - } - } - }; -} - -kb_ffi!(agent_goal_sig, kb::goal_sig, "agent_goal_sig"); -kb_ffi!(agent_goal_slug, kb::goal_slug, "agent_goal_slug"); -kb_ffi!(agent_kb_canonicalize, kb::kb_canonicalize, "agent_kb_canonicalize"); -kb_ffi!(agent_kb_lookup, kb::kb_lookup, "agent_kb_lookup"); -kb_ffi!(agent_kb_near_match, kb::kb_near_match, "agent_kb_near_match"); -kb_ffi!(agent_kb_list_tasks, kb::kb_list_tasks, "agent_kb_list_tasks"); -kb_ffi!(agent_corpus_search, corpus::corpus_search, "agent_corpus_search"); -kb_ffi!(agent_mcp_fixture, corpus::mcp_fixture, "agent_mcp_fixture"); -kb_ffi!(agent_kb_add_alias, kb::kb_add_alias, "agent_kb_add_alias"); -kb_ffi!(agent_kb_promote, kb::kb_promote, "agent_kb_promote"); -kb_ffi!(agent_kb_quarantine, kb::kb_quarantine, "agent_kb_quarantine"); -kb_ffi!(agent_kb_record_hit, kb::kb_record_hit, "agent_kb_record_hit"); -kb_ffi!( - agent_workbook_solidify, - kb::workbook_solidify, - "agent_workbook_solidify" -); -kb_ffi!(agent_kb_task_files, kb::kb_task_files, "agent_kb_task_files"); -kb_ffi!(agent_memory_ensure, memory::memory_ensure, "agent_memory_ensure"); -kb_ffi!(agent_record_episode, memory::record_episode, "agent_record_episode"); -kb_ffi!(agent_list_episodes, memory::list_episodes, "agent_list_episodes"); -kb_ffi!(agent_get_episode, memory::get_episode, "agent_get_episode"); -kb_ffi!(agent_cluster_episodes, memory::cluster_episodes, "agent_cluster_episodes"); -kb_ffi!(agent_extract_pattern, memory::extract_pattern, "agent_extract_pattern"); -kb_ffi!(agent_generalize, memory::generalize, "agent_generalize"); -kb_ffi!(agent_synthesize_skill, memory::synthesize_skill, "agent_synthesize_skill"); -kb_ffi!(agent_compile_skill, memory::compile_skill, "agent_compile_skill"); -kb_ffi!(agent_maybe_learn, memory::maybe_learn, "agent_maybe_learn"); -kb_ffi!(agent_metrics, memory::metrics, "agent_metrics"); -kb_ffi!(agent_resolve, memory::resolve_task, "agent_resolve"); -kb_ffi!(agent_route, route::route, "agent_route"); -kb_ffi!(agent_route_apply, route::route_apply, "agent_route_apply"); -kb_ffi!(agent_compile_policy, route::compile_policy, "agent_compile_policy"); -kb_ffi!( - agent_maybe_compile_policy, - route::maybe_compile_policy, - "agent_maybe_compile_policy" -); -kb_ffi!(agent_resume_save, resume::resume_save, "agent_resume_save"); -kb_ffi!(agent_resume_load, resume::resume_load, "agent_resume_load"); -kb_ffi!(agent_resume_clear, resume::resume_clear, "agent_resume_clear"); -kb_ffi!(agent_resume_list, resume::resume_list, "agent_resume_list"); -kb_ffi!(agent_choice_parse, choice::parse_choice, "agent_choice_parse"); -kb_ffi!(agent_context_scope, context_scope::project, "agent_context_scope"); -kb_ffi!(agent_input_open, input::input_open, "agent_input_open"); -kb_ffi!(agent_input_resume, input::input_resume, "agent_input_resume"); -kb_ffi!(agent_parallel_report, parallel::report, "agent_parallel_report"); -kb_ffi!(agent_workflow_open, workflow::open, "agent_workflow_open"); -kb_ffi!(agent_workflow_next, workflow::next, "agent_workflow_next"); -kb_ffi!(agent_workflow_inspect, workflow::inspect, "agent_workflow_inspect"); -kb_ffi!(agent_workflow_list, workflow::list, "agent_workflow_list"); -kb_ffi!(agent_workflow_commit, workflow::commit, "agent_workflow_commit"); -kb_ffi!(agent_workflow_cancel, workflow::cancel, "agent_workflow_cancel"); -kb_ffi!(agent_workflow_retry_plan, workflow::retry_plan, "agent_workflow_retry_plan"); -kb_ffi!(agent_workflow_retry_commit, workflow::retry_commit, "agent_workflow_retry_commit"); -kb_ffi!(agent_error_make, error::make_error, "agent_error_make"); -kb_ffi!(agent_error_decide_retry, error::decide_retry, "agent_error_decide_retry"); -kb_ffi!(agent_tools_register, tools::tools_register, "agent_tools_register"); -kb_ffi!(agent_tools_clear, tools::tools_clear, "agent_tools_clear"); -kb_ffi!(agent_tools_search, tools::tools_search, "agent_tools_search"); -kb_ffi!(agent_tools_describe, tools::tools_describe, "agent_tools_describe"); -kb_ffi!(agent_tools_prepare_call, tools::tools_prepare_call, "agent_tools_prepare_call"); -kb_ffi!(agent_tools_wrap_result, tools::tools_wrap_result, "agent_tools_wrap_result"); -kb_ffi!( - agent_tools_args_digest, - tools::tools_args_digest, - "agent_tools_args_digest" -); -kb_ffi!( - agent_tools_needs_ledger, - tools::tools_needs_ledger, - "agent_tools_needs_ledger" -); -kb_ffi!( - agent_tools_register_eng_defaults, - tools::tools_register_eng_defaults, - "agent_tools_register_eng_defaults" -); -kb_ffi!( - agent_tools_seed_allowlist, - tools::seed_from_allowlist_args, - "agent_tools_seed_allowlist" -); -kb_ffi!(agent_output_build, output::output_build, "agent_output_build"); -kb_ffi!( - agent_output_apply_policy, - output::output_apply_policy, - "agent_output_apply_policy" -); -kb_ffi!( - agent_output_channel_event, - output::output_channel_event, - "agent_output_channel_event" -); -kb_ffi!( - agent_output_project_conclusion, - output::output_project_conclusion, - "agent_output_project_conclusion" -); -kb_ffi!( - agent_context_pack_build, - context_pack::context_pack_build, - "agent_context_pack_build" -); -kb_ffi!( - agent_context_pack_compact, - context_pack::context_pack_compact, - "agent_context_pack_compact" -); -kb_ffi!( - agent_effects_prepare, - effects::effects_prepare, - "agent_effects_prepare" -); -kb_ffi!( - agent_effects_transition, - effects::effects_transition, - "agent_effects_transition" -); -kb_ffi!(agent_effects_get, effects::effects_get, "agent_effects_get"); -kb_ffi!( - agent_effects_list, - effects::effects_list, - "agent_effects_list" -); -kb_ffi!( - agent_effects_watermark, - effects::effects_watermark, - "agent_effects_watermark" -); -kb_ffi!( - agent_effects_reconcile, - effects::effects_reconcile, - "agent_effects_reconcile" -); -kb_ffi!(agent_eng_preflight, eng::eng_preflight, "agent_eng_preflight"); -kb_ffi!(agent_eng_reuse, eng::eng_reuse, "agent_eng_reuse"); -kb_ffi!(agent_eng_bind_execute, eng::eng_bind_execute, "agent_eng_bind_execute"); -kb_ffi!(agent_eng_publish_gate, eng::eng_publish_gate, "agent_eng_publish_gate"); -kb_ffi!(agent_eng_record, eng::eng_record, "agent_eng_record"); - -#[no_mangle] -pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 { - ABI_VERSION -} - -#[no_mangle] -pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int { - if host.is_null() { - return 1; - } - if (*host).host_query.is_none() { - return 1; - } - let regs: &[(&str, &str, PluginFn)] = &[ - ("agent_find_root", "start,markers", agent_find_root), - ("agent_ensure_layout", "root", agent_ensure_layout), - ("agent_probe", "root", agent_probe), - ("agent_scaffold", "root,name,template,dest", agent_scaffold), - ("agent_match_skill", "skill,members", agent_match_skill), - ("agent_bump_load", "member,delta", agent_bump_load), - ("agent_alloc", "", agent_alloc), - ("agent_history_get", "id", agent_history_get), - ("agent_history_clear", "id", agent_history_clear), - ("agent_history_append", "id,item", agent_history_append), - ("agent_module_source", "", agent_module_source), - ("agent_call_site", "", agent_call_site), - ("agent_marqdo_skill", "", agent_marqdo_skill), - ("agent_format_tools", "tools", agent_format_tools), - ("agent_tool_allowed", "tools,name", agent_tool_allowed), - ("agent_goal_sig", "goal", agent_goal_sig), - ("agent_goal_slug", "goal", agent_goal_slug), - ("agent_kb_canonicalize", "goal", agent_kb_canonicalize), - ("agent_kb_lookup", "kb_dir,goal", agent_kb_lookup), - ("agent_kb_near_match", "kb_dir,goal", agent_kb_near_match), - ("agent_kb_list_tasks", "kb_dir", agent_kb_list_tasks), - ("agent_corpus_search", "query", agent_corpus_search), - ("agent_mcp_fixture", "action,fixture", agent_mcp_fixture), - ("agent_mcp_serve", "name,tools,transport", mcp_server::agent_mcp_serve), - ("agent_mcp_client", "action,command", mcp_client::agent_mcp_client), - ("agent_resume_save", "id,goal,status,round", agent_resume_save), - ("agent_resume_load", "id,resume_dir", agent_resume_load), - ("agent_resume_clear", "id,resume_dir", agent_resume_clear), - ("agent_resume_list", "resume_dir", agent_resume_list), - ("agent_choice_parse", "reply,options", agent_choice_parse), - ("agent_context_scope", "source,scope,class,function", agent_context_scope), - ("agent_input_open", "id,question,options,source_revision", agent_input_open), - ("agent_input_resume", "id,reply,source_revision", agent_input_resume), - ("agent_parallel_report", "results", agent_parallel_report), - ("agent_workflow_open", "id,steps,source_revision,session_id,principal_ref,resume_dir", agent_workflow_open), - ("agent_workflow_next", "id,source_revision,session_id,principal_ref,resume_dir", agent_workflow_next), - ("agent_workflow_inspect", "id,source_revision,session_id,principal_ref,resume_dir", agent_workflow_inspect), - ("agent_workflow_list", "session_id,principal_ref,resume_dir", agent_workflow_list), - ("agent_workflow_commit", "id,step_id,response,source_revision,session_id,principal_ref,resume_dir", agent_workflow_commit), - ("agent_workflow_cancel", "id,source_revision,session_id,principal_ref,resume_dir", agent_workflow_cancel), - ("agent_workflow_retry_plan", "id,source_revision,session_id,principal_ref,resume_dir", agent_workflow_retry_plan), - ("agent_workflow_retry_commit", "id,results,source_revision,session_id,principal_ref,resume_dir", agent_workflow_retry_commit), - ("agent_error_make", "code,message,category", agent_error_make), - ("agent_error_decide_retry", "error,attempts,effect_class", agent_error_decide_retry), - ("agent_tools_register", "spec,specs", agent_tools_register), - ("agent_tools_clear", "", agent_tools_clear), - ("agent_tools_search", "query,tools", agent_tools_search), - ("agent_tools_describe", "id,tools", agent_tools_describe), - ("agent_tools_prepare_call", "tool_id,arguments,tools", agent_tools_prepare_call), - ("agent_tools_wrap_result", "ok,status,summary", agent_tools_wrap_result), - ("agent_tools_args_digest", "arguments", agent_tools_args_digest), - ("agent_tools_needs_ledger", "effect", agent_tools_needs_ledger), - ( - "agent_tools_register_eng_defaults", - "", - agent_tools_register_eng_defaults, - ), - ("agent_tools_seed_allowlist", "tools", agent_tools_seed_allowlist), - ("agent_output_build", "status,text,validation", agent_output_build), - ( - "agent_output_apply_policy", - "status,text,policy", - agent_output_apply_policy, - ), - ( - "agent_output_channel_event", - "channel,delta", - agent_output_channel_event, - ), - ( - "agent_output_project_conclusion", - "document", - agent_output_project_conclusion, - ), - ( - "agent_context_pack_build", - "items,budget_tokens", - agent_context_pack_build, - ), - ( - "agent_context_pack_compact", - "items,budget_tokens", - agent_context_pack_compact, - ), - ( - "agent_effects_prepare", - "operation_id,idempotency_key,args_digest", - agent_effects_prepare, - ), - ( - "agent_effects_transition", - "operation_id,state", - agent_effects_transition, - ), - ("agent_effects_get", "operation_id", agent_effects_get), - ("agent_effects_list", "ledger_dir", agent_effects_list), - ( - "agent_effects_watermark", - "ledger_dir", - agent_effects_watermark, - ), - ( - "agent_effects_reconcile", - "operation_id,outcome", - agent_effects_reconcile, - ), - ("agent_kb_add_alias", "kb_dir,slug,alias", agent_kb_add_alias), - ("agent_kb_promote", "kb_dir,goal,workbook", agent_kb_promote), - ("agent_kb_quarantine", "kb_dir,slug", agent_kb_quarantine), - ("agent_kb_record_hit", "kb_dir,goal", agent_kb_record_hit), - ("agent_workbook_solidify", "path", agent_workbook_solidify), - ("agent_kb_task_files", "kb_dir,goal", agent_kb_task_files), - ("agent_memory_ensure", "memory_dir", agent_memory_ensure), - ("agent_record_episode", "task,status,result,mode", agent_record_episode), - ("agent_list_episodes", "memory_dir,task", agent_list_episodes), - ("agent_get_episode", "id", agent_get_episode), - ("agent_cluster_episodes", "memory_dir,task,threshold", agent_cluster_episodes), - ("agent_extract_pattern", "task", agent_extract_pattern), - ("agent_generalize", "task", agent_generalize), - ("agent_synthesize_skill", "task", agent_synthesize_skill), - ("agent_compile_skill", "task,kb_dir,min_evidence", agent_compile_skill), - ("agent_maybe_learn", "task,kb_dir,improve_every", agent_maybe_learn), - ("agent_metrics", "memory_dir", agent_metrics), - ("agent_resolve", "task,kb_dir", agent_resolve), - ("agent_route", "task,backend,kb_dir,memory_dir", agent_route), - ("agent_route_apply", "task,reply,kb_dir", agent_route_apply), - ("agent_compile_policy", "memory_dir,min_evidence", agent_compile_policy), - ("agent_maybe_compile_policy", "memory_dir,min_evidence", agent_maybe_compile_policy), - ("agent_eng_preflight", "task", agent_eng_preflight), - ("agent_eng_reuse", "task", agent_eng_reuse), - ("agent_eng_bind_execute", "project,query,policy", agent_eng_bind_execute), - ("agent_eng_publish_gate", "project,artifact_id,candidate_only", agent_eng_publish_gate), - ("agent_eng_record", "decision", agent_eng_record), - ("sandbox_open", "", sandbox::sandbox_open), - ("sandbox_write", "", sandbox::sandbox_write), - ("sandbox_read", "", sandbox::sandbox_read), - ("sandbox_remove", "", sandbox::sandbox_remove), - ("sandbox_diff", "", sandbox::sandbox_diff), - ("sandbox_commit", "", sandbox::sandbox_commit), - ("sandbox_discard", "", sandbox::sandbox_discard), - ("sandbox_inspect", "", sandbox::sandbox_inspect), - ("sandbox_run", "", sandbox::sandbox_run), - ]; - init_plugin(host, regs) -} - -#[no_mangle] -pub unsafe extern "C" fn marqdo_plugin_shutdown() { - HOST_ALLOC = None; - HOST_FREE = None; - HOST_QUERY = None; - HOST_USERDATA = ptr::null_mut(); - if let Ok(mut map) = HISTORIES.lock() { - map.clear(); - } - if let Ok(mut seq) = AGENT_SEQ.lock() { - *seq = 0; - } -} diff --git a/plugins/agent/src/mcp_client.rs b/plugins/agent/src/mcp_client.rs deleted file mode 100755 index 3905207..0000000 --- a/plugins/agent/src/mcp_client.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! MCP Client (stdio JSON-RPC) — spawn a server process, initialize, list/call tools. - -use serde_json::{json, Value}; -use std::ffi::CStr; -use std::io::{BufRead, BufReader, Write}; -use std::os::raw::{c_char, c_int}; -use std::process::{Child, Command, Stdio}; -use std::sync::Mutex; -use std::time::Duration; - -use crate::{parse_args, set_err, set_out}; - -struct Session { - child: Child, - stdin: std::process::ChildStdin, - reader: BufReader, - next_id: i64, - server_name: String, -} - -static SESSIONS: Mutex> = Mutex::new(Vec::new()); - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty()) -} - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - opt_text(args, key).ok_or_else(|| format!("missing text `{key}`")) -} - -fn write_rpc(stdin: &mut impl Write, msg: &Value) -> Result<(), String> { - let s = serde_json::to_string(msg).map_err(|e| e.to_string())?; - writeln!(stdin, "{s}").map_err(|e| format!("mcp client write: {e}"))?; - stdin.flush().map_err(|e| format!("mcp client flush: {e}"))?; - Ok(()) -} - -fn read_rpc(reader: &mut impl BufRead) -> Result { - let mut line = String::new(); - loop { - line.clear(); - let n = reader - .read_line(&mut line) - .map_err(|e| format!("mcp client read: {e}"))?; - if n == 0 { - return Err("mcp client: server closed stdout".into()); - } - let t = line.trim(); - if t.is_empty() { - continue; - } - return serde_json::from_str(t).map_err(|e| format!("mcp client json: {e}")); - } -} - -fn rpc_call(session: &mut Session, method: &str, params: Value) -> Result { - let id = session.next_id; - session.next_id += 1; - let req = json!({ - "jsonrpc": "2.0", - "id": id, - "method": method, - "params": params, - }); - write_rpc(&mut session.stdin, &req)?; - // Read until matching id (skip notifications). - for _ in 0..64 { - let resp = read_rpc(&mut session.reader)?; - if resp.get("id") == Some(&json!(id)) { - if let Some(err) = resp.get("error") { - let msg = err - .get("message") - .and_then(|v| v.as_str()) - .unwrap_or("rpc error"); - return Err(msg.to_string()); - } - return Ok(resp.get("result").cloned().unwrap_or(Value::Null)); - } - } - Err("mcp client: no matching response".into()) -} - -fn spawn_session(command: &str, args: &[String], name: &str) -> Result { - let mut cmd = Command::new(command); - for a in args { - cmd.arg(a); - } - cmd.stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()); - let mut child = cmd - .spawn() - .map_err(|e| format!("mcp client spawn `{command}`: {e}"))?; - let stdin = child - .stdin - .take() - .ok_or_else(|| "mcp client: no stdin".to_string())?; - let stdout = child - .stdout - .take() - .ok_or_else(|| "mcp client: no stdout".to_string())?; - let mut session = Session { - child, - stdin, - reader: BufReader::new(stdout), - next_id: 1, - server_name: name.to_string(), - }; - // initialize - let _ = rpc_call( - &mut session, - "initialize", - json!({ - "protocolVersion": "2024-11-05", - "capabilities": {}, - "clientInfo": { "name": "marqdo-agent", "version": "0.1.0" } - }), - )?; - // optional initialized notification - let _ = write_rpc( - &mut session.stdin, - &json!({ - "jsonrpc": "2.0", - "method": "notifications/initialized", - "params": {} - }), - ); - let _ = session.server_name; - // Give slow servers a beat (ignore). - let _ = Duration::from_millis(1); - Ok(session) -} - -fn command_args(args: &Value) -> Result<(String, Vec), String> { - let command = arg_text(args, "command")?; - let mut argv = Vec::new(); - if let Some(arr) = args.get("args").and_then(|v| v.as_array()) { - for a in arr { - if let Some(s) = a.as_str() { - argv.push(s.to_string()); - } else { - argv.push(a.to_string()); - } - } - } else if let Some(s) = opt_text(args, "args") { - // space-split simple args - for part in s.split_whitespace() { - argv.push(part.to_string()); - } - } - Ok((command.to_string(), argv)) -} - -fn session_id_of(args: &Value) -> String { - opt_text(args, "session") - .or_else(|| opt_text(args, "id")) - .unwrap_or("default") - .to_string() -} - -fn with_session(args: &Value, f: F) -> Result -where - F: FnOnce(&mut Session) -> Result, -{ - let sid = session_id_of(args); - let mut guard = SESSIONS - .lock() - .map_err(|_| "mcp client: session lock poisoned".to_string())?; - let idx = guard - .iter() - .position(|(id, _)| id == &sid) - .ok_or_else(|| format!("mcp client: no session `{sid}` (call connect first)"))?; - f(&mut guard[idx].1) -} - -fn action_connect(args: &Value) -> Result { - let (command, argv) = command_args(args)?; - let name = opt_text(args, "name").unwrap_or("mcp"); - let sid = session_id_of(args); - let session = spawn_session(&command, &argv, name)?; - let mut guard = SESSIONS - .lock() - .map_err(|_| "mcp client: session lock poisoned".to_string())?; - // Replace existing - guard.retain(|(id, _)| id != &sid); - guard.push((sid.clone(), session)); - Ok(json!({ - "ok": true, - "session": sid, - "transport": "stdio", - "command": command, - })) -} - -fn action_list(args: &Value) -> Result { - with_session(args, |s| { - let result = rpc_call(s, "tools/list", json!({}))?; - let mut out = result; - if let Some(obj) = out.as_object_mut() { - obj.insert("authority".into(), json!("workbook")); - obj.insert("session".into(), json!(session_id_of(args))); - } - Ok(out) - }) -} - -fn action_call(args: &Value) -> Result { - let name = arg_text(args, "name")?; - let arguments = args.get("arguments").cloned().unwrap_or(json!({})); - with_session(args, |s| { - let result = rpc_call( - s, - "tools/call", - json!({ "name": name, "arguments": arguments }), - )?; - let mut out = if result.is_object() { - result - } else { - json!({ "result": result }) - }; - if let Some(obj) = out.as_object_mut() { - obj.insert("authority".into(), json!("workbook")); - obj.insert("session".into(), json!(session_id_of(args))); - } - Ok(out) - }) -} - -fn action_close(args: &Value) -> Result { - let sid = session_id_of(args); - let mut guard = SESSIONS - .lock() - .map_err(|_| "mcp client: session lock poisoned".to_string())?; - if let Some(idx) = guard.iter().position(|(id, _)| id == &sid) { - let (_, mut session) = guard.remove(idx); - let _ = session.child.kill(); - let _ = session.child.wait(); - Ok(json!({ "ok": true, "session": sid, "closed": true })) - } else { - Ok(json!({ "ok": true, "session": sid, "closed": false })) - } -} - -/// One-shot: connect → list or call → close (no persistent session). -fn action_oneshot(args: &Value, kind: &str) -> Result { - let (command, argv) = command_args(args)?; - let name = opt_text(args, "name").unwrap_or("mcp"); - let mut session = spawn_session(&command, &argv, name)?; - let result = match kind { - "list" => { - let r = rpc_call(&mut session, "tools/list", json!({}))?; - Ok(r) - } - "call" => { - let tname = arg_text(args, "tool").or_else(|_| arg_text(args, "name"))?; - // When oneshot call, `name` may be server name — prefer `tool=`. - let tname = opt_text(args, "tool").unwrap_or(tname); - let arguments = args.get("arguments").cloned().unwrap_or(json!({})); - rpc_call( - &mut session, - "tools/call", - json!({ "name": tname, "arguments": arguments }), - ) - } - _ => Err(format!("unknown oneshot kind `{kind}`")), - }; - let _ = session.child.kill(); - let _ = session.child.wait(); - let mut out = result?; - if let Some(obj) = out.as_object_mut() { - obj.insert("authority".into(), json!("workbook")); - obj.insert("transport".into(), json!("stdio")); - } - Ok(out) -} - -pub fn mcp_client(args: &Value) -> Result { - let action = opt_text(args, "action").unwrap_or("list"); - match action { - "connect" => action_connect(args), - "list" => { - if opt_text(args, "command").is_some() && opt_text(args, "session").is_none() { - action_oneshot(args, "list") - } else { - action_list(args) - } - } - "call" => { - if opt_text(args, "command").is_some() && opt_text(args, "session").is_none() { - action_oneshot(args, "call") - } else { - action_call(args) - } - } - "close" | "disconnect" => action_close(args), - other => Err(format!( - "mcp client: unknown action `{other}` (connect|list|call|close)" - )), - } -} - -pub unsafe extern "C" fn agent_mcp_client( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let args = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &e); - return 1; - } - }; - match mcp_client(&args) { - Ok(v) => { - set_out(out_json, &v.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &e); - 1 - } - } -} - -#[allow(dead_code)] -fn _unused(_: &CStr) {} diff --git a/plugins/agent/src/mcp_server.rs b/plugins/agent/src/mcp_server.rs deleted file mode 100755 index 679a33d..0000000 --- a/plugins/agent/src/mcp_server.rs +++ /dev/null @@ -1,507 +0,0 @@ -//! Minimal MCP Server — stdio JSON-RPC + Streamable HTTP (spec 2025-03-26). - -use serde_json::{json, Map, Value}; -use std::ffi::CStr; -use std::io::{BufRead, BufReader, Read, Write}; -use std::net::{TcpListener, TcpStream}; -use std::os::raw::{c_char, c_int}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; -use std::thread; -use std::time::{SystemTime, UNIX_EPOCH}; - -use crate::{host_query_json_args, parse_args, set_err, set_out}; - -fn read_line_message(reader: &mut impl BufRead) -> Result, String> { - let mut line = String::new(); - let n = reader - .read_line(&mut line) - .map_err(|e| format!("stdin: {e}"))?; - if n == 0 { - return Ok(None); - } - let line = line.trim(); - if line.is_empty() { - return read_line_message(reader); - } - let v: Value = serde_json::from_str(line).map_err(|e| format!("json-rpc parse: {e}"))?; - Ok(Some(v)) -} - -fn write_message(msg: &Value) -> Result<(), String> { - let mut out = std::io::stdout().lock(); - let s = serde_json::to_string(msg).map_err(|e| e.to_string())?; - writeln!(out, "{s}").map_err(|e| format!("stdout: {e}"))?; - out.flush().map_err(|e| format!("flush: {e}"))?; - Ok(()) -} - -fn rpc_result(id: &Value, result: Value) -> Value { - json!({ - "jsonrpc": "2.0", - "id": id, - "result": result, - }) -} - -fn rpc_error(id: &Value, code: i64, message: &str) -> Value { - json!({ - "jsonrpc": "2.0", - "id": id, - "error": { "code": code, "message": message }, - }) -} - -fn tools_list(tools: &[Value]) -> Value { - let mut arr = Vec::new(); - for t in tools { - let name = t.get("name").and_then(|v| v.as_str()).unwrap_or(""); - let desc = t - .get("description") - .and_then(|v| v.as_str()) - .unwrap_or(""); - if name.is_empty() { - continue; - } - arr.push(json!({ - "name": name, - "description": desc, - "inputSchema": { - "type": "object", - "properties": {}, - "additionalProperties": true - } - })); - } - json!({ "tools": arr }) -} - -fn call_tool(tools: &[Value], name: &str, arguments: &Value) -> Result { - let tool = tools - .iter() - .find(|t| t.get("name").and_then(|v| v.as_str()) == Some(name)) - .ok_or_else(|| format!("unknown tool `{name}`"))?; - let fn_path = tool - .get("fn") - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("tool `{name}` missing fn"))? - .to_string(); - let result = host_query_json_args( - "call_lib_path", - &json!({ - "path": fn_path, - "args": arguments, - }), - )?; - Ok(json!({ - "content": [{ - "type": "text", - "text": serde_json::to_string(&result).unwrap_or_else(|_| "{}".into()) - }], - "isError": false, - "authority": "workbook" - })) -} - -/// Handle one JSON-RPC message. Returns `None` for notifications (no response body). -fn dispatch_rpc(name: &str, tools: &[Value], msg: &Value) -> Option { - let id = msg.get("id").cloned().unwrap_or(Value::Null); - let method = msg.get("method").and_then(|v| v.as_str()).unwrap_or(""); - let params = msg.get("params").cloned().unwrap_or(json!({})); - - if matches!(id, Value::Null) && method.starts_with("notifications/") { - return None; - } - - Some(match method { - "initialize" => rpc_result( - &id, - json!({ - "protocolVersion": "2025-03-26", - "capabilities": { "tools": {} }, - "serverInfo": { "name": name, "version": "0.1.0" } - }), - ), - "tools/list" | "list_tools" => rpc_result(&id, tools_list(tools)), - "tools/call" | "call_tool" => { - let tname = params.get("name").and_then(|v| v.as_str()).unwrap_or(""); - let args = params.get("arguments").cloned().unwrap_or(json!({})); - match call_tool(tools, tname, &args) { - Ok(r) => rpc_result(&id, r), - Err(e) => rpc_error(&id, -32000, &e), - } - } - "ping" => rpc_result(&id, json!({})), - "" => rpc_error(&id, -32600, "missing method"), - other => rpc_error(&id, -32601, &format!("method not found: {other}")), - }) -} - -/// Blocking stdio MCP loop. `tools` is a JSON array of `{name, fn, description}`. -pub fn serve_stdio(name: &str, tools: Vec) -> Result { - let stdin = std::io::stdin(); - let mut reader = BufReader::new(stdin.lock()); - loop { - let Some(msg) = read_line_message(&mut reader)? else { - break; - }; - if let Some(reply) = dispatch_rpc(name, &tools, &msg) { - write_message(&reply)?; - } - } - Ok(json!({ "ok": true, "transport": "stdio" })) -} - -fn new_session_id() -> String { - static SEQ: AtomicU64 = AtomicU64::new(1); - let n = SEQ.fetch_add(1, Ordering::Relaxed); - let ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_millis()) - .unwrap_or(0); - format!("mcp-{ms}-{n}") -} - -fn read_http_request( - reader: &mut BufReader, -) -> Result<(String, String, Vec<(String, String)>, Vec), String> { - let mut request_line = String::new(); - reader - .read_line(&mut request_line) - .map_err(|e| format!("read request: {e}"))?; - let parts: Vec<&str> = request_line.trim().split_whitespace().collect(); - if parts.len() < 2 { - return Err("bad request line".into()); - } - let method = parts[0].to_string(); - let path = parts[1].to_string(); - let mut headers = Vec::new(); - let mut content_length = 0usize; - loop { - let mut line = String::new(); - reader - .read_line(&mut line) - .map_err(|e| format!("read header: {e}"))?; - let line = line.trim_end_matches(['\r', '\n']); - if line.is_empty() { - break; - } - if let Some((k, v)) = line.split_once(':') { - let key = k.trim().to_string(); - let val = v.trim().to_string(); - if key.eq_ignore_ascii_case("content-length") { - content_length = val.parse().unwrap_or(0); - } - headers.push((key, val)); - } - } - let mut body = vec![0u8; content_length]; - if content_length > 0 { - reader - .read_exact(&mut body) - .map_err(|e| format!("read body: {e}"))?; - } - Ok((method, path, headers, body)) -} - -fn header_get<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> { - headers - .iter() - .find(|(k, _)| k.eq_ignore_ascii_case(name)) - .map(|(_, v)| v.as_str()) -} - -fn write_http( - stream: &mut TcpStream, - status: u16, - reason: &str, - content_type: &str, - body: &[u8], - extra: &[(&str, &str)], -) -> Result<(), String> { - let mut head = format!( - "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n", - body.len() - ); - for (k, v) in extra { - head.push_str(k); - head.push_str(": "); - head.push_str(v); - head.push_str("\r\n"); - } - head.push_str("\r\n"); - stream - .write_all(head.as_bytes()) - .map_err(|e| e.to_string())?; - stream.write_all(body).map_err(|e| e.to_string())?; - stream.flush().map_err(|e| e.to_string())?; - Ok(()) -} - -fn path_matches(req_path: &str, endpoint: &str) -> bool { - let base = req_path.split('?').next().unwrap_or(req_path); - base == endpoint || base.trim_end_matches('/') == endpoint.trim_end_matches('/') -} - -fn handle_http_conn( - stream: TcpStream, - name: &str, - tools: &[Value], - endpoint: &str, -) -> Result<(), String> { - let mut reader = BufReader::new(stream); - let (method, path, headers, body) = read_http_request(&mut reader)?; - let mut stream = reader.into_inner(); - if !path_matches(&path, endpoint) { - write_http( - &mut stream, - 404, - "Not Found", - "application/json", - br#"{"error":"not_found"}"#, - &[], - )?; - return Ok(()); - } - - if method.eq_ignore_ascii_case("GET") { - // Optional SSE stream — empty keepalive then close (clients may 405). - let accept = header_get(&headers, "Accept").unwrap_or(""); - if accept.contains("text/event-stream") { - let body = b": mcp streamable-http ready\n\n"; - write_http( - &mut stream, - 200, - "OK", - "text/event-stream", - body, - &[("Cache-Control", "no-cache")], - )?; - } else { - write_http( - &mut stream, - 405, - "Method Not Allowed", - "application/json", - br#"{"error":"use_post_for_jsonrpc"}"#, - &[("Allow", "POST, GET")], - )?; - } - return Ok(()); - } - - if method.eq_ignore_ascii_case("DELETE") { - write_http(&mut stream, 200, "OK", "application/json", b"{}", &[])?; - return Ok(()); - } - - if !method.eq_ignore_ascii_case("POST") { - write_http( - &mut stream, - 405, - "Method Not Allowed", - "application/json", - br#"{"error":"method_not_allowed"}"#, - &[("Allow", "POST, GET, DELETE")], - )?; - return Ok(()); - } - - let text = String::from_utf8_lossy(&body); - let msg: Value = serde_json::from_str(text.trim()).map_err(|e| format!("json-rpc: {e}"))?; - let is_init = msg.get("method").and_then(|v| v.as_str()) == Some("initialize"); - let existing_sid = header_get(&headers, "Mcp-Session-Id") - .or_else(|| header_get(&headers, "MCP-Session-Id")) - .map(|s| s.to_string()); - - // Notifications → 202 Accepted, empty body. - if msg.get("id").is_none() || msg.get("id") == Some(&Value::Null) { - if let Some(m) = msg.get("method").and_then(|v| v.as_str()) { - if m.starts_with("notifications/") { - write_http( - &mut stream, - 202, - "Accepted", - "application/json", - b"", - &[], - )?; - return Ok(()); - } - } - } - - let reply = match dispatch_rpc(name, tools, &msg) { - Some(r) => r, - None => { - write_http( - &mut stream, - 202, - "Accepted", - "application/json", - b"", - &[], - )?; - return Ok(()); - } - }; - - let body = serde_json::to_vec(&reply).map_err(|e| e.to_string())?; - let mut extras: Vec<(&str, String)> = Vec::new(); - if is_init { - let sid = existing_sid.unwrap_or_else(new_session_id); - extras.push(("Mcp-Session-Id", sid)); - } else if let Some(sid) = existing_sid { - extras.push(("Mcp-Session-Id", sid)); - } - let extra_refs: Vec<(&str, &str)> = extras.iter().map(|(k, v)| (*k, v.as_str())).collect(); - write_http( - &mut stream, - 200, - "OK", - "application/json", - &body, - &extra_refs, - )?; - Ok(()) -} - -/// Streamable HTTP MCP (POST JSON-RPC + optional GET SSE). Spec 2025-03-26. -pub fn serve_http( - name: &str, - tools: Vec, - host: &str, - port: u16, - path: &str, -) -> Result { - let addr = format!("{host}:{port}"); - let listener = TcpListener::bind(&addr).map_err(|e| format!("bind {addr}: {e}"))?; - let name = Arc::new(name.to_string()); - let tools = Arc::new(tools); - let endpoint = Arc::new(if path.is_empty() { - "/mcp".to_string() - } else if path.starts_with('/') { - path.to_string() - } else { - format!("/{path}") - }); - eprintln!( - "mcp streamable-http listening on http://{addr}{} (POST JSON-RPC)", - &*endpoint - ); - for conn in listener.incoming() { - match conn { - Ok(stream) => { - let name = Arc::clone(&name); - let tools = Arc::clone(&tools); - let endpoint = Arc::clone(&endpoint); - thread::spawn(move || { - if let Err(e) = handle_http_conn(stream, &name, &tools, &endpoint) { - eprintln!("mcp http conn: {e}"); - } - }); - } - Err(e) => eprintln!("mcp http accept: {e}"), - } - } - Ok(json!({ - "ok": true, - "transport": "http", - "host": host, - "port": port, - "path": *endpoint - })) -} - -pub fn tools_from_value(v: &Value) -> Vec { - if let Some(arr) = v.as_array() { - return arr.clone(); - } - if let Value::Object(map) = v { - let mut out = Vec::new(); - for (name, spec) in map { - let mut m = Map::new(); - m.insert("name".into(), json!(name)); - if let Some(obj) = spec.as_object() { - for (k, val) in obj { - m.insert(k.clone(), val.clone()); - } - } else if let Some(s) = spec.as_str() { - m.insert("fn".into(), json!(s)); - } - out.push(Value::Object(m)); - } - return out; - } - Vec::new() -} - -pub unsafe extern "C" fn agent_mcp_serve( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let args = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &e); - return 1; - } - }; - let transport = args - .get("transport") - .and_then(|v| v.as_str()) - .unwrap_or("stdio"); - let name = args - .get("name") - .and_then(|v| v.as_str()) - .unwrap_or("marqdo"); - let tools = args - .get("tools") - .map(tools_from_value) - .unwrap_or_default(); - - let result = match transport { - "stdio" => serve_stdio(name, tools), - "http" | "streamable-http" | "sse" => { - let host = args - .get("host") - .and_then(|v| v.as_str()) - .unwrap_or("127.0.0.1"); - let port = args - .get("port") - .and_then(|v| { - v.as_u64() - .or_else(|| v.as_i64().map(|n| n as u64)) - .or_else(|| v.as_str().and_then(|s| s.parse().ok())) - }) - .unwrap_or(7434) as u16; - let path = args - .get("path") - .and_then(|v| v.as_str()) - .unwrap_or("/mcp"); - serve_http(name, tools, host, port, path) - } - other => { - set_err( - err_msg, - &format!("mcp serve: transport `{other}` not supported (use stdio|http)"), - ); - return 1; - } - }; - - match result { - Ok(v) => { - set_out(out_json, &v.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &e); - 1 - } - } -} - -#[allow(dead_code)] -fn _unused(_: &CStr) {} diff --git a/plugins/agent/src/memory.rs b/plugins/agent/src/memory.rs deleted file mode 100755 index 9c86115..0000000 --- a/plugins/agent/src/memory.rs +++ /dev/null @@ -1,1161 +0,0 @@ -//! Agent Framework v2 memory: episodes → experience → compile (plugin-side). -//! Layout under `.marqdo/agent-memory/` (default). Does not touch `src/host`. - -use std::fs; -use std::path::{Path, PathBuf}; - -use chrono::Datelike; -use serde_json::{json, Value}; - -use crate::kb::{ - canonicalize_goal_str, char_bigram_tf, cosine_tf, goal_sig_hex, goal_slug_str, normalize_goal, -}; - -const DEFAULT_MEMORY_DIR: &str = ".marqdo/agent-memory"; -const DEFAULT_KB_DIR: &str = ".marqdo/agent-kb"; - -fn resolve_path(rel: &str) -> PathBuf { - let p = PathBuf::from(rel); - if p.is_absolute() { - return p; - } - // Already valid relative to process cwd (e.g. re-passed after prior join). - if p.exists() { - return p; - } - let base = (|| { - let q = crate::host_query_json("cwd")?; - q.as_str() - .map(PathBuf::from) - .ok_or_else(|| "cwd not text".to_string()) - })() - .or_else(|_| std::env::current_dir().map_err(|e| e.to_string())) - .unwrap_or_else(|_| PathBuf::from(".")); - let joined = base.join(&p); - if joined.exists() || !base.as_os_str().is_empty() { - return joined; - } - p -} - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - args.get(key) - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("missing text `{key}`")) -} - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty()) -} - -fn opt_i64(args: &Value, key: &str, default: i64) -> i64 { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Number(n)) => n.as_i64().unwrap_or(default), - Some(Value::String(s)) => s.parse().unwrap_or(default), - Some(Value::Bool(b)) => { - if *b { - 1 - } else { - 0 - } - } - _ => default, - } -} - -fn opt_bool(args: &Value, key: &str, default: bool) -> bool { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Bool(b)) => *b, - Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"), - Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0, - _ => default, - } -} - -fn memory_root(args: &Value) -> PathBuf { - let rel = opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR); - resolve_path(rel) -} - -fn now_rfc3339() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) -} - -fn yaml_escape(s: &str) -> String { - if s.is_empty() - || s.contains(':') - || s.contains('#') - || s.contains('"') - || s.contains('\'') - || s.contains('\n') - || s.starts_with(' ') - { - format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) - } else { - s.to_string() - } -} - -fn marqdo_quoted(s: &str) -> String { - let mut out = String::from("\""); - for c in s.chars() { - match c { - '\\' => out.push_str("\\\\"), - '"' => out.push_str("\\\""), - '\n' => out.push_str("\\n"), - '\t' => out.push_str("\\t"), - c => out.push(c), - } - } - out.push('"'); - out -} - -fn value_brief(v: &Value) -> String { - match v { - Value::Null => String::new(), - Value::String(s) => s.clone(), - Value::Number(n) => n.to_string(), - Value::Bool(b) => { - if *b { - "true".into() - } else { - "false".into() - } - } - other => other.to_string(), - } -} - -fn ensure_layout(root: &Path) -> Result<(), String> { - for sub in [ - "episodes", - "experiences", - "candidates", - "skills", - "policies", - "tests", - ] { - fs::create_dir_all(root.join(sub)).map_err(|e| format!("mkdir {sub}: {e}"))?; - } - let index = root.join("index.mq.md"); - if !index.is_file() { - let body = "---\ntype: agent-memory-index\ntitle: agent-memory\n---\n\n# Agent memory\n\nEpisodes, experiences, and compiled skills.\n"; - fs::write(&index, body).map_err(|e| format!("write index: {e}"))?; - } - Ok(()) -} - -/// Ensure `.marqdo/agent-memory/` layout exists. -pub fn memory_ensure(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - Ok(json!({ - "ok": true, - "memory_dir": root.to_string_lossy(), - })) -} - -fn episode_dir(root: &Path) -> PathBuf { - let now = chrono::Utc::now(); - root.join("episodes") - .join(format!("{:04}", now.year())) - .join(format!("{:02}", now.month())) -} - -fn next_episode_id(dir: &Path) -> Result<(String, PathBuf), String> { - fs::create_dir_all(dir).map_err(|e| format!("mkdir episodes: {e}"))?; - let mut max = 0u64; - if let Ok(rd) = fs::read_dir(dir) { - for ent in rd.flatten() { - let name = ent.file_name().to_string_lossy().into_owned(); - if let Some(rest) = name.strip_prefix("episode-") { - if let Some(num) = rest.strip_suffix(".mq.md") { - if let Ok(n) = num.parse::() { - max = max.max(n); - } - } - } - } - } - let id_n = max + 1; - let id = format!("episode-{id_n:04}"); - let path = dir.join(format!("{id}.mq.md")); - Ok((id, path)) -} - -fn section(title: &str, body: &str) -> String { - let b = body.trim(); - if b.is_empty() { - format!("# {title}\n\nnone\n") - } else { - format!("# {title}\n\n{b}\n") - } -} - -/// Record one execution as a readable `.mq.md` episode (v2 Phase 1). -pub fn record_episode(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?; - let task_n = normalize_goal(task); - let task_hash = goal_sig_hex(&task_n); - let slug = goal_slug_str(&task_n); - let status = opt_text(args, "status").unwrap_or("success"); - let mode = opt_text(args, "mode").unwrap_or("explore"); - let skill = opt_text(args, "skill") - .map(|s| s.to_string()) - .or_else(|| { - args.get("skill") - .filter(|v| !v.is_null()) - .map(value_brief) - .filter(|s| !s.is_empty() && s != "null") - }) - .unwrap_or_else(|| "none".into()); - let result = args - .get("result") - .map(value_brief) - .unwrap_or_default(); - let context = args - .get("context") - .map(value_brief) - .unwrap_or_default(); - let actions = args - .get("actions") - .map(value_brief) - .unwrap_or_default(); - let observations = args - .get("observations") - .or_else(|| args.get("observation")) - .map(value_brief) - .unwrap_or_default(); - let verification = args - .get("verification") - .map(value_brief) - .unwrap_or_else(|| { - if status == "ok" || status == "success" { - "status: passed".into() - } else { - "status: failed".into() - } - }); - let errors = args - .get("errors") - .or_else(|| args.get("error")) - .map(value_brief) - .unwrap_or_else(|| "none".into()); - let llm_calls = opt_i64(args, "llm_calls", 0); - let tool_calls = opt_i64(args, "tool_calls", 0); - let tokens = opt_i64(args, "tokens", 0); - let latency_ms = opt_i64(args, "latency_ms", 0); - let workbook = opt_text(args, "workbook").unwrap_or(""); - let cache = opt_text(args, "cache").unwrap_or(""); - let match_kind = opt_text(args, "match").unwrap_or(""); - - let ep_status = if status == "ok" || status == "success" { - "success" - } else { - "failure" - }; - - let dir = episode_dir(&root); - let (id, path) = next_episode_id(&dir)?; - let ts = now_rfc3339(); - - let mut fm = format!( - "---\ntype: episode\nid: {id}\ntask_hash: {task_hash}\nslug: {slug}\ntimestamp: {ts}\nstatus: {ep_status}\nskill: {}\nmode: {}\nllm_calls: {llm_calls}\ntool_calls: {tool_calls}\ntokens: {tokens}\nlatency_ms: {latency_ms}\n", - yaml_escape(&skill), - yaml_escape(mode), - ); - if !workbook.is_empty() { - fm.push_str(&format!("workbook: {}\n", yaml_escape(workbook))); - } - if !cache.is_empty() { - fm.push_str(&format!("cache: {}\n", yaml_escape(cache))); - } - if !match_kind.is_empty() { - fm.push_str(&format!("match: {}\n", yaml_escape(match_kind))); - } - fm.push_str("---\n\n"); - - let body = format!( - "{fm}{}\n{}\n{}\n{}\n{}\n{}\n{}\n", - section("Task", &task_n), - section("Context", &context), - section("Decisions", &actions), - section("Actions", &actions), - section("Observations", &observations), - section("Result", &result), - section("Verification", &verification), - ); - let body = if errors != "none" && !errors.is_empty() { - format!("{body}\n{}\n", section("Errors", &errors)) - } else { - format!("{body}\n{}\n", section("Errors", "none")) - }; - - fs::write(&path, body).map_err(|e| format!("write episode: {e}"))?; - let rel = path - .strip_prefix(resolve_path(".")) - .unwrap_or(&path) - .to_string_lossy() - .into_owned(); - - Ok(json!({ - "ok": true, - "id": id, - "path": path.to_string_lossy(), - "rel": rel, - "task_hash": task_hash, - "slug": slug, - "status": ep_status, - "mode": mode, - })) -} - -fn extract_fm_field(source: &str, key: &str) -> Option { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return None; - } - let prefix = format!("{key}:"); - for line in lines.iter().skip(1) { - let t = line.trim(); - if t == "---" { - break; - } - if let Some(rest) = t.strip_prefix(&prefix) { - return Some(rest.trim().trim_matches('"').to_string()); - } - } - None -} - -fn extract_section(source: &str, title: &str) -> String { - let marker = format!("# {title}"); - let mut lines = source.lines(); - while let Some(line) = lines.next() { - if line.trim() == marker { - let mut body = String::new(); - for l in lines.by_ref() { - if l.starts_with("# ") { - break; - } - if !body.is_empty() { - body.push('\n'); - } - body.push_str(l); - } - return body.trim().to_string(); - } - } - String::new() -} - -#[derive(Clone)] -struct EpisodeMeta { - id: String, - path: PathBuf, - task_hash: String, - slug: String, - status: String, - mode: String, - task: String, - result: String, - workbook: String, - llm_calls: i64, - tool_calls: i64, -} - -fn walk_episodes(root: &Path) -> Vec { - let mut out = Vec::new(); - let base = root.join("episodes"); - if !base.is_dir() { - return out; - } - walk_mq(&base, &mut out); - out.sort_by(|a, b| a.id.cmp(&b.id)); - out -} - -fn walk_mq(dir: &Path, out: &mut Vec) { - let Ok(rd) = fs::read_dir(dir) else { - return; - }; - for ent in rd.flatten() { - let p = ent.path(); - if p.is_dir() { - walk_mq(&p, out); - continue; - } - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if !name.ends_with(".mq.md") { - continue; - } - let Ok(src) = fs::read_to_string(&p) else { - continue; - }; - if extract_fm_field(&src, "type").as_deref() != Some("episode") { - continue; - } - let id = extract_fm_field(&src, "id").unwrap_or_else(|| name.trim_end_matches(".mq.md").into()); - let task_hash = extract_fm_field(&src, "task_hash").unwrap_or_default(); - let slug = extract_fm_field(&src, "slug").unwrap_or_default(); - let status = extract_fm_field(&src, "status").unwrap_or_default(); - let mode = extract_fm_field(&src, "mode").unwrap_or_default(); - let workbook = extract_fm_field(&src, "workbook").unwrap_or_default(); - let llm_calls = extract_fm_field(&src, "llm_calls") - .and_then(|s| s.parse().ok()) - .unwrap_or(0); - let tool_calls = extract_fm_field(&src, "tool_calls") - .and_then(|s| s.parse().ok()) - .unwrap_or(0); - let task = extract_section(&src, "Task"); - let result = extract_section(&src, "Result"); - out.push(EpisodeMeta { - id, - path: p, - task_hash, - slug, - status, - mode, - task, - result, - workbook, - llm_calls, - tool_calls, - }); - } -} - -/// List episodes, optionally filtered by task / task_hash / status. -pub fn list_episodes(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - let mut eps = walk_episodes(&root); - if let Some(th) = opt_text(args, "task_hash") { - eps.retain(|e| e.task_hash == th); - } else if let Ok(task) = arg_text(args, "task").or_else(|_| arg_text(args, "goal")) { - let th = goal_sig_hex(&normalize_goal(task)); - eps.retain(|e| e.task_hash == th); - } - if let Some(st) = opt_text(args, "status") { - eps.retain(|e| e.status == st); - } - let limit = opt_i64(args, "limit", 50).max(0) as usize; - let total = eps.len(); - eps.truncate(limit); - let items: Vec = eps - .into_iter() - .map(|e| { - json!({ - "id": e.id, - "path": e.path.to_string_lossy(), - "task_hash": e.task_hash, - "slug": e.slug, - "status": e.status, - "mode": e.mode, - "llm_calls": e.llm_calls, - "tool_calls": e.tool_calls, - }) - }) - .collect(); - Ok(json!({ "count": total, "episodes": items })) -} - -/// Read one episode by id or path. -pub fn get_episode(args: &Value) -> Result { - let root = memory_root(args); - if let Some(path) = opt_text(args, "path") { - let p = resolve_path(path); - let src = fs::read_to_string(&p).map_err(|e| format!("read episode: {e}"))?; - return Ok(json!({ - "ok": true, - "path": p.to_string_lossy(), - "source": src, - "id": extract_fm_field(&src, "id"), - "task_hash": extract_fm_field(&src, "task_hash"), - "status": extract_fm_field(&src, "status"), - "result": extract_section(&src, "Result"), - "task": extract_section(&src, "Task"), - })); - } - let id = arg_text(args, "id")?; - for e in walk_episodes(&root) { - if e.id == id { - let src = fs::read_to_string(&e.path).map_err(|e| format!("read episode: {e}"))?; - return Ok(json!({ - "ok": true, - "path": e.path.to_string_lossy(), - "source": src, - "id": e.id, - "task_hash": e.task_hash, - "status": e.status, - "result": e.result, - "task": e.task, - })); - } - } - Ok(Value::Null) -} - -fn near_score(a: &str, b: &str) -> f64 { - let q = canonicalize_goal_str(a); - let c = canonicalize_goal_str(b); - if q.is_empty() || c.is_empty() { - return 0.0; - } - cosine_tf(&char_bigram_tf(&q), &char_bigram_tf(&c)) -} - -/// Public near-score for Adaptive Routing policy match. -pub(crate) fn task_near_score(a: &str, b: &str) -> f64 { - near_score(a, b) -} - -/// Cheap cluster of episodes by task_hash first, then n-gram near-match (v2 Phase 2). -pub fn cluster_episodes(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - let threshold = match args.get("threshold") { - Some(Value::Number(n)) => n.as_f64().unwrap_or(0.82), - Some(Value::String(s)) => s.parse().unwrap_or(0.82), - _ => 0.82, - }; - let mut eps = walk_episodes(&root); - if let Ok(task) = arg_text(args, "task").or_else(|_| arg_text(args, "goal")) { - let th = goal_sig_hex(&normalize_goal(task)); - // Prefer same hash; also keep near-hash neighbors via task text. - let task_n = normalize_goal(task); - eps.retain(|e| e.task_hash == th || near_score(&task_n, &e.task) >= threshold); - } - // Group by task_hash. - let mut by_hash: Vec<(String, Vec)> = Vec::new(); - for e in eps { - if let Some((_, g)) = by_hash.iter_mut().find(|(h, _)| *h == e.task_hash) { - g.push(e); - } else { - by_hash.push((e.task_hash.clone(), vec![e])); - } - } - // Merge near groups when representatives are similar. - let mut clusters: Vec> = by_hash.into_iter().map(|(_, g)| g).collect(); - let mut merged = true; - while merged { - merged = false; - 'outer: for i in 0..clusters.len() { - for j in (i + 1)..clusters.len() { - let ai = clusters[i].first().map(|e| e.task.as_str()).unwrap_or(""); - let aj = clusters[j].first().map(|e| e.task.as_str()).unwrap_or(""); - if !ai.is_empty() && !aj.is_empty() && near_score(ai, aj) >= threshold { - let other = clusters.remove(j); - clusters[i].extend(other); - merged = true; - break 'outer; - } - } - } - } - let out: Vec = clusters - .into_iter() - .enumerate() - .map(|(i, g)| { - let ids: Vec = g.iter().map(|e| Value::String(e.id.clone())).collect(); - let sample = g.first().map(|e| e.task.clone()).unwrap_or_default(); - let success = g.iter().filter(|e| e.status == "success").count() as i64; - json!({ - "cluster": format!("cluster-{}", i + 1), - "size": g.len() as i64, - "success": success, - "sample_task": sample, - "task_hash": g.first().map(|e| e.task_hash.clone()).unwrap_or_default(), - "episodes": ids, - }) - }) - .collect(); - Ok(json!({ "count": out.len(), "clusters": out })) -} - -/// Extract a shared pattern from successful episodes (heuristic; no LLM). -pub fn extract_pattern(args: &Value) -> Result { - let root = memory_root(args); - let mut eps = walk_episodes(&root); - if let Ok(task) = arg_text(args, "task").or_else(|_| arg_text(args, "goal")) { - let th = goal_sig_hex(&normalize_goal(task)); - eps.retain(|e| e.task_hash == th); - } else if let Some(th) = opt_text(args, "task_hash") { - eps.retain(|e| e.task_hash == th); - } - eps.retain(|e| e.status == "success"); - if eps.is_empty() { - return Ok(json!({ - "ok": false, - "reason": "no_success_episodes", - })); - } - let results: Vec<&str> = eps.iter().map(|e| e.result.as_str()).collect(); - let same_result = results.iter().all(|r| *r == results[0]) && !results[0].is_empty() && results[0] != "none"; - let workbooks: Vec<&str> = eps - .iter() - .map(|e| e.workbook.as_str()) - .filter(|w| !w.is_empty()) - .collect(); - let avg_llm = { - let n = eps.len() as f64; - eps.iter().map(|e| e.llm_calls as f64).sum::() / n - }; - let steps = if same_result { - vec![ - "Return cached solidified answer".to_string(), - format!("result = {}", results[0]), - ] - } else if !workbooks.is_empty() { - vec![ - "Spawn solidified workbook resource".to_string(), - format!("workbook = {}", workbooks[0]), - ] - } else { - vec!["Replay last successful procedure".to_string()] - }; - Ok(json!({ - "ok": true, - "evidence": eps.len() as i64, - "same_result": same_result, - "result": if same_result { results[0] } else { "" }, - "workbook": workbooks.first().copied().unwrap_or(""), - "avg_llm_calls": avg_llm, - "steps": steps, - "invariants": if same_result { json!(["deterministic_result"]) } else { json!([]) }, - "variables": ["task"], - })) -} - -/// Write an experience note under `experiences/.mq.md`. -pub fn generalize(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - let pattern = extract_pattern(args)?; - if pattern.get("ok").and_then(|v| v.as_bool()) != Some(true) { - return Ok(pattern); - } - let task = arg_text(args, "task") - .or_else(|_| arg_text(args, "goal")) - .unwrap_or("task"); - let slug = goal_slug_str(task); - let path = root.join("experiences").join(format!("{slug}.mq.md")); - let evidence = pattern.get("evidence").and_then(|v| v.as_i64()).unwrap_or(0); - let steps = pattern - .get("steps") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - let mut steps_md = String::new(); - for (i, s) in steps.iter().enumerate() { - if let Some(t) = s.as_str() { - steps_md.push_str(&format!("{}. {t}\n", i + 1)); - } - } - let ts = now_rfc3339(); - let body = format!( - "---\ntype: experience\nslug: {slug}\nevidence: {evidence}\ntimestamp: {ts}\nstatus: draft\n---\n\n# Experience: {slug}\n\n# Task\n\n{}\n\n# Pattern\n\n{steps_md}\n", - normalize_goal(task), - ); - fs::write(&path, body).map_err(|e| format!("write experience: {e}"))?; - Ok(json!({ - "ok": true, - "slug": slug, - "path": path.to_string_lossy(), - "evidence": evidence, - "pattern": pattern, - })) -} - -fn write_compiled_mq(result: &str, title: &str) -> String { - let lit = marqdo_quoted(result); - format!( - "---\ntitle: {title}\ntype: skill\nstatus: compiled\nllm_free: true\n---\n\nCompiled from successful episodes (deterministic return).\n\n# main\n\n**`result` = {lit}**\n*`result`*\n" - ) -} - -/// Synthesize a candidate skill `.mq.md` from pattern / episodes. -pub fn synthesize_skill(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - let pattern = extract_pattern(args)?; - if pattern.get("ok").and_then(|v| v.as_bool()) != Some(true) { - return Ok(pattern); - } - let task = arg_text(args, "task") - .or_else(|_| arg_text(args, "goal")) - .unwrap_or("task"); - let slug = goal_slug_str(task); - let cand_dir = root.join("candidates").join(&slug); - fs::create_dir_all(&cand_dir).map_err(|e| format!("mkdir candidates: {e}"))?; - let path = cand_dir.join("candidate.mq.md"); - let evidence = pattern.get("evidence").and_then(|v| v.as_i64()).unwrap_or(0); - let same = pattern.get("same_result").and_then(|v| v.as_bool()).unwrap_or(false); - let result = pattern - .get("result") - .and_then(|v| v.as_str()) - .unwrap_or(""); - let workbook = pattern - .get("workbook") - .and_then(|v| v.as_str()) - .unwrap_or(""); - - let (body, llm_free) = if same && !result.is_empty() && result != "none" { - (write_compiled_mq(result, &slug), true) - } else if !workbook.is_empty() { - let wb_path = resolve_path(workbook); - match fs::read_to_string(&wb_path) { - Ok(src) => { - let lf = !src.contains(".step") - && !src.contains(".单步") - && !src.contains("worker.step"); - (src, lf) - } - Err(_) => ( - format!( - "---\ntitle: {slug}\ntype: skill\nstatus: candidate\nllm_free: false\n---\n\n# main\n\n*\"candidate pending solidify\"*\n" - ), - false, - ), - } - } else { - ( - format!( - "---\ntitle: {slug}\ntype: skill\nstatus: candidate\nllm_free: false\n---\n\n# Purpose\n\nCandidate skill — needs further exploration.\n\n# Main\n\n# main\n\n*\"not yet compiled\"*\n" - ), - false, - ) - }; - fs::write(&path, &body).map_err(|e| format!("write candidate: {e}"))?; - Ok(json!({ - "ok": true, - "slug": slug, - "path": path.to_string_lossy(), - "llm_free": llm_free, - "evidence": evidence, - "status": if llm_free { "compiled" } else { "candidate" }, - })) -} - -/// Validate + compile candidate into `skills//vN.mq.md`, optionally promote to agent-kb. -pub fn compile_skill(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - let task = arg_text(args, "task") - .or_else(|_| arg_text(args, "goal")) - .unwrap_or("task"); - let slug = opt_text(args, "slug") - .map(|s| s.to_string()) - .unwrap_or_else(|| goal_slug_str(task)); - let cand = opt_text(args, "candidate") - .map(PathBuf::from) - .unwrap_or_else(|| root.join("candidates").join(&slug).join("candidate.mq.md")); - let cand = if cand.is_absolute() { - cand - } else { - resolve_path(&cand.to_string_lossy()) - }; - if !cand.is_file() { - // Try synthesize first. - let syn = synthesize_skill(args)?; - if syn.get("ok").and_then(|v| v.as_bool()) != Some(true) { - return Ok(json!({ - "ok": false, - "reason": "no_candidate", - "synthesize": syn, - })); - } - } - let cand_path = if cand.is_file() { - cand - } else { - root.join("candidates").join(&slug).join("candidate.mq.md") - }; - let src = fs::read_to_string(&cand_path).map_err(|e| format!("read candidate: {e}"))?; - let llm_free = extract_fm_field(&src, "llm_free") - .map(|s| s == "true" || s == "True") - .unwrap_or_else(|| { - !src.contains(".step") && !src.contains(".单步") && !src.contains("worker.step") - }); - if !llm_free && !opt_bool(args, "force", false) { - return Ok(json!({ - "ok": false, - "reason": "not_llm_free", - "slug": slug, - "candidate": cand_path.to_string_lossy(), - })); - } - // Held-out / historical gate: require min evidence unless forced. - let min_evidence = opt_i64(args, "min_evidence", 3); - let pattern = extract_pattern(args)?; - let evidence = pattern.get("evidence").and_then(|v| v.as_i64()).unwrap_or(0); - if evidence < min_evidence && !opt_bool(args, "force", false) { - return Ok(json!({ - "ok": false, - "reason": "insufficient_evidence", - "evidence": evidence, - "min_evidence": min_evidence, - })); - } - - let skill_dir = root.join("skills").join(&slug); - fs::create_dir_all(&skill_dir).map_err(|e| format!("mkdir skills: {e}"))?; - let mut ver = 1i64; - if let Ok(rd) = fs::read_dir(&skill_dir) { - for ent in rd.flatten() { - let name = ent.file_name().to_string_lossy().into_owned(); - if let Some(rest) = name.strip_prefix('v') { - if let Some(num) = rest.strip_suffix(".mq.md") { - if let Ok(n) = num.parse::() { - ver = ver.max(n + 1); - } - } - } - } - } - let out_path = skill_dir.join(format!("v{ver}.mq.md")); - let mut body = src.clone(); - if !body.contains("llm_free:") { - body = body.replacen("---\n", "---\nllm_free: true\nstatus: compiled\n", 1); - } else { - // Force compiled markers. - body = body - .lines() - .map(|l| { - if l.starts_with("status:") { - "status: compiled".to_string() - } else if l.starts_with("llm_free:") { - "llm_free: true".to_string() - } else { - l.to_string() - } - }) - .collect::>() - .join("\n"); - if !body.ends_with('\n') { - body.push('\n'); - } - } - fs::write(&out_path, &body).map_err(|e| format!("write skill: {e}"))?; - // Absolute workbook path so kb_promote's resolve_path does not re-join cwd. - let wb_abs = out_path - .canonicalize() - .unwrap_or_else(|_| std::env::current_dir().unwrap_or_default().join(&out_path)); - - let mut promoted = Value::Null; - if opt_bool(args, "promote", true) { - let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR); - let prom_args = json!({ - "kb_dir": kb, - "goal": task, - "workbook": wb_abs.to_string_lossy(), - }); - match crate::kb::kb_promote(&prom_args) { - Ok(p) => promoted = p, - Err(e) => { - return Ok(json!({ - "ok": true, - "compiled": true, - "slug": slug, - "version": ver, - "path": out_path.to_string_lossy(), - "llm_free": true, - "evidence": evidence, - "promote_error": e, - })); - } - } - } - - Ok(json!({ - "ok": true, - "compiled": true, - "slug": slug, - "version": ver, - "path": out_path.to_string_lossy(), - "llm_free": true, - "evidence": evidence, - "promoted": promoted, - })) -} - -/// If enough successful episodes exist, generalize → synthesize → compile (v2 learn loop). -pub fn maybe_learn(args: &Value) -> Result { - let min_evidence = opt_i64(args, "improve_every", opt_i64(args, "min_evidence", 3)); - let root = memory_root(args); - ensure_layout(&root)?; - let mem_arg = opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR); - let task = match arg_text(args, "task").or_else(|_| arg_text(args, "goal")) { - Ok(t) => t.to_string(), - Err(_) => { - return Ok(json!({ - "learned": false, - "reason": "missing_task", - })); - } - }; - let th = goal_sig_hex(&normalize_goal(&task)); - let eps: Vec<_> = walk_episodes(&root) - .into_iter() - .filter(|e| e.task_hash == th && e.status == "success") - .collect(); - let evidence = eps.len() as i64; - if evidence < min_evidence { - return Ok(json!({ - "learned": false, - "reason": "insufficient_evidence", - "evidence": evidence, - "min_evidence": min_evidence, - "task_hash": th, - })); - } - // Skip if already llm_free in kb. - let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR); - let lookup = crate::kb::kb_lookup(&json!({ - "kb_dir": kb, - "goal": task, - "near_match": true, - "near_threshold": 0.78, - })) - .unwrap_or(Value::Null); - if lookup.get("llm_free").and_then(|v| v.as_bool()) == Some(true) { - return Ok(json!({ - "learned": false, - "reason": "already_llm_free", - "evidence": evidence, - "skill": lookup.get("skill").cloned().unwrap_or(Value::Null), - })); - } - - // Pass the original memory_dir string (not resolved root) so nested - // resolve_path does not double-join against host cwd. - let exp = generalize(&json!({ - "memory_dir": mem_arg, - "task": task, - }))?; - let syn = synthesize_skill(&json!({ - "memory_dir": mem_arg, - "task": task, - }))?; - if syn.get("llm_free").and_then(|v| v.as_bool()) != Some(true) - && !opt_bool(args, "force", false) - { - return Ok(json!({ - "learned": false, - "reason": "candidate_not_llm_free", - "evidence": evidence, - "experience": exp, - "candidate": syn, - })); - } - let compiled = compile_skill(&json!({ - "memory_dir": mem_arg, - "task": task, - "kb_dir": kb, - "min_evidence": min_evidence, - "promote": opt_bool(args, "promote", true), - "force": opt_bool(args, "force", false), - }))?; - Ok(json!({ - "learned": compiled.get("ok").and_then(|v| v.as_bool()).unwrap_or(false), - "evidence": evidence, - "experience": exp, - "candidate": syn, - "compile": compiled, - })) -} - -/// Reasoning-amortization metrics over episodes (+ optional kb skill counts). -pub fn metrics(args: &Value) -> Result { - let root = memory_root(args); - ensure_layout(&root)?; - let eps = walk_episodes(&root); - let total = eps.len() as i64; - let success = eps.iter().filter(|e| e.status == "success").count() as i64; - let compiled_runs = eps - .iter() - .filter(|e| e.mode == "compiled" || e.llm_calls == 0) - .count() as i64; - let explore_runs = eps.iter().filter(|e| e.mode == "explore").count() as i64; - let sum_llm: i64 = eps.iter().map(|e| e.llm_calls).sum(); - let sum_tools: i64 = eps.iter().map(|e| e.tool_calls).sum(); - let avg_llm = if total > 0 { - sum_llm as f64 / total as f64 - } else { - 0.0 - }; - let mut by_mode: serde_json::Map = serde_json::Map::new(); - for e in &eps { - let entry = by_mode.entry(e.mode.clone()).or_insert_with(|| { - json!({ "count": 0, "llm_calls": 0 }) - }); - if let Some(obj) = entry.as_object_mut() { - let c = obj.get("count").and_then(|v| v.as_i64()).unwrap_or(0) + 1; - let l = obj.get("llm_calls").and_then(|v| v.as_i64()).unwrap_or(0) + e.llm_calls; - obj.insert("count".into(), json!(c)); - obj.insert("llm_calls".into(), json!(l)); - } - } - Ok(json!({ - "episodes": total, - "success": success, - "compiled_runs": compiled_runs, - "explore_runs": explore_runs, - "llm_calls_total": sum_llm, - "tool_calls_total": sum_tools, - "avg_llm_calls": avg_llm, - "reasoning_amortization": if success > 0 { - sum_llm as f64 / success as f64 - } else { - 0.0 - }, - "by_mode": by_mode, - "memory_dir": root.to_string_lossy(), - })) -} - -/// Resolve task → skill (thin wrapper around kb_lookup with mode labels). -pub fn resolve_task(args: &Value) -> Result { - let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR); - let goal = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?; - let near = opt_bool(args, "near_match", true); - let thr = match args.get("threshold").or_else(|| args.get("near_threshold")) { - Some(Value::Number(n)) => n.as_f64().unwrap_or(0.78), - Some(Value::String(s)) => s.parse().unwrap_or(0.78), - _ => 0.78, - }; - let hit = crate::kb::kb_lookup(&json!({ - "kb_dir": kb, - "goal": goal, - "near_match": near, - "near_threshold": thr, - "tools": args.get("tools").cloned().unwrap_or(Value::Null), - }))?; - if hit.is_null() { - // Keep field set aligned with hit path so facades can safely read llm_free - // (qdagent / agent.run crashed on missing key when OKF is cold). - return Ok(json!({ - "mode": "unknown", - "match": null, - "skill": null, - "resource": null, - "slug": null, - "status": null, - "llm_free": false, - "score": null, - "confidence": 0.0, - })); - } - let match_kind = hit - .get("match") - .and_then(|v| v.as_str()) - .unwrap_or("exact"); - let llm_free = hit.get("llm_free").and_then(|v| v.as_bool()).unwrap_or(false); - let mode = if llm_free { - "exact" - } else if match_kind == "near" || match_kind == "soft" { - "near" - } else { - match_kind - }; - let confidence = hit - .get("score") - .and_then(|v| v.as_f64()) - .unwrap_or(if llm_free { 0.99 } else { 0.85 }); - Ok(json!({ - "mode": mode, - "match": match_kind, - "skill": hit.get("skill").cloned().unwrap_or(Value::Null), - "resource": hit.get("resource").cloned().unwrap_or(Value::Null), - "slug": hit.get("slug").cloned().unwrap_or(Value::Null), - "status": hit.get("status").cloned().unwrap_or(Value::Null), - "llm_free": llm_free, - "score": hit.get("score").cloned().unwrap_or(Value::Null), - "confidence": confidence, - })) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn resolve_miss_includes_llm_free() { - let dir = std::env::temp_dir().join(format!( - "marqdo-resolve-miss-{}", - std::process::id() - )); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let out = resolve_task(&json!({ - "task": "no-such-skill-cold-miss", - "kb_dir": dir.to_string_lossy(), - "near_match": false, - })) - .unwrap(); - assert_eq!(out.get("mode").and_then(|v| v.as_str()), Some("unknown")); - assert_eq!(out.get("llm_free").and_then(|v| v.as_bool()), Some(false)); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn record_and_cluster_and_compile() { - let dir = std::env::temp_dir().join(format!( - "marqdo-mem-{}", - std::process::id() - )); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let mem = dir.join("agent-memory"); - let kb = dir.join("agent-kb"); - let mem_s = mem.to_string_lossy().into_owned(); - let kb_s = kb.to_string_lossy().into_owned(); - let task = "Reply with exactly the word pong and nothing else."; - for _ in 0..3 { - let out = record_episode(&json!({ - "memory_dir": mem_s, - "task": task, - "status": "ok", - "mode": "explore", - "result": "pong", - "llm_calls": 2, - })) - .unwrap(); - assert_eq!(out.get("ok").and_then(|v| v.as_bool()), Some(true)); - } - let listed = list_episodes(&json!({ - "memory_dir": mem_s, - "task": task, - })) - .unwrap(); - assert_eq!(listed.get("count").and_then(|v| v.as_i64()), Some(3)); - let cl = cluster_episodes(&json!({ - "memory_dir": mem_s, - "task": task, - })) - .unwrap(); - assert!(cl.get("count").and_then(|v| v.as_i64()).unwrap_or(0) >= 1); - let learned = maybe_learn(&json!({ - "memory_dir": mem_s, - "kb_dir": kb_s, - "task": task, - "improve_every": 3, - "promote": true, - })) - .unwrap(); - assert_eq!( - learned.get("learned").and_then(|v| v.as_bool()), - Some(true), - "{learned}" - ); - let m = metrics(&json!({ "memory_dir": mem_s })).unwrap(); - assert_eq!(m.get("episodes").and_then(|v| v.as_i64()), Some(3)); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/plugins/agent/src/output.rs b/plugins/agent/src/output.rs deleted file mode 100755 index a105c18..0000000 --- a/plugins/agent/src/output.rs +++ /dev/null @@ -1,289 +0,0 @@ -//! AgentOutputV1 + ResponsePolicy (M-A4). - -use serde_json::{json, Value}; - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) -} - -/// Normalize / build an AgentOutputV1 document. -pub fn output_build(args: &Value) -> Result { - let status = opt_text(args, "status").unwrap_or("succeeded"); - if !matches!( - status, - "succeeded" | "partial" | "failed" | "needs_input" | "cancelled" - ) { - return Err(format!("invalid status={status}")); - } - let answer = args.get("answer").cloned().unwrap_or_else(|| { - json!({ - "format": opt_text(args, "format").unwrap_or("markdown"), - "text": opt_text(args, "text").unwrap_or(""), - }) - }); - let validation = args.get("validation").cloned().unwrap_or_else(|| { - json!({ - "status": "not_run", - "report_ref": Value::Null - }) - }); - let vstatus = validation - .get("status") - .and_then(|v| v.as_str()) - .unwrap_or("not_run"); - if !matches!( - vstatus, - "passed" | "failed" | "not_applicable" | "not_run" - ) { - return Err(format!("invalid validation.status={vstatus}")); - } - // Never claim passed without an explicit report when status says passed. - if vstatus == "passed" && validation.get("report_ref").map(|v| v.is_null()).unwrap_or(true) { - if args.get("allow_passed_without_report").and_then(|v| v.as_bool()) != Some(true) { - return Err("validation.status=passed requires report_ref".into()); - } - } - - let finish = opt_text(args, "finish_reason").unwrap_or(match status { - "succeeded" => "completed", - "partial" => "length_limited", - "cancelled" => "cancelled", - "needs_input" => "needs_input", - _ => "error", - }); - - Ok(json!({ - "schema": "AgentOutputV1", - "schema_version": 1, - "status": status, - "answer": answer, - "artifacts": args.get("artifacts").cloned().unwrap_or_else(|| json!([])), - "citations": args.get("citations").cloned().unwrap_or_else(|| json!([])), - "validation": validation, - "finish_reason": finish, - "recovery_options": args.get("recovery_options").cloned().unwrap_or_else(|| json!([])), - "channels": args.get("channels").cloned().unwrap_or_else(|| json!({ - "answer": true, - "artifact": true, - "progress": true, - "diagnostic": true - })), - })) -} - -/// Apply ResponsePolicy budgets to an answer text → possibly partial output. -pub fn output_apply_policy(args: &Value) -> Result { - let mut out = if args.get("schema").and_then(|v| v.as_str()) == Some("AgentOutputV1") { - args.clone() - } else { - output_build(args)? - }; - let policy = args.get("policy").cloned().unwrap_or(json!({})); - let detail = policy - .get("detail") - .and_then(|v| v.as_str()) - .unwrap_or("standard"); - let max_chars = match policy.get("max_chars").and_then(|v| v.as_u64()) { - Some(n) if n > 0 => n as usize, - _ => match detail { - "concise" => 250, - "detailed" => 8_000, - _ => 700, - }, - }; - let max_tokens = policy - .get("max_output_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or(0) as usize; - let artifact_allowed = policy - .get("artifact_allowed") - .and_then(|v| v.as_bool()) - .unwrap_or(true); - - let text = out - .pointer("/answer/text") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - // Soft char budget (CJK-aware enough: count Unicode scalars). - let chars: Vec = text.chars().collect(); - let mut finish = out - .get("finish_reason") - .and_then(|v| v.as_str()) - .unwrap_or("completed") - .to_string(); - let mut status = out - .get("status") - .and_then(|v| v.as_str()) - .unwrap_or("succeeded") - .to_string(); - let mut answer_text = text.clone(); - if chars.len() > max_chars { - answer_text = chars.into_iter().take(max_chars).collect(); - // Prefer not to cut mid-code fence if possible — soft trim at last newline. - if let Some(pos) = answer_text.rfind('\n') { - if pos > max_chars / 2 { - answer_text.truncate(pos); - } - } - finish = "length_limited".into(); - if status == "succeeded" { - status = "partial".into(); - } - } - // Token budget is advisory here (chars/4 approx) when max_output_tokens set. - if max_tokens > 0 { - let approx = answer_text.chars().count().div_ceil(2); // rough CJK token estimate - if approx > max_tokens { - let keep = max_tokens.saturating_mul(2); - answer_text = answer_text.chars().take(keep).collect(); - finish = "length_limited".into(); - status = "partial".into(); - } - } - - if let Some(obj) = out.as_object_mut() { - obj.insert("status".into(), json!(status)); - obj.insert("finish_reason".into(), json!(finish)); - if let Some(ans) = obj.get_mut("answer").and_then(|v| v.as_object_mut()) { - ans.insert("text".into(), json!(answer_text)); - } - if !artifact_allowed { - obj.insert("artifacts".into(), json!([])); - } - obj.insert( - "response_policy".into(), - json!({ - "detail": detail, - "max_chars": max_chars, - "max_output_tokens": max_tokens, - "artifact_allowed": artifact_allowed, - }), - ); - } - Ok(out) -} - -/// Split a channel event. Only `answer` is meant for chat body append. -pub fn output_channel_event(args: &Value) -> Result { - let channel = opt_text(args, "channel").ok_or_else(|| "missing channel".to_string())?; - if !matches!(channel, "answer" | "artifact" | "progress" | "diagnostic") { - return Err(format!("invalid channel={channel}")); - } - let delta = opt_text(args, "delta").unwrap_or(""); - Ok(json!({ - "schema": "AgentChannelEventV1", - "schema_version": 1, - "channel": channel, - "delta": delta, - "append_to_chat": channel == "answer", - "resource_id": args.get("resource_id").cloned().unwrap_or(Value::Null), - "meta": args.get("meta").cloned().unwrap_or(json!({})), - })) -} - -/// Project `# 结论` (or first non-empty paragraph) from a marqdo document for chat. -pub fn output_project_conclusion(args: &Value) -> Result { - let doc = opt_text(args, "document") - .or_else(|| opt_text(args, "text")) - .unwrap_or(""); - let mut in_conclusion = false; - let mut buf = String::new(); - for line in doc.lines() { - let t = line.trim(); - if t == "# 结论" || t.eq_ignore_ascii_case("# conclusion") { - in_conclusion = true; - continue; - } - if in_conclusion { - if t.starts_with("# ") { - break; - } - if t.is_empty() { - if !buf.is_empty() { - buf.push('\n'); - } - continue; - } - if !buf.is_empty() { - buf.push('\n'); - } - buf.push_str(t); - } - } - if buf.trim().is_empty() { - // Fallback: first non-frontmatter paragraph. - let mut past_fm = !doc.starts_with("---"); - let mut fm_done = past_fm; - for line in doc.lines() { - if !fm_done { - if line.trim() == "---" { - if past_fm { - fm_done = true; - } else { - past_fm = true; - } - } - continue; - } - let t = line.trim(); - if t.is_empty() || t.starts_with('#') || t.starts_with('|') { - continue; - } - buf = t.to_string(); - break; - } - } - Ok(json!({ - "ok": true, - "text": buf.trim(), - "channel": "answer", - "source": "conclusion_projection", - })) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn build_and_policy_limits() { - let out = output_build(&json!({ - "status": "succeeded", - "text": "短答", - "validation": {"status": "not_applicable", "report_ref": null} - })) - .unwrap(); - assert_eq!(out["schema"], "AgentOutputV1"); - assert_eq!(out["answer"]["text"], "短答"); - - let long: String = "字".repeat(400); - let limited = output_apply_policy(&json!({ - "status": "succeeded", - "text": long, - "validation": {"status": "not_applicable"}, - "policy": {"detail": "concise", "max_chars": 100} - })) - .unwrap(); - assert_eq!(limited["status"], "partial"); - assert_eq!(limited["finish_reason"], "length_limited"); - assert!(limited["answer"]["text"].as_str().unwrap().chars().count() <= 100); - } - - #[test] - fn channel_answer_only_appends_chat() { - let e = output_channel_event(&json!({"channel": "progress", "delta": "检索中"})).unwrap(); - assert_eq!(e["append_to_chat"], false); - let a = output_channel_event(&json!({"channel": "answer", "delta": "hi"})).unwrap(); - assert_eq!(a["append_to_chat"], true); - } - - #[test] - fn project_conclusion() { - let doc = "---\ntitle: t\n---\n\n# 任务\n问\n\n# 结论\n答案是 42。\n\n# main\nprint\n"; - let p = output_project_conclusion(&json!({"document": doc})).unwrap(); - assert!(p["text"].as_str().unwrap().contains("42")); - } -} diff --git a/plugins/agent/src/parallel.rs b/plugins/agent/src/parallel.rs deleted file mode 100644 index e5d6ad2..0000000 --- a/plugins/agent/src/parallel.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! Deterministic fan-out results: never discard a successful sibling and never -//! infer success from a completed wait protocol alone. - -use serde_json::{json, Value}; - -pub fn report(args: &Value) -> Result { - let results = args - .get("results") - .and_then(Value::as_array) - .ok_or_else(|| "results must be ordered subtask result list".to_string())?; - if results.len() > 10_000 { - return Err("parallel result count exceeds scheduler limit".into()); - } - let mut passed = 0usize; - let mut failed = 0usize; - let mut unknown = 0usize; - let mut entries = Vec::with_capacity(results.len()); - for (index, child) in results.iter().enumerate() { - let transport = child.get("ok").and_then(Value::as_bool); - let body = child.get("value").unwrap_or(&Value::Null); - let status = match (transport, body.get("code").and_then(Value::as_i64)) { - (Some(true), Some(0)) => { passed += 1; "succeeded" } - (Some(true), Some(_)) | (Some(false), _) => { failed += 1; "failed" } - _ => { unknown += 1; "uncertain" } - }; - // Raw child result is kept as data; the model sees only an optional - // bounded summary. The host may store detailed output as an artifact. - let detail = child.get("error") - .and_then(Value::as_str) - .or_else(|| body.get("stderr").and_then(Value::as_str)) - .unwrap_or(""); - let brief: String = detail.chars().take(280).collect(); - entries.push(json!({ - "index": index, - "status": status, - "summary": brief, - "result": child - })); - } - let status = if unknown != 0 { - "uncertain" - } else if failed == 0 { - "succeeded" - } else if passed > 0 { - "partial" - } else { - "failed" - }; - Ok(json!({ - "ok": failed == 0 && unknown == 0, - "schema": "AgentParallelResultV1", - "status": status, - "succeeded": passed, - "failed": failed, - "uncertain": unknown, - "items": entries - })) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn preserves_success_and_exposes_failed_child() { - let result = report(&json!({"results":[ - {"ok":true,"value":{"code":0,"value":"good"}}, - {"ok":true,"value":{"code":2,"stderr":"failed"}}, - {"ok":false,"error":"timeout"} - ]})).unwrap(); - assert_eq!(result["status"], "partial"); - assert_eq!(result["succeeded"], 1); - assert_eq!(result["failed"], 2); - assert_eq!(result["items"][0]["status"], "succeeded"); - } - #[test] - fn unknown_child_cannot_be_mislabeled_successful() { - let value = report(&json!({"results":[{"ok":true,"value":{"value":"no code"}}]})).unwrap(); - assert_eq!(value["status"], "uncertain"); - assert_eq!(value["ok"], false); - } -} diff --git a/plugins/agent/src/resume.rs b/plugins/agent/src/resume.rs deleted file mode 100755 index 821aec1..0000000 --- a/plugins/agent/src/resume.rs +++ /dev/null @@ -1,511 +0,0 @@ -//! Agent plan/run resume checkpoints under `.marqdo/agent-resume/`. -//! M-A1: CheckpointV2 atomic write (temp→fsync→rename); legacy load → manual_review. - -use std::fs::{self, File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -const DEFAULT_RESUME_DIR: &str = ".marqdo/agent-resume"; - -fn resolve_path(rel: &str) -> PathBuf { - let p = PathBuf::from(rel); - if p.is_absolute() { - return p; - } - if p.exists() { - return p; - } - let base = (|| { - let q = crate::host_query_json("cwd")?; - q.as_str() - .map(PathBuf::from) - .ok_or_else(|| "cwd not text".to_string()) - })() - .or_else(|_| std::env::current_dir().map_err(|e| e.to_string())) - .unwrap_or_else(|_| PathBuf::from(".")); - base.join(p) -} - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) -} - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - opt_text(args, key).ok_or_else(|| format!("missing text `{key}`")) -} - -fn opt_i64(args: &Value, key: &str, default: i64) -> i64 { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Number(n)) => n.as_i64().unwrap_or(default), - Some(Value::String(s)) => s.parse().unwrap_or(default), - _ => default, - } -} - -/// Host-relative resume roots only — reject absolute client paths (M-A1). -fn resume_root(args: &Value) -> Result { - let rel = opt_text(args, "resume_dir").unwrap_or(DEFAULT_RESUME_DIR); - let p = PathBuf::from(rel); - if p.is_absolute() { - return Err( - "resume_dir must be host-relative; absolute client paths are rejected".into(), - ); - } - if rel.contains("..") { - return Err("resume_dir must not contain '..'".into()); - } - Ok(resolve_path(rel)) -} - -fn checkpoint_path(root: &Path, id: &str) -> PathBuf { - let safe: String = id - .chars() - .map(|c| { - if c.is_ascii_alphanumeric() || c == '-' || c == '_' { - c - } else { - '_' - } - }) - .collect(); - root.join(format!("{safe}.json")) -} - -fn now_rfc3339() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) -} - -fn ensure_dir(root: &Path) -> Result<(), String> { - fs::create_dir_all(root).map_err(|e| format!("resume mkdir: {e}")) -} - -/// Atomic durable write: unique temp → write → flush/fsync → rename. -static TEMP_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - -fn atomic_write_json(path: &Path, doc: &Value) -> Result<(), String> { - let parent = path - .parent() - .ok_or_else(|| "checkpoint path has no parent".to_string())?; - ensure_dir(parent)?; - let tmp_name = format!( - ".{}.tmp-{}-{}", - path.file_name() - .and_then(|s| s.to_str()) - .unwrap_or("ckpt.json"), - std::process::id(), - format!("{}-{}", now_rfc3339().replace(':', ""), - TEMP_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) - ); - let tmp = parent.join(tmp_name); - let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?; - { - let mut f = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .open(&tmp) - .map_err(|e| format!("resume temp open: {e}"))?; - f.write_all(text.as_bytes()) - .map_err(|e| format!("resume temp write: {e}"))?; - f.flush().map_err(|e| format!("resume temp flush: {e}"))?; - f.sync_all() - .map_err(|e| format!("resume temp fsync: {e}"))?; - } - // Best-effort directory fsync (platform may ignore). - if let Ok(dir) = File::open(parent) { - let _ = dir.sync_all(); - } - fs::rename(&tmp, path).map_err(|e| { - let _ = fs::remove_file(&tmp); - format!("resume atomic rename: {e}") - })?; - Ok(()) -} - -fn wants_checkpoint_v2(args: &Value) -> bool { - matches!( - args.get("schema").and_then(|v| v.as_str()), - Some("CheckpointV2") - ) || args.get("schema_version").and_then(|v| v.as_u64()) == Some(2) - || args.get("checkpoint_v2").and_then(|v| v.as_bool()) == Some(true) -} - -fn build_checkpoint_v2(args: &Value, id: &str) -> Value { - let committed = now_rfc3339(); - let mut doc = json!({ - "schema": "CheckpointV2", - "schema_version": 2, - "checkpoint_id": args.get("checkpoint_id").cloned().unwrap_or_else(|| json!(id)), - "logical_run_id": args.get("logical_run_id").cloned().unwrap_or_else(|| json!(id)), - "task_id": args.get("task_id").cloned().unwrap_or_else(|| json!(id)), - "attempt_id": args.get("attempt_id").cloned().unwrap_or_else(|| json!("attempt_1")), - "step_id": args.get("step_id").cloned().unwrap_or(Value::Null), - "parent_checkpoint_id": args.get("parent_checkpoint_id").cloned().unwrap_or(Value::Null), - "principal_ref": args.get("principal_ref").cloned().unwrap_or(Value::Null), - "workspace_id": args.get("workspace_id").cloned().unwrap_or(Value::Null), - "session_id": args.get("session_id").cloned().unwrap_or(Value::Null), - "completed_steps": args.get("completed_steps").cloned().unwrap_or_else(|| json!([])), - "pending_operation": args.get("pending_operation").cloned().unwrap_or(Value::Null), - "deadline": args.get("deadline").cloned().unwrap_or(Value::Null), - "committed_at": args.get("committed_at").cloned().unwrap_or_else(|| json!(committed)), - // Effect watermark — absent/null means no ledger yet (write auto-resume closed). - "effect_ledger_watermark": args.get("effect_ledger_watermark").cloned().unwrap_or(Value::Null), - "event_seq": args.get("event_seq").cloned().unwrap_or(Value::Null), - "manifest_digest": args.get("manifest_digest").cloned().unwrap_or(Value::Null), - }); - if let Some(obj) = doc.as_object_mut() { - // Preserve legacy author fields for dual-read. - for key in [ - "goal", "task", "status", "workbook", "events", "route", "result", "round", "meta", - "id", - ] { - if let Some(v) = args.get(key) { - if !v.is_null() { - obj.insert(key.to_string(), v.clone()); - } - } - } - if !obj.contains_key("id") { - obj.insert("id".into(), json!(id)); - } - if !obj.contains_key("updated_at") { - obj.insert("updated_at".into(), json!(committed.clone())); - } - if !obj.contains_key("round") { - obj.insert("round".into(), json!(opt_i64(args, "round", 0))); - } - if !obj.contains_key("status") { - obj.insert("status".into(), json!("running")); - } - } - doc -} - -fn build_legacy_doc(args: &Value, id: &str) -> Value { - let mut doc = json!({ - "id": id, - "updated_at": now_rfc3339(), - }); - if let Some(obj) = doc.as_object_mut() { - for key in [ - "goal", "task", "status", "workbook", "events", "route", "result", "round", "meta", - ] { - if let Some(v) = args.get(key) { - if !v.is_null() { - obj.insert(key.to_string(), v.clone()); - } - } - } - if !obj.contains_key("round") { - obj.insert("round".into(), json!(opt_i64(args, "round", 0))); - } - if !obj.contains_key("status") { - obj.insert("status".into(), json!("running")); - } - } - doc -} - -pub fn resume_save(args: &Value) -> Result { - let id = arg_text(args, "id")?; - let root = resume_root(args)?; - ensure_dir(&root)?; - let path = checkpoint_path(&root, id); - let v2 = wants_checkpoint_v2(args); - let doc = if v2 { - build_checkpoint_v2(args, id) - } else { - build_legacy_doc(args, id) - }; - atomic_write_json(&path, &doc)?; - Ok(json!({ - "ok": true, - "id": id, - "path": path.to_string_lossy(), - "schema": doc.get("schema").cloned().unwrap_or(Value::Null), - "schema_version": doc.get("schema_version").cloned().unwrap_or(Value::Null), - "updated_at": doc.get("updated_at").or_else(|| doc.get("committed_at")).cloned().unwrap_or(Value::Null), - "atomic": true, - })) -} - -fn watermark_allows_write_auto(wm: &Value) -> bool { - match wm { - Value::Null => false, - Value::String(s) => !s.is_empty(), - Value::Object(obj) => { - // Prefer explicit safety bit from effects_watermark; bare digest objects - // without the bit are treated as unsafe (open unknown / pending writes). - match obj.get("write_auto_resume_safe").and_then(|v| v.as_bool()) { - Some(b) => b, - None => obj - .get("watermark") - .and_then(|v| v.as_str()) - .map(|s| !s.is_empty()) - .unwrap_or(false) - && obj.get("open_unknown").and_then(|v| v.as_u64()).unwrap_or(1) == 0 - && obj.get("pending_writes").and_then(|v| v.as_u64()).unwrap_or(1) == 0, - } - } - _ => false, - } -} - -fn annotate_recovery(mut doc: Value) -> Value { - let is_v2 = doc.get("schema").and_then(|v| v.as_str()) == Some("CheckpointV2") - && doc.get("schema_version").and_then(|v| v.as_u64()) == Some(2); - let wm = doc - .get("effect_ledger_watermark") - .cloned() - .unwrap_or(Value::Null); - let ledger_safe = watermark_allows_write_auto(&wm); - let (recovery_mode, write_auto_resume) = if is_v2 && ledger_safe { - ("checkpoint_v2", true) - } else if is_v2 { - // V2 without a safe ledger watermark: read resume OK; write auto-resume closed. - ("checkpoint_v2_read_only", false) - } else { - // Legacy: no effect info → manual_review; never auto redo writes. - ("manual_review", false) - }; - if let Some(obj) = doc.as_object_mut() { - obj.insert("recovery_mode".into(), json!(recovery_mode)); - obj.insert("write_auto_resume".into(), json!(write_auto_resume)); - if !is_v2 { - obj.insert("legacy_adaptation".into(), json!("manual_review")); - } - } - doc -} - -pub fn resume_load(args: &Value) -> Result { - let id = arg_text(args, "id")?; - let root = resume_root(args)?; - let path = checkpoint_path(&root, id); - if !path.is_file() { - return Ok(json!({ - "ok": false, - "found": false, - "id": id, - "path": path.to_string_lossy(), - })); - } - let text = fs::read_to_string(&path).map_err(|e| format!("resume load: {e}"))?; - let parsed: Value = match serde_json::from_str(&text) { - Ok(v) => v, - Err(e) => { - return Ok(json!({ - "ok": false, - "found": true, - "id": id, - "path": path.to_string_lossy(), - "error": { - "schema": "AgentErrorV1", - "schema_version": 1, - "code": "checkpoint.corrupt", - "category": "unknown_effect", - "stage": "checkpoint", - "message": format!("corrupt checkpoint json: {e}"), - "retryable": false, - "effect_state": "unknown", - "recovery_action": "manual_review", - }, - "recovery_mode": "manual_review", - "write_auto_resume": false, - })); - } - }; - let mut doc = annotate_recovery(parsed); - if let Some(obj) = doc.as_object_mut() { - obj.insert("ok".into(), json!(true)); - obj.insert("found".into(), json!(true)); - obj.insert("path".into(), json!(path.to_string_lossy())); - } - Ok(doc) -} - -pub fn resume_clear(args: &Value) -> Result { - let id = arg_text(args, "id")?; - let root = resume_root(args)?; - let path = checkpoint_path(&root, id); - let existed = path.is_file(); - if existed { - fs::remove_file(&path).map_err(|e| format!("resume clear: {e}"))?; - } - Ok(json!({ - "ok": true, - "id": id, - "cleared": existed, - "path": path.to_string_lossy(), - })) -} - -pub fn resume_list(args: &Value) -> Result { - let root = resume_root(args)?; - if !root.is_dir() { - return Ok(json!({ "ok": true, "items": [], "resume_dir": root.to_string_lossy() })); - } - let mut items = Vec::new(); - let rd = fs::read_dir(&root).map_err(|e| format!("resume list: {e}"))?; - for ent in rd.flatten() { - let p = ent.path(); - if p.extension().and_then(|e| e.to_str()) != Some("json") { - continue; - } - // Skip leftover temp files from crashed writers. - if p.file_name() - .and_then(|s| s.to_str()) - .map(|s| s.starts_with('.')) - .unwrap_or(false) - { - continue; - } - let id = p - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("") - .to_string(); - let meta = fs::metadata(&p).ok(); - items.push(json!({ - "id": id, - "path": p.to_string_lossy(), - "len": meta.map(|m| m.len()).unwrap_or(0), - })); - } - items.sort_by(|a, b| { - let ai = a.get("id").and_then(|v| v.as_str()).unwrap_or(""); - let bi = b.get("id").and_then(|v| v.as_str()).unwrap_or(""); - ai.cmp(bi) - }); - Ok(json!({ - "ok": true, - "items": items, - "resume_dir": root.to_string_lossy(), - })) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn scratch(label: &str) -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - // Do not mutate process-wide cwd from concurrent Rust unit tests. - let dir = PathBuf::from("target").join(format!("marqdo-resume-{label}-{nanos}")); - fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn absolute_resume_dir_rejected() { - let err = resume_root(&json!({"resume_dir": "/tmp/evil"})).unwrap_err(); - assert!(err.contains("host-relative")); - } - - #[test] - fn atomic_v2_roundtrip_and_legacy_manual_review() { - let dir = scratch("v2"); - let rel = dir.join("ckpts").to_string_lossy().to_string(); - let saved = resume_save(&json!({ - "id": "run1", - "schema": "CheckpointV2", - "schema_version": 2, - "goal": "ping", - "status": "running", - "round": 1, - "resume_dir": rel, - "attempt_id": "a1", - })) - .unwrap(); - assert_eq!(saved["ok"], true); - assert_eq!(saved["atomic"], true); - assert_eq!(saved["schema"], "CheckpointV2"); - - let loaded = resume_load(&json!({"id": "run1", "resume_dir": rel})).unwrap(); - assert_eq!(loaded["found"], true); - assert_eq!(loaded["schema"], "CheckpointV2"); - assert_eq!(loaded["recovery_mode"], "checkpoint_v2_read_only"); - assert_eq!(loaded["write_auto_resume"], false); - - // Legacy document without schema. - let _ = resume_save(&json!({ - "id": "legacy1", - "goal": "pong", - "status": "interrupted", - "round": 2, - "resume_dir": rel, - })) - .unwrap(); - let legacy = resume_load(&json!({"id": "legacy1", "resume_dir": rel})).unwrap(); - assert_eq!(legacy["recovery_mode"], "manual_review"); - assert_eq!(legacy["write_auto_resume"], false); - assert_eq!(legacy["legacy_adaptation"], "manual_review"); - - // V2 + safe watermark → write_auto_resume opens. - let _ = resume_save(&json!({ - "id": "run_safe", - "schema": "CheckpointV2", - "schema_version": 2, - "status": "running", - "round": 3, - "resume_dir": rel, - "attempt_id": "a2", - "effect_ledger_watermark": { - "schema": "EffectLedgerWatermarkV1", - "watermark": "sha256-lite:abc", - "write_auto_resume_safe": true, - "open_unknown": 0, - "pending_writes": 0 - } - })) - .unwrap(); - let safe = resume_load(&json!({"id": "run_safe", "resume_dir": rel})).unwrap(); - assert_eq!(safe["recovery_mode"], "checkpoint_v2"); - assert_eq!(safe["write_auto_resume"], true); - - // Unsafe watermark (open unknown) keeps write auto-resume closed. - let _ = resume_save(&json!({ - "id": "run_unsafe", - "schema": "CheckpointV2", - "schema_version": 2, - "status": "running", - "round": 4, - "resume_dir": rel, - "attempt_id": "a3", - "effect_ledger_watermark": { - "watermark": "sha256-lite:def", - "write_auto_resume_safe": false, - "open_unknown": 1 - } - })) - .unwrap(); - let unsafe_ck = resume_load(&json!({"id": "run_unsafe", "resume_dir": rel})).unwrap(); - assert_eq!(unsafe_ck["recovery_mode"], "checkpoint_v2_read_only"); - assert_eq!(unsafe_ck["write_auto_resume"], false); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn corrupt_checkpoint_reports_error() { - let dir = scratch("corrupt"); - let ckpts = dir.join("ckpts"); - fs::create_dir_all(&ckpts).unwrap(); - fs::write(ckpts.join("bad.json"), "{not-json").unwrap(); - let loaded = resume_load(&json!({"id": "bad", "resume_dir": ckpts.to_string_lossy()})).unwrap(); - assert_eq!(loaded["found"], true); - assert_eq!(loaded["ok"], false); - assert_eq!(loaded["error"]["code"], "checkpoint.corrupt"); - assert_eq!(loaded["recovery_mode"], "manual_review"); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/plugins/agent/src/route.rs b/plugins/agent/src/route.rs deleted file mode 100755 index 1fc168f..0000000 --- a/plugins/agent/src/route.rs +++ /dev/null @@ -1,719 +0,0 @@ -//! Adaptive Routing / Policy Compilation (Phase 4). -//! Router is abstract: marqdo | small-llm | llm | auto. -//! `jev` is accepted as an alias of `small-llm` (compat); not a first-class backend. - -use std::collections::HashMap; -use std::fs; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -use crate::kb::{goal_sig_hex, goal_slug_str, normalize_goal}; -use crate::memory::{self}; - -const DEFAULT_MEMORY_DIR: &str = ".marqdo/agent-memory"; -const DEFAULT_KB_DIR: &str = ".marqdo/agent-kb"; -const POLICY_NAME: &str = "router.mq.md"; - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - args.get(key) - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("missing text `{key}`")) -} - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty()) -} - -fn opt_i64(args: &Value, key: &str, default: i64) -> i64 { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Number(n)) => n.as_i64().unwrap_or(default), - Some(Value::String(s)) => s.parse().unwrap_or(default), - _ => default, - } -} - -fn opt_f64(args: &Value, key: &str, default: f64) -> f64 { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Number(n)) => n.as_f64().unwrap_or(default), - Some(Value::String(s)) => s.parse().unwrap_or(default), - _ => default, - } -} - -fn opt_bool(args: &Value, key: &str, default: bool) -> bool { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Bool(b)) => *b, - Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"), - Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0, - _ => default, - } -} - -fn now_rfc3339() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) -} - -fn yaml_escape(s: &str) -> String { - if s.is_empty() - || s.contains(':') - || s.contains('#') - || s.contains('|') - || s.contains('"') - || s.contains('\n') - { - format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) - } else { - s.to_string() - } -} - -fn resolve_path(rel: &str) -> PathBuf { - let p = PathBuf::from(rel); - if p.is_absolute() { - return p; - } - if p.exists() { - return p; - } - let base = (|| { - let q = crate::host_query_json("cwd")?; - q.as_str() - .map(PathBuf::from) - .ok_or_else(|| "cwd not text".to_string()) - })() - .or_else(|_| std::env::current_dir().map_err(|e| e.to_string())) - .unwrap_or_else(|_| PathBuf::from(".")); - base.join(p) -} - -fn memory_root(args: &Value) -> PathBuf { - let rel = opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR); - resolve_path(rel) -} - -fn policy_path(root: &Path) -> PathBuf { - root.join("policies").join(POLICY_NAME) -} - -#[derive(Clone, Debug)] -struct PolicyRule { - task_hash: String, - slug: String, - skill: String, - task: String, - count: i64, - confidence: f64, -} - -fn parse_policy(src: &str) -> Vec { - let mut rules = Vec::new(); - let mut in_table = false; - let mut header_ok = false; - for line in src.lines() { - let t = line.trim(); - if t.starts_with("|") && t.contains("task_hash") { - in_table = true; - header_ok = true; - continue; - } - if in_table && t.starts_with("|") && t.contains("---") { - continue; - } - if in_table && t.starts_with("|") { - let cols: Vec<&str> = t - .trim_matches('|') - .split('|') - .map(|c| c.trim().trim_matches('"')) - .collect(); - if cols.len() >= 5 { - let count = cols[4].parse().unwrap_or(1); - let confidence = if cols.len() >= 6 { - cols[5].parse().unwrap_or(0.9) - } else { - 0.9 - }; - let task = if cols.len() >= 7 { - cols[6].to_string() - } else { - String::new() - }; - rules.push(PolicyRule { - task_hash: cols[0].to_string(), - slug: cols[1].to_string(), - skill: cols[2].to_string(), - count, - confidence, - task, - }); - } - continue; - } - if in_table && header_ok && !t.starts_with('|') && !t.is_empty() { - break; - } - } - rules -} - -fn write_policy(root: &Path, rules: &[PolicyRule]) -> Result { - fs::create_dir_all(root.join("policies")).map_err(|e| format!("mkdir policies: {e}"))?; - let path = policy_path(root); - let ts = now_rfc3339(); - let mut body = format!( - "---\ntype: policy\nstatus: compiled\nbackend: marqdo\ngenerated_at: {ts}\nrules: {}\n---\n\n# Adaptive router (compiled Marqdo policy)\n\nDeterministic task → skill routing. No LLM required.\n\n# Rules\n\n| task_hash | slug | skill | resource | count | confidence | task |\n|-----------|------|-------|----------|------:|-----------:|------|\n", - rules.len() - ); - for r in rules { - body.push_str(&format!( - "| {} | {} | {} | {} | {} | {:.2} | {} |\n", - r.task_hash, - yaml_escape(&r.slug), - yaml_escape(&r.skill), - yaml_escape(&r.skill), // resource often == skill path for OKF - r.count, - r.confidence, - yaml_escape(&r.task), - )); - } - body.push_str("\n# Fallback\n\nllm\n"); - fs::write(&path, body).map_err(|e| format!("write policy: {e}"))?; - Ok(path) -} - -fn load_rules(root: &Path) -> Vec { - let path = policy_path(root); - let Ok(src) = fs::read_to_string(&path) else { - return Vec::new(); - }; - parse_policy(&src) -} - -fn match_policy(rules: &[PolicyRule], task: &str, threshold: f64) -> Option { - let th = goal_sig_hex(&normalize_goal(task)); - if let Some(r) = rules.iter().find(|r| r.task_hash == th) { - return Some(r.clone()); - } - // Near-match on stored task text / slug. - let mut best: Option<(f64, PolicyRule)> = None; - for r in rules { - let score = memory::task_near_score(task, &r.task); - if score >= threshold { - if best.as_ref().map(|(s, _)| score > *s).unwrap_or(true) { - best = Some((score, r.clone())); - } - } - let slug_score = memory::task_near_score(task, &r.slug); - if slug_score >= threshold { - if best.as_ref().map(|(s, _)| slug_score > *s).unwrap_or(true) { - let mut rr = r.clone(); - rr.confidence = slug_score; - best = Some((slug_score, rr)); - } - } - } - best.map(|(s, mut r)| { - r.confidence = s; - r - }) -} - -fn build_route_prompt(task: &str, candidates: &[Value]) -> String { - let mut s = String::from( - "You are a Marqdo Agent router. Pick the best skill slug for the task, or say EXPLORE.\n\nReply with exactly one line:\nSKILL:\nor\nEXPLORE\n\nTask:\n", - ); - s.push_str(task); - s.push_str("\n\nCandidates:\n"); - for (i, c) in candidates.iter().enumerate() { - let slug = c - .get("slug") - .or_else(|| c.get("title")) - .and_then(|v| v.as_str()) - .unwrap_or("?"); - let title = c - .get("title") - .or_else(|| c.get("goal")) - .and_then(|v| v.as_str()) - .unwrap_or(""); - s.push_str(&format!("{}. {slug} — {title}\n", i + 1)); - } - s -} - -fn candidate_list(args: &Value) -> Result, String> { - if let Some(Value::Array(items)) = args.get("candidates") { - return Ok(items.clone()); - } - let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR); - let listed = crate::kb::kb_list_tasks(&json!({ "kb_dir": kb }))?; - let tasks = listed - .get("tasks") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - if !tasks.is_empty() { - return Ok(tasks); - } - let goal = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?; - let near = crate::kb::kb_near_match(&json!({ - "kb_dir": kb, - "goal": goal, - }))?; - Ok(near - .get("candidates") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default()) -} - -fn enrich_with_kb(rule: &PolicyRule, kb: &str, task: &str) -> Result { - let hit = crate::kb::kb_lookup(&json!({ - "kb_dir": kb, - "goal": task, - "slug": rule.slug, - "near_match": true, - "near_threshold": 0.5, - })) - .unwrap_or(Value::Null); - let resource = hit - .get("resource") - .cloned() - .unwrap_or_else(|| Value::String(rule.skill.clone())); - let skill = hit - .get("skill") - .cloned() - .unwrap_or_else(|| Value::String(rule.skill.clone())); - let llm_free = hit - .get("llm_free") - .and_then(|v| v.as_bool()) - .unwrap_or(true); - Ok(json!({ - "backend": "marqdo", - "mode": "policy", - "matched": true, - "needs_llm": false, - "slug": rule.slug, - "skill": skill, - "resource": resource, - "task_hash": rule.task_hash, - "confidence": rule.confidence, - "llm_free": llm_free, - "count": rule.count, - })) -} - -fn route_marqdo(args: &Value) -> Result { - let root = memory_root(args); - let _ = memory::memory_ensure(&json!({ - "memory_dir": opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR), - })); - let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?; - let threshold = opt_f64(args, "threshold", 0.78); - let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR); - let rules = load_rules(&root); - if let Some(rule) = match_policy(&rules, task, threshold) { - if rule.confidence >= threshold { - return enrich_with_kb(&rule, kb, task); - } - } - Ok(json!({ - "backend": "marqdo", - "mode": "miss", - "matched": false, - "needs_llm": false, - "confidence": 0.0, - })) -} - -fn route_resolve_fallback(args: &Value) -> Result { - let resolved = memory::resolve_task(args)?; - let conf = resolved - .get("confidence") - .and_then(|v| v.as_f64()) - .unwrap_or(0.0); - let llm_free = resolved - .get("llm_free") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - if conf >= opt_f64(args, "threshold", 0.78) || llm_free { - return Ok(json!({ - "backend": "kb", - "mode": resolved.get("mode").cloned().unwrap_or(Value::String("near".into())), - "matched": true, - "needs_llm": false, - "slug": resolved.get("slug").cloned().unwrap_or(Value::Null), - "skill": resolved.get("skill").cloned().unwrap_or(Value::Null), - "resource": resolved.get("resource").cloned().unwrap_or(Value::Null), - "confidence": conf, - "llm_free": llm_free, - })); - } - Ok(json!({ - "backend": "kb", - "mode": "miss", - "matched": false, - "needs_llm": false, - "confidence": conf, - "resolve": resolved, - })) -} - -fn route_model_request(args: &Value, level: &str) -> Result { - let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?; - let cands = candidate_list(args)?; - let prompt = build_route_prompt(task, &cands); - Ok(json!({ - "backend": level, - "mode": "needs_llm", - "matched": false, - "needs_llm": true, - "level": level, - "prompt": prompt, - "candidates": cands, - "confidence": 0.0, - })) -} - -/// Cascade Adaptive Router (Phase 4). -/// -/// `backend`: `auto` | `marqdo` | `small-llm` | `llm` (`jev` → alias of `small-llm`). -/// -/// `auto` order: marqdo policy → kb resolve → small-llm request. -pub fn route(args: &Value) -> Result { - let backend = opt_text(args, "backend").unwrap_or("auto"); - let threshold = opt_f64(args, "threshold", 0.78); - - match backend { - "marqdo" => { - let hit = route_marqdo(args)?; - if hit.get("matched").and_then(|v| v.as_bool()) == Some(true) { - return Ok(hit); - } - route_resolve_fallback(args) - } - "small-llm" | "small_llm" | "small" | "jev" => route_model_request(args, "small-llm"), - "llm" | "large" | "large-llm" => route_model_request(args, "llm"), - "auto" | _ => { - let mut trace: Vec = Vec::new(); - let m = route_marqdo(args)?; - trace.push(json!({"try": "marqdo", "matched": m.get("matched")})); - if m.get("matched").and_then(|v| v.as_bool()) == Some(true) - && m.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0) >= threshold - { - let mut out = m; - if let Some(obj) = out.as_object_mut() { - obj.insert("trace".into(), Value::Array(trace)); - obj.insert("backend".into(), Value::String("auto/marqdo".into())); - } - return Ok(out); - } - let kb = route_resolve_fallback(args)?; - trace.push(json!({"try": "kb", "matched": kb.get("matched")})); - if kb.get("matched").and_then(|v| v.as_bool()) == Some(true) { - let mut out = kb; - if let Some(obj) = out.as_object_mut() { - obj.insert("trace".into(), Value::Array(trace)); - obj.insert("backend".into(), Value::String("auto/kb".into())); - } - return Ok(out); - } - // Prefer small-llm request in auto when nothing matched (caller may use large). - let mut req = route_model_request(args, "small-llm")?; - if let Some(obj) = req.as_object_mut() { - obj.insert("trace".into(), Value::Array(trace)); - obj.insert("backend".into(), Value::String("auto/small-llm".into())); - } - Ok(req) - } - } -} - -/// Apply a router model reply (`SKILL:` / `EXPLORE`) to a concrete skill hit. -pub fn route_apply(args: &Value) -> Result { - let reply = arg_text(args, "reply")?; - let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR); - let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?; - let line = reply - .lines() - .map(|l| l.trim()) - .find(|l| !l.is_empty()) - .unwrap_or(""); - let upper = line.to_ascii_uppercase(); - if upper.starts_with("EXPLORE") || upper == "LLM" || upper == "NEW" { - return Ok(json!({ - "matched": false, - "mode": "explore", - "decision": "EXPLORE", - "needs_llm": false, - })); - } - let slug = if let Some(rest) = line.strip_prefix("SKILL:") { - rest.trim() - } else if let Some(rest) = line.strip_prefix("skill:") { - rest.trim() - } else if let Some(rest) = line.strip_prefix("调用:") { - rest.trim() - } else { - line.trim() - }; - if slug.is_empty() { - return Ok(json!({ - "matched": false, - "mode": "explore", - "decision": "EXPLORE", - "reason": "empty_slug", - })); - } - let hit = crate::kb::kb_lookup(&json!({ - "kb_dir": kb, - "goal": task, - "slug": slug, - "near_match": true, - "near_threshold": 0.5, - }))?; - if hit.is_null() { - return Ok(json!({ - "matched": false, - "mode": "miss", - "decision": "SKILL", - "slug": slug, - "reason": "slug_not_in_kb", - })); - } - Ok(json!({ - "matched": true, - "mode": "routed", - "decision": "SKILL", - "backend": opt_text(args, "backend").unwrap_or("llm"), - "slug": slug, - "skill": hit.get("skill").cloned().unwrap_or(Value::Null), - "resource": hit.get("resource").cloned().unwrap_or(Value::Null), - "llm_free": hit.get("llm_free").cloned().unwrap_or(Value::Bool(false)), - "confidence": 0.85, - "needs_llm": false, - })) -} - -/// Compile policy from successful episode skill selections (Policy Compilation). -pub fn compile_policy(args: &Value) -> Result { - let root = memory_root(args); - let mem_arg = opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR); - let _ = memory::memory_ensure(&json!({ "memory_dir": mem_arg })); - let min_evidence = opt_i64(args, "min_evidence", opt_i64(args, "improve_every", 3)); - let listed = memory::list_episodes(&json!({ - "memory_dir": mem_arg, - "status": "success", - "limit": 500, - }))?; - let eps = listed - .get("episodes") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - - // task_hash → (slug → count, sample task, skill path) - let mut by_hash: HashMap> = HashMap::new(); - for e in &eps { - let id = e.get("id").and_then(|v| v.as_str()).unwrap_or(""); - if id.is_empty() { - continue; - } - let full = memory::get_episode(&json!({ - "memory_dir": mem_arg, - "id": id, - }))?; - if full.is_null() { - continue; - } - let src = full.get("source").and_then(|v| v.as_str()).unwrap_or(""); - let skill = extract_fm(src, "skill").unwrap_or_default(); - if skill.is_empty() || skill == "none" || skill == "null" { - continue; - } - let task_hash = extract_fm(src, "task_hash") - .or_else(|| e.get("task_hash").and_then(|v| v.as_str()).map(|s| s.to_string())) - .unwrap_or_default(); - if task_hash.is_empty() { - continue; - } - let task = full - .get("task") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let slug = extract_fm(src, "slug") - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| goal_slug_str(&task)); - // Prefer skill path as key when it looks like a path; else slug. - let key = if skill.contains('/') || skill.ends_with(".md") { - skill.clone() - } else { - slug.clone() - }; - let entry = by_hash.entry(task_hash).or_default(); - let cell = entry.entry(key).or_insert((0, task, skill)); - cell.0 += 1; - } - - let mut rules: Vec = Vec::new(); - for (task_hash, skills) in by_hash { - let Some((skill_key, (count, task, skill_path))) = - skills.into_iter().max_by_key(|(_, (c, _, _))| *c) - else { - continue; - }; - if count < min_evidence { - continue; - } - let slug = if skill_key.contains('/') { - Path::new(&skill_key) - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or(&skill_key) - .trim_end_matches(".mq") - .to_string() - } else { - skill_key - }; - let confidence = (count as f64 / (count as f64 + 1.0)).min(0.99); - rules.push(PolicyRule { - task_hash, - slug, - skill: skill_path, - task, - count, - confidence, - }); - } - rules.sort_by(|a, b| b.count.cmp(&a.count)); - - if rules.is_empty() && !opt_bool(args, "force", false) { - return Ok(json!({ - "ok": false, - "compiled": false, - "reason": "insufficient_stable_mappings", - "min_evidence": min_evidence, - })); - } - - let path = write_policy(&root, &rules)?; - Ok(json!({ - "ok": true, - "compiled": true, - "path": path.to_string_lossy(), - "rules": rules.len() as i64, - "min_evidence": min_evidence, - })) -} - -fn extract_fm(source: &str, key: &str) -> Option { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return None; - } - let prefix = format!("{key}:"); - for line in lines.iter().skip(1) { - let t = line.trim(); - if t == "---" { - break; - } - if let Some(rest) = t.strip_prefix(&prefix) { - return Some(rest.trim().trim_matches('"').to_string()); - } - } - None -} - -/// Learn gate for policy: compile when enough skill-tagged episodes exist. -pub fn maybe_compile_policy(args: &Value) -> Result { - let compiled = compile_policy(args)?; - Ok(json!({ - "policy_learned": compiled.get("ok").and_then(|v| v.as_bool()).unwrap_or(false), - "compile": compiled, - })) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn compile_and_route_marqdo() { - let dir = std::env::temp_dir().join(format!("marqdo-route-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let mem = dir.join("agent-memory"); - let kb = dir.join("agent-kb"); - let mem_s = mem.to_string_lossy().into_owned(); - let kb_s = kb.to_string_lossy().into_owned(); - let task = "Reply with exactly the word pong and nothing else."; - - // Seed a solidified skill via memory compile path. - for _ in 0..3 { - memory::record_episode(&json!({ - "memory_dir": mem_s, - "task": task, - "status": "ok", - "mode": "explore", - "result": "pong", - "skill": "concepts/skills/reply-with-exactly-the-word-pong-and-nothing-els.md", - "llm_calls": 1, - })) - .unwrap(); - } - let learned = memory::maybe_learn(&json!({ - "memory_dir": mem_s, - "kb_dir": kb_s, - "task": task, - "improve_every": 3, - "promote": true, - })) - .unwrap(); - assert_eq!(learned.get("learned").and_then(|v| v.as_bool()), Some(true)); - - // Tag episodes with skill path for policy mining (re-record with skill). - for _ in 0..3 { - memory::record_episode(&json!({ - "memory_dir": mem_s, - "task": task, - "status": "ok", - "mode": "compiled", - "result": "pong", - "skill": "concepts/skills/reply-with-exactly-the-word-pong-and-nothing-els.md", - "llm_calls": 0, - })) - .unwrap(); - } - - let pol = compile_policy(&json!({ - "memory_dir": mem_s, - "min_evidence": 3, - })) - .unwrap(); - assert_eq!(pol.get("ok").and_then(|v| v.as_bool()), Some(true), "{pol}"); - - let routed = route(&json!({ - "memory_dir": mem_s, - "kb_dir": kb_s, - "task": task, - "backend": "auto", - })) - .unwrap(); - assert_eq!( - routed.get("matched").and_then(|v| v.as_bool()), - Some(true), - "{routed}" - ); - assert_eq!( - routed.get("needs_llm").and_then(|v| v.as_bool()), - Some(false), - "{routed}" - ); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/plugins/agent/src/sandbox.rs b/plugins/agent/src/sandbox.rs deleted file mode 100755 index 2193aae..0000000 --- a/plugins/agent/src/sandbox.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Forward `sandbox_*` plugin calls to host_query (CoW lives in the host). - -use super::{ - host_query_json_args, parse_args, set_err, set_out, -}; -use std::os::raw::c_char; - -fn forward( - query_name: &str, - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> i32 { - let v = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("{query_name}: {e}")); - return 1; - } - }; - match host_query_json_args(query_name, &v) { - Ok(j) => { - set_out(out_json, &j.to_string()); - 0 - } - Err(e) => { - set_err(err_msg, &e); - 1 - } - } -} - -macro_rules! sandbox_ffi { - ($fn_name:ident, $query:expr) => { - pub unsafe extern "C" fn $fn_name( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, - ) -> i32 { - forward($query, args_json, out_json, err_msg) - } - }; -} - -sandbox_ffi!(sandbox_open, "sandbox_open"); -sandbox_ffi!(sandbox_write, "sandbox_write"); -sandbox_ffi!(sandbox_read, "sandbox_read"); -sandbox_ffi!(sandbox_remove, "sandbox_remove"); -sandbox_ffi!(sandbox_diff, "sandbox_diff"); -sandbox_ffi!(sandbox_commit, "sandbox_commit"); -sandbox_ffi!(sandbox_discard, "sandbox_discard"); -sandbox_ffi!(sandbox_inspect, "sandbox_inspect"); -sandbox_ffi!(sandbox_run, "sandbox_run"); diff --git a/plugins/agent/src/tools.rs b/plugins/agent/src/tools.rs deleted file mode 100755 index b351320..0000000 --- a/plugins/agent/src/tools.rs +++ /dev/null @@ -1,794 +0,0 @@ -//! ToolSpecV1 registry + call validation (M-A2). -//! Discovery → schema validate → authorize. Execution of Marqdo `##` stays in subtask; -//! this module never evals model-supplied code. - -use std::collections::HashMap; -use std::sync::{Mutex, OnceLock}; - -use serde_json::{json, Map, Value}; - -fn registry() -> &'static Mutex> { - static REG: OnceLock>> = OnceLock::new(); - REG.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) -} - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - opt_text(args, key).ok_or_else(|| format!("missing text `{key}`")) -} - -/// Supported JSON Schema subset for tool input (reject unsupported constructs). -fn validate_schema_subset(schema: &Value) -> Result<(), String> { - let obj = schema - .as_object() - .ok_or_else(|| "input_schema must be object".to_string())?; - let ty = obj - .get("type") - .and_then(|v| v.as_str()) - .unwrap_or("object"); - if ty != "object" { - return Err(format!("unsupported root type={ty}; only object")); - } - if let Some(props) = obj.get("properties") { - let props = props - .as_object() - .ok_or_else(|| "properties must be object".to_string())?; - for (name, prop) in props { - let p = prop - .as_object() - .ok_or_else(|| format!("property {name} must be object"))?; - let pty = p.get("type").and_then(|v| v.as_str()).unwrap_or("string"); - match pty { - "string" | "integer" | "number" | "boolean" | "array" | "object" => {} - other => { - return Err(format!( - "unsupported property type {other} for {name}; refuse register" - )) - } - } - // Reject constructs we do not implement. - for banned in ["$ref", "oneOf", "anyOf", "allOf", "not", "if", "then", "else"] { - if p.contains_key(banned) { - return Err(format!( - "unsupported schema keyword {banned} on {name}; refuse register" - )); - } - } - } - } - for banned in ["$ref", "oneOf", "anyOf", "allOf", "not", "if", "then", "else"] { - if obj.contains_key(banned) { - return Err(format!( - "unsupported schema keyword {banned}; refuse register" - )); - } - } - Ok(()) -} - -fn normalize_spec(mut spec: Value) -> Result { - let obj = spec - .as_object_mut() - .ok_or_else(|| "spec must be object".to_string())?; - obj.insert("schema".into(), json!("ToolSpecV1")); - obj.entry("schema_version".to_string()) - .or_insert(json!(1)); - let id = obj - .get("id") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| "ToolSpecV1 requires id".to_string())? - .to_string(); - obj.entry("version".to_string()).or_insert(json!("1")); - obj.entry("description".to_string()) - .or_insert(json!("")); - let input = obj - .get("input_schema") - .cloned() - .unwrap_or_else(|| json!({"type": "object", "properties": {}, "additionalProperties": false})); - validate_schema_subset(&input)?; - obj.insert("input_schema".into(), input); - obj.entry("effect".to_string()).or_insert(json!("read")); - let effect = obj.get("effect").and_then(|v| v.as_str()).unwrap_or("read"); - if !matches!(effect, "read" | "write" | "execute" | "external_write") { - return Err(format!("invalid effect={effect}")); - } - obj.entry("scopes".to_string()).or_insert(json!([])); - obj.entry("timeout_ms".to_string()).or_insert(json!(10_000)); - obj.entry("max_result_bytes".to_string()) - .or_insert(json!(65_536)); - obj.entry("idempotency".to_string()) - .or_insert(json!("safe")); - obj.entry("availability".to_string()) - .or_insert(json!("ready")); - let _ = id; - Ok(spec) -} - -fn validate_args_against_schema(schema: &Value, arguments: &Value) -> Result<(), String> { - let args = arguments - .as_object() - .ok_or_else(|| "arguments must be object".to_string())?; - let sch = schema.as_object().ok_or_else(|| "input_schema invalid".to_string())?; - let props = sch - .get("properties") - .and_then(|v| v.as_object()) - .cloned() - .unwrap_or_default(); - let additional = sch - .get("additionalProperties") - .and_then(|v| v.as_bool()) - .unwrap_or(true); - if !additional { - for key in args.keys() { - if !props.contains_key(key) { - return Err(format!("unknown argument `{key}`")); - } - } - } - if let Some(req) = sch.get("required").and_then(|v| v.as_array()) { - for r in req { - let name = r.as_str().unwrap_or(""); - if name.is_empty() { - continue; - } - if !args.contains_key(name) || args.get(name).map(|v| v.is_null()).unwrap_or(true) { - return Err(format!("missing required argument `{name}`")); - } - } - } - for (key, val) in args { - if let Some(prop) = props.get(key) { - if let Some(pty) = prop.get("type").and_then(|v| v.as_str()) { - let ok = match pty { - "string" => val.is_string(), - "integer" => val.as_i64().is_some() || val.as_u64().is_some(), - "number" => val.as_f64().is_some(), - "boolean" => val.is_boolean(), - "array" => val.is_array(), - "object" => val.is_object(), - _ => true, - }; - if !ok { - return Err(format!("argument `{key}` type mismatch (want {pty})")); - } - } - if let Some(min) = prop.get("minimum").and_then(|v| v.as_f64()) { - if let Some(n) = val.as_f64() { - if n < min { - return Err(format!("argument `{key}` below minimum {min}")); - } - } - } - if let Some(max) = prop.get("maximum").and_then(|v| v.as_f64()) { - if let Some(n) = val.as_f64() { - if n > max { - return Err(format!("argument `{key}` above maximum {max}")); - } - } - } - } - } - Ok(()) -} - -fn authorized(allowlist: Option<&Value>, tool_id: &str) -> bool { - match allowlist { - None => true, // registry-only call sites may omit; still need registered spec - Some(tools) => crate::tool_names(tools).iter().any(|n| n == tool_id), - } -} - -/// Register one ToolSpecV1 (or list). Host/trusted only — model cannot invent principal/root. -pub fn tools_register(args: &Value) -> Result { - let specs = if let Some(arr) = args.get("specs").and_then(|v| v.as_array()) { - arr.clone() - } else if args.get("spec").is_some() || args.get("id").is_some() { - let raw = args.get("spec").cloned().unwrap_or_else(|| args.clone()); - vec![raw] - } else { - return Err("tools.register requires spec or specs[]".into()); - }; - let mut registered = Vec::new(); - let mut guard = registry() - .lock() - .map_err(|_| "tools registry lock poisoned".to_string())?; - for raw in specs { - let spec = normalize_spec(raw)?; - let id = spec - .get("id") - .and_then(|v| v.as_str()) - .unwrap() - .to_string(); - guard.insert(id.clone(), spec); - registered.push(id); - } - Ok(json!({ - "ok": true, - "registered": registered, - "count": registered.len(), - })) -} - -pub fn tools_clear(args: &Value) -> Result { - let _ = args; - let mut guard = registry() - .lock() - .map_err(|_| "tools registry lock poisoned".to_string())?; - let n = guard.len(); - guard.clear(); - Ok(json!({"ok": true, "cleared": n})) -} - -pub fn tools_search(args: &Value) -> Result { - let query = opt_text(args, "query").unwrap_or("").to_ascii_lowercase(); - let allow = args.get("tools"); - let guard = registry() - .lock() - .map_err(|_| "tools registry lock poisoned".to_string())?; - let mut items = Vec::new(); - for (id, spec) in guard.iter() { - let avail = spec - .get("availability") - .and_then(|v| v.as_str()) - .unwrap_or("ready"); - let auth = authorized(allow, id); - if !auth { - // Do not leak unauthorized private connector names in search hits. - continue; - } - if !query.is_empty() { - let desc = spec - .get("description") - .and_then(|v| v.as_str()) - .unwrap_or(""); - if !id.to_ascii_lowercase().contains(&query) - && !desc.to_ascii_lowercase().contains(&query) - { - continue; - } - } - items.push(json!({ - "id": id, - "version": spec.get("version").cloned().unwrap_or(json!("1")), - "description": spec.get("description").cloned().unwrap_or(json!("")), - "effect": spec.get("effect").cloned().unwrap_or(json!("read")), - "availability": avail, - "authorized": true, - })); - } - items.sort_by(|a, b| { - let ai = a.get("id").and_then(|v| v.as_str()).unwrap_or(""); - let bi = b.get("id").and_then(|v| v.as_str()).unwrap_or(""); - ai.cmp(bi) - }); - Ok(json!({ - "ok": true, - "schema": "ToolSearchResultV1", - "schema_version": 1, - "items": items, - "count": items.len(), - })) -} - -pub fn tools_describe(args: &Value) -> Result { - let id = arg_text(args, "id")?; - let allow = args.get("tools"); - if !authorized(allow, id) { - return Ok(json!({ - "ok": false, - "found": false, - "authorized": false, - "error": { - "schema": "AgentErrorV1", - "schema_version": 1, - "code": "tool.forbidden", - "category": "forbidden", - "stage": "tool", - "message": format!("tool `{id}` not in allowlist"), - "retryable": false, - "effect_state": "none", - "recovery_action": "needs_input", - } - })); - } - let guard = registry() - .lock() - .map_err(|_| "tools registry lock poisoned".to_string())?; - match guard.get(id) { - Some(spec) => Ok(json!({ - "ok": true, - "found": true, - "authorized": true, - "spec": spec, - })), - None => Ok(json!({ - "ok": false, - "found": false, - "authorized": true, - "error": { - "schema": "AgentErrorV1", - "schema_version": 1, - "code": "tool.not_found", - "category": "capability_unavailable", - "stage": "tool", - "message": format!("tool `{id}` not registered"), - "retryable": false, - "effect_state": "none", - "recovery_action": "stop", - } - })), - } -} - -/// Validate + authorize a ToolCallV1. Does not execute side effects. -pub fn tools_prepare_call(args: &Value) -> Result { - let tool_id = arg_text(args, "tool_id") - .or_else(|_| arg_text(args, "id")) - .or_else(|_| arg_text(args, "name"))?; - let allow = args.get("tools"); - if !authorized(allow, tool_id) { - return Ok(tool_result_err( - "tool.forbidden", - "forbidden", - format!("unauthorized call to `{tool_id}`"), - false, - )); - } - let guard = registry() - .lock() - .map_err(|_| "tools registry lock poisoned".to_string())?; - let spec = match guard.get(tool_id) { - Some(s) => s.clone(), - None => { - return Ok(tool_result_err( - "tool.not_found", - "capability_unavailable", - format!("tool `{tool_id}` not registered"), - false, - )); - } - }; - drop(guard); - - let avail = spec - .get("availability") - .and_then(|v| v.as_str()) - .unwrap_or("ready"); - if avail != "ready" { - return Ok(tool_result_err( - "tool.unavailable", - "capability_unavailable", - format!("tool `{tool_id}` availability={avail}"), - false, - )); - } - - let arguments = match args.get("arguments") { - None | Some(Value::Null) => json!({}), - Some(v) => v.clone(), - }; - let schema = spec - .get("input_schema") - .cloned() - .unwrap_or_else(|| json!({"type":"object"})); - if let Err(e) = validate_args_against_schema(&schema, &arguments) { - return Ok(tool_result_err( - "tool.invalid_arguments", - "invalid_arguments", - e, - true, - )); - } - - let call_id = opt_text(args, "call_id") - .map(|s| s.to_string()) - .unwrap_or_else(|| format!("call_{}", std::process::id())); - let operation_id = opt_text(args, "operation_id") - .map(|s| s.to_string()) - .unwrap_or_else(|| format!("op_{tool_id}_{call_id}")); - let version = spec - .get("version") - .and_then(|v| v.as_str()) - .unwrap_or("1"); - let effect = spec - .get("effect") - .and_then(|v| v.as_str()) - .unwrap_or("read"); - let digest = args_digest(&arguments); - let logical_run = opt_text(args, "logical_run_id").unwrap_or("-"); - let step = opt_text(args, "step_id").unwrap_or("-"); - let idempotency_key = opt_text(args, "idempotency_key") - .map(|s| s.to_string()) - .unwrap_or_else(|| format!("{logical_run}|{step}|{tool_id}|{digest}")); - let needs_ledger = matches!(effect, "write" | "execute" | "external_write"); - - let call = json!({ - "schema": "ToolCallV1", - "schema_version": 1, - "call_id": call_id, - "tool_id": tool_id, - "tool_version": version, - "arguments": arguments, - "operation_id": operation_id, - "parent_span_id": args.get("parent_span_id").cloned().unwrap_or(Value::Null), - }); - - Ok(json!({ - "ok": true, - "status": "prepared", - "call": call, - "spec": { - "id": tool_id, - "effect": effect, - "timeout_ms": spec.get("timeout_ms").cloned().unwrap_or(json!(10000)), - "max_result_bytes": spec.get("max_result_bytes").cloned().unwrap_or(json!(65536)), - }, - "args_digest": digest, - "idempotency_key": idempotency_key, - "needs_ledger": needs_ledger, - "summary": format!("prepared authorized call to `{tool_id}`"), - })) -} - -/// Stable digest of tool arguments for effect ledger idempotency (M-A5a). -pub fn tools_args_digest(args: &Value) -> Result { - let arguments = args - .get("arguments") - .cloned() - .or_else(|| args.get("value").cloned()) - .unwrap_or_else(|| json!({})); - Ok(json!({ - "ok": true, - "args_digest": args_digest(&arguments), - })) -} - -fn args_digest(arguments: &Value) -> String { - let text = serde_json::to_string(arguments).unwrap_or_else(|_| "{}".into()); - format!("sha256-lite:{:x}", fnv1a64(&text)) -} - -fn fnv1a64(s: &str) -> u64 { - let mut h: u64 = 0xcbf29ce484222325; - for b in s.as_bytes() { - h ^= u64::from(*b); - h = h.wrapping_mul(0x100000001b3); - } - h -} - -/// True when effect_class requires EffectLedger before/after execution. -pub fn tools_needs_ledger(args: &Value) -> Result { - let effect = opt_text(args, "effect") - .or_else(|| opt_text(args, "effect_class")) - .unwrap_or("read"); - Ok(json!({ - "ok": true, - "needs_ledger": matches!(effect, "write" | "execute" | "external_write"), - "effect": effect, - })) -} - -/// Wrap a successful / failed tool execution into ToolResultV1. -pub fn tools_wrap_result(args: &Value) -> Result { - let ok = args.get("ok").and_then(|v| v.as_bool()).unwrap_or(false); - let status = opt_text(args, "status").unwrap_or(if ok { "succeeded" } else { "failed" }); - let summary = opt_text(args, "summary").unwrap_or(""); - let mut out = json!({ - "schema": "ToolResultV1", - "schema_version": 1, - "ok": ok, - "status": status, - "summary": summary, - "structured_content": args.get("structured_content").cloned().unwrap_or(Value::Null), - "resources": args.get("resources").cloned().unwrap_or_else(|| json!([])), - "citations": args.get("citations").cloned().unwrap_or_else(|| json!([])), - "error": args.get("error").cloned().unwrap_or(Value::Null), - "usage": args.get("usage").cloned().unwrap_or(Value::Null), - "truncated": args.get("truncated").and_then(|v| v.as_bool()).unwrap_or(false), - "next_cursor": args.get("next_cursor").cloned().unwrap_or(Value::Null), - "effect_receipt_ref": args.get("effect_receipt_ref").cloned().unwrap_or(Value::Null), - }); - // Truncate oversized summary into artifact hint (do not dump MB into prompt). - let max_bytes = args - .get("max_result_bytes") - .and_then(|v| v.as_u64()) - .unwrap_or(65_536) as usize; - if summary.len() > max_bytes { - if let Some(obj) = out.as_object_mut() { - obj.insert("truncated".into(), json!(true)); - obj.insert( - "summary".into(), - json!(format!( - "{}… [truncated; use resource handle]", - &summary[..max_bytes.min(summary.len())] - )), - ); - } - } - Ok(out) -} - -/// Seed the five engineering tools used by qdagent (aliases remain CALL:tool_*). -pub fn tools_register_eng_defaults(args: &Value) -> Result { - let _ = args; - let specs = eng_default_specs(); - tools_register(&json!({"specs": specs})) -} - -fn eng_default_specs() -> Vec { - vec![ - json!({ - "id": "tool_find", - "version": "1", - "description": "Engineering find via EKC (read-only)", - "input_schema": { - "type": "object", - "properties": {"query": {"type": "string"}}, - "required": ["query"], - "additionalProperties": false - }, - "effect": "read", - "scopes": ["knowledge:read"], - "availability": "ready" - }), - json!({ - "id": "tool_reuse", - "version": "1", - "description": "Engineering reuse / preflight discovery (read-only)", - "input_schema": { - "type": "object", - "properties": {"task": {"type": "string"}}, - "required": ["task"], - "additionalProperties": false - }, - "effect": "read", - "scopes": ["knowledge:read"], - "availability": "ready" - }), - json!({ - "id": "tool_bind", - "version": "1", - "description": "Bind and execute a verified knowledge artifact", - "input_schema": { - "type": "object", - "properties": { - "query": {"type": "string"}, - "policy": {"type": "string"}, - "project": {"type": "string"} - }, - "required": ["query"], - "additionalProperties": false - }, - "effect": "execute", - "scopes": ["knowledge:execute"], - "availability": "ready" - }), - json!({ - "id": "tool_verify", - "version": "1", - "description": "Run L3 knowledge verification checks", - "input_schema": { - "type": "object", - "properties": {}, - "additionalProperties": false - }, - "effect": "read", - "scopes": ["knowledge:verify"], - "availability": "ready" - }), - json!({ - "id": "tool_summarize", - "version": "1", - "description": "Summarize a Context Pack / preflight map", - "input_schema": { - "type": "object", - "properties": {"preflight": {"type": "object"}}, - "required": ["preflight"], - "additionalProperties": false - }, - "effect": "read", - "scopes": ["knowledge:read"], - "availability": "ready" - }), - ] -} - -fn tool_result_err(code: &str, category: &str, message: String, retryable: bool) -> Value { - let recovery = if category == "invalid_arguments" { - "repair_args" - } else if category == "forbidden" { - "needs_input" - } else { - "stop" - }; - json!({ - "ok": false, - "status": "failed", - "summary": message, - "schema": "ToolResultV1", - "schema_version": 1, - "structured_content": null, - "resources": [], - "citations": [], - "error": { - "schema": "AgentErrorV1", - "schema_version": 1, - "code": code, - "category": category, - "stage": "tool", - "message": message, - "retryable": retryable, - "retry_after_ms": null, - "effect_state": "none", - "recovery_action": recovery, - }, - "usage": null, - "truncated": false, - "next_cursor": null, - "effect_receipt_ref": null, - }) -} - -/// Seed stub specs from a CALL allowlist (args.tools). -pub fn seed_from_allowlist_args(args: &Value) -> Result { - let tools = args - .get("tools") - .ok_or_else(|| "tools.seed_allowlist requires tools".to_string())?; - seed_from_allowlist(tools) -} - -fn seed_from_allowlist(tools: &Value) -> Result { - let names = crate::tool_names(tools); - let mut specs = Vec::new(); - for name in names { - // Minimal stub if not already registered — CALL whitelist compatibility. - let already = { - let guard = registry() - .lock() - .map_err(|_| "tools registry lock poisoned".to_string())?; - guard.contains_key(&name) - }; - if already { - continue; - } - let mut m = Map::new(); - m.insert("id".into(), json!(name)); - m.insert("version".into(), json!("1")); - m.insert( - "description".into(), - json!(format!("Allowlist-derived tool `{name}`")), - ); - m.insert( - "input_schema".into(), - json!({"type":"object","properties":{},"additionalProperties":true}), - ); - m.insert("effect".into(), json!("execute")); - m.insert("scopes".into(), json!(["call:allowlist"])); - m.insert("availability".into(), json!("ready")); - specs.push(Value::Object(m)); - } - if specs.is_empty() { - return Ok(json!({"ok": true, "registered": [], "count": 0})); - } - tools_register(&json!({"specs": specs})) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn register_search_describe_and_forbid() { - let _ = tools_clear(&json!({})); - let reg = tools_register_eng_defaults(&json!({})).unwrap(); - assert_eq!(reg["count"], 5); - - let allow = json!(["tool_find", "tool_reuse"]); - let search = tools_search(&json!({"tools": allow, "query": "find"})).unwrap(); - assert_eq!(search["count"], 1); - assert_eq!(search["items"][0]["id"], "tool_find"); - - // Unauthorized tool must not appear. - let search2 = tools_search(&json!({"tools": allow, "query": "bind"})).unwrap(); - assert_eq!(search2["count"], 0); - - let denied = tools_describe(&json!({"id": "tool_bind", "tools": allow})).unwrap(); - assert_eq!(denied["authorized"], false); - assert_eq!(denied["ok"], false); - - let ok = tools_describe(&json!({"id": "tool_find", "tools": allow})).unwrap(); - assert_eq!(ok["found"], true); - assert_eq!(ok["spec"]["schema"], "ToolSpecV1"); - } - - #[test] - fn prepare_rejects_bad_args_and_unauthorized() { - let _ = tools_clear(&json!({})); - tools_register_eng_defaults(&json!({})).unwrap(); - let allow = json!(["tool_find"]); - - let bad = tools_prepare_call(&json!({ - "tool_id": "tool_find", - "tools": allow, - "arguments": {} - })) - .unwrap(); - assert_eq!(bad["ok"], false); - assert_eq!(bad["error"]["category"], "invalid_arguments"); - - let unauth = tools_prepare_call(&json!({ - "tool_id": "tool_bind", - "tools": allow, - "arguments": {"query": "x"} - })) - .unwrap(); - assert_eq!(unauth["ok"], false); - assert_eq!(unauth["error"]["category"], "forbidden"); - - let good = tools_prepare_call(&json!({ - "tool_id": "tool_find", - "tools": allow, - "arguments": {"query": "foo"}, - "call_id": "c1" - })) - .unwrap(); - assert_eq!(good["ok"], true); - assert_eq!(good["call"]["schema"], "ToolCallV1"); - assert_eq!(good["call"]["tool_id"], "tool_find"); - assert_eq!(good["needs_ledger"], false); - assert!(good["args_digest"].as_str().unwrap().starts_with("sha256-lite:")); - - let allow2 = json!(["tool_bind"]); - let bind = tools_prepare_call(&json!({ - "tool_id": "tool_bind", - "tools": allow2, - "arguments": {"query": "x"}, - "call_id": "c2", - "logical_run_id": "run1", - "step_id": "s1" - })) - .unwrap(); - assert_eq!(bind["ok"], true); - assert_eq!(bind["needs_ledger"], true); - assert_eq!(bind["spec"]["effect"], "execute"); - assert!(bind["idempotency_key"] - .as_str() - .unwrap() - .starts_with("run1|s1|tool_bind|")); - } - - #[test] - fn needs_ledger_only_for_mutating_effects() { - assert_eq!( - tools_needs_ledger(&json!({"effect": "read"})).unwrap()["needs_ledger"], - false - ); - assert_eq!( - tools_needs_ledger(&json!({"effect": "write"})).unwrap()["needs_ledger"], - true - ); - assert_eq!( - tools_needs_ledger(&json!({"effect": "execute"})).unwrap()["needs_ledger"], - true - ); - } - - #[test] - fn refuse_unsupported_schema_keywords() { - let err = tools_register(&json!({ - "id": "bad", - "input_schema": { - "type": "object", - "oneOf": [{"type": "object"}] - } - })); - assert!(err.is_err()); - } -} diff --git a/plugins/agent/src/workflow.rs b/plugins/agent/src/workflow.rs deleted file mode 100644 index f7d3578..0000000 --- a/plugins/agent/src/workflow.rs +++ /dev/null @@ -1,679 +0,0 @@ -//! Plugin-only durable step workflow. -//! No interpreter-frame serialization: every model/tool decision is a checkpointed -//! transition. This state machine issues actions but never executes arbitrary code. - -use std::fs::{self, OpenOptions}; -use std::path::PathBuf; -use serde_json::{json, Value}; - -use crate::{choice, parallel, resume}; - -const MAX_STEPS: usize = 128; - -struct Guard(PathBuf); -impl Drop for Guard { - fn drop(&mut self) { let _ = fs::remove_file(&self.0); } -} - -fn field<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> { - v.get(key).and_then(Value::as_str).filter(|x| !x.is_empty()) - .ok_or_else(|| format!("workflow requires text {key}")) -} - -fn safe_key(s: &str) -> bool { - !s.is_empty() && s.len() <= 100 - && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') -} - -fn storage(args: &Value) -> Result { - let rel = args.get("resume_dir").and_then(Value::as_str) - .unwrap_or(".marqdo/agent-resume"); - let path = PathBuf::from(rel); - if path.is_absolute() || path.components().any(|part| - matches!(part, std::path::Component::ParentDir | std::path::Component::Prefix(_))) - { - return Err("resume_dir must be relative with no parent traversal".into()); - } - let base = crate::host_query_json("cwd").ok() - .and_then(|v| v.as_str().map(PathBuf::from)) - .unwrap_or(std::env::current_dir().map_err(|e| e.to_string())?); - let dir = base.join(path); - fs::create_dir_all(&dir).map_err(|e| format!("workflow mkdir: {e}"))?; - Ok(dir) -} - -fn lock(args: &Value, id: &str) -> Result { - if !safe_key(id) { - return Err("workflow id must be <=100 ASCII letters, numbers, - or _".into()); - } - let path = storage(args)?.join(format!("{id}.flow-lock")); - OpenOptions::new().write(true).create_new(true).open(&path) - .map_err(|e| format!("workflow busy or stale lock; review before recovering: {e}"))?; - Ok(Guard(path)) -} - -fn checkpoint_args(args: &Value, id: &str) -> Value { - json!({"id": id, "resume_dir": args.get("resume_dir")}) -} - -fn read(args: &Value, id: &str) -> Result { - resume::resume_load(&checkpoint_args(args,id)) -} - -fn context(args: &Value) -> Value { - json!({ - "source_revision": args.get("source_revision").cloned().unwrap_or(Value::Null), - "session_id": args.get("session_id").cloned().unwrap_or(Value::Null), - "principal_ref": args.get("principal_ref").cloned().unwrap_or(Value::Null) - }) -} - -fn check_context(args: &Value, ckpt: &Value) -> bool { - ckpt["meta"]["identity"] == context(args) -} - -fn validate_steps(args: &Value) -> Result { - let steps = args.get("steps").and_then(Value::as_array) - .ok_or_else(|| "steps must be a list".to_string())?; - if steps.is_empty() || steps.len() > MAX_STEPS { - return Err("steps must contain 1..=128 items".into()); - } - let mut seen = std::collections::HashSet::new(); - for s in steps { - let id = field(s, "id")?; - if !safe_key(id) || !seen.insert(id) { - return Err("step ids must be unique safe identifiers".into()); - } - let kind = field(s, "kind")?; - if !matches!(kind, "model" | "input" | "skill" | "parallel" | "return") { - return Err(format!("unsupported step kind: {kind}")); - } - if matches!(kind, "model" | "input") { - let options = s.get("options").and_then(Value::as_array) - .ok_or_else(|| "choice step requires options list".to_string())?; - let _ = choice::parse_choice(&json!({"reply":"","options":options}))?; - if kind == "input" { let _ = field(s, "question")?; } - if kind == "model" { let _ = field(s, "prompt")?; } - } - if kind == "skill" { let _ = field(s, "skill")?; } - if kind == "parallel" && !s.get("tasks").is_some_and(Value::is_array) { - return Err("parallel step requires tasks array".into()); - } - } - // Resolve all branch targets against frozen, forward-only step IDs. - for (i, s) in steps.iter().enumerate() { - let targets = s.get("next").and_then(Value::as_str).into_iter() - .chain(s.get("routes").and_then(Value::as_object) - .into_iter().flat_map(|m| m.values().filter_map(Value::as_str))); - for target in targets { - let position = steps.iter().position(|x|x["id"]==target) - .ok_or_else(|| format!("unknown workflow target: {target}"))?; - if position <= i { - return Err("workflow routes must move forward to avoid loops".into()); - } - } - if let Some(routes)=s.get("routes").and_then(Value::as_object) { - if !matches!(s["kind"].as_str(),Some("model"|"input")) { - return Err("only choice steps may declare routes".into()); - } - for key in routes.keys() { - if !s["options"].as_array().is_some_and(|opts| - opts.iter().any(|x|x.as_str()==Some(key.as_str()))) { - return Err("route label is not a declared choice".into()); - } - } - } - } - Ok(Value::Array(steps.clone())) -} - -fn advance_cursor(step:&Value, value:&Value, steps:&[Value], current:usize)->Result { - let target=if let Some(routes)=step.get("routes").and_then(Value::as_object) { - let label=value.as_str().ok_or("routed choice must return a text label")?; - Some(routes.get(label).and_then(Value::as_str) - .ok_or("chosen option is missing a declared route")?) - } else { - step.get("next").and_then(Value::as_str) - }; - match target { - None=>Ok(current+1), - Some(name)=> { - let n=steps.iter().position(|s|s["id"]==name) - .ok_or("unknown target after checkpoint recovery")?; - if n<=current {return Err("cyclic route refused".into())} - Ok(n) - } - } -} - -fn state(ckpt: &Value) -> Result<(&Value,usize),String> { - let meta = ckpt.get("meta").ok_or("missing workflow metadata")?; - if meta.get("kind").and_then(Value::as_str) != Some("MarqdoAgentFlowV1") { - return Err("checkpoint is not a workflow".into()); - } - let index = meta.get("cursor").and_then(Value::as_u64) - .ok_or("missing workflow cursor")? as usize; - Ok((meta,index)) -} - -fn save(args: &Value, id: &str, meta: &Value, status: &str) -> Result<(),String> { - let result = resume::resume_save(&json!({ - "id": id, - "resume_dir": args.get("resume_dir"), - "checkpoint_v2": true, - "status": status, - "meta": meta, - "completed_steps": meta["completed"], - "step_id": meta["steps"].get(meta["cursor"].as_u64().unwrap_or(0) as usize) - .and_then(|x| x.get("id")).cloned().unwrap_or(Value::Null) - }))?; - if result["ok"] != true { return Err("workflow checkpoint write failed".into()); } - Ok(()) -} - -/// Register a bounded, frozen plan. Re-opening never resets a progressed plan. -pub fn open(args: &Value) -> Result { - let id = field(args,"id")?; - let _guard = lock(args,id)?; - let revision = field(args,"source_revision")?; - if revision.len()>256 { return Err("source_revision too long".into()); } - let steps = validate_steps(args)?; - let existing = read(args,id)?; - let identity = context(args); - if existing["found"] == true { - if existing["ok"] == true - && existing["meta"]["identity"] == identity - && existing["meta"]["steps"] == steps - { - return next_doc(&existing,id,true); - } - return Ok(json!({"ok":false,"status":"conflict","error":"workflow.id_or_revision_reused"})); - } - let meta = json!({ - "kind":"MarqdoAgentFlowV1", - "identity":identity, - "steps":steps, - "cursor":0, - "completed":[], - }); - save(args,id,&meta,"running")?; - Ok(json!({"ok":true,"id":id,"status":"created","cursor":0})) -} - -fn next_doc(ckpt: &Value, id: &str, reused: bool) -> Result { - let (meta,index)=state(ckpt)?; - let steps = meta["steps"].as_array().ok_or("invalid steps")?; - if index>=steps.len() { - return Ok(json!({"ok":true,"id":id,"status":"succeeded", - "cursor":index,"completed":meta["completed"],"reused":reused})); - } - let step=&steps[index]; - let status=ckpt["status"].as_str().unwrap_or("running"); - if status=="blocked" || status=="uncertain" || status=="cancelled" { - return Ok(json!({"ok":false,"id":id,"status":status, - "cursor":index,"step":step,"completed":meta["completed"], - "partial": meta.get("partial").cloned().unwrap_or(Value::Null)})); - } - // Never auto-dispatch effectful or unclassified child documents. - // Those must be executed using the existing EffectLedger policy and an - // independently verified receipt, not an arbitrary model instruction. - if (step["kind"]=="skill" || step["kind"]=="parallel") - && step["effect_class"]!="read" - { - return Ok(json!({"ok":false,"id":id,"status":"manual_review", - "cursor":index,"step":step, - "reason":"automatic child dispatch requires an explicit read-only effect class"})); - } - let waiting=match step["kind"].as_str().unwrap_or("") { - "model"=>"waiting_model", - "input"=>"waiting_input", - "skill" | "parallel"=>"ready_tool", - "return"=>"ready_return", - _=>"blocked" - }; - Ok(json!({"ok":true,"id":id,"status":waiting, - "cursor":index,"step":step,"completed":meta["completed"],"reused":reused})) -} - -/// Query the durable next action. This is non-blocking and does not invoke LLM. -pub fn next(args: &Value) -> Result { - let id=field(args,"id")?; - let ckpt=read(args,id)?; - if ckpt["ok"]!=true || !check_context(args,&ckpt) { - return Ok(json!({"ok":false,"id":id,"status":"not_found_or_mismatched"})); - } - next_doc(&ckpt,id,false) -} - -/// Read a workflow summary without advancing it or running any step. -/// The caller-supplied identity must match the checkpoint, exactly like next. -pub fn inspect(args:&Value)->Result { - let id=field(args,"id")?; - let ckpt=read(args,id)?; - if ckpt["ok"]!=true || !check_context(args,&ckpt) { - return Ok(json!({"ok":false,"id":id,"status":"not_found_or_mismatched"})); - } - let (meta,index)=state(&ckpt)?; - let steps=meta["steps"].as_array().ok_or("invalid steps")?; - let completed=meta["completed"].as_array().ok_or("invalid completed")?; - // `status` is the durable checkpoint status; `action` is what tick would - // observe next (waiting_model, waiting_input, ready_tool, ...). - let action=next_doc(&ckpt,id,false)?.get("status").cloned().unwrap_or(Value::Null); - Ok(json!({ - "ok":true,"id":id, - "status":ckpt["status"].as_str().unwrap_or("running"), - "action":action, - "cursor":index, - "total_steps":steps.len(), - "completed_steps":completed.len(), - "completed":meta["completed"], - "step":steps.get(index).cloned().unwrap_or(Value::Null), - "partial":meta.get("partial").cloned().unwrap_or(Value::Null), - "identity":meta["identity"], - "updated_at":ckpt.get("updated_at").cloned().unwrap_or(Value::Null) - })) -} - -/// List workflow checkpoints in the (host-relative) resume directory. -/// Non-workflow checkpoints and corrupt entries are omitted. When the caller -/// supplies an attested session or principal, only matching runs are returned. -pub fn list(args:&Value)->Result { - let dir=storage(args)?; - let session=args.get("session_id").and_then(Value::as_str); - let principal=args.get("principal_ref").and_then(Value::as_str); - let mut items=Vec::new(); - let rd=fs::read_dir(&dir).map_err(|e|format!("workflow list: {e}"))?; - for ent in rd.flatten() { - let path=ent.path(); - if path.extension().and_then(|x|x.to_str())!=Some("json") { continue; } - if path.file_name().and_then(|x|x.to_str()) - .map(|x|x.starts_with('.')).unwrap_or(false) { continue; } - let Ok(text)=fs::read_to_string(&path) else { continue }; - let Ok(doc)=serde_json::from_str::(&text) else { continue }; - let meta=&doc["meta"]; - if meta["kind"].as_str()!=Some("MarqdoAgentFlowV1") { continue; } - if session.is_some() && meta["identity"]["session_id"].as_str()!=session { continue; } - if principal.is_some() && meta["identity"]["principal_ref"].as_str()!=principal { continue; } - let steps=meta["steps"].as_array().map(|x|x.len()).unwrap_or(0); - let completed=meta["completed"].as_array().map(|x|x.len()).unwrap_or(0); - items.push(json!({ - "id":doc.get("id").cloned().unwrap_or(Value::Null), - "status":doc.get("status").cloned().unwrap_or(Value::Null), - "cursor":meta.get("cursor").cloned().unwrap_or(Value::Null), - "total_steps":steps, - "completed_steps":completed, - "source_revision":meta["identity"]["source_revision"], - "updated_at":doc.get("updated_at").cloned().unwrap_or(Value::Null) - })); - } - items.sort_by(|a,b| a["id"].as_str().cmp(&b["id"].as_str())); - Ok(json!({"ok":true,"items":items,"resume_dir":dir.to_string_lossy()})) -} - -/// Commit a verified result for the exact current step. All mutations are -/// serialized with a lock; a completed step cannot be committed a second time. -pub fn commit(args: &Value) -> Result { - let id=field(args,"id")?; - let _guard=lock(args,id)?; - let step_id=field(args,"step_id")?; - let ckpt=read(args,id)?; - if ckpt["ok"]!=true || !check_context(args,&ckpt) { - return Ok(json!({"ok":false,"status":"not_found_or_mismatched"})); - } - let (meta,index)=state(&ckpt)?; - let steps=meta["steps"].as_array().ok_or("invalid steps")?; - let response=args.get("response").ok_or("missing response")?; - if index>=steps.len() { - let previous = meta["completed"].as_array().ok_or("invalid completed")?; - if previous.iter().any(|x|x["step_id"]==step_id && x["value"]==*response) { - return Ok(json!({"ok":true,"status":"succeeded","reused":true})); - } - return Ok(json!({"ok":false,"status":"already_finished"})); - } - let step=&steps[index]; - if step["id"]!=step_id { - if meta["completed"].as_array().is_some_and(|list| - list.iter().any(|x|x["step_id"]==step_id && x["value"]==*response)) - { - return Ok(json!({"ok":true,"status":"already_committed","reused":true})); - } - return Ok(json!({"ok":false,"status":"step_conflict"})); - } - if ckpt["status"]!="running" { - return Ok(json!({"ok":false,"status":"blocked","reason":ckpt["status"]})); - } - let kind=field(step,"kind")?; - let value = match kind { - "model" | "input" => { - let reply = response.as_str().ok_or("model/input response must be text")?; - let valid=choice::parse_choice(&json!({"options":step["options"],"reply":reply}))?; - if valid["ok"]!=true { - return Ok(json!({"ok":false,"status":"invalid_choice", - "error":valid["error"]})); - } - valid["value"].clone() - } - "skill" => { - // A completed wait is not equivalent to a successful child process. - let exit = response.get("value").and_then(|v| v.get("code")) - .or_else(|| response.get("code")).and_then(Value::as_i64); - if response["ok"]==false || exit != Some(0) { - return Ok(json!({"ok":false, - "status":if exit.is_none() {"uncertain"} else {"failed"}, - "reason":"child process exit code zero is required before commit"})); - } - response.clone() - } - "parallel" => { - let report=if response["schema"]=="AgentParallelResultV1" { - response.clone() - } else { - parallel::report(&json!({"results":response}))? - }; - if report["ok"]!=true { - let status=if report["uncertain"].as_u64().unwrap_or(0)>0 { - "uncertain" - } else {"blocked"}; - // Save the full manifest of successful and failed siblings before - // returning. Do not run failed/unknown children automatically. - let mut frozen=meta.clone(); - frozen["partial"]=report.clone(); - save(args,id,&frozen,status)?; - return Ok(json!({"ok":false,"status":status, - "report":report,"reason":"child results retained for reconciliation"})); - } - report - } - "return" => response.clone(), - _ => return Err("invalid step kind".into()), - }; - let target=advance_cursor(step,&value,steps,index)?; - let mut new_meta=meta.clone(); - new_meta["cursor"]=json!(target); - new_meta["completed"].as_array_mut().ok_or("completed not array")? - .push(json!({"step_id":step_id,"value":value})); - let terminal=target==steps.len(); - save(args,id,&new_meta,if terminal {"succeeded"} else {"running"})?; - Ok(json!({"ok":true,"id":id, - "status":if terminal {"succeeded"} else {"advanced"}, - "cursor":target,"value":value,"reused":false})) -} - -/// Produce a plan containing only previously failed *read-only* child tasks. -/// "uncertain" children and effectful plans cannot be blindly retried. -pub fn retry_plan(args: &Value) -> Result { - let id=field(args,"id")?; - let ckpt=read(args,id)?; - if ckpt["ok"]!=true || !check_context(args,&ckpt) { - return Ok(json!({"ok":false,"status":"not_found_or_mismatched"})); - } - let (meta,index)=state(&ckpt)?; - if ckpt["status"]!="blocked" { - return Ok(json!({"ok":false,"status":"not_retryable"})); - } - let step=&meta["steps"][index]; - if step["kind"]!="parallel" || step["effect_class"]!="read" - || meta["partial"]["uncertain"].as_u64().unwrap_or(1)!=0 - { - return Ok(json!({"ok":false,"status":"manual_reconciliation_required"})); - } - let Some(items)=meta["partial"]["items"].as_array() else { - return Err("partial report has no items".into()); - }; - let Some(tasks)=step["tasks"].as_array() else { - return Err("parallel plan has no tasks".into()); - }; - if items.len()!=tasks.len() { - return Err("partial report task count mismatch".into()); - } - let mut failed=Vec::new(); - let mut indices=Vec::new(); - for (i,item) in items.iter().enumerate() { - if item["index"]!=i { - return Err("out-of-order child result index".into()); - } - if item["status"]=="failed" { - failed.push(tasks[i].clone()); - indices.push(i); - } else if item["status"]!="succeeded" { - return Ok(json!({"ok":false,"status":"manual_reconciliation_required"})); - } - } - Ok(json!({"ok":true,"status":"retry_read_only", - "id":id,"step_id":step["id"],"tasks":failed,"indices":indices})) -} - -/// Merge only the failed child slots with verified new outcomes. -/// Successful results and their order remain untouched. -pub fn retry_commit(args: &Value) -> Result { - let id=field(args,"id")?; - let _guard=lock(args,id)?; - let ckpt=read(args,id)?; - if ckpt["ok"]!=true || !check_context(args,&ckpt) { - return Ok(json!({"ok":false,"status":"not_found_or_mismatched"})); - } - let (meta,index)=state(&ckpt)?; - if ckpt["status"]!="blocked" { - return Ok(json!({"ok":false,"status":"not_retryable"})); - } - let step=&meta["steps"][index]; - if step["kind"]!="parallel" || step["effect_class"]!="read" - || meta["partial"]["uncertain"].as_u64().unwrap_or(1)!=0 - { - return Ok(json!({"ok":false,"status":"manual_reconciliation_required"})); - } - let items=meta["partial"]["items"].as_array() - .ok_or("invalid partial report")?; - let incoming=args.get("results").and_then(Value::as_array) - .ok_or("retry_commit requires results list")?; - let expected=items.iter().filter(|it|it["status"]=="failed").count(); - if incoming.len()!=expected { - return Err("retry result count differs from failed child count".into()); - } - let mut next=Vec::with_capacity(items.len()); - let mut replacement=incoming.iter(); - for item in items { - if item["status"]=="succeeded" { - next.push(item["result"].clone()); - } else if item["status"]=="failed" { - next.push(replacement.next().ok_or("missing retry result")?.clone()); - } else { - return Ok(json!({"ok":false,"status":"manual_reconciliation_required"})); - } - } - let report=parallel::report(&json!({"results":next}))?; - let mut updated=meta.clone(); - if report["ok"]==true { - let target=advance_cursor(step,&report, - updated["steps"].as_array().ok_or("steps missing")?,index)?; - updated["cursor"]=json!(target); - updated["partial"]=Value::Null; - updated["completed"].as_array_mut().ok_or("completed not list")? - .push(json!({"step_id":step["id"],"value":report})); - let finished=target==updated["steps"].as_array().ok_or("steps missing")?.len(); - save(args,id,&updated,if finished {"succeeded"} else {"running"})?; - Ok(json!({"ok":true,"status":if finished {"succeeded"} else {"advanced"}, - "cursor":target,"result":report})) - } else { - updated["partial"]=report.clone(); - save(args,id,&updated,if report["uncertain"].as_u64().unwrap_or(0)>0 { - "uncertain" } else {"blocked"})?; - Ok(json!({"ok":false,"status":"blocked","report":report})) - } -} - -pub fn cancel(args: &Value) -> Result { - let id=field(args,"id")?; - let _guard=lock(args,id)?; - let ckpt=read(args,id)?; - if ckpt["ok"]!=true || !check_context(args,&ckpt) { - return Ok(json!({"ok":false,"status":"not_found_or_mismatched"})); - } - if ckpt["status"]=="succeeded" { - return Ok(json!({"ok":false,"status":"already_finished"})); - } - let (meta,_)=state(&ckpt)?; - save(args,id,meta,"cancelled")?; - Ok(json!({"ok":true,"id":id,"status":"cancelled"})) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicU64,Ordering}; - static SEQ: AtomicU64=AtomicU64::new(0); - fn fixture()->Value { - let n=SEQ.fetch_add(1,Ordering::Relaxed); - json!({"id":format!("wf-{}-{n}",std::process::id()), - "resume_dir":format!("target/workflow-test-{}-{n}",std::process::id()), - "source_revision":"v1", - "steps":[ - {"id":"choose","kind":"model","prompt":"Choose a skill","options":["chat","office"]}, - {"id":"answer","kind":"input","question":"OK?","options":["yes","no"]}, - {"id":"end","kind":"return"} - ]}) - } - - #[test] - fn nonblocking_model_then_input_then_terminal() { - let a=fixture(); - assert_eq!(open(&a).unwrap()["status"],"created"); - assert_eq!(next(&a).unwrap()["status"],"waiting_model"); - let mut c=a.clone(); - c["step_id"]=json!("choose"); - c["response"]=json!("office"); - assert_eq!(commit(&c).unwrap()["status"],"advanced"); - assert_eq!(next(&a).unwrap()["status"],"waiting_input"); - assert_eq!(commit(&c).unwrap()["status"],"already_committed"); - c["step_id"]=json!("answer"); - c["response"]=json!("yes"); - assert_eq!(commit(&c).unwrap()["status"],"advanced"); - c["step_id"]=json!("end"); - c["response"]=json!("ok"); - assert_eq!(commit(&c).unwrap()["status"],"succeeded"); - assert_eq!(next(&a).unwrap()["status"],"succeeded"); - assert_eq!(open(&a).unwrap()["status"],"succeeded"); - } - - #[test] - fn unknown_and_write_effects_never_auto_dispatch() { - let mut a=fixture(); - a["steps"]=json!([{"id":"publish","kind":"skill","skill":"office"}]); - open(&a).unwrap(); - assert_eq!(next(&a).unwrap()["status"],"manual_review"); - } - - #[test] - fn routes_skip_unselected_skill_branches() { - let mut a=fixture(); - a["steps"]=json!([ - {"id":"decide","kind":"model","prompt":"Pick","options":["chat","office"], - "routes":{"chat":"chat_skill","office":"office_skill"}}, - {"id":"chat_skill","kind":"skill","skill":"chat","effect_class":"read","next":"done"}, - {"id":"office_skill","kind":"skill","skill":"office","effect_class":"read","next":"done"}, - {"id":"done","kind":"return"} - ]); - open(&a).unwrap(); - let mut c=a.clone(); - c["step_id"]=json!("decide"); - c["response"]=json!("office"); - assert_eq!(commit(&c).unwrap()["cursor"],2); - assert_eq!(next(&a).unwrap()["step"]["id"],"office_skill"); - c["step_id"]=json!("office_skill"); - c["response"]=json!({"ok":true,"value":{"code":0}}); - assert_eq!(commit(&c).unwrap()["cursor"],3); - assert_eq!(next(&a).unwrap()["step"]["id"],"done"); - } - - #[test] - fn source_change_conflict_and_invalid_model_choice() { - let a=fixture(); - open(&a).unwrap(); - let mut bad=a.clone(); - bad["source_revision"]=json!("v2"); - assert_eq!(next(&bad).unwrap()["status"],"not_found_or_mismatched"); - assert_eq!(open(&bad).unwrap()["status"],"conflict"); - let mut c=a.clone(); - c["step_id"]=json!("choose"); - c["response"]=json!("chat or office"); - assert_eq!(commit(&c).unwrap()["status"],"invalid_choice"); - assert_eq!(next(&a).unwrap()["status"],"waiting_model"); - } - - #[test] - fn partial_children_remain_durable_and_unknown_requires_reconciliation() { - let mut a=fixture(); - a["steps"]=json!([{"id":"batch","kind":"parallel","tasks":[{"skill":"a"},{"skill":"b"}]}]); - open(&a).unwrap(); - let mut c=a.clone(); - c["step_id"]=json!("batch"); - c["response"]=json!([ - {"ok":true,"value":{"code":0,"value":"useful"}}, - {"ok":false,"error":"connection lost"} - ]); - assert_eq!(commit(&c).unwrap()["status"],"blocked"); - let after=next(&a).unwrap(); - assert_eq!(after["status"],"blocked"); - assert_eq!(after["partial"]["succeeded"],1); - assert_eq!(after["partial"]["failed"],1); - assert_eq!(commit(&c).unwrap()["status"],"blocked"); - } - - #[test] - fn retries_only_failed_read_only_children_without_redoing_successes() { - let mut a=fixture(); - a["steps"]=json!([{"id":"batch","kind":"parallel","effect_class":"read", - "tasks":[{"path":"a.mq.md"},{"path":"b.mq.md"}]}]); - open(&a).unwrap(); - let mut c=a.clone(); - c["step_id"]=json!("batch"); - c["response"]=json!([ - {"ok":true,"value":{"code":0,"value":"keep"}}, - {"ok":false,"error":"temporary timeout"} - ]); - assert_eq!(commit(&c).unwrap()["status"],"blocked"); - let plan=retry_plan(&a).unwrap(); - assert_eq!(plan["indices"],json!([1])); - assert_eq!(plan["tasks"].as_array().unwrap().len(),1); - let mut retry=a.clone(); - retry["results"]=json!([{"ok":true,"value":{"code":0,"value":"fixed"}}]); - assert_eq!(retry_commit(&retry).unwrap()["status"],"succeeded"); - let out=next(&a).unwrap(); - assert_eq!(out["completed"][0]["value"]["items"][0]["result"]["value"]["value"],"keep"); - assert_eq!(out["completed"][0]["value"]["items"][1]["result"]["value"]["value"],"fixed"); - } - - #[test] - fn inspect_and_list_are_read_only_and_session_scoped() { - let mut a=fixture(); - a["session_id"]=json!("s1"); - a["principal_ref"]=json!("u1"); - open(&a).unwrap(); - let seen=inspect(&a).unwrap(); - assert_eq!(seen["status"],"running"); - assert_eq!(seen["action"],"waiting_model"); - assert_eq!(seen["total_steps"],3); - assert_eq!(seen["completed_steps"],0); - assert_eq!(seen["step"]["id"],"choose"); - // Inspection must not consume the current step. - assert_eq!(next(&a).unwrap()["status"],"waiting_model"); - let listed=list(&a).unwrap(); - assert!(listed["items"].as_array().unwrap() - .iter().any(|x|x["id"]==a["id"])); - let mut other=a.clone(); - other["session_id"]=json!("s2"); - assert_eq!(inspect(&other).unwrap()["status"],"not_found_or_mismatched"); - assert!(list(&other).unwrap()["items"].as_array().unwrap().is_empty()); - } - - #[test] - fn explicit_cancel_stops_future_commits() { - let a=fixture(); - open(&a).unwrap(); - assert_eq!(cancel(&a).unwrap()["status"],"cancelled"); - let mut c=a.clone(); - c["step_id"]=json!("choose"); - c["response"]=json!("chat"); - assert_eq!(commit(&c).unwrap()["status"],"blocked"); - } -} diff --git a/plugins/demo/Cargo.toml b/plugins/demo/Cargo.toml deleted file mode 100755 index 4ddeb80..0000000 --- a/plugins/demo/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "marqdo_plugin_demo" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -description = "Demo Marqdo ABI v1 plugin (cdylib)" -publish = false - -[lib] -name = "demo" -crate-type = ["cdylib"] - -[dependencies] -marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" } -serde_json = "1" diff --git a/plugins/demo/src/lib.rs b/plugins/demo/src/lib.rs deleted file mode 100755 index 241aa1b..0000000 --- a/plugins/demo/src/lib.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Demo Marqdo plugin (C ABI v1). Registers `demo_add` and `demo_echo`. - -use std::ffi::CStr; -use std::os::raw::{c_char, c_int}; - -use marqdo_plugin_sdk::*; - - -unsafe extern "C" fn demo_add( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - if args_json.is_null() { - set_err(err_msg, "demo_add: null args"); - return 1; - } - let s = match CStr::from_ptr(args_json).to_str() { - Ok(s) => s, - Err(_) => { - set_err(err_msg, "demo_add: args not utf-8"); - return 1; - } - }; - let v: serde_json::Value = match serde_json::from_str(s) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("demo_add: {e}")); - return 1; - } - }; - let a = v.get("a").and_then(|x| x.as_i64()).unwrap_or(0); - let b = v.get("b").and_then(|x| x.as_i64()).unwrap_or(0); - set_out(out_json, &(a + b).to_string()); - 0 -} - -unsafe extern "C" fn demo_echo( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - if args_json.is_null() { - set_err(err_msg, "demo_echo: null args"); - return 1; - } - let s = match CStr::from_ptr(args_json).to_str() { - Ok(s) => s, - Err(_) => { - set_err(err_msg, "demo_echo: args not utf-8"); - return 1; - } - }; - let v: serde_json::Value = match serde_json::from_str(s) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("demo_echo: {e}")); - return 1; - } - }; - let text = v - .get("text") - .and_then(|x| x.as_str()) - .unwrap_or(""); - let out = serde_json::Value::String(text.to_string()).to_string(); - set_out(out_json, &out); - 0 -} - -marqdo_plugin!(1, [ - ("demo_add", "a,b", demo_add), - ("demo_echo", "text", demo_echo), -]); diff --git a/plugins/engineering/Cargo.toml b/plugins/engineering/Cargo.toml deleted file mode 100755 index 4f8142b..0000000 --- a/plugins/engineering/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "marqdo_plugin_engineering" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -description = "OS, authenticated service and archive boundaries for executable Marqdo engineering handbooks" -publish = false - -[lib] -name = "engineering" -crate-type = ["cdylib", "rlib"] - -[dependencies] -marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" } -serde_json = "1" -ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"] } -sha2 = "=0.10.9" -hmac = "=0.12.1" -chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } -zip = { version = "=0.6.6", default-features = false, features = ["deflate"] } -libc = "0.2" -flate2 = "1" -base64 = "0.22" - -# Reuse the real compiler for source analysis; no second syntax recognizer. -marqdo = { path = "../.." } diff --git a/plugins/engineering/src/lib.rs b/plugins/engineering/src/lib.rs deleted file mode 100755 index 50ac2ff..0000000 --- a/plugins/engineering/src/lib.rs +++ /dev/null @@ -1,633 +0,0 @@ -//! Native boundaries for executable engineering documents. Business ordering, -//! version decisions and ordinary file reads/writes belong in .mq.md. -//! No Python interpreter, generated shell program or secret-valued tool result. -use std::{ - collections::BTreeMap, - ffi::CStr, - fs::{self, File}, - io::{Read, Write}, - os::raw::{c_char, c_int}, - path::{Component, Path, PathBuf}, - process::{Command, Stdio}, - sync::mpsc, - thread, - time::{Duration, Instant}, -}; -use hmac::{Hmac, Mac}; -use marqdo_plugin_sdk::*; -use sha2::{Digest, Sha256}; -use serde_json::{json, Value}; - -type Answer = Result; -const OUTPUT: usize = 256 * 1024; -const HTTP_MAX: u64 = 16 * 1024 * 1024; -fn field<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> { - v.get(key).and_then(Value::as_str).ok_or_else(|| format!("missing text field {key}")) -} -fn hash(b: &[u8]) -> String { hex(&Sha256::digest(b)) } -fn hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() } -fn read_bounded(mut r: impl Read, max: u64) -> Result, String> { - let mut b = Vec::new(); - r.by_ref().take(max + 1).read_to_end(&mut b).map_err(|e| format!("read failed ({:?})",e.kind()))?; - if b.len() as u64 > max { return Err("bounded input limit exceeded".into()); } - Ok(b) -} -fn strip_verbatim(path: &Path) -> &Path { - path.strip_prefix(r"\\?\").unwrap_or(path) -} - -fn scoped(root: &Path, relative: &str) -> Result { - let p = root.join(relative).canonicalize().map_err(|_| "path does not exist")?; - if p.starts_with(root) || strip_verbatim(&p).starts_with(strip_verbatim(root)) { - return Ok(p); - } - Err("artifact path escapes the selected root".into()) -} -fn homes(root: &Path) -> Vec { - let mut out = Vec::new(); - for key in ["MARQDO_RELEASE_CREDENTIAL_HOME", "USERPROFILE", "HOME"] { - if let Some(s) = std::env::var_os(key) { out.push(PathBuf::from(s)); } - } - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt; - for p in std::iter::once(root).chain(root.ancestors().skip(1)) { - if p.join(".git").exists() { - if let Ok(m) = p.metadata() { - unsafe { - let mut entry: libc::passwd = std::mem::zeroed(); - let mut result = std::ptr::null_mut(); - let mut buf = vec![0u8; 32768]; - if libc::getpwuid_r(m.uid(), &mut entry, buf.as_mut_ptr().cast(), buf.len(), &mut result) == 0 - && !result.is_null() && !entry.pw_dir.is_null() { - out.push(PathBuf::from(CStr::from_ptr(entry.pw_dir).to_string_lossy().into_owned())); - } - } - } - } - } - } - out.dedup(); - out -} -fn redact(mut text: String, private: &[String]) -> String { - for token in private.iter().filter(|s| !s.is_empty()) { text = text.replace(token, ""); } - for (k, v) in std::env::vars() { - if v.len() >= 8 && ["TOKEN", "SECRET", "PASSWORD", "ACCESS_KEY"].iter().any(|x| k.contains(x)) { - text = text.replace(&v, ""); - } - } - text -} -struct Output { code: i32, stdout: String, stderr: String, timed_out: bool, truncated: bool } -fn pipe(mut input: impl Read + Send + 'static, limit: usize) -> mpsc::Receiver<(Vec, bool)> { - let (send, recv) = mpsc::channel(); - thread::spawn(move || { - let mut buf = Vec::new(); let mut part = [0u8; 8192]; let mut truncated = false; - while let Ok(n) = input.read(&mut part) { - if n == 0 { break; } - let keep = (limit - buf.len()).min(n); - buf.extend_from_slice(&part[..keep]); truncated |= keep < n; - } - let _ = send.send((buf, truncated)); - }); - recv -} -fn execute(root: &Path, argv: &[String], input: Option, env: &BTreeMap, - timeout_ms: u64, max_output: usize) -> Result { - if argv.is_empty() || argv[0].is_empty() { return Err("argv must not be empty".into()); } - if !(1..=3_600_000).contains(&timeout_ms) || !(1..=16_777_216).contains(&max_output) { - return Err("timeout/output limit outside supported range".into()); - } - let mut cmd = Command::new(&argv[0]); - cmd.args(&argv[1..]).current_dir(root).envs(env) - .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); - #[cfg(unix)] { - use std::os::unix::process::CommandExt; - unsafe { cmd.pre_exec(|| { - if libc::setpgid(0, 0) != 0 { return Err(std::io::Error::last_os_error()); } - Ok(()) - }); } - } - let mut child = cmd.spawn().map_err(|_| format!("cannot start {}", argv[0]))?; - let stdout = pipe(child.stdout.take().unwrap(), max_output); - let stderr = pipe(child.stderr.take().unwrap(), max_output); - let mut stdin = child.stdin.take().unwrap(); - thread::spawn(move || { if let Some(text) = input { let _ = stdin.write_all(text.as_bytes()); } }); - let started = Instant::now(); let mut timed_out = false; - let code = loop { - match child.try_wait().map_err(|_| "cannot observe process")? { - Some(status) => break status.code().unwrap_or(1), - None if started.elapsed() >= Duration::from_millis(timeout_ms) => { - timed_out = true; - #[cfg(unix)] unsafe { libc::kill(-(child.id() as i32), libc::SIGKILL); } - #[cfg(windows)] { let _ = Command::new("taskkill").args(["/PID", &child.id().to_string(), "/T", "/F"]).output(); } - let _ = child.kill(); let _ = child.wait(); break 124; - } - None => thread::sleep(Duration::from_millis(10)), - } - }; - // Descendants retaining inherited pipes must not prevent a bounded return. - let (out, out_clip) = stdout.recv_timeout(Duration::from_secs(1)).unwrap_or((Vec::new(), true)); - let (err, err_clip) = stderr.recv_timeout(Duration::from_secs(1)).unwrap_or((Vec::new(), true)); - Ok(Output { code, stdout: String::from_utf8_lossy(&out).into(), stderr: String::from_utf8_lossy(&err).into(), - timed_out, truncated: out_clip || err_clip }) -} -fn github_token(root: &Path) -> Option { - for key in ["GH_TOKEN", "GITHUB_TOKEN"] { - if let Ok(s) = std::env::var(key) { if !s.is_empty() { return Some(s); } } - } - let args = ["git", "-c", &format!("safe.directory={}", root.display()), "credential", "fill"] - .into_iter().map(str::to_string).collect::>(); - let env = BTreeMap::from([("GIT_TERMINAL_PROMPT".into(), "0".into())]); - if let Ok(p) = execute(root, &args, Some("protocol=https\nhost=github.com\n\n".into()), &env, 15_000, OUTPUT) { - if let Some(s) = p.stdout.lines().find_map(|s| s.strip_prefix("password=")) { return Some(s.into()); } - } - for home in homes(root) { - if let Ok(text) = fs::read_to_string(home.join(".config/gh/hosts.yml")) { - if let Some(s) = text.lines().find_map(|s| s.trim().strip_prefix("oauth_token:")) { - return Some(s.trim().trim_matches(['"', '\'']).into()); - } - } - } - None -} - -fn git_config(env: &mut BTreeMap, key: &str, value: String) { - let start = env.get("GIT_CONFIG_COUNT").cloned().or_else(|| std::env::var("GIT_CONFIG_COUNT").ok()) - .and_then(|s| s.parse::().ok()).unwrap_or(0); - env.insert(format!("GIT_CONFIG_KEY_{start}"),key.into()); - env.insert(format!("GIT_CONFIG_VALUE_{start}"),value); - env.insert("GIT_CONFIG_COUNT".into(),(start+1).to_string()); -} - -fn command(root: &Path, p: &Value) -> Answer { - let mut argv = p.get("argv").and_then(Value::as_array).ok_or("argv must be a list")? - .iter().map(|v| v.as_str().map(str::to_string).ok_or("argv items must be text".to_string())) - .collect::, _>>()?; - let cwd = scoped(root, p.get("cwd").and_then(Value::as_str).unwrap_or("."))?; - let mut env = BTreeMap::new(); let mut private = Vec::new(); - // Trust only the explicitly selected workspace, only in this child tree. - // Cargo/Go VCS probes inherit the same scoped Git metadata access. - git_config(&mut env,"safe.directory",root.display().to_string()); - let exe = argv.first().and_then(|s| Path::new(s).file_stem()).and_then(|s| s.to_str()).unwrap_or(""); - if ["bash", "sh", "pwsh", "powershell"].contains(&exe) && argv.iter().any(|s| ["-c", "-Command", "-EncodedCommand"].contains(&s.as_str())) { - return Err("use argument vectors or maintained external scripts, not generated shell programs".into()); - } - if exe == "git" { - if argv.iter().any(|s| ["--force", "-f", "--force-with-lease", "--no-verify"].contains(&s.as_str()) || s.starts_with("--force=")) { - return Err("forced Git updates and hook bypass are forbidden".into()); - } - argv.splice(1..1, ["-c".into(), format!("safe.directory={}", cwd.display())]); - env.insert("GIT_TERMINAL_PROMPT".into(), "0".into()); - if argv.iter().any(|s| ["fetch", "push", "ls-remote"].contains(&s.as_str())) { - if let Some(token) = github_token(root) { - // URL-scoped headers stay in the child environment, not argv. - let auth = format!("Authorization: Basic {}", base64(format!("x-access-token:{token}").as_bytes())); - for url in ["https://proxy.cflmy.top/github.com/", "https://github.com/"] { - git_config(&mut env,&format!("http.{url}.extraheader"),auth.clone()); - } - private.push(token); private.push(auth); - argv.splice(1..1, ["-c".into(), "http.version=HTTP/1.1".into(), "-c".into(), "http.postBuffer=524288000".into()]); - } - } - } - if let Some(e) = p.get("env").and_then(Value::as_object) { - for (k, v) in e { env.insert(k.clone(), v.as_str().ok_or("env values must be text")?.into()); } - } - // Child Git trace output could expose internally attached authentication. - for key in ["GIT_TRACE", "GIT_TRACE_CURL", "GIT_CURL_VERBOSE"] { env.insert(key.into(), "0".into()); } - let timeout = p.get("timeout_ms").and_then(Value::as_u64) - .unwrap_or_else(|| p.get("timeout").and_then(Value::as_u64).unwrap_or(120) * 1000); - let max = p.get("max_output").and_then(Value::as_u64).unwrap_or(OUTPUT as u64) as usize; - let out = execute(&cwd, &argv, p.get("stdin").and_then(Value::as_str).map(str::to_string), &env, timeout, max)?; - Ok(json!({"code":out.code,"stdout":redact(out.stdout,&private),"stderr":redact(out.stderr,&private), - "timed_out":out.timed_out,"truncated":out.truncated})) -} -fn http_json(root: &Path, p: &Value) -> Answer { - let path = field(p, "path")?; - if !path.starts_with("/repos/cflmy/marqdo/") || path.contains("..") { return Err("GitHub path is outside the project".into()); } - let method = p.get("method").and_then(Value::as_str).unwrap_or("GET"); - if !["GET", "PATCH", "POST"].contains(&method) { return Err("unsupported GitHub method".into()); } - let bases = std::env::var("MARQDO_RELEASE_API_BASE").map(|s| vec![s]) - .unwrap_or_else(|_| vec!["https://proxy.cflmy.top/api.github.com".into(), "https://api.github.com".into()]); - let token = github_token(root); - for (i, base) in bases.iter().enumerate() { - let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(35)).build(); - let url = format!("{}{path}", base.trim_end_matches('/')); - let mut req = agent.request(method, &url).set("Accept", "application/vnd.github+json") - .set("User-Agent", "marqdo-engineering/1").set("X-GitHub-Api-Version", "2022-11-28"); - if let Some(token) = &token { req = req.set("Authorization", &format!("Bearer {token}")); } - let response = if let Some(body) = p.get("data").filter(|v| !v.is_null()) { - req.set("Content-Type", "application/json").send_string(&body.to_string()) - } else { req.call() }; - match response { - Ok(r) => { - let body = read_bounded(r.into_reader(), HTTP_MAX) - .and_then(|bytes| serde_json::from_slice(&bytes).map_err(|_| "GitHub response is not JSON".into())); - match body { - Ok(value) => return Ok(value), - Err(_) if method != "POST" && i + 1 < bases.len() => continue, - Err(message) => return Err(message), - } - } - Err(ureq::Error::Status(404,_)) if p.get("missing").and_then(Value::as_bool).unwrap_or(false) => return Ok(Value::Null), - Err(ureq::Error::Status(code,_)) => { - if method == "POST" || i + 1 == bases.len() || ![429,500,502,503,504].contains(&code) { - return Err(format!("GitHub HTTP {code}")); - } - } - Err(_) if method == "POST" || i + 1 == bases.len() => return Err("GitHub network request failed; uncertain mutations are not replayed".into()), - Err(_) => {} - } - } - Err("GitHub request failed after proxy and direct routes".into()) -} -fn archive(root: &Path, p: &Value) -> Answer { - let path = scoped(root, field(p,"path")?)?; - let file = File::open(path).map_err(|_|"cannot open archive")?; - let mut zip = zip::ZipArchive::new(file).map_err(|_|"invalid ZIP")?; - if zip.len() > 100000 { return Err("ZIP has too many entries".into()); } - let mut seen=std::collections::HashSet::new(); - let mut entries = Vec::new(); let mut metadata = serde_json::Map::new(); let mut total = 0u64; let mut actual = 0u64; - for i in 0..zip.len() { - let mut f = zip.by_index(i).map_err(|_|"cannot read ZIP entry")?; - let name = f.name().replace('\\', "/"); - if !seen.insert(name.clone()) || name.as_bytes().get(1)==Some(&b':') {return Err("duplicate or drive-qualified ZIP path".into());} - if Path::new(&name).components().any(|c| matches!(c, Component::ParentDir | Component::RootDir | Component::Prefix(_))) { - return Err("unsafe ZIP path".into()); - } - if f.unix_mode().is_some_and(|m|m & 0o170000 == 0o120000) { return Err("ZIP symlink is not supported".into()); } - total = total.checked_add(f.size()).ok_or("ZIP expansion overflow")?; - if total > 2 * 1024 * 1024 * 1024 { return Err("ZIP expands beyond 2 GiB".into()); } - let mut selected = Vec::new(); - let keep = ["VERSION","ext/VERSION","Cargo.toml","extension/package.json"].contains(&name.as_str()); - let mut buf=[0u8;65536]; - loop { - let n=f.read(&mut buf).map_err(|_|"ZIP content/CRC validation failed")?; - if n==0 {break;} - actual = actual.checked_add(n as u64).ok_or("ZIP expansion overflow")?; - if actual > 2 * 1024 * 1024 * 1024 { return Err("ZIP expands beyond 2 GiB".into()); } - if keep && selected.len()<16384 {selected.extend_from_slice(&buf[..n.min(16384-selected.len())]);} - } - if keep { metadata.insert(name.clone(),json!(String::from_utf8(selected).map_err(|_|"ZIP metadata is not UTF-8")?)); } - entries.push(name); - } - Ok(json!({"entries":entries,"metadata":metadata})) -} -fn hmac(key:&[u8], data:&str)->Vec { - let mut mac=Hmac::::new_from_slice(key).expect("HMAC accepts all key lengths"); - mac.update(data.as_bytes());mac.finalize().into_bytes().to_vec() -} -fn r2_settings(root:&Path)->Result,String> { - let mut settings=std::env::vars().filter(|(k,_)|k.starts_with("R2_")).collect::>(); - for home in homes(root) { - if let Ok(text)=fs::read_to_string(home.join(".marqdo/r2.env")) { - for line in text.lines().map(str::trim).filter(|s|!s.starts_with('#')) { - if let Some((k,v))=line.split_once('=') {settings.entry(k.trim().into()).or_insert_with(||v.trim().trim_matches(['\'','"']).into());} - } - } - } - for k in ["R2_ENDPOINT","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY"] { - if settings.get(k).map_or(true, String::is_empty) {return Err(format!("missing {k}; configure ~/.marqdo/r2.env"));} - } - Ok(settings) -} -fn r2_put(root:&Path,p:&Value)->Answer { - let s=r2_settings(root)?; - let key=field(p,"key")?; - if !key.bytes().all(|b|b.is_ascii_alphanumeric() || b"/.-_".contains(&b)) || key.contains("..") { - return Err("unsafe R2 key".into()); - } - let body=if let Some(path)=p.get("path").and_then(Value::as_str) { - read_bounded(File::open(scoped(root,path)?).map_err(|_|"cannot open upload")?,256*1024*1024)? - } else {field(p,"text")?.as_bytes().to_vec()}; - let digest=hash(&body); - if let Some(expected)=p.get("sha256").and_then(Value::as_str) { - if digest!=expected {return Err("upload bytes changed after verification".into());} - } - let endpoint=s["R2_ENDPOINT"].trim_end_matches('/'); - let host=endpoint.split_once("://").ok_or("R2 endpoint needs a scheme")?.1; - if host.contains('/') || !(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:")) { - return Err("R2 endpoint must be HTTPS (loopback HTTP is for isolated tests)".into()); - } - let uri=format!("/{}/{key}",s["R2_BUCKET"]); - let date=chrono::Utc::now();let amz=date.format("%Y%m%dT%H%M%SZ").to_string();let day=date.format("%Y%m%d").to_string(); - let region=s.get("R2_REGION").map(String::as_str).unwrap_or("auto"); - let mime=if key.ends_with("/VERSION"){"text/plain; charset=utf-8"}else{"application/zip"}; - let headers=format!("content-type:{mime}\nhost:{host}\nx-amz-content-sha256:{digest}\nx-amz-date:{amz}\n"); - let signed="content-type;host;x-amz-content-sha256;x-amz-date"; - let canonical=format!("PUT\n{uri}\n\n{headers}\n{signed}\n{digest}"); - let scope=format!("{day}/{region}/s3/aws4_request"); - let string=format!("AWS4-HMAC-SHA256\n{amz}\n{scope}\n{}",hash(canonical.as_bytes())); - let k=hmac(format!("AWS4{}",s["R2_SECRET_ACCESS_KEY"]).as_bytes(),&day); - let k=hmac(&k,region);let k=hmac(&k,"s3");let k=hmac(&k,"aws4_request"); - let auth=format!("AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed}, Signature={}",s["R2_ACCESS_KEY_ID"],hex(&hmac(&k,&string))); - let response=ureq::AgentBuilder::new().timeout(Duration::from_secs(180)).build() - .put(&format!("{endpoint}{uri}")).set("Content-Type",mime).set("x-amz-content-sha256",&digest) - .set("x-amz-date",&amz).set("Authorization",&auth).send_bytes(&body); - match response { - Ok(r) if [200,201].contains(&r.status()) => Ok(json!({"key":key,"sha256":digest,"size":body.len()})), - Ok(r)=>Err(format!("R2 HTTP {}",r.status())), - Err(ureq::Error::Status(code,_))=>Err(format!("R2 HTTP {code}")), - Err(_)=>Err("R2 upload failed or timed out; verify before retrying".into()) - } -} - -fn git_inspect(root:&Path)->Answer { - if !root.join(".git").exists() {return Err("inspect requires a Git checkout".into());} - let query=|args:&[&str]|->Result{ - let argv=std::iter::once("git").chain(args.iter().copied()).map(|s|json!(s)).collect::>(); - let out=command(root,&json!({"argv":argv}))?; - if out["code"]!=0 {return Err("Git metadata query failed".into());} - Ok(out["stdout"].as_str().unwrap_or("").trim().into()) - }; - Ok(json!({"root":root.display().to_string(),"branch":query(&["branch","--show-current"])?, - "commit":query(&["rev-parse","HEAD"])?,"changes":query(&["status","--porcelain"])?, - "tags":query(&["tag","--list"])?.lines().collect::>(), - "extension_on_main":query(&["ls-files","vscode-extension"])?, - "origin":query(&["remote","get-url","origin"])?})) -} -fn base64(bytes:&[u8])->String { - const C:&[u8]=b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut out=String::new(); - for part in bytes.chunks(3) { - let a=part[0] as usize;let b=*part.get(1).unwrap_or(&0) as usize;let c=*part.get(2).unwrap_or(&0) as usize; - out.push(C[a>>2] as char);out.push(C[((a&3)<<4)|(b>>4)] as char); - out.push(if part.len()>1 {C[((b&15)<<2)|(c>>6)] as char}else{'='}); - out.push(if part.len()>2 {C[c&63] as char}else{'='}); - } - out -} - - - -fn expression(e:&marqdo::ast::Expr)->Option { - use marqdo::ast::{Expr,Literal,InterpPart,UnaryOp,BinaryOp,IndexKey}; - Some(match e { - Expr::Literal(Literal::None)=>"None".into(), - Expr::Literal(Literal::Bool(v))=>if *v{"True".into()}else{"False".into()}, - Expr::Literal(Literal::Int(v))=>v.to_string(), - Expr::Literal(Literal::Num(v))=>{let s=v.to_string();if s.contains('.')||s.contains('e')||s.contains('E'){s}else{format!("{s}.0")}}, - Expr::Literal(Literal::Text(v))=>{ - if v.contains('`'){return None;} serde_json::to_string(v).ok()? - }, - Expr::Var(v)=>format!("`{v}`"), - Expr::Interp(parts)=>{ - let mut text=String::new(); - for p in parts {match p { - InterpPart::Lit(v)=>{if v.contains('`'){return None;}text.push_str(v);}, - InterpPart::Var(v)=>text.push_str(&format!("`{v}`")), - _=>return None - }} - serde_json::to_string(&text).ok()? - }, - Expr::Unary{op,expr}=>match op {UnaryOp::Neg=>format!("-{}",expression(expr)?),UnaryOp::Not=>format!("(not {})",expression(expr)?)}, - Expr::Binary{op,left,right}=>format!("({} {} {})",expression(left)?,match op { - BinaryOp::Add=>"+",BinaryOp::Sub=>"-",BinaryOp::Mul=>"*",BinaryOp::Div=>"/", - BinaryOp::Eq=>"==",BinaryOp::Ne=>"!=",BinaryOp::Lt=>"<",BinaryOp::Le=>"<=", - BinaryOp::Gt=>">",BinaryOp::Ge=>">=",BinaryOp::And=>"and",BinaryOp::Or=>"or"},expression(right)?), - Expr::Call(call)=>call_source(call,false)?, - Expr::List(items)=>format!("[{}]",items.iter().map(expression).collect::>>()?.join(", ")), - // Dynamic map construction is deliberately not emitted as an alternate - // author DSL: keep its real bound GFM table at the structural boundary. - Expr::Map(_)|Expr::Formula(_)|Expr::Code(_)=>return None, - Expr::Index{base,label}=>format!("access({}, {})",expression(base)?,match label { - IndexKey::Lit(v)=>serde_json::to_string(v).ok()?,IndexKey::Var(v)=>format!("`{v}`")}), - Expr::Occluded{label,payload}=>format!("[{}]({})",label,payload.as_deref().map(expression).transpose_option()?), - }) -} -trait OptionalText {fn transpose_option(self)->Option;} -impl OptionalText for Option> { - fn transpose_option(self)->Option{match self{None=>Some(String::new()),Some(v)=>v}} -} -fn call_source(call:&marqdo::ast::CallExpr,statement:bool)->Option { - use marqdo::ast::Arg; - let call=call.with_modifiers_expanded().ok()?; - let target=if let Some(path)=&call.path{path.join(".")} - else if let Some(recv)=&call.receiver{format!("`{recv}`.{}",call.callee)} - else{call.callee.clone()}; - let args=call.args.iter().map(|a|match a { - Arg::Named{name,value}=>Some(format!("{name}={}",expression(value)?)), - Arg::Positional(value)=>expression(value) - }).collect::>>()?; - if statement || call.receiver.is_some() { - let target=if target.contains(char::is_whitespace){format!("[{target}]")}else{target}; - Some(format!("> {target} {}",args.join(" ")).trim_end().into()) - } else { - if target.contains(char::is_whitespace){return None;} - Some(format!("{target}({})",args.join(", "))) - } -} -fn semantic_expr(e:&marqdo::ast::Expr)->Value { - use marqdo::ast::{Expr,Arg}; - match e { - Expr::Occluded{payload,..}=>payload.as_deref().map(semantic_expr).unwrap_or(json!(["none"])), - Expr::Call(c)=>{ - let c=c.for_evaluation().unwrap_or_else(|_|c.clone()); - json!(["call",c.callee,c.path,c.receiver,c.args.iter().map(|a|match a{ - Arg::Named{name,value}=>json!(["named",name,semantic_expr(value)]), - Arg::Positional(v)=>json!(["positional",semantic_expr(v)]) - }).collect::>()]) - }, - Expr::List(v)=>json!(["list",v.iter().map(semantic_expr).collect::>()]), - Expr::Map(v)=>json!(["map",v.iter().map(|(k,v)|json!([k,semantic_expr(v)])).collect::>()]), - Expr::Unary{op,expr}=>json!(["unary",format!("{op:?}"),semantic_expr(expr)]), - Expr::Binary{op,left,right}=>json!(["binary",format!("{op:?}"),semantic_expr(left),semantic_expr(right)]), - _=>json!(format!("{e:?}")) - } -} -fn semantic_statements(body:&[marqdo::ast::Stmt])->Vec { - use marqdo::ast::{Expr,Stmt}; - body.iter().map(|s|match s { - Stmt::Assign{name,value,..}=>json!(["assign",name,semantic_expr(value)]), - Stmt::Return{value,..}=>json!(["return",semantic_expr(value)]), - Stmt::Call{call,..}=>json!(["eval",semantic_expr(&Expr::Call(call.clone()))]), - Stmt::Expr{value,..}=>json!(["eval",semantic_expr(value)]), - Stmt::Branch{arms,..}=>json!(["branch",arms.iter().map(|a|json!([a.condition.as_ref().map(semantic_expr),semantic_statements(&a.body)])).collect::>()]), - Stmt::While{condition,body,..}=>json!(["while",semantic_expr(condition),semantic_statements(body)]), - Stmt::ForEach{item,collection,body,..}=>json!(["foreach",item,collection,semantic_statements(body)]) - }).collect() -} -fn statement_locations(body:&[marqdo::ast::Stmt])->Vec { - use marqdo::ast::Stmt; - let mut out=Vec::new(); - for s in body {match s { - Stmt::Assign{name,value,span,end_line}=>out.push(json!({"kind":"assign","name":name,"line":span.line,"end_line":end_line,"rendered":expression(value)})), - Stmt::Return{value,span}=>out.push(json!({"kind":"return","line":span.line,"rendered":expression(value)})), - Stmt::Call{call,span}=>out.push(json!({"kind":"call","line":span.line,"callee":call.path.as_ref().map(|p|p.join(".")).unwrap_or_else(||call.callee.clone()),"rendered":call_source(call,true)})), - Stmt::Expr{value,span}=>out.push(json!({"kind":"eval","line":span.line,"rendered":expression(value)})), - Stmt::Branch{arms,..}=>for arm in arms{out.extend(statement_locations(&arm.body));}, - Stmt::While{body,..}|Stmt::ForEach{body,..}=>out.extend(statement_locations(body)) - }} - out -} - -fn analyze(p:&Value)->Answer { - use marqdo::ast::{Expr,Function,Literal}; - fn default(e:&Expr)->Value {match e { - Expr::Literal(Literal::Text(t))=>json!({"text":t}), - Expr::Literal(Literal::None)=>json!({"source":"None"}), - Expr::Literal(Literal::Bool(v))=>json!({"source":if *v{"True"}else{"False"}}), - Expr::Literal(Literal::Int(v))=>json!({"source":v.to_string()}), - Expr::Literal(Literal::Num(v))=>json!({"source":if v.fract()==0.0 { format!("{v:.1}") } else {v.to_string()}}), - _=>json!({"debug":format!("{e:?}")}) - }} - fn units(fs:&[Function],body:bool)->Vec {fs.iter().map(|f|json!({ - "name":f.name,"line":f.span.line,"level":f.level,"base":f.base, - "params":f.params.iter().map(|p|json!({"name":p.name,"line":p.span.line,"inferred":p.inferred,"default":p.default.as_ref().map(default)})).collect::>(), - "contract":f.contract.as_ref().map(|c|json!({"params":c.params.iter().map(|p|json!({"name":p.name,"ty":p.ty.name(),"desc":p.desc})).collect::>(),"returns":c.returns.as_ref().map(|r|json!({"ty":r.ty.name(),"desc":r.desc}))})), - "children":units(&f.children,body),"semantic":semantic_statements(&f.body),"statements":statement_locations(&f.body),"body":if body{Some(format!("{:?}",f.body))}else{None} - })).collect()} - let source=field(p,"source")?; - let module=marqdo::parse::parse_source(source).map_err(|e|format!("{e:#}"))?; - let diagnostics=marqdo::check::check_module(&module,None).iter().map(|d|d.to_json()).collect::>(); - let ratios=marqdo::narrative_ratio::measure_source_units(source,&module.functions).iter() - .map(|r|json!({"name":r.name,"line":r.line,"narrative":r.narrative,"total":r.total,"ratio":r.ratio})).collect::>(); - Ok(json!({"schema_version":1,"functions":units(&module.functions,p.get("include_body").and_then(Value::as_bool).unwrap_or(false)), - "ratios":ratios,"diagnostics":diagnostics})) -} - - -fn gzip_text(p: &Value) -> Answer { - use base64::Engine; - let data = p.get("data").ok_or("missing portable bytes")?; - if data.get("_type").and_then(Value::as_str) != Some("bytes") { - return Err("gzip expects portable bytes".into()); - } - let encoded = field(data,"base64")?; - if encoded.len() > 24 * 1024 * 1024 { return Err("compressed input exceeds limit".into()); } - let bytes = base64::engine::general_purpose::STANDARD.decode(encoded).map_err(|_| "invalid base64 bytes")?; - let limit = p.get("max_bytes").and_then(Value::as_u64).unwrap_or(16 * 1024 * 1024); - if limit == 0 || limit > 64 * 1024 * 1024 { return Err("invalid gzip output limit".into()); } - let plain = read_bounded(flate2::read::MultiGzDecoder::new(bytes.as_slice()),limit)?; - Ok(json!(String::from_utf8(plain).map_err(|_| "gzip text is not UTF-8")?)) -} - -fn resolve_root(request: &Value) -> Result { - let raw = request.get("root").and_then(Value::as_str).unwrap_or("."); - let selected = PathBuf::from(raw); - if let Ok(path) = selected.canonicalize() { - return Ok(path); - } - // Relative grants must still resolve when the caller only passed "." and the - // process cwd is the intended checkout (Windows runners are sensitive here). - if raw == "." || raw.is_empty() { - return std::env::current_dir() - .and_then(|p| p.canonicalize()) - .map_err(|e| format!("root does not exist ({raw}: {e})")); - } - Err(format!("root does not exist ({raw})")) -} - -fn dispatch(request:&Value)->Answer { - let root=resolve_root(request)?; - let op=field(request,"operation")?; - let empty=json!({});let p=request.get("payload").unwrap_or(&empty); - match op { - "command"=>command(&root,p), - "git_inspect"=>git_inspect(&root), - "github"=>http_json(&root,p), - "archive"=>archive(&root,p), - "gzip_text"=>gzip_text(p), - "analyze"=>analyze(p), - "r2_put"=>r2_put(&root,p), - _=>Err("unknown engineering boundary operation".into()) - } -} -unsafe extern "C" fn engineering_request(args:*const c_char,out:*mut *mut c_char,err:*mut *mut c_char)->c_int { - let args=match parse_args(args){Ok(v)=>v,Err(e)=>{set_err(err,&e);return 1;}}; - let request=args.get("request").unwrap_or(&args); - let result=match dispatch(request) { - Ok(value)=>json!({"ok":true,"value":value,"error":null}), - Err(message)=>json!({"ok":false,"value":null,"error":{"code":"engineering.boundary","message":message,"operation":request.get("operation")}}) - }; - set_out(out,&result.to_string());0 -} -marqdo_plugin!(2,[("engineering_request","request",engineering_request)]); - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize,Ordering}; - static NEXT:AtomicUsize=AtomicUsize::new(0); - fn fixture()->PathBuf { - let p=std::env::temp_dir().join(format!("mq-engineering-{}-{}",std::process::id(),NEXT.fetch_add(1,Ordering::Relaxed))); - fs::create_dir_all(&p).unwrap(); p - } - #[cfg(unix)] - #[test] - fn argv_input_is_literal_and_noisy_output_is_bounded() { - let dir=fixture(); - let input="quotes \" ' $HOME $(never-run) 😀\n".repeat(1000); - let result=command(&dir,&json!({"argv":["/bin/cat"],"stdin":input})).unwrap(); - assert_eq!(result["code"],0);assert_eq!(result["stdout"],input); - let result=command(&dir,&json!({"argv":["/usr/bin/head","-c","65536","/dev/zero"],"max_output":128})).unwrap(); - assert_eq!(result["code"],0);assert_eq!(result["stdout"].as_str().unwrap().len(),128); - assert_eq!(result["truncated"],true); - fs::remove_dir_all(dir).unwrap(); - } - #[cfg(unix)] - #[test] - fn timeout_and_nonzero_exit_remain_observable() { - let dir=fixture();let started=Instant::now(); - let result=command(&dir,&json!({"argv":["/bin/sleep","2"],"timeout_ms":20})).unwrap(); - assert_eq!(result["timed_out"],true);assert_eq!(result["code"],124); - assert!(started.elapsed()Vec { - let mut writer=flate2::write::GzEncoder::new(Vec::new(),flate2::Compression::default()); - writer.write_all(payload).unwrap();writer.finish().unwrap() - } - let mut bytes=compressed(b"Package: marqdo\n");bytes.extend(compressed(b"Version: 2.6.0\n")); - let data=json!({"_type":"bytes","base64":base64::engine::general_purpose::STANDARD.encode(&bytes)}); - assert_eq!(gzip_text(&json!({"data":data})).unwrap(),"Package: marqdo\nVersion: 2.6.0\n"); - assert!(gzip_text(&json!({"data":data,"max_bytes":2})).is_err()); - assert!(gzip_text(&json!({"data":{"_type":"bytes","base64":"invalid"}})).is_err()); - let data=json!({"_type":"bytes","base64":base64::engine::general_purpose::STANDARD.encode(compressed(&[0xff]))}); - assert!(gzip_text(&json!({"data":data})).is_err()); - } - #[test] - fn analysis_uses_the_real_parser_without_loading_imports() { - let source="---\nmarkup: occlusion\nimport:\n absent: /does/not/exist.mq.md\n---\n## answer\n\n完成计算后返回*42*。\n"; - let result=analyze(&json!({"source":source})).unwrap(); - assert_eq!(result["functions"][0]["name"],"answer"); - assert!(result["diagnostics"].as_array().unwrap().is_empty()); - assert_eq!(result["functions"][0]["semantic"][0][0],"return"); - } -} diff --git a/plugins/linalg/Cargo.toml b/plugins/linalg/Cargo.toml deleted file mode 100755 index 627c10c..0000000 --- a/plugins/linalg/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "marqdo_plugin_linalg" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -description = "Marqdo linear algebra plugin — formula-first MatExpr (ABI v2)" -publish = false - -[lib] -name = "linalg" -crate-type = ["cdylib"] - -[dependencies] -marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" } -serde = { version = "1", features = ["derive"] } -serde_json = "1" diff --git a/plugins/linalg/src/complex.rs b/plugins/linalg/src/complex.rs deleted file mode 100755 index 6218ce0..0000000 --- a/plugins/linalg/src/complex.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! Complex dense baseline (L6): parse/store + Frobenius norm. -//! Factorize / solve stay real-only for now. - -use serde_json::{json, Value}; - -use crate::dense::MAX_ELEMENTS; - -pub type CMat = Vec>; - -pub fn shape(m: &CMat) -> Result<(usize, usize), String> { - if m.is_empty() { - return Err("empty complex matrix".into()); - } - let r = m.len(); - let c = m[0].len(); - if c == 0 || m.iter().any(|row| row.len() != c) { - return Err("complex matrix rows must have equal non-zero length".into()); - } - Ok((r, c)) -} - -fn check_elems(rows: usize, cols: usize) -> Result<(), String> { - let n = rows.saturating_mul(cols); - if n > MAX_ELEMENTS { - return Err(format!( - "complex matrix {rows}×{cols} has {n} elements > limit {MAX_ELEMENTS}" - )); - } - Ok(()) -} - -fn parse_cell(c: &Value) -> Result<(f64, f64), String> { - if let Some(n) = c - .as_f64() - .or_else(|| c.as_i64().map(|i| i as f64)) - .or_else(|| c.as_u64().map(|u| u as f64)) - { - return Ok((n, 0.0)); - } - if let Some(arr) = c.as_array() { - if arr.len() == 2 { - let re = arr[0] - .as_f64() - .or_else(|| arr[0].as_i64().map(|i| i as f64)) - .ok_or_else(|| "complex re must be number".to_string())?; - let im = arr[1] - .as_f64() - .or_else(|| arr[1].as_i64().map(|i| i as f64)) - .ok_or_else(|| "complex im must be number".to_string())?; - return Ok((re, im)); - } - } - if let Some(obj) = c.as_object() { - let re = obj - .get("re") - .or_else(|| obj.get("real")) - .and_then(|v| v.as_f64().or_else(|| v.as_i64().map(|i| i as f64))) - .ok_or_else(|| "complex cell needs re/real".to_string())?; - let im = obj - .get("im") - .or_else(|| obj.get("imag")) - .and_then(|v| v.as_f64().or_else(|| v.as_i64().map(|i| i as f64))) - .unwrap_or(0.0); - return Ok((re, im)); - } - Err("complex cell must be number, [re,im], or {re,im}".into()) -} - -fn cell_looks_complex(c: &Value) -> bool { - if let Some(arr) = c.as_array() { - return arr.len() == 2 - && arr.iter().all(|x| { - x.is_number() || x.as_i64().is_some() || x.as_u64().is_some() - }); - } - c.as_object() - .map(|o| o.contains_key("re") || o.contains_key("real") || o.contains_key("im")) - .unwrap_or(false) -} - -/// True if nested list contains any complex-looking cell. -pub fn data_has_complex(v: &Value) -> bool { - let Some(rows) = v.as_array() else { - return false; - }; - rows.iter().any(|row| { - row.as_array() - .map(|cells| cells.iter().any(cell_looks_complex)) - .unwrap_or(false) - }) -} - -pub fn from_data(v: &Value) -> Result { - let rows = v - .as_array() - .ok_or_else(|| "complex data must be list of rows".to_string())?; - let mut out = Vec::new(); - let mut width = None; - for row in rows { - let cells = row - .as_array() - .ok_or_else(|| "complex row must be a list".to_string())?; - let mut r = Vec::new(); - for c in cells { - r.push(parse_cell(c)?); - } - if let Some(w) = width { - if r.len() != w { - return Err("complex matrix rows must have equal length".into()); - } - } else { - width = Some(r.len()); - } - out.push(r); - } - let (rows, cols) = shape(&out)?; - check_elems(rows, cols)?; - Ok(out) -} - -pub fn from_value(v: &Value) -> Result { - if let Some(obj) = v.as_object() { - if obj.get("dtype").and_then(|d| d.as_str()) == Some("complex") { - if let Some(data) = obj.get("data") { - return from_data(data); - } - } - if let Some(data) = obj.get("data") { - if data_has_complex(data) { - return from_data(data); - } - } - } - if v.is_array() && data_has_complex(v) { - return from_data(v); - } - Err("expected linalg_dense dtype=complex or nested complex list".into()) -} - -fn format_c(z: (f64, f64)) -> String { - let (re, im) = z; - if im.abs() < 1e-15 { - if re.fract() == 0.0 && re.abs() < 1e15 { - format!("{}", re as i64) - } else { - format!("{re}") - } - } else if re.abs() < 1e-15 { - format!("{im}i") - } else { - format!("{re}{im:+}i") - } -} - -pub fn to_dense_value(m: &CMat) -> Result { - let (rows, cols) = shape(m)?; - check_elems(rows, cols)?; - let data: Vec> = m - .iter() - .map(|row| { - row.iter() - .map(|&(re, im)| json!([re, im])) - .collect() - }) - .collect(); - let ascii_rows: Vec = m - .iter() - .map(|row| { - let cells: Vec = row.iter().map(|&z| format_c(z)).collect(); - format!("[{}]", cells.join(",")) - }) - .collect(); - Ok(json!({ - "_type": "matrix", - "kind": "dense", - "rows": rows, - "cols": cols, - "data": data, - "dtype": "complex", - "ascii": format!("[{}]", ascii_rows.join(",")), - "latex": format!( - "\\begin{{bmatrix}}{}\\end{{bmatrix}}", - m.iter() - .map(|row| { - row.iter() - .map(|&z| format_c(z)) - .collect::>() - .join(" & ") - }) - .collect::>() - .join(" \\\\ ") - ), - })) -} - -pub fn frobenius_norm(m: &CMat) -> Result { - let _ = shape(m)?; - let mut s = 0.0; - for row in m { - for &(re, im) in row { - s += re * re + im * im; - } - } - Ok(s.sqrt()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fro_i() { - let m = from_data(&json!([[[0.0, 1.0], [1.0, 0.0]], [[1.0, 0.0], [0.0, -1.0]]])).unwrap(); - assert!((frobenius_norm(&m).unwrap() - 2.0).abs() < 1e-12); - } -} diff --git a/plugins/linalg/src/dense.rs b/plugins/linalg/src/dense.rs deleted file mode 100755 index 6b65d5c..0000000 --- a/plugins/linalg/src/dense.rs +++ /dev/null @@ -1,583 +0,0 @@ -//! Dense real matrix kernels for L2 (`explicit` / solve / det / trace). - -use serde_json::{json, Value}; - -use crate::matexpr::{Dim, Expr}; - -/// Max elements for `explicit` / dense ops (design default 10^4). -pub const MAX_ELEMENTS: usize = 10_000; - -pub type Mat = Vec>; - -pub fn check_elems(rows: usize, cols: usize) -> Result<(), String> { - let n = rows.saturating_mul(cols); - if n > MAX_ELEMENTS { - return Err(format!( - "dense matrix {rows}×{cols} has {n} elements > limit {MAX_ELEMENTS}; keep symbolic or reduce size" - )); - } - Ok(()) -} - -pub fn eye(n: usize) -> Mat { - let mut m = vec![vec![0.0; n]; n]; - for i in 0..n { - m[i][i] = 1.0; - } - m -} - -pub fn zeros(rows: usize, cols: usize) -> Mat { - vec![vec![0.0; cols]; rows] -} - -pub fn shape(m: &Mat) -> Result<(usize, usize), String> { - if m.is_empty() { - return Err("empty dense matrix".into()); - } - let r = m.len(); - let c = m[0].len(); - if c == 0 || m.iter().any(|row| row.len() != c) { - return Err("dense matrix rows must have equal non-zero length".into()); - } - Ok((r, c)) -} - -pub fn to_dense_value(m: &Mat) -> Result { - let (rows, cols) = shape(m)?; - check_elems(rows, cols)?; - Ok(json!({ - "_type": "matrix", - "kind": "dense", - "rows": rows, - "cols": cols, - "data": m, - "dtype": "real", - "ascii": format_ascii(m), - "latex": format_latex(m), - })) -} - -fn format_ascii(m: &Mat) -> String { - let rows: Vec = m - .iter() - .map(|row| { - let cells: Vec = row.iter().map(|x| format_num(*x)).collect(); - format!("[{}]", cells.join(",")) - }) - .collect(); - format!("[{}]", rows.join(",")) -} - -fn format_latex(m: &Mat) -> String { - let body: Vec = m - .iter() - .map(|row| { - row.iter() - .map(|x| format_num(*x)) - .collect::>() - .join(" & ") - }) - .collect(); - format!( - "\\begin{{bmatrix}}{}\\end{{bmatrix}}", - body.join(" \\\\ ") - ) -} - -fn format_num(n: f64) -> String { - if n.fract() == 0.0 && n.abs() < 1e15 { - format!("{}", n as i64) - } else { - format!("{n}") - } -} - -pub fn from_value(v: &Value) -> Result { - if let Some(obj) = v.as_object() { - if let Some(data) = obj.get("data") { - return parse_data(data); - } - // linalg_expr kind=dense - if obj.get("kind").and_then(|k| k.as_str()) == Some("dense") { - if let Some(data) = obj.get("data") { - return parse_data(data); - } - } - } - // Formula Matrix / raw nested list - if v.is_array() { - return parse_data(v); - } - Err("expected matrix dense, dense expr, or nested list".into()) -} - -fn parse_data(v: &Value) -> Result { - let rows = v - .as_array() - .ok_or_else(|| "dense data must be list of rows".to_string())?; - let mut out = Vec::new(); - let mut width = None; - for row in rows { - let cells = row - .as_array() - .ok_or_else(|| "dense row must be a list".to_string())?; - let mut r = Vec::new(); - for c in cells { - let n = c - .as_f64() - .or_else(|| c.as_i64().map(|i| i as f64)) - .or_else(|| c.as_u64().map(|u| u as f64)) - .or_else(|| c.as_str().and_then(|s| s.trim().parse().ok())) - .ok_or_else(|| "dense cell must be a number".to_string())?; - r.push(n); - } - if let Some(w) = width { - if r.len() != w { - return Err("dense matrix rows must have equal length".into()); - } - } else { - width = Some(r.len()); - } - out.push(r); - } - let (rows, cols) = shape(&out)?; - check_elems(rows, cols)?; - Ok(out) -} - -fn dim_usize(d: &Dim) -> Result { - match d { - Dim::Int(n) => Ok(*n), - Dim::Sym(s) => Err(format!( - "cannot explicit symbolic dim `{s}`; bind concrete sizes or use dense leaves only" - )), - } -} - -/// Evaluate MatExpr to dense; symbols are not allowed unless already dense leaves. -pub fn explicit(expr: &Expr) -> Result { - match expr { - Expr::Dense { data } => { - let (r, c) = shape(data)?; - check_elems(r, c)?; - Ok(data.clone()) - } - Expr::Eye { n } => { - let n = dim_usize(n)?; - check_elems(n, n)?; - Ok(eye(n)) - } - Expr::Zero { rows, cols } => { - let r = dim_usize(rows)?; - let c = dim_usize(cols)?; - check_elems(r, c)?; - Ok(zeros(r, c)) - } - Expr::Symbol { name, .. } => Err(format!( - "cannot explicit unbound symbol `{name}`; substitute a dense matrix first" - )), - Expr::Mul { factors } => { - if factors.is_empty() { - return Err("empty MatMul".into()); - } - let mut acc = explicit(&factors[0])?; - for f in &factors[1..] { - acc = matmul(&acc, &explicit(f)?)?; - } - Ok(acc) - } - Expr::Add { terms } => { - if terms.is_empty() { - return Err("empty MatAdd".into()); - } - let mut acc = explicit(&terms[0])?; - for t in &terms[1..] { - acc = mat_add(&acc, &explicit(t)?)?; - } - Ok(acc) - } - Expr::Sub { left, right } => mat_sub(&explicit(left)?, &explicit(right)?), - Expr::Transpose { arg } => Ok(transpose(&explicit(arg)?)), - Expr::Inv { arg } => invert(&explicit(arg)?), - Expr::Kron { factors } => { - if factors.is_empty() { - return Err("empty Kronecker product".into()); - } - let mut acc = explicit(&factors[0])?; - for f in &factors[1..] { - acc = kronecker(&acc, &explicit(f)?)?; - } - Ok(acc) - } - Expr::Block { blocks } => explicit_block(blocks), - } -} - -fn explicit_block(blocks: &[Vec]) -> Result { - if blocks.is_empty() || blocks[0].is_empty() { - return Err("empty block matrix".into()); - } - let br = blocks.len(); - let bc = blocks[0].len(); - let mut tiles: Vec> = Vec::with_capacity(br); - for i in 0..br { - let mut row = Vec::with_capacity(bc); - for j in 0..bc { - row.push(explicit(&blocks[i][j])?); - } - tiles.push(row); - } - // Validate and assemble - let mut row_heights = Vec::with_capacity(br); - for i in 0..br { - let (h, _) = shape(&tiles[i][0])?; - for j in 1..bc { - let (h2, _) = shape(&tiles[i][j])?; - if h != h2 { - return Err("block row height mismatch when explicit".into()); - } - } - row_heights.push(h); - } - let mut col_widths = Vec::with_capacity(bc); - for j in 0..bc { - let (_, w) = shape(&tiles[0][j])?; - for i in 1..br { - let (_, w2) = shape(&tiles[i][j])?; - if w != w2 { - return Err("block col width mismatch when explicit".into()); - } - } - col_widths.push(w); - } - let total_r: usize = row_heights.iter().sum(); - let total_c: usize = col_widths.iter().sum(); - check_elems(total_r, total_c)?; - let mut out = zeros(total_r, total_c); - let mut r0 = 0; - for i in 0..br { - let mut c0 = 0; - for j in 0..bc { - let tile = &tiles[i][j]; - let (h, w) = shape(tile)?; - for ii in 0..h { - for jj in 0..w { - out[r0 + ii][c0 + jj] = tile[ii][jj]; - } - } - c0 += w; - } - r0 += row_heights[i]; - } - Ok(out) -} - -pub fn kronecker(a: &Mat, b: &Mat) -> Result { - let (ar, ac) = shape(a)?; - let (br, bc) = shape(b)?; - let rows = ar.saturating_mul(br); - let cols = ac.saturating_mul(bc); - check_elems(rows, cols)?; - let mut out = zeros(rows, cols); - for i in 0..ar { - for j in 0..ac { - let aij = a[i][j]; - for ii in 0..br { - for jj in 0..bc { - out[i * br + ii][j * bc + jj] = aij * b[ii][jj]; - } - } - } - } - Ok(out) -} - -pub fn matmul(a: &Mat, b: &Mat) -> Result { - let (ar, ac) = shape(a)?; - let (br, bc) = shape(b)?; - if ac != br { - return Err(format!( - "matmul shape mismatch: {ar}×{ac} · {br}×{bc}" - )); - } - check_elems(ar, bc)?; - let mut out = zeros(ar, bc); - for i in 0..ar { - for k in 0..ac { - let aik = a[i][k]; - if aik == 0.0 { - continue; - } - for j in 0..bc { - out[i][j] += aik * b[k][j]; - } - } - } - Ok(out) -} - -pub fn mat_add(a: &Mat, b: &Mat) -> Result { - let (ar, ac) = shape(a)?; - let (br, bc) = shape(b)?; - if ar != br || ac != bc { - return Err(format!("add shape mismatch: {ar}×{ac} vs {br}×{bc}")); - } - let mut out = zeros(ar, ac); - for i in 0..ar { - for j in 0..ac { - out[i][j] = a[i][j] + b[i][j]; - } - } - Ok(out) -} - -pub fn mat_sub(a: &Mat, b: &Mat) -> Result { - let (ar, ac) = shape(a)?; - let (br, bc) = shape(b)?; - if ar != br || ac != bc { - return Err(format!("sub shape mismatch: {ar}×{ac} vs {br}×{bc}")); - } - let mut out = zeros(ar, ac); - for i in 0..ar { - for j in 0..ac { - out[i][j] = a[i][j] - b[i][j]; - } - } - Ok(out) -} - -pub fn transpose(m: &Mat) -> Mat { - let (r, c) = shape(m).unwrap_or((0, 0)); - let mut out = zeros(c, r); - for i in 0..r { - for j in 0..c { - out[j][i] = m[i][j]; - } - } - out -} - -pub fn trace(m: &Mat) -> Result { - let (r, c) = shape(m)?; - if r != c { - return Err(format!("trace needs square matrix, got {r}×{c}")); - } - Ok((0..r).map(|i| m[i][i]).sum()) -} - -pub fn det(m: &Mat) -> Result { - let (n, c) = shape(m)?; - if n != c { - return Err(format!("det needs square matrix, got {n}×{c}")); - } - if n == 0 { - return Ok(1.0); - } - if n == 1 { - return Ok(m[0][0]); - } - if n == 2 { - return Ok(m[0][0] * m[1][1] - m[0][1] * m[1][0]); - } - // Gaussian elimination with partial pivoting - let mut a = m.clone(); - let mut det = 1.0; - for k in 0..n { - let mut piv = k; - let mut best = a[k][k].abs(); - for i in (k + 1)..n { - let v = a[i][k].abs(); - if v > best { - best = v; - piv = i; - } - } - if best < 1e-15 { - return Ok(0.0); - } - if piv != k { - a.swap(k, piv); - det = -det; - } - let akk = a[k][k]; - det *= akk; - for i in (k + 1)..n { - let f = a[i][k] / akk; - for j in k..n { - a[i][j] -= f * a[k][j]; - } - } - } - Ok(det) -} - -pub fn invert(m: &Mat) -> Result { - let (n, c) = shape(m)?; - if n != c { - return Err(format!("inverse needs square matrix, got {n}×{c}")); - } - check_elems(n, n)?; - // Augment [A|I] - let mut a = zeros(n, 2 * n); - for i in 0..n { - for j in 0..n { - a[i][j] = m[i][j]; - } - a[i][n + i] = 1.0; - } - for k in 0..n { - let mut piv = k; - let mut best = a[k][k].abs(); - for i in (k + 1)..n { - let v = a[i][k].abs(); - if v > best { - best = v; - piv = i; - } - } - if best < 1e-15 { - return Err("matrix is singular (not invertible)".into()); - } - if piv != k { - a.swap(k, piv); - } - let akk = a[k][k]; - for j in 0..(2 * n) { - a[k][j] /= akk; - } - for i in 0..n { - if i == k { - continue; - } - let f = a[i][k]; - for j in 0..(2 * n) { - a[i][j] -= f * a[k][j]; - } - } - } - let mut out = zeros(n, n); - for i in 0..n { - for j in 0..n { - out[i][j] = a[i][n + j]; - } - } - Ok(out) -} - -/// Solve A x = b. `b` may be n×1 or n×k; returns n×k. -pub fn solve(a: &Mat, b: &Mat) -> Result { - let (n, ac) = shape(a)?; - if n != ac { - return Err(format!("solve needs square A, got {n}×{ac}")); - } - let (br, bc) = shape(b)?; - if br != n { - return Err(format!("solve rhs rows {br} != A rows {n}")); - } - // Augment [A|B] - let mut m = zeros(n, n + bc); - for i in 0..n { - for j in 0..n { - m[i][j] = a[i][j]; - } - for j in 0..bc { - m[i][n + j] = b[i][j]; - } - } - for k in 0..n { - let mut piv = k; - let mut best = m[k][k].abs(); - for i in (k + 1)..n { - let v = m[i][k].abs(); - if v > best { - best = v; - piv = i; - } - } - if best < 1e-15 { - return Err("singular matrix in solve".into()); - } - if piv != k { - m.swap(k, piv); - } - let akk = m[k][k]; - for j in k..(n + bc) { - m[k][j] /= akk; - } - for i in 0..n { - if i == k { - continue; - } - let f = m[i][k]; - for j in k..(n + bc) { - m[i][j] -= f * m[k][j]; - } - } - } - let mut x = zeros(n, bc); - for i in 0..n { - for j in 0..bc { - x[i][j] = m[i][n + j]; - } - } - Ok(x) -} - -pub fn solve_result(a: &Mat, b: &Mat) -> Result { - let x = solve(a, b)?; - let ax = matmul(a, &x)?; - let resid = mat_sub(&ax, b)?; - let mut max_r = 0.0_f64; - for row in &resid { - for &v in row { - max_r = max_r.max(v.abs()); - } - } - Ok(json!({ - "_type": "linalg_solve", - "method": "gauss", - "x": to_dense_value(&x)?, - "residual_max": max_r, - })) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn solve_2x2() { - let a = vec![vec![2.0, 1.0], vec![1.0, 3.0]]; - let b = vec![vec![5.0], vec![5.0]]; - let x = solve(&a, &b).unwrap(); - assert!((x[0][0] - 2.0).abs() < 1e-9); - assert!((x[1][0] - 1.0).abs() < 1e-9); - } - - #[test] - fn det_2x2() { - let m = vec![vec![1.0, 2.0], vec![3.0, 4.0]]; - assert!((det(&m).unwrap() + 2.0).abs() < 1e-9); - } - - #[test] - fn explicit_mul() { - let a = Expr::Dense { - data: vec![vec![1.0, 2.0], vec![0.0, 1.0]], - }; - let b = Expr::Dense { - data: vec![vec![1.0, 0.0], vec![1.0, 1.0]], - }; - let p = Expr::Mul { - factors: vec![a, b], - }; - let m = explicit(&p).unwrap(); - assert_eq!(m, vec![vec![3.0, 2.0], vec![1.0, 1.0]]); - } - - #[test] - fn oversize_guard() { - assert!(check_elems(101, 100).is_err()); - } -} diff --git a/plugins/linalg/src/draw.rs b/plugins/linalg/src/draw.rs deleted file mode 100755 index 4c924bd..0000000 --- a/plugins/linalg/src/draw.rs +++ /dev/null @@ -1,361 +0,0 @@ -//! Structure SVG for factorizations (teaching layouts) with Q8-aligned themes. - -use serde_json::Value; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ThemeName { - Dark, - Light, - Bw, -} - -impl ThemeName { - pub fn parse(raw: &str) -> Result { - match raw.trim().to_ascii_lowercase().as_str() { - "dark" | "暗" => Ok(Self::Dark), - "light" | "亮" | "浅" => Ok(Self::Light), - "bw" | "mono" | "黑白" => Ok(Self::Bw), - other => Err(format!("unknown theme `{other}` (dark|light|bw)")), - } - } - - pub fn as_str(self) -> &'static str { - match self { - Self::Dark => "dark", - Self::Light => "light", - Self::Bw => "bw", - } - } -} - -struct Theme { - name: ThemeName, - bg: &'static str, - ink: &'static str, - muted: &'static str, - stroke: &'static str, - box_a: &'static str, - box_b: &'static str, - box_c: &'static str, - heat_neg: &'static str, - heat_pos: &'static str, -} - -impl Theme { - fn of(name: ThemeName) -> Self { - match name { - ThemeName::Dark => Self { - name, - bg: "#0a0e14", - ink: "#e8eef6", - muted: "#93a4b8", - stroke: "#6b7f96", - box_a: "#1e3a5f", - box_b: "#3d2e14", - box_c: "#1e3f2e", - heat_neg: "#cc5555", - heat_pos: "#4c8fff", - }, - ThemeName::Light => Self { - name, - bg: "#eef3f9", - ink: "#15202b", - muted: "#5a6a7a", - stroke: "#4a5a6a", - box_a: "#e8f1ff", - box_b: "#fff3d6", - box_c: "#e8ffe8", - heat_neg: "#cc3333", - heat_pos: "#2266aa", - }, - ThemeName::Bw => Self { - name, - bg: "#ffffff", - ink: "#111111", - muted: "#555555", - stroke: "#222222", - box_a: "#f0f0f0", - box_b: "#e0e0e0", - box_c: "#d0d0d0", - heat_neg: "#000000", - heat_pos: "#666666", - }, - } - } -} - -/// Draw a factor object or matrix as structure SVG. -pub fn draw_factor( - factor: &Value, - kind: Option<&str>, - path: Option<&str>, - theme: ThemeName, -) -> Result { - let kind = kind - .or_else(|| factor.get("kind").and_then(|k| k.as_str())) - .unwrap_or("structure"); - let th = Theme::of(theme); - let svg = match kind { - "eig" => draw_eig(factor, &th), - "svd" => draw_svd(factor, &th), - "qr" => draw_qr(factor, &th), - "lu" | "ge" => draw_lu(factor, &th), - "chol" => draw_chol(factor, &th), - "structure" => draw_structure(factor, &th), - "heatmap" | "hinton" => draw_heatmap(factor, kind == "hinton", &th), - other => { - return Err(format!( - "unknown draw kind `{other}` (want eig|svd|qr|lu|ge|chol|structure|heatmap|hinton)" - )) - } - }; - let _ = path; - Ok(svg) -} - -fn escape(s: &str) -> String { - s.replace('&', "&") - .replace('<', "<") - .replace('>', ">") -} - -fn box_svg(x: f64, y: f64, w: f64, h: f64, label: &str, fill: &str, th: &Theme) -> String { - format!( - "\ -{}", - th.stroke, - x + w / 2.0, - y + h / 2.0, - th.ink, - escape(label) - ) -} - -fn root(w: f64, h: f64, kind: &str, th: &Theme, body: &str) -> String { - format!( - "\ -{body}\ -", - th.name.as_str(), - th.bg - ) -} - -fn draw_eig(factor: &Value, th: &Theme) -> String { - let latex = factor - .get("latex") - .and_then(|x| x.as_str()) - .unwrap_or("A = P D P^{-1}"); - let evals = factor - .get("eigenvalues") - .and_then(|x| x.as_array()) - .map(|a| { - a.iter() - .filter_map(|v| v.as_f64()) - .map(|v| format!("{v:.4}")) - .collect::>() - .join(", ") - }) - .unwrap_or_default(); - let body = format!( - "{}\ -{}\ -{}\ -{}\ -λ = [{}]", - th.ink, - escape(latex), - box_svg(40.0, 48.0, 70.0, 50.0, "P", th.box_a, th), - box_svg(130.0, 48.0, 70.0, 50.0, "D", th.box_b, th), - box_svg(220.0, 48.0, 90.0, 50.0, "P⁻¹", th.box_a, th), - th.muted, - escape(&evals) - ); - root(520.0, 140.0, "eig", th, &body) -} - -fn draw_svd(factor: &Value, th: &Theme) -> String { - let s = factor - .get("S") - .and_then(|x| x.as_array()) - .map(|a| { - a.iter() - .filter_map(|v| v.as_f64()) - .map(|v| format!("{v:.4}")) - .collect::>() - .join(", ") - }) - .unwrap_or_default(); - let body = format!( - "A = U Σ V⊤\ -{}\ -{}\ -{}\ -σ = [{}]", - th.ink, - box_svg(40.0, 48.0, 70.0, 50.0, "U", th.box_a, th), - box_svg(130.0, 48.0, 70.0, 50.0, "Σ", th.box_b, th), - box_svg(220.0, 48.0, 80.0, 50.0, "V⊤", th.box_a, th), - th.muted, - escape(&s) - ); - root(560.0, 140.0, "svd", th, &body) -} - -fn draw_qr(_factor: &Value, th: &Theme) -> String { - let body = format!( - "A = Q R\ -{}\ -{}", - th.ink, - box_svg(40.0, 48.0, 70.0, 50.0, "Q", th.box_a, th), - box_svg(130.0, 48.0, 70.0, 50.0, "R", th.box_b, th), - ); - root(420.0, 120.0, "qr", th, &body) -} - -fn draw_lu(_factor: &Value, th: &Theme) -> String { - let body = format!( - "A = L U\ -{}\ -{}", - th.ink, - box_svg(40.0, 48.0, 70.0, 50.0, "L", th.box_c, th), - box_svg(130.0, 48.0, 70.0, 50.0, "U", th.box_b, th), - ); - root(420.0, 120.0, "lu", th, &body) -} - -fn draw_chol(_factor: &Value, th: &Theme) -> String { - let body = format!( - "A = L L⊤\ -{}\ -{}", - th.ink, - box_svg(40.0, 48.0, 70.0, 50.0, "L", th.box_c, th), - box_svg(130.0, 48.0, 80.0, 50.0, "L⊤", th.box_c, th), - ); - root(420.0, 120.0, "chol", th, &body) -} - -fn draw_structure(factor: &Value, th: &Theme) -> String { - let label = if let (Some(r), Some(c)) = (factor.get("rows"), factor.get("cols")) { - format!("{}×{}", r, c) - } else if let Some(Value::Array(a)) = factor.get("shape") { - if a.len() >= 2 { - format!("{}×{}", a[0], a[1]) - } else { - factor - .get("kind") - .and_then(|k| k.as_str()) - .unwrap_or("matrix") - .to_string() - } - } else { - factor - .get("kind") - .and_then(|k| k.as_str()) - .unwrap_or("matrix") - .to_string() - }; - let body = box_svg(40.0, 30.0, 160.0, 60.0, &label, th.box_a, th); - root(280.0, 120.0, "structure", th, &body) -} - -fn draw_heatmap(factor: &Value, hinton: bool, th: &Theme) -> String { - let data = factor - .get("data") - .or_else(|| factor.get("eigenvectors").and_then(|v| v.get("data"))) - .and_then(|d| d.as_array()); - let Some(rows) = data else { - return draw_structure(factor, th); - }; - let n = rows.len().min(16); - let m = rows - .first() - .and_then(|r| r.as_array()) - .map(|r| r.len()) - .unwrap_or(0) - .min(16); - if n == 0 || m == 0 { - return draw_structure(factor, th); - } - let mut max_abs: f64 = 1e-12; - for row in rows.iter().take(n) { - if let Some(cells) = row.as_array() { - for c in cells.iter().take(m) { - let v = cell_mag(c); - max_abs = max_abs.max(v); - } - } - } - let cell = 18.0; - let w = 40.0 + m as f64 * cell; - let h = 40.0 + n as f64 * cell; - let tag = if hinton { "hinton" } else { "heatmap" }; - let mut parts = vec![format!( - "", - th.name.as_str(), - th.bg - )]; - for (i, row) in rows.iter().take(n).enumerate() { - let Some(cells) = row.as_array() else { continue }; - for (j, c) in cells.iter().take(m).enumerate() { - let v = cell_signed(c); - let x = 20.0 + j as f64 * cell; - let y = 20.0 + i as f64 * cell; - if hinton { - let s = (v.abs() / max_abs).sqrt() * (cell - 4.0); - let fill = if v >= 0.0 { th.heat_pos } else { th.heat_neg }; - parts.push(format!( - "", - x + (cell - s) / 2.0, - y + (cell - s) / 2.0 - )); - } else { - let t = ((v / max_abs) + 1.0) * 0.5; - let r = (255.0 * (1.0 - t)) as u8; - let b = (255.0 * t) as u8; - let fill = if th.name == ThemeName::Bw { - let g = (255.0 * (1.0 - v.abs() / max_abs)) as u8; - format!("rgb({g},{g},{g})") - } else { - format!("rgb({r},80,{b})") - }; - parts.push(format!( - "", - th.bg - )); - } - } - } - parts.push("".into()); - parts.join("") -} - -fn cell_mag(c: &Value) -> f64 { - if let Some(v) = c.as_f64() { - return v.abs(); - } - if let Some(a) = c.as_array() { - if a.len() >= 2 { - let re = a[0].as_f64().unwrap_or(0.0); - let im = a[1].as_f64().unwrap_or(0.0); - return (re * re + im * im).sqrt(); - } - } - 0.0 -} - -fn cell_signed(c: &Value) -> f64 { - if let Some(v) = c.as_f64() { - return v; - } - // complex: use real part for signed heatmap, magnitude for abs - if let Some(a) = c.as_array() { - if a.len() >= 2 { - return a[0].as_f64().unwrap_or(0.0); - } - } - 0.0 -} diff --git a/plugins/linalg/src/factor.rs b/plugins/linalg/src/factor.rs deleted file mode 100755 index 97a8477..0000000 --- a/plugins/linalg/src/factor.rs +++ /dev/null @@ -1,451 +0,0 @@ -//! Dense factorizations for L4: LU, QR, eig (symmetric Jacobi), SVD, Cholesky. - -use serde_json::{json, Value}; - -use crate::dense::{self, Mat, MAX_ELEMENTS}; - -pub const FACTOR_MAX_SIDE: usize = 64; - -fn check_side(n: usize, label: &str) -> Result<(), String> { - if n > FACTOR_MAX_SIDE { - return Err(format!( - "{label} limited to side ≤ {FACTOR_MAX_SIDE} (got {n})" - )); - } - Ok(()) -} - -pub fn check_side_limit(n: usize, label: &str) -> Result<(), String> { - check_side(n, label) -} - -fn check_mat(m: &Mat) -> Result<(usize, usize), String> { - let (r, c) = dense::shape(m)?; - dense::check_elems(r, c)?; - Ok((r, c)) -} - -/// Factorize `kind` ∈ lu|qr|svd|eig|chol. -pub fn factorize(m: &Mat, kind: &str) -> Result { - let kind = kind.trim().to_ascii_lowercase(); - match kind.as_str() { - "lu" => lu_value(m), - "qr" => qr_value(m), - "eig" => eig_value(m), - "svd" => svd_value(m), - "chol" | "cholesky" => chol_value(m), - other => Err(format!( - "unknown factorize kind `{other}` (want lu|qr|svd|eig|chol)" - )), - } -} - -fn lu_value(m: &Mat) -> Result { - let (n, c) = check_mat(m)?; - if n != c { - return Err(format!("LU needs square matrix, got {n}×{c}")); - } - check_side(n, "LU")?; - let (l, u, piv) = lu_decomp(m)?; - Ok(json!({ - "_type": "linalg_factor", - "kind": "lu", - "L": dense::to_dense_value(&l)?, - "U": dense::to_dense_value(&u)?, - "pivots": piv, - "latex": "A = LU", - "ascii": "LU", - })) -} - -fn qr_value(m: &Mat) -> Result { - let (rows, cols) = check_mat(m)?; - check_side(rows.max(cols), "QR")?; - let (q, r) = qr_decomp(m)?; - Ok(json!({ - "_type": "linalg_factor", - "kind": "qr", - "Q": dense::to_dense_value(&q)?, - "R": dense::to_dense_value(&r)?, - "latex": "A = QR", - "ascii": "QR", - })) -} - -fn eig_value(m: &Mat) -> Result { - let (n, c) = check_mat(m)?; - if n != c { - return Err(format!("eig needs square matrix, got {n}×{c}")); - } - check_side(n, "eig")?; - // Jacobi assumes symmetric; if nearly symmetric, symmetrize. - let (evals, evecs) = jacobi_symm(m)?; - let d = dense::zeros(n, n); - let mut d = d; - for i in 0..n { - d[i][i] = evals[i]; - } - Ok(json!({ - "_type": "linalg_factor", - "kind": "eig", - "eigenvalues": evals, - "eigenvectors": dense::to_dense_value(&evecs)?, - "D": dense::to_dense_value(&d)?, - "latex": "A = P D P^{-1}", - "ascii": "eig", - })) -} - -fn svd_value(m: &Mat) -> Result { - let (rows, cols) = check_mat(m)?; - check_side(rows.max(cols), "SVD")?; - let (u, s, vt) = svd_decomp(m)?; - Ok(json!({ - "_type": "linalg_factor", - "kind": "svd", - "U": dense::to_dense_value(&u)?, - "S": s, - "Vt": dense::to_dense_value(&vt)?, - "latex": "A = U \\Sigma V^{\\top}", - "ascii": "SVD", - })) -} - -fn chol_value(m: &Mat) -> Result { - let (n, c) = check_mat(m)?; - if n != c { - return Err(format!("Cholesky needs square matrix, got {n}×{c}")); - } - check_side(n, "Cholesky")?; - let l = cholesky(m)?; - Ok(json!({ - "_type": "linalg_factor", - "kind": "chol", - "L": dense::to_dense_value(&l)?, - "latex": "A = L L^{\\top}", - "ascii": "chol", - })) -} - -/// PA = LU with partial pivoting; returns (L, U, pivot row order). -pub fn lu_decomp(a: &Mat) -> Result<(Mat, Mat, Vec), String> { - let (n, _) = dense::shape(a)?; - let mut m = a.clone(); - let mut piv: Vec = (0..n).collect(); - let mut l = dense::eye(n); - for k in 0..n { - let mut piv_row = k; - let mut best = m[k][k].abs(); - for i in (k + 1)..n { - let v = m[i][k].abs(); - if v > best { - best = v; - piv_row = i; - } - } - if best < 1e-15 { - return Err("LU failed: singular or near-singular matrix".into()); - } - if piv_row != k { - m.swap(k, piv_row); - piv.swap(k, piv_row); - for j in 0..k { - let t = l[k][j]; - l[k][j] = l[piv_row][j]; - l[piv_row][j] = t; - } - } - for i in (k + 1)..n { - let f = m[i][k] / m[k][k]; - l[i][k] = f; - m[i][k] = 0.0; - for j in (k + 1)..n { - m[i][j] -= f * m[k][j]; - } - } - } - Ok((l, m, piv)) -} - -/// Thin QR via modified Gram-Schmidt. A is m×n with m≥n preferred. -pub fn qr_decomp(a: &Mat) -> Result<(Mat, Mat), String> { - let (m, n) = dense::shape(a)?; - let mut v = a.clone(); - let mut q = dense::zeros(m, n); - let mut r = dense::zeros(n, n); - for j in 0..n { - // orthogonalize against previous - for i in 0..j { - let mut dot = 0.0; - for k in 0..m { - dot += q[k][i] * v[k][j]; - } - r[i][j] = dot; - for k in 0..m { - v[k][j] -= dot * q[k][i]; - } - } - let mut norm = 0.0; - for k in 0..m { - norm += v[k][j] * v[k][j]; - } - norm = norm.sqrt(); - if norm < 1e-15 { - return Err("QR failed: linearly dependent columns".into()); - } - r[j][j] = norm; - for k in 0..m { - q[k][j] = v[k][j] / norm; - } - } - Ok((q, r)) -} - -/// Jacobi eigenvalue for symmetric (or symmetrized) real matrix. -/// Returns eigenvalues (descending) and eigenvector matrix (columns). -pub fn jacobi_symm(a: &Mat) -> Result<(Vec, Mat), String> { - let (n, _) = dense::shape(a)?; - // Symmetrize - let mut s = dense::zeros(n, n); - for i in 0..n { - for j in 0..n { - s[i][j] = 0.5 * (a[i][j] + a[j][i]); - } - } - let mut v = dense::eye(n); - for _ in 0..(n * n * 40).max(40) { - // Find largest off-diagonal - let mut p = 0usize; - let mut q = 1usize; - let mut best = 0.0; - for i in 0..n { - for j in (i + 1)..n { - let v = s[i][j].abs(); - if v > best { - best = v; - p = i; - q = j; - } - } - } - if best < 1e-12 { - break; - } - let app = s[p][p]; - let aqq = s[q][q]; - let apq = s[p][q]; - let tau = (aqq - app) / (2.0 * apq); - let t = if tau >= 0.0 { - 1.0 / (tau + (1.0 + tau * tau).sqrt()) - } else { - -1.0 / (-tau + (1.0 + tau * tau).sqrt()) - }; - let c = 1.0 / (1.0 + t * t).sqrt(); - let sn = t * c; - // Rotate S - s[p][p] = app - t * apq; - s[q][q] = aqq + t * apq; - s[p][q] = 0.0; - s[q][p] = 0.0; - for i in 0..n { - if i == p || i == q { - continue; - } - let sip = s[i][p]; - let siq = s[i][q]; - s[i][p] = c * sip - sn * siq; - s[p][i] = s[i][p]; - s[i][q] = c * siq + sn * sip; - s[q][i] = s[i][q]; - } - // Accumulate V - for i in 0..n { - let vip = v[i][p]; - let viq = v[i][q]; - v[i][p] = c * vip - sn * viq; - v[i][q] = c * viq + sn * vip; - } - } - let mut pairs: Vec<(f64, usize)> = (0..n).map(|i| (s[i][i], i)).collect(); - pairs.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); - let mut evals = Vec::with_capacity(n); - let mut evecs = dense::zeros(n, n); - for (col, &(ev, idx)) in pairs.iter().enumerate() { - evals.push(ev); - for row in 0..n { - evecs[row][col] = v[row][idx]; - } - } - Ok((evals, evecs)) -} - -/// Economy SVD via eig of AᵀA (n small). -pub fn svd_decomp(a: &Mat) -> Result<(Mat, Vec, Mat), String> { - let (m, n) = dense::shape(a)?; - // Gram = Aᵀ A (n×n) - let at = dense::transpose(a); - let gram = dense::matmul(&at, a)?; - let (evals, v) = jacobi_symm(&gram)?; - let mut svals = Vec::with_capacity(n.min(m)); - let rank = n.min(m); - for i in 0..rank { - let s = if evals[i] > 0.0 { evals[i].sqrt() } else { 0.0 }; - svals.push(s); - } - // Vt = Vᵀ - let vt = dense::transpose(&v); - // U = A V S^{+} - let mut u = dense::zeros(m, rank); - for j in 0..rank { - if svals[j] < 1e-15 { - continue; - } - // u_j = A v_j / s_j - for i in 0..m { - let mut sum = 0.0; - for k in 0..n { - sum += a[i][k] * v[k][j]; - } - u[i][j] = sum / svals[j]; - } - } - // Truncate Vt to rank rows - let mut vt_r = dense::zeros(rank, n); - for i in 0..rank { - for j in 0..n { - vt_r[i][j] = vt[i][j]; - } - } - let _ = MAX_ELEMENTS; - Ok((u, svals, vt_r)) -} - -pub fn cholesky(a: &Mat) -> Result { - let (n, _) = dense::shape(a)?; - let mut l = dense::zeros(n, n); - for i in 0..n { - for j in 0..=i { - let mut sum = 0.0; - for k in 0..j { - sum += l[i][k] * l[j][k]; - } - if i == j { - let v = a[i][i] - sum; - if v <= 1e-15 { - return Err("Cholesky failed: matrix not positive definite".into()); - } - l[i][j] = v.sqrt(); - } else { - if l[j][j].abs() < 1e-15 { - return Err("Cholesky failed: zero pivot".into()); - } - l[i][j] = (a[i][j] - sum) / l[j][j]; - } - } - } - Ok(l) -} - -/// Forward/back-sub with LU from `factorize kind=lu` (pivots applied to rhs). -pub fn solve_lu_factor(factor: &Value, b: &Mat) -> Result { - if factor.get("kind").and_then(|k| k.as_str()) != Some("lu") { - return Err("solve(factor=…) needs kind=lu factor".into()); - } - let l = dense::from_value(factor.get("L").ok_or_else(|| "factor missing L".to_string())?)?; - let u = dense::from_value(factor.get("U").ok_or_else(|| "factor missing U".to_string())?)?; - let piv = factor - .get("pivots") - .and_then(|p| p.as_array()) - .ok_or_else(|| "factor missing pivots".to_string())?; - let (n, _) = dense::shape(&l)?; - let (br, bc) = dense::shape(b)?; - if br != n { - return Err(format!("rhs rows {br} != factor size {n}")); - } - let mut pb = dense::zeros(n, bc); - for (i, p) in piv.iter().enumerate() { - let src = p - .as_u64() - .or_else(|| p.as_i64().map(|x| x as u64)) - .ok_or_else(|| "bad pivot".to_string())? as usize; - if src >= n { - return Err("pivot out of range".into()); - } - for j in 0..bc { - pb[i][j] = b[src][j]; - } - } - // Ly = Pb - let mut y = dense::zeros(n, bc); - for i in 0..n { - for j in 0..bc { - let mut s = pb[i][j]; - for k in 0..i { - s -= l[i][k] * y[k][j]; - } - y[i][j] = s / l[i][i]; - } - } - // Ux = y - let mut x = dense::zeros(n, bc); - for i in (0..n).rev() { - for j in 0..bc { - let mut s = y[i][j]; - for k in (i + 1)..n { - s -= u[i][k] * x[k][j]; - } - if u[i][i].abs() < 1e-15 { - return Err("singular U in LU solve".into()); - } - x[i][j] = s / u[i][i]; - } - } - Ok(x) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn eig_diag() { - let m = vec![vec![2.0, 0.0], vec![0.0, 3.0]]; - let (ev, _) = jacobi_symm(&m).unwrap(); - assert!((ev[0] - 3.0).abs() < 1e-9); - assert!((ev[1] - 2.0).abs() < 1e-9); - } - - #[test] - fn qr_roundtrip() { - let a = vec![vec![1.0, 1.0], vec![0.0, 1.0], vec![1.0, 0.0]]; - let (q, r) = qr_decomp(&a).unwrap(); - let recon = dense::matmul(&q, &r).unwrap(); - for i in 0..3 { - for j in 0..2 { - assert!((recon[i][j] - a[i][j]).abs() < 1e-9); - } - } - } - - #[test] - fn lu_roundtrip_no_pivot_needed() { - let a = vec![vec![2.0, 1.0], vec![1.0, 3.0]]; - let (l, u, _) = lu_decomp(&a).unwrap(); - let recon = dense::matmul(&l, &u).unwrap(); - for i in 0..2 { - for j in 0..2 { - assert!((recon[i][j] - a[i][j]).abs() < 1e-9); - } - } - } - - #[test] - fn lu_solve_reuse() { - let a = vec![vec![2.0, 1.0], vec![1.0, 3.0]]; - let b = vec![vec![5.0], vec![5.0]]; - let f = factorize(&a, "lu").unwrap(); - let x = solve_lu_factor(&f, &b).unwrap(); - assert!((x[0][0] - 2.0).abs() < 1e-9); - assert!((x[1][0] - 1.0).abs() < 1e-9); - } -} diff --git a/plugins/linalg/src/lib.rs b/plugins/linalg/src/lib.rs deleted file mode 100755 index 53f339a..0000000 --- a/plugins/linalg/src/lib.rs +++ /dev/null @@ -1,524 +0,0 @@ -//! Marqdo linalg plugin (C ABI v2): formula-first matrix expressions. - -mod complex; -mod dense; -mod draw; -mod factor; -mod matexpr; -mod metrics; - -use std::os::raw::{c_char, c_int}; - -use serde_json::{json, Value}; - -use marqdo_plugin_sdk::*; - -use matexpr::{Dim, Expr}; - - -macro_rules! la_ffi { - ($name:ident, $body:expr) => { - unsafe extern "C" fn $name( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, - ) -> c_int { - let args = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("{}: {e}", stringify!($name))); - return 1; - } - }; - let r: Result = (|| $body(&args))(); - reply( - out_json, - err_msg, - r.map_err(|e| format!("{}: {e}", stringify!($name))), - ) - } - }; -} - -fn record_plot(svg: &str, path: Option<&str>) -> Result<(), String> { - let mut args = json!({ "svg": svg }); - if let Some(p) = path { - if !p.is_empty() { - args.as_object_mut() - .unwrap() - .insert("path".into(), json!(p)); - } - } - host_query_json_with("record_plot", &args)?; - Ok(()) -} - -fn arg_dim(v: &Value, key: &str) -> Result { - Dim::from_json(v.get(key).ok_or_else(|| format!("missing `{key}`"))?) -} - -fn arg_expr_opt(v: &Value, keys: &[&str]) -> Result { - for k in keys { - if let Some(e) = v.get(*k) { - if !e.is_null() { - return coerce_expr(e); - } - } - } - Err(format!("missing one of {:?}", keys)) -} - -fn coerce_expr(v: &Value) -> Result { - if let Ok(e) = Expr::from_value(v) { - return Ok(e); - } - let data = dense::from_value(v)?; - Ok(Expr::Dense { data }) -} - -fn wrap(expr: Expr) -> Result { - expr.to_value() -} - -la_ffi!(linalg_ping, |_args: &Value| { - Ok(json!({ - "ok": true, - "name": "linalg", - "abi": ABI_VERSION, - "features": [ - "matexpr", - "simplify", - "dense", - "solve", - "block", - "kron", - "factorize", - "draw", - "lstsq", - "norm", - "cond", - "rank", - "complex", - "declare", - ], - })) -}); - -la_ffi!(linalg_symbol, |args: &Value| { - let name = args - .get("name") - .or_else(|| args.get("名")) - .and_then(|x| x.as_str()) - .ok_or_else(|| "missing `name`".to_string())?; - let rows = arg_dim(args, "rows").or_else(|_| arg_dim(args, "行"))?; - let cols = arg_dim(args, "cols").or_else(|_| arg_dim(args, "列"))?; - wrap(matexpr::symbol(name, rows, cols)) -}); - -la_ffi!(linalg_eye, |args: &Value| { - let n = arg_dim(args, "n") - .or_else(|_| arg_dim(args, "阶")) - .or_else(|_| arg_dim(args, "rows"))?; - wrap(matexpr::eye(n)) -}); - -la_ffi!(linalg_zeros, |args: &Value| { - let rows = arg_dim(args, "rows").or_else(|_| arg_dim(args, "行"))?; - let cols = arg_dim(args, "cols").or_else(|_| arg_dim(args, "列"))?; - wrap(matexpr::zeros(rows, cols)) -}); - -la_ffi!(linalg_from_list, |args: &Value| { - let data = args - .get("data") - .or_else(|| args.get("数据")) - .ok_or_else(|| "missing `data`".to_string())?; - if complex::data_has_complex(data) { - return complex::to_dense_value(&complex::from_data(data)?); - } - let m = dense::from_value(data)?; - wrap(matexpr::from_list(m)?) -}); - -la_ffi!(linalg_declare, |args: &Value| { - let table = args - .get("table") - .or_else(|| args.get("rows")) - .or_else(|| args.get("表")) - .or_else(|| args.get("行")) - .ok_or_else(|| "missing `table` (list of {name,rows,cols})".to_string())?; - let rows = table - .as_array() - .ok_or_else(|| "`table` must be a list of row maps".to_string())?; - let tag = args - .get("type_tag") - .or_else(|| args.get("类型标签")) - .and_then(|x| x.as_str()) - .unwrap_or("matrix"); - let mut out = serde_json::Map::new(); - out.insert("_type".into(), json!("matrix_env")); - for (i, row) in rows.iter().enumerate() { - let obj = row - .as_object() - .ok_or_else(|| format!("declare row {i} must be a map"))?; - let name = obj - .get("name") - .or_else(|| obj.get("名")) - .and_then(|x| x.as_str()) - .ok_or_else(|| format!("declare row {i} missing name"))? - .to_string(); - let r = Dim::from_json( - obj.get("rows") - .or_else(|| obj.get("行")) - .ok_or_else(|| format!("declare `{name}` missing rows"))?, - )?; - let c = Dim::from_json( - obj.get("cols") - .or_else(|| obj.get("列")) - .ok_or_else(|| format!("declare `{name}` missing cols"))?, - )?; - let expr = matexpr::symbol(&name, r, c); - let mut v = expr.to_value()?; - if let Some(m) = v.as_object_mut() { - m.insert("_type".into(), json!(tag)); - } - out.insert(name, v); - } - Ok(Value::Object(out)) -}); - -la_ffi!(linalg_mul, |args: &Value| { - let a = arg_expr_opt(args, &["a", "左"])?; - let b = arg_expr_opt(args, &["b", "右"])?; - wrap(matexpr::mul(a, b)?) -}); - -la_ffi!(linalg_add, |args: &Value| { - let a = arg_expr_opt(args, &["a", "左"])?; - let b = arg_expr_opt(args, &["b", "右"])?; - wrap(matexpr::add(a, b)?) -}); - -la_ffi!(linalg_sub, |args: &Value| { - let a = arg_expr_opt(args, &["a", "左"])?; - let b = arg_expr_opt(args, &["b", "右"])?; - wrap(matexpr::sub(a, b)?) -}); - -la_ffi!(linalg_transpose, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - wrap(matexpr::transpose(e)?) -}); - -la_ffi!(linalg_inv, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - wrap(matexpr::inv(e)?) -}); - -la_ffi!(linalg_simplify, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - wrap(matexpr::simplify(e)?) -}); - -fn display_expr(args: &Value, e: matexpr::Expr) -> Result { - let raw = args - .get("raw") - .or_else(|| args.get("原始")) - .and_then(|v| match v { - Value::Bool(b) => Some(*b), - Value::String(s) => Some(matches!(s.to_ascii_lowercase().as_str(), "true" | "1" | "yes")), - _ => v.as_bool(), - }) - .unwrap_or(false); - if raw { - Ok(e) - } else { - matexpr::simplify(e) - } -} - -la_ffi!(linalg_ascii, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - let e = display_expr(args, e)?; - Ok(json!(e.ascii())) -}); - -la_ffi!(linalg_latex, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - let e = display_expr(args, e)?; - Ok(json!(e.latex())) -}); - -la_ffi!(linalg_shape, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - let (r, c) = e.shape()?; - Ok(json!([r.to_json(), c.to_json()])) -}); - -la_ffi!(linalg_show, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - let e = display_expr(args, e)?; - let latex = e.latex(); - let ascii = e.ascii(); - let path = args - .get("path") - .or_else(|| args.get("路径")) - .and_then(|x| x.as_str()) - .filter(|s| !s.is_empty()); - // Minimal SVG so view/plot channel can embed the formula text. - let escaped = latex - .replace('&', "&") - .replace('<', "<") - .replace('>', ">"); - let svg = format!( - "\ -{escaped}" - ); - let _ = record_plot(&svg, path); - let mut out = e.to_value()?; - if let Some(obj) = out.as_object_mut() { - obj.insert("shown".into(), json!(true)); - obj.insert("ascii".into(), json!(ascii)); - obj.insert("latex".into(), json!(latex)); - } - Ok(out) -}); - -la_ffi!(linalg_from_formula, |args: &Value| { - let f = args - .get("formula") - .or_else(|| args.get("公式")) - .or_else(|| args.get("expr")) - .or_else(|| args.get("式")) - .ok_or_else(|| "missing `formula`".to_string())?; - wrap(coerce_expr(f)?) -}); - -la_ffi!(linalg_explicit, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"]).or_else(|_| { - let f = args - .get("formula") - .or_else(|| args.get("公式")) - .ok_or_else(|| "missing `expr`".to_string())?; - coerce_expr(f) - })?; - let e = display_expr(args, e)?; - let m = dense::explicit(&e)?; - dense::to_dense_value(&m) -}); - -la_ffi!(linalg_det, |args: &Value| { - let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?; - Ok(json!(dense::det(&m)?)) -}); - -la_ffi!(linalg_trace, |args: &Value| { - let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?; - Ok(json!(dense::trace(&m)?)) -}); - -la_ffi!(linalg_solve, |args: &Value| { - let b = dense_arg(args, &["b", "B", "rhs", "右"])?; - if let Some(f) = args - .get("factor") - .or_else(|| args.get("分解")) - .filter(|v| !v.is_null()) - { - let x = factor::solve_lu_factor(f, &b)?; - return dense::to_dense_value(&x).map(|xv| { - json!({ - "_type": "linalg_solve", - "method": "lu", - "x": xv, - }) - }); - } - let a = dense_arg(args, &["a", "A", "matrix", "矩阵", "左"])?; - dense::solve_result(&a, &b) -}); - -la_ffi!(linalg_matmul, |args: &Value| { - let a = dense_arg(args, &["a", "左"])?; - let b = dense_arg(args, &["b", "右"])?; - dense::to_dense_value(&dense::matmul(&a, &b)?) -}); - -la_ffi!(linalg_kron, |args: &Value| { - let a = arg_expr_opt(args, &["a", "左"])?; - let b = arg_expr_opt(args, &["b", "右"])?; - wrap(matexpr::kron(a, b)?) -}); - -la_ffi!(linalg_block, |args: &Value| { - let blocks_v = args - .get("blocks") - .or_else(|| args.get("块")) - .ok_or_else(|| "missing `blocks`".to_string())?; - let grid = blocks_v - .as_array() - .ok_or_else(|| "`blocks` must be a list of rows".to_string())?; - let mut blocks = Vec::new(); - for row in grid { - let cells = row - .as_array() - .ok_or_else(|| "each block row must be a list".to_string())?; - let mut r = Vec::new(); - for c in cells { - r.push(coerce_expr(c)?); - } - blocks.push(r); - } - wrap(matexpr::block(blocks)?) -}); - -la_ffi!(linalg_collapse, |args: &Value| { - let e = arg_expr_opt(args, &["expr", "a", "式"])?; - wrap(matexpr::collapse(e)?) -}); - -la_ffi!(linalg_factorize, |args: &Value| { - let m = dense_arg(args, &["matrix", "expr", "a", "矩阵", "式"])?; - let kind = args - .get("kind") - .or_else(|| args.get("类型")) - .and_then(|x| x.as_str()) - .unwrap_or("lu"); - factor::factorize(&m, kind) -}); - -la_ffi!(linalg_draw, |args: &Value| { - let factor_v = args - .get("factor") - .or_else(|| args.get("分解")) - .or_else(|| args.get("expr")) - .or_else(|| args.get("matrix")) - .or_else(|| args.get("式")) - .or_else(|| args.get("矩阵")) - .ok_or_else(|| "missing `factor`".to_string())?; - let kind = args - .get("kind") - .or_else(|| args.get("类型")) - .and_then(|x| x.as_str()); - let path = args - .get("path") - .or_else(|| args.get("路径")) - .and_then(|x| x.as_str()) - .filter(|s| !s.is_empty()); - let theme = args - .get("theme") - .or_else(|| args.get("主题")) - .and_then(|x| x.as_str()) - .map(draw::ThemeName::parse) - .transpose()? - .unwrap_or(draw::ThemeName::Light); - let svg = draw::draw_factor(factor_v, kind, path, theme)?; - let _ = record_plot(&svg, path); - Ok(json!({ - "_type": "linalg_svg", - "kind": kind - .or_else(|| factor_v.get("kind").and_then(|k| k.as_str())) - .unwrap_or("structure"), - "theme": theme.as_str(), - "svg": svg, - })) -}); - -la_ffi!(linalg_lstsq, |args: &Value| { - let a = dense_arg(args, &["a", "A", "matrix", "矩阵", "左"])?; - let b = dense_arg(args, &["b", "B", "rhs", "右"])?; - metrics::lstsq(&a, &b) -}); - -la_ffi!(linalg_norm, |args: &Value| { - let ord = args - .get("ord") - .or_else(|| args.get("order")) - .or_else(|| args.get("范数")) - .and_then(|x| x.as_str()) - .unwrap_or("fro"); - if let Some(v) = args - .get("expr") - .or_else(|| args.get("a")) - .or_else(|| args.get("matrix")) - .or_else(|| args.get("式")) - .or_else(|| args.get("矩阵")) - { - if v.get("dtype").and_then(|d| d.as_str()) == Some("complex") - || complex::from_value(v).is_ok() - { - if !matches!(ord, "fro" | "frobenius" | "f" | "") { - return Err("complex norm only supports fro for now".into()); - } - let cm = complex::from_value(v).or_else(|_| { - v.get("data") - .ok_or_else(|| "missing complex data".to_string()) - .and_then(complex::from_data) - })?; - return Ok(json!(complex::frobenius_norm(&cm)?)); - } - } - let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?; - Ok(json!(metrics::norm(&m, ord)?)) -}); - -la_ffi!(linalg_cond, |args: &Value| { - let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?; - metrics::cond(&m) -}); - -la_ffi!(linalg_rank, |args: &Value| { - let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?; - Ok(json!(metrics::rank(&m)?)) -}); - -fn dense_arg(args: &Value, keys: &[&str]) -> Result { - for k in keys { - if let Some(v) = args.get(*k) { - if v.is_null() { - continue; - } - if v.get("dtype").and_then(|d| d.as_str()) == Some("complex") { - return Err("real dense op got dtype=complex (use norm fro on complex; factorize/solve stay real)".into()); - } - if let Ok(e) = Expr::from_value(v) { - return dense::explicit(&e); - } - return dense::from_value(v); - } - } - Err(format!("missing dense matrix among {:?}", keys)) -} - -marqdo_plugin!(marqdo_plugin_sdk::ABI_VERSION, [ - ("linalg_ping", "", linalg_ping), - ("linalg_symbol", "name,rows,cols", linalg_symbol), - ("linalg_eye", "n", linalg_eye), - ("linalg_zeros", "rows,cols", linalg_zeros), - ("linalg_from_list", "data", linalg_from_list), - ("linalg_declare", "table,type_tag", linalg_declare), - ("linalg_from_formula", "formula", linalg_from_formula), - ("linalg_mul", "a,b", linalg_mul), - ("linalg_add", "a,b", linalg_add), - ("linalg_sub", "a,b", linalg_sub), - ("linalg_transpose", "expr", linalg_transpose), - ("linalg_inv", "expr", linalg_inv), - ("linalg_simplify", "expr", linalg_simplify), - ("linalg_ascii", "expr,raw", linalg_ascii), - ("linalg_latex", "expr,raw", linalg_latex), - ("linalg_shape", "expr", linalg_shape), - ("linalg_show", "expr,path,raw", linalg_show), - ("linalg_explicit", "expr,raw", linalg_explicit), - ("linalg_det", "expr", linalg_det), - ("linalg_trace", "expr", linalg_trace), - ("linalg_solve", "a,b,factor", linalg_solve), - ("linalg_matmul", "a,b", linalg_matmul), - ("linalg_kron", "a,b", linalg_kron), - ("linalg_block", "blocks", linalg_block), - ("linalg_collapse", "expr", linalg_collapse), - ("linalg_factorize", "matrix,kind", linalg_factorize), - ("linalg_draw", "factor,kind,path,theme", linalg_draw), - ("linalg_lstsq", "a,b", linalg_lstsq), - ("linalg_norm", "expr,ord", linalg_norm), - ("linalg_cond", "expr", linalg_cond), - ("linalg_rank", "expr", linalg_rank), -]); diff --git a/plugins/linalg/src/matexpr.rs b/plugins/linalg/src/matexpr.rs deleted file mode 100755 index a0c079f..0000000 --- a/plugins/linalg/src/matexpr.rs +++ /dev/null @@ -1,1144 +0,0 @@ -//! Symbolic matrix expressions (MatExpr) for formula-first linear algebra. -//! -//! Trees stay abstract until `explicit` (L2). Simplify applies R1–R5. - -use serde_json::{json, Value}; - -#[derive(Debug, Clone, PartialEq)] -pub enum Dim { - Int(usize), - Sym(String), -} - -impl Dim { - pub fn to_json(&self) -> Value { - match self { - Dim::Int(n) => json!(*n), - Dim::Sym(s) => json!(s), - } - } - - pub fn from_json(v: &Value) -> Result { - match v { - Value::Number(n) => { - let u = n - .as_u64() - .or_else(|| n.as_i64().map(|i| i as u64)) - .ok_or_else(|| "bad dim number".to_string())?; - Ok(Dim::Int(u as usize)) - } - Value::String(s) => { - let t = s.trim(); - if let Ok(n) = t.parse::() { - Ok(Dim::Int(n)) - } else { - Ok(Dim::Sym(t.to_string())) - } - } - _ => Err("dim must be int or string".into()), - } - } - - fn ascii(&self) -> String { - match self { - Dim::Int(n) => n.to_string(), - Dim::Sym(s) => s.clone(), - } - } - - fn latex(&self) -> String { - self.ascii() - } -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Expr { - Symbol { - name: String, - rows: Dim, - cols: Dim, - }, - Eye { - n: Dim, - }, - Zero { - rows: Dim, - cols: Dim, - }, - Dense { - data: Vec>, - }, - Mul { - factors: Vec, - }, - Add { - terms: Vec, - }, - Sub { - left: Box, - right: Box, - }, - Transpose { - arg: Box, - }, - Inv { - arg: Box, - }, - /// Block matrix grid (rows of block rows). - Block { - blocks: Vec>, - }, - /// Kronecker product (lazy; do not expand by default). - Kron { - factors: Vec, - }, -} - -impl Expr { - pub fn shape(&self) -> Result<(Dim, Dim), String> { - match self { - Expr::Symbol { rows, cols, .. } => Ok((rows.clone(), cols.clone())), - Expr::Eye { n } => Ok((n.clone(), n.clone())), - Expr::Zero { rows, cols } => Ok((rows.clone(), cols.clone())), - Expr::Dense { data } => { - let r = data.len(); - let c = data.first().map(|row| row.len()).unwrap_or(0); - if data.iter().any(|row| row.len() != c) { - return Err("dense matrix rows must have equal length".into()); - } - Ok((Dim::Int(r), Dim::Int(c))) - } - Expr::Mul { factors } => { - if factors.is_empty() { - return Err("empty MatMul".into()); - } - let (rows, mut cols) = factors[0].shape()?; - for f in &factors[1..] { - let (r, c) = f.shape()?; - if !dims_eq(&cols, &r) { - return Err(format!( - "incompatible shapes for mul: …×{} with {}×{}", - cols.ascii(), - r.ascii(), - c.ascii() - )); - } - cols = c; - } - Ok((rows, cols)) - } - Expr::Add { terms } => { - if terms.is_empty() { - return Err("empty MatAdd".into()); - } - let (r0, c0) = terms[0].shape()?; - for t in &terms[1..] { - let (r, c) = t.shape()?; - if !dims_eq(&r0, &r) || !dims_eq(&c0, &c) { - return Err(format!( - "incompatible shapes for add: {}×{} vs {}×{}", - r0.ascii(), - c0.ascii(), - r.ascii(), - c.ascii() - )); - } - } - Ok((r0, c0)) - } - Expr::Sub { left, right } => { - let (r0, c0) = left.shape()?; - let (r1, c1) = right.shape()?; - if !dims_eq(&r0, &r1) || !dims_eq(&c0, &c1) { - return Err(format!( - "incompatible shapes for sub: {}×{} vs {}×{}", - r0.ascii(), - c0.ascii(), - r1.ascii(), - c1.ascii() - )); - } - Ok((r0, c0)) - } - Expr::Transpose { arg } => { - let (r, c) = arg.shape()?; - Ok((c, r)) - } - Expr::Inv { arg } => { - let (r, c) = arg.shape()?; - if !dims_eq(&r, &c) { - return Err(format!( - "inverse needs square matrix, got {}×{}", - r.ascii(), - c.ascii() - )); - } - Ok((r, c)) - } - Expr::Block { blocks } => block_shape(blocks), - Expr::Kron { factors } => { - if factors.is_empty() { - return Err("empty Kronecker product".into()); - } - let (mut rows, mut cols) = factors[0].shape()?; - for f in &factors[1..] { - let (r, c) = f.shape()?; - rows = dim_mul(&rows, &r)?; - cols = dim_mul(&cols, &c)?; - } - Ok((rows, cols)) - } - } - } - - pub fn ascii(&self) -> String { - match self { - Expr::Symbol { name, .. } => name.clone(), - Expr::Eye { n } => format!("I({})", n.ascii()), - Expr::Zero { rows, cols } => format!("0({}×{})", rows.ascii(), cols.ascii()), - Expr::Dense { data } => format_dense_ascii(data), - Expr::Mul { factors } => factors - .iter() - .map(|f| { - let s = f.ascii(); - if matches!(f, Expr::Add { .. } | Expr::Sub { .. }) { - format!("({s})") - } else { - s - } - }) - .collect::>() - .join("*"), - Expr::Add { terms } => terms - .iter() - .map(|t| t.ascii()) - .collect::>() - .join(" + "), - Expr::Sub { left, right } => format!("{} - {}", left.ascii(), right.ascii()), - Expr::Transpose { arg } => { - let inner = arg.ascii(); - if matches!( - arg.as_ref(), - Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } - ) { - format!("{inner}^T") - } else { - format!("({inner})^T") - } - } - Expr::Inv { arg } => { - let inner = arg.ascii(); - if matches!( - arg.as_ref(), - Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } - ) { - format!("{inner}^-1") - } else { - format!("({inner})^-1") - } - } - Expr::Block { blocks } => { - let rows: Vec = blocks - .iter() - .map(|row| { - let cells: Vec = row.iter().map(|b| b.ascii()).collect(); - format!("[{}]", cells.join(", ")) - }) - .collect(); - format!("Block[{}]", rows.join("; ")) - } - Expr::Kron { factors } => factors - .iter() - .map(|f| { - let s = f.ascii(); - if matches!( - f, - Expr::Add { .. } | Expr::Sub { .. } | Expr::Mul { .. } | Expr::Block { .. } - ) { - format!("({s})") - } else { - s - } - }) - .collect::>() - .join("⊗"), - } - } - - pub fn latex(&self) -> String { - match self { - Expr::Symbol { name, .. } => name.clone(), - Expr::Eye { n } => format!("I_{{{}}}", n.latex()), - Expr::Zero { rows, cols } => { - format!("0_{{{}\\times {}}}", rows.latex(), cols.latex()) - } - Expr::Dense { data } => format_dense_latex(data), - Expr::Mul { factors } => factors - .iter() - .map(|f| { - let s = f.latex(); - if matches!(f, Expr::Add { .. } | Expr::Sub { .. }) { - format!("\\left({s}\\right)") - } else { - s - } - }) - .collect::>() - .join(""), - Expr::Add { terms } => terms - .iter() - .map(|t| t.latex()) - .collect::>() - .join(" + "), - Expr::Sub { left, right } => format!("{} - {}", left.latex(), right.latex()), - Expr::Transpose { arg } => { - let inner = arg.latex(); - if matches!( - arg.as_ref(), - Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } - ) { - format!("{inner}^{{\\top}}") - } else { - format!("\\left({inner}\\right)^{{\\top}}") - } - } - Expr::Inv { arg } => { - let inner = arg.latex(); - if matches!( - arg.as_ref(), - Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } - ) { - format!("{inner}^{{-1}}") - } else { - format!("\\left({inner}\\right)^{{-1}}") - } - } - Expr::Block { blocks } => { - let body: Vec = blocks - .iter() - .map(|row| { - row.iter() - .map(|b| b.latex()) - .collect::>() - .join(" & ") - }) - .collect(); - format!( - "\\begin{{bmatrix}}{}\\end{{bmatrix}}", - body.join(" \\\\ ") - ) - } - Expr::Kron { factors } => factors - .iter() - .map(|f| { - let s = f.latex(); - if matches!( - f, - Expr::Add { .. } | Expr::Sub { .. } | Expr::Mul { .. } | Expr::Block { .. } - ) { - format!("\\left({s}\\right)") - } else { - s - } - }) - .collect::>() - .join(" \\otimes "), - } - } - - pub fn to_value(&self) -> Result { - let (rows, cols) = self.shape()?; - let mut obj = serde_json::Map::new(); - obj.insert("_type".into(), json!("matrix")); - obj.insert("shape".into(), json!([rows.to_json(), cols.to_json()])); - obj.insert("ascii".into(), json!(self.ascii())); - obj.insert("latex".into(), json!(self.latex())); - match self { - Expr::Symbol { name, rows, cols } => { - obj.insert("kind".into(), json!("symbol")); - obj.insert("name".into(), json!(name)); - obj.insert("rows".into(), rows.to_json()); - obj.insert("cols".into(), cols.to_json()); - } - Expr::Eye { n } => { - obj.insert("kind".into(), json!("eye")); - obj.insert("n".into(), n.to_json()); - } - Expr::Zero { rows, cols } => { - obj.insert("kind".into(), json!("zero")); - obj.insert("rows".into(), rows.to_json()); - obj.insert("cols".into(), cols.to_json()); - } - Expr::Dense { data } => { - obj.insert("kind".into(), json!("dense")); - obj.insert("data".into(), json!(data)); - obj.insert("dtype".into(), json!("real")); - } - Expr::Mul { factors } => { - obj.insert("kind".into(), json!("mul")); - let kids: Result, _> = factors.iter().map(|f| f.to_value()).collect(); - obj.insert("factors".into(), Value::Array(kids?)); - } - Expr::Add { terms } => { - obj.insert("kind".into(), json!("add")); - let kids: Result, _> = terms.iter().map(|t| t.to_value()).collect(); - obj.insert("terms".into(), Value::Array(kids?)); - } - Expr::Sub { left, right } => { - obj.insert("kind".into(), json!("sub")); - obj.insert("left".into(), left.to_value()?); - obj.insert("right".into(), right.to_value()?); - } - Expr::Transpose { arg } => { - obj.insert("kind".into(), json!("transpose")); - obj.insert("arg".into(), arg.to_value()?); - } - Expr::Inv { arg } => { - obj.insert("kind".into(), json!("inv")); - obj.insert("arg".into(), arg.to_value()?); - } - Expr::Block { blocks } => { - obj.insert("kind".into(), json!("block")); - let mut grid = Vec::new(); - for row in blocks { - let mut r = Vec::new(); - for b in row { - r.push(b.to_value()?); - } - grid.push(Value::Array(r)); - } - obj.insert("blocks".into(), Value::Array(grid)); - } - Expr::Kron { factors } => { - obj.insert("kind".into(), json!("kron")); - let kids: Result, _> = factors.iter().map(|f| f.to_value()).collect(); - obj.insert("factors".into(), Value::Array(kids?)); - } - } - Ok(Value::Object(obj)) - } - - pub fn from_value(v: &Value) -> Result { - let obj = v - .as_object() - .ok_or_else(|| "matrix expr must be a map".to_string())?; - // Accept legacy `linalg_expr` and author types `matrix` / `矩阵`. - if let Some(t) = obj.get("_type").and_then(|x| x.as_str()) { - if !matches!(t, "matrix" | "矩阵" | "linalg_expr" | "linalg_dense") { - // still allow untyped maps that have `kind` - } - } - let kind = obj - .get("kind") - .and_then(|x| x.as_str()) - .ok_or_else(|| "missing kind".to_string())?; - match kind { - "symbol" => Ok(Expr::Symbol { - name: obj - .get("name") - .and_then(|x| x.as_str()) - .ok_or_else(|| "symbol missing name")? - .to_string(), - rows: Dim::from_json(obj.get("rows").ok_or("symbol missing rows")?)?, - cols: Dim::from_json(obj.get("cols").ok_or("symbol missing cols")?)?, - }), - "eye" => Ok(Expr::Eye { - n: Dim::from_json(obj.get("n").ok_or("eye missing n")?)?, - }), - "zero" => Ok(Expr::Zero { - rows: Dim::from_json(obj.get("rows").ok_or("zero missing rows")?)?, - cols: Dim::from_json(obj.get("cols").ok_or("zero missing cols")?)?, - }), - "dense" => { - let data = parse_dense(obj.get("data").ok_or("dense missing data")?)?; - Ok(Expr::Dense { data }) - } - "mul" => { - let factors = obj - .get("factors") - .and_then(|x| x.as_array()) - .ok_or("mul missing factors")?; - let factors: Result, _> = - factors.iter().map(Expr::from_value).collect(); - Ok(Expr::Mul { - factors: factors?, - }) - } - "add" => { - let terms = obj - .get("terms") - .and_then(|x| x.as_array()) - .ok_or("add missing terms")?; - let terms: Result, _> = terms.iter().map(Expr::from_value).collect(); - Ok(Expr::Add { terms: terms? }) - } - "sub" => Ok(Expr::Sub { - left: Box::new(Expr::from_value( - obj.get("left").ok_or("sub missing left")?, - )?), - right: Box::new(Expr::from_value( - obj.get("right").ok_or("sub missing right")?, - )?), - }), - "transpose" => Ok(Expr::Transpose { - arg: Box::new(Expr::from_value( - obj.get("arg").ok_or("transpose missing arg")?, - )?), - }), - "inv" => Ok(Expr::Inv { - arg: Box::new(Expr::from_value(obj.get("arg").ok_or("inv missing arg")?)?), - }), - "block" => { - let grid = obj - .get("blocks") - .and_then(|x| x.as_array()) - .ok_or("block missing blocks")?; - let mut blocks = Vec::new(); - for row in grid { - let cells = row - .as_array() - .ok_or("block row must be a list")?; - let row: Result, _> = - cells.iter().map(Expr::from_value).collect(); - blocks.push(row?); - } - let expr = Expr::Block { blocks }; - let _ = expr.shape()?; - Ok(expr) - } - "kron" => { - let factors = obj - .get("factors") - .and_then(|x| x.as_array()) - .ok_or("kron missing factors")?; - let factors: Result, _> = - factors.iter().map(Expr::from_value).collect(); - Ok(Expr::Kron { - factors: flatten_kron(factors?), - }) - }, - other => Err(format!("unknown linalg_expr kind `{other}`")), - } - } -} - -fn dims_eq(a: &Dim, b: &Dim) -> bool { - match (a, b) { - (Dim::Int(x), Dim::Int(y)) => x == y, - (Dim::Sym(x), Dim::Sym(y)) => x == y, - // symbolic vs int: allow only if we cannot prove mismatch — treat as compatible - // for teaching formulas like n×n with concrete later; strict mode would reject. - (Dim::Int(_), Dim::Sym(_)) | (Dim::Sym(_), Dim::Int(_)) => true, - } -} - -fn dim_add(a: &Dim, b: &Dim) -> Result { - match (a, b) { - (Dim::Int(x), Dim::Int(y)) => Ok(Dim::Int(x + y)), - (Dim::Sym(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}+{y})"))), - (Dim::Int(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}+{y})"))), - (Dim::Sym(x), Dim::Int(y)) => Ok(Dim::Sym(format!("({x}+{y})"))), - } -} - -fn dim_mul(a: &Dim, b: &Dim) -> Result { - match (a, b) { - (Dim::Int(x), Dim::Int(y)) => Ok(Dim::Int(x.saturating_mul(*y))), - (Dim::Sym(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}*{y})"))), - (Dim::Int(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}*{y})"))), - (Dim::Sym(x), Dim::Int(y)) => Ok(Dim::Sym(format!("({x}*{y})"))), - } -} - -fn block_shape(blocks: &[Vec]) -> Result<(Dim, Dim), String> { - if blocks.is_empty() || blocks[0].is_empty() { - return Err("empty block matrix".into()); - } - let br = blocks.len(); - let bc = blocks[0].len(); - if blocks.iter().any(|row| row.len() != bc) { - return Err("block matrix rows must have equal width".into()); - } - // Row heights: from column 0 - let mut row_heights = Vec::with_capacity(br); - for i in 0..br { - let (h, _) = blocks[i][0].shape()?; - for j in 1..bc { - let (h2, _) = blocks[i][j].shape()?; - if !dims_eq(&h, &h2) { - return Err(format!( - "block row {i}: incompatible heights {} vs {}", - h.ascii(), - h2.ascii() - )); - } - } - row_heights.push(h); - } - // Col widths: from row 0 - let mut col_widths = Vec::with_capacity(bc); - for j in 0..bc { - let (_, w) = blocks[0][j].shape()?; - for i in 1..br { - let (_, w2) = blocks[i][j].shape()?; - if !dims_eq(&w, &w2) { - return Err(format!( - "block col {j}: incompatible widths {} vs {}", - w.ascii(), - w2.ascii() - )); - } - } - col_widths.push(w); - } - let mut rows = row_heights[0].clone(); - for h in &row_heights[1..] { - rows = dim_add(&rows, h)?; - } - let mut cols = col_widths[0].clone(); - for w in &col_widths[1..] { - cols = dim_add(&cols, w)?; - } - Ok((rows, cols)) -} - -fn parse_dense(v: &Value) -> Result>, String> { - let rows = v - .as_array() - .ok_or_else(|| "dense data must be list of rows".to_string())?; - let mut out = Vec::new(); - let mut width = None; - for row in rows { - let cells = row - .as_array() - .ok_or_else(|| "dense row must be a list".to_string())?; - let mut r = Vec::new(); - for c in cells { - let n = c - .as_f64() - .or_else(|| c.as_i64().map(|i| i as f64)) - .or_else(|| c.as_u64().map(|u| u as f64)) - .or_else(|| c.as_str().and_then(|s| s.trim().parse().ok())) - .ok_or_else(|| "dense cell must be a number".to_string())?; - r.push(n); - } - if let Some(w) = width { - if r.len() != w { - return Err("dense matrix rows must have equal length".into()); - } - } else { - width = Some(r.len()); - } - out.push(r); - } - if out.is_empty() { - return Err("empty dense matrix".into()); - } - Ok(out) -} - -fn format_dense_ascii(data: &[Vec]) -> String { - let rows: Vec = data - .iter() - .map(|row| { - let cells: Vec = row.iter().map(|x| format_num(*x)).collect(); - format!("[{}]", cells.join(",")) - }) - .collect(); - format!("[{}]", rows.join(",")) -} - -fn format_dense_latex(data: &[Vec]) -> String { - let body: Vec = data - .iter() - .map(|row| { - row.iter() - .map(|x| format_num(*x)) - .collect::>() - .join(" & ") - }) - .collect(); - format!( - "\\begin{{bmatrix}}{}\\end{{bmatrix}}", - body.join(" \\\\ ") - ) -} - -fn format_num(n: f64) -> String { - if n.fract() == 0.0 && n.abs() < 1e15 { - format!("{}", n as i64) - } else { - format!("{n}") - } -} - -/// Flatten nested Mul. -fn flatten_mul(factors: Vec) -> Vec { - let mut out = Vec::new(); - for f in factors { - match f { - Expr::Mul { factors: inner } => out.extend(flatten_mul(inner)), - other => out.push(other), - } - } - out -} - -fn is_eye(e: &Expr) -> bool { - matches!(e, Expr::Eye { .. }) -} - -fn is_zero(e: &Expr) -> bool { - matches!(e, Expr::Zero { .. }) -} - -/// Apply R1–R5 once bottom-up, then iterate to fixpoint (small bound). -pub fn simplify(expr: Expr) -> Result { - let mut cur = expr; - for _ in 0..32 { - let next = simplify_once(cur.clone())?; - // shape check keeps trees valid - let _ = next.shape()?; - if next == cur { - return Ok(cur); - } - cur = next; - } - Ok(cur) -} - -fn simplify_once(expr: Expr) -> Result { - match expr { - Expr::Mul { factors } => { - let factors: Result, _> = - flatten_mul(factors).into_iter().map(simplify_once).collect(); - let mut factors = factors?; - let eye_n = factors.iter().find_map(|f| match f { - Expr::Eye { n } => Some(n.clone()), - _ => None, - }); - // R1: drop Eye - factors.retain(|f| !is_eye(f)); - if factors.is_empty() { - return Ok(Expr::Eye { - n: eye_n.unwrap_or(Dim::Sym("n".into())), - }); - } - if factors.len() == 1 { - return Ok(factors.pop().unwrap()); - } - // R1 zero absorb: …*0*… → 0 with product shape - if let Some(z) = factors.iter().find(|f| is_zero(f)) { - let (r, _) = factors.first().unwrap().shape()?; - let (_, c) = factors.last().unwrap().shape()?; - let _ = z; - return Ok(Expr::Zero { rows: r, cols: c }); - } - Ok(Expr::Mul { factors }) - } - Expr::Add { terms } => { - let terms: Result, _> = terms.into_iter().map(simplify_once).collect(); - let mut terms = terms?; - let zero_shape = terms.iter().find_map(|t| match t { - Expr::Zero { rows, cols } => Some((rows.clone(), cols.clone())), - _ => None, - }); - terms.retain(|t| !is_zero(t)); - if terms.is_empty() { - let (rows, cols) = zero_shape.unwrap_or((Dim::Int(0), Dim::Int(0))); - return Ok(Expr::Zero { rows, cols }); - } - if terms.len() == 1 { - return Ok(terms.pop().unwrap()); - } - Ok(Expr::Add { terms }) - } - Expr::Sub { left, right } => { - let left = simplify_once(*left)?; - let right = simplify_once(*right)?; - if is_zero(&right) { - return Ok(left); - } - Ok(Expr::Sub { - left: Box::new(left), - right: Box::new(right), - }) - } - Expr::Transpose { arg } => { - let arg = simplify_once(*arg)?; - match arg { - // R3: (AB…)^T → …^T B^T A^T - Expr::Mul { factors } => { - let factors: Vec = factors - .into_iter() - .rev() - .map(|f| Expr::Transpose { - arg: Box::new(f), - }) - .collect(); - simplify_once(Expr::Mul { factors }) - } - // R3: (A^T)^T → A - Expr::Transpose { arg: inner } => Ok(*inner), - // (A+B)^T → A^T+B^T - Expr::Add { terms } => { - let terms = terms - .into_iter() - .map(|t| Expr::Transpose { - arg: Box::new(t), - }) - .collect(); - simplify_once(Expr::Add { terms }) - } - Expr::Sub { left, right } => simplify_once(Expr::Sub { - left: Box::new(Expr::Transpose { arg: left }), - right: Box::new(Expr::Transpose { arg: right }), - }), - // R4 partial: (A^-1)^T → (A^T)^-1 - Expr::Inv { arg: inner } => Ok(Expr::Inv { - arg: Box::new(Expr::Transpose { arg: inner }), - }), - Expr::Eye { n } => Ok(Expr::Eye { n }), - Expr::Zero { rows, cols } => Ok(Expr::Zero { - rows: cols, - cols: rows, - }), - // Block^T → block of transposed tiles, swapped indices - Expr::Block { blocks } => { - if blocks.is_empty() { - return Ok(Expr::Block { blocks }); - } - let br = blocks.len(); - let bc = blocks[0].len(); - let mut out = vec![vec![]; bc]; - for j in 0..bc { - out[j] = Vec::with_capacity(br); - for i in 0..br { - out[j].push(Expr::Transpose { - arg: Box::new(blocks[i][j].clone()), - }); - } - } - simplify_once(Expr::Block { blocks: out }) - } - // (A⊗B)^T → A^T ⊗ B^T - Expr::Kron { factors } => { - let factors = factors - .into_iter() - .map(|f| Expr::Transpose { - arg: Box::new(f), - }) - .collect(); - simplify_once(Expr::Kron { factors }) - } - other => Ok(Expr::Transpose { - arg: Box::new(other), - }), - } - } - Expr::Inv { arg } => { - let arg = simplify_once(*arg)?; - match arg { - // R2: (A^-1)^-1 → A - Expr::Inv { arg: inner } => Ok(*inner), - // R4: (A^T)^-1 stays; (A^-1)^T handled above - Expr::Eye { n } => Ok(Expr::Eye { n }), - other => Ok(Expr::Inv { - arg: Box::new(other), - }), - } - } - Expr::Block { blocks } => { - let mut out = Vec::new(); - for row in blocks { - let mut r = Vec::new(); - for b in row { - r.push(simplify_once(b)?); - } - out.push(r); - } - Ok(Expr::Block { blocks: out }) - } - Expr::Kron { factors } => { - // R7: flatten nested Kronecker - let factors: Result, _> = flatten_kron(factors) - .into_iter() - .map(simplify_once) - .collect(); - let mut factors = factors?; - if factors.len() == 1 { - return Ok(factors.pop().unwrap()); - } - Ok(Expr::Kron { factors }) - } - Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } => { - Ok(expr) - } - } -} - -fn flatten_kron(factors: Vec) -> Vec { - let mut out = Vec::new(); - for f in factors { - match f { - Expr::Kron { factors: inner } => out.extend(flatten_kron(inner)), - other => out.push(other), - } - } - out -} - -/// Block-level collapse (R6 subset): `Block * Block` → block of products. -pub fn collapse(expr: Expr) -> Result { - let expr = simplify(expr)?; - collapse_once(expr) -} - -fn collapse_once(expr: Expr) -> Result { - match expr { - Expr::Mul { factors } => { - let factors: Result, _> = - flatten_mul(factors).into_iter().map(collapse_once).collect(); - let factors = factors?; - let mut acc = factors[0].clone(); - for f in factors.into_iter().skip(1) { - acc = collapse_mul_pair(acc, f)?; - } - Ok(acc) - } - Expr::Block { blocks } => { - let mut out = Vec::new(); - for row in blocks { - let mut r = Vec::new(); - for b in row { - r.push(collapse_once(b)?); - } - out.push(r); - } - Ok(Expr::Block { blocks: out }) - } - Expr::Add { terms } => { - let terms: Result, _> = terms.into_iter().map(collapse_once).collect(); - Ok(Expr::Add { terms: terms? }) - } - Expr::Sub { left, right } => Ok(Expr::Sub { - left: Box::new(collapse_once(*left)?), - right: Box::new(collapse_once(*right)?), - }), - Expr::Transpose { arg } => Ok(Expr::Transpose { - arg: Box::new(collapse_once(*arg)?), - }), - Expr::Inv { arg } => Ok(Expr::Inv { - arg: Box::new(collapse_once(*arg)?), - }), - Expr::Kron { factors } => { - let factors: Result, _> = factors.into_iter().map(collapse_once).collect(); - Ok(Expr::Kron { - factors: flatten_kron(factors?), - }) - } - other => Ok(other), - } -} - -fn collapse_mul_pair(a: Expr, b: Expr) -> Result { - match (a, b) { - (Expr::Block { blocks: left }, Expr::Block { blocks: right }) => { - let lr = left.len(); - let lc = left[0].len(); - let rr = right.len(); - let rc = right[0].len(); - if lc != rr { - return Err(format!( - "block mul: left cols {lc} != right rows {rr}" - )); - } - let mut out = Vec::with_capacity(lr); - for i in 0..lr { - let mut row = Vec::with_capacity(rc); - for j in 0..rc { - let mut term = mul(left[i][0].clone(), right[0][j].clone())?; - for k in 1..lc { - let p = mul(left[i][k].clone(), right[k][j].clone())?; - term = add(term, p)?; - } - row.push(simplify(term)?); - } - out.push(row); - } - let expr = Expr::Block { blocks: out }; - let _ = expr.shape()?; - Ok(expr) - } - (a, b) => { - let expr = Expr::Mul { - factors: flatten_mul(vec![a, b]), - }; - let _ = expr.shape()?; - Ok(expr) - } - } -} - -pub fn mul(a: Expr, b: Expr) -> Result { - let expr = Expr::Mul { - factors: flatten_mul(vec![a, b]), - }; - let _ = expr.shape()?; - Ok(expr) -} - -pub fn add(a: Expr, b: Expr) -> Result { - let expr = Expr::Add { - terms: vec![a, b], - }; - let _ = expr.shape()?; - Ok(expr) -} - -pub fn sub(a: Expr, b: Expr) -> Result { - let expr = Expr::Sub { - left: Box::new(a), - right: Box::new(b), - }; - let _ = expr.shape()?; - Ok(expr) -} - -pub fn transpose(a: Expr) -> Result { - let expr = Expr::Transpose { - arg: Box::new(a), - }; - let _ = expr.shape()?; - Ok(expr) -} - -pub fn inv(a: Expr) -> Result { - let expr = Expr::Inv { - arg: Box::new(a), - }; - let _ = expr.shape()?; - Ok(expr) -} - -pub fn symbol(name: &str, rows: Dim, cols: Dim) -> Expr { - Expr::Symbol { - name: name.to_string(), - rows, - cols, - } -} - -pub fn eye(n: Dim) -> Expr { - Expr::Eye { n } -} - -pub fn zeros(rows: Dim, cols: Dim) -> Expr { - Expr::Zero { rows, cols } -} - -pub fn from_list(data: Vec>) -> Result { - if data.is_empty() { - return Err("empty matrix".into()); - } - let w = data[0].len(); - if w == 0 || data.iter().any(|r| r.len() != w) { - return Err("dense matrix rows must have equal non-zero length".into()); - } - Ok(Expr::Dense { data }) -} - -pub fn block(blocks: Vec>) -> Result { - let expr = Expr::Block { blocks }; - let _ = expr.shape()?; - Ok(expr) -} - -pub fn kron(a: Expr, b: Expr) -> Result { - let expr = Expr::Kron { - factors: flatten_kron(vec![a, b]), - }; - let _ = expr.shape()?; - Ok(expr) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn transpose_of_product() { - let a = symbol("A", Dim::Int(2), Dim::Int(3)); - let b = symbol("B", Dim::Int(3), Dim::Int(2)); - let p = mul(a, b).unwrap(); - let t = transpose(p).unwrap(); - let s = simplify(t).unwrap(); - assert_eq!(s.ascii(), "B^T*A^T"); - } - - #[test] - fn double_inv() { - let a = symbol("A", Dim::Sym("n".into()), Dim::Sym("n".into())); - let i = inv(inv(a).unwrap()).unwrap(); - let s = simplify(i).unwrap(); - assert_eq!(s.ascii(), "A"); - } - - #[test] - fn shape_mismatch() { - let a = symbol("A", Dim::Int(2), Dim::Int(2)); - let b = symbol("B", Dim::Int(3), Dim::Int(3)); - assert!(mul(a, b).is_err()); - } - - #[test] - fn kron_lazy_ascii() { - let a = symbol("A", Dim::Int(2), Dim::Int(2)); - let b = symbol("B", Dim::Int(2), Dim::Int(2)); - let k = kron(a, b).unwrap(); - assert_eq!(k.ascii(), "A⊗B"); - let (r, c) = k.shape().unwrap(); - assert_eq!(r, Dim::Int(4)); - assert_eq!(c, Dim::Int(4)); - } - - #[test] - fn block_collapse_mul() { - let a = symbol("A", Dim::Int(2), Dim::Int(2)); - let b = symbol("B", Dim::Int(2), Dim::Int(2)); - let z = zeros(Dim::Int(2), Dim::Int(2)); - let left = block(vec![ - vec![a.clone(), b.clone()], - vec![z.clone(), a.clone()], - ]) - .unwrap(); - let right = block(vec![ - vec![a.clone(), z.clone()], - vec![z.clone(), b.clone()], - ]) - .unwrap(); - let p = mul(left, right).unwrap(); - let c = collapse(p).unwrap(); - // [[A,B],[0,A]] * [[A,0],[0,B]] → [[A*A, B*B],[0, A*B]] - assert!(matches!(c, Expr::Block { .. })); - assert_eq!(c.ascii(), "Block[[A*A, B*B]; [0(2×2), A*B]]"); - } - - #[test] - fn block_collapse_same_blocks() { - let a = symbol("A", Dim::Int(2), Dim::Int(2)); - let b = symbol("B", Dim::Int(2), Dim::Int(2)); - let z = zeros(Dim::Int(2), Dim::Int(2)); - let m = block(vec![ - vec![a.clone(), b.clone()], - vec![z.clone(), a.clone()], - ]) - .unwrap(); - let p = mul(m.clone(), m).unwrap(); - let c = collapse(p).unwrap(); - assert_eq!( - c.ascii(), - "Block[[A*A, A*B + B*A]; [0(2×2), A*A]]" - ); - } -} diff --git a/plugins/linalg/src/metrics.rs b/plugins/linalg/src/metrics.rs deleted file mode 100755 index 382dd96..0000000 --- a/plugins/linalg/src/metrics.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! Real dense metrics: lstsq, norm, cond, rank (L6). - -use serde_json::{json, Value}; - -use crate::dense::{self, Mat}; -use crate::factor; - -/// Least squares `min ||A x - b||_2`. Tall: thin QR; wide/square: SVD pseudoinverse. -pub fn lstsq(a: &Mat, b: &Mat) -> Result { - let (m, n) = dense::shape(a)?; - let (br, bc) = dense::shape(b)?; - if br != m { - return Err(format!("lstsq: A is {m}×{n} but b has {br} rows")); - } - factor::check_side_limit(m.max(n), "lstsq")?; - let (x, residual_fro, method) = if m >= n { - lstsq_qr(a, b)? - } else { - lstsq_svd(a, b)? - }; - let residual_fro = if bc == 1 { - residual_fro - } else { - // recompute full residual for multi-RHS - let ax = dense::matmul(a, &x)?; - frobenius_diff(&ax, b) - }; - Ok(json!({ - "_type": "linalg_lstsq", - "method": method, - "x": dense::to_dense_value(&x)?, - "residual_fro": residual_fro, - })) -} - -fn lstsq_qr(a: &Mat, b: &Mat) -> Result<(Mat, f64, &'static str), String> { - let (q, r) = factor::qr_decomp(a)?; - let qt = dense::transpose(&q); - let qtb = dense::matmul(&qt, b)?; - let x = dense::solve(&r, &qtb)?; - let ax = dense::matmul(a, &x)?; - Ok((x, frobenius_diff(&ax, b), "qr")) -} - -fn lstsq_svd(a: &Mat, b: &Mat) -> Result<(Mat, f64, &'static str), String> { - let (m, n) = dense::shape(a)?; - let (_, bc) = dense::shape(b)?; - let (u, s, vt) = factor::svd_decomp(a)?; - let rank = n.min(m); - let mut s_inv = vec![0.0; rank]; - let smax = s.first().copied().unwrap_or(0.0); - let tol = smax * (m.max(n) as f64) * f64::EPSILON * 100.0; - for i in 0..rank { - if s[i] > tol { - s_inv[i] = 1.0 / s[i]; - } - } - // x = V Σ⁺ Uᵀ b ; U is m×rank, Vt is rank×n - let ut = dense::transpose(&u); - let utb = dense::matmul(&ut, b)?; // rank×bc - let mut mid = dense::zeros(rank, bc); - for i in 0..rank { - for j in 0..bc { - mid[i][j] = s_inv[i] * utb[i][j]; - } - } - let v = dense::transpose(&vt); // n×rank - let x = dense::matmul(&v, &mid)?; - let ax = dense::matmul(a, &x)?; - Ok((x, frobenius_diff(&ax, b), "svd")) -} - -fn frobenius_diff(a: &Mat, b: &Mat) -> f64 { - let mut s = 0.0; - for (ra, rb) in a.iter().zip(b.iter()) { - for (&x, &y) in ra.iter().zip(rb.iter()) { - let d = x - y; - s += d * d; - } - } - s.sqrt() -} - -/// Matrix norm: `fro` (default), `1`, `inf`, `2`. -pub fn norm(m: &Mat, ord: &str) -> Result { - let (rows, cols) = dense::shape(m)?; - match ord.trim().to_ascii_lowercase().as_str() { - "fro" | "frobenius" | "f" | "" => { - let mut s = 0.0; - for row in m { - for &v in row { - s += v * v; - } - } - Ok(s.sqrt()) - } - "1" | "one" => { - let mut best: f64 = 0.0; - for j in 0..cols { - let mut col = 0.0; - for i in 0..rows { - col += m[i][j].abs(); - } - best = best.max(col); - } - Ok(best) - } - "inf" | "infty" | "∞" => { - let mut best: f64 = 0.0; - for row in m { - let mut r = 0.0; - for &v in row { - r += v.abs(); - } - best = best.max(r); - } - Ok(best) - } - "2" | "spectral" => { - let (_, s, _) = factor::svd_decomp(m)?; - Ok(s.first().copied().unwrap_or(0.0)) - } - other => Err(format!( - "unknown norm `{other}` (want fro|1|inf|2)" - )), - } -} - -/// 2-norm condition number σ_max / σ_min (∞ if rank-deficient). -pub fn cond(m: &Mat) -> Result { - let (rows, cols) = dense::shape(m)?; - let (_, s, _) = factor::svd_decomp(m)?; - let smax = s.first().copied().unwrap_or(0.0); - let smin = s - .iter() - .copied() - .filter(|&x| x > 0.0) - .last() - .unwrap_or(0.0); - let tol = smax * (rows.max(cols) as f64) * f64::EPSILON * 100.0; - let (value, infinite) = if smin <= tol { - (f64::INFINITY, true) - } else { - (smax / smin, false) - }; - Ok(json!({ - "_type": "linalg_cond", - "ord": 2, - "value": if infinite { Value::Null } else { json!(value) }, - "infinite": infinite, - "sigma_max": smax, - "sigma_min": smin, - })) -} - -/// Numerical rank via SVD. -pub fn rank(m: &Mat) -> Result { - let (rows, cols) = dense::shape(m)?; - let (_, s, _) = factor::svd_decomp(m)?; - let smax = s.first().copied().unwrap_or(0.0); - let tol = smax * (rows.max(cols) as f64) * f64::EPSILON * 100.0; - Ok(s.iter().filter(|&&x| x > tol).count()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn lstsq_line_fit() { - // points (0,1), (1,2), (2,2) → line ≈ 1.1667 + 0.5 t - let a = vec![vec![1.0, 0.0], vec![1.0, 1.0], vec![1.0, 2.0]]; - let b = vec![vec![1.0], vec![2.0], vec![2.0]]; - let out = lstsq(&a, &b).unwrap(); - let x = dense::from_value(out.get("x").unwrap()).unwrap(); - assert!((x[0][0] - 7.0 / 6.0).abs() < 1e-9); - assert!((x[1][0] - 0.5).abs() < 1e-9); - } - - #[test] - fn fro_identity() { - let i = dense::eye(3); - assert!((norm(&i, "fro").unwrap() - 3f64.sqrt()).abs() < 1e-12); - } - - #[test] - fn cond_diag() { - let m = vec![vec![2.0, 0.0], vec![0.0, 1.0]]; - let c = cond(&m).unwrap(); - assert_eq!(c["infinite"], false); - assert!((c["value"].as_f64().unwrap() - 2.0).abs() < 1e-9); - assert_eq!(rank(&m).unwrap(), 2); - } -} diff --git a/plugins/llm/Cargo.toml b/plugins/llm/Cargo.toml deleted file mode 100755 index 755aad4..0000000 --- a/plugins/llm/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "marqdo_plugin_llm" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -description = "Marqdo LLM transport plugin (ABI v2) — OpenAI-compatible chat completions" -publish = false - -[lib] -name = "llm" -crate-type = ["cdylib"] - -[dependencies] -marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" } -serde_json = "1" -# Pin with host (edition2024-safe for rustc 1.81). -ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"] } -idna_adapter = { version = "=1.1.0" } -zeroize = { version = "=1.8.1" } diff --git a/plugins/llm/src/lib.rs b/plugins/llm/src/lib.rs deleted file mode 100755 index 57f2553..0000000 --- a/plugins/llm/src/lib.rs +++ /dev/null @@ -1,739 +0,0 @@ -//! Marqdo LLM transport plugin (C ABI v2): OpenAI-compatible chat completions. - -use std::io::{BufRead, BufReader, Read}; -use std::os::raw::{c_char, c_int}; -use std::time::Duration; - -use serde_json::{json, Map, Value}; - -use marqdo_plugin_sdk::*; - -const MAX_BODY: usize = 32 * 1024 * 1024; - -fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty()) -} - -fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - opt_text(args, key).ok_or_else(|| format!("missing text `{key}`")) -} - -fn opt_bool(args: &Value, key: &str, default: bool) -> bool { - match args.get(key) { - None | Some(Value::Null) => default, - Some(Value::Bool(b)) => *b, - Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"), - Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0, - _ => default, - } -} - -fn read_limited(mut r: impl Read) -> Result { - let mut buf = Vec::new(); - let mut chunk = [0u8; 8192]; - loop { - let n = r.read(&mut chunk).map_err(|e| e.to_string())?; - if n == 0 { - break; - } - if buf.len() + n > MAX_BODY { - return Err("response body too large".into()); - } - buf.extend_from_slice(&chunk[..n]); - } - String::from_utf8(buf).map_err(|e| e.to_string()) -} - -/// Prefer null over zero when the provider omitted a field (ModelCallUsageV1 / F04). -fn token_or_null(v: Option) -> Value { - match v { - Some(n) if n >= 0 => json!(n), - _ => Value::Null, - } -} - -fn usage_from(data: &Value) -> Value { - let u = data.get("usage").cloned().unwrap_or(Value::Null); - if u.is_null() || !u.is_object() { - return json!({ - "prompt_tokens": Value::Null, - "completion_tokens": Value::Null, - "total_tokens": Value::Null, - "usage_state": "unknown", - "measurement_source": "none", - }); - } - let pt = u.get("prompt_tokens").and_then(|v| v.as_i64()); - let ct = u.get("completion_tokens").and_then(|v| v.as_i64()); - let tt = u - .get("total_tokens") - .and_then(|v| v.as_i64()) - .or_else(|| match (pt, ct) { - (Some(a), Some(b)) => Some(a + b), - _ => None, - }); - json!({ - "prompt_tokens": token_or_null(pt), - "completion_tokens": token_or_null(ct), - "total_tokens": token_or_null(tt), - "usage_state": "final", - "measurement_source": "provider", - }) -} - -fn tool_calls_from(data: &Value) -> Value { - data.get("choices") - .and_then(|c| c.as_array()) - .and_then(|a| a.first()) - .and_then(|c0| c0.get("message")) - .and_then(|m| m.get("tool_calls")) - .cloned() - .unwrap_or_else(|| json!([])) -} - -fn cancel_requested() -> bool { - // Prefer request-scoped token handle. Empty / "0" ≠ cancel (M-R1). - // When a token path is set, ignore process-global MARQDO_CANCEL so parallel - // tasks cannot cancel each other via shared env. - if let Ok(tok) = std::env::var("MARQDO_CANCEL_TOKEN") { - if !tok.is_empty() { - let path = std::path::Path::new(&tok); - if path.is_file() { - if let Ok(body) = std::fs::read_to_string(path) { - let t = body.trim(); - return t == "1" || t.eq_ignore_ascii_case("cancelled"); - } - } - return false; - } - } - // Legacy single-task CLI only when no token handle is bound. - std::env::var("MARQDO_CANCEL") - .map(|v| v == "1" || v.eq_ignore_ascii_case("true")) - .unwrap_or(false) -} - -/// Mirror host `net::push_openai_delta_events`: append semantic frames to -/// `MARQDO_EVENT_FORWARD` so subtask/web sse-live can flush tokens before the -/// lib call returns (OpenAI-style incremental SSE). -fn forward_event_bus_frame(ev: &Value) { - let Ok(path) = std::env::var("MARQDO_EVENT_FORWARD") else { - return; - }; - if path.is_empty() { - return; - } - use std::io::Write; - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) - { - let _ = writeln!(f, "{ev}"); - let _ = f.flush(); - } -} - -/// Publish `{type:delta|plan|reasoning|error, text|message}` from one OpenAI chunk. -/// `content_type` is usually `delta` (answer tokens) or `plan` (parent protocol LLM). -fn forward_openai_chunk(data: &str, content_type: &str) { - let data = data.trim(); - if data.is_empty() || data == "[DONE]" { - return; - } - let Ok(v) = serde_json::from_str::(data) else { - return; - }; - if let Some(msg) = v.get("error").and_then(|e| { - e.get("message") - .and_then(|m| m.as_str()) - .or_else(|| e.as_str()) - }) { - forward_event_bus_frame(&json!({"type": "error", "message": msg})); - return; - } - let reasoning = v - .pointer("/choices/0/delta/reasoning_content") - .and_then(|c| c.as_str()) - .unwrap_or(""); - if !reasoning.is_empty() { - forward_event_bus_frame(&json!({"type": "reasoning", "text": reasoning})); - } - let content = v - .pointer("/choices/0/delta/content") - .and_then(|c| c.as_str()) - .unwrap_or(""); - if !content.is_empty() { - let ty = if content_type.is_empty() { - "delta" - } else { - content_type - }; - forward_event_bus_frame(&json!({"type": ty, "text": content})); - } -} - -fn parse_sse_events( - reader: impl BufRead, - echo: bool, - content_type: &str, -) -> Result, String> { - let mut events = Vec::new(); - let mut data_lines: Vec = Vec::new(); - let mut accumulated = String::new(); - for line in reader.lines() { - if cancel_requested() { - events.push(json!({"type": "cancelled", "message": "MARQDO_CANCEL"})); - return Ok(events); - } - let line = line.map_err(|e| e.to_string())?; - if echo { - eprint!("{line}\n"); - } - if line.is_empty() { - if !data_lines.is_empty() { - let data = data_lines.join("\n"); - data_lines.clear(); - if data.trim() == "[DONE]" { - // Parent owns run lifecycle `done`; only forward for answer streams. - if content_type == "delta" || content_type.is_empty() { - let done = json!({"type": "done", "result": accumulated}); - forward_event_bus_frame(&done); - } - events.push(json!({"type": "done", "data": "[DONE]"})); - break; - } - forward_openai_chunk(&data, content_type); - if let Ok(v) = serde_json::from_str::(&data) { - if let Some(c) = v - .pointer("/choices/0/delta/content") - .and_then(|x| x.as_str()) - { - accumulated.push_str(c); - } - // Preserve provider usage as a first-class event for llm.collect_usage. - if let Some(u) = v.get("usage").filter(|u| u.is_object()) { - events.push(json!({"type": "usage", "usage": u})); - } - } - events.push(json!({"type": "data", "data": data})); - } - continue; - } - if let Some(rest) = line.strip_prefix("data:") { - data_lines.push(rest.trim_start().to_string()); - } - } - if !data_lines.is_empty() { - let data = data_lines.join("\n"); - if data.trim() == "[DONE]" { - if content_type == "delta" || content_type.is_empty() { - let done = json!({"type": "done", "result": accumulated}); - forward_event_bus_frame(&done); - } - events.push(json!({"type": "done", "data": "[DONE]"})); - } else { - forward_openai_chunk(&data, content_type); - events.push(json!({"type": "data", "data": data})); - } - } - Ok(events) -} - -fn build_messages(args: &Value) -> Result { - if let Some(arr) = args.get("messages").and_then(|v| v.as_array()) { - if arr.is_empty() { - return Err("messages array must not be empty".into()); - } - // Validate minimal role/content shape; reject unsupported part types loudly. - for (i, m) in arr.iter().enumerate() { - let role = m.get("role").and_then(|r| r.as_str()).unwrap_or(""); - if role.is_empty() { - return Err(format!("llm.unsupported_input: messages[{i}].role missing")); - } - if let Some(parts) = m.get("content").and_then(|c| c.as_array()) { - for (j, p) in parts.iter().enumerate() { - let ty = p.get("type").and_then(|t| t.as_str()).unwrap_or("text"); - if ty != "text" { - return Err(format!( - "llm.unsupported_input: messages[{i}].content[{j}] type={ty}" - )); - } - } - } - } - return Ok(Value::Array(arr.clone())); - } - let prompt = arg_text(args, "prompt")?; - Ok(json!([{"role": "user", "content": prompt}])) -} - -fn chat_completions(args: &Value) -> Result { - if cancel_requested() { - return Ok(json!({ - "text": "", - "usage": { - "prompt_tokens": Value::Null, - "completion_tokens": Value::Null, - "total_tokens": Value::Null, - "usage_state": "unknown", - "measurement_source": "none", - }, - "finish": "cancelled", - "error": "cancelled", - "tool_calls": [], - "transport": "plugin", - })); - } - // Strict selection mode: refuse env fallback when selection.strict is set. - let strict = opt_bool(args, "strict_selection", false) - || args - .get("selection") - .and_then(|s| s.get("strict")) - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let selection = args.get("selection").cloned(); - if strict { - if selection.is_none() { - return Err("llm.selection_missing:selection".into()); - } - let sel = selection.as_ref().unwrap(); - for key in ["selection_id", "provider_id", "model_id", "upstream_model_id"] { - if sel - .get(key) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .is_none() - { - return Err(format!("llm.selection_missing:{key}")); - } - } - } - - let base_url = match arg_text(args, "base_url") { - Ok(u) => u, - Err(_) if strict => return Err("llm.selection_missing:base_url".into()), - Err(e) => return Err(e), - }; - let auth_mode = opt_text(args, "auth_mode") - .or_else(|| { - selection - .as_ref() - .and_then(|s| s.get("auth_mode")) - .and_then(|v| v.as_str()) - }) - .unwrap_or("api_key"); - let api_key = if auth_mode == "none" { - "" - } else { - arg_text(args, "api_key").unwrap_or("") - }; - if strict && auth_mode != "none" && api_key.is_empty() { - return Err("llm.selection_missing:api_key".into()); - } - let model = selection - .as_ref() - .and_then(|s| s.get("upstream_model_id")) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .or_else(|| arg_text(args, "model").ok().map(|s| s.to_string())) - .ok_or_else(|| "missing text `model`".to_string())?; - let messages = build_messages(args)?; - let stream = opt_bool(args, "stream", false); - let echo = opt_bool(args, "echo", false); - // Answer tokens → "delta"; parent plan protocol → "plan" (UI process trail). - let stream_kind = opt_text(args, "stream_kind").unwrap_or("delta"); - let suffix = opt_text(args, "suffix").unwrap_or("/chat/completions"); - let bearer = opt_text(args, "bearer").unwrap_or("Bearer "); - - let url = format!("{}{}", base_url.trim_end_matches('/'), suffix); - if !(url.starts_with("http://") || url.starts_with("https://")) { - return Err("url must start with http:// or https://".into()); - } - - let mut req_body = Map::new(); - req_body.insert("model".into(), Value::String(model.clone())); - req_body.insert("messages".into(), messages); - if let Some(params) = selection - .as_ref() - .and_then(|s| s.get("parameters")) - .and_then(|p| p.as_object()) - { - if let Some(max) = params.get("max_output_tokens").and_then(|v| v.as_u64()) { - req_body.insert("max_tokens".into(), json!(max)); - } - if let Some(temp) = params.get("temperature") { - req_body.insert("temperature".into(), temp.clone()); - } - } - if stream { - req_body.insert("stream".into(), Value::Bool(true)); - // OpenAI / DeepSeek / compatible: final SSE chunk carries usage only when requested. - req_body.insert( - "stream_options".into(), - json!({ "include_usage": true }), - ); - } - let body = Value::Object(req_body).to_string(); - let auth = format!("{bearer}{api_key}"); - - let agent = ureq::AgentBuilder::new() - .timeout_connect(Duration::from_secs(15)) - .timeout_read(Duration::from_secs(120)) - .build(); - let mut req = agent - .post(&url) - .set("User-Agent", "marqdo-plugin-llm") - .set("Content-Type", "application/json; charset=utf-8"); - if stream { - req = req.set("Accept", "text/event-stream"); - } - if !api_key.is_empty() { - req = req.set("Authorization", &auth); - } - - if stream { - match req.send_string(&body) { - Ok(r) => { - let status = r.status(); - if status != 200 { - let text = read_limited(r.into_reader())?; - return Ok(json!({ - "events": [{"type": "error", "message": format!("HTTP {status}: {text}")}], - "finish": "error", - "error": format!("HTTP {status}: {text}"), - "transport": "plugin", - })); - } - let events = - parse_sse_events(BufReader::new(r.into_reader()), echo, stream_kind)?; - Ok(json!({ - "events": events, - "finish": "stop", - "transport": "plugin", - })) - } - Err(ureq::Error::Status(code, r)) => { - let text = read_limited(r.into_reader()).unwrap_or_default(); - Ok(json!({ - "events": [{"type": "error", "message": format!("HTTP {code}: {text}")}], - "finish": "error", - "error": format!("HTTP {code}: {text}"), - "transport": "plugin", - })) - } - Err(e) => Ok(json!({ - "events": [{"type": "error", "message": format!("http POST sse {url}: {e}")}], - "finish": "error", - "error": format!("http POST sse {url}: {e}"), - "transport": "plugin", - })), - } - } else { - match req.send_string(&body) { - Ok(r) => { - let status = r.status(); - let text = read_limited(r.into_reader())?; - if status != 200 { - return Ok(json!({ - "text": "", - "usage": { - "prompt_tokens": Value::Null, - "completion_tokens": Value::Null, - "total_tokens": Value::Null, - "usage_state": "unknown", - "measurement_source": "none", - }, - "finish": "error", - "error": format!("HTTP {status}: {text}"), - "tool_calls": [], - "transport": "plugin", - "requested_model": model, - "resolved_model": model, - })); - } - let data: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; - let msg = data - .get("choices") - .and_then(|c| c.as_array()) - .and_then(|a| a.first()) - .and_then(|c0| c0.get("message")) - .cloned() - .unwrap_or(json!({})); - // Some gateways (reasoning models) return null content + reasoning_content. - let content = msg - .get("content") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .or_else(|| msg.get("reasoning_content").and_then(|v| v.as_str())) - .unwrap_or("") - .to_string(); - let fr = data - .get("choices") - .and_then(|c| c.as_array()) - .and_then(|a| a.first()) - .and_then(|c0| c0.get("finish_reason")) - .and_then(|v| v.as_str()) - .unwrap_or("stop") - .to_string(); - let resolved = data - .get("model") - .and_then(|v| v.as_str()) - .unwrap_or(model.as_str()) - .to_string(); - Ok(json!({ - "text": content, - "usage": usage_from(&data), - "finish": fr, - "tool_calls": tool_calls_from(&data), - "transport": "plugin", - "requested_model": model, - "resolved_model": resolved, - "selection": selection.as_ref().map(|s| { - let mut snap = s.clone(); - if let Some(obj) = snap.as_object_mut() { - obj.remove("api_key"); - } - snap - }), - })) - } - Err(ureq::Error::Status(code, r)) => { - let text = read_limited(r.into_reader()).unwrap_or_default(); - Ok(json!({ - "text": "", - "usage": { - "prompt_tokens": Value::Null, - "completion_tokens": Value::Null, - "total_tokens": Value::Null, - "usage_state": "unknown", - "measurement_source": "none", - }, - "finish": "error", - "error": format!("HTTP {code}: {text}"), - "tool_calls": [], - "transport": "plugin", - "requested_model": model, - "resolved_model": model, - })) - } - Err(e) => Ok(json!({ - "text": "", - "usage": { - "prompt_tokens": Value::Null, - "completion_tokens": Value::Null, - "total_tokens": Value::Null, - "usage_state": "unknown", - "measurement_source": "none", - }, - "finish": "error", - "error": format!("http POST {url}: {e}"), - "tool_calls": [], - "transport": "plugin", - "requested_model": model, - "resolved_model": model, - })), - } - } -} - -unsafe extern "C" fn llm_chat_completions( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let r = (|| { - let args = parse_args(args_json)?; - chat_completions(&args) - })(); - reply(out_json, err_msg, r) -} - -unsafe extern "C" fn llm_ping( - _args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - reply(out_json, err_msg, Ok(json!({"ok": true, "plugin": "llm"}))) -} - -marqdo_plugin!(marqdo_plugin_sdk::ABI_VERSION, [ - ("llm_ping", "", llm_ping), - ("llm_chat_completions", "base_url,api_key,model,prompt,messages,selection,strict_selection,auth_mode,stream,echo,suffix,bearer", llm_chat_completions), -]); - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn f03_messages_preserve_roles_and_reject_image() { - let msgs = build_messages(&json!({ - "messages": [ - {"role": "system", "content": "rules"}, - {"role": "user", "content": "你好"}, - {"role": "assistant", "content": "先前"}, - {"role": "user", "content": "最新用户"} - ] - })) - .unwrap(); - let arr = msgs.as_array().unwrap(); - assert_eq!(arr.len(), 4); - assert_eq!(arr[3]["role"], "user"); - assert_eq!(arr[3]["content"], "最新用户"); - - let err = build_messages(&json!({ - "messages": [{"role": "user", "content": [{"type": "image", "url": "x"}]}] - })) - .unwrap_err(); - assert!(err.contains("unsupported_input"), "{err}"); - } - - #[test] - fn f01_strict_selection_does_not_invent_env_model() { - std::env::remove_var("MARQDO_CANCEL"); - std::env::remove_var("MARQDO_CANCEL_TOKEN"); - let err = chat_completions(&json!({ - "strict_selection": true, - "base_url": "http://127.0.0.1:9", - "api_key": "k", - "prompt": "hi" - // missing selection → must fail before any HTTP - })) - .unwrap_err(); - assert!(err.contains("selection_missing"), "{err}"); - } - - #[test] - fn f06_cancel_short_circuits_before_http() { - // Prefer token file over process-global MARQDO_CANCEL to avoid parallel test races. - let tok = std::env::temp_dir().join(format!("llm-cancel-{}", std::process::id())); - std::fs::write(&tok, "cancelled").unwrap(); - std::env::set_var("MARQDO_CANCEL_TOKEN", &tok); - let out = chat_completions(&json!({ - "base_url": "http://127.0.0.1:9", - "api_key": "k", - "model": "m", - "prompt": "hi" - })); - std::env::remove_var("MARQDO_CANCEL_TOKEN"); - let _ = std::fs::remove_file(&tok); - let out = out.unwrap(); - assert_eq!(out["finish"], "cancelled"); - } - - #[test] - fn f06_empty_cancel_token_is_not_cancelled() { - // sse-live creates an empty token file; that must NOT abort the turn. - let tok = std::env::temp_dir().join(format!("llm-cancel-empty-{}", std::process::id())); - std::fs::write(&tok, "").unwrap(); - std::env::set_var("MARQDO_CANCEL_TOKEN", &tok); - std::env::remove_var("MARQDO_CANCEL"); - assert!(!cancel_requested()); - std::env::remove_var("MARQDO_CANCEL_TOKEN"); - let _ = std::fs::remove_file(&tok); - } - - /// F01: two local endpoints receive distinct models/auth — no cross-talk. - #[test] - fn f01_dual_endpoint_isolation() { - use std::io::{Read, Write}; - use std::net::TcpListener; - use std::sync::{Arc, Mutex}; - use std::thread; - - fn spawn_mock(tag: &'static str, seen: Arc>>) -> String { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - thread::spawn(move || { - if let Ok((mut stream, _)) = listener.accept() { - let mut raw = Vec::new(); - let mut buf = [0u8; 4096]; - loop { - let n = stream.read(&mut buf).unwrap_or(0); - if n == 0 { - break; - } - raw.extend_from_slice(&buf[..n]); - if let Some(pos) = raw.windows(4).position(|w| w == b"\r\n\r\n") { - let header = String::from_utf8_lossy(&raw[..pos]); - let cl = header - .lines() - .find_map(|l| l.strip_prefix("Content-Length:")) - .and_then(|v| v.trim().parse::().ok()) - .unwrap_or(0); - let body_start = pos + 4; - while raw.len() < body_start + cl { - let n = stream.read(&mut buf).unwrap_or(0); - if n == 0 { - break; - } - raw.extend_from_slice(&buf[..n]); - } - break; - } - } - let req = String::from_utf8_lossy(&raw).to_string(); - seen.lock().unwrap().push(format!("{tag}:{req}")); - let body = r#"{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}"#; - let resp = format!( - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", - body.len(), - body - ); - let _ = stream.write_all(resp.as_bytes()); - } - }); - format!("http://{addr}") - } - - let seen_a = Arc::new(Mutex::new(Vec::new())); - let seen_b = Arc::new(Mutex::new(Vec::new())); - let url_a = spawn_mock("A", seen_a.clone()); - let url_b = spawn_mock("B", seen_b.clone()); - - let out_a = chat_completions(&json!({ - "base_url": url_a, - "api_key": "key-a", - "model": "model-a", - "auth_mode": "api_key", - "messages": [{"role":"user","content":"from-a"}], - "selection": { - "selection_id": "sel-a", - "provider_id": "p-a", - "model_id": "m-a", - "upstream_model_id": "model-a", - "strict": true - }, - "strict_selection": true - })) - .unwrap(); - let out_b = chat_completions(&json!({ - "base_url": url_b, - "api_key": "key-b", - "model": "model-b", - "auth_mode": "api_key", - "messages": [{"role":"user","content":"from-b"}], - "selection": { - "selection_id": "sel-b", - "provider_id": "p-b", - "model_id": "m-b", - "upstream_model_id": "model-b", - "strict": true - }, - "strict_selection": true - })) - .unwrap(); - - assert_eq!(out_a["finish"], "stop", "{out_a}"); - assert_eq!(out_b["finish"], "stop", "{out_b}"); - let a = seen_a.lock().unwrap().join("\n"); - let b = seen_b.lock().unwrap().join("\n"); - assert!(a.contains("model-a"), "A saw wrong model: {a}"); - assert!(a.contains("key-a") || a.contains("Authorization"), "{a}"); - assert!(!a.contains("model-b"), "A must not see B's model: {a}"); - assert!(b.contains("model-b"), "B saw wrong model: {b}"); - assert!(!b.contains("model-a"), "B must not see A's model: {b}"); - } -} diff --git a/plugins/quantum/Cargo.toml b/plugins/quantum/Cargo.toml deleted file mode 100755 index 9d5696f..0000000 --- a/plugins/quantum/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "marqdo_plugin_quantum" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -description = "Marqdo quantum simulator plugin (ABI v2)" -publish = false - -[lib] -name = "quantum" -crate-type = ["cdylib"] - -[dependencies] -marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" } -serde = { version = "1", features = ["derive"] } -serde_json = "1" diff --git a/plugins/quantum/src/draw.rs b/plugins/quantum/src/draw.rs deleted file mode 100755 index 734dc6c..0000000 --- a/plugins/quantum/src/draw.rs +++ /dev/null @@ -1,1098 +0,0 @@ -//! Circuit rail SVG (design §7.4 + Q8 viz style). - -use serde_json::Value; - -use crate::sim::{parse_ops, C, Op}; - -const COL_W: f64 = 80.0; -const ROW_H: f64 = 64.0; -const PAD_X: f64 = 24.0; -const PAD_Y: f64 = 36.0; -const LABEL_W: f64 = 52.0; -const GUTTER: f64 = 20.0; -const FONT_MONO: &str = "ui-monospace,Menlo,Consolas,monospace"; -const GATE_W: f64 = 40.0; -const GATE_H: f64 = 40.0; - -/// Legacy aliases used by older advanced-viz helpers until Q8c. -const BOX: &str = "#f7f4ef"; -const STROKE: &str = "#1a1a1a"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ThemeName { - Dark, - Light, - Bw, -} - -impl ThemeName { - pub fn parse(raw: &str) -> Result { - match raw.trim().to_ascii_lowercase().as_str() { - "dark" | "暗" => Ok(Self::Dark), - "light" | "亮" | "浅" => Ok(Self::Light), - "bw" | "mono" | "黑白" => Ok(Self::Bw), - other => Err(format!("unknown theme `{other}` (dark|light|bw)")), - } - } - - pub fn as_str(self) -> &'static str { - match self { - Self::Dark => "dark", - Self::Light => "light", - Self::Bw => "bw", - } - } -} - -#[derive(Clone, Copy)] -struct Theme { - name: ThemeName, - bg: &'static str, - bg2: &'static str, - panel: &'static str, - wire: &'static str, - label: &'static str, - chip: &'static str, - clifford_fill: &'static str, - clifford_ink: &'static str, - phase_fill: &'static str, - phase_ink: &'static str, - rotation_fill: &'static str, - rotation_ink: &'static str, - measure_fill: &'static str, - measure_ink: &'static str, - barrier: &'static str, - ctrl: &'static str, - accent: &'static str, - muted: &'static str, - axis: &'static str, - glow: &'static str, -} - -impl Theme { - fn of(name: ThemeName) -> Self { - match name { - ThemeName::Dark => Self { - name, - bg: "#0a0e14", - bg2: "#141c28", - panel: "#1a2433", - wire: "#6b7f96", - label: "#e8eef6", - chip: "#1e2a3a", - clifford_fill: "#4c6fff", - clifford_ink: "#f2f6ff", - phase_fill: "#2de2e6", - phase_ink: "#042024", - rotation_fill: "#3dd6c6", - rotation_ink: "#041a18", - measure_fill: "#8fa3b8", - measure_ink: "#0a1018", - barrier: "#9aafc0", - ctrl: "#f0f5ff", - accent: "#5b7cfa", - muted: "#93a4b8", - axis: "#7d8fa3", - glow: "#4c6fff", - }, - ThemeName::Light => Self { - name, - bg: "#eef3f9", - bg2: "#ffffff", - panel: "#e2eaf3", - wire: "#4a5a6a", - label: "#15202b", - chip: "#ffffff", - clifford_fill: "#3d5afe", - clifford_ink: "#ffffff", - phase_fill: "#00838f", - phase_ink: "#ffffff", - rotation_fill: "#00897b", - rotation_ink: "#ffffff", - measure_fill: "#546e7a", - measure_ink: "#ffffff", - barrier: "#78909c", - ctrl: "#1a237e", - accent: "#3d5afe", - muted: "#5a6a7a", - axis: "#4a5560", - glow: "#3d5afe", - }, - ThemeName::Bw => Self { - name, - bg: "#ffffff", - bg2: "#f7f7f7", - panel: "#eeeeee", - wire: "#222222", - label: "#111111", - chip: "#f0f0f0", - clifford_fill: "#ffffff", - clifford_ink: "#111111", - phase_fill: "#eeeeee", - phase_ink: "#111111", - rotation_fill: "#f5f5f5", - rotation_ink: "#111111", - measure_fill: "#e8e8e8", - measure_ink: "#111111", - barrier: "#666666", - ctrl: "#111111", - accent: "#333333", - muted: "#555555", - axis: "#222222", - glow: "#888888", - }, - } - } - - fn family_colors(self, family: &str) -> (&'static str, &'static str) { - match family { - "phase" => (self.phase_fill, self.phase_ink), - "rotation" => (self.rotation_fill, self.rotation_ink), - "measure" => (self.measure_fill, self.measure_ink), - "neutral" => (self.measure_fill, self.measure_ink), - _ => (self.clifford_fill, self.clifford_ink), - } - } -} - -fn esc(s: &str) -> String { - s.replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) -} - -fn gate_family(gate: &str) -> &'static str { - match gate { - "I" | "X" | "Y" | "Z" | "H" | "HADAMARD" | "CX" | "CNOT" | "CN" | "SWAP" => "clifford", - "S" | "T" | "RZ" | "CZ" => "phase", - "RX" | "RY" => "rotation", - "MEASURE" | "M" => "measure", - "BARRIER" => "barrier", - _ => "neutral", - } -} - -fn gate_label(op: &Op) -> String { - match op.gate.as_str() { - "RX" => op - .theta - .map(|t| format!("Rx({t:.2})")) - .unwrap_or_else(|| "Rx".into()), - "RY" => op - .theta - .map(|t| format!("Ry({t:.2})")) - .unwrap_or_else(|| "Ry".into()), - "RZ" => op - .theta - .map(|t| format!("Rz({t:.2})")) - .unwrap_or_else(|| "Rz".into()), - "HADAMARD" => "H".into(), - "CNOT" | "CN" => "CX".into(), - other => other.to_string(), - } -} - -fn rail_x0() -> f64 { - PAD_X + LABEL_W + GUTTER -} - -fn y_of(q: usize) -> f64 { - PAD_Y + q as f64 * ROW_H -} - -fn x_of(col: usize) -> f64 { - rail_x0() + (col as f64 + 0.5) * COL_W -} - -/// Draw a circuit diagram as standalone SVG. -pub fn circuit_svg(circuit: &Value, theme: ThemeName) -> Result { - let th = Theme::of(theme); - let qubits = circuit - .get("qubits") - .or_else(|| circuit.get("比特数")) - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) - .ok_or_else(|| "circuit missing qubits".to_string())? as usize; - let ops = parse_ops(circuit)?; - let cols = ops.len().max(1); - let width = (rail_x0() + cols as f64 * COL_W + PAD_X).max(320.0); - let height = PAD_Y * 2.0 + (qubits.saturating_sub(1) as f64) * ROW_H; - let height = height.max(PAD_Y * 2.0 + GATE_H + 8.0); - - let mut body = String::new(); - body.push_str(&svg_defs(&th)); - body.push_str(&format!( - r##" -"##, - w = width, - h = height, - wi = width - 3.0, - hi = height - 3.0, - panel = th.panel, - )); - - let wire_x0 = rail_x0(); - let wire_x1 = width - PAD_X; - let label_x = PAD_X + LABEL_W - 6.0; - for q in 0..qubits { - let y = y_of(q); - // dual-tone wire for depth - body.push_str(&format!( - r##" -"##, - x0 = wire_x0, - x1 = wire_x1, - y = y, - wire = th.wire, - )); - // label chip — wire never crosses text - let chip_w = 38.0; - let chip_h = 22.0; - body.push_str(&format!( - r##" -q{q}"##, - rx = label_x - chip_w / 2.0, - ry = y - chip_h / 2.0, - chip_w = chip_w, - chip_h = chip_h, - chip = th.chip, - panel = th.panel, - lx = label_x, - y = y, - font = FONT_MONO, - fill = th.label, - q = q, - )); - } - - for (col, op) in ops.iter().enumerate() { - let x = x_of(col); - match op.gate.as_str() { - "BARRIER" => { - draw_barrier(&mut body, x, qubits, &th); - } - "MEASURE" | "M" => { - let qs = if op.qubits.is_empty() { - (0..qubits).collect::>() - } else { - op.qubits.clone() - }; - for q in qs { - draw_measure(&mut body, x, q, &th); - } - } - "CX" | "CNOT" | "CN" if op.qubits.len() >= 2 => { - draw_cx(&mut body, x, op.qubits[0], op.qubits[1], &th); - } - "CZ" if op.qubits.len() >= 2 => { - draw_cz(&mut body, x, op.qubits[0], op.qubits[1], &th); - } - "SWAP" if op.qubits.len() >= 2 => { - draw_swap(&mut body, x, op.qubits[0], op.qubits[1], &th); - } - _ => { - let q = *op.qubits.first().unwrap_or(&0); - let fam = gate_family(&op.gate); - draw_box(&mut body, x, q, &gate_label(op), fam, &th); - } - } - } - - Ok(format!( - r##"{body}"##, - w = width, - h = height, - theme = th.name.as_str(), - body = body, - )) -} - -fn svg_defs(th: &Theme) -> String { - format!( - r##" - - - - - - - - - - - - -"##, - bg = th.bg, - bg2 = th.bg2, - glow = th.glow, - ) -} - -fn draw_box(out: &mut String, x: f64, q: usize, label: &str, family: &str, th: &Theme) { - let y = y_of(q); - let w = GATE_W; - let h = GATE_H; - let (fill, ink) = th.family_colors(family); - out.push_str(&format!( - r##" -{label}"##, - rx = x - w / 2.0, - ry = y - h / 2.0, - w = w, - h = h, - fill = fill, - ink = ink, - fam = family, - x = x, - y = y, - font = FONT_MONO, - label = esc(label), - )); -} - -fn draw_barrier(out: &mut String, x: f64, qubits: usize, th: &Theme) { - let y0 = y_of(0) - 20.0; - let y1 = y_of(qubits.saturating_sub(1)) + 20.0; - out.push_str(&format!( - r##""##, - x = x, - y0 = y0, - y1 = y1, - c = th.barrier, - )); -} - -fn draw_measure(out: &mut String, x: f64, q: usize, th: &Theme) { - let y = y_of(q); - let w = GATE_W; - let h = GATE_H; - let (fill, ink) = th.family_colors("measure"); - out.push_str(&format!( - r##" - -"##, - rx = x - w / 2.0, - ry = y - h / 2.0, - w = w, - h = h, - fill = fill, - ink = ink, - x0 = x - 11.0, - y0 = y + 4.0, - x1 = x + 11.0, - x = x, - y1 = y + 4.0, - x2 = x + 8.0, - y2 = y - 8.0, - )); -} - -fn draw_cx(out: &mut String, x: f64, control: usize, target: usize, th: &Theme) { - let yc = y_of(control); - let yt = y_of(target); - let (fill, _) = th.family_colors("clifford"); - let r = 13.0; - out.push_str(&format!( - r##" - - - -"##, - x = x, - yc = yc, - yt = yt, - ctrl = th.ctrl, - fill = fill, - r = r, - a = yt - r, - b = yt + r, - a2 = x - r, - b2 = x + r, - )); -} - -fn draw_cz(out: &mut String, x: f64, control: usize, target: usize, th: &Theme) { - let yc = y_of(control); - let yt = y_of(target); - out.push_str(&format!( - r##" - -"##, - x = x, - yc = yc, - yt = yt, - c = th.phase_fill, - )); -} - -fn draw_swap(out: &mut String, x: f64, a: usize, b: usize, th: &Theme) { - let ya = y_of(a); - let yb = y_of(b); - out.push_str(&format!( - r##""##, - x = x, - ya = ya, - yb = yb, - c = th.ctrl, - )); - for y in [ya, yb] { - out.push_str(&format!( - r##" -"##, - x0 = x - 10.0, - y0 = y - 10.0, - x1 = x + 10.0, - y1 = y + 10.0, - c = th.ctrl, - )); - } -} - -/// Probability histogram from basis-label → probability map. -pub fn probs_svg(probs: &serde_json::Map, theme: ThemeName) -> String { - let th = Theme::of(theme); - let mut entries: Vec<(String, f64)> = probs - .iter() - .filter_map(|(k, v)| v.as_f64().map(|p| (k.clone(), p))) - .collect(); - entries.sort_by(|a, b| a.0.cmp(&b.0)); - if entries.is_empty() { - entries.push(("∅".into(), 0.0)); - } - let n = entries.len().max(1); - let bar_w = 36.0; - let gap = 12.0; - let chart_h = 120.0; - let pad_l = 40.0; - let pad_b = 36.0; - let pad_t = 24.0; - let pad_r = 16.0; - let width = pad_l + n as f64 * (bar_w + gap) + pad_r; - let height = pad_t + chart_h + pad_b; - let mut body = String::new(); - body.push_str(&svg_defs(&th)); - body.push_str(&format!( - r##""##, - w = width, - h = height, - )); - body.push_str(&format!( - r##""##, - x0 = pad_l - 4.0, - x1 = width - pad_r, - y = pad_t + chart_h, - axis = th.axis, - )); - body.push_str(&format!( - r##""##, - x = pad_l - 4.0, - y0 = pad_t, - y1 = pad_t + chart_h, - axis = th.axis, - )); - body.push_str(&format!( - r##"1"##, - ty = pad_t + 4.0, - font = FONT_MONO, - lab = th.label, - )); - body.push_str(&format!( - r##"0"##, - ty = pad_t + chart_h + 4.0, - font = FONT_MONO, - lab = th.label, - )); - for (i, (label, p)) in entries.iter().enumerate() { - let p = (*p).clamp(0.0, 1.0); - let h = p * chart_h; - let x = pad_l + i as f64 * (bar_w + gap); - let y = pad_t + chart_h - h; - body.push_str(&format!( - r##""##, - x = x, - y = y, - bar_w = bar_w, - h = h.max(0.5), - fill = th.accent, - ink = th.ctrl, - )); - body.push_str(&format!( - r##"{lab_t}"##, - cx = x + bar_w / 2.0, - ty = pad_t + chart_h + 18.0, - font = FONT_MONO, - lab = th.label, - lab_t = esc(label), - )); - body.push_str(&format!( - r##"{pval:.2}"##, - cx = x + bar_w / 2.0, - ty = y - 5.0, - font = FONT_MONO, - muted = th.muted, - pval = p, - )); - } - format!( - r##"{body}"##, - w = width, - h = height, - theme = th.name.as_str(), - body = body, - ) -} - -/// 2D Bloch sphere projection with state arrow. -pub fn bloch_svg(x: f64, y: f64, z: f64, theme: ThemeName) -> String { - let th = Theme::of(theme); - let cx = 130.0; - let cy = 125.0; - let r = 82.0; - let width = 280.0; - let height = 290.0; - // Project: X right, Z up, Y into page (slight oblique). - let px = |vx: f64, vy: f64, _vz: f64| cx + r * (vx * 0.85 + vy * 0.35); - let py = |_vx: f64, vy: f64, vz: f64| cy - r * (vz * 0.9 - vy * 0.25); - let mut body = String::new(); - body.push_str(&svg_defs(&th)); - body.push_str(&format!( - r##""##, - w = width, - h = height, - )); - body.push_str(&format!( - r##""##, - cx = cx, - cy = cy, - r = r, - fill = th.clifford_fill, - stroke = th.wire, - )); - // axes - let axes = [ - ("+X", 1.0, 0.0, 0.0), - ("-X", -1.0, 0.0, 0.0), - ("+Y", 0.0, 1.0, 0.0), - ("+Z", 0.0, 0.0, 1.0), - ("-Z", 0.0, 0.0, -1.0), - ]; - for (lab, vx, vy, vz) in axes { - let x1 = px(0.0, 0.0, 0.0); - let y1 = py(0.0, 0.0, 0.0); - let x2 = px(vx, vy, vz); - let y2 = py(vx, vy, vz); - body.push_str(&format!( - r##""##, - x1 = x1, - y1 = y1, - x2 = x2, - y2 = y2, - axis = th.axis, - )); - body.push_str(&format!( - r##"{lab}"##, - tx = x2 + 4.0, - ty = y2 + 3.0, - font = FONT_MONO, - lab_c = th.label, - lab = lab, - )); - } - // state vector - let sx = px(x, y, z); - let sy = py(x, y, z); - let ox = px(0.0, 0.0, 0.0); - let oy = py(0.0, 0.0, 0.0); - let arrow = th.phase_fill; - body.push_str(&format!( - r##""##, - ox = ox, - oy = oy, - sx = sx, - sy = sy, - arrow = arrow, - )); - body.push_str(&format!( - r##""##, - sx = sx, - sy = sy, - arrow = arrow, - ctrl = th.ctrl, - )); - body.push_str(&format!( - r##"⟨X⟩={bx:.3} ⟨Y⟩={by:.3} ⟨Z⟩={bz:.3}"##, - hy = height - 12.0, - font = FONT_MONO, - lab = th.label, - bx = x, - by = y, - bz = z, - )); - format!( - r##"{body}"##, - w = width, - h = height, - theme = th.name.as_str(), - body = body, - ) -} - -/// Minimal single-gate glyph for `# gate`.draw. -pub fn gate_svg(name: &str) -> String { - let label = esc(name); - let width = 64.0; - let height = 48.0; - format!( - r#"{label}"#, - w = width, - h = height, - label = label, - BOX = BOX, - STROKE = STROKE, - ) -} - -fn mag(c: C) -> f64 { - (c.re * c.re + c.im * c.im).sqrt() -} - -fn heat_fill(m: f64) -> String { - // pale → indigo by |amp| - let t = m.clamp(0.0, 1.0); - let r = (232.0 + (55.0 - 232.0) * t).round() as i32; - let g = (236.0 + (66.0 - 236.0) * t).round() as i32; - let b = (241.0 + (250.0 - 241.0) * t).round() as i32; - format!("rgb({r},{g},{b})") -} - -/// Complex matrix heatmap (magnitude fill + re/im labels for small dims). -pub fn matrix_heatmap_svg(m: &[Vec], title: &str) -> String { - let n = m.len().max(1); - let cell = if n <= 2 { - 72.0 - } else if n <= 4 { - 56.0 - } else { - 40.0 - }; - let left = 36.0; - let top = 28.0; - let width = left + cell * n as f64 + 16.0; - let height = top + cell * n as f64 + 20.0; - let mut body = String::new(); - body.push_str(&format!( - r#"{title}"#, - title = esc(title), - STROKE = STROKE, - )); - for i in 0..n { - body.push_str(&format!( - r#"{i}"#, - y = top + (i as f64 + 0.55) * cell, - i = i, - muted = "#666", - )); - body.push_str(&format!( - r#"{i}"#, - x = left + (i as f64 + 0.5) * cell, - y = top - 6.0, - i = i, - muted = "#666", - )); - for j in 0..n { - let c = m - .get(i) - .and_then(|row| row.get(j)) - .copied() - .unwrap_or(C { re: 0.0, im: 0.0 }); - let x = left + j as f64 * cell; - let y = top + i as f64 * cell; - let fill = heat_fill(mag(c)); - body.push_str(&format!( - r#""#, - x = x, - y = y, - cell = cell, - fill = fill, - STROKE = STROKE, - )); - if n <= 4 { - let label = if c.im.abs() < 1e-9 { - format!("{:.3}", c.re) - } else if c.re.abs() < 1e-9 { - format!("{:.3}i", c.im) - } else { - format!("{:.2}{:+.2}i", c.re, c.im) - }; - let ink = if mag(c) > 0.55 { "#fff" } else { STROKE }; - body.push_str(&format!( - r#"{lab}"#, - tx = x + cell * 0.5, - ty = y + cell * 0.55, - lab = esc(&label), - ink = ink, - )); - } - } - } - format!( - r#"{body}"#, - w = width, - h = height, - body = body, - ) -} - -fn phase_hue(arg: f64) -> String { - // map [-π,π] → hue degrees - let h = ((arg + std::f64::consts::PI) / (2.0 * std::f64::consts::PI) * 360.0) % 360.0; - format!("hsl({h:.0},70%,45%)") -} - -/// Hinton diagram for density matrix (Q7b). -pub fn hinton_svg(m: &[Vec], title: &str) -> String { - let n = m.len().max(1); - let cell = if n <= 2 { 56.0 } else if n <= 4 { 44.0 } else { 32.0 }; - let left = 40.0; - let top = 28.0; - let width = left + cell * n as f64 + 16.0; - let height = top + cell * n as f64 + 24.0; - let mut max_a: f64 = 1e-12; - for row in m { - for c in row { - max_a = max_a.max(mag(*c)); - } - } - let mut body = String::new(); - body.push_str(&format!( - r#"{title}"#, - title = esc(title), - STROKE = STROKE, - )); - body.push_str(&format!( - r##""##, - left = left, - top = top, - w = cell * n as f64, - h = cell * n as f64, - STROKE = STROKE, - )); - for i in 0..n { - for j in 0..n { - let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero()); - let a = mag(c) / max_a; - let side = (cell * 0.85 * a.sqrt()).max(1.0); - let cx = left + (j as f64 + 0.5) * cell; - let cy = top + (i as f64 + 0.5) * cell; - let fill = if c.re >= 0.0 { "#f5f5f5" } else { "#1a1a1a" }; - let stroke = if c.re >= 0.0 { STROKE } else { "#f5f5f5" }; - body.push_str(&format!( - r#""#, - x = cx - side * 0.5, - y = cy - side * 0.5, - side = side, - fill = fill, - stroke = stroke, - )); - } - } - format!( - r#"{body}"#, - w = width, - h = height, - body = body, - ) -} - -/// Cirq-inspired density: magnitude disk + phase needle; diagonal probability bars. -pub fn density_cells_svg(m: &[Vec], title: &str) -> String { - let n = m.len().max(1); - let cell = if n <= 2 { 64.0 } else if n <= 4 { 48.0 } else { 36.0 }; - let left = 36.0; - let top = 28.0; - let width = left + cell * n as f64 + 16.0; - let height = top + cell * n as f64 + 20.0; - let mut max_a: f64 = 1e-12; - for row in m { - for c in row { - max_a = max_a.max(mag(*c)); - } - } - let mut body = String::new(); - body.push_str(&format!( - r#"{title}"#, - title = esc(title), - STROKE = STROKE, - )); - for i in 0..n { - for j in 0..n { - let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero()); - let x0 = left + j as f64 * cell; - let y0 = top + i as f64 * cell; - body.push_str(&format!( - r##""##, - x0 = x0, - y0 = y0, - cell = cell, - )); - let cx = x0 + cell * 0.5; - let cy = y0 + cell * 0.5; - if i == n - 1 - j || i == j { - // soft diagonal highlight for probability (i==j) - } - if i == j { - let p = c.re.clamp(0.0, 1.0); - let bw = cell * 0.7 * p; - body.push_str(&format!( - r##""##, - x = cx - cell * 0.35, - y = y0 + cell - 10.0, - bw = bw, - )); - } - let r = cell * 0.35 * (mag(c) / max_a).sqrt(); - let arg = c.im.atan2(c.re); - body.push_str(&format!( - r#""#, - cx = cx, - cy = cy, - r = r.max(0.5), - fill = phase_hue(arg), - )); - let nx = cx + r * arg.cos(); - let ny = cy - r * arg.sin(); - body.push_str(&format!( - r#""#, - cx = cx, - cy = cy, - nx = nx, - ny = ny, - STROKE = STROKE, - )); - } - } - format!( - r#"{body}"#, - w = width, - h = height, - body = body, - ) -} - -/// 2.5D cityscape: Re (left) and Im (right) bar grids. -pub fn city_svg(m: &[Vec], title: &str) -> String { - let n = m.len().max(1); - let cell = 28.0; - let left = 40.0; - let top = 40.0; - let gap = 24.0; - let grid_w = cell * n as f64; - let width = left + grid_w * 2.0 + gap + 24.0; - let max_h = 80.0; - let mut max_re: f64 = 1e-12; - let mut max_im: f64 = 1e-12; - for row in m { - for c in row { - max_re = max_re.max(c.re.abs()); - max_im = max_im.max(c.im.abs()); - } - } - let height = top + max_h + cell * n as f64 * 0.35 + 40.0; - let mut body = String::new(); - body.push_str(&format!( - r#"{title} (city)"#, - title = esc(title), - STROKE = STROKE, - )); - body.push_str(r##"Re"##); - body.push_str(&format!( - r##"Im"##, - x = left + grid_w + gap, - )); - let draw_city = |body: &mut String, origin_x: f64, use_re: bool| { - for i in 0..n { - for j in 0..n { - let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero()); - let val = if use_re { c.re } else { c.im }; - let denom = if use_re { max_re } else { max_im }; - let h = (val.abs() / denom) * max_h; - let iso_x = origin_x + (j as f64 - i as f64) * cell * 0.5; - let iso_y = top + (i as f64 + j as f64) * cell * 0.28 + (max_h - h); - let fill = if use_re { "#3a6ea5" } else { "#c45c26" }; - body.push_str(&format!( - r#""#, - iso_x = iso_x, - iso_y = iso_y, - w = cell * 0.45, - h = h.max(0.5), - fill = fill, - STROKE = STROKE, - )); - } - } - }; - draw_city(&mut body, left + grid_w * 0.35, true); - draw_city(&mut body, left + grid_w + gap + grid_w * 0.35, false); - format!( - r#"{body}"#, - w = width, - h = height, - body = body, - ) -} - -/// Pauli expectation bar chart. -pub fn paulivec_svg(labels: &[String], values: &[f64], title: &str) -> String { - let n = labels.len().max(1); - let bar_w = 28.0; - let gap = 8.0; - let left = 48.0; - let top = 28.0; - let chart_h = 120.0; - let width = left + n as f64 * (bar_w + gap) + 16.0; - let height = top + chart_h + 40.0; - let mid_y = top + chart_h * 0.5; - let mut body = String::new(); - body.push_str(&format!( - r#"{title}"#, - title = esc(title), - STROKE = STROKE, - )); - body.push_str(&format!( - r##""##, - left = left, - mid_y = mid_y, - x2 = width - 8.0, - )); - for (i, (lab, val)) in labels.iter().zip(values.iter()).enumerate() { - let x = left + i as f64 * (bar_w + gap); - let h = val.abs().clamp(0.0, 1.0) * (chart_h * 0.45); - let y = if *val >= 0.0 { mid_y - h } else { mid_y }; - body.push_str(&format!( - r##""##, - x = x, - y = y, - bar_w = bar_w, - h = h.max(0.5), - )); - body.push_str(&format!( - r#"{lab}"#, - tx = x + bar_w * 0.5, - ty = top + chart_h + 14.0, - lab = esc(lab), - STROKE = STROKE, - )); - } - format!( - r#"{body}"#, - w = width, - h = height, - body = body, - ) -} - -/// QSphere-style: amplitudes on a circle (phase→angle, amp→radius of marker). -pub fn qsphere_svg(amps: &[C], qubits: usize) -> String { - let dim = amps.len(); - let cx = 160.0; - let cy = 160.0; - let r = 110.0; - let width = 320.0; - let height = 320.0; - let mut body = String::new(); - body.push_str(&format!( - r#""#, - cx = cx, - cy = cy, - r = r, - STROKE = STROKE, - )); - body.push_str(r##"qsphere"##); - for (i, a) in amps.iter().enumerate() { - let amp = mag(*a); - if amp < 1e-9 { - continue; - } - // latitude from Hamming weight, longitude from index - let wt = (i as u32).count_ones() as f64; - let lat = if qubits == 0 { - 0.0 - } else { - std::f64::consts::PI * (wt / qubits as f64 - 0.5) - }; - let lon = 2.0 * std::f64::consts::PI * (i as f64) / (dim as f64); - let rr = r * lat.cos(); - let x = cx + rr * lon.cos(); - let y = cy - r * lat.sin(); - let rad = 4.0 + 14.0 * amp; - let arg = a.im.atan2(a.re); - body.push_str(&format!( - r#""#, - x = x, - y = y, - rad = rad, - fill = phase_hue(arg), - STROKE = STROKE, - )); - } - format!( - r#"{body}"#, - w = width, - h = height, - body = body, - ) -} - -/// Side-by-side Bloch spheres for each qubit. -pub fn multibloch_svg(amps: &[C], qubits: usize) -> Result { - let sphere_w = 140.0; - let width = 16.0 + qubits as f64 * sphere_w; - let height = 160.0; - let mut body = String::new(); - body.push_str(r##"multibloch"##); - for q in 0..qubits { - let (x, y, z) = crate::sim::bloch_vector(amps, qubits, q)?; - // Mini sphere (Q8c will share Theme tokens fully). - let ox = 8.0 + q as f64 * sphere_w; - let cx = ox + 60.0; - let cy = 90.0; - let r = 40.0; - body.push_str(&format!( - r##"q{q}"##, - ox = ox + 8.0, - q = q, - )); - body.push_str(&format!( - r##""##, - cx = cx, - cy = cy, - r = r, - ry = r * 0.55, - STROKE = STROKE, - )); - body.push_str(&format!( - r#""#, - cx = cx, - cy = cy, - r = r, - STROKE = STROKE, - )); - let px = cx + x * r; - let py = cy - z * r * 0.85; - body.push_str(&format!( - r##""##, - cx = cx, - cy = cy, - px = px, - py = py, - )); - let _ = y; - } - Ok(format!( - r#"{body}"#, - w = width, - h = height, - body = body, - )) -} diff --git a/plugins/quantum/src/lib.rs b/plugins/quantum/src/lib.rs deleted file mode 100755 index 74a791f..0000000 --- a/plugins/quantum/src/lib.rs +++ /dev/null @@ -1,835 +0,0 @@ -//! Marqdo quantum plugin (C ABI v2): state-vector circuit simulation. - -mod draw; -mod linalg; -mod sim; - -use std::ffi::{CStr, CString}; -use std::os::raw::{c_char, c_int, c_void}; -use std::ptr; - -use serde_json::{json, Value}; - -use marqdo_plugin_sdk::*; - - -macro_rules! q_ffi { - ($name:ident, $body:expr) => { - unsafe extern "C" fn $name( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, - ) -> c_int { - let args = match parse_args(args_json) { - Ok(v) => v, - Err(e) => { - set_err(err_msg, &format!("{}: {e}", stringify!($name))); - return 1; - } - }; - let r: Result = (|| $body(&args))(); - reply( - out_json, - err_msg, - r.map_err(|e| format!("{}: {e}", stringify!($name))), - ) - } - }; -} - -fn arg_u(v: &Value, key: &str) -> Result { - match v.get(key) { - Some(Value::Number(n)) => n - .as_u64() - .or_else(|| n.as_i64().map(|i| i as u64)) - .map(|u| u as usize) - .ok_or_else(|| format!("bad `{key}`")), - Some(Value::String(s)) => s - .trim() - .parse() - .map_err(|_| format!("bad `{key}`")), - _ => Err(format!("missing `{key}`")), - } -} - -fn arg_f(v: &Value, key: &str) -> Result { - match v.get(key) { - Some(Value::Number(n)) => n - .as_f64() - .ok_or_else(|| format!("bad `{key}`")), - Some(Value::String(s)) => s - .trim() - .parse() - .map_err(|_| format!("bad `{key}`")), - _ => Err(format!("missing `{key}`")), - } -} - -fn circuit_of(args: &Value) -> Result<&Value, String> { - args.get("circuit") - .or_else(|| args.get("电路")) - .ok_or_else(|| "missing `circuit`".to_string()) -} - -fn take_host_string(p: *mut c_char) -> Option { - if p.is_null() { - return None; - } - let s = unsafe { CStr::from_ptr(p) } - .to_str() - .ok() - .map(|s| s.to_string()); - unsafe { - if let Some(free) = HOST_FREE { - free(p as *mut c_void); - } - } - s -} - -fn host_query_json(name: &str, args: &Value) -> Result { - let query = unsafe { HOST_QUERY }.ok_or_else(|| "host_query not available".to_string())?; - let userdata = unsafe { HOST_USERDATA }; - let c_name = CString::new(name).map_err(|e| e.to_string())?; - let c_args = CString::new(args.to_string()).map_err(|e| e.to_string())?; - let mut out_ptr: *mut c_char = ptr::null_mut(); - let mut err_ptr: *mut c_char = ptr::null_mut(); - let rc = unsafe { - query( - userdata, - c_name.as_ptr(), - c_args.as_ptr(), - &mut out_ptr, - &mut err_ptr, - ) - }; - let err = take_host_string(err_ptr); - let out = take_host_string(out_ptr); - if rc != 0 { - return Err(err.unwrap_or_else(|| format!("host_query `{name}` failed"))); - } - let out = out.unwrap_or_else(|| "null".into()); - serde_json::from_str(&out).map_err(|e| format!("host_query `{name}` bad JSON: {e}")) -} - -fn record_plot(svg: &str, path: Option<&str>) -> Result<(), String> { - let mut args = json!({ "svg": svg }); - if let Some(p) = path { - if !p.is_empty() { - args.as_object_mut() - .unwrap() - .insert("path".into(), json!(p)); - } - } - host_query_json("record_plot", &args)?; - Ok(()) -} - -q_ffi!(quantum_ping, |_args: &Value| { - Ok(json!({ - "ok": true, - "name": "quantum", - "abi": ABI_VERSION, - "max_qubits": sim::max_qubits(), - })) -}); - -q_ffi!(quantum_circuit_new, |args: &Value| { - let qubits = arg_u(args, "qubits").or_else(|_| arg_u(args, "比特数"))?; - let steps = args - .get("steps") - .or_else(|| args.get("步骤")) - .filter(|v| !v.is_null()); - sim::circuit_new(qubits, steps) -}); - -q_ffi!(quantum_h, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - sim::push_op(c, "H", vec![q], None) -}); - -q_ffi!(quantum_x, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - sim::push_op(c, "X", vec![q], None) -}); - -q_ffi!(quantum_y, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - sim::push_op(c, "Y", vec![q], None) -}); - -q_ffi!(quantum_z, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - sim::push_op(c, "Z", vec![q], None) -}); - -q_ffi!(quantum_s, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - sim::push_op(c, "S", vec![q], None) -}); - -q_ffi!(quantum_t, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - sim::push_op(c, "T", vec![q], None) -}); - -q_ffi!(quantum_i, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - sim::push_op(c, "I", vec![q], None) -}); - -q_ffi!(quantum_rx, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - let th = arg_f(args, "theta").or_else(|_| arg_f(args, "参数"))?; - sim::push_op(c, "RX", vec![q], Some(th)) -}); - -q_ffi!(quantum_ry, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - let th = arg_f(args, "theta").or_else(|_| arg_f(args, "参数"))?; - sim::push_op(c, "RY", vec![q], Some(th)) -}); - -q_ffi!(quantum_rz, |args: &Value| { - let c = circuit_of(args)?; - let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; - let th = arg_f(args, "theta").or_else(|_| arg_f(args, "参数"))?; - sim::push_op(c, "RZ", vec![q], Some(th)) -}); - -q_ffi!(quantum_cx, |args: &Value| { - let c = circuit_of(args)?; - let control = arg_u(args, "control").or_else(|_| arg_u(args, "控制"))?; - let target = arg_u(args, "target").or_else(|_| arg_u(args, "目标"))?; - sim::push_op(c, "CX", vec![control, target], None) -}); - -q_ffi!(quantum_cz, |args: &Value| { - let c = circuit_of(args)?; - let control = arg_u(args, "control").or_else(|_| arg_u(args, "控制"))?; - let target = arg_u(args, "target").or_else(|_| arg_u(args, "目标"))?; - sim::push_op(c, "CZ", vec![control, target], None) -}); - -q_ffi!(quantum_swap, |args: &Value| { - let c = circuit_of(args)?; - let a = arg_u(args, "a").or_else(|_| arg_u(args, "比特甲"))?; - let b = arg_u(args, "b").or_else(|_| arg_u(args, "比特乙"))?; - sim::push_op(c, "SWAP", vec![a, b], None) -}); - -q_ffi!(quantum_simulate, |args: &Value| { - let c = circuit_of(args)?; - let (qubits, amps) = sim::simulate_circuit(c)?; - Ok(json!({ - "qubits": qubits, - "dim": amps.len(), - "amplitudes": sim::amps_to_json(&s), - })) -}); - -q_ffi!(quantum_probabilities, |args: &Value| { - let c = circuit_of(args)?; - let (qubits, amps) = sim::simulate_circuit(c)?; - Ok(Value::Object(sim::probabilities(&s, qubits))) -}); - -q_ffi!(quantum_run, |args: &Value| { - let c = circuit_of(args)?; - let shots = arg_u(args, "shots") - .or_else(|_| arg_u(args, "次数")) - .unwrap_or(1024); - let seed = arg_u(args, "seed") - .or_else(|_| arg_u(args, "种子")) - .unwrap_or(1) as u64; - sim::run_circuit(c, shots, seed) -}); - -q_ffi!(quantum_barrier, |args: &Value| { - let c = circuit_of(args)?; - sim::push_op(c, "BARRIER", vec![], None) -}); - -q_ffi!(quantum_measure, |args: &Value| { - let c = circuit_of(args)?; - let qs = match args.get("qubits").or_else(|| args.get("比特")) { - None | Some(Value::Null) => vec![], - Some(Value::Array(a)) => a - .iter() - .map(|v| { - v.as_u64() - .or_else(|| v.as_i64().map(|i| i as u64)) - .ok_or_else(|| "bad qubit".to_string()) - .map(|u| u as usize) - }) - .collect::, _>>()?, - Some(Value::Number(n)) => { - vec![n.as_u64().or_else(|| n.as_i64().map(|i| i as u64)).unwrap() as usize] - } - Some(Value::String(s)) => { - if s.trim().is_empty() { - vec![] - } else { - s.split(|c| c == ',' || c == ' ' || c == ',') - .filter(|t| !t.is_empty()) - .map(|t| { - t.trim() - .parse::() - .map_err(|_| format!("bad qubit `{t}`")) - }) - .collect::, _>>()? - } - } - _ => return Err("bad qubits for measure".into()), - }; - sim::push_op(c, "MEASURE", qs, None) -}); - -q_ffi!(quantum_append, |args: &Value| { - let c = circuit_of(args)?; - let op = args - .get("op") - .or_else(|| args.get("操作")) - .ok_or_else(|| "append needs `op`".to_string())?; - sim::append(c, op) -}); - -q_ffi!(quantum_noise, |args: &Value| { - let c = circuit_of(args)?; - let kind = args - .get("kind") - .or_else(|| args.get("种类")) - .and_then(|v| v.as_str()) - .ok_or_else(|| "noise needs `kind`".to_string())?; - let p = arg_f(args, "p").or_else(|_| arg_f(args, "概率"))?; - sim::set_noise(c, kind, p) -}); - -q_ffi!(quantum_state, |args: &Value| { - let c = circuit_of(args)?; - let (qubits, amps) = sim::simulate_circuit(c)?; - Ok(json!({ - "_type": "quantum_state", - "qubits": qubits, - "dim": amps.len(), - "amplitudes": sim::amps_to_json(&s), - })) -}); - -fn draw_theme_of(args: &Value) -> Result { - match args - .get("theme") - .or_else(|| args.get("主题")) - .and_then(|v| v.as_str()) - { - None => Ok(draw::ThemeName::Dark), - Some(s) => draw::ThemeName::parse(s), - } -} - -q_ffi!(quantum_draw_circuit, |args: &Value| { - let c = circuit_of(args)?; - let kind = args - .get("kind") - .or_else(|| args.get("种类")) - .and_then(|v| v.as_str()) - .unwrap_or("circuit") - .to_ascii_lowercase(); - let theme = draw_theme_of(args)?; - let qubit = arg_u(args, "qubit") - .or_else(|_| arg_u(args, "比特")) - .unwrap_or(0); - let path = args - .get("path") - .or_else(|| args.get("路径")) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()); - - let (kind_out, svg) = match kind.as_str() { - "circuit" | "" => ("circuit", draw::circuit_svg(c, theme)?), - "probs" | "probabilities" | "概率" => { - let (qubits, amps) = sim::simulate_circuit(c)?; - let probs = sim::probabilities(&s, qubits); - ("probs", draw::probs_svg(&probs, theme)) - } - "bloch" | "布洛赫" => { - let (qubits, amps) = sim::simulate_circuit(c)?; - let (x, y, z) = sim::bloch_vector(&s, qubits, qubit)?; - ("bloch", draw::bloch_svg(x, y, z, theme)) - } - "hinton" | "欣顿" => { - let (n, amps) = sim::simulate_circuit(c)?; - let (_, rho) = linalg::density_from_amps(&s, n)?; - let nested = linalg::flat_to_nested(&rho, 1 << n); - ("hinton", draw::hinton_svg(&nested, "ρ hinton")) - } - "city" | "城市" => { - let (n, amps) = sim::simulate_circuit(c)?; - let (_, rho) = linalg::density_from_amps(&s, n)?; - let nested = linalg::flat_to_nested(&rho, 1 << n); - ("city", draw::city_svg(&nested, "ρ")) - } - "density" | "密度图" => { - let (n, amps) = sim::simulate_circuit(c)?; - let (_, rho) = linalg::density_from_amps(&s, n)?; - let nested = linalg::flat_to_nested(&rho, 1 << n); - ("density", draw::density_cells_svg(&nested, "ρ")) - } - "paulivec" | "泡利向量" => { - let (n, amps) = sim::simulate_circuit(c)?; - let (_, rho) = linalg::density_from_amps(&s, n)?; - let dim = 1 << n; - let labels = linalg::all_pauli_labels(n)?; - let mut vals = Vec::with_capacity(labels.len()); - for lab in &labels { - vals.push(linalg::expect_pauli(&rho, dim, n, lab)?); - } - ("paulivec", draw::paulivec_svg(&labels, &vals, "Pauli")) - } - "qsphere" | "球" => { - let (n, amps) = sim::simulate_circuit(c)?; - ("qsphere", draw::qsphere_svg(&s, n)) - } - "multibloch" | "多布洛赫" => { - let (n, amps) = sim::simulate_circuit(c)?; - ("multibloch", draw::multibloch_svg(&s, n)?) - } - other => { - return Err(format!( - "unknown draw kind `{other}` (circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch)" - )); - } - }; - - record_plot(&svg, path)?; - let ops_n = c - .get("ops") - .and_then(|v| v.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - let qubits = c - .get("qubits") - .and_then(|v| v.as_u64()) - .unwrap_or(0); - Ok(json!({ - "_type": "quantum_svg", - "kind": kind_out, - "qubits": qubits, - "ops": ops_n, - "svg": svg, - })) -}); - -q_ffi!(quantum_gate_new, |args: &Value| { - let matrix = args.get("matrix").or_else(|| args.get("矩阵")); - if let Some(m) = matrix { - if !m.is_null() { - let name = args - .get("name") - .or_else(|| args.get("名")) - .and_then(|v| v.as_str()); - return sim::gate_from_matrix(m, name); - } - } - let name = args - .get("name") - .or_else(|| args.get("名")) - .and_then(|v| v.as_str()) - .ok_or_else(|| "gate needs `name` or `matrix`".to_string())?; - let theta = match args.get("theta").or_else(|| args.get("参数")) { - None | Some(Value::Null) => None, - Some(v) => Some( - v.as_f64() - .or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())) - .ok_or_else(|| "bad theta".to_string())?, - ), - }; - sim::gate_new(name, theta) -}); - -q_ffi!(quantum_gate_from_matrix, |args: &Value| { - let matrix = args - .get("matrix") - .or_else(|| args.get("矩阵")) - .ok_or_else(|| "missing `matrix`".to_string())?; - let name = args - .get("name") - .or_else(|| args.get("名")) - .and_then(|v| v.as_str()); - sim::gate_from_matrix(matrix, name) -}); - -q_ffi!(quantum_gate_matrix, |args: &Value| { - let gate = args - .get("gate") - .or_else(|| args.get("门")) - .ok_or_else(|| "missing `gate`".to_string())?; - let m = sim::gate_matrix_of(gate)?; - Ok(sim::matrix_to_json(&m)) -}); - -q_ffi!(quantum_gate_matches_matrix, |args: &Value| { - let gate = args - .get("gate") - .or_else(|| args.get("门")) - .ok_or_else(|| "missing `gate`".to_string())?; - let matrix = args - .get("matrix") - .or_else(|| args.get("矩阵")) - .ok_or_else(|| "missing `matrix`".to_string())?; - let tol = args - .get("tol") - .or_else(|| args.get("容差")) - .and_then(|v| v.as_f64()) - .unwrap_or(1e-9); - let expect = sim::gate_matrix_of(gate)?; - let got = sim::parse_matrix(matrix)?; - Ok(json!(sim::matrices_close(&expect, &got, tol))) -}); - -q_ffi!(quantum_gate_draw, |args: &Value| { - let gate = args - .get("gate") - .or_else(|| args.get("门")) - .ok_or_else(|| "missing `gate`".to_string())?; - let name = gate - .get("name") - .or_else(|| gate.get("名")) - .and_then(|v| v.as_str()) - .unwrap_or("?"); - let kind = args - .get("kind") - .or_else(|| args.get("种类")) - .or_else(|| args.get("类型")) - .and_then(|v| v.as_str()) - .unwrap_or("gate") - .to_ascii_lowercase(); - let path = args - .get("path") - .or_else(|| args.get("路径")) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()); - let (kind_out, svg) = if matches!(kind.as_str(), "matrix" | "heatmap" | "矩阵") { - let m = sim::gate_matrix_of(gate)?; - ( - "matrix", - draw::matrix_heatmap_svg(&m, &format!("{name} matrix")), - ) - } else if matches!(kind.as_str(), "gate" | "glyph" | "门") { - ("gate", draw::gate_svg(name)) - } else { - return Err(format!("unknown gate draw kind `{kind}` (gate|matrix)")); - }; - record_plot(&svg, path)?; - Ok(json!({ - "_type": "quantum_svg", - "kind": kind_out, - "svg": svg, - })) -}); - -q_ffi!(quantum_apply, |args: &Value| { - let c = circuit_of(args)?; - let gate = args - .get("gate") - .or_else(|| args.get("门")) - .ok_or_else(|| "missing `gate`".to_string())?; - let qubits = args.get("qubits").or_else(|| args.get("比特")); - sim::apply_gate(c, gate, qubits) -}); - -q_ffi!(quantum_density_from_state, |args: &Value| { - let src = args - .get("state") - .or_else(|| args.get("态")) - .or_else(|| args.get("circuit")) - .or_else(|| args.get("电路")) - .ok_or_else(|| "density needs `state` or `circuit`".to_string())?; - let (n, amps) = linalg::amps_from_state_or_circuit(src)?; - let (_, rho) = linalg::density_from_amps(&s, n)?; - Ok(linalg::density_handle(n, &rho)) -}); - -q_ffi!(quantum_density_from_matrix, |args: &Value| { - let matrix = args - .get("matrix") - .or_else(|| args.get("矩阵")) - .ok_or_else(|| "missing `matrix`".to_string())?; - let bag = json!({ "matrix": matrix }); - let (n, rho) = linalg::parse_density(&bag)?; - Ok(linalg::density_handle(n, &rho)) -}); - -q_ffi!(quantum_density_matrix, |args: &Value| { - let d = args - .get("density") - .or_else(|| args.get("密度")) - .ok_or_else(|| "missing `density`".to_string())?; - let (n, rho) = linalg::parse_density(d)?; - let dim = 1 << n; - Ok(sim::matrix_to_json(&linalg::flat_to_nested(&rho, dim))) -}); - -q_ffi!(quantum_density_purity, |args: &Value| { - let d = args - .get("density") - .or_else(|| args.get("密度")) - .ok_or_else(|| "missing `density`".to_string())?; - let (n, rho) = linalg::parse_density(d)?; - let dim = 1 << n; - Ok(json!(linalg::purity(&rho, dim))) -}); - -q_ffi!(quantum_density_partial_trace, |args: &Value| { - let d = args - .get("density") - .or_else(|| args.get("密度")) - .ok_or_else(|| "missing `density`".to_string())?; - let keep_v = args - .get("keep") - .or_else(|| args.get("保留")) - .ok_or_else(|| "missing `keep`".to_string())?; - let keep = parse_usize_list(keep_v)?; - let (n, rho) = linalg::parse_density(d)?; - let (k, out) = linalg::partial_trace(&rho, n, &keep)?; - Ok(linalg::density_handle(k, &out)) -}); - -q_ffi!(quantum_density_eig, |args: &Value| { - let d = args - .get("density") - .or_else(|| args.get("密度")) - .ok_or_else(|| "missing `density`".to_string())?; - let (n, rho) = linalg::parse_density(d)?; - let dim = 1 << n; - let (evals, evecs) = linalg::hermite_eig(&rho, dim)?; - Ok(linalg::spectrum_handle(&evals, &evecs)) -}); - -q_ffi!(quantum_density_expect, |args: &Value| { - let d = args - .get("density") - .or_else(|| args.get("密度")) - .or_else(|| args.get("state")) - .or_else(|| args.get("态")) - .or_else(|| args.get("circuit")) - .or_else(|| args.get("电路")) - .ok_or_else(|| "expect needs density/state/circuit".to_string())?; - let (n, rho) = if d.get("amplitudes").is_some() - || d.get("_type").and_then(|t| t.as_str()) == Some("quantum_state") - || d.get("ops").is_some() - { - let (qn, amps) = linalg::amps_from_state_or_circuit(d)?; - let (_, r) = linalg::density_from_amps(&s, qn)?; - (qn, r) - } else { - linalg::parse_density(d)? - }; - let dim = 1 << n; - let obs = args - .get("obs") - .or_else(|| args.get("可观测量")) - .ok_or_else(|| "missing `obs`".to_string())?; - let val = if let Some(s) = obs.as_str() { - linalg::expect_pauli(&rho, dim, n, s)? - } else { - let (_od, om) = linalg::value_as_matrix(obs)?; - linalg::expect_matrix(&rho, dim, &om, dim)? - }; - Ok(json!(val)) -}); - -q_ffi!(quantum_density_draw, |args: &Value| { - let d = args - .get("density") - .or_else(|| args.get("密度")) - .ok_or_else(|| "missing `density`".to_string())?; - let kind = args - .get("kind") - .or_else(|| args.get("种类")) - .and_then(|v| v.as_str()) - .unwrap_or("hinton") - .to_ascii_lowercase(); - let path = args - .get("path") - .or_else(|| args.get("路径")) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()); - let (n, rho) = linalg::parse_density(d)?; - let dim = 1 << n; - let nested = linalg::flat_to_nested(&rho, dim); - let (kind_out, svg) = match kind.as_str() { - "hinton" | "欣顿" => ("hinton", draw::hinton_svg(&nested, "ρ hinton")), - "city" | "城市" => ("city", draw::city_svg(&nested, "ρ")), - "density" | "密度图" => ("density", draw::density_cells_svg(&nested, "ρ")), - "paulivec" | "泡利向量" => { - let labels = linalg::all_pauli_labels(n)?; - let mut vals = Vec::with_capacity(labels.len()); - for lab in &labels { - vals.push(linalg::expect_pauli(&rho, dim, n, lab)?); - } - ("paulivec", draw::paulivec_svg(&labels, &vals, "Pauli")) - } - other => { - return Err(format!( - "unknown density draw kind `{other}` (hinton|city|density|paulivec)" - )); - } - }; - record_plot(&svg, path)?; - Ok(json!({ - "_type": "quantum_svg", - "kind": kind_out, - "qubits": n, - "svg": svg, - })) -}); - -q_ffi!(quantum_kron, |args: &Value| { - let a = args - .get("a") - .or_else(|| args.get("左")) - .ok_or_else(|| "kron needs `a`".to_string())?; - let b = args - .get("b") - .or_else(|| args.get("右")) - .ok_or_else(|| "kron needs `b`".to_string())?; - if (a.get("amplitudes").is_some() - || a.get("_type").and_then(|t| t.as_str()) == Some("quantum_state")) - && (b.get("amplitudes").is_some() - || b.get("_type").and_then(|t| t.as_str()) == Some("quantum_state")) - { - let (na, aa) = linalg::amps_from_state_or_circuit(a)?; - let (nb, bb) = linalg::amps_from_state_or_circuit(b)?; - let out = linalg::kronecker_amps(&aa, &bb); - return Ok(json!({ - "_type": "quantum_state", - "qubits": na + nb, - "dim": out.len(), - "amplitudes": sim::amps_to_json(&out), - })); - } - let (_na, ma) = linalg::value_as_matrix(a)?; - let (_nb, mb) = linalg::value_as_matrix(b)?; - let da = (ma.len() as f64).sqrt() as usize; - let db = (mb.len() as f64).sqrt() as usize; - if da * da != ma.len() || db * db != mb.len() { - return Err("kron: matrices must be square".into()); - } - let out = linalg::kronecker(&ma, da, &mb, db); - let dim = da * db; - let qubits_f = (dim as f64).log2(); - if (qubits_f - qubits_f.round()).abs() < 1e-9 { - let qubits = qubits_f.round() as usize; - Ok(linalg::density_handle(qubits, &out)) - } else { - Ok(json!({ - "_type": "quantum_density", - "dim": dim, - "matrix": sim::matrix_to_json(&linalg::flat_to_nested(&out, dim)), - })) - } -}); - -q_ffi!(quantum_schmidt, |args: &Value| { - let src = args - .get("state") - .or_else(|| args.get("态")) - .or_else(|| args.get("circuit")) - .or_else(|| args.get("电路")) - .ok_or_else(|| "schmidt needs `state` or `circuit`".to_string())?; - let cut = arg_u(args, "cut") - .or_else(|_| arg_u(args, "分割")) - .unwrap_or(1); - let (n, amps) = linalg::amps_from_state_or_circuit(src)?; - linalg::schmidt_decompose(&s, n, cut) -}); - -q_ffi!(quantum_fidelity, |args: &Value| { - let a = args - .get("a") - .or_else(|| args.get("左")) - .ok_or_else(|| "fidelity needs `a`".to_string())?; - let b = args - .get("b") - .or_else(|| args.get("右")) - .ok_or_else(|| "fidelity needs `b`".to_string())?; - let (_, aa) = linalg::amps_from_state_or_circuit(a)?; - let (_, bb) = linalg::amps_from_state_or_circuit(b)?; - Ok(json!(linalg::fidelity_pure(&aa, &bb)?)) -}); - -fn parse_usize_list(v: &Value) -> Result, String> { - match v { - Value::Array(a) => a - .iter() - .map(|x| { - x.as_u64() - .or_else(|| x.as_i64().map(|i| i as u64)) - .or_else(|| x.as_str().and_then(|s| s.trim().parse().ok())) - .map(|u| u as usize) - .ok_or_else(|| "bad keep list entry".to_string()) - }) - .collect(), - Value::Number(n) => Ok(vec![n.as_u64().unwrap_or(0) as usize]), - Value::String(s) => s - .split(|c| c == ',' || c == ' ') - .filter(|t| !t.is_empty()) - .map(|t| t.parse().map_err(|_| format!("bad keep `{t}`"))) - .collect(), - _ => Err("keep must be list, number, or comma string".into()), - } -} - -marqdo_plugin!(marqdo_plugin_sdk::ABI_VERSION, [ - ("quantum_ping", "", quantum_ping), - ("quantum_circuit_new", "qubits,steps", quantum_circuit_new), - ("quantum_h", "circuit,qubit", quantum_h), - ("quantum_x", "circuit,qubit", quantum_x), - ("quantum_y", "circuit,qubit", quantum_y), - ("quantum_z", "circuit,qubit", quantum_z), - ("quantum_s", "circuit,qubit", quantum_s), - ("quantum_t", "circuit,qubit", quantum_t), - ("quantum_i", "circuit,qubit", quantum_i), - ("quantum_rx", "circuit,qubit,theta", quantum_rx), - ("quantum_ry", "circuit,qubit,theta", quantum_ry), - ("quantum_rz", "circuit,qubit,theta", quantum_rz), - ("quantum_cx", "circuit,control,target", quantum_cx), - ("quantum_cz", "circuit,control,target", quantum_cz), - ("quantum_swap", "circuit,a,b", quantum_swap), - ("quantum_simulate", "circuit", quantum_simulate), - ("quantum_probabilities", "circuit", quantum_probabilities), - ("quantum_run", "circuit,shots,seed", quantum_run), - ("quantum_barrier", "circuit", quantum_barrier), - ("quantum_measure", "circuit,qubits", quantum_measure), - ("quantum_append", "circuit,op", quantum_append), - ("quantum_noise", "circuit,kind,p", quantum_noise), - ("quantum_state", "circuit", quantum_state), - ("quantum_draw_circuit", "circuit,path,kind,qubit", quantum_draw_circuit), - ("quantum_gate_new", "name,theta", quantum_gate_new), - ("quantum_gate_from_matrix", "matrix", quantum_gate_from_matrix), - ("quantum_gate_matrix", "gate", quantum_gate_matrix), - ("quantum_gate_matches_matrix", "gate,matrix,tol", quantum_gate_matches_matrix), - ("quantum_gate_draw", "gate,path,kind", quantum_gate_draw), - ("quantum_apply", "circuit,gate,qubits", quantum_apply), - ("quantum_density_from_state", "state", quantum_density_from_state), - ("quantum_density_from_matrix", "matrix", quantum_density_from_matrix), - ("quantum_density_matrix", "density", quantum_density_matrix), - ("quantum_density_purity", "density", quantum_density_purity), - ("quantum_density_partial_trace", "density,keep", quantum_density_partial_trace), - ("quantum_density_eig", "density", quantum_density_eig), - ("quantum_density_expect", "density,obs", quantum_density_expect), - ("quantum_density_draw", "density,path,kind", quantum_density_draw), - ("quantum_kron", "a,b", quantum_kron), - ("quantum_schmidt", "state,cut", quantum_schmidt), - ("quantum_fidelity", "a,b", quantum_fidelity), -]); diff --git a/plugins/quantum/src/linalg.rs b/plugins/quantum/src/linalg.rs deleted file mode 100755 index db9f13b..0000000 --- a/plugins/quantum/src/linalg.rs +++ /dev/null @@ -1,640 +0,0 @@ -//! Q7a: density matrix, Kronecker, partial trace, Hermitian eig, Schmidt, Pauli expect. - -use serde_json::{json, Map, Value}; - -use crate::sim::{ - amps_to_json, matrix_to_json, parse_matrix, simulate_circuit, C, -}; - -pub const DENSITY_MAX_QUBITS: usize = 6; - -fn check_density_qubits(n: usize) -> Result<(), String> { - if n > DENSITY_MAX_QUBITS { - return Err(format!( - "density-matrix ops limited to {DENSITY_MAX_QUBITS} qubits (got {n}); use state-vector APIs for larger n" - )); - } - Ok(()) -} - -fn dim_of(n: usize) -> usize { - 1usize << n -} - -/// Flat row-major dim×dim complex matrix. -pub type Mat = Vec; - -pub fn mat_get(m: &Mat, dim: usize, i: usize, j: usize) -> C { - m[i * dim + j] -} - -pub fn mat_set(m: &mut Mat, dim: usize, i: usize, j: usize, v: C) { - m[i * dim + j] = v; -} - -pub fn mat_zeros(dim: usize) -> Mat { - vec![C::zero(); dim * dim] -} - -pub fn nested_to_flat(m: &[Vec]) -> Result<(usize, Mat), String> { - if m.is_empty() { - return Err("matrix is empty".into()); - } - let dim = m.len(); - for (i, row) in m.iter().enumerate() { - if row.len() != dim { - return Err(format!("matrix row {i} length {} != {dim}", row.len())); - } - } - let mut flat = Mat::with_capacity(dim * dim); - for row in m { - flat.extend_from_slice(row); - } - Ok((dim, flat)) -} - -pub fn flat_to_nested(m: &Mat, dim: usize) -> Vec> { - let mut out = Vec::with_capacity(dim); - for i in 0..dim { - out.push(m[i * dim..(i + 1) * dim].to_vec()); - } - out -} - -pub fn density_from_amps(amps: &[C], qubits: usize) -> Result<(usize, Mat), String> { - check_density_qubits(qubits)?; - let dim = dim_of(qubits); - if amps.len() != dim { - return Err(format!( - "state dim {} != 2^{qubits}={dim}", - amps.len() - )); - } - let mut rho = mat_zeros(dim); - for i in 0..dim { - for j in 0..dim { - // ρ_ij = ψ_i * conj(ψ_j) - mat_set(&mut rho, dim, i, j, amps[i].mul(amps[j].conj())); - } - } - Ok((dim, rho)) -} - -pub fn amps_from_state_or_circuit(v: &Value) -> Result<(usize, Vec), String> { - if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_circuit") - || (v.get("qubits").is_some() && v.get("ops").is_some()) - { - let (n, amps) = simulate_circuit(v)?; - return Ok((n, amps)); - } - if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_state") - || v.get("amplitudes").is_some() - { - let qubits = v - .get("qubits") - .or_else(|| v.get("比特数")) - .and_then(|x| x.as_u64().or_else(|| x.as_i64().map(|i| i as u64))) - .ok_or_else(|| "state missing qubits".to_string())? as usize; - let amps_v = v - .get("amplitudes") - .or_else(|| v.get("振幅")) - .ok_or_else(|| "state missing amplitudes".to_string())?; - let nested = match amps_v { - Value::Array(a) => a - .iter() - .map(|c| match c { - Value::Object(o) => Ok(C::new( - o.get("re").and_then(|x| x.as_f64()).unwrap_or(0.0), - o.get("im").and_then(|x| x.as_f64()).unwrap_or(0.0), - )), - _ => Err("amplitude cell must be {re,im}".into()), - }) - .collect::, String>>()?, - _ => return Err("amplitudes must be a list".into()), - }; - return Ok((qubits, nested)); - } - Err("expected quantum_state or quantum_circuit".into()) -} - -pub fn density_handle(qubits: usize, rho: &Mat) -> Value { - let dim = dim_of(qubits); - json!({ - "_type": "density", - "qubits": qubits, - "dim": dim, - "matrix": matrix_to_json(&flat_to_nested(rho, dim)), - }) -} - -pub fn parse_density(v: &Value) -> Result<(usize, Mat), String> { - if let Some(mat_v) = v.get("matrix").or_else(|| v.get("矩阵")) { - let nested = parse_matrix(mat_v)?; - let (dim, flat) = nested_to_flat(&nested)?; - let qubits = (dim as f64).log2() as usize; - if dim_of(qubits) != dim { - return Err(format!("density dim {dim} is not a power of two")); - } - check_density_qubits(qubits)?; - check_hermitian(&flat, dim)?; - return Ok((qubits, flat)); - } - let (n, amps) = amps_from_state_or_circuit(v)?; - density_from_amps(&s, n) -} - -pub fn check_hermitian(m: &Mat, dim: usize) -> Result<(), String> { - let mut err = 0.0; - for i in 0..dim { - for j in i..dim { - let a = mat_get(m, dim, i, j); - let b = mat_get(m, dim, j, i).conj(); - let d = a.sub(b); - err += d.norm_sq(); - } - } - if err.sqrt() > 1e-8 { - return Err(format!( - "matrix is not Hermitian (‖ρ−ρ†‖_F ≈ {:.2e})", - err.sqrt() - )); - } - Ok(()) -} - -pub fn purity(m: &Mat, dim: usize) -> f64 { - // Tr(ρ²) = Σ_ij |ρ_ij|² for Hermitian ρ? Actually Tr(ρ²)=Σ_ij ρ_ij ρ_ji = Σ_ij |ρ_ij|² when Hermitian. - let mut s = 0.0; - for i in 0..dim { - for j in 0..dim { - s += mat_get(m, dim, i, j).norm_sq(); - } - } - s -} - -pub fn kronecker(a: &Mat, da: usize, b: &Mat, db: usize) -> Mat { - let dim = da * db; - let mut out = mat_zeros(dim); - for i in 0..da { - for j in 0..da { - let aij = mat_get(a, da, i, j); - for k in 0..db { - for l in 0..db { - let bij = mat_get(b, db, k, l); - mat_set( - &mut out, - dim, - i * db + k, - j * db + l, - aij.mul(bij), - ); - } - } - } - } - out -} - -pub fn kronecker_amps(a: &[C], b: &[C]) -> Vec { - let mut out = Vec::with_capacity(a.len() * b.len()); - for &ai in a { - for &bj in b { - out.push(ai.mul(bj)); - } - } - out -} - -/// Keep listed qubits (LSB numbering). Trace out the rest. -pub fn partial_trace(rho: &Mat, qubits: usize, keep: &[usize]) -> Result<(usize, Mat), String> { - check_density_qubits(qubits)?; - let mut keep_sorted = keep.to_vec(); - keep_sorted.sort_unstable(); - keep_sorted.dedup(); - for &q in &keep_sorted { - if q >= qubits { - return Err(format!("keep qubit {q} out of range for n={qubits}")); - } - } - let k = keep_sorted.len(); - check_density_qubits(k)?; - let dim = dim_of(qubits); - let kdim = dim_of(k); - let mut out = mat_zeros(kdim); - - // Map full basis index -> kept subspace index - let map_keep = |full: usize| -> usize { - let mut idx = 0usize; - for (bit_pos, &q) in keep_sorted.iter().enumerate() { - if (full >> q) & 1 == 1 { - idx |= 1 << bit_pos; - } - } - idx - }; - - let traced: Vec = (0..qubits).filter(|q| !keep_sorted.contains(q)).collect(); - - for i in 0..dim { - for j in 0..dim { - // Only contribute when traced bits of i and j match - let mut same = true; - for &q in &traced { - if ((i >> q) & 1) != ((j >> q) & 1) { - same = false; - break; - } - } - if !same { - continue; - } - let ik = map_keep(i); - let jk = map_keep(j); - let v = mat_get(rho, dim, i, j); - let cur = mat_get(&out, kdim, ik, jk); - mat_set(&mut out, kdim, ik, jk, cur.add(v)); - } - } - Ok((k, out)) -} - -/// Jacobi eigenvalue algorithm for Hermitian matrices. Returns eigenvalues (desc) and eigenvectors as columns. -pub fn hermite_eig(m: &Mat, dim: usize) -> Result<(Vec, Vec>), String> { - check_hermitian(m, dim)?; - let mut a = m.clone(); - // Force diagonal imaginary parts to 0 (Hermitian) - for i in 0..dim { - let d = mat_get(&a, dim, i, i); - mat_set(&mut a, dim, i, i, C::new(d.re, 0.0)); - } - let mut v = mat_zeros(dim); - for i in 0..dim { - mat_set(&mut v, dim, i, i, C::one()); - } - - let max_iter = 200 * dim * dim; - for _ in 0..max_iter { - let mut p = 0usize; - let mut q = 1usize; - let mut max_abs = 0.0; - for i in 0..dim { - for j in (i + 1)..dim { - let mag = mat_get(&a, dim, i, j).norm_sq().sqrt(); - if mag > max_abs { - max_abs = mag; - p = i; - q = j; - } - } - } - if max_abs < 1e-14 { - break; - } - - let app = mat_get(&a, dim, p, p).re; - let aqq = mat_get(&a, dim, q, q).re; - let apq = mat_get(&a, dim, p, q); - let abs_apq = apq.norm_sq().sqrt(); - let phase = apq.scale(1.0 / abs_apq); // e^{iα} - - // tan(2φ) = 2|apq| / (app - aqq) - let diff = app - aqq; - let (c, s_mag) = if abs_apq < 1e-30 { - (1.0, 0.0) - } else { - let tau = diff / (2.0 * abs_apq); - let t = if tau >= 0.0 { - 1.0 / (tau + (1.0 + tau * tau).sqrt()) - } else { - -1.0 / (-tau + (1.0 + tau * tau).sqrt()) - }; - let cc = 1.0 / (1.0 + t * t).sqrt(); - (cc, t * cc) - }; - let s = phase.scale(s_mag); // complex sine - - // Apply Jacobi rotation to A (similarity J† A J) - let mut row_p = vec![C::zero(); dim]; - let mut row_q = vec![C::zero(); dim]; - for i in 0..dim { - let aip = mat_get(&a, dim, i, p); - let aiq = mat_get(&a, dim, i, q); - row_p[i] = aip.scale(c).add(aiq.mul(s)); - row_q[i] = aiq.scale(c).sub(aip.mul(s.conj())); - } - // Diagonals: phase = apq/|apq| ⇒ Re(conj(phase)*apq) = |apq| - let new_app = c * c * app + s_mag * s_mag * aqq + 2.0 * c * s_mag * abs_apq; - let new_aqq = c * c * aqq + s_mag * s_mag * app - 2.0 * c * s_mag * abs_apq; - - for i in 0..dim { - if i == p || i == q { - continue; - } - mat_set(&mut a, dim, i, p, row_p[i]); - mat_set(&mut a, dim, p, i, row_p[i].conj()); - mat_set(&mut a, dim, i, q, row_q[i]); - mat_set(&mut a, dim, q, i, row_q[i].conj()); - } - mat_set(&mut a, dim, p, p, C::new(new_app, 0.0)); - mat_set(&mut a, dim, q, q, C::new(new_aqq, 0.0)); - mat_set(&mut a, dim, p, q, C::zero()); - mat_set(&mut a, dim, q, p, C::zero()); - - // V ← V J - for i in 0..dim { - let vip = mat_get(&v, dim, i, p); - let viq = mat_get(&v, dim, i, q); - mat_set(&mut v, dim, i, p, vip.scale(c).add(viq.mul(s))); - mat_set( - &mut v, - dim, - i, - q, - viq.scale(c).sub(vip.mul(s.conj())), - ); - } - } - - let mut evals: Vec<(f64, usize)> = (0..dim) - .map(|i| (mat_get(&a, dim, i, i).re, i)) - .collect(); - evals.sort_by(|x, y| y.0.partial_cmp(&x.0).unwrap_or(std::cmp::Ordering::Equal)); - - let mut eigenvalues = Vec::with_capacity(dim); - let mut eigenvectors = Vec::with_capacity(dim); - for &(ev, idx) in &evals { - eigenvalues.push(ev); - let mut col = Vec::with_capacity(dim); - for row in 0..dim { - col.push(mat_get(&v, dim, row, idx)); - } - let nrm = col.iter().map(|c| c.norm_sq()).sum::().sqrt(); - if nrm > 1e-15 { - for c in &mut col { - *c = c.scale(1.0 / nrm); - } - } - eigenvectors.push(col); - } - Ok((eigenvalues, eigenvectors)) -} - -/// Thin SVD via eig of A†A for complex matrix rows×cols (rows = 2^cut, cols = 2^(n-cut)). -pub fn schmidt_decompose(amps: &[C], qubits: usize, cut: usize) -> Result { - if cut == 0 || cut >= qubits { - return Err(format!("schmidt cut must be in 1..{} (got {cut})", qubits - 1)); - } - check_density_qubits(qubits)?; - let da = dim_of(cut); - let db = dim_of(qubits - cut); - if amps.len() != da * db { - return Err("state dimension mismatch for schmidt".into()); - } - // Build Gram G = M M† (da×da) where M[ia, ib] = ψ[(ib << cut) | ia] (A = low bits) - let mut gram = mat_zeros(da); - for ia in 0..da { - for ja in 0..da { - let mut s = C::zero(); - for ib in 0..db { - let i = (ib << cut) | ia; - let j = (ib << cut) | ja; - s = s.add(amps[i].mul(amps[j].conj())); - } - mat_set(&mut gram, da, ia, ja, s); - } - } - let (evals, evecs) = hermite_eig(&gram, da)?; - let coeffs: Vec = evals - .iter() - .map(|e| e.max(0.0).sqrt()) - .collect(); - // entropy - let mut entropy = 0.0; - for &c in &coeffs { - let p = c * c; - if p > 1e-15 { - entropy -= p * p.ln(); - } - } - // Keep significant coeffs - let ua: Vec = evecs - .iter() - .map(|col| Value::Array(col.iter().map(|c| c.to_json()).collect())) - .collect(); - - // For each singular vector u_k, v_k = M† u_k / σ_k - let mut ub = Vec::new(); - for (k, sigma) in coeffs.iter().enumerate() { - if *sigma < 1e-12 { - ub.push(Value::Array( - (0..db).map(|_| C::zero().to_json()).collect(), - )); - continue; - } - let u = &evecs[k]; - let mut vk = vec![C::zero(); db]; - for ib in 0..db { - let mut s = C::zero(); - for ia in 0..da { - let idx = (ib << cut) | ia; - // (M† u)_ib = Σ_ia conj(M_ia,ib) u_ia = Σ conj(ψ) u - s = s.add(amps[idx].conj().mul(u[ia])); - } - vk[ib] = s.scale(1.0 / sigma); - } - ub.push(Value::Array(vk.iter().map(|c| c.to_json()).collect())); - } - - // Drop near-zero trailing for readability but keep all for determinism - let _ = coeffs - .iter() - .position(|&c| c < 1e-10) - .unwrap_or(coeffs.len()); - - Ok(json!({ - "_type": "quantum_schmidt", - "cut": cut, - "qubits": qubits, - "coeffs": coeffs, - "ua": ua, - "ub": ub, - "entropy": entropy, - })) -} - -fn pauli_matrix(p: char) -> Result<[[C; 2]; 2], String> { - match p.to_ascii_uppercase() { - 'I' => Ok([ - [C::one(), C::zero()], - [C::zero(), C::one()], - ]), - 'X' => Ok([ - [C::zero(), C::one()], - [C::one(), C::zero()], - ]), - 'Y' => Ok([ - [C::zero(), C::new(0.0, -1.0)], - [C::new(0.0, 1.0), C::zero()], - ]), - 'Z' => Ok([ - [C::one(), C::zero()], - [C::zero(), C::new(-1.0, 0.0)], - ]), - other => Err(format!("unknown Pauli `{other}` (I/X/Y/Z)")), - } -} - -/// Pauli string: left = qubit n-1 (MSB), right = qubit 0 (LSB). Returns dim×dim. -pub fn pauli_string_matrix(s: &str, qubits: usize) -> Result<(usize, Mat), String> { - let t = s.trim(); - if t.len() != qubits { - return Err(format!( - "Pauli string length {} != qubits {qubits} (left=high bit)", - t.len() - )); - } - let chars: Vec = t.chars().collect(); - // chars[0] = qubit n-1 - let mut mat = { - let p = pauli_matrix(chars[qubits - 1])?; // qubit 0 first in kron chain - let mut m = mat_zeros(2); - for i in 0..2 { - for j in 0..2 { - mat_set(&mut m, 2, i, j, p[i][j]); - } - } - (2usize, m) - }; - for q in 1..qubits { - let ch = chars[qubits - 1 - q]; - let p = pauli_matrix(ch)?; - let mut b = mat_zeros(2); - for i in 0..2 { - for j in 0..2 { - mat_set(&mut b, 2, i, j, p[i][j]); - } - } - // New = b ⊗ old so that higher qubit is left in kron... - // Full basis: index bit q corresponds to qubit q. - // Kronecker A⊗B means A on high subspace if we use (i< Result { - let (od, op) = pauli_string_matrix(obs, qubits)?; - if od != dim { - return Err("observable dimension mismatch".into()); - } - // ⟨P⟩ = Tr(ρ P) = Σ_ij ρ_ij P_ji - let mut s = C::zero(); - for i in 0..dim { - for j in 0..dim { - s = s.add(mat_get(rho, dim, i, j).mul(mat_get(&op, dim, j, i))); - } - } - if s.im.abs() > 1e-8 { - return Err(format!("expectation has imaginary part {}", s.im)); - } - Ok(s.re) -} - -pub fn expect_matrix(rho: &Mat, dim: usize, obs: &Mat, odim: usize) -> Result { - if odim != dim { - return Err("observable dimension mismatch".into()); - } - let mut s = C::zero(); - for i in 0..dim { - for j in 0..dim { - s = s.add(mat_get(rho, dim, i, j).mul(mat_get(obs, dim, j, i))); - } - } - Ok(s.re) -} - -pub fn fidelity_pure(a: &[C], b: &[C]) -> Result { - if a.len() != b.len() { - return Err("fidelity: state dimensions differ".into()); - } - let mut s = C::zero(); - for i in 0..a.len() { - s = s.add(a[i].conj().mul(b[i])); - } - Ok(s.norm_sq()) -} - -pub fn all_pauli_labels(qubits: usize) -> Result, String> { - if qubits > 3 { - return Err("paulivec default basis only for n≤3; pass explicit ops".into()); - } - let letters = ['I', 'X', 'Y', 'Z']; - let n = qubits; - let total = 4usize.pow(n as u32); - let mut out = Vec::with_capacity(total); - for code in 0..total { - let mut s = String::with_capacity(n); - let mut c = code; - // left = high qubit - let mut chars = vec!['I'; n]; - for q in 0..n { - chars[n - 1 - q] = letters[c % 4]; - c /= 4; - } - for ch in chars { - s.push(ch); - } - out.push(s); - } - Ok(out) -} - -pub fn spectrum_handle(evals: &[f64], evecs: &[Vec]) -> Value { - let eigenvectors: Vec = evecs - .iter() - .map(|col| Value::Array(col.iter().map(|c| c.to_json()).collect())) - .collect(); - json!({ - "_type": "quantum_spectrum", - "eigenvalues": evals, - "eigenvectors": eigenvectors, - }) -} - -pub fn value_as_matrix(v: &Value) -> Result<(usize, Mat), String> { - if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_density") - || v.get("_type").and_then(|t| t.as_str()) == Some("density") - || v.get("_type").and_then(|t| t.as_str()) == Some("密度") - || v.get("matrix").is_some() - { - return parse_density(v); - } - if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_gate") { - let nested = crate::sim::gate_matrix_of(v)?; - let (dim, flat) = nested_to_flat(&nested)?; - return Ok(((dim as f64).log2() as usize, flat)); - } - // nested list - let nested = parse_matrix(v)?; - let (dim, flat) = nested_to_flat(&nested)?; - Ok(((dim as f64).log2() as usize, flat)) -} - -/// Helper for JSON amps list export (re-export style). -#[allow(dead_code)] // kept: referenced by draw/JSON export paths in the host -pub fn amps_json(amps: &[C]) -> Value { - amps_to_json(amps) -} - -#[allow(dead_code)] // kept: referenced by draw/JSON export paths in the host -pub fn density_map_insert_matrix(obj: &mut Map, rho: &Mat, dim: usize) { - obj.insert( - "matrix".into(), - matrix_to_json(&flat_to_nested(rho, dim)), - ); -} diff --git a/plugins/quantum/src/sim.rs b/plugins/quantum/src/sim.rs deleted file mode 100755 index 72ba28d..0000000 --- a/plugins/quantum/src/sim.rs +++ /dev/null @@ -1,1600 +0,0 @@ -//! Pure-state state-vector simulator (design §6). - -use serde_json::{json, Map, Value}; - -pub const DEFAULT_MAX_QUBITS: usize = 12; -pub const HARD_MAX_QUBITS: usize = 16; - -#[derive(Clone, Copy, Debug, Default)] -pub struct C { - pub re: f64, - pub im: f64, -} - -impl C { - pub fn new(re: f64, im: f64) -> Self { - Self { re, im } - } - pub fn zero() -> Self { - Self { re: 0.0, im: 0.0 } - } - pub fn one() -> Self { - Self { re: 1.0, im: 0.0 } - } - pub fn norm_sq(self) -> f64 { - self.re * self.re + self.im * self.im - } - pub fn mul(self, o: C) -> C { - C { - re: self.re * o.re - self.im * o.im, - im: self.re * o.im + self.im * o.re, - } - } - pub fn add(self, o: C) -> C { - C { - re: self.re + o.re, - im: self.im + o.im, - } - } - pub fn scale(self, s: f64) -> C { - C { - re: self.re * s, - im: self.im * s, - } - } - pub fn conj(self) -> C { - C { - re: self.re, - im: -self.im, - } - } - pub fn sub(self, o: C) -> C { - C { - re: self.re - o.re, - im: self.im - o.im, - } - } - pub fn to_json(self) -> Value { - json!({ "re": self.re, "im": self.im }) - } -} - -pub fn max_qubits() -> usize { - match std::env::var("MARQDO_QUANTUM_MAX_QUBITS") { - Ok(s) => s - .trim() - .parse::() - .ok() - .map(|n| n.clamp(1, HARD_MAX_QUBITS)) - .unwrap_or(DEFAULT_MAX_QUBITS), - Err(_) => DEFAULT_MAX_QUBITS, - } -} - -pub fn check_qubits(n: usize) -> Result<(), String> { - let max = max_qubits(); - if n == 0 { - return Err("qubits must be >= 1".into()); - } - if n > max { - return Err(format!( - "qubits={n} exceeds max {max} (set MARQDO_QUANTUM_MAX_QUBITS to lower, hard cap {HARD_MAX_QUBITS})" - )); - } - Ok(()) -} - -fn bit(i: usize, q: usize) -> bool { - ((i >> q) & 1) == 1 -} - -fn flip(i: usize, q: usize) -> usize { - i ^ (1 << q) -} - -/// Apply 2×2 gate `[[a,b],[c,d]]` on qubit `q`. -pub fn apply_u2(amps: &mut [C], q: usize, a: C, b: C, c: C, d: C) { - let n = amps.len(); - let step = 1 << q; - let mut i = 0; - while i < n { - for j in 0..step { - let i0 = i + j; - let i1 = i0 + step; - let v0 = amps[i0]; - let v1 = amps[i1]; - amps[i0] = a.mul(v0).add(b.mul(v1)); - amps[i1] = c.mul(v0).add(d.mul(v1)); - } - i += 2 * step; - } -} - -pub fn apply_x(amps: &mut [C], q: usize) { - apply_u2( - amps, - q, - C::zero(), - C::one(), - C::one(), - C::zero(), - ); -} - -pub fn apply_h(amps: &mut [C], q: usize) { - let s = std::f64::consts::FRAC_1_SQRT_2; - let t = C::new(s, 0.0); - apply_u2(amps, q, t, t, t, t.scale(-1.0)); -} - -pub fn apply_i(_amps: &mut [C], _q: usize) {} - -pub fn apply_cx(amps: &mut [C], control: usize, target: usize) { - if control == target { - return; - } - let n = amps.len(); - for i in 0..n { - if bit(i, control) && !bit(i, target) { - let j = flip(i, target); - if i < j { - amps.swap(i, j); - } - } - } -} - -pub fn apply_y(amps: &mut [C], q: usize) { - // [[0, -i], [i, 0]] - apply_u2( - amps, - q, - C::zero(), - C::new(0.0, -1.0), - C::new(0.0, 1.0), - C::zero(), - ); -} - -pub fn apply_z(amps: &mut [C], q: usize) { - apply_u2( - amps, - q, - C::one(), - C::zero(), - C::zero(), - C::new(-1.0, 0.0), - ); -} - -pub fn apply_s(amps: &mut [C], q: usize) { - apply_u2( - amps, - q, - C::one(), - C::zero(), - C::zero(), - C::new(0.0, 1.0), - ); -} - -pub fn apply_t(amps: &mut [C], q: usize) { - let s = std::f64::consts::FRAC_1_SQRT_2; - apply_u2( - amps, - q, - C::one(), - C::zero(), - C::zero(), - C::new(s, s), - ); -} - -pub fn apply_rx(amps: &mut [C], q: usize, theta: f64) { - let half = theta / 2.0; - let c = half.cos(); - let s = half.sin(); - apply_u2( - amps, - q, - C::new(c, 0.0), - C::new(0.0, -s), - C::new(0.0, -s), - C::new(c, 0.0), - ); -} - -pub fn apply_ry(amps: &mut [C], q: usize, theta: f64) { - let half = theta / 2.0; - let c = half.cos(); - let s = half.sin(); - apply_u2( - amps, - q, - C::new(c, 0.0), - C::new(-s, 0.0), - C::new(s, 0.0), - C::new(c, 0.0), - ); -} - -pub fn apply_rz(amps: &mut [C], q: usize, theta: f64) { - let half = theta / 2.0; - apply_u2( - amps, - q, - C::new((-half).cos(), (-half).sin()), - C::zero(), - C::zero(), - C::new(half.cos(), half.sin()), - ); -} - -pub fn apply_cz(amps: &mut [C], control: usize, target: usize) { - if control == target { - return; - } - for (i, a) in amps.iter_mut().enumerate() { - if bit(i, control) && bit(i, target) { - *a = a.scale(-1.0); - } - } -} - -pub fn apply_swap(amps: &mut [C], a: usize, b: usize) { - if a == b { - return; - } - let n = amps.len(); - for i in 0..n { - let j = if bit(i, a) != bit(i, b) { - flip(flip(i, a), b) - } else { - i - }; - if i < j { - amps.swap(i, j); - } - } -} - - -pub fn zero_state(qubits: usize) -> Vec { - let dim = 1usize << qubits; - let mut amps = vec![C::zero(); dim]; - amps[0] = C::one(); - amps -} - -pub fn renormalize(amps: &mut [C]) { - let n2: f64 = amps.iter().map(|c| c.norm_sq()).sum(); - if n2 <= 0.0 { - return; - } - let inv = 1.0 / n2.sqrt(); - for a in amps.iter_mut() { - *a = a.scale(inv); - } -} - -pub fn basis_label(i: usize, qubits: usize) -> String { - // LSB = qubit 0 on the right - format!("{i:0qubits$b}") -} - -pub fn probabilities(amps: &[C], qubits: usize) -> Map { - let mut m = Map::new(); - for (i, a) in amps.iter().enumerate() { - let p = a.norm_sq(); - if p > 1e-15 { - m.insert(basis_label(i, qubits), json!(p)); - } - } - m -} - -pub fn amps_to_json(amps: &[C]) -> Value { - Value::Array(amps.iter().map(|c| c.to_json()).collect()) -} - -#[derive(Clone, Debug)] -pub struct Op { - pub gate: String, - pub qubits: Vec, - pub theta: Option, - /// Custom unitary (row-major). When set, overrides named-gate dispatch. - pub matrix: Option>>, -} - -pub fn op_to_json(op: &Op) -> Value { - let mut m = json!({ - "gate": op.gate, - "qubits": op.qubits, - }); - if let Some(t) = op.theta { - m.as_object_mut() - .unwrap() - .insert("theta".into(), json!(t)); - } - if let Some(ref mat) = op.matrix { - m.as_object_mut() - .unwrap() - .insert("matrix".into(), matrix_to_json(mat)); - } - m -} - -fn parse_op_row(row: &Value) -> Result { - let gate = row - .get("gate") - .or_else(|| row.get("门")) - .and_then(|v| v.as_str()) - .ok_or_else(|| "op missing gate".to_string())? - .to_ascii_uppercase(); - let qubits = match row.get("qubits").or_else(|| row.get("比特")) { - Some(Value::Array(a)) => a - .iter() - .map(|v| { - v.as_u64() - .or_else(|| v.as_i64().map(|i| i as u64)) - .ok_or_else(|| "bad qubit index".to_string()) - .map(|u| u as usize) - }) - .collect::, _>>()?, - Some(Value::Number(n)) => { - let u = n.as_u64().or_else(|| n.as_i64().map(|i| i as u64)).unwrap() as usize; - vec![u] - } - Some(Value::String(s)) => { - let t = s.trim(); - if t.is_empty() { - vec![] - } else { - parse_qubit_list(s)? - } - } - Some(Value::Null) => vec![], - None => { - if is_meta_gate(&gate) { - vec![] - } else if let Some(q) = row - .get("qubit") - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) - { - vec![q as usize] - } else if let (Some(c), Some(t)) = ( - row.get("control") - .or_else(|| row.get("控制")) - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))), - row.get("target") - .or_else(|| row.get("目标")) - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))), - ) { - vec![c as usize, t as usize] - } else { - return Err(format!("op `{gate}` missing qubits")); - } - } - _ => return Err(format!("op `{gate}` bad qubits")), - }; - let theta = row - .get("theta") - .or_else(|| row.get("参数")) - .or_else(|| row.get("params")) - .and_then(|v| parse_theta_value(v).ok().flatten()); - let matrix = match row.get("matrix").or_else(|| row.get("矩阵")) { - None | Some(Value::Null) => None, - Some(v) => Some(parse_matrix(v)?), - }; - Ok(Op { - gate, - qubits, - theta, - matrix, - }) -} - -pub fn parse_ops(circuit: &Value) -> Result, String> { - let arr = circuit - .get("ops") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - let mut out = Vec::new(); - for row in arr { - out.push(parse_op_row(&row)?); - } - Ok(out) -} - -fn parse_qubit_list(s: &str) -> Result, String> { - s.split(|c| c == ',' || c == ' ' || c == ',') - .filter(|t| !t.is_empty()) - .map(|t| { - t.trim() - .parse::() - .map_err(|_| format!("bad qubit `{t}`")) - }) - .collect() -} - -pub fn apply_op(amps: &mut [C], qubits: usize, op: &Op) -> Result<(), String> { - for &q in &op.qubits { - if q >= qubits { - return Err(format!("qubit {q} out of range for n={qubits}")); - } - } - if let Some(ref mat) = op.matrix { - return apply_unitary(amps, &op.qubits, mat); - } - match op.gate.as_str() { - "BARRIER" | "MEASURE" | "M" => Ok(()), - "I" | "ID" | "IDENTITY" => { - let q = *op.qubits.first().ok_or("I needs qubit")?; - apply_i(amps, q); - Ok(()) - } - "X" | "NOT" => { - let q = *op.qubits.first().ok_or("X needs qubit")?; - apply_x(amps, q); - Ok(()) - } - "Y" => { - let q = *op.qubits.first().ok_or("Y needs qubit")?; - apply_y(amps, q); - Ok(()) - } - "Z" => { - let q = *op.qubits.first().ok_or("Z needs qubit")?; - apply_z(amps, q); - Ok(()) - } - "S" => { - let q = *op.qubits.first().ok_or("S needs qubit")?; - apply_s(amps, q); - Ok(()) - } - "T" => { - let q = *op.qubits.first().ok_or("T needs qubit")?; - apply_t(amps, q); - Ok(()) - } - "H" | "HADAMARD" => { - let q = *op.qubits.first().ok_or("H needs qubit")?; - apply_h(amps, q); - Ok(()) - } - "RX" => { - let q = *op.qubits.first().ok_or("Rx needs qubit")?; - let th = op.theta.ok_or("Rx needs theta")?; - apply_rx(amps, q, th); - Ok(()) - } - "RY" => { - let q = *op.qubits.first().ok_or("Ry needs qubit")?; - let th = op.theta.ok_or("Ry needs theta")?; - apply_ry(amps, q, th); - Ok(()) - } - "RZ" => { - let q = *op.qubits.first().ok_or("Rz needs qubit")?; - let th = op.theta.ok_or("Rz needs theta")?; - apply_rz(amps, q, th); - Ok(()) - } - "CX" | "CNOT" | "CN" => { - if op.qubits.len() < 2 { - return Err("CX needs control and target".into()); - } - apply_cx(amps, op.qubits[0], op.qubits[1]); - Ok(()) - } - "CZ" => { - if op.qubits.len() < 2 { - return Err("CZ needs control and target".into()); - } - apply_cz(amps, op.qubits[0], op.qubits[1]); - Ok(()) - } - "SWAP" => { - if op.qubits.len() < 2 { - return Err("SWAP needs two qubits".into()); - } - apply_swap(amps, op.qubits[0], op.qubits[1]); - Ok(()) - } - other => Err(format!( - "unsupported gate `{other}` (I/X/Y/Z/H/S/T/Rx/Ry/Rz/CX/CZ/SWAP/BARRIER/MEASURE or custom matrix)" - )), - } -} - -/// Apply a `2^k × 2^k` unitary on `targets` (targets[0] = LSB of matrix index). -pub fn apply_unitary(amps: &mut [C], targets: &[usize], u: &[Vec]) -> Result<(), String> { - let k = targets.len(); - if k == 0 { - return Err("unitary needs at least one qubit".into()); - } - let mut seen = Vec::new(); - for &q in targets { - if seen.contains(&q) { - return Err("unitary qubits must be unique".into()); - } - seen.push(q); - } - let dim = 1usize << k; - if u.len() != dim || u.iter().any(|r| r.len() != dim) { - return Err(format!( - "unitary matrix must be {dim}x{dim} for {} qubit(s)", - k - )); - } - let n = amps.len(); - for i in 0..n { - let mut sub = 0usize; - for (b, &q) in targets.iter().enumerate() { - if bit(i, q) { - sub |= 1 << b; - } - } - if sub != 0 { - continue; - } - let mut idxs = vec![0usize; dim]; - let mut vin = vec![C::zero(); dim]; - for s in 0..dim { - let mut idx = i; - for (b, &q) in targets.iter().enumerate() { - if (s >> b) & 1 == 1 { - idx = flip(idx, q); - } - } - idxs[s] = idx; - vin[s] = amps[idx]; - } - let mut vout = vec![C::zero(); dim]; - for r in 0..dim { - let mut sum = C::zero(); - for c in 0..dim { - sum = sum.add(u[r][c].mul(vin[c])); - } - vout[r] = sum; - } - for s in 0..dim { - amps[idxs[s]] = vout[s]; - } - } - Ok(()) -} - -pub fn is_meta_gate(gate: &str) -> bool { - matches!( - gate.to_ascii_uppercase().as_str(), - "BARRIER" | "MEASURE" | "M" - ) -} - -pub fn is_unitary_op(op: &Op) -> bool { - !is_meta_gate(&op.gate) -} - -#[derive(Clone, Debug)] -pub struct NoiseSpec { - pub kind: String, // bitflip | depolarizing | amplitude_damping - pub p: f64, -} - -fn normalize_noise_kind(k: &str) -> Result<&'static str, String> { - match k.trim().to_ascii_lowercase().as_str() { - "bitflip" | "bit_flip" | "比特翻转" => Ok("bitflip"), - "depolarizing" | "depolarise" | "退极化" => Ok("depolarizing"), - "amplitude_damping" - | "amplitude-damping" - | "amp_damp" - | "ampdamp" - | "振幅阻尼" => Ok("amplitude_damping"), - other => Err(format!( - "unknown noise kind `{other}` (bitflip|depolarizing|amplitude_damping)" - )), - } -} - -pub fn parse_noise(circuit: &Value) -> Result, String> { - let kind = circuit - .get("noise_kind") - .or_else(|| circuit.get("噪声种类")) - .and_then(|v| v.as_str()) - .map(|s| s.to_ascii_lowercase()); - let p = circuit - .get("noise_p") - .or_else(|| circuit.get("噪声概率")) - .and_then(|v| v.as_f64()); - match (kind, p) { - (None, None) => Ok(None), - (Some(k), Some(p)) => { - if !(0.0..=1.0).contains(&p) { - return Err("noise p must be in [0,1]".into()); - } - let kind = normalize_noise_kind(&k)?.to_string(); - Ok(Some(NoiseSpec { kind, p })) - } - _ => Err("noise needs both kind and p".into()), - } -} - -pub fn set_noise(circuit: &Value, kind: &str, p: f64) -> Result { - if !(0.0..=1.0).contains(&p) { - return Err("noise p must be in [0,1]".into()); - } - let k = normalize_noise_kind(kind)?; - let mut obj = circuit.as_object().cloned().unwrap_or_default(); - obj.insert("noise_kind".into(), json!(k)); - obj.insert("noise_p".into(), json!(p)); - Ok(Value::Object(obj)) -} - -/// Qubits to read out: union of MEASURE ops; empty MEASURE list = all qubits; no MEASURE = all. -pub fn measure_targets(ops: &[Op], n: usize) -> Vec { - let mut measured = Vec::new(); - let mut any = false; - for op in ops { - let g = op.gate.to_ascii_uppercase(); - if g == "MEASURE" || g == "M" { - any = true; - if op.qubits.is_empty() { - return (0..n).collect(); - } - for &q in &op.qubits { - if !measured.contains(&q) { - measured.push(q); - } - } - } - } - if !any { - return (0..n).collect(); - } - measured.sort_unstable(); - measured -} - -struct Rng { - state: u64, -} - -impl Rng { - fn new(seed: u64) -> Self { - Self { - state: if seed == 0 { - 0x9e37_79b9_7f4a_7c15 - } else { - seed - }, - } - } - fn next_u64(&mut self) -> u64 { - // SplitMix64 - self.state = self.state.wrapping_add(0x9e37_79b9_7f4a_7c15); - let mut z = self.state; - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) - } - fn next_f64(&mut self) -> f64 { - (self.next_u64() >> 11) as f64 / ((1u64 << 53) as f64) - } -} - -fn apply_amplitude_damping_jump(amps: &mut [C], q: usize) { - // Jump Kraus E1 = |0⟩⟨1| on qubit q, then renormalize. - let n = amps.len(); - let mut out = vec![C::zero(); n]; - for i in 0..n { - if bit(i, q) { - let j = flip(i, q); - out[j] = out[j].add(amps[i]); - } - } - let norm_sq: f64 = out.iter().map(|c| c.norm_sq()).sum(); - if norm_sq < 1e-30 { - // State had no |1⟩ weight on q — jump is a no-op. - return; - } - let inv = 1.0 / norm_sq.sqrt(); - for i in 0..n { - amps[i] = out[i].scale(inv); - } -} - -fn apply_noise_on_qubits( - amps: &mut [C], - qs: &[usize], - noise: &NoiseSpec, - rng: &mut Rng, -) { - if noise.p <= 0.0 { - return; - } - for &q in qs { - if rng.next_f64() >= noise.p { - continue; - } - match noise.kind.as_str() { - "bitflip" => apply_x(amps, q), - "depolarizing" => match rng.next_u64() % 3 { - 0 => apply_x(amps, q), - 1 => apply_y(amps, q), - _ => apply_z(amps, q), - }, - "amplitude_damping" => apply_amplitude_damping_jump(amps, q), - _ => {} - } - } -} - -fn sample_label(amps: &[C], n: usize, targets: &[usize], rng: &mut Rng) -> String { - // Build CDF over full basis, then project bits onto targets (ascending, LSB = targets[0]). - let mut cdf = Vec::with_capacity(amps.len()); - let mut acc = 0.0; - for a in amps { - acc += a.norm_sq(); - cdf.push(acc); - } - if acc <= 0.0 { - return "0".repeat(targets.len().max(1)); - } - let inv = 1.0 / acc; - for x in &mut cdf { - *x *= inv; - } - let r = rng.next_f64(); - let mut idx = 0usize; - for (i, &c) in cdf.iter().enumerate() { - if r <= c { - idx = i; - break; - } - idx = i; - } - if targets.len() == n { - return basis_label(idx, n); - } - let mut bits = String::with_capacity(targets.len()); - // label: targets[0] is rightmost (LSB of the label string) - for &q in targets.iter().rev() { - bits.push(if bit(idx, q) { '1' } else { '0' }); - } - bits -} - -/// Sample computational-basis shots; returns counts map. -#[allow(dead_code)] -pub fn sample_counts(amps: &[C], qubits: usize, shots: usize, seed: u64) -> Map { - let targets: Vec = (0..qubits).collect(); - let mut counts: Map = Map::new(); - let mut rng = Rng::new(seed); - for _ in 0..shots { - let label = sample_label(amps, qubits, &targets, &mut rng); - let n = counts.get(&label).and_then(|v| v.as_u64()).unwrap_or(0) + 1; - counts.insert(label, json!(n)); - } - counts -} - -pub fn run_circuit(circuit: &Value, shots: usize, seed: u64) -> Result { - if shots == 0 { - return Err("shots must be >= 1".into()); - } - let qubits = circuit - .get("qubits") - .or_else(|| circuit.get("比特数")) - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) - .ok_or_else(|| "circuit missing qubits".to_string())? as usize; - check_qubits(qubits)?; - let ops = parse_ops(circuit)?; - let noise = parse_noise(circuit)?; - let targets = measure_targets(&ops, qubits); - let mut counts: Map = Map::new(); - let mut rng = Rng::new(seed); - - for _ in 0..shots { - let mut amps = zero_state(qubits); - for op in &ops { - if !is_unitary_op(op) { - continue; - } - apply_op(&mut amps, qubits, op)?; - if let Some(ref nspec) = noise { - if nspec.p > 0.0 { - apply_noise_on_qubits(&mut amps, &op.qubits, nspec, &mut rng); - } - } - } - renormalize(&mut amps); - let label = sample_label(&s, qubits, &targets, &mut rng); - let c = counts.get(&label).and_then(|v| v.as_u64()).unwrap_or(0) + 1; - counts.insert(label, json!(c)); - } - - let mut out = json!({ - "qubits": qubits, - "shots": shots, - "seed": seed, - "counts": counts, - "measure": targets, - }); - if let Some(nspec) = noise { - out.as_object_mut().unwrap().insert( - "noise".into(), - json!({ "kind": nspec.kind, "p": nspec.p }), - ); - } - Ok(out) -} - -pub fn simulate_circuit(circuit: &Value) -> Result<(usize, Vec), String> { - let qubits = circuit - .get("qubits") - .or_else(|| circuit.get("比特数")) - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) - .ok_or_else(|| "circuit missing qubits".to_string())? as usize; - check_qubits(qubits)?; - let ops = parse_ops(circuit)?; - let mut amps = zero_state(qubits); - for op in &ops { - apply_op(&mut amps, qubits, op)?; - } - renormalize(&mut amps); - Ok((qubits, amps)) -} - -/// Build a circuit from `qubits` + optional `steps=` table (column map or row list). -pub fn circuit_new(qubits: usize, steps: Option<&Value>) -> Result { - check_qubits(qubits)?; - let ops = match steps { - None | Some(Value::Null) => Vec::new(), - Some(v) => ops_from_steps(v)?, - }; - for op in &ops { - for &q in &op.qubits { - if q >= qubits { - return Err(format!("qubit {q} out of range for n={qubits}")); - } - } - } - let ops_json: Vec = ops.into_iter().map(|op| op_to_json(&op)).collect(); - Ok(json!({ - "qubits": qubits, - "ops": ops_json, - })) -} - -/// Parse GFM `steps=` into ops. -/// -/// Accepts: -/// - list of row maps (`@` / `行` / `row` tables) -/// - column-oriented map (`gate`/`门` + `qubits`/`比特` lists or scalars) -pub fn ops_from_steps(steps: &Value) -> Result, String> { - match steps { - Value::Array(rows) => { - let mut out = Vec::with_capacity(rows.len()); - for row in rows { - out.push(op_from_step_row(row)?); - } - Ok(out) - } - Value::Object(map) => { - let gate_col = map - .get("gate") - .or_else(|| map.get("门")) - .ok_or_else(|| "steps table needs `gate` / `门` column".to_string())?; - let qubit_col = map - .get("qubits") - .or_else(|| map.get("qubit")) - .or_else(|| map.get("比特")) - .ok_or_else(|| "steps table needs `qubits` / `比特` column".to_string())?; - let theta_col = map - .get("theta") - .or_else(|| map.get("参数")) - .or_else(|| map.get("params")); - - let gates = as_col_list(gate_col)?; - let qubits = as_col_list(qubit_col)?; - let thetas = match theta_col { - Some(v) => as_col_list(v)?, - None => vec![Value::Null; gates.len()], - }; - if qubits.len() != gates.len() { - return Err(format!( - "steps column length mismatch: gate={} qubits={}", - gates.len(), - qubits.len() - )); - } - if thetas.len() != gates.len() && theta_col.is_some() { - return Err("steps `theta`/`参数` column length mismatch".into()); - } - let mut out = Vec::with_capacity(gates.len()); - for i in 0..gates.len() { - let gate = gates[i] - .as_str() - .ok_or_else(|| format!("steps gate row {i} must be text"))? - .to_ascii_uppercase(); - let qs = qubits_from_cell(&qubits[i])?; - let theta = thetas - .get(i) - .map(parse_theta_value) - .transpose()? - .flatten(); - out.push(Op { - gate, - qubits: qs, - theta, - matrix: None, - }); - } - Ok(out) - } - _ => Err("steps must be a table (map or list of rows)".into()), - } -} - -fn as_col_list(v: &Value) -> Result, String> { - match v { - Value::Array(a) => Ok(a.clone()), - other => Ok(vec![other.clone()]), - } -} - -fn op_from_step_row(row: &Value) -> Result { - let gate = row - .get("gate") - .or_else(|| row.get("门")) - .and_then(|v| v.as_str()) - .ok_or_else(|| "step row missing `gate` / `门`".to_string())? - .to_ascii_uppercase(); - let qubits = match row - .get("qubits") - .or_else(|| row.get("qubit")) - .or_else(|| row.get("比特")) - { - None if is_meta_gate(&gate) => vec![], - None => { - return Err("step row missing `qubits` / `比特`".into()); - } - Some(v) => qubits_from_cell(v)?, - }; - let theta = row - .get("theta") - .or_else(|| row.get("参数")) - .or_else(|| row.get("params")) - .map(parse_theta_value) - .transpose()? - .flatten(); - Ok(Op { - gate, - qubits, - theta, - matrix: None, - }) -} - -fn qubits_from_cell(v: &Value) -> Result, String> { - match v { - Value::Null => Ok(vec![]), - Value::Array(a) => a - .iter() - .map(|x| { - x.as_u64() - .or_else(|| x.as_i64().map(|i| i as u64)) - .ok_or_else(|| "bad qubit index".to_string()) - .map(|u| u as usize) - }) - .collect(), - Value::Number(n) => { - let u = n - .as_u64() - .or_else(|| n.as_i64().map(|i| i as u64)) - .ok_or_else(|| "bad qubit index".to_string())? as usize; - Ok(vec![u]) - } - Value::String(s) => { - if s.trim().is_empty() { - Ok(vec![]) - } else { - parse_qubit_list(s) - } - } - _ => Err("bad qubits cell".into()), - } -} - -fn parse_theta_value(v: &Value) -> Result, String> { - match v { - Value::Null => Ok(None), - Value::Number(n) => n - .as_f64() - .ok_or_else(|| "bad theta".to_string()) - .map(Some), - Value::String(s) => { - let t = s.trim(); - if t.is_empty() { - return Ok(None); - } - parse_theta_str(t).map(Some) - } - _ => Err("bad theta".into()), - } -} - -fn parse_theta_str(s: &str) -> Result { - let t = s.trim().to_ascii_lowercase().replace('π', "pi"); - if t == "pi" { - return Ok(std::f64::consts::PI); - } - if let Some(rest) = t.strip_prefix("pi/") { - let d: f64 = rest - .trim() - .parse() - .map_err(|_| format!("bad theta `{s}`"))?; - if d == 0.0 { - return Err(format!("bad theta `{s}`")); - } - return Ok(std::f64::consts::PI / d); - } - if let Some(rest) = t.strip_suffix("*pi") { - let n: f64 = rest - .trim() - .parse() - .map_err(|_| format!("bad theta `{s}`"))?; - return Ok(n * std::f64::consts::PI); - } - t.parse::() - .map_err(|_| format!("bad theta `{s}`")) -} - -pub fn push_op(circuit: &Value, gate: &str, qubits: Vec, theta: Option) -> Result { - let n = circuit - .get("qubits") - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) - .ok_or_else(|| "circuit missing qubits".to_string())? as usize; - check_qubits(n)?; - let g = gate.to_ascii_uppercase(); - if !is_meta_gate(&g) || !qubits.is_empty() { - for &q in &qubits { - if q >= n { - return Err(format!("qubit {q} out of range for n={n}")); - } - } - } - if is_meta_gate(&g) { - // ok with empty qubits (barrier / measure-all) - } else if qubits.is_empty() { - return Err(format!("gate `{g}` needs qubits")); - } - let mut obj = circuit.as_object().cloned().unwrap_or_default(); - let mut ops = obj - .get("ops") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - let mut op = json!({ - "gate": g, - "qubits": qubits, - }); - if let Some(t) = theta { - op.as_object_mut().unwrap().insert("theta".into(), json!(t)); - } - ops.push(op); - obj.insert("ops".into(), Value::Array(ops)); - Ok(Value::Object(obj)) -} - -/// Append another circuit's ops, a single op map, or reject bare gate handles without qubits. -pub fn append(circuit: &Value, op: &Value) -> Result { - let n = circuit - .get("qubits") - .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) - .ok_or_else(|| "circuit missing qubits".to_string())? as usize; - let mut obj = circuit.as_object().cloned().unwrap_or_default(); - let mut ops = obj - .get("ops") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - - if let Some(arr) = op.get("ops").and_then(|v| v.as_array()) { - let other_n = op - .get("qubits") - .and_then(|v| v.as_u64()) - .unwrap_or(n as u64) as usize; - if other_n > n { - return Err(format!( - "append: other circuit qubits={other_n} exceeds this n={n}" - )); - } - for row in arr { - ops.push(row.clone()); - } - } else if op.get("gate").or_else(|| op.get("门")).is_some() { - let parsed = parse_ops(&json!({ "ops": [op] }))?; - for p in parsed { - for &q in &p.qubits { - if q >= n { - return Err(format!("append qubit {q} out of range for n={n}")); - } - } - ops.push(op_to_json(&p)); - } - } else if op.get("name").or_else(|| op.get("名")).is_some() { - return Err("append gate handle needs an op with qubits; pass a circuit or {{gate,qubits}}".into()); - } else { - return Err("append needs a circuit (ops) or op {{gate,qubits}}".into()); - } - - obj.insert("ops".into(), Value::Array(ops)); - Ok(Value::Object(obj)) -} - -/// Bloch vector (x,y,z) for reduced density of `qubit` (LSB = qubit 0). -pub fn bloch_vector(amps: &[C], qubits: usize, qubit: usize) -> Result<(f64, f64, f64), String> { - if qubit >= qubits { - return Err(format!("bloch qubit {qubit} out of range for n={qubits}")); - } - let mut rho00 = C::zero(); - let mut rho01 = C::zero(); - let mut rho11 = C::zero(); - let dim = amps.len(); - let mask = 1usize << qubit; - for i in 0..dim { - if i & mask != 0 { - continue; - } - let i0 = i; - let i1 = i | mask; - let a0 = amps[i0]; - let a1 = amps[i1]; - // ρ00 += |a0|², ρ11 += |a1|², ρ01 += a0 conj(a1) - rho00 = rho00.add(C::new(a0.norm_sq(), 0.0)); - rho11 = rho11.add(C::new(a1.norm_sq(), 0.0)); - rho01 = rho01.add(a0.mul(C::new(a1.re, -a1.im))); - } - let x = 2.0 * rho01.re; - let y = 2.0 * rho01.im; - let z = rho00.re - rho11.re; - Ok((x, y, z)) -} - -/// Named single-/two-qubit unitary as row-major nested list of `{re,im}`. -pub fn named_gate_matrix(name: &str, theta: Option) -> Result>, String> { - let g = name.trim().to_ascii_uppercase(); - let s = std::f64::consts::FRAC_1_SQRT_2; - let m = match g.as_str() { - "I" | "ID" | "IDENTITY" => vec![ - vec![C::one(), C::zero()], - vec![C::zero(), C::one()], - ], - "X" | "NOT" => vec![ - vec![C::zero(), C::one()], - vec![C::one(), C::zero()], - ], - "Y" => vec![ - vec![C::zero(), C::new(0.0, -1.0)], - vec![C::new(0.0, 1.0), C::zero()], - ], - "Z" => vec![ - vec![C::one(), C::zero()], - vec![C::zero(), C::new(-1.0, 0.0)], - ], - "S" => vec![ - vec![C::one(), C::zero()], - vec![C::zero(), C::new(0.0, 1.0)], - ], - "T" => vec![ - vec![C::one(), C::zero()], - vec![C::zero(), C::new(s, s)], - ], - "H" | "HADAMARD" => vec![ - vec![C::new(s, 0.0), C::new(s, 0.0)], - vec![C::new(s, 0.0), C::new(-s, 0.0)], - ], - "RX" => { - let th = theta.ok_or("Rx needs theta")?; - let half = th / 2.0; - let c = half.cos(); - let sn = half.sin(); - vec![ - vec![C::new(c, 0.0), C::new(0.0, -sn)], - vec![C::new(0.0, -sn), C::new(c, 0.0)], - ] - } - "RY" => { - let th = theta.ok_or("Ry needs theta")?; - let half = th / 2.0; - let c = half.cos(); - let sn = half.sin(); - vec![ - vec![C::new(c, 0.0), C::new(-sn, 0.0)], - vec![C::new(sn, 0.0), C::new(c, 0.0)], - ] - } - "RZ" => { - let th = theta.ok_or("Rz needs theta")?; - let half = th / 2.0; - vec![ - vec![C::new((-half).cos(), (-half).sin()), C::zero()], - vec![C::zero(), C::new(half.cos(), half.sin())], - ] - } - "CX" | "CNOT" | "CN" => vec![ - vec![C::one(), C::zero(), C::zero(), C::zero()], - vec![C::zero(), C::one(), C::zero(), C::zero()], - vec![C::zero(), C::zero(), C::zero(), C::one()], - vec![C::zero(), C::zero(), C::one(), C::zero()], - ], - "CZ" => vec![ - vec![C::one(), C::zero(), C::zero(), C::zero()], - vec![C::zero(), C::one(), C::zero(), C::zero()], - vec![C::zero(), C::zero(), C::one(), C::zero()], - vec![C::zero(), C::zero(), C::zero(), C::new(-1.0, 0.0)], - ], - "SWAP" => vec![ - vec![C::one(), C::zero(), C::zero(), C::zero()], - vec![C::zero(), C::zero(), C::one(), C::zero()], - vec![C::zero(), C::one(), C::zero(), C::zero()], - vec![C::zero(), C::zero(), C::zero(), C::one()], - ], - other => { - return Err(format!( - "unknown gate `{other}` (I/X/Y/Z/H/S/T/Rx/Ry/Rz/CX/CZ/SWAP)" - )); - } - }; - Ok(m) -} - -pub fn matrix_to_json(m: &[Vec]) -> Value { - Value::Array( - m.iter() - .map(|row| Value::Array(row.iter().map(|c| c.to_json()).collect())) - .collect(), - ) -} - -fn parse_complex_cell(v: &Value) -> Result { - match v { - Value::Number(n) => Ok(C::new( - n.as_f64().ok_or_else(|| "bad matrix cell".to_string())?, - 0.0, - )), - Value::String(s) => { - let t = s.trim(); - t.parse::() - .map(|f| C::new(f, 0.0)) - .map_err(|_| format!("matrix cell string not a number: `{s}`")) - } - Value::Object(map) => { - let re = map - .get("re") - .and_then(|x| x.as_f64()) - .ok_or_else(|| "complex cell needs `re`".to_string())?; - let im = map.get("im").and_then(|x| x.as_f64()).unwrap_or(0.0); - Ok(C::new(re, im)) - } - Value::Array(a) if a.len() == 2 => { - let re = a[0] - .as_f64() - .ok_or_else(|| "complex pair needs numbers".to_string())?; - let im = a[1] - .as_f64() - .ok_or_else(|| "complex pair needs numbers".to_string())?; - Ok(C::new(re, im)) - } - _ => Err("matrix cell must be number or {re,im}".into()), - } -} - -/// Parse nested list / column-map table into matrix rows. -pub fn parse_matrix(v: &Value) -> Result>, String> { - match v { - Value::Array(rows) => { - let mut out = Vec::with_capacity(rows.len()); - for (i, row) in rows.iter().enumerate() { - match row { - Value::Array(cells) => { - let mut r = Vec::with_capacity(cells.len()); - for c in cells { - r.push(parse_complex_cell(c)?); - } - out.push(r); - } - other => { - // Flat list of complexes → treat as single row only if nested fails. - // Prefer: list of row lists. - return Err(format!( - "matrix row {i}: expected list of cells, got {other}" - )); - } - } - } - if out.is_empty() { - return Err("matrix is empty".into()); - } - let w = out[0].len(); - if w == 0 || out.iter().any(|r| r.len() != w) { - return Err("matrix rows must be non-empty and equal length".into()); - } - Ok(out) - } - Value::Object(map) => { - // Column-oriented: keys are column names with list values → transpose to rows. - // Or single key holding nested arrays. - if let Some(Value::Array(rows)) = map.values().next() { - if rows.iter().all(|r| r.is_array()) && map.len() == 1 { - return parse_matrix(&Value::Array(rows.clone())); - } - } - // Horizontal 2-col map like | a | b | with list cells → one row per index - let cols: Vec<&Vec> = map - .values() - .filter_map(|v| v.as_array()) - .collect(); - if cols.is_empty() { - return Err("matrix map needs list columns".into()); - } - let n = cols[0].len(); - if cols.iter().any(|c| c.len() != n) { - return Err("matrix columns length mismatch".into()); - } - let mut out = Vec::with_capacity(n); - for i in 0..n { - let mut row = Vec::with_capacity(cols.len()); - for c in &cols { - row.push(parse_complex_cell(&c[i])?); - } - out.push(row); - } - Ok(out) - } - _ => Err("matrix must be nested list or table".into()), - } -} - -pub fn matrices_close(a: &[Vec], b: &[Vec], tol: f64) -> bool { - if a.len() != b.len() { - return false; - } - for (ra, rb) in a.iter().zip(b.iter()) { - if ra.len() != rb.len() { - return false; - } - for (ca, cb) in ra.iter().zip(rb.iter()) { - if (ca.re - cb.re).abs() > tol || (ca.im - cb.im).abs() > tol { - return false; - } - } - } - true -} - -pub fn gate_new(name: &str, theta: Option) -> Result { - let g = name.trim().to_ascii_uppercase(); - // Validate known gate. - let _ = named_gate_matrix(&g, theta)?; - let mut out = json!({ "name": g }); - if let Some(t) = theta { - out.as_object_mut() - .unwrap() - .insert("theta".into(), json!(t)); - } - Ok(out) -} - -fn is_power_of_two(n: usize) -> bool { - n > 0 && (n & (n - 1)) == 0 -} - -pub fn check_unitary(m: &[Vec], tol: f64) -> Result<(), String> { - let n = m.len(); - if n == 0 || m.iter().any(|r| r.len() != n) { - return Err("matrix must be square".into()); - } - // U† U ≈ I - for i in 0..n { - for j in 0..n { - let mut re = 0.0; - let mut im = 0.0; - for k in 0..n { - // (U†)_{ik} = conj(U_ki); sum_k conj(U_ki)*U_kj - let a = m[k][i]; - let b = m[k][j]; - re += a.re * b.re + a.im * b.im; - im += a.re * b.im - a.im * b.re; - } - let expect = if i == j { 1.0 } else { 0.0 }; - if (re - expect).abs() > tol || im.abs() > tol { - return Err(format!( - "matrix not unitary within tol={tol} (U†U[{i},{j}]≈{re}+{im}i)" - )); - } - } - } - Ok(()) -} - -/// Build a custom gate handle from a nested matrix (or table). -pub fn gate_from_matrix(matrix: &Value, name: Option<&str>) -> Result { - let m = parse_matrix(matrix)?; - let n = m.len(); - if !is_power_of_two(n) { - return Err(format!( - "gate matrix size {n} must be a power of two (2^k × 2^k)" - )); - } - check_unitary(&m, 1e-6)?; - let label = name - .map(|s| s.trim()) - .filter(|s| !s.is_empty()) - .unwrap_or("U") - .to_string(); - Ok(json!({ - "name": label, - "custom": true, - "matrix": matrix_to_json(&m), - })) -} - -pub fn gate_matrix_of(gate: &Value) -> Result>, String> { - if let Some(m) = gate.get("matrix").or_else(|| gate.get("矩阵")) { - if !m.is_null() { - return parse_matrix(m); - } - } - let name = gate - .get("name") - .or_else(|| gate.get("名")) - .and_then(|v| v.as_str()) - .ok_or_else(|| "gate missing name".to_string())?; - let theta = gate - .get("theta") - .or_else(|| gate.get("参数")) - .and_then(|v| v.as_f64()); - named_gate_matrix(name, theta) -} - -fn parse_qubits_arg(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::Null) => Ok(vec![0]), - Some(Value::Number(n)) => { - let u = n - .as_u64() - .or_else(|| n.as_i64().map(|i| i as u64)) - .ok_or_else(|| "bad qubits".to_string())? as usize; - Ok(vec![u]) - } - Some(Value::Array(a)) => a - .iter() - .map(|x| { - x.as_u64() - .or_else(|| x.as_i64().map(|i| i as u64)) - .ok_or_else(|| "bad qubit index".to_string()) - .map(|u| u as usize) - }) - .collect(), - Some(Value::String(s)) => parse_qubit_list(s), - _ => Err("qubits must be int or list".into()), - } -} - -/// Apply a gate handle (named or custom matrix) onto a circuit. -pub fn apply_gate(circuit: &Value, gate: &Value, qubits: Option<&Value>) -> Result { - let qs = parse_qubits_arg(qubits)?; - let name = gate - .get("name") - .or_else(|| gate.get("名")) - .and_then(|v| v.as_str()) - .unwrap_or("U"); - let custom = gate - .get("custom") - .and_then(|v| v.as_bool()) - .unwrap_or(false) - || gate.get("matrix").or_else(|| gate.get("矩阵")).is_some_and(|m| !m.is_null()); - if custom { - let mat = gate_matrix_of(gate)?; - let dim = mat.len(); - let k = (dim as f64).log2() as usize; - if 1usize << k != dim { - return Err("custom gate matrix size must be 2^k".into()); - } - if qs.len() != k { - return Err(format!( - "custom gate is {k}-qubit (matrix {dim}x{dim}); got {} qubit index(es)", - qs.len() - )); - } - let n = circuit - .get("qubits") - .and_then(|v| v.as_u64()) - .ok_or_else(|| "circuit missing qubits".to_string())? as usize; - for &q in &qs { - if q >= n { - return Err(format!("qubit {q} out of range for n={n}")); - } - } - let mut obj = circuit.as_object().cloned().unwrap_or_default(); - let mut ops = obj - .get("ops") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - ops.push(op_to_json(&Op { - gate: name.to_ascii_uppercase(), - qubits: qs, - theta: None, - matrix: Some(mat), - })); - obj.insert("ops".into(), Value::Array(ops)); - return Ok(Value::Object(obj)); - } - let theta = gate - .get("theta") - .or_else(|| gate.get("参数")) - .and_then(|v| v.as_f64()); - let g = name.trim().to_ascii_uppercase(); - let mat = named_gate_matrix(&g, theta)?; - let k = { - let mut k = 0usize; - let mut d = mat.len(); - while d > 1 { - if d % 2 != 0 { - return Err(format!("gate `{g}` matrix size not power of two")); - } - d /= 2; - k += 1; - } - k - }; - if qs.len() != k { - return Err(format!("gate `{g}` needs {k} qubit(s), got {}", qs.len())); - } - push_op(circuit, &g, qs, theta) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn h_bloch_on_plus() { - let mut amps = zero_state(1); - apply_h(&mut amps, 0); - let (x, y, z) = bloch_vector(&s, 1, 0).unwrap(); - assert!((x - 1.0).abs() < 1e-9, "x={x}"); - assert!(y.abs() < 1e-9, "y={y}"); - assert!(z.abs() < 1e-9, "z={z}"); - } - - #[test] - fn h_matrix_matches() { - let m = named_gate_matrix("H", None).unwrap(); - let s = std::f64::consts::FRAC_1_SQRT_2; - let expect = vec![ - vec![C::new(s, 0.0), C::new(s, 0.0)], - vec![C::new(s, 0.0), C::new(-s, 0.0)], - ]; - assert!(matrices_close(&m, &expect, 1e-12)); - } - - #[test] - fn custom_h_unitary_on_zero() { - let s = std::f64::consts::FRAC_1_SQRT_2; - let u = vec![ - vec![C::new(s, 0.0), C::new(s, 0.0)], - vec![C::new(s, 0.0), C::new(-s, 0.0)], - ]; - let mut amps = zero_state(1); - apply_unitary(&mut amps, &[0], &u).unwrap(); - assert!((amps[0].norm_sq() - 0.5).abs() < 1e-12); - assert!((amps[1].norm_sq() - 0.5).abs() < 1e-12); - } -} diff --git a/plugins/web/README.md b/plugins/web/README.md deleted file mode 100755 index 329c26a..0000000 --- a/plugins/web/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Marqdo `plugins/web` — Go (C ABI v2) - -施工图:[doc/design/ext-web-go-rewrite.md](../../doc/design/ext-web-go-rewrite.md) · ADR:[0004](../../doc/adr/0004-web-plugin-go.md) - -**Default native web plugin (W-G13).** `plugin.native_path name=web` resolves `plugins/web/build/libweb.so` (and copies under `target/{debug,release}/`). - -## Build - -```bash -./scripts/build-web-plugin.sh -# → plugins/web/build/libweb.so -# → also copied to target/debug|release/libweb.so -``` - -Requires **Go 1.22+** with cgo (`CGO_ENABLED=1`) and a C toolchain. - -Override path: `export MARQDO_WEB_PLUGIN=$PWD/plugins/web/build/libweb.so` - -## Layout - -| Path | Role | -|------|------| -| `plugin.go` / `abi_*.go` | `//export` ABI entry + registration | -| `abi/marqdo_abi_cgo.h` | C contract for cgo | -| `internal/*` | page / db / http / ws / … | - -The legacy Rust implementation was archived during v1.6 and then removed from the -working tree (it remains in git history before commit ``); see -`CHANGELOG.md` “默认 libweb 为 Go”。 diff --git a/plugins/web/abi/marqdo_abi.h b/plugins/web/abi/marqdo_abi.h deleted file mode 100755 index c61eec5..0000000 --- a/plugins/web/abi/marqdo_abi.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Marqdo plugin ABI v2 — C contract (source of truth). - * - * Plugins are optional shared libraries (.dll / .so / .dylib), never linked - * into the marqdo binary. Values cross the boundary as UTF-8 JSON. - * - * v1: register_fn, alloc, free - * v2: + host_query (allowlisted host introspection for plugins) - */ -#ifndef MARQDO_ABI_H -#define MARQDO_ABI_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MARQDO_ABI_VERSION 2u -#define MARQDO_ABI_VERSION_MIN 1u - -/* Plugin function: args_json is a UTF-8 JSON object whose keys are param names. - * On success: return 0, set *out_json to a heap string (host frees via free). - * On failure: return non-zero; optional *err_msg heap string (host frees). - * out_json / err_msg may be left NULL. - */ -typedef int (*MarqdoPluginFn)(const char *args_json, char **out_json, char **err_msg); - -/* Host → plugin query (v2). `name` is an allowlisted query id. - * Same success/failure convention as MarqdoPluginFn. - */ -typedef int (*MarqdoHostQueryFn)(void *userdata, const char *name, const char *args_json, - char **out_json, char **err_msg); - -typedef struct MarqdoHostApi { - void *userdata; - /* params: comma-separated param names in order, e.g. "a,b". May be "". */ - int (*register_fn)(void *userdata, const char *name, const char *params, - MarqdoPluginFn fn); - void *(*alloc)(size_t n); - void (*free)(void *p); - /* v2: NULL for hosts that only speak v1; required when plugin abi >= 2 */ - MarqdoHostQueryFn host_query; -} MarqdoHostApi; - -/* Required exports from every plugin shared library. */ -uint32_t marqdo_plugin_abi_version(void); -int marqdo_plugin_init(const MarqdoHostApi *host); -void marqdo_plugin_shutdown(void); - -#ifdef __cplusplus -} -#endif - -#endif /* MARQDO_ABI_H */ diff --git a/plugins/web/abi/marqdo_abi_cgo.h b/plugins/web/abi/marqdo_abi_cgo.h deleted file mode 100755 index f2ab0cd..0000000 --- a/plugins/web/abi/marqdo_abi_cgo.h +++ /dev/null @@ -1,40 +0,0 @@ -/* Go/cgo local ABI view — same layout as include/marqdo_abi.h. - * cgo //export cannot emit `const` on parameters; this header matches - * the generated prototypes so -buildmode=c-shared links cleanly. - * Wire format & semantics remain ABI v2 (see include/marqdo_abi.h). - */ -#ifndef MARQDO_ABI_CGO_H -#define MARQDO_ABI_CGO_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MARQDO_ABI_VERSION 2u -#define MARQDO_ABI_VERSION_MIN 1u - -typedef int (*MarqdoPluginFn)(char *args_json, char **out_json, char **err_msg); - -typedef int (*MarqdoHostQueryFn)(void *userdata, char *name, char *args_json, - char **out_json, char **err_msg); - -typedef struct MarqdoHostApi { - void *userdata; - int (*register_fn)(void *userdata, char *name, char *params, MarqdoPluginFn fn); - void *(*alloc)(size_t n); - void (*free)(void *p); - MarqdoHostQueryFn host_query; -} MarqdoHostApi; - -uint32_t marqdo_plugin_abi_version(void); -int marqdo_plugin_init(MarqdoHostApi *host); -void marqdo_plugin_shutdown(void); - -#ifdef __cplusplus -} -#endif - -#endif /* MARQDO_ABI_CGO_H */ diff --git a/plugins/web/abi_artifact.go b/plugins/web/abi_artifact.go deleted file mode 100755 index fb77ecc..0000000 --- a/plugins/web/abi_artifact.go +++ /dev/null @@ -1,365 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_render_nodes(char *args_json, char **out_json, char **err_msg); -extern int web_render_document(char *args_json, char **out_json, char **err_msg); -extern int web_dom_markdown(char *args_json, char **out_json, char **err_msg); -extern int web_serve_root(char *args_json, char **out_json, char **err_msg); -extern int web_inspect(char *args_json, char **out_json, char **err_msg); -extern int web_app_use(char *args_json, char **out_json, char **err_msg); -extern int web_route_use(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/artifact" - "github.com/marqdo/marqdo/plugins/web/internal/httpx" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" - "github.com/marqdo/marqdo/plugins/web/internal/page" - "github.com/marqdo/marqdo/plugins/web/internal/plugin" -) - -//export web_render_nodes -func web_render_nodes(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pg := asPageMap(args["page"]) - title := "" - if pg != nil { - if t, ok := pg["title"].(string); ok { - title = t - } - } - if t, ok := argStr(args, "title"); ok && t != "" { - title = t - } - html, err := artifact.RenderViewDocument(title, args["nodes"], nil) - return replyJSON(outJSON, errMsg, html, err) -} - -//export web_render_document -func web_render_document(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pg := asPageMap(args["page"]) - title := "" - body := "" - if pg != nil { - if t, ok := pg["title"].(string); ok { - title = t - } - if b, ok := pg["body"].(string); ok { - body = b - } - } - if b, ok := argStr(args, "body"); ok && b != "" { - body = b - } - if t, ok := argStr(args, "title"); ok && t != "" { - title = t - } - return replyJSON(outJSON, errMsg, artifact.RenderDocument(title, body), nil) -} - -//export web_dom_markdown -func web_dom_markdown(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - text, _ := argStr(args, "text") - return replyJSON(outJSON, errMsg, artifact.MarkdownHTML(text), nil) -} - -// prepareArtifactApp shares discovery and startup assembly between direct serving -// and resource composition. Listening starts only after resources have been bound. -func prepareArtifactApp(args map[string]any) (map[string]any, error) { - root, _ := argStr(args, "root") - if root == "" { - root = "." - } - abs, err := filepath.Abs(root) - if err != nil { - return nil, err - } - if st, err := os.Stat(abs); err != nil || !st.IsDir() { - return nil, fmt.Errorf("web.prepare: root not a directory: %s", abs) - } - files, err := artifact.ScanRoot(abs) - if err != nil { - return nil, err - } - host, _ := argStr(args, "host") - if host == "" { - host = "127.0.0.1" - } - port := float64(18081) - if v, ok := args["port"]; ok && v != nil { - switch t := v.(type) { - case float64: - port = t - case string: - if n, e := strconv.Atoi(t); e == nil { - port = float64(n) - } - } - } - documentPage := func(f artifact.ArtifactFile) (map[string]any, error) { - title := f.Meta["title"] - if title == "" { - title = f.Meta["标题"] - } - nodes, structured, err := artifact.AssembleView(f, func(path string, args map[string]any) (any, error) { - return plugin.RunArtifactAtRoot(path, args, abs) - }) - if err != nil { - return nil, err - } - pg := page.New(map[string]any{"title": title, "intro": artifact.MarkdownHTML(f.Body)}) - stampArtifactData(pg, f.Meta) - if structured { - // Validate structure and Resource contracts without querying or posting. - if _, err := artifact.CollectDocumentHead(nodes); err != nil { - return nil, fmt.Errorf("%s: %w", f.Rel, err) - } - if _, err := artifact.RenderNodesWithResources(nodes, httpx.ValidateViewResource); err != nil { - return nil, fmt.Errorf("%s: %w", f.Rel, err) - } - pg["artifact_nodes"] = nodes - } - return pg, nil - } - home := page.New(map[string]any{"title": "Marqdo"}) - for _, f := range files { - if f.Kind == "web" && f.Route == "/" { - home, err = documentPage(f) - if err != nil { - return nil, err - } - break - } - } - a := app.New(map[string]any{ - "page": home, - "db": args["db"], - "host": host, - "port": port, - }) - artifactRoutes := map[string]any{} - for _, f := range files { - if f.Kind == "web" { - if f.Route == "/" { - continue - } - pg, err := documentPage(f) - if err != nil { - return nil, err - } - out, err := app.Route(a, f.Route, pg) - if err != nil { - return nil, err - } - a = out - continue - } - // endpoint - req := f.Meta["request"] - if req == "" { - req = f.Meta["请求"] - } - if req == "" { - req = "json" - } - resp := f.Meta["response"] - if resp == "" { - resp = f.Meta["响应"] - } - if resp == "" { - resp = "json" - } - auth := f.Meta["auth"] - if auth == "" { - auth = f.Meta["鉴权"] - } - key := f.Method + " " + f.Route - artifactRoutes[key] = map[string]any{ - "method": f.Method, - "path": f.Route, - "file": f.Path, - "request": req, - "response": resp, - "auth": auth, - "kind": "endpoint", - } - } - if len(artifactRoutes) > 0 { - a["artifact_routes"] = artifactRoutes - } - if mw := args["middleware"]; mw != nil { - out, err := middleware.Configure(a, map[string]any{"security": mw}) - if err != nil { - return nil, err - } - a = out - } - if sd, ok := argStr(args, "static_dir"); ok && sd != "" { - out, err := app.Static(a, sd, "/static") - if err != nil { - return nil, err - } - a = out - } - a["artifact_declared"] = artifact.InspectBag(nil, files)["declared"] - a["inspect"] = artifact.InspectBag(a, files) - a["artifact_root"] = abs - return a, nil -} - -//export web_prepare_root -func web_prepare_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - a, err := prepareArtifactApp(args) - return replyJSON(outJSON, errMsg, a, err) -} - -//export web_serve_root -func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - a, err := prepareArtifactApp(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - inspection, err := httpx.InspectApp(a) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - _, err = httpx.Listen(a, a["artifact_root"].(string)) - return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "value": inspection, "error": nil}, err) -} - -//export web_inspect -func web_inspect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - if root, ok := argStr(args, "root"); ok && root != "" { - files, err := artifact.ScanRoot(root) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, files), nil) - } - a := asPageMap(args["app"]) - if a == nil { - return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, nil), nil) - } - inspection, err := httpx.InspectApp(a) - return replyJSON(outJSON, errMsg, inspection, err) -} - -//export web_app_use -func web_app_use(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - a := asPageMap(args["app"]) - out, err := middleware.Configure(a, map[string]any{"security": args["middleware"]}) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_route_use -func web_route_use(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - rt := asPageMap(args["route"]) - if rt == nil { - rt = map[string]any{} - } - rt["middleware"] = args["middleware"] - return replyJSON(outJSON, errMsg, rt, nil) -} - -// stampArtifactData applies flat Document metadata (ADR 0007) onto a page bag. -func stampArtifactData(pg map[string]any, meta map[string]string) { - if pg == nil || meta == nil { - return - } - src := meta["data_source"] - if src == "" { - src = meta["数据源"] - } - if src != "" { - pg["data_source"] = src - } - order := meta["data_order"] - if order == "" { - order = meta["排序"] - } - if order != "" { - pg["order"] = order - } - where := meta["data_where"] - if where == "" { - where = meta["条件"] - } - if where != "" { - // col=val,col2=val2 → query map (values may contain {param}) - q := map[string]any{} - for _, part := range strings.Split(where, ",") { - part = strings.TrimSpace(part) - if part == "" { - continue - } - k, v, ok := strings.Cut(part, "=") - if !ok { - continue - } - q[strings.TrimSpace(k)] = strings.TrimSpace(v) - } - if len(q) > 0 { - pg["query"] = q - // Filtered Document routes render as article detail (007 /post/{slug}). - pg["detail"] = true - } - } - if d := meta["detail"]; d != "" { - pg["detail"] = d == "true" || d == "True" || d == "1" - } - if d := meta["详情"]; d != "" { - pg["detail"] = d == "true" || d == "True" || d == "1" || d == "是" - } - prefix := meta["link_prefix"] - if prefix == "" { - prefix = meta["链接前缀"] - } - if prefix != "" { - pg["link_prefix"] = prefix - } else if src != "" && where == "" { - // List pages default card links to /post/{slug}. - pg["link_prefix"] = "/post/" - } -} diff --git a/plugins/web/abi_extra.go b/plugins/web/abi_extra.go deleted file mode 100755 index d4e4095..0000000 --- a/plugins/web/abi_extra.go +++ /dev/null @@ -1,685 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" -*/ -import "C" - -import ( - "fmt" - "strconv" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/auth" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/form" - "github.com/marqdo/marqdo/plugins/web/internal/httpx" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" - "github.com/marqdo/marqdo/plugins/web/internal/password" - "github.com/marqdo/marqdo/plugins/web/internal/rbac" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func argUint64(args map[string]any, def uint64, keys ...string) uint64 { - for _, k := range keys { - v, ok := args[k] - if !ok || v == nil { - continue - } - switch t := v.(type) { - case float64: - if t > 0 { - return uint64(t) - } - case int: - if t > 0 { - return uint64(t) - } - case int64: - if t > 0 { - return uint64(t) - } - case uint64: - if t > 0 { - return t - } - case string: - if n, e := strconv.ParseUint(t, 10, 64); e == nil && n > 0 { - return n - } - } - } - return def -} - -func txnOpt(args map[string]any) string { - s, _ := argStr(args, "txn", "事务") - return s -} - -//export web_db_begin -func web_db_begin(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Begin(url) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_commit -func web_db_commit(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - txn, err := argStrReq(args, "txn", "事务") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Commit(txn) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_rollback -func web_db_rollback(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - txn, err := argStrReq(args, "txn", "事务") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Rollback(txn) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_migrate -func web_db_migrate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - steps := args["steps"] - if steps == nil { - steps = []any{} - } - out, err := db.Migrate(url, steps) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_fts_create -func web_db_fts_create(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - name, _ := argStr(args, "name") - out, err := db.FtsCreate(url, tableName, args["columns"], name) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_search -func web_db_search(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - q, _ := argStr(args, "q") - limit := int64(50) - if v, ok := args["limit"].(float64); ok { - limit = int64(v) - } - name, _ := argStr(args, "name") - out, err := db.Search(url, tableName, q, limit, name) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_form_rules -func web_form_rules(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - formBag := asPageMap(args["form"]) - if args["rules"] == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `rules`")) - } - return replyJSON(outJSON, errMsg, form.SetRules(formBag, args["rules"]), nil) -} - -//export web_form_labels -func web_form_labels(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - submit, _ := argStr(args, "submit") - if submit == "" { - submit, _ = argStr(args, "提交") - } - cancel, _ := argStr(args, "cancel") - if cancel == "" { - cancel, _ = argStr(args, "取消") - } - cancelHref, _ := argStr(args, "cancel_href") - if cancelHref == "" { - cancelHref, _ = argStr(args, "取消链接") - } - return replyJSON(outJSON, errMsg, form.SetLabels(asPageMap(args["form"]), submit, cancel, cancelHref), nil) -} - -//export web_form_validate -func web_form_validate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - if args["data"] == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `data`")) - } - return replyJSON(outJSON, errMsg, form.Validate(asPageMap(args["form"]), args["rules"], args["data"]), nil) -} - -//export web_form_render -func web_form_render(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, _ := argStr(args, "id") - if id == "" { - id = "form" - } - csrf, _ := argStr(args, "csrf") - html := form.Render(asPageMap(args["form"]), id, args["data"], args["errors"], csrf) - return replyJSON(outJSON, errMsg, html, nil) -} - -//export web_form_submit -func web_form_submit(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - if args["data"] == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `data`")) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := form.Submit(asPageMap(args["form"]), args["data"], url) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_table_info -func web_db_table_info(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - cols, err := db.TableInfo(url, tableName) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - arr := make([]any, len(cols)) - for i, c := range cols { - arr[i] = map[string]any{ - "name": c.Name, - "type": c.SQLType, - "notnull": c.NotNull, - "pk": c.PK, - } - } - return replyJSON(outJSON, errMsg, map[string]any{"columns": arr}, nil) -} - -//export web_form_from_schema -func web_form_from_schema(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - action, _ := argStr(args, "action") - id, _ := argStr(args, "id") - adminPrefix, _ := argStr(args, "admin_prefix", "后台前缀") - if adminPrefix == "" { - adminPrefix = "/admin" - } - out, err := form.FromSchema(url, tableName, action, id, adminPrefix) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_mount_form -func web_app_mount_form(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - if args["form"] == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `form`")) - } - out, err := app.MountForm(asPageMap(args["app"]), id, args["form"]) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_static -func web_app_static(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - dir, err := argStrReq(args, "dir") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - mount, _ := argStr(args, "mount") - out, err := app.Static(asPageMap(args["app"]), dir, mount) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_middleware -func web_app_middleware(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := middleware.Configure(asPageMap(args["app"]), args) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_listen -func web_listen(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - appBag := asPageMap(args["app"]) - if len(appBag) == 0 { - appBag = args - } - root := entryDir() - if artifactRoot, ok := appBag["artifact_root"].(string); ok && artifactRoot != "" { - root = artifactRoot - } - if _, err := httpx.InspectApp(appBag); err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := httpx.Listen(appBag, root) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_password_hash -func web_password_hash(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pw, err := argStrReq(args, "password", "密码") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := password.HashResult(pw) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_session_new -func web_session_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - ttl := argUint64(args, 3600, "ttl_sec", "ttl", "session_ttl") - return replyJSON(outJSON, errMsg, session.New(ttl), nil) -} - -//export web_session_set -func web_session_set(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id", "session_id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, session.Set(id, key, args["value"]), nil) -} - -//export web_session_get -func web_session_get(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id", "session_id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, session.Get(id, key), nil) -} - -//export web_session_del -func web_session_del(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id", "session_id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, session.Del(id, key), nil) -} - -//export web_session_destroy -func web_session_destroy(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id", "session_id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, session.Destroy(id), nil) -} - -//export web_auth_login -func web_auth_login(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - username, err := argStrReq(args, "username", "用户名", "用户") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pw, err := argStrReq(args, "password", "密码") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - ttl := argUint64(args, 3600, "session_ttl", "ttl_sec", "ttl") - out := auth.Login(username, pw, args["users"], ttl) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_auth_check -func web_auth_check(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "session_id", "id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, auth.Check(id), nil) -} - -//export web_auth_logout -func web_auth_logout(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "session_id", "id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, auth.Logout(id), nil) -} - -//export web_auth_new -func web_auth_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - ttl := argUint64(args, 3600, "session_ttl", "ttl_sec", "ttl") - return replyJSON(outJSON, errMsg, auth.New(args["users"], ttl), nil) -} - -//export web_app_auth -func web_app_auth(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := app.Auth(asPageMap(args["app"]), args["users"], args) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_oidc -func web_app_oidc(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := app.OIDC(asPageMap(args["app"]), args) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_gate -func web_app_gate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, err := argStrReq(args, "path", "路径") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := app.Gate(asPageMap(args["app"]), path, args) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_rbac -func web_app_rbac(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := app.Rbac(asPageMap(args["app"]), args) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_tenant -func web_app_tenant(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := app.Tenant(asPageMap(args["app"]), args) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_rbac_can -func web_rbac_can(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - heldRaw, _ := argStrReq(args, "permissions", "权限", "held") - neededRaw, _ := argStrReq(args, "needed", "需要") - if neededRaw == "" { - neededRaw, _ = argStrReq(args, "permission", "权限码") - } - ok := rbac.HasAny(rbac.ParseCSV(heldRaw), rbac.ParseCSV(neededRaw)) - return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "allowed": ok}, nil) -} - -//export web_rbac_ensure -func web_rbac_ensure(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - if err := rbac.EnsureSchema(url); err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, map[string]any{"ok": true}, nil) -} - -//export web_rbac_assign_role -func web_rbac_assign_role(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - user, err := argStrReq(args, "username", "用户名", "user") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - role, err := argStrReq(args, "role", "角色") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - err = rbac.AssignRole(url, user, role) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, map[string]any{"ok": true}, nil) -} - -//export web_rbac_create_role -func web_rbac_create_role(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - name, err := argStrReq(args, "name", "名称") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := rbac.CreateRole(url, name) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "id": id, "name": name}, nil) -} - -//export web_rbac_set_role_permissions -func web_rbac_set_role_permissions(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - roleName, _ := argStrReq(args, "role", "角色") - permsRaw, _ := argStrReq(args, "permissions", "权限") - grantRaw, _ := argStrReq(args, "grantable", "可授") - err = rbac.SetRolePermissionsByName(url, roleName, rbac.ParseCSV(permsRaw), rbac.ParseCSV(grantRaw)) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, map[string]any{"ok": true}, nil) -} - -//export web_rbac_list_roles -func web_rbac_list_roles(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - roles, err := rbac.ListRoles(url) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "roles": roles}, nil) -} - -//export web_rbac_list_permissions -func web_rbac_list_permissions(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - perms, err := rbac.ListPermissions(url) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "permissions": perms}, nil) -} diff --git a/plugins/web/abi_page.go b/plugins/web/abi_page.go deleted file mode 100755 index 8cec421..0000000 --- a/plugins/web/abi_page.go +++ /dev/null @@ -1,91 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_page_query(char *args_json, char **out_json, char **err_msg); -extern int web_page_order(char *args_json, char **out_json, char **err_msg); -extern int web_page_link_prefix(char *args_json, char **out_json, char **err_msg); -extern int web_page_css(char *args_json, char **out_json, char **err_msg); -extern int web_page_detail(char *args_json, char **out_json, char **err_msg); -extern int web_page_chrome(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "github.com/marqdo/marqdo/plugins/web/internal/page" -) - -//export web_page_query -func web_page_query(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out := page.SetQuery(asPageMap(args["page"]), args["query"]) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_page_order -func web_page_order(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - order, _ := argStr(args, "order", "排序") - out := page.SetOrder(asPageMap(args["page"]), order) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_page_link_prefix -func web_page_link_prefix(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - prefix, err := argStrReq(args, "prefix", "前缀") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out := page.SetLinkPrefix(asPageMap(args["page"]), prefix) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_page_css -func web_page_css(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - css, _ := argStr(args, "css", "样式") - out := page.AppendCSS(asPageMap(args["page"]), css) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_page_detail -func web_page_detail(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - on := page.AsBool(args["detail"], true) - if v, ok := args["详情"]; ok { - on = page.AsBool(v, on) - } - out := page.SetDetail(asPageMap(args["page"]), on) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_page_chrome -func web_page_chrome(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - nav, _ := argStr(args, "nav_html", "导航") - foot, _ := argStr(args, "footer_html", "页脚") - body, _ := argStr(args, "body_class", "体类") - out := page.SetChromeHTML(asPageMap(args["page"]), nav, foot, body) - return replyJSON(outJSON, errMsg, out, nil) -} diff --git a/plugins/web/abi_w10.go b/plugins/web/abi_w10.go deleted file mode 100755 index 387a45d..0000000 --- a/plugins/web/abi_w10.go +++ /dev/null @@ -1,43 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_app_proxy(char *args_json, char **out_json, char **err_msg); -extern int web_app_invoke(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "github.com/marqdo/marqdo/plugins/web/internal/invoke" - "github.com/marqdo/marqdo/plugins/web/internal/proxy" -) - -//export web_app_proxy -func web_app_proxy(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - opts, err := proxy.OptionsFromArgs(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := proxy.Register(asPageMap(args["app"]), opts) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_invoke -func web_app_invoke(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - opts, err := invoke.OptionsFromArgs(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := invoke.Register(asPageMap(args["app"]), opts) - return replyJSON(outJSON, errMsg, out, err) -} diff --git a/plugins/web/abi_w12.go b/plugins/web/abi_w12.go deleted file mode 100755 index e628fe1..0000000 --- a/plugins/web/abi_w12.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_api_key_check(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "github.com/marqdo/marqdo/plugins/web/internal/apikey" -) - -//export web_api_key_check -func web_api_key_check(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, _ := argStr(args, "key", "密钥") - auth, _ := argStr(args, "authorization", "auth", "授权") - pepper, _ := argStr(args, "pepper", "椒盐") - keys := args["keys"] - if keys == nil { - keys = args["hashes"] - } - out := apikey.Check(key, auth, pepper, keys) - return replyJSON(outJSON, errMsg, out, nil) -} diff --git a/plugins/web/abi_w6.go b/plugins/web/abi_w6.go deleted file mode 100755 index b26291b..0000000 --- a/plugins/web/abi_w6.go +++ /dev/null @@ -1,361 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_storage_new(char *args_json, char **out_json, char **err_msg); -extern int web_storage_put(char *args_json, char **out_json, char **err_msg); -extern int web_storage_get(char *args_json, char **out_json, char **err_msg); -extern int web_storage_delete(char *args_json, char **out_json, char **err_msg); -extern int web_storage_list(char *args_json, char **out_json, char **err_msg); -extern int web_media_new(char *args_json, char **out_json, char **err_msg); -extern int web_upload_validate(char *args_json, char **out_json, char **err_msg); -extern int web_upload_save(char *args_json, char **out_json, char **err_msg); -extern int web_app_upload(char *args_json, char **out_json, char **err_msg); -extern int web_app_download(char *args_json, char **out_json, char **err_msg); -extern int web_app_gallery(char *args_json, char **out_json, char **err_msg); -extern int web_page_meta(char *args_json, char **out_json, char **err_msg); -extern int web_page_head(char *args_json, char **out_json, char **err_msg); -extern int web_page_images(char *args_json, char **out_json, char **err_msg); -extern int web_head(char *args_json, char **out_json, char **err_msg); -extern int web_images(char *args_json, char **out_json, char **err_msg); -extern int web_app_icons(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "fmt" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/assets" - "github.com/marqdo/marqdo/plugins/web/internal/storage" - "github.com/marqdo/marqdo/plugins/web/internal/upload" -) - -func storageURLOf(args map[string]any, keys ...string) (string, error) { - for _, k := range keys { - if v, ok := args[k]; ok { - if s, err := app.StorageURL(v); err == nil { - return s, nil - } - } - } - return "", fmt.Errorf("missing storage url") -} - -//export web_storage_new -func web_storage_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, _ := argStr(args, "url", "地址") - if url == "" { - url = "file:data/blobs" - } - out, err := storage.Open(url) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_storage_put -func web_storage_put(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - var body, path, ct *string - if s, ok := argStr(args, "body", "正文"); ok { - body = &s - } - if s, ok := argStr(args, "path", "路径"); ok { - path = &s - } - if s, ok := argStr(args, "content_type", "类型"); ok { - ct = &s - } - out, err := storage.Put(url, key, body, path, ct) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_storage_get -func web_storage_get(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := storage.Get(url, key) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_storage_delete -func web_storage_delete(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := storage.Delete(url, key) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_storage_list -func web_storage_list(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - prefix, _ := argStr(args, "prefix", "前缀") - out, err := storage.List(url, prefix) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_media_new -func web_media_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - st := args["storage"] - if st == nil { - st = args["存储"] - } - return replyJSON(outJSON, errMsg, map[string]any{"_type": "media", "storage": st}, nil) -} - -//export web_upload_validate -func web_upload_validate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - filename, err := argStrReq(args, "filename", "文件名") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - ct, _ := argStr(args, "content_type", "类型") - if ct == "" { - ct = "application/octet-stream" - } - size := argUint64(args, 0, "size", "大小") - if size == 0 { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `size`")) - } - maxBytes := argUint64(args, 5_242_880, "max_bytes", "最大字节") - types := args["types"] - if types == nil { - types = args["允许"] - } - out := upload.Validate(filename, ct, size, maxBytes, types) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_upload_save -func web_upload_save(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - storageURL, err := storageURLOf(args, "storage", "url", "storage_url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, err := argStrReq(args, "path", "路径") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - var key, ct, prefix *string - if s, ok := argStr(args, "key", "键"); ok && s != "" { - key = &s - } - if s, ok := argStr(args, "content_type", "类型"); ok { - ct = &s - } - if s, ok := argStr(args, "prefix", "前缀"); ok { - prefix = &s - } - out, err := upload.Save(storageURL, key, path, ct, prefix) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_upload -func web_app_upload(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, _ := argStr(args, "path", "路径") - field, _ := argStr(args, "field") - storageURL, err := storageURLOf(args, "storage", "存储") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - prefix, _ := argStr(args, "prefix", "前缀") - maxBytes := argUint64(args, 5_242_880, "max_bytes", "最大字节") - types := args["types"] - if types == nil { - types = args["允许"] - } - if types == nil { - types = nil // explicit null ok - } - out, err := app.Upload(asPageMap(args["app"]), path, field, storageURL, prefix, maxBytes, types) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_download -func web_app_download(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, _ := argStr(args, "path", "路径") - storageURL, err := storageURLOf(args, "storage", "存储") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - disposition, _ := argStr(args, "disposition") - out, err := app.Download(asPageMap(args["app"]), path, storageURL, disposition) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_gallery -func web_app_gallery(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, _ := argStr(args, "path", "路径") - storageURL, err := storageURLOf(args, "storage", "存储") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - prefix, _ := argStr(args, "prefix", "前缀") - title, _ := argStr(args, "title", "标题") - downloadBase, _ := argStr(args, "download_base", "media", "下载基址") - out, err := app.Gallery(asPageMap(args["app"]), path, storageURL, prefix, title, downloadBase) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_page_meta -func web_page_meta(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - meta := args["meta"] - if meta == nil { - meta = args["table"] - } - if meta == nil { - meta = args["元数据"] - } - out := assets.AttachMeta(pageBag, meta) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_page_head -func web_page_head(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - table := args["table"] - if table == nil { - table = args["head"] - } - if table == nil { - table = args["表"] - } - out := assets.AttachHead(pageBag, table) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_page_images -func web_page_images(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - table := args["table"] - if table == nil { - table = args["images"] - } - out := assets.AttachImages(pageBag, table) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_head -func web_head(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - table := args["table"] - if table == nil { - table = args["head"] - } - if table == nil { - table = args["表"] - } - html := assets.MakeHeadHTML(table) - return replyJSON(outJSON, errMsg, html, nil) -} - -//export web_images -func web_images(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - table := args["table"] - if table == nil { - table = args["images"] - } - html := assets.MakeImagesHTML(table) - return replyJSON(outJSON, errMsg, html, nil) -} - -//export web_app_icons -func web_app_icons(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - table := args["table"] - if table == nil { - table = args["icons"] - } - out, err := app.Icons(asPageMap(args["app"]), table) - return replyJSON(outJSON, errMsg, out, err) -} diff --git a/plugins/web/abi_w7.go b/plugins/web/abi_w7.go deleted file mode 100755 index b71f9db..0000000 --- a/plugins/web/abi_w7.go +++ /dev/null @@ -1,244 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_page_paginate(char *args_json, char **out_json, char **err_msg); -extern int web_rss_build(char *args_json, char **out_json, char **err_msg); -extern int web_app_route_rss(char *args_json, char **out_json, char **err_msg); -extern int web_app_redirect(char *args_json, char **out_json, char **err_msg); -extern int web_app_error_page(char *args_json, char **out_json, char **err_msg); -extern int web_app_sitemap(char *args_json, char **out_json, char **err_msg); -extern int web_app_robots(char *args_json, char **out_json, char **err_msg); -extern int web_sitemap_build(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "fmt" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/page" - "github.com/marqdo/marqdo/plugins/web/internal/rss" - "github.com/marqdo/marqdo/plugins/web/internal/sitemap" -) - -func argInt64(args map[string]any, def int64, keys ...string) int64 { - for _, k := range keys { - v, ok := args[k] - if !ok || v == nil { - continue - } - switch t := v.(type) { - case float64: - return int64(t) - case int: - return int64(t) - case int64: - return t - case string: - if n, err := parseInt64(t); err == nil { - return n - } - } - } - return def -} - -func parseInt64(s string) (int64, error) { - var n int64 - _, err := fmt.Sscanf(s, "%d", &n) - return n, err -} - -func argStatus(args map[string]any) uint16 { - v, ok := first(args, "status", "状态") - if !ok || v == nil { - return 404 - } - switch t := v.(type) { - case float64: - return uint16(t) - case int: - if t < 0 { - return 404 - } - return uint16(t) - case int64: - if t < 0 { - return 404 - } - return uint16(t) - case string: - if n, err := parseInt64(t); err == nil && n >= 0 { - return uint16(n) - } - } - return 404 -} - -func first(args map[string]any, keys ...string) (any, bool) { - for _, k := range keys { - if v, ok := args[k]; ok && v != nil { - return v, true - } - } - return nil, false -} - -func argPermanent(args map[string]any) bool { - v, ok := first(args, "permanent", "永久") - if !ok { - return false - } - switch t := v.(type) { - case bool: - return t - case string: - switch t { - case "true", "True", "1", "yes", "真": - return true - } - case float64: - return int64(t) != 0 - } - return false -} - -func itemsOf(args map[string]any) any { - if v, ok := first(args, "items", "rows", "条目"); ok { - return v - } - return []any{} -} - -//export web_page_paginate -func web_page_paginate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - offset := argInt64(args, 0, "offset", "偏移") - limit := argInt64(args, 10, "limit", "上限") - path, _ := argStr(args, "path", "路径") - out := page.Paginate(asPageMap(args["page"]), offset, limit, path) - return replyJSON(outJSON, errMsg, out, nil) -} - -//export web_rss_build -func web_rss_build(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - title, _ := argStr(args, "title", "标题") - if title == "" { - title = "Feed" - } - link, _ := argStr(args, "link", "链接") - if link == "" { - link = "/" - } - description, _ := argStr(args, "description", "描述") - items, _ := itemsOf(args).([]any) - if items == nil { - items = []any{} - } - xml := rss.BuildRSS(title, link, description, items) - return replyJSON(outJSON, errMsg, xml, nil) -} - -//export web_app_route_rss -func web_app_route_rss(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, err := argStrReq(args, "path", "路径") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - table, err := argStrReq(args, "table", "表") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - limit := argInt64(args, 20, "limit", "上限") - order, _ := argStr(args, "order", "排序") - title, _ := argStr(args, "title", "标题") - link, _ := argStr(args, "link", "链接") - description, _ := argStr(args, "description", "描述") - out, err := app.RouteRSS(asPageMap(args["app"]), path, table, order, title, link, description, limit) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_redirect -func web_app_redirect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - from, err := argStrReq(args, "from", "来源", "path", "路径") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - to, err := argStrReq(args, "to", "目标") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := app.Redirect(asPageMap(args["app"]), from, to, argPermanent(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_error_page -func web_app_error_page(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageV, ok := first(args, "page", "页面") - if !ok { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `page`")) - } - out, err := app.ErrorPage(asPageMap(args["app"]), argStatus(args), pageV) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_sitemap -func web_app_sitemap(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, _ := argStr(args, "path", "路径") - base, _ := argStr(args, "base", "基址") - table, _ := argStr(args, "table", "表") - loc, _ := argStr(args, "loc", "定位列") - limit := argInt64(args, 1000, "limit", "上限") - items := itemsOf(args) - out, err := app.Sitemap(asPageMap(args["app"]), path, base, table, loc, limit, items) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_robots -func web_app_robots(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - body, _ := argStr(args, "body", "正文") - sitemapURL, _ := argStr(args, "sitemap", "站点地图") - out, err := app.Robots(asPageMap(args["app"]), body, sitemapURL) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_sitemap_build -func web_sitemap_build(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - base, _ := argStr(args, "base", "基址") - out := sitemap.SitemapJSON(base, itemsOf(args)) - return replyJSON(outJSON, errMsg, out, nil) -} diff --git a/plugins/web/abi_w8.go b/plugins/web/abi_w8.go deleted file mode 100755 index 8165310..0000000 --- a/plugins/web/abi_w8.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_app_route_ws(char *args_json, char **out_json, char **err_msg); -extern int web_ws_connect(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "github.com/marqdo/marqdo/plugins/web/internal/ws" -) - -//export web_app_route_ws -func web_app_route_ws(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - path, err := argStrReq(args, "path", "路径") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := ws.RouteWS(asPageMap(args["app"]), path, args) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_ws_connect -func web_ws_connect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url", "地址") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - message, _ := argStr(args, "message", "消息") - var headers map[string]any - if h, ok := args["headers"]; ok && h != nil { - if m, ok := h.(map[string]any); ok { - headers = m - } - } - timeout := argUint64(args, 30, "timeout_sec", "timeout", "超时") - out := ws.Connect(url, message, headers, timeout) - return replyJSON(outJSON, errMsg, out, nil) -} diff --git a/plugins/web/abi_w9.go b/plugins/web/abi_w9.go deleted file mode 100755 index 664cd68..0000000 --- a/plugins/web/abi_w9.go +++ /dev/null @@ -1,151 +0,0 @@ -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" - -extern int web_cache_new(char *args_json, char **out_json, char **err_msg); -extern int web_cache_get(char *args_json, char **out_json, char **err_msg); -extern int web_cache_set(char *args_json, char **out_json, char **err_msg); -extern int web_cache_del(char *args_json, char **out_json, char **err_msg); -extern int web_cache_exists(char *args_json, char **out_json, char **err_msg); -extern int web_cache_ttl(char *args_json, char **out_json, char **err_msg); -*/ -import "C" - -import ( - "github.com/marqdo/marqdo/plugins/web/internal/cache" -) - -func argOptUint64(args map[string]any, keys ...string) *uint64 { - for _, k := range keys { - v, ok := args[k] - if !ok || v == nil { - continue - } - switch t := v.(type) { - case float64: - n := uint64(t) - return &n - case int: - n := uint64(t) - return &n - case int64: - n := uint64(t) - return &n - case string: - // ignore parse errors — treat as absent - continue - } - } - return nil -} - -//export web_cache_new -func web_cache_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, _ := argStr(args, "url", "地址") - if url == "" { - url = "memory:" - } - out, err := cache.Open(url) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_cache_get -func web_cache_get(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := cache.Get(url, key) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_cache_set -func web_cache_set(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - value, err := argStrReq(args, "value", "值") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - ttl := argOptUint64(args, "ttl", "过期") - out, err := cache.Set(url, key, value, ttl) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_cache_del -func web_cache_del(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := cache.Del(url, key) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_cache_exists -func web_cache_exists(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := cache.Exists(url, key) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_cache_ttl -func web_cache_ttl(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := argStrReq(args, "url") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - key, err := argStrReq(args, "key", "键") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := cache.TTL(url, key) - return replyJSON(outJSON, errMsg, out, err) -} diff --git a/plugins/web/go.mod b/plugins/web/go.mod deleted file mode 100755 index 0591bec..0000000 --- a/plugins/web/go.mod +++ /dev/null @@ -1,34 +0,0 @@ -module github.com/marqdo/marqdo/plugins/web - -go 1.25.0 - -require ( - github.com/gorilla/websocket v1.5.3 - github.com/redis/go-redis/v9 v9.22.0 - golang.org/x/crypto v0.41.0 - modernc.org/sqlite v1.34.5 -) - -require ( - github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect - github.com/alicebob/miniredis/v2 v2.34.0 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/dustin/go-humanize v1.0.1 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.7.4 // indirect - github.com/jackc/puddle/v2 v2.2.2 // indirect - github.com/mattn/go-isatty v0.0.24 // indirect - github.com/ncruces/go-strftime v1.0.0 // indirect - github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect - github.com/yuin/goldmark v1.7.8 // indirect - github.com/yuin/gopher-lua v1.1.1 // indirect - go.uber.org/atomic v1.11.0 // indirect - golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect - golang.org/x/text v0.28.0 // indirect - modernc.org/libc v1.75.6 // indirect - modernc.org/mathutil v1.7.1 // indirect - modernc.org/memory v1.12.1 // indirect -) diff --git a/plugins/web/go.sum b/plugins/web/go.sum deleted file mode 100755 index 8410434..0000000 --- a/plugins/web/go.sum +++ /dev/null @@ -1,98 +0,0 @@ -github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE= -github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= -github.com/alicebob/miniredis/v2 v2.34.0 h1:mBFWMaJSNL9RwdGRyEDoAAv8OQc5UlEhLDQggTglU/0= -github.com/alicebob/miniredis/v2 v2.34.0/go.mod h1:kWShP4b58T1CW0Y5dViCd5ztzrDqRWqM3nksiyXk5s8= -github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= -github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= -github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= -github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= -github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= -github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= -github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= -github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= -github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= -github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= -github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= -github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= -github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= -github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= -github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= -github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= -github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= -github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= -github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0= -github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4= -github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= -github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= -github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= -github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= -github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= -github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= -github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= -golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= -golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= -golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= -golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= -golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= -golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8= -modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= -modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w= -modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I= -modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= -modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= -modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= -modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= -modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc= -modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= -modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= -modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= -modernc.org/libc v1.75.6 h1:yKk8qo+Di4gkmvRboK8ocCqH22FiUCR6jRy2OwtCRus= -modernc.org/libc v1.75.6/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ= -modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= -modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= -modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= -modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= -modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= -modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= -modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= -modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= -modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g= -modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE= -modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= -modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= -modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= -modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/plugins/web/internal/apikey/apikey.go b/plugins/web/internal/apikey/apikey.go deleted file mode 100755 index 3a6b215..0000000 --- a/plugins/web/internal/apikey/apikey.go +++ /dev/null @@ -1,93 +0,0 @@ -// Package apikey implements Bearer API key verification (G-API1). -// -// Hash formula: sha256 hex of pepper + ":" + key. -package apikey - -import ( - "crypto/sha256" - "encoding/hex" - "fmt" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -var ( - hashKeys = []string{"hash", "哈希", "key_hash", "密钥哈希"} - scopeKeys = []string{"scopes", "scope", "作用域", "权限"} -) - -// Hash returns the stored digest for pepper+key (sha256 hex of "pepper:key"). -func Hash(pepper, key string) string { - sum := sha256.Sum256([]byte(pepper + ":" + key)) - return hex.EncodeToString(sum[:]) -} - -// BearerToken strips a Bearer prefix from an Authorization header value. -func BearerToken(authorization string) string { - s := strings.TrimSpace(authorization) - if s == "" { - return "" - } - const prefix = "Bearer " - if len(s) > len(prefix) && strings.EqualFold(s[:len(prefix)], prefix) { - return strings.TrimSpace(s[len(prefix):]) - } - return s -} - -// Check verifies a raw key or Authorization header against a GFM keys table. -// Args: key or authorization, pepper, keys (rows with hash + scopes). -// Returns {"ok":true,"scopes":[...]} or {"ok":false}. -func Check(key, authorization, pepper string, keys any) map[string]any { - raw := strings.TrimSpace(key) - if raw == "" { - raw = BearerToken(authorization) - } - if raw == "" || pepper == "" { - return map[string]any{"ok": false} - } - digest := Hash(pepper, raw) - rowsAny := table.AsRows(keys) - rows, ok := rowsAny.([]any) - if !ok { - return map[string]any{"ok": false} - } - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - stored := pickCell(m, hashKeys) - if stored == "" || !strings.EqualFold(stored, digest) { - continue - } - return map[string]any{"ok": true, "scopes": parseScopes(pickCell(m, scopeKeys))} - } - return map[string]any{"ok": false} -} - -func pickCell(m map[string]any, keys []string) string { - for _, k := range keys { - if v, ok := m[k]; ok && v != nil { - return strings.TrimSpace(fmt.Sprint(v)) - } - } - return "" -} - -func parseScopes(raw string) []any { - raw = strings.TrimSpace(raw) - if raw == "" { - return []any{} - } - parts := strings.Split(raw, ",") - out := make([]any, 0, len(parts)) - for _, p := range parts { - p = strings.TrimSpace(p) - if p != "" { - out = append(out, p) - } - } - return out -} diff --git a/plugins/web/internal/apikey/apikey_test.go b/plugins/web/internal/apikey/apikey_test.go deleted file mode 100755 index bedc8fc..0000000 --- a/plugins/web/internal/apikey/apikey_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package apikey_test - -import ( - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/apikey" -) - -func TestHashFormula(t *testing.T) { - got := apikey.Hash("pep", "secret-key") - want := apikey.Hash("pep", "secret-key") - if got != want || got == "" { - t.Fatalf("hash=%q", got) - } - if got == apikey.Hash("pep", "other") { - t.Fatal("different keys should differ") - } -} - -func TestCheckMatchAndScopes(t *testing.T) { - pepper := "site-pepper" - key := "live-key-1" - digest := apikey.Hash(pepper, key) - keys := []any{ - map[string]any{ - "hash": digest, - "scopes": "read,write", - }, - } - out := apikey.Check("", "Bearer "+key, pepper, keys) - if out["ok"] != true { - t.Fatalf("match: %v", out) - } - scopes, _ := out["scopes"].([]any) - if len(scopes) != 2 || scopes[0] != "read" || scopes[1] != "write" { - t.Fatalf("scopes=%v", scopes) - } -} - -func TestCheckMiss(t *testing.T) { - keys := []any{ - map[string]any{"hash": apikey.Hash("p", "stored"), "scopes": "admin"}, - } - out := apikey.Check("wrong", "", "p", keys) - if out["ok"] != false { - t.Fatalf("expected miss: %v", out) - } -} - -func TestCheckKeyParam(t *testing.T) { - pepper := "p" - key := "direct" - digest := apikey.Hash(pepper, key) - keys := []any{map[string]any{"hash": digest, "scopes": "api"}} - out := apikey.Check(key, "", pepper, keys) - if out["ok"] != true { - t.Fatalf("%v", out) - } -} diff --git a/plugins/web/internal/app/app.go b/plugins/web/internal/app/app.go deleted file mode 100755 index 55de1ac..0000000 --- a/plugins/web/internal/app/app.go +++ /dev/null @@ -1,780 +0,0 @@ -// Package app ports minimal app bag helpers (new + route + auth + gate) for offline smoke. -package app - -import ( - "fmt" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/assets" - "github.com/marqdo/marqdo/plugins/web/internal/oidc" - "github.com/marqdo/marqdo/plugins/web/internal/session" - "github.com/marqdo/marqdo/plugins/web/internal/tenant" -) - -// New builds an app bag matching Rust web_app_new defaults used by zh-smoke. -func New(args map[string]any) map[string]any { - page := args["page"] - if page == nil { - page = map[string]any{} - } - dbv := args["db"] - host := strOpt(args, "host", "127.0.0.1") - port := float64(18081) - if v, ok := args["port"]; ok { - switch t := v.(type) { - case float64: - port = t - case string: - // leave default if unparsable - _ = t - } - } - admin := boolish(args["admin"]) - adminPrefix := strOpt(args, "admin_prefix", "/admin") - if s := strOpt(args, "后台前缀", ""); s != "" { - adminPrefix = s - } - if p, err := NormalizeAdminPrefix(adminPrefix); err == nil { - adminPrefix = p - } - out := map[string]any{ - "page": page, - "db": dbv, - "host": host, - "port": port, - "admin": admin, - "admin_prefix": adminPrefix, - "forms": map[string]any{}, - "routes": map[string]any{}, - "ws_routes": map[string]any{}, - "static_dir": nil, - "static_mount": "/static", - } - if s := strOpt(args, "shell_css", ""); s == "" { - s = strOpt(args, "壳样式", "") - if s != "" { - out["shell_css"] = s - } - } else { - out["shell_css"] = s - } - if s := strOpt(args, "layout", ""); s == "" { - s = strOpt(args, "布局", "") - if s != "" { - out["layout"] = s - } - } else { - out["layout"] = s - } - if s := strOpt(args, "asset_version", ""); s == "" { - s = strOpt(args, "资源版本", "") - if s != "" { - out["asset_version"] = s - } - } else { - out["asset_version"] = s - } - return out -} - -// Route registers path → page on app.routes and stamps page._route. -// When admin=true, paths under admin_prefix are reserved (c0 frees /admin when admin=false). -func Route(appBag map[string]any, path string, page any) (map[string]any, error) { - path, err := NormalizeRoutePath(path, appBag) - if err != nil { - return nil, err - } - out := clone(appBag) - pageMap := map[string]any{} - if m, ok := page.(map[string]any); ok { - pageMap = clone(m) - } - pageMap["_route"] = path - routes := map[string]any{} - if r, ok := out["routes"].(map[string]any); ok { - routes = clone(r) - } - routes[path] = pageMap - out["routes"] = routes - return out, nil -} - -// MountForm stores form under app.forms[id]. -func MountForm(appBag map[string]any, id string, form any) (map[string]any, error) { - id = strings.TrimSpace(id) - if id == "" { - return nil, fmt.Errorf("missing form id") - } - if form == nil { - return nil, fmt.Errorf("missing `form`") - } - out := clone(appBag) - forms := map[string]any{} - if f, ok := out["forms"].(map[string]any); ok { - forms = clone(f) - } - forms[id] = form - out["forms"] = forms - return out, nil -} - -// NormalizeStaticMount mirrors Rust http::normalize_static_mount. -func NormalizeStaticMount(raw string) string { - s := strings.TrimSpace(raw) - if s == "" { - return "/static" - } - m := s - if !strings.HasPrefix(m, "/") { - m = "/" + m - } - for len(m) > 1 && strings.HasSuffix(m, "/") { - m = strings.TrimSuffix(m, "/") - } - return m -} - -// Static sets static_dir + static_mount (Rust web_app_static). -func Static(appBag map[string]any, dir, mount string) (map[string]any, error) { - dir = strings.TrimSpace(dir) - if dir == "" { - return nil, fmt.Errorf("static `dir` is empty") - } - if mount == "" { - mount = "/static" - } - mount = NormalizeStaticMount(mount) - if mount == "/_form" || strings.HasPrefix(mount, "/_form/") || - mount == "/_part" || strings.HasPrefix(mount, "/_part/") { - return nil, fmt.Errorf("static mount `%s` is reserved", mount) - } - if boolish(appBag["admin"]) { - prefix := AdminPrefix(appBag) - if pathUnderPrefix(mount, prefix) { - return nil, fmt.Errorf("static mount `%s` is reserved", mount) - } - } - out := clone(appBag) - out["static_dir"] = dir - out["static_mount"] = mount - return out, nil -} - -// Auth wires users + default admin gate (Rust web_app_auth). -// opts may include session_ttl, admin_prefix/后台前缀, login_redirect/登录回跳, -// logout_redirect/登出回跳, login_path/登录路径. -func Auth(appBag map[string]any, users any, opts map[string]any) (map[string]any, error) { - if opts == nil { - opts = map[string]any{} - } - out := clone(appBag) - sessionTTL := uint64(3600) - if v, ok := opts["session_ttl"]; ok { - if n, ok := asUint64(v); ok && n > 0 { - sessionTTL = n - } - } - if p := firstStr(opts, "admin_prefix", "后台前缀"); p != "" { - np, err := NormalizeAdminPrefix(p) - if err != nil { - return nil, err - } - out["admin_prefix"] = np - } - if v := firstStr(opts, "login_redirect", "登录回跳"); v != "" { - out["login_redirect"] = v - } - if v := firstStr(opts, "logout_redirect", "登出回跳"); v != "" { - out["logout_redirect"] = v - } - if v := firstStr(opts, "login_path", "登录路径"); v != "" { - out["login_path"] = v - } - prefix := AdminPrefix(out) - loginPath := strOpt(out, "login_path", "") - if loginPath == "" { - loginPath = prefix + "/login" - } - out["login_path"] = loginPath - authBag, _ := out["auth"].(map[string]any) - if authBag == nil { - authBag = map[string]any{} - } else { - authBag = clone(authBag) - } - authBag["users"] = users - authBag["session_ttl"] = float64(sessionTTL) - if v, ok := first(opts, "register", "注册"); ok { - authBag["register"] = boolish(v) - } - if v := firstStr(opts, "register_path", "注册路径"); v != "" { - authBag["register_path"] = v - out["register_path"] = v - } - if v := firstStr(opts, "default_role", "默认角色"); v != "" { - authBag["default_role"] = v - } - if v := firstStr(opts, "session_url", "会话地址", "redis_url", "Redis"); v != "" { - out["session_url"] = v - authBag["session_url"] = v - } - out["auth"] = authBag - gates := gatesOf(out) - // Auto-gate the built-in admin prefix only when admin=true. Custom desks - // (admin=false) declare their own gates and must not inherit /admin noise. - if boolish(out["admin"]) && !hasAdminGate(gates, prefix) { - gates = append(gates, map[string]any{ - "path": prefix, - "roles": []any{"admin"}, - "match": "prefix", - "on_deny": "redirect", - "exclude": []any{loginPath}, - }) - } - out["gates"] = gates - return out, nil -} - -// OIDC configures OAuth2/OIDC authorization-code login (CFLMY IdP or compatible). -// When enabled, GET/POST on login_path and register_path redirect to the IdP; -// callback at redirect_uri path establishes the local session. IdP is_admin / -// admin_role map to local role "admin". -func OIDC(appBag map[string]any, opts map[string]any) (map[string]any, error) { - if opts == nil { - opts = map[string]any{} - } - cfg := oidc.ParseConfig(opts) - if !cfg.Enabled() { - return nil, fmt.Errorf("oidc: need client_id, client_secret, redirect_uri, and issuer (or authorize_url)") - } - out := clone(appBag) - bag := map[string]any{ - "issuer": cfg.Issuer, - "client_id": cfg.ClientID, - "client_secret": cfg.ClientSecret, - "redirect_uri": cfg.RedirectURI, - "scopes": cfg.ScopesCSV(), - "callback_path": cfg.Callback(), - } - if cfg.RedirectOrigins != "" { - bag["redirect_origins"] = cfg.RedirectOrigins - } - if cfg.AuthorizeURL != "" { - bag["authorize_url"] = cfg.AuthorizeURL - } - if cfg.TokenURL != "" { - bag["token_url"] = cfg.TokenURL - } - if cfg.UserInfoURL != "" { - bag["userinfo_url"] = cfg.UserInfoURL - } - out["oidc"] = bag - authBag, _ := out["auth"].(map[string]any) - if authBag == nil { - authBag = map[string]any{} - } else { - authBag = clone(authBag) - } - authBag["oidc"] = true - out["auth"] = authBag - return out, nil -} - -// Tenant configures multi-tenant resolution on the app bag (path|subdomain|header). -func Tenant(appBag map[string]any, opts map[string]any) (map[string]any, error) { - return tenant.Configure(appBag, opts) -} - -// Gate appends an RBAC gate (Rust web_app_gate). -// opts: roles/角色, permissions/权限, match/匹配, on_deny/拒绝, exclude/排除. -// When permissions is non-empty, the HTTP middleware authorizes by permission codes; -// otherwise it falls back to roles (legacy). -func Gate(appBag map[string]any, path string, opts map[string]any) (map[string]any, error) { - if opts == nil { - opts = map[string]any{} - } - path = strings.TrimSpace(path) - if path == "" { - return nil, fmt.Errorf("missing `path`") - } - rolesRaw := firstStr(opts, "roles", "角色") - permsRaw := firstStr(opts, "permissions", "权限") - if rolesRaw == "" && permsRaw == "" { - rolesRaw = "admin" - } - roles := session.ParseRolesCSV(rolesRaw) - roleAny := make([]any, len(roles)) - for i, r := range roles { - roleAny[i] = r - } - perms := session.ParseRolesCSV(permsRaw) - permAny := make([]any, len(perms)) - for i, p := range perms { - permAny[i] = p - } - matchMode := firstStr(opts, "match", "匹配") - if matchMode == "" { - matchMode = "prefix" - } - onDeny := firstStr(opts, "on_deny", "拒绝") - if onDeny == "" { - onDeny = "forbid" - } - entry := map[string]any{ - "path": path, - "roles": roleAny, - "match": matchMode, - "on_deny": onDeny, - } - if len(permAny) > 0 { - entry["permissions"] = permAny - } - if v, ok := first(opts, "exclude", "排除"); ok && v != nil { - entry["exclude"] = v - } - out := clone(appBag) - gates := gatesOf(out) - gates = append(gates, entry) - out["gates"] = gates - return out, nil -} - -// Rbac enables DB-backed RBAC on the app (ensure schema at listen). -// opts: catalog/目录 (optional seed table); desk/管理台 (bool, default false) — -// when true, listen mounts /_rbac/* API + desk UI; permission gates work either way. -func Rbac(appBag map[string]any, opts map[string]any) (map[string]any, error) { - out := clone(appBag) - authBag, _ := out["auth"].(map[string]any) - if authBag == nil { - authBag = map[string]any{} - } else { - authBag = clone(authBag) - } - authBag["rbac"] = true - authBag["rbac_desk"] = false - if opts != nil { - if v, ok := first(opts, "catalog", "目录"); ok && v != nil { - authBag["permission_catalog"] = v - } - if v, ok := first(opts, "desk", "管理台"); ok { - authBag["rbac_desk"] = boolish(v) - } - } - out["auth"] = authBag - return out, nil -} - -// NormalizeAdminPrefix cleans and validates admin_prefix. -func NormalizeAdminPrefix(raw string) (string, error) { - path, err := cleanMountPath(raw) - if err != nil { - return "", err - } - if path == "/" { - return "", fmt.Errorf("admin_prefix cannot be `/`") - } - if path == "/_form" || strings.HasPrefix(path, "/_form/") || - path == "/_part" || strings.HasPrefix(path, "/_part/") { - return "", fmt.Errorf("admin_prefix `%s` collides with framework paths", path) - } - return path, nil -} - -// AdminPrefix returns the active admin mount from an app bag. -func AdminPrefix(appBag map[string]any) string { - s := strOpt(appBag, "admin_prefix", "/admin") - if p, err := NormalizeAdminPrefix(s); err == nil { - return p - } - return "/admin" -} - -// NormalizeRoutePath applies Rust reserved-path rules for the app bag. -func NormalizeRoutePath(raw string, appBag map[string]any) (string, error) { - path, err := cleanMountPath(raw) - if err != nil { - return "", err - } - if path == "/" { - return "", fmt.Errorf("route path `/` is reserved for the home page") - } - staticMount := NormalizeStaticMount(strOpt(appBag, "static_mount", "/static")) - if isFrameworkReserved(path, staticMount) { - return "", fmt.Errorf("route path `%s` is reserved", path) - } - if boolish(appBag["admin"]) && pathUnderPrefix(path, AdminPrefix(appBag)) { - return "", fmt.Errorf("route path `%s` is reserved", path) - } - return path, nil -} - -func cleanMountPath(raw string) (string, error) { - s := strings.TrimSpace(raw) - if s == "" { - return "", fmt.Errorf("path is empty") - } - if !strings.HasPrefix(s, "/") { - s = "/" + s - } - for len(s) > 1 && strings.HasSuffix(s, "/") { - s = strings.TrimSuffix(s, "/") - } - return s, nil -} - -func pathUnderPrefix(path, prefix string) bool { - return path == prefix || strings.HasPrefix(path, prefix+"/") -} - -func isFrameworkReserved(path, staticMount string) bool { - return path == "/_form" || strings.HasPrefix(path, "/_form/") || - path == "/_part" || strings.HasPrefix(path, "/_part/") || - pathUnderPrefix(path, staticMount) -} - -func gatesOf(appBag map[string]any) []any { - if g, ok := appBag["gates"].([]any); ok { - out := make([]any, len(g)) - copy(out, g) - return out - } - return []any{} -} - -func hasAdminGate(gates []any, prefix string) bool { - want := strings.TrimSuffix(prefix, "/") - for _, g := range gates { - m, ok := g.(map[string]any) - if !ok { - continue - } - p, _ := m["path"].(string) - cleaned := strings.TrimSuffix(strings.TrimSuffix(p, "*"), "/") - if cleaned == want { - return true - } - } - return false -} - -func first(m map[string]any, keys ...string) (any, bool) { - for _, k := range keys { - if v, ok := m[k]; ok && v != nil { - return v, true - } - } - return nil, false -} - -func firstStr(m map[string]any, keys ...string) string { - v, ok := first(m, keys...) - if !ok { - return "" - } - s, _ := v.(string) - return strings.TrimSpace(s) -} - -func asUint64(v any) (uint64, bool) { - switch t := v.(type) { - case uint64: - return t, true - case int: - if t < 0 { - return 0, false - } - return uint64(t), true - case int64: - if t < 0 { - return 0, false - } - return uint64(t), true - case float64: - if t < 0 { - return 0, false - } - return uint64(t), true - default: - return 0, false - } -} - -func clone(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} - -func strOpt(args map[string]any, key, def string) string { - v, ok := args[key] - if !ok || v == nil { - return def - } - if s, ok := v.(string); ok { - return s - } - return def -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - return t == "true" || t == "True" || t == "1" || t == "yes" - case float64: - return t != 0 - } - return false -} - -// StorageURL extracts a storage url string or handle map. -func StorageURL(v any) (string, error) { - if v == nil { - return "", fmt.Errorf("missing storage") - } - if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { - return strings.TrimSpace(s), nil - } - if m, ok := v.(map[string]any); ok { - if s, ok := m["url"].(string); ok && strings.TrimSpace(s) != "" { - return strings.TrimSpace(s), nil - } - } - return "", fmt.Errorf("storage must be a url string or storage handle") -} - -// Upload registers an upload route on the app bag (offline stub; live HTTP in listen). -func Upload(appBag map[string]any, path, field, storageURL, prefix string, maxBytes uint64, types any) (map[string]any, error) { - out := clone(appBag) - if path == "" { - path = "/_upload" - } - path, err := NormalizeRoutePath(path, out) - if err != nil { - return nil, err - } - if field == "" { - field = "file" - } - if prefix == "" { - prefix = "uploads/" - } - routes := map[string]any{} - if r, ok := out["upload_routes"].(map[string]any); ok { - routes = clone(r) - } - entry := map[string]any{ - "field": field, - "storage_url": storageURL, - "prefix": prefix, - "max_bytes": float64(maxBytes), - } - if types != nil { - entry["types"] = types - } - routes[path] = entry - out["upload_routes"] = routes - return out, nil -} - -// Download registers a media download route with {key} capture. -func Download(appBag map[string]any, path, storageURL, disposition string) (map[string]any, error) { - path = strings.TrimSpace(path) - if path == "" { - path = "/_media/{*key}" - } - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - for len(path) > 1 && strings.HasSuffix(path, "/") { - path = strings.TrimSuffix(path, "/") - } - if !strings.Contains(path, "{") { - return nil, fmt.Errorf("download path must include a `{key}` or `{*key}` capture") - } - if disposition == "" { - disposition = "attachment" - } - if strings.TrimSpace(storageURL) == "" { - return nil, fmt.Errorf("missing storage") - } - out := clone(appBag) - routes := map[string]any{} - if r, ok := out["download_routes"].(map[string]any); ok { - routes = clone(r) - } - routes[path] = map[string]any{ - "storage_url": storageURL, - "disposition": disposition, - } - out["download_routes"] = routes - return out, nil -} - -// Gallery registers a gallery page route (offline bag; live HTML in listen). -func Gallery(appBag map[string]any, path, storageURL, prefix, title, downloadBase string) (map[string]any, error) { - out := clone(appBag) - if path == "" { - path = "/gallery" - } - var err error - path, err = NormalizeRoutePath(path, out) - if err != nil { - return nil, err - } - if prefix == "" { - prefix = "uploads/" - } - if title == "" { - title = "Gallery" - } - if downloadBase == "" { - downloadBase = "/_media" - } - storageURL, err = StorageURL(storageURL) - if err != nil { - return nil, err - } - routes := map[string]any{} - if r, ok := out["gallery_routes"].(map[string]any); ok { - routes = clone(r) - } - routes[path] = map[string]any{ - "storage": storageURL, - "prefix": prefix, - "title": title, - "download_base": downloadBase, - } - out["gallery_routes"] = routes - return out, nil -} - -// Redirect registers a redirect from → to on app.redirects. -func Redirect(appBag map[string]any, from, to string, permanent bool) (map[string]any, error) { - out := clone(appBag) - from, err := NormalizeRoutePath(from, out) - if err != nil { - return nil, err - } - redirects := map[string]any{} - if r, ok := out["redirects"].(map[string]any); ok { - redirects = clone(r) - } - redirects[from] = map[string]any{ - "to": to, - "permanent": permanent, - } - out["redirects"] = redirects - return out, nil -} - -// ErrorPage stores a custom page for HTTP 404 or 500. -func ErrorPage(appBag map[string]any, status uint16, page any) (map[string]any, error) { - if page == nil { - return nil, fmt.Errorf("missing `page`") - } - out := clone(appBag) - key := "page_404" - if status == 500 { - key = "page_500" - } - out[key] = page - return out, nil -} - -// Sitemap registers a sitemap route bag on app.sitemap_routes. -func Sitemap(appBag map[string]any, path, base string, table, loc string, limit int64, items any) (map[string]any, error) { - out := clone(appBag) - if path == "" { - path = "/sitemap.xml" - } - path, err := NormalizeRoutePath(path, out) - if err != nil { - return nil, err - } - if loc == "" { - loc = "path" - } - if items == nil { - items = []any{} - } - routes := map[string]any{} - if r, ok := out["sitemap_routes"].(map[string]any); ok { - routes = clone(r) - } - entry := map[string]any{ - "base": base, - "loc": loc, - "limit": float64(limit), - "items": items, - } - if table != "" { - entry["table"] = table - } - routes[path] = entry - out["sitemap_routes"] = routes - return out, nil -} - -// Robots sets app.robots_body from body or a default Allow-all robots.txt. -func Robots(appBag map[string]any, body, sitemapURL string) (map[string]any, error) { - out := clone(appBag) - text := strings.TrimSpace(body) - if text == "" { - text = defaultRobotsBody(sitemapURL) - } - out["robots_body"] = text - return out, nil -} - -func defaultRobotsBody(sitemapURL string) string { - out := "User-agent: *\nAllow: /\n" - if strings.TrimSpace(sitemapURL) != "" { - out += "Sitemap: " + strings.TrimSpace(sitemapURL) + "\n" - } - return out -} - -// RouteRSS registers an RSS feed route on app.rss_routes. -func RouteRSS(appBag map[string]any, path, table, order, title, link, description string, limit int64) (map[string]any, error) { - out := clone(appBag) - path, err := NormalizeRoutePath(path, out) - if err != nil { - return nil, err - } - if order == "" { - order = "-created_at" - } - if title == "" { - title = "Feed" - } - if link == "" { - link = "/" - } - routes := map[string]any{} - if r, ok := out["rss_routes"].(map[string]any); ok { - routes = clone(r) - } - routes[path] = map[string]any{ - "table": table, - "limit": float64(limit), - "order": order, - "title": title, - "link": link, - "description": description, - } - out["rss_routes"] = routes - return out, nil -} - -// Icons normalizes icons table → app.icons + app.site_head. -func Icons(appBag map[string]any, table any) (map[string]any, error) { - out := clone(appBag) - icons, siteHead, _ := assets.NormalizeIcons(table) - out["icons"] = icons - out["site_head"] = assets.HeadLinksToJSON(siteHead) - return out, nil -} diff --git a/plugins/web/internal/app/app_test.go b/plugins/web/internal/app/app_test.go deleted file mode 100755 index e40cb74..0000000 --- a/plugins/web/internal/app/app_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package app_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" -) - -func TestNormalizeStaticMount(t *testing.T) { - cases := []struct { - in, want string - }{ - {"", "/static"}, - {" ", "/static"}, - {"static", "/static"}, - {"/static/", "/static"}, - {"/assets", "/assets"}, - {"assets/", "/assets"}, - } - for _, c := range cases { - if got := app.NormalizeStaticMount(c.in); got != c.want { - t.Fatalf("NormalizeStaticMount(%q)=%q want %q", c.in, got, c.want) - } - } -} - -func TestStaticSetsDirAndMount(t *testing.T) { - a := app.New(map[string]any{"page": map[string]any{"title": "Home"}}) - out, err := app.Static(a, "web-fixtures/public", "/static") - if err != nil { - t.Fatal(err) - } - if out["static_dir"] != "web-fixtures/public" { - t.Fatalf("static_dir=%v", out["static_dir"]) - } - if out["static_mount"] != "/static" { - t.Fatalf("static_mount=%v", out["static_mount"]) - } - out2, err := app.Static(out, "assets", "/assets/") - if err != nil { - t.Fatal(err) - } - if out2["static_mount"] != "/assets" { - t.Fatalf("custom mount=%v", out2["static_mount"]) - } -} - -func TestStaticRejectsReserved(t *testing.T) { - a := app.New(nil) - for _, mount := range []string{"/_form", "/_form/x", "/_part", "/_part/nav"} { - _, err := app.Static(a, "pub", mount) - if err == nil || !strings.Contains(err.Error(), "reserved") { - t.Fatalf("mount %q: want reserved error, got %v", mount, err) - } - } - admin := app.New(map[string]any{"admin": true, "admin_prefix": "/admin"}) - _, err := app.Static(admin, "pub", "/admin") - if err == nil || !strings.Contains(err.Error(), "reserved") { - t.Fatalf("admin mount: want reserved, got %v", err) - } -} - -func TestRouteFreesAdminWhenDisabled(t *testing.T) { - a := app.New(map[string]any{"admin": false}) - page := map[string]any{"title": "news"} - out, err := app.Route(a, "/admin/news", page) - if err != nil { - t.Fatal(err) - } - routes := out["routes"].(map[string]any) - if routes["/admin/news"] == nil { - t.Fatal("missing route") - } -} - -func TestRouteCustomPrefixFreesAdmin(t *testing.T) { - a := app.New(map[string]any{"admin": true, "admin_prefix": "/desk"}) - out, err := app.Route(a, "/admin/news", map[string]any{"title": "news"}) - if err != nil { - t.Fatal(err) - } - if out["routes"].(map[string]any)["/admin/news"] == nil { - t.Fatal("missing") - } - _, err = app.Route(a, "/desk/x", map[string]any{"title": "x"}) - if err == nil || !strings.Contains(err.Error(), "reserved") { - t.Fatalf("want reserved under /desk, got %v", err) - } -} - -func TestAuthDefaultGate(t *testing.T) { - a := app.New(map[string]any{"admin": true}) - users := map[string]any{ - "用户名": []any{"admin"}, - "密码": []any{"secret"}, - "角色": []any{"admin"}, - } - out, err := app.Auth(a, users, nil) - if err != nil { - t.Fatal(err) - } - if out["login_path"] != "/admin/login" { - t.Fatalf("login_path=%v", out["login_path"]) - } - gates := out["gates"].([]any) - g0 := gates[0].(map[string]any) - if g0["path"] != "/admin" || g0["match"] != "prefix" || g0["on_deny"] != "redirect" { - t.Fatalf("gate=%v", g0) - } - ex := g0["exclude"].([]any) - if len(ex) != 1 || ex[0] != "/admin/login" { - t.Fatalf("exclude=%v", ex) - } -} - -func TestAuthNoAutoGateWhenAdminOff(t *testing.T) { - a := app.New(map[string]any{"admin": false}) - out, err := app.Auth(a, []any{}, map[string]any{"login_path": "/login"}) - if err != nil { - t.Fatal(err) - } - if gates, ok := out["gates"].([]any); ok && len(gates) != 0 { - t.Fatalf("expected no auto gate when admin=false, got %v", gates) - } -} - -func TestRbacDeskOptIn(t *testing.T) { - a := app.New(map[string]any{"admin": false}) - out, err := app.Rbac(a, nil) - if err != nil { - t.Fatal(err) - } - authBag := out["auth"].(map[string]any) - if !boolishTest(authBag["rbac"]) || boolishTest(authBag["rbac_desk"]) { - t.Fatalf("default rbac_desk should be false: %v", authBag) - } - out2, err := app.Rbac(a, map[string]any{"管理台": true}) - if err != nil { - t.Fatal(err) - } - if !boolishTest(out2["auth"].(map[string]any)["rbac_desk"]) { - t.Fatal("expected rbac_desk true") - } -} - -func boolishTest(v any) bool { - switch x := v.(type) { - case bool: - return x - case string: - s := strings.ToLower(strings.TrimSpace(x)) - return s == "1" || s == "true" || s == "yes" || s == "真" - case float64: - return x != 0 - default: - return false - } -} - -func TestAuthCustomPrefix(t *testing.T) { - a := app.New(map[string]any{"admin": true}) - out, err := app.Auth(a, []any{}, map[string]any{ - "admin_prefix": "/desk", - "login_redirect": "/desk", - "logout_redirect": "/desk/login", - }) - if err != nil { - t.Fatal(err) - } - if out["admin_prefix"] != "/desk" || out["login_redirect"] != "/desk" { - t.Fatalf("%v", out) - } - g0 := out["gates"].([]any)[0].(map[string]any) - if g0["path"] != "/desk" { - t.Fatalf("gate path=%v", g0["path"]) - } -} - -func TestGateCustomFields(t *testing.T) { - a := app.New(map[string]any{"admin": false}) - out, err := app.Gate(a, "/desk", map[string]any{ - "roles": "admin", - "match": "prefix", - "on_deny": "redirect", - "exclude": "/desk/login", - }) - if err != nil { - t.Fatal(err) - } - g0 := out["gates"].([]any)[0].(map[string]any) - if g0["path"] != "/desk" || g0["match"] != "prefix" || g0["on_deny"] != "redirect" { - t.Fatalf("%v", g0) - } - if g0["exclude"] != "/desk/login" { - t.Fatalf("exclude=%v", g0["exclude"]) - } - out2, err := app.Gate(a, "/write*", map[string]any{"roles": "admin,author"}) - if err != nil { - t.Fatal(err) - } - g1 := out2["gates"].([]any)[0].(map[string]any) - roles := g1["roles"].([]any) - if g1["path"] != "/write*" || len(roles) != 2 { - t.Fatalf("%v", g1) - } -} - -func TestRedirectStoresMap(t *testing.T) { - a := app.New(map[string]any{"page": map[string]any{"title": "Home"}}) - out, err := app.Redirect(a, "/old", "/new", true) - if err != nil { - t.Fatal(err) - } - rd, ok := out["redirects"].(map[string]any) - if !ok { - t.Fatalf("redirects=%v", out["redirects"]) - } - entry, ok := rd["/old"].(map[string]any) - if !ok || entry["to"] != "/new" || entry["permanent"] != true { - t.Fatalf("entry=%v", entry) - } -} - -func TestErrorPage404(t *testing.T) { - a := app.New(nil) - p := map[string]any{"title": "Missing"} - out, err := app.ErrorPage(a, 404, p) - if err != nil { - t.Fatal(err) - } - got, ok := out["page_404"].(map[string]any) - if !ok || got["title"] != "Missing" { - t.Fatalf("page_404=%v", out["page_404"]) - } -} - -func TestRobotsDefaultBody(t *testing.T) { - a := app.New(nil) - out, err := app.Robots(a, "", "https://example.com/sitemap.xml") - if err != nil { - t.Fatal(err) - } - rb, ok := out["robots_body"].(string) - if !ok || !strings.Contains(rb, "Sitemap: https://example.com/sitemap.xml") { - t.Fatalf("robots_body=%v", out["robots_body"]) - } -} - -func TestSitemapRouteBag(t *testing.T) { - a := app.New(nil) - items := []any{map[string]any{"loc": "/"}} - out, err := app.Sitemap(a, "/sitemap.xml", "https://example.com", "", "path", 1000, items) - if err != nil { - t.Fatal(err) - } - routes, ok := out["sitemap_routes"].(map[string]any) - if !ok { - t.Fatalf("sitemap_routes=%v", out["sitemap_routes"]) - } - entry, ok := routes["/sitemap.xml"].(map[string]any) - if !ok || entry["base"] != "https://example.com" { - t.Fatalf("entry=%v", entry) - } -} diff --git a/plugins/web/internal/artifact/artifact.go b/plugins/web/internal/artifact/artifact.go deleted file mode 100755 index e4f2c46..0000000 --- a/plugins/web/internal/artifact/artifact.go +++ /dev/null @@ -1,711 +0,0 @@ -// Package artifact implements Document/Endpoint View render, serve scan, and inspect (ADR 0007). -package artifact - -import ( - "encoding/json" - "fmt" - "html" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/render" -) - -// MetaType returns canonical kind: web | endpoint | "" from flat frontmatter map. -func MetaType(meta map[string]string) string { - if v := strings.TrimSpace(meta["type"]); v != "" { - return normalizeType(v) - } - if v := strings.TrimSpace(meta["类型"]); v != "" { - return normalizeType(v) - } - return "" -} - -func normalizeType(v string) string { - switch v { - case "web", "网页": - return "web" - case "endpoint", "端点": - return "endpoint" - default: - return v - } -} - -// ParseFrontmatter reads flat key: value pairs from a .mq.md file head. -func ParseFrontmatter(src string) (meta map[string]string, body string) { - meta = map[string]string{} - s := strings.TrimPrefix(src, "\ufeff") - if !strings.HasPrefix(s, "---\n") && !strings.HasPrefix(s, "---\r\n") { - return meta, src - } - rest := s[4:] - if strings.HasPrefix(rest, "\r\n") { - rest = rest[2:] - } else if strings.HasPrefix(rest, "\n") { - rest = rest[1:] - } - end := strings.Index(rest, "\n---\n") - if end < 0 { - end = strings.Index(rest, "\r\n---\r\n") - } - if end < 0 { - end = strings.Index(rest, "\n---\r\n") - } - if end < 0 { - return meta, src - } - fm := rest[:end] - body = rest[end:] - if i := strings.Index(body, "---"); i >= 0 { - body = body[i+3:] - body = strings.TrimPrefix(body, "\r") - body = strings.TrimPrefix(body, "\n") - // Drop blank line(s) between closing --- and first content. - for strings.HasPrefix(body, "\n") || strings.HasPrefix(body, "\r\n") { - body = strings.TrimPrefix(body, "\r\n") - body = strings.TrimPrefix(body, "\n") - } - } - for _, line := range strings.Split(fm, "\n") { - line = strings.TrimSpace(strings.TrimSuffix(line, "\r")) - if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "import ") || strings.HasPrefix(line, "导入 ") { - continue - } - k, v, ok := strings.Cut(line, ":") - if !ok { - continue - } - k = strings.TrimSpace(k) - v = strings.TrimSpace(v) - if len(v) >= 2 { - if (v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'') { - v = v[1 : len(v)-1] - } - } - if k != "" { - meta[k] = v - } - } - return meta, body -} - -// RenderNodes renders the existing five-column View schema recursively. Container -// value cells hold more View rows; markdown leaves hold ordinary Markdown text. -func RenderNodes(nodes any) (string, error) { - return RenderNodesWithResources(nodes, nil) -} - -// ResourceRenderer resolves a typed Resource at the request boundary. -// Ordinary View construction remains pure; a nil renderer never starts IO. -type ResourceRenderer func(map[string]any) (string, error) - -func RenderNodesWithResources(nodes any, resources ResourceRenderer) (string, error) { - var b strings.Builder - b.WriteString(`
`) - if err := renderNodes(&b, nodes, 0, resources); err != nil { - return "", err - } - b.WriteString(`
`) - return b.String(), nil -} - -// Fixed runtime geometry, shared by offline previews and served Documents. -// Authors choose row/column instead of embedding CSS or HTML in content cells. -const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0;overflow-wrap:anywhere}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}.mq-view input,.mq-view textarea,.mq-view select{max-width:100%;font:inherit}.mq-view textarea{width:100%}` - -// Preserve typed value cells when normalizing column tables. General AsRows -// treats @ cells as text, which would stringify nested component tables. -func viewRows(nodes any) ([]any, error) { - switch v := nodes.(type) { - case nil: - return nil, nil - case []any: - return v, nil - case map[string]any: - if _, ok := v["type"].(string); ok { - return []any{v}, nil - } - if _, ok := v["类型"].(string); ok { - return []any{v}, nil - } - n := -1 - for _, cell := range v { - col, ok := cell.([]any) - if !ok { - return nil, fmt.Errorf("View: expected a row or column table") - } - if n < 0 { - n = len(col) - } else if n != len(col) { - return nil, fmt.Errorf("View: column lengths differ") - } - } - rows := []any{} - for i := 0; i < n; i++ { - row := map[string]any{} - for key, cell := range v { - row[key] = cell.([]any)[i] - } - rows = append(rows, row) - } - return rows, nil - default: - return nil, fmt.Errorf("View: expected rows, got %T", nodes) - } -} - -func containerTag(kind string) (string, string) { - switch kind { - case "row", "横排": - return "div", " mq-row" - case "column", "纵排": - return "div", " mq-column" - case "nav", "导航": - return "nav", "" - case "header", "页头": - return "header", "" - case "footer", "页脚": - return "footer", "" - case "section", "区域": - return "section", "" - case "aside", "侧栏": - return "aside", "" - case "form", "表单": - return "form", "" - case "list", "列表": - return "ul", "" - case "item", "列表项": - return "li", "" - case "select", "选择": - return "select", "" - } - return "", "" -} - -// FindSlot selects one declared View region without resolving any Resources. -// Container traversal is identical to rendering and never descends into a -// Resource's private map as if it were another View table. -func FindSlot(nodes any, slot string) (any, bool, error) { - var selected []any - var walk func(any, int) error - walk = func(nodes any, depth int) error { - if depth > 64 { - return fmt.Errorf("View: nesting exceeds 64 levels") - } - rows, err := viewRows(nodes) - if err != nil { - return err - } - for _, value := range rows { - row, ok := value.(map[string]any) - if !ok { - return fmt.Errorf("View slot: expected a row map") - } - if first(row, "slot", "槽") == slot { - selected = append(selected, row) - } - kind := strings.ToLower(first(row, "type", "类型")) - if tag, _ := containerTag(kind); tag != "" { - children := row["value"] - if children == nil { - children = row["值"] - } - if children == nil { - return fmt.Errorf("View %s: missing child rows", kind) - } - if err := walk(children, depth+1); err != nil { - return err - } - } - } - return nil - } - if err := walk(nodes, 0); err != nil { - return nil, false, err - } - if len(selected) > 1 { - return nil, false, fmt.Errorf("View slot %q is ambiguous", slot) - } - if len(selected) == 0 { - return nil, false, nil - } - return selected, true, nil -} - -func renderNodes(b *strings.Builder, nodes any, depth int, resources ResourceRenderer) error { - if depth > 64 { - return fmt.Errorf("View: nesting exceeds 64 levels") - } - rows, err := viewRows(nodes) - if err != nil { - return err - } - for i, item := range rows { - row, ok := item.(map[string]any) - if !ok { - return fmt.Errorf("View row %d: expected a map", i+1) - } - ty := strings.ToLower(first(row, "type", "类型")) - slot := first(row, "slot", "槽") - val := first(row, "value", "值") - attrs := first(row, "attrs", "属性") - attributes, err := renderAttributes(row) - if err != nil { - return fmt.Errorf("View row %d: %w", i+1, err) - } - style := first(row, "style", "样式") - class := "mq-node" - if style != "" { - class += " " + html.EscapeString(style) - } - if slot != "" { - class += " slot-" + html.EscapeString(slot) - } - tag, geometry := containerTag(ty) - class += geometry - if tag != "" { - children := row["value"] - if children == nil { - children = row["值"] - } - if children == nil { - return fmt.Errorf("View row %d (%s): missing child rows in value", i+1, ty) - } - b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>`) - if err := renderNodes(b, children, depth+1, resources); err != nil { - return fmt.Errorf("View %s/%s: %w", ty, slot, err) - } - b.WriteString(``) - continue - } - switch ty { - case "resource", "资源": - value := row["value"] - if value == nil { - value = row["值"] - } - resource, ok := value.(map[string]any) - if !ok || first(resource, "_type") == "" { - return fmt.Errorf("View row %d: resource value must be a typed Resource", i+1) - } - if first(resource, "_type") == "document_head" { - if _, err := ParseDocumentHead(resource); err != nil { - return err - } - continue - } - if resources == nil { - return fmt.Errorf("View row %d: resource requires an explicit request renderer", i+1) - } - fragment, err := resources(resource) - if err != nil { - return fmt.Errorf("View resource %s: %w", slot, err) - } - b.WriteString(`
` + fragment + `
`) - case "markdown", "正文": - b.WriteString(`
` + render.MarkdownToHTML(val) + `
`) - case "title", "标题": - b.WriteString(`

` + inline(val) + `

`) - case "link", "链接": - if !hasAttributeMap(row) { - if attrs == "" { - attrs = "#" - } - attributes = ` href="` + html.EscapeString(attrs) + `"` - } - b.WriteString(`
` + inline(val) + ``) - case "input", "输入": - b.WriteString(``) - case "button", "按钮", "textarea", "多行输入", "label", "标签", "pre", "预格式", "option", "选项": - tags := map[string]string{"button": "button", "按钮": "button", "textarea": "textarea", "多行输入": "textarea", "label": "label", "标签": "label", "pre": "pre", "预格式": "pre", "option": "option", "选项": "option"} - tag := tags[ty] - b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>` + html.EscapeString(val) + ``) - case "script", "脚本", "stylesheet", "样式表": - url := strings.ToLower(strings.TrimSpace(val)) - if url == "" || strings.ContainsAny(url, "\r\n\t") || strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") { - return fmt.Errorf("View row %d: resource requires a nonempty non-script URL", i+1) - } - if attrs, ok := attributeValue(row).(map[string]any); ok { - for _, reserved := range []string{"href", "src", "rel"} { - if _, exists := attrs[reserved]; exists { - return fmt.Errorf("View row %d: resource URL and relation belong to its kind/value, not attrs.%s", i+1, reserved) - } - } - } - if ty == "script" || ty == "脚本" { - b.WriteString(``) - } else { - b.WriteString(``) - } - case "html", "原文": - b.WriteString(`
` + val + `
`) - default: - value := row["value"] - if value == nil { - value = row["值"] - } - switch value.(type) { - case []any, map[string]any: - return fmt.Errorf("View row %d: unknown structural type %q", i+1, ty) - } - b.WriteString(`

` + inline(val) + `

`) - } - } - return nil -} - -// Attribute records keep controls in the same five-column View schema. -// Legacy link rows may still carry a plain href string. Names and scalar values -// are checked before emission; handlers and inline style remain explicit escapes. -func attributeValue(row map[string]any) any { - if value, ok := row["attrs"]; ok && value != nil { - return value - } - return row["属性"] -} - -func hasAttributeMap(row map[string]any) bool { - _, ok := attributeValue(row).(map[string]any) - return ok -} - -func renderAttributes(row map[string]any) (string, error) { - value := attributeValue(row) - if value == nil || value == "" { - return "", nil - } - attrs, ok := value.(map[string]any) - if !ok { - if _, legacy := value.(string); legacy { - return "", nil - } - return "", fmt.Errorf("attrs must be a scalar attribute record or legacy link URL") - } - allowed := map[string]bool{ - "id": true, "title": true, "role": true, "name": true, "type": true, - "href": true, "src": true, "action": true, "method": true, "enctype": true, - "placeholder": true, "for": true, "rows": true, "cols": true, "size": true, - "min": true, "max": true, "step": true, "minlength": true, "maxlength": true, - "pattern": true, "autocomplete": true, "target": true, "rel": true, - "tabindex": true, "download": true, "accept": true, "alt": true, - "integrity": true, "crossorigin": true, "media": true, "referrerpolicy": true, - } - booleans := map[string]bool{"hidden": true, "disabled": true, "required": true, "readonly": true, "checked": true, "selected": true, "multiple": true, "autofocus": true, "async": true, "defer": true, "nomodule": true} - keys := make([]string, 0, len(attrs)) - for name := range attrs { - keys = append(keys, name) - } - sort.Strings(keys) - var out strings.Builder - for _, name := range keys { - if !(allowed[name] || booleans[name] || validCustomAttribute(name)) { - return "", fmt.Errorf("unsupported attribute %q; use attrs data/aria keys for client state", name) - } - v := attrs[name] - if v == nil { - continue - } - if booleans[name] { - flag, ok := v.(bool) - if !ok { - return "", fmt.Errorf("attribute %s requires a boolean", name) - } - if flag { - out.WriteString(" " + name) - } - continue - } - switch v.(type) { - case string, bool, float64, int, int64, json.Number: - default: - return "", fmt.Errorf("attribute %s requires a scalar value", name) - } - text := fmt.Sprint(v) - if name == "href" || name == "src" || name == "action" { - url := strings.ToLower(strings.TrimSpace(text)) - if strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") { - return "", fmt.Errorf("attribute %s cannot execute a script URL", name) - } - } - out.WriteString(" " + name + `="` + html.EscapeString(text) + `"`) - } - return out.String(), nil -} - -func validCustomAttribute(name string) bool { - if !(strings.HasPrefix(name, "data-") || strings.HasPrefix(name, "aria-")) { - return false - } - if strings.HasSuffix(name, "-") { - return false - } - for _, char := range name { - if !(char >= 'a' && char <= 'z' || char >= '0' && char <= '9' || char == '-' || char == '_') { - return false - } - } - return true -} - -// RenderFile explicitly opts a Document into startup-time component assembly. -// Documents without view: main retain their existing Markdown/data-source path. -// AssembleView runs the existing startup entry once and retains typed rows. -// Request resources are deliberately not resolved during assembly. -func AssembleView(f ArtifactFile, run func(string, map[string]any) (any, error)) (any, bool, error) { - view := metaString(f.Meta, "view", "视图") - if view == "" { - return nil, false, nil - } - if view != "main" { - return nil, false, fmt.Errorf("%s: view/视图 must be main", f.Rel) - } - if metaString(f.Meta, "data_source", "数据源") != "" { - return nil, false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel) - } - nodes, err := run(f.Path, nil) - if err != nil { - return nil, false, fmt.Errorf("%s: view main: %w", f.Rel, err) - } - if nodes == nil { - return nil, false, fmt.Errorf("%s: view main must return View rows", f.Rel) - } - return nodes, true, nil -} - -func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) { - nodes, structured, err := AssembleView(f, run) - if err != nil { - return "", false, err - } - if !structured { - return MarkdownHTML(f.Body), false, nil - } - html, err := RenderNodes(nodes) - if err != nil { - return "", false, fmt.Errorf("%s: %w", f.Rel, err) - } - return html, true, nil -} - -func inline(s string) string { - return html.EscapeString(s) -} - -func first(row map[string]any, keys ...string) string { - for _, k := range keys { - if v, ok := row[k]; ok && v != nil { - return fmt.Sprint(v) - } - } - return "" -} - -// RenderDocument builds a minimal HTML page from title + markdown body. -func RenderDocument(title, body string) string { - return RenderHTMLPage(title, render.MarkdownToHTML(body)) -} - -// RenderHTMLPage wraps an HTML fragment in a minimal document shell. -func RenderHTMLPage(title, innerHTML string) string { - t := html.EscapeString(title) - if t == "" { - t = "Marqdo" - } - return renderHTMLPageWithHead(""+t+"", innerHTML) -} - -func renderHTMLPageWithHead(head, innerHTML string) string { - return "" + head + - "
" + innerHTML + "
" -} - -// MarkdownHTML exposes render helper. -func MarkdownHTML(md string) string { - return render.MarkdownToHTML(md) -} - -// ScanRoot finds Artifact .mq.md files under root. -func ScanRoot(root string) ([]ArtifactFile, error) { - var out []ArtifactFile - err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { - if err != nil { - return err - } - name := d.Name() - if d.IsDir() { - if name == "data" || name == ".git" || name == "node_modules" || strings.HasPrefix(name, ".") { - return filepath.SkipDir - } - return nil - } - if !strings.HasSuffix(name, ".mq.md") { - return nil - } - raw, err := os.ReadFile(path) - if err != nil { - return err - } - meta, body := ParseFrontmatter(string(raw)) - kind := MetaType(meta) - if kind != "web" && kind != "endpoint" { - return nil - } - rel, _ := filepath.Rel(root, path) - af := ArtifactFile{Path: path, Rel: rel, Kind: kind, Meta: meta, Body: body} - if kind == "web" { - af.Route = metaString(meta, "route", "路由") - if af.Route == "" { - af.Route = routeFromRel(rel) - } - af.Method = metaString(meta, "method", "方法") - if af.Method == "" { - af.Method = "GET" - } - } else { - af.Route = metaString(meta, "path", "路径") - af.Method = metaString(meta, "method", "方法") - if af.Method == "" { - af.Method = "GET" - } - if af.Route == "" { - return fmt.Errorf("endpoint %s: missing path/路径", rel) - } - } - out = append(out, af) - return nil - }) - return out, err -} - -// ArtifactFile is one discovered Document or Endpoint. -type ArtifactFile struct { - Path string - Rel string - Kind string - Route string - Method string - Meta map[string]string - Body string -} - -func metaString(meta map[string]string, keys ...string) string { - for _, k := range keys { - if v := strings.TrimSpace(meta[k]); v != "" { - return v - } - } - return "" -} - -func routeFromRel(rel string) string { - rel = filepath.ToSlash(rel) - if rel == "index.mq.md" { - return "/" - } - rel = strings.TrimSuffix(rel, ".mq.md") - rel = strings.TrimSuffix(rel, "/index") - if !strings.HasPrefix(rel, "/") { - rel = "/" + rel - } - return rel -} - -// SystemRoutes lists runtime-owned routes for inspect. -func SystemRoutes() []map[string]any { - return []map[string]any{ - {"method": "GET", "path": "/_part/*", "kind": "system"}, - {"method": "GET|POST", "path": "/_form/*", "kind": "system"}, - {"method": "POST", "path": "/_md", "kind": "system"}, - {"method": "POST", "path": "/_runtime/tasks", "kind": "system"}, - {"method": "GET", "path": "/_runtime/tasks/{id}", "kind": "system"}, - {"method": "POST", "path": "/_runtime/tasks/{id}/cancel", "kind": "system"}, - {"method": "GET", "path": "/_runtime/tasks/{id}/events", "kind": "system"}, - } -} - -// InspectBag reads declarations only. A prepared app's actual handler inventory -// is generated by httpx.InspectApp through the same registrar as NewHandler. -func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any { - entries := map[string]map[string]any{} - add := func(row map[string]any) { - path := first(row, "path") - method := first(row, "method") - if method == "" { - method = "GET" - } - if path == "" { - return - } - key := method + " " + path - if _, exists := entries[key]; !exists { - entries[key] = row - } - } - for _, file := range declared { - add(map[string]any{"method": file.Method, "path": file.Route, "kind": file.Kind, "file": file.Rel}) - } - if app != nil { - switch rows := app["artifact_declared"].(type) { - case []map[string]any: - for _, row := range rows { - add(row) - } - case []any: - for _, value := range rows { - if row, ok := value.(map[string]any); ok { - add(row) - } - } - } - if app["page"] != nil { - add(map[string]any{"method": "GET", "path": "/", "kind": "document"}) - } - if routes, ok := app["routes"].(map[string]any); ok { - for path := range routes { - add(map[string]any{"method": "GET", "path": path, "kind": "document"}) - } - } - for _, group := range []string{"artifact_routes", "invoke_routes"} { - if routes, ok := app[group].(map[string]any); ok { - for key, value := range routes { - spec, _ := value.(map[string]any) - method, path := first(spec, "method"), first(spec, "path") - if parts := strings.SplitN(key, " ", 2); len(parts) == 2 { - if method == "" { - method = parts[0] - } - if path == "" { - path = parts[1] - } - } else if path == "" { - path = key - } - if method == "" { - method = "GET" - } - row := map[string]any{"method": method, "path": path, "kind": "endpoint"} - for _, name := range []string{"file", "class", "fn"} { - if value := first(spec, name); value != "" { - row[name] = value - } - } - add(row) - } - } - } - } - keys := make([]string, 0, len(entries)) - for key := range entries { - keys = append(keys, key) - } - sort.Strings(keys) - rows := make([]map[string]any, 0, len(keys)) - for _, key := range keys { - rows = append(rows, entries[key]) - } - return map[string]any{"_type": "web_inspection", "scope": "metadata", "declared": rows, "system": SystemRoutes()} -} diff --git a/plugins/web/internal/artifact/artifact_test.go b/plugins/web/internal/artifact/artifact_test.go deleted file mode 100755 index 51d3967..0000000 --- a/plugins/web/internal/artifact/artifact_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package artifact - -import ( - "strings" - "testing" -) - -func TestMetaType(t *testing.T) { - if MetaType(map[string]string{"type": "web"}) != "web" { - t.Fatal("en web") - } - if MetaType(map[string]string{"类型": "网页"}) != "web" { - t.Fatal("zh web") - } - if MetaType(map[string]string{"type": "endpoint"}) != "endpoint" { - t.Fatal("endpoint") - } -} - -func TestParseFrontmatter(t *testing.T) { - src := "---\ntype: web\nroute: /x\n---\n\n# Hi\n" - meta, body := ParseFrontmatter(src) - if meta["type"] != "web" || meta["route"] != "/x" { - t.Fatalf("meta=%v", meta) - } - if body == "" || body[0] != '#' { - t.Fatalf("body=%q", body) - } -} - -func TestRenderNodes(t *testing.T) { - nodes := map[string]any{ - "type": []any{"title", "text"}, - "slot": []any{"title", "lede"}, - "value": []any{"Marqdo", "Hello"}, - "attrs": []any{"", ""}, - "style": []any{"title", "lede"}, - } - html, err := RenderNodes(nodes) - if err != nil { - t.Fatal(err) - } - if !contains(html, "Marqdo") || !contains(html, "mq-view") { - t.Fatalf("html=%s", html) - } -} - -func contains(s, sub string) bool { - return len(s) >= len(sub) && (s == sub || len(sub) == 0 || - (func() bool { - for i := 0; i+len(sub) <= len(s); i++ { - if s[i:i+len(sub)] == sub { - return true - } - } - return false - })()) -} - -func TestNestedLayoutKeepsMarkdownLeavesAndSiblingOrder(t *testing.T) { - leaf := func(slot, text string) any { return map[string]any{"type": "markdown", "slot": slot, "value": text} } - nodes := []any{map[string]any{"type": "footer", "value": []any{ - map[string]any{"type": "row", "slot": "footer", "value": []any{ - leaf("brand", "### Marqdo\n\nReadable **documents**."), - map[string]any{"类型": "横排", "槽": "links", "值": []any{ - leaf("docs", "### Docs\n\n[Guide](/guide)"), - leaf("community", "### Community\n\n[About](/about)"), - }}, - }}, - }}} - got, err := RenderNodes(nodes) - if err != nil { - t.Fatal(err) - } - for _, want := range []string{"documents", `href="/guide"`, `href="/about"`} { - if !strings.Contains(got, want) { - t.Fatalf("missing %q: %s", want, got) - } - } - if strings.Index(got, "slot-brand") > strings.Index(got, "slot-docs") || strings.Index(got, "slot-docs") > strings.Index(got, "slot-community") { - t.Fatal("component order changed") - } - if strings.Contains(got, "map[") { - t.Fatal("nested data was stringified") - } -} - -func TestNestedColumnTableRetainsTypedValue(t *testing.T) { - nodes := map[string]any{"@": []any{1}, "type": []any{"column"}, "value": []any{[]any{map[string]any{"type": "markdown", "value": "# Leaf"}}}} - got, err := RenderNodes(nodes) - if err != nil || !strings.Contains(got, "not child rows", []any{"bad row"}} { - if _, err := RenderNodes([]any{map[string]any{"type": "row", "value": value}}); err == nil { - t.Fatalf("accepted %v", value) - } - } - var deep any = []any{map[string]any{"type": "text", "value": "end"}} - for i := 0; i < 66; i++ { - deep = []any{map[string]any{"type": "column", "value": deep}} - } - if _, err := RenderNodes(deep); err == nil { - t.Fatal("unbounded nesting") - } -} - -func TestViewDocumentExecutesOnlyAnExplicitMain(t *testing.T) { - calls := 0 - run := func(path string, args map[string]any) (any, error) { - calls++ - return []any{map[string]any{"type": "markdown", "value": "# Composed"}}, nil - } - f := ArtifactFile{Path: "index.mq.md", Rel: "index.mq.md", Meta: map[string]string{}, Body: "# Ordinary"} - body, structured, err := RenderFile(f, run) - if err != nil || structured || calls != 0 || !strings.Contains(body, "Ordinary") { - t.Fatalf("ordinary: %v %v %d", err, structured, calls) - } - f.Meta["视图"] = "main" - body, structured, err = RenderFile(f, run) - if err != nil || !structured || calls != 1 || !strings.Contains(body, "Composed") { - t.Fatalf("view: %v %v %d", err, structured, calls) - } - f.Meta["视图"] = "typo" - if _, _, err = RenderFile(f, run); err == nil || calls != 1 { - t.Fatal("invalid view must fail before execution") - } -} - -func TestViewDocumentRejectsAnEmptyAssemblyAndAutomaticDataSource(t *testing.T) { - f := ArtifactFile{Path: "index.mq.md", Rel: "index.mq.md", Meta: map[string]string{"view": "main"}} - calls := 0 - run := func(string, map[string]any) (any, error) { calls++; return nil, nil } - if _, _, err := RenderFile(f, run); err == nil || !strings.Contains(err.Error(), "must return View rows") { - t.Fatalf("empty assembly: %v", err) - } - f.Meta["data_source"] = "posts" - if _, _, err := RenderFile(f, run); err == nil || calls != 1 { - t.Fatalf("data source silently ignored: %v", err) - } -} - -func TestInteractiveControlsUseTypedAttributesAndEscapedText(t *testing.T) { - nodes := []any{map[string]any{"type":"form", "attrs":map[string]any{"id":"editor", "method":"post", "action":"/save"}, "value":[]any{ - map[string]any{"type":"label", "value":"Title", "attrs":map[string]any{"for":"title"}}, - map[string]any{"type":"input", "value":`">`, "attrs":map[string]any{"id":"title", "name":"title", "required":true, "disabled":false, "maxlength":float64(120)}}, - map[string]any{"type":"textarea", "value":"", "attrs":map[string]any{"id":"doc", "rows":float64(16), "aria-label":"Document"}}, - map[string]any{"type":"button", "value":"Save & return", "attrs":map[string]any{"type":"submit", "data-action":"save"}}, - map[string]any{"类型":"预格式", "值":"", "属性":map[string]any{"id":"log","hidden":false}}, - }}} - got,err := RenderNodes(nodes) - if err != nil { t.Fatal(err) } - for _, expected := range []string{`") || strings.Contains(got," disabled") || strings.Contains(got," hidden") || strings.Contains(got,"map[") { t.Fatalf("control values leaked into markup: %s",got) } -} -func TestAttributeRecordsApplyToContainersAndLinks(t *testing.T) { - got,err:=RenderNodes([]any{map[string]any{"type":"section","attrs":map[string]any{"id":"view-detail","hidden":true},"value":[]any{ - map[string]any{"type":"link","value":"Open","attrs":map[string]any{"href":"/a?x=1&y=2","title":"Detail"}}, - }}}) - if err != nil || !strings.Contains(got,`id="view-detail"`) || !strings.Contains(got," hidden") || !strings.Contains(got,`href="/a?x=1&y=2"`) { t.Fatalf("%v: %s",err,got) } - for _,attrs:=range []map[string]any{ - {"onclick":"alert(1)"},{"style":"position:fixed"},{"data-x\" onload":"x"},{"href":"javascript:alert(1)"},{"required":"true"},{"title":[]any{"nested"}}, - } { - if _,err:=RenderNodes([]any{map[string]any{"type":"button","value":"Run","attrs":attrs}});err==nil { t.Fatalf("accepted invalid attributes: %v",attrs) } - } -} - -func TestResourcesStayStructuredAndEscapeTheirURLs(t *testing.T) { - got,err:=RenderNodes([]any{ - map[string]any{"type":"script","value":"/static/marqdo-bridge.js","attrs":map[string]any{"type":"module","data-mq-wasm":"/static/runtime.wasm","data-mq-source-url":"/static/client.mq.md"}}, - map[string]any{"type":"stylesheet","value":"/static/theme.css?x=1&y=2"}, - }) - if err!=nil {t.Fatal(err)} - for _,want:=range []string{``, - } { - if !strings.Contains(head, want) { - t.Fatalf("missing %s: %s", want, head) - } - } - if strings.Count(head, `href="/theme.css`) != 1 || strings.Count(head, `src="/client.js"`) != 1 { - t.Fatal("duplicate head resource: " + head) - } - if strings.Contains(body, "Actual OG") || strings.Contains(body, "fonts.example") || strings.Contains(body, "slot-head") || !strings.Contains(body, "Actual page") { - t.Fatal(body) - } - calls := 0 - fragment, err := RenderNodesWithResources(nodes, func(map[string]any) (string, error) { calls++; return "unexpected", nil }) - if err != nil || calls != 0 || strings.Contains(fragment, "x"}, - {"_type": "document_head", "body_class": "admin"}, - {"_type": "document_head", "meta": []any{42}}, - {"_type": "document_head", "meta": map[string]any{"key": []any{"a", "b"}, "value": []any{"one"}}}, - {"_type": "document_head", "meta": map[string]any{"key": "description", "value": []any{"nested"}}}, - {"_type": "document_head", "meta": map[string]any{"key": "viewport", "value": "owned"}}, - {"_type": "document_head", "meta": []any{map[string]any{"key": "description", "value": "a"}, map[string]any{"key": "description", "value": "b"}}}, - {"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": "/a.js", "onclick": "x"}}}, - {"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet", "href": "/a.css", "media": map[string]any{"x": "nested"}}}}, - {"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet"}}}, - } { - if _, err := ParseDocumentHead(resource); err == nil { - t.Fatalf("accepted %#v", resource) - } - } - if _, err := ParseDocumentHead(valid); err != nil { - t.Fatal(err) - } - for _, url := range []string{"javascript:alert(1)", "data:text/javascript,x", "//other.test/a", "relative.css", "/\\other.test/a", "https://", "/a\n.js"} { - for _, resource := range []map[string]any{ - {"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": url}}}, - {"_type": "document_head", "meta": map[string]any{"key": "canonical", "value": url}}, - } { - if _, err := ParseDocumentHead(resource); err == nil { - t.Fatalf("accepted %q", url) - } - } - } - conflict := []any{headNode(map[string]any{"key": "description", "value": "first"}, nil), - map[string]any{"类型": "纵排", "值": []any{headNode(map[string]any{"键": "description", "值": "second"}, nil)}}} - if _, err := CollectDocumentHead(conflict); err == nil { - t.Fatal("nested head conflict silently overwrote metadata") - } - private := []any{map[string]any{"type": "resource", "value": map[string]any{"_type": "data_query", "where": headNode(nil, nil)}}} - head, err := CollectDocumentHead(private) - if err != nil || len(head.Links) != 0 || len(head.Meta) != 0 { - t.Fatalf("walked private Resource: %v %#v", err, head) - } - var deep any = []any{headNode(nil, nil)} - for i := 0; i < 66; i++ { - deep = []any{map[string]any{"type": "row", "value": deep}} - } - if _, err := CollectDocumentHead(deep); err == nil { - t.Fatal("unbounded head traversal") - } -} diff --git a/plugins/web/internal/artifact/slot_test.go b/plugins/web/internal/artifact/slot_test.go deleted file mode 100755 index eae79fb..0000000 --- a/plugins/web/internal/artifact/slot_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package artifact - -import ( - "strings" - "testing" -) - -func TestFindSlotKeepsNestedTypedResourcesAndRejectsAmbiguity(t *testing.T) { - descriptor := map[string]any{"_type": "data_query", "source": "articles", "slot": "not-a-view-slot"} - nodes := []any{map[string]any{"type": "row", "slot": "layout", "value": []any{ - map[string]any{"类型": "纵排", "槽": "main", "值": []any{ - map[string]any{"type": "resource", "slot": "articles", "value": descriptor}, - }}, - map[string]any{"type": "markdown", "slot": "sidebar", "value": "Separate"}, - }}} - selected, found, err := FindSlot(nodes, "articles") - if err != nil || !found { - t.Fatalf("%v %v", found, err) - } - calls := 0 - html, err := RenderNodesWithResources(selected, func(value map[string]any) (string, error) { - calls++ - if value["source"] != "articles" { - t.Fatal(value) - } - return "

Actual request value

", nil - }) - if err != nil || calls != 1 || !strings.Contains(html, "Actual request value") || strings.Contains(html, "Separate") { - t.Fatalf("%d %v %s", calls, err, html) - } - if _, found, err := FindSlot(nodes, "not-a-view-slot"); err != nil || found { - t.Fatalf("walked Resource internals: %v %v", found, err) - } - duplicate := append(nodes, map[string]any{"type": "text", "slot": "articles", "value": "Ambiguous"}) - if _, _, err := FindSlot(duplicate, "articles"); err == nil { - t.Fatal("duplicate slot accepted") - } - if _, _, err := FindSlot([]any{42}, "articles"); err == nil { - t.Fatal("malformed View accepted") - } -} diff --git a/plugins/web/internal/assets/assets.go b/plugins/web/internal/assets/assets.go deleted file mode 100755 index 431374c..0000000 --- a/plugins/web/internal/assets/assets.go +++ /dev/null @@ -1,585 +0,0 @@ -// Package assets ports head/images/icons HTML assembly (W8 / W-G6). -package assets - -import ( - "fmt" - "path" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// HeadLink is one or `, esc(href)) - s.WriteString(tag) - continue - } - tag := fmt.Sprintf(``, esc(loading)) - inner := img - if href != "" { - inner = fmt.Sprintf(`%s`, esc(href), img) - } - figClass := "mq-img" - if class != "" { - figClass = "mq-img " + class - } - figures.WriteString(fmt.Sprintf(`
%s`, figClass, inner)) - if caption != "" { - figures.WriteString(fmt.Sprintf("
%s
", esc(caption))) - } - figures.WriteString("
") - } - if figures.Len() == 0 { - return "" - } - return `
` + figures.String() + `
` -} - -// AttachHead merges head table links onto page.head. -func AttachHead(page map[string]any, table any) map[string]any { - out := cloneMap(page) - links := AsHeadLinks(table) - existing := HeadLinksFromJSON(out["head"]) - for _, link := range links { - dup := false - for _, e := range existing { - if e.Href == link.Href && strings.EqualFold(e.Rel, link.Rel) { - dup = true - break - } - } - if !dup { - existing = append(existing, link) - } - } - out["head"] = HeadLinksToJSON(existing) - return out -} - -// AttachImages appends images_html on page. -func AttachImages(page map[string]any, table any) map[string]any { - out := cloneMap(page) - html := MakeImagesHTML(table) - prev, _ := out["images_html"].(string) - switch { - case prev == "": - out["images_html"] = html - case html == "": - out["images_html"] = prev - default: - out["images_html"] = prev + html - } - return out -} - -// AttachMeta sets page.meta from SEO table. -func AttachMeta(page map[string]any, meta any) map[string]any { - out := cloneMap(page) - out["meta"] = table.AsMetaMap(meta) - return out -} - -func cloneMap(m map[string]any) map[string]any { - if m == nil { - return map[string]any{} - } - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} diff --git a/plugins/web/internal/assets/assets_test.go b/plugins/web/internal/assets/assets_test.go deleted file mode 100755 index 3f80d2a..0000000 --- a/plugins/web/internal/assets/assets_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package assets - -import ( - "strings" - "testing" -) - -func TestImagesBasic(t *testing.T) { - table := []any{ - map[string]any{"源": "/a.png", "替代": "A", "类": "logo", "加载": "eager"}, - } - h := MakeImagesHTML(table) - if !strings.Contains(h, "mq-images") { - t.Fatalf("missing mq-images: %s", h) - } - if !strings.Contains(h, `src="/a.png"`) { - t.Fatalf("missing src: %s", h) - } - if !strings.Contains(h, `loading="eager"`) { - t.Fatalf("missing loading: %s", h) - } - if !strings.Contains(h, `class="mq-img logo"`) { - t.Fatalf("missing class: %s", h) - } -} - -func TestHeadScriptAndIcon(t *testing.T) { - table := []any{ - map[string]any{"关系": "icon", "地址": "/favicon.ico", "类型": "image/x-icon"}, - map[string]any{"关系": "script", "地址": "/static/a.js"}, - } - h := MakeHeadHTML(table) - if !strings.Contains(h, `rel="icon"`) { - t.Fatalf("missing icon: %s", h) - } - if !strings.Contains(h, ``) { - t.Fatalf("missing script: %s", h) - } - if strings.Contains(h, " defer") { - t.Fatalf("unexpected defer: %s", h) - } -} - -func TestHeadDeferVersion(t *testing.T) { - table := []any{ - map[string]any{"关系": "script", "地址": "/static/a.js", "推迟": true, "版本": "3"}, - } - links := AsHeadLinks(table) - h := RenderHeadLinksWithVersion(links, "2026-09-04") - if !strings.Contains(h, ``) { - t.Fatalf("defer+version: %s", h) - } -} - -func TestNormalizeIcons(t *testing.T) { - table := []any{ - map[string]any{ - "path": "web-fixtures/public/favicon.png", "rel": "icon", - "type": "image/png", "sizes": "32x32", "url": "/favicon.ico", - }, - } - icons, head, routes := NormalizeIcons(table) - if len(icons) != 1 { - t.Fatalf("icons=%d", len(icons)) - } - if len(head) == 0 { - t.Fatal("expected site head") - } - if len(routes) == 0 { - t.Fatal("expected routes") - } -} diff --git a/plugins/web/internal/auth/auth.go b/plugins/web/internal/auth/auth.go deleted file mode 100755 index df35a16..0000000 --- a/plugins/web/internal/auth/auth.go +++ /dev/null @@ -1,142 +0,0 @@ -// Package auth ports login/check/logout and credential checks from the Rust web plugin. -package auth - -import ( - "fmt" - "strconv" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/password" - "github.com/marqdo/marqdo/plugins/web/internal/session" - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -var ( - userKeys = []string{"用户名", "用户", "username", "user", "账号"} - passKeys = []string{"密码", "password", "pass", "口令"} - roleKeys = []string{"角色", "role", "roles"} -) - -// New builds an auth bag: {"users":…,"session_ttl":N} (web_auth_new). -func New(users any, sessionTTL uint64) map[string]any { - if sessionTTL == 0 { - sessionTTL = 3600 - } - return map[string]any{ - "users": users, - "session_ttl": float64(sessionTTL), - } -} - -// CheckCredentials validates username/password against a users table (GFM or row list). -// Missing role defaults to "admin". Returns username, role, ok. -func CheckCredentials(users any, username, pass string) (string, string, bool) { - rowsAny := table.AsRows(users) - rows, ok := rowsAny.([]any) - if !ok { - return "", "", false - } - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - u := pickCell(m, userKeys) - p := pickCell(m, passKeys) - if u == username && password.Verify(pass, p) { - role := pickCell(m, roleKeys) - if role == "" { - role = "admin" - } - return u, strings.ToLower(role), true - } - } - return "", "", false -} - -func pickCell(m map[string]any, keys []string) string { - for _, k := range keys { - if v, ok := m[k]; ok { - return cellStr(v) - } - } - return "" -} - -func cellStr(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - case int: - return strconv.Itoa(t) - case int64: - return strconv.FormatInt(t, 10) - default: - return fmt.Sprint(t) - } -} - -// Login validates credentials and creates a session. -// Success: {"ok":true,"session_id":…,"username":…,"role":…,"permissions":…} -// Failure: {"ok":false} -func Login(username, pass string, users any, sessionTTL uint64) map[string]any { - u, role, ok := CheckCredentials(users, username, pass) - if !ok { - return map[string]any{"ok": false} - } - id := session.NewID(sessionTTL) - session.SetValue(id, "username", u) - session.SetValue(id, "role", role) - return map[string]any{ - "ok": true, - "session_id": id, - "username": u, - "role": role, - } -} - -// AttachPermissions writes permission codes onto an existing login session. -func AttachPermissions(sessionID string, codes []string) { - if sessionID == "" { - return - } - session.SetPermissions(sessionID, codes) -} - -// Check returns session auth state (web_auth_check). -func Check(sessionID string) map[string]any { - v, ok := session.GetValue(sessionID, "username") - if !ok { - return map[string]any{"ok": false} - } - u, _ := v.(string) - if u == "" { - return map[string]any{"ok": false} - } - role := "admin" - if rv, rok := session.GetValue(sessionID, "role"); rok { - if s, ok := rv.(string); ok && s != "" { - role = s - } - } - perms := session.PermissionsFromSession(sessionID) - out := map[string]any{"ok": true, "username": u, "role": role} - if len(perms) > 0 { - out["permissions"] = perms - } - return out -} - -// Logout destroys the session (web_auth_logout). -func Logout(sessionID string) map[string]any { - return map[string]any{"ok": session.DestroyID(sessionID)} -} diff --git a/plugins/web/internal/auth/auth_test.go b/plugins/web/internal/auth/auth_test.go deleted file mode 100755 index c06b83f..0000000 --- a/plugins/web/internal/auth/auth_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package auth_test - -import ( - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/auth" - "github.com/marqdo/marqdo/plugins/web/internal/password" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func usersEN() any { - return []any{ - map[string]any{"username": "admin", "password": "secret"}, - map[string]any{"用户": "站长", "密码": "pw123"}, - } -} - -func usersZHTable() any { - return map[string]any{ - "行": []any{"1"}, - "用户": []any{"admin"}, - "密码": []any{"secret"}, - } -} - -func TestLoginCheckLogout(t *testing.T) { - session.Configure(session.Config{TTLSec: 3600}) - session.Reset(3600) - r := auth.Login("admin", "secret", usersEN(), 0) - if r["ok"] != true { - t.Fatalf("login: %v", r) - } - sid, _ := r["session_id"].(string) - if sid == "" || r["username"] != "admin" || r["role"] != "admin" { - t.Fatalf("login fields: %v", r) - } - check := auth.Check(sid) - if check["ok"] != true || check["username"] != "admin" { - t.Fatalf("check: %v", check) - } - bad := auth.Login("admin", "wrong", usersEN(), 0) - if bad["ok"] != false { - t.Fatalf("bad login: %v", bad) - } - out := auth.Logout(sid) - if out["ok"] != true { - t.Fatalf("logout: %v", out) - } - if auth.Check(sid)["ok"] != false { - t.Fatal("after logout still ok") - } -} - -func TestGFMUsersTable(t *testing.T) { - session.Reset(3600) - r := auth.Login("admin", "secret", usersZHTable(), 120) - if r["ok"] != true { - t.Fatalf("gfm login: %v", r) - } -} - -func TestHashedPasswordLogin(t *testing.T) { - session.Reset(3600) - hash, err := password.Hash("secret") - if err != nil { - t.Fatal(err) - } - users := []any{map[string]any{"username": "admin", "password": hash}} - r := auth.Login("admin", "secret", users, 0) - if r["ok"] != true { - t.Fatalf("hashed login: %v", r) - } -} - -func TestAuthNew(t *testing.T) { - bag := auth.New(usersEN(), 120) - if bag["session_ttl"] != float64(120) { - t.Fatalf("%v", bag) - } -} diff --git a/plugins/web/internal/cache/cache.go b/plugins/web/internal/cache/cache.go deleted file mode 100755 index af07627..0000000 --- a/plugins/web/internal/cache/cache.go +++ /dev/null @@ -1,260 +0,0 @@ -// Package cache ports memory and Redis cache backends from the Rust web plugin (W-G9). -package cache - -import ( - "context" - "fmt" - "strings" - "sync" - "time" - - "github.com/redis/go-redis/v9" -) - -type entry struct { - value string - exp *uint64 // absolute expiry unix secs; nil = no TTL -} - -type memStore struct { - data map[string]entry -} - -type backend struct { - mem *memStore - redisURL string -} - -var ( - handlesMu sync.Mutex - handles = map[string]*backend{} -) - -func now() uint64 { - return uint64(time.Now().Unix()) -} - -func isMemory(url string) bool { - u := strings.ToLower(strings.TrimSpace(url)) - return u == "" || u == "memory:" || u == "memory://" || strings.HasPrefix(u, "memory:") -} - -func isRedis(url string) bool { - u := strings.ToLower(strings.TrimSpace(url)) - return strings.HasPrefix(u, "redis://") || strings.HasPrefix(u, "rediss://") -} - -// Open creates or reuses a cache handle. Returns {_type, url}. -func Open(url string) (map[string]any, error) { - url = strings.TrimSpace(url) - if url == "" { - url = "memory:" - } - if !isMemory(url) && !isRedis(url) { - return nil, fmt.Errorf("cache url must be `memory:` or `redis://…`, got `%s`", url) - } - handlesMu.Lock() - defer handlesMu.Unlock() - if _, ok := handles[url]; !ok { - var b backend - if isMemory(url) { - b.mem = &memStore{data: map[string]entry{}} - } else { - b.redisURL = url - } - handles[url] = &b - } - return map[string]any{"_type": "cache", "url": url}, nil -} - -func pruneMem(store *memStore) { - t := now() - for k, e := range store.data { - if e.exp != nil && *e.exp <= t { - delete(store.data, k) - } - } -} - -func withBackend(url string, f func(*backend) (map[string]any, error)) (map[string]any, error) { - handlesMu.Lock() - defer handlesMu.Unlock() - b, ok := handles[url] - if !ok { - return nil, fmt.Errorf("cache `%s` not opened — call cache.new first", url) - } - return f(b) -} - -// Get returns {ok:true,value} on hit or {ok:false} on miss. -func Get(url, key string) (map[string]any, error) { - return withBackend(url, func(b *backend) (map[string]any, error) { - if b.mem != nil { - pruneMem(b.mem) - if e, ok := b.mem.data[key]; ok { - return map[string]any{"ok": true, "value": e.value}, nil - } - return map[string]any{"ok": false}, nil - } - return redisGet(b.redisURL, key) - }) -} - -// Set stores a value with optional TTL seconds (0/nil = no expiry). -func Set(url, key, value string, ttlSec *uint64) (map[string]any, error) { - return withBackend(url, func(b *backend) (map[string]any, error) { - if b.mem != nil { - pruneMem(b.mem) - var exp *uint64 - if ttlSec != nil && *ttlSec > 0 { - t := now() + *ttlSec - exp = &t - } - b.mem.data[key] = entry{value: value, exp: exp} - return map[string]any{"ok": true}, nil - } - return redisSet(b.redisURL, key, value, ttlSec) - }) -} - -// Del removes a key. Returns {ok:bool} (true if key existed). -func Del(url, key string) (map[string]any, error) { - return withBackend(url, func(b *backend) (map[string]any, error) { - if b.mem != nil { - ok := false - if _, exists := b.mem.data[key]; exists { - delete(b.mem.data, key) - ok = true - } - return map[string]any{"ok": ok}, nil - } - return redisDel(b.redisURL, key) - }) -} - -// Exists returns {ok:bool} — ok is true when the key is present. -func Exists(url, key string) (map[string]any, error) { - return withBackend(url, func(b *backend) (map[string]any, error) { - if b.mem != nil { - pruneMem(b.mem) - _, ok := b.mem.data[key] - return map[string]any{"ok": ok}, nil - } - return redisExists(b.redisURL, key) - }) -} - -// TTL returns remaining seconds: -1 no expiry, -2 missing key. -func TTL(url, key string) (map[string]any, error) { - return withBackend(url, func(b *backend) (map[string]any, error) { - if b.mem != nil { - pruneMem(b.mem) - if e, ok := b.mem.data[key]; ok { - var left int64 = -1 - if e.exp != nil { - left = int64(*e.exp - now()) - if left < 0 { - left = 0 - } - } - return map[string]any{"ok": true, "ttl": left}, nil - } - return map[string]any{"ok": false, "ttl": -2}, nil - } - return redisTTL(b.redisURL, key) - }) -} - -// Reset clears all handles (tests). -func Reset() { - handlesMu.Lock() - defer handlesMu.Unlock() - handles = map[string]*backend{} -} - -func redisClient(url string) (*redis.Client, error) { - opts, err := redis.ParseURL(url) - if err != nil { - return nil, err - } - return redis.NewClient(opts), nil -} - -func redisGet(url, key string) (map[string]any, error) { - client, err := redisClient(url) - if err != nil { - return nil, err - } - defer client.Close() - ctx := context.Background() - v, err := client.Get(ctx, key).Result() - if err == redis.Nil { - return map[string]any{"ok": false}, nil - } - if err != nil { - return nil, err - } - return map[string]any{"ok": true, "value": v}, nil -} - -func redisSet(url, key, value string, ttlSec *uint64) (map[string]any, error) { - client, err := redisClient(url) - if err != nil { - return nil, err - } - defer client.Close() - ctx := context.Background() - if ttlSec != nil && *ttlSec > 0 { - if err := client.SetEx(ctx, key, value, time.Duration(*ttlSec)*time.Second).Err(); err != nil { - return nil, err - } - } else { - if err := client.Set(ctx, key, value, 0).Err(); err != nil { - return nil, err - } - } - return map[string]any{"ok": true}, nil -} - -func redisDel(url, key string) (map[string]any, error) { - client, err := redisClient(url) - if err != nil { - return nil, err - } - defer client.Close() - ctx := context.Background() - n, err := client.Del(ctx, key).Result() - if err != nil { - return nil, err - } - return map[string]any{"ok": n > 0}, nil -} - -func redisExists(url, key string) (map[string]any, error) { - client, err := redisClient(url) - if err != nil { - return nil, err - } - defer client.Close() - ctx := context.Background() - n, err := client.Exists(ctx, key).Result() - if err != nil { - return nil, err - } - return map[string]any{"ok": n > 0}, nil -} - -func redisTTL(url, key string) (map[string]any, error) { - client, err := redisClient(url) - if err != nil { - return nil, err - } - defer client.Close() - ctx := context.Background() - t, err := client.TTL(ctx, key).Result() - if err != nil { - return nil, err - } - secs := int64(t.Seconds()) - return map[string]any{"ok": secs >= -1, "ttl": secs}, nil -} diff --git a/plugins/web/internal/cache/cache_test.go b/plugins/web/internal/cache/cache_test.go deleted file mode 100755 index c258a4a..0000000 --- a/plugins/web/internal/cache/cache_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package cache - -import ( - "testing" - "time" -) - -func TestMemoryRoundtrip(t *testing.T) { - Reset() - url := "memory:test-cache" - if _, err := Open(url); err != nil { - t.Fatal(err) - } - ttl := uint64(60) - if _, err := Set(url, "a", "1", &ttl); err != nil { - t.Fatal(err) - } - g, err := Get(url, "a") - if err != nil { - t.Fatal(err) - } - if g["ok"] != true { - t.Fatalf("get ok: %v", g["ok"]) - } - if g["value"] != "1" { - t.Fatalf("value: %v", g["value"]) - } - ex, err := Exists(url, "a") - if err != nil { - t.Fatal(err) - } - if ex["ok"] != true { - t.Fatalf("exists: %v", ex["ok"]) - } - if _, err := Del(url, "a"); err != nil { - t.Fatal(err) - } - g, err = Get(url, "a") - if err != nil { - t.Fatal(err) - } - if g["ok"] != false { - t.Fatalf("get after del: %v", g["ok"]) - } - ex, err = Exists(url, "a") - if err != nil { - t.Fatal(err) - } - if ex["ok"] != false { - t.Fatalf("exists after del: %v", ex["ok"]) - } -} - -func TestMemoryTTLExpiry(t *testing.T) { - Reset() - url := "memory:ttl-test" - if _, err := Open(url); err != nil { - t.Fatal(err) - } - ttl := uint64(1) - if _, err := Set(url, "k", "v", &ttl); err != nil { - t.Fatal(err) - } - tt, err := TTL(url, "k") - if err != nil { - t.Fatal(err) - } - if tt["ok"] != true { - t.Fatalf("ttl ok: %v", tt["ok"]) - } - ttlVal, ok := tt["ttl"].(int64) - if !ok { - // JSON roundtrip may use float64 in some paths; accept both. - if f, ok := tt["ttl"].(float64); ok { - ttlVal = int64(f) - } else { - t.Fatalf("ttl type: %T", tt["ttl"]) - } - } - if ttlVal < 0 || ttlVal > 1 { - t.Fatalf("ttl seconds: %d", ttlVal) - } - time.Sleep(1100 * time.Millisecond) - g, err := Get(url, "k") - if err != nil { - t.Fatal(err) - } - if g["ok"] != false { - t.Fatalf("expected expired miss, got %v", g) - } -} - -func TestMemoryDelReturnsOk(t *testing.T) { - Reset() - url := "memory:del-test" - if _, err := Open(url); err != nil { - t.Fatal(err) - } - d, err := Del(url, "missing") - if err != nil { - t.Fatal(err) - } - if d["ok"] != false { - t.Fatalf("del missing: %v", d["ok"]) - } - if _, err := Set(url, "x", "y", nil); err != nil { - t.Fatal(err) - } - d, err = Del(url, "x") - if err != nil { - t.Fatal(err) - } - if d["ok"] != true { - t.Fatalf("del existing: %v", d["ok"]) - } -} - -func TestRedisOpenOnly(t *testing.T) { - Reset() - out, err := Open("redis://127.0.0.1:6379/0") - if err != nil { - t.Fatal(err) - } - if out["_type"] != "cache" { - t.Fatalf("type: %v", out["_type"]) - } -} diff --git a/plugins/web/internal/compose/compose.go b/plugins/web/internal/compose/compose.go deleted file mode 100755 index c031432..0000000 --- a/plugins/web/internal/compose/compose.go +++ /dev/null @@ -1,342 +0,0 @@ -// Package compose ports page assemble helpers from the Rust web plugin. -package compose - -import ( - "fmt" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// CallLib loads a lib.member value (host callback). -type CallLib func(path string) (any, error) - -func cloneMap(m map[string]any) map[string]any { - if m == nil { - return map[string]any{} - } - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} - -func asObject(v any) map[string]any { - if m, ok := v.(map[string]any); ok { - return cloneMap(m) - } - return map[string]any{} -} - -func strField(m map[string]any, key string) string { - if m == nil { - return "" - } - s, _ := m[key].(string) - return s -} - -// ComposeComponents merges layout component rows into a page bag. -func ComposeComponents(page any, layout any, callLib CallLib) (any, error) { - obj := asObject(page) - rows := table.AsCompose(layout) - arr, _ := rows.([]any) - - css := strField(obj, "styles_css") - slotClass := map[string]any{} - if sc, ok := obj["slot_class"].(map[string]any); ok { - slotClass = cloneMap(sc) - } - parts := map[string]any{} - composeOut := make([]any, 0, len(arr)) - - for _, row := range arr { - rm, ok := row.(map[string]any) - if !ok { - continue - } - srcRaw := strField(rm, "src") - styleRaw := strField(rm, "style") - if srcRaw == "" { - continue - } - - var name string - var bindTable any - switch sp := table.ParseSitePath(srcRaw); sp.Kind { - case table.SitePathLibMember: - t, err := callLib(sp.Lib + "." + sp.Member) - if err != nil { - return nil, err - } - name = sp.Member - bindTable = t - case table.SitePathPlain: - t, err := callLib(sp.Plain + "." + sp.Plain) - if err != nil { - return nil, err - } - name = sp.Plain - bindTable = t - case table.SitePathDbField: - return nil, fmt.Errorf("component cell cannot be a db field: %s", srcRaw) - } - - slot := table.NormalizeSlot(name) - styleName := "" - if styleRaw != "" { - switch sp := table.ParseSitePath(styleRaw); sp.Kind { - case table.SitePathLibMember: - st, err := callLib(sp.Lib + "." + sp.Member) - if err != nil { - return nil, err - } - css += table.AsCSSNamed(sp.Member, st) - styleName = sp.Member - case table.SitePathPlain: - styleName = sp.Plain - case table.SitePathDbField: - styleName = table.NormalizeRef(styleRaw) - } - } - - binds := table.AsBind(bindTable) - switch slot { - case "nav": - obj["nav"] = binds - case "sidebar": - obj["sidebar"] = binds - case "footer": - obj["footer"] = binds - default: - obj["main"] = binds - } - if styleName != "" { - slotClass[slot] = styleName - } - composeOut = append(composeOut, map[string]any{ - "src": name, - "style": styleName, - "slot": slot, - }) - - part := map[string]any{ - "_type": "page", - "slot": slot, - "fragment": slot, - } - switch slot { - case "nav": - part["nav"] = binds - case "sidebar": - part["sidebar"] = binds - case "footer": - part["footer"] = binds - default: - part["main"] = binds - } - parts[name] = part - } - - obj["compose"] = composeOut - if css != "" { - obj["styles_css"] = css - } - if len(slotClass) > 0 { - obj["slot_class"] = slotClass - } - if len(parts) > 0 { - obj["parts"] = parts - } - return obj, nil -} - -func resolveBinds(mainTable any, callLib CallLib) (binds []any, css string, err error) { - raw := table.AsBind(mainTable) - arr, _ := raw.([]any) - binds = make([]any, 0, len(arr)) - for _, b := range arr { - bm, ok := b.(map[string]any) - if !ok { - continue - } - front := strField(bm, "front") - backRaw := strField(bm, "back") - cssRaw := strField(bm, "css") - - var back string - switch sp := table.ParseSitePath(backRaw); sp.Kind { - case table.SitePathDbField: - back = sp.Table + "." + sp.Field - case table.SitePathPlain: - back = sp.Plain - case table.SitePathLibMember: - v, err := callLib(sp.Lib + "." + sp.Member) - if err != nil { - back = sp.Lib + "." + sp.Member - } else if s, ok := v.(string); ok { - back = s - } else { - back = fmt.Sprint(v) - } - } - - cssName := "" - switch sp := table.ParseSitePath(cssRaw); sp.Kind { - case table.SitePathLibMember: - st, err := callLib(sp.Lib + "." + sp.Member) - if err != nil { - return nil, "", err - } - css += table.AsCSSNamed(sp.Member, st) - cssName = sp.Member - case table.SitePathPlain: - cssName = sp.Plain - case table.SitePathDbField: - cssName = table.NormalizeRef(cssRaw) - } - - binds = append(binds, map[string]any{ - "front": front, - "back": back, - "css": cssName, - }) - } - return binds, css, nil -} - -// ComposeMain merges a main bind table into a page bag. -func ComposeMain(page any, mainTable any, callLib CallLib) (any, error) { - obj := asObject(page) - binds, cssExtra, err := resolveBinds(mainTable, callLib) - if err != nil { - return nil, err - } - css := strField(obj, "styles_css") + cssExtra - - if t, ok := table.BindTableName(binds); ok { - obj["table"] = t - } - obj["main"] = binds - if css != "" { - obj["styles_css"] = css - } - - parts := map[string]any{} - if p, ok := obj["parts"].(map[string]any); ok { - parts = cloneMap(p) - } - part := map[string]any{ - "_type": "page", - "slot": "main", - "fragment": "main", - "main": binds, - } - if intro, ok := obj["intro"]; ok { - part["intro"] = intro - } - parts["index"] = part - obj["parts"] = parts - return obj, nil -} - -// ComposeList appends a secondary bind (detail + child list), with optional -// query/order/target (inject into intro element id, same as form_target). -func ComposeList(page any, mainTable any, query any, order, target string, callLib CallLib) (any, error) { - obj := asObject(page) - binds, cssExtra, err := resolveBinds(mainTable, callLib) - if err != nil { - return nil, err - } - if cssExtra != "" { - prev := strField(obj, "styles_css") - if prev != "" { - obj["styles_css"] = prev + cssExtra - } else { - obj["styles_css"] = cssExtra - } - } - entry := map[string]any{"main": binds} - if query != nil { - entry["query"] = query - } - if strings.TrimSpace(order) != "" { - entry["order"] = strings.TrimSpace(order) - } - if t := strings.TrimSpace(target); t != "" { - entry["target"] = t - } - lists := []any{} - if existing, ok := obj["lists"].([]any); ok { - lists = append(lists, existing...) - } - lists = append(lists, entry) - obj["lists"] = lists - return obj, nil -} - -// ComposeForm embeds a form into the page main slot. -func ComposeForm(page any, form any, formID string, formTarget *string) (any, error) { - id := strings.TrimSpace(formID) - if id == "" { - return nil, fmt.Errorf("compose_form requires non-empty `id`") - } - obj := asObject(page) - - frm := form - if m, ok := form.(map[string]any); ok { - fm := cloneMap(m) - if _, ok := fm["show_meta"]; !ok { - fm["show_meta"] = false - } - if _, ok := fm["title"]; !ok { - fm["title"] = id - } - frm = fm - } - - obj["form_id"] = id - obj["form"] = frm - - var target *string - if formTarget != nil { - t := strings.TrimSpace(*formTarget) - if t != "" { - target = &t - obj["form_target"] = t - } else { - delete(obj, "form_target") - } - } else { - delete(obj, "form_target") - } - - forms := map[string]any{} - if f, ok := obj["forms"].(map[string]any); ok { - forms = cloneMap(f) - } - forms[id] = frm - obj["forms"] = forms - - parts := map[string]any{} - if p, ok := obj["parts"].(map[string]any); ok { - parts = cloneMap(p) - } - part := map[string]any{ - "_type": "page", - "slot": "main", - "fragment": "main", - "form_id": id, - "form": frm, - } - if target != nil { - part["form_target"] = *target - } - if intro, ok := obj["intro"]; ok { - part["intro"] = intro - } - parts["form_"+id] = part - obj["parts"] = parts - return obj, nil -} diff --git a/plugins/web/internal/compose/compose_auth.go b/plugins/web/internal/compose/compose_auth.go deleted file mode 100755 index 31cde8c..0000000 --- a/plugins/web/internal/compose/compose_auth.go +++ /dev/null @@ -1,45 +0,0 @@ -package compose - -import ( - "fmt" - "strings" -) - -// ComposeAuthForm stamps page.auth_form for progressive-enhancement login/register. -// action is the form POST path (e.g. /login, /desk/login, /register). -func ComposeAuthForm(page any, action, submit, formID, errID, target, nextDefault, kind string) (any, error) { - action = strings.TrimSpace(action) - if action == "" { - return nil, fmt.Errorf("compose_auth_form requires non-empty action") - } - obj := asObject(page) - kind = strings.TrimSpace(strings.ToLower(kind)) - if kind == "" { - if strings.Contains(strings.ToLower(action), "register") { - kind = "register" - } else { - kind = "login" - } - } - spec := map[string]any{ - "action": action, - "kind": kind, - } - if s := strings.TrimSpace(submit); s != "" { - spec["submit"] = s - } - if s := strings.TrimSpace(formID); s != "" { - spec["form_id"] = s - } - if s := strings.TrimSpace(errID); s != "" { - spec["err_id"] = s - } - if s := strings.TrimSpace(target); s != "" { - spec["target"] = s - } - if s := strings.TrimSpace(nextDefault); s != "" { - spec["next"] = s - } - obj["auth_form"] = spec - return obj, nil -} diff --git a/plugins/web/internal/compose/compose_form_load.go b/plugins/web/internal/compose/compose_form_load.go deleted file mode 100755 index 3d26b5a..0000000 --- a/plugins/web/internal/compose/compose_form_load.go +++ /dev/null @@ -1,24 +0,0 @@ -package compose - -import ( - "fmt" - "strings" -) - -// ComposeFormLoad stamps page.form_load so render prefills the composed form -// from DB by route/query id (desk edit pages without author JS). -func ComposeFormLoad(page any, table, idParam string) (any, error) { - obj := asObject(page) - table = strings.TrimSpace(table) - if table == "" { - return nil, fmt.Errorf("compose_form_load requires non-empty table") - } - spec := map[string]any{"table": table} - if s := strings.TrimSpace(idParam); s != "" { - spec["id_param"] = s - } else { - spec["id_param"] = "id" - } - obj["form_load"] = spec - return obj, nil -} diff --git a/plugins/web/internal/compose/compose_form_load_test.go b/plugins/web/internal/compose/compose_form_load_test.go deleted file mode 100755 index c130a2b..0000000 --- a/plugins/web/internal/compose/compose_form_load_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package compose - -import "testing" - -func TestComposeFormLoad(t *testing.T) { - page := map[string]any{"title": "Edit"} - out, err := ComposeFormLoad(page, "posts", "") - if err != nil { - t.Fatal(err) - } - obj, ok := out.(map[string]any) - if !ok { - t.Fatalf("want map, got %T", out) - } - load, ok := obj["form_load"].(map[string]any) - if !ok { - t.Fatalf("missing form_load: %#v", obj) - } - if load["table"] != "posts" { - t.Fatalf("table=%v", load["table"]) - } - if load["id_param"] != "id" { - t.Fatalf("id_param=%v", load["id_param"]) - } -} - -func TestComposeFormLoadRequiresTable(t *testing.T) { - _, err := ComposeFormLoad(map[string]any{}, " ", "id") - if err == nil { - t.Fatal("expected error for empty table") - } -} diff --git a/plugins/web/internal/compose/compose_intro.go b/plugins/web/internal/compose/compose_intro.go deleted file mode 100755 index c483a96..0000000 --- a/plugins/web/internal/compose/compose_intro.go +++ /dev/null @@ -1,437 +0,0 @@ -package compose - -import ( - "fmt" - "html" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// ComposeIntro binds an intro table (|属性|值|样式| / |front|back|style|) onto the -// page — same shape as ComposeMain. Literals go in 值/back; 样式 resolves like -// card_title into styles_css + element class names. Sets page.intro HTML. -// -// Unlike AsBind, the 值/back column is not NormalizeRef'd so inline `code` -// markers survive for richText. -func ComposeIntro(page any, introTable any, callLib CallLib) (any, error) { - obj := asObject(page) - arr := asIntroRows(introTable) - css := strField(obj, "styles_css") - seenStyle := map[string]bool{} - binds := make([]map[string]any, 0, len(arr)) - - for _, bm := range arr { - front := table.NormalizeRef(strField(bm, "front")) - backRaw := strings.TrimSpace(strField(bm, "back")) - cssRaw := table.NormalizeRef(strField(bm, "css")) - - back := backRaw - switch sp := table.ParseSitePath(backRaw); sp.Kind { - case table.SitePathLibMember: - // Intro copy is almost always prose; only resolve clear lib.member refs - // that look like style/module paths (no spaces). - if !strings.ContainsAny(backRaw, " \t\n") { - v, err := callLib(sp.Lib + "." + sp.Member) - if err != nil { - back = sp.Lib + "." + sp.Member - } else if s, ok := v.(string); ok { - back = s - } else { - back = fmt.Sprint(v) - } - } - } - - cssName := "" - if cssRaw != "" { - switch sp := table.ParseSitePath(cssRaw); sp.Kind { - case table.SitePathLibMember: - cssName = sp.Member - if !seenStyle[cssName] { - st, err := callLib(sp.Lib + "." + sp.Member) - if err != nil { - return nil, err - } - css += table.AsCSSNamed(sp.Member, st) - seenStyle[cssName] = true - } - case table.SitePathPlain: - cssName = sp.Plain - case table.SitePathDbField: - cssName = table.NormalizeRef(cssRaw) - } - } - - if front == "" && back == "" { - continue - } - binds = append(binds, map[string]any{ - "front": front, - "back": back, - "css": cssName, - }) - } - - obj["intro"] = RenderIntroHTML(binds) - obj["intro_bind"] = binds - if css != "" { - obj["styles_css"] = css - } - return obj, nil -} - -// MakeIntroHTML builds intro HTML from a bind table without resolving lib styles -// (css column used as class name as-is). Preserves backticks in 值/back. -func MakeIntroHTML(introTable any) string { - arr := asIntroRows(introTable) - binds := make([]map[string]any, 0, len(arr)) - for _, bm := range arr { - front := table.NormalizeRef(strField(bm, "front")) - back := strings.TrimSpace(strField(bm, "back")) - cssName := table.NormalizeRef(strField(bm, "css")) - if front == "" && back == "" { - continue - } - binds = append(binds, map[string]any{ - "front": front, - "back": back, - "css": cssName, - }) - } - return RenderIntroHTML(binds) -} - -func asIntroRows(v any) []map[string]any { - switch t := v.(type) { - case []any: - out := make([]map[string]any, 0, len(t)) - for _, row := range t { - m, ok := row.(map[string]any) - if !ok { - continue - } - front, back, css := "", "", "" - if x, ok := pickIntro(m, []string{"属性", "前端变量", "front", "field"}); ok { - front = cellIntro(x) - } - if x, ok := pickIntro(m, []string{"值", "后端数据库", "back", "db", "text", "文"}); ok { - back = cellIntro(x) - } - if x, ok := pickIntro(m, []string{"样式", "绑定css样式", "css", "class", "style"}); ok { - css = cellIntro(x) - } - if front != "" || back != "" { - out = append(out, map[string]any{"front": front, "back": back, "css": css}) - } - } - return out - case map[string]any: - // Column-oriented map of lists (GFM multi-row table). - fronts, backs, csses := []string{}, []string{}, []string{} - if x, ok := pickIntro(t, []string{"属性", "前端变量", "front", "field"}); ok { - fronts = asIntroStrList(x) - } - if x, ok := pickIntro(t, []string{"值", "后端数据库", "back", "db", "text", "文"}); ok { - backs = asIntroStrList(x) - } - if x, ok := pickIntro(t, []string{"样式", "绑定css样式", "css", "class", "style"}); ok { - csses = asIntroStrList(x) - } - n := len(fronts) - if len(backs) > n { - n = len(backs) - } - out := make([]map[string]any, 0, n) - for i := 0; i < n; i++ { - front, back, css := "", "", "" - if i < len(fronts) { - front = fronts[i] - } - if i < len(backs) { - back = backs[i] - } - if i < len(csses) { - css = csses[i] - } - if front != "" || back != "" { - out = append(out, map[string]any{"front": front, "back": back, "css": css}) - } - } - return out - default: - return nil - } -} - -func asIntroStrList(v any) []string { - switch t := v.(type) { - case []any: - out := make([]string, 0, len(t)) - for _, x := range t { - out = append(out, cellIntro(x)) - } - return out - case []string: - return t - default: - s := cellIntro(v) - if s == "" { - return nil - } - return []string{s} - } -} - -func pickIntro(m map[string]any, keys []string) (any, bool) { - for _, k := range keys { - if v, ok := m[k]; ok { - return v, true - } - } - return nil, false -} - -func cellIntro(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - if t { - return "true" - } - return "false" - case float64: - if t == float64(int64(t)) { - return fmt.Sprintf("%d", int64(t)) - } - return fmt.Sprintf("%v", t) - default: - return fmt.Sprint(t) - } -} - -// RenderIntroHTML turns normalized intro binds into .main-intro inner HTML. -func RenderIntroHTML(binds []map[string]any) string { - if len(binds) == 0 { - return "" - } - var out strings.Builder - i := 0 - for i < len(binds) { - front := strings.TrimSpace(strField(binds[i], "front")) - kind := introKind(front) - switch kind { - case "claim": - j := i - for j < len(binds) && introKind(strField(binds[j], "front")) == "claim" { - j++ - } - out.WriteString(`

`) - for _, row := range binds[i:j] { - cls := classAttr(strField(row, "css")) - out.WriteString(fmt.Sprintf("%s", cls, richText(strField(row, "back")))) - } - out.WriteString(`

`) - i = j - case "step": - j := i - for j < len(binds) && introKind(strField(binds[j], "front")) == "step" { - j++ - } - out.WriteString(`
    `) - for _, row := range binds[i:j] { - cls := classAttr(strField(row, "css")) - out.WriteString(fmt.Sprintf("%s", cls, richText(strField(row, "back")))) - } - out.WriteString(`
`) - i = j - case "mount": - id := strField(binds[i], "back") - if id == "" { - id = front - } - id = strings.TrimPrefix(id, "#") - out.WriteString(fmt.Sprintf(`
`, html.EscapeString(id))) - i++ - case "html": - out.WriteString(strField(binds[i], "back")) - i++ - default: - tag, baseClass := introTagClass(kind, front) - cssName := strField(binds[i], "css") - cls := mergeClass(baseClass, cssName) - out.WriteString(fmt.Sprintf("<%s%s>%s", tag, classAttr(cls), richText(strField(binds[i], "back")), tag)) - i++ - } - } - return out.String() -} - -func introKind(front string) string { - s := strings.ToLower(strings.TrimSpace(front)) - switch s { - case "kicker", "eyebrow", "眉题": - return "kicker" - case "title", "h1", "标题": - return "title" - case "lede", "lead", "导语": - return "lede" - case "claim", "badge", "标签": - return "claim" - case "step", "步骤": - return "step" - case "h2", "小标题": - return "h2" - case "p", "段落": - return "p" - case "mount", "插槽", "slot": - return "mount" - case "html", "原文", "raw": - return "html" - default: - return s - } -} - -func introTagClass(kind, front string) (tag, baseClass string) { - switch kind { - case "kicker": - return "p", "kicker" - case "title": - return "h1", "" - case "lede": - return "p", "lede" - case "h2": - return "h2", "" - case "p": - return "p", "" - default: - if front != "" { - return "p", front - } - return "p", "" - } -} - -func mergeClass(base, style string) string { - base = strings.TrimSpace(base) - style = strings.TrimSpace(style) - switch { - case base == "": - return style - case style == "" || style == base: - return base - default: - return base + " " + style - } -} - -func classAttr(class string) string { - class = strings.TrimSpace(class) - if class == "" { - return "" - } - return ` class="` + html.EscapeString(class) + `"` -} - -// richText escapes text then applies a tiny Markdown subset: [label](url), `code`, **bold**. -func richText(s string) string { - if s == "" { - return "" - } - type span struct { - kind string // text|a|code|strong - a string - b string - } - var spans []span - rest := s - for len(rest) > 0 { - // find earliest special - iLink := strings.Index(rest, "[") - iCode := strings.Index(rest, "`") - iBold := strings.Index(rest, "**") - next := -1 - which := "" - if iLink >= 0 && (next < 0 || iLink < next) { - next, which = iLink, "a" - } - if iCode >= 0 && (next < 0 || iCode < next) { - next, which = iCode, "code" - } - if iBold >= 0 && (next < 0 || iBold < next) { - next, which = iBold, "strong" - } - if next < 0 { - spans = append(spans, span{kind: "text", a: rest}) - break - } - if next > 0 { - spans = append(spans, span{kind: "text", a: rest[:next]}) - } - rest = rest[next:] - switch which { - case "a": - // [label](url) - endLabel := strings.Index(rest, "](") - if endLabel < 0 { - spans = append(spans, span{kind: "text", a: rest[:1]}) - rest = rest[1:] - continue - } - endURL := strings.Index(rest[endLabel+2:], ")") - if endURL < 0 { - spans = append(spans, span{kind: "text", a: rest[:1]}) - rest = rest[1:] - continue - } - label := rest[1:endLabel] - url := rest[endLabel+2 : endLabel+2+endURL] - spans = append(spans, span{kind: "a", a: label, b: url}) - rest = rest[endLabel+2+endURL+1:] - case "code": - end := strings.Index(rest[1:], "`") - if end < 0 { - spans = append(spans, span{kind: "text", a: rest[:1]}) - rest = rest[1:] - continue - } - spans = append(spans, span{kind: "code", a: rest[1 : 1+end]}) - rest = rest[1+end+1:] - case "strong": - end := strings.Index(rest[2:], "**") - if end < 0 { - spans = append(spans, span{kind: "text", a: rest[:2]}) - rest = rest[2:] - continue - } - spans = append(spans, span{kind: "strong", a: rest[2 : 2+end]}) - rest = rest[2+end+2:] - } - } - var out strings.Builder - for _, sp := range spans { - switch sp.kind { - case "a": - out.WriteString(``) - out.WriteString(html.EscapeString(sp.a)) - out.WriteString(``) - case "code": - out.WriteString(``) - out.WriteString(html.EscapeString(sp.a)) - out.WriteString(``) - case "strong": - out.WriteString(``) - out.WriteString(html.EscapeString(sp.a)) - out.WriteString(``) - default: - out.WriteString(html.EscapeString(sp.a)) - } - } - return out.String() -} diff --git a/plugins/web/internal/compose/compose_list_test.go b/plugins/web/internal/compose/compose_list_test.go deleted file mode 100755 index b912c75..0000000 --- a/plugins/web/internal/compose/compose_list_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package compose - -import "testing" - -func TestComposeListAppends(t *testing.T) { - page := map[string]any{"title": "p"} - main := []any{ - map[string]any{"front": "title", "back": "comments.author", "css": ""}, - map[string]any{"front": "body", "back": "comments.body", "css": ""}, - } - q := []any{map[string]any{"field": "post_slug", "op": "=", "value": "{slug}"}} - out, err := ComposeList(page, main, q, "-created_at", "#comment-list", func(string) (any, error) { - return nil, nil - }) - if err != nil { - t.Fatal(err) - } - m := out.(map[string]any) - lists, ok := m["lists"].([]any) - if !ok || len(lists) != 1 { - t.Fatalf("lists=%v", m["lists"]) - } - entry := lists[0].(map[string]any) - if entry["order"] != "-created_at" || entry["target"] != "#comment-list" { - t.Fatalf("entry=%v", entry) - } - if entry["query"] == nil { - t.Fatal("missing query") - } -} diff --git a/plugins/web/internal/compose/compose_nav_brand.go b/plugins/web/internal/compose/compose_nav_brand.go deleted file mode 100755 index d2a3cd7..0000000 --- a/plugins/web/internal/compose/compose_nav_brand.go +++ /dev/null @@ -1,55 +0,0 @@ -package compose - -import ( - "strings" -) - -// ComposeNavBrand stamps page.nav_brand for SSR topnav lockup (logo + title), -// theme toggle, and drawer button chrome. Client WASM only wires behavior. -func ComposeNavBrand(page any, title, href, logo, logoLight, themeKey string) (any, error) { - obj := asObject(page) - spec := map[string]any{} - if s := strings.TrimSpace(title); s != "" { - spec["title"] = s - } - if s := strings.TrimSpace(href); s != "" { - spec["href"] = s - } else { - spec["href"] = "/" - } - if s := strings.TrimSpace(logo); s != "" { - spec["logo"] = s - } - if s := strings.TrimSpace(logoLight); s != "" { - spec["logo_light"] = s - } - if s := strings.TrimSpace(themeKey); s != "" { - spec["theme_key"] = s - } else { - spec["theme_key"] = "mq-theme" - } - obj["nav_brand"] = spec - return obj, nil -} - -// ComposeClient stamps page.client so render injects official bridge auto-mount -// (data-mq-wasm / data-mq-source-url). Authors ship client.mq.md, not business JS. -func ComposeClient(page any, bridge, wasm, source string) (any, error) { - obj := asObject(page) - spec := map[string]any{} - if s := strings.TrimSpace(bridge); s != "" { - spec["bridge"] = s - } else { - spec["bridge"] = "/static/marqdo-bridge.js" - } - if s := strings.TrimSpace(wasm); s != "" { - spec["wasm"] = s - } else { - spec["wasm"] = "/static/marqdo_wasm.wasm" - } - if s := strings.TrimSpace(source); s != "" { - spec["source"] = s - } - obj["client"] = spec - return obj, nil -} diff --git a/plugins/web/internal/compose/compose_nav_brand_test.go b/plugins/web/internal/compose/compose_nav_brand_test.go deleted file mode 100755 index fd27415..0000000 --- a/plugins/web/internal/compose/compose_nav_brand_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package compose_test - -import ( - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/compose" -) - -func TestComposeNavBrandAndClient(t *testing.T) { - page := map[string]any{"title": "t"} - out, err := compose.ComposeNavBrand(page, "求道量子", "/", "/static/logo.png", "/static/logo-light.png", "mq-theme") - if err != nil { - t.Fatal(err) - } - m := out.(map[string]any) - b, ok := m["nav_brand"].(map[string]any) - if !ok || b["title"] != "求道量子" || b["logo"] != "/static/logo.png" { - t.Fatalf("nav_brand: %#v", m["nav_brand"]) - } - out, err = compose.ComposeClient(m, "", "", "/static/client.mq.md") - if err != nil { - t.Fatal(err) - } - m = out.(map[string]any) - c, ok := m["client"].(map[string]any) - if !ok || c["source"] != "/static/client.mq.md" { - t.Fatalf("client: %#v", m["client"]) - } - if c["bridge"] != "/static/marqdo-bridge.js" { - t.Fatalf("bridge default: %#v", c) - } -} diff --git a/plugins/web/internal/compose/compose_test.go b/plugins/web/internal/compose/compose_test.go deleted file mode 100755 index 9325959..0000000 --- a/plugins/web/internal/compose/compose_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package compose_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/compose" -) - -func TestComposeIntroBindAndRichText(t *testing.T) { - page := map[string]any{"title": "Home"} - intro := []any{ - map[string]any{"属性": "kicker", "值": "WWW Demo", "样式": "shell.kicker"}, - map[string]any{"属性": "title", "值": "Marqdo", "样式": "shell.intro_title"}, - map[string]any{"属性": "lede", "值": "Zero author `JS`.", "样式": "shell.lede"}, - map[string]any{"属性": "claim", "值": "0 JS", "样式": "shell.claim"}, - map[string]any{"属性": "claim", "值": "GFM", "样式": "shell.claim"}, - map[string]any{"属性": "step", "值": "Open [New](/new) now.", "样式": "shell.step"}, - map[string]any{"属性": "step", "值": "Compare source.", "样式": "shell.step"}, - } - callLib := func(path string) (any, error) { - switch path { - case "shell.kicker", "shell.intro_title", "shell.lede", "shell.claim", "shell.step": - return map[string]any{ - "property": []any{"color"}, - "value": []any{"red"}, - }, nil - default: - t.Fatalf("unexpected callLib %q", path) - return nil, nil - } - } - out, err := compose.ComposeIntro(page, intro, callLib) - if err != nil { - t.Fatal(err) - } - obj := out.(map[string]any) - html, _ := obj["intro"].(string) - for _, want := range []string{ - `class="kicker"`, - `

Marqdo

`, - `JS`, - `

`, - `0 JS`, - `

    `, - `New`, - } { - if !strings.Contains(html, want) { - t.Fatalf("missing %q in html=%q", want, html) - } - } - css, _ := obj["styles_css"].(string) - if !strings.Contains(css, ".kicker") || !strings.Contains(css, ".intro_title") { - t.Fatalf("styles_css incomplete: %q", css) - } -} - -func TestMakeIntroHTMLZHAliases(t *testing.T) { - tbl := []any{ - map[string]any{"属性": "眉题", "值": "演示", "样式": "kicker"}, - map[string]any{"属性": "标题", "值": "站名", "样式": "intro_title"}, - map[string]any{"属性": "标签", "值": "A", "样式": "claim"}, - map[string]any{"属性": "步骤", "值": "第一步", "样式": "step"}, - } - html := compose.MakeIntroHTML(tbl) - for _, want := range []string{ - `class="kicker"`, - `

    站名

    `, - `

    `, - `

      `, - } { - if !strings.Contains(html, want) { - t.Fatalf("missing %q in %q", want, html) - } - } -} - -func TestComposeComponentsFakeCallLib(t *testing.T) { - page := map[string]any{ - "title": "Home", - } - layout := []any{ - map[string]any{"组件": "site.nav", "样式": ""}, - map[string]any{"组件": "site.footer", "样式": ""}, - } - callLib := func(path string) (any, error) { - switch path { - case "site.nav": - return map[string]any{ - "属性": []any{"Home", "About"}, - "值": []any{"/", "/about"}, - }, nil - case "site.footer": - return []any{ - map[string]any{"属性": "©", "值": "/"}, - }, nil - default: - t.Fatalf("unexpected callLib %q", path) - return nil, nil - } - } - out, err := compose.ComposeComponents(page, layout, callLib) - if err != nil { - t.Fatal(err) - } - obj := out.(map[string]any) - nav, ok := obj["nav"].([]any) - if !ok || len(nav) != 2 { - t.Fatalf("nav=%v", obj["nav"]) - } - n0 := nav[0].(map[string]any) - if n0["front"] != "Home" || n0["back"] != "/" { - t.Fatalf("nav[0]=%v", n0) - } - foot, ok := obj["footer"].([]any) - if !ok || len(foot) != 1 { - t.Fatalf("footer=%v", obj["footer"]) - } - comp, ok := obj["compose"].([]any) - if !ok || len(comp) != 2 { - t.Fatalf("compose=%v", obj["compose"]) - } - c0 := comp[0].(map[string]any) - if c0["src"] != "nav" || c0["slot"] != "nav" { - t.Fatalf("compose[0]=%v", c0) - } - parts, ok := obj["parts"].(map[string]any) - if !ok { - t.Fatalf("parts missing: %v", obj) - } - if _, ok := parts["nav"]; !ok { - t.Fatalf("parts.nav missing: %v", parts) - } - if _, ok := parts["footer"]; !ok { - t.Fatalf("parts.footer missing: %v", parts) - } -} diff --git a/plugins/web/internal/db/db.go b/plugins/web/internal/db/db.go deleted file mode 100755 index 194ce78..0000000 --- a/plugins/web/internal/db/db.go +++ /dev/null @@ -1,1166 +0,0 @@ -// Package db ports minimal SQLite CRUD from the Rust web plugin (sqlite: URLs). -package db - -import ( - "database/sql" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "sync" - "time" - - "github.com/marqdo/marqdo/plugins/web/internal/table" - _ "github.com/jackc/pgx/v5/stdlib" - _ "modernc.org/sqlite" -) - -var ( - poolMu sync.Mutex - pool = map[string]*sql.DB{} -) - -// ResolveURL normalizes sqlite: paths. Absolute paths stay; relative stay as given -// (caller / host resolve cwd). Always returns a sqlite:… URL when prefixed. -func ResolveURL(url string) string { - lower := strings.ToLower(url) - if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") { - return url - } - stripped := url - prefix := "" - if strings.HasPrefix(url, "sqlite:") { - stripped = strings.TrimPrefix(url, "sqlite:") - prefix = "sqlite:" - } else if strings.HasPrefix(url, "SQLITE:") { - stripped = strings.TrimPrefix(url, "SQLITE:") - prefix = "SQLITE:" - } - if prefix == "" { - return stripped - } - return prefix + stripped -} - -func pathOf(url string) string { - u := ResolveURL(url) - if strings.HasPrefix(u, "sqlite:") { - return strings.TrimPrefix(u, "sqlite:") - } - if strings.HasPrefix(u, "SQLITE:") { - return strings.TrimPrefix(u, "SQLITE:") - } - return u -} - -func open(url string) (*sql.DB, error) { - poolMu.Lock() - defer poolMu.Unlock() - key := ResolveURL(url) - if db, ok := pool[key]; ok { - return db, nil - } - if IsPostgres(url) { - db, err := sql.Open("pgx", key) - if err != nil { - return nil, err - } - db.SetMaxOpenConns(16) - db.SetMaxIdleConns(4) - if err := db.Ping(); err != nil { - _ = db.Close() - return nil, fmt.Errorf("postgres ping: %w", err) - } - pool[key] = db - return db, nil - } - path := pathOf(url) - if parent := filepath.Dir(path); parent != "" && parent != "." { - if err := os.MkdirAll(parent, 0o755); err != nil { - return nil, err - } - } - db, err := sql.Open("sqlite", path) - if err != nil { - return nil, err - } - if _, err := db.Exec(`PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`); err != nil { - _ = db.Close() - return nil, err - } - pool[key] = db - return db, nil -} - -// OpenSQL returns a pooled *sql.DB (sqlite or postgres). Prefer OpenSQLDB when -// issuing `?` placeholders against Postgres (RBAC). -func OpenSQL(url string) (*sql.DB, error) { - return open(url) -} - -// ResetPool closes pooled connections and open transactions (tests). -func ResetPool() { - resetTxns() - poolMu.Lock() - defer poolMu.Unlock() - for k, db := range pool { - _ = db.Close() - delete(pool, k) - } -} - -func ident(s string) (string, error) { - s = strings.TrimSpace(s) - if s == "" { - return "", fmt.Errorf("bad identifier `%s`", s) - } - for _, c := range s { - if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_') { - return "", fmt.Errorf("bad identifier `%s`", s) - } - } - return s, nil -} - -func sqlType(t string) string { - switch strings.ToLower(strings.TrimSpace(t)) { - case "int", "integer": - return "INTEGER" - case "real", "float", "double": - return "REAL" - case "blob": - return "BLOB" - case "timestamp", "datetime", "timestamptz", "审计": - return "TEXT" - default: - return "TEXT" - } -} - -func sqlTypeFor(url, t string) string { - ty := sqlType(t) - if IsPostgres(url) && ty == "REAL" { - return "DOUBLE PRECISION" - } - if IsPostgres(url) && ty == "BLOB" { - return "BYTEA" - } - return ty -} - -func cellStr(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - case int: - return strconv.Itoa(t) - case int64: - return strconv.FormatInt(t, 10) - default: - return fmt.Sprint(t) - } -} - -func boolField(m map[string]any, keys []string, def bool) bool { - for _, k := range keys { - v, ok := m[k] - if !ok { - continue - } - switch t := v.(type) { - case bool: - return t - case string: - switch t { - case "true", "True", "1", "yes", "是", "可", "唯一", "索引": - return true - case "false", "False", "0", "no", "否": - return false - } - case float64: - return int64(t) != 0 - } - } - return def -} - -func parseFK(raw string) (string, string, error) { - s := strings.TrimSpace(raw) - if s == "" { - return "", "", fmt.Errorf("empty foreign key") - } - if i := strings.IndexByte(s, '('); i >= 0 { - t, err := ident(s[:i]) - if err != nil { - return "", "", err - } - col := strings.TrimSpace(strings.TrimSuffix(s[i+1:], ")")) - if col == "" { - return t, "id", nil - } - c, err := ident(col) - return t, c, err - } - if i := strings.IndexByte(s, '.'); i >= 0 { - t, err := ident(s[:i]) - if err != nil { - return "", "", err - } - c, err := ident(s[i+1:]) - return t, c, err - } - t, err := ident(s) - return t, "id", err -} - -func utcNowISO() string { - return time.Now().UTC().Format("2006-01-02T15:04:05Z") -} - -// Init creates a table from AsFields-shaped schema. -// Returns {"_type":"db_table","name":table,"url":url}. -func Init(url, name string, fields any) (map[string]any, error) { - tableName, err := ident(name) - if err != nil { - return nil, err - } - colsAny := table.AsFields(fields) - arr, ok := colsAny.([]any) - if !ok { - return nil, fmt.Errorf("fields must be a list") - } - if len(arr) == 0 { - return nil, fmt.Errorf("empty fields") - } - var parts []string - var indexSQL []string - hasPK := false - for _, c := range arr { - m, ok := c.(map[string]any) - if !ok { - continue - } - nm := cellStr(m["name"]) - if nm == "" { - nm = cellStr(m["字段"]) - } - colName, err := ident(nm) - if err != nil { - return nil, err - } - ty := cellStr(m["type"]) - if ty == "" { - ty = cellStr(m["类型"]) - } - if ty == "" { - ty = "text" - } - nullable := boolField(m, []string{"nullable", "可空"}, true) - unique := boolField(m, []string{"unique", "唯一"}, false) - index := boolField(m, []string{"index", "索引"}, false) - col := fmt.Sprintf(`"%s" %s`, colName, sqlTypeFor(url, ty)) - if colName == "id" && !hasPK { - if IsPostgres(url) && sqlType(ty) == "INTEGER" { - col = fmt.Sprintf(`"%s" INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`, colName) - } else { - col += " PRIMARY KEY" - if sqlType(ty) == "INTEGER" { - col += " AUTOINCREMENT" - } - } - hasPK = true - } else if !nullable { - col += " NOT NULL" - } - if unique && colName != "id" { - col += " UNIQUE" - } - fkRaw := cellStr(m["fk"]) - if fkRaw == "" { - fkRaw = cellStr(m["外键"]) - } - if fkRaw != "" { - rt, rc, err := parseFK(fkRaw) - if err != nil { - return nil, err - } - col += fmt.Sprintf(` REFERENCES "%s"("%s")`, rt, rc) - } - parts = append(parts, col) - if (index || unique) && colName != "id" { - kind := "" - if unique { - kind = "UNIQUE " - } - indexSQL = append(indexSQL, fmt.Sprintf( - `CREATE %sINDEX IF NOT EXISTS "idx_%s_%s" ON "%s" ("%s")`, - kind, tableName, colName, tableName, colName, - )) - } - } - sqlStmt := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS "%s" (%s)`, tableName, strings.Join(parts, ", ")) - db, err := open(url) - if err != nil { - return nil, err - } - if _, err := db.Exec(sqlStmt); err != nil { - return nil, err - } - for _, stmt := range indexSQL { - if _, err := db.Exec(stmt); err != nil { - return nil, err - } - } - return map[string]any{ - "_type": "db_table", - "name": tableName, - "url": ResolveURL(url), - }, nil -} - -func columnNames(c dbConn, tableName string, dbURL string) ([]string, error) { - if IsPostgres(dbURL) { - rows, err := c.Query(` -SELECT column_name FROM information_schema.columns -WHERE table_schema = current_schema() AND table_name = ? -ORDER BY ordinal_position`, tableName) - if err != nil { - return nil, err - } - defer rows.Close() - var out []string - for rows.Next() { - var name string - if err := rows.Scan(&name); err != nil { - return nil, err - } - out = append(out, name) - } - return out, rows.Err() - } - rows, err := c.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tableName)) - if err != nil { - return nil, err - } - defer rows.Close() - var out []string - for rows.Next() { - var cid int - var name, ctype string - var notnull, pk int - var dflt any - if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { - return nil, err - } - out = append(out, name) - } - return out, rows.Err() -} - -func toSQLArg(v any) any { - switch t := v.(type) { - case nil: - return nil - case bool: - if t { - return int64(1) - } - return int64(0) - case float64: - if t == float64(int64(t)) { - return int64(t) - } - return t - case string: - s := strings.TrimSpace(t) - if i, err := strconv.ParseInt(s, 10, 64); err == nil { - return i - } - if f, err := strconv.ParseFloat(s, 64); err == nil && strings.Contains(s, ".") && !strings.ContainsAny(s, "eE") { - return f - } - return t - case int: - return int64(t) - case int64: - return t - default: - return fmt.Sprint(t) - } -} - -func fromSQL(v any) any { - switch t := v.(type) { - case nil: - return nil - case int64: - return float64(t) // JSON numbers are float64 - case float64: - return t - case bool: - return t - case []byte: - return string(t) - case string: - return t - default: - return fmt.Sprint(t) - } -} - -// Insert inserts row maps. Returns {"ok":true,"inserted":n}. -// Optional txnID routes through an open Begin transaction. -func Insert(url, tableName string, rows any, txnID ...string) (map[string]any, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - colsPresent, err := columnNames(c, tn, url) - if err != nil { - return nil, err - } - hasCreated, hasUpdated := false, false - for _, col := range colsPresent { - if col == "created_at" { - hasCreated = true - } - if col == "updated_at" { - hasUpdated = true - } - } - normalized := table.AsRows(rows) - arr, ok := normalized.([]any) - if !ok { - return nil, fmt.Errorf("rows must be a list") - } - now := utcNowISO() - var n int64 - for _, row := range arr { - obj, ok := row.(map[string]any) - if !ok { - return nil, fmt.Errorf("row must be a map") - } - var cols, placeholders []string - var vals []any - seenCreated, seenUpdated := false, false - for k, v := range obj { - if k == "@" || k == "行" || k == "row" { - continue - } - if _, err := ident(k); err != nil { - return nil, err - } - if k == "created_at" { - seenCreated = true - } - if k == "updated_at" { - seenUpdated = true - } - cols = append(cols, `"`+k+`"`) - placeholders = append(placeholders, "?") - vals = append(vals, toSQLArg(v)) - } - if hasCreated && !seenCreated { - cols = append(cols, `"created_at"`) - placeholders = append(placeholders, "?") - vals = append(vals, now) - } - if hasUpdated && !seenUpdated { - cols = append(cols, `"updated_at"`) - placeholders = append(placeholders, "?") - vals = append(vals, now) - } - if len(cols) == 0 { - continue - } - sqlStmt := fmt.Sprintf( - `INSERT INTO "%s" (%s) VALUES (%s)`, - tn, strings.Join(cols, ", "), strings.Join(placeholders, ", "), - ) - if _, err := c.Exec(sqlStmt, vals...); err != nil { - return nil, err - } - n++ - } - return map[string]any{"ok": true, "inserted": float64(n)}, nil -} - -func skipWhereKey(k string) bool { - return k == "@" || k == "行" || k == "row" || strings.HasPrefix(k, "_") -} - -func whereOp(raw string) (string, error) { - switch strings.ToLower(strings.TrimSpace(raw)) { - case "", "=", "eq", "==", "等于": - return "=", nil - case "!=", "<>", "ne", "不等于": - return "!=", nil - case ">", "gt", "大于": - return ">", nil - case ">=", "gte", "大于等于": - return ">=", nil - case "<", "lt", "小于": - return "<", nil - case "<=", "lte", "小于等于": - return "<=", nil - case "like", "contains", "包含", "匹配": - return "LIKE", nil - case "in", "在": - return "IN", nil - case "between", "介于", "在之间": - return "BETWEEN", nil - case "is null", "isnull", "为空", "空": - return "IS NULL", nil - default: - return "", fmt.Errorf("unsupported where op `%s`", raw) - } -} - -type whereClause struct { - expr string - vals []any - or bool -} - -func inValues(v any) []any { - switch t := v.(type) { - case []any: - out := make([]any, len(t)) - for i, x := range t { - out[i] = toSQLArg(x) - } - return out - case string: - parts := strings.Split(t, ",") - out := make([]any, 0, len(parts)) - for _, p := range parts { - out = append(out, toSQLArg(strings.TrimSpace(p))) - } - return out - default: - return []any{toSQLArg(v)} - } -} - -func betweenValues(v any) ([]any, error) { - switch t := v.(type) { - case []any: - if len(t) != 2 { - return nil, fmt.Errorf(`between expects two bounds ("lo,hi" or [lo,hi])`) - } - return []any{toSQLArg(t[0]), toSQLArg(t[1])}, nil - case string: - parts := strings.SplitN(t, ",", 2) - lo, hi := "", "" - if len(parts) > 0 { - lo = strings.TrimSpace(parts[0]) - } - if len(parts) > 1 { - hi = strings.TrimSpace(parts[1]) - } - return []any{toSQLArg(lo), toSQLArg(hi)}, nil - default: - return nil, fmt.Errorf(`between expects two bounds ("lo,hi" or [lo,hi])`) - } -} - -func boolOrFlag(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - switch strings.ToLower(strings.TrimSpace(t)) { - case "1", "true", "是", "or", "或者": - return true - } - case float64: - return int64(t) != 0 - } - return false -} - -func clauseFromRow(m map[string]any) (*whereClause, error) { - field := "" - for _, k := range []string{"field", "字段", "列"} { - if v, ok := m[k]; ok { - field = cellStr(v) - break - } - } - if field == "" { - return nil, nil - } - col, err := ident(field) - if err != nil { - return nil, err - } - opRaw := "" - if v, ok := m["op"]; ok { - opRaw = cellStr(v) - } else if v, ok := m["操作"]; ok { - opRaw = cellStr(v) - } - op, err := whereOp(opRaw) - if err != nil { - return nil, err - } - var val any - if v, ok := m["value"]; ok { - val = v - } else if v, ok := m["值"]; ok { - val = v - } - or := false - if v, ok := m["or"]; ok { - or = boolOrFlag(v) - } else if v, ok := m["或"]; ok { - or = boolOrFlag(v) - } - var expr string - var vals []any - switch op { - case "IS NULL": - expr = fmt.Sprintf(`"%s" IS NULL`, col) - case "IN": - vs := inValues(val) - ph := make([]string, len(vs)) - for i := range vs { - ph[i] = "?" - } - expr = fmt.Sprintf(`"%s" IN (%s)`, col, strings.Join(ph, ", ")) - vals = vs - case "BETWEEN": - vs, err := betweenValues(val) - if err != nil { - return nil, err - } - expr = fmt.Sprintf(`"%s" BETWEEN ? AND ?`, col) - vals = vs - default: - expr = fmt.Sprintf(`"%s" %s ?`, col, op) - vals = []any{toSQLArg(val)} - } - return &whereClause{expr: expr, vals: vals, or: or}, nil -} - -// parseWhere builds AND/OR filter clauses. -// Supports: -// - equality map `{title:"Alpha", body:"first"}` → col = ? -// - filter rows `{field|字段|列, op|操作, value|值, or|或?}` -// - ops: = != > >= < <= LIKE IN BETWEEN IS NULL (+ Chinese aliases) -// - GFM columnar tables via table.AsRows -func parseWhere(where any) (exprs []string, vals []any, err error) { - if where == nil { - return nil, nil, nil - } - if s, ok := where.(string); ok { - if s == "" || strings.EqualFold(s, "none") || strings.EqualFold(s, "null") { - return nil, nil, nil - } - // Non-empty bare strings: AsRows yields []; treat as no filter (Rust parity). - } - w := table.AsRows(where) - arr, ok := w.([]any) - if !ok { - return nil, nil, fmt.Errorf("where must be a map or filter table") - } - var clauses []whereClause - for _, item := range arr { - m, ok := item.(map[string]any) - if !ok { - return nil, nil, fmt.Errorf("where must be a map or filter table") - } - field := "" - for _, k := range []string{"field", "字段", "列"} { - if v, ok := m[k]; ok { - field = cellStr(v) - break - } - } - _, hasVal := m["value"] - if !hasVal { - _, hasVal = m["值"] - } - _, hasOp := m["op"] - if !hasOp { - _, hasOp = m["操作"] - } - if field != "" && (hasVal || hasOp) { - cl, err := clauseFromRow(m) - if err != nil { - return nil, nil, err - } - if cl != nil { - clauses = append(clauses, *cl) - } - continue - } - for k, v := range m { - if skipWhereKey(k) { - continue - } - col, err := ident(k) - if err != nil { - return nil, nil, err - } - clauses = append(clauses, whereClause{ - expr: fmt.Sprintf(`"%s" = ?`, col), - vals: []any{toSQLArg(v)}, - }) - } - } - // Assemble: AND by default; OR-marked clauses join the current group. - var group []string - for _, cl := range clauses { - if cl.or { - group = append(group, cl.expr) - } else { - if len(group) > 0 { - exprs = append(exprs, "("+strings.Join(group, " OR ")+")") - group = group[:0] - } - group = append(group, cl.expr) - } - vals = append(vals, cl.vals...) - } - if len(group) > 0 { - exprs = append(exprs, "("+strings.Join(group, " OR ")+")") - } - return exprs, vals, nil -} - -func scanRows(rows *sql.Rows) ([]any, error) { - cols, err := rows.Columns() - if err != nil { - return nil, err - } - var out []any - for rows.Next() { - raw := make([]any, len(cols)) - ptrs := make([]any, len(cols)) - for i := range raw { - ptrs[i] = &raw[i] - } - if err := rows.Scan(ptrs...); err != nil { - return nil, err - } - m := map[string]any{} - for i, name := range cols { - m[name] = fromSQL(raw[i]) - } - out = append(out, m) - } - return out, rows.Err() -} - -// SelectOpts controls select_order behavior. -type SelectOpts struct { - Where any - Order string - Offset *int64 -} - -// Select runs SELECT * FROM table with optional where/order/offset. -// Without offset: {"rows":[…]}; with offset: {"rows":[…],"total":N}. -// Optional txnID routes through an open Begin transaction. -func Select(url, tableName string, limit int64, opts SelectOpts, txnID ...string) (map[string]any, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - exprs, vals, err := parseWhere(opts.Where) - if err != nil { - return nil, err - } - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - sqlStmt := fmt.Sprintf(`SELECT * FROM "%s"`, tn) - whereSQL := "" - if len(exprs) > 0 { - whereSQL = " WHERE " + strings.Join(exprs, " AND ") - sqlStmt += whereSQL - } - if order := strings.TrimSpace(opts.Order); order != "" { - parts := strings.Split(order, ",") - var orderExprs []string - for _, part := range parts { - part = strings.TrimSpace(part) - if part == "" { - continue - } - dir := "" - col := part - if strings.HasPrefix(part, "-") { - col = part[1:] - dir = " DESC" - } - cname, err := ident(col) - if err != nil { - return nil, err - } - orderExprs = append(orderExprs, fmt.Sprintf(`"%s"%s`, cname, dir)) - } - if len(orderExprs) > 0 { - sqlStmt += " ORDER BY " + strings.Join(orderExprs, ", ") - } - } - sqlStmt += " LIMIT ?" - vals = append(vals, limit) - if opts.Offset != nil && *opts.Offset > 0 { - sqlStmt += " OFFSET ?" - vals = append(vals, *opts.Offset) - } - rows, err := c.Query(sqlStmt, vals...) - if err != nil { - return nil, err - } - defer rows.Close() - list, err := scanRows(rows) - if err != nil { - return nil, err - } - if list == nil { - list = []any{} - } - if opts.Offset != nil { - countSQL := fmt.Sprintf(`SELECT COUNT(*) FROM "%s"%s`, tn, whereSQL) - _, whereOnly, _ := parseWhere(opts.Where) - var total int64 - if err := c.QueryRow(countSQL, whereOnly...).Scan(&total); err != nil { - total = int64(len(list)) - } - return map[string]any{"rows": list, "total": float64(total)}, nil - } - return map[string]any{"rows": list}, nil -} - -// Get returns one row by id, or nil (JSON null). -// Optional txnID routes through an open Begin transaction. -func Get(url, tableName, id string, txnID ...string) (any, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - sqlStmt := fmt.Sprintf(`SELECT * FROM "%s" WHERE "id" = ? LIMIT 1`, tn) - rows, err := c.Query(sqlStmt, toSQLArg(id)) - if err != nil { - return nil, err - } - defer rows.Close() - list, err := scanRows(rows) - if err != nil { - return nil, err - } - if len(list) == 0 { - return nil, nil - } - return list[0], nil -} - -func sqlArgs(args any) []any { - switch t := args.(type) { - case []any: - out := make([]any, len(t)) - for i, v := range t { - out[i] = toSQLArg(v) - } - return out - case nil: - return nil - default: - return []any{toSQLArg(t)} - } -} - -// Exec runs a non-SELECT statement. Returns {"ok":true,"changes":N}. -// Optional txnID routes through an open Begin transaction. -func Exec(url, sqlStmt string, args any, txnID ...string) (map[string]any, error) { - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - vals := sqlArgs(args) - res, err := c.Exec(sqlStmt, vals...) - if err != nil { - return nil, err - } - n, _ := res.RowsAffected() - return map[string]any{"ok": true, "changes": float64(n)}, nil -} - -// Update sets columns from row (skips id). Auto-sets updated_at when present. -// Returns {"ok":true,"updated":N}. -// Optional txnID routes through an open Begin transaction. -func Update(url, tableName, id string, row any, txnID ...string) (map[string]any, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - obj, ok := row.(map[string]any) - if !ok { - return nil, fmt.Errorf("row must be a map") - } - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - colsPresent, err := columnNames(c, tn, url) - if err != nil { - return nil, err - } - hasUpdated := false - for _, col := range colsPresent { - if col == "updated_at" { - hasUpdated = true - break - } - } - var sets []string - var vals []any - seenUpdated := false - for k, v := range obj { - if k == "id" { - continue - } - if _, err := ident(k); err != nil { - return nil, err - } - if k == "updated_at" { - seenUpdated = true - } - sets = append(sets, fmt.Sprintf(`"%s" = ?`, k)) - vals = append(vals, toSQLArg(v)) - } - if hasUpdated && !seenUpdated { - sets = append(sets, `"updated_at" = ?`) - vals = append(vals, utcNowISO()) - } - if len(sets) == 0 { - return nil, fmt.Errorf("nothing to update") - } - vals = append(vals, id) // Rust binds id as text; SQLite coerces - sqlStmt := fmt.Sprintf(`UPDATE "%s" SET %s WHERE "id" = ?`, tn, strings.Join(sets, ", ")) - res, err := c.Exec(sqlStmt, vals...) - if err != nil { - return nil, err - } - n, _ := res.RowsAffected() - return map[string]any{"ok": true, "updated": float64(n)}, nil -} - -// UpdateIf is a conditional update (CAS): SET row WHERE id=? AND expect_col=expect_val. -// Returns {"ok":true,"updated":N,"matched":N}. Callers treat updated==0 as conflict. -// Optional txnID routes through an open Begin transaction. -func UpdateIf(url, tableName, id string, row any, expectCol string, expectVal any, txnID ...string) (map[string]any, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - ecol, err := ident(expectCol) - if err != nil { - return nil, err - } - obj, ok := row.(map[string]any) - if !ok { - return nil, fmt.Errorf("row must be a map") - } - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - var sets []string - var vals []any - for k, v := range obj { - if k == "id" { - continue - } - if _, err := ident(k); err != nil { - return nil, err - } - sets = append(sets, fmt.Sprintf(`"%s" = ?`, k)) - vals = append(vals, toSQLArg(v)) - } - if len(sets) == 0 { - return nil, fmt.Errorf("nothing to update") - } - vals = append(vals, id, toSQLArg(expectVal)) - sqlStmt := fmt.Sprintf( - `UPDATE "%s" SET %s WHERE "id" = ? AND "%s" = ?`, - tn, strings.Join(sets, ", "), ecol, - ) - res, err := c.Exec(sqlStmt, vals...) - if err != nil { - return nil, err - } - n, _ := res.RowsAffected() - return map[string]any{"ok": true, "updated": float64(n), "matched": float64(n)}, nil -} - -// Delete removes a row by id. Returns {"ok":true,"deleted":N}. -// Optional txnID routes through an open Begin transaction. -func Delete(url, tableName, id string, txnID ...string) (map[string]any, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - sqlStmt := fmt.Sprintf(`DELETE FROM "%s" WHERE "id" = ?`, tn) - res, err := c.Exec(sqlStmt, id) - if err != nil { - return nil, err - } - n, _ := res.RowsAffected() - return map[string]any{"ok": true, "deleted": float64(n)}, nil -} - -// Query runs a SELECT (or any result-set SQL). Returns {"rows":[…],"count":N}. -// Optional txnID routes through an open Begin transaction. -func Query(url, sqlStmt string, args any, txnID ...string) (map[string]any, error) { - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - vals := sqlArgs(args) - rows, err := c.Query(sqlStmt, vals...) - if err != nil { - return nil, err - } - defer rows.Close() - list, err := scanRows(rows) - if err != nil { - return nil, err - } - if list == nil { - list = []any{} - } - return map[string]any{"rows": list, "count": float64(len(list))}, nil -} - -// Count returns {"count":N} for rows matching where (nil where → all). -// Optional txnID routes through an open Begin transaction. -func Count(url, tableName string, where any, txnID ...string) (map[string]any, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - exprs, vals, err := parseWhere(where) - if err != nil { - return nil, err - } - c, err := connFor(url, optTxn(txnID)) - if err != nil { - return nil, err - } - sqlStmt := fmt.Sprintf(`SELECT COUNT(*) FROM "%s"`, tn) - if len(exprs) > 0 { - sqlStmt += " WHERE " + strings.Join(exprs, " AND ") - } - var n int64 - if err := c.QueryRow(sqlStmt, vals...).Scan(&n); err != nil { - return nil, err - } - return map[string]any{"count": float64(n)}, nil -} - -// ColumnInfo is one PRAGMA table_info row (admin forms / schema introspection). -type ColumnInfo struct { - Name string - SQLType string - NotNull bool - PK bool -} - -// TableInfo returns column metadata for a table (SQLite or Postgres). -func TableInfo(url, tableName string) ([]ColumnInfo, error) { - tn, err := ident(tableName) - if err != nil { - return nil, err - } - c, err := connFor(url, "") - if err != nil { - return nil, err - } - if IsPostgres(url) { - rows, err := c.Query(` -SELECT c.column_name, c.data_type, c.is_nullable, - CASE WHEN tc.constraint_type = 'PRIMARY KEY' THEN 1 ELSE 0 END AS is_pk -FROM information_schema.columns c -LEFT JOIN information_schema.key_column_usage kcu - ON c.table_schema = kcu.table_schema AND c.table_name = kcu.table_name AND c.column_name = kcu.column_name -LEFT JOIN information_schema.table_constraints tc - ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema - AND tc.constraint_type = 'PRIMARY KEY' -WHERE c.table_schema = current_schema() AND c.table_name = ? -ORDER BY c.ordinal_position`, tn) - if err != nil { - return nil, err - } - defer rows.Close() - var out []ColumnInfo - for rows.Next() { - var name, dtype, nullable string - var pk int - if err := rows.Scan(&name, &dtype, &nullable, &pk); err != nil { - return nil, err - } - if dtype == "" { - dtype = "TEXT" - } - out = append(out, ColumnInfo{ - Name: name, - SQLType: dtype, - NotNull: strings.EqualFold(nullable, "NO"), - PK: pk != 0, - }) - } - return out, rows.Err() - } - rows, err := c.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tn)) - if err != nil { - return nil, err - } - defer rows.Close() - var out []ColumnInfo - for rows.Next() { - var cid int - var name, ctype string - var notnull, pk int - var dflt any - if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { - return nil, err - } - if ctype == "" { - ctype = "TEXT" - } - out = append(out, ColumnInfo{ - Name: name, - SQLType: ctype, - NotNull: notnull != 0, - PK: pk != 0, - }) - } - return out, rows.Err() -} diff --git a/plugins/web/internal/db/db_test.go b/plugins/web/internal/db/db_test.go deleted file mode 100755 index 3120df4..0000000 --- a/plugins/web/internal/db/db_test.go +++ /dev/null @@ -1,364 +0,0 @@ -package db_test - -import ( - "os" - "path/filepath" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/db" -) - -func setupArticles(t *testing.T) string { - t.Helper() - dir := t.TempDir() - path := filepath.Join(dir, "t.db") - url := "sqlite:" + path - t.Cleanup(db.ResetPool) - - fields := []any{ - map[string]any{"name": "id", "type": "integer", "nullable": false}, - map[string]any{"name": "title", "type": "text", "nullable": false}, - map[string]any{"name": "body", "type": "text", "nullable": true}, - map[string]any{"name": "updated_at", "type": "text", "nullable": true}, - } - if _, err := db.Init(url, "articles", fields); err != nil { - t.Fatal(err) - } - if _, err := db.Insert(url, "articles", []any{ - map[string]any{"id": float64(1), "title": "Alpha", "body": "first"}, - map[string]any{"id": float64(2), "title": "Beta", "body": "second"}, - map[string]any{"id": float64(3), "title": "Gamma", "body": "third"}, - }); err != nil { - t.Fatal(err) - } - return url -} - -func TestInitInsertSelectGet(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "t.db") - url := "sqlite:" + path - defer db.ResetPool() - - fields := []any{ - map[string]any{"name": "id", "type": "integer", "nullable": false}, - map[string]any{"name": "title", "type": "text", "nullable": false}, - map[string]any{"name": "body", "type": "text", "nullable": true}, - } - initOut, err := db.Init(url, "articles", fields) - if err != nil { - t.Fatal(err) - } - if initOut["_type"] != "db_table" || initOut["name"] != "articles" { - t.Fatalf("init=%v", initOut) - } - if _, err := os.Stat(path); err != nil { - t.Fatal(err) - } - - ins, err := db.Insert(url, "articles", []any{ - map[string]any{"id": float64(1), "title": "Hello Marqdo", "body": "First"}, - map[string]any{"id": float64(2), "title": "Two", "body": "Second"}, - }) - if err != nil { - t.Fatal(err) - } - if ins["ok"] != true || ins["inserted"] != float64(2) { - t.Fatalf("insert=%v", ins) - } - - sel, err := db.Select(url, "articles", 10, db.SelectOpts{}) - if err != nil { - t.Fatal(err) - } - rows, ok := sel["rows"].([]any) - if !ok || len(rows) != 2 { - t.Fatalf("select=%v", sel) - } - if _, hasTotal := sel["total"]; hasTotal { - t.Fatalf("unexpected total without offset: %v", sel) - } - - got, err := db.Get(url, "articles", "1") - if err != nil { - t.Fatal(err) - } - m, ok := got.(map[string]any) - if !ok { - t.Fatalf("get=%v", got) - } - if m["title"] != "Hello Marqdo" { - t.Fatalf("title=%v", m["title"]) - } - - miss, err := db.Get(url, "articles", "999") - if err != nil { - t.Fatal(err) - } - if miss != nil { - t.Fatalf("expected null, got %v", miss) - } -} - -func TestUpdateIfCAS(t *testing.T) { - url := setupArticles(t) - ok, err := db.UpdateIf(url, "articles", "1", map[string]any{"title": "CAS"}, "title", "Alpha") - if err != nil { - t.Fatal(err) - } - if ok["updated"] != float64(1) { - t.Fatalf("cas hit=%v", ok) - } - miss, err := db.UpdateIf(url, "articles", "1", map[string]any{"title": "Nope"}, "title", "Alpha") - if err != nil { - t.Fatal(err) - } - if miss["updated"] != float64(0) { - t.Fatalf("cas miss should be 0, got %v", miss) - } -} - -func TestUpdateDelete(t *testing.T) { - url := setupArticles(t) - - up, err := db.Update(url, "articles", "1", map[string]any{"title": "Alpha2", "body": "updated"}) - if err != nil { - t.Fatal(err) - } - if up["ok"] != true || up["updated"] != float64(1) { - t.Fatalf("update=%v", up) - } - got, err := db.Get(url, "articles", "1") - if err != nil { - t.Fatal(err) - } - m := got.(map[string]any) - if m["title"] != "Alpha2" { - t.Fatalf("title=%v", m["title"]) - } - if ua, _ := m["updated_at"].(string); ua == "" { - t.Fatalf("expected auto updated_at, got %v", m["updated_at"]) - } - - del, err := db.Delete(url, "articles", "2") - if err != nil { - t.Fatal(err) - } - if del["ok"] != true || del["deleted"] != float64(1) { - t.Fatalf("delete=%v", del) - } - miss, err := db.Get(url, "articles", "2") - if err != nil { - t.Fatal(err) - } - if miss != nil { - t.Fatalf("expected deleted, got %v", miss) - } -} - -func TestQueryAndCount(t *testing.T) { - url := setupArticles(t) - - q, err := db.Query(url, `SELECT title FROM "articles" WHERE "id" = ?`, []any{"1"}) - if err != nil { - t.Fatal(err) - } - if q["count"] != float64(1) { - t.Fatalf("query=%v", q) - } - rows := q["rows"].([]any) - if rows[0].(map[string]any)["title"] != "Alpha" { - t.Fatalf("rows=%v", rows) - } - - all, err := db.Count(url, "articles", nil) - if err != nil { - t.Fatal(err) - } - if all["count"] != float64(3) { - t.Fatalf("count all=%v", all) - } - - eq, err := db.Count(url, "articles", map[string]any{"title": "Alpha", "body": "first"}) - if err != nil { - t.Fatal(err) - } - if eq["count"] != float64(1) { - t.Fatalf("equality where count=%v", eq) - } - - filt, err := db.Count(url, "articles", []any{ - map[string]any{"字段": "title", "操作": "=", "值": "Beta"}, - }) - if err != nil { - t.Fatal(err) - } - if filt["count"] != float64(1) { - t.Fatalf("filter table count=%v", filt) - } - - like, err := db.Select(url, "articles", 10, db.SelectOpts{ - Where: []any{ - map[string]any{"field": "title", "op": "like", "value": "A%"}, - }, - }) - if err != nil { - t.Fatal(err) - } - if len(like["rows"].([]any)) != 1 { - t.Fatalf("like=%v", like) - } -} - -func TestTxnCommitRollback(t *testing.T) { - url := setupArticles(t) - - begin, err := db.Begin(url) - if err != nil { - t.Fatal(err) - } - if begin["_type"] != "txn" { - t.Fatalf("begin=%v", begin) - } - tid, _ := begin["txn"].(string) - if tid == "" { - t.Fatalf("missing txn id: %v", begin) - } - if begin["事务"] != tid || begin["地址"] != begin["url"] { - t.Fatalf("bilingual keys: %v", begin) - } - - if _, err := db.Insert(url, "articles", []any{ - map[string]any{"id": float64(99), "title": "TxnRow", "body": "in-txn"}, - }, tid); err != nil { - t.Fatal(err) - } - // Visible inside the transaction. - inside, err := db.Count(url, "articles", nil, tid) - if err != nil { - t.Fatal(err) - } - if inside["count"] != float64(4) { - t.Fatalf("in-txn count=%v", inside) - } - if _, err := db.Commit(tid); err != nil { - t.Fatal(err) - } - after, err := db.Count(url, "articles", nil) - if err != nil { - t.Fatal(err) - } - if after["count"] != float64(4) { - t.Fatalf("after commit count=%v", after) - } - - begin2, err := db.Begin(url) - if err != nil { - t.Fatal(err) - } - tid2 := begin2["txn"].(string) - if _, err := db.Insert(url, "articles", []any{ - map[string]any{"id": float64(100), "title": "Zeta", "body": "rolled"}, - }, tid2); err != nil { - t.Fatal(err) - } - if _, err := db.Rollback(tid2); err != nil { - t.Fatal(err) - } - final, err := db.Count(url, "articles", nil) - if err != nil { - t.Fatal(err) - } - if final["count"] != float64(4) { - t.Fatalf("after rollback count=%v", final) - } - miss, err := db.Get(url, "articles", "100") - if err != nil { - t.Fatal(err) - } - if miss != nil { - t.Fatalf("expected rolled-back row absent, got %v", miss) - } -} - -func TestMigrate(t *testing.T) { - dir := t.TempDir() - url := "sqlite:" + filepath.Join(dir, "m.db") - defer db.ResetPool() - - steps := []any{ - map[string]any{ - "版本": float64(1), - "SQL": `CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT, status TEXT NOT NULL DEFAULT 'draft')`, - }, - map[string]any{ - "版本": float64(2), - "SQL": `CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY AUTOINCREMENT, post_id INTEGER NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending')`, - }, - } - m1, err := db.Migrate(url, steps) - if err != nil { - t.Fatal(err) - } - if m1["ok"] != true || m1["from"] != float64(0) || m1["to"] != float64(2) { - t.Fatalf("migrate1=%v", m1) - } - applied, ok := m1["applied"].([]any) - if !ok || len(applied) != 2 { - t.Fatalf("applied=%v", m1["applied"]) - } - - m2, err := db.Migrate(url, steps) - if err != nil { - t.Fatal(err) - } - applied2 := m2["applied"].([]any) - if len(applied2) != 0 || m2["from"] != float64(2) || m2["to"] != float64(2) { - t.Fatalf("idempotent migrate=%v", m2) - } -} - -func TestFtsCreateSearch(t *testing.T) { - dir := t.TempDir() - url := "sqlite:" + filepath.Join(dir, "fts.db") - defer db.ResetPool() - - steps := []any{ - map[string]any{ - "version": float64(1), - "sql": `CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT, status TEXT NOT NULL DEFAULT 'draft')`, - }, - } - if _, err := db.Migrate(url, steps); err != nil { - t.Fatal(err) - } - if _, err := db.Insert(url, "posts", []any{ - map[string]any{"title": "Alpha note", "body": "hello world search", "status": "published"}, - map[string]any{"title": "Beta draft", "body": "secret draft body", "status": "draft"}, - map[string]any{"title": "Gamma published", "body": "another hello", "status": "published"}, - }); err != nil { - t.Fatal(err) - } - - fts, err := db.FtsCreate(url, "posts", "title,body", "") - if err != nil { - t.Fatal(err) - } - if fts["ok"] != true || fts["fts"] != "posts_fts" { - t.Fatalf("fts=%v", fts) - } - - hit, err := db.Search(url, "posts", "hello", 10, "") - if err != nil { - t.Fatal(err) - } - n, _ := hit["count"].(float64) - if n < 1 { - t.Fatalf("search=%v", hit) - } - rows := hit["rows"].([]any) - first := rows[0].(map[string]any) - if cell, _ := first["title"].(string); cell == "" { - t.Fatalf("expected title on FTS row: %v", first) - } -} diff --git a/plugins/web/internal/db/dialect.go b/plugins/web/internal/db/dialect.go deleted file mode 100755 index 039bfcb..0000000 --- a/plugins/web/internal/db/dialect.go +++ /dev/null @@ -1,144 +0,0 @@ -package db - -import ( - "database/sql" - "strings" -) - -// IsPostgres reports whether url selects the Postgres backend. -func IsPostgres(url string) bool { - lower := strings.ToLower(strings.TrimSpace(url)) - return strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") -} - -// RewritePlaceholdersPG turns `?` into `$1,$2,…` for Postgres. -func RewritePlaceholdersPG(sqlStmt string) string { - var b strings.Builder - b.Grow(len(sqlStmt) + 8) - n := 0 - for _, c := range sqlStmt { - if c == '?' { - n++ - b.WriteByte('$') - b.WriteString(itoa(n)) - } else { - b.WriteRune(c) - } - } - return b.String() -} - -func itoa(n int) string { - // small positive ints only - if n < 10 { - return string(rune('0' + n)) - } - var buf [12]byte - i := len(buf) - for n > 0 { - i-- - buf[i] = byte('0' + n%10) - n /= 10 - } - return string(buf[i:]) -} - -// rewritingDB rewrites `?` placeholders when talking to Postgres. -type rewritingDB struct { - db *sql.DB - pg bool -} - -func (d *rewritingDB) Exec(query string, args ...any) (sql.Result, error) { - if d.pg { - query = RewritePlaceholdersPG(query) - } - return d.db.Exec(query, args...) -} - -func (d *rewritingDB) Query(query string, args ...any) (*sql.Rows, error) { - if d.pg { - query = RewritePlaceholdersPG(query) - } - return d.db.Query(query, args...) -} - -func (d *rewritingDB) QueryRow(query string, args ...any) *sql.Row { - if d.pg { - query = RewritePlaceholdersPG(query) - } - return d.db.QueryRow(query, args...) -} - -func (d *rewritingDB) Begin() (*sql.Tx, error) { - return d.db.Begin() -} - -func (d *rewritingDB) Underlying() *sql.DB { return d.db } - -type rewritingTx struct { - tx *sql.Tx - pg bool -} - -func (t *rewritingTx) Exec(query string, args ...any) (sql.Result, error) { - if t.pg { - query = RewritePlaceholdersPG(query) - } - return t.tx.Exec(query, args...) -} - -func (t *rewritingTx) Query(query string, args ...any) (*sql.Rows, error) { - if t.pg { - query = RewritePlaceholdersPG(query) - } - return t.tx.Query(query, args...) -} - -func (t *rewritingTx) QueryRow(query string, args ...any) *sql.Row { - if t.pg { - query = RewritePlaceholdersPG(query) - } - return t.tx.QueryRow(query, args...) -} - -func (t *rewritingTx) Commit() error { return t.tx.Commit() } -func (t *rewritingTx) Rollback() error { return t.tx.Rollback() } - -// SQLDB is *sql.DB with optional Postgres `?` rewrite (RBAC / admin). -type SQLDB interface { - Exec(query string, args ...any) (sql.Result, error) - Query(query string, args ...any) (*sql.Rows, error) - QueryRow(query string, args ...any) *sql.Row - Begin() (SQLTx, error) -} - -// SQLTx is a transaction with optional placeholder rewrite. -type SQLTx interface { - Exec(query string, args ...any) (sql.Result, error) - Query(query string, args ...any) (*sql.Rows, error) - QueryRow(query string, args ...any) *sql.Row - Commit() error - Rollback() error -} - -type sqlDBHandle struct { - *rewritingDB -} - -func (h *sqlDBHandle) Begin() (SQLTx, error) { - tx, err := h.rewritingDB.Begin() - if err != nil { - return nil, err - } - return &rewritingTx{tx: tx, pg: h.pg}, nil -} - -// OpenSQLDB returns a pooled handle that rewrites `?` on Postgres. -func OpenSQLDB(url string) (SQLDB, error) { - raw, err := open(url) - if err != nil { - return nil, err - } - return &sqlDBHandle{rewritingDB: &rewritingDB{db: raw, pg: IsPostgres(url)}}, nil -} diff --git a/plugins/web/internal/db/fts.go b/plugins/web/internal/db/fts.go deleted file mode 100755 index c5d1896..0000000 --- a/plugins/web/internal/db/fts.go +++ /dev/null @@ -1,242 +0,0 @@ -package db - -import ( - "fmt" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -func parseColumnList(columns any) ([]string, error) { - switch t := columns.(type) { - case string: - parts := strings.Split(t, ",") - var cols []string - for _, p := range parts { - p = strings.TrimSpace(p) - if p == "" { - continue - } - if _, err := ident(p); err != nil { - return nil, err - } - cols = append(cols, p) - } - if len(cols) == 0 { - return nil, fmt.Errorf("fts columns is empty") - } - return cols, nil - case []any: - var cols []string - for _, v := range t { - name := cellStr(v) - if _, err := ident(name); err != nil { - return nil, err - } - cols = append(cols, name) - } - if len(cols) == 0 { - return nil, fmt.Errorf("fts columns is empty") - } - return cols, nil - case map[string]any: - rows := table.AsRows(columns) - arr, ok := rows.([]any) - if !ok { - return nil, fmt.Errorf("fts columns must be a list or CSV string") - } - var cols []string - for _, row := range arr { - if obj, ok := row.(map[string]any); ok { - name := "" - for _, k := range []string{"name", "字段", "column"} { - if v, ok := obj[k]; ok { - name = cellStr(v) - break - } - } - if name == "" { - for _, v := range obj { - name = cellStr(v) - break - } - } - if name != "" { - if _, err := ident(name); err != nil { - return nil, err - } - cols = append(cols, name) - } - } else { - name := cellStr(row) - if name != "" { - if _, err := ident(name); err != nil { - return nil, err - } - cols = append(cols, name) - } - } - } - if len(cols) == 0 { - return nil, fmt.Errorf("fts columns is empty") - } - return cols, nil - case nil: - return nil, fmt.Errorf("fts columns is empty") - default: - return nil, fmt.Errorf("fts columns must be a list or CSV string") - } -} - -func ftsName(tableName string, name string) (string, error) { - name = strings.TrimSpace(name) - if name == "" { - return tableName + "_fts", nil - } - return ident(name) -} - -// FtsCreate builds an FTS5 virtual table synced via content= + triggers. -// Returns {"ok":true,"table":…,"fts":…,"columns":[…]}. -func FtsCreate(url, tableName string, columns any, name string) (map[string]any, error) { - lower := strings.ToLower(ResolveURL(url)) - if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") { - return nil, fmt.Errorf("db.fts is SQLite-only in this wave") - } - tn, err := ident(tableName) - if err != nil { - return nil, err - } - cols, err := parseColumnList(columns) - if err != nil { - return nil, err - } - fts, err := ftsName(tn, name) - if err != nil { - return nil, err - } - quoted := make([]string, len(cols)) - for i, c := range cols { - quoted[i] = `"` + c + `"` - } - colSQL := strings.Join(quoted, ", ") - - db, err := open(url) - if err != nil { - return nil, err - } - create := fmt.Sprintf( - `CREATE VIRTUAL TABLE IF NOT EXISTS "%s" USING fts5(%s, content="%s", content_rowid="id")`, - fts, colSQL, tn, - ) - if _, err := db.Exec(create); err != nil { - return nil, err - } - - ai, ad, au := fts+"_ai", fts+"_ad", fts+"_au" - for _, trg := range []string{ai, ad, au} { - if _, err := db.Exec(fmt.Sprintf(`DROP TRIGGER IF EXISTS "%s"`, trg)); err != nil { - return nil, err - } - } - - newCols := make([]string, len(cols)) - oldCols := make([]string, len(cols)) - for i, c := range cols { - newCols[i] = `new."` + c + `"` - oldCols[i] = `old."` + c + `"` - } - newSQL := strings.Join(newCols, ", ") - oldSQL := strings.Join(oldCols, ", ") - - aiSQL := fmt.Sprintf( - `CREATE TRIGGER "%s" AFTER INSERT ON "%s" BEGIN - INSERT INTO "%s"(rowid, %s) VALUES (new.id, %s); - END`, - ai, tn, fts, colSQL, newSQL, - ) - adSQL := fmt.Sprintf( - `CREATE TRIGGER "%s" AFTER DELETE ON "%s" BEGIN - INSERT INTO "%s"("%s", rowid, %s) VALUES('delete', old.id, %s); - END`, - ad, tn, fts, fts, colSQL, oldSQL, - ) - auSQL := fmt.Sprintf( - `CREATE TRIGGER "%s" AFTER UPDATE ON "%s" BEGIN - INSERT INTO "%s"("%s", rowid, %s) VALUES('delete', old.id, %s); - INSERT INTO "%s"(rowid, %s) VALUES (new.id, %s); - END`, - au, tn, fts, fts, colSQL, oldSQL, fts, colSQL, newSQL, - ) - for _, stmt := range []string{aiSQL, adSQL, auSQL} { - if _, err := db.Exec(stmt); err != nil { - return nil, err - } - } - if _, err := db.Exec(fmt.Sprintf(`INSERT INTO "%s"("%s") VALUES('rebuild')`, fts, fts)); err != nil { - return nil, err - } - - colAny := make([]any, len(cols)) - for i, c := range cols { - colAny[i] = c - } - return map[string]any{ - "ok": true, - "table": tn, - "fts": fts, - "columns": colAny, - }, nil -} - -// Search runs FTS5 MATCH against a table created by FtsCreate. -// Returns {"rows":[…],"count":N}. -func Search(url, tableName, q string, limit int64, name string) (map[string]any, error) { - lower := strings.ToLower(ResolveURL(url)) - if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") { - return nil, fmt.Errorf("db.search is SQLite-only in this wave") - } - tn, err := ident(tableName) - if err != nil { - return nil, err - } - fts, err := ftsName(tn, name) - if err != nil { - return nil, err - } - q = strings.TrimSpace(q) - if q == "" { - return map[string]any{"rows": []any{}, "count": float64(0)}, nil - } - if limit <= 0 { - limit = 20 - } else if limit > 500 { - limit = 500 - } - sqlStmt := fmt.Sprintf( - `SELECT t.*, bm25("%s") AS rank - FROM "%s" - JOIN "%s" t ON t.id = "%s".rowid - WHERE "%s" MATCH ? - ORDER BY rank - LIMIT ?`, - fts, fts, tn, fts, fts, - ) - db, err := open(url) - if err != nil { - return nil, err - } - rows, err := db.Query(sqlStmt, q, limit) - if err != nil { - return nil, err - } - defer rows.Close() - list, err := scanRows(rows) - if err != nil { - return nil, err - } - if list == nil { - list = []any{} - } - return map[string]any{"rows": list, "count": float64(len(list))}, nil -} diff --git a/plugins/web/internal/db/migrate.go b/plugins/web/internal/db/migrate.go deleted file mode 100755 index 5686694..0000000 --- a/plugins/web/internal/db/migrate.go +++ /dev/null @@ -1,174 +0,0 @@ -package db - -import ( - "fmt" - "strconv" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// Migrate applies versioned SQL steps (SQLite only). -// steps: list of {version|版本|ver, sql|SQL} maps (GFM columnar via AsRows). -// Returns {"ok":true,"from":N,"to":M,"applied":[…]}. -func Migrate(url string, steps any) (map[string]any, error) { - lower := strings.ToLower(ResolveURL(url)) - if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") { - return nil, fmt.Errorf("db.migrate is SQLite-only in this wave (use postgres migration tooling)") - } - - normalized := table.AsRows(steps) - arr, ok := normalized.([]any) - if !ok { - return nil, fmt.Errorf("migrate steps must be a list") - } - - type step struct { - version int64 - sql string - } - var parsed []step - for _, row := range arr { - // Bare SQL string → treat as sequential versions later if needed; - // Rust requires maps; also accept plain SQL strings with auto version. - if s, ok := row.(string); ok { - s = strings.TrimSpace(s) - if s == "" { - return nil, fmt.Errorf("migrate step has empty SQL") - } - parsed = append(parsed, step{version: 0, sql: s}) // version filled below - continue - } - obj, ok := row.(map[string]any) - if !ok { - return nil, fmt.Errorf("migrate step must be a map") - } - var ver any - for _, k := range []string{"version", "版本", "ver"} { - if v, ok := obj[k]; ok { - ver = v - break - } - } - if ver == nil { - return nil, fmt.Errorf("migrate step missing `version`/`版本`") - } - version, err := migrateVersion(ver) - if err != nil { - return nil, err - } - if version <= 0 { - return nil, fmt.Errorf("migrate version must be positive, got %d", version) - } - sqlStmt := "" - for _, k := range []string{"sql", "SQL", "Sql"} { - if v, ok := obj[k]; ok { - sqlStmt = cellStr(v) - break - } - } - if strings.TrimSpace(sqlStmt) == "" { - return nil, fmt.Errorf("migrate version %d has empty SQL", version) - } - parsed = append(parsed, step{version: version, sql: sqlStmt}) - } - - // Auto-number bare SQL strings (1-based in list order among string-only steps, - // or continue after max explicit version when mixed — prefer Rust map path). - var auto int64 - for i := range parsed { - if parsed[i].version == 0 { - auto++ - parsed[i].version = auto - } else if parsed[i].version > auto { - auto = parsed[i].version - } - } - - // Sort by version (stable insertion sort). - for i := 1; i < len(parsed); i++ { - j := i - for j > 0 && parsed[j-1].version > parsed[j].version { - parsed[j-1], parsed[j] = parsed[j], parsed[j-1] - j-- - } - } - for i := 1; i < len(parsed); i++ { - if parsed[i-1].version == parsed[i].version { - return nil, fmt.Errorf("duplicate migrate version %d", parsed[i].version) - } - } - - db, err := open(url) - if err != nil { - return nil, err - } - if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS "_marqdo_migrations" ( - version INTEGER PRIMARY KEY, - applied_at TEXT NOT NULL - )`); err != nil { - return nil, err - } - var current int64 - if err := db.QueryRow(`SELECT COALESCE(MAX(version), 0) FROM "_marqdo_migrations"`).Scan(¤t); err != nil { - current = 0 - } - - var applied []any - for _, st := range parsed { - if st.version <= current { - continue - } - tx, err := db.Begin() - if err != nil { - return nil, err - } - if _, err := tx.Exec(st.sql); err != nil { - _ = tx.Rollback() - return nil, fmt.Errorf("migrate version %d failed: %w", st.version, err) - } - if _, err := tx.Exec( - `INSERT INTO "_marqdo_migrations" (version, applied_at) VALUES (?, datetime('now'))`, - st.version, - ); err != nil { - _ = tx.Rollback() - return nil, err - } - if err := tx.Commit(); err != nil { - return nil, err - } - applied = append(applied, float64(st.version)) - } - if applied == nil { - applied = []any{} - } - to := current - if len(applied) > 0 { - to = int64(applied[len(applied)-1].(float64)) - } - return map[string]any{ - "ok": true, - "from": float64(current), - "to": float64(to), - "applied": applied, - }, nil -} - -func migrateVersion(ver any) (int64, error) { - switch t := ver.(type) { - case float64: - return int64(t), nil - case int64: - return t, nil - case int: - return int64(t), nil - case string: - n, err := strconv.ParseInt(strings.TrimSpace(t), 10, 64) - if err != nil { - return 0, fmt.Errorf("bad migrate version `%s`", t) - } - return n, nil - default: - return 0, fmt.Errorf("migrate version must be an integer") - } -} diff --git a/plugins/web/internal/db/txn.go b/plugins/web/internal/db/txn.go deleted file mode 100755 index 7666c48..0000000 --- a/plugins/web/internal/db/txn.go +++ /dev/null @@ -1,171 +0,0 @@ -package db - -import ( - "context" - "database/sql" - "fmt" - "os" - "sync" - "sync/atomic" - "time" -) - -// dbConn is *sql.DB or a transaction-bound *sql.Conn. -type dbConn interface { - Exec(query string, args ...any) (sql.Result, error) - Query(query string, args ...any) (*sql.Rows, error) - QueryRow(query string, args ...any) *sql.Row -} - -type txnConn struct { - conn *sql.Conn - url string -} - -func (t *txnConn) Exec(query string, args ...any) (sql.Result, error) { - if IsPostgres(t.url) { - query = RewritePlaceholdersPG(query) - } - return t.conn.ExecContext(context.Background(), query, args...) -} - -func (t *txnConn) Query(query string, args ...any) (*sql.Rows, error) { - if IsPostgres(t.url) { - query = RewritePlaceholdersPG(query) - } - return t.conn.QueryContext(context.Background(), query, args...) -} - -func (t *txnConn) QueryRow(query string, args ...any) *sql.Row { - if IsPostgres(t.url) { - query = RewritePlaceholdersPG(query) - } - return t.conn.QueryRowContext(context.Background(), query, args...) -} - -var ( - txnsMu sync.Mutex - txns = map[string]*txnConn{} - txnSeq atomic.Uint64 - txnSeedM sync.Mutex - txnSeed = uint64(0x243f_6a88_85a3_08d3) -) - -func nextTxnID() string { - nanos := time.Now().UnixNano() & 0xffffffff - pid := os.Getpid() - txnSeedM.Lock() - x := txnSeed - x ^= x << 13 - x ^= x >> 7 - x ^= x << 17 - txnSeed = x - txnSeedM.Unlock() - n := txnSeq.Add(1) - return fmt.Sprintf("txn-%x%x%x%x", pid, nanos, x, n) -} - -func optTxn(txnID []string) string { - if len(txnID) == 0 { - return "" - } - return txnID[0] -} - -// connFor returns the pooled DB or an active transaction connection. -func connFor(url, txnID string) (dbConn, error) { - if txnID != "" { - txnsMu.Lock() - defer txnsMu.Unlock() - t, ok := txns[txnID] - if !ok { - return nil, fmt.Errorf("unknown transaction `%s`", txnID) - } - return t, nil - } - raw, err := open(url) - if err != nil { - return nil, err - } - return &rewritingDB{db: raw, pg: IsPostgres(url)}, nil -} - -func takeTxn(txnID string) (*txnConn, error) { - txnsMu.Lock() - defer txnsMu.Unlock() - t, ok := txns[txnID] - if !ok { - return nil, fmt.Errorf("unknown transaction `%s`", txnID) - } - delete(txns, txnID) - return t, nil -} - -func resetTxns() { - txnsMu.Lock() - defer txnsMu.Unlock() - for id, t := range txns { - _, _ = t.conn.ExecContext(context.Background(), "ROLLBACK") - _ = t.conn.Close() - delete(txns, id) - } -} - -// Begin starts a transaction (BEGIN IMMEDIATE on SQLite, BEGIN on Postgres). -// Returns {"_type":"txn","txn":id,"url":url,"事务":id,"地址":url}. -func Begin(url string) (map[string]any, error) { - db, err := open(url) - if err != nil { - return nil, err - } - conn, err := db.Conn(context.Background()) - if err != nil { - return nil, err - } - beginSQL := "BEGIN IMMEDIATE" - if IsPostgres(url) { - beginSQL = "BEGIN" - } - if _, err := conn.ExecContext(context.Background(), beginSQL); err != nil { - _ = conn.Close() - return nil, err - } - id := nextTxnID() - resolved := ResolveURL(url) - txnsMu.Lock() - txns[id] = &txnConn{conn: conn, url: resolved} - txnsMu.Unlock() - return map[string]any{ - "_type": "txn", - "txn": id, - "url": resolved, - "事务": id, - "地址": resolved, - }, nil -} - -// Commit commits a transaction. Returns {"ok":true}. -func Commit(txnID string) (map[string]any, error) { - t, err := takeTxn(txnID) - if err != nil { - return nil, err - } - defer t.conn.Close() - if _, err := t.conn.ExecContext(context.Background(), "COMMIT"); err != nil { - return nil, err - } - return map[string]any{"ok": true}, nil -} - -// Rollback rolls back a transaction. Returns {"ok":true}. -func Rollback(txnID string) (map[string]any, error) { - t, err := takeTxn(txnID) - if err != nil { - return nil, err - } - defer t.conn.Close() - if _, err := t.conn.ExecContext(context.Background(), "ROLLBACK"); err != nil { - return nil, err - } - return map[string]any{"ok": true}, nil -} diff --git a/plugins/web/internal/form/form.go b/plugins/web/internal/form/form.go deleted file mode 100755 index fe1cdf1..0000000 --- a/plugins/web/internal/form/form.go +++ /dev/null @@ -1,967 +0,0 @@ -// Package form ports form fields / validate / render / submit (design §5.5, W-G3). -package form - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" - "unicode/utf8" - - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -var ( - fieldKeys = []string{"字段", "name", "field", "列"} - labelKeys = []string{"标签", "label"} - typeKeys = []string{"类型", "type"} - reqKeys = []string{"必填", "required"} - defKeys = []string{"默认", "default"} - sourceKeys = []string{"来源", "source"} - ruleFieldKeys = []string{"字段", "field", "name"} - ruleKeys = []string{"规则", "rule"} - msgKeys = []string{"消息", "message", "msg"} -) - -// New matches Rust form_new. -func New(tableName, action, id string) map[string]any { - action = normalizeAction(action) - out := map[string]any{ - "_type": "form", - "action": action, - "fields": []any{}, - "rules": []any{}, - "redirect": "/", - } - if tableName != "" { - out["table"] = tableName - } - if id != "" { - out["id"] = id - } - return out -} - -func normalizeAction(action string) string { - switch action { - case "update", "更新": - return "update" - case "delete", "删除": - return "delete" - case "": - return "insert" - default: - return "insert" - } -} - -// SetFields attaches normalized field rows to the form bag. -func SetFields(formBag map[string]any, fields any) map[string]any { - out := cloneMap(formBag) - out["fields"] = asFormFields(fields) - return out -} - -// SetRules attaches normalized rule rows to the form bag. -func SetRules(formBag map[string]any, rules any) map[string]any { - out := cloneMap(formBag) - out["rules"] = asFormRules(rules) - return out -} - -// SetLabels stamps localized submit / cancel button copy (and optional cancel href). -// When cancelHref is set, also stamps redirect so successful POST lands on the list -// (or other cancel target) instead of the composing page's _mq_return path. -func SetLabels(formBag map[string]any, submit, cancel, cancelHref string) map[string]any { - out := cloneMap(formBag) - if s := strings.TrimSpace(submit); s != "" { - out["submit"] = s - } - if s := strings.TrimSpace(cancel); s != "" { - out["cancel"] = s - } - if s := strings.TrimSpace(cancelHref); s != "" { - out["cancel_href"] = s - out["redirect"] = s - } - return out -} - -func cloneMap(m map[string]any) map[string]any { - out := map[string]any{} - for k, v := range m { - out[k] = v - } - return out -} - -func cellStr(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - case int: - return strconv.Itoa(t) - case int64: - return strconv.FormatInt(t, 10) - default: - return fmt.Sprint(t) - } -} - -func asStrList(v any) []string { - switch t := v.(type) { - case nil: - return nil - case []any: - out := make([]string, len(t)) - for i, x := range t { - out[i] = cellStr(x) - } - return out - default: - return []string{cellStr(v)} - } -} - -func pick(m map[string]any, keys []string) (any, bool) { - for _, k := range keys { - if v, ok := m[k]; ok { - return v, true - } - } - return nil, false -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - s := strings.TrimSpace(t) - switch s { - case "1", "true", "True", "yes", "是", "必填", "required", "可": - return true - } - case float64: - return t != 0 - case int: - return t != 0 - case int64: - return t != 0 - } - return false -} - -func asFormFields(fields any) []any { - switch t := fields.(type) { - case []any: - var out []any - for _, row := range t { - m, ok := row.(map[string]any) - if !ok { - continue - } - nameRaw := "" - if v, ok := pick(m, fieldKeys); ok { - nameRaw = cellStr(v) - } - name := table.NormalizeRef(nameRaw) - if name == "" { - continue - } - label := name - if v, ok := pick(m, labelKeys); ok { - if s := cellStr(v); s != "" { - label = s - } - } - ty := "text" - if v, ok := pick(m, typeKeys); ok { - if s := cellStr(v); s != "" { - ty = s - } - } - required := false - if v, ok := pick(m, reqKeys); ok { - required = boolish(v) - } - def := "" - if v, ok := pick(m, defKeys); ok { - def = cellStr(v) - } - source := "client" - if v, ok := pick(m, sourceKeys); ok { - if s := strings.TrimSpace(cellStr(v)); s != "" { - source = s - } - } - item := map[string]any{ - "name": name, - "label": label, - "type": ty, - "required": required, - "default": def, - "source": normalizeSource(source), - } - if v, ok := m["pk"]; ok { - item["pk"] = boolish(v) - } - out = append(out, item) - } - return out - case map[string]any: - names := []string{} - if v, ok := pick(t, fieldKeys); ok { - names = asStrList(v) - } - labels := []string{} - if v, ok := pick(t, labelKeys); ok { - labels = asStrList(v) - } - types := []string{} - if v, ok := pick(t, typeKeys); ok { - types = asStrList(v) - } - reqs := []string{} - if v, ok := pick(t, reqKeys); ok { - reqs = asStrList(v) - } - defs := []string{} - if v, ok := pick(t, defKeys); ok { - defs = asStrList(v) - } - sources := []string{} - if v, ok := pick(t, sourceKeys); ok { - sources = asStrList(v) - } - var out []any - for i, nameRaw := range names { - name := table.NormalizeRef(nameRaw) - if name == "" { - continue - } - label := name - if i < len(labels) && labels[i] != "" { - label = labels[i] - } - ty := "text" - if i < len(types) && types[i] != "" { - ty = types[i] - } - required := false - if i < len(reqs) { - required = boolish(reqs[i]) - } - def := "" - if i < len(defs) { - def = defs[i] - } - source := "client" - if i < len(sources) && strings.TrimSpace(sources[i]) != "" { - source = sources[i] - } - out = append(out, map[string]any{ - "name": name, - "label": label, - "type": ty, - "required": required, - "default": def, - "source": normalizeSource(source), - }) - } - return out - default: - return []any{} - } -} - -func asFormRules(rules any) []any { - switch t := rules.(type) { - case []any: - var out []any - for _, row := range t { - m, ok := row.(map[string]any) - if !ok { - continue - } - fieldRaw := "" - if v, ok := pick(m, ruleFieldKeys); ok { - fieldRaw = cellStr(v) - } - field := table.NormalizeRef(fieldRaw) - rule := "" - if v, ok := pick(m, ruleKeys); ok { - rule = cellStr(v) - } - if field == "" || rule == "" { - continue - } - msg := "" - if v, ok := pick(m, msgKeys); ok { - msg = cellStr(v) - } - out = append(out, map[string]any{ - "field": field, - "rule": rule, - "message": msg, - }) - } - return out - case map[string]any: - fields := []string{} - if v, ok := pick(t, ruleFieldKeys); ok { - fields = asStrList(v) - } - ruleList := []string{} - if v, ok := pick(t, ruleKeys); ok { - ruleList = asStrList(v) - } - msgs := []string{} - if v, ok := pick(t, msgKeys); ok { - msgs = asStrList(v) - } - n := len(fields) - if len(ruleList) > n { - n = len(ruleList) - } - var out []any - for i := 0; i < n; i++ { - field := "" - if i < len(fields) { - field = table.NormalizeRef(fields[i]) - } - rule := "" - if i < len(ruleList) { - rule = ruleList[i] - } - if field == "" || rule == "" { - continue - } - msg := "" - if i < len(msgs) { - msg = msgs[i] - } - out = append(out, map[string]any{ - "field": field, - "rule": rule, - "message": msg, - }) - } - return out - default: - return []any{} - } -} - -func sqlTypeToInput(sqlType, name string) string { - t := strings.ToUpper(sqlType) - if strings.Contains(t, "INT") || strings.Contains(t, "REAL") || - strings.Contains(t, "FLOAT") || strings.Contains(t, "DOUBLE") { - return "number" - } - if name == "body" || strings.HasSuffix(name, "_body") || strings.HasSuffix(name, "_text") { - return "textarea" - } - if strings.Contains(name, "email") { - return "email" - } - if strings.Contains(name, "url") || name == "href" { - return "url" - } - return "text" -} - -// FromSchema builds a form handle from live SQLite schema (admin new/edit). -func FromSchema(dbURL, tableName, action, id, adminPrefix string) (map[string]any, error) { - action = normalizeAction(action) - cols, err := db.TableInfo(dbURL, tableName) - if err != nil { - return nil, err - } - if len(cols) == 0 { - return nil, fmt.Errorf("unknown table `%s`", tableName) - } - fields := make([]any, 0, len(cols)) - for _, c := range cols { - if action == "insert" && c.PK && c.Name == "id" { - continue - } - required := c.NotNull || (action == "update" && c.PK) - fields = append(fields, map[string]any{ - "name": c.Name, - "label": c.Name, - "type": sqlTypeToInput(c.SQLType, c.Name), - "required": required, - "default": "", - "pk": c.PK, - }) - } - if adminPrefix == "" { - adminPrefix = "/admin" - } - base := strings.TrimRight(adminPrefix, "/") - tableHref := base + "/" + tableName - formBag := New(tableName, action, id) - formBag["fields"] = fields - formBag["redirect"] = tableHref - formBag["cancel_href"] = tableHref - if action == "insert" { - formBag["action_url"] = tableHref + "/new" - formBag["title"] = "New " + tableName - } else if id != "" { - formBag["action_url"] = tableHref + "/" + id + "/edit" - formBag["title"] = fmt.Sprintf("Edit %s #%s", tableName, id) - formBag["id"] = id - } - return formBag, nil -} - -func dataMap(data any) map[string]any { - rows := table.AsRows(data) - if arr, ok := rows.([]any); ok && len(arr) > 0 { - if m, ok := arr[0].(map[string]any); ok { - return cloneMap(m) - } - } - if m, ok := data.(map[string]any); ok { - return cloneMap(m) - } - return map[string]any{} -} - -func fieldText(data map[string]any, name string) string { - if data == nil { - return "" - } - if v, ok := data[name]; ok { - return cellStr(v) - } - return "" -} - -func defaultMessage(rule, field string) string { - if rest, ok := strings.CutPrefix(rule, "min:"); ok { - return fmt.Sprintf("%s must be at least %s", field, rest) - } - if rest, ok := strings.CutPrefix(rule, "max:"); ok { - return fmt.Sprintf("%s must be at most %s", field, rest) - } - if other, ok := strings.CutPrefix(rule, "match:"); ok { - return fmt.Sprintf("%s must match %s", field, other) - } - if strings.HasPrefix(rule, "in:") { - return fmt.Sprintf("%s is not an allowed value", field) - } - switch rule { - case "required": - return field + " is required" - case "email": - return field + " must be an email" - case "url": - return field + " must be a URL" - default: - return fmt.Sprintf("%s failed `%s`", field, rule) - } -} - -func checkRule(rule, field string, data map[string]any) (string, bool) { - val := fieldText(data, field) - trimmed := strings.TrimSpace(val) - if rule == "required" { - if trimmed == "" { - return defaultMessage(rule, field), true - } - return "", false - } - if trimmed == "" { - return "", false - } - if n, ok := strings.CutPrefix(rule, "min:"); ok { - if min, err := strconv.ParseInt(n, 10, 64); err == nil { - if num, err := strconv.ParseFloat(trimmed, 64); err == nil { - if num < float64(min) { - return defaultMessage(rule, field), true - } - } else if int64(utf8.RuneCountInString(trimmed)) < min { - return defaultMessage(rule, field), true - } - } - return "", false - } - if n, ok := strings.CutPrefix(rule, "max:"); ok { - if max, err := strconv.ParseInt(n, 10, 64); err == nil { - if num, err := strconv.ParseFloat(trimmed, 64); err == nil { - if num > float64(max) { - return defaultMessage(rule, field), true - } - } else if int64(utf8.RuneCountInString(trimmed)) > max { - return defaultMessage(rule, field), true - } - } - return "", false - } - if other, ok := strings.CutPrefix(rule, "match:"); ok { - if val != fieldText(data, other) { - return defaultMessage(rule, field), true - } - return "", false - } - if list, ok := strings.CutPrefix(rule, "in:"); ok { - allowed := strings.Split(list, ",") - found := false - for _, a := range allowed { - if strings.TrimSpace(a) == trimmed { - found = true - break - } - } - if !found { - return defaultMessage(rule, field), true - } - return "", false - } - switch rule { - case "email": - if !(strings.Contains(trimmed, "@") && strings.Contains(trimmed, ".")) { - return defaultMessage(rule, field), true - } - case "url": - if !(strings.HasPrefix(trimmed, "http://") || strings.HasPrefix(trimmed, "https://")) { - return defaultMessage(rule, field), true - } - } - return "", false -} - -func fieldSlice(formBag map[string]any) []any { - if formBag == nil { - return nil - } - arr, _ := formBag["fields"].([]any) - return arr -} - -func ruleSlice(formBag map[string]any) []any { - if formBag == nil { - return nil - } - arr, _ := formBag["rules"].([]any) - return arr -} - -// Validate merges field-required + author rules; returns {ok, errors:[{field,message}]}. -// extraRules may be nil. -func Validate(formBag map[string]any, extraRules any, data any) map[string]any { - dataM := dataMap(data) - fields := fieldSlice(formBag) - rules := append([]any{}, ruleSlice(formBag)...) - if extraRules != nil { - rules = append(rules, asFormRules(extraRules)...) - } - for _, f := range fields { - fm, ok := f.(map[string]any) - if !ok { - continue - } - name, _ := fm["name"].(string) - required, _ := fm["required"].(bool) - if !required || name == "" { - continue - } - already := false - for _, r := range rules { - rm, ok := r.(map[string]any) - if !ok { - continue - } - if rm["field"] == name && rm["rule"] == "required" { - already = true - break - } - } - if !already { - rules = append([]any{map[string]any{ - "field": name, - "rule": "required", - "message": name + " is required", - }}, rules...) - } - } - - var errors []any - for _, r := range rules { - rm, ok := r.(map[string]any) - if !ok { - continue - } - field, _ := rm["field"].(string) - rule, _ := rm["rule"].(string) - msg, _ := rm["message"].(string) - if field == "" || rule == "" { - continue - } - if defMsg, fail := checkRule(rule, field, dataM); fail { - outMsg := defMsg - if msg != "" { - outMsg = msg - } - errors = append(errors, map[string]any{ - "field": field, - "message": outMsg, - }) - } - } - if errors == nil { - errors = []any{} - } - return map[string]any{ - "ok": len(errors) == 0, - "errors": errors, - } -} - -func esc(s string) string { - s = strings.ReplaceAll(s, "&", "&") - s = strings.ReplaceAll(s, "<", "<") - s = strings.ReplaceAll(s, ">", ">") - s = strings.ReplaceAll(s, `"`, """) - return s -} - -func strOf(m map[string]any, key, def string) string { - if m == nil { - return def - } - if v, ok := m[key]; ok { - if s := cellStr(v); s != "" { - return s - } - } - return def -} - -// RenderBody emits form markup only (no document shell). -func RenderBody(formBag map[string]any, formID string, data, errors any, csrf string) string { - return RenderBodyCtx(formBag, formID, data, errors, csrf, nil) -} - -// RenderBodyCtx is RenderBody plus request-context hidden fields for POST. -func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf string, ctx *RequestContext) string { - fields := fieldSlice(formBag) - dataM := map[string]any{} - if data != nil { - dataM = dataMap(data) - } - errMap := map[string]string{} - switch e := errors.(type) { - case []any: - for _, item := range e { - if m, ok := item.(map[string]any); ok { - f, _ := m["field"].(string) - msg := cellStr(m["message"]) - if f != "" && msg != "" { - errMap[f] = msg - } - } - } - case map[string]any: - for k, v := range e { - errMap[k] = cellStr(v) - } - } - - action := strOf(formBag, "action", "insert") - tableName := strOf(formBag, "table", "") - heading := strOf(formBag, "title", formID) - postTo := strOf(formBag, "action_url", "/_form/"+formID) - cancel := strOf(formBag, "cancel_href", "/") - rowID := "" - if formBag != nil { - rowID = cellStr(formBag["id"]) - } - if rowID == "" { - rowID = fieldText(dataM, "id") - } - showMeta := true - if formBag != nil { - if v, ok := formBag["show_meta"].(bool); ok { - showMeta = v - } - } - - var body strings.Builder - hasFile := false - hasMarkdown := false - for _, f := range fields { - if fm, ok := f.(map[string]any); ok { - ty, _ := fm["type"].(string) - if strings.EqualFold(ty, "file") { - hasFile = true - } - if strings.EqualFold(ty, "markdown") { - hasMarkdown = true - } - } - } - formClass := "site-form" - if hasMarkdown { - formClass += " editor-skin" - } - body.WriteString(`
      `) - if showMeta { - fmt.Fprintf(&body, `

      table=%s · action=%s · id=%s

      `, - esc(tableName), esc(action), esc(heading)) - } - body.WriteString(`
      `) - if csrf != "" { - fmt.Fprintf(&body, ``, esc(csrf)) - } - hasIDField := false - for _, f := range fields { - if fm, ok := f.(map[string]any); ok { - if strOf(fm, "name", "") == "id" && IsClientSource(strOf(fm, "source", "client")) { - hasIDField = true - break - } - } - } - if (action == "update" || action == "delete") && rowID != "" && !hasIDField { - fmt.Fprintf(&body, ``, esc(rowID)) - } - if ctx != nil { - if len(ctx.Params) > 0 { - if b, err := json.Marshal(ctx.Params); err == nil { - fmt.Fprintf(&body, ``, esc(string(b))) - } - } - ret := strings.TrimSpace(ctx.ReturnPath) - if ret == "" { - ret = strings.TrimSpace(ctx.Path) - } - if ret != "" && strings.HasPrefix(ret, "/") && !strings.HasPrefix(ret, "//") { - fmt.Fprintf(&body, ``, esc(ret)) - } - } - for _, f := range fields { - fm, ok := f.(map[string]any) - if !ok { - continue - } - name, _ := fm["name"].(string) - if name == "" { - continue - } - if !IsClientSource(strOf(fm, "source", "client")) { - continue - } - label := strOf(fm, "label", name) - ty := strOf(fm, "type", "text") - required, _ := fm["required"].(bool) - def := strOf(fm, "default", "") - pk, _ := fm["pk"].(bool) - var value string - if _, ok := dataM[name]; ok { - value = fieldText(dataM, name) - } else if name == "id" && rowID != "" { - value = rowID - } else { - value = def - } - readonly := action == "update" && pk && name == "id" - if readonly { - fmt.Fprintf(&body, ``, - esc(label), esc(value)) - continue - } - reqAttr := "" - if required { - reqAttr = " required" - } - if ty == "hidden" { - fmt.Fprintf(&body, ``, esc(name), esc(value)) - continue - } - body.WriteString("") - } - submitLabel := strOf(formBag, "submit", "") - if submitLabel == "" { - submitLabel = strOf(formBag, "提交", "") - } - if submitLabel == "" { - submitLabel = "Submit" - } - cancelLabel := strOf(formBag, "cancel", "") - if cancelLabel == "" { - cancelLabel = strOf(formBag, "取消", "") - } - if cancelLabel == "" { - cancelLabel = "cancel" - } - cancelHref := cancel - if c := strOf(formBag, "cancel_href", ""); c != "" { - cancelHref = c - } else if c := strOf(formBag, "取消链接", ""); c != "" { - cancelHref = c - } - fmt.Fprintf(&body, `
      %s
      `, - esc(submitLabel), esc(cancelHref), esc(cancelLabel)) - body.WriteString(`
      `) - return body.String() -} - -// Render returns a standalone form HTML document. -// data and errors may be nil; csrf is optional (pass "" when unused). -func Render(formBag map[string]any, formID string, data, errors any, csrf string) string { - heading := formID - if formBag != nil { - if t := strOf(formBag, "title", ""); t != "" { - heading = t - } - } - var body strings.Builder - body.WriteString(``) - fmt.Fprintf(&body, `%s`, esc(heading)) - body.WriteString(``) - fmt.Fprintf(&body, `

      %s

      `, esc(heading)) - body.WriteString(RenderBody(formBag, formID, data, errors, csrf)) - body.WriteString(``) - return body.String() -} - -// Submit validates then insert/update via db. On validation failure returns -// {ok:false, errors:[…]} with a nil error (matches Rust). -func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, error) { - action := strOf(formBag, "action", "insert") - rowMap := dataMap(data) - if action == "update" || action == "delete" { - if formBag != nil { - if fid := cellStr(formBag["id"]); fid != "" { - if _, ok := rowMap["id"]; !ok { - rowMap["id"] = fid - } - } - } - } - if action != "delete" { - v := Validate(formBag, nil, rowMap) - ok, _ := v["ok"].(bool) - if !ok { - errs := v["errors"] - if errs == nil { - errs = []any{} - } - return map[string]any{"ok": false, "errors": errs}, nil - } - } - tableName := "" - if formBag != nil { - tableName, _ = formBag["table"].(string) - } - if tableName == "" { - return nil, fmt.Errorf("form missing `table`") - } - var result map[string]any - var err error - switch action { - case "delete": - id := "" - if formBag != nil { - id = cellStr(formBag["id"]) - } - if id == "" { - id = cellStr(rowMap["id"]) - } - if id == "" { - return nil, fmt.Errorf("delete requires `id`") - } - result, err = db.Delete(dbURL, tableName, id) - case "update": - id := "" - if formBag != nil { - id = cellStr(formBag["id"]) - } - if id == "" { - id = cellStr(rowMap["id"]) - } - if id == "" { - return nil, fmt.Errorf("update requires `id`") - } - result, err = db.Update(dbURL, tableName, id, rowMap) - default: - result, err = db.Insert(dbURL, tableName, []any{rowMap}) - } - if err != nil { - return nil, err - } - redirect := strOf(formBag, "redirect", "/") - return map[string]any{ - "ok": true, - "result": result, - "redirect": redirect, - }, nil -} diff --git a/plugins/web/internal/form/form_test.go b/plugins/web/internal/form/form_test.go deleted file mode 100755 index c28aa21..0000000 --- a/plugins/web/internal/form/form_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package form_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/form" -) - -func TestValidateRequiredAndEmail(t *testing.T) { - f := form.New("users", "insert", "") - f = form.SetFields(f, []any{ - map[string]any{"字段": "email", "标签": "Email", "类型": "email", "必填": true}, - map[string]any{"字段": "name", "标签": "Name", "类型": "text", "必填": false}, - }) - f = form.SetRules(f, []any{ - map[string]any{"字段": "email", "规则": "email", "消息": "bad email"}, - }) - - bad := form.Validate(f, nil, map[string]any{"email": "", "name": "x"}) - if ok, _ := bad["ok"].(bool); ok { - t.Fatalf("expected required failure: %v", bad) - } - errs, _ := bad["errors"].([]any) - if len(errs) == 0 { - t.Fatal("expected errors") - } - - badEmail := form.Validate(f, nil, map[string]any{"email": "not-an-email", "name": "x"}) - if ok, _ := badEmail["ok"].(bool); ok { - t.Fatalf("expected email failure: %v", badEmail) - } - found := false - for _, e := range badEmail["errors"].([]any) { - m := e.(map[string]any) - if m["field"] == "email" && m["message"] == "bad email" { - found = true - } - } - if !found { - t.Fatalf("expected custom email message: %v", badEmail) - } - - good := form.Validate(f, nil, map[string]any{"email": "a@b.co", "name": "x"}) - if ok, _ := good["ok"].(bool); !ok { - t.Fatalf("expected ok: %v", good) - } -} - -func TestRenderContainsInputFields(t *testing.T) { - f := form.New("articles", "insert", "") - f = form.SetFields(f, []any{ - map[string]any{"字段": "title", "标签": "Title", "类型": "text", "必填": true}, - map[string]any{"字段": "body", "标签": "Body", "类型": "textarea"}, - }) - html := form.Render(f, "article", nil, nil, "") - checks := []string{ - `name="title"`, - `name="body"`, - "发布文章", - `href="/desk/posts"`, - ">返回列表", - } { - if !strings.Contains(html, want) { - t.Fatalf("missing %q in:\n%s", want, html) - } - } -} diff --git a/plugins/web/internal/form/source.go b/plugins/web/internal/form/source.go deleted file mode 100755 index 18b7668..0000000 --- a/plugins/web/internal/form/source.go +++ /dev/null @@ -1,128 +0,0 @@ -package form - -import ( - "encoding/json" - "strings" - "time" -) - -func normalizeSource(raw string) string { - s := strings.TrimSpace(raw) - if s == "" { - return "client" - } - switch strings.ToLower(s) { - case "client", "用户", "input", "form": - return "client" - case "user", "username", "session.user", "session.username", "用户名": - return "session.username" - case "now", "utc.now", "server.now", "时间", "utc": - return "now" - case "now_if_empty", "空则现在", "now?": - return "now_if_empty" - default: - return s - } -} - -// IsClientSource reports whether the field is filled by the browser. -func IsClientSource(source string) bool { - src := normalizeSource(source) - return src == "client" || src == "now_if_empty" -} - -// RequestContext carries session user and route params for form source stamping -// (design: ext-web-request-context.md). Domain-agnostic — no table-name branches. -type RequestContext struct { - Username string - Params map[string]any - ReturnPath string - Path string - Method string -} - -// ApplySources strips client-supplied values for non-client fields, then stamps -// from ctx. Always overwrites server-owned keys. `now_if_empty` keeps a non-empty -// client value and only stamps UTC now when the field was left blank. -func ApplySources(formBag map[string]any, data map[string]any, ctx *RequestContext) { - if data == nil { - return - } - if ctx == nil { - ctx = &RequestContext{} - } - for _, f := range fieldSlice(formBag) { - fm, ok := f.(map[string]any) - if !ok { - continue - } - name, _ := fm["name"].(string) - if name == "" { - continue - } - src := normalizeSource(strOf(fm, "source", "client")) - switch src { - case "client": - continue - case "now_if_empty": - if data[name] != nil && strings.TrimSpace(cellStr(data[name])) != "" { - continue - } - if v, ok := resolveSource("now", ctx); ok { - data[name] = v - } - default: - delete(data, name) - if v, ok := resolveSource(src, ctx); ok { - data[name] = v - } - } - } -} - -func resolveSource(src string, ctx *RequestContext) (any, bool) { - src = normalizeSource(src) - switch src { - case "client": - return nil, false - case "session.username": - if ctx.Username == "" { - return nil, false - } - return ctx.Username, true - case "now": - return time.Now().UTC().Format("2006-01-02 15:04:05"), true - } - lower := strings.ToLower(src) - for _, prefix := range []string{"route.", "param.", "params."} { - if strings.HasPrefix(lower, prefix) { - key := src[len(prefix):] - if key == "" || ctx.Params == nil { - return nil, false - } - if v, ok := ctx.Params[key]; ok { - return v, true - } - for k, v := range ctx.Params { - if strings.EqualFold(k, key) { - return v, true - } - } - return nil, false - } - } - return nil, false -} - -// ParseMQParams decodes the hidden `_mq_params` JSON posted with forms. -func ParseMQParams(raw string) map[string]any { - raw = strings.TrimSpace(raw) - if raw == "" { - return nil - } - var out map[string]any - if err := json.Unmarshal([]byte(raw), &out); err != nil { - return nil - } - return out -} diff --git a/plugins/web/internal/form/source_test.go b/plugins/web/internal/form/source_test.go deleted file mode 100755 index 27c5c54..0000000 --- a/plugins/web/internal/form/source_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package form - -import "testing" - -func TestApplySourcesOverwritesClient(t *testing.T) { - frm := SetFields(New("comments", "insert", "c"), []any{ - map[string]any{"字段": "body", "标签": "body", "类型": "textarea", "必填": true, "来源": "client"}, - map[string]any{"字段": "author", "标签": "a", "类型": "text", "必填": true, "来源": "session.username"}, - map[string]any{"字段": "post_slug", "标签": "s", "类型": "text", "必填": true, "来源": "route.slug"}, - map[string]any{"字段": "created_at", "标签": "t", "类型": "text", "来源": "now"}, - }) - data := map[string]any{ - "body": "hi", - "author": "forged", - "post_slug": "evil", - } - ApplySources(frm, data, &RequestContext{ - Username: "alice", - Params: map[string]any{"slug": "hello"}, - }) - if data["author"] != "alice" { - t.Fatalf("author=%v", data["author"]) - } - if data["post_slug"] != "hello" { - t.Fatalf("slug=%v", data["post_slug"]) - } - if data["body"] != "hi" { - t.Fatalf("body=%v", data["body"]) - } - if data["created_at"] == nil || data["created_at"] == "" { - t.Fatalf("created_at missing") - } -} - -func TestApplySourcesNowIfEmpty(t *testing.T) { - frm := SetFields(New("news", "insert", "n"), []any{ - map[string]any{"字段": "title", "标签": "t", "类型": "text", "必填": true}, - map[string]any{"字段": "published_at", "标签": "d", "类型": "text", "来源": "空则现在"}, - }) - empty := map[string]any{"title": "x", "published_at": ""} - ApplySources(frm, empty, &RequestContext{}) - if empty["published_at"] == nil || empty["published_at"] == "" { - t.Fatalf("expected stamp, got %#v", empty["published_at"]) - } - kept := map[string]any{"title": "x", "published_at": "2020-01-02"} - ApplySources(frm, kept, &RequestContext{}) - if kept["published_at"] != "2020-01-02" { - t.Fatalf("should keep client date, got %#v", kept["published_at"]) - } -} - -func TestRenderSkipsServerSources(t *testing.T) { - frm := SetFields(New("comments", "insert", "c"), []any{ - map[string]any{"字段": "body", "标签": "Body", "类型": "textarea", "必填": true}, - map[string]any{"字段": "author", "标签": "Author", "类型": "text", "来源": "session.username"}, - }) - html := RenderBodyCtx(frm, "c", nil, nil, "", &RequestContext{ - Username: "alice", - Params: map[string]any{"slug": "x"}, - ReturnPath: "/post/x", - }) - if stringsContains(html, `name="author"`) { - t.Fatalf("author field should not render: %s", html) - } - if !stringsContains(html, `name="body"`) { - t.Fatalf("body missing") - } - if !stringsContains(html, `_mq_params`) || !stringsContains(html, `_mq_return`) { - t.Fatalf("missing mq context fields: %s", html) - } -} - -func stringsContains(s, sub string) bool { - return len(s) >= len(sub) && (s == sub || len(sub) == 0 || - (func() bool { - for i := 0; i+len(sub) <= len(s); i++ { - if s[i:i+len(sub)] == sub { - return true - } - } - return false - })()) -} diff --git a/plugins/web/internal/httpx/auth.go b/plugins/web/internal/httpx/auth.go deleted file mode 100755 index 98dafd8..0000000 --- a/plugins/web/internal/httpx/auth.go +++ /dev/null @@ -1,1007 +0,0 @@ -package httpx - -import ( - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/auth" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/password" - "github.com/marqdo/marqdo/plugins/web/internal/ratelimit" - "github.com/marqdo/marqdo/plugins/web/internal/rbac" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -type gateMatch int - -const ( - gateMatchPrefix gateMatch = 0 - gateMatchExact gateMatch = 1 -) - -type onDeny int - -const ( - onDenyForbid onDeny = 0 - onDenyRedirect onDeny = 1 -) - -type gate struct { - path string - roles []string - permissions []string - matchMode gateMatch - onDeny onDeny - exclude []string -} - -type authConfig struct { - users any - sessionTTL uint64 - cookieSecure bool - admin bool - adminPrefix string - loginPath string - loginRedirect string - logoutRedirect string - gates []gate - rbac bool - rbacDesk bool - register bool - registerPath string - defaultRole string -} - -func authConfigOf(appBag map[string]any) authConfig { - cfg := authConfig{ - admin: boolish(appBag["admin"]), - adminPrefix: app.AdminPrefix(appBag), - sessionTTL: 3600, - } - cfg.loginPath = strOpt(appBag, "login_path", "") - if cfg.loginPath == "" { - cfg.loginPath = cfg.adminPrefix + "/login" - } - cfg.loginRedirect = strOpt(appBag, "login_redirect", "") - if cfg.loginRedirect == "" { - cfg.loginRedirect = cfg.adminPrefix - } - cfg.logoutRedirect = strOpt(appBag, "logout_redirect", "") - if cfg.logoutRedirect == "" { - cfg.logoutRedirect = cfg.loginPath - } - if v, ok := appBag["cookie_secure"].(bool); ok { - cfg.cookieSecure = v - } - cfg.registerPath = strOpt(appBag, "register_path", "") - if authBag, ok := appBag["auth"].(map[string]any); ok { - cfg.users = authBag["users"] - if n, ok := asUint64(authBag["session_ttl"]); ok && n > 0 { - cfg.sessionTTL = n - } else if n, ok := asUint64(authBag["ttl"]); ok && n > 0 { - cfg.sessionTTL = n - } - cfg.rbac = boolish(authBag["rbac"]) - cfg.rbacDesk = boolish(authBag["rbac_desk"]) - cfg.register = boolish(authBag["register"]) - if p := strOpt(authBag, "register_path", ""); p != "" { - cfg.registerPath = p - } - cfg.defaultRole = strOpt(authBag, "default_role", "") - if cfg.defaultRole == "" { - cfg.defaultRole = "member" - } - } - if cfg.registerPath == "" { - cfg.registerPath = "/register" - } - cfg.gates = parseGates(appBag["gates"]) - return cfg -} - -func parseGates(v any) []gate { - arr, ok := v.([]any) - if !ok { - return nil - } - out := make([]gate, 0, len(arr)) - for _, item := range arr { - m, ok := item.(map[string]any) - if !ok { - continue - } - path := strings.TrimSpace(strOpt(m, "path", "")) - if path == "" { - path = strings.TrimSpace(strOpt(m, "路径", "")) - } - if path == "" { - continue - } - starred := strings.HasSuffix(path, "*") - if starred { - path = strings.TrimSuffix(path, "*") - } - roles := parseGateRoles(m["roles"]) - if roles == nil { - roles = parseGateRoles(m["角色"]) - } - perms := parseGateRoles(m["permissions"]) - if perms == nil { - perms = parseGateRoles(m["权限"]) - } - if len(roles) == 0 && len(perms) == 0 { - roles = []string{"admin"} - } - matchS := strings.ToLower(strings.TrimSpace(strOpt(m, "match", ""))) - if matchS == "" { - matchS = strings.ToLower(strings.TrimSpace(strOpt(m, "匹配", ""))) - } - matchMode := gateMatchPrefix - switch matchS { - case "exact", "精确": - matchMode = gateMatchExact - case "prefix", "前缀": - matchMode = gateMatchPrefix - default: - if starred { - matchMode = gateMatchPrefix - } - } - denyS := strings.ToLower(strings.TrimSpace(strOpt(m, "on_deny", ""))) - if denyS == "" { - denyS = strings.ToLower(strings.TrimSpace(strOpt(m, "拒绝", ""))) - } - on := onDenyForbid - switch denyS { - case "redirect", "重定向", "login": - on = onDenyRedirect - case "forbid", "禁止", "403": - on = onDenyForbid - } - out = append(out, gate{ - path: path, - roles: roles, - permissions: perms, - matchMode: matchMode, - onDeny: on, - exclude: parseExclude(m["exclude"], m["排除"]), - }) - } - return out -} - -func parseGateRoles(v any) []string { - switch t := v.(type) { - case string: - return session.ParseRolesCSV(t) - case []any: - var out []string - for _, item := range t { - if s, ok := item.(string); ok && strings.TrimSpace(s) != "" { - out = append(out, strings.ToLower(strings.TrimSpace(s))) - } - } - return out - case []string: - var out []string - for _, s := range t { - if strings.TrimSpace(s) != "" { - out = append(out, strings.ToLower(strings.TrimSpace(s))) - } - } - return out - default: - return nil - } -} - -func parseExclude(primary, alt any) []string { - if primary == nil { - primary = alt - } - switch t := primary.(type) { - case string: - var out []string - for _, part := range strings.Split(t, ",") { - part = strings.TrimSpace(part) - if part != "" { - out = append(out, part) - } - } - return out - case []any: - var out []string - for _, item := range t { - if s, ok := item.(string); ok { - s = strings.TrimSpace(s) - if s != "" { - out = append(out, s) - } - } - } - return out - default: - return nil - } -} - -func gateMatches(path string, g gate) bool { - pat := strings.TrimRight(strings.TrimSuffix(g.path, "*"), "/") - if pat == "" { - pat = "/" - } - switch g.matchMode { - case gateMatchExact: - return path == pat || path == g.path - default: - return path == pat || strings.HasPrefix(path, pat+"/") - } -} - -func pathExcluded(path string, exclude []string, loginPath string) bool { - if path == loginPath || strings.HasPrefix(path, loginPath+"?") { - return true - } - if strings.HasPrefix(path, "/oidc/") { - return true - } - // Local logout must always run; never bounce visitors to login→IdP first. - if path == "/logout" || strings.HasSuffix(path, "/logout") { - return true - } - for _, ex := range exclude { - ex = strings.TrimRight(strings.TrimSuffix(ex, "*"), "/") - if ex == "" { - continue - } - if path == ex || strings.HasPrefix(path, ex+"/") { - return true - } - } - return false -} - -func withRBAC(next http.Handler, gates []gate, loginPath string) http.Handler { - if len(gates) == 0 { - return next - } - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - path := r.URL.Path - cookie := r.Header.Get("Cookie") - for _, g := range gates { - if !gateMatches(path, g) { - continue - } - if pathExcluded(path, g.exclude, loginPath) { - break - } - role := session.RoleFromCookie(cookie) - allowed := false - if len(g.permissions) > 0 { - held := session.PermissionsFromCookie(cookie) - if len(held) == 0 && role != "visitor" { - held = expandLegacyRole(role) - } - allowed = session.PermissionAllowed(held, g.permissions) - } else { - allowed = session.RoleAllowed(role, g.roles) - } - if !allowed { - if role == "visitor" && g.onDeny == onDenyRedirect { - nextQ := urlEncodePath(path) - dest := loginPath - if nextQ != "" && path != loginPath { - dest = loginPath + "?next=" + nextQ - } - http.Redirect(w, r, dest, http.StatusSeeOther) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.WriteHeader(http.StatusForbidden) - _, _ = io.WriteString(w, fmt.Sprintf( - "

      403 Forbidden

      Role `%s` cannot access `%s`.

      ", - esc(role), esc(path))) - return - } - break - } - next.ServeHTTP(w, r) - }) -} - -func expandLegacyRole(role string) []string { - switch strings.ToLower(strings.TrimSpace(role)) { - case "superadmin", "admin": - return []string{ - "comments:create", "comments:delete", "comments:delete_own", - "desk:access", "roles:manage", "posts:edit", "users:manage", - } - case "member", "user": - return []string{"comments:create", "comments:delete_own"} - case "editor", "author": - return []string{"comments:create", "comments:delete_own", "posts:edit", "desk:access"} - default: - return nil - } -} - -func urlEncodePath(path string) string { - var out strings.Builder - for _, b := range []byte(path) { - switch { - case b >= 'A' && b <= 'Z', b >= 'a' && b <= 'z', b >= '0' && b <= '9', - b == '-', b == '_', b == '.', b == '~', b == '/': - out.WriteByte(b) - default: - out.WriteString(fmt.Sprintf("%%%02X", b)) - } - } - return out.String() -} - -func withNavAuth(page map[string]any, cookieHeader string) { - sid, ok := session.IDFromCookie(cookieHeader) - loggedIn := false - var username string - if ok && sid != "" { - if v, has := session.GetValue(sid, "username"); has { - if u, ok := v.(string); ok && u != "" { - loggedIn = true - username = u - } - } - } - page["_logged_in"] = loggedIn - if loggedIn { - page["_nav_user"] = username - } else { - delete(page, "_nav_user") - } -} - -func (st *state) hasPageRoute(path string) bool { - if path == "" || st.routes == nil { - return false - } - _, ok := st.routes[path] - return ok -} - -func (st *state) mountAuthRoutes(mux routeRegistrar) { - st.mountOIDCRoutes(mux) - if st.auth.users == nil && !(st.auth.rbac && st.auth.register) && !st.oidcEnabled() { - return - } - if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() { - lp := st.auth.loginPath - // Site pages may own GET /login (or /desk/login); always keep POST for auth. - if !st.hasPageRoute(lp) { - mux.HandleFunc("GET "+lp, st.handleLoginGet) - } - mux.HandleFunc("POST "+lp, st.handleLoginPost) - altLogin := strings.TrimRight(st.auth.adminPrefix, "/") + "/login" - if altLogin != lp { - if !st.hasPageRoute(altLogin) { - mux.HandleFunc("GET "+altLogin, st.handleLoginGet) - } - mux.HandleFunc("POST "+altLogin, st.handleLoginPost) - } - st.mountExtraLoginPosts(mux, map[string]bool{lp: true, altLogin: true}) - logoutPath := strings.TrimRight(st.auth.adminPrefix, "/") + "/logout" - mux.HandleFunc("GET "+logoutPath, st.handleLogout) - } - if st.auth.register && st.auth.rbac && !st.oidcEnabled() { - rp := st.auth.registerPath - if !st.hasPageRoute(rp) { - mux.HandleFunc("GET "+rp, st.handleRegisterGet) - } - mux.HandleFunc("POST "+rp, st.handleRegisterPost) - } - // Opt-in: enable_rbac alone wires gates/schema; /_rbac HTTP surface needs desk=true. - if st.auth.rbac && st.auth.rbacDesk && st.dbURL != "" { - mux.HandleFunc("GET /_rbac/roles", st.handleRbacListRoles) - mux.HandleFunc("GET /_rbac/permissions", st.handleRbacListPermissions) - mux.HandleFunc("POST /_rbac/roles", st.handleRbacCreateRole) - mux.HandleFunc("POST /_rbac/roles/{id}/permissions", st.handleRbacSetRolePerms) - mux.HandleFunc("POST /_rbac/assign", st.handleRbacAssign) - mux.HandleFunc("GET /_rbac/desk", st.handleRbacDesk) - } - if st.auth.admin { - adminHome := strings.TrimRight(st.auth.adminPrefix, "/") - if adminHome == "" { - adminHome = "/admin" - } - // The canonical no-slash path must be registered too: the global - // trailing-slash normalizer otherwise triggers a ServeMux redirect loop. - mux.HandleFunc("GET "+adminHome, st.handleAdminHome) - mux.HandleFunc("GET "+adminHome+"/{$}", st.handleAdminHome) - } -} - -func (st *state) handleLoginGet(w http.ResponseWriter, r *http.Request) { - if st.oidcEnabled() { - st.handleOIDCStart(w, r) - return - } - if st.auth.users == nil && !st.auth.rbac { - http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther) - return - } - cookieHdr := r.Header.Get("Cookie") - if session.RoleFromCookie(cookieHdr) != "visitor" { - http.Redirect(w, r, loginDest(r, st.auth.loginRedirect), http.StatusSeeOther) - return - } - _, csrf, setCookie := resolveSession(r) - html := loginPageHTML(st.auth.loginPath, nil, csrf, r.URL.Query().Get("next")) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - appendSetCookie(w, setCookie) - _, _ = io.WriteString(w, html) -} - -func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) { - if st.oidcEnabled() { - st.handleOIDCStart(w, r) - return - } - if st.auth.users == nil && !st.auth.rbac { - http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther) - return - } - if err := r.ParseForm(); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - cookieHdr := r.Header.Get("Cookie") - sid, _, _ := resolveSession(r) - _, hadCookie := session.IDFromCookie(cookieHdr) - csrfToken := r.FormValue("_csrf") - if csrfToken != "" || hadCookie { - if !session.ValidateCSRF(sid, csrfToken) { - st.writeAuthFailure(w, r, "Invalid or missing CSRF token. Refresh and try again.") - return - } - } - username := r.FormValue("username") - password := r.FormValue("password") - ip := clientIP(r) - if err := ratelimit.Check(ip, username); err != nil { - st.writeAuthFailure(w, r, err.Error()) - return - } - res := st.tryLogin(username, password) - if ok, _ := res["ok"].(bool); !ok { - ratelimit.RecordFailure(ip, username) - st.writeAuthFailure(w, r, "Invalid username or password.") - return - } - ratelimit.ClearSuccess(ip, username) - sessID, _ := res["session_id"].(string) - role, _ := res["role"].(string) - st.attachLoginPermissions(sessID, username, role) - fallback := st.auth.loginRedirect - if page := st.pageForAuthPath(r.URL.Path); page != nil { - if af, ok := page["auth_form"].(map[string]any); ok { - if n, ok := af["next"].(string); ok { - if n = strings.TrimSpace(n); n != "" { - fallback = n - } - } - } - } - dest := loginDest(r, fallback) - held := session.PermissionsFromSession(sessID) - if (strings.HasPrefix(dest, "/desk") || strings.HasPrefix(dest, "/admin")) && - !session.PermissionAllowed(held, []string{"desk:access"}) { - dest = "/" - } - w.Header().Add("Set-Cookie", session.IssueCookie(sessID)) - http.Redirect(w, r, dest, http.StatusSeeOther) -} - -// tryLogin: GFM users first, then web_users when RBAC is on. -func (st *state) tryLogin(username, password string) map[string]any { - if st.auth.users != nil { - res := auth.Login(username, password, st.auth.users, st.auth.sessionTTL) - if ok, _ := res["ok"].(bool); ok { - u, _ := res["username"].(string) - role, _ := res["role"].(string) - st.seedGFMUserIntoRBAC(u, password, role) - return res - } - } - if st.auth.rbac && st.dbURL != "" { - role, ok, err := rbac.Authenticate(st.dbURL, username, password, passwordVerify) - if err == nil && ok { - id := session.NewID(st.auth.sessionTTL) - session.SetValue(id, "username", username) - session.SetValue(id, "role", role) - return map[string]any{ - "ok": true, "session_id": id, "username": username, "role": role, - } - } - } - return map[string]any{"ok": false} -} - -func (st *state) attachLoginPermissions(sessID, username, role string) { - var perms []string - if st.dbURL != "" && st.auth.rbac { - if dbPerms, err := rbac.PermissionsForUser(st.dbURL, username); err == nil && len(dbPerms) > 0 { - perms = dbPerms - } - } - if len(perms) == 0 { - perms = rbac.ExpandRole(role) - } - if len(perms) == 0 { - perms = expandLegacyRole(role) - } - auth.AttachPermissions(sessID, perms) -} - -func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) { - if sid, ok := session.IDFromCookie(r.Header.Get("Cookie")); ok { - auth.Logout(sid) - } - w.Header().Add("Set-Cookie", session.ClearCookie()) - dest := strings.TrimSpace(st.auth.logoutRedirect) - // With OIDC, /login (and siblings) immediately bounce to the IdP — that is - // re-auth, not logout. Land on a public page instead. - if dest == "" || (st.oidcEnabled() && st.isOIDCEntryPath(dest)) { - dest = "/" - } - http.Redirect(w, r, dest, http.StatusSeeOther) -} - -func (st *state) handleAdminHome(w http.ResponseWriter, r *http.Request) { - // Only explicitly mounted forms expose their associated business tables. - // Never enumerate session/credential tables just because they share a DB. - var body strings.Builder - body.WriteString(`Admin

      Admin

      Mounted forms and their current business records (up to 100 rows per table).

      `) - seen := map[string]bool{} - for _, id := range sortedKeys(st.forms) { - selected, ok := st.forms[id].(map[string]any) - if !ok { - continue - } - tableName, _ := selected["table"].(string) - fmt.Fprintf(&body, `

      %s

      Open form

      `, esc(id), esc(url.PathEscape(id))) - if tableName != "" && st.dbURL != "" && !seen[tableName] { - current, err := db.Select(st.dbURL, tableName, 100, db.SelectOpts{}) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - var data strings.Builder - encoder := json.NewEncoder(&data) - encoder.SetIndent("", " ") - encoder.SetEscapeHTML(false) - if err := encoder.Encode(current["rows"]); err != nil { - http.Error(w, "cannot encode admin records", http.StatusInternalServerError) - return - } - // Escape once for HTML, preserving readable literal angle brackets - // instead of displaying JSON's optional Unicode escape sequences. - fmt.Fprintf(&body, `

      %s

      %s
      `, esc(tableName), esc(data.String())) - seen[tableName] = true - } - body.WriteString("
      ") - } - if len(st.forms) == 0 { - body.WriteString("

      No forms are mounted.

      ") - } - body.WriteString("") - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, body.String()) -} - -func loginDest(r *http.Request, fallback string) string { - next := strings.TrimSpace(r.FormValue("next")) - if next == "" { - next = strings.TrimSpace(r.URL.Query().Get("next")) - } - if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") { - return next - } - return fallback -} - -func loginPageHTML(loginAction string, errMsg *string, csrf string, next string) string { - errHTML := "" - if errMsg != nil && *errMsg != "" { - errHTML = fmt.Sprintf("

      %s

      ", esc(*errMsg)) - } - csrfField := "" - if csrf != "" { - csrfField = fmt.Sprintf("", esc(csrf)) - } - nextField := "" - if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") { - nextField = fmt.Sprintf("", esc(next)) - } - return fmt.Sprintf(` - - - -Admin Login - - - - -`, errHTML, esc(loginAction), csrfField, nextField) -} - -func passwordVerify(pass, encoded string) bool { - return password.Verify(pass, encoded) -} - -func (st *state) seedGFMUserIntoRBAC(username, plaintext, role string) { - if !st.auth.rbac || st.dbURL == "" || username == "" { - return - } - exists, err := rbac.UserExists(st.dbURL, username) - if err != nil || exists { - return - } - hash, err := password.Hash(plaintext) - if err != nil { - return - } - target := "member" - switch strings.ToLower(role) { - case "admin", "superadmin": - target = "superadmin" - case "editor", "author": - // custom roles may not exist yet; fall back to member + ExpandRole at session - target = "member" - } - _ = rbac.EnsureUserWithRole(st.dbURL, username, hash, target) -} - -func (st *state) handleRegisterGet(w http.ResponseWriter, r *http.Request) { - _, csrf, setCookie := resolveSession(r) - html := registerPageHTML(st.auth.registerPath, nil, csrf) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - appendSetCookie(w, setCookie) - _, _ = io.WriteString(w, html) -} - -func (st *state) handleRegisterPost(w http.ResponseWriter, r *http.Request) { - if err := r.ParseForm(); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - sid, _, _ := resolveSession(r) - _, hadCookie := session.IDFromCookie(r.Header.Get("Cookie")) - csrfToken := r.FormValue("_csrf") - if csrfToken != "" || hadCookie { - if !session.ValidateCSRF(sid, csrfToken) { - st.writeRegisterFailure(w, r, "Invalid CSRF token.") - return - } - } - username := strings.TrimSpace(r.FormValue("username")) - pass := r.FormValue("password") - if len(username) < 2 || len(pass) < 4 { - st.writeRegisterFailure(w, r, "Username (≥2) and password (≥4) required.") - return - } - hash, err := password.Hash(pass) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if err := rbac.RegisterUser(st.dbURL, username, hash, st.auth.defaultRole); err != nil { - st.writeRegisterFailure(w, r, err.Error()) - return - } - res := st.tryLogin(username, pass) - if ok, _ := res["ok"].(bool); ok { - sessID, _ := res["session_id"].(string) - role, _ := res["role"].(string) - st.attachLoginPermissions(sessID, username, role) - w.Header().Add("Set-Cookie", session.IssueCookie(sessID)) - dest := st.auth.loginRedirect - held := session.PermissionsFromSession(sessID) - if !session.PermissionAllowed(held, []string{"desk:access"}) { - dest = "/" - } - http.Redirect(w, r, dest, http.StatusSeeOther) - return - } - http.Redirect(w, r, st.auth.loginPath, http.StatusSeeOther) -} - -func registerPageHTML(action string, errMsg *string, csrf string) string { - errHTML := "" - if errMsg != nil && *errMsg != "" { - errHTML = fmt.Sprintf("

      %s

      ", esc(*errMsg)) - } - csrfField := "" - if csrf != "" { - csrfField = fmt.Sprintf("", esc(csrf)) - } - return fmt.Sprintf(` - - - -Register - - - - -`, errHTML, esc(action), csrfField) -} - -func (st *state) requireRolesManage(w http.ResponseWriter, r *http.Request) bool { - held := session.PermissionsFromCookie(r.Header.Get("Cookie")) - if !session.PermissionAllowed(held, []string{"roles:manage"}) { - http.Error(w, "forbidden", http.StatusForbidden) - return false - } - return true -} - -func (st *state) writeJSON(w http.ResponseWriter, status int, v any) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(v) -} - -func (st *state) handleRbacListRoles(w http.ResponseWriter, r *http.Request) { - if !st.requireRolesManage(w, r) { - return - } - roles, err := rbac.ListRoles(st.dbURL) - if err != nil { - st.writeJSON(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": err.Error()}) - return - } - st.writeJSON(w, http.StatusOK, map[string]any{"ok": true, "roles": roles}) -} - -func (st *state) handleRbacListPermissions(w http.ResponseWriter, r *http.Request) { - if !st.requireRolesManage(w, r) { - return - } - perms, err := rbac.ListPermissions(st.dbURL) - if err != nil { - st.writeJSON(w, http.StatusInternalServerError, map[string]any{"ok": false, "error": err.Error()}) - return - } - st.writeJSON(w, http.StatusOK, map[string]any{"ok": true, "permissions": perms}) -} - -func (st *state) handleRbacCreateRole(w http.ResponseWriter, r *http.Request) { - if !st.requireRolesManage(w, r) { - return - } - var body struct { - Name string `json:"name"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil || strings.TrimSpace(body.Name) == "" { - st.writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": "name required"}) - return - } - id, err := rbac.CreateRole(st.dbURL, strings.TrimSpace(body.Name)) - if err != nil { - st.writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": err.Error()}) - return - } - st.writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "name": body.Name}) -} - -func (st *state) handleRbacSetRolePerms(w http.ResponseWriter, r *http.Request) { - if !st.requireRolesManage(w, r) { - return - } - idStr := r.PathValue("id") - roleID, err := strconv.ParseInt(idStr, 10, 64) - if err != nil { - st.writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": "bad id"}) - return - } - var body struct { - Permissions []string `json:"permissions"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - st.writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": "bad json"}) - return - } - grantable := session.PermissionsFromCookie(r.Header.Get("Cookie")) - if err := rbac.SetRolePermissions(st.dbURL, roleID, body.Permissions, grantable); err != nil { - st.writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": err.Error()}) - return - } - st.writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func (st *state) handleRbacAssign(w http.ResponseWriter, r *http.Request) { - if !st.requireRolesManage(w, r) { - return - } - var body struct { - Username string `json:"username"` - Role string `json:"role"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - st.writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": "bad json"}) - return - } - if err := rbac.AssignRole(st.dbURL, body.Username, body.Role); err != nil { - st.writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error": err.Error()}) - return - } - st.writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func (st *state) handleRbacDesk(w http.ResponseWriter, r *http.Request) { - if !st.requireRolesManage(w, r) { - return - } - roles, _ := rbac.ListRoles(st.dbURL) - perms, _ := rbac.ListPermissions(st.dbURL) - var roleOpts, permChecks strings.Builder - for _, role := range roles { - name, _ := role["name"].(string) - id := role["id"] - sys, _ := role["is_system"].(bool) - tag := "" - if sys { - tag = " (system)" - } - fmt.Fprintf(&roleOpts, ``, id, esc(name), tag) - } - for _, p := range perms { - code, _ := p["code"].(string) - desc, _ := p["description"].(string) - fmt.Fprintf(&permChecks, ``, - esc(code), esc(code), esc(desc)) - } - html := fmt.Sprintf(` - -Roles · RBAC - -

      角色与权限

      -

      需 roles:manage。系统角色权限不可在此改写;可新建角色并勾选权限,或给用户赋角色。

      -

      -
      -

      新建角色

      - -
      -
      -

      设置角色权限

      - -
      %s
      - -
      -
      -

      赋角色给用户

      - - - -
      -

      ← 后台

      - -`, roleOpts.String(), permChecks.String()) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, html) -} - -func clientIP(r *http.Request) string { - if xff := r.Header.Get("X-Forwarded-For"); xff != "" { - if i := strings.Index(xff, ","); i >= 0 { - return strings.TrimSpace(xff[:i]) - } - return strings.TrimSpace(xff) - } - if xri := r.Header.Get("X-Real-IP"); xri != "" { - return strings.TrimSpace(xri) - } - host, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - return r.RemoteAddr - } - return host -} - -func asUint64(v any) (uint64, bool) { - switch t := v.(type) { - case float64: - if t > 0 { - return uint64(t), true - } - case int: - if t > 0 { - return uint64(t), true - } - case int64: - if t > 0 { - return uint64(t), true - } - case uint64: - if t > 0 { - return t, true - } - case string: - var n uint64 - if _, err := fmt.Sscanf(strings.TrimSpace(t), "%d", &n); err == nil && n > 0 { - return n, true - } - } - return 0, false -} diff --git a/plugins/web/internal/httpx/auth_custom.go b/plugins/web/internal/httpx/auth_custom.go deleted file mode 100755 index 2c94394..0000000 --- a/plugins/web/internal/httpx/auth_custom.go +++ /dev/null @@ -1,164 +0,0 @@ -package httpx - -import ( - "fmt" - "io" - "net/http" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func isLoginAuthPage(page any) bool { - m, ok := page.(map[string]any) - if !ok || m == nil { - return false - } - af, ok := m["auth_form"].(map[string]any) - if !ok || af == nil { - return false - } - kind := strings.ToLower(strings.TrimSpace(fmt.Sprint(af["kind"]))) - action := strings.ToLower(strings.TrimSpace(fmt.Sprint(af["action"]))) - if kind == "register" || strings.Contains(action, "register") { - return false - } - return true -} - -func (st *state) pageForAuthPath(path string) map[string]any { - if path == "" || st.routes == nil { - return nil - } - if p, ok := st.routes[path].(map[string]any); ok && p != nil { - return p - } - alt := strings.TrimRight(st.auth.adminPrefix, "/") + "/login" - if path == alt { - if p, ok := st.routes["/desk/login"].(map[string]any); ok { - return p - } - } - return nil -} - -func localizeAuthErr(msg string) string { - s := strings.TrimSpace(msg) - lower := strings.ToLower(s) - switch { - case s == "": - return "操作失败,请重试。" - case strings.Contains(s, "Too many failed"): - return "尝试次数过多,请约 15 分钟后再试。" - case strings.Contains(s, "Invalid username or password"): - return "用户名或密码错误。" - case strings.Contains(s, "Invalid or missing CSRF"), strings.Contains(s, "Invalid CSRF"): - return "登录令牌失效,请刷新页面后重试。" - case strings.Contains(s, "Username") && strings.Contains(lower, "password"): - return "请填写有效的用户名(≥2)与密码(≥4)。" - case strings.Contains(lower, "already"), strings.Contains(lower, "exists"), strings.Contains(s, "存在"): - return "该用户名已被注册,请换一个。" - default: - return s - } -} - -func safeAuthNext(raw string) string { - next := strings.TrimSpace(raw) - if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") { - return next - } - return "" -} - -func (st *state) writeAuthFailure(w http.ResponseWriter, r *http.Request, msg string) { - path := r.URL.Path - page := st.pageForAuthPath(path) - if page == nil && path == strings.TrimRight(st.auth.adminPrefix, "/")+"/login" { - page = st.pageForAuthPath("/desk/login") - } - if page != nil { - p := cloneMap(page) - p["_flash_err"] = localizeAuthErr(msg) - if next := safeAuthNext(r.FormValue("next")); next != "" { - p["_auth_next"] = next - } else if next := safeAuthNext(r.URL.Query().Get("next")); next != "" { - p["_auth_next"] = next - } - st.writePage(w, r, p) - return - } - _, csrf, setCookie := resolveSession(r) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - appendSetCookie(w, setCookie) - loc := localizeAuthErr(msg) - _, _ = io.WriteString(w, loginPageHTML(st.auth.loginPath, &loc, csrf, r.FormValue("next"))) -} - -func (st *state) writeRegisterFailure(w http.ResponseWriter, r *http.Request, msg string) { - path := r.URL.Path - page := st.pageForAuthPath(path) - if page == nil { - page = st.pageForAuthPath(st.auth.registerPath) - } - if page != nil { - p := cloneMap(page) - p["_flash_err"] = localizeAuthErr(msg) - st.writePage(w, r, p) - return - } - _, csrf, setCookie := resolveSession(r) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - appendSetCookie(w, setCookie) - loc := localizeAuthErr(msg) - _, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &loc, csrf)) -} - -func (st *state) mountExtraLoginPosts(mux routeRegistrar, already map[string]bool) { - for path, pageV := range st.routes { - if already[path] { - continue - } - if isLoginAuthPage(pageV) { - mux.HandleFunc("POST "+path, st.handleLoginPost) - already[path] = true - } - } -} - -func (st *state) authEntryRedirect(w http.ResponseWriter, r *http.Request, page map[string]any) bool { - if page == nil || r == nil { - return false - } - path := r.URL.Path - isEntry := false - if path == st.auth.loginPath || path == st.auth.registerPath { - isEntry = true - } - alt := strings.TrimRight(st.auth.adminPrefix, "/") + "/login" - if path == alt { - isEntry = true - } - if _, ok := page["auth_form"]; ok { - isEntry = true - } - if !isEntry { - return false - } - if session.RoleFromCookie(r.Header.Get("Cookie")) == "visitor" { - return false - } - fallback := st.auth.loginRedirect - if af, ok := page["auth_form"].(map[string]any); ok { - if n, ok := af["next"].(string); ok { - if n = strings.TrimSpace(n); n != "" { - fallback = n - } - } - } - if path == st.auth.registerPath { - fallback = st.auth.loginRedirect - } - http.Redirect(w, r, loginDest(r, fallback), http.StatusSeeOther) - return true -} diff --git a/plugins/web/internal/httpx/auth_oidc.go b/plugins/web/internal/httpx/auth_oidc.go deleted file mode 100755 index 9f8e68f..0000000 --- a/plugins/web/internal/httpx/auth_oidc.go +++ /dev/null @@ -1,261 +0,0 @@ -package httpx - -import ( - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/marqdo/marqdo/plugins/web/internal/auth" - "github.com/marqdo/marqdo/plugins/web/internal/oidc" - "github.com/marqdo/marqdo/plugins/web/internal/rbac" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -const oidcPasswordSentinel = "!oidc!" - -var ( - oidcHTTPOnce sync.Once - oidcHTTP *http.Client -) - -func oidcClient() *http.Client { - oidcHTTPOnce.Do(func() { - oidcHTTP = &http.Client{Timeout: 20 * time.Second} - }) - return oidcHTTP -} - -func (st *state) oidcEnabled() bool { - return st.oidc.Enabled() -} - -func (st *state) ensureOIDCEndpoints() error { - if !st.oidc.Enabled() { - return fmt.Errorf("oidc not configured") - } - return st.oidc.ResolveEndpoints(oidcClient()) -} - -func (st *state) isOIDCEntryPath(path string) bool { - if !st.oidcEnabled() || path == "" { - return false - } - if path == st.auth.loginPath || path == st.auth.registerPath { - return true - } - alt := strings.TrimRight(st.auth.adminPrefix, "/") + "/login" - if path == alt || path == "/desk/login" || path == "/admin/login" { - return true - } - return false -} - -// oidcFallbackNext picks where to land after IdP login when ?next= is absent. -// Admin entry pages must not fall back to the public homepage. -func (st *state) oidcFallbackNext(r *http.Request) string { - path := "" - if r != nil { - path = r.URL.Path - } - switch path { - case "/desk/login", "/admin/login", "/oidc/login": - return "/admin" - case "/desk", "/admin": - return "/admin" - } - if strings.HasPrefix(path, "/desk/") || strings.HasPrefix(path, "/admin/") { - return "/admin" - } - if st.auth.loginRedirect != "" { - return st.auth.loginRedirect - } - return "/" -} - -func (st *state) mountOIDCRoutes(mux routeRegistrar) { - if !st.oidcEnabled() { - return - } - cb := st.oidc.Callback() - mux.HandleFunc("GET "+cb, st.handleOIDCCallback) - mux.HandleFunc("GET /oidc/login", st.handleOIDCStart) - mux.HandleFunc("GET /oidc/register", st.handleOIDCStart) -} - -func (st *state) handleOIDCStart(w http.ResponseWriter, r *http.Request) { - if !st.oidcEnabled() { - http.NotFound(w, r) - return - } - // Already signed in → skip IdP round-trip when destination is allowed. - cookie := r.Header.Get("Cookie") - if session.RoleFromCookie(cookie) != "visitor" { - next := loginDest(r, st.oidcFallbackNext(r)) - needsDesk := strings.HasPrefix(next, "/admin") || strings.HasPrefix(next, "/desk") - held := session.PermissionsFromCookie(cookie) - if needsDesk && !session.PermissionAllowed(held, []string{"desk:access"}) { - http.Redirect(w, r, "/", http.StatusSeeOther) - return - } - http.Redirect(w, r, next, http.StatusSeeOther) - return - } - if err := st.ensureOIDCEndpoints(); err != nil { - http.Error(w, "oidc discovery failed: "+err.Error(), http.StatusBadGateway) - return - } - sid, _, setCookie := resolveSession(r) - state, err := oidc.RandomURLString(24) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - verifier, err := oidc.RandomURLString(32) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - redirectURI, err := st.oidc.ResolveRedirectURI(r) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - session.SetValue(sid, "oidc_state", state) - session.SetValue(sid, "oidc_verifier", verifier) - session.SetValue(sid, "oidc_redirect_uri", redirectURI) - next := loginDest(r, st.oidcFallbackNext(r)) - session.SetValue(sid, "oidc_next", next) - loc, err := st.oidc.AuthorizeRedirect(state, oidc.PKCEChallengeS256(verifier), redirectURI) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - appendSetCookie(w, setCookie) - w.Header().Add("Set-Cookie", session.IssueCookie(sid)) - http.Redirect(w, r, loc, http.StatusFound) -} - -func (st *state) handleOIDCCallback(w http.ResponseWriter, r *http.Request) { - if !st.oidcEnabled() { - http.NotFound(w, r) - return - } - if err := st.ensureOIDCEndpoints(); err != nil { - http.Error(w, "oidc discovery failed: "+err.Error(), http.StatusBadGateway) - return - } - q := r.URL.Query() - if errCode := q.Get("error"); errCode != "" { - msg := errCode - if d := q.Get("error_description"); d != "" { - msg = errCode + ": " + d - } - http.Error(w, "oidc: "+msg, http.StatusBadRequest) - return - } - code := q.Get("code") - state := q.Get("state") - if code == "" || state == "" { - http.Error(w, "oidc: missing code or state", http.StatusBadRequest) - return - } - sid, _, setCookie := resolveSession(r) - want, _ := session.GetValue(sid, "oidc_state") - wantS, _ := want.(string) - if wantS == "" || wantS != state { - http.Error(w, "oidc: state mismatch", http.StatusBadRequest) - return - } - verifier, _ := session.GetValue(sid, "oidc_verifier") - verifierS, _ := verifier.(string) - redirVal, _ := session.GetValue(sid, "oidc_redirect_uri") - redirectURI, _ := redirVal.(string) - if redirectURI == "" && !st.oidc.IsPathRedirect() { - redirectURI = strings.TrimSpace(st.oidc.RedirectURI) - } - if redirectURI == "" { - http.Error(w, "oidc: missing redirect_uri in session", http.StatusBadRequest) - return - } - nextVal, _ := session.GetValue(sid, "oidc_next") - next, _ := nextVal.(string) - if next == "" { - next = st.auth.loginRedirect - } - session.DelKey(sid, "oidc_state") - session.DelKey(sid, "oidc_verifier") - session.DelKey(sid, "oidc_redirect_uri") - session.DelKey(sid, "oidc_next") - - tok, err := st.oidc.ExchangeCode(oidcClient(), code, verifierS, redirectURI) - if err != nil { - http.Error(w, "oidc token exchange: "+err.Error(), http.StatusBadGateway) - return - } - info, err := st.oidc.FetchUserInfo(oidcClient(), tok.AccessToken) - if err != nil { - http.Error(w, "oidc userinfo: "+err.Error(), http.StatusBadGateway) - return - } - username := info.LocalUsername() - if username == "" { - http.Error(w, "oidc: empty username", http.StatusBadGateway) - return - } - role := info.LocalRole(st.auth.defaultRole) - if role == "admin" { - // System RBAC seed uses superadmin; keep session role "admin" for ExpandRole. - if st.dbURL != "" && st.auth.rbac { - _ = rbac.EnsureUserWithRole(st.dbURL, username, oidcPasswordSentinel, "superadmin") - } - } else if st.dbURL != "" && st.auth.rbac { - _ = rbac.EnsureUserWithRole(st.dbURL, username, oidcPasswordSentinel, role) - } - newID := session.NewID(st.auth.sessionTTL) - session.SetValue(newID, "username", username) - session.SetValue(newID, "role", role) - session.SetValue(newID, "oidc_sub", info.Sub) - if info.Email != "" { - session.SetValue(newID, "email", info.Email) - } - if info.AdminRole != "" { - session.SetValue(newID, "admin_role", info.AdminRole) - } - st.attachOIDCPermissions(newID, username, role) - - held := session.PermissionsFromSession(newID) - if (strings.HasPrefix(next, "/desk") || strings.HasPrefix(next, "/admin")) && - !session.PermissionAllowed(held, []string{"desk:access"}) { - next = "/" - } - appendSetCookie(w, setCookie) - w.Header().Add("Set-Cookie", session.IssueCookie(newID)) - http.Redirect(w, r, next, http.StatusSeeOther) -} - -func (st *state) attachOIDCPermissions(sessID, username, role string) { - // Prefer IdP-derived role expansion so platform admins always get desk access - // even before local RBAC rows catch up. - perms := rbac.ExpandRole(role) - if len(perms) == 0 { - perms = expandLegacyRole(role) - } - if st.dbURL != "" && st.auth.rbac { - if dbPerms, err := rbac.PermissionsForUser(st.dbURL, username); err == nil && len(dbPerms) > 0 { - // Union IdP role perms with any local grants. - seen := map[string]bool{} - var out []string - for _, p := range append(perms, dbPerms...) { - if p == "" || seen[p] { - continue - } - seen[p] = true - out = append(out, p) - } - perms = out - } - } - auth.AttachPermissions(sessID, perms) -} diff --git a/plugins/web/internal/httpx/auth_test.go b/plugins/web/internal/httpx/auth_test.go deleted file mode 100755 index 0798144..0000000 --- a/plugins/web/internal/httpx/auth_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package httpx - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/auth" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func TestGateMatchesAndRBAC(t *testing.T) { - session.Configure(session.Config{TTLSec: 3600}) - session.Reset(3600) - - gates := []gate{{ - path: "/write", - roles: []string{"admin"}, - matchMode: gateMatchPrefix, - onDeny: onDenyRedirect, - exclude: []string{"/admin/login"}, - }} - mux := http.NewServeMux() - mux.HandleFunc("GET /write", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }) - handler := withRBAC(mux, gates, "/admin/login") - - req := httptest.NewRequest(http.MethodGet, "/write", nil) - rec := httptest.NewRecorder() - handler.ServeHTTP(rec, req) - if rec.Code != http.StatusSeeOther { - t.Fatalf("anonymous /write: got %d", rec.Code) - } - loc := rec.Header().Get("Location") - if loc != "/admin/login?next=/write" { - t.Fatalf("location=%q", loc) - } - - res := auth.Login("admin", "secret", []any{ - map[string]any{"username": "admin", "password": "secret", "role": "admin"}, - }, 3600) - sid, _ := res["session_id"].(string) - req2 := httptest.NewRequest(http.MethodGet, "/write", nil) - req2.Header.Set("Cookie", "marqdo_sid="+sid) - rec2 := httptest.NewRecorder() - handler.ServeHTTP(rec2, req2) - if rec2.Code != http.StatusOK { - t.Fatalf("authed /write: got %d", rec2.Code) - } -} - -func TestWithNavAuth(t *testing.T) { - session.Configure(session.Config{TTLSec: 3600}) - session.Reset(3600) - page := map[string]any{} - withNavAuth(page, "") - if page["_logged_in"] != false { - t.Fatalf("expected logged out") - } - res := auth.Login("u", "p", []any{ - map[string]any{"username": "u", "password": "p"}, - }, 3600) - sid, _ := res["session_id"].(string) - withNavAuth(page, "marqdo_sid="+sid) - if page["_logged_in"] != true { - t.Fatalf("expected logged in") - } - if page["_nav_user"] != "u" { - t.Fatalf("nav user=%v", page["_nav_user"]) - } -} - -func TestLogoutPathExcludedFromGate(t *testing.T) { - gates := []gate{{ - path: "/admin", - permissions: []string{"desk:access"}, - matchMode: gateMatchPrefix, - onDeny: onDenyRedirect, - exclude: []string{"/admin/login"}, - }} - mux := http.NewServeMux() - mux.HandleFunc("GET /admin/logout", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNoContent) - }) - handler := withRBAC(mux, gates, "/login") - - req := httptest.NewRequest(http.MethodGet, "/admin/logout", nil) - rec := httptest.NewRecorder() - handler.ServeHTTP(rec, req) - if rec.Code != http.StatusNoContent { - t.Fatalf("visitor /admin/logout should reach handler, got %d loc=%s", rec.Code, rec.Header().Get("Location")) - } -} diff --git a/plugins/web/internal/httpx/cancel_bridge_test.go b/plugins/web/internal/httpx/cancel_bridge_test.go deleted file mode 100755 index 2105143..0000000 --- a/plugins/web/internal/httpx/cancel_bridge_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package httpx - -import ( - "os" - "path/filepath" - "testing" -) - -// F06: client-disconnect cancel bridge writes token file + MARQDO_CANCEL for llm plugin. -func TestPropagateCancelSignal(t *testing.T) { - dir := t.TempDir() - tok := filepath.Join(dir, "cancel.tok") - if err := os.WriteFile(tok, []byte("cancelled"), 0o600); err != nil { - t.Fatal(err) - } - t.Setenv("MARQDO_CANCEL_TOKEN", tok) - t.Setenv("MARQDO_CANCEL", "1") - - if os.Getenv("MARQDO_CANCEL") != "1" { - t.Fatalf("MARQDO_CANCEL not set") - } - body, err := os.ReadFile(tok) - if err != nil { - t.Fatal(err) - } - if string(body) != "cancelled" { - t.Fatalf("token body=%q", body) - } -} diff --git a/plugins/web/internal/httpx/drain_forward_test.go b/plugins/web/internal/httpx/drain_forward_test.go deleted file mode 100755 index 5a16628..0000000 --- a/plugins/web/internal/httpx/drain_forward_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package httpx - -import ( - "os" - "path/filepath" - "testing" -) - -func TestDrainForwardReadsIncrementalLines(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "evt.ndjson") - if err := os.WriteFile(path, []byte("{\"type\":\"a\"}\n{\"type\":\"b\"}\n"), 0o600); err != nil { - t.Fatal(err) - } - var lines []string - off := drainForward(path, 0, func(line string) { - lines = append(lines, line) - }) - if len(lines) != 2 { - t.Fatalf("got %d lines %#v", len(lines), lines) - } - if off <= 0 { - t.Fatalf("offset=%d", off) - } - // Append after first drain — second call with offset must only see new line. - f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteString("{\"type\":\"c\"}\n"); err != nil { - t.Fatal(err) - } - _ = f.Close() - var more []string - off2 := drainForward(path, off, func(line string) { - more = append(more, line) - }) - if len(more) != 1 || more[0] != "{\"type\":\"c\"}" { - t.Fatalf("incremental got %#v off=%d→%d", more, off, off2) - } -} diff --git a/plugins/web/internal/httpx/helpers.go b/plugins/web/internal/httpx/helpers.go deleted file mode 100755 index 62b4a30..0000000 --- a/plugins/web/internal/httpx/helpers.go +++ /dev/null @@ -1,241 +0,0 @@ -package httpx - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func esc(s string) string { - s = strings.ReplaceAll(s, "&", "&") - s = strings.ReplaceAll(s, "<", "<") - s = strings.ReplaceAll(s, ">", ">") - return s -} - -func weakETag(bytes []byte) string { - var h uint64 = 0xcbf29ce484222325 - for _, b := range bytes { - h ^= uint64(b) - h *= 0x0100000001b3 - } - return fmt.Sprintf("W/\"%x-%d\"", h, len(bytes)) -} - -func jsonErr(w http.ResponseWriter, code int, msg string) { - writeJSON(w, code, map[string]any{"ok": false, "error": msg}) -} - -func routeMapOf(appBag map[string]any, key string) map[string]any { - if r, ok := appBag[key].(map[string]any); ok { - return r - } - return map[string]any{} -} - -func routePathKey(path string) string { - p := strings.TrimSpace(path) - if !strings.HasPrefix(p, "/") { - p = "/" + p - } - return p -} - -// goMuxPattern converts Marqdo route patterns (`{*key}`) to Go ServeMux (`{key...}`). -func goMuxPattern(path string) string { - out := path - for { - start := strings.Index(out, "{*") - if start < 0 { - break - } - end := strings.Index(out[start:], "}") - if end < 0 { - break - } - end += start - name := out[start+2 : end] - out = out[:start] + "{" + name + "...}" + out[end+1:] - } - return out -} - -func resolveSession(r *http.Request) (sid, csrf string, setCookie *string) { - cookieHdr := r.Header.Get("Cookie") - id, hadCookie := session.IDFromCookie(cookieHdr) - if hadCookie && id != "" { - if tok, ok := session.CSRFFor(id); ok && tok != "" { - return id, tok, nil - } - // Stale/expired/missing session: mint a fresh session and replace the cookie. - // Previously we returned the dead sid with empty CSRF, so login forms had no - // _csrf while POST still saw hadCookie=true → "登录令牌失效". - } - sid = session.NewID(0) - tok, _ := session.CSRFFor(sid) - // Use configured session TTL (never Max-Age=0): browsers drop Max-Age=0 - // immediately, so CSRF cookies from GET /login would never stick. - c := session.IssueCookie(sid) - return sid, tok, &c -} - -func appendSetCookie(w http.ResponseWriter, setCookie *string) { - if setCookie != nil && *setCookie != "" { - w.Header().Add("Set-Cookie", *setCookie) - } -} - -func queryToMap(q string) map[string]any { - out := map[string]any{} - if q == "" { - return out - } - for _, pair := range strings.Split(q, "&") { - if pair == "" { - continue - } - k, v, _ := strings.Cut(pair, "=") - k, _ = url.QueryUnescape(k) - v, _ = url.QueryUnescape(v) - if k != "" { - out[k] = v - } - } - return out -} - -func formToMap(body []byte) map[string]any { - return queryToMap(string(body)) -} - -func jsonWrapInvokeValue(value any) (int, map[string]any, error) { - if value == nil { - return http.StatusInternalServerError, nil, fmt.Errorf("null result") - } - switch t := value.(type) { - case map[string]any: - code := http.StatusOK - if ok, has := t["ok"]; has { - if b, isBool := ok.(bool); isBool && !b { - if errMsg, _ := t["error"].(string); strings.EqualFold(errMsg, "unauthorized") || - strings.Contains(strings.ToLower(errMsg), "unauthorized") { - code = http.StatusUnauthorized - } - } - } - return code, t, nil - default: - return http.StatusOK, map[string]any{"ok": true, "result": value}, nil - } -} - -// writeSSE writes OpenAI-compatible (or generic) Server-Sent Events. -// value may be a string body, or a map with key "sse" / "body" / "chunks". -func writeSSE(w http.ResponseWriter, value any) { - w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.WriteHeader(http.StatusOK) - flusher, _ := w.(http.Flusher) - - writeChunk := func(s string) { - if s == "" { - return - } - if !strings.HasSuffix(s, "\n") { - s += "\n" - } - _, _ = io.WriteString(w, s) - if flusher != nil { - flusher.Flush() - } - } - - switch t := value.(type) { - case string: - writeChunk(t) - case map[string]any: - if s, ok := t["sse"].(string); ok { - writeChunk(s) - return - } - if s, ok := t["body"].(string); ok { - writeChunk(s) - return - } - if chunks, ok := t["chunks"].([]any); ok { - for _, c := range chunks { - writeChunk(fmt.Sprint(c)) - } - return - } - b, err := json.Marshal(t) - if err != nil { - writeChunk("data: {\"error\":\"sse_encode\"}\n\n") - return - } - writeChunk("data: " + string(b) + "\n\n") - writeChunk("data: [DONE]\n\n") - default: - writeChunk("data: " + fmt.Sprint(value) + "\n\n") - writeChunk("data: [DONE]\n\n") - } -} - -func invokeArgsFromPayload(payload map[string]any) map[string]any { - args := map[string]any{} - for k, v := range payload { - args[k] = v - } - if _, ok := args["payload"]; !ok { - args["payload"] = payload - } - return args -} - -// payloadWantsStream detects OpenAI-compatible stream:true on the request body. -func payloadWantsStream(payload map[string]any) bool { - if payload == nil { - return false - } - if v, ok := payload["stream"]; ok { - return boolishAny(v) - } - return false -} - -func boolishAny(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - s := strings.ToLower(strings.TrimSpace(t)) - return s == "1" || s == "true" || s == "yes" || s == "on" - case float64: - return t != 0 - case int: - return t != 0 - case int64: - return t != 0 - default: - return false - } -} - -func readJSONBody(r *http.Request, max int64) (map[string]any, error) { - r.Body = http.MaxBytesReader(nil, r.Body, max) - defer r.Body.Close() - var raw map[string]any - if err := json.NewDecoder(r.Body).Decode(&raw); err != nil { - return nil, err - } - if raw == nil { - raw = map[string]any{} - } - return raw, nil -} diff --git a/plugins/web/internal/httpx/helpers_test.go b/plugins/web/internal/httpx/helpers_test.go deleted file mode 100755 index 8b538ee..0000000 --- a/plugins/web/internal/httpx/helpers_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package httpx - -import ( - "net/http/httptest" - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func TestGoMuxPattern(t *testing.T) { - if got := goMuxPattern("/_media/{*key}"); got != "/_media/{key...}" { - t.Fatalf("got %q", got) - } - if got := goMuxPattern("/post/{slug}"); got != "/post/{slug}" { - t.Fatalf("got %q", got) - } -} - -func TestPathParamNamesIncludesID(t *testing.T) { - got := pathParamNames("/desk/posts/{id}") - if len(got) != 1 || got[0] != "id" { - t.Fatalf("got %#v", got) - } - got = pathParamNames("/post/{slug}") - if len(got) != 1 || got[0] != "slug" { - t.Fatalf("got %#v", got) - } -} - -func TestResolveSessionReplacesStaleCookie(t *testing.T) { - session.Configure(session.Config{TTLSec: 3600}) - session.Reset(3600) - - req := httptest.NewRequest("GET", "/login", nil) - req.Header.Set("Cookie", "marqdo_sid="+strings.Repeat("ab", 32)) - sid, csrf, setCookie := resolveSession(req) - if sid == "" || csrf == "" { - t.Fatalf("expected fresh sid+csrf, got sid=%q csrf=%q", sid, csrf) - } - if setCookie == nil || !strings.Contains(*setCookie, "marqdo_sid=") { - t.Fatalf("expected Set-Cookie for replacement session, got %#v", setCookie) - } - if !session.ValidateCSRF(sid, csrf) { - t.Fatal("csrf should validate for new session") - } - - // Live session should keep the same id without re-issuing cookie. - req2 := httptest.NewRequest("GET", "/login", nil) - req2.Header.Set("Cookie", "marqdo_sid="+sid) - sid2, csrf2, setCookie2 := resolveSession(req2) - if sid2 != sid || csrf2 != csrf { - t.Fatalf("live session should be stable: %q/%q vs %q/%q", sid, csrf, sid2, csrf2) - } - if setCookie2 != nil { - t.Fatalf("live session should not Set-Cookie again") - } -} diff --git a/plugins/web/internal/httpx/inspection.go b/plugins/web/internal/httpx/inspection.go deleted file mode 100755 index 0b225be..0000000 --- a/plugins/web/internal/httpx/inspection.go +++ /dev/null @@ -1,171 +0,0 @@ -package httpx - -import ( - "fmt" - "net/http" - "regexp" - "sort" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/artifact" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" - "github.com/marqdo/marqdo/plugins/web/internal/oidc" -) - -type recordedMux struct { - validate *http.ServeMux - patterns []string -} - -func (mux *recordedMux) Handle(pattern string, _ http.Handler) { - // Validate registration conflicts without retaining or running handlers. - mux.validate.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {}) - mux.patterns = append(mux.patterns, pattern) -} -func (mux *recordedMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) { - mux.Handle(pattern, http.HandlerFunc(handler)) -} - -var tailWildcard = regexp.MustCompile(`\{([^{}]+)\.\.\.\}`) - -func inspectionPath(path string) string { - path = strings.TrimSuffix(path, "{$}") - return tailWildcard.ReplaceAllString(path, "{*$1}") -} - -// InspectApp executes only trusted registration logic. It does not create a -// session, reset global runtime state, query a DB, run Documents or listen. -func InspectApp(bag map[string]any) (report map[string]any, err error) { - defer func() { - if recovered := recover(); recovered != nil { - report = nil - err = fmt.Errorf("web.inspect: invalid route registration: %v", recovered) - } - }() - if bag == nil { - bag = map[string]any{} - } - routes := routeMapOf(bag, "routes") - page, _ := bag["page"].(map[string]any) - forms := map[string]any{} - if existing, ok := bag["forms"].(map[string]any); ok { - for key, value := range existing { - forms[key] = value - } - } - collectPageForms(page, forms) - for _, value := range routes { - if page, ok := value.(map[string]any); ok { - collectPageForms(page, forms) - } - } - root := strOpt(bag, "artifact_root", "") - staticDir := strOpt(bag, "static_dir", "") - if staticDir != "" { - staticDir = resolvePath(staticDir, root) - } - icons, err := iconRoutesFromBag(bag, root, staticDir) - if err != nil { - return nil, err - } - st := &state{ - page: page, routes: routes, forms: forms, mw: middleware.Parse(bag), entryDir: root, - iconRoutes: icons, redirects: redirectsOf(bag), sitemapRoutes: sitemapRoutesOf(bag), - robotsBody: robotsBodyOf(bag), page404: pageOf(bag, "page_404"), page500: pageOf(bag, "page_500"), - uploadRoutes: routeMapOf(bag, "upload_routes"), downloadRoutes: routeMapOf(bag, "download_routes"), - wsRoutes: routeMapOf(bag, "ws_routes"), galleryRoutes: routeMapOf(bag, "gallery_routes"), - proxyRoutes: routeMapOf(bag, "proxy_routes"), invokeRoutes: routeMapOf(bag, "invoke_routes"), - artifactRoutes: routeMapOf(bag, "artifact_routes"), auth: authConfigOf(bag), oidc: oidc.ParseConfig(bag), - } - // Only a nonempty DB URL determines whether DB-backed routes are enabled. - // Its existence and contents are intentionally not inspected here. - st.dbURL = dbURLOf(bag) - staticMount := app.NormalizeStaticMount(strOpt(bag, "static_mount", "/static")) - mux := &recordedMux{validate: http.NewServeMux()} - st.registerRoutes(mux, staticDir, staticMount, false) - report = artifact.InspectBag(bag, nil) - declarations := map[string]map[string]any{} - byPath := map[string]map[string]any{} - for _, row := range report["declared"].([]map[string]any) { - path := inspectionPath(goMuxPattern(fmt.Sprint(row["path"]))) - method := fmt.Sprint(row["method"]) - declarations[method+" "+path] = row - if _, exists := byPath[path]; !exists { - byPath[path] = row - } - } - // Classification uses the explicitly supplied Resource paths; the method - // and presence still come from the actual recorded registration. - for group, kind := range map[string]string{ - "ws_routes": "websocket", "upload_routes": "upload", "download_routes": "download", - "gallery_routes": "gallery", "proxy_routes": "proxy", "redirects": "redirect", "sitemap_routes": "sitemap", - } { - for key, value := range routeMapOf(bag, group) { - spec, _ := value.(map[string]any) - path := strOpt(spec, "path", key) - if parts := strings.SplitN(path, " ", 2); len(parts) == 2 { - path = parts[1] - } - path = inspectionPath(goMuxPattern(path)) - byPath[path] = map[string]any{"path": path, "kind": kind} - } - } - for _, query := range st.mw.JSONRoutes { - row := map[string]any{"path": query.Path, "method": query.Method, "kind": "data_query"} - declarations[query.Method+" "+query.Path] = row - } - var declared, system []map[string]any - seen := map[string]bool{} - for _, pattern := range mux.patterns { - method, path := "*", pattern - if parts := strings.SplitN(pattern, " ", 2); len(parts) == 2 { - method, path = parts[0], parts[1] - } - path = inspectionPath(path) - if method == "*" && (path == staticMount || path == staticMount+"/") && strOpt(bag, "static_dir", "") != "" { - method = "GET|HEAD" - } - key := method + " " + path - if seen[key] { - continue - } - seen[key] = true - row := map[string]any{"method": method, "path": path, "kind": "system"} - source, found := declarations[key] - if !found { - source, found = byPath[path] - } - if found { - for key, value := range source { - if key != "method" && key != "path" { - row[key] = value - } - } - declared = append(declared, row) - } else { - system = append(system, row) - } - } - less := func(rows []map[string]any) { - sort.Slice(rows, func(i, j int) bool { - a, b := fmt.Sprint(rows[i]["path"]), fmt.Sprint(rows[j]["path"]) - if a != b { - return a < b - } - return fmt.Sprint(rows[i]["method"]) < fmt.Sprint(rows[j]["method"]) - }) - } - less(declared) - less(system) - if declared == nil { - declared = []map[string]any{} - } - if system == nil { - system = []map[string]any{} - } - report["scope"] = "registered" - report["declared"] = declared - report["system"] = system - return report, nil -} diff --git a/plugins/web/internal/httpx/inspection_test.go b/plugins/web/internal/httpx/inspection_test.go deleted file mode 100755 index 735210f..0000000 --- a/plugins/web/internal/httpx/inspection_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package httpx - -import ( - "encoding/json" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/form" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func TestInspectionUsesActualRegistrationsAfterResourceBindingsWithoutExecutingThem(t *testing.T) { - filename := filepath.Join(t.TempDir(), "must-not-create.db") - bag := app.New(map[string]any{"page": map[string]any{"title": "Home"}, - "db": map[string]any{"url": "sqlite:" + filename}, "admin": true}) - bag["artifact_declared"] = []any{map[string]any{"method": "GET", "path": "/", "kind": "web", "file": "index.mq.md"}} - // A cached observation is deliberately stale and must never be returned. - bag["inspect"] = map[string]any{"declared": []any{map[string]any{"path": "/stale"}}} - var err error - bag, err = app.Route(bag, "/post/{id}", map[string]any{"title": "Post"}) - if err != nil { - t.Fatal(err) - } - before, err := InspectApp(bag) - if err != nil { - t.Fatal(err) - } - bag, err = app.Auth(bag, []any{map[string]any{"username": "fixture", "password": "never-return-this-secret"}}, map[string]any{"login_path": "/members/login"}) - if err != nil { - t.Fatal(err) - } - bag, err = app.MountForm(bag, "article", form.New("articles", "insert", "")) - if err != nil { - t.Fatal(err) - } - bag["ws_routes"] = map[string]any{"/live/{id}": map[string]any{"mode": "echo"}} - bag["middleware"] = map[string]any{"json_routes": map[string]any{"api/items": map[string]any{"table": "items", "method": "GET"}}} - bag["artifact_routes"] = map[string]any{"GET /api/ping": map[string]any{"method": "GET", "path": "/api/ping", "file": "/never-run.mq.md"}} - bag["static_dir"] = "." - bag["static_mount"] = "/assets" - session.Configure(session.Config{TTLSec: 3600}) - session.Reset(3600) - sid := session.NewID(3600) - session.SetValue(sid, "inspection_marker", "retained") - report, err := InspectApp(bag) - if err != nil { - t.Fatal(err) - } - if report["scope"] != "registered" { - t.Fatal(report) - } - type route struct{ method, path string } - observed := map[route]string{} - for _, group := range []string{"declared", "system"} { - for _, row := range report[group].([]map[string]any) { - key := route{row["method"].(string), row["path"].(string)} - if _, seen := observed[key]; seen { - t.Fatalf("duplicate registered route: %#v", key) - } - observed[key] = group - } - } - for _, key := range []route{{"GET", "/"}, {"GET", "/post/{id}"}, {"GET", "/live/{id}"}, {"GET", "/api/items"}, {"GET", "/api/ping"}} { - if observed[key] != "declared" { - t.Fatalf("missing current Resource declaration %#v: %#v", key, report) - } - } - for _, key := range []route{{"POST", "/_md"}, {"GET", "/_form/{id}"}, {"POST", "/_form/{id}"}, - {"GET", "/post/{id}/_part/{part}"}, {"GET", "/members/login"}, {"POST", "/members/login"}, - {"GET", "/admin/login"}, {"GET", "/admin"}, {"GET", "/admin/"}, {"GET|HEAD", "/assets/"}} { - if observed[key] != "system" { - t.Fatalf("missing actual system route %#v: %#v", key, report) - } - } - encoded, _ := json.Marshal(report) - if strings.Contains(string(encoded), "never-return-this-secret") || strings.Contains(string(encoded), "/stale") { - t.Fatalf("inspection leaked unrelated app state: %s", encoded) - } - if value, ok := session.GetValue(sid, "inspection_marker"); !ok || value != "retained" { - t.Fatal("inspection reset runtime sessions") - } - if _, err := os.Stat(filename); !os.IsNotExist(err) { - t.Fatalf("inspection opened a database: %v", err) - } - prior, _ := json.Marshal(before) - if strings.Contains(string(prior), "/live/") { - t.Fatal("inspection mutated an earlier returned observation") - } -} - -func TestInspectionRejectsActualRouteConflictsWithoutStartingTheServer(t *testing.T) { - bag := app.New(map[string]any{"page": map[string]any{}}) - bag["routes"] = map[string]any{"/_md": map[string]any{}} - bag["artifact_routes"] = map[string]any{"POST /_md": map[string]any{"method": "POST", "path": "/_md", "file": "never-run.mq.md"}} - if _, err := InspectApp(bag); err == nil || !strings.Contains(err.Error(), "invalid route registration") { - t.Fatalf("conflicting routes were advertised as usable: %v", err) - } -} diff --git a/plugins/web/internal/httpx/listen.go b/plugins/web/internal/httpx/listen.go deleted file mode 100755 index f081991..0000000 --- a/plugins/web/internal/httpx/listen.go +++ /dev/null @@ -1,1144 +0,0 @@ -// Package httpx implements blocking HTTP listen for the Marqdo web app bag. -package httpx - -import ( - "bufio" - "compress/gzip" - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "net/url" - "os" - "os/signal" - "path/filepath" - "strings" - "syscall" - "time" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/artifact" - "github.com/marqdo/marqdo/plugins/web/internal/assets" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/form" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" - "github.com/marqdo/marqdo/plugins/web/internal/oidc" - "github.com/marqdo/marqdo/plugins/web/internal/ratelimit" - "github.com/marqdo/marqdo/plugins/web/internal/rbac" - "github.com/marqdo/marqdo/plugins/web/internal/render" - "github.com/marqdo/marqdo/plugins/web/internal/session" - "github.com/marqdo/marqdo/plugins/web/internal/sitemap" - "github.com/marqdo/marqdo/plugins/web/internal/tenant" -) - -// NewHandler builds the HTTP handler for an app bag (no listen). -// Relative static_dir is resolved against entryDir when non-empty, else cwd. -func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { - if appBag == nil { - appBag = map[string]any{} - } - authCfg := authConfigOf(appBag) - dbURL := dbURLOf(appBag) - if authCfg.rbac && dbURL != "" { - if err := rbac.EnsureSchema(dbURL); err != nil { - return nil, fmt.Errorf("rbac ensure: %w", err) - } - } - session.Configure(session.Config{ - DBURL: dbURL, - RedisURL: sessionURLOf(appBag), - TTLSec: authCfg.sessionTTL, - CookieSecure: authCfg.cookieSecure, - }) - session.Reset(authCfg.sessionTTL) - ratelimit.Reset() - - page, _ := appBag["page"].(map[string]any) - if page == nil { - page = map[string]any{} - } - if _, ok := page["asset_version"]; !ok { - if v := strOpt(appBag, "asset_version", ""); v != "" { - page["asset_version"] = v - } - } - routes := map[string]any{} - if r, ok := appBag["routes"].(map[string]any); ok { - routes = r - } - if av, ok := page["asset_version"]; ok { - for _, p := range routes { - if pm, ok := p.(map[string]any); ok { - if _, has := pm["asset_version"]; !has { - pm["asset_version"] = av - } - } - } - } - forms := map[string]any{} - if f, ok := appBag["forms"].(map[string]any); ok { - forms = cloneMap(f) - } - collectPageForms(page, forms) - for _, p := range routes { - if pm, ok := p.(map[string]any); ok { - collectPageForms(pm, forms) - } - } - - staticMount := app.NormalizeStaticMount(strOpt(appBag, "static_mount", "/static")) - var staticDir string - if s, ok := appBag["static_dir"].(string); ok && strings.TrimSpace(s) != "" { - staticDir = resolvePath(strings.TrimSpace(s), entryDir) - fi, err := os.Stat(staticDir) - if err != nil || !fi.IsDir() { - return nil, fmt.Errorf("static dir `%s` is not a directory", staticDir) - } - } - - mw := middleware.Parse(appBag) - siteHead := assets.HeadLinksFromJSON(appBag["site_head"]) - iconRoutes, err := iconRoutesFromBag(appBag, entryDir, staticDir) - if err != nil { - return nil, err - } - st := &state{ - page: page, - dbURL: dbURL, - routes: routes, - forms: forms, - mw: mw, - entryDir: entryDir, - siteHead: siteHead, - iconRoutes: iconRoutes, - redirects: redirectsOf(appBag), - sitemapRoutes: sitemapRoutesOf(appBag), - robotsBody: robotsBodyOf(appBag), - page404: pageOf(appBag, "page_404"), - page500: pageOf(appBag, "page_500"), - uploadRoutes: routeMapOf(appBag, "upload_routes"), - downloadRoutes: routeMapOf(appBag, "download_routes"), - wsRoutes: routeMapOf(appBag, "ws_routes"), - galleryRoutes: routeMapOf(appBag, "gallery_routes"), - proxyRoutes: routeMapOf(appBag, "proxy_routes"), - invokeRoutes: routeMapOf(appBag, "invoke_routes"), - artifactRoutes: routeMapOf(appBag, "artifact_routes"), - auth: authCfg, - oidc: oidc.ParseConfig(appBag), - tenant: tenant.FromBag(appBag), - } - - mux := http.NewServeMux() - st.registerRoutes(mux, staticDir, staticMount, true) - - handler := withMiddleware(mux, mw) - handler = withRBAC(handler, authCfg.gates, authCfg.loginPath) - handler = withTenant(handler, st.tenant) - handler = withStripTrailingSlash(handler) - return handler, nil -} - -// routeRegistrar is shared by the real server and its read-only inventory. -// Recording registrations does not invoke any captured handler. -type routeRegistrar interface { - Handle(string, http.Handler) - HandleFunc(string, func(http.ResponseWriter, *http.Request)) -} - -func (st *state) registerRoutes(mux routeRegistrar, staticDir, staticMount string, logSetup bool) { - mux.HandleFunc("GET /{$}", st.handleHome) - // Part slot uses {part} (not {id}) so dynamic routes like /desk/posts/{id} - // do not collide with Go ServeMux duplicate wildcard names. - mux.HandleFunc("GET /_part/{part}", st.handleHomePart) - mux.HandleFunc("GET /_form/{id}", st.handleFormGet) - mux.HandleFunc("POST /_form/{id}", st.handleFormPost) - mux.HandleFunc("POST /_md", st.handleMarkdownPreview) - - paths := sortedKeys(st.routes) - for _, p := range paths { - routePath := p - pageV, _ := st.routes[routePath].(map[string]any) - if pageV == nil { - pageV = map[string]any{} - } - if strings.Contains(routePath, "{") { - mux.HandleFunc("GET "+goMuxPattern(routePath), st.makeDynamicPage(pageV, routePath)) - mux.HandleFunc("GET "+goMuxPattern(routePath)+"/_part/{part}", st.makeDynamicPart(pageV, routePath)) - } else { - pv := pageV - mux.HandleFunc("GET "+routePath, func(w http.ResponseWriter, r *http.Request) { - st.writePage(w, r, pv) - }) - mux.HandleFunc("GET "+routePath+"/_part/{part}", func(w http.ResponseWriter, r *http.Request) { - st.writePart(w, r, pv, r.PathValue("part")) - }) - } - } - - for _, jr := range st.mw.JSONRoutes { - route := jr - pattern := route.Method + " " + route.Path - mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - st.handleJSON(w, r, route) - }) - } - - // Icon routes before the static prefix so /static/favicon.svg does not - // conflict with Go 1.22+ ServeMux method/path overlap rules. - for _, ir := range st.iconRoutes { - url := ir.URL - path := ir.Path - ct := ir.ContentType - if staticDir != "" && (url == staticMount || strings.HasPrefix(url, staticMount+"/")) { - // FileServer under staticMount already serves these paths. - if logSetup { - fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount) - } - continue - } - if logSetup { - fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct) - } - mux.HandleFunc("GET "+url, func(w http.ResponseWriter, r *http.Request) { - st.serveIcon(w, path, ct) - }) - mux.HandleFunc("HEAD "+url, func(w http.ResponseWriter, r *http.Request) { - st.serveIcon(w, path, ct) - }) - } - - if staticDir != "" { - if logSetup { - fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir) - } - fs := http.StripPrefix(staticMount, http.FileServer(http.Dir(staticDir))) - // Register without method so GET+HEAD share one pattern (avoids conflicts - // with more-specific GET/HEAD icon paths under the same prefix). - serveStatic := func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet && r.Method != http.MethodHead { - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - // Long browser cache; FileServer still honors Last-Modified / 304. - // Prefer ?v= / asset_version on HTML refs when assets change. - w.Header().Set("Cache-Control", "public, max-age=604800") - fs.ServeHTTP(w, r) - } - mux.Handle(staticMount+"/", http.HandlerFunc(serveStatic)) - mux.Handle(staticMount, http.HandlerFunc(serveStatic)) - } - - for _, from := range sortedKeys(st.redirects) { - spec, _ := st.redirects[from].(map[string]any) - to := strOpt(spec, "to", "/") - permanent := boolish(spec["permanent"]) - mux.HandleFunc("GET "+from, func(w http.ResponseWriter, r *http.Request) { - code := http.StatusTemporaryRedirect - if permanent { - code = http.StatusMovedPermanently - } - http.Redirect(w, r, to, code) - }) - } - - for _, path := range sortedKeys(st.sitemapRoutes) { - cfg, _ := st.sitemapRoutes[path].(map[string]any) - mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) { - st.writeSitemap(w, cfg) - }) - } - - if st.robotsBody != "" { - body := st.robotsBody - mux.HandleFunc("GET /robots.txt", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - _, _ = io.WriteString(w, body) - }) - } - - st.mountWSRoutes(mux) - st.mountUploadRoutes(mux) - st.mountDownloadRoutes(mux) - st.mountGalleryRoutes(mux) - st.mountProxyRoutes(mux) - st.mountInvokeRoutes(mux) - st.mountRuntimeRoutes(mux) - st.mountArtifactRoutes(mux) - st.mountAuthRoutes(mux) - - mux.HandleFunc("/{path...}", st.handleNotFound) - -} - -// Listen binds host:port from the app bag and serves until interrupt/kill. -func Listen(appBag map[string]any, entryDir string) (map[string]any, error) { - if appBag == nil { - appBag = map[string]any{} - } - handler, err := NewHandler(appBag, entryDir) - if err != nil { - return nil, err - } - host := strOpt(appBag, "host", "127.0.0.1") - port := intFrom(appBag["port"], 18081) - addr := fmt.Sprintf("%s:%d", host, port) - ln, err := net.Listen("tcp", addr) - if err != nil { - return nil, fmt.Errorf("bind %s: %w", addr, err) - } - fmt.Fprintf(os.Stderr, "marqdo web listening on http://%s\n", addr) - - srv := &http.Server{Handler: handler} - errCh := make(chan error, 1) - go func() { - errCh <- srv.Serve(ln) - }() - - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) - defer signal.Stop(sigCh) - select { - case sig := <-sigCh: - _ = srv.Close() - fmt.Fprintf(os.Stderr, "marqdo web shutdown (%v)\n", sig) - case err := <-errCh: - if err != nil && err != http.ErrServerClosed { - return nil, fmt.Errorf("serve: %w", err) - } - } - return map[string]any{"ok": true}, nil -} - -type state struct { - page map[string]any - dbURL string - routes map[string]any - forms map[string]any - mw middleware.Config - entryDir string - siteHead []assets.HeadLink - iconRoutes []assets.IconRoute - redirects map[string]any - sitemapRoutes map[string]any - robotsBody string - page404 map[string]any - page500 map[string]any - uploadRoutes map[string]any - downloadRoutes map[string]any - wsRoutes map[string]any - galleryRoutes map[string]any - proxyRoutes map[string]any - invokeRoutes map[string]any - artifactRoutes map[string]any - auth authConfig - oidc oidc.Config - tenant tenant.Config -} - -func (st *state) handleHome(w http.ResponseWriter, r *http.Request) { - st.writePage(w, r, st.page) -} - -func (st *state) handleHomePart(w http.ResponseWriter, r *http.Request) { - st.writePart(w, r, st.page, r.PathValue("part")) -} - -func (st *state) handleMarkdownPreview(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - html := render.MarkdownToHTML(string(body)) - if html == "" { - html = `

      预览

      ` - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, html) -} - -func (st *state) preparePage(page map[string]any, r *http.Request) map[string]any { - p := cloneMap(page) - assets.MergeSiteHead(p, st.siteHead) - if r != nil { - withNavAuth(p, r.Header.Get("Cookie")) - params, _ := p["params"].(map[string]any) - if params == nil { - params = map[string]any{} - } else { - params = cloneMap(params) - } - for k, vs := range r.URL.Query() { - if len(vs) == 0 { - continue - } - if _, exists := params[k]; !exists { - params[k] = vs[0] - } - } - p["params"] = params - } - return p -} - -// attachCSRF stamps page._csrf so custom login/register pages expose a token -// in meta and (via InjectAuthFields) in POST forms — progressive enhancement, no author JS. -func (st *state) attachCSRF(page map[string]any, r *http.Request) *string { - if page == nil || r == nil { - return nil - } - if st.auth.users == nil && !st.auth.rbac && !st.oidcEnabled() { - return nil - } - _, csrf, setCookie := resolveSession(r) - if csrf != "" { - page["_csrf"] = csrf - } - return setCookie -} - -func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[string]any) { - if st.oidcEnabled() && st.isOIDCEntryPath(r.URL.Path) { - st.handleOIDCStart(w, r) - return - } - p := st.preparePage(page, r) - if st.authEntryRedirect(w, r, p) { - return - } - if next := safeAuthNext(r.URL.Query().Get("next")); next != "" { - p["_auth_next"] = next - } - setCookie := st.attachCSRF(p, r) - html := "" - if nodes, ok := p["artifact_nodes"]; ok { - document, err := artifact.RenderViewDocument(strOpt(p, "title", ""), nodes, func(resource map[string]any) (string, error) { - return st.renderViewResource(resource, p, r) - }) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - html = document - } else { - html = render.RenderPage(p, st.dbURL, "") - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - appendSetCookie(w, setCookie) - _, _ = io.WriteString(w, html) -} - -func (st *state) writePart(w http.ResponseWriter, r *http.Request, page map[string]any, id string) { - p := st.preparePage(page, r) - setCookie := st.attachCSRF(p, r) - html := "" - if nodes, ok := p["artifact_nodes"]; ok { - selected, found, err := artifact.FindSlot(nodes, id) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !found { - if id != "main" { - http.NotFound(w, r) - return - } - // Keep the existing main-fragment fallback for a View without a - // named main region; never expose the Document's program source. - selected = nodes - } - html, err = artifact.RenderNodesWithResources(selected, func(resource map[string]any) (string, error) { - return st.renderViewResource(resource, p, r) - }) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - } else { - html = render.RenderPage(p, st.dbURL, id) - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - appendSetCookie(w, setCookie) - _, _ = io.WriteString(w, html) -} - -func (st *state) serveIcon(w http.ResponseWriter, path, contentType string) { - data, err := os.ReadFile(path) - if err != nil { - http.NotFound(w, nil) - return - } - w.Header().Set("Content-Type", contentType) - w.Header().Set("Cache-Control", "public, max-age=86400") - w.WriteHeader(http.StatusOK) - _, _ = w.Write(data) -} - -func (st *state) writeSitemap(w http.ResponseWriter, cfg map[string]any) { - base := strOpt(cfg, "base", "") - items := cfg["items"] - if tbl, ok := cfg["table"].(string); ok && tbl != "" && st.dbURL != "" { - locCol := strOpt(cfg, "loc", "path") - limit := int64(1000) - if n, ok := cfg["limit"].(float64); ok && n > 0 { - limit = int64(n) - } - opts := db.SelectOpts{} - out, err := db.Select(st.dbURL, tbl, limit, opts) - if err == nil { - if rows, ok := out["rows"].([]any); ok { - norm := make([]any, 0, len(rows)) - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - cp := cloneMap(m) - if _, has := cp["loc"]; !has { - if v, ok := cp[locCol]; ok { - cp["loc"] = v - } - } - norm = append(norm, cp) - } - items = norm - } - } - } - xml := sitemap.BuildSitemap(base, items) - w.Header().Set("Content-Type", "application/xml; charset=utf-8") - _, _ = io.WriteString(w, xml) -} - -func (st *state) handleNotFound(w http.ResponseWriter, r *http.Request) { - if st.page404 != nil { - html := render.RenderPage(st.preparePage(st.page404, r), st.dbURL, "") - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.WriteHeader(http.StatusNotFound) - _, _ = io.WriteString(w, html) - return - } - http.NotFound(w, r) -} - -func (st *state) makeDynamicPage(page map[string]any, pattern string) http.HandlerFunc { - paramNames := pathParamNames(pattern) - return func(w http.ResponseWriter, r *http.Request) { - p := cloneMap(page) - params := map[string]any{} - for _, name := range paramNames { - params[name] = r.PathValue(name) - } - injectParams(p, params) - st.writePage(w, r, p) - } -} - -func (st *state) makeDynamicPart(page map[string]any, pattern string) http.HandlerFunc { - paramNames := pathParamNames(pattern) - return func(w http.ResponseWriter, r *http.Request) { - p := cloneMap(page) - params := map[string]any{} - for _, name := range paramNames { - params[name] = r.PathValue(name) - } - injectParams(p, params) - st.writePart(w, r, p, r.PathValue("part")) - } -} - -func (st *state) handleFormGet(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - frm, ok := st.forms[id].(map[string]any) - if !ok { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, fmt.Sprintf("

      unknown form %s

      ", id)) - return - } - page := map[string]any{} - setCookie := st.attachCSRF(page, r) - csrf, _ := page["_csrf"].(string) - html := form.Render(frm, id, nil, nil, csrf) - appendSetCookie(w, setCookie) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, html) -} - -func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - frm, ok := st.forms[id].(map[string]any) - if !ok { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, fmt.Sprintf("

      unknown form %s

      ", id)) - return - } - if st.dbURL == "" { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, "

      no database

      ") - return - } - if err := r.ParseForm(); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - csrf := "" - if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() { - sid, token, setCookie := resolveSession(r) - appendSetCookie(w, setCookie) - csrf = token - _, hadCookie := session.IDFromCookie(r.Header.Get("Cookie")) - if hadCookie || r.FormValue("_csrf") != "" { - if !session.ValidateCSRF(sid, r.FormValue("_csrf")) { - http.Error(w, "Invalid or missing CSRF token", http.StatusForbidden) - return - } - } - } - data := map[string]any{} - for k, vs := range r.PostForm { - if len(vs) > 0 { - data[k] = vs[0] - } - } - if st.tenant.Enabled() && st.tenant.DefaultScope { - if tid := tenant.FromContext(r.Context()); tid != "" { - data = tenant.StampRow(data, st.tenant.Column, tid) - } - } - ctx := st.requestContext(r, data) - delete(data, "_mq_params") - delete(data, "_mq_return") - delete(data, "_csrf") - form.ApplySources(frm, data, ctx) - res, err := form.Submit(frm, data, st.dbURL) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if ok, _ := res["ok"].(bool); ok { - // Prefer an explicit form redirect (e.g. cancel_href list URL) over the - // composing page path stamped as _mq_return. - redir := strOpt(res, "redirect", "/") - if (redir == "" || redir == "/") && ctx.ReturnPath != "" && strOpt(frm, "cancel_href", "") == "" { - redir = ctx.ReturnPath - } - http.Redirect(w, r, redir, http.StatusSeeOther) - return - } - html := form.RenderBodyCtx(frm, id, data, res["errors"], csrf, ctx) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = io.WriteString(w, html) -} - -func (st *state) requestContext(r *http.Request, data map[string]any) *form.RequestContext { - ctx := &form.RequestContext{ - Username: session.UsernameFromCookie(r.Header.Get("Cookie")), - Path: r.URL.Path, - Method: r.Method, - } - if data != nil { - if p := form.ParseMQParams(fmt.Sprint(data["_mq_params"])); len(p) > 0 { - ctx.Params = p - } - if ret, ok := data["_mq_return"].(string); ok { - if back := sameHostPath(ret, r.Host); back != "" { - ctx.ReturnPath = back - } else if strings.HasPrefix(ret, "/") && !strings.HasPrefix(ret, "//") { - ctx.ReturnPath = ret - } - } - } - if ctx.ReturnPath == "" { - if back := sameHostPath(r.Referer(), r.Host); back != "" { - ctx.ReturnPath = back - } - } - return ctx -} - -func sameHostPath(raw, host string) string { - raw = strings.TrimSpace(raw) - if raw == "" { - return "" - } - u, err := url.Parse(raw) - if err != nil || u == nil { - return "" - } - if u.Host != "" && host != "" && !strings.EqualFold(u.Host, host) { - return "" - } - path := u.Path - if path == "" { - path = "/" - } - if u.RawQuery != "" { - path += "?" + u.RawQuery - } - if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "//") { - return "" - } - return path -} - -func (st *state) handleJSON(w http.ResponseWriter, r *http.Request, route middleware.JSONRouteMount) { - if st.dbURL == "" { - writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "no database"}) - return - } - where := route.Where - if (route.TenantScope || st.tenant.DefaultScope) && st.tenant.Enabled() { - tid := tenant.FromContext(r.Context()) - if tid == "" { - writeJSON(w, http.StatusBadRequest, map[string]any{"error": "tenant required"}) - return - } - where = tenant.MergeWhere(where, st.tenant.Column, tid) - } - opts := db.SelectOpts{Where: where, Order: route.Order} - out, err := db.Select(st.dbURL, route.Table, route.Limit, opts) - if err != nil { - writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()}) - return - } - writeJSON(w, http.StatusOK, out) -} - -func withTenant(next http.Handler, cfg tenant.Config) http.Handler { - if !cfg.Enabled() { - return next - } - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - id := tenant.Resolve(r, cfg) - ctx := tenant.WithContext(r.Context(), id) - next.ServeHTTP(w, r.WithContext(ctx)) - }) -} - -// withStripTrailingSlash rewrites request URLs so that paths like /post/foo/ -// are routed as /post/foo. The root path "/" is left unchanged. -func withStripTrailingSlash(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - path := r.URL.Path - if len(path) > 1 && path[len(path)-1] == '/' { - r.URL.Path = strings.TrimRight(path, "/") - if r.URL.Path == "" { - r.URL.Path = "/" - } - } - next.ServeHTTP(w, r) - }) -} - -func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { - h := next - if mw.BodyLimit != nil && *mw.BodyLimit > 0 { - limit := int64(*mw.BodyLimit) - inner := h - h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.ContentLength > limit { - http.Error(w, "request body too large", http.StatusRequestEntityTooLarge) - return - } - r.Body = http.MaxBytesReader(w, r.Body, limit) - inner.ServeHTTP(w, r) - }) - } - if mw.CacheControl != "" { - cc := mw.CacheControl - inner := h - h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", cc) - inner.ServeHTTP(w, r) - }) - } - if mw.Compress { - inner := h - h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { - inner.ServeHTTP(w, r) - return - } - setHeader(w, "content-encoding", "gzip") - w.Header().Add("Vary", "Accept-Encoding") - gz := gzip.NewWriter(w) - defer gz.Close() - inner.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, w: gz}, r) - }) - } - for _, hv := range mw.Security { - name, ok := securityHeaderName(hv[0]) - if !ok { - continue - } - val := hv[1] - inner := h - h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - setHeader(w, strings.ToLower(name), val) - inner.ServeHTTP(w, r) - }) - } - if mw.CORS != nil { - c := mw.CORS - inner := h - h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - applyCORS(w, r, c) - if r.Method == http.MethodOptions { - w.WriteHeader(http.StatusNoContent) - return - } - inner.ServeHTTP(w, r) - }) - } - if mw.AccessLog { - inner := h - h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - start := time.Now() - rw := &statusRecorder{ResponseWriter: w, status: 200} - inner.ServeHTTP(rw, r) - fmt.Fprintf(os.Stderr, "marqdo web %s %s %d %dms\n", - r.Method, r.URL.Path, rw.status, time.Since(start).Milliseconds()) - }) - } - return h -} - -func applyCORS(w http.ResponseWriter, r *http.Request, c *middleware.CORSConfig) { - origin := r.Header.Get("Origin") - if len(c.AllowOrigins) == 0 { - setHeader(w, "access-control-allow-origin", "*") - } else if origin != "" { - for _, o := range c.AllowOrigins { - if o == origin { - setHeader(w, "access-control-allow-origin", origin) - break - } - } - } - if len(c.Methods) == 0 { - setHeader(w, "access-control-allow-methods", "*") - } else { - setHeader(w, "access-control-allow-methods", strings.Join(unique(c.Methods), ", ")) - } - if len(c.Headers) == 0 { - setHeader(w, "access-control-allow-headers", "*") - } else { - setHeader(w, "access-control-allow-headers", strings.Join(unique(c.Headers), ", ")) - } - if len(c.ExposeHeaders) > 0 { - expose := strings.ToLower(strings.Join(unique(c.ExposeHeaders), ", ")) - setHeader(w, "access-control-expose-headers", expose) - } - if c.Credentials { - setHeader(w, "access-control-allow-credentials", "true") - } -} - -func setHeader(w http.ResponseWriter, name, value string) { - w.Header()[name] = []string{value} -} - -func securityHeaderName(raw string) (string, bool) { - n := strings.ToLower(strings.ReplaceAll(raw, "_", "-")) - switch n { - case "x-frame-options": - return "X-Frame-Options", true - case "content-security-policy": - return "Content-Security-Policy", true - case "x-content-type-options": - return "X-Content-Type-Options", true - case "referrer-policy": - return "Referrer-Policy", true - case "strict-transport-security", "hsts": - return "Strict-Transport-Security", true - case "x-xss-protection": - return "X-XSS-Protection", true - default: - return "", false - } -} - -type gzipResponseWriter struct { - http.ResponseWriter - w *gzip.Writer -} - -func (g *gzipResponseWriter) Write(b []byte) (int, error) { return g.w.Write(b) } - -func (g *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if h, ok := g.ResponseWriter.(http.Hijacker); ok { - return h.Hijack() - } - return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking") -} - -func (g *gzipResponseWriter) Flush() { - _ = g.w.Flush() - if f, ok := g.ResponseWriter.(http.Flusher); ok { - f.Flush() - } -} - -type statusRecorder struct { - http.ResponseWriter - status int -} - -func (s *statusRecorder) WriteHeader(code int) { - s.status = code - s.ResponseWriter.WriteHeader(code) -} - -func (s *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if h, ok := s.ResponseWriter.(http.Hijacker); ok { - return h.Hijack() - } - return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking") -} - -// Flush must be forwarded so sse-live / EventBus token streams are not buffered -// behind access-log wrapping (otherwise clients see 0 bytes until the invoke ends). -func (s *statusRecorder) Flush() { - if f, ok := s.ResponseWriter.(http.Flusher); ok { - f.Flush() - } -} - -func writeJSON(w http.ResponseWriter, code int, v any) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(code) - _ = json.NewEncoder(w).Encode(v) -} - -func collectPageForms(page map[string]any, forms map[string]any) { - if page == nil { - return - } - if obj, ok := page["forms"].(map[string]any); ok { - for k, v := range obj { - forms[k] = v - } - } - if id, ok := page["form_id"].(string); ok && id != "" { - if f := page["form"]; f != nil { - forms[id] = f - } - } -} - -func injectParams(page map[string]any, params map[string]any) { - page["params"] = params - // Stamp concrete path onto `_route` so part slot URLs use /post/slug not /post/{slug}. - if r, ok := page["_route"].(string); ok && r != "" && len(params) > 0 { - page["_route"] = render.ResolveRouteParams(r, params) - } - if parts, ok := page["parts"].(map[string]any); ok { - for k, cfg := range parts { - if m, ok := cfg.(map[string]any); ok { - cp := cloneMap(m) - cp["params"] = params - if r, ok := cp["_route"].(string); ok && r != "" { - cp["_route"] = render.ResolveRouteParams(r, params) - } - parts[k] = cp - } - } - } -} - -func pathParamNames(pattern string) []string { - var names []string - for _, seg := range strings.Split(pattern, "/") { - if strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}") { - name := strings.TrimSuffix(strings.TrimPrefix(seg, "{"), "}") - name = strings.TrimPrefix(name, "*") - // Include "id" — part slots use {part}, so route {id} is safe for PathValue. - if name != "" { - names = append(names, name) - } - } - } - return names -} - -func dbURLOf(appBag map[string]any) string { - if dbObj, ok := appBag["db"].(map[string]any); ok { - if s, ok := dbObj["url"].(string); ok && s != "" { - return s - } - } - if s, ok := appBag["db_url"].(string); ok { - return s - } - return "" -} - -func sessionURLOf(appBag map[string]any) string { - if s, ok := appBag["session_url"].(string); ok && s != "" { - return s - } - if auth, ok := appBag["auth"].(map[string]any); ok { - if s, ok := auth["session_url"].(string); ok && s != "" { - return s - } - } - return "" -} - -func resolvePath(p, entryDir string) string { - if filepath.IsAbs(p) { - return p - } - base := entryDir - if base == "" { - base, _ = os.Getwd() - } - return filepath.Join(base, p) -} - -func strOpt(m map[string]any, key, def string) string { - if s, ok := m[key].(string); ok && s != "" { - return s - } - return def -} - -func intFrom(v any, def int) int { - switch t := v.(type) { - case float64: - return int(t) - case int: - return t - case int64: - return int(t) - case string: - var n int - if _, err := fmt.Sscanf(t, "%d", &n); err == nil { - return n - } - } - return def -} - -func cloneMap(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} - -func sortedKeys(m map[string]any) []string { - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - for i := 0; i < len(keys); i++ { - for j := i + 1; j < len(keys); j++ { - if keys[j] < keys[i] { - keys[i], keys[j] = keys[j], keys[i] - } - } - } - return keys -} - -func unique(ss []string) []string { - seen := map[string]bool{} - var out []string - for _, s := range ss { - if !seen[s] { - seen[s] = true - out = append(out, s) - } - } - return out -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - return t == "true" || t == "True" || t == "1" || t == "yes" - case float64: - return t != 0 - } - return false -} - -func redirectsOf(appBag map[string]any) map[string]any { - if r, ok := appBag["redirects"].(map[string]any); ok { - return r - } - return map[string]any{} -} - -func sitemapRoutesOf(appBag map[string]any) map[string]any { - if r, ok := appBag["sitemap_routes"].(map[string]any); ok { - return r - } - return map[string]any{} -} - -func robotsBodyOf(appBag map[string]any) string { - if s, ok := appBag["robots_body"].(string); ok { - return s - } - return "" -} - -func pageOf(appBag map[string]any, key string) map[string]any { - if p, ok := appBag[key].(map[string]any); ok { - return p - } - return nil -} - -func iconRoutesFromBag(appBag map[string]any, entryDir, staticDir string) ([]assets.IconRoute, error) { - var routes []assets.IconRoute - if icons, ok := appBag["icons"].([]any); ok { - for _, ic := range icons { - m, ok := ic.(map[string]any) - if !ok { - continue - } - p := strOpt(m, "path", "") - url := strOpt(m, "url", "") - if p == "" || url == "" { - continue - } - if !strings.HasPrefix(url, "/") { - return nil, fmt.Errorf("icon url `%s` must start with /", url) - } - abs := resolvePath(p, entryDir) - fi, err := os.Stat(abs) - if err != nil || fi.IsDir() { - return nil, fmt.Errorf("icon file `%s` not found for `%s`", abs, url) - } - ct := strOpt(m, "type", "") - if ct == "" { - ct = assets.MimeForPath(p) - } - routes = append(routes, assets.IconRoute{ - URL: url, Path: abs, ContentType: ct, - }) - } - } - if len(routes) == 0 && staticDir != "" { - for _, name := range []string{"favicon.ico", "favicon.png", "favicon.svg"} { - p := filepath.Join(staticDir, name) - fi, err := os.Stat(p) - if err == nil && !fi.IsDir() { - routes = append(routes, assets.IconRoute{ - URL: "/favicon.ico", - Path: p, - ContentType: assets.MimeForPath(name), - }) - break - } - } - } - return routes, nil -} diff --git a/plugins/web/internal/httpx/listen_test.go b/plugins/web/internal/httpx/listen_test.go deleted file mode 100755 index a41c6bf..0000000 --- a/plugins/web/internal/httpx/listen_test.go +++ /dev/null @@ -1,216 +0,0 @@ -package httpx_test - -import ( - "io" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/httpx" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" -) - -func TestNewHandlerHomeRoutesStatic(t *testing.T) { - dir := t.TempDir() - pub := filepath.Join(dir, "public") - if err := os.MkdirAll(pub, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(pub, "hi.txt"), []byte("hello-static"), 0o644); err != nil { - t.Fatal(err) - } - - page := map[string]any{"title": "Home", "intro": "

      Home

      "} - a := app.New(map[string]any{"page": page}) - a, err := app.Static(a, pub, "/static") - if err != nil { - t.Fatal(err) - } - about := map[string]any{"title": "About", "intro": "

      About

      ", "_route": "/about"} - a, err = app.Route(a, "/about", about) - if err != nil { - t.Fatal(err) - } - - h, err := httpx.NewHandler(a, "") - if err != nil { - t.Fatal(err) - } - - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) - if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Home") { - t.Fatalf("home code=%d body=%q", rec.Code, rec.Body.String()) - } - - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about", nil)) - if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") { - t.Fatalf("about code=%d body=%q", rec.Code, rec.Body.String()) - } - - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/static/hi.txt", nil)) - if rec.Code != 200 { - t.Fatalf("static code=%d", rec.Code) - } - if cc := rec.Header().Get("Cache-Control"); !strings.Contains(cc, "max-age=") { - t.Fatalf("static cache-control=%q", cc) - } - b, _ := io.ReadAll(rec.Result().Body) - if string(b) != "hello-static" { - // httptest body is already in rec.Body - if rec.Body.String() != "hello-static" { - t.Fatalf("static body=%q", rec.Body.String()) - } - } -} - -func TestNewHandlerIconsRedirectSitemap404(t *testing.T) { - dir := t.TempDir() - iconPath := filepath.Join(dir, "favicon.png") - if err := os.WriteFile(iconPath, []byte("PNG"), 0o644); err != nil { - t.Fatal(err) - } - - page := map[string]any{"title": "W7", "intro": "

      home

      "} - nf := map[string]any{"title": "Not Found Page", "intro": "

      missing

      "} - a := app.New(map[string]any{"page": page}) - a, err := app.Icons(a, []any{ - map[string]any{"path": iconPath, "rel": "icon", "type": "image/png", "url": "/favicon.ico"}, - }) - if err != nil { - t.Fatal(err) - } - a, err = app.Redirect(a, "/legacy", "/", true) - if err != nil { - t.Fatal(err) - } - a, err = app.ErrorPage(a, 404, nf) - if err != nil { - t.Fatal(err) - } - items := []any{map[string]any{"loc": "/"}, map[string]any{"loc": "/about"}} - a, err = app.Sitemap(a, "/sitemap.xml", "http://example.com", "", "path", 100, items) - if err != nil { - t.Fatal(err) - } - a, err = app.Robots(a, "", "http://example.com/sitemap.xml") - if err != nil { - t.Fatal(err) - } - a, err = middleware.Configure(a, map[string]any{"cache_control": "public, max-age=120"}) - if err != nil { - t.Fatal(err) - } - - h, err := httpx.NewHandler(a, dir) - if err != nil { - t.Fatal(err) - } - - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/favicon.ico", nil)) - if rec.Code != 200 || !strings.Contains(rec.Header().Get("Content-Type"), "image/") { - t.Fatalf("favicon code=%d ct=%q", rec.Code, rec.Header().Get("Content-Type")) - } - - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/legacy", nil)) - if rec.Code != http.StatusMovedPermanently { - t.Fatalf("redirect code=%d", rec.Code) - } - - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/sitemap.xml", nil)) - if rec.Code != 200 || !strings.Contains(rec.Body.String(), "home

      "} - a := app.New(map[string]any{"page": page}) - about := map[string]any{"title": "About", "intro": "

      About

      ", "_route": "/about"} - var err error - a, err = app.Route(a, "/about", about) - if err != nil { - t.Fatal(err) - } - // Dynamic route: /post/{slug} - post := map[string]any{"title": "Post", "intro": "

      Post

      ", "_route": "/post/{slug}"} - a, err = app.Route(a, "/post/{slug}", post) - if err != nil { - t.Fatal(err) - } - - h, err := httpx.NewHandler(a, "") - if err != nil { - t.Fatal(err) - } - - // Static route: /about should work with and without trailing slash. - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about", nil)) - if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") { - t.Fatalf("about (no slash) code=%d body=%q", rec.Code, rec.Body.String()) - } - - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about/", nil)) - if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") { - t.Fatalf("about (trailing slash) code=%d body=%q", rec.Code, rec.Body.String()) - } - - // Dynamic route: /post/hello should work with and without trailing slash. - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/post/hello", nil)) - if rec.Code != 200 { - t.Fatalf("post/hello (no slash) code=%d body=%q", rec.Code, rec.Body.String()) - } - - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/post/hello/", nil)) - if rec.Code != 200 { - t.Fatalf("post/hello (trailing slash) code=%d body=%q", rec.Code, rec.Body.String()) - } - - // Root path "/" should still work. - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) - if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Home") { - t.Fatalf("root code=%d body=%q", rec.Code, rec.Body.String()) - } - - // Query string should be preserved after trailing slash strip. - rec = httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about/?foo=bar", nil)) - if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") { - t.Fatalf("about (trailing slash + query) code=%d body=%q", rec.Code, rec.Body.String()) - } -} diff --git a/plugins/web/internal/httpx/routes_artifact.go b/plugins/web/internal/httpx/routes_artifact.go deleted file mode 100755 index cce3288..0000000 --- a/plugins/web/internal/httpx/routes_artifact.go +++ /dev/null @@ -1,159 +0,0 @@ -package httpx - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/plugin" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -// artifactRoute is one Endpoint file registered by web.serve (ADR 0007). -type artifactRoute struct { - Method string - Path string - File string - Request string // json | form | none | query - Response string // json | text | html | sse - Auth string // role name or "" / "none" | "bearer" -} - -func parseArtifactRoute(v any) artifactRoute { - m, _ := v.(map[string]any) - return artifactRoute{ - Method: strings.ToUpper(strOpt(m, "method", "GET")), - Path: strOpt(m, "path", ""), - File: strOpt(m, "file", ""), - Request: strings.ToLower(strOpt(m, "request", "json")), - Response: strings.ToLower(strOpt(m, "response", "json")), - Auth: strOpt(m, "auth", ""), - } -} - -func (st *state) mountArtifactRoutes(mux routeRegistrar) { - for _, key := range sortedKeys(st.artifactRoutes) { - cfg := parseArtifactRoute(st.artifactRoutes[key]) - if cfg.File == "" || cfg.Path == "" { - continue - } - method := cfg.Method - if method == "" { - method = http.MethodGet - } - pattern := method + " " + goMuxPattern(cfg.Path) - routeCfg := cfg - mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - if r.Method != method { - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - st.handleArtifact(w, r, routeCfg) - }) - } -} - -func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route artifactRoute) { - if route.Auth != "" && !strings.EqualFold(route.Auth, "none") { - if strings.EqualFold(route.Auth, "bearer") || strings.EqualFold(route.Auth, "api_key") { - // Bearer / API-key auth is enforced inside the Endpoint `# main` - // (payload carries authorization / api_key). Do not require cookies. - } else { - cookie := r.Header.Get("Cookie") - user := session.UsernameFromCookie(cookie) - if user == "" { - jsonErr(w, http.StatusUnauthorized, "auth required") - return - } - role := session.RoleFromCookie(cookie) - if role != "" && role != route.Auth && role != "admin" && role != "superadmin" { - jsonErr(w, http.StatusForbidden, "forbidden") - return - } - } - } - - payload := map[string]any{} - switch route.Request { - case "none": - payload = queryToMap(r.URL.RawQuery) - case "query": - payload = queryToMap(r.URL.RawQuery) - case "form": - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20)) - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err)) - return - } - payload = formToMap(body) - default: // json - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20)) - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err)) - return - } - q := queryToMap(r.URL.RawQuery) - if len(body) == 0 { - payload = q - } else { - var raw map[string]any - if err := json.Unmarshal(body, &raw); err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("json: %v", err)) - return - } - if raw == nil { - payload = q - } else { - for k, v := range q { - if _, exists := raw[k]; !exists { - raw[k] = v - } - } - payload = raw - } - } - } - for _, name := range pathParamNames(route.Path) { - if v := r.PathValue(name); v != "" { - payload[name] = v - } - } - if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" { - if _, exists := payload["authorization"]; !exists { - payload["authorization"] = auth - } - } - if key := strings.TrimSpace(r.Header.Get("X-Api-Key")); key != "" { - if _, exists := payload["api_key"]; !exists { - payload["api_key"] = key - } - } - - value, err := plugin.RunArtifactAtRoot(route.File, payload, st.entryDir) - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - - switch route.Response { - case "text": - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, fmt.Sprint(value)) - case "html", "text/html": - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, fmt.Sprint(value)) - case "sse", "event-stream", "text/event-stream": - writeSSE(w, value) - default: - code, body, err := jsonWrapInvokeValue(value) - if err != nil { - jsonErr(w, code, err.Error()) - return - } - writeJSON(w, code, body) - } -} diff --git a/plugins/web/internal/httpx/routes_invoke.go b/plugins/web/internal/httpx/routes_invoke.go deleted file mode 100755 index 87dd249..0000000 --- a/plugins/web/internal/httpx/routes_invoke.go +++ /dev/null @@ -1,762 +0,0 @@ -package httpx - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "path/filepath" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/marqdo/marqdo/plugins/web/internal/plugin" -) - -// legacySSEBridgeMu serializes the process-global MARQDO_EVENT_FORWARD / -// MARQDO_CANCEL_TOKEN bridge for the legacy_serial path only. Isolated execute -// never acquires this lock (ADR 0009). -var legacySSEBridgeMu sync.Mutex - -// legacySSEBridgeActive is 1 while a holder has mutated process env for the bridge. -var legacySSEBridgeActive atomic.Int32 - -func tryAcquireLegacySSEBridge() bool { - return legacySSEBridgeMu.TryLock() -} - -func releaseLegacySSEBridge() { - legacySSEBridgeActive.Store(0) - legacySSEBridgeMu.Unlock() -} - -type invokeRoute struct { - Method string - FnPath string - BodyMode string - ReturnMode string - Class string - Path string -} - -func parseInvokeRoute(v any) invokeRoute { - m, _ := v.(map[string]any) - method := strings.ToUpper(strOpt(m, "method", "POST")) - body := strings.ToLower(strOpt(m, "body", "json")) - ret := strings.ToLower(strOpt(m, "return", "json")) - fn := strOpt(m, "fn", "") - if fn == "" { - fn = strOpt(m, "function", "") - } - class := strings.ToLower(strOpt(m, "class", "")) - if class == "" { - class = strings.ToLower(strOpt(m, "类别", "")) - } - return invokeRoute{ - Method: method, - FnPath: fn, - BodyMode: body, - ReturnMode: ret, - Class: class, - } -} - -func (st *state) mountInvokeRoutes(mux routeRegistrar) { - for _, key := range sortedKeys(st.invokeRoutes) { - cfg := parseInvokeRoute(st.invokeRoutes[key]) - path := routePathKey(key) - cfg.Path = path - method := cfg.Method - if method == "" { - method = http.MethodPost - } - pattern := method + " " + path - routeCfg := cfg - mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - if r.Method != method { - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - st.handleInvoke(w, r, routeCfg) - }) - } -} - -func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invokeRoute) { - queryMap := queryToMap(r.URL.RawQuery) - - var payload map[string]any - switch route.BodyMode { - case "query": - payload = queryMap - case "raw": - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20)) - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err)) - return - } - payload = map[string]any{"payload": string(body)} - case "form": - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20)) - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err)) - return - } - payload = formToMap(body) - default: - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20)) - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err)) - return - } - if len(body) == 0 { - payload = queryMap - } else { - var raw map[string]any - if err := json.Unmarshal(body, &raw); err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("json: %v", err)) - return - } - if raw == nil { - payload = queryMap - } else { - for k, v := range queryMap { - if _, exists := raw[k]; !exists { - raw[k] = v - } - } - payload = raw - } - } - } - - if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" { - if _, exists := payload["authorization"]; !exists { - payload["authorization"] = auth - } - } - if key := strings.TrimSpace(r.Header.Get("X-Api-Key")); key != "" { - if _, exists := payload["api_key"]; !exists { - payload["api_key"] = key - } - } - if last := strings.TrimSpace(r.Header.Get("Last-Event-ID")); last != "" { - if _, exists := payload["last_event_id"]; !exists { - payload["last_event_id"] = last - } - } - // Merge Go ServeMux path wildcards (e.g. /turns/{id}/events → id / turn_id). - if route.Path != "" { - pathVals := pathValuesOf(r, route.Path) - for k, v := range pathVals { - if _, exists := payload[k]; !exists { - payload[k] = v - } - } - if id, ok := pathVals["id"]; ok { - if _, exists := payload["turn_id"]; !exists { - payload["turn_id"] = id - } - } - } - - args := invokeArgsFromPayload(payload) - - liveSSE := route.ReturnMode == "sse-live" || route.ReturnMode == "sse_live" - if !liveSSE && payloadWantsStream(payload) { - liveSSE = true - } - - class := resolveInvokeClass(route, liveSSE) - switch class { - case "execute": - // Isolated workers: do not take parent INVOKE_LOCK (ADR 0009). - st.handleInvokeIsolated(w, r, route, args, liveSSE, class) - return - case "short", "read", "control": - // Stay on parent: execute already runs off-process, so parent lock is free. - // Putting short/read/control on the 2-slot execute worker pool caused - // systemic no_slot (and zombies held slots after observer disconnect). - // Product cancel/events prefer /_runtime/* (lock-free). - st.handleInvokeParent(w, r, route, args) - return - default: - // legacy_serial: parent CallLibPath (ADR 0008). Never isolate undeclared non-stream. - st.handleInvokeParent(w, r, route, args) - } -} - -func resolveInvokeClass(route invokeRoute, liveSSE bool) string { - c := strings.ToLower(strings.TrimSpace(route.Class)) - switch c { - case "execute", "short", "read", "control": - return c - case "legacy", "legacy_serial": - return "legacy_serial" - } - if liveSSE { - return "execute" - } - return "legacy_serial" -} - -func (st *state) handleInvokeParent(w http.ResponseWriter, r *http.Request, route invokeRoute, args map[string]any) { - _ = r - value, err := plugin.CallLibPath(route.FnPath, args) - if err != nil { - code := http.StatusInternalServerError - msg := err.Error() - if strings.Contains(msg, "interpreter busy") { - w.Header().Set("Retry-After", "2") - jsonErr(w, http.StatusServiceUnavailable, msg) - return - } - if strings.Contains(msg, "unknown library") || - strings.Contains(msg, "call_lib_path: need") || - strings.Contains(msg, "not allowed") || - strings.Contains(msg, "no site") || - strings.Contains(msg, "no active host") { - code = http.StatusBadRequest - } - if strings.Contains(msg, "unauthorized") || strings.Contains(msg, "Unauthorized") { - code = http.StatusUnauthorized - } - jsonErr(w, code, msg) - return - } - - if m, ok := value.(map[string]any); ok { - if s, ok := m["sse"].(string); ok && strings.TrimSpace(s) != "" { - writeSSE(w, m) - return - } - } - - switch route.ReturnMode { - case "text", "html", "text/html": - if value == nil { - jsonErr(w, http.StatusInternalServerError, "null result") - return - } - text := fmt.Sprint(value) - if s, ok := value.(string); ok { - text = s - } - ct := "text/plain; charset=utf-8" - if route.ReturnMode == "html" || route.ReturnMode == "text/html" { - ct = "text/html; charset=utf-8" - } - w.Header().Set("Content-Type", ct) - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, text) - case "sse", "event-stream", "text/event-stream": - writeSSE(w, value) - case "status": - if value == nil { - jsonErr(w, http.StatusInternalServerError, "null result") - return - } - w.WriteHeader(http.StatusNoContent) - default: - code, body, err := jsonWrapInvokeValue(value) - if err != nil { - jsonErr(w, code, err.Error()) - return - } - writeJSON(w, code, body) - } -} - -// handleInvokeIsolated runs admits on a Supervisor worker (no parent -// CallLibPath / Setenv / legacySSEBridgeMu). admissionClass is execute|short|read|control. -func (st *state) handleInvokeIsolated(w http.ResponseWriter, r *http.Request, route invokeRoute, args map[string]any, liveSSE bool, admissionClass string) { - if admissionClass == "" { - admissionClass = "execute" - } - taskID := fmt.Sprintf("exec_%d", time.Now().UnixNano()) - adm, err := runtimeQuery("admit", map[string]any{ - "task_id": taskID, - "idempotency_key": taskID, - "class": admissionClass, - "payload": map[string]any{"fn": route.FnPath}, - }) - if err != nil { - jsonErr(w, http.StatusInternalServerError, fmt.Sprintf("admit: %v", err)) - return - } - if ok, _ := adm["ok"].(bool); !ok { - status := http.StatusServiceUnavailable - if s, ok := adm["status"].(float64); ok && s >= 400 { - status = int(s) - } - w.Header().Set("Retry-After", "2") - jsonErr(w, status, fmt.Sprint(adm["error"])) - return - } - cancelTok, _ := adm["cancel_token"].(string) - eventPath, _ := adm["event_path"].(string) - - entryModule, fsRoot, err := resolveSiteEntry(st) - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - - argsFile, err := materializeArgsJSON(args) - if err != nil { - jsonErr(w, http.StatusInternalServerError, fmt.Sprintf("args: %v", err)) - return - } - defer os.Remove(argsFile) - - disp, err := runtimeQuery("dispatch", map[string]any{ - "task_id": taskID, - "entry": map[string]any{ - "module": entryModule, - "function": route.FnPath, - }, - "fs_root": fsRoot, - "args_json": argsFile, - }) - if err != nil { - _, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID}) - jsonErr(w, http.StatusInternalServerError, fmt.Sprintf("dispatch: %v", err)) - return - } - if ok, _ := disp["ok"].(bool); !ok { - status := http.StatusTooManyRequests - if s, ok := disp["status"].(float64); ok && s >= 400 { - status = int(s) - } - if ra, ok := disp["Retry-After"]; ok { - w.Header().Set("Retry-After", fmt.Sprint(ra)) - } else { - w.Header().Set("Retry-After", "2") - } - jsonErr(w, status, fmt.Sprint(disp["error"])) - return - } - if ep, ok := disp["event_path"].(string); ok && ep != "" { - eventPath = ep - } - if tok, ok := disp["cancel_token"].(string); ok && tok != "" { - cancelTok = tok - } - emitResult, _ := disp["emit_result"].(string) - - if liveSSE { - st.streamIsolatedSSE(w, r, route, taskID, eventPath, cancelTok, emitResult) - return - } - st.waitIsolatedJSON(w, r, route, taskID, eventPath, cancelTok, emitResult) -} - -// cancelOnDisconnect reports whether the client opted into legacy -// disconnect=cancel (header X-Marqdo-Cancel-On-Disconnect: 1|true). -// Default is false: subscription close must not cancel the task (ADR 0009 / design §7.2). -func cancelOnDisconnect(r *http.Request) bool { - v := strings.TrimSpace(strings.ToLower(r.Header.Get("X-Marqdo-Cancel-On-Disconnect"))) - return v == "1" || v == "true" || v == "yes" -} - -func (st *state) streamIsolatedSSE(w http.ResponseWriter, r *http.Request, route invokeRoute, taskID, eventPath, cancelTok, emitResult string) { - w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("X-Accel-Buffering", "no") - w.WriteHeader(http.StatusOK) - flusher, _ := w.(http.Flusher) - writeEvent := func(payload any) { - b, err := json.Marshal(payload) - if err != nil { - return - } - _, _ = io.WriteString(w, "data: "+string(b)+"\n\n") - if flusher != nil { - flusher.Flush() - } - } - writeEvent(map[string]any{ - "schema": "RuntimeEventV1", - "schema_version": 1, - "type": "run.started", - "payload": map[string]any{ - "fn": route.FnPath, - "bridge": "isolated", - "task_id": taskID, - }, - }) - - offset := int64(0) - carry := "" - seq := uint64(1) - poll := time.NewTicker(25 * time.Millisecond) - defer poll.Stop() - ctx := r.Context() - - finish := func(clientGone bool) { - offset, carry = drainForwardCarry(eventPath, offset, carry, func(line string) { - seq++ - writeEvent(normalizeLiveSSELine(seq, line)) - }) - if !clientGone { - result := readEmitResult(emitResult) - if result == nil { - if g, err := runtimeQuery("get", map[string]any{"task_id": taskID}); err == nil { - if t, ok := g["task"].(map[string]any); ok { - result = t["result"] - } - } - } - writeEvent(map[string]any{ - "schema": "RuntimeEventV1", "schema_version": 1, "type": "run.completed", - "payload": map[string]any{"result": result, "task_id": taskID}, - }) - _, _ = io.WriteString(w, "data: [DONE]\n\n") - if flusher != nil { - flusher.Flush() - } - } - } - - doCancelOnDisconnect := cancelOnDisconnect(r) - - for { - select { - case <-ctx.Done(): - // Default: observer gone ≠ cancel. Task keeps running; client may - // reattach via GET /_runtime/tasks/{id}/events (Last-Event-ID). - if doCancelOnDisconnect { - _, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID}) - _ = writeCancelToken(cancelTok) - writeEvent(map[string]any{ - "schema": "RuntimeEventV1", "schema_version": 1, "type": "run.interrupted", - "payload": map[string]any{ - "reason": "client_disconnect", - "cancel_propagated": cancelTok != "", - "status": "stopping", - "task_id": taskID, - }, - }) - deadline := time.Now().Add(3 * time.Second) - for time.Now().Before(deadline) { - if workerDone(taskID, emitResult) { - break - } - time.Sleep(50 * time.Millisecond) - } - } else { - writeEvent(map[string]any{ - "schema": "RuntimeEventV1", "schema_version": 1, "type": "run.interrupted", - "payload": map[string]any{ - "reason": "client_disconnect", - "cancel_propagated": false, - "status": "observer_closed", - "task_id": taskID, - "resume": "/_runtime/tasks/" + taskID + "/events", - }, - }) - // Observer gone ≠ cancel, but still reap when the worker exits so - // execute slots are not held forever by zombies. - go reapIsolatedTask(taskID, emitResult, 10*time.Minute) - } - finish(true) - return - case <-poll.C: - offset, carry = drainForwardCarry(eventPath, offset, carry, func(line string) { - seq++ - writeEvent(normalizeLiveSSELine(seq, line)) - }) - if workerDone(taskID, emitResult) { - finish(false) - return - } - } - } -} - -func (st *state) waitIsolatedJSON(w http.ResponseWriter, r *http.Request, route invokeRoute, taskID, eventPath, cancelTok, emitResult string) { - _ = eventPath - poll := time.NewTicker(25 * time.Millisecond) - defer poll.Stop() - ctx := r.Context() - for { - select { - case <-ctx.Done(): - _, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID}) - _ = writeCancelToken(cancelTok) - jsonErr(w, http.StatusRequestTimeout, "client disconnected") - return - case <-poll.C: - if !workerDone(taskID, emitResult) { - continue - } - value := readEmitResult(emitResult) - if value == nil { - jsonErr(w, http.StatusInternalServerError, "worker produced no result") - return - } - if m, ok := value.(map[string]any); ok { - if s, ok := m["sse"].(string); ok && strings.TrimSpace(s) != "" { - writeSSE(w, m) - return - } - } - switch route.ReturnMode { - case "text", "html", "text/html": - text := fmt.Sprint(value) - if s, ok := value.(string); ok { - text = s - } - ct := "text/plain; charset=utf-8" - if route.ReturnMode == "html" || route.ReturnMode == "text/html" { - ct = "text/html; charset=utf-8" - } - w.Header().Set("Content-Type", ct) - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, text) - case "status": - w.WriteHeader(http.StatusNoContent) - default: - code, body, err := jsonWrapInvokeValue(value) - if err != nil { - jsonErr(w, code, err.Error()) - return - } - writeJSON(w, code, body) - } - return - } - } -} - -// reapIsolatedTask polls runtime get until the worker exits (or timeout), -// so supervisor/scheduler slots are released after observer disconnect. -func reapIsolatedTask(taskID, emitResult string, budget time.Duration) { - deadline := time.Now().Add(budget) - for time.Now().Before(deadline) { - if workerDone(taskID, emitResult) { - return - } - time.Sleep(200 * time.Millisecond) - } - // Last-chance cancel so slots can free. - _, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID}) - for i := 0; i < 25; i++ { - if workerDone(taskID, emitResult) { - return - } - time.Sleep(200 * time.Millisecond) - } -} - -func workerDone(taskID, emitResult string) bool { - // Always runtime.get when probing completion: get runs try_reap and - // releases execute slots. Do not return early on emit_result alone — - // that left zombie workers holding both pool slots (no_slot). - if taskID == "" { - return false - } - g, err := runtimeQuery("get", map[string]any{"task_id": taskID}) - if err != nil { - // Fallback: result file present (get may fail during early boot). - if emitResult != "" { - if st, err := os.Stat(emitResult); err == nil && st.Size() > 0 { - return true - } - } - if dir := os.Getenv("MARQDO_RUNTIME_DIR"); dir != "" { - p := filepath.Join(dir, "events", taskID+".result.json") - if st, err := os.Stat(p); err == nil && st.Size() > 0 { - return true - } - } - return false - } - if _, ok := g["exit_code"]; ok { - return true - } - if t, ok := g["task"].(map[string]any); ok { - switch fmt.Sprint(t["state"]) { - case "succeeded", "failed", "cancelled", "interrupted": - return true - } - } - return false -} - -func readEmitResult(path string) any { - if path == "" { - return nil - } - b, err := os.ReadFile(path) - if err != nil || len(b) == 0 { - return nil - } - var v any - if err := json.Unmarshal(b, &v); err != nil { - return string(b) - } - return v -} - -func materializeArgsJSON(args map[string]any) (string, error) { - f, err := os.CreateTemp("", "mq-args-*.json") - if err != nil { - return "", err - } - path := f.Name() - enc := json.NewEncoder(f) - if err := enc.Encode(args); err != nil { - _ = f.Close() - _ = os.Remove(path) - return "", err - } - if err := f.Close(); err != nil { - _ = os.Remove(path) - return "", err - } - return path, nil -} - -func resolveSiteEntry(st *state) (module string, fsRoot string, err error) { - fsRoot = st.entryDir - if raw, qerr := plugin.Query("entry_dir", "{}"); qerr == nil { - var s string - if json.Unmarshal([]byte(raw), &s) == nil && s != "" { - fsRoot = s - } - } - if raw, qerr := plugin.Query("entry_path", "{}"); qerr == nil { - var s string - if json.Unmarshal([]byte(raw), &s) == nil && s != "" { - module = s - } - } - if module == "" { - // Fallback: common serve entry names under fs_root. - for _, name := range []string{"serve.mq.md", "index.mq.md", "main.mq.md"} { - p := filepath.Join(fsRoot, name) - if st, e := os.Stat(p); e == nil && !st.IsDir() { - module = p - break - } - } - } - if module == "" { - return "", "", fmt.Errorf("isolated execute: cannot resolve site entry module") - } - if !filepath.IsAbs(module) { - abs, aerr := filepath.Abs(module) - if aerr == nil { - module = abs - } - } - if fsRoot == "" { - fsRoot = filepath.Dir(module) - } - if !filepath.IsAbs(fsRoot) { - abs, aerr := filepath.Abs(fsRoot) - if aerr == nil { - fsRoot = abs - } - } - return module, fsRoot, nil -} - -// normalizeLiveSSELine maps Marqdo EventBus frames onto RuntimeEventV1. -func normalizeLiveSSELine(seq uint64, line string) map[string]any { - base := map[string]any{ - "schema": "RuntimeEventV1", "schema_version": 1, "seq": seq, - } - var obj map[string]any - if err := json.Unmarshal([]byte(line), &obj); err != nil || obj == nil { - base["type"] = "message.delta" - base["payload"] = map[string]any{"raw": line} - return base - } - if t, _ := obj["type"].(string); t == "message.delta" || t == "turn.started" || t == "model.resolved" || t == "usage.updated" || t == "turn.completed" || t == "turn.failed" { - for k, v := range obj { - base[k] = v - } - base["seq"] = seq - return base - } - if t, _ := obj["type"].(string); t == "delta" || t == "plan" || t == "reasoning" { - text, _ := obj["text"].(string) - base["type"] = "message.delta" - base["payload"] = map[string]any{"delta": text, "kind": t} - return base - } - if t, _ := obj["type"].(string); t == "decompose" || t == "decision" || t == "await" || t == "round" || t == "done" || t == "tool_start" || t == "tool_end" || t == "plan_act" { - base["type"] = "message.delta" - base["payload"] = obj - return base - } - if text, ok := obj["text"].(string); ok && text != "" { - base["type"] = "message.delta" - base["payload"] = map[string]any{"delta": text} - return base - } - base["type"] = "message.delta" - base["payload"] = obj - return base -} - -func drainForward(path string, offset int64, onLine func(string)) int64 { - off, _ := drainForwardCarry(path, offset, "", onLine) - return off -} - -const drainForwardMaxLine = 1024 * 1024 - -func drainForwardCarry(path string, offset int64, carry string, onLine func(string)) (int64, string) { - f, err := os.Open(path) - if err != nil { - return offset, carry - } - defer f.Close() - if _, err := f.Seek(offset, io.SeekStart); err != nil { - return offset, carry - } - chunk, err := io.ReadAll(io.LimitReader(f, drainForwardMaxLine+1)) - if err != nil && err != io.EOF { - onLine(fmt.Sprintf(`{"type":"protocol.error","error":%q}`, err.Error())) - return offset, carry - } - if len(chunk) == 0 { - return offset, carry - } - offset += int64(len(chunk)) - buf := carry + string(chunk) - for { - i := strings.IndexByte(buf, '\n') - if i < 0 { - if len(buf) > drainForwardMaxLine { - onLine(`{"type":"protocol.error","error":"ndjson line exceeds 1MiB"}`) - return offset, "" - } - return offset, buf - } - lineBytes := buf[:i] - line := strings.TrimSpace(strings.TrimSuffix(lineBytes, "\r")) - buf = buf[i+1:] - if line == "" { - continue - } - onLine(line) - } -} - -func legacySSEBridgeSnapshot() (active bool, forward string, cancelTok string) { - return legacySSEBridgeActive.Load() != 0, os.Getenv("MARQDO_EVENT_FORWARD"), os.Getenv("MARQDO_CANCEL_TOKEN") -} - -func writeCancelToken(path string) error { - if path == "" { - return nil - } - return os.WriteFile(path, []byte("cancelled"), 0o600) -} diff --git a/plugins/web/internal/httpx/routes_media.go b/plugins/web/internal/httpx/routes_media.go deleted file mode 100755 index b097370..0000000 --- a/plugins/web/internal/httpx/routes_media.go +++ /dev/null @@ -1,339 +0,0 @@ -package httpx - -import ( - "fmt" - "io" - "net/http" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/session" - "github.com/marqdo/marqdo/plugins/web/internal/storage" - "github.com/marqdo/marqdo/plugins/web/internal/upload" -) - -type uploadRoute struct { - Field string - StorageURL string - Prefix string - MaxBytes uint64 - Types any -} - -type downloadRoute struct { - StorageURL string - Disposition string -} - -func parseUploadRoute(v any) uploadRoute { - m, _ := v.(map[string]any) - max := uint64(0) - if n, ok := m["max_bytes"].(float64); ok { - max = uint64(n) - } - return uploadRoute{ - Field: strOpt(m, "field", "file"), - StorageURL: strOpt(m, "storage_url", ""), - Prefix: strOpt(m, "prefix", "uploads/"), - MaxBytes: max, - Types: m["types"], - } -} - -func parseDownloadRoute(v any) downloadRoute { - m, _ := v.(map[string]any) - return downloadRoute{ - StorageURL: strOpt(m, "storage_url", ""), - Disposition: strOpt(m, "disposition", "attachment"), - } -} - -func (st *state) mountUploadRoutes(mux routeRegistrar) { - for _, path := range sortedKeys(st.uploadRoutes) { - routePath := path - cfg := parseUploadRoute(st.uploadRoutes[path]) - mux.HandleFunc("POST "+routePath, func(w http.ResponseWriter, r *http.Request) { - st.handleUpload(w, r, routePath, cfg) - }) - } -} - -func (st *state) mountDownloadRoutes(mux routeRegistrar) { - for _, path := range sortedKeys(st.downloadRoutes) { - routePath := path - cfg := parseDownloadRoute(st.downloadRoutes[path]) - pattern := "GET " + goMuxPattern(routePath) - mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - st.handleDownload(w, r, routePath, cfg) - }) - } -} - -func (st *state) mountGalleryRoutes(mux routeRegistrar) { - for _, path := range sortedKeys(st.galleryRoutes) { - cfg, _ := st.galleryRoutes[path].(map[string]any) - mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) { - st.writeGallery(w, cfg) - }) - } -} - -func (st *state) handleUpload(w http.ResponseWriter, r *http.Request, routePath string, cfg uploadRoute) { - _, hadCookie := session.IDFromCookie(r.Header.Get("Cookie")) - sid, _, setCookie := resolveSession(r) - - // M01: hard-limit request body before multipart parse (32MiB was only in-memory - // form budget, not a request total). Cap at configured MaxBytes + 1MiB overhead. - maxBody := int64(cfg.MaxBytes) - if maxBody <= 0 { - maxBody = 32 << 20 - } - overhead := int64(1 << 20) - r.Body = http.MaxBytesReader(w, r.Body, maxBody+overhead) - - if err := r.ParseMultipartForm(maxBody + overhead); err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("multipart: %v", err)) - return - } - - csrfToken := "" - if vals := r.MultipartForm.Value["_csrf"]; len(vals) > 0 { - csrfToken = vals[0] - } - - var fileName, fileCT string - fileCT = "application/octet-stream" - var fileBytes []byte - - if files := r.MultipartForm.File[cfg.Field]; len(files) > 0 { - fh := files[0] - fileName = fh.Filename - if fh.Header != nil { - if ct := fh.Header.Get("Content-Type"); ct != "" { - fileCT = ct - } - } - f, err := fh.Open() - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("open file: %v", err)) - return - } - defer f.Close() - // Stream-capped read: never buffer more than MaxBytes. - lim := maxBody - if lim <= 0 { - lim = 32 << 20 - } - b, err := io.ReadAll(io.LimitReader(f, lim+1)) - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("read file: %v", err)) - return - } - if int64(len(b)) > lim { - jsonErr(w, http.StatusRequestEntityTooLarge, "file exceeds max_bytes") - return - } - fileBytes = b - } else { - // Fallback: walk File map keys. - for name, fhs := range r.MultipartForm.File { - if name == cfg.Field && len(fhs) > 0 { - fh := fhs[0] - fileName = fh.Filename - f, err := fh.Open() - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("open file: %v", err)) - return - } - defer f.Close() - fileBytes, err = io.ReadAll(f) - if err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("read file: %v", err)) - return - } - break - } - } - } - - if hadCookie && !session.ValidateCSRF(sid, csrfToken) { - jsonErr(w, http.StatusForbidden, "Invalid or missing CSRF token") - return - } - - if len(fileBytes) == 0 { - jsonErr(w, http.StatusBadRequest, "missing file field") - return - } - - size := uint64(len(fileBytes)) - check := upload.Validate(fileName, fileCT, size, cfg.MaxBytes, cfg.Types) - if ok, _ := check["ok"].(bool); !ok { - errMsg := strOpt(check, "error", "validation failed") - jsonErr(w, http.StatusBadRequest, errMsg) - return - } - ct := strOpt(check, "content_type", fileCT) - - key, err := upload.MakeKey(cfg.Prefix, fileName) - if err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - saved, err := storage.PutBytes(cfg.StorageURL, key, fileBytes, ct) - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - - body := map[string]any{ - "ok": true, - "key": key, - "size": float64(size), - "content_type": ct, - } - if sz, ok := saved["size"]; ok { - body["size"] = sz - } - appendSetCookie(w, setCookie) - writeJSON(w, http.StatusOK, body) -} - -func (st *state) handleDownload(w http.ResponseWriter, r *http.Request, routePath string, cfg downloadRoute) { - key := downloadKeyFromRequest(r, routePath) - if key == "" { - jsonErr(w, http.StatusBadRequest, "missing key") - return - } - - bytes, contentType, filename, found, err := storage.ReadBytes(cfg.StorageURL, key) - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - if !found { - jsonErr(w, http.StatusNotFound, "not found") - return - } - - etag := weakETag(bytes) - if inm := r.Header.Get("If-None-Match"); inm != "" { - for _, part := range strings.Split(inm, ",") { - if strings.TrimSpace(part) == etag { - w.WriteHeader(http.StatusNotModified) - return - } - } - } - - disp := "attachment" - if strings.EqualFold(cfg.Disposition, "inline") { - disp = "inline" - } - safeName := strings.ReplaceAll(filename, `"`, "_") - w.Header().Set("Content-Type", contentType) - w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", disp, safeName)) - w.Header().Set("ETag", etag) - w.WriteHeader(http.StatusOK) - _, _ = w.Write(bytes) -} - -func downloadKeyFromRequest(r *http.Request, routePath string) string { - for _, name := range downloadParamNames(routePath) { - if v := strings.TrimPrefix(r.PathValue(name), "/"); v != "" { - return v - } - } - if v := strings.TrimPrefix(r.PathValue("key"), "/"); v != "" { - return v - } - return "" -} - -func downloadParamNames(routePath string) []string { - var names []string - for _, seg := range strings.Split(routePath, "/") { - if strings.HasPrefix(seg, "{*") && strings.HasSuffix(seg, "}") { - names = append(names, strings.TrimSuffix(strings.TrimPrefix(seg, "{*"), "}")) - } else if strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}") { - inner := strings.TrimSuffix(strings.TrimPrefix(seg, "{"), "}") - if strings.HasSuffix(inner, "...") { - inner = strings.TrimSuffix(inner, "...") - } - if inner != "" { - names = append(names, inner) - } - } - } - return names -} - -func (st *state) writeGallery(w http.ResponseWriter, cfg map[string]any) { - storageURL := strOpt(cfg, "storage", "") - prefix := strOpt(cfg, "prefix", "") - title := strOpt(cfg, "title", "Gallery") - downloadBase := strOpt(cfg, "download_base", "/_media") - - listed, err := storage.List(storageURL, prefix) - keys := []any{} - if err == nil { - if k, ok := listed["keys"].([]string); ok { - for _, s := range k { - keys = append(keys, s) - } - } else if k, ok := listed["keys"].([]any); ok { - keys = k - } - } - - var items strings.Builder - for _, k := range keys { - key, _ := k.(string) - if key == "" { - continue - } - href := downloadBase + "/" + strings.TrimPrefix(key, "/") - name := key - if i := strings.LastIndexByte(key, '/'); i >= 0 { - name = key[i+1:] - } - lower := strings.ToLower(name) - isImg := strings.HasSuffix(lower, ".png") || strings.HasSuffix(lower, ".jpg") || - strings.HasSuffix(lower, ".jpeg") || strings.HasSuffix(lower, ".gif") || - strings.HasSuffix(lower, ".webp") || strings.HasSuffix(lower, ".svg") - if isImg { - items.WriteString(fmt.Sprintf( - "
      \"%s\"/
      %s
      ", - esc(href), esc(href), esc(name), esc(name))) - } else { - items.WriteString(fmt.Sprintf( - "
      %s
      ", - esc(href), esc(name))) - } - } - itemHTML := items.String() - if itemHTML == "" { - itemHTML = "

      No media yet.

      " - } - - html := fmt.Sprintf(` - - -%s - -

      %s

      %s
      `, - esc(title), esc(title), itemHTML) - - etag := weakETag([]byte(html)) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("ETag", etag) - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, html) -} diff --git a/plugins/web/internal/httpx/routes_media_test.go b/plugins/web/internal/httpx/routes_media_test.go deleted file mode 100755 index 7028c43..0000000 --- a/plugins/web/internal/httpx/routes_media_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package httpx - -import ( - "bytes" - "mime/multipart" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestHandleUploadRejectsOversizedBeforeFullBuffer(t *testing.T) { - st := &state{ - uploadRoutes: map[string]any{ - "/upload": map[string]any{ - "field": "file", - "storage_url": "memory://t", - "prefix": "u", - "max_bytes": float64(64), - }, - }, - } - cfg := parseUploadRoute(st.uploadRoutes["/upload"]) - var body bytes.Buffer - w := multipart.NewWriter(&body) - part, err := w.CreateFormFile("file", "big.txt") - if err != nil { - t.Fatal(err) - } - if _, err := part.Write([]byte(strings.Repeat("x", 200))); err != nil { - t.Fatal(err) - } - _ = w.Close() - - req := httptest.NewRequest(http.MethodPost, "/upload", &body) - req.Header.Set("Content-Type", w.FormDataContentType()) - rr := httptest.NewRecorder() - st.handleUpload(rr, req, "/upload", cfg) - if rr.Code == http.StatusOK { - t.Fatalf("expected reject for oversized upload, got %d body=%s", rr.Code, rr.Body.String()) - } - if rr.Code != http.StatusRequestEntityTooLarge && rr.Code != http.StatusBadRequest { - t.Fatalf("expected 413 or 400, got %d body=%s", rr.Code, rr.Body.String()) - } -} diff --git a/plugins/web/internal/httpx/routes_proxy.go b/plugins/web/internal/httpx/routes_proxy.go deleted file mode 100755 index 872a5fb..0000000 --- a/plugins/web/internal/httpx/routes_proxy.go +++ /dev/null @@ -1,285 +0,0 @@ -package httpx - -import ( - "bytes" - "fmt" - "io" - "net/http" - "os" - "strings" - "time" -) - -type proxyRoute struct { - Upstream string - Stream bool - StripPrefix string - Methods []string - HeadersFromEnv []envHeader - TimeoutMs uint64 -} - -type envHeader struct { - Env string - Header string -} - -func parseProxyRoute(v any) proxyRoute { - m, _ := v.(map[string]any) - stream := true - if s, ok := m["stream"].(bool); ok { - stream = s - } - timeout := uint64(120_000) - if n, ok := m["timeout_ms"].(float64); ok && n > 0 { - timeout = uint64(n) - } - var methods []string - if arr, ok := m["methods"].([]any); ok { - for _, x := range arr { - if s, ok := x.(string); ok && s != "" { - methods = append(methods, strings.ToUpper(s)) - } - } - } - if len(methods) == 0 { - methods = []string{"POST"} - } - return proxyRoute{ - Upstream: strOpt(m, "upstream", ""), - Stream: stream, - StripPrefix: strOpt(m, "strip_prefix", ""), - Methods: methods, - HeadersFromEnv: parseHeadersFromEnv(m["headers_from_env"]), - TimeoutMs: timeout, - } -} - -func parseHeadersFromEnv(v any) []envHeader { - switch t := v.(type) { - case string: - return parseHeadersFromEnvStr(t) - case []any: - var out []envHeader - for _, x := range t { - if s, ok := x.(string); ok { - out = append(out, parseHeadersFromEnvStr(s)...) - } - } - return out - default: - return nil - } -} - -func parseHeadersFromEnvStr(s string) []envHeader { - var out []envHeader - for _, part := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ';' }) { - part = strings.TrimSpace(part) - if part == "" { - continue - } - env, hdr, _ := strings.Cut(part, "=") - env = strings.TrimSpace(env) - hdr = strings.TrimSpace(hdr) - if env == "" || hdr == "" { - continue - } - out = append(out, envHeader{Env: env, Header: hdr}) - } - return out -} - -func (st *state) mountProxyRoutes(mux routeRegistrar) { - for _, key := range sortedKeys(st.proxyRoutes) { - cfg := parseProxyRoute(st.proxyRoutes[key]) - path := routePathKey(key) - for _, method := range cfg.Methods { - pattern := method + " " + path - routeCfg := cfg - mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - if r.Method != method { - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - st.handleProxy(w, r, routeCfg) - }) - } - } -} - -func (st *state) handleProxy(w http.ResponseWriter, r *http.Request, route proxyRoute) { - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<20)) - if err != nil { - http.Error(w, fmt.Sprintf("read body: %v", err), http.StatusBadRequest) - return - } - - target, err := buildUpstreamURL(route, r.URL.Path, r.URL.RawQuery) - if err != nil { - http.Error(w, err.Error(), http.StatusBadGateway) - return - } - - timeout := time.Duration(route.TimeoutMs) * time.Millisecond - client := &http.Client{Timeout: timeout} - - req, err := http.NewRequestWithContext(r.Context(), r.Method, target, nil) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if len(body) > 0 { - req.Body = io.NopCloser(bytes.NewReader(body)) - req.ContentLength = int64(len(body)) - } - - for name, vals := range r.Header { - lname := strings.ToLower(name) - if isHopByHop(lname) || lname == "host" { - continue - } - for _, v := range vals { - req.Header.Add(name, v) - } - } - - for _, eh := range route.HeadersFromEnv { - val := os.Getenv(eh.Env) - if val == "" { - continue - } - if strings.EqualFold(eh.Header, "authorization") && - !strings.HasPrefix(strings.ToLower(val), "bearer ") { - val = "Bearer " + val - } - req.Header.Set(eh.Header, val) - } - - resp, err := client.Do(req) - if err != nil { - http.Error(w, fmt.Sprintf("upstream: %v", err), http.StatusBadGateway) - return - } - defer resp.Body.Close() - - for name, vals := range resp.Header { - lname := strings.ToLower(name) - if isHopByHop(lname) { - continue - } - for _, v := range vals { - w.Header().Add(name, v) - } - } - if route.Stream { - w.Header().Set("Cache-Control", "no-cache, no-transform") - w.Header().Set("X-Accel-Buffering", "no") - } - w.WriteHeader(resp.StatusCode) - if route.Stream { - _, _ = io.Copy(w, resp.Body) - return - } - out, err := io.ReadAll(resp.Body) - if err != nil { - return - } - _, _ = w.Write(out) -} - -func buildUpstreamURL(route proxyRoute, reqPath, query string) (string, error) { - base := expandEnv(route.Upstream) - if base == "" { - return "", fmt.Errorf("proxy upstream empty after env expand") - } - path := reqPath - strip := strings.TrimSpace(route.StripPrefix) - if strip != "" { - stripN := routePathKey(strip) - if strings.HasPrefix(path, stripN) { - path = path[len(stripN):] - if path == "" { - path = "/" - } else if !strings.HasPrefix(path, "/") { - path = "/" + path - } - } - } - - if !strings.Contains(base, "://") { - return "", fmt.Errorf("proxy upstream must be absolute URL, got `%s`", base) - } - - trimmed := strings.TrimRight(base, "/") - idx := strings.Index(trimmed, "://") - after := "" - if idx >= 0 { - after = trimmed[idx+3:] - } - var url string - if strings.Contains(after, "/") { - if path == "/" { - url = trimmed - } else { - url = trimmed + path - } - } else { - url = trimmed + path - } - - if query != "" { - if strings.Contains(url, "?") { - url += "&" + query - } else { - url += "?" + query - } - } - return url, nil -} - -func expandEnv(s string) string { - var out strings.Builder - b := s - i := 0 - for i < len(b) { - if b[i] == '$' { - if i+1 < len(b) && b[i+1] == '{' { - if end := strings.Index(b[i+2:], "}"); end >= 0 { - name := b[i+2 : i+2+end] - out.WriteString(os.Getenv(name)) - i += 3 + end - continue - } - } else { - start := i + 1 - end := start - for end < len(b) && (isAlnum(b[end]) || b[end] == '_') { - end++ - } - if end > start { - out.WriteString(os.Getenv(b[start:end])) - i = end - continue - } - } - } - out.WriteByte(b[i]) - i++ - } - return out.String() -} - -func isAlnum(c byte) bool { - return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') -} - -func isHopByHop(name string) bool { - switch name { - case "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", - "te", "trailers", "transfer-encoding", "upgrade", "content-length": - return true - default: - return false - } -} diff --git a/plugins/web/internal/httpx/routes_runtime.go b/plugins/web/internal/httpx/routes_runtime.go deleted file mode 100755 index 8094446..0000000 --- a/plugins/web/internal/httpx/routes_runtime.go +++ /dev/null @@ -1,207 +0,0 @@ -package httpx - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - "time" - - "github.com/marqdo/marqdo/plugins/web/internal/plugin" -) - -// System runtime control routes (M-R3 / M-R4). Cancel and event replay do not -// enter the Marqdo interpreter lock. -func (st *state) mountRuntimeRoutes(mux routeRegistrar) { - mux.HandleFunc("POST /_runtime/tasks", st.handleRuntimeAdmit) - mux.HandleFunc("GET /_runtime/tasks/{id}", st.handleRuntimeGet) - mux.HandleFunc("POST /_runtime/tasks/{id}/cancel", st.handleRuntimeCancel) - mux.HandleFunc("GET /_runtime/tasks/{id}/events", st.handleRuntimeEvents) -} - -func runtimeQuery(op string, extra map[string]any) (map[string]any, error) { - payload := map[string]any{"op": op} - for k, v := range extra { - payload[k] = v - } - raw, err := json.Marshal(payload) - if err != nil { - return nil, err - } - out, err := plugin.Query("runtime", string(raw)) - if err != nil { - return nil, err - } - var m map[string]any - if err := json.Unmarshal([]byte(out), &m); err != nil { - return nil, err - } - return m, nil -} - -func (st *state) handleRuntimeAdmit(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) - if err != nil { - jsonErr(w, http.StatusBadRequest, err.Error()) - return - } - var req map[string]any - if len(body) > 0 { - if err := json.Unmarshal(body, &req); err != nil { - jsonErr(w, http.StatusBadRequest, fmt.Sprintf("json: %v", err)) - return - } - } - if req == nil { - req = map[string]any{} - } - taskID, _ := req["task_id"].(string) - if taskID == "" { - taskID = fmt.Sprintf("task_%d", time.Now().UnixNano()) - req["task_id"] = taskID - } - if _, ok := req["idempotency_key"]; !ok { - req["idempotency_key"] = taskID - } - if _, ok := req["class"]; !ok { - req["class"] = "execute" - } - m, err := runtimeQuery("admit", req) - if err != nil { - if strings.Contains(err.Error(), "conflict") || strings.Contains(fmt.Sprint(m["error"]), "conflict") { - jsonErr(w, http.StatusConflict, err.Error()) - return - } - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - if ok, _ := m["ok"].(bool); !ok { - jsonErr(w, http.StatusConflict, fmt.Sprint(m["error"])) - return - } - w.Header().Set("Location", "/_runtime/tasks/"+taskID) - writeJSON(w, http.StatusAccepted, m) -} - -func (st *state) handleRuntimeGet(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - m, err := runtimeQuery("get", map[string]any{"task_id": id}) - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - if st, _ := m["status"].(float64); st == 404 || fmt.Sprint(m["error"]) == "not_found" { - jsonErr(w, http.StatusNotFound, "task not found") - return - } - writeJSON(w, http.StatusOK, m) -} - -func (st *state) handleRuntimeCancel(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - m, err := runtimeQuery("cancel", map[string]any{"task_id": id}) - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - if st, _ := m["status"].(float64); st == 404 || fmt.Sprint(m["error"]) == "not_found" { - jsonErr(w, http.StatusNotFound, "task not found") - return - } - writeJSON(w, http.StatusOK, m) -} - -func (st *state) handleRuntimeEvents(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("id") - after := int64(0) - if s := r.URL.Query().Get("after_seq"); s != "" { - fmt.Sscanf(s, "%d", &after) - } - if last := strings.TrimSpace(r.Header.Get("Last-Event-ID")); last != "" { - // Accept "task:seq" or bare seq. - if i := strings.LastIndexByte(last, ':'); i >= 0 { - fmt.Sscanf(last[i+1:], "%d", &after) - } else { - fmt.Sscanf(last, "%d", &after) - } - } - wantSSE := strings.Contains(r.Header.Get("Accept"), "text/event-stream") || - r.URL.Query().Get("stream") == "1" - - if !wantSSE { - m, err := runtimeQuery("events", map[string]any{"task_id": id, "after_seq": after}) - if err != nil { - jsonErr(w, http.StatusInternalServerError, err.Error()) - return - } - if st, _ := m["status"].(float64); st == 404 || fmt.Sprint(m["error"]) == "not_found" { - jsonErr(w, http.StatusNotFound, "task not found") - return - } - writeJSON(w, http.StatusOK, m) - return - } - - w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.WriteHeader(http.StatusOK) - flusher, _ := w.(http.Flusher) - cursor := after - ticker := time.NewTicker(25 * time.Millisecond) - defer ticker.Stop() - heartbeat := time.NewTicker(15 * time.Second) - defer heartbeat.Stop() - ctx := r.Context() - for { - select { - case <-ctx.Done(): - return - case <-heartbeat.C: - _, _ = io.WriteString(w, ": ping\n\n") - if flusher != nil { - flusher.Flush() - } - case <-ticker.C: - m, err := runtimeQuery("events", map[string]any{"task_id": id, "after_seq": cursor}) - if err != nil { - continue - } - if st, _ := m["status"].(float64); st == 404 { - _, _ = io.WriteString(w, "event: error\ndata: {\"error\":\"not_found\"}\n\n") - if flusher != nil { - flusher.Flush() - } - return - } - evs, _ := m["events"].([]any) - for _, raw := range evs { - b, err := json.Marshal(raw) - if err != nil { - continue - } - var obj map[string]any - _ = json.Unmarshal(b, &obj) - eid := "" - if s, ok := obj["event_id"].(string); ok { - eid = s - } - if seq, ok := obj["seq"].(float64); ok { - cursor = int64(seq) - } - etype, _ := obj["type"].(string) - if etype == "" { - etype = "message" - } - if eid != "" { - _, _ = io.WriteString(w, "id: "+eid+"\n") - } - _, _ = io.WriteString(w, "event: "+etype+"\ndata: "+string(b)+"\n\n") - if flusher != nil { - flusher.Flush() - } - } - } - } -} diff --git a/plugins/web/internal/httpx/routes_ws.go b/plugins/web/internal/httpx/routes_ws.go deleted file mode 100755 index 3a5b662..0000000 --- a/plugins/web/internal/httpx/routes_ws.go +++ /dev/null @@ -1,236 +0,0 @@ -package httpx - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/gorilla/websocket" - "github.com/marqdo/marqdo/plugins/web/internal/plugin" - "github.com/marqdo/marqdo/plugins/web/internal/session" - "github.com/marqdo/marqdo/plugins/web/internal/ws" -) - -const maxWSMessageBytes = 1 << 20 - -var wsUpgrader = websocket.Upgrader{CheckOrigin: sameOrigin} - -// Browsers send Origin for a cross-site WebSocket handshake. Permit clients -// without Origin, but reject browser origins that differ from this application. -func sameOrigin(r *http.Request) bool { - origin := r.Header.Get("Origin") - if origin == "" { - return true - } - u, err := url.Parse(origin) - return err == nil && strings.EqualFold(u.Host, r.Host) -} - -func (st *state) mountWSRoutes(mux routeRegistrar) { - for _, path := range sortedKeys(st.wsRoutes) { - spec := ws.ParseRouteSpec(st.wsRoutes[path]) // mode + optional room_key / on_message - routePath := path - pattern := routePath - if strings.Contains(routePath, "{") { - pattern = goMuxPattern(routePath) - } - mux.HandleFunc("GET "+pattern, func(w http.ResponseWriter, r *http.Request) { - st.handleWS(w, r, routePath, spec) - }) - } -} - -func pathValuesOf(r *http.Request, routePath string) map[string]string { - out := map[string]string{} - // Collect {name} tokens from the route template. - rest := routePath - for { - i := strings.Index(rest, "{") - if i < 0 { - break - } - rest = rest[i+1:] - j := strings.Index(rest, "}") - if j < 0 { - break - } - name := rest[:j] - name = strings.TrimPrefix(name, "*") - if name != "" { - if v := r.PathValue(name); v != "" { - out[name] = v - } - } - rest = rest[j+1:] - } - return out -} - -func (st *state) handleWS(w http.ResponseWriter, r *http.Request, path string, spec ws.RouteSpec) { - if spec.RequireAuth && session.UsernameFromCookie(r.Header.Get("Cookie")) == "" { - http.Error(w, "WebSocket authentication required", http.StatusUnauthorized) - return - } - conn, err := wsUpgrader.Upgrade(w, r, nil) - if err != nil { - return - } - defer conn.Close() - conn.SetReadLimit(maxWSMessageBytes) - - vals := pathValuesOf(r, path) - switch spec.Mode { - case ws.ModeEcho: - for { - mt, data, err := conn.ReadMessage() - if err != nil { - return - } - if mt == websocket.TextMessage { - if err := conn.WriteMessage(websocket.TextMessage, data); err != nil { - return - } - } else if mt == websocket.CloseMessage { - return - } - } - case ws.ModeDrain: - for { - mt, _, err := conn.ReadMessage() - if err != nil || mt == websocket.CloseMessage { - return - } - } - case ws.ModeBroadcast, ws.ModeRoom: - room := path - if spec.RoomKey != "" { - room = ws.ExpandTemplate(spec.RoomKey, vals) - } else if len(vals) > 0 { - room = ws.ExpandTemplate(path, vals) - } - user := session.UsernameFromCookie(r.Header.Get("Cookie")) - if user == "" { - user = "anon" - } - ch := ws.JoinRoom(room) - defer ws.LeaveRoom(room, ch) - - presenceRoom := room + ".presence" - var presenceCh chan string - if spec.Presence { - presenceCh = ws.JoinRoom(presenceRoom) - defer ws.LeaveRoom(presenceRoom, presenceCh) - ws.PublishRoom(presenceRoom, presenceJSON("join", user, room)) - defer ws.PublishRoom(presenceRoom, presenceJSON("leave", user, room)) - } - - done := make(chan struct{}) - go func() { - defer close(done) - for { - mt, data, err := conn.ReadMessage() - if err != nil { - return - } - if mt == websocket.TextMessage { - text := string(data) - if spec.OnMessage != "" { - out, err := plugin.CallLibPath(spec.OnMessage, map[string]any{ - "message": text, - "room": room, - "path": path, - "user": user, - }) - if err != nil { - _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"error":`+jsonQuote(err.Error())+`}`)) - continue - } - skip, rewritten := interpretOnMessage(out, text) - if skip { - continue - } - text = rewritten - } - ws.PublishRoom(room, text) - } else if mt == websocket.CloseMessage { - return - } - } - }() - - for { - select { - case <-done: - return - case text, ok := <-ch: - if !ok { - return - } - if err := conn.WriteMessage(websocket.TextMessage, []byte(text)); err != nil { - return - } - case text, ok := <-presenceOrNil(presenceCh): - if presenceCh == nil { - continue - } - if !ok { - return - } - if err := conn.WriteMessage(websocket.TextMessage, []byte(text)); err != nil { - return - } - } - } - default: - return - } -} - -func presenceOrNil(ch chan string) <-chan string { - if ch == nil { - return nil - } - return ch -} - -func presenceJSON(event, user, room string) string { - b, _ := json.Marshal(map[string]any{ - "type": "presence", - "event": event, - "user": user, - "room": room, - }) - return string(b) -} - -func jsonQuote(s string) string { - b, _ := json.Marshal(s) - return string(b) -} - -func interpretOnMessage(out any, original string) (skip bool, text string) { - text = original - m, ok := out.(map[string]any) - if !ok { - if s, ok := out.(string); ok && s != "" { - return false, s - } - return false, original - } - if v, ok := m["skip"]; ok && boolish(v) { - return true, "" - } - if v, ok := m["drop"]; ok && boolish(v) { - return true, "" - } - if v, ok := m["message"]; ok { - text = fmt.Sprint(v) - } else if v, ok := m["消息"]; ok { - text = fmt.Sprint(v) - } else if v, ok := m["text"]; ok { - text = fmt.Sprint(v) - } - return false, text -} diff --git a/plugins/web/internal/httpx/routes_ws_test.go b/plugins/web/internal/httpx/routes_ws_test.go deleted file mode 100755 index 436a2b6..0000000 --- a/plugins/web/internal/httpx/routes_ws_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package httpx - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/ws" -) - -func TestHandleWSRejectsUnauthenticatedHandshake(t *testing.T) { - st := &state{} - r := httptest.NewRequest("GET", "http://app.example/live", nil) - w := httptest.NewRecorder() - st.handleWS(w, r, "/live", ws.RouteSpec{Mode: ws.ModeBroadcast, RequireAuth: true}) - if w.Code != http.StatusUnauthorized { - t.Fatalf("unauthenticated ws handshake code=%d, want 401", w.Code) - } -} - -func TestHandleWSAllowsPublicRouteThroughAuthGate(t *testing.T) { - st := &state{} - r := httptest.NewRequest("GET", "http://app.example/live", nil) - w := httptest.NewRecorder() - // Public route: must not 401. Upgrade then fails on the recorder (no - // Hijacker), which is fine — only the auth gate is under test. - st.handleWS(w, r, "/live", ws.RouteSpec{Mode: ws.ModeBroadcast, RequireAuth: false}) - if w.Code == http.StatusUnauthorized { - t.Fatalf("public ws route unexpectedly requires authentication") - } -} - -func TestSameOriginWebSocketHandshake(t *testing.T) { - cases := []struct { - name string - origin string - want bool - }{ - {name: "non-browser client", want: true}, - {name: "same origin", origin: "https://app.example", want: true}, - {name: "different origin", origin: "https://evil.example", want: false}, - {name: "malformed origin", origin: "://bad", want: false}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - r := httptest.NewRequest("GET", "http://app.example/live", nil) - if tc.origin != "" { - r.Header.Set("Origin", tc.origin) - } - if got := sameOrigin(r); got != tc.want { - t.Fatalf("sameOrigin(%q)=%v, want %v", tc.origin, got, tc.want) - } - }) - } -} diff --git a/plugins/web/internal/httpx/runtime_routes_test.go b/plugins/web/internal/httpx/runtime_routes_test.go deleted file mode 100755 index ce7320e..0000000 --- a/plugins/web/internal/httpx/runtime_routes_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package httpx - -import ( - "testing" -) - -func TestSystemRuntimeRoutesListed(t *testing.T) { - // Compile-time presence: handlers must be addressable. - var st state - _ = st.handleRuntimeAdmit - _ = st.handleRuntimeCancel - _ = st.handleRuntimeEvents - _ = st.handleRuntimeGet -} diff --git a/plugins/web/internal/httpx/sse_bridge_test.go b/plugins/web/internal/httpx/sse_bridge_test.go deleted file mode 100755 index 53769ad..0000000 --- a/plugins/web/internal/httpx/sse_bridge_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package httpx - -import ( - "os" - "path/filepath" - "sync" - "testing" - "time" -) - -// M-R0: second stream must fail before rewriting A's forward/cancel env. -func TestLegacySSEBridgeSingleFlight(t *testing.T) { - if !tryAcquireLegacySSEBridge() { - t.Fatal("expected first acquire to succeed") - } - fwdA := filepath.Join(t.TempDir(), "a.ndjson") - tokA := filepath.Join(t.TempDir(), "a.tok") - if err := os.WriteFile(fwdA, nil, 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(tokA, nil, 0o600); err != nil { - t.Fatal(err) - } - t.Setenv("MARQDO_EVENT_FORWARD", fwdA) - t.Setenv("MARQDO_CANCEL_TOKEN", tokA) - legacySSEBridgeActive.Store(1) - - if tryAcquireLegacySSEBridge() { - releaseLegacySSEBridge() - t.Fatal("second acquire must fail while bridge held") - } - active, fwd, tok := legacySSEBridgeSnapshot() - if !active { - t.Fatal("bridge should remain active for holder A") - } - if fwd != fwdA || tok != tokA { - t.Fatalf("rejected second stream rewrote env: fwd=%q tok=%q", fwd, tok) - } - - releaseLegacySSEBridge() - if tryAcquireLegacySSEBridge() { - releaseLegacySSEBridge() - } else { - t.Fatal("bridge should be free after release") - } -} - -// M-R0: cancel-token file must not be deleted while bridge holder waits. -// (sse-live observer disconnect no longer cancels by default — see cancelOnDisconnect.) -func TestCancelTokenSurvivesUntilHolderExits(t *testing.T) { - dir := t.TempDir() - tok := filepath.Join(dir, "cancel.tok") - if err := os.WriteFile(tok, nil, 0o600); err != nil { - t.Fatal(err) - } - if err := writeCancelToken(tok); err != nil { - t.Fatal(err) - } - body, err := os.ReadFile(tok) - if err != nil { - t.Fatalf("token must still exist after cancel mark: %v", err) - } - if string(body) != "cancelled" { - t.Fatalf("body=%q", body) - } -} - -func TestDrainForwardCarryHalfFrames(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "evt.ndjson") - if err := os.WriteFile(path, []byte(`{"t":"部`), 0o600); err != nil { - t.Fatal(err) - } - var lines []string - off, carry := drainForwardCarry(path, 0, "", func(line string) { - lines = append(lines, line) - }) - if len(lines) != 0 { - t.Fatalf("incomplete UTF-8 frame must stay in carry, got %#v", lines) - } - f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteString("分\"}\n{\"t\":\"ok\"}\n"); err != nil { - t.Fatal(err) - } - _ = f.Close() - off, carry = drainForwardCarry(path, off, carry, func(line string) { - lines = append(lines, line) - }) - if len(lines) != 2 { - t.Fatalf("got %d lines %#v carry=%q off=%d", len(lines), lines, carry, off) - } - if carry != "" { - t.Fatalf("carry should be empty, got %q", carry) - } -} - -func TestDrainForwardCarryCRLFAndSplit(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "evt.ndjson") - part1 := []byte("{\"a\":1}\r\n{\"b\":") - if err := os.WriteFile(path, part1, 0o600); err != nil { - t.Fatal(err) - } - var lines []string - off, carry := drainForwardCarry(path, 0, "", func(line string) { - lines = append(lines, line) - }) - if len(lines) != 1 || lines[0] != `{"a":1}` { - t.Fatalf("first frame %#v", lines) - } - f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteString("2}\n"); err != nil { - t.Fatal(err) - } - _ = f.Close() - _, carry = drainForwardCarry(path, off, carry, func(line string) { - lines = append(lines, line) - }) - if len(lines) != 2 || lines[1] != `{"b":2}` { - t.Fatalf("split frame %#v carry=%q", lines, carry) - } -} - -func TestLegacySSEBridgeConcurrentReject(t *testing.T) { - var wg sync.WaitGroup - acquired := 0 - var mu sync.Mutex - for i := 0; i < 8; i++ { - wg.Add(1) - go func() { - defer wg.Done() - if tryAcquireLegacySSEBridge() { - mu.Lock() - acquired++ - mu.Unlock() - time.Sleep(20 * time.Millisecond) - releaseLegacySSEBridge() - } - }() - } - wg.Wait() - if acquired < 1 { - t.Fatal("expected at least one acquirer") - } -} diff --git a/plugins/web/internal/httpx/view_resources.go b/plugins/web/internal/httpx/view_resources.go deleted file mode 100755 index c8069f4..0000000 --- a/plugins/web/internal/httpx/view_resources.go +++ /dev/null @@ -1,185 +0,0 @@ -package httpx - -import ( - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/artifact" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/form" - "github.com/marqdo/marqdo/plugins/web/internal/render" - "github.com/marqdo/marqdo/plugins/web/internal/tenant" -) - -// ValidateViewResource validates the closed Resource contracts without IO. -// Assembly calls this before listening; request rendering validates again. -func ValidateViewResource(resource map[string]any) (string, error) { - kind, _ := resource["_type"].(string) - switch kind { - case "document_head": - _, err := artifact.ParseDocumentHead(resource) - return "", err - case "data_query": - if source, ok := resource["source"].(string); !ok || strings.TrimSpace(source) == "" { - return "", fmt.Errorf("data_query: source must be a nonempty table name") - } - for _, key := range []string{"order", "link_prefix"} { - if value, exists := resource[key]; exists { - if _, ok := value.(string); !ok { - return "", fmt.Errorf("data_query: %s must be text", key) - } - } - } - for _, key := range []string{"detail", "tenant_scope"} { - if value, exists := resource[key]; exists { - if _, ok := value.(bool); !ok { - return "", fmt.Errorf("data_query: %s must be boolean", key) - } - } - } - if raw, exists := resource["limit"]; exists { - n, ok := raw.(float64) - if !ok || n < 1 || n > 1000 || n != float64(int64(n)) { - return "", fmt.Errorf("data_query: limit must be an integer in 1..1000") - } - } - if prefix, _ := resource["link_prefix"].(string); prefix != "" && (!strings.HasPrefix(prefix, "/") || strings.HasPrefix(prefix, "//")) { - return "", fmt.Errorf("data_query: link_prefix must be site-relative") - } - if where := resource["where"]; where != nil { - switch where.(type) { - case map[string]any, []any: - default: - return "", fmt.Errorf("data_query: where must be a native condition map or list") - } - } - case "form_ref": - if id, ok := resource["id"].(string); !ok || strings.TrimSpace(id) == "" { - return "", fmt.Errorf("form_ref: id must name an explicitly mounted form") - } - case "view_navigation": - region, _ := resource["region"].(string) - if region != "nav" && region != "sidebar" && region != "footer" { - return "", fmt.Errorf("view_navigation: region must be nav, sidebar or footer") - } - switch resource["items"].(type) { - case map[string]any, []any: - default: - return "", fmt.Errorf("view_navigation: items must be link records") - } - default: - return "", fmt.Errorf("unsupported View Resource %q", kind) - } - return "", nil -} - -var viewParameter = regexp.MustCompile(`\{([^{}]+)\}`) - -// Copy parameterized conditions without mutating the retained startup nodes. -func resourceWhere(value any, params map[string]any) (any, error) { - switch value := value.(type) { - case string: - var missing string - out := viewParameter.ReplaceAllStringFunc(value, func(token string) string { - key := token[1 : len(token)-1] - actual, ok := params[key] - if !ok { - missing = key - return token - } - return fmt.Sprint(actual) - }) - if missing != "" { - return nil, fmt.Errorf("data_query: missing route parameter %q", missing) - } - return out, nil - case map[string]any: - out := make(map[string]any, len(value)) - for key, item := range value { - resolved, err := resourceWhere(item, params) - if err != nil { - return nil, err - } - out[key] = resolved - } - return out, nil - case []any: - out := make([]any, len(value)) - for i, item := range value { - resolved, err := resourceWhere(item, params) - if err != nil { - return nil, err - } - out[i] = resolved - } - return out, nil - default: - return value, nil - } -} - -func (st *state) renderViewResource(resource, page map[string]any, request *http.Request) (string, error) { - if _, err := ValidateViewResource(resource); err != nil { - return "", err - } - switch resource["_type"] { - case "document_head": - return "", nil - case "data_query": - if st.dbURL == "" { - return "", fmt.Errorf("data_query: the application has no database resource") - } - params, _ := page["params"].(map[string]any) - where, err := resourceWhere(resource["where"], params) - if err != nil { - return "", err - } - scoped, _ := resource["tenant_scope"].(bool) - if scoped && !st.tenant.Enabled() { - return "", fmt.Errorf("data_query: scoped query requires a tenant policy") - } - if scoped || st.tenant.DefaultScope { - id := tenant.FromContext(request.Context()) - if id == "" { - return "", fmt.Errorf("data_query: tenant required") - } - where = tenant.MergeWhere(where, st.tenant.Column, id) - } - limit := int64(50) - if n, ok := resource["limit"].(float64); ok { - limit = int64(n) - } - order, _ := resource["order"].(string) - rows, err := db.Select(st.dbURL, resource["source"].(string), limit, db.SelectOpts{Where: where, Order: order}) - if err != nil { - return "", err - } - detail, _ := resource["detail"].(bool) - prefix, _ := resource["link_prefix"].(string) - return render.RenderQueryRows(rows["rows"], detail, prefix), nil - case "form_ref": - id := resource["id"].(string) - selected, ok := st.forms[id].(map[string]any) - if !ok { - return "", fmt.Errorf("form_ref: form %q was not explicitly mounted", id) - } - csrf, _ := page["_csrf"].(string) - return form.RenderBodyCtx(selected, id, nil, nil, csrf, st.requestContext(request, nil)), nil - case "view_navigation": - region := resource["region"].(string) - navigation := map[string]any{region: resource["items"]} - if region == "nav" { - navigation["nav"] = resource["items"] - } - if logged, ok := page["_logged_in"]; ok { - navigation["_logged_in"] = logged - } - if user, ok := page["_nav_user"]; ok { - navigation["_nav_user"] = user - } - return render.RenderPage(navigation, "", region), nil - } - return "", fmt.Errorf("unsupported View Resource") -} diff --git a/plugins/web/internal/httpx/view_resources_test.go b/plugins/web/internal/httpx/view_resources_test.go deleted file mode 100755 index 39bcaba..0000000 --- a/plugins/web/internal/httpx/view_resources_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package httpx - -import ( - "net/http" - "net/http/httptest" - "net/url" - "path/filepath" - "regexp" - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/artifact" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/form" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func resourceNode(resource map[string]any) map[string]any { - return map[string]any{"type": "resource", "value": resource, "slot": "content"} -} - -func TestViewResourcesObserveRequestsFormsAndNavigation(t *testing.T) { - uri := "sqlite:" + filepath.Join(t.TempDir(), "view.db") - fields := []any{ - map[string]any{"name": "id", "type": "integer", "nullable": false}, - map[string]any{"name": "title", "type": "text", "nullable": false}, - map[string]any{"name": "slug", "type": "text", "nullable": true}, - map[string]any{"name": "summary", "type": "text", "nullable": true}, - map[string]any{"name": "body", "type": "text", "nullable": true}, - } - if _, err := db.Init(uri, "articles", fields); err != nil { - t.Fatal(err) - } - if _, err := db.Insert(uri, "articles", map[string]any{ - "title": "Original ", "slug": "first", "summary": "Short summary", "body": "Full article body", - }); err != nil { - t.Fatal(err) - } - query := map[string]any{"_type": "data_query", "source": "articles", "limit": float64(50), "link_prefix": "/post/"} - navigation := map[string]any{"_type": "view_navigation", "region": "nav", "items": []any{ - map[string]any{"label": "Guest login", "href": "/admin/login", "when": "guest"}, - map[string]any{"label": "Private desk", "href": "/admin", "when": "auth"}, - }} - page := map[string]any{"title": "View resources", "artifact_nodes": []any{ - resourceNode(navigation), resourceNode(query), - resourceNode(map[string]any{"_type": "form_ref", "id": "article"}), - }} - bag := app.New(map[string]any{"page": page, "db": map[string]any{"url": uri}}) - var err error - bag, err = app.Auth(bag, []any{map[string]any{"username": "admin", "password": "secret", "role": "admin"}}, nil) - if err != nil { - t.Fatal(err) - } - selected := form.SetFields(form.New("articles", "insert", ""), fields[1:2]) - selected = form.SetRules(selected, []any{map[string]any{"field": "title", "rule": "required", "message": "Title required"}}) - selected = form.SetLabels(selected, "Publish", "Cancel", "/") - bag, err = app.MountForm(bag, "article", selected) - if err != nil { - t.Fatal(err) - } - detailed := map[string]any{"_type": "data_query", "source": "articles", "detail": true, - "where": map[string]any{"slug": "{slug}"}} - bag, err = app.Route(bag, "/post/{slug}", map[string]any{"title": "Article", "artifact_nodes": []any{resourceNode(detailed)}}) - if err != nil { - t.Fatal(err) - } - handler, err := NewHandler(bag, "") - if err != nil { - t.Fatal(err) - } - call := func(method, path, body, cookie string) *httptest.ResponseRecorder { - request := httptest.NewRequest(method, path, strings.NewReader(body)) - if body != "" { - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - } - if cookie != "" { - request.Header.Set("Cookie", cookie) - } - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - return recorder - } - initial := call("GET", "/", "", "") - if initial.Code != http.StatusOK { - t.Fatalf("initial: %d %s", initial.Code, initial.Body.String()) - } - text := initial.Body.String() - if !strings.Contains(text, "Guest login") || strings.Contains(text, "Private desk") || - !strings.Contains(text, "Short summary") || strings.Contains(text, "Full article body") || - !strings.Contains(text, "Original <title>") { - t.Fatal(text) - } - cookies := initial.Result().Cookies() - if len(cookies) == 0 { - t.Fatal("rendered form has no actual session cookie") - } - cookie := cookies[0].Name + "=" + cookies[0].Value - match := regexp.MustCompile(`name="_csrf" value="([^"]+)"`).FindStringSubmatch(text) - if len(match) != 2 { - t.Fatal("resource form omitted its CSRF token") - } - token := match[1] - bad := call("POST", "/_form/article", "title=Rejected&_csrf=wrong", cookie) - if bad.Code != http.StatusForbidden { - t.Fatalf("bad csrf accepted: %d %s", bad.Code, bad.Body.String()) - } - invalid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {""}}.Encode(), cookie) - if invalid.Code != http.StatusOK || !strings.Contains(invalid.Body.String(), "Title required") || - !strings.Contains(invalid.Body.String(), `name="_csrf" value="`+token+`"`) { - t.Fatalf("validation retry: %d %s", invalid.Code, invalid.Body.String()) - } - valid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {"Inserted after startup"}, "_mq_return": {"/new"}}.Encode(), cookie) - if valid.Code != http.StatusSeeOther || valid.Header().Get("Location") != "/" { - t.Fatalf("submit: %d %s", valid.Code, valid.Body.String()) - } - current := call("GET", "/", "", cookie) - if !strings.Contains(current.Body.String(), "Inserted after startup") { - t.Fatal("query cached startup rows") - } - fragment := call("GET", "/_part/main", "", cookie) - if fragment.Code != http.StatusOK || !strings.Contains(fragment.Body.String(), "Inserted after startup") || - !strings.Contains(fragment.Body.String(), `name="_csrf" value="`+token+`"`) || - strings.Contains(fragment.Body.String(), "<!DOCTYPE") { - t.Fatalf("request fragment lost context: %d %s", fragment.Code, fragment.Body.String()) - } - unknown := call("GET", "/_part/not-declared", "", cookie) - if unknown.Code != http.StatusNotFound { - t.Fatalf("unknown View slot: %d", unknown.Code) - } - - detail := call("GET", "/post/first?slug=other", "", cookie) - if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), "Full article body") || - strings.Contains(detail.Body.String(), "Short summary") { - t.Fatal(detail.Body.String()) - } - if detailed["where"].(map[string]any)["slug"] != "{slug}" { - t.Fatal("request mutated retained Resource") - } - sid, ok := session.IDFromCookie(cookie) - if !ok || !session.SetValue(sid, "username", "admin") { - t.Fatal("could not establish fixture session") - } - logged := call("GET", "/", "", cookie) - if strings.Contains(logged.Body.String(), "Guest login") || !strings.Contains(logged.Body.String(), "Private desk") { - t.Fatal(logged.Body.String()) - } -} - -func TestViewResourceValidationDoesNotQueryAndFailuresRemainVisible(t *testing.T) { - query := map[string]any{"_type": "data_query", "source": "missing"} - if _, err := artifact.RenderNodesWithResources([]any{resourceNode(query)}, ValidateViewResource); err != nil { - t.Fatalf("startup unexpectedly queried missing DB: %v", err) - } - for _, resource := range []map[string]any{ - {"_type": "invented"}, {"_type": "data_query", "source": "items", "limit": 1.5}, - {"_type": "data_query", "source": "items", "link_prefix": "javascript:"}, - {"_type": "form_ref", "id": ""}, - } { - if _, err := ValidateViewResource(resource); err == nil { - t.Fatalf("bad resource accepted: %#v", resource) - } - } - if _, err := artifact.RenderNodes([]any{resourceNode(query)}); err == nil { - t.Fatal("offline render invented request context") - } - bag := app.New(map[string]any{"page": map[string]any{"artifact_nodes": []any{resourceNode(query)}}}) - handler, err := NewHandler(bag, "") - if err != nil { - t.Fatal(err) - } - response := httptest.NewRecorder() - handler.ServeHTTP(response, httptest.NewRequest("GET", "/", nil)) - if response.Code != http.StatusInternalServerError || !strings.Contains(response.Body.String(), "no database") { - t.Fatalf("missing backend became successful empty content: %d %s", response.Code, response.Body.String()) - } -} - -func TestViewHeadResourcesServeInHeadAndNeverLeakIntoFragments(t *testing.T) { - nodes := []any{ - map[string]any{"type": "resource", "value": map[string]any{"_type": "document_head", "meta": map[string]any{"key": "description", "value": "Actual SEO"}, "links": []any{map[string]any{"rel": "stylesheet", "href": "/theme.css"}}}}, - map[string]any{"type": "markdown", "slot": "content", "value": "# Real content"}, - } - bag := app.New(map[string]any{"page": map[string]any{"title": "Head test", "artifact_nodes": nodes}}) - handler, err := NewHandler(bag, "") - if err != nil { - t.Fatal(err) - } - for _, path := range []string{"/", "/_part/main", "/_part/content"} { - response := httptest.NewRecorder() - handler.ServeHTTP(response, httptest.NewRequest("GET", path, nil)) - body := response.Body.String() - if response.Code != http.StatusOK || !strings.Contains(body, "Real content") { - t.Fatalf("%s %d %s", path, response.Code, body) - } - if path == "/" { - head, rest, _ := strings.Cut(body, "</head>") - if !strings.Contains(head, `<meta name="description" content="Actual SEO"`) || !strings.Contains(head, `href="/theme.css"`) || strings.Contains(rest, "Actual SEO") { - t.Fatal(body) - } - } else if strings.Contains(body, "Actual SEO") || strings.Contains(body, "<head") || strings.Contains(body, "theme.css") { - t.Fatal(body) - } - } -} diff --git a/plugins/web/internal/invoke/invoke.go b/plugins/web/internal/invoke/invoke.go deleted file mode 100755 index b46016f..0000000 --- a/plugins/web/internal/invoke/invoke.go +++ /dev/null @@ -1,183 +0,0 @@ -// Package invoke ports offline invoke route bags (Rust invoke.rs). -package invoke - -import ( - "fmt" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// Options is one invoke mount (web_app_invoke args). -type Options struct { - Path string - Method string - Fn string - Body string - Return string - Class string -} - -// RoutesFromTable normalizes `|路径|方法|函数|正文|返回|类别|` into invoke_routes map keys. -func RoutesFromTable(tableV any) map[string]any { - rows, _ := table.AsRows(tableV).([]any) - out := map[string]any{} - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - path := strings.Trim(strings.TrimSpace(col(m, "路径", "path", "Path")), "/") - if path == "" { - continue - } - fnPath := col(m, "函数", "fn", "function", "Function") - if fnPath == "" { - continue - } - method := strings.ToUpper(strings.TrimSpace(col(m, "方法", "method", "Method"))) - if method == "" { - method = "POST" - } - body := strings.ToLower(strings.TrimSpace(col(m, "正文", "body", "Body"))) - if body == "" { - body = "json" - } - ret := strings.ToLower(strings.TrimSpace(col(m, "返回", "return", "Return"))) - if ret == "" { - ret = "json" - } - class := strings.ToLower(strings.TrimSpace(col(m, "类别", "class", "Class"))) - out[path] = routeEntry(method, fnPath, body, ret, class) - } - return out -} - -// Register adds one invoke route to app.invoke_routes (Rust web_app_invoke). -func Register(appBag map[string]any, opts Options) (map[string]any, error) { - fnPath := strings.TrimSpace(opts.Fn) - if fnPath == "" { - return nil, fmt.Errorf("invoke requires `fn`") - } - if !strings.Contains(fnPath, ".") || strings.Contains(fnPath, "/") || strings.Contains(fnPath, "#") { - return nil, fmt.Errorf("invoke `fn` must be `lib.member` (imported on the entry module)") - } - path, err := app.NormalizeRoutePath(opts.Path, appBag) - if err != nil { - return nil, err - } - key := strings.TrimPrefix(path, "/") - method := strings.ToUpper(strings.TrimSpace(opts.Method)) - if method == "" { - method = "POST" - } - body := strings.ToLower(strings.TrimSpace(opts.Body)) - if body == "" { - body = "json" - } - ret := strings.ToLower(strings.TrimSpace(opts.Return)) - if ret == "" { - ret = "json" - } - class := strings.ToLower(strings.TrimSpace(opts.Class)) - out := clone(appBag) - routes := map[string]any{} - if r, ok := out["invoke_routes"].(map[string]any); ok { - routes = clone(r) - } - routes[key] = routeEntry(method, fnPath, body, ret, class) - out["invoke_routes"] = routes - return out, nil -} - -// OptionsFromArgs parses web_app_invoke ABI args. -func OptionsFromArgs(args map[string]any) (Options, error) { - path, err := argStrReq(args, "path", "路径") - if err != nil { - return Options{}, err - } - fnPath, err := argStrReq(args, "fn", "function", "函数") - if err != nil { - return Options{}, err - } - method, _ := argStr(args, "method", "方法") - body, _ := argStr(args, "body", "正文") - ret, _ := argStr(args, "return", "返回") - class, _ := argStr(args, "class", "类别") - return Options{ - Path: path, - Method: method, - Fn: fnPath, - Body: body, - Return: ret, - Class: class, - }, nil -} - -func routeEntry(method, fnPath, body, ret, class string) map[string]any { - m := map[string]any{ - "method": method, - "fn": fnPath, - "body": body, - "return": ret, - } - if class != "" { - m["class"] = class - } - return m -} - -func col(m map[string]any, keys ...string) string { - for _, k := range keys { - if v, ok := m[k]; ok { - return cellText(v) - } - } - return "" -} - -func cellText(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - default: - return fmt.Sprint(t) - } -} - -func first(args map[string]any, keys ...string) (any, bool) { - for _, k := range keys { - if v, ok := args[k]; ok && v != nil { - return v, true - } - } - return nil, false -} - -func argStr(args map[string]any, keys ...string) (string, bool) { - v, ok := first(args, keys...) - if !ok { - return "", false - } - s, _ := v.(string) - return s, true -} - -func argStrReq(args map[string]any, keys ...string) (string, error) { - s, ok := argStr(args, keys...) - if !ok || strings.TrimSpace(s) == "" { - return "", fmt.Errorf("missing `%s`", keys[0]) - } - return s, nil -} - -func clone(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} diff --git a/plugins/web/internal/invoke/invoke_test.go b/plugins/web/internal/invoke/invoke_test.go deleted file mode 100755 index 3c348fe..0000000 --- a/plugins/web/internal/invoke/invoke_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package invoke_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/invoke" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" -) - -func TestRoutesFromTable(t *testing.T) { - tbl := map[string]any{ - "path": []any{"/api/echo"}, - "method": []any{"POST"}, - "fn": []any{"demo.echo"}, - "body": []any{"json"}, - "return": []any{"json"}, - } - routes := invoke.RoutesFromTable(tbl) - echo, ok := routes["api/echo"].(map[string]any) - if !ok { - t.Fatalf("routes=%v", routes) - } - if echo["fn"] != "demo.echo" { - t.Fatalf("fn=%v", echo["fn"]) - } - if echo["method"] != "POST" { - t.Fatalf("method=%v", echo["method"]) - } -} - -func TestRegisterInvokeRoute(t *testing.T) { - a := app.New(nil) - out, err := invoke.Register(a, invoke.Options{ - Path: "/api/ping", - Method: "GET", - Fn: "demo.ping", - Body: "query", - }) - if err != nil { - t.Fatal(err) - } - routes := out["invoke_routes"].(map[string]any) - ping, ok := routes["api/ping"].(map[string]any) - if !ok { - t.Fatalf("routes=%v", routes) - } - if ping["method"] != "GET" { - t.Fatalf("method=%v", ping["method"]) - } - if ping["body"] != "query" { - t.Fatalf("body=%v", ping["body"]) - } -} - -func TestRegisterRejectsInvalidFn(t *testing.T) { - _, err := invoke.Register(app.New(nil), invoke.Options{ - Path: "/api/x", - Fn: "not-valid", - }) - if err == nil || !strings.Contains(err.Error(), "lib.member") { - t.Fatalf("want lib.member error, got %v", err) - } -} - -func TestConfigureMergesInvokeTable(t *testing.T) { - a := app.New(nil) - invokeTbl := map[string]any{ - "path": []any{"/api/echo"}, - "method": []any{"POST"}, - "fn": []any{"demo.echo"}, - "body": []any{"json"}, - "return": []any{"json"}, - } - out, err := middleware.Configure(a, map[string]any{"invoke": invokeTbl}) - if err != nil { - t.Fatal(err) - } - routes := out["invoke_routes"].(map[string]any) - if routes["api/echo"] == nil { - t.Fatalf("invoke_routes=%v", routes) - } -} diff --git a/plugins/web/internal/middleware/middleware.go b/plugins/web/internal/middleware/middleware.go deleted file mode 100755 index 312bc79..0000000 --- a/plugins/web/internal/middleware/middleware.go +++ /dev/null @@ -1,434 +0,0 @@ -// Package middleware ports declarative CORS/security/compress/JSON configure -// from the Rust web plugin (配置即数据、装配即函数). -package middleware - -import ( - "fmt" - "strconv" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/invoke" - "github.com/marqdo/marqdo/plugins/web/internal/proxy" - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// Config is the runtime view of app["middleware"]. -type Config struct { - CORS *CORSConfig - Security [][2]string - Compress bool - BodyLimit *uint64 - AccessLog bool - CacheControl string - JSONRoutes []JSONRouteMount -} - -// CORSConfig matches middleware.cors map shape. -type CORSConfig struct { - AllowOrigins []string - Methods []string - Headers []string - ExposeHeaders []string - Credentials bool -} - -// JSONRouteMount is one JSON API route with leading-slash path. -type JSONRouteMount struct { - Path string - Method string - Table string - Where any - Order string - Limit int64 - TenantScope bool -} - -// Configure merges configure tables into app.middleware (Rust web_app_middleware). -func Configure(appBag map[string]any, args map[string]any) (map[string]any, error) { - out := clone(appBag) - mw, _ := out["middleware"].(map[string]any) - if mw == nil { - mw = map[string]any{} - } else { - mw = clone(mw) - } - - if v, ok := args["cors"]; ok && v != nil { - mw["cors"] = CorsFromTable(v) - } - if v, ok := args["security"]; ok && v != nil { - mw["security"] = SecurityFromTable(v) - } - if v, ok := args["compress"]; ok && v != nil { - mw["compress"] = boolish(v) - } - if v, ok := first(args, "access_log", "访问日志"); ok { - mw["access_log"] = boolish(v) - } - if v, ok := first(args, "cache_control", "缓存控制"); ok { - if s := strings.TrimSpace(cellText(v)); s != "" { - mw["cache_control"] = s - } - } - if v, ok := args["body_limit"]; ok && v != nil { - if n, ok := asUint64(v); ok && n > 0 { - mw["body_limit"] = float64(n) - } - } - if v, ok := first(args, "json_routes", "json"); ok && v != nil { - mw["json_routes"] = JSONRoutesFromTable(v) - } - out["middleware"] = mw - - if v, ok := first(args, "proxy", "proxy_routes", "代理"); ok && v != nil { - mergeRouteMap(out, "proxy_routes", proxy.RoutesFromTable(v)) - } - if v, ok := first(args, "invoke", "invoke_routes", "调用"); ok && v != nil { - mergeRouteMap(out, "invoke_routes", invoke.RoutesFromTable(v)) - } - return out, nil -} - -func mergeRouteMap(appBag map[string]any, key string, incoming map[string]any) { - if len(incoming) == 0 { - return - } - existing := map[string]any{} - if r, ok := appBag[key].(map[string]any); ok { - existing = clone(r) - } - for k, v := range incoming { - existing[k] = v - } - appBag[key] = existing -} - -// Parse reads app["middleware"] into Config (Rust middleware::parse). -func Parse(app map[string]any) Config { - var cfg Config - obj, _ := app["middleware"].(map[string]any) - if obj == nil { - return cfg - } - if c, ok := obj["cors"].(map[string]any); ok { - cfg.CORS = parseCORS(c) - } - if sec, ok := obj["security"].(map[string]any); ok { - for k, v := range sec { - s := cellText(v) - if s != "" { - cfg.Security = append(cfg.Security, [2]string{k, s}) - } - } - } - cfg.Compress = boolish(obj["compress"]) - cfg.AccessLog = boolish(obj["access_log"]) - if s := strings.TrimSpace(cellText(obj["cache_control"])); s != "" { - cfg.CacheControl = s - } - if n, ok := asUint64(obj["body_limit"]); ok && n > 0 { - cfg.BodyLimit = &n - } - if routes, ok := obj["json_routes"].(map[string]any); ok { - for path, spec := range routes { - if r, ok := parseJSONRoute(path, spec); ok { - cfg.JSONRoutes = append(cfg.JSONRoutes, r) - } - } - sortJSONRoutes(cfg.JSONRoutes) - } - return cfg -} - -func parseCORS(obj map[string]any) *CORSConfig { - return &CORSConfig{ - AllowOrigins: strList(obj["allow_origins"]), - Methods: strList(obj["methods"]), - Headers: strList(obj["headers"]), - ExposeHeaders: strList(obj["expose_headers"]), - Credentials: boolish(obj["credentials"]), - } -} - -func parseJSONRoute(path string, spec any) (JSONRouteMount, bool) { - m, ok := spec.(map[string]any) - if !ok { - return JSONRouteMount{}, false - } - tableName := strings.TrimSpace(cellText(m["table"])) - if tableName == "" { - return JSONRouteMount{}, false - } - method := strings.ToUpper(strings.TrimSpace(cellText(m["method"]))) - if method == "" { - method = "GET" - } - limit := int64(200) - if n, ok := asInt64(m["limit"]); ok { - limit = n - } - order := strings.TrimSpace(cellText(m["order"])) - p := "/" + strings.TrimPrefix(strings.TrimSpace(path), "/") - r := JSONRouteMount{ - Path: p, - Method: method, - Table: tableName, - Order: order, - Limit: limit, - } - if w, ok := m["where"]; ok && w != nil { - r.Where = w - } - if v, ok := m["tenant_scope"]; ok { - r.TenantScope = boolish(v) - } else if v, ok := m["租户作用域"]; ok { - r.TenantScope = boolish(v) - } - return r, true -} - -func sortJSONRoutes(rs []JSONRouteMount) { - for i := 0; i < len(rs); i++ { - for j := i + 1; j < len(rs); j++ { - if rs[j].Path < rs[i].Path { - rs[i], rs[j] = rs[j], rs[i] - } - } - } -} - -// CorsFromTable normalizes `|允许来源|方法|头|暴露头|凭证|` into middleware.cors. -func CorsFromTable(tableV any) map[string]any { - rows, _ := table.AsRows(tableV).([]any) - var allowOrigins, methods, headers, expose []string - credentials := false - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - origin := col(m, "允许来源", "origin", "Origin") - if origin != "" && origin != "*" { - allowOrigins = append(allowOrigins, origin) - } - for _, part := range strings.Split(col(m, "方法", "methods", "Methods"), ",") { - part = strings.TrimSpace(part) - if part != "" { - methods = append(methods, part) - } - } - for _, part := range strings.Split(col(m, "头", "headers", "Headers"), ",") { - part = strings.TrimSpace(part) - if part != "" { - headers = append(headers, part) - } - } - for _, part := range strings.Split(col(m, "暴露头", "expose_headers", "Expose-Headers"), ",") { - part = strings.TrimSpace(part) - if part != "" { - expose = append(expose, part) - } - } - cred := col(m, "凭证", "credentials", "Credentials") - if strings.EqualFold(cred, "true") || cred == "1" || strings.EqualFold(cred, "yes") { - credentials = true - } - } - return map[string]any{ - "allow_origins": toAnyList(allowOrigins), - "methods": toAnyList(methods), - "headers": toAnyList(headers), - "expose_headers": toAnyList(expose), - "credentials": credentials, - } -} - -// SecurityFromTable normalizes `|头|值|` into middleware.security map. -func SecurityFromTable(tableV any) map[string]any { - rows, _ := table.AsRows(tableV).([]any) - out := map[string]any{} - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - k := col(m, "头", "header", "Header", "name") - v := col(m, "值", "value", "Value") - if k != "" { - out[k] = v - } - } - return out -} - -// JSONRoutesFromTable normalizes `|路径|方法|表|条件|排序|上限|租户作用域|` into json_routes. -func JSONRoutesFromTable(tableV any) map[string]any { - rows, _ := table.AsRows(tableV).([]any) - out := map[string]any{} - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - path := strings.TrimPrefix(strings.TrimSpace(col(m, "路径", "path", "Path")), "/") - if path == "" { - continue - } - method := strings.ToUpper(strings.TrimSpace(col(m, "方法", "method", "Method"))) - if method == "" { - method = "GET" - } - tbl := col(m, "表", "table", "Table") - if tbl == "" { - continue - } - order := col(m, "排序", "order", "Order") - limit := int64(200) - if s := col(m, "上限", "limit", "Limit"); s != "" { - if n, err := strconv.ParseInt(s, 10, 64); err == nil { - limit = n - } - } - spec := map[string]any{ - "method": method, - "table": tbl, - "limit": float64(limit), - } - if order != "" { - spec["order"] = order - } - if scope := col(m, "租户作用域", "tenant_scope", "TenantScope"); scope != "" { - spec["tenant_scope"] = boolish(scope) - } - out[path] = spec - } - return out -} - -func col(m map[string]any, keys ...string) string { - for _, k := range keys { - if v, ok := m[k]; ok { - return cellText(v) - } - } - return "" -} - -func cellText(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - case int: - return strconv.Itoa(t) - case int64: - return strconv.FormatInt(t, 10) - default: - return fmt.Sprint(t) - } -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - switch strings.TrimSpace(t) { - case "true", "True", "1", "yes", "on", "真": - return true - } - return false - case float64: - return t != 0 - case int: - return t != 0 - case int64: - return t != 0 - } - return false -} - -func asUint64(v any) (uint64, bool) { - switch t := v.(type) { - case float64: - if t > 0 { - return uint64(t), true - } - case int64: - if t > 0 { - return uint64(t), true - } - case int: - if t > 0 { - return uint64(t), true - } - case string: - n, err := strconv.ParseUint(strings.TrimSpace(t), 10, 64) - return n, err == nil && n > 0 - } - return 0, false -} - -func asInt64(v any) (int64, bool) { - switch t := v.(type) { - case float64: - return int64(t), true - case int64: - return t, true - case int: - return int64(t), true - case string: - n, err := strconv.ParseInt(strings.TrimSpace(t), 10, 64) - return n, err == nil - } - return 0, false -} - -func strList(v any) []string { - switch t := v.(type) { - case []any: - out := make([]string, 0, len(t)) - for _, x := range t { - if s, ok := x.(string); ok { - out = append(out, s) - } - } - return out - case []string: - return append([]string{}, t...) - } - return nil -} - -func toAnyList(ss []string) []any { - out := make([]any, len(ss)) - for i, s := range ss { - out[i] = s - } - return out -} - -func first(args map[string]any, keys ...string) (any, bool) { - for _, k := range keys { - if v, ok := args[k]; ok && v != nil { - return v, true - } - } - return nil, false -} - -func clone(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} diff --git a/plugins/web/internal/middleware/middleware_test.go b/plugins/web/internal/middleware/middleware_test.go deleted file mode 100755 index 13b7525..0000000 --- a/plugins/web/internal/middleware/middleware_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" -) - -func TestConfigureCORSOrigins(t *testing.T) { - cors := map[string]any{ - "允许来源": []any{"https://a.example", "https://b.example"}, - "方法": []any{"GET,POST", "GET"}, - "头": []any{"Content-Type,Authorization", "Content-Type"}, - "暴露头": []any{"X-Total", ""}, - "凭证": []any{"true", ""}, - } - sec := map[string]any{ - "头": []any{"X-Frame-Options", "X-Content-Type-Options", "Content-Security-Policy"}, - "值": []any{"DENY", "nosniff", "default-src 'self'"}, - } - api := map[string]any{ - "路径": []any{"/api/posts", "/api/publish"}, - "方法": []any{"GET", "POST"}, - "表": []any{"articles", "articles"}, - "条件": []any{"", ""}, - "排序": []any{"-created_at", ""}, - "上限": []any{"20", "10"}, - } - - a := app.New(map[string]any{"page": map[string]any{"title": "mw"}}) - out, err := middleware.Configure(a, map[string]any{ - "cors": cors, - "security": sec, - "compress": true, - "body_limit": float64(1048576), - "json": api, - }) - if err != nil { - t.Fatal(err) - } - mw, _ := out["middleware"].(map[string]any) - if mw == nil { - t.Fatal("missing middleware") - } - cobj, _ := mw["cors"].(map[string]any) - origins, _ := cobj["allow_origins"].([]any) - if len(origins) < 1 || origins[0] != "https://a.example" { - t.Fatalf("allow_origins=%v", origins) - } - methods, _ := cobj["methods"].([]any) - if len(methods) < 2 || methods[1] != "POST" { - t.Fatalf("methods=%v", methods) - } - expose, _ := cobj["expose_headers"].([]any) - if len(expose) < 1 || expose[0] != "X-Total" { - t.Fatalf("expose=%v", expose) - } - if cred, _ := cobj["credentials"].(bool); !cred { - t.Fatal("credentials want true") - } - - secmap, _ := mw["security"].(map[string]any) - if secmap["X-Frame-Options"] != "DENY" { - t.Fatalf("security frame=%v", secmap["X-Frame-Options"]) - } - if mw["compress"] != true { - t.Fatalf("compress=%v", mw["compress"]) - } - if mw["body_limit"] != float64(1048576) { - t.Fatalf("body_limit=%v", mw["body_limit"]) - } - jmap, _ := mw["json_routes"].(map[string]any) - posts, _ := jmap["api/posts"].(map[string]any) - if posts["method"] != "GET" || posts["table"] != "articles" { - t.Fatalf("posts=%v", posts) - } - if posts["order"] != "-created_at" || posts["limit"] != float64(20) { - t.Fatalf("posts order/limit=%v", posts) - } - pub, _ := jmap["api/publish"].(map[string]any) - if pub["method"] != "POST" { - t.Fatalf("publish=%v", pub) - } -} - -func TestParseReadsBag(t *testing.T) { - a := map[string]any{ - "middleware": map[string]any{ - "cors": map[string]any{ - "allow_origins": []any{"https://a.example"}, - "methods": []any{"GET"}, - "credentials": true, - }, - "compress": true, - "body_limit": float64(1000), - "json_routes": map[string]any{ - "api/posts": map[string]any{"method": "GET", "table": "articles", "limit": float64(10)}, - }, - }, - } - cfg := middleware.Parse(a) - if cfg.CORS == nil || len(cfg.CORS.AllowOrigins) != 1 { - t.Fatalf("cors=%v", cfg.CORS) - } - if !cfg.Compress || cfg.BodyLimit == nil || *cfg.BodyLimit != 1000 { - t.Fatalf("cfg=%+v", cfg) - } - if len(cfg.JSONRoutes) != 1 || cfg.JSONRoutes[0].Path != "/api/posts" { - t.Fatalf("json routes=%v", cfg.JSONRoutes) - } -} diff --git a/plugins/web/internal/oidc/oidc.go b/plugins/web/internal/oidc/oidc.go deleted file mode 100755 index 17fd800..0000000 --- a/plugins/web/internal/oidc/oidc.go +++ /dev/null @@ -1,464 +0,0 @@ -// Package oidc implements OAuth 2.0 authorization-code + OIDC userinfo for ext/web. -package oidc - -import ( - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "time" -) - -// Config is the relying-party settings (CFLMY IdP or any OIDC provider). -type Config struct { - Issuer string - ClientID string - ClientSecret string - RedirectURI string - // RedirectOrigins is an optional comma-separated allowlist of origins - // (e.g. "https://qdqc.com,https://www.qdqc.com") used when RedirectURI is a path. - RedirectOrigins string - Scopes string - CallbackPath string - // AuthorizeURL / TokenURL / UserInfoURL override discovery when set. - AuthorizeURL string - TokenURL string - UserInfoURL string -} - -// Enabled reports whether the minimum OIDC fields are present. -func (c Config) Enabled() bool { - return strings.TrimSpace(c.ClientID) != "" && - strings.TrimSpace(c.ClientSecret) != "" && - strings.TrimSpace(c.RedirectURI) != "" && - (strings.TrimSpace(c.Issuer) != "" || strings.TrimSpace(c.AuthorizeURL) != "") -} - -// IsPathRedirect reports whether RedirectURI is a path (resolved per request Host). -func (c Config) IsPathRedirect() bool { - s := strings.TrimSpace(c.RedirectURI) - if s == "" { - return false - } - if strings.HasPrefix(s, "/") { - return true - } - u, err := url.Parse(s) - if err != nil { - return false - } - // scheme-relative or bare path without host - return u.Scheme == "" && u.Host == "" && u.Path != "" -} - -// Callback reports the local path (default /oidc/callback). -func (c Config) Callback() string { - p := strings.TrimSpace(c.CallbackPath) - if p == "" { - ru := strings.TrimSpace(c.RedirectURI) - if c.IsPathRedirect() { - if !strings.HasPrefix(ru, "/") { - ru = "/" + ru - } - return ru - } - if u, err := url.Parse(ru); err == nil && u.Path != "" { - return u.Path - } - return "/oidc/callback" - } - if !strings.HasPrefix(p, "/") { - p = "/" + p - } - return p -} - -// PublicOrigin derives scheme://host from a login/callback request. -// Prefers X-Forwarded-Proto + X-Forwarded-Host (first value), else Host + TLS. -func PublicOrigin(r *http.Request) (string, error) { - if r == nil { - return "", fmt.Errorf("oidc: nil request") - } - scheme := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")) - if i := strings.IndexByte(scheme, ','); i >= 0 { - scheme = strings.TrimSpace(scheme[:i]) - } - if scheme == "" { - if r.TLS != nil { - scheme = "https" - } else { - scheme = "http" - } - } - host := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")) - if i := strings.IndexByte(host, ','); i >= 0 { - host = strings.TrimSpace(host[:i]) - } - if host == "" { - host = strings.TrimSpace(r.Host) - } - if host == "" { - return "", fmt.Errorf("oidc: empty Host") - } - return scheme + "://" + host, nil -} - -// ResolveRedirectURI returns the absolute redirect_uri for this request. -// Absolute RedirectURI is returned unchanged; path RedirectURI is joined to the request origin. -func (c Config) ResolveRedirectURI(r *http.Request) (string, error) { - ru := strings.TrimSpace(c.RedirectURI) - if ru == "" { - return "", fmt.Errorf("oidc: empty redirect_uri") - } - if !c.IsPathRedirect() { - return ru, nil - } - origin, err := PublicOrigin(r) - if err != nil { - return "", err - } - path := ru - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - abs := origin + path - if err := c.checkOriginAllowlist(origin); err != nil { - return "", err - } - return abs, nil -} - -// AllowedOrigins returns trimmed non-empty origins from RedirectOrigins. -func (c Config) AllowedOrigins() []string { - raw := strings.TrimSpace(c.RedirectOrigins) - if raw == "" { - return nil - } - var out []string - for _, p := range strings.Split(raw, ",") { - p = strings.TrimRight(strings.TrimSpace(p), "/") - if p != "" { - out = append(out, p) - } - } - return out -} - -func (c Config) checkOriginAllowlist(origin string) error { - allowed := c.AllowedOrigins() - if len(allowed) == 0 { - return nil - } - origin = strings.TrimRight(strings.TrimSpace(origin), "/") - for _, a := range allowed { - if strings.EqualFold(a, origin) { - return nil - } - } - return fmt.Errorf("oidc: origin %q not in redirect_origins", origin) -} - -type discoveryDoc struct { - AuthorizationEndpoint string `json:"authorization_endpoint"` - TokenEndpoint string `json:"token_endpoint"` - UserinfoEndpoint string `json:"userinfo_endpoint"` -} - -// ResolveEndpoints fills Authorize/Token/UserInfo from discovery when missing. -func (c *Config) ResolveEndpoints(client *http.Client) error { - if c.AuthorizeURL != "" && c.TokenURL != "" && c.UserInfoURL != "" { - return nil - } - issuer := strings.TrimRight(strings.TrimSpace(c.Issuer), "/") - if issuer == "" { - return fmt.Errorf("oidc: issuer or explicit endpoints required") - } - if client == nil { - client = &http.Client{Timeout: 15 * time.Second} - } - discURL := issuer + "/.well-known/openid-configuration" - res, err := client.Get(discURL) - if err != nil { - return fmt.Errorf("oidc discovery: %w", err) - } - defer res.Body.Close() - body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - if err != nil { - return err - } - if res.StatusCode >= 300 { - return fmt.Errorf("oidc discovery HTTP %d: %s", res.StatusCode, truncate(string(body), 200)) - } - var doc discoveryDoc - if err := json.Unmarshal(body, &doc); err != nil { - return fmt.Errorf("oidc discovery json: %w", err) - } - if c.AuthorizeURL == "" { - c.AuthorizeURL = doc.AuthorizationEndpoint - } - if c.TokenURL == "" { - c.TokenURL = doc.TokenEndpoint - } - if c.UserInfoURL == "" { - c.UserInfoURL = doc.UserinfoEndpoint - } - if c.AuthorizeURL == "" || c.TokenURL == "" || c.UserInfoURL == "" { - return fmt.Errorf("oidc: incomplete discovery endpoints") - } - return nil -} - -// ScopesCSV returns space-separated scopes (default openid profile email). -func (c Config) ScopesCSV() string { - s := strings.TrimSpace(c.Scopes) - if s == "" { - return "openid profile email" - } - return s -} - -// RandomURLString returns a URL-safe random string of n bytes (base64url, no pad). -func RandomURLString(n int) (string, error) { - b := make([]byte, n) - if _, err := rand.Read(b); err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(b), nil -} - -// PKCEChallengeS256 returns code_challenge for a verifier. -func PKCEChallengeS256(verifier string) string { - sum := sha256.Sum256([]byte(verifier)) - return base64.RawURLEncoding.EncodeToString(sum[:]) -} - -// AuthorizeRedirect builds the browser redirect to the IdP authorize endpoint. -// redirectURI must be the absolute URI used for this login (same value later for token exchange). -func (c Config) AuthorizeRedirect(state, codeChallenge, redirectURI string) (string, error) { - if c.AuthorizeURL == "" { - return "", fmt.Errorf("oidc: authorize URL not resolved") - } - redirectURI = strings.TrimSpace(redirectURI) - if redirectURI == "" { - return "", fmt.Errorf("oidc: empty redirect_uri") - } - q := url.Values{} - q.Set("response_type", "code") - q.Set("client_id", c.ClientID) - q.Set("redirect_uri", redirectURI) - q.Set("scope", c.ScopesCSV()) - q.Set("state", state) - if codeChallenge != "" { - q.Set("code_challenge", codeChallenge) - q.Set("code_challenge_method", "S256") - } - sep := "?" - if strings.Contains(c.AuthorizeURL, "?") { - sep = "&" - } - return c.AuthorizeURL + sep + q.Encode(), nil -} - -// TokenResponse is the OAuth token endpoint JSON. -type TokenResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - RefreshToken string `json:"refresh_token"` - IDToken string `json:"id_token"` - Scope string `json:"scope"` - Error string `json:"error"` - ErrorDesc string `json:"error_description"` -} - -// ExchangeCode swaps authorization code for tokens (client_secret_post). -// redirectURI must match the absolute URI sent in AuthorizeRedirect. -func (c Config) ExchangeCode(client *http.Client, code, codeVerifier, redirectURI string) (*TokenResponse, error) { - if c.TokenURL == "" { - return nil, fmt.Errorf("oidc: token URL not resolved") - } - redirectURI = strings.TrimSpace(redirectURI) - if redirectURI == "" { - return nil, fmt.Errorf("oidc: empty redirect_uri") - } - if client == nil { - client = &http.Client{Timeout: 15 * time.Second} - } - form := url.Values{} - form.Set("grant_type", "authorization_code") - form.Set("code", code) - form.Set("redirect_uri", redirectURI) - form.Set("client_id", c.ClientID) - form.Set("client_secret", c.ClientSecret) - if codeVerifier != "" { - form.Set("code_verifier", codeVerifier) - } - req, err := http.NewRequest(http.MethodPost, c.TokenURL, strings.NewReader(form.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.Header.Set("Accept", "application/json") - res, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("oidc token: %w", err) - } - defer res.Body.Close() - body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - if err != nil { - return nil, err - } - var tok TokenResponse - if err := json.Unmarshal(body, &tok); err != nil { - return nil, fmt.Errorf("oidc token json: %w (%s)", err, truncate(string(body), 200)) - } - if tok.Error != "" { - return nil, fmt.Errorf("oidc token: %s (%s)", tok.Error, tok.ErrorDesc) - } - if tok.AccessToken == "" { - return nil, fmt.Errorf("oidc token: empty access_token (HTTP %d)", res.StatusCode) - } - return &tok, nil -} - -// UserInfo is the subset we need from /oauth2/userinfo (CFLMY + standard OIDC). -type UserInfo struct { - Sub string `json:"sub"` - Email string `json:"email"` - PreferredUsername string `json:"preferred_username"` - Name string `json:"name"` - Picture string `json:"picture"` - IsAdmin bool `json:"is_admin"` - AdminRole string `json:"admin_role"` -} - -// FetchUserInfo calls the userinfo endpoint with a bearer access token. -func (c Config) FetchUserInfo(client *http.Client, accessToken string) (*UserInfo, error) { - if c.UserInfoURL == "" { - return nil, fmt.Errorf("oidc: userinfo URL not resolved") - } - if client == nil { - client = &http.Client{Timeout: 15 * time.Second} - } - req, err := http.NewRequest(http.MethodGet, c.UserInfoURL, nil) - if err != nil { - return nil, err - } - req.Header.Set("Authorization", "Bearer "+accessToken) - req.Header.Set("Accept", "application/json") - res, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("oidc userinfo: %w", err) - } - defer res.Body.Close() - body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - if err != nil { - return nil, err - } - if res.StatusCode >= 300 { - return nil, fmt.Errorf("oidc userinfo HTTP %d: %s", res.StatusCode, truncate(string(body), 200)) - } - var info UserInfo - if err := json.Unmarshal(body, &info); err != nil { - return nil, fmt.Errorf("oidc userinfo json: %w", err) - } - if info.Sub == "" { - return nil, fmt.Errorf("oidc userinfo: missing sub") - } - return &info, nil -} - -// LocalUsername picks a stable display username for sessions / RBAC. -func (u *UserInfo) LocalUsername() string { - if u == nil { - return "" - } - if s := strings.TrimSpace(u.PreferredUsername); s != "" { - return s - } - if s := strings.TrimSpace(u.Email); s != "" { - if i := strings.IndexByte(s, '@'); i > 0 { - return s[:i] - } - return s - } - if s := strings.TrimSpace(u.Name); s != "" { - return s - } - sub := strings.TrimSpace(u.Sub) - if len(sub) > 32 { - return sub[:32] - } - return sub -} - -// IsIdPAdmin reports whether CFLMY IdP marks this user as an administrator. -func (u *UserInfo) IsIdPAdmin() bool { - if u == nil { - return false - } - if u.IsAdmin { - return true - } - return strings.TrimSpace(u.AdminRole) != "" -} - -// LocalRole maps IdP admin → site admin; otherwise defaultRole (member). -func (u *UserInfo) LocalRole(defaultRole string) string { - if defaultRole == "" { - defaultRole = "member" - } - if u.IsIdPAdmin() { - return "admin" - } - return defaultRole -} - -func truncate(s string, n int) string { - if len(s) <= n { - return s - } - return s[:n] + "…" -} - -// ParseConfig reads oidc bag from app / auth options (EN + ZH keys). -func ParseConfig(m map[string]any) Config { - if m == nil { - return Config{} - } - if nested, ok := m["oidc"].(map[string]any); ok { - m = nested - } - c := Config{ - Issuer: firstStr(m, "issuer", "发行方", "issuer_url"), - ClientID: firstStr(m, "client_id", "客户端编号", "客户端id", "clientId"), - ClientSecret: firstStr(m, "client_secret", "客户端密钥", "clientSecret"), - RedirectURI: firstStr(m, "redirect_uri", "回调", "回调地址", "redirect"), - RedirectOrigins: firstStr(m, "redirect_origins", "回调来源", "redirect_origin"), - Scopes: firstStr(m, "scopes", "范围", "scope"), - CallbackPath: firstStr(m, "callback_path", "回调路径"), - AuthorizeURL: firstStr(m, "authorize_url", "授权地址"), - TokenURL: firstStr(m, "token_url", "令牌地址"), - UserInfoURL: firstStr(m, "userinfo_url", "用户信息地址"), - } - return c -} - -func firstStr(m map[string]any, keys ...string) string { - for _, k := range keys { - if v, ok := m[k]; ok { - switch t := v.(type) { - case string: - if s := strings.TrimSpace(t); s != "" && !strings.EqualFold(s, "none") { - return s - } - } - } - } - return "" -} diff --git a/plugins/web/internal/oidc/oidc_test.go b/plugins/web/internal/oidc/oidc_test.go deleted file mode 100755 index 54e889a..0000000 --- a/plugins/web/internal/oidc/oidc_test.go +++ /dev/null @@ -1,187 +0,0 @@ -package oidc_test - -import ( - "crypto/tls" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/oidc" -) - -func TestUserInfoLocalRole(t *testing.T) { - u := &oidc.UserInfo{PreferredUsername: "alice", IsAdmin: false} - if u.LocalRole("member") != "member" { - t.Fatal("expected member") - } - u.IsAdmin = true - if u.LocalRole("member") != "admin" { - t.Fatal("expected admin from is_admin") - } - u.IsAdmin = false - u.AdminRole = "super_admin" - if u.LocalRole("member") != "admin" { - t.Fatal("expected admin from admin_role") - } - if u.LocalUsername() != "alice" { - t.Fatalf("username=%s", u.LocalUsername()) - } -} - -func TestPKCEAndParse(t *testing.T) { - v, err := oidc.RandomURLString(32) - if err != nil || v == "" { - t.Fatal(err) - } - ch := oidc.PKCEChallengeS256(v) - if len(ch) < 20 { - t.Fatalf("challenge=%q", ch) - } - c := oidc.ParseConfig(map[string]any{ - "发行方": "https://id.example.com", - "客户端编号": "app_x", - "客户端密钥": "secret", - "回调": "http://localhost:18085/oidc/callback", - }) - if !c.Enabled() { - t.Fatal("expected enabled") - } - if c.Callback() != "/oidc/callback" { - t.Fatalf("callback=%s", c.Callback()) - } - if c.IsPathRedirect() { - t.Fatal("absolute redirect should not be path mode") - } -} - -func TestPathRedirectParseAndCallback(t *testing.T) { - c := oidc.ParseConfig(map[string]any{ - "issuer": "https://id.example.com", - "client_id": "app_x", - "client_secret": "secret", - "redirect_uri": "/oidc/callback", - "redirect_origins": "https://qdqc.com,https://www.qdqc.com", - }) - if !c.Enabled() { - t.Fatal("expected enabled") - } - if !c.IsPathRedirect() { - t.Fatal("expected path mode") - } - if c.Callback() != "/oidc/callback" { - t.Fatalf("callback=%s", c.Callback()) - } - origins := c.AllowedOrigins() - if len(origins) != 2 || origins[0] != "https://qdqc.com" { - t.Fatalf("origins=%v", origins) - } -} - -func TestResolveRedirectURIAbsolute(t *testing.T) { - c := oidc.Config{RedirectURI: "https://qdqc.com/oidc/callback"} - r, _ := http.NewRequest(http.MethodGet, "http://www.qdqc.com/oidc/login", nil) - r.Host = "www.qdqc.com" - got, err := c.ResolveRedirectURI(r) - if err != nil { - t.Fatal(err) - } - if got != "https://qdqc.com/oidc/callback" { - t.Fatalf("got=%s", got) - } -} - -func TestResolveRedirectURIPathFromHost(t *testing.T) { - c := oidc.Config{RedirectURI: "/oidc/callback"} - r, _ := http.NewRequest(http.MethodGet, "http://qdqc.com/oidc/login", nil) - r.Host = "qdqc.com" - got, err := c.ResolveRedirectURI(r) - if err != nil { - t.Fatal(err) - } - if got != "http://qdqc.com/oidc/callback" { - t.Fatalf("got=%s", got) - } -} - -func TestResolveRedirectURIPathTLS(t *testing.T) { - c := oidc.Config{RedirectURI: "/oidc/callback"} - r, _ := http.NewRequest(http.MethodGet, "https://qdqc.com/oidc/login", nil) - r.Host = "qdqc.com" - r.TLS = &tls.ConnectionState{} - got, err := c.ResolveRedirectURI(r) - if err != nil { - t.Fatal(err) - } - if got != "https://qdqc.com/oidc/callback" { - t.Fatalf("got=%s", got) - } -} - -func TestResolveRedirectURIXForwarded(t *testing.T) { - c := oidc.Config{RedirectURI: "/oidc/callback"} - r, _ := http.NewRequest(http.MethodGet, "http://127.0.0.1:18085/oidc/login", nil) - r.Host = "127.0.0.1:18085" - r.Header.Set("X-Forwarded-Proto", "https") - r.Header.Set("X-Forwarded-Host", "www.qdqc.com, other.example") - got, err := c.ResolveRedirectURI(r) - if err != nil { - t.Fatal(err) - } - if got != "https://www.qdqc.com/oidc/callback" { - t.Fatalf("got=%s", got) - } -} - -func TestResolveRedirectURIAllowlistReject(t *testing.T) { - c := oidc.Config{ - RedirectURI: "/oidc/callback", - RedirectOrigins: "https://qdqc.com,https://www.qdqc.com", - } - r, _ := http.NewRequest(http.MethodGet, "https://evil.example/oidc/login", nil) - r.Host = "evil.example" - r.Header.Set("X-Forwarded-Proto", "https") - _, err := c.ResolveRedirectURI(r) - if err == nil || !strings.Contains(err.Error(), "redirect_origins") { - t.Fatalf("expected allowlist error, got %v", err) - } -} - -func TestResolveRedirectURIAllowlistOK(t *testing.T) { - c := oidc.Config{ - RedirectURI: "/oidc/callback", - RedirectOrigins: "https://qdqc.com,https://www.qdqc.com", - } - r, _ := http.NewRequest(http.MethodGet, "https://www.qdqc.com/oidc/login", nil) - r.Host = "www.qdqc.com" - r.Header.Set("X-Forwarded-Proto", "https") - got, err := c.ResolveRedirectURI(r) - if err != nil { - t.Fatal(err) - } - if got != "https://www.qdqc.com/oidc/callback" { - t.Fatalf("got=%s", got) - } -} - -func TestAuthorizeRedirectUsesExplicitURI(t *testing.T) { - c := oidc.Config{ - ClientID: "app_x", - AuthorizeURL: "https://id.example.com/oauth2/authorize", - RedirectURI: "/oidc/callback", - } - loc, err := c.AuthorizeRedirect("st", "ch", "https://www.qdqc.com/oidc/callback") - if err != nil { - t.Fatal(err) - } - u, err := url.Parse(loc) - if err != nil { - t.Fatal(err) - } - if got := u.Query().Get("redirect_uri"); got != "https://www.qdqc.com/oidc/callback" { - t.Fatalf("redirect_uri=%s", got) - } - if u.Query().Get("state") != "st" { - t.Fatal("state") - } -} diff --git a/plugins/web/internal/page/page.go b/plugins/web/internal/page/page.go deleted file mode 100755 index ad7b3fd..0000000 --- a/plugins/web/internal/page/page.go +++ /dev/null @@ -1,160 +0,0 @@ -package page - -import ( - "strconv" - "strings" -) - -// New builds a page bag (ABI web_page_new), matching the Rust plugin shape. -func New(args map[string]any) map[string]any { - title := strOpt(args, "title", "Marqdo Web") - intro := strOpt(args, "intro", "") - out := map[string]any{ - "title": title, - "intro": intro, - } - if s, ok := strAny(args, "shell_css", "壳样式"); ok { - out["shell_css"] = s - } - if s, ok := strAny(args, "layout", "布局"); ok { - out["layout"] = s - } - if s, ok := strAny(args, "asset_version", "资源版本"); ok { - out["asset_version"] = s - } - return out -} - -// Paginate stamps page.paginate with offset/limit/path (Rust web_page_paginate). -func Paginate(page map[string]any, offset, limit int64, path string) map[string]any { - out := clone(page) - if path == "" { - path = "/" - } - out["paginate"] = map[string]any{ - "offset": offset, - "limit": limit, - "path": path, - } - return out -} - -// SetQuery stamps page.query (Rust web_page_query). -func SetQuery(page map[string]any, query any) map[string]any { - out := clone(page) - if query == nil { - query = map[string]any{} - } - out["query"] = query - return out -} - -// SetOrder stamps page.order (Rust web_page_order). -func SetOrder(page map[string]any, order string) map[string]any { - out := clone(page) - out["order"] = order - return out -} - -// SetLinkPrefix stamps page.link_prefix (Rust web_page_link_prefix). -func SetLinkPrefix(page map[string]any, prefix string) map[string]any { - out := clone(page) - out["link_prefix"] = prefix - return out -} - -// AppendCSS appends raw CSS to page.styles_css (Rust web_page_css). -func AppendCSS(page map[string]any, css string) map[string]any { - out := clone(page) - css = strings.TrimSpace(css) - if css == "" { - return out - } - prev, _ := out["styles_css"].(string) - if prev == "" { - out["styles_css"] = css - } else { - out["styles_css"] = prev + "\n" + css - } - return out -} - -// SetDetail stamps page.detail bool (Rust web_page_detail). -func SetDetail(page map[string]any, on bool) map[string]any { - out := clone(page) - out["detail"] = on - return out -} - -// SetChromeHTML sets raw nav_html / footer_html / body_class overrides. -func SetChromeHTML(page map[string]any, navHTML, footerHTML, bodyClass string) map[string]any { - out := clone(page) - if strings.TrimSpace(navHTML) != "" { - out["nav_html"] = navHTML - } - if strings.TrimSpace(footerHTML) != "" { - out["footer_html"] = footerHTML - } - if strings.TrimSpace(bodyClass) != "" { - out["body_class"] = bodyClass - } - return out -} - -func clone(page map[string]any) map[string]any { - out := map[string]any{} - for k, v := range page { - out[k] = v - } - return out -} - -func strOpt(args map[string]any, key, def string) string { - if s, ok := strAny(args, key); ok { - return s - } - return def -} - -func strAny(args map[string]any, keys ...string) (string, bool) { - for _, k := range keys { - v, ok := args[k] - if !ok || v == nil { - continue - } - switch t := v.(type) { - case string: - return t, true - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10), true - } - return strconv.FormatFloat(t, 'f', -1, 64), true - case bool: - return strconv.FormatBool(t), true - } - } - return "", false -} - -// AsBool interprets ABI detail flags (bool / 0|1 / 真|是|true). -func AsBool(v any, def bool) bool { - if v == nil { - return def - } - switch t := v.(type) { - case bool: - return t - case float64: - return t != 0 - case string: - s := strings.TrimSpace(t) - switch s { - case "1", "true", "True", "yes", "on", "真", "是": - return true - case "0", "false", "False", "no", "off", "假", "否", "": - return false - } - } - return def -} diff --git a/plugins/web/internal/page/page_test.go b/plugins/web/internal/page/page_test.go deleted file mode 100755 index 8065bd2..0000000 --- a/plugins/web/internal/page/page_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package page_test - -import ( - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/page" -) - -func TestNewDefaults(t *testing.T) { - p := page.New(map[string]any{}) - if p["title"] != "Marqdo Web" { - t.Fatalf("title=%v", p["title"]) - } - if p["intro"] != "" { - t.Fatalf("intro=%v", p["intro"]) - } -} - -func TestNewZhAliases(t *testing.T) { - p := page.New(map[string]any{ - "title": "T", - "壳样式": "minimal", - "布局": "bare", - "资源版本": "v1", - }) - if p["shell_css"] != "minimal" || p["layout"] != "bare" || p["asset_version"] != "v1" { - t.Fatalf("%v", p) - } -} - -func TestPaginateBag(t *testing.T) { - p := page.New(map[string]any{"title": "List"}) - out := page.Paginate(p, 0, 5, "/") - pg, ok := out["paginate"].(map[string]any) - if !ok { - t.Fatalf("paginate=%v", out["paginate"]) - } - if pg["offset"] != int64(0) || pg["limit"] != int64(5) || pg["path"] != "/" { - t.Fatalf("%v", pg) - } -} diff --git a/plugins/web/internal/password/password.go b/plugins/web/internal/password/password.go deleted file mode 100755 index 50a55fd..0000000 --- a/plugins/web/internal/password/password.go +++ /dev/null @@ -1,123 +0,0 @@ -// Package password ports argon2id hashing from the Rust web plugin. -package password - -import ( - "crypto/rand" - "crypto/subtle" - "encoding/base64" - "fmt" - "strconv" - "strings" - - "golang.org/x/crypto/argon2" -) - -// Defaults match Rust argon2::Argon2::default() (argon2id, m=19456, t=2, p=1). -const ( - timeCost = 2 - memoryKiB = 19456 - parallelism = 1 - keyLen = 32 - saltLen = 16 -) - -// IsHashed reports whether stored looks like an argon2 PHC string. -func IsHashed(stored string) bool { - return strings.HasPrefix(stored, "$argon2") -} - -// Hash returns an argon2id PHC string for plaintext password. -func Hash(password string) (string, error) { - if password == "" { - return "", fmt.Errorf("password must not be empty") - } - salt := make([]byte, saltLen) - if _, err := rand.Read(salt); err != nil { - return "", fmt.Errorf("getrandom: %w", err) - } - sum := argon2.IDKey([]byte(password), salt, timeCost, memoryKiB, uint8(parallelism), keyLen) - b64Salt := base64.RawStdEncoding.EncodeToString(salt) - b64Hash := base64.RawStdEncoding.EncodeToString(sum) - return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", - memoryKiB, timeCost, parallelism, b64Salt, b64Hash), nil -} - -// HashResult is the ABI shape for web_password_hash: {"hash":"…"}. -func HashResult(password string) (map[string]any, error) { - h, err := Hash(password) - if err != nil { - return nil, err - } - return map[string]any{"hash": h}, nil -} - -// Verify checks plaintext against an argon2 PHC hash, or legacy plaintext equality -// (dev / gold tests). -func Verify(password, encoded string) bool { - if password == "" || encoded == "" { - return false - } - if IsHashed(encoded) { - return verifyArgon2(password, encoded) - } - return password == encoded -} - -func verifyArgon2(password, encoded string) bool { - // $argon2id$v=19$m=19456,t=2,p=1$salt$hash - parts := strings.Split(encoded, "$") - // "", "argon2id", "v=19", "m=…,t=…,p=…", salt, hash - if len(parts) != 6 { - return false - } - if parts[1] != "argon2id" && parts[1] != "argon2i" && parts[1] != "argon2d" { - return false - } - var m uint32 - var t, p uint32 - for _, kv := range strings.Split(parts[3], ",") { - k, v, ok := strings.Cut(kv, "=") - if !ok { - return false - } - n, err := strconv.ParseUint(v, 10, 32) - if err != nil { - return false - } - switch k { - case "m": - m = uint32(n) - case "t": - t = uint32(n) - case "p": - p = uint32(n) - } - } - if m == 0 || t == 0 || p == 0 { - return false - } - salt, err := base64.RawStdEncoding.DecodeString(parts[4]) - if err != nil { - salt, err = base64.StdEncoding.DecodeString(parts[4]) - if err != nil { - return false - } - } - want, err := base64.RawStdEncoding.DecodeString(parts[5]) - if err != nil { - want, err = base64.StdEncoding.DecodeString(parts[5]) - if err != nil { - return false - } - } - var got []byte - switch parts[1] { - case "argon2id": - got = argon2.IDKey([]byte(password), salt, t, m, uint8(p), uint32(len(want))) - case "argon2i": - got = argon2.Key([]byte(password), salt, t, m, uint8(p), uint32(len(want))) - default: - return false - } - return subtle.ConstantTimeCompare(got, want) == 1 -} diff --git a/plugins/web/internal/password/password_test.go b/plugins/web/internal/password/password_test.go deleted file mode 100755 index 9af3a28..0000000 --- a/plugins/web/internal/password/password_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package password_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/password" -) - -func TestHashAndVerifyRoundtrip(t *testing.T) { - hash, err := password.Hash("secret") - if err != nil { - t.Fatal(err) - } - if !password.IsHashed(hash) { - t.Fatalf("not PHC: %q", hash) - } - if !strings.HasPrefix(hash, "$argon2id$") { - t.Fatalf("want argon2id prefix, got %q", hash) - } - if !password.Verify("secret", hash) { - t.Fatal("verify secret failed") - } - if password.Verify("wrong", hash) { - t.Fatal("wrong password should fail") - } - out, err := password.HashResult("secret") - if err != nil { - t.Fatal(err) - } - if out["hash"] == nil || out["hash"] == "" { - t.Fatalf("HashResult shape: %v", out) - } -} - -func TestLegacyPlaintext(t *testing.T) { - if !password.Verify("secret", "secret") { - t.Fatal("plaintext equality") - } - if password.Verify("other", "secret") { - t.Fatal("plaintext mismatch") - } - if password.Verify("", "secret") || password.Verify("secret", "") { - t.Fatal("empty should fail") - } -} - -func TestEmptyHashError(t *testing.T) { - if _, err := password.Hash(""); err == nil { - t.Fatal("expected error") - } -} diff --git a/plugins/web/internal/plugin/host.go b/plugins/web/internal/plugin/host.go deleted file mode 100755 index 507b29b..0000000 --- a/plugins/web/internal/plugin/host.go +++ /dev/null @@ -1,81 +0,0 @@ -package plugin - -import "encoding/json" - -// HostFns holds callbacks into the Marqdo host (valid after marqdo_plugin_init). -type HostFns struct { - Query func(name, argsJSON string) (string, error) -} - -var host HostFns - -// SetHost stores host callbacks from ABI init. -func SetHost(h HostFns) { host = h } - -// Shutdown clears plugin global state (HTTP servers, pools, …). -func Shutdown() { - host = HostFns{} -} - -// Query runs an allowlisted host_query. -func Query(name, argsJSON string) (string, error) { - if host.Query == nil { - return "", errString("host_query not available") - } - return host.Query(name, argsJSON) -} - -type errString string - -func (e errString) Error() string { return string(e) } - -// CallLibPath invokes `lib.member` on the site entry module (optional named args). -func CallLibPath(path string, args map[string]any) (any, error) { - payload := map[string]any{"path": path} - if len(args) > 0 { - payload["args"] = args - } - raw, err := json.Marshal(payload) - if err != nil { - return nil, err - } - out, err := Query("call_lib_path", string(raw)) - if err != nil { - return nil, err - } - var v any - if err := json.Unmarshal([]byte(out), &v); err != nil { - return nil, err - } - return v, nil -} - -// RunArtifact loads and runs a Document/Endpoint `.mq.md` (ADR 0007). -// Request fields are passed as Metadata Binding overlays (`arg` / `--bind`). -func RunArtifact(path string, args map[string]any) (any, error) { - return RunArtifactAtRoot(path, args, "") -} - -// RunArtifactAtRoot retains a selected site directory within the host's grant. -func RunArtifactAtRoot(path string, args map[string]any, root string) (any, error) { - payload := map[string]any{"path": path} - if root != "" { - payload["root"] = root - } - if len(args) > 0 { - payload["args"] = args - } - raw, err := json.Marshal(payload) - if err != nil { - return nil, err - } - out, err := Query("run_artifact", string(raw)) - if err != nil { - return nil, err - } - var v any - if err := json.Unmarshal([]byte(out), &v); err != nil { - return nil, err - } - return v, nil -} diff --git a/plugins/web/internal/proxy/proxy.go b/plugins/web/internal/proxy/proxy.go deleted file mode 100755 index 04b8413..0000000 --- a/plugins/web/internal/proxy/proxy.go +++ /dev/null @@ -1,283 +0,0 @@ -// Package proxy ports offline proxy route bags (Rust proxy.rs). -package proxy - -import ( - "fmt" - "strconv" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// Options is one proxy mount (web_app_proxy args). -type Options struct { - Path string - Upstream string - Stream bool - StripPrefix string - Methods []string - HeadersFromEnv string - TimeoutMs uint64 -} - -// RoutesFromTable normalizes `|路径|上游|流式|去前缀|方法|环境头|超时|` into proxy_routes map keys. -func RoutesFromTable(tableV any) map[string]any { - rows, _ := table.AsRows(tableV).([]any) - out := map[string]any{} - for _, row := range rows { - m, ok := row.(map[string]any) - if !ok { - continue - } - path := normalizeTablePath(col(m, "路径", "path", "Path")) - if path == "" || path == "/" { - continue - } - upstream := col(m, "上游", "upstream", "Upstream") - if upstream == "" { - continue - } - stream := true - if s := col(m, "流式", "stream", "Stream"); s != "" { - stream = boolish(s) - } - stripPrefix := col(m, "去前缀", "strip_prefix", "Strip-Prefix") - methodsRaw := col(m, "方法", "methods", "Methods") - methods := parseMethods(methodsRaw) - headersFromEnv := col(m, "环境头", "headers_from_env", "Headers-From-Env") - timeoutMs := uint64(120_000) - if s := col(m, "超时", "timeout_ms", "Timeout"); s != "" { - if n, err := strconv.ParseUint(strings.TrimSpace(s), 10, 64); err == nil { - timeoutMs = n - } - } - key := strings.TrimPrefix(path, "/") - out[key] = routeEntry(upstream, stream, stripPrefix, methods, headersFromEnv, timeoutMs) - } - return out -} - -// Register adds one proxy route to app.proxy_routes (Rust web_app_proxy). -func Register(appBag map[string]any, opts Options) (map[string]any, error) { - if strings.TrimSpace(opts.Upstream) == "" { - return nil, fmt.Errorf("proxy requires `upstream`") - } - path, err := app.NormalizeRoutePath(opts.Path, appBag) - if err != nil { - return nil, err - } - key := strings.TrimPrefix(path, "/") - out := clone(appBag) - routes := map[string]any{} - if r, ok := out["proxy_routes"].(map[string]any); ok { - routes = clone(r) - } - methods := opts.Methods - if len(methods) == 0 { - methods = []string{"POST"} - } - timeout := opts.TimeoutMs - if timeout == 0 { - timeout = 120_000 - } - routes[key] = routeEntry(opts.Upstream, opts.Stream, opts.StripPrefix, methods, opts.HeadersFromEnv, timeout) - out["proxy_routes"] = routes - return out, nil -} - -// OptionsFromArgs parses web_app_proxy ABI args. -func OptionsFromArgs(args map[string]any) (Options, error) { - path, err := argStrReq(args, "path", "路径") - if err != nil { - return Options{}, err - } - upstream, err := argStrReq(args, "upstream", "上游") - if err != nil { - return Options{}, err - } - stream := true - if v, ok := first(args, "stream", "流式"); ok { - stream = boolish(v) - } - stripPrefix, _ := argStr(args, "strip_prefix", "去前缀") - headersFromEnv, _ := argStr(args, "headers_from_env", "环境头") - timeoutMs := uint64(120_000) - if v, ok := first(args, "timeout_ms", "超时"); ok { - if n, ok := asUint64(v); ok { - timeoutMs = n - } - } - return Options{ - Path: path, - Upstream: upstream, - Stream: stream, - StripPrefix: stripPrefix, - Methods: parseMethodsArg(args["methods"], args["方法"]), - HeadersFromEnv: headersFromEnv, - TimeoutMs: timeoutMs, - }, nil -} - -func routeEntry(upstream string, stream bool, stripPrefix string, methods []string, headersFromEnv string, timeoutMs uint64) map[string]any { - methodAny := make([]any, len(methods)) - for i, m := range methods { - methodAny[i] = m - } - return map[string]any{ - "upstream": upstream, - "stream": stream, - "strip_prefix": stripPrefix, - "methods": methodAny, - "headers_from_env": headersFromEnv, - "timeout_ms": float64(timeoutMs), - } -} - -func normalizeTablePath(raw string) string { - s := strings.TrimSpace(raw) - if s == "" { - return "" - } - if !strings.HasPrefix(s, "/") { - return "/" + s - } - return s -} - -func parseMethods(raw string) []string { - if strings.TrimSpace(raw) == "" { - return []string{"POST"} - } - var out []string - for _, part := range strings.Split(raw, ",") { - part = strings.TrimSpace(part) - if part != "" { - out = append(out, strings.ToUpper(part)) - } - } - if len(out) == 0 { - return []string{"POST"} - } - return out -} - -func parseMethodsArg(v any, alt any) []string { - if v == nil { - v = alt - } - if v == nil { - return nil - } - switch t := v.(type) { - case []any: - var out []string - for _, x := range t { - if s, ok := x.(string); ok && strings.TrimSpace(s) != "" { - out = append(out, strings.ToUpper(strings.TrimSpace(s))) - } - } - return out - case string: - return parseMethods(t) - } - return nil -} - -func col(m map[string]any, keys ...string) string { - for _, k := range keys { - if v, ok := m[k]; ok { - return cellText(v) - } - } - return "" -} - -func cellText(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - default: - return fmt.Sprint(t) - } -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - switch strings.TrimSpace(t) { - case "true", "True", "1", "yes", "on", "真": - return true - } - return false - case float64: - return t != 0 - } - return false -} - -func asUint64(v any) (uint64, bool) { - switch t := v.(type) { - case float64: - if t >= 0 { - return uint64(t), true - } - case int64: - if t >= 0 { - return uint64(t), true - } - case int: - if t >= 0 { - return uint64(t), true - } - case string: - n, err := strconv.ParseUint(strings.TrimSpace(t), 10, 64) - return n, err == nil - } - return 0, false -} - -func first(args map[string]any, keys ...string) (any, bool) { - for _, k := range keys { - if v, ok := args[k]; ok && v != nil { - return v, true - } - } - return nil, false -} - -func argStr(args map[string]any, keys ...string) (string, bool) { - v, ok := first(args, keys...) - if !ok { - return "", false - } - s, _ := v.(string) - return s, true -} - -func argStrReq(args map[string]any, keys ...string) (string, error) { - s, ok := argStr(args, keys...) - if !ok || strings.TrimSpace(s) == "" { - return "", fmt.Errorf("missing `%s`", keys[0]) - } - return s, nil -} - -func clone(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} diff --git a/plugins/web/internal/proxy/proxy_test.go b/plugins/web/internal/proxy/proxy_test.go deleted file mode 100755 index 9086d24..0000000 --- a/plugins/web/internal/proxy/proxy_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package proxy_test - -import ( - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/middleware" - "github.com/marqdo/marqdo/plugins/web/internal/proxy" -) - -func TestRoutesFromTable(t *testing.T) { - tbl := map[string]any{ - "path": []any{"/proxy/chat"}, - "upstream": []any{"$OPENAI_BASE_URL"}, - "stream": []any{true}, - "strip_prefix": []any{"/proxy"}, - "methods": []any{"POST"}, - "headers_from_env": []any{"OPENAI_API_KEY=Authorization"}, - "timeout_ms": []any{60000}, - } - routes := proxy.RoutesFromTable(tbl) - chat, ok := routes["proxy/chat"].(map[string]any) - if !ok { - t.Fatalf("routes=%v", routes) - } - if chat["upstream"] != "$OPENAI_BASE_URL" { - t.Fatalf("upstream=%v", chat["upstream"]) - } - if chat["stream"] != true { - t.Fatalf("stream=%v", chat["stream"]) - } - if chat["strip_prefix"] != "/proxy" { - t.Fatalf("strip_prefix=%v", chat["strip_prefix"]) - } - if chat["headers_from_env"] != "OPENAI_API_KEY=Authorization" { - t.Fatalf("headers_from_env=%v", chat["headers_from_env"]) - } - methods, _ := chat["methods"].([]any) - if len(methods) != 1 || methods[0] != "POST" { - t.Fatalf("methods=%v", methods) - } - if chat["timeout_ms"] != float64(60000) { - t.Fatalf("timeout_ms=%v", chat["timeout_ms"]) - } -} - -func TestRegisterProxyRoute(t *testing.T) { - a := app.New(map[string]any{"page": map[string]any{"title": "p"}}) - out, err := proxy.Register(a, proxy.Options{ - Path: "/v1/stream", - Upstream: "https://example.com/v1/chat", - Stream: true, - HeadersFromEnv: "TOKEN=X-Token", - }) - if err != nil { - t.Fatal(err) - } - routes := out["proxy_routes"].(map[string]any) - entry, ok := routes["v1/stream"].(map[string]any) - if !ok { - t.Fatalf("routes=%v", routes) - } - if entry["upstream"] != "https://example.com/v1/chat" { - t.Fatalf("upstream=%v", entry["upstream"]) - } - if entry["headers_from_env"] != "TOKEN=X-Token" { - t.Fatalf("headers=%v", entry["headers_from_env"]) - } -} - -func TestConfigureMergesProxyTable(t *testing.T) { - a := app.New(nil) - proxyTbl := map[string]any{ - "path": []any{"/proxy/chat"}, - "upstream": []any{"$OPENAI_BASE_URL"}, - "stream": []any{true}, - } - out, err := middleware.Configure(a, map[string]any{"proxy": proxyTbl}) - if err != nil { - t.Fatal(err) - } - routes := out["proxy_routes"].(map[string]any) - if routes["proxy/chat"] == nil { - t.Fatalf("proxy_routes=%v", routes) - } -} - -func TestRegisterRejectsEmptyUpstream(t *testing.T) { - _, err := proxy.Register(app.New(nil), proxy.Options{Path: "/x", Upstream: " "}) - if err == nil { - t.Fatal("want error for empty upstream") - } -} diff --git a/plugins/web/internal/ratelimit/ratelimit.go b/plugins/web/internal/ratelimit/ratelimit.go deleted file mode 100755 index 42b8e93..0000000 --- a/plugins/web/internal/ratelimit/ratelimit.go +++ /dev/null @@ -1,95 +0,0 @@ -// Package ratelimit ports login attempt throttling from the Rust web plugin. -package ratelimit - -import ( - "fmt" - "sync" - "time" -) - -const ( - maxFails = 5 - windowSec = 900 // 15 minutes - lockMsg = "Too many failed login attempts. Try again in about 15 minutes." -) - -type window struct { - count uint32 - start int64 -} - -var ( - mu sync.Mutex - attempts map[string]*window -) - -func nowSecs() int64 { - return time.Now().Unix() -} - -func key(ip, username string) string { - return ip + "|" + username -} - -// Reset clears attempt counters (between listens / tests). -func Reset() { - mu.Lock() - defer mu.Unlock() - attempts = map[string]*window{} -} - -func ensureMap() { - if attempts == nil { - attempts = map[string]*window{} - } -} - -// Check returns an error when the client is temporarily locked out. -func Check(ip, username string) error { - k := key(ip, username) - now := nowSecs() - mu.Lock() - defer mu.Unlock() - ensureMap() - w, ok := attempts[k] - if !ok { - return nil - } - if now-w.start < windowSec && w.count >= maxFails { - return fmt.Errorf("%s", lockMsg) - } - if now-w.start >= windowSec { - delete(attempts, k) - } - return nil -} - -// RecordFailure increments the failure counter for IP+username. -func RecordFailure(ip, username string) { - k := key(ip, username) - now := nowSecs() - mu.Lock() - defer mu.Unlock() - ensureMap() - w, ok := attempts[k] - if !ok { - attempts[k] = &window{count: 1, start: now} - return - } - if now-w.start >= windowSec { - w.count = 0 - w.start = now - } - if w.count < ^uint32(0) { - w.count++ - } -} - -// ClearSuccess removes the counter after a successful login. -func ClearSuccess(ip, username string) { - k := key(ip, username) - mu.Lock() - defer mu.Unlock() - ensureMap() - delete(attempts, k) -} diff --git a/plugins/web/internal/ratelimit/ratelimit_test.go b/plugins/web/internal/ratelimit/ratelimit_test.go deleted file mode 100755 index 9faca65..0000000 --- a/plugins/web/internal/ratelimit/ratelimit_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package ratelimit_test - -import ( - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/ratelimit" -) - -func TestLocksAfterMaxFails(t *testing.T) { - ratelimit.Reset() - ip, user := "127.0.0.1", "admin" - for i := 0; i < 5; i++ { - ratelimit.RecordFailure(ip, user) - } - if err := ratelimit.Check(ip, user); err == nil { - t.Fatal("expected lockout") - } - ratelimit.ClearSuccess(ip, user) - if err := ratelimit.Check(ip, user); err != nil { - t.Fatalf("cleared: %v", err) - } -} diff --git a/plugins/web/internal/rbac/rbac.go b/plugins/web/internal/rbac/rbac.go deleted file mode 100755 index 89b0920..0000000 --- a/plugins/web/internal/rbac/rbac.go +++ /dev/null @@ -1,575 +0,0 @@ -// Package rbac implements configurable role ⊥ permission for ext/web. -package rbac - -import ( - "database/sql" - "fmt" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/db" -) - -// Perm is one catalog entry. -type Perm struct { - Code string - Resource string - Action string - Description string -} - -// DefaultCatalog is seeded when EnsureSchema runs. -func DefaultCatalog() []Perm { - return []Perm{ - {"comments:create", "comments", "create", "Create a comment"}, - {"comments:delete", "comments", "delete", "Delete any comment"}, - {"comments:delete_own", "comments", "delete_own", "Delete own comment"}, - {"desk:access", "desk", "access", "Access writing desk / admin chrome"}, - {"roles:manage", "roles", "manage", "Create roles and assign permissions"}, - {"posts:edit", "posts", "edit", "Create or edit posts"}, - {"users:manage", "users", "manage", "Manage user accounts"}, - } -} - -// AllCodes returns every default permission code. -func AllCodes() []string { - cat := DefaultCatalog() - out := make([]string, len(cat)) - for i, p := range cat { - out[i] = p.Code - } - return out -} - -// ExpandRole maps legacy/system role names to permission codes when DB grants are empty. -func ExpandRole(role string) []string { - switch strings.ToLower(strings.TrimSpace(role)) { - case "superadmin", "admin": - return AllCodes() - case "member", "user": - return []string{"comments:create", "comments:delete_own"} - case "editor", "author": - return []string{"comments:create", "comments:delete_own", "posts:edit", "desk:access"} - default: - return nil - } -} - -// ParseCSV splits a CSV of permission or role tokens. -func ParseCSV(s string) []string { - var out []string - for _, part := range strings.Split(s, ",") { - part = strings.ToLower(strings.TrimSpace(part)) - if part != "" { - out = append(out, part) - } - } - return out -} - -// HasAny reports whether held contains any of needed (case-insensitive). -// Empty needed → false. Held containing "*" → true. -func HasAny(held, needed []string) bool { - if len(needed) == 0 { - return false - } - set := map[string]struct{}{} - for _, h := range held { - h = strings.ToLower(strings.TrimSpace(h)) - if h == "*" { - return true - } - if h != "" { - set[h] = struct{}{} - } - } - for _, n := range needed { - n = strings.ToLower(strings.TrimSpace(n)) - if _, ok := set[n]; ok { - return true - } - } - return false -} - -// MergeUnique concatenates permission lists. -func MergeUnique(lists ...[]string) []string { - seen := map[string]struct{}{} - var out []string - for _, list := range lists { - for _, p := range list { - p = strings.ToLower(strings.TrimSpace(p)) - if p == "" { - continue - } - if _, ok := seen[p]; ok { - continue - } - seen[p] = struct{}{} - out = append(out, p) - } - } - return out -} - -const schemaSQLSqlite = ` -CREATE TABLE IF NOT EXISTS web_permissions ( - code TEXT PRIMARY KEY, - resource TEXT NOT NULL, - action TEXT NOT NULL, - description TEXT -); -CREATE TABLE IF NOT EXISTS web_roles ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL UNIQUE, - is_system INTEGER NOT NULL DEFAULT 0, - tenant_id TEXT -); -CREATE TABLE IF NOT EXISTS web_role_permissions ( - role_id INTEGER NOT NULL, - permission_code TEXT NOT NULL, - PRIMARY KEY (role_id, permission_code), - FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE, - FOREIGN KEY (permission_code) REFERENCES web_permissions(code) ON DELETE CASCADE -); -CREATE TABLE IF NOT EXISTS web_users ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT NOT NULL UNIQUE, - password_hash TEXT NOT NULL, - created_at TEXT -); -CREATE TABLE IF NOT EXISTS web_user_roles ( - user_id INTEGER NOT NULL, - role_id INTEGER NOT NULL, - tenant_id TEXT NOT NULL DEFAULT '', - PRIMARY KEY (user_id, role_id, tenant_id), - FOREIGN KEY (user_id) REFERENCES web_users(id) ON DELETE CASCADE, - FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE -); -` - -var schemaSQLPostgres = []string{ - `CREATE TABLE IF NOT EXISTS web_permissions ( - code TEXT PRIMARY KEY, - resource TEXT NOT NULL, - action TEXT NOT NULL, - description TEXT -)`, - `CREATE TABLE IF NOT EXISTS web_roles ( - id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - is_system INTEGER NOT NULL DEFAULT 0, - tenant_id TEXT -)`, - `CREATE TABLE IF NOT EXISTS web_role_permissions ( - role_id INTEGER NOT NULL, - permission_code TEXT NOT NULL, - PRIMARY KEY (role_id, permission_code), - FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE, - FOREIGN KEY (permission_code) REFERENCES web_permissions(code) ON DELETE CASCADE -)`, - `CREATE TABLE IF NOT EXISTS web_users ( - id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, - username TEXT NOT NULL UNIQUE, - password_hash TEXT NOT NULL, - created_at TEXT -)`, - `CREATE TABLE IF NOT EXISTS web_user_roles ( - user_id INTEGER NOT NULL, - role_id INTEGER NOT NULL, - tenant_id TEXT NOT NULL DEFAULT '', - PRIMARY KEY (user_id, role_id, tenant_id), - FOREIGN KEY (user_id) REFERENCES web_users(id) ON DELETE CASCADE, - FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE -)`, -} - -func insertIgnoreSQL(dbURL, table, cols, placeholders, conflict string) string { - if db.IsPostgres(dbURL) { - return fmt.Sprintf(`INSERT INTO %s(%s) VALUES(%s) ON CONFLICT %s DO NOTHING`, table, cols, placeholders, conflict) - } - return fmt.Sprintf(`INSERT OR IGNORE INTO %s(%s) VALUES(%s)`, table, cols, placeholders) -} - -// EnsureSchema creates RBAC tables and seeds default catalog + system roles. -func EnsureSchema(dbURL string) error { - if strings.TrimSpace(dbURL) == "" { - return fmt.Errorf("rbac: empty db url") - } - sqlDB, err := openDB(dbURL) - if err != nil { - return err - } - if db.IsPostgres(dbURL) { - for _, stmt := range schemaSQLPostgres { - if _, err := sqlDB.Exec(stmt); err != nil { - return err - } - } - } else if _, err := sqlDB.Exec(schemaSQLSqlite); err != nil { - return err - } - permSQL := insertIgnoreSQL(dbURL, "web_permissions", "code, resource, action, description", "?,?,?,?", "(code)") - for _, p := range DefaultCatalog() { - _, _ = sqlDB.Exec(permSQL, p.Code, p.Resource, p.Action, p.Description) - } - if err := ensureSystemRole(sqlDB, dbURL, "superadmin", true, AllCodes()); err != nil { - return err - } - if err := ensureSystemRole(sqlDB, dbURL, "member", true, []string{"comments:create", "comments:delete_own"}); err != nil { - return err - } - return nil -} - -func ensureSystemRole(sqlDB db.SQLDB, dbURL, name string, isSystem bool, perms []string) error { - var id int64 - err := sqlDB.QueryRow(`SELECT id FROM web_roles WHERE name = ?`, name).Scan(&id) - if err == sql.ErrNoRows { - sys := 0 - if isSystem { - sys = 1 - } - if db.IsPostgres(dbURL) { - err = sqlDB.QueryRow(`INSERT INTO web_roles(name, is_system) VALUES(?,?) RETURNING id`, name, sys).Scan(&id) - if err != nil { - return err - } - } else { - res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,?)`, name, sys) - if err != nil { - return err - } - id, err = res.LastInsertId() - if err != nil { - return err - } - } - } else if err != nil { - return err - } - rpSQL := insertIgnoreSQL(dbURL, "web_role_permissions", "role_id, permission_code", "?,?", "(role_id, permission_code)") - for _, code := range perms { - _, _ = sqlDB.Exec(rpSQL, id, code) - } - return nil -} - -// PermissionsForUser returns permission codes granted via user_roles for username. -func PermissionsForUser(dbURL, username string) ([]string, error) { - sqlDB, err := openDB(dbURL) - if err != nil { - return nil, err - } - rows, err := sqlDB.Query(` -SELECT DISTINCT rp.permission_code -FROM web_users u -JOIN web_user_roles ur ON ur.user_id = u.id -JOIN web_role_permissions rp ON rp.role_id = ur.role_id -WHERE u.username = ?`, username) - if err != nil { - return nil, err - } - defer rows.Close() - var out []string - for rows.Next() { - var code string - if err := rows.Scan(&code); err != nil { - return nil, err - } - out = append(out, strings.ToLower(code)) - } - return out, rows.Err() -} - -// AssignRole binds username to role name (creates user row link only; user must exist in web_users). -func AssignRole(dbURL, username, roleName string) error { - sqlDB, err := openDB(dbURL) - if err != nil { - return err - } - var uid, rid int64 - if err := sqlDB.QueryRow(`SELECT id FROM web_users WHERE username = ?`, username).Scan(&uid); err != nil { - return fmt.Errorf("rbac assign: user %q: %w", username, err) - } - if err := sqlDB.QueryRow(`SELECT id FROM web_roles WHERE name = ?`, roleName).Scan(&rid); err != nil { - return fmt.Errorf("rbac assign: role %q: %w", roleName, err) - } - _, err = sqlDB.Exec( - insertIgnoreSQL(dbURL, "web_user_roles", "user_id, role_id, tenant_id", "?,?,?", "(user_id, role_id, tenant_id)"), - uid, rid, "", - ) - return err -} - -// CreateRole inserts a non-system role; returns role id. -func CreateRole(dbURL, name string) (int64, error) { - if err := EnsureSchema(dbURL); err != nil { - return 0, err - } - sqlDB, err := openDB(dbURL) - if err != nil { - return 0, err - } - if db.IsPostgres(dbURL) { - var id int64 - err = sqlDB.QueryRow(`INSERT INTO web_roles(name, is_system) VALUES(?,0) RETURNING id`, name).Scan(&id) - return id, err - } - res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,0)`, name) - if err != nil { - return 0, err - } - return res.LastInsertId() -} - -// SetRolePermissions replaces role's permissions. grantable restricts what can be set (anti-escalation); -// empty grantable means allow all catalog codes. -func SetRolePermissions(dbURL string, roleID int64, codes, grantable []string) error { - sqlDB, err := openDB(dbURL) - if err != nil { - return err - } - var isSystem int - if err := sqlDB.QueryRow(`SELECT is_system FROM web_roles WHERE id = ?`, roleID).Scan(&isSystem); err != nil { - return err - } - if isSystem == 1 { - return fmt.Errorf("rbac: cannot rewrite system role permissions via set") - } - allow := map[string]struct{}{} - if len(grantable) == 0 { - for _, c := range AllCodes() { - allow[c] = struct{}{} - } - } else { - for _, c := range grantable { - allow[strings.ToLower(c)] = struct{}{} - } - } - tx, err := sqlDB.Begin() - if err != nil { - return err - } - defer func() { _ = tx.Rollback() }() - if _, err := tx.Exec(`DELETE FROM web_role_permissions WHERE role_id = ?`, roleID); err != nil { - return err - } - for _, code := range codes { - code = strings.ToLower(strings.TrimSpace(code)) - if code == "" { - continue - } - if _, ok := allow[code]; !ok { - return fmt.Errorf("rbac: cannot grant permission %q (not held by actor)", code) - } - if _, err := tx.Exec( - `INSERT INTO web_role_permissions(role_id, permission_code) VALUES(?,?)`, - roleID, code, - ); err != nil { - return err - } - } - return tx.Commit() -} - -// CreateUser inserts a web_users row with hashed password; returns user id. -func CreateUser(dbURL, username, passwordHash string) (int64, error) { - username = strings.TrimSpace(username) - if username == "" || passwordHash == "" { - return 0, fmt.Errorf("rbac: username and password_hash required") - } - sqlDB, err := openDB(dbURL) - if err != nil { - return 0, err - } - now := "datetime('now')" - if db.IsPostgres(dbURL) { - var id int64 - err = sqlDB.QueryRow( - `INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS')) RETURNING id`, - username, passwordHash, - ).Scan(&id) - return id, err - } - res, err := sqlDB.Exec( - `INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,`+now+`)`, - username, passwordHash, - ) - if err != nil { - return 0, err - } - return res.LastInsertId() -} - -// UserExists reports whether username is in web_users. -func UserExists(dbURL, username string) (bool, error) { - sqlDB, err := openDB(dbURL) - if err != nil { - return false, err - } - var id int64 - err = sqlDB.QueryRow(`SELECT id FROM web_users WHERE username = ?`, username).Scan(&id) - if err == sql.ErrNoRows { - return false, nil - } - if err != nil { - return false, err - } - return true, nil -} - -// Authenticate checks username/password against web_users; returns primary role name. -func Authenticate(dbURL, username, pass string, verify func(password, encoded string) bool) (role string, ok bool, err error) { - sqlDB, err := openDB(dbURL) - if err != nil { - return "", false, err - } - var hash string - var uid int64 - err = sqlDB.QueryRow(`SELECT id, password_hash FROM web_users WHERE username = ?`, username).Scan(&uid, &hash) - if err == sql.ErrNoRows { - return "", false, nil - } - if err != nil { - return "", false, err - } - if verify == nil || !verify(pass, hash) { - return "", false, nil - } - var roleName string - err = sqlDB.QueryRow(` -SELECT r.name FROM web_user_roles ur -JOIN web_roles r ON r.id = ur.role_id -WHERE ur.user_id = ? -ORDER BY r.is_system DESC, r.name -LIMIT 1`, uid).Scan(&roleName) - if err == sql.ErrNoRows { - return "member", true, nil - } - if err != nil { - return "", false, err - } - return strings.ToLower(roleName), true, nil -} - -// RegisterUser creates web_users + assigns defaultRole (default member). -func RegisterUser(dbURL, username, passwordHash, defaultRole string) error { - if defaultRole == "" { - defaultRole = "member" - } - exists, err := UserExists(dbURL, username) - if err != nil { - return err - } - if exists { - return fmt.Errorf("rbac: username already taken") - } - if _, err := CreateUser(dbURL, username, passwordHash); err != nil { - return err - } - return AssignRole(dbURL, username, defaultRole) -} - -// EnsureUserWithRole creates user if missing (hash may be empty → skip create) and assigns role. -func EnsureUserWithRole(dbURL, username, passwordHash, roleName string) error { - exists, err := UserExists(dbURL, username) - if err != nil { - return err - } - if !exists { - if passwordHash == "" { - return fmt.Errorf("rbac: cannot create user %q without hash", username) - } - if _, err := CreateUser(dbURL, username, passwordHash); err != nil { - return err - } - } - return AssignRole(dbURL, username, roleName) -} - -// ListRoles returns [{id,name,is_system}, …]. -func ListRoles(dbURL string) ([]map[string]any, error) { - sqlDB, err := openDB(dbURL) - if err != nil { - return nil, err - } - rows, err := sqlDB.Query(`SELECT id, name, is_system FROM web_roles ORDER BY name`) - if err != nil { - return nil, err - } - defer rows.Close() - var out []map[string]any - for rows.Next() { - var id int64 - var name string - var sys int - if err := rows.Scan(&id, &name, &sys); err != nil { - return nil, err - } - out = append(out, map[string]any{"id": id, "name": name, "is_system": sys == 1}) - } - return out, rows.Err() -} - -// ListPermissions returns catalog rows. -func ListPermissions(dbURL string) ([]map[string]any, error) { - sqlDB, err := openDB(dbURL) - if err != nil { - return nil, err - } - rows, err := sqlDB.Query(`SELECT code, resource, action, description FROM web_permissions ORDER BY code`) - if err != nil { - return nil, err - } - defer rows.Close() - var out []map[string]any - for rows.Next() { - var code, resource, action, desc string - if err := rows.Scan(&code, &resource, &action, &desc); err != nil { - return nil, err - } - out = append(out, map[string]any{ - "code": code, "resource": resource, "action": action, "description": desc, - }) - } - return out, rows.Err() -} - -// RolePermissionCodes returns permission codes for a role id. -func RolePermissionCodes(dbURL string, roleID int64) ([]string, error) { - sqlDB, err := openDB(dbURL) - if err != nil { - return nil, err - } - rows, err := sqlDB.Query(`SELECT permission_code FROM web_role_permissions WHERE role_id = ? ORDER BY permission_code`, roleID) - if err != nil { - return nil, err - } - defer rows.Close() - var out []string - for rows.Next() { - var code string - if err := rows.Scan(&code); err != nil { - return nil, err - } - out = append(out, code) - } - return out, rows.Err() -} - -// SetRolePermissionsByName looks up role by name then SetRolePermissions. -func SetRolePermissionsByName(dbURL, roleName string, codes, grantable []string) error { - sqlDB, err := openDB(dbURL) - if err != nil { - return err - } - var id int64 - if err := sqlDB.QueryRow(`SELECT id FROM web_roles WHERE name = ?`, roleName).Scan(&id); err != nil { - return fmt.Errorf("rbac role %q: %w", roleName, err) - } - return SetRolePermissions(dbURL, id, codes, grantable) -} - -func openDB(dbURL string) (db.SQLDB, error) { - return db.OpenSQLDB(dbURL) -} diff --git a/plugins/web/internal/rbac/rbac_test.go b/plugins/web/internal/rbac/rbac_test.go deleted file mode 100755 index 37900ad..0000000 --- a/plugins/web/internal/rbac/rbac_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package rbac_test - -import ( - "path/filepath" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/rbac" -) - -func TestHasAnyAndExpandRole(t *testing.T) { - if !rbac.HasAny([]string{"desk:access", "comments:create"}, []string{"desk:access"}) { - t.Fatal("expected desk:access held") - } - if rbac.HasAny([]string{"comments:create"}, []string{"desk:access"}) { - t.Fatal("member should not have desk") - } - if !rbac.HasAny([]string{"*"}, []string{"roles:manage"}) { - t.Fatal("star should allow all") - } - admin := rbac.ExpandRole("admin") - if !rbac.HasAny(admin, []string{"roles:manage", "desk:access"}) { - t.Fatalf("admin expand incomplete: %v", admin) - } - member := rbac.ExpandRole("member") - if rbac.HasAny(member, []string{"desk:access"}) { - t.Fatal("member must not get desk:access") - } -} - -func TestEnsureSchemaAndAssign(t *testing.T) { - dir := t.TempDir() - url := "sqlite:" + filepath.Join(dir, "rbac.db") - if err := rbac.EnsureSchema(url); err != nil { - t.Fatal(err) - } - sqlDB, err := db.OpenSQL(url) - if err != nil { - t.Fatal(err) - } - _, err = sqlDB.Exec(`INSERT INTO web_users(username, password_hash, created_at) VALUES('alice','x','now')`) - if err != nil { - t.Fatal(err) - } - if err := rbac.AssignRole(url, "alice", "member"); err != nil { - t.Fatal(err) - } - perms, err := rbac.PermissionsForUser(url, "alice") - if err != nil { - t.Fatal(err) - } - if !rbac.HasAny(perms, []string{"comments:create"}) { - t.Fatalf("alice perms=%v", perms) - } - if rbac.HasAny(perms, []string{"roles:manage"}) { - t.Fatal("member should not manage roles") - } -} diff --git a/plugins/web/internal/render/artifact_data_test.go b/plugins/web/internal/render/artifact_data_test.go deleted file mode 100755 index 62d71b1..0000000 --- a/plugins/web/internal/render/artifact_data_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package render - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/db" -) - -func TestResolveMainDataSource(t *testing.T) { - dir := t.TempDir() - url := "sqlite:" + filepath.Join(dir, "t.db") - fields := []any{ - map[string]any{"字段": "title", "类型": "text", "可空": false}, - map[string]any{"字段": "slug", "类型": "text", "可空": false}, - map[string]any{"字段": "summary", "类型": "text", "可空": true}, - map[string]any{"字段": "content", "类型": "text", "可空": true}, - } - if _, err := db.Init(url, "posts", fields); err != nil { - t.Fatal(err) - } - rows := []any{ - map[string]any{ - "title": "Hello", "slug": "hello", - "summary": "sum", "content": "# Body", - }, - } - if _, err := db.Insert(url, "posts", rows); err != nil { - t.Fatal(err) - } - page := map[string]any{ - "intro": "<p>hi</p>", - "data_source": "posts", - "order": "-id", - "link_prefix": "/post/", - } - intro, items, _ := resolveMain(page, url) - if intro != "<p>hi</p>" { - t.Fatalf("intro=%q", intro) - } - if len(items) != 1 { - t.Fatalf("items=%d", len(items)) - } - if items[0]["title"] != "Hello" || items[0]["href"] != "hello" { - t.Fatalf("item=%v", items[0]) - } - html := RenderPage(page, url, "") - if !strings.Contains(html, `class="card"`) || !strings.Contains(html, "Hello") { - t.Fatalf("html missing card: %s", html[:min(400, len(html))]) - } - _ = os.RemoveAll(dir) -} - -func TestResolveMainDataWhereDetail(t *testing.T) { - dir := t.TempDir() - url := "sqlite:" + filepath.Join(dir, "t.db") - fields := []any{ - map[string]any{"字段": "title", "类型": "text", "可空": false}, - map[string]any{"字段": "slug", "类型": "text", "可空": false}, - map[string]any{"字段": "content", "类型": "text", "可空": true}, - } - if _, err := db.Init(url, "posts", fields); err != nil { - t.Fatal(err) - } - rows := []any{ - map[string]any{"title": "A", "slug": "a", "content": "alpha"}, - map[string]any{"title": "B", "slug": "b", "content": "beta"}, - } - if _, err := db.Insert(url, "posts", rows); err != nil { - t.Fatal(err) - } - page := map[string]any{ - "data_source": "posts", - "query": map[string]any{"slug": "{slug}"}, - "params": map[string]any{"slug": "b"}, - "detail": true, - } - _, items, _ := resolveMain(page, url) - if len(items) != 1 || items[0]["title"] != "B" { - t.Fatalf("items=%v", items) - } - html := RenderPage(page, url, "") - if !strings.Contains(html, "article-title") || !strings.Contains(html, "B") { - t.Fatalf("detail html: %s", html[:min(500, len(html))]) - } -} diff --git a/plugins/web/internal/render/auth_inject.go b/plugins/web/internal/render/auth_inject.go deleted file mode 100755 index e954fe9..0000000 --- a/plugins/web/internal/render/auth_inject.go +++ /dev/null @@ -1,225 +0,0 @@ -package render - -import ( - "fmt" - "regexp" - "strings" -) - -var ( - rePostForm = regexp.MustCompile(`(?is)<form\b([^>]*\bmethod\s*=\s*["']post["'][^>]*)>([\s\S]*?)</form>`) - reAction = regexp.MustCompile(`(?i)\baction\s*=\s*["']([^"']*)["']`) - reCSRFIn = regexp.MustCompile(`(?i)\bname\s*=\s*["']_csrf["']`) - reNextIn = regexp.MustCompile(`(?i)\bname\s*=\s*["']next["']`) -) - -// AuthFormSpec describes a progressive-enhancement login/register form. -type AuthFormSpec struct { - Action string - Submit string - FormID string - ErrID string - Target string - NextDefault string - Kind string // login | register -} - -// AuthFormFromPage reads page["auth_form"]. -func AuthFormFromPage(page map[string]any) *AuthFormSpec { - if page == nil { - return nil - } - raw, ok := page["auth_form"].(map[string]any) - if !ok || raw == nil { - return nil - } - spec := &AuthFormSpec{ - Action: strings.TrimSpace(text(raw["action"])), - Submit: strings.TrimSpace(text(raw["submit"])), - FormID: strings.TrimSpace(text(raw["form_id"])), - ErrID: strings.TrimSpace(text(raw["err_id"])), - Target: strings.TrimSpace(text(raw["target"])), - NextDefault: strings.TrimSpace(text(raw["next"])), - Kind: strings.TrimSpace(strings.ToLower(text(raw["kind"]))), - } - if spec.Action == "" { - return nil - } - if spec.Submit == "" { - if spec.Kind == "register" { - spec.Submit = "注册" - } else { - spec.Submit = "登录" - } - } - if spec.FormID == "" { - if spec.Kind == "register" { - spec.FormID = "site-register-form" - } else { - spec.FormID = "site-login-form" - } - } - if spec.ErrID == "" { - spec.ErrID = "site-auth-err" - } - if spec.Kind == "" { - if strings.Contains(spec.Action, "register") { - spec.Kind = "register" - } else { - spec.Kind = "login" - } - } - return spec -} - -// RenderAuthFormHTML builds a complete auth form (CSRF/next filled at inject time too). -func RenderAuthFormHTML(spec *AuthFormSpec, csrf, next, flash string) string { - if spec == nil { - return "" - } - next = strings.TrimSpace(next) - if next == "" { - next = strings.TrimSpace(spec.NextDefault) - } - var b strings.Builder - fmt.Fprintf(&b, `<form id="%s" class="auth-form mq-auth-form" method="post" action="%s">`, esc(spec.FormID), esc(spec.Action)) - if csrf != "" { - fmt.Fprintf(&b, `<input type="hidden" name="_csrf" value="%s"/>`, esc(csrf)) - } - if next != "" && spec.Kind != "register" { - fmt.Fprintf(&b, `<input type="hidden" name="next" value="%s"/>`, esc(next)) - } - b.WriteString(`<label>用户名<input name="username" autocomplete="username" required autofocus/></label>`) - b.WriteString(`<label>密码<input name="password" type="password" autocomplete="`) - if spec.Kind == "register" { - b.WriteString(`new-password`) - } else { - b.WriteString(`current-password`) - } - b.WriteString(`" required`) - if spec.Kind == "register" { - b.WriteString(` minlength="4"`) - } - b.WriteString(`/></label>`) - fmt.Fprintf(&b, `<button type="submit">%s</button>`, esc(spec.Submit)) - b.WriteString(`</form>`) - flashAttr := ` hidden` - flashText := "" - if strings.TrimSpace(flash) != "" { - flashAttr = "" - flashText = strings.TrimSpace(flash) - } - fmt.Fprintf(&b, `<p id="%s" class="auth-err"%s>%s</p>`, esc(spec.ErrID), flashAttr, esc(flashText)) - return b.String() -} - -// ApplyAuthFormIntoIntro injects generated form into intro HTML target, or appends it. -func ApplyAuthFormIntoIntro(intro string, spec *AuthFormSpec, csrf, next, flash string) string { - if spec == nil { - return intro - } - formHTML := RenderAuthFormHTML(spec, csrf, next, flash) - target := strings.TrimSpace(spec.Target) - if target != "" { - if injected, ok := injectHTMLIntoID(intro, target, formHTML); ok { - return injected - } - } - if intro == "" { - return formHTML - } - return intro + formHTML -} - -// IsAuthAction reports whether a form action path is a login/register endpoint. -func IsAuthAction(action string) bool { - a := strings.TrimSpace(action) - if a == "" { - return false - } - // Absolute same-origin paths only. - if strings.HasPrefix(a, "http://") || strings.HasPrefix(a, "https://") || strings.HasPrefix(a, "//") { - return false - } - path := a - if i := strings.IndexByte(path, '?'); i >= 0 { - path = path[:i] - } - path = strings.TrimRight(path, "/") - if path == "" { - path = "/" - } - base := path - if i := strings.LastIndexByte(path, '/'); i >= 0 { - base = path[i+1:] - } - return base == "login" || base == "register" || - strings.HasSuffix(path, "/login") || strings.HasSuffix(path, "/register") -} - -// InjectAuthFields ensures POST auth forms carry _csrf / next, and surfaces flash errors. -func InjectAuthFields(html, csrf, next, flash string) string { - csrf = strings.TrimSpace(csrf) - next = strings.TrimSpace(next) - flash = strings.TrimSpace(flash) - if csrf == "" && next == "" && flash == "" { - return html - } - out := rePostForm.ReplaceAllStringFunc(html, func(full string) string { - m := rePostForm.FindStringSubmatch(full) - if len(m) < 3 { - return full - } - attrs, body := m[1], m[2] - am := reAction.FindStringSubmatch(attrs) - action := "" - if len(am) > 1 { - action = am[1] - } - if !IsAuthAction(action) { - return full - } - var inject strings.Builder - if csrf != "" && !reCSRFIn.MatchString(body) { - fmt.Fprintf(&inject, `<input type="hidden" name="_csrf" value="%s"/>`, esc(csrf)) - } - if next != "" && !reNextIn.MatchString(body) && !strings.Contains(strings.ToLower(action), "register") { - fmt.Fprintf(&inject, `<input type="hidden" name="next" value="%s"/>`, esc(next)) - } - if inject.Len() == 0 { - return full - } - return `<form` + attrs + `>` + inject.String() + body + `</form>` - }) - if flash != "" { - out = surfaceAuthFlash(out, flash) - } - return out -} - -var reErrSlot = regexp.MustCompile(`(?is)(<(?:p|div)\b[^>]*\bid\s*=\s*["'](?:site-auth-err|desk-login-err|auth-err)["'][^>]*)(>)([^<]*)(</(?:p|div)>)`) - -func surfaceAuthFlash(html, flash string) string { - replaced := false - out := reErrSlot.ReplaceAllStringFunc(html, func(full string) string { - m := reErrSlot.FindStringSubmatch(full) - if len(m) < 5 { - return full - } - replaced = true - open := m[1] - open = regexp.MustCompile(`(?i)\s*\bhidden\b`).ReplaceAllString(open, "") - return open + m[2] + esc(flash) + m[4] - }) - if replaced { - return out - } - flashHTML := `<p class="flash err auth-err">` + esc(flash) + `</p>` - if i := strings.Index(out, `<main`); i >= 0 { - if j := strings.Index(out[i:], `>`); j >= 0 { - at := i + j + 1 - return out[:at] + flashHTML + out[at:] - } - } - return flashHTML + out -} diff --git a/plugins/web/internal/render/auth_inject_test.go b/plugins/web/internal/render/auth_inject_test.go deleted file mode 100755 index b6c79d5..0000000 --- a/plugins/web/internal/render/auth_inject_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package render - -import ( - "strings" - "testing" -) - -func TestInjectAuthFieldsAddsCSRFAndNext(t *testing.T) { - html := `<!DOCTYPE html><html><body><main> -<form id="site-login-form" method="post" action="/login"> -<label>用户名<input name="username"/></label> -<button type="submit">登录</button> -</form> -<p id="site-auth-err" class="auth-err" hidden></p> -</main></body></html>` - out := InjectAuthFields(html, "tok123", "/desk", "用户名或密码错误。") - for _, want := range []string{`name="_csrf"`, `value="tok123"`, `name="next"`, `value="/desk"`, `用户名或密码错误`} { - if !strings.Contains(out, want) { - t.Fatalf("missing %q in %s", want, out) - } - } - if strings.Contains(out, `id="site-auth-err" class="auth-err" hidden`) { - t.Fatalf("err still hidden: %s", out) - } -} - -func TestInjectSkipsNonAuthForms(t *testing.T) { - html := `<form method="post" action="/_form/comment"><input name="body"/></form>` - out := InjectAuthFields(html, "tok", "/x", "") - if strings.Contains(out, `_csrf`) { - t.Fatalf("should not inject into comment form: %s", out) - } -} - -func TestRenderAuthFormHTML(t *testing.T) { - spec := &AuthFormSpec{Action: "/desk/login", Submit: "进入后台", FormID: "desk-login-form", ErrID: "desk-login-err", NextDefault: "/desk", Kind: "login"} - html := RenderAuthFormHTML(spec, "c", "", "") - for _, want := range []string{`action="/desk/login"`, `name="_csrf"`, `value="/desk"`, `进入后台`} { - if !strings.Contains(html, want) { - t.Fatalf("missing %q in %s", want, html) - } - } -} diff --git a/plugins/web/internal/render/chrome_brand.go b/plugins/web/internal/render/chrome_brand.go deleted file mode 100755 index 00195ec..0000000 --- a/plugins/web/internal/render/chrome_brand.go +++ /dev/null @@ -1,247 +0,0 @@ -package render - -import ( - "regexp" - "strings" - "unicode" - "unicode/utf8" -) - -// formatMetaDate shortens ISO timestamps to YYYY-MM-DD for card/article meta. -func formatMetaDate(s string) string { - s = strings.TrimSpace(s) - if len(s) >= 10 && s[4] == '-' && s[7] == '-' { - if len(s) == 10 || s[10] == 'T' || s[10] == ' ' { - return s[:10] - } - } - return s -} - -func navBrandSpec(page map[string]any) map[string]any { - if page == nil { - return nil - } - if b, ok := page["nav_brand"].(map[string]any); ok { - return b - } - return nil -} - -func themeKeyOf(page map[string]any) string { - if b := navBrandSpec(page); b != nil { - if k := text(b["theme_key"]); k != "" { - return k - } - if k := text(b["主题键"]); k != "" { - return k - } - } - return "mq-theme" -} - -func renderNavBrandHTML(page map[string]any) string { - b := navBrandSpec(page) - if b == nil { - return "" - } - title := text(b["title"]) - if title == "" { - title = text(b["标题"]) - } - if title == "" { - title = text(page["title"]) - } - href := text(b["href"]) - if href == "" { - href = text(b["链接"]) - } - if href == "" { - href = "/" - } - logo := text(b["logo"]) - if logo == "" { - logo = text(b["标志"]) - } - var s strings.Builder - s.WriteString(`<a id="nav-brand" class="nav-brand" href="`) - s.WriteString(esc(href)) - s.WriteString(`" aria-label="`) - s.WriteString(esc(title)) - s.WriteString(`">`) - if logo != "" { - s.WriteString(`<img class="nav-brand-logo" src="`) - s.WriteString(esc(logo)) - s.WriteString(`" alt="`) - s.WriteString(esc(title)) - s.WriteString(`" width="36" height="36" decoding="async"/>`) - } - if title != "" { - s.WriteString(`<span class="nav-brand-text">`) - s.WriteString(esc(title)) - s.WriteString(`</span>`) - } - s.WriteString(`</a>`) - s.WriteString(`<button type="button" id="nav-menu-toggle" class="nav-menu-toggle" aria-controls="site-side-drawer" aria-expanded="false" aria-label="打开目录">`) - s.WriteString(`<span class="nav-menu-bars" aria-hidden="true"><i></i><i></i><i></i></span>`) - s.WriteString(`<span class="nav-menu-label">目录</span></button>`) - return s.String() -} - -func renderThemeToggleHTML(page map[string]any) string { - if navBrandSpec(page) == nil { - return "" - } - return `<button type="button" id="theme-toggle" class="theme-toggle on-dark" title="切换主题" aria-label="切换到浅色模式">浅色</button>` -} - -func renderNavInner(page map[string]any, linksHTML string) string { - brand := renderNavBrandHTML(page) - toggle := renderThemeToggleHTML(page) - return brand + linksHTML + toggle -} - -func chromeExtrasHTML(page map[string]any) string { - if navBrandSpec(page) == nil && pageClient(page) == nil { - return "" - } - return `<div id="qd-progress" aria-hidden="true"></div>` + - `<button type="button" id="nav-drawer-veil" class="nav-drawer-veil" aria-label="关闭目录" hidden></button>` -} - -func pageClient(page map[string]any) map[string]any { - if page == nil { - return nil - } - if c, ok := page["client"].(map[string]any); ok { - return c - } - return nil -} - -func themeBootScript(page map[string]any) string { - if navBrandSpec(page) == nil && pageClient(page) == nil { - return "" - } - key := themeKeyOf(page) - return `<script>(function(){try{var t=localStorage.getItem("` + key + `");` + - `if(t==="light"||t==="dark")document.documentElement.setAttribute("data-theme",t);` + - `else document.documentElement.setAttribute("data-theme","dark");` + - `}catch(e){document.documentElement.setAttribute("data-theme","dark");}})();</script>` -} - -func clientEmbedScript(page map[string]any) string { - c := pageClient(page) - if c == nil { - return "" - } - source := text(c["source"]) - if source == "" { - source = text(c["源"]) - } - if source == "" { - return "" - } - bridge := text(c["bridge"]) - if bridge == "" { - bridge = text(c["桥"]) - } - if bridge == "" { - bridge = "/static/marqdo-bridge.js" - } - wasm := text(c["wasm"]) - if wasm == "" { - wasm = "/static/marqdo_wasm.wasm" - } - ver := "" - if v, ok := page["asset_version"].(string); ok { - ver = strings.TrimSpace(v) - } else if v, ok := page["资源版本"].(string); ok { - ver = strings.TrimSpace(v) - } - if ver != "" { - bridge = withAssetQuery(bridge, ver) - wasm = withAssetQuery(wasm, ver) - source = withAssetQuery(source, ver) - } - return `<script type="module" src="` + esc(bridge) + `" data-mq-wasm="` + esc(wasm) + - `" data-mq-source-url="` + esc(source) + `"></script>` -} - -func withAssetQuery(url, ver string) string { - if ver == "" || url == "" { - return url - } - if strings.Contains(url, "v=") { - return url - } - sep := "?" - if strings.Contains(url, "?") { - sep = "&" - } - return url + sep + "v=" + ver -} - -var firstPBlockRe = regexp.MustCompile(`(?is)^(\s*)(<p\b[^>]*>)(.*?)(</p>)`) - -func shouldDropcap(plain string) bool { - plain = strings.Join(strings.Fields(plain), "") - if plain == "" { - return false - } - if strings.HasPrefix(plain, "$$") { - return false - } - r, _ := utf8.DecodeRuneInString(plain) - if r == '$' || r == '\\' || r == '[' || r == '(' || unicode.IsDigit(r) { - return false - } - if unicode.In(r, unicode.Han) { - return true - } - return (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') -} - -func stripTags(s string) string { - var b strings.Builder - in := false - for _, r := range s { - switch { - case r == '<': - in = true - case r == '>': - in = false - case !in: - b.WriteRune(r) - } - } - return b.String() -} - -// tuneDropcapHTML adds has-dropcap to the first eligible paragraph in article markdown HTML. -func tuneDropcapHTML(inner string) string { - m := firstPBlockRe.FindStringSubmatch(inner) - if m == nil { - return inner - } - plain := stripTags(m[3]) - if !shouldDropcap(plain) { - return inner - } - open := m[2] - if strings.Contains(open, "has-dropcap") { - return inner - } - if strings.Contains(open, `class="`) { - open = strings.Replace(open, `class="`, `class="has-dropcap `, 1) - } else if strings.Contains(open, `class='`) { - open = strings.Replace(open, `class='`, `class='has-dropcap `, 1) - } else { - open = strings.TrimSuffix(open, ">") + ` class="has-dropcap">` - } - loc := firstPBlockRe.FindStringIndex(inner) - if loc == nil { - return inner - } - return inner[:loc[0]] + m[1] + open + m[3] + m[4] + inner[loc[1]:] -} diff --git a/plugins/web/internal/render/chrome_brand_test.go b/plugins/web/internal/render/chrome_brand_test.go deleted file mode 100755 index 56cd979..0000000 --- a/plugins/web/internal/render/chrome_brand_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package render - -import ( - "strings" - "testing" -) - -func TestFormatMetaDate(t *testing.T) { - if got := formatMetaDate("2026-09-17T13:41:04Z"); got != "2026-09-17" { - t.Fatalf("got %q", got) - } - if got := formatMetaDate("plain"); got != "plain" { - t.Fatalf("got %q", got) - } -} - -func TestTuneDropcapHTML(t *testing.T) { - in := "<p>中文首段。</p><p>二段</p>" - out := tuneDropcapHTML(in) - if !strings.Contains(out, `class="has-dropcap"`) { - t.Fatalf("expected dropcap: %s", out) - } - skip := "<p>$E=mc^2$</p>" - if got := tuneDropcapHTML(skip); strings.Contains(got, "has-dropcap") { - t.Fatalf("formula should skip: %s", got) - } -} diff --git a/plugins/web/internal/render/document_posts_resolve_test.go b/plugins/web/internal/render/document_posts_resolve_test.go deleted file mode 100755 index 356411c..0000000 --- a/plugins/web/internal/render/document_posts_resolve_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package render - -import ( - "fmt" - "path/filepath" - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/compose" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -func TestDocumentPostsResolve(t *testing.T) { - url := "sqlite:" + filepath.Join(t.TempDir(), "posts.db") - fields := []any{ - map[string]any{"name": "title", "type": "text", "nullable": false}, - map[string]any{"name": "summary", "type": "text"}, - map[string]any{"name": "board", "type": "text"}, - map[string]any{"name": "slug", "type": "text"}, - } - if _, err := db.Init(url, "posts", fields); err != nil { - t.Fatal(err) - } - rows := []any{map[string]any{"title": "欢迎", "summary": "Portable test fixture", "board": "demo", "slug": "welcome"}} - if _, err := db.Insert(url, "posts", rows); err != nil { - t.Fatal(err) - } - card := map[string]any{ - "属性": []any{"title", "body", "meta", "href"}, - "值": []any{"posts.title", "posts.summary", "posts.board", "posts.slug"}, - "样式": []any{"", "", "", ""}, - } - page, err := compose.ComposeMain(map[string]any{"title": "帖子", "intro": "<h1>帖子</h1>"}, card, func(path string) (any, error) { - return nil, fmt.Errorf("no lib %s", path) - }) - if err != nil { - t.Fatal(err) - } - pm := page.(map[string]any) - binds, _ := table.AsBind(pm["main"]).([]any) - tn, ok := table.BindTableName(binds) - t.Logf("table=%v BindTableName=%q ok=%v main=%v", pm["table"], tn, ok, pm["main"]) - out, err := db.Select(url, tn, 200, db.SelectOpts{Order: "-created_at"}) - t.Logf("select err=%v rows=%v", err, out["rows"]) - intro, items, _ := resolveMain(pm, url) - t.Logf("intro=%q items=%d", intro, len(items)) - html := RenderPage(pm, url, "") - if !strings.Contains(html, "欢迎") { - t.Fatalf("missing 欢迎 in html:\n%s", html) - } -} diff --git a/plugins/web/internal/render/markdown.go b/plugins/web/internal/render/markdown.go deleted file mode 100755 index 7eb6b26..0000000 --- a/plugins/web/internal/render/markdown.go +++ /dev/null @@ -1,43 +0,0 @@ -package render - -import ( - "bytes" - "strings" - - "github.com/yuin/goldmark" - "github.com/yuin/goldmark/extension" - "github.com/yuin/goldmark/parser" - "github.com/yuin/goldmark/renderer/html" -) - -// MarkdownToHTML renders Markdown to an article-body HTML fragment (GFM subset). -func MarkdownToHTML(md string) string { - return markdownToHTML(md) -} - -// markdownToHTML renders article body Markdown to HTML (GFM subset), matching -// the Rust web plugin's pulldown-cmark path. -func markdownToHTML(md string) string { - md = strings.TrimSpace(md) - if md == "" { - return "" - } - gm := goldmark.New( - goldmark.WithExtensions( - extension.GFM, - extension.Strikethrough, - ), - goldmark.WithParserOptions( - parser.WithAutoHeadingID(), - ), - goldmark.WithRendererOptions( - html.WithHardWraps(), - html.WithXHTML(), - ), - ) - var buf bytes.Buffer - if err := gm.Convert([]byte(md), &buf); err != nil { - return `<div class="article-body"><p class="article-p">` + esc(md) + `</p></div>` - } - return `<div class="article-body md">` + tuneDropcapHTML(buf.String()) + `</div>` -} diff --git a/plugins/web/internal/render/rail_test.go b/plugins/web/internal/render/rail_test.go deleted file mode 100755 index e20d288..0000000 --- a/plugins/web/internal/render/rail_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package render - -import ( - "strings" - "testing" -) - -func TestIsRailTarget(t *testing.T) { - for _, in := range []string{"rail", "轨", "新闻轨", "#side-rail", "aside.side-rail"} { - if !isRailTarget(in) { - t.Fatalf("expected rail: %q", in) - } - } - if isRailTarget("#comment-list") { - t.Fatal("comment list must not be rail") - } -} - -func TestRenderNewsRail(t *testing.T) { - html := renderNewsRail([]map[string]any{ - {"title": "A", "href": "https://ex.test/a", "meta": "2026-09-01", "tag": "IBM"}, - }) - for _, want := range []string{`side-rail--news`, `https://ex.test/a`, `target="_blank"`, `量子新闻`, `全部 →`} { - if !strings.Contains(html, want) { - t.Fatalf("missing %q in %s", want, html) - } - } -} diff --git a/plugins/web/internal/render/render.go b/plugins/web/internal/render/render.go deleted file mode 100755 index 6f4bbb1..0000000 --- a/plugins/web/internal/render/render.go +++ /dev/null @@ -1,1642 +0,0 @@ -// Package render ports HTML shell rendering from the Rust web plugin. -package render - -import ( - "fmt" - "sort" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/assets" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/form" - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -func esc(s string) string { - r := strings.NewReplacer( - "&", "&", - "<", "<", - ">", ">", - `"`, """, - ) - return r.Replace(s) -} - -func text(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - if t { - return "true" - } - return "false" - case float64: - if t == float64(int64(t)) { - return fmt.Sprintf("%d", int64(t)) - } - return fmt.Sprint(t) - default: - return fmt.Sprint(t) - } -} - -func classAttr(css string) string { - if css == "" { - return "" - } - return fmt.Sprintf(` class="%s"`, esc(css)) -} - -func isSimpleIdent(s string) bool { - if s == "" { - return false - } - for _, c := range s { - if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' { - continue - } - if c > 127 { - continue - } - return false - } - return true -} - -func isDBBindBack(back string) bool { - s := table.NormalizeRef(back) - if s == "" || strings.Contains(s, "://") || strings.HasPrefix(s, "/") || - strings.HasPrefix(s, "#") || strings.HasPrefix(s, "?") { - return false - } - sp := table.ParseSitePath(s) - switch sp.Kind { - case table.SitePathDbField: - return true - case table.SitePathLibMember: - return isSimpleIdent(sp.Lib) && isSimpleIdent(sp.Member) - case table.SitePathPlain: - parts := strings.Split(sp.Plain, ".") - n := 0 - for _, p := range parts { - if p != "" { - n++ - if !isSimpleIdent(p) { - return false - } - } - } - return n == 2 - } - return false -} - -type navLink struct { - label string - href string - class string - media string -} - -type navWhen int - -const ( - navAlways navWhen = iota - navHide - navAuth - navGuest -) - -func parseNavWhen(raw string) navWhen { - t := strings.TrimSpace(raw) - switch t { - case "", "*", "always", "Always", "真", "yes", "on", "show", "all": - return navAlways - case "hide", "never", "off", "no", "假", "否", "0", "false", "False": - return navHide - case "auth", "user", "登录", "已登录", "logged_in", "logged-in": - return navAuth - case "guest", "anon", "anonymous", "访客", "匿名", "未登录": - return navGuest - default: - return navAlways - } -} - -func pageAuthState(page map[string]any) *bool { - if page == nil { - return nil - } - for _, k := range []string{"_nav_user", "user", "username", "_user"} { - if v, ok := page[k]; ok { - b := false - switch t := v.(type) { - case nil: - b = false - case bool: - b = t - case string: - b = strings.TrimSpace(t) != "" - case float64: - b = int64(t) != 0 - default: - b = true - } - return &b - } - } - for _, k := range []string{"_logged_in", "logged_in"} { - if v, ok := page[k]; ok { - switch t := v.(type) { - case bool: - return &t - case string: - b := false - switch strings.TrimSpace(t) { - case "1", "true", "True", "yes", "on", "真", "是": - b = true - } - return &b - case float64: - b := int64(t) != 0 - return &b - } - } - } - return nil -} - -func navWhenVisible(when navWhen, auth *bool) bool { - switch when { - case navAlways: - return true - case navHide: - return false - case navAuth: - if auth == nil { - return true - } - return *auth - case navGuest: - if auth == nil { - return true - } - return !*auth - } - return true -} - -func selectPageData(url, tableName string, page map[string]any, limit, offset int64) map[string]any { - var where any - if q, ok := page["query"]; ok { - // Expand `{param}` placeholders from dynamic route params (ABI: 查询条件). - where = resolvePlaceholders(q, pageParams(page)) - } - order, _ := page["order"].(string) - opts := db.SelectOpts{Where: where, Order: order} - if _, ok := page["paginate"]; ok || offset > 0 { - opts.Offset = &offset - } - out, err := db.Select(url, tableName, limit, opts) - if err != nil { - return map[string]any{"rows": []any{}} - } - return out -} - -func pageParams(page map[string]any) map[string]any { - if page == nil { - return nil - } - p, _ := page["params"].(map[string]any) - return p -} - -// resolvePlaceholders walks query / route values and replaces `{name}` with -// page.params[name]. Unmatched placeholders are left as `{name}` for debugging. -func resolvePlaceholders(v any, params map[string]any) any { - if len(params) == 0 { - return v - } - switch t := v.(type) { - case string: - return resolveParamsString(t, params) - case map[string]any: - out := make(map[string]any, len(t)) - for k, val := range t { - out[k] = resolvePlaceholders(val, params) - } - return out - case []any: - out := make([]any, len(t)) - for i, val := range t { - out[i] = resolvePlaceholders(val, params) - } - return out - default: - return v - } -} - -// ResolveRouteParams substitutes `{name}` in a route pattern using params. -func ResolveRouteParams(pattern string, params map[string]any) string { - return resolveParamsString(pattern, params) -} - -func resolveParamsString(s string, params map[string]any) string { - if !strings.Contains(s, "{") || len(params) == 0 { - return s - } - var out strings.Builder - rest := s - for { - start := strings.Index(rest, "{") - if start < 0 { - out.WriteString(rest) - break - } - out.WriteString(rest[:start]) - rest = rest[start+1:] - end := strings.Index(rest, "}") - if end < 0 { - out.WriteByte('{') - out.WriteString(rest) - break - } - key := rest[:end] - if val, ok := params[key]; ok { - out.WriteString(text(val)) - } else { - out.WriteByte('{') - out.WriteString(key) - out.WriteByte('}') - } - rest = rest[end+1:] - } - return out.String() -} - -func resolveLinks(raw any, dbURL string, page map[string]any) []navLink { - if raw == nil { - return nil - } - auth := pageAuthState(page) - bindsAny := table.AsBind(raw) - arr, _ := bindsAny.([]any) - var rows []map[string]any - if len(arr) > 0 { - hasDB := false - for _, b := range arr { - m, _ := b.(map[string]any) - back, _ := m["back"].(string) - if isDBBindBack(back) { - hasDB = true - break - } - } - if hasDB { - if dbURL == "" { - return nil - } - tn, ok := table.BindTableName(arr) - if !ok { - return nil - } - data := selectPageData(dbURL, tn, map[string]any{}, 200, 0) - rawRows, _ := data["rows"].([]any) - projected := table.ProjectRows(arr, rawRows) - parr, _ := projected.([]any) - for _, it := range parr { - if m, ok := it.(map[string]any); ok { - rows = append(rows, m) - } - } - } else { - for _, b := range arr { - if m, ok := b.(map[string]any); ok { - rows = append(rows, m) - } - } - } - } else { - rows = table.AsNavRows(raw) - } - - var out []navLink - for _, m := range rows { - label, href := table.NavLabelHref(m) - if label == "" { - continue - } - media, whenRaw, class := table.NavMediaWhenClass(m) - if whenRaw == "" { - if v, ok := m["when"]; ok { - whenRaw = text(v) - } else if v, ok := m["当"]; ok { - whenRaw = text(v) - } - } - if media == "" { - if v, ok := m["media"]; ok { - media = text(v) - } else if v, ok := m["媒体"]; ok { - media = text(v) - } - } - when := parseNavWhen(whenRaw) - if !navWhenVisible(when, auth) { - continue - } - out = append(out, navLink{label: label, href: href, class: class, media: media}) - } - return out -} - -func navMediaClassMapMany(groups ...[]navLink) (string, [][2]string) { - var pairs [][2]string - var css strings.Builder - for _, links := range groups { - for _, link := range links { - media := strings.TrimSpace(link.media) - if media == "" { - continue - } - dup := false - for _, p := range pairs { - if p[0] == media { - dup = true - break - } - } - if dup { - continue - } - class := fmt.Sprintf("nav-mq-%d", len(pairs)) - css.WriteString(fmt.Sprintf( - "@media not %s { li.%s { display:none !important; } }\n", - media, class, - )) - pairs = append(pairs, [2]string{media, class}) - } - } - return css.String(), pairs -} - -func renderULWithMQ(links []navLink, class string, mqPairs [][2]string) string { - var s strings.Builder - s.WriteString(fmt.Sprintf(`<ul class="%s">`, esc(class))) - for _, link := range links { - mq := strings.TrimSpace(link.media) - mqClass := "" - if mq != "" { - for _, p := range mqPairs { - if p[0] == mq { - mqClass = p[1] - break - } - } - } - liClass := link.class - if mqClass != "" { - if liClass != "" { - liClass += " " - } - liClass += mqClass - } - if liClass == "" { - s.WriteString(fmt.Sprintf(`<li><a href="%s">%s</a></li>`, esc(link.href), esc(link.label))) - } else { - s.WriteString(fmt.Sprintf( - `<li class="%s"><a href="%s">%s</a></li>`, - esc(liClass), esc(link.href), esc(link.label), - )) - } - } - s.WriteString("</ul>") - return s.String() -} - -func resolveMain(page map[string]any, dbURL string) (intro string, items []map[string]any, total *int64) { - intro, _ = page["intro"].(string) - limit := int64(200) - offset := int64(0) - if p, ok := page["paginate"].(map[string]any); ok { - if v, ok := p["limit"].(float64); ok { - limit = int64(v) - } - if v, ok := p["offset"].(float64); ok { - offset = int64(v) - } - } - - // Legacy compose_main bind table (internal); prefer when present. - if main, ok := page["main"]; ok { - bindsAny := table.AsBind(main) - arr, _ := bindsAny.([]any) - if len(arr) > 0 && dbURL != "" { - if tn, ok := table.BindTableName(arr); ok { - data := selectPageData(dbURL, tn, page, limit, offset) - if t, ok := data["total"].(float64); ok { - ti := int64(t) - total = &ti - } - rawRows, _ := data["rows"].([]any) - projected := table.ProjectRows(arr, rawRows) - parr, _ := projected.([]any) - for _, v := range parr { - if m, ok := v.(map[string]any); ok { - items = append(items, m) - } - } - return intro, items, total - } - } - } - - // Artifact Document: flat data_source / data_order / data_where (ADR 0007). - src, _ := page["data_source"].(string) - if src == "" || dbURL == "" { - return intro, nil, nil - } - data := selectPageData(dbURL, src, page, limit, offset) - if t, ok := data["total"].(float64); ok { - ti := int64(t) - total = &ti - } - rawRows, _ := data["rows"].([]any) - for _, v := range rawRows { - if m := projectArtifactRow(v); m != nil { - items = append(items, m) - } - } - return intro, items, total -} - -// projectArtifactRow maps a DB row to card/article fields without compose binds. -func projectArtifactRow(row any) map[string]any { - obj, ok := row.(map[string]any) - if !ok || obj == nil { - return nil - } - m := map[string]any{} - if id, ok := obj["id"]; ok { - m["id"] = id - } - if t := text(obj["title"]); t != "" { - m["title"] = t - } - if s := text(obj["slug"]); s != "" { - m["href"] = s - } else if h := text(obj["href"]); h != "" { - m["href"] = h - } - // Detail pages prefer full content; list cards prefer summary. - if c := text(obj["content"]); c != "" { - m["body"] = c - } else if s := text(obj["summary"]); s != "" { - m["body"] = s - } else if b := text(obj["body"]); b != "" { - m["body"] = b - } - if tag := text(obj["tag"]); tag != "" { - m["tag"] = tag - } - if meta := text(obj["created_at"]); meta != "" { - m["meta"] = meta - } else if meta := text(obj["meta"]); meta != "" { - m["meta"] = meta - } - if len(m) == 0 { - return nil - } - return m -} - -// listBind is one secondary page list (compose_list / 列表装配). -type listBind struct { - Items []map[string]any - Target string - HTML string - Rail bool -} - -func isRailTarget(target string) bool { - t := strings.TrimSpace(strings.ToLower(target)) - t = strings.TrimPrefix(t, "#") - switch t { - case "rail", "轨", "side-rail", "aside.side-rail", "新闻轨": - return true - default: - return false - } -} - -func resolveLists(page map[string]any, dbURL string) []listBind { - raw, ok := page["lists"].([]any) - if !ok || len(raw) == 0 || dbURL == "" { - return nil - } - var out []listBind - for _, entry := range raw { - em, ok := entry.(map[string]any) - if !ok { - continue - } - bindsAny := table.AsBind(em["main"]) - arr, _ := bindsAny.([]any) - if len(arr) == 0 { - continue - } - tn, ok := table.BindTableName(arr) - if !ok { - continue - } - sub := map[string]any{"params": pageParams(page)} - if q, ok := em["query"]; ok { - sub["query"] = q - } - if o, ok := em["order"].(string); ok { - sub["order"] = o - } - limit := int64(200) - target := "" - if t, ok := em["target"].(string); ok { - target = t - } - if isRailTarget(target) { - limit = 24 - } - data := selectPageData(dbURL, tn, sub, limit, 0) - rawRows, _ := data["rows"].([]any) - projected := table.ProjectRows(arr, rawRows) - parr, _ := projected.([]any) - var items []map[string]any - for _, v := range parr { - if m, ok := v.(map[string]any); ok { - items = append(items, m) - } - } - lb := listBind{Items: items, Target: target, Rail: isRailTarget(target)} - if lb.Rail { - lb.HTML = renderNewsRail(items) - } else { - lb.HTML = renderListSection(page, items) - } - out = append(out, lb) - } - return out -} - -func renderNewsRail(items []map[string]any) string { - var list strings.Builder - if len(items) == 0 { - list.WriteString(`<li class="side-news-empty">暂无快讯,请在库表 news 中添加。</li>`) - } else { - for _, it := range items { - title := text(it["title"]) - href := strings.TrimSpace(text(it["href"])) - if href == "" { - href = "#" - } - meta := text(it["meta"]) - if len(meta) > 10 { - meta = meta[:10] - } - tag := text(it["tag"]) - ext := strings.HasPrefix(href, "http://") || strings.HasPrefix(href, "https://") - list.WriteString(`<li>`) - list.WriteString(`<a href="` + esc(href) + `"`) - if ext { - list.WriteString(` target="_blank" rel="noopener noreferrer"`) - } - list.WriteString(`>`) - list.WriteString(`<span class="side-news-meta">`) - if meta != "" { - list.WriteString(`<time>` + esc(meta) + `</time>`) - } - if tag != "" { - list.WriteString(`<span class="side-news-src">` + esc(tag) + `</span>`) - } - list.WriteString(`</span>`) - list.WriteString(`<span class="side-news-title">` + esc(title) + `</span>`) - list.WriteString(`</a></li>`) - } - } - return `<aside class="side-rail side-rail--news" aria-label="量子新闻">` + - `<div class="side-rail-head">` + - `<p class="side-rail-label">量子新闻</p>` + - `<a class="side-rail-jump" href="/news" title="浏览全部新闻" aria-label="浏览全部新闻">全部 →</a>` + - `</div>` + - `<div class="side-rail-body"><ul class="side-news-list">` + list.String() + `</ul></div>` + - `</aside>` -} - -func renderListSection(page map[string]any, items []map[string]any) string { - var s strings.Builder - s.WriteString(`<div class="list-bind" aria-live="polite">`) - if len(items) == 0 { - s.WriteString(`<p class="list-empty comment-empty">还没有条目。</p>`) - } else { - s.WriteString(`<ul class="list-thread comment-thread">`) - for _, it := range items { - s.WriteString(renderListItem(page, it)) - } - s.WriteString(`</ul>`) - } - s.WriteString(`</div>`) - return s.String() -} - -func renderListItem(page map[string]any, it map[string]any) string { - title := text(it["title"]) - body := text(it["body"]) - meta := text(it["meta"]) - href := text(it["href"]) - if href != "" { - return `<li class="list-item">` + renderCard(page, it) + `</li>` - } - var s strings.Builder - s.WriteString(`<li class="list-item comment-item">`) - s.WriteString(`<div class="comment-meta">`) - if title != "" { - s.WriteString(fmt.Sprintf(`<span class="comment-author">%s</span>`, esc(title))) - } - if meta != "" { - s.WriteString(fmt.Sprintf(`<time>%s</time>`, esc(meta))) - } - s.WriteString(`</div>`) - if body != "" { - escaped := esc(body) - escaped = strings.ReplaceAll(escaped, "\n", "<br>") - s.WriteString(fmt.Sprintf(`<p class="comment-body">%s</p>`, escaped)) - } - s.WriteString(`</li>`) - return s.String() -} - -func applyListTargets(intro string, lists []listBind) (string, string, string) { - rest := strings.Builder{} - rail := "" - for _, lb := range lists { - if lb.HTML == "" { - continue - } - if lb.Rail { - if rail == "" { - rail = lb.HTML - } - continue - } - if lb.Target != "" && intro != "" { - if injected, ok := injectHTMLIntoID(intro, lb.Target, lb.HTML); ok { - intro = injected - continue - } - } - rest.WriteString(lb.HTML) - } - return intro, rest.String(), rail -} - -func fieldCSS(obj map[string]any, field string) string { - css, _ := obj["_css"].(map[string]any) - if css == nil { - return "" - } - s, _ := css[field].(string) - return s -} - -func partSrcPrefix(page map[string]any) string { - r, _ := page["_route"].(string) - r = resolveParamsString(r, pageParams(page)) - if r == "" || r == "/" { - return "" - } - for len(r) > 1 && strings.HasSuffix(r, "/") { - r = r[:len(r)-1] - } - if strings.HasPrefix(r, "/") { - return r - } - return "/" + r -} - -func slotAttrs(slot string, parts map[string]any, page map[string]any) string { - prefix := partSrcPrefix(page) - a := fmt.Sprintf(` data-slot="%s"`, esc(slot)) - for id, cfg := range parts { - cm, ok := cfg.(map[string]any) - if !ok { - continue - } - s, _ := cm["slot"].(string) - if s == "" { - s, _ = cm["fragment"].(string) - } - if s == slot || (slot == "sidebar" && id == "side") || (slot == "main" && id == "index") { - a += fmt.Sprintf(` data-slot-src="%s/_part/%s"`, esc(prefix), esc(id)) - break - } - } - return a -} - -func slotClass(page map[string]any, slot, base string) string { - extra := "" - if sc, ok := page["slot_class"].(map[string]any); ok { - extra, _ = sc[slot].(string) - } - if extra == "" { - return base - } - return base + " " + extra -} - -const shellVars = ` -:root { --ink:#1c1917; --muted:#57534e; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; } -body { margin:0; font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif; background:var(--paper); color:var(--ink); } -a { color:var(--ink); text-decoration:none; } -a:hover { color:var(--accent); } -` - -const shellLayout = ` -body { display:grid; min-height:100vh; grid-template-rows:auto 1fr auto; } -body.has-sidebar { grid-template-columns:14rem 1fr; grid-template-areas:"top top" "side main" "foot foot"; } -body.no-sidebar { grid-template-areas:"top" "main" "foot"; } -@media (max-width:720px) { - body.has-sidebar { grid-template-columns:1fr; grid-template-areas:"top" "main" "foot" "side"; } - body.has-sidebar aside.side { border-right:0; border-top:1px solid var(--line); } -} -body.layout-stacked { display:flex; flex-direction:column; min-height:100vh; } -body.layout-stacked header.topnav, body.layout-stacked aside.side, body.layout-stacked main.main, body.layout-stacked footer.foot { width:100%; } -body.layout-stacked aside.side { border-right:0; border-bottom:1px solid var(--line); } -body.layout-bare { display:block; min-height:100vh; } -body.layout-bare main.main { padding:1.5rem 1.25rem 2rem; } -header.topnav { grid-area:top; border-bottom:1px solid var(--line); padding:.85rem 1.25rem; background:#fff; } -aside.side { grid-area:side; border-right:1px solid var(--line); padding:1.25rem 1rem; background:#f5f5f4; } -main.main { grid-area:main; padding:1.5rem 1.25rem 2rem; } -footer.foot { grid-area:foot; border-top:1px solid var(--line); padding:.85rem 1.25rem; color:var(--muted); background:#fff; } -ul.nav, ul.side-nav, ul.foot-nav { list-style:none; margin:0; padding:0; display:flex; flex-wrap:wrap; gap:.35rem 1rem; } -ul.side-nav { flex-direction:column; } -` - -const shellWidgets = ` -.content.cards { display:grid; gap:1rem; margin-top:1.25rem; grid-template-columns:repeat(auto-fill,minmax(16rem,1fr)); } -.content.cards article { background:#fff; border:1px solid var(--line); border-radius:6px; padding:1rem; } -.main-intro h1 { margin:0 0 .75rem; font-size:2rem; } -.main-intro p { color:var(--muted); } -.site-form { margin-top:1.25rem; max-width:28rem; } -.article { background:#fff; border:1px solid var(--line); border-radius:8px; padding:2rem; margin-top:1.5rem; } -.article-title { margin:0 0 .75rem; font-size:2rem; } -.article-body { line-height:1.75; color:var(--ink); } -.article-body.md { line-height: 1.75; } -.article-body.md pre { background:#f5f5f4; border:1px solid var(--line); border-radius:6px; padding:1rem; overflow-x:auto; } -.article-body.md code { font-size:.9em; } -.pagination { display:flex; gap:1rem; align-items:center; margin:1.5rem 0; font-size:.95rem; } -` - -func shellCSSFor(mode string) string { - switch strings.ToLower(strings.TrimSpace(mode)) { - case "off", "none", "false", "0": - return "" - case "minimal", "min", "vars": - return shellVars - default: - return shellVars + shellLayout + shellWidgets - } -} - -func resolveShellCSS(page map[string]any) string { - raw := "full" - if s, ok := page["shell_css"].(string); ok { - raw = s - } else if s, ok := page["壳样式"].(string); ok { - raw = s - } - return shellCSSFor(raw) -} - -func normalizeLayout(raw string) string { - switch strings.ToLower(strings.TrimSpace(raw)) { - case "", "auto", "default": - return "" - case "sidebar", "side": - return "sidebar" - case "stacked", "stack", "column": - return "stacked" - case "bare", "main", "none": - return "bare" - case "rail": - return "rail" - default: - return raw - } -} - -func resolveLayout(page map[string]any) string { - raw := "" - if s, ok := page["layout"].(string); ok { - raw = s - } else if s, ok := page["布局"].(string); ok { - raw = s - } - return normalizeLayout(raw) -} - -// DocumentHead reuses ordinary Document metadata, links and native head boot -// helpers without adding application configuration or a second HTML dialect. -func DocumentHead(title string, meta map[string]any, links []assets.HeadLink) string { - if title == "" { - title = "Marqdo" - } - return headHTML(map[string]any{"meta": meta, "head": assets.HeadLinksToJSON(links)}, title) -} - -func headHTML(page map[string]any, defaultTitle string) string { - pageTitle := defaultTitle - if meta, ok := page["meta"].(map[string]any); ok { - if t := text(meta["title"]); t != "" { - pageTitle = t - } - } - var s strings.Builder - s.WriteString(fmt.Sprintf("<title>%s", esc(pageTitle))) - if csrf, ok := page["_csrf"].(string); ok && strings.TrimSpace(csrf) != "" { - s.WriteString(fmt.Sprintf(``, esc(strings.TrimSpace(csrf)))) - } - if meta, ok := page["meta"].(map[string]any); ok { - keys := make([]string, 0, len(meta)) - for key := range meta { - keys = append(keys, key) - } - sort.Strings(keys) - for _, k := range keys { - v := meta[k] - if k == "title" { - continue - } - val := text(v) - if val == "" { - continue - } - switch { - case k == "description": - s.WriteString(fmt.Sprintf(``, esc(val))) - case k == "canonical": - s.WriteString(fmt.Sprintf(``, esc(val))) - case k == "icon" || k == "favicon": - s.WriteString(fmt.Sprintf(``, esc(val))) - case strings.HasPrefix(k, "og:"): - s.WriteString(fmt.Sprintf(``, esc(k), esc(val))) - default: - s.WriteString(fmt.Sprintf(``, esc(k), esc(val))) - } - } - } - if head, ok := page["head"]; ok { - links := assets.HeadLinksFromJSON(head) - assetVersion := "" - if v, ok := page["asset_version"].(string); ok { - assetVersion = v - } else if v, ok := page["资源版本"].(string); ok { - assetVersion = v - } - s.WriteString(assets.RenderHeadLinksWithVersion(links, assetVersion)) - if headNeedsKatexBoot(links) { - s.WriteString(katexBootScript()) - } - } - if pageNeedsMarkdownPreview(page) { - s.WriteString(markdownPreviewBootScript()) - } - s.WriteString(themeBootScript(page)) - s.WriteString(clientEmbedScript(page)) - return s.String() -} - -func headNeedsKatexBoot(links []assets.HeadLink) bool { - hasAuto := false - for _, l := range links { - href := strings.ToLower(l.Href) - if strings.Contains(href, "auto-render") { - hasAuto = true - break - } - } - return hasAuto -} - -func katexBootScript() string { - // Official host glue: call KaTeX auto-render after deferred scripts load. - // Authors must not ship this as business JS. - return `` -} - -func pageNeedsMarkdownPreview(page map[string]any) bool { - if page == nil { - return false - } - frm, _ := page["form"].(map[string]any) - if frm == nil { - return false - } - fields, _ := frm["fields"].([]any) - for _, f := range fields { - fm, ok := f.(map[string]any) - if !ok { - continue - } - ty := strings.ToLower(strings.TrimSpace(text(fm["type"]))) - if ty == "markdown" { - return true - } - } - return false -} - -func markdownPreviewBootScript() string { - // Official host glue: live-preview textarea.mq-markdown via POST /_md. - return `` -} - -func cardHref(page map[string]any, href string) string { - href = strings.TrimSpace(href) - if href == "" { - return "" - } - if strings.HasPrefix(href, "http://") || strings.HasPrefix(href, "https://") || strings.HasPrefix(href, "//") { - return href - } - if strings.HasPrefix(href, "/") { - return href - } - prefix := "/post/" - if page != nil { - if p, ok := page["link_prefix"].(string); ok { - prefix = p - } - } - return prefix + href -} - -func renderCard(page map[string]any, it map[string]any) string { - title := text(it["title"]) - body := text(it["body"]) - href := cardHref(page, text(it["href"])) - meta := text(it["meta"]) - tag := text(it["tag"]) - tc := classAttr(fieldCSS(it, "title")) - bc := classAttr(fieldCSS(it, "body")) - cls := "card" - switch v := it["pinned"].(type) { - case bool: - if v { - cls += " is-pinned" - } - case string: - if v == "1" || strings.EqualFold(v, "true") { - cls += " is-pinned" - } - case float64: - if v == 1 { - cls += " is-pinned" - } - case int: - if v == 1 { - cls += " is-pinned" - } - case int64: - if v == 1 { - cls += " is-pinned" - } - } - var card strings.Builder - card.WriteString(`") - return card.String() -} - -func renderArticle(it map[string]any) string { - title := text(it["title"]) - body := text(it["body"]) - meta := text(it["meta"]) - tag := text(it["tag"]) - var s strings.Builder - s.WriteString(`
      `) - if meta != "" { - s.WriteString(fmt.Sprintf(``, esc(formatMetaDate(meta)))) - } - s.WriteString(fmt.Sprintf(`

      %s

      `, esc(title))) - if tag != "" { - s.WriteString(fmt.Sprintf(``, esc(tag))) - } - if body != "" { - s.WriteString(markdownToHTML(body)) - } - s.WriteString("
      ") - return s.String() -} - -func renderPagination(page map[string]any, total int64, itemCount int) string { - p, ok := page["paginate"].(map[string]any) - if !ok { - return "" - } - offset := int64(0) - limit := int64(10) - if v, ok := p["offset"].(float64); ok { - offset = int64(v) - } - if v, ok := p["limit"].(float64); ok { - limit = int64(v) - } - if limit <= 0 { - return "" - } - path := "/" - if s, ok := p["path"].(string); ok { - path = s - } - var s strings.Builder - s.WriteString(`") - return s.String() -} - -func formMountID(target string) string { - t := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(target), "#")) - if t == "" { - return "" - } - for _, c := range t { - if c == ' ' || c == '\t' || c == '\n' || c == '"' || c == '\'' || c == '<' || c == '>' { - return "" - } - } - return t -} - -// injectHTMLIntoID puts payload inside the first element with id="…" / id='…'. -func injectHTMLIntoID(haystack, id, payload string) (string, bool) { - id = formMountID(id) - if id == "" { - return "", false - } - patterns := []string{`id="` + id + `"`, `id='` + id + `'`} - for _, pat := range patterns { - idx := strings.Index(haystack, pat) - if idx < 0 { - continue - } - tagStart := strings.LastIndex(haystack[:idx], "<") - if tagStart < 0 { - continue - } - if tagStart+1 >= len(haystack) { - continue - } - afterLt := haystack[tagStart+1] - if afterLt == '/' || afterLt == '!' { - continue - } - nameEnd := tagStart + 1 - for nameEnd < len(haystack) { - c := haystack[nameEnd] - if c == ' ' || c == '\t' || c == '\n' || c == '>' || c == '/' { - break - } - nameEnd++ - } - tagName := strings.TrimSpace(haystack[tagStart+1 : nameEnd]) - if tagName == "" { - continue - } - afterID := idx + len(pat) - rel := strings.IndexByte(haystack[afterID:], '>') - if rel < 0 { - continue - } - openGt := afterID + rel - if openGt > 0 && haystack[openGt-1] == '/' { - continue - } - close := "" - rest := haystack[openGt+1:] - closeRel := strings.Index(strings.ToLower(rest), strings.ToLower(close)) - if closeRel < 0 { - continue - } - closeIdx := openGt + 1 + closeRel - var out strings.Builder - out.Grow(len(haystack) + len(payload)) - out.WriteString(haystack[:openGt+1]) - out.WriteString(payload) - out.WriteString(haystack[closeIdx:]) - return out.String(), true - } - return "", false -} - -func pageFormHTML(page map[string]any) (formID string, html string) { - if page == nil { - return "", "" - } - id, _ := page["form_id"].(string) - id = strings.TrimSpace(id) - if id == "" { - return "", "" - } - frm, ok := page["form"].(map[string]any) - if !ok || frm == nil { - return "", "" - } - ctx := &form.RequestContext{ - Params: pageParams(page), - } - if u, ok := page["_nav_user"].(string); ok { - ctx.Username = u - } - if r, ok := page["_route"].(string); ok && r != "" { - ctx.ReturnPath = r - ctx.Path = r - } - data := resolveFormData(page, "") - return id, form.RenderBodyCtx(frm, id, data, nil, "", ctx) -} - -// resolveFormData returns stamped form_data, or loads a DB row via form_load + params. -func resolveFormData(page map[string]any, dbURL string) map[string]any { - if page == nil { - return nil - } - if raw, ok := page["form_data"].(map[string]any); ok && raw != nil && len(raw) > 0 { - return raw - } - if dbURL == "" { - if u, ok := page["_db_url"].(string); ok { - dbURL = u - } - } - load, ok := page["form_load"].(map[string]any) - if !ok || load == nil || dbURL == "" { - return nil - } - table := text(load["table"]) - if table == "" { - table = text(load["表"]) - } - if table == "" { - return nil - } - idParam := text(load["id_param"]) - if idParam == "" { - idParam = text(load["id参数"]) - } - if idParam == "" { - idParam = "id" - } - id := "" - if params, ok := page["params"].(map[string]any); ok { - id = text(params[idParam]) - } - if id == "" { - return nil - } - row, err := db.Get(dbURL, table, id) - if err != nil || row == nil { - return nil - } - if m, ok := row.(map[string]any); ok { - return m - } - return nil -} - -func pushIntro(buf *strings.Builder, intro string) { - pushIntroAndForm(buf, intro, nil) -} - -// pushIntroAndForm writes intro and optional composed form (GAP-11 form_target inject). -func pushIntroAndForm(buf *strings.Builder, intro string, page map[string]any) { - formID, formHTML := pageFormHTML(page) - target := "" - if page != nil { - if t, ok := page["form_target"].(string); ok { - target = t - } else if t, ok := page["target"].(string); ok { - target = t - } else if t, ok := page["form_slot"].(string); ok { - target = t - } else if t, ok := page["表单插槽"].(string); ok { - target = t - } - } - if formHTML != "" && target != "" && intro != "" { - if injected, ok := injectHTMLIntoID(intro, target, formHTML); ok { - buf.WriteString(fmt.Sprintf(`
      %s
      `, introWrapClass(injected), injected)) - return - } - } - if intro != "" { - buf.WriteString(fmt.Sprintf(`
      %s
      `, introWrapClass(intro), intro)) - } - if formHTML != "" { - buf.WriteString(formHTML) - _ = formID - } -} - -func introWrapClass(intro string) string { - if strings.Contains(intro, "masthead-guide") { - return "main-intro masthead-split" - } - return "main-intro" -} - -func renderFragment(page map[string]any, dbURL, slot string) string { - slot = table.NormalizeSlot(slot) - switch slot { - case "nav": - links := resolveLinks(page["nav"], dbURL, page) - return fmt.Sprintf( - `
      %s
      `, - renderNavInner(page, renderULWithMQ(links, "nav", nil)), - ) - case "sidebar": - links := resolveLinks(page["sidebar"], dbURL, page) - return fmt.Sprintf( - ``, - renderULWithMQ(links, "side-nav", nil), - ) - case "footer": - links := resolveLinks(page["footer"], dbURL, page) - return fmt.Sprintf( - `
      %s
      `, - renderULWithMQ(links, "foot-nav", nil), - ) - default: - intro, items, _ := resolveMain(page, dbURL) - lists := resolveLists(page, dbURL) - intro, listRest, _ := applyListTargets(intro, lists) - isDetail, _ := page["detail"].(bool) - var body strings.Builder - if isDetail { - if len(items) > 0 { - body.WriteString(renderArticle(items[0])) - } - body.WriteString(listRest) - pushIntroAndForm(&body, intro, page) - } else { - pushIntroAndForm(&body, intro, page) - if len(items) > 0 { - body.WriteString(`
      `) - for _, it := range items { - body.WriteString(renderCard(page, it)) - } - body.WriteString(`
      `) - } - body.WriteString(listRest) - } - return fmt.Sprintf(`
      %s
      `, body.String()) - } -} - -// RenderQueryRows projects native database records into existing card/article -// rendering. Query failures remain with the Resource caller, never empty success. -func RenderQueryRows(rows any, detail bool, prefix string) string { - raw, _ := rows.([]any) - var body strings.Builder - if !detail { - body.WriteString(`
      `) - } - for _, row := range raw { - item := projectArtifactRow(row) - if item == nil { - continue - } - if detail { - if object, ok := row.(map[string]any); ok { - if full, exists := object["body"]; exists { - item["body"] = text(full) - } - if full, exists := object["content"]; exists { - item["body"] = text(full) - } - } - body.WriteString(renderArticle(item)) - break - } - body.WriteString(renderCard(map[string]any{"link_prefix": prefix}, item)) - } - if !detail { - body.WriteString("
      ") - } - return body.String() -} - -// RenderPage builds full-page HTML (or a part fragment when partID is set). -func RenderPage(page map[string]any, dbURL string, partID string) string { - // Explicit View Documents already own their structure and document shell. - if partID == "" && page != nil { - if html, ok := page["artifact_html"].(string); ok { - return html - } - } - if page == nil { - page = map[string]any{} - } - if dbURL != "" { - page["_db_url"] = dbURL - } - if partID != "" { - parts, _ := page["parts"].(map[string]any) - if parts != nil { - if cfg, ok := parts[partID].(map[string]any); ok { - merged := map[string]any{} - for k, v := range page { - merged[k] = v - } - for k, v := range cfg { - merged[k] = v - } - slot, _ := cfg["slot"].(string) - if slot == "" { - slot, _ = cfg["fragment"].(string) - } - if slot == "" { - slot = "main" - } - return renderFragment(merged, dbURL, slot) - } - } - return renderFragment(page, dbURL, partID) - } - - title := "Marqdo Web" - if t, ok := page["title"].(string); ok && t != "" { - title = t - } - shell := resolveShellCSS(page) - layout := resolveLayout(page) - parts, _ := page["parts"].(map[string]any) - if parts == nil { - parts = map[string]any{} - } - nav := resolveLinks(page["nav"], dbURL, page) - side := resolveLinks(page["sidebar"], dbURL, page) - foot := resolveLinks(page["footer"], dbURL, page) - intro, items, total := resolveMain(page, dbURL) - if params, ok := page["params"].(map[string]any); ok && len(params) > 0 && intro != "" { - intro = ResolveRouteParams(intro, params) - } - navCSS, mqPairs := navMediaClassMapMany(nav, side, foot) - extra, _ := page["styles_css"].(string) - if navCSS != "" { - if extra != "" { - extra += "\n" - } - extra += navCSS - } - - _, hasSideKey := page["sidebar"] - hasSide := hasSideKey || len(side) > 0 - bare := layout == "bare" - var bodyClass string - switch layout { - case "bare": - bodyClass = "layout-bare" - case "stacked": - bodyClass = "layout-stacked" - case "rail": - if hasSide { - bodyClass = "has-rail has-sidebar" - } else { - bodyClass = "has-rail no-sidebar" - } - case "sidebar": - if hasSide { - bodyClass = "has-sidebar" - } else { - bodyClass = "no-sidebar" - } - case "": - if hasSide { - bodyClass = "has-sidebar" - } else { - bodyClass = "no-sidebar" - } - default: - bodyClass = layout - } - - var mainHTML strings.Builder - if images, ok := page["images_html"].(string); ok && images != "" { - mainHTML.WriteString(images) - } - lists := resolveLists(page, dbURL) - csrfTok := "" - if v, ok := page["_csrf"].(string); ok { - csrfTok = strings.TrimSpace(v) - } - authNext := "" - if v, ok := page["_auth_next"].(string); ok { - authNext = strings.TrimSpace(v) - } - flashErr := "" - if v, ok := page["_flash_err"].(string); ok { - flashErr = strings.TrimSpace(v) - } - if spec := AuthFormFromPage(page); spec != nil { - if authNext == "" && spec.NextDefault != "" { - authNext = spec.NextDefault - } - intro = ApplyAuthFormIntoIntro(intro, spec, csrfTok, authNext, flashErr) - } - intro, listRest, railHTML := applyListTargets(intro, lists) - isDetail, _ := page["detail"].(bool) - if isDetail { - if len(items) > 0 { - mainHTML.WriteString(renderArticle(items[0])) - if total != nil { - mainHTML.WriteString(renderPagination(page, *total, len(items))) - } - } - mainHTML.WriteString(listRest) - pushIntroAndForm(&mainHTML, intro, page) - } else { - pushIntroAndForm(&mainHTML, intro, page) - if len(items) > 0 { - mainHTML.WriteString(`
      `) - for _, it := range items { - mainHTML.WriteString(renderCard(page, it)) - } - mainHTML.WriteString(`
      `) - if total != nil { - mainHTML.WriteString(renderPagination(page, *total, len(items))) - } - } - mainHTML.WriteString(listRest) - } - - styleBlock := "" - if shell != "" || extra != "" { - styleBlock = fmt.Sprintf("", shell, extra) - } - - showChrome := !bare - sideHTML := "" - if showChrome && hasSide { - sideHTML = fmt.Sprintf( - ``, - slotClass(page, "sidebar", "side"), - slotAttrs("sidebar", parts, page), - renderULWithMQ(side, "side-nav", mqPairs), - ) - } - headerHTML := "" - if showChrome { - if raw, ok := page["nav_html"].(string); ok && strings.TrimSpace(raw) != "" { - headerHTML = raw - } else { - headerHTML = fmt.Sprintf( - `
      %s
      `, - slotClass(page, "nav", "topnav"), - slotAttrs("nav", parts, page), - renderNavInner(page, renderULWithMQ(nav, "nav", mqPairs)), - ) - } - } - footerHTML := "" - if showChrome { - if raw, ok := page["footer_html"].(string); ok && strings.TrimSpace(raw) != "" { - footerHTML = raw - } else { - footerHTML = fmt.Sprintf( - `
      %s
      `, - slotClass(page, "footer", "foot"), - slotAttrs("footer", parts, page), - renderULWithMQ(foot, "foot-nav", mqPairs), - ) - } - } - - if extraBody, ok := page["body_class"].(string); ok && strings.TrimSpace(extraBody) != "" { - if bodyClass == "" { - bodyClass = strings.TrimSpace(extraBody) - } else { - bodyClass = bodyClass + " " + strings.TrimSpace(extraBody) - } - } - if railHTML != "" && !strings.Contains(bodyClass, "has-rail") { - if bodyClass == "" { - bodyClass = "has-rail" - } else { - bodyClass = bodyClass + " has-rail" - } - } - - html := fmt.Sprintf(` - - - -%s -%s - - -%s -%s -%s -
      %s
      -%s -%s -`, - headHTML(page, title), - styleBlock, - bodyClass, - chromeExtrasHTML(page), - headerHTML, - sideHTML, - slotClass(page, "main", "main"), - slotAttrs("main", parts, page), - mainHTML.String(), - railHTML, - footerHTML, - ) - return InjectAuthFields(html, csrfTok, authNext, flashErr) -} diff --git a/plugins/web/internal/render/render_test.go b/plugins/web/internal/render/render_test.go deleted file mode 100755 index b7523fe..0000000 --- a/plugins/web/internal/render/render_test.go +++ /dev/null @@ -1,319 +0,0 @@ -package render_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/render" -) - -func TestRenderPageIntroNoDB(t *testing.T) { - page := map[string]any{ - "title": "smoke", - "intro": "

      smoke

      ", - "styles_css": ".x { color: red; }", - "shell_css": "minimal", - } - html := render.RenderPage(page, "", "") - if html == "" { - t.Fatal("empty html") - } - if !strings.Contains(html, "

      smoke

      ") { - t.Fatalf("missing intro: %s", html) - } - if !strings.Contains(html, ".x { color: red; }") { - t.Fatalf("missing styles: %s", html) - } - if !strings.Contains(html, "") { - t.Fatalf("not a document: %s", html[:80]) - } -} - -func TestShellOffStackedOmitsSidebarGrid(t *testing.T) { - page := map[string]any{ - "title": "t", - "shell_css": "off", - "layout": "stacked", - "sidebar": []any{ - map[string]any{"label": "A", "href": "/a"}, - }, - } - html := render.RenderPage(page, "", "") - if !strings.Contains(html, "layout-stacked") { - t.Fatalf("missing layout-stacked: %s", html) - } - if strings.Contains(html, "has-sidebar") { - t.Fatalf("unexpected has-sidebar: %s", html) - } - if strings.Contains(html, "grid-template-columns:14rem") { - t.Fatalf("unexpected sidebar grid: %s", html) - } -} - -func TestShellMinimalKeepsVarsNotCards(t *testing.T) { - page := map[string]any{"title": "t", "shell_css": "minimal"} - html := render.RenderPage(page, "", "") - if !strings.Contains(html, "--ink:") { - t.Fatalf("missing vars: %s", html) - } - if strings.Contains(html, ".content.cards article") { - t.Fatalf("unexpected cards css: %s", html) - } -} - -func TestLayoutBareSkipsAside(t *testing.T) { - page := map[string]any{ - "title": "t", - "layout": "bare", - "sidebar": []any{ - map[string]any{"label": "A", "href": "/a"}, - }, - "nav": []any{ - map[string]any{"label": "Home", "href": "/"}, - }, - } - html := render.RenderPage(page, "", "") - if !strings.Contains(html, "layout-bare") { - t.Fatalf("missing layout-bare: %s", html) - } - if strings.Contains(html, "Home<") { - t.Fatalf("missing Home: %s", html) - } - if strings.Contains(html, "/x") { - t.Fatalf("hide leaked: %s", html) - } -} - -func TestNavWhenAuthGuestRespectsLoggedIn(t *testing.T) { - nav := []any{ - map[string]any{"front": "Public", "back": "/"}, - map[string]any{"front": "Admin", "back": "/admin", "when": "auth"}, - map[string]any{"front": "Login", "back": "/login", "when": "guest"}, - } - guest := map[string]any{ - "title": "t", - "shell_css": "off", - "_logged_in": false, - "nav": nav, - } - g := render.RenderPage(guest, "", "") - if !strings.Contains(g, "/login") { - t.Fatalf("guest missing login: %s", g) - } - if strings.Contains(g, "/admin") { - t.Fatalf("guest leaked admin: %s", g) - } - user := map[string]any{ - "title": "t", - "shell_css": "off", - "_logged_in": true, - "_nav_user": "alice", - "nav": nav, - } - u := render.RenderPage(user, "", "") - if !strings.Contains(u, "/admin") { - t.Fatalf("user missing admin: %s", u) - } - if strings.Contains(u, "/login") { - t.Fatalf("user leaked login: %s", u) - } -} - -func TestNavMediaEmitsClassAndCSS(t *testing.T) { - page := map[string]any{ - "title": "t", - "shell_css": "off", - "nav": []any{ - map[string]any{"label": "Wide", "href": "/w", "media": "(min-width: 900px)"}, - map[string]any{"label": "Home", "href": "/"}, - }, - } - html := render.RenderPage(page, "", "") - if !strings.Contains(html, "nav-mq-0") { - t.Fatalf("missing nav-mq-0: %s", html) - } - if !strings.Contains(html, "@media not (min-width: 900px)") { - t.Fatalf("missing media css: %s", html) - } -} - -func TestHeadDeferVersionAndAssetVersion(t *testing.T) { - page := map[string]any{ - "title": "t", - "asset_version": "appv", - "head": []any{ - map[string]any{"rel": "script", "href": "/static/a.js", "defer": true, "version": "3"}, - map[string]any{"rel": "stylesheet", "href": "/static/t.css", "version": "1"}, - map[string]any{"rel": "script", "href": "/static/b.js", "defer": true}, - }, - } - html := render.RenderPage(page, "", "") - if !strings.Contains(html, `a.js?v=3`) { - t.Fatalf("missing script version: %s", html) - } - if !strings.Contains(html, "script defer") { - t.Fatalf("missing defer: %s", html) - } - if !strings.Contains(html, `t.css?v=1`) { - t.Fatalf("missing css version: %s", html) - } - if !strings.Contains(html, `b.js?v=appv`) { - t.Fatalf("missing asset_version fallback: %s", html) - } - syncPage := map[string]any{ - "title": "t", - "head": []any{ - map[string]any{"rel": "script", "href": "/static/sync.js"}, - }, - } - syncHTML := render.RenderPage(syncPage, "", "") - if !strings.Contains(syncHTML, `sync.js`) { - t.Fatalf("missing sync script: %s", syncHTML) - } - if strings.Contains(syncHTML, "script defer") { - t.Fatalf("unexpected defer on sync: %s", syncHTML) - } -} - -func TestRenderPageNavChrome(t *testing.T) { - page := map[string]any{ - "title": "t", - "nav": []any{ - map[string]any{"front": "Home", "back": "/", "css": "", "media": "", "when": ""}, - }, - "sidebar": []any{ - map[string]any{"front": "A", "back": "/a", "css": "", "media": "", "when": ""}, - }, - "footer": []any{ - map[string]any{"front": "©", "back": "/", "css": "", "media": "", "when": ""}, - }, - "intro": "hi", - } - html := render.RenderPage(page, "", "") - for _, needle := range []string{"bold") { - t.Fatalf("%s", out) - } -} - -func TestCardHrefAbsoluteAndPrefixed(t *testing.T) { - page := map[string]any{"link_prefix": "/post/"} - if got := cardHref(page, "https://example.com/a"); got != "https://example.com/a" { - t.Fatalf("absolute: %q", got) - } - if got := cardHref(page, "/about"); got != "/about" { - t.Fatalf("root: %q", got) - } - if got := cardHref(page, "hello"); got != "/post/hello" { - t.Fatalf("prefixed: %q", got) - } - html := renderCard(page, map[string]any{"title": "T", "href": "https://ex.test/x", "body": "b"}) - if !strings.Contains(html, `href="https://ex.test/x"`) { - t.Fatalf("card absolute: %s", html) - } -} diff --git a/plugins/web/internal/rss/rss.go b/plugins/web/internal/rss/rss.go deleted file mode 100755 index 164ba77..0000000 --- a/plugins/web/internal/rss/rss.go +++ /dev/null @@ -1,83 +0,0 @@ -// Package rss builds RSS 2.0 feeds (content-site W4 / W-G7). -package rss - -import ( - "fmt" - "strconv" - "strings" -) - -func esc(s string) string { - s = strings.ReplaceAll(s, "&", "&") - s = strings.ReplaceAll(s, "<", "<") - s = strings.ReplaceAll(s, ">", ">") - s = strings.ReplaceAll(s, `"`, """) - return s -} - -func cellStr(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - default: - return fmt.Sprint(t) - } -} - -func pick(m map[string]any, keys ...string) any { - for _, k := range keys { - if v, ok := m[k]; ok { - return v - } - } - return nil -} - -// BuildRSS assembles RSS 2.0 XML from channel metadata and row maps. -func BuildRSS(title, link, description string, items []any) string { - body := fmt.Sprintf(` - -%s -%s -%s -`, esc(title), esc(link), esc(description)) - for _, row := range items { - m, ok := row.(map[string]any) - if !ok { - continue - } - itemTitle := cellStr(pick(m, "title", "标题")) - itemLink := cellStr(pick(m, "link", "href", "链接", "slug")) - itemDesc := cellStr(pick(m, "description", "summary", "摘要", "body", "正文")) - pubDate := cellStr(pick(m, "pubDate", "published", "created_at", "发布")) - fullLink := link - if itemLink != "" { - if strings.HasPrefix(itemLink, "http") { - fullLink = itemLink - } else if itemLink[0] == '/' { - fullLink = link + itemLink - } else { - fullLink = link + "/" + itemLink - } - } - body += "" - body += fmt.Sprintf("%s", esc(itemTitle)) - body += fmt.Sprintf("%s", esc(fullLink)) - body += fmt.Sprintf("%s", esc(itemDesc)) - if pubDate != "" { - body += fmt.Sprintf("%s", esc(pubDate)) - } - body += "" - } - body += "" - return body -} diff --git a/plugins/web/internal/rss/rss_test.go b/plugins/web/internal/rss/rss_test.go deleted file mode 100755 index 9296017..0000000 --- a/plugins/web/internal/rss/rss_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package rss - -import ( - "strings" - "testing" -) - -func TestBuildRSSContainsItem(t *testing.T) { - items := []any{ - map[string]any{"title": "Hi", "slug": "/post/a", "summary": "text"}, - } - xml := BuildRSS("Blog", "http://example.com", "Feed", items) - if !strings.Contains(xml, "Hi") { - t.Fatalf("missing item title: %s", xml) - } - if !strings.Contains(xml, "http://example.com/post/a") { - t.Fatalf("missing full link: %s", xml) - } -} diff --git a/plugins/web/internal/session/session.go b/plugins/web/internal/session/session.go deleted file mode 100755 index bfde136..0000000 --- a/plugins/web/internal/session/session.go +++ /dev/null @@ -1,693 +0,0 @@ -// Package session ports in-memory / SQLite session store from the Rust web plugin. -package session - -import ( - "context" - "crypto/rand" - "encoding/hex" - "encoding/json" - "fmt" - "strings" - "sync" - "time" - - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/redis/go-redis/v9" -) - -const ( - sessionTable = "_marqdo_sessions" - csrfKey = "_csrf" - defaultTTL = 3600 -) - -// Config controls session backend. -type Config struct { - DBURL string // sqlite:… or legacy SQL session table - RedisURL string // redis:// or rediss:// (G-SESS1) - TTLSec uint64 - CookieSecure bool -} - -var ( - cfgMu sync.Mutex - cfg = Config{TTLSec: defaultTTL} - - memMu sync.Mutex - mem = map[string]memRec{} - memTTL uint64 = defaultTTL - - redisMu sync.Mutex - redisClient *redis.Client - redisURL string -) - -type memRec struct { - exp uint64 - data map[string]any -} - -func nowSecs() uint64 { - return uint64(time.Now().Unix()) -} - -func cloneData(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} - -func isRedisURL(url string) bool { - u := strings.ToLower(strings.TrimSpace(url)) - return strings.HasPrefix(u, "redis://") || strings.HasPrefix(u, "rediss://") -} - -func isSQLiteURL(url string) bool { - u := strings.TrimSpace(url) - return u != "" && !isRedisURL(u) -} - -// Configure sets session backend before listen or offline ABI calls. -// RedisURL or a redis:// DBURL selects the Redis backend; sqlite DBURL keeps SQL table storage. -func Configure(c Config) { - ttl := c.TTLSec - if ttl == 0 { - ttl = defaultTTL - } - c.TTLSec = ttl - if c.RedisURL == "" && isRedisURL(c.DBURL) { - c.RedisURL = strings.TrimSpace(c.DBURL) - c.DBURL = "" - } - if isSQLiteURL(c.DBURL) { - _ = ensureSessionTable(c.DBURL) - } - if c.RedisURL != "" { - _ = openRedis(c.RedisURL) - } else { - closeRedis() - } - cfgMu.Lock() - cfg = c - cfgMu.Unlock() -} - -func openRedis(url string) error { - redisMu.Lock() - defer redisMu.Unlock() - if redisClient != nil && redisURL == url { - return nil - } - if redisClient != nil { - _ = redisClient.Close() - redisClient = nil - } - opts, err := redis.ParseURL(url) - if err != nil { - return err - } - redisClient = redis.NewClient(opts) - redisURL = url - return nil -} - -func closeRedis() { - redisMu.Lock() - defer redisMu.Unlock() - if redisClient != nil { - _ = redisClient.Close() - redisClient = nil - redisURL = "" - } -} - -// CloseRedis releases the Redis client (plugin shutdown / tests). -func CloseRedis() { - closeRedis() -} - -func redisKey(id string) string { - return "marqdo:session:" + id -} - -type redisBlob struct { - Data map[string]any `json:"data"` -} - -func loadRedis(id string) (map[string]any, bool) { - client := redisClientForRead() - if client == nil { - return nil, false - } - ctx := context.Background() - raw, err := client.Get(ctx, redisKey(id)).Result() - if err == redis.Nil || err != nil { - return nil, false - } - var blob redisBlob - if err := json.Unmarshal([]byte(raw), &blob); err != nil { - return nil, false - } - if blob.Data == nil { - blob.Data = map[string]any{} - } - return blob.Data, true -} - -func saveRedis(id string, ttl uint64, data map[string]any) bool { - client := redisClientForRead() - if client == nil { - return false - } - raw, err := json.Marshal(redisBlob{Data: cloneData(data)}) - if err != nil { - return false - } - ctx := context.Background() - if ttl == 0 { - ttl = defaultTTL - } - if err := client.SetEx(ctx, redisKey(id), raw, time.Duration(ttl)*time.Second).Err(); err != nil { - return false - } - return true -} - -func deleteRedis(id string) { - client := redisClientForRead() - if client == nil { - return - } - ctx := context.Background() - _, _ = client.Del(ctx, redisKey(id)).Result() -} - -func redisClientForRead() *redis.Client { - redisMu.Lock() - defer redisMu.Unlock() - return redisClient -} - -func usingRedis() bool { - c := getCfg() - return c.RedisURL != "" -} - -func getCfg() Config { - cfgMu.Lock() - defer cfgMu.Unlock() - return cfg -} - -// Reset clears in-memory sessions (tests / each listen). -func Reset(ttlSec uint64) { - ttl := ttlSec - if ttl == 0 { - ttl = defaultTTL - } - cfgMu.Lock() - cfg.TTLSec = ttl - if cfg.DBURL == "" { - // keep cookie_secure / db as-is when already configured - } - cfgMu.Unlock() - memMu.Lock() - mem = map[string]memRec{} - memTTL = ttl - memMu.Unlock() -} - -func ensureSessionTable(url string) error { - create := fmt.Sprintf(` -CREATE TABLE IF NOT EXISTS "%s" ( - id TEXT PRIMARY KEY, - expires_at INTEGER NOT NULL, - data TEXT NOT NULL -)`, sessionTable) - if _, err := db.Exec(url, create, nil); err != nil { - return err - } - idx := fmt.Sprintf(`CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON "%s"(expires_at)`, sessionTable) - _, err := db.Exec(url, idx, nil) - return err -} - -func pruneMem() { - now := nowSecs() - for id, rec := range mem { - if rec.exp <= now { - delete(mem, id) - } - } -} - -func pruneSQL(url string) { - now := int64(nowSecs()) - _, _ = db.Exec(url, fmt.Sprintf(`DELETE FROM "%s" WHERE expires_at <= ?`, sessionTable), []any{now}) -} - -func secureRandomID() (string, error) { - b := make([]byte, 32) - if _, err := rand.Read(b); err != nil { - return "", err - } - return hex.EncodeToString(b), nil -} - -func randomCSRF() (string, error) { - b := make([]byte, 24) - if _, err := rand.Read(b); err != nil { - return "", err - } - return hex.EncodeToString(b), nil -} - -func ensureCSRF(data map[string]any) (string, error) { - if v, ok := data[csrfKey].(string); ok && v != "" { - return v, nil - } - t, err := randomCSRF() - if err != nil { - return "", err - } - data[csrfKey] = t - return t, nil -} - -func loadSQL(url, id string) (uint64, map[string]any, bool) { - q, err := db.Query(url, fmt.Sprintf(`SELECT expires_at, data FROM "%s" WHERE id = ?`, sessionTable), []any{id}) - if err != nil { - return 0, nil, false - } - rows, _ := q["rows"].([]any) - if len(rows) == 0 { - return 0, nil, false - } - row, ok := rows[0].(map[string]any) - if !ok { - return 0, nil, false - } - exp := uint64(asInt64(row["expires_at"])) - dataS, _ := row["data"].(string) - data := map[string]any{} - _ = json.Unmarshal([]byte(dataS), &data) - if data == nil { - data = map[string]any{} - } - return exp, data, true -} - -func asInt64(v any) int64 { - switch t := v.(type) { - case int64: - return t - case float64: - return int64(t) - case int: - return int64(t) - default: - return 0 - } -} - -func saveSQL(url, id string, exp uint64, data map[string]any) error { - raw, err := json.Marshal(data) - if err != nil { - return err - } - _, err = db.Exec(url, fmt.Sprintf(` -INSERT INTO "%s" (id, expires_at, data) VALUES (?, ?, ?) -ON CONFLICT (id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data`, sessionTable), - []any{id, int64(exp), string(raw)}) - return err -} - -func deleteSQL(url, id string) { - _, _ = db.Exec(url, fmt.Sprintf(`DELETE FROM "%s" WHERE id = ?`, sessionTable), []any{id}) -} - -func touchExpiry(ttl uint64) uint64 { - return nowSecs() + ttl -} - -func getRecord(id string) (map[string]any, bool) { - c := getCfg() - now := nowSecs() - if usingRedis() { - data, ok := loadRedis(id) - if !ok { - return nil, false - } - return cloneData(data), true - } - if c.DBURL != "" { - pruneSQL(c.DBURL) - exp, data, ok := loadSQL(c.DBURL, id) - if !ok { - return nil, false - } - if exp <= now { - deleteSQL(c.DBURL, id) - return nil, false - } - return data, true - } - memMu.Lock() - defer memMu.Unlock() - pruneMem() - rec, ok := mem[id] - if !ok { - return nil, false - } - if rec.exp <= now { - delete(mem, id) - return nil, false - } - return cloneData(rec.data), true -} - -func putRecord(id string, exp uint64, data map[string]any) bool { - c := getCfg() - if usingRedis() { - ttl := c.TTLSec - if ttl == 0 { - ttl = defaultTTL - } - if exp > nowSecs() { - ttl = exp - nowSecs() - } - return saveRedis(id, ttl, data) - } - if c.DBURL != "" { - return saveSQL(c.DBURL, id, exp, data) == nil - } - memMu.Lock() - defer memMu.Unlock() - mem[id] = memRec{exp: exp, data: cloneData(data)} - return true -} - -// NewID creates a session and returns its id (optional ttl; 0 = configured default). -func NewID(ttlSec uint64) string { - c := getCfg() - ttl := ttlSec - if ttl == 0 { - ttl = c.TTLSec - } - if ttl == 0 { - ttl = defaultTTL - } - if ttlSec > 0 { - cfgMu.Lock() - cfg.TTLSec = ttl - cfgMu.Unlock() - } - id, err := secureRandomID() - if err != nil { - id = fmt.Sprintf("fallback-%d", nowSecs()) - } - data := map[string]any{} - _, _ = ensureCSRF(data) - exp := touchExpiry(ttl) - if usingRedis() { - ttl := ttl - _ = saveRedis(id, ttl, data) - } else if c.DBURL != "" { - pruneSQL(c.DBURL) - _ = saveSQL(c.DBURL, id, exp, data) - } else { - memMu.Lock() - memTTL = ttl - pruneMem() - mem[id] = memRec{exp: exp, data: data} - memMu.Unlock() - } - return id -} - -// New is ABI shape web_session_new → {"id":"…"}. -func New(ttlSec uint64) map[string]any { - return map[string]any{"id": NewID(ttlSec)} -} - -// Set stores a key (sliding expiry). ABI: {"ok":bool}. -func Set(id, key string, value any) map[string]any { - return map[string]any{"ok": SetValue(id, key, value)} -} - -// SetValue is the low-level setter. -func SetValue(id, key string, value any) bool { - data, ok := getRecord(id) - if !ok { - return false - } - data[key] = value - return putRecord(id, touchExpiry(getCfg().TTLSec), data) -} - -// Get is ABI shape: {"ok":true,"value":…} or {"ok":false}. -func Get(id, key string) map[string]any { - v, ok := GetValue(id, key) - if !ok { - return map[string]any{"ok": false} - } - return map[string]any{"ok": true, "value": v} -} - -// GetValue returns the value and whether it existed (sliding expiry on hit). -func GetValue(id, key string) (any, bool) { - data, ok := getRecord(id) - if !ok { - return nil, false - } - v, exists := data[key] - if !exists { - return nil, false - } - putRecord(id, touchExpiry(getCfg().TTLSec), data) - return v, true -} - -// Del removes a key. ABI: {"ok":bool}. -func Del(id, key string) map[string]any { - return map[string]any{"ok": DelKey(id, key)} -} - -// DelKey is the low-level deleter. -func DelKey(id, key string) bool { - data, ok := getRecord(id) - if !ok { - return false - } - if _, exists := data[key]; !exists { - return false - } - delete(data, key) - return putRecord(id, touchExpiry(getCfg().TTLSec), data) -} - -// Destroy removes a session. ABI: {"ok":bool}. -func Destroy(id string) map[string]any { - return map[string]any{"ok": DestroyID(id)} -} - -// DestroyID is the low-level destroyer. -func DestroyID(id string) bool { - c := getCfg() - if usingRedis() { - deleteRedis(id) - return true - } - if c.DBURL != "" { - deleteSQL(c.DBURL, id) - return true - } - memMu.Lock() - defer memMu.Unlock() - _, ok := mem[id] - if ok { - delete(mem, id) - } - return ok -} - -// CSRFFor returns (creating if needed) the CSRF token for a session. -func CSRFFor(id string) (string, bool) { - data, ok := getRecord(id) - if !ok { - return "", false - } - tok, err := ensureCSRF(data) - if err != nil { - return "", false - } - putRecord(id, touchExpiry(getCfg().TTLSec), data) - return tok, true -} - -// ValidateCSRF checks token against session. -func ValidateCSRF(id, token string) bool { - if token == "" { - return false - } - v, ok := GetValue(id, csrfKey) - if !ok { - return false - } - s, _ := v.(string) - return s == token -} - -// SessionCookie builds Set-Cookie for marqdo_sid. -// ttlSec 0 means the configured default (never Max-Age=0 — that clears cookies; -// use ClearCookie for logout). -func SessionCookie(id string, ttlSec uint64, secure bool) string { - if ttlSec == 0 { - ttlSec = getCfg().TTLSec - if ttlSec == 0 { - ttlSec = defaultTTL - } - } - s := fmt.Sprintf("marqdo_sid=%s; HttpOnly; Path=/; SameSite=Lax; Max-Age=%d", id, ttlSec) - if secure { - s += "; Secure" - } - return s -} - -// IssueCookie builds Set-Cookie using Configure'd TTL and CookieSecure. -func IssueCookie(id string) string { - c := getCfg() - return SessionCookie(id, c.TTLSec, c.CookieSecure) -} - -// ClearCookie is the Set-Cookie value that expires marqdo_sid immediately. -func ClearCookie() string { - return "marqdo_sid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax" -} - -// IDFromCookie parses marqdo_sid from a Cookie header. -func IDFromCookie(cookieHeader string) (string, bool) { - if cookieHeader == "" { - return "", false - } - for _, part := range strings.Split(cookieHeader, ";") { - p := strings.TrimSpace(part) - if v, ok := strings.CutPrefix(p, "marqdo_sid="); ok { - v = strings.Trim(v, `"`) - if v != "" { - return v, true - } - } - } - return "", false -} - -// ParseRolesCSV splits "admin,author" into lowercased roles. -func ParseRolesCSV(raw string) []string { - var out []string - for _, part := range strings.Split(raw, ",") { - part = strings.TrimSpace(part) - if part != "" { - out = append(out, strings.ToLower(part)) - } - } - return out -} - -// RoleFromCookie returns session role (visitor when anonymous or missing). -func RoleFromCookie(cookieHeader string) string { - sid, ok := IDFromCookie(cookieHeader) - if !ok { - return "visitor" - } - if v, ok := GetValue(sid, "role"); ok { - if s, ok := v.(string); ok && s != "" { - return strings.ToLower(s) - } - } - if v, ok := GetValue(sid, "username"); ok { - if s, ok := v.(string); ok && s != "" { - return "admin" - } - } - return "visitor" -} - -// UsernameFromCookie returns the session username or empty string. -func UsernameFromCookie(cookieHeader string) string { - sid, ok := IDFromCookie(cookieHeader) - if !ok { - return "" - } - if v, ok := GetValue(sid, "username"); ok { - if s, ok := v.(string); ok { - return s - } - } - return "" -} - -// RoleAllowed reports whether role is in allowed (empty allowed = all). -func RoleAllowed(role string, allowed []string) bool { - if len(allowed) == 0 { - return true - } - role = strings.ToLower(role) - for _, a := range allowed { - if strings.EqualFold(a, role) { - return true - } - } - return false -} - -// PermissionsFromCookie returns session permission codes (empty if anonymous). -func PermissionsFromCookie(cookieHeader string) []string { - sid, ok := IDFromCookie(cookieHeader) - if !ok { - return nil - } - return PermissionsFromSession(sid) -} - -// PermissionsFromSession reads the permissions CSV from a session id. -func PermissionsFromSession(sid string) []string { - if v, ok := GetValue(sid, "permissions"); ok { - if s, ok := v.(string); ok && s != "" { - return ParseRolesCSV(s) - } - } - return nil -} - -// SetPermissions stores permission codes on the session. -func SetPermissions(sid string, codes []string) { - SetValue(sid, "permissions", strings.Join(codes, ",")) -} - -// PermissionAllowed reports whether the session holds any of needed. -func PermissionAllowed(held, needed []string) bool { - if len(needed) == 0 { - return true - } - set := map[string]struct{}{} - for _, h := range held { - h = strings.ToLower(strings.TrimSpace(h)) - if h == "*" { - return true - } - if h != "" { - set[h] = struct{}{} - } - } - for _, n := range needed { - n = strings.ToLower(strings.TrimSpace(n)) - if _, ok := set[n]; ok { - return true - } - } - return false -} diff --git a/plugins/web/internal/session/session_test.go b/plugins/web/internal/session/session_test.go deleted file mode 100755 index 85de928..0000000 --- a/plugins/web/internal/session/session_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package session_test - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/alicebob/miniredis/v2" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/session" -) - -func TestSessionSetGetDel(t *testing.T) { - session.Configure(session.Config{TTLSec: 3600}) - session.Reset(3600) - id := session.NewID(0) - if id == "" { - t.Fatal("empty id") - } - if !session.SetValue(id, "username", "admin") { - t.Fatal("set") - } - v, ok := session.GetValue(id, "username") - if !ok || v != "admin" { - t.Fatalf("get=%v ok=%v", v, ok) - } - got := session.Get(id, "username") - if got["ok"] != true || got["value"] != "admin" { - t.Fatalf("Get ABI: %v", got) - } - if !session.DelKey(id, "username") { - t.Fatal("del") - } - if _, ok := session.GetValue(id, "username"); ok { - t.Fatal("del leftover") - } - if !session.DestroyID(id) { - t.Fatal("destroy") - } -} - -func TestCSRFAndCookie(t *testing.T) { - session.Reset(3600) - id := session.NewID(0) - tok, ok := session.CSRFFor(id) - if !ok || tok == "" { - t.Fatal("csrf") - } - if !session.ValidateCSRF(id, tok) { - t.Fatal("validate") - } - if session.ValidateCSRF(id, "bad") { - t.Fatal("bad csrf") - } - cookie := session.SessionCookie(id, 3600, false) - got, ok := session.IDFromCookie("theme=light; " + cookie) - if !ok || got != id { - t.Fatalf("cookie parse %q != %q", got, id) - } - zero := session.SessionCookie(id, 0, false) - if strings.Contains(zero, "Max-Age=0") { - t.Fatalf("ttl 0 must not clear cookie: %s", zero) - } - if !strings.Contains(session.ClearCookie(), "Max-Age=0") { - t.Fatal("ClearCookie should expire") - } -} - -func TestSessionPersistsInSQLite(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "persist.db") - url := "sqlite:" + path - db.ResetPool() - session.Configure(session.Config{DBURL: url, TTLSec: 3600}) - id := session.NewID(0) - if !session.SetValue(id, "theme", "dark") { - t.Fatal("set") - } - session.Configure(session.Config{DBURL: url, TTLSec: 3600}) - v, ok := session.GetValue(id, "theme") - if !ok || v != "dark" { - t.Fatalf("persist get=%v ok=%v", v, ok) - } - _ = os.RemoveAll(dir) -} - -func TestNewABI(t *testing.T) { - session.Reset(120) - out := session.New(120) - id, _ := out["id"].(string) - if id == "" { - t.Fatal(out) - } -} - -func TestConfigureRedisURLNoPanic(t *testing.T) { - session.CloseRedis() - session.Configure(session.Config{RedisURL: "redis://127.0.0.1:16379/0", TTLSec: 60}) - session.CloseRedis() -} - -func TestConfigureRedisViaDBURL(t *testing.T) { - session.CloseRedis() - session.Configure(session.Config{DBURL: "redis://127.0.0.1:16379/1", TTLSec: 60}) - session.CloseRedis() -} - -func TestSessionPersistsInRedis(t *testing.T) { - mr, err := miniredis.Run() - if err != nil { - t.Fatal(err) - } - defer mr.Close() - url := "redis://" + mr.Addr() + "/0" - session.CloseRedis() - session.Configure(session.Config{RedisURL: url, TTLSec: 3600}) - session.Reset(3600) - id := session.NewID(0) - if !session.SetValue(id, "lang", "zh") { - t.Fatal("set") - } - session.CloseRedis() - session.Configure(session.Config{RedisURL: url, TTLSec: 3600}) - v, ok := session.GetValue(id, "lang") - if !ok || v != "zh" { - t.Fatalf("persist get=%v ok=%v", v, ok) - } - session.CloseRedis() -} diff --git a/plugins/web/internal/sitemap/sitemap.go b/plugins/web/internal/sitemap/sitemap.go deleted file mode 100755 index fdd3ceb..0000000 --- a/plugins/web/internal/sitemap/sitemap.go +++ /dev/null @@ -1,147 +0,0 @@ -// Package sitemap builds sitemap.xml and robots.txt helpers (W7 / W-G7). -package sitemap - -import ( - "fmt" - "strconv" - "strings" -) - -func cellStr(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - default: - return fmt.Sprint(t) - } -} - -func xmlEscape(s string) string { - r := strings.NewReplacer( - "&", "&", - "<", "<", - ">", ">", - `"`, """, - "'", "'", - ) - return r.Replace(s) -} - -func rowsFromItems(items any) []map[string]any { - switch t := items.(type) { - case []any: - out := make([]map[string]any, 0, len(t)) - for _, row := range t { - switch r := row.(type) { - case map[string]any: - out = append(out, r) - case string: - out = append(out, map[string]any{"loc": r}) - default: - out = append(out, map[string]any{"loc": cellStr(r)}) - } - } - return out - case map[string]any: - locs, ok := firstArray(t, "loc", "路径", "path", "url") - if !ok { - return nil - } - out := make([]map[string]any, 0, len(locs)) - for i, loc := range locs { - obj := map[string]any{"loc": loc} - for k, v := range t { - if k == "loc" || k == "路径" || k == "path" || k == "url" { - continue - } - if col, ok := v.([]any); ok && i < len(col) { - obj[k] = col[i] - } - } - out = append(out, obj) - } - return out - default: - return nil - } -} - -func firstArray(m map[string]any, keys ...string) ([]any, bool) { - for _, k := range keys { - if v, ok := m[k]; ok { - if a, ok := v.([]any); ok { - return a, true - } - } - } - return nil, false -} - -// BuildSitemap builds a sitemap.xml document from rows. -func BuildSitemap(base string, items any) string { - base = strings.TrimRight(base, "/") - rows := rowsFromItems(items) - out := ` - -` - for _, obj := range rows { - locRaw := cellStr(first(obj, "loc", "url", "路径", "path")) - if locRaw == "" { - continue - } - loc := locRaw - if strings.HasPrefix(locRaw, "http://") || strings.HasPrefix(locRaw, "https://") { - loc = locRaw - } else if strings.HasPrefix(locRaw, "/") { - loc = base + locRaw - } else { - loc = base + "/" + locRaw - } - out += " \n" - out += fmt.Sprintf(" %s\n", xmlEscape(loc)) - if lm := cellStr(first(obj, "lastmod", "更新")); lm != "" { - out += fmt.Sprintf(" %s\n", xmlEscape(lm)) - } - if cf := cellStr(first(obj, "changefreq", "频率")); cf != "" { - out += fmt.Sprintf(" %s\n", xmlEscape(cf)) - } - if pr := cellStr(first(obj, "priority", "优先级")); pr != "" { - out += fmt.Sprintf(" %s\n", xmlEscape(pr)) - } - out += " \n" - } - out += "\n" - return out -} - -func first(m map[string]any, keys ...string) any { - for _, k := range keys { - if v, ok := m[k]; ok { - return v - } - } - return nil -} - -// BuildRobots returns a default robots.txt body with optional Sitemap line. -func BuildRobots(sitemapURL string) string { - out := "User-agent: *\nAllow: /\n" - if strings.TrimSpace(sitemapURL) != "" { - out += "Sitemap: " + strings.TrimSpace(sitemapURL) + "\n" - } - return out -} - -// SitemapJSON is the ABI helper returning {"xml":"…"}. -func SitemapJSON(base string, items any) map[string]any { - return map[string]any{"xml": BuildSitemap(base, items)} -} diff --git a/plugins/web/internal/sitemap/sitemap_test.go b/plugins/web/internal/sitemap/sitemap_test.go deleted file mode 100755 index 58519c0..0000000 --- a/plugins/web/internal/sitemap/sitemap_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package sitemap - -import ( - "strings" - "testing" -) - -func TestBuildSitemapRowTable(t *testing.T) { - items := []any{ - map[string]any{"loc": "/", "更新": "2026-08-28"}, - map[string]any{"loc": "/about", "更新": "2026-08-28"}, - } - xml := BuildSitemap("https://example.com", items) - if !strings.Contains(xml, "https://example.com/") { - t.Fatalf("missing home loc: %s", xml) - } - if !strings.Contains(xml, "https://example.com/about") { - t.Fatalf("missing about loc: %s", xml) - } - if !strings.Contains(xml, "2026-08-28") { - t.Fatalf("missing lastmod: %s", xml) - } -} - -func TestBuildRobotsWithSitemap(t *testing.T) { - body := BuildRobots("https://example.com/sitemap.xml") - if !strings.Contains(body, "User-agent: *") { - t.Fatalf("missing user-agent: %s", body) - } - if !strings.Contains(body, "Sitemap: https://example.com/sitemap.xml") { - t.Fatalf("missing sitemap line: %s", body) - } -} - -func TestSitemapJSONShape(t *testing.T) { - j := SitemapJSON("https://x.com", []any{map[string]any{"loc": "/a"}}) - if j["xml"] == nil || j["xml"] == "" { - t.Fatalf("expected xml: %v", j) - } -} diff --git a/plugins/web/internal/storage/storage.go b/plugins/web/internal/storage/storage.go deleted file mode 100755 index 004bf33..0000000 --- a/plugins/web/internal/storage/storage.go +++ /dev/null @@ -1,324 +0,0 @@ -// Package storage ports file: blob storage from the Rust web plugin (W-G6). -package storage - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "unicode/utf8" -) - -func isFile(url string) bool { - u := strings.ToLower(strings.TrimSpace(url)) - return strings.HasPrefix(u, "file:") || strings.HasPrefix(u, "file://") -} - -func isS3(url string) bool { - return strings.HasPrefix(strings.ToLower(strings.TrimSpace(url)), "s3://") -} - -func fileRoot(url string) (string, error) { - raw := strings.TrimSpace(url) - raw = strings.TrimPrefix(raw, "file://") - raw = strings.TrimPrefix(raw, "file:") - if raw == "" { - return "", nil - } - if err := os.MkdirAll(raw, 0o755); err != nil { - return "", fmt.Errorf("storage mkdir: %w", err) - } - return raw, nil -} - -func safeKey(key string) (string, error) { - k := strings.TrimPrefix(strings.TrimSpace(key), "/") - if k == "" { - return "", fmt.Errorf("storage key is empty") - } - if strings.Contains(k, "..") { - return "", fmt.Errorf("storage key must not contain `..`") - } - return strings.ReplaceAll(k, `\`, "/"), nil -} - -func pathFor(root, key string) (string, error) { - k, err := safeKey(key) - if err != nil { - return "", err - } - return filepath.Join(root, filepath.FromSlash(k)), nil -} - -func ctypePath(dest string) string { - return dest + ".ctype" -} - -// Open validates and describes a storage backend. -func Open(url string) (map[string]any, error) { - url = strings.TrimSpace(url) - if isFile(url) { - if _, err := fileRoot(url); err != nil { - return nil, err - } - return map[string]any{ - "_type": "storage", - "url": url, - "backend": "file", - }, nil - } - if isS3(url) { - rest := strings.TrimPrefix(url, "s3://") - rest = strings.TrimPrefix(rest, "S3://") - bucket := rest - if i := strings.IndexByte(bucket, '?'); i >= 0 { - bucket = bucket[:i] - } - if bucket == "" { - return nil, fmt.Errorf("s3 url missing bucket (s3://bucket?endpoint=…)") - } - return map[string]any{ - "_type": "storage", - "url": url, - "backend": "s3", - }, nil - } - return nil, fmt.Errorf("storage url must be `file:…` or `s3://bucket?…`, got `%s`", url) -} - -func loadBytes(body *string, path *string) ([]byte, error) { - if path != nil && *path != "" { - b, err := os.ReadFile(*path) - if err != nil { - return nil, fmt.Errorf("read path `%s`: %w", *path, err) - } - return b, nil - } - if body != nil { - return []byte(*body), nil - } - return nil, fmt.Errorf("storage.put needs `body` or `path`") -} - -// Put stores bytes from body or local path. -func Put(url, key string, body, path, contentType *string) (map[string]any, error) { - bytes, err := loadBytes(body, path) - if err != nil { - return nil, err - } - ct := "application/octet-stream" - if contentType != nil && strings.TrimSpace(*contentType) != "" { - ct = strings.TrimSpace(*contentType) - } - return PutBytes(url, key, bytes, ct) -} - -// PutBytes persists raw bytes (multipart upload / binary save). -func PutBytes(url, key string, data []byte, contentType string) (map[string]any, error) { - ct := strings.TrimSpace(contentType) - if ct == "" { - ct = "application/octet-stream" - } - if isFile(url) { - root, err := fileRoot(url) - if err != nil { - return nil, err - } - dest, err := pathFor(root, key) - if err != nil { - return nil, err - } - if parent := filepath.Dir(dest); parent != "" && parent != "." { - if err := os.MkdirAll(parent, 0o755); err != nil { - return nil, err - } - } - if err := os.WriteFile(dest, data, 0o644); err != nil { - return nil, err - } - _ = os.WriteFile(ctypePath(dest), []byte(ct), 0o644) - return map[string]any{ - "ok": true, - "key": key, - "size": float64(len(data)), - "content_type": ct, - }, nil - } - if isS3(url) { - return nil, fmt.Errorf("s3 put not implemented in Go plugin yet") - } - return nil, fmt.Errorf("unknown storage backend") -} - -// Get reads an object; JSON shape matches Rust gold. -func Get(url, key string) (map[string]any, error) { - if isFile(url) { - root, err := fileRoot(url) - if err != nil { - return nil, err - } - dest, err := pathFor(root, key) - if err != nil { - return nil, err - } - info, err := os.Stat(dest) - if err != nil || info.IsDir() { - return map[string]any{"ok": false}, nil - } - bytes, err := os.ReadFile(dest) - if err != nil { - return nil, err - } - ctBytes, err := os.ReadFile(ctypePath(dest)) - ct := "application/octet-stream" - if err == nil { - ct = string(ctBytes) - } - if utf8.Valid(bytes) { - s := string(bytes) - return map[string]any{ - "ok": true, - "key": key, - "body": s, - "content_type": ct, - "size": float64(len(s)), - }, nil - } - return map[string]any{ - "ok": true, - "key": key, - "path": dest, - "content_type": ct, - "size": float64(len(bytes)), - "binary": true, - }, nil - } - if isS3(url) { - return nil, fmt.Errorf("s3 get not implemented in Go plugin yet") - } - return nil, fmt.Errorf("unknown storage backend") -} - -// Delete removes an object if present. -func Delete(url, key string) (map[string]any, error) { - if isFile(url) { - root, err := fileRoot(url) - if err != nil { - return nil, err - } - dest, err := pathFor(root, key) - if err != nil { - return nil, err - } - info, err := os.Stat(dest) - ok := false - if err == nil && !info.IsDir() { - if err := os.Remove(dest); err != nil { - return nil, err - } - _ = os.Remove(ctypePath(dest)) - ok = true - } - return map[string]any{"ok": ok}, nil - } - if isS3(url) { - return nil, fmt.Errorf("s3 delete not implemented in Go plugin yet") - } - return nil, fmt.Errorf("unknown storage backend") -} - -// ReadBytes loads raw object bytes for HTTP download. -// Returns found=false when the object is missing. -func ReadBytes(url, key string) ([]byte, string, string, bool, error) { - k, err := safeKey(key) - if err != nil { - return nil, "", "", false, err - } - filename := k - if i := strings.LastIndexByte(k, '/'); i >= 0 && i < len(k)-1 { - filename = k[i+1:] - } - if filename == "" { - filename = "download" - } - if isFile(url) { - root, err := fileRoot(url) - if err != nil { - return nil, "", "", false, err - } - dest, err := pathFor(root, k) - if err != nil { - return nil, "", "", false, err - } - info, err := os.Stat(dest) - if err != nil || info.IsDir() { - return nil, "", "", false, nil - } - bytes, err := os.ReadFile(dest) - if err != nil { - return nil, "", "", false, err - } - ct := "application/octet-stream" - if ctBytes, err := os.ReadFile(ctypePath(dest)); err == nil { - ct = string(ctBytes) - } - return bytes, ct, filename, true, nil - } - if isS3(url) { - return nil, "", "", false, fmt.Errorf("s3 read not implemented in Go plugin yet") - } - return nil, "", "", false, fmt.Errorf("unknown storage backend") -} - -// List returns keys under optional prefix. -func List(url, prefix string) (map[string]any, error) { - prefix = strings.TrimPrefix(strings.TrimSpace(prefix), "/") - if isFile(url) { - root, err := fileRoot(url) - if err != nil { - return nil, err - } - var keys []string - if err := walkKeys(root, root, prefix, &keys); err != nil { - return nil, err - } - return map[string]any{ - "ok": true, - "keys": keys, - "count": float64(len(keys)), - }, nil - } - if isS3(url) { - return nil, fmt.Errorf("s3 list not implemented in Go plugin yet") - } - return nil, fmt.Errorf("unknown storage backend") -} - -func walkKeys(root, dir, prefix string, out *[]string) error { - entries, err := os.ReadDir(dir) - if err != nil { - return nil - } - for _, ent := range entries { - name := ent.Name() - if strings.HasSuffix(name, ".ctype") { - continue - } - path := filepath.Join(dir, name) - if ent.IsDir() { - if err := walkKeys(root, path, prefix, out); err != nil { - return err - } - continue - } - rel, err := filepath.Rel(root, path) - if err != nil { - return err - } - rel = filepath.ToSlash(rel) - if prefix == "" || strings.HasPrefix(rel, prefix) { - *out = append(*out, rel) - } - } - return nil -} diff --git a/plugins/web/internal/storage/storage_test.go b/plugins/web/internal/storage/storage_test.go deleted file mode 100755 index 21d023d..0000000 --- a/plugins/web/internal/storage/storage_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package storage - -import ( - "os" - "path/filepath" - "testing" -) - -func TestFilePutGetListDelete(t *testing.T) { - dir := t.TempDir() - url := "file:" + dir - if _, err := Open(url); err != nil { - t.Fatal(err) - } - body := "hi" - if _, err := Put(url, "a/hello.txt", &body, nil, strPtr("text/plain")); err != nil { - t.Fatal(err) - } - got, err := Get(url, "a/hello.txt") - if err != nil { - t.Fatal(err) - } - if got["ok"] != true || got["body"] != "hi" { - t.Fatalf("get: %#v", got) - } - ls, err := List(url, "a/") - if err != nil { - t.Fatal(err) - } - if ls["count"].(float64) != 1 { - t.Fatalf("list: %#v", ls) - } - if _, err := Delete(url, "a/hello.txt"); err != nil { - t.Fatal(err) - } - got2, _ := Get(url, "a/hello.txt") - if got2["ok"] != false { - t.Fatalf("expected missing after delete: %#v", got2) - } -} - -func TestPutFromPath(t *testing.T) { - dir := t.TempDir() - src := filepath.Join(dir, "src.txt") - if err := os.WriteFile(src, []byte("hello-upload"), 0o644); err != nil { - t.Fatal(err) - } - url := "file:" + filepath.Join(dir, "blobs") - p := src - if _, err := Put(url, "x.txt", nil, &p, strPtr("text/plain")); err != nil { - t.Fatal(err) - } - got, err := Get(url, "x.txt") - if err != nil { - t.Fatal(err) - } - if got["body"] != "hello-upload" { - t.Fatalf("body=%v", got["body"]) - } -} - -func strPtr(s string) *string { return &s } diff --git a/plugins/web/internal/style/style.go b/plugins/web/internal/style/style.go deleted file mode 100755 index 0285d88..0000000 --- a/plugins/web/internal/style/style.go +++ /dev/null @@ -1,63 +0,0 @@ -// Package style implements web_style (CSS from GFM style tables). -package style - -import ( - "strconv" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -// Style matches Rust web_style: args name + table + optional strict → CSS string. -func Style(args map[string]any) (string, error) { - name := "" - if v, ok := args["name"]; ok && v != nil { - name = cellStr(v) - } - var tbl any = []any{} - if v, ok := args["table"]; ok && v != nil { - tbl = v - } - strict := false - for _, k := range []string{"strict", "strict_css_cells", "严格"} { - if v, ok := args[k]; ok { - strict = boolishStrict(v) - break - } - } - return table.AsCSSNamedChecked(name, tbl, strict) -} - -func cellStr(v any) string { - switch t := v.(type) { - case string: - return t - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - case bool: - return strconv.FormatBool(t) - default: - return "" - } -} - -func boolishStrict(v any) bool { - switch t := v.(type) { - case bool: - return t - case float64: - return int64(t) != 0 - case string: - s := strings.TrimSpace(t) - switch s { - case "1", "true", "True", "yes", "on", "真", "是": - return true - } - return false - default: - return false - } -} diff --git a/plugins/web/internal/style/style_test.go b/plugins/web/internal/style/style_test.go deleted file mode 100755 index 89fd208..0000000 --- a/plugins/web/internal/style/style_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package style_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/style" -) - -func TestStyleSimple(t *testing.T) { - css, err := style.Style(map[string]any{ - "name": "card", - "table": []any{ - map[string]any{"选择器": ".card", "属性": "color", "值": "navy"}, - }, - }) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(css, ".card {") || !strings.Contains(css, "color: navy;") { - t.Fatalf("%q", css) - } -} - -func TestStyleStrictKeepsQuotedSlash(t *testing.T) { - css, err := style.Style(map[string]any{ - "name": "t", - "strict": true, - "table": []any{ - map[string]any{"选择器": ".box", "属性": "grid-column", "值": "1 / 5"}, - }, - }) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(css, "1 / 5") { - t.Fatalf("missing quoted value: %q", css) - } -} - -func TestStyleStrictAllowsNumeric(t *testing.T) { - css, err := style.Style(map[string]any{ - "name": "x", - "strict": true, - "table": []any{ - map[string]any{"选择器": ".x", "属性": "z-index", "值": float64(20)}, - map[string]any{"选择器": ".y", "属性": "opacity", "值": float64(0.5)}, - map[string]any{"选择器": ".z", "属性": "font-weight", "值": float64(700)}, - }, - }) - if err != nil { - t.Fatalf("numeric CSS must not be suspicious: %v", err) - } - if !strings.Contains(css, "z-index: 20") || !strings.Contains(css, "opacity: 0.5") { - t.Fatalf("%q", css) - } -} - -func TestStyleStrictRejectsBoolean(t *testing.T) { - _, err := style.Style(map[string]any{ - "name": "x", - "strict": true, - "table": []any{ - map[string]any{"选择器": ".x", "属性": "display", "值": true}, - }, - }) - if err == nil || !strings.Contains(err.Error(), "suspicious") { - t.Fatalf("err=%v", err) - } -} diff --git a/plugins/web/internal/table/table.go b/plugins/web/internal/table/table.go deleted file mode 100755 index 5687f32..0000000 --- a/plugins/web/internal/table/table.go +++ /dev/null @@ -1,1131 +0,0 @@ -// Package table ports GFM table helpers + site path parsing from the Rust web plugin. -package table - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -var ( - fieldKeys = []string{"字段", "name", "列", "column"} - typeKeys = []string{"类型", "type"} - nullKeys = []string{"可空", "null", "nullable"} - frontKeys = []string{"属性", "前端变量", "front", "field"} - backKeys = []string{"值", "后端数据库", "back", "db"} - cssKeys = []string{"样式", "绑定css样式", "css", "class", "style"} - srcKeys = []string{"组件", "导入的页面", "src", "page"} - styleKeys = []string{"样式", "style", "class"} - propKeys = []string{"属性", "property", "prop", "名", "name"} - valKeys = []string{"值", "value"} - selKeys = []string{"选择器", "selector", "sel"} - mediaKeys = []string{"媒体", "media", "mq", "@media"} - whenKeys = []string{"当", "when", "if", "条件", "visible"} - navLabelKeys = []string{"标签", "label", "title", "text", "名"} - navHrefKeys = []string{"链接", "href", "url", "path", "地址"} - uniqueKeys = []string{"唯一", "unique", "uniq"} - indexKeys = []string{"索引", "index", "idx"} - fkKeys = []string{"外键", "fk", "references", "ref", "引用"} - metaKeyKeys = []string{"键", "key", "name"} - metaValKeys = []string{"值", "value"} -) - -// NormalizeRef strips surrounding backticks from ref cells (paired `…`). -func NormalizeRef(s string) string { - s = strings.TrimSpace(s) - var out strings.Builder - out.Grow(len(s)) - rest := s - for { - start := strings.IndexByte(rest, '`') - if start < 0 { - out.WriteString(rest) - return out.String() - } - out.WriteString(rest[:start]) - rest = rest[start+1:] - end := strings.IndexByte(rest, '`') - if end < 0 { - out.WriteByte('`') - out.WriteString(rest) - return out.String() - } - out.WriteString(rest[:end]) - rest = rest[end+1:] - } -} - -func pick(m map[string]any, keys []string) (any, bool) { - for _, k := range keys { - if v, ok := m[k]; ok { - return v, true - } - } - return nil, false -} - -func cellStr(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case bool: - return strconv.FormatBool(t) - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10) - } - return strconv.FormatFloat(t, 'f', -1, 64) - case int: - return strconv.Itoa(t) - case int64: - return strconv.FormatInt(t, 10) - default: - return fmt.Sprint(t) - } -} - -func asStrList(v any) []string { - switch t := v.(type) { - case nil: - return nil - case []any: - out := make([]string, len(t)) - for i, x := range t { - out[i] = cellStr(x) - } - return out - default: - return []string{cellStr(v)} - } -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - s := strings.TrimSpace(t) - switch s { - case "1", "true", "True", "yes", "是", "可": - return true - } - return false - case float64: - return int64(t) != 0 - case int: - return t != 0 - case int64: - return t != 0 - default: - return false - } -} - -func asMap(v any) (map[string]any, bool) { - m, ok := v.(map[string]any) - return m, ok -} - -func asArray(v any) ([]any, bool) { - a, ok := v.([]any) - return a, ok -} - -// AsFields converts a schema table → [{name,type,nullable,unique,index,fk}, …]. -func AsFields(table any) any { - switch t := table.(type) { - case []any: - out := make([]any, 0, len(t)) - for _, row := range t { - m, ok := asMap(row) - if !ok { - continue - } - name := "" - if v, ok := pick(m, fieldKeys); ok { - name = cellStr(v) - } - if name == "" { - continue - } - ty := "text" - if v, ok := pick(m, typeKeys); ok { - ty = cellStr(v) - } - nullable := true - if v, ok := pick(m, nullKeys); ok { - nullable = boolish(v) - } - unique := false - if v, ok := pick(m, uniqueKeys); ok { - unique = boolish(v) - } - index := false - if v, ok := pick(m, indexKeys); ok { - index = boolish(v) - } - fk := "" - if v, ok := pick(m, fkKeys); ok { - fk = cellStr(v) - } - out = append(out, map[string]any{ - "name": name, - "type": ty, - "nullable": nullable, - "unique": unique, - "index": index, - "fk": fk, - }) - } - return out - case map[string]any: - names := []string{} - if v, ok := pick(t, fieldKeys); ok { - names = asStrList(v) - } - types := []string{} - if v, ok := pick(t, typeKeys); ok { - types = asStrList(v) - } - nulls := []string{} - if v, ok := pick(t, nullKeys); ok { - nulls = asStrList(v) - } - uniques := []string{} - if v, ok := pick(t, uniqueKeys); ok { - uniques = asStrList(v) - } - indexes := []string{} - if v, ok := pick(t, indexKeys); ok { - indexes = asStrList(v) - } - fks := []string{} - if v, ok := pick(t, fkKeys); ok { - fks = asStrList(v) - } - out := make([]any, 0, len(names)) - for i, name := range names { - if name == "" { - continue - } - ty := "text" - if i < len(types) { - ty = types[i] - } - nullable := true - if i < len(nulls) { - nullable = boolish(nulls[i]) - } - unique := false - if i < len(uniques) { - unique = boolish(uniques[i]) - } - index := false - if i < len(indexes) { - index = boolish(indexes[i]) - } - fk := "" - if i < len(fks) { - fk = fks[i] - } - out = append(out, map[string]any{ - "name": name, - "type": ty, - "nullable": nullable, - "unique": unique, - "index": index, - "fk": fk, - }) - } - return out - default: - return []any{} - } -} - -// AsRows converts a seed / row table → list of maps. -func AsRows(table any) any { - switch t := table.(type) { - case []any: - out := make([]any, len(t)) - copy(out, t) - return out - case map[string]any: - keys := make([]string, 0, len(t)) - for k := range t { - keys = append(keys, k) - } - var rowKey string - found := false - for _, k := range []string{"@", "行", "row"} { - if _, ok := t[k]; ok { - rowKey = k - found = true - break - } - } - if found { - n := len(asStrList(t[rowKey])) - out := make([]any, 0, n) - for i := 0; i < n; i++ { - row := map[string]any{} - for _, k := range keys { - if k == rowKey { - continue - } - list := asStrList(t[k]) - val := "" - if i < len(list) { - val = list[i] - } - row[k] = val - } - ids := asStrList(t[rowKey]) - if i < len(ids) && ids[i] != "" { - row["id"] = ids[i] - } - out = append(out, row) - } - return out - } - // Columnar GFM table: each value is a same-length array → zip into rows. - colLens := make([]int, 0, len(t)) - allArrays := len(t) > 0 - for _, v := range t { - a, ok := v.([]any) - if !ok { - allArrays = false - break - } - colLens = append(colLens, len(a)) - } - if allArrays { - n := 0 - for _, l := range colLens { - if l > n { - n = l - } - } - okLens := n > 0 - for _, l := range colLens { - if l != n && l != 0 { - okLens = false - break - } - } - if okLens { - out := make([]any, 0, n) - for i := 0; i < n; i++ { - row := map[string]any{} - for k, v := range t { - a := v.([]any) - if i < len(a) { - row[k] = a[i] - } else { - row[k] = nil - } - } - out = append(out, row) - } - return out - } - } - // single map - cp := map[string]any{} - for k, v := range t { - cp[k] = v - } - return []any{cp} - default: - return []any{} - } -} - -// AsBind converts a bind table → [{front,back,css,media,when}, …]. -func AsBind(table any) any { - switch t := table.(type) { - case []any: - out := make([]any, 0, len(t)) - for _, row := range t { - m, ok := asMap(row) - if !ok { - continue - } - front, back, css, media, when := "", "", "", "", "" - if v, ok := pick(m, frontKeys); ok { - front = NormalizeRef(cellStr(v)) - } - if v, ok := pick(m, backKeys); ok { - back = NormalizeRef(cellStr(v)) - } - if v, ok := pick(m, cssKeys); ok { - css = NormalizeRef(cellStr(v)) - } - if v, ok := pick(m, mediaKeys); ok { - media = NormalizeRef(cellStr(v)) - } - if v, ok := pick(m, whenKeys); ok { - when = NormalizeRef(cellStr(v)) - } - if front != "" || back != "" { - out = append(out, map[string]any{ - "front": front, - "back": back, - "css": css, - "media": media, - "when": when, - }) - } - } - return out - case map[string]any: - fronts, backs, csses, medias, whens := []string{}, []string{}, []string{}, []string{}, []string{} - if v, ok := pick(t, frontKeys); ok { - fronts = asStrList(v) - } - if v, ok := pick(t, backKeys); ok { - backs = asStrList(v) - } - if v, ok := pick(t, cssKeys); ok { - csses = asStrList(v) - } - if v, ok := pick(t, mediaKeys); ok { - medias = asStrList(v) - } - if v, ok := pick(t, whenKeys); ok { - whens = asStrList(v) - } - n := len(fronts) - if len(backs) > n { - n = len(backs) - } - out := make([]any, 0, n) - for i := 0; i < n; i++ { - front, back, css, media, when := "", "", "", "", "" - if i < len(fronts) { - front = NormalizeRef(fronts[i]) - } - if i < len(backs) { - back = NormalizeRef(backs[i]) - } - if i < len(csses) { - css = NormalizeRef(csses[i]) - } - if i < len(medias) { - media = NormalizeRef(medias[i]) - } - if i < len(whens) { - when = NormalizeRef(whens[i]) - } - if front != "" || back != "" { - out = append(out, map[string]any{ - "front": front, - "back": back, - "css": css, - "media": media, - "when": when, - }) - } - } - return out - default: - return []any{} - } -} - -// AsNavRows converts a nav / link table → row maps with label/href. -func AsNavRows(table any) []map[string]any { - binds := AsBind(table) - if arr, ok := binds.([]any); ok && len(arr) > 0 { - out := make([]map[string]any, 0, len(arr)) - for _, v := range arr { - if m, ok := asMap(v); ok { - out = append(out, m) - } - } - return out - } - rows := AsRows(table) - arr, _ := rows.([]any) - out := make([]map[string]any, 0, len(arr)) - for _, v := range arr { - if m, ok := asMap(v); ok { - out = append(out, m) - } - } - return out -} - -// NavLabelHref picks label/href from a nav row. -func NavLabelHref(m map[string]any) (string, string) { - label := "" - if v, ok := pick(m, navLabelKeys); ok { - label = NormalizeRef(cellStr(v)) - } else if v, ok := m["front"]; ok { - label = NormalizeRef(cellStr(v)) - } - href := "#" - if v, ok := pick(m, navHrefKeys); ok { - s := NormalizeRef(cellStr(v)) - if s != "" { - href = s - } - } else if v, ok := m["back"]; ok { - s := NormalizeRef(cellStr(v)) - if s != "" { - href = s - } - } - return label, href -} - -// NavMediaWhenClass picks media/when/class from a nav row. -func NavMediaWhenClass(m map[string]any) (string, string, string) { - media := "" - if v, ok := pick(m, mediaKeys); ok { - media = NormalizeRef(cellStr(v)) - } else if v, ok := m["media"]; ok { - media = NormalizeRef(cellStr(v)) - } - when := "" - if v, ok := pick(m, whenKeys); ok { - when = NormalizeRef(cellStr(v)) - } else if v, ok := m["when"]; ok { - when = NormalizeRef(cellStr(v)) - } - class := "" - if v, ok := pick(m, cssKeys); ok { - class = NormalizeRef(cellStr(v)) - } else if v, ok := m["css"]; ok { - class = NormalizeRef(cellStr(v)) - } - return media, when, class -} - -// AsCompose converts a page table → [{src,style,slot}, …]. -func AsCompose(table any) any { - switch t := table.(type) { - case map[string]any: - srcs, styles := []string{}, []string{} - if v, ok := pick(t, srcKeys); ok { - srcs = asStrList(v) - } - if v, ok := pick(t, styleKeys); ok { - styles = asStrList(v) - } - out := make([]any, 0, len(srcs)) - for i, srcRaw := range srcs { - src := NormalizeRef(srcRaw) - if src == "" { - continue - } - style := "" - if i < len(styles) { - style = NormalizeRef(styles[i]) - } - out = append(out, map[string]any{ - "src": src, - "style": style, - "slot": inferSlot(src), - }) - } - return out - case []any: - out := make([]any, 0, len(t)) - for _, row := range t { - m, ok := asMap(row) - if !ok { - continue - } - src := "" - if v, ok := pick(m, srcKeys); ok { - src = NormalizeRef(cellStr(v)) - } - if src == "" { - continue - } - style := "" - if v, ok := pick(m, styleKeys); ok { - style = NormalizeRef(cellStr(v)) - } - out = append(out, map[string]any{ - "src": src, - "style": style, - "slot": inferSlot(src), - }) - } - return out - default: - return []any{} - } -} - -func inferSlot(src string) string { - base := src - if i := strings.LastIndex(src, "."); i >= 0 { - base = src[i+1:] - } - switch base { - case "nav", "links", "导航": - return "nav" - case "side", "sidebar", "侧栏": - return "sidebar" - case "foot", "footer", "页脚": - return "footer" - default: - return base - } -} - -// NormalizeSlot maps author slot names to canonical slots. -func NormalizeSlot(name string) string { - switch name { - case "nav", "links", "导航": - return "nav" - case "side", "sidebar", "侧栏": - return "sidebar" - case "foot", "footer", "页脚": - return "footer" - case "main", "index", "", "主体": - return "main" - default: - return name - } -} - -// AsCSSNamed converts a style table → CSS text (non-strict). -func AsCSSNamed(name string, table any) string { - s, _ := AsCSSNamedChecked(name, table, false) - return s -} - -// AsCSSNamedChecked is like AsCSSNamed; when strict, reject numeric/bool CSS value cells. -func AsCSSNamedChecked(name string, table any, strict bool) (string, error) { - name = NormalizeRef(name) - if name == "" { - return "", nil - } - var out strings.Builder - switch t := table.(type) { - case map[string]any: - sels, props, vals, medias := []string{}, []string{}, []string{}, []string{} - if v, ok := pick(t, selKeys); ok { - sels = asStrList(v) - } - if v, ok := pick(t, propKeys); ok { - props = asStrList(v) - } - var valsRaw any - if v, ok := pick(t, valKeys); ok { - valsRaw = v - vals = asStrList(v) - } - if v, ok := pick(t, mediaKeys); ok { - medias = asStrList(v) - } - n := len(props) - if len(sels) > n { - n = len(sels) - } - if len(vals) > n { - n = len(vals) - } - if n == 0 { - return "", nil - } - if valsRaw != nil { - if err := checkCSSValueCells(valsRaw, props, strict); err != nil { - return "", err - } - } - rows := make([][4]string, n) - for i := 0; i < n; i++ { - media, sel, p, v := "", "", "", "" - if i < len(medias) { - media = medias[i] - } - if i < len(sels) { - sel = sels[i] - } - if i < len(props) { - p = props[i] - } - if i < len(vals) { - v = vals[i] - } - rows[i] = [4]string{media, sel, p, v} - } - emitCSSRows(rows, name, &out) - case []any: - collected := make([][4]string, 0, len(t)) - for _, row := range t { - m, ok := asMap(row) - if !ok { - continue - } - prop := "" - if v, ok := pick(m, propKeys); ok { - prop = cellStr(v) - } - if v, ok := pick(m, valKeys); ok { - if err := noteCSSValueCell(prop, v, strict); err != nil { - return "", err - } - } - media, sel, val := "", "", "" - if v, ok := pick(m, mediaKeys); ok { - media = cellStr(v) - } - if v, ok := pick(m, selKeys); ok { - sel = cellStr(v) - } - if v, ok := pick(m, valKeys); ok { - val = cellStr(v) - } - collected = append(collected, [4]string{media, sel, prop, val}) - } - emitCSSRows(collected, name, &out) - } - return out.String(), nil -} - -func cssValueSuspicious(v any) string { - // Numbers are normal CSS (z-index, opacity, font-weight, unitless 0). - // Do not treat Markup-evaluated ints/floats as "bare `/` division". - switch v.(type) { - case bool: - return "boolean CSS value (quote the cell if intentional)" - default: - return "" - } -} - -func noteCSSValueCell(prop string, val any, strict bool) error { - why := cssValueSuspicious(val) - if why == "" { - return nil - } - p := strings.TrimSpace(prop) - if p == "" { - p = "(value)" - } - msg := fmt.Sprintf("ext/web style: suspicious cell for `%s`: %s", p, why) - if strict { - return fmt.Errorf("%s", msg) - } - fmt.Fprintf(os.Stderr, "warning: %s\n", msg) - return nil -} - -func checkCSSValueCells(vals any, props []string, strict bool) error { - switch t := vals.(type) { - case []any: - for i, v := range t { - prop := "" - if i < len(props) { - prop = props[i] - } - if err := noteCSSValueCell(prop, v, strict); err != nil { - return err - } - } - default: - prop := "" - if len(props) > 0 { - prop = props[0] - } - return noteCSSValueCell(prop, vals, strict) - } - return nil -} - -func parseKeyframesSel(sel string) (anim string, stop *string, ok bool) { - t := strings.TrimSpace(sel) - if len(t) < 10 || !strings.EqualFold(t[:10], "@keyframes") { - return "", nil, false - } - rest := strings.TrimSpace(t[10:]) - if rest == "" { - return "", nil, false - } - parts := strings.Fields(rest) - if len(parts) == 0 { - return "", nil, false - } - anim = parts[0] - if len(parts) > 1 { - s := parts[1] - stop = &s - } - return anim, stop, true -} - -func isKeyframeStop(s string) bool { - t := strings.TrimSpace(s) - if t == "" { - return false - } - if strings.EqualFold(t, "from") || strings.EqualFold(t, "to") { - return true - } - stripped := strings.TrimSuffix(t, "%") - if stripped == "" || !strings.HasSuffix(t, "%") { - return false - } - for _, c := range stripped { - if !(c >= '0' && c <= '9' || c == '.') { - return false - } - } - return true -} - -func keyframeDeclLines(cssProp, value string) []string { - v := strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(value), ";")) - if v == "" { - return nil - } - if strings.Contains(v, ":") { - parts := strings.Split(v, ";") - out := make([]string, 0, len(parts)) - for _, p := range parts { - p = strings.TrimSpace(p) - if p == "" { - continue - } - out = append(out, " "+p+";") - } - return out - } - if cssProp != "" && !isKeyframeStop(cssProp) { - return []string{fmt.Sprintf(" %s: %s;", cssProp, v)} - } - return []string{" " + v + ";"} -} - -type kfStop struct { - stop string - decls []string -} - -type kfAnim struct { - anim string - stops []kfStop -} - -func pushKeyframe(groups *[]kfAnim, anim, stop string, decls []string) { - if anim == "" || stop == "" || len(decls) == 0 { - return - } - var animGroup *[]kfStop - for i := range *groups { - if (*groups)[i].anim == anim { - animGroup = &(*groups)[i].stops - break - } - } - if animGroup == nil { - *groups = append(*groups, kfAnim{anim: anim}) - animGroup = &(*groups)[len(*groups)-1].stops - } - for i := range *animGroup { - if (*animGroup)[i].stop == stop { - (*animGroup)[i].decls = append((*animGroup)[i].decls, decls...) - return - } - } - *animGroup = append(*animGroup, kfStop{stop: stop, decls: decls}) -} - -type ruleGroup struct { - sel string - decls []string -} - -type mediaGroup struct { - media string - rules []ruleGroup -} - -func pushRule(groups *[]ruleGroup, sel, decl string) { - if sel == "" { - return - } - for i := range *groups { - if (*groups)[i].sel == sel { - (*groups)[i].decls = append((*groups)[i].decls, decl) - return - } - } - *groups = append(*groups, ruleGroup{sel: sel, decls: []string{decl}}) -} - -func emitCSSRows(rows [][4]string, className string, out *strings.Builder) { - var byMedia []mediaGroup - var byKeyframes []kfAnim - var plain []string - - for _, row := range rows { - media := strings.TrimSpace(row[0]) - sel := strings.TrimSpace(row[1]) - p := strings.TrimSpace(row[2]) - v := strings.TrimSpace(row[3]) - - if anim, stopInSel, ok := parseKeyframesSel(sel); ok { - stopFromSel := stopInSel != nil - var stop, propForDecl string - if stopInSel != nil { - stop = *stopInSel - propForDecl = p - } else { - if !isKeyframeStop(p) { - continue - } - stop = p - propForDecl = "" - } - var decls []string - if stopFromSel { - decls = keyframeDeclLines(propForDecl, v) - } else { - decls = keyframeDeclLines("", v) - } - if len(decls) == 0 && v != "" && propForDecl != "" { - decls = keyframeDeclLines(propForDecl, v) - } - pushKeyframe(&byKeyframes, anim, stop, decls) - continue - } - - if p == "" { - continue - } - decl := fmt.Sprintf(" %s: %s;", p, v) - if media != "" { - var group *[]ruleGroup - for i := range byMedia { - if byMedia[i].media == media { - group = &byMedia[i].rules - break - } - } - if group == nil { - byMedia = append(byMedia, mediaGroup{media: media}) - group = &byMedia[len(byMedia)-1].rules - } - pushRule(group, sel, decl) - } else if sel != "" { - var group *[]ruleGroup - for i := range byMedia { - if byMedia[i].media == "" { - group = &byMedia[i].rules - break - } - } - if group == nil { - byMedia = append(byMedia, mediaGroup{media: ""}) - group = &byMedia[len(byMedia)-1].rules - } - pushRule(group, sel, decl) - } else { - plain = append(plain, decl) - } - } - - for _, mg := range byMedia { - if mg.media == "" { - for _, r := range mg.rules { - out.WriteString(fmt.Sprintf("%s {\n%s\n}\n", r.sel, strings.Join(r.decls, "\n"))) - } - } else { - inners := make([]string, 0, len(mg.rules)) - for _, r := range mg.rules { - inners = append(inners, fmt.Sprintf("%s {\n%s\n}", r.sel, strings.Join(r.decls, "\n"))) - } - out.WriteString(fmt.Sprintf("@media %s {\n%s\n}\n", mg.media, strings.Join(inners, "\n"))) - } - } - for _, kf := range byKeyframes { - out.WriteString(fmt.Sprintf("@keyframes %s {\n", kf.anim)) - for _, st := range kf.stops { - out.WriteString(fmt.Sprintf(" %s {\n", st.stop)) - out.WriteString(strings.Join(st.decls, "\n")) - out.WriteByte('\n') - out.WriteString(" }\n") - } - out.WriteString("}\n") - } - if len(plain) > 0 { - out.WriteString(fmt.Sprintf(".%s {\n%s\n}\n", className, strings.Join(plain, "\n"))) - } -} - -// SitePathKind distinguishes parse_site_path variants. -type SitePathKind int - -const ( - SitePathPlain SitePathKind = iota - SitePathLibMember - SitePathDbField -) - -// SitePath is the result of ParseSitePath. -type SitePath struct { - Kind SitePathKind - Lib string // LibMember - Member string // LibMember - Table string // DbField - Field string // DbField - Plain string // Plain -} - -// ParseSitePath parses `lib.member`, `x.table.field`, or plain refs. -func ParseSitePath(raw string) SitePath { - s := NormalizeRef(raw) - if s == "" { - return SitePath{Kind: SitePathPlain, Plain: ""} - } - parts := make([]string, 0) - for _, p := range strings.Split(s, ".") { - if p != "" { - parts = append(parts, p) - } - } - switch len(parts) { - case 2: - return SitePath{Kind: SitePathLibMember, Lib: parts[0], Member: parts[1]} - case 3: - return SitePath{Kind: SitePathDbField, Table: parts[1], Field: parts[2]} - default: - return SitePath{Kind: SitePathPlain, Plain: s} - } -} - -// BindTableName returns the single DB table referenced by binds, or "" if none/ambiguous. -func BindTableName(binds []any) (string, bool) { - var found string - have := false - for _, b := range binds { - m, ok := asMap(b) - if !ok { - continue - } - back, _ := m["back"].(string) - sp := ParseSitePath(back) - if sp.Kind == SitePathDbField { - if !have { - found = sp.Table - have = true - } else if found != sp.Table { - return "", false - } - } else if strings.Contains(back, ".") { - p := strings.SplitN(back, ".", 2) - if len(p) == 2 && p[0] != "" && p[1] != "" { - t := p[0] - if !have { - found = t - have = true - } else if found != t { - return "", false - } - } - } - } - return found, have -} - -// ProjectRows projects DB rows through bind front/back/css mappings. -func ProjectRows(binds []any, rows []any) any { - out := make([]any, 0, len(rows)) - for _, row := range rows { - obj, _ := asMap(row) - if obj == nil { - obj = map[string]any{} - } - m := map[string]any{} - css := map[string]any{} - for _, b := range binds { - bm, ok := asMap(b) - if !ok { - continue - } - front, _ := bm["front"].(string) - back, _ := bm["back"].(string) - class, _ := bm["css"].(string) - var col string - switch sp := ParseSitePath(back); sp.Kind { - case SitePathDbField: - col = sp.Field - case SitePathLibMember: - col = sp.Member - case SitePathPlain: - if strings.Contains(sp.Plain, ".") { - parts := strings.Split(sp.Plain, ".") - col = parts[len(parts)-1] - } else { - col = sp.Plain - } - } - if v, ok := obj[col]; ok { - m[front] = v - } else if v, ok := obj[front]; ok { - m[front] = v - } - if class != "" { - css[front] = class - } - } - if id, ok := obj["id"]; ok { - m["id"] = id - } - if len(css) > 0 { - m["_css"] = css - } - out = append(out, m) - } - return out -} - -// AsMetaMap converts an SEO / OpenGraph meta table → map. -func AsMetaMap(table any) map[string]any { - out := map[string]any{} - switch t := table.(type) { - case []any: - for _, row := range t { - obj, ok := asMap(row) - if !ok { - continue - } - key := "" - for _, k := range metaKeyKeys { - if v, ok := obj[k]; ok { - key = NormalizeRef(metaText(v)) - break - } - } - val := "" - for _, k := range metaValKeys { - if v, ok := obj[k]; ok { - val = metaText(v) - break - } - } - if key != "" { - out[key] = val - } - } - case map[string]any: - for k, v := range t { - out[k] = metaText(v) - } - } - return out -} - -func metaText(v any) string { - return cellStr(v) -} diff --git a/plugins/web/internal/table/table_test.go b/plugins/web/internal/table/table_test.go deleted file mode 100755 index 1b8c3ab..0000000 --- a/plugins/web/internal/table/table_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package table_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/table" -) - -func TestNormalizeRefBackticks(t *testing.T) { - cases := []struct { - in, want string - }{ - {"`foo`", "foo"}, - {" `a.b` ", "a.b"}, - {"plain", "plain"}, - {"`a` and `b`", "a and b"}, - {"`unclosed", "`unclosed"}, - {"", ""}, - } - for _, c := range cases { - got := table.NormalizeRef(c.in) - if got != c.want { - t.Errorf("NormalizeRef(%q)=%q want %q", c.in, got, c.want) - } - } -} - -func TestAsBindChineseHeaders(t *testing.T) { - tbl := map[string]any{ - "属性": []any{"title", "body"}, - "值": []any{"posts.title", "posts.body"}, - "样式": []any{"`hero`", ""}, - } - got := table.AsBind(tbl) - arr, ok := got.([]any) - if !ok || len(arr) != 2 { - t.Fatalf("AsBind=%v", got) - } - r0 := arr[0].(map[string]any) - if r0["front"] != "title" || r0["back"] != "posts.title" || r0["css"] != "hero" { - t.Fatalf("row0=%v", r0) - } - r1 := arr[1].(map[string]any) - if r1["front"] != "body" || r1["back"] != "posts.body" || r1["css"] != "" { - t.Fatalf("row1=%v", r1) - } -} - -func TestAsCSSNamedSimpleSelector(t *testing.T) { - tbl := []any{ - map[string]any{"选择器": ".card", "属性": "color", "值": "red"}, - map[string]any{"选择器": ".card", "属性": "padding", "值": "1rem"}, - } - css := table.AsCSSNamed("card", tbl) - if !strings.Contains(css, ".card {") { - t.Fatalf("missing selector: %q", css) - } - if !strings.Contains(css, "color: red;") || !strings.Contains(css, "padding: 1rem;") { - t.Fatalf("missing decls: %q", css) - } -} diff --git a/plugins/web/internal/tenant/tenant.go b/plugins/web/internal/tenant/tenant.go deleted file mode 100755 index a85970f..0000000 --- a/plugins/web/internal/tenant/tenant.go +++ /dev/null @@ -1,252 +0,0 @@ -// Package tenant resolves multi-tenant request context for ext/web. -package tenant - -import ( - "context" - "fmt" - "net/http" - "strings" -) - -type ctxKey int - -const requestKey ctxKey = 1 - -// Config is stored on the app bag under key "tenant". -type Config struct { - Mode string // path | subdomain | header - Param string // path capture / query / header name - Column string // DB column (default tenant_id) - DefaultScope bool // auto-scope all selects/inserts when true -} - -// FromBag reads tenant config from an app bag. -func FromBag(appBag map[string]any) Config { - cfg := Config{Column: "tenant_id"} - raw, ok := appBag["tenant"].(map[string]any) - if !ok { - return cfg - } - cfg.Mode = strings.ToLower(strings.TrimSpace(str(raw, "mode", "模式"))) - cfg.Param = strings.TrimSpace(str(raw, "param", "参数", "tenant_param")) - if c := str(raw, "column", "列", "tenant_column"); c != "" { - cfg.Column = c - } - if v, ok := raw["default_scope"]; ok { - cfg.DefaultScope = boolish(v) - } else if v, ok := raw["默认作用域"]; ok { - cfg.DefaultScope = boolish(v) - } else if v, ok := raw["scope"]; ok { - cfg.DefaultScope = boolish(v) - } - return cfg -} - -// Enabled reports whether tenant resolution is configured. -func (c Config) Enabled() bool { - return c.Mode != "" -} - -// Configure merges tenant options onto the app bag. -func Configure(appBag map[string]any, opts map[string]any) (map[string]any, error) { - if opts == nil { - opts = map[string]any{} - } - mode := strings.ToLower(strings.TrimSpace(str(opts, "mode", "模式"))) - if mode == "" { - return nil, fmt.Errorf("tenant: mode required (path|subdomain|header)") - } - switch mode { - case "path", "路径", "subdomain", "子域", "header", "头": - default: - return nil, fmt.Errorf("tenant: unknown mode %q", mode) - } - if mode == "路径" { - mode = "path" - } - if mode == "子域" { - mode = "subdomain" - } - if mode == "头" { - mode = "header" - } - param := strings.TrimSpace(str(opts, "param", "参数", "tenant_param")) - if param == "" { - switch mode { - case "path": - param = "t" - case "header": - param = "X-Tenant-Id" - case "subdomain": - param = "" - } - } - col := strings.TrimSpace(str(opts, "column", "列", "tenant_column")) - if col == "" { - col = "tenant_id" - } - entry := map[string]any{ - "mode": mode, - "param": param, - "column": col, - } - if v, ok := first(opts, "default_scope", "默认作用域", "scope"); ok { - entry["default_scope"] = boolish(v) - } - out := clone(appBag) - out["tenant"] = entry - return out, nil -} - -// Resolve extracts tenant id from the HTTP request. -func Resolve(r *http.Request, cfg Config) string { - if !cfg.Enabled() { - return "" - } - switch cfg.Mode { - case "path": - if cfg.Param != "" { - if v := r.PathValue(cfg.Param); v != "" { - return sanitize(v) - } - if v := r.URL.Query().Get(cfg.Param); v != "" { - return sanitize(v) - } - // /t/{tenant}/… when param is t: take segment after /t/ - parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") - if cfg.Param == "t" && len(parts) >= 2 && parts[0] == "t" { - return sanitize(parts[1]) - } - for i, p := range parts { - if p == cfg.Param && i+1 < len(parts) { - return sanitize(parts[i+1]) - } - } - } - case "subdomain": - host := r.Host - if h, _, ok := strings.Cut(host, ":"); ok { - host = h - } - labels := strings.Split(host, ".") - if len(labels) >= 3 { - return sanitize(labels[0]) - } - case "header": - name := cfg.Param - if name == "" { - name = "X-Tenant-Id" - } - return sanitize(r.Header.Get(name)) - } - return "" -} - -// WithContext stores tenant id on the request context. -func WithContext(ctx context.Context, id string) context.Context { - return context.WithValue(ctx, requestKey, id) -} - -// FromContext reads tenant id (empty if unset). -func FromContext(ctx context.Context) string { - if ctx == nil { - return "" - } - if s, ok := ctx.Value(requestKey).(string); ok { - return s - } - return "" -} - -// MergeWhere adds tenant_id equality to a where value (map or list of maps). -func MergeWhere(where any, column, tenantID string) any { - if tenantID == "" || column == "" { - return where - } - clause := map[string]any{"字段": column, "field": column, "操作": "=", "op": "=", "值": tenantID, "value": tenantID} - switch t := where.(type) { - case nil: - return []any{clause} - case []any: - out := make([]any, 0, len(t)+1) - out = append(out, t...) - out = append(out, clause) - return out - case map[string]any: - out := cloneMap(t) - out[column] = tenantID - return out - default: - return []any{where, clause} - } -} - -// StampRow sets tenant column on an insert/update row map if missing. -func StampRow(row map[string]any, column, tenantID string) map[string]any { - if row == nil || tenantID == "" || column == "" { - return row - } - if _, ok := row[column]; ok { - return row - } - out := cloneMap(row) - out[column] = tenantID - return out -} - -func sanitize(s string) string { - s = strings.TrimSpace(strings.ToLower(s)) - var b strings.Builder - for _, r := range s { - if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' { - b.WriteRune(r) - } - } - return b.String() -} - -func str(m map[string]any, keys ...string) string { - for _, k := range keys { - if v, ok := m[k]; ok && v != nil { - if s, ok := v.(string); ok { - return s - } - return fmt.Sprint(v) - } - } - return "" -} - -func first(m map[string]any, keys ...string) (any, bool) { - for _, k := range keys { - if v, ok := m[k]; ok && v != nil { - return v, true - } - } - return nil, false -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - switch strings.TrimSpace(t) { - case "true", "True", "1", "yes", "on", "真": - return true - } - case float64: - return t != 0 - } - return false -} - -func clone(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} - -func cloneMap(m map[string]any) map[string]any { return clone(m) } diff --git a/plugins/web/internal/tenant/tenant_test.go b/plugins/web/internal/tenant/tenant_test.go deleted file mode 100755 index 842bd5e..0000000 --- a/plugins/web/internal/tenant/tenant_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package tenant_test - -import ( - "net/http/httptest" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/tenant" -) - -func TestResolvePathQuery(t *testing.T) { - cfg := tenant.Config{Mode: "path", Param: "t", Column: "tenant_id"} - r := httptest.NewRequest("GET", "/api/items?t=acme", nil) - if got := tenant.Resolve(r, cfg); got != "acme" { - t.Fatalf("got %q", got) - } -} - -func TestResolvePathPrefix(t *testing.T) { - cfg := tenant.Config{Mode: "path", Param: "t"} - r := httptest.NewRequest("GET", "/t/beta/items", nil) - if got := tenant.Resolve(r, cfg); got != "beta" { - t.Fatalf("got %q", got) - } -} - -func TestResolveHeader(t *testing.T) { - cfg := tenant.Config{Mode: "header", Param: "X-Tenant-Id"} - r := httptest.NewRequest("GET", "/", nil) - r.Header.Set("X-Tenant-Id", "Gamma") - if got := tenant.Resolve(r, cfg); got != "gamma" { - t.Fatalf("got %q", got) - } -} - -func TestMergeWhereAndStamp(t *testing.T) { - w := tenant.MergeWhere(nil, "tenant_id", "acme") - arr, ok := w.([]any) - if !ok || len(arr) != 1 { - t.Fatalf("where=%v", w) - } - row := tenant.StampRow(map[string]any{"title": "x"}, "tenant_id", "acme") - if row["tenant_id"] != "acme" { - t.Fatalf("row=%v", row) - } -} - -func TestConfigure(t *testing.T) { - out, err := tenant.Configure(map[string]any{}, map[string]any{ - "mode": "path", "param": "org", "default_scope": true, - }) - if err != nil { - t.Fatal(err) - } - cfg := tenant.FromBag(out) - if cfg.Mode != "path" || cfg.Param != "org" || !cfg.DefaultScope { - t.Fatalf("%+v", cfg) - } -} diff --git a/plugins/web/internal/upload/upload.go b/plugins/web/internal/upload/upload.go deleted file mode 100755 index dde0cf6..0000000 --- a/plugins/web/internal/upload/upload.go +++ /dev/null @@ -1,273 +0,0 @@ -// Package upload ports media validation and offline save (W-G6). -package upload - -import ( - "crypto/rand" - "encoding/hex" - "fmt" - "os" - "path/filepath" - "strings" - "time" - - "github.com/marqdo/marqdo/plugins/web/internal/storage" -) - -// Validate checks size / MIME / extension against optional allowlist table. -func Validate(filename, contentType string, size, maxBytes uint64, types any) map[string]any { - if size > maxBytes { - return map[string]any{ - "ok": false, - "error": fmt.Sprintf("file too large: %d > %d", size, maxBytes), - } - } - name := strings.TrimSpace(filename) - if name == "" { - return map[string]any{"ok": false, "error": "empty filename"} - } - if strings.Contains(name, "..") || strings.Contains(name, "/") || strings.Contains(name, `\`) { - return map[string]any{"ok": false, "error": "unsafe filename"} - } - ct := strings.ToLower(strings.TrimSpace(contentType)) - if i := strings.IndexByte(ct, ';'); i >= 0 { - ct = strings.TrimSpace(ct[:i]) - } - ext := "" - if i := strings.LastIndexByte(name, '.'); i >= 0 && i < len(name)-1 { - ext = strings.ToLower(name[i+1:]) - } - if types != nil && !typesAllow(types, ct, ext) { - return map[string]any{ - "ok": false, - "error": fmt.Sprintf("type not allowed: content_type=%s ext=%s", ct, ext), - } - } - outCT := ct - if outCT == "" { - outCT = "application/octet-stream" - } - return map[string]any{ - "ok": true, - "filename": name, - "content_type": outCT, - "size": float64(size), - "ext": ext, - } -} - -func typesAllow(types any, contentType, ext string) bool { - if types == nil { - return true - } - switch t := types.(type) { - case string: - s := strings.TrimSpace(t) - if s == "" { - return true - } - for _, p := range strings.Split(s, ",") { - p = strings.ToLower(strings.TrimSpace(p)) - if p != "" && p == contentType { - return true - } - } - return false - case []any: - if len(t) == 0 { - return true - } - for _, row := range t { - if rowAllows(row, contentType, ext) { - return true - } - } - return false - case map[string]any: - colMime := first(t, "类型", "type", "mime") - colExt := first(t, "扩展名", "ext", "extension") - if ma, ok := colMime.([]any); ok { - var exts []string - switch ev := colExt.(type) { - case []any: - for _, x := range ev { - exts = append(exts, strings.ToLower(cellStr(x))) - } - case string: - exts = []string{strings.ToLower(ev)} - } - if len(ma) == 0 { - return true - } - for i, mimeV := range ma { - mime := strings.ToLower(strings.TrimSpace(cellStr(mimeV))) - rowExt := "" - if i < len(exts) { - rowExt = exts[i] - } - mimeOK := mime == "" || mime == contentType - extOK := rowExt == "" || extMatches(rowExt, ext) - if mimeOK && extOK { - return true - } - } - return false - } - if colMime != nil || colExt != nil { - return rowAllows(t, contentType, ext) - } - if len(t) == 0 { - return true - } - for mime, extsV := range t { - exts := extList(extsV) - mimeOK := strings.TrimSpace(mime) == "" || strings.EqualFold(mime, contentType) - extOK := exts == "" || extMatches(exts, ext) - if mimeOK && extOK { - return true - } - } - return false - default: - return true - } -} - -func rowAllows(row any, contentType, ext string) bool { - switch t := row.(type) { - case string: - return strings.EqualFold(strings.TrimSpace(t), contentType) - case map[string]any: - mime := strings.ToLower(strings.TrimSpace(firstStr(t, "类型", "type", "mime"))) - exts := strings.ToLower(strings.TrimSpace(firstStr(t, "扩展名", "ext", "extension"))) - mimeOK := mime == "" || mime == contentType - extOK := exts == "" || extMatches(exts, ext) - return mimeOK && extOK - default: - return false - } -} - -func extMatches(exts, ext string) bool { - for _, e := range strings.Split(exts, ",") { - e = strings.TrimSpace(strings.TrimPrefix(e, ".")) - if e == ext { - return true - } - } - return false -} - -func extList(v any) string { - switch t := v.(type) { - case string: - return strings.ToLower(strings.TrimSpace(t)) - case []any: - parts := make([]string, 0, len(t)) - for _, x := range t { - if s, ok := x.(string); ok { - parts = append(parts, s) - } - } - return strings.ToLower(strings.Join(parts, ",")) - default: - return "" - } -} - -func first(m map[string]any, keys ...string) any { - for _, k := range keys { - if v, ok := m[k]; ok { - return v - } - } - return nil -} - -func firstStr(m map[string]any, keys ...string) string { - return cellStr(first(m, keys...)) -} - -func cellStr(v any) string { - switch t := v.(type) { - case nil: - return "" - case string: - return t - case float64: - if t == float64(int64(t)) { - return fmt.Sprintf("%d", int64(t)) - } - return fmt.Sprintf("%v", t) - case bool: - if t { - return "true" - } - return "false" - default: - return fmt.Sprint(t) - } -} - -// MakeKey builds prefix + timestamp-random + sanitized basename. -func MakeKey(prefix, filename string) (string, error) { - base := filename - if i := strings.LastIndexAny(filename, `/\`); i >= 0 { - base = filename[i+1:] - } - base = strings.TrimSpace(base) - if base == "" { - return "", fmt.Errorf("empty filename") - } - var safe strings.Builder - for _, c := range base { - if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || - c == '.' || c == '-' || c == '_' { - safe.WriteRune(c) - } else { - safe.WriteRune('_') - } - } - s := safe.String() - if strings.Contains(s, "..") { - return "", fmt.Errorf("unsafe filename") - } - pref := strings.ReplaceAll(strings.TrimPrefix(strings.TrimSpace(prefix), "/"), `\`, "/") - if pref != "" && !strings.HasSuffix(pref, "/") { - pref += "/" - } - if strings.Contains(pref, "..") { - return "", fmt.Errorf("prefix must not contain `..`") - } - rnd := make([]byte, 4) - if _, err := rand.Read(rnd); err != nil { - return "", err - } - return fmt.Sprintf("%s%d-%s-%s", pref, time.Now().Unix(), hex.EncodeToString(rnd), s), nil -} - -// Save reads local path bytes into storage under key (or auto key). -func Save(storageURL string, key *string, path string, contentType, prefix *string) (map[string]any, error) { - data, err := os.ReadFile(path) - if err != nil { - return nil, fmt.Errorf("read `%s`: %w", path, err) - } - filename := filepath.Base(path) - ct := "application/octet-stream" - if contentType != nil && strings.TrimSpace(*contentType) != "" { - ct = strings.TrimSpace(*contentType) - } - objectKey := "" - if key != nil && strings.TrimSpace(*key) != "" { - objectKey = *key - } else { - p := "uploads/" - if prefix != nil && strings.TrimSpace(*prefix) != "" { - p = *prefix - } - objectKey, err = MakeKey(p, filename) - if err != nil { - return nil, err - } - } - return storage.PutBytes(storageURL, objectKey, data, ct) -} diff --git a/plugins/web/internal/upload/upload_test.go b/plugins/web/internal/upload/upload_test.go deleted file mode 100755 index 8b2232d..0000000 --- a/plugins/web/internal/upload/upload_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package upload - -import ( - "os" - "path/filepath" - "testing" -) - -func TestValidateAllowReject(t *testing.T) { - types := []any{ - map[string]any{"类型": "image/png", "扩展名": "png"}, - map[string]any{"类型": "text/plain", "扩展名": "txt"}, - } - ok := Validate("a.png", "image/png", 100, 1000, types) - if ok["ok"] != true { - t.Fatalf("expected ok: %#v", ok) - } - bad := Validate("a.exe", "application/octet-stream", 100, 1000, types) - if bad["ok"] != false { - t.Fatalf("expected reject: %#v", bad) - } - big := Validate("a.png", "image/png", 9000, 1000, types) - if big["ok"] != false { - t.Fatalf("expected size reject: %#v", big) - } -} - -func TestSaveRoundtrip(t *testing.T) { - dir := t.TempDir() - src := filepath.Join(dir, "sample.txt") - if err := os.WriteFile(src, []byte("hello-upload"), 0o644); err != nil { - t.Fatal(err) - } - url := "file:" + filepath.Join(dir, "blobs") - prefix := "smoke/" - ct := "text/plain" - saved, err := Save(url, nil, src, &ct, &prefix) - if err != nil { - t.Fatal(err) - } - if saved["ok"] != true { - t.Fatalf("save: %#v", saved) - } - key, _ := saved["key"].(string) - if key == "" { - t.Fatal("missing key") - } -} diff --git a/plugins/web/internal/ws/connect.go b/plugins/web/internal/ws/connect.go deleted file mode 100755 index e44c70d..0000000 --- a/plugins/web/internal/ws/connect.go +++ /dev/null @@ -1,96 +0,0 @@ -package ws - -import ( - "fmt" - "net/http" - "strings" - "time" - - "github.com/gorilla/websocket" -) - -const ( - maxMessageBytes = 1 << 20 - maxMessages = 256 -) - -// Connect dials url, sends one text message, collects text replies until close or timeout. -// Mirrors Rust ws::connect; errors are returned as {ok:false, error}. -func Connect(url, message string, headers map[string]any, timeoutSec uint64) map[string]any { - if !(strings.HasPrefix(url, "ws://") || strings.HasPrefix(url, "wss://")) { - return map[string]any{"ok": false, "error": "ws url must start with ws:// or wss://"} - } - if timeoutSec < 1 { - timeoutSec = 1 - } - timeout := time.Duration(timeoutSec) * time.Second - hdr := http.Header{} - for k, v := range headersFromValue(headers) { - hdr.Set(k, v) - } - dialer := websocket.Dialer{HandshakeTimeout: timeout} - conn, _, err := dialer.Dial(url, hdr) - if err != nil { - return map[string]any{"ok": false, "error": fmt.Sprintf("ws connect: %v", err)} - } - defer conn.Close() - conn.SetReadLimit(maxMessageBytes) - - if err := conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil { - return map[string]any{"ok": false, "error": fmt.Sprintf("ws send: %v", err)} - } - if err := conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil { - return map[string]any{"ok": false, "error": fmt.Sprintf("ws send: %v", err)} - } - - var messages []string - deadline := time.Now().Add(timeout) - for { - if err := conn.SetReadDeadline(deadline); err != nil { - break - } - mt, data, err := conn.ReadMessage() - if err != nil { - if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) { - break - } - return map[string]any{"ok": false, "error": fmt.Sprintf("ws receive: %v", err)} - } - if mt == websocket.TextMessage { - if len(messages) == maxMessages { - return map[string]any{"ok": false, "error": "ws receive: too many messages"} - } - messages = append(messages, string(data)) - } - if mt == websocket.CloseMessage { - break - } - } - return map[string]any{"ok": true, "messages": toAnyList(messages)} -} - -func headersFromValue(headers map[string]any) map[string]string { - out := map[string]string{} - if headers == nil { - return out - } - for k, v := range headers { - switch t := v.(type) { - case string: - out[k] = t - case nil: - out[k] = "" - default: - out[k] = fmt.Sprint(t) - } - } - return out -} - -func toAnyList(ss []string) []any { - out := make([]any, len(ss)) - for i, s := range ss { - out[i] = s - } - return out -} diff --git a/plugins/web/internal/ws/hub.go b/plugins/web/internal/ws/hub.go deleted file mode 100755 index b966f26..0000000 --- a/plugins/web/internal/ws/hub.go +++ /dev/null @@ -1,94 +0,0 @@ -package ws - -import ( - "sync" -) - -const hubCap = 256 - -type hub struct { - mu sync.Mutex - room map[string]*broadcastRoom -} - -type broadcastRoom struct { - mu sync.Mutex - subs map[chan string]struct{} -} - -var globalHub = &hub{room: map[string]*broadcastRoom{}} - -func subscribe(path string) chan string { - ch := make(chan string, hubCap) - globalHub.mu.Lock() - room := globalHub.room[path] - if room == nil { - room = &broadcastRoom{subs: map[chan string]struct{}{}} - globalHub.room[path] = room - } - room.mu.Lock() - room.subs[ch] = struct{}{} - room.mu.Unlock() - globalHub.mu.Unlock() - return ch -} - -func unsubscribe(path string, ch chan string) { - globalHub.mu.Lock() - room := globalHub.room[path] - globalHub.mu.Unlock() - if room == nil { - return - } - room.mu.Lock() - delete(room.subs, ch) - empty := len(room.subs) == 0 - room.mu.Unlock() - if !empty { - return - } - // A room can be derived from a URL path. Remove empty rooms so a stream of - // one-off room names cannot leave metadata allocated for the process lifetime. - globalHub.mu.Lock() - if globalHub.room[path] == room { - room.mu.Lock() - if len(room.subs) == 0 { - delete(globalHub.room, path) - } - room.mu.Unlock() - } - globalHub.mu.Unlock() -} - -// JoinRoom subscribes to a named room (G-WS1). Same backing store as path broadcast. -func JoinRoom(room string) chan string { - return subscribe(room) -} - -// LeaveRoom unsubscribes from a named room (G-WS1). -func LeaveRoom(room string, ch chan string) { - unsubscribe(room, ch) -} - -// PublishRoom fans out text to all subscribers in a named room (G-WS1). -func PublishRoom(room string, text string) { - Publish(room, text) -} - -// Publish fans out text to all subscribers on path (Rust ws_hub::publish). -func Publish(path string, text string) { - globalHub.mu.Lock() - room := globalHub.room[path] - globalHub.mu.Unlock() - if room == nil { - return - } - room.mu.Lock() - for ch := range room.subs { - select { - case ch <- text: - default: - } - } - room.mu.Unlock() -} diff --git a/plugins/web/internal/ws/hub_test.go b/plugins/web/internal/ws/hub_test.go deleted file mode 100755 index 991a5cb..0000000 --- a/plugins/web/internal/ws/hub_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package ws - -import ( - "testing" - "time" -) - -func TestNamedRoomJoinPublishLeave(t *testing.T) { - room := "chat.room.42" - ch := JoinRoom(room) - ch2 := JoinRoom(room) - PublishRoom(room, "hello-room") - if got := readOne(ch); got != "hello-room" { - t.Fatalf("ch1=%q", got) - } - if got := readOne(ch2); got != "hello-room" { - t.Fatalf("ch2=%q", got) - } - LeaveRoom(room, ch) - LeaveRoom(room, ch2) -} - -func TestBroadcastFanout(t *testing.T) { - path := "/t-fanout-go" - ch := subscribe(path) - ch2 := subscribe(path) - Publish(path, "hi") - if got := readOne(ch); got != "hi" { - t.Fatalf("ch1=%q", got) - } - if got := readOne(ch2); got != "hi" { - t.Fatalf("ch2=%q", got) - } - unsubscribe(path, ch) - unsubscribe(path, ch2) -} - -func TestUnsubscribeRemovesEmptyRoom(t *testing.T) { - path := "/t-empty-room-gc" - ch := subscribe(path) - unsubscribe(path, ch) - globalHub.mu.Lock() - _, ok := globalHub.room[path] - globalHub.mu.Unlock() - if ok { - t.Fatalf("empty room %q was not garbage-collected", path) - } -} - -func TestResubscribeDuringCleanupKeepsRoom(t *testing.T) { - path := "/t-room-rejoin" - ch := subscribe(path) - ch2 := subscribe(path) - unsubscribe(path, ch) - unsubscribe(path, ch2) - ch3 := subscribe(path) - Publish(path, "still-alive") - if got := readOne(ch3); got != "still-alive" { - t.Fatalf("re-subscribed chan got %q", got) - } - unsubscribe(path, ch3) - globalHub.mu.Lock() - _, ok := globalHub.room[path] - globalHub.mu.Unlock() - if ok { - t.Fatalf("empty room %q was not garbage-collected after rejoin", path) - } -} - -func readOne(ch chan string) string { - select { - case s := <-ch: - return s - case <-time.After(time.Second): - return "" - } -} diff --git a/plugins/web/internal/ws/mode.go b/plugins/web/internal/ws/mode.go deleted file mode 100755 index 0198dd5..0000000 --- a/plugins/web/internal/ws/mode.go +++ /dev/null @@ -1,98 +0,0 @@ -// Package ws ports WebSocket route registration and client connect from the Rust web plugin. -package ws - -import ( - "strings" -) - -// Mode is the server-side WebSocket handler mode for a path. -type Mode string - -const ( - ModeEcho Mode = "echo" - ModeBroadcast Mode = "broadcast" - ModeDrain Mode = "drain" - ModeRoom Mode = "room" -) - -// ParseMode mirrors Rust ws_hub::WsMode::parse. -func ParseMode(v any) Mode { - switch t := v.(type) { - case bool: - if t { - return ModeEcho - } - return ModeDrain - case string: - switch strings.TrimSpace(strings.ToLower(t)) { - case "broadcast", "广播": - return ModeBroadcast - case "room", "房间": - return ModeRoom - case "drain", "false", "0", "no", "drain_only": - return ModeDrain - default: - return ModeEcho - } - case map[string]any: - if m, ok := t["mode"]; ok { - return ParseMode(m) - } - if m, ok := t["模式"]; ok { - return ParseMode(m) - } - if e, ok := t["echo"]; ok { - return ParseMode(e) - } - if e, ok := t["回显"]; ok { - return ParseMode(e) - } - return ModeEcho - default: - return ModeEcho - } -} - -// ModeFromArgs picks mode from route_ws ABI args (mode/模式 or echo/回显, default echo). -func ModeFromArgs(args map[string]any) Mode { - if v, ok := first(args, "mode", "模式"); ok { - return ParseMode(v) - } - echo := true - if v, ok := first(args, "echo", "回显"); ok { - echo = boolish(v) - } - if echo { - return ModeEcho - } - return ModeDrain -} - -func first(m map[string]any, keys ...string) (any, bool) { - for _, k := range keys { - if v, ok := m[k]; ok && v != nil { - return v, true - } - } - return nil, false -} - -func boolish(v any) bool { - switch t := v.(type) { - case bool: - return t - case string: - switch strings.TrimSpace(t) { - case "true", "True", "1", "yes", "on", "真": - return true - } - return false - case float64: - return t != 0 - case int: - return t != 0 - case int64: - return t != 0 - } - return false -} diff --git a/plugins/web/internal/ws/route.go b/plugins/web/internal/ws/route.go deleted file mode 100755 index f57eda0..0000000 --- a/plugins/web/internal/ws/route.go +++ /dev/null @@ -1,189 +0,0 @@ -package ws - -import ( - "fmt" - "strings" - - "github.com/marqdo/marqdo/plugins/web/internal/app" -) - -// RouteSpec is one ws_routes entry (mode + optional room_key / on_message / presence). -type RouteSpec struct { - Mode Mode - RoomKey string - OnMessage string - Presence bool - RequireAuth bool -} - -// RouteWS registers path → {mode, room_key?, on_message?, presence?} on app.ws_routes. -func RouteWS(appBag map[string]any, path string, args map[string]any) (map[string]any, error) { - path, err := app.NormalizeRoutePath(path, appBag) - if err != nil { - return nil, err - } - mode := ModeFromArgs(args) - roomKey := RoomKeyFromArgs(args) - if mode == ModeRoom && roomKey == "" { - return nil, fmt.Errorf("mode=room requires room_key") - } - onMsg := OnMessageFromArgs(args) - presence := PresenceFromArgs(args) - // Stateful fan-out routes are private by default. Echo and drain remain - // useful for public health checks and demos; authors can opt out explicitly. - requireAuth := mode == ModeBroadcast || mode == ModeRoom - if v, ok := first(args, "require_auth", "需要登录"); ok && v != nil { - requireAuth = boolish(v) - } - out := clone(appBag) - wsRoutes := map[string]any{} - if r, ok := out["ws_routes"].(map[string]any); ok { - wsRoutes = clone(r) - } - spec := map[string]any{"mode": string(mode)} - if roomKey != "" { - spec["room_key"] = roomKey - } - if onMsg != "" { - spec["on_message"] = onMsg - } - if presence { - spec["presence"] = true - } - if requireAuth { - spec["require_auth"] = true - } - wsRoutes[path] = spec - out["ws_routes"] = wsRoutes - return out, nil -} - -// RoomKeyFromArgs reads room_key / 房间 from route_ws ABI args. -func RoomKeyFromArgs(args map[string]any) string { - if v, ok := first(args, "room_key", "房间"); ok { - return strings.TrimSpace(fmt.Sprint(v)) - } - return "" -} - -// OnMessageFromArgs reads on_message / 消息钩子 (lib.member path). -func OnMessageFromArgs(args map[string]any) string { - if v, ok := first(args, "on_message", "消息钩子", "钩子"); ok { - return strings.TrimSpace(fmt.Sprint(v)) - } - return "" -} - -// PresenceFromArgs reads presence / 在场 flag. -func PresenceFromArgs(args map[string]any) bool { - if v, ok := first(args, "presence", "在场"); ok { - return boolish(v) - } - return false -} - -// ExpandTemplate replaces `{name}` tokens using values from PathValue-style map. -func ExpandTemplate(tmpl string, values map[string]string) string { - if tmpl == "" || len(values) == 0 { - return tmpl - } - out := tmpl - for k, v := range values { - out = strings.ReplaceAll(out, "{"+k+"}", v) - } - return out -} - -// RoutesOf reads ws_routes from an app bag. -func RoutesOf(appBag map[string]any) map[string]Mode { - out := map[string]Mode{} - obj, ok := appBag["ws_routes"].(map[string]any) - if !ok { - return out - } - for path, spec := range obj { - switch t := spec.(type) { - case map[string]any: - if m, ok := t["mode"]; ok { - out[path] = ParseMode(m) - continue - } - out[path] = ParseMode(t) - case string: - out[path] = ParseMode(t) - default: - out[path] = ParseMode(spec) - } - } - return out -} - -func clone(m map[string]any) map[string]any { - out := make(map[string]any, len(m)) - for k, v := range m { - out[k] = v - } - return out -} - -// ModeOf returns the mode for one ws route path, or error if missing. -func ModeOf(appBag map[string]any, path string) (Mode, error) { - spec, err := RouteSpecOf(appBag, path) - if err != nil { - return "", err - } - return spec.Mode, nil -} - -// RouteSpecOf returns mode and room_key for one ws route path. -func RouteSpecOf(appBag map[string]any, path string) (RouteSpec, error) { - routes, ok := appBag["ws_routes"].(map[string]any) - if !ok { - return RouteSpec{}, fmt.Errorf("missing ws route %s", path) - } - spec, ok := routes[path] - if !ok { - return RouteSpec{}, fmt.Errorf("missing ws route %s", path) - } - return parseRouteSpec(spec), nil -} - -// ParseRouteSpec reads mode and room_key from a ws_routes value. -func ParseRouteSpec(spec any) RouteSpec { - return parseRouteSpec(spec) -} - -func parseRouteSpec(spec any) RouteSpec { - out := RouteSpec{Mode: ModeEcho} - switch t := spec.(type) { - case map[string]any: - if mode, ok := t["mode"]; ok { - out.Mode = ParseMode(mode) - } else { - out.Mode = ParseMode(t) - } - if rk, ok := t["room_key"]; ok { - out.RoomKey = strings.TrimSpace(fmt.Sprint(rk)) - } - if om, ok := t["on_message"]; ok { - out.OnMessage = strings.TrimSpace(fmt.Sprint(om)) - } else if om, ok := t["消息钩子"]; ok { - out.OnMessage = strings.TrimSpace(fmt.Sprint(om)) - } - if p, ok := t["presence"]; ok { - out.Presence = boolish(p) - } else if p, ok := t["在场"]; ok { - out.Presence = boolish(p) - } - if a, ok := t["require_auth"]; ok { - out.RequireAuth = boolish(a) - } else if a, ok := t["需要登录"]; ok { - out.RequireAuth = boolish(a) - } - case string: - out.Mode = ParseMode(t) - default: - out.Mode = ParseMode(spec) - } - return out -} diff --git a/plugins/web/internal/ws/route_test.go b/plugins/web/internal/ws/route_test.go deleted file mode 100755 index e433311..0000000 --- a/plugins/web/internal/ws/route_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package ws_test - -import ( - "strings" - "testing" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/ws" -) - -func TestRouteWSBroadcastMode(t *testing.T) { - a := app.New(map[string]any{"page": map[string]any{"title": "w6b"}}) - out, err := ws.RouteWS(a, "/room", map[string]any{"mode": "broadcast"}) - if err != nil { - t.Fatal(err) - } - mode, err := ws.ModeOf(out, "/room") - if err != nil { - t.Fatal(err) - } - if mode != ws.ModeBroadcast { - t.Fatalf("mode=%q want broadcast", mode) - } - routes := out["ws_routes"].(map[string]any) - room := routes["/room"].(map[string]any) - if room["mode"] != "broadcast" { - t.Fatalf("bag mode=%v", room["mode"]) - } - if room["require_auth"] != true { - t.Fatalf("broadcast must require authentication by default: %v", room) - } -} - -func TestRouteWSPublicBroadcastOptOut(t *testing.T) { - a := app.New(nil) - out, err := ws.RouteWS(a, "/live", map[string]any{ - "mode": "broadcast", - "require_auth": false, - }) - if err != nil { - t.Fatal(err) - } - spec, err := ws.RouteSpecOf(out, "/live") - if err != nil { - t.Fatal(err) - } - if spec.RequireAuth { - t.Fatalf("explicit public route unexpectedly requires authentication: %+v", spec) - } -} - -func TestRouteWSEchoDefault(t *testing.T) { - a := app.New(nil) - out, err := ws.RouteWS(a, "/live", map[string]any{"echo": true}) - if err != nil { - t.Fatal(err) - } - mode, err := ws.ModeOf(out, "/live") - if err != nil { - t.Fatal(err) - } - if mode != ws.ModeEcho { - t.Fatalf("mode=%q want echo", mode) - } -} - -func TestRouteWSDrainFromEchoFalse(t *testing.T) { - a := app.New(nil) - out, err := ws.RouteWS(a, "/sink", map[string]any{"echo": false}) - if err != nil { - t.Fatal(err) - } - mode, err := ws.ModeOf(out, "/sink") - if err != nil { - t.Fatal(err) - } - if mode != ws.ModeDrain { - t.Fatalf("mode=%q want drain", mode) - } -} - -func TestParseModeVariants(t *testing.T) { - cases := []struct { - in any - want ws.Mode - }{ - {true, ws.ModeEcho}, - {false, ws.ModeDrain}, - {"broadcast", ws.ModeBroadcast}, - {"广播", ws.ModeBroadcast}, - {"drain", ws.ModeDrain}, - {"room", ws.ModeRoom}, - {"房间", ws.ModeRoom}, - {"nope", ws.ModeEcho}, - } - for _, c := range cases { - if got := ws.ParseMode(c.in); got != c.want { - t.Fatalf("ParseMode(%#v)=%q want %q", c.in, got, c.want) - } - } -} - -func TestRouteWSRoomModeWithKey(t *testing.T) { - a := app.New(nil) - out, err := ws.RouteWS(a, "/chat", map[string]any{ - "mode": "room", - "room_key": "chat.room.{id}", - }) - if err != nil { - t.Fatal(err) - } - spec, err := ws.RouteSpecOf(out, "/chat") - if err != nil { - t.Fatal(err) - } - if spec.Mode != ws.ModeRoom { - t.Fatalf("mode=%q want room", spec.Mode) - } - if spec.RoomKey != "chat.room.{id}" { - t.Fatalf("room_key=%q", spec.RoomKey) - } - routes := out["ws_routes"].(map[string]any) - room := routes["/chat"].(map[string]any) - if room["mode"] != "room" || room["room_key"] != "chat.room.{id}" { - t.Fatalf("bag=%v", room) - } -} - -func TestRouteWSRoomRequiresKey(t *testing.T) { - a := app.New(nil) - _, err := ws.RouteWS(a, "/chat", map[string]any{"mode": "room"}) - if err == nil { - t.Fatal("expected error without room_key") - } -} - -func TestExpandTemplate(t *testing.T) { - got := ws.ExpandTemplate("chat.room.{id}", map[string]string{"id": "lobby"}) - if got != "chat.room.lobby" { - t.Fatalf("got %q", got) - } -} - -func TestRouteWSOnMessageAndPresence(t *testing.T) { - a := app.New(nil) - out, err := ws.RouteWS(a, "/chat/{id}", map[string]any{ - "mode": "room", - "room_key": "chat.room.{id}", - "on_message": "chat.persist", - "presence": true, - }) - if err != nil { - t.Fatal(err) - } - spec, err := ws.RouteSpecOf(out, "/chat/{id}") - if err != nil { - t.Fatal(err) - } - if spec.OnMessage != "chat.persist" || !spec.Presence { - t.Fatalf("spec=%+v", spec) - } -} - -func TestConnectRefusesBadURL(t *testing.T) { - out := ws.Connect("http://127.0.0.1:1", "hi", nil, 1) - if out["ok"] == true { - t.Fatal("expected ok=false for http url") - } - err, _ := out["error"].(string) - if err == "" || !strings.Contains(err, "ws://") { - t.Fatalf("error=%q", err) - } -} diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go deleted file mode 100755 index 7403f64..0000000 --- a/plugins/web/plugin.go +++ /dev/null @@ -1,1091 +0,0 @@ -// Package main builds the Marqdo web plugin as a C shared library (ABI v2). -// -// go build -buildmode=c-shared -o build/libweb.so . -// -// See doc/design/ext-web-go-rewrite.md (W-G0+). -package main - -/* -#cgo CFLAGS: -I${SRCDIR}/abi -#include "marqdo_abi_cgo.h" -#include -#include - -static void *g_userdata; -static int (*g_register_fn)(void *, char *, char *, MarqdoPluginFn); -static void *(*g_alloc)(size_t); -static void (*g_free)(void *); -static MarqdoHostQueryFn g_host_query; - -static void host_save(MarqdoHostApi *h) { - g_userdata = h->userdata; - g_register_fn = h->register_fn; - g_alloc = h->alloc; - g_free = h->free; - g_host_query = h->host_query; -} - -static char *host_strdup(const char *s) { - if (!g_alloc || !s) return NULL; - size_t n = strlen(s); - char *p = (char *)g_alloc(n + 1); - if (!p) return NULL; - memcpy(p, s, n); - p[n] = 0; - return p; -} - -static void host_free(void *p) { - if (g_free && p) g_free(p); -} - -static int host_register(char *name, char *params, MarqdoPluginFn fn) { - if (!g_register_fn) return 1; - return g_register_fn(g_userdata, name, params, fn); -} - -static int host_query(char *name, char *args_json, char **out_json, char **err_msg) { - if (!g_host_query) return 1; - return g_host_query(g_userdata, name, args_json, out_json, err_msg); -} - -extern int web_go_ready(char *args_json, char **out_json, char **err_msg); -extern int web_page_new(char *args_json, char **out_json, char **err_msg); -extern int web_page_query(char *args_json, char **out_json, char **err_msg); -extern int web_page_order(char *args_json, char **out_json, char **err_msg); -extern int web_page_link_prefix(char *args_json, char **out_json, char **err_msg); -extern int web_page_css(char *args_json, char **out_json, char **err_msg); -extern int web_page_detail(char *args_json, char **out_json, char **err_msg); -extern int web_page_chrome(char *args_json, char **out_json, char **err_msg); -extern int web_style(char *args_json, char **out_json, char **err_msg); -extern int web_compose_components(char *args_json, char **out_json, char **err_msg); -extern int web_compose_main(char *args_json, char **out_json, char **err_msg); -extern int web_compose_list(char *args_json, char **out_json, char **err_msg); -extern int web_compose_intro(char *args_json, char **out_json, char **err_msg); -extern int web_intro(char *args_json, char **out_json, char **err_msg); -extern int web_render(char *args_json, char **out_json, char **err_msg); -extern int web_db_new(char *args_json, char **out_json, char **err_msg); -extern int web_db_init(char *args_json, char **out_json, char **err_msg); -extern int web_db_insert(char *args_json, char **out_json, char **err_msg); -extern int web_db_select(char *args_json, char **out_json, char **err_msg); -extern int web_db_get(char *args_json, char **out_json, char **err_msg); -extern int web_db_exec(char *args_json, char **out_json, char **err_msg); -extern int web_form_new(char *args_json, char **out_json, char **err_msg); -extern int web_form_fields(char *args_json, char **out_json, char **err_msg); -extern int web_compose_form(char *args_json, char **out_json, char **err_msg); - extern int web_compose_auth_form(char *args_json, char **out_json, char **err_msg); - extern int web_compose_nav_brand(char *args_json, char **out_json, char **err_msg); - extern int web_compose_client(char *args_json, char **out_json, char **err_msg); - extern int web_compose_form_load(char *args_json, char **out_json, char **err_msg); -extern int web_app_new(char *args_json, char **out_json, char **err_msg); -extern int web_app_route(char *args_json, char **out_json, char **err_msg); -extern int web_db_update(char *args_json, char **out_json, char **err_msg); -extern int web_db_update_if(char *args_json, char **out_json, char **err_msg); -extern int web_db_delete(char *args_json, char **out_json, char **err_msg); -extern int web_db_query(char *args_json, char **out_json, char **err_msg); -extern int web_db_count(char *args_json, char **out_json, char **err_msg); -extern int web_db_begin(char *args_json, char **out_json, char **err_msg); -extern int web_db_commit(char *args_json, char **out_json, char **err_msg); -extern int web_db_rollback(char *args_json, char **out_json, char **err_msg); -extern int web_db_migrate(char *args_json, char **out_json, char **err_msg); -extern int web_db_fts_create(char *args_json, char **out_json, char **err_msg); -extern int web_db_search(char *args_json, char **out_json, char **err_msg); -extern int web_db_table_info(char *args_json, char **out_json, char **err_msg); - extern int web_form_rules(char *args_json, char **out_json, char **err_msg); - extern int web_form_labels(char *args_json, char **out_json, char **err_msg); -extern int web_form_validate(char *args_json, char **out_json, char **err_msg); -extern int web_form_render(char *args_json, char **out_json, char **err_msg); -extern int web_form_submit(char *args_json, char **out_json, char **err_msg); -extern int web_form_from_schema(char *args_json, char **out_json, char **err_msg); -extern int web_app_mount_form(char *args_json, char **out_json, char **err_msg); -extern int web_app_static(char *args_json, char **out_json, char **err_msg); -extern int web_app_middleware(char *args_json, char **out_json, char **err_msg); -extern int web_listen(char *args_json, char **out_json, char **err_msg); -extern int web_password_hash(char *args_json, char **out_json, char **err_msg); -extern int web_session_new(char *args_json, char **out_json, char **err_msg); -extern int web_session_set(char *args_json, char **out_json, char **err_msg); -extern int web_session_get(char *args_json, char **out_json, char **err_msg); -extern int web_session_del(char *args_json, char **out_json, char **err_msg); -extern int web_session_destroy(char *args_json, char **out_json, char **err_msg); -extern int web_auth_login(char *args_json, char **out_json, char **err_msg); -extern int web_auth_check(char *args_json, char **out_json, char **err_msg); -extern int web_auth_logout(char *args_json, char **out_json, char **err_msg); -extern int web_auth_new(char *args_json, char **out_json, char **err_msg); -extern int web_app_auth(char *args_json, char **out_json, char **err_msg); -extern int web_app_oidc(char *args_json, char **out_json, char **err_msg); -extern int web_app_gate(char *args_json, char **out_json, char **err_msg); -extern int web_app_rbac(char *args_json, char **out_json, char **err_msg); -extern int web_app_tenant(char *args_json, char **out_json, char **err_msg); -extern int web_rbac_can(char *args_json, char **out_json, char **err_msg); -extern int web_rbac_ensure(char *args_json, char **out_json, char **err_msg); -extern int web_rbac_assign_role(char *args_json, char **out_json, char **err_msg); -extern int web_rbac_create_role(char *args_json, char **out_json, char **err_msg); -extern int web_rbac_set_role_permissions(char *args_json, char **out_json, char **err_msg); -extern int web_rbac_list_roles(char *args_json, char **out_json, char **err_msg); -extern int web_rbac_list_permissions(char *args_json, char **out_json, char **err_msg); -extern int web_storage_new(char *args_json, char **out_json, char **err_msg); -extern int web_storage_put(char *args_json, char **out_json, char **err_msg); -extern int web_storage_get(char *args_json, char **out_json, char **err_msg); -extern int web_storage_delete(char *args_json, char **out_json, char **err_msg); -extern int web_storage_list(char *args_json, char **out_json, char **err_msg); -extern int web_media_new(char *args_json, char **out_json, char **err_msg); -extern int web_upload_validate(char *args_json, char **out_json, char **err_msg); -extern int web_upload_save(char *args_json, char **out_json, char **err_msg); -extern int web_app_upload(char *args_json, char **out_json, char **err_msg); -extern int web_app_download(char *args_json, char **out_json, char **err_msg); -extern int web_app_gallery(char *args_json, char **out_json, char **err_msg); -extern int web_page_meta(char *args_json, char **out_json, char **err_msg); -extern int web_page_head(char *args_json, char **out_json, char **err_msg); -extern int web_page_images(char *args_json, char **out_json, char **err_msg); -extern int web_head(char *args_json, char **out_json, char **err_msg); -extern int web_images(char *args_json, char **out_json, char **err_msg); -extern int web_app_icons(char *args_json, char **out_json, char **err_msg); -extern int web_page_paginate(char *args_json, char **out_json, char **err_msg); -extern int web_rss_build(char *args_json, char **out_json, char **err_msg); -extern int web_app_route_rss(char *args_json, char **out_json, char **err_msg); -extern int web_app_redirect(char *args_json, char **out_json, char **err_msg); -extern int web_app_error_page(char *args_json, char **out_json, char **err_msg); -extern int web_app_sitemap(char *args_json, char **out_json, char **err_msg); -extern int web_app_robots(char *args_json, char **out_json, char **err_msg); -extern int web_sitemap_build(char *args_json, char **out_json, char **err_msg); -extern int web_app_route_ws(char *args_json, char **out_json, char **err_msg); -extern int web_ws_connect(char *args_json, char **out_json, char **err_msg); -extern int web_cache_new(char *args_json, char **out_json, char **err_msg); -extern int web_cache_get(char *args_json, char **out_json, char **err_msg); -extern int web_cache_set(char *args_json, char **out_json, char **err_msg); -extern int web_cache_del(char *args_json, char **out_json, char **err_msg); -extern int web_cache_exists(char *args_json, char **out_json, char **err_msg); -extern int web_cache_ttl(char *args_json, char **out_json, char **err_msg); -extern int web_app_proxy(char *args_json, char **out_json, char **err_msg); -extern int web_app_invoke(char *args_json, char **out_json, char **err_msg); -extern int web_api_key_check(char *args_json, char **out_json, char **err_msg); -extern int web_render_nodes(char *args_json, char **out_json, char **err_msg); -extern int web_render_document(char *args_json, char **out_json, char **err_msg); -extern int web_dom_markdown(char *args_json, char **out_json, char **err_msg); -extern int web_serve_root(char *args_json, char **out_json, char **err_msg); -extern int web_prepare_root(char *args_json, char **out_json, char **err_msg); -extern int web_inspect(char *args_json, char **out_json, char **err_msg); -extern int web_app_use(char *args_json, char **out_json, char **err_msg); -extern int web_route_use(char *args_json, char **out_json, char **err_msg); - -static int register_core(void) { - if (host_register((char *)"web_go_ready", (char *)"", web_go_ready) != 0) return 1; - if (host_register((char *)"web_page_new", (char *)"title,intro,shell_css,layout,asset_version", web_page_new) != 0) return 1; - if (host_register((char *)"web_page_query", (char *)"page,query", web_page_query) != 0) return 1; - if (host_register((char *)"web_page_order", (char *)"page,order", web_page_order) != 0) return 1; - if (host_register((char *)"web_page_link_prefix", (char *)"page,prefix", web_page_link_prefix) != 0) return 1; - if (host_register((char *)"web_page_css", (char *)"page,css", web_page_css) != 0) return 1; - if (host_register((char *)"web_page_detail", (char *)"page,detail", web_page_detail) != 0) return 1; - if (host_register((char *)"web_page_chrome", (char *)"page,nav_html,footer_html,body_class", web_page_chrome) != 0) return 1; - if (host_register((char *)"web_style", (char *)"name,table,strict", web_style) != 0) return 1; - if (host_register((char *)"web_render", (char *)"page", web_render) != 0) return 1; - if (host_register((char *)"web_db_new", (char *)"url", web_db_new) != 0) return 1; - if (host_register((char *)"web_db_init", (char *)"url,name,fields", web_db_init) != 0) return 1; - if (host_register((char *)"web_db_insert", (char *)"url,table,rows,txn", web_db_insert) != 0) return 1; - if (host_register((char *)"web_db_select", (char *)"url,table,where,limit,order,offset,txn", web_db_select) != 0) return 1; - if (host_register((char *)"web_db_get", (char *)"url,table,id,txn", web_db_get) != 0) return 1; - if (host_register((char *)"web_db_update", (char *)"url,table,id,row,txn", web_db_update) != 0) return 1; - if (host_register((char *)"web_db_update_if", (char *)"url,table,id,row,expect_col,expect_val,txn", web_db_update_if) != 0) return 1; - if (host_register((char *)"web_db_delete", (char *)"url,table,id,txn", web_db_delete) != 0) return 1; - if (host_register((char *)"web_db_exec", (char *)"url,sql,args,txn", web_db_exec) != 0) return 1; - if (host_register((char *)"web_db_query", (char *)"url,sql,args,txn", web_db_query) != 0) return 1; - if (host_register((char *)"web_db_count", (char *)"url,table,where,txn", web_db_count) != 0) return 1; - if (host_register((char *)"web_db_begin", (char *)"url", web_db_begin) != 0) return 1; - if (host_register((char *)"web_db_commit", (char *)"txn", web_db_commit) != 0) return 1; - if (host_register((char *)"web_db_rollback", (char *)"txn", web_db_rollback) != 0) return 1; - if (host_register((char *)"web_db_migrate", (char *)"url,steps", web_db_migrate) != 0) return 1; - if (host_register((char *)"web_db_fts_create", (char *)"url,table,columns,name", web_db_fts_create) != 0) return 1; - if (host_register((char *)"web_db_search", (char *)"url,table,q,limit,name", web_db_search) != 0) return 1; - if (host_register((char *)"web_db_table_info", (char *)"url,table", web_db_table_info) != 0) return 1; - if (host_register((char *)"web_form_new", (char *)"table,action,id", web_form_new) != 0) return 1; - if (host_register((char *)"web_form_fields", (char *)"form,fields", web_form_fields) != 0) return 1; - if (host_register((char *)"web_form_rules", (char *)"form,rules", web_form_rules) != 0) return 1; - if (host_register((char *)"web_form_labels", (char *)"form,submit,cancel,cancel_href", web_form_labels) != 0) return 1; - if (host_register((char *)"web_form_validate", (char *)"form,rules,data", web_form_validate) != 0) return 1; - if (host_register((char *)"web_form_render", (char *)"form,id", web_form_render) != 0) return 1; - if (host_register((char *)"web_form_submit", (char *)"form,data,url", web_form_submit) != 0) return 1; - if (host_register((char *)"web_form_from_schema", (char *)"url,table,action", web_form_from_schema) != 0) return 1; - if (host_register((char *)"web_app_new", (char *)"page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout,asset_version", web_app_new) != 0) return 1; - if (host_register((char *)"web_app_route", (char *)"app,path,page", web_app_route) != 0) return 1; - if (host_register((char *)"web_app_mount_form", (char *)"app,id,form", web_app_mount_form) != 0) return 1; - if (host_register((char *)"web_app_static", (char *)"app,dir,mount", web_app_static) != 0) return 1; - if (host_register((char *)"web_app_middleware", (char *)"app,cors,security,compress,body_limit,json_routes,access_log,cache_control,proxy,invoke", web_app_middleware) != 0) return 1; - if (host_register((char *)"web_listen", (char *)"app", web_listen) != 0) return 1; - if (host_register((char *)"web_password_hash", (char *)"password", web_password_hash) != 0) return 1; - if (host_register((char *)"web_session_new", (char *)"ttl_sec", web_session_new) != 0) return 1; - if (host_register((char *)"web_session_set", (char *)"id,key,value", web_session_set) != 0) return 1; - if (host_register((char *)"web_session_get", (char *)"id,key", web_session_get) != 0) return 1; - if (host_register((char *)"web_session_del", (char *)"id,key", web_session_del) != 0) return 1; - if (host_register((char *)"web_session_destroy", (char *)"id", web_session_destroy) != 0) return 1; - if (host_register((char *)"web_auth_login", (char *)"username,password,users,session_ttl", web_auth_login) != 0) return 1; - if (host_register((char *)"web_auth_check", (char *)"session_id", web_auth_check) != 0) return 1; - if (host_register((char *)"web_auth_logout", (char *)"session_id", web_auth_logout) != 0) return 1; - if (host_register((char *)"web_auth_new", (char *)"users,session_ttl", web_auth_new) != 0) return 1; - if (host_register((char *)"web_app_auth", (char *)"app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path,register,register_path,default_role,session_url", web_app_auth) != 0) return 1; - if (host_register((char *)"web_app_oidc", (char *)"app,issuer,client_id,client_secret,redirect_uri,redirect_origins,scopes,callback_path,authorize_url,token_url,userinfo_url", web_app_oidc) != 0) return 1; - if (host_register((char *)"web_app_gate", (char *)"app,path,roles,permissions,match,on_deny,exclude", web_app_gate) != 0) return 1; - if (host_register((char *)"web_app_rbac", (char *)"app,catalog,desk", web_app_rbac) != 0) return 1; - if (host_register((char *)"web_app_tenant", (char *)"app,mode,param,column,default_scope", web_app_tenant) != 0) return 1; - if (host_register((char *)"web_rbac_can", (char *)"permissions,needed", web_rbac_can) != 0) return 1; - if (host_register((char *)"web_rbac_ensure", (char *)"url", web_rbac_ensure) != 0) return 1; - if (host_register((char *)"web_rbac_assign_role", (char *)"url,username,role", web_rbac_assign_role) != 0) return 1; - if (host_register((char *)"web_rbac_create_role", (char *)"url,name", web_rbac_create_role) != 0) return 1; - if (host_register((char *)"web_rbac_set_role_permissions", (char *)"url,role,permissions,grantable", web_rbac_set_role_permissions) != 0) return 1; - if (host_register((char *)"web_rbac_list_roles", (char *)"url", web_rbac_list_roles) != 0) return 1; - if (host_register((char *)"web_rbac_list_permissions", (char *)"url", web_rbac_list_permissions) != 0) return 1; - if (host_register((char *)"web_storage_new", (char *)"url", web_storage_new) != 0) return 1; - if (host_register((char *)"web_storage_put", (char *)"url,key,body,path,content_type", web_storage_put) != 0) return 1; - if (host_register((char *)"web_storage_get", (char *)"url,key", web_storage_get) != 0) return 1; - if (host_register((char *)"web_storage_delete", (char *)"url,key", web_storage_delete) != 0) return 1; - if (host_register((char *)"web_storage_list", (char *)"url,prefix", web_storage_list) != 0) return 1; - if (host_register((char *)"web_media_new", (char *)"storage", web_media_new) != 0) return 1; - if (host_register((char *)"web_upload_validate", (char *)"filename,content_type,size,max_bytes,types", web_upload_validate) != 0) return 1; - if (host_register((char *)"web_upload_save", (char *)"storage,path,key,content_type,prefix", web_upload_save) != 0) return 1; - if (host_register((char *)"web_app_upload", (char *)"app,path,field,storage,prefix,max_bytes,types", web_app_upload) != 0) return 1; - if (host_register((char *)"web_app_download", (char *)"app,path,storage,disposition", web_app_download) != 0) return 1; - if (host_register((char *)"web_app_gallery", (char *)"app,path,storage,prefix,title,download_base", web_app_gallery) != 0) return 1; - if (host_register((char *)"web_page_meta", (char *)"page,meta", web_page_meta) != 0) return 1; - if (host_register((char *)"web_page_head", (char *)"page,table", web_page_head) != 0) return 1; - if (host_register((char *)"web_page_images", (char *)"page,table", web_page_images) != 0) return 1; - if (host_register((char *)"web_head", (char *)"table", web_head) != 0) return 1; - if (host_register((char *)"web_images", (char *)"table", web_images) != 0) return 1; - if (host_register((char *)"web_app_icons", (char *)"app,table", web_app_icons) != 0) return 1; - if (host_register((char *)"web_page_paginate", (char *)"page,offset,limit,path", web_page_paginate) != 0) return 1; - if (host_register((char *)"web_rss_build", (char *)"title,link,description,items", web_rss_build) != 0) return 1; - if (host_register((char *)"web_app_route_rss", (char *)"app,path,table,limit,order,title,link,description", web_app_route_rss) != 0) return 1; - if (host_register((char *)"web_app_redirect", (char *)"app,from,to,permanent", web_app_redirect) != 0) return 1; - if (host_register((char *)"web_app_error_page", (char *)"app,status,page", web_app_error_page) != 0) return 1; - if (host_register((char *)"web_app_sitemap", (char *)"app,path,base,table,loc,limit,items", web_app_sitemap) != 0) return 1; - if (host_register((char *)"web_app_robots", (char *)"app,body,sitemap", web_app_robots) != 0) return 1; - if (host_register((char *)"web_sitemap_build", (char *)"base,items", web_sitemap_build) != 0) return 1; - if (host_register((char *)"web_app_route_ws", (char *)"app,path,echo,mode,room_key,on_message,presence,require_auth", web_app_route_ws) != 0) return 1; - if (host_register((char *)"web_ws_connect", (char *)"url,message,headers,timeout_sec", web_ws_connect) != 0) return 1; - if (host_register((char *)"web_cache_new", (char *)"url", web_cache_new) != 0) return 1; - if (host_register((char *)"web_cache_get", (char *)"url,key", web_cache_get) != 0) return 1; - if (host_register((char *)"web_cache_set", (char *)"url,key,value,ttl", web_cache_set) != 0) return 1; - if (host_register((char *)"web_cache_del", (char *)"url,key", web_cache_del) != 0) return 1; - if (host_register((char *)"web_cache_exists", (char *)"url,key", web_cache_exists) != 0) return 1; - if (host_register((char *)"web_cache_ttl", (char *)"url,key", web_cache_ttl) != 0) return 1; - if (host_register((char *)"web_app_proxy", (char *)"app,path,upstream,stream,strip_prefix,methods,headers_from_env,timeout_ms", web_app_proxy) != 0) return 1; - if (host_register((char *)"web_app_invoke", (char *)"app,path,method,fn,body,return,class", web_app_invoke) != 0) return 1; - if (host_register((char *)"web_api_key_check", (char *)"key,authorization,pepper,keys", web_api_key_check) != 0) return 1; - if (host_register((char *)"web_render_nodes", (char *)"page,nodes,db,title", web_render_nodes) != 0) return 1; - if (host_register((char *)"web_render_document", (char *)"page,body,db,title", web_render_document) != 0) return 1; - if (host_register((char *)"web_dom_markdown", (char *)"text", web_dom_markdown) != 0) return 1; - if (host_register((char *)"web_serve_root", (char *)"root,host,port,db,static_dir,middleware", web_serve_root) != 0) return 1; - if (host_register((char *)"web_prepare_root", (char *)"root,host,port,db,static_dir,middleware", web_prepare_root) != 0) return 1; - if (host_register((char *)"web_inspect", (char *)"app,root", web_inspect) != 0) return 1; - if (host_register((char *)"web_app_use", (char *)"app,middleware", web_app_use) != 0) return 1; - if (host_register((char *)"web_route_use", (char *)"route,middleware", web_route_use) != 0) return 1; - return 0; -} -*/ -import "C" - -import ( - "encoding/json" - "fmt" - "path/filepath" - "strconv" - "strings" - "unsafe" - - "github.com/marqdo/marqdo/plugins/web/internal/app" - "github.com/marqdo/marqdo/plugins/web/internal/compose" - "github.com/marqdo/marqdo/plugins/web/internal/db" - "github.com/marqdo/marqdo/plugins/web/internal/form" - "github.com/marqdo/marqdo/plugins/web/internal/page" - "github.com/marqdo/marqdo/plugins/web/internal/plugin" - "github.com/marqdo/marqdo/plugins/web/internal/render" - "github.com/marqdo/marqdo/plugins/web/internal/session" - "github.com/marqdo/marqdo/plugins/web/internal/style" -) - -func main() {} - -//export marqdo_plugin_abi_version -func marqdo_plugin_abi_version() C.uint32_t { return 2 } - -//export marqdo_plugin_init -func marqdo_plugin_init(host *C.MarqdoHostApi) C.int { - if host == nil { - return 1 - } - C.host_save(host) - plugin.SetHost(plugin.HostFns{Query: hostQueryJSON}) - return C.register_core() -} - -//export marqdo_plugin_shutdown -func marqdo_plugin_shutdown() { - session.CloseRedis() - db.ResetPool() - plugin.Shutdown() -} - -func hostQueryJSON(name, argsJSON string) (string, error) { - cname := C.CString(name) - cargs := C.CString(argsJSON) - defer C.free(unsafe.Pointer(cname)) - defer C.free(unsafe.Pointer(cargs)) - var out, errMsg *C.char - rc := C.host_query(cname, cargs, &out, &errMsg) - outGo := cstrTakeHost(out) - errGo := cstrTakeHost(errMsg) - if rc != 0 { - if errGo == "" { - errGo = "host_query failed" - } - return "", fmt.Errorf("%s", errGo) - } - if outGo == "" { - outGo = "null" - } - return outGo, nil -} - -func cstrTakeHost(p *C.char) string { - if p == nil { - return "" - } - s := C.GoString(p) - C.host_free(unsafe.Pointer(p)) - return s -} - -func hostDup(s string) *C.char { - cs := C.CString(s) - defer C.free(unsafe.Pointer(cs)) - return C.host_strdup(cs) -} - -func replyJSON(outJSON **C.char, errMsg **C.char, v any, err error) C.int { - if err != nil { - if errMsg != nil { - *errMsg = hostDup(err.Error()) - } - return 1 - } - b, e := json.Marshal(v) - if e != nil { - if errMsg != nil { - *errMsg = hostDup(e.Error()) - } - return 1 - } - if outJSON != nil { - *outJSON = hostDup(string(b)) - } - return 0 -} - -func parseArgs(argsJSON *C.char) (map[string]any, error) { - if argsJSON == nil { - return map[string]any{}, nil - } - s := C.GoString(argsJSON) - if s == "" { - return map[string]any{}, nil - } - var m map[string]any - if err := json.Unmarshal([]byte(s), &m); err != nil { - return nil, err - } - if m == nil { - m = map[string]any{} - } - return m, nil -} - -func argStr(args map[string]any, keys ...string) (string, bool) { - for _, k := range keys { - v, ok := args[k] - if !ok || v == nil { - continue - } - switch t := v.(type) { - case string: - return t, true - case float64: - if t == float64(int64(t)) { - return strconv.FormatInt(int64(t), 10), true - } - return strconv.FormatFloat(t, 'f', -1, 64), true - case bool: - return strconv.FormatBool(t), true - case json.Number: - return t.String(), true - } - } - return "", false -} - -func argStrReq(args map[string]any, keys ...string) (string, error) { - s, ok := argStr(args, keys...) - if !ok || s == "" { - return "", fmt.Errorf("missing `%s`", keys[0]) - } - return s, nil -} - -func entryDir() string { - raw, err := plugin.Query("entry_dir", "{}") - if err != nil { - return "." - } - var s string - if json.Unmarshal([]byte(raw), &s) == nil && s != "" { - return s - } - return "." -} - -func resolveDbURL(url string) string { - lower := strings.ToLower(url) - if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") { - return url - } - stripped := url - prefix := "sqlite:" - switch { - case strings.HasPrefix(url, "sqlite:"): - stripped = strings.TrimPrefix(url, "sqlite:") - case strings.HasPrefix(url, "SQLITE:"): - stripped = strings.TrimPrefix(url, "SQLITE:") - prefix = "SQLITE:" - default: - prefix = "sqlite:" - } - if filepath.IsAbs(stripped) { - return prefix + stripped - } - abs := filepath.Join(entryDir(), stripped) - return prefix + abs -} - -func dbURLOf(args map[string]any) (string, error) { - if s, ok := argStr(args, "url", "db_url", "数据库"); ok && s != "" { - return resolveDbURL(s), nil - } - for _, key := range []string{"url", "db", "数据库"} { - if dbObj, ok := args[key].(map[string]any); ok { - if s, ok := argStr(dbObj, "url"); ok && s != "" { - return resolveDbURL(s), nil - } - } - } - return "", fmt.Errorf("missing db url") -} - -func callLib(path string) (any, error) { - payload, _ := json.Marshal(map[string]any{"path": path}) - raw, err := plugin.Query("call_lib_path", string(payload)) - if err != nil { - return nil, err - } - var v any - if err := json.Unmarshal([]byte(raw), &v); err != nil { - return nil, err - } - return v, nil -} - -func asPageMap(v any) map[string]any { - if m, ok := v.(map[string]any); ok { - return m - } - return map[string]any{} -} - -//export web_go_ready -func web_go_ready(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - _ = argsJSON - return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "impl": "go", "abi": 2}, nil) -} - -//export web_page_new -func web_page_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, page.New(args), nil) -} - -//export web_style -func web_style(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - css, err := style.Style(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, css, nil) -} - -//export web_compose_components -func web_compose_components(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - components := args["components"] - if components == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `components`")) - } - out, err := compose.ComposeComponents(pageBag, components, callLib) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_compose_main -func web_compose_main(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - main := args["main"] - if main == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `main`")) - } - out, err := compose.ComposeMain(pageBag, main, callLib) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_compose_list -func web_compose_list(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - main := args["main"] - if main == nil { - main = args["主体"] - } - if main == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `main`")) - } - query := args["query"] - if query == nil { - query = args["条件"] - } - order, _ := argStr(args, "order", "排序") - target, _ := argStr(args, "target", "插槽", "表单插槽") - out, err := compose.ComposeList(pageBag, main, query, order, target, callLib) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_compose_intro -func web_compose_intro(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - intro := args["intro"] - if intro == nil { - intro = args["引言"] - } - if intro == nil { - intro = args["table"] - } - if intro == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `intro`")) - } - out, err := compose.ComposeIntro(pageBag, intro, callLib) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_intro -func web_intro(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tbl := args["table"] - if tbl == nil { - tbl = args["intro"] - } - if tbl == nil { - tbl = args["表"] - } - if tbl == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `table`")) - } - return replyJSON(outJSON, errMsg, compose.MakeIntroHTML(tbl), nil) -} - -//export web_render -func web_render(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := asPageMap(args["page"]) - if len(pageBag) == 0 { - pageBag = args - } - dbURL, _ := dbURLOf(args) - html := render.RenderPage(pageBag, dbURL, "") - return replyJSON(outJSON, errMsg, html, nil) -} - -//export web_db_new -func web_db_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, _ := argStr(args, "url") - if url == "" { - url = "sqlite:site.db" - } - return replyJSON(outJSON, errMsg, map[string]any{ - "url": resolveDbURL(url), - "_type": "db", - }, nil) -} - -//export web_db_init -func web_db_init(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - name, err := argStrReq(args, "name", "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - fields := args["fields"] - if fields == nil { - fields = []any{} - } - out, err := db.Init(url, name, fields) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_insert -func web_db_insert(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - rows := args["rows"] - if rows == nil { - rows = args["row"] - } - if rows == nil { - rows = []any{} - } - out, err := db.Insert(url, tableName, rows, txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_select -func web_db_select(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - limit := int64(200) - if v, ok := args["limit"]; ok { - switch t := v.(type) { - case float64: - limit = int64(t) - case string: - if n, e := strconv.ParseInt(t, 10, 64); e == nil { - limit = n - } - } - } - opts := db.SelectOpts{} - if w, ok := args["where"]; ok && w != nil { - if s, ok := w.(string); ok { - if s != "" && !strings.EqualFold(s, "none") && !strings.EqualFold(s, "null") { - opts.Where = w - } - } else { - opts.Where = w - } - } - if o, ok := argStr(args, "order"); ok { - opts.Order = o - } - if v, ok := args["offset"]; ok && v != nil { - switch t := v.(type) { - case float64: - n := int64(t) - opts.Offset = &n - case string: - if n, e := strconv.ParseInt(t, 10, 64); e == nil { - opts.Offset = &n - } - } - } else if v, ok := args["跳过"]; ok && v != nil { - if t, ok := v.(float64); ok { - n := int64(t) - opts.Offset = &n - } - } - out, err := db.Select(url, tableName, limit, opts, txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_get -func web_db_get(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Get(url, tableName, id, txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_exec -func web_db_exec(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - sqlStmt, err := argStrReq(args, "sql") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Exec(url, sqlStmt, args["args"], txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_form_new -func web_form_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, _ := argStr(args, "table") - action, _ := argStr(args, "action") - id, _ := argStr(args, "id") - return replyJSON(outJSON, errMsg, form.New(tableName, action, id), nil) -} - -//export web_form_fields -func web_form_fields(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - formBag := asPageMap(args["form"]) - fields := args["fields"] - if fields == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `fields`")) - } - return replyJSON(outJSON, errMsg, form.SetFields(formBag, fields), nil) -} - -//export web_compose_form -func web_compose_form(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := args["page"] - formV := args["form"] - id, _ := argStr(args, "id") - var target *string - if t, ok := argStr(args, "target"); ok && t != "" { - target = &t - } - out, err := compose.ComposeForm(pageBag, formV, id, target) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_compose_auth_form -func web_compose_auth_form(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageBag := args["page"] - action, _ := argStr(args, "action") - if action == "" { - action, _ = argStr(args, "动作") - } - submit, _ := argStr(args, "submit") - if submit == "" { - submit, _ = argStr(args, "提交") - } - formID, _ := argStr(args, "form_id") - if formID == "" { - formID, _ = argStr(args, "表单id") - } - errID, _ := argStr(args, "err_id") - if errID == "" { - errID, _ = argStr(args, "错误id") - } - target, _ := argStr(args, "target") - if target == "" { - target, _ = argStr(args, "表单插槽") - } - next, _ := argStr(args, "next") - if next == "" { - next, _ = argStr(args, "回跳") - } - kind, _ := argStr(args, "kind") - if kind == "" { - kind, _ = argStr(args, "种类") - } - out, err := compose.ComposeAuthForm(pageBag, action, submit, formID, errID, target, next, kind) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_compose_nav_brand -func web_compose_nav_brand(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - title, _ := argStr(args, "title") - if title == "" { - title, _ = argStr(args, "标题") - } - href, _ := argStr(args, "href") - if href == "" { - href, _ = argStr(args, "链接") - } - logo, _ := argStr(args, "logo") - if logo == "" { - logo, _ = argStr(args, "标志") - } - logoLight, _ := argStr(args, "logo_light") - if logoLight == "" { - logoLight, _ = argStr(args, "浅色标志") - } - themeKey, _ := argStr(args, "theme_key") - if themeKey == "" { - themeKey, _ = argStr(args, "主题键") - } - out, err := compose.ComposeNavBrand(args["page"], title, href, logo, logoLight, themeKey) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_compose_client -func web_compose_client(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - source, _ := argStr(args, "source") - if source == "" { - source, _ = argStr(args, "源") - } - bridge, _ := argStr(args, "bridge") - if bridge == "" { - bridge, _ = argStr(args, "桥") - } - wasm, _ := argStr(args, "wasm") - out, err := compose.ComposeClient(args["page"], bridge, wasm, source) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_compose_form_load -func web_compose_form_load(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - table, _ := argStr(args, "table") - if table == "" { - table, _ = argStr(args, "表") - } - idParam, _ := argStr(args, "id_param") - if idParam == "" { - idParam, _ = argStr(args, "id参数") - } - out, err := compose.ComposeFormLoad(args["page"], table, idParam) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_app_new -func web_app_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - return replyJSON(outJSON, errMsg, app.New(args), nil) -} - -//export web_app_route -func web_app_route(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - appBag := asPageMap(args["app"]) - path, err := argStrReq(args, "path") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - pageV := args["page"] - if pageV == nil { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `page` for route")) - } - out, err := app.Route(appBag, path, pageV) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_update -func web_db_update(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - row := args["row"] - if row == nil { - row = map[string]any{} - } - out, err := db.Update(url, tableName, id, row, txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_update_if -func web_db_update_if(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - expectCol, err := argStrReq(args, "expect_col") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - expectVal, ok := args["expect_val"] - if !ok { - return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing expect_val")) - } - row := args["row"] - if row == nil { - row = map[string]any{} - } - out, err := db.UpdateIf(url, tableName, id, row, expectCol, expectVal, txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_delete -func web_db_delete(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - id, err := argStrReq(args, "id") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Delete(url, tableName, id, txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_query -func web_db_query(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - sqlStmt, err := argStrReq(args, "sql") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Query(url, sqlStmt, args["args"], txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} - -//export web_db_count -func web_db_count(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { - args, err := parseArgs(argsJSON) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - url, err := dbURLOf(args) - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - tableName, err := argStrReq(args, "table") - if err != nil { - return replyJSON(outJSON, errMsg, nil, err) - } - out, err := db.Count(url, tableName, args["where"], txnOpt(args)) - return replyJSON(outJSON, errMsg, out, err) -} diff --git a/public/00-welcome-plot-1.svg b/public/00-welcome-plot-1.svg deleted file mode 100755 index ae318f6..0000000 --- a/public/00-welcome-plot-1.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - -xy-3-2-1123-22460 - \ No newline at end of file diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md deleted file mode 100755 index 7e17537..0000000 --- a/public/00-welcome.mq.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -markup: occlusion -title: Welcome to Marqdo -description: User-docs home — code as documentation (English) -import: - math: lib/math.mq.md - foreign: lib/foreign.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Hello — and welcome. I built Marqdo so that code is documentation and documentation is code: Markdown markers are the program structure, so what you read is what runs. - -AI systems already favor Markdown-shaped output. That raised a simple question: why keep docs and programs as two separate artifacts? Marqdo is the answer. The `.mq.md` suffix exists so a file stays renderable as Markdown while remaining executable. Richer OKF-style YAML catalogs and even slide decks are on the roadmap; for now this site itself is generated by Marqdo — and that often saves tokens when an AI is writing with you. - -The language is still early: structural markers, English/Chinese builtin aliases (`print` / `打印` …), an importable standard library (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Join in at [GitHub](https://github.com/cflmy/marqdo). - -中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。 - -Want a quick hello? `marqdo run` executes the entry `# main`. Try **greet who="marqdo"**. Names can include spaces: **greet who="marqdo user"**. - -This version also runs one function on its own. `marqdo call` takes the file, the function and named arguments. The page you read is the program that runs. What that is for, and why it matters, is in [features/22-call.mq.md](features/22-call.mq.md). - -Beyond the basics, Marqdo ships table, time, text, files, system, math, foreign, and more. Math and foreign deserve a special mention. - -Write a math block and bind it with a TeX comment: - -$$ -% marqdo: var=f -x^2 - 2 -$$ - -Then plot it: **_svg = math.plot formula=`f` var="x" min=-3 max=3** - -Foreign lets you embed another language. Use Node Intl for locale-aware currency formatting, a genuine presentation boundary: - -`hi` = -```node -console.log(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(950)); -``` - -Under Markdown this stays easy to read — which is the point: code as documentation, documentation as code. - -One file, three surfaces. - -| Surface | What it is | -|---|---| -| Document | ordinary Markdown: prose, tables, links and fenced code | -| Program | the same markers are executable: assignments, calls, returns | -| Knowledge | frontmatter, links and generated catalog entries an agent can query | - -The static site you are reading is generated from these files, so the examples are not screenshots. Run the same source and you get the same page. - -Foreign v2 is a good example. Probe Node, then run the bound fence: - -We first **node = [Check the formatting runtime](foreign.probe(lang="node"))** for the next step. - -1. [ok](access(`node`, "ok")) - We first **hello = [Format the native amount](foreign.run(code=`hi`))** for the next step. - We now **[Display this step's result](> print text=`hello`)**. -2. * - We now **[Display this step's result](> print text="(node not found — install Node to run this cell)")**. - -The same module also supports JSON calls, parallel fan-out, persistent kernels and an explicit state bridge. See [stdlib/foreign.mq.md](stdlib/foreign.mq.md) and the native-first Intl walkthrough in [features/19-foreign-view-cells.mq.md](features/19-foreign-view-cells.mq.md). - -A view document is still a document. Named kernels and a cell order are ordinary bound tables: - -```text -`分析内核` = - -| 名称 | 语言 | 说明 | -|------|------|------| -| 分析 | node | shared state | -| 复核 | node | isolated state | - -`分析单元` = - -| 单元 | 内核 | 说明 | -|------|------|------| -| 准备数据 | 分析 | write | -| 计算指标 | 分析 | read | -| 独立复核 | 复核 | validate | - -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` -``` - -`marqdo view` consumes the foreign-owned `会话` handle and turns it into Run All, Step, per-cell kernels, a journal and a state panel. Without `会话`, cells are stateless one-shot runs. There is no separate interactive mode or command; `marqdo run` still executes the file as one program. - -Documentation becomes knowledge when it can be discovered, verified and reused. OKF supplies the portable Markdown + YAML shape; EKC projects the repository into catalog layers L0–L4, a graph and an engineering preflight. The source `.mq.md` remains the only authority; generated artifacts are marked and rebuildable. - -| Loop | Question | -|---|---| -| OKF | How do people and agents share a readable knowledge page? | -| EKC | What existing capability, decision, constraint or failure should be reused before creating more? | -| Preflight | REUSE → ADAPT → CREATE | - -Read [features/20-okf-ekc.mq.md](features/20-okf-ekc.mq.md) for the concepts and commands. - -Welcome again — enjoy exploring Marqdo. - -Installation choices. - -Install the interpreter (CLI) in any of these ways: - -| Way | Notes | -|------|------| -| Ubuntu PPA | sudo add-apt-repository ppa:cflmy/marqdo then sudo apt install marqdo | -| GitHub Releases | Prebuilt Windows / Linux packages from [releases](https://github.com/cflmy/marqdo/releases) | -| From source | cargo build --release (needs a local Rust toolchain) | - -Official extensions update independently of the CLI: - -```text -marqdo ext add web -marqdo ext add quantum -``` - -`ext add` tries CDN https://ext.marqdo.com first, then GitHub, then the proxy mirror. See [`features/05-extensions.mq.md`](features/05-extensions.mq.md). - - -## greet - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| who | any | required | Recipient name inserted into the greeting | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; this function performs the described effects instead of returning business data | - -When we meet a visitor `who`, we **print text="Welcome, `who`!"** and close with*None*. diff --git a/public/00-欢迎-plot-1.svg b/public/00-欢迎-plot-1.svg deleted file mode 100755 index ae318f6..0000000 --- a/public/00-欢迎-plot-1.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - -xy-3-2-1123-22460 - \ No newline at end of file diff --git a/public/00-欢迎.mq.md b/public/00-欢迎.mq.md deleted file mode 100755 index 48959a4..0000000 --- a/public/00-欢迎.mq.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -markup: occlusion -title: 欢迎使用 Marqdo -description: 用户文档首页 — 代码即文档(中文版) -导入: - 数学: lib/数学.mq.md - 外联: lib/外联.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门「代码即文档,文档即代码」的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。 - -AI 偏爱 Markdown 结构的输出。我当时的念头很简单——何必再把文档和代码拆成两套?于是有了 marqdo。为了让文件既能当文档渲染又能执行,后缀定为 `.mq.md`。更远的目标还有 OKF 式知识库的 YAML、甚至自动生成 PPT;眼下它至少已经是个不错的博客工具——对,这个站点就是 Marqdo 生成的。AI 写 `.mq.md` 时往往更省 token,钱包也会轻松一点。 - -语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(见本站 [`stdlib/`](stdlib/))、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。 - -English docs: [`00-welcome.mq.md`](00-welcome.mq.md)(English prose and English builtins). - -想先打个招呼?`marqdo run` 会运行入口 `# main`。比如:**问候 谁="marqdo"**。名字里可以带空格:**问候 谁="marqdo user"**。 - -从这一版起,不必为了试用一个函数再包一层入口。`marqdo call` 直接运行文件里的某个函数,参数写在命令上。同一页仍然是给人读的文档。作用和价值写在 [features/22-函数调用.mq.md](features/22-函数调用.mq.md)。 - -除了这些基本面,标准库里还有表、时间、文本、文件、系统、数学、外联等。我特别想提数学和外联。 - -比方说,直接写一块公式,并用 TeX 注释标上变量名: - -$$ -% marqdo: var=f -x^2 - 2 -$$ - -接着画出来:**_svg = 数学.绘图 formula=`f` var="x" min=-3 max=3** - -外联则允许嵌一段别的语言。把`hi`绑成下面这样即可: - -`hi` = -```node -console.log(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(950)); -``` - -这些在 Markdown 里读起来仍然像文章——这就是 marqdo 想坚持的:代码即文档,文档即代码。 - -一份文件,三个面。 - -| 面 | 是什么 | -|---|---| -| 文档 | 普通 Markdown:叙述、表格、链接、围栏代码 | -| 程序 | 同一批标记可执行:赋值、调用、返回 | -| 知识 | frontmatter、链接与生成的 catalog 条目,Agent 可查询 | - -你正在读的静态站就是由这些文件生成的,所以示例不是截图。运行同一份源,会得到同一页。 - -外联 v2 是个好例子。先探测 Node,再运行绑定围栏: - -我们先**node = [检查本地化展示所需的解释器](外联.探测(语言="node"))**,供下一步使用。 - -1. [ok](access(`node`, "ok")) - 我们先**问候 = [通过 Intl 展示原生金额](外联.运行(代码=`hi`))**,供下一步使用。 - 随后我们**[显示当前步骤的结果](> 打印 内容=`问候`)**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="(未找到 node — 安装 Node 后可运行此单元)")**。 - -同一个模块还支持 JSON 调用、并行扇出、持久内核与显式状态桥。见 [stdlib/外联.mq.md](stdlib/外联.mq.md) 与原生分析与 Intl 示例 [features/19-外联视图单元.mq.md](features/19-外联视图单元.mq.md)。 - -view 仍然是一篇文档。命名内核与单元顺序就是普通绑定表: - -```text -`分析内核` = - -| 名称 | 语言 | 说明 | -|------|------|------| -| 分析 | node | 共享状态 | -| 复核 | node | 隔离状态 | - -`分析单元` = - -| 单元 | 内核 | 说明 | -|------|------|------| -| 准备数据 | 分析 | 写入 | -| 计算指标 | 分析 | 读取 | -| 独立复核 | 复核 | 校验 | - -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` -``` - -`marqdo view` 消费 foreign 拥有的 `会话` 句柄,变成 Run All、Step、每单元内核、journal 与状态面板。没有 `会话` 时,单元是无状态的一次性运行。没有单独的交互模式或命令;`marqdo run` 仍然把文件当单个程序运行。 - -文档能被发现、验证和复用时,才成为知识。OKF 提供可移植的 Markdown + YAML 形态;EKC 把仓库投影成 catalog L0–L4、图与工程 preflight。源 `.mq.md` 始终是唯一权威,生成物有标记、可重建。 - -| 循环 | 问题 | -|---|---| -| OKF | 人和 Agent 如何共享一页可读知识? | -| EKC | 创建之前,应该复用哪些已有能力、决策、约束与失败? | -| Preflight | REUSE → ADAPT → CREATE | - -概念与命令见 [features/20-OKF与EKC.mq.md](features/20-OKF与EKC.mq.md)。 - -最后,再次欢迎你,尽情体验 marqdo 吧! - -安装方式。 - -解释器(CLI)任选其一: - -| 方式 | 说明 | -|------|------| -| Ubuntu PPA | sudo add-apt-repository ppa:cflmy/marqdo 后 sudo apt install marqdo | -| GitHub Releases | [releases](https://github.com/cflmy/marqdo/releases) 下载 Windows / Linux 预编译包 | -| 源码 | cargo build --release(需本机 Rust) | - -官方扩展与 CLI 可分开更新。安装扩展: - -```text -marqdo ext add web -marqdo ext add quantum -``` - -`ext add` 下载顺序:CDN https://ext.marqdo.com → GitHub → proxy 镜像。详见本站 [`features/05-扩展.mq.md`](features/05-扩展.mq.md)。 - - -## 问候 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 谁 | any | 必填 | 要显示在问候中的称呼 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;本函数通过上述操作产生效果,不返回业务数据。 | - -见到访客`谁`时,我们 **打印 内容="欢迎,`谁`!"**,然后收束为*None*。 diff --git a/public/README.md b/public/README.md deleted file mode 100755 index 23ad736..0000000 --- a/public/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# 用户文档(可执行 · 可下载 · 中英双语) - -本目录即面向访客的 Marqdo 介绍:每个 `.mq.md` 既是文稿也能 `marqdo run`,并随仓库 / 静态站一起下载。 - -**双语约定:** 拉丁文件名 → 英文叙述与英文内置;中文文件名 → 中文叙述与中文编程。成对放在同一目录。标准库:拉丁路径用英文 API,中文路径用中文 API;JSON 仅 `lib/json.mq.md`。 - -| 路径 | 内容 | -|------|------| -| [`00-welcome.mq.md`](00-welcome.mq.md) / [`00-欢迎.mq.md`](00-欢迎.mq.md) | 首页(英 / 中) | -| [`structure/`](structure/) | 基本结构 | -| [`keywords/`](keywords/) | 关键字与 L0 内置 | -| [`stdlib/`](stdlib/) | **标准库**(导入方式 + text/表/文件/时间/系统/json/网络/数学/外联/插件/**自写回**/**子任务**;v0.1.2+ 内置于 CLI) | -| [`features/`](features/) | 特性迭代(含对象、官方 `ext/`) | -| [`features/19-foreign-view-cells.mq.md`](features/19-foreign-view-cells.mq.md) / [`19-外联视图单元.mq.md`](features/19-外联视图单元.mq.md) | 外联 v2 完整 Python 示例:probe / JSON call / 并行 / 持久内核 / 状态桥 / view 单元 | -| [`features/20-okf-ekc.mq.md`](features/20-okf-ekc.mq.md) / [`20-OKF与EKC.mq.md`](features/20-OKF与EKC.mq.md) | 代码即文档、文档即知识:OKF 形态与 EKC 工程知识编译器 | -| [`features/21-persistence.mq.md`](features/21-persistence.mq.md) / [`21-持久化.mq.md`](features/21-持久化.mq.md) | 外联结果持久化:静态快照与 writeback | -| [`features/22-call.mq.md`](features/22-call.mq.md) / [`22-函数调用.mq.md`](features/22-函数调用.mq.md) | `marqdo call`:同一份文档按函数执行,知识可以直接当工具 | - -官方扩展(非 stdlib):`ext/llm`、`ext/agent`、`ext/web`、`ext/quantum`、`ext/linalg` — 见 `features/05-*.mq.md`、`06-*.mq.md`、`07-linalg.mq.md` / `07-线性代数.mq.md` 与 `doc/design/ext-*.md`。 - -中层标准库(Mid):`08`–`12`(re/encoding · path/fs · hash/secrets · csv/text · list/cli;及对应中文页)。 - -**不放** `errors/`:失败样例只在 `tests/errors/`。 - -开发文档在 [`doc/`](../doc/)。 - -## 浏览与生成 HTML - -```bash -cargo run -- view public -cargo run -- view output public -o public -``` - -详见 [user-site.md](../doc/design/user-site.md)。 diff --git a/public/features/01-phase-i-treewalk.mq.md b/public/features/01-phase-i-treewalk.mq.md deleted file mode 100755 index 09858fd..0000000 --- a/public/features/01-phase-i-treewalk.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: Phase I — tree-walk interpreter -description: Lex · parse · check · tree-walk end to end ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Milestone: Phase I (tree-walk). - -Pipeline: load → line classify → recursive-descent parse → semantic check → tree-walk eval. No Flex/Bison. - -This page runs as a program — documentation is executable: - -We now **[Display this step's result](> print text="Phase I: tree-walk interpreter is live.")**. diff --git a/public/features/01-树遍历.mq.md b/public/features/01-树遍历.mq.md deleted file mode 100755 index 8609ea2..0000000 --- a/public/features/01-树遍历.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: 第一阶段 — 树遍历解释器 -description: 词法 · 语法 · 语义 · 树遍历已贯通 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -里程碑:第一阶段(树遍历)。 - -流水线:加载 → 行分类 → 递归下降语法 → 语义检查 → 树遍历执行。实现不用 Flex/Bison。 - -本页本身即可运行,证明「文档即程序」已落地: - -随后我们**[显示当前步骤的结果](> 打印 内容="第一阶段:树遍历解释器已就绪。")**。 diff --git a/public/features/02-bytecode.mq.md b/public/features/02-bytecode.mq.md deleted file mode 100755 index b83a3e2..0000000 --- a/public/features/02-bytecode.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: Bytecode backend -description: `--backend bytecode` shares semantics with tree-walk ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Milestone: bytecode prototype. - -The same `.mq.md` runs on tree-walk or the bytecode VM: - - marqdo run FILE --backend tree - - marqdo run FILE --backend bytecode - -Output matches on both backends: - -We now **[Display this step's result](> print text="Bytecode backend: same program, alternate engine.")**. diff --git a/public/features/02-字节码.mq.md b/public/features/02-字节码.mq.md deleted file mode 100755 index 389f2ab..0000000 --- a/public/features/02-字节码.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: 字节码后端 -description: `--backend bytecode` 与树遍历共用语义 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -里程碑:字节码原型。 - -同一套 `.mq.md` 可用树遍历或字节码 VM: - - marqdo run FILE --backend tree - - marqdo run FILE --backend bytecode - -两种后端输出一致: - -随后我们**[显示当前步骤的结果](> 打印 内容="字节码后端:同一程序,另一引擎。")**。 diff --git a/public/features/03-view-and-docs.mq.md b/public/features/03-view-and-docs.mq.md deleted file mode 100755 index 4bb18ba..0000000 --- a/public/features/03-view-and-docs.mq.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -markup: occlusion -title: view and the user docs site -description: Local browse and static export from the interpreter ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Version 2.6.0 keeps action descriptions in the sentence and moves their implementation to side notes. Empty parentheses explicitly mark missing logic. Multiple actions and returns keep their original prose, while ordinary links remain navigation. On compact screens, native disclosures keep the implementation readable even without JavaScript. - -Executable knowledge now presents inputs, returns, effects, dependencies and separate verification facts. Technical identities and digests stay folded. Source explanations are distinct from captured results; a pure effect summary or linked source is not proof that a program ran or its content was verified. - -The reader introduced in 2.5.1: `marqdo view` and `view output` share a warm paper reader with a new -Marqdo logo, serif document text, botanical ornaments, navigation, search and a -floating action toolbar. Wide screens place real execution notes in the margins; -compact screens keep them below the corresponding paragraph. Click a note to -inspect its full captured value. Call and loop frame selectors remain available. - -Static exports embed decorations, KaTeX and math fonts for offline reading. The -play button runs the document in live view; static pages retain their captured -results and explain how to start a live view. Ordinary document reruns update -prose, bindings and notes from the same execution capture. - -Annotations follow the exact source span across calls and loop iterations. Flowing -curves and staggered margin notes avoid source text and neighboring connections. -The floating toolbar labels its actions: refresh, settings, run, clear and more. - -Local: `marqdo view public` - -Static export: `marqdo view output public -o public` - -Browse Structure keeps narration, highlights executable markers, and attaches -run results (values, taken branch arms, call/loop frames). The same render path -builds this user docs site; CI publishes to `gh-pages`. - -We now **[Display this step's result](> print text="Docs site: generated by the Marqdo interpreter, not hand-written HTML.")**. diff --git a/public/features/03-view与文档.mq.md b/public/features/03-view与文档.mq.md deleted file mode 100755 index cbf505b..0000000 --- a/public/features/03-view与文档.mq.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -markup: occlusion -title: view 与用户文档站 -description: 本地浏览与静态导出由解释器生成 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -版本 2.6.0 将动作说明留在句子里,实际实现引到侧注;空圆括号明确提示待补逻辑。同一句话可以保留多个调用与返回,普通链接仍是导航。窄屏使用原生可展开详情,没有 JavaScript 也能查看实现。 - -可执行知识先展示输入、返回、调用边界、依赖和分别列出的验证依据,技术身份与摘要按需展开。源码说明与运行捕获有不同含义;pure、来源关联或构造配置都不能被当作已运行或内容已验证的证据。 - -沿用 2.5.1 的阅读底座:`marqdo view` 与 `view output` 共用暖白金色阅读界面,新 Marqdo 标志、 -衬线正文、花枝装饰、导航搜索与底部悬浮工具栏。宽屏将真实执行结果沿左右页边引出, -窄屏将标注放回对应段落下方;点击标注可查看完整捕获值,调用帧和循环轮次仍可切换。 - -静态导出内嵌装饰素材、KaTeX 与数学字体,断网也能阅读公式。播放按钮在实时 view 中 -运行文档;静态页面保留导出结果,并提示如何启动实时 view。普通文档重跑后,正文、 -变量和执行标注使用同一次执行捕获同步刷新。 - -执行标注跨调用帧与循环轮次精确对应源码区间。连续曲线与错落标注会避让正文和相邻连线; -底部工具栏显示“刷新、设置、运行、清理、更多”,深浅色配色保持一致。 - -本地浏览:`marqdo view public` - -静态导出:`marqdo view output public -o public` - -Browse Structure 保真叙述、高亮可执行标记,并挂载运行结果(变量值、分支命中臂、调用/循环帧)。 -用户站与 live view 同源渲染;CI 发布到 `gh-pages`。 - -随后我们**[显示当前步骤的结果](> 打印 内容="文档站:由 Marqdo 解释器生成,不是手写 HTML。")**。 diff --git a/public/features/04-objects.mq.md b/public/features/04-objects.mq.md deleted file mode 100755 index a0d6f71..0000000 --- a/public/features/04-objects.mq.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -markup: occlusion -title: Objects and methods -description: Sharp heading is a type; deeper headings are functions or methods ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -In Marqdo, a single sharp (#) defines an object / type constructor. Double sharp and deeper (## …) define free functions or methods. Constructing an object yields a map handle tagged with _type. Call methods with backtick object, then dot, then method name. - -See doc/design/objects.md. Example gold: tests/structure/object-handle.mq.md. Official ext/llm and ext/agent use this pattern. - -We now **[Display this step's result](> print text="objects-ok")**. diff --git a/public/features/04-对象.mq.md b/public/features/04-对象.mq.md deleted file mode 100755 index 3ad2191..0000000 --- a/public/features/04-对象.mq.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -markup: occlusion -title: 对象与方法 -description: 一级标题是类型;更深标题是函数或方法 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -Marqdo 中,单个井号(#)定义对象 / 类型构造体;二级及以上(## …)定义自由函数或方法。构造得到带 _type 标记的 map 句柄。方法调用形如:反引号对象、点、方法名。 - -详见 doc/design/objects.md。金样例:tests/structure/object-handle.mq.md。官方 ext/llm 与 ext/agent 使用同一模式。 - -随后我们**[显示当前步骤的结果](> 打印 内容="对象就绪")**。 diff --git a/public/features/05-extensions.mq.md b/public/features/05-extensions.mq.md deleted file mode 100755 index c64cec1..0000000 --- a/public/features/05-extensions.mq.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -markup: occlusion -title: Official extensions (ext/) -description: Optional packages — not stdlib ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -ext/ holds official optional extensions. They are not part of lib/. Resolve via `~/.marqdo/ext`, MARQDO_EXT, ./ext, or ext/ next to the binary. - -Install (v0.2+): - -```text -marqdo ext list -marqdo ext add llm -marqdo ext add agent -marqdo ext add web -marqdo ext add quantum -marqdo ext add linalg -``` - -`ext add` downloads L1 sources and prebuilt natives when available. Order: CDN https://ext.marqdo.com → GitHub Releases → proxy mirror. Pack SemVer is `ext/VERSION` and may differ from the CLI. - -Rebuild natives locally only when developing plugins: - -```text -cargo build --release -p marqdo_plugin_agent -cargo build --release -p marqdo_plugin_quantum -cargo build --release -p marqdo_plugin_linalg -bash ./scripts/build-web-plugin.sh -marqdo ext add agent -marqdo ext add web -marqdo ext add quantum -``` - -Packages (not Markdown list markers — those are loops in Marqdo): - -ext/llm — OpenAI-compatible chat. Design: doc/design/ext-llm.md - -ext/agent — agent framework + native plugin. Design: doc/design/ext-agent.md - -ext/web provides Documents/Endpoints, recursive View, document-head and request resources. Decompose layout to Markdown or native-control leaves; data, authentication and transport belong to ext/data, ext/security and ext/net. Follow examples/web-site/index.mq.md and examples/web-net-site/index.mq.md for complete workflows. Browser interaction uses Marqdo clients and the official WASM bridge. Development, builds and real acceptance run through marqdo call in skills/marqdo-dev/index.mq.md; the current author contract starts at ext/web/index.mq.md. - -ext/quantum — circuits, draw, noise, formula matrix custom gates, Q7 density/viz, Q8 themed SVG (`theme=dark|light|bw`). Design: doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md - -Installer: marqdo ext list / add / remove — doc/design/ext-cli.md - -Native plugins: lib/plugin + include/marqdo_abi.h — doc/design/ext-abi.md - -We now **[Display this step's result](> print text="ext-ok")**. diff --git a/public/features/05-扩展.mq.md b/public/features/05-扩展.mq.md deleted file mode 100755 index 9ab5f76..0000000 --- a/public/features/05-扩展.mq.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -markup: occlusion -title: 官方扩展(ext/) -description: 可选包 — 不是标准库 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -ext/ 存放官方可选扩展,不属于 lib/。解析顺序:`~/.marqdo/ext`、MARQDO_EXT、./ext、或可执行文件旁的 ext/。 - -安装(v0.2+): - -```text -marqdo ext list -marqdo ext add llm -marqdo ext add agent -marqdo ext add web -marqdo ext add quantum -marqdo ext add linalg -``` - -`ext add` 会下载 L1 与预编译 native(若有)。下载顺序:CDN https://ext.marqdo.com → GitHub Releases → proxy 镜像。扩展包版本见 `ext/VERSION`,可与 CLI 分开发版。 - -带原生插件的包若需本地重编: - -```text -cargo build --release -p marqdo_plugin_agent -cargo build --release -p marqdo_plugin_quantum -cargo build --release -p marqdo_plugin_linalg -bash ./scripts/build-web-plugin.sh -marqdo ext add agent -marqdo ext add web -marqdo ext add quantum -``` - -扩展包(勿用 Markdown `-` 列表:在 Marqdo 里 `-` 是循环): - -ext/llm(大模型)— OpenAI 兼容聊天。设计:doc/design/ext-llm.md - -ext/agent(智能体)— 智能体框架 + 原生插件。设计:doc/design/ext-agent.md - -ext/web(网页)提供 Document/Endpoint、递归 View、页头和请求资源。布局拆到 Markdown 或原生控件叶子,数据、鉴权与运输分别归 ext/data、ext/security、ext/net。完整实践见 examples/web-site-zh/index.mq.md 与 examples/web-net-site-zh/index.mq.md;浏览器交互通过 Marqdo 客户端及官方 WASM 桥完成。开发、构建和真实验收入口为 skills/marqdo-dev/index.mq.md,操作使用 marqdo call;当前作者契约见 ext/web/网页/索引.mq.md。 - -ext/quantum(量子)— 电路、绘图、噪声、公式矩阵自定义门、Q7 密度/高级图、Q8 主题 SVG(`主题=dark|light|bw`)。设计:doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md - -安装器:marqdo ext list / add / remove — doc/design/ext-cli.md - -通用原生插件:lib/plugin + include/marqdo_abi.h — doc/design/ext-abi.md - -随后我们**[显示当前步骤的结果](> 打印 内容="扩展就绪")**。 diff --git a/public/features/06-quantum-plot-1.svg b/public/features/06-quantum-plot-1.svg deleted file mode 100755 index 6409a88..0000000 --- a/public/features/06-quantum-plot-1.svg +++ /dev/null @@ -1 +0,0 @@ -100000.501110.50 \ No newline at end of file diff --git a/public/features/06-quantum-plot-2.svg b/public/features/06-quantum-plot-2.svg deleted file mode 100755 index 2091dae..0000000 --- a/public/features/06-quantum-plot-2.svg +++ /dev/null @@ -1 +0,0 @@ -H matrix000.7070.707110.707-0.707 \ No newline at end of file diff --git a/public/features/06-quantum.mq.md b/public/features/06-quantum.mq.md deleted file mode 100755 index 25163d3..0000000 --- a/public/features/06-quantum.mq.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -markup: occlusion -title: Quantum circuits (ext/quantum) -description: Official quantum simulator — tables, gates, Q7 density, Q8 themed SVG -import: - quantum: ext/quantum/circuit/index.mq.md - gate: ext/quantum/gate/index.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Optional package (not stdlib). Install: `marqdo ext add quantum` (or build `marqdo_plugin_quantum`). - -GHZ (3 qubits): H on q0, then CX 0→1 and 0→2. Ideal |000⟩ / |111⟩ each ≈ 1/2. - -Q7: Bell density, partial trace, Schmidt, `draw kind=hinton` / qsphere — `examples/quantum-entanglement/`. - -Q8: `draw theme="dark"|"light"|"bw"` (default dark lab look) on circuit / probs / bloch. Rebuild plugin then `ext add` so view loads the new native lib. - -`steps` = - -| step | gate | qubits | -|------|------|--------| -| 1 | H | 0 | -| 2 | CX | 0,1 | -| 3 | CX | 0,2 | - -We first **qc = [Compute qc](quantum.circuit(qubits=3, steps=`steps`))** for the next step. -We first **p = [Compute p](> `qc`.probabilities)** for the next step. -We first **_ = [Compute _](> `qc`.draw kind="probs" theme="dark")** for the next step. -We first **H = [Compute H](gate.gate(name="H"))** for the next step. -We first **__ = [Compute __](> `H`.draw kind="matrix")** for the next step. - -We now **[Display this step's result](> print text=`p`)**. -We now **[Display this step's result](> print text="quantum-feature-ok")**. diff --git a/public/features/06-量子-plot-1.svg b/public/features/06-量子-plot-1.svg deleted file mode 100755 index fe619c4..0000000 --- a/public/features/06-量子-plot-1.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - -100000.501110.50 \ No newline at end of file diff --git a/public/features/06-量子-plot-2.svg b/public/features/06-量子-plot-2.svg deleted file mode 100755 index 2091dae..0000000 --- a/public/features/06-量子-plot-2.svg +++ /dev/null @@ -1 +0,0 @@ -H matrix000.7070.707110.707-0.707 \ No newline at end of file diff --git a/public/features/06-量子.mq.md b/public/features/06-量子.mq.md deleted file mode 100755 index ea78855..0000000 --- a/public/features/06-量子.mq.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -markup: occlusion -title: 量子电路(ext/quantum) -description: 官方量子模拟 — 表、门、Q7 密度与高级图、Q8 主题 SVG -导入: - 量子: ext/quantum/量子/电路/索引.mq.md - 门: ext/quantum/量子/门/索引.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -可选扩展(非 stdlib)。安装:`marqdo ext add quantum`(或编译 `marqdo_plugin_quantum`)。 - -中文面在同包 `ext/quantum/量子/`(根 skill:`索引.mq.md`),与英文模块树并列、不混排 API。 - -GHZ(3 比特):q0 哈达玛,再控非 0→1、0→2。理想 |000⟩ / |111⟩ 各约 1/2。 - -Q7:密度 / 部分迹 / Schmidt / `绘图 种类=hinton` 等 — `examples/quantum-entanglement/`。 - -Q8:`绘图 主题="dark"|"light"|"bw"`(默认 dark 科技感)作用于电路 / 概率 / 布洛赫。改插件后须再 `ext add`,view 才会加载新 `.so`。 - -`步骤` = - -| 步 | 门 | 比特 | -|----|----|------| -| 1 | H | 0 | -| 2 | CX | 0,1 | -| 3 | CX | 0,2 | - -我们先**qc = [计算并保存 qc](量子.电路(比特数=3, 步骤=`步骤`))**,供下一步使用。 -我们先**p = [计算并保存 p](> `qc`.概率)**,供下一步使用。 -我们先**_ = [计算并保存 _](> `qc`.绘图 种类="probs" 主题="dark")**,供下一步使用。 -我们先**H = [计算并保存 H](门.门(名="H"))**,供下一步使用。 -我们先**__ = [计算并保存 __](> `H`.绘图 种类="matrix")**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`p`)**。 -随后我们**[显示当前步骤的结果](> 打印 内容="量子特性-ok")**。 diff --git a/public/features/07-linalg.mq.md b/public/features/07-linalg.mq.md deleted file mode 100755 index 64ca0fb..0000000 --- a/public/features/07-linalg.mq.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -markup: occlusion -title: How to write a linear-algebra formula document -description: ext/linalg formula-doc — declare, infix, run-implies-correct -import: - la: ext/linalg/linalg.mq.md ---- - -# Formula documents with ext/linalg - - -Not stdlib. Install: `marqdo ext add linalg` (or build `marqdo_plugin_linalg`). - -*Idea:* if the `.mq.md` runs and the asserted form matches, the identity holds under the library rules. Algebra reads like a lecture; `factorize` / `lstsq` / `draw` stay explicit calculation steps. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Declare symbols in a table, multiply, transpose — `T_ascii` is one-step display (auto-simplify). - -`shapes` = - -| @ | name | rows | cols | -|---|------|------|------| -| 1 | A | 2 | 3 | -| 2 | B | 3 | 2 | - -We first **env = [Compute env](la.declare(table=`shapes`))** for the next step. -We first **A = [A](access(`env`, "A"))** for the next step. -We first **B = [B](access(`env`, "B"))** for the next step. -We first **P = (`A` * `B`)** for the next step. -We first **t = [Compute t](> `P`.T_ascii)** for the next step. -We now **[Display this step's result](> print text=`t`)**. -1. `t` == "B^T*A^T" - We now **[Display this step's result](> print text="formula-doc-ok")**. -2. * - We now **[Display this step's result](> print text="formula-doc-fail")**. - -We now **[Display this step's result](> print text="see-examples-linalg-transpose")**. diff --git a/public/features/07-线性代数.mq.md b/public/features/07-线性代数.mq.md deleted file mode 100755 index 73aa26f..0000000 --- a/public/features/07-线性代数.mq.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -markup: occlusion -title: 如何写线性代数公式文档 -description: ext/linalg 公式文档面 — 声明、中缀、跑通即正确 -导入: - la: ext/linalg/线性代数.mq.md ---- - -# 用 ext/linalg 写公式文档 - -可选扩展(非 stdlib)。安装:`marqdo ext add linalg`(中文 id:`线性代数`)。 - -*思想:* `.mq.md` 能跑通且断言的规范形一致,则在库规则下该恒等式成立。代数叙述像讲义;`分解` / `最小二乘` / `绘图` 才是显式计算步骤。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -这里讨论符号表达式的形状,而不是对矩阵中的每个数值做计算。先声明 A 为两行三列、B 为三行两列,乘积才具有合法的二行二列形状;转置时两个因子的顺序交换,得到 B^T*A^T。输出相符只证明本例在库定义的规范化规则下成立,不意味着任意数值近似或未声明符号也会被接受。 - -阅读时先看形状表,再看乘法和转置的动作说明。公式库需要对应的原生插件,缺少依赖时应先安装 linalg;不要把插件加载错误当成恒等式不成立。此例不读取或写入业务文件,也不把输出字符串重新执行成代码。需要实际矩阵分解时,沿文件开头的导入路径阅读分解函数的独立契约。 - -用表声明符号,再乘与转置 — `转置文本` 一步展示(默认化简)。 - -`形状` = - -| @ | 名 | 行 | 列 | -|---|----|----|----| -| 1 | A | 2 | 3 | -| 2 | B | 3 | 2 | - -我们先**环境 = [声明带有行列约束的符号环境](la.声明(表=`形状`))**,供下一步使用。 -我们先**A = [A](access(`环境`, "A"))**,供下一步使用。 -我们先**B = [B](access(`环境`, "B"))**,供下一步使用。 -我们先**P = (`A` * `B`)**,供下一步使用。 -我们先**t = [取得当前步骤的转置公式或随机令牌](> `P`.转置文本)**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=`t`)**。 -1. `t` == "B^T*A^T" - 随后我们**[显示当前步骤的结果](> 打印 内容="formula-doc-ok")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="formula-doc-fail")**。 - -随后我们**[显示当前步骤的结果](> 打印 内容="see-examples-linalg-transpose")**。 diff --git a/public/features/08-re-encoding.mq.md b/public/features/08-re-encoding.mq.md deleted file mode 100755 index d4ed0ca..0000000 --- a/public/features/08-re-encoding.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — regex and encoding -description: lib/re + lib/encoding without plugins (Mid M1) -import: - re: lib/re.mq.md - enc: lib/encoding.mq.md ---- - -# Regex and encoding in lib/ - - -Mid-tier stdlib: everyday primitives stay in `lib/`, not ABI plugins. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **ok = [Compute ok](re.is_match(text="user@example.com", pattern="^[^@]+@[^@]+$"))** for the next step. -We first **tok = [Compute tok](enc.base64_encode(text="marqdo"))** for the next step. -We first **hex = [Compute hex](enc.hex_encode(text="ok"))** for the next step. -We now **[Display this step's result](> print text=`ok`)**. -We now **[Display this step's result](> print text=`tok`)**. -We now **[Display this step's result](> print text=`hex`)**. -1. `ok` - We now **[Display this step's result](> print text="mid-m1-ok")**. -2. * - We now **[Display this step's result](> print text="mid-m1-fail")**. diff --git a/public/features/08-正则编解码.mq.md b/public/features/08-正则编解码.mq.md deleted file mode 100755 index d812f5d..0000000 --- a/public/features/08-正则编解码.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 正则与编解码 -description: lib/正则 + lib/编码,无需插件(中层 M1) -导入: - 正则: lib/正则.mq.md - 编码: lib/编码.mq.md ---- - -# 标准库中的正则与编解码 - -中层标准库:日常原语进 `lib/`,不必 ABI 插件。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -本例从固定的邮箱样式文本开始:正则只检查是否符合给定模式,并不是邮件地址真实性验证。随后把普通 UTF-8 文本分别编码成 Base64 和十六进制,以展示三种返回值的区别:匹配结果是布尔值,两种编码结果是文本。编码后的文本可以继续传给解码函数,还原原始字节或文字。 - -编码不具有保密作用,也不会替调用方校验邮箱能否接收消息。这里没有网络请求、文件读写或插件安装;所有输入都来自正文中的字面值。实际接入用户输入时要保留模式与编码函数的错误诊断,不能用空字符串代替失败。最后的标记只检查本例的匹配分支,不能代替编码往返和非法输入的验收。 - -我们先**ok = [检查给定模式是否匹配邮箱样式](正则.匹配(内容="user@example.com", 模式="^[^@]+@[^@]+$"))**,供下一步使用。 -我们先**tok = [把文本编码为 Base64](编码.基64编码(内容="marqdo"))**,供下一步使用。 -我们先**hex = [把文本编码为十六进制](编码.十六进制编码(内容="ok"))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=`ok`)**。 -随后我们**[显示当前步骤的结果](> 打印 内容=`tok`)**。 -随后我们**[显示当前步骤的结果](> 打印 内容=`hex`)**。 -1. `ok` - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m1-ok")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m1-fail")**。 diff --git a/public/features/09-path-fs.mq.md b/public/features/09-path-fs.mq.md deleted file mode 100755 index 2a8f866..0000000 --- a/public/features/09-path-fs.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: Path algebra and isolated native file copying -import: - path: lib/path.mq.md - fs: lib/fs.mq.md ---- - -This page composes native path and filesystem libraries. Call main with fs.write and a disposable --fs-root; the return contains actual observations for a caller or View. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Joined/normalized path text and actual copied content | - -Joining and normalizing transform path text without granting filesystem access. The illustrative out/demo.txt is not an actual write destination. All real IO uses a unique native temporary directory, so this page neither requires a pre-existing out directory nor overwrites a caller's same-named files. - -Grant fs.write and choose a disposable root. Native encoding, path and root checks still apply. Read the copied content before cleaning this run's directory; the returned value should be path-m2. The result contains observations rather than live file paths. An intermediate failure retains its native diagnostic and can leave this run's directory for inspection and caller cleanup. - -The complete flow demonstrates text-only path algebra, actual writing, copying, reading and scoped cleanup. A normalized string is not a filesystem permission, and a printed marker alone would not prove what bytes were copied. - -We **requested = [Join the illustrative output path](path.join(a="out", b="demo.txt"))** and **normalized = [Remove redundant path segments without filesystem IO](path.normalize(path="out/./x/../demo.txt"))** before the file demonstration. -For actual IO we **work = [Create a unique directory inside the granted root](fs.temp_dir(prefix="path-demo"))** and **original = [Name this run own source file](path.join(a=`work`, b="demo.txt"))** and **copied = [Name its isolated copy](path.join(a=`work`, b="demo-copy.txt"))**. -We **[Write the actual text to copy](fs.write_text(path=`original`, text="path-m2"))** and **[Copy only this run own file](fs.copy_file(src=`original`, dest=`copied`))**. -We **copied_text = [Observe the actual copied content](fs.read_text(path=`copied`))** and then **[Clean only this run unique directory](fs.remove_tree(path=`work`))**. - -`observed` = - -| requested | normalized | copied_text | -|---|---|---| -| `requested` | `normalized` | `copied_text` | - -After the isolated file operation we return *observed*. The temporary files have been removed. diff --git a/public/features/09-路径文件.mq.md b/public/features/09-路径文件.mq.md deleted file mode 100755 index 1cdf6cf..0000000 --- a/public/features/09-路径文件.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: 路径代数与隔离的原生文件复制 -import: - 路径: lib/路径.mq.md - 文件: lib/文件.mq.md ---- - -本页直接使用路径库和文件库。调用 main 时授权 fs.write,并将 --fs-root 指向可丢弃的工作目录。函数返回实际观察记录,View 可以显示这些值;无需生成外部脚本。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 路径拼接文本、规范化文本与实际复制正文 | - -路径拼接和规范化先处理文本,不隐含文件访问授权。out/demo.txt 只是这个代数示例的输入,不会成为实际写入目的地。真正的文件操作全部放在通过固有库创建的唯一临时目录里,因此不要求已有 out 目录,也不覆盖用户的同名文件。 - -调用需要 fs.write,文件库仍会检查授权根目录、编码与路径边界。复制后的正文应为 path-m2。保存这个实际值后清理本轮目录,再返回观察记录;临时路径不会成为可继续使用的持久产物。失败保留原生诊断,中途错误可能留下本轮临时目录供检查,调用方负责识别并清理它。 - -本函数既展示无 IO 的路径代数,也展示真实写入、复制、读取和清理。业务中不要根据一个规范化后的字符串就认为已经获得文件权限,更不要把打印成功标记当成已读回复制内容的证明。 - -先**requested = [组合演示用的相对路径文本](路径.拼接(甲="out", 乙="demo.txt"))**和**normalized = [消除相对路径中的冗余片段](路径.规范化(路径="out/./x/../demo.txt"))**,核对路径代数本身。 -为实际读写创建**work = [只使用本轮独有的授权临时目录](文件.临时目录(前缀="路径演示"))**,再准备**original = [在临时目录中命名原文件](路径.拼接(甲=`work`, 乙="demo.txt"))**和**copied = [在同一目录中命名副本](路径.拼接(甲=`work`, 乙="demo-copy.txt"))**。 -随后**[写入本轮需要复制的正文](文件.写文本(路径=`original`, 内容="path-m2"))**,并**[复制本轮文件而不触及已有用户文件](文件.复制文件(源=`original`, 目标=`copied`))**。 -读取阶段保存**copied_text = [读取副本的真实正文](文件.读文本(路径=`copied`))**,完成观察后**[清理本轮独有的临时目录](文件.删目录树(路径=`work`))**。 - -`observed` = - -| requested | normalized | copied_text | -|---|---|---| -| `requested` | `normalized` | `copied_text` | - -完成路径处理与隔离读写后,我们返回*observed*,其中保留的是已观察到的值,临时文件已经清理。 diff --git a/public/features/10-hash-secrets.mq.md b/public/features/10-hash-secrets.mq.md deleted file mode 100755 index 5de2661..0000000 --- a/public/features/10-hash-secrets.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — hash and secrets -description: lib/hash + lib/secrets without plugins (Mid M3) -import: - hash: lib/hash.mq.md - sec: lib/secrets.mq.md ---- - -# Digests and secure tokens - - -Integrity digests and cryptographic tokens stay in `lib/` — do not use `math.random` for secrets. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **d = [Compute d](hash.sha256(text="marqdo"))** for the next step. -We first **t = [Compute t](sec.token_hex(n=8))** for the next step. -We first **L = [Compute L](len(`t`))** for the next step. -We now **[Display this step's result](> print text=`d`)**. -We now **[Display this step's result](> print text=`L`)**. -1. `L` == 16 - We now **[Display this step's result](> print text="mid-m3-ok")**. -2. * - We now **[Display this step's result](> print text="mid-m3-fail")**. diff --git a/public/features/10-哈希机密.mq.md b/public/features/10-哈希机密.mq.md deleted file mode 100755 index a07bcc6..0000000 --- a/public/features/10-哈希机密.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 哈希与机密 -description: lib/哈希 + lib/机密,无需插件(中层 M3) -导入: - 哈希: lib/哈希.mq.md - 机密: lib/机密.mq.md ---- - -# 摘要与安全令牌 - -完整性摘要与加密令牌进 `lib/` — 勿用 `math.random` 生成令牌。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -摘要和随机令牌解决不同的问题。固定文本的 SHA-256 摘要可用于比对内容是否变化;随机令牌从安全随机源获取字节,再编码为十六进制文本。八个随机字节会显示为十六个十六进制字符,因此这里检查输出长度,不把令牌与某个固定值比较。 - -本例不会把令牌写到磁盘或发送到网络。实际产品需要依据用途选择令牌字节数,并在使用后按应用规则保管或撤销;这里的短值只演示参数与编码长度的关系。哈希不提供加密,也不能单靠未认证的摘要证明内容来自谁。随机源失败时应保留诊断,不能改用普通伪随机数或固定文本充当安全令牌。 - -我们先**d = [计算固定文本的 SHA-256](哈希.哈希256(内容="marqdo"))**,供下一步使用。 -我们先**t = [取得当前步骤的转置公式或随机令牌](机密.十六进制令牌(字节数=8))**,供下一步使用。 -我们先**L = [读取十六进制令牌的字符数](长度(`t`))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=`d`)**。 -随后我们**[显示当前步骤的结果](> 打印 内容=`L`)**。 -1. `L` == 16 - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m3-ok")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m3-fail")**。 diff --git a/public/features/11-csv-text.mq.md b/public/features/11-csv-text.mq.md deleted file mode 100755 index ef2b2f1..0000000 --- a/public/features/11-csv-text.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — csv and text -description: lib/csv + thickened lib/text (Mid M4) -import: - csv: lib/csv.mq.md - text: lib/text.mq.md ---- - -# CSV cleaning with text helpers - - -Parse a tiny CSV, normalize a field, print — no plugins. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **raw = "name,city\nAda,london\nBob,PARIS\n"** for the next step. -We first **rows = [Compute rows](csv.parse(text=`raw`))** for the next step. -We first **r0 = [Compute r0](at(value=`rows`, index=0))** for the next step. -We first **city = [Compute city](text.to_upper(text=[city](access(`r0`, "city"))))** for the next step. -We now **[Display this step's result](> print text=[name](access(`r0`, "name")))**. -We now **[Display this step's result](> print text=`city`)**. -We first **n = [Compute n](len(`rows`))** for the next step. -1. `n` == 2 - We now **[Display this step's result](> print text="mid-m4-ok")**. -2. * - We now **[Display this step's result](> print text="mid-m4-fail")**. diff --git a/public/features/11-逗号表文本.mq.md b/public/features/11-逗号表文本.mq.md deleted file mode 100755 index bd22944..0000000 --- a/public/features/11-逗号表文本.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 逗号表与文本 -description: lib/逗号表 + 加厚 lib/文本(中层 M4) -导入: - 逗号表: lib/逗号表.mq.md - 文本: lib/文本.mq.md ---- - -# 用文本助手清洗 CSV - -解析小表、规范化字段、打印 — 无需插件。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -CSV 解析先保留每个单元格的文本语义;下面选择第一条记录,再把城市字段规范为大写,得到 LONDON。姓名字段仍是 Ada,另一条记录仍保留在原集合中。调用文本变换不会自动替换原记录,因此这里只展示规范化值,不宣称整个表已经被清洗。 - -这里的 at 使用从零开始的位置,access 则按字段名读取记录;不要把二者的索引规则混用。输入正文直接写在本页,没有文件或进程访问。接入真实文件时先用原生文件库读取文本,再交给同一个解析函数;需要金额等数值运算时必须另外做明确的类型转换,不能根据 CSV 中的数字外观推断类型。两行计数只验证这份固定样本的解析结果。 - -我们先**raw = "name,city\nAda,london\nBob,PARIS\n"**,供下一步使用。 -我们先**rows = [解析或排序当前行记录](逗号表.解析(内容=`raw`))**,供下一步使用。 -我们先**r0 = [选择列表中的第一条记录](at(value=`rows`, index=0))**,供下一步使用。 -我们先**city = [将第一条记录的城市改为大写文本](文本.大写(内容=[city](access(`r0`, "city"))))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=[name](access(`r0`, "name")))**。 -随后我们**[显示当前步骤的结果](> 打印 内容=`city`)**。 -我们先**n = [取得本步骤需要的路径或计数](长度(`rows`))**,供下一步使用。 -1. `n` == 2 - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m4-ok")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m4-fail")**。 diff --git a/public/features/12-list-cli.mq.md b/public/features/12-list-cli.mq.md deleted file mode 100755 index 80f9d90..0000000 --- a/public/features/12-list-cli.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — lists and cli -description: table sort/unique/zip + cli.parse (Mid M5) -import: - table: lib/table.mq.md - csv: lib/csv.mq.md - cli: lib/cli.mq.md ---- - -# Sort CSV rows and parse flags - - -Zero plugins: parse CSV, sort by key, parse `--input`. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **raw = "name,score\nbob,2\nalice,10\n"** for the next step. -We first **rows = [Compute rows](csv.parse(text=`raw`))** for the next step. -We first **rows = [Compute rows](table.sort_by(list=`rows`, key="name"))** for the next step. -We first **r0 = [Compute r0](at(value=`rows`, index=0))** for the next step. -We now **[Display this step's result](> print text=[name](access(`r0`, "name")))**. - -We first **args = [Compute args](split(value="--input,scores.csv,--pretty", sep=","))** for the next step. -We first **flags = [Compute flags](cli.parse(args=`args`))** for the next step. -We now **[Display this step's result](> print text=[input](access(`flags`, "input")))**. -1. [pretty](access(`flags`, "pretty")) - We now **[Display this step's result](> print text="mid-m5-ok")**. -2. * - We now **[Display this step's result](> print text="mid-m5-fail")**. diff --git a/public/features/12-列表命令行.mq.md b/public/features/12-列表命令行.mq.md deleted file mode 100755 index ec6d49c..0000000 --- a/public/features/12-列表命令行.mq.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 列表与命令行 -description: 表排序/去重 + 命令行解析(中层 M5) -导入: - 表: lib/表.mq.md - 逗号表: lib/逗号表.mq.md - 命令行: lib/命令行.mq.md ---- - -# 排序 CSV 并解析参数 - -零插件:解析 CSV、按键排序、解析 `--input`。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -这里先按 name 字段对 CSV 记录排序,所以第一条姓名是 alice;score 在本例中仍是文本,尚未参与数值排序。排序函数返回新集合,重新保存 rows 才能让后续取值使用排序结果。随后构造三个命令参数并交给命令行库,读取 input 的文件名以及 pretty 的开关状态。 - -参数数组中的元素始终是数据:本例解析 scores.csv 这个名字,不会读取该文件,也不会启动命令解释器。用于真实进程调用时应继续保持逐个参数传递,选项文本要加引号,不要拼成 shell 源码。没有插件、网络和文件授权需求;缺少必须的业务参数时,应由上层根据解析结果决定是否继续,而不是仅看到 pretty 为真就认定所有输入有效。 - -我们先**raw = "name,score\nbob,2\nalice,10\n"**,供下一步使用。 -我们先**rows = [解析或排序当前行记录](逗号表.解析(内容=`raw`))**,供下一步使用。 -我们先**rows = [解析或排序当前行记录](表.按键排序(list=`rows`, key="name"))**,供下一步使用。 -我们先**r0 = [选择列表中的第一条记录](at(value=`rows`, index=0))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=[name](access(`r0`, "name")))**。 - -我们先**args = [构造逐项传递的命令参数](split(value="--input,scores.csv,--pretty", sep=","))**,供下一步使用。 -我们先**flags = [解析选项值与布尔开关](命令行.解析(参数=`args`))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=[input](access(`flags`, "input")))**。 -1. [pretty](access(`flags`, "pretty")) - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m5-ok")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="mid-m5-fail")**。 diff --git a/public/features/13-log-uuid.mq.md b/public/features/13-log-uuid.mq.md deleted file mode 100755 index c4d6b8d..0000000 --- a/public/features/13-log-uuid.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — log and uuid -description: Level-filtered logs + UUID v4 (Mid M6) -import: - log: lib/log.mq.md - uuid: lib/uuid.mq.md ---- - -# Observable scripts without plugins - - -Default log level is info; raise to debug when you need more. Mint ids with uuid.v4. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We now **[Call log.info](> log.info text="mid-m6-start")**. - -We now **[Call log.debug](> log.debug text="skipped-by-default")**. - -We now **[Call log.set level](> log.set_level level="debug")**. - -We now **[Call log.debug](> log.debug text="now-visible")**. - -We first **id = [Compute id](uuid.v4())** for the next step. -We first **n = [Compute n](len(`id`))** for the next step. -We now **[Display this step's result](> print text=`n`)**. diff --git a/public/features/13-日志标识.mq.md b/public/features/13-日志标识.mq.md deleted file mode 100755 index ccbd8c7..0000000 --- a/public/features/13-日志标识.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 日志与标识 -description: 按级别过滤的日志 + UUID 版本4(中层 M6) -导入: - 日志: lib/日志.mq.md - 标识: lib/标识.mq.md ---- - -# 无插件的可观测脚本 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;本段完成下述操作,不额外返回业务数据。 | - -默认日志级别为 info;需要细节时再调到 debug。用 标识.版本4 生成 id。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -随后我们**[执行 日志.信息](> 日志.信息 内容="中层-m6-开始")**。 - -随后我们**[执行 日志.调试](> 日志.调试 内容="默认会跳过")**。 - -随后我们**[执行 日志.设级别](> 日志.设级别 级别="debug")**。 - -随后我们**[执行 日志.调试](> 日志.调试 内容="现在可见")**。 - -我们先**id = [计算并保存 id](标识.版本4())**,供下一步使用。 -我们先**n = [计算并保存 n](长度(`id`))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 diff --git a/public/features/14-datetime-url.mq.md b/public/features/14-datetime-url.mq.md deleted file mode 100755 index e5b6377..0000000 --- a/public/features/14-datetime-url.mq.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — datetime and url -description: Calendar moments + URL/query parse (Mid2 M7) -import: - dt: lib/datetime.mq.md - url: lib/url.mq.md ---- - -# Time and addresses without plugins - - -Moments are maps `{unix, zone, iso}`. Parse HTTPS URLs and round-trip query strings in `lib/url` (segment encoding stays in `net.url_encode`). - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **epoch = [Compute epoch](dt.from_unix(unix=0, zone="Asia/Shanghai"))** for the next step. -We now **[Display this step's result](> print text=[iso](access(`epoch`, "iso")))**. - -We first **u = [Compute u](url.parse(text="https://example.com/path?q=1#top"))** for the next step. -We now **[Display this step's result](> print text=[host](access(`u`, "host")))**. -We now **[Display this step's result](> print text=[query](access(`u`, "query")))**. diff --git a/public/features/14-日期时间地址.mq.md b/public/features/14-日期时间地址.mq.md deleted file mode 100755 index d8c0ce0..0000000 --- a/public/features/14-日期时间地址.mq.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 日期时间与地址 -description: 日历时刻 + URL/查询串(Mid2 M7) -导入: - 日时: lib/日期时间.mq.md - 址: lib/地址.mq.md ---- - -# 无需插件的时间与地址 - -时刻是 map `{unix, zone, iso}`。用 `地址` 拆 HTTPS URL 与查询串。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -时间戳零表示同一个时间点;指定 Asia/Shanghai 后,ISO 展示采用该时区的当地时间。改变时区不应改变 unix 字段所代表的瞬间。固定时间戳使本例可以重复验证,不依赖机器当前时钟,也不要求读取时间服务。 - -地址解析只拆分给定的 HTTPS 文本,host 应为 example.com,query 保留 q=1。它不会访问服务器、验证网站可用性或把查询字符串当作本地文件名。后续需要查询参数时应使用地址库对应的查询解析能力,并保留转义和重复键的边界。时间与 URL 都返回有明确字段的记录;先按契约读取字段,再决定展示格式,避免把整份记录误当成最终用户需要的单段文本。 - -我们先**epoch = [构造固定时区的零时刻](日时.自戳(秒=0, 区="Asia/Shanghai"))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> print text=[iso](access(`epoch`, "iso")))**。 - -我们先**u = [解析当前日期或 URL 输入](址.解析(内容="https://example.com/path?q=1"))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> print text=[host](access(`u`, "host")))**。 -随后我们**[显示当前步骤的结果](> print text=[query](access(`u`, "query")))**。 diff --git a/public/features/15-toml-html-encoding.mq.md b/public/features/15-toml-html-encoding.mq.md deleted file mode 100755 index 6125a01..0000000 --- a/public/features/15-toml-html-encoding.mq.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — toml, html, base32 -description: Config TOML + HTML escape + base32 (Mid2 M8) -import: - toml: lib/toml.mq.md - html: lib/html.mq.md - enc: lib/encoding.mq.md ---- - -# Config and safe text without plugins - - -Parse a TOML subset for tools, escape HTML before assembly, encode with base32. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **cfg = [Compute cfg](toml.parse(text="app = \"demo\"\n[server]\nport = 8080\n"))** for the next step. -We now **[Display this step's result](> print text=[app](access(`cfg`, "app")))**. -We first **srv = [server](access(`cfg`, "server"))** for the next step. -We now **[Display this step's result](> print text=[port](access(`srv`, "port")))**. - -We first **safe = [Compute safe](html.escape(text=""))** for the next step. -We now **[Display this step's result](> print text=`safe`)**. - -We first **b = [Compute b](enc.base32_encode(text="ok"))** for the next step. -We now **[Display this step's result](> print text=`b`)**. diff --git a/public/features/15-配置表超文本编码.mq.md b/public/features/15-配置表超文本编码.mq.md deleted file mode 100755 index 2b25884..0000000 --- a/public/features/15-配置表超文本编码.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 配置表、超文本、基32 -description: TOML 配置 + HTML 转义 + base32(Mid2 M8) -导入: - 配置: lib/配置表.mq.md - 超: lib/超文本.mq.md - 编: lib/编码.mq.md ---- - -# 无需插件的配置与安全字面 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -三个步骤处理三种文本边界:TOML 解析得到 app 字段的记录,HTML 转义把尖括号变成普通可展示文本,Base32 把 UTF-8 输入编码为另一种文本表示。它们彼此独立,不能把配置解析、页面布局和编码混成一个隐藏的字符串处理流程。 - -TOML 文本直接来自本页,读取真实配置文件时应先使用原生文件库;本例不会隐式寻找系统配置。HTML 转义适用于普通文本展示,不能代替 URL、脚本或样式上下文各自需要的处理,更不应因此拼接大量业务 HTML。Base32 只改变表示方法,不加密数据。所有结果都可继续传递给其他 Marqdo 函数,当前步骤不创建文件、不发送网络请求,也不需要外联解释器。 - -我们先**cfg = [解析显式提供的 TOML 配置](配置.解析(内容="app = \"演示\"\n"))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> print text=[app](access(`cfg`, "app")))**。 - -我们先**safe = [将尖括号转义为普通展示文本](超.转义(内容=""))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> print text=`safe`)**。 - -我们先**b = [把输入文本编码为 Base32](编.基32编码(内容="ok"))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> print text=`b`)**。 diff --git a/public/features/16-fs-mid2.mq.md b/public/features/16-fs-mid2.mq.md deleted file mode 100755 index 9cbe5ac..0000000 --- a/public/features/16-fs-mid2.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: Native directory trees, enumeration and file metadata -import: - fs: lib/fs.mq.md ---- - -This complete demonstration uses native filesystem tools. Call main with fs.write and a disposable --fs-root. It returns actual metadata and relative paths after cleaning its own temporary directory. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Actual byte size, directory entry count and relative paths | - -Create a unique temporary directory, then one child directory and one text file. Every write remains under the granted root, avoiding collisions with a pre-existing demo folder. Paths are built explicitly; no generated reader/writer or foreign process participates. - -The content ok occupies two UTF-8 bytes. File size measures stored bytes rather than text character count. Enumeration returns relative paths for the child directory and file; counting those paths is another distinct observation. The example does not depend on operating-system enumeration order. Sort explicitly if a later workflow requires stable ordering. - -Collect the real metadata and paths before removing this run's unique tree. Returned paths describe an observation, not still-live artifacts. A failure can retain its native diagnostic and this run's directory for caller inspection. Cleanup must stay scoped to the directory created by this invocation. - -We **work = [Create a unique directory inside the granted root](fs.temp_dir(prefix="fs-tree-demo"))** and **child = work + "/sub"** and **note = work + "/readme.txt"**. -We **[Create this run own child directory](fs.make_dirs(path=`child`))** and **[Write the exact UTF-8 example content](fs.write_text(path=`note`, text="ok"))**. -We **metadata = [Read the actual file metadata](fs.stat(path=`note`))** and **paths = [Enumerate this run directory entries](fs.walk(path=`work`))** and **size = [Retain storage byte size](access(metadata, "size"))** and **entries = [Count the actual enumerated paths](len(`paths`))**. -We **[Remove only this run unique directory tree](fs.remove_tree(path=`work`))** after collecting the observations. - -`observed` = - -| size | entries | paths | -|---|---|---| -| `size` | `entries` | `paths` | - -After observing and cleaning this run we return *observed*. diff --git a/public/features/16-文件mid2.mq.md b/public/features/16-文件mid2.mq.md deleted file mode 100755 index be7898f..0000000 --- a/public/features/16-文件mid2.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: 原生目录树、遍历与文件状态 -import: - 文件: lib/文件.mq.md ---- - -使用固有文件库完成整个演示。调用 main 时授予 fs.write,并指定独立的 --fs-root。函数返回实际元数据与相对路径列表,正常结束后清理自己的临时目录。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 真实文件字节数、目录条目数与相对路径列表 | - -本轮先创建唯一临时目录,再在其中建立子目录和文本文件,避免固定的演示名称与已有目录冲突。创建和写入都受 --fs-root 约束,目录参数并不授予访问其他位置的权限。所有路径由当前流程明确构造,没有外部脚本代为读取或修改正文。 - -内容“好”占三个 UTF-8 字节,size 描述存储大小而不是字符数。遍历结果包含文件和子目录的相对路径,条目数与字符串长度也是不同的量。本例只观察枚举内容,不依赖操作系统给出的顺序;需要稳定排序时应继续组合表库。 - -实际观察值保存后删除本轮独有的临时树。返回的路径列表描述已经观察过的内容,不是仍然存在的文件句柄。中途失败保留原生诊断与可能留下的本轮目录,调用方可以检查后清理,不应递归删除与演示无关的用户目录。 - -先**work = [创建本轮独有的授权临时目录](文件.临时目录(前缀="文件树演示"))**和**child = work + "/子"**及**note = work + "/说明.txt"**。 -接着**[递归创建本轮子目录](文件.建目录树(路径=`child`))**,并**[写入一个明确的 UTF-8 字符](文件.写文本(路径=`note`, 内容="好"))**。 -观察时保存**metadata = [读取真实文件元数据](文件.状态(路径=`note`))**和**paths = [枚举本轮目录里的实际条目](文件.遍历(路径=`work`))**及**size = [保留存储字节数](access(metadata, "size"))**和**entries = [保留遍历条目数](长度(`paths`))**。 -最后**[只清理本轮独有的目录树](文件.删目录树(路径=`work`))**,再组织实际观察值。 - -`observed` = - -| size | entries | paths | -|---|---|---| -| `size` | `entries` | `paths` | - -完成观察与清理后,我们返回*observed*。 diff --git a/public/features/17-stats-log.mq.md b/public/features/17-stats-log.mq.md deleted file mode 100755 index 3489945..0000000 --- a/public/features/17-stats-log.mq.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -markup: occlusion -title: Mid stdlib — stats and log fields -description: Thin mean/median/stdev + structured log fields (Mid2 M10) -import: - stats: lib/stats.mq.md - log: lib/log.mq.md ---- - -# Closing Mid2 sugar - - -Light statistics and optional `fields=` on log lines — no remote sinks, no dataframes. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -`xs` = - -| | -|---| -| 10 | -| 20 | -| 30 | - -We first **m = [Compute m](stats.mean(list=`xs`))** for the next step. -We now **[Display this step's result](> print text=`m`)**. - -`fld` = - -| step | status | -|------|--------| -| done | ok | - -We now **[Call log.info](> log.info text="mid2-m10" fields=`fld`)**. diff --git a/public/features/17-统计日志.mq.md b/public/features/17-统计日志.mq.md deleted file mode 100755 index 0052614..0000000 --- a/public/features/17-统计日志.mq.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -markup: occlusion -title: 中层标准库 — 统计与日志字段 -description: 薄均值/中位数/标准差 + 日志 fields(Mid2 M10) -导入: - 统计: lib/统计.mq.md - 日志: lib/日志.mq.md ---- - -# Mid2 收口糖 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -数值列表包含十、二十和三十,平均值应为二十。这里把数据写成一列表格,让读者能直接核对输入,而不是在外部解释器中再构造同一份列表。统计函数不修改原集合;需要中位数、标准差或空集合策略时,应继续阅读统计库对应函数的独立契约。 - -结构化日志同时携带消息与步骤、状态字段,用于后续过滤或诊断。日志输出不是函数的业务返回值,也不能作为已经完成某项发布或文件写入的证据。本例没有文件和网络操作;实际日志目的地与权限沿用日志库的运行环境规则。若后续任务依赖统计结果,就应直接传递 m 的数值,而不是重新解析打印文本或把最后一条日志当作成功标志。 - -`xs` = - -| | -|---| -| 10 | -| 20 | -| 30 | - -我们先**m = [计算列表的算术平均值](统计.均值(列表=`xs`))**,供下一步使用。 -随后我们**[显示当前步骤的结果](> print text=`m`)**。 - -`fld` = - -| 步骤 | 状态 | -|------|------| -| 完成 | ok | - -随后我们**[执行 日志.信息](> 日志.信息 内容="mid2-m10" 字段=`fld`)**。 diff --git a/public/features/18-AI原生闭环.mq.md b/public/features/18-AI原生闭环.mq.md deleted file mode 100755 index 4f5500d..0000000 --- a/public/features/18-AI原生闭环.mq.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -markup: occlusion -title: AI 原生闭环(契约 + MLSP) -description: 渐进式契约、结构化诊断与面向 AI 的 Marqdo 语言服务 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -里程碑(v1.1.0):AI 原生闭环——让 AI 不仅能写 Marqdo,还能验证 Marqdo。 - -三件套。核心表面守卫(`doc/design/core-surface.md`)钉住 19 个核心构造,任一侧(清单 / 文档 / 金样)单边改动,CI 必红。渐进式契约是可选的 `参数` / `返回` / `字段` 表,直接嵌在叙述里,四边界校验:调用实参、返回值、表绑定、键访问。MLSP for AI(`marqdo mlsp`)是行分隔 JSON 的语言服务,AI 按需查询语法,而不是背诵整部语法。 - -静态契约检查: - -```bash -marqdo check tests/contracts/ok_contract.mq.md -``` - -结构化诊断——错误即数据: - -```bash -marqdo run tests/structure/hello.mq.md --json -``` - -按需查询语法(MLSP): - -```bash -printf '%s\n' '{"id":1,"method":"syntax","params":{"query":"返回"}}' | marqdo mlsp -``` - -MLSP 方法:`locate`(查符号 / 构造卡片)、`syntax`(戒律原文 + 样例 + 文档锚点)、`validate`(结构化诊断)、`repair_targets`(有界靶点)、`repair_apply`(有界行编辑,越界必拒)、`schema`(单元契约)。 - -随后我们**[显示当前步骤的结果](> print text="契约是可选的:不写契约表,文件保持全动态。")**。 - -随后我们**[显示当前步骤的结果](> print text="诊断自带 code / severity / suggestion / doc_anchor / doc_quote。")**。 - -随后我们**[显示当前步骤的结果](> print text="MLSP 语法卡片内嵌戒律原文与样例,AI 无需预学语法。")**。 - -验证结果见:`doc/roadmap/perf-validation-report-2026-09-23.md`。 diff --git a/public/features/18-ai-native-loop.mq.md b/public/features/18-ai-native-loop.mq.md deleted file mode 100755 index 47ca0d8..0000000 --- a/public/features/18-ai-native-loop.mq.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -markup: occlusion -title: AI-native loop (contracts + MLSP) -description: Progressive contracts, structured diagnostics, and the Marqdo Language Server for AI ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Milestone (v1.1.0): the AI-native loop — so an AI can verify Marqdo, not just write it. - -Three pieces. A core surface guard (`doc/design/core-surface.md`) pins the 19 core constructs, so a single-sided change (list / doc / golden sample) turns CI red. Progressive contracts are optional `参数` / `返回` / `字段` tables embedded in the narrative, checked at four boundaries: call argument, return, table bind, key access. MLSP for AI (`marqdo mlsp`) is a line-delimited JSON language service; the AI queries syntax on demand instead of memorizing the whole grammar. - -Static contract check: - -```bash -marqdo check tests/contracts/ok_contract.mq.md -``` - -Structured diagnostics — errors as data: - -```bash -marqdo run tests/structure/hello.mq.md --json -``` - -Query syntax on demand (MLSP): - -```bash -printf '%s\n' '{"id":1,"method":"syntax","params":{"query":"返回"}}' | marqdo mlsp -``` - -MLSP methods: `locate` (find a symbol / construct card), `syntax` (rule text + sample + doc anchor), `validate` (structured diagnostics), `repair_targets` (bounded span), `repair_apply` (bounded line edits, out-of-scope refused), `schema` (contract of one unit). - -We now **[Display this step's result](> print text="Contracts are optional: with no contract table, a file stays fully dynamic.")**. - -We now **[Display this step's result](> print text="Diagnostics carry code, severity, suggestion, doc_anchor and doc_quote.")**. - -We now **[Display this step's result](> print text="MLSP syntax cards embed the rule text and a sample, so AI need not pre-learn the grammar.")**. - -See validation results: `doc/roadmap/perf-validation-report-2026-09-23.md`. diff --git a/public/features/19-foreign-view-cells.mq.md b/public/features/19-foreign-view-cells.mq.md deleted file mode 100755 index b1d8c0e..0000000 --- a/public/features/19-foreign-view-cells.mq.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -markup: occlusion -title: Native analysis and an explicit Intl formatting boundary -import: - foreign: lib/foreign.mq.md - table: lib/table.mq.md - result: lib/result.mq.md - native: ../../examples/foreign-native-report/index.mq.md ---- - -This page keeps order analysis in Marqdo and uses Node Intl only for locale-aware -currency formatting. Read [the actual native report tools](../../examples/foreign-native-report/index.mq.md) -for their independently callable input and return contracts. That single module -contains grouping, population statistics and the bounded persistent formatter. - -Call this page's main with process.exec for a full workflow, or call analyze_orders -in that module with no effects for native analysis alone. View evaluates the same -cells with shared state and isolated kernels. No Python interpreter is needed. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | View-session plan plus the native report and checked localized formatting | - -This complete page uses six ordinary orders: their native total is 950, count -is six, and the four regional rows retain count, total, mean and normalized span. -The pure analysis is independently callable in the linked module. Formatting is a separate -capability with an explicit process.exec grant and an installed Node runtime. -The successful return contains report and formatting alongside the view-session -plan; it contains no live kernel handle and can be returned by marqdo call. - -The view gets the same native report copied into two named kernels. Its cells -perform presentation rather than reimplementing native grouping or arithmetic. -Run All first initializes the formatter in the analysis kernel, then a second -cell reuses it. The review kernel receives its own report copy and formatter. -This demonstrates both shared state and kernel isolation. Running the dependent -formatting cell before its initializer should show the real missing-state error. - -Static View export evaluates those same cells and embeds actual stdout. -Interactive View retains their kernels for later runs. The low-level formatter -used to check the public return is opened and closed separately, so it cannot -secretly supply state to the view kernels. No stdin, notebook command, generated -file-reader program or package installation is hidden in this example. -If Node or formatting fails, the page returns that failure before declaring a -ready view. Native-only consumers can still call analyze_orders with no effects. -The table cells below are data, while the three bound node fences are explicit -foreign code. The distinction is visible without translating a Python workflow -into another ad hoc command sequence. - -`orders` = - -| @ | region | amount | -|---|---|---| -| 1 | 华东 | 120 | -| 2 | 华东 | 300 | -| 3 | 华南 | 90 | -| 4 | 华南 | 140 | -| 5 | 华北 | 220 | -| 6 | 西部 | 80 | - -We **report = [Perform all analysis in Marqdo](native.analyze_orders(orders=`orders`))** and **formatted = [Use the genuine external formatting boundary](native.format_summary(report=`report`))**. -1. not access(`formatted`, "ok") - Return *formatted* before declaring an executable view ready. - -`kernels` = - -| @ | 名称 | 语言 | -|---|---|---| -| 1 | 分析 | node | -| 2 | 复核 | node | - -`cells` = - -| @ | 单元 | 内核 | -|---|---|---| -| 1 | 计算 | 分析 | -| 2 | 格式化 | 分析 | -| 3 | 复核 | 复核 | - -`initial` = - -| @ | 内核 | 名称 | 值 | -|---|---|---|---| -| 1 | 分析 | report | `report` | -| 2 | 复核 | report | `report` | - -We **会话 = [Declare the view with native values and explicit kernels](foreign.session(kernels=`kernels`, cells=`cells`, values=`initial`))**. - -`计算` = -```node -var money = new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}); -console.log(JSON.stringify(report)); -``` - -`格式化` = -```node -console.log(money.format(report.total)); -console.log(money.format(report.average)); -``` - -`复核` = -```node -var reviewMoney = new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}); -console.log(JSON.stringify({count:report.count, total:reviewMoney.format(report.total)})); -``` - -We **formatting = [Retain the checked persistent-kernel result](access(formatted, "value"))**. - -`evidence` = - -| report | formatting | -|---|---| -| `report` | `formatting` | - -Return *[The executable view plan with native analysis evidence](table.merge(a=`会话`, b=`evidence`))*. diff --git a/public/features/19-外联视图单元.mq.md b/public/features/19-外联视图单元.mq.md deleted file mode 100755 index 8dde8e1..0000000 --- a/public/features/19-外联视图单元.mq.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -markup: occlusion -title: 原生分析与明确的 Intl 格式化边界 -import: - 外联: lib/外联.mq.md - 表: lib/table.mq.md - 例程: ../../examples/foreign-native-report/index.mq.md ---- - -先用固有能力,外联只补真实的能力缺口。本页复用 [原生报告例程](../../examples/foreign-native-report/index.mq.md),让统计在 Marqdo 中完成,再通过已支持的 Node 持久内核使用 Intl。阅读例程的源码即可找到可以独立调用的参数、返回值与失败约束。 - -在仓库根目录调用 marqdo call public/features/19-外联视图单元.mq.md main --effects process.exec --fs-root . --json 可以获得真实报告与视图计划。使用 view 导出同一份源码即可运行下面声明的单元。这里采用函数标题 main,便于作为工具直接调用;不需要 Python 解释器或另一套笔记本入口。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | 包含 report、formatting 及内核/单元/初始值的视图计划;失败时返回实际 Result | - -格式化结果中的数字会显示为 950.00 与 158.33,货币标志由区域设置决定;原生 report 保留未格式化的数值。 - -本页的六笔订单全部由 Marqdo 固有能力处理,得到合计 950、数量六、四个区域的订单数、合计、均值和总体标准化跨度。分组、排序、统计与数值运算都不需要外部脚本;真正交给 Node 的只有 Intl 本地化货币格式。直接调用本页 main 需要 process.exec,Node 应预先安装。成功返回的计划包含 report 原始报告和 formatting 展示结果,调用者可以继续验证具体数值。 - -共享例程有独立的参数及返回表,区域键和金额键都由调用者明确指定,因此中文字段不需要重命名成另一套 JSON 拼接语言。本页和英文页共同调用一份原生算法,避免两个版本逐渐出现不同的统计规则。纯数据分析可以直接调用例程的 analyze_orders,不需要任何进程授权;空输入、单元素区域与相同金额的区域也有清楚的定义。金额只是示例数值,展示的两位小数由 Intl 决定,不宣称是金融十进制定点模型。 - -视图的分析内核先输出已经算好的报告,并创建本地化格式器;同一内核中的第二个单元继续使用这个格式器。因此 Run All 的顺序是明确的执行依赖,直接先运行格式化单元应展示真实的未初始化状态。复核单元使用另一份内核和自己的格式器,体现状态隔离。两个内核收到的是报告的数据拷贝,谁都不会重新实现一份分组算法,也不会修改 Marqdo 的源订单。 - -用于验证工具返回值的低层格式化例程单独创建并关闭了一个持久内核:第一次求值创建格式器,第二次复用状态。它检查每次求值的 ok,遇到可恢复错误时关闭仍存活的内核,再返回真实诊断。用于视图的会话随后才被声明;工具验证的内核不能暗中给视图提供状态。视图的静态导出与交互模式运行同一批单元,输出来自实际执行,不用预写的通过文字冒充结果。 - -正文先交代数据来源和边界,再把调用放入相应的句子。下面的订单、内核、单元和初始值都是普通表格;三段绑定的 node 围栏才是明确外联的代码。整个操作不要求向终端输入 JSON,也不生成文件读取器。若解释器不可用或格式化失败,会在创建可用视图之前把失败交给调用者。 - -`订单` = - -| @ | 区域 | 金额 | -|---|---|---| -| 1 | 华东 | 120 | -| 2 | 华东 | 300 | -| 3 | 华南 | 90 | -| 4 | 华南 | 140 | -| 5 | 华北 | 220 | -| 6 | 西部 | 80 | - -我们先**报告 = [使用固有库完成分组和总体统计](例程.analyze_orders(orders=`订单`, region_key="区域", amount_key="金额"))**,再**格式结果 = [把真正缺失的本地化展示交给 Intl](例程.format_summary(report=`报告`, locale="zh-CN"))**。 -1. not access(`格式结果`, "ok") - 返回*格式结果*,保留外联解释器或格式化的真实失败。 - -`内核` = - -| @ | 名称 | 语言 | -|---|---|---| -| 1 | 分析 | node | -| 2 | 复核 | node | - -`单元` = - -| @ | 单元 | 内核 | -|---|---|---| -| 1 | 计算 | 分析 | -| 2 | 格式化 | 分析 | -| 3 | 复核 | 复核 | - -`初始值` = - -| @ | 内核 | 名称 | 值 | -|---|---|---|---| -| 1 | 分析 | report | `报告` | -| 2 | 复核 | report | `报告` | - -接着**会话 = [用普通表格声明显式的视图会话](外联.会话(内核表=`内核`, 单元表=`单元`, 值表=`初始值`))**,让两份内核获得同一个原生报告的独立 JSON 拷贝。 - -`计算` = -```node -var money = new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}); -console.log(JSON.stringify(report)); -``` - -`格式化` = -```node -console.log(money.format(report.total)); -console.log(money.format(report.average)); -``` - -`复核` = -```node -var reviewMoney = new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}); -console.log(JSON.stringify({count:report.count, total:reviewMoney.format(report.total)})); -``` - -我们**展示 = [保留已经检查过的持久格式化结果](access(格式结果, "value"))**,把数据与展示来源一并交给调用者。 - -`依据` = - -| report | formatting | -|---|---| -| `报告` | `展示` | - -所有值准备好后返回*[带原生分析依据的可执行视图计划](表.merge(a=`会话`, b=`依据`))*。 diff --git a/public/features/20-OKF与EKC.mq.md b/public/features/20-OKF与EKC.mq.md deleted file mode 100755 index 5fa515f..0000000 --- a/public/features/20-OKF与EKC.mq.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -markup: occlusion -title: 代码即文档,文档即知识 — OKF 与 EKC -description: Marqdo 如何以一份可执行源为唯一权威,把它投影成 OKF 风格知识与 Engineering Knowledge Compiler 制品 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -Marqdo 的宪法是「代码即文档,文档即知识库」。`.mq.md` 不是程序截图:它同时是可读源码、可执行单元和知识页。 - -这个承诺只有在知识始终从源派生时才成立。OKF 提供可移植知识包的形态;EKC 提供工程化投影。二者都不成为第二份权威。 - ---- - -OKF 的形,Marqdo 的义。 - -OKF(Open Knowledge Format)用 Markdown + YAML frontmatter 表示知识:一页一概念、路径即身份、链接成图、强制面刻意保持很小。Marqdo 借用这个形态,但正文是可执行语法。 - -因此概念页可以直接指向证明它的文件: - -```yaml -type: Capability -title: 持久外联内核 -description: 向显式声明的本地内核传递原生数据并保留状态 -resource: public/features/19-外联视图单元.mq.md -status: stable -verified: - by: marqdo-knowledge/verify -tags: - - foreign - - view-cells -``` - -同一页可以在编辑器里读、从 catalog 链接、被 Agent 查询,也可以直接运行。未知字段保留;未知类型降级为可读正文。概念页不是源文件的复制品。 - ---- - -哪些是生成的,哪些不是。 - -| 层 | 作者 | 职责 | -|---|---|---| -| 源 | 人或编码 Agent | .mq.md;唯一语义权威 | -| 目录包 | marqdo catalog | 模块、符号、能力与图投影 | -| 任务知识 | plan 晋升 | 任务、技能与可执行资源包 | -| 静态站 | marqdo view output | 人读 HTML,永远不是权威 | - -生成物带 GENERATED 标记,可以删除重建;没有它们源树仍能运行。Catalog 是索引,不是语言特性。 - ---- - -EKC:Engineering Knowledge Compiler。 - -EKC 把仓库投影成工程知识系统,并在 Agent 写新代码前提供 preflight: - -```text -.mq.md ──► EKC ──► catalog L0–L4 - ├─ graph - ├─ context pack - └─ Agent preflight -``` - -| 层 | 知识 | 例子 | -|---|---|---| -| L0 Repository | 语言、规模、根目录 | 仓库总览 | -| L1 Module | imports、exports、职责 | 外联内核模块 | -| L2 Symbol | 签名、调用、指纹 | 外部源码中的函数 | -| L3 Capability | 工程能做什么 | 运行持久外联内核 | -| L4 Knowledge | 决策、约束、失败 | 为什么状态桥必须显式 | - -图记录 implements、uses、depends_on、tested_by、documented_by、constrained_by、decided_by、supersedes、conflicts_with、deprecated_by 等关系。Agent 先沿图发现已有能力,而不是重新造轮子。 - ---- - -Engineering First Information:先发现,再创建。 - -复用协议是硬顺序: - -```text -REUSE → ADAPT → CREATE -``` - -preflight 可以在实现开始前返回已有能力、API、约束、决策与失败经验。知识图缺失时返回明确的 missing_knowledge,而不是静默编造。 - -五条原则: - -| # | 原则 | -|---|---| -| 1 | Discover before Create | -| 2 | Reuse before Adapt | -| 3 | Adapt before Duplicate | -| 4 | Verify before Promote | -| 5 | Code changes update knowledge | - ---- - -命令。 - -```bash -# 把仓库投影成 catalog + EKC 制品 -marqdo catalog . - -# 写代码前先问:已经有了什么? -marqdo knowledge preflight "增加一个持久外联内核" -marqdo find "外联 会话" -marqdo reuse "实现 JSON 并行扇出" - -# 看一次修改会影响什么 -marqdo impact public/features/19-外联视图单元.mq.md - -# 校验知识投影 -marqdo knowledge verify -``` - -`marqdo catalog` 保留人读的 `index.md` 与模块页;EKC 在 `.marqdo/` 下增加 L0–L4。两者都从同一棵源树生成。 - ---- - -每个声称的能力都必须有可执行资源。 - -一个知识页说“这个工程能分析订单”,就必须指向一个真正能跑的 `.mq.md` 资源。这是 OKF 形态的笔记与可执行知识系统的区别。 - -外联示例先用 Marqdo 固有能力分析订单,再把本地化展示交给 Node Intl。显式导入指向共享的可调用报表手册,页面本身声明实际的视图内核、原生值与单元。验收仍要检查逐单元的真实结果,不能把一份可序列化计划当作单元已经运行成功的证明。 - ---- - -继续阅读。 - -OKF 设计:[OKF 设计](../../doc/design/okf.md) - -Engineering Knowledge Compiler:[Engineering Knowledge Compiler](../../doc/design/engineering-knowledge.md) - -Catalog CLI:[Catalog CLI](../../doc/design/catalog-cli.md) - -OKF 与 Marqdo 调研:[OKF 与 Marqdo 调研](../../doc/research/okf-and-marqdo.md) - -外联 view 单元示例:[外联 view 单元示例](19-外联视图单元.mq.md) diff --git a/public/features/20-okf-ekc.mq.md b/public/features/20-okf-ekc.mq.md deleted file mode 100755 index 8c77599..0000000 --- a/public/features/20-okf-ekc.mq.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -markup: occlusion -title: Code as documentation, documentation as knowledge — OKF and EKC -description: How Marqdo keeps one executable source of truth while projecting it into OKF-style knowledge and Engineering Knowledge Compiler artifacts ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Marqdo's constitution is code as documentation and documentation as knowledge. A `.mq.md` file is not a screenshot of a program: it is the readable source, the executable unit and the knowledge page at the same time. - -That claim matters only if the knowledge stays derived from the source. OKF gives us the shape of a portable knowledge bundle; EKC gives us the engineering projection. Neither becomes a second source of truth. - ---- - -OKF shape, Marqdo meaning. - -OKF (Open Knowledge Format) describes knowledge as Markdown pages with YAML frontmatter: one concept per page, path as identity, links as graph, a deliberately small required surface. Marqdo borrows that shape, but its body is executable. - -A concept page can therefore point at the exact file that proves it: - -```yaml -type: Capability -title: Persistent foreign kernels -description: Run an explicitly declared local kernel with native data -resource: public/features/19-foreign-view-cells.mq.md -status: stable -verified: - by: marqdo-knowledge/verify -tags: - - foreign - - view-cells -``` - -The same page can be opened in an editor, linked from a catalog, queried by an agent, and executed. Unknown fields are preserved; unknown types degrade to readable prose. The page is a concept, not a copy of one. - ---- - -What is generated, and what is not. - -| Layer | Author | Role | -|---|---|---| -| Source | person or coding agent | .mq.md; the only semantic authority | -| Catalog | marqdo catalog | module, symbol, capability and graph projection | -| Task knowledge | plan promotion | task, skill and executable resource bundle | -| Static site | marqdo view output | human-readable HTML, never an authority | - -Generated artifacts are marked GENERATED and can be deleted and rebuilt. The source tree still runs without them. A catalog is an index, not a language feature. - ---- - -EKC: the Engineering Knowledge Compiler. - -EKC projects the repository into an engineering knowledge system, then exposes it through a preflight before an agent writes new code: - -```text -.mq.md ──► EKC ──► catalog L0–L4 - ├─ graph - ├─ context pack - └─ Agent preflight -``` - -| Layer | Knowledge | Example | -|---|---|---| -| L0 Repository | language, size, roots | repository summary | -| L1 Module | imports, exports, responsibility | a foreign kernel module | -| L2 Symbol | signature, calls, fingerprint | a function in external source code | -| L3 Capability | what the project can do | run a persistent foreign kernel | -| L4 Knowledge | decisions, constraints, failures | why the bridge is explicit | - -The graph records relations such as implements, uses, depends_on, tested_by, documented_by, constrained_by, decided_by, supersedes, conflicts_with and deprecated_by. That graph is how an agent discovers existing capability before inventing a duplicate. - ---- - -Engineering First Information: discover before create. - -The reuse protocol is a hard order: - -```text -REUSE → ADAPT → CREATE -``` - -A preflight can return existing capabilities, APIs, constraints, decisions and failure notes before a new implementation starts. If the knowledge graph is missing, the result is an explicit missing_knowledge state, not a silent fabrication. - -The five principles are: - -| # | Principle | -|---|---| -| 1 | Discover before Create | -| 2 | Reuse before Adapt | -| 3 | Adapt before Duplicate | -| 4 | Verify before Promote | -| 5 | Code changes update knowledge | - ---- - -The commands. - -```bash -# Project the repository into catalog + EKC artifacts -marqdo catalog . - -# Ask what already exists before writing code -marqdo knowledge preflight "add a persistent foreign kernel" -marqdo find "foreign session" -marqdo reuse "implement JSON fan-out" - -# See what a change would touch -marqdo impact public/features/19-foreign-view-cells.mq.md - -# Validate the knowledge projection -marqdo knowledge verify -``` - -`marqdo catalog` keeps the human-readable `index.md` and module pages; EKC adds L0–L4 files under `.marqdo/`. Both are generated from the same source tree. - ---- - -Every claimed capability has an executable resource. - -A knowledge page that says “this project can analyze orders” must point to a `.mq.md` resource that actually runs. That is the difference between an OKF-shaped note and an executable knowledge system. - -The foreign example computes its order report in native Marqdo and uses Node Intl for locale-aware presentation. Explicit imports point to the shared callable report handbook, while the page declares the actual view kernels, values and cells. Inspect the real per-cell results; a serialized plan alone does not establish that its cells ran successfully. - ---- - -Read more. - -OKF design: [OKF design](../../doc/design/okf.md) - -Engineering Knowledge Compiler: [Engineering Knowledge Compiler](../../doc/design/engineering-knowledge.md) - -Catalog CLI: [Catalog CLI](../../doc/design/catalog-cli.md) - -OKF and Marqdo research: [OKF and Marqdo research](../../doc/research/okf-and-marqdo.md) - -Foreign view-cells example: [Foreign view-cells example](19-foreign-view-cells.mq.md) diff --git a/public/features/21-persistence.mq.md b/public/features/21-persistence.mq.md deleted file mode 100755 index 2e8e355..0000000 --- a/public/features/21-persistence.mq.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -markup: occlusion -title: Persist an actual formatting result through native writeback -import: - guide: ../../doc/library-development.mq.md - formatter: ../../examples/foreign-native-report/index.mq.md - writeback: lib/writeback.mq.md - result: lib/result.mq.md ---- - -The source remains the manual for this file operation. Its callable main computes -native data, crosses a genuine formatting boundary, checks the result and records -only the successful value. Invoke with process.exec,fs.write and --fs-root .; -static View uses the same source and embeds its actual observed output. - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with the actual string recorded in this source's total slot | - -A static View snapshot embeds executed output in HTML. Explicit writeback -instead keeps a selected value in this source file's named slot. A caller should -choose that file effect deliberately: this main needs process.exec and fs.write, -with --fs-root pointing at the repository. Reading the page alone does not write. - -The amount is computed by the native programming guide, then the shared example -uses Node Intl only for locale-aware currency formatting. Its persistent kernel -is closed before this page receives the result. No Python process, foreign file -writer or duplicated arithmetic participates. The exact returned string is then -passed to lib/writeback, so the file operation remains a Marqdo capability. - -The total slot below is actual recorded output. Repeated execution replaces that -same key rather than appending another slot. An unavailable interpreter or failed -formatting returns before the write; native write-policy or IO faults retain -their diagnostics. Writeback persists this selected ordinary value, not a live -kernel or arbitrary process memory. Review source changes with the repository's -normal diff workflow. For published docs use a static snapshot unless a living -auditable source result is intended, as it explicitly is in this demonstration. - -We **amount = [Compute the native amount](guide.计算金额(单价=190, 数量=5))**. - -`report` = - -| total | average | -|---|---| -| `amount` | `amount` | - -We **formatted = [Use only the actual Intl presentation gap](formatter.format_summary(report=`report`))**. -1. not access(`formatted`, "ok") - Return *formatted* before writing a result slot. -We **text = [Select the actual formatter output](access(access(formatted, "value"), "total"))**. -We **written = [Persist this actual output through Marqdo's native writeback](writeback.record(value=`text`, key="total"))**. - - -After the explicit native file operation, return *[The persisted formatted value](result.ok(value=`text`))*. diff --git a/public/features/21-持久化.mq.md b/public/features/21-持久化.mq.md deleted file mode 100755 index 11903c3..0000000 --- a/public/features/21-持久化.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -title: 用固有写回保存真实的格式化结果 -import: - 指南: ../../doc/library-development.mq.md - 例程: ../../examples/foreign-native-report/index.mq.md - 写回: lib/writeback.mq.md - 结果: lib/result.mq.md ---- - -调用 main 需要 process.exec,fs.write,并将 --fs-root 指向仓库根目录。这是本页明确声明的文件修改,普通阅读不会写文件。静态 View 与可调用函数使用同一份源码,输出来自实际执行。 - -## main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:保存到本页 total 槽位的实际文本 | - -静态快照把执行输出嵌入 HTML;显式写回则把选定结果保存在源码的命名槽位里。本页正是需要后者的活文档示例,调用者应先知道会修改本页,再授予 fs.write。写回后的值可以在普通 Markdown 源码和差异中审阅,不依赖仍存活的外部进程。 - -金额由原生开发指南计算,随后共享例程只调用 Node Intl 完成固有库尚未提供的本地化货币展示。例程检查每次求值并关闭其持久内核,调用者得到的已经是普通文本。没有 Python 编排,也没有外部文件写入器;保存动作继续使用 Marqdo 的 writeback。示例的金额为 950,当前区域设置下的文本为 ¥950.00,真实输出会成为下面的 total 槽位内容。 - -再次执行替换同一个键,不重复添加槽位。若解释器不可用或格式化失败,在写文件之前就返回真实失败;固有文件策略或 IO 错误也保留诊断。这里持久化的是已经选定的文本,不保存任意内核内存,也不能根据它重建活资源句柄。完成后可用正常的仓库差异审阅流程检查变更,再决定是否随文档提交。 - -面向读者的发布页面通常选择静态快照;明确需要在源码中保存最新运行结果的审计文档才使用写回。两者可以共存,但静态导出如果执行了本页,仍会尊重这个显式写回操作。权限不会因为文档外观而被隐式扩张,依赖步骤也不能在失败后继续伪造结果。 - -先**金额 = [计算需要展示的原生金额](指南.计算金额(单价=190, 数量=5))**. - -`report` = - -| total | average | -|---|---| -| `金额` | `金额` | - -再**格式结果 = [只把本地化展示交给 Intl](例程.format_summary(report=`report`, locale="zh-CN"))**。 -1. not access(`格式结果`, "ok") - 返回*格式结果*,失败时不进入文件写回。 -我们**正文 = [读取实际格式化文本](access(access(格式结果, "value"), "total"))**。 -随后**写入 = [使用固有写回能力保存真实文本](写回.record(value=`正文`, key="total"))**。 - - -写回完成后返回*[已经保存的格式化文本](结果.ok(value=`正文`))*。 diff --git a/public/features/22-call.mq.md b/public/features/22-call.mq.md deleted file mode 100755 index b785515..0000000 --- a/public/features/22-call.mq.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -markup: occlusion -title: Call one function: the same document is the tool -description: v2.2.0 marqdo call runs a function inside any .mq.md. The explanation, the implementation and the call are one page. ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -v2.2.0 adds one command: `marqdo call`. It adds no Markdown marker and no skill system. An ordinary .mq.md file is already a document, a piece of knowledge and a program. What was missing is a way to call one of its functions from outside. - -The usual command runs the whole file. Functions inside it run only when the entry calls them. Trying one calculation meant writing an entry, a print and a check. The smallest unit you can execute is now a function. - -```text -marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 -``` - -Standard output is 5. `--json` is for programs and agents: success carries the result, failure carries a diagnostic code, and the process exits non-zero. `--backend tree` and `--backend bytecode` both run that function. Another entry in the file is not used as a fallback. - -The second half of this page is itself a calculator. This command calls this page: - -```text -marqdo call public/features/22-call.mq.md calculator.add a=2 b=3 -``` - ---- - -The change is how the file is used. - -A person reads the sentences next to the function and sees what add computes. The compiler reads the same markers and checks parameters and the return. A developer composes the function into another program. A test passes inputs to this function and looks at the output, without a wrapper whose only job is to print. An agent reads what the function is for and runs the implementation that is already there, instead of reading the page and rewriting it. - -Those four uses are one call. Knowledge becomes a tool because knowledge can already run, now at function scope. The file does not need a special name, and it does not need to declare itself a skill. - ---- - -The command keeps a boundary. - -An external call defaults to a pure function. Writing files, starting a process, using the network or loading a plugin is refused before the function runs. Pass `--effects plugin` when the tool needs an ABI plugin (for example `ext/quantum`). Session bindings use `--session` and `--toget name` (or trailing `toget name`); later calls may pass `$name`. Nested sub-tools use a dotted path such as `outer.helper`. An instance method needs its receiver; this command does not invent one. - -The function must resolve to exactly one declaration. No match, or one short name that hits two functions, is a structured error. The command does not pick the first hit. Arguments bind through the signature and contract that the function already has. Missing, unknown and ill-typed arguments are diagnostics. - -After editing a function, call it again with the inputs that failed. A passing check is a reason to keep the edit. A test does not prove every input. It gives the edit a check that can be repeated. - -# calculator - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Object/type namespace for the child functions below; call the intended child directly | - -This is an ordinary Marqdo document. - -It holds a little reusable arithmetic. - -## add - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left operand supplied to this calculation | -| b | any | required | Right operand supplied to this calculation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -Add the numbers `a` and `b`. - -After these steps, return *[result]((`a` + `b`))*. - -## multiply - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | required | Left operand supplied to this calculation | -| b | any | required | Right operand supplied to this calculation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | - -Multiply the numbers `a` and `b`. - -After these steps, return *[result]((`a` * `b`))*. diff --git a/public/features/22-函数调用.mq.md b/public/features/22-函数调用.mq.md deleted file mode 100755 index 093966e..0000000 --- a/public/features/22-函数调用.mq.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -markup: occlusion -title: 函数级调用:同一份文档成为工具 -description: v2.2.0 的 marqdo call 让任意 .mq.md 里的函数可以带参数执行。说明、实现和调用是同一页。 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -v2.2.0 增加一条命令:`marqdo call`。它不新增 Markdown 标记,也不另建一套技能系统。一个普通的 .mq.md 本来就是文档、知识和程序。缺的是从外部直接调用其中某个函数。 - -以前日常用法是运行整份文件。入口对象跑完,里面的函数要等文件自己去调用。要试验一个计算,往往得再写入口、打印和检查。现在最小可执行单位是函数。 - -```text -marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 -``` - -标准输出是 5。`--json` 给程序和 Agent 读:成功时是带结果的对象,失败时是带诊断码的对象,退出码非 0。`--backend tree` 与 `--backend bytecode` 执行同一个函数。文件里即使还有别的入口,也不会改去跑那个入口。 - -本页后半本身就是一份计算器。下面这条命令调用的就是这一页: - -```text -marqdo call public/features/22-函数调用.mq.md 计算器.加法 a=2 b=3 -``` - ---- - -它解决的是使用方式,不是再写一份说明书。 - -人打开这一页,读函数旁边的句子,知道加法在算什么。编译器解析同一批标记,检查参数和返回。开发者把函数嵌进别的程序。测试对这个函数传入输入,看输出是不是期望值,不必为它包一层只用来打印的程序。Agent 读到的是函数的用途,执行的是已经写好的实现,而不是读完说明再临时重写一遍。 - -这四件事共用一次调用。知识成为工具,是「知识即可执行」在函数这一层上的结果。文件不需要改名,也不需要声明自己是技能。运行时和工具清单都不会把一页普通文档挡在门外。 - ---- - -边界也写在命令里。 - -外部调用默认只执行纯函数。写文件、起进程、访问网络、加载插件,会在运行前被拒绝,副作用不会发生。要放宽权限,仍走项目里已有的验证,而不是在这条命令上新开一个开关。实例方法需要接收者,不能靠这条命令凭空调用。 - -函数名必须能唯一对上。没有这个函数,或同一个短名指向两个函数,都会返回结构化错误,不会擅自挑第一个。参数按函数已有的签名和契约绑定:缺了、多了、类型不对,都是诊断,不是静默猜一个值。 - -改一个函数之后,用原来的输入再调用一次。结果对了,这个实现就留下来;不对,就还是原来的实现。测试不能证明所有输入都正确。它让修改有一个可以重复的检查点。 - -# 计算器 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | - -这是一个普通的 Marqdo 文档。 - -其中包含一些可以复用的数学计算知识。 - -## 加法 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | Left operand supplied to this calculation | -| b | any | 必填 | Right operand supplied to this calculation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -计算两个数字`a`和`b`的和。 - -完成上述步骤后,返回*[计算结果]((`a` + `b`))*。 - -## 乘法 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| a | any | 必填 | Left operand supplied to this calculation | -| b | any | 必填 | Right operand supplied to this calculation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | - -计算两个数字`a`和`b`的积。 - -完成上述步骤后,返回*[计算结果]((`a` * `b`))*。 diff --git a/public/features/23-prove.mq.md b/public/features/23-prove.mq.md deleted file mode 100644 index 58e0137..0000000 --- a/public/features/23-prove.mq.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -markup: occlusion -import: - result: ../../lib/result.mq.md -title: Prove what a page claims: theorem tables judged by Lean 4 -description: v2.8.0 marqdo prove compiles theorem tables to Lean 4 and judges them. Offline symbolic execution works without a toolchain and never outruns Lean. ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -v2.8.0 adds one command: `marqdo prove`. A theorem table in a knowledge file is compiled to Lean 4 and judged automatically. The claim stops being prose that a reader agrees with and becomes a statement a proof assistant checks. - -```text -marqdo prove examples/approval.mq.md --json -``` - -The pipeline has six stages: load, lower to an intermediate representation, type the claim, generate a Lean module, judge it, and issue a certificate. Judging has two layers. Offline symbolic execution runs first — path enumeration over the pure fragment, milliseconds, no toolchain required. When a Lean toolchain is available it re-checks the emitted module and upgrades the verdict. - -The status ladder is honest by construction: `proved > checked > unverified > rejected > unproved > error`. Offline `checked` is a decided trace for the explored paths, never a proof; `proved` exists only when Lean says so. Without a toolchain the verdict stays at `checked` or `unverified` and the process exits zero — advisory, not silent. `--require-lean` flips unjudged states into failures for CI. - -A false theorem does not get a shrug. The judge produces a counterexample witness — concrete input values that walk the function down a path where the conclusion fails — and points back at the theorem-table row. - -The boundary that makes this trustworthy is monotonicity: whatever the offline layer claims, Lean must be able to confirm. If the offline verdict says checked and Lean cannot prove it, or a counterexample is proven away, the command fails with `proof.divergence` and exits non-zero. A judger defect fails loudly; a green light is never defended. - -The fragment is deliberately small: pure functions, branch comparisons, call-trace shapes, constructor structure, interval restatements. Loops report `proof.foreach_pending` instead of pretending. Cross-module calls stay opaque until assumption tables arrive. Every simplification is recorded in the design docs, because a proof system that hides its boundaries is marketing, not verification. - -This page runs — the theorems below live in the same file that explains them. `轨迹` is the implicit call trace of the function: the big-amount path must pass through 复核, opaque calls append to it, and inlined `result.ok` constructors do not. - -# 台账 - -## 记一笔 -+ `金额` - -| 参数 | 类型 | 说明 | -|---|---|---| -| 金额 | int | 记账金额(元) | - -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 大额必经复核 | 包含(轨迹, "复核") | 金额 > 10000 | auto | -| 大额单次外呼 | 长度(轨迹) = 1 | 金额 > 10000 | auto | -| 必有回执 | 结果.ok = True | | auto | - -1. 当`金额`小于等于10000时 - **回执 = [直接记账](result.ok(value="记"))** -2. * - **复核结论 = [转复核](复核(金额=`金额`))** - **回执 = [采纳](result.ok(value=`复核结论`))** - -*回执* - -## 复核 -+ `金额` - -**复核回执 = [复核通过](result.ok(value="复核"))** - -*复核回执* diff --git a/public/keywords/bool-logic.mq.md b/public/keywords/bool-logic.mq.md deleted file mode 100755 index 3fbf84b..0000000 --- a/public/keywords/bool-logic.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -title: Booleans and logic -description: True / False / None and and / or / not ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Keywords: `True`, `False`, `None`, and `and` / `or` / `not`. - -We first **a = True** for the next step. -We first **b = False** for the next step. - -1. `a` and not `b` - We now **[Display this step's result](> print text="ok")**. -2. * - We now **[Display this step's result](> print text="fail")**. - -We first **probe = 1** for the next step. - -1. None - We now **[Display this step's result](> print text="none-truthy")**. -2. * - We now **[Display this step's result](> print text="none-falsy")**. diff --git a/public/keywords/input.mq.md b/public/keywords/input.mq.md deleted file mode 100755 index 97097c0..0000000 --- a/public/keywords/input.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -title: Built-in input -description: Read one line from stdin; optional prompt. Demo via frontmatter stdin. -stdin: Ada ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -The input builtin reads one line. For demos and marqdo view / static export, put sample lines in frontmatter (stdin:). CLI can also use a pipe or --stdin-file. Live view can override with the Preset input box. - -We first **name = [Compute name](input(prompt="Name: "))** for the next step. - -We now **[Display this step's result](> print text="Hello `name`!")**. diff --git a/public/keywords/print.mq.md b/public/keywords/print.mq.md deleted file mode 100755 index 7f4346a..0000000 --- a/public/keywords/print.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: Built-in print -description: Named and positional forms ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -The `print` builtin accepts named or positional arguments: - -We now **[Display this step's result](> print text="named form")**. - -We now **[Display this step's result](> print "positional")**. - -Named args may contain spaces; positional args may not. diff --git a/public/keywords/stdlib.mq.md b/public/keywords/stdlib.mq.md deleted file mode 100755 index b4cf79a..0000000 --- a/public/keywords/stdlib.mq.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -markup: occlusion -title: Built-ins len / str / int / type / trim / split / join / at -description: Host builtins for strings and tables ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Length and type: - -We first **s = "hello"** for the next step. - -We first **n = [Compute n](len(`s`))** for the next step. - -We now **[Display this step's result](> print text=`n`)**. - -We first **ty = [Compute ty](type(`s`))** for the next step. - -We now **[Display this step's result](> print text=`ty`)**. - -Trim, split, join, and index: - -We first **t = [Compute t](trim(value=" hi "))** for the next step. - -We first **parts = [Compute parts](split(value="a,b", sep=","))** for the next step. - -We first **mid = [Compute mid](at(value=`parts`, index=0))** for the next step. - -We first **j = [Compute j](join(value=`parts`, sep="-"))** for the next step. - -We now **[Display this step's result](> print text=`t`)**. - -We now **[Display this step's result](> print text=`mid`)**. - -We now **[Display this step's result](> print text=`j`)**. diff --git a/public/keywords/内核双名.mq.md b/public/keywords/内核双名.mq.md deleted file mode 100755 index 5f8d52f..0000000 --- a/public/keywords/内核双名.mq.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -markup: occlusion -title: 中英内核双名 -description: 无需导入:打印、长度、文本、整数 与 print / len / … ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -内核中英别名等价,可混用: - -我们先**s = "你好"**,供下一步使用。 - -我们先**n = [计算并保存 n](长度(值=`s`))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 - -随后我们**[显示当前步骤的结果](> print text="also-english")**。 diff --git a/public/keywords/布尔逻辑.mq.md b/public/keywords/布尔逻辑.mq.md deleted file mode 100755 index 922420b..0000000 --- a/public/keywords/布尔逻辑.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -title: 布尔与逻辑 -description: 真 / 假 / 空 与 且 / 或 / 非 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -关键字:`真`、`假`、`空`,以及 `且` / `或` / `非`。 - -我们先**a = True**,供下一步使用。 -我们先**b = False**,供下一步使用。 - -1. `a` 且 非 `b` - 随后我们**[显示当前步骤的结果](> 打印 内容="通过")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="失败")**。 - -我们先**probe = 1**,供下一步使用。 - -1. 空 - 随后我们**[显示当前步骤的结果](> 打印 内容="空为真")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="空为假")**。 diff --git a/public/keywords/打印.mq.md b/public/keywords/打印.mq.md deleted file mode 100755 index 11ecbc8..0000000 --- a/public/keywords/打印.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: 内置 打印 -description: 具名与位置两种写法 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -内置 `打印` 接受具名或位置实参: - -随后我们**[显示当前步骤的结果](> 打印 内容="具名写法")**。 - -随后我们**[显示当前步骤的结果](> 打印 "位置写法")**。 - -具名实参可以带空格;位置实参不可以。 diff --git a/public/keywords/标准库.mq.md b/public/keywords/标准库.mq.md deleted file mode 100755 index d0f17be..0000000 --- a/public/keywords/标准库.mq.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -markup: occlusion -title: 内置 长度 / 文本 / 整数 与 trim 等 -description: 主机内置;中文别名覆盖常用几个 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -长度与英文 `type`(类型无中文内核别名,见标准库文档): - -我们先**s = "你好"**,供下一步使用。 - -我们先**n = [计算并保存 n](长度(值=`s`))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 - -我们先**ty = [计算并保存 ty](type(`s`))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`ty`)**。 - -去空白、拆分、拼接、按下标(主机名仍为英文): - -我们先**t = [计算并保存 t](trim(value=" 嗨 "))**,供下一步使用。 - -我们先**parts = [计算并保存 parts](split(value="甲,乙", sep=","))**,供下一步使用。 - -我们先**mid = [计算并保存 mid](at(value=`parts`, index=0))**,供下一步使用。 - -我们先**j = [计算并保存 j](join(value=`parts`, sep="-"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`t`)**。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`mid`)**。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`j`)**。 diff --git a/public/keywords/输入.mq.md b/public/keywords/输入.mq.md deleted file mode 100755 index 1241408..0000000 --- a/public/keywords/输入.mq.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -markup: occlusion -title: 内置 输入 -description: 从 stdin 读一行;可选提示。演示数据写在 frontmatter 输入。 -输入: 小明 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -内置「输入」读一行。演示与 marqdo view / 静态导出可在 frontmatter 写「输入:」(或 stdin:)。CLI 也可用管道或 --stdin-file。Live view 可用 Preset input 覆盖。 - -我们先**名字 = [计算并保存 名字](输入(提示="名字:"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容="你好 `名字`!")**。 diff --git a/public/stdlib/00-overview.mq.md b/public/stdlib/00-overview.mq.md deleted file mode 100755 index 8f69a24..0000000 --- a/public/stdlib/00-overview.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: Standard library — overview -description: How to import official lib modules ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Version 2.6.0: each standard library is normally one lib/name.mq.md source file, which is its own handbook. No extra index is required. Read the parameter/default and return tables below its headings to call it; multi-file extensions use indexes to organize modules. The 61 public sources provide 650 functions. - -Import with a nested YAML import mapping. File, network and process effects still need authorization at the execution entry. marqdo call defaults to pure functions; file operations require explicit --effects and --fs-root. Contract documentation never grants permission. - -New bytes, archive, Result, document and collection workflows retain explicit platform limits. Check one-based paths versus legacy zero-based indexes before using arrays. Real workflows live in examples/stdlib-handbook; the development guide is doc/library-development.mq.md. - -Official libraries live under lib/ (alias std/). Use a nested import mapping in YAML frontmatter, for example a module alias mapped to lib/text.mq.md or lib/fs.mq.md. - -English-named files export English APIs; Chinese-named files export Chinese APIs. JSON is special: only lib/json.mq.md (shared by both languages). - -Importing selects the module; it does not replace effect authorization at the execution entry. Under marqdo view or static export, exit soft-fails and long sleeps are clamped so the console stays up. - -Modules: text (text / 文本), table (table / 表), files (fs / 文件), time (time / 时间), system (sys / 系统), json (json only), net (net / 网络), math (math / 数学), foreign (foreign / 外联), plugin (plugin / 插件), writeback (writeback / 自写回), subtask (subtask / 子任务). Foreign v2 adds structured invoke records, JSON calls, parallel fan-out, persistent Python/Node kernels, an explicit state bridge and document-native view cells — see stdlib/foreign.mq.md and features/19-foreign-view-cells.mq.md. - -From v0.1.2, official `lib/*.mq.md` is embedded in the `marqdo` binary (disk `lib/` or `MARQDO_LIB` still overrides). Standalone `.exe` works without a separate stdlib zip. - -Official optional extensions live under ext/ (not stdlib): ext/llm, ext/agent — see features/05-extensions.mq.md and doc/design/ext-llm.md / ext-agent.md. - -Sibling pages in this folder document each module. Chinese overview: 00-索引.mq.md. - -We now **[Display this step's result](> print text="stdlib overview ok")**. diff --git a/public/stdlib/00-索引.mq.md b/public/stdlib/00-索引.mq.md deleted file mode 100755 index 3df806d..0000000 --- a/public/stdlib/00-索引.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: 标准库 — 总览 -description: 如何导入官方 lib 模块 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -版本 2.6.0:标准库通常是单个 lib/名称.mq.md 文件,源码本身就是手册,不要求额外 index。直接阅读标题下的参数、默认值和返回表即可调用;多文件拓展库才通过 index 组织模块。当前 61 份公开标准库包含 650 个函数。 - -使用 YAML 的 import(或导入)映射导入模块。文件、网络、进程等副作用仍由运行入口授权;marqdo call 默认只运行纯函数,文件调用要明确 --effects 与 --fs-root。文档契约不会自动授予权限。 - -新增字节、归档、Result、文档操作及集合工作流;数组读写要注意一基路径与旧零基接口的区别。更完整的标准库源码在 lib/,真实工程在 examples/stdlib-handbook,开发规范见 doc/library-development.mq.md。 - -官方库在仓库 lib/(别名 std/)。在 YAML frontmatter 的 import 或导入映射中填写模块别名与路径,例如 lib/文本.mq.md 或 lib/文件.mq.md。 - -拉丁文件名导出英文 API;中文文件名导出中文 API。JSON 特例:只有 lib/json.mq.md(中英共用)。 - -导入只选择模块,不替代实际运行入口的副作用授权。marqdo view 或静态导出里,退出会软失败、长睡眠会被钳制,以免拖垮控制台。 - -模块:文本(text / 文本)、表(table / 表)、文件(fs / 文件)、时间(time / 时间)、系统(sys / 系统)、json(仅 json)、网络(net / 网络)、数学(math / 数学)、外联(foreign / 外联)、插件(plugin / 插件)、自写回(writeback / 自写回)、子任务(subtask / 子任务)。外联 v2 新增结构化执行记录、JSON 调用、并行扇出、Python/Node 持久内核、显式状态桥与文档原生 view 单元 — 见 stdlib/外联.mq.md 与 features/19-外联视图单元.mq.md。 - -自 v0.1.2 起,官方 `lib/*.mq.md` 内置于 `marqdo` 二进制(磁盘 `lib/` 或 `MARQDO_LIB` 仍可覆盖)。单独下载 `.exe` 即可导入标准库,无需再解压 stdlib 包。 - -官方可选扩展在 ext/(不是标准库):ext/llm、ext/agent — 见 features/05-扩展.mq.md。 - -各模块说明见本目录其它页。English: 00-overview.mq.md. - -随后我们**[显示当前步骤的结果](> 打印 内容="标准库总览就绪")**。 diff --git a/public/stdlib/foreign.mq.md b/public/stdlib/foreign.mq.md deleted file mode 100755 index fad27f7..0000000 --- a/public/stdlib/foreign.mq.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -markup: occlusion -title: lib/foreign — foreign kernels v2 -description: Structured execution, JSON calls, parallel fan-out, persistent kernels and an explicit state bridge -import: - foreign: lib/foreign.mq.md -stdin: 21 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -`lib/foreign` runs code fences and inline sources with local interpreters. v2 keeps the Markdown surface unchanged while adding structured records, JSON in/out, parallel fan-out, persistent Python/Node kernels and an explicit state bridge. - -The same file is still a document: a bound fence is readable Markdown, and `foreign.*` turns it into an executable unit. - ---- - -Probe before you run. - -We first **node = [Compute node](foreign.probe(lang="node"))** for the next step. - -We now **[Display this step's result](> print text=[ok](access(`node`, "ok")))**. -We now **[Display this step's result](> print text=[version](access(`node`, "version")))**. - -`probe` returns `{lang, cmd, path, ok, version, error}`. Omit `lang` to inspect every known language. - ---- - -A structured record, not just stdout. - -`marker` = -```node -console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950)); -``` - -We first **record = [Compute record](foreign.invoke(code=`marker`))** for the next step. - -We now **[Display this step's result](> print text=[ok](access(`record`, "ok")))**. -We now **[Display this step's result](> print text=[stdout](access(`record`, "stdout")))**. -We now **[Display this step's result](> print text=[code](access(`record`, "code")))**. - -`invoke` never throws on a process failure. Read `ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result` and `error` from one record. - ---- - -JSON in, JSON out. - -`format_money` = -```node -let input = ""; -process.stdin.on("data", chunk => { input += chunk; }); -process.stdin.on("end", () => { - console.log(JSON.stringify(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(JSON.parse(input)))); -}); -``` - -We first **single = [Compute single](foreign.call(code=`format_money`, input=21))** for the next step. - -We now **[Display this step's result](> print text=`single`)**. - -The input is encoded as JSON on stdin; the last stdout value is parsed as JSON. Use `output="json"` with `invoke` when you also want the raw record. - ---- - -Parallel fan-out. - -`numbers` = - -| value | -|-------| -| 1 | -| 2 | -| 3 | -| 4 | - -This single-column bound table is a native list of numbers, ready for the batch call. -We **formatted_batch = [Format each amount while retaining input order](foreign.call_many(code=`format_money`, inputs=`numbers`, concurrency=4))**. - -We now **[Display this step's result](> print text=`formatted_batch`)**. - -`call_many` applies one program to every input, runs independently, preserves input order, and returns parsed JSON results. `run_many` does the same for full invoke-option maps. - ---- - -A persistent kernel. - -We first **session = [Compute session](foreign.session_open(lang="node"))** for the next step. - -We first **first = [Compute first](foreign.session_eval(id=`session`, source="var money = new Intl.NumberFormat(\"en-US\", {style:\"currency\", currency:\"CNY\"});"))** for the next step. - -We first **second = [Compute second](foreign.session_eval(id=`session`, source="money.format(21)"))** for the next step. - -We now **[Display this step's result](> print text=[result](access(`second`, "result")))**. - -Variables created in the first evaluation survive into the second. The kernel is not a shell: use `session_eval`, `session_get`, `session_names`, then `session_close`. - ---- - -The explicit state bridge. - -We **[Copy the explicit rate into the existing kernel](foreign.session_set(id=`session`, name="rate", value=0.08))**. - -We first **rate = [Compute rate](foreign.session_get(id=`session`, name="rate"))** for the next step. - -We now **[Display this step's result](> print text=`rate`)**. - -After reading the copied value, we **[Close this persistent formatting kernel](foreign.session_close(id=`session`))**. - -This is a JSON copy, not shared memory. The kernel receives a value; Marqdo receives a value. There is no implicit mirroring and no hidden global namespace. - ---- - -Cells in view. - -`foreign.session` owns the document's kernel state. The kernel and cell order are ordinary tables passed as arguments; the names are free: - -```text -`分析内核` = - -| 名称 | 语言 | 命令 | 说明 | -|------|------|------|------| -| 分析 | node | | shared analysis | -| 复核 | node | | isolated review | - -`分析单元` = - -| 单元 | 内核 | 说明 | -|------|------|------| -| 准备数据 | 分析 | write state | -| 计算指标 | 分析 | read state | -| 独立复核 | 复核 | isolated kernel | - -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` -``` - -`view` consumes the `会话` handle and adds Run All, Step, kernel switching, a journal and per-cell state. Without `会话`, view cells are stateless one-shot runs: same shell, no persistent kernel. There is no second CLI mode. See the native-first Intl workflow in [`features/19-foreign-view-cells.mq.md`](../features/19-foreign-view-cells.mq.md). - ---- - -Safety defaults. - -| Boundary | Default | -|---|---| -| Execution | requires the host execution capability | -| Shell | no shell; arguments are split explicitly | -| Output | bounded, with truncated | -| Timeout | process group killed on Unix / taskkill /T on Windows | -| CWD | starts at the granted root; the child retains normal OS authority | -| Parallelism | capped fan-out; each item isolated | - -Read the full API in [../../lib/foreign.mq.md](../../lib/foreign.mq.md) and the design in [../../doc/design/foreign-kernel.md](../../doc/design/foreign-kernel.md). diff --git a/public/stdlib/fs.mq.md b/public/stdlib/fs.mq.md deleted file mode 100755 index a59c48e..0000000 --- a/public/stdlib/fs.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -title: lib/fs — files -description: Read and write text under the sandbox -import: - fs: lib/fs.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Filesystem helpers from lib/fs. Bare path words must not contain `/` (division). Prefer a same-folder name or a variable. - -We first **ok = [Compute ok](fs.exists(path="demo.txt"))** for the next step. - -1. `ok` - **打印 内容="demo-present"** -2. * - **打印 内容="demo-missing"** diff --git a/public/stdlib/json.mq.md b/public/stdlib/json.mq.md deleted file mode 100755 index 7205ce0..0000000 --- a/public/stdlib/json.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: lib/json — JSON -description: Shared EN/ZH path; parse and stringify (code-as-docs pilot) -import: - json: lib/json.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Shared JSON helpers for EN and ZH docs. Prefer parse, stringify, and quote. -Build maps with tables or table.put — not json.set chains. - -We first **obj = [Compute obj](json.parse(text="{}"))** for the next step. -We first **ty = [Compute ty](type(`obj`))** for the next step. -**打印 内容=`ty`** - -We first **out = [Compute out](json.stringify(value=`obj`))** for the next step. -**打印 内容=`out`** diff --git a/public/stdlib/math-plot-1.svg b/public/stdlib/math-plot-1.svg deleted file mode 100755 index ae318f6..0000000 --- a/public/stdlib/math-plot-1.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - -xy-3-2-1123-22460 - \ No newline at end of file diff --git a/public/stdlib/math.mq.md b/public/stdlib/math.mq.md deleted file mode 100755 index 72460e7..0000000 --- a/public/stdlib/math.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -title: lib/math — numbers, formulas, plots -description: High-school math stdlib (English) -import: - math: lib/math.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Import lib/math.mq.md. Runtime types: num (float) and formula (symbolic tree). Bind a formula with an empty-RHS assign followed by a `$$…$$` fence (same shape as table assigns). In view, Structure renders that fence with KaTeX. - -`f` = -$$ -x^2 - 2 -$$ - -Numeric helpers: pi, e, num, add/sub/mul/div/pow, sin/cos/tan, sqrt/abs/ln/exp, floor/ceil, min/max. Random: seed, random, random_int (reproducible after seed). - -Symbolic: formula(text), simplify, expand, diff, subs, eval, solve. - -Plotting (already in the library): plot / plot_points / plot_conic return SVG text. Axes include arrows and tick labels; grid is on by default (pass grid=False / grid=假 to hide). Optional path= writes a file under the sandbox. With no path, CLI auto-writes stem-plot-n.svg and prints plot: …; view embeds the SVG under Execution. - -diff / simplify / expand / partial subs return formula values so you can chain (e.g. differentiate twice, then plot or eval). - -We first **ty = [Compute ty](type(`f`))** for the next step. - -We now **[Display this step's result](> print text=`ty`)**. - -We first **df = [Compute df](math.diff(formula=`f`, var="x"))** for the next step. - -We now **[Display this step's result](> print text=`df`)**. - -We first **roots = [Compute roots](math.solve(formula=`f`, var="x"))** for the next step. - -We now **[Display this step's result](> print text=`roots`)**. - -We first **_svg = [Compute _svg](math.plot(formula=`f`, var="x", min=-3, max=3))** for the next step. - -We now **[Display this step's result](> print text="plot-ok")**. diff --git a/public/stdlib/net.mq.md b/public/stdlib/net.mq.md deleted file mode 100755 index b164dea..0000000 --- a/public/stdlib/net.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: lib/net — HTTP(S) -description: Minimal HTTP(S) client and URL encode -import: - net: lib/net.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Import lib/net.mq.md. Functions: http_get, http_post, http_post_sse, openai_sse_parse, http_request, url_encode. HTTPS and optional headers= map are supported. Default post content-type is JSON. `http_post_sse` / `openai_sse_parse` return OpenAI chat stream event lists (`delta` / `done`). - -We first **e = [Compute e](net.url_encode(text="hello world"))** for the next step. - -We now **[Display this step's result](> print text=`e`)**. diff --git a/public/stdlib/plugin.mq.md b/public/stdlib/plugin.mq.md deleted file mode 100755 index 14d8d68..0000000 --- a/public/stdlib/plugin.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: lib/plugin — native ABI -description: Load optional shared libraries (.dll / .so / .dylib) -import: - plugin: lib/plugin.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Import lib/plugin.mq.md. Functions: load(path), unload(), list(). After load, registered plugin names are callable like other functions. C ABI: include/marqdo_abi.h — see doc/design/ext-abi.md. Path must stay under the program sandbox (cwd / fs root). - -We first **names = [Compute names](plugin.list())** for the next step. - -We first **n = [Compute n](len(`names`))** for the next step. - -1. `n` >= 0 - We now **[Display this step's result](> print text="plugin-ok")**. -2. * - We now **[Display this step's result](> print text="plugin-bad")**. diff --git a/public/stdlib/subtask.mq.md b/public/stdlib/subtask.mq.md deleted file mode 100755 index 931a26f..0000000 --- a/public/stdlib/subtask.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: lib/subtask — concurrent tasks -description: Spawn file, function, or foreign code in parallel -import: - subtask: lib/subtask.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -spawn picks one mode (others default to None). - -path= runs a marqdo run child process; wait returns the exit code. - -fn= plus optional args= runs a function in a thread; wait returns the return value. - -code= runs a foreign fence subprocess; wait returns stdout text. - -lang= plus source= runs foreign source; wait returns stdout text. - -File children are silent unless quiet=False. Also: poll id=, kill id=, wait_all. Parent exit kills file/foreign children. - -We now **[Display this step's result](> print text="subtask overview ok")**. diff --git a/public/stdlib/sys.mq.md b/public/stdlib/sys.mq.md deleted file mode 100755 index 1f4286e..0000000 --- a/public/stdlib/sys.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: lib/sys — process -description: Env, dotenv, cwd, args, exit, exec -import: - sys: lib/sys.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Import lib/sys.mq.md. Functions: env_get, env_set, load_dotenv(optional path), args, cwd, exit(code), exec(cmd), stream_publish(event). load_dotenv does not override existing variables. Under view, exit soft-fails instead of killing the process. `stream_publish` feeds the view SSE EventBus. - -We first **d = [Compute d](sys.cwd())** for the next step. - -We first **n = [Compute n](len(`d`))** for the next step. - -1. `n` > 0 - We now **[Display this step's result](> print text="cwd-ok")**. -2. * - We now **[Display this step's result](> print text="cwd-empty")**. diff --git a/public/stdlib/table.mq.md b/public/stdlib/table.mq.md deleted file mode 100755 index 029005f..0000000 --- a/public/stdlib/table.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: lib/table — collections -description: put, append, and map helpers (code-as-docs pilot) -import: - table: lib/table.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Prefer table.put for element updates (at= text key, 1-based int, or list path). -Read with link-index get. Use json for parse/stringify only. - -We first **h = [Compute h](table.put(in=None, at="Authorization", value="Bearer-demo"))** for the next step. - -`xs` = - -| v | -|---| -| a | -| b | - -We first **xs = [Compute xs](table.put(in=`xs`, at=1, value="A"))** for the next step. -We first **n = [Compute n](table.rows(xs=`xs`))** for the next step. - -**打印 内容=[Authorization](access(h, "Authorization"))** -**打印 内容=[1](access(xs, "1"))** -**打印 内容=`n`** diff --git a/public/stdlib/text.mq.md b/public/stdlib/text.mq.md deleted file mode 100755 index 2a9bf8e..0000000 --- a/public/stdlib/text.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -title: lib/text — strings -description: Trim, split, join (code-as-docs pilot) -import: - text: lib/text.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Import lib/text. Bracket path or classic dotted calls both work. - -We first **t = [Compute t](text.str_trim(s=" marqdo "))** for the next step. -**打印 内容=`t`** - -We first **parts = [Compute parts](text.str_split(s="a,b,c", sep=","))** for the next step. -We first **j = [Compute j](text.str_join(xs=`parts`, sep="-"))** for the next step. -**打印 内容=`j`** diff --git a/public/stdlib/time.mq.md b/public/stdlib/time.mq.md deleted file mode 100755 index 1221ebe..0000000 --- a/public/stdlib/time.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: lib/time — clock -description: Unix time, format, parse, sleep -import: - time: lib/time.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Unix time helpers from lib/time. Patterns use strftime. - -We first **s = [Compute s](time.format(unix=0, pattern="%Y-%m-%d"))** for the next step. -**打印 内容=`s`** - -We first **u = [Compute u](time.parse(text="1970-01-01 00:00:00", pattern="%Y-%m-%d %H:%M:%S"))** for the next step. -**打印 内容=`u`** - -**[time.sleep_ms] ms=0** diff --git a/public/stdlib/writeback.mq.md b/public/stdlib/writeback.mq.md deleted file mode 100755 index 8ad1468..0000000 --- a/public/stdlib/writeback.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: lib/writeback — Jupyter-style writeback -description: Persist run output in the entry .mq.md file -import: - writeback: lib/writeback.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Writeback stores output in `` blocks in the **entry** file (the one you run). - -record value= — default: insert or replace the block below the call; at_end=true → single block at EOF. - -get / clear — read or remove the adjacent block (or EOF block when at_end=true). - -list — all output blocks in the entry file. - -We now **[Display this step's result](> print text="writeback overview ok")**. diff --git a/public/stdlib/外联.mq.md b/public/stdlib/外联.mq.md deleted file mode 100755 index 48e2fab..0000000 --- a/public/stdlib/外联.mq.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -markup: occlusion -title: lib/外联 — 外联内核 v2 -description: 结构化执行、JSON 调用、并行扇出、持久内核与显式状态桥 -导入: - 外联: lib/外联.mq.md -stdin: 21 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -`lib/外联` 用本机解释器运行代码围栏和内联源码。v2 不改 Markdown 表面,新增结构化记录、JSON 进出、并行扇出、Python/Node 持久内核和显式状态桥。 - -文件仍然是一篇文档:绑定的代码围栏是可读的 Markdown,`外联.*` 把它变成可执行单元。 - ---- - -先探测,再运行。 - -我们先**node = [计算并保存 node](外联.探测(语言="node"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=[ok](access(`node`, "ok")))**。 -随后我们**[显示当前步骤的结果](> 打印 内容=[version](access(`node`, "version")))**。 - -`探测` 返回 `{lang, cmd, path, ok, version, error}`。省略语言时探测所有已知语言。 - ---- - -结构化记录,而不只是 stdout。 - -`标记` = -```node -console.log(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(950)); -``` - -我们先**记录 = [计算并保存 记录](外联.执行(代码=`标记`))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=[ok](access(`记录`, "ok")))**。 -随后我们**[显示当前步骤的结果](> 打印 内容=[stdout](access(`记录`, "stdout")))**。 -随后我们**[显示当前步骤的结果](> 打印 内容=[code](access(`记录`, "code")))**。 - -`执行` 在进程失败时不抛错,而是在一条记录里给出 `ok`、`code`、`stdout`、`stderr`、`ms`、`timed_out`、`truncated`、`result` 与 `error`。 - ---- - -JSON 进,JSON 出。 - -`金额格式` = -```node -let input = ""; -process.stdin.on("data", chunk => { input += chunk; }); -process.stdin.on("end", () => { - console.log(JSON.stringify(new Intl.NumberFormat("zh-CN", {style:"currency", currency:"CNY"}).format(JSON.parse(input)))); -}); -``` - -我们先**单个 = [计算并保存 单个](外联.调用(代码=`金额格式`, 输入=21))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`单个`)**。 - -输入编码成 JSON 写到 stdin;stdout 的最后一个值再解析成 JSON。想同时保留原始记录时,用 `执行` 的 `输出="json"`。 - ---- - -并行扇出。 - -`数值表` = - -| 数值 | -|------| -| 1 | -| 2 | -| 3 | -| 4 | - -这张单列绑定表本身就是原生数值列表,可以直接交给批量调用。 -随后我们**格式列表 = [并行展示金额并保持输入顺序](外联.批量调用(代码=`金额格式`, 输入表=`数值表`, 并发=4))**。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`格式列表`)**。 - -`批量调用` 对每个输入独立运行同一程序,保持输入顺序并返回解析后的 JSON 列表;`批量运行` 对完整 invoke 选项表做同样的事。 - ---- - -持久内核。 - -我们先**会话 = [计算并保存 会话](外联.会话开启(语言="node"))**,供下一步使用。 - -我们先**第一次 = [计算并保存 第一次](外联.会话求值(标识=`会话`, 源码="var money = new Intl.NumberFormat(\"zh-CN\", {style:\"currency\", currency:\"CNY\"});"))**,供下一步使用。 - -我们先**第二次 = [计算并保存 第二次](外联.会话求值(标识=`会话`, 源码="money.format(21)"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=[result](access(`第二次`, "result")))**。 - -第一次求值创建的变量会保留到第二次。内核不是 shell:用 `会话求值`、`会话取值`、`会话变量`,最后 `会话关闭`。 - ---- - -显式状态桥。 - -我们**[将明确选定的值复制进已有内核](外联.会话设值(标识=`会话`, 名称="rate", 值=0.08))**。 - -我们先**利率 = [计算并保存 利率](外联.会话取值(标识=`会话`, 名称="rate"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`利率`)**。 - -读回所需结果后,我们**[关闭本次持久展示内核](外联.会话关闭(标识=`会话`))**。 - -这是 JSON 拷贝,不是共享内存:内核收到一个值,Marqdo 取回一个值。没有隐式镜像,也没有隐藏的全局命名空间。 - ---- - -view 中的单元。 - -`foreign.session` 拥有文档的内核状态。内核和单元顺序都是作为参数传入的普通表格,名字可以自由选择: - -```text -`分析内核` = - -| 名称 | 语言 | 命令 | 说明 | -|------|------|------|------| -| 分析 | node | | 共享分析 | -| 复核 | node | | 独立复核 | - -`分析单元` = - -| 单元 | 内核 | 说明 | -|------|------|------| -| 准备数据 | 分析 | 写入状态 | -| 计算指标 | 分析 | 读取状态 | -| 独立复核 | 复核 | 隔离内核 | - -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` -``` - -`view` 消费 `会话` 句柄,提供 Run All、Step、切换内核、journal 和单元状态。没有 `会话` 时,view 的 cells 是无状态的一次性运行:同一套外壳,但没有持久内核。没有第二个 CLI 模式。原生分析与 Intl 示例见 [`features/19-外联视图单元.mq.md`](../features/19-外联视图单元.mq.md)。 - ---- - -安全默认值。 - -| 边界 | 默认 | -|---|---| -| 执行 | 需要宿主执行能力 | -| Shell | 不经过 shell;参数显式切分 | -| 输出 | 有界,带 truncated | -| 超时 | Unix 杀进程组 / Windows taskkill /T | -| 工作目录 | 文件沙箱根目录;不隐式越界 | -| 并行 | 扇出有上限;每个任务隔离 | - -完整 API 见 [../../lib/外联.mq.md](../../lib/外联.mq.md),设计见 [../../doc/design/foreign-kernel.md](../../doc/design/foreign-kernel.md)。 diff --git a/public/stdlib/子任务.mq.md b/public/stdlib/子任务.mq.md deleted file mode 100755 index c2fac20..0000000 --- a/public/stdlib/子任务.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: lib/子任务 — 并发子任务 -description: 文件、函数或外联代码并行执行 -导入: - 子任务: lib/子任务.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -启动(spawn)四选一(其余参数默认 None)。 - -路径=:marqdo run 子进程;等待返回退出码。 - -函数= 加可选 参数=:入口模块中的函数(线程);等待返回返回值。 - -代码=:外联代码块子进程;等待返回 stdout 文本。 - -语言= 加 源码=:外联源码子进程;等待返回 stdout 文本。 - -文件子任务默认静默;静默=假 时继承父终端。另有:探测、终止、等待全部。父进程结束会终止文件/外联子进程。 - -随后我们**[显示当前步骤的结果](> 打印 内容="子任务总览就绪")**。 diff --git a/public/stdlib/插件.mq.md b/public/stdlib/插件.mq.md deleted file mode 100755 index 62739b1..0000000 --- a/public/stdlib/插件.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: lib/插件 — 原生 ABI -description: 加载可选共享库(.dll / .so / .dylib) -导入: - 插件: lib/插件.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -导入 lib/插件.mq.md。函数:加载(路径)、卸载()、列出()。加载后,插件注册的名称可像普通函数一样调用。C 契约见 include/marqdo_abi.h 与 doc/design/ext-abi.md。路径须落在程序沙箱内。 - -我们先**names = [计算并保存 names](插件.列出())**,供下一步使用。 - -我们先**n = [计算并保存 n](长度(值=`names`))**,供下一步使用。 - -1. `n` >= 0 - 随后我们**[显示当前步骤的结果](> 打印 内容="插件就绪")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="插件异常")**。 diff --git a/public/stdlib/数学-plot-1.svg b/public/stdlib/数学-plot-1.svg deleted file mode 100755 index ae318f6..0000000 --- a/public/stdlib/数学-plot-1.svg +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - -xy-3-2-1123-22460 - \ No newline at end of file diff --git a/public/stdlib/数学.mq.md b/public/stdlib/数学.mq.md deleted file mode 100755 index d5205a8..0000000 --- a/public/stdlib/数学.mq.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -markup: occlusion -title: lib/数学 — 数值、公式、作图 -description: 高中数学标准库(中文) -导入: - 数学: lib/数学.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -导入 lib/数学.mq.md。运行时类型:num(浮点)与 formula(符号树)。用空 RHS 赋值后跟 `$$…$$` 围栏绑定公式(与表格赋值同构)。view 的 Structure 会用 KaTeX 渲染该公式。 - -`f` = -$$ -x^2 - 2 -$$ - -数值:圆周率、自然底数、数、加/减/乘/除/幂、正弦/余弦/正切、平方根/绝对值/对数/指数、向下取整/向上取整、最小/最大。随机:设种子、随机、随机整数。 - -符号:公式、化简、展开、求导、代入、求值、求解。 - -作图(库已提供):绘图 / 绘点列 / 绘圆锥,返回 SVG 文本。坐标轴带箭头与刻度;*默认显示网格*(`grid=假` 可关闭)。可选 path= 写盘。无 path 时 CLI 自动写 stem-plot-n.svg 并打印 plot: …;view 在 Execution 内嵌 SVG。 - -求导 / 化简 / 展开 / 未完全数值化的代入仍返回 formula,可继续链式调用(例如求二阶导后再绘图或求值)。 - -我们先**ty = [计算并保存 ty](type(`f`))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text=`ty`)**。 - -我们先**df = [计算并保存 df](数学.求导(formula=`f`, var="x"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text=`df`)**。 - -我们先**roots = [计算并保存 roots](数学.求解(formula=`f`, var="x"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text=`roots`)**。 - -我们先**_svg = [计算并保存 _svg](数学.绘图(formula=`f`, var="x", min=-3, max=3))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> print text="plot-ok")**。 diff --git a/public/stdlib/文件.mq.md b/public/stdlib/文件.mq.md deleted file mode 100755 index 18ce32d..0000000 --- a/public/stdlib/文件.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -title: lib/文件 — 文件系统 -description: 沙箱内读写文本 -导入: - 文件: lib/文件.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -文件系统助手(lib/文件)。裸路径不要写斜杠(会被当成除法)。可用同目录文件名或变量。 - -我们先**ok = [计算并保存 ok](文件.存在(路径="demo.txt"))**,供下一步使用。 - -1. `ok` - **打印 内容="有演示文件"** -2. * - **打印 内容="无演示文件"** diff --git a/public/stdlib/文本.mq.md b/public/stdlib/文本.mq.md deleted file mode 100755 index b42bab9..0000000 --- a/public/stdlib/文本.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -title: lib/文本 — 字符串 -description: 去空白、拆分、拼接(代码即文档试点) -导入: - 文本: lib/文本.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -导入 lib/文本。括号路径或经典点号调用均可。 - -我们先**t = [计算并保存 t](文本.去空白(s=" marqdo "))**,供下一步使用。 -**打印 内容=`t`** - -我们先**parts = [计算并保存 parts](文本.拆分(s="甲,乙,丙", sep=","))**,供下一步使用。 -我们先**j = [计算并保存 j](文本.拼接(xs=`parts`, sep="-"))**,供下一步使用。 -**打印 内容=`j`** diff --git a/public/stdlib/时间.mq.md b/public/stdlib/时间.mq.md deleted file mode 100755 index 67ac365..0000000 --- a/public/stdlib/时间.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: lib/时间 — 时钟 -description: Unix 时间、格式化、解析、睡眠 -导入: - 时间: lib/时间.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -这一页使用固定的 Unix 时间戳与固定日期文本,展示格式化和解析之间的关系。格式化得到 1970-01-01,解析得到相应秒数;它没有读取机器当前时钟。格式串使用 strftime 规则,接入其他来源时应明确原文本的时区与完整格式,不能根据看起来相似的日期就假设含义相同。 - -最后的零毫秒睡眠只演示调用位置,不用于测量调度精度,也不会制造实际等待。格式化、解析与睡眠有各自的效应和错误边界,按时间库契约授权即可。非法日期或格式不匹配时应保留诊断,不回退到时间戳零来掩盖失败。本页输出用于观察这两个固定值,不把打印结果写回源文件。 - -Unix 时间助手(lib/时间)。格式为 strftime。 - -我们先**s = [格式化给定的零时刻](时间.格式化(秒=0, 格式="%Y-%m-%d"))**,供下一步使用。 -**打印 内容=`s`** - -我们先**u = [解析当前日期或 URL 输入](时间.解析时间(内容="1970-01-01 00:00:00", 格式="%Y-%m-%d %H:%M:%S"))**,供下一步使用。 -**打印 内容=`u`** - -此处**[以零毫秒演示等待调用](时间.睡眠毫秒(毫秒=0))**,随后即可结束本页演示。 diff --git a/public/stdlib/系统.mq.md b/public/stdlib/系统.mq.md deleted file mode 100755 index 77c74cc..0000000 --- a/public/stdlib/系统.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: lib/系统 — 进程 -description: 环境变量、dotenv、工作目录、参数、退出、执行 -导入: - 系统: lib/系统.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -导入 lib/系统.mq.md。函数:取环境、设环境、加载环境(可选路径)、参数表、工作目录、退出(码)、执行(命令)。加载环境不覆盖已有变量。view 下退出会软失败,不结束进程。 - -我们先**d = [计算并保存 d](系统.工作目录())**,供下一步使用。 - -我们先**n = [计算并保存 n](长度(值=`d`))**,供下一步使用。 - -1. `n` > 0 - 随后我们**[显示当前步骤的结果](> 打印 内容="工作目录就绪")**。 -2. * - 随后我们**[显示当前步骤的结果](> 打印 内容="工作目录空")**。 diff --git a/public/stdlib/网络.mq.md b/public/stdlib/网络.mq.md deleted file mode 100755 index 1f914a8..0000000 --- a/public/stdlib/网络.mq.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -markup: occlusion -title: lib/网络 — HTTP -description: HTTP(S) 与地址编码 -导入: - 网络: lib/网络.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -导入 lib/网络.mq.md。函数:获取(地址)、提交(地址, 内容;可选 content_type / headers)、编码地址(内容)。支持 HTTP 与 HTTPS(ureq)。 - -我们先**e = [计算并保存 e](网络.编码地址(内容="你好"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`e`)**。 diff --git a/public/stdlib/自写回.mq.md b/public/stdlib/自写回.mq.md deleted file mode 100755 index facc756..0000000 --- a/public/stdlib/自写回.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: lib/自写回 — Jupyter 式写回 -description: 把运行结果写回入口 .mq.md -导入: - 自写回: lib/自写回.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -自写回把结果写入入口文件(你 run 的那份 .mq.md)里的 marqdo-out 注释块。 - -记录 内容=(record)— 默认写在调用下方;at_end=真 则在文件末尾单独一块。 - -读取 / 清除 — 读或删相邻块(at_end 时指 EOF 块)。 - -列表 — 列出文件中所有输出块。 - -随后我们**[显示当前步骤的结果](> 打印 内容="自写回总览就绪")**。 diff --git a/public/stdlib/表.mq.md b/public/stdlib/表.mq.md deleted file mode 100755 index e0a1430..0000000 --- a/public/stdlib/表.mq.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -markup: occlusion -title: lib/表 — 列表与字典 -description: 改 / 行数 / 取行(代码即文档试点) -导入: - 表: lib/表.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -先用一列表格表示两个文本元素,再替换第一项并保存返回的新列表。集合更新是不可变操作,若忽略返回值,原变量就仍指向旧数据。改操作的路径位置从一开始,而取行的 i 从零开始;本例刻意把两者并排展示,以免读者把不同接口的索引约定混为一谈。 - -更新后的第一项为甲改,列表长度仍为二,取行返回同一个第一项。本例不涉及文件、插件或解释器,输入与返回均是普通 Marqdo 值。真实业务可以继续组合筛选、映射和聚合;对于嵌套记录,先明确路径中每一段是字段名还是列表位置,并让缺失路径的诊断保持可见。打印只帮助观察,不会使后续函数自动获得这些值。 - -嵌套写入用 表.改;读元用链接取元。 - -`xs` = - -| v | -|---| -| 甲 | -| 乙 | - -我们先**xs = [替换列表第一项并保留新集合](表.改(入=`xs`, 于=1, 值="甲改"))**,供下一步使用。 -我们先**n = [取得本步骤需要的路径或计数](表.行数(xs=`xs`))**,供下一步使用。 -我们先**r = [按零起点读取第一行](表.取行(xs=`xs`, i=0))**,供下一步使用。 - -**打印 内容=[1](access(xs, "1"))** -**打印 内容=`n`** -**打印 内容=`r`** diff --git a/public/structure/01-hello.mq.md b/public/structure/01-hello.mq.md deleted file mode 100755 index c1f33c2..0000000 --- a/public/structure/01-hello.mq.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -markup: occlusion -title: Hello World -description: Smallest runnable doc ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Ordinary paragraphs are comments. `print` is a built-in, not a syntax marker. - -Lines that start with Markdown emphasis markers can be treated as code — keep narrative as plain prose. - -We now **[Display this step's result](> print text="Hello World!")**. diff --git a/public/structure/01-你好.mq.md b/public/structure/01-你好.mq.md deleted file mode 100755 index b53cefa..0000000 --- a/public/structure/01-你好.mq.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -markup: occlusion -title: 你好世界 -description: 最小可运行文档 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -普通段落是注释。`打印` 是内置函数,不是语法标记。 - -以 Markdown 强调标记开头的行可当作代码——叙述请用普通段落。 - -随后我们**[显示当前步骤的结果](> 打印 内容="你好世界!")**。 diff --git a/public/structure/02-function.mq.md b/public/structure/02-function.mq.md deleted file mode 100755 index 511017b..0000000 --- a/public/structure/02-function.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -title: Functions and named calls -description: Callable headings, narrative inputs and readable named calls ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Headings expose callable definitions. The input contract sits directly below the heading, and its body names the recipient in prose; callers supply that value by name. - -Call with `>` and named args `param=value`: - -We now **[Call greet](> greet who="World")**. - -## greet - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| who | any | required | Recipient name inserted into the greeting | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; display the computed content on stdout | -Input `who`, used by the steps below. - -We now **[Display this step's result](> print text="Hello `who`!")**. diff --git a/public/structure/02-函数.mq.md b/public/structure/02-函数.mq.md deleted file mode 100755 index b9d99d6..0000000 --- a/public/structure/02-函数.mq.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -markup: occlusion -title: 函数与具名调用 -description: `#` 定义函数;`>` 调用;`-` 列出参数名 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -用 `#` / `##` 定义函数。参数是标题下的裸 `- 名` 行。 - -用 `>` 与具名实参 `参数=值` 调用: - -随后我们**[执行 问候](> 问候 谁="世界")**。 - -## 问候 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 谁 | any | 必填 | 要显示在问候中的称呼 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;通过标准输出显示本函数计算的内容。 | -输入`谁`,按下方步骤使用这个值。 - -随后我们**[显示当前步骤的结果](> 打印 内容="你好 `谁`!")**。 diff --git a/public/structure/03-positional-call.mq.md b/public/structure/03-positional-call.mq.md deleted file mode 100755 index 5516c4b..0000000 --- a/public/structure/03-positional-call.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: Positional arguments -description: Bind by parameter order; named form still works ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Positional args bind in declaration order (no `who=` needed): - -We now **[Call greet](> greet "Marqdo")**. - -Named form still works: - -We now **[Call greet](> greet who="World")**. - -## greet - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| who | any | required | Recipient name inserted into the greeting | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; display the computed content on stdout | -Input `who`, used by the steps below. - -We now **[Display this step's result](> print text="Hello `who`!")**. diff --git a/public/structure/03-位置调用.mq.md b/public/structure/03-位置调用.mq.md deleted file mode 100755 index f78db05..0000000 --- a/public/structure/03-位置调用.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: 位置实参 -description: 按参数声明顺序绑定;具名写法仍然可用 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -位置实参按声明顺序绑定(不必写 `谁=`): - -随后我们**[执行 问候](> 问候 "Marqdo")**。 - -具名写法仍然可用: - -随后我们**[执行 问候](> 问候 谁="世界")**。 - -## 问候 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 谁 | any | 必填 | 要显示在问候中的称呼 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;通过标准输出显示本函数计算的内容。 | -输入`谁`,按下方步骤使用这个值。 - -随后我们**[显示当前步骤的结果](> 打印 内容="你好 `谁`!")**。 diff --git a/public/structure/04-branch.mq.md b/public/structure/04-branch.mq.md deleted file mode 100755 index 8140f15..0000000 --- a/public/structure/04-branch.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -title: Branch -description: Ordered branches select one case and retain an explicit fallback ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Bold markers execute statements and single italics return a value. Ordered list items select a branch; the final asterisk condition is the fallback when earlier conditions do not match. - -We first **x = 0** for the next step. - -1. `x` > 0 - We now **[Display this step's result](> print text="positive")**. -2. `x` < 0 - We now **[Display this step's result](> print text="negative")**. -3. * - We now **[Display this step's result](> print text="zero")**. diff --git a/public/structure/04-分支.mq.md b/public/structure/04-分支.mq.md deleted file mode 100755 index d162a36..0000000 --- a/public/structure/04-分支.mq.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -markup: occlusion -title: 分支 -description: `+` 各臂;单独的 `*` 臂为否则 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -斜体行是语句。分支用 `+`;表头仅为 `*` 的是否则臂。 - -我们先**x = 0**,供下一步使用。 - -1. `x` > 0 - 随后我们**[显示当前步骤的结果](> 打印 内容="正数")**。 -2. `x` < 0 - 随后我们**[显示当前步骤的结果](> 打印 内容="负数")**。 -3. * - 随后我们**[显示当前步骤的结果](> 打印 内容="零")**。 diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md deleted file mode 100755 index b746851..0000000 --- a/public/structure/05-loop.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: Loops -description: Condition loops and table walks ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -Inside a function body, `-` starts a loop (not a parameter). - -Countdown: - -We first **n = 3** for the next step. - -- `n` > 0 - We now **[Display this step's result](> print text=`n`)**. - We first **n = (`n` - 1)** for the next step. - -Walk a table (tables are collections): - -`basket` = - -| fruit | -|-------| -| apple | -| pear | - -- [fruit](遍历 basket 为 fruit) - We now **[Display this step's result](> print text="today `fruit`")**. diff --git a/public/structure/05-循环.mq.md b/public/structure/05-循环.mq.md deleted file mode 100755 index fcf8673..0000000 --- a/public/structure/05-循环.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: 循环 -description: 条件循环与表遍历 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -在函数体里,`-` 表示循环(不是参数)。 - -倒数: - -我们先**n = 3**,供下一步使用。 - -- `n` > 0 - 随后我们**[显示当前步骤的结果](> 打印 内容=`n`)**。 - 我们先**n = (`n` - 1)**,供下一步使用。 - -遍历表(表即集合): - -`篮子` = - -| 水果 | -|------| -| 苹果 | -| 梨 | - -- [水果](遍历 篮子 为 水果) - 随后我们**[显示当前步骤的结果](> 打印 内容="今天 `水果`")**。 diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md deleted file mode 100755 index 5e202fb..0000000 --- a/public/structure/06-collection.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: Collections (tables) -description: One-column tables are lists ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -A single-column Markdown table is a list; loop to read each item. Prefer link-index get `[1](basket)` (1-based). - -`basket` = - -| fruit | -|-------| -| apple | -| pear | -| peach | - -- [fruit](遍历 basket 为 fruit) - We now **[Display this step's result](> print text=`fruit`)**. diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md deleted file mode 100755 index bf6223c..0000000 --- a/public/structure/06-集合.mq.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -markup: occlusion -title: 集合(表) -description: 单列竖表即列表 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -单列 Markdown 表是列表;用循环读每一项。按下标优先用链接取元 `[1](篮子)`(1-based)。 - -`篮子` = - -| 水果 | -|------| -| 苹果 | -| 梨 | -| 桃 | - -- [水果](遍历 篮子 为 水果) - 随后我们**[显示当前步骤的结果](> 打印 内容=`水果`)**。 diff --git a/public/structure/07-map.mq.md b/public/structure/07-map.mq.md deleted file mode 100755 index 0f605db..0000000 --- a/public/structure/07-map.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: Maps (horizontal tables) -description: Multi-column tables are maps; link-index get ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -A multi-column table with one data row is a map. Read values with `[key](map)`. - -`kinds` = - -| apple | cucumber | -|-------|----------| -| fruit | vegetable | - -We first **k = [apple](access(`kinds`, "apple"))** for the next step. - -We now **[Display this step's result](> print text=`k`)**. - -We first **k = [cucumber](access(`kinds`, "cucumber"))** for the next step. - -We now **[Display this step's result](> print text=`k`)**. diff --git a/public/structure/07-字典.mq.md b/public/structure/07-字典.mq.md deleted file mode 100755 index aa9d6a1..0000000 --- a/public/structure/07-字典.mq.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -markup: occlusion -title: 字典(横表) -description: 多列表是字典;链接取元 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -多列且仅一行数据的表是字典。用 `[键](字典)` 取元。 - -`分类` = - -| 苹果 | 黄瓜 | -|------|------| -| 水果 | 蔬菜 | - -我们先**种 = [苹果](access(`分类`, "苹果"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`种`)**。 - -我们先**种 = [黄瓜](access(`分类`, "黄瓜"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`种`)**。 diff --git a/public/structure/08-records.mq.md b/public/structure/08-records.mq.md deleted file mode 100755 index 2ccdaca..0000000 --- a/public/structure/08-records.mq.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -markup: occlusion -title: Row records -description: First header @ / row makes a list of maps ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -When the first header is `@` or `row`, each data row is a map (marker column is not a field). Nested get: `[field]([1](orders))`. - -`orders` = - -| @ | name | qty | -|---|------|-----| -| 1 | apple | 2 | -| 2 | pear | 3 | - -We first **n = [name](access([1](access(`orders`, "1")), "name"))** for the next step. - -We now **[Display this step's result](> print text=`n`)**. - -We first **q = [qty](access([2](access(`orders`, "2")), "qty"))** for the next step. - -We now **[Display this step's result](> print text=`q`)**. diff --git a/public/structure/08-记录表.mq.md b/public/structure/08-记录表.mq.md deleted file mode 100755 index a11e68a..0000000 --- a/public/structure/08-记录表.mq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -markup: occlusion -title: 行向记录表 -description: 首列表头「行」→ 每行一个字典 ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -表头标记决定了这是一组行记录,而不是按列保存的字段列表。第一条记录的品名为苹果,第二条记录的数量为三;标记列只负责声明形态,不成为业务字段。读者可以先用 access 选出某一条记录,再按字段名取值,逐步核对每一步得到的是列表、记录还是标量。 - -本例保留两种字段类型:品名是文本,数量是整数,不把整张表先转成 JSON 再解析。遮蔽标签只写读取目的,真正的索引和字段名放在圆括号里;不要把标签中的数字当成另外一次索引。所有数据都来自本页,没有文件或网络访问。扩展字段时应同步更新相关函数的输入契约,让调用者知道新增列是否必填。 - -首列表头为 `行`(或 `@` / `row`)时,每行数据是一个字典;标记列不进入字段。嵌套取元:`[字段]([1](订单))`。 - -`订单` = - -| 行 | 品名 | 数量 | -|----|------|------| -| 1 | 苹果 | 2 | -| 2 | 梨 | 3 | - -我们先**名 = [品名](access([1](access(`订单`, "1")), "品名"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`名`)**。 - -我们先**量 = [数量](access([2](access(`订单`, "2")), "数量"))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`量`)**。 diff --git a/public/structure/09-inherit.mq.md b/public/structure/09-inherit.mq.md deleted file mode 100755 index 5f6efdc..0000000 --- a/public/structure/09-inherit.mq.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -markup: occlusion -title: Object inheritance -description: "# Child = > Parent; methods walk the base chain" ---- - -# Greeter - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Object/type namespace for the child functions below; call the intended child directly | - -## hello - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| who | any | required | Recipient name inserted into the greeting | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | -Input `who`, used by the steps below. - -We first **msg = "Hello, `who`!"** for the next step. -After these steps, return *msg*. - -# Loud = > Greeter - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Object/type namespace for the child functions below; call the intended child directly | - -## hello - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| who | any | required | Recipient name inserted into the greeting | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | -Input `who`, used by the steps below. - -We first **msg = "HELLO, `who`!"** for the next step. -After these steps, return *msg*. - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -We first **g = [Compute g](Greeter())** for the next step. -We first **m = `g`.hello(who="world")** for the next step. -We now **[Display this step's result](> print text=`m`)**. -We first **l = [Compute l](Loud())** for the next step. -We first **m2 = `l`.hello(who="world")** for the next step. -We now **[Display this step's result](> print text=`m2`)**. diff --git a/public/structure/09-继承.mq.md b/public/structure/09-继承.mq.md deleted file mode 100755 index 8f8e8bd..0000000 --- a/public/structure/09-继承.mq.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -markup: occlusion -title: 对象继承 -description: "# 子类 = > 父类;方法沿基类链查找" ---- - -# 问候者 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | - -## 你好 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 谁 | any | 必填 | 要显示在问候中的称呼 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | -输入`谁`,按下方步骤使用这个值。 - -我们先**msg = "你好,`谁`!"**,供下一步使用。 -完成上述步骤后,返回*msg*。 - -# 大声 = > 问候者 - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 供下述方法复用的对象或类型命名空间;直接调用所需的子函数。 | - -## 你好 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 谁 | any | 必填 | 要显示在问候中的称呼 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | -输入`谁`,按下方步骤使用这个值。 - -我们先**msg = "你好,`谁`!!!"**,供下一步使用。 -完成上述步骤后,返回*msg*。 - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -我们先**g = [计算并保存 g](问候者())**,供下一步使用。 -我们先**m = `g`.你好(谁="世界")**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=`m`)**。 -我们先**l = [计算并保存 l](大声())**,供下一步使用。 -我们先**m2 = `l`.你好(谁="世界")**,供下一步使用。 -随后我们**[显示当前步骤的结果](> 打印 内容=`m2`)**。 diff --git a/public/structure/import/main.mq.md b/public/structure/import/main.mq.md deleted file mode 100755 index 3b8d826..0000000 --- a/public/structure/import/main.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: Cross-file import -description: Frontmatter nested import: map -import: - utils: utils.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; execute this page's documented steps in order and observe their output or stated effects | - -In the YAML header, nested `import:` with `utils: utils.mq.md` imports a sibling module and binds the library name `utils`. - -Bind a return value, print it, then call greet: - -We first **y = [Compute y](utils.add_one(n=41))** for the next step. - -We now **[Display this step's result](> print text=`y`)**. - -We now **[Call utils.greet](> utils.greet who="Marqdo")**. diff --git a/public/structure/import/utils.mq.md b/public/structure/import/utils.mq.md deleted file mode 100755 index 7ec6a08..0000000 --- a/public/structure/import/utils.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: Utility module -description: Imported by main; italic is return; print for side effects ---- - -## add_one - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | required | Numeric input advanced or calculated by this example | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | The value explicitly returned below; conditional returns follow the selected branch | -Input `n`, used by the steps below. - -After these steps, return *(`n` + 1)*. - -## greet - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| who | any | required | Recipient name inserted into the greeting | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None; this function performs the described effects instead of returning business data | -Input `who`, used by the steps below. - -We now **[Display this step's result](> print text="Hello, `who`!")**. - -After these steps, return *None*. diff --git a/public/structure/import/主.mq.md b/public/structure/import/主.mq.md deleted file mode 100755 index 412251a..0000000 --- a/public/structure/import/主.mq.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -markup: occlusion -title: 跨文件导入 -description: frontmatter 导入 bind:路径.mq.md -导入: - 工具: 工具.mq.md ---- - -# main - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;按顺序执行本页的演示步骤,观察输出或已说明的副作用。 | - -在 YAML 头里写 `导入 工具:工具.mq.md` 可导入同级模块并绑定库名「工具」。 - -绑定返回值、打印,再调用问候: - -我们先**y = [计算并保存 y](工具.加一(n=41))**,供下一步使用。 - -随后我们**[显示当前步骤的结果](> 打印 内容=`y`)**。 - -随后我们**[执行 工具.问候](> 工具.问候 谁="Marqdo")**。 diff --git a/public/structure/import/工具.mq.md b/public/structure/import/工具.mq.md deleted file mode 100755 index f8c6eb3..0000000 --- a/public/structure/import/工具.mq.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -markup: occlusion -title: 工具模块 -description: 被 main 导入;斜体为返回;副作用用打印 ---- - -## 加一 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| n | any | 必填 | Numeric input advanced or calculated by this example | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 下文显式返回的计算值或结构化结果;分支存在时遵循实际命中的分支。 | -输入`n`,按下方步骤使用这个值。 - -完成上述步骤后,返回*(`n` + 1)*。 - -## 问候 - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| 谁 | any | 必填 | 要显示在问候中的称呼 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | 空值;本函数通过上述操作产生效果,不返回业务数据。 | -输入`谁`,按下方步骤使用这个值。 - -随后我们**[显示当前步骤的结果](> 打印 内容="你好,`谁`!")**。 - -完成上述步骤后,返回*None*。 diff --git a/rust-toolchain.toml b/rust-toolchain.toml deleted file mode 100755 index 0f102b7..0000000 --- a/rust-toolchain.toml +++ /dev/null @@ -1,4 +0,0 @@ -[toolchain] -channel = "1.81.0" -profile = "minimal" -components = ["rustfmt", "clippy"] diff --git a/scripts/agent-harness.sh b/scripts/agent-harness.sh deleted file mode 100755 index be31ba4..0000000 --- a/scripts/agent-harness.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env bash -# Wave B1 — offline constitution / OKF harness (no network required). -set -euo pipefail -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" -MQ="${MARQDO_BIN:-$ROOT/target/release/marqdo}" -export MARQDO_EXT="${MARQDO_EXT:-$ROOT/ext}" -export MARQDO_AGENT_PLUGIN="${MARQDO_AGENT_PLUGIN:-$ROOT/target/release/libagent.so}" -# Offline golds that construct an llm handle need a dummy key (no network). -export OPENAI_API_KEY="${OPENAI_API_KEY:-sk-test}" - -if [[ ! -x "$MQ" ]]; then - echo "missing $MQ — run: cargo build --release -p marqdo -p marqdo_plugin_agent" >&2 - exit 1 -fi - -fail=0 -run() { - local f="$1" - echo "==> $f" - if ! "$MQ" run "$f"; then - echo "FAIL $f" >&2 - fail=1 - fi -} - -run tests/ext/agent-constitution-b0.mq.md -run tests/ext/agent-dump-context.mq.md -run tests/ext/agent-writeback-shadow.mq.md -run tests/ext/agent-kb-plan-hit.mq.md -run tests/ext/agent-context-budget-a3.mq.md -run tests/ext/agent-workbook-patch-a0.mq.md -run tests/ext/agent-v2-learn.mq.md -run tests/ext/agent-p4-route.mq.md -run tests/ext/agent-small-llm-route.mq.md -run tests/ext/agent-mcp-client.mq.md -run tests/ext/agent-resume.mq.md -run tests/ext/agent-zero-llm.mq.md -run tests/ext/agent-plan-preserve.mq.md -run examples/agent-okf-flywheel/index.mq.md -run examples/agent-pong/index.mq.md -run examples/agent-sandbox-okf/index.mq.md -run tests/ext/agent-sandbox-optin.mq.md -run tests/ext/agent-sandbox-promote.mq.md - -# Skill Lift subset (O2 B3/E1): with-skill vs without — constitution / writeback / call_site markers. -skill_lift_pass=0 -skill_lift_fail=0 -assert_out_has() { - local f="$1" - local needle="$2" - local label="$3" - local out - out="$("$MQ" run "$f" 2>/dev/null || true)" - if printf '%s' "$out" | grep -q -- "$needle"; then - echo "SkillLift OK $label ($needle)" - skill_lift_pass=$((skill_lift_pass + 1)) - else - echo "SkillLift MISS $label (need $needle)" >&2 - skill_lift_fail=$((skill_lift_fail + 1)) - fail=1 - fi -} -assert_out_has tests/ext/agent-constitution-b0.mq.md "constitution-ok" "constitution" -assert_out_has tests/ext/agent-writeback-shadow.mq.md "writeback-shadow-ok" "writeback" -assert_out_has tests/ext/agent-dump-context.mq.md "dump-context-ok" "call_site" -echo "SkillLift summary: pass=$skill_lift_pass fail=$skill_lift_fail" - -if [[ "${AGENT_HARNESS_LIVE:-}" == "1" ]]; then - export AGENT_LIVE=1 - if [[ ! -f "$ROOT/.env" ]]; then - echo "AGENT_HARNESS_LIVE=1 needs repo-root .env (see .env.example)" >&2 - exit 1 - fi - run examples/agent-pong/index.mq.md - run tests/ext/agent-run-live.mq.md -fi - -if [[ "$fail" -ne 0 ]]; then - echo "agent harness: FAILED" >&2 - exit 1 -fi -echo "agent harness: OK" diff --git a/scripts/build-public.ps1 b/scripts/build-public.ps1 deleted file mode 100755 index e74c31a..0000000 --- a/scripts/build-public.ps1 +++ /dev/null @@ -1,6 +0,0 @@ -# Generate HTML next to public/*.mq.md via the Marqdo interpreter. -$ErrorActionPreference = "Stop" -Set-Location (Split-Path $PSScriptRoot -Parent) -cargo build --release -q -& .\target\release\marqdo.exe view output public -o public -Write-Host "OK → public/index.html + public/pages/ (sources: public/**/*.mq.md)" diff --git a/scripts/build-public.sh b/scripts/build-public.sh deleted file mode 100755 index 572d012..0000000 --- a/scripts/build-public.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -# Generate HTML next to public/*.mq.md via the Marqdo interpreter. -set -euo pipefail -cd "$(dirname "$0")/.." -cargo build --release -q -./target/release/marqdo view output public -o public -echo "OK → public/index.html + public/pages/ (sources: public/**/*.mq.md)" diff --git a/scripts/build-web-plugin.sh b/scripts/build-web-plugin.sh deleted file mode 100755 index 2d25291..0000000 --- a/scripts/build-web-plugin.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash -# Build Marqdo web plugin (Go → C shared library). -# Canonical output: plugins/web/build/libweb.so (Linux) / libweb.dylib / web.dll -# Also copies into target/{debug,release}/ for ext CLI and release packaging. -set -euo pipefail -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT/plugins/web" -mkdir -p build -export PATH="${HOME}/.local/go/bin:/usr/local/go/bin:${PATH}" -if ! command -v go >/dev/null 2>&1; then - echo "error: go not found (install Go 1.22+ or set PATH)" >&2 - exit 1 -fi -OUT="build/libweb.so" -case "$(uname -s)" in - Darwin) OUT="build/libweb.dylib" ;; - MINGW*|MSYS*|CYGWIN*|Windows_NT) OUT="build/web.dll" ;; -esac -echo "building $OUT (go $(go version | awk '{print $3}'))…" -CGO_ENABLED=1 go build -buildmode=c-shared -o "$OUT" . -ABS="$ROOT/plugins/web/$OUT" -BASE="$(basename "$OUT")" -for dir in "$ROOT/target/debug" "$ROOT/target/release"; do - mkdir -p "$dir" - cp -f "$ABS" "$dir/$BASE" -done -echo "ok: $ABS" -echo "also: $ROOT/target/debug/$BASE $ROOT/target/release/$BASE" -echo "hint: plugin.native_path name=web resolves these; override with MARQDO_WEB_PLUGIN=$ABS" diff --git a/scripts/capture-procurement-showcase.py b/scripts/capture-procurement-showcase.py deleted file mode 100644 index 2d9a687..0000000 --- a/scripts/capture-procurement-showcase.py +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env python3 -"""Reproducible marketing captures from the actual Marqdo 2.7.1 Linux CLI. - -All procurement outputs are simulation-only. The GIF is a curated display of -the real function-call JSON responses, not a filmed human typing session. -The screenshot is taken with a real headless browser from marqdo view output. -""" -from __future__ import annotations - -import argparse -import json -import subprocess -from pathlib import Path -from PIL import Image, ImageDraw, ImageFont - -ROOT = Path(__file__).resolve().parents[1] -OUT = ROOT / "assets" / "marketing" -SRC = "examples/procurement/index.mq.md" - -def invoke(cli, fn, args=(), effects=None): - cmd = [str(cli), "call", SRC, fn, *args] - if effects: - cmd += ["--effects", effects] - cmd.append("--json") - p = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=45) - if p.returncode != 0: - raise RuntimeError("Command failed:\n" + " ".join(cmd) + "\n" + p.stdout + "\n" + p.stderr) - try: - result = json.loads(p.stdout) - except json.JSONDecodeError as exc: - raise RuntimeError(f"Non-JSON CLI response {p.stdout!r}") from exc - if not result.get("ok"): - raise RuntimeError("Marqdo call rejected: " + p.stdout) - print("VERIFIED", fn, json.dumps(result, ensure_ascii=False)) - return result["result"] - -def font(size, bold=False): - for name in ( - "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", - "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", - ): - try: - return ImageFont.truetype(name, size) - except OSError: - continue - return ImageFont.load_default() - -def frame(index, headline, invocation, details, emphasis=None, danger=False): - W, H = 1200, 660 - img = Image.new("RGB", (W,H), (14,22,37)) - d = ImageDraw.Draw(img) - gold = (238,201,145); muted = (159,178,204) - d.rounded_rectangle((24,22,1175,635), radius=25, fill=(22,32,51), outline=(59,77,101), width=2) - d.text((53,49), "Marqdo", font=font(30,True), fill=gold) - d.text((231,57), "EXECUTABLE SKILLS / PROCUREMENT",font=font(19),fill=muted) - d.rounded_rectangle((976,44,1138,82), radius=16, fill=(39,54,75)) - d.text((1000,54),"v2.7.1",font=font(18),fill=(216,227,239)) - d.text((53,139),headline,font=font(32,True),fill=(245,244,239)) - d.text((54,188),"CALL",font=font(16,True),fill=gold) - d.rounded_rectangle((49,208,1150,293),radius=11,fill=(12,19,33)) - for i,line in enumerate(invocation): - d.text((66,223+i*34),line,font=font(19),fill=(194,221,240)) - d.text((54,336),"ACTUAL CLI RESULT / DOMAIN FIELDS",font=font(16,True),fill=gold) - d.rounded_rectangle((49,352,1150,536),radius=11,fill=(16,26,43)) - for i,line in enumerate(details[:5]): - d.text((69,371+i*33),line,font=font(20),fill=(219,233,241)) - if emphasis: - accent=(245,153,159) if danger else (155,231,185) - d.rounded_rectangle((52,554,1149,609),radius=10,fill=(68,38,48) if danger else (30,67,57)) - d.text((71,569),emphasis,font=font(22,True),fill=accent) - for i in range(5): - x=79+i*219 - d.rounded_rectangle((x,621,x+204,628),radius=3,fill=gold if i<=index else (69,81,99)) - d.text((855,641),f"FRAME {index+1} / 5 · SIMULATED ONLY",font=font(13),fill=muted) - return img - -def make_gif(cli): - suppliers=invoke(cli,"查询采购商",["采购商状态='正常'"]) - quote=invoke(cli,"查询采购商价格",["采购商标识符='SUP_JN'","数量=8","有效秒数=300"]) - balance=invoke(cli,"查询余额",["已花费=120"]) - orderargs=["采购商标识符='SUP_JN'","数量=8","单价=36","交付要求天数=7"] - good=invoke(cli,"向采购商发工单",orderargs+["已花费=120"],effects="time.read,process.control") - bad=invoke(cli,"向采购商发工单",orderargs+["已花费=360"],effects="time.read,process.control") - assert isinstance(suppliers,list) and any(x.get("标识符")=="SUP_JN" for x in suppliers), suppliers - assert quote["单价"]==36 and quote["报价总额"]==288,quote - assert balance["可用余额"]==480,balance - assert good["ok"] is True and good["value"]["工单金额"]==288 and good["value"]["状态"]=="本地模拟,未发送",good - assert bad["ok"] is False and "采购金额超过" in bad["error"],bad - - frames=[ - frame(0,"01 / Supplier approval", - ["$ marqdo call ... 查询采购商", " 采购商状态='正常'"], - [f"result: {len(suppliers)} approved suppliers", "SUP_JN / 江南配件 / 正常", "Paused and blacklisted suppliers excluded."], - "✓ SUP_JN passes supplier status"), - frame(1,"02 / Quote lookup", - ["$ marqdo call ... 查询采购商价格", " 采购商标识符='SUP_JN' 数量=8 有效秒数=300"], - [f"单价: ¥{quote['单价']}",f"数量: {quote['数量']}",f"报价总额: ¥{quote['报价总额']}","报价来源: 示例目录(未接实时接口)"], - "✓ ¥36 × 8 = ¥288 — example quote"), - frame(2,"03 / Budget check", - ["$ marqdo call ... 查询余额 已花费=120"], - [f"最高预算: ¥{balance['最高预算']}",f"已花费: ¥{balance['已花费']}",f"可用余额: ¥{balance['可用余额']}","还能下单: "+str(balance["还能下单"])], - "✓ ¥480 ≥ ¥288 — budget check passes"), - frame(3,"04 / Callable simulated order", - ["$ marqdo call ... 向采购商发工单", " SUP_JN 数量=8 单价=36 已花费=120"], - [f"result.ok: {str(good['ok']).lower()}", f"工单金额: ¥{good['value']['工单金额']}",f"状态: {good['value']['状态']}","No ERP message, payment or purchase was made."], - "✓ SIMULATED ORDER ONLY — NOT SENT"), - frame(4,"05 / Over-budget request denied", - ["$ marqdo call ... 向采购商发工单", " SUP_JN 数量=8 单价=36 已花费=360"], - [f"result.ok: {str(bad['ok']).lower()}","最高预算: ¥600","剩余额度: ¥240","工单金额: ¥288", "错误: "+bad["error"]], - "× WORK ORDER REFUSED AT RUNTIME",danger=True) - ] - OUT.mkdir(parents=True,exist_ok=True) - name=OUT/"procurement-cli.gif" - frames[0].save(name,save_all=True,append_images=frames[1:],duration=[1600,1600,1600,1900,2300],loop=0,optimize=True) - assert name.stat().st_size>10000, name - print("GIF_WRITTEN",name,name.stat().st_size) - -def make_screenshot(cli): - from selenium import webdriver - from selenium.webdriver.common.by import By - from selenium.webdriver.chrome.options import Options - import time - import tempfile - with tempfile.TemporaryDirectory() as td: - dest=Path(td)/"view" - cmd=[str(cli),"view","output","examples/procurement","--out",str(dest),"--no-exec"] - p=subprocess.run(cmd,cwd=ROOT,text=True,capture_output=True,timeout=90) - if p.returncode: - raise RuntimeError("View output error:\n"+p.stdout+"\n"+p.stderr) - pages=sorted(dest.rglob("*.html"),key=lambda p:len(p.parts)) - print("VIEW_PAGES",[str(p.relative_to(dest)) for p in pages[:40]]) - if not pages: - raise RuntimeError("No HTML pages emitted by Marqdo View") - chosen=next((p for p in pages if "向采购商发工单" in p.read_text(encoding="utf-8",errors="replace")),pages[0]) - opts=Options() - for arg in ["--headless=new","--no-sandbox","--disable-dev-shm-usage","--disable-gpu","--window-size=1500,1000"]: - opts.add_argument(arg) - driver=webdriver.Chrome(options=opts) - try: - driver.set_window_size(1500,1000) - driver.get(chosen.as_uri()) - time.sleep(2) - headings=driver.find_elements(By.CSS_SELECTOR,"h1,h2,h3,h4") - matches=[el for el in headings if "向采购商发工单" in el.text] - print("VIEW_HEADINGS",[(el.tag_name,el.text[:65]) for el in headings[:25]]) - if not matches: - raise RuntimeError("Couldn't find procurement function heading in exported View") - target=matches[0] - driver.execute_script("arguments[0].scrollIntoView({block:'start'}); window.scrollBy(0,-115);",target) - time.sleep(1) - shot=OUT/"procurement-view.png" - driver.save_screenshot(str(shot)) - assert shot.stat().st_size>20000,shot - print("VIEW_SCREENSHOT_WRITTEN",shot,shot.stat().st_size) - finally: - driver.quit() - -if __name__=="__main__": - a=argparse.ArgumentParser() - a.add_argument("--cli",required=True) - args=a.parse_args() - make_gif(Path(args.cli).resolve()) - make_screenshot(Path(args.cli).resolve()) diff --git a/scripts/check-layout.py b/scripts/check-layout.py new file mode 100644 index 0000000..69d091d --- /dev/null +++ b/scripts/check-layout.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +import argparse +import graphlib +import re +import subprocess +import sys +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +NAME = r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*" +FIELDS = {"id", "path", "kind", "state", "owner", "scope", "requires", "checks_with", "release"} +ROOT_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"} +ROOT_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts"} +RELEASE_ROLES = {"core": "base", "stdlib": "base", "extension": "optional", "tool": "optional", "test": "none"} + + +def git(*args, cwd=ROOT): + return subprocess.check_output(["git", "-C", cwd, *args]).decode() + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def catalog(revision): + components = tomllib.loads(git("show", f"{revision}:components.toml")) + require(set(components) == {"component"} and isinstance(components["component"], list), "invalid catalog") + by_id = {} + paths = set() + for component in components["component"]: + state = component.get("state") + fields = FIELDS | ({"entry"} if state == "active" else set()) + require(set(component) == fields and state in {"active", "planned"}, f"invalid fields: {component}") + id = component["id"] + kind = component["kind"] + require(isinstance(id, str) and re.fullmatch(NAME, id) and id not in by_id, f"invalid or duplicate id: {id}") + require(kind in RELEASE_ROLES and component["release"] == RELEASE_ROLES[kind], f"invalid release role: {id}") + path = component["path"] + expected = { + "core": "cli" if id == "cli" else None, + "test": "tests/conformance" if id == "conformance" else None, + "stdlib": f"stdlib/{id.removeprefix('std-')}" if id.startswith("std-") else None, + "extension": f"extensions/{id}", + "tool": f"tools/{id}", + }[kind] + require(path == expected and path not in paths, f"invalid or duplicate path: {path}") + for key in ("owner", "scope"): + require(isinstance(component[key], str) and component[key].strip(), f"missing {key}: {id}") + for key in ("requires", "checks_with"): + items = component[key] + require(isinstance(items, list) and all(isinstance(item, str) for item in items), f"invalid {key}: {id}") + require(id not in items and len(set(items)) == len(items), f"invalid {key}: {id}") + if state == "active": + require(re.fullmatch(r"(?:[a-zA-Z0-9_-]+/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*", component["entry"]), f"unsafe entry: {id}") + paths.add(path) + by_id[id] = component + + for id, component in by_id.items(): + for field in ("requires", "checks_with"): + for dependency in component[field]: + require(dependency in by_id, f"unknown dependency: {id} -> {dependency}") + target = by_id[dependency] + require(component["state"] != "active" or target["state"] == "active", f"active depends on planned: {id} -> {dependency}") + if field == "requires": + require(component["kind"] != "stdlib" or target["kind"] in {"core", "stdlib"}, f"stdlib dependency violation: {id} -> {dependency}") + require(component["kind"] != "tool" or target["kind"] == "core", f"tool dependency violation: {id} -> {dependency}") + tuple(graphlib.TopologicalSorter({id: item["requires"] for id, item in by_id.items()}).static_order()) + return by_id + + +def tree(revision): + entries = {} + for record in git("ls-tree", "-rz", "--full-tree", revision).split("\0"): + if record: + metadata, path = record.split("\t", 1) + mode, _, sha = metadata.split() + entries[path] = (mode, sha) + return entries + + +def validate(revision, checkouts): + components = catalog(revision) + active = {item["path"]: item for item in components.values() if item["state"] == "active"} + entries = tree(revision) + gitlinks = {path: sha for path, (mode, sha) in entries.items() if mode == "160000"} + require(gitlinks.keys() == active.keys(), f"gitlink/catalog mismatch: {sorted(gitlinks.keys() ^ active.keys())}") + for path, (mode, _) in entries.items(): + root = path.split("/", 1)[0] + require( + path in active or (mode in {"100644", "100755"} and ( + path in ROOT_FILES or root in ROOT_DIRS and "/" in path or path.startswith("tests/integration/") + )), + f"unexpected tracked path or mode: {path} ({mode})", + ) + + config = {} + for record in git("config", "--null", "--blob", f"{revision}:.gitmodules", "--list").split("\0"): + if record: + key, value = record.split("\n", 1) + require(key not in config, f"duplicate submodule setting: {key}") + config[key] = value + for path, item in active.items(): + prefix = f"submodule.{path}." + require(config.pop(prefix + "path", None) == path, f"missing or invalid submodule path: {path}") + name = item["id"] + if item["kind"] == "extension": + name = f"ext-{name}" + elif item["kind"] == "test": + name = "extension-conformance" + url = config.pop(prefix + "url", "") + require(url == f"https://git.cflmy.cn/cflmy/marqdo-{name}.git", f"invalid submodule URL: {path}") + if checkouts: + checkout = ROOT / path + sha = gitlinks[path] + require(checkout.resolve() == checkout and (checkout / ".git").exists(), f"missing submodule checkout: {path}") + require(git("rev-parse", "HEAD", cwd=checkout).strip() == sha, f"wrong checked-out commit: {path}") + require(not git("status", "--porcelain", cwd=checkout), f"dirty submodule: {path}") + entry = checkout / item["entry"] + require(entry.is_file() and entry.resolve() == entry, f"missing or symbolic entry: {path}/{item['entry']}") + print(f"{item['id']} {path} {gitlinks[path]}") + require(not config, f"unexpected submodule settings: {sorted(config)}") + + +def main(): + parser = argparse.ArgumentParser(description="Validate a Marqdo ecosystem Git tree") + parser.add_argument("revision", nargs="?", default="HEAD") + parser.add_argument("--checkouts", action="store_true") + args = parser.parse_args() + try: + validate(git("rev-parse", "--verify", args.revision + "^{commit}").strip(), args.checkouts) + except (AttributeError, KeyError, OSError, subprocess.CalledProcessError, TypeError, ValueError) as error: + sys.exit(f"layout: {error}") + + +if __name__ == "__main__": + main() diff --git a/scripts/check-proof-library.sh b/scripts/check-proof-library.sh deleted file mode 100755 index eb67d79..0000000 --- a/scripts/check-proof-library.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/sh -# 校验内嵌语义底座(src/prove/driver.rs include_str!)与 -# doc/verification/skill-proof/MarqdoProof.lean 一致,并输出其 sha256。 -# 用法:scripts/check-proof-library.sh [LEAN_BIN] -# LEAN_BIN 缺省用 PATH/MARQDO_PROOF_LEAN 里的 lean。 -set -eu - -cd "$(dirname "$0")/.." -LIB=doc/verification/skill-proof/MarqdoProof.lean -LEAN_BIN="${1:-${MARQDO_PROOF_LEAN:-lean}}" - -# 1) 内嵌源必须与仓库里的底座逐字节一致(发布二进制自带它)。 -# driver.rs 的 include_str! 在编译期锁定该路径;这里再防人手改跑偏。 -grep -q 'include_str!("../../doc/verification/skill-proof/MarqdoProof.lean")' src/prove/driver.rs - -# 2) 底座 sha256(写进判定证书,判定可复核)。 -if command -v sha256sum >/dev/null 2>&1; then - SHA=$(sha256sum "$LIB" | cut -d' ' -f1) -else - SHA=$(shasum -a 256 "$LIB" | cut -d' ' -f1) -fi -echo "MarqdoProof.lean sha256: $SHA" - -# 3) (可选)真机验底座本身可编译。 -if command -v "$LEAN_BIN" >/dev/null 2>&1; then - TMP=$(mktemp -d) - cp "$LIB" "$TMP/MarqdoProof.lean" - (cd "$TMP" && "$LEAN_BIN" -o MarqdoProof.olean MarqdoProof.lean) - rm -rf "$TMP" - echo "MarqdoProof.lean compiles with $LEAN_BIN" -else - echo "(未找到 $LEAN_BIN,跳过底座编译验证)" -fi diff --git a/scripts/deploy-public.ps1 b/scripts/deploy-public.ps1 deleted file mode 100755 index 3b9d444..0000000 --- a/scripts/deploy-public.ps1 +++ /dev/null @@ -1,52 +0,0 @@ -# Deploy public/ static site to branch gh-pages. -$ErrorActionPreference = "Stop" -$Root = Split-Path $PSScriptRoot -Parent -Set-Location $Root - -function Invoke-Git { - param([Parameter(ValueFromRemainingArguments = $true)][string[]]$GitArgs) - $prev = $ErrorActionPreference - $ErrorActionPreference = "Continue" - & git @GitArgs 2>&1 | Out-Null - $code = $LASTEXITCODE - $ErrorActionPreference = $prev - if ($code -ne 0) { throw "git $($GitArgs -join ' ') failed (exit $code)" } -} - -if (-not (Test-Path "public\index.html")) { - Write-Host "Building public site..." - cargo build --release -q - & .\target\release\marqdo.exe view output public -o public -} - -$staging = Join-Path $Root "dist\gh-pages-publish" -if (Test-Path $staging) { - $prev = $ErrorActionPreference - $ErrorActionPreference = "Continue" - git worktree remove $staging -f 2>&1 | Out-Null - $ErrorActionPreference = $prev - Remove-Item $staging -Recurse -Force -ErrorAction SilentlyContinue -} - -Invoke-Git fetch origin gh-pages -Invoke-Git worktree add -B gh-pages $staging origin/gh-pages - -Get-ChildItem $staging -Force | Where-Object { $_.Name -ne ".git" } | Remove-Item -Recurse -Force -Copy-Item -Recurse (Join-Path $Root "public\*") $staging -Force - -Set-Location $staging -Invoke-Git add -A -$status = git status --porcelain -if ($status) { - Invoke-Git commit -m "Deploy public site for v0.1.2" - Invoke-Git push origin gh-pages - Write-Host "Pushed gh-pages" -} else { - Write-Host "gh-pages unchanged" -} - -Set-Location $Root -$prev = $ErrorActionPreference -$ErrorActionPreference = "Continue" -git worktree remove $staging -f 2>&1 | Out-Null -$ErrorActionPreference = $prev diff --git a/scripts/dev-env.sh b/scripts/dev-env.sh deleted file mode 100755 index 252b3a9..0000000 --- a/scripts/dev-env.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash -# Marqdo dev environment. -# -# Usage: source scripts/dev-env.sh -# -# If a bundled toolchain is present under target/toolchain/, it is preferred; -# otherwise the script keeps using tools already installed on PATH. This makes -# the script work both in the maintained sandbox image and on a normal dev host. -# -# Two non-obvious constraints this script encodes: -# 1. $HOME is not writable -> zig/rust caches must be redirected explicitly. -# 2. /tmp is a noexec tmpfs -> anything a build *executes* from a temp dir -# fails with "AccessDenied" (zig link step) or "signal: aborted" (go link -# step via gcc). TMPDIR must point at a writable+executable dir. - -_marqdo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -_tc="$_marqdo_root/target/toolchain" -_zshim="${MARQDO_ZIG_SHIM:-$_marqdo_root/.tools/zigcc}" - -_prepend_existing() { - [ -d "$1" ] && PATH="$1:$PATH" -} - -export RUSTUP_HOME="${RUSTUP_HOME:-$_tc/rustup}" -export CARGO_HOME="${CARGO_HOME:-$_tc/cargo}" -export GOCACHE="${GOCACHE:-$_tc/gocache}" -export GOPATH="${GOPATH:-$_tc/gopath}" -export TMPDIR="${TMPDIR:-$_tc/tmp}" -export ZIG_GLOBAL_CACHE_DIR="${ZIG_GLOBAL_CACHE_DIR:-$_tc/zigcache}" -export ZIG_LOCAL_CACHE_DIR="${ZIG_LOCAL_CACHE_DIR:-$_tc/zigcache}" - -_prepend_existing "$_zshim/bin" -_prepend_existing "$_tc/bin" -_prepend_existing "$_tc/python/bin" -_prepend_existing "$_tc/go/bin" -_prepend_existing "$_tc/cargo/bin" - -# Rust: link through zig cc pinned to glibc 2.36 so the binary runs on this host. -if [ -x "$_zshim/cc" ] && [ -x "$_zshim/ar" ]; then - export CC="$_zshim/cc" - export CXX="$_zshim/cc" - export AR="$_zshim/ar" - export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER="$_zshim/cc" -fi - -mkdir -p "$TMPDIR" "$GOCACHE" "$GOPATH" "$ZIG_GLOBAL_CACHE_DIR" - -echo "marqdo dev-env: rust=$(rustc --version 2>/dev/null | cut -d' ' -f2 || echo missing) go=$(go version 2>/dev/null | awk '{print $3}' || echo missing) python=$(python3 --version 2>&1 | awk '{print $2}' || echo missing)" diff --git a/scripts/integration.sh b/scripts/integration.sh new file mode 100755 index 0000000..a317d9c --- /dev/null +++ b/scripts/integration.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." +root="$PWD" +python3 scripts/check-layout.py --checkouts +active="$(git ls-tree -r HEAD | awk '$1 == "160000" { print $4 }')" +expected=$'cli\ntests/conformance\ntools/knowledge\ntools/lint\ntools/prove\ntools/view' +if [[ "$active" != "$expected" ]]; then + echo "UNVERIFIED: update the integration plan for the changed active component set" >&2 + exit 1 +fi + +mkdir -p .integration-work +work="$(mktemp -d "$root/.integration-work/run.XXXXXX")" +echo "integration evidence: $work" +exec > >(tee "$work/run.log") 2>&1 +set -x +git rev-parse HEAD +git submodule status +uname -m +ldd --version +cargo --version +python3 --version +python3 -c 'import jsonschema' + +unset MARQDO_STDLIB_DIR +export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" +mkdir "$work/frozen" +frozen="$root/tools/view/scripts/frozen-beta.sh" +metadata="$("$frozen" metadata)" +artifact="$(sed -n 's/^artifact=//p' <<<"$metadata")" +if [[ -n "${MARQDO_INTEGRATION_ARCHIVE:-}" ]]; then + archive="$(realpath "$MARQDO_INTEGRATION_ARCHIVE")" + archive_sha="$(sed -n 's/^archive_sha=//p' <<<"$metadata")" + printf '%s %s\n' "$archive_sha" "$archive" | sha256sum -c - + tar -xzf "$archive" -C "$work/frozen" + MARQDO_BIN="$work/frozen/$artifact/marqdo" + "$frozen" verify "$MARQDO_BIN" +else + MARQDO_BIN="$("$frozen" fetch "$work/frozen")" + archive="$work/frozen/$artifact.tar.gz" +fi +export MARQDO_BIN +source_sha="$(git -C cli rev-parse HEAD)" +test "$(cat "$(dirname "$MARQDO_BIN")/SOURCE_SHA")" = "$source_sha" +sha256sum "$archive" "$MARQDO_BIN" "$(dirname "$MARQDO_BIN")/marqdo-provider-worker" + +python3 cli/tools/release/smoke.py --archive "$archive" +python3 cli/tools/ci/verify_extension_contracts.py \ + --source-repo cli --tested-sha "$source_sha" --cli "$MARQDO_BIN" \ + --release-info "$(dirname "$MARQDO_BIN")/RELEASE_INFO.json" \ + --fixtures tests/conformance --out "$work/conformance.json" + +( + cd tools/view + export MARQDO_TOOL_HOME="$work/view-registry" + scripts/package.sh + "$MARQDO_BIN" tool install dist/marqdo-view/tool.json + "$MARQDO_BIN" view verify examples/mixed-modes/index.mq.md + "$MARQDO_BIN" view export examples/tables-math --out "$work/view-export" + setsid "$MARQDO_BIN" view examples/control-flow --port 0 --no-open >"$work/view-server.log" 2>&1 & + view_pid=$! + stop_view() { + kill -- "-$view_pid" 2>/dev/null || true + wait "$view_pid" 2>/dev/null || true + } + trap stop_view EXIT + view_url="" + for attempt in {1..100}; do + view_url="$(grep -m1 -o 'http://127\.0\.0\.1:[0-9]\+/' "$work/view-server.log" || true)" + if [[ -n "$view_url" ]] || ! kill -0 "$view_pid" 2>/dev/null; then + break + fi + sleep 0.1 + done + if [[ -z "$view_url" ]]; then + cat "$work/view-server.log" >&2 + exit 1 + fi + python3 scripts/acceptance-run.py "$view_url" + stop_view + trap - EXIT + python3 scripts/check-observation.py stream-snapshot + "$MARQDO_BIN" tool remove view + if "$MARQDO_BIN" view --version; then + echo "view still dispatches after removal" >&2 + exit 1 + fi +) + +( + cd tools/knowledge + MARQDO_TEST_BIN="$MARQDO_BIN" cargo test --locked --test core_cli --test compile +) +( + cd tools/prove + cargo test --locked --test analysis_document --test document_contract +) +( + cd tools/lint + export MARQDO_TOOL_HOME="$work/lint-registry" + scripts/package-tool.sh "$work/lint" + "$MARQDO_BIN" tool install "$work/lint/tool.json" + "$MARQDO_BIN" lint examples/nested/inventory.mq.md --format json + "$MARQDO_BIN" tool remove lint +) + +echo "PASS: ecosystem RC.4 candidate checks" diff --git a/scripts/make-procurement-promo.py b/scripts/make-procurement-promo.py deleted file mode 100644 index b600857..0000000 --- a/scripts/make-procurement-promo.py +++ /dev/null @@ -1,369 +0,0 @@ -#!/usr/bin/env python3 -"""Make a 16:9 Marqdo promotional video from checked-in repository assets. - -Inputs: GIF generated from actual v2.7.1 CLI results, and screenshot captured -from actual v2.7.1 View. The budget scenario is explicitly simulated. -Everything used to reproduce this movie is in the repository. -No third-party soundtrack or music clips are used. -""" -from __future__ import annotations - -import math -import os -import subprocess -import tempfile -import wave -from bisect import bisect_right -from pathlib import Path - -import numpy as np -from PIL import Image, ImageDraw, ImageFont, ImageOps - -ROOT = Path(__file__).resolve().parents[1] -ASSETS = ROOT / "assets" / "marketing" -GIF = ASSETS / "procurement-cli.gif" -VIEW = ASSETS / "procurement-view.png" -PROC = ROOT / "examples" / "procurement" / "index.mq.md" -OUT = ASSETS / "marqdo-2.7.1-promo.mp4" -POSTER = ASSETS / "marqdo-2.7.1-poster.jpg" -SUBTITLES = ASSETS / "marqdo-2.7.1-promo.srt" -W, H, FPS = 1280, 720, 24 -DURATION = 32.0 -CUTS = [0.0, 3.9, 9.0, 17.4, 23.4, 29.0, DURATION] -DARK = (11, 19, 32) -GOLD = (232, 187, 123) -LIGHT = (248, 246, 238) -MUTED = (155, 174, 197) -GREEN = (125, 224, 174) -RED = (251, 151, 155) - -def rgb(c): - return tuple(c) - -def choose_font(size, bold=False, serif=False): - paths = [ - "/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc" if serif and bold else "", - "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc" if serif else "", - "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", - "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", - ] - for p in paths: - if not p: - continue - try: - return ImageFont.truetype(p, size) - except OSError: - continue - return ImageFont.load_default() - -F = { - "hero": choose_font(72, True), - "big": choose_font(55, True), - "h1": choose_font(42, True), - "h2": choose_font(31, True), - "mid": choose_font(25, True), - "code": choose_font(23), - "body": choose_font(22), - "small": choose_font(17), - "micro": choose_font(14), - "zh": choose_font(28, serif=True), -} - -def text(draw, xy, msg, font, color=LIGHT, anchor=None): - draw.text(xy, str(msg), font=font, fill=color, anchor=anchor) - -def panel(draw, xy, fill=(24,35,54), outline=(51,67,89), rad=23, width=2): - draw.rounded_rectangle(xy, radius=rad, fill=fill, outline=outline, width=width) - -def mix(a, b, t): - return a + (b-a)*t - -def ease(x): - u = max(0., min(1., x)) - return u*u*(3-2*u) - -def appear(t, delay=0., span=.65): - return ease((t-delay)/span) - -def xshift(t, delay=.0): - return int(38*(1-appear(t,delay))) - -def opacity_overlay(base, overlay, alpha): - return Image.blend(base, overlay, max(0.,min(1.,alpha))) - -def clipped(src, size, center=(.5,.5), zoom=1): - w,h=size - if zoom > 1: - p=ImageOps.fit(src,(int(w*zoom),int(h*zoom)),method=Image.Resampling.LANCZOS,centering=center) - z=(p.width-w)//2 - v=(p.height-h)//2 - return p.crop((z,v,z+w,v+h)) - return ImageOps.fit(src,size,method=Image.Resampling.LANCZOS,centering=center) - -def background(seed=0): - im = Image.new("RGB",(W,H),DARK) - pix=im.load() - for y in range(H): - for x in range(W): - glow= max(0,1-math.hypot((x-1090)/1.3,(y-95)/1.1)/520) - edge= max(0,1-math.hypot((x-25),y-690)/500) - pix[x,y]=(int(11+14*glow+7*edge),int(19+9*glow+7*edge),int(32+13*glow+10*edge)) - d=ImageDraw.Draw(im) - for x in range(45,W,82): - d.line((x,0,x,H),fill=(18,29,45),width=1) - for y in range(48,H,82): - d.line((0,y,W,y),fill=(18,29,45),width=1) - return im - -BG=background() - -def base_frame(t,scene): - im=BG.copy() - d=ImageDraw.Draw(im) - # top identity, bottom running progress - text(d,(63,35),"MARQDO",F["small"],GOLD) - text(d,(168,36),"/ EXECUTABLE AI SKILLS",F["micro"],MUTED) - d.rounded_rectangle((1079,21,1211,57),radius=15,fill=(40,51,68)) - text(d,(1095,30),"v2.7.1",F["small"],LIGHT) - d.line((62,76,1214,76),fill=(48,61,80),width=2) - d.line((62,694,1214,694),fill=(47,61,80),width=2) - d.line((62,694,62+int((1152)*(t/DURATION)),694),fill=GOLD,width=4) - text(d,(64,705),"DOCUMENT → FUNCTION → TOOL",F["micro"],(104,120,141)) - text(d,(1115,705),"%02d / 06" % (scene+1),F["micro"],(104,120,141)) - return im,d - -def scene_hero(local,global_t): - im,d=base_frame(global_t,0) - a=appear(local,.07) - yy=xshift(local,.08) - text(d,(69,167+yy),"Your SKILL",F["hero"],LIGHT) - text(d,(69,264+yy),"is now a",F["hero"],LIGHT) - text(d,(69,361+yy),"TOOL.",F["hero"],GOLD) - # typographic bar - x=69 - d.rounded_rectangle((x,485,x+min(643,int(643*a)),489),radius=2,fill=GOLD) - text(d,(71,520),"Write it. Inspect it. Call it.",F["mid"],LIGHT) - text(d,(71,573),"让可读文档中的函数,真正成为可调用工具。",F["zh"],(224,219,205)) - d.rounded_rectangle((975,207,1169,493),radius=25,fill=(26,37,57),outline=(84,99,118),width=2) - text(d,(1017,276),".mq.md",F["h2"],GOLD) - text(d,(1017,357),"01 Read",F["small"],MUTED) - text(d,(1017,399),"02 Call",F["small"],MUTED) - text(d,(1017,441),"03 Check",F["small"],MUTED) - return im - -SOURCE_LINES=[ - "## 向采购商发工单", - "采购商标识符 数量 单价 已花费", - "", - "正常商户 = 查询采购商(...)", - "报价 = 查询采购商价格(...)", - "预算 = 查询余额(已花费=...)", - "", - "1. 剩余额度 < 本单金额", - " → 拒绝模拟工单", -] -def scene_source(local,global_t): - im,d=base_frame(global_t,1) - text(d,(71,110),"ONE DOCUMENT.",F["h1"],LIGHT) - text(d,(71,159),"Contract, data, policy and implementation in the same .mq.md.",F["body"],MUTED) - panel(d,(67,205,842,642),fill=(18,28,44),outline=(72,91,113)) - d.rounded_rectangle((67,205,842,254),radius=17,fill=(35,48,67)) - text(d,(93,218),"index.mq.md / procurement skill",F["small"],GOLD) - ready=int(len(SOURCE_LINES)*ease((local-.40)/3.8)) - for i,ln in enumerate(SOURCE_LINES[:ready]): - clr=GOLD if i in (0,7) else GREEN if i==8 else (178,204,232) - text(d,(101,279+i*37),ln,F["code"],clr) - panel(d,(863,205,1214,642),fill=(24,35,55),outline=(74,88,107)) - for j,(label,desc) in enumerate([ - ("01 READ","human-readable"), - ("02 CHECK","typed contracts"), - ("03 CALL","marqdo call"), - ("04 RETURN","structured values") - ]): - y=268+j*96 - d.rounded_rectangle((888,y,1187,y+66),radius=13,fill=(30,48,65)) - text(d,(907,y+11),label,F["small"],GOLD) - text(d,(907,y+34),desc,F["micro"],(186,203,220)) - text(d,(71,662),"Excerpt simplified for screen layout; the full source is linked in the repository.",F["micro"],(110,135,154)) - return im - -GIF_FRAMES=[] -GIF_DURATIONS=[] -if GIF.exists(): - im=Image.open(GIF) - for i in range(getattr(im,"n_frames",1)): - im.seek(i) - GIF_FRAMES.append(im.convert("RGB").copy()) - GIF_DURATIONS.append(max(.3, im.info.get("duration",1600)/1000)) - if len(GIF_FRAMES) < 5: - raise RuntimeError(f"Expected >= 5 real CLI demonstration frames, found {len(GIF_FRAMES)}") -else: - raise FileNotFoundError(GIF) -GIF_CUM=[0.] -for dur in GIF_DURATIONS: - GIF_CUM.append(GIF_CUM[-1]+dur) -GIF_CYCLE=GIF_CUM[-1] -GIF_FITTED=[clipped(im,(1136,620)) for im in GIF_FRAMES] - -def scene_cli(local,global_t): - im,d=base_frame(global_t,2) - # The 5 panels are constructed from real calls and validated in the original capture script. - k=min(len(GIF_FITTED)-1,bisect_right(GIF_CUM,(local+.3)%GIF_CYCLE)-1) - im.paste(GIF_FITTED[k],(72,73)) - d=ImageDraw.Draw(im) - d.rectangle((73,73,1210,113),fill=(15,24,37)) - text(d,(91,82),"REAL CLI RETURNS / CURATED ANIMATED WALKTHROUGH",F["small"],GOLD) - d.rectangle((76,664,1206,688),fill=(15,24,37)) - text(d,(87,665),"Supplier → Quote → Balance → Mock order → Over-budget refusal",F["small"],LIGHT) - return im - -def scene_outcomes(local,global_t): - im,d=base_frame(global_t,3) - text(d,(70,113),"THE LIMIT IS EXECUTED.",F["h1"]) - text(d,(70,164),"Two calls. Same unit price. Different accumulated spend.",F["body"],MUTED) - q=ease((local-.6)/1.5) - left=120+int(288*q) - right=360+int(288*q) - panel(d,(70,219,616,610),fill=(17,49,43),outline=(69,124,102)) - panel(d,(652,219,1202,610),fill=(55,29,39),outline=(150,78,90)) - text(d,(99,253),"ALLOWED · SIMULATION",F["small"],GREEN) - text(d,(681,253),"DENIED · RUNTIME CHECK",F["small"],RED) - text(d,(99,304),"¥120 + ¥288",F["h2"],LIGHT) - text(d,(681,304),"¥360 + ¥288",F["h2"],LIGHT) - text(d,(99,396),"¥"+str(left),F["hero"],GREEN) - text(d,(681,396),"¥"+str(right),F["hero"],RED) - text(d,(103,445),"≤ ¥600",F["mid"],(196,239,212)) - text(d,(686,445),"> ¥600",F["mid"],(255,202,211)) - d.line((100,476,581,476),fill=(77,119,101),width=2) - d.line((681,476,1170,476),fill=(135,80,90),width=2) - text(d,(101,497),"ok: true",F["mid"],GREEN) - text(d,(680,497),"ok: false",F["mid"],RED) - text(d,(101,553),"本地模拟,未发送",F["body"],(211,233,220)) - text(d,(680,553),"采购金额超过剩余额度",F["body"],(251,213,217)) - text(d,(71,651),"The function re-checks its own budget constraints. This is an offline example, not a real purchase.",F["micro"],MUTED) - return im - -VIEW_IMAGE=Image.open(VIEW).convert("RGB") -VIEW_PANEL=(101,195,1179,635) -VIEW_MASK=Image.new("L",(VIEW_PANEL[2]-VIEW_PANEL[0],VIEW_PANEL[3]-VIEW_PANEL[1]),0) -ImageDraw.Draw(VIEW_MASK).rounded_rectangle((0,0,VIEW_MASK.width-1,VIEW_MASK.height-1),radius=18,fill=255) - -def scene_view(local,global_t): - im,d=base_frame(global_t,4) - text(d,(70,111),"THE SAME SOURCE, BEAUTIFULLY INSPECTABLE.",F["h2"]) - text(d,(71,158),"Marqdo 2.7.1 View — an actual screenshot of the procurement function.",F["body"],MUTED) - factor=1+.06*ease(local/5) - content=clipped(VIEW_IMAGE,(VIEW_MASK.width,VIEW_MASK.height),center=(.50,.38),zoom=factor) - im.paste(content,(VIEW_PANEL[0],VIEW_PANEL[1]),VIEW_MASK) - d=ImageDraw.Draw(im) - d.rounded_rectangle(VIEW_PANEL,radius=18,outline=(199,165,118),width=3) - text(d,(104,665),"From marqdo view output • function 向采购商发工单",F["small"],(187,207,222)) - return im - -def scene_outro(local,global_t): - im,d=base_frame(global_t,5) - text(d,(71,163),"One .mq.md",F["hero"],LIGHT) - text(d,(71,260),"Many ways to use it.",F["h1"],GOLD) - d.rounded_rectangle((70,365,1212,436),radius=19,fill=(33,49,67),outline=(81,101,124),width=2) - text(d,(107,381),"Write it. Inspect it. Call it.",F["h2"],LIGHT) - text(d,(73,490),"github.com/cflmy/marqdo",F["h1"],GOLD) - text(d,(73,548),"Marqdo 2.7.1 • Rust-based document-native runtime",F["body"],MUTED) - text(d,(73,613),"Demo uses simulated supplier data. No ERP connection or actual purchase.",F["small"],(176,190,204)) - return im - -SCENE_FNS=[scene_hero,scene_source,scene_cli,scene_outcomes,scene_view,scene_outro] -def render(t): - i=min(len(SCENE_FNS)-1,bisect_right(CUTS,t)-1) - im=SCENE_FNS[i](t-CUTS[i],t) - end=CUTS[i+1] - if i end-.43: - other=SCENE_FNS[i+1](0,t) - im=Image.blend(im,other,ease((t-(end-.43))/.43)) - return im - -def make_audio(path): - sr=24000 - count=round(DURATION*sr) - times=np.arange(count,dtype=np.float64)/sr - signal=np.zeros(count,dtype=np.float64) - chords=[(110.0,164.8,220.0),(123.5,185.0,246.9),(130.8,196.0,261.6),(110.0,174.6,220.0),(123.5,185.0,246.9),(130.8,196.0,261.6)] - for idx in range(6): - start,end=CUTS[idx],CUTS[idx+1] - mask=(times>=start)&(times {b}\n{c}" for i,(a,b,c) in enumerate(times))+"\n" - SUBTITLES.write_text(txt,encoding="utf-8") - -def main(): - if not PROC.exists() or not VIEW.exists(): - raise FileNotFoundError("Expected procurement source and actual View screenshot") - source=PROC.read_text("utf-8") - assert "## 向采购商发工单" in source and "查询余额" in source - assert VIEW_IMAGE.width >= 1200 and VIEW_IMAGE.height >= 700 - OUT.parent.mkdir(parents=True,exist_ok=True) - POSTER_IMG=render(1.8) - POSTER_IMG.save(POSTER,quality=92,optimize=True) - make_srt() - frames=int(DURATION*FPS) - with tempfile.TemporaryDirectory() as tmp: - unscored=Path(tmp)/"silent.mp4" - music=Path(tmp)/"music.wav" - cmd=["ffmpeg","-y","-hide_banner","-loglevel","error","-f","rawvideo", - "-pixel_format","rgb24","-video_size",f"{W}x{H}","-framerate",str(FPS), - "-i","pipe:0","-an","-c:v","libx264","-preset","veryfast","-crf","21", - "-pix_fmt","yuv420p","-movflags","+faststart",str(unscored)] - proc=subprocess.Popen(cmd,stdin=subprocess.PIPE,stderr=subprocess.PIPE) - try: - for k in range(frames): - fr=render(k/FPS) - proc.stdin.write(fr.tobytes()) - if k%120==0: - print("rendered",k,"/",frames,flush=True) - finally: - if proc.stdin: - proc.stdin.close() - stderr=proc.stderr.read().decode(errors="replace") - rc=proc.wait(timeout=70) - if rc: - raise RuntimeError("Video encoder error: "+stderr) - make_audio(music) - subprocess.run(["ffmpeg","-y","-hide_banner","-loglevel","error", - "-i",str(unscored),"-i",str(music),"-c:v","copy","-c:a", - "aac","-b:a","128k","-shortest","-movflags","+faststart", - str(OUT)],check=True,timeout=90) - print("VIDEO_WRITTEN",OUT,OUT.stat().st_size,flush=True) - print("POSTER_WRITTEN",POSTER,POSTER.stat().st_size,flush=True) - print("SUBTITLES_WRITTEN",SUBTITLES,SUBTITLES.stat().st_size,flush=True) - ffprobe=subprocess.run(["ffprobe","-v","error","-show_entries", - "format=duration,size:stream=codec_name,width,height", - "-of","json",str(OUT)],capture_output=True,text=True,check=True) - print("FFPROBE",ffprobe.stdout,flush=True) - assert OUT.stat().st_size>1000000, "Suspiciously small encoded video" - -if __name__=="__main__": - main() diff --git a/scripts/migrate-branch-ordered.py b/scripts/migrate-branch-ordered.py deleted file mode 100755 index 9633305..0000000 --- a/scripts/migrate-branch-ordered.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python3 -"""Migrate branch arms: + cond -> N. cond (params + `name` unchanged).""" -from __future__ import annotations - -import re -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -SKIP_DIRS = {"target", ".git", "node_modules"} - -PARAM_LINE = re.compile(r"^(\s{4,})\+ `([^`]+)`(=.*)?\s*$") -ORDERED = re.compile(r"^(\s*)(\d+)\.\s+(.*)$") -PLUS_BRANCH = re.compile(r"^(\s*)\+ (.+)$") - - -def migrate_text(text: str) -> str: - lines = text.splitlines(keepends=True) - out: list[str] = [] - arm = 0 - for line in lines: - raw = line.rstrip("\n\r") - end = line[len(raw) :] - if not raw.strip(): - arm = 0 - out.append(line) - continue - if PARAM_LINE.match(raw): - arm = 0 - out.append(line) - continue - m = PLUS_BRANCH.match(raw) - if m: - arm += 1 - indent, rest = m.groups() - out.append(f"{indent}{arm}. {rest}{end}") - continue - om = ORDERED.match(raw) - if om: - arm = int(om.group(2)) - out.append(line) - continue - stripped = raw.lstrip() - indent = raw[: len(raw) - len(stripped)] - if indent == 0 and ( - stripped.startswith("#") - or stripped.startswith(">") - or (stripped.startswith("*") and stripped.endswith("*")) - or stripped.startswith("`") - or stripped.startswith("|") - or stripped.startswith("---") - ): - arm = 0 - out.append(line) - return "".join(out) - - -def should_skip(path: Path) -> bool: - return any(part in SKIP_DIRS for part in path.parts) - - -def main() -> int: - changed = 0 - for path in sorted(ROOT.rglob("*.mq.md")): - if should_skip(path): - continue - text = path.read_text(encoding="utf-8") - new_text = migrate_text(text) - if new_text != text: - path.write_text(new_text, encoding="utf-8") - print(path.relative_to(ROOT)) - changed += 1 - print(f"migrated {changed} files") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/migrate-v02-syntax.py b/scripts/migrate-v02-syntax.py deleted file mode 100755 index d56380f..0000000 --- a/scripts/migrate-v02-syntax.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -"""One-shot migrate v0.2: params + `name`, foreach [`i`](`xs`).""" -from __future__ import annotations - -import re -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -SKIP_DIRS = {"man-test", "target", ".git", "node_modules"} - -PARAM_RE = re.compile( - r"^(\s+)- ([A-Za-z_\u4e00-\u9fff][A-Za-z0-9_\u4e00-\u9fff]*)(=(.*))?\s*$" -) -FOREACH_RE = re.compile(r"^(\s*)- \[([^\]]+)\]\(([^)]+)\)\s*$") - - -def wrap_id(name: str) -> str: - name = name.strip() - if name.startswith("`") and name.endswith("`"): - return name - return f"`{name}`" - - -def migrate_line(line: str) -> str: - m = FOREACH_RE.match(line) - if m: - indent, item, coll = m.groups() - return f"{indent}- [{wrap_id(item)}]({wrap_id(coll)})\n" - m = PARAM_RE.match(line) - if m: - indent, name, _, default = m.groups() - if default is not None: - return f"{indent}+ {wrap_id(name)}={default.rstrip()}\n" - return f"{indent}+ {wrap_id(name)}\n" - return line - - -def should_skip(path: Path) -> bool: - return any(part in SKIP_DIRS for part in path.parts) - - -def main() -> int: - changed = 0 - for path in sorted(ROOT.rglob("*.mq.md")): - if should_skip(path): - continue - text = path.read_text(encoding="utf-8") - lines = text.splitlines(keepends=True) - out = [migrate_line(ln) for ln in lines] - new_text = "".join(out) - if new_text != text: - path.write_text(new_text, encoding="utf-8") - print(path.relative_to(ROOT)) - changed += 1 - print(f"migrated {changed} files") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/mq-style-lint.sh b/scripts/mq-style-lint.sh deleted file mode 100755 index 8d141e3..0000000 --- a/scripts/mq-style-lint.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bash -# O4 — style gate: flag json.set dict chains and mixed EN/ZH API hints in .mq.md. -# Exit 0 when clean; 1 when findings (unless MQ_STYLE_LINT_SOFT=1). -set -euo pipefail -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" -TARGETS=("$@") -if [[ ${#TARGETS[@]} -eq 0 ]]; then - TARGETS=(ext/ai/sandbox.mq.md ext/ai/policies examples/agent-sandbox-okf) -fi - -fail=0 -findings=0 - -scan_file() { - local f="$1" - [[ -f "$f" ]] || return 0 - # Long json.set pipelines (3+ consecutive) — style bug per marqdo-dev. - if awk ' - /json\.set/ { c++; if (c >= 3) { found=1 } next } - { c=0 } - END { exit found ? 0 : 1 } - ' "$f"; then - echo "STYLE json.set-chain: $f" >&2 - findings=$((findings + 1)) - fail=1 - fi - # Same file imports both EN agent and ZH 智能体 (or web/网页) — mixed surface. - if grep -qE 'import[[:space:]]+agent:|import[[:space:]]+web:' "$f" \ - && grep -qE '导入[[:space:]]+(智能体|网页):' "$f"; then - echo "STYLE mixed-EN/ZH-import: $f" >&2 - findings=$((findings + 1)) - fail=1 - fi -} - -while IFS= read -r -d '' f; do - scan_file "$f" -done < <(find "${TARGETS[@]}" -type f -name '*.mq.md' -print0 2>/dev/null) - -echo "mq-style-lint: findings=$findings" -if [[ "${MQ_STYLE_LINT_SOFT:-}" == "1" ]]; then - exit 0 -fi -exit "$fail" diff --git a/scripts/optimize-standing-policy.sh b/scripts/optimize-standing-policy.sh deleted file mode 100755 index 441b19d..0000000 --- a/scripts/optimize-standing-policy.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env bash -# O5 — offline standing / policy rewrite hint (GEPA-like, products stay repo files). -# Does NOT change the runtime agent path. Reads harness failure log + current files, -# writes a suggested patch under .marqdo/optimize/ for human review. -set -euo pipefail -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" -LOG="${1:-}" -STANDING="${2:-ext/ai/agent.mq.md}" -POLICY="${3:-ext/ai/policies/step-route.mq.md}" -OUT_DIR="${OUT_DIR:-.marqdo/optimize}" -mkdir -p "$OUT_DIR" -STAMP="$(date -u +%Y%m%dT%H%M%SZ)" -REPORT="$OUT_DIR/standing-policy-$STAMP.md" - -{ - echo "# Offline standing / policy optimize suggestion" - echo - echo "Generated: $STAMP" - echo - echo "This is a **review artifact**, not an automatic runtime rewrite." - echo "Strong models may rewrite \`standing\` / \`policies/*.mq.md\` offline;" - echo "commit only after harness green." - echo - echo "## Inputs" - echo - echo "- standing source: \`$STANDING\`" - echo "- policy source: \`$POLICY\`" - if [[ -n "$LOG" && -f "$LOG" ]]; then - echo "- harness log: \`$LOG\`" - echo - echo "## Harness failure excerpt" - echo - echo '```' - tail -n 80 "$LOG" || true - echo '```' - else - echo "- harness log: _(none — pass path as \$1)_" - fi - echo - echo "## Current policy table (copy)" - echo - if [[ -f "$POLICY" ]]; then - echo '```markdown' - cat "$POLICY" - echo '```' - else - echo "_missing $POLICY_" - fi - echo - echo "## Suggested next edits" - echo - echo "1. Keep step-class → backend as a **GFM table** (no json glue)." - echo "2. Quarantine failing skills (\`status: quarantine\`) before promoting again." - echo "3. Re-run \`scripts/agent-harness.sh\` and confirm Skill Lift summary." -} > "$REPORT" - -echo "wrote $REPORT" diff --git a/scripts/ppa-build-source.sh b/scripts/ppa-build-source.sh deleted file mode 100755 index 1f496df..0000000 --- a/scripts/ppa-build-source.sh +++ /dev/null @@ -1,263 +0,0 @@ -#!/usr/bin/env bash -# Build a signed Ubuntu *source* package for Launchpad PPA. -# Usage: ./scripts/ppa-build-source.sh [series] -# Example: ./scripts/ppa-build-source.sh noble -# -# Launchpad builders have no network and noble's cargo (1.75) cannot read -# Cargo.lock v4. For a *new* upstream SemVer this script: -# 1) cargo vendor → vendor/ -# 2) installs a modern Rust toolchain into third_party/rust (cached) -# 3) packs both into the .orig.tar.xz for offline debuild on Launchpad -# -# For debian-only bumps (same upstream X.Y.Z already in the PPA): -# - Reuse the published marqdo_X.Y.Z.orig.tar.xz (never rewrite it) -# - debuild -S -sd (do not re-upload .orig) -# Override: MARQDO_PPA_FORCE_ORIG=1 rebuilds orig; MARQDO_PPA_ORIG=/path uses that file. -set -euo pipefail - -SERIES="${1:-noble}" -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" - -# File authoring uses the interpreter being released, including in package staging. -MARQDO_TOOL="${MARQDO_BIN:-$ROOT/target/debug/marqdo}" -if [ ! -x "$MARQDO_TOOL" ]; then - MARQDO_TOOL="$ROOT/target/release/marqdo" -fi -if [ ! -x "$MARQDO_TOOL" ]; then - MARQDO_TOOL="$(command -v marqdo || true)" -fi -if [ -z "$MARQDO_TOOL" ] || [ ! -x "$MARQDO_TOOL" ]; then - echo "error: build Marqdo or set MARQDO_BIN before packaging" >&2 - exit 1 -fi - -need() { command -v "$1" >/dev/null || { echo "missing tool: $1 (sudo apt install $2)"; exit 1; }; } -need cargo cargo -need debuild devscripts -need dpkg-parsechangelog dpkg-dev -need curl curl -need tar tar -need xz xz-utils - -# /tmp is often a small tmpfs; vendor + Rust extract exceed quota. Prefer disk. -if [ -z "${TMPDIR:-}" ] || [ "$TMPDIR" = /tmp ] || [ "$TMPDIR" = /var/tmp ]; then - TMPDIR="${HOME}/.cache/marqdo-ppa/work" -fi -mkdir -p "$TMPDIR" -export TMPDIR - -# The callable handbook owns metadata parsing; stdout contains the exact text. -VER="$("$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" upstream \ - --require-ok --effects fs.read --fs-root "$ROOT")" -DEB_VER="$("$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" debian_version \ - "series=\"$SERIES\"" --require-ok --effects fs.read --fs-root "$ROOT")" -PKG_ROOT="${TMPDIR}/marqdo-ppa/${VER}" -BUILD_AREA="${ROOT}/../build-area" -GPG_KEY="${MARQDO_PPA_GPG_KEY:-505943294D04C803}" -RUST_VER="${MARQDO_PPA_RUST_VERSION:-1.85.0}" -RUST_TRIPLE="${MARQDO_PPA_RUST_TRIPLE:-x86_64-unknown-linux-gnu}" -RUST_NAME="rust-${RUST_VER}-${RUST_TRIPLE}" -RUST_CACHE="${MARQDO_PPA_RUST_CACHE:-${HOME}/.cache/marqdo-ppa}" -RUST_TARBALL="${RUST_CACHE}/${RUST_NAME}.tar.gz" -RUST_URL="${MARQDO_PPA_RUST_URL:-https://static.rust-lang.org/dist/${RUST_NAME}.tar.gz}" -PPA_OWNER="${MARQDO_PPA_OWNER:-cflmy}" -PPA_NAME="${MARQDO_PPA_NAME:-marqdo}" -ORIG_NAME="marqdo_${VER}.orig.tar.xz" -FORCE_ORIG="${MARQDO_PPA_FORCE_ORIG:-0}" - -resolve_existing_orig() { - local candidate - if [ -n "${MARQDO_PPA_ORIG:-}" ]; then - candidate="${MARQDO_PPA_ORIG}" - if [ ! -f "$candidate" ]; then - echo "error: MARQDO_PPA_ORIG not a file: $candidate" >&2 - exit 1 - fi - echo "$candidate" - return 0 - fi - for candidate in \ - "$BUILD_AREA/$ORIG_NAME" \ - "$RUST_CACHE/$ORIG_NAME" \ - "$HOME/.cache/marqdo-ppa/$ORIG_NAME" - do - if [ -f "$candidate" ]; then - echo "$candidate" - return 0 - fi - done - return 1 -} - -download_published_orig() { - local dest="$1" - local urls=( - "https://ppa.launchpadcontent.net/${PPA_OWNER}/${PPA_NAME}/ubuntu/pool/main/m/marqdo/${ORIG_NAME}" - "https://launchpad.net/~${PPA_OWNER}/+archive/ubuntu/${PPA_NAME}/+files/${ORIG_NAME}" - ) - local url - mkdir -p "$(dirname "$dest")" - for url in "${urls[@]}"; do - echo " trying ${url}" - if curl -fL --retry 3 --retry-delay 2 --connect-timeout 30 \ - -o "${dest}.partial" "$url"; then - mv "${dest}.partial" "$dest" - return 0 - fi - rm -f "${dest}.partial" - done - return 1 -} - -echo "==> upstream ${VER} → debian ${DEB_VER} (${SERIES})" -rm -rf "$PKG_ROOT" -mkdir -p "$PKG_ROOT" "$BUILD_AREA" "$RUST_CACHE" - -REUSE_ORIG=0 -ORIG_PUBLISHED=0 -ORIG_SRC="" -if [ "$FORCE_ORIG" != "1" ]; then - # Prefer the bytes already accepted by Launchpad (rewriting .orig is rejected). - if download_published_orig "$RUST_CACHE/$ORIG_NAME"; then - ORIG_SRC="$RUST_CACHE/$ORIG_NAME" - ORIG_PUBLISHED=1 - elif ORIG_SRC="$(resolve_existing_orig)"; then - echo "warning: could not fetch PPA ${ORIG_NAME}; using local ${ORIG_SRC}" >&2 - echo "warning: if its sha256 differs from the archive, Launchpad will reject the upload" >&2 - fi - if [ -n "$ORIG_SRC" ]; then - REUSE_ORIG=1 - fi -fi - -if [ "$REUSE_ORIG" -eq 1 ]; then - echo "==> reusing published ${ORIG_NAME} (debian-only bump; do not rewrite orig)" - echo " source: ${ORIG_SRC}" - sha256sum "$ORIG_SRC" - # Local fallback may already be build-area/ORIG_NAME — do not cp onto itself. - if [ "$(realpath "$ORIG_SRC")" != "$(realpath "$BUILD_AREA/$ORIG_NAME" 2>/dev/null || echo "")" ]; then - cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME" - fi - # Unpack orig (top dir is usually ${VER} or marqdo-${VER}) - tar -xJf "$BUILD_AREA/$ORIG_NAME" -C "$(dirname "$PKG_ROOT")" - if [ ! -d "$PKG_ROOT" ]; then - # Some tarballs use marqdo-${VER}/ - if [ -d "$(dirname "$PKG_ROOT")/marqdo-${VER}" ]; then - mv "$(dirname "$PKG_ROOT")/marqdo-${VER}" "$PKG_ROOT" - else - echo "error: unpack did not create ${PKG_ROOT}" >&2 - tar -tJf "$BUILD_AREA/$ORIG_NAME" | head -5 >&2 - exit 1 - fi - fi - rsync -a "$ROOT/debian/" "$PKG_ROOT/debian/" -else - echo "==> building fresh ${ORIG_NAME} (new upstream or MARQDO_PPA_FORCE_ORIG=1)" - # Clean export of sources (no target/, .git) - if command -v git >/dev/null && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then - git archive --format=tar HEAD | tar -x -C "$PKG_ROOT" - else - rsync -a --exclude target --exclude .git --exclude build-area "$ROOT"/ "$PKG_ROOT"/ - fi - rsync -a "$ROOT/debian/" "$PKG_ROOT/debian/" - - cd "$PKG_ROOT" - echo "==> cargo vendor (Launchpad offline)" - mkdir -p .cargo - cargo vendor --locked vendor - "$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" vendor_config \ - --require-ok --effects fs.write --fs-root "$PKG_ROOT" --json - # dh_clean removes *.orig; drop those paths from vendor checksums so a - # stray clean (or older rules) cannot break `cargo --offline` on Launchpad. - "$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" sanitize_vendor \ - --require-ok --effects fs.write --fs-root "$PKG_ROOT" --json - - echo "==> bundle Rust ${RUST_VER} (${RUST_TRIPLE}) for Launchpad" - if [ ! -f "$RUST_TARBALL" ]; then - echo " downloading ${RUST_URL}" - curl -fL --retry 3 --retry-delay 2 -o "${RUST_TARBALL}.partial" "$RUST_URL" - mv "${RUST_TARBALL}.partial" "$RUST_TARBALL" - else - echo " cache hit ${RUST_TARBALL}" - fi - rm -rf third_party/rust - mkdir -p third_party - RUST_EXTRACT="$(mktemp -d "${TMPDIR:-/tmp}/marqdo-rust.XXXXXX")" - # Always drop the ~1.5G extract dir, even on failure (tmpfs fills up otherwise). - trap 'rm -rf "$RUST_EXTRACT"' EXIT - tar -xzf "$RUST_TARBALL" -C "$RUST_EXTRACT" - INSTALL_SH="$(find "$RUST_EXTRACT" -maxdepth 2 -name install.sh | head -1)" - if [ -z "$INSTALL_SH" ]; then - echo "error: install.sh not found in ${RUST_TARBALL}" >&2 - exit 1 - fi - # Launchpad builds need only rustc + cargo + rust-std (debian/rules PATH). - # install.sh's --without is a *single* comma-separated valopt; repeating - # --without=… keeps only the last flag, so rust-docs still installed and - # blew /tmp quota. Prefer explicit --components= instead. - bash "$INSTALL_SH" \ - --prefix="$PKG_ROOT/third_party/rust" \ - --components="rustc,cargo,rust-std-${RUST_TRIPLE}" \ - --disable-ldconfig - # Belt: docs must never ship in .orig (even if component list drifts). - rm -rf "$PKG_ROOT/third_party/rust/share/doc" - rm -rf "$RUST_EXTRACT" - trap - EXIT - "$PKG_ROOT/third_party/rust/bin/rustc" --version - "$PKG_ROOT/third_party/rust/bin/cargo" --version - du -sh "$PKG_ROOT/third_party/rust" - - cd "$(dirname "$PKG_ROOT")" - echo "==> packing ${ORIG_NAME} (vendor + third_party/rust)" - rm -f "$BUILD_AREA/$ORIG_NAME" - tar -cJf "$BUILD_AREA/$ORIG_NAME" \ - --exclude=debian \ - -C "$(dirname "$PKG_ROOT")" "$(basename "$PKG_ROOT")" -fi - -cd "$PKG_ROOT" -"$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" changelog \ - "version=\"$DEB_VER\"" "series=\"$SERIES\"" \ - --require-ok --effects fs.write --fs-root "$PKG_ROOT" --json - -ln -sfn "$BUILD_AREA/$ORIG_NAME" "$(dirname "$PKG_ROOT")/$ORIG_NAME" -ls -lh "$BUILD_AREA/$ORIG_NAME" - -cd "$PKG_ROOT" -# Local cache reuse does not prove Launchpad already has the orig archive. -# Include its unchanged bytes until the published download succeeds. -if [ "$ORIG_PUBLISHED" -eq 1 ]; then - DEBUILD_ORIG_FLAG="-sd" - echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; not re-uploading .orig)" -else - DEBUILD_ORIG_FLAG="-sa" - echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; including new .orig)" -fi -debuild -S ${DEBUILD_ORIG_FLAG} -k"${GPG_KEY}" -d - -# debuild writes next to package parent (/tmp/marqdo-ppa/); collect into build-area -mkdir -p "$BUILD_AREA" -shopt -s nullglob -for f in ../marqdo_"${DEB_VER}"* ../marqdo_"${VER}".orig.tar.*; do - [ -e "$f" ] || continue - if [ "$(realpath -m "$f")" = "$(realpath -m "$BUILD_AREA/$(basename "$f")")" ]; then - continue - fi - cp -f "$f" "$BUILD_AREA/" -done -shopt -u nullglob - -echo "==> artifacts in $BUILD_AREA:" -ls -la "$BUILD_AREA"/marqdo_"${DEB_VER}"* "$BUILD_AREA"/marqdo_"${VER}".orig.tar.* 2>/dev/null || true -if [ "$REUSE_ORIG" -eq 1 ]; then - echo " sha256 of reused orig (must match PPA):" - sha256sum "$BUILD_AREA/$ORIG_NAME" -fi -CHANGES="$BUILD_AREA/marqdo_${DEB_VER}_source.changes" -if [ -f "$CHANGES" ]; then - echo - echo "Upload with:" - echo " dput ppa:cflmy/marqdo $CHANGES" - echo " # or: ./scripts/ppa-ship.sh ${SERIES}" -fi diff --git a/scripts/ppa-ship.sh b/scripts/ppa-ship.sh deleted file mode 100755 index 45531cd..0000000 --- a/scripts/ppa-ship.sh +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env bash -# One-shot: install packaging tools → build signed source package → dput to Launchpad PPA. -# -# Run in YOUR terminal (needs sudo for apt + GPG passphrase for signing): -# ./scripts/ppa-ship.sh # default series: noble -# ./scripts/ppa-ship.sh resolute # match host /etc/os-release -# ./scripts/ppa-ship.sh noble --no-upload -# sudo ./scripts/ppa-ship.sh noble # also OK — build/sign/upload drop back to $SUDO_USER -# -# PPA: ppa:cflmy/marqdo | key: 505943294D04C803 -set -euo pipefail - -SERIES="${1:-noble}" -NO_UPLOAD=0 -for arg in "${@:2}"; do - case "$arg" in - --no-upload|-n) NO_UPLOAD=1 ;; - *) echo "unknown arg: $arg" >&2; exit 2 ;; - esac -done - -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" - -# Never cargo/debuild/dput as root — GPG lives in the human user's ~/.gnupg -if [ "$(id -u)" -eq 0 ]; then - if [ -z "${SUDO_USER:-}" ] || [ "$SUDO_USER" = root ]; then - echo "error: run as a normal user, or: sudo -u \$USER ./scripts/ppa-ship.sh" >&2 - exit 1 - fi - REAL_USER="$SUDO_USER" - REAL_HOME="$(getent passwd "$REAL_USER" | cut -d: -f6)" - echo "==> root detected; apt as root, build/upload as ${REAL_USER}" - run_user() { - local upath="${REAL_HOME}/.cargo/bin:/usr/local/bin:/usr/bin:/bin" - sudo -u "$REAL_USER" -H --preserve-env=MARQDO_PPA_GPG_KEY \ - env HOME="$REAL_HOME" PATH="$upath" "$@" - } - APT=(apt-get) -else - REAL_USER="$(id -un)" - REAL_HOME="$HOME" - run_user() { "$@"; } - APT=(sudo apt-get) -fi - -PPA_TARGET="${MARQDO_PPA:-ppa:cflmy/marqdo}" -PKGS=(build-essential debhelper devscripts dput lintian - dpkg-dev quilt cargo rustc pkg-config libssl-dev ca-certificates - xz-utils) - -need_apt=0 -for bin in debuild dput dpkg-parsechangelog cargo gpg; do - if ! command -v "$bin" >/dev/null 2>&1; then - need_apt=1 - break - fi -done -# dh_auto_* comes from debhelper even if debuild exists from a partial install -if ! dpkg -s debhelper >/dev/null 2>&1; then - need_apt=1 -fi - -if [ "$need_apt" -eq 1 ]; then - echo "==> installing packaging toolchain (sudo)…" - "${APT[@]}" update -qq - DEBIAN_FRONTEND=noninteractive "${APT[@]}" install -y "${PKGS[@]}" -else - echo "==> packaging tools already present" -fi - -echo "==> building source package for series=${SERIES}" -run_user bash "$ROOT/scripts/ppa-build-source.sh" "$SERIES" - -# The native handbook selects the exact current-version artifact. -MARQDO_TOOL="${MARQDO_BIN:-$ROOT/target/debug/marqdo}" -if [ ! -x "$MARQDO_TOOL" ]; then MARQDO_TOOL="$ROOT/target/release/marqdo"; fi -if [ ! -x "$MARQDO_TOOL" ]; then MARQDO_TOOL="$(command -v marqdo || true)"; fi -if [ -z "$MARQDO_TOOL" ] || [ ! -x "$MARQDO_TOOL" ]; then - echo "error: build Marqdo or set MARQDO_BIN before packaging" >&2 - exit 1 -fi -DEB_VER="$(run_user "$MARQDO_TOOL" call "$ROOT/skills/marqdo-release/package.mq.md" debian_version \ - "series=\"$SERIES\"" --require-ok --effects fs.read --fs-root "$ROOT")" -BUILD_AREA="$(cd "$ROOT/.." && pwd)/build-area" -CHANGES="$BUILD_AREA/marqdo_${DEB_VER}_source.changes" -if [ ! -f "$CHANGES" ]; then - echo "error: expected source artifact is missing: $CHANGES" >&2 - exit 1 -fi - -echo "==> artifact: $CHANGES" -if command -v lintian >/dev/null 2>&1; then - echo "==> lintian (non-fatal)" - run_user lintian -i "$CHANGES" || true -fi - -if [ "$NO_UPLOAD" -eq 1 ]; then - echo - echo "Skip upload (--no-upload). When ready:" - echo " dput ${PPA_TARGET} ${CHANGES}" - exit 0 -fi - -echo "==> dput ${PPA_TARGET}" -run_user dput --unchecked "${PPA_TARGET}" "$CHANGES" - -echo -echo "Done. Watch builds:" -echo " https://launchpad.net/~cflmy/+archive/ubuntu/marqdo/+builds" -echo "Enable the Ubuntu series (${SERIES}) in PPA → Change details if Launchpad rejects the upload." diff --git a/scripts/publish-release.py b/scripts/publish-release.py deleted file mode 100755 index f5a7ea9..0000000 --- a/scripts/publish-release.py +++ /dev/null @@ -1,170 +0,0 @@ -# -*- coding: utf-8 -*- -"""Create a GitHub release from Cargo.toml version and upload Windows binaries.""" -from __future__ import annotations - -import json -import re -import subprocess -import urllib.error -import urllib.request -from pathlib import Path - -REPO = "cflmy/marqdo" - - -def crate_version() -> str: - text = Path("Cargo.toml").read_text(encoding="utf-8") - m = re.search(r'(?m)^version\s*=\s*"([^"]+)"', text) - if not m: - raise SystemExit("version not found in Cargo.toml") - return m.group(1) - - -def git_token() -> str: - proc = subprocess.run( - ["git", "credential", "fill"], - input="protocol=https\nhost=github.com\n\n", - text=True, - capture_output=True, - check=True, - ) - for line in proc.stdout.splitlines(): - if line.startswith("password="): - return line[len("password=") :] - raise SystemExit("no github password from git credential fill") - - -def api(method: str, url: str, token: str, data: bytes | None = None, content_type: str | None = None): - req = urllib.request.Request(url, data=data, method=method) - req.add_header("Accept", "application/vnd.github+json") - req.add_header("Authorization", f"Bearer {token}") - req.add_header("X-GitHub-Api-Version", "2022-11-28") - req.add_header("User-Agent", "marqdo-release-script") - if content_type: - req.add_header("Content-Type", content_type) - try: - with urllib.request.urlopen(req) as resp: - body = resp.read() - return resp.status, json.loads(body.decode()) if body else {} - except urllib.error.HTTPError as e: - err = e.read().decode("utf-8", errors="replace") - raise SystemExit(f"HTTP {e.code} {url}: {err}") from e - - -def find_assets(stem: str, ver: str) -> list[Path]: - names = [ - f"{stem}.exe", - f"{stem}.zip", - f"marqdo-{ver}-stdlib.zip", - ] - assets: list[Path] = [] - for name in names: - found = None - for base in (Path("dist"), Path("target/dist")): - p = base / name - if p.exists(): - found = p - break - if not found: - raise SystemExit(f"missing asset: {name} under dist/ or target/dist/") - assets.append(found) - return assets - - -def main() -> None: - ver = crate_version() - tag = f"v{ver}" - stem = f"marqdo-{ver}-x86_64-pc-windows-msvc" - assets = find_assets(stem, ver) - - notes = f"""## Marqdo {tag} - -### Downloads - -| Asset | Contents | -|-------|----------| -| `{stem}.exe` | **Executable only** — does **not** include the standard library | -| `{stem}.zip` | **Recommended**: `marqdo.exe` + `lib/` (keep them together; `lib/` resolves next to the binary) | -| `marqdo-{ver}-stdlib.zip` | Standard library only (`lib/*.mq.md`) — unpack next to an existing exe, or set `MARQDO_LIB` | - -> **Important:** the standalone `.exe` does **not** ship `lib/`. Importing `lib/text.mq.md` etc. needs the bundle zip or the stdlib zip. - -### Highlights -- **Code as docs as knowledge**: `.mq.md` is narrative + program in one tree -- **`marqdo debug`**: dedicated debugger; view stays docs-only -- **View**: function outline + search -- Roadmap: deeper **OKF**-aligned catalog for human–AI knowledge bases - -```text -marqdo --version -marqdo run public/00-welcome.mq.md -marqdo view public -marqdo debug public -``` -""" - - token = git_token() - - existing = None - try: - _, existing = api( - "GET", - f"https://api.github.com/repos/{REPO}/releases/tags/{tag}", - token, - ) - except SystemExit as e: - if "404" not in str(e): - raise - - if existing: - release_id = existing["id"] - upload_url = existing["upload_url"].split("{", 1)[0] - print(f"reuse release id={release_id}") - else: - payload = json.dumps( - { - "tag_name": tag, - "name": tag, - "body": notes, - "draft": False, - "prerelease": False, - } - ).encode("utf-8") - _, created = api( - "POST", - f"https://api.github.com/repos/{REPO}/releases", - token, - data=payload, - content_type="application/json", - ) - release_id = created["id"] - upload_url = created["upload_url"].split("{", 1)[0] - print(f"created release id={release_id}") - - _, rel = api( - "GET", - f"https://api.github.com/repos/{REPO}/releases/{release_id}", - token, - ) - want = {p.name for p in assets} - for asset in rel.get("assets", []): - if asset["name"] in want: - api( - "DELETE", - f"https://api.github.com/repos/{REPO}/releases/assets/{asset['id']}", - token, - ) - print(f"deleted old asset {asset['name']}") - - for path in assets: - data = path.read_bytes() - url = f"{upload_url}?name={path.name}" - ctype = "application/zip" if path.suffix == ".zip" else "application/octet-stream" - _, uploaded = api("POST", url, token, data=data, content_type=ctype) - print(f"uploaded {path.name} -> {uploaded.get('browser_download_url')}") - - print(f"OK https://github.com/{REPO}/releases/tag/{tag}") - - -if __name__ == "__main__": - main() diff --git a/scripts/release-full.ps1 b/scripts/release-full.ps1 deleted file mode 100755 index b333b48..0000000 --- a/scripts/release-full.ps1 +++ /dev/null @@ -1,208 +0,0 @@ -# Build all Marqdo v0.1.2+ release assets and optionally upload to GitHub Releases. -# Usage (repo root): -# powershell -File ./scripts/release-full.ps1 -# powershell -File ./scripts/release-full.ps1 -Tag v0.1.2 -Upload -# powershell -File ./scripts/release-full.ps1 -SkipPublic -param( - [string]$Tag = "", - [switch]$Upload, - [switch]$DeployPages, - [switch]$SkipPublic, - [switch]$SkipVsix -) - -$ErrorActionPreference = "Stop" -$Root = Split-Path $PSScriptRoot -Parent -Set-Location $Root - -function Invoke-Git { - param([Parameter(ValueFromRemainingArguments = $true)][string[]]$GitArgs) - $prev = $ErrorActionPreference - $ErrorActionPreference = "Continue" - & git @GitArgs 2>&1 | Out-Null - $code = $LASTEXITCODE - $ErrorActionPreference = $prev - if ($code -ne 0) { throw "git $($GitArgs -join ' ') failed (exit $code)" } -} - -if (-not $Tag) { - $Tag = (Select-String -Path Cargo.toml -Pattern '^version\s*=\s*"([^"]+)"').Matches.Groups[1].Value - $Tag = "v$Tag" -} -$ver = $Tag.TrimStart("v") -$target = "x86_64-pc-windows-msvc" -$dist = Join-Path $Root "dist" -New-Item -ItemType Directory -Force -Path $dist | Out-Null - -$exeName = "marqdo-$ver-$target.exe" -$zipName = "marqdo-$ver-$target.zip" -$stdlibName = "marqdo-$ver-stdlib.zip" -$sourceName = "marqdo-$ver-source.zip" -$vsixName = "marqdo-$ver.vsix" -$publicName = "marqdo-$ver-public.zip" - -Write-Host "=== Marqdo release $Tag ===" - -Write-Host "[1/6] cargo build --release" -cargo build --release -q - -Write-Host "[2/6] binary + bundle + stdlib zips" -$exePath = Join-Path $dist $exeName -Copy-Item ".\target\release\marqdo.exe" $exePath -Force - -$stage = Join-Path $dist "stage-bundle" -if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } -New-Item -ItemType Directory -Force -Path $stage | Out-Null -Copy-Item ".\target\release\marqdo.exe" (Join-Path $stage "marqdo.exe") -Force -Copy-Item ".\lib" (Join-Path $stage "lib") -Recurse -Force -$zipPath = Join-Path $dist $zipName -if (Test-Path $zipPath) { Remove-Item $zipPath -Force } -Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force - -$stageLib = Join-Path $dist "stage-stdlib" -if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force } -New-Item -ItemType Directory -Force -Path $stageLib | Out-Null -Copy-Item ".\lib" (Join-Path $stageLib "lib") -Recurse -Force -$stdlibPath = Join-Path $dist $stdlibName -if (Test-Path $stdlibPath) { Remove-Item $stdlibPath -Force } -Compress-Archive -Path (Join-Path $stageLib "*") -DestinationPath $stdlibPath -Force - -Write-Host "[3/6] source archive (main @ HEAD, no .git)" -$sourcePath = Join-Path $dist $sourceName -if (Test-Path $sourcePath) { Remove-Item $sourcePath -Force } -git archive --format=zip -o $sourcePath HEAD -if ($LASTEXITCODE -ne 0) { throw "git archive failed" } - -if (-not $SkipVsix) { - Write-Host "[4/6] VSIX (branch vscode-extension)" - Invoke-Git fetch origin vscode-extension - if (Test-Path "vscode-extension") { Remove-Item "vscode-extension" -Recurse -Force } - Invoke-Git checkout origin/vscode-extension -- vscode-extension - Push-Location vscode-extension - npm ci --silent - npm run compile - $vsixPath = Join-Path $dist $vsixName - if (Test-Path $vsixPath) { Remove-Item $vsixPath -Force } - npx --yes @vscode/vsce package --no-dependencies -o $vsixPath - Pop-Location - Remove-Item "vscode-extension" -Recurse -Force -ErrorAction SilentlyContinue -} else { - Write-Host "[4/6] VSIX skipped" -} - -if (-not $SkipPublic) { - Write-Host "[5/6] public static site" - & .\target\release\marqdo.exe view output public -o public - if (-not (Test-Path "public\index.html")) { throw "public/index.html missing after view output" } - $publicPath = Join-Path $dist $publicName - if (Test-Path $publicPath) { Remove-Item $publicPath -Force } - Compress-Archive -Path "public\*" -DestinationPath $publicPath -Force -} else { - Write-Host "[5/6] public skipped" -} - -Write-Host "[6/6] dist summary" -Get-ChildItem $dist -File | ForEach-Object { Write-Host (" {0,12:N0} bytes {1}" -f $_.Length, $_.Name) } - -if ($DeployPages) { - Write-Host "Deploying gh-pages..." - if (-not (Test-Path "public\index.html")) { - & .\target\release\marqdo.exe view output public -o public - } - $pagesDir = Join-Path $dist "gh-pages-staging" - if (Test-Path $pagesDir) { Remove-Item $pagesDir -Recurse -Force } - New-Item -ItemType Directory -Force -Path $pagesDir | Out-Null - Copy-Item -Recurse public\* $pagesDir -Force - # peaceiris-style: only site artifacts on gh-pages - git worktree add $pagesDir gh-pages 2>$null - if ($LASTEXITCODE -ne 0) { - git branch -D gh-pages 2>$null - git checkout --orphan gh-pages-temp - git reset --hard - git checkout main - git branch -D gh-pages-temp 2>$null - git checkout -b gh-pages - Copy-Item -Recurse (Join-Path $Root "public\*") . -Force - git add -A - git commit -m "Deploy public site for $Tag" - git push -f origin gh-pages - git checkout main - } else { - Write-Host "gh-pages worktree exists; copy public/ manually or use CI pages workflow" - } -} - -if ($Upload) { - Write-Host "Uploading to GitHub Release $Tag ..." - $assets = @($exeName, $zipName, $stdlibName, $sourceName) - if (-not $SkipVsix) { $assets += $vsixName } - if (-not $SkipPublic) { $assets += $publicName } - - $raw = ("protocol=https`nhost=github.com`n`n" | git credential fill 2>$null) -join "`n" - $user = ([regex]::Match($raw, '(?m)^username=(.+)$')).Groups[1].Value - $token = ([regex]::Match($raw, '(?m)^password=(.+)$')).Groups[1].Value - if (-not $token) { throw "No GitHub token from git credential; run gh auth login" } - $headers = @{ - Authorization = "Bearer $token" - Accept = "application/vnd.github+json" - "User-Agent" = "marqdo-release-full" - } - - $notes = @" -## Marqdo $Tag - -### Downloads - -| Asset | Contents | -|-------|----------| -| ``$exeName`` | Windows CLI (**embedded** official ``lib/``) | -| ``$zipName`` | ``marqdo.exe`` + ``lib/`` (optional disk override) | -| ``$stdlibName`` | Standard library ``lib/*.mq.md`` only | -| ``$sourceName`` | Source tree snapshot (``git archive`` of ``main``) | -| ``$vsixName`` | VS Code / Cursor extension (from branch ``vscode-extension``) | -| ``$publicName`` | Static user docs site (also at [gh-pages](https://cflmy.github.io/marqdo/)) | - -### Highlights -- Embedded stdlib, **writeback** + **subtask**, v0.2 syntax, ``marqdo version --check`` -- Extension source: branch ``vscode-extension`` — [vscode-extension-commit.md](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md) - -See [CHANGELOG.md](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md). -"@ - - try { - $rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/tags/$Tag" -Headers $headers - $releaseId = $rel.id - $uploadUrl = $rel.upload_url -replace "\{.*", "" - Write-Host "Updating release $($rel.html_url)" - $body = @{ tag_name = $Tag; name = "Marqdo $Tag"; body = $notes; draft = $false; prerelease = $false } | ConvertTo-Json -Depth 5 - Invoke-RestMethod -Method Patch -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$releaseId" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($body)) | Out-Null - } catch { - Write-Host "Creating release $Tag ..." - $body = @{ tag_name = $Tag; name = "Marqdo $Tag"; body = $notes; draft = $false; prerelease = $false } | ConvertTo-Json -Depth 5 - $rel = Invoke-RestMethod -Method Post -Uri "https://api.github.com/repos/cflmy/marqdo/releases" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($body)) - $releaseId = $rel.id - $uploadUrl = $rel.upload_url -replace "\{.*", "" - } - - $rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$releaseId" -Headers $headers - foreach ($file in $assets) { - $path = Join-Path $dist $file - if (-not (Test-Path $path)) { Write-Warning "skip missing $file"; continue } - $existing = $rel.assets | Where-Object { $_.name -eq $file } - if ($existing) { - Invoke-RestMethod -Method Delete -Uri "https://api.github.com/repos/cflmy/marqdo/releases/assets/$($existing.id)" -Headers $headers | Out-Null - } - $uri = "$uploadUrl`?name=$([uri]::EscapeDataString($file))" - $bytes = [System.IO.File]::ReadAllBytes($path) - $ctype = switch -Regex ($file) { - '\.zip$' { "application/zip" } - '\.vsix$' { "application/vsix" } - default { "application/octet-stream" } - } - $asset = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType $ctype -Body $bytes - Write-Host " uploaded $($asset.browser_download_url)" - } - Write-Host "OK https://github.com/cflmy/marqdo/releases/tag/$Tag" -} - -Write-Host "Done." diff --git a/scripts/release-windows.ps1 b/scripts/release-windows.ps1 deleted file mode 100755 index df30a4a..0000000 --- a/scripts/release-windows.ps1 +++ /dev/null @@ -1,137 +0,0 @@ -# Build Windows release assets (exe, bundle zip, stdlib zip, VSIX) and upload -# to an existing GitHub Release tag. -# Usage (from repo root): -# powershell -File ./scripts/release-windows.ps1 -# powershell -File ./scripts/release-windows.ps1 -Tag v0.1.2 -param( - [string]$Tag = "" -) - -$ErrorActionPreference = "Stop" -Set-Location (Split-Path $PSScriptRoot -Parent) - -if (-not $Tag) { - $Tag = (Select-String -Path Cargo.toml -Pattern '^version\s*=\s*"([^"]+)"').Matches.Groups[1].Value - $Tag = "v$Tag" -} -$ver = $Tag.TrimStart("v") -$target = "x86_64-pc-windows-msvc" -$dist = Join-Path (Get-Location) "dist" -$stage = Join-Path $dist "stage-bundle" -$stageLib = Join-Path $dist "stage-stdlib" -New-Item -ItemType Directory -Force -Path $dist | Out-Null - -Write-Host "Building release binary for $Tag ..." -cargo build --release -q - -$exeName = "marqdo-$ver-$target.exe" -$zipName = "marqdo-$ver-$target.zip" -$stdlibName = "marqdo-$ver-stdlib.zip" -$vsixName = "marqdo-$ver.vsix" -$exePath = Join-Path $dist $exeName -$zipPath = Join-Path $dist $zipName -$stdlibPath = Join-Path $dist $stdlibName -$vsixPath = Join-Path $dist $vsixName - -Copy-Item ".\target\release\marqdo.exe" $exePath -Force - -Write-Host "Building VS Code extension $vsixName (from branch vscode-extension) ..." -git fetch origin vscode-extension 2>$null -git checkout origin/vscode-extension -- vscode-extension -Push-Location vscode-extension -npm ci --silent -npm run compile -npx @vscode/vsce package --no-dependencies -o $vsixPath -Pop-Location - -# Bundle: marqdo.exe + lib/ (optional disk override) -if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } -New-Item -ItemType Directory -Force -Path $stage | Out-Null -Copy-Item ".\target\release\marqdo.exe" (Join-Path $stage "marqdo.exe") -Force -Copy-Item ".\lib" (Join-Path $stage "lib") -Recurse -Force -if (Test-Path $zipPath) { Remove-Item $zipPath -Force } -Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force - -# Stdlib-only zip (override / mirror) -if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force } -New-Item -ItemType Directory -Force -Path $stageLib | Out-Null -Copy-Item ".\lib" (Join-Path $stageLib "lib") -Recurse -Force -if (Test-Path $stdlibPath) { Remove-Item $stdlibPath -Force } -Compress-Archive -Path (Join-Path $stageLib "*") -DestinationPath $stdlibPath -Force - -Write-Host "Packaged:" -Write-Host " $exePath (CLI with embedded stdlib)" -Write-Host " $zipPath (marqdo.exe + lib/)" -Write-Host " $stdlibPath (lib/ only)" -Write-Host " $vsixPath (VS Code extension)" - -$raw = ("protocol=https`nhost=github.com`n`n" | git credential fill 2>$null) -join "`n" -$user = ([regex]::Match($raw, '(?m)^username=(.+)$')).Groups[1].Value -$token = ([regex]::Match($raw, '(?m)^password=(.+)$')).Groups[1].Value -if (-not $token) { throw "No GitHub credentials from git credential fill; run gh auth login or configure git credentials." } -$pair = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${user}:${token}")) -$headers = @{ - Authorization = "Basic $pair" - Accept = "application/vnd.github+json" - "User-Agent" = "marqdo-release-windows" -} - -$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/tags/$Tag" -Headers $headers -Write-Host "Uploading to release $($rel.html_url)" - -$notes = @" -## Marqdo $Tag - -### Downloads - -| Asset | Contents | -|-------|----------| -| ``$exeName`` | CLI with **embedded** official stdlib (``lib/*.mq.md``) | -| ``$zipName`` | ``marqdo.exe`` + ``lib/`` (optional disk override) | -| ``$stdlibName`` | Standard library only — unpack to override embedded lib | -| ``$vsixName`` | **VS Code / Cursor extension** — built from branch ``vscode-extension`` only (see doc/design/vscode-extension-commit.md) | - -### Highlights -- **Embedded stdlib**: standalone ``.exe`` imports ``lib/…`` without a separate zip -- **writeback** + **subtask** (file / function / foreign concurrency) -- **v0.2 syntax**: ``+`param` ``, ``1.`` branches, backtick identifiers, quoted strings -- ``marqdo version --check`` compares with GitHub latest release - -### Quick start - -``````text -marqdo --version -marqdo version --check -marqdo run public/00-welcome.mq.md -marqdo view public -`````` - -See [CHANGELOG.md](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md). -"@ - -$body = @{ - tag_name = $Tag - name = "Marqdo $Tag" - body = $notes - draft = $false - prerelease = $false -} | ConvertTo-Json -Depth 5 -Invoke-RestMethod -Method Patch -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$($rel.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($body)) | Out-Null - -$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/cflmy/marqdo/releases/$($rel.id)" -Headers $headers - -foreach ($file in @($exeName, $zipName, $stdlibName, $vsixName)) { - $path = Join-Path $dist $file - $existing = $rel.assets | Where-Object { $_.name -eq $file } - if ($existing) { - Invoke-RestMethod -Method Delete -Uri $existing.url -Headers $headers | Out-Null - Write-Host " deleted old $file" - } - $uri = "https://uploads.github.com/repos/cflmy/marqdo/releases/$($rel.id)/assets?name=$([uri]::EscapeDataString($file))" - $bytes = [System.IO.File]::ReadAllBytes($path) - $ctype = if ($file.EndsWith(".zip")) { "application/zip" } elseif ($file.EndsWith(".vsix")) { "application/vsix" } else { "application/octet-stream" } - $asset = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType $ctype -Body $bytes - Write-Host " $($asset.browser_download_url)" -} - -Write-Host "OK" diff --git a/scripts/render-markdown-execution-promo.py b/scripts/render-markdown-execution-promo.py deleted file mode 100644 index 7ebff88..0000000 --- a/scripts/render-markdown-execution-promo.py +++ /dev/null @@ -1,251 +0,0 @@ -#!/usr/bin/env python3 -"""Rebuild the Marqdo Markdown → View → execution promotional film. - -Source imagery: - - assets/marketing/user-procurement-view.png: original user-provided View capture - - assets/marketing/source-markdown-view-concept.png: original generated concept art -Other images are generated from the repository's actual procurement source. -The purchasing demo is simulated, not an ERP transaction. -""" -from pathlib import Path -import math, subprocess, wave, tempfile -import numpy as np -from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps -from markdown_it import MarkdownIt -from selenium import webdriver -from selenium.webdriver.chrome.options import Options - -ROOT=Path(__file__).resolve().parents[1] -A=ROOT/"assets"/"marketing" -OUT=A/"marqdo-2.7.1-markdown-to-execution.mp4" -POSTER=A/"marqdo-2.7.1-markdown-to-execution-cover.jpg" -SRT=A/"marqdo-2.7.1-markdown-to-execution.srt" -W,H=1600,900 -D=[4.8,6.8,6.4,7.0,7.5,9.5,8.8,5.2] -IVORY=(249,247,242);INK=(37,35,34);GOLD=(191,146,81);PEARL=(242,232,214);DIM=(122,114,105);NIGHT=(18,23,32) -REG="/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc" -BOLD="/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" -SERIF="/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc" -SERIFB="/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc" -def f(size,mode="regular"): - return ImageFont.truetype({"regular":REG,"bold":BOLD,"serif":SERIF,"serifbold":SERIFB}[mode],size) -def txt(d,xy,s,size=26,color=INK,style="regular"): - d.text(xy,str(s),font=f(size,style),fill=color) -def card(d,box,fill=IVORY,stroke=(220,210,195),r=24): - d.rounded_rectangle(box,radius=r,fill=fill,outline=stroke,width=2) -def base(dark=False): - im=Image.new("RGB",(W,H),NIGHT if dark else IVORY) - d=ImageDraw.Draw(im) - if dark: - for j in range(8): - d.arc((880+j*32,-200+j*26,1760+j*28,1030+j*25),158,268,fill=(68+j*7,60+j*6,51+j*4),width=2) - else: - for j in range(7): - d.arc((-430+j*14,-500+j*14,500+j*25,520+j*25),35,150,fill=(238,224+j*2,207+j*2),width=2) - return im -def rounded_image(im,src,box,focus=(.5,.5)): - x1,y1,x2,y2=box - crop=ImageOps.fit(src,(x2-x1,y2-y1),method=Image.Resampling.LANCZOS,centering=focus) - mask=Image.new("L",crop.size,0) - ImageDraw.Draw(mask).rounded_rectangle((0,0,crop.width-1,crop.height-1),radius=18,fill=255) - im.paste(crop,(x1,y1),mask) - ImageDraw.Draw(im).rounded_rectangle(box,radius=18,outline=(200,177,145),width=2) -def footer(d,text,dark=False): - txt(d,(80,855),text,18,(148,158,171) if dark else DIM) -def make_intro(): - im=base(True);d=ImageDraw.Draw(im) - txt(d,(94,113),"MARQDO / v2.7.1",21,(233,197,146)) - txt(d,(90,221),"Your SKILL",83,IVORY,"serifbold") - txt(d,(90,327),"is now a",83,IVORY,"serifbold") - txt(d,(90,435),"TOOL.",91,(244,201,148),"serifbold") - d.line((100,562,1040,562),fill=GOLD,width=3) - txt(d,(102,613),"不只是让 AI 阅读文档。",35,(232,230,224),"serif") - txt(d,(102,681),"让同一份 Markdown 承载可控执行流。",35,(232,230,224),"serif") - footer(d,"WRITE ONCE · RENDER AS MARKDOWN · INSPECT AS RUNTIME",True) - return im - -source=(ROOT/"examples/procurement/index.mq.md").read_text(encoding="utf8") -assert "## 查询采购商价格" in source -section=source.split("## 查询采购商价格",1)[1].split("\n## ",1)[0] -excerpt="## 查询采购商价格\n"+section -lines=excerpt.splitlines() -content=[] -for line in lines: - if len(content)>=18:break - content.append(line) -assert len(content)>10 -md=MarkdownIt("commonmark").enable("table") -html=md.render("\n".join(content)) -document=f""" -{html}""" -opts=Options() -for arg in ["--headless=new","--no-sandbox","--disable-dev-shm-usage","--disable-gpu","--window-size=1450,1600"]: - opts.add_argument(arg) -browser=webdriver.Chrome(options=opts) -try: - browser.set_window_size(1450,1600) - browser.get("data:text/html;charset=utf-8,"+__import__("urllib.parse",fromlist=["quote"]).quote(document)) - htmlscreen=A/"marqdo-procurement-standard-markdown.png" - browser.save_screenshot(str(htmlscreen)) - assert htmlscreen.stat().st_size>20000 -finally: - browser.quit() -RENDER=Image.open(htmlscreen).convert("RGB") -USER=Image.open(A/"user-procurement-view.png").convert("RGB") -CONCEPT=Image.open(A/"source-markdown-view-concept.png").convert("RGB") - -def make_source(): - im=base(True);d=ImageDraw.Draw(im) - txt(d,(78,69),"01 / SOURCE",21,(226,192,141)) - txt(d,(77,123),"源码态:它本来就是 Markdown",54,IVORY,"serifbold") - txt(d,(80,209),"普通段落保持可读,标题、参数表和返回契约仍是 Markdown。",28,(187,198,213)) - card(d,(75,265,1520,797),(28,38,51),(78,89,105),23) - card(d,(76,265,1519,332),(43,53,70),(43,53,70),23) - for j,col in enumerate([(190,97,91),(224,173,97),(109,173,130)]): - d.ellipse((105+j*33,293,122+j*33,310),fill=col) - txt(d,(256,282),"index.mq.md · 查询采购商价格",24,(227,227,222)) - for i,line in enumerate(content[:16]): - value=line[:77].replace("\t"," ") - clr=(232,193,133) if value.startswith("#") or "返回" in value else ((164,214,201) if "正常" in value else (221,226,230)) - txt(d,(106,358+i*25),f"{i+1:02d} {value}",20,clr) - footer(d,"ACTUAL .mq.md EXCERPT · source: examples/procurement/index.mq.md",True) - return im - -def make_render(): - im=base();d=ImageDraw.Draw(im) - txt(d,(81,69),"02 / STANDARD MARKDOWN",21,(170,126,67)) - txt(d,(77,128),"渲染态:它首先是一篇文档",56,INK,"serifbold") - txt(d,(80,205),"同一段源码,无需定制语法高亮,也可以按 Markdown 阅读。",29,DIM) - card(d,(80,265,1516,839),(255,254,251)) - rounded_image(im,RENDER,(120,290,1469,814),(.5,.19)) - txt(ImageDraw.Draw(im),(1145,280),"STANDARD MARKDOWN",18,(167,115,55)) - footer(ImageDraw.Draw(im),"A MARKDOWN-IT RENDER · FROM THE SAME SOURCE") - return im - -def make_triple(): - im=base();d=ImageDraw.Draw(im) - txt(d,(75,60),"03 / THREE VIEWS, ONE FILE",21,(170,126,67)) - txt(d,(76,130),"同一份 .mq.md,三种视图",55,INK,"serifbold") - txt(d,(81,211),"源码能编写,Markdown 能阅读,View 能看到函数、值和执行依赖。",27,DIM) - screens=[("SOURCE / 源码",make_source()),("MARKDOWN / 渲染",RENDER),("VIEW / 执行",USER)] - xlist=[75,578,1081] - for i,(label,src) in enumerate(screens): - x=xlist[i];tw=442 - card(d,(x,280,x+tw,777),(255,254,250)) - txt(d,(x+21,301),label,23,(130,95,56)) - rounded_image(im,src,(x+15,349,x+tw-15,749),(.50,.38)) - d=ImageDraw.Draw(im) - for x in [523,1026]: - d.line((x,530,x+49,530),fill=GOLD,width=4) - d.polygon([(x+49,530),(x+32,519),(x+32,541)],fill=GOLD) - footer(d,"NOT THREE FILES · ONE DOCUMENT + EXECUTION SEMANTICS") - return im - -def make_concept(): - im=base();d=ImageDraw.Draw(im) - txt(d,(72,58),"04 / DESIGN LANGUAGE",21,(170,126,67)) - rounded_image(im,CONCEPT,(55,112,1545,850),(.5,.5)) - txt(ImageDraw.Draw(im),(92,855),"CONCEPT ART · Source → Rendered Markdown → Marqdo View",18,DIM) - return im - -def make_view(): - im=base();d=ImageDraw.Draw(im) - txt(d,(78,62),"05 / REAL MARQDO VIEW",21,(170,126,67)) - txt(d,(78,127),"在文档上,看见它的执行流",58,INK,"serifbold") - txt(d,(80,216),"自然语言依然是主体,执行信息沿优雅的曲线引出。",28,DIM) - card(d,(70,278,1530,841),(255,254,250)) - rounded_image(im,USER,(88,295,1513,817),(.50,.50)) - footer(ImageDraw.Draw(im),"ACTUAL VIEW SCREENSHOT · PROVIDED BY THE PROJECT AUTHOR") - return im - -def make_execution(): - im=base(True);d=ImageDraw.Draw(im) - txt(d,(80,66),"06 / EXECUTABLE FUNCTIONS",21,(230,192,137)) - txt(d,(80,132),"在哪里执行?就在同一份文档的函数里。",53,IVORY,"serifbold") - txt(d,(84,216),"说明是可读的,规则却会通过函数调用实际检查。",28,(183,198,211)) - card(d,(76,275,1519,367),(30,42,57),(78,88,100)) - txt(d,(99,303),"marqdo call examples/procurement/index.mq.md 查询余额 已花费=120",25,(233,218,188)) - card(d,(76,418,760,775),(25,55,48),(70,124,96)) - card(d,(790,418,1520,775),(58,34,43),(154,85,96)) - txt(d,(110,455),"PASS / LOCAL SIMULATION",24,(150,227,185)) - txt(d,(822,455),"DENIED / BUDGET CHECK",24,(249,164,170)) - txt(d,(112,533),"¥120 + ¥288",43,IVORY) - txt(d,(823,533),"¥360 + ¥288",43,IVORY) - txt(d,(113,606),"¥408",86,(146,229,185),"bold") - txt(d,(823,606),"¥648",86,(250,162,166),"bold") - txt(d,(115,720),"ok: true · 本地模拟,未发送",23,(217,237,224)) - txt(d,(824,720),"ok: false · 超预算拒绝",23,(248,216,217)) - footer(d,"OUTCOMES VERIFIED WITH MARQDO 2.7.1 CLI · NO REAL ORDER WAS SENT",True) - return im - -def make_outro(): - im=base(True);d=ImageDraw.Draw(im) - txt(d,(97,157),"Marqdo",90,IVORY,"serifbold") - txt(d,(98,313),"Write it. Read it. Run it.",61,(238,195,136),"serifbold") - d.line((99,431,1480,431),fill=GOLD,width=3) - txt(d,(101,500),"A document-native runtime for executable AI skills.",31,(217,221,225)) - txt(d,(101,649),"github.com/cflmy/marqdo",43,IVORY) - footer(d,"Marqdo v2.7.1 · Apache 2.0 · simulated procurement demo",True) - return im - -slides=[make_intro(),make_source(),make_render(),make_triple(),make_concept(),make_view(),make_execution(),make_outro()] -A.mkdir(parents=True,exist_ok=True) -slides[0].save(POSTER,quality=95) -with tempfile.TemporaryDirectory() as tmp: - tmp=Path(tmp);clips=[] - for i,(still,dur) in enumerate(zip(slides,D)): - imagefile=tmp/f"slide_{i:02d}.png" - still.save(imagefile) - clip=tmp/f"clip_{i:02d}.mp4" - filt=f"scale=1280:720,zoompan=z='min(zoom+0.00016,1.02)':x='iw/2-iw/zoom/2':y='ih/2-ih/zoom/2':d=1:s=1280x720:fps=24,fade=t=in:st=0:d=0.4,fade=t=out:st={dur-.5}:d=0.5,format=yuv420p" - cmd=["ffmpeg","-y","-hide_banner","-loglevel","error","-loop","1","-framerate","24","-t",str(dur),"-i",str(imagefile),"-vf",filt,"-an","-c:v","libx264","-preset","veryfast","-crf","19","-pix_fmt","yuv420p",str(clip)] - subprocess.run(cmd,check=True,timeout=200) - clips.append(clip) - print("RENDERED_SLIDE",i,flush=True) - playlist=tmp/"concat.txt" - playlist.write_text("\n".join(f"file '{c}'" for c in clips)+"\n") - silent=tmp/"silent.mp4" - subprocess.run(["ffmpeg","-y","-hide_banner","-loglevel","error","-f","concat","-safe","0","-i",str(playlist),"-c","copy",str(silent)],check=True,timeout=90) - sr=24000 - total=sum(D);ts=np.arange(int(total*sr))/sr - sound=np.zeros(len(ts)) - at=0. - for i,dur in enumerate(D): - mask=(ts>=at)&(ts {stamp(times[i+1])}\n{msg}" for i,msg in enumerate(messages))+"\n",encoding="utf-8") -print("VIDEO",OUT,OUT.stat().st_size) -print("COVER",POSTER,POSTER.stat().st_size) -print("SRT",SRT,SRT.stat().st_size) -assert OUT.stat().st_size>800000 and sum(D)==56 diff --git a/scripts/run-public-pages.sh b/scripts/run-public-pages.sh deleted file mode 100755 index 8fc4a8d..0000000 --- a/scripts/run-public-pages.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -# Run every public/*.mq.md that defines `# main`, then export the site. -set -euo pipefail -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" - -# CLI + native plugins used by public demos (ext/quantum, ext/linalg). -cargo build --release -p marqdo -p marqdo_plugin_quantum -p marqdo_plugin_linalg - -BIN=./target/release/marqdo -while IFS= read -r -d '' f; do - if grep -q '^# main' "$f"; then - echo "+ marqdo run $f" - "$BIN" run "$f" - else - echo "- skip (no # main): $f" - fi -done < <(find public -name '*.mq.md' -print0) - -"$BIN" view output public -o public diff --git a/scripts/upload-ext-r2.py b/scripts/upload-ext-r2.py deleted file mode 100755 index f0c26bb..0000000 --- a/scripts/upload-ext-r2.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python3 -"""Upload Marqdo extension packs to Cloudflare R2 (CDN: https://ext.marqdo.com). - -No third-party deps (stdlib only) — AWS Signature V4 PutObject. - -Credentials: ~/.marqdo/r2.env (chmod 600; never commit). Required: - R2_ENDPOINT, R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY -Optional: R2_PUBLIC_BASE, R2_REGION (default auto) - -Usage: - python3 scripts/upload-ext-r2.py --version 1.0.2 dist/marqdo-1.0.2-ext.zip \\ - dist/marqdo-1.0.2-native-x86_64-unknown-linux-gnu.zip - python3 scripts/upload-ext-r2.py --version 1.0.2 --from-dir dist/ -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import hashlib -import hmac -import os -import sys -import tempfile -import urllib.error -import urllib.request -from pathlib import Path -from urllib.parse import quote, urlparse - - -def load_env_file(path: Path) -> None: - if not path.is_file(): - return - for line in path.read_text(encoding="utf-8").splitlines(): - line = line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - k, _, v = line.partition("=") - os.environ.setdefault(k.strip(), v.strip().strip("'").strip('"')) - - -def sha256_hex(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def hmac_sha256(key: bytes, msg: str) -> bytes: - return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() - - -def signing_key(secret: str, datestamp: str, region: str, service: str) -> bytes: - k_date = hmac_sha256(("AWS4" + secret).encode("utf-8"), datestamp) - k_region = hmac.new(k_date, region.encode("utf-8"), hashlib.sha256).digest() - k_service = hmac.new(k_region, service.encode("utf-8"), hashlib.sha256).digest() - return hmac.new(k_service, b"aws4_request", hashlib.sha256).digest() - - -def put_object( - *, - endpoint: str, - bucket: str, - key: str, - body: bytes, - content_type: str, - access_key: str, - secret_key: str, - region: str, -) -> None: - endpoint = endpoint.rstrip("/") - host = urlparse(endpoint).netloc - # Path-style: https://endpoint/bucket/key - canonical_uri = "/" + bucket + "/" + quote(key, safe="/~") - amz_date = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") - datestamp = amz_date[:8] - payload_hash = sha256_hex(body) - canonical_headers = ( - f"content-type:{content_type}\n" - f"host:{host}\n" - f"x-amz-content-sha256:{payload_hash}\n" - f"x-amz-date:{amz_date}\n" - ) - signed_headers = "content-type;host;x-amz-content-sha256;x-amz-date" - canonical_request = "\n".join( - [ - "PUT", - canonical_uri, - "", - canonical_headers, - signed_headers, - payload_hash, - ] - ) - credential_scope = f"{datestamp}/{region}/s3/aws4_request" - string_to_sign = "\n".join( - [ - "AWS4-HMAC-SHA256", - amz_date, - credential_scope, - sha256_hex(canonical_request.encode("utf-8")), - ] - ) - sig = hmac.new( - signing_key(secret_key, datestamp, region, "s3"), - string_to_sign.encode("utf-8"), - hashlib.sha256, - ).hexdigest() - auth = ( - f"AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, " - f"SignedHeaders={signed_headers}, Signature={sig}" - ) - url = endpoint + canonical_uri - req = urllib.request.Request(url, data=body, method="PUT") - req.add_header("Content-Type", content_type) - req.add_header("x-amz-content-sha256", payload_hash) - req.add_header("x-amz-date", amz_date) - req.add_header("Authorization", auth) - try: - with urllib.request.urlopen(req, timeout=300) as resp: - if resp.status not in (200, 201): - raise RuntimeError(f"PUT {key} HTTP {resp.status}") - except urllib.error.HTTPError as e: - detail = e.read().decode("utf-8", errors="replace") - raise RuntimeError(f"PUT {key} HTTP {e.code}: {detail}") from e - - -def content_type_for(path: Path) -> str: - if path.name == "VERSION" or path.suffix.lower() == ".txt": - return "text/plain; charset=utf-8" - if path.suffix.lower() == ".json": - return "application/json" - return "application/zip" - - -def upload_file( - path: Path, - key: str, - *, - endpoint: str, - bucket: str, - access_key: str, - secret_key: str, - region: str, - public_base: str, -) -> None: - body = path.read_bytes() - print(f"upload {path.name} → s3://{bucket}/{key} ({len(body)} bytes)") - put_object( - endpoint=endpoint, - bucket=bucket, - key=key, - body=body, - content_type=content_type_for(path), - access_key=access_key, - secret_key=secret_key, - region=region, - ) - print(f" public: {public_base.rstrip('/')}/{key}") - - -def main() -> int: - load_env_file(Path.home() / ".marqdo" / "r2.env") - load_env_file(Path(".env")) - load_env_file(Path(".env.r2")) - - ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--version", required=True, help="Extension pack SemVer (no v prefix)") - ap.add_argument("--from-dir", type=Path, help="Upload all marqdo-{VER}-*.zip from dir") - ap.add_argument("files", nargs="*", type=Path, help="Files to upload") - ap.add_argument("--no-latest", action="store_true", help="Do not update latest/ pointers") - args = ap.parse_args() - - ver = args.version.lstrip("v") - for key in ("R2_ENDPOINT", "R2_BUCKET", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY"): - if not os.environ.get(key): - print( - f"missing {key}; write ~/.marqdo/r2.env (see .env.r2.example)", - file=sys.stderr, - ) - return 1 - - endpoint = os.environ["R2_ENDPOINT"] - bucket = os.environ["R2_BUCKET"] - access_key = os.environ["R2_ACCESS_KEY_ID"] - secret_key = os.environ["R2_SECRET_ACCESS_KEY"] - region = os.environ.get("R2_REGION", "auto") - public_base = os.environ.get("R2_PUBLIC_BASE", "https://ext.marqdo.com") - - files: list[Path] = [p for p in args.files if p.is_file()] - if args.from_dir: - files.extend(sorted(args.from_dir.glob(f"marqdo-{ver}-*.zip"))) - if not files: - print("no files to upload", file=sys.stderr) - return 1 - - kw = dict( - endpoint=endpoint, - bucket=bucket, - access_key=access_key, - secret_key=secret_key, - region=region, - public_base=public_base, - ) - for path in files: - upload_file(path, f"v{ver}/{path.name}", **kw) - if not args.no_latest: - upload_file(path, f"latest/{path.name}", **kw) - - if not args.no_latest: - with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False) as tf: - tf.write(ver + "\n") - tmp = Path(tf.name) - try: - upload_file(tmp, "latest/VERSION", **kw) - upload_file(tmp, f"v{ver}/VERSION", **kw) - finally: - tmp.unlink(missing_ok=True) - - print("done.") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/skills/marqdo-dev/SKILL.md b/skills/marqdo-dev/SKILL.md deleted file mode 100755 index 0769554..0000000 --- a/skills/marqdo-dev/SKILL.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: marqdo-dev -description: Write, refactor and verify Marqdo programs, standard libraries and extensions through the executable development handbook. Use native Marqdo file tools and marqdo call; extend capability gaps through plugins or explicit external tools. ---- - -Read [the executable development entry](../marqdo-dev/index.mq.md), then [the programming guide](../../doc/library-development.mq.md). The same guide governs programs, libraries and executable SKILLs. For installed skills, resolve these paths against the Marqdo source checkout. - -Use `**statement**` to execute and `*return*` to return; write `[intent](actual code)` inside executable positions, and `access(coll, key)` to read collections. The guide provides real examples. Native file tasks live in [files.mq.md](../marqdo-dev/files.mq.md): read, bounded excerpt, write, patch, search, inventory, audit and apply. Use excerpt for long generated lines; its source locations remain one-based and clipped text is inspection evidence, not replacement source. Do not generate Python or shell programs for ordinary file operations. - -Prepare the native engineering plugin with the development entry before using its analysis or process tasks. The repository development binary is `target/debug/marqdo`; installed older binaries may need a bootstrap Cargo build through `lib/sys.mq.md exec`. All subsequent task execution uses `marqdo call`. Keep decisions and sequencing in readable mq.md; use a new extension or a documented foreign tool only for a real capability gap. - -The guide is authoritative for narrative over 50%, immediate parameter/return tables, inline statements and returns, GFM data, index.mq.md organization, recursive Markdown web components, failure evidence and verification. Read each task's contract and grant its actual effects. External processes retain their OS authority. Do not rewrite intentional test fixtures or restore removed compose_* APIs. - -Use the development entry's audit task to discover and review maintained repository sources. Its failed Result retains every finding; write_report=True saves the same evidence under .marqdo/audit. It does not execute inspected source or treat known placeholder warnings as completed logic. - -Build current WASM with the entry's build_browser task. If the system target is incompatible, call [toolchain.mq.md](../marqdo-dev/toolchain.mq.md) rust_wasm_linux and pass its returned compiler path. Prepare the workspace browser driver with prepare_browser, then run test_browser for actual SPA/history and two-tab collaboration behavior. These tasks retain native file IO and use existing compiler/browser tools only at their documented boundaries. diff --git a/skills/marqdo-dev/browser.mq.md b/skills/marqdo-dev/browser.mq.md deleted file mode 100755 index ab53ed6..0000000 --- a/skills/marqdo-dev/browser.mq.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -markup: occlusion -title: Real browser preparation and verification through Marqdo -import: - fs: lib/fs.mq.md - sys: lib/sys.mq.md - re: lib/re.mq.md - table: lib/table.mq.md - result: lib/result.mq.md - engineering: ext/engineering/index.mq.md ---- - -Build current browser assets through the development entry's build_browser task. This module prepares the external browser driver and runs the actual UI cases, including the native browser-effects demonstration and both complete literary sites. Files and orchestration remain native Marqdo; browser automation is a documented external capability, and no Python program performs the development workflow. - -## prepare - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | "1.65.0" | Pinned Playwright package version verified by this repository | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result of workspace-local dependency and Chromium preparation | - -Use `version`="1.65.0" to prepare the external browser-test driver under .marqdo/browser-tests. Node, npm and Playwright are explicit test-tool boundaries; the application itself remains Marqdo, and each test starts the real server through marqdo call. Native filesystem operations create the selected workspace directories. The package and browser caches stay there, with no global npm installation or Python runner. Grant plugin, process.exec and fs.write. - -Preparation is separate from verification because installing a browser does not test a page. Each command must succeed before the next one starts. The pinned version and child-only PLAYWRIGHT_BROWSERS_PATH make the driver reproducible. If a required system library is absent, preserve the actual error rather than reporting browser validation as complete. This task changes no application source or repository package manifest. - -1. not [A pinned stable package version](re.is_match(text=`version`, pattern="^[0-9]+[.][0-9]+[.][0-9]+$")) - Return *[Require an explicit stable package version](result.error(code="browser.version", message="use a pinned numeric Playwright version"))*. -We **[Create the task-owned workspace tool directory](fs.make_dirs(path=".marqdo/browser-tests"))**. -We **package = "playwright@" + version**. - -`install_args` = - -| argument | -|---| -| npm | -| install | -| "--prefix" | -| .marqdo/browser-tests | -| "--cache" | -| .marqdo/browser-tests/npm-cache | -| "--no-save" | -| "--package-lock=false" | -| `package` | - -We **installed = [Prepare the pinned external browser driver](engineering.checked(argv=`install_args`, timeout_ms=180000, max_output=65536))**. -1. not access(`installed`, "ok") - Return *installed*. -We **cache = sys.cwd() + "/.marqdo/browser-tests/browsers"** and **environment = [Keep browser downloads inside this workspace](table.put(in=None, at="PLAYWRIGHT_BROWSERS_PATH", value=`cache`))**. - -`browser_args` = - -| argument | -|---| -| node | -| .marqdo/browser-tests/node_modules/playwright/cli.js | -| install | -| chromium | - -Return *[Prepare the actual headless Chromium runtime](engineering.checked(argv=`browser_args`, env=`environment`, timeout_ms=300000, max_output=65536))*. - -## verify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| out | text | ".marqdo/browser-handbook-assets" | Current build_browser output directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result from real browser effects, SPA, collaboration, bilingual network and bilingual complete-site browser cases | - -Use `out`=".marqdo/browser-handbook-assets" after build_browser has produced the current WASM and prepare has installed the pinned browser driver. This task copies only the two named generated runtime assets with native Marqdo file operations; client sources remain in their project directories. Both source artifacts must exist before any example is staged. Grant plugin, process.exec and fs.write. - -The external Node test harness supplies browser automation and process supervision only. It starts each application's callable serve function on a selected loopback port, then uses the actual WASM, DOM events, history and WebSocket transport. The browser-effects case verifies duplicate-row identity, literal labels, clipboard/download payloads, completed draft storage, timer cancellation, real history, ordered HTTP success/failure records and local WebSocket echo. SPA checks cover native list records, editing quoted text, new ids and back/forward behavior. Two tabs verify presence, remote snapshots, the first local edit after a remote update and an empty document. The English and Chinese network-site cases uses an owned database created and removed through native Marqdo file calls, verifying real echo, form-validation retry, current article data and authenticated administration. The complete English and Chinese sites also verify original theme declarations, current card/detail separation, real session navigation, the gated custom desk and logout. Their font requests are explicitly aborted so local acceptance proves declared families and fallback rendering, not external font delivery. Narrow viewport checks expose layout overflow. A saved native report retains actual failures; a source contract or constructed effect map is not substituted for a browser result. - -We **wasm = out + "/marqdo_wasm.wasm"** and **bridge = out + "/marqdo-bridge.js"**. -1. not [The current WASM exists](fs.exists(path=`wasm`)) or not [The canonical bridge exists](fs.exists(path=`bridge`)) - Return *[Require a real current browser build](result.error(code="browser.assets", message="call build_browser before browser verification"))*. - -`sites` = - -| path | -|---| -| examples/browser-app/static | -| examples/web-spa-app/static | -| examples/web-collab-doc/static | -| examples/web-net-site/public/generated | -| examples/web-net-site-zh/public/generated | - -- [Stage only the two generated browser resources](for sites as directory) - We **[Keep the static destination inside the granted root](fs.make_dirs(path=`directory`))**. - We **wasm_dest = directory + "/marqdo_wasm.wasm"** and **bridge_dest = directory + "/marqdo-bridge.js"**. - We **[Copy the actual current WASM natively](fs.copy_file(src=`wasm`, dest=`wasm_dest`))** and **[Copy the canonical bridge natively](fs.copy_file(src=`bridge`, dest=`bridge_dest`))**. -We **cache = sys.cwd() + "/.marqdo/browser-tests/browsers"** and **environment = [Use only the prepared workspace browser cache](table.put(in=None, at="PLAYWRIGHT_BROWSERS_PATH", value=`cache`))**. - -`argv` = - -| argument | -|---| -| node | -| "--test" | -| tests/browser_handbook.mjs | - -We **observed = [Run actual browser interaction tests](engineering.checked(argv=`argv`, env=`environment`, timeout_ms=150000, max_output=65536))**. -We **[Retain the actual test report with native IO](fs.write_json(path=".marqdo/browser-tests/result.json", value=`observed`))**. -Return *observed*. diff --git a/skills/marqdo-dev/data.mq.md b/skills/marqdo-dev/data.mq.md deleted file mode 100755 index 77fb145..0000000 --- a/skills/marqdo-dev/data.mq.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -markup: occlusion -title: Native verification for Markdown data refactors -import: - document: lib/document.mq.md - table: lib/table.mq.md - result: lib/result.mq.md ---- - -Extract static literal tables into readable Markdown data leaves while callable sources explain their use. Compare actual old function values with the new native parser before applying source changes. These pure tasks do not execute the supplied data as a program or mutate files. - -## literal_tables - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| specifications | list | required | Records with a unique key and literal Markdown table text | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing ordered key/value records for all selected literal tables | - -Use `specifications` to inspect a planned Markdown data split before writing it. Each key identifies the original file and function, while text carries that table's exact source. The standard document parser preserves native literal types and shapes and refuses dynamic expressions. No file, import, process or code fence is executed. Duplicate identities are a failed Result rather than an overwritten observation, and parser diagnostics retain their actual failure. This task is pure; it supplies data evidence, not permission to replace source. - -We **rows = [Start the ordered literal evidence](table.empty_list())** and **keys = [Track exact source identities](table.empty_list())**. -- [Read every explicitly selected literal table](for specifications as specification) - We **key = [Read its source identity](access(`specification`, "key"))** and **source = [Read its exact table source](access(`specification`, "text"))**. - 1. [This identity was already observed](table.contains(list=`keys`, item=`key`)) - Return *[Keep duplicate source identity explicit](result.error(code="data.duplicate", message=`key`, operation="literal_tables"))*. - We **value = [Use the native literal table parser](document.table(text=`source`))** and **keys = [Retain this identity](table.append(list=`keys`, item=`key`))**. - - `row` = - - | key | value | - |---|---| - | `key` | `value` | - - We **rows = [Keep the complete native value](table.append(list=`rows`, item=`row`))**. -Return *[Expose ordered immutable data evidence](result.ok(value=`rows`))*. - -## compare - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| expected | list | required | Baseline key/value records obtained from actual original functions | -| actual | list | required | Key/value records obtained from the proposed literal data | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with exact count and the source keys whose native values differ | - -Use `expected` and `actual` for a data-only refactor review. Identities and cardinality are checked before any source mutation, then values are compared through native equality. A boolean must remain a boolean, and row/column/list structure must remain the same. The failed Result keeps mismatched identities in value, allowing --require-ok to stop a migration without losing evidence. This task neither writes files nor declares a later behavioral change equivalent; deliberate content edits need their own review. - -We **mismatched = [Start actual data differences](table.empty_list())** and **expected_keys = [Read baseline identities](table.pluck(list=`expected`, key="key"))** and **actual_keys = [Read proposed identities](table.pluck(list=`actual`, key="key"))**. -1. len(`expected`) != len(`actual`) or len(table.unique(list=`expected_keys`)) != len(`expected`) or len(table.unique(list=`actual_keys`)) != len(`actual`) - Return *[Reject missing or repeated data identities](result.error(code="data.identities", message="baseline and actual must have equal counts and unique keys", operation="compare"))*. -- [Compare each source's actual native value](for expected as row) - We **key = [Read its identity](access(`row`, "key"))** and **found = [Find the corresponding proposed value](table.find(list=`actual`, key="key", value=`key`))** and **same = False**. - 1. `found` != None - We **same = [Compare original and proposed types and shapes](access(row, "value") == access(found, "value"))**. - 1. not `same` - We **mismatched = [Retain the differing source identity](table.append(list=`mismatched`, item=`key`))**. -We **count = [Keep the actual baseline count](len(expected))**. - -`evidence` = - -| count | mismatched | -|---|---| -| `count` | `mismatched` | - -1. len(`mismatched`) == 0 - Return *[Retain the unchanged data evidence](result.ok(value=`evidence`))*. -We **failed = [Keep the refactor incomplete](result.error(code="data.value_drift", message="inspect the mismatched source keys", operation="compare"))**. -Return *[Preserve differences on failure](table.put(in=`failed`, at="value", value=`evidence`))*. diff --git a/skills/marqdo-dev/files.mq.md b/skills/marqdo-dev/files.mq.md deleted file mode 100755 index 52fccf3..0000000 --- a/skills/marqdo-dev/files.mq.md +++ /dev/null @@ -1,476 +0,0 @@ ---- -markup: occlusion -title: Native repository file operations -import: - fs: lib/fs.mq.md - re: lib/re.mq.md - hash: lib/hash.mq.md - table: lib/table.mq.md - result: lib/result.mq.md - engineering: ext/engineering/index.mq.md ---- - -Repository development reads and writes through Marqdo's own filesystem tools. -These functions are the same operations used by the handbooks, not shell text -that another agent must regenerate. Paths stay under the granted filesystem -root; pass --fs-root . at the checkout root. read/search need fs.read, while -write/patch need fs.write. Writes imply reads but grant no process or network IO. - -A write is an explicit edit requested by the caller. Read the current file and -review the intended change before writing; these functions do not decide which -files belong to a task. Patch is useful for a unique bounded change; write is -useful for an explicitly reviewed complete artifact. Neither creates parent -directories implicitly, and neither promises a transaction across multiple files. - -## read - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | UTF-8 source path under --fs-root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| source | text | Exact UTF-8 file contents without interpretation | - -Use `path` to read a source document before editing it. The returned text is -data: embedded bold, returns, imports and shell-looking content are not run. -A missing path, invalid UTF-8 or root escape produces the native filesystem -diagnostic. For binary data use lib/fs.read_bytes or read_chunk instead. - -After selecting the source we return *[Read the actual UTF-8 artifact](fs.read_text(path=`path`))*. - -## write - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Destination under --fs-root; parent must exist | -| source | text | required | Reviewed complete UTF-8 content, including intentional newlines | - -| 返回 | 类型 | 说明 | -|---|---|---| -| sha256 | text | SHA256 of the bytes actually written | - -Use `path` and `source` for an explicit authored artifact. JSON argument input -carries quotes, Unicode, literal dollar signs and newlines without generating -a program in another language. Existing files are replaced only because the -caller selected write. A single-file atomic replacement does not turn a batch -of writes into a transaction or erase unrelated work on failure. - -We **written = [Atomically replace this selected UTF-8 artifact](fs.atomic_write(path=`path`, text=`source`))**. -After writing, return *[Hash the actual resulting file](fs.file_hash(path=`path`))*. - -## patch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Existing UTF-8 file under --fs-root | -| find | text | required | Exact nonempty fragment that occurs once | -| replace | text | required | Reviewed replacement fragment | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Native patch result; missing/ambiguous matches are diagnostics | - -Use `path`, `find` and `replace` when changing one known part of a file. -The exact-match requirement catches drift between reading and editing, though -it is not a concurrent kernel compare-and-swap. A whole-file replacement belongs -to write. This helper never falls back to a model-generated search-and-replace -program when the old fragment no longer matches. - -Once the bounded change is reviewed, return *[Apply one exact native text patch](fs.text_patch(path=`path`, find=`find`, replace=`replace`))*. - -## search - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | "." | Selected source directory under --fs-root | -| pattern | text | required | Unicode regex applied to each source line | -| glob | text | "**/*.mq.md" | File pattern; choose **/*.rs for runtime code | - -| 返回 | 类型 | 说明 | -|---|---|---| -| matches | list | Records with path, one-based line and original text | - -Use `path`=".", `pattern` and `glob`="**/*.mq.md" to search actual sources. -The native walker does not traverse symlinks and prunes generated/cache trees. -Reading remains UTF-8 and bounded by the filesystem implementation. Each result -retains its source path and line so an agent can read that artifact rather than -guessing from a detached snippet. This is a source query, not a code execution. - -`excluded` = - -| pattern | -|---| -| .git/** | -| **/target/** | -| **/node_modules/** | -| **/.marqdo/** | -| **/vendor/** | -| **/__pycache__/** | - -We **paths = [Find source files through the native filesystem](fs.find(path=`path`, pattern=`glob`, exclude=`excluded`))** and -**matches = [Start the source-location result list](table.empty_list())**. -- [Read each selected text source](for paths as file) - We **actual_path = path + "/" + file** and - **lines = [Read its UTF-8 lines](fs.read_lines(path=`actual_path`))** and **number = 0**. - - [Test the requested expression against each line](for lines as source) - We **number = number + 1** to retain one-based source coordinates. - 1. [This line matches the requested source query](re.is_match(text=`source`, pattern=`pattern`)) - - `hit` = - - | path | line | text | - |---|---|---| - | `actual_path` | `number` | `source` | - - We **matches = [Retain this source location](table.append(list=`matches`, item=`hit`))**. - -When the selected sources are exhausted we return *matches*. -## read_many - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| paths | list | required | Explicit UTF-8 source paths selected for one review batch | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Sources and hashes for the exact requested files | - -Use `paths` when reviewing a small related batch. Native filesystem reads -preserve the full UTF-8 text; hashes identify the exact returned source used to prepare a patch. The digest is -computed from that text, so a later filesystem change cannot pair new bytes with -an older source in the same record. -Reading does not run imports, main or embedded code. Choose a bounded batch so -the returned source remains useful to the agent rather than dumping a whole -repository into one response. Any missing or escaping path is a native error. -The same path/hash pair can be passed to apply for a preflight drift check. - -We **records = [Start the source review batch](table.empty_list())**. -- [Read only the selected artifacts](for paths as path) - We **source = [Read the exact UTF-8 source](fs.read_text(path=`path`))** and - **sha256 = [Identify the bytes used for this review](hash.sha256(text=`source`))**. - - - `record` = - - | path | source | sha256 | - |---|---|---| - | `path` | `source` | `sha256` | - - We **records = [Retain the source and its observed identity](table.append(list=`records`, item=`record`))**. -Return *records* after reading the selected batch. - -## inventory - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| paths | list | required | Explicit source paths to inspect without executing | -| include_body | bool | False | Include compiler AST debug evidence for a migration | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Source, hash and actual compiler analysis for each selected artifact | - -Use `paths` and `include_body`=False for an authored source review. -Marqdo reads each file through lib/fs, then sends its text to the compiler-backed -extension analyzer. The analyzer parses the same language, supplies real -parameters/defaults/contracts and measures each function's narrative ratio. -Imports are not executed or followed by this text inspection; full program checks -still use marqdo check. It needs fs.read and the engineering plugin, and makes no -network request or edit. A parse failure stays attached to that file as a Result -instead of making the rest of the inventory disappear. - -We **records = [Start the executable source inventory](table.empty_list())**. -- [Inspect the selected source with its actual compiler](for paths as path) - We **source = [Read the original source through the native filesystem](fs.read_text(path=`path`))** and - **sha256 = [Retain its observed byte identity](hash.sha256(text=`source`))** and - **analysis = [Parse contracts and statements without running them](engineering.analyze(source=`source`, include_body=`include_body`))**. - - `record` = - - | path | source | sha256 | analysis | - |---|---|---|---| - | `path` | `source` | `sha256` | `analysis` | - - We **records = [Keep the actual per-file evidence](table.append(list=`records`, item=`record`))**. -Return *records* after the requested source inventory. - -## apply - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| updates | list | required | Reviewed records containing path/source and optional expected_sha256 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing paths and SHA256 values actually written | - -Use `updates` to apply a reviewed batch through native file IO. Each record -selects its path and complete source; expected_sha256 optionally ties that edit -to the previously read version. All supplied digests and duplicate destinations -are checked before the first write, preventing an ordinary stale review from -partially changing the batch. Path access checks also happen before writing. - -This is still not a multi-file transaction or a kernel CAS. Each file replacement -is atomic on its own; a later disk failure can leave earlier reviewed files -written. Parent directories must already exist. A deliberate new file can omit -expected_sha256, while updating an observed file should retain its hash. -The result lists actual file hashes rather than claiming compliance with a style -rule. Call the static and behavioral checks after applying the batch. - -We **seen = [Start the destination preflight list](table.empty_list())**. -- [Preflight every reviewed destination before writing](for updates as update) - We **path = [Read the selected destination](access(update, "path"))** and - **exists = [Apply the native root policy before any write](fs.exists(path=`path`))** and - **expected = [Read its optional reviewed source identity](table.get(map=`update`, key="expected_sha256"))**. - 1. [This destination occurs twice](table.contains(list=`seen`, item=`path`)) - Return *[Reject duplicate writes in one batch](result.error(code="authoring.duplicate", message=`path`, operation="files.apply"))*. - 1. `expected` != None - 1. not `exists` - Return *[Keep a missing reviewed artifact visible](result.error(code="authoring.missing", message=`path`, operation="files.apply"))*. - 1. fs.file_hash(path=`path`) != `expected` - Return *[Refuse a stale reviewed update](result.error(code="authoring.changed", message=`path`, operation="files.apply"))*. - We **seen = [Retain this checked destination](table.append(list=`seen`, item=`path`))**. -We **written = [Start the actual write evidence list](table.empty_list())**. -- [Write each explicit reviewed artifact through Marqdo](for updates as update) - We **path = [Read its checked destination](access(update, "path"))** and - **saved = [Atomically replace the selected UTF-8 content](fs.atomic_write(path=`path`, text=access(update, "source")))** and - **sha256 = [Identify the bytes that were actually written](fs.file_hash(path=`path`))**. - - `evidence` = - - | path | sha256 | - |---|---| - | `path` | `sha256` | - - We **written = [Retain this actual file result](table.append(list=`written`, item=`evidence`))**. -Return *[The completed native edit batch](result.ok(value=`written`))*. - -## analyze_updates - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| updates | list | required | Proposed path/source records; no filesystem mutation | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Compiler metadata for each proposed artifact | - -Use `updates` before applying an authored batch. Each proposal is analyzed -as text by the real compiler without replacing the current file or executing -the proposal. The path is an identity label for the report; no untrusted path -is opened here. Parameter order/defaults and statement projections allow a -reviewer to distinguish documentation changes from behavioral changes. - -The projection deliberately omits source locations and occlusion labels from -executable statements; it is review evidence, not a proof of all runtime behavior. -Keep real golden calls and backend tests for observable behavior. Parse failures -remain per-file Results so another proposal's valid syntax cannot mask them. - -We **reports = [Start the proposed-source review](table.empty_list())**. -- [Analyze one proposed artifact without writing it](for updates as update) - We **path = [Retain its intended destination label](access(update, "path"))** and - **source = [Read the proposed UTF-8 value](access(update, "source"))** and - **analysis = [Use the actual parser and contract checker](engineering.analyze(source=`source`))**. - - `report` = - - | path | analysis | - |---|---| - | `path` | `analysis` | - - We **reports = [Retain the actual compile evidence](table.append(list=`reports`, item=`report`))**. -Return *reports* after analyzing all proposals. - - -## _missing_contracts - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| functions | list | required | Compiler-projected function tree from engineering.analyze | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Executable functions whose return contract is missing | - -Use `functions` from the compiler projection; never infer functions by scanning -hash-prefixed source lines. Content-only headings have no executable statements -and are omitted, so a prose section does not acquire a fictional return table. -Nested functions are inspected recursively and retain compiler source lines. - -This is a pure structural check. The compiler separately checks declared -parameter names and types. A return table's presence is not proof that prose is -accurate or that an effectful function behaves correctly. Keep runtime tests for -those properties. The source tree is ordinary data and no imports are executed. - -We **missing = [Start the actual missing-contract findings](table.empty_list())**. -- [Inspect real callable units and their nested definitions](for functions as function) - We **contract = [Read its parsed public contract](access(function, "contract"))** and - **active = [Distinguish executable units from content-only headings](len(access(function, "semantic")) > 0)**. - We **missing_return = True** until an actual return contract is observed. - 1. `contract` != None - We **missing_return = [Inspect the existing contract without indexing None](access(contract, "returns") == None)**. - 1. `active` and `missing_return` - We **name = [Keep the exact callable name](access(function, "name"))** and **line = [Keep its source location](access(function, "line"))**. - - `finding` = - - | name | line | issue | - |---|---|---| - | `name` | `line` | "missing return contract" | - - We **missing = [Retain the source-based finding](table.append(list=`missing`, item=`finding`))**. - We **nested = [Inspect child definitions by the same rule](_missing_contracts(functions=access(function, "children")))** and - **missing = [Combine findings without executing a function](table.concat(a=`missing`, b=`nested`))**. -Return *missing* for the caller's report. - -## _active_lines - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| functions | list | required | Compiler-projected function tree | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Source heading lines belonging to executable units | - -Use `functions` from the compiler projection. An executable statement or a -declared parameter makes a unit part of the callable audit; a plain content -heading is not a zero-length program. This distinction also covers field-only -object schemas, which use field contracts rather than fictional return tables. - -The walk includes nested definitions and retains their actual heading lines. -It is a pure projection, not a source-text pattern or an import traversal. -An explicit return of None and an empty-payload assignment are still statements, -so intentionally unfinished callable code stays visible to the authoring checks. -The compiler's narrative measurements are used unchanged for every selected unit. - -We **lines = [Start the actual executable heading locations](table.empty_list())**. -- [Inspect real declarations and their nested definitions](for functions as function) - 1. len(access(`function`, "semantic")) > 0 or len(access(`function`, "params")) > 0 - We **lines = [Retain this executable source unit](table.append(list=`lines`, item=access(function, "line")))**. - We **nested = [Inspect nested source units by the same rule](_active_lines(functions=access(function, "children")))** and - **lines = [Keep the combined executable locations](table.concat(a=`lines`, b=`nested`))**. -Return *lines* for matching the unchanged narrative measurements. - -## audit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| paths | list | required | Explicit maintained source paths; exclude intentional invalid fixtures | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with compact per-file parser, narrative and contract findings | - -Use `paths` for a selected maintained source batch. The same compiler that -runs Marqdo parses each source, checks declared contracts and measures narrative -per function. This task reads through the native filesystem and gives the plugin -only source text. It neither executes imports nor writes files. Requires -fs.read and plugin; it performs no network request. - -A ratio at or below one half is a finding, including a data-heavy callable. -Do not solve findings by adding repeated filler or inventing return values for -pure content. Reorganize large code/data into useful modules and explain actual -inputs, decisions and limits. This structural audit is an editing aid; run check -for dependency validation and real cases for behavioral and visual results. - -Pure content headings are excluded from callable ratios. Compiler warnings stay -in diagnostics for review; errors, parser failures and authoring gaps make the -batch incomplete. This allows a documented empty-payload demonstration to retain -its warning without replacing the example with fake business logic. - -The result retains all selected file findings even if one fails parsing. A -complete batch returns ok=true. An incomplete batch returns ok=false with the -same evidence in value, so --require-ok can stop automation without discarding -the review report. Missing files or root violations remain native diagnostics. -Newline-bearing paths have no special meaning here; they are ordinary input data. - -We **reports = [Start the compact source review](table.empty_list())** and **complete = True**. -- [Audit every explicitly selected source without running it](for paths as path) - We **source = [Read the source using native Marqdo IO](fs.read_text(path=`path`))** and - **analysis = [Use the actual compiler projection](engineering.analyze(source=`source`))** and - **parse_ok = [Retain whether parsing succeeded](access(analysis, "ok"))** and - **diagnostics = [Start this file diagnostic list](table.empty_list())** and - **ratio_gaps = [Start this file narrative findings](table.empty_list())** and - **missing_contracts = [Start this file contract findings](table.empty_list())**. - 1. `parse_ok` - We **data = [Read the successful source projection](access(analysis, "value"))** and - **diagnostics = [Retain genuine contract diagnostics](access(data, "diagnostics"))** and - **missing_contracts = [Inspect executable units recursively](_missing_contracts(functions=access(data, "functions")))**. - We **ratios = [Read the measured function units](access(data, "ratios"))** and **active_lines = [Identify actual executable units](_active_lines(functions=access(data, "functions")))**. - - [Review the narrative measure of each unit](for ratios as ratio) - We **line = [Read the measured source heading location](access(ratio, "line"))**. - 1. [This is an executable source unit](table.contains(list=`active_lines`, item=`line`)) and access(`ratio`, "ratio") <= 0.5 - We **ratio_gaps = [Retain this function and its actual measured ratio](table.append(list=`ratio_gaps`, item=`ratio`))**. - 1. not `parse_ok` - We **diagnostics = [Retain the real parser failure](table.append(list=`diagnostics`, item=access(analysis, "error")))**. - We **errors = 0** before examining the diagnostic severities. - - [Keep errors separate from expected illustrative warnings](for diagnostics as diagnostic) - We **severity = [Read a diagnostic severity when provided](table.get(map=`diagnostic`, key="severity"))**. - 1. `severity` == "error" - We **errors = errors + 1**. - We **ok = [Require all structural checks for this file](parse_ok and errors == 0 and len(ratio_gaps) == 0 and len(missing_contracts) == 0)**. - 1. not `ok` - We **complete = False** to retain the incomplete batch state. - - `report` = - - | path | ok | diagnostics | ratio_gaps | missing_contracts | - |---|---|---|---|---| - | `path` | `ok` | `diagnostics` | `ratio_gaps` | `missing_contracts` | - - We **reports = [Retain this file evidence without its full source dump](table.append(list=`reports`, item=`report`))**. -We **count = [Retain the actual number of selected sources](len(`paths`))**. - -`evidence` = - -| complete | count | reports | -|---|---|---| -| `complete` | `count` | `reports` | - -1. `complete` - Return *[The complete structural evidence](result.ok(value=`evidence`))*. -We **failed = [Retain the incomplete authoring result](result.error(code="authoring.incomplete", message="inspect the per-file findings in value", operation="files.audit"))**. -Return *[Keep the report available on failure](table.put(in=`failed`, at="value", value=`evidence`))*. - - -## excerpt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | UTF-8 artifact under --fs-root | -| start | number | 1 | First one-based line to inspect | -| count | number | 40 | Number of lines, from 1 through 200 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | A record with total_lines and selected {line,text} records; each line is clipped to 2000 characters | - -Use `path`, `start`=1 and `count`=40 when a generated HTML line or a large source file would overflow the agent's output window. Line numbers refer to the original file, so the excerpt can guide a precise later read or patch. This is a bounded inspection view: clipping does not alter the file or turn a truncated excerpt into suitable replacement source. Start and count must be positive integral numbers; selection past the end returns no lines. The native reader still validates UTF-8 and the granted filesystem root. - -We **lines = [Read UTF-8 lines through the native filesystem](fs.read_lines(path=`path`))**. -1. `start` < 1 or `count` < 1 or `count` > 200 - Return *[Explain the supported inspection window](result.error(code="files.excerpt_window", message="start >= 1; count must be 1..200"))*. -We **selected = [Select only the requested line range](table.slice(list=`lines`, start=(`start` - 1), end=(`start` - 1 + `count`)))** and **records = [Start the source-location list](table.empty_list())**. -We **number = [Keep the original first line number](start)**. -- [Inspect each selected line](for selected as line) - We **visible = [Limit one generated line to 2000 characters](re.replace(text=`line`, pattern="(?s)\\A(.{0,2000}).*\\z", with="$1"))**. - - `record` = - - | line | text | - |---|---| - | `number` | `visible` | - - We **records = [Retain the original location and readable text](table.append(list=`records`, item=`record`))**. - We **number = [Advance the original line number](number + 1)**. -We **total = [Count the actual source lines](len(lines))**. - -`window` = - -| total_lines | lines | -|---|---| -| `total` | `records` | - -After selecting this window, return *window*. diff --git a/skills/marqdo-dev/index.mq.md b/skills/marqdo-dev/index.mq.md deleted file mode 100755 index b840d66..0000000 --- a/skills/marqdo-dev/index.mq.md +++ /dev/null @@ -1,269 +0,0 @@ ---- -markup: occlusion -title: 以 Marqdo 本身开发和验证 Marqdo -import: - files: ./files.mq.md - browser_tools: ./browser.mq.md - fs: lib/fs.mq.md - repository: ./repository.mq.md - table: lib/table.mq.md - text: lib/text.mq.md - sys: lib/sys.mq.md - result: lib/result.mq.md - engineering: ext/engineering/index.mq.md ---- - -本目录是开发智能体的可执行手册。先阅读 [编程规范](../../doc/library-development.mq.md),再按具体任务调用本目录的函数。单文件标准库本身就是手册;只有多文件库或工程才需要 index.mq.md 组织入口。叙述应解释任务、数据、失败和限制,不能靠重复句子凑比例。 - -日常读写通过 files.mq.md 的 read、excerpt、write、patch、search、inventory 和 apply 完成。批量写入前可携带 expected_sha256,防止覆盖已经变化的源码。大段文本使用 CLI 的 --args-json 文件或标准输入传送;它保留换行、引号、中文和以美元符号开头的字面数据。不要为了搬运源码再生成 Python 或 shell 程序。 - -原生库能完成的计算和文件操作直接使用 lib。缺少可复用能力时新增拓展库;需要现有操作系统工具时使用 engineering.run 的参数数组。编排、条件、重试和结果判断留在 mq.md 中。process.exec 与 plugin 是真实的外部能力授权,fs-root 不能限制外部进程自己的权限。 - -调用示例:marqdo call skills/marqdo-dev/index.mq.md prepare_engineering --effects process.exec --fs-root . --json。读取文件可调用 files.mq.md read 并传入 path;修订现有文件优先使用 patch 或带哈希的 apply。每个真实函数标题下都应先给出参数和返回值表,然后是能够独立指导调用者的叙述。 - -## prepare_engineering - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:构建工程插件,失败时保留 Cargo 输出 | - -第一次使用工程拓展前执行此任务。这里通过已有 sys.exec 引导 Cargo 构建本仓库的原生插件,之后开发和发布流程都可以使用同一份工程拓展。构建需要本机 Rust 工具链和已经可用的依赖缓存;不会安装 Python,也不修改版本或发布远端资源。 - -调用需要 process.exec。子进程退出不为零时返回失败,调用者应查看真实 stderr 并修复编译问题;成功只表示本机插件已构建,不意味着其他平台包已验证。依赖尚未缓存时应按仓库工具链配置获取依赖,再运行同一任务。 - -`args` = - -| argument | -|---| -| "build" | -| "-p" | -| "marqdo" | -| "-p" | -| "marqdo_plugin_engineering" | -| "--offline" | - -We **built = [构建已维护的工程边界插件](sys.exec(cmd="cargo", args=`args`, capture=True))**。 -1. access(`built`, "code") != 0 - 返回*[保留构建错误](result.error(code="dev.plugin_build", message=str(`built`), operation="prepare_engineering"))*。 -构建完成后返回*[真实 Cargo 证据](result.ok(value=`built`))*。 - -## check - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | 需要完整检查依赖的真实文件路径 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:编译检查和逐函数叙述比例检查的进程证据 | - -使用 `path` 指定本次修改的入口或单文件库。从仓库根目录调用,并授权 plugin。检查器加载真实依赖,验证契约、参数与调用,同时要求函数的叙述比例超过一半。故意损坏的测试夹具和明确标记禁止修改的人工测试不应当被这项作者任务批量改写。 - -检查通过不能证明页面视觉效果、网络服务或发布凭据正确。根据变更运行实际用例:纯函数比较返回值,文件操作使用临时目录,外部发布操作使用隔离服务夹具。失败时先修复实际问题,保留诊断位置,不通过删除业务能力或补空话来消除告警。 - -`argv` = - -| argument | -|---| -| "target/debug/marqdo" | -| "check" | -| `path` | -| "--narrative-ratio" | - -We **checked = [检查真实文件及其可读性](engineering.run(argv=`argv`))**。 -检查结束后返回*[按实际退出状态保留通过或失败证据](engineering.check_exit(outcome=`checked`))*。 - -## audit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| write_report | bool | False | 保存同一份真实报告到忽略目录 .marqdo/audit | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:实际发现的维护源码与逐文件问题清单 | - -使用 `write_report`=False,在仓库根目录授权 plugin 和 fs.read,即可发现维护中的源码并逐个审查。文件枚举、读取和报告写入都由固有能力完成;分析使用真实编译器,不会运行被审查程序或其导入。需要保留证据时传 True 并增加 fs.write。 - -测试夹具、人工保护样例和历史兼容文件保留既有语义。占位演示的 warning 留在报告中供阅读,不伪造实现以消除提示。失败 Result 仍携带完整清单,因此可结合 --require-ok 阻止后续自动化;比例与契约通过后还应执行实际用例,不能把结构审查当成运行成功。 - -审查完成后返回*[实际仓库源码的完整观察结果](repository.audit(write_report=`write_report`))*。 - - -## test - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| targets | list | required | 明确选择的 Rust 集成测试目标名称 | -| filter | any | None | 可选测试名称过滤文本;不是 Cargo 命令选项 | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:真实 Cargo 退出状态、标准输出与错误输出 | - -使用 `targets` 和可选的 `filter`=None,在仓库根目录授权 plugin。目标清单转成逐个 --test 参数,Cargo 在离线模式下执行;这里不会安装依赖、调用 Python 或生成 shell 程序。需要先完成工具链与插件引导,测试使用的本地服务或其他依赖仍按各目标的实际要求准备。 - -传入的是测试目标名称和可选名称过滤器,不能用空目标清单或把命令选项伪装成过滤文本。构建错误、断言失败、超时与启动失败都返回失败结果;失败仍携带真实执行证据,便于定位哪个用例没有通过。成功只说明所选测试通过,不覆盖未运行的目标,更不能替代发布服务的实际状态验证。名称过滤只缩小用例集合;检查输出中的实际运行数量,避免过滤器没有命中却被当作完成验收。 - -这个入口把重复的测试命令收进源码手册。修改相关模块后运行对应目标,已通过后只有新改动、失败或未解决的疑问才扩大或重复检查。外部进程保留操作系统权限,--fs-root 不是 Cargo 子进程的沙箱。 - -1. len(`targets`) == 0 - Return *[要求明确的验收范围](result.error(code="dev.test_targets", message="select at least one integration test target", operation="test"))*. -1. `filter` != None - 1. [过滤器不能冒充 Cargo 选项](text.starts_with(text=`filter`, prefix="-")) - Return *[拒绝选项形式的过滤文本](result.error(code="dev.test_filter", message="filter is a test name, not an option", operation="test"))*. - -`argv` = - -| argument | -|---| -| "cargo" | -| "test" | -| "--offline" | - -- [将每个目标作为独立参数交给测试工具](for targets as target) - 1. [测试目标不能冒充命令选项](text.starts_with(text=`target`, prefix="-")) - Return *[保留错误目标的诊断](result.error(code="dev.test_targets", message=`target`, operation="test"))*. - We **argv = [增加明确的集成测试选择标记](table.append(list=`argv`, item="--test"))** and **argv = [增加原样传入的目标名称](table.append(list=`argv`, item=`target`))**. -1. `filter` != None - We **argv = [追加可选的用例名称过滤器](table.append(list=`argv`, item=`filter`))**. -We **checked = [执行实际离线构建与验收](engineering.run(argv=`argv`, timeout_ms=300000, max_output=2097152))**. -验收结束后返回*[按真实退出状态判断结果并保留输出](engineering.check_exit(outcome=`checked`))*。 - -## prove -+ `path` -+ `all` -+ `max_files` -+ `require_lean` -+ `json` - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | "." | 单个 `.mq.md` 或目录(目录需要 all=True) | -| all | bool | False | 目录模式:递归收集 .mq.md 逐文件出证,整体取最差状态 | -| max_files | text | "200" | 目录收集上限(--max-files 的值,文本形式) | -| require_lean | bool | False | CI 严格模式:未判定状态退 2 | -| json | bool | False | 单个 JSON 对象输出(智能体可读契约) | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:真实 `marqdo prove` 退出状态、标准输出与错误输出 | - -证明知识文件的定理表:先离线符号执行(毫秒级 checked,不是 proved),有 Lean 工具链时由 Lean 复核升级 proved;假定理给出路径见证反例;离线与 Lean 分歧触发 proof.divergence 错误并退 1,永不落绿。这个任务调用真实 CLI——不带 Lean 时状态如实停留在 unverified/checked(咨询性退 0),require_lean=True 才把未判定当作阻塞。 - -目录模式逐文件出证书,整体状态按 error > unproved > rejected > unverified > checked > proved 取最差;证书缓存在 .marqdo/prove/,重复运行命中缓存。通过只说明所选文件判定完成,不能替代 test 任务的运行时验收;两者结合才是完整验收。 - -1. len(text.trim(`path`)) == 0 - Return *[要求明确的证明范围](result.error(code="dev.prove_path", message="path is required", operation="prove"))*. - -`argv` = - -| argument | -|---| -| "prove" | -| "path" | - -1. `all` == True - We **argv = [切换目录模式](table.append(list=`argv`, item="--all"))** and **argv = [追加收集上限标记](table.append(list=`argv`, item="--max-files"))** and **argv = [追加原样传入的上限文本](table.append(list=`argv`, item=`max_files`))**. -1. not `all` - We **argv = [追加原样传入的证明路径](table.append(list=`argv`, item=`path`))**. -1. `require_lean` == True - We **argv = [追加严格模式](table.append(list=`argv`, item="--require-lean"))**. -1. `json` == True - We **argv = [追加机器可读输出](table.append(list=`argv`, item="--json"))**. -We **checked = [执行真实证明管线](engineering.run(argv=`argv`, timeout_ms=600000, max_output=4194304))**. -验收结束后返回*[按真实退出状态判断结果并保留输出](engineering.check_exit(outcome=`checked`))*。 - -## build_browser - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| out | text | ".marqdo/browser-handbook-assets" | Workspace output directory for current WASM and canonical bridge | -| compiler | any | None | Optional absolute rustc path from toolchain.rust_wasm_linux | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with native artifact hashes and the actual bounded build report path | - -Use `out`=".marqdo/browser-handbook-assets" and `compiler`=None from the checkout root. This task calls Marqdo's own wasm build operation through the explicit engineering process boundary, then hashes its real outputs with native filesystem tools. If the system compiler lacks a compatible WASM target, first call [the workspace toolchain task](toolchain.mq.md) and pass its returned compiler path. That override applies only to this child process, with no global environment or system installation change. - -Grant plugin, process.exec and fs.write. Native directory validation runs before the external build and keeps selected output under the granted root. Compiler logs are bounded and saved natively to .marqdo/build/browser.json; the CLI returns compact evidence so an oversized log does not hide the error. A failed Result remains failed for --require-ok and points to that report. Success includes the hashes of both generated files, not an assumption based on Cargo's exit code. Browser interaction and real HTTP mounting still need their own tests after this build. - -We **[Validate and create the selected native output directory](fs.make_dirs(path=`out`))** and **[Create the native build-report directory](fs.make_dirs(path=".marqdo/build"))** and **environment = None**. -1. `compiler` != None - We **environment = [Select this compiler for one child process](table.put(in=None, at="RUSTC", value=`compiler`))**. - -`argv` = - -| argument | -|---| -| "target/debug/marqdo" | -| wasm | -| build | -| "-o" | -| `out` | - -We **execution = [Build the current official browser artifact](engineering.run(argv=`argv`, env=`environment`, timeout_ms=300000, max_output=65536))** and **checked = [Retain actual build success or failure](engineering.check_exit(outcome=`execution`))**. -We **[Save bounded compiler evidence through native IO](fs.write_json(path=".marqdo/build/browser.json", value=`checked`))**. -1. not access(`checked`, "ok") - We **failed = [Keep this build incomplete](result.error(code="dev.browser_build", message="inspect .marqdo/build/browser.json", operation="build_browser"))**. - Return *failed*. -We **wasm = out + "/marqdo_wasm.wasm"** and **bridge = out + "/marqdo-bridge.js"** and **wasm_sha256 = [Hash the actual new WASM](fs.file_hash(path=`wasm`))** and **bridge_sha256 = [Hash the actual canonical bridge](fs.file_hash(path=`bridge`))**. - -`receipt` = - -| out | wasm_sha256 | bridge_sha256 | report | -|---|---|---|---| -| `out` | `wasm_sha256` | `bridge_sha256` | .marqdo/build/browser.json | - -Return *[Expose real browser build evidence](result.ok(value=`receipt`))*. - - -## prepare_browser - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | "1.65.0" | Pinned Playwright driver version | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result of workspace-local browser driver preparation | - -Use `version`="1.65.0" when preparing actual browser tests. The browser handbook keeps dependency installation and browser caches inside the workspace, using native directory operations and explicit existing npm/Playwright tools. Grant plugin, process.exec and fs.write. This prepares a driver only; call build_browser for current runtime artifacts and test_browser for actual behavior. No Python runner or global npm package is required. - -Return *[Prepare the pinned external browser capability](browser_tools.prepare(version=`version`))*. - - -## test_browser - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| out | text | ".marqdo/browser-handbook-assets" | Current native browser build output | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result from actual browser-effects, SPA, collaboration and bilingual network/complete-site browser tests | - -Use `out`=".marqdo/browser-handbook-assets" after prepare_browser and build_browser. The browser handbook stages the named runtime files with native IO, then supervises real callable servers and drives current WASM through the official bridge. The test result includes actual failures and is saved under .marqdo/browser-tests. Grant plugin, process.exec and fs.write; use --require-ok to stop a later task when a browser case fails. Constructed effects and source audit results remain separate evidence. - -Return *[Verify the actual callable sites in a real browser](browser_tools.verify(out=`out`))*. - - -## prepare_web - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:当前 Go Web 插件构建的真实退出状态和日志 | - -先完成 prepare_engineering,再从仓库根调用并授权 plugin。既有构建脚本负责调用 Go/cgo 编译本仓库的原生 Web 实现,并把编译产物放到插件解析器使用的构建目录。需要本机 Go 与 C 编译工具链;这里不安装工具、不更改全局环境,也不选择新的发布版本。Windows 构建仍须具备脚本要求的 cgo 工具链,Linux 的通过不能替代 Windows 验证。 - -这个入口把常用插件准备动作保存在可执行手册中。工程边界为子进程传递本仓库的 Git 信任配置,避免 Go 的 VCS 检查因不同文件所有者失败;该配置不写入全局 Git 设置,也不关闭 VCS 来源记录。只有编译和编译产物处理外联维护中的构建工具;日常源码读写仍使用原生文件任务。缺少工具、编译错误或非零退出会保留实际日志并返回失败,不能继续把旧插件当成本轮实现。成功只证明当前平台的插件已构建,随后还需运行对应 HTTP 与浏览器用例。 - -`argv` = - -| argument | -|---| -| bash | -| scripts/build-web-plugin.sh | - -构建结束后返回 *[在保留来源记录的受控进程边界编译当前插件](engineering.checked(argv=`argv`, timeout_ms=300000, max_output=65536))*。 diff --git a/skills/marqdo-dev/repository.mq.md b/skills/marqdo-dev/repository.mq.md deleted file mode 100755 index 8cb4e4b..0000000 --- a/skills/marqdo-dev/repository.mq.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -markup: occlusion -title: Native audit of the maintained Marqdo repository -import: - files: ./files.mq.md - fs: lib/fs.mq.md - table: lib/table.mq.md - text: lib/text.mq.md ---- - -This repository task discovers the maintained source scope using native file -operations and passes it to the compiler-backed audit. It is an actual callable -workflow, not a generated inventory script. Read the development index for -bootstrap and the programming guide for how to resolve findings. - -Only lib, ext, public, examples, skills and doc are selected. Intentional invalid -tests and protected man-test programs are outside this scope. Historical -.compat.mq.md examples remain compatibility evidence. Compiler warnings on -documented placeholders stay in the report; they do not turn into fake logic. -A report records the current source state, not a promise that the task is done. - -## audit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| write_report | bool | False | Also write the actual Result to .marqdo/audit/handbooks.json | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Actual repository source audit, with evidence retained on failure | - -Use `write_report`=False from the checkout root with plugin and fs.read. -Each selected directory is discovered natively; no Python, shell enumeration or -maintained list of hundreds of filenames is needed. Hidden staging trees, -dependency installs and build outputs are pruned. The historical compatibility -suffix is the only source-name exclusion within this maintained scope. - -The audit does not run found programs or load their imports. It reports source -parser/contract errors, missing callable return contracts and executable-unit -narrative gaps. Actual dependency checks, behavior, rendering and service -publication require their own workflow tests. An incomplete source report is -returned as a failed Result so --require-ok stops automation. - -Set write_report=True and grant fs.write to retain the same actual evidence -under the ignored audit directory. This intentionally replaces that generated -report; it never rewrites a program to silence a finding. A later audit reflects -later files, and a historical report does not establish compliance of new edits. -Missing selected directories retain a native error rather than silently narrowing -the task to make it appear complete. - -`directories` = - -| path | -|---| -| "lib" | -| "ext" | -| "public" | -| "examples" | -| "skills" | -| "doc" | - -`excluded` = - -| pattern | -|---| -| "**/.marqdo/**" | -| "**/node_modules/**" | -| "**/target/**" | - -We **paths = [Start the currently discovered source scope](table.empty_list())**. -- [Discover maintained modules through native file operations](for directories as directory) - We **names = [Discover actual Marqdo source files](fs.find(path=`directory`, pattern="**/*.mq.md", exclude=`excluded`))**. - - [Keep current sources while preserving historical compatibility examples](for names as relative) - 1. not [This file is an explicitly historical compatibility source](text.ends_with(text=`relative`, suffix=".compat.mq.md")) - We **path = directory + "/" + relative** and **paths = [Retain this actual maintained source](table.append(list=`paths`, item=`path`))**. -We **observed = [Audit the actual discovered sources without executing them](files.audit(paths=`paths`))**. -1. `write_report` - We **directory = [Prepare only the ignored generated audit directory](fs.make_dirs(path=".marqdo/audit"))** and - **saved = [Retain the same real success or failure evidence](fs.write_json(path=".marqdo/audit/handbooks.json", value=`observed`))**. -Return *observed* with all incomplete findings intact. diff --git a/skills/marqdo-dev/toolchain.mq.md b/skills/marqdo-dev/toolchain.mq.md deleted file mode 100755 index 6ab4b58..0000000 --- a/skills/marqdo-dev/toolchain.mq.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -markup: occlusion -title: Workspace-only Rust toolchain for real WASM validation -import: - fs: lib/fs.mq.md - net: lib/net.mq.md - re: lib/re.mq.md - text: lib/text.mq.md - table: lib/table.mq.md - sys: lib/sys.mq.md - result: lib/result.mq.md - engineering: ext/engineering/index.mq.md ---- - -This development tool handles one concrete environment gap: a compatible Linux x86 compiler and WASM standard library. Native Marqdo handles files, HTTP, SHA256 and decisions; the existing tar executable handles the official xz archive format. Call rust_wasm_linux, then pass its compiler path as the child RUSTC for the ordinary Marqdo wasm build command. Other operating systems use their own supported toolchain setup. - -## rust_wasm_linux - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | "1.93.1" | Pinned stable Rust version for the isolated Linux x86 toolchain | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with compiler path, matching host/WASM standard libraries and native digest receipts | - -Use `version`="1.93.1" on Linux x86 when the current compiler has no compatible wasm32-unknown-unknown standard library. The task prepares a complete official compiler plus its matching host and WASM standard libraries in the reserved .marqdo/toolchain cache. A distribution compiler rebuilt from source can reject official precompiled metadata even when its visible release number is identical; installing only one target archive is therefore insufficient in that case. This task changes no system compiler, global environment, shell profile or Python setup. The returned compiler path can be passed as RUSTC in a single engineering process environment. - -Run from the checkout root with plugin, process.exec, fs.read, fs.write and network.read. Each download is bounded and verified against its official checksum before tar extracts a component. Failures preserve their real evidence and stop the remaining sequence. Repeating the task rechecks cached bytes rather than assuming an existing filename is valid. The final compiler probe must report the requested version before a manifest is written. The result proves toolchain preparation; a separate wasm build and browser test must still verify this repository's artifact. - -1. not [A stable numeric release](re.is_match(text=`version`, pattern="^[0-9]+[.][0-9]+[.][0-9]+$")) - Return *[Explain the required version shape](result.error(code="toolchain.version", message="use a stable numeric Rust release"))*. -We **directory = ".marqdo/toolchain/rust-linux-x86-" + version** and **receipts = [Start verified distribution receipts](table.empty_list())**. -We **[Create this task-owned workspace directory](fs.make_dirs(path=`directory`))**. - -`components` = - -| @ | component | target | -|---|---|---| -| 1 | rustc | x86_64-unknown-linux-gnu | -| 2 | rust-std | x86_64-unknown-linux-gnu | -| 3 | rust-std | wasm32-unknown-unknown | - -- [Prepare matching compiler and target components](for components as specification) - We **installed = [Download, verify and extract this exact component](_component(version=`version`, component=access(specification, "component"), target=access(specification, "target"), directory=`directory`))**. - 1. not access(`installed`, "ok") - Return *installed*. - We **receipts = [Retain its native digest receipt](table.append(list=`receipts`, item=access(installed, "value")))**. -We **compiler = sys.cwd() + "/" + directory + "/bin/rustc"** and **probed = [Verify the extracted compiler actually starts](engineering.checked(argv=table.append(list=table.append(list=table.empty_list(), item=`compiler`), item="--version"), timeout_ms=30000, max_output=32768))**. -1. not access(`probed`, "ok") - Return *probed*. -We **reported = [Read the actual compiler version](access(access(`probed`, "value"), "stdout"))**. -1. not [The requested release was installed](text.starts_with(text=`reported`, prefix=("rustc " + `version` + " "))) - Return *[Retain the unexpected compiler identity](result.error(code="toolchain.compiler", message=`reported`))*. - -`manifest` = - -| version | compiler | components | -|---|---|---| -| `version` | `compiler` | `receipts` | - -We **[Save the verified workspace toolchain receipt](fs.write_json(path=(directory + "/manifest.json"), value=`manifest`))**. -Return *[Expose the compiler for an explicit child environment](result.ok(value=`manifest`))*. - -## _component - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable numeric Rust release | -| component | text | required | rustc or rust-std | -| target | text | required | x86_64-unknown-linux-gnu or wasm32-unknown-unknown | -| directory | text | required | Task-owned workspace toolchain directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with the verified component digest and extraction evidence | - -Use `version`, `component`, `target` and `directory` only for the fixed compiler/standard-library components selected by rust_wasm_linux. Source bytes and checksums come from the official Rust distribution over HTTPS. A cached archive is reused only after its current native SHA256 matches the fetched checksum. A truncated transfer or HTTP failure is preserved as a failed Result; extraction never runs on an unchecked archive. Downloading, hashing and directory creation use native Marqdo. Tar is the explicit system boundary for the xz distribution format, with an argument array rather than generated shell code. Extraction is restricted to this component's own archive subtree and the selected workspace directory. No Python interpreter or system installation directory participates. - -The extracted files retain their official executable modes, while --no-same-owner keeps archive ownership out of this workspace installation. The tar installer script is not executed. Component receipts identify the checked archive bytes; only the later compiler probe and repository build establish that those files work together. A failed extraction leaves the task-owned cache available for a verified retry. The caller's operating system still governs the external tar process, so this helper uses the fixed official component subtree rather than a caller-supplied archive member. - -1. not [A stable numeric release](re.is_match(text=`version`, pattern="^[0-9]+[.][0-9]+[.][0-9]+$")) - Return *[Reject an invalid release name](result.error(code="toolchain.version", message="stable numeric Rust release required"))*. -1. (`component` != "rustc" and `component` != "rust-std") or (`target` != "x86_64-unknown-linux-gnu" and `target` != "wasm32-unknown-unknown") or (`component` == "rustc" and `target` != "x86_64-unknown-linux-gnu") - Return *[Reject an unsupported component](result.error(code="toolchain.component", message="this task supports the Linux x86 compiler and its host/WASM standard libraries"))*. -We **package = component + "-" + version + "-" + target** and **url = "https://static.rust-lang.org/dist/" + package + ".tar.xz"** and **cache = directory + "/downloads"**. -We **[Create the native download cache](fs.make_dirs(path=`cache`))**. -We **archive = cache + "/" + package + ".tar.xz"** and **checksum = [Read the official bounded checksum](net.get(url=(url + ".sha256"), max_bytes=4096))**. -1. not access(`checksum`, "ok") - Return *checksum*. -We **body = [Read the checksum text](access(access(`checksum`, "value"), "body"))** and **expected = [Select its SHA256 field](table.first(list=text.str_split(s=text.str_trim(s=`body`), sep=" ")))**. -1. not [A complete SHA256 was returned](re.is_match(text=`expected`, pattern="^[a-f0-9]{64}$")) - Return *[Retain the invalid checksum response](result.error(code="toolchain.checksum", message="official checksum is not a SHA256 digest"))*. -We **ready = False** before inspecting this cache entry. -1. [The selected archive is already cached](fs.exists(path=`archive`)) - We **actual = [Hash its actual cached bytes](fs.file_hash(path=`archive`))** and **ready = actual == expected**. -1. not `ready` - We **downloaded = [Stream the official component into its cache path](net.download(url=`url`, path=`archive`, timeout_ms=120000, max_bytes=268435456))**. - 1. not access(`downloaded`, "ok") - Return *downloaded*. -We **actual = [Verify the bytes before extraction](fs.file_hash(path=`archive`))**. -1. `actual` != `expected` - Return *[Stop on a mismatching component](result.error(code="toolchain.digest", message="downloaded Rust component SHA256 differs from the official checksum"))*. -We **member = component**. -1. `component` == "rust-std" - We **member = "rust-std-" + target**. -We **subtree = [Select the verified component path](package + "/" + member)**. - -`argv` = - -| argument | -|---| -| tar | -| "--extract" | -| "--xz" | -| "--no-same-owner" | -| "--file" | -| `archive` | -| "--directory" | -| `directory` | -| "--strip-components=2" | -| `subtree` | - -We **extracted = [Extract only this verified distribution component](engineering.checked(argv=`argv`, timeout_ms=120000, max_output=32768))**. -1. not access(`extracted`, "ok") - Return *extracted*. - -`receipt` = - -| package | sha256 | -|---|---| -| `package` | `actual` | - -Return *[Retain the verified component identity](result.ok(value=`receipt`))*. diff --git a/skills/marqdo-release/SKILL.md b/skills/marqdo-release/SKILL.md deleted file mode 100755 index a9948a9..0000000 --- a/skills/marqdo-release/SKILL.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -name: marqdo-release -description: Prepare, publish and verify a user-authorized Marqdo full, cli or extension release through its executable mq.md handbook. Use for release versioning, immutable tags, matching CI gates, GitHub/R2 parity and Ubuntu PPA publication. ---- - -Read [the executable release entry](../marqdo-release/index.mq.md) and use its task routing. Version and mode come from the user; an already stated choice remains authorized. Inspection of an old release does not authorize republishing it. Never infer a new version, replace a tag, force-push or bypass hooks. - -Use `marqdo call` on the actual handbook headings. The repository development binary is `target/debug/marqdo`; prepare its engineering plugin through [the development entry](../marqdo-dev/index.mq.md). File reading and authoring use native [file tools](../marqdo-dev/files.mq.md). No Python release orchestrator is required. New OS/service capabilities belong at explicit plugin or external-tool boundaries; version decisions, retries and publication order remain readable mq.md. - -The entry preserves full/cli/ext deliverables, separate editor sources, clean-main tagging, bilingual authored notes, exact-commit Release and EK gates, both native platforms, GitHub/R2 identical bytes, VERSION-after-ZIP ordering and Ubuntu source/build/apt evidence. Every applicable obligation must be verified before declaring completion. Default full/cli work includes PPA; gh-pages deployment needs its own instruction. - -Read-only status and verification are separate from publication. Grant effects stated by each task. Inspect Result.ok before value; use --require-ok when an external automation must stop on a failed Result. Credentials stay in their existing private stores. Interactive sudo/GPG/dput or a failed service request remains incomplete: report the concrete failure and the exact handbook recovery call, preserving local evidence. - -Independent extension releases commit reviewed bilingual notes at doc/releases/ext-X.Y.Z.md before tagging. The [pack handbook](../../skills/marqdo-release/packs.mq.md) and extension-release.yml run native staging, both platform builds, exact-tag release creation and non-clobbering gh asset upload through marqdo call. An existing upload is inspected rather than replaced. Windows execution remains a CI obligation; a local Linux ZIP cannot prove it. diff --git a/skills/marqdo-release/_bridge.mq.md b/skills/marqdo-release/_bridge.mq.md deleted file mode 100755 index ab45cac..0000000 --- a/skills/marqdo-release/_bridge.mq.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -markup: occlusion -title: Native release boundary -import: - engineering: ext/engineering/index.mq.md - result: lib/result.mq.md ---- - -The release handbook composes native Marqdo libraries and this narrow extension -boundary. Ordinary file reads/writes, version decisions, asset lists and state -checks stay in Marqdo. Authenticated service requests, bounded OS commands and -ZIP-format inspection use the engineering native plugin. No Python loader, -generated command program or duplicate release orchestrator is involved. - -A native plugin has the calling OS user's authority. Root is a working/artifact -location and cannot be described as an OS sandbox. These calls need plugin -effects; their public task contracts additionally declare any native filesystem, -network or environment operations they perform. Reading the handbook authorizes -none of its external publication steps. - -## request - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| operation | text | required | Native boundary operation selected by the task | -| payload | map | required | Structured arguments; never credentials | -| root | text | "." | Existing checkout/artifact root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Actual boundary Result; failed child exit stays failed | - -Use `operation`, `payload` and `root`="." for a documented external boundary. -The extension reports transport success separately from a child's exit code. -Release commands require code zero and no timeout, so convert a completed but -failed child into a release failure before another phase can continue. Stdout -and stderr retain bounded diagnostic evidence with known credentials redacted. -Other operations preserve their own Result without manufacturing success. - -We **answer = [Invoke the maintained native engineering boundary](engineering.request(operation=`operation`, payload=`payload`, root=`root`))**. -1. not access(`answer`, "ok") - Return *answer* with its original error. -1. `operation` == "command" - We **execution = [Read the bounded child result](access(answer, "value"))**. - 1. access(`execution`, "code") != 0 or access(`execution`, "timed_out") - Return *[Keep the unsuccessful child visible](result.error(code="release.command_failed", message=str(`execution`), operation="command"))*. -Return *answer* when this requested boundary completed successfully. diff --git a/skills/marqdo-release/asset_io.mq.md b/skills/marqdo-release/asset_io.mq.md deleted file mode 100755 index 1c488ad..0000000 --- a/skills/marqdo-release/asset_io.mq.md +++ /dev/null @@ -1,228 +0,0 @@ ---- -markup: occlusion -title: Native artifact IO for the release handbook -import: - engineering: ext/engineering/index.mq.md - fs: lib/fs.mq.md - net: lib/net.mq.md - table: lib/table.mq.md - result: lib/result.mq.md - text: lib/text.mq.md - re: lib/re.mq.md - uuid: lib/uuid.mq.md - sys: lib/sys.mq.md ---- - -These functions are the concrete IO used by assets.mq.md. Native Marqdo libraries read, hash, download, stage and clean files. The extension handles authenticated R2 writes and ZIP-format inspection. Source identity, release completeness and publication ordering remain visible Marqdo dataflow. - -## verify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| asset | map | required | Exact GitHub asset record including size and digest | -| path | text | required | Local file selected inside the granted filesystem root | -| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with native hash evidence and validated archive metadata | - -Use `asset`, `path` and `root`="." to verify local bytes before publication. -Size and SHA256 come from lib/fs; a GitHub digest, when supplied, must match. -The native engineering extension inspects only the ZIP/VSIX format and CRCs. -Ordinary file facts stay in Marqdo instead of an external script. A mismatched -length or hash remains a failed Result and cannot advance the CDN pointer. - -The format layer rejects escaping entries, duplicate names, symlinks and excessive -expansion. It does not extract or execute a CLI. Source pack version, native file -roles and VSIX version are checked by assets.content after this byte-level stage. -This function requires fs.read and plugin; executable-only assets use the same -size/hash checks without pretending they contain an archive. - -We **information = [Read the native file information](fs.stat(path=`path`))** and -**size = [Read its actual byte count](access(information, "size"))** and -**sha256 = [Hash the actual file through the native filesystem](fs.file_hash(path=`path`))** and -**expected = [Read GitHub's optional digest metadata](table.get(map=`asset`, key="digest"))** and -**name = [Retain the asset's exact filename](access(asset, "name"))**. -1. `size` != access(`asset`, "size") or (`expected` != None and `expected` != "sha256:" + `sha256`) - Return *[Reject bytes that differ from GitHub metadata](result.error(code="release.asset_digest", message=`name`, operation="asset_io.verify"))*. - -`record` = - -| name | size | sha256 | -|---|---|---| -| `name` | `size` | `sha256` | - -1. [This asset is an archive format](text.ends_with(text=`name`, suffix=".zip") or text.ends_with(text=`name`, suffix=".vsix")) - We **archive = [Inspect ZIP entries and their CRCs without extraction](engineering.inspect_zip(path=`path`, root=`root`))**. - 1. not access(`archive`, "ok") - Return *archive* with the actual format error. - We **record = [Retain the inspected format evidence](table.merge(a=`record`, b=access(archive, "value")))**. -Return *[The verified local byte identity](result.ok(value=`record`))*. - -## fetch - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| asset | map | required | GitHub asset record chosen by the release catalog | -| directory | text | required | Release-specific destination under --fs-root | -| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with a reused or freshly downloaded verified local artifact | - -Use `asset`, `directory` and `root`="." after assets.catalog has checked all -required filenames. A local file is reused only after its size, hash and archive -format are verified again. Otherwise native net.download streams into an atomic -replacement under the granted filesystem root. Failed HTTP transfers do not -replace an existing destination. The proxy route is tried before the original -GitHub asset URL; explicit fixture URLs remain visible in test metadata. - -Downloads have a 64 MiB per-file limit and a 90-second request timeout here. -These limits cover the current release matrix; a larger future artifact needs -a deliberate documented limit change. No credential is put into a URL or native -download header. Role-specific contents are checked by the calling task. - -We **name = [Read the exact catalog filename](access(asset, "name"))** and -**path = directory + "/" + name** and **prepared = [Create the explicit staging directory](fs.make_dirs(path=`directory`))**. -1. [A local candidate already exists](fs.exists(path=`path`)) - We **existing = [Recheck its actual byte identity](verify(asset=`asset`, path=`path`, root=`root`))**. - 1. access(`existing`, "ok") - Return *existing* without downloading it again. -We **original = [Read the selected asset's original URL](access(asset, "browser_download_url"))** and -**proxy = [Select the documented GitHub mirror](text.replace(text=`original`, old="https://github.com/", new="https://proxy.cflmy.top/github.com/"))**. - -`urls` = - -| url | -|---| -| `proxy` | -| `original` | - -We **headers = [Identify this public verification download](table.put(in=None, at="User-Agent", value="marqdo-engineering"))**. - -We **last = [Start with no completed transfer](result.error(code="release.download", message=`name`, operation="asset_io.fetch"))**. -- [Try the bounded public download routes](for urls as url) - We **downloaded = [Stream the official artifact through native IO](net.download(url=`url`, path=`path`, headers=`headers`, timeout_ms=90000, max_bytes=67108864))**. - 1. access(`downloaded`, "ok") - We **last = [Check the downloaded bytes and archive format](verify(asset=`asset`, path=`path`, root=`root`))**. - 1. access(`last`, "ok") - Return *last* with its real evidence. - 2. * - We **last = downloaded** to preserve the last transport failure. -Return *last* when neither route produced a verified artifact. - -## cdn - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Versioned or latest VERSION/pack path from the release model | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing public pointer text or native download hash | - -Use `path` only for a modeled CDN object. The public base is ext.marqdo.com -unless an explicit fixture override is configured. VERSION is read as UTF-8; -binary packs use native net.download, fs.file_hash and native cleanup in a -UUID-named directory under .marqdo/release-check. No Python body reader or local -file writer participates. A handled network failure cleans its owned directory. - -A successful HTTP request proves only that URL's bytes; the caller compares the -hash with GitHub and decides whether the release is complete. Edge-cache delay -remains visible. Unexpected filesystem diagnostics may leave the uniquely owned -staging directory for inspection; no unrelated directory is removed. -This task needs network.read, fs.write, environment.read and random.read. - -We **valid = [Accept only modeled public artifact paths](re.is_match(text=`path`, pattern="^(latest|v[0-9]+\\.[0-9]+\\.[0-9]+)/(VERSION|marqdo-[A-Za-z0-9._-]+\\.zip)$"))**. -1. not `valid` - Return *[Reject an arbitrary CDN cache path](result.error(code="release.cdn_path", message="expected a modeled release path", operation="asset_io.cdn"))*. -We **base = [Read the explicit fixture override if configured](sys.env_get(name="MARQDO_RELEASE_CDN"))**. -1. `base` == None - We **base = "https://ext.marqdo.com"** for normal public verification. -We **url = base + "/" + path**. - -We **headers = [Identify this public verification download](table.put(in=None, at="User-Agent", value="marqdo-engineering"))**. - -1. [This object is a version pointer](text.ends_with(text=`path`, suffix="/VERSION")) - We **read = [Read the public UTF-8 version pointer](net.get(url=`url`, headers=`headers`, timeout_ms=30000))**. - 1. not access(`read`, "ok") - Return *read* with its actual network error. - We **response = [Read the HTTP result](access(read, "value"))**. - 1. access(`response`, "status") != 200 - Return *[Keep the public pointer HTTP failure](result.error(code="release.cdn_http", message=str(access(response, "status")), operation="asset_io.cdn"))*. - We **version = [Trim only the pointer's outer whitespace](text.str_trim(s=access(response, "body")))**. - - We **pointer = [Keep the version as one named result field](table.put(in=None, at="version", value=`version`))**. - - Return *[The actual public version pointer](result.ok(value=`pointer`))*. -We **parent = [Prepare the ignored verification area](fs.make_dirs(path=".marqdo/release-check"))** and -**identifier = [Choose an independent staging identity](uuid.v4())** and **directory = ".marqdo/release-check/" + identifier** and -**created = [Reserve this verification directory](fs.make_dir(path=`directory`))** and **destination = directory + "/artifact.zip"**. -We **downloaded = [Stream public bytes into this owned native stage](net.download(url=`url`, path=`destination`, headers=`headers`, timeout_ms=90000, max_bytes=67108864))**. -1. not access(`downloaded`, "ok") - We **removed = [Clean only this failed request's owned stage](fs.remove_tree(path=`directory`))**. - Return *downloaded* with its real transport failure. -We **sha256 = [Hash the actual public bytes](fs.file_hash(path=`destination`))** and -**information = [Read the downloaded file information](fs.stat(path=`destination`))** and -**size = [Read their actual byte count](access(information, "size"))** and -**removed = [Remove this completed request's owned stage](fs.remove_tree(path=`directory`))**. - -`evidence` = - -| size | sha256 | -|---|---| -| `size` | `sha256` | - -Return *[The measured public object identity](result.ok(value=`evidence`))*. - -## upload - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| files | list | required | Exactly three verified path/name/sha256 records | -| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing the actual R2 write evidence | - -Use `version`, `files` and `root`="." only for the release already authorized -by the user. The caller has checked all three source/native files against -GitHub before this operation begins. Marqdo controls the write order explicitly: -versioned and latest pack objects first, both VERSION pointers last. Private R2 -signing is the only native service boundary. No whole-directory sweep occurs. - -An interrupted upload keeps the old pointer until every required pack has -succeeded. Existing older versions are never deleted. The tool returns an error -on the first failed write and preserves already-written object evidence through -the service itself; it does not call a partial batch complete. Public byte-parity -checks still follow in assets.status. - -We **count = [Require the source pack and both platform packs](len(`files`))**. -1. `count` != 3 - Return *[Reject an incomplete CDN upload set](result.error(code="release.cdn_files", message="exactly three verified packs are required", operation="asset_io.upload"))*. - -`prefixes` = - -| prefix | -|---| -| "v`version`" | -| latest | - -We **written = [Start the service write evidence](table.empty_list())**. -- [Write both public pack namespaces before pointers](for prefixes as prefix) - - [Upload only the preverified pack set](for files as file) - We **key = prefix + "/" + access(file, "name")** and - **uploaded = [Sign and upload the exact checked local bytes](engineering.put_file(path=access(file, "path"), key=`key`, sha256=access(file, "sha256"), root=`root`))**. - 1. not access(`uploaded`, "ok") - Return *uploaded* before changing any VERSION pointer. - We **written = [Retain the completed object identity](table.append(list=`written`, item=access(uploaded, "value")))**. -- [Advance pointers only after all six pack writes succeeded](for prefixes as prefix) - We **uploaded = [Write the explicit version pointer](engineering.put_text(key=`prefix` + "/VERSION", text=`version` + "\n", root=`root`))**. - 1. not access(`uploaded`, "ok") - Return *uploaded* with the actual pointer failure. - We **written = [Retain this pointer write](table.append(list=`written`, item=access(uploaded, "value")))**. -Return *[All completed service writes](result.ok(value=`written`))*. diff --git a/skills/marqdo-release/assets.mq.md b/skills/marqdo-release/assets.mq.md deleted file mode 100755 index 8c45f66..0000000 --- a/skills/marqdo-release/assets.mq.md +++ /dev/null @@ -1,590 +0,0 @@ ---- -markup: occlusion -title: Release assets: bytes, contents and CDN parity -import: - bridge: ./_bridge.mq.md - native: ./asset_io.mq.md - github: ./github.mq.md - model: ./model.mq.md - result: lib/result.mq.md - table: lib/table.mq.md - text: lib/text.mq.md - json: lib/json.mq.md - toml: lib/toml.mq.md ---- - -Artifacts have a lifecycle: discover the exact GitHub metadata, download to a -release-specific directory, verify bytes and package role, publish only the -three extension packs, then compare every public copy. Full mode requires ten -GitHub assets; Linux CLI and Linux native packages are separate obligations. - -The local staging directory is dist/release-X.Y.Z by default. Downloads use -atomic .partial replacement and bounded retries. Verification reads ZIP entries -without extraction. Existing verified files are reusable; a failed operation -never changes an old tag or treats an incomplete upload as completion. - -Read-only public checks and local downloads use plugin,fs.write,network.read,environment.read because the checked-in -native transport owns those service and filesystem operations. Publishing is an -explicit external mutation authorized by a release request. Credentials remain -in existing environment or ~/.marqdo/r2.env stores and are not call arguments. - -```sh -marqdo call skills/marqdo-release/assets.mq.md download 'version="2.6.0"' --effects plugin,fs.write,network.read,environment.read --fs-root . --json -marqdo call skills/marqdo-release/assets.mq.md status 'version="2.6.0"' --effects plugin,fs.write,network.read,environment.read --fs-root . --json -``` - -These commands inspect the existing release; they do not republish it. Use -publish only for the version and mode actually authorized. On missing keys, -configure the documented local credential store and call publish again. Never -put credentials in a parameter, notes file, source tree or session binding. - -## named - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| assets | list | required | GitHub asset records from one exact release | -| name | text | required | Exact filename to look up | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Matching asset record or None | - -Use `assets` and `name` to find one exact release artifact. Prefix matches -are insufficient because source packs, CLI bundles and native packs serve -different roles. This pure helper preserves the GitHub-provided size, digest and -download URL together. It neither creates an asset nor substitutes a file from -a previous release. None means the caller must keep the release incomplete, -even if other files are already downloadable. - -- [Find the exact filename in this release](for assets as asset) - 1. access(`asset`, "name") == `name` - Return *asset* with its original metadata. -Return *None* when no asset has that exact name. - -## catalog - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing the accepted plan and complete GitHub asset records | - -Use `version`, `mode`="full" and `root`="." before downloading or publishing. -All required names are checked first, so an incomplete release cannot partially -advance the CDN pointer. Extra GitHub assets are allowed; they do not replace -any required filename. A missing release and a missing platform pack have -separate error codes. Only metadata is fetched here; no local archive is trusted -merely because it has the right filename. Content and digest checks occur next. -For ext mode the same rule requires source, Windows native and Linux native packs. - -We **planned = [Read the exact deliverable contract](model.plan(version=`version`, mode=`mode`))**. -1. not access(`planned`, "ok") - Return *planned* with its failure intact. - -We **published = [Read this tag's actual GitHub assets](github.release(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`published`, "ok") - Return *published* with its failure intact. - -We **release_data = [Read published metadata or None](access(published, "value"))**. -1. `release_data` == None - Return *[Keep a missing release visible](result.error(code="release.missing", message="GitHub release is not published", operation="assets.catalog"))*. -We **plan_data = [Keep the validated mode and names](access(planned, "value"))** and -**assets = [Read GitHub asset records](access(release_data, "assets"))** and -**required = [Read the required filenames](access(plan_data, "required"))**. -- [Require every declared deliverable before continuing](for required as name) - We **asset = [Find this exact artifact](named(assets=`assets`, name=`name`))**. - 1. `asset` == None - Return *[Report the missing deliverable](result.error(code="release.asset_missing", message=`name`, operation="assets.catalog"))*. - -`catalog_data` = - -| plan | release | assets | -|---|---|---| -| `plan_data` | `release_data` | `assets` | - -Return *[The complete metadata catalog](result.ok(value=`catalog_data`))*. - -## bundle_content - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| entries | list | required | Validated archive entry names | -| platform | text | required | windows or linux, chosen from the catalog filename | -| name | text | required | Exact bundle filename retained in errors | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result confirming CLI, readable libraries and every embedded native plugin | - -Use `entries`, `platform` and `name` for an already CRC-checked CLI bundle. -A standalone executable has a different role: the bundle must also carry its -readable standard and extension sources. This task requires the interpreter, -file/table libraries, extension version, web/quantum handbooks and all baseline -native libraries. When engineering sources are present, its native library is -required in the same bundle. - -Platform names are explicit data. Windows uses marqdo.exe and DLL names, Linux -uses marqdo and lib-prefixed shared objects. A missing library cannot be excused -by success on the other platform. Archive paths use their portable forward-slash -representation; no extraction or ABI execution happens in this pure layer. - -Hash/size/CRC identity comes from the earlier byte check, and the correct-commit -CI gate proves the platform build. This function verifies packaging coherence, -not scientific correctness, loader ABI compatibility or a machine's installed -system dependencies. Its successful Result means every listed bundle obligation -was observed in these actual entry names. - -We **binary = "marqdo"** and **prefix = "lib"** and **suffix = ".so"** for Linux. -1. `platform` == "windows" - We **binary = "marqdo.exe"** and **prefix = ""** and **suffix = ".dll"**. -2. `platform` != "linux" - Return *[Reject an unknown bundle platform](result.error(code="release.platform", message=`platform`, operation="bundle_content"))*. - -`required` = - -| entry | -|---| -| `binary` | -| "lib/fs.mq.md" | -| "lib/table.mq.md" | -| "ext/VERSION" | -| "ext/web/index.mq.md" | -| "ext/quantum/index.mq.md" | - -`plugins` = - -| plugin | -|---| -| "agent" | -| "linalg" | -| "llm" | -| "quantum" | -| "web" | - -1. [This bundle includes engineering sources](table.contains(list=`entries`, item="ext/engineering/index.mq.md")) - We **plugins = [Require the same new native capability](table.append(list=`plugins`, item="engineering"))**. -- [Add each embedded native dependency](for plugins as plugin) - We **required = [Retain the platform-specific native path](table.append(list=`required`, item="ext/native/" + prefix + plugin + suffix))**. -- [Check each actual bundle obligation](for required as entry) - 1. not [The bundle contains this required file](table.contains(list=`entries`, item=`entry`)) - Return *[Retain the missing packaging entry](result.error(code="release.bundle_content", message=`name` + ": " + `entry`, operation="bundle_content"))*. -Return *[The actual packaging checks passed](result.ok(value=True))*. - - -## matrix - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| records | list | required | Complete catalog-selected records after individual size/digest/role checks | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result retaining records only when declared engineering sources have both native platforms | - -Use `records` after individual content checks on the complete release set. -The source pack declares which extension sources it actually ships. If it contains -engineering/index.mq.md, both native packs must contain that capability too. -A new source pack combined with older native packs would otherwise pass separate -filename checks and fail only when an agent tries to load its new tool. - -This check follows package contents rather than guessing a version threshold. -Historical packs without engineering sources retain their original five-plugin -contract. CLI bundles are checked independently by bundle_content, including -their embedded source/native correspondence. The release model and catalog still -own the complete filename matrix for full/cli/ext; this helper does not turn an -arbitrary partial list into proof of an entire release. - -The function is pure. It neither downloads, extracts nor executes an archive. -Missing new native capability remains a failed Result before publication, and -a successful result preserves all previously verified records for summarization. - -We **engineering = False** and **windows = False** and **linux = False** before inspecting the declared source footprint. -- [Read capability declarations from the source pack](for records as record) - We **name = [Read this verified filename](access(record, "name"))**. - 1. [This is the extension source pack](text.ends_with(text=`name`, suffix="-ext.zip")) - We **engineering = [Observe whether engineering sources actually ship](table.contains(list=access(record, "entries"), item="ext/engineering/index.mq.md"))**. -1. not `engineering` - Return *[Keep the historical source/native contract](result.ok(value=`records`))*. -- [Require new capability on each native platform](for records as record) - We **name = [Read this native candidate's filename](access(record, "name"))** and **required = None**. - 1. [This is the Windows native pack](text.ends_with(text=`name`, suffix="-native-x86_64-pc-windows-msvc.zip")) - We **windows = True** and **required = "native/engineering.dll"**. - 1. [This is the Linux native pack](text.ends_with(text=`name`, suffix="-native-x86_64-unknown-linux-gnu.zip")) - We **linux = True** and **required = "native/libengineering.so"**. - 1. `required` != None - 1. not [This platform contains its declared engineering library](table.contains(list=access(`record`, "entries"), item=`required`)) - Return *[Reject source/native capability drift](result.error(code="release.native_capability", message=`name`, operation="assets.matrix"))*. -1. not `windows` or not `linux` - Return *[Require both native platforms](result.error(code="release.native_platform", message="engineering sources require Windows and Linux native packs", operation="assets.matrix"))*. -Return *[The consistent source/native records](result.ok(value=`records`))*. - - -## summaries - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| records | list | required | Verified records retained after matrix checks | -| directory | text | required | Actual local staging directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Compact name/path/size/SHA256/entry-count evidence rows | - -Use `records` and `directory` after verification, not as a replacement for it. -An archive can contain thousands of source paths. Returning every path and full -package metadata at the end of a release obscures the handful of facts an agent -needs to act: exact local path, byte length, digest and entry count. - -This pure projection keeps those observed facts in one row per artifact. -It does not invent a verified flag, rehash a file or silently discard an earlier -failure. Executable-only files have zero archive entries. Detailed inspection -remains available from asset_io.verify and engineering.inspect_zip when needed. -The reduced final evidence is also suitable for saving through native fs.write_json, -without requiring another language to parse command output or reconstruct a report. - -We **rows = [Start concise artifact evidence](table.empty_list())**. -- [Project already-checked artifacts into readable rows](for records as record) - We **name = [Keep the exact filename](access(record, "name"))** and **size = [Keep the measured size](access(record, "size"))** and **sha256 = [Keep the measured digest](access(record, "sha256"))** and **entries = [Read optional archive details](table.get(map=`record`, key="entries"))** and **entry_count = 0** and **path = directory + "/" + name**. - 1. `entries` != None - We **entry_count = [Count the inspected entries](len(entries))**. - - `row` = - - | name | path | size | sha256 | entry_count | - |---|---|---|---|---| - | `name` | `path` | `size` | `sha256` | `entry_count` | - - We **rows = [Retain this measured artifact](table.append(list=`rows`, item=`row`))**. -Return *rows* after projecting each verified record. - - -## content - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| record | map | required | Verified archive record produced by the byte transport | -| version | text | required | Stable X.Y.Z explicitly chosen by the user | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result retaining archive evidence after role-specific content checks | - -Use `record` and `version` after a SHA256/size/CRC check. This second layer -checks useful contents: extension sources identify their pack version; native -packs retain their baseline plugins and source-declared new capabilities; bundles include the embedded-library -sources and a CLI; VSIX metadata declares its editor version; the source archive -contains the tagged Cargo version. These checks complement CI and do not claim -to prove ABI compatibility or scientific correctness of every plugin. -An executable-only asset has no ZIP entries and relies on its GitHub digest and -build evidence. A source pack without either handbook entry is unusable for the -document-first workflow even when it decompresses correctly. Native filenames -are checked individually because one missing shared library would otherwise -surface only after installation, far from the publication step that caused it. No archive is extracted or executed while reading its metadata. - -Version text is trimmed for comparison, so Windows CRLF and Unix LF identify -the same declared version without changing any archive bytes. SHA256 still -covers the original byte sequence. A source snapshot is checked through its -actual TOML package.version field; a matching dependency version cannot satisfy -that role. Missing metadata remains a failure rather than a guessed version. - -We **name = [Read the verified filename](access(record, "name"))**. -1. [This is an executable-only asset](text.ends_with(text=`name`, suffix=".exe")) - Return *[Retain its verified digest evidence](result.ok(value=`record`))*. -We **entries = [Read the archive entry list](access(record, "entries"))** and -**metadata = [Read bounded metadata files](access(record, "metadata"))** and -**required = [Start the role-specific entry list](table.empty_list())**. -1. [This is the source extension pack](text.ends_with(text=`name`, suffix="-ext.zip")) - - `required` = - - | entry | - |---| - | ext/VERSION | - | ext/quantum/index.mq.md | - | ext/web/index.mq.md | - - We **declared = [Read the pack version without assuming platform newlines](table.get(map=`metadata`, key="ext/VERSION"))**. - 1. `declared` == None - Return *[Report missing version metadata](result.error(code="release.pack_version", message=`name`, operation="assets.content"))*. - We **pack_version = [Normalize the source pack version field](text.str_trim(s=`declared`))**. - 1. `pack_version` != `version` - Return *[Reject a mismatched source pack version](result.error(code="release.pack_version", message=`name`, operation="assets.content"))*. -1. [This is a Linux native pack](text.contains(text=`name`, sub="-native-x86_64-unknown-linux-gnu")) - - `required` = - - | entry | - |---| - | native/libagent.so | - | native/liblinalg.so | - | native/libllm.so | - | native/libquantum.so | - | native/libweb.so | - -1. [This is a Windows native pack](text.contains(text=`name`, sub="-native-x86_64-pc-windows-msvc")) - - `required` = - - | entry | - |---| - | native/agent.dll | - | native/linalg.dll | - | native/llm.dll | - | native/quantum.dll | - | native/web.dll | - -1. [This is the standard-library source pack](text.ends_with(text=`name`, suffix="-stdlib.zip")) - - `required` = - - | entry | - |---| - | lib/fs.mq.md | - | lib/table.mq.md | - | lib/文件.mq.md | - -1. [This is the offline documentation pack](text.ends_with(text=`name`, suffix="-public.zip")) - We **required = [Require the documentation entry](table.append(list=`required`, item="index.html"))**. -1. [This is the tagged source snapshot](text.ends_with(text=`name`, suffix="-source.zip")) - We **cargo_source = [Read the selected manifest metadata](table.get(map=`metadata`, key="Cargo.toml"))**. - 1. `cargo_source` == None - Return *[Report missing source manifest](result.error(code="release.source_metadata", message=`name`, operation="assets.content"))*. - We **manifest = [Parse the actual source package declaration](toml.parse(text=`cargo_source`))** and **package_version = [Read the package version](access(access(manifest, "package"), "version"))**. - 1. `package_version` != `version` - Return *[Reject a source snapshot from another version](result.error(code="release.source_version", message=`name`, operation="assets.content"))*. -1. [This is the editor extension](text.ends_with(text=`name`, suffix=".vsix")) - We **package = [Decode the VSIX package metadata](json.parse(text=access(metadata, "extension/package.json")))**. - 1. access(`package`, "version") != `version` - Return *[Reject a mismatched VSIX version](result.error(code="release.vsix_version", message=`name`, operation="assets.content"))*. -- [Check every entry required by this role](for required as entry) - 1. not [The entry is present](table.contains(list=`entries`, item=`entry`)) - Return *[Report missing archive content](result.error(code="release.archive_content", message=`name` + ": " + entry, operation="assets.content"))*. -1. not [This is a standalone native pack](text.contains(text=`name`, sub="-native-")) - We **platform = None**. - 1. [This is a Windows CLI bundle](text.ends_with(text=`name`, suffix="-x86_64-pc-windows-msvc.zip")) - We **platform = "windows"**. - 1. [This is a Linux CLI bundle](text.ends_with(text=`name`, suffix="-x86_64-unknown-linux-gnu.zip")) - We **platform = "linux"**. - 1. `platform` != None - We **checked = [Verify the embedded source/native bundle](bundle_content(entries=`entries`, platform=`platform`, name=`name`))**. - 1. not access(`checked`, "ok") - Return *checked*. -Return *[Keep the verified digest and content evidence](result.ok(value=`record`))*. - -## download - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| directory | any | None | Relative destination; None selects dist/release-X.Y.Z | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with locally downloaded, byte-verified and content-checked assets | - -Use `version`, `mode`="full", `directory`=None and `root`=".". -The destination stays inside the checkout. Files are reused only after their -size and GitHub digest are checked again; a .partial file never counts as an -artifact. Network retries try the configured GitHub proxy then the original -asset URL. The download adapter validates archive paths and CRCs without -extracting an executable. Role-specific checks below use the same version. -A failure stops the batch with its real error. Successfully verified files -remain in the destination for a retry, while no R2 pointer or PPA is changed. -plugin,fs.write,network.read,environment.read includes the adapter's local writes and network authority; the -working root is a location constraint, not a subprocess permission sandbox. - -We **catalog_result = [Require complete GitHub metadata first](catalog(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`catalog_result`, "ok") - Return *catalog_result* with its failure intact. - -We **catalog_data = [Read the accepted metadata](access(catalog_result, "value"))** and -**required = [Read required names](access(access(catalog_data, "plan"), "required"))** and -**assets = [Read their GitHub size and digest records](access(catalog_data, "assets"))**. -1. `directory` == None - We **directory = "dist/release-" + version** for the release staging directory. -We **checked = [Start the verified artifact list](table.empty_list())**. -- [Download and verify each required artifact](for required as name) - We **asset = [Select its unmodified metadata](named(assets=`assets`, name=`name`))**. - - `payload` = - - | asset | directory | - |---|---| - | `asset` | `directory` | - - We **fetched = [Transfer exact GitHub bytes and validate digest and CRC](native.fetch(asset=`asset`, directory=`directory`, root=`root`))**. - 1. not access(`fetched`, "ok") - Return *fetched* with the completed earlier files retained. - We **verified = [Check the package's actual role and version](content(record=access(fetched, "value"), version=`version`))**. - 1. not access(`verified`, "ok") - Return *verified* before any publication step. - We **checked = [Append the checked evidence](table.append(list=`checked`, item=access(verified, "value")))**. -We **consistent = [Check source/native capabilities across the complete set](matrix(records=`checked`))**. -1. not access(`consistent`, "ok") - Return *consistent* before publication. -We **evidence = [Keep concise observed paths and hashes](summaries(records=`checked`, directory=`directory`))**. -Return *[The real verified local artifacts](result.ok(value=`evidence`))*. - -## status - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with CDN parity, version pointers and checked URLs | - -Use `version`, `mode`="full" and `root`="." to verify published extension -bytes. CLI mode has no CDN obligation and reports that explicitly. Other modes -require both the versioned and latest download for each of the three packs, plus -both VERSION pointers. Their SHA256 values must match the GitHub-provided digest -for the exact release. Missing digests remain a failure; the task does not infer -integrity from a filename, HTTP status or a previous version's pointer. -This operation is read-only but downloads the bytes to compute their hashes. -A pointer can be published before every edge cache refreshes; any mismatch keeps -complete=False and retains the URL evidence so a later query can verify it. - -We **catalog_result = [Read the same release's asset metadata](catalog(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`catalog_result`, "ok") - Return *catalog_result* with its failure intact. - -We **catalog_data = [Read the accepted catalog](access(catalog_result, "value"))** and -**checks = [Start public endpoint evidence](table.empty_list())** and **complete = True**. -1. `mode` != "cli" - We **names = [Read the three CDN deliverables](access(access(catalog_data, "plan"), "cdn"))** and - **assets = [Read the exact GitHub asset digests](access(catalog_data, "assets"))**. - - `prefixes` = - - | prefix | - |---| - | "v`version`" | - | latest | - - - [Verify versioned and latest publication independently](for prefixes as prefix) - - We **pointer_path = prefix + "/VERSION"** as the explicit public pointer. - - We **pointer = [Read the public version pointer](native.cdn(path=`pointer_path`))**. - 1. not access(`pointer`, "ok") - Return *pointer* with its service failure. - We **complete = [Keep a mismatched pointer incomplete](complete and access(access(pointer, "value"), "version") == version)**. - - [Compare every pack with its GitHub SHA256](for names as name) - We **asset = [Keep GitHub metadata as the source of truth](named(assets=`assets`, name=`name`))**. - - We **asset_path = prefix + "/" + name** as the exact public object. - - We **observed = [Hash the actual public download](native.cdn(path=`asset_path`))**. - 1. not access(`observed`, "ok") - Return *observed* with its failed public read. - We **digest = [Read the observed SHA256](access(access(observed, "value"), "sha256"))** and - **matches = [Require the same exact release bytes](table.get(map=`asset`, key="digest") == "sha256:" + digest)** and - **complete = complete and matches**. - - `evidence` = - - | path | sha256 | matches | - |---|---|---| - | "`prefix`/`name`" | `digest` | `matches` | - - We **checks = [Retain this endpoint's evidence](table.append(list=`checks`, item=`evidence`))**. - -We **needed = [Decide whether this mode publishes extension packs](mode != "cli")**. - -`state` = - -| complete | required | checks | -|---|---|---| -| `complete` | `needed` | `checks` | - -Return *[The measured CDN publication state](result.ok(value=`state`))*. - -## publish - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| directory | any | None | Verified staging directory; None uses dist/release-X.Y.Z | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result of verified R2 upload followed by public byte-parity checks | - -Use `version`, `mode`="full", `directory`=None and `root`="." only after the -user has instructed this release. CLI-only mode has no extension publication -step. The three local ZIPs must already exist, match GitHub metadata and pass -content checks before any R2 write begins. Their combined capability matrix -must also agree: source-declared plugins require both matching native libraries. -Individually valid archives cannot hide a missing runtime on one platform. Missing credentials produce an error -with the existing uploader command available in this handbook's recovery notes. -The maintained uploader writes all versioned/latest packs before VERSION, keeping -pointer updates after content. It does not delete older versions. After upload, -this function verifies public parity; an edge-cache delay is incomplete evidence, -not a reason to upload unrelated files from the whole dist directory. - -We **catalog_result = [Validate the intended release and all required filenames](catalog(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`catalog_result`, "ok") - Return *catalog_result* with its failure intact. - -1. `mode` == "cli" - Return *[Report that this mode has no CDN publication](status(version=`version`, mode=`mode`, root=`root`))*. -1. `directory` == None - We **directory = "dist/release-" + version** as the staging directory. -We **catalog_data = [Read the verified metadata catalog](access(catalog_result, "value"))** and -**names = [Read the exact three CDN packs](access(access(catalog_data, "plan"), "cdn"))** and -**assets = [Read their GitHub digests](access(catalog_data, "assets"))** and -**files = [Start the explicit upload path list](table.empty_list())** and -**records = [Retain the complete source and platform content evidence](table.empty_list())**. -- [Verify all local packs before touching R2](for names as name) - We **asset = [Choose the same release asset](named(assets=`assets`, name=`name`))** and - **path = directory + "/" + name**. - - `payload` = - - | asset | path | - |---|---| - | `asset` | `path` | - - We **verified = [Require local size, SHA256 and archive CRC parity](native.verify(asset=`asset`, path=`path`, root=`root`))**. - 1. not access(`verified`, "ok") - Return *verified* before any CDN write. - We **checked = [Require the expected contents and version](content(record=access(verified, "value"), version=`version`))**. - 1. not access(`checked`, "ok") - Return *checked* with the source or platform error. - We **records = [Retain the verified archive for capability matching](table.append(list=`records`, item=access(verified, "value")))** and - **sha256 = [Retain this file's checked native hash](access(access(verified, "value"), "sha256"))**. - - `file` = - - | path | name | sha256 | - |---|---|---| - | `path` | `name` | `sha256` | - - We **files = [Keep only the verified upload record](table.append(list=`files`, item=`file`))**. - -We **matched = [Require the source-declared plugins in both native platform packs](matrix(records=`records`))**. -1. not access(`matched`, "ok") - Return *matched* before publishing any pack or pointer. - -`upload` = - -| version | files | -|---|---| -| `version` | `files` | - -We **uploaded = [Upload only the three verified packs using private R2 credentials](native.upload(version=`version`, files=`files`, root=`root`))**. -1. not access(`uploaded`, "ok") - Return *uploaded* with its failure intact. - -Return *[Verify the public bytes after uploading](status(version=`version`, mode=`mode`, root=`root`))*. diff --git a/skills/marqdo-release/github.mq.md b/skills/marqdo-release/github.mq.md deleted file mode 100755 index e6c60d9..0000000 --- a/skills/marqdo-release/github.mq.md +++ /dev/null @@ -1,353 +0,0 @@ ---- -markup: occlusion -title: Observe and update GitHub release evidence -import: - bridge: ./_bridge.mq.md - model: ./model.mq.md - table: lib/table.mq.md - result: lib/result.mq.md - fs: lib/fs.mq.md ---- - -GitHub release tasks keep source identity and publication state explicit. Start -with status for an existing version; notes is a separate mutation that consumes -a reviewed bilingual file. The same release metadata feeds assets.download and -assets.status, so name, size and digest checks do not drift between channels. - -Every task returns Result.ok/value/error. Check that inner ok before consuming -value, then inspect complete for gates. A successful query may truthfully report -an incomplete release. plugin grants the native boundary OS/network -authority; credentials are resolved privately from the environment or existing -credential stores. They are never parameters, return values or journal bindings. - -Example, from the checkout root: - -```sh -marqdo call skills/marqdo-release/github.mq.md status 'version="2.6.0"' --effects plugin --fs-root . --json -``` - -The command is read-only. A future release uses the version the user actually -specified. A red EK gate, missing Linux build or wrong-commit green run keeps the -release incomplete even if a GitHub download page already exists. - -## request - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | API path scoped to /repos/cflmy/marqdo/ | -| method | text | "GET" | GET for observation; PATCH for notes; POST for explicit publication | -| data | any | None | JSON request body; credentials are never arguments | -| missing | bool | False | Whether GET 404 is represented as a successful None | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing service JSON or a transport error | - -Use `path`, `method`="GET", `data`=None, `missing`=False and `root`=".". -This function is the authenticated GitHub boundary used by the tasks below. -The proxy is tried before direct GitHub; GET and idempotent note PATCH may be -retried, while an uncertain POST is returned as failure. API failures retain a -code and service name without exposing tokens, headers or signed download URLs. -Reading requires plugin because the native engineering plugin owns HTTPS. - -`payload` = - -| path | method | data | missing | -|---|---|---|---| -| `path` | `method` | `data` | `missing` | - -Return *[Request GitHub JSON through the maintained transport](bridge.request(operation="github", payload=`payload`, root=`root`))*. - -## release - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing release metadata, or None when not published | - -Use `version`, `mode`="full" and `root`=".". -The mode selects vX.Y.Z or ext-vX.Y.Z through the same pure plan used for -packaging. A missing release is an observable state, not proof that a previous -publish command failed before creating anything. Callers can distinguish it -from a network or authentication failure by inspecting Result.ok first. -This query does not create a release and never invokes the old Windows-only -publication script, whose assumptions predate embedded standard libraries. - -We **planned = [Derive the correct release tag](model.plan(version=`version`, mode=`mode`))**. -1. not access(`planned`, "ok") - Return *planned* with its failure intact. - -We **plan_data = [Read the accepted tag contract](access(planned, "value"))** and -**path = "/repos/cflmy/marqdo/releases/tags/" + access(plan_data, "tag")**. -Return *[Observe this exact release without creating one](request(path=`path`, missing=True, root=`root`))*. - -## commit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| tag | text | required | Exact tag from the release plan | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with the commit SHA targeted by a lightweight or annotated tag | - -Use `tag` and `root`=".". Annotated tags point first to a tag object, -whereas lightweight tags already point to a commit. Follow that distinction -before matching a workflow run. Comparing a tag-object SHA with head_sha would -silently fail to find the correct green run. Only the single annotated object -created by this handbook is accepted; nested tag objects remain an error. -A missing tag is reported as a transport failure rather than guessed from main. - -We **reference = [Read the exact remote tag reference](request(path="/repos/cflmy/marqdo/git/ref/tags/" + tag, root=`root`))**. -1. not access(`reference`, "ok") - Return *reference* with its failure intact. - -We **object = [Read the tag target](access(access(reference, "value"), "object"))**. -1. access(`object`, "type") == "tag" - We **annotation = [Resolve the annotated tag object](request(path="/repos/cflmy/marqdo/git/tags/" + access(object, "sha"), root=`root`))**. - 1. not access(`annotation`, "ok") - Return *annotation* without substituting main. - We **object = [Read the annotated commit target](access(access(annotation, "value"), "object"))**. -1. access(`object`, "type") != "commit" - Return *[Reject an unexpected tag target](result.error(code="release.tag_target", message="tag must resolve to a commit", operation="github.commit"))*. -Return *[The immutable release commit](result.ok(value=access(object, "sha")))*. - -## select_run - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| runs | list | required | Workflow runs ordered newest first by the GitHub API | -| sha | text | required | Exact commit that this gate must cover | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Newest run for this commit, or None | - -Use `runs` and `sha` to select one observed gate attempt. The first matching -head_sha is the most recent attempt provided by the API; an older successful -attempt cannot mask a later failure for the same commit. Runs for other commits -are irrelevant even if their badges are green. No API access or waiting occurs -here, making this decision directly testable with recorded service responses. -If the bounded query contains no matching run, return None and keep the gate -incomplete. The caller may fetch again after CI starts. - -- [Inspect workflow runs in their returned order](for runs as run) - 1. access(`run`, "head_sha") == `sha` - Return *run* as the observed attempt for this source. - -Return *None* when this commit has no observed run. - -## gate - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| workflow | text | required | release.yml, extension-release.yml or executable-knowledge.yml | -| sha | text | required | Commit that the workflow must cover | -| required | list | required | Required job names, such as windows and linux | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with completion, observed run and required-job evidence | - -Use `workflow`, `sha`, `required` and `root`=".". Completion requires both a -successful run for the exact commit and every named job with conclusion success. -A skipped or missing Linux job cannot pass just because the Windows job created -a release. This query checks at most 100 recent runs, returns immediately for -queued/running CI, and does not rerun or cancel anything. Polling belongs to the -agent's bounded observation cycle, not an unbounded loop hidden in a tool. -Knowledge checks use the same rule, so uploaded assets never replace a green EK -gate. Missing evidence returns complete=False with the observed run retained. - -We **response = [Read recent attempts for one workflow](request(path="/repos/cflmy/marqdo/actions/workflows/" + workflow + "/runs?per_page=100", root=`root`))**. -1. not access(`response`, "ok") - Return *response* with its failure intact. - -We **run = [Choose the latest attempt for this commit](select_run(runs=access(access(response, "value"), "workflow_runs"), sha=`sha`))**. -We **complete = False** and **jobs = [Start an empty required-job evidence list](table.empty_list())**. -1. `run` != None - We **answer = [Read this attempt's actual jobs](request(path="/repos/cflmy/marqdo/actions/runs/" + access(run, "id") + "/jobs?per_page=100", root=`root`))**. - 1. not access(`answer`, "ok") - Return *answer* with its failed observation. - We **jobs = [Keep the observed jobs](access(access(answer, "value"), "jobs"))** and - **complete = [Require a successful completed run](access(run, "status") == "completed" and access(run, "conclusion") == "success")**. -- [Check that every required platform or knowledge job passed](for required as name) - We **matched = False** before examining this job name. - - [Match this job against observed evidence](for jobs as job) - 1. access(`job`, "name") == `name` and access(`job`, "conclusion") == "success" - We **matched = True** because the named job succeeded. - We **complete = complete and matched** to preserve every missing-job failure. - -`evidence` = - -| complete | sha | run | jobs | -|---|---|---|---| -| `complete` | `sha` | `run` | `jobs` | - -Return *[The observed gate and its evidence](result.ok(value=`evidence`))*. - -## status - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with exact-source Release and executable-knowledge gates | - -Use `version`, `mode`="full" and `root`="." to inspect an existing release. -The Release workflow is matched against the resolved release tag; executable -knowledge is matched against the current remote main tip. Both sources are -returned so a reviewer can see if main has advanced. Every mode requires both -Windows and Linux jobs on the tag commit. Independent packs use extension-release.yml; -full/cli use release.yml. Existing assets cannot replace missing build evidence. -A missing release or an unfinished gate leaves complete=False. This task does -not mutate GitHub, push local work, create tags, or change the requested version. -The returned service metadata is evidence for the next task, not a permission -to publish a different version or overwrite a release's existing files. - -We **published = [Inspect the exact version's release](release(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`published`, "ok") - Return *published* with its failure intact. - -We **planned = [Read the pure release contract](model.plan(version=`version`, mode=`mode`))**. -1. not access(`planned`, "ok") - Return *planned* with its failure intact. - -We **release_data = [Keep the published metadata or None](access(published, "value"))** and -**tag = [Read the planned tag](access(access(planned, "value"), "tag"))**. -We **tagged = [Resolve its actual source commit](commit(tag=`tag`, root=`root`))**. -1. not access(`tagged`, "ok") - Return *tagged* with its failure intact. - -We **main = [Observe the remote main tip](request(path="/repos/cflmy/marqdo/git/ref/heads/main", root=`root`))**. -1. not access(`main`, "ok") - Return *main* with its failure intact. - -We **main_sha = [Read main's commit SHA](access(access(access(main, "value"), "object"), "sha"))**. - -`knowledge_jobs` = - -| name | -|---| -| gate | - -We **knowledge = [Verify EK on the actual remote main commit](gate(workflow="executable-knowledge.yml", sha=`main_sha`, required=`knowledge_jobs`, root=`root`))**. -1. not access(`knowledge`, "ok") - Return *knowledge* with its failure intact. - -We **workflow = "release.yml"** for a CLI or full release. -1. `mode` == "ext" - We **workflow = "extension-release.yml"** for independent extension builds. - -`platform_jobs` = - -| name | -|---| -| windows | -| linux | - -We **platforms = [Require both platform builds for the tagged source](gate(workflow=`workflow`, sha=access(tagged, "value"), required=`platform_jobs`, root=`root`))**. -1. not access(`platforms`, "ok") - Return *platforms* with its failed gate observation. -We **release_gate = [Keep actual platform evidence](access(platforms, "value"))** and **release_complete = [Read the exact-tag completion decision](access(release_gate, "complete"))**. - -We **all_complete = [Require the published release and both source-specific gates](release_data != None and release_complete and access(access(knowledge, "value"), "complete"))**, -**release_sha = [Keep the resolved release commit](access(tagged, "value"))** and -**knowledge_state = [Keep the exact-main knowledge evidence](access(knowledge, "value"))** before forming the record. - -`status_data` = - -| complete | release | release_sha | main_sha | release_ci | knowledge_ci | -|---|---|---|---|---|---| -| `all_complete` | `release_data` | `release_sha` | `main_sha` | `release_gate` | `knowledge_state` | - -Return *[The release's observed gates and source identities](result.ok(value=`status_data`))*. - -## notes - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| path | text | required | Reviewed UTF-8 bilingual notes file under the filesystem root | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result of updating only the existing release body | - -Use `version`, `path`, `mode`="full" and `root`=".". This is an explicit -GitHub mutation and needs the user's release instruction; reading this handbook -or asking for status does not authorize it. The prepared notes must contain -Chinese and English highlights, the actual asset matrix, installation routes, -core-surface delta and validation limits. The author remains responsible for -those claims; this function uploads the reviewed file rather than inventing it. -Reading uses fs.read in addition to plugin. UTF-8 text and its intentional -newlines travel in a structured JSON body, never through shell quoting. - -We **published = [Locate the existing release to edit](release(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`published`, "ok") - Return *published* with its failure intact. - -We **release_data = [Read its metadata](access(published, "value"))**. -1. `release_data` == None - Return *[Do not invent a release when only editing notes](result.error(code="release.missing", message="release does not exist; wait for CI or attach an ext release", operation="github.notes"))*. -We **body = [Read the exact reviewed bilingual note file](fs.read_text(path=`path`))**. - -We **data = [Keep the reviewed body as one named API field](table.put(in=None, at="body", value=`body`))**. - -Return *[Publish the reviewed release body](request(path="/repos/cflmy/marqdo/releases/" + access(release_data, "id"), method="PATCH", data=`data`, root=`root`))*. - - -## create_ext - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable independent extension version | -| path | text | required | Reviewed bilingual notes committed with the release source | -| sha | text | required | Exact source commit expected from the authorized tag | -| root | text | "." | Checkout root matching the granted filesystem root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing newly created or already existing release metadata | - -Use `version`, `path`, `sha` and `root`="." only for authorized extension publication. This is an explicit GitHub mutation. First resolve ext-vX.Y.Z to its actual commit and require the caller's expected SHA. Read the committed note file through native filesystem operations before requesting creation. The file must describe this version's real changes and validation limits; the task does not synthesize release claims. - -An existing release is returned unchanged so a resumed upload cannot overwrite its notes or assets. A missing release is created once through the authenticated service boundary, with its exact existing tag and reviewed body. Uncertain POST completion is a failure, never an automatic replay; inspect the release before resuming. CI uses this task after packaging and then uploads with the existing gh tool without clobbering prior assets. - -We **planned = [Validate the independent extension version](model.plan(version=`version`, mode="ext"))**. -1. not access(`planned`, "ok") - Return *planned*. -We **tag = [Read the exact immutable extension tag](access(access(planned, "value"), "tag"))** and **target = [Resolve the actual remote tag commit](commit(tag=`tag`, root=`root`))**. -1. not access(`target`, "ok") - Return *target*. -1. access(`target`, "value") != `sha` - Return *[Refuse publication from a different source](result.error(code="release.source_mismatch", message="extension tag differs from expected commit", operation="create_ext"))*. -We **body = [Read the reviewed version-specific bilingual notes](fs.read_text(path=`path`))**. -1. `body` == "" - Return *[Require actual reviewed notes](result.error(code="release.notes_empty", message="extension notes must not be empty", operation="create_ext"))*. -We **existing = [Observe whether an earlier creation completed](release(version=`version`, mode="ext", root=`root`))**. -1. not access(`existing`, "ok") - Return *existing*. -1. access(`existing`, "value") != None - Return *existing*, preserving the existing release. - -`data` = - -| tag_name | name | target_commitish | body | draft | prerelease | -|---|---|---|---|---|---| -| `tag` | `tag` | `sha` | `body` | False | False | - -Return *[Create this exact tagged release once](request(path="/repos/cflmy/marqdo/releases", method="POST", data=`data`, root=`root`))*. diff --git a/skills/marqdo-release/index.mq.md b/skills/marqdo-release/index.mq.md deleted file mode 100755 index 033892e..0000000 --- a/skills/marqdo-release/index.mq.md +++ /dev/null @@ -1,220 +0,0 @@ ---- -markup: occlusion -title: Marqdo release as an executable handbook -import: - model: ./model.mq.md - local: ./local.mq.md - github: ./github.mq.md - assets: ./assets.mq.md - ubuntu: ./ubuntu.mq.md - table: lib/table.mq.md - result: lib/result.mq.md ---- - -这份入口替代需要智能体重新拼装命令的发版 SKILL。版本和 full/cli/ext 模式必须由用户选择;已有明确选择时沿用授权,不重复询问。读取本手册或检查旧版本不会授权再次发布。当前维护版本的真实只读验证可调用 status 或 verify,并传入 version="2.6.0"。 - -先调用 plan 查看版本对应的产物与步骤,再由 local.inspect 查看本地状态。local.bump 修订版本,作者用开发手册的原生文件工具撰写双语 CHANGELOG、发布说明与用户文档,local.docs 构建真实文档。需要 CLI 的模式先编译独立编辑器分支,再显式提交审核过的文件并推送 main;EK 在实际提交上变绿后才创建新的不可变标签。每一步保留真实 Result,不通过资产存在来掩盖失败。 - -多文件工程按职责分开:model 是纯产物契约;local 是本地元数据、Git 与编辑器任务;github 是提交身份及 CI 证据;assets 与 asset_io 是同字节下载、内容检查和 R2 发布;ubuntu 与 package 是 noble 源码构建及 apt 验证。标准库的文件读写、JSON/TOML、哈希、网络、日期和表格负责组合,工程插件仅承担进程、认证和压缩格式边界。开发流程不需要 Python。独立拓展包在 packs.mq.md 中通过原生文件能力暂存与检查,并外联既有 ZIP 工具;ext-v 标签触发 extension-release.yml,两个平台均使用 packs.ci 与 packs.attach_ci 完成构建、精确来源检查、创建 Release 和不覆盖已有资产的上传。创建标签前须提交 doc/releases/ext-X.Y.Z.md 双语说明。 - -发布必须保留以下约束:main 不跟踪 vscode-extension 源码;标签不可覆盖;不得强推或绕过钩子;full 必须具备 Windows 和 Linux 产物。拓展包同时发布到 GitHub 和 R2,所有 ZIP 先于 VERSION 指针上传。full/cli 还需 Ubuntu PPA 源码上传、构建和 apt 发布证据。Release 与 EK 都应在正确来源提交上成功。双语说明要写实际核心表面变化及验证限制,不能只用模板宣称兼容。 - -凭据留在原有私密存储,不作为调用参数、源码或会话绑定。网络失败先走配置代理并有界重试,再直连;仍失败时保留本地证据,使用明确配置的外联传输,不能假装完成。sudo、GPG 或 dput 若需要人工输入,报告失败阶段及具体的 marqdo call 恢复命令。gh-pages 部署需要另外的用户指令。 - -命令形式是 marqdo call skills/marqdo-release/index.mq.md plan 'version="2.6.0"' --json。源码仓库开发时使用已构建的 target/debug/marqdo;先按开发入口 prepare_engineering 准备插件。status 和 verify 都使用 plugin,fs.write,network.read,environment.read,用于本地暂存和公开下载的校验;preflight 只需 plugin,fs.read,plan 不需要效应授权。自动化串接可加 --require-ok:函数返回失败 Result 时退出码非零,并保留真实返回值。所有命令都从仓库根目录传 --fs-root .。 - -## plan - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | -| mode | text | "full" | full, cli or ext | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with exact deliverable names and task routing | - -Use `version` and `mode`="full" after the user's version decision. -This pure entry derives filenames and publication obligations; it grants no -effect and writes no resource. Full has ten GitHub deliverables and both native -platforms, cli keeps the independent pack version, and ext has three packs on -both GitHub and R2. Unknown modes and malformed versions fail before IO. - -Follow the returned task routing to the actual callable files, whose headings -specify their inputs, outputs and failures. The routing is not a shell program -for the model to reconstruct. Inspecting the plan for an existing version is -safe and does not authorize a replacement release or a new immutable tag. - -Return *[Derive the confirmed release contract](model.plan(version=`version`, mode=`mode`))*. - -## preflight - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | -| mode | text | "full" | full, cli or ext | -| root | text | "." | Checkout/artifact root matching --fs-root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with ready, plan and actual local checkout facts | - -Use `version`, `mode`="full" and `root`="." before preparing a -release. This reads actual Git state and native version files; it does not fetch, -reset, stage, sign or publish. A clean main checkout without tracked editor -sources and without the selected local tag is ready for preparation. Existing -tags require inspection of their release state rather than replacement. - -A successful Result may contain ready=False. That is a real observation, not -permission to discard dirty files or overwrite refs. During authorized release -preparation, intentional edits remain visible until the explicit commit task. -The later tag task checks matching versions, remote main identity and EK again, -so preflight cannot become stale authorization. Call with plugin,fs.read and a -filesystem root that identifies the same checkout as the plugin's root. - -We **planned = [Validate the requested release contract](model.plan(version=`version`, mode=`mode`))**. -1. not access(`planned`, "ok") - Return *planned*. -We **observed = [Read the real checkout without changing it](local.inspect(root=`root`))**. -1. not access(`observed`, "ok") - Return *observed*. -We **plan_data = [Keep the pure release plan](access(planned, "value"))** and **state = [Keep the actual Git and version facts](access(observed, "value"))**. -We **exists = [Preserve any existing immutable tag](table.contains(list=access(state, "tags"), item=access(plan_data, "tag")))** and -**ready = access(state, "branch") == "main" and access(state, "changes") == "" and access(state, "extension_on_main") == "" and not exists**. - -`inspection` = - -| ready | plan | checkout | -|---|---|---| -| `ready` | `plan_data` | `state` | - -Return *[The preparation decision with its evidence](result.ok(value=`inspection`))*. - -## status - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | -| mode | text | "full" | full, cli or ext | -| root | text | "." | Checkout/artifact root matching --fs-root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with source-specific GitHub CI, CDN parity and Ubuntu state | - -Use `version`, `mode`="full" and `root`="." for an existing release. -This entry independently checks GitHub publication and its exact source commits, -the versioned and latest CDN bytes when packs ship, and Ubuntu publication when -the CLI ships. It creates no tag, release, upload or apt mutation. Temporary -download files are owned and cleaned by the native CDN task. - -The result keeps each component's evidence and requires all applicable components -to complete. A missing or red gate, different digest, pending build or stale apt -index remains incomplete. Network failures are failed Results, not fabricated -absence. Call with plugin,fs.write,network.read,environment.read: local writes -are only bounded verification staging. An ext-only release skips Ubuntu; a -cli-only release skips CDN. Existing GitHub assets alone never prove completion. - -We **source = [Observe publication and CI on the actual source identities](github.status(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`source`, "ok") - Return *source*. -We **cdn = [Verify published pack hashes and VERSION pointers](assets.status(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`cdn`, "ok") - Return *cdn*. -We **ppa = None** and **ppa_complete = True** for an extension-only release. -1. `mode` != "ext" - We **observed = [Check source publication, builds and the actual apt index](ubuntu.status(version=`version`))**. - 1. not access(`observed`, "ok") - Return *observed*. - We **ppa = [Retain the real Ubuntu evidence](access(observed, "value"))** and **ppa_complete = [Read its independent completion state](access(ppa, "complete"))**. -We **github_state = [Keep GitHub evidence](access(source, "value"))** and **cdn_state = [Keep CDN evidence](access(cdn, "value"))** and -**complete = access(github_state, "complete") and access(cdn_state, "complete") and ppa_complete**. - -`state` = - -| complete | github | cdn | ubuntu | -|---|---|---|---| -| `complete` | `github_state` | `cdn_state` | `ppa` | - -Return *[The independently measured release state](result.ok(value=`state`))*. - -## verify - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z; inspection never chooses another version | -| mode | text | "full" | full, cli or ext | -| root | text | "." | Checkout/artifact root matching --fs-root | -| directory | any | None | Staging directory; None means dist/release-X.Y.Z | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with all verified local artifacts and published completion evidence | - -Use `version`, `mode`="full", `root`="." and `directory`=None to -verify an existing release from its actual bytes. First download or reuse every -required GitHub artifact, check size and digest, inspect archive paths and CRCs, -and verify each package's role and version. Then status checks independent -publication channels. Existing valid local files may be reused after rechecking. - -This is verification, not publication. It needs plugin,fs.write,network.read, -environment.read and can consume network time for all platform packs. Failed -checks preserve their source error and completed local files for diagnosis; -none triggers a re-upload. Full completion includes Linux and Windows, green -source-specific CI, matching CDN copies and Ubuntu's actual apt index. Keep the -returned hashes as release evidence. A later release still needs its own user -version decision and source review. - -We **downloaded = [Validate all required GitHub asset bytes and package contents](assets.download(version=`version`, mode=`mode`, directory=`directory`, root=`root`))**. -1. not access(`downloaded`, "ok") - Return *downloaded*. -We **observed = [Verify all applicable published channels](status(version=`version`, mode=`mode`, root=`root`))**. -1. not access(`observed`, "ok") - Return *observed*. -We **artifacts = [Retain exact local hash evidence](access(downloaded, "value"))** and **publication = [Retain independent remote evidence](access(observed, "value"))** and **complete = [Read the real completion decision](access(publication, "complete"))**. - -`evidence` = - -| complete | artifacts | publication | -|---|---|---| -| `complete` | `artifacts` | `publication` | - -Return *[The verified bytes and actual publication state](result.ok(value=`evidence`))*. - - -## finish - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z | -| mode | text | "full" | full, cli or ext | -| root | text | "." | Checkout/artifact root matching --fs-root | -| directory | any | None | Local artifact staging directory | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result succeeding only when all verified release obligations are complete | - -Use `version`, `mode`="full", `root`="." and `directory`=None at the -final verification step of an authorized release. This runs verify on actual -artifact bytes and independent published channels. It does not create another -release, overwrite assets or repeat an upload. - -Unlike an observational status query, this completion gate returns a failed -Result when any applicable obligation is pending. The failure retains its -evidence record so a reviewer can identify the unfinished channel. Use ---require-ok when this task is the last step of external automation; a pending -release then produces a nonzero exit status. It needs the same native staging, -network, environment and plugin grants as verify. A service failure retains its -original source diagnostic. Only this successful final gate permits reporting -the chosen release complete; changing the version still requires the user's -explicit decision. - -We **observed = [Verify actual artifacts and every applicable publication channel](verify(version=`version`, mode=`mode`, root=`root`, directory=`directory`))**. -1. not access(`observed`, "ok") - Return *observed* with its original failure. -We **evidence = [Retain the complete verification record](access(observed, "value"))**. -1. not access(`evidence`, "complete") - We **failure = [Keep pending publication distinct from successful completion](result.error(code="release.incomplete", message="inspect evidence for the unfinished release obligation", operation="finish"))**. - Return *[Retain evidence with the failed completion gate](table.put(in=`failure`, at="evidence", value=`evidence`))*. -Return *observed* when every required obligation is verified. diff --git a/skills/marqdo-release/local.mq.md b/skills/marqdo-release/local.mq.md deleted file mode 100755 index 250b528..0000000 --- a/skills/marqdo-release/local.mq.md +++ /dev/null @@ -1,883 +0,0 @@ ---- -markup: occlusion -title: Prepare and publish a reviewed source release -import: - bridge: ./_bridge.mq.md - model: ./model.mq.md - github: ./github.mq.md - fs: lib/fs.mq.md - table: lib/table.mq.md - result: lib/result.mq.md - text: lib/text.mq.md - toml: lib/toml.mq.md - sys: lib/sys.mq.md - datetime: lib/datetime.mq.md - re: lib/re.mq.md ---- - -Local release tasks replace repeated command-writing with explicit callable -operations. Inspect first, use bump for version metadata, author and review the -bilingual release text, build docs, compile the editor branch separately, commit -reviewed paths, push main, wait for EK, then create the annotated tag. - -These are separate tasks because their results are reviewable artifacts and -because waiting for CI is different from creating a new reference. Existing -user authorization carries through the chosen release; none of the tasks asks -for a second version choice. A new release version or a replacement tag needs -its own user decision. No task force-pushes or bypasses hooks. - -Every process operation returns Result.ok/value/error. A failed compile, Git -hook or network request stops the dependent task. Multi-file metadata edits are -not a transaction: inspect any partial changes before retrying. No task cleans -or stages unrelated work, commits editor sources on main, or deploys gh-pages. - -```sh -marqdo call skills/marqdo-release/local.mq.md inspect --effects plugin,fs.read --fs-root . --json -``` - -For mutation, use the chosen version and the effect grant described on that -heading. bump needs fs.write and plugin; the rest of the command tasks -use plugin, whose children retain normal OS authority. Do not interpret ---fs-root as a sandbox for external tools. GPG or sudo interaction is reported -at the Ubuntu boundary rather than hidden behind an unconditional success. - -## inspect - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with Git identity and versions read by native filesystem tools | - -Use `root`="." to inspect a checkout without changing it. Git supplies branch, -HEAD, dirty paths and tags through the engineering boundary. Cargo manifests -and ext/VERSION are read with lib/fs and decoded with lib/toml and lib/text. -The version facts are therefore visible in this source rather than hidden in -an external file-reading script. No credential contents are returned. - -The plugin root and --fs-root must identify the same directory; this check catches -a caller accidentally combining one checkout's Git state with another checkout's -version files. Local tags are evidence only; remote references are checked before -tagging. This operation requires plugin and fs.read but performs no publication. - -We **payload = [Start an empty Git metadata request](table.empty_map())** and -**observed = [Read Git's actual repository state](bridge.request(operation="git_inspect", payload=`payload`, root=`root`))**. -1. not access(`observed`, "ok") - Return *observed* with its source error. -We **state = [Read the observed Git metadata](access(observed, "value"))** and -**cwd = [Read the native filesystem working root](sys.cwd())**. -1. access(`state`, "root") != `cwd` - Return *[Refuse inconsistent process and filesystem roots](result.error(code="release.root_mismatch", message="root must match --fs-root", operation="local.inspect"))*. - -We **cli = [Read and decode the actual interpreter manifest](toml.parse(text=fs.read_text(path="Cargo.toml")))** and -**wasm = [Read and decode the actual WASM manifest](toml.parse(text=fs.read_text(path="crates/marqdo-wasm/Cargo.toml")))** and -**cli_version = [Read the interpreter package version](access(access(cli, "package"), "version"))** and -**wasm_version = [Read the WASM package version](access(access(wasm, "package"), "version"))** and -**ext_version = [Read the independent pack version](text.str_trim(s=fs.read_text(path="ext/VERSION")))**. - -`versions` = - -| cli_version | wasm_version | ext_version | -|---|---|---| -| `cli_version` | `wasm_version` | `ext_version` | - -We **combined = [Combine native file facts with Git identity](table.merge(a=`state`, b=`versions`))**. -Return *[The actual checkout facts](result.ok(value=`combined`))*. - -## command - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| argv | list | required | Exact command and argument vector; never shell source | -| cwd | text | "." | Working directory inside the checkout | -| timeout | number | 120 | Maximum child duration in seconds | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with checked exit status and bounded stdout/stderr | - -Use `argv`, `cwd`=".", `timeout`=120 and `root`="." for maintained commands. -This transport keeps arguments separate even when filenames contain spaces, -quotes, dollar signs or backticks. It refuses inline shell programs, forced Git -updates and hook bypass. Git credentials are attached privately when needed; -they never become parameters or command text. Nonzero exit and timeout remain -failed Results, so a later stage cannot silently continue after a failed build. -A child inherits the caller's OS capabilities. This helper does not claim that ---fs-root makes arbitrary subprocesses safe or confines their own file access. - -`payload` = - -| argv | cwd | timeout | -|---|---|---| -| `argv` | `cwd` | `timeout` | - -Return *[Execute this exact maintained argument vector](bridge.request(operation="command", payload=`payload`, root=`root`))*. - -## replace_version - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| path | text | required | Cargo manifest relative to the granted filesystem root | -| old | text | required | Observed previous package version | -| version | text | required | Stable X.Y.Z explicitly chosen by the user | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Number of replaced manifest version fields | - -Use `path`, `old` and `version` only after inspecting the version files. -The exact package-version line is replaced once. Other dependency versions and -surrounding documentation remain intact. The file helper refuses a missing or -ambiguous match, exposing drift instead of rewriting a whole manifest from a -model-generated template. Calling with the same version is a no-op. -This helper writes one file and is not a multi-file transaction. The calling -bump operation records which stage failed so the author can inspect any partial -changes before retrying. It needs fs.write under the supplied filesystem root. - -1. `old` == `version` - Return *0* because this manifest already has the requested version. -We **find = "version = \"" + old + "\""** and -**replacement = "version = \"" + version + "\""** as exact manifest lines. -Return *[Replace only the observed package version line](fs.text_patch(path=`path`, find=`find`, replace=`replacement`))*. - -## bump - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with updated version metadata and Cargo check evidence | - -Use `version`, `mode`="full" and `root`="." after the user chooses the release. -Full updates CLI, WASM and ext/VERSION; cli updates the two Cargo packages; ext -updates only ext/VERSION. Cargo check updates the lockfile for CLI/full and the -Debian stanza preserves the existing maintainer while dating the entry in -Asia/Shanghai. No tag, commit, remote push, R2 upload or PPA upload happens here. -The author still writes the bilingual CHANGELOG, README/tutorial changes and -release notes: version replacement cannot decide or verify their factual claims. -Run docs and the relevant regressions after those authored changes are reviewed. -The native filesystem calls need fs.write; Cargo and packaging transport need -plugin. A failure leaves intentional local changes available for review, -rather than pretending the multi-file edit was atomic or resetting other work. - -We **planned = [Validate the user-chosen version and mode](model.plan(version=`version`, mode=`mode`))**. -1. not access(`planned`, "ok") - Return *planned* with its failure intact. - -We **observed = [Read current versions before changing any](inspect(root=`root`))**. -1. not access(`observed`, "ok") - Return *observed* with its failure intact. - -We **state = [Keep the observed version metadata](access(observed, "value"))**. -1. access(`state`, "branch") != "main" or access(`state`, "extension_on_main") != "" - Return *[Require the main checkout without tracked editor sources](result.error(code="release.branch", message="bump runs on main; editor sources belong only on vscode-extension", operation="local.bump"))*. -1. `mode` != "ext" - We **cli_edit = [Update the interpreter package version](replace_version(path="Cargo.toml", old=access(state, "cli_version"), version=`version`))** and - **wasm_edit = [Update the WASM package version](replace_version(path="crates/marqdo-wasm/Cargo.toml", old=access(state, "wasm_version"), version=`version`))**. - - `cargo_args` = - - | argument | - |---| - | "cargo" | - | "check" | - | "--offline" | - - We **checked = [Update Cargo.lock and verify the new package metadata](command(argv=`cargo_args`, root=`root`, timeout=600))**. - 1. not access(`checked`, "ok") - Return *checked* with the local edits left for inspection. - We **packaging = [Add the dated Debian stanza through native file IO](debian(version=`version`))**. - 1. not access(`packaging`, "ok") - Return *packaging* before committing any metadata. -1. `mode` != "cli" - We **ext_edit = [Write the independent extension pack version](fs.write_text(path="ext/VERSION", text=`version` + "\n"))**. -Return *[Read back all resulting metadata and dirty paths](inspect(root=`root`))*. - -## docs - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result from rebuilding the actual public documentation | - -Use `root`="." after authoring public sources and release-facing documentation. -This command runs the checked-in documentation builder, which uses Marqdo View -on the real pages instead of copying stale generated HTML. Generated files stay -ignored and are packaged by CI. Library-only import helpers have no main entry; -their expected page execution status does not authorize inventing a main. -A failed builder is returned as an error and is not treated as proof that docs -were refreshed. This task does not deploy gh-pages; deployment is a separate -user request, even during a full release. - -`argv` = - -| argument | -|---| -| "bash" | -| "scripts/build-public.sh" | - -Return *[Regenerate documentation from the authored Marqdo sources](command(argv=`argv`, root=`root`, timeout=900))*. - -## review_index - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| paths | list | required | Exact reviewed repository-relative file paths | -| cwd | text | "." | Git checkout within root; editor stage or main | -| root | text | "." | Checkout root matching --fs-root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result whose value lists the already staged paths | - -Use `paths`, `cwd`="." and `root`="." before staging or running a -version-changing tool. This inspection reads the actual Git index with explicit -unquoted path output; UTF-8 names and spaces remain ordinary path data. -Every existing staged path must appear in the supplied reviewed file list. -A refusal leaves both the index and working tree unchanged. - -The release source and editor branch share this inspection so a pre-staged -unrelated edit cannot become part of either version commit. It does not inspect -unstaged file content, authorize a commit or reset another task's index. -Newline-bearing filenames are outside this release handbook's path contract. -Requires plugin for Git; there is no network request or filesystem write. - -`argv` = - -| argument | -|---| -| "git" | -| "-c" | -| "core.quotepath=false" | -| "diff" | -| "--cached" | -| "--name-only" | - -We **observed = [Read the current staged file names before any change](command(argv=`argv`, cwd=`cwd`, root=`root`))**. -1. not access(`observed`, "ok") - Return *observed* with its Git diagnostic. -We **staged = [Split the observed index into individual file names](text.str_split(s=access(access(observed, "value"), "stdout"), sep="\n"))**. -- [Require each existing index path to be explicitly reviewed](for staged as path) - 1. `path` != "" and not [This staged path belongs to the review](table.contains(list=`paths`, item=`path`)) - Return *[Preserve unrelated staged work](result.error(code="release.staged_unrelated", message=`path`, operation="review_index"))*. -Return *[The inspected index paths](result.ok(value=`staged`))*. - -## commit - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| paths | list | required | Reviewed explicit paths; never use a blanket git add . | -| message | text | required | Commit message describing the actual reviewed release | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with commit output; no remote mutation | - -Use `paths`, `message` and `root`="." after reviewing authored changes and -running the relevant checks. This function stages only the supplied paths, -checks the staged patch for whitespace errors, and creates an ordinary commit -with hooks enabled. It does not infer that every dirty file belongs to a release. -Editor sources remain on their own branch: do not include vscode-extension in -these paths. The current branch must be main. Only individual reviewed files are accepted; -a directory path is refused before staging. Deleted files can still be reviewed -by their exact repository path. Retries preserve already-staged deletions: Git no longer knows those missing paths in its index, so they must not be handed to git add again. Existing staged paths must all -appear in that same explicit file list before staging begins, so another task's -index work cannot be swept into the release commit. Broad pathspecs, parent -traversal and nested editor paths are rejected. These checks preserve the index -on refusal; a later hook failure keeps intentional staging available for review. The author can inspect staged changes before -this explicit commit task; a hook failure stays visible and is never bypassed. - -`branch_args` = - -| argument | -|---| -| "git" | -| "branch" | -| "--show-current" | - -We **observed = [Require the source branch before touching its index](command(argv=`branch_args`, root=`root`))**. -1. not access(`observed`, "ok") - Return *observed* with the command diagnostic. -We **branch = [Read the actual source branch](text.str_trim(s=access(access(observed, "value"), "stdout")))**. -1. `branch` != "main" - Return *[Keep release source commits on main](result.error(code="release.commit_branch", message="source commit requires main", operation="local.commit"))*. - -1. len(`paths`) == 0 or [Editor sources are not main-branch release files](table.contains(list=`paths`, item="vscode-extension")) - Return *[Require explicit reviewed main-branch paths](result.error(code="release.commit_paths", message="provide reviewed paths and exclude vscode-extension", operation="local.commit"))*. - -- [Validate individual reviewed repository paths](for paths as path) - 1. `path` == "." or `path` == "" or [This path is broad, outside the checkout or editor-only](re.is_match(text=`path`, pattern="(^/|(^|/)\\.\\.(/|$)|(^|/)vscode-extension(/|$)|[:*?])")) - Return *[Require concrete main-branch file paths](result.error(code="release.commit_paths", message=`path`, operation="local.commit"))*. - 1. [Inspect an existing reviewed path without opening it](fs.exists(path=`path`)) - We **metadata = [Require a file rather than a directory pathspec](fs.stat(path=`path`))**. - 1. access(`metadata`, "is_dir") - Return *[Do not stage an entire reviewed directory](result.error(code="release.commit_paths", message=`path`, operation="local.commit"))*. - -We **reviewed = [Protect all previously staged work](review_index(paths=`paths`, root=`root`))**. -1. not access(`reviewed`, "ok") - Return *reviewed* before changing the index. - -`deleted_args` = - -| argument | -|---| -| "git" | -| "-c" | -| "core.quotepath=false" | -| "diff" | -| "--cached" | -| "--name-only" | -| "--diff-filter=D" | -| "--no-renames" | - -We **removed = [Read deletions already retained by the reviewed index](command(argv=`deleted_args`, root=`root`))**. -1. not access(`removed`, "ok") - Return *removed* with the original index diagnostic. -We **deleted = [Keep exact already-staged deletion paths](text.str_split(s=access(access(removed, "value"), "stdout"), sep="\n"))** and **stage_paths = [Start only files requiring staging](table.empty_list())**. -- [Preserve reviewed deletions when retrying a failed commit](for paths as path) - 1. fs.exists(path=`path`) or not table.contains(list=`deleted`, item=`path`) - We **stage_paths = [Stage existing files and unstaged removals](table.append(list=`stage_paths`, item=`path`))**. -1. len(`stage_paths`) > 0 - - `prefix` = - - | argument | - |---| - | "git" | - | "add" | - | -- | - - We **argv = [Append only paths still requiring staging](table.concat(a=`prefix`, b=`stage_paths`))** and - **staged = [Stage those exact reviewed paths](command(argv=`argv`, root=`root`))**. - 1. not access(`staged`, "ok") - Return *staged* with its failure intact. - -`check_args` = - -| argument | -|---| -| "git" | -| "diff" | -| "--cached" | -| "--check" | - -We **checked = [Check the exact staged patch](command(argv=`check_args`, root=`root`))**. -1. not access(`checked`, "ok") - Return *checked* with its failure intact. - -`commit_args` = - -| argument | -|---| -| "git" | -| "commit" | -| "-m" | -| `message` | - -Return *[Create an ordinary commit with hooks](command(argv=`commit_args`, root=`root`))*. - -## push - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| refspec | text | "HEAD:refs/heads/main" | main, vscode-extension or a same-name stable tag; force syntax is rejected | -| cwd | text | "." | Checkout directory inside root; editor staging may override it | -| root | text | "." | Checkout root matching --fs-root; relative to the granted runtime cwd | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result confirming the exact expected remote ref SHA | - -Use `refspec`="HEAD:refs/heads/main", `cwd`="." and `root`="." only for -the authorized source publication. The argument vector and retry order are -visible here: proxy first, then direct GitHub, with two attempts per route. -After each response, including an uncertain timeout, read the remote ref before -deciding to retry. Only its exact expected SHA proves that this push arrived. - -A branch must match its destination; stable tags can only push to the same name. -The native boundary also rejects force and hook bypass. A test-only configured -remote can replace the network routes in an isolated fixture. Production -credentials remain private inside the engineering Git boundary. This task never -changes origin and never treats stale remote state as success. If both network -routes fail, retain local refs and use an explicitly configured SSH/HK transport -rather than force-pushing or silently skipping publication. - -MARQDO_RELEASE_GIT_REMOTE is an explicit transport override for an already -reviewed SSH/HK route or an isolated fixture. The task does not invent that -route, rewrite origin or generate a jump program. The same branch checks and -exact-SHA readback apply to an override; transport success alone is insufficient. -Configure SSH identities in the existing OS store, never in tool arguments. - -We **valid = [Accept only reviewed release refspec shapes](re.is_match(text=`refspec`, pattern="^(HEAD:refs/heads/(main|vscode-extension)|refs/tags/(ext-)?v[0-9]+\\.[0-9]+\\.[0-9]+:refs/tags/(ext-)?v[0-9]+\\.[0-9]+\\.[0-9]+)$"))**. -1. not `valid` - Return *[Reject arbitrary or forced ref updates](result.error(code="release.refspec", message="unsupported release refspec", operation="local.push"))*. -We **parts = [Separate the source and destination ref](text.str_split(s=`refspec`, sep=":"))** and -**source = [Read its local source](access(parts, 1))** and **destination = [Read its remote target](access(parts, 2))**. -1. `source` != "HEAD" and `source` != `destination` - Return *[Keep tag names immutable across push](result.error(code="release.refspec", message="tag destination must equal its source", operation="local.push"))*. - -`rev_args` = - -| argument | -|---| -| "git" | -| "rev-parse" | -| `source` | - -1. `source` == "HEAD" - `branch_args` = - - | argument | - |---| - | "git" | - | "branch" | - | "--show-current" | - - We **observed = [Read the current source branch before any push](command(argv=`branch_args`, cwd=`cwd`, root=`root`))**. - 1. not access(`observed`, "ok") - Return *observed*. - We **branch = [Keep the actual source branch](text.str_trim(s=access(access(observed, "value"), "stdout")))**. - 1. `destination` != "refs/heads/" + `branch` - Return *[Refuse a different branch destination](result.error(code="release.push_branch", message="source branch must match destination", operation="local.push"))*. - -We **local = [Resolve the exact local ref before transport](command(argv=`rev_args`, cwd=`cwd`, root=`root`))**. -1. not access(`local`, "ok") - Return *local* before any remote mutation. -We **expected = [Keep the expected local SHA](text.str_trim(s=access(access(local, "value"), "stdout")))** and -**override = [Read an explicitly configured fixture remote](sys.env_get(name="MARQDO_RELEASE_GIT_REMOTE"))**. - -`remotes` = - -| remote | -|---| -| "https://proxy.cflmy.top/github.com/cflmy/marqdo.git" | -| "https://github.com/cflmy/marqdo.git" | - -1. `override` != None - - `remotes` = - - | remote | - |---| - | `override` | - -`attempts` = - -| attempt | -|---| -| 1 | -| 2 | - -- [Try each configured route without changing origin](for remotes as remote) - - [Bound retries and verify after uncertain responses](for attempts as attempt) - - `push_args` = - - | argument | - |---| - | "git" | - | "push" | - | `remote` | - | `refspec` | - - We **pushed = [Send the explicit ref without force](command(argv=`push_args`, cwd=`cwd`, root=`root`, timeout=180))**. - - `read_args` = - - | argument | - |---| - | "git" | - | "ls-remote" | - | `remote` | - | `destination` | - - We **read = [Observe whether that exact ref arrived](command(argv=`read_args`, cwd=`cwd`, root=`root`, timeout=90))**. - 1. access(`read`, "ok") - We **observed = [Read the server's ref response](text.str_trim(s=access(access(read, "value"), "stdout")))** and - **fields = [Separate the SHA from the ref name](text.str_split(s=`observed`, sep="\t"))**. - 1. access(`fields`, 1) == `expected` - - `verified` = - - | ref | sha | verified | - |---|---|---| - | `destination` | `expected` | True | - - Return *[The confirmed remote source identity](result.ok(value=`verified`))*. -Return *[Preserve an unconfirmed network outcome](result.error(code="release.push_unconfirmed", message="proxy retries and direct route did not confirm the expected SHA; retain local refs and inspect the configured transport", operation="local.push"))*. - -## tag - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| mode | text | "full" | full, cli or ext; determines the deliverable contract | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result confirming a new annotated tag on the checked remote commit | - -Use `version`, `mode`="full" and `root`="." only for the already authorized -release. Main must be clean, contain no tracked editor source, and carry the -mode's matching versions. A local existing tag is rejected. The remote main SHA -must equal local HEAD, and its latest EK gate must be green before this task -creates anything. These conditions preserve the release skill's hard rules. -The remote source identity is retained as evidence for CI matching. -The tag is annotated and then pushed through the same bounded proxy transport. -If pushing fails after local creation, call push with that exact tag refspec; -do not rerun tag, delete the tag or move it to a new commit. An ext tag triggers -extension-release.yml, which runs packs.ci and packs.attach_ci on Windows and Linux. -Commit reviewed bilingual doc/releases/ext-X.Y.Z.md notes before creating that tag. -The notes travel in the tagged checkout, so CI reads the reviewed content rather -than reconstructing publication text. Existence and nonempty checks are only a -preflight: the author must still verify the actual changes, asset scope and test -limits before committing. A clean checkout ensures the note file is included in -the source decision; the later CI creation task verifies the same commit again. -This function creates an immutable release reference. Its invocation needs the -release authorization; merely reading this file or running inspect is read-only. - -We **planned = [Validate the authorized version and release mode](model.plan(version=`version`, mode=`mode`))**. -1. not access(`planned`, "ok") - Return *planned* with its failure intact. - -1. `mode` == "ext" - We **notes_path = "doc/releases/ext-" + version + ".md"**. - 1. not [The independent pack's reviewed notes exist](fs.exists(path=`notes_path`)) - Return *[Require committed version-specific release notes](result.error(code="release.notes_missing", message=`notes_path`, operation="local.tag"))*. - 1. [The independent pack's note file is empty](fs.read_text(path=`notes_path`) == "") - Return *[Require actual bilingual release content](result.error(code="release.notes_empty", message=`notes_path`, operation="local.tag"))*. - -We **observed = [Require an actual clean main checkout](inspect(root=`root`))**. -1. not access(`observed`, "ok") - Return *observed* with its failure intact. - -We **state = [Read observed branch and version metadata](access(observed, "value"))** and -**tag_name = [Read the mode's immutable tag name](access(access(planned, "value"), "tag"))**. -1. access(`state`, "branch") != "main" or access(`state`, "changes") != "" or access(`state`, "extension_on_main") != "" - Return *[Reject a dirty or wrong-branch release](result.error(code="release.dirty", message="tagging requires clean main without tracked editor sources", operation="local.tag"))*. -1. [This tag already exists locally](table.contains(list=access(`state`, "tags"), item=`tag_name`)) - Return *[Preserve the existing immutable tag](result.error(code="release.tag_exists", message="existing tag requires inspection; never replace it", operation="local.tag"))*. -1. `mode` != "ext" and (access(`state`, "cli_version") != `version` or access(`state`, "wasm_version") != `version`) - Return *[Reject mismatched CLI metadata](result.error(code="release.versions", message="CLI and WASM must match the chosen version", operation="local.tag"))*. -1. `mode` != "cli" and access(`state`, "ext_version") != `version` - Return *[Reject a mismatched extension pack](result.error(code="release.versions", message="ext/VERSION must match the chosen pack version", operation="local.tag"))*. -We **remote = [Read the current remote main reference](github.request(path="/repos/cflmy/marqdo/git/ref/heads/main", root=`root`))**. -1. not access(`remote`, "ok") - Return *remote* with its failure intact. - -We **sha = [Read the remote source identity](access(access(access(remote, "value"), "object"), "sha"))**. -1. `sha` != access(`state`, "commit") - Return *[Require the reviewed commit to be pushed first](result.error(code="release.unpushed", message="remote main differs from local HEAD", operation="local.tag"))*. - -`required` = - -| name | -|---| -| gate | - -We **knowledge = [Require green EK before publishing a tag](github.gate(workflow="executable-knowledge.yml", sha=`sha`, required=`required`, root=`root`))**. -1. not access(`knowledge`, "ok") - Return *knowledge* with its failure intact. - -1. not access(access(`knowledge`, "value"), "complete") - Return *[Keep a red or running gate visible](result.error(code="release.ek_incomplete", message="wait for or fix EK on the exact main commit", operation="local.tag"))*. - -`argv` = - -| argument | -|---| -| "git" | -| "tag" | -| "-a" | -| `tag_name` | -| "-m" | -| `tag_name` | - -We **created = [Create the new annotated tag without replacement](command(argv=`argv`, root=`root`))**. -1. not access(`created`, "ok") - Return *created* with its failure intact. - -Return *[Push the same immutable tag and verify the remote SHA](push(refspec="refs/tags/" + tag_name + ":refs/tags/" + tag_name, root=`root`))*. - -## editor_workspace - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Validated release version naming the isolated editor stage | -| root | text | "." | Checkout root matching --fs-root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing the isolated vscode-extension directory | - -Use `version` and `root`="." after model.plan validates the release. -This task creates a separate clone under .marqdo/release/editor-X.Y.Z. The main -checkout never receives editor files. Git clones only the vscode-extension branch; -proxy transport is attempted before direct GitHub. A failed clone that leaves a -directory is retained for diagnosis rather than deleted or reset to retry. - -An existing stage is reusable only when its branch is vscode-extension and its -origin is one of this project's explicit release transports. That check prevents -npm from being sent into an unrelated repository merely because its path exists. -The stage is deliberately persistent: inspect a failed install or compile there, -then call extension again. No source merge, hard reset, stash or force checkout -is performed. Requires plugin and fs.write under the same root. Normal Git -credential stores remain private inside the engineering boundary. - -The returned path is only local preparation evidence, not a pushed editor -commit. The extension task below performs package versioning, dependency install, -compilation, narrowly scoped staging and normal push. Publishing on the editor -branch remains part of the user's authorized CLI/full release; simply reading -this file or running preflight authorizes none of those mutations. - -We **directory = ".marqdo/release/editor-" + version** and **parent = [Prepare the ignored release stage parent](fs.make_dirs(path=".marqdo/release"))**. - -`remotes` = - -| remote | -|---| -| "https://proxy.cflmy.top/github.com/cflmy/marqdo.git" | -| "https://github.com/cflmy/marqdo.git" | - -1. not [An existing stage needs inspection before reuse](fs.exists(path=`directory`)) - - [Try maintained transports without replacing an existing stage](for remotes as remote) - `clone_argv` = - - | argument | - |---| - | "git" | - | "clone" | - | "--single-branch" | - | "--branch" | - | "vscode-extension" | - | `remote` | - | `directory` | - - We **cloned = [Clone only the editor-source branch](command(argv=`clone_argv`, root=`root`, timeout=300))**. - 1. access(`cloned`, "ok") - Return *[Validate the newly created stage before using npm](editor_workspace(version=`version`, root=`root`))*. - 1. [A failed partial clone needs explicit diagnosis](fs.exists(path=`directory`)) - Return *cloned* with its preserved directory. - Return *[Report exhausted clone transports](result.error(code="release.editor_clone", message="both editor clone transports failed", operation="editor_workspace"))*. - -`branch_argv` = - -| argument | -|---| -| "git" | -| "branch" | -| "--show-current" | - -We **observed = [Read the stage's real branch](command(argv=`branch_argv`, cwd=`directory`, root=`root`))**. -1. not access(`observed`, "ok") - Return *observed*. -We **branch = [Trim the actual branch name](text.str_trim(s=access(access(observed, "value"), "stdout")))**. -1. `branch` != "vscode-extension" - Return *[Preserve a stage on another branch](result.error(code="release.editor_branch", message="stage must remain on vscode-extension", operation="editor_workspace"))*. - -`origin_argv` = - -| argument | -|---| -| "git" | -| "remote" | -| "get-url" | -| "origin" | - -We **observed = [Read the stage's source repository](command(argv=`origin_argv`, cwd=`directory`, root=`root`))**. -1. not access(`observed`, "ok") - Return *observed*. -We **origin = [Keep the actual origin URL](text.str_trim(s=access(access(observed, "value"), "stdout")))**. -1. not [The source belongs to this release project](table.contains(list=`remotes`, item=`origin`)) - Return *[Refuse an unrelated editor stage](result.error(code="release.editor_origin", message="stage origin is outside the maintained project transports", operation="editor_workspace"))*. - -`stage` = - -| directory | branch | -|---|---| -| `directory` | `branch` | - -Return *[The inspected isolated editor checkout](result.ok(value=`stage`))*. - - -## extension - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | -| root | text | "." | Checkout directory; pass --fs-root . from its root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with an isolated editor-branch commit and confirmed remote SHA | - -Use `version` and `root`="." for an authorized full/cli release. This handbook -prepares a separate clone under .marqdo/release and checks out only the -vscode-extension branch there. Main never receives the ignored editor source. -A failed existing stage is resumed without reset or deletion so local evidence -remains reviewable. npm updates package.json and its lockfile; install and -compile run before that version commit is pushed. Unrelated staged files are -refused before npm modifies anything. Repeating a successful build with unchanged -version files skips the empty commit and resumes exact-SHA push verification. -An editor-branch failure leaves main unchanged and retains its separate workspace. -This task requires Node/npm and network access through plugin. CI packages -the VSIX from the pushed branch; this local task verifies compilation but does -not upload a separate Marketplace package. A compile or push failure propagates -and leaves the stage available for inspection. No model-generated terminal -program is needed to repeat these same mechanics for the next release. - -We **planned = [Accept a valid confirmed editor version](model.plan(version=`version`, mode="cli"))**. -1. not access(`planned`, "ok") - Return *planned* with its failure intact. - -We **workspace = [Prepare or resume the isolated editor-source checkout](editor_workspace(version=`version`, root=`root`))**. -1. not access(`workspace`, "ok") - Return *workspace* with its failure intact. - -We **cwd = [Keep the editor checkout separate from main](access(access(workspace, "value"), "directory"))**. - -`reviewed_paths` = - -| path | -|---| -| "vscode-extension/package.json" | -| "vscode-extension/package-lock.json" | - -We **reviewed = [Protect unrelated editor index work before npm changes versions](review_index(paths=`reviewed_paths`, cwd=`cwd`, root=`root`))**. -1. not access(`reviewed`, "ok") - Return *reviewed* before installing or versioning. - - -`version_argv` = - -| argument | -|---| -| "npm" | -| "version" | -| `version` | -| "--no-git-tag-version" | -| "--allow-same-version" | -| "--prefix" | -| "vscode-extension" | - -We **updated = [Update the editor package and lockfile version](command(argv=`version_argv`, cwd=`cwd`, root=`root`))**. -1. not access(`updated`, "ok") - Return *updated* with its failure intact. - -`install_argv` = - -| argument | -|---| -| "npm" | -| "ci" | -| "--no-audit" | -| "--prefix" | -| "vscode-extension" | - -We **installed = [Install the declared editor build dependencies](command(argv=`install_argv`, cwd=`cwd`, root=`root`, timeout=600))**. -1. not access(`installed`, "ok") - Return *installed* with its failure intact. - -`compile_argv` = - -| argument | -|---| -| "npm" | -| "run" | -| "compile" | -| "--prefix" | -| "vscode-extension" | - -We **compiled = [Compile the editor source before publishing it](command(argv=`compile_argv`, cwd=`cwd`, root=`root`, timeout=300))**. -1. not access(`compiled`, "ok") - Return *compiled* with its failure intact. - -`stage_argv` = - -| argument | -|---| -| "git" | -| "add" | -| -- | -| "vscode-extension/package.json" | -| "vscode-extension/package-lock.json" | - -We **staged = [Stage only the editor version files](command(argv=`stage_argv`, cwd=`cwd`, root=`root`))**. -1. not access(`staged`, "ok") - Return *staged* with its failure intact. - -`changed_args` = - -| argument | -|---| -| "git" | -| "diff" | -| "--cached" | -| "--name-only" | - -We **changes = [Observe whether the successful rebuild changed the version files](command(argv=`changed_args`, cwd=`cwd`, root=`root`))**. -1. not access(`changes`, "ok") - Return *changes* with the index diagnostic. -We **changed = [Retain the actual staged changes](text.str_trim(s=access(access(changes, "value"), "stdout")))**. -1. `changed` != "" - `commit_argv` = - - | argument | - |---| - | "git" | - | "commit" | - | "-m" | - | "vscode-extension: bump to `version` for release" | - - We **committed = [Commit the compiled version when there is a real change](command(argv=`commit_argv`, cwd=`cwd`, root=`root`))**. - 1. not access(`committed`, "ok") - Return *committed* with its hook or commit failure. - -Return *[Push only the editor branch and verify its SHA](push(refspec="HEAD:refs/heads/vscode-extension", cwd=`cwd`, root=`root`))*. - -## debian - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable X.Y.Z explicitly chosen by the user | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result reporting whether a Debian source stanza was added | - -Use `version` after its release plan has been validated. The existing -changelog supplies the maintainer identity; Marqdo reads it, checks whether that -upstream already has a revision, and creates the dated stanza through native -file IO. Asia/Shanghai supplies the release date, independent of the execution -host's default timezone. This is a local metadata edit, not a source upload. - -An existing revision for this upstream is retained, including packaging fixes. -The source archive rules remain the packaging tool's responsibility: never -rewrite an orig archive already accepted by Launchpad. This helper needs fs.write -and time.read, preserves older changelog entries, and returns a recoverable -failure if the old maintainer line cannot be identified. - -We **previous = [Read the actual Debian changelog](fs.read_text(path="debian/changelog"))**. -1. [This upstream already has a packaging revision](text.starts_with(text=`previous`, prefix="marqdo (" + `version` + "-")) - Return *[Preserve its reviewed revision](result.ok(value=False))*. -We **maintainer = [Retain the changelog's maintainer identity](re.find(text=`previous`, pattern="(?m)^ -- .+? "))**. -1. `maintainer` == None - Return *[Require an existing maintainer identity](result.error(code="release.debian_maintainer", message="no changelog maintainer line", operation="local.debian"))*. -We **now = [Read the actual release clock](datetime.now())** and -**local = [Use the release timezone](datetime.in_zone(dt=`now`, zone="Asia/Shanghai"))** and -**date = [Format the Debian timestamp](datetime.format(dt=`local`, style="%a, %d %b %Y %H:%M:%S %z"))** and -**stanza = "marqdo (" + version + "-1ppa1) noble; urgency=medium\n\n * Release " + version + "; see the reviewed upstream CHANGELOG.\n\n" + maintainer + date + "\n\n"**. -We **written = [Atomically prepend this packaging entry](fs.atomic_write(path="debian/changelog", text=`stanza` + previous))**. -Return *[Report the actual local metadata change](result.ok(value=True))*. diff --git a/skills/marqdo-release/model.mq.md b/skills/marqdo-release/model.mq.md deleted file mode 100755 index d20c72d..0000000 --- a/skills/marqdo-release/model.mq.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -markup: occlusion -title: Release model and deliverable contract -import: - re: lib/re.mq.md - result: lib/result.mq.md - table: lib/table.mq.md ---- - -This is the pure release model: version choice belongs to the user, while artifact -names and stage requirements are derived here once. Calling plan never edits a -file, contacts a service, tags a commit or publishes a package. It is suitable -for an agent to inspect before requesting any effect grant. - -Full releases unify CLI, WASM, extension pack and VSIX versions. CLI releases keep -the independently versioned extension pack. Ext releases publish source and both -native packs to GitHub and R2 without retagging the CLI or uploading an Ubuntu CLI. -A tag is a reference to an immutable source decision; an existing tag is not an -invitation to overwrite it. The transport enforces the no-force constraint too. - -Use marqdo call skills/marqdo-release/model.mq.md plan 'version="2.6.0"' --json. -The example describes the already published version; it grants no authorization -to publish it again. Inspecting an existing release uses index.status instead. - -## plan - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z; never infer the next release | -| mode | text | "full" | full, cli or ext; this selects required deliverables | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Derive required assets and stages from a confirmed version and release mode. | - -Derive required assets and stages from a confirmed version and release mode. -Use `version` and `mode`="full". Stable versions have three nonnegative decimal -components without leading zeroes. Unknown modes and malformed versions return -release.input failures before any path or command can be constructed. -The result includes exact filenames; platform completeness is therefore a data -check rather than a model's recollection of what should have been uploaded. - -We **valid = [Accept only stable X.Y.Z version input](re.is_match(text=`version`, pattern="^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"))**. -1. not `valid` - Return *[Report an invalid confirmed version](result.error(code="release.input", message="version must be stable X.Y.Z without leading zeroes", operation="plan"))*. -1. `mode` != "full" and `mode` != "cli" and `mode` != "ext" - Return *[Report an unsupported release mode](result.error(code="release.input", message="mode must be full, cli or ext", operation="plan"))*. - -We **cdn = [Read the maintained cdn contract](cdn_names(version=`version`))**. - -We **cli = [Read the maintained cli contract](cli_names(version=`version`))**. - -1. `mode` == "ext" - We **required = cdn** and **tag = "ext-v" + version** for an independent pack. -2. `mode` == "cli" - We **required = cli** and **tag = "v" + version** for the interpreter. -3. * - We **required = [Require both CLI and cross-platform extension assets](table.concat(a=`cli`, b=`cdn`))** and **tag = "v" + version**. - -We **stages = [Read the maintained stages contract](stages_names())**. - -We **needs_ppa = [Select Ubuntu publication for CLI and full modes](mode != "ext")**. - -`plan_data` = - -| version | mode | tag | required | cdn | ppa | stages | -|---|---|---|---|---|---|---| -| `version` | `mode` | `tag` | `required` | `cdn` | `needs_ppa` | `stages` | - -After establishing the contract, return *[The pure release plan](result.ok(value=`plan_data`))*. - -## cdn_names - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable version already accepted by plan | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Exact cdn release asset names | - -Exact cdn release asset names. -Source and native assets are three separate deliverables. The source ZIP contains -readable extension modules; each native ZIP contains platform-specific plugins. -Windows success cannot stand in for Linux support. Publishing uses all three -files from the same GitHub release and writes VERSION pointers only after uploads. - -Use `version` for these filenames. This helper performs no IO. - -`cdn` = - -| filename | -|---| -| "marqdo-`version`-ext.zip" | -| "marqdo-`version`-native-x86_64-pc-windows-msvc.zip" | -| "marqdo-`version`-native-x86_64-unknown-linux-gnu.zip" | - -We return *cdn* once this contract is assembled. - -## cli_names - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | Stable version already accepted by plan | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Exact cli release asset names | - -Exact cli release asset names. -The executable is convenient for an existing installation; each platform bundle -also carries readable libraries and the platform runtime dependencies. The -standard-library ZIP supports source inspection, the source ZIP identifies the -tagged repository, the VSIX is installed into the editor, and the public ZIP is -offline documentation. These roles remain distinct even when some content overlaps. - -Use `version` for these filenames. This helper performs no IO. - -`cli` = - -| filename | -|---| -| "marqdo-`version`-x86_64-pc-windows-msvc.exe" | -| "marqdo-`version`-x86_64-pc-windows-msvc.zip" | -| "marqdo-`version`-x86_64-unknown-linux-gnu.zip" | -| "marqdo-`version`-stdlib.zip" | -| "marqdo-`version`-source.zip" | -| "marqdo-`version`.vsix" | -| "marqdo-`version`-public.zip" | - -We return *cli* once this contract is assembled. - -## stages_names - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | list | Task routing for the release lifecycle | - -Task routing for the release lifecycle. -The routing table is a map for the agent, not a shell script to rewrite. -Each task resolves to a callable heading in this package. Mode-specific work -is selected by plan.mode and plan.ppa; an ext release skips the CLI and Ubuntu -stages. Any external-state failure remains visible to the next invocation. -Review bilingual notes before the notes task, and retain the returned commit -and artifact hashes with the release record. The table orders responsibilities; -it never authorizes a version the user has not chosen. -CI waiting is observational and bounded by the caller, so asking for status does -not queue another release or repeat an upload. - -`stages` = - -| @ | task | responsibility | -|---|---|---| -| 1 | local.inspect / index.preflight | versions, branch, tree and tag checks | -| 2 | local.bump / local.docs | version files, reviewed notes and generated documentation | -| 3 | local.extension | VSIX source version on its own branch | -| 4 | local.commit / local.push / local.tag | reviewed commit, proxy push, immutable annotated tag | -| 5 | packs.ci / packs.attach_ci (ext); github.status / github.notes / assets.download | both-platform exact-tag builds, reviewed bilingual notes and verified GitHub assets | -| 6 | assets.publish / assets.status | exact same extension bytes on R2 and GitHub | -| 7 | ubuntu.ship / ubuntu.status | signed noble source upload, build and apt publication | - -We return *stages* once this contract is assembled. diff --git a/skills/marqdo-release/package.mq.md b/skills/marqdo-release/package.mq.md deleted file mode 100755 index fe9c414..0000000 --- a/skills/marqdo-release/package.mq.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -markup: occlusion -title: Ubuntu 源码包的原生文件处理 -import: - fs: lib/fs.mq.md - json: lib/json.mq.md - table: lib/table.mq.md - text: lib/text.mq.md - re: lib/re.mq.md - result: lib/result.mq.md - toml: lib/toml.mq.md ---- - -本文件由已维护的 Debian 打包脚本调用。文件枚举、JSON 修订和 changelog 更新使用 Marqdo 固有库;cargo vendor、tar、debuild、GPG 和 dput 是已有工具的外联边界。任务失败应立即中止外层脚本,不能继续签名或上传不完整的源码包。 - -元数据读取任务使用仓库根目录和 fs.read;暂存修订任务要求把 --fs-root 指向实际暂存源码根目录,并授权 fs.write。它们不会选择版本、创建 Git 标签或上传文件。发布者必须先检查所需版本及打包修订号,已经被 Launchpad 接受的 orig 归档必须复用原字节。 - -## upstream - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | text | Current interpreter version read from Cargo package metadata | - -Run this task at the checkout root with fs.read. It reads Cargo.toml through -the native filesystem and TOML parser, then selects package.version rather than -matching an arbitrary dependency version. The release preflight checks that this -actual version is the one the user requested; this helper never chooses a version. - -Without --json, marqdo call prints this text on stdout. The maintained Debian -tool boundary captures that exact output; it does not run sed over the manifest -or regenerate a Python reader. Invalid files retain their native diagnostics. -No network, Git mutation, changelog edit or package upload occurs here. - -We **manifest = [Read and decode the actual interpreter manifest](toml.parse(text=fs.read_text(path="Cargo.toml")))**. -Return *[The current Cargo package version](access(access(manifest, "package"), "version"))*. - -## debian_version - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| series | text | "noble" | Ubuntu series appended to the existing packaging revision | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | Full Debian version text, or failed Result for invalid input | - -Use `series`="noble" at the checkout root. Read the current upstream version -and first Debian changelog header through native Marqdo file operations. Retain -the existing packaging revision, remove its old series suffix and append the -selected series. If the changelog has no revision, use 1ppa1, matching the -maintained packaging rule. This is a read-only projection, not a revision bump. - -A missing marqdo header or invalid series returns a failed Result. The shell -boundary uses --require-ok, so that failure stops before a staging directory or -signature is created. A successful non-JSON call prints only the version text. -Use local.debian or an explicit reviewed changelog edit to choose a new packaging -revision; never silently increment one to bypass an existing upstream archive. - -1. not [The Ubuntu series has the expected shape](re.is_match(text=`series`, pattern="^[a-z][a-z0-9]*$")) - Return *[Reject invalid packaging input](result.error(code="package.series", message=`series`, operation="debian_version"))*. -We **version = [Read the actual interpreter version](upstream())** and **source = [Read the existing Debian changelog](fs.read_text(path="debian/changelog"))** and -**header = [Require its first package declaration](re.find(text=`source`, pattern="^marqdo \\([^)]+\\)"))**. -1. `header` == None - Return *[Keep a missing changelog header visible](result.error(code="package.changelog", message="missing marqdo changelog header", operation="debian_version"))*. -We **observed = [Extract the declared package version](re.replace(text=`header`, pattern="^marqdo \\(([^)]+)\\)$", with="$1"))** and -**base = [Remove the previously selected series suffix](re.replace(text=`observed`, pattern="~.*$", with=""))** and **revision = "1ppa1"**. -1. [The existing version contains a packaging revision](re.is_match(text=`base`, pattern="-")) - We **revision = [Keep the reviewed revision after the upstream component](re.replace(text=`base`, pattern="^[^-]+-", with=""))**. -Return *[The packaging version for this upstream and Ubuntu series](version + "-" + revision + "~" + series)*. - -## vendor_config - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing the natively written staging Cargo configuration | - -Run after cargo vendor in a disposable source-package root. The explicit -configuration makes Cargo use that root's vendor directory when Launchpad builds -offline. Directory creation and UTF-8 writing use the native filesystem rather -than a shell heredoc. Grant fs.write and point --fs-root at the staged package. - -The file is replaced atomically, as the prior packaging script did. This helper -is for the generated staging tree, not for silently changing a developer's -personal Cargo settings. It neither downloads crates nor changes vendor checksums; -sanitize_vendor remains a separate reviewed task. A write failure propagates and -the packaging boundary must stop before building or signing the source archive. - -We **directory = [Prepare the staged Cargo configuration directory](fs.make_dirs(path=".cargo"))** and -**configuration = "[source.crates-io]\nreplace-with = \"vendored-sources\"\n\n[source.vendored-sources]\ndirectory = \"vendor\"\n"**. -We **saved = [Atomically write the explicit offline source configuration](fs.atomic_write(path=".cargo/config.toml", text=`configuration`))**. -Return *[The actual prepared path](result.ok(value=".cargo/config.toml"))*. - -## sanitize_vendor - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:移除的备份文件数与修改的 checksum 文件数 | - -cargo vendor 完成后执行此任务。Debian 的清理步骤会删除 .orig 和 .rej 文件;若 Cargo 的 vendor 清单仍引用这些文件,离线构建就会失败。因此先枚举每个 crate 的真实 checksum,删除对应条目及备份文件,再原子保存清单。普通源码文件和 package 校验值保持原样。 - -路径来自生成的清单,但仍需验证没有父目录跳转或绝对路径。一个 crate 完成后才处理下一个;发生错误时已完成的修订留在暂存目录供诊断,不能宣称整个目录修改具有事务性。重复运行不会继续增加计数,也不应引入 Python 作为备用写入器。 - -The package checksum and the individual file checksums serve different purposes. -Retain the upstream package digest and every ordinary source entry. Removing -only backup suffixes mirrors the existing Debian clean rule; it is not a general -vendor rewrite or permission to replace code inside third-party crates. -After this task, the packaging boundary must still run the normal offline -build checks. A successful count only records this local preparation step. -Review the resulting checksum changes when diagnosing a Launchpad failure, -and preserve the staged tree if any later signing or upload operation fails. - -We **checksums = [枚举 vendor 的实际校验清单](fs.find(path="vendor", pattern="**/.cargo-checksum.json"))** and **removed = 0** and **changed = 0**。 -- [逐个处理 crate 的校验清单](for checksums as relative) - We **path = "vendor/" + relative** and **source = [读取校验清单](fs.read_text(path=`path`))** and **data = [解码 JSON 边界文本](json.parse(text=`source`))** and **files = [取得文件散列映射](access(data, "files"))** and **dirty = False**。 - We **keys = [保留遍历开始时的文件名](table.keys(map=`files`))** and **directory = [取得此清单所在目录](re.replace(text=`path`, pattern="/[^/]+$", with=""))**。 - - [仅移除 Debian 清理器会删除的备份](for keys as name) - 1. [该路径是备份或补丁拒绝文件](text.ends_with(text=`name`, suffix=".orig")) or [该路径是补丁拒绝文件](text.ends_with(text=`name`, suffix=".rej")) - 1. [清单路径越出 crate 边界](re.is_match(text=`name`, pattern="(^/|(^|/)\\.\\.(/|$)|\\\\|:)")) - 返回*[拒绝不可信的清单路径](result.error(code="package.vendor_path", message=`name`, operation="sanitize_vendor"))*。 - We **target = directory + "/" + name**。 - 1. [备份文件实际存在](fs.exists(path=`target`)) - We **deleted = [通过固有库删除备份文件](fs.remove_file(path=`target`))** and **removed = removed + 1**。 - We **files = [从校验清单删除同名项](table.delete(map=`files`, key=`name`))** and **dirty = True**。 - 1. `dirty` - We **data = [保留其他元数据并替换文件表](table.put(in=`data`, at="files", value=`files`))** and **encoded = [序列化修改后的边界文本](json.stringify(value=`data`, indent=4))**。 - We **written = [原子保存此 crate 的清单](fs.atomic_write(path=`path`, text=`encoded` + "\n"))** and **changed = changed + 1**。 - -`counts` = - -| removed | changed | -|---|---| -| `removed` | `changed` | - -处理结束后返回*[实际修改计数](result.ok(value=`counts`))*。 - -## changelog - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | 包含 Debian 修订号的完整源码包版本 | -| series | text | "noble" | 目标 Ubuntu series | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result:保存后的第一行 | - -以 `version` 和 `series`="noble" 修订暂存目录中的 Debian changelog。这里传入的是类似 2.6.0-1ppa1~noble 的完整打包版本,不能只传上游版本。任务只替换现有首行的包版本和发行系列,维护者、签名时间和旧条目由先前准备步骤保留。 - -实际调用的 version 需要保留完整修订号和发行系列后缀,例如 2.6.0-1ppa1~noble。 -输入必须符合 Debian 版本和 series 的字符范围;缺少现有 marqdo 首行时返回错误,避免悄悄生成一份内容不足的 changelog。这里不递增打包修订,也不重建已经接收的 orig 归档。写入采用固有库原子替换,需要 fs.write。 - -1. not [打包版本只包含允许的字符](re.is_match(text=`version`, pattern="^[0-9][0-9A-Za-z.+:~_-]*$")) or not [发行系列合法](re.is_match(text=`series`, pattern="^[a-z][a-z0-9]*$")) - 返回*[拒绝无效打包元数据](result.error(code="package.input", message="invalid Debian version or series", operation="changelog"))*。 -We **source = [读取已准备的 changelog](fs.read_text(path="debian/changelog"))** and **first = [查找现有包声明](re.find(text=`source`, pattern="^marqdo \\([^)]+\\) [^;]+;"))**。 -1. `first` == None - 返回*[保留缺失首行的诊断](result.error(code="package.changelog", message="missing marqdo changelog header", operation="changelog"))*。 -We **header = "marqdo (" + version + ") " + series + ";"** and **updated = [仅替换已确认的首行](text.replace(text=`source`, old=`first`, new=`header`, count=1))**。 -We **saved = [原子保存暂存包元数据](fs.atomic_write(path="debian/changelog", text=`updated`))**。 -完成后返回*[实际保存的包声明](result.ok(value=`header`))*。 diff --git a/skills/marqdo-release/packs.mq.md b/skills/marqdo-release/packs.mq.md deleted file mode 100755 index a4aff3d..0000000 --- a/skills/marqdo-release/packs.mq.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -markup: occlusion -title: Independent extension-pack build tasks -import: - model: ./model.mq.md - github: ./github.mq.md - fs: lib/fs.mq.md - path: lib/path.mq.md - sys: lib/sys.mq.md - text: lib/text.mq.md - table: lib/table.mq.md - result: lib/result.mq.md - engineering: ext/engineering/index.mq.md ---- - -This leaf builds source and one platform's native extension archives for an authorized version. It does not publish, choose a version, create a tag or edit version files. The extension-release workflow runs the same tasks on Windows and Linux after local.tag pushes ext-vX.Y.Z. Its attach_ci task creates the exact tagged release through the native service boundary and attaches three assets with the existing gh upload tool; assets.publish subsequently verifies those exact bytes before R2 publication. - -Build all six maintained native plugins first. The native_dir contract is a directory containing their platform library names, normally target/release. Source discovery and staging use native Marqdo filesystem operations. Only ZIP encoding uses the existing platform tool: Info-ZIP on Linux, 7-Zip on Windows. Compiler and format boundaries do not require Python or a generated shell program. - -## libraries - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| platform | text | required | x86_64-pc-windows-msvc or x86_64-unknown-linux-gnu | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing the six exact native library filenames | - -Use `platform` to select the format names rather than guessing suffixes from one local file. Both platform packs must contain web, agent, quantum, linalg, llm and engineering. This pure contract neither proves ABI compatibility nor substitutes for compiling on the selected platform. Unknown targets fail before a staging directory is created. - -1. `platform` == "x86_64-pc-windows-msvc" - - `names` = - - | name | - |---| - | web.dll | - | agent.dll | - | quantum.dll | - | linalg.dll | - | llm.dll | - | engineering.dll | - - Return *[The complete Windows native contract](result.ok(value=`names`))*. -1. `platform` == "x86_64-unknown-linux-gnu" - - `names` = - - | name | - |---| - | libweb.so | - | libagent.so | - | libquantum.so | - | liblinalg.so | - | libllm.so | - | libengineering.so | - - Return *[The complete Linux native contract](result.ok(value=`names`))*. -Return *[Reject an unsupported native target](result.error(code="packs.platform", message=`platform`, operation="libraries"))*. - -## _archive - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| stage | text | required | Owned staging root with one selected ext or native directory | -| entry | text | required | ext or native directory to encode | -| output | text | required | New ZIP path under the same filesystem root | -| platform | text | required | Already validated platform target | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Checked ZIP encoder result; an existing output is never replaced | - -Use `stage`, `entry`, `output` and `platform` only after build preflight. Native resolution validates the stage and output paths first; the encoder receives individual arguments and one named staging subtree. It cannot expand a generated shell expression. A failed encoder can leave the selected incomplete archive for inspection; this task never reuses it as successful output or deletes unrelated files. - -The Windows runner supplies 7-Zip with ZIP format support; Linux supplies Info-ZIP. Format encoding is the only external operation here. Reads, directory creation, copies, hashes and final ZIP validation remain separate explicit native tasks. The caller removes only its owned temporary stage after the child exits. Existing archives require inspection or a different output directory, keeping reruns from silently replacing publication candidates. - -1. [This output already belongs to an earlier attempt](fs.exists(path=`output`)) - Return *[Preserve the existing archive](result.error(code="packs.output_exists", message=`output`, operation="_archive"))*. -We **destination = [Resolve the new archive inside the granted root](fs.resolve(path=`output`))**. - -`argv` = - -| argument | -|---| -| zip | -| "-q" | -| "-r" | -| `destination` | -| `entry` | - -1. `platform` == "x86_64-pc-windows-msvc" - - `argv` = - - | argument | - |---| - | "C:\\Program Files\\7-Zip\\7z.exe" | - | a | - | "-tzip" | - | `destination` | - | `entry` | - -We **checkout = [Use the absolute runtime checkout as the plugin root](sys.cwd())**. -Return *[Encode only the explicitly staged format subtree](engineering.checked(argv=`argv`, cwd=`stage`, timeout_ms=300000, max_output=65536, root=`checkout`))*. - -## _receipt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| file | text | required | Completed archive selected by build | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with path, SHA256, size and validated archive entries | - -Use `file` after the encoder exits successfully. Hash the resulting bytes through the native filesystem, then inspect ZIP contents with the maintained archive boundary. CRC, traversal, duplicate-path and expansion checks apply to actual archive bytes; a process exit alone does not establish a valid publication candidate. A later upload still rechecks this digest. - -A receipt is local evidence, not a declaration that both platforms have been built. The format boundary reads the named archive without extracting it. Failure remains a failed Result with its original diagnostic. Keep completed archives and receipts for review; the build task cleans temporary staging, not its explicitly requested outputs. - -We **sha256 = [Hash the actual encoded bytes](fs.file_hash(path=`file`))** and **metadata = [Read the native file size](fs.stat(path=`file`))** and **inspected = [Validate actual ZIP entries and CRCs](engineering.inspect_zip(path=`file`))**. -1. not access(`inspected`, "ok") - Return *inspected*. -We **size = [Retain the actual byte count](access(metadata, "size"))** and **archive = [Retain validated archive evidence](access(inspected, "value"))**. - -`receipt` = - -| path | sha256 | size | archive | -|---|---|---|---| -| `file` | `sha256` | `size` | `archive` | - -Return *[Expose the verified local candidate](result.ok(value=`receipt`))*. - -## _stage_sources - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| stage | text | required | Newly created temporary root owned by build | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | any | None after native source copies; filesystem failures remain diagnostics | - -Use `stage` with fs.write on the checkout root. Discover source files under ext while excluding native binaries and generated caches. Each returned path stays relative to ext, preserving module organization, language mirrors and VERSION. Copies use the native root and symlink policy; this task does not call cp, PowerShell file commands or an archive tool to enumerate authoring data. - -The stage is private to this invocation. No existing distribution tree is cleared, and no source file is edited. Parent directories are created only for selected copies. Keeping enumeration separate from ZIP encoding makes the source list visible in Marqdo rather than embedding repository policy in a shell script. - -`excluded` = - -| pattern | -|---| -| native/** | -| **/target/** | -| **/node_modules/** | -| **/.git/** | - -We **files = [Find maintained extension source files](fs.find(path="ext", pattern="**", exclude=`excluded`))**. -- [Copy only the discovered source entries](for files as file) - We **target = stage + "/ext/" + file** and **parent = [Find the selected native destination parent](path.parent(path=`target`))**. - We **[Create that destination directory](fs.make_dirs(path=`parent`))** and **[Copy this exact source file](fs.copy_file(src="ext/" + file, dest=`target`))**. -Return *None* after all explicit source copies finish. - -## build - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable extension version already present in ext/VERSION | -| platform | text | required | One supported native target compiled by this runner | -| directory | text | "dist/ext-release" | New output directory under the granted checkout root | -| native_dir | text | "target/release" | Existing directory containing all six compiled native libraries | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing source and current-platform native archive receipts | - -Use `version`, `platform`, `directory`="dist/ext-release" and `native_dir`="target/release". Grant plugin and fs.write from the checkout root. Stable version, supported platform, ext/VERSION, all six library files and both absent destination names are checked before any stage is created. This task packages previously compiled libraries; it does not claim to cross-compile Windows from Linux. - -The source archive contains the readable ext tree without native binaries. The platform archive contains six libraries under native. Every file copy and output digest uses native filesystem tools, with only ZIP encoding at the existing external-tool boundary. Stage cleanup happens after encoding returns; a native filesystem diagnostic may retain the owned stage for inspection. Existing output archives are preserved rather than overwritten on a retry. - -We **plan = [Validate the confirmed independent-pack version](model.plan(version=`version`, mode="ext"))** and **selected = [Select the complete platform library contract](libraries(platform=`platform`))**. -1. not access(`plan`, "ok") - Return *plan*. -1. not access(`selected`, "ok") - Return *selected*. -1. [The actual extension version differs](text.str_trim(s=fs.read_text(path="ext/VERSION")) != `version`) - Return *[Require reviewed extension metadata first](result.error(code="packs.version", message="ext/VERSION differs from the requested pack", operation="build"))*. -We **names = [Read the six required library names](access(selected, "value"))**. -- [Preflight all actual native files before staging](for names as name) - 1. not [The compiled library exists](fs.exists(path=(`native_dir` + "/" + `name`))) - Return *[Keep the missing native capability visible](result.error(code="packs.library", message=`name`, operation="build"))*. -We **source = directory + "/marqdo-" + version + "-ext.zip"** and **native = directory + "/marqdo-" + version + "-native-" + platform + ".zip"**. -1. [The source output already exists](fs.exists(path=`source`)) or [The native output already exists](fs.exists(path=`native`)) - Return *[Preserve all existing output candidates](result.error(code="packs.output_exists", message="inspect existing archives or choose a new directory", operation="build"))*. -We **[Create the requested output directory](fs.make_dirs(path=`directory`))** and **stage = [Allocate an owned native staging directory](fs.temp_dir(prefix=".release-pack"))**. -We **[Copy readable extension sources](_stage_sources(stage=`stage`))** and **[Create the native library subtree](fs.make_dirs(path=stage + "/native"))**. -- [Copy each selected compiled library](for names as name) - We **[Retain the exact compiled bytes](fs.copy_file(src=native_dir + "/" + name, dest=stage + "/native/" + name))**. -We **packed = [Encode the source subtree](_archive(stage=`stage`, entry="ext", output=`source`, platform=`platform`))**. -1. access(`packed`, "ok") - We **packed = [Encode the platform native subtree](_archive(stage=`stage`, entry="native", output=`native`, platform=`platform`))**. -We **[Remove only this invocation's completed staging tree](fs.remove_tree(path=`stage`))**. -1. not access(`packed`, "ok") - Return *packed*. -We **source_receipt = [Validate the actual source archive](_receipt(file=`source`))** and **native_receipt = [Validate the actual platform archive](_receipt(file=`native`))**. -1. not access(`source_receipt`, "ok") - Return *source_receipt*. -1. not access(`native_receipt`, "ok") - Return *native_receipt*. -We **sources = [Keep source candidate evidence](access(source_receipt, "value"))** and **platform_pack = [Keep native candidate evidence](access(native_receipt, "value"))**. - -`receipt` = - -| version | platform | source | native | -|---|---|---|---| -| `version` | `platform` | `sources` | `platform_pack` | - -Return *[Expose both verified local pack candidates](result.ok(value=`receipt`))*. - -## ci - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result from building the current runner's user-tagged independent pack | - -Run this task only in the extension-release workflow after its compiler steps. Grant environment.read, fs.write and plugin. The runner provides GITHUB_REF_NAME and RUNNER_OS; neither is interpolated into generated shell source. Require the ext-v prefix, validate its stable version through build, and map only the two known runner operating systems to their supported targets. - -This entry does not create a remote release. The workflow's separate attach_ci task attaches the exact output names after local validation. Windows contributes the source and Windows native pack; Linux contributes its native pack. CI status must subsequently cover both jobs on the exact annotated-tag commit. A failed task stops the upload step through --require-ok; no stale package replaces it. - -We **tag = [Read the actual pushed tag](sys.env_get(name="GITHUB_REF_NAME"))** and **runner = [Read the actual compilation runner](sys.env_get(name="RUNNER_OS"))**. -1. `tag` == None or not [The tag selects independent extension publication](text.starts_with(text=`tag`, prefix="ext-v")) - Return *[Reject an unrelated ref](result.error(code="packs.tag", message="expected ext-vX.Y.Z", operation="ci"))*. -We **version = [Read the tag's stable version component](text.replace(text=`tag`, old="ext-v", new="", count=1))** and **platform = ""**. -1. `runner` == "Windows" - We **platform = "x86_64-pc-windows-msvc"**. -1. `runner` == "Linux" - We **platform = "x86_64-unknown-linux-gnu"**. -We **built = [Build the exact runner and tag contract](build(version=`version`, platform=`platform`))**. -1. not access(`built`, "ok") - Return *built*. -We **[Create the receipt directory through native IO](fs.make_dirs(path=".marqdo/release"))** and **[Retain exact bytes for the separate upload step](fs.write_json(path=".marqdo/release/packs.json", value=access(built, "value")))**. -Return *built*. - -## _unchanged - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| receipt | map | required | Local path/SHA256 evidence returned by this runner's build | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | bool | Whether the selected archive still has the recorded byte identity | - -Use `receipt` before an upload mutation. Native filesystem hashing checks the exact file selected by the build rather than trusting its name, timestamp or successful encoder exit. A missing file remains a filesystem diagnostic. A changed digest returns False and prevents release creation as well as upload. This is a preflight drift check, not a lock against concurrent writers; CI owns its output directory during publication. - -Return *[Recheck the recorded candidate's actual bytes](fs.file_hash(path=access(receipt, "path")) == access(receipt, "sha256"))*. - -## attach_ci - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Checked result of attaching this runner's unchanged archives without replacement | - -Run after ci in the independent extension workflow, with plugin, fs.read and environment.read. The GitHub runner supplies its existing GH_TOKEN privately to the installed gh tool; credentials never become arguments or journal values. Read the saved build receipt, pushed tag and source SHA first. Only the two supported runner names are accepted, and the receipt must match that runner and exact version. - -Before any service mutation, rehash both local archives and read the reviewed notes at doc/releases/ext-X.Y.Z.md. The release source must commit those bilingual notes before its immutable tag is pushed. create_ext verifies that remote tag's commit equals GITHUB_SHA, creates a missing release once, and preserves an existing release. An uncertain creation remains failed for explicit observation, not automatic retry. - -Windows attaches the source archive and Windows native archive. Linux attaches only its native archive. The existing gh release upload command is an explicit service-tool boundary; no --clobber flag is used, so rerunning cannot silently replace a prior asset. An already attached file requires inspection and byte comparison rather than deleting or overwriting it. Both platform CI jobs and later GitHub/R2 parity still must pass before finish can declare the release complete. - -We **tag = [Read the actual pushed tag](sys.env_get(name="GITHUB_REF_NAME"))** and **runner = [Read the actual build runner](sys.env_get(name="RUNNER_OS"))** and **sha = [Read the runner's exact source commit](sys.env_get(name="GITHUB_SHA"))**. -1. `tag` == None or `sha` == None or not [The ref selects extension publication](text.starts_with(text=`tag`, prefix="ext-v")) - Return *[Require an explicit extension CI context](result.error(code="packs.ci_context", message="missing extension tag or commit", operation="attach_ci"))*. -We **version = [Read the selected stable version](text.replace(text=`tag`, old="ext-v", new="", count=1))** and **plan = [Validate that version before choosing paths](model.plan(version=`version`, mode="ext"))**. -1. not access(`plan`, "ok") - Return *plan*. -We **platform = ""**. -1. `runner` == "Windows" - We **platform = "x86_64-pc-windows-msvc"**. -1. `runner` == "Linux" - We **platform = "x86_64-unknown-linux-gnu"**. -We **supported = [Reject unsupported compilation runners](libraries(platform=`platform`))**. -1. not access(`supported`, "ok") - Return *supported*. -We **receipt = [Read this runner's actual native build receipt](fs.read_json(path=".marqdo/release/packs.json"))**. -1. access(`receipt`, "version") != `version` or access(`receipt`, "platform") != `platform` - Return *[Reject stale or foreign runner evidence](result.error(code="packs.receipt", message="receipt version/platform mismatch", operation="attach_ci"))*. -We **source = [Read the source archive identity](access(receipt, "source"))** and **native = [Read the platform archive identity](access(receipt, "native"))**. -1. access(`source`, "path") != ("dist/ext-release/marqdo-" + `version` + "-ext.zip") or access(`native`, "path") != ("dist/ext-release/marqdo-" + `version` + "-native-" + `platform` + ".zip") - Return *[Require the exact runner output names](result.error(code="packs.receipt_path", message="receipt paths differ from the selected outputs", operation="attach_ci"))*. -1. not [_unchanged source bytes](_unchanged(receipt=`source`)) or not [Unchanged native bytes](_unchanged(receipt=`native`)) - Return *[Stop before publication when local bytes drift](result.error(code="packs.changed", message="archive changed after build", operation="attach_ci"))*. -We **published = [Create or observe the exact release from reviewed committed notes](github.create_ext(version=`version`, path="doc/releases/ext-" + version + ".md", sha=`sha`))**. -1. not access(`published`, "ok") - Return *published*. - -`argv` = - -| argument | -|---| -| gh | -| release | -| upload | -| `tag` | -| "--repo" | -| "cflmy/marqdo" | - -1. `runner` == "Windows" - We **argv = [Attach the source pack from the Windows runner](table.append(list=`argv`, item=access(source, "path")))**. -We **argv = [Attach only this runner's native pack](table.append(list=`argv`, item=access(native, "path")))**. -Return *[Upload the verified candidates without replacing existing assets](engineering.checked(argv=`argv`, timeout_ms=300000, max_output=65536))*. diff --git a/skills/marqdo-release/reference.md b/skills/marqdo-release/reference.md deleted file mode 100755 index cc9e2ba..0000000 --- a/skills/marqdo-release/reference.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release task reference - -Read [the executable release entry](index.mq.md). Version and mode come from the user; existing authorization is retained. Every task has its own input/return tables, effects, failure boundaries and recovery behavior. - -| Need | Actual callable source | -|---|---| -| Inspect versions and checkout | local.mq.md inspect | -| Derive mode obligations | index.mq.md plan | -| Author local source/notes | ../marqdo-dev/files.mq.md read, patch, write or apply | -| Prepare versions/editor/docs | local.mq.md bump, extension and docs | -| Commit reviewed files/push refs | local.mq.md commit, push and tag | -| Observe exact-source CI/edit reviewed notes | github.mq.md status and notes | -| Verify GitHub bytes and package roles | assets.mq.md download | -| Publish verified R2 packs/check public parity | assets.mq.md publish and status | -| Build signed noble source/check actual apt | ubuntu.mq.md ship and status | -| Require every release obligation complete | index.mq.md finish | - -A failed process, hook, HTTP response or pending CI remains visible. Inspect Result.ok before value. Use --require-ok when an external automation must stop on a failed Result; observational status may truthfully return complete=False. finish turns incomplete publication into a failed completion gate and retains its evidence. - -Git retries use the documented proxy then direct route. A reviewed SSH/HK route can be supplied through MARQDO_RELEASE_GIT_REMOTE; no jump program or credential value belongs in a model argument. Existing tags and failed stages remain available for inspection. Do not force, retag or reset to make a check green. If sudo, GPG or dput needs human interaction, report the exact failure and give the concrete ubuntu.mq.md ship call for the already authorized version. An accepted orig archive must retain its original bytes. - -Credentials stay in existing private stores. Do not publish from reading this note, deploy gh-pages without instruction, or call an asset list proof of green CI and apt publication. diff --git a/skills/marqdo-release/ubuntu.mq.md b/skills/marqdo-release/ubuntu.mq.md deleted file mode 100755 index daf2841..0000000 --- a/skills/marqdo-release/ubuntu.mq.md +++ /dev/null @@ -1,265 +0,0 @@ ---- -markup: occlusion -title: Ubuntu publication: source, build and apt evidence -import: - net: lib/net.mq.md - json: lib/json.mq.md - text: lib/text.mq.md - table: lib/table.mq.md - re: lib/re.mq.md - result: lib/result.mq.md - engineering: ext/engineering/index.mq.md - local: ./local.mq.md - model: ./model.mq.md ---- - -Ubuntu 发布分为源码接收、构建成功和 apt 索引发布三个状态。这里用 Marqdo 固有网络库读取公开证据;gzip 格式交给工程拓展解码,不启动 Python。ship 是独立的外部写入任务,只有实际发版授权才能调用。status 只读,不会尝试重新上传已经存在的版本。 - -源包准备和文件修订在 package.mq.md;Debian 工具链、GPG 和 dput 通过维护中的系统脚本外联。sudo、签名口令或 Launchpad 拒绝都是真实失败,需要报告确切阶段与修复命令。已接收的 orig 归档不能改字节重传,打包修复只递增 Debian 修订号。 - -## read_json - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| url | text | required | Public Launchpad JSON URL | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing decoded response JSON | - -Use `url` for an explicitly selected public metadata endpoint. Native net.get -returns an HTTP response separately from transport success. Require status 200 -before decoding its body: a 404 HTML page must never become an empty publication -record. The helper reads at most one MiB with a bounded timeout and keeps the -original transport failure. No authentication, subprocess or temporary file is -needed for these public facts. - -This helper does not guess whether an upstream version has shipped. Its caller -selects matching source publications and builds from the returned records. -A schema change remains visible to that caller. Reading a successful response -is evidence for that endpoint at this time, not permission to upload a new -package. Call with network.read; further gzip decoding is a separate capability. - -We **fetched = [Read bounded public Launchpad JSON](net.get(url=`url`, timeout_ms=30000, max_bytes=1048576))**. -1. not access(`fetched`, "ok") - Return *fetched* with the transport diagnostic. -We **response = [Inspect the actual HTTP response](access(fetched, "value"))**. -1. access(`response`, "status") != 200 - Return *[Retain the unsuccessful HTTP status](result.error(code="ubuntu.http", message=str(access(response, "status")), operation="read_json"))*. -We **body = [Decode the successful JSON body](json.parse(text=access(response, "body")))**. -Return *[The service's actual metadata](result.ok(value=`body`))*. - -## source - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z | -| series | text | "noble" | Ubuntu series being observed | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result containing the newest matching published source or None | - -Use `version` and `series`="noble" to locate a published upstream package. -The pure release model first validates the upstream version. Launchpad returns -publication history ordered by date; select the first entry with this upstream -version followed by a Debian revision and the exact target distro series. -A newer unrelated release or another Ubuntu series cannot satisfy this check. - -None is a successful observation that this version is not currently published. -An HTTP failure remains a failed Result and must not be reported as absence. -A source publication alone does not establish successful binary compilation: -builds and apt are separate tasks below. This query is public and requires -network.read. It changes neither Launchpad state nor local version metadata, -and it never infers the user's next version from the newest remote package. - -We **planned = [Validate the selected upstream version](model.plan(version=`version`))**. -1. not access(`planned`, "ok") - Return *planned*. -We **observed = [Read ordered publication history](read_json(url="https://api.launchpad.net/1.0/~cflmy/+archive/ubuntu/marqdo?ws.op=getPublishedSources&source_name=marqdo&exact_match=true&status=Published&order_by_date=true"))**. -1. not access(`observed`, "ok") - Return *observed*. -We **entries = [Read actual publication records](access(access(observed, "value"), "entries"))**. -- [Choose the exact upstream and distro series](for entries as entry) - 1. [The Debian revision belongs to this upstream](text.starts_with(text=access(`entry`, "source_package_version"), prefix=`version` + "-")) and access(`entry`, "distro_series_link") == "https://api.launchpad.net/1.0/ubuntu/" + `series` - Return *[The matching source publication](result.ok(value=`entry`))*. -Return *[No matching publication exists](result.ok(value=None))*. - -## builds - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| publication | any | required | Source publication returned by source, or None | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with complete and the selected source's actual builds | - -Use `publication` from the source task, rather than a build number copied -from a previous release. Launchpad's source record supplies the build collection. -The required amd64 build must report Successfully built. Keep all returned build -records for diagnosis, including logs and a pending or failed status. - -A missing source or an empty build collection remains incomplete. Do not treat -the successful metadata request as successful compilation. The task deliberately -does not retry or rescore Launchpad jobs; those are separate external mutations -that need a concrete packaging fix and release authorization. This read requires -network.read. Successful compilation still leaves the apt publication check: -the publisher may need time to expose the binary package in the repository -index after a build turns green. - -We **entries = [Start with no invented build records](table.empty_list())** and **complete = False**. -1. `publication` != None - We **observed = [Read builds belonging to this source publication](read_json(url=access(publication, "self_link") + "?ws.op=getBuilds"))**. - 1. not access(`observed`, "ok") - Return *observed*. - We **entries = [Keep the real build evidence](access(access(observed, "value"), "entries"))**. - - [Require the intended Linux architecture](for entries as build) - 1. access(`build`, "arch_tag") == "amd64" and access(`build`, "buildstate") == "Successfully built" - We **complete = True** because this source's amd64 binary compiled. - -`state` = - -| complete | entries | -|---|---| -| `complete` | `entries` | - -Return *[The actual source-specific build state](result.ok(value=`state`))*. - -## apt - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z | -| series | text | "noble" | Ubuntu series being observed | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result with complete, package_version and the public index URL | - -Use `version` and `series`="noble" to inspect the actual public amd64 apt -index. Launchpad publishes Packages.gz; the uncompressed URL may return 404. -Native net.get reads portable bytes, then the engineering format boundary -validates gzip and decodes bounded UTF-8 text. No shell pipeline, local apt cache -or Python parser substitutes for the remote index. - -Find the marqdo package stanza and its exact upstream prefix plus Debian revision. -A different package's Version line cannot satisfy this check. A successful build -may precede index publication, so complete=False is an honest intermediate state. -Transport, gzip and schema failures retain their diagnostics. The task needs -network.read and plugin and writes no file. It proves repository visibility at -this instant; installation on a particular user's machine additionally depends -on their configured source and apt refresh. - -We **url = "https://ppa.launchpadcontent.net/cflmy/marqdo/ubuntu/dists/" + series + "/main/binary-amd64/Packages.gz"** and -**fetched = [Read the actual compressed apt index](net.get(url=`url`, response="bytes", max_bytes=16777216))**. -1. not access(`fetched`, "ok") - Return *fetched*. -We **response = [Inspect its HTTP status](access(fetched, "value"))**. -1. access(`response`, "status") != 200 - Return *[Retain index unavailability](result.error(code="ubuntu.apt_http", message=str(access(response, "status")), operation="apt"))*. -We **decoded = [Validate and decode the gzip format](engineering.gzip_text(data=access(response, "body")))**. -1. not access(`decoded`, "ok") - Return *decoded*. -We **stanzas = [Keep package fields in their own records](text.str_split(s=access(decoded, "value"), sep="\n\n"))** and **complete = False** and **package_version = None**. -- [Inspect only the marqdo package's version](for stanzas as stanza) - 1. [This is the marqdo package stanza](text.starts_with(text=`stanza`, prefix="Package: marqdo\n")) - We **line = [Read its Version field](re.find(text=`stanza`, pattern="(?m)^Version: [^\n]+"))**. - 1. `line` != None - We **candidate = [Remove the field label](text.replace(text=`line`, old="Version: ", new="", count=1))**. - 1. [This index contains the requested upstream](text.starts_with(text=`candidate`, prefix=`version` + "-")) - We **package_version = candidate** and **complete = True**. - -`state` = - -| complete | package_version | url | -|---|---|---| -| `complete` | `package_version` | `url` | - -Return *[The observed apt publication state](result.ok(value=`state`))*. - -## status - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z | -| series | text | "noble" | Ubuntu series being observed | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result combining source publication, build and apt completion | - -Use `version` and `series`="noble" to verify an existing Ubuntu release. -Each observation remains separate in the returned record so the user can tell -whether upload, compilation or apt publication is pending. Completion requires -a published source, its successful amd64 build, and the matching apt package. - -This is a read-only task requiring network.read and plugin. It does not invoke -sudo, GPG, debuild or dput. Repeating status observes newer external state without -creating another upload. If a service request fails, return its real failure -rather than manufacturing a pending state. An ext-only release has no Ubuntu -obligation; the top-level release handbook handles that mode explicitly. Keep -the version provided by the caller: querying status never selects a next release -or edits the local changelog. - -We **published = [Locate this upstream's source publication](source(version=`version`, series=`series`))**. -1. not access(`published`, "ok") - Return *published*. -We **publication = [Retain its matching source record](access(published, "value"))** and -**built = [Check the source-specific amd64 build](builds(publication=`publication`))**. -1. not access(`built`, "ok") - Return *built*. -We **indexed = [Verify actual apt repository visibility](apt(version=`version`, series=`series`))**. -1. not access(`indexed`, "ok") - Return *indexed*. -We **build_state = [Keep build evidence](access(built, "value"))** and **apt_state = [Keep index evidence](access(indexed, "value"))** and -**complete = publication != None and access(build_state, "complete") and access(apt_state, "complete")**. - -`state` = - -| complete | publication | build | apt | -|---|---|---|---| -| `complete` | `publication` | `build_state` | `apt_state` | - -Return *[The independently measured Ubuntu release state](result.ok(value=`state`))*. - -## ship - -| 参数 | 类型 | 默认 | 说明 | -|---|---|---|---| -| version | text | required | User-confirmed stable X.Y.Z | -| series | text | "noble" | Ubuntu series being observed | -| root | text | "." | Checkout matching --fs-root | - -| 返回 | 类型 | 说明 | -|---|---|---| -| result | map | Result from the signed Ubuntu source publication boundary | - -Use `version`, `series`="noble" and `root`="." only for an authorized -CLI/full release. Verify the checked-out interpreter has that exact upstream -version before invoking the maintained Debian tools. Their signatures, orig -archive rules and dput behavior remain the operating-system boundary. File -preparation in that script delegates to package.mq.md. - -This task requires plugin and fs.read and may need interactive OS credentials. -A sudo, GPG or dput failure is incomplete publication. Report the exact failing -stage and give the concrete recovery call, rather than hiding it behind success -or inventing another version. After the command succeeds, run status: upload -acceptance alone does not establish green builds or apt availability. Never -rewrite an orig archive already accepted by Launchpad. - -We **observed = [Require actual checkout version metadata](local.inspect(root=`root`))**. -1. not access(`observed`, "ok") - Return *observed*. -1. access(access(`observed`, "value"), "cli_version") != `version` - Return *[Refuse a different source version](result.error(code="ubuntu.version", message="checkout version differs from requested upstream", operation="ship"))*. - -`argv` = - -| argument | -|---| -| "bash" | -| "scripts/ppa-ship.sh" | -| `series` | - -Return *[Build, sign and upload through the maintained Debian tools](local.command(argv=`argv`, timeout=3600, root=`root`))*. diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md deleted file mode 100755 index 6a8f1bc..0000000 --- a/skills/marqdo/SKILL.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -name: marqdo -description: Author, run and review readable Marqdo programs, libraries and executable knowledge. Use for .mq.md, marqdo call, Document/Endpoint/Resource web projects and quantum tools; read the executable programming and development handbooks. ---- - -# Marqdo - - - -## CORE SYNTAX - -Occlusion is the current default. `**…**` executes a statement; `*…*` returns. -Use `[intent](actual code)` in an executable position: the label is prose and -only its payload executes. Empty parentheses are a pending None stub. -Read collections with `access(coll, key)`. Classic indexing is only for explicit -legacy sources and migration. Reading narrative references never runs effects. - -| Marker | Meaning | -|---|---| -| `**…**` | Statement (assign / call / expression) | -| `*…*` | Return | -| `[intent](payload)` | Readable intent with executable payload | -| `access(c, k)` | Collection read | -| `- [intent](for items as item)` | Explicit traversal | -| `1.` / `2.` | Branches; numbered * is else | -| GFM table | Data: one column list, one row record, @ row records | - -Read [the executable programming guide](../../doc/library-development.mq.md) -before authoring. Its actual callable examples demonstrate inline computation, -structured results, defaults and recoverable native file reads. Use -[the development entry](../marqdo-dev/index.mq.md) and its file tools for source -work, and [the release entry](../marqdo-release/index.mq.md) for an authorized -release. These mq.md files are the working instructions and tools; do not rebuild -a parallel command playbook in SKILL.md. - -Call the actual file and heading with `marqdo call`. In a source checkout use -the built `target/debug/marqdo`; prepare its engineering plugin through the -development entry. Large structured inputs use --args-json FILE or stdin; -JSON strings stay literal during call-session replay. --require-ok makes failed -Results stop external automation while preserving their returned evidence. -Read each function's parameter/return tables and effect contract before calling. - -Author programs as readable explanations: useful narrative exceeds half of -each callable unit; parameter and return tables immediately follow its heading; -inline assignments, actions and returns explain their purpose. Standard libraries -remain single-file handbooks. Multi-file projects and extensions use index.mq.md. -GFM describes data, public helpers describe operations, and components recursively -split web layouts until their content leaves are ordinary Markdown. - -Native Marqdo capabilities handle file reading/writing, tables, parsing, hashing -and network reads. Add an extension for a reusable capability gap or call an -explicit existing external tool with argument arrays. Keep decisions, retries -and the execution flow in mq.md. Do not generate Python or shell programs for -already available native operations. OS processes and plugins retain their OS -authority; an fs-root does not sandbox their own access. - -Use the current [web entry](../../ext/web/index.mq.md) for Document, Endpoint and -Resource artifacts, or [quantum entry](../../ext/quantum/index.mq.md) for circuit -workflows. Do not restore removed compose_* or app.configure APIs. Preserve -intentional fixtures and [classic migration context](migration-classic.md). -Validate the real calls and error paths; a narrative ratio or uploaded asset -alone is never functional evidence. diff --git a/skills/marqdo/examples.md b/skills/marqdo/examples.md deleted file mode 100755 index 6d29a72..0000000 --- a/skills/marqdo/examples.md +++ /dev/null @@ -1,5 +0,0 @@ -# Marqdo executable examples - -The maintained programming rules and runnable examples live in [the executable programming guide](../../doc/library-development.mq.md). Read its parameter and return contracts, then call the actual source heading. [The development entry](../marqdo-dev/index.mq.md) provides native file operations and verification tasks; [the release entry](../marqdo-release/index.mq.md) provides publication workflows. - -Use [the recursive Markdown web example](../../examples/web-layout-handbook/index.mq.md) and [the quantum workflow](../../examples/quantum-entanglement/index.mq.md) for domain development. Their real source is the manual. [Classic migration context](migration-classic.md) remains for explicitly historical syntax; new programs use readable occlusion and access(collection, key). Do not copy a second fenced program from this discovery note. diff --git a/skills/marqdo/migration-classic.md b/skills/marqdo/migration-classic.md deleted file mode 100755 index 79922ce..0000000 --- a/skills/marqdo/migration-classic.md +++ /dev/null @@ -1,12 +0,0 @@ -# Classic markup migration card (not default) - -Use this card **only** when editing files that declare `markup: classic` / `标记: 经典`, or when the CLI is run with `--legacy-markup`. New documents must use Occlusion (see SKILL.md CORE SYNTAX). - -| Classic (legacy) | Occlusion / current | -|---|---| -| `[key](map)` index read | `access(map, "key")` / `取(map, "key")` | -| `- [item](coll)` foreach by index form | `- [描述](遍历 coll 为 item)` | -| Teach `**…**` as “the return of print” | Print with `> print`; `**…**` is return/code expression | -| Default link = index | Default `[描述](payload)` = occlusion; `[]` never executes | - -Do not place Classic rules in the front of the default Skill pack. After migration, remove `markup: classic` and verify with `marqdo run` / `marqdo check`. diff --git a/skills/marqdo/reference.md b/skills/marqdo/reference.md deleted file mode 100755 index e81b7e2..0000000 --- a/skills/marqdo/reference.md +++ /dev/null @@ -1,32 +0,0 @@ -# Marqdo executable reference - -The maintained programming rules and runnable examples live in [the executable programming guide](../../doc/library-development.mq.md). Read its parameter and return contracts, then call the actual source heading. [The development entry](../marqdo-dev/index.mq.md) provides native file operations and verification tasks; [the release entry](../marqdo-release/index.mq.md) provides publication workflows. - -Use [the recursive Markdown web example](../../examples/web-layout-handbook/index.mq.md) and [the quantum workflow](../../examples/quantum-entanglement/index.mq.md) for domain development. Their real source is the manual. [Classic migration context](migration-classic.md) remains for explicitly historical syntax; new programs use readable occlusion and access(collection, key). Do not copy a second fenced program from this discovery note. - -## Theorem tables (`marqdo prove`, CLI 2.8.0+) - -A knowledge function may carry a theorem table before its first executable -statement. Place it right under the parameter list: - -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 大额必经人工 | 包含(轨迹, "工单.创建") | 金额 > 10000 | auto | - -- `结论` grammar: `结果.ok = True/False`, `包含(轨迹, "操作名")`, - `长度(轨迹) ⋈ n`, `参数 ⋈ 常量`, combined with 且/或/非. `轨迹` names the - operation trace by the link's display text; `结果` is the returned value. -- `前提` restricts the claim's scope (same comparison grammar). Keep it a - single-variable linear condition. -- `策略` is `auto` (generated proof script) or `none` (theorem generated but - not proven — honest `unverified`). - -Judge with `marqdo prove 文件.mq.md --json`. Statuses, strongest first: -`proved` (Lean confirms) > `checked` (offline symbolic execution closed the -path — advisory, never a proof) > `unverified` (outside the provable subset) -> `rejected` (subset check refused) > `unproved` (counterexample found, e.g. -`金额 = 10001`) > `error`. Without a Lean toolchain the run stays honest at -`checked`/`unverified` and exits 0; `--require-lean` makes unjudged statuses -exit 2 for CI. Never weaken a failing claim to make it pass — fix the claim -or the code, and let `proof.divergence` stop the line when the offline -judger and Lean disagree. Full contract: [design/prove-cli.md](../../doc/design/prove-cli.md). diff --git a/spike/.gitignore b/spike/.gitignore deleted file mode 100755 index 17cd2fc..0000000 --- a/spike/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.venv/ -__pycache__/ -*.pyc -.pytest_cache/ diff --git a/spike/README.md b/spike/README.md deleted file mode 100755 index cf7827c..0000000 --- a/spike/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Marqdo Spike(Python) - -快速验收 ADR 0001 中的 S1–S5,**不是**完整解释器。 - -```bash -cd spike -python -m venv .venv -# Windows: -.\.venv\Scripts\activate -pip install -r requirements.txt -pytest -q -``` - -若需代理:`pip install -r requirements.txt --proxy http://127.0.0.1:7890` diff --git a/spike/REPORT.md b/spike/REPORT.md deleted file mode 100755 index 1a4ffe6..0000000 --- a/spike/REPORT.md +++ /dev/null @@ -1,35 +0,0 @@ -# Spike 报告:Python + markdown-it-py(S1–S5) - -| | | -|---|---| -| 日期 | 2026-08-04 | -| 状态 | **通过** | -| 命令 | `cd spike && pytest -q` → `6 passed` | - ---- - -## 结果 - -| ID | 项 | 结果 | 备注 | -|----|----|------|------| -| S1 | `*` vs `**` | 通过 | `em_*` / `strong_*` 在 inline children 中 | -| S2 | `-` vs `+` | 通过 | **行扫描** `scan_bullets` 保留项目符;库只保证有 `bullet_list` | -| S3 | 单列表格 | 通过 | `table` 规则开启后可解析 | -| S4 | FM `---` vs 正文 `---` | 通过 | 自研 `split_front_matter` | -| S5 | FM 内 `> *.mq.md` | 通过 | 行正则抽取,不整块丢给严格 YAML | - ---- - -## 对实现的含义 - -1. **行扫描是必需层**:`-`/`+` 消歧、frontmatter 导入、注释行分类,不宜只靠 MD 库 AST。 -2. **markdown-it-py** 足够做块/inline 结构(标题、表、强调、列表);避免 `gfm-like` 默认 `linkify`(缺可选依赖会炸)。 -3. Spike **不**等于选定长期实现语言;仅证明 Python 路径可验证宪法。参考实现可继续 Python,或再评 TS/Rust。 - ---- - -## 建议下一步 - -1. 将 ADR 0001 中 Spike 标为通过。 -2. 拍板:参考实现是否 **继续 Python**(推荐,与 Spike 同栈)或换栈。 -3. 再搭建正式包(`src/marqdo`)与 `marqdo run`,按 examples 金样例推进。 diff --git a/spike/marqdo_spike.py b/spike/marqdo_spike.py deleted file mode 100755 index 86d4421..0000000 --- a/spike/marqdo_spike.py +++ /dev/null @@ -1,78 +0,0 @@ -""" -Spike helpers: GFM parse via markdown-it-py + line-level bullet probe. -""" - -from __future__ import annotations - -import re -from dataclasses import dataclass - -from markdown_it import MarkdownIt -from mdit_py_plugins.front_matter import front_matter_plugin - - -def make_md() -> MarkdownIt: - # Avoid gfm-like's linkify (needs optional linkify-it-py). - md = MarkdownIt("commonmark", {"html": False, "linkify": False}) - md.enable(["table"]) - md.use(front_matter_plugin) - return md - - -@dataclass -class BulletLine: - line_no: int - marker: str # "-" | "+" | "*" | "1." - text: str - - -_BULLET = re.compile( - r"^(?P\s*)(?P[-+*]|\d+\.)\s+(?P.*)$" -) - - -def scan_bullets(source: str) -> list[BulletLine]: - """Line-level scan: preserves '-' vs '+' regardless of MD library.""" - out: list[BulletLine] = [] - for i, line in enumerate(source.splitlines(), start=1): - m = _BULLET.match(line) - if not m: - continue - out.append( - BulletLine(line_no=i, marker=m.group("marker"), text=m.group("text")) - ) - return out - - -def parse_tokens(source: str): - return make_md().parse(source) - - -def split_front_matter(source: str) -> tuple[str | None, str]: - """ - Split leading --- ... --- front matter from body. - Body-internal --- is left untouched. - """ - if not source.startswith("---"): - return None, source - lines = source.splitlines(keepends=True) - if not lines or lines[0].strip() != "---": - return None, source - for i in range(1, len(lines)): - if lines[i].strip() == "---": - fm = "".join(lines[1:i]) - body = "".join(lines[i + 1 :]) - return fm, body - return None, source - - -_IMPORT = re.compile(r"^>\s*(?P\S+\.mq\.md)\s*$") - - -def front_matter_imports(fm: str) -> list[str]: - paths: list[str] = [] - for line in fm.splitlines(): - m = _IMPORT.match(line.strip()) - if m: - paths.append(m.group("path")) - return paths diff --git a/spike/requirements.txt b/spike/requirements.txt deleted file mode 100755 index e5a62a3..0000000 --- a/spike/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -markdown-it-py>=3.0,<4 -mdit-py-plugins>=0.4,<1 -pytest>=8.0,<9 diff --git a/spike/test_s1_s5.py b/spike/test_s1_s5.py deleted file mode 100755 index 87738cf..0000000 --- a/spike/test_s1_s5.py +++ /dev/null @@ -1,104 +0,0 @@ -"""ADR 0001 Spike acceptance: S1–S5.""" - -from __future__ import annotations - -from marqdo_spike import ( - front_matter_imports, - parse_tokens, - scan_bullets, - split_front_matter, -) - - -def test_s1_emphasis_vs_strong(): - """S1: *a* vs **a** yield distinct inline marks.""" - src = "hello *em* and **strong** end\n" - tokens = parse_tokens(src) - inlines = [t for t in tokens if t.type == "inline"] - assert inlines, "expected inline token" - children = inlines[0].children or [] - types = [c.type for c in children] - assert "em_open" in types and "em_close" in types - assert "strong_open" in types and "strong_close" in types - assert any(c.type == "text" and c.content == "em" for c in children) - assert any(c.type == "text" and c.content == "strong" for c in children) - - -def test_s2_bullet_minus_vs_plus_line_scan(): - """S2: line scan distinguishes '-' (loop) vs '+' (branch).""" - src = """ -# main - -- loop item -+ branch item -""" - bullets = scan_bullets(src) - markers = [b.marker for b in bullets] - assert "-" in markers - assert "+" in markers - assert bullets[0].marker == "-" - assert bullets[1].marker == "+" - - -def test_s2_library_list_tokens_exist(): - """S2b: library at least parses both as lists (bullet char may need line scan).""" - src = "- a\n\n+ b\n" - tokens = parse_tokens(src) - assert any(t.type == "bullet_list_open" for t in tokens) - - -def test_s3_single_column_table(): - """S3: GFM single-column table.""" - src = """ -| 果 | -|----| -| 苹果 | -| 梨 | -""" - tokens = parse_tokens(src) - assert any(t.type == "table_open" for t in tokens) - texts = [t.content for t in tokens if t.type == "inline"] - flat = " ".join(texts) - assert "果" in flat - assert "苹果" in flat - assert "梨" in flat - - -def test_s4_front_matter_vs_body_hr(): - """S4: file-level --- front matter vs body --- frame.""" - src = """--- -title: demo ---- - -# main - ---- -+ `x` > 0 - > 输出 内容=正 ---- -""" - fm, body = split_front_matter(src) - assert fm is not None - assert "title: demo" in fm - assert body.lstrip().startswith("# main") - assert "---" in body - assert "+ `x` > 0" in body - # Body still has its own ---; must not be eaten by FM splitter - assert body.count("---") >= 2 - - -def test_s5_front_matter_mq_imports(): - """S5: `> file.mq.md` lines inside front matter.""" - src = """--- -title: main -> utils.mq.md -> lib/math.mq.md ---- - -# main -""" - fm, body = split_front_matter(src) - assert fm is not None - imports = front_matter_imports(fm) - assert imports == ["utils.mq.md", "lib/math.mq.md"] - assert "# main" in body diff --git a/src/aliases.rs b/src/aliases.rs deleted file mode 100755 index 51397ab..0000000 --- a/src/aliases.rs +++ /dev/null @@ -1,227 +0,0 @@ -//! Canonical names and Chinese aliases for L0 keywords / builtins / params. -//! -//! See `doc/design/keywords-i18n.md`. No language mode — aliases are equivalent. - -/// Map a literal / logic keyword to its English canonical form, if reserved. -pub fn canonical_keyword(name: &str) -> Option<&'static str> { - match name { - "True" | "真" => Some("True"), - "False" | "假" => Some("False"), - "None" | "空" => Some("None"), - "and" | "且" => Some("and"), - "or" | "或" => Some("or"), - "not" | "非" => Some("not"), - _ => None, - } -} - -pub fn is_reserved_keyword(name: &str) -> bool { - canonical_keyword(name).is_some() -} - -/// Map a builtin callee (EN or ZH alias) to its English canonical name. -/// Host primitives without ZH L0 aliases only match English. -pub fn canonical_builtin(name: &str) -> Option<&'static str> { - if let Some(h) = crate::host::HostFn::from_name(name) { - return Some(h.name()); - } - match name { - "print" | "打印" => Some("print"), - "input" | "输入" => Some("input"), - "len" | "长度" => Some("len"), - "str" | "文本" => Some("str"), - "int" | "整数" => Some("int"), - "type" => Some("type"), - "trim" => Some("trim"), - "split" => Some("split"), - "join" => Some("join"), - "at" => Some("at"), - "call_fn" | "调用" => Some("call_fn"), - _ => None, - } -} - -/// Normalize a named-argument key for a builtin to the English param name. -pub fn canonical_param(builtin: &str, param: &str) -> String { - let b = canonical_builtin(builtin).unwrap_or(builtin); - match (b, param) { - ("print", "text" | "内容") => "text".into(), - ("input", "prompt" | "提示") => "prompt".into(), - ("len" | "str" | "int" | "type" | "trim", "value" | "值") => "value".into(), - ("split" | "join", "value" | "值") => "value".into(), - ("split" | "join", "sep" | "分隔") => "sep".into(), - ("at", "value" | "值") => "value".into(), - ("at", "index" | "下标") => "index".into(), - ("call_fn", "name" | "名") => "name".into(), - ( - "host_writeback_record" | "host_writeback_get" | "host_writeback_clear", - "key" | "键", - ) => "key".into(), - ("host_writeback_ensure", "key" | "键") => "key".into(), - ( - "host_writeback_ensure", - "placeholder" | "占位", - ) => "placeholder".into(), - ( - "host_writeback_record" | "host_writeback_get" | "host_writeback_clear", - "at_end" | "末尾", - ) => "at_end".into(), - ( - "host_writeback_record" - | "host_writeback_get" - | "host_writeback_clear" - | "host_writeback_ensure", - "line" | "行", - ) => "line".into(), - ( - "host_writeback_record", - "value" | "值", - ) => "value".into(), - ( - "host_plot" | "host_plot_points" | "host_plot_conic", - "grid" | "网格", - ) => "grid".into(), - ("host_plot" | "host_plot_points" | "host_plot_conic", "path" | "路径") => { - "path".into() - } - ("host_dotenv_load" | "load_dotenv", "path" | "路径") => "path".into(), - ("host_meta_get" | "meta_get", "key" | "键") => "key".into(), - ("host_exec" | "exec", "cmd" | "命令") => "cmd".into(), - ("host_exec" | "exec", "args" | "参数") => "args".into(), - ("host_exec" | "exec", "capture" | "捕获") => "capture".into(), - ( - "host_stream_publish" | "stream_publish", - "event" | "事件", - ) => "event".into(), - ( - "host_http_get" | "http_get" | "host_http_post" | "http_post" | "host_http_post_sse" - | "http_post_sse" | "host_http_request" | "http_request", - "headers" | "头", - ) => "headers".into(), - ( - "host_http_post" | "http_post" | "host_http_post_sse" | "http_post_sse" - | "host_http_request" | "http_request", - "content_type" | "类型", - ) => "content_type".into(), - ( - "host_http_get" | "http_get" | "host_http_post" | "http_post" | "host_http_post_sse" - | "http_post_sse" | "host_http_request" | "http_request", - "url" | "地址", - ) => "url".into(), - ( - "host_http_post" | "http_post" | "host_http_post_sse" | "http_post_sse" - | "host_http_request" | "http_request", - "body" | "内容", - ) => "body".into(), - ( - "host_http_post_sse" | "http_post_sse" | "host_openai_sse_parse" | "openai_sse_parse", - "echo" | "打印增量" | "print_deltas", - ) => "echo".into(), - ( - "host_openai_sse_parse" | "openai_sse_parse", - "text" | "内容", - ) => "text".into(), - ("host_json_stringify" | "stringify", "indent" | "缩进") => "indent".into(), - ("host_plot", "steps" | "步数") => "steps".into(), - ("host_plot", "derivative" | "导数") => "derivative".into(), - ("host_foreign_run" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_eval", "code" | "代码") => "code".into(), - ( - "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" - | "host_foreign_call", - "stdin" | "标准输入", - ) => "stdin".into(), - ( - "host_foreign_set_cmd" - | "host_foreign_run_lang" - | "host_foreign_invoke" - | "host_foreign_probe" - | "host_foreign_register" - | "host_foreign_unset" - | "host_foreign_call" - | "host_foreign_call_many" - | "host_foreign_session_open", - "lang" | "语言", - ) => "lang".into(), - ( - "host_foreign_set_cmd" - | "host_foreign_invoke" - | "host_foreign_register" - | "host_foreign_call_many" - | "host_foreign_session_open", - "cmd" | "命令", - ) => "cmd".into(), - ("host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_eval", "source" | "源码") => "source".into(), - ( - "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_open" | "host_foreign_session_eval", - "env" | "环境", - ) => "env".into(), - ( - "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_open" | "host_foreign_session_eval", - "cwd" | "工作目录", - ) => "cwd".into(), - ( - "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_open" | "host_foreign_session_eval", - "timeout" | "超时", - ) => "timeout".into(), - ( - "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" - | "host_foreign_register" | "host_foreign_call" | "host_foreign_call_many", - "args" | "参数", - ) => "args".into(), - ( - "host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call_many", - "max_output" | "最大输出", - ) => "max_output".into(), - ("host_foreign_invoke" | "host_foreign_call" | "host_foreign_session_eval", "input" | "输入") => "input".into(), - ("host_foreign_session_eval" | "host_foreign_session_set" | "host_foreign_session_get" | "host_foreign_session_names" | "host_foreign_session_close", "id" | "标识") => "id".into(), - ("host_foreign_session_set" | "host_foreign_session_get", "name" | "名称") => "name".into(), - ("host_foreign_session_set", "value" | "值") => "value".into(), - ("host_foreign_invoke", "output" | "输出") => "output".into(), - ("host_foreign_invoke", "keep" | "保留") => "keep".into(), - ("host_foreign_register", "template" | "模板") => "template".into(), - ("host_foreign_register", "ext" | "扩展名") => "ext".into(), - ("host_foreign_register", "version_args" | "版本参数") => "version_args".into(), - ("host_foreign_load_config", "path" | "路径") => "path".into(), - ("host_foreign_run_many", "runs" | "任务表") => "runs".into(), - ("host_foreign_call_many", "inputs" | "输入表") => "inputs".into(), - ("host_foreign_run_many" | "host_foreign_call_many", "concurrency" | "并发") => "concurrency".into(), - ("host_ext_native_path", "name" | "名") => "name".into(), - _ => param.to_string(), - } -} - -/// Rewrite callee + named args to English canonical forms when this is a builtin. -/// Returns the callee to dispatch on (canonical builtin or original user/fn name). -pub fn normalize_call_callee_and_args(callee: &str, args: &mut [crate::ast::Arg]) -> String { - match canonical_builtin(callee) { - Some(canon) => { - for a in args.iter_mut() { - if let crate::ast::Arg::Named { name, .. } = a { - *name = canonical_param(canon, name); - } - } - canon.to_string() - } - None => callee.to_string(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn keyword_aliases() { - assert_eq!(canonical_keyword("真"), Some("True")); - assert_eq!(canonical_keyword("且"), Some("and")); - assert!(is_reserved_keyword("空")); - } - - #[test] - fn builtin_aliases() { - assert_eq!(canonical_builtin("打印"), Some("print")); - assert_eq!(canonical_builtin("长度"), Some("len")); - assert_eq!(canonical_param("打印", "内容"), "text"); - assert_eq!(canonical_param("print", "内容"), "text"); - } -} diff --git a/src/application_tests.rs b/src/application_tests.rs deleted file mode 100755 index efbf327..0000000 --- a/src/application_tests.rs +++ /dev/null @@ -1,293 +0,0 @@ -//! Application compositions with precomputed independent SQL/Floyd oracles. -use crate::host::{ - foreign_doc::{packing, DocumentSession}, - json::{json_to_value, value_to_json}, -}; -use crate::value::Value; -use serde_json::{json, Value as Json}; -use sha2::{Digest, Sha256}; -use std::path::{Path, PathBuf}; - -fn root() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) -} -fn cases() -> Vec { - let path = std::env::var_os("MARQDO_APPLICATION_CASES") - .map(PathBuf::from) - .unwrap_or_else(|| root().join("tests/applications/CASES.json")); - let rows: Vec = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); - assert!(!rows.is_empty()); - rows -} -fn out() -> PathBuf { - let path = std::env::var_os("MARQDO_APPLICATION_ARTIFACT_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| root().join("target/applications")); - std::fs::create_dir_all(&path).unwrap(); - path -} -fn code(case: &Json, stage: &str) -> String { - let lang = if stage == "producer" { - case["producer"].as_str().unwrap() - } else { - case["consumer"].as_str().unwrap() - }; - let ext = if lang == "python" { "py" } else { "js" }; - std::fs::read_to_string( - root() - .join("tests/applications") - .join(case["family"].as_str().unwrap()) - .join(format!("{stage}.{ext}")), - ) - .unwrap() -} -fn failure(lang: &str) -> &'static str { - if lang == "python" { - "retained = answer\nraise RuntimeError('application_expected_failure')" - } else { - "globalThis.retained = answer; throw new Error('application_expected_failure');" - } -} -fn mutate(lang: &str) -> &'static str { - if lang == "python" { - "bridge = None\nNone" - } else { - "bridge = null; null;" - } -} -fn field<'a>(value: &'a Value, name: &str) -> &'a Value { - let Value::Map(fields) = value else { - panic!("expected record: {value:?}") - }; - &fields.iter().find(|(k, _)| k == name).unwrap().1 -} -fn save(path: &Path, value: &Json) { - std::fs::write(path, serde_json::to_vec_pretty(value).unwrap()).unwrap(); -} - -#[test] -fn compositions_preserve_data_failure_recovery_and_copy_isolation_on_both_backends() { - let out = out(); - let rows = cases(); - for case in &rows { - let id = case["id"].as_str().unwrap(); - let q = |s: &str| serde_json::to_string(s).unwrap(); - let input = q(&case["input"].to_string()); - let family = root().join("lib"); - let consumer = case["consumer"].as_str().unwrap(); - let source = format!( - r#"--- -markup: occlusion -import: - foreign: {foreign} - json: {json} ---- -# main -**data = > json.parse text={input}** -**p = > foreign.session_open lang={producer}** -**c = > foreign.session_open lang={consumer}** -**> foreign.session_set id=`p` name="data" value=`data`** -**first = > evaluate target=`p` source={produce}** -**bridge = > foreign.session_get id=`p` name="bridge"** -**> foreign.session_set id=`c` name="bridge" value=`bridge`** -**second = > evaluate target=`c` source={consume}** -**failure = > evaluate target=`c` source={failure}** -**kept = > foreign.session_get id=`c` name="retained"** -**cleared = > evaluate target=`c` source={mutate}** -**empty = > foreign.session_get id=`c` name="bridge"** -**original = > foreign.session_get id=`p` name="bridge"** -**answer = > foreign.session_get id=`c` name="answer"** -**> foreign.session_close id=`p`** -**> foreign.session_close id=`c`** -*answer* - -## evaluate - + `target` - + `source` -**record = > foreign.session_eval id=`target` source=`source`** -*record* -"#, - foreign = family.join("foreign.mq.md").display(), - json = family.join("json.mq.md").display(), - producer = q(case["producer"].as_str().unwrap()), - consumer = q(consumer), - produce = q(&code(case, "producer")), - consume = q(&code(case, "consumer")), - failure = q(failure(consumer)), - mutate = q(mutate(consumer)) - ); - let path = out.join(format!("{id}.mq.md")); - std::fs::write(&path, &source).unwrap(); - let module = crate::load::load_module(&path).unwrap(); - let mut executions = Vec::new(); - for backend in ["tree", "bytecode"] { - let (result, stdout, (journal, protocol, live)) = if backend == "tree" { - let mut tree = crate::interp::Interpreter::with_capture(Some(&path), false); - let result = tree.run_module(&module); - ( - result, - tree.captured_stdout.clone(), - tree.application_evidence(), - ) - } else { - let program = crate::bytecode::compile_module(Some(&path), &module).unwrap(); - let mut vm = crate::bytecode::Vm::with_capture(Some(&path)); - let result = vm.run(&program); - ( - result, - vm.captured_stdout.clone(), - vm.application_evidence(), - ) - }; - let error = result.as_ref().err().map(|e| e.to_string()); - let actual = result.ok().map(|v| value_to_json(&v).unwrap()); - executions.push(json!({"backend":backend,"ok":error.is_none(),"error":error,"result":actual,"stdout":stdout,"live_sessions":live, - "journal":value_to_json(&Value::List(journal)).unwrap(),"protocol":protocol.iter().map(|p|json!({"session":p.session,"request":p.request,"response":p.response})).collect::>()})); - } - let result = json!({"version":1,"kind":"document","case":case,"source":source,"source_sha256":format!("{:x}",Sha256::digest(source.as_bytes())),"executions":executions}); - save(&out.join(format!("{id}-document.json")), &result); - for execution in result["executions"].as_array().unwrap() { - assert_eq!(execution["result"], case["answer"], "{id}: {execution}"); - assert_eq!(execution["ok"], true, "{id}: {execution}"); - assert_eq!(execution["stdout"], ""); - assert_eq!(execution["live_sessions"], 0); - } - } - println!( - "APPLICATION_METRIC:{}", - json!({"cases":rows.len(),"executions":rows.len()*2}) - ); -} - -#[test] -fn application_action_histories_replay_raw_and_packed_after_failure() { - let out = out(); - let rows = cases(); - for case in &rows { - let id = case["id"].as_str().unwrap(); - let consumer = case["consumer"].as_str().unwrap(); - let source=format!("---\nimport:\n foreign: {}\n---\n# main\n\n`会话` = > foreign.session\n\n`produce` =\n```{}\n{}\n```\n\n`consume` =\n```{}\n{}\n```\n\n`failure` =\n```{}\n{}\n```\n\n`mutate` =\n```{}\n{}\n```\n",root().join("lib/foreign.mq.md").display(),case["producer"].as_str().unwrap(),code(case,"producer"),consumer,code(case,"consumer"),consumer,failure(consumer),consumer,mutate(consumer)); - let path = out.join(format!("{id}-interactive.mq.md")); - std::fs::write(&path, &source).unwrap(); - let mut session = DocumentSession::open(&path, &root()).unwrap(); - let p = session - .cells - .iter() - .find(|c| c.name == "produce") - .unwrap() - .kernel - .clone(); - let c = session - .cells - .iter() - .find(|c| c.name == "consume") - .unwrap() - .kernel - .clone(); - let expected = json_to_value(&case["answer"]).unwrap(); - session - .set_value(&p, "data", json_to_value(&case["input"]).unwrap()) - .unwrap(); - let first = session.run_cell("produce", None).unwrap(); - assert_eq!(field(&first, "ok"), &Value::Bool(true), "{id}: {first:?}"); - let bridge = session.pull_value(&p, "bridge").unwrap(); - assert_eq!(value_to_json(&bridge).unwrap(), case["bridge"]); - session.set_value(&c, "bridge", bridge.clone()).unwrap(); - let second = session.run_cell("consume", None).unwrap(); - assert_eq!(field(&second, "result"), &expected, "{id}: {second:?}"); - let failed = session.run_cell("failure", None).unwrap(); - assert_eq!(field(&failed, "ok"), &Value::Bool(false)); - assert_eq!( - session - .cells - .iter() - .find(|c| c.name == "failure") - .unwrap() - .last_result, - Value::None - ); - assert_eq!(session.pull_value(&c, "retained").unwrap(), expected); - session.run_cell("mutate", None).unwrap(); - assert_eq!( - session - .cells - .iter() - .find(|c| c.name == "mutate") - .unwrap() - .last_result, - Value::None - ); - assert_eq!(session.pull_value(&c, "bridge").unwrap(), Value::None); - assert_eq!(session.pull_value(&p, "bridge").unwrap(), bridge); - assert_eq!(session.pull_value(&c, "answer").unwrap(), expected); - let snapshot = session.export_snapshot().unwrap(); - session.close(); - let packed = packing::pack(&snapshot).unwrap(); - assert_eq!( - value_to_json(&packing::unpack(&packed).unwrap()).unwrap(), - value_to_json(&snapshot).unwrap() - ); - let raw_check = - DocumentSession::check_snapshot_isolated(&path, &root(), &snapshot).unwrap(); - let packed_check = - DocumentSession::check_snapshot_isolated(&path, &root(), &packed).unwrap(); - save( - &out.join(format!("{id}-interactive.json")), - &json!({"version":1,"kind":"interactive","case":case,"source":source,"source_sha256":format!("{:x}",Sha256::digest(source.as_bytes())),"snapshot":value_to_json(&snapshot).unwrap(),"packed":value_to_json(&packed).unwrap(),"raw_check":value_to_json(&raw_check).unwrap(),"packed_check":value_to_json(&packed_check).unwrap()}), - ); - assert_eq!( - field(&raw_check, "ok"), - &Value::Bool(true), - "{id}: {raw_check:?}" - ); - assert_eq!( - field(&packed_check, "ok"), - &Value::Bool(true), - "{id}: {packed_check:?}" - ); - } - println!( - "APPLICATION_REPLAY_METRIC:{}", - json!({"cases":rows.len(),"strict_replays":rows.len()*2}) - ); -} - -#[test] -fn explicit_null_and_stdout_remain_distinct_and_only_success_can_persist() { - for lang in ["python", "node"] { - let (good, bad) = if lang == "python" { - ( - "print('audit')\nNone", - "print('failed audit')\nraise RuntimeError('expected_failure')", - ) - } else { - ( - "console.log('audit'); null;", - "console.log('failed audit'); throw Error('expected_failure');", - ) - }; - let path = out().join(format!("null-persist-{lang}-{}.mq.md", std::process::id())); - std::fs::write(&path,format!("---\nimport:\n foreign: {}\n---\n# main\n\n`会话` = > foreign.session\n\n`good` =\n```{lang}\n{good}\n```\n\n`bad` =\n```{lang}\n{bad}\n```\n",root().join("lib/foreign.mq.md").display())).unwrap(); - let mut session = DocumentSession::open(&path, &root()).unwrap(); - assert!(session.persist_cell("good", "empty").is_err()); - session.run_cell("good", None).unwrap(); - let cell = session.cells.iter().find(|c| c.name == "good").unwrap(); - assert_eq!(cell.last_result, Value::None); - assert_eq!(cell.last_stdout, "audit\n"); - assert_eq!(session.oracle_journal.last().unwrap().value, Value::None); - assert_eq!(session.oracle_journal.last().unwrap().result, Value::None); - session.persist_cell("good", "empty").unwrap(); - session.run_cell("bad", None).unwrap(); - assert_eq!( - session - .cells - .iter() - .find(|c| c.name == "bad") - .unwrap() - .last_result, - Value::None - ); - assert!(session.persist_cell("bad", "must_not_write").is_err()); - session.close(); - } -} diff --git a/src/arguments.rs b/src/arguments.rs deleted file mode 100755 index 9a95a3f..0000000 --- a/src/arguments.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Value-independent argument binding. Effects finish before this plan is used. -use std::collections::HashMap; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct ArgumentPlan { - pub parameters: Vec>, - pub assignments: Vec<(String, usize)>, -} -pub(crate) fn plan( - params: &[String], - names: &[Option], - allow_missing: bool, -) -> Result { - plan_with(params, names, |_| allow_missing) -} - -pub(crate) fn plan_with_omissions( - params: &[String], - names: &[Option], - omissions: &[bool], -) -> Result { - if params.len() != omissions.len() { - return Err("argument omission mask count mismatch".into()); - } - plan_with(params, names, |index| omissions[index]) -} - -fn plan_with( - params: &[String], - names: &[Option], - may_omit: impl Fn(usize) -> bool, -) -> Result { - let mut named = HashMap::new(); - let mut positionals = Vec::new(); - for (index, name) in names.iter().enumerate() { - match name { - Some(name) => { - if named.insert(name.clone(), index).is_some() { - return Err(format!("duplicate named argument `{name}`")); - } - } - None => positionals.push(index), - } - } - let mut pos = 0; - let mut parameters = Vec::new(); - let mut assignments = Vec::new(); - for (parameter_index, param) in params.iter().enumerate() { - let index = if let Some(index) = named.get(param) { - Some(*index) - } else if let Some(index) = positionals.get(pos) { - pos += 1; - Some(*index) - } else if may_omit(parameter_index) { - None - } else { - return Err(format!("missing argument for parameter `{param}`")); - }; - parameters.push(index); - if let Some(index) = index { - assignments.push((param.clone(), index)); - } - } - if pos < positionals.len() { - return Err(format!( - "too many positional arguments ({} extra)", - positionals.len() - pos - )); - } - for (index, name) in names.iter().enumerate() { - if let Some(name) = name { - if !params.contains(name) { - assignments.push((name.clone(), index)); - } - } - } - Ok(ArgumentPlan { - parameters, - assignments, - }) -} -pub(crate) fn bind( - params: &[String], - names: &[Option], - values: &[T], - allow_missing: bool, -) -> Result, String> { - if names.len() != values.len() { - return Err("argument layout/value count mismatch".into()); - } - let plan = plan(params, names, allow_missing)?; - Ok(plan - .assignments - .into_iter() - .map(|(name, index)| (name, values[index].clone())) - .collect()) -} - -pub(crate) fn plan_evidence( - params: &[String], - names: &[Option], - omissions: &[bool], -) -> serde_json::Value { - let result = match plan_with_omissions(params, names, omissions) { - Ok(plan) => { - serde_json::json!({"ok":true,"parameters":plan.parameters,"assignments":plan.assignments}) - } - Err(error) => serde_json::json!({"ok":false,"error":error}), - }; - serde_json::json!({"params":params,"arguments":names,"omissions":omissions,"result":result}) -} -pub(crate) fn builtin_signature(name: &str) -> Option<(&'static [&'static str], bool)> { - Some(match name { - "print" => (&["text"], false), - "input" => (&["prompt"], true), - "len" | "str" | "int" | "type" | "trim" => (&["value"], false), - "split" | "join" => (&["value", "sep"], false), - "at" => (&["value", "index"], false), - "call_fn" => (&["name"], false), - _ => return None, - }) -} diff --git a/src/artifact/mod.rs b/src/artifact/mod.rs deleted file mode 100755 index 45cd8a1..0000000 --- a/src/artifact/mod.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! Web / Endpoint Artifact classification from bound Metadata. -//! -//! Spec: `doc/design/ext-web-artifact.md` · ADR 0007. -//! Does not add CORE_CONSTRUCTS — reuses flat frontmatter `type` / `类型`. - -use crate::value::Value; - -/// Kind of executable document recognized for the Web model. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ArtifactKind { - /// `type: web` / `类型: 网页` - Web, - /// `type: endpoint` / `类型: 端点` - Endpoint, - /// `type: prompt` / `类型: 提示` (AI stack; classified for inspect) - Prompt, - /// `type: llm` / other known types - Other, -} - -/// Read `type` or `类型` from bound metadata. -pub fn metadata_type(metadata: &[(String, Value)]) -> Option { - for key in ["type", "类型"] { - if let Some(v) = meta_get(metadata, key) { - let s = v.as_display(); - if !s.is_empty() { - return Some(s); - } - } - } - None -} - -/// Classify artifact kind from metadata (None if no type key). -pub fn classify(metadata: &[(String, Value)]) -> Option { - let t = metadata_type(metadata)?; - Some(match t.as_str() { - "web" | "网页" => ArtifactKind::Web, - "endpoint" | "端点" => ArtifactKind::Endpoint, - "prompt" | "提示" => ArtifactKind::Prompt, - _ => ArtifactKind::Other, - }) -} - -/// True when this module is a Web Document Artifact. -pub fn is_web_document(metadata: &[(String, Value)]) -> bool { - matches!(classify(metadata), Some(ArtifactKind::Web)) -} - -/// True when this module is an Endpoint Artifact. -pub fn is_endpoint(metadata: &[(String, Value)]) -> bool { - matches!(classify(metadata), Some(ArtifactKind::Endpoint)) -} - -/// Lookup a metadata string (EN key, then ZH aliases). -pub fn meta_text(metadata: &[(String, Value)], en: &str, zh: &str) -> Option { - for key in [en, zh] { - if let Some(v) = meta_get(metadata, key) { - let s = v.as_display(); - if !s.is_empty() { - return Some(s); - } - } - } - None -} - -/// Route for a web document: `route` / `路由`, else None. -pub fn web_route(metadata: &[(String, Value)]) -> Option { - meta_text(metadata, "route", "路由") -} - -/// HTTP method defaulting to GET. -pub fn http_method(metadata: &[(String, Value)]) -> String { - meta_text(metadata, "method", "方法").unwrap_or_else(|| "GET".to_string()) -} - -/// Endpoint path: `path` / `路径`. -pub fn endpoint_path(metadata: &[(String, Value)]) -> Option { - meta_text(metadata, "path", "路径") -} - -fn meta_get<'a>(metadata: &'a [(String, Value)], key: &str) -> Option<&'a Value> { - metadata.iter().find(|(k, _)| k == key).map(|(_, v)| v) -} - -/// A Web/Endpoint declaration without a runnable local entry has no executable -/// body. Both backends return the same summary instead of inventing bytecode. -pub fn declaration_summary(module: &crate::ast::Module) -> Option { - if module.functions.iter().any(|f| f.name == "main") - || module - .functions - .iter() - .filter(|f| f.is_object() && f.params.is_empty()) - .count() - == 1 - { - return None; - } - let kind = classify(&module.metadata)?; - let kind_name = match kind { - ArtifactKind::Web => "web", - ArtifactKind::Endpoint => "endpoint", - _ => return None, - }; - let mut fields = vec![ - ("kind".into(), Value::Text(kind_name.into())), - ("method".into(), Value::Text(http_method(&module.metadata))), - ]; - let target = if kind == ArtifactKind::Web { - web_route(&module.metadata) - } else { - endpoint_path(&module.metadata) - }; - if let Some(target) = target { - fields.push(( - if kind == ArtifactKind::Web { - "route" - } else { - "path" - } - .into(), - Value::Text(target), - )); - } - Some(Value::Map(vec![ - ("ok".into(), Value::Bool(true)), - ("value".into(), Value::Map(fields)), - ("error".into(), Value::None), - ])) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::value::Value; - - #[test] - fn classify_web_en_zh() { - let en = vec![("type".into(), Value::Text("web".into()))]; - assert_eq!(classify(&en), Some(ArtifactKind::Web)); - let zh = vec![("类型".into(), Value::Text("网页".into()))]; - assert_eq!(classify(&zh), Some(ArtifactKind::Web)); - } - - #[test] - fn classify_endpoint() { - let m = vec![ - ("type".into(), Value::Text("endpoint".into())), - ("path".into(), Value::Text("/api/x".into())), - ("method".into(), Value::Text("POST".into())), - ]; - assert!(is_endpoint(&m)); - assert_eq!(endpoint_path(&m).as_deref(), Some("/api/x")); - assert_eq!(http_method(&m), "POST"); - } - - #[test] - fn no_type() { - let m = vec![("title".into(), Value::Text("x".into()))]; - assert_eq!(classify(&m), None); - } -} diff --git a/src/ast.rs b/src/ast.rs deleted file mode 100755 index d944c45..0000000 --- a/src/ast.rs +++ /dev/null @@ -1,576 +0,0 @@ -//! Marqdo AST (Phase I). - -use std::collections::HashMap; - -use crate::diagnostics::Span; -use crate::formula::Expr as FormulaExpr; -use crate::value::CodeBlock; - -/// Frontmatter file import under nested `import:\n bind: path.mq.md` (see `doc/design/module-namespace.md`). -#[derive(Debug, Clone)] -pub struct Import { - pub path: String, - pub bind: String, -} - -/// Frontmatter short-name bind under nested `import:\n bind: lib.member` (same map as file import). -#[derive(Debug, Clone)] -pub struct Use { - pub path: Vec, - pub bind: String, -} - -#[derive(Debug, Clone)] -pub struct Module { - pub source: crate::diagnostics::SourceIdentity, - pub imports: Vec, - pub uses: Vec, - pub functions: Vec, - /// Populated by the loader: bind name → imported module (not flattened). - pub import_modules: HashMap, - /// Unresolved Artifact Metadata (from frontmatter); filled by parse. - pub metadata_raw: Vec<(String, crate::binding::MetaValue)>, - /// Bound metadata after load-time Binding resolve (insertion order). - pub metadata: Vec<(String, crate::value::Value)>, -} - -impl Default for Module { - fn default() -> Self { - Self { - source: Default::default(), - imports: Vec::new(), - uses: Vec::new(), - functions: Vec::new(), - import_modules: HashMap::new(), - metadata_raw: Vec::new(), - metadata: Vec::new(), - } - } -} - -/// Parameter names have distinct slots. Function lookup retains its existing -/// first-match/ambiguity rules rather than narrowing accepted declaration trees. -pub(crate) fn validate_parameters(module:&Module) -> Result<(),crate::diagnostics::Diagnostic> { - fn siblings(module:&Module,functions:&[Function]) -> Result<(),crate::diagnostics::Diagnostic> { - for fun in functions { - let mut params=std::collections::HashSet::new(); - for param in &fun.params { - if !params.insert(¶m.name) { - return Err(crate::diagnostics::Diagnostic::new(module.source.path.as_deref(),param.span,format!("duplicate parameter `{}`",param.name)).with_source(&module.source)); - } - } - siblings(module,&fun.children)?; - } - Ok(()) - } - siblings(module,&module.functions)?; - let mut imports=module.import_modules.iter().collect::>();imports.sort_by_key(|(name,_)|*name); - for (_,child) in imports { validate_parameters(child)?; } - Ok(()) -} - -#[derive(Debug, Clone)] -pub struct Param { - pub name: String, - pub span: Span, - pub default: Option, - /// True when collected by v0.3 body/prose inference (not an explicit `+` line). - pub inferred: bool, -} - -#[derive(Debug, Clone)] -pub struct Function { - pub name: String, - /// Heading depth 1–6. Level 1 = object/type; level ≥ 2 = function/method. - pub level: u8, - pub span: Span, - pub params: Vec, - pub body: Vec, - pub children: Vec, - /// Base type name for `# Child = > Parent` (objects only). - pub base: Option, - /// Prose `` `名` `` never read/assigned on the executable surface (not params). - pub dead_binds: Vec, - /// 渐进式契约(T2.1):形参/返回/对象字段契约(附着在文档表上,升参推断前提取)。 - pub contract: Option, - /// 集合契约(T2.1):变量名 → 字段契约(紧邻 `` `名` = `` 绑定之前的文档表)。 - pub var_contracts: HashMap, - /// 定理表(ADR 0010):函数级命题声明;首条可执行语句之前提取,不参与运行。 - pub claims: Vec, - /// Non-executable modular assumptions, never accepted as proven facts. - pub assumptions: Vec, -} - -/// Author-declared operation contract. Call-site obligations must still be -/// proved and callee implementation identity checked before it can be reused. -#[derive(Debug, Clone)] -pub struct Assumption { - pub op: String, - pub premise: Option, - pub postcondition: String, - pub line: u32, -} - -/// 一条定理声明(设计 §7.1):`| 定理 | 结论 | 前提 | 策略 |` 的一行。 -#[derive(Debug, Clone)] -pub struct Claim { - /// 定理 id(函数内唯一;重复由 `check --proof` 报 `proof.claim_duplicate`)。 - pub id: String, - /// 受限表达式文本(参数、`结果`、`轨迹`、三个谓词、算术/比较/布尔)。 - pub conclusion: String, - pub premise: Option, - /// `auto`(默认)或 `none`;其他值由 `check --proof` 报 unsupported。 - pub tactic: Option, - /// 表行所在行号(锚定漂移检测)。 - pub line: u32, -} - -impl Function { - /// `# Name` — object / type (constructor body). - pub fn is_object(&self) -> bool { - self.level == 1 - } -} - -/// Whether this function needs an instance receiver. -/// -/// A direct child of a level-1 object may be an associated function: when its -/// executable body does not read `self` / `自`, it can be invoked through its -/// definition path (`lib.Type.fact`). Child declarations are not traversed; -/// each declaration owns its own receiver requirement. -pub fn function_uses_receiver(fun: &Function) -> bool { - fn is_receiver(name: &str) -> bool { - matches!(name, "self" | "自") - } - - fn call_uses_receiver(call: &CallExpr) -> bool { - call.receiver.as_deref().is_some_and(is_receiver) - || call.path.as_ref().is_some_and(|path| { - path.first().is_some_and(|name| is_receiver(name)) - }) - || call.args.iter().any(|arg| match arg { - Arg::Positional(value) | Arg::Named { value, .. } => expr_uses_receiver(value), - }) - } - - fn expr_uses_receiver(expr: &Expr) -> bool { - match expr { - Expr::Var(name) => is_receiver(name), - Expr::Interp(parts) => parts.iter().any(|part| match part { - InterpPart::Var(name) | InterpPart::Index { base: name, .. } => is_receiver(name), - InterpPart::Lit(_) => false, - }), - Expr::Unary { expr, .. } => expr_uses_receiver(expr), - Expr::Binary { left, right, .. } => { - expr_uses_receiver(left) || expr_uses_receiver(right) - } - Expr::Call(call) => call_uses_receiver(call), - Expr::List(items) => items.iter().any(expr_uses_receiver), - Expr::Map(entries) => entries.iter().any(|(_, value)| expr_uses_receiver(value)), - Expr::Index { base, label } => { - expr_uses_receiver(base) - || matches!(label, IndexKey::Var(name) if is_receiver(name)) - } - Expr::Occluded { payload, .. } => payload.as_deref().is_some_and(expr_uses_receiver), - Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => false, - } - } - - fn stmt_uses_receiver(stmt: &Stmt) -> bool { - match stmt { - Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { - expr_uses_receiver(value) - } - Stmt::Call { call, .. } => call_uses_receiver(call), - Stmt::Branch { arms, .. } => arms.iter().any(|arm| { - arm.condition.as_ref().is_some_and(expr_uses_receiver) - || arm.body.iter().any(stmt_uses_receiver) - }), - Stmt::While { condition, body, .. } => { - expr_uses_receiver(condition) || body.iter().any(stmt_uses_receiver) - } - Stmt::ForEach { collection, body, .. } => { - is_receiver(collection) || body.iter().any(stmt_uses_receiver) - } - } - } - - fun.params.iter().any(|param| param.default.as_ref().is_some_and(expr_uses_receiver)) - || fun.body.iter().any(stmt_uses_receiver) -} - -/// Source line of a statement (every variant carries a span). -pub fn stmt_line(st: &Stmt) -> u32 { - match st { - Stmt::Assign { span, .. } - | Stmt::Return { span, .. } - | Stmt::Call { span, .. } - | Stmt::Expr { span, .. } - | Stmt::Branch { span, .. } - | Stmt::While { span, .. } - | Stmt::ForEach { span, .. } => span.line, - } -} - -/// Depth-first walk over every statement of a function: its body, nested block -/// bodies (branch arms / loops) and child functions. -/// -/// `` slimming: three view modules each re-implemented this recursion; the -/// traversal lives here so collectors only supply the per-statement logic. -pub fn walk_stmts(fun: &Function, f: &mut impl FnMut(&Stmt)) { - fn go(st: &Stmt, f: &mut impl FnMut(&Stmt)) { - f(st); - match st { - Stmt::Branch { arms, .. } => { - for arm in arms { - for b in &arm.body { - go(b, f); - } - } - } - Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { - for b in body { - go(b, f); - } - } - _ => {} - } - } - for st in &fun.body { - go(st, f); - } - for c in &fun.children { - walk_stmts(c, f); - } -} - -#[derive(Debug, Clone)] -pub enum Stmt { - Assign { - name: String, - value: Expr, - span: Span, - /// Inclusive last source line (covers following `$$` fence or table rows). - end_line: u32, - }, - Return { - value: Expr, - span: Span, - }, - /// Statement-form call (`> …`); return value discarded. - Call { - call: CallExpr, - span: Span, - }, - /// Bold expression statement (`**n + 1**`); value evaluated and discarded. - Expr { - value: Expr, - span: Span, - }, - Branch { - arms: Vec, - span: Span, - }, - While { - condition: Expr, - body: Vec, - span: Span, - }, - ForEach { - item: String, - collection: String, - /// `` M3: occlusion form `- [描述](遍历 集合 为 变量)` carries prose. - label: Option, - body: Vec, - span: Span, - }, -} - -#[derive(Debug, Clone)] -pub struct BranchArm { - pub condition: Option, // None = else - pub body: Vec, -} - -#[derive(Debug, Clone)] -pub struct CallExpr { - pub callee: String, - /// Bare library path segments, e.g. `["time","parse"]` for `time.parse`. - /// Mutually exclusive with `receiver` (instance method). - pub path: Option>, - /// When set, `` `recv`.callee `` method call; receiver is a variable name. - pub receiver: Option, - pub args: Vec, - /// Pre-bracket modifiers: `礼貌 [问候] x` → `["礼貌"]`, expanded to `礼貌=True` at eval. - /// See [bracket-call-modifiers.md](../../doc/design/bracket-call-modifiers.md). - pub pre_modifiers: Vec, - /// True when the call was authored with `[callee]` (even with no modifiers). - /// View prefers `修饰 [callee] …` / `[callee] …` over `> callee …` when set. - pub bracket_marked: bool, -} - -impl CallExpr { - /// Shared execution preparation: normalize bare aliases before testing - /// modifier conflicts, matching the source evaluator's binding order. - pub fn for_evaluation(&self) -> Result { - let mut call=self.clone(); - if call.path.is_none() && call.receiver.is_none(){ - call.callee=crate::aliases::normalize_call_callee_and_args(&call.callee,&mut call.args); - } - call.with_modifiers_expanded() - } - /// Fold `pre_modifiers` into leading `name=True` named args (conflicts → Err). - pub fn with_modifiers_expanded(&self) -> Result { - let mut call = self.clone(); - for m in &call.pre_modifiers { - if call - .args - .iter() - .any(|a| matches!(a, Arg::Named { name, .. } if name == m)) - { - return Err(format!( - "pre-bracket modifier `{m}` conflicts with named argument `{m}`" - )); - } - } - if call.pre_modifiers.is_empty() { - return Ok(call); - } - let mut args = Vec::with_capacity(call.pre_modifiers.len() + call.args.len()); - for m in &call.pre_modifiers { - args.push(Arg::Named { - name: m.clone(), - value: Expr::Literal(Literal::Bool(true)), - }); - } - args.append(&mut call.args); - call.args = args; - call.pre_modifiers.clear(); - Ok(call) - } -} - -#[derive(Debug, Clone)] -pub enum Arg { - Positional(Expr), - Named { name: String, value: Expr }, -} - -#[derive(Debug, Clone)] -pub enum Expr { - Literal(Literal), - Var(String), - /// Text with embedded `` `var` `` segments. - Interp(Vec), - Unary { - op: UnaryOp, - expr: Box, - }, - Binary { - op: BinaryOp, - left: Box, - right: Box, - }, - Call(CallExpr), - List(Vec), - /// Object literal / horizontal table (`map` value). - Map(Vec<(String, Expr)>), - /// Collection index: `` [拿铁](菜单) `` / `` [`名`](菜单) `` (preferred), or - /// legacy footnote `` `菜单`[^拿铁] `` / `` `菜单`[^`名`] ``. - Index { - base: Box, - /// Key or 1-based list index; see [`IndexKey`]. - label: IndexKey, - }, - /// Parsed `$$…$$` formula tree (from assignment RHS). - Formula(FormulaExpr), - /// Bound ```lang … ``` fence (`code` value). - Code(CodeBlock), - /// `[描述](实现)` — **occlusion**: `label` is inert prose (never executed, - /// only scanned for keywords and checked for staleness), `payload` is the - /// only thing that runs. `payload: None` means the empty-payload stub - /// (`[某某功能开发中]()`), which evaluates to `None`. `` M2 - Occluded { - label: String, - payload: Option>, - }, -} - -#[derive(Debug, Clone)] -pub enum InterpPart { - Lit(String), - Var(String), - /// `` `base`[^label] `` — variable followed by footnote index inside interpolated - /// text (chained labels fold into one part, e.g. `` `x`[^a][^b] `` → two labels). - Index { base: String, labels: Vec }, -} - -/// Map / list index key (`[key](coll)` or legacy `[^…]`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum IndexKey { - /// Static text: `[拿铁](…)` / `[^拿铁]` / `[^1]`. - Lit(String), - /// Dynamic: `` [`品名`](…) `` / `` [^`品名`] `` — evaluate variable, then stringify as key. - Var(String), -} - -#[derive(Debug, Clone)] -pub enum Literal { - None, - Bool(bool), - Int(i64), - /// Decimal literal (`0.85`, `3.14`). - Num(f64), - Text(String), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum UnaryOp { - Not, - Neg, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum BinaryOp { - Add, - Sub, - Mul, - Div, - Eq, - Ne, - Lt, - Le, - Gt, - Ge, - And, - Or, -} - -/// Pretty-print AST for `--dump-ast`. -pub fn format_ast_dump(path: &str, module: &Module) -> String { - let mut out = String::new(); - out.push_str(&format!("=== marqdo: ast ({path}) ===\n")); - if !module.imports.is_empty() { - let specs: Vec = module - .imports - .iter() - .map(|i| format!("import {}:{}", i.bind, i.path)) - .collect(); - out.push_str(&format!("(imports {:?})\n", specs)); - } - for fun in &module.functions { - dump_fun(&mut out, fun, 0); - } - out.push_str("=== marqdo: end ast ===\n"); - out -} - -fn dump_fun(out: &mut String, fun: &Function, depth: usize) { - let pad = " ".repeat(depth); - let kind = if fun.is_object() { "object" } else { "fun" }; - let params = format_params(&fun.params); - let dead = if fun.dead_binds.is_empty() { - String::new() - } else { - format!(" dead={:?}", fun.dead_binds) - }; - match &fun.base { - Some(base) => out.push_str(&format!( - "{pad}({kind} level={} {:?} extends={base:?} params={params}{dead} @{}\n", - fun.level, fun.name, fun.span - )), - None => out.push_str(&format!( - "{pad}({kind} level={} {:?} params={params}{dead} @{}\n", - fun.level, fun.name, fun.span - )), - } - for stmt in &fun.body { - dump_stmt(out, stmt, depth + 1); - } - for child in &fun.children { - dump_fun(out, child, depth + 1); - } - out.push_str(&format!("{pad})\n")); -} - -fn dump_stmt(out: &mut String, stmt: &Stmt, depth: usize) { - let pad = " ".repeat(depth); - match stmt { - Stmt::Assign { - name, - value, - span, - end_line, - } => { - out.push_str(&format!( - "{pad}(assign {name:?} {value:?} @{span}..{end_line})\n" - )); - } - Stmt::Return { value, span } => { - out.push_str(&format!("{pad}(return {value:?} @{span})\n")); - } - Stmt::Call { call, span } => { - out.push_str(&format!( - "{pad}(call recv={:?} {:?} {:?} @{span}\n", - call.receiver, call.callee, call.args - )); - } - Stmt::Expr { value, span } => { - out.push_str(&format!("{pad}(expr {value:?} @{span})\n")); - } - Stmt::Branch { arms, span } => { - out.push_str(&format!("{pad}(branch @{span}\n")); - for arm in arms { - out.push_str(&format!("{pad} (arm cond={:?}\n", arm.condition)); - for s in &arm.body { - dump_stmt(out, s, depth + 2); - } - out.push_str(&format!("{pad} )\n")); - } - out.push_str(&format!("{pad})\n")); - } - Stmt::While { - condition, - body, - span, - } => { - out.push_str(&format!("{pad}(while {condition:?} @{span}\n")); - for s in body { - dump_stmt(out, s, depth + 1); - } - out.push_str(&format!("{pad})\n")); - } - Stmt::ForEach { - item, - collection, - label: _, - body, - span, - } => { - out.push_str(&format!( - "{pad}(foreach {item:?} in {collection:?} @{span}\n" - )); - for s in body { - dump_stmt(out, s, depth + 1); - } - out.push_str(&format!("{pad})\n")); - } - } -} - -fn format_params(params: &[Param]) -> String { - let parts: Vec = params - .iter() - .map(|p| { - let mut s = p.name.clone(); - if p.default.is_some() { - s.push('?'); - } - if p.inferred { - s.push_str(" inferred"); - } - s - }) - .collect(); - format!("[{}]", parts.join(", ")) -} diff --git a/src/binding/mod.rs b/src/binding/mod.rs deleted file mode 100755 index 0184a3a..0000000 --- a/src/binding/mod.rs +++ /dev/null @@ -1,531 +0,0 @@ -//! Artifact Metadata Binding (`${ns.name}`) — Phase 1: frontmatter only. -//! -//! Spec: `doc/design/binding.md` · ADR 0006. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -use anyhow::{bail, Result}; - -use crate::diagnostics::{bail_at, Span}; -use crate::value::Value; - -/// Unresolved frontmatter value (literal, sole binding, or interpolated text). -#[derive(Debug, Clone)] -pub enum MetaValue { - /// Already typed literal (no `${}`). - Literal(Value), - /// Whole value is one `${…}` expression. - Binding(BindingExpr), - /// Quoted/bare string containing `${…}` interpolations → Text after resolve. - Interpolated(String), -} - -/// Parsed binding expression (inside `${…}`). -#[derive(Debug, Clone)] -pub struct BindingExpr { - pub cast: Option, - pub primary: BindingRef, - pub default: Option, - pub required: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CastKind { - Int, - Float, - Bool, -} - -#[derive(Debug, Clone)] -pub struct BindingRef { - pub ns: String, - pub name: String, -} - -#[derive(Debug, Clone)] -pub enum DefaultVal { - Text(String), - /// Nested `${…}` not supported in Phase 1 defaults; only quoted/bare literals. - Binding(Box), -} - -/// Sources available while resolving metadata at load time. -#[derive(Debug, Clone, Default)] -pub struct BindingContext { - /// `--bind KEY=VALUE` → `arg.KEY` and post-resolve overlay. - pub args: HashMap, - pub cwd: PathBuf, -} - -impl BindingContext { - pub fn from_binds(binds: &[(String, String)], cwd: PathBuf) -> Self { - let mut args = HashMap::new(); - for (k, v) in binds { - args.insert(k.clone(), v.clone()); - } - Self { args, cwd } - } -} - -/// Parse a frontmatter RHS into a [`MetaValue`]. -pub fn parse_meta_value(raw: &str) -> Result { - let t = raw.trim(); - if t.is_empty() { - return Ok(MetaValue::Literal(Value::Text(String::new()))); - } - - // Sole binding: entire value is `${…}` - if let Some(inner) = sole_binding(t) { - let expr = parse_binding_expr(inner)?; - return Ok(MetaValue::Binding(expr)); - } - - // Quoted string (may interpolate) - if (t.starts_with('"') && t.ends_with('"') && t.len() >= 2) - || (t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2) - { - let inner = &t[1..t.len() - 1]; - if inner.contains("${") { - return Ok(MetaValue::Interpolated(unquote_escapes(inner))); - } - return Ok(MetaValue::Literal(Value::Text(unquote_escapes(inner)))); - } - - // Bare with interpolation - if t.contains("${") { - return Ok(MetaValue::Interpolated(t.to_string())); - } - - Ok(MetaValue::Literal(parse_scalar_literal(t))) -} - -fn sole_binding(t: &str) -> Option<&str> { - let t = t.trim(); - if !t.starts_with("${") || !t.ends_with('}') { - return None; - } - // Ensure matching: first `${` closes at last `}` and nothing outside - let inner = &t[2..t.len() - 1]; - // Reject if another `${` appears that would mean concatenation (not sole) - // Allow nested parens inside cast: ${int(env.X ?? "1")} - Some(inner) -} - -fn unquote_escapes(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut chars = s.chars().peekable(); - while let Some(c) = chars.next() { - if c == '\\' { - match chars.next() { - Some('n') => out.push('\n'), - Some('t') => out.push('\t'), - Some('\\') => out.push('\\'), - Some('"') => out.push('"'), - Some('\'') => out.push('\''), - Some(o) => { - out.push('\\'); - out.push(o); - } - None => out.push('\\'), - } - } else { - out.push(c); - } - } - out -} - -fn parse_scalar_literal(t: &str) -> Value { - match t { - "true" | "True" | "TRUE" => Value::Bool(true), - "false" | "False" | "FALSE" => Value::Bool(false), - "null" | "Null" | "None" | "~" => Value::None, - _ => { - if let Ok(n) = t.parse::() { - return Value::Int(n); - } - if let Ok(n) = t.parse::() { - if !n.is_nan() && !n.is_infinite() { - return Value::Num(n); - } - } - Value::Text(t.to_string()) - } - } -} - -/// Parse inside `${…}` (without braces). -pub fn parse_binding_expr(inner: &str) -> Result { - let s = inner.trim(); - // cast: int(…) / float(…) / bool(…) - if let Some((cast, rest)) = parse_cast_wrap(s)? { - let mut expr = parse_binding_expr(rest)?; - if expr.cast.is_some() { - bail!("nested casts are not allowed in binding expressions"); - } - expr.cast = Some(cast); - return Ok(expr); - } - - let (body, required) = if let Some(b) = s.strip_suffix('!') { - (b.trim(), true) - } else { - (s, false) - }; - - let (primary_s, default) = if let Some((left, right)) = split_default(body) { - (left.trim(), Some(parse_default_val(right.trim())?)) - } else { - (body, None) - }; - - if required && default.is_some() { - bail!("binding cannot combine `!` with `??` default"); - } - - let primary = parse_binding_ref(primary_s)?; - Ok(BindingExpr { - cast: None, - primary, - default, - required, - }) -} - -fn parse_cast_wrap(s: &str) -> Result> { - for (name, kind) in [ - ("int", CastKind::Int), - ("float", CastKind::Float), - ("bool", CastKind::Bool), - ] { - let prefix = format!("{name}("); - if let Some(rest) = s.strip_prefix(&prefix) { - if let Some(inner) = strip_trailing_paren(rest) { - return Ok(Some((kind, inner))); - } - bail!("unclosed `{name}(` in binding expression"); - } - } - Ok(None) -} - -fn strip_trailing_paren(s: &str) -> Option<&str> { - let s = s.trim_end(); - if !s.ends_with(')') { - return None; - } - Some(s[..s.len() - 1].trim()) -} - -fn split_default(s: &str) -> Option<(&str, &str)> { - // Split on top-level `??` - let bytes = s.as_bytes(); - let mut i = 0; - let mut depth = 0i32; - while i + 1 < bytes.len() { - match bytes[i] { - b'(' => depth += 1, - b')' => depth -= 1, - b'?' if depth == 0 && bytes[i + 1] == b'?' => { - return Some((&s[..i], &s[i + 2..])); - } - _ => {} - } - i += 1; - } - None -} - -fn parse_default_val(s: &str) -> Result { - let s = s.trim(); - if let Some(inner) = sole_binding(s) { - return Ok(DefaultVal::Binding(Box::new(parse_binding_expr(inner)?))); - } - if (s.starts_with('"') && s.ends_with('"') && s.len() >= 2) - || (s.starts_with('\'') && s.ends_with('\'') && s.len() >= 2) - { - return Ok(DefaultVal::Text(unquote_escapes(&s[1..s.len() - 1]))); - } - // bare default token - Ok(DefaultVal::Text(s.to_string())) -} - -fn parse_binding_ref(s: &str) -> Result { - let s = s.trim(); - let Some((ns, name)) = s.split_once('.') else { - bail!("binding path must be `namespace.name` (got `{s}`)"); - }; - let ns = ns.trim(); - let name = name.trim(); - if ns.is_empty() || name.is_empty() { - bail!("binding path must be `namespace.name` (got `{s}`)"); - } - match ns { - "env" | "arg" | "sys" | "secret" => {} - "config" | "file" => { - bail!("binding namespace `{ns}` is not available in Phase 1 (Metadata-only)") - } - other => bail!("unknown binding namespace `{other}`"), - } - if name.contains('.') { - // Phase 1: single segment name only - bail!("binding name must be a single segment (got `{s}`)"); - } - Ok(BindingRef { - ns: ns.to_string(), - name: name.to_string(), - }) -} - -/// Resolve raw metadata entries; then overlay `--bind` keys. -pub fn resolve_metadata( - raw: &[(String, MetaValue)], - ctx: &BindingContext, - span: Span, -) -> Result> { - let mut out: Vec<(String, Value)> = Vec::with_capacity(raw.len()); - for (k, mv) in raw { - let v = resolve_meta_value(mv, ctx, span) - .map_err(|e| bail_at(None, span, e.to_string()))?; - out.push((k.clone(), v)); - } - // CLI overlay - for (k, v) in &ctx.args { - if let Some(slot) = out.iter_mut().find(|(mk, _)| mk == k) { - slot.1 = Value::Text(v.clone()); - } else { - out.push((k.clone(), Value::Text(v.clone()))); - } - } - Ok(out) -} - -fn resolve_meta_value(mv: &MetaValue, ctx: &BindingContext, span: Span) -> Result { - match mv { - MetaValue::Literal(v) => Ok(v.clone()), - MetaValue::Binding(expr) => resolve_expr(expr, ctx, span), - MetaValue::Interpolated(s) => { - let text = interpolate(s, ctx, span)?; - Ok(Value::Text(text)) - } - } -} - -fn interpolate(s: &str, ctx: &BindingContext, span: Span) -> Result { - let mut out = String::new(); - let mut rest = s; - while let Some(start) = rest.find("${") { - out.push_str(&rest[..start]); - let after = &rest[start + 2..]; - let end = find_binding_close(after).ok_or_else(|| { - anyhow::anyhow!("{}:{}: unclosed `${{` in metadata interpolation", span.line, span.col) - })?; - let inner = &after[..end]; - let expr = parse_binding_expr(inner)?; - let v = resolve_expr(&expr, ctx, span)?; - out.push_str(&v.as_display()); - rest = &after[end + 1..]; - } - out.push_str(rest); - Ok(out) -} - -fn find_binding_close(s: &str) -> Option { - let mut depth = 0i32; - for (i, c) in s.char_indices() { - match c { - '(' => depth += 1, - ')' => depth -= 1, - '}' if depth == 0 => return Some(i), - _ => {} - } - } - None -} - -fn resolve_expr(expr: &BindingExpr, ctx: &BindingContext, span: Span) -> Result { - let got = lookup(&expr.primary, ctx)?; - let value = match got { - Some(v) => v, - None if expr.required => { - bail!( - "required binding `{}.{}` is missing", - expr.primary.ns, - expr.primary.name - ) - } - None => match &expr.default { - Some(DefaultVal::Text(t)) => Value::Text(t.clone()), - Some(DefaultVal::Binding(inner)) => resolve_expr(inner, ctx, span)?, - None => Value::None, - }, - }; - apply_cast(expr.cast, value) -} - -fn lookup(r: &BindingRef, ctx: &BindingContext) -> Result> { - match r.ns.as_str() { - "env" => Ok(std::env::var(&r.name).ok().map(Value::Text)), - "arg" => Ok(ctx.args.get(&r.name).cloned().map(Value::Text)), - "secret" => Ok(std::env::var(&r.name).ok().map(Value::Secret)), - "sys" => Ok(lookup_sys(&r.name, ctx)), - other => bail!("unknown binding namespace `{other}`"), - } -} - -fn lookup_sys(name: &str, ctx: &BindingContext) -> Option { - match name { - "cwd" => Some(Value::Text(ctx.cwd.display().to_string())), - "platform" => Some(Value::Text(std::env::consts::OS.to_string())), - _ => None, - } -} - -fn apply_cast(cast: Option, v: Value) -> Result { - let Some(c) = cast else { - return Ok(v); - }; - let text = match &v { - Value::None => { - bail!("cannot cast None to {:?}", c); - } - Value::Text(s) => s.clone(), - Value::Secret(s) => s.clone(), - Value::Int(n) => n.to_string(), - Value::Num(n) => n.to_string(), - Value::Bool(b) => { - if *b { - "true".into() - } else { - "false".into() - } - } - other => bail!("cannot cast {} to {:?}", other.as_display(), c), - }; - match c { - CastKind::Int => { - let n: i64 = text - .trim() - .parse() - .map_err(|_| anyhow::anyhow!("cannot cast `{text}` to int"))?; - Ok(Value::Int(n)) - } - CastKind::Float => { - let n: f64 = text - .trim() - .parse() - .map_err(|_| anyhow::anyhow!("cannot cast `{text}` to float"))?; - Ok(Value::Num(n)) - } - CastKind::Bool => { - let t = text.trim().to_ascii_lowercase(); - match t.as_str() { - "1" | "true" | "yes" | "on" => Ok(Value::Bool(true)), - "0" | "false" | "no" | "off" => Ok(Value::Bool(false)), - _ => bail!("cannot cast `{text}` to bool"), - } - } - } -} - -/// Split `KEY=VALUE` from CLI `--bind`. -pub fn parse_bind_kv(s: &str) -> Result<(String, String)> { - let Some((k, v)) = s.split_once('=') else { - bail!("--bind expects KEY=VALUE (got `{s}`)"); - }; - let k = k.trim(); - if k.is_empty() { - bail!("--bind key must be non-empty"); - } - Ok((k.to_string(), v.to_string())) -} - -pub fn cwd_for_path(path: Option<&Path>) -> PathBuf { - path.and_then(|p| p.parent()) - .map(|p| { - if p.as_os_str().is_empty() { - PathBuf::from(".") - } else { - p.to_path_buf() - } - }) - .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sole_env_default() { - let mv = parse_meta_value(r#"${env.NO_SUCH_MARQDO_VAR_XYZ ?? "gpt"}"#).unwrap(); - let ctx = BindingContext::default(); - let v = resolve_meta_value(&mv, &ctx, Span::new(1, 1)).unwrap(); - assert_eq!(v, Value::Text("gpt".into())); - } - - #[test] - fn required_missing_errors() { - let mv = parse_meta_value("${env.NO_SUCH_MARQDO_REQ_XYZ!}").unwrap(); - let ctx = BindingContext::default(); - let err = resolve_meta_value(&mv, &ctx, Span::new(1, 1)).unwrap_err(); - assert!(err.to_string().contains("required binding")); - } - - #[test] - fn secret_masks_display() { - std::env::set_var("MARQDO_TEST_SECRET_BIND", "s3cr3t"); - let mv = parse_meta_value("${secret.MARQDO_TEST_SECRET_BIND}").unwrap(); - let ctx = BindingContext::default(); - let v = resolve_meta_value(&mv, &ctx, Span::new(1, 1)).unwrap(); - assert_eq!(v.as_display(), ""); - match v { - Value::Secret(s) => assert_eq!(s, "s3cr3t"), - other => panic!("expected Secret, got {other:?}"), - } - std::env::remove_var("MARQDO_TEST_SECRET_BIND"); - } - - #[test] - fn literal_not_overridden_by_env() { - std::env::set_var("OPENAI_MODEL", "from-env"); - let raw = vec![( - "model".into(), - MetaValue::Literal(Value::Text("gpt-literal".into())), - )]; - let ctx = BindingContext::default(); - let meta = resolve_metadata(&raw, &ctx, Span::new(1, 1)).unwrap(); - assert_eq!(meta[0].1, Value::Text("gpt-literal".into())); - std::env::remove_var("OPENAI_MODEL"); - } - - #[test] - fn bind_overlay_wins() { - let raw = vec![( - "model".into(), - MetaValue::Literal(Value::Text("gpt-literal".into())), - )]; - let ctx = BindingContext::from_binds(&[("model".into(), "from-cli".into())], PathBuf::from(".")); - let meta = resolve_metadata(&raw, &ctx, Span::new(1, 1)).unwrap(); - assert_eq!(meta[0].1, Value::Text("from-cli".into())); - } - - #[test] - fn int_cast() { - std::env::set_var("MARQDO_TEST_MAX_TOKENS", "2048"); - let mv = parse_meta_value("${int(env.MARQDO_TEST_MAX_TOKENS)}").unwrap(); - let v = resolve_meta_value(&mv, &BindingContext::default(), Span::new(1, 1)).unwrap(); - assert_eq!(v, Value::Int(2048)); - std::env::remove_var("MARQDO_TEST_MAX_TOKENS"); - } - - #[test] - fn interpolate_string() { - std::env::set_var("MARQDO_TEST_USER", "Ada"); - let mv = parse_meta_value(r#""Hello ${env.MARQDO_TEST_USER}""#).unwrap(); - let v = resolve_meta_value(&mv, &BindingContext::default(), Span::new(1, 1)).unwrap(); - assert_eq!(v, Value::Text("Hello Ada".into())); - std::env::remove_var("MARQDO_TEST_USER"); - } -} diff --git a/src/browser_session.rs b/src/browser_session.rs deleted file mode 100755 index 4bb3e76..0000000 --- a/src/browser_session.rs +++ /dev/null @@ -1,197 +0,0 @@ -//! In-memory browser / WASM session: boot `# main`, then call handlers with shared entry env. - -use anyhow::{bail, Result}; - -use crate::ast::Module; -use crate::host::json::{json_to_value, value_to_json}; -use crate::host::{HostCaps, HostContext}; -use crate::interp::Interpreter; -use crate::load::load_module_from_source; -use crate::value::Value; -use crate::Backend; - -/// Persistent Marqdo program for the browser host bridge. -/// -/// Session calls (`call`) use the **tree** interpreter so entry bindings persist -/// across handlers (C3). One-shot [`crate::run_source`] may still use bytecode. -pub struct BrowserSession { - module: Module, - interp: Interpreter, -} - -impl BrowserSession { - /// Parse source, run `# main`, keep entry bindings for later [`Self::call`]. - pub fn boot(source: &str) -> Result<(Self, Value)> { - Self::boot_with(source, Backend::Tree) - } - - /// Like [`Self::boot`]. `Backend::Bytecode` is rejected for sessions (no shared entry env yet). - pub fn boot_with(source: &str, backend: Backend) -> Result<(Self, Value)> { - if source.trim().is_empty() { - bail!("source is empty"); - } - if backend != Backend::Tree { - bail!("browser session requires tree backend (bytecode has no entry-env invoke yet)"); - } - let module = load_module_from_source(source)?; - let caps = HostCaps { - fs_write: false, - exec: false, - net: false, - plugin: false, - }; - let mut host = HostContext::for_capture(None, caps); - host.set_entry_source(None, source); - host.sleep_limit_ms = Some(0); - let mut interp = Interpreter::with_capture(None, false).with_host(host); - let value = interp.run_module(&module)?; - Ok((Self { module, interp }, value)) - } - - /// Invoke `name` with optional JSON object of named args; updates entry bindings. - pub fn call(&mut self, name: &str, args_json: &str) -> Result { - let args = parse_named_args(args_json)?; - self.interp.captured_stdout.clear(); - self.interp.invoke_in_entry(&self.module, name, &args) - } - - pub fn take_stdout(&mut self) -> String { - std::mem::take(&mut self.interp.captured_stdout) - } -} - -fn parse_named_args(args_json: &str) -> Result> { - let t = args_json.trim(); - if t.is_empty() || t == "{}" || t == "null" { - return Ok(Vec::new()); - } - let v: serde_json::Value = - serde_json::from_str(t).map_err(|e| anyhow::anyhow!("call args json: {e}"))?; - match v { - serde_json::Value::Object(map) => { - let mut out = Vec::new(); - for (k, j) in map { - out.push((k, json_to_value(&j).map_err(|e| anyhow::anyhow!(e))?)); - } - Ok(out) - } - serde_json::Value::Null => Ok(Vec::new()), - _ => bail!("call args must be a JSON object"), - } -} - -/// Serialize a runtime [`Value`] to JSON (for WASM bridge responses). -pub fn value_as_json(v: &Value) -> Result { - value_to_json(v) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn boot_and_call_share_count() { - let src = r##"--- -import: - json: lib/json.mq.md ---- - -# main - -**count = 0** - -`wire` = - -| @ | 选择器 | 事件 | 调用 | -|---|--------|------|------| -| 1 | "#btn" | click | bump | - -*wire* - -## bump -**count = count + 1** -**label = > str count** -**patch = > json.set map=None key="#out" value=label** -*> json.set map=None key="set_text" value=patch* -"##; - let (mut sess, wire) = BrowserSession::boot(src).expect("boot"); - assert!(matches!(wire, Value::List(_)), "wire={wire:?}"); - let _v1 = sess.call("bump", "{}").expect("call1"); - let v2 = sess.call("bump", "{}").expect("call2"); - let j2 = value_as_json(&v2).unwrap(); - assert_eq!(j2["set_text"]["#out"], "2"); - } - - #[test] - fn fetch_mq_load_returns_fetch_effect() { - // A protocol regression must not depend on a retired public example. - let src = r###"--- -markup: occlusion -title: browser fetch (C4) -description: fetch/after effects via lib/browser — no json glue -import: - browser: lib/browser.mq.md ---- - -# main - -`wire` = - -| @ | 选择器 | 事件 | 调用 | -|---|--------|------|------| -| 1 | "#load" | click | load | -| 2 | "#ping" | click | ping | - -*`wire`* - -## load -**`msg` = > browser.set_text sel="#status" text="loading…"** -**`req` = > browser.fetch url="https://httpbin.org/uuid" then="on_uuid"** -*> browser.merge a=msg b=req* - -## on_uuid - + `ok` - + `status` - + `body`="" - + `error`="" - -1. ok - *> browser.set_text sel="#status" text=body* -2. * - *> browser.set_text sel="#status" text="fetch failed"* - -## ping -**`msg` = > browser.set_text sel="#status" text="wait 600ms…"** -**`t` = > browser.after ms=600 then="on_ping"** -*> browser.merge a=msg b=t* - -## on_ping - + `ok`=True - -*> browser.set_text sel="#status" text="pong"* -"###; - let (mut sess, wire) = BrowserSession::boot(src).expect("boot"); - assert!(matches!(wire, Value::List(_))); - let v = sess.call("load", "{}").expect("load"); - let j = value_as_json(&v).unwrap(); - assert_eq!(j["set_text"]["#status"], "loading…"); - assert_eq!(j["fetch"]["then"], "on_uuid"); - assert!(j["fetch"]["url"].as_str().unwrap().contains("httpbin")); - let done = sess - .call( - "on_uuid", - r#"{"ok":true,"status":200,"body":"{\"uuid\":\"x\"}"}"#, - ) - .expect("on_uuid"); - let jd = value_as_json(&done).unwrap(); - assert!(jd["set_text"]["#status"].as_str().unwrap().contains("uuid")); - } - - #[test] - fn session_rejects_bytecode_backend() { - let err = BrowserSession::boot_with("# main\n\n> print text=x\n", Backend::Bytecode) - .err() - .expect("err"); - assert!(err.to_string().contains("tree backend")); - } -} diff --git a/src/builtin.rs b/src/builtin.rs deleted file mode 100755 index 0a19c51..0000000 --- a/src/builtin.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! Built-in helpers shared by tree-walk and bytecode. - -mod primitives; -pub use primitives::{eval_binary,eval_unary}; - -use crate::value::Value; - -/// Machine integer arithmetic has one profile-independent failure contract. -/// Overflow must remain a language diagnostic in debug, release and Wasm. -pub fn checked_int_binary(op: crate::ast::BinaryOp, left: i64, right: i64) -> Result { - use crate::ast::BinaryOp; - if matches!(op, BinaryOp::Div) && right == 0 { return Err("division by zero".into()); } - let result = match op { - BinaryOp::Add => left.checked_add(right), - BinaryOp::Sub => left.checked_sub(right), - BinaryOp::Mul => left.checked_mul(right), - BinaryOp::Div => left.checked_div(right), - _ => return Err("not an integer arithmetic operation".into()), - }; - result.ok_or_else(|| "integer overflow".into()) -} - -pub fn checked_int_neg(value: i64) -> Result { - value.checked_neg().ok_or_else(|| "integer overflow".into()) -} - -/// `len`: text → Unicode scalar count; list → element count. -pub fn builtin_len(v: &Value) -> Result { - match v { - Value::Text(s) => Ok(s.chars().count() as i64), - Value::List(xs) => Ok(xs.len() as i64), - _ => Err("len needs text or list".into()), - } -} - -/// `str`: display conversion (same surface as `print`). -pub fn builtin_str(v: &Value) -> Value { - Value::Text(v.as_display()) -} - -/// `int`: Int passthrough; Bool → 0/1; Text → parse trimmed decimal. -pub fn builtin_int(v: &Value) -> Result { - match v { - Value::Int(n) => Ok(*n), - Value::Num(n) => { - // The upper bound is exclusive: i64::MAX rounds to 2^63 as f64. - if !n.is_finite() || *n < -9223372036854775808.0 || *n >= 9223372036854775808.0 { - return Err("int conversion outside signed 64-bit domain".into()); - } - Ok(*n as i64) - } - Value::Bool(true) => Ok(1), - Value::Bool(false) => Ok(0), - Value::Text(s) => { - let t = s.trim(); - t.parse::() - .map_err(|_| format!("cannot convert to int: {s:?}")) - } - _ => Err("int needs int, num, bool, or text".into()), - } -} - -/// `type`: type tag as text (`none` / `bool` / `int` / `num` / `text` / `list` / `map` / `formula`). -pub fn builtin_type(v: &Value) -> Value { - Value::Text( - match v { - Value::None => "none", - Value::Bool(_) => "bool", - Value::Int(_) => "int", - Value::Num(_) => "num", - Value::Text(_) => "text", - Value::Secret(_) => "secret", - Value::Handle(_) => "handle", - Value::List(_) => "list", - Value::Map(_) => "map", - Value::Formula(_) => "formula", - Value::Code(_) => "code", - } - .into(), - ) -} - -/// `trim`: strip leading/trailing Unicode whitespace from text. -pub fn builtin_trim(v: &Value) -> Result { - match v { - Value::Text(s) => Ok(Value::Text(s.trim().to_string())), - _ => Err("trim needs text".into()), - } -} - -/// `split`: split text by separator → list of text parts. -pub fn builtin_split(value: &Value, sep: &Value) -> Result { - let text = match value { - Value::Text(s) => s.as_str(), - _ => return Err("split needs text value".into()), - }; - let sep = match sep { - Value::Text(s) => s.as_str(), - _ => return Err("split needs text sep".into()), - }; - if sep.is_empty() { - return Err("split sep must not be empty".into()); - } - let parts: Vec = text - .split(sep) - .map(|p| Value::Text(p.to_string())) - .collect(); - Ok(Value::List(parts)) -} - -/// `join`: join list elements with separator → text. -pub fn builtin_join(value: &Value, sep: &Value) -> Result { - let items = match value { - Value::List(xs) => xs, - _ => return Err("join needs list value".into()), - }; - let sep = match sep { - Value::Text(s) => s.as_str(), - _ => return Err("join needs text sep".into()), - }; - let mut out = String::new(); - for (i, item) in items.iter().enumerate() { - if i > 0 { - out.push_str(sep); - } - out.push_str(&item.as_display()); - } - Ok(Value::Text(out)) -} - -/// `at`: list element at index (0-based); out of range → None. -pub fn builtin_at(value: &Value, index: &Value) -> Result { - let xs = match value { - Value::List(xs) => xs, - _ => return Err("at needs list value".into()), - }; - let i = match index { - Value::Int(n) => *n, - _ => return Err("at needs int index".into()), - }; - if i < 0 || i >= xs.len() as i64 { - return Ok(Value::None); - } - Ok(xs[i as usize].clone()) -} - -/// Foreach surface: list items unchanged; map → list of keys (insertion order). -pub fn builtin_iter_items(value: &Value) -> Result { - match value { - Value::List(xs) => Ok(Value::List(xs.clone())), - Value::Map(pairs) => Ok(Value::List( - pairs - .iter() - .map(|(k, _)| Value::Text(k.clone())) - .collect(), - )), - _ => Err("foreach needs a list or map".into()), - } -} - -/// Footnote get: `` `xs`[^1] `` (1-based list) or `` `m`[^key] `` (map key). -pub fn builtin_footnote_get(base: &Value, label: &str) -> Result { - let is_digits = !label.is_empty() && label.bytes().all(|b| b.is_ascii_digit()); - match base { - Value::List(xs) => { - if !is_digits { - return Err(format!( - "list footnote index must be digits (1-based), got `[^{label}]`" - )); - } - let n: i64 = label - .parse() - .map_err(|_| format!("invalid list index `[^{label}]`"))?; - if n == 0 { - return Err("`[^0]` is invalid; list indices are 1-based".into()); - } - if n < 1 || (n as usize) > xs.len() { - return Err(format!( - "list index {n} out of range (len {})", - xs.len() - )); - } - Ok(xs[(n as usize) - 1].clone()) - } - Value::Map(pairs) => pairs - .iter() - .find(|(k, _)| k == label) - .map(|(_, v)| v.clone()) - .ok_or_else(|| format!("missing map key `{label}`")), - _ => Err("footnote index needs list or map".into()), - } -} diff --git a/src/builtin/primitives.rs b/src/builtin/primitives.rs deleted file mode 100755 index ab8b25c..0000000 --- a/src/builtin/primitives.rs +++ /dev/null @@ -1,88 +0,0 @@ -//! Scalar operator semantics shared by source evaluation and VM. -use crate::{ast::BinaryOp, value::Value}; -pub fn eval_binary(op: BinaryOp, l: &Value, r: &Value) -> Result { - match op { - BinaryOp::Add => match (l, r) { - (Value::Int(a), Value::Int(b)) => { - crate::builtin::checked_int_binary(op, *a, *b).map(Value::Int) - } - (Value::Num(a), Value::Num(b)) => Ok(Value::Num(a + b)), - (Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 + b)), - (Value::Num(a), Value::Int(b)) => Ok(Value::Num(a + *b as f64)), - (Value::Text(a), Value::Text(b)) => Ok(Value::Text(format!("{a}{b}"))), - (Value::Text(a), Value::Secret(b)) => Ok(Value::Text(format!("{a}{b}"))), - (Value::Secret(a), Value::Text(b)) => Ok(Value::Text(format!("{a}{b}"))), - (Value::Secret(a), Value::Secret(b)) => Ok(Value::Text(format!("{a}{b}"))), - (Value::Text(a), b) => Ok(Value::Text(format!("{a}{}", b.as_display()))), - (a, Value::Text(b)) => Ok(Value::Text(format!("{}{b}", a.as_display()))), - _ => Err("`+` needs ints, nums, or text".into()), - }, - BinaryOp::Sub => match (l, r) { - (Value::Int(a), Value::Int(b)) => { - crate::builtin::checked_int_binary(op, *a, *b).map(Value::Int) - } - (Value::Num(a), Value::Num(b)) => Ok(Value::Num(a - b)), - (Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 - b)), - (Value::Num(a), Value::Int(b)) => Ok(Value::Num(a - *b as f64)), - _ => Err("`-` needs ints or nums".into()), - }, - BinaryOp::Mul => match (l, r) { - (Value::Int(a), Value::Int(b)) => { - crate::builtin::checked_int_binary(op, *a, *b).map(Value::Int) - } - (Value::Num(a), Value::Num(b)) => Ok(Value::Num(a * b)), - (Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 * b)), - (Value::Num(a), Value::Int(b)) => Ok(Value::Num(a * *b as f64)), - _ => Err("`*` needs ints or nums".into()), - }, - BinaryOp::Div => match (l, r) { - (Value::Int(_), Value::Int(0)) => Err("division by zero".into()), - (Value::Int(a), Value::Int(b)) => { - crate::builtin::checked_int_binary(op, *a, *b).map(Value::Int) - } - (Value::Num(_), Value::Num(b)) if *b == 0.0 => Err("division by zero".into()), - (Value::Int(_), Value::Num(b)) if *b == 0.0 => Err("division by zero".into()), - (Value::Num(_), Value::Int(0)) => Err("division by zero".into()), - (Value::Num(a), Value::Num(b)) => Ok(Value::Num(a / b)), - (Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 / b)), - (Value::Num(a), Value::Int(b)) => Ok(Value::Num(a / *b as f64)), - _ => Err("`/` needs ints or nums".into()), - }, - BinaryOp::Eq => Ok(Value::Bool(l == r)), - BinaryOp::Ne => Ok(Value::Bool(l != r)), - BinaryOp::Lt => cmp_ord(l, r, |o| o.is_lt()), - BinaryOp::Le => cmp_ord(l, r, |o| o.is_le()), - BinaryOp::Gt => cmp_ord(l, r, |o| o.is_gt()), - BinaryOp::Ge => cmp_ord(l, r, |o| o.is_ge()), - BinaryOp::And | BinaryOp::Or => unreachable!("handled above"), - } -} - -fn cmp_ord(l: &Value, r: &Value, f: impl Fn(std::cmp::Ordering) -> bool) -> Result { - match (l, r) { - (Value::Int(a), Value::Int(b)) => Ok(Value::Bool(f(a.cmp(b)))), - (Value::Num(a), Value::Num(b)) => Ok(Value::Bool(f(a - .partial_cmp(b) - .unwrap_or(std::cmp::Ordering::Equal)))), - (Value::Int(a), Value::Num(b)) => Ok(Value::Bool(f((*a as f64) - .partial_cmp(b) - .unwrap_or(std::cmp::Ordering::Equal)))), - (Value::Num(a), Value::Int(b)) => Ok(Value::Bool(f(a - .partial_cmp(&(*b as f64)) - .unwrap_or(std::cmp::Ordering::Equal)))), - (Value::Text(a), Value::Text(b)) => Ok(Value::Bool(f(a.cmp(b)))), - _ => Err("comparison needs two ints/nums or two texts".into()), - } -} - -/// Scalar unary semantics shared by source and target execution. -pub fn eval_unary(op: crate::ast::UnaryOp, value: &Value) -> Result { - match op { - crate::ast::UnaryOp::Not => Ok(Value::Bool(!value.truthy())), - crate::ast::UnaryOp::Neg => match value { - Value::Int(n) => crate::builtin::checked_int_neg(*n).map(Value::Int), - Value::Num(n) => Ok(Value::Num(-n)), - _ => Err("unary `-` needs int or num".into()), - }, - } -} diff --git a/src/bytecode/call.rs b/src/bytecode/call.rs deleted file mode 100755 index c1e63a5..0000000 --- a/src/bytecode/call.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! Check actual staging, scratch separation and post-evaluation call selection. -//! Resolution and dispatch implementations remain semantic interfaces. -use super::{expression::Cursor, ExpressionRule, FnChunk, Op, Program}; -use crate::{ - ast::{Arg, CallExpr}, - value::Value, -}; -use std::collections::HashSet; - -#[derive(Debug, Clone)] -pub struct CallStage { - pub expression: usize, - pub slot: usize, -} -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum PathFallback { - User { target: usize, tag_instance: bool }, - Error { message: String }, -} -impl PathFallback { - fn evidence(&self) -> serde_json::Value { - match self { - Self::User { target, tag_instance } => serde_json::json!({"kind":"user","target":target,"tag_instance":tag_instance}), - Self::Error { message } => serde_json::json!({"kind":"error","message":message}), - } - } -} -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum CallDispatch { - User { target: usize, tag_instance: bool }, - Method { receiver: String }, - Builtin, - Host { function: u16 }, - Plugin, - RejectDuplicate { name: String }, - Path { receiver: String, check_receiver: bool, fallback: PathFallback }, - ResolutionFault { message: String }, -} -#[derive(Debug, Clone)] -pub struct CallEmission { - pub expression: usize, - /// Expanded and normalized source, captured before argument replacement. - pub source: CallExpr, - pub stages: Vec, - pub dispatch: Option, - pub as_statement: bool, -} -impl CallEmission { - pub fn binding_evidence(&self,program:&Program)->serde_json::Value { - let signature=match self.dispatch.as_ref() { - Some(CallDispatch::User{target,..})|Some(CallDispatch::Path{fallback:PathFallback::User{target,..},..})=>{ - program.functions.get(*target).map(|callee|(callee.params.clone(),callee.defaults.clone())) - }, - Some(CallDispatch::Builtin)=>crate::arguments::builtin_signature(&self.source.callee).map(|(params,optional)| - (params.iter().map(|p|p.to_string()).collect::>(),vec![optional;params.len()])), - Some(CallDispatch::Host{function})=>crate::host::HostFn::from_u16(*function).map(|h|{ - let params=h.all_params();let len=params.len();(params.into_iter().map(str::to_string).collect(),vec![true;len]) - }), - _=>None, - }; - match signature { - Some((params,omissions))=>crate::arguments::plan_evidence(¶ms,&names(self),&omissions), - None=>serde_json::Value::Null, - } - } - pub fn evidence(&self) -> serde_json::Value { - use serde_json::json; - let dispatch = match &self.dispatch { - Some(CallDispatch::User { - target, - tag_instance, - }) => json!({"kind":"user","target":target,"tag_instance":tag_instance}), - Some(CallDispatch::Method { receiver }) => json!({"kind":"method","receiver":receiver}), - Some(CallDispatch::Builtin) => json!({"kind":"builtin"}), - Some(CallDispatch::Host { function }) => { - let host = crate::host::HostFn::from_u16(*function); - json!({"kind":"host","function":function,"params":host.map(|h|h.all_params()),"required":host.map(|h|h.required_params().len())}) - } - Some(CallDispatch::Plugin) => json!({"kind":"plugin"}), - Some(CallDispatch::RejectDuplicate { name }) => json!({"kind":"duplicate","name":name}), - Some(CallDispatch::Path { receiver, check_receiver, fallback }) => json!({"kind":"path","receiver":receiver,"check_receiver":check_receiver,"fallback":fallback.evidence()}), - Some(CallDispatch::ResolutionFault { message }) => json!({"kind":"resolution_fault","message":message}), - None => serde_json::Value::Null, - }; - json!({"expression":self.expression,"callee":self.source.callee,"receiver":self.source.receiver,"path":self.source.path, - "arguments":self.source.args.iter().map(|a|match a {Arg::Positional(_)=>None,Arg::Named{name,..}=>Some(name)}).collect::>(), - "source_rules":self.source.args.iter().map(|a|match a {Arg::Positional(e)|Arg::Named{value:e,..}=>ExpressionRule::from_source(e).evidence()}).collect::>(), - "stages":self.stages.iter().map(|s|json!({"expression":s.expression,"slot":s.slot})).collect::>(), - "dispatch":dispatch,"as_statement":self.as_statement}) - } -} -fn names(call: &CallEmission) -> Vec> { - call.source - .args - .iter() - .map(|a| match a { - Arg::Positional(_) => None, - Arg::Named { name, .. } => Some(name.clone()), - }) - .collect() -} -fn read(c: &mut Cursor<'_>, slot: usize) -> Result<(), String> { - c.op(Op::GetLocal(slot)) -} -fn read_child( - c: &mut Cursor<'_>, - ids: &mut std::slice::Iter<'_, usize>, - slot: usize, -) -> Result<(), String> { - let id = *ids.next().ok_or("missing staged argument reload witness")?; - let expr = c - .fun - .expressions - .get(id) - .ok_or("missing reload expression")?; - if expr.start != c.position - || expr.end != c.position + 1 - || !matches!(&expr.rule,ExpressionRule::Read(name) if c.fun.locals.get(slot)==Some(name)) - || !expr.children.is_empty() - { - return Err("staged argument reload source differs".into()); - } - read(c, slot) -} -fn layout(c: &mut Cursor<'_>, arguments: &[Option]) -> Result { - let id = match c.fun.code.get(c.position) { - Some(Op::CallArgs(_, id) | Op::MethodCallArgs(_, id)) => *id, - _ => return Err("missing argument-layout call".into()), - }; - if c.fun.call_layouts.get(id).map(Vec::as_slice) != Some(arguments) { - return Err("call argument layout differs from source".into()); - } - Ok(id) -} -pub fn verify(program: &Program, fun: &FnChunk) -> Result<(), String> { - let caller=program.functions.iter().position(|f|std::ptr::eq(f,fun)).ok_or("missing call owner")?; - if fun.source_local_count < fun.params.len() || fun.source_local_count > fun.locals.len() { - return Err("invalid source/scratch local boundary".into()); - } - let mut owners = HashSet::new(); - let loops = fun - .statements - .iter() - .flat_map(|s| s.auxiliary.iter().copied()) - .collect::>(); - let mut active: Vec<(&super::ExpressionEmission, HashSet)> = Vec::new(); - for call in &fun.calls { - let node = fun - .expressions - .get(call.expression) - .ok_or("missing call source expression")?; - if !matches!(node.rule, ExpressionRule::CallBoundary(_)) - || !owners.insert(call.expression) - || call.as_statement - { - return Err("call source owner differs".into()); - } - let arguments = names(call); - if call.stages.len() != arguments.len() || node.children.len() < arguments.len() { - return Err("call authored-actual inventory".into()); - } - let slots = call.stages.iter().map(|s| s.slot).collect::>(); - if slots.len() != arguments.len() - || slots - .iter() - .any(|s| *s < fun.source_local_count || *s >= fun.locals.len() || loops.contains(s)) - { - return Err("call scratch aliases source/loop/another actual".into()); - } - while active - .last() - .is_some_and(|(parent, _)| parent.end <= node.start) - { - active.pop(); - } - if active.iter().any(|(parent, other)| { - node.start < parent.start || node.end > parent.end || !slots.is_disjoint(other) - }) { - return Err("nested call scratch overlap or interval order".into()); - } - let mut c = Cursor { - fun, - position: node.start, - end: node.end, - }; - for (i, stage) in call.stages.iter().enumerate() { - if node.children[i] != stage.expression { - return Err("authored actual order differs".into()); - } - let source = match &call.source.args[i] { - Arg::Positional(e) | Arg::Named { value: e, .. } => e, - }; - if ExpressionRule::from_source(source).evidence() - != fun.expressions[stage.expression].rule.evidence() - { - return Err("authored argument source rule differs".into()); - } - c.child(stage.expression)?; - c.op(Op::SetLocal(stage.slot))?; - c.op(Op::Pop)?; - } - let mut reloads = node.children[arguments.len()..].iter(); - let dispatch=call.dispatch.as_ref().ok_or("missing call dispatch obligation")?; - use crate::sema::{DynamicReason, resolution::Target}; - let target=super::names::resolve(program,caller,&call.source); - let user=match &target { Target::Local(id)|Target::Import{fun:id,..}=>Some(*id),_=>None }; - let user_dispatch=|id:usize|CallDispatch::User{target:id,tag_instance:program.parents[id].is_none()&&program.functions[id].source_ast.level==1}; - let expected=if let Some(receiver)=&call.source.receiver { - CallDispatch::Method{receiver:receiver.clone()} - } else if let Some(path)=call.source.path.as_ref().filter(|p|p.len()==2) { - let fallback=match user.map(user_dispatch) { - Some(CallDispatch::User{target,tag_instance})=>PathFallback::User{target,tag_instance}, - _=>PathFallback::Error{message:match target {Target::Unresolved{message,..}=>message,_=>format!("unresolved dynamic call `{}`",crate::sema::call_display(&call.source))}}, - }; - CallDispatch::Path{receiver:path[0].clone(),check_receiver:!fun.source_ast.imports.contains(&path[0]),fallback} - } else if let Some(id)=user {user_dispatch(id)} else {match target { - Target::Builtin(_)|Target::Dynamic{reason:DynamicReason::CallFn,..}=>CallDispatch::Builtin, - Target::Host(h)=>CallDispatch::Host{function:h.as_u16()}, - Target::Dynamic{reason:DynamicReason::Plugin,..}=>CallDispatch::Plugin, - Target::Unresolved{message,..}=>CallDispatch::ResolutionFault{message}, - _=>return Err("unmodeled source call resolution".into()), - }}; - if *dispatch!=expected{return Err("call resolution differs from source declaration graph".into());} - match dispatch { - CallDispatch::Path{..}=>{ - for stage in &call.stages{read_child(&mut c,&mut reloads,stage.slot)?;} - let id=match fun.code.get(c.position){Some(Op::PathCallArgs(owner,id)) if fun.calls.get(*owner).is_some_and(|other|std::ptr::eq(other,call))=>*id,_=>return Err("path call owner differs".into())}; - if fun.call_layouts.get(id)!=Some(&arguments){return Err("path call layout differs".into());} - let owner=fun.calls.iter().position(|other|std::ptr::eq(other,call)).unwrap(); - c.op(Op::PathCallArgs(owner,id))?; - }, - CallDispatch::ResolutionFault{message}=>{ - let index=match fun.code.get(c.position){Some(Op::RejectCallResolution(index))=>*index,_=>return Err("missing call resolution fault".into())}; - if fun.constants.get(index)!=Some(&Value::Text(message.clone())){return Err("call resolution fault payload differs".into());} - c.op(Op::RejectCallResolution(index))?; - }, - CallDispatch::RejectDuplicate { name } => { - let index = match fun.code.get(c.position) { - Some(Op::RejectDuplicateArgument(i)) => *i, - _ => return Err("duplicate argument refusal missing".into()), - }; - if fun.constants.get(index) != Some(&Value::Text(name.clone())) { - return Err("duplicate argument name differs".into()); - } - c.op(Op::RejectDuplicateArgument(index))?; - } - CallDispatch::User { - target, - tag_instance, - } => { - if *target >= program.functions.len() - || *tag_instance != program.objects.iter().any(|(_, id)| id == target) - { - return Err("resolved call target/tag differs".into()); - } - for stage in &call.stages { - read_child(&mut c, &mut reloads, stage.slot)?; - } - let id = layout(&mut c, &arguments)?; - c.op(Op::CallArgs(*target, id))?; - if *tag_instance { - c.op(Op::TagInstance(*target))?; - } - } - CallDispatch::Method { receiver } => { - if call.source.receiver.as_ref() != Some(receiver) - && call.source.path.as_ref().and_then(|p| p.first()) != Some(receiver) - { - return Err("method receiver differs from source".into()); - } - for stage in &call.stages { - read_child(&mut c, &mut reloads, stage.slot)?; - } - let slot = fun - .locals - .iter() - .position(|n| n == receiver) - .ok_or("method receiver slot")?; - read(&mut c, slot)?; - let index = match fun.code.get(c.position) { - Some(Op::MethodCallArgs(i, _)) => *i, - _ => return Err("method dispatch missing".into()), - }; - if fun.constants.get(index) != Some(&Value::Text(call.source.callee.clone())) { - return Err("method name differs from source".into()); - } - let id = layout(&mut c, &arguments)?; - c.op(Op::MethodCallArgs(index, id))?; - } - CallDispatch::Builtin|CallDispatch::Plugin|CallDispatch::Host{..}=>{ - for stage in &call.stages{read_child(&mut c,&mut reloads,stage.slot)?;} - let (first,id)=match fun.code.get(c.position){Some(Op::BuiltinCallArgs(n,l)|Op::PluginCallArgs(n,l))=>(*n,*l),Some(Op::HostCallArgs(n,l))=>(*n as usize,*l),_=>return Err("missing native argument dispatch".into())}; - if fun.call_layouts.get(id)!=Some(&arguments){return Err("native argument layout differs".into());} - match dispatch { - CallDispatch::Builtin=>{ - if crate::arguments::builtin_signature(&call.source.callee).is_none() || fun.constants.get(first)!=Some(&Value::Text(call.source.callee.clone())){return Err("builtin identity differs".into());} - c.op(Op::BuiltinCallArgs(first,id))?; - }, - CallDispatch::Plugin=>{ - if fun.constants.get(first)!=Some(&Value::Text(call.source.callee.clone())){return Err("plugin identity differs".into());} - c.op(Op::PluginCallArgs(first,id))?; - }, - CallDispatch::Host{function}=>{ - let hf=crate::host::HostFn::from_name(&call.source.callee).ok_or("source host name")?; - if hf.as_u16()!=*function || first!=*function as usize{return Err("host primitive identity differs".into());} - c.op(Op::HostCallArgs(*function,id))?; - },_=>unreachable!(), - } - } - - } - if reloads.next().is_some() || c.position != node.end { - return Err("call instruction/expression coverage differs".into()); - } - active.push((node, slots)); - } - if fun - .expressions - .iter() - .filter(|e| matches!(e.rule, ExpressionRule::CallBoundary(_))) - .count() - != owners.len() - { - return Err("uncovered call source expression".into()); - } - Ok(()) -} diff --git a/src/bytecode/compile.rs b/src/bytecode/compile.rs deleted file mode 100755 index 4961f43..0000000 --- a/src/bytecode/compile.rs +++ /dev/null @@ -1,997 +0,0 @@ -//! AST → bytecode Program. - -use anyhow::{bail, Result}; -use std::collections::HashMap; -use std::path::Path; - -use crate::ast::{ - Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Param, Stmt, UnaryOp, -}; -use crate::bytecode::{FnChunk, Op, Program}; -use crate::diagnostics::{bail_at, Span}; -use crate::value::Value; - -struct FlatFun<'m> { - owner: &'m Module, - definition: &'m Function, - source: crate::diagnostics::SourceIdentity, - module_path: Vec, - name: String, - level: u8, - /// Receiver-free children of an object are associated functions, not - /// instance methods. This flag is computed from executable AST only. - uses_receiver: bool, - parent: Option, - /// Inheritance base type name (`# Child = > Parent`), objects only. - base: Option, - params: Vec, - contract: Option, - var_contracts: HashMap, - body: Vec, - children: Vec, - span: Span, - /// Full path segments (`lib.member` / `lib.Type.method`) → flat index. - path_index: HashMap, usize>, - /// Short name from frontmatter `use` → path segments. - uses: HashMap>, - /// Module collection scope (G02): bare-name resolve must not cross imports. - scope: u32, -} - -pub fn compile_module(path: Option<&Path>, module: &Module) -> Result { - compile_with(path, module, true) -} - -/// Compile every function even when the file has no single program entry. -/// `Program::entry` is then only a placeholder; callers must use [`Vm::call_function`]. -pub fn compile_for_call(path: Option<&Path>, module: &Module) -> Result { - compile_with(path, module, false) -} - -fn compile_with(path: Option<&Path>, module: &Module, require_entry: bool) -> Result { - crate::ast::validate_parameters(module)?; - let mut flat = Vec::new(); - let mut next_scope = 1u32; - let _exports = collect_module_tree(module, &mut flat, 0, &mut next_scope, &[]); - for fun in &mut flat { - if fun.scope == 0 && fun.source.path.is_none() { - fun.source.path = path.map(Path::to_path_buf); - } - } - if flat.is_empty() { - bail!("bytecode: no functions to compile"); - } - - let chosen = flat - .iter() - .position(|f| f.scope == 0 && f.name == "main" && f.parent.is_none()) - .or_else(|| { - let tops: Vec = flat - .iter() - .enumerate() - .filter(|(_, f)| f.scope == 0 && f.parent.is_none() && f.level == 1 && f.params.is_empty()) - .map(|(i, _)| i) - .collect(); - if tops.len() == 1 { - Some(tops[0]) - } else { - None - } - }); - let entry = match chosen { - Some(index) => index, - None if !require_entry => 0, - None => bail!("bytecode: no `# main` object"), - }; - // Imports are compiled first, so a missing entry must take paths from the file's own functions. - let path_owner = if chosen.is_some() { - entry - } else { - flat.len() - 1 - }; - - let mut objects = Vec::new(); - let mut methods = Vec::new(); - for (i, f) in flat.iter().enumerate() { - if f.parent.is_none() && f.level == 1 { - objects.push((f.name.clone(), i)); - for &cid in &f.children { - methods.push((i, flat[cid].name.clone(), cid)); - } - } - } - let mut object_bases = Vec::with_capacity(objects.len()); - for (_, flat_i) in &objects { - let owner = &flat[*flat_i]; - let base = if let Some(base) = &owner.base { - let path = owner.uses.get(base).cloned().unwrap_or_else(|| vec![base.clone()]); - let (name, prefix) = path.split_last().expect("base path"); - let mut wanted = owner.module_path.clone(); - wanted.extend_from_slice(prefix); - let local = objects.iter().find(|(n,id)| n == name && flat[*id].module_path == wanted).map(|(_,id)| *id); - if local.is_some() || !prefix.is_empty() { local } else { - let candidates = objects.iter().filter(|(n,id)| n == name && flat[*id].module_path.starts_with(&owner.module_path)).map(|(_,id)| *id).collect::>(); - if candidates.len() == 1 { Some(candidates[0]) } else { None } - } - } else { None }; - object_bases.push(base); - } - - let mut functions = Vec::new(); - for i in 0..flat.len() { - let meta = if i == entry { - Some(module.metadata.as_slice()) - } else { - None - }; - let compiled = - compile_function(i, &flat, flat[i].source.path.as_deref(), meta).map_err(|error| { - if let Some(diagnostic) = crate::diagnostics::Diagnostic::find(&error).cloned() { - anyhow::Error::new(diagnostic.with_source(&flat[i].source)) - } else { - error - } - })?; - functions.push(compiled); - } - - let parents: Vec> = flat.iter().map(|f| f.parent).collect(); - let children: Vec> = flat.iter().map(|f| f.children.clone()).collect(); - let path_index = flat[path_owner].path_index.clone(); - - let program=Program { - entry_metadata: module.metadata.clone(), - functions, - entry, - objects, - object_bases, - methods, - parents, - children, - path_index, - }; - program.verify().map_err(|error|anyhow::anyhow!(error))?; - Ok(program) -} - -/// Collect `module` and its imports into `flat`. -/// Returns relative export paths within this module (e.g. `["parse"]`, `["agent","step"]`). -/// -/// Each module gets a distinct `scope` id. Bare-name `resolve_call` only searches -/// within the caller's scope so imported same-named functions cannot be silently -/// selected (BoundCall / G02). Cross-module calls must use `bind.member` paths. -fn collect_module_tree<'m>( - module: &'m Module, - flat: &mut Vec>, - scope: u32, - next_scope: &mut u32, - module_path: &[String], -) -> HashMap, usize> { - let mut path_index = HashMap::new(); - let mut imports = module.import_modules.iter().collect::>(); - imports.sort_by_key(|(name,_)| *name); - for (bind, dep) in imports { - let child_scope = *next_scope; - *next_scope += 1; - let mut child_path=module_path.to_vec(); child_path.push(bind.clone()); - let dep_exports = collect_module_tree(dep, flat, child_scope, next_scope, &child_path); - for (rel, idx) in dep_exports { - let mut full = Vec::with_capacity(rel.len() + 1); - full.push(bind.clone()); - full.extend(rel); - path_index.insert(full, idx); - } - } - - let uses: HashMap> = module - .uses - .iter() - .map(|u| (u.bind.clone(), u.path.clone())) - .collect(); - - let start = flat.len(); - let mut exports = HashMap::new(); - for fun in &module.functions { - let id = collect_fun(fun, module, None, flat, &path_index, &uses, scope, &module.source, module_path); - export_tree(&mut exports, &[], id, flat); - } - // Same-module BoundCall paths (`Type.member`) must be visible to siblings. - for (rel, idx) in &exports { - path_index.insert(rel.clone(), *idx); - } - for f in &mut flat[start..] { - if f.scope == scope { - for (rel, idx) in &exports { - f.path_index.insert(rel.clone(), *idx); - } - } - } - exports -} - -fn export_tree( - out: &mut HashMap, usize>, - prefix: &[String], - id: usize, - flat: &[FlatFun], -) { - let mut p = prefix.to_vec(); - p.push(flat[id].name.clone()); - out.entry(p.clone()).or_insert(id); - for &cid in &flat[id].children { - export_tree(out, &p, cid, flat); - } -} - -fn collect_fun<'m>( - fun: &'m Function, - owner: &'m Module, - parent: Option, - flat: &mut Vec>, - path_index: &HashMap, usize>, - uses: &HashMap>, - scope: u32, - source: &crate::diagnostics::SourceIdentity, - module_path: &[String], -) -> usize { - let id = flat.len(); - flat.push(FlatFun { - owner, definition: fun, - source: source.clone(), - module_path: module_path.to_vec(), - name: fun.name.clone(), - level: fun.level, - uses_receiver: crate::ast::function_uses_receiver(fun), - parent, - base: fun.base.clone(), - params: fun.params.clone(), - contract: fun.contract.clone(), - var_contracts: fun.var_contracts.clone(), - body: fun.body.clone(), - children: Vec::new(), - span: fun.span, - path_index: path_index.clone(), - uses: uses.clone(), - scope, - }); - let mut child_ids = Vec::new(); - for child in &fun.children { - child_ids.push(collect_fun( - child, - owner, - Some(id), - flat, - path_index, - uses, - scope, - source, - module_path, - )); - } - flat[id].children = child_ids; - id -} - -#[derive(Hash, PartialEq, Eq)] -enum ConstantKey { - None, - Bool(bool), - Int(i64), - Num(u64), - Text(String), -} - -struct FnCompiler<'a> { - path: Option<&'a Path>, - flat: &'a [FlatFun<'a>], - fn_id: usize, - chunk: FnChunk, - locals: HashMap, - stmt_span: Span, - call_depth: usize, - constant_indices: HashMap, - argument_scratch: HashMap<(usize,usize),(String,usize)>, - expression_stack: Vec, - statement_stack: Vec, - call_emission_stack: Vec, -} - -/// Reserve source names before synthesizing scratch names. This covers future -/// statements as well as defaults, so even an authored backtick name containing -/// the internal prefix cannot alias a temporary. -fn reserve_function_names(fun:&FlatFun,locals:&mut HashMap) { - fn name(name:&str,locals:&mut HashMap) { - if !locals.contains_key(name) { let slot=locals.len();locals.insert(name.into(),slot); } - } - fn call(call:&CallExpr,locals:&mut HashMap) { - if let Some(receiver)=&call.receiver { name(receiver,locals); } - if let Some(path)=&call.path { if let Some(first)=path.first() { name(first,locals); } } - for arg in &call.args { match arg { Arg::Named{value,..}|Arg::Positional(value)=>expr(value,locals) } } - } - fn expr(value:&Expr,locals:&mut HashMap) { - match value { - Expr::Var(value)=>name(value,locals), - Expr::Interp(parts)=>for part in parts { match part { - InterpPart::Lit(_)=>{}, - InterpPart::Var(value)|InterpPart::Index{base:value,..}=>name(value,locals), - } }, - Expr::Unary{expr:value,..}=>expr(value,locals), - Expr::Binary{left,right,..}=>{expr(left,locals);expr(right,locals);}, - Expr::Call(value)=>call(value,locals), - Expr::List(values)=>for value in values {expr(value,locals);}, - Expr::Map(values)=>for (_,value) in values {expr(value,locals);}, - Expr::Index{base,label}=>{expr(base,locals);if let crate::ast::IndexKey::Var(value)=label {name(value,locals);}}, - Expr::Occluded{payload,..}=>if let Some(value)=payload {expr(value,locals);}, - Expr::Literal(_)|Expr::Formula(_)|Expr::Code(_)=>{}, - } - } - fn block(statements:&[Stmt],locals:&mut HashMap) { - for statement in statements { match statement { - Stmt::Assign{name:key,value,..}=>{name(key,locals);expr(value,locals);}, - Stmt::Return{value,..}|Stmt::Expr{value,..}=>expr(value,locals), - Stmt::Call{call:value,..}=>call(value,locals), - Stmt::Branch{arms,..}=>for arm in arms {if let Some(condition)=&arm.condition {expr(condition,locals);}block(&arm.body,locals);}, - Stmt::While{condition,body,..}=>{expr(condition,locals);block(body,locals);}, - Stmt::ForEach{item,collection,body,..}=>{name(item,locals);name(collection,locals);block(body,locals);}, - } } - } - for param in &fun.params {if let Some(default)=¶m.default {expr(default,locals);}} - block(&fun.body,locals); -} - -fn compile_function( - fn_id: usize, - flat: &[FlatFun], - path: Option<&Path>, - metadata: Option<&[(String, Value)]>, -) -> Result { - let fun = &flat[fn_id]; - let mut locals = HashMap::new(); - for (i, p) in fun.params.iter().enumerate() { - locals.insert(p.name.clone(), i as usize); - } - let is_method = fun.uses_receiver; - if is_method { - for name in ["自", "self"] { - if !locals.contains_key(name) { - let s = locals.len() as usize; - locals.insert(name.to_string(), s); - } - } - } - // Phase 2: reserve locals for entry metadata keys before body compile. - if let Some(meta) = metadata { - for (k, _) in meta { - if !locals.contains_key(k) { - let s = locals.len() as usize; - locals.insert(k.clone(), s); - } - } - } - let mut c = FnCompiler { - path, - flat, - fn_id, - chunk: FnChunk { - source_ast: crate::bytecode::SourceFunction::from_declaration(fun.owner, fun.definition), - module_scope: fun.scope, - module_path: fun.module_path.clone(), - source: fun.source.clone(), - declaration_span: fun.span, - name: fun.name.clone(), - params: fun.params.iter().map(|p| p.name.clone()).collect(), - contract: fun.contract.clone(), - var_contracts: fun.var_contracts.clone(), - receiver_aliases: is_method, - defaults: fun.params.iter().map(|p| p.default.is_some()).collect(), - default_expressions:vec![None;fun.params.len()], - call_layouts: Vec::new(), - calls: Vec::new(), source_local_count:0, - expressions: Vec::new(), - statements: Vec::new(),statement_roots: Vec::new(),body_start:0, - code: Vec::new(), - spans: Vec::new(), - constants: Vec::new(), - locals: fun.params.iter().map(|p| p.name.clone()).collect(), - }, - locals, - stmt_span: fun.span, - call_depth: 0, - constant_indices: HashMap::new(), - argument_scratch: HashMap::new(), - expression_stack: Vec::new(), - statement_stack: Vec::new(), - call_emission_stack: Vec::new(), - }; - reserve_function_names(fun,&mut c.locals); - c.chunk.source_local_count=c.locals.len(); - // Defaults execute in the declaration's lexical scope and callee frame. - // None is a valid supplied value, so omission has a separate presence bit. - for (index, param) in fun.params.iter().enumerate() { - if let Some(default) = ¶m.default { - c.stmt_span=param.span; - let jump = c.here(); - c.emit(Op::JumpIfProvided(index as usize, 0)); - c.chunk.default_expressions[index]=Some(c.chunk.expressions.len()); - c.compile_expr(default)?; - c.emit(Op::SetLocal(index as usize)); - c.emit(Op::Pop); - c.patch(jump, Op::JumpIfProvided(index as usize, c.here())); - } - } - c.stmt_span=fun.span; - // Metadata is an input to Program::run, not code baked into a function. - // Fill only after defaults, so a later omitted default stays unbound while - // an earlier default evaluates. - c.emit(Op::FillMissingParameters); - if fun.contract.is_some() { c.emit(Op::CheckArguments); } - if is_method {c.emit(Op::RestoreReceiver);if fun.contract.is_some(){c.emit(Op::CheckFrameArguments);}} - c.chunk.body_start=c.here(); - for stmt in &fun.body { - c.compile_stmt(stmt)?; - } - c.stmt_span = fun.span; - c.emit(Op::None_); - c.emit(Op::Return); - let mut names = vec![String::new(); c.locals.len()]; - for (name, slot) in &c.locals { - names[*slot as usize] = name.clone(); - } - c.chunk.locals = names; - debug_assert_eq!(c.chunk.code.len(), c.chunk.spans.len()); - Ok(c.chunk) -} - -impl<'a> FnCompiler<'a> { - fn err(&self, message: impl Into) -> anyhow::Error { - bail_at(self.path, self.stmt_span, message) - } - - fn emit(&mut self, op: Op) { - self.chunk.code.push(op); - self.chunk.spans.push(self.stmt_span); - } - - fn here(&self) -> usize { - self.chunk.code.len() as usize - } - - fn patch(&mut self, at: usize, op: Op) { - self.chunk.code[at as usize] = op; - } - - fn add_const(&mut self, v: Value) -> usize { - // Index widths follow Vec rather than truncating at 8/16 bits. Scalar - // interning is linear overall; float keys preserve their exact bits. - let key = match &v { - Value::None => Some(ConstantKey::None), - Value::Bool(value) => Some(ConstantKey::Bool(*value)), - Value::Int(value) => Some(ConstantKey::Int(*value)), - Value::Num(value) => Some(ConstantKey::Num(value.to_bits())), - Value::Text(value) => Some(ConstantKey::Text(value.clone())), - _ => None, - }; - if let Some(index) = key.as_ref().and_then(|key| self.constant_indices.get(key)) { - return *index; - } - let i = self.chunk.constants.len(); - if let Some(key) = key { self.constant_indices.insert(key, i); } - self.chunk.constants.push(v); - i - } - - fn fresh_slot(&mut self,label:&str)->usize { - let mut name=format!("\0{label}.{}",self.locals.len()); - while self.locals.contains_key(&name){name.push('\0');} - let slot=self.locals.len();self.locals.insert(name,slot);slot - } - - fn local_slot(&mut self, name: &str) -> usize { - if let Some(&s) = self.locals.get(name) { - return s; - } - let s = self.locals.len() as usize; - self.locals.insert(name.to_string(), s); - s - } - - fn compile_stmt(&mut self,stmt:&Stmt)->Result<()> { - let id=self.chunk.statements.len();let start=self.here(); - self.chunk.statements.push(crate::bytecode::StatementEmission{ - rule:crate::bytecode::StatementRule::from_source(stmt),start,end:start, - statements:Vec::new(),expressions:Vec::new(),auxiliary:Vec::new(), - }); - if let Some(parent)=self.statement_stack.last(){self.chunk.statements[*parent].statements.push(id);}else{self.chunk.statement_roots.push(id);} - self.statement_stack.push(id);let result=self.compile_stmt_inner(stmt);self.statement_stack.pop(); - self.chunk.statements[id].end=self.here();result - } - fn compile_stmt_inner(&mut self, stmt: &Stmt) -> Result<()> { - match stmt { - Stmt::Assign { - name, value, span, .. - } => { - self.stmt_span = *span; - self.compile_expr(value)?; - let slot = self.local_slot(name); - if self.chunk.var_contracts.contains_key(name) { self.emit(Op::CheckBinding(slot)); } - self.emit(Op::SetLocal(slot)); - self.emit(Op::Pop); - } - Stmt::Return { value, span } => { - self.stmt_span = *span; - self.compile_expr(value)?; - if self.chunk.contract.is_some() { self.emit(Op::CheckReturn); } - self.emit(Op::Return); - } - Stmt::Call { call, span } => { - self.stmt_span = *span; - self.compile_expr(&Expr::Call(call.clone()))?; - self.emit(Op::Pop); - } - Stmt::Expr { value, span } => { - self.stmt_span = *span; - self.compile_expr(value)?; - self.emit(Op::Pop); - } - Stmt::Branch { arms, span } => { - self.stmt_span = *span; - let mut end_jumps = Vec::new(); - for (i, arm) in arms.iter().enumerate() { - let is_last = i + 1 == arms.len(); - let mut else_jump = None; - if let Some(cond) = &arm.condition { - self.compile_expr(cond)?; - let jf = self.here(); - self.emit(Op::JumpIfFalse(0)); - else_jump = Some(jf); - } - for st in &arm.body { - self.compile_stmt(st)?; - } - self.stmt_span = *span; - if !is_last { - let j = self.here(); - self.emit(Op::Jump(0)); - end_jumps.push(j); - } - if let Some(jf) = else_jump { - self.patch(jf, Op::JumpIfFalse(self.here())); - } - } - let end = self.here(); - for j in end_jumps { - self.patch(j, Op::Jump(end)); - } - } - Stmt::While { - condition, - body, - span, - } => { - self.stmt_span = *span; - let loop_id=*self.statement_stack.last().unwrap(); - self.emit(Op::ResetLoop(loop_id)); - let loop_start = self.here(); - self.compile_expr(condition)?; - let exit_j = self.here(); - self.emit(Op::JumpIfFalse(0)); - self.emit(Op::CheckLoop(loop_id)); - for st in body { - self.compile_stmt(st)?; - } - self.stmt_span = *span; - self.emit(Op::Jump(loop_start)); - self.patch(exit_j, Op::JumpIfFalse(self.here())); - } - Stmt::ForEach { - item, - collection, - label: _, - body, - span, - } => { - self.stmt_span = *span; - self.compile_expr(&Expr::Var(collection.clone()))?; - self.emit(Op::IterItems); - let coll_slot = self.fresh_slot("loop.collection"); - self.emit(Op::SetLocal(coll_slot)); - self.emit(Op::Pop); - let i_slot = self.fresh_slot("loop.index"); - let statement=*self.statement_stack.last().unwrap(); - self.chunk.statements[statement].auxiliary=vec![coll_slot,i_slot]; - let zero = self.add_const(Value::Int(0)); - self.emit(Op::Constant(zero)); - self.emit(Op::SetLocal(i_slot)); - self.emit(Op::Pop); - let item_slot = self.local_slot(item); - - let loop_start = self.here(); - self.emit(Op::GetLocal(i_slot)); - self.emit(Op::GetLocal(coll_slot)); - self.emit(Op::Len); - self.emit(Op::Less); - let exit_j = self.here(); - self.emit(Op::JumpIfFalse(0)); - - self.emit(Op::GetLocal(coll_slot)); - self.emit(Op::GetLocal(i_slot)); - self.emit(Op::GetIndex); - self.emit(Op::SetLocal(item_slot)); - self.emit(Op::Pop); - - for st in body { - self.compile_stmt(st)?; - } - - self.stmt_span = *span; - self.emit(Op::GetLocal(i_slot)); - let one = self.add_const(Value::Int(1)); - self.emit(Op::Constant(one)); - self.emit(Op::Add); - self.emit(Op::SetLocal(i_slot)); - self.emit(Op::Pop); - self.emit(Op::Jump(loop_start)); - self.patch(exit_j, Op::JumpIfFalse(self.here())); - } - } - Ok(()) - } - - fn compile_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> { - let id=self.chunk.calls.len(); - self.chunk.calls.push(crate::bytecode::CallEmission{ - expression:*self.expression_stack.last().ok_or_else(||self.err("call has no source expression"))?, - source:call.clone(),stages:Vec::new(),dispatch:None,as_statement:as_stmt, - }); - self.call_emission_stack.push(id); - self.call_depth += 1; - let result = self.compile_call_inner(call, as_stmt); - self.call_depth -= 1; - self.call_emission_stack.pop(); - result - } - - fn record_dispatch(&mut self, dispatch:crate::bytecode::CallDispatch){ - let id=*self.call_emission_stack.last().expect("active call emission"); - self.chunk.calls[id].dispatch=Some(dispatch); - } - - fn compile_call_inner(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> { - // Mirror `sema::bind::resolve_for_exec` (G02 BoundCall): - // static → Op::Call(fid); dynamic → MethodCall / CallFn / PluginCall. - let mut call = call.for_evaluation().map_err(|m| self.err(m))?; - let emission=*self.call_emission_stack.last().expect("active call emission"); - self.chunk.calls[emission].source=call.clone(); - // All actuals run once, left to right, including unused extra named - // arguments. Subsequent parameter permutation only reads temporaries. - for (index, arg) in call.args.iter_mut().enumerate() { - let value = match arg { - Arg::Positional(value) => value, - Arg::Named { value, .. } => value - }; - let expression=self.chunk.expressions.len(); - self.compile_expr(value)?; - let key=(self.call_depth,index); - let (name,slot)=if let Some(existing)=self.argument_scratch.get(&key) { existing.clone() } else { - let mut name=format!("\0call.arg.{}.{}", self.call_depth, index); - while self.locals.contains_key(&name) { name.push('\0'); } - let slot = self.locals.len() as usize; - self.locals.insert(name.clone(), slot); - self.argument_scratch.insert(key,(name.clone(),slot)); - (name,slot) - }; - self.emit(Op::SetLocal(slot)); - self.emit(Op::Pop); - self.chunk.calls[emission].stages.push(crate::bytecode::CallStage{expression,slot}); - *value = Expr::Var(name); - } - if let Some(recv) = &call.receiver { - return self.compile_method_call(recv, &call, as_stmt); - } - use crate::sema::{ExecTarget, DynamicReason}; - let caller=&self.flat[self.fn_id]; - let target=crate::sema::resolve_for_exec(caller.owner,caller.definition,&call); - let user=match &target { - ExecTarget::Local(fun)=>Some((caller.owner,*fun)), - ExecTarget::Import{lib,fun,..}=>Some((*lib,*fun)), - _=>None, - }; - let fid=user.map(|(owner,definition)|self.flat.iter().position(|f|std::ptr::eq(f.owner,owner)&&std::ptr::eq(f.definition,definition)) - .ok_or_else(||self.err("resolved declaration missing from flat program"))).transpose()?; - if let Some(path)=call.path.as_ref().filter(|p|p.len()==2) { - let fallback=if let Some(target)=fid { crate::bytecode::PathFallback::User{target,tag_instance:self.flat[target].parent.is_none()&&self.flat[target].level==1} } - else { crate::bytecode::PathFallback::Error{message:match target { - ExecTarget::Unresolved{message,..}=>message, - _=>format!("unresolved dynamic call `{}`",crate::sema::call_display(&call)), - }} }; - self.record_dispatch(crate::bytecode::CallDispatch::Path{receiver:path[0].clone(),check_receiver:!caller.owner.import_modules.contains_key(&path[0]),fallback}); - let layout=self.argument_layout(&call)?; - self.emit(Op::PathCallArgs(emission,layout)); - if as_stmt{self.emit(Op::Pop);}return Ok(()); - } - if let Some(fid)=fid{return self.compile_user_call(fid,&call,as_stmt);} - match target { - ExecTarget::Builtin(_) | ExecTarget::Dynamic{reason:DynamicReason::CallFn,..}=>{ - self.record_dispatch(crate::bytecode::CallDispatch::Builtin); - let layout=self.argument_layout(&call)?;let name=self.add_const(Value::Text(call.callee.clone())); - self.emit(Op::BuiltinCallArgs(name,layout));if as_stmt{self.emit(Op::Pop);}return Ok(()); - }, - ExecTarget::Host(hf)=>{ - self.record_dispatch(crate::bytecode::CallDispatch::Host{function:hf.as_u16()}); - let layout=self.argument_layout(&call)?;self.emit(Op::HostCallArgs(hf.as_u16(),layout)); - if as_stmt{self.emit(Op::Pop);}return Ok(()); - }, - ExecTarget::Dynamic{reason:DynamicReason::Plugin,..}=>self.compile_plugin_call(&call,as_stmt), - ExecTarget::Unresolved{message,..}=>{ - self.record_dispatch(crate::bytecode::CallDispatch::ResolutionFault{message:message.clone()}); - let index=self.add_const(Value::Text(message));self.emit(Op::RejectCallResolution(index));Ok(()) - }, - _=>Err(self.err("unsupported resolved call")), - } - } - - fn argument_layout(&mut self, call: &CallExpr) -> Result { - let mut layout = Vec::new(); - for arg in &call.args { - let (name, expr) = match arg { - Arg::Positional(expr) => (None, expr), - Arg::Named { name, value } => (Some(name.clone()), value), - }; - self.compile_expr(expr)?; - layout.push(name); - } - let index = self.chunk.call_layouts.len() as usize; - self.chunk.call_layouts.push(layout); - Ok(index) - } - - fn compile_user_call(&mut self, fid: usize, call: &CallExpr, as_stmt: bool) -> Result<()> { - self.record_dispatch(crate::bytecode::CallDispatch::User{target:fid,tag_instance:self.flat[fid].parent.is_none() && self.flat[fid].level==1}); - let layout = self.argument_layout(call)?; - self.emit(Op::CallArgs(fid as usize, layout)); - if self.flat[fid].parent.is_none() && self.flat[fid].level == 1 { - self.emit(Op::TagInstance(fid)); - } - if as_stmt { self.emit(Op::Pop); } - Ok(()) - } - - /// Unresolved callee → runtime plugin registry (or unknown-fn error). - /// Preserve authored labels until the runtime registry supplies the signature. - fn compile_plugin_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> { - self.record_dispatch(crate::bytecode::CallDispatch::Plugin); - let layout=self.argument_layout(call)?; - let name=self.add_const(Value::Text(call.callee.clone())); - self.emit(Op::PluginCallArgs(name,layout)); - if as_stmt{self.emit(Op::Pop);}Ok(()) - } - - fn compile_method_call(&mut self, recv: &str, call: &CallExpr, as_stmt: bool) -> Result<()> { - self.record_dispatch(crate::bytecode::CallDispatch::Method{receiver:recv.into()}); - // A method name alone does not determine a signature. Its owner is - // selected from the actual receiver before runtime argument binding. - let layout = self.argument_layout(call)?; - let slot = self.locals.get(recv).copied() - .ok_or_else(|| self.err(format!("undefined variable `{recv}`")))?; - self.emit(Op::GetLocal(slot)); - let name = self.add_const(Value::Text(call.callee.clone())); - self.emit(Op::MethodCallArgs(name, layout)); - if as_stmt { self.emit(Op::Pop); } - Ok(()) - } - - fn compile_expr(&mut self, expr:&Expr)->Result<()> { - let id=self.chunk.expressions.len(); - let start=self.here(); - self.chunk.expressions.push(crate::bytecode::ExpressionEmission{ - rule:crate::bytecode::ExpressionRule::from_source(expr),start,end:start,children:Vec::new(), - }); - if let Some(parent)=self.expression_stack.last(){self.chunk.expressions[*parent].children.push(id);}else if let Some(stmt)=self.statement_stack.last(){self.chunk.statements[*stmt].expressions.push(id);} - self.expression_stack.push(id); - let result=self.compile_expr_inner(expr); - self.expression_stack.pop(); - self.chunk.expressions[id].end=self.here(); - result - } - - fn compile_expr_inner(&mut self, expr: &Expr) -> Result<()> { - match expr { - // `` M2: occlusion is transparent for execution — only the - // payload runs; the label is diagnosed/rendered, never evaluated. - Expr::Occluded { payload, .. } => match payload { - Some(inner) => self.compile_expr(inner)?, - None => self.emit(Op::None_), - }, - Expr::Literal(lit) => match lit { - Literal::None => self.emit(Op::None_), - Literal::Bool(true) => self.emit(Op::True), - Literal::Bool(false) => self.emit(Op::False), - Literal::Int(n) => { - let i = self.add_const(Value::Int(*n)); - self.emit(Op::Constant(i)); - } - Literal::Num(n) => { - let i = self.add_const(Value::Num(*n)); - self.emit(Op::Constant(i)); - } - Literal::Text(t) => { - let i = self.add_const(Value::Text(t.clone())); - self.emit(Op::Constant(i)); - } - }, - Expr::Var(name) => { - let slot = self - .locals - .get(name) - .copied() - .ok_or_else(|| self.err(format!("undefined variable `{name}`")))?; - self.emit(Op::GetLocal(slot)); - } - Expr::Interp(parts) => { - if parts.is_empty() { - let i = self.add_const(Value::Text(String::new())); - self.emit(Op::Constant(i)); - return Ok(()); - } - for (idx, part) in parts.iter().enumerate() { - match part { - InterpPart::Lit(t) => { - let i = self.add_const(Value::Text(t.clone())); - self.emit(Op::Constant(i)); - } - InterpPart::Var(n) => { - let slot = self - .locals - .get(n) - .copied() - .ok_or_else(|| self.err(format!("undefined variable `{n}`")))?; - self.emit(Op::GetLocal(slot)); - } - InterpPart::Index { base, labels } => { - let slot = - self.locals.get(base).copied().ok_or_else(|| { - self.err(format!("undefined variable `{base}`")) - })?; - self.emit(Op::GetLocal(slot)); - for label in labels { - let li = self.add_const(Value::Text(label.clone())); - self.emit(Op::Constant(li)); - self.emit(Op::FootnoteGet); - } - } - } - self.emit(Op::Str); - if idx > 0 { - self.emit(Op::Add); - } - } - } - Expr::Unary { op, expr } => { - self.compile_expr(expr)?; - match op { - UnaryOp::Not => self.emit(Op::Not), - UnaryOp::Neg => self.emit(Op::Negate), - } - } - Expr::Binary { - op: BinaryOp::And, - left, - right, - } => { - self.compile_expr(left)?; - let j_false = self.here(); - self.emit(Op::JumpIfFalse(0)); - self.compile_expr(right)?; - let j_false2 = self.here(); - self.emit(Op::JumpIfFalse(0)); - self.emit(Op::True); - let j_end = self.here(); - self.emit(Op::Jump(0)); - let f2 = self.here(); - self.patch(j_false2, Op::JumpIfFalse(f2)); - self.emit(Op::False); - let j_end2 = self.here(); - self.emit(Op::Jump(0)); - let f1 = self.here(); - self.patch(j_false, Op::JumpIfFalse(f1)); - self.emit(Op::False); - let end = self.here(); - self.patch(j_end, Op::Jump(end)); - self.patch(j_end2, Op::Jump(end)); - } - Expr::Binary { - op: BinaryOp::Or, - left, - right, - } => { - self.compile_expr(left)?; - let j_else = self.here(); - self.emit(Op::JumpIfFalse(0)); - self.emit(Op::True); - let j_end = self.here(); - self.emit(Op::Jump(0)); - let else_ip = self.here(); - self.patch(j_else, Op::JumpIfFalse(else_ip)); - self.compile_expr(right)?; - let j_f = self.here(); - self.emit(Op::JumpIfFalse(0)); - self.emit(Op::True); - let j_end2 = self.here(); - self.emit(Op::Jump(0)); - let f = self.here(); - self.patch(j_f, Op::JumpIfFalse(f)); - self.emit(Op::False); - let end = self.here(); - self.patch(j_end, Op::Jump(end)); - self.patch(j_end2, Op::Jump(end)); - } - Expr::Binary { op, left, right } => { - self.compile_expr(left)?; - self.compile_expr(right)?; - self.emit(match op { - BinaryOp::Add => Op::Add, - BinaryOp::Sub => Op::Sub, - BinaryOp::Mul => Op::Mul, - BinaryOp::Div => Op::Div, - BinaryOp::Eq => Op::Equal, - BinaryOp::Ne => Op::NotEqual, - BinaryOp::Lt => Op::Less, - BinaryOp::Le => Op::Lessequal, - BinaryOp::Gt => Op::Greater, - BinaryOp::Ge => Op::GreaterEqual, - BinaryOp::And | BinaryOp::Or => unreachable!(), - }); - } - Expr::Call(call) => { - if let Err(message)=call.for_evaluation(){ - let index=self.add_const(Value::Text(message)); - self.emit(Op::RejectArgumentExpansion(index)); - }else{self.compile_call(call, false)?;} - }, - Expr::List(items) => { - for it in items { - self.compile_expr(it)?; - } - self.emit(Op::BuildList(items.len() as usize)); - } - Expr::Map(pairs) => { - for (k, e) in pairs { - let ki = self.add_const(Value::Text(k.clone())); - self.emit(Op::Constant(ki)); - self.compile_expr(e)?; - } - self.emit(Op::BuildMap(pairs.len() as usize)); - } - Expr::Index { base, label } => { - self.compile_expr(base)?; - match label { - crate::ast::IndexKey::Lit(s) => { - let li = self.add_const(Value::Text(s.clone())); - self.emit(Op::Constant(li)); - } - crate::ast::IndexKey::Var(name) => { - let slot = self.locals.get(name).copied().ok_or_else(|| { - self.err(format!("undefined variable `{name}` in footnote key")) - })?; - self.emit(Op::GetLocal(slot)); - self.emit(Op::Str); - } - } - if let Expr::Var(name)=base.as_ref() { - if self.chunk.var_contracts.contains_key(name) { - self.emit(Op::ContractFootnoteGet(self.locals[name])); - } else { self.emit(Op::FootnoteGet); } - } else { self.emit(Op::FootnoteGet); } - } - Expr::Formula(e) => { - let i = self.add_const(Value::Formula(e.clone())); - self.emit(Op::Constant(i)); - } - Expr::Code(c) => { - let i = self.add_const(Value::Code(c.clone())); - self.emit(Op::Constant(i)); - } - } - Ok(()) - } -} diff --git a/src/bytecode/expression.rs b/src/bytecode/expression.rs deleted file mode 100755 index e9aa5a2..0000000 --- a/src/bytecode/expression.rs +++ /dev/null @@ -1,439 +0,0 @@ -//! Source-directed expression emission obligations. Call staging and selection -//! are checked separately in call.rs; dispatch semantics remain a proof boundary. -use super::{FnChunk, Op}; -use crate::{ - ast::{BinaryOp, Expr, IndexKey, InterpPart, Literal, UnaryOp}, - value::Value, -}; - -#[derive(Debug, Clone)] -pub enum ExpressionRule { - Literal(Value), - Read(String), - Unary(UnaryOp), - Binary(BinaryOp), - Interpolation(Vec), - List(usize), - Map(Vec), - Index { - label: IndexKey, - base_variable: Option, - }, - Occluded(bool), - CallBoundary(Vec), - CallFault(String), -} -impl ExpressionRule { - pub fn from_source(expr: &Expr) -> Self { - match expr { - Expr::Literal(value) => Self::Literal(match value { - Literal::None => Value::None, - Literal::Bool(v) => Value::Bool(*v), - Literal::Int(v) => Value::Int(*v), - Literal::Num(v) => Value::Num(*v), - Literal::Text(v) => Value::Text(v.clone()), - }), - Expr::Var(name) => Self::Read(name.clone()), - Expr::Unary { op, .. } => Self::Unary(*op), - Expr::Binary { op, .. } => Self::Binary(*op), - Expr::Interp(parts) => Self::Interpolation(parts.clone()), - Expr::List(items) => Self::List(items.len()), - Expr::Map(items) => Self::Map(items.iter().map(|(k, _)| k.clone()).collect()), - Expr::Index { base, label } => Self::Index { - label: label.clone(), - base_variable: if let Expr::Var(name) = base.as_ref() { - Some(name.clone()) - } else { - None - }, - }, - Expr::Formula(value) => Self::Literal(Value::Formula(value.clone())), - Expr::Code(value) => Self::Literal(Value::Code(value.clone())), - Expr::Occluded { payload, .. } => Self::Occluded(payload.is_some()), - Expr::Call(call) if call.for_evaluation().is_err() => { - Self::CallFault(call.for_evaluation().unwrap_err()) - } - Expr::Call(call) => Self::CallBoundary( - call.receiver - .iter() - .cloned() - .chain(call.path.iter().filter_map(|path| path.first().cloned())) - .collect(), - ), - } - } -} -#[derive(Debug, Clone)] -pub struct ExpressionEmission { - pub rule: ExpressionRule, - pub start: usize, - pub end: usize, - pub children: Vec, -} - -pub(super) fn formula_equal(a: &crate::formula::Expr, b: &crate::formula::Expr) -> bool { - use crate::formula::Expr::*; - match (a, b) { - (Num(x), Num(y)) => x.to_bits() == y.to_bits(), - (Var(x), Var(y)) => x == y, - (UnaryNeg(x), UnaryNeg(y)) => formula_equal(x, y), - ( - Bin { - op: a, - left: x, - right: y, - }, - Bin { - op: b, - left: u, - right: v, - }, - ) => a == b && formula_equal(x, u) && formula_equal(y, v), - (Call { name: a, args: x }, Call { name: b, args: y }) => { - a == b && x.len() == y.len() && x.iter().zip(y).all(|(a, b)| formula_equal(a, b)) - } - (Matrix { source: a, rows: x }, Matrix { source: b, rows: y }) => { - a == b - && x.len() == y.len() - && x.iter().zip(y).all(|(a, b)| { - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()) - }) - } - _ => false, - } -} -fn value_equal(a: &Value, b: &Value) -> bool { - match (a, b) { - (Value::Num(x), Value::Num(y)) => x.to_bits() == y.to_bits(), - (Value::Formula(x), Value::Formula(y)) => formula_equal(x, y), - _ => a == b, - } -} -pub(super) struct Cursor<'a> { - pub(super) fun: &'a FnChunk, - pub(super) position: usize, - pub(super) end: usize, -} -impl Cursor<'_> { - pub(super) fn op(&mut self, expected: Op) -> Result<(), String> { - if self.position >= self.end || self.fun.code.get(self.position) != Some(&expected) { - return Err(format!( - "source expression opcode differs at {}: expected {expected:?}", - self.position - )); - } - self.position += 1; - Ok(()) - } - pub(super) fn literal(&mut self, value: &Value) -> Result<(), String> { - match value { - Value::None => self.op(Op::None_), - Value::Bool(true) => self.op(Op::True), - Value::Bool(false) => self.op(Op::False), - _ => { - let Some(Op::Constant(index)) = self.fun.code.get(self.position) else { - return Err("source literal is not a constant instruction".into()); - }; - if !self - .fun - .constants - .get(*index) - .is_some_and(|actual| value_equal(actual, value)) - { - return Err("source literal value differs".into()); - } - self.op(Op::Constant(*index)) - } - } - } - fn read(&mut self, name: &str) -> Result<(), String> { - let slot = self - .fun - .locals - .iter() - .position(|local| local == name) - .ok_or("source variable has no slot")?; - self.op(Op::GetLocal(slot)) - } - pub(super) fn child(&mut self, id: usize) -> Result<(), String> { - let child = &self.fun.expressions[id]; - if child.start != self.position { - return Err("source operand order/range differs".into()); - } - self.position = child.end; - Ok(()) - } -} -pub fn verify(fun: &FnChunk) -> Result { - let mut boundaries = 0; - for (id, node) in fun.expressions.iter().enumerate() { - if node.start >= node.end || node.end > fun.code.len() { - return Err("invalid source expression interval".into()); - } - for child in &node.children { - if *child <= id || *child >= fun.expressions.len() { - return Err("invalid source expression child".into()); - } - let c = &fun.expressions[*child]; - if c.start < node.start || c.end > node.end { - return Err("expression child outside parent".into()); - } - } - let mut c = Cursor { - fun, - position: node.start, - end: node.end, - }; - let expected_children = match &node.rule { - ExpressionRule::Literal(v) => { - c.literal(v)?; - 0 - } - ExpressionRule::Read(name) => { - c.read(name)?; - 0 - } - ExpressionRule::Unary(op) => { - if node.children.len() != 1 { - return Err("unary source arity".into()); - } - c.child(node.children[0])?; - c.op(match op { - UnaryOp::Not => Op::Not, - UnaryOp::Neg => Op::Negate, - })?; - 1 - } - ExpressionRule::Binary(op) => { - if node.children.len() != 2 { - return Err("binary source arity".into()); - } - let left = &fun.expressions[node.children[0]]; - let right = &fun.expressions[node.children[1]]; - c.child(node.children[0])?; - match op { - BinaryOp::And => { - c.op(Op::JumpIfFalse(right.end + 5))?; - c.child(node.children[1])?; - for op in [ - Op::JumpIfFalse(right.end + 3), - Op::True, - Op::Jump(node.end), - Op::False, - Op::Jump(node.end), - Op::False, - ] { - c.op(op)?; - } - } - BinaryOp::Or => { - c.op(Op::JumpIfFalse(right.start))?; - c.op(Op::True)?; - c.op(Op::Jump(node.end))?; - c.child(node.children[1])?; - for op in [ - Op::JumpIfFalse(right.end + 3), - Op::True, - Op::Jump(node.end), - Op::False, - ] { - c.op(op)?; - } - } - _ => { - let _ = left; - c.child(node.children[1])?; - c.op(match op { - BinaryOp::Add => Op::Add, - BinaryOp::Sub => Op::Sub, - BinaryOp::Mul => Op::Mul, - BinaryOp::Div => Op::Div, - BinaryOp::Eq => Op::Equal, - BinaryOp::Ne => Op::NotEqual, - BinaryOp::Lt => Op::Less, - BinaryOp::Le => Op::Lessequal, - BinaryOp::Gt => Op::Greater, - BinaryOp::Ge => Op::GreaterEqual, - _ => unreachable!(), - })?; - } - } - 2 - } - ExpressionRule::List(count) => { - for child in &node.children { - c.child(*child)?; - } - c.op(Op::BuildList(*count))?; - *count - } - ExpressionRule::Map(keys) => { - if node.children.len() != keys.len() { - return Err("map source arity".into()); - } - for (key, child) in keys.iter().zip(&node.children) { - c.literal(&Value::Text(key.clone()))?; - c.child(*child)?; - } - c.op(Op::BuildMap(keys.len()))?; - keys.len() - } - ExpressionRule::Occluded(payload) => { - if *payload { - if node.children.len() != 1 { - return Err("occluded source arity".into()); - } - c.child(node.children[0])?; - 1 - } else { - c.literal(&Value::None)?; - 0 - } - } - ExpressionRule::Index { - label, - base_variable, - } => { - if node.children.len() != 1 { - return Err("index source arity".into()); - } - c.child(node.children[0])?; - match label { - IndexKey::Lit(key) => c.literal(&Value::Text(key.clone()))?, - IndexKey::Var(name) => { - c.read(name)?; - c.op(Op::Str)?; - } - } - if let Some(name) = base_variable - .as_ref() - .filter(|name| fun.var_contracts.contains_key(*name)) - { - let slot = fun - .locals - .iter() - .position(|local| local == name) - .ok_or("index source slot")?; - c.op(Op::ContractFootnoteGet(slot))?; - } else { - c.op(Op::FootnoteGet)?; - } - 1 - } - ExpressionRule::Interpolation(parts) => { - if parts.is_empty() { - c.literal(&Value::Text(String::new()))?; - } - for (i, part) in parts.iter().enumerate() { - match part { - InterpPart::Lit(value) => c.literal(&Value::Text(value.clone()))?, - InterpPart::Var(name) => c.read(name)?, - InterpPart::Index { base, labels } => { - c.read(base)?; - for label in labels { - c.literal(&Value::Text(label.clone()))?; - c.op(Op::FootnoteGet)?; - } - } - } - c.op(Op::Str)?; - if i > 0 { - c.op(Op::Add)?; - } - } - 0 - } - ExpressionRule::CallFault(message) => { - let Some(Op::RejectArgumentExpansion(index)) = fun.code.get(c.position) else { - return Err("missing argument preparation fault".into()); - }; - if fun.constants.get(*index) != Some(&Value::Text(message.clone())) { - return Err("argument preparation message differs".into()); - } - c.op(Op::RejectArgumentExpansion(*index))?; - 0 - } - ExpressionRule::CallBoundary(_) => { - boundaries += 1; - continue; - } - }; - if node.children.len() != expected_children || c.position != node.end { - return Err("source expression coverage differs".into()); - } - } - Ok(boundaries) -} - -/// Local evidence preserves machine values, not the narrower foreign copy domain. -pub(super) fn interpolation_evidence(part: &InterpPart) -> serde_json::Value { - use serde_json::json; - match part { - InterpPart::Lit(value) => json!({"kind":"text","value":value}), - InterpPart::Var(name) => json!({"kind":"read","name":name}), - InterpPart::Index { base, labels } => json!({"kind":"index","base":base,"labels":labels}), - } -} -pub(super) fn index_evidence(key: &IndexKey) -> serde_json::Value { - use serde_json::json; - match key { - IndexKey::Lit(value) => json!({"kind":"literal","value":value}), - IndexKey::Var(name) => json!({"kind":"read","name":name}), - } -} -pub(super) fn formula_evidence(value: &crate::formula::Expr) -> serde_json::Value { - use crate::formula::Expr::*; - use serde_json::json; - match value { - Num(n) => json!({"kind":"number","bits":n.to_bits()}), - Var(name) => json!({"kind":"variable","name":name}), - UnaryNeg(value) => json!({"kind":"negative","value":formula_evidence(value)}), - Bin { op, left, right } => { - json!({"kind":"binary","op":format!("{op:?}"),"left":formula_evidence(left),"right":formula_evidence(right)}) - } - Call { name, args } => { - json!({"kind":"call","name":name,"args":args.iter().map(formula_evidence).collect::>()}) - } - Matrix { source, rows } => { - json!({"kind":"matrix","source":source,"rows":rows.iter().map(|row|row.iter().map(|n|n.to_bits()).collect::>()).collect::>()}) - } - } -} -pub fn value_evidence(value: &Value) -> serde_json::Value { - use serde_json::json; - match value { - Value::None => json!({"tag":"none"}), - Value::Bool(v) => json!({"tag":"bool","value":v}), - Value::Int(v) => json!({"tag":"int","value":v}), - Value::Num(v) => json!({"tag":"num","bits":v.to_bits()}), - Value::Text(v) => json!({"tag":"text","value":v}), - Value::Code(v) => json!({"tag":"code","lang":v.lang,"source":v.source}), - Value::Formula(v) => json!({"tag":"formula","value":formula_evidence(v)}), - _ => json!({"tag":"nonliteral","value":format!("{value:?}")}), - } -} -impl ExpressionRule { - pub fn evidence(&self) -> serde_json::Value { - use serde_json::json; - match self { - Self::Literal(v) => json!({"kind":"literal","value":value_evidence(v)}), - Self::Read(name) => json!({"kind":"read","name":name}), - Self::Unary(op) => json!({"kind":"unary","op":format!("{op:?}")}), - Self::Binary(op) => json!({"kind":"binary","op":format!("{op:?}")}), - Self::CallBoundary(names) => json!({"kind":"call_boundary","names":names}), - Self::CallFault(message) => json!({"kind":"call_expansion_fault","message":message}), - Self::Interpolation(parts) => { - json!({"kind":"interpolation_boundary","parts":parts.iter().map(interpolation_evidence).collect::>()}) - } - Self::List(n) => json!({"kind":"list","arity":n}), - Self::Map(keys) => json!({"kind":"map","keys":keys}), - Self::Index { - label, - base_variable, - } => { - json!({"kind":"index_boundary","label":index_evidence(label),"base_variable":base_variable}) - } - Self::Occluded(payload) => json!({"kind":"occluded","payload":payload}), - } - } -} diff --git a/src/bytecode/mod.rs b/src/bytecode/mod.rs deleted file mode 100755 index 2a258ab..0000000 --- a/src/bytecode/mod.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! Bytecode chunk + opcodes (M5 prototype). - -mod compile; -mod vm; -mod verify; -mod expression; -mod statement; -mod call; -mod source; -mod names; -pub use source::SourceFunction; -pub use call::{CallEmission, CallStage, CallDispatch, PathFallback}; -pub use statement::{StatementRule,StatementEmission}; -pub use expression::{ExpressionRule,ExpressionEmission,value_evidence as expression_value_evidence}; -pub use verify::StackCertificate; - -pub use compile::{compile_for_call, compile_module}; -pub use vm::Vm; - -use std::collections::HashMap; - -use crate::diagnostics::Span; -use crate::value::Value; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Op { - Constant(usize), - True, - False, - None_, - Pop, - GetLocal(usize), - SetLocal(usize), - Add, - Sub, - Mul, - Div, - Negate, - Not, - Equal, - NotEqual, - Greater, - GreaterEqual, - Less, - Lessequal, - /// Absolute jump to instruction index. - Jump(usize), - JumpIfFalse(usize), - Print, - /// Pop prompt text, print it (no newline), read one stdin line → push Text. - Input, - BuildList(usize), - /// Stack (bottom→top): k0, v0, k1, v1, … (n pairs); push Map. - BuildMap(usize), - /// Pop value → push `len` (text/list). - Len, - /// Pop value → push display text. - Str, - /// Pop value → push int (or fail). - Int, - /// Pop value → push type name text. - TypeOf, - /// Pop text → push trimmed text. - Trim, - /// Pop sep, then value → push list of text parts. - Split, - /// Pop sep, then list → push joined text. - Join, - GetIndex, - /// Pop list/map → push list of foreach items (list elements or map keys). - IterItems, - /// Pop footnote label text, then base → push indexed value (1-based list / map key). - FootnoteGet, - /// Call function by index; argc values are on the stack (param order). - Call(usize, usize), - /// Evaluated actuals in authored order; layout preserves optional names. - CallArgs(usize, usize), - /// Runtime binding fault after all explicit actual effects. - RejectDuplicateArgument(usize), - /// Modifier/argument preparation failed before any actual is evaluated. - RejectArgumentExpansion(usize), - /// Skip a callee default when the parameter was explicitly supplied. - JumpIfProvided(usize, usize), - /// Entry/raw-call parameters without a value retain language None after defaults. - FillMissingParameters, - ResetLoop(usize), - CheckLoop(usize), - CheckArguments, - RestoreReceiver, - CheckFrameArguments, - CheckReturn, - /// Check the stack top against the named local's field contract. - CheckBinding(usize), - /// Checked footnote access; operand identifies the contracted base local. - ContractFootnoteGet(usize), - /// Pop function name text → call zero-arg top-level or lexically visible function. - CallFn, - /// After a constructor call: stamp name and module of functions[idx]. - TagInstance(usize), - /// Method call: stack has argc args (param order) then receiver on top. - /// constants[name_idx] is method name text; resolve via receiver `_type`. - MethodCall(usize, usize), - /// Resolve the receiver first, then bind against that method's signature. - MethodCallArgs(usize, usize), - /// Plugin call: stack has argc args in registered param order; name in constants. - PluginCall(usize, usize), - /// Host primitive: pop `argc` args (param order), push result. - HostCall(u16, usize), - /// Native dispatch with authored argument labels; binding happens at runtime. - BuiltinCallArgs(usize, usize), - HostCallArgs(u16, usize), - PluginCallArgs(usize, usize), - /// Two-component paths inspect actual receiver presence before static fallback. - PathCallArgs(usize, usize), - RejectCallResolution(usize), - Return, -} - -#[derive(Debug, Clone)] -pub struct FnChunk { - /// Captured directly from the loaded declaration before emission. - pub source_ast: SourceFunction, - pub module_scope: u32, - pub module_path: Vec, - pub source: crate::diagnostics::SourceIdentity, - pub declaration_span: Span, - pub name: String, - pub params: Vec, - pub contract: Option, - pub var_contracts: HashMap, - pub receiver_aliases: bool, - pub defaults: Vec, - pub default_expressions: Vec>, - pub call_layouts: Vec>>, - pub calls: Vec, - /// Source names are reserved before synthetic slots are allocated. - pub source_local_count: usize, - pub expressions: Vec, - pub statements: Vec, - pub statement_roots: Vec, - pub body_start: usize, - pub code: Vec, - /// Parallel to `code`: source location for diagnostics / debug. - pub spans: Vec, - pub constants: Vec, - /// Local slot names (params first). - pub locals: Vec, -} - -#[derive(Debug, Clone)] -pub struct Program { - pub functions: Vec, - pub entry: usize, - /// Applied by run(), not by named or nested calls to the entry function. - pub entry_metadata: Vec<(String, Value)>, - /// Top-level object name → function index (level-1). - pub objects: Vec<(String, usize)>, - /// Parallel to `objects`: base object flat index (`# Child = > Parent`). - pub object_bases: Vec>, - /// (object_fn_idx, method_name) → method fn idx - pub methods: Vec<(usize, String, usize)>, - /// Parallel to `functions`: parent fn index for dynamic `call_fn` lookup. - pub parents: Vec>, - /// Parallel to `functions`: child fn indices. - pub children: Vec>, - /// Dotted path (`计算器.加法`, `inc.加一`) → function index. Entry module exports plus imports. - pub path_index: HashMap, usize>, -} - -impl Program { - pub fn disassemble(&self) -> String { - let mut out = String::new(); - out.push_str("=== marqdo: bytecode ===\n"); - for (fi, fun) in self.functions.iter().enumerate() { - let entry = if fi == self.entry { " " } else { "" }; - out.push_str(&format!( - "fn[{fi}] {} params={:?} locals={:?}{entry}\n", - fun.name, fun.params, fun.locals - )); - for (i, c) in fun.constants.iter().enumerate() { - out.push_str(&format!(" const[{i}] = {c:?}\n")); - } - for (ip, op) in fun.code.iter().enumerate() { - let sp = fun.spans.get(ip).copied().unwrap_or(Span::new(1, 1)); - out.push_str(&format!(" {ip:04} {op:?} @{sp}\n")); - } - } - out.push_str("=== marqdo: end bytecode ===\n"); - out - } -} diff --git a/src/bytecode/names.rs b/src/bytecode/names.rs deleted file mode 100755 index 577efc5..0000000 --- a/src/bytecode/names.rs +++ /dev/null @@ -1,172 +0,0 @@ -//! Source-grounded declaration identities and the flat view of name resolution. -use super::Program; -use crate::sema::resolution::{NameView, Target}; -use std::collections::{HashMap, HashSet}; - -pub(crate) struct FlatView<'a>(pub &'a Program); -impl NameView for FlatView<'_> { - type Function = usize; - type Module = Vec; - fn roots(&self, m: &Self::Module) -> Vec { - self.0 - .functions - .iter() - .enumerate() - .filter(|(i, f)| &f.module_path == m && self.0.parents[*i].is_none()) - .map(|(i, _)| i) - .collect() - } - fn children(&self, f: usize) -> Vec { - self.0.children[f].clone() - } - fn parent(&self, _: &Self::Module, f: usize) -> Option { - self.0.parents[f] - } - fn same(&self, a: usize, b: usize) -> bool { - a == b - } - fn name(&self, f: usize) -> String { - self.0.functions[f].source_ast.name.clone() - } - fn level(&self, f: usize) -> u8 { - self.0.functions[f].source_ast.level - } - fn is_object(&self, f: usize) -> bool { - self.level(f) == 1 - } - fn uses_receiver(&self, f: usize) -> bool { - self.0.functions[f].source_ast.receiver_aliases - } - fn import(&self, m: &Self::Module, name: &str) -> Option { - let owner = self.0.functions.iter().find(|f| &f.module_path == m)?; - if !owner.source_ast.imports.iter().any(|n| n == name) { - return None; - } - let mut path = m.clone(); - path.push(name.into()); - Some(path) - } - fn used_path(&self, m: &Self::Module, name: &str) -> Option> { - self.0 - .functions - .iter() - .find(|f| &f.module_path == m)? - .source_ast - .uses - .iter() - .find(|(n, _)| n == name) - .map(|(_, p)| p.clone()) - } -} -pub(crate) fn resolve( - program: &Program, - caller: usize, - call: &crate::ast::CallExpr, -) -> Target> { - crate::sema::resolution::resolve( - &FlatView(program), - &program.functions[caller].module_path, - caller, - call, - ) -} -pub(crate) fn lookup(program: &Program, caller: usize, name: &str) -> Option { - crate::sema::resolution::lookup( - &FlatView(program), - &program.functions[caller].module_path, - caller, - name, - ) -} -pub(crate) fn verify(program: &Program) -> Result<(), String> { - let objects = program - .functions - .iter() - .enumerate() - .filter(|(id, f)| program.parents[*id].is_none() && f.source_ast.level == 1) - .map(|(id, f)| (f.source_ast.name.clone(), id)) - .collect::>(); - if program.objects != objects { - return Err("object names differ from source declarations".into()); - } - let methods = objects - .iter() - .flat_map(|(_, owner)| { - program.children[*owner].iter().map(|child| { - ( - *owner, - program.functions[*child].source_ast.name.clone(), - *child, - ) - }) - }) - .collect::>(); - if program.methods != methods { - return Err("method names differ from source declarations".into()); - } - let mut identities = HashSet::new(); - let mut scopes = HashMap::new(); - let mut namespaces = HashMap::new(); - for f in &program.functions { - let source = &f.source_ast; - if source.declaration_path.is_empty() - || !identities.insert((f.module_path.clone(), source.declaration_path.clone())) - { - return Err("duplicate or missing source declaration identity".into()); - } - if scopes - .insert(f.module_scope, f.module_path.clone()) - .is_some_and(|p| p != f.module_path) - || namespaces - .insert(f.module_path.clone(), f.module_scope) - .is_some_and(|s| s != f.module_scope) - || (f.module_scope == 0) != f.module_path.is_empty() - { - return Err("source module scope mapping differs".into()); - } - let owner = program - .functions - .iter() - .find(|g| g.module_path == f.module_path) - .unwrap(); - if source.module_root_count != owner.source_ast.module_root_count - || source.imports != owner.source_ast.imports - || source.uses != owner.source_ast.uses - { - return Err("inconsistent source module header".into()); - } - } - for (id, f) in program.functions.iter().enumerate() { - let source = &f.source_ast; - let parent_path = &source.declaration_path[..source.declaration_path.len() - 1]; - match program.parents[id] { - Some(parent) - if program.functions[parent].source_ast.declaration_path == parent_path => - { - () - } - None if parent_path.is_empty() => (), - _ => return Err("flat parent differs from source declaration".into()), - } - if program.children[id].len() != source.child_count { - return Err("source child inventory differs".into()); - } - for (ordinal, child) in program.children[id].iter().enumerate() { - let mut expected = source.declaration_path.clone(); - expected.push(ordinal); - if program.functions[*child].source_ast.declaration_path != expected { - return Err("source child order differs".into()); - } - } - let roots = FlatView(program).roots(&f.module_path); - if roots.len() != source.module_root_count - || roots - .iter() - .enumerate() - .any(|(i, r)| program.functions[*r].source_ast.declaration_path != [i]) - { - return Err("source root inventory/order differs".into()); - } - } - Ok(()) -} diff --git a/src/bytecode/source.rs b/src/bytecode/source.rs deleted file mode 100755 index 716fb8a..0000000 --- a/src/bytecode/source.rs +++ /dev/null @@ -1,366 +0,0 @@ -//! Structural correspondence from a separately captured loaded AST to emission -//! witnesses. Parsing and capture of the source snapshot remain trusted inputs. -use super::{ExpressionRule, FnChunk}; -use crate::ast::{Arg, CallExpr, Expr, Function, Literal, Param, Stmt}; -use serde_json::{json, Value as Json}; - -#[derive(Debug, Clone)] -pub struct SourceFunction { - pub declaration_path: Vec, - pub level: u8, - pub child_count: usize, - pub module_root_count: usize, - pub imports: Vec, - pub uses: Vec<(String, Vec)>, - pub name: String, - pub line: u32, - pub params: Vec, - pub body: Vec, - pub receiver_aliases: bool, - pub has_contract: bool, - pub binding_contracts: Vec, - pub contract: Option, - pub var_contracts: std::collections::HashMap, -} -impl SourceFunction { - pub fn from_function(fun: &Function) -> Self { - let mut bindings = fun.var_contracts.keys().cloned().collect::>(); - bindings.sort(); - Self { - declaration_path: Vec::new(), - level: fun.level, - child_count: fun.children.len(), - module_root_count: 0, - imports: Vec::new(), - uses: Vec::new(), - name: fun.name.clone(), - line: fun.span.line, - params: fun.params.clone(), - body: fun.body.clone(), - receiver_aliases: crate::ast::function_uses_receiver(fun), - has_contract: fun.contract.is_some(), - binding_contracts: bindings, - contract: fun.contract.clone(), - var_contracts: fun.var_contracts.clone(), - } - } - pub fn from_declaration(module: &crate::ast::Module, fun: &Function) -> Self { - fn locate(nodes: &[Function], target: &Function, path: &mut Vec) -> bool { - for (index, node) in nodes.iter().enumerate() { - path.push(index); - if std::ptr::eq(node, target) || locate(&node.children, target, path) { return true; } - path.pop(); - } - false - } - let mut result = Self::from_function(fun); - assert!(locate(&module.functions, fun, &mut result.declaration_path), "source declaration belongs to its module"); - result.module_root_count = module.functions.len(); - result.imports = module.import_modules.keys().cloned().collect(); - result.imports.sort(); - result.uses = module.uses.iter().map(|u| (u.bind.clone(), u.path.clone())).collect(); - result - } - pub fn evidence(&self) -> Result { - Ok( - json!({"declaration_path":self.declaration_path,"level":self.level,"child_count":self.child_count,"module_root_count":self.module_root_count,"imports":self.imports,"uses":self.uses, - "name":self.name,"line":self.line,"params":self.params.iter().map(|p|Ok(json!({"name":p.name,"default":p.default.as_ref().map(expression_tree).transpose()?}))).collect::,String>>()?, - "body":self.body.iter().map(statement_tree).collect::,_>>()?,"receiver_aliases":self.receiver_aliases,"has_contract":self.has_contract,"binding_contracts":self.binding_contracts,"contracts":Self::contract_metadata(self.contract.as_ref(),&self.var_contracts)}), - ) - } - pub fn contract_metadata( - contract: Option<&crate::contract::Contract>, - bindings: &std::collections::HashMap, - ) -> Json { - fn ty(ty: &crate::contract::Ty) -> Json { - match ty { - crate::contract::Ty::Object(name) => json!({"kind":"object","name":name}), - other => json!({"kind":other.name()}), - } - } - fn encode(c: &crate::contract::Contract) -> Json { - json!({"params":c.params.iter().map(|p|json!({"name":p.name,"type":ty(&p.ty),"description":p.desc})).collect::>(), - "returns":c.returns.as_ref().map(|r|json!({"type":ty(&r.ty),"description":r.desc})), - "fields":c.fields.iter().map(|f|json!({"name":f.name,"type":ty(&f.ty),"nullable":f.nullable,"description":f.desc})).collect::>(), - "start_line":c.start_line,"end_line":c.end_line,"quote":c.quote}) - } - let bindings = bindings - .iter() - .map(|(name, c)| (name, encode(c))) - .collect::>(); - json!({"function":contract.map(encode),"bindings":bindings}) - } -} -fn normalized(call: &CallExpr) -> Result { - call.for_evaluation() -} -fn call_shape(call: &CallExpr) -> Json { - json!({"callee":call.callee,"receiver":call.receiver,"path":call.path,"arguments":call.args.iter().map(|a|match a {Arg::Positional(_)=>None,Arg::Named{name,..}=>Some(name)}).collect::>()}) -} -fn arg_expr(arg: &Arg) -> &Expr { - match arg { - Arg::Positional(e) | Arg::Named { value: e, .. } => e, - } -} - -// Deliberately match the loaded AST directly, rather than invoking the emitter's -// ExpressionRule::from_source or StatementRule::from_source recorder. -fn rule(expr: &Expr) -> Json { - use crate::value::Value; - match expr { - Expr::Literal(lit) => { - let value = match lit { - Literal::None => json!({"tag":"none"}), - Literal::Bool(v) => json!({"tag":"bool","value":v}), - Literal::Int(v) => json!({"tag":"int","value":v}), - Literal::Num(v) => json!({"tag":"num","bits":v.to_bits()}), - Literal::Text(v) => json!({"tag":"text","value":v}), - }; - json!({"kind":"literal","value":value}) - } - Expr::Var(name) => json!({"kind":"read","name":name}), - Expr::Unary { op, .. } => json!({"kind":"unary","op":format!("{op:?}")}), - Expr::Binary { op, .. } => json!({"kind":"binary","op":format!("{op:?}")}), - Expr::Call(call) => { - if let Err(message) = normalized(call) { - return json!({"kind":"call_expansion_fault","message":message}); - } - json!({"kind":"call_boundary","names":call.receiver.iter().cloned().chain(call.path.iter().filter_map(|p|p.first().cloned())).collect::>()}) - } - Expr::List(items) => json!({"kind":"list","arity":items.len()}), - Expr::Map(items) => { - json!({"kind":"map","keys":items.iter().map(|(name,_)|name).collect::>()}) - } - Expr::Interp(parts) => { - json!({"kind":"interpolation_boundary","parts":parts.iter().map(super::expression::interpolation_evidence).collect::>()}) - } - Expr::Index { base, label } => { - json!({"kind":"index_boundary","label":super::expression::index_evidence(label),"base_variable":if let Expr::Var(name)=base.as_ref(){Some(name)}else{None}}) - } - Expr::Occluded { payload, .. } => json!({"kind":"occluded","payload":payload.is_some()}), - Expr::Formula(value) => { - json!({"kind":"literal","value":super::expression::value_evidence(&Value::Formula(value.clone()))}) - } - Expr::Code(value) => { - json!({"kind":"literal","value":{"tag":"code","lang":value.lang,"source":value.source}}) - } - } -} -fn children(expr: &Expr) -> Vec<&Expr> { - match expr { - Expr::Unary { expr, .. } => vec![expr], - Expr::Binary { left, right, .. } => vec![left, right], - Expr::List(items) => items.iter().collect(), - Expr::Map(items) => items.iter().map(|(_, e)| e).collect(), - Expr::Index { base, .. } => vec![base], - Expr::Occluded { payload, .. } => payload.iter().map(|e| e.as_ref()).collect(), - _ => Vec::new(), - } -} -fn expression_tree(expr: &Expr) -> Result { - if matches!(expr,Expr::Call(call) if normalized(call).is_err()) { - return Ok(json!({"rule":rule(expr),"children":[],"call":null})); - } - let (children, call) = if let Expr::Call(call) = expr { - let expanded = normalized(call)?; - ( - expanded - .args - .iter() - .map(|a| expression_tree(arg_expr(a))) - .collect::, _>>()?, - Some(call_shape(&expanded)), - ) - } else { - ( - children(expr) - .iter() - .map(|e| expression_tree(e)) - .collect::, _>>()?, - None, - ) - }; - Ok(json!({"rule":rule(expr),"children":children,"call":call})) -} -fn statement_rule(stmt: &Stmt) -> Json { - match stmt { - Stmt::Assign { name, .. } => json!({"kind":"assign","name":name}), - Stmt::Return { .. } => json!({"kind":"return"}), - Stmt::Call { .. } => json!({"kind":"call"}), - Stmt::Expr { .. } => json!({"kind":"expression"}), - Stmt::Branch { arms, .. } => { - json!({"kind":"branch","arms":arms.iter().map(|a|(a.condition.is_some(),a.body.len())).collect::>()}) - } - Stmt::While { body, .. } => json!({"kind":"while","body":body.len()}), - Stmt::ForEach { - item, - collection, - body, - .. - } => json!({"kind":"foreach","item":item,"collection":collection,"body":body.len()}), - } -} -fn statement_children(stmt: &Stmt) -> Vec<&Stmt> { - match stmt { - Stmt::Branch { arms, .. } => arms.iter().flat_map(|a| a.body.iter()).collect(), - Stmt::While { body, .. } | Stmt::ForEach { body, .. } => body.iter().collect(), - _ => Vec::new(), - } -} -fn statement_expressions(stmt: &Stmt) -> Vec { - match stmt { - Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { - vec![value.clone()] - } - Stmt::Call { call, .. } => vec![Expr::Call(call.clone())], - Stmt::Branch { arms, .. } => arms.iter().filter_map(|a| a.condition.clone()).collect(), - Stmt::While { condition, .. } => vec![condition.clone()], - Stmt::ForEach { collection, .. } => vec![Expr::Var(collection.clone())], - } -} -fn statement_tree(stmt: &Stmt) -> Result { - Ok( - json!({"rule":statement_rule(stmt),"expressions":statement_expressions(stmt).iter().map(expression_tree).collect::,_>>()?,"statements":statement_children(stmt).iter().map(|s|statement_tree(s)).collect::,_>>()?}), - ) -} - -struct Walk<'a> { - fun: &'a FnChunk, - expressions: Vec, - statements: Vec, -} -impl Walk<'_> { - fn expression(&mut self, source: &Expr, id: usize) -> Result<(), String> { - let node = self - .fun - .expressions - .get(id) - .ok_or("AST expression reference")?; - if self.expressions[id] { - return Err("AST expression has multiple owners".into()); - } - self.expressions[id] = true; - if node.rule.evidence() != rule(source) { - return Err("loaded AST expression rule differs from witness".into()); - } - if let Expr::Call(call) = source { - let call = match normalized(call) { - Ok(call) => call, - Err(_) => { - if !node.children.is_empty() - || self.fun.calls.iter().any(|c| c.expression == id) - { - return Err("AST preparation fault evaluated actuals".into()); - } - return Ok(()); - } - }; - let record = self - .fun - .calls - .iter() - .find(|c| c.expression == id) - .ok_or("AST call obligation missing")?; - if call_shape(&call) != call_shape(&record.source) - || node.children.len() < call.args.len() - { - return Err("loaded AST call differs from witness".into()); - } - for (arg, child) in call.args.iter().zip(&node.children) { - self.expression(arg_expr(arg), *child)?; - } - for &generated in &node.children[call.args.len()..] { - let expr = self - .fun - .expressions - .get(generated) - .ok_or("generated reload reference")?; - if self.expressions[generated] - || !expr.children.is_empty() - || !matches!(expr.rule, ExpressionRule::Read(_)) - { - return Err("generated reload is shared or not a read".into()); - } - self.expressions[generated] = true; - } - } else { - let expected = children(source); - if expected.len() != node.children.len() { - return Err("loaded AST expression child inventory differs".into()); - } - for (source, child) in expected.iter().zip(&node.children) { - self.expression(source, *child)?; - } - } - Ok(()) - } - fn statement(&mut self, source: &Stmt, id: usize) -> Result<(), String> { - let node = self - .fun - .statements - .get(id) - .ok_or("AST statement reference")?; - if self.statements[id] { - return Err("AST statement has multiple owners".into()); - } - self.statements[id] = true; - if node.rule.evidence() != statement_rule(source) { - return Err("loaded AST statement rule differs from witness".into()); - } - let exprs = statement_expressions(source); - let stmts = statement_children(source); - if node.expressions.len() != exprs.len() || node.statements.len() != stmts.len() { - return Err("loaded AST statement child inventory differs".into()); - } - for (expr, id) in exprs.iter().zip(&node.expressions) { - self.expression(expr, *id)?; - } - for (stmt, id) in stmts.iter().zip(&node.statements) { - self.statement(stmt, *id)?; - } - Ok(()) - } -} -pub fn verify(fun: &FnChunk) -> Result<(), String> { - let source = &fun.source_ast; - if source.contract != fun.contract || source.var_contracts != fun.var_contracts { - return Err("loaded AST contract metadata differs".into()); - } - if source.name != fun.name - || source.line != fun.declaration_span.line - || source.params.iter().map(|p| &p.name).ne(fun.params.iter()) - || source.receiver_aliases != fun.receiver_aliases - || source.has_contract != fun.contract.is_some() - || source.binding_contracts.len() != fun.var_contracts.len() - || source - .binding_contracts - .iter() - .any(|name| !fun.var_contracts.contains_key(name)) - { - return Err("loaded AST function metadata differs".into()); - } - let mut walk = Walk { - fun, - expressions: vec![false; fun.expressions.len()], - statements: vec![false; fun.statements.len()], - }; - if source.params.len() != fun.default_expressions.len() - || source.body.len() != fun.statement_roots.len() - { - return Err("loaded AST function root inventory differs".into()); - } - for (param, id) in source.params.iter().zip(&fun.default_expressions) { - match (¶m.default, id) { - (Some(expr), Some(id)) => walk.expression(expr, *id)?, - (None, None) => {} - _ => return Err("loaded AST default presence differs".into()), - } - } - for (stmt, id) in source.body.iter().zip(&fun.statement_roots) { - walk.statement(stmt, *id)?; - } - if walk.expressions.iter().any(|seen| !seen) || walk.statements.iter().any(|seen| !seen) { - return Err("emission witness has no loaded AST owner".into()); - } - Ok(()) -} diff --git a/src/bytecode/statement.rs b/src/bytecode/statement.rs deleted file mode 100755 index bceab59..0000000 --- a/src/bytecode/statement.rs +++ /dev/null @@ -1,365 +0,0 @@ -//! Source-directed statement and control-flow templates. These checks validate -//! emitted templates; they do not prove the parser or source-witness exporter. -use super::expression::Cursor; -use super::{FnChunk, Op}; -use crate::ast::Stmt; - -#[derive(Debug, Clone)] -pub enum StatementRule { - Assign(String), - Return, - Call, - Expression, - Branch(Vec<(bool, usize)>), - While(usize), - ForEach { - item: String, - collection: String, - body: usize, - }, -} -impl StatementRule { - pub fn from_source(stmt: &Stmt) -> Self { - match stmt { - Stmt::Assign { name, .. } => Self::Assign(name.clone()), - Stmt::Return { .. } => Self::Return, - Stmt::Call { .. } => Self::Call, - Stmt::Expr { .. } => Self::Expression, - Stmt::Branch { arms, .. } => Self::Branch( - arms.iter() - .map(|a| (a.condition.is_some(), a.body.len())) - .collect(), - ), - Stmt::While { body, .. } => Self::While(body.len()), - Stmt::ForEach { - item, - collection, - body, - .. - } => Self::ForEach { - item: item.clone(), - collection: collection.clone(), - body: body.len(), - }, - } - } -} -#[derive(Debug, Clone)] -pub struct StatementEmission { - pub rule: StatementRule, - pub start: usize, - pub end: usize, - pub statements: Vec, - pub expressions: Vec, - pub auxiliary: Vec, -} -fn statement(c: &mut Cursor<'_>, id: usize) -> Result<(), String> { - let child = c.fun.statements.get(id).ok_or("missing statement child")?; - if child.start != c.position { - return Err("source statement order/range differs".into()); - } - c.position = child.end; - Ok(()) -} -pub fn verify(fun: &FnChunk) -> Result<(), String> { - if fun.defaults.len() != fun.params.len() || fun.default_expressions.len() != fun.params.len() { - return Err("default expression inventory".into()); - } - let mut prefix = 0; - for (parameter, default) in fun.default_expressions.iter().enumerate() { - if fun.defaults[parameter] != default.is_some() { - return Err("default source presence differs".into()); - } - if let Some(id) = default { - let expr = fun - .expressions - .get(*id) - .ok_or("default source expression missing")?; - if expr.start != prefix + 1 - || fun.code.get(prefix) != Some(&Op::JumpIfProvided(parameter, expr.end + 2)) - || fun.code.get(expr.end..expr.end + 2) - != Some([Op::SetLocal(parameter), Op::Pop].as_slice()) - { - return Err("source default prologue differs".into()); - } - prefix = expr.end + 2; - } - } - if fun.code.get(prefix) != Some(&Op::FillMissingParameters) { - return Err("missing parameter-fill boundary".into()); - } - prefix += 1; - if fun.contract.is_some() { - if fun.code.get(prefix) != Some(&Op::CheckArguments) { - return Err("missing input contract boundary".into()); - } - prefix += 1; - } - if fun.receiver_aliases { - if fun.code.get(prefix)!=Some(&Op::RestoreReceiver){return Err("missing receiver restoration".into());}prefix+=1; - if fun.contract.is_some(){if fun.code.get(prefix)!=Some(&Op::CheckFrameArguments){return Err("missing frame contract boundary".into());}prefix+=1;} - } - if prefix != fun.body_start { - return Err("function prologue/body boundary differs".into()); - } - let mut protected = fun - .params - .iter() - .cloned() - .collect::>(); - protected.extend(["self".to_string(), "自".to_string()]); - for expression in &fun.expressions { - use super::ExpressionRule; - match &expression.rule { - ExpressionRule::Read(name) => { - protected.insert(name.clone()); - } - ExpressionRule::CallBoundary(names) => protected.extend(names.iter().cloned()), - ExpressionRule::Interpolation(parts) => { - for part in parts { - match part { - crate::ast::InterpPart::Var(name) - | crate::ast::InterpPart::Index { base: name, .. } => { - protected.insert(name.clone()); - } - _ => {} - } - } - } - ExpressionRule::Index { - label, - base_variable, - } => { - if let Some(name) = base_variable { - protected.insert(name.clone()); - } - if let crate::ast::IndexKey::Var(name) = label { - protected.insert(name.clone()); - } - } - _ => {} - } - } - for statement in &fun.statements { - match &statement.rule { - StatementRule::Assign(name) => { - protected.insert(name.clone()); - } - StatementRule::ForEach { - item, collection, .. - } => { - protected.insert(item.clone()); - protected.insert(collection.clone()); - } - _ => {} - } - } - let mut auxiliary_slots = std::collections::HashSet::new(); - let mut parent_counts = vec![0usize; fun.statements.len()]; - for (id, node) in fun.statements.iter().enumerate() { - if node.start > node.end || node.end > fun.code.len() { - return Err("invalid statement interval".into()); - } - for &child in &node.statements { - if child <= id || child >= fun.statements.len() { - return Err("invalid statement child".into()); - } - parent_counts[child] += 1; - let child = &fun.statements[child]; - if child.start < node.start || child.end > node.end { - return Err("statement child outside parent".into()); - } - } - for &expr in &node.expressions { - let expr = fun - .expressions - .get(expr) - .ok_or("invalid statement expression")?; - if expr.start < node.start || expr.end > node.end { - return Err("expression outside statement".into()); - } - } - let mut c = Cursor { - fun, - position: node.start, - end: node.end, - }; - match &node.rule { - StatementRule::Assign(_) - | StatementRule::Return - | StatementRule::Call - | StatementRule::Expression => { - if !node.statements.is_empty() || node.expressions.len() != 1 { - return Err("statement source arity".into()); - } - c.child(node.expressions[0])?; - match &node.rule { - StatementRule::Assign(name) => { - let slot = fun - .locals - .iter() - .position(|n| n == name) - .ok_or("assignment slot")?; - if fun.var_contracts.contains_key(name) { - c.op(Op::CheckBinding(slot))?; - } - c.op(Op::SetLocal(slot))?; - c.op(Op::Pop)?; - } - StatementRule::Return => { - if fun.contract.is_some() { - c.op(Op::CheckReturn)?; - } - c.op(Op::Return)?; - } - StatementRule::Call | StatementRule::Expression => c.op(Op::Pop)?, - _ => unreachable!(), - } - } - StatementRule::While(count) => { - if node.expressions.len() != 1 || node.statements.len() != *count { - return Err("while source arity".into()); - } - c.op(Op::ResetLoop(id))?; - let head = c.position; - c.child(node.expressions[0])?; - c.op(Op::JumpIfFalse(node.end))?; - c.op(Op::CheckLoop(id))?; - for &child in &node.statements { - statement(&mut c, child)?; - } - c.op(Op::Jump(head))?; - } - StatementRule::Branch(arms) => { - if node.expressions.len() != arms.iter().filter(|(condition, _)| *condition).count() - || node.statements.len() != arms.iter().map(|(_, n)| n).sum::() - { - return Err("branch source arity".into()); - } - let (mut expr, mut stmt) = (0, 0); - for (index, (condition, count)) in arms.iter().enumerate() { - let guard = if *condition { - c.child(node.expressions[expr])?; - expr += 1; - let pc = c.position; - c.position += 1; - Some(pc) - } else { - None - }; - for _ in 0..*count { - statement(&mut c, node.statements[stmt])?; - stmt += 1; - } - if index + 1 < arms.len() { - c.op(Op::Jump(node.end))?; - } - if let Some(guard) = guard { - if fun.code.get(guard) != Some(&Op::JumpIfFalse(c.position)) { - return Err("source branch false target differs".into()); - } - } - } - } - StatementRule::ForEach { - item, - collection, - body, - } => { - if node.expressions.len() != 1 - || node.statements.len() != *body - || node.auxiliary.len() != 2 - { - return Err("foreach source arity".into()); - } - let (coll, index) = (node.auxiliary[0], node.auxiliary[1]); - if coll == index || coll >= fun.locals.len() || index >= fun.locals.len() { - return Err("foreach auxiliary slots".into()); - } - for slot in [coll, index] { - if protected.contains(&fun.locals[slot]) || !auxiliary_slots.insert(slot) { - return Err("loop temporary aliases source or another loop".into()); - } - } - // The initial expression must read the authored collection. - if !matches!(&fun.expressions[node.expressions[0]].rule,super::ExpressionRule::Read(name) if name==collection) - { - return Err("foreach source collection differs".into()); - } - c.child(node.expressions[0])?; - c.op(Op::IterItems)?; - c.op(Op::SetLocal(coll))?; - c.op(Op::Pop)?; - c.literal(&crate::value::Value::Int(0))?; - c.op(Op::SetLocal(index))?; - c.op(Op::Pop)?; - let head = c.position; - for op in [ - Op::GetLocal(index), - Op::GetLocal(coll), - Op::Len, - Op::Less, - Op::JumpIfFalse(node.end), - Op::GetLocal(coll), - Op::GetLocal(index), - Op::GetIndex, - ] { - c.op(op)?; - } - let item = fun - .locals - .iter() - .position(|n| n == item) - .ok_or("foreach item slot")?; - c.op(Op::SetLocal(item))?; - c.op(Op::Pop)?; - for &child in &node.statements { - statement(&mut c, child)?; - } - c.op(Op::GetLocal(index))?; - c.literal(&crate::value::Value::Int(1))?; - for op in [Op::Add, Op::SetLocal(index), Op::Pop, Op::Jump(head)] { - c.op(op)?; - } - } - } - if c.position != node.end { - return Err("statement instruction coverage differs".into()); - } - } - let mut cursor = fun.body_start; - for &root in &fun.statement_roots { - let node = fun.statements.get(root).ok_or("statement root missing")?; - if parent_counts[root] != 0 || node.start != cursor { - return Err("source body root order differs".into()); - } - parent_counts[root] += 1; - cursor = node.end; - } - if parent_counts.iter().any(|n| *n != 1) { - return Err("statement forest coverage differs".into()); - } - if fun.code.get(cursor..) != Some([Op::None_, Op::Return].as_slice()) { - return Err("implicit function return differs".into()); - } - Ok(()) -} - -impl StatementRule { - pub fn evidence(&self) -> serde_json::Value { - use serde_json::json; - match self { - Self::Assign(name) => json!({"kind":"assign","name":name}), - Self::Return => json!({"kind":"return"}), - Self::Call => json!({"kind":"call"}), - Self::Expression => json!({"kind":"expression"}), - Self::Branch(arms) => json!({"kind":"branch","arms":arms}), - Self::While(body) => json!({"kind":"while","body":body}), - Self::ForEach { - item, - collection, - body, - } => json!({"kind":"foreach","item":item,"collection":collection,"body":body}), - } - } -} diff --git a/src/bytecode/verify.rs b/src/bytecode/verify.rs deleted file mode 100755 index b6dc8be..0000000 --- a/src/bytecode/verify.rs +++ /dev/null @@ -1,331 +0,0 @@ -//! Checks every emitted instruction and a control-flow stack-height certificate. -//! This is structural validation, not source/bytecode semantic equivalence. -use super::{FnChunk, Op, Program}; -use crate::value::Value; -use std::collections::{HashSet, VecDeque}; - -#[derive(Debug, Clone)] -pub struct StackCertificate { - pub heights: Vec>, -} - -impl Program { - pub fn verify(&self) -> Result, String> { - let n = self.functions.len(); - if self.entry >= n || self.parents.len() != n || self.children.len() != n { - return Err("invalid program function tables".into()); - } - for (i, parent) in self.parents.iter().enumerate() { - if parent.is_some_and(|p| p >= n || p == i) { - return Err("invalid function parent".into()); - } - for &child in &self.children[i] { - if child >= n || self.parents[child] != Some(i) { - return Err("inconsistent function child".into()); - } - } - } - check_forest(&self.parents)?; - for (child, parent) in self.parents.iter().enumerate() { - if let Some(parent) = parent { - if !self.children[*parent].contains(&child) - || self.functions[*parent].module_path != self.functions[child].module_path - { - return Err("inconsistent parent owner".into()); - } - } - } - super::names::verify(self)?; - if self.objects.len() != self.object_bases.len() { - return Err("invalid object tables".into()); - } - for (i, (_, fid)) in self.objects.iter().enumerate() { - if *fid >= n - || self.object_bases[i] - .is_some_and(|base| base >= n || !self.objects.iter().any(|(_, f)| *f == base)) - { - return Err("invalid object reference".into()); - } - } - if self.methods.iter().any(|(owner, _, fid)| { - *owner >= n || *fid >= n || !self.objects.iter().any(|(_, f)| f == owner) - }) || self.path_index.values().any(|id| *id >= n) - { - return Err("invalid method/export reference".into()); - } - let object_ids = self - .objects - .iter() - .enumerate() - .map(|(i, (_, fid))| (*fid, i)) - .collect::>(); - if object_ids.len() != self.objects.len() { - return Err("duplicate object reference".into()); - } - let bases = self - .object_bases - .iter() - .map(|base| base.map(|fid| object_ids[&fid])) - .collect::>(); - check_forest(&bases)?; - if self - .methods - .iter() - .any(|(owner, _, fid)| self.parents[*fid] != Some(*owner)) - { - return Err("inconsistent method owner".into()); - } - self.functions - .iter() - .enumerate() - .map(|(i, f)| { - verify_chunk(self, i, f) - .map_err(|e| format!("bytecode verification in {}: {e}", f.name)) - }) - .collect() - } -} - -fn verify_chunk(program: &Program, _fid: usize, fun: &FnChunk) -> Result { - super::expression::verify(fun)?; - super::statement::verify(fun)?; - super::call::verify(program,fun)?; - super::source::verify(fun)?; - let size = fun.code.len(); - if size == 0 || fun.spans.len() != size { - return Err("invalid code/span table".into()); - } - if fun.defaults.len() != fun.params.len() - || fun.locals.get(..fun.params.len()) != Some(fun.params.as_slice()) - { - return Err("parameters must be a local-slot prefix".into()); - } - if fun.locals.iter().collect::>().len() != fun.locals.len() { - return Err("duplicate local slot name".into()); - } - let local = |i: usize| { - if i < fun.locals.len() { - Ok(()) - } else { - Err("invalid local reference".to_string()) - } - }; - let target = |i: usize| { - if i < size { - Ok(()) - } else { - Err("invalid jump target".to_string()) - } - }; - let function = |i: usize| { - if i < program.functions.len() { - Ok(()) - } else { - Err("invalid call target".to_string()) - } - }; - let text = |i: usize| { - if matches!(fun.constants.get(i), Some(Value::Text(_))) { - Ok(()) - } else { - Err("invalid text constant reference".to_string()) - } - }; - let mut shapes = Vec::with_capacity(size); - for (ip, op) in fun.code.iter().copied().enumerate() { - // pop count, push count, successor PCs. All opcodes are handled. - let next = vec![ip + 1]; - let shape = match op { - Op::Constant(i) => { - if i >= fun.constants.len() { - return Err("invalid constant reference".into()); - } - (0, 1, next) - } - Op::True | Op::False | Op::None_ => (0, 1, next), - Op::GetLocal(i) => { - local(i)?; - (0, 1, next) - } - Op::SetLocal(i) | Op::CheckBinding(i) => { - local(i)?; - (1, 1, next) - } - Op::Pop | Op::Print => (1, 0, next), - Op::Add - | Op::Sub - | Op::Mul - | Op::Div - | Op::Equal - | Op::NotEqual - | Op::Greater - | Op::GreaterEqual - | Op::Less - | Op::Lessequal - | Op::Split - | Op::Join - | Op::GetIndex - | Op::FootnoteGet => (2, 1, next), - Op::ContractFootnoteGet(i) => { - local(i)?; - (2, 1, next) - } - Op::Negate - | Op::Not - | Op::Input - | Op::Len - | Op::Str - | Op::Int - | Op::TypeOf - | Op::Trim - | Op::IterItems - | Op::CallFn => (1, 1, next), - Op::BuildList(n) => (n, 1, next), - Op::BuildMap(n) => (n.checked_mul(2).ok_or("map arity overflow")?, 1, next), - Op::Jump(t) => { - target(t)?; - (0, 0, vec![t]) - } - Op::JumpIfFalse(t) => { - target(t)?; - (1, 0, vec![ip + 1, t]) - } - Op::JumpIfProvided(p, t) => { - target(t)?; - if p >= fun.params.len() { - return Err("invalid presence reference".into()); - } - (0, 0, vec![ip + 1, t]) - } - Op::ResetLoop(id)|Op::CheckLoop(id)=>{ - if !matches!(fun.statements.get(id).map(|s|&s.rule),Some(super::StatementRule::While(_))){return Err("invalid source loop reference".into());} - (0,0,next) - }, - Op::FillMissingParameters | Op::CheckArguments | Op::RestoreReceiver | Op::CheckFrameArguments => (0, 0, next), - Op::CheckReturn => (1, 1, next), - Op::Call(f, n) => { - function(f)?; - (n, 1, next) - } - Op::CallArgs(f, l) => { - function(f)?; - let layout = fun.call_layouts.get(l).ok_or("invalid call layout")?; - (layout.len(), 1, next) - } - Op::BuiltinCallArgs(name,l)|Op::PluginCallArgs(name,l)=>{ - text(name)?; - if matches!(op,Op::BuiltinCallArgs(_,_)) && !matches!(&fun.constants[name],Value::Text(name) if crate::arguments::builtin_signature(name).is_some()){return Err("unknown builtin signature".into());} - let layout=fun.call_layouts.get(l).ok_or("invalid call layout")?;(layout.len(),1,next) - }, - Op::HostCallArgs(id,l)=>{ - if crate::host::HostFn::from_u16(id).is_none(){return Err("unknown host id".into());} - let layout=fun.call_layouts.get(l).ok_or("invalid call layout")?;(layout.len(),1,next) - }, - Op::PathCallArgs(id,l)=>{ - if !matches!(fun.calls.get(id).and_then(|c|c.dispatch.as_ref()),Some(super::CallDispatch::Path{..})){return Err("invalid path call record".into());} - let layout=fun.call_layouts.get(l).ok_or("invalid path call layout")?;(layout.len(),1,next) - }, - Op::RejectCallResolution(index)=>{text(index)?;(0,0,vec![])}, - Op::MethodCall(name, n) => { - text(name)?; - (n.checked_add(1).ok_or("method arity overflow")?, 1, next) - } - Op::MethodCallArgs(name, l) => { - text(name)?; - let layout = fun.call_layouts.get(l).ok_or("invalid method layout")?; - ( - layout.len().checked_add(1).ok_or("method arity overflow")?, - 1, - next, - ) - } - Op::PluginCall(name, n) => { - text(name)?; - if let Value::Text(s) = &fun.constants[name] { - if s.starts_with('@') && n % 2 != 0 { - return Err("odd named plugin arity".into()); - } - } - (n, 1, next) - } - Op::HostCall(id, n) => { - if crate::host::HostFn::from_u16(id).is_none() { - return Err("invalid host reference".into()); - } - (n, 1, next) - } - Op::TagInstance(f) => { - function(f)?; - if !program.objects.iter().any(|(_, id)| *id == f) { - return Err("invalid constructor reference".into()); - } - (1, 1, next) - } - Op::RejectDuplicateArgument(name) | Op::RejectArgumentExpansion(name) => { - text(name)?; - (0, 0, vec![]) - } - Op::Return => (1, 0, vec![]), - }; - shapes.push(shape); - } - let mut heights = vec![None; size]; - heights[0] = Some(0); - let mut queue = VecDeque::from([0]); - while let Some(ip) = queue.pop_front() { - let height = heights[ip].unwrap(); - let (pop, push, edges) = &shapes[ip]; - if height < *pop { - return Err(format!("stack underflow at {ip}")); - } - if matches!(fun.code[ip], Op::Return) && height != 1 { - return Err(format!("return leaks stack values at {ip}")); - } - let after = (height - pop) - .checked_add(*push) - .ok_or("stack height overflow")?; - for &to in edges { - target(to)?; - match heights[to] { - Some(known) if known != after => { - return Err(format!("inconsistent stack join at {to}")) - } - Some(_) => {} - None => { - heights[to] = Some(after); - queue.push_back(to); - } - } - } - } - Ok(StackCertificate { heights }) -} - -fn check_forest(parents: &[Option]) -> Result<(), String> { - let mut colors = vec![0u8; parents.len()]; - for start in 0..parents.len() { - if colors[start] != 0 { - continue; - } - let mut cursor = Some(start); - let mut path = Vec::new(); - while let Some(node) = cursor { - if node >= parents.len() { - return Err("invalid forest reference".into()); - } - if colors[node] == 1 { - return Err("cyclic bytecode declaration graph".into()); - } - if colors[node] == 2 { - break; - } - colors[node] = 1; - path.push(node); - cursor = parents[node]; - } - for node in path { - colors[node] = 2; - } - } - Ok(()) -} diff --git a/src/bytecode/vm.rs b/src/bytecode/vm.rs deleted file mode 100755 index 3c26bda..0000000 --- a/src/bytecode/vm.rs +++ /dev/null @@ -1,951 +0,0 @@ -//! Stack VM for Marqdo bytecode. - -use anyhow::Result; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use crate::builtin::{ - builtin_at, builtin_footnote_get, builtin_int, builtin_iter_items, builtin_join, builtin_len, - builtin_split, builtin_str, builtin_trim, builtin_type, -}; -use crate::bytecode::{FnChunk, Op, Program}; -use crate::debug::emit_trace; -use crate::diagnostics::{Diagnostic, DiagnosticFrame, SourceIdentity, Span}; -use crate::host::{call_host, HostContext, HostFn}; -use crate::input_feed::InputFeed; -use crate::value::Value; -use std::collections::HashMap; - -pub struct Vm { - path: Option, - capture: bool, - pub captured_stdout: String, - input: InputFeed, - trace: bool, - host: HostContext, - current_source: SourceIdentity, - current_scope: Option, - diagnostic_frames: Vec, -} - -struct Frame { - fn_idx: usize, - ip: usize, - slots: Vec>, - provided: Vec, - loop_counts: HashMap, - receiver: Option, - defaults_active: bool, - /// When set, retag matrix-like return to this `_type` (method chaining). - retag_matrix: Option<(String, Option>)>, - has_call_site: bool, - retag_instance: Option, -} - -impl Frame { - fn read(&self, fun: &FnChunk, index: usize) -> Option { - let name=&fun.locals[index]; - let overlay=self.defaults_active && self.receiver.is_some() && (name=="self" || name=="自") && - (index>=fun.params.len() || self.provided.get(index).copied().unwrap_or(false) || self.slots[index].is_none()); - if overlay {self.receiver.clone()} else {self.slots[index].clone()} - } -} - -impl Vm { - pub fn new(path: Option<&Path>) -> Self { - Self { - path: path.map(|p| p.to_path_buf()), - capture: false, - captured_stdout: String::new(), - input: InputFeed::new(false, Vec::new()), - trace: false, - host: HostContext::for_run(path, Default::default(), Vec::new()), - current_source: SourceIdentity { - path: path.map(Path::to_path_buf), - sha256: None, - }, - current_scope: None, - diagnostic_frames: Vec::new(), - } - } - - pub fn with_capture(path: Option<&Path>) -> Self { - Self { - path: path.map(|p| p.to_path_buf()), - capture: true, - captured_stdout: String::new(), - input: InputFeed::new(true, Vec::new()), - trace: false, - host: HostContext::for_capture(path, Default::default()), - current_source: SourceIdentity { - path: path.map(Path::to_path_buf), - sha256: None, - }, - current_scope: None, - diagnostic_frames: Vec::new(), - } - } - - pub fn with_stdin(mut self, lines: Vec) -> Self { - self.input = InputFeed::new(self.capture, lines); - self - } - - pub fn with_trace(mut self, trace: bool) -> Self { - self.trace = trace; - self - } - - pub fn with_host(mut self, host: HostContext) -> Self { - self.host = host; - self - } - - pub fn take_plots(&mut self) -> Vec { - std::mem::take(&mut self.host.plots) - } - - #[cfg(all(test, feature = "exec-host"))] - pub(crate) fn foreign_source_evidence( - &mut self, - ) -> ( - Vec, - Vec, - Vec, - ) { - crate::source_refinement_tests::boundary_evidence(&mut self.host) - } - - #[cfg(test)] - pub(crate) fn diagnostic_scope_state( - &self, - ) -> (SourceIdentity, usize, Vec, Vec, Option) { - ( - self.current_source.clone(), - self.diagnostic_frames.len(), - self.host.call_stack.clone(), - self.host.call_site_lines.clone(), - self.current_scope, - ) - } - - #[cfg(all(test, feature = "exec-host"))] - pub(crate) fn causal_replay_evidence(&mut self) -> serde_json::Value { - crate::causal_replay_tests::evidence(&mut self.host) - } - - #[cfg(all(test, feature = "exec-host"))] - pub(crate) fn application_evidence( - &self, - ) -> ( - Vec, - Vec, - usize, - ) { - ( - self.host.oracle_observations.clone(), - self.host.foreign_protocol_steps.clone(), - self.host.foreign_sessions.len(), - ) - } - - fn emit_line(&mut self, text: &str) { - if self.capture { - self.captured_stdout.push_str(text); - self.captured_stdout.push('\n'); - } else { - println!("{text}"); - } - } - - fn emit_prompt(&mut self, prompt: &str) { - if prompt.is_empty() { - return; - } - if self.capture { - self.captured_stdout.push_str(prompt); - } else { - print!("{prompt}"); - let _ = std::io::stdout().flush(); - } - } - - fn err_at(&self, span: Span, message: impl Into) -> anyhow::Error { - Diagnostic::new(self.current_source.path.as_deref(), span, message) - .with_source(&self.current_source) - .with_frames(&self.diagnostic_frames) - .into() - } - - fn push_source_frame(&mut self, callee: &FnChunk, call_span: Option) { - let mut source = callee.source.clone(); - if source.path.is_none() { - if self.diagnostic_frames.is_empty() { - source.path = self.path.clone(); - } else if self.current_scope == Some(callee.module_scope) { - source.path = self.current_source.path.clone(); - } - } - self.diagnostic_frames.push(DiagnosticFrame { - function: callee.name.clone(), - declaration: source.at(callee.declaration_span), - call_site: call_span.map(|span| self.current_source.at(span)), - }); - } - - pub fn run(&mut self, program: &Program) -> Result { - // Entry execution, like Interpreter::run_function, seeds unbound locals - // with None. Inferred prose parameters do not require a program caller. - let mut seen=std::collections::HashSet::new(); - let metadata=program.entry_metadata.iter().filter(|(name,_)|seen.insert(name.clone())).cloned().collect::>(); - self.execute(program, program.entry, &metadata) - } - - /// Run `fn_idx` with named arguments already bound to local slots. - /// Does not fall back to [`Program::entry`]. - pub fn call_function( - &mut self, - program: &Program, - fn_idx: usize, - args: &[(String, Value)], - ) -> Result { - if fn_idx >= program.functions.len() { - return Err(self.err_at( - Span::new(1, 1), - format!("bytecode: function index {fn_idx} is out of range"), - )); - } - self.execute(program, fn_idx, args) - } - - fn execute( - &mut self, - program: &Program, - fn_idx: usize, - args: &[(String, Value)], - ) -> Result { - program.verify().map_err(|error|self.err_at(Span::new(1,1),error))?; - let previous_source = self.current_source.clone(); - let previous_scope = self.current_scope; - let previous_depth = self.diagnostic_frames.len(); - let previous_calls = self.host.call_stack.clone(); - let previous_sites = self.host.call_site_lines.clone(); - let previous_line = self.host.current_line; - // Scope numbers belong to one compiled program; never carry them into - // a new external invocation, even when it preserves an outer prefix. - self.current_scope = None; - let result = self.execute_inner(program, fn_idx, args); - self.diagnostic_frames.truncate(previous_depth); - self.current_source = previous_source; - self.current_scope = previous_scope; - self.host.call_stack = previous_calls; - self.host.call_site_lines = previous_sites; - self.host.current_line = previous_line; - result - } - - fn execute_inner( - &mut self, - program: &Program, - fn_idx: usize, - args: &[(String, Value)], - ) -> Result { - let mut stack: Vec = Vec::new(); - let mut slots = vec![None; program.functions[fn_idx].locals.len().max(1)]; - for (name, value) in args { - if let Some(i) = program.functions[fn_idx] - .locals - .iter() - .position(|local| local == name) - { - if i < slots.len() { - slots[i] = Some(value.clone()); - } - } - } - let mut frames = vec![Frame { - fn_idx, - loop_counts: HashMap::new(), - receiver: None, defaults_active: true, - ip: 0, - provided: initial_presence(&slots,program.functions[fn_idx].params.len()), - slots, - retag_matrix: None, - has_call_site: false, - retag_instance: None, - }]; - self.push_source_frame(&program.functions[fn_idx], None); - self.host - .push_call_frame(&program.functions[fn_idx].name.clone()); - - let mut source_owner = None; - loop { - let frame = frames.last_mut().unwrap(); - let fun = &program.functions[frame.fn_idx]; - if source_owner != Some(frame.fn_idx) { - self.current_source = self - .diagnostic_frames - .last() - .expect("active source frame") - .declaration - .source - .clone(); - self.current_scope = Some(fun.module_scope); - source_owner = Some(frame.fn_idx); - } - if frame.ip >= fun.code.len() { - let span = fun.spans.last().copied().unwrap_or(Span::new(1, 1)); - return Err(self.err_at(span, format!("bytecode: ip out of range in {}", fun.name))); - } - let ip = frame.ip; - let mut op = fun.code[ip]; - let span = fun.spans.get(ip).copied().unwrap_or(Span::new(1, 1)); - frame.ip += 1; - self.host.current_line = span.line; - - let mut print_returns_none=false; - let mut method_name_override=None; - let mut constructor_tag=None; - if let Op::PathCallArgs(owner,layout)=op { - let call=&fun.calls[owner]; - let Some(super::CallDispatch::Path{receiver,check_receiver,fallback})=&call.dispatch else{unreachable!("verified path dispatch")}; - let value=if *check_receiver {fun.locals.iter().position(|n|n==receiver).and_then(|slot|frame.read(fun,slot))}else{None}; - if let Some(value)=value { - stack.push(value);method_name_override=Some(call.source.callee.clone());op=Op::MethodCallArgs(0,layout); - } else {match fallback { - super::PathFallback::User{target,tag_instance}=>{op=Op::CallArgs(*target,layout);if *tag_instance{constructor_tag=Some(*target);}}, - super::PathFallback::Error{message}=>return Err(self.err_at(span,message)), - }} - } - if let Op::BuiltinCallArgs(name,layout)=op { - let name=fun.constants[name].as_display();let names=&fun.call_layouts[layout]; - let values=take_actuals(&mut stack,names.len()).map_err(|m|self.err_at(span,m))?; - let (params,allow_missing)=crate::arguments::builtin_signature(&name).ok_or_else(||self.err_at(span,"unknown builtin signature"))?; - let parameters=params.iter().map(|p|p.to_string()).collect::>(); - let bound=crate::arguments::bind(¶meters,names,&values,allow_missing).map_err(|m|self.err_at(span,m))?; - for param in params { - stack.push(bound.get(*param).cloned().unwrap_or_else(||Value::Text(String::new()))); - } - op=match name.as_str(){"print"=>{print_returns_none=true;Op::Print},"input"=>Op::Input,"len"=>Op::Len,"str"=>Op::Str,"int"=>Op::Int,"type"=>Op::TypeOf,"trim"=>Op::Trim,"split"=>Op::Split,"join"=>Op::Join,"at"=>Op::GetIndex,"call_fn"=>Op::CallFn,_=>unreachable!()}; - } - - if self.trace { - match op { - Op::Print | Op::Input | Op::Call(_, _) | Op::CallArgs(_, _) | Op::Return => { - let kind = match op { - Op::Print => "print", - Op::Input => "input", - Op::Call(_, _) | Op::CallArgs(_, _) => "call", - Op::Return => "return", - _ => unreachable!(), - }; - let ip_s = ip.to_string(); - emit_trace( - self.current_source.path.as_deref(), - Some(span), - "op", - &[ - ("kind", kind), - ("fn", fun.name.as_str()), - ("ip", ip_s.as_str()), - ], - ); - } - _ => {} - } - } - - match op { - Op::CheckArguments => { - if let Some(contract)=&fun.contract { - let bound=fun.locals.iter().zip(&frame.slots).filter_map(|(name,value)| - value.clone().map(|value|(name.clone(),value))).collect(); - // Internal call errors identify the authored call site, like Tree. - let site=self.diagnostic_frames.last().and_then(|f|f.call_site.as_ref()); - let call_site=site.cloned().unwrap_or_else(||self.current_source.at(span)); - if let Some(diag)=crate::contract::call_arg_diag_in(contract,&fun.name,&bound,&call_site,&fun.source) { - let depth=self.diagnostic_frames.len()-usize::from(site.is_some()); - return Err(diag.with_frames(&self.diagnostic_frames[..depth]).into()); - } - } - } - Op::CheckReturn => { - if let Some(contract)=&fun.contract { - let value=stack.last().cloned().unwrap_or(Value::None); - if let Some(diag)=crate::contract::return_diag(contract,&fun.name,&value,self.current_source.path.as_deref(),span) { - return Err(diag.into()); - } - } - } - Op::CheckBinding(slot) => { - let name=&fun.locals[slot]; - if let Some(contract)=fun.var_contracts.get(name) { - let value=stack.last().cloned().unwrap_or(Value::None); - if let Some(diag)=crate::contract::fields_diag(contract,name,&value,self.current_source.path.as_deref(),span) { - return Err(diag.into()); - } - } - } - Op::RestoreReceiver => { - if let Some(receiver)=&frame.receiver { - for (index,name) in fun.locals.iter().enumerate() { - if name=="self" || name=="自" {frame.slots[index]=Some(receiver.clone());} - } - } - frame.defaults_active=false; - } - Op::CheckFrameArguments => { - if let Some(contract)=&fun.contract { - let bound=fun.locals.iter().zip(&frame.slots).filter_map(|(name,value)|value.clone().map(|value|(name.clone(),value))).collect(); - if let Some(diag)=crate::contract::call_arg_diag(contract,&fun.name,&bound,self.current_source.path.as_deref(),fun.declaration_span){return Err(diag.with_source(&self.current_source).with_frames(&self.diagnostic_frames).into());} - } - } - Op::ResetLoop(id) => {frame.loop_counts.insert(id,0);} - Op::CheckLoop(id) => { - let counter=frame.loop_counts.get_mut(&id).ok_or_else(||self.err_at(span,"uninitialized loop counter"))?; - if *counter>=1_000_000 {return Err(self.err_at(span,"while loop exceeded iteration limit"));} - *counter+=1; - } - Op::FillMissingParameters => { - for index in 0..fun.params.len() { - if frame.slots[index].is_none() { frame.slots[index]=Some(Value::None); } - } - } - Op::Constant(i) => stack.push(fun.constants[i as usize].clone()), - Op::True => stack.push(Value::Bool(true)), - Op::False => stack.push(Value::Bool(false)), - Op::None_ => stack.push(Value::None), - Op::Pop => { - stack.pop(); - } - Op::GetLocal(i) => { - let current=frames.last().unwrap(); - let index=i as usize;let name=&fun.locals[index]; - let value=current.read(fun,index); - let v=value.ok_or_else(||self.err_at(span,format!("undefined variable `{name}`")))?; - stack.push(v); - } - Op::SetLocal(i) => { - let v = stack.last().cloned().unwrap_or(Value::None); - let slot = i as usize; - let fr = frames.last_mut().unwrap(); - if fr.slots.len() <= slot { - fr.slots.resize(slot + 1, None); - } - fr.slots[slot] = Some(v); - } - Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Equal | Op::NotEqual | - Op::Greater | Op::GreaterEqual | Op::Less | Op::Lessequal => { - use crate::ast::BinaryOp; - let operation=match op { - Op::Add=>BinaryOp::Add,Op::Sub=>BinaryOp::Sub,Op::Mul=>BinaryOp::Mul,Op::Div=>BinaryOp::Div, - Op::Equal=>BinaryOp::Eq,Op::NotEqual=>BinaryOp::Ne,Op::Greater=>BinaryOp::Gt, - Op::GreaterEqual=>BinaryOp::Ge,Op::Less=>BinaryOp::Lt,Op::Lessequal=>BinaryOp::Le, - _=>unreachable!(), - }; - let right=pop(&mut stack).map_err(|m|self.err_at(span,m))?; - let left=pop(&mut stack).map_err(|m|self.err_at(span,m))?; - let value=if let Some(value)=crate::linalg_ops::try_matrix_binary(&mut self.host,operation,&left,&right) - .map_err(|m|self.err_at(span,m))? {value} else { - crate::builtin::eval_binary(operation,&left,&right).map_err(|m|self.err_at(span,m))? - }; - stack.push(value); - } - Op::Negate | Op::Not => { - let value=pop(&mut stack).map_err(|m|self.err_at(span,m))?; - let operation=if matches!(op,Op::Negate){crate::ast::UnaryOp::Neg}else{crate::ast::UnaryOp::Not}; - stack.push(crate::builtin::eval_unary(operation,&value).map_err(|m|self.err_at(span,m))?); - } - Op::Jump(t) => { - frames.last_mut().unwrap().ip = t as usize; - } - Op::JumpIfFalse(t) => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - if !v.truthy() { - frames.last_mut().unwrap().ip = t as usize; - } - } - Op::Print => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - self.emit_line(&v.as_display()); - } - Op::Input => { - let prompt = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let text = prompt.as_display(); - let line = if self.capture { - self.emit_prompt(&text); - self.input.read_line() - } else if crate::input_feed::stdin_is_tty() { - self.input - .read_line_with_prompt(&text) - .map(|(line, _)| line) - } else { - self.emit_prompt(&text); - self.input.read_line() - } - .map_err(|e| { - let msg = e.to_string(); - if msg.contains("input needs a line") { - self.err_at(span, msg) - } else { - e - } - })?; - stack.push(Value::Text(line)); - } - Op::BuildList(n) => { - let n = n as usize; - let mut items = Vec::with_capacity(n); - for _ in 0..n { - items.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?); - } - items.reverse(); - stack.push(Value::List(items)); - } - Op::BuildMap(n) => { - let n = n as usize; - let mut pairs = Vec::with_capacity(n); - for _ in 0..n { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let k = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let ks = match k { - Value::Text(s) => s, - _ => { - return Err(self.err_at(span, "map key must be text")); - } - }; - pairs.push((ks, v)); - } - pairs.reverse(); - stack.push(Value::Map(pairs)); - } - Op::Len => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let n = builtin_len(&v).map_err(|m| self.err_at(span, m))?; - stack.push(Value::Int(n)); - } - Op::Str => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(builtin_str(&v)); - } - Op::Int => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let n = builtin_int(&v).map_err(|m| self.err_at(span, m))?; - stack.push(Value::Int(n)); - } - Op::TypeOf => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(builtin_type(&v)); - } - Op::Trim => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(builtin_trim(&v).map_err(|m| self.err_at(span, m))?); - } - Op::Split => { - let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(builtin_split(&value, &sep).map_err(|m| self.err_at(span, m))?); - } - Op::Join => { - let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(builtin_join(&value, &sep).map_err(|m| self.err_at(span, m))?); - } - Op::GetIndex => { - let idx = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let list = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(builtin_at(&list, &idx).map_err(|m| self.err_at(span, m))?); - } - Op::IterItems => { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(builtin_iter_items(&v).map_err(|m| self.err_at(span, m))?); - } - Op::FootnoteGet | Op::ContractFootnoteGet(_) => { - let label = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let base = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let label = match label { - Value::Text(s) => s, - _ => { - return Err(self.err_at(span, "footnote label must be text")); - } - }; - let contract=if let Op::ContractFootnoteGet(slot)=op { - let name=&fun.locals[slot];fun.var_contracts.get(name).map(|c|(name,c)) - } else {None}; - if let Some((name,c))=contract { - if let Some(diag)=crate::contract::index_diag(c,name,&label,&Value::None,self.current_source.path.as_deref(),span) {return Err(diag.into());} - } - let value=builtin_footnote_get(&base,&label).map_err(|m|self.err_at(span,m))?; - if let Some((name,c))=contract { - if let Some(diag)=crate::contract::index_diag(c,name,&label,&value,self.current_source.path.as_deref(),span) {return Err(diag.into());} - } - stack.push(value); - } - Op::HostCallArgs(id, layout) => { - let hf=HostFn::from_u16(id).ok_or_else(||self.err_at(span,"unknown host id"))?; - let names=&fun.call_layouts[layout];let values=take_actuals(&mut stack,names.len()).map_err(|m|self.err_at(span,m))?; - let params=hf.all_params().iter().map(|p|p.to_string()).collect::>(); - let bound=crate::arguments::bind(¶ms,names,&values,true).map_err(|m|self.err_at(span,m))?; - for req in hf.required_params(){if !bound.contains_key(*req){return Err(self.err_at(span,format!("{} requires `{req}`",hf.name())));}} - stack.push(call_host(&mut self.host,hf,&bound).map_err(|m|self.err_at(span,m))?); - } - Op::BuiltinCallArgs(_,_)=>unreachable!("builtin dispatch was prepared above"), - Op::HostCall(id, argc) => { - let hf = HostFn::from_u16(id) - .ok_or_else(|| self.err_at(span, format!("unknown host id {id}")))?; - let argc = argc as usize; - let params = hf.all_params(); - if params.len() != argc { - return Err(self.err_at(span, "host call argc mismatch")); - } - let mut vals = Vec::with_capacity(argc); - for _ in 0..argc { - vals.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?); - } - vals.reverse(); - let mut bound = HashMap::new(); - for (p, v) in params.iter().zip(vals.into_iter()) { - bound.insert((*p).to_string(), v); - } - for req in hf.required_params() { - if !bound.contains_key(*req) { - return Err( - self.err_at(span, format!("{} requires `{req}`", hf.name())) - ); - } - } - let result = - call_host(&mut self.host, hf, &bound).map_err(|m| self.err_at(span, m))?; - stack.push(result); - } - Op::RejectDuplicateArgument(index) => { - let name=fun.constants[index].as_display(); - return Err(self.err_at(span,format!("duplicate named argument `{name}`"))); - } - Op::RejectArgumentExpansion(index) => { - return Err(self.err_at(span,fun.constants[index].as_display())); - } - Op::RejectCallResolution(index)=>return Err(self.err_at(span,fun.constants[index].as_display())), - Op::PathCallArgs(_,_)=>unreachable!("path dispatch was selected above"), - Op::JumpIfProvided(index, target) => { - if frame.provided.get(index as usize).copied().unwrap_or(false) { - frame.ip = target as usize; - } - } - Op::Call(_, _) | Op::CallArgs(_, _) => { - let (fid, argc) = match op { - Op::Call(fid, argc) => (fid, argc as usize), - Op::CallArgs(fid, layout) => (fid, layout), - _ => unreachable!(), - }; - let fid = fid as usize; - let callee = &program.functions[fid]; - let layout = if matches!(op, Op::CallArgs(_, _)) { - fun.call_layouts[argc as usize].clone() - } else { vec![None; argc as usize] }; - let mut values = Vec::new(); - for _ in &layout { values.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?); } - values.reverse(); - let (slots, provided) = bind_call_values(callee, &layout, values).map_err(|m| self.err_at(span, m))?; - let fname = program.functions[fid].name.clone(); - frames.push(Frame { - fn_idx: fid, - loop_counts: HashMap::new(), - receiver: None, defaults_active: true, - ip: 0, - provided, - slots, - retag_matrix: None, - has_call_site: true, - retag_instance: constructor_tag, - }); - self.push_source_frame(callee, Some(span)); - self.host.push_call_frame(&fname); - self.host.push_call_site_line(span.line); - } - Op::TagInstance(idx) => { - let class = program.functions.get(idx).ok_or_else(|| self.err_at(span,"TagInstance needs an object function"))?; - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - stack.push(crate::value::tag_instance(&class.name, &class.module_path, v)); - } - Op::MethodCall(_, _) | Op::MethodCallArgs(_, _) => { - let (name_idx, argc) = match op { - Op::MethodCall(name, argc) => (name, argc as usize), - Op::MethodCallArgs(name, layout) => (name, layout), - _ => unreachable!(), - }; - let layout = if matches!(op, Op::MethodCallArgs(_, _)) { - fun.call_layouts[argc as usize].clone() - } else { vec![None; argc as usize] }; - let argc = layout.len(); - let method_name = if let Some(name)=method_name_override {name} else {match fun.constants.get(name_idx as usize) { - Some(Value::Text(s)) => s.clone(), - _ => { - return Err(self.err_at(span, "MethodCall needs method name constant")); - } - }}; - let recv = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let mut vals = Vec::with_capacity(argc); - for _ in 0..argc { - vals.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?); - } - vals.reverse(); - let type_name = - instance_type_name_bc(&recv).map_err(|m| self.err_at(span, m))?; - let namespace=crate::value::instance_module(&recv).map_err(|m| self.err_at(span,m))?; - let start_oi = if let Some(namespace)=&namespace { - program.objects.iter().position(|(name,id)| name==&type_name && &program.functions[*id].module_path==namespace) - } else { - let local=program.objects.iter().position(|(name,id)| name==&type_name && program.functions[*id].module_scope==fun.module_scope); - if local.is_some() { local } else { - let candidates=program.objects.iter().enumerate().filter(|(_, (name,_))| name==&type_name).map(|(index,_)|index).collect::>(); - if candidates.len()>1 { return Err(self.err_at(span,format!("ambiguous object type `{type_name}`: a module tag is required"))); } - candidates.first().copied() - } - } - .ok_or_else(|| { - self.err_at(span, format!("unknown object type `{type_name}`")) - })?; - let method_fid = resolve_method_fid(program, start_oi, &method_name) - .ok_or_else(|| { - let mut chain = Vec::new(); - let mut oi = Some(start_oi); - let mut seen = std::collections::HashSet::new(); - while let Some(i) = oi { - if !seen.insert(i) { - break; - } - chain.push(program.objects[i].0.as_str()); - oi = program.object_bases.get(i).copied().flatten().and_then( - |base_flat| { - program.objects.iter().position(|(_, f)| *f == base_flat) - }, - ); - } - self.err_at( - span, - format!( - "unknown method `{type_name}.{method_name}` (searched {})", - chain.join(" → ") - ), - ) - })?; - let callee = &program.functions[method_fid]; - let (slots, provided) = bind_call_values(callee, &layout, vals).map_err(|m| self.err_at(span, m))?; - let retag_matrix = if crate::linalg_ops::is_matrix_value(&recv) { - Some((type_name.clone(), namespace)) - } else { - None - }; - let fname = callee.name.clone(); - frames.push(Frame { - fn_idx: method_fid, - loop_counts: HashMap::new(), - receiver: Some(recv.clone()), defaults_active: true, - ip: 0, - provided, - slots, - retag_matrix, - has_call_site: true, - retag_instance: None, - }); - self.push_source_frame(callee, Some(span)); - self.host.push_call_frame(&fname); - self.host.push_call_site_line(span.line); - } - Op::PluginCallArgs(name_idx,layout) => { - let name=fun.constants[name_idx].as_display();let names=&fun.call_layouts[layout]; - let values=take_actuals(&mut stack,names.len()).map_err(|m|self.err_at(span,m))?; - let reg=self.host.plugins.get(&name).cloned().ok_or_else(||self.err_at(span,format!("unknown function `{name}`")))?; - let bound=crate::arguments::bind(®.params,names,&values,false).map_err(|m|self.err_at(span,m))?; - stack.push(crate::host::plugin::call_registered(&mut self.host,&name,&bound).map_err(|m|self.err_at(span,m))?); - } - Op::PluginCall(name_idx, argc) => { - let argc = argc as usize; - let raw_name = match fun.constants.get(name_idx as usize) { - Some(Value::Text(s)) => s.clone(), - _ => { - return Err(self.err_at(span, "PluginCall needs name constant")); - } - }; - let mut bound = HashMap::new(); - if let Some(name) = raw_name.strip_prefix('@') { - // named pairs: (name, value) × N, argc = 2N - if argc % 2 != 0 { - return Err(self.err_at(span, "PluginCall named argc must be even")); - } - let pairs = argc / 2; - for _ in 0..pairs { - let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let k = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let ks = match k { - Value::Text(s) => s, - _ => { - return Err(self.err_at(span, "plugin arg name must be text")); - } - }; - bound.insert(ks, v); - } - let result = - crate::host::plugin::call_registered(&mut self.host, name, &bound) - .map_err(|m| self.err_at(span, m))?; - stack.push(result); - } else { - let mut vals = Vec::with_capacity(argc); - for _ in 0..argc { - vals.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?); - } - vals.reverse(); - let reg = self.host.plugins.get(&raw_name).cloned().ok_or_else(|| { - self.err_at(span, format!("unknown function `{raw_name}`")) - })?; - if reg.params.len() != vals.len() { - return Err(self.err_at( - span, - format!( - "plugin `{raw_name}` expects {} args, got {}", - reg.params.len(), - vals.len() - ), - )); - } - for (p, v) in reg.params.iter().zip(vals.into_iter()) { - bound.insert(p.clone(), v); - } - let result = - crate::host::plugin::call_registered(&mut self.host, &raw_name, &bound) - .map_err(|m| self.err_at(span, m))?; - stack.push(result); - } - } - Op::CallFn => { - let name_v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - let name = match name_v { - Value::Text(s) => s, - _ => return Err(self.err_at(span, "call_fn requires text name")), - }; - let current = frames.last().unwrap().fn_idx; - let fid = resolve_fn_dynamic(program, current, &name) - .map_err(|m| self.err_at(span, m))?; - let callee = &program.functions[fid]; - if !callee.params.is_empty() { - return Err( - self.err_at(span, format!("call_fn: `{name}` must have no parameters")) - ); - } - let slots = vec![None; callee.locals.len().max(1)]; - let fname = callee.name.clone(); - frames.push(Frame { - fn_idx: fid, - loop_counts: HashMap::new(), - receiver: None, defaults_active: true, - ip: 0, - provided: Vec::new(), - slots, - retag_matrix: None, - has_call_site: true, - retag_instance: None, - }); - self.push_source_frame(callee, Some(span)); - self.host.push_call_frame(&fname); - self.host.push_call_site_line(span.line); - } - Op::Return => { - let ret = pop(&mut stack).unwrap_or(Value::None); - let frame = frames.pop(); - let constructor=frame.as_ref().and_then(|f|f.retag_instance); - self.diagnostic_frames.pop(); - self.host.pop_call_frame(); - if frame.as_ref().is_some_and(|f| f.has_call_site) { - self.host.pop_call_site_line(); - } - let ret = match frame.and_then(|f| f.retag_matrix) { - Some((ty,namespace)) => { - let result=crate::linalg_ops::retag_matrix_like(&ty,ret); - if let Some(namespace)=namespace { crate::value::tag_instance(&ty,&namespace,result) } else { result } - }, - None => ret, - }; - let ret=if let Some(id)=constructor {let class=&program.functions[id];crate::value::tag_instance(&class.name,&class.module_path,ret)}else{ret}; - if frames.is_empty() { - return Ok(ret); - } - stack.push(ret); - } - } - if print_returns_none{stack.push(Value::None);} - } - } -} - -fn take_actuals(stack:&mut Vec,count:usize)->Result,String>{ - if stack.len() Option { - let mut oi = Some(start_oi); - let mut seen = std::collections::HashSet::new(); - while let Some(i) = oi { - if !seen.insert(i) { - break; - } - let obj_flat = program.objects[i].1; - if let Some((_, _, fid)) = program - .methods - .iter() - .find(|(o, m, _)| *o == obj_flat && m == method_name) - { - return Some(*fid); - } - oi = program - .object_bases - .get(i) - .copied() - .flatten() - .and_then(|base_flat| program.objects.iter().position(|(_, f)| *f == base_flat)); - } - None -} - -fn pop(stack: &mut Vec) -> Result { - stack - .pop() - .ok_or_else(|| "bytecode: stack underflow".to_string()) -} - -fn instance_type_name_bc(v: &Value) -> Result { - match v { - Value::Map(entries) => entries - .iter() - .find(|(k, _)| k == "_type") - .and_then(|(_, v)| match v { - Value::Text(s) => Some(s.clone()), - _ => None, - }) - .ok_or_else(|| "method receiver needs a map with `_type`".into()), - _ => Err("method receiver must be an object map".into()), - } -} - -fn resolve_fn_dynamic(program: &Program, current: usize, name: &str) -> Result { - super::names::lookup(program,current,name).ok_or_else(||format!("call_fn: unknown function `{name}`")) -} - -/// Bind already evaluated actuals; no expression or foreign effect runs here. -fn bind_call_values(callee: &FnChunk, layout: &[Option], values: Vec) - -> std::result::Result<(Vec>, Vec), String> { - if layout.len()!=values.len(){return Err("argument layout/value count mismatch".into());} - let plan=crate::arguments::plan_with_omissions(&callee.params,layout,&callee.defaults)?; - let mut slots = vec![None; callee.locals.len().max(1)]; - for (name,actual) in plan.assignments { - if let Some(index)=callee.locals.iter().position(|local|local==&name){slots[index]=Some(values[actual].clone());} - } - let provided=initial_presence(&slots,callee.params.len()); - Ok((slots, provided)) -} - -/// Presence is derived once, before defaults, rather than independently rebound. -fn initial_presence(slots:&[Option],parameters:usize)->Vec { - slots.iter().take(parameters).map(Option::is_some).collect() -} diff --git a/src/call.rs b/src/call.rs deleted file mode 100755 index 0799abf..0000000 --- a/src/call.rs +++ /dev/null @@ -1,584 +0,0 @@ -//! `marqdo call`: run one already-bound function in a `.mq.md` file. -//! -//! Location, effects, and execution go through the existing compiler and runtime. -//! The command does not scan headings, and it does not run the program entry when -//! the named function cannot be compiled. - -use std::path::Path; - -use anyhow::Result; - -use crate::ast::Function; -use crate::bytecode::{compile_for_call, Vm}; -use crate::diagnostics::{Diagnostic, Span}; -use crate::host::json::json_to_value; -use crate::host::{HostCaps, HostContext}; -use crate::interp::Interpreter; -use crate::load::load_module; -use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject}; -use crate::value::Value; -use crate::Backend; - -/// Explicit effect grants. Writes imply reads; unrelated effects stay denied. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct CallEffects(u32); - -impl CallEffects { - #[allow(non_upper_case_globals)] - pub const None: Self = Self(0); - #[allow(non_upper_case_globals)] - pub const Plugin: Self = Self((1 << 2) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 11)); - const NAMES: &'static [&'static str] = &[ - "fs.read", - "fs.write", - "plugin.call", - "network.read", - "network.write", - "process.exec", - "output.write", - "time.read", - "random.read", - "environment.read", - "environment.write", - "process.control", - "user.input", - ]; - pub fn parse(s: &str) -> Result { - let mut out = Self::None; - for name in s.split(',').map(str::trim) { - match name { - "none" | "" => {} - "plugin" => out.0 |= Self::Plugin.0, - "read" => out.0 |= 1, - "write" => out.0 |= 3, - _ => { - let index = Self::NAMES.iter().position(|v| *v == name) - .ok_or_else(|| call_diag(None, 0, "call.bad_effects", - format!("unknown effect `{name}`; use none, plugin or comma-separated effect names")))?; - out.0 |= 1 << index; - } - } - } - if out.0 & (1 << 1) != 0 { - out.0 |= 1; - } - if out.0 & (1 << 4) != 0 { - out.0 |= 1 << 3; - } - Ok(out) - } - pub fn as_str(self) -> String { - if self == Self::None { - return "none".into(); - } - if self == Self::Plugin { - return "plugin".into(); - } - Self::NAMES - .iter() - .enumerate() - .filter(|(i, _)| self.0 & (1 << i) != 0) - .map(|(_, name)| *name) - .collect::>() - .join(",") - } - /// File/network/process writes must never be repeated to rebuild a handle. - pub(crate) fn needs_snapshot(self) -> bool { - [ - "fs.write", - "network.write", - "process.exec", - "environment.write", - ] - .iter() - .any(|effect| self.allows(effect)) - } - fn host_caps(self) -> HostCaps { - HostCaps { - fs_write: self.allows("fs.write"), - exec: self.allows("process.exec"), - net: self.allows("network.read") || self.allows("network.write"), - plugin: self.allows("plugin.call"), - } - } - fn allows(self, effect: &str) -> bool { - effect == "pure" - || Self::NAMES - .iter() - .position(|v| *v == effect) - .is_some_and(|i| self.0 & (1 << i) != 0) - } -} - -/// Options for one external call. -#[derive(Debug, Clone, Default)] -pub struct CallOptions { - pub effects: CallEffects, - pub fs_root: Option, - pub session: Option, - pub toget: Option, - /// JSON transport values are literal data, including leading $ and @. - pub literal_args: bool, -} - -/// Call `function` in `path` with named arguments (pure-only, no session). -pub fn call_file( - path: &Path, - function: &str, - args: &[(String, Value)], - backend: Backend, -) -> Result { - call_file_with(path, function, args, backend, CallOptions::default()) -} - -/// Call with effects / session / toget. -pub fn call_file_with( - path: &Path, - function: &str, - args: &[(String, Value)], - backend: Backend, - opts: CallOptions, -) -> Result { - let path = path.canonicalize().map_err(|e| { - call_diag( - None, - 1, - "call.compile", - format!("failed to read {}: {e}", path.display()), - ) - })?; - - let mut session = if opts.session.is_some() || opts.toget.is_some() || (!opts.literal_args && args_need_session(args)) { - let id = opts - .session - .clone() - .unwrap_or_else(crate::call_session::default_session_id); - Some(crate::call_session::load_session(&id)?) - } else { - None - }; - - let resolved = if opts.literal_args { - args.to_vec() - } else if let Some(ref mut sess) = session { - crate::call_session::resolve_args(sess, args, backend)? - } else { - args.to_vec() - }; - - // Record uses original arg texts (with $refs) so replay can re-resolve. - let record_args = args.to_vec(); - - let value = call_file_raw_with_root( - &path, - function, - &resolved, - opts.effects, - backend, - opts.fs_root.as_deref(), - )?; - - if let Some(ref mut sess) = session { - crate::call_session::record_step( - sess, - &path, - function, - &record_args, - opts.effects, - opts.fs_root.as_deref(), - opts.toget.as_deref(), - &value, - )?; - if let Some(step) = sess.steps.last_mut() { - step.literal_args = opts.literal_args; - } - crate::call_session::save_session(sess)?; - } - - Ok(value) -} - -/// Execute without session bookkeeping (used by journal replay). -pub fn call_file_raw( - path: &Path, - function: &str, - args: &[(String, Value)], - effects: CallEffects, - backend: Backend, -) -> Result { - call_file_raw_with_root(path, function, args, effects, backend, None) -} - -pub(crate) fn call_file_raw_with_root( - path: &Path, - function: &str, - args: &[(String, Value)], - effects: CallEffects, - backend: Backend, - fs_root: Option<&Path>, -) -> Result { - let path = if path.is_absolute() { - path.to_path_buf() - } else { - path.canonicalize().map_err(|e| { - call_diag( - None, - 1, - "call.compile", - format!("failed to read {}: {e}", path.display()), - ) - })? - }; - let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?; - let artifact = locate_artifact(&compilation.semantics, &path, function)?; - deny_unsafe(&path, artifact, effects)?; - execute_source_function_with_root( - &path, - artifact.source.line, - &artifact.display_name, - args, - effects.host_caps(), - backend, - true, - fs_root, - ) - .map(|(value, _stdout)| value) -} - -fn args_need_session(args: &[(String, Value)]) -> bool { - args.iter() - .any(|(_, v)| matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@'))) -} - -/// Run the function declared at `line` in `path`. -pub(crate) fn execute_source_function( - path: &Path, - line: u32, - display_name: &str, - args: &[(String, Value)], - caps: HostCaps, - backend: Backend, - strict_args: bool, -) -> Result<(Value, String)> { - execute_source_function_with_root( - path, - line, - display_name, - args, - caps, - backend, - strict_args, - None, - ) -} - -fn execute_source_function_with_root( - path: &Path, - line: u32, - display_name: &str, - args: &[(String, Value)], - caps: HostCaps, - backend: Backend, - strict_args: bool, - fs_root: Option<&Path>, -) -> Result<(Value, String)> { - let module = load_module(path)?; - let source = std::fs::read_to_string(path)?; - let fun = find_function_at_line(&module.functions, line).ok_or_else(|| { - call_diag( - Some(path), - line, - "artifact.unresolved", - format!("无法在 {}:{} 定位函数 {display_name}", path.display(), line), - ) - })?; - let expected = display_name.rsplit('.').next().unwrap_or(display_name); - if fun.name != expected { - return Err(call_diag( - Some(path), - line, - "artifact.unresolved", - format!( - "源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致", - fun.name - ), - )); - } - let mut host = HostContext::for_capture(Some(path), caps); - host.set_entry_source(Some(path), &source); - if let Some(root) = fs_root { - let root = root.canonicalize()?; - if !root.is_dir() { - anyhow::bail!("call.fs_root: root must be a directory"); - } - host.cwd = root.clone(); - host.fs_root = Some(root); - } - let mut interp = Interpreter::with_capture(Some(path), false).with_host(host); - let bound; - let invoke_args: &[(String, Value)] = if strict_args { - bound = interp.bind_external_args(&module, fun, args)?; - &bound - } else { - args - }; - match backend { - Backend::Tree => { - let value = interp.invoke_bound_function(&module, fun, invoke_args)?; - Ok((value, interp.captured_stdout)) - } - Backend::Bytecode => { - let program = compile_for_call(Some(path), &module)?; - let idx = program - .functions - .iter() - .position(|chunk| { - chunk.module_scope == 0 - && chunk.declaration_span == fun.span - && chunk.name == fun.name - && chunk.source.sha256 == module.source.sha256 - }) - .ok_or_else(|| { - call_diag( - Some(path), - line, - "artifact.unresolved", - format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"), - ) - })?; - let mut host = HostContext::for_capture(Some(path), caps); - host.set_entry_source(Some(path), &source); - if let Some(root) = fs_root { - let root = root.canonicalize()?; - host.cwd = root.clone(); - host.fs_root = Some(root); - } - let mut vm = Vm::with_capture(Some(path)).with_host(host); - let value = vm.call_function(&program, idx, invoke_args)?; - Ok((value, vm.captured_stdout)) - } - } -} - -/// Split trailing `toget ` from a clap `args` vector. -pub fn split_toget(tokens: &[String]) -> Result<(Vec, Option)> { - if tokens.len() >= 2 { - let n = tokens.len(); - if tokens[n - 2] == "toget" { - let name = tokens[n - 1].clone(); - if name.contains('=') { - return Err(call_diag( - None, - 0, - "call.bad_toget", - "toget 名字不能含 `=`".into(), - )); - } - return Ok((tokens[..n - 2].to_vec(), Some(name))); - } - } - Ok((tokens.to_vec(), None)) -} - -/// Parse `name=value` tokens. Values are integers, decimals, quoted text, True/False/None, -/// or JSON when the raw value starts with `[` or `{`. -pub fn parse_call_args(tokens: &[String]) -> Result> { - let mut out = Vec::new(); - for token in tokens { - let Some((name, raw)) = token.split_once('=') else { - return Err(call_diag( - None, - 0, - "call.bad_arg", - format!("参数 `{token}` 需要写成 名字=值"), - )); - }; - if name.is_empty() { - return Err(call_diag( - None, - 0, - "call.bad_arg", - format!("参数 `{token}` 缺少名字"), - )); - } - let value = parse_literal(raw).map_err(|message| { - call_diag( - None, - 0, - "call.bad_value", - format!("参数 `{name}`: {message}"), - ) - })?; - out.push((name.to_string(), value)); - } - Ok(out) -} - -/// Decode a JSON object of literal arguments with the standard safe-JSON domain. -/// Unlike command-line $name syntax, JSON strings remain data during replay. -pub fn parse_call_args_json(source: &str) -> Result> { - crate::host::json::decode_arguments(source) - .map_err(|message| call_diag(None, 0, "call.bad_value", message)) -} - -fn locate_artifact<'a>( - project: &'a SemanticProject, - entry: &Path, - query: &str, -) -> Result<&'a SemanticArtifact> { - let in_entry: Vec<&SemanticArtifact> = project - .artifacts - .iter() - .filter(|artifact| same_file(&project.root, &artifact.source.file, entry)) - .collect(); - let exact: Vec<&SemanticArtifact> = in_entry - .iter() - .copied() - .filter(|artifact| { - artifact.display_name == query - || artifact - .symbol_id - .as_ref() - .is_some_and(|id| id.as_str() == query) - || artifact.artifact_id.0 == query - }) - .collect(); - let hits = if !exact.is_empty() { - exact - } else if !query.contains('.') { - in_entry - .iter() - .copied() - .filter(|artifact| { - artifact.kind == "function" - && artifact.display_name.rsplit('.').next() == Some(query) - }) - .collect() - } else { - // Nested sub-tools: `outer.helper` matches display path `main.outer.helper`. - let suffix = format!(".{query}"); - in_entry - .iter() - .copied() - .filter(|artifact| { - artifact.kind == "function" - && (artifact.display_name.ends_with(&suffix) || artifact.display_name == query) - }) - .collect() - }; - match hits.len() { - 1 => Ok(hits[0]), - 0 => Err(call_diag( - Some(entry), - 1, - "artifact.unresolved", - format!("无法唯一绑定 `{query}`"), - )), - _ => Err(call_diag( - Some(entry), - 1, - "artifact.ambiguous", - format!("无法唯一绑定 `{query}`"), - )), - } -} - -fn deny_unsafe(path: &Path, artifact: &SemanticArtifact, effects: CallEffects) -> Result<()> { - if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") { - return Err(call_diag( - Some(path), - artifact.source.line, - "artifact.not_executable", - "只有非实例函数可由 call 直接执行".to_string(), - )); - } - let denied: Vec = artifact - .effects - .values() - .into_iter() - .filter(|e| !effects.allows(e)) - .collect(); - if !denied.is_empty() { - return Err(call_diag( - Some(path), - artifact.source.line, - "artifact.effect_denied", - format!( - "call --effects {} 拒绝效应 {}", - effects.as_str(), - denied.join(", ") - ), - )); - } - Ok(()) -} - -fn same_file(root: &Path, rel: &str, entry: &Path) -> bool { - let abs = root.join(rel); - match (abs.canonicalize(), entry.canonicalize()) { - (Ok(left), Ok(right)) => left == right, - _ => false, - } -} - -fn find_function_at_line(functions: &[Function], line: u32) -> Option<&Function> { - for fun in functions { - if fun.span.line == line { - return Some(fun); - } - if let Some(found) = find_function_at_line(&fun.children, line) { - return Some(found); - } - } - None -} - -fn parse_literal(raw: &str) -> Result { - match raw { - "True" | "true" => return Ok(Value::Bool(true)), - "False" | "false" => return Ok(Value::Bool(false)), - "None" | "none" => return Ok(Value::None), - _ => {} - } - if raw.starts_with('$') || raw.starts_with('@') { - return Ok(Value::Text(raw.to_string())); - } - // Preserve the existing name=value raw-quoted text transport. Escaped, - // structured and multiline data uses the explicit --args-json channel. - if raw.len() >= 2 { - let bytes = raw.as_bytes(); - if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"') - || (bytes[0] == b'\'' && bytes[raw.len() - 1] == b'\'') - { - return Ok(Value::Text(raw[1..raw.len() - 1].to_string())); - } - } - if raw.starts_with('[') || raw.starts_with('{') { - let json: serde_json::Value = - serde_json::from_str(raw).map_err(|e| format!("JSON 解析失败: {e}"))?; - return json_to_value(&json); - } - if let Ok(n) = raw.parse::() { - return Ok(Value::Int(n)); - } - if raw.contains('.') { - if let Ok(n) = raw.parse::() { - return Ok(Value::Num(n)); - } - } - Err(format!( - "无法解析 `{raw}`(整数、小数、引号文本、True/False/None、JSON、`$name`)" - )) -} - -fn preserve_diag(path: &Path, err: anyhow::Error) -> anyhow::Error { - if Diagnostic::find(&err).is_some() { - err - } else { - call_diag(Some(path), 1, "call.compile", format!("{err:#}")) - } -} - -fn call_diag(path: Option<&Path>, line: u32, code: &str, message: String) -> anyhow::Error { - anyhow::Error::new(Diagnostic::new(path, Span::new(line, 1), message).with_code(code)) -} diff --git a/src/call_session.rs b/src/call_session.rs deleted file mode 100755 index 405e144..0000000 --- a/src/call_session.rs +++ /dev/null @@ -1,361 +0,0 @@ -//! Call-session journal for `marqdo call … toget` across process boundaries. -//! -//! Plugin handles do not survive a new OS process; replaying the journal rebuilds them. - -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; - -use anyhow::{bail, Context, Result}; -use serde::{Deserialize, Serialize}; - -use crate::call::{self, CallEffects}; -use crate::host::json::{json_to_value, value_to_json}; -use crate::value::Value; -use crate::Backend; - -const SESSION_DIR: &str = ".marqdo/call-sessions"; - -#[derive(Debug, Clone, Serialize, Deserialize, Default)] -pub struct CallSession { - pub session: String, - #[serde(default)] - pub steps: Vec, - /// JSON-serializable bindings from `toget` (when the result was V_safe JSON). - #[serde(default)] - pub bindings: BTreeMap, - /// Names whose live value must be rebuilt by replaying `steps` (plugin handles / opaque). - #[serde(default)] - pub journal_bindings: BTreeMap, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CallStep { - pub file: String, - pub function: String, - pub args: BTreeMap, - pub effects: String, - #[serde(default, skip_serializing_if = "is_false")] - pub literal_args: bool, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub result: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub fs_root: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub toget: Option, -} - -fn is_false(value: &bool) -> bool { !*value } - -fn sessions_root() -> PathBuf { - if let Ok(p) = std::env::var("MARQDO_CALL_SESSION_DIR") { - return PathBuf::from(p); - } - PathBuf::from(SESSION_DIR) -} - -pub fn session_path(id: &str) -> PathBuf { - let safe: String = id - .chars() - .map(|c| { - if c.is_ascii_alphanumeric() || c == '-' || c == '_' { - c - } else { - '_' - } - }) - .collect(); - sessions_root().join(format!("{safe}.json")) -} - -pub fn load_session(id: &str) -> Result { - let path = session_path(id); - if !path.exists() { - return Ok(CallSession { - session: id.to_string(), - ..Default::default() - }); - } - let text = fs::read_to_string(&path) - .with_context(|| format!("read call session {}", path.display()))?; - let mut s: CallSession = serde_json::from_str(&text) - .with_context(|| format!("parse call session {}", path.display()))?; - s.session = id.to_string(); - Ok(s) -} - -pub fn save_session(session: &CallSession) -> Result<()> { - let path = session_path(&session.session); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - let text = serde_json::to_string_pretty(session)?; - fs::write(&path, text)?; - Ok(()) -} - -/// Resolve `$name` / `@name` argument values from the session (replaying journal as needed). -pub fn resolve_args( - session: &mut CallSession, - args: &[(String, Value)], - backend: Backend, -) -> Result> { - let mut live: BTreeMap = BTreeMap::new(); - for (k, v) in &session.bindings { - live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?); - } - let needs_replay = args.iter().any(|(_, v)| { - matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')) && { - let name = v_text_ref(v); - session.journal_bindings.contains_key(name) - || (!session.bindings.contains_key(name) - && session - .steps - .iter() - .any(|s| s.toget.as_deref() == Some(name))) - } - }); - if needs_replay - || args.iter().any(|(_, v)| { - matches!(v, Value::Text(t) if (t.starts_with('$') || t.starts_with('@')) - && session.journal_bindings.contains_key(&t[1..])) - }) - { - live = replay_live(session, backend)?; - } - let mut out = Vec::with_capacity(args.len()); - for (name, value) in args { - out.push(( - name.clone(), - resolve_one(session, &live, value.clone(), backend)?, - )); - } - Ok(out) -} - -fn v_text_ref(v: &Value) -> &str { - match v { - Value::Text(t) if t.starts_with('$') || t.starts_with('@') => &t[1..], - Value::Text(t) => t.as_str(), - _ => "", - } -} - -fn resolve_one( - session: &CallSession, - live: &BTreeMap, - value: Value, - backend: Backend, -) -> Result { - let Value::Text(t) = &value else { - return Ok(value); - }; - if !(t.starts_with('$') || t.starts_with('@')) { - return Ok(value); - } - let key = &t[1..]; - if let Some(v) = live.get(key) { - return Ok(v.clone()); - } - if let Some(j) = session.bindings.get(key) { - return json_to_value(j).map_err(|e| anyhow::anyhow!(e)); - } - // Last resort: full replay - let live = replay_live(session, backend)?; - live.get(key).cloned().ok_or_else(|| { - anyhow::anyhow!( - "call.session_unbound: `${key}` not in session {}", - session.session - ) - }) -} - -fn replay_live(session: &CallSession, backend: Backend) -> Result> { - let mut live: BTreeMap = BTreeMap::new(); - for (k, v) in &session.bindings { - // Prefer journal rebuild for names also in journal_bindings - if !session.journal_bindings.contains_key(k) { - live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?); - } - } - for step in &session.steps { - let mut args = Vec::new(); - for (k, jv) in &step.args { - let mut val = json_to_value(jv).map_err(|e| anyhow::anyhow!(e))?; - if let Value::Text(t) = &val { - if !step.literal_args && (t.starts_with('$') || t.starts_with('@')) { - let key = &t[1..]; - val = live - .get(key) - .cloned() - .ok_or_else(|| anyhow::anyhow!("call.session_replay: missing `${key}`"))?; - } - } - args.push((k.clone(), val)); - } - let effects = CallEffects::parse(&step.effects)?; - let value = if effects.needs_snapshot() { - let result = step.result.as_ref().ok_or_else(|| anyhow::anyhow!( - "call.session_replay: effectful step has no durable result; refusing to repeat {}", step.effects))?; - json_to_value(result).map_err(|e| anyhow::anyhow!(e))? - } else { - call::call_file_raw_with_root( - Path::new(&step.file), - &step.function, - &args, - effects, - backend, - step.fs_root.as_deref(), - )? - }; - if let Some(name) = &step.toget { - live.insert(name.clone(), value); - } - } - Ok(live) -} - -pub fn record_step( - session: &mut CallSession, - file: &Path, - function: &str, - args: &[(String, Value)], - effects: CallEffects, - fs_root: Option<&Path>, - toget: Option<&str>, - result: &Value, -) -> Result<()> { - let mut arg_map = BTreeMap::new(); - for (k, v) in args { - // Keep $ refs as text so replay can resolve them. - if let Value::Text(t) = v { - if t.starts_with('$') || t.starts_with('@') { - arg_map.insert(k.clone(), serde_json::Value::String(t.clone())); - continue; - } - } - match value_to_json(v) { - Ok(j) => { - arg_map.insert(k.clone(), j); - } - Err(_) => { - bail!("call.session: argument `{k}` is not JSON-serializable for the journal"); - } - } - } - let file_s = file - .canonicalize() - .unwrap_or_else(|_| file.to_path_buf()) - .display() - .to_string(); - let step = CallStep { - file: file_s, - function: function.to_string(), - args: arg_map, - effects: effects.as_str(), - literal_args: false, - result: if is_json_friendly(result) { - value_to_json(result).ok() - } else { - None - }, - fs_root: fs_root.map(|p| p.canonicalize()).transpose()?, - toget: toget.map(|s| s.to_string()), - }; - session.steps.push(step); - if let Some(name) = toget { - match value_to_json(result) { - Ok(j) if is_json_friendly(result) => { - session.bindings.insert(name.to_string(), j); - session.journal_bindings.remove(name); - } - _ => { - session.bindings.remove(name); - session - .journal_bindings - .insert(name.to_string(), session.steps.len() - 1); - } - } - } - Ok(()) -} - -fn is_json_friendly(v: &Value) -> bool { - match v { - Value::None | Value::Bool(_) | Value::Int(_) | Value::Num(_) | Value::Text(_) => true, - Value::List(xs) => xs.iter().all(is_json_friendly), - Value::Map(pairs) => { - // Tagged quantum objects need journal replay across processes. - if pairs.iter().any(|(k, _)| k == "_type") { - return false; - } - pairs.iter().all(|(_, v)| is_json_friendly(v)) - } - Value::Handle(_) | Value::Formula(_) | Value::Code(_) | Value::Secret(_) => false, - } -} - -/// Dump journal steps as a minimal Marqdo script for later `marqdo run`. -pub fn dump_replay_script(session: &CallSession) -> String { - let mut out = - String::from("# main\n\n# Replayed from call-session journal. Review before trusting.\n\n"); - for (i, step) in session.steps.iter().enumerate() { - out.push_str(&format!( - "> print text=\"step {i}: call {} {} effects={}\"\n", - step.file, step.function, step.effects - )); - } - if let Some(last) = session.steps.last().and_then(|s| s.toget.as_ref()) { - out.push_str(&format!("\n> print text=\"last toget was {last}\"\n")); - } - out.push_str("*None*\n"); - out -} - -pub fn default_session_id() -> String { - std::env::var("MARQDO_CALL_SESSION").unwrap_or_else(|_| "default".into()) -} - -#[cfg(test)] -mod write_snapshot_tests { - use super::*; - #[test] - fn replay_uses_durable_write_results_instead_of_repeating_io() { - let dir = std::env::temp_dir().join(format!("mq-write-replay-{}", std::process::id())); - fs::create_dir_all(&dir).unwrap(); - fs::write(dir.join("log.txt"), "once").unwrap(); - for backend in [Backend::Tree, Backend::Bytecode] { - let step = CallStep { - literal_args: false, - file: Path::new(env!("CARGO_MANIFEST_DIR")) - .join("lib/fs.mq.md") - .to_string_lossy() - .into(), - function: "append_text".into(), - args: BTreeMap::from([ - ("path".into(), serde_json::json!("log.txt")), - ("text".into(), serde_json::json!("once")), - ]), - effects: "fs.write".into(), - result: Some(serde_json::Value::Null), - fs_root: Some(dir.clone()), - toget: Some("written".into()), - }; - let mut session = CallSession { - steps: vec![step], - ..Default::default() - }; - assert_eq!( - replay_live(&session, backend).unwrap()["written"], - Value::None - ); - assert_eq!(fs::read_to_string(dir.join("log.txt")).unwrap(), "once"); - session.steps[0].result = None; - assert!(replay_live(&session, backend) - .unwrap_err() - .to_string() - .contains("refusing to repeat")); - } - fs::remove_dir_all(dir).unwrap(); - } -} diff --git a/src/capture.rs b/src/capture.rs deleted file mode 100755 index 5ba01b2..0000000 --- a/src/capture.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Captured program run (for tests and `view`). - -use crate::host::PlotArtifact; -use crate::value::Value; - -/// Silent execution trace for view annotations (not stderr `trace_eval`). -#[derive(Debug, Clone, Default)] -pub struct ViewTrace { - pub branches: Vec, - pub loops: Vec, - /// Per-statement post-state / control events (tree capture). - pub events: Vec, - /// User-function invocations (tree capture). - pub calls: Vec, - /// Foreach / while loop frames with per-iteration item values. - pub loop_frames: Vec, -} - -#[derive(Debug, Clone)] -pub struct BranchHit { - pub line: u32, - pub arm_index: usize, - pub count: u32, - /// Call frame that took this arm (`0` = entry / `# main`). - pub call_id: u32, -} - -#[derive(Debug, Clone)] -pub struct LoopHit { - pub line: u32, - pub iterations: u32, - pub last_item: Option, -} - -#[derive(Debug, Clone)] -pub struct LoopFrame { - pub loop_id: u32, - pub line: u32, - pub item_name: Option, - pub collection: Option, - pub iterations: Vec, -} - -#[derive(Debug, Clone)] -pub struct LoopIter { - /// 0-based iteration index. - pub index: u32, - pub item_value: String, - pub call_id: u32, -} - -#[derive(Debug, Clone)] -pub struct StmtEvent { - pub line: u32, - pub kind: StmtEventKind, - pub name: Option, - pub value_after: Option, - pub arm_index: Option, - /// 0-based iteration index when inside a loop. - pub iter: Option, - pub call_id: u32, - pub loop_id: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum StmtEventKind { - Assign, - Return, - Call, - Branch, - Loop, - BindRef, -} - -impl StmtEventKind { - pub fn as_str(self) -> &'static str { - match self { - StmtEventKind::Assign => "assign", - StmtEventKind::Return => "return", - StmtEventKind::Call => "call", - StmtEventKind::Branch => "branch", - StmtEventKind::Loop => "loop", - StmtEventKind::BindRef => "bind_ref", - } - } -} - -#[derive(Debug, Clone)] -pub struct CallFrame { - pub call_id: u32, - pub fn_name: String, - /// Definition line of the callee. - pub fn_line: u32, - /// Call site line in the executing document (0 for the entry call). - pub call_line: u32, - pub ordinal: u32, - pub args_brief: String, -} - -#[derive(Debug, Clone)] -pub struct RunCapture { - pub stdout: String, - pub value: Value, - pub plots: Vec, - /// Entry-function bindings after a successful tree-backend run (empty for bytecode). - pub bindings: std::collections::HashMap, - /// Branch/loop/stmt hits collected during tree capture (empty for bytecode). - pub view_trace: ViewTrace, -} diff --git a/src/catalog.rs b/src/catalog.rs deleted file mode 100755 index 49e0914..0000000 --- a/src/catalog.rs +++ /dev/null @@ -1,520 +0,0 @@ -//! OKF-compatible catalog generation: `marqdo catalog` / `sync` (O1+O3). - -use std::fs; -use std::path::{Path, PathBuf}; - -// `` slimming: these were byte-identical copies of `knowledge::util`. -use crate::knowledge::util::{extract_fm_field, extract_fm_list, extract_nested_by, yaml_escape}; - -use anyhow::{Context, Result}; - -use crate::lex::{classify_source, LineKind}; -use crate::parse::parse_source; - -pub struct CatalogOptions { - pub path: PathBuf, - pub out_dir: PathBuf, -} - -struct ModuleInfo { - id: String, - resource: String, - title: String, - imports: Vec, - exports: Vec, - /// Optional OKF trust fields copied from source frontmatter. - verified_by: Option, - sources: Vec, -} - -struct ConceptInfo { - /// Relative id e.g. `concepts/tasks/` - id: String, - concept_type: String, - title: String, - status: String, - resource: Option, - skill: Option, - description: Option, - verified_by: Option, - /// Absolute path of source concept page (to copy). - abs: PathBuf, - /// Relative path under out_dir e.g. `concepts/tasks/x.md` - out_rel: String, -} - -pub fn write_catalog(opts: CatalogOptions) -> Result<()> { - let root = if opts.path.is_file() { - opts.path - .parent() - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| PathBuf::from(".")) - } else { - opts.path.clone() - }; - let root = root.canonicalize().unwrap_or(root); - let out_canon = opts.out_dir.canonicalize().unwrap_or(opts.out_dir.clone()); - - let mut files = Vec::new(); - if opts.path.is_file() { - files.push(opts.path.canonicalize().unwrap_or(opts.path.clone())); - } else { - collect_mq_md(&root, &root, &out_canon, &mut files)?; - files.sort(); - } - - fs::create_dir_all(opts.out_dir.join("modules")) - .with_context(|| format!("create {}", opts.out_dir.display()))?; - fs::create_dir_all(opts.out_dir.join("concepts")) - .with_context(|| format!("create concepts under {}", opts.out_dir.display()))?; - - let version = env!("CARGO_PKG_VERSION"); - let mut modules = Vec::new(); - let mut had_err = false; - - for abs in &files { - let rel = abs - .strip_prefix(&root) - .unwrap_or(abs) - .to_string_lossy() - .replace('\\', "/"); - // Skip agent-kb resources (executable skills) from Module table — they appear as concepts. - if rel.contains("/.marqdo/agent-kb/") || rel.starts_with(".marqdo/agent-kb/") { - continue; - } - match inspect_file(abs, &rel) { - Ok(info) => modules.push(info), - Err(e) => { - eprintln!("catalog: skip {rel}: {e:#}"); - had_err = true; - } - } - } - - let mut concepts = Vec::new(); - collect_agent_concepts(&root, &out_canon, &mut concepts)?; - concepts.sort_by(|a, b| a.id.cmp(&b.id)); - - for c in &concepts { - let dest = opts.out_dir.join(&c.out_rel); - if let Some(p) = dest.parent() { - fs::create_dir_all(p)?; - } - let body = fs::read_to_string(&c.abs) - .with_context(|| format!("read concept {}", c.abs.display()))?; - fs::write(&dest, body)?; - } - - let catalog_yaml = render_catalog_yaml(&modules, &concepts, version); - fs::write(opts.out_dir.join("catalog.yaml"), catalog_yaml)?; - - let index_md = render_index_md(&modules, &concepts, version); - fs::write(opts.out_dir.join("index.md"), index_md)?; - - for m in &modules { - let stem = module_stem(&m.resource); - let path = opts.out_dir.join("modules").join(format!("{stem}.md")); - fs::write(&path, render_module_md(m, &modules, version))?; - } - - eprintln!( - "marqdo catalog: {} module(s), {} concept(s) → {}", - modules.len(), - concepts.len(), - opts.out_dir.display() - ); - if had_err { - anyhow::bail!("catalog completed with errors"); - } - Ok(()) -} - -fn module_stem(resource: &str) -> String { - resource - .replace('/', "__") - .replace('\\', "__") - .trim_end_matches(".mq.md") - .to_string() -} - -fn collect_mq_md( - root: &Path, - dir: &Path, - out_canon: &Path, - out: &mut Vec, -) -> Result<()> { - for entry in fs::read_dir(dir)? { - let entry = entry?; - let p = entry.path(); - if p.is_dir() { - if let Ok(canon) = p.canonicalize() { - if canon == *out_canon { - continue; - } - } - collect_mq_md(root, &p, out_canon, out)?; - } else if p - .file_name() - .and_then(|s| s.to_str()) - .map(|s| s.ends_with(".mq.md")) - .unwrap_or(false) - { - out.push(p); - } - } - Ok(()) -} - -/// Find `**/.marqdo/agent-kb/concepts/**/*.md` under scan root. -fn collect_agent_concepts( - root: &Path, - out_canon: &Path, - out: &mut Vec, -) -> Result<()> { - walk_for_concepts(root, root, out_canon, out) -} - -fn walk_for_concepts( - root: &Path, - dir: &Path, - out_canon: &Path, - out: &mut Vec, -) -> Result<()> { - for entry in fs::read_dir(dir)? { - let entry = entry?; - let p = entry.path(); - if p.is_dir() { - if let Ok(canon) = p.canonicalize() { - if canon == *out_canon { - continue; - } - } - walk_for_concepts(root, &p, out_canon, out)?; - continue; - } - let Some(name) = p.file_name().and_then(|s| s.to_str()) else { - continue; - }; - if !name.ends_with(".md") || name.ends_with(".mq.md") { - continue; - } - let rel = p - .strip_prefix(root) - .unwrap_or(&p) - .to_string_lossy() - .replace('\\', "/"); - let marker = "/.marqdo/agent-kb/concepts/"; - let idx = if let Some(i) = rel.find(marker) { - i + marker.len() - } else if let Some(rest) = rel.strip_prefix(".marqdo/agent-kb/concepts/") { - // path relative from agent-kb concepts - let _ = rest; - 0 - } else { - continue; - }; - let under = if idx == 0 { - rel.strip_prefix(".marqdo/agent-kb/concepts/") - .unwrap_or("") - .to_string() - } else { - rel[idx..].to_string() - }; - if under.is_empty() { - continue; - } - let source = fs::read_to_string(&p)?; - let concept_type = - extract_fm_field(&source, "type").unwrap_or_else(|| "Marqdo Concept".into()); - let title = extract_fm_field(&source, "title").unwrap_or_else(|| under.clone()); - let status = extract_fm_field(&source, "status").unwrap_or_else(|| "stable".into()); - let resource = extract_fm_field(&source, "resource"); - let skill = extract_fm_field(&source, "skill"); - let description = extract_fm_field(&source, "description"); - let verified_by = extract_nested_by(&source, "verified"); - let id = format!("concepts/{}", under.trim_end_matches(".md")); - let out_rel = format!("concepts/{under}"); - out.push(ConceptInfo { - id, - concept_type, - title, - status, - resource, - skill, - description, - verified_by, - abs: p, - out_rel, - }); - } - Ok(()) -} - -fn inspect_file(abs: &Path, rel: &str) -> Result { - let source = fs::read_to_string(abs)?; - let imports = extract_frontmatter_imports(&source); - let title = extract_frontmatter_title(&source) - .unwrap_or_else(|| rel.trim_end_matches(".mq.md").to_string()); - let verified_by = extract_nested_by(&source, "verified"); - let sources = extract_fm_list(&source, "sources"); - - let mut exports = Vec::new(); - match parse_source(&source) { - Ok(module) => { - for f in &module.functions { - exports.push(f.name.clone()); - } - } - Err(_) => { - for line in classify_source(&source) { - if line.kind != LineKind::Code { - continue; - } - let t = line.text.trim(); - if let Some(rest) = t.strip_prefix("# ") { - if !rest.starts_with('#') { - exports.push(rest.to_string()); - } - } - } - } - } - - let id = rel.trim_end_matches(".mq.md").to_string(); - Ok(ModuleInfo { - id, - resource: rel.to_string(), - title, - imports, - exports, - verified_by, - sources, - }) -} - -fn extract_frontmatter_imports(source: &str) -> Vec { - crate::parse::scan_frontmatter_imports(source) - .iter() - .map(crate::parse::format_import_display) - .collect() -} - -fn extract_frontmatter_title(source: &str) -> Option { - extract_fm_field(source, "title") -} - - -/// `verified:\n by: foo` → Some("foo") - - - -fn import_path(imp: &str) -> &str { - imp.split(" as ").next().unwrap_or(imp).trim() -} - -fn resolve_import_module<'a>(imp: &str, modules: &'a [ModuleInfo]) -> Option<&'a ModuleInfo> { - let path = import_path(imp); - modules.iter().find(|m| { - m.resource == path - || m.resource.ends_with(path) - || m.resource.ends_with(&format!("/{path}")) - }) -} - -fn render_catalog_yaml(modules: &[ModuleInfo], concepts: &[ConceptInfo], version: &str) -> String { - let mut out = String::new(); - out.push_str("# GENERATED by marqdo — do not edit by hand\n"); - out.push_str("type: Marqdo Catalog\n"); - out.push_str("title: marqdo-project\n"); - out.push_str("generated:\n"); - out.push_str(&format!(" by: marqdo/{version}\n")); - out.push_str("modules:\n"); - for m in modules { - out.push_str(&format!(" - id: {}\n", yaml_escape(&m.id))); - out.push_str(&format!(" resource: {}\n", yaml_escape(&m.resource))); - out.push_str(&format!(" title: {}\n", yaml_escape(&m.title))); - if m.imports.is_empty() { - out.push_str(" imports: []\n"); - } else { - out.push_str(" imports:\n"); - for i in &m.imports { - out.push_str(&format!(" - {}\n", yaml_escape(i))); - } - } - if m.exports.is_empty() { - out.push_str(" exports: []\n"); - } else { - out.push_str(" exports:\n"); - for e in &m.exports { - out.push_str(&format!(" - name: {}\n", yaml_escape(e))); - out.push_str(" kind: fn\n"); - } - } - if let Some(ref v) = m.verified_by { - out.push_str(" verified:\n"); - out.push_str(&format!(" by: {}\n", yaml_escape(v))); - } - if !m.sources.is_empty() { - out.push_str(" sources:\n"); - for s in &m.sources { - out.push_str(&format!(" - {}\n", yaml_escape(s))); - } - } - } - out.push_str("concepts:\n"); - if concepts.is_empty() { - // keep key present for consumers - out.push_str(" []\n"); - } else { - for c in concepts { - out.push_str(&format!(" - id: {}\n", yaml_escape(&c.id))); - out.push_str(&format!(" type: {}\n", yaml_escape(&c.concept_type))); - out.push_str(&format!(" title: {}\n", yaml_escape(&c.title))); - out.push_str(&format!(" status: {}\n", yaml_escape(&c.status))); - out.push_str(&format!(" page: {}\n", yaml_escape(&c.out_rel))); - if let Some(ref r) = c.resource { - out.push_str(&format!(" resource: {}\n", yaml_escape(r))); - } - if let Some(ref s) = c.skill { - out.push_str(&format!(" skill: {}\n", yaml_escape(s))); - } - if let Some(ref d) = c.description { - out.push_str(&format!(" description: {}\n", yaml_escape(d))); - } - if let Some(ref v) = c.verified_by { - out.push_str(" verified:\n"); - out.push_str(&format!(" by: {}\n", yaml_escape(v))); - } - } - } - out -} - -fn render_index_md(modules: &[ModuleInfo], concepts: &[ConceptInfo], version: &str) -> String { - let mut out = String::new(); - out.push_str("---\n"); - out.push_str("type: Marqdo Catalog\n"); - out.push_str("title: marqdo catalog\n"); - out.push_str("generated:\n"); - out.push_str(&format!(" by: marqdo/{version}\n")); - out.push_str("---\n\n"); - out.push_str("# Catalog\n\n"); - out.push_str("> Generated by Marqdo. Do not edit by hand.\n\n"); - out.push_str("## Modules\n\n"); - out.push_str("| Module | Resource | Imports |\n"); - out.push_str("|--------|----------|--------|\n"); - for m in modules { - let stem = module_stem(&m.resource); - let imports_cell = if m.imports.is_empty() { - "—".to_string() - } else { - m.imports - .iter() - .map(|i| { - if let Some(dep) = resolve_import_module(i, modules) { - format!( - "[{}](modules/{}.md)", - dep.title, - module_stem(&dep.resource) - ) - } else { - format!("`{i}`") - } - }) - .collect::>() - .join(", ") - }; - out.push_str(&format!( - "| [{}](modules/{stem}.md) | `{}` | {imports_cell} |\n", - m.title, m.resource - )); - } - - out.push_str("\n## Agent knowledge (OKF concepts)\n\n"); - if concepts.is_empty() { - out.push_str("_No `.marqdo/agent-kb` concepts found under the scan root._\n"); - } else { - out.push_str("| Concept | Type | Status | Page |\n"); - out.push_str("|---------|------|--------|------|\n"); - for c in concepts { - out.push_str(&format!( - "| {} | `{}` | {} | [{}]({}) |\n", - c.title, c.concept_type, c.status, c.id, c.out_rel - )); - } - out.push_str( - "\nThese pages are copied from local `agent-kb` for human browsing alongside modules.\n", - ); - } - out -} - -fn render_module_md(m: &ModuleInfo, modules: &[ModuleInfo], version: &str) -> String { - let mut out = String::new(); - out.push_str("---\n"); - out.push_str("type: Marqdo Module\n"); - out.push_str(&format!("title: {}\n", m.title)); - out.push_str(&format!("resource: {}\n", m.resource)); - if m.imports.is_empty() { - out.push_str("depends: []\n"); - } else { - out.push_str("depends:\n"); - for i in &m.imports { - out.push_str(&format!(" - {i}\n")); - } - } - if m.exports.is_empty() { - out.push_str("exports: []\n"); - } else { - out.push_str("exports:\n"); - for e in &m.exports { - out.push_str(&format!(" - {e}\n")); - } - } - out.push_str("generated:\n"); - out.push_str(&format!(" by: marqdo/{version}\n")); - if let Some(ref v) = m.verified_by { - out.push_str("verified:\n"); - out.push_str(&format!(" by: {v}\n")); - } - if !m.sources.is_empty() { - out.push_str("sources:\n"); - for s in &m.sources { - out.push_str(&format!(" - {s}\n")); - } - } - out.push_str("---\n\n"); - out.push_str(&format!("# {}\n\n", m.title)); - out.push_str(&format!( - "> Auto-generated from [`{}`](../../{}). Do not edit by hand.\n\n", - m.resource, m.resource - )); - out.push_str("## Dependencies\n\n"); - if m.imports.is_empty() { - out.push_str("_None_\n\n"); - } else { - for i in &m.imports { - if let Some(dep) = resolve_import_module(i, modules) { - out.push_str(&format!( - "- [{}]({}.md) (`{}`)\n", - dep.title, - module_stem(&dep.resource), - i - )); - } else { - out.push_str(&format!("- `{i}`\n")); - } - } - out.push('\n'); - } - out.push_str("## Exports\n\n"); - if m.exports.is_empty() { - out.push_str("_None_\n"); - } else { - out.push_str("| Symbol | Kind |\n|--------|------|\n"); - for e in &m.exports { - out.push_str(&format!("| `{e}` | fn |\n")); - } - } - out -} diff --git a/src/causal_replay_tests.rs b/src/causal_replay_tests.rs deleted file mode 100755 index b02bcf0..0000000 --- a/src/causal_replay_tests.rs +++ /dev/null @@ -1,235 +0,0 @@ -use crate::host::{foreign_session as session, json::value_to_json, oracle, HostContext}; -use crate::value::Value; -use serde_json::{json, Value as Json}; -use sha2::{Digest, Sha256}; -use std::path::PathBuf; - -fn root() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) -} -fn directory() -> PathBuf { - let p = std::env::var_os("MARQDO_CAUSAL_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| root().join("target/causal-replay")); - std::fs::create_dir_all(&p).unwrap(); - p -} -fn steps(protocol: &[session::ProtocolStep]) -> Vec { - protocol - .iter() - .map(|p| json!({"session":p.session,"request":p.request,"response":p.response})) - .collect() -} -pub(crate) fn evidence(ctx: &mut HostContext) -> Json { - let journal = value_to_json(&Value::List(ctx.oracle_observations.clone())).unwrap(); - let protocol = steps(&ctx.foreign_protocol_steps); - let divergence = ctx.foreign_replay_divergence.clone(); - let live = ctx.foreign_sessions.len(); - // Inspection is explicitly outside replay and outside the admitted journal. - ctx.foreign_replay_expected = None; - ctx.foreign_replay_divergence = None; - let n = if live == 1 { - session::get(ctx, &Value::Handle("s1".into()), &Value::Text("n".into())) - .ok() - .map(|v| value_to_json(&v).unwrap()) - } else { - None - }; - json!({"journal":journal,"protocol":protocol,"divergence":divergence,"live":live,"n":n}) -} - -#[test] -fn observation_journal_erases_writes_but_a_context_distinguishes_them() { - for lang in ["python", "node"] { - let out = directory(); - let path = out.join(format!("journal-only-{lang}.marker")); - let literal = serde_json::to_string(&path.display().to_string()).unwrap(); - let code = if lang == "python" { - format!("from pathlib import Path\nPath({literal}).write_text(str(ticket))\nNone") - } else { - format!("require('fs').writeFileSync({literal},String(ticket)); null;") - }; - let mut journals = Vec::new(); - let mut histories = Vec::new(); - let mut contents = Vec::new(); - let mut reads = Vec::new(); - let mut first_history = Vec::new(); - for ticket in [7, 8] { - let mut ctx = HostContext::default(); - let id = - session::open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - session::set( - &mut ctx, - &id, - &Value::Text("ticket".into()), - &Value::Int(ticket), - ) - .unwrap(); - let reply = session::eval( - &mut ctx, - &id, - None, - Some(&Value::Text(code.clone())), - None, - None, - ) - .unwrap(); - let observed = oracle::eval_observation(&reply).unwrap(); - oracle::append(&mut ctx, "eval", &observed).unwrap(); - journals.push(Value::List(ctx.oracle_observations.clone())); - histories.push(steps(&ctx.foreign_protocol_steps)); - if ticket == 7 { - first_history = ctx.foreign_protocol_steps.clone(); - } - contents.push(std::fs::read_to_string(&path).unwrap()); - reads.push(session::get(&mut ctx, &id, &Value::Text("ticket".into())).unwrap()); - session::close(&mut ctx, &id).unwrap(); - } - let checked = oracle::replay_check(&journals[0], &journals[1]).unwrap(); - assert_eq!(journals[0], journals[1]); - assert_eq!(contents, ["7", "8"]); - assert_ne!(reads[0], reads[1]); - assert_eq!(value_to_json(&checked).unwrap()["ok"], true); - // Control requests use a different wrapper than eval. A mismatching - // setter must not retire the live kernel or overwrite its prior value. - let mut ctx = HostContext::default(); - let id = - session::open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - session::set( - &mut ctx, - &id, - &Value::Text("ticket".into()), - &Value::Int(99), - ) - .unwrap(); - ctx.foreign_protocol_steps.clear(); - ctx.foreign_replay_expected = Some(first_history.into()); - let error = - session::set(&mut ctx, &id, &Value::Text("ticket".into()), &Value::Int(8)).unwrap_err(); - let dispatched = ctx.foreign_protocol_steps.len(); - let live = ctx.foreign_sessions.len(); - ctx.foreign_replay_expected = None; - ctx.foreign_replay_divergence = None; - let retained = session::get(&mut ctx, &id, &Value::Text("ticket".into())).unwrap(); - assert_eq!(dispatched, 0); - assert_eq!(live, 1); - assert_eq!(retained, Value::Int(99)); - session::close(&mut ctx, &id).unwrap(); - std::fs::write(out.join(format!("journal-only-{lang}.json")),serde_json::to_vec_pretty(&json!({"kind":"journal-erasure","language":lang,"journals":journals.iter().map(|j|value_to_json(j).unwrap()).collect::>(),"histories":histories,"contents":contents,"reads":reads.iter().map(|v|value_to_json(v).unwrap()).collect::>(),"journal_check":value_to_json(&checked).unwrap(),"setter_guard":{"error":error,"dispatched":dispatched,"live":live,"retained":value_to_json(&retained).unwrap()}})).unwrap()).unwrap(); - } -} - -#[test] -fn first_protocol_divergence_stops_host_suffix_and_preserves_current_effects() { - let lengths = std::env::var("MARQDO_CAUSAL_PREFIXES") - .unwrap_or("0,4".into()) - .split(',') - .map(|s| s.parse::().unwrap()) - .collect::>(); - let seeds = std::env::var("MARQDO_CAUSAL_SEEDS") - .unwrap_or("3".into()) - .split(',') - .map(|s| s.parse::().unwrap()) - .collect::>(); - let mut count = 0; - for lang in ["python", "node"] { - for &length in &lengths { - for &seed in &seeds { - for backend in ["tree", "bytecode"] { - for mode in ["reply", "request"] { - let out = directory(); - let id = format!("{lang}-{length}-{seed}-{backend}-{mode}"); - let path = out.join(format!("{id}.mq.md")); - let input = out.join(format!("{id}.input")); - let marker = out.join(format!("{id}.suffix")); - let q = |s: &str| serde_json::to_string(s).unwrap(); - let code = if lang == "python" { - format!( - "from pathlib import Path\nn = 99\nint(Path({}).read_text())", - q(&input.display().to_string()) - ) - } else { - format!( - "n = 99; Number(require('fs').readFileSync({},'utf8'));", - q(&input.display().to_string()) - ) - }; - let prefix=(0..length).map(|i|format!("**p{i} = > foreign.session_eval id=`s` source=\"n += 1; n\"**\n")).collect::(); - let source=format!("---\nmarkup: occlusion\nimport:\n foreign: {}\n fs: {}\n---\n# main\n**s = > foreign.session_open lang={}**\n**> foreign.session_set id=`s` name=\"n\" value={seed}**\n{prefix}**r = > foreign.session_eval id=`s` source={}**\n**> fs.write_text path={} text=\"suffix\"**\n*r*\n",root().join("lib/foreign.mq.md").display(),root().join("lib/fs.mq.md").display(),q(lang),q(&code),q(&marker.display().to_string())); - std::fs::write(&path, &source).unwrap(); - std::fs::write(&input, "1").unwrap(); - let module = crate::load::load_module(&path).unwrap(); - let expected = if backend == "tree" { - let mut tree = - crate::interp::Interpreter::with_capture(Some(&path), false); - tree.run_module(&module).unwrap(); - tree.application_evidence().1 - } else { - let program = - crate::bytecode::compile_module(Some(&path), &module).unwrap(); - let mut vm = crate::bytecode::Vm::with_capture(Some(&path)); - vm.run(&program).unwrap(); - vm.application_evidence().1 - }; - assert_eq!(std::fs::read_to_string(&marker).unwrap(), "suffix"); - std::fs::remove_file(&marker).unwrap(); - let actual_source = if mode == "request" { - source.replace(&q(&code), &q(&code.replace("n = 99", "n = 77"))) - } else { - std::fs::write(&input, "2").unwrap(); - source.clone() - }; - std::fs::write(&path, &actual_source).unwrap(); - let actual = crate::load::load_module(&path).unwrap(); - let mut host = HostContext::for_capture(Some(&path), Default::default()); - host.foreign_replay_expected = Some(expected.clone().into()); - let (error, observed) = if backend == "tree" { - let mut tree = - crate::interp::Interpreter::with_capture(Some(&path), false) - .with_host(host); - let error = tree.run_module(&actual).err().map(|e| e.to_string()); - (error, tree.causal_replay_evidence()) - } else { - let program = - crate::bytecode::compile_module(Some(&path), &actual).unwrap(); - let mut vm = - crate::bytecode::Vm::with_capture(Some(&path)).with_host(host); - let error = vm.run(&program).err().map(|e| e.to_string()); - (error, vm.causal_replay_evidence()) - }; - let record = json!({"kind":"causal-stop","id":id,"language":lang,"prefix":length,"seed":seed,"backend":backend,"mode":mode,"expected":steps(&expected),"observed":observed,"error":error,"suffix_exists":marker.exists(),"source":actual_source,"source_sha256":format!("{:x}",Sha256::digest(actual_source.as_bytes()))}); - std::fs::write( - out.join(format!("{id}.json")), - serde_json::to_vec_pretty(&record).unwrap(), - ) - .unwrap(); - assert!( - error.is_some(), - "{id}: replay divergence returned a soft result: {record}" - ); - assert!(!marker.exists(), "{id}: host suffix ran after divergence"); - assert_eq!( - observed["n"], - if mode == "reply" { - json!(99) - } else { - json!(seed + length as i64) - } - ); - assert_eq!(observed["live"], 1); - assert_eq!(observed["journal"].as_array().unwrap().len(), length); - assert_eq!( - observed["protocol"].as_array().unwrap().len(), - length + if mode == "reply" { 2 } else { 1 } - ); - count += 1; - } - } - } - } - } - println!( - "CAUSAL_METRIC:{}", - json!({"cases":count,"document_runs":count*2}) - ); -} diff --git a/src/check.rs b/src/check.rs deleted file mode 100755 index f36aa8b..0000000 --- a/src/check.rs +++ /dev/null @@ -1,240 +0,0 @@ -//! `marqdo check` —— 静态契约互查(T2.3 + T2.5)。 -//! -//! 只读静态检查,不执行程序。三类必产诊断: -//! -//! 1. **防漂移(T2.5)**:契约行 vs 升参推断形参**双向互查**——契约表一经出现 -//! 就是该单元形参的完整声明:契约多出的名字(错行)与未被覆盖的推断形参 -//! (新升参)都是 `contract.param_drift`。 -//! 2. **未知类型名**:`Ty::Object` 必须是已知对象类型(防 `nubmer` 拼错, -//! 附最近建议)⇒ `contract.unknown_type`。 -//! 3. **错位契约**:契约形状(含 `类型` 列)的未绑定表出现在不允许位置 -//! (提取阶段原样留在 body 里的就是)⇒ `contract.misplaced`。 -//! -//! 任一 Error ⇒ 进程以非零码退出。诊断全部带 `doc_anchor` 锚点(T2.4)。 - -use std::path::Path; - -use anyhow::Result; - -use crate::ast::{Expr, Function, Module, Stmt}; -use crate::contract::{self, Contract, Ty}; -use crate::diagnostics::{Diagnostic, Severity, Span}; -use crate::load; - -/// 读取文件 + 装载(含 import)后做全量契约互查。 -pub fn check_path(path: &Path) -> Result> { - check_path_opts(path, false, false) -} - -/// `implicit_labels` enables the fuzzy M5 check (prose above `>` calls). -/// -/// It is **off by default**: describing a call in prose is freeform, so the -/// check is inherently ambiguous and would be noisy — opt in when you want it. -/// -/// `proof` enables the theorem-table check (`check --proof`, ADR 0010, -/// 默认关):表形、名字、片段、遮蔽。 -pub fn check_path_opts(path: &Path, implicit_labels: bool, proof: bool) -> Result> { - let module = load::load_module(path)?; - let mut out = check_module(&module, Some(path)); - if implicit_labels { - if let Ok(source) = std::fs::read_to_string(path) { - out.extend(crate::label::check_implicit(&module, &source, Some(path))); - } - } - if proof { - out.extend(crate::prove::proof_check::check_proofs(&module, Some(path))); - } - Ok(out) -} - -/// 递归检查模块全部函数(含子函数)的契约。 -pub fn check_module(module: &Module, path: Option<&Path>) -> Vec { - let known = known_type_names(module); - let mut out = Vec::new(); - walk(module, &module.functions, path, &known, &mut out); - // `` M2.5: occlusion labels (`label.missing` / `label.empty_payload`). - out.extend(crate::label::check(module, path)); - out -} - -/// 已知对象类型名:本文件 `#` 对象 + import/use 绑定 + 导入库的 `#` 对象。 -fn known_type_names(module: &Module) -> Vec { - let mut names = Vec::new(); - for f in &module.functions { - if f.is_object() { - names.push(f.name.clone()); - } - } - for i in &module.imports { - names.push(i.bind.clone()); - } - for u in &module.uses { - names.push(u.bind.clone()); - } - for lib in module.import_modules.values() { - for f in &lib.functions { - if f.is_object() { - names.push(f.name.clone()); - } - } - } - names -} - -fn walk( - module: &Module, - funs: &[Function], - path: Option<&Path>, - known: &[String], - out: &mut Vec, -) { - for fun in funs { - check_one(module, fun, path, known, out); - walk(module, &fun.children, path, known, out); - } -} - -fn check_one( - module: &Module, - fun: &Function, - path: Option<&Path>, - known: &[String], - out: &mut Vec, -) { - if let Some(c) = &fun.contract { - for p in &c.params { - type_name_check(&p.ty, c, &fun.name, path, fun.span, known, out); - } - if let Some(r) = &c.returns { - type_name_check(&r.ty, c, &fun.name, path, fun.span, known, out); - } - for f in &c.fields { - type_name_check(&f.ty, c, &fun.name, path, fun.span, known, out); - } - // ---- T2.5 防漂移:契约行 vs 升参推断形参(双向) ---- - let inferred: Vec = fun.params.iter().map(|p| p.name.clone()).collect(); - for p in &c.params { - if !inferred.contains(&p.name) { - out.push(c.diagnostic( - "contract.param_drift", - &fun.name, - format!( - "契约参数 `{}` 不是 `{}` 的形参(当前形参:[{}])", - p.name, - fun.name, - inferred.join(", ") - ), - "删除契约表该行,或让该名在函数体被读取(升参)/ 用 `+` 行显式声明".to_string(), - path, - fun.span, - )); - } - } - for name in &inferred { - if !c.params.iter().any(|p| p.name == *name) { - let d = c - .diagnostic( - "contract.param_drift", - &fun.name, - format!( - "形参 `{name}` 未被契约覆盖(可能是新推断的升参;契约表一经出现即为完整声明)" - ), - "在契约表补一行 `| {name} | 类型 | 说明 |`,或删掉契约表回到纯动态".to_string(), - path, - fun.span, - ) - .with_severity(Severity::Warning); - out.push(d); - } - } - } - for (name, c) in &fun.var_contracts { - for f in &c.fields { - type_name_check(&f.ty, c, name, path, fun.span, known, out); - } - } - // ---- 错位契约:契约形状的未绑定表被提取器原样留在 body ---- - for stmt in &fun.body { - let Stmt::Expr { value: Expr::Map(pairs), span } = stmt else { - continue; - }; - if let Some(Ok(c)) = contract::parse_contract_table(pairs, span.line, span.line, Vec::new()) - { - out.push(c.diagnostic( - "contract.misplaced", - &fun.name, - "契约表位置不允许(形参/返回表只能在函数体首个可执行行之前;字段表只能紧邻绑定或对象体首成员之前),已按普通表处理".to_string(), - "移动契约表到允许位置,或改表头避开契约形状(含 `类型` 列)".to_string(), - path, - *span, - )); - } - } - let _ = module; -} - -/// 对象类型名必须已知;拼错(`nubmer`)⇒ `contract.unknown_type` + 最近建议。 -fn type_name_check( - ty: &Ty, - c: &Contract, - unit: &str, - path: Option<&Path>, - span: Span, - known: &[String], - out: &mut Vec, -) { - let Ty::Object(name) = ty else { return }; - if known.iter().any(|k| k == name) { - return; - } - let suggestion = match suggest(name, known) { - Some(near) => format!("是不是想写 `{near}`?已知类型:{}", known.join(" / ")), - None => format!("已知类型:{}", known.join(" / ")), - }; - out.push(c.diagnostic( - "contract.unknown_type", - unit, - format!("未知类型名 `{name}`(不是原语,也没有对应的 `#` 对象)"), - suggestion, - path, - span, - )); -} - -const PRIMITIVES: &[&str] = &["text", "number", "bool", "list", "map", "any"]; - -fn edit_distance(a: &str, b: &str) -> usize { - let a: Vec = a.chars().collect(); - let b: Vec = b.chars().collect(); - let mut prev: Vec = (0..=b.len()).collect(); - let mut cur = vec![0usize; b.len() + 1]; - for i in 1..=a.len() { - cur[0] = i; - for j in 1..=b.len() { - let cost = usize::from(a[i - 1] != b[j - 1]); - cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost); - } - std::mem::swap(&mut prev, &mut cur); - } - prev[b.len()] -} - -/// 供 `prove::proof_check` 复用的最近名建议(编辑距离 ≤ 2)。 -pub fn suggest_closest(name: &str, known: &[String]) -> Option { - suggest(name, known) -} - -fn suggest(name: &str, known: &[String]) -> Option { - let lower = name.to_ascii_lowercase(); - let mut best: Option<(usize, String)> = None; - let candidates = PRIMITIVES.iter().map(|s| s.to_string()).chain( - known.iter().cloned(), - ); - for cand in candidates { - let d = edit_distance(&lower, &cand.to_ascii_lowercase()); - if d <= 2 && best.as_ref().map(|(bd, _)| d < *bd).unwrap_or(true) { - best = Some((d, cand)); - } - } - best.map(|(_, c)| c) -} diff --git a/src/contract.rs b/src/contract.rs deleted file mode 100755 index b09bfd0..0000000 --- a/src/contract.rs +++ /dev/null @@ -1,849 +0,0 @@ -//! Progressive contracts (渐进式契约 / 标注类型) —— schema 长在表格/说明段落里。 -//! -//! 动态默认、按需校验、零契约文件零回归;TS/TS 的全程序静态类型被明确**拒绝**。 -//! 契约唯一来源是**未绑定文档表**(绑定表是数据,永不视为契约): -//! -//! | 形状(含 `类型` 列) | 允许位置 | 附着对象 | -//! |----------------------|----------|----------| -//! | `参数`/`返回` 表 | 函数体首个可执行行之前 | 函数(形参/返回契约) | -//! | `字段` 表 | 紧邻 `` `名` = `` 绑定之前 | 变量(集合契约) | -//! | `字段` 表 | 对象(`#`)体首成员之前 | 对象类型(字段契约) | -//! -//! 提取在**升参推断之前**执行(见 `parse`),契约表的单元不会污染推断。 -//! 校验只发生在四个运行时边界(调用实参 / 字段访问 / 表绑定 / 返回)与 -//! `marqdo check` 静态互查;契约表本身永不执行、永不进入值空间。 -//! 锚点诊断见 [`Contract::anchor`] / [`Contract::quote_text`](T2.4)。 - -use std::collections::HashMap; -use std::path::Path; - -use anyhow::Result; - -use crate::ast::Expr; -use crate::diagnostics::{ContractRef, Diagnostic, Severity, Span}; -use crate::value::Value; - -/// 契约类型词汇(`doc/design/core-surface.md` 的文档层扩展,不进语言核心)。 -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Ty { - /// 任意值(类型列留空)。 - Any, - Text, - /// `int` / `num`(`Value::Int` / `Value::Num` / 符号公式)。 - Number, - Bool, - List, - Map, - /// 对象类型名(`#` 对象;`check` 阶段校验存在性,防 `nubmer` 拼错)。 - Object(String), -} - -impl Ty { - /// 解析类型列文本(大小写不敏感;未知名 → `Object(name)`,由 check 验证)。 - pub fn parse(raw: &str) -> Ty { - let name = raw.trim().trim_matches('`').to_ascii_lowercase(); - match name.as_str() { - "" | "any" | "任意" => Ty::Any, - "text" | "str" | "string" | "文本" | "字串" | "字符串" => Ty::Text, - "number" | "int" | "float" | "num" | "numeric" | "数字" | "数值" => Ty::Number, - "bool" | "boolean" | "布尔" => Ty::Bool, - "list" | "列表" | "表" => Ty::List, - "map" | "dict" | "object" | "字典" | "映射" => Ty::Map, - _ => Ty::Object(raw.trim().trim_matches('`').to_string()), - } - } - - /// 契约类型名(诊断消息显示用;与 `type` 内置的运行时名对照)。 - pub fn name(&self) -> String { - match self { - Ty::Any => "any".into(), - Ty::Text => "text".into(), - Ty::Number => "number".into(), - Ty::Bool => "bool".into(), - Ty::List => "list".into(), - Ty::Map => "map".into(), - Ty::Object(n) => n.clone(), - } - } - - /// 值是否满足契约类型(对象类型看 `_type` 实例标签)。 - pub fn matches_value(&self, v: &Value) -> bool { - match self { - Ty::Any => true, - Ty::Text => matches!(v, Value::Text(_)), - // 符号公式($$…$$)是数值表达式,按 number 收。 - Ty::Number => matches!(v, Value::Int(_) | Value::Num(_) | Value::Formula(_)), - Ty::Bool => matches!(v, Value::Bool(_)), - Ty::List => matches!(v, Value::List(_)), - Ty::Map => matches!(v, Value::Map(_)), - Ty::Object(n) => instance_type_name(v).as_deref() == Some(n.as_str()), - } - } - - /// 列语义(几何即类型):标量按本类型,或**元素全匹配**的列向量。 - pub fn matches_column(&self, v: &Value) -> bool { - if self.matches_value(v) { - return true; - } - match v { - Value::List(items) => items.iter().all(|it| self.matches_value(it)), - Value::Map(pairs) => pairs - .iter() - .all(|(_, it)| match it { - // map-of-lists 的列向量 - Value::List(xs) => xs.iter().all(|x| self.matches_value(x)), - scalar => self.matches_value(scalar), - }) - && !pairs.is_empty(), - _ => false, - } - } -} - -/// 运行时 `type` 名(诊断消息里的「实际」侧)。 -pub fn type_of(v: &Value) -> &'static str { - match v { - Value::None => "none", - Value::Bool(_) => "bool", - Value::Int(_) => "int", - Value::Num(_) => "num", - Value::Text(_) => "text", - Value::Secret(_) => "secret", - Value::Handle(_) => "handle", - Value::List(_) => "list", - Value::Map(_) => "map", - Value::Formula(_) => "formula", - Value::Code(_) => "code", - } -} - -fn instance_type_name(v: &Value) -> Option { - let Value::Map(pairs) = v else { return None }; - pairs - .iter() - .find(|(k, _)| k == "_type") - .and_then(|(_, v)| match v { - Value::Text(t) => Some(t.clone()), - _ => None, - }) -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ParamContract { - pub name: String, - pub ty: Ty, - pub desc: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ReturnContract { - pub ty: Ty, - pub desc: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct FieldContract { - pub name: String, - pub ty: Ty, - pub nullable: bool, - pub desc: String, -} - -/// 一份契约(一个契约表块;同单元多表由 [`merge_contract`] 合并)。 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Contract { - pub params: Vec, - pub returns: Option, - pub fields: Vec, - pub start_line: u32, - pub end_line: u32, - /// 契约表原文行(诊断 `doc_quote`)。 - pub quote: Vec, -} - -impl Contract { - /// 文档锚点(T2.4):`file.mq.md#L4-L7`。 - pub fn anchor(&self, path: Option<&Path>) -> String { - match path { - Some(p) => format!("{}#L{}-L{}", p.display(), self.start_line, self.end_line), - None => format!("#L{}-L{}", self.start_line, self.end_line), - } - } - - pub fn quote_text(&self) -> String { - self.quote.join("\n") - } - - /// 契约声明摘要(诊断 `contract_ref.declared`)。 - pub fn describe(&self) -> String { - let mut parts = Vec::new(); - if !self.params.is_empty() { - let list = self - .params - .iter() - .map(|p| format!("{}: {}", p.name, p.ty.name())) - .collect::>() - .join(", "); - parts.push(format!("参数[{list}]")); - } - if let Some(r) = &self.returns { - parts.push(format!("返回 {}", r.ty.name())); - } - if !self.fields.is_empty() { - let list = self - .fields - .iter() - .map(|f| format!("{}: {}", f.name, f.ty.name())) - .collect::>() - .join(", "); - parts.push(format!("字段[{list}]")); - } - parts.join("; ") - } - - /// 装配带契约上下文的诊断(code + suggestion + doc_anchor + doc_quote + contract_ref)。 - pub fn diagnostic( - &self, - code: &str, - unit: &str, - message: String, - suggestion: String, - path: Option<&Path>, - span: Span, - ) -> Diagnostic { - Diagnostic::new(path, span, message) - .with_code(code) - .with_severity(Severity::Error) - .with_suggestion(suggestion) - .with_doc_anchor(self.anchor(path)) - .with_doc_quote(self.quote_text()) - .with_contract_ref(ContractRef { - unit: unit.to_string(), - kind: "contract".to_string(), - name: unit.to_string(), - declared: self.describe(), - }) - } -} - -/// 把第二个契约表合并进第一个(多表块;重复行 → Err 防两份契约打架)。 -pub fn merge_contract(dst: &mut Contract, src: Contract) -> std::result::Result<(), String> { - for p in src.params { - if dst.params.iter().any(|q| q.name == p.name) { - return Err(format!("契约参数 `{}` 重复(防两份契约打架)", p.name)); - } - dst.params.push(p); - } - if let Some(r) = src.returns { - if dst.returns.is_some() { - return Err("返回契约重复(防两份契约打架)".to_string()); - } - dst.returns = Some(r); - } - for f in src.fields { - if dst.fields.iter().any(|g| g.name == f.name) { - return Err(format!("契约字段 `{}` 重复(防两份契约打架)", f.name)); - } - dst.fields.push(f); - } - dst.start_line = dst.start_line.min(src.start_line); - dst.end_line = dst.end_line.max(src.end_line); - for q in src.quote { - if !dst.quote.contains(&q) { - dst.quote.push(q); - } - } - Ok(()) -} - -// ---------- 契约表识别与解析 ---------- - -const PARAM_HEADERS: &[&str] = &["参数", "形参", "param", "params", "arg", "args"]; -const RETURN_HEADERS: &[&str] = &["返回", "返回值", "return", "returns", "result"]; -const FIELD_HEADERS: &[&str] = &["字段", "列", "键", "field", "fields", "key", "keys", "column", "columns"]; -const TYPE_HEADERS: &[&str] = &["类型", "type"]; -const DESC_HEADERS: &[&str] = &["说明", "描述", "备注", "注释", "desc", "description"]; -const NULLABLE_HEADERS: &[&str] = &["可空", "nullable", "optional"]; - -// ---------- 定理表识别(ADR 0010 / 设计 §7.1) ---------- - -/// 定理表头(第一列)词表:`定理/证明/claim/theorem`。 -pub const CLAIM_NAME_HEADERS: &[&str] = &["定理", "证明", "claim", "theorem"]; -/// 结论列词表(必填列)。 -pub const CLAIM_CONCLUSION_HEADERS: &[&str] = &["结论", "conclusion"]; -/// 前提列词表(可缺省)。 -pub const CLAIM_PREMISE_HEADERS: &[&str] = &["前提", "premise", "assumes"]; -/// 策略列词表(可缺省)。 -pub const CLAIM_TACTIC_HEADERS: &[&str] = &["策略", "tactic"]; - -/// 表头是否命中定理表第一列(只看词,不看列形)。 -pub fn header_hits_claim(headers: &[String]) -> bool { - find_col(headers, CLAIM_NAME_HEADERS).is_some() -} - -/// 定理表认领判定(设计 §7.1 规则 1/5): -/// - `None`:表头不命中定理词表 → 普通表; -/// - `Some(Ok(rows))`:命中且列形正确(有结论列,无 `类型` 列)→ 定理表; -/// - `Some(Err(e))`:命中但有形状问题(歧义/行数不齐/缺名)→ `check --proof` 报。 -pub fn parse_claim_table( - pairs: &[(String, Expr)], - start_line: u32, -) -> Option, ClaimTableError>> { - let headers: Vec = pairs.iter().map(|(k, _)| k.clone()).collect(); - if !header_hits_claim(&headers) { - return None; - } - // 同时有 `类型` 列与 `结论` 列 → 歧义,不猜(§7.1 规则 5)。 - if find_col(&headers, TYPE_HEADERS).is_some() - && find_col(&headers, CLAIM_CONCLUSION_HEADERS).is_some() - { - return Some(Err(ClaimTableError { - code: "proof.claim_ambiguous", - message: "表同时含 `类型` 与 `结论` 列——契约表与定理表不猜,请拆开或改名".into(), - })); - } - // 无结论列 → 不是定理表(两列的 `定理/说明` 是普通说明表,§7.3.5)。 - let Some(conclusion_col) = find_col(&headers, CLAIM_CONCLUSION_HEADERS) else { - return None; - }; - let premise_col = find_col(&headers, CLAIM_PREMISE_HEADERS); - let tactic_col = find_col(&headers, CLAIM_TACTIC_HEADERS); - // 第一列=定理名;若第一列不是命中列,命中列才是名字列。 - let name_col = find_col(&headers, CLAIM_NAME_HEADERS).unwrap_or(0); - - let names = col_rows(&pairs[name_col].1).unwrap_or_default(); - let conclusions = claim_col_rows(&pairs[conclusion_col].1); - if names.len() != conclusions.len() { - return Some(Err(ClaimTableError { - code: "proof.claim_malformed", - message: format!( - "定理/结论 列行数不一致({} vs {})", - names.len(), - conclusions.len() - ), - })); - } - let premises = premise_col - .map(|c| claim_col_rows(&pairs[c].1)) - .unwrap_or_default(); - let tactics = tactic_col - .map(|c| col_rows(&pairs[c].1).unwrap_or_default()) - .unwrap_or_default(); - if !premises.is_empty() && premises.len() != names.len() { - return Some(Err(ClaimTableError { - code: "proof.claim_malformed", - message: "前提 列行数与 定理 列不一致".into(), - })); - } - if !tactics.is_empty() && tactics.len() != names.len() { - return Some(Err(ClaimTableError { - code: "proof.claim_malformed", - message: "策略 列行数与 定理 列不一致".into(), - })); - } - - let mut rows = Vec::new(); - for (i, name) in names.iter().enumerate() { - let name = name.trim(); - if name.is_empty() { - return Some(Err(ClaimTableError { - code: "proof.claim_malformed", - message: format!("定理表第 {} 行缺定理名", i + 1), - })); - } - rows.push(crate::ast::Claim { - id: name.to_string(), - conclusion: conclusions[i].trim().to_string(), - // 空前提单元格 = 无前提(全称命题)。 - premise: premises - .get(i) - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()), - tactic: tactics - .get(i) - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()), - line: start_line, - }); - } - Some(Ok(rows)) -} - -/// Parse the v2.9 modular assumption table. An assumption is metadata, -/// never a runtime statement or an independently verified theorem. -pub fn parse_assumption_table( - pairs: &[(String, Expr)], line: u32, -) -> Option,String>> { - const OP: &[&str] = &["假设","assumption"]; - const PRE: &[&str] = &["前置","requires","precondition"]; - const POST: &[&str] = &["后置","ensures","postcondition"]; - let headers:Vec=pairs.iter().map(|(k,_)|k.clone()).collect(); - let op=find_col(&headers,OP)?; - let post=match find_col(&headers,POST){ - Some(i)=>i, - None=>return Some(Err("assumption table requires a 后置 / ensures column".into())) - }; - let op_names=col_rows(&pairs[op].1).unwrap_or_default(); - let posts=claim_col_rows(&pairs[post].1); - let pres=find_col(&headers,PRE).map(|i|claim_col_rows(&pairs[i].1)); - if op_names.len()!=posts.len() - || pres.as_ref().is_some_and(|p|p.len()!=op_names.len()) { - return Some(Err("assumption table columns have different row counts".into())); - } - let mut results=Vec::new(); - for (i,name) in op_names.into_iter().enumerate(){ - if name.trim().is_empty() || posts[i].trim().is_empty() { - return Some(Err(format!("assumption row {} lacks operation or postcondition",i+1))); - } - results.push(crate::ast::Assumption{ - op:name.trim().to_string(), - premise:pres.as_ref().and_then(|p|p.get(i)) - .map(|s|s.trim().to_string()).filter(|s|!s.is_empty()), - postcondition:posts[i].trim().to_string(), - line, - }); - } - Some(Ok(results)) -} - -/// 定理表形状错误(`check --proof` 才报;默认关)。 -#[derive(Debug, Clone)] -pub struct ClaimTableError { - pub code: &'static str, - pub message: String, -} - -fn norm_header(h: &str) -> String { - h.trim().trim_matches('`').to_ascii_lowercase() -} - -fn header_is(h: &str, vocab: &[&str]) -> bool { - let n = norm_header(h); - vocab.iter().any(|v| *v == n) -} - -fn find_col(headers: &[String], vocab: &[&str]) -> Option { - headers.iter().position(|h| header_is(h, vocab)) -} - -/// 单元格 → 文本(text / `` `ident` `` / 数字);嵌套表 → None(那是数据表)。 -fn cell_to_text(e: &Expr) -> Option { - match e { - Expr::Literal(crate::ast::Literal::Text(s)) => Some(s.clone()), - Expr::Var(name) => Some(name.clone()), - Expr::Literal(crate::ast::Literal::Int(i)) => Some(i.to_string()), - Expr::Literal(crate::ast::Literal::Num(n)) => Some(n.to_string()), - Expr::Literal(crate::ast::Literal::Bool(b)) => Some(b.to_string()), - _ => None, - } -} - -/// 列值 → 行文本(标量 = 单行;列向量 = 多行;其它 = None)。 -fn col_rows(e: &Expr) -> Option> { - match e { - Expr::List(items) => items.iter().map(cell_to_text).collect(), - scalar => Some(vec![cell_to_text(scalar)?]), - } -} - -/// 定理表单元格取文本:标量直取;比较/算术/布尔表达式按 `a op b` 还原 -/// (`金额 > 10000` 这类单元格会解析成 Binary,不能因为不是标量就丢行)。 -/// 不认识的形状 → None(该行按缺失处理,`check --proof` 会报 unknown_symbol)。 -fn claim_cell_text(e: &Expr) -> Option { - if let Some(text) = cell_to_text(e) { - return Some(text); - } - match e { - Expr::Binary { op, left, right } => Some(format!( - "{} {} {}", - claim_cell_text(left)?, - op_token(*op), - claim_cell_text(right)? - )), - Expr::Unary { op, expr } => match op { - crate::ast::UnaryOp::Not => Some(format!("非 ({})", claim_cell_text(expr)?)), - crate::ast::UnaryOp::Neg => Some(format!("-({})", claim_cell_text(expr)?)), - }, - _ => None, - } -} - -fn op_token(op: crate::ast::BinaryOp) -> &'static str { - use crate::ast::BinaryOp as B; - match op { - B::Add => "+", - B::Sub => "-", - B::Mul => "*", - B::Div => "/", - B::Eq => "=", - B::Ne => "≠", - B::Lt => "<", - B::Le => "≤", - B::Gt => ">", - B::Ge => "≥", - B::And => "且", - B::Or => "或", - } -} - -/// 定理表列取文本(行级 None 不整列丢弃——只丢该行该列)。 -fn claim_col_rows(e: &Expr) -> Vec { - match e { - Expr::List(items) => items - .iter() - .map(|item| claim_cell_text(item).unwrap_or_default()) - .collect(), - scalar => vec![claim_cell_text(scalar).unwrap_or_default()], - } -} - -fn is_nullable(raw: &str) -> bool { - matches!( - norm_header(raw).as_str(), - "是" | "true" | "yes" | "y" | "可空" | "✓" - ) -} - -/// 未绑定文档表(`Expr::Map`)→ 契约块。 -/// -/// - `None`:非契约形状(普通数据/说明表,原样保留)。 -/// - `Some(Err)`:契约形状但畸形(缺参数名、列不齐、多行返回表…)——必产诊断。 -/// - `Some(Ok)`:合法契约(`参数`/`返回`/`字段` 三形状之一,须含 `类型` 列)。 -pub fn parse_contract_table( - pairs: &[(String, Expr)], - start_line: u32, - end_line: u32, - quote: Vec, -) -> Option> { - let headers: Vec = pairs.iter().map(|(k, _)| k.clone()).collect(); - let kind = if find_col(&headers, PARAM_HEADERS).is_some() { - 1 - } else if find_col(&headers, RETURN_HEADERS).is_some() { - 2 - } else if find_col(&headers, FIELD_HEADERS).is_some() { - 3 - } else { - return None; - }; - // 契约表必须有 `类型` 列(否则是普通说明表——如 `| 参数 | 说明 |`)。 - let Some(type_col) = find_col(&headers, TYPE_HEADERS) else { - return None; - }; - - let meta = || (start_line, end_line, quote.clone()); - Some(match kind { - 1 => parse_params_table(pairs, &headers, type_col, meta()), - 2 => parse_return_table(pairs, &headers, type_col, meta()), - _ => parse_fields_table(pairs, &headers, type_col, meta()), - }) -} - -fn contract( - meta: (u32, u32, Vec), -) -> Contract { - Contract { - params: Vec::new(), - returns: None, - fields: Vec::new(), - start_line: meta.0, - end_line: meta.1, - quote: meta.2, - } -} - -fn malformed(meta: (u32, u32, Vec), span_line: u32, msg: String) -> Result { - let (start, end, quote) = meta; - let c = Contract { - params: Vec::new(), - returns: None, - fields: Vec::new(), - start_line: start, - end_line: end, - quote, - }; - Err(c - .diagnostic( - "contract.malformed", - "(契约表)", - msg, - "按 `参数|类型|说明` / `返回|类型|说明` / `字段|类型|可空|说明` 形状修正契约表".into(), - None, - Span { line: span_line, col: 1 }, - ) - .into()) -} - -fn parse_params_table( - pairs: &[(String, Expr)], - headers: &[String], - type_col: usize, - meta: (u32, u32, Vec), -) -> Result { - let start_line = meta.0; - let name_col = find_col(headers, PARAM_HEADERS).unwrap(); - let desc_col = find_col(headers, DESC_HEADERS); - let names = col_rows(&pairs[name_col].1).unwrap_or_default(); - let types = col_rows(&pairs[type_col].1).unwrap_or_default(); - let descs = desc_col - .and_then(|c| col_rows(&pairs[c].1)) - .unwrap_or_default(); - if names.len() != types.len() || (!descs.is_empty() && descs.len() != names.len()) { - return malformed(meta, start_line, "契约表列不齐(参数/类型/说明 行数不一致)".into()); - } - let mut c = contract(meta.clone()); - for (i, name) in names.iter().enumerate() { - let name = name.trim(); - if name.is_empty() { - return malformed(meta, start_line, format!("契约表第 {} 行缺参数名", i + 1)); - } - c.params.push(ParamContract { - name: name.to_string(), - ty: Ty::parse(&types[i]), - desc: descs.get(i).cloned().unwrap_or_default(), - }); - } - Ok(c) -} - -fn parse_return_table( - pairs: &[(String, Expr)], - headers: &[String], - type_col: usize, - meta: (u32, u32, Vec), -) -> Result { - let start_line = meta.0; - let desc_col = find_col(headers, DESC_HEADERS); - let types = col_rows(&pairs[type_col].1).unwrap_or_default(); - let descs = desc_col - .and_then(|c| col_rows(&pairs[c].1)) - .unwrap_or_default(); - if types.len() != 1 { - return malformed(meta, start_line, "返回契约只能一行(`返回|类型|说明`)".into()); - } - let mut c = contract(meta.clone()); - c.returns = Some(ReturnContract { - ty: Ty::parse(&types[0]), - desc: descs.first().cloned().unwrap_or_default(), - }); - Ok(c) -} - -fn parse_fields_table( - pairs: &[(String, Expr)], - headers: &[String], - type_col: usize, - meta: (u32, u32, Vec), -) -> Result { - let start_line = meta.0; - let name_col = find_col(headers, FIELD_HEADERS).unwrap(); - let desc_col = find_col(headers, DESC_HEADERS); - let null_col = find_col(headers, NULLABLE_HEADERS); - let names = col_rows(&pairs[name_col].1).unwrap_or_default(); - let types = col_rows(&pairs[type_col].1).unwrap_or_default(); - if names.len() != types.len() { - return malformed(meta, start_line, "契约表列不齐(字段/类型 行数不一致)".into()); - } - let mut c = contract(meta.clone()); - for (i, name) in names.iter().enumerate() { - let name = name.trim(); - if name.is_empty() { - return malformed(meta, start_line, format!("契约表第 {} 行缺字段名", i + 1)); - } - c.fields.push(FieldContract { - name: name.to_string(), - ty: Ty::parse(&types[i]), - nullable: null_col - .and_then(|c| col_rows(&pairs[c].1)) - .and_then(|rows| rows.get(i).cloned()) - .map(|s| is_nullable(&s)) - .unwrap_or(false), - desc: desc_col - .and_then(|c| col_rows(&pairs[c].1)) - .and_then(|rows| rows.get(i).cloned()) - .unwrap_or_default(), - }); - } - Ok(c) -} - -// ---------- 运行时边界校验(T2.2,四个边界) ---------- - -/// 边界 1:调用实参 vs 形参契约。 -pub fn call_arg_diag( - c: &Contract, - unit: &str, - bound: &HashMap, - path: Option<&Path>, - span: Span, -) -> Option { - for p in &c.params { - let Some(v) = bound.get(&p.name) else { continue }; - if v == &Value::None { - continue; // 显式 None = 未填,交给缺参/默认值语义 - } - if !p.ty.matches_value(v) { - return Some(c.diagnostic( - "contract.arg_mismatch", - unit, - format!( - "参数 `{}` 期望 {},实际 {}(契约校验)", - p.name, - p.ty.name(), - type_of(v) - ), - format!( - "把实参改为 {},或修正契约表 `参数/类型` 列(锚点 {})", - p.ty.name(), - c.anchor(path) - ), - path, - span, - )); - } - } - None -} - -/// Argument blame belongs to the caller; contract evidence belongs to the -/// declaration. Import aliases must not relocate a contract into the caller. -pub fn call_arg_diag_in( - c: &Contract, unit: &str, bound: &HashMap, - call_site: &crate::diagnostics::SourceLocation, - declaration: &crate::diagnostics::SourceIdentity, -) -> Option { - let mut diag=call_arg_diag(c,unit,bound,call_site.source.path.as_deref(),call_site.span)? - .with_source(&call_site.source); - let old=c.anchor(call_site.source.path.as_deref()); - let new=c.anchor(declaration.path.as_deref()); - diag.doc_anchor=Some(new.clone()); - diag.suggestion=diag.suggestion.map(|text|text.replace(&old,&new)); - Some(diag) -} - -/// 边界 2:返回值 vs 返回契约。 -pub fn return_diag( - c: &Contract, - unit: &str, - v: &Value, - path: Option<&Path>, - span: Span, -) -> Option { - let r = c.returns.as_ref()?; - if !r.ty.matches_value(v) { - return Some(c.diagnostic( - "contract.return_mismatch", - unit, - format!( - "返回值期望 {},实际 {}(契约校验)", - r.ty.name(), - type_of(v) - ), - format!( - "修正返回值,或调整契约表 `返回|类型`(锚点 {})", - c.anchor(path) - ), - path, - span, - )); - } - None -} - -/// 边界 3:表绑定 vs 字段契约(集合契约;几何即类型——标量或列向量皆可)。 -pub fn fields_diag( - c: &Contract, - unit: &str, - v: &Value, - path: Option<&Path>, - span: Span, -) -> Option { - if c.fields.is_empty() { - return None; - } - let Value::Map(pairs) = v else { - return Some(c.diagnostic( - "contract.field_mismatch", - unit, - format!("绑定值期望表(map),实际 {}(契约校验)", type_of(v)), - "绑定一个表值,或删除该字段契约表".into(), - path, - span, - )); - }; - for f in &c.fields { - match pairs.iter().find(|(k, _)| k == &f.name) { - Some((_, val)) => { - if !f.ty.matches_column(val) { - return Some(c.diagnostic( - "contract.field_mismatch", - unit, - format!( - "字段 `{}` 期望 {},实际 {}(契约校验)", - f.name, - f.ty.name(), - type_of(val) - ), - format!("修正数据,或调整契约表 `字段/类型`(锚点 {})", c.anchor(path)), - path, - span, - )); - } - } - None if f.nullable => {} - None => { - return Some(c.diagnostic( - "contract.field_mismatch", - unit, - format!("缺少字段 `{}`(契约要求,不可空)", f.name), - format!("补上字段 `{}`,或在契约表 `可空` 列标 `是`(锚点 {})", f.name, c.anchor(path)), - path, - span, - )); - } - } - } - None -} - -/// 边界 4:字段访问 `[键](集合)` vs 字段契约(键存在性 + 取值类型)。 -pub fn index_diag( - c: &Contract, - unit: &str, - key: &str, - v: &Value, - path: Option<&Path>, - span: Span, -) -> Option { - let Some(f) = c.fields.iter().find(|f| f.name == key) else { - return Some(c.diagnostic( - "contract.unknown_key", - unit, - format!("字段 `{key}` 不在契约中(契约校验)"), - format!( - "使用契约内的字段({}),或在契约表补一行", - c.fields - .iter() - .map(|f| f.name.as_str()) - .collect::>() - .join(" / ") - ), - path, - span, - )); - }; - if v != &Value::None && !f.ty.matches_column(v) { - return Some(c.diagnostic( - "contract.field_mismatch", - unit, - format!( - "字段 `{key}` 期望 {},实际 {}(契约校验)", - f.ty.name(), - type_of(v) - ), - format!("修正数据,或调整契约表 `字段/类型`(锚点 {})", c.anchor(path)), - path, - span, - )); - } - None -} diff --git a/src/debug/ctrl.rs b/src/debug/ctrl.rs deleted file mode 100755 index c062e1b..0000000 --- a/src/debug/ctrl.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! Interactive debug controller for tree-walk (view + tests). - -use std::collections::{HashMap, HashSet}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Condvar, Mutex}; -use std::time::Duration; - -use crate::value::Value; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DebugAction { - Continue, - Step, - Stop, -} - -#[derive(Debug, Clone)] -pub struct DebugPause { - pub line: u32, - pub fun: String, - pub locals: Vec<(String, String)>, - pub stdout: String, -} - -#[derive(Debug, Clone)] -pub enum DebugSnapshot { - Idle, - Running, - Paused(DebugPause), - Done { - ok: bool, - stdout: String, - stderr: String, - }, -} - -struct Gate { - action: Mutex>, - cv: Condvar, -} - -/// Shared between the interpreter thread and HTTP/CLI control. -pub struct DebugController { - breakpoints: Mutex>, - /// Pause at the next statement (step). - step_once: AtomicBool, - stop: AtomicBool, - /// Skip re-breaking on this line once after continue-from-pause (same entry). - suppress_line: Mutex>, - gate: Gate, - snapshot: Mutex, - /// Notifies waiters that snapshot changed. - snap_cv: Condvar, -} - -impl DebugController { - pub fn new(breakpoints: HashSet) -> Arc { - Arc::new(Self { - breakpoints: Mutex::new(breakpoints), - step_once: AtomicBool::new(false), - stop: AtomicBool::new(false), - suppress_line: Mutex::new(None), - gate: Gate { - action: Mutex::new(None), - cv: Condvar::new(), - }, - snapshot: Mutex::new(DebugSnapshot::Idle), - snap_cv: Condvar::new(), - }) - } - - pub fn set_breakpoints(&self, lines: HashSet) { - *self.breakpoints.lock().unwrap() = lines; - } - - /// Pause at the next statement (used when starting with no breakpoints). - pub fn request_step(&self) { - self.step_once.store(true, Ordering::SeqCst); - } - - pub fn breakpoints(&self) -> HashSet { - self.breakpoints.lock().unwrap().clone() - } - - pub fn snapshot(&self) -> DebugSnapshot { - self.snapshot.lock().unwrap().clone() - } - - pub fn set_running(&self) { - *self.snapshot.lock().unwrap() = DebugSnapshot::Running; - self.snap_cv.notify_all(); - } - - pub fn set_done(&self, ok: bool, stdout: String, stderr: String) { - *self.snapshot.lock().unwrap() = DebugSnapshot::Done { - ok, - stdout, - stderr, - }; - self.snap_cv.notify_all(); - // Unblock any waiter in on_stmt - self.send_action(DebugAction::Stop); - } - - pub fn send_action(&self, action: DebugAction) { - // Clear stale Paused so wait_until_* does not return the previous pause. - { - let mut snap = self.snapshot.lock().unwrap(); - if matches!(&*snap, DebugSnapshot::Paused(_)) { - *snap = DebugSnapshot::Running; - self.snap_cv.notify_all(); - } - } - let mut g = self.gate.action.lock().unwrap(); - *g = Some(action); - self.gate.cv.notify_all(); - } - - /// Wait until snapshot is Paused or Done (or timeout). - pub fn wait_until_paused_or_done(&self, timeout: Duration) -> DebugSnapshot { - let mut snap = self.snapshot.lock().unwrap(); - let deadline = std::time::Instant::now() + timeout; - loop { - match &*snap { - DebugSnapshot::Paused(_) | DebugSnapshot::Done { .. } => return snap.clone(), - _ => {} - } - let now = std::time::Instant::now(); - if now >= deadline { - return snap.clone(); - } - let (s, _) = self - .snap_cv - .wait_timeout(snap, deadline - now) - .unwrap(); - snap = s; - } - } - - /// Called at the start of each statement. - pub fn on_stmt( - &self, - line: u32, - fun: &str, - locals: &HashMap, - stdout: &str, - ) -> Result<(), String> { - if self.stop.load(Ordering::SeqCst) { - return Err("debug stopped".into()); - } - - let step = self.step_once.swap(false, Ordering::SeqCst); - let is_bp = self.breakpoints.lock().unwrap().contains(&line); - let suppressed = *self.suppress_line.lock().unwrap() == Some(line); - if suppressed { - *self.suppress_line.lock().unwrap() = None; - } - let should_pause = step || (is_bp && !suppressed); - if !should_pause { - return Ok(()); - } - - let mut locals_v: Vec<(String, String)> = locals - .iter() - .map(|(k, v)| (k.clone(), v.as_display())) - .collect(); - locals_v.sort_by(|a, b| a.0.cmp(&b.0)); - - { - let mut snap = self.snapshot.lock().unwrap(); - *snap = DebugSnapshot::Paused(DebugPause { - line, - fun: fun.to_string(), - locals: locals_v, - stdout: stdout.to_string(), - }); - self.snap_cv.notify_all(); - } - - // Wait for Continue / Step / Stop - let mut guard = self.gate.action.lock().unwrap(); - loop { - while guard.is_none() { - guard = self.gate.cv.wait(guard).unwrap(); - } - let action = guard.take().unwrap(); - match action { - DebugAction::Continue => { - // Don't immediately re-break on this same line entry. - *self.suppress_line.lock().unwrap() = Some(line); - return Ok(()); - } - DebugAction::Step => { - self.step_once.store(true, Ordering::SeqCst); - *self.suppress_line.lock().unwrap() = Some(line); - return Ok(()); - } - DebugAction::Stop => { - self.stop.store(true, Ordering::SeqCst); - return Err("debug stopped".into()); - } - } - } - } -} - -/// Serialize snapshot for JSON APIs. -pub fn snapshot_json(s: &DebugSnapshot) -> serde_json::Value { - match s { - DebugSnapshot::Idle => serde_json::json!({ "status": "idle" }), - DebugSnapshot::Running => serde_json::json!({ "status": "running" }), - DebugSnapshot::Paused(p) => { - let locals: serde_json::Map = p - .locals - .iter() - .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone()))) - .collect(); - serde_json::json!({ - "status": "paused", - "line": p.line, - "fun": p.fun, - "locals": locals, - "stdout": p.stdout, - }) - } - DebugSnapshot::Done { - ok, - stdout, - stderr, - } => serde_json::json!({ - "status": "done", - "ok": ok, - "stdout": stdout, - "stderr": stderr, - }), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::thread; - use std::time::Duration; - - #[test] - fn pause_continue_and_locals() { - let ctrl = DebugController::new(HashSet::from([2])); - let c2 = ctrl.clone(); - let handle = thread::spawn(move || { - let mut locals = HashMap::new(); - locals.insert("x".into(), Value::Int(1)); - c2.on_stmt(1, "main", &locals, "").unwrap(); // no bp - locals.insert("x".into(), Value::Int(2)); - c2.on_stmt(2, "main", &locals, "hi\n").unwrap(); // pauses - locals.insert("x".into(), Value::Int(3)); - c2.on_stmt(3, "main", &locals, "hi\n").unwrap(); - c2.set_done(true, "hi\n".into(), String::new()); - }); - - let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); - match snap { - DebugSnapshot::Paused(p) => { - assert_eq!(p.line, 2); - assert_eq!(p.fun, "main"); - assert!(p.locals.iter().any(|(k, v)| k == "x" && v == "2")); - assert_eq!(p.stdout, "hi\n"); - } - other => panic!("expected paused, got {other:?}"), - } - ctrl.send_action(DebugAction::Continue); - let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); - match snap { - DebugSnapshot::Done { ok, stdout, .. } => { - assert!(ok); - assert_eq!(stdout, "hi\n"); - } - other => panic!("expected done, got {other:?}"), - } - handle.join().unwrap(); - } - - #[test] - fn step_once() { - let ctrl = DebugController::new(HashSet::new()); - ctrl.request_step(); - let c2 = ctrl.clone(); - let handle = thread::spawn(move || { - let locals = HashMap::new(); - c2.on_stmt(10, "main", &locals, "").unwrap(); - c2.set_done(true, String::new(), String::new()); - }); - let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); - assert!(matches!(snap, DebugSnapshot::Paused(p) if p.line == 10)); - ctrl.send_action(DebugAction::Continue); - let _ = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); - handle.join().unwrap(); - } - - #[test] - fn interpreter_pauses_on_breakpoint() { - use crate::interp::Interpreter; - use crate::parse::parse_source; - - let src = "# main\n\n**x = 1**\n> print text=`x`\n**x = 2**\n> print text=`x`\n"; - let module = parse_source(src).expect("parse"); - // Line 4 is first `> print` - let ctrl = DebugController::new(HashSet::from([4u32])); - let c2 = ctrl.clone(); - let handle = thread::spawn(move || { - let mut interp = Interpreter::with_capture(None, false).with_debug(c2.clone()); - let r = interp.run_module(&module); - let out = interp.captured_stdout.clone(); - match r { - Ok(_) => c2.set_done(true, out, String::new()), - Err(e) => c2.set_done(false, out, e.to_string()), - } - }); - - let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); - match snap { - DebugSnapshot::Paused(p) => { - assert_eq!(p.line, 4, "locals={:?}", p.locals); - assert!(p.locals.iter().any(|(k, v)| k == "x" && v == "1")); - } - other => panic!("expected pause on line 4, got {other:?}"), - } - ctrl.send_action(DebugAction::Continue); - let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(2)); - match snap { - DebugSnapshot::Done { ok, stdout, stderr } => { - assert!(ok, "stderr={stderr}"); - assert!(stdout.contains('1') && stdout.contains('2'), "{stdout:?}"); - } - other => panic!("expected done, got {other:?}"), - } - handle.join().unwrap(); - } -} diff --git a/src/debug/mod.rs b/src/debug/mod.rs deleted file mode 100755 index 8cd0c5c..0000000 --- a/src/debug/mod.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Pipeline dump helpers + interactive debug (see doc/design/pipeline-debug.md, view-debug). - -mod ctrl; -mod trace; - -pub use crate::lex::format_lines_dump; -pub use ctrl::{ - snapshot_json, DebugAction, DebugController, DebugPause, DebugSnapshot, -}; -pub use trace::emit_trace; - -use crate::lex::{ClassifiedLine, LineKind}; -use crate::parse::{scan_prose_line, ProseBit}; - -/// Line dump with v0.3 prose bits (decl / bold / italic) on each line. -pub fn format_lines_dump_v03(path: &str, lines: &[ClassifiedLine]) -> String { - let mut out = String::new(); - out.push_str(&format!("=== marqdo: lines ({path}) ===\n")); - for line in lines { - let preview = if line.text.len() > 80 { - format!("{}…", &line.text.chars().take(80).collect::()) - } else { - line.text.clone() - }; - match line.kind { - LineKind::Blank => { - out.push_str(&format!("{:4} {:7}\n", line.line_no, line.kind)); - } - _ => { - let tags = prose_tags(&preview); - if tags.is_empty() { - out.push_str(&format!( - "{:4} {:7} | {}\n", - line.line_no, line.kind, preview - )); - } else { - out.push_str(&format!( - "{:4} {:7} | {} {}\n", - line.line_no, line.kind, preview, tags - )); - } - } - } - } - out.push_str("=== marqdo: end lines ===\n"); - out -} - -fn prose_tags(text: &str) -> String { - let bits = scan_prose_line(text.trim_end_matches(['\r', '\n'])); - if bits.is_empty() { - return String::new(); - } - bits.iter() - .map(|b| match b { - ProseBit::Decl { name, default, .. } => match default { - Some(d) => format!("[decl {name}={d}]"), - None => format!("[decl {name}]"), - }, - ProseBit::BoldCode { inner, .. } => format!("[bold {}]", compact(inner)), - ProseBit::ItalicReturn { inner, .. } => format!("[italic {}]", compact(inner)), - }) - .collect::>() - .join(" ") -} - -fn compact(s: &str) -> String { - let t = s.trim(); - if t.chars().count() <= 40 { - t.to_string() - } else { - format!("{}…", t.chars().take(40).collect::()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::lex::classify_source; - - #[test] - fn dump_lines_tags_decl_bold_italic() { - let src = "对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。\n"; - let lines = classify_source(src); - let dump = format_lines_dump_v03("t.mq.md", &lines); - assert!(dump.contains("[decl n]"), "{dump}"); - assert!(dump.contains("[bold n=n+1]"), "{dump}"); - assert!(dump.contains("[italic n]"), "{dump}"); - } -} diff --git a/src/debug/trace.rs b/src/debug/trace.rs deleted file mode 100755 index f49a8cb..0000000 --- a/src/debug/trace.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Structured eval trace (P3-D1): JSON lines on stderr. - -use std::path::Path; - -use crate::diagnostics::{display_path, Span}; - -/// Emit one JSON object line to stderr when tracing. -pub fn emit_trace(path: Option<&Path>, span: Option, event: &str, fields: &[(&str, &str)]) { - let mut out = String::from("{"); - out.push_str(&format!("\"event\":{}", json_str(event))); - if let Some(p) = path { - out.push_str(&format!(",\"path\":{}", json_str(&display_path(p)))); - } - if let Some(sp) = span { - out.push_str(&format!(",\"span\":{}", json_str(&sp.to_string()))); - } - for (k, v) in fields { - out.push_str(&format!(",\"{}\":{}", k, json_str(v))); - } - out.push('}'); - eprintln!("{out}"); -} - -fn json_str(s: &str) -> String { - let mut out = String::from("\""); - for c in s.chars() { - match c { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), - c => out.push(c), - } - } - out.push('"'); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn json_str_escapes() { - assert_eq!(json_str("a\"b"), r#""a\"b""#); - } -} diff --git a/src/diagnostics.rs b/src/diagnostics.rs deleted file mode 100755 index 4af5476..0000000 --- a/src/diagnostics.rs +++ /dev/null @@ -1,326 +0,0 @@ -//! Diagnostics with file/line/column. - -use std::fmt; -use std::path::{Path, PathBuf}; - -use thiserror::Error; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Span { - pub line: u32, - pub col: u32, -} - -impl Span { - pub fn new(line: u32, col: u32) -> Self { - Self { line, col } - } -} - -impl fmt::Display for Span { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}:{}", self.line, self.col) - } -} - -/// Identity of the exact text that was parsed, including recorded revisions. -/// A path is a label; the digest is never recomputed from a later disk version. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct SourceIdentity { - pub path: Option, - pub sha256: Option, -} - -impl SourceIdentity { - pub fn from_source(path: Option<&Path>, text: &str) -> Self { - use sha2::{Digest, Sha256}; - Self { - path: path.map(Path::to_path_buf), - sha256: Some(format!("{:x}", Sha256::digest(text.as_bytes()))), - } - } - - pub fn at(&self, span: Span) -> SourceLocation { - SourceLocation { - source: self.clone(), - span, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SourceLocation { - pub source: SourceIdentity, - pub span: Span, -} - -impl SourceLocation { - pub fn to_json(&self) -> serde_json::Value { - serde_json::json!({"file": self.source.path.as_ref().map(|p| display_path(p)), - "source_sha256": self.source.sha256, "line": self.span.line, "col": self.span.col}) - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DiagnosticFrame { - pub function: String, - pub declaration: SourceLocation, - pub call_site: Option, -} - -impl DiagnosticFrame { - pub fn to_json(&self) -> serde_json::Value { - serde_json::json!({"function": self.function, "declaration": self.declaration.to_json(), - "call_site": self.call_site.as_ref().map(SourceLocation::to_json)}) - } -} - -/// Format a path for user-facing diagnostics. -/// -/// Strips the Windows extended-length prefix (`\\?\` / `\\?\UNC\`) that -/// `canonicalize` often adds, so messages stay readable. -pub fn display_path(path: &Path) -> String { - let raw = path.display().to_string(); - if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") { - format!(r"\\{rest}") - } else if let Some(rest) = raw.strip_prefix(r"\\?\") { - rest.to_string() - } else if let Some(rest) = raw.strip_prefix("//?/") { - // Some tools emit forward-slash forms - rest.to_string() - } else { - raw - } -} - -/// Diagnostic severity. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Severity { - Error, - Warning, -} - -/// Contract reference (Phase 2 填值;schema 源头 = 契约表 / 说明段落). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ContractRef { - pub unit: String, - pub kind: String, - pub name: String, - pub declared: String, -} - -/// Unified diagnostic: `path:line:col: message` (path omitted if unknown). -/// -/// 人类文本(`Display`)与机器面([`Diagnostic::to_json`])同源:凡可定位必有 -/// `span`;凡契约错必带 `doc_anchor` / `doc_quote` / `contract_ref` -/// (见 `doc/roadmap/three-problems.md` §3.3 诊断协议)。 -#[derive(Debug, Error, Clone)] -#[error("{}", self.format_message())] -pub struct Diagnostic { - pub path: Option, - pub span: Span, - pub message: String, - /// Stable machine code (`parse.*` / `contract.*` / `runtime.*` …). - pub code: String, - pub severity: Severity, - pub suggestion: Option, - pub doc_anchor: Option, - pub doc_quote: Option, - pub contract_ref: Option, - pub source_sha256: Option, - /// Ordered outermost to innermost; every site retains its own source. - pub frames: Vec, -} - -impl Diagnostic { - pub fn new(path: Option<&Path>, span: Span, message: impl Into) -> Self { - Self { - path: path.map(|p| p.to_path_buf()), - span, - message: message.into(), - code: "marqdo.error".to_string(), - severity: Severity::Error, - suggestion: None, - doc_anchor: None, - doc_quote: None, - contract_ref: None, - source_sha256: None, - frames: Vec::new(), - } - } - - pub fn at(path: &Path, span: Span, message: impl Into) -> Self { - Self::new(Some(path), span, message) - } - - pub fn with_code(mut self, code: impl Into) -> Self { - self.code = code.into(); - self - } - - pub fn with_source(mut self, source: &SourceIdentity) -> Self { - self.path = source.path.clone(); - self.source_sha256 = source.sha256.clone(); - self - } - - pub fn with_frames(mut self, frames: &[DiagnosticFrame]) -> Self { - self.frames = frames.to_vec(); - self - } - - pub fn with_severity(mut self, severity: Severity) -> Self { - self.severity = severity; - self - } - - pub fn with_suggestion(mut self, suggestion: impl Into) -> Self { - self.suggestion = Some(suggestion.into()); - self - } - - pub fn with_doc_anchor(mut self, anchor: impl Into) -> Self { - self.doc_anchor = Some(anchor.into()); - self - } - - pub fn with_doc_quote(mut self, quote: impl Into) -> Self { - self.doc_quote = Some(quote.into()); - self - } - - pub fn with_contract_ref(mut self, contract_ref: ContractRef) -> Self { - self.contract_ref = Some(contract_ref); - self - } - - /// 从 anyhow 错误链中找回结构化诊断(load/parse 包了 context 也不丢;MLSP 面)。 - pub fn find(err: &anyhow::Error) -> Option<&Diagnostic> { - err.chain().find_map(|e| e.downcast_ref::()) - } - - pub fn format_message(&self) -> String { - let mut message = match &self.path { - Some(p) => format!("{}:{}: {}", display_path(p), self.span, self.message), - None => format!("{}: {}", self.span, self.message), - }; - for frame in self.frames.iter().rev() { - if let Some(site) = &frame.call_site { - let file = site - .source - .path - .as_ref() - .map(|p| display_path(p)) - .unwrap_or_else(|| "".into()); - message.push_str(&format!( - "\n called {} from {}:{}", - frame.function, file, site.span - )); - } - } - message - } - - /// Machine-readable form(AI/MLSP 面;`run --json` 出口)。 - pub fn to_json(&self) -> serde_json::Value { - use serde_json::json; - json!({ - "code": self.code, - "severity": match self.severity { - Severity::Error => "error", - Severity::Warning => "warning", - }, - "message": self.message, - "span": { - "file": self.path.as_ref().map(|p| display_path(p)), - "line": self.span.line, - "col": self.span.col, - }, - "source_sha256": self.source_sha256, - "frames": self.frames.iter().map(DiagnosticFrame::to_json).collect::>(), - "doc_anchor": self.doc_anchor, - "doc_quote": self.doc_quote, - "contract_ref": self.contract_ref.as_ref().map(|c| json!({ - "unit": c.unit, - "kind": c.kind, - "name": c.name, - "declared": c.declared, - })), - "suggestion": self.suggestion, - }) - } -} - -/// Convenience for `anyhow` sites that already have a span. -pub fn bail_at(path: Option<&Path>, span: Span, message: impl Into) -> anyhow::Error { - anyhow::Error::new(Diagnostic::new(path, span, message)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn strips_windows_extended_prefix() { - let p = PathBuf::from(r"\\?\E:\marqdo\examples\errors\bad-arity.mq.md"); - assert_eq!( - display_path(&p), - r"E:\marqdo\examples\errors\bad-arity.mq.md" - ); - } - - #[test] - fn strips_unc_extended_prefix() { - let p = PathBuf::from(r"\\?\UNC\server\share\file.mq.md"); - assert_eq!(display_path(&p), r"\\server\share\file.mq.md"); - } - - #[test] - fn diagnostic_message_uses_clean_path() { - let d = Diagnostic::at( - Path::new(r"\\?\E:\marqdo\x.mq.md"), - Span::new(7, 1), - "missing argument for parameter `x`", - ); - let msg = d.format_message(); - assert!(!msg.contains(r"\\?\")); - assert!(msg.contains(r"E:\marqdo\x.mq.md:7:1:")); - } - - #[test] - fn json_shape_defaults_nonempty_code_and_span() { - let d = Diagnostic::at(Path::new("x.mq.md"), Span::new(3, 5), "boom"); - let v = d.to_json(); - assert_eq!(v["code"], "marqdo.error"); - assert_eq!(v["severity"], "error"); - assert_eq!(v["span"]["line"], 3); - assert_eq!(v["span"]["col"], 5); - assert_eq!(v["span"]["file"], "x.mq.md"); - } - - #[test] - fn json_carries_doc_anchor_and_contract_ref() { - let d = Diagnostic::at( - Path::new("demo.mq.md"), - Span::new(12, 3), - "参数 `n` 期望 number,实际 text", - ) - .with_code("contract.arg_mismatch") - .with_doc_anchor("demo.mq.md#L4-L7") - .with_doc_quote("| `n` | number | 输入值 |") - .with_suggestion("把实参改为数字") - .with_contract_ref(ContractRef { - unit: "加一".to_string(), - kind: "param".to_string(), - name: "n".to_string(), - declared: "number".to_string(), - }); - let v = d.to_json(); - assert_eq!(v["code"], "contract.arg_mismatch"); - assert_eq!(v["doc_anchor"], "demo.mq.md#L4-L7"); - assert_eq!(v["contract_ref"]["unit"], "加一"); - assert_eq!(v["suggestion"], "把实参改为数字"); - // Display 零回归 - assert!(d.format_message().contains("demo.mq.md:12:3:")); - } -} diff --git a/src/document_extract.rs b/src/document_extract.rs deleted file mode 100755 index d76c627..0000000 --- a/src/document_extract.rs +++ /dev/null @@ -1,299 +0,0 @@ -//! Document extraction protocol (M01): DocumentSource → ExtractedDocument. -//! -//! Format parsers live here / in extensions — language core does not OCR. -//! First slice: plain text and Markdown. PDF/DOCX plug in later via the same shape. - -use std::fs; -use std::path::Path; - -use sha2::{Digest, Sha256}; -use serde_json::{json, Value}; - -pub const EXTRACTOR_VERSION: &str = "marqdo-document-extract/1"; - -#[derive(Debug, Clone)] -pub struct DocumentSource { - pub path: std::path::PathBuf, - pub format_hint: Option, -} - -#[derive(Debug, Clone)] -pub struct ExtractedSegment { - pub id: String, - pub kind: String, - pub text: String, - pub locator: String, - pub confidence: f64, -} - -#[derive(Debug, Clone)] -pub struct ExtractedDocument { - pub source_uri: String, - pub source_digest: String, - pub format: String, - pub extractor_version: String, - pub text: String, - pub segments: Vec, - pub missing: Vec, - pub diagnostics: Vec, - pub status: String, -} - -impl ExtractedDocument { - pub fn to_json(&self) -> Value { - json!({ - "schema_version": 1, - "source_uri": self.source_uri, - "source_digest": self.source_digest, - "format": self.format, - "extractor_version": self.extractor_version, - "status": self.status, - "text": self.text, - "segments": self.segments.iter().map(|s| json!({ - "id": s.id, - "kind": s.kind, - "text": s.text, - "locator": s.locator, - "confidence": s.confidence, - })).collect::>(), - "missing": self.missing, - "diagnostics": self.diagnostics, - }) - } -} - -/// Extract text/Markdown from a file. Uploaded `.mq.md` is treated as untrusted -/// source text and is never executed here. -pub fn extract_document(source: &DocumentSource) -> ExtractedDocument { - let path = &source.path; - let uri = path.to_string_lossy().replace('\\', "/"); - let ext = path - .extension() - .and_then(|e| e.to_str()) - .unwrap_or("") - .to_ascii_lowercase(); - let name = path - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or("") - .to_ascii_lowercase(); - - let format = source - .format_hint - .clone() - .unwrap_or_else(|| { - if name.ends_with(".mq.md") || ext == "md" { - "markdown".into() - } else if matches!(ext.as_str(), "txt" | "text") { - "text".into() - } else if matches!(ext.as_str(), "pdf" | "docx") { - ext.clone() - } else { - "unknown".into() - } - }); - - if matches!( - format.as_str(), - "pdf" | "docx" | "ocr" | "png" | "jpg" | "jpeg" | "webp" | "tiff" - ) || matches!(ext.as_str(), "pdf" | "docx" | "png" | "jpg" | "jpeg" | "webp" | "tiff") - { - let kind = if matches!(format.as_str(), "ocr") - || matches!(ext.as_str(), "png" | "jpg" | "jpeg" | "webp" | "tiff") - { - "ocr/image".to_string() - } else { - format.clone() - }; - return ExtractedDocument { - source_uri: uri, - source_digest: String::new(), - format, - extractor_version: EXTRACTOR_VERSION.into(), - text: String::new(), - segments: vec![], - missing: vec!["full_document".into()], - diagnostics: vec![format!( - "format `{kind}` requires an external extractor plugin (not in core); incomplete extraction is explicit failure" - )], - status: "failed".into(), - }; - } - - let bytes = match fs::read(path) { - Ok(b) => b, - Err(e) => { - return ExtractedDocument { - source_uri: uri, - source_digest: String::new(), - format, - extractor_version: EXTRACTOR_VERSION.into(), - text: String::new(), - segments: vec![], - missing: vec!["full_document".into()], - diagnostics: vec![format!("read error: {e}")], - status: "failed".into(), - }; - } - }; - - if bytes.is_empty() { - return ExtractedDocument { - source_uri: uri, - source_digest: digest_bytes(&bytes), - format, - extractor_version: EXTRACTOR_VERSION.into(), - text: String::new(), - segments: vec![], - missing: vec!["content".into()], - diagnostics: vec!["empty document".into()], - status: "failed".into(), - }; - } - - // Resource limit: refuse to fully buffer huge uploads as text (M01). - const MAX_EXTRACT_BYTES: usize = 8 << 20; - if bytes.len() > MAX_EXTRACT_BYTES { - let head = &bytes[..MAX_EXTRACT_BYTES]; - let lossy = String::from_utf8_lossy(head).into_owned(); - let mut doc = extract_markdown_or_text(&uri, &digest_bytes(&bytes), &format, &lossy); - doc.missing.push("tail_beyond_limit".into()); - doc.diagnostics.push(format!( - "document truncated at {MAX_EXTRACT_BYTES} bytes (got {}); extraction is partial", - bytes.len() - )); - doc.status = "partial".into(); - return doc; - } - - let text = match String::from_utf8(bytes.clone()) { - Ok(t) => t, - Err(e) => { - let lossy = String::from_utf8_lossy(&bytes).into_owned(); - let mut doc = extract_markdown_or_text(&uri, &digest_bytes(&bytes), &format, &lossy); - doc.diagnostics - .push(format!("invalid utf-8 ({e}); decoded lossy")); - doc.status = if doc.text.is_empty() { - "failed".into() - } else { - "partial".into() - }; - return doc; - } - }; - - extract_markdown_or_text(&uri, &digest_bytes(&bytes), &format, &text) -} - -fn extract_markdown_or_text( - uri: &str, - digest: &str, - format: &str, - text: &str, -) -> ExtractedDocument { - let mut segments = Vec::new(); - let mut n = 0u32; - let mut byte_off = 0usize; - for (i, line) in text.lines().enumerate() { - let line_no = i + 1; - let line_bytes = line.len(); - // M05: stable fragment locator with 1-based line + UTF-8 byte offset. - let loc = |kind: &str| format!("{kind}:L{line_no}:B{byte_off}"); - if let Some(rest) = line.trim().strip_prefix('#') { - n += 1; - let heading = rest.trim_start_matches('#').trim(); - segments.push(ExtractedSegment { - id: format!("seg-{n}"), - kind: "heading".into(), - text: heading.to_string(), - locator: loc("heading"), - confidence: 1.0, - }); - } else if line.trim().starts_with('|') { - n += 1; - segments.push(ExtractedSegment { - id: format!("seg-{n}"), - kind: "table_row".into(), - text: line.to_string(), - locator: loc("table_row"), - confidence: 0.9, - }); - } else if !line.trim().is_empty() { - n += 1; - segments.push(ExtractedSegment { - id: format!("seg-{n}"), - kind: "paragraph".into(), - text: line.to_string(), - locator: loc("paragraph"), - confidence: 1.0, - }); - } - // +1 for '\n' when present in original (lines() strips it). - byte_off += line_bytes + 1; - } - ExtractedDocument { - source_uri: uri.to_string(), - source_digest: digest.to_string(), - format: format.to_string(), - extractor_version: EXTRACTOR_VERSION.into(), - text: text.to_string(), - segments, - missing: vec![], - diagnostics: vec![], - status: "ok".into(), - } -} - -fn digest_bytes(bytes: &[u8]) -> String { - let mut h = Sha256::new(); - h.update(bytes); - format!("sha256:{:x}", h.finalize()) -} - -/// Convenience for tests / CLI: extract if path exists. -pub fn extract_path(path: &Path) -> ExtractedDocument { - extract_document(&DocumentSource { - path: path.to_path_buf(), - format_hint: None, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - #[test] - fn extracts_markdown_headings() { - let dir = std::env::temp_dir().join(format!("mq-extract-{}", std::process::id())); - let _ = fs::create_dir_all(&dir); - let path = dir.join("note.md"); - let mut f = fs::File::create(&path).unwrap(); - writeln!(f, "# rate\n\nhello").unwrap(); - let doc = extract_path(&path); - assert_eq!(doc.status, "ok"); - assert!(doc.segments.iter().any(|s| s.kind == "heading" && s.text == "rate")); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn pdf_reports_missing_extractor() { - let doc = extract_document(&DocumentSource { - path: Path::new("x.pdf").into(), - format_hint: Some("pdf".into()), - }); - assert_eq!(doc.status, "failed"); - assert!(!doc.diagnostics.is_empty()); - } - - #[test] - fn ocr_image_reports_missing_extractor() { - let doc = extract_document(&DocumentSource { - path: Path::new("scan.png").into(), - format_hint: Some("ocr".into()), - }); - assert_eq!(doc.status, "failed"); - assert!(doc.missing.contains(&"full_document".into())); - assert!(doc.diagnostics.iter().any(|d| d.contains("ocr") || d.contains("extractor"))); - } -} diff --git a/src/embedded_lib.rs b/src/embedded_lib.rs deleted file mode 100755 index e46e703..0000000 --- a/src/embedded_lib.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! Official `lib/*.mq.md` baked into the binary (fallback when disk `lib/` is absent). - -use include_dir::{include_dir, Dir}; - -static LIB: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/lib"); - -/// Read `lib/` from the embedded tree (e.g. `text.mq.md`). -pub fn read_file(remainder: &str) -> Option { - let key = remainder.replace('\\', "/"); - LIB.get_file(&key) - .and_then(|f| f.contents_utf8().map(|s| s.to_string())) -} - -pub fn has_file(remainder: &str) -> bool { - let key = remainder.replace('\\', "/"); - LIB.get_file(&key).is_some() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn embedded_has_core_libs() { - assert!(has_file("text.mq.md")); - assert!(has_file("subtask.mq.md")); - assert!(has_file("writeback.mq.md")); - assert!(read_file("math.mq.md") - .unwrap() - .contains("host_math_add")); - } -} diff --git a/src/ext_cli.rs b/src/ext_cli.rs deleted file mode 100755 index 5266036..0000000 --- a/src/ext_cli.rs +++ /dev/null @@ -1,691 +0,0 @@ -//! Official extension installer (`marqdo ext list|add|remove`). - -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; - -use anyhow::{bail, Context, Result}; - -/// Official extension catalog entry. -#[derive(Debug, Clone)] -pub struct ExtPackage { - pub id: &'static str, - pub description: &'static str, - /// Files relative to a source `ext/` directory (UTF-8 paths). - pub mq_files: &'static [&'static str], - /// If set, also install native plugin named by [`native_lib_filename`]. - pub native_crate: Option<&'static str>, -} - -pub const CATALOG: &[ExtPackage] = &[ - ExtPackage { - id: "engineering", - description: "Native process, authenticated service and archive boundaries for executable handbooks", - mq_files: &["engineering/index.mq.md", "engineering/索引.mq.md"], - native_crate: Some("marqdo_plugin_engineering"), - }, - ExtPackage { - id: "llm", - description: "OpenAI-compatible chat object (ext/ai/llm)", - mq_files: &[ - "ai/index.mq.md", - "ai/索引.mq.md", - "ai/llm/index.mq.md", - "ai/llm.mq.md", - "ai/大模型.mq.md", - "ai/llm/openai.mq.md", - "ai/llm/ollama.mq.md", - ], - native_crate: Some("marqdo_plugin_llm"), - }, - ExtPackage { - id: "agent", - description: "Agent development framework (ext/ai/agent)", - mq_files: &[ - "ai/agent.mq.md", - "ai/智能体.mq.md", - "ai/sandbox.mq.md", - "ai/沙盒.mq.md", - "ai/policies/step-route.mq.md", - ], - native_crate: Some("marqdo_plugin_agent"), - }, - ExtPackage { - id: "web", - description: "Dynamic website toolkit (ext/web) — Document/Endpoint + layout skill", - mq_files: &[ - "data/index.mq.md", - "data/cache.mq.md", - "data/db.mq.md", - "data/form.mq.md", - "data/表单.mq.md", - "data/admin.mq.md", - "data/后台.mq.md", - "data/view.mq.md", - "data/视图.mq.md", - "data/api.mq.md", - "data/storage.mq.md", - "security/index.mq.md", - "security/auth.mq.md", - "security/鉴权.mq.md", - "security/tenant.mq.md", - "security/rbac.mq.md", - "security/oidc.mq.md", - "net/index.mq.md", - "net/http.mq.md", - "net/url.mq.md", - "net/websocket.mq.md", - "net/实时.mq.md", - "web/index.mq.md", - "web/web.mq.md", - "web/head.mq.md", - "web/页头.mq.md", - "web/网页.mq.md", - "web/_capability/index.mq.md", - "web/page/index.mq.md", - "web/route/index.mq.md", - "web/component/index.mq.md", - "web/dom/index.mq.md", - "web/client/index.mq.md", - "web/layout/index.mq.md", - "web/布局/索引.mq.md", - "web/网页/索引.mq.md", - "web/网页/页面/索引.mq.md", - "web/网页/路由/索引.mq.md", - "web/网页/组件/索引.mq.md", - "web/网页/文档对象模型/索引.mq.md", - "web/网页/客户端/索引.mq.md", - "web/网页/能力/索引.mq.md", - ], - native_crate: Some("marqdo_plugin_web"), - }, - ExtPackage { - id: "quantum", - description: "Quantum circuit simulator (ext/quantum) — gates/state vector", - mq_files: &[ - "quantum/index.mq.md", - "quantum/_capability/index.mq.md", - "quantum/circuit/index.mq.md", - "quantum/gate/index.mq.md", - "quantum/simulate/index.mq.md", - "quantum/state/index.mq.md", - "quantum/density/index.mq.md", - "quantum/viz/index.mq.md", - "quantum/量子/索引.mq.md", - "quantum/量子/能力/索引.mq.md", - "quantum/量子/电路/索引.mq.md", - "quantum/量子/门/索引.mq.md", - "quantum/量子/模拟/索引.mq.md", - "quantum/量子/态/索引.mq.md", - "quantum/量子/密度/索引.mq.md", - "quantum/量子/可视化/索引.mq.md", - ], - native_crate: Some("marqdo_plugin_quantum"), - }, - ExtPackage { - id: "linalg", - description: "Formula-first linear algebra (ext/linalg) — MatExpr simplify/display", - mq_files: &[ - "linalg/index.mq.md", - "linalg/索引.mq.md", - "linalg/linalg.mq.md", - "linalg/线性代数.mq.md", - ], - native_crate: Some("marqdo_plugin_linalg"), - }, -]; - -pub fn find_package(id: &str) -> Option<&'static ExtPackage> { - let id = id.trim(); - CATALOG.iter().find(|p| p.id == id) -} - -/// Default install root: `MARQDO_EXT` if set, else `~/.marqdo/ext`. -pub fn install_root() -> Result { - if let Ok(h) = env::var("MARQDO_EXT") { - let p = PathBuf::from(h); - if !p.as_os_str().is_empty() { - return Ok(p); - } - } - Ok(default_user_ext_dir()) -} - -pub fn default_user_ext_dir() -> PathBuf { - dirs_next_home() - .unwrap_or_else(|| PathBuf::from(".")) - .join(".marqdo") - .join("ext") -} - -fn dirs_next_home() -> Option { - env::var_os("USERPROFILE") - .or_else(|| env::var_os("HOME")) - .map(PathBuf::from) -} - -/// Trusted roots for native plugins (sandbox bypass for `host_plugin_load`). -pub fn trusted_plugin_roots() -> Vec { - let mut roots = Vec::new(); - if let Ok(h) = env::var("MARQDO_EXT") { - roots.push(PathBuf::from(h)); - } - roots.push(default_user_ext_dir()); - if let Ok(exe) = env::current_exe() { - if let Some(dir) = exe.parent() { - roots.push(dir.join("ext")); - } - } - roots -} - -pub fn native_short_name(crate_or_id: &str) -> &str { - match crate_or_id { - "marqdo_plugin_agent" | "agent" => "agent", - "marqdo_plugin_web" | "web" => "web", - "marqdo_plugin_llm" | "llm" => "llm", - "marqdo_plugin_quantum" | "quantum" => "quantum", - "marqdo_plugin_linalg" | "linalg" => "linalg", - "marqdo_plugin_engineering" | "engineering" => "engineering", - other => other, - } -} - -pub fn native_lib_filename(short: &str) -> String { - let short = native_short_name(short); - if cfg!(windows) { - format!("{short}.dll") - } else if cfg!(target_os = "macos") { - format!("lib{short}.dylib") - } else { - format!("lib{short}.so") - } -} - -pub fn native_env_var(short: &str) -> &'static str { - match native_short_name(short) { - "web" => "MARQDO_WEB_PLUGIN", - "llm" => "MARQDO_LLM_PLUGIN", - "quantum" => "MARQDO_QUANTUM_PLUGIN", - "linalg" => "MARQDO_LINALG_PLUGIN", - "engineering" => "MARQDO_ENGINEERING_PLUGIN", - _ => "MARQDO_AGENT_PLUGIN", - } -} - -pub fn is_installed(root: &Path, pkg: &ExtPackage) -> bool { - pkg.mq_files - .iter() - .all(|f| root.join(f).is_file()) -} - -pub fn list_ext() -> Result<()> { - let root = install_root()?; - println!("Install root: {}", root.display()); - println!(); - println!( - "{:<10} {:<8} {}", - "ID", "STATUS", "DESCRIPTION" - ); - println!("{:-<10} {:-<8} {:-<40}", "", "", ""); - for pkg in CATALOG { - let status = if is_installed(&root, pkg) { - "yes" - } else { - "no" - }; - println!("{:<10} {:<8} {}", pkg.id, status, pkg.description); - } - Ok(()) -} - -/// Directories that may contain source `ext/*.mq.md` for `add` (dev / release layout). -pub fn source_ext_roots() -> Vec { - let mut roots = Vec::new(); - if let Ok(h) = env::var("MARQDO_EXT_SOURCE") { - roots.push(PathBuf::from(h)); - } - if let Ok(cwd) = env::current_dir() { - roots.push(cwd.join("ext")); - // cargo test / run from repo root - roots.push(cwd.join("..").join("ext")); - } - if let Ok(exe) = env::current_exe() { - if let Some(dir) = exe.parent() { - roots.push(dir.join("ext")); - roots.push(dir.join("..").join("ext")); - roots.push(dir.join("..").join("..").join("ext")); - roots.push(dir.join("..").join("..").join("..").join("ext")); - // target/debug → repo ext - roots.push(dir.join("..").join("..").join("..").join("ext")); - } - } - roots -} - -fn find_source_file(name: &str) -> Result { - for root in source_ext_roots() { - let p = root.join(name); - if p.is_file() { - return Ok(p); - } - } - #[cfg(feature = "net-host")] - { - if crate::ext_fetch::downloads_enabled() { - match crate::ext_fetch::ensure_ext_source_tree() { - Ok(root) => { - let p = root.join(name); - if p.is_file() { - return Ok(p); - } - } - Err(e) => { - eprintln!("note: could not download ext sources: {e:#}"); - } - } - } - } - bail!( - "cannot find source `{name}` for install (set MARQDO_EXT_SOURCE to an ext/ directory, run from the Marqdo repo, or use a release that publishes marqdo-*-ext.zip)" - ); -} - -fn find_native_plugin(short: &str) -> Result { - let short = native_short_name(short); - let name = native_lib_filename(short); - let env_key = native_env_var(short); - let mut candidates = Vec::new(); - if let Ok(p) = env::var(env_key) { - let p = PathBuf::from(p); - if p.is_file() { - return Ok(p); - } - candidates.push(p); - } - if let Ok(h) = env::var("MARQDO_EXT_SOURCE") { - let base = PathBuf::from(h); - candidates.push(base.join("native").join(&name)); - candidates.push(base.join(&name)); - // MARQDO_EXT_SOURCE often points at repo `ext/`; native libs live in sibling target/. - if let Some(repo) = base.parent() { - candidates.push(repo.join("target").join("debug").join(&name)); - candidates.push(repo.join("target").join("release").join(&name)); - } - } - // Honor CARGO_TARGET_DIR (sandbox / custom target roots) before cwd/target. - if let Ok(td) = env::var("CARGO_TARGET_DIR") { - let td = PathBuf::from(td); - candidates.push(td.join("debug").join(&name)); - candidates.push(td.join("release").join(&name)); - } - if let Ok(cwd) = env::current_dir() { - // Go web plugin (ext-web-go-rewrite): prefer plugins/web/build over cargo target/ - // so `cargo build -p marqdo_plugin_web` (rust archive) does not mask the Go .so. - if short == "web" { - let mut dir = cwd.clone(); - for _ in 0..6 { - candidates.push(dir.join("plugins").join("web").join("build").join(&name)); - if !dir.pop() { - break; - } - } - } - candidates.push(cwd.join("target").join("debug").join(&name)); - candidates.push(cwd.join("target").join("release").join(&name)); - candidates.push(cwd.join("ext").join("native").join(&name)); - // Walk up looking for a Cargo workspace target/ (run from a subdir). - let mut dir = cwd.clone(); - for _ in 0..6 { - candidates.push(dir.join("target").join("debug").join(&name)); - candidates.push(dir.join("target").join("release").join(&name)); - if short == "web" { - candidates.push(dir.join("plugins").join("web").join("build").join(&name)); - } - if !dir.pop() { - break; - } - } - } - if let Ok(exe) = env::current_exe() { - if let Some(dir) = exe.parent() { - candidates.push(dir.join("ext").join("native").join(&name)); - // Same directory as the marqdo binary (typical: target/debug/). - candidates.push(dir.join(&name)); - // target/debug/deps → target/debug - candidates.push(dir.join("..").join(&name)); - candidates.push(dir.join("..").join("release").join(&name)); - } - } - for p in &candidates { - if p.is_file() { - return Ok(p.clone()); - } - } - bail!( - "cannot find native plugin `{name}` (for `web`: `./scripts/build-web-plugin.sh`; \ - else `cargo build -p marqdo_plugin_{short}`; or set {env_key})" - ) -} - -/// Walk from cwd (and common anchors) to find the Marqdo repo root that contains -/// `scripts/build-web-plugin.sh`. -fn find_web_plugin_build_script() -> Option { - let mut starts = Vec::new(); - if let Ok(cwd) = env::current_dir() { - starts.push(cwd); - } - if let Ok(exe) = env::current_exe() { - if let Some(dir) = exe.parent() { - starts.push(dir.to_path_buf()); - } - } - for start in starts { - let mut dir = start; - for _ in 0..8 { - let script = dir.join("scripts").join("build-web-plugin.sh"); - if script.is_file() { - return Some(script); - } - if !dir.pop() { - break; - } - } - } - None -} - -fn build_go_web_plugin() -> Result { - let script = find_web_plugin_build_script().ok_or_else(|| { - anyhow::anyhow!( - "cannot locate scripts/build-web-plugin.sh (run from the Marqdo repo, \ - or set {} to a built libweb path)", - native_env_var("web") - ) - })?; - let root = script - .parent() - .and_then(|p| p.parent()) - .ok_or_else(|| anyhow::anyhow!("invalid build-web-plugin.sh path"))?; - println!("native plugin for `web` not found; building Go libweb via scripts/build-web-plugin.sh…"); - let status = std::process::Command::new("bash") - .arg(&script) - .current_dir(root) - .status() - .with_context(|| format!("spawn {}", script.display()))?; - if !status.success() { - bail!( - "scripts/build-web-plugin.sh failed (status {status}); \ - install Go 1.22+ with cgo, or set {} to a built libweb path", - native_env_var("web") - ); - } - find_native_plugin("web").with_context(|| { - format!( - "built Go libweb but still cannot find {}; set {} to the .so/.dll path", - native_lib_filename("web"), - native_env_var("web") - ) - }) -} - -/// Locate a built native plugin: local artifact → GitHub Release prebuild → optional build. -fn ensure_native_plugin(crate_name: &str) -> Result { - let short = native_short_name(crate_name); - if let Ok(p) = find_native_plugin(short) { - return Ok(p); - } - let lib_name = native_lib_filename(short); - - #[cfg(feature = "net-host")] - { - match crate::ext_fetch::download_native_plugin(short, &lib_name) { - Ok(p) => return Ok(p), - Err(e) => { - eprintln!("note: prebuilt native download skipped/failed: {e:#}"); - } - } - } - - // Official web plugin is Go (W-G13); do not cargo-build the Rust archive. - if short == "web" { - return build_go_web_plugin(); - } - - #[cfg(feature = "net-host")] - let have_cargo = crate::ext_fetch::cargo_available(); - #[cfg(not(feature = "net-host"))] - let have_cargo = true; - - if have_cargo { - println!( - "native plugin for `{short}` not found; building `{crate_name}` (debug)…" - ); - let status = std::process::Command::new("cargo") - .args(["build", "-p", crate_name]) - .status() - .with_context(|| format!("spawn cargo build -p {crate_name}"))?; - if !status.success() { - bail!( - "cargo build -p {crate_name} failed (status {status}); \ - install a prebuilt release asset or build the plugin then re-run `marqdo ext add {short}`" - ); - } - return find_native_plugin(short).with_context(|| { - format!( - "built `{crate_name}` but still cannot find {}; set {} to the .so/.dll path", - lib_name, - native_env_var(short) - ) - }); - } - - bail!( - "cannot find native plugin `{lib_name}` and Rust/cargo is not available. \ - Install Marqdo from a GitHub Release that includes `marqdo-*-native-*.zip`, \ - or set {} to a built plugin path.", - native_env_var(short) - ) -} - -fn same_path(a: &Path, b: &Path) -> bool { - match (a.canonicalize(), b.canonicalize()) { - (Ok(x), Ok(y)) => x == y, - _ => a == b, - } -} - -/// True when `install_root` is also a source `ext/` tree (dev layout). Copying -/// there truncates `.mq.md` on Linux (`fs::copy` same-file) and drops `.plugin` -/// junk into the repo. -fn install_root_is_source_tree(root: &Path) -> bool { - source_ext_roots().iter().any(|s| same_path(root, s)) -} - -pub fn add_ext(id: &str) -> Result<()> { - let pkg = find_package(id).with_context(|| { - format!( - "unknown extension `{id}` (official: {})", - CATALOG - .iter() - .map(|p| p.id) - .collect::>() - .join(", ") - ) - })?; - let root = install_root()?; - if install_root_is_source_tree(&root) { - bail!( - "refusing to install into extension *source* tree {} \ -(set MARQDO_EXT to an install directory such as ~/.marqdo/ext, \ -and use MARQDO_EXT_SOURCE for the repo ext/ when needed)", - root.display() - ); - } - fs::create_dir_all(&root) - .with_context(|| format!("create install root {}", root.display()))?; - - // Preflight native binary *before* copying .mq.md so a missing .so does not - // leave a half-installed tree that fails at `plugin.native_path` / load time. - let native_src = if let Some(crate_name) = pkg.native_crate { - Some(ensure_native_plugin(crate_name)?) - } else { - None - }; - - for f in pkg.mq_files { - let src = find_source_file(f)?; - let dest = root.join(f); - if same_path(&src, &dest) { - bail!( - "refusing same-file copy {} (install root overlaps source)", - src.display() - ); - } - if let Some(parent) = dest.parent() { - fs::create_dir_all(parent) - .with_context(|| format!("create {}", parent.display()))?; - } - fs::copy(&src, &dest) - .with_context(|| format!("copy {} → {}", src.display(), dest.display()))?; - println!("installed {}", dest.display()); - } - - if let (Some(crate_name), Some(src)) = (pkg.native_crate, native_src) { - let short = native_short_name(crate_name); - let lib_name = native_lib_filename(short); - let native_dir = root.join("native"); - fs::create_dir_all(&native_dir)?; - let dest = native_dir.join(&lib_name); - fs::copy(&src, &dest) - .with_context(|| format!("copy {} → {}", src.display(), dest.display()))?; - println!("installed {}", dest.display()); - // Absolute path hint for loaders / env - let abs = dest - .canonicalize() - .unwrap_or_else(|_| dest.clone()); - let hint = root.join(format!("{short}.plugin")); - fs::write(&hint, abs.to_string_lossy().as_bytes())?; - println!("wrote {}", hint.display()); - println!( - "hint: `plugin.native_path name={short}` resolves via {}; or set {}={}", - dest.display(), - native_env_var(short), - abs.display() - ); - } - - if env::var_os("MARQDO_EXT").is_none() { - println!( - "hint: imports resolve via {} automatically; or set MARQDO_EXT to this directory", - root.display() - ); - } - Ok(()) -} - -pub fn remove_ext(id: &str) -> Result<()> { - let pkg = find_package(id).with_context(|| format!("unknown extension `{id}`"))?; - let root = install_root()?; - let mut removed = 0usize; - for f in pkg.mq_files { - let dest = root.join(f); - if dest.is_file() { - fs::remove_file(&dest) - .with_context(|| format!("remove {}", dest.display()))?; - println!("removed {}", dest.display()); - removed += 1; - } - } - if let Some(crate_name) = pkg.native_crate { - let short = native_short_name(crate_name); - let dest = root.join("native").join(native_lib_filename(short)); - if dest.is_file() { - fs::remove_file(&dest)?; - println!("removed {}", dest.display()); - removed += 1; - } - let hint = root.join(format!("{short}.plugin")); - if hint.is_file() { - fs::remove_file(&hint)?; - removed += 1; - } - } - if removed == 0 { - println!("nothing to remove for `{id}` under {}", root.display()); - } - Ok(()) -} - -/// Resolve installed native plugin path for `name` (`agent`, `web`, …). -/// Also falls back to cargo `target/{debug,release}` and Go `plugins/web/build`. -/// -/// `MARQDO_*_PLUGIN` env overrides installed `~/.marqdo/ext` so developers can -/// point at a freshly built plugin path. -pub fn installed_native_path(name: &str) -> Option { - let short = native_short_name(name); - if !CATALOG.iter().any(|package| package.id == short && package.native_crate.is_some()) { - return None; - } - let lib_name = native_lib_filename(short); - if let Ok(p) = env::var(native_env_var(short)) { - let p = PathBuf::from(p); - if p.is_file() { - return Some(p); - } - } - for root in trusted_plugin_roots() { - let hint = root.join(format!("{short}.plugin")); - if let Ok(s) = fs::read_to_string(&hint) { - let p = PathBuf::from(s.trim()); - if p.is_file() { - return Some(p); - } - } - let p = root.join("native").join(&lib_name); - if p.is_file() { - return Some(p); - } - } - find_native_plugin(short).ok() -} - -pub fn path_is_trusted_plugin(path: &Path) -> bool { - let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); - for root in trusted_plugin_roots() { - let root = root.canonicalize().unwrap_or(root); - if crate::host::path_under_root(&path, &root) { - return true; - } - let native = root.join("native"); - let native = native.canonicalize().unwrap_or(native); - if crate::host::path_under_root(&path, &native) { - return true; - } - } - for key in [ - "MARQDO_AGENT_PLUGIN", - "MARQDO_WEB_PLUGIN", - "MARQDO_LLM_PLUGIN", - "MARQDO_QUANTUM_PLUGIN", - "MARQDO_LINALG_PLUGIN", - "MARQDO_ENGINEERING_PLUGIN", - ] { - if let Ok(p) = env::var(key) { - let p = PathBuf::from(p); - let p = p.canonicalize().unwrap_or(p); - if p == path { - return true; - } - } - } - for short in CATALOG.iter().filter_map(|p| p.native_crate).map(native_short_name) { - if let Ok(found) = find_native_plugin(short) { - let found = found.canonicalize().unwrap_or(found); - if found == path { - return true; - } - } - } - false -} diff --git a/src/ext_fetch.rs b/src/ext_fetch.rs deleted file mode 100755 index 71cfc54..0000000 --- a/src/ext_fetch.rs +++ /dev/null @@ -1,447 +0,0 @@ -//! Download official `ext/` L1 sources and native plugins. -//! -//! Enables `marqdo ext add web` without a local Rust toolchain or repo checkout. -//! -//! Disable with `MARQDO_EXT_NO_DOWNLOAD=1`. Override pack SemVer with -//! `MARQDO_EXT_VERSION` (independent of CLI `CARGO_PKG_VERSION`). -//! -//! Download order (first success wins): -//! 1. `MARQDO_EXT_DOWNLOAD_BASE` (optional override) -//! 2. **CDN** `https://ext.marqdo.com` (Cloudflare R2 custom domain) -//! 3. GitHub Releases `github.com/cflmy/marqdo` -//! 4. GitHub via reverse proxy `proxy.cflmy.top` - -use std::env; -use std::fs::{self, File}; -use std::io::{self, Read, Write}; -use std::path::{Path, PathBuf}; -use std::sync::OnceLock; -use std::time::Duration; - -use anyhow::{bail, Context, Result}; - -const REPO: &str = "cflmy/marqdo"; -/// Public CDN for extension packs (R2 bucket `marqdo`, custom domain). -pub const EXT_CDN_BASE: &str = "https://ext.marqdo.com"; -/// HTTPS reverse proxy used when github.com is slow or blocked. -const GITHUB_MIRROR_PREFIX: &str = "https://proxy.cflmy.top/github.com"; -/// Packaged with the repo; may diverge from CLI SemVer for ext-only releases. -const EMBEDDED_EXT_VERSION: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/ext/VERSION")); - -pub fn downloads_enabled() -> bool { - match env::var("MARQDO_EXT_NO_DOWNLOAD") { - Ok(v) => { - let v = v.trim(); - !(v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes")) - } - Err(_) => true, - } -} - -fn normalize_semver(raw: &str) -> Option { - let v = raw.trim().trim_start_matches('v').trim(); - if v.is_empty() { - return None; - } - // one line only - let v = v.lines().next()?.trim().trim_start_matches('v').trim(); - if v.is_empty() { - return None; - } - Some(v.to_string()) -} - -/// SemVer of the **extension pack** (may differ from CLI version). -/// -/// Resolution order: -/// 1. `MARQDO_EXT_VERSION` -/// 2. CDN `GET {EXT_CDN}/latest/VERSION` (short timeout; skipped if downloads disabled) -/// 3. Embedded `ext/VERSION` at build time -/// 4. CLI `CARGO_PKG_VERSION` -pub fn release_version() -> String { - if let Ok(v) = env::var("MARQDO_EXT_VERSION") { - if let Some(n) = normalize_semver(&v) { - return n; - } - } - if downloads_enabled() { - if let Some(n) = fetch_cdn_latest_version() { - return n; - } - } - if let Some(n) = normalize_semver(EMBEDDED_EXT_VERSION) { - return n; - } - env!("CARGO_PKG_VERSION").to_string() -} - -fn fetch_cdn_latest_version() -> Option { - static CACHED: OnceLock> = OnceLock::new(); - CACHED - .get_or_init(|| { - let base = env::var("MARQDO_EXT_CDN") - .ok() - .map(|s| s.trim().trim_end_matches('/').to_string()) - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| EXT_CDN_BASE.to_string()); - let url = format!("{base}/latest/VERSION"); - let agent = ureq::AgentBuilder::new() - .timeout_connect(Duration::from_secs(5)) - .timeout_read(Duration::from_secs(10)) - .user_agent(&user_agent()) - .build(); - let resp = agent.get(&url).call().ok()?; - if !(200..300).contains(&resp.status()) { - return None; - } - let mut body = String::new(); - resp.into_reader().read_to_string(&mut body).ok()?; - normalize_semver(&body) - }) - .clone() -} - -pub fn host_target_triple() -> Option<&'static str> { - if cfg!(all(target_os = "windows", target_arch = "x86_64")) { - Some("x86_64-pc-windows-msvc") - } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) { - Some("x86_64-unknown-linux-gnu") - } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) { - Some("aarch64-apple-darwin") - } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) { - Some("x86_64-apple-darwin") - } else { - None - } -} - -fn cache_root() -> Result { - let home = env::var_os("USERPROFILE") - .or_else(|| env::var_os("HOME")) - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(".")); - let dir = home.join(".marqdo").join("cache"); - fs::create_dir_all(&dir)?; - Ok(dir) -} - -fn user_agent() -> String { - format!("marqdo/{}", env!("CARGO_PKG_VERSION")) -} - -fn http_agent() -> ureq::Agent { - ureq::AgentBuilder::new() - .timeout_connect(Duration::from_secs(20)) - .timeout_read(Duration::from_secs(600)) - .user_agent(&user_agent()) - .build() -} - -fn cdn_base() -> String { - env::var("MARQDO_EXT_CDN") - .ok() - .map(|s| s.trim().trim_end_matches('/').to_string()) - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| EXT_CDN_BASE.to_string()) -} - -/// Candidate download URLs for a release asset. -/// -/// Order: optional `MARQDO_EXT_DOWNLOAD_BASE` → CDN → GitHub → GitHub proxy. -pub fn release_asset_urls(ver: &str, filename: &str) -> Vec { - let mut urls = Vec::new(); - if let Ok(base) = env::var("MARQDO_EXT_DOWNLOAD_BASE") { - let base = base.trim().trim_end_matches('/'); - if !base.is_empty() { - urls.push(format!("{base}/{REPO}/releases/download/v{ver}/{filename}")); - urls.push(format!("{base}/releases/download/v{ver}/{filename}")); - urls.push(format!("{base}/v{ver}/{filename}")); - urls.push(format!("{base}/{filename}")); - } - } - let cdn = cdn_base(); - // Preferred public layout on ext.marqdo.com / R2 - urls.push(format!("{cdn}/v{ver}/{filename}")); - urls.push(format!("{cdn}/releases/v{ver}/{filename}")); - urls.push(format!("{cdn}/{filename}")); - urls.push(format!( - "https://github.com/{REPO}/releases/download/v{ver}/{filename}" - )); - urls.push(format!( - "{GITHUB_MIRROR_PREFIX}/{REPO}/releases/download/v{ver}/{filename}" - )); - let mut seen = std::collections::HashSet::new(); - urls.into_iter().filter(|u| seen.insert(u.clone())).collect() -} - -fn download_to_file(url: &str, dest: &Path) -> Result<()> { - if let Some(parent) = dest.parent() { - fs::create_dir_all(parent)?; - } - let tmp = dest.with_extension("download-tmp"); - let resp = http_agent() - .get(url) - .set("Accept", "application/octet-stream") - .call() - .with_context(|| format!("GET {url}"))?; - if !(200..300).contains(&resp.status()) { - bail!("download {url} returned HTTP {}", resp.status()); - } - let mut reader = resp.into_reader(); - let mut out = File::create(&tmp).with_context(|| format!("create {}", tmp.display()))?; - io::copy(&mut reader, &mut out).with_context(|| format!("write {}", tmp.display()))?; - out.flush()?; - drop(out); - if dest.exists() { - let _ = fs::remove_file(dest); - } - fs::rename(&tmp, dest).with_context(|| format!("rename {}", dest.display()))?; - Ok(()) -} - -fn download_first_ok(urls: &[String], dest: &Path) -> Result<()> { - let mut errors: Vec = Vec::new(); - for (i, url) in urls.iter().enumerate() { - if i == 0 { - println!("downloading ({url})…"); - } else { - println!("retry ({url})…"); - } - match download_to_file(url, dest) { - Ok(()) => return Ok(()), - Err(e) => { - eprintln!("note: {e:#}"); - errors.push(format!("{url} → {e:#}")); - let _ = fs::remove_file(dest.with_extension("download-tmp")); - } - } - } - bail!( - "all download mirrors failed for {}:\n - {}", - dest.file_name().and_then(|s| s.to_str()).unwrap_or("asset"), - errors.join("\n - ") - ) -} - -fn extract_zip(zip_path: &Path, dest_dir: &Path) -> Result<()> { - fs::create_dir_all(dest_dir)?; - let file = File::open(zip_path).with_context(|| format!("open {}", zip_path.display()))?; - let mut archive = zip::ZipArchive::new(file) - .with_context(|| format!("read zip {}", zip_path.display()))?; - for i in 0..archive.len() { - let mut entry = archive - .by_index(i) - .with_context(|| format!("zip entry {i}"))?; - let name = entry.name().to_string(); - if name.is_empty() { - continue; - } - if Path::new(&name) - .components() - .any(|c| matches!(c, std::path::Component::ParentDir)) - { - bail!("refusing zip entry with ..: {name}"); - } - let out_path = dest_dir.join(Path::new(&name)); - if entry.is_dir() || name.ends_with('/') { - fs::create_dir_all(&out_path)?; - continue; - } - if let Some(parent) = out_path.parent() { - fs::create_dir_all(parent)?; - } - let mut outfile = - File::create(&out_path).with_context(|| format!("create {}", out_path.display()))?; - io::copy(&mut entry, &mut outfile) - .with_context(|| format!("extract {name}"))?; - } - Ok(()) -} - -/// Ensure L1 `ext/` tree is available (repo checkout or downloaded Release zip). -/// Returns a directory that contains `web/web.mq.md`, `ai/…`, etc. -pub fn ensure_ext_source_tree() -> Result { - let ver = release_version(); - let cache = cache_root()?.join(format!("ext-src-v{ver}")); - let marker = cache.join("web").join("web.mq.md"); - if marker.is_file() { - return Ok(cache); - } - let nested = cache.join("ext").join("web").join("web.mq.md"); - if nested.is_file() { - return Ok(cache.join("ext")); - } - if !downloads_enabled() { - bail!("extension sources not found and downloads disabled (MARQDO_EXT_NO_DOWNLOAD)"); - } - let zip_name = format!("marqdo-{ver}-ext.zip"); - let urls = release_asset_urls(&ver, &zip_name); - let zip_path = cache_root()?.join(&zip_name); - download_first_ok(&urls, &zip_path)?; - let stage = cache_root()?.join(format!("ext-src-v{ver}-extract")); - if stage.exists() { - let _ = fs::remove_dir_all(&stage); - } - extract_zip(&zip_path, &stage)?; - let src = if stage.join("ext").join("web").join("web.mq.md").is_file() { - stage.join("ext") - } else if stage.join("web").join("web.mq.md").is_file() { - stage.clone() - } else { - bail!( - "downloaded {zip_name} but could not find web/web.mq.md inside; check release assets" - ); - }; - if cache.exists() { - let _ = fs::remove_dir_all(&cache); - } - copy_dir_recursive(&src, &cache)?; - let _ = fs::remove_dir_all(&stage); - if !cache.join("web").join("web.mq.md").is_file() { - bail!("failed to cache ext sources under {}", cache.display()); - } - println!("cached ext sources at {}", cache.display()); - Ok(cache) -} - -fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<()> { - fs::create_dir_all(dest)?; - for entry in fs::read_dir(src).with_context(|| format!("read {}", src.display()))? { - let entry = entry?; - let ty = entry.file_type()?; - let to = dest.join(entry.file_name()); - if ty.is_dir() { - copy_dir_recursive(&entry.path(), &to)?; - } else if ty.is_file() { - if let Some(parent) = to.parent() { - fs::create_dir_all(parent)?; - } - fs::copy(entry.path(), &to) - .with_context(|| format!("copy {} → {}", entry.path().display(), to.display()))?; - } - } - Ok(()) -} - -/// Download prebuilt native plugins zip for this host; return path to `lib` file for `short`. -pub fn download_native_plugin(short: &str, lib_name: &str) -> Result { - if !downloads_enabled() { - bail!("native plugin not found and downloads disabled (MARQDO_EXT_NO_DOWNLOAD)"); - } - let Some(triple) = host_target_triple() else { - bail!( - "no prebuilt native plugins for this platform; install Rust and run `cargo build -p marqdo_plugin_{short}`" - ); - }; - let ver = release_version(); - let zip_name = format!("marqdo-{ver}-native-{triple}.zip"); - let urls = release_asset_urls(&ver, &zip_name); - let cache = cache_root()?.join(format!("native-v{ver}-{triple}")); - let lib_in_cache = cache.join("native").join(lib_name); - if lib_in_cache.is_file() { - return Ok(lib_in_cache); - } - let flat = cache.join(lib_name); - if flat.is_file() { - return Ok(flat); - } - let zip_path = cache_root()?.join(&zip_name); - download_first_ok(&urls, &zip_path).with_context(|| { - format!( - "failed to download prebuilt plugins for {triple}. \ - Set MARQDO_EXT_CDN / MARQDO_EXT_DOWNLOAD_BASE, build locally, \ - or check https://github.com/{REPO}/releases and https://ext.marqdo.com/v{ver}/" - ) - })?; - if cache.exists() { - let _ = fs::remove_dir_all(&cache); - } - fs::create_dir_all(&cache)?; - extract_zip(&zip_path, &cache)?; - if lib_in_cache.is_file() { - println!("cached {}", lib_in_cache.display()); - return Ok(lib_in_cache); - } - if flat.is_file() { - return Ok(flat); - } - if let Some(found) = find_named_file(&cache, lib_name)? { - return Ok(found); - } - bail!( - "downloaded {zip_name} but missing {lib_name}; expected native/{lib_name} in the archive" - ) -} - -fn find_named_file(root: &Path, name: &str) -> Result> { - fn walk(dir: &Path, name: &str, out: &mut Option) -> Result<()> { - if out.is_some() { - return Ok(()); - } - for entry in fs::read_dir(dir)? { - let entry = entry?; - let p = entry.path(); - if entry.file_type()?.is_dir() { - walk(&p, name, out)?; - } else if entry.file_name() == name { - *out = Some(p); - } - } - Ok(()) - } - let mut found = None; - walk(root, name, &mut found)?; - Ok(found) -} - -pub fn cargo_available() -> bool { - std::process::Command::new("cargo") - .arg("-V") - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .status() - .map(|s| s.success()) - .unwrap_or(false) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn asset_urls_prefer_cdn_then_github_then_proxy() { - let u = release_asset_urls("1.0.2", "marqdo-1.0.2-ext.zip"); - assert!(u[0].starts_with("https://ext.marqdo.com/")); - assert!(u.iter().any(|x| x.contains("github.com/cflmy/marqdo"))); - assert!(u - .iter() - .any(|x| x.contains("proxy.cflmy.top/github.com/cflmy/marqdo"))); - let gh = u - .iter() - .position(|x| x.starts_with("https://github.com/")) - .unwrap(); - let proxy = u - .iter() - .position(|x| x.contains("proxy.cflmy.top")) - .unwrap(); - assert!(gh < proxy); - } - - #[test] - fn embedded_ext_version_parses() { - assert!(normalize_semver(EMBEDDED_EXT_VERSION).is_some()); - } - - #[test] - fn triple_known_on_ci_hosts() { - let t = host_target_triple(); - if cfg!(any( - all(target_os = "linux", target_arch = "x86_64"), - all(target_os = "windows", target_arch = "x86_64"), - all(target_os = "macos", target_arch = "aarch64"), - all(target_os = "macos", target_arch = "x86_64"), - )) { - assert!(t.is_some()); - } - } -} diff --git a/src/foreign/mod.rs b/src/foreign/mod.rs deleted file mode 100755 index e5ab993..0000000 --- a/src/foreign/mod.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Foreign / code-block helpers (外联). - -pub mod registry; - -pub use registry::{default_argv, default_cmd_display, default_python_argv}; - -/// Shell-like split: whitespace, single/double quotes, backslash escapes. -pub fn split_cmd_line(s: &str) -> Vec { - let mut out = Vec::new(); - let mut cur = String::new(); - let mut quote: Option = None; - let mut chars = s.chars().peekable(); - while let Some(c) = chars.next() { - match quote { - Some(q) => { - if c == q { - quote = None; - } else if c == '\\' && q == '"' { - if let Some(n) = chars.next() { - cur.push(n); - } - } else { - cur.push(c); - } - } - None => { - if c.is_whitespace() { - if !cur.is_empty() { - out.push(std::mem::take(&mut cur)); - } - } else if c == '\'' || c == '"' { - quote = Some(c); - } else if c == '\\' { - if let Some(n) = chars.next() { - cur.push(n); - } - } else { - cur.push(c); - } - } - } - } - if !cur.is_empty() { - out.push(cur); - } - out -} - -/// Parse ```lang … opener → language id (first token). -pub fn fence_lang(opener_trimmed: &str) -> Option { - let rest = opener_trimmed.strip_prefix("```")?; - if rest.is_empty() || rest.chars().all(|c| c == '`') { - return None; - } - let lang = rest.split_whitespace().next()?.to_string(); - if lang.is_empty() { - None - } else { - Some(lang) - } -} - -pub fn is_fence_opener(trimmed: &str) -> bool { - fence_lang(trimmed).is_some() -} - -pub fn is_fence_closer(trimmed: &str) -> bool { - trimmed.starts_with("```") - && trimmed - .chars() - .skip_while(|c| *c == '`') - .all(|c| c.is_whitespace()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fence_lang_python() { - assert_eq!(fence_lang("```python").as_deref(), Some("python")); - assert_eq!(fence_lang("```python name=x").as_deref(), Some("python")); - assert!(fence_lang("```").is_none()); - } -} diff --git a/src/foreign/registry.rs b/src/foreign/registry.rs deleted file mode 100755 index 20c51cd..0000000 --- a/src/foreign/registry.rs +++ /dev/null @@ -1,188 +0,0 @@ -//! Language presets and specs for `lib/foreign` (pure data; no process spawning). -//! -//! The host runner resolves a `LangSpec`, then builds the command. Keeping this -//! module free of `std::process` lets the browser/wasm build share the syntax and -//! preset tables. - -use std::path::PathBuf; - -/// One language's invocation recipe. -#[derive(Debug, Clone, Default)] -pub struct LangSpec { - pub lang: String, - /// Simple interpreter prefix; the script path is appended. - pub argv: Vec, - /// Optional full argv template; supports `{file}`/`{inline}`/… placeholders. - pub template: Option>, - pub ext: Option, - pub env: Vec<(String, String)>, - /// Arguments appended to the executable for `probe` (e.g. `--version`). - pub version_args: Vec, - /// Persistent session bootstrap available. - pub session: bool, - /// Directory for resolving a relative interpreter path (config file dir). - pub base_dir: Option, -} - -impl LangSpec { - fn simple(lang: &str, argv: &[&str], ext: &str, version: &[&str], session: bool) -> Self { - Self { - lang: lang.to_string(), - argv: argv.iter().map(|s| (*s).to_string()).collect(), - template: None, - ext: Some(ext.to_string()), - env: Vec::new(), - version_args: version.iter().map(|s| (*s).to_string()).collect(), - session, - base_dir: None, - } - } - - fn templated(lang: &str, template: &[&str], ext: &str, version: &[&str]) -> Self { - Self { - lang: lang.to_string(), - argv: vec![template[0].to_string()], - template: Some(template.iter().map(|s| (*s).to_string()).collect()), - ext: Some(ext.to_string()), - env: Vec::new(), - version_args: version.iter().map(|s| (*s).to_string()).collect(), - session: false, - base_dir: None, - } - } -} - -pub fn default_python_argv() -> Vec { - #[cfg(windows)] - { - vec!["python".into()] - } - #[cfg(not(windows))] - { - vec!["python3".into()] - } -} - -/// Canonical preset id for a language or alias. Unknown names pass through lowercased. -pub fn canonical(lang: &str) -> String { - let l = lang.to_ascii_lowercase(); - match l.as_str() { - "python3" | "py" => "python".into(), - "javascript" | "js" => "node".into(), - "shell" | "sh" => "bash".into(), - "rscript" => "r".into(), - "pwsh" | "ps1" => "powershell".into(), - "sqlite3" => "sqlite".into(), - "typescript" => "tsx".into(), - _ => l, - } -} - -/// Built-in preset for a language/alias. -pub fn preset_spec(lang: &str) -> Option { - let id = canonical(lang); - Some(match id.as_str() { - "python" => LangSpec { - argv: default_python_argv(), - ..LangSpec::simple("python", &["python3"], "py", &["--version"], true) - }, - "node" => LangSpec::simple("node", &["node"], "js", &["-v"], true), - "deno" => LangSpec::simple("deno", &["deno", "run"], "ts", &["--version"], false), - "bun" => LangSpec::simple("bun", &["bun"], "js", &["--version"], false), - "ruby" => LangSpec::simple("ruby", &["ruby"], "rb", &["--version"], false), - "perl" => LangSpec::simple("perl", &["perl"], "pl", &["--version"], false), - "php" => LangSpec::templated("php", &["php", "-r", "{inline}"], "php", &["--version"]), - "lua" => LangSpec::simple("lua", &["lua"], "lua", &["-v"], false), - "r" => LangSpec::simple("r", &["Rscript"], "R", &["--version"], false), - "julia" => LangSpec::simple("julia", &["julia"], "jl", &["--version"], false), - "go" => LangSpec::templated("go", &["go", "run", "{file}"], "go", &["version"]), - "bash" => LangSpec::simple("bash", &["bash"], "sh", &["--version"], false), - "powershell" => { - #[cfg(windows)] - { - LangSpec::simple("powershell", &["powershell"], "ps1", &["--version"], false) - } - #[cfg(not(windows))] - { - LangSpec::simple("powershell", &["pwsh"], "ps1", &["--version"], false) - } - } - "sqlite" => LangSpec::simple("sqlite", &["sqlite3"], "sql", &["--version"], false), - "tsx" => LangSpec::simple("tsx", &["tsx"], "ts", &["--version"], false), - _ => return None, - }) -} - -/// Sorted preset ids (for `langs`). -pub fn preset_ids() -> Vec { - [ - "python", "node", "deno", "bun", "ruby", "perl", "php", "lua", "r", "julia", "go", - "bash", "powershell", "sqlite", "tsx", - ] - .iter() - .map(|s| (*s).to_string()) - .collect() -} - -/// Display string for the command box (e.g. `python3`, `go run`, `php -r`). -pub fn default_cmd_display(lang: &str) -> String { - match preset_spec(lang) { - Some(spec) => { - if let Some(t) = &spec.template { - let mut parts = Vec::new(); - for x in t { - if x.contains('{') { - break; - } - parts.push(x.clone()); - } - if parts.is_empty() { - lang.to_string() - } else { - parts.join(" ") - } - } else { - spec.argv.join(" ") - } - } - None => lang.to_string(), - } -} - -/// Default argv for v1 compatibility (simple presets only). -pub fn default_argv(lang: &str) -> Option> { - preset_spec(lang).map(|s| s.argv) -} - -/// Session support for a language (based on preset). -pub fn session_supported(lang: &str) -> bool { - preset_spec(lang).map(|s| s.session).unwrap_or(false) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn aliases_canonicalize() { - assert_eq!(canonical("py"), "python"); - assert_eq!(canonical("javascript"), "node"); - assert_eq!(canonical("sh"), "bash"); - assert_eq!(canonical("unknown"), "unknown"); - } - - #[test] - fn presets_cover_docs() { - assert_eq!(preset_ids().len(), 15); - assert!(preset_spec("python").is_some()); - assert!(preset_spec("node").is_some()); - assert!(preset_spec("go").unwrap().template.is_some()); - assert!(preset_spec("php").unwrap().template.is_some()); - } - - #[test] - fn display_uses_template_prefix() { - assert_eq!(default_cmd_display("go"), "go run"); - assert_eq!(default_cmd_display("php"), "php -r"); - } -} diff --git a/src/formula/mod.rs b/src/formula/mod.rs deleted file mode 100755 index 55db744..0000000 --- a/src/formula/mod.rs +++ /dev/null @@ -1,1309 +0,0 @@ -//! High-school formula AST: parse, simplify, diff, eval, solve, plot helpers. - -mod plot; - -pub use plot::{plot_conic_svg, plot_function_svg, plot_points_svg, PlotStyle}; - -use std::collections::HashMap; -use std::fmt; - -/// Expression tree for `Value::Formula`. -#[derive(Debug, Clone, PartialEq)] -pub enum Expr { - Num(f64), - Var(String), - UnaryNeg(Box), - Bin { - op: BinOp, - left: Box, - right: Box, - }, - Call { - name: String, - args: Vec, - }, - /// Matrix from a `$$` fence (LaTeX / `[[…]]`). `source` is for display; `rows` for eval/JSON. - Matrix { - source: String, - rows: Vec>, - }, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum BinOp { - Add, - Sub, - Mul, - Div, - Pow, -} - -impl Expr { - pub fn num(n: f64) -> Self { - Expr::Num(n) - } - - pub fn var(name: impl Into) -> Self { - Expr::Var(name.into()) - } - - pub fn as_display(&self) -> String { - self.fmt_prec(0) - } - - fn fmt_prec(&self, parent_prec: u8) -> String { - match self { - Expr::Num(n) => format_num(*n), - Expr::Var(v) => v.clone(), - Expr::UnaryNeg(e) => { - let inner = e.fmt_prec(3); - let s = format!("-{inner}"); - if parent_prec > 2 { - format!("({s})") - } else { - s - } - } - Expr::Bin { op, left, right } => { - let prec = op.prec(); - let ls = left.fmt_prec(prec); - let rs = right.fmt_prec(if matches!(op, BinOp::Sub | BinOp::Div) { - prec + 1 - } else if matches!(op, BinOp::Pow) { - prec - } else { - prec - }); - let s = format!("{ls}{}{rs}", op.sym()); - if prec < parent_prec { - format!("({s})") - } else { - s - } - } - Expr::Call { name, args } => { - let joined: Vec = args.iter().map(|a| a.as_display()).collect(); - format!("{name}({})", joined.join(", ")) - } - Expr::Matrix { source, .. } => source.clone(), - } - } -} - -impl fmt::Display for Expr { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.as_display()) - } -} - -impl BinOp { - fn prec(self) -> u8 { - match self { - BinOp::Add | BinOp::Sub => 1, - BinOp::Mul | BinOp::Div => 2, - BinOp::Pow => 3, - } - } - - fn sym(self) -> &'static str { - match self { - BinOp::Add => " + ", - BinOp::Sub => " - ", - BinOp::Mul => "*", - BinOp::Div => "/", - BinOp::Pow => "^", - } - } -} - -pub fn format_num(n: f64) -> String { - if n.is_nan() { - return "nan".into(); - } - if n.is_infinite() { - return if n.is_sign_positive() { - "inf".into() - } else { - "-inf".into() - }; - } - if n.fract() == 0.0 && n.abs() < 1e15 { - return format!("{}", n as i64); - } - let s = format!("{n:.10}"); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s.is_empty() || s == "-" { - "0".into() - } else { - s.to_string() - } -} - -/// Parse ASCII formula text (`sin(x) + x^2`, optional simple `y = …` left strip). -pub fn parse(input: &str) -> Result { - let t = input.trim(); - if t.is_empty() { - return Err("empty formula".into()); - } - let body = if let Some((lhs, rhs)) = t.split_once('=') { - let lhs = lhs.trim(); - if lhs.chars().all(|c| c.is_ascii_alphabetic() || c == '_') && !rhs.trim().is_empty() { - rhs.trim() - } else { - t - } - } else { - t - }; - let mut p = Parser { - src: body.chars().collect(), - i: 0, - }; - let e = p.parse_expr()?; - p.skip_ws(); - if p.i < p.src.len() { - return Err(format!( - "unexpected trailing input near `{}`", - p.src[p.i..].iter().collect::() - )); - } - Ok(e) -} - -struct Parser { - src: Vec, - i: usize, -} - -impl Parser { - fn skip_ws(&mut self) { - while self.i < self.src.len() && self.src[self.i].is_whitespace() { - self.i += 1; - } - } - - fn peek(&mut self) -> Option { - self.skip_ws(); - self.src.get(self.i).copied() - } - - fn bump(&mut self) -> Option { - self.skip_ws(); - let c = self.src.get(self.i).copied()?; - self.i += 1; - Some(c) - } - - fn parse_expr(&mut self) -> Result { - self.parse_add() - } - - fn parse_add(&mut self) -> Result { - let mut left = self.parse_mul()?; - loop { - match self.peek() { - Some('+') => { - self.bump(); - let right = self.parse_mul()?; - left = Expr::Bin { - op: BinOp::Add, - left: Box::new(left), - right: Box::new(right), - }; - } - Some('-') => { - self.bump(); - let right = self.parse_mul()?; - left = Expr::Bin { - op: BinOp::Sub, - left: Box::new(left), - right: Box::new(right), - }; - } - _ => break, - } - } - Ok(left) - } - - fn parse_mul(&mut self) -> Result { - let mut left = self.parse_pow()?; - loop { - match self.peek() { - Some('*') => { - self.bump(); - let right = self.parse_pow()?; - left = Expr::Bin { - op: BinOp::Mul, - left: Box::new(left), - right: Box::new(right), - }; - } - Some('/') => { - self.bump(); - let right = self.parse_pow()?; - left = Expr::Bin { - op: BinOp::Div, - left: Box::new(left), - right: Box::new(right), - }; - } - _ => break, - } - } - Ok(left) - } - - fn parse_pow(&mut self) -> Result { - let left = self.parse_unary()?; - if self.peek() == Some('^') { - self.bump(); - let right = self.parse_pow()?; // right-assoc - Ok(Expr::Bin { - op: BinOp::Pow, - left: Box::new(left), - right: Box::new(right), - }) - } else { - Ok(left) - } - } - - fn parse_unary(&mut self) -> Result { - match self.peek() { - Some('+') => { - self.bump(); - self.parse_unary() - } - Some('-') => { - self.bump(); - Ok(Expr::UnaryNeg(Box::new(self.parse_unary()?))) - } - _ => self.parse_primary(), - } - } - - fn parse_primary(&mut self) -> Result { - match self.peek() { - Some('(') => { - self.bump(); - let e = self.parse_expr()?; - if self.bump() != Some(')') { - return Err("expected `)`".into()); - } - Ok(e) - } - Some(c) if c.is_ascii_digit() || c == '.' => self.parse_number(), - Some(c) if c.is_ascii_alphabetic() || c == '_' => { - let name = self.parse_ident()?; - if self.peek() == Some('(') { - self.bump(); - let mut args = Vec::new(); - if self.peek() != Some(')') { - loop { - args.push(self.parse_expr()?); - match self.peek() { - Some(',') => { - self.bump(); - } - Some(')') => break, - _ => return Err("expected `,` or `)` in call".into()), - } - } - } - if self.bump() != Some(')') { - return Err("expected `)` after call args".into()); - } - Ok(Expr::Call { name, args }) - } else { - Ok(Expr::Var(name)) - } - } - Some(c) => Err(format!("unexpected `{c}` in formula")), - None => Err("unexpected end of formula".into()), - } - } - - fn parse_number(&mut self) -> Result { - self.skip_ws(); - let start = self.i; - while self.i < self.src.len() - && (self.src[self.i].is_ascii_digit() || self.src[self.i] == '.') - { - self.i += 1; - } - let s: String = self.src[start..self.i].iter().collect(); - let n: f64 = s - .parse() - .map_err(|_| format!("invalid number `{s}`"))?; - Ok(Expr::Num(n)) - } - - fn parse_ident(&mut self) -> Result { - self.skip_ws(); - let start = self.i; - while self.i < self.src.len() { - let c = self.src[self.i]; - if c.is_ascii_alphanumeric() || c == '_' { - self.i += 1; - } else { - break; - } - } - if start == self.i { - return Err("expected identifier".into()); - } - Ok(self.src[start..self.i].iter().collect()) - } -} - -/// Constant-fold + light algebraic cleanup. -pub fn simplify(e: &Expr) -> Expr { - match e { - Expr::Num(n) => Expr::Num(*n), - Expr::Var(v) => Expr::Var(v.clone()), - Expr::UnaryNeg(inner) => { - let i = simplify(inner); - match i { - Expr::Num(n) => Expr::Num(-n), - Expr::UnaryNeg(x) => *x, - other => Expr::UnaryNeg(Box::new(other)), - } - } - Expr::Bin { op, left, right } => { - let l = simplify(left); - let r = simplify(right); - fold_bin(*op, l, r) - } - Expr::Call { name, args } => { - let args: Vec = args.iter().map(simplify).collect(); - if args.len() == 1 { - if let Expr::Num(n) = &args[0] { - if let Some(v) = eval_call_f64(name, &[*n]) { - return Expr::Num(v); - } - } - } - Expr::Call { - name: name.clone(), - args, - } - } - Expr::Matrix { source, rows } => Expr::Matrix { - source: source.clone(), - rows: rows.clone(), - }, - } -} - -fn fold_bin(op: BinOp, l: Expr, r: Expr) -> Expr { - match (op, &l, &r) { - (BinOp::Add, Expr::Num(a), Expr::Num(b)) => Expr::Num(a + b), - (BinOp::Sub, Expr::Num(a), Expr::Num(b)) => Expr::Num(a - b), - (BinOp::Mul, Expr::Num(a), Expr::Num(b)) => Expr::Num(a * b), - (BinOp::Div, Expr::Num(a), Expr::Num(b)) if *b != 0.0 => Expr::Num(a / b), - (BinOp::Pow, Expr::Num(a), Expr::Num(b)) => Expr::Num(a.powf(*b)), - (BinOp::Add, _, Expr::Num(0.0)) => l, - (BinOp::Add, Expr::Num(0.0), _) => r, - (BinOp::Sub, _, Expr::Num(0.0)) => l, - (BinOp::Mul, _, Expr::Num(1.0)) => l, - (BinOp::Mul, Expr::Num(1.0), _) => r, - (BinOp::Mul, _, Expr::Num(0.0)) | (BinOp::Mul, Expr::Num(0.0), _) => Expr::Num(0.0), - (BinOp::Pow, _, Expr::Num(1.0)) => l, - (BinOp::Pow, _, Expr::Num(0.0)) => Expr::Num(1.0), - (BinOp::Div, _, Expr::Num(1.0)) => l, - _ => Expr::Bin { - op, - left: Box::new(l), - right: Box::new(r), - }, - } -} - -/// Lightweight expand: distribute multiplication over addition one level. -pub fn expand(e: &Expr) -> Expr { - let e = simplify(e); - match e { - Expr::Bin { - op: BinOp::Mul, - left, - right, - } => { - let l = expand(&left); - let r = expand(&right); - match (l, r) { - ( - Expr::Bin { - op: BinOp::Add, - left: a, - right: b, - }, - r, - ) => simplify(&Expr::Bin { - op: BinOp::Add, - left: Box::new(Expr::Bin { - op: BinOp::Mul, - left: a, - right: Box::new(r.clone()), - }), - right: Box::new(Expr::Bin { - op: BinOp::Mul, - left: b, - right: Box::new(r), - }), - }), - ( - l, - Expr::Bin { - op: BinOp::Add, - left: a, - right: b, - }, - ) => simplify(&Expr::Bin { - op: BinOp::Add, - left: Box::new(Expr::Bin { - op: BinOp::Mul, - left: Box::new(l.clone()), - right: a, - }), - right: Box::new(Expr::Bin { - op: BinOp::Mul, - left: Box::new(l), - right: b, - }), - }), - (l, r) => simplify(&Expr::Bin { - op: BinOp::Mul, - left: Box::new(l), - right: Box::new(r), - }), - } - } - Expr::Bin { op, left, right } => simplify(&Expr::Bin { - op, - left: Box::new(expand(&left)), - right: Box::new(expand(&right)), - }), - Expr::UnaryNeg(x) => simplify(&Expr::UnaryNeg(Box::new(expand(&x)))), - Expr::Call { name, args } => Expr::Call { - name, - args: args.iter().map(expand).collect(), - }, - other => other, - } -} - -pub fn diff(e: &Expr, var: &str) -> Expr { - simplify(&diff_raw(e, var)) -} - -fn diff_raw(e: &Expr, var: &str) -> Expr { - match e { - Expr::Num(_) => Expr::Num(0.0), - Expr::Var(v) => { - if v == var { - Expr::Num(1.0) - } else { - Expr::Num(0.0) - } - } - Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(diff_raw(x, var))), - Expr::Bin { - op: BinOp::Add, - left, - right, - } => Expr::Bin { - op: BinOp::Add, - left: Box::new(diff_raw(left, var)), - right: Box::new(diff_raw(right, var)), - }, - Expr::Bin { - op: BinOp::Sub, - left, - right, - } => Expr::Bin { - op: BinOp::Sub, - left: Box::new(diff_raw(left, var)), - right: Box::new(diff_raw(right, var)), - }, - Expr::Bin { - op: BinOp::Mul, - left, - right, - } => { - // product rule - Expr::Bin { - op: BinOp::Add, - left: Box::new(Expr::Bin { - op: BinOp::Mul, - left: Box::new(diff_raw(left, var)), - right: right.clone(), - }), - right: Box::new(Expr::Bin { - op: BinOp::Mul, - left: left.clone(), - right: Box::new(diff_raw(right, var)), - }), - } - } - Expr::Bin { - op: BinOp::Div, - left, - right, - } => { - // (u'v - uv') / v^2 - let num = Expr::Bin { - op: BinOp::Sub, - left: Box::new(Expr::Bin { - op: BinOp::Mul, - left: Box::new(diff_raw(left, var)), - right: right.clone(), - }), - right: Box::new(Expr::Bin { - op: BinOp::Mul, - left: left.clone(), - right: Box::new(diff_raw(right, var)), - }), - }; - Expr::Bin { - op: BinOp::Div, - left: Box::new(num), - right: Box::new(Expr::Bin { - op: BinOp::Pow, - left: right.clone(), - right: Box::new(Expr::Num(2.0)), - }), - } - } - Expr::Bin { - op: BinOp::Pow, - left, - right, - } => { - // d/dx [u^n] when n constant: n*u^(n-1)*u' - if let Expr::Num(n) = right.as_ref() { - Expr::Bin { - op: BinOp::Mul, - left: Box::new(Expr::Bin { - op: BinOp::Mul, - left: Box::new(Expr::Num(*n)), - right: Box::new(Expr::Bin { - op: BinOp::Pow, - left: left.clone(), - right: Box::new(Expr::Num(n - 1.0)), - }), - }), - right: Box::new(diff_raw(left, var)), - } - } else { - // a^u → a^u * ln(a) * u' when a constant - if let Expr::Num(a) = left.as_ref() { - Expr::Bin { - op: BinOp::Mul, - left: Box::new(Expr::Bin { - op: BinOp::Mul, - left: Box::new(e.clone()), - right: Box::new(Expr::Call { - name: "ln".into(), - args: vec![Expr::Num(*a)], - }), - }), - right: Box::new(diff_raw(right, var)), - } - } else { - // fallback: treat as exp(v*ln(u)) - Expr::Num(0.0) - } - } - } - Expr::Call { name, args } => { - if args.len() != 1 { - return Expr::Num(0.0); - } - let u = &args[0]; - let du = diff_raw(u, var); - let chain = |outer: Expr| { - Expr::Bin { - op: BinOp::Mul, - left: Box::new(outer), - right: Box::new(du.clone()), - } - }; - match name.as_str() { - "sin" => chain(Expr::Call { - name: "cos".into(), - args: vec![u.clone()], - }), - "cos" => chain(Expr::UnaryNeg(Box::new(Expr::Call { - name: "sin".into(), - args: vec![u.clone()], - }))), - "tan" => chain(Expr::Bin { - op: BinOp::Pow, - left: Box::new(Expr::Call { - name: "cos".into(), - args: vec![u.clone()], - }), - right: Box::new(Expr::Num(-2.0)), - }), - "sqrt" => chain(Expr::Bin { - op: BinOp::Div, - left: Box::new(Expr::Num(1.0)), - right: Box::new(Expr::Bin { - op: BinOp::Mul, - left: Box::new(Expr::Num(2.0)), - right: Box::new(Expr::Call { - name: "sqrt".into(), - args: vec![u.clone()], - }), - }), - }), - "ln" | "log" => chain(Expr::Bin { - op: BinOp::Div, - left: Box::new(Expr::Num(1.0)), - right: Box::new(u.clone()), - }), - "exp" => chain(Expr::Call { - name: "exp".into(), - args: vec![u.clone()], - }), - "abs" => { - // sign(u)*u' — use u/abs(u) when u≠0 - chain(Expr::Bin { - op: BinOp::Div, - left: Box::new(u.clone()), - right: Box::new(Expr::Call { - name: "abs".into(), - args: vec![u.clone()], - }), - }) - } - _ => Expr::Num(0.0), - } - } - Expr::Matrix { .. } => Expr::Num(0.0), - } -} - -pub fn subs(e: &Expr, var: &str, value: &Expr) -> Expr { - simplify(&subs_raw(e, var, value)) -} - -fn subs_raw(e: &Expr, var: &str, value: &Expr) -> Expr { - match e { - Expr::Num(n) => Expr::Num(*n), - Expr::Var(v) => { - if v == var { - value.clone() - } else { - Expr::Var(v.clone()) - } - } - Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(subs_raw(x, var, value))), - Expr::Bin { op, left, right } => Expr::Bin { - op: *op, - left: Box::new(subs_raw(left, var, value)), - right: Box::new(subs_raw(right, var, value)), - }, - Expr::Call { name, args } => Expr::Call { - name: name.clone(), - args: args.iter().map(|a| subs_raw(a, var, value)).collect(), - }, - Expr::Matrix { source, rows } => Expr::Matrix { - source: source.clone(), - rows: rows.clone(), - }, - } -} - -pub fn eval_f64(e: &Expr, env: &HashMap) -> Result { - match e { - Expr::Num(n) => Ok(*n), - Expr::Var(v) => env - .get(v) - .copied() - .ok_or_else(|| format!("unbound variable `{v}`")), - Expr::UnaryNeg(x) => Ok(-eval_f64(x, env)?), - Expr::Bin { op, left, right } => { - let a = eval_f64(left, env)?; - let b = eval_f64(right, env)?; - Ok(match op { - BinOp::Add => a + b, - BinOp::Sub => a - b, - BinOp::Mul => a * b, - BinOp::Div => { - if b == 0.0 { - return Err("division by zero".into()); - } - a / b - } - BinOp::Pow => a.powf(b), - }) - } - Expr::Call { name, args } => { - let mut xs = Vec::with_capacity(args.len()); - for a in args { - xs.push(eval_f64(a, env)?); - } - eval_call_f64(name, &xs).ok_or_else(|| format!("unknown or arity-mismatch function `{name}`")) - } - Expr::Matrix { .. } => Err("cannot evaluate matrix as a scalar".into()), - } -} - -fn eval_call_f64(name: &str, args: &[f64]) -> Option { - match (name, args) { - ("sin", [x]) => Some(x.sin()), - ("cos", [x]) => Some(x.cos()), - ("tan", [x]) => Some(x.tan()), - ("asin", [x]) => Some(x.asin()), - ("acos", [x]) => Some(x.acos()), - ("atan", [x]) => Some(x.atan()), - ("sqrt", [x]) => Some(x.sqrt()), - ("abs", [x]) => Some(x.abs()), - ("ln" | "log", [x]) => Some(x.ln()), - ("exp", [x]) => Some(x.exp()), - ("floor", [x]) => Some(x.floor()), - ("ceil", [x]) => Some(x.ceil()), - ("pow", [a, b]) => Some(a.powf(*b)), - ("min", [a, b]) => Some(a.min(*b)), - ("max", [a, b]) => Some(a.max(*b)), - _ => None, - } -} - -/// Solve `e = 0` for `var`. Quadratic/linear closed form; else numeric scan. -pub fn solve(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result, String> { - let e = expand(&simplify(e)); - if let Some(roots) = try_polynomial_solve(&e, var) { - return Ok(roots); - } - numeric_roots(&e, var, xmin, xmax) -} - -fn try_polynomial_solve(e: &Expr, var: &str) -> Option> { - let (a, b, c) = poly_coeffs_quadratic(e, var)?; - if a.abs() < 1e-12 { - if b.abs() < 1e-12 { - return if c.abs() < 1e-12 { - None // identity - } else { - Some(vec![]) - }; - } - return Some(vec![-c / b]); - } - let disc = b * b - 4.0 * a * c; - if disc < -1e-12 { - return Some(vec![]); - } - if disc.abs() <= 1e-12 { - return Some(vec![-b / (2.0 * a)]); - } - let s = disc.sqrt(); - let mut roots = vec![(-b - s) / (2.0 * a), (-b + s) / (2.0 * a)]; - roots.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)); - Some(roots) -} - -/// Collect ax^2+bx+c if expression is a polynomial of degree ≤ 2 in `var`. -fn poly_coeffs_quadratic(e: &Expr, var: &str) -> Option<(f64, f64, f64)> { - let mut a = 0.0; - let mut b = 0.0; - let mut c = 0.0; - if !accum_poly(e, var, 1.0, &mut a, &mut b, &mut c) { - return None; - } - Some((a, b, c)) -} - -fn accum_poly(e: &Expr, var: &str, scale: f64, a: &mut f64, b: &mut f64, c: &mut f64) -> bool { - match e { - Expr::Num(n) => { - *c += scale * n; - true - } - Expr::Var(v) if v == var => { - *b += scale; - true - } - Expr::Var(_) => false, - Expr::UnaryNeg(x) => accum_poly(x, var, -scale, a, b, c), - Expr::Bin { - op: BinOp::Add, - left, - right, - } => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, scale, a, b, c), - Expr::Bin { - op: BinOp::Sub, - left, - right, - } => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, -scale, a, b, c), - Expr::Bin { - op: BinOp::Mul, - left, - right, - } => match (left.as_ref(), right.as_ref()) { - (Expr::Num(n), r) => accum_poly(r, var, scale * n, a, b, c), - (l, Expr::Num(n)) => accum_poly(l, var, scale * n, a, b, c), - (Expr::Var(v), Expr::Var(w)) if v == var && w == var => { - *a += scale; - true - } - ( - Expr::Bin { - op: BinOp::Pow, - left: base, - right: exp, - }, - other, - ) - | ( - other, - Expr::Bin { - op: BinOp::Pow, - left: base, - right: exp, - }, - ) => { - if let (Expr::Var(v), Expr::Num(2.0)) = (base.as_ref(), exp.as_ref()) { - if v == var { - if let Expr::Num(n) = other { - *a += scale * n; - return true; - } - } - } - false - } - _ => false, - }, - Expr::Bin { - op: BinOp::Pow, - left, - right, - } => match (left.as_ref(), right.as_ref()) { - (Expr::Var(v), Expr::Num(2.0)) if v == var => { - *a += scale; - true - } - (Expr::Var(v), Expr::Num(1.0)) if v == var => { - *b += scale; - true - } - (Expr::Var(v), Expr::Num(0.0)) if v == var => { - *c += scale; - true - } - _ => false, - }, - _ => false, - } -} - -fn numeric_roots(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result, String> { - const STEPS: usize = 200; - let mut roots = Vec::new(); - let mut env = HashMap::new(); - let dx = (xmax - xmin) / STEPS as f64; - let mut x0 = xmin; - env.insert(var.to_string(), x0); - let mut y0 = eval_f64(e, &env)?; - for i in 1..=STEPS { - let x1 = xmin + dx * i as f64; - env.insert(var.to_string(), x1); - let y1 = eval_f64(e, &env)?; - if y0 == 0.0 { - push_unique(&mut roots, x0); - } else if y0.signum() != y1.signum() && y1 != 0.0 { - // bisection - let mut lo = x0; - let mut hi = x1; - let mut flo = y0; - for _ in 0..40 { - let mid = 0.5 * (lo + hi); - env.insert(var.to_string(), mid); - let fm = eval_f64(e, &env)?; - if fm == 0.0 || (hi - lo).abs() < 1e-10 { - push_unique(&mut roots, mid); - break; - } - if flo.signum() == fm.signum() { - lo = mid; - flo = fm; - } else { - hi = mid; - } - } - } - if i == STEPS && y1 == 0.0 { - push_unique(&mut roots, x1); - } - x0 = x1; - y0 = y1; - } - Ok(roots) -} - -fn push_unique(xs: &mut Vec, x: f64) { - if xs.iter().any(|y| (y - x).abs() < 1e-6) { - return; - } - xs.push(x); -} - -/// True if `$$` body looks like a matrix (ASCII `[[` or LaTeX pmatrix/bmatrix). -pub fn looks_like_matrix(input: &str) -> bool { - let t = input.trim(); - t.contains("[[") - || t.contains("\\begin{pmatrix}") - || t.contains("\\begin{bmatrix}") - || t.contains("\\begin{matrix}") -} - -fn replace_latex_cmd(s: &str, cmd: &str, open: char, close: char) -> Result { - let needle = format!("\\{cmd}"); - let mut out = String::new(); - let mut i = 0; - let bytes = s.as_bytes(); - while i < s.len() { - if s[i..].starts_with(&needle) { - i += needle.len(); - while i < s.len() && bytes[i].is_ascii_whitespace() { - i += 1; - } - if i >= s.len() || s[i..].chars().next() != Some(open) { - return Err(format!("\\{cmd} needs `{{{open}…{close}}}`")); - } - i += open.len_utf8(); - let start = i; - let mut depth = 1; - while i < s.len() { - let c = s[i..].chars().next().unwrap(); - if c == open { - depth += 1; - } else if c == close { - depth -= 1; - if depth == 0 { - break; - } - } - i += c.len_utf8(); - } - if depth != 0 { - return Err(format!("unclosed \\{cmd}{{…}}")); - } - let inner = &s[start..i]; - i += close.len_utf8(); - let inner_norm = normalize_latex_math(inner)?; - match cmd { - "frac" => { - // frac has two braced args — this helper only got first; handled separately - out.push_str(&inner_norm); - } - "sqrt" => { - out.push_str("sqrt("); - out.push_str(&inner_norm); - out.push(')'); - } - _ => out.push_str(&inner_norm), - } - } else { - let c = s[i..].chars().next().unwrap(); - out.push(c); - i += c.len_utf8(); - } - } - Ok(out) -} - -fn normalize_frac(s: &str) -> Result { - let mut out = String::new(); - let mut i = 0; - while i < s.len() { - if s[i..].starts_with("\\frac") { - i += "\\frac".len(); - while i < s.len() && s.as_bytes()[i].is_ascii_whitespace() { - i += 1; - } - let (num, ni) = read_brace_group(s, i)?; - i = ni; - while i < s.len() && s.as_bytes()[i].is_ascii_whitespace() { - i += 1; - } - let (den, di) = read_brace_group(s, i)?; - i = di; - let num = normalize_latex_math(&num)?; - let den = normalize_latex_math(&den)?; - out.push_str(&format!("(({num})/({den}))")); - } else { - let c = s[i..].chars().next().unwrap(); - out.push(c); - i += c.len_utf8(); - } - } - Ok(out) -} - -fn read_brace_group(s: &str, mut i: usize) -> Result<(String, usize), String> { - if i >= s.len() || !s[i..].starts_with('{') { - return Err("expected `{` group".into()); - } - i += 1; - let start = i; - let mut depth = 1; - while i < s.len() { - let c = s[i..].chars().next().unwrap(); - if c == '{' { - depth += 1; - } else if c == '}' { - depth -= 1; - if depth == 0 { - let inner = s[start..i].to_string(); - return Ok((inner, i + 1)); - } - } - i += c.len_utf8(); - } - Err("unclosed `{`".into()) -} - -fn normalize_begin_matrix(s: &str) -> Result { - let envs = ["pmatrix", "bmatrix", "matrix"]; - let mut out = String::new(); - let mut i = 0; - while i < s.len() { - let mut matched = false; - for env in envs { - let open = format!("\\begin{{{env}}}"); - let close = format!("\\end{{{env}}}"); - if s[i..].starts_with(&open) { - i += open.len(); - let start = i; - let Some(rel) = s[i..].find(&close) else { - return Err(format!("missing \\end{{{env}}}")); - }; - let body = s[start..start + rel].trim(); - i = start + rel + close.len(); - let body = normalize_latex_math(body)?; - let rows: Vec<&str> = body - .split("\\\\") - .map(|r| r.trim()) - .filter(|r| !r.is_empty()) - .collect(); - let mut mat = String::from("[["); - for (ri, row) in rows.iter().enumerate() { - if ri > 0 { - mat.push_str("],["); - } - let cells: Vec<&str> = row.split('&').map(|c| c.trim()).collect(); - for (ci, cell) in cells.iter().enumerate() { - if ci > 0 { - mat.push(','); - } - mat.push_str(cell); - } - } - mat.push_str("]]"); - // Implicit multiply if previous token is `)` / digit / `}` - if out - .chars() - .rev() - .find(|c| !c.is_whitespace()) - .is_some_and(|c| c.is_ascii_alphanumeric() || c == ')' || c == '}') - { - out.push('*'); - } - out.push_str(&mat); - matched = true; - break; - } - } - if !matched { - let c = s[i..].chars().next().unwrap(); - out.push(c); - i += c.len_utf8(); - } - } - Ok(out) -} - -fn normalize_latex_math(s: &str) -> Result { - let s = s.replace('\n', " "); - let s = normalize_frac(&s)?; - let s = replace_latex_cmd(&s, "sqrt", '{', '}')?; - let s = normalize_begin_matrix(&s)?; - // leftover common no-ops - let s = s.replace("\\left", "").replace("\\right", ""); - Ok(s) -} - -fn eval_cell(expr: &str) -> Result { - let e = parse(expr.trim())?; - eval_f64(&simplify(&e), &HashMap::new()) -} - -fn parse_bracket_matrix(s: &str) -> Result>, String> { - let t = s.trim(); - if !t.starts_with("[[") || !t.ends_with("]]") { - return Err("matrix must look like [[…],[…]]".into()); - } - let inner = &t[2..t.len() - 2]; - // Split rows on "],[" at top level - let mut rows_s: Vec = Vec::new(); - let mut cur = String::new(); - let mut depth = 0i32; - let chars: Vec = inner.chars().collect(); - let mut i = 0; - while i < chars.len() { - if chars[i] == ']' - && depth == 0 - && i + 2 < chars.len() - && chars[i + 1] == ',' - && chars[i + 2] == '[' - { - rows_s.push(cur.clone()); - cur.clear(); - i += 3; - continue; - } - let c = chars[i]; - if c == '[' { - depth += 1; - } else if c == ']' { - depth -= 1; - } - cur.push(c); - i += 1; - } - rows_s.push(cur); - let mut rows = Vec::new(); - for row in rows_s { - let row = row.trim().trim_matches(|c| c == '[' || c == ']'); - let mut cells = Vec::new(); - let mut cell = String::new(); - let mut depth = 0i32; - for c in row.chars() { - match c { - '(' | '[' => { - depth += 1; - cell.push(c); - } - ')' | ']' => { - depth -= 1; - cell.push(c); - } - ',' if depth == 0 => { - cells.push(eval_cell(&cell)?); - cell.clear(); - } - _ => cell.push(c), - } - } - if !cell.trim().is_empty() { - cells.push(eval_cell(&cell)?); - } - if cells.is_empty() { - return Err("empty matrix row".into()); - } - rows.push(cells); - } - if rows.is_empty() { - return Err("empty matrix".into()); - } - let w = rows[0].len(); - if rows.iter().any(|r| r.len() != w) { - return Err("matrix rows must have equal length".into()); - } - Ok(rows) -} - -fn scale_matrix(m: &[Vec], s: f64) -> Vec> { - m.iter() - .map(|row| row.iter().map(|x| x * s).collect()) - .collect() -} - -/// Parse ASCII / LaTeX matrix source into numeric rows (constant-fold cells). -pub fn parse_eval_matrix(input: &str) -> Result>, String> { - let norm = normalize_latex_math(input)?.trim().to_string(); - // scalar * [[…]] or [[…]] * scalar or bare [[…]] - if let Some(idx) = norm.find("[[") { - let before = norm[..idx].trim(); - let rest = &norm[idx..]; - let end = rest - .rfind("]]") - .ok_or_else(|| "unclosed [[ matrix".to_string())?; - let mat_s = &rest[..=end + 1]; - let after = rest[end + 2..].trim(); - let mat = parse_bracket_matrix(mat_s)?; - let mut scale = 1.0; - if before.ends_with('*') { - let expr = before.trim_end_matches('*').trim(); - if !expr.is_empty() { - scale *= eval_cell(expr)?; - } - } else if !before.is_empty() { - return Err(format!("unexpected prefix before matrix: `{before}`")); - } - if after.starts_with('*') { - let expr = after.trim_start_matches('*').trim(); - if !expr.is_empty() { - scale *= eval_cell(expr)?; - } - } else if !after.is_empty() { - return Err(format!("unexpected suffix after matrix: `{after}`")); - } - Ok(if (scale - 1.0).abs() < 1e-15 { - mat - } else { - scale_matrix(&mat, scale) - }) - } else { - Err("no [[…]] matrix found after LaTeX normalize".into()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_and_diff_quadratic() { - let e = parse("x^2 - 2").unwrap(); - let d = diff(&e, "x"); - assert_eq!(d.as_display(), "2*x"); - let roots = solve(&e, "x", -10.0, 10.0).unwrap(); - assert_eq!(roots.len(), 2); - assert!((roots[0] + 2f64.sqrt()).abs() < 1e-6); - assert!((roots[1] - 2f64.sqrt()).abs() < 1e-6); - } - - #[test] - fn eval_sin() { - let e = parse("sin(x)").unwrap(); - let mut env = HashMap::new(); - env.insert("x".into(), 0.0); - assert!((eval_f64(&e, &env).unwrap()).abs() < 1e-12); - } - - #[test] - fn latex_hadamard_matrix() { - let m = parse_eval_matrix( - r"\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix}", - ) - .unwrap(); - let s = std::f64::consts::FRAC_1_SQRT_2; - assert_eq!(m.len(), 2); - assert!((m[0][0] - s).abs() < 1e-12); - assert!((m[0][1] - s).abs() < 1e-12); - assert!((m[1][0] - s).abs() < 1e-12); - assert!((m[1][1] + s).abs() < 1e-12); - } - - #[test] - fn ascii_pauli_z() { - let m = parse_eval_matrix("[[1,0],[0,-1]]").unwrap(); - assert_eq!(m, vec![vec![1.0, 0.0], vec![0.0, -1.0]]); - } -} diff --git a/src/formula/plot.rs b/src/formula/plot.rs deleted file mode 100755 index c4d8595..0000000 --- a/src/formula/plot.rs +++ /dev/null @@ -1,432 +0,0 @@ -//! SVG plot helpers for high-school graphs. - -use std::collections::HashMap; - -use super::{eval_f64, Expr}; - -const MAX_STEPS: usize = 2000; -const DEFAULT_STEPS: usize = 200; -const SVG_W: f64 = 520.0; -const SVG_H: f64 = 360.0; -const PAD: f64 = 36.0; - -#[derive(Debug, Clone, Copy)] -pub struct PlotStyle { - pub grid: bool, -} - -impl Default for PlotStyle { - fn default() -> Self { - Self { grid: true } - } -} - -pub fn plot_function_svg( - expr: &Expr, - var: &str, - xmin: f64, - xmax: f64, - steps: usize, - style: PlotStyle, -) -> Result { - if !(xmin.is_finite() && xmax.is_finite()) || xmax <= xmin { - return Err("plot needs finite min < max".into()); - } - let steps = steps.clamp(2, MAX_STEPS); - let mut env = HashMap::new(); - let mut pts: Vec<(f64, f64)> = Vec::with_capacity(steps + 1); - let mut ymin = f64::INFINITY; - let mut ymax = f64::NEG_INFINITY; - for i in 0..=steps { - let x = xmin + (xmax - xmin) * (i as f64) / (steps as f64); - env.insert(var.to_string(), x); - match eval_f64(expr, &env) { - Ok(y) if y.is_finite() => { - ymin = ymin.min(y); - ymax = ymax.max(y); - pts.push((x, y)); - } - _ => {} - } - } - if pts.is_empty() { - return Err("plot produced no finite points".into()); - } - if (ymax - ymin).abs() < 1e-12 { - ymin -= 1.0; - ymax += 1.0; - } - let pad_y = 0.05 * (ymax - ymin); - ymin -= pad_y; - ymax += pad_y; - - let mut path = String::new(); - for (i, (x, y)) in pts.iter().enumerate() { - let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax); - if i == 0 { - path.push_str(&format!("M {sx:.2} {sy:.2}")); - } else { - path.push_str(&format!(" L {sx:.2} {sy:.2}")); - } - } - - let frame = draw_frame(xmin, xmax, ymin, ymax, style); - Ok(svg_wrap( - &format!(r#"{frame}"#), - "function plot", - )) -} - -pub fn plot_points_svg(xs: &[f64], ys: &[f64], style: PlotStyle) -> Result { - if xs.len() != ys.len() { - return Err("plot_points: xs and ys length mismatch".into()); - } - if xs.is_empty() { - return Err("plot_points: empty series".into()); - } - let xmin = xs.iter().cloned().fold(f64::INFINITY, f64::min); - let xmax = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max); - let ymin = ys.iter().cloned().fold(f64::INFINITY, f64::min); - let ymax = ys.iter().cloned().fold(f64::NEG_INFINITY, f64::max); - let (xmin, xmax) = pad_range(xmin, xmax); - let (ymin, ymax) = pad_range(ymin, ymax); - let mut dots = String::new(); - for (x, y) in xs.iter().zip(ys.iter()) { - if !x.is_finite() || !y.is_finite() { - continue; - } - let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax); - dots.push_str(&format!( - r#""# - )); - } - let frame = draw_frame(xmin, xmax, ymin, ymax, style); - Ok(svg_wrap(&format!("{frame}{dots}"), "points plot")) -} - -/// Standard conics via parametric sampling. -/// kind: circle | ellipse | hyperbola | parabola -pub fn plot_conic_svg( - kind: &str, - a: f64, - b: f64, - h: f64, - k: f64, - style: PlotStyle, -) -> Result { - let steps = DEFAULT_STEPS; - let mut pts: Vec<(f64, f64)> = Vec::new(); - match kind { - "circle" => { - let r = if a > 0.0 { a } else { b }; - if r <= 0.0 { - return Err("circle needs positive radius (a)".into()); - } - for i in 0..=steps { - let t = std::f64::consts::TAU * (i as f64) / (steps as f64); - pts.push((h + r * t.cos(), k + r * t.sin())); - } - } - "ellipse" => { - if a <= 0.0 || b <= 0.0 { - return Err("ellipse needs a>0, b>0".into()); - } - for i in 0..=steps { - let t = std::f64::consts::TAU * (i as f64) / (steps as f64); - pts.push((h + a * t.cos(), k + b * t.sin())); - } - } - "hyperbola" => { - if a <= 0.0 || b <= 0.0 { - return Err("hyperbola needs a>0, b>0".into()); - } - for branch in [-1.0_f64, 1.0] { - for i in 0..=steps { - let t = -2.0 + 4.0 * (i as f64) / (steps as f64); - pts.push((h + branch * a * t.cosh(), k + b * t.sinh())); - } - } - let mid = pts.len() / 2; - let (left, right) = pts.split_at(mid); - let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min); - let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max); - let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); - let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max); - let (xmin, xmax) = pad_range(xmin, xmax); - let (ymin, ymax) = pad_range(ymin, ymax); - let p1 = polyline_path(left, xmin, xmax, ymin, ymax); - let p2 = polyline_path(right, xmin, xmax, ymin, ymax); - let frame = draw_frame(xmin, xmax, ymin, ymax, style); - return Ok(svg_wrap( - &format!( - r#"{frame}"# - ), - "hyperbola", - )); - } - "parabola" => { - let scale = if a.abs() > 1e-12 { a } else { 1.0 }; - for i in 0..=steps { - let t = -3.0 + 6.0 * (i as f64) / (steps as f64); - let x = h + t; - let y = k + (t * t) / (4.0 * scale.abs()) * scale.signum(); - pts.push((x, y)); - } - } - other => return Err(format!("unknown conic kind `{other}`")), - } - - let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min); - let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max); - let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); - let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max); - let (xmin, xmax) = pad_range(xmin, xmax); - let (ymin, ymax) = pad_range(ymin, ymax); - let path = polyline_path(&pts, xmin, xmax, ymin, ymax); - let frame = draw_frame(xmin, xmax, ymin, ymax, style); - Ok(svg_wrap( - &format!(r#"{frame}"#), - kind, - )) -} - -fn pad_range(lo: f64, hi: f64) -> (f64, f64) { - if (hi - lo).abs() < 1e-12 { - (lo - 1.0, hi + 1.0) - } else { - let pad = 0.05 * (hi - lo); - (lo - pad, hi + pad) - } -} - -fn polyline_path(pts: &[(f64, f64)], xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> String { - let mut path = String::new(); - for (i, (x, y)) in pts.iter().enumerate() { - let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax); - if i == 0 { - path.push_str(&format!("M {sx:.2} {sy:.2}")); - } else { - path.push_str(&format!(" L {sx:.2} {sy:.2}")); - } - } - path -} - -fn map_xy(x: f64, y: f64, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> (f64, f64) { - let w = SVG_W - 2.0 * PAD; - let h = SVG_H - 2.0 * PAD; - let sx = PAD + (x - xmin) / (xmax - xmin) * w; - let sy = PAD + (ymax - y) / (ymax - ymin) * h; - (sx, sy) -} - -fn nice_step(span: f64, target: usize) -> f64 { - let target = target.max(2) as f64; - let raw = (span / target).abs().max(1e-12); - let exp = raw.log10().floor(); - let mag = 10f64.powf(exp); - let norm = raw / mag; - let nice = if norm <= 1.5 { - 1.0 - } else if norm <= 3.0 { - 2.0 - } else if norm <= 7.0 { - 5.0 - } else { - 10.0 - }; - nice * mag -} - -fn tick_values(lo: f64, hi: f64, step: f64) -> Vec { - if step <= 0.0 || !step.is_finite() { - return Vec::new(); - } - let start = (lo / step).ceil() * step; - let mut out = Vec::new(); - let mut v = start; - let mut guard = 0; - while v <= hi + step * 1e-9 && guard < 200 { - if v >= lo - step * 1e-9 && v <= hi + step * 1e-9 { - if v.abs() < step * 1e-9 { - out.push(0.0); - } else { - out.push(v); - } - } - v += step; - guard += 1; - } - out -} - -fn draw_frame(xmin: f64, xmax: f64, ymin: f64, ymax: f64, style: PlotStyle) -> String { - let left = PAD; - let right = SVG_W - PAD; - let top = PAD; - let bottom = SVG_H - PAD; - - let (ox, _) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax); - let (_, oy) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax); - let axis_x_y = if ymin <= 0.0 && ymax >= 0.0 { - oy.clamp(top, bottom) - } else if ymax < 0.0 { - top - } else { - bottom - }; - let axis_y_x = if xmin <= 0.0 && xmax >= 0.0 { - ox.clamp(left, right) - } else if xmax < 0.0 { - right - } else { - left - }; - - let mut s = String::new(); - let x_step = nice_step(xmax - xmin, 8); - let y_step = nice_step(ymax - ymin, 6); - - if style.grid { - for x in tick_values(xmin, xmax, x_step) { - let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax); - if sx < left - 0.5 || sx > right + 0.5 { - continue; - } - s.push_str(&format!( - r#""# - )); - } - for y in tick_values(ymin, ymax, y_step) { - let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax); - if sy < top - 0.5 || sy > bottom + 0.5 { - continue; - } - s.push_str(&format!( - r#""# - )); - } - } - - // Axes with arrowheads (positive direction). - s.push_str(&format!( - r#""# - )); - s.push_str(&format!( - r#""# - )); - - // Axis end labels - s.push_str(&format!( - r#"x"#, - x = right + 4.0, - y = axis_x_y + 4.0, - )); - s.push_str(&format!( - r#"y"#, - x = axis_y_x + 6.0, - y = top + 4.0, - )); - - // Tick labels along axes (skip 0 clutter when both axes cross). - for x in tick_values(xmin, xmax, x_step) { - if x.abs() < x_step * 1e-9 { - continue; - } - let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax); - if sx < left || sx > right { - continue; - } - s.push_str(&format!( - r#""#, - y1 = axis_x_y - 4.0, - y2 = axis_x_y + 4.0, - )); - s.push_str(&format!( - r#"{label}"#, - ty = (axis_x_y + 14.0).min(bottom + 14.0), - label = super::format_num(x), - )); - } - for y in tick_values(ymin, ymax, y_step) { - if y.abs() < y_step * 1e-9 { - continue; - } - let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax); - if sy < top || sy > bottom { - continue; - } - s.push_str(&format!( - r#""#, - x1 = axis_y_x - 4.0, - x2 = axis_y_x + 4.0, - )); - s.push_str(&format!( - r#"{label}"#, - tx = (axis_y_x - 8.0).max(4.0), - label = super::format_num(y), - )); - } - - // Origin mark when visible - if xmin <= 0.0 && xmax >= 0.0 && ymin <= 0.0 && ymax >= 0.0 { - s.push_str(&format!( - r#"0"#, - x = axis_y_x - 8.0, - y = axis_x_y + 14.0, - )); - } - - s -} - -fn svg_wrap(body: &str, title: &str) -> String { - // r## so fill="#…" does not terminate the raw string at "# - format!( - r##" - - - - - - -{body} -"##, - w = SVG_W, - h = SVG_H, - title = title, - body = body, - ) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::formula::parse; - - #[test] - fn plot_has_arrows_and_grid_by_default() { - let e = parse("x^2").unwrap(); - let svg = plot_function_svg(&e, "x", -2.0, 2.0, 40, PlotStyle::default()).unwrap(); - assert!(svg.contains("marker-end=\"url(#arrow)\"")); - assert!(svg.contains("class=\"grid\"")); - assert!(svg.contains(">x")); - assert!(svg.contains(">y")); - } - - #[test] - fn plot_can_disable_grid() { - let e = parse("x").unwrap(); - let svg = plot_function_svg(&e, "x", -1.0, 1.0, 20, PlotStyle { grid: false }).unwrap(); - assert!(!svg.contains("class=\"grid\"")); - assert!(svg.contains("marker-end=\"url(#arrow)\"")); - } -} diff --git a/src/frontend_elaboration_tests.rs b/src/frontend_elaboration_tests.rs deleted file mode 100755 index c6257e5..0000000 --- a/src/frontend_elaboration_tests.rs +++ /dev/null @@ -1,2121 +0,0 @@ -//! Source-level obligations for the real elaborator and both execution paths. -use crate::{ - bytecode::{compile_module, Vm}, - interp::Interpreter, - load::load_module, - value::Value, -}; -use std::path::PathBuf; - -// Evidence describes local machine values, not a foreign copied payload. -fn local_json(value: &Value) -> serde_json::Value { - match value { - Value::Int(value) => serde_json::json!(value), - _ => crate::host::json::value_to_json(value).unwrap(), - } -} - -fn document(id: &str, source: &str) -> (PathBuf, crate::ast::Module) { - // Scratch belongs to the build target dir; honor CARGO_TARGET_DIR when set. - let base = std::env::var_os("CARGO_TARGET_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); - let dir = base - .join("frontend-elaboration") - .join(format!("{id}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("main.mq.md"); - std::fs::write(&path, source).unwrap(); - let module = load_module(&path).unwrap(); - (path, module) -} - -#[test] -fn named_arguments_preserve_authored_effect_order() { - let source = "# main\n**answer = combine(b=mark(2), a=mark(1))**\n*answer*\n\n## combine\n + `a`\n + `b`\n**n = a * 10 + b**\n*n*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n"; - both("argument-order", source, Value::Int(12), "2\n1\n"); -} - -#[test] -fn defaults_see_target_lexical_scope_and_earlier_parameters() { - let source = "# main\n**answer = > choose a=7**\n*answer*\n\n## choose\n + `a`\n + `b`=`a`\n + `c`=> helper\n**n = b * 10 + c**\n\n### helper\n*3*\n\n*n*\n\n## helper\n*9*\n"; - both("default-scope", source, Value::Int(73), ""); - let (_, module) = document("default-scope", source); - let choose = module.functions[0] - .children - .iter() - .find(|f| f.name == "choose") - .unwrap(); - assert!(choose.children.iter().any(|f| f.name == "helper")); - assert_eq!( - module.functions[0] - .children - .iter() - .filter(|f| f.name == "helper") - .count(), - 1 - ); -} - -fn both(id: &str, source: &str, value: Value, stdout: &str) { - let (path, module) = document(id, source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let tree_value = tree.run_module(&module).unwrap(); - assert_eq!(tree_value, value, "{id}: tree"); - assert_eq!(tree.captured_stdout, stdout, "{id}: tree stdout"); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let vm_value = vm.run(&program).unwrap(); - assert_eq!(vm_value, value, "{id}: bytecode"); - assert_eq!(vm.captured_stdout, stdout, "{id}: bytecode stdout"); - #[cfg(feature = "exec-host")] - let boundary = { - let encode = |(journal, protocol, live): ( - Vec, - Vec, - usize, - )| { - serde_json::json!({ - "journal":crate::host::json::value_to_json(&Value::List(journal)).unwrap(), - "protocol":protocol.iter().map(|step|serde_json::json!({"session":step.session,"request":step.request,"response":step.response})).collect::>(),"live":live}) - }; - serde_json::json!({"tree":encode(tree.application_evidence()),"bytecode":encode(vm.application_evidence())}) - }; - #[cfg(not(feature = "exec-host"))] - let boundary = serde_json::Value::Null; - if let Some(out) = std::env::var_os("MARQDO_FRONTEND_DIR") { - use serde_json::json; - fn rows( - module: &crate::ast::Module, - namespace: &[String], - out: &mut Vec, - modules: &mut Vec, - ) { - fn functions( - module: &crate::ast::Module, - namespace: &[String], - lexical: &[String], - parent: Option, - items: &[crate::ast::Function], - out: &mut Vec, - ) { - for fun in items { - let mut path = lexical.to_vec(); - path.push(fun.name.clone()); - out.push(json!({"name":fun.name,"line":fun.span.line,"path":module.source.path,"sha256":module.source.sha256, - "module_path":namespace,"lexical_path":path,"parent_line":parent,"level":fun.level,"base":fun.base, - "params":fun.params.iter().map(|p|json!({"name":p.name,"default":p.default.is_some(),"line":p.span.line})).collect::>(), - "source_ast":crate::bytecode::SourceFunction::from_declaration(module,fun).evidence().unwrap(),"body_count":fun.body.len(),"uses_receiver":crate::ast::function_uses_receiver(fun)})); - functions( - module, - namespace, - &path, - Some(fun.span.line), - &fun.children, - out, - ); - } - } - let text = module - .source - .path - .as_ref() - .and_then(|path| std::fs::read_to_string(path).ok()); - modules.push(json!({"module_path":namespace,"path":module.source.path,"sha256":module.source.sha256,"text":text, - "imports":({let mut names=module.import_modules.keys().cloned().collect::>();names.sort();names}), - "uses":module.uses.iter().map(|binding|json!({"bind":binding.bind,"path":binding.path})).collect::>()})); - functions(module, namespace, &[], None, &module.functions, out); - let mut imports = module.import_modules.iter().collect::>(); - imports.sort_by_key(|(name, _)| *name); - for (bind, imported) in imports { - let mut child = namespace.to_vec(); - child.push(bind.clone()); - rows(imported, &child, out, modules); - } - } - let mut ast = Vec::new(); - let mut modules = Vec::new(); - rows(&module, &[], &mut ast, &mut modules); - let certificates = program.verify().unwrap(); - let evidence = json!({"version":1,"id":id,"source":source,"path":path,"sha256":module.source.sha256, - "expected":{"value":local_json(&value),"stdout":stdout}, - "tree":{"value":local_json(&tree_value),"stdout":tree.captured_stdout}, - "bytecode":{"value":local_json(&vm_value),"stdout":vm.captured_stdout}, - "boundary":boundary,"ast":ast,"modules":modules,"objects":program.objects,"object_bases":program.object_bases,"methods":program.methods,"parents":program.parents,"children":program.children, - "entry":program.entry,"entry_metadata":program.entry_metadata.iter().map(|(name,value)|json!([name,local_json(value)])).collect::>(),"functions":program.functions.iter().enumerate().map(|(fi,f)|{let mut row=json!({ - "stack_heights":certificates[fi].heights, - "body_start":f.body_start,"default_expressions":f.default_expressions,"statement_roots":f.statement_roots, - "statements":f.statements.iter().map(|s|json!({"rule":s.rule.evidence(),"start":s.start,"end":s.end,"statements":s.statements,"expressions":s.expressions,"auxiliary":s.auxiliary})).collect::>(), - "constants":f.constants.iter().map(crate::bytecode::expression_value_evidence).collect::>(), - "expressions":f.expressions.iter().map(|e|json!({"rule":e.rule.evidence(),"start":e.start,"end":e.end,"children":e.children})).collect::>(), - "name":f.name,"line":f.declaration_span.line,"path":f.source.path,"sha256":f.source.sha256, - "module_path":f.module_path,"spans":f.spans.iter().map(|span|span.line).collect::>(), - "params":f.params,"receiver_aliases":f.receiver_aliases,"defaults":f.defaults,"scope":f.module_scope,"locals":f.locals,"call_layouts":f.call_layouts,"constant_count":f.constants.len(), - "code":f.code.iter().map(|op|format!("{op:?}")).collect::>() - });row["source_ast"]=f.source_ast.evidence().unwrap();row["contracts"]=crate::bytecode::SourceFunction::contract_metadata(f.contract.as_ref(),&f.var_contracts);row["has_contract"]=json!(f.contract.is_some());row["binding_contracts"]=json!(f.var_contracts.keys().collect::>());row["source_local_count"]=json!(f.source_local_count);row["calls"]=json!(f.calls.iter().map(|c|{let mut row=c.evidence();row["binding_plan"]=c.binding_evidence(&program);row}).collect::>());row}).collect::>()}); - let out = PathBuf::from(out); - std::fs::create_dir_all(&out).unwrap(); - std::fs::write( - out.join(format!("{id}.json")), - serde_json::to_vec_pretty(&evidence).unwrap(), - ) - .unwrap(); - } -} - -#[test] -fn method_signature_belongs_to_the_actual_receiver() { - both("receiver-signature", "# A\n## m\n + `x`\n*x*\n\n# B\n## m\n + `y`\n + `z`=3\n**r = y * 10 + z**\n*r*\n\n# main\n**b = > B**\n**answer = > `b`.m y=7**\n*answer*\n", Value::Int(73), ""); -} - -#[test] -fn defaults_distinguish_omission_from_explicit_none() { - both( - "explicit-none", - "# main\n**answer = > f value=None**\n*answer*\n\n## f\n + `value`=7\n*value*\n", - Value::None, - "", - ); -} - -#[test] -fn default_effects_execute_once_and_in_parameter_order() { - both("default-order", "# main\n**answer = f(c=mark(9))**\n*answer*\n\n## f\n + `a`=> mark value=1\n + `b`=> mark value=2\n + `c`=0\n**r = a * 100 + b * 10 + c**\n*r*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n", Value::Int(129), "9\n1\n2\n"); -} - -#[test] -fn supplied_later_parameter_is_available_to_a_default() { - both( - "provided-later", - "# main\n**answer = > f b=8**\n*answer*\n\n## f\n + `a`=`b`\n + `b`=7\n*a*\n", - Value::Int(8), - "", - ); -} - -#[test] -fn imported_defaults_keep_the_definition_module() { - let (path, _) = document("import-default", "# main\n*0*\n"); - let library = "## choose\n + `value`=> helper\n*value*\n\n## helper\n*3*\n"; - std::fs::write(path.parent().unwrap().join("lib.mq.md"), library).unwrap(); - both("import-default", "---\nimport:\n lib: lib.mq.md\n---\n# main\n**answer = > lib.choose**\n*answer*\n\n## helper\n*9*\n", Value::Int(3), ""); -} - -#[test] -fn nested_calls_do_not_overwrite_pending_actuals_or_leak_temporary_slots() { - let mut source = String::from("# main\n"); - for _ in 0..400 { - source.push_str("**answer = pair(b=pair(2, 3), a=pair(4, 5))**\n"); - } - source.push_str("*answer*\n\n## pair\n + `a`\n + `b`\n**r = a * 10 + b**\n*r*\n"); - both("temporary-lifetimes", &source, Value::Int(473), ""); -} - -#[test] -fn unused_extra_named_arguments_still_execute_in_authored_order() { - both("extra-effects", "# main\n**answer = f(extra=mark(2), x=mark(1))**\n*answer*\n\n## f\n + `x`\n*x*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n", Value::Int(1), "2\n1\n"); -} - -#[test] -fn builtin_argument_permutation_happens_after_authored_evaluation() { - both("builtin-order", "# main\n**answer = split(sep=mark(\"S\"), value=mark(\"X\"))**\n*answer*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n", Value::List(vec![Value::Text("X".into())]), "S\nX\n"); -} - -#[test] -fn imported_object_identity_survives_cross_module_calls() { - let (path, _) = document("qualified-objects", "# main\n*0*\n"); - std::fs::write( - path.parent().unwrap().join("a.mq.md"), - "# Counter\n## read\n*3*\n", - ) - .unwrap(); - std::fs::write( - path.parent().unwrap().join("b.mq.md"), - "## through\n + `value`\n**r = > `value`.read**\n*r*\n\n# Counter\n## read\n*7*\n", - ) - .unwrap(); - both("qualified-objects", "---\nimport:\n a: a.mq.md\n b: b.mq.md\n---\n# main\n**x = > a.Counter**\n**y = > b.Counter**\n**p = > `x`.read**\n**q = > `y`.read**\n**r = > b.through value=`x`**\n**answer = p * 100 + q * 10 + r**\n*answer*\n", Value::Int(373), ""); -} - -#[test] -fn inherited_methods_resolve_bases_in_the_defining_module() { - let (path, _) = document("qualified-inheritance", "# main\n*0*\n"); - for (name, value) in [("a", 3), ("b", 7)] { - std::fs::write( - path.parent().unwrap().join(format!("{name}.mq.md")), - format!("# Parent\n## read\n*{value}*\n\n# Child = > Parent\n"), - ) - .unwrap(); - } - both("qualified-inheritance", "---\nimport:\n a: a.mq.md\n b: b.mq.md\n---\n# main\n**x = > a.Child**\n**y = > b.Child**\n**p = > `x`.read**\n**q = > `y`.read**\n**answer = p * 10 + q**\n*answer*\n", Value::Int(37), ""); -} - -#[test] -fn imported_type_aliases_disambiguate_inheritance() { - let (path, _) = document("aliased-base", "# main\n*0*\n"); - for (name, value) in [("a", 3), ("b", 7)] { - std::fs::write( - path.parent().unwrap().join(format!("{name}.mq.md")), - format!("# Parent\n## read\n*{value}*\n"), - ) - .unwrap(); - } - both("aliased-base","---\nimport:\n a: a.mq.md\n b: b.mq.md\n Base: a.Parent\n---\n# Child = > Base\n\n# main\n**x = > Child**\n**answer = > `x`.read**\n*answer*\n",Value::Int(3),""); -} - -#[test] -fn default_object_arguments_keep_root_module_context() { - let (path, _) = document("external-object-default", "# main\n*0*\n"); - std::fs::write( - path.parent().unwrap().join("a.mq.md"), - "# Counter\n## read\n*3*\n", - ) - .unwrap(); - std::fs::write( - path.parent().unwrap().join("b.mq.md"), - "## through\n + `value`\n**r = > `value`.read**\n*r*\n\n# Counter\n## read\n*7*\n", - ) - .unwrap(); - let source=format!("---\nimport:\n a: a.mq.md\n b: b.mq.md\n json: {}\n---\n## choose\n + `value`=> a.Counter\n**r = > json.get value=`value` key=\"_type_module\"**\n*r*\n",PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib/json.mq.md").display()); - std::fs::write(&path, &source).unwrap(); - for backend in [crate::Backend::Tree, crate::Backend::Bytecode] { - assert_eq!( - crate::call::call_file(&path, "choose", &[], backend).unwrap(), - Value::List(vec![Value::Text("a".into())]) - ); - } -} - -#[test] -fn entry_defaults_use_metadata_as_supplied_arguments() { - both("entry-metadata-default","---\nvalue: 7\n---\n# main\n + `value`=> mark\n*value*\n\n## mark\n> print text=DEFAULT\n*99*\n",Value::Int(7),""); - both( - "entry-omitted-default", - "# main\n + `value`=> mark\n*value*\n\n## mark\n> print text=DEFAULT\n*99*\n", - Value::Int(99), - "DEFAULT\n", - ); -} - -#[test] -fn named_calls_to_main_do_not_inject_entry_metadata() { - let (path, module) = document( - "named-main", - "---\nvalue: 7\n---\n# main\n + `value`=3\n*value*\n", - ); - let fun = module.functions.iter().find(|f| f.name == "main").unwrap(); - let args = vec![("value".into(), Value::Int(42))]; - let mut tree = Interpreter::with_capture(Some(&path), false); - assert_eq!( - tree.invoke_bound_function(&module, fun, &args).unwrap(), - Value::Int(42) - ); - let program = crate::bytecode::compile_for_call(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - assert_eq!( - vm.call_function(&program, program.entry, &args).unwrap(), - Value::Int(42) - ); -} - -#[cfg(feature = "exec-host")] -#[test] -fn entry_session_defaults_execute_in_the_owning_backend_context() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - for language in ["python", "node"] { - let source=format!("---\nimport:\n foreign: {}\n---\n# main\n + `s`=> foreign.session_open lang=\"{language}\"\n**> foreign.session_set id=`s` name=\"n\" value=7**\n**answer = > foreign.session_get id=`s` name=\"n\"**\n**> foreign.session_close id=`s`**\n*answer*\n",root.join("lib/foreign.mq.md").display()); - both( - &format!("entry-session-{language}"), - &source, - Value::Int(7), - "", - ); - } -} - -#[test] -fn declarations_read_only_by_defaults_are_inferred_inputs() { - let source="# main\n**answer = > choose b=7**\n*answer*\n\n## choose\n + `a`=`b`\n请求参数`b`。\n*a*\n"; - both("default-only-input", source, Value::Int(7), ""); - let (path, module) = document("default-only-input", source); - let choose = &module.functions[0].children[0]; - assert!(choose.params.iter().any(|p| p.name == "b" && p.inferred)); - for backend in [crate::Backend::Tree, crate::Backend::Bytecode] { - assert_eq!( - crate::call::call_file( - &path, - "main.choose", - &[("b".into(), Value::Int(7))], - backend - ) - .unwrap(), - Value::Int(7) - ); - } -} - -#[test] -fn explicit_and_prose_defaults_keep_declaration_order() { - let source="# main\n**answer = > choose**\n*answer*\n\n## choose\n + `a`=> mark value=1\n参数`b`=mark(2)\n**r = a * 10 + b**\n*r*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n"; - both("prose-default-order", source, Value::Int(12), "1\n2\n"); -} - -#[test] -fn default_faults_use_the_parameter_source_line() { - let source = "# main\n**answer = > bad**\n*answer*\n\n## bad\n + `value`=1 / 0\n*value*\n"; - let (path, module) = document("default-fault-line", source); - let expected = source - .lines() - .position(|line| line.contains("+ `value`")) - .unwrap() as u32 - + 1; - let mut tree = Interpreter::with_capture(Some(&path), false); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - for result in [tree.run_module(&module), vm.run(&program)] { - let error = result.unwrap_err(); - let diagnostic = crate::diagnostics::Diagnostic::find(&error).unwrap(); - assert!(diagnostic.message.contains("division by zero")); - assert_eq!(diagnostic.span, crate::diagnostics::Span::new(expected, 1)); - assert_eq!(diagnostic.path.as_deref(), Some(path.as_path())); - } -} - -#[test] -fn duplicate_parameters_are_frontend_errors() { - let (path, _) = document("duplicate-names", "# main\n*0*\n"); - for (source, expected) in [( - "# main\n + `value`\n + `value`=7\n*value*\n", - "duplicate parameter", - )] { - std::fs::write(&path, source).unwrap(); - let error = load_module(&path).unwrap_err(); - assert!(error.to_string().contains(expected), "{error:#}"); - } -} - -#[test] -fn qualified_paths_keep_the_first_source_declaration() { - let (path, _) = document("first-qualified-declaration", "# main\n*0*\n"); - std::fs::write( - path.parent().unwrap().join("a.mq.md"), - "# A\n## read\n*1*\n\n## read\n*2*\n", - ) - .unwrap(); - both( - "first-qualified-declaration", - "---\nimport:\n a: a.mq.md\n---\n# main\n**answer = > a.A.read**\n*answer*\n", - Value::Int(1), - "", - ); -} - -#[test] -fn scratch_slots_do_not_alias_authored_names() { - let source="# main\n**ignored = mark(1)**\n**`\0call.arg.1.0` = 7**\n**ignored = mark(2)**\n*`\0call.arg.1.0`*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n"; - both("scratch-freshness", source, Value::Int(7), "1\n2\n"); -} - -#[test] -fn default_expressions_can_read_extra_named_bindings() { - both( - "default-extra-binding", - "# main\n**answer = > choose b=7**\n*answer*\n\n## choose\n + `a`=`b`\n*a*\n", - Value::Int(7), - "", - ); -} - -#[test] -fn metadata_initialization_matches_first_binding_semantics() { - let (path, mut module) = document("metadata-first-binding", "# main\n*value*\n"); - module.metadata = vec![ - ("value".into(), Value::Int(7)), - ("value".into(), Value::Int(8)), - ]; - let mut tree = Interpreter::with_capture(Some(&path), false); - assert_eq!(tree.run_module(&module).unwrap(), Value::Int(7)); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - assert_eq!(vm.run(&program).unwrap(), Value::Int(7)); -} - -#[cfg(feature = "exec-host")] -#[test] -fn copied_object_module_tags_remain_data_across_foreign_boundaries() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - for language in ["python", "node"] { - let id = format!("copied-object-{language}"); - let (path, _) = document(&id, "# main\n*0*\n"); - for (name, value) in [("a", 3), ("b", 7)] { - std::fs::write( - path.parent().unwrap().join(format!("{name}.mq.md")), - format!("# Counter\n## read\n*{value}*\n"), - ) - .unwrap(); - } - let source=format!("---\nimport:\n a: a.mq.md\n b: b.mq.md\n foreign: {}\n---\n# main\n**x = > a.Counter**\n**s = > foreign.session_open lang=\"{language}\"**\n**> foreign.session_set id=`s` name=\"object\" value=`x`**\n**copy = > foreign.session_get id=`s` name=\"object\"**\n**> foreign.session_close id=`s`**\n**p = > `copy`.read**\n**y = > b.Counter**\n**q = > `y`.read**\n**answer = p * 10 + q**\n*answer*\n",root.join("lib/foreign.mq.md").display()); - both(&id, &source, Value::Int(37), ""); - } -} - -#[test] -fn local_constant_and_jump_indices_do_not_truncate() { - let mut locals = String::from("# main\n"); - for i in 0..700 { - locals.push_str(&format!("**x{i} = {i}**\n")); - } - locals.push_str("**answer = x0 + x699**\n*answer*\n"); - both("wide-locals", &locals, Value::Int(699), ""); - let mut constants = String::from("# main\n"); - for i in 0..70000 { - constants.push_str(&format!("**answer = {i}**\n")); - } - constants.push_str("*answer*\n"); - both("wide-constants", &constants, Value::Int(69999), ""); - let mut jump = String::from("# main\n**flag = False**\n1. `flag`\n"); - for _ in 0..25000 { - jump.push_str(" **answer = 0**\n"); - } - jump.push_str("2. *\n **answer = 8**\n\n*answer*\n"); - both("wide-jumps", &jump, Value::Int(8), ""); -} - -#[test] -fn receiver_used_only_by_a_default_is_still_an_instance_method() { - let source = format!("---\nimport:\n json: {}\n---\n# B\n**state = > json.parse text={{\"n\":7}}**\n*state*\n\n## m\n + `value`=> json.get value=`self` key=\"n\"\n*value*\n\n# main\n**b = > B**\n**answer = > `b`.m**\n*answer*\n", PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib/json.mq.md").display()); - both("receiver-default", &source, Value::Int(7), ""); - let (_, module) = document("receiver-default", &source); - assert!(crate::ast::function_uses_receiver( - &module.functions[0].children[0] - )); -} - -#[test] -fn pure_call_checks_transitive_default_effects_before_executing_them() { - let source = "## choose\n + `value`=> mark\n*value*\n\n## mark\n> print text=effect\n*7*\n"; - let (path, _) = document("default-effects-policy", source); - for backend in [crate::Backend::Tree, crate::Backend::Bytecode] { - let error = crate::call::call_file(&path, "choose", &[], backend).unwrap_err(); - let diagnostic = crate::diagnostics::Diagnostic::find(&error).unwrap(); - assert_eq!(diagnostic.code, "artifact.effect_denied", "{error:#}"); - } -} - -#[test] -fn an_imported_main_cannot_replace_the_entry_module() { - let (path, _) = document("entry-scope", "# main\n*0*\n"); - std::fs::write( - path.parent().unwrap().join("lib.mq.md"), - "# main\n> print text=WRONG-ENTRY\n*99*\n", - ) - .unwrap(); - both( - "entry-scope", - "---\nimport:\n lib: lib.mq.md\n---\n# main\n*7*\n", - Value::Int(7), - "", - ); -} - -#[test] -fn omitted_later_defaults_are_unbound_and_none_is_not_a_missing_slot() { - let source = "# main\n**answer = > f**\n*answer*\n\n## f\n + `a`=`b`\n + `b`=7\n*a*\n"; - let (path, module) = document("unbound-default", source); - let mut tree = Interpreter::with_capture(Some(&path), false); - assert!(tree - .run_module(&module) - .unwrap_err() - .to_string() - .contains("undefined variable `b`")); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - assert!(vm - .run(&program) - .unwrap_err() - .to_string() - .contains("undefined variable `b`")); -} - -#[test] -fn signed_integer_literals_include_the_negative_endpoint() { - both( - "minimum-int", - "# main\n**answer = -9223372036854775808**\n*answer*\n", - Value::Int(i64::MIN), - "", - ); -} - -#[cfg(feature = "exec-host")] -#[test] -fn nested_actuals_and_lexical_defaults_preserve_real_foreign_transitions() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - for language in ["python", "node"] { - let code = "n = n * 10 + marqdo_input; n"; - let source = format!( - r#"--- -import: - foreign: {} - json: {} ---- -# main -**h = > foreign.session_open lang="{language}"** -**> foreign.session_set id=`h` name="n" value=0** -**answer = combine(b=mark(id=h, value=2), a=mark(id=h, value=1))** -**n = > foreign.session_get id=`h` name="n"** -**> foreign.session_close id=`h`** -**r = answer * 100 + n** -*r* - -## mark - + `id` - + `value` -**record = > foreign.session_eval id=`id` source={code:?} input=`value`** -**answer = > json.get value=`record` key="result"** -*answer* - -## combine - + `a` - + `b` - + `c`=> helper -**r = a * 1000 + b * 10 + c** - -### helper -*3* - -*r* - -## helper -*9* -"#, - root.join("lib/foreign.mq.md").display(), - root.join("lib/json.mq.md").display() - ); - both( - &format!("foreign-arguments-{language}"), - &source, - Value::Int(2102321), - "", - ); - } -} - -#[test] -fn machine_arithmetic_matches_wide_reference_and_reports_language_faults() { - let values = [ - i64::MIN, - i64::MIN + 1, - -3037000500, - -7, - -1, - 0, - 1, - 7, - 3037000500, - i64::MAX - 1, - i64::MAX, - ]; - let mut records = Vec::new(); - for left in values { - for right in values { - for op in ["+", "-", "*", "/"] { - let wide = if op == "/" && right == 0 { - None - } else { - Some(match op { - "+" => left as i128 + right as i128, - "-" => left as i128 - right as i128, - "*" => left as i128 * right as i128, - "/" => left as i128 / right as i128, - _ => unreachable!(), - }) - }; - let expected = wide.and_then(|n| i64::try_from(n).ok()); - let fault = if op == "/" && right == 0 { - "division by zero" - } else { - "integer overflow" - }; - let source = format!("# main\n**answer = ({left}) {op} ({right})**\n*answer*\n"); - let (path, module) = document("machine-ints", &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let result = tree.run_module(&module); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let result_vm = vm.run(&program); - let encode = |result: anyhow::Result| match result { - Ok(value) => { - assert_eq!(Some(value.clone()), expected.map(Value::Int), "{source}"); - serde_json::json!({"value":local_json(&value)}) - } - Err(error) => { - assert!(expected.is_none(), "{source}: {error}"); - assert!(error.to_string().contains(fault), "{source}: {error}"); - serde_json::json!({"error":error.to_string()}) - } - }; - records.push(serde_json::json!({"left":left,"right":right,"op":op,"tree":encode(result),"bytecode":encode(result_vm)})); - } - } - } - for value in values { - let source = format!("# main\n**answer = -({value})**\n*answer*\n"); - let (path, module) = document("machine-negation", &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - for result in [tree.run_module(&module), vm.run(&program)] { - if value == i64::MIN { - assert!(result.unwrap_err().to_string().contains("integer overflow")); - } else { - assert_eq!(result.unwrap(), Value::Int((-(value as i128)) as i64)); - } - } - } - for value in [ - f64::INFINITY, - f64::NEG_INFINITY, - f64::NAN, - 9223372036854775808.0, - ] { - assert!(crate::builtin::builtin_int(&Value::Num(value)) - .unwrap_err() - .contains("64-bit")); - } - assert_eq!( - crate::builtin::builtin_int(&Value::Num(-9223372036854775808.0)).unwrap(), - i64::MIN - ); - if let Some(out) = std::env::var_os("MARQDO_FRONTEND_DIR") { - let out = PathBuf::from(out); - std::fs::create_dir_all(&out).unwrap(); - std::fs::write( - out.join("machine-arithmetic.json"), - serde_json::to_vec_pretty(&serde_json::json!({"version":1,"cases":records})).unwrap(), - ) - .unwrap(); - } -} - -#[test] -fn source_bound_calls_preserve_the_selected_declaration() { - let source = "# A\n## read\n*1*\n\n## read\n*2*\n"; - let (path, module) = document("source-bound-duplicates", source); - assert_eq!(module.functions[0].children.len(), 2); - let mut rows = Vec::new(); - for (index, fun) in module.functions[0].children.iter().enumerate() { - let expected = Value::Int(index as i64 + 1); - let mut observed = Vec::new(); - for backend in [crate::Backend::Tree, crate::Backend::Bytecode] { - let (value, stdout) = crate::call::execute_source_function( - &path, - fun.span.line, - "A.read", - &[], - crate::host::HostCaps::default(), - backend, - false, - ) - .unwrap(); - assert_eq!(value, expected); - assert!(stdout.is_empty()); - observed.push(local_json(&value)); - } - rows.push( - serde_json::json!({"line":fun.span.line,"tree":observed[0],"bytecode":observed[1]}), - ); - } - write_extra_evidence( - "source-bound-duplicates", - serde_json::json!({"source":source,"calls":rows}), - ); -} - -fn write_extra_evidence(name: &str, value: serde_json::Value) { - if let Some(out) = std::env::var_os("MARQDO_FRONTEND_DIR") { - let out = PathBuf::from(out); - std::fs::create_dir_all(&out).unwrap(); - std::fs::write( - out.join(format!("{name}.json")), - serde_json::to_vec_pretty(&value).unwrap(), - ) - .unwrap(); - } -} - -#[test] -fn all_four_contract_boundaries_preserve_diagnostics() { - let mut rows = Vec::new(); - for (fixture, code) in [ - ("arg_mismatch", "contract.arg_mismatch"), - ("return_mismatch", "contract.return_mismatch"), - ("field_mismatch", "contract.field_mismatch"), - ("unknown_key", "contract.unknown_key"), - ] { - let source = std::fs::read_to_string( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("tests/contracts") - .join(format!("{fixture}.mq.md")), - ) - .unwrap(); - let (path, module) = document(fixture, &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let tree_error = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let vm_error = vm.run(&program).unwrap_err(); - let t = crate::diagnostics::Diagnostic::find(&tree_error) - .unwrap() - .to_json(); - let v = crate::diagnostics::Diagnostic::find(&vm_error) - .unwrap() - .to_json(); - assert_eq!(t["code"], code); - assert_eq!(v["code"], code); - for key in ["span", "doc_anchor", "doc_quote", "contract_ref"] { - assert_eq!(t[key], v[key], "{fixture}: {key}"); - } - assert!(tree.captured_stdout.is_empty()); - assert!(vm.captured_stdout.is_empty()); - rows.push(serde_json::json!({"fixture":fixture,"source":source,"tree":t,"bytecode":v,"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout})); - } - // Invalid defaults must be checked before any authored body effect. - let source="# main\n**answer = > choose**\n*answer*\n\n## choose\n + `n`=\"bad\"\n\n| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 输入 |\n\n> print text=\"BODY\"\n*n*\n"; - let (path, module) = document("default-contract", source); - for bytecode in [false, true] { - let (error, stdout) = if bytecode { - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - (vm.run(&program).unwrap_err(), vm.captured_stdout) - } else { - let mut tree = Interpreter::with_capture(Some(&path), false); - (tree.run_module(&module).unwrap_err(), tree.captured_stdout) - }; - assert_eq!( - crate::diagnostics::Diagnostic::find(&error) - .unwrap() - .to_json()["code"], - "contract.arg_mismatch" - ); - assert!(stdout.is_empty()); - } - write_extra_evidence("contract-boundaries", serde_json::json!({"cases":rows})); - let source = std::fs::read_to_string( - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/contracts/ok_contract.mq.md"), - ) - .unwrap(); - both("valid-contract", &source, Value::Int(4), ""); -} - -#[test] -fn duplicate_actuals_fault_after_evaluation_and_only_when_reached() { - both( - "unreached-duplicate", - "# main\n*7*\n\n## unused\n> print text=\"a\" text=\"b\"\n", - Value::Int(7), - "", - ); - let source="# main\n**answer = combine(a=mark(1), a=mark(2), b=mark(3))**\n> print text=\"SUFFIX\"\n*answer*\n\n## combine\n + `a`\n + `b`\n*a*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n"; - let (path, module) = document("duplicate-arguments", source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let t = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let v = vm.run(&program).unwrap_err(); - assert!(t.to_string().contains("duplicate named argument `a`")); - assert!(v.to_string().contains("duplicate named argument `a`")); - assert_eq!(tree.captured_stdout, "1\n2\n3\n"); - assert_eq!(vm.captured_stdout, tree.captured_stdout); - write_extra_evidence( - "duplicate-arguments", - serde_json::json!({"source":source,"tree_error":t.to_string(),"bytecode_error":v.to_string(),"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout}), - ); -} - -#[test] -fn imported_contract_blame_separates_call_site_and_declaration() { - let mut rows = Vec::new(); - for omitted in [false, true] { - let (path, _) = document( - if omitted { - "import-contract-default" - } else { - "import-contract-supplied" - }, - "# main\n*0*\n", - ); - let library="## check\n + `n`=\"bad\"\n\n| 参数 | 类型 | 说明 |\n|------|------|------|\n| n | number | 输入 |\n\n> print text=\"BODY\"\n*n*\n"; - let library_path = path.parent().unwrap().join("api.mq.md"); - std::fs::write(&library_path, library).unwrap(); - let source = format!( - "---\nimport:\n api: api.mq.md\n---\n# main\n**answer = > api.check{}**\n*answer*\n", - if omitted { "" } else { " n=\"bad\"" } - ); - std::fs::write(&path, &source).unwrap(); - let module = load_module(&path).unwrap(); - let mut tree = Interpreter::with_capture(Some(&path), false); - let te = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let ve = vm.run(&program).unwrap_err(); - let t = crate::diagnostics::Diagnostic::find(&te).unwrap().to_json(); - let v = crate::diagnostics::Diagnostic::find(&ve).unwrap().to_json(); - for diag in [&t, &v] { - assert_eq!(diag["code"], "contract.arg_mismatch"); - assert_eq!(diag["span"]["line"], 6); - assert_eq!(diag["span"]["file"], path.to_str().unwrap()); - assert_eq!( - diag["doc_anchor"], - format!("{}#L4-L6", library_path.display()) - ); - assert!(diag["suggestion"] - .as_str() - .unwrap() - .contains(&format!("{}#L4-L6", library_path.display()))); - } - assert!(tree.captured_stdout.is_empty() && vm.captured_stdout.is_empty()); - rows.push(serde_json::json!({"omitted":omitted,"source":source,"library":library,"tree":t,"bytecode":v,"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout})); - } - write_extra_evidence("imported-contracts", serde_json::json!({"cases":rows})); -} - -#[test] -fn generated_default_masks_and_declaration_orders_preserve_effects() { - let names = ["a", "b", "c"]; - let mut rows = Vec::new(); - for order in [ - [0, 1, 2], - [0, 2, 1], - [1, 0, 2], - [1, 2, 0], - [2, 0, 1], - [2, 1, 0], - ] { - for mask in 0..27usize { - let states = [mask % 3, (mask / 3) % 3, (mask / 9) % 3]; - let args = (0..3) - .filter_map(|i| match states[i] { - 0 => None, - 1 => Some(format!("{}={}", names[i], (i + 1) * 10)), - _ => Some(format!("{}=None", names[i])), - }) - .collect::>() - .join(" "); - let params = order - .iter() - .map(|i| { - format!( - " + `{}`=> mark value={}\n", - names[*i], - match i { - 0 => "1", - 1 => "`a`", - _ => "`b`", - } - ) - }) - .collect::(); - let source=format!("# main\n**answer = > choose {args}**\n*answer*\n\n## choose\n{params}\n**out = str(a) + \"|\" + str(b) + \"|\" + str(c)**\n*out*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n"); - let (path, module) = document("generated-defaults", &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let tr = tree.run_module(&module); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let vr = vm.run(&program); - let encode = |r: anyhow::Result, stdout: String| match r { - Ok(value) => serde_json::json!({"value":local_json(&value),"stdout":stdout}), - Err(error) => serde_json::json!({"error":error.to_string(),"stdout":stdout}), - }; - rows.push(serde_json::json!({"order":order,"states":states,"source":source,"tree":encode(tr,tree.captured_stdout),"bytecode":encode(vr,vm.captured_stdout)})); - } - } - write_extra_evidence("generated-defaults", serde_json::json!({"cases":rows})); -} - -#[test] -fn flat_bytecode_validation_rejects_corruption_before_effects() { - use crate::bytecode::Op; - let (path, module) = document( - "flat-corruptions", - "# main\n> print text=\"BEFORE\"\n*7*\n\n## f\n + `n`=3\n*n*\n", - ); - let program = compile_module(Some(&path), &module).unwrap(); - let certs = program.verify().unwrap(); - assert_eq!(certs.len(), program.functions.len()); - let main = program.entry; - let mutations: Vec<(&str, Box)> = vec![ - ( - "constant", - Box::new(move |p| p.functions[main].code[0] = Op::Constant(usize::MAX)), - ), - ( - "local", - Box::new(move |p| p.functions[main].code[0] = Op::GetLocal(usize::MAX)), - ), - ( - "jump", - Box::new(move |p| p.functions[main].code[0] = Op::Jump(usize::MAX)), - ), - ( - "underflow", - Box::new(move |p| p.functions[main].code[0] = Op::Add), - ), - ( - "callee", - Box::new(move |p| p.functions[main].code[0] = Op::Call(usize::MAX, 0)), - ), - ( - "layout", - Box::new(move |p| p.functions[main].code[0] = Op::CallArgs(main, usize::MAX)), - ), - ( - "presence", - Box::new(move |p| p.functions[main].code[0] = Op::JumpIfProvided(usize::MAX, 1)), - ), - ( - "span", - Box::new(move |p| { - p.functions[main].spans.pop(); - }), - ), - ( - "duplicate-slot", - Box::new(move |p| { - p.functions[main].locals = vec!["x".into(), "x".into()]; - }), - ), - ( - "parameter-prefix", - Box::new(move |p| { - let f = p.functions.iter_mut().find(|f| f.name == "f").unwrap(); - f.locals[0] = "wrong".into(); - }), - ), - ]; - let mut cycle = program.clone(); - let child = cycle.functions.iter().position(|f| f.name == "f").unwrap(); - cycle.parents[main] = Some(child); - cycle.children[child].push(main); - assert!(cycle.verify().unwrap_err().contains("cyclic")); - let mut rows = Vec::new(); - for (name, mutate) in mutations { - let mut corrupted = program.clone(); - mutate(&mut corrupted); - let error = corrupted.verify().unwrap_err(); - let mut vm = Vm::with_capture(Some(&path)); - let runtime = vm.run(&corrupted).unwrap_err(); - assert!(vm.captured_stdout.is_empty(), "{name}"); - assert!( - runtime.to_string().contains("bytecode") || runtime.to_string().contains("invalid") - ); - rows.push(serde_json::json!({"mutation":name,"error":error,"stdout":vm.captured_stdout})); - } - write_extra_evidence("flat-corruptions", serde_json::json!({"cases":rows})); -} - -#[test] -fn bare_calls_use_the_source_resolver_declaration_identity() { - both( - "first-bare-declaration", - "## pick\n*1*\n\n## pick\n*2*\n\n# main\n**answer = > pick**\n*answer*\n", - Value::Int(1), - "", - ); -} - -#[test] -fn semantic_emission_checks_reject_stack_preserving_corruption() { - both("short-circuit-effects","# main\n**a = False and mark()**\n**b = True or mark()**\n**c = True and mark()**\n**d = False or mark()**\n*b and c and d*\n\n## mark\n> print text=\"RHS\"\n*True*\n",Value::Bool(true),"RHS\nRHS\n"); - use crate::bytecode::Op; - let (path, module) = document( - "semantic-corruptions", - "# main\n**a = 7**\n**b = 3**\n**answer = a + b**\n> print text=\"AFTER\"\n*answer*\n", - ); - let original = compile_module(Some(&path), &module).unwrap(); - let mut rows = Vec::new(); - for mutation in ["operator", "constant", "variable", "operand_order"] { - let mut p = original.clone(); - let f = &mut p.functions[p.entry]; - match mutation { - "operator" => *f.code.iter_mut().find(|op| matches!(op, Op::Add)).unwrap() = Op::Sub, - "constant" => { - *f.constants - .iter_mut() - .find(|v| matches!(v, Value::Int(7))) - .unwrap() = Value::Int(8) - } - "variable" => { - let a = f.locals.iter().position(|n| n == "a").unwrap(); - let b = f.locals.iter().position(|n| n == "b").unwrap(); - *f.code - .iter_mut() - .find(|op| **op == Op::GetLocal(a)) - .unwrap() = Op::GetLocal(b); - } - _ => { - let e = f - .expressions - .iter_mut() - .find(|e| { - matches!( - e.rule, - crate::bytecode::ExpressionRule::Binary(crate::ast::BinaryOp::Add) - ) - }) - .unwrap(); - e.children.swap(0, 1); - } - } - let error = p.verify().unwrap_err(); - let mut vm = Vm::with_capture(Some(&path)); - assert!(vm.run(&p).is_err()); - assert!(vm.captured_stdout.is_empty()); - rows.push( - serde_json::json!({"mutation":mutation,"error":error,"stdout":vm.captured_stdout}), - ); - } - for (name, source) in [ - ("unary", "# main\n**a = 7**\n**answer = -a**\n*answer*\n"), - ( - "short_circuit", - "# main\n**answer = False and True**\n*answer*\n", - ), - ] { - let (path, module) = document(name, source); - let mut p = compile_module(Some(&path), &module).unwrap(); - let f = &mut p.functions[p.entry]; - if name == "unary" { - *f.code - .iter_mut() - .find(|op| matches!(op, Op::Negate)) - .unwrap() = Op::Not; - } else { - let op = f - .code - .iter_mut() - .find(|op| matches!(op, Op::JumpIfFalse(_))) - .unwrap(); - if let Op::JumpIfFalse(t) = op { - *t -= 1; - } - } - let error = p.verify().unwrap_err(); - rows.push(serde_json::json!({"mutation":name,"error":error,"stdout":""})); - } - write_extra_evidence("semantic-corruptions", serde_json::json!({"cases":rows})); -} - -#[test] -fn scalar_addition_and_interpolation_preserve_source_types() { - let mut rows = Vec::new(); - for expression in ["7 + True", "None + 7", "7 + False"] { - let source = format!("# main\n**answer = {expression}**\n*answer*\n"); - let (path, module) = document("scalar-source-types", &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let tr = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let vr = vm.run(&program).unwrap_err(); - assert!(tr.to_string().contains("`+` needs ints, nums, or text")); - assert!(vr.to_string().contains("`+` needs ints, nums, or text")); - rows.push(serde_json::json!({"expression":expression,"source":source,"tree_error":tr.to_string(),"bytecode_error":vr.to_string()})); - } - let (path, mut module) = document("adjacent-interpolation-ast", "# main\n*0*\n"); - module.metadata = vec![("a".into(), Value::Int(7)), ("b".into(), Value::Int(3))]; - module.functions[0].body[0] = crate::ast::Stmt::Return { - value: crate::ast::Expr::Interp(vec![ - crate::ast::InterpPart::Var("a".into()), - crate::ast::InterpPart::Var("b".into()), - ]), - span: crate::diagnostics::Span::new(2, 1), - }; - let mut tree = Interpreter::with_capture(Some(&path), false); - let tr = tree.run_module(&module).unwrap(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let vr = vm.run(&program).unwrap(); - assert_eq!(tr, Value::Text("73".into())); - assert_eq!(vr, tr); - write_extra_evidence( - "primitive-regressions", - serde_json::json!({"cases":rows,"interpolation_ast":{"tree":local_json(&tr),"bytecode":local_json(&vr)}}), - ); -} - -#[test] -fn nested_foreach_uses_fresh_slots_and_preserves_authored_names() { - let source="# main\n`xs` =\n| value |\n|---|\n| 1 |\n| 2 |\n\n**__i_xs = 99**\n**total = 0**\n- [x](遍历 xs 为 x)\n - [y](遍历 xs 为 y)\n **total = total + 1**\n\n**answer = __i_xs * 10 + total**\n*answer*\n"; - both("nested-loop-hygiene", source, Value::Int(994), ""); -} - -#[test] -fn statement_and_prologue_changes_are_rejected_before_effects() { - use crate::bytecode::Op; - let source="# main\n**answer = > choose**\n> print text=\"AFTER\"\n*answer*\n\n## choose\n + `n`=7\n**value = n + 1**\n*value*\n"; - let (path, module) = document("statement-corruptions", source); - let p = compile_module(Some(&path), &module).unwrap(); - let fid = p.functions.iter().position(|f| f.name == "choose").unwrap(); - let mut rows = Vec::new(); - for mutation in [ - "wrong_default_target", - "missing_fill", - "wrong_assignment", - "wrong_return", - "extra_instruction", - ] { - let mut bad = p.clone(); - let f = &mut bad.functions[fid]; - match mutation { - "wrong_default_target" => { - if let Op::JumpIfProvided(_, target) = &mut f.code[0] { - *target = f.body_start; - } - } - "missing_fill" => { - let pc = f - .code - .iter() - .position(|op| matches!(op, Op::FillMissingParameters)) - .unwrap(); - f.code[pc] = Op::CheckArguments; - } - "wrong_assignment" => { - let value = f.locals.iter().position(|n| n == "value").unwrap(); - let n = f.locals.iter().position(|n| n == "n").unwrap(); - *f.code - .iter_mut() - .find(|op| **op == Op::SetLocal(value)) - .unwrap() = Op::SetLocal(n); - } - "wrong_return" => { - let pc = f - .code - .iter() - .position(|op| matches!(op, Op::Return)) - .unwrap(); - f.code[pc] = Op::Pop; - } - _ => { - f.code.push(Op::None_); - f.spans.push(f.declaration_span); - } - } - let error = bad.verify().unwrap_err(); - let mut vm = Vm::with_capture(Some(&path)); - assert!(vm.run(&bad).is_err()); - assert!(vm.captured_stdout.is_empty()); - rows.push( - serde_json::json!({"mutation":mutation,"error":error,"stdout":vm.captured_stdout}), - ); - } - write_extra_evidence("statement-corruptions", serde_json::json!({"cases":rows})); -} - -#[test] -fn while_iteration_limit_is_the_same_language_fault_on_both_backends() { - both("while-condition-effects", "# main\n**n = 2**\n- test(value=`n`)\n > print text=\"BODY\"\n **n = n - 1**\n*n*\n\n## test\n + `value`\n> print text=`value`\n**answer = value > 0**\n*answer*\n",Value::Int(0),"2\nBODY\n1\nBODY\n0\n"); - both( - "while-early-return", - "# main\n- True\n *7*\n> print text=\"UNREACHABLE\"\n*0*\n", - Value::Int(7), - "", - ); - both( - "while-normal", - "# main\n**n = 3**\n- `n` > 0\n **n = n - 1**\n*n*\n", - Value::Int(0), - "", - ); - let (path, mut module) = document("while-limit-ast", "# main\n*0*\n"); - module.functions[0].body = vec![crate::ast::Stmt::While { - condition: crate::ast::Expr::Literal(crate::ast::Literal::Bool(true)), - body: Vec::new(), - span: crate::diagnostics::Span::new(2, 1), - }]; - let mut tree = Interpreter::new(Some(&path), false); - let tr = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::new(Some(&path)); - let vr = vm.run(&program).unwrap_err(); - assert!(tr - .to_string() - .contains("while loop exceeded iteration limit")); - assert!(vr - .to_string() - .contains("while loop exceeded iteration limit")); - for error in [&tr, &vr] { - assert_eq!( - crate::diagnostics::Diagnostic::find(error) - .unwrap() - .span - .line, - 2 - ); - } - write_extra_evidence( - "while-limit", - serde_json::json!({"limit":1000000,"tree_error":tr.to_string(),"bytecode_error":vr.to_string(),"line":2,"input":"direct AST with literal-True empty while"}), - ); -} - -#[test] -fn dynamic_calls_keep_the_calling_module_scope() { - let (path, _) = document("dynamic-local-scope", "# main\n*0*\n"); - std::fs::write(path.parent().unwrap().join("a.mq.md"), "## hidden\n*99*\n").unwrap(); - let source="---\nimport:\n a: a.mq.md\n---\n## hidden\n*7*\n\n# main\n**answer = > call_fn name=\"hidden\"**\n*answer*\n"; - both("dynamic-local-scope", source, Value::Int(7), ""); - let denied="---\nimport:\n a: a.mq.md\n---\n# main\n**answer = > call_fn name=\"hidden\"**\n*answer*\n"; - std::fs::write(&path, denied).unwrap(); - let module = load_module(&path).unwrap(); - let mut tree = Interpreter::with_capture(Some(&path), false); - let tr = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let vr = vm.run(&program).unwrap_err(); - assert!(tr.to_string().contains("hidden")); - assert!(vr.to_string().contains("hidden")); - assert!(tree.captured_stdout.is_empty() && vm.captured_stdout.is_empty()); - write_extra_evidence( - "dynamic-import-refused", - serde_json::json!({"source":denied,"tree_error":tr.to_string(),"bytecode_error":vr.to_string(),"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout}), - ); -} - -#[test] -fn receiver_alias_defaults_use_logical_presence_and_restore_the_body_receiver() { - let method="## mark\n> print text=\"DEFAULT\"\n*9*\n\n# Box\n## m\n + `self`=> mark\n + `x`=`self`\n**answer = type(value=self) + \"|\" + type(value=x)**\n*answer*\n\n# main\n**box = > Box**\n"; - for (id, args, value, stdout) in [ - ("receiver-alias-omitted", "", "map|int", "DEFAULT\n"), - ("receiver-alias-none", " self=None", "map|map", ""), - ] { - let source = format!("{method}**answer = > `box`.m{args}**\n*answer*\n"); - both(id, &source, Value::Text(value.into()), stdout); - } - let mut cases = Vec::new(); - for (argument, expect_call_site) in - [("", false), (" self=None", false), (" self=\"bad\"", true)] - { - let source=format!("## mark\n*9*\n\n# Box\n## m\n + `self`=> mark\n + `x`=`self`\n\n| 参数 | 类型 |\n|---|---|\n| self | number |\n\n*x*\n\n# main\n**box = > Box**\n**answer = > `box`.m{argument}**\n*answer*\n"); - let (path, module) = document("receiver-alias-contract", &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let te = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let ve = vm.run(&program).unwrap_err(); - let t = crate::diagnostics::Diagnostic::find(&te).unwrap().to_json(); - let v = crate::diagnostics::Diagnostic::find(&ve).unwrap().to_json(); - assert_eq!(t["code"], "contract.arg_mismatch"); - assert_eq!(v["code"], t["code"]); - assert_eq!(t["span"], v["span"]); - assert_eq!(t["doc_anchor"], v["doc_anchor"]); - assert_eq!(t["source_sha256"], v["source_sha256"]); - assert_eq!(t["frames"], v["frames"]); - let line = if expect_call_site { 17 } else { 5 }; - assert_eq!(t["span"]["line"], line); - cases.push(serde_json::json!({"argument":argument,"source":source,"tree":t,"bytecode":v,"expected_line":line})); - } - write_extra_evidence( - "receiver-alias-contracts", - serde_json::json!({"cases":cases}), - ); -} - -#[test] -fn call_staging_checks_reject_layout_target_and_scratch_corruption() { - both("unreached-plugin", "# main\n*7*\n\n## unused_named\n> unknown_plugin z=7 a=3\n\n## unused_positional\n> unknown_plugin 9 3\n> input\n",Value::Int(7),""); - use crate::bytecode::{CallDispatch, Op}; - let source="# main\n> print text=\"PROBE\"\n**answer = combine(b=mark(2), a=mark(1))**\n*answer*\n\n## combine\n + `a`\n + `b`\n**n = a * 10 + b**\n*n*\n\n## mark\n + `value`\n*value*\n"; - let (path, module) = document("call-corruption", source); - let original = compile_module(Some(&path), &module).unwrap(); - let entry = original.entry; - let call = original.functions[entry] - .calls - .iter() - .position(|c| c.source.callee == "combine") - .unwrap(); - let target = original.functions[entry] - .calls - .iter() - .find_map(|c| { - if c.source.callee == "mark" { - match c.dispatch { - Some(CallDispatch::User { target, .. }) => Some(target), - _ => None, - } - } else { - None - } - }) - .unwrap(); - let mut cases = Vec::new(); - for mutation in [ - "target", - "layout", - "reload", - "scratch_store", - "source_alias", - "nested_alias", - "actual_order", - "uncovered_call", - ] { - let mut bad = original.clone(); - let f = &mut bad.functions[entry]; - let record = f.calls[call].clone(); - let node = &f.expressions[record.expression]; - match mutation { - "target" => { - let pc = (node.start..node.end) - .rev() - .find(|i| matches!(f.code[*i], Op::CallArgs(_, _))) - .unwrap(); - let Op::CallArgs(_, layout) = f.code[pc] else { - unreachable!() - }; - f.code[pc] = Op::CallArgs(target, layout); - } - "layout" => { - let Op::CallArgs(_, layout) = f.code[node.end - 1] else { - unreachable!() - }; - f.call_layouts[layout].swap(0, 1); - } - "reload" => { - let id = node.children[record.stages.len()]; - let pc = f.expressions[id].start; - let other = record.stages[1].slot; - f.code[pc] = Op::GetLocal(other); - f.expressions[id].rule = - crate::bytecode::ExpressionRule::Read(f.locals[other].clone()); - } - "scratch_store" => { - let pc = f.expressions[record.stages[0].expression].end; - f.code[pc] = Op::SetLocal(record.stages[1].slot); - } - "source_alias" => { - f.calls[call].stages[0].slot = 0; - } - "nested_alias" => { - let nested = f - .calls - .iter() - .position(|c| c.source.callee == "mark") - .unwrap(); - f.calls[nested].stages[0].slot = record.stages[0].slot; - } - "actual_order" => { - f.calls[call].stages.swap(0, 1); - } - "uncovered_call" => { - f.calls.remove(call); - } - _ => unreachable!(), - } - let mut vm = Vm::with_capture(Some(&path)); - let error = vm.run(&bad).unwrap_err().to_string(); - assert!( - error.contains("bytecode verification"), - "{mutation}: {error}" - ); - assert_eq!(vm.captured_stdout, ""); - cases.push( - serde_json::json!({"mutation":mutation,"error":error,"stdout":vm.captured_stdout}), - ); - } - for (mutation,source) in [ - ("host_identity","# main\n> print text=\"PROBE\"\n**answer = host_exists(path=\"unused\")**\n*answer*\n"), - ("method_name","# Box\n## m\n*7*\n\n# main\n> print text=\"PROBE\"\n**box = > Box**\n**answer = > `box`.m**\n*answer*\n"), - ("plugin_name","# main\n> print text=\"PROBE\"\n**answer = > unknown_plugin x=7**\n*answer*\n"), - ] { - let (path,module)=document(mutation,source);let mut bad=compile_module(Some(&path),&module).unwrap();let f=&mut bad.functions[bad.entry]; - for op in &mut f.code { - match op { - Op::HostCallArgs(id,_) if mutation=="host_identity"=>{*id=5;break;}, - Op::MethodCallArgs(id,_) if mutation=="method_name"=>{let index=f.constants.len();f.constants.push(Value::Text("other_method".into()));*id=index;break;}, - Op::PluginCallArgs(id,_) if mutation=="plugin_name"=>{let index=f.constants.len();f.constants.push(Value::Text("@other_plugin".into()));*id=index;break;}, - _=>{}, - } - } - let mut vm=Vm::with_capture(Some(&path));let error=vm.run(&bad).unwrap_err().to_string();assert!(error.contains("bytecode verification"),"{mutation}: {error}");assert_eq!(vm.captured_stdout,""); - cases.push(serde_json::json!({"mutation":mutation,"error":error,"stdout":vm.captured_stdout})); - } - write_extra_evidence("call-corruptions", serde_json::json!({"cases":cases})); -} - -#[test] -fn loaded_ast_refuses_coherently_forged_emission_witnesses() { - use crate::bytecode::{CallDispatch, ExpressionRule, Op, StatementRule}; - let (path, module) = document( - "source-witness-corruption", - "# main\n> print text=\"PROBE\"\n**n = 7**\n**m = 3**\n**result = n + m**\n*result*\n", - ); - let original = compile_module(Some(&path), &module).unwrap(); - let mut cases = Vec::new(); - for mutation in [ - "operator_and_rule", - "literal_and_rule", - "variable_and_rule", - "assignment_and_rule", - "orphan_expression", - ] { - let mut bad = original.clone(); - let f = &mut bad.functions[bad.entry]; - match mutation { - "operator_and_rule" => { - let e = f - .expressions - .iter_mut() - .find(|e| matches!(e.rule, ExpressionRule::Binary(crate::ast::BinaryOp::Add))) - .unwrap(); - e.rule = ExpressionRule::Binary(crate::ast::BinaryOp::Sub); - f.code[e.end - 1] = Op::Sub; - } - "literal_and_rule" => { - let e = f - .expressions - .iter_mut() - .find(|e| matches!(e.rule, ExpressionRule::Literal(Value::Int(7)))) - .unwrap(); - let Op::Constant(index) = f.code[e.start] else { - unreachable!() - }; - f.constants[index] = Value::Int(9); - e.rule = ExpressionRule::Literal(Value::Int(9)); - } - "variable_and_rule" => { - let e = f - .expressions - .iter_mut() - .find(|e| matches!(&e.rule,ExpressionRule::Read(name) if name=="result")) - .unwrap(); - let slot = f.locals.iter().position(|name| name == "m").unwrap(); - e.rule = ExpressionRule::Read("m".into()); - f.code[e.start] = Op::GetLocal(slot); - } - "assignment_and_rule" => { - let s = f - .statements - .iter_mut() - .find(|s| matches!(&s.rule,StatementRule::Assign(name) if name=="n")) - .unwrap(); - let slot = f.locals.iter().position(|name| name == "m").unwrap(); - s.rule = StatementRule::Assign("m".into()); - f.code[s.end - 2] = Op::SetLocal(slot); - } - "orphan_expression" => { - f.expressions.push( - f.expressions - .iter() - .find(|e| matches!(e.rule, ExpressionRule::Literal(Value::Int(7)))) - .unwrap() - .clone(), - ); - } - _ => unreachable!(), - } - let mut vm = Vm::with_capture(Some(&path)); - let error = vm.run(&bad).unwrap_err().to_string(); - assert!(error.contains("AST"), "{mutation}: {error}"); - assert_eq!(vm.captured_stdout, ""); - cases.push( - serde_json::json!({"mutation":mutation,"error":error,"stdout":vm.captured_stdout}), - ); - } - let (path,module)=document("source-call-witness-corruption","# main\n> print text=\"PROBE\"\n**answer = f(value=7)**\n*answer*\n\n## f\n + `value`\n*7*\n\n## g\n + `value`\n*3*\n"); - let mut bad = compile_module(Some(&path), &module).unwrap(); - let target = bad.functions.iter().position(|f| f.name == "g").unwrap(); - let f = &mut bad.functions[bad.entry]; - let call = f.calls.iter_mut().find(|c| c.source.callee == "f").unwrap(); - call.source.callee = "g".into(); - call.dispatch = Some(CallDispatch::User { - target, - tag_instance: false, - }); - let node = &f.expressions[call.expression]; - let Op::CallArgs(_, layout) = f.code[node.end - 1] else { - unreachable!() - }; - f.code[node.end - 1] = Op::CallArgs(target, layout); - let mut vm = Vm::with_capture(Some(&path)); - let error = vm.run(&bad).unwrap_err().to_string(); - assert!(error.contains("AST"), "{error}"); - assert_eq!(vm.captured_stdout, ""); - cases.push(serde_json::json!({"mutation":"callee_and_dispatch_witness","error":error,"stdout":vm.captured_stdout})); - for mutation in [ - "formula_bits_and_rule", - "index_key_and_rule", - "interpolation_and_rule", - ] { - use crate::ast::{Expr, IndexKey, InterpPart, Literal, Stmt}; - let (path, mut module) = document(mutation, "# main\n*0*\n"); - let span = crate::diagnostics::Span::new(2, 1); - let (prefix, value) = match mutation { - "formula_bits_and_rule" => ( - Vec::new(), - Expr::Formula(crate::formula::Expr::Num(f64::from_bits( - 0x7ff8_0000_0000_0001, - ))), - ), - "index_key_and_rule" => ( - vec![Stmt::Assign { - name: "m".into(), - value: Expr::Map(vec![ - ("a".into(), Expr::Literal(Literal::Int(7))), - ("b".into(), Expr::Literal(Literal::Int(3))), - ]), - span, - end_line: 2, - }], - Expr::Index { - base: Box::new(Expr::Var("m".into())), - label: IndexKey::Lit("a".into()), - }, - ), - _ => ( - vec![Stmt::Assign { - name: "n".into(), - value: Expr::Literal(Literal::Int(7)), - span, - end_line: 2, - }], - Expr::Interp(vec![ - InterpPart::Lit("ORIGINAL-".into()), - InterpPart::Var("n".into()), - ]), - ), - }; - module.functions[0].body = prefix; - module.functions[0].body.push(Stmt::Return { value, span }); - let mut bad = compile_module(Some(&path), &module).unwrap(); - let f = &mut bad.functions[bad.entry]; - match mutation { - "formula_bits_and_rule" => { - let e = f - .expressions - .iter_mut() - .find(|e| matches!(e.rule, ExpressionRule::Literal(Value::Formula(_)))) - .unwrap(); - let value = Value::Formula(crate::formula::Expr::Num(f64::from_bits( - 0x7ff8_0000_0000_0002, - ))); - let Op::Constant(index) = f.code[e.start] else { - unreachable!() - }; - f.constants[index] = value.clone(); - e.rule = ExpressionRule::Literal(value); - } - "index_key_and_rule" => { - let id = f - .expressions - .iter() - .position(|e| matches!(e.rule, ExpressionRule::Index { .. })) - .unwrap(); - let pc = f.expressions[f.expressions[id].children[0]].end; - let index = f.constants.len(); - f.constants.push(Value::Text("b".into())); - f.code[pc] = Op::Constant(index); - let ExpressionRule::Index { label, .. } = &mut f.expressions[id].rule else { - unreachable!() - }; - *label = IndexKey::Lit("b".into()); - } - _ => { - let e = f - .expressions - .iter_mut() - .find(|e| matches!(e.rule, ExpressionRule::Interpolation(_))) - .unwrap(); - let ExpressionRule::Interpolation(parts) = &mut e.rule else { - unreachable!() - }; - parts[0] = InterpPart::Lit("CHANGED-".into()); - let Op::Constant(index) = f.code[e.start] else { - unreachable!() - }; - f.constants[index] = Value::Text("CHANGED-".into()); - } - } - let mut vm = Vm::with_capture(Some(&path)); - let error = vm.run(&bad).unwrap_err().to_string(); - assert!(error.contains("AST"), "{mutation}: {error}"); - assert_eq!(vm.captured_stdout, ""); - cases.push(serde_json::json!({"mutation":mutation,"error":error,"stdout":vm.captured_stdout,"input":"direct AST; formula NaN payload bits, static index and interpolation component identity"})); - } - let (path, mut module) = document("source-contract-witness-corruption", "# main\n*7*\n"); - module.functions[0].contract = Some(crate::contract::Contract { - params: Vec::new(), - returns: Some(crate::contract::ReturnContract { - ty: crate::contract::Ty::Number, - desc: "must remain numeric".into(), - }), - fields: Vec::new(), - start_line: 1, - end_line: 1, - quote: vec!["return number".into()], - }); - let mut bad = compile_module(Some(&path), &module).unwrap(); - bad.functions[bad.entry] - .contract - .as_mut() - .unwrap() - .returns - .as_mut() - .unwrap() - .ty = crate::contract::Ty::Any; - let mut vm = Vm::with_capture(Some(&path)); - let error = vm.run(&bad).unwrap_err().to_string(); - assert!(error.contains("AST"), "{error}"); - assert_eq!(vm.captured_stdout, ""); - cases.push(serde_json::json!({"mutation":"contract_metadata","error":error,"stdout":vm.captured_stdout,"input":"direct AST contract; preserve contract presence but weaken Number to Any"})); - write_extra_evidence( - "source-witness-corruptions", - serde_json::json!({"cases":cases}), - ); -} - -#[test] -fn modifier_conflicts_are_runtime_faults_before_actual_effects() { - both( - "unreached-modifier-conflict", - "# main\n*7*\n\n## unused\n> 礼貌 [f] 礼貌=False\n\n## f\n*3*\n", - Value::Int(7), - "", - ); - both( - "modifier-valid", - "# main\n**answer = 礼貌 [f]**\n*answer*\n\n## f\n + `礼貌`\n*礼貌*\n", - Value::Bool(true), - "", - ); - both( - "modifier-alias-order", - "# main\n> 内容 [打印] 内容=False\n*7*\n", - Value::Int(7), - "False\n", - ); - let defaults = - "## choose\n + `value`=> 礼貌 [f] 礼貌=False\n*value*\n\n## f\n*3*\n\n# main\n"; - both( - "modifier-default-skipped", - &format!("{defaults}**answer = > choose value=7**\n*answer*\n"), - Value::Int(7), - "", - ); - both( - "modifier-default-none", - &format!("{defaults}**answer = > choose value=None**\n*answer*\n"), - Value::None, - "", - ); - let mut cases = Vec::new(); - for (id,source,wanted_stdout,line) in [ - ("modifier-reached","# main\n> print text=\"PREFIX\"\n**answer = 礼貌 [f] 礼貌=([mark] 2)**\n> print text=\"SUFFIX\"\n\n## mark\n + `value`\n> print text=\"ACTUAL\"\n*value*\n\n## f\n*3*\n".to_string(),"PREFIX\n",3), - ("modifier-default-omitted",format!("{defaults}**answer = > choose**\n*answer*\n"),"",2), - ] { - let (path,module)=document(id,&source); - if id=="modifier-reached" { - let crate::ast::Stmt::Assign{value:crate::ast::Expr::Call(call),..}=&module.functions[0].body[1] else{panic!("not a source call")}; - assert!(matches!(&call.args[0],crate::ast::Arg::Named{value:crate::ast::Expr::Call(_),..}),"probe must contain an actual effectful argument: {:?}",call.args); - } - let mut tree=Interpreter::with_capture(Some(&path),false);let te=tree.run_module(&module).unwrap_err(); - let program=compile_module(Some(&path),&module).unwrap();let mut vm=Vm::with_capture(Some(&path));let ve=vm.run(&program).unwrap_err(); - assert!(te.to_string().contains("pre-bracket modifier"));assert!(ve.to_string().contains("pre-bracket modifier")); - assert_eq!(tree.captured_stdout,wanted_stdout);assert_eq!(vm.captured_stdout,wanted_stdout); - let t=crate::diagnostics::Diagnostic::find(&te).unwrap().to_json();let v=crate::diagnostics::Diagnostic::find(&ve).unwrap().to_json(); - for key in ["code","message","span","source_sha256","frames"]{assert_eq!(t[key],v[key],"{id}: {key}");} - assert_eq!(t["span"]["line"],line); - cases.push(serde_json::json!({"id":id,"source":source,"tree":t,"bytecode":v,"stdout":wanted_stdout,"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout,"line":line})); - } - write_extra_evidence("modifier-faults", serde_json::json!({"cases":cases})); -} - -#[test] -fn native_call_binding_faults_preserve_effects_and_diagnostic_frames() { - let mut rows = Vec::new(); - for (id, call, trace, message) in [ - ( - "len-missing", - "len()", - "", - "missing argument for parameter `value`", - ), - ( - "len-extra", - "len(mark(1), mark(2))", - "1\n2\n", - "too many positional arguments (1 extra)", - ), - ( - "len-unknown-named", - "len(other=mark(1))", - "1\n", - "missing argument for parameter `value`", - ), - ( - "str-missing", - "str()", - "", - "missing argument for parameter `value`", - ), - ( - "print-missing", - "print()", - "", - "missing argument for parameter `text`", - ), - ( - "split-missing", - "split(mark(1))", - "1\n", - "missing argument for parameter `sep`", - ), - ( - "split-extra", - "split(mark(1), mark(2), mark(3))", - "1\n2\n3\n", - "too many positional arguments (1 extra)", - ), - ( - "at-missing", - "at(mark(1))", - "1\n", - "missing argument for parameter `index`", - ), - ( - "call-fn-missing", - "call_fn()", - "", - "missing argument for parameter `name`", - ), - ( - "host-missing", - "host_exists(extra=mark(1))", - "1\n", - "host_exists requires `path`", - ), - ( - "host-extra", - "host_now_unix(mark(1))", - "1\n", - "too many positional arguments (1 extra)", - ), - ( - "plugin-mixed", - "missing_plugin(mark(1), extra=mark(2))", - "1\n2\n", - "unknown function `missing_plugin`", - ), - ( - "unknown-path", - "missing_lib.f(value=mark(1))", - "1\n", - "unresolved dynamic call `missing_lib.f`", - ), - ( - "unknown-deep-path", - "missing_lib.Box.f(value=mark(1))", - "1\n", - "unknown `missing_lib.Box.f`", - ), - ( - "duplicate-builtin", - "len(value=mark(1), value=mark(2))", - "1\n2\n", - "duplicate named argument `value`", - ), - ( - "duplicate-host", - "host_now_unix(extra=mark(1), extra=mark(2))", - "1\n2\n", - "duplicate named argument `extra`", - ), - ( - "duplicate-unknown-plugin", - "missing_plugin(a=mark(1), a=mark(2))", - "1\n2\n", - "unknown function `missing_plugin`", - ), - ( - "duplicate-unknown-path", - "missing_lib.f(a=mark(1), a=mark(2))", - "1\n2\n", - "unresolved dynamic call `missing_lib.f`", - ), - ] { - let body = format!( - "> print text=\"PREFIX\"\n**answer = {call}**\n> print text=\"SUFFIX\"\n*answer*\n" - ); - let mark = "\n## mark\n + `value`\n> print text=`value`\n*value*\n"; - let unreached = format!("# main\n*7*\n\n## unused\n{body}{mark}"); - both( - &format!("call-fault-{id}-unreached"), - &unreached, - Value::Int(7), - "", - ); - let source = format!("# main\n{body}{mark}"); - let (path, module) = document(&format!("call-fault-{id}"), &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let te = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let ve = vm.run(&program).unwrap_err(); - let t = crate::diagnostics::Diagnostic::find(&te).unwrap().to_json(); - let v = crate::diagnostics::Diagnostic::find(&ve).unwrap().to_json(); - let wanted_stdout = format!("PREFIX\n{trace}"); - assert_eq!(t["message"], message, "{id}: source error"); - assert_eq!(tree.captured_stdout, wanted_stdout, "{id}: source trace"); - assert_eq!(vm.captured_stdout, wanted_stdout, "{id}: VM trace"); - for key in ["code", "message", "span", "source_sha256", "frames"] { - assert_eq!(t[key], v[key], "{id}: {key}"); - } - assert_eq!(t["span"]["line"], 3); - rows.push(serde_json::json!({"id":id,"source":source,"expected_message":message,"expected_stdout":wanted_stdout,"tree":t,"bytecode":v,"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout})); - } - write_extra_evidence("call-binding-faults", serde_json::json!({"cases":rows})); -} - -#[test] -fn path_dispatch_uses_runtime_presence_before_static_fallback() { - let definitions = "# Box\n## read\n*1*\n\n# Other\n## read\n*7*\n\n"; - both( - "path-bound-receiver", - &format!("{definitions}# main\n**Box = > Other**\n**answer = > Box.read**\n*answer*\n"), - Value::Int(7), - "", - ); - both( - "path-unbound-fallback", - &format!("{definitions}# main\n**answer = > Box.read**\n*answer*\n**Box = > Other**\n"), - Value::Int(1), - "", - ); -} - -#[cfg(feature = "plugin-host")] -#[test] -fn registered_plugins_bind_mixed_arguments_after_authored_effects() { - let source="# main\n**answer = binding_probe(mark(2), b=mark(3), ignored=mark(9))**\n*answer*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n"; - let (path, module) = document("plugin-native-binding", source); - let host = || { - let mut h = crate::host::HostContext::for_capture(Some(&path), Default::default()); - h.plugins.register_binding_probe(); - h - }; - let expected = Value::Map(vec![ - ("a".into(), Value::Int(2)), - ("b".into(), Value::Int(3)), - ("ignored".into(), Value::Int(9)), - ]); - let mut tree = Interpreter::with_capture(Some(&path), false).with_host(host()); - let t = tree.run_module(&module).unwrap(); - assert_eq!(t, expected); - assert_eq!(tree.captured_stdout, "2\n3\n9\n"); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)).with_host(host()); - let v = vm.run(&program).unwrap(); - assert_eq!(v, expected); - assert_eq!(vm.captured_stdout, "2\n3\n9\n"); - write_extra_evidence( - "registered-plugin-binding", - serde_json::json!({"source":source,"expected":local_json(&expected),"tree":local_json(&t),"bytecode":local_json(&v),"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout,"abi":"native-json-c"}), - ); -} - -#[test] -fn source_declaration_graph_rejects_coherent_target_and_order_corruption() { - use crate::bytecode::{CallDispatch, Op, PathFallback}; - let source="# main\n> print text=\"PROBE\"\n**answer = choose()**\n*answer*\n\n## choose\n*1*\n\n## other\n*2*\n"; - both("same-signature-targets", source, Value::Int(1), "PROBE\n"); - let (path, module) = document("name-graph-corruption", source); - let original = compile_module(Some(&path), &module).unwrap(); - let entry = original.entry; - let other = original - .functions - .iter() - .position(|f| f.name == "other") - .unwrap(); - let mut rows = Vec::new(); - for mutation in [ - "coherent-target", - "child-order", - "declaration-identity", - "scope", - "module-header", - "missing-root", - "object-name", - "method-name", - ] { - let mut bad = original.clone(); - match mutation { - "coherent-target" => { - let f = &mut bad.functions[entry]; - let c = f - .calls - .iter_mut() - .find(|c| c.source.callee == "choose") - .unwrap(); - c.dispatch = Some(CallDispatch::User { - target: other, - tag_instance: false, - }); - let e = &f.expressions[c.expression]; - let Op::CallArgs(_, layout) = f.code[e.end - 1] else { - panic!("native call") - }; - f.code[e.end - 1] = Op::CallArgs(other, layout); - } - "child-order" => bad.children[entry].reverse(), - "declaration-identity" => { - bad.functions[other].source_ast.declaration_path = - bad.functions[entry].source_ast.declaration_path.clone() - } - "scope" => bad.functions[other].module_scope = 99, - "module-header" => bad.functions[other] - .source_ast - .imports - .push("invented".into()), - "missing-root" => bad.functions[entry].source_ast.module_root_count += 1, - "object-name" => bad.objects[0].0 = "invented".into(), - "method-name" => bad.methods[0].1 = "invented".into(), - _ => unreachable!(), - } - let rejection = bad.verify().unwrap_err(); - let mut vm = Vm::with_capture(Some(&path)); - let error = vm.run(&bad).unwrap_err().to_string(); - assert!(error.contains(&rejection), "{mutation}: {error}"); - assert_eq!(vm.captured_stdout, ""); - rows.push( - serde_json::json!({"mutation":mutation,"error":error,"stdout":vm.captured_stdout}), - ); - } - let (path,module)=document("path-fallback-corruption","# Box\n## read\n*1*\n\n## other\n*2*\n\n# main\n> print text=\"PROBE\"\n**answer = > Box.read**\n*answer*\n"); - let mut bad = compile_module(Some(&path), &module).unwrap(); - let other = bad - .functions - .iter() - .position(|f| f.name == "other") - .unwrap(); - let call = bad.functions[bad.entry] - .calls - .iter_mut() - .find(|c| c.source.path.is_some()) - .unwrap(); - let Some(CallDispatch::Path { fallback, .. }) = &mut call.dispatch else { - panic!("path call") - }; - *fallback = PathFallback::User { - target: other, - tag_instance: false, - }; - let mut vm = Vm::with_capture(Some(&path)); - let error = vm.run(&bad).unwrap_err().to_string(); - assert!(error.contains("bytecode verification")); - assert_eq!(vm.captured_stdout, ""); - rows.push(serde_json::json!({"mutation":"coherent-path-fallback","error":error,"stdout":vm.captured_stdout})); - write_extra_evidence("name-graph-corruptions", serde_json::json!({"cases":rows})); -} - -#[test] -fn user_parameter_masks_preserve_fault_priority_and_actual_effects() { - let definitions="\n## choose\n + `a`=> mark value=9\n + `b`\n**answer = a * 10 + b**\n*answer*\n\n## mark\n + `value`\n> print text=`value`\n*value*\n"; - both( - "masked-default-binding", - &format!("# main\n**answer = choose(b=mark(2))**\n*answer*\n{definitions}"), - Value::Int(92), - "2\n9\n", - ); - both( - "named-before-positional", - &format!("# main\n**answer = choose(mark(1), a=mark(2))**\n*answer*\n{definitions}"), - Value::Int(21), - "1\n2\n", - ); - let mut rows = Vec::new(); - for (id, call, trace, message) in [ - ( - "user-surplus", - "choose(mark(1), mark(2), mark(3))", - "1\n2\n3\n", - "too many positional arguments (1 extra)", - ), - ( - "user-required-before-default", - "choose()", - "", - "missing argument for parameter `b`", - ), - ( - "user-duplicate", - "choose(a=mark(1), a=mark(2))", - "1\n2\n", - "duplicate named argument `a`", - ), - ] { - let body = format!( - "> print text=\"PREFIX\"\n**answer = {call}**\n> print text=\"SUFFIX\"\n*answer*\n" - ); - both( - &format!("{id}-unreached"), - &format!("# main\n*7*\n\n## unused\n{body}{definitions}"), - Value::Int(7), - "", - ); - let source = format!("# main\n{body}{definitions}"); - let (path, module) = document(id, &source); - let mut tree = Interpreter::with_capture(Some(&path), false); - let te = tree.run_module(&module).unwrap_err(); - let program = compile_module(Some(&path), &module).unwrap(); - let mut vm = Vm::with_capture(Some(&path)); - let ve = vm.run(&program).unwrap_err(); - let t = crate::diagnostics::Diagnostic::find(&te).unwrap().to_json(); - let v = crate::diagnostics::Diagnostic::find(&ve).unwrap().to_json(); - let wanted_stdout = format!("PREFIX\n{trace}"); - assert_eq!(t["message"], message); - assert_eq!(tree.captured_stdout, wanted_stdout); - assert_eq!(vm.captured_stdout, wanted_stdout); - for key in ["message", "code", "span", "source_sha256", "frames"] { - assert_eq!(t[key], v[key], "{id}: {key}"); - } - rows.push(serde_json::json!({"id":id,"source":source,"expected_message":message,"expected_stdout":wanted_stdout,"tree":t,"bytecode":v,"tree_stdout":tree.captured_stdout,"bytecode_stdout":vm.captured_stdout})); - } - write_extra_evidence("user-binding-faults", serde_json::json!({"cases":rows})); -} - -#[test] -fn argument_binding_plans_cover_parameter_masks_and_labels() { - let alphabet = [ - None, - Some("a".to_string()), - Some("b".to_string()), - Some("extra".to_string()), - ]; - let mut cases = Vec::new(); - for parameters in [ - vec![], - vec!["a"], - vec!["a", "b"], - vec!["a", "a"], - vec!["a", "b", "c"], - ] { - let params = parameters.iter().map(|p| p.to_string()).collect::>(); - for mask in 0..(1usize << params.len()) { - let omissions = (0..params.len()) - .map(|i| mask & (1 << i) != 0) - .collect::>(); - for size in 0..=4 { - for code in 0..4usize.pow(size as u32) { - let mut digits = code; - let mut names = Vec::new(); - for _ in 0..size { - names.push(alphabet[digits % 4].clone()); - digits /= 4; - } - cases.push(crate::arguments::plan_evidence(¶ms, &names, &omissions)); - } - } - } - } - assert_eq!(cases.len(), 6479, "complete mask/label corpus"); - write_extra_evidence("argument-binding-plans", serde_json::json!({"cases":cases})); -} diff --git a/src/host/agent_rt.rs b/src/host/agent_rt.rs deleted file mode 100755 index 30357c4..0000000 --- a/src/host/agent_rt.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Runtime helpers for ABI `host_query` and shared map/list ops. - -use std::path::{Path, PathBuf}; - -use crate::host::HostContext; -use crate::value::Value; - -impl HostContext { - pub fn set_entry_source(&mut self, path: Option<&Path>, source: &str) { - self.entry_source = Some(source.to_string()); - self.entry_path = path.map(|p| p.to_path_buf()); - } - - pub fn push_call_frame(&mut self, name: &str) { - self.call_stack.push(name.to_string()); - } - - pub fn pop_call_frame(&mut self) { - self.call_stack.pop(); - } -} - -pub fn module_source(ctx: &HostContext) -> Result { - Ok(match &ctx.entry_source { - Some(s) => Value::Text(s.clone()), - None => Value::Text(String::new()), - }) -} - -pub fn call_site(ctx: &HostContext, line: Option) -> Result { - let path = ctx - .entry_path - .as_ref() - .map(|p| p.display().to_string()) - .unwrap_or_default(); - let function = ctx - .call_stack - .last() - .cloned() - .unwrap_or_else(|| "main".into()); - let line_v = match line { - Some(n) => Value::Int(n as i64), - None => Value::None, - }; - Ok(Value::Map(vec![ - ("path".into(), Value::Text(path)), - ("function".into(), Value::Text(function)), - ("line".into(), line_v), - ])) -} - -pub fn marqdo_skill(ctx: &HostContext) -> Result { - let text = load_marqdo_skill(ctx)?; - Ok(Value::Text(text)) -} - -fn load_marqdo_skill(ctx: &HostContext) -> Result { - if let Ok(p) = std::env::var("MARQDO_SKILL") { - let path = PathBuf::from(p); - if path.is_file() { - return std::fs::read_to_string(&path) - .map_err(|e| format!("MARQDO_SKILL read {}: {e}", path.display())); - } - let skill = path.join("SKILL.md"); - if skill.is_file() { - return read_skill_pack(&path); - } - } - - for root in skill_search_roots(ctx) { - let pack = root.join("skills").join("marqdo"); - if pack.join("SKILL.md").is_file() { - return read_skill_pack(&pack); - } - if root.join("SKILL.md").is_file() && root.ends_with("marqdo") { - return read_skill_pack(&root); - } - } - Ok(String::new()) -} - -fn read_skill_pack(dir: &Path) -> Result { - let mut out = String::new(); - for name in ["SKILL.md", "reference.md", "examples.md"] { - let p = dir.join(name); - if p.is_file() { - let body = std::fs::read_to_string(&p) - .map_err(|e| format!("skill read {}: {e}", p.display()))?; - if !out.is_empty() { - out.push_str("\n\n---\n\n"); - } - out.push_str(&format!("# file: {name}\n\n")); - out.push_str(&body); - } - } - Ok(out) -} - -fn skill_search_roots(ctx: &HostContext) -> Vec { - let mut roots = Vec::new(); - if let Ok(exe) = std::env::current_exe() { - if let Some(dir) = exe.parent() { - roots.push(dir.to_path_buf()); - if let Some(parent) = dir.parent() { - roots.push(parent.to_path_buf()); - if let Some(repo) = parent.parent() { - roots.push(repo.to_path_buf()); - } - } - } - } - roots.push(ctx.cwd.clone()); - if let Some(p) = &ctx.entry_path { - if let Some(parent) = p.parent() { - roots.push(parent.to_path_buf()); - if let Some(repo) = parent.parent().and_then(|p| p.parent()) { - roots.push(repo.to_path_buf()); - } - } - } - if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") { - roots.push(PathBuf::from(manifest)); - } - roots -} - -pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result { - crate::host::collection::map_set(map, key, value) -} - -pub fn list_append(list: &Value, item: &Value) -> Result { - crate::host::collection::list_append(list, item) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn map_set_updates() { - let m = Value::Map(vec![("a".into(), Value::Int(1))]); - let m2 = map_set(&m, &Value::Text("a".into()), &Value::Int(2)).unwrap(); - assert_eq!(m2, Value::Map(vec![("a".into(), Value::Int(2))])); - } -} diff --git a/src/host/archive.rs b/src/host/archive.rs deleted file mode 100755 index 2a224e4..0000000 --- a/src/host/archive.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! Optional ZIP tasks with preflight, expansion limits and no path traversal. -use crate::{ - host::{HostContext, HostFn}, - value::Value, -}; -use std::collections::HashMap; -#[cfg(feature = "net-host")] -use std::{ - collections::HashSet, - fs, - io::{Read, Write}, - path::Path, -}; -type Args = HashMap; -#[cfg(feature = "net-host")] -fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { - b.get(k).ok_or_else(|| format!("missing {k}")) -} -pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { - #[cfg(feature = "net-host")] - let answer = operate(ctx, id, b); - #[cfg(not(feature = "net-host"))] - let answer = { - let _ = (ctx, id, b); - Err("ZIP unavailable: build with net-host (native default)".into()) - }; - Ok(super::result::capture( - if id == HostFn::ZipPack { - "archive.pack" - } else { - "archive.unpack" - }, - answer, - )) -} -#[cfg(feature = "net-host")] -fn operate(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { - if !ctx.allow_fs_write() { - return Err("filesystem write denied by host policy".into()); - } - if ctx.sandbox_session.is_some() { - return Err("ZIP unavailable in CoW sandbox".into()); - } - let src = ctx.resolve_path(super::as_text(arg(b, "src")?, "src")?)?; - let dest = ctx.resolve_path(super::as_text(arg(b, "dest")?, "dest")?)?; - let max = match arg(b, "max_bytes")? { - Value::Int(n) if *n > 0 && *n <= 1024 * 1024 * 1024 => *n as u64, - _ => return Err("max_bytes must be 1..1073741824".into()), - }; - if dest.exists() { - return Err("destination conflict: ZIP output must not exist".into()); - } - if id == HostFn::ZipPack { - if !src.is_dir() || dest.starts_with(&src) { - return Err("pack src must be directory and dest outside src".into()); - } - let mut args = HashMap::new(); - args.insert("path".into(), Value::Text(src.to_string_lossy().into())); - args.insert("pattern".into(), Value::Text("**".into())); - args.insert("exclude".into(), Value::None); - args.insert("max_depth".into(), Value::Int(256)); - args.insert("kind".into(), Value::Text("file".into())); - let Value::List(files) = super::fs_ops::call(ctx, HostFn::FsFind, &args)? else { - unreachable!() - }; - let total = files.iter().try_fold(0u64, |n, name| { - let p = src.join(super::as_text(name, "name")?); - let size = fs::metadata(p).map_err(|e| e.to_string())?.len(); - n.checked_add(size) - .ok_or_else(|| "archive size overflow".to_string()) - })?; - if total > max { - return Err("archive source exceeds max_bytes".into()); - } - let parent = dest.parent().ok_or("archive needs parent")?; - fs::create_dir_all(parent).map_err(|e| e.to_string())?; - let temp = parent.join(format!(".mq-zip-{}", random_name()?)); - let file = fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&temp) - .map_err(|e| e.to_string())?; - let written = (|| { - let mut writer = zip::ZipWriter::new(file); - let mut buffer = [0u8; 65536]; - let mut seen = 0u64; - for name in &files { - let name = super::as_text(name, "name")?; - writer - .start_file( - name, - zip::write::FileOptions::default() - .compression_method(zip::CompressionMethod::Deflated), - ) - .map_err(|e| e.to_string())?; - let p = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?; - let mut file = fs::File::open(p).map_err(|e| e.to_string())?; - loop { - let n = file.read(&mut buffer).map_err(|e| e.to_string())?; - if n == 0 { - break; - } - seen += n as u64; - if seen > max { - return Err("archive source grew past max_bytes".into()); - } - writer.write_all(&buffer[..n]).map_err(|e| e.to_string())?; - } - } - writer - .finish() - .map_err(|e| e.to_string())? - .sync_all() - .map_err(|e| e.to_string())?; - // hard_link is an atomic no-clobber publish on the same filesystem. - fs::hard_link(&temp, &dest).map_err(|e| e.to_string())?; - Ok(Value::Int(files.len() as i64)) - })(); - let _ = fs::remove_file(&temp); - return written; - } - let file = fs::File::open(src).map_err(|e| e.to_string())?; - let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; - if zip.len() > 100000 { - return Err("archive exceeds 100000 entries".into()); - } - let mut names = HashSet::new(); - let mut total = 0u64; - for i in 0..zip.len() { - let entry = zip.by_index(i).map_err(|e| e.to_string())?; - let name = entry - .enclosed_name() - .ok_or("archive path escapes destination")?; - if entry.name().contains('\\') || name == Path::new("") || !names.insert(name.to_path_buf()) - { - return Err("invalid or duplicate archive path".into()); - } - if entry - .unix_mode() - .is_some_and(|mode| mode & 0o170000 == 0o120000) - { - return Err("archive symlinks unsupported".into()); - } - total = total - .checked_add(entry.size()) - .ok_or("archive size overflow")?; - if total > max { - return Err("archive expansion exceeds max_bytes".into()); - } - } - fs::create_dir_all(dest.parent().ok_or("destination needs parent")?) - .map_err(|e| e.to_string())?; - fs::create_dir(&dest).map_err(|e| e.to_string())?; - let extracted = (|| { - let mut total = 0u64; - let mut buffer = [0u8; 65536]; - for i in 0..zip.len() { - let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; - let path = ctx.resolve_path( - dest.join(entry.enclosed_name().ok_or("invalid archive path")?) - .to_str() - .ok_or("non UTF-8 path")?, - )?; - if entry.is_dir() { - fs::create_dir_all(path).map_err(|e| e.to_string())?; - continue; - } - fs::create_dir_all(path.parent().ok_or("entry needs parent")?) - .map_err(|e| e.to_string())?; - let mut file = fs::OpenOptions::new() - .create_new(true) - .write(true) - .open(path) - .map_err(|e| e.to_string())?; - loop { - let n = entry.read(&mut buffer).map_err(|e| e.to_string())?; - if n == 0 { - break; - } - total += n as u64; - if total > max { - return Err("archive expansion exceeds max_bytes".into()); - } - file.write_all(&buffer[..n]).map_err(|e| e.to_string())?; - } - } - Ok(Value::Int(zip.len() as i64)) - })(); - if extracted.is_err() { - let _ = fs::remove_dir_all(&dest); - } - extracted -} -#[cfg(feature = "net-host")] -fn random_name() -> Result { - let mut bytes = [0u8; 16]; - getrandom::getrandom(&mut bytes).map_err(|e| e.to_string())?; - Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) -} diff --git a/src/host/cli.rs b/src/host/cli.rs deleted file mode 100755 index ae3d4ef..0000000 --- a/src/host/cli.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! CLI arg parsing for Mid M5 (`lib/cli`). - -use crate::host::HostContext; -use crate::value::Value; - -fn as_text_list(v: &Value) -> Result, String> { - match v { - Value::List(xs) => { - let mut out = Vec::new(); - for x in xs { - match x { - Value::Text(s) => out.push(s.clone()), - _ => return Err("cli.parse: args must be list of text".into()), - } - } - Ok(out) - } - Value::None => Ok(vec![]), - _ => Err("cli.parse: args needs list".into()), - } -} - -/// Parse `--key value` / `--key=value` / `--flag` / positionals into a map. -/// Positionals are stored under key `_` as a list. -pub fn parse(ctx: &HostContext, args: Option<&Value>) -> Result { - let argv = match args { - None | Some(Value::None) => ctx.argv.clone(), - Some(v) => as_text_list(v)?, - }; - let mut map: Vec<(String, Value)> = Vec::new(); - let mut positionals: Vec = Vec::new(); - let mut i = 0usize; - while i < argv.len() { - let a = &argv[i]; - if let Some(rest) = a.strip_prefix("--") { - if rest.is_empty() { - // bare `--` — remaining are positionals - i += 1; - while i < argv.len() { - positionals.push(Value::Text(argv[i].clone())); - i += 1; - } - break; - } - if let Some((k, v)) = rest.split_once('=') { - upsert(&mut map, k.to_string(), Value::Text(v.to_string())); - i += 1; - continue; - } - let key = rest.to_string(); - if i + 1 < argv.len() && !argv[i + 1].starts_with('-') { - upsert(&mut map, key, Value::Text(argv[i + 1].clone())); - i += 2; - } else { - upsert(&mut map, key, Value::Bool(true)); - i += 1; - } - } else if let Some(rest) = a.strip_prefix('-') { - // short flags: -abc → a/b/c True; -k val not special-cased beyond single letter groups - if rest.is_empty() { - positionals.push(Value::Text(a.clone())); - i += 1; - continue; - } - if rest.len() == 1 && i + 1 < argv.len() && !argv[i + 1].starts_with('-') { - upsert(&mut map, rest.to_string(), Value::Text(argv[i + 1].clone())); - i += 2; - } else { - for ch in rest.chars() { - upsert(&mut map, ch.to_string(), Value::Bool(true)); - } - i += 1; - } - } else { - positionals.push(Value::Text(a.clone())); - i += 1; - } - } - if !positionals.is_empty() { - upsert(&mut map, "_".into(), Value::List(positionals)); - } - Ok(Value::Map(map)) -} - -fn upsert(map: &mut Vec<(String, Value)>, key: String, value: Value) { - if let Some((_, slot)) = map.iter_mut().find(|(k, _)| *k == key) { - *slot = value; - } else { - map.push((key, value)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_flags() { - let ctx = HostContext::default(); - let args = Value::List(vec![ - Value::Text("--input".into()), - Value::Text("a.csv".into()), - Value::Text("x".into()), - Value::Text("--verbose".into()), - ]); - let m = parse(&ctx, Some(&args)).unwrap(); - match m { - Value::Map(entries) => { - assert!(entries - .iter() - .any(|(k, v)| k == "input" && *v == Value::Text("a.csv".into()))); - assert!(entries - .iter() - .any(|(k, v)| k == "verbose" && *v == Value::Bool(true))); - assert!(entries - .iter() - .any(|(k, v)| k == "_" && matches!(v, Value::List(_)))); - } - _ => panic!("map"), - } - } -} diff --git a/src/host/collection.rs b/src/host/collection.rs deleted file mode 100755 index 9f02c89..0000000 --- a/src/host/collection.rs +++ /dev/null @@ -1,616 +0,0 @@ -//! List / map collection primitives for `lib/table` (and json compat aliases). - -use crate::value::Value; - -#[derive(Clone)] -enum PathSeg { - Key(String), - /// 1-based list index (aligned with footnote `[^1]`). - Index1(usize), -} - -fn path_segments(at: &Value) -> Result, String> { - match at { - Value::Text(s) => Ok(vec![PathSeg::Key(s.clone())]), - Value::Int(n) => { - if *n < 1 { - return Err("put path index must be >= 1 (1-based)".into()); - } - Ok(vec![PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?)]) - } - Value::List(xs) => { - if xs.is_empty() { - return Err("put path must not be empty".into()); - } - let mut out = Vec::with_capacity(xs.len()); - for (i, seg) in xs.iter().enumerate() { - match seg { - Value::Text(s) => out.push(PathSeg::Key(s.clone())), - Value::Int(n) => { - if *n < 1 { - return Err(format!( - "put path segment {i}: index must be >= 1 (1-based)" - )); - } - out.push(PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?)); - } - _ => { - return Err(format!( - "put path segment {i}: need text key or int index" - )); - } - } - } - Ok(out) - } - _ => Err("put at= needs text, int, or list path".into()), - } -} - -/// Deep put: `in` collection, `at` path (1-based ints), `value` leaf. -/// `in=None` + single text key → new one-entry map. -pub fn collection_put(input: &Value, at: &Value, value: &Value) -> Result { - let path = path_segments(at)?; - if matches!(input, Value::None) { - if path.len() == 1 { - if let PathSeg::Key(k) = &path[0] { - return Ok(Value::Map(vec![(k.clone(), value.clone())])); - } - } - return Err("put in=None only allowed with a single text key".into()); - } - put_rec(input, &path, value) -} - -fn put_rec(cur: &Value, path: &[PathSeg], value: &Value) -> Result { - let Some((head, rest)) = path.split_first() else { - return Ok(value.clone()); - }; - if rest.is_empty() { - return put_leaf(cur, head, value); - } - match head { - PathSeg::Key(k) => { - let Value::Map(entries) = cur else { - return Err(format!("put: expected map at key `{k}`")); - }; - let child = entries - .iter() - .find(|(kk, _)| kk == k) - .map(|(_, v)| v.clone()) - .ok_or_else(|| format!("put: missing key `{k}` on path"))?; - let new_child = put_rec(&child, rest, value)?; - map_set(cur, &Value::Text(k.clone()), &new_child) - } - PathSeg::Index1(i1) => { - let Value::List(xs) = cur else { - return Err(format!("put: expected list at index {i1}")); - }; - let i0 = i1 - 1; - if i0 >= xs.len() { - return Err(format!("put: list index {i1} out of range (len {})", xs.len())); - } - let new_child = put_rec(&xs[i0], rest, value)?; - list_set_at(cur, i0 as i64, &new_child) - } - } -} - -fn put_leaf(cur: &Value, head: &PathSeg, value: &Value) -> Result { - match head { - PathSeg::Key(k) => map_set(cur, &Value::Text(k.clone()), value), - PathSeg::Index1(i1) => { - let i0 = (*i1 as i64) - 1; - list_set_at(cur, i0, value) - } - } -} - -pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result { - let k = match key { - Value::Text(s) => s.clone(), - _ => return Err("map_set key must be text".into()), - }; - match map { - Value::Map(entries) => { - let mut out = entries.clone(); - if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| *kk == k) { - *slot = value.clone(); - } else { - out.push((k, value.clone())); - } - Ok(Value::Map(out)) - } - Value::None => Ok(Value::Map(vec![(k, value.clone())])), - _ => Err("map_set needs map".into()), - } -} - -pub fn map_get(map: &Value, key: &Value) -> Result { - let k = match key { - Value::Text(s) => s.as_str(), - _ => return Err("map_get key must be text".into()), - }; - match map { - Value::Map(entries) => Ok(entries - .iter() - .find(|(kk, _)| kk == k) - .map(|(_, v)| v.clone()) - .unwrap_or(Value::None)), - Value::None => Ok(Value::None), - _ => Err("map_get needs map".into()), - } -} - -pub fn map_delete(map: &Value, key: &Value) -> Result { - let k = match key { - Value::Text(s) => s.as_str(), - _ => return Err("map_delete key must be text".into()), - }; - match map { - Value::Map(entries) => { - let out: Vec<_> = entries.iter().filter(|(kk, _)| kk != k).cloned().collect(); - Ok(Value::Map(out)) - } - Value::None => Ok(Value::Map(vec![])), - _ => Err("map_delete needs map".into()), - } -} - -pub fn map_has(map: &Value, key: &Value) -> Result { - let k = match key { - Value::Text(s) => s.as_str(), - _ => return Err("map_has key must be text".into()), - }; - match map { - Value::Map(entries) => Ok(Value::Bool(entries.iter().any(|(kk, _)| kk == k))), - Value::None => Ok(Value::Bool(false)), - _ => Err("map_has needs map".into()), - } -} - -pub fn map_keys(map: &Value) -> Result { - match map { - Value::Map(entries) => Ok(Value::List( - entries - .iter() - .map(|(k, _)| Value::Text(k.clone())) - .collect(), - )), - Value::None => Ok(Value::List(vec![])), - _ => Err("map_keys needs map".into()), - } -} - -pub fn map_values(map: &Value) -> Result { - match map { - Value::Map(entries) => Ok(Value::List(entries.iter().map(|(_, v)| v.clone()).collect())), - Value::None => Ok(Value::List(vec![])), - _ => Err("map_values needs map".into()), - } -} - -pub fn map_items(map: &Value) -> Result { - match map { - Value::Map(entries) => { - let rows: Vec = entries - .iter() - .map(|(k, v)| { - Value::Map(vec![ - ("key".into(), Value::Text(k.clone())), - ("value".into(), v.clone()), - ]) - }) - .collect(); - Ok(Value::List(rows)) - } - Value::None => Ok(Value::List(vec![])), - _ => Err("map_items needs map".into()), - } -} - -pub fn map_merge(left: &Value, right: &Value) -> Result { - let mut out = match left { - Value::Map(e) => e.clone(), - Value::None => vec![], - _ => return Err("map_merge left needs map".into()), - }; - let right_entries = match right { - Value::Map(e) => e, - Value::None => return Ok(Value::Map(out)), - _ => return Err("map_merge right needs map".into()), - }; - for (k, v) in right_entries { - if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| kk == k) { - *slot = v.clone(); - } else { - out.push((k.clone(), v.clone())); - } - } - Ok(Value::Map(out)) -} - -pub fn map_size(map: &Value) -> Result { - match map { - Value::Map(entries) => Ok(Value::Int(entries.len() as i64)), - Value::None => Ok(Value::Int(0)), - _ => Err("map_size needs map".into()), - } -} - -pub fn list_append(list: &Value, item: &Value) -> Result { - match list { - Value::List(xs) => { - let mut out = xs.clone(); - out.push(item.clone()); - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![item.clone()])), - _ => Err("list_append needs list".into()), - } -} - -pub fn list_prepend(list: &Value, item: &Value) -> Result { - match list { - Value::List(xs) => { - let mut out = vec![item.clone()]; - out.extend(xs.iter().cloned()); - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![item.clone()])), - _ => Err("list_prepend needs list".into()), - } -} - -pub fn list_concat(a: &Value, b: &Value) -> Result { - let left = match a { - Value::List(xs) => xs.clone(), - Value::None => vec![], - _ => return Err("list_concat left needs list".into()), - }; - let right = match b { - Value::List(xs) => xs, - Value::None => return Ok(Value::List(left)), - _ => return Err("list_concat right needs list".into()), - }; - let mut out = left; - out.extend(right.iter().cloned()); - Ok(Value::List(out)) -} - -pub fn list_insert(list: &Value, index: i64, item: &Value) -> Result { - let mut xs = match list { - Value::List(xs) => xs.clone(), - Value::None => vec![], - _ => return Err("list_insert needs list".into()), - }; - if index < 0 || index > xs.len() as i64 { - return Err(format!( - "list_insert index {index} out of range (len {})", - xs.len() - )); - } - xs.insert(index as usize, item.clone()); - Ok(Value::List(xs)) -} - -pub fn list_set_at(list: &Value, index: i64, item: &Value) -> Result { - let Value::List(xs) = list else { - return Err("list_set_at needs list".into()); - }; - if index < 0 || index >= xs.len() as i64 { - return Err(format!( - "list_set_at index {index} out of range (len {})", - xs.len() - )); - } - let mut out = xs.clone(); - out[index as usize] = item.clone(); - Ok(Value::List(out)) -} - -pub fn list_remove_at(list: &Value, index: i64) -> Result { - let Value::List(xs) = list else { - return Err("list_remove_at needs list".into()); - }; - if index < 0 || index >= xs.len() as i64 { - return Err(format!( - "list_remove_at index {index} out of range (len {})", - xs.len() - )); - } - let mut out = xs.clone(); - out.remove(index as usize); - Ok(Value::List(out)) -} - -pub fn list_slice(list: &Value, start: i64, end: Option) -> Result { - let Value::List(xs) = list else { - return Err("list_slice needs list".into()); - }; - let n = xs.len() as i64; - let s = start.clamp(0, n) as usize; - let e = end.unwrap_or(n).clamp(0, n) as usize; - if e < s { - return Ok(Value::List(vec![])); - } - Ok(Value::List(xs[s..e].to_vec())) -} - -pub fn list_contains(list: &Value, item: &Value) -> Result { - match list { - Value::List(xs) => Ok(Value::Bool(xs.iter().any(|x| x == item))), - Value::None => Ok(Value::Bool(false)), - _ => Err("list_contains needs list".into()), - } -} - -pub fn list_index_of(list: &Value, item: &Value) -> Result { - match list { - Value::List(xs) => Ok(xs - .iter() - .position(|x| x == item) - .map(|i| Value::Int(i as i64)) - .unwrap_or(Value::None)), - Value::None => Ok(Value::None), - _ => Err("list_index_of needs list".into()), - } -} - -pub fn list_reverse(list: &Value) -> Result { - match list { - Value::List(xs) => { - let mut out = xs.clone(); - out.reverse(); - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![])), - _ => Err("list_reverse needs list".into()), - } -} - -pub fn list_first(list: &Value) -> Result { - match list { - Value::List(xs) => Ok(xs.first().cloned().unwrap_or(Value::None)), - Value::None => Ok(Value::None), - _ => Err("list_first needs list".into()), - } -} - -pub fn list_last(list: &Value) -> Result { - match list { - Value::List(xs) => Ok(xs.last().cloned().unwrap_or(Value::None)), - Value::None => Ok(Value::None), - _ => Err("list_last needs list".into()), - } -} - -/// Total type order avoids cyclic comparisons between numeric and text keys. -pub(super) fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering { - use std::cmp::Ordering; - fn rank(v:&Value)->u8{match v{ - Value::Int(_)|Value::Num(_)=>0,Value::Text(_)=>1,Value::Bool(_)=>2, - Value::None=>3,Value::List(_)=>4,Value::Map(_)=>5,Value::Formula(_)=>6, - Value::Code(_)=>7,Value::Secret(_)=>8,Value::Handle(_)=>9, - }} - fn int_float(integer:i64,number:f64)->Ordering{ - if number.is_nan(){return Ordering::Less} - if number >= -(i64::MIN as f64){return Ordering::Less} - if number < i64::MIN as f64{return Ordering::Greater} - let truncated=number as i64; - match integer.cmp(&truncated){Ordering::Equal=>0.0f64.partial_cmp(&number.fract()).unwrap_or(Ordering::Equal),other=>other} - } - let order=rank(a).cmp(&rank(b));if !order.is_eq(){return order} - match (a,b){ - (Value::Int(a),Value::Int(b))=>a.cmp(b), - (Value::Num(a),Value::Num(b))=>match(a.is_nan(),b.is_nan()){ - (true,false)=>Ordering::Greater,(false,true)=>Ordering::Less, - _=>a.partial_cmp(b).unwrap_or_else(||a.total_cmp(b)), - }, - (Value::Int(a),Value::Num(b))=>int_float(*a,*b), - (Value::Num(a),Value::Int(b))=>int_float(*b,*a).reverse(), - (Value::Text(a),Value::Text(b))=>a.cmp(b), - (Value::Bool(a),Value::Bool(b))=>a.cmp(b), - _=>a.as_display().cmp(&b.as_display()), - } -} - -pub fn list_sort(list: &Value) -> Result { - match list { - Value::List(xs) => { - let mut out = xs.clone(); - out.sort_by(cmp_value); - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![])), - _ => Err("list_sort needs list".into()), - } -} - -pub fn list_sort_by(list: &Value, key: &Value) -> Result { - let key = match key { - Value::Text(s) => s.as_str(), - _ => return Err("sort_by key needs text".into()), - }; - match list { - Value::List(xs) => { - let mut out = xs.clone(); - out.sort_by(|a, b| { - let ka = match a { - Value::Map(m) => m - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v) - .unwrap_or(&Value::None), - _ => &Value::None, - }; - let kb = match b { - Value::Map(m) => m - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v) - .unwrap_or(&Value::None), - _ => &Value::None, - }; - cmp_value(ka, kb) - }); - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![])), - _ => Err("list_sort_by needs list".into()), - } -} - -pub fn list_unique(list: &Value) -> Result { - match list { - Value::List(xs) => { - let mut out: Vec = Vec::new(); - let mut seen: std::collections::HashMap> = std::collections::HashMap::new(); - for x in xs { - let bucket = seen.entry(super::collection_ops::fingerprint(x)).or_default(); - if !bucket.iter().any(|i| out[*i] == *x) { - bucket.push(out.len()); - out.push(x.clone()); - } - } - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![])), - _ => Err("list_unique needs list".into()), - } -} - -pub fn list_chunk(list: &Value, size: &Value) -> Result { - let n = match size { - Value::Int(i) if *i > 0 => usize::try_from(*i).unwrap_or(usize::MAX), - Value::Int(_) => return Err("chunk size must be positive".into()), - _ => return Err("chunk size needs int".into()), - }; - match list { - Value::List(xs) => { - let mut out = Vec::new(); - let mut i = 0; - while i < xs.len() { - let end = (i + n).min(xs.len()); - out.push(Value::List(xs[i..end].to_vec())); - i = end; - } - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![])), - _ => Err("list_chunk needs list".into()), - } -} - -pub fn list_zip(a: &Value, b: &Value) -> Result { - let (aa, bb) = match (a, b) { - (Value::List(x), Value::List(y)) => (x, y), - (Value::None, Value::List(y)) => (&Vec::new(), y), - (Value::List(x), Value::None) => (x, &Vec::new()), - (Value::None, Value::None) => return Ok(Value::List(vec![])), - _ => return Err("list_zip needs two lists".into()), - }; - let n = aa.len().min(bb.len()); - let mut out = Vec::with_capacity(n); - for i in 0..n { - out.push(Value::List(vec![aa[i].clone(), bb[i].clone()])); - } - Ok(Value::List(out)) -} - -pub fn list_flatten(list: &Value) -> Result { - match list { - Value::List(xs) => { - let mut out = Vec::new(); - for x in xs { - match x { - Value::List(inner) => out.extend(inner.iter().cloned()), - other => out.push(other.clone()), - } - } - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![])), - _ => Err("list_flatten needs list".into()), - } -} - -pub fn collection_clear(value: &Value) -> Result { - match value { - Value::List(_) | Value::None => Ok(Value::List(vec![])), - Value::Map(_) => Ok(Value::Map(vec![])), - _ => Err("clear needs list or map".into()), - } -} - -fn require_i64(v: &Value, name: &str) -> Result { - match v { - Value::Int(n) => Ok(*n), - _ => Err(format!("{name} must be int")), - } -} - -/// Bind helper used by dispatch for optional end=. -pub fn list_slice_bound(list: &Value, start: &Value, end: Option<&Value>) -> Result { - let s = require_i64(start, "start")?; - let e = match end { - None | Some(Value::None) => None, - Some(v) => Some(require_i64(v, "end")?), - }; - list_slice(list, s, e) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn put_map_key_and_nested() { - let m = Value::Map(vec![("a".into(), Value::Int(1))]); - let m2 = collection_put(&m, &Value::Text("b".into()), &Value::Int(2)).unwrap(); - assert!(matches!(map_get(&m2, &Value::Text("b".into())).unwrap(), Value::Int(2))); - - let rows = Value::List(vec![Value::Map(vec![("qty".into(), Value::Int(1))])]); - let path = Value::List(vec![Value::Int(1), Value::Text("qty".into())]); - let rows2 = collection_put(&rows, &path, &Value::Int(9)).unwrap(); - let row = match &rows2 { - Value::List(xs) => &xs[0], - _ => panic!(), - }; - assert!(matches!( - map_get(row, &Value::Text("qty".into())).unwrap(), - Value::Int(9) - )); - } - - #[test] - fn put_none_single_key() { - let m = collection_put(&Value::None, &Value::Text("k".into()), &Value::Text("v".into())) - .unwrap(); - assert!(matches!(m, Value::Map(_))); - } -} - -#[cfg(test)] -mod task_scale_tests { - use super::*; - #[test] - fn unique_preserves_signed_zero_nan_and_nested_equality(){ - let xs=Value::List(vec![Value::Num(-0.0),Value::Num(0.0),Value::Num(f64::NAN),Value::Num(f64::NAN),Value::Int(0),Value::List(vec![Value::Num(-0.0)]),Value::List(vec![Value::Num(0.0)])]); - let Value::List(out)=list_unique(&xs).unwrap()else{panic!()}; - assert_eq!(out.len(),5);assert_eq!(out[0],Value::Num(-0.0));assert_eq!(out[3],Value::Int(0)); - } - #[test] - fn mixed_order_is_transitive_and_exact_at_integer_float_boundary(){ - let values=[Value::Int(2),Value::Int(10),Value::Text("11".into()),Value::Int(i64::MAX),Value::Num(i64::MAX as f64),Value::Num(f64::NAN),Value::Num(-0.0),Value::Bool(false),Value::None]; - for a in &values{for b in &values{for c in &values{ - if cmp_value(a,b).is_le()&&cmp_value(b,c).is_le(){assert!(cmp_value(a,c).is_le(),"{a:?} {b:?} {c:?}");} - }}} - assert!(cmp_value(&Value::Int(i64::MAX),&Value::Num(i64::MAX as f64)).is_lt()); - } - #[test] - fn bulk_unique_handles_one_hundred_thousand_values(){ - let xs=Value::List((0..100_000).map(|n|Value::Int(n%50_000)).collect()); - let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};assert_eq!(out.len(),50_000); - } -} diff --git a/src/host/collection_ops.rs b/src/host/collection_ops.rs deleted file mode 100755 index 1f7ad9d..0000000 --- a/src/host/collection_ops.rs +++ /dev/null @@ -1,584 +0,0 @@ -//! Field-driven collection transforms. No string evaluation or callback language. -use super::{as_text, collection::cmp_value}; -use crate::{ - host::{HostContext, HostFn}, - value::Value, -}; -use std::collections::{HashMap, HashSet}; - -type Args = HashMap; -fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { - b.get(k).ok_or_else(|| format!("missing {k}")) -} -fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> { - as_text(arg(b, k)?, k) -} -fn list(v: &Value) -> Result<&[Value], String> { - match v { - Value::List(xs) => Ok(xs), - _ => Err("expected list".into()), - } -} -fn record(v: &Value) -> Result<&[(String, Value)], String> { - match v { - Value::Map(m) => Ok(m), - _ => Err("expected record map".into()), - } -} -fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> { - record(v)? - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v) - .ok_or_else(|| format!("missing field {key}")) -} -fn strings(v: &Value) -> Result, String> { - list(v)? - .iter() - .map(|v| as_text(v, "key").map(str::to_owned)) - .collect() -} -fn integer(v: &Value) -> Result { - match v { - Value::Int(n) => Ok(*n), - _ => Err("expected integer".into()), - } -} -fn number(v: &Value) -> Result { - match v { - Value::Int(n) => Ok(*n as f64), - Value::Num(n) if n.is_finite() => Ok(*n), - _ => Err("expected finite number".into()), - } -} -fn row(fields: Vec<(&str, Value)>) -> Value { - Value::Map(fields.into_iter().map(|(k, v)| (k.into(), v)).collect()) -} -// Structural equality is type-sensitive and map-order-sensitive, like Value::eq. -// Fingerprints accelerate buckets; equality is still checked inside each bucket. -pub(super) fn fingerprint(v: &Value) -> String { - match v { - Value::Num(n) if *n == 0.0 => "Num(0)".into(), - Value::List(xs) => format!("List{:?}", xs.iter().map(fingerprint).collect::>()), - Value::Map(xs) => format!( - "Map{:?}", - xs.iter() - .map(|(k, v)| (k, fingerprint(v))) - .collect::>() - ), - Value::Formula(formula) => format!("Formula{}", formula.as_display()), - _ => format!("{v:?}"), - } -} - -pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { - match id { - HostFn::ListRange => { - let start = integer(arg(b, "start")?)?; - let end = integer(arg(b, "end")?)?; - let step = integer(arg(b, "step")?)?; - if step == 0 { - return Err("range step cannot be zero".into()); - } - let mut out = Vec::new(); - let mut n = start; - while if step > 0 { n < end } else { n > end } { - if out.len() >= 1_000_000 { - return Err("range exceeds 1000000 items".into()); - } - out.push(Value::Int(n)); - match n.checked_add(step) { - Some(next) => n = next, - None => break, - } - } - Ok(Value::List(out)) - } - HostFn::ListEnumerate => { - let start = integer(arg(b, "start")?)?; - let out = list(arg(b, "list")?)? - .iter() - .enumerate() - .map(|(i, v)| { - let index = start - .checked_add(i as i64) - .ok_or("enumerate index overflow")?; - Ok(row(vec![ - ("index", Value::Int(index)), - ("value", v.clone()), - ])) - }) - .collect::, String>>()?; - Ok(Value::List(out)) - } - HostFn::ListPluck => { - let key = text(b, "key")?; - Ok(Value::List( - list(arg(b, "list")?)? - .iter() - .map(|v| field(v, key).cloned()) - .collect::>()?, - )) - } - HostFn::ListProject => { - let keys = strings(arg(b, "keys")?)?; - if keys.iter().collect::>().len() != keys.len() { - return Err("project keys must be unique".into()); - } - let out = list(arg(b, "list")?)? - .iter() - .map(|v| { - keys.iter() - .map(|k| Ok((k.clone(), field(v, k)?.clone()))) - .collect::, String>>() - .map(Value::Map) - }) - .collect::>()?; - Ok(Value::List(out)) - } - HostFn::ListWhere => { - let key = text(b, "key")?; - let op = text(b, "op")?; - let wanted = arg(b, "value")?; - if !matches!( - op, - "eq" | "ne" | "gt" | "ge" | "lt" | "le" | "contains" | "in" - ) { - return Err(format!("unknown where operator {op}")); - } - let mut out = Vec::new(); - for v in list(arg(b, "list")?)? { - let got = field(v, key)?; - let yes = match op { - "eq" => got == wanted, - "ne" => got != wanted, - "gt" | "ge" | "lt" | "le" => { - let order = match (got, wanted) { - (Value::Text(a), Value::Text(b)) => a.cmp(b), - _ => number(got)? - .partial_cmp(&number(wanted)?) - .ok_or("unordered comparison")?, - }; - match op { - "gt" => order.is_gt(), - "ge" => order.is_ge(), - "lt" => order.is_lt(), - _ => order.is_le(), - } - } - "contains" => match got { - Value::List(xs) => xs.contains(wanted), - Value::Text(s) => s.contains(as_text(wanted, "value")?), - _ => return Err("contains needs text or list".into()), - }, - "in" => list(wanted)?.contains(got), - _ => return Err(format!("unknown where operator {op}")), - }; - if yes { - out.push(v.clone()) - } - } - Ok(Value::List(out)) - } - HostFn::ListGroupBy | HostFn::ListUniqueBy => { - let key = text(b, "key")?; - let mut groups: Vec<(Value, Vec)> = Vec::new(); - let mut index: HashMap> = HashMap::new(); - for v in list(arg(b, "list")?)? { - let k = field(v, key)?; - let fp = fingerprint(k); - let bucket = index.entry(fp).or_default(); - if let Some(i) = bucket.iter().find(|i| groups[**i].0 == *k) { - groups[*i].1.push(v.clone()); - } else { - bucket.push(groups.len()); - groups.push((k.clone(), vec![v.clone()])); - } - } - Ok(Value::List( - groups - .into_iter() - .map(|(key, rows)| { - if id == HostFn::ListUniqueBy { - rows.into_iter().next().unwrap() - } else { - row(vec![ - ("key", key), - ("count", Value::Int(rows.len() as i64)), - ("rows", Value::List(rows)), - ]) - } - }) - .collect(), - )) - } - HostFn::ListAggregate => { - let xs = list(arg(b, "list")?)?; - let op = text(b, "op")?; - if op == "count" { - return Ok(Value::Int(xs.len() as i64)); - } - let key = arg(b, "key")?; - let values = xs - .iter() - .map(|v| { - if matches!(key, Value::None) { - Ok(v) - } else { - field(v, as_text(key, "key")?) - } - }) - .collect::, String>>()?; - if op == "sum" && values.iter().all(|v| matches!(v, Value::Int(_))) { - let sum = values.into_iter().try_fold(0i64, |sum, v| { - sum.checked_add(integer(v)?) - .ok_or_else(|| "sum integer overflow".to_string()) - })?; - return Ok(Value::Int(sum)); - } - let nums = values - .into_iter() - .map(number) - .collect::, _>>()?; - let n = match op { - "sum" => nums.iter().sum(), - "mean" if !nums.is_empty() => nums.iter().sum::() / nums.len() as f64, - "min" if !nums.is_empty() => nums.iter().copied().fold(f64::INFINITY, f64::min), - "max" if !nums.is_empty() => nums.iter().copied().fold(f64::NEG_INFINITY, f64::max), - _ => { - return Err( - "aggregate needs sum/count/min/max/mean; empty min/max/mean is invalid" - .into(), - ) - } - }; - if !n.is_finite() { - return Err("aggregate overflow".into()); - } - Ok(Value::Num(n)) - } - HostFn::ListSortKeys => { - let keys = strings(arg(b, "keys")?)?; - let descending = matches!(arg(b, "descending")?, Value::Bool(true)); - let mut xs = list(arg(b, "list")?)?.to_vec(); - for v in &xs { - for k in &keys { - field(v, k)?; - } - } - xs.sort_by(|a, b| { - let mut order = std::cmp::Ordering::Equal; - for k in &keys { - order = cmp_value(field(a, k).unwrap(), field(b, k).unwrap()); - if !order.is_eq() { - break; - } - } - if descending { - order.reverse() - } else { - order - } - }); - Ok(Value::List(xs)) - } - HostFn::ListRename => { - let names = record(arg(b, "fields")?)?; - for (_, v) in names { - as_text(v, "new field name")?; - } - let mut out = Vec::new(); - for v in list(arg(b, "list")?)? { - let mut seen = HashSet::new(); - let mut fields = Vec::new(); - for (k, v) in record(v)? { - let name = names - .iter() - .find(|(old, _)| old == k) - .map(|(_, v)| as_text(v, "name").unwrap()) - .unwrap_or(k); - if !seen.insert(name) { - return Err(format!("rename conflict: {name}")); - } - fields.push((name.into(), v.clone())); - } - out.push(Value::Map(fields)); - } - Ok(Value::List(out)) - } - HostFn::TableFromColumns => { - let columns = record(arg(b, "columns")?)?; - let n = columns - .first() - .map(|(_, v)| list(v).map(|xs| xs.len())) - .transpose()? - .unwrap_or(0); - for (_, v) in columns { - if list(v)?.len() != n { - return Err("column lengths differ".into()); - } - } - Ok(Value::List( - (0..n) - .map(|i| { - Value::Map( - columns - .iter() - .map(|(k, v)| (k.clone(), list(v).unwrap()[i].clone())) - .collect(), - ) - }) - .collect(), - )) - } - HostFn::TableToColumns => { - let rows = list(arg(b, "rows")?)?; - if rows.is_empty() { - return Ok(Value::Map(vec![])); - } - let keys: Vec<_> = record(&rows[0])?.iter().map(|(k, _)| k.clone()).collect(); - for v in rows { - let fields = record(v)?; - if fields.len() != keys.len() - || keys.iter().any(|k| !fields.iter().any(|(f, _)| f == k)) - { - return Err("rows have different fields".into()); - } - } - Ok(Value::Map( - keys.into_iter() - .map(|k| { - let values = rows.iter().map(|v| field(v, &k).unwrap().clone()).collect(); - (k, Value::List(values)) - }) - .collect(), - )) - } - HostFn::ListJoin => { - let a = list(arg(b, "a")?)?; - let b_rows = list(arg(b, "b")?)?; - let key = text(b, "key")?; - let right_key = text(b, "right_key")?; - let mode = text(b, "mode")?; - if !matches!(mode, "inner" | "left") { - return Err("join mode must be inner or left".into()); - } - let mut index: HashMap> = HashMap::new(); - for v in b_rows { - index - .entry(fingerprint(field(v, right_key)?)) - .or_default() - .push(v); - } - let right_fields: Vec<_> = b_rows - .first() - .map(|v| record(v).map(|m| m.iter().map(|(k, _)| k.clone()).collect())) - .transpose()? - .unwrap_or_default(); - for right in b_rows { - let fields = record(right)?; - if fields.len() != right_fields.len() - || right_fields - .iter() - .any(|key| !fields.iter().any(|(k, _)| k == key)) - { - return Err("join right rows have different fields".into()); - } - } - let mut out = Vec::new(); - for left in a { - let left_key = field(left, key)?; - let hits = index.get(&fingerprint(left_key)); - let matches: Vec> = match hits { - Some(h) => { - let values: Vec<_> = h - .iter() - .filter(|v| field(v, right_key).is_ok_and(|key| key == left_key)) - .map(|v| Some(*v)) - .collect(); - if values.is_empty() && mode == "left" { - vec![None] - } else { - values - } - } - None if mode == "left" => vec![None], - _ => vec![], - }; - for hit in matches { - let mut fields = record(left)?.to_vec(); - let source = hit.map(record).transpose()?; - for k in &right_fields { - if k == right_key && key == right_key { - continue; - } - let name = if fields.iter().any(|(f, _)| f == k) { - format!("right_{k}") - } else { - k.clone() - }; - if fields.iter().any(|(f, _)| f == &name) { - return Err(format!("join field conflict: {name}")); - } - let value = source - .and_then(|m| m.iter().find(|(f, _)| f == k)) - .map(|(_, v)| v.clone()) - .unwrap_or(Value::None); - fields.push((name, value)); - } - if out.len() >= 1_000_000 { - return Err("join exceeds 1000000 rows".into()); - } - out.push(Value::Map(fields)); - } - } - Ok(Value::List(out)) - } - HostFn::TableCast => { - let schema = record(arg(b, "schema")?)?; - let mut out = Vec::new(); - for (i, v) in list(arg(b, "rows")?)?.iter().enumerate() { - let mut fields = record(v)?.to_vec(); - for (k, ty) in schema { - let value = field(v, k)?; - let ty = as_text(ty, "type")?; - let cast = cast(value, ty).map_err(|e| format!("row {i} field {k}: {e}"))?; - fields.iter_mut().find(|(name, _)| name == k).unwrap().1 = cast; - } - out.push(Value::Map(fields)); - } - Ok(Value::List(out)) - } - HostFn::TableSummarize => { - let groups = call(_ctx, HostFn::ListGroupBy, b)?; - let field_name = text(b, "field")?; - let op = text(b, "op")?; - let mut out = Vec::new(); - for group in list(&groups)? { - let rows = field(group, "rows")?; - let mut args = HashMap::new(); - args.insert("list".into(), rows.clone()); - args.insert("key".into(), Value::Text(field_name.into())); - args.insert("op".into(), Value::Text(op.into())); - let value = call(_ctx, HostFn::ListAggregate, &args)?; - out.push(row(vec![ - ("key", field(group, "key")?.clone()), - ("count", field(group, "count")?.clone()), - ("value", value), - ])); - } - Ok(Value::List(out)) - } - HostFn::TableTryCast => { - let answer = - call(_ctx, HostFn::TableCast, b).map_err(|e| format!("validation_failed: {e}")); - Ok(super::result::capture("table.cast", answer)) - } - HostFn::TableValidate => { - let rows = list(arg(b, "rows")?)?; - let schema = record(arg(b, "schema")?)?; - let mut errors = Vec::new(); - for (index, value) in rows.iter().enumerate() { - let fields = record(value)?; - for (key, ty) in schema { - let name = as_text(ty, "type")?; - let ty = crate::contract::Ty::parse(name); - let got = fields.iter().find(|(k, _)| k == key).map(|(_, v)| v); - if !got.is_some_and(|v| ty.matches_value(v)) { - errors.push(row(vec![ - ("row", Value::Int(index as i64)), - ("field", Value::Text(key.clone())), - ("expected", Value::Text(name.into())), - ( - "actual", - Value::Text( - got.map(crate::contract::type_of) - .unwrap_or("missing") - .into(), - ), - ), - ])); - } - } - } - if errors.is_empty() { - Ok(super::result::capture( - "table.validate", - Ok(arg(b, "rows")?.clone()), - )) - } else { - let mut result = super::result::capture( - "table.validate", - Err("validation_failed: records do not match schema".into()), - ); - if let Value::Map(fields) = &mut result { - if let Some((_, Value::Map(error))) = - fields.iter_mut().find(|(k, _)| k == "error") - { - error.push(("details".into(), Value::List(errors))); - } - } - Ok(result) - } - } - HostFn::ListUnion | HostFn::ListIntersection | HostFn::ListDifference => { - let left = list(arg(b, "a")?)?; - let right = list(arg(b, "b")?)?; - let mut index: HashMap> = HashMap::new(); - for v in right { - index.entry(fingerprint(v)).or_default().push(v) - } - let mut values = Vec::new(); - for v in left { - let contains = index - .get(&fingerprint(v)) - .is_some_and(|bucket| bucket.iter().any(|r| *r == v)); - if id == HostFn::ListUnion - || (id == HostFn::ListIntersection && contains) - || (id == HostFn::ListDifference && !contains) - { - values.push(v.clone()) - } - } - if id == HostFn::ListUnion { - values.extend_from_slice(right) - } - super::collection::list_unique(&Value::List(values)) - } - _ => Err("not a collection transform".into()), - } -} -fn cast(v: &Value, ty: &str) -> Result { - match ty { - "text" => Ok(Value::Text(v.as_display())), - "int" => match v { - Value::Int(_) => Ok(v.clone()), - Value::Text(s) => s - .parse::() - .map(Value::Int) - .map_err(|_| "invalid integer".into()), - _ => Err("int expects integer or text".into()), - }, - "number" => { - let n = match v { - Value::Text(s) => s.parse::().map_err(|_| "invalid number")?, - _ => number(v)?, - }; - if !n.is_finite() { - return Err("non-finite number".into()); - } - Ok(Value::Num(n)) - } - "bool" => match v { - Value::Bool(_) => Ok(v.clone()), - Value::Text(s) => match s.as_str() { - "true" | "True" => Ok(Value::Bool(true)), - "false" | "False" => Ok(Value::Bool(false)), - _ => Err("invalid bool".into()), - }, - _ => Err("bool expects bool or text".into()), - }, - "any" => Ok(v.clone()), - _ => Err(format!("unknown cast type {ty}")), - } -} diff --git a/src/host/csv.rs b/src/host/csv.rs deleted file mode 100755 index 5b04f67..0000000 --- a/src/host/csv.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! Minimal RFC4180 CSV for Mid M4 (`lib/csv`). - -use crate::host::as_text; -use crate::value::Value; - - -/// Parse CSV text into a list of maps (first row = headers). -pub fn parse(text: &Value) -> Result { - let s = as_text(text, "text")?; - let rows = parse_rows(s)?; - if rows.is_empty() { - return Ok(Value::List(vec![])); - } - let headers = rows[0].clone(); - if headers.is_empty() { - return Err("csv.parse: header row is empty".into()); - } - let mut out = Vec::new(); - for row in rows.into_iter().skip(1) { - let mut map = Vec::new(); - for (i, key) in headers.iter().enumerate() { - let val = row.get(i).cloned().unwrap_or_default(); - map.push((key.clone(), Value::Text(val))); - } - out.push(Value::Map(map)); - } - Ok(Value::List(out)) -} - -/// Serialize list of maps to CSV (header order = first row's keys). -pub fn stringify(rows: &Value) -> Result { - let list = match rows { - Value::List(xs) => xs, - _ => return Err("csv.stringify: rows needs list".into()), - }; - if list.is_empty() { - return Ok(Value::Text(String::new())); - } - let first = match &list[0] { - Value::Map(m) => m, - _ => return Err("csv.stringify: each row needs map".into()), - }; - let headers: Vec = first.iter().map(|(k, _)| k.clone()).collect(); - let mut lines = Vec::new(); - lines.push(headers.iter().map(|h| escape_field(h)).collect::>().join(",")); - for row in list { - let map = match row { - Value::Map(m) => m, - _ => return Err("csv.stringify: each row needs map".into()), - }; - let mut fields = Vec::new(); - for h in &headers { - let cell = map - .iter() - .find(|(k, _)| k == h) - .map(|(_, v)| value_to_cell(v)) - .unwrap_or_default(); - fields.push(escape_field(&cell)); - } - lines.push(fields.join(",")); - } - Ok(Value::Text(lines.join("\n"))) -} - -fn value_to_cell(v: &Value) -> String { - match v { - Value::Text(s) => s.clone(), - Value::Int(n) => n.to_string(), - Value::Num(n) => n.to_string(), - Value::Bool(b) => { - if *b { - "True".into() - } else { - "False".into() - } - } - Value::None => String::new(), - other => other.as_display(), - } -} - -fn escape_field(s: &str) -> String { - if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') { - format!("\"{}\"", s.replace('"', "\"\"")) - } else { - s.to_string() - } -} - -fn parse_rows(input: &str) -> Result>, String> { - let mut rows = Vec::new(); - let mut row = Vec::new(); - let mut field = String::new(); - let mut chars = input.chars().peekable(); - let mut in_quotes = false; - while let Some(c) = chars.next() { - if in_quotes { - if c == '"' { - if chars.peek() == Some(&'"') { - chars.next(); - field.push('"'); - } else { - in_quotes = false; - } - } else { - field.push(c); - } - } else { - match c { - '"' => in_quotes = true, - ',' => { - row.push(std::mem::take(&mut field)); - } - '\r' => { - // swallow optional \n - if chars.peek() == Some(&'\n') { - chars.next(); - } - row.push(std::mem::take(&mut field)); - rows.push(std::mem::take(&mut row)); - } - '\n' => { - row.push(std::mem::take(&mut field)); - rows.push(std::mem::take(&mut row)); - } - _ => field.push(c), - } - } - } - if in_quotes { - return Err("csv.parse: unterminated quote".into()); - } - if !field.is_empty() || !row.is_empty() { - row.push(field); - rows.push(row); - } else if !input.is_empty() && input.ends_with('\n') { - // trailing newline already flushed last row - } - // Drop a single trailing empty row produced by final newline only when last row empty? - while rows.last().is_some_and(|r| r.len() == 1 && r[0].is_empty()) { - // only drop if it's a spurious empty line at end with no fields - if rows.len() > 1 { - rows.pop(); - } else { - break; - } - } - Ok(rows) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn roundtrip_simple() { - let text = Value::Text("a,b\n1,2\n3,\"x,y\"\n".into()); - let rows = parse(&text).unwrap(); - let Value::List(ref xs) = rows else { - panic!("list"); - }; - assert_eq!(xs.len(), 2); - let out = stringify(&rows).unwrap(); - let again = parse(&out).unwrap(); - assert_eq!(again, rows); - } -} diff --git a/src/host/data_ops.rs b/src/host/data_ops.rs deleted file mode 100755 index 30c17bd..0000000 --- a/src/host/data_ops.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Recoverable parsing and timezone operations at the public data boundary. -use crate::{ - host::{HostContext, HostFn}, - value::Value, -}; -use std::collections::HashMap; -fn arg<'a>(b: &'a HashMap, k: &str) -> Result<&'a Value, String> { - b.get(k).ok_or_else(|| format!("missing {k}")) -} -pub(super) fn call( - _ctx: &mut HostContext, - id: HostFn, - b: &HashMap, -) -> Result { - match id { - HostFn::TomlStringify => super::toml_ops::stringify(arg(b, "value")?), - HostFn::TomlTryParse => Ok(super::result::capture( - "toml.parse", - super::toml_ops::parse(arg(b, "text")?).map_err(|e| format!("invalid_toml: {e}")), - )), - HostFn::DatetimeLocal => Ok(super::result::capture( - "datetime.parse_local", - super::datetime::local(arg(b, "text")?, arg(b, "zone")?, arg(b, "ambiguity")?), - )), - HostFn::DatetimeCalendarAdd => Ok(super::result::capture( - "datetime.add_calendar", - super::datetime::calendar_add(arg(b, "dt")?, arg(b, "days")?, arg(b, "ambiguity")?), - )), - _ => Err("not a data operation".into()), - } -} diff --git a/src/host/datetime.rs b/src/host/datetime.rs deleted file mode 100755 index b74f310..0000000 --- a/src/host/datetime.rs +++ /dev/null @@ -1,337 +0,0 @@ -//! Calendar moments with fixed offsets or embedded IANA timezone rules. -//! -//! Moments retain `{unix, zone, iso}`; `zone` is the numeric offset. -//! Named zones additionally retain `timezone`, so future instants and calendar -//! arithmetic recompute offsets using embedded IANA/DST rules. - -use crate::host::as_text; -use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc, Offset, LocalResult}; - -use crate::value::Value; - -fn as_i64(v: &Value, label: &str) -> Result { - match v { - Value::Int(n) => Ok(*n), - _ => Err(format!("{label} must be int")), - } -} - - -fn optional_i64(v: Option<&Value>, label: &str) -> Result { - match v { - None | Some(Value::None) => Ok(0), - Some(x) => as_i64(x, label), - } -} - -fn format_offset(off: FixedOffset) -> String { - let secs = off.local_minus_utc(); - let sign = if secs >= 0 { '+' } else { '-' }; - let abs = secs.abs(); - let h = abs / 3600; - let m = (abs % 3600) / 60; - format!("{sign}{h:02}:{m:02}") -} - -fn parse_zone(s: &str) -> Result { - let s = s.trim(); - if s.is_empty() || s.eq_ignore_ascii_case("utc") || s.eq_ignore_ascii_case("gmt") || s == "Z" { - return FixedOffset::east_opt(0).ok_or_else(|| "invalid UTC offset".into()); - } - // Common fixed-offset IANA aliases (no DST). - let aliased = match s { - "Asia/Shanghai" | "Asia/Hong_Kong" | "Asia/Taipei" | "Asia/Singapore" => Some(8 * 3600), - "Asia/Tokyo" | "Asia/Seoul" => Some(9 * 3600), - "Asia/Kolkata" | "Asia/Calcutta" => Some(5 * 3600 + 30 * 60), - "Europe/Moscow" => Some(3 * 3600), - "America/Phoenix" => Some(-7 * 3600), - "Pacific/Honolulu" => Some(-10 * 3600), - _ => None, - }; - if let Some(secs) = aliased { - return FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone: {s}")); - } - let (sign, rest) = if let Some(r) = s.strip_prefix('+') { - (1i32, r) - } else if let Some(r) = s.strip_prefix('-') { - (-1i32, r) - } else { - return Err(format!( - "unknown zone {s:?}; use +HH:MM / -HH:MM / UTC or a fixed-offset alias (e.g. Asia/Shanghai)" - )); - }; - let (hh, mm) = if let Some((h, m)) = rest.split_once(':') { - ( - h.parse::() - .map_err(|_| format!("bad zone hour in {s}"))?, - m.parse::() - .map_err(|_| format!("bad zone minute in {s}"))?, - ) - } else if rest.len() == 4 && rest.chars().all(|c| c.is_ascii_digit()) { - ( - rest[..2] - .parse::() - .map_err(|_| format!("bad zone hour in {s}"))?, - rest[2..] - .parse::() - .map_err(|_| format!("bad zone minute in {s}"))?, - ) - } else if rest.len() == 2 && rest.chars().all(|c| c.is_ascii_digit()) { - ( - rest.parse::() - .map_err(|_| format!("bad zone hour in {s}"))?, - 0, - ) - } else { - return Err(format!("bad zone offset {s}")); - }; - if !(0..=14).contains(&hh) || !(0..60).contains(&mm) { - return Err(format!("zone offset out of range: {s}")); - } - let secs = sign * (hh * 3600 + mm * 60); - FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone offset: {s}")) -} - -fn moment(unix: i64, zone: FixedOffset) -> Result { - let dt = zone - .timestamp_opt(unix, 0) - .single() - .ok_or_else(|| format!("invalid unix timestamp: {unix}"))?; - Ok(Value::Map(vec![ - ("unix".into(), Value::Int(unix)), - ("zone".into(), Value::Text(format_offset(zone))), - ( - "iso".into(), - Value::Text(dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)), - ), - ])) -} - -fn zone_of_moment(m: &[(String, Value)]) -> Result { - for (k, v) in m { - if k == "zone" { - return parse_zone(as_text(v, "zone")?); - } - } - Ok(FixedOffset::east_opt(0).unwrap()) -} - -fn unix_of_value(v: &Value) -> Result<(i64, FixedOffset), String> { - match v { - Value::Int(n) => Ok((*n, FixedOffset::east_opt(0).unwrap())), - Value::Map(entries) => { - let mut unix = None; - for (k, val) in entries { - if k == "unix" { - unix = Some(as_i64(val, "unix")?); - } - } - let unix = unix.ok_or_else(|| "datetime map needs unix".to_string())?; - let offset = if let Some((_, Value::Text(zone))) = entries.iter().find(|(k,_)|k=="timezone") { - let zone: chrono_tz::Tz = zone.parse().map_err(|_| format!("unknown IANA timezone {zone}"))?; - zone.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.offset().fix() - } else { zone_of_moment(entries)? }; - Ok((unix, offset)) - } - Value::Text(s) => { - // Treat bare ISO/RFC3339 text as a moment. - let parsed = parse_text(s, None)?; - unix_of_value(&parsed) - } - _ => Err("datetime needs int unix, moment map, or ISO text".into()), - } -} - -pub fn now() -> Result { - #[cfg(target_arch = "wasm32")] - { - return Err("datetime.now unavailable in browser wasm (no clock bridge yet)".into()); - } - #[cfg(not(target_arch = "wasm32"))] - { - let secs = Utc::now().timestamp(); - moment(secs, FixedOffset::east_opt(0).unwrap()) - } -} - -pub fn from_unix(unix: &Value, zone: Option<&Value>) -> Result { - let secs = as_i64(unix, "unix")?; - match zone { - None | Some(Value::None) => moment(secs, FixedOffset::east_opt(0).unwrap()), - Some(zone) => moment_in_zone(secs, as_text(zone,"zone")?), - } -} - -pub fn to_unix(dt: &Value) -> Result { - let (secs, _) = unix_of_value(dt)?; - Ok(Value::Int(secs)) -} - -fn parse_text(text: &str, pattern: Option<&str>) -> Result { - if let Some(pat) = pattern { - if pat.eq_ignore_ascii_case("rfc3339") || pat.eq_ignore_ascii_case("iso") { - return parse_rfc3339(text); - } - if let Ok(dt) = DateTime::parse_from_str(text, pat) { - return moment(dt.timestamp(), *dt.offset()); - } - let naive = NaiveDateTime::parse_from_str(text, pat) - .or_else(|_| { - NaiveDate::parse_from_str(text, pat).map(|d| d.and_hms_opt(0, 0, 0).unwrap()) - }) - .map_err(|e| format!("datetime.parse: {e}"))?; - return moment(naive.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap()); - } - if let Ok(v) = parse_rfc3339(text) { - return Ok(v); - } - if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S") { - return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap()); - } - if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S") { - return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap()); - } - if let Ok(d) = NaiveDate::parse_from_str(text, "%Y-%m-%d") { - let dt = d.and_hms_opt(0, 0, 0).unwrap(); - return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap()); - } - Err(format!( - "datetime.parse: unrecognized {text:?}; pass pattern= or use RFC3339 / YYYY-MM-DD" - )) -} - -fn parse_rfc3339(text: &str) -> Result { - let dt = DateTime::parse_from_rfc3339(text).map_err(|e| format!("datetime.parse: {e}"))?; - moment(dt.timestamp(), *dt.offset()) -} - -pub fn parse(text: &Value, pattern: Option<&Value>) -> Result { - let t = as_text(text, "text")?; - let pat = match pattern { - None | Some(Value::None) => None, - Some(p) => Some(as_text(p, "pattern")?), - }; - parse_text(t, pat) -} - -pub fn format(dt: &Value, style: Option<&Value>) -> Result { - let (secs, zone) = unix_of_value(dt)?; - let local = zone - .timestamp_opt(secs, 0) - .single() - .ok_or_else(|| format!("invalid unix timestamp: {secs}"))?; - let style = match style { - None | Some(Value::None) => "rfc3339", - Some(s) => as_text(s, "style")?, - }; - let out = match style { - "rfc3339" | "iso" => local.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - "date" => local.format("%Y-%m-%d").to_string(), - "time" => local.format("%H:%M:%S").to_string(), - other => local.format(other).to_string(), - }; - Ok(Value::Text(out)) -} - -pub fn add( - dt: &Value, - days: Option<&Value>, - hours: Option<&Value>, - minutes: Option<&Value>, - seconds: Option<&Value>, -) -> Result { - let (secs, zone) = unix_of_value(dt)?; - let days = optional_i64(days, "days")?; - let hours = optional_i64(hours, "hours")?; - let minutes = optional_i64(minutes, "minutes")?; - let seconds = optional_i64(seconds, "seconds")?; - let delta = days.checked_mul(86400).and_then(|n|hours.checked_mul(3600).and_then(|h|n.checked_add(h))) - .and_then(|n|minutes.checked_mul(60).and_then(|m|n.checked_add(m))).and_then(|n|n.checked_add(seconds)) - .ok_or("datetime.add overflow")?; - let new_secs = secs.checked_add(delta).ok_or("datetime.add overflow")?; - if let Some(zone) = named_zone(dt) { moment_in_zone(new_secs,zone) } else { moment(new_secs,zone) } -} - -pub fn in_zone(dt: &Value, zone: &Value) -> Result { - let (secs, _) = unix_of_value(dt)?; - moment_in_zone(secs, as_text(zone,"zone")?) -} - -fn named_zone(dt:&Value)->Option<&str>{ - let Value::Map(fields)=dt else{return None}; - fields.iter().find_map(|(k,v)|if k=="timezone"{if let Value::Text(zone)=v{Some(zone.as_str())}else{None}}else{None}) -} -fn moment_in_zone(unix:i64,zone:&str)->Result{ - if let Ok(tz)=zone.parse::(){ - let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?; - let mut value=moment(unix,local.offset().fix())?; - if let Value::Map(fields)=&mut value{fields.push(("timezone".into(),Value::Text(zone.into())));} - Ok(value) - }else{moment(unix,parse_zone(zone)?)} -} -fn choose_local(tz:chrono_tz::Tz,local:NaiveDateTime,ambiguity:&str)->Result{ - if !matches!(ambiguity,"reject"|"earliest"|"latest"){return Err("ambiguity must be reject/earliest/latest".into())} - match tz.from_local_datetime(&local){ - LocalResult::Single(dt)=>Ok(dt.timestamp()), - LocalResult::None=>Err("nonexistent_time: local time is in a DST gap".into()), - LocalResult::Ambiguous(a,b)=>match ambiguity{ - "earliest"=>Ok(a.timestamp().min(b.timestamp())), - "latest"=>Ok(a.timestamp().max(b.timestamp())), - _=>Err("ambiguous_time: DST fold; select earliest or latest".into()), - } - } -} -pub(super) fn local(text:&Value,zone:&Value,ambiguity:&Value)->Result{ - let source=as_text(text,"text")?.replace('T'," "); - let local=NaiveDateTime::parse_from_str(&source,"%Y-%m-%d %H:%M:%S").map_err(|e|format!("datetime.parse_local: {e}"))?; - let zone=as_text(zone,"zone")?;let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?; - moment_in_zone(choose_local(tz,local,as_text(ambiguity,"ambiguity")?)?,zone) -} -pub(super) fn calendar_add(dt:&Value,days:&Value,ambiguity:&Value)->Result{ - let (unix,_)=unix_of_value(dt)?;let days=as_i64(days,"days")?; - let Some(zone)=named_zone(dt) else{return add(dt,Some(&Value::Int(days)),None,None,None)}; - let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?; - let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.naive_local(); - let duration=Duration::try_days(days).ok_or("calendar day overflow")?; - let next=local.checked_add_signed(duration).ok_or("calendar date overflow")?; - moment_in_zone(choose_local(tz,next,as_text(ambiguity,"ambiguity")?)?,zone) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn from_unix_utc_iso() { - let m = from_unix(&Value::Int(0), None).unwrap(); - let Value::Map(entries) = m else { panic!() }; - let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone(); - assert_eq!(iso, Value::Text("1970-01-01T00:00:00Z".into())); - } - - #[test] - fn shanghai_alias() { - let m = from_unix(&Value::Int(0), Some(&Value::Text("Asia/Shanghai".into()))).unwrap(); - let Value::Map(entries) = m else { panic!() }; - let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone(); - assert_eq!(iso, Value::Text("1970-01-01T08:00:00+08:00".into())); - } - - #[test] - fn parse_rfc3339_roundtrip() { - let m = parse( - &Value::Text("2020-01-02T03:04:05+08:00".into()), - None, - ) - .unwrap(); - let u = to_unix(&m).unwrap(); - assert_eq!(u, Value::Int(1_577_905_445)); - } - - #[test] - fn add_day() { - let m = from_unix(&Value::Int(0), None).unwrap(); - let n = add(&m, Some(&Value::Int(1)), None, None, None).unwrap(); - assert_eq!(to_unix(&n).unwrap(), Value::Int(86_400)); - } -} diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs deleted file mode 100755 index d3d1cfd..0000000 --- a/src/host/dispatch.rs +++ /dev/null @@ -1,2224 +0,0 @@ -//! Host function registry and dispatch. - -use std::collections::HashMap; - -use crate::host::{ - cli, csv, datetime, encoding, fs, hash, html_ops, json, log, math, net, path, re, secrets, stats, - sys, text_ops, time, toml_ops, url_ops, uuid_ops, writeback, HostContext, -}; -#[cfg(feature = "exec-host")] -use crate::host::{foreign, subtask}; -#[cfg(feature = "plugin-host")] -use crate::host::plugin; -use crate::value::Value; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(u16)] -pub enum HostFn { - ReadText = 1, - WriteText = 2, - AppendText = 3, - Exists = 4, - ListDir = 5, - MakeDir = 6, - Remove = 7, - NowUnix = 8, - NowMs = 9, - FormatTime = 10, - SleepMs = 11, - ParseTime = 12, - EnvGet = 13, - EnvSet = 14, - Args = 15, - Cwd = 16, - Exit = 17, - Exec = 18, - JsonParse = 19, - JsonStringify = 20, - JsonGet = 21, - JsonKeys = 22, - HttpGet = 23, - HttpPost = 24, - UrlEncode = 25, - // math - Pi = 26, - EConst = 27, - Num = 28, - MathAdd = 29, - MathSub = 30, - MathMul = 31, - MathDiv = 32, - MathPow = 33, - MathNeg = 34, - MathSin = 35, - MathCos = 36, - MathTan = 37, - MathAsin = 38, - MathAcos = 39, - MathAtan = 40, - MathSqrt = 41, - MathAbs = 42, - MathLn = 43, - MathExp = 44, - MathFloor = 45, - MathCeil = 46, - MathMin = 47, - MathMax = 48, - Random = 49, - RandomInt = 50, - Seed = 51, - Formula = 52, - Simplify = 53, - Expand = 54, - Diff = 55, - Subs = 56, - Eval = 57, - Solve = 58, - Plot = 59, - PlotPoints = 60, - PlotConic = 61, - ForeignSetCmd = 62, - ForeignRun = 63, - ForeignRunLang = 64, - ForeignLangs = 65, - DotenvLoad = 66, - HttpRequest = 67, - JsonQuote = 68, - PluginLoad = 69, - PluginUnload = 70, - PluginList = 71, - ExtNativePath = 72, - MapSet = 76, - ListAppend = 77, - WritebackRecord = 84, - WritebackGet = 85, - WritebackClear = 86, - WritebackList = 87, - SubtaskSpawn = 88, - SubtaskPoll = 89, - SubtaskJoin = 90, - SubtaskKill = 91, - SubtaskWaitAll = 92, - WritebackEnsure = 93, - OuterCallLine = 94, - TextPatch = 95, - ApplyPatchBlocks = 96, - WritebackScanPath = 97, - HttpPostSse = 98, - OpenAiSseParse = 99, - StreamPublish = 100, - CollectionPut = 101, - ListPrepend = 102, - ListConcat = 103, - ListInsert = 104, - ListSetAt = 105, - ListRemoveAt = 106, - ListSlice = 107, - ListContains = 108, - ListIndexOf = 109, - ListReverse = 110, - ListFirst = 111, - ListLast = 112, - MapGet = 113, - MapDelete = 114, - MapHas = 115, - MapKeys = 116, - MapValues = 117, - MapItems = 118, - MapMerge = 119, - MapSize = 120, - CollectionClear = 121, - CookieParse = 122, - MultipartParse = 123, - MarkdownParse = 124, - ReIsMatch = 125, - ReFind = 126, - ReFindAll = 127, - ReReplace = 128, - ReSplit = 129, - EncodingBase64Encode = 130, - EncodingBase64Decode = 131, - EncodingHexEncode = 132, - EncodingHexDecode = 133, - PathJoin = 134, - PathSplit = 135, - PathFileName = 136, - PathParent = 137, - PathExtension = 138, - PathNormalize = 139, - PathIsAbsolute = 140, - FsCopyFile = 141, - FsMove = 142, - FsMakeTemp = 143, - HashSha256 = 144, - HashSha1 = 145, - HashMd5 = 146, - HashHmacSha256 = 147, - SecretsTokenHex = 148, - SecretsTokenUrlsafe = 149, - TextContains = 150, - TextStartsWith = 151, - TextEndsWith = 152, - TextReplace = 153, - TextToUpper = 154, - TextToLower = 155, - TextRepeat = 156, - TextPad = 157, - CsvParse = 158, - CsvStringify = 159, - ListSort = 160, - ListSortBy = 161, - ListUnique = 162, - ListChunk = 163, - ListZip = 164, - ListFlatten = 165, - CliParse = 166, - LogSetLevel = 167, - LogLine = 168, - UuidV4 = 169, - DatetimeNow = 170, - DatetimeFromUnix = 171, - DatetimeToUnix = 172, - DatetimeParse = 173, - DatetimeFormat = 174, - DatetimeAdd = 175, - DatetimeInZone = 176, - UrlParse = 177, - UrlQueryParse = 178, - UrlQueryStringify = 179, - TomlParse = 180, - HtmlEscape = 181, - HtmlUnescape = 182, - EncodingBase32Encode = 183, - EncodingBase32Decode = 184, - FsMakeDirs = 185, - FsRemoveTree = 186, - FsStat = 187, - FsWalk = 188, - StatsMean = 189, - StatsMedian = 190, - StatsStdev = 191, - Meta = 192, - MetaGet = 193, - ModuleSource = 194, - ArtifactKind = 195, - ForeignInvoke = 196, - ForeignProbe = 197, - ForeignRegister = 198, - ForeignUnset = 199, - ForeignLoadConfig = 200, - ForeignCall = 201, - ForeignRunMany = 202, - ForeignCallMany = 203, - ForeignSessionOpen = 204, - ForeignSessionEval = 205, - ForeignSessionSet = 206, - ForeignSessionGet = 207, - ForeignSessionNames = 208, - ForeignSessionClose = 209, - ForeignSessionList = 210, - ForeignSessionInterrupt = 211, - /// `` M7: `access(集合, 键)` — polymorphic collection access (legacy index). - Access = 212, - OracleJournal = 213, - OracleReplayCheck = 214, - ListRange = 215, - ListEnumerate = 216, - ListPluck = 217, - ListProject = 218, - ListWhere = 219, - ListGroupBy = 220, - ListUniqueBy = 221, - ListAggregate = 222, - ListSortKeys = 223, - ListRename = 224, - TableFromColumns = 225, - TableToColumns = 226, - ListJoin = 227, - TableCast = 228, - FsTryReadText = 229, - FsTryWriteText = 230, - TryJsonParse = 231, - TryCsvParse = 232, - BytesFromText = 233, - BytesFromBase64 = 234, - BytesToText = 235, - BytesToBase64 = 236, - BytesLen = 237, - BytesSlice = 238, - FsReadBytes = 239, - FsWriteBytes = 240, - FsReadChunk = 241, - FsAppendBytes = 242, - FsAtomicWrite = 243, - FsWriteChanged = 244, - FsWriteChecked = 245, - FsReadLines = 246, - FsWriteLines = 247, - FsRemoveFile = 248, - FsRemoveEmptyDir = 249, - FsTempDir = 250, - FsFileHash = 251, - FsFind = 252, - FsCopyTree = 253, - FsSyncTree = 254, - FsRenameMany = 255, - PathRelative = 256, - PathWithExtension = 257, - DocumentSections = 258, - DocumentSection = 259, - DocumentReplaceSection = 260, - DocumentTables = 261, - DocumentReplaceTable = 262, - DocumentLinks = 263, - DocumentCodeBlocks = 264, - HttpRequestResult = 265, - HttpDownload = 266, - TomlStringify = 267, - TomlTryParse = 268, - DatetimeLocal = 269, - DatetimeCalendarAdd = 270, - SubtaskWaitTimeout = 271, - SubtaskCancelAll = 272, - SubtaskRunMany = 273, - HttpGetResult = 274, - ZipPack = 275, - ZipUnpack = 276, - TableTryCast = 277, - TableValidate = 278, - ListUnion = 279, - ListIntersection = 280, - ListDifference = 281, - TableSummarize = 282, - DocumentTable = 283, - FsResolve = 284, -} - -/// Single source of truth for every host function. `` slimming -/// -/// Replaces five hand-written matches (id, name, required, optional) that -/// had already drifted; `call_host` keeps its one-line arms. -pub struct HostFnDef { - pub id: u16, - pub f: HostFn, - pub name: &'static str, - pub required: &'static [&'static str], - pub optional: &'static [&'static str], -} - -pub const HOST_FN_TABLE: &[HostFnDef] = &[ - HostFnDef { id: 1, f: HostFn::ReadText, name: "host_read_text", required: &["path"], optional: &[] }, - HostFnDef { id: 2, f: HostFn::WriteText, name: "host_write_text", required: &["path", "text"], optional: &[] }, - HostFnDef { id: 3, f: HostFn::AppendText, name: "host_append_text", required: &["path", "text"], optional: &[] }, - HostFnDef { id: 4, f: HostFn::Exists, name: "host_exists", required: &["path"], optional: &[] }, - HostFnDef { id: 5, f: HostFn::ListDir, name: "host_list_dir", required: &["path"], optional: &[] }, - HostFnDef { id: 6, f: HostFn::MakeDir, name: "host_make_dir", required: &["path"], optional: &[] }, - HostFnDef { id: 7, f: HostFn::Remove, name: "host_remove", required: &["path"], optional: &[] }, - HostFnDef { id: 8, f: HostFn::NowUnix, name: "host_now_unix", required: &[], optional: &[] }, - HostFnDef { id: 9, f: HostFn::NowMs, name: "host_now_ms", required: &[], optional: &[] }, - HostFnDef { id: 10, f: HostFn::FormatTime, name: "host_format_time", required: &["unix", "pattern"], optional: &[] }, - HostFnDef { id: 11, f: HostFn::SleepMs, name: "host_sleep_ms", required: &["ms"], optional: &[] }, - HostFnDef { id: 12, f: HostFn::ParseTime, name: "host_parse_time", required: &["text", "pattern"], optional: &[] }, - HostFnDef { id: 13, f: HostFn::EnvGet, name: "host_env_get", required: &["name"], optional: &[] }, - HostFnDef { id: 14, f: HostFn::EnvSet, name: "host_env_set", required: &["name", "value"], optional: &[] }, - HostFnDef { id: 15, f: HostFn::Args, name: "host_args", required: &[], optional: &[] }, - HostFnDef { id: 16, f: HostFn::Cwd, name: "host_cwd", required: &[], optional: &[] }, - HostFnDef { id: 17, f: HostFn::Exit, name: "host_exit", required: &["code"], optional: &[] }, - HostFnDef { id: 18, f: HostFn::Exec, name: "host_exec", required: &["cmd"], optional: &["args", "capture"] }, - HostFnDef { id: 19, f: HostFn::JsonParse, name: "host_json_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 20, f: HostFn::JsonStringify, name: "host_json_stringify", required: &["value"], optional: &["indent"] }, - HostFnDef { id: 21, f: HostFn::JsonGet, name: "host_json_get", required: &["value", "key"], optional: &[] }, - HostFnDef { id: 22, f: HostFn::JsonKeys, name: "host_json_keys", required: &["value"], optional: &[] }, - HostFnDef { id: 23, f: HostFn::HttpGet, name: "host_http_get", required: &["url"], optional: &["headers"] }, - HostFnDef { id: 24, f: HostFn::HttpPost, name: "host_http_post", required: &["url", "body"], optional: &["content_type", "headers"] }, - HostFnDef { id: 25, f: HostFn::UrlEncode, name: "host_url_encode", required: &["text"], optional: &[] }, - HostFnDef { id: 26, f: HostFn::Pi, name: "host_pi", required: &[], optional: &[] }, - HostFnDef { id: 27, f: HostFn::EConst, name: "host_e", required: &[], optional: &[] }, - HostFnDef { id: 28, f: HostFn::Num, name: "host_num", required: &["value"], optional: &[] }, - HostFnDef { id: 29, f: HostFn::MathAdd, name: "host_math_add", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 30, f: HostFn::MathSub, name: "host_math_sub", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 31, f: HostFn::MathMul, name: "host_math_mul", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 32, f: HostFn::MathDiv, name: "host_math_div", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 33, f: HostFn::MathPow, name: "host_math_pow", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 34, f: HostFn::MathNeg, name: "host_math_neg", required: &["value"], optional: &[] }, - HostFnDef { id: 35, f: HostFn::MathSin, name: "host_math_sin", required: &["value"], optional: &[] }, - HostFnDef { id: 36, f: HostFn::MathCos, name: "host_math_cos", required: &["value"], optional: &[] }, - HostFnDef { id: 37, f: HostFn::MathTan, name: "host_math_tan", required: &["value"], optional: &[] }, - HostFnDef { id: 38, f: HostFn::MathAsin, name: "host_math_asin", required: &["value"], optional: &[] }, - HostFnDef { id: 39, f: HostFn::MathAcos, name: "host_math_acos", required: &["value"], optional: &[] }, - HostFnDef { id: 40, f: HostFn::MathAtan, name: "host_math_atan", required: &["value"], optional: &[] }, - HostFnDef { id: 41, f: HostFn::MathSqrt, name: "host_math_sqrt", required: &["value"], optional: &[] }, - HostFnDef { id: 42, f: HostFn::MathAbs, name: "host_math_abs", required: &["value"], optional: &[] }, - HostFnDef { id: 43, f: HostFn::MathLn, name: "host_math_ln", required: &["value"], optional: &[] }, - HostFnDef { id: 44, f: HostFn::MathExp, name: "host_math_exp", required: &["value"], optional: &[] }, - HostFnDef { id: 45, f: HostFn::MathFloor, name: "host_math_floor", required: &["value"], optional: &[] }, - HostFnDef { id: 46, f: HostFn::MathCeil, name: "host_math_ceil", required: &["value"], optional: &[] }, - HostFnDef { id: 47, f: HostFn::MathMin, name: "host_math_min", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 48, f: HostFn::MathMax, name: "host_math_max", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 49, f: HostFn::Random, name: "host_random", required: &[], optional: &[] }, - HostFnDef { id: 50, f: HostFn::RandomInt, name: "host_random_int", required: &["min", "max"], optional: &[] }, - HostFnDef { id: 51, f: HostFn::Seed, name: "host_seed", required: &["value"], optional: &[] }, - HostFnDef { id: 52, f: HostFn::Formula, name: "host_formula", required: &["value"], optional: &[] }, - HostFnDef { id: 53, f: HostFn::Simplify, name: "host_simplify", required: &["value"], optional: &[] }, - HostFnDef { id: 54, f: HostFn::Expand, name: "host_expand", required: &["value"], optional: &[] }, - HostFnDef { id: 55, f: HostFn::Diff, name: "host_diff", required: &["formula", "var"], optional: &[] }, - HostFnDef { id: 56, f: HostFn::Subs, name: "host_subs", required: &["formula", "var", "value"], optional: &[] }, - HostFnDef { id: 57, f: HostFn::Eval, name: "host_eval", required: &["formula", "var", "value"], optional: &[] }, - HostFnDef { id: 58, f: HostFn::Solve, name: "host_solve", required: &["formula", "var"], optional: &["min", "max"] }, - HostFnDef { id: 59, f: HostFn::Plot, name: "host_plot", required: &["formula", "var", "min", "max"], optional: &["steps", "path", "derivative", "grid"] }, - HostFnDef { id: 60, f: HostFn::PlotPoints, name: "host_plot_points", required: &["xs", "ys"], optional: &["path", "grid"] }, - HostFnDef { id: 61, f: HostFn::PlotConic, name: "host_plot_conic", required: &["kind", "a"], optional: &["b", "h", "k", "path", "grid"] }, - HostFnDef { id: 62, f: HostFn::ForeignSetCmd, name: "host_foreign_set_cmd", required: &["lang", "cmd"], optional: &["args"] }, - HostFnDef { id: 63, f: HostFn::ForeignRun, name: "host_foreign_run", required: &["code"], optional: &["stdin", "env", "cwd", "timeout", "args", "max_output"] }, - HostFnDef { id: 64, f: HostFn::ForeignRunLang, name: "host_foreign_run_lang", required: &["lang", "source"], optional: &["stdin", "env", "cwd", "timeout", "args", "max_output"] }, - HostFnDef { id: 65, f: HostFn::ForeignLangs, name: "host_foreign_langs", required: &[], optional: &[] }, - HostFnDef { id: 66, f: HostFn::DotenvLoad, name: "host_dotenv_load", required: &[], optional: &["path"] }, - HostFnDef { id: 67, f: HostFn::HttpRequest, name: "host_http_request", required: &["method", "url"], optional: &["body", "content_type", "headers"] }, - HostFnDef { id: 68, f: HostFn::JsonQuote, name: "host_json_quote", required: &["text"], optional: &[] }, - HostFnDef { id: 69, f: HostFn::PluginLoad, name: "host_plugin_load", required: &["path"], optional: &[] }, - HostFnDef { id: 70, f: HostFn::PluginUnload, name: "host_plugin_unload", required: &[], optional: &[] }, - HostFnDef { id: 71, f: HostFn::PluginList, name: "host_plugin_list", required: &[], optional: &[] }, - HostFnDef { id: 72, f: HostFn::ExtNativePath, name: "host_ext_native_path", required: &["name"], optional: &[] }, - HostFnDef { id: 76, f: HostFn::MapSet, name: "host_map_set", required: &["map", "key", "value"], optional: &[] }, - HostFnDef { id: 77, f: HostFn::ListAppend, name: "host_list_append", required: &["list", "item"], optional: &[] }, - HostFnDef { id: 84, f: HostFn::WritebackRecord, name: "host_writeback_record", required: &["value"], optional: &["at_end", "key", "line"] }, - HostFnDef { id: 85, f: HostFn::WritebackGet, name: "host_writeback_get", required: &[], optional: &["at_end", "key", "line"] }, - HostFnDef { id: 86, f: HostFn::WritebackClear, name: "host_writeback_clear", required: &[], optional: &["at_end", "key", "line"] }, - HostFnDef { id: 87, f: HostFn::WritebackList, name: "host_writeback_list", required: &[], optional: &[] }, - HostFnDef { id: 88, f: HostFn::SubtaskSpawn, name: "host_subtask_spawn", required: &[], optional: &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"] }, - HostFnDef { id: 89, f: HostFn::SubtaskPoll, name: "host_subtask_poll", required: &["id"], optional: &[] }, - HostFnDef { id: 90, f: HostFn::SubtaskJoin, name: "host_subtask_join", required: &["id"], optional: &[] }, - HostFnDef { id: 91, f: HostFn::SubtaskKill, name: "host_subtask_kill", required: &["id"], optional: &[] }, - HostFnDef { id: 92, f: HostFn::SubtaskWaitAll, name: "host_subtask_wait_all", required: &[], optional: &[] }, - HostFnDef { id: 93, f: HostFn::WritebackEnsure, name: "host_writeback_ensure", required: &["key"], optional: &["placeholder", "line"] }, - HostFnDef { id: 94, f: HostFn::OuterCallLine, name: "host_outer_call_line", required: &[], optional: &[] }, - HostFnDef { id: 95, f: HostFn::TextPatch, name: "host_text_patch", required: &["path", "find", "replace"], optional: &[] }, - HostFnDef { id: 96, f: HostFn::ApplyPatchBlocks, name: "host_apply_patch_blocks", required: &["path", "text", "soft"], optional: &[] }, - HostFnDef { id: 97, f: HostFn::WritebackScanPath, name: "host_writeback_scan_path", required: &["path"], optional: &[] }, - HostFnDef { id: 98, f: HostFn::HttpPostSse, name: "host_http_post_sse", required: &["url", "body"], optional: &["content_type", "headers", "echo"] }, - HostFnDef { id: 99, f: HostFn::OpenAiSseParse, name: "host_openai_sse_parse", required: &["text"], optional: &["echo"] }, - HostFnDef { id: 100, f: HostFn::StreamPublish, name: "host_stream_publish", required: &["event"], optional: &[] }, - HostFnDef { id: 101, f: HostFn::CollectionPut, name: "host_collection_put", required: &["in", "at", "value"], optional: &[] }, - HostFnDef { id: 102, f: HostFn::ListPrepend, name: "host_list_prepend", required: &["list", "item"], optional: &[] }, - HostFnDef { id: 103, f: HostFn::ListConcat, name: "host_list_concat", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 104, f: HostFn::ListInsert, name: "host_list_insert", required: &["list", "index", "item"], optional: &[] }, - HostFnDef { id: 105, f: HostFn::ListSetAt, name: "host_list_set_at", required: &["list", "index", "item"], optional: &[] }, - HostFnDef { id: 106, f: HostFn::ListRemoveAt, name: "host_list_remove_at", required: &["list", "index"], optional: &[] }, - HostFnDef { id: 107, f: HostFn::ListSlice, name: "host_list_slice", required: &["list", "start"], optional: &["end"] }, - HostFnDef { id: 108, f: HostFn::ListContains, name: "host_list_contains", required: &["list", "item"], optional: &[] }, - HostFnDef { id: 109, f: HostFn::ListIndexOf, name: "host_list_index_of", required: &["list", "item"], optional: &[] }, - HostFnDef { id: 110, f: HostFn::ListReverse, name: "host_list_reverse", required: &["list"], optional: &[] }, - HostFnDef { id: 111, f: HostFn::ListFirst, name: "host_list_first", required: &["list"], optional: &[] }, - HostFnDef { id: 112, f: HostFn::ListLast, name: "host_list_last", required: &["list"], optional: &[] }, - HostFnDef { id: 113, f: HostFn::MapGet, name: "host_map_get", required: &["map", "key"], optional: &[] }, - HostFnDef { id: 114, f: HostFn::MapDelete, name: "host_map_delete", required: &["map", "key"], optional: &[] }, - HostFnDef { id: 115, f: HostFn::MapHas, name: "host_map_has", required: &["map", "key"], optional: &[] }, - HostFnDef { id: 116, f: HostFn::MapKeys, name: "host_map_keys", required: &["map"], optional: &[] }, - HostFnDef { id: 117, f: HostFn::MapValues, name: "host_map_values", required: &["map"], optional: &[] }, - HostFnDef { id: 118, f: HostFn::MapItems, name: "host_map_items", required: &["map"], optional: &[] }, - HostFnDef { id: 119, f: HostFn::MapMerge, name: "host_map_merge", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 120, f: HostFn::MapSize, name: "host_map_size", required: &["map"], optional: &[] }, - HostFnDef { id: 121, f: HostFn::CollectionClear, name: "host_collection_clear", required: &["value"], optional: &[] }, - HostFnDef { id: 122, f: HostFn::CookieParse, name: "host_cookie_parse", required: &["text", "is_response"], optional: &[] }, - HostFnDef { id: 123, f: HostFn::MultipartParse, name: "host_multipart_parse", required: &["body", "boundary"], optional: &[] }, - HostFnDef { id: 124, f: HostFn::MarkdownParse, name: "host_markdown_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 125, f: HostFn::ReIsMatch, name: "host_re_is_match", required: &["text", "pattern"], optional: &[] }, - HostFnDef { id: 126, f: HostFn::ReFind, name: "host_re_find", required: &["text", "pattern"], optional: &[] }, - HostFnDef { id: 127, f: HostFn::ReFindAll, name: "host_re_find_all", required: &["text", "pattern"], optional: &[] }, - HostFnDef { id: 128, f: HostFn::ReReplace, name: "host_re_replace", required: &["text", "pattern", "with"], optional: &["count"] }, - HostFnDef { id: 129, f: HostFn::ReSplit, name: "host_re_split", required: &["text", "pattern"], optional: &[] }, - HostFnDef { id: 130, f: HostFn::EncodingBase64Encode, name: "host_encoding_base64_encode", required: &["text"], optional: &[] }, - HostFnDef { id: 131, f: HostFn::EncodingBase64Decode, name: "host_encoding_base64_decode", required: &["text"], optional: &[] }, - HostFnDef { id: 132, f: HostFn::EncodingHexEncode, name: "host_encoding_hex_encode", required: &["text"], optional: &[] }, - HostFnDef { id: 133, f: HostFn::EncodingHexDecode, name: "host_encoding_hex_decode", required: &["text"], optional: &[] }, - HostFnDef { id: 134, f: HostFn::PathJoin, name: "host_path_join", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 135, f: HostFn::PathSplit, name: "host_path_split", required: &["path"], optional: &[] }, - HostFnDef { id: 136, f: HostFn::PathFileName, name: "host_path_file_name", required: &["path"], optional: &[] }, - HostFnDef { id: 137, f: HostFn::PathParent, name: "host_path_parent", required: &["path"], optional: &[] }, - HostFnDef { id: 138, f: HostFn::PathExtension, name: "host_path_extension", required: &["path"], optional: &[] }, - HostFnDef { id: 139, f: HostFn::PathNormalize, name: "host_path_normalize", required: &["path"], optional: &[] }, - HostFnDef { id: 140, f: HostFn::PathIsAbsolute, name: "host_path_is_absolute", required: &["path"], optional: &[] }, - HostFnDef { id: 141, f: HostFn::FsCopyFile, name: "host_copy_file", required: &["src", "dest"], optional: &[] }, - HostFnDef { id: 142, f: HostFn::FsMove, name: "host_move", required: &["src", "dest"], optional: &[] }, - HostFnDef { id: 143, f: HostFn::FsMakeTemp, name: "host_make_temp", required: &[], optional: &["prefix"] }, - HostFnDef { id: 144, f: HostFn::HashSha256, name: "host_hash_sha256", required: &["text"], optional: &[] }, - HostFnDef { id: 145, f: HostFn::HashSha1, name: "host_hash_sha1", required: &["text"], optional: &[] }, - HostFnDef { id: 146, f: HostFn::HashMd5, name: "host_hash_md5", required: &["text"], optional: &[] }, - HostFnDef { id: 147, f: HostFn::HashHmacSha256, name: "host_hash_hmac_sha256", required: &["key", "text"], optional: &[] }, - HostFnDef { id: 148, f: HostFn::SecretsTokenHex, name: "host_secrets_token_hex", required: &[], optional: &["n"] }, - HostFnDef { id: 149, f: HostFn::SecretsTokenUrlsafe, name: "host_secrets_token_urlsafe", required: &[], optional: &["n"] }, - HostFnDef { id: 150, f: HostFn::TextContains, name: "host_text_contains", required: &["text", "sub"], optional: &[] }, - HostFnDef { id: 151, f: HostFn::TextStartsWith, name: "host_text_starts_with", required: &["text", "prefix"], optional: &[] }, - HostFnDef { id: 152, f: HostFn::TextEndsWith, name: "host_text_ends_with", required: &["text", "suffix"], optional: &[] }, - HostFnDef { id: 153, f: HostFn::TextReplace, name: "host_text_replace", required: &["text", "old", "new"], optional: &["count"] }, - HostFnDef { id: 154, f: HostFn::TextToUpper, name: "host_text_to_upper", required: &["text"], optional: &[] }, - HostFnDef { id: 155, f: HostFn::TextToLower, name: "host_text_to_lower", required: &["text"], optional: &[] }, - HostFnDef { id: 156, f: HostFn::TextRepeat, name: "host_text_repeat", required: &["text", "n"], optional: &[] }, - HostFnDef { id: 157, f: HostFn::TextPad, name: "host_text_pad", required: &["text", "width"], optional: &["fill", "align"] }, - HostFnDef { id: 158, f: HostFn::CsvParse, name: "host_csv_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 159, f: HostFn::CsvStringify, name: "host_csv_stringify", required: &["rows"], optional: &[] }, - HostFnDef { id: 160, f: HostFn::ListSort, name: "host_list_sort", required: &["list"], optional: &[] }, - HostFnDef { id: 161, f: HostFn::ListSortBy, name: "host_list_sort_by", required: &["list", "key"], optional: &[] }, - HostFnDef { id: 162, f: HostFn::ListUnique, name: "host_list_unique", required: &["list"], optional: &[] }, - HostFnDef { id: 163, f: HostFn::ListChunk, name: "host_list_chunk", required: &["list", "size"], optional: &[] }, - HostFnDef { id: 164, f: HostFn::ListZip, name: "host_list_zip", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 165, f: HostFn::ListFlatten, name: "host_list_flatten", required: &["list"], optional: &[] }, - HostFnDef { id: 166, f: HostFn::CliParse, name: "host_cli_parse", required: &[], optional: &["args"] }, - HostFnDef { id: 167, f: HostFn::LogSetLevel, name: "host_log_set_level", required: &["level"], optional: &[] }, - HostFnDef { id: 168, f: HostFn::LogLine, name: "host_log_line", required: &["level", "text"], optional: &["fields"] }, - HostFnDef { id: 169, f: HostFn::UuidV4, name: "host_uuid_v4", required: &[], optional: &[] }, - HostFnDef { id: 170, f: HostFn::DatetimeNow, name: "host_datetime_now", required: &[], optional: &[] }, - HostFnDef { id: 171, f: HostFn::DatetimeFromUnix, name: "host_datetime_from_unix", required: &["unix"], optional: &["zone"] }, - HostFnDef { id: 172, f: HostFn::DatetimeToUnix, name: "host_datetime_to_unix", required: &["dt"], optional: &[] }, - HostFnDef { id: 173, f: HostFn::DatetimeParse, name: "host_datetime_parse", required: &["text"], optional: &["pattern"] }, - HostFnDef { id: 174, f: HostFn::DatetimeFormat, name: "host_datetime_format", required: &["dt"], optional: &["style"] }, - HostFnDef { id: 175, f: HostFn::DatetimeAdd, name: "host_datetime_add", required: &["dt"], optional: &["days", "hours", "minutes", "seconds"] }, - HostFnDef { id: 176, f: HostFn::DatetimeInZone, name: "host_datetime_in_zone", required: &["dt", "zone"], optional: &[] }, - HostFnDef { id: 177, f: HostFn::UrlParse, name: "host_url_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 178, f: HostFn::UrlQueryParse, name: "host_url_query_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 179, f: HostFn::UrlQueryStringify, name: "host_url_query_stringify", required: &["map"], optional: &[] }, - HostFnDef { id: 180, f: HostFn::TomlParse, name: "host_toml_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 181, f: HostFn::HtmlEscape, name: "host_html_escape", required: &["text"], optional: &[] }, - HostFnDef { id: 182, f: HostFn::HtmlUnescape, name: "host_html_unescape", required: &["text"], optional: &[] }, - HostFnDef { id: 183, f: HostFn::EncodingBase32Encode, name: "host_encoding_base32_encode", required: &["text"], optional: &[] }, - HostFnDef { id: 184, f: HostFn::EncodingBase32Decode, name: "host_encoding_base32_decode", required: &["text"], optional: &[] }, - HostFnDef { id: 185, f: HostFn::FsMakeDirs, name: "host_make_dirs", required: &["path"], optional: &[] }, - HostFnDef { id: 186, f: HostFn::FsRemoveTree, name: "host_remove_tree", required: &["path"], optional: &[] }, - HostFnDef { id: 187, f: HostFn::FsStat, name: "host_stat", required: &["path"], optional: &[] }, - HostFnDef { id: 188, f: HostFn::FsWalk, name: "host_walk", required: &["path"], optional: &[] }, - HostFnDef { id: 189, f: HostFn::StatsMean, name: "host_stats_mean", required: &["list"], optional: &[] }, - HostFnDef { id: 190, f: HostFn::StatsMedian, name: "host_stats_median", required: &["list"], optional: &[] }, - HostFnDef { id: 191, f: HostFn::StatsStdev, name: "host_stats_stdev", required: &["list"], optional: &[] }, - HostFnDef { id: 192, f: HostFn::Meta, name: "host_meta", required: &[], optional: &[] }, - HostFnDef { id: 193, f: HostFn::MetaGet, name: "host_meta_get", required: &["key"], optional: &[] }, - HostFnDef { id: 194, f: HostFn::ModuleSource, name: "host_module_source", required: &[], optional: &[] }, - HostFnDef { id: 195, f: HostFn::ArtifactKind, name: "host_artifact_kind", required: &[], optional: &[] }, - HostFnDef { id: 196, f: HostFn::ForeignInvoke, name: "host_foreign_invoke", required: &[], optional: &["code", "lang", "source", "stdin", "input", "env", "cwd", "timeout", "args", "output", "max_output", "cmd", "keep"] }, - HostFnDef { id: 197, f: HostFn::ForeignProbe, name: "host_foreign_probe", required: &[], optional: &["lang"] }, - HostFnDef { id: 198, f: HostFn::ForeignRegister, name: "host_foreign_register", required: &["lang"], optional: &["cmd", "args", "template", "ext", "env", "version_args"] }, - HostFnDef { id: 199, f: HostFn::ForeignUnset, name: "host_foreign_unset", required: &["lang"], optional: &[] }, - HostFnDef { id: 200, f: HostFn::ForeignLoadConfig, name: "host_foreign_load_config", required: &[], optional: &["path"] }, - HostFnDef { id: 201, f: HostFn::ForeignCall, name: "host_foreign_call", required: &[], optional: &["code", "lang", "source", "input", "stdin", "env", "cwd", "timeout", "args"] }, - HostFnDef { id: 202, f: HostFn::ForeignRunMany, name: "host_foreign_run_many", required: &["runs"], optional: &["concurrency"] }, - HostFnDef { id: 203, f: HostFn::ForeignCallMany, name: "host_foreign_call_many", required: &["inputs"], optional: &["code", "lang", "source", "cmd", "env", "cwd", "timeout", "args", "max_output", "concurrency"] }, - HostFnDef { id: 204, f: HostFn::ForeignSessionOpen, name: "host_foreign_session_open", required: &["lang"], optional: &["cmd", "env", "cwd", "timeout"] }, - HostFnDef { id: 205, f: HostFn::ForeignSessionEval, name: "host_foreign_session_eval", required: &["id"], optional: &["code", "source", "input", "stdin", "timeout"] }, - HostFnDef { id: 206, f: HostFn::ForeignSessionSet, name: "host_foreign_session_set", required: &["id", "name", "value"], optional: &[] }, - HostFnDef { id: 207, f: HostFn::ForeignSessionGet, name: "host_foreign_session_get", required: &["id", "name"], optional: &[] }, - HostFnDef { id: 208, f: HostFn::ForeignSessionNames, name: "host_foreign_session_names", required: &["id"], optional: &[] }, - HostFnDef { id: 209, f: HostFn::ForeignSessionClose, name: "host_foreign_session_close", required: &["id"], optional: &[] }, - HostFnDef { id: 210, f: HostFn::ForeignSessionList, name: "host_foreign_session_list", required: &[], optional: &[] }, - HostFnDef { id: 211, f: HostFn::ForeignSessionInterrupt, name: "host_foreign_session_interrupt", required: &["id"], optional: &[] }, - HostFnDef { id: 212, f: HostFn::Access, name: "host_access", required: &["value", "key"], optional: &[] }, - HostFnDef { id: 213, f: HostFn::OracleJournal, name: "host_oracle_journal", required: &[], optional: &[] }, - HostFnDef { id: 214, f: HostFn::OracleReplayCheck, name: "host_oracle_replay_check", required: &["expected", "observed"], optional: &[] }, - HostFnDef { id: 215, f: HostFn::ListRange, name: "host_table_range", required: &["start", "end"], optional: &["step"] }, - HostFnDef { id: 216, f: HostFn::ListEnumerate, name: "host_table_enumerate", required: &["list"], optional: &["start"] }, - HostFnDef { id: 217, f: HostFn::ListPluck, name: "host_table_pluck", required: &["list", "key"], optional: &[] }, - HostFnDef { id: 218, f: HostFn::ListProject, name: "host_table_project", required: &["list", "keys"], optional: &[] }, - HostFnDef { id: 219, f: HostFn::ListWhere, name: "host_table_where", required: &["list", "key", "value"], optional: &["op"] }, - HostFnDef { id: 220, f: HostFn::ListGroupBy, name: "host_table_group_by", required: &["list", "key"], optional: &[] }, - HostFnDef { id: 221, f: HostFn::ListUniqueBy, name: "host_table_unique_by", required: &["list", "key"], optional: &[] }, - HostFnDef { id: 222, f: HostFn::ListAggregate, name: "host_table_aggregate", required: &["list"], optional: &["key", "op"] }, - HostFnDef { id: 223, f: HostFn::ListSortKeys, name: "host_table_sort_keys", required: &["list", "keys"], optional: &["descending"] }, - HostFnDef { id: 224, f: HostFn::ListRename, name: "host_table_rename", required: &["list", "fields"], optional: &[] }, - HostFnDef { id: 225, f: HostFn::TableFromColumns, name: "host_table_from_columns", required: &["columns"], optional: &[] }, - HostFnDef { id: 226, f: HostFn::TableToColumns, name: "host_table_to_columns", required: &["rows"], optional: &[] }, - HostFnDef { id: 227, f: HostFn::ListJoin, name: "host_table_join", required: &["a", "b", "key", "right_key"], optional: &["mode"] }, - HostFnDef { id: 228, f: HostFn::TableCast, name: "host_table_cast", required: &["rows", "schema"], optional: &[] }, - HostFnDef { id: 229, f: HostFn::FsTryReadText, name: "host_fs_try_read_text", required: &["path"], optional: &[] }, - HostFnDef { id: 230, f: HostFn::FsTryWriteText, name: "host_fs_try_write_text", required: &["path", "text"], optional: &[] }, - HostFnDef { id: 231, f: HostFn::TryJsonParse, name: "host_try_json_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 232, f: HostFn::TryCsvParse, name: "host_try_csv_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 233, f: HostFn::BytesFromText, name: "host_bytes_from_text", required: &["text"], optional: &[] }, - HostFnDef { id: 234, f: HostFn::BytesFromBase64, name: "host_bytes_from_base64", required: &["text"], optional: &[] }, - HostFnDef { id: 235, f: HostFn::BytesToText, name: "host_bytes_to_text", required: &["data"], optional: &[] }, - HostFnDef { id: 236, f: HostFn::BytesToBase64, name: "host_bytes_to_base64", required: &["data"], optional: &[] }, - HostFnDef { id: 237, f: HostFn::BytesLen, name: "host_bytes_len", required: &["data"], optional: &[] }, - HostFnDef { id: 238, f: HostFn::BytesSlice, name: "host_bytes_slice", required: &["data", "start", "end"], optional: &[] }, - HostFnDef { id: 239, f: HostFn::FsReadBytes, name: "host_fs_read_bytes", required: &["path"], optional: &["max_bytes"] }, - HostFnDef { id: 240, f: HostFn::FsWriteBytes, name: "host_fs_write_bytes", required: &["path", "data"], optional: &[] }, - HostFnDef { id: 241, f: HostFn::FsReadChunk, name: "host_fs_read_chunk", required: &["path"], optional: &["offset", "size"] }, - HostFnDef { id: 242, f: HostFn::FsAppendBytes, name: "host_fs_append_bytes", required: &["path", "data"], optional: &[] }, - HostFnDef { id: 243, f: HostFn::FsAtomicWrite, name: "host_fs_atomic_write", required: &["path", "text"], optional: &[] }, - HostFnDef { id: 244, f: HostFn::FsWriteChanged, name: "host_fs_write_changed", required: &["path", "text"], optional: &[] }, - HostFnDef { id: 245, f: HostFn::FsWriteChecked, name: "host_fs_write_checked", required: &["path", "text", "expected_sha256"], optional: &[] }, - HostFnDef { id: 246, f: HostFn::FsReadLines, name: "host_fs_read_lines", required: &["path"], optional: &["max_bytes"] }, - HostFnDef { id: 247, f: HostFn::FsWriteLines, name: "host_fs_write_lines", required: &["path", "lines"], optional: &[] }, - HostFnDef { id: 248, f: HostFn::FsRemoveFile, name: "host_fs_remove_file", required: &["path"], optional: &[] }, - HostFnDef { id: 249, f: HostFn::FsRemoveEmptyDir, name: "host_fs_remove_empty_dir", required: &["path"], optional: &[] }, - HostFnDef { id: 250, f: HostFn::FsTempDir, name: "host_fs_temp_dir", required: &[], optional: &["prefix"] }, - HostFnDef { id: 251, f: HostFn::FsFileHash, name: "host_fs_file_hash", required: &["path"], optional: &[] }, - HostFnDef { id: 252, f: HostFn::FsFind, name: "host_fs_find", required: &["path"], optional: &["pattern", "exclude", "max_depth", "kind"] }, - HostFnDef { id: 253, f: HostFn::FsCopyTree, name: "host_fs_copy_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] }, - HostFnDef { id: 254, f: HostFn::FsSyncTree, name: "host_fs_sync_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] }, - HostFnDef { id: 255, f: HostFn::FsRenameMany, name: "host_fs_rename_many", required: &["moves"], optional: &["dry_run"] }, - HostFnDef { id: 256, f: HostFn::PathRelative, name: "host_path_relative", required: &["path", "base"], optional: &[] }, - HostFnDef { id: 257, f: HostFn::PathWithExtension, name: "host_path_with_extension", required: &["path", "extension"], optional: &[] }, - HostFnDef { id: 258, f: HostFn::DocumentSections, name: "host_document_sections", required: &["text"], optional: &[] }, - HostFnDef { id: 259, f: HostFn::DocumentSection, name: "host_document_section", required: &["text", "title"], optional: &[] }, - HostFnDef { id: 260, f: HostFn::DocumentReplaceSection, name: "host_document_replace_section", required: &["text", "title", "body"], optional: &["expected_sha256"] }, - HostFnDef { id: 261, f: HostFn::DocumentTables, name: "host_document_tables", required: &["text"], optional: &[] }, - HostFnDef { id: 262, f: HostFn::DocumentReplaceTable, name: "host_document_replace_table", required: &["text", "index", "headers", "rows"], optional: &["expected_sha256"] }, - HostFnDef { id: 263, f: HostFn::DocumentLinks, name: "host_document_links", required: &["text"], optional: &[] }, - HostFnDef { id: 264, f: HostFn::DocumentCodeBlocks, name: "host_document_code_blocks", required: &["text"], optional: &[] }, - HostFnDef { id: 265, f: HostFn::HttpRequestResult, name: "host_http_request_result", required: &["method", "url"], optional: &["body", "headers", "timeout_ms", "max_bytes", "response"] }, - HostFnDef { id: 266, f: HostFn::HttpDownload, name: "host_http_download", required: &["url", "path"], optional: &["headers", "timeout_ms", "max_bytes"] }, - HostFnDef { id: 267, f: HostFn::TomlStringify, name: "host_toml_stringify", required: &["value"], optional: &[] }, - HostFnDef { id: 268, f: HostFn::TomlTryParse, name: "host_toml_try_parse", required: &["text"], optional: &[] }, - HostFnDef { id: 269, f: HostFn::DatetimeLocal, name: "host_datetime_local", required: &["text", "zone"], optional: &["ambiguity"] }, - HostFnDef { id: 270, f: HostFn::DatetimeCalendarAdd, name: "host_datetime_calendar_add", required: &["dt", "days"], optional: &["ambiguity"] }, - HostFnDef { id: 271, f: HostFn::SubtaskWaitTimeout, name: "host_subtask_wait_timeout", required: &["id"], optional: &["timeout_ms", "cancel"] }, - HostFnDef { id: 272, f: HostFn::SubtaskCancelAll, name: "host_subtask_cancel_all", required: &[], optional: &[] }, - HostFnDef { id: 273, f: HostFn::SubtaskRunMany, name: "host_subtask_run_many", required: &["tasks"], optional: &["limit", "timeout_ms"] }, - HostFnDef { id: 274, f: HostFn::HttpGetResult, name: "host_http_get_result", required: &["url"], optional: &["headers", "timeout_ms", "max_bytes", "response"] }, - HostFnDef { id: 275, f: HostFn::ZipPack, name: "host_zip_pack", required: &["src", "dest"], optional: &["max_bytes"] }, - HostFnDef { id: 276, f: HostFn::ZipUnpack, name: "host_zip_unpack", required: &["src", "dest"], optional: &["max_bytes"] }, - HostFnDef { id: 277, f: HostFn::TableTryCast, name: "host_table_try_cast", required: &["rows", "schema"], optional: &[] }, - HostFnDef { id: 278, f: HostFn::TableValidate, name: "host_table_validate", required: &["rows", "schema"], optional: &[] }, - HostFnDef { id: 279, f: HostFn::ListUnion, name: "host_table_union", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 280, f: HostFn::ListIntersection, name: "host_table_intersection", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 281, f: HostFn::ListDifference, name: "host_table_difference", required: &["a", "b"], optional: &[] }, - HostFnDef { id: 282, f: HostFn::TableSummarize, name: "host_table_summarize", required: &["list", "key", "field"], optional: &["op"] }, - HostFnDef { id: 283, f: HostFn::DocumentTable, name: "host_document_table", required: &["text"], optional: &["title", "index"] }, - HostFnDef { id: 284, f: HostFn::FsResolve, name: "host_fs_resolve", required: &["path"], optional: &[] }, -]; - - -impl HostFn { - pub fn from_u16(id: u16) -> Option { - HOST_FN_TABLE.iter().find(|d| d.id == id).map(|d| d.f) - } - - pub fn from_name(name: &str) -> Option { - Some(match name { - "host_table_summarize" => Self::TableSummarize, - "host_table_difference" => Self::ListDifference, - "host_table_intersection" => Self::ListIntersection, - "host_table_union" => Self::ListUnion, - "host_table_validate" => Self::TableValidate, - "host_table_try_cast" => Self::TableTryCast, - "host_zip_unpack" => Self::ZipUnpack, - "host_zip_pack" => Self::ZipPack, - "host_http_get_result" => Self::HttpGetResult, - "host_subtask_run_many" => Self::SubtaskRunMany, - "host_subtask_cancel_all" => Self::SubtaskCancelAll, - "host_subtask_wait_timeout" => Self::SubtaskWaitTimeout, - "host_datetime_calendar_add" => Self::DatetimeCalendarAdd, - "host_datetime_local" => Self::DatetimeLocal, - "host_toml_try_parse" => Self::TomlTryParse, - "host_toml_stringify" => Self::TomlStringify, - "host_http_download" => Self::HttpDownload, - "host_http_request_result" => Self::HttpRequestResult, - "host_document_code_blocks" => Self::DocumentCodeBlocks, - "host_document_links" => Self::DocumentLinks, - "host_document_replace_table" => Self::DocumentReplaceTable, - "host_document_tables" => Self::DocumentTables, - "host_document_table" => Self::DocumentTable, - "host_fs_resolve" => Self::FsResolve, - "host_document_replace_section" => Self::DocumentReplaceSection, - "host_document_section" => Self::DocumentSection, - "host_document_sections" => Self::DocumentSections, - "host_path_with_extension" => Self::PathWithExtension, - "host_path_relative" => Self::PathRelative, - "host_fs_rename_many" => Self::FsRenameMany, - "host_fs_sync_tree" => Self::FsSyncTree, - "host_fs_copy_tree" => Self::FsCopyTree, - "host_fs_find" => Self::FsFind, - "host_fs_file_hash" => Self::FsFileHash, - "host_fs_temp_dir" => Self::FsTempDir, - "host_fs_remove_empty_dir" => Self::FsRemoveEmptyDir, - "host_fs_remove_file" => Self::FsRemoveFile, - "host_fs_write_lines" => Self::FsWriteLines, - "host_fs_read_lines" => Self::FsReadLines, - "host_fs_write_checked" => Self::FsWriteChecked, - "host_fs_write_changed" => Self::FsWriteChanged, - "host_fs_atomic_write" => Self::FsAtomicWrite, - "host_fs_append_bytes" => Self::FsAppendBytes, - "host_fs_read_chunk" => Self::FsReadChunk, - "host_fs_write_bytes" => Self::FsWriteBytes, - "host_fs_read_bytes" => Self::FsReadBytes, - "host_bytes_slice" => Self::BytesSlice, - "host_bytes_len" => Self::BytesLen, - "host_bytes_to_base64" => Self::BytesToBase64, - "host_bytes_to_text" => Self::BytesToText, - "host_bytes_from_base64" => Self::BytesFromBase64, - "host_bytes_from_text" => Self::BytesFromText, - "host_try_csv_parse" => Self::TryCsvParse, - "host_try_json_parse" => Self::TryJsonParse, - "host_fs_try_write_text" => Self::FsTryWriteText, - "host_fs_try_read_text" => Self::FsTryReadText, - "host_table_cast" => Self::TableCast, - "host_table_join" => Self::ListJoin, - "host_table_to_columns" => Self::TableToColumns, - "host_table_from_columns" => Self::TableFromColumns, - "host_table_rename" => Self::ListRename, - "host_table_sort_keys" => Self::ListSortKeys, - "host_table_aggregate" => Self::ListAggregate, - "host_table_unique_by" => Self::ListUniqueBy, - "host_table_group_by" => Self::ListGroupBy, - "host_table_where" => Self::ListWhere, - "host_table_project" => Self::ListProject, - "host_table_pluck" => Self::ListPluck, - "host_table_enumerate" => Self::ListEnumerate, - "host_table_range" => Self::ListRange, - "host_read_text" => Self::ReadText, - "host_write_text" => Self::WriteText, - "host_append_text" => Self::AppendText, - "host_exists" => Self::Exists, - "host_list_dir" => Self::ListDir, - "host_make_dir" => Self::MakeDir, - "host_remove" => Self::Remove, - "host_now_unix" => Self::NowUnix, - "host_now_ms" => Self::NowMs, - "host_format_time" => Self::FormatTime, - "host_sleep_ms" => Self::SleepMs, - "host_parse_time" => Self::ParseTime, - "host_env_get" => Self::EnvGet, - "host_env_set" => Self::EnvSet, - "host_args" => Self::Args, - "host_cwd" => Self::Cwd, - "host_exit" => Self::Exit, - "host_exec" => Self::Exec, - "host_oracle_journal" => Self::OracleJournal, - "host_oracle_replay_check" => Self::OracleReplayCheck, - "host_json_parse" => Self::JsonParse, - "host_json_stringify" => Self::JsonStringify, - "host_json_get" => Self::JsonGet, - "host_json_keys" => Self::JsonKeys, - // Aliases so optional `headers` / `content_type` bind like plot. - "host_http_get" | "http_get" => Self::HttpGet, - "host_http_post" | "http_post" => Self::HttpPost, - "host_http_post_sse" | "http_post_sse" => Self::HttpPostSse, - "host_openai_sse_parse" | "openai_sse_parse" => Self::OpenAiSseParse, - "host_stream_publish" | "stream_publish" => Self::StreamPublish, - "host_url_encode" => Self::UrlEncode, - "host_pi" => Self::Pi, - "host_e" => Self::EConst, - "host_num" => Self::Num, - "host_math_add" => Self::MathAdd, - "host_math_sub" => Self::MathSub, - "host_math_mul" => Self::MathMul, - "host_math_div" => Self::MathDiv, - "host_math_pow" => Self::MathPow, - "host_math_neg" => Self::MathNeg, - "host_math_sin" => Self::MathSin, - "host_math_cos" => Self::MathCos, - "host_math_tan" => Self::MathTan, - "host_math_asin" => Self::MathAsin, - "host_math_acos" => Self::MathAcos, - "host_math_atan" => Self::MathAtan, - "host_math_sqrt" => Self::MathSqrt, - "host_math_abs" => Self::MathAbs, - "host_math_ln" => Self::MathLn, - "host_math_exp" => Self::MathExp, - "host_math_floor" => Self::MathFloor, - "host_math_ceil" => Self::MathCeil, - "host_math_min" => Self::MathMin, - "host_math_max" => Self::MathMax, - "host_random" => Self::Random, - "host_random_int" => Self::RandomInt, - "host_seed" => Self::Seed, - "host_formula" => Self::Formula, - "host_simplify" => Self::Simplify, - "host_expand" => Self::Expand, - "host_diff" => Self::Diff, - "host_subs" => Self::Subs, - "host_eval" => Self::Eval, - "host_solve" => Self::Solve, - // Friendly aliases so L1 `plot` / `绘图` get host optionals (`grid`, `path`, …) - // instead of thin wrappers that only forward required params. - "host_plot" | "plot" | "绘图" => Self::Plot, - "host_plot_points" | "plot_points" | "绘点列" => Self::PlotPoints, - "host_plot_conic" | "plot_conic" | "绘圆锥" => Self::PlotConic, - "host_foreign_set_cmd" => Self::ForeignSetCmd, - "host_foreign_run" => Self::ForeignRun, - "host_foreign_run_lang" => Self::ForeignRunLang, - "host_foreign_invoke" | "foreign_invoke" => Self::ForeignInvoke, - "host_foreign_probe" | "foreign_probe" => Self::ForeignProbe, - "host_foreign_register" | "foreign_register" => Self::ForeignRegister, - "host_foreign_unset" | "foreign_unset" => Self::ForeignUnset, - "host_foreign_load_config" | "foreign_load_config" => Self::ForeignLoadConfig, - "host_foreign_call" | "foreign_call" => Self::ForeignCall, - "host_foreign_run_many" | "foreign_run_many" => Self::ForeignRunMany, - "host_foreign_call_many" | "foreign_call_many" => Self::ForeignCallMany, - "host_foreign_session_open" | "foreign_session_open" => Self::ForeignSessionOpen, - "host_foreign_session_eval" | "foreign_session_eval" => Self::ForeignSessionEval, - "host_foreign_session_set" | "foreign_session_set" => Self::ForeignSessionSet, - "host_foreign_session_get" | "foreign_session_get" => Self::ForeignSessionGet, - "host_foreign_session_names" | "foreign_session_names" => Self::ForeignSessionNames, - "host_foreign_session_close" | "foreign_session_close" => Self::ForeignSessionClose, - "host_foreign_session_list" | "foreign_session_list" => Self::ForeignSessionList, - "host_foreign_session_interrupt" | "foreign_session_interrupt" => Self::ForeignSessionInterrupt, - "host_foreign_langs" => Self::ForeignLangs, - "host_dotenv_load" | "load_dotenv" => Self::DotenvLoad, - "host_http_request" | "http_request" => Self::HttpRequest, - "host_json_quote" | "quote" => Self::JsonQuote, - "host_plugin_load" | "plugin_load" => Self::PluginLoad, - "host_plugin_unload" | "plugin_unload" => Self::PluginUnload, - "host_plugin_list" | "plugin_list" => Self::PluginList, - "host_access" | "access" | "取" | "取值" => Self::Access, - "host_ext_native_path" | "ext_native_path" => Self::ExtNativePath, - "host_map_set" | "map_set" => Self::MapSet, - "host_list_append" | "list_append" => Self::ListAppend, - "host_writeback_record" | "writeback_record" => Self::WritebackRecord, - "host_writeback_get" | "writeback_get" => Self::WritebackGet, - "host_writeback_clear" | "writeback_clear" => Self::WritebackClear, - "host_writeback_list" | "writeback_list" => Self::WritebackList, - "host_writeback_ensure" | "writeback_ensure" => Self::WritebackEnsure, - "host_outer_call_line" | "outer_call_line" => Self::OuterCallLine, - "host_text_patch" | "text_patch" => Self::TextPatch, - "host_apply_patch_blocks" | "apply_patch_blocks" => Self::ApplyPatchBlocks, - "host_writeback_scan_path" | "writeback_scan_path" => Self::WritebackScanPath, - "host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn, - "host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll, - "host_subtask_join" | "subtask_join" => Self::SubtaskJoin, - "host_subtask_kill" | "subtask_kill" => Self::SubtaskKill, - "host_subtask_wait_all" | "subtask_wait_all" => Self::SubtaskWaitAll, - "host_collection_put" | "collection_put" => Self::CollectionPut, - "host_list_prepend" | "list_prepend" => Self::ListPrepend, - "host_list_concat" | "list_concat" => Self::ListConcat, - "host_list_insert" | "list_insert" => Self::ListInsert, - "host_list_set_at" | "list_set_at" => Self::ListSetAt, - "host_list_remove_at" | "list_remove_at" => Self::ListRemoveAt, - "host_list_slice" | "list_slice" => Self::ListSlice, - "host_list_contains" | "list_contains" => Self::ListContains, - "host_list_index_of" | "list_index_of" => Self::ListIndexOf, - "host_list_reverse" | "list_reverse" => Self::ListReverse, - "host_list_first" | "list_first" => Self::ListFirst, - "host_list_last" | "list_last" => Self::ListLast, - "host_map_get" | "map_get" => Self::MapGet, - "host_map_delete" | "map_delete" => Self::MapDelete, - "host_map_has" | "map_has" => Self::MapHas, - "host_map_keys" | "map_keys" => Self::MapKeys, - "host_map_values" | "map_values" => Self::MapValues, - "host_map_items" | "map_items" => Self::MapItems, - "host_map_merge" | "map_merge" => Self::MapMerge, - "host_map_size" | "map_size" => Self::MapSize, - "host_collection_clear" | "collection_clear" => Self::CollectionClear, - "host_cookie_parse" | "cookie_parse" => Self::CookieParse, - "host_multipart_parse" | "multipart_parse" => Self::MultipartParse, - "host_markdown_parse" | "markdown_parse" => Self::MarkdownParse, - "host_re_is_match" | "re_is_match" => Self::ReIsMatch, - "host_re_find" | "re_find" => Self::ReFind, - "host_re_find_all" | "re_find_all" => Self::ReFindAll, - "host_re_replace" | "re_replace" => Self::ReReplace, - "host_re_split" | "re_split" => Self::ReSplit, - "host_encoding_base64_encode" | "encoding_base64_encode" => Self::EncodingBase64Encode, - "host_encoding_base64_decode" | "encoding_base64_decode" => Self::EncodingBase64Decode, - "host_encoding_hex_encode" | "encoding_hex_encode" => Self::EncodingHexEncode, - "host_encoding_hex_decode" | "encoding_hex_decode" => Self::EncodingHexDecode, - "host_path_join" | "path_join" => Self::PathJoin, - "host_path_split" | "path_split" => Self::PathSplit, - "host_path_file_name" | "path_file_name" => Self::PathFileName, - "host_path_parent" | "path_parent" => Self::PathParent, - "host_path_extension" | "path_extension" => Self::PathExtension, - "host_path_normalize" | "path_normalize" => Self::PathNormalize, - "host_path_is_absolute" | "path_is_absolute" => Self::PathIsAbsolute, - "host_copy_file" | "copy_file" => Self::FsCopyFile, - "host_move" | "move_path" => Self::FsMove, - "host_make_temp" | "make_temp" => Self::FsMakeTemp, - "host_hash_sha256" | "hash_sha256" => Self::HashSha256, - "host_hash_sha1" | "hash_sha1" => Self::HashSha1, - "host_hash_md5" | "hash_md5" => Self::HashMd5, - "host_hash_hmac_sha256" | "hash_hmac_sha256" => Self::HashHmacSha256, - "host_secrets_token_hex" | "secrets_token_hex" => Self::SecretsTokenHex, - "host_secrets_token_urlsafe" | "secrets_token_urlsafe" => Self::SecretsTokenUrlsafe, - "host_text_contains" | "text_contains" => Self::TextContains, - "host_text_starts_with" | "text_starts_with" => Self::TextStartsWith, - "host_text_ends_with" | "text_ends_with" => Self::TextEndsWith, - "host_text_replace" | "text_replace" => Self::TextReplace, - "host_text_to_upper" | "text_to_upper" => Self::TextToUpper, - "host_text_to_lower" | "text_to_lower" => Self::TextToLower, - "host_text_repeat" | "text_repeat" => Self::TextRepeat, - "host_text_pad" | "text_pad" => Self::TextPad, - "host_csv_parse" | "csv_parse" => Self::CsvParse, - "host_csv_stringify" | "csv_stringify" => Self::CsvStringify, - "host_list_sort" | "list_sort" => Self::ListSort, - "host_list_sort_by" | "list_sort_by" => Self::ListSortBy, - "host_list_unique" | "list_unique" => Self::ListUnique, - "host_list_chunk" | "list_chunk" => Self::ListChunk, - "host_list_zip" | "list_zip" => Self::ListZip, - "host_list_flatten" | "list_flatten" => Self::ListFlatten, - "host_cli_parse" | "cli_parse" => Self::CliParse, - "host_log_set_level" | "log_set_level" => Self::LogSetLevel, - "host_log_line" | "log_line" => Self::LogLine, - "host_uuid_v4" | "uuid_v4" => Self::UuidV4, - "host_datetime_now" | "datetime_now" => Self::DatetimeNow, - "host_datetime_from_unix" | "datetime_from_unix" => Self::DatetimeFromUnix, - "host_datetime_to_unix" | "datetime_to_unix" => Self::DatetimeToUnix, - "host_datetime_parse" | "datetime_parse" => Self::DatetimeParse, - "host_datetime_format" | "datetime_format" => Self::DatetimeFormat, - "host_datetime_add" | "datetime_add" => Self::DatetimeAdd, - "host_datetime_in_zone" | "datetime_in_zone" => Self::DatetimeInZone, - "host_url_parse" | "url_parse" => Self::UrlParse, - "host_url_query_parse" | "url_query_parse" => Self::UrlQueryParse, - "host_url_query_stringify" | "url_query_stringify" => Self::UrlQueryStringify, - "host_toml_parse" | "toml_parse" => Self::TomlParse, - "host_html_escape" | "html_escape" => Self::HtmlEscape, - "host_html_unescape" | "html_unescape" => Self::HtmlUnescape, - "host_encoding_base32_encode" | "encoding_base32_encode" => Self::EncodingBase32Encode, - "host_encoding_base32_decode" | "encoding_base32_decode" => Self::EncodingBase32Decode, - "host_make_dirs" | "make_dirs" => Self::FsMakeDirs, - "host_remove_tree" | "remove_tree" => Self::FsRemoveTree, - "host_stat" | "stat" => Self::FsStat, - "host_walk" | "walk" => Self::FsWalk, - "host_stats_mean" | "stats_mean" => Self::StatsMean, - "host_stats_median" | "stats_median" => Self::StatsMedian, - "host_stats_stdev" | "stats_stdev" => Self::StatsStdev, - "host_meta" | "meta" => Self::Meta, - "host_meta_get" | "meta_get" => Self::MetaGet, - "host_module_source" | "module_source" => Self::ModuleSource, - "host_artifact_kind" | "artifact_kind" => Self::ArtifactKind, - _ => return None, - }) - } - - /// Effects belong to resolved host identities, never import spellings. - /// Exhaustive match forces every new primitive to declare its effects. - pub fn effects(self) -> &'static [&'static str] { - match self { - Self::TableSummarize => &["pure"], - Self::DotenvLoad => &["fs.read", "environment.write"], - Self::ForeignLoadConfig => &["fs.read"], - Self::ExtNativePath => &["plugin.call"], - Self::ListDifference => &["pure"], - Self::ListIntersection => &["pure"], - Self::ListUnion => &["pure"], - Self::TableValidate => &["pure"], - Self::TableTryCast => &["pure"], - Self::ZipUnpack => &["fs.write"], - Self::ZipPack => &["fs.write"], - Self::HttpGetResult => &["network.read"], - Self::SubtaskRunMany => &["process.exec"], - Self::SubtaskCancelAll => &["process.exec"], - Self::SubtaskWaitTimeout => &["process.exec"], - Self::DatetimeCalendarAdd => &["pure"], - Self::DatetimeLocal => &["pure"], - Self::TomlTryParse => &["pure"], - Self::TomlStringify => &["pure"], - Self::HttpDownload => &["network.read", "fs.write"], - Self::HttpRequestResult => &["network.write"], - Self::DocumentCodeBlocks => &["pure"], - Self::DocumentLinks => &["pure"], - Self::DocumentReplaceTable => &["pure"], - Self::DocumentTables => &["pure"], - Self::DocumentTable => &["pure"], - Self::FsResolve => &["fs.read"], - Self::DocumentReplaceSection => &["pure"], - Self::DocumentSection => &["pure"], - Self::DocumentSections => &["pure"], - Self::PathWithExtension => &["pure"], - Self::PathRelative => &["pure"], - Self::FsRenameMany => &["fs.write"], - Self::FsSyncTree => &["fs.write"], - Self::FsCopyTree => &["fs.write"], - Self::FsFind => &["fs.read"], - Self::FsFileHash => &["fs.read"], - Self::FsTempDir => &["fs.write"], - Self::FsRemoveEmptyDir => &["fs.write"], - Self::FsRemoveFile => &["fs.write"], - Self::FsWriteLines => &["fs.write"], - Self::FsReadLines => &["fs.read"], - Self::FsWriteChecked => &["fs.write"], - Self::FsWriteChanged => &["fs.write"], - Self::FsAtomicWrite => &["fs.write"], - Self::FsAppendBytes => &["fs.write"], - Self::FsReadChunk => &["fs.read"], - Self::FsWriteBytes => &["fs.write"], - Self::FsReadBytes => &["fs.read"], - Self::BytesSlice => &["pure"], - Self::BytesLen => &["pure"], - Self::BytesToBase64 => &["pure"], - Self::BytesToText => &["pure"], - Self::BytesFromBase64 => &["pure"], - Self::BytesFromText => &["pure"], - Self::TryCsvParse => &["pure"], - Self::TryJsonParse => &["pure"], - Self::FsTryWriteText => &["fs.write"], - Self::FsTryReadText => &["fs.read"], - Self::TableCast => &["pure"], - Self::ListJoin => &["pure"], - Self::TableToColumns => &["pure"], - Self::TableFromColumns => &["pure"], - Self::ListRename => &["pure"], - Self::ListSortKeys => &["pure"], - Self::ListAggregate => &["pure"], - Self::ListUniqueBy => &["pure"], - Self::ListGroupBy => &["pure"], - Self::ListWhere => &["pure"], - Self::ListProject => &["pure"], - Self::ListPluck => &["pure"], - Self::ListEnumerate => &["pure"], - Self::ListRange => &["pure"], - Self::ReadText - | Self::Exists - | Self::ListDir - | Self::FsStat - | Self::FsWalk - | Self::WritebackGet - | Self::WritebackList - | Self::WritebackScanPath => &["fs.read"], - Self::WriteText - | Self::AppendText - | Self::MakeDir - | Self::Remove - | Self::FsCopyFile - | Self::FsMove - | Self::FsMakeTemp - | Self::FsMakeDirs - | Self::FsRemoveTree - | Self::TextPatch - | Self::ApplyPatchBlocks - | Self::WritebackRecord - | Self::WritebackClear - | Self::WritebackEnsure => &["fs.write"], - Self::HttpGet => &["network.read"], - Self::HttpRequest => &["network.write"], - Self::HttpPost | Self::HttpPostSse => &["network.write"], - Self::Exec - | Self::SubtaskSpawn - | Self::SubtaskPoll - | Self::SubtaskJoin - | Self::SubtaskKill - | Self::SubtaskWaitAll - | Self::ForeignRun - | Self::ForeignRunLang - | Self::ForeignInvoke - | Self::ForeignProbe - | Self::ForeignCall - | Self::ForeignRunMany - | Self::ForeignCallMany - | Self::ForeignSessionOpen - | Self::ForeignSessionEval - | Self::ForeignSessionSet - | Self::ForeignSessionGet - | Self::ForeignSessionNames - | Self::ForeignSessionClose - | Self::ForeignSessionList - | Self::ForeignSessionInterrupt => &["process.exec"], - Self::PluginLoad | Self::PluginUnload => &["plugin.call"], - Self::LogLine - | Self::StreamPublish - | Self::Plot - | Self::PlotPoints - | Self::PlotConic => &["output.write"], - Self::NowUnix | Self::NowMs | Self::DatetimeNow => &["time.read"], - Self::Random - | Self::RandomInt - | Self::SecretsTokenHex - | Self::SecretsTokenUrlsafe - | Self::UuidV4 => &["random.read"], - Self::EnvGet => &["environment.read"], - Self::EnvSet => &["environment.write"], - Self::Exit | Self::SleepMs => &["process.control"], - Self::FormatTime - | Self::ParseTime - | Self::Args - | Self::Cwd - | Self::JsonParse - | Self::JsonStringify - | Self::JsonGet - | Self::JsonKeys - | Self::UrlEncode - | Self::Pi - | Self::EConst - | Self::Num - | Self::MathAdd - | Self::MathSub - | Self::MathMul - | Self::MathDiv - | Self::MathPow - | Self::MathNeg - | Self::MathSin - | Self::MathCos - | Self::MathTan - | Self::MathAsin - | Self::MathAcos - | Self::MathAtan - | Self::MathSqrt - | Self::MathAbs - | Self::MathLn - | Self::MathExp - | Self::MathFloor - | Self::MathCeil - | Self::MathMin - | Self::MathMax - | Self::Seed - | Self::Formula - | Self::Simplify - | Self::Expand - | Self::Diff - | Self::Subs - | Self::Eval - | Self::Solve - | Self::ForeignSetCmd - | Self::ForeignLangs - | Self::JsonQuote - | Self::PluginList - | Self::MapSet - | Self::ListAppend - | Self::OuterCallLine - | Self::OpenAiSseParse - | Self::CollectionPut - | Self::ListPrepend - | Self::ListConcat - | Self::ListInsert - | Self::ListSetAt - | Self::ListRemoveAt - | Self::ListSlice - | Self::ListContains - | Self::ListIndexOf - | Self::ListReverse - | Self::ListFirst - | Self::ListLast - | Self::MapGet - | Self::MapDelete - | Self::MapHas - | Self::MapKeys - | Self::MapValues - | Self::MapItems - | Self::MapMerge - | Self::MapSize - | Self::CollectionClear - | Self::CookieParse - | Self::MultipartParse - | Self::MarkdownParse - | Self::ReIsMatch - | Self::ReFind - | Self::ReFindAll - | Self::ReReplace - | Self::ReSplit - | Self::EncodingBase64Encode - | Self::EncodingBase64Decode - | Self::EncodingHexEncode - | Self::EncodingHexDecode - | Self::PathJoin - | Self::PathSplit - | Self::PathFileName - | Self::PathParent - | Self::PathExtension - | Self::PathNormalize - | Self::PathIsAbsolute - | Self::HashSha256 - | Self::HashSha1 - | Self::HashMd5 - | Self::HashHmacSha256 - | Self::TextContains - | Self::TextStartsWith - | Self::TextEndsWith - | Self::TextReplace - | Self::TextToUpper - | Self::TextToLower - | Self::TextRepeat - | Self::TextPad - | Self::CsvParse - | Self::CsvStringify - | Self::ListSort - | Self::ListSortBy - | Self::ListUnique - | Self::ListChunk - | Self::ListZip - | Self::ListFlatten - | Self::CliParse - | Self::LogSetLevel - | Self::DatetimeFromUnix - | Self::DatetimeToUnix - | Self::DatetimeParse - | Self::DatetimeFormat - | Self::DatetimeAdd - | Self::DatetimeInZone - | Self::UrlParse - | Self::UrlQueryParse - | Self::UrlQueryStringify - | Self::TomlParse - | Self::HtmlEscape - | Self::HtmlUnescape - | Self::EncodingBase32Encode - | Self::EncodingBase32Decode - | Self::StatsMean - | Self::StatsMedian - | Self::StatsStdev - | Self::Meta - | Self::MetaGet - | Self::ModuleSource - | Self::ArtifactKind - | Self::ForeignRegister - | Self::ForeignUnset - | Self::Access - | Self::OracleJournal - | Self::OracleReplayCheck => &["pure"], - } - } - - pub fn as_u16(self) -> u16 { - self as u16 - } - - pub fn name(self) -> &'static str { - HOST_FN_TABLE - .iter() - .find(|d| d.f.as_u16() == self.as_u16()) - .map(|d| d.name) - .unwrap_or("host_unknown") - } - - pub fn required_params(self) -> &'static [&'static str] { - HOST_FN_TABLE - .iter() - .find(|d| d.f.as_u16() == self.as_u16()) - .map(|d| d.required) - .unwrap_or(&[]) - } - - pub fn optional_params(self) -> &'static [&'static str] { - HOST_FN_TABLE - .iter() - .find(|d| d.f.as_u16() == self.as_u16()) - .map(|d| d.optional) - .unwrap_or(&[]) - } - - pub fn all_params(self) -> Vec<&'static str> { - let mut v = self.required_params().to_vec(); - v.extend_from_slice(self.optional_params()); - v - } -} - -pub fn call_host( - ctx: &mut HostContext, - fn_id: HostFn, - bound: &HashMap, -) -> Result { - match fn_id { - HostFn::TableSummarize => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListDifference => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListIntersection => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListUnion => super::collection_ops::call(ctx, fn_id, bound), - HostFn::TableValidate => super::collection_ops::call(ctx, fn_id, bound), - HostFn::TableTryCast => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ZipUnpack => super::archive::call(ctx, fn_id, bound), - HostFn::ZipPack => super::archive::call(ctx, fn_id, bound), - HostFn::HttpGetResult => super::net_ops::call(ctx, fn_id, bound), - HostFn::SubtaskRunMany => super::task_ops::call(ctx, fn_id, bound), - HostFn::SubtaskCancelAll => super::task_ops::call(ctx, fn_id, bound), - HostFn::SubtaskWaitTimeout => super::task_ops::call(ctx, fn_id, bound), - HostFn::DatetimeCalendarAdd => super::data_ops::call(ctx, fn_id, bound), - HostFn::DatetimeLocal => super::data_ops::call(ctx, fn_id, bound), - HostFn::TomlTryParse => super::data_ops::call(ctx, fn_id, bound), - HostFn::TomlStringify => super::data_ops::call(ctx, fn_id, bound), - HostFn::HttpDownload => super::net_ops::call(ctx, fn_id, bound), - HostFn::HttpRequestResult => super::net_ops::call(ctx, fn_id, bound), - HostFn::DocumentCodeBlocks => super::document::call(ctx, fn_id, bound), - HostFn::DocumentLinks => super::document::call(ctx, fn_id, bound), - HostFn::DocumentReplaceTable => super::document::call(ctx, fn_id, bound), - HostFn::DocumentTables => super::document::call(ctx, fn_id, bound), - HostFn::DocumentTable => super::document::call(ctx, fn_id, bound), - HostFn::DocumentReplaceSection => super::document::call(ctx, fn_id, bound), - HostFn::DocumentSection => super::document::call(ctx, fn_id, bound), - HostFn::DocumentSections => super::document::call(ctx, fn_id, bound), - HostFn::PathWithExtension => super::fs_ops::call(ctx, fn_id, bound), - HostFn::PathRelative => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsRenameMany => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsSyncTree => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsCopyTree => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsFind => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsFileHash => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsTempDir => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsRemoveEmptyDir => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsRemoveFile => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsWriteLines => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsReadLines => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsWriteChecked => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsWriteChanged => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsAtomicWrite => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsAppendBytes => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsReadChunk => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsWriteBytes => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsReadBytes => super::fs_ops::call(ctx, fn_id, bound), - HostFn::BytesSlice => super::fs_ops::call(ctx, fn_id, bound), - HostFn::BytesLen => super::fs_ops::call(ctx, fn_id, bound), - HostFn::BytesToBase64 => super::fs_ops::call(ctx, fn_id, bound), - HostFn::BytesToText => super::fs_ops::call(ctx, fn_id, bound), - HostFn::BytesFromBase64 => super::fs_ops::call(ctx, fn_id, bound), - HostFn::BytesFromText => super::fs_ops::call(ctx, fn_id, bound), - HostFn::TryCsvParse => super::fs_ops::call(ctx, fn_id, bound), - HostFn::TryJsonParse => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsTryWriteText => super::fs_ops::call(ctx, fn_id, bound), - HostFn::FsTryReadText => super::fs_ops::call(ctx, fn_id, bound), - HostFn::TableCast => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListJoin => super::collection_ops::call(ctx, fn_id, bound), - HostFn::TableToColumns => super::collection_ops::call(ctx, fn_id, bound), - HostFn::TableFromColumns => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListRename => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListSortKeys => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListAggregate => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListUniqueBy => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListGroupBy => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListWhere => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListProject => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListPluck => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListEnumerate => super::collection_ops::call(ctx, fn_id, bound), - HostFn::ListRange => super::collection_ops::call(ctx, fn_id, bound), - HostFn::Access => { - let base = require(bound, "value")?; - let key = match require(bound, "key")? { - Value::Text(t) => t.clone(), - Value::Int(i) => i.to_string(), - other => crate::builtin::builtin_str(other).as_display(), - }; - crate::builtin::builtin_footnote_get(base, &key) - } - HostFn::ReadText => fs::read_text(ctx, require(bound, "path")?), - HostFn::WriteText => { - fs::write_text(ctx, require(bound, "path")?, require(bound, "text")?) - } - HostFn::AppendText => { - fs::append_text(ctx, require(bound, "path")?, require(bound, "text")?) - } - HostFn::Exists => fs::exists(ctx, require(bound, "path")?), - HostFn::ListDir => fs::list_dir(ctx, require(bound, "path")?), - HostFn::MakeDir => fs::make_dir(ctx, require(bound, "path")?), - HostFn::Remove => fs::remove(ctx, require(bound, "path")?), - HostFn::FsMakeDirs => fs::make_dirs(ctx, require(bound, "path")?), - HostFn::FsRemoveTree => fs::remove_tree(ctx, require(bound, "path")?), - HostFn::FsStat => fs::stat(ctx, require(bound, "path")?), - HostFn::FsResolve => fs::resolve(ctx, require(bound, "path")?), - HostFn::FsWalk => fs::walk(ctx, require(bound, "path")?), - HostFn::NowUnix => time::now_unix(), - HostFn::NowMs => time::now_ms(), - HostFn::FormatTime => { - time::format_time(require(bound, "unix")?, require(bound, "pattern")?) - } - HostFn::SleepMs => time::sleep_ms(ctx, require(bound, "ms")?), - HostFn::ParseTime => { - time::parse_time(require(bound, "text")?, require(bound, "pattern")?) - } - HostFn::EnvGet => sys::env_get(require(bound, "name")?), - HostFn::EnvSet => sys::env_set(require(bound, "name")?, require(bound, "value")?), - HostFn::DotenvLoad => sys::dotenv_load(ctx, bound.get("path")), - HostFn::Args => sys::args(ctx), - HostFn::Cwd => sys::cwd(ctx), - HostFn::Meta => sys::meta(ctx), - HostFn::MetaGet => sys::meta_get(ctx, require(bound, "key")?), - HostFn::ModuleSource => crate::host::agent_rt::module_source(ctx), - HostFn::ArtifactKind => sys::artifact_kind(ctx), - HostFn::Exit => sys::exit(ctx, require(bound, "code")?), - HostFn::Exec => sys::exec( - ctx, - require(bound, "cmd")?, - bound.get("args"), - bound.get("capture"), - ), - HostFn::OracleJournal => Ok(Value::List(ctx.oracle_observations.clone())), - HostFn::OracleReplayCheck => super::oracle::replay_check(require(bound, "expected")?, require(bound, "observed")?), - HostFn::JsonParse => { - let value = json::parse(require(bound, "text")?)?; - super::oracle::append(ctx, "decode", &value)?; - Ok(value) - }, - HostFn::JsonStringify => { - json::stringify(require(bound, "value")?, bound.get("indent")) - } - HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?), - HostFn::JsonKeys => json::keys(require(bound, "value")?), - HostFn::JsonQuote => json::quote(require(bound, "text")?), - HostFn::HttpGet => { - #[cfg(feature = "net-host")] - { - net::http_get(ctx, require(bound, "url")?, bound.get("headers")) - } - #[cfg(not(feature = "net-host"))] - { - let _ = (ctx, bound); - Err("http_get unavailable in browser wasm".into()) - } - } - HostFn::HttpPost => { - #[cfg(feature = "net-host")] - { - net::http_post( - ctx, - require(bound, "url")?, - require(bound, "body")?, - bound.get("content_type"), - bound.get("headers"), - ) - } - #[cfg(not(feature = "net-host"))] - { - let _ = (ctx, bound); - Err("http_post unavailable in browser wasm".into()) - } - } - HostFn::HttpPostSse => { - #[cfg(feature = "net-host")] - { - net::http_post_sse( - ctx, - require(bound, "url")?, - require(bound, "body")?, - bound.get("content_type"), - bound.get("headers"), - bound.get("echo"), - ) - } - #[cfg(not(feature = "net-host"))] - { - let _ = (ctx, bound); - Err("http_post_sse unavailable in browser wasm".into()) - } - } - HostFn::OpenAiSseParse => { - net::openai_sse_parse(require(bound, "text")?, bound.get("echo")) - } - HostFn::StreamPublish => { - crate::host::event_bus::publish(require(bound, "event")?); - Ok(Value::Bool(true)) - } - HostFn::HttpRequest => { - #[cfg(feature = "net-host")] - { - net::http_request( - ctx, - require(bound, "method")?, - require(bound, "url")?, - bound.get("body"), - bound.get("content_type"), - bound.get("headers"), - ) - } - #[cfg(not(feature = "net-host"))] - { - let _ = (ctx, bound); - Err("http_request unavailable in browser wasm".into()) - } - } - HostFn::UrlEncode => net::url_encode(require(bound, "text")?), - HostFn::Pi => math::pi(), - HostFn::EConst => math::e_const(), - HostFn::Num => math::to_num(require(bound, "value")?), - HostFn::MathAdd => math::binary_num("add", require(bound, "a")?, require(bound, "b")?), - HostFn::MathSub => math::binary_num("sub", require(bound, "a")?, require(bound, "b")?), - HostFn::MathMul => math::binary_num("mul", require(bound, "a")?, require(bound, "b")?), - HostFn::MathDiv => math::binary_num("div", require(bound, "a")?, require(bound, "b")?), - HostFn::MathPow => math::binary_num("pow", require(bound, "a")?, require(bound, "b")?), - HostFn::MathMin => math::binary_num("min", require(bound, "a")?, require(bound, "b")?), - HostFn::MathMax => math::binary_num("max", require(bound, "a")?, require(bound, "b")?), - HostFn::MathNeg => math::unary_num("neg", require(bound, "value")?), - HostFn::MathSin => math::unary_num("sin", require(bound, "value")?), - HostFn::MathCos => math::unary_num("cos", require(bound, "value")?), - HostFn::MathTan => math::unary_num("tan", require(bound, "value")?), - HostFn::MathAsin => math::unary_num("asin", require(bound, "value")?), - HostFn::MathAcos => math::unary_num("acos", require(bound, "value")?), - HostFn::MathAtan => math::unary_num("atan", require(bound, "value")?), - HostFn::MathSqrt => math::unary_num("sqrt", require(bound, "value")?), - HostFn::MathAbs => math::unary_num("abs", require(bound, "value")?), - HostFn::MathLn => math::unary_num("ln", require(bound, "value")?), - HostFn::MathExp => math::unary_num("exp", require(bound, "value")?), - HostFn::MathFloor => math::unary_num("floor", require(bound, "value")?), - HostFn::MathCeil => math::unary_num("ceil", require(bound, "value")?), - HostFn::Random => math::random(ctx), - HostFn::RandomInt => { - math::random_int(ctx, require(bound, "min")?, require(bound, "max")?) - } - HostFn::Seed => math::seed(ctx, require(bound, "value")?), - HostFn::Formula => math::formula_parse(require(bound, "value")?), - HostFn::Simplify => math::simplify(require(bound, "value")?), - HostFn::Expand => math::expand(require(bound, "value")?), - HostFn::Diff => math::diff(require(bound, "formula")?, require(bound, "var")?), - HostFn::Subs => math::subs( - require(bound, "formula")?, - require(bound, "var")?, - require(bound, "value")?, - ), - HostFn::Eval => math::eval_at( - require(bound, "formula")?, - require(bound, "var")?, - require(bound, "value")?, - ), - HostFn::Solve => math::solve( - require(bound, "formula")?, - require(bound, "var")?, - bound.get("min"), - bound.get("max"), - ), - HostFn::Plot => math::plot( - ctx, - require(bound, "formula")?, - require(bound, "var")?, - require(bound, "min")?, - require(bound, "max")?, - bound.get("steps"), - bound.get("path"), - bound.get("derivative"), - bound.get("grid"), - ), - HostFn::PlotPoints => math::plot_points( - ctx, - require(bound, "xs")?, - require(bound, "ys")?, - bound.get("path"), - bound.get("grid"), - ), - HostFn::PlotConic => math::plot_conic( - ctx, - require(bound, "kind")?, - require(bound, "a")?, - bound.get("b"), - bound.get("h"), - bound.get("k"), - bound.get("path"), - bound.get("grid"), - ), - HostFn::ForeignSetCmd => { - #[cfg(feature = "exec-host")] - { - foreign::set_cmd( - ctx, - require(bound, "lang")?, - require(bound, "cmd")?, - bound.get("args"), - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignRun => { - #[cfg(feature = "exec-host")] - { - foreign::run_with_options( - ctx, - require(bound, "code")?, - bound.get("stdin"), - bound, - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignRunLang => { - #[cfg(feature = "exec-host")] - { - foreign::run_lang_with_options( - ctx, - require(bound, "lang")?, - require(bound, "source")?, - bound.get("stdin"), - bound, - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignInvoke => { - #[cfg(feature = "exec-host")] - { - foreign::invoke( - ctx, - foreign::InvokeArgs { - code: bound.get("code"), - lang: bound.get("lang"), - source: bound.get("source"), - stdin: bound.get("stdin"), - input: bound.get("input"), - env: bound.get("env"), - cwd: bound.get("cwd"), - timeout: bound.get("timeout"), - args: bound.get("args"), - output: bound.get("output"), - max_output: bound.get("max_output"), - cmd: bound.get("cmd"), - keep: bound.get("keep"), - }, - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignProbe => { - #[cfg(feature = "exec-host")] - { - foreign::probe(ctx, bound.get("lang")) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignRegister => { - #[cfg(feature = "exec-host")] - { - foreign::register( - ctx, - require(bound, "lang")?, - bound.get("cmd"), - bound.get("args"), - bound.get("template"), - bound.get("ext"), - bound.get("env"), - bound.get("version_args"), - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignUnset => { - #[cfg(feature = "exec-host")] - { - foreign::unset(ctx, require(bound, "lang")?) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignLoadConfig => { - #[cfg(feature = "exec-host")] - { - foreign::load_config(ctx, bound.get("path")) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignCall => { - #[cfg(feature = "exec-host")] - { - foreign::call( - ctx, - foreign::InvokeArgs { - code: bound.get("code"), - lang: bound.get("lang"), - source: bound.get("source"), - stdin: bound.get("stdin"), - input: bound.get("input"), - env: bound.get("env"), - cwd: bound.get("cwd"), - timeout: bound.get("timeout"), - args: bound.get("args"), - output: None, - max_output: None, - cmd: None, - keep: None, - }, - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignRunMany => { - #[cfg(feature = "exec-host")] - { - foreign::run_many( - ctx, - require(bound, "runs")?, - bound.get("concurrency"), - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignCallMany => { - #[cfg(feature = "exec-host")] - { - foreign::call_many( - ctx, - foreign::InvokeArgs { - code: bound.get("code"), - lang: bound.get("lang"), - source: bound.get("source"), - stdin: None, - input: None, - env: bound.get("env"), - cwd: bound.get("cwd"), - timeout: bound.get("timeout"), - args: bound.get("args"), - output: None, - max_output: bound.get("max_output"), - cmd: bound.get("cmd"), - keep: None, - }, - require(bound, "inputs")?, - bound.get("concurrency"), - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionOpen => { - #[cfg(feature = "exec-host")] - { - crate::host::foreign_session::open( - ctx, - require(bound, "lang")?, - bound.get("cmd"), - bound.get("env"), - bound.get("cwd"), - bound.get("timeout"), - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionEval => { - #[cfg(feature = "exec-host")] - { - let record = crate::host::foreign_session::eval_with_stdin( - ctx, - require(bound, "id")?, - bound.get("code"), - bound.get("source"), - bound.get("input"), - bound.get("stdin").and_then(|v| v.reveal_text()), - bound.get("timeout"), - )?; - let value = super::oracle::eval_observation(&record)?; - super::oracle::append(ctx, "eval", &value)?; - Ok(record) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionSet => { - #[cfg(feature = "exec-host")] - { - crate::host::foreign_session::set( - ctx, - require(bound, "id")?, - require(bound, "name")?, - require(bound, "value")?, - ) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionGet => { - #[cfg(feature = "exec-host")] - { - let value = crate::host::foreign_session::get( - ctx, - require(bound, "id")?, - require(bound, "name")?, - )?; - super::oracle::append(ctx, "get", &value)?; - Ok(value) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionNames => { - #[cfg(feature = "exec-host")] - { - let value = crate::host::foreign_session::names(ctx, require(bound, "id")?)?; - super::oracle::append(ctx, "decode", &value)?; - Ok(value) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionClose => { - #[cfg(feature = "exec-host")] - { - crate::host::foreign_session::close(ctx, require(bound, "id")?) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionInterrupt => { - #[cfg(feature = "exec-host")] - { - crate::host::foreign_session::interrupt(ctx, require(bound, "id")?) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("foreign unavailable in browser wasm".into()) - } - } - HostFn::ForeignSessionList => { - #[cfg(feature = "exec-host")] - { - crate::host::foreign_session::list(ctx) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = ctx; - Ok(Value::List(Vec::new())) - } - } - HostFn::ForeignLangs => { - #[cfg(feature = "exec-host")] - { - foreign::langs(ctx) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = ctx; - Ok(Value::List(Vec::new())) - } - } - HostFn::PluginLoad => { - #[cfg(feature = "plugin-host")] - { - plugin::load(ctx, require(bound, "path")?) - } - #[cfg(not(feature = "plugin-host"))] - { - let _ = (ctx, bound); - Err("plugin.load unavailable in browser wasm".into()) - } - } - HostFn::PluginUnload => { - #[cfg(feature = "plugin-host")] - { - plugin::unload(ctx) - } - #[cfg(not(feature = "plugin-host"))] - { - let _ = ctx; - Err("plugin.unload unavailable in browser wasm".into()) - } - } - HostFn::PluginList => { - #[cfg(feature = "plugin-host")] - { - plugin::list(ctx) - } - #[cfg(not(feature = "plugin-host"))] - { - let _ = ctx; - Ok(Value::List(Vec::new())) - } - } - HostFn::ExtNativePath => { - let name = require(bound, "name")?; - let s = match name { - Value::Text(t) => t.as_str(), - _ => return Err("name must be text".into()), - }; - #[cfg(feature = "cli")] - { - Ok(match crate::ext_cli::installed_native_path(s) { - Some(p) => Value::Text(p.to_string_lossy().into_owned()), - None => Value::None, - }) - } - #[cfg(not(feature = "cli"))] - { - let _ = s; - Ok(Value::None) - } - } - HostFn::MapSet => { - super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?) - } - HostFn::ListAppend => { - super::collection::list_append(require(bound, "list")?, require(bound, "item")?) - } - HostFn::CollectionPut => super::collection::collection_put( - require(bound, "in")?, - require(bound, "at")?, - require(bound, "value")?, - ), - HostFn::ListPrepend => { - super::collection::list_prepend(require(bound, "list")?, require(bound, "item")?) - } - HostFn::ListConcat => { - super::collection::list_concat(require(bound, "a")?, require(bound, "b")?) - } - HostFn::ListInsert => { - let idx = match require(bound, "index")? { - Value::Int(n) => *n, - _ => return Err("index must be int".into()), - }; - super::collection::list_insert(require(bound, "list")?, idx, require(bound, "item")?) - } - HostFn::ListSetAt => { - let idx = match require(bound, "index")? { - Value::Int(n) => *n, - _ => return Err("index must be int".into()), - }; - super::collection::list_set_at(require(bound, "list")?, idx, require(bound, "item")?) - } - HostFn::ListRemoveAt => { - let idx = match require(bound, "index")? { - Value::Int(n) => *n, - _ => return Err("index must be int".into()), - }; - super::collection::list_remove_at(require(bound, "list")?, idx) - } - HostFn::ListSlice => super::collection::list_slice_bound( - require(bound, "list")?, - require(bound, "start")?, - bound.get("end"), - ), - HostFn::ListContains => { - super::collection::list_contains(require(bound, "list")?, require(bound, "item")?) - } - HostFn::ListIndexOf => { - super::collection::list_index_of(require(bound, "list")?, require(bound, "item")?) - } - HostFn::ListReverse => super::collection::list_reverse(require(bound, "list")?), - HostFn::ListFirst => super::collection::list_first(require(bound, "list")?), - HostFn::ListLast => super::collection::list_last(require(bound, "list")?), - HostFn::MapGet => super::collection::map_get(require(bound, "map")?, require(bound, "key")?), - HostFn::MapDelete => super::collection::map_delete(require(bound, "map")?, require(bound, "key")?), - HostFn::MapHas => super::collection::map_has(require(bound, "map")?, require(bound, "key")?), - HostFn::MapKeys => super::collection::map_keys(require(bound, "map")?), - HostFn::MapValues => super::collection::map_values(require(bound, "map")?), - HostFn::MapItems => super::collection::map_items(require(bound, "map")?), - HostFn::MapMerge => super::collection::map_merge(require(bound, "a")?, require(bound, "b")?), - HostFn::MapSize => super::collection::map_size(require(bound, "map")?), - HostFn::CollectionClear => super::collection::collection_clear(require(bound, "value")?), - HostFn::CookieParse => net::cookie_parse(require(bound, "text")?, bound.get("is_response")), - HostFn::MultipartParse => net::multipart_parse(require(bound, "body")?, require(bound, "boundary")?), - HostFn::MarkdownParse => net::markdown_parse(require(bound, "text")?), - HostFn::ReIsMatch => re::is_match(require(bound, "text")?, require(bound, "pattern")?), - HostFn::ReFind => re::find(require(bound, "text")?, require(bound, "pattern")?), - HostFn::ReFindAll => re::find_all(require(bound, "text")?, require(bound, "pattern")?), - HostFn::ReReplace => re::replace( - require(bound, "text")?, - require(bound, "pattern")?, - require(bound, "with")?, - bound.get("count"), - ), - HostFn::ReSplit => re::split(require(bound, "text")?, require(bound, "pattern")?), - HostFn::EncodingBase64Encode => encoding::base64_encode(require(bound, "text")?), - HostFn::EncodingBase64Decode => encoding::base64_decode(require(bound, "text")?), - HostFn::EncodingHexEncode => encoding::hex_encode(require(bound, "text")?), - HostFn::EncodingHexDecode => encoding::hex_decode(require(bound, "text")?), - HostFn::EncodingBase32Encode => encoding::base32_encode(require(bound, "text")?), - HostFn::EncodingBase32Decode => encoding::base32_decode(require(bound, "text")?), - HostFn::TomlParse => toml_ops::parse(require(bound, "text")?), - HostFn::HtmlEscape => html_ops::escape(require(bound, "text")?), - HostFn::HtmlUnescape => html_ops::unescape(require(bound, "text")?), - HostFn::PathJoin => path::join(require(bound, "a")?, require(bound, "b")?), - HostFn::PathSplit => path::split(require(bound, "path")?), - HostFn::PathFileName => path::file_name(require(bound, "path")?), - HostFn::PathParent => path::parent(require(bound, "path")?), - HostFn::PathExtension => path::extension(require(bound, "path")?), - HostFn::PathNormalize => path::normalize(require(bound, "path")?), - HostFn::PathIsAbsolute => path::is_absolute(require(bound, "path")?), - HostFn::FsCopyFile => { - fs::copy_file(ctx, require(bound, "src")?, require(bound, "dest")?) - } - HostFn::FsMove => fs::move_path(ctx, require(bound, "src")?, require(bound, "dest")?), - HostFn::FsMakeTemp => fs::make_temp(ctx, bound.get("prefix")), - HostFn::HashSha256 => hash::sha256(require(bound, "text")?), - HostFn::HashSha1 => hash::sha1(require(bound, "text")?), - HostFn::HashMd5 => hash::md5(require(bound, "text")?), - HostFn::HashHmacSha256 => { - hash::hmac_sha256(require(bound, "key")?, require(bound, "text")?) - } - HostFn::SecretsTokenHex => secrets::token_hex(bound.get("n")), - HostFn::SecretsTokenUrlsafe => secrets::token_urlsafe(bound.get("n")), - HostFn::TextContains => { - text_ops::contains(require(bound, "text")?, require(bound, "sub")?) - } - HostFn::TextStartsWith => { - text_ops::starts_with(require(bound, "text")?, require(bound, "prefix")?) - } - HostFn::TextEndsWith => { - text_ops::ends_with(require(bound, "text")?, require(bound, "suffix")?) - } - HostFn::TextReplace => text_ops::replace( - require(bound, "text")?, - require(bound, "old")?, - require(bound, "new")?, - bound.get("count"), - ), - HostFn::TextToUpper => text_ops::to_upper(require(bound, "text")?), - HostFn::TextToLower => text_ops::to_lower(require(bound, "text")?), - HostFn::TextRepeat => text_ops::repeat(require(bound, "text")?, require(bound, "n")?), - HostFn::TextPad => text_ops::pad( - require(bound, "text")?, - require(bound, "width")?, - bound.get("fill"), - bound.get("align"), - ), - HostFn::CsvParse => csv::parse(require(bound, "text")?), - HostFn::CsvStringify => csv::stringify(require(bound, "rows")?), - HostFn::ListSort => super::collection::list_sort(require(bound, "list")?), - HostFn::ListSortBy => { - super::collection::list_sort_by(require(bound, "list")?, require(bound, "key")?) - } - HostFn::ListUnique => super::collection::list_unique(require(bound, "list")?), - HostFn::ListChunk => { - super::collection::list_chunk(require(bound, "list")?, require(bound, "size")?) - } - HostFn::ListZip => { - super::collection::list_zip(require(bound, "a")?, require(bound, "b")?) - } - HostFn::ListFlatten => super::collection::list_flatten(require(bound, "list")?), - HostFn::CliParse => cli::parse(ctx, bound.get("args")), - HostFn::LogSetLevel => log::set_level(ctx, require(bound, "level")?), - HostFn::LogLine => log::line( - ctx, - require(bound, "level")?, - require(bound, "text")?, - bound.get("fields"), - ), - HostFn::StatsMean => stats::mean(require(bound, "list")?), - HostFn::StatsMedian => stats::median(require(bound, "list")?), - HostFn::StatsStdev => stats::stdev(require(bound, "list")?), - HostFn::UuidV4 => uuid_ops::v4(), - HostFn::DatetimeNow => datetime::now(), - HostFn::DatetimeFromUnix => { - datetime::from_unix(require(bound, "unix")?, bound.get("zone")) - } - HostFn::DatetimeToUnix => datetime::to_unix(require(bound, "dt")?), - HostFn::DatetimeParse => datetime::parse(require(bound, "text")?, bound.get("pattern")), - HostFn::DatetimeFormat => datetime::format(require(bound, "dt")?, bound.get("style")), - HostFn::DatetimeAdd => datetime::add( - require(bound, "dt")?, - bound.get("days"), - bound.get("hours"), - bound.get("minutes"), - bound.get("seconds"), - ), - HostFn::DatetimeInZone => { - datetime::in_zone(require(bound, "dt")?, require(bound, "zone")?) - } - HostFn::UrlParse => url_ops::parse(require(bound, "text")?), - HostFn::UrlQueryParse => url_ops::query_parse(require(bound, "text")?), - HostFn::UrlQueryStringify => url_ops::query_stringify(require(bound, "map")?), - HostFn::OuterCallLine => Ok(Value::Int( - ctx.call_site_lines - .first() - .copied() - .unwrap_or(ctx.current_line) as i64, - )), - HostFn::TextPatch => fs::text_patch( - ctx, - require(bound, "path")?, - require(bound, "find")?, - require(bound, "replace")?, - ), - HostFn::ApplyPatchBlocks => fs::apply_patch_blocks( - ctx, - require(bound, "path")?, - require(bound, "text")?, - bound.get("soft"), - ), - HostFn::WritebackScanPath => writeback::scan_path(ctx, require(bound, "path")?), - HostFn::WritebackRecord => writeback::record( - ctx, - require(bound, "value")?, - bound.get("at_end"), - bound.get("key"), - bound.get("line"), - ), - HostFn::WritebackGet => writeback::get( - ctx, - bound.get("at_end"), - bound.get("key"), - bound.get("line"), - ), - HostFn::WritebackClear => writeback::clear( - ctx, - bound.get("at_end"), - bound.get("key"), - bound.get("line"), - ), - HostFn::WritebackList => writeback::list(ctx), - HostFn::WritebackEnsure => { - let placeholder = bound - .get("placeholder") - .cloned() - .unwrap_or_else(|| Value::Text("pending".into())); - writeback::ensure_slot( - ctx, - require(bound, "key")?, - &placeholder, - bound.get("line"), - ) - } - HostFn::SubtaskSpawn => { - #[cfg(feature = "exec-host")] - { - subtask::spawn(ctx, bound) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("subtask unavailable in browser wasm".into()) - } - } - HostFn::SubtaskPoll => { - #[cfg(feature = "exec-host")] - { - subtask::poll(ctx, require(bound, "id")?) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("subtask unavailable in browser wasm".into()) - } - } - HostFn::SubtaskJoin => { - #[cfg(feature = "exec-host")] - { - subtask::join(ctx, require(bound, "id")?) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("subtask unavailable in browser wasm".into()) - } - } - HostFn::SubtaskKill => { - #[cfg(feature = "exec-host")] - { - subtask::kill(ctx, require(bound, "id")?) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, bound); - Err("subtask unavailable in browser wasm".into()) - } - } - HostFn::SubtaskWaitAll => { - #[cfg(feature = "exec-host")] - { - subtask::wait_all(ctx) - } - #[cfg(not(feature = "exec-host"))] - { - let _ = ctx; - Err("subtask unavailable in browser wasm".into()) - } - } - } -} - -fn require<'a>(bound: &'a HashMap, key: &str) -> Result<&'a Value, String> { - bound - .get(key) - .ok_or_else(|| format!("host call missing `{key}`")) -} - -#[cfg(test)] -mod tests { - use super::HostFn; - - /// Every host id must round-trip through `from_u16` / `as_u16`, and every - /// canonical name through `from_name` / `name`. This pins the drift the - /// audit found (`from_name` accepted `http_get` while `name()` emitted - /// `host_http_get`) without rewriting the five tables. - #[test] - fn every_assigned_id_round_trips() { - // The id space is intentionally sparse: retired ids are never reused - // (bytecode from an older build must not silently change meaning). - let mut seen = 0; - for id in 1..=400u16 { - let Some(f) = HostFn::from_u16(id) else { - continue; // retired id - }; - seen += 1; - assert_eq!(f.as_u16(), id, "id {id} → {f:?} → {}", f.as_u16()); - } - assert!(seen >= 200, "expected ~200 live host ids, got {seen}"); - } - - #[test] - fn every_id_has_a_name_that_round_trips() { - for id in 1..=300u16 { - let Some(f) = HostFn::from_u16(id) else { - continue; - }; - let name = f.name(); - assert!(!name.is_empty(), "id {id} has an empty name"); - assert_eq!( - HostFn::from_name(name), - Some(f), - "id {id}: name `{name}` does not round-trip" - ); - } - } - - #[test] - fn names_are_unique() { - let mut seen = std::collections::HashMap::new(); - for id in 1..=300u16 { - let Some(f) = HostFn::from_u16(id) else { - continue; - }; - let name = f.name(); - if let Some(prev) = seen.insert(name.to_string(), id) { - panic!("duplicate host name `{name}` at ids {prev} and {id}"); - } - } - } - - #[test] - fn required_and_optional_params_are_disjoint() { - for id in 1..=300u16 { - let Some(f) = HostFn::from_u16(id) else { - continue; - }; - let req = f.required_params(); - let opt = f.optional_params(); - for r in req { - assert!( - !opt.contains(r), - "{:?} lists `{r}` as both required and optional", - f - ); - } - let all = f.all_params(); - let mut uniq = all.clone(); - uniq.sort_unstable(); - uniq.dedup(); - assert_eq!(uniq.len(), all.len(), "{f:?} has duplicate params"); - } - } -} - diff --git a/src/host/document.rs b/src/host/document.rs deleted file mode 100755 index 7e99646..0000000 --- a/src/host/document.rs +++ /dev/null @@ -1,455 +0,0 @@ -//! Inert Markdown structure using the same pulldown-cmark parser as rendering. -//! Byte ranges always refer to the original UTF-8 source; nothing is executed. -use super::{as_text, result}; -use crate::{ - host::{HostContext, HostFn}, - value::Value, -}; -use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd}; -use sha2::{Digest, Sha256}; -use std::collections::HashMap; -type Args = HashMap; -fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { - b.get(k).ok_or_else(|| format!("missing {k}")) -} -fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> { - as_text(arg(b, k)?, k) -} -fn map(values: Vec<(&str, Value)>) -> Value { - Value::Map(values.into_iter().map(|(k, v)| (k.into(), v)).collect()) -} -fn string(v: impl Into) -> Value { - Value::Text(v.into()) -} -fn num(v: usize) -> Value { - Value::Int(v as i64) -} -#[derive(Debug)] -struct Section { - title: String, - level: usize, - start: usize, - body: usize, - end: usize, -} -fn sections(text: &str) -> Vec
      { - let mut out: Vec
      = Vec::new(); - let mut active = None; - for (event, range) in Parser::new_ext( - text, - Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, - ) - .into_offset_iter() - { - match event { - Event::Start(Tag::Heading { level, .. }) => { - let n = level as usize; - for section in &mut out { - if section.end == text.len() && section.level >= n { - section.end = range.start - } - } - out.push(Section { - title: String::new(), - level: n, - start: range.start, - body: range.end, - end: text.len(), - }); - active = Some(out.len() - 1); - } - Event::End(TagEnd::Heading(_)) => { - if let Some(i) = active.take() { - out[i].body = range.end - } - } - Event::Text(t) | Event::Code(t) => { - if let Some(i) = active { - out[i].title.push_str(&t) - } - } - Event::SoftBreak | Event::HardBreak => { - if let Some(i) = active { - out[i].title.push(' ') - } - } - _ => {} - } - } - out -} -fn unique_section<'a>(sections: &'a [Section], title: &str) -> Result<&'a Section, String> { - let hits: Vec<_> = sections.iter().filter(|s| s.title == title).collect(); - match hits.as_slice() { - [s] => Ok(s), - [] => Err(format!("section not found: {title}")), - _ => Err(format!("ambiguous section: {title}")), - } -} -#[derive(Default)] -struct Table { - start: usize, - end: usize, - headers: Vec, - rows: Vec>, -} -fn tables(text: &str) -> Vec { - let mut out = Vec::new(); - let mut table: Option
      = None; - let mut header = false; - let mut row = Vec::new(); - let mut cell: Option = None; - for (event, range) in Parser::new_ext( - text, - Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, - ) - .into_offset_iter() - { - match event { - Event::Start(Tag::Table(_)) => { - table = Some(Table { - start: range.start, - ..Default::default() - }) - } - Event::Start(Tag::TableHead) => { - header = true; - row.clear() - } - Event::End(TagEnd::TableHead) => { - if let Some(t) = table.as_mut() { - t.headers = std::mem::take(&mut row) - } - header = false - } - Event::Start(Tag::TableRow) => row.clear(), - Event::End(TagEnd::TableRow) => { - if !header { - if let Some(t) = table.as_mut() { - t.rows.push(std::mem::take(&mut row)); - } - } - } - Event::Start(Tag::TableCell) => cell = Some(String::new()), - Event::End(TagEnd::TableCell) => { - if let Some(c) = cell.take() { - row.push(c) - } - } - Event::Text(t) | Event::Code(t) => { - if let Some(c) = cell.as_mut() { - c.push_str(&t) - } - } - Event::SoftBreak | Event::HardBreak => { - if let Some(c) = cell.as_mut() { - c.push('\n') - } - } - Event::End(TagEnd::Table) => { - if let Some(mut t) = table.take() { - t.end = range.end; - out.push(t) - } - } - _ => {} - } - } - out -} -fn literal_value(expression: crate::ast::Expr) -> Result { - use crate::ast::{Expr, Literal}; - match expression { - Expr::Literal(literal) => Ok(match literal { - Literal::None => Value::None, - Literal::Bool(value) => Value::Bool(value), - Literal::Int(value) => Value::Int(value), - Literal::Num(value) => Value::Num(value), - Literal::Text(value) => Value::Text(value), - }), - Expr::Unary { op: crate::ast::UnaryOp::Neg, expr } => match literal_value(*expr)? { - Value::Int(value) => value.checked_neg().map(Value::Int).ok_or_else(|| "negative table literal overflows an integer".into()), - Value::Num(value) => Ok(Value::Num(-value)), - _ => Err("negative table literal requires a number".into()), - }, - Expr::List(values) => values.into_iter().map(literal_value) - .collect::, _>>().map(Value::List), - Expr::Map(fields) => fields.into_iter() - .map(|(key, value)| literal_value(value).map(|value| (key, value))) - .collect::, _>>().map(Value::Map), - _ => Err("document.table accepts literal data cells; variable references, interpolation and calls are not evaluated".into()), - } -} -fn table_value(source: &str, title: Option<&str>, index: usize) -> Result { - let section_list; - let selected = if let Some(title) = title { - section_list = sections(source); - let section = unique_section(§ion_list, title)?; - &source[section.body..section.end] - } else { - source - }; - let found = tables(selected); - let table = found.get(index).ok_or_else(|| format!( - "document.table index {index} is out of range ({} tables)", found.len()))?; - let expression = crate::parse::parse_gfm_table(&selected[table.start..table.end]) - .map_err(|error| format!("document.table: {error:#}"))?; - literal_value(expression) -} - -fn check_digest(b: &Args, text: &str) -> Result<(), String> { - if let Some(Value::Text(expected)) = b.get("expected_sha256") { - if format!("{:x}", Sha256::digest(text.as_bytes())) != *expected { - return Err("conflict: document content changed".into()); - } - } - Ok(()) -} -pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { - let source = text(b, "text")?; - match id { - HostFn::DocumentSections => Ok(Value::List( - sections(source) - .into_iter() - .map(|s| { - map(vec![ - ("title", string(s.title)), - ("level", num(s.level)), - ("start", num(s.start)), - ("body_start", num(s.body)), - ("end", num(s.end)), - ("text", string(&source[s.body..s.end])), - ]) - }) - .collect(), - )), - HostFn::DocumentSection => { - let sections = sections(source); - let section = unique_section(§ions, text(b, "title")?)?; - Ok(string(&source[section.body..section.end])) - } - HostFn::DocumentReplaceSection => { - let change = (|| { - check_digest(b, source)?; - let sections = sections(source); - let section = unique_section(§ions, text(b, "title")?)?; - let mut out = source[..section.body].to_string(); - let body = text(b, "body")?; - if !out.ends_with('\n') { - out.push('\n') - } - out.push('\n'); - out.push_str(body); - if !body.ends_with('\n') { - out.push('\n') - } - out.push_str(&source[section.end..]); - Ok(string(out)) - })(); - Ok(result::capture("document.replace_section", change)) - } - HostFn::DocumentTables => Ok(Value::List( - tables(source) - .into_iter() - .map(|t| { - map(vec![ - ("start", num(t.start)), - ("end", num(t.end)), - ( - "headers", - Value::List(t.headers.into_iter().map(string).collect()), - ), - ( - "rows", - Value::List( - t.rows - .into_iter() - .map(|r| Value::List(r.into_iter().map(string).collect())) - .collect(), - ), - ), - ]) - }) - .collect(), - )), - HostFn::DocumentTable => { - let title = match b.get("title") { - None | Some(Value::None) => None, - Some(value) => Some(as_text(value, "title")?), - }; - let index = match b.get("index") { - None | Some(Value::None) => 0, - Some(Value::Int(value)) if *value >= 0 => - usize::try_from(*value).map_err(|_| "table index too large")?, - _ => return Err("table index must be a zero-based nonnegative integer".into()), - }; - table_value(source, title, index) - } - HostFn::DocumentReplaceTable => { - let change = (|| { - check_digest(b, source)?; - let index = match arg(b, "index")? { - Value::Int(n) if *n >= 0 => *n as usize, - _ => return Err("table index is zero-based nonnegative integer".into()), - }; - let tables = tables(source); - let table = tables.get(index).ok_or("table index out of range")?; - fn cells(v: &Value) -> Result, String> { - let Value::List(xs) = v else { - return Err("cells must be list of text".into()); - }; - xs.iter() - .map(|v| { - as_text(v, "cell").map(|s| { - s.replace('\\', "\\\\") - .replace('|', "\\|") - .replace('\n', "
      ") - }) - }) - .collect() - } - let headers = cells(arg(b, "headers")?)?; - if headers.is_empty() { - return Err("table needs headers".into()); - } - let Value::List(rows) = arg(b, "rows")? else { - return Err("rows must be list".into()); - }; - let mut rendered = format!( - "| {} |\n| {} |\n", - headers.join(" | "), - vec!["---"; headers.len()].join(" | ") - ); - for row in rows { - let row = cells(row)?; - if row.len() != headers.len() { - return Err("table row length differs from header".into()); - } - rendered.push_str(&format!("| {} |\n", row.join(" | "))) - } - Ok(string(format!( - "{}{}{}", - &source[..table.start], - rendered, - &source[table.end..] - ))) - })(); - Ok(result::capture("document.replace_table", change)) - } - HostFn::DocumentLinks => { - let mut out = Vec::new(); - let mut active: Vec<(String, String, usize)> = Vec::new(); - for (event, range) in Parser::new_ext( - source, - Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, - ) - .into_offset_iter() - { - match event { - Event::Start(Tag::Link { dest_url, .. }) => { - active.push((dest_url.into_string(), String::new(), range.start)) - } - Event::Text(s) | Event::Code(s) => { - if let Some((_, text, _)) = active.last_mut() { - text.push_str(&s) - } - } - Event::End(TagEnd::Link) => { - if let Some((url, text, start)) = active.pop() { - out.push(map(vec![ - ("label", string(text)), - ("target", string(url)), - ("start", num(start)), - ("end", num(range.end)), - ])) - } - } - _ => {} - } - } - Ok(Value::List(out)) - } - HostFn::DocumentCodeBlocks => { - let mut out = Vec::new(); - let mut active = None; - for (event, range) in Parser::new_ext( - source, - Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, - ) - .into_offset_iter() - { - match event { - Event::Start(Tag::CodeBlock(kind)) => { - let lang = match kind { - CodeBlockKind::Fenced(s) => s.into_string(), - CodeBlockKind::Indented => String::new(), - }; - active = Some((lang, String::new(), range.start)); - } - Event::Text(s) => { - if let Some((_, body, _)) = active.as_mut() { - body.push_str(&s) - } - } - Event::End(TagEnd::CodeBlock) => { - if let Some((lang, body, start)) = active.take() { - out.push(map(vec![ - ("language", string(lang)), - ("text", string(body)), - ("start", num(start)), - ("end", num(range.end)), - ])) - } - } - _ => {} - } - } - Ok(Value::List(out)) - } - _ => Err("not a document operation".into()), - } -} - -#[cfg(test)] -mod literal_table_tests { - use super::*; - #[test] - fn literal_values_retain_native_record_column_and_list_shapes() { - let source="# 数据\n\n| @ | name | enabled | count |\n|---|---|---|---|\n| 1 | 中国 | True | 3 |\n"; - let actual=table_value(source,Some("数据"),0).unwrap(); - assert_eq!(actual,Value::List(vec![Value::Map(vec![ - ("name".into(),Value::Text("中国".into())), - ("enabled".into(),Value::Bool(true)), - ("count".into(),Value::Int(3)), - ])])); - assert_eq!(table_value("| number |\n|---|\n| 1 |\n| 2 |\n",None,0).unwrap(),Value::List(vec![Value::Int(1),Value::Int(2)])); - let columns=table_value("| key | value |\n|---|---|\n| a | 1 |\n| b | 2 |\n",None,0).unwrap(); - assert!(matches!(columns,Value::Map(fields) if fields.iter().all(|(_, value)|matches!(value,Value::List(_))))); - } - #[test] - fn negative_numbers_none_and_false_keep_their_literal_types() { - let source="| values |\n|---|\n| -3 |\n| -0.5 |\n| None |\n| False |\n"; - assert_eq!(table_value(source,None,0).unwrap(),Value::List(vec![ - Value::Int(-3),Value::Num(-0.5),Value::None,Value::Bool(false), - ])); - } - #[test] - fn unique_sections_and_indices_skip_fenced_examples() { - let source="```text\n| code |\n|---|\n| hidden |\n```\n\n# first\n\n| x | y |\n|---|---|\n| 1 | 2 |\n\n# second\n\n| x | y |\n|---|---|\n| 3 | 4 |\n"; - let second=Value::Map(vec![("x".into(),Value::Int(3)),("y".into(),Value::Int(4))]); - assert_eq!(table_value(source,Some("second"),0).unwrap(),second); - assert_eq!(table_value(source,None,1).unwrap(),second); - assert!(table_value("# same\n\n# same\n",Some("same"),0).unwrap_err().contains("ambiguous")); - assert!(table_value(source,None,2).unwrap_err().contains("out of range")); - } - #[test] - fn rejects_dynamic_cells_duplicate_headers_and_silent_truncation() { - for source in ["| value |\n|---|\n| `outside` |\n","| x | x |\n|---|---|\n| a | b |\n","| x | y |\n|---|---|\n| a | b | extra |\n"] { - assert!(table_value(source,None,0).is_err(),"accepted {source}"); - } - let escaped="| @ | text | flag |\n|---|---|---|\n| 1 | left\\|right | False |\n"; - assert_eq!(table_value(escaped,None,0).unwrap(),Value::List(vec![Value::Map(vec![ - ("text".into(),Value::Text("left|right".into())),("flag".into(),Value::Bool(false)), - ])])); - } -} diff --git a/src/host/encoding.rs b/src/host/encoding.rs deleted file mode 100755 index d503de2..0000000 --- a/src/host/encoding.rs +++ /dev/null @@ -1,223 +0,0 @@ -//! Base64 / hex encoding for Mid M1 (`lib/encoding`). -//! No third-party crates — standard alphabet + padding. - -use crate::host::as_text; -use crate::value::Value; - - -const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -pub fn base64_encode(text: &Value) -> Result { - let s = as_text(text, "text")?; - Ok(Value::Text(encode_base64(s.as_bytes()))) -} - -pub fn base64_decode(text: &Value) -> Result { - let s = as_text(text, "text")?; - let bytes = decode_base64(s)?; - let out = String::from_utf8(bytes).map_err(|e| format!("base64_decode: invalid utf-8: {e}"))?; - Ok(Value::Text(out)) -} - -pub fn hex_encode(text: &Value) -> Result { - let s = as_text(text, "text")?; - let mut out = String::with_capacity(s.len() * 2); - for b in s.as_bytes() { - out.push_str(&format!("{b:02x}")); - } - Ok(Value::Text(out)) -} - -pub fn hex_decode(text: &Value) -> Result { - let s = as_text(text, "text")?; - if s.len() % 2 != 0 { - return Err("hex_decode: length must be even".into()); - } - let mut bytes = Vec::with_capacity(s.len() / 2); - // Require ASCII hex digits only (byte-oriented). - let raw = s.as_bytes(); - if raw.len() != s.len() { - return Err("hex_decode: needs ASCII hex".into()); - } - for i in (0..raw.len()).step_by(2) { - let hi = from_hex(raw[i])?; - let lo = from_hex(raw[i + 1])?; - bytes.push((hi << 4) | lo); - } - let out = String::from_utf8(bytes).map_err(|e| format!("hex_decode: invalid utf-8: {e}"))?; - Ok(Value::Text(out)) -} - -const B32: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - -pub fn base32_encode(text: &Value) -> Result { - let s = as_text(text, "text")?; - Ok(Value::Text(encode_base32(s.as_bytes()))) -} - -pub fn base32_decode(text: &Value) -> Result { - let s = as_text(text, "text")?; - let bytes = decode_base32(s)?; - let out = String::from_utf8(bytes).map_err(|e| format!("base32_decode: invalid utf-8: {e}"))?; - Ok(Value::Text(out)) -} - -fn encode_base32(input: &[u8]) -> String { - let mut out = String::new(); - let mut buffer: u64 = 0; - let mut bits = 0u32; - for &b in input { - buffer = (buffer << 8) | (b as u64); - bits += 8; - while bits >= 5 { - bits -= 5; - let idx = ((buffer >> bits) & 31) as usize; - out.push(B32[idx] as char); - } - } - if bits > 0 { - let idx = ((buffer << (5 - bits)) & 31) as usize; - out.push(B32[idx] as char); - } - while out.len() % 8 != 0 { - out.push('='); - } - out -} - -fn decode_base32(input: &str) -> Result, String> { - let cleaned: String = input - .chars() - .filter(|c| !c.is_whitespace()) - .map(|c| c.to_ascii_uppercase()) - .collect(); - if cleaned.len() % 8 != 0 { - return Err("base32_decode: length must be multiple of 8".into()); - } - let mut out = Vec::new(); - let mut buffer: u64 = 0; - let mut bits = 0u32; - for c in cleaned.bytes() { - if c == b'=' { - break; - } - let v = match c { - b'A'..=b'Z' => c - b'A', - b'2'..=b'7' => c - b'2' + 26, - _ => return Err(format!("base32_decode: invalid character {:?}", c as char)), - } as u64; - buffer = (buffer << 5) | v; - bits += 5; - if bits >= 8 { - bits -= 8; - out.push(((buffer >> bits) & 0xff) as u8); - } - } - Ok(out) -} - -fn from_hex(b: u8) -> Result { - match b { - b'0'..=b'9' => Ok(b - b'0'), - b'a'..=b'f' => Ok(b - b'a' + 10), - b'A'..=b'F' => Ok(b - b'A' + 10), - _ => Err(format!("hex_decode: invalid digit {:?}", b as char)), - } -} - -pub(super) fn encode_base64(input: &[u8]) -> String { - let mut out = String::with_capacity((input.len() + 2) / 3 * 4); - let mut i = 0; - while i + 3 <= input.len() { - let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8) | (input[i + 2] as u32); - out.push(B64[((n >> 18) & 63) as usize] as char); - out.push(B64[((n >> 12) & 63) as usize] as char); - out.push(B64[((n >> 6) & 63) as usize] as char); - out.push(B64[(n & 63) as usize] as char); - i += 3; - } - let rem = input.len() - i; - if rem == 1 { - let n = (input[i] as u32) << 16; - out.push(B64[((n >> 18) & 63) as usize] as char); - out.push(B64[((n >> 12) & 63) as usize] as char); - out.push('='); - out.push('='); - } else if rem == 2 { - let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8); - out.push(B64[((n >> 18) & 63) as usize] as char); - out.push(B64[((n >> 12) & 63) as usize] as char); - out.push(B64[((n >> 6) & 63) as usize] as char); - out.push('='); - } - out -} - -pub(super) fn decode_base64(input: &str) -> Result, String> { - let raw = input.as_bytes(); - if raw.len() % 4 != 0 { - return Err("base64_decode: length must be multiple of 4".into()); - } - let mut out = Vec::with_capacity(raw.len() / 4 * 3); - let mut i = 0; - while i < raw.len() { - let a = decode_b64_char(raw[i])?; - let b = decode_b64_char(raw[i + 1])?; - let c = raw[i + 2]; - let d = raw[i + 3]; - let c_val = if c == b'=' { - 0 - } else { - decode_b64_char(c)? - }; - let d_val = if d == b'=' { - 0 - } else { - decode_b64_char(d)? - }; - let n = (a << 18) | (b << 12) | (c_val << 6) | d_val; - out.push(((n >> 16) & 0xff) as u8); - if c != b'=' { - out.push(((n >> 8) & 0xff) as u8); - } - if d != b'=' { - out.push((n & 0xff) as u8); - } - if c == b'=' && d != b'=' { - return Err("base64_decode: invalid padding".into()); - } - i += 4; - } - Ok(out) -} - -fn decode_b64_char(b: u8) -> Result { - let v = match b { - b'A'..=b'Z' => b - b'A', - b'a'..=b'z' => b - b'a' + 26, - b'0'..=b'9' => b - b'0' + 52, - b'+' => 62, - b'/' => 63, - _ => return Err(format!("base64_decode: invalid character {:?}", b as char)), - }; - Ok(v as u32) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn roundtrip_hello() { - let enc = base64_encode(&Value::Text("hello".into())).unwrap(); - assert_eq!(enc, Value::Text("aGVsbG8=".into())); - let dec = base64_decode(&enc).unwrap(); - assert_eq!(dec, Value::Text("hello".into())); - let hx = hex_encode(&Value::Text("hi".into())).unwrap(); - assert_eq!(hx, Value::Text("6869".into())); - assert_eq!(hex_decode(&hx).unwrap(), Value::Text("hi".into())); - let b32 = base32_encode(&Value::Text("hello".into())).unwrap(); - assert_eq!(b32, Value::Text("NBSWY3DP".into())); - assert_eq!(base32_decode(&b32).unwrap(), Value::Text("hello".into())); - } -} diff --git a/src/host/event_bus.rs b/src/host/event_bus.rs deleted file mode 100755 index 3f4ef92..0000000 --- a/src/host/event_bus.rs +++ /dev/null @@ -1,76 +0,0 @@ -//! Process-wide stream event bus for `marqdo view` SSE (S3). -//! Publishers: LLM SSE parse, optional `host_stream_publish`. -//! Subscribers: view `GET /api/events` / `POST /api/run`. -//! -//! File subtasks set `MARQDO_EVENT_FORWARD=`; the child appends each -//! published event so the parent can fan them onto its own bus while `wait` blocks. - -use std::io::Write; -use std::sync::mpsc::{self, Receiver, Sender}; -use std::sync::{Mutex, OnceLock}; - -use crate::host::json::value_to_json; -use crate::value::Value; - -static BUS: OnceLock = OnceLock::new(); - -pub struct EventBus { - subs: Mutex>>, -} - -impl EventBus { - fn new() -> Self { - Self { - subs: Mutex::new(Vec::new()), - } - } - - pub fn global() -> &'static EventBus { - BUS.get_or_init(EventBus::new) - } - - /// Subscribe to JSON event lines (already serialized maps). - pub fn subscribe(&self) -> Receiver { - let (tx, rx) = mpsc::channel(); - if let Ok(mut g) = self.subs.lock() { - g.push(tx); - } - rx - } - - pub fn publish_json(&self, json_line: &str) { - if let Ok(mut g) = self.subs.lock() { - g.retain(|tx| tx.send(json_line.to_string()).is_ok()); - } - // Child → parent bridge (no-op unless spawn set the env). - forward_to_parent_file(json_line); - } - - pub fn publish_value(&self, v: &Value) { - if let Ok(j) = value_to_json(v) { - self.publish_json(&j.to_string()); - } - } -} - -fn forward_to_parent_file(json_line: &str) { - let Ok(path) = std::env::var("MARQDO_EVENT_FORWARD") else { - return; - }; - if path.is_empty() { - return; - } - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) - { - let _ = writeln!(f, "{json_line}"); - let _ = f.flush(); - } -} - -/// Publish a Marqdo map (or any value) onto the global bus. -pub fn publish(v: &Value) { - EventBus::global().publish_value(v); -} diff --git a/src/host/foreign.rs b/src/host/foreign.rs deleted file mode 100755 index 7937587..0000000 --- a/src/host/foreign.rs +++ /dev/null @@ -1,1967 +0,0 @@ -//! Foreign language runners (subprocess) and persistent kernels. -//! -//! F0: safe one-shot execution + structured `invoke` records. -//! Later phases add language registry, JSON bridge, parallel fan-out and sessions. - -use crate::host::as_text; -use std::collections::{HashMap, VecDeque}; -use std::io::{Read, Write}; -use std::panic::{catch_unwind, AssertUnwindSafe}; -use std::path::{Path, PathBuf}; -use std::process::{Child, Command, Stdio}; -use std::sync::{Arc, Mutex}; -use std::thread; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; - -use crate::foreign::registry::{self, LangSpec}; -use crate::foreign::split_cmd_line; -use crate::host::json::value_to_json; -use crate::host::{HostCaps, HostContext}; -use crate::value::{CodeBlock, Value}; - -const DEFAULT_TIMEOUT_SECS: f64 = 10.0; -const MAX_TIMEOUT_SECS: f64 = 3600.0; -pub(crate) const MAX_OUTPUT: usize = 1_048_576; -const MIN_OUTPUT: usize = 1024; -const MAX_OUTPUT_LIMIT: usize = 64 * 1024 * 1024; -const INPUT_ENV_CAP: usize = 8 * 1024; -const FAILURE_TAIL: usize = 4096; - - -fn opt_text(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(None), - Some(Value::Text(s)) => Ok(Some(s.clone())), - Some(Value::Secret(s)) => Ok(Some(s.clone())), - Some(_) => Err("value must be text".into()), - } -} - -fn parse_env(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(Vec::new()), - Some(Value::Map(entries)) => Ok(entries - .iter() - .map(|(k, v)| { - let value = match v { - Value::Secret(s) => s.clone(), - other => other.as_display(), - }; - (k.clone(), value) - }) - .collect()), - Some(_) => Err("env must be a map".into()), - } -} - -fn parse_args(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(Vec::new()), - Some(Value::List(xs)) => Ok(xs.iter().map(|x| x.as_display()).collect()), - Some(Value::Text(s)) => Ok(vec![s.clone()]), - Some(_) => Err("args must be list or text".into()), - } -} - -fn parse_bool(v: Option<&Value>, what: &str, default: bool) -> Result { - match v { - None | Some(Value::None) => Ok(default), - Some(Value::Bool(b)) => Ok(*b), - Some(_) => Err(format!("{what} must be bool")), - } -} - -fn parse_timeout(v: Option<&Value>) -> Result { - let secs = match v { - None | Some(Value::None) => DEFAULT_TIMEOUT_SECS, - Some(Value::Int(n)) => *n as f64, - Some(Value::Num(n)) => *n, - Some(_) => return Err("timeout must be a number of seconds".into()), - }; - if !secs.is_finite() || secs <= 0.0 { - return Err("timeout must be > 0 seconds".into()); - } - if secs > MAX_TIMEOUT_SECS { - return Err(format!("timeout must be <= {MAX_TIMEOUT_SECS} seconds")); - } - Ok(Duration::from_secs_f64(secs)) -} - -fn parse_max_output(v: Option<&Value>) -> Result { - let n = match v { - None | Some(Value::None) => MAX_OUTPUT, - Some(Value::Int(n)) if *n > 0 => *n as usize, - Some(Value::Int(_)) => return Err("max_output must be > 0".into()), - Some(_) => return Err("max_output must be an integer byte count".into()), - }; - if n < MIN_OUTPUT { - return Err(format!("max_output must be >= {MIN_OUTPUT} bytes")); - } - if n > MAX_OUTPUT_LIMIT { - return Err(format!("max_output must be <= {MAX_OUTPUT_LIMIT} bytes")); - } - Ok(n) -} - -fn as_code(v: &Value) -> Result<&CodeBlock, String> { - match v { - Value::Code(c) => Ok(c), - _ => Err("run needs a code value (bind with `name` = then a ```lang fence)".into()), - } -} - -/// One execution request. Owned so it can be sent to worker threads later. -#[derive(Debug, Clone)] -pub(crate) struct Job { - pub lang: String, - pub source: String, - pub stdin: Option, - pub input_json: Option, - pub env: Vec<(String, String)>, - pub cwd: Option, - pub timeout: Duration, - pub extra_args: Vec, - pub max_output: usize, - pub keep: bool, - pub cmd_override: Option, -} - -impl Job { - fn simple(lang: &str, source: &str, stdin: Option<&str>) -> Self { - Self { - lang: lang.to_string(), - source: source.to_string(), - stdin: stdin.map(str::to_string), - input_json: None, - env: Vec::new(), - cwd: None, - timeout: Duration::from_secs_f64(DEFAULT_TIMEOUT_SECS), - extra_args: Vec::new(), - max_output: MAX_OUTPUT, - keep: false, - cmd_override: None, - } - } -} - -/// Result of one subprocess execution. `ok` is the success bit; failures are data. -#[derive(Debug, Clone)] -pub(crate) struct Execution { - pub ok: bool, - pub code: i32, - pub stdout: String, - pub stderr: String, - pub ms: u64, - pub timed_out: bool, - pub truncated: bool, - pub error: String, - pub lang: String, - pub cmd: String, - pub script: String, - pub diagnostic_source: String, -} - -impl Execution { - fn failure_ok(&self) -> bool { - self.ok - } - - fn record(&self, result: Value, result_error: String) -> Value { - Value::Map(vec![ - ("ok".into(), Value::Bool(self.failure_ok())), - ("code".into(), Value::Int(self.code as i64)), - ("stdout".into(), Value::Text(self.stdout.clone())), - ("stderr".into(), Value::Text(self.stderr.clone())), - ("ms".into(), Value::Int(self.ms as i64)), - ("lang".into(), Value::Text(self.lang.clone())), - ("cmd".into(), Value::Text(self.cmd.clone())), - ("timed_out".into(), Value::Bool(self.timed_out)), - ("truncated".into(), Value::Bool(self.truncated)), - ("result".into(), result), - ("result_error".into(), Value::Text(result_error)), - ("error".into(), Value::Text(self.error.clone())), - ("script".into(), Value::Text(self.script.clone())), - ("diagnostic_source".into(), Value::Text(self.diagnostic_source.clone())), - ("cached".into(), Value::Bool(false)), - ]) - } -} - -/// Arguments for `foreign.invoke`. Kept as a struct so dispatch stays readable. -#[derive(Default)] -pub struct InvokeArgs<'a> { - pub code: Option<&'a Value>, - pub lang: Option<&'a Value>, - pub source: Option<&'a Value>, - pub stdin: Option<&'a Value>, - pub input: Option<&'a Value>, - pub env: Option<&'a Value>, - pub cwd: Option<&'a Value>, - pub timeout: Option<&'a Value>, - pub args: Option<&'a Value>, - pub output: Option<&'a Value>, - pub max_output: Option<&'a Value>, - pub cmd: Option<&'a Value>, - pub keep: Option<&'a Value>, -} - -/// Register interpreter argv for `lang` (e.g. venv python). -pub fn set_cmd( - ctx: &mut HostContext, - lang: &Value, - cmd: &Value, - args: Option<&Value>, -) -> Result { - ensure_config(ctx); - let requested = as_text(lang, "lang")?.to_ascii_lowercase(); - let canon = registry::canonical(&requested); - let cmd = as_text(cmd, "cmd")?; - let mut argv = vec![cmd.to_string()]; - if let Some(a) = args { - match a { - Value::List(xs) => { - for x in xs { - argv.push(x.as_display()); - } - } - Value::Text(s) => argv.push(s.clone()), - Value::None => {} - _ => return Err("set_cmd args must be list or text".into()), - } - } - let spec = LangSpec { - lang: canon.clone(), - argv: argv.clone(), - template: None, - ext: None, - env: Vec::new(), - version_args: Vec::new(), - session: registry::session_supported(&canon), - base_dir: None, - }; - ctx.foreign_specs.insert(canon.clone(), spec); - ctx.foreign_cmds.insert(canon, argv); - Ok(Value::None) -} - -fn parse_template(v: Option<&Value>) -> Result>, String> { - match v { - None | Some(Value::None) => Ok(None), - Some(Value::List(xs)) => Ok(Some(xs.iter().map(|x| x.as_display()).collect())), - Some(Value::Text(s)) => Ok(Some(vec![s.clone()])), - Some(_) => Err("template must be a list of text".into()), - } -} - -fn parse_version_args(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(Vec::new()), - Some(Value::List(xs)) => Ok(xs.iter().map(|x| x.as_display()).collect()), - Some(Value::Text(s)) => Ok(vec![s.clone()]), - Some(_) => Err("version_args must be a list of text".into()), - } -} - -/// Register a language invocation (`register`). `cmd` and `template` are exclusive. -pub fn register( - ctx: &mut HostContext, - lang: &Value, - cmd: Option<&Value>, - args: Option<&Value>, - template: Option<&Value>, - ext: Option<&Value>, - env: Option<&Value>, - version_args: Option<&Value>, -) -> Result { - ensure_config(ctx); - let requested = as_text(lang, "lang")?.to_ascii_lowercase(); - let canon = registry::canonical(&requested); - let cmd = opt_text(cmd)?; - let template = parse_template(template)?; - if cmd.is_some() && template.is_some() { - return Err("register: cmd and template are mutually exclusive".into()); - } - if cmd.is_none() && template.is_none() { - return Err("register: provide cmd or template".into()); - } - let mut argv = match &cmd { - Some(c) => { - let mut v = vec![c.clone()]; - v.extend(parse_args(args)?); - v - } - None => vec![template - .as_ref() - .and_then(|t| t.first()) - .cloned() - .ok_or_else(|| "register: template must not be empty".to_string())?], - }; - if let Some(t) = &template { - if t.is_empty() { - return Err("register: template must not be empty".into()); - } - if t.iter().any(|x| x == "{file}") && t.iter().any(|x| x == "{inline}") { - return Err("register: {file} and {inline} cannot be used together".into()); - } - // A template without file/inline gets the script path appended. - if !t.iter().any(|x| x == "{file}" || x == "{inline}") { - // leave as-is; prepare adds the script path - } - } - if cmd.is_none() { - argv = vec![template.as_ref().unwrap()[0].clone()]; - } - let ext = match opt_text(ext)? { - Some(e) => { - let e = e.trim().trim_start_matches('.').to_string(); - if e.is_empty() - || e.len() > 16 - || !e.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-') - { - return Err("register: ext must be 1..16 ASCII alphanumerics".into()); - } - Some(e) - } - None => None, - }; - let env = parse_env(env)?; - let version_args = parse_version_args(version_args)?; - let spec = LangSpec { - lang: canon.clone(), - argv: argv.clone(), - template, - ext, - env, - version_args, - session: registry::session_supported(&canon), - base_dir: None, - }; - ctx.foreign_specs.insert(canon.clone(), spec); - if ctx.foreign_specs.get(&canon).map(|s| s.template.is_none()).unwrap_or(false) { - ctx.foreign_cmds.insert(canon, argv); - } - Ok(Value::None) -} - -/// Remove a process-local registration; presets/config/env still apply. -pub fn unset(ctx: &mut HostContext, lang: &Value) -> Result { - ensure_config(ctx); - let requested = as_text(lang, "lang")?.to_ascii_lowercase(); - let canon = registry::canonical(&requested); - let mut removed = ctx.foreign_specs.remove(&canon).is_some(); - removed |= ctx.foreign_specs.remove(&requested).is_some(); - removed |= ctx.foreign_cmds.remove(&canon).is_some(); - removed |= ctx.foreign_cmds.remove(&requested).is_some(); - Ok(Value::Bool(removed)) -} - -fn discover_config_path(ctx: &HostContext) -> Option { - if let Ok(v) = std::env::var("MARQDO_FOREIGN_CONFIG") { - let v = v.trim(); - if !v.is_empty() { - return Some(PathBuf::from(v)); - } - } - let mut candidates = vec![ctx.cwd.join(".marqdo").join("foreign.toml")]; - if let Some(entry) = &ctx.entry_path { - if let Some(dir) = entry.parent() { - candidates.push(dir.join(".marqdo").join("foreign.toml")); - } - } - if let Ok(home) = std::env::var("HOME") { - if !home.trim().is_empty() { - candidates.push( - PathBuf::from(home) - .join(".config") - .join("marqdo") - .join("foreign.toml"), - ); - } - } - candidates.into_iter().find(|p| p.is_file()) -} - -/// Load project config once; malformed auto-config warns but does not block presets. -pub fn ensure_config(ctx: &mut HostContext) { - if ctx.foreign_config_loaded { - return; - } - ctx.foreign_config_loaded = true; - if let Some(path) = discover_config_path(ctx) { - if let Err(e) = load_config_path(ctx, &path) { - eprintln!( - "marqdo: foreign config {} ignored: {e}", - path.display() - ); - } - } -} - -fn load_config_path(ctx: &mut HostContext, path: &Path) -> Result { - let source = std::fs::read_to_string(path) - .map_err(|e| format!("read {}: {e}", path.display()))?; - let parsed = crate::host::toml_ops::parse(&Value::Text(source)) - .map_err(|e| format!("parse {}: {e}", path.display()))?; - let map = match parsed { - Value::Map(m) => m, - _ => return Err("config must be a TOML table".into()), - }; - let base = path.parent().map(|p| p.to_path_buf()); - let mut count = 0usize; - for (lang, val) in map { - let spec = spec_from_config(&lang, &val, base.as_deref())?; - let canon = registry::canonical(&lang); - // Runtime registrations win; config fills the lower layer. - if !ctx.foreign_config_specs.contains_key(&canon) { - ctx.foreign_config_specs.insert(canon.clone(), spec.clone()); - } - if !ctx.foreign_specs.contains_key(&canon) && !ctx.foreign_cmds.contains_key(&canon) { - if let Some(t) = &spec.template { - if !t.iter().any(|x| x == "{inline}") { - ctx.foreign_cmds.insert(canon, spec.argv.clone()); - } - } else { - ctx.foreign_cmds.insert(canon, spec.argv.clone()); - } - } - count += 1; - } - Ok(count) -} - -fn spec_from_config(lang: &str, v: &Value, base: Option<&Path>) -> Result { - let entries = match v { - Value::Map(m) => m, - _ => return Err(format!("[{lang}] must be a table")), - }; - let mut cmd: Option = None; - let mut args: Vec = Vec::new(); - let mut template: Option> = None; - let mut ext: Option = None; - let mut env: Vec<(String, String)> = Vec::new(); - let mut version_args: Vec = Vec::new(); - let mut session = registry::session_supported(®istry::canonical(lang)); - for (k, val) in entries { - match k.as_str() { - "cmd" => cmd = Some(as_text(val, "cmd")?.to_string()), - "args" => args = parse_args(Some(val))?, - "template" => template = parse_template(Some(val))?, - "ext" => ext = opt_text(Some(val))?, - "env" => env = parse_env(Some(val))?, - "version_args" => version_args = parse_version_args(Some(val))?, - "session" => { - session = parse_bool(Some(val), "session", session)?; - } - _ => {} - } - } - if cmd.is_some() && template.is_some() { - return Err(format!("[{lang}]: cmd and template are mutually exclusive")); - } - if cmd.is_none() && template.is_none() { - return Err(format!("[{lang}]: provide cmd or template")); - } - let canon = registry::canonical(lang); - let mut argv = if let Some(c) = &cmd { - let mut v = vec![resolve_relative_cmd(c, base)]; - v.extend(args); - v - } else { - vec![template.as_ref().unwrap()[0].clone()] - }; - if let Some(t) = &template { - if t.is_empty() { - return Err(format!("[{lang}]: template must not be empty")); - } - argv = vec![t[0].clone()]; - } - Ok(LangSpec { - lang: canon, - argv, - template, - ext, - env, - version_args, - session, - base_dir: base.map(|p| p.to_path_buf()), - }) -} - -fn resolve_relative_cmd(cmd: &str, base: Option<&Path>) -> String { - let p = Path::new(cmd); - if p.is_absolute() || !cmd.contains('/') && !cmd.contains('\\') { - return cmd.to_string(); - } - let base = base.unwrap_or_else(|| Path::new(".")); - std::path::absolute(base.join(p)) - .map(|p| p.display().to_string()) - .unwrap_or_else(|_| cmd.to_string()) -} - -/// Explicit config load; returns the number of language tables read. -pub fn load_config(ctx: &mut HostContext, path: Option<&Value>) -> Result { - let explicit = opt_text(path)?; - if let Some(p) = explicit { - let p = PathBuf::from(p); - if !p.is_file() { - return Err(format!("foreign config not found: {}", p.display())); - } - let n = load_config_path(ctx, &p)?; - ctx.foreign_config_loaded = true; - return Ok(Value::Int(n as i64)); - } - ensure_config(ctx); - Ok(Value::Int(ctx.foreign_config_specs.len() as i64)) -} - -pub fn run( - ctx: &mut HostContext, - code: &Value, - stdin: Option<&Value>, -) -> Result { - run_with_options(ctx, code, stdin, &HashMap::new()) -} - -/// `run` with the F0 optional parameters (`stdin` is also accepted in `bound`). -pub fn run_with_options( - ctx: &mut HostContext, - code: &Value, - stdin: Option<&Value>, - bound: &HashMap, -) -> Result { - ensure_config(ctx); - let block = as_code(code)?; - let mut job = bound_job(ctx, &block.lang, &block.source, stdin, bound)?; - job.lang = block.lang.clone(); - let exec = execute_job(ctx, &job)?; - outcome_text(&exec) -} - -pub fn run_lang( - ctx: &mut HostContext, - lang: &Value, - source: &Value, - stdin: Option<&Value>, -) -> Result { - run_lang_with_options(ctx, lang, source, stdin, &HashMap::new()) -} - -pub fn run_lang_with_options( - ctx: &mut HostContext, - lang: &Value, - source: &Value, - stdin: Option<&Value>, - bound: &HashMap, -) -> Result { - ensure_config(ctx); - let lang = as_text(lang, "lang")?; - let source = as_text(source, "source")?; - let job = bound_job(ctx, lang, source, stdin, bound)?; - let exec = execute_job(ctx, &job)?; - outcome_text(&exec) -} - -fn bound_job( - ctx: &HostContext, - lang: &str, - source: &str, - stdin: Option<&Value>, - bound: &HashMap, -) -> Result { - let mut job = Job::simple(lang, source, None); - job.stdin = opt_text(stdin)?; - job.env = parse_env(bound.get("env"))?; - job.cwd = opt_text(bound.get("cwd"))?; - job.timeout = parse_timeout(bound.get("timeout"))?; - job.extra_args = parse_args(bound.get("args"))?; - job.max_output = parse_max_output(bound.get("max_output"))?; - let _ = ctx; - Ok(job) -} - -/// Structured one-shot execution. Never errors for process failures; only bad args/policy. -struct PreparedInvoke { - job: Job, - output: String, -} - -fn prepare_invoke(args: &InvokeArgs<'_>) -> Result { - let (lang, source) = resolve_invoke_source(args)?; - let stdin = opt_text(args.stdin)?; - let input_json = match args.input { - None | Some(Value::None) => None, - Some(v) => { - super::oracle::admit(v)?; - Some(serde_json::to_string(&value_to_json(v)?) - .map_err(|e| format!("input JSON encode: {e}"))?) - }, - }; - if stdin.is_some() && input_json.is_some() { - return Err("stdin and input are mutually exclusive".into()); - } - let output = match opt_text(args.output)? { - None => "auto".to_string(), - Some(s) => s.to_ascii_lowercase(), - }; - if !matches!(output.as_str(), "auto" | "text" | "json" | "lines") { - return Err(format!("unknown output mode `{output}` (auto|text|json|lines)")); - } - let mut job = Job::simple(&lang, &source, None); - job.stdin = stdin.or_else(|| input_json.clone()); - job.input_json = input_json; - job.env = parse_env(args.env)?; - job.cwd = opt_text(args.cwd)?; - job.timeout = parse_timeout(args.timeout)?; - job.extra_args = parse_args(args.args)?; - job.max_output = parse_max_output(args.max_output)?; - job.cmd_override = opt_text(args.cmd)?; - job.keep = parse_bool(args.keep, "keep", false)?; - Ok(PreparedInvoke { job, output }) -} - -pub fn invoke(ctx: &mut HostContext, args: InvokeArgs<'_>) -> Result { - ensure_config(ctx); - let prepared = prepare_invoke(&args)?; - let exec = execute_job(ctx, &prepared.job)?; - let (result, result_error) = parse_output(&exec.stdout, &prepared.output)?; - Ok(exec.record(result, result_error)) -} - -/// JSON-in / JSON-out convenience: raises on process failure or invalid JSON. -pub fn call(ctx: &mut HostContext, args: InvokeArgs<'_>) -> Result { - ensure_config(ctx); - let mut prepared = prepare_invoke(&args)?; - prepared.output = "json".into(); - let exec = execute_job(ctx, &prepared.job)?; - if !exec.ok { - return Err(format_failure(&exec)); - } - if exec.stdout.trim().is_empty() { - return Ok(Value::None); - } - super::json::decode_text(&exec.stdout).map_err(|e| match e { - super::json::DecodeError::Domain(e) => e, - super::json::DecodeError::Syntax(e) => format!("foreign call: stdout is not JSON: {e}; stdout: {}", tail(exec.stdout.trim(), 512)), - }) -} - -fn present(v: Option<&Value>) -> Option<&Value> { - match v { - None | Some(Value::None) => None, - Some(x) => Some(x), - } -} - -#[derive(Clone)] -struct ForeignEnv { - cwd: PathBuf, - fs_root: Option, - entry_path: Option, - caps: HostCaps, - foreign_cmds: HashMap>, - foreign_specs: HashMap, - foreign_config_specs: HashMap, - foreign_config_loaded: bool, - sandbox_session: Option, -} - -impl ForeignEnv { - fn from_ctx(ctx: &HostContext) -> Self { - Self { - cwd: ctx.cwd.clone(), - fs_root: ctx.fs_root.clone(), - entry_path: ctx.entry_path.clone(), - caps: ctx.caps.clone(), - foreign_cmds: ctx.foreign_cmds.clone(), - foreign_specs: ctx.foreign_specs.clone(), - foreign_config_specs: ctx.foreign_config_specs.clone(), - foreign_config_loaded: ctx.foreign_config_loaded, - sandbox_session: ctx.sandbox_session.clone(), - } - } - - fn to_ctx(&self) -> HostContext { - let mut c = HostContext::default(); - c.cwd = self.cwd.clone(); - c.fs_root = self.fs_root.clone(); - c.entry_path = self.entry_path.clone(); - c.caps = self.caps.clone(); - c.foreign_cmds = self.foreign_cmds.clone(); - c.foreign_specs = self.foreign_specs.clone(); - c.foreign_config_specs = self.foreign_config_specs.clone(); - c.foreign_config_loaded = self.foreign_config_loaded; - c.sandbox_session = self.sandbox_session.clone(); - c - } -} - -struct PreparedMany { - idx: usize, - job: Job, - output: String, -} - -fn parse_concurrency(v: Option<&Value>) -> Result { - let n = match v { - None | Some(Value::None) => 4, - Some(Value::Int(n)) if *n >= 0 => *n as usize, - Some(_) => return Err("concurrency must be a non-negative integer".into()), - }; - Ok(n.min(32)) -} - -fn map_get<'a>(m: &'a Value, key: &str) -> Option<&'a Value> { - match m { - Value::Map(entries) => entries - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v) - .filter(|v| !matches!(v, Value::None)), - _ => None, - } -} - -fn args_from_map<'a>(m: &'a Value) -> InvokeArgs<'a> { - InvokeArgs { - code: map_get(m, "code"), - lang: map_get(m, "lang"), - source: map_get(m, "source"), - stdin: map_get(m, "stdin"), - input: map_get(m, "input"), - env: map_get(m, "env"), - cwd: map_get(m, "cwd"), - timeout: map_get(m, "timeout"), - args: map_get(m, "args"), - output: map_get(m, "output"), - max_output: map_get(m, "max_output"), - cmd: map_get(m, "cmd"), - keep: map_get(m, "keep"), - } -} - -fn error_record(ctx: &HostContext, job: &Job, error: String) -> Value { - Execution { - ok: false, - code: -1, - stdout: String::new(), - stderr: String::new(), - ms: 0, - timed_out: false, - truncated: false, - error, - lang: job.lang.clone(), - cmd: display_for_job(ctx, job, None), - script: String::new(), - diagnostic_source: String::new(), - } - .record(Value::None, String::new()) -} - -fn run_prepared(env: &ForeignEnv, items: Vec, concurrency: usize) -> Result, String> { - if items.is_empty() { - return Ok(Vec::new()); - } - let workers = concurrency.max(1).min(items.len()); - let queue = Arc::new(Mutex::new(VecDeque::from(items))); - let results: Arc)>>> = Arc::new(Mutex::new(Vec::new())); - thread::scope(|scope| { - for _ in 0..workers { - let queue = Arc::clone(&queue); - let results = Arc::clone(&results); - let env = env.clone(); - scope.spawn(move || loop { - let item = { - let mut q = match queue.lock() { - Ok(q) => q, - Err(_) => break, - }; - q.pop_front() - }; - let Some(item) = item else { break }; - let ctx = env.to_ctx(); - let value = match catch_unwind(AssertUnwindSafe(|| { - execute_job(&ctx, &item.job) - })) { - Ok(Ok(exec)) => { - parse_output(&exec.stdout, &item.output).map(|(result, error)| exec.record(result, error)) - } - Ok(Err(e)) => Ok(error_record(&ctx, &item.job, e)), - Err(_) => Ok(error_record(&ctx, &item.job, "foreign worker panicked".into())), - }; - if let Ok(mut out) = results.lock() { - out.push((item.idx, value)); - } - }); - } - }); - let mut out = match Arc::try_unwrap(results) { - Ok(m) => m.into_inner().unwrap_or_default(), - Err(shared) => shared.lock().map(|m| m.clone()).unwrap_or_default(), - }; - out.sort_by_key(|(i, _)| *i); - out.into_iter().map(|(i, result)| result.map(|value| (i, value)).map_err(|e| format!("foreign[{i}]: {e}"))).collect() -} - -/// Build a prepared job for one `runs` item (code value or option map). -fn prepare_many_item(ctx: &HostContext, idx: usize, item: &Value) -> Result { - match item { - Value::Code(c) => Ok(PreparedMany { - idx, - job: Job::simple(&c.lang, &c.source, None), - output: "auto".into(), - }), - Value::Map(_) => { - let args = args_from_map(item); - let prepared = prepare_invoke(&args)?; - let _ = ctx; - Ok(PreparedMany { - idx, - job: prepared.job, - output: prepared.output, - }) - } - _ => Err(format!( - "runs[{idx}] must be a code value or a map of invoke options" - )), - } -} - -pub fn run_many( - ctx: &mut HostContext, - runs: &Value, - concurrency: Option<&Value>, -) -> Result { - ensure_config(ctx); - if !ctx.allow_exec() { - return Err("foreign run_many denied by host policy".into()); - } - let list = match runs { - Value::List(xs) => xs, - _ => return Err("run_many runs must be a list".into()), - }; - let mut prepared = Vec::with_capacity(list.len()); - for (idx, item) in list.iter().enumerate() { - prepared.push(prepare_many_item(ctx, idx, item)?); - } - let n = prepared.len(); - let requested = parse_concurrency(concurrency)?; - let concurrency = if requested == 0 { - n.min(8) - } else { - requested - }; - let env = ForeignEnv::from_ctx(ctx); - let results = run_prepared(&env, prepared, concurrency)?; - Ok(Value::List(results.into_iter().map(|(_, v)| v).collect())) -} - -pub fn call_many( - ctx: &mut HostContext, - args: InvokeArgs<'_>, - inputs: &Value, - concurrency: Option<&Value>, -) -> Result { - ensure_config(ctx); - if !ctx.allow_exec() { - return Err("foreign call_many denied by host policy".into()); - } - let list = match inputs { - Value::List(xs) => xs, - _ => return Err("call_many inputs must be a list".into()), - }; - let base = prepare_invoke(&args)?; - let n = list.len(); - let requested = parse_concurrency(concurrency)?; - let concurrency = if requested == 0 { - n.min(8) - } else { - requested - }; - let mut prepared = Vec::with_capacity(n); - for (idx, input) in list.iter().enumerate() { - super::oracle::admit(input)?; - let json = serde_json::to_string(&value_to_json(input)?) - .map_err(|e| format!("call_many input JSON encode: {e}"))?; - let mut job = base.job.clone(); - job.stdin = Some(json.clone()); - job.input_json = Some(json); - prepared.push(PreparedMany { - idx, - job, - output: "json".into(), - }); - } - let env = ForeignEnv::from_ctx(ctx); - let records = run_prepared(&env, prepared, concurrency)?; - let mut results = Vec::with_capacity(records.len()); - let mut errors = Vec::new(); - for (idx, record) in records { - let ok = matches!(map_get(&record, "ok"), Some(Value::Bool(true))); - let result_error = map_get(&record, "result_error") - .and_then(|v| v.reveal_text()) - .unwrap_or(""); - if !ok { - let err = map_get(&record, "error") - .and_then(|v| v.reveal_text()) - .or_else(|| map_get(&record, "stderr").and_then(|v| v.reveal_text())) - .unwrap_or("foreign call failed"); - errors.push(format!("call_many[{idx}]: {err}")); - continue; - } - if !result_error.is_empty() { - errors.push(format!("call_many[{idx}]: {result_error}")); - continue; - } - results.push(map_get(&record, "result").cloned().unwrap_or(Value::None)); - } - if !errors.is_empty() { - return Err(errors.join("; ")); - } - Ok(Value::List(results)) -} - -fn resolve_invoke_source(args: &InvokeArgs<'_>) -> Result<(String, String), String> { - if let Some(code) = present(args.code) { - if present(args.lang).is_some() || present(args.source).is_some() { - return Err("invoke: pass either code or lang+source, not both".into()); - } - let block = as_code(code)?; - return Ok((block.lang.clone(), block.source.clone())); - } - let lang = present(args.lang).ok_or_else(|| "invoke needs code or lang+source".to_string())?; - let source = - present(args.source).ok_or_else(|| "invoke needs source when lang is given".to_string())?; - Ok(( - as_text(lang, "lang")?.to_string(), - as_text(source, "source")?.to_string(), - )) -} - -fn parse_output(stdout: &str, mode: &str) -> Result<(Value, String), String> { - if mode == "text" { return Ok((Value::None, String::new())); } - if mode == "lines" { return Ok((Value::List(stdout.lines().map(|s| Value::Text(s.into())).collect()), String::new())); } - if stdout.trim().is_empty() { return Ok((Value::None, String::new())); } - match super::json::decode_text(stdout) { - Ok(v) => Ok((v, String::new())), - Err(super::json::DecodeError::Domain(e)) => Err(e), - Err(super::json::DecodeError::Syntax(e)) if mode == "json" => Ok((Value::None, format!("stdout is not JSON: {e}"))), - Err(super::json::DecodeError::Syntax(_)) => Ok((Value::None, String::new())), - } -} - -fn outcome_text(exec: &Execution) -> Result { - if !exec.ok { - return Err(format_failure(exec)); - } - let mut out = exec.stdout.clone(); - if out.ends_with('\n') { - out.pop(); - if out.ends_with('\r') { - out.pop(); - } - } - Ok(Value::Text(out)) -} - -fn format_failure(exec: &Execution) -> String { - let mut msg = format!( - "foreign run failed (lang={}, cmd={}, exit={})", - exec.lang, exec.cmd, exec.code - ); - if exec.timed_out { - msg.push_str(": timed out"); - } - if !exec.error.is_empty() { - msg.push_str(": "); - msg.push_str(&exec.error); - } - let err = exec.stderr.trim(); - if !err.is_empty() { - msg.push_str(": "); - msg.push_str(&tail(err, FAILURE_TAIL)); - } else { - let out = exec.stdout.trim(); - if !out.is_empty() { - msg.push_str(": stdout: "); - msg.push_str(&tail(out, FAILURE_TAIL)); - } - } - msg -} - -fn tail(s: &str, n: usize) -> String { - if s.len() <= n { - return s.to_string(); - } - let mut start = s.len() - n; - while start < s.len() && !s.is_char_boundary(start) { - start += 1; - } - format!("…{}", &s[start..]) -} - -fn known_langs(ctx: &HostContext) -> Vec { - let mut names: Vec = registry::preset_ids(); - names.extend(ctx.foreign_specs.keys().cloned()); - names.extend(ctx.foreign_config_specs.keys().cloned()); - names.extend(ctx.foreign_cmds.keys().map(|k| registry::canonical(k))); - names.sort(); - names.dedup(); - names -} - -pub fn langs(ctx: &mut HostContext) -> Result { - ensure_config(ctx); - Ok(Value::List( - known_langs(ctx).into_iter().map(Value::Text).collect(), - )) -} - -/// Probe one language: path, version, availability. Never panics on missing tools. -pub fn probe(ctx: &mut HostContext, lang: Option<&Value>) -> Result { - ensure_config(ctx); - if !ctx.allow_exec() { - return Err("foreign probe denied by host policy".into()); - } - match opt_text(lang)? { - Some(l) => Ok(probe_one(ctx, &l)), - None => { - let ids = known_langs(ctx); - Ok(Value::List( - ids.iter().map(|l| probe_one(ctx, l)).collect(), - )) - } - } -} - -fn probe_one(ctx: &HostContext, lang: &str) -> Value { - let spec = match resolve_spec(ctx, lang) { - Ok(s) => s, - Err(e) => { - return Value::Map(vec![ - ("lang".into(), Value::Text(lang.to_string())), - ("cmd".into(), Value::Text(String::new())), - ("path".into(), Value::Text(String::new())), - ("ok".into(), Value::Bool(false)), - ("version".into(), Value::Text(String::new())), - ("error".into(), Value::Text(e)), - ]) - } - }; - let exe = spec - .argv - .first() - .cloned() - .or_else(|| spec.template.as_ref().and_then(|t| t.first()).cloned()) - .unwrap_or_default(); - let path = resolve_executable(&spec, &exe, &ctx.cwd); - let path_text = path - .as_ref() - .map(|p| p.display().to_string()) - .unwrap_or_default(); - let version_args = if spec.version_args.is_empty() { - vec!["--version".to_string()] - } else { - spec.version_args.clone() - }; - let mut display = vec![exe.clone()]; - display.extend(version_args.iter().cloned()); - let cmd_text = display.join(" "); - let Some(exe_path) = path else { - return Value::Map(vec![ - ("lang".into(), Value::Text(lang.to_string())), - ("cmd".into(), Value::Text(cmd_text)), - ("path".into(), Value::Text(String::new())), - ("ok".into(), Value::Bool(false)), - ("version".into(), Value::Text(String::new())), - ("error".into(), Value::Text(format!( - "interpreter `{exe}` not found on PATH — register / set_cmd / MARQDO_FOREIGN_*" - ))), - ]); - }; - let mut command = Command::new(&exe_path); - command.args(&version_args); - command.stdin(Stdio::null()); - command.stdout(Stdio::piped()); - command.stderr(Stdio::piped()); - command.env("MARQDO_FOREIGN_LANG", &spec.lang); - for (k, v) in &spec.env { - command.env(k, v); - } - let mut child = match command.spawn() { - Ok(c) => c, - Err(e) => { - return Value::Map(vec![ - ("lang".into(), Value::Text(lang.to_string())), - ("cmd".into(), Value::Text(cmd_text)), - ("path".into(), Value::Text(path_text)), - ("ok".into(), Value::Bool(false)), - ("version".into(), Value::Text(String::new())), - ("error".into(), Value::Text(format!("spawn {exe}: {e}"))), - ]) - } - }; - let out = child.stdout.take(); - let err = child.stderr.take(); - let out_h = thread::spawn(move || read_capped(out, 64 * 1024)); - let err_h = thread::spawn(move || read_capped(err, 64 * 1024)); - let start = Instant::now(); - let mut ok = false; - let mut error = String::new(); - loop { - match child.try_wait() { - Ok(Some(st)) => { - ok = st.success(); - break; - } - Ok(None) if start.elapsed() > Duration::from_secs(3) => { - let _ = child.kill(); - let _ = child.wait(); - error = "version probe timed out after 3s".into(); - break; - } - Ok(None) => thread::sleep(Duration::from_millis(15)), - Err(e) => { - let _ = child.kill(); - error = format!("version probe failed: {e}"); - break; - } - } - } - let (stdout, _) = out_h.join().unwrap_or_default(); - let (stderr, _) = err_h.join().unwrap_or_default(); - let version = stdout - .lines() - .chain(stderr.lines()) - .map(str::trim) - .find(|l| !l.is_empty()) - .unwrap_or("") - .to_string(); - Value::Map(vec![ - ("lang".into(), Value::Text(lang.to_string())), - ("cmd".into(), Value::Text(cmd_text)), - ("path".into(), Value::Text(path_text)), - ("ok".into(), Value::Bool(ok && error.is_empty())), - ("version".into(), Value::Text(version)), - ("error".into(), Value::Text(error)), - ]) -} - -fn resolve_executable(spec: &LangSpec, exe: &str, cwd: &Path) -> Option { - if exe.is_empty() { - return None; - } - let looks_path = exe.contains('/') || exe.contains('\\'); - if looks_path { - let base = spec.base_dir.as_deref().unwrap_or(cwd); - let p = if Path::new(exe).is_absolute() { - PathBuf::from(exe) - } else { - base.join(exe) - }; - return std::path::absolute(&p).ok().filter(|p| p.is_file()); - } - let path_var = std::env::var_os("PATH")?; - for dir in std::env::split_paths(&path_var) { - let p = dir.join(exe); - if p.is_file() { - return std::path::absolute(&p).ok().or(Some(p)); - } - #[cfg(windows)] - { - for ext in ["exe", "cmd", "bat", "com"] { - let with = dir.join(format!("{exe}.{ext}")); - if with.is_file() { - return Some(with); - } - } - } - } - None -} - -/// Shared entry for CLI host and live view `/api/foreign-run`. -pub fn run_source( - ctx: &HostContext, - lang: &str, - source: &str, - stdin: Option<&str>, -) -> Result { - let job = Job::simple(lang, source, stdin); - let exec = execute_job(ctx, &job)?; - outcome_text(&exec) -} - -/// Resolve argv with optional one-shot cmd override (view command box). -pub fn resolve_argv_with_override( - ctx: &HostContext, - lang: &str, - cmd_override: Option<&str>, -) -> Result, String> { - if let Some(cmd) = cmd_override.map(str::trim).filter(|s| !s.is_empty()) { - let argv = split_cmd_line(cmd); - if argv.is_empty() { - return Err("cmd override is empty".into()); - } - return Ok(argv); - } - Ok(resolve_spec(ctx, lang)?.argv) -} - -fn env_argv_for(lang: &str, canon: &str) -> Result>, String> { - let mut keys = vec![format!("MARQDO_FOREIGN_{}", lang.to_ascii_uppercase())]; - if canon != lang { - keys.push(format!("MARQDO_FOREIGN_{}", canon.to_ascii_uppercase())); - } - if canon == "python" { - keys.push("MARQDO_FOREIGN_PYTHON".to_string()); - } - for key in keys { - if let Ok(v) = std::env::var(&key) { - let v = v.trim(); - if !v.is_empty() { - let argv = parse_env_argv(v)?; - if !argv.is_empty() { - return Ok(Some(argv)); - } - } - } - } - Ok(None) -} - -/// Resolve the effective language spec: register > env > config > preset. -fn resolve_spec(ctx: &HostContext, lang: &str) -> Result { - let requested = lang.to_ascii_lowercase(); - let canon = registry::canonical(&requested); - if let Some(s) = ctx - .foreign_specs - .get(&requested) - .or_else(|| ctx.foreign_specs.get(&canon)) - { - return Ok(s.clone()); - } - if let Some(argv) = env_argv_for(&requested, &canon)? { - let mut spec = registry::preset_spec(&canon).unwrap_or_else(|| LangSpec { - lang: canon.clone(), - ..Default::default() - }); - spec.argv = argv; - spec.template = None; - spec.lang = canon.clone(); - return Ok(spec); - } - if let Some(s) = ctx - .foreign_config_specs - .get(&requested) - .or_else(|| ctx.foreign_config_specs.get(&canon)) - { - return Ok(s.clone()); - } - if let Some(s) = registry::preset_spec(&canon) { - return Ok(s); - } - Err(format!( - "no interpreter configured for lang=`{lang}` — register lang={lang} cmd=… \ - or env MARQDO_FOREIGN_{} (check your environment)", - lang.to_ascii_uppercase() - )) -} - -pub(crate) fn resolve_session_spec( - ctx: &HostContext, - lang: &str, -) -> Result { - resolve_spec(ctx, lang) -} - -struct Invocation { - argv: Vec, - template: Option>, - ext: String, - env: Vec<(String, String)>, - inline: bool, - #[allow(dead_code)] - session: bool, -} - -fn default_ext(lang: &str) -> String { - if let Some(s) = registry::preset_spec(lang) { - if let Some(e) = s.ext { - return e; - } - } - let l = lang.to_ascii_lowercase(); - if l.len() <= 8 && l.chars().all(|c| c.is_ascii_alphanumeric()) { - l - } else { - "txt".to_string() - } -} - -fn resolve_invocation(ctx: &HostContext, job: &Job) -> Result { - if let Some(cmd) = job.cmd_override.as_deref().map(str::trim).filter(|s| !s.is_empty()) { - let argv = split_cmd_line(cmd); - if argv.is_empty() { - return Err("cmd override is empty".into()); - } - return Ok(Invocation { - argv, - template: None, - ext: default_ext(&job.lang), - env: Vec::new(), - inline: false, - session: registry::session_supported(&job.lang), - }); - } - let spec = resolve_spec(ctx, &job.lang)?; - let mut template = spec.template.clone(); - if let Some(t) = &mut template { - if t.is_empty() { - return Err(format!("language `{}` has an empty template", spec.lang)); - } - let has_file = t.iter().any(|x| x == "{file}"); - let has_inline = t.iter().any(|x| x == "{inline}"); - if has_file && has_inline { - return Err(format!( - "language `{}` template uses both {{file}} and {{inline}}", - spec.lang - )); - } - if !has_file && !has_inline { - t.push("{file}".into()); - } - } - let inline = template - .as_ref() - .map(|t| t.iter().any(|x| x == "{inline}")) - .unwrap_or(false); - Ok(Invocation { - argv: spec.argv, - template, - ext: spec.ext.unwrap_or_else(|| default_ext(&job.lang)), - env: spec.env, - inline, - session: spec.session, - }) -} - - -/// `MARQDO_FOREIGN_` accepts a shell-like line or a JSON array of strings. -fn parse_env_argv(v: &str) -> Result, String> { - if v.starts_with('[') { - let parsed: serde_json::Value = - serde_json::from_str(v).map_err(|e| format!("invalid JSON argv: {e}"))?; - let arr = parsed - .as_array() - .ok_or_else(|| "argv JSON must be an array".to_string())?; - let mut out = Vec::new(); - for x in arr { - let s = x - .as_str() - .ok_or_else(|| "argv JSON entries must be strings".to_string())?; - out.push(s.to_string()); - } - return Ok(out); - } - Ok(split_cmd_line(v)) -} - -/// Shell-like split: whitespace, single/double quotes, backslash escapes. - -fn is_python(lang: &str) -> bool { - matches!(lang, "python" | "python3" | "py") -} - -fn write_temp_script( - ctx: &HostContext, - lang: &str, - source: &str, - ext: &str, -) -> Result { - let body = if is_python(lang) { - format!("# -*- coding: utf-8 -*-\n{source}") - } else { - source.to_string() - }; - let base = { - let preferred = temp_base(ctx); - match std::fs::create_dir_all(&preferred) { - Ok(()) => preferred, - Err(_) => { - let fallback = std::env::temp_dir(); - std::fs::create_dir_all(&fallback).map_err(|e| { - format!( - "failed to create foreign temp dir {} or fallback {}: {e}", - preferred.display(), - fallback.display() - ) - })?; - fallback - } - } - }; - let name = format!( - "marqdo-foreign-{}-{}.{}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0), - ext - ); - let path = base.join(name); - std::fs::write(&path, body.as_bytes()) - .map_err(|e| format!("failed to write temp foreign script: {e}"))?; - Ok(path) -} - -fn temp_base(ctx: &HostContext) -> PathBuf { - let p = if let Ok(v) = std::env::var("MARQDO_FOREIGN_TMPDIR") { - let v = v.trim(); - if !v.is_empty() { - PathBuf::from(v) - } else { - ctx.cwd.join(".marqdo").join("tmp") - } - } else { - ctx.cwd.join(".marqdo").join("tmp") - }; - std::path::absolute(&p).unwrap_or(p) -} - -/// Background foreign subprocess (for `lib/subtask`); caller removes `script_path` after join. -pub struct SpawnedForeign { - pub child: Child, - pub script_path: PathBuf, - pub stdout: thread::JoinHandle<(String, bool)>, - pub stderr: thread::JoinHandle<(String, bool)>, -} - -pub fn spawn_source( - ctx: &mut HostContext, - lang: &str, - source: &str, - stdin: Option<&str>, -) -> Result { - ensure_config(ctx); - let job = Job::simple(lang, source, stdin); - let (child, script_path, stdout, stderr) = spawn_job(ctx, &job)?; - Ok(SpawnedForeign { - child, - script_path, - stdout, - stderr, - }) -} - -fn job_cwd(ctx: &HostContext, job: &Job) -> Result { - let cwd = match &job.cwd { - Some(c) => ctx.resolve_path(c)?, - None => ctx.cwd.clone(), - }; - if !cwd.is_dir() { - return Err(format!("foreign cwd is not a directory: {}", cwd.display())); - } - Ok(cwd) -} - -fn expand_template( - ctx: &HostContext, - job: &Job, - template: &[String], - script: Option<&Path>, - cwd: &Path, -) -> Vec { - let dir = script - .and_then(|p| p.parent()) - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| temp_base(ctx)); - let file = script - .map(|p| p.display().to_string()) - .unwrap_or_default(); - let base = script - .and_then(|p| p.file_name()) - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - let mut out = Vec::with_capacity(template.len()); - for item in template { - let mut s = item.clone(); - s = s.replace("{file}", &file); - s = s.replace("{dir}", &dir.display().to_string()); - s = s.replace("{base}", &base); - s = s.replace("{inline}", &job.source); - s = s.replace("{lang}", &job.lang); - s = s.replace("{cwd}", &cwd.display().to_string()); - out.push(s); - } - out -} - -fn build_command( - ctx: &HostContext, - job: &Job, - inv: &Invocation, - script: Option<&Path>, -) -> Result<(Command, String), String> { - let cwd = job_cwd(ctx, job)?; - let argv = if let Some(template) = &inv.template { - let mut v = expand_template(ctx, job, template, script, &cwd); - v.extend(job.extra_args.iter().cloned()); - v - } else { - let mut v = inv.argv.clone(); - v.extend(job.extra_args.iter().cloned()); - if let Some(script) = script { - v.push(script.display().to_string()); - } - v - }; - if argv.is_empty() { - return Err("foreign cmd argv is empty — check register / env".into()); - } - let mut command = Command::new(&argv[0]); - for a in &argv[1..] { - command.arg(a); - } - command.current_dir(&cwd); - command.stdin(Stdio::piped()); - command.stdout(Stdio::piped()); - command.stderr(Stdio::piped()); - - command.env("MARQDO_FOREIGN", "1"); - command.env("MARQDO_FOREIGN_LANG", &job.lang); - if let Some(script) = script { - command.env("MARQDO_FOREIGN_SCRIPT", script); - } - command.env( - "MARQDO_FOREIGN_DIR", - script - .and_then(|p| p.parent()) - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| temp_base(ctx)), - ); - command.env("MARQDO_FOREIGN_CWD", &cwd); - if let Some(path) = &ctx.entry_path { - command.env("MARQDO_ENTRY", path); - if let Some(dir) = path.parent() { - command.env("MARQDO_ENTRY_DIR", dir); - } - } - if let Some(input) = &job.input_json { - if input.len() <= INPUT_ENV_CAP { - command.env("MARQDO_INPUT", input); - } - } - for (k, v) in &inv.env { - command.env(k, v); - } - for (k, v) in &job.env { - command.env(k, v); - } - if is_python(&job.lang) { - command.env("PYTHONUNBUFFERED", "1"); - command.env("PYTHONIOENCODING", "utf-8"); - command.env("PYTHONUTF8", "1"); - let sep = if cfg!(windows) { ";" } else { ":" }; - let mut paths = vec![cwd.to_string_lossy().into_owned()]; - if let Ok(existing) = std::env::var("PYTHONPATH") { - if !existing.is_empty() { - paths.push(existing); - } - } - command.env("PYTHONPATH", paths.join(sep)); - } - - #[cfg(unix)] - { - use std::os::unix::process::CommandExt; - command.process_group(0); - } - - Ok((command, argv.join(" "))) -} - -fn spawn_job( - ctx: &HostContext, - job: &Job, -) -> Result< - ( - Child, - PathBuf, - thread::JoinHandle<(String, bool)>, - thread::JoinHandle<(String, bool)>, - ), - String, -> { - let inv = resolve_invocation(ctx, job)?; - let script = if inv.inline { - None - } else { - Some(write_temp_script(ctx, &job.lang, &job.source, &inv.ext)?) - }; - let (mut command, display) = match build_command(ctx, job, &inv, script.as_deref()) { - Ok(v) => v, - Err(e) => { - if let Some(p) = &script { - let _ = std::fs::remove_file(p); - } - return Err(e); - } - }; - let mut child = match command.spawn() { - Ok(c) => c, - Err(e) => { - if let Some(p) = &script { - let _ = std::fs::remove_file(p); - } - return Err(format!( - "foreign spawn failed (lang={}, cmd={}): {e} — check your interpreter / \ - MARQDO_FOREIGN_* / register", - job.lang, display - )); - } - }; - - let mut stdin_pipe = child.stdin.take(); - let stdin_data = job.stdin.clone(); - if let Some(data) = stdin_data { - thread::spawn(move || { - if let Some(mut pipe) = stdin_pipe.take() { - let _ = pipe.write_all(data.as_bytes()); - } - }); - } else { - drop(stdin_pipe.take()); - } - - let stdout = child.stdout.take(); - let stderr = child.stderr.take(); - let max = job.max_output; - let out_h = thread::spawn(move || read_capped(stdout, max)); - let err_h = thread::spawn(move || read_capped(stderr, max)); - Ok((child, script.unwrap_or_default(), out_h, err_h)) -} - -fn display_for_job(ctx: &HostContext, job: &Job, script: Option<&Path>) -> String { - match resolve_invocation(ctx, job) { - Ok(inv) => match build_command(ctx, job, &inv, script) { - Ok((_, d)) => d, - Err(_) => inv.argv.join(" "), - }, - Err(_) => job.lang.clone(), - } -} - -fn read_capped(reader: Option, max: usize) -> (String, bool) { - let mut kept: Vec = Vec::new(); - let mut truncated = false; - if let Some(mut r) = reader { - let mut buf = [0u8; 8192]; - loop { - match r.read(&mut buf) { - Ok(0) => break, - Ok(n) => { - if kept.len() < max { - let take = (max - kept.len()).min(n); - kept.extend_from_slice(&buf[..take]); - if take < n { - truncated = true; - } - } else { - truncated = true; - } - } - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, - Err(_) => break, - } - } - } - (String::from_utf8_lossy(&kept).into_owned(), truncated) -} - -fn kill_tree(child: &mut Child) { - #[cfg(unix)] - unsafe { - libc::kill(-(child.id() as i32), libc::SIGKILL); - } - #[cfg(windows)] - { - let _ = Command::new("taskkill") - .args(["/PID", &child.id().to_string(), "/T", "/F"]) - .output(); - } - let _ = child.kill(); -} - -fn execute_job(ctx: &HostContext, job: &Job) -> Result { - if !ctx.allow_exec() { - if ctx.sandbox_session.is_some() { - return Err("foreign unavailable in sandbox".into()); - } - return Err("foreign denied by host policy".into()); - } - let (mut child, script_path, out_h, err_h) = match spawn_job(ctx, job) { - Ok(v) => v, - Err(error) => { - return Ok(Execution { - ok: false, - code: -1, - stdout: String::new(), - stderr: String::new(), - ms: 0, - timed_out: false, - truncated: false, - error, - lang: job.lang.clone(), - cmd: display_for_job(ctx, job, None), - script: String::new(), - diagnostic_source: String::new(), - }); - } - }; - let start = Instant::now(); - let mut timed_out = false; - let mut wait_error: Option = None; - let status = loop { - match child.try_wait() { - Ok(Some(st)) => break Some(st), - Ok(None) => { - if start.elapsed() >= job.timeout { - timed_out = true; - kill_tree(&mut child); - let _ = child.wait(); - break None; - } - thread::sleep(Duration::from_millis(10)); - } - Err(e) => { - wait_error = Some(format!("foreign wait failed: {e}")); - kill_tree(&mut child); - let _ = child.wait(); - break None; - } - } - }; - let (stdout, out_trunc) = out_h.join().unwrap_or_default(); - let (stderr, err_trunc) = err_h.join().unwrap_or_default(); - let ms = start.elapsed().as_millis() as u64; - - let script_is_empty = script_path.as_os_str().is_empty(); - let script_keep = if job.keep && !script_is_empty { - script_path.display().to_string() - } else { - if !script_is_empty { - let _ = std::fs::remove_file(&script_path); - } - String::new() - }; - let code = status.and_then(|s| s.code()).unwrap_or(-1); - let ok = status.map(|s| s.success()).unwrap_or(false) && !timed_out && wait_error.is_none(); - let error = if let Some(e) = wait_error { - e - } else if timed_out { - format!("timed out after {:.3}s", job.timeout.as_secs_f64()) - } else { - String::new() - }; - let cmd = display_for_job( - ctx, - job, - if script_is_empty { - None - } else { - Some(script_path.as_path()) - }, - ); - Ok(Execution { - ok, - code, - stdout, - stderr, - ms, - timed_out, - truncated: out_trunc || err_trunc, - error, - lang: job.lang.clone(), - cmd, - script: script_keep, - diagnostic_source: script_path.display().to_string(), - }) -} - -/// View helper: execute one fence with the command-box override + full record. -pub fn invoke_for_view( - root: &Path, - lang: &str, - source: &str, - cmd_override: Option<&str>, - stdin: Option<&str>, - timeout_secs: Option, -) -> Result { - let mut ctx = HostContext::default(); - ctx.cwd = root.to_path_buf(); - ctx.fs_root = Some(root.to_path_buf()); - ensure_config(&mut ctx); - let timeout = match timeout_secs { - Some(t) if t > 0.0 => Duration::from_secs_f64(t.min(MAX_TIMEOUT_SECS)), - _ => Duration::from_secs_f64(DEFAULT_TIMEOUT_SECS), - }; - let job = Job { - lang: lang.to_string(), - source: source.to_string(), - stdin: stdin.map(str::to_string), - input_json: None, - env: Vec::new(), - cwd: None, - timeout, - extra_args: Vec::new(), - max_output: MAX_OUTPUT, - keep: false, - cmd_override: cmd_override.map(str::to_string), - }; - let exec = execute_job(&ctx, &job)?; - let (result, result_error) = parse_output(&exec.stdout, "auto")?; - Ok(exec.record(result, result_error)) -} - -#[cfg(test)] -mod tests { - use crate::foreign; - use super::*; - - #[test] - fn fence_lang_python() { - assert_eq!(foreign::fence_lang("```python").as_deref(), Some("python")); - assert_eq!( - foreign::fence_lang("```python name=x").as_deref(), - Some("python") - ); - assert!(foreign::fence_lang("```").is_none()); - } - - #[test] - fn split_quotes() { - assert_eq!( - split_cmd_line("python3 -u -c 'a b'"), - vec!["python3", "-u", "-c", "a b"] - ); - assert_eq!( - split_cmd_line(r#"node -e "console.log(\"x\")""#), - vec!["node", "-e", "console.log(\"x\")"] - ); - assert_eq!( - split_cmd_line(r#"/opt/my python/bin/python -u"#), - vec!["/opt/my", "python/bin/python", "-u"] - ); - assert_eq!( - split_cmd_line(r#""/opt/my python/bin/python" -u"#), - vec!["/opt/my python/bin/python", "-u"] - ); - } - - #[test] - fn env_argv_json() { - assert_eq!( - parse_env_argv(r#"["python3","-u"]"#).unwrap(), - vec!["python3", "-u"] - ); - } - - #[test] - fn output_modes() { - let (v, e) = parse_output("42", "auto").unwrap(); - assert!(e.is_empty()); - assert_eq!(v, Value::Int(42)); - let (v, e) = parse_output("a\nb\n", "lines").unwrap(); - assert!(e.is_empty()); - assert_eq!(v, Value::List(vec![Value::Text("a".into()), Value::Text("b".into())])); - let (v, e) = parse_output("not json", "json").unwrap(); - assert!(v == Value::None); - assert!(!e.is_empty()); - } - - #[test] - fn exec_cap_denies() { - let mut ctx = HostContext::default(); - ctx.caps.exec = false; - let job = Job::simple("node", "console.log(1)", None); - let err = execute_job(&ctx, &job).unwrap_err(); - assert!(err.contains("denied"), "{err}"); - } - - #[test] - fn missing_interpreter_is_record() { - let mut ctx = HostContext::default(); - ctx.foreign_cmds.insert( - "nope".into(), - vec!["/definitely/not/a/real/interpreter".into()], - ); - let job = Job::simple("nope", "x", None); - let exec = execute_job(&ctx, &job).unwrap(); - assert!(!exec.ok); - assert_eq!(exec.code, -1); - assert!(!exec.error.is_empty(), "spawn failure should be recorded"); - } - - #[test] - fn read_cap_marks_truncated() { - let data = b"0123456789".to_vec(); - let (text, truncated) = read_capped(Some(std::io::Cursor::new(data)), 4); - assert_eq!(text, "0123"); - assert!(truncated); - } - - fn node_available() -> bool { - Command::new("node") - .args(["-e", "process.exit(0)"]) - .output() - .map(|o| o.status.success()) - .unwrap_or(false) - } - - #[test] - fn run_many_keeps_order_and_isolates_failures() { - if !node_available() { - return; - } - let mut ctx = HostContext::default(); - let runs = Value::List(vec![ - Value::Code(CodeBlock { - lang: "node".into(), - source: "console.log('a')".into(), - }), - Value::Code(CodeBlock { - lang: "node".into(), - source: "process.exit(2)".into(), - }), - Value::Code(CodeBlock { - lang: "node".into(), - source: "console.log('c')".into(), - }), - ]); - let out = run_many(&mut ctx, &runs, Some(&Value::Int(2))).unwrap(); - let Value::List(records) = out else { - panic!("expected list"); - }; - assert_eq!(records.len(), 3); - assert_eq!(map_get(&records[0], "stdout").and_then(|v| v.reveal_text()), Some("a\n")); - assert_eq!(map_get(&records[1], "ok"), Some(&Value::Bool(false))); - assert_eq!(map_get(&records[2], "stdout").and_then(|v| v.reveal_text()), Some("c\n")); - } - #[test] - fn structured_output_domain_errors_are_not_none_or_success_records() { - for mode in ["auto", "json"] { - for bad in ["9007199254740992", "9.007199254740992e15", "1e9999", r#"{"x":1,"x":2}"#, r#"{"a":[],"b":[1]}"#] { - assert!(parse_output(bad, mode).is_err(), "{mode}: {bad}"); - } - } - let ctx = HostContext::default(); - let env = ForeignEnv::from_ctx(&ctx); - let items = (0..2).map(|idx| PreparedMany { - idx, job: Job::simple("python", "print('{\"x\":1,\"x\":2}')", None), output: "auto".into(), - }).collect(); - assert!(run_prepared(&env, items, 2).unwrap_err().contains("duplicate")); - } - -} diff --git a/src/host/foreign_doc.rs b/src/host/foreign_doc.rs deleted file mode 100755 index fdb9ffe..0000000 --- a/src/host/foreign_doc.rs +++ /dev/null @@ -1,2552 +0,0 @@ -//! Document session: cells, kernels, journals, state store. -//! -//! Two journals (do not mix names): -//! - **execution journal** (`JournalRecord`): UI timing / status / errors. -//! - **oracle journal** (`OracleRecord`): Ω step recordings for `replay_check` -//! (source hash, stdout, result, ok, code). -//! -//! Stateful cells live here, owned by the foreign runtime. The view reads a -//! `会话 = > foreign.session ...` handle; no table names are reserved, and a -//! document without that handle gets stateless one-shot cells. - -use std::collections::{HashMap, HashSet}; -use std::path::{Path, PathBuf}; - -use sha2::{Digest, Sha256}; - -use crate::foreign::registry; -use crate::host::foreign_session; -use crate::host::HostContext; -use crate::value::Value; - -mod control; -pub mod packing; -pub use control::DocumentControl; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CellStatus { - Never, - Running, - Clean, - Dirty, - Stale, - Error, - Unlisted, -} - -impl CellStatus { - fn as_str(self) -> &'static str { - match self { - Self::Never => "never", - Self::Running => "running", - Self::Clean => "clean", - Self::Dirty => "dirty", - Self::Stale => "stale", - Self::Error => "error", - Self::Unlisted => "unlisted", - } - } -} - -#[derive(Debug, Clone)] -pub struct Cell { - pub name: String, - pub lang: String, - pub source: String, - pub line_start: u32, - pub line_end: u32, - pub source_hash: String, - pub kernel: String, - /// Per-cell raw stdin from foreign.session inputs=. - pub stdin: String, - pub listed: bool, - pub status: CellStatus, - pub runs: u64, - pub last_ms: u64, - pub last_ok: bool, - pub last_error: String, - /// Captured stdout from the last evaluation (recording surface for replay_check). - pub last_stdout: String, - pub last_code: i64, - /// Value returned by the last successful evaluation, used by explicit persist. - pub last_result: Value, -} - -#[derive(Debug, Clone)] -pub struct KernelDecl { - pub name: String, - pub lang: String, - pub cmd: Option, - pub implicit: bool, -} - -#[derive(Debug, Clone)] -pub struct JournalRecord { - pub seq: u64, - pub cell: String, - pub kernel: String, - pub lang: String, - pub ok: bool, - pub code: i64, - pub ms: u64, - pub timestamp_ms: i64, - pub error: String, -} - -/// One recorded Ω step: what a later `replay_check` compares against. -#[derive(Debug, Clone)] -pub struct OracleRecord { - pub value: Value, - pub stdin: String, - pub seq: u64, - pub cell: String, - pub kernel: String, - pub lang: String, - pub source_hash: String, - pub ok: bool, - pub code: i64, - pub stdout: String, - pub result: Value, -} - -impl OracleRecord { - fn to_value(&self) -> Value { - Value::Map(vec![ - ("value".into(), self.value.clone()), - ("seq".into(), Value::Int(self.seq as i64)), - ("stdin".into(), Value::Text(self.stdin.clone())), - ("cell".into(), Value::Text(self.cell.clone())), - ("kernel".into(), Value::Text(self.kernel.clone())), - ("lang".into(), Value::Text(self.lang.clone())), - ("source_hash".into(), Value::Text(self.source_hash.clone())), - ("ok".into(), Value::Bool(self.ok)), - ("code".into(), Value::Int(self.code)), - ("stdout".into(), Value::Text(self.stdout.clone())), - ("result".into(), self.result.clone()), - ]) - } -} - -pub struct DocumentSession { - pub control: DocumentControl, - replay_controls: Vec, - replay_boundary: Option, - source_hash: String, - initial_values: Vec<(String, String, Value)>, - initial_image: Value, - action_history: Vec, - action_depth: usize, - replay_fresh: bool, - pub path: PathBuf, - root: PathBuf, - pub persistent: bool, - pub cells: Vec, - pub kernels: Vec, - pub order: Vec, - pub journal: Vec, - pub oracle_journal: Vec, - pub value_store: HashMap, - pub cursor: usize, - pub generation: u64, - pub opened_ms: i64, - host: HostContext, - kernel_sessions: HashMap, - seq: u64, -} - -fn hash_source(source: &str) -> String { - let mut h = Sha256::new(); - h.update(source.as_bytes()); - format!("{:x}", h.finalize()) -} - -fn now_ms() -> i64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as i64) - .unwrap_or(0) -} - -/// Convert a table value into row maps. Handles both row tables (`| @ | ... |`) -/// and ordinary column tables; no source text is scanned. -fn table_rows(v: &Value) -> Result>, String> { - match v { - Value::None => Ok(Vec::new()), - Value::List(rows) => { - let mut out = Vec::with_capacity(rows.len()); - for (i, row) in rows.iter().enumerate() { - let Value::Map(pairs) = row else { - return Err(format!("view table row {} is not a map", i + 1)); - }; - out.push( - pairs - .iter() - .filter(|(k, _)| k != "@") - .map(|(k, v)| (k.clone(), v.clone())) - .collect(), - ); - } - Ok(out) - } - Value::Map(cols) => { - // A single-row table may evaluate to a map of scalar fields rather - // than a column map. Treat that map as one record. - if !cols.iter().all(|(_, v)| matches!(v, Value::List(_))) { - let row = cols - .iter() - .filter(|(k, _)| k != "@") - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); - return Ok(vec![row]); - } - let mut width = 0usize; - for (_, value) in cols { - let Value::List(xs) = value else { - unreachable!(); - }; - width = width.max(xs.len()); - } - let mut out = Vec::with_capacity(width); - for i in 0..width { - let mut row = HashMap::new(); - for (name, value) in cols { - if let Value::List(xs) = value { - if let Some(v) = xs.get(i) { - row.insert(name.clone(), v.clone()); - } - } - } - out.push(row); - } - Ok(out) - } - _ => Err("view plan binding is not a table".into()), - } -} - -fn plan_tables( - bindings: &HashMap, -) -> Result< - ( - Option>>, - Option>>, - Option>>, - Option>>, - ), - String, -> { - let Some(plan) = bindings.get("会话") else { - return Ok((None, None, None, None)); - }; - let Value::Map(fields) = plan else { - // `会话` is also a common low-level session id binding (e.g. from - // foreign.session_open). It is not a view plan; leave cells stateless. - return Ok((None, None, None, None)); - }; - let field = |name: &str| { - fields - .iter() - .find(|(k, _)| k == name) - .map(|(_, v)| v.clone()) - }; - let kind = field("kind").map(|v| value_text(&v)).unwrap_or_default(); - if kind != "foreign-session" { - return Err("`会话` must be a foreign.session handle".into()); - } - let kernels = match field("kernels") { - Some(Value::None) | None => None, - Some(v) => Some(table_rows(&v)?), - }; - let cells = match field("cells") { - Some(Value::None) | None => None, - Some(v) => Some(table_rows(&v)?), - }; - let values = match field("values") { - Some(Value::None) | None => None, - Some(v) => Some(table_rows(&v)?), - }; - let inputs = match field("inputs") { - Some(Value::None) | None => None, - Some(v) => Some(table_rows(&v)?), - }; - Ok((kernels, cells, values, inputs)) -} - -fn col_value<'a>(row: &'a HashMap, names: &[&str]) -> Option<&'a Value> { - for n in names { - if let Some(v) = row.get(*n) { - if !matches!(v, Value::None) { - return Some(v); - } - } - } - None -} - -fn value_text(v: &Value) -> String { - match v { - Value::Text(s) => s.clone(), - Value::None => String::new(), - other => other.as_display(), - } -} - -fn col_text(row: &HashMap, names: &[&str]) -> Option { - col_value(row, names).map(value_text).filter(|s| !s.trim().is_empty()) -} - -/// Evaluate the entry object's declarations with the real interpreter. Tables -/// are ordinary Marqdo values; the view does not re-parse source text. -fn capture_bindings( - path: &Path, - root: &Path, - module: &crate::ast::Module, - source: &str, -) -> Result, String> { - let mut host = HostContext::for_capture(Some(path), crate::host::HostCaps::default()); - host.cwd = path.parent().unwrap_or_else(|| Path::new(".")).to_path_buf(); - host.fs_root = Some(root.to_path_buf()); - host.entry_path = Some(path.to_path_buf()); - host.entry_source = Some(source.to_string()); - host.entry_metadata = module.metadata.clone(); - let mut interp = crate::interp::Interpreter::with_capture(Some(path), false).with_host(host); - interp - .capture_declarations(module, &["会话"]) - .map_err(|e| format!("view plan evaluation: {e}")) -} - -fn collect_cells(stmts: &[crate::ast::Stmt], out: &mut Vec, seen: &mut HashSet) -> Result<(), String> { - for stmt in stmts { - match stmt { - crate::ast::Stmt::Assign { - name, - value: crate::ast::Expr::Code(c), - span, - end_line, - } => { - if !seen.insert(name.clone()) { - return Err(format!( - "cell `{name}` is assigned more than once (line {})", - span.line - )); - } - out.push(Cell { - name: name.clone(), - lang: c.lang.clone(), - source: c.source.clone(), - line_start: span.line, - line_end: *end_line, - source_hash: hash_source(&c.source), - kernel: String::new(), - stdin: String::new(), - listed: false, - status: CellStatus::Never, - runs: 0, - last_ms: 0, - last_ok: false, - last_error: String::new(), - last_stdout: String::new(), - last_code: 0, - last_result: Value::None, - }); - } - crate::ast::Stmt::Branch { arms, .. } => { - for arm in arms { - collect_cells(&arm.body, out, seen)?; - } - } - crate::ast::Stmt::While { body, .. } | crate::ast::Stmt::ForEach { body, .. } => { - collect_cells(body, out, seen)?; - } - _ => {} - } - } - Ok(()) -} - -fn fun_has_plan(fun: &crate::ast::Function) -> bool { - fun.body.iter().any(|stmt| match stmt { - crate::ast::Stmt::Assign { name, .. } => name == "会话", - _ => false, - }) || fun.children.iter().any(fun_has_plan) -} - -fn has_nested_plan(module: &crate::ast::Module, entry_name: &str) -> bool { - module - .functions - .iter() - .find(|f| f.name == entry_name) - .map(|entry| entry.children.iter().any(fun_has_plan)) - .unwrap_or(false) -} - -mod replay; - -impl DocumentSession { - pub(crate) fn adopt_control(&mut self, control: DocumentControl) { - self.control = control; - for (name, id) in &self.kernel_sessions { - if let Some(session) = self.host.foreign_sessions.get(id) { - self.control.register(name, session.interrupt_handle.clone()); - } - } - } - pub fn open(path: &Path, root: &Path) -> Result { - let source = std::fs::read_to_string(path) - .map_err(|e| format!("read {}: {e}", path.display()))?; - Self::open_source(path, root, &source, true) - } - - fn open_source(path: &Path, root: &Path, source: &str, initialize: bool) -> Result { - let bind_ctx = crate::binding::BindingContext::from_binds( - &[], - crate::binding::cwd_for_path(Some(path)), - ); - let module = crate::load::load_module_with_source(path, source, &bind_ctx) - .map_err(|e| format!("load {}: {e}", path.display()))?; - let entry = module - .functions - .iter() - .find(|f| f.name == "main") - .or_else(|| { - let objs: Vec<_> = module.functions.iter().filter(|f| f.is_object()).collect(); - if objs.len() == 1 { - Some(objs[0]) - } else { - None - } - }) - .ok_or_else(|| "notebook: no `main` entry (or sole object) to index".to_string())?; - let mut cells = Vec::new(); - let mut seen = HashSet::new(); - collect_cells(&entry.body, &mut cells, &mut seen)?; - let declarations = capture_bindings(path, root, &module, &source)?; - if !declarations.contains_key("会话") && has_nested_plan(&module, &entry.name) { - return Err( - "foreign.session: plan must be a top-level binding (`会话` = > foreign.session ...)" - .into(), - ); - } - - let (plan_kernels, plan_cells, plan_values, plan_inputs) = plan_tables(&declarations)?; - let persistent = matches!( - declarations.get("会话"), - Some(Value::Map(fields)) - if fields - .iter() - .any(|(k, v)| k == "kind" && value_text(v) == "foreign-session") - ); - let mut kernels: Vec = Vec::new(); - let mut kernel_map: HashMap = HashMap::new(); - if let Some(rows) = plan_kernels { - if rows.is_empty() { - return Err("foreign.session: at least one kernel row is required".into()); - } - for row in rows { - let name = col_text(&row, &["名称", "Name", "name"]) - .ok_or_else(|| "foreign.session kernels: missing 名称/Name".to_string())?; - let lang = col_text(&row, &["语言", "Language", "language", "lang"]) - .ok_or_else(|| format!("foreign.session[{name}]: missing 语言/Language"))?; - let lang = registry::canonical(&lang); - let cmd = col_text(&row, &["命令", "Command", "command", "cmd"]); - if kernel_map.contains_key(&name) { - return Err(format!("foreign.session: kernel `{name}` is declared twice")); - } - let decl = KernelDecl { - name: name.clone(), - lang, - cmd, - implicit: false, - }; - kernel_map.insert(name.clone(), decl.clone()); - kernels.push(decl); - } - } - - let mut order: Vec = Vec::new(); - let session_rows = plan_cells; - if let Some(rows) = session_rows { - if rows.is_empty() { - return Err("foreign.session cells: at least one cell row is required".into()); - } - let by_name: HashMap = cells - .iter() - .enumerate() - .map(|(i, c)| (c.name.clone(), i)) - .collect(); - let mut listed = HashSet::new(); - for row in rows { - let cell_name = col_text(&row, &["单元", "Cell", "cell", "单元名"]) - .ok_or_else(|| "foreign.session cells: missing 单元/Cell".to_string())?; - let kernel_name = col_text(&row, &["内核", "Kernel", "kernel"]) - .ok_or_else(|| format!("foreign.session[{cell_name}]: missing 内核/Kernel"))?; - let Some(&ci) = by_name.get(&cell_name) else { - return Err(format!("foreign.session: unknown cell `{cell_name}`")); - }; - if !listed.insert(cell_name.clone()) { - return Err(format!("foreign.session: cell `{cell_name}` is listed twice")); - } - let kernel = resolve_kernel(&mut kernels, &mut kernel_map, &kernel_name)?; - if registry::canonical(&cells[ci].lang) != registry::canonical(&kernel.lang) { - return Err(format!( - "foreign.session: cell `{cell_name}` ({}) cannot use kernel `{}` ({})", - cells[ci].lang, kernel.name, kernel.lang - )); - } - cells[ci].kernel = kernel.name.clone(); - cells[ci].listed = true; - order.push(cell_name); - } - for cell in &mut cells { - if !cell.listed { - cell.status = CellStatus::Unlisted; - } - } - } else if persistent { - for cell in &mut cells { - let kernel = ensure_default_kernel( - &mut kernels, - &mut kernel_map, - &cell.lang, - ); - cell.kernel = kernel; - cell.listed = true; - order.push(cell.name.clone()); - } - } else { - for cell in &mut cells { - cell.kernel = "one-shot".into(); - cell.listed = true; - order.push(cell.name.clone()); - } - } - - let mut host = HostContext::default(); - let doc_dir = path.parent().unwrap_or_else(|| Path::new(".")); - host.cwd = doc_dir.to_path_buf(); - host.fs_root = Some(root.to_path_buf()); - host.entry_path = Some(path.to_path_buf()); - host.entry_metadata = module.metadata.clone(); - let source_hash = hash_source(&source); - host.entry_source = Some(source.to_string()); - - let mut session = Self { - control: DocumentControl::default(), - replay_controls: Vec::new(), - replay_boundary: None, - source_hash, - initial_values: Vec::new(), - initial_image: Value::None, - action_history: Vec::new(), - action_depth: 0, - replay_fresh: false, - path: path.to_path_buf(), - root: root.to_path_buf(), - persistent, - cells, - kernels, - order, - journal: Vec::new(), - oracle_journal: Vec::new(), - value_store: HashMap::new(), - cursor: 0, - generation: 1, - opened_ms: now_ms(), - host, - kernel_sessions: HashMap::new(), - seq: 0, - }; - if let Some(rows) = plan_values { - for row in rows { - let kernel = col_text(&row, &["内核", "Kernel", "kernel"]) - .ok_or_else(|| "foreign.session values: missing 内核/Kernel".to_string())?; - let name = col_text(&row, &["名称", "Name", "name"]) - .ok_or_else(|| "foreign.session values: missing 名称/Name".to_string())?; - let value = col_value(&row, &["值", "Value", "value", "数据"]) - .ok_or_else(|| format!("foreign.session values[{name}]: missing 值/Value"))? - .clone(); - if session.kernel(&kernel).is_none() { return Err(format!("unknown kernel `{kernel}`")); } - if !foreign_session::valid_name(&name) { return Err("initial value: name must be an identifier".into()); } - super::oracle::admit(&value)?; - session.initial_values.push((kernel, name, value)); - } - } - if let Some(rows) = plan_inputs { - for row in rows { - let cell = col_text(&row, &["单元", "Cell", "cell", "单元名"]) - .ok_or_else(|| "foreign.session inputs: missing 单元/Cell".to_string())?; - let raw = col_value(&row, &["stdin", "标准输入", "输入"]) - .map(value_text) - .unwrap_or_default(); - if let Some(i) = session.cell_index(&cell) { - session.cells[i].stdin = raw; - } - } - } - session.initial_image = session.plan_image(); - if initialize { session.initialize_values()?; } - session.replay_fresh = true; - Ok(session) - } - - /// Re-read the document, preserving kernels/state/journal. Changed cells become dirty. - fn reload_source(&mut self, source: &str, root: &Path) -> Result<(), String> { - let fresh = Self::open_source(&self.path, root, source, false)?; - self.install_reload(fresh) - } - - fn install_reload(&mut self, mut fresh: Self) -> Result<(), String> { - let new_source = fresh.host.entry_source.clone(); - let new_metadata = fresh.host.entry_metadata.clone(); - let old_kernels = self.kernels.clone(); - let old: HashMap = self - .cells - .iter() - .cloned() - .map(|c| (c.name.clone(), c)) - .collect(); - for c in &mut fresh.cells { - if let Some(o) = old.get(&c.name) { - c.runs = o.runs; - c.last_ms = o.last_ms; - c.last_ok = o.last_ok; - c.last_error = o.last_error.clone(); - c.last_stdout = o.last_stdout.clone(); - c.last_code = o.last_code; - c.last_result = o.last_result.clone(); - c.status = if o.source_hash != c.source_hash || o.kernel != c.kernel { - CellStatus::Dirty - } else if o.status == CellStatus::Running { - CellStatus::Dirty - } else { - o.status - }; - } - } - fresh.host = std::mem::replace(&mut self.host, HostContext::default()); - fresh.host.entry_source = new_source; - fresh.host.entry_metadata = new_metadata; - fresh.initial_image = self.initial_image.clone(); - fresh.action_history = std::mem::take(&mut self.action_history); - fresh.control = self.control.clone(); - fresh.replay_controls = std::mem::take(&mut self.replay_controls); - fresh.replay_boundary = self.replay_boundary.take(); - fresh.action_depth = self.action_depth; - fresh.generation = self.generation + 1; - fresh.kernel_sessions = std::mem::take(&mut self.kernel_sessions); - fresh.value_store = std::mem::take(&mut self.value_store); - fresh.journal = std::mem::take(&mut self.journal); - fresh.oracle_journal = std::mem::take(&mut self.oracle_journal); - fresh.seq = self.seq; - fresh.replay_fresh = false; - fresh.cursor = self.cursor.min(fresh.order.len()); - fresh.opened_ms = self.opened_ms; - let known: HashSet = fresh.kernels.iter().filter(|k| - old_kernels.iter().any(|old| old.name == k.name && old.lang == k.lang && old.cmd == k.cmd) - ).map(|k| k.name.clone()).collect(); - let orphans: Vec = fresh - .kernel_sessions - .keys() - .filter(|k| !known.contains(*k)) - .cloned() - .collect(); - for k in orphans { - if let Some(id) = fresh.kernel_sessions.remove(&k) { - let _ = foreign_session::close(&mut fresh.host, &Value::Handle(id)); - } - } - *self = fresh; - Ok(()) - } - - pub fn title(&self) -> String { - self.path - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("session") - .trim_end_matches(".mq") - .to_string() - } - - fn cell_index(&self, name: &str) -> Option { - self.cells.iter().position(|c| c.name == name) - } - - fn kernel(&self, name: &str) -> Option<&KernelDecl> { - self.kernels.iter().find(|k| k.name == name) - } - - fn ensure_kernel_session(&mut self, kernel_name: &str) -> Result { - self.replay_fresh = false; - if let Some(id) = self.kernel_sessions.get(kernel_name) { - if self.host.foreign_sessions.contains_key(id) { - return Ok(id.clone()); - } - } - let decl = self - .kernel(kernel_name) - .ok_or_else(|| format!("unknown kernel `{kernel_name}`"))? - .clone(); - let cmd_value = decl.cmd.map(Value::Text); - let lang = Value::Text(decl.lang.clone()); - let id = foreign_session::open( - &mut self.host, - &lang, - cmd_value.as_ref(), - None, - None, - None, - )?; - let id = match id { - Value::Handle(s) => s, - _ => return Err("session_open returned non-handle id".into()), - }; - for (kernel, name, value) in self.initial_values.clone() { - if kernel == kernel_name { - if let Err(error) = foreign_session::set(&mut self.host, &Value::Handle(id.clone()), &Value::Text(name), &value) { - let _ = foreign_session::close(&mut self.host, &Value::Handle(id.clone())); - return Err(error); - } - } - } - self.kernel_sessions.insert(kernel_name.to_string(), id.clone()); - self.control.register(kernel_name, self.host.foreign_sessions[&id].interrupt_handle.clone()); - Ok(id) - } - - fn record_result(&mut self, cell: &str, kernel: &str, record: &Value, stdin: Option<&str>) -> Result<(), String> { - let field = |k: &str| match record { - Value::Map(entries) => entries - .iter() - .find(|(kk, _)| kk == k) - .map(|(_, v)| v.clone()), - _ => None, - }; - let ok = matches!(field("ok"), Some(Value::Bool(true))); - let ms = match field("ms") { - Some(Value::Int(n)) => n as u64, - _ => 0, - }; - let error = field("error") - .and_then(|v| v.reveal_text().map(|s| s.to_string())) - .unwrap_or_default(); - let code = match field("code") { - Some(Value::Int(n)) => n, - _ => 0, - }; - let stdout = field("stdout") - .and_then(|v| v.reveal_text().map(|s| s.to_string())) - .unwrap_or_default(); - let (lang, source_hash) = self - .cell_index(cell) - .map(|i| { - ( - self.cells[i].lang.clone(), - self.cells[i].source_hash.clone(), - ) - }) - .unwrap_or_default(); - // An explicit null is a semantic result, even when stdout is nonempty. - // Keep display output separate; only legacy records lacking the field - // can use their stdout as a fallback. - let last_result = field("result").unwrap_or_else(|| { - field("stdout") - .and_then(|v| v.reveal_text().map(|s| Value::Text(s.to_string()))) - .unwrap_or(Value::None) - }); - if let Some(i) = self.cell_index(cell) { - let c = &mut self.cells[i]; - c.runs += 1; - c.last_ms = ms; - c.last_ok = ok; - c.last_error = error.clone(); - c.last_stdout = stdout.clone(); - c.last_code = code; - c.last_result = last_result.clone(); - c.status = if ok { CellStatus::Clean } else { CellStatus::Error }; - } - self.seq += 1; - self.journal.push(JournalRecord { - seq: self.seq, - cell: cell.to_string(), - kernel: kernel.to_string(), - lang: lang.clone(), - ok, - code, - ms, - timestamp_ms: now_ms(), - error, - }); - let value = super::oracle::eval_observation(record)?; - super::oracle::append(&mut self.host, "eval", &value)?; - self.oracle_journal.push(OracleRecord { - value, - stdin: stdin.unwrap_or_default().to_string(), - seq: self.seq, - cell: cell.to_string(), - kernel: kernel.to_string(), - lang, - source_hash, - ok, - code, - stdout, - result: last_result, - }); - self.check_replay_cell_boundary(); - Ok(()) - } - - pub fn run_cell(&mut self, cell_name: &str, kernel_override: Option<&str>) -> Result { - self.run_cell_with_stdin(cell_name, kernel_override, None) - } - - fn run_cell_with_stdin_inner( - &mut self, - cell_name: &str, - kernel_override: Option<&str>, - stdin: Option<&str>, - ) -> Result { - self.replay_fresh = false; - let ci = self - .cell_index(cell_name) - .ok_or_else(|| format!("unknown cell `{cell_name}`"))?; - if !self.cells[ci].listed && kernel_override.is_none() { - return Err(format!("cell `{cell_name}` is not listed in the foreign session")); - } - let stdin_owned = stdin.map(str::to_string).or_else(|| { - let s = self.cells[ci].stdin.clone(); - if s.is_empty() { None } else { Some(s) } - }); - let stdin = stdin_owned.as_deref(); - if !self.persistent { - self.cells[ci].kernel = "one-shot".into(); - self.cells[ci].status = CellStatus::Running; - let lang = self.cells[ci].lang.clone(); - let source = self.cells[ci].source.clone(); - let result = crate::host::foreign::invoke_for_view( - &self.root, - &lang, - &source, - None, - stdin, - None, - ); - return match result { - Ok(record) => { - self.record_result(cell_name, "one-shot", &record, stdin)?; - Ok(record) - } - Err(e) => { - if let Some(i) = self.cell_index(cell_name) { - self.cells[i].status = CellStatus::Error; - self.cells[i].last_error = e.clone(); - } - Err(e) - } - }; - } - let kernel = match kernel_override { - Some(k) => { - if self.kernel(k).is_none() { - return Err(format!("unknown kernel `{k}`")); - } - let ci_lang = registry::canonical(&self.cells[ci].lang); - let klang = registry::canonical( - &self.kernel(k).map(|d| d.lang.clone()).unwrap_or_default(), - ); - if ci_lang != klang { - return Err(format!( - "cell `{cell_name}` ({}) cannot run in kernel `{k}` ({klang})", - self.cells[ci].lang - )); - } - self.cells[ci].kernel = k.to_string(); - self.cells[ci].listed = true; - k.to_string() - } - None => self.cells[ci].kernel.clone(), - }; - self.cells[ci].status = CellStatus::Running; - let result = (|| -> Result { - let id = self.ensure_kernel_session(&kernel)?; - if self.control.cancelled() { return Err("document action interrupted before evaluation".into()); } - let source = Value::Text(self.cells[ci].source.clone()); - let record = foreign_session::eval_with_stdin( - &mut self.host, - &Value::Handle(id), - None, - Some(&source), - None, - stdin, - None, - )?; - self.record_result(cell_name, &kernel, &record, stdin)?; - Ok(record) - })(); - if result.is_err() { - self.cells[ci].status = CellStatus::Error; - } - result - } - - pub fn step(&mut self) -> Result { - self.step_with_stdin(None) - } - - fn step_with_stdin_inner(&mut self, stdin: Option<&str>) -> Result { - if self.cursor >= self.order.len() { - return Ok(Value::Map(vec![ - ("done".into(), Value::Bool(true)), - ("cursor".into(), Value::Int(self.cursor as i64)), - ("generation".into(), Value::Int(self.generation as i64)), - ])); - } - let name = self.order[self.cursor].clone(); - let record = self.run_cell_with_stdin(&name, None, stdin)?; - let ci = self.cell_index(&name).unwrap_or(0); - let kernel = self.cells[ci].kernel.clone(); - self.cursor += 1; - let mut fields = match record { - Value::Map(m) => m, - other => vec![("result".into(), other)], - }; - fields.push(("cell".into(), Value::Text(name))); - fields.push(("kernel".into(), Value::Text(kernel))); - fields.push(("cursor".into(), Value::Int(self.cursor as i64))); - Ok(Value::Map(fields)) - } - - pub fn run_all(&mut self, restart: bool) -> Result { - self.run_all_with_stdin(restart, None) - } - - pub fn run_all_with_stdin( - &mut self, - restart: bool, - stdin: Option<&str>, - ) -> Result { - self.run_all_with_inputs(restart, stdin, None) - } - - fn run_all_with_inputs_inner( - &mut self, - restart: bool, - stdin: Option<&str>, - inputs: Option<&HashMap>, - ) -> Result { - if restart { - self.restart_all()?; - } - self.cursor = 0; - let mut records = Vec::new(); - let mut failed = 0i64; - for name in self.order.clone() { - if self.control.cancelled() { break; } - if !self.replay_batch_can_continue() { break; } - let seq_before = self.seq; - let cell_stdin = inputs - .and_then(|m| m.get(&name)) - .map(String::as_str) - .or(stdin); - let record = match self.run_cell_with_stdin(&name, None, cell_stdin) { - Ok(record) => record, - Err(error) => { - if let Some(i) = self.cell_index(&name) { - self.cells[i].status = CellStatus::Error; - self.cells[i].last_error = error.clone(); - } - Value::Map(vec![ - ("ok".into(), Value::Bool(false)), - ("stdout".into(), Value::Text(String::new())), - ("stderr".into(), Value::Text(String::new())), - ("error".into(), Value::Text(error)), - ("code".into(), Value::Int(-1)), - ("ms".into(), Value::Int(0)), - ]) - } - }; - let ok = match &record { - Value::Map(m) => matches!( - m.iter().find(|(k, _)| k == "ok").map(|(_, v)| v), - Some(Value::Bool(true)) - ), - _ => false, - }; - if !ok { - failed += 1; - } - let mut m = match record { - Value::Map(m) => m, - other => vec![("result".into(), other)], - }; - m.push(("cell".into(), Value::Text(name))); - let record = Value::Map(m); - self.check_replay_batch_record(&record, seq_before); - records.push(record); - self.cursor += 1; - } - let mut summary = vec![ - ("ok".into(), Value::Bool(failed == 0 && !self.control.cancelled())), - ("ran".into(), Value::Int(records.len() as i64)), - ("failed".into(), Value::Int(failed)), - ("records".into(), Value::List(records)), - ]; - if self.control.cancelled() { - summary.push(("cancelled".into(), Value::Bool(true))); - summary.push(("remaining".into(), Value::Int((self.order.len() - self.cursor) as i64))); - } - Ok(Value::Map(summary)) - } - - fn interrupt_inner(&mut self) -> Result { - let mut ids: Vec = self.kernel_sessions.keys().cloned().collect(); - ids.sort(); - let mut out = Vec::new(); - for name in ids { - if let Some(id) = self.kernel_sessions.get(&name) { - match foreign_session::interrupt(&mut self.host, &Value::Handle(id.clone())) { - Ok(_) => out.push(Value::Text(name)), - Err(e) => out.push(Value::Text(format!("{name}: {e}"))), - } - } - } - Ok(Value::List(out)) - } - - fn restart_kernel_inner(&mut self, name: &str) -> Result { - if let Some(id) = self.kernel_sessions.remove(name) { - let _ = foreign_session::close(&mut self.host, &Value::Handle(id)); - } - for c in &mut self.cells { - if c.kernel == name { - c.status = CellStatus::Never; - c.last_error.clear(); - } - } - Ok(Value::Bool(true)) - } - - fn restart_all_inner(&mut self) -> Result { - let mut names: Vec = self.kernel_sessions.keys().cloned().collect(); - names.sort(); - for name in names { - self.restart_kernel(&name)?; - } - self.cursor = 0; - for c in &mut self.cells { - c.status = if c.listed { CellStatus::Never } else { CellStatus::Unlisted }; - } - Ok(Value::Bool(true)) - } - - fn assign_kernel_inner(&mut self, cell: &str, kernel: &str) -> Result { - let ci = self - .cell_index(cell) - .ok_or_else(|| format!("unknown cell `{cell}`"))?; - let decl = self - .kernel(kernel) - .ok_or_else(|| format!("unknown kernel `{kernel}`"))? - .clone(); - if registry::canonical(&self.cells[ci].lang) != registry::canonical(&decl.lang) { - return Err(format!( - "cell `{cell}` ({}) cannot use kernel `{kernel}` ({})", - self.cells[ci].lang, decl.lang - )); - } - self.cells[ci].kernel = kernel.to_string(); - self.cells[ci].listed = true; - self.cells[ci].status = CellStatus::Dirty; - self.generation += 1; - Ok(Value::None) - } - - fn add_cell_inner( - &mut self, - cell: &str, - lang: &str, - source: &str, - kernel: &str, - ) -> Result { - if self.cell_index(cell).is_some() { - return Err(format!("cell `{cell}` already exists")); - } - let lang = registry::canonical(lang); - let decl = self - .kernel(kernel) - .ok_or_else(|| format!("unknown kernel `{kernel}`"))? - .clone(); - if registry::canonical(&decl.lang) != lang { - return Err(format!( - "cell `{cell}` ({lang}) cannot use kernel `{kernel}` ({})", - decl.lang - )); - } - self.cells.push(Cell { - name: cell.to_string(), - lang, - source: source.to_string(), - line_start: 0, - line_end: 0, - source_hash: hash_source(source), - kernel: kernel.to_string(), - stdin: String::new(), - listed: true, - status: CellStatus::Never, - runs: 0, - last_ms: 0, - last_ok: false, - last_error: String::new(), - last_stdout: String::new(), - last_code: 0, - last_result: Value::None, - }); - self.order.push(cell.to_string()); - self.generation += 1; - Ok(Value::Bool(true)) - } - - fn remove_cell_inner(&mut self, cell: &str) -> Result { - let Some(i) = self.cell_index(cell) else { - return Err(format!("unknown cell `{cell}`")); - }; - self.cells.remove(i); - self.order.retain(|name| name != cell); - self.journal.retain(|j| j.cell != cell); - self.generation += 1; - Ok(Value::Bool(true)) - } - - fn set_value_inner(&mut self, kernel: &str, name: &str, value: Value) -> Result { - let out = self.push_value(kernel, name, value)?; - self.generation += 1; - Ok(out) - } - - fn state_list_inner(&mut self) -> Result { - let marqdo = self - .value_store - .iter() - .map(|(k, v)| (k.clone(), v.clone())) - .collect::>(); - let mut kernels = Vec::new(); - for k in &self.kernels { - let live = self.kernel_sessions.get(&k.name).cloned(); - let mut vars = Vec::new(); - if let Some(id) = live { - if self.host.foreign_sessions.contains_key(&id) { - if let Ok(names) = foreign_session::names(&mut self.host, &Value::Handle(id)) { - if let Value::List(xs) = names { - vars = xs; - } - } - } - } - kernels.push(Value::Map(vec![ - ("name".into(), Value::Text(k.name.clone())), - ("lang".into(), Value::Text(k.lang.clone())), - ("vars".into(), Value::List(vars)), - ])); - } - Ok(Value::Map(vec![ - ("marqdo".into(), Value::Map(marqdo)), - ("kernels".into(), Value::List(kernels)), - ])) - } - - fn push_value_inner(&mut self, kernel: &str, name: &str, value: Value) -> Result { - if self.kernel(kernel).is_none() { return Err(format!("unknown kernel `{kernel}`")); } - if !foreign_session::valid_name(name) { return Err("session_set: name must be an identifier".into()); } - super::oracle::admit(&value)?; - let id = self.ensure_kernel_session(kernel)?; - foreign_session::set( - &mut self.host, - &Value::Handle(id), - &Value::Text(name.to_string()), - &value, - )?; - self.value_store.insert(name.to_string(), value); - Ok(Value::None) - } - - fn pull_value_inner(&mut self, kernel: &str, name: &str) -> Result { - if self.kernel(kernel).is_none() { return Err(format!("unknown kernel `{kernel}`")); } - if !foreign_session::valid_name(name) { return Err("session_get: name must be an identifier".into()); } - let id = self.ensure_kernel_session(kernel)?; - let value = foreign_session::get( - &mut self.host, - &Value::Handle(id), - &Value::Text(name.to_string()), - )?; - super::oracle::append(&mut self.host, "get", &value)?; - self.value_store - .insert(name.to_string(), value.clone()); - Ok(value) - } - - pub fn summary(&self) -> Value { - let cells = self - .cells - .iter() - .map(|c| { - Value::Map(vec![ - ("name".into(), Value::Text(c.name.clone())), - ("lang".into(), Value::Text(c.lang.clone())), - ("kernel".into(), Value::Text(c.kernel.clone())), - ("listed".into(), Value::Bool(c.listed)), - ("status".into(), Value::Text(c.status.as_str().into())), - ("line_start".into(), Value::Int(c.line_start as i64)), - ("line_end".into(), Value::Int(c.line_end as i64)), - ("runs".into(), Value::Int(c.runs as i64)), - ("last_ms".into(), Value::Int(c.last_ms as i64)), - ("last_ok".into(), Value::Bool(c.last_ok)), - ("last_error".into(), Value::Text(c.last_error.clone())), - ("stdin".into(), Value::Text(c.stdin.clone())), - ]) - }) - .collect(); - let kernels = self - .kernels - .iter() - .map(|k| { - Value::Map(vec![ - ("name".into(), Value::Text(k.name.clone())), - ("lang".into(), Value::Text(k.lang.clone())), - ("implicit".into(), Value::Bool(k.implicit)), - ( - "live".into(), - Value::Bool(self.kernel_sessions.contains_key(&k.name)), - ), - ]) - }) - .collect(); - Value::Map(vec![ - ("title".into(), Value::Text(self.title())), - ("path".into(), Value::Text(self.path.display().to_string())), - ("persistent".into(), Value::Bool(self.persistent)), - ("cells".into(), Value::List(cells)), - ("kernels".into(), Value::List(kernels)), - ("order".into(), Value::List( - self.order.iter().cloned().map(Value::Text).collect(), - )), - ("cursor".into(), Value::Int(self.cursor as i64)), - ("generation".into(), Value::Int(self.generation as i64)), - ("journal".into(), Value::List( - self.journal - .iter() - .map(|j| { - Value::Map(vec![ - ("seq".into(), Value::Int(j.seq as i64)), - ("cell".into(), Value::Text(j.cell.clone())), - ("kernel".into(), Value::Text(j.kernel.clone())), - ("lang".into(), Value::Text(j.lang.clone())), - ("ok".into(), Value::Bool(j.ok)), - ("code".into(), Value::Int(j.code)), - ("ms".into(), Value::Int(j.ms as i64)), - ("timestamp_ms".into(), Value::Int(j.timestamp_ms)), - ("error".into(), Value::Text(j.error.clone())), - ]) - }) - .collect(), - )), - ("opened_ms".into(), Value::Int(self.opened_ms)), - ]) - } - - /// Clear one cell's displayed output/record; kernels and live state survive. - fn clear_cell_inner(&mut self, cell: &str) -> Result { - let i = self - .cell_index(cell) - .ok_or_else(|| format!("unknown cell `{cell}`"))?; - self.cells[i].runs = 0; - self.cells[i].last_ms = 0; - self.cells[i].last_ok = false; - self.cells[i].last_error.clear(); - self.cells[i].last_stdout.clear(); - self.cells[i].last_code = 0; - self.cells[i].last_result = Value::None; - if self.cells[i].listed { - self.cells[i].status = CellStatus::Never; - } - self.journal.retain(|j| j.cell != cell); - self.oracle_journal.retain(|j| j.cell != cell); - Ok(self.summary()) - } - - /// Clear displayed outputs and per-cell records; kernels and live state survive. - /// Export plan, explicit values, kernel values and journal as JSON-safe data. - pub fn export_snapshot(&mut self) -> Result { - let kernels = self.tracked("inspect",Value::Map(Vec::new()), |session| session.inspect_kernels())?; - let cells = self - .cells - .iter() - .map(|c| { - Value::Map(vec![ - ("name".into(), Value::Text(c.name.clone())), - ("lang".into(), Value::Text(c.lang.clone())), - ("kernel".into(), Value::Text(c.kernel.clone())), - ("source".into(), Value::Text(c.source.clone())), - ("source_hash".into(), Value::Text(c.source_hash.clone())), - ("stdin".into(), Value::Text(c.stdin.clone())), - ("status".into(), Value::Text(c.status.as_str().into())), - ("runs".into(), Value::Int(c.runs as i64)), - ("last_ok".into(), Value::Bool(c.last_ok)), - // Recording fields: replay_check compares a later run against these. - ("ok".into(), Value::Bool(c.last_ok)), - ("code".into(), Value::Int(c.last_code)), - ("stdout".into(), Value::Text(c.last_stdout.clone())), - ("result".into(), c.last_result.clone()), - ]) - }) - .collect(); - let journal = self.journal_json(); - Ok(Value::Map(vec![ - ("document_hash".into(), Value::Text(self.source_hash.clone())), - ("version".into(), Value::Int(5)), - ("initial_image".into(), self.initial_image.clone()), - ("action_count".into(), Value::Int(self.action_history.len() as i64)), - ("actions".into(), self.action_history_json()), - ("observation_journal".into(), Value::List(self.host.oracle_observations.clone())), - ("oracle_count".into(), Value::Int(self.complete_oracle_rows().len() as i64)), - ("path".into(), Value::Text(self.path.display().to_string())), - ("persistent".into(), Value::Bool(self.persistent)), - ("generation".into(), Value::Int(self.generation as i64)), - ("kernels".into(), kernels), - ("cells".into(), Value::List(cells)), - ("order".into(), Value::List( - self.order.iter().cloned().map(Value::Text).collect(), - )), - ("journal".into(), journal), - ("oracle_journal".into(), Value::List(self.complete_oracle_rows())), - ])) - } - - /// Import JSON-safe values from an exported snapshot. Source identity and - /// cell names must already match; no arbitrary objects are deserialized. - fn import_snapshot_inner(&mut self, snapshot: &Value) -> Result { - replay::validate_control(snapshot)?; - let Value::Map(fields) = snapshot else { - return Err("snapshot must be a map".into()); - }; - let field = |name: &str| { - fields - .iter() - .find(|(k, _)| k == name) - .map(|(_, v)| v.clone()) - }; - let Some(Value::List(kernels)) = field("kernels") else { - return Err("snapshot: missing kernels".into()); - }; - if field("document_hash") != Some(Value::Text(self.source_hash.clone())) { - return Err("snapshot: document hash differs".into()); - } - // Validate all crossing payloads before mutating any live foreign store. - for kernel in &kernels { - let Value::Map(kfields) = kernel else { return Err("snapshot: malformed kernel".into()) }; - let Some((_, Value::Text(name))) = kfields.iter().find(|(k, _)| k == "name") - else { return Err("snapshot: kernel name missing".into()) }; - if self.kernel(name).is_none() { return Err(format!("snapshot: unknown kernel `{name}`")); } - let Some((_, Value::List(values))) = kfields.iter().find(|(k, _)| k == "values") - else { return Err("snapshot: values missing".into()) }; - for item in values { - let Value::Map(vfields) = item else { return Err("snapshot: malformed value".into()) }; - let Some((_, Value::Text(name))) = vfields.iter().find(|(k, _)| k == "name") - else { return Err("snapshot: value name missing".into()) }; - if !foreign_session::valid_name(name) { return Err("snapshot: invalid value name".into()); } - let Some((_, value)) = vfields.iter().find(|(k, _)| k == "value") - else { return Err("snapshot: value missing".into()) }; - super::oracle::admit(value)?; - } - } - let mut restored = 0i64; - for kernel in kernels { - let Value::Map(kfields) = kernel else { continue }; - let get = |name: &str| { - kfields - .iter() - .find(|(k, _)| k == name) - .map(|(_, v)| v.clone()) - }; - let Some(Value::Text(name)) = get("name") else { continue }; - if self.kernel(&name).is_none() { - return Err(format!("snapshot: unknown kernel `{name}`")); - } - let Some(Value::List(values)) = get("values") else { continue }; - let id = self.ensure_kernel_session(&name)?; - for item in values { - let Value::Map(vfields) = item else { continue }; - let getv = |name: &str| { - vfields - .iter() - .find(|(k, _)| k == name) - .map(|(_, v)| v.clone()) - }; - let Some(Value::Text(vname)) = getv("name") else { continue }; - let Some(value) = getv("value") else { continue }; - foreign_session::set( - &mut self.host, - &Value::Handle(id.clone()), - &Value::Text(vname), - &value, - )?; - restored += 1; - } - } - if let Some(Value::List(cells)) = field("cells") { - for item in cells { - let Value::Map(cfields) = item else { continue }; - let getc = |name: &str| { - cfields - .iter() - .find(|(k, _)| k == name) - .map(|(_, v)| v.clone()) - }; - let Some(Value::Text(name)) = getc("name") else { continue }; - let Some(i) = self.cell_index(&name) else { continue }; - if let Some(Value::Text(status)) = getc("status") { - self.cells[i].status = match status.as_str() { - "clean" => CellStatus::Clean, - "error" => CellStatus::Error, - "dirty" => CellStatus::Dirty, - "stale" => CellStatus::Stale, - "unlisted" => CellStatus::Unlisted, - _ => CellStatus::Never, - }; - } - } - } - self.replay_fresh = false; - self.generation += 1; - Ok(Value::Int(restored)) - } - - /// Replay recorded cells in order, using the snapshot's per-cell stdin. - /// Re-runs only; does not compare against the recording. Prefer - /// [`Self::replay_check`] when equivalence against a recording matters. - fn replay_snapshot_inner(&mut self, snapshot: &Value) -> Result { - let Value::Map(fields) = snapshot else { - return Err("snapshot must be a map".into()); - }; - let cells = fields - .iter() - .find(|(k, _)| k == "cells") - .and_then(|(_, v)| match v { - Value::List(xs) => Some(xs.clone()), - _ => None, - }) - .ok_or_else(|| "snapshot: missing cells".to_string())?; - let mut records = Vec::new(); - for item in cells { - let Value::Map(cfields) = item else { continue }; - let getc = |name: &str| { - cfields - .iter() - .find(|(k, _)| k == name) - .map(|(_, v)| v.clone()) - }; - let Some(Value::Text(name)) = getc("name") else { continue }; - if self.cell_index(&name).is_none() { - continue; - } - if !self.replay_batch_can_continue() { break; } - let stdin = getc("stdin").and_then(|v| match v { - Value::Text(s) if !s.is_empty() => Some(s), - _ => None, - }); - let record = self.run_cell_with_stdin(&name, None, stdin.as_deref())?; - self.check_replay_batch_record(&record, self.seq.saturating_sub(1)); - let mut m = match record { - Value::Map(m) => m, - other => vec![("result".into(), other)], - }; - m.push(("cell".into(), Value::Text(name))); - records.push(Value::Map(m)); - } - Ok(Value::Map(vec![ - ("ok".into(), Value::Bool(true)), - ("replayed".into(), Value::Int(records.len() as i64)), - ("records".into(), Value::List(records)), - ])) - } - - /// Explicitly persist the last cell result through lib/writeback. - fn persist_cell_inner(&mut self, cell: &str, key: &str) -> Result { - let i = self - .cell_index(cell) - .ok_or_else(|| format!("unknown cell `{cell}`"))?; - let value = self.cells[i].last_result.clone(); - if self.cells[i].runs == 0 || !self.cells[i].last_ok { - return Err(format!("cell `{cell}` has no successful result to persist")); - } - let key = if key.is_empty() { cell } else { key }; - let line = self.cells[i].line_end.max(self.cells[i].line_start); - crate::host::writeback::record( - &mut self.host, - &value, - None, - Some(&Value::Text(key.to_string())), - Some(&Value::Int(line as i64)), - )?; - self.generation += 1; - Ok(Value::Bool(true)) - } - - fn clear_outputs_inner(&mut self) -> Value { - for cell in &mut self.cells { - cell.runs = 0; - cell.last_ms = 0; - cell.last_ok = false; - cell.last_error.clear(); - cell.last_stdout.clear(); - cell.last_code = 0; - cell.last_result = Value::None; - if cell.listed { - cell.status = CellStatus::Never; - } - } - self.journal.clear(); - self.oracle_journal.clear(); - self.cursor = 0; - self.summary() - } - - pub fn journal_json(&self) -> Value { - Value::List( - self.journal - .iter() - .map(|j| { - Value::Map(vec![ - ("seq".into(), Value::Int(j.seq as i64)), - ("cell".into(), Value::Text(j.cell.clone())), - ("kernel".into(), Value::Text(j.kernel.clone())), - ("lang".into(), Value::Text(j.lang.clone())), - ("ok".into(), Value::Bool(j.ok)), - ("code".into(), Value::Int(j.code)), - ("ms".into(), Value::Int(j.ms as i64)), - ("timestamp_ms".into(), Value::Int(j.timestamp_ms)), - ("error".into(), Value::Text(j.error.clone())), - ]) - }) - .collect(), - ) - } - - pub fn oracle_journal_json(&self) -> Value { - Value::List(self.oracle_journal.iter().map(OracleRecord::to_value).collect()) - } - - fn close_inner(&mut self) { - self.replay_fresh = false; - let ids: Vec = self.kernel_sessions.values().cloned().collect(); - for id in ids { - let _ = foreign_session::close(&mut self.host, &Value::Handle(id)); - } - self.kernel_sessions.clear(); - } -} - -fn resolve_kernel( - kernels: &mut Vec, - map: &mut HashMap, - name: &str, -) -> Result { - if let Some(k) = map.get(name) { - return Ok(k.clone()); - } - if registry::preset_spec(name).is_some() { - let lang = registry::canonical(name); - let decl = KernelDecl { - name: lang.clone(), - lang, - cmd: None, - implicit: true, - }; - map.insert(decl.name.clone(), decl.clone()); - kernels.push(decl.clone()); - return Ok(decl); - } - Err(format!( - "foreign.session: kernel `{name}` is not declared in kernels" - )) -} - -fn ensure_default_kernel( - kernels: &mut Vec, - map: &mut HashMap, - lang: &str, -) -> String { - let lang = registry::canonical(lang); - let name = format!("default:{lang}"); - if !map.contains_key(&name) { - let decl = KernelDecl { - name: name.clone(), - lang, - cmd: None, - implicit: true, - }; - map.insert(name.clone(), decl.clone()); - kernels.push(decl); - } - name -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn table_rows_reads_row_records_and_columns() { - let row_table = Value::List(vec![Value::Map(vec![ - ("@".into(), Value::Text("1".into())), - ("名称".into(), Value::Text("分析".into())), - ("语言".into(), Value::Text("python".into())), - ])]); - let rows = table_rows(&row_table).unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(col_text(&rows[0], &["名称"]).as_deref(), Some("分析")); - - let column_table = Value::Map(vec![ - ("名称".into(), Value::List(vec![Value::Text("分析".into())])), - ("语言".into(), Value::List(vec![Value::Text("python".into())])), - ]); - let rows = table_rows(&column_table).unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(col_text(&rows[0], &["语言"]).as_deref(), Some("python")); - } - - #[test] - fn plan_uses_evaluated_bindings() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-plan-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"--- -title: evaluated plan test -import: - foreign: lib/foreign.mq.md ---- - -# main - -`lang` = python - -`分析内核` = - -| @ | 名称 | 语言 | -|---|------|------| -| 1 | 分析 | `lang` | - -`分析单元` = - -| @ | 单元 | 内核 | -|---|------|------| -| 1 | 单元 | 分析 | - -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` - -`单元` = -```python -print(1) -``` -"#; - std::fs::write(&path, source).unwrap(); - let s = DocumentSession::open(&path, &root).unwrap(); - assert_eq!(s.cells.len(), 1); - assert_eq!(s.cells[0].kernel, "分析"); - assert_eq!(s.kernels[0].lang, "python"); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn view_open_accepts_a_document_without_cells() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-empty-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - std::fs::write(&path, "# main\n\n> print text=hello\n").unwrap(); - let s = DocumentSession::open(&path, &root).unwrap(); - assert!(s.cells.is_empty()); - let _ = std::fs::remove_file(&path); - } - - fn node_available() -> bool { - std::process::Command::new("node") - .args(["-e", "process.exit(0)"]) - .output() - .map(|o| o.status.success()) - .unwrap_or(false) - } - - fn field(record: &Value, key: &str) -> Option { - match record { - Value::Map(entries) => entries - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v.clone()), - _ => None, - } - } - - #[test] - fn shared_state_and_isolation() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/notebook-test-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"--- -title: shared state test -import: - foreign: lib/foreign.mq.md ---- - -# main - -`内核表` = - -| 名称 | 语言 | 命令 | 说明 | -|------|------|------|------| -| 分析 | node | | shared | -| 绘图 | node | | isolated | - -`会话表` = - -| 单元 | 内核 | 说明 | -|------|------|------| -| 设置 | 分析 | write | -| 读取 | 分析 | read | -| 隔离 | 绘图 | isolated | - -`会话` = > foreign.session kernels=`内核表` cells=`会话表` - -`设置` = -```node -let shared = 41; -``` - -`读取` = -```node -console.log(shared + 1); -``` - -`隔离` = -```node -console.log(typeof shared === "undefined" ? "isolated" : "leaked"); -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - assert_eq!( - s.order, - vec!["设置".to_string(), "读取".to_string(), "隔离".to_string()] - ); - let r = s.run_cell("设置", None).unwrap(); - assert_eq!(field(&r, "ok"), Some(Value::Bool(true))); - let r = s.run_cell("读取", None).unwrap(); - assert_eq!( - field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("42\n".to_string()) - ); - let r = s.run_cell("隔离", None).unwrap(); - assert_eq!( - field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("isolated\n".to_string()) - ); - s.restart_all().unwrap(); - let r = s.run_cell("读取", None).unwrap(); - assert_eq!(field(&r, "ok"), Some(Value::Bool(false))); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn magic_table_names_without_session_are_ignored() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-stateless-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"# main - -`内核表` = - -| 名称 | 语言 | -|------|------| -| 分析 | node | - -`会话表` = - -| 单元 | 内核 | -|------|------| -| a | 分析 | - -`a` = -```node -console.log("stateless"); -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - assert!(!s.persistent); - assert!(s.kernels.is_empty(), "magic tables must not create kernels"); - assert_eq!(s.order, vec!["a".to_string()]); - assert_eq!(s.cells[0].kernel, "one-shot"); - let r = s.run_cell("a", None).unwrap(); - assert_eq!( - field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("stateless\n".to_string()) - ); - assert_eq!(s.cells[0].status, CellStatus::Clean); - s.clear_outputs(); - assert_eq!(s.cells[0].status, CellStatus::Never); - assert!(s.journal.is_empty()); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn clear_outputs_keeps_persistent_kernel_state() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-clear-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"--- -title: clear outputs -import: - foreign: lib/foreign.mq.md ---- - -# main - -`内核` = - -| 名称 | 语言 | -|------|------| -| 分析 | node | - -`单元` = - -| 单元 | 内核 | -|------|------| -| a | 分析 | - -`会话` = > foreign.session kernels=`内核` cells=`单元` - -`a` = -```node -globalThis.kept = (globalThis.kept || 0) + 1; -console.log(globalThis.kept); -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let r = s.run_cell("a", None).unwrap(); - assert_eq!( - field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("1\n".to_string()) - ); - s.clear_outputs(); - assert_eq!(s.cells[0].status, CellStatus::Never); - assert!(s.journal.is_empty()); - let r = s.run_cell("a", None).unwrap(); - assert_eq!( - field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("2\n".to_string()), - "clear outputs must not restart the kernel" - ); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn snapshot_export_import_restores_values() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.set_value("分析", "rate", Value::Int(42)).unwrap(); - let snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - let mut wrong_source = snap.clone(); - replace_field(&mut wrong_source, "document_hash", Value::Text("different-document".into())); - assert!(b.import_snapshot(&wrong_source).unwrap_err().contains("hash")); - assert!(b.kernel_sessions.is_empty()); - let restored = b.import_snapshot(&snap).unwrap(); - assert!(matches!(restored, Value::Int(n) if n > 0)); - let rate = b.pull_value("分析", "rate").unwrap(); - assert_eq!(rate, Value::Int(42)); - b.close(); - } - - #[test] - fn nested_plan_is_rejected_at_open() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-nested-plan-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = "# main\n\n## view\n\n`会话` = > foreign.session\n"; - std::fs::write(&path, source).unwrap(); - let err = match DocumentSession::open(&path, &root) { - Ok(_) => panic!("nested plan should be rejected"), - Err(e) => e, - }; - assert!(err.contains("top-level"), "{err}"); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn nested_plan_helper_detects_child_binding() { - let src = "# main\n\n## view\n\n`会话` = > foreign.session\n"; - let module = crate::parse::parse_source(src).unwrap(); - assert!(has_nested_plan(&module, "main")); - } - - #[test] - fn runtime_plan_add_remove_and_generation() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let before = s.generation; - s.add_cell("extra", "node", "console.log('extra');", "分析") - .unwrap(); - assert!(s.generation > before); - assert!(s.cells.iter().any(|c| c.name == "extra")); - s.assign_kernel("extra", "分析").unwrap(); - s.remove_cell("extra").unwrap(); - assert!(!s.cells.iter().any(|c| c.name == "extra")); - assert!(s.generation > before + 1); - s.close(); - } - - #[test] - fn persist_cell_writes_a_keyed_slot() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-persist-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"# main - -`a` = -```python -print(950) -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - s.run_cell("a", None).unwrap(); - s.persist_cell("a", "total").unwrap(); - let text = std::fs::read_to_string(&path).unwrap(); - assert!(text.contains("marqdo-out total"), "{text}"); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn plan_inputs_feed_each_cell() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-plan-input-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"--- -title: plan inputs test -import: - foreign: lib/foreign.mq.md ---- - -# main - -`内核` = -| 名称 | 语言 | -|------|------| -| py | python | - -`单元` = -| 单元 | 内核 | -|------|------| -| a | py | - -`输入` = -| 单元 | stdin | -|------|-------| -| a | hello plan | - -`会话` = > foreign.session kernels=`内核` cells=`单元` inputs=`输入` - -`a` = -```python -import sys -print(sys.stdin.read().strip()) -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let summary = s.run_all_with_stdin(false, None).unwrap(); - let records = match &summary { - Value::Map(entries) => entries.iter().find(|(k, _)| k == "records").map(|(_, v)| v.clone()), - _ => None, - }; - let Some(Value::List(records)) = records else { panic!("no records") }; - assert_eq!( - field(&records[0], "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("hello plan\n".to_string()) - ); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn persistent_node_cell_accepts_raw_stdin() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-node-stdin-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"--- -title: persistent node stdin test -import: - foreign: lib/foreign.mq.md ---- - -# main - -`内核` = -| 名称 | 语言 | -|------|------| -| js | node | - -`单元` = -| 单元 | 内核 | -|------|------| -| a | js | - -`会话` = > foreign.session kernels=`内核` cells=`单元` - -`a` = -```node -(async () => { - await new Promise((resolve) => { - let input = ""; - process.stdin.on("data", (chunk) => { input += chunk; }); - process.stdin.on("end", () => { console.log(input.trim()); resolve(); }); - }); -})(); -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let record = s - .run_cell_with_stdin("a", None, Some("hello node")) - .unwrap(); - assert_eq!( - field(&record, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("hello node\n".to_string()) - ); - s.run_cell_with_stdin("a", None, Some("second input 中文")).unwrap(); - let snapshot = s.export_snapshot().unwrap(); - s.close(); - let mut fresh = DocumentSession::open(&path, &root).unwrap(); - let replay = fresh.replay_check(&snapshot).unwrap(); - assert_eq!(field(&replay, "ok"), Some(Value::Bool(true))); - assert_eq!(field(&replay, "matched"), Some(Value::Int(2))); - fresh.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn persistent_python_cell_accepts_raw_stdin() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-persistent-stdin-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"--- -title: persistent stdin test -import: - foreign: lib/foreign.mq.md ---- - -# main - -`内核` = -| 名称 | 语言 | -|------|------| -| py | python | - -`单元` = -| 单元 | 内核 | -|------|------| -| a | py | - -`会话` = > foreign.session kernels=`内核` cells=`单元` - -`a` = -```python -import sys -print(sys.stdin.read().strip()) -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let record = s - .run_cell_with_stdin("a", None, Some("hello persistent")) - .unwrap(); - assert_eq!( - field(&record, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("hello persistent\n".to_string()) - ); - s.run_cell_with_stdin("a", None, Some("second input 中文")).unwrap(); - let snapshot = s.export_snapshot().unwrap(); - s.close(); - let mut fresh = DocumentSession::open(&path, &root).unwrap(); - let replay = fresh.replay_check(&snapshot).unwrap(); - assert_eq!(field(&replay, "ok"), Some(Value::Bool(true))); - assert_eq!(field(&replay, "matched"), Some(Value::Int(2))); - fresh.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn stateless_cell_accepts_stdin() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-stdin-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"# main - -`a` = -```node -const fs = require("fs"); -const input = fs.readFileSync(0, "utf8").trim(); -console.log("got:" + input); -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let record = s - .run_cell_with_stdin("a", None, Some("hello stdin")) - .unwrap(); - assert_eq!( - field(&record, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), - Some("got:hello stdin\n".to_string()) - ); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn run_all_continues_after_a_cell_error() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/view-run-all-error-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let source = r#"# main - -`a` = -```node -throw new Error("boom"); -``` - -`b` = -```node -console.log("after error"); -``` -"#; - std::fs::write(&path, source).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let summary = s.run_all(false).unwrap(); - let records = match &summary { - Value::Map(entries) => entries.iter().find(|(k, _)| k == "records").map(|(_, v)| v.clone()), - _ => None, - }; - let Some(Value::List(records)) = records else { panic!("no records") }; - assert_eq!(records.len(), 2); - assert_eq!(field(&records[0], "ok"), Some(Value::Bool(false))); - assert_eq!(field(&records[1], "ok"), Some(Value::Bool(true))); - assert!(field(&records[1], "stdout") - .and_then(|v| v.reveal_text().map(|s| s.to_string())) - .unwrap_or_default() - .contains("after error")); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn reload_marks_changed_cell_dirty() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/notebook-reload-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - let src = "# main\n\n`a` =\n```node\nconsole.log(1);\n```\n"; - std::fs::write(&path, src).unwrap(); - let mut s = DocumentSession::open(&path, &root).unwrap(); - let r = s.run_cell("a", None).unwrap(); - assert_eq!(field(&r, "ok"), Some(Value::Bool(true))); - assert_eq!(s.cells[0].status, CellStatus::Clean); - let before = s.oracle_journal_json(); - let src2 = "# main\n\n`a` =\n```node\nconsole.log(2);\n```\n"; - std::fs::write(&path, src2).unwrap(); - s.reload(&root).unwrap(); - assert_eq!(s.cells[0].status, CellStatus::Dirty); - assert!(s.cells[0].source.contains("console.log(2)")); - assert_eq!(s.oracle_journal_json(), before, "reload must retain observations of the old source"); - s.close(); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn oracle_journal_records_stdout_separate_from_execution_journal() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut s = DocumentSession::open(&path, &root).unwrap(); - s.run_all(true).unwrap(); - assert!(!s.journal.is_empty()); - assert_eq!(s.oracle_journal.len(), s.journal.len()); - let read = s - .oracle_journal - .iter() - .find(|j| j.cell == "读取") - .expect("oracle entry for 读取"); - assert!(read.ok); - assert!( - read.stdout.contains('4') || read.stdout.contains("42"), - "oracle must capture stdout, got {:?}", - read.stdout - ); - assert!(!read.source_hash.is_empty()); - // Execution journal must not pretend to be the oracle (no stdout field). - let exec = s.journal.iter().find(|j| j.cell == "读取").unwrap(); - assert_eq!(exec.ok, read.ok); - s.close(); - } - - #[test] - fn replay_check_matches_exported_recording() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.run_all(true).unwrap(); - let snap = a.export_snapshot().unwrap(); - a.close(); - - let mut b = DocumentSession::open(&path, &root).unwrap(); - let check = b.replay_check(&snap).unwrap(); - assert_eq!(field(&check, "ok"), Some(Value::Bool(true))); - assert_eq!(field(&check, "mismatched"), Some(Value::Int(0))); - let matched = field(&check, "matched").and_then(|v| match v { - Value::Int(n) => Some(n), - _ => None, - }); - assert!(matched.unwrap_or(0) >= 1, "expected at least one compared cell"); - b.close(); - } - - #[test] - fn replay_check_localizes_stdout_mismatch() { - if !node_available() { - return; - } - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.run_all(true).unwrap(); - let mut snap = a.export_snapshot().unwrap(); - a.close(); - - // Tamper with the recording for cell 读取. - if let Value::Map(ref mut fields) = snap { - if let Some((_, Value::List(cells))) = - fields.iter_mut().find(|(k, _)| k == "oracle_journal") - { - for cell in cells.iter_mut() { - let Value::Map(cfields) = cell else { continue }; - let name = cfields - .iter() - .find(|(k, _)| k == "cell") - .and_then(|(_, v)| v.reveal_text().map(|s| s.to_string())); - if name.as_deref() == Some("读取") { - if let Some((_, v)) = cfields.iter_mut().find(|(k, _)| k == "stdout") { - *v = Value::Text("wrong-recording\n".into()); - } - } - } - } - } - - replay::sync_expected_cells(&mut snap).unwrap(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - let check = b.replay_check(&snap).unwrap(); - assert_eq!(field(&check, "ok"), Some(Value::Bool(false))); - assert_eq!(field(&check, "mismatched"), Some(Value::Int(1))); - assert_eq!(field(&check, "skipped"), Some(Value::Int(1))); - let Some(Value::List(checks)) = field(&check, "checks") else { - panic!("missing checks"); - }; - let bad = checks.iter().find(|c| { - field(c, "cell") - .and_then(|v| v.reveal_text().map(|s| s.to_string())) - .as_deref() - == Some("读取") - }); - let Some(bad) = bad else { panic!("missing 读取 check") }; - assert_eq!(field(bad, "match"), Some(Value::Bool(false))); - let diff = field(bad, "diff") - .and_then(|v| v.reveal_text().map(|s| s.to_string())) - .unwrap_or_default(); - assert!(diff.contains("stdout"), "diff should localize to stdout: {diff}"); - b.close(); - } - fn snapshot_list_mut<'a>(snap: &'a mut Value, key: &str) -> &'a mut Vec { - let Value::Map(m) = snap else { panic!("map") }; - let (_, Value::List(xs)) = m.iter_mut().find(|(k, _)| k == key).unwrap() - else { panic!("list") }; - xs - } - - fn replace_field(v: &mut Value, key: &str, value: Value) { - let Value::Map(m) = v else { panic!("map") }; - m.iter_mut().find(|(k, _)| k == key).unwrap().1 = value; - } - - #[test] - fn replay_check_rejects_incomplete_recordings_before_execution() { - assert!(node_available(), "replay experiment requires node"); - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.run_all(true).unwrap(); - let original = a.export_snapshot().unwrap(); - a.close(); - let cases = ["empty", "truncate", "insert", "duplicate", "reorder", "unknown", - "missing_cell", "non_map", "missing_outcome", "wrong_bool", "wrong_code", - "wrong_stdout", "missing_result", "source", "routing", "plan", "version", - "missing_oracle", "duplicate_field", "stdin_type"]; - for case in cases { - let mut snap = original.clone(); - match case { - "empty" => snapshot_list_mut(&mut snap, "oracle_journal").clear(), - "truncate" => { snapshot_list_mut(&mut snap, "oracle_journal").pop(); } - "insert" | "duplicate" => { - let xs = snapshot_list_mut(&mut snap, "oracle_journal"); - xs.push(xs[0].clone()); - } - "reorder" => snapshot_list_mut(&mut snap, "oracle_journal").swap(0, 1), - "unknown" => replace_field(&mut snapshot_list_mut(&mut snap, "oracle_journal")[0], "cell", Value::Text("unknown".into())), - "missing_cell" => { snapshot_list_mut(&mut snap, "cells").pop(); } - "non_map" => snapshot_list_mut(&mut snap, "oracle_journal")[0] = Value::None, - "missing_outcome" | "missing_result" => { - let Value::Map(m) = &mut snapshot_list_mut(&mut snap, "oracle_journal")[0] else { panic!() }; - m.retain(|(k, _)| k != if case == "missing_result" { "result" } else { "ok" }); - } - "wrong_bool" | "wrong_code" | "wrong_stdout" | "stdin_type" => { - let key = match case { "wrong_bool" => "ok", "wrong_code" => "code", "wrong_stdout" => "stdout", _ => "stdin" }; - replace_field(&mut snapshot_list_mut(&mut snap, "oracle_journal")[0], key, Value::None); - } - "source" => replace_field(&mut snapshot_list_mut(&mut snap, "cells")[0], "source", Value::Text("console.log(42)".into())), - "routing" => replace_field(&mut snapshot_list_mut(&mut snap, "oracle_journal")[0], "kernel", Value::Text("绘图".into())), - "plan" => snapshot_list_mut(&mut snap, "order").swap(0, 1), - "version" => replace_field(&mut snap, "version", Value::Int(1)), - "missing_oracle" => { let Value::Map(m) = &mut snap else { panic!() }; m.retain(|(k, _)| k != "oracle_journal"); } - "duplicate_field" => { let Value::Map(m) = &mut snapshot_list_mut(&mut snap, "oracle_journal")[0] else { panic!() }; m.push(m[0].clone()); } - _ => unreachable!(), - } - let mut b = DocumentSession::open(&path, &root).unwrap(); - let result = b.replay_check(&snap); - assert!(result.is_err(), "{case}: {result:?}"); - assert!(b.oracle_journal.is_empty(), "{case}: executed before validation"); - assert!(b.kernel_sessions.is_empty(), "{case}: started a kernel before validation"); - println!("E1 {case}: rejected before execution: {}", result.unwrap_err()); - b.close(); - } - } - - #[test] - fn replay_check_uses_oracle_not_cell_summary_or_execution_journal() { - assert!(node_available()); - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.run_all(true).unwrap(); - // Repeat the read: a per-cell summary cannot represent this history. - a.run_cell("读取", None).unwrap(); - let mut snap = a.export_snapshot().unwrap(); - a.close(); - snapshot_list_mut(&mut snap, "journal").clear(); - for c in snapshot_list_mut(&mut snap, "cells") { - replace_field(c, "stdout", Value::Text("irrelevant-summary".into())); - } - let mut b = DocumentSession::open(&path, &root).unwrap(); - let check = b.replay_check(&snap).unwrap(); - assert_eq!(field(&check, "ok"), Some(Value::Bool(true))); - assert_eq!(field(&check, "matched"), Some(Value::Int(4))); - assert_eq!(field(&check, "skipped"), Some(Value::Int(0))); - assert!(b.replay_check(&snap).unwrap_err().contains("fresh")); - b.close(); - } - - #[test] - fn replay_check_accepts_declared_initial_values_but_rejects_external_changes() { - assert!(node_available()); - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!("target/replay-initial-{}.mq.md", std::process::id())); - let source = std::fs::read_to_string(root.join("tests/notebook/shared.mq.md")).unwrap() - .replace("`会话` = > foreign.session kernels=`内核表` cells=`会话表`", - "`初始` =\n\n| 内核 | 名称 | 值 |\n|---|---|---|\n| 分析 | seed | 41 |\n\n`会话` = > foreign.session kernels=`内核表` cells=`会话表` values=`初始`"); - std::fs::write(&path, source).unwrap(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - assert!(!a.kernel_sessions.is_empty(), "fixture must initialize a live kernel"); - a.run_all(false).unwrap(); - let snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - let check = b.replay_check(&snap).unwrap(); - assert_eq!(field(&check, "ok"), Some(Value::Bool(true))); - b.close(); - let mut warm = DocumentSession::open(&path, &root).unwrap(); - warm.set_value("分析", "seed", Value::Int(99)).unwrap(); - assert!(warm.replay_check(&snap).unwrap_err().contains("fresh")); - warm.close(); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn snapshot_introspection_does_not_pollute_document_observations() { - assert!(node_available()); - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join("tests/notebook/shared.mq.md"); - let mut s = DocumentSession::open(&path, &root).unwrap(); - s.run_all(false).unwrap(); - let before = s.host.oracle_observations.clone(); - assert_eq!(before.len(), 3); - s.export_snapshot().unwrap(); - s.export_snapshot().unwrap(); - assert_eq!(s.host.oracle_observations, before, "snapshot get/names are metadata, not document actions"); - // The cell trace projects to exactly the same language observations. - let projected: Vec = s.oracle_journal.iter().enumerate().map(|(i,r)| - Value::Map(vec![("index".into(), Value::Int(i as i64)), - ("channel".into(), Value::Text("eval".into())), ("value".into(), r.value.clone())])).collect(); - assert_eq!(before, projected); - s.pull_value("分析", "shared").unwrap(); - assert_eq!(s.host.oracle_observations.len(), before.len() + 1, "explicit user get must be observed"); - s.close(); - } - - #[test] - fn replay_check_compares_failed_cell_diagnostics() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!("target/replay-failure-{}.mq.md", std::process::id())); - let source = "# main\n\n`a` =\n```python\nraise ValueError('ordinary error')\n```\n"; - std::fs::write(&path, source).unwrap(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - let record = a.run_cell("a", None).unwrap(); - assert_eq!(field(&record, "ok"), Some(Value::Bool(false))); - let mut snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - let initial_check = b.replay_check(&snap).unwrap(); - assert_eq!(field(&initial_check, "ok"), Some(Value::Bool(true)), "{initial_check:?}"); - b.close(); - let rows = snapshot_list_mut(&mut snap, "oracle_journal"); - let Value::Map(fields) = &mut rows[0] else { panic!() }; - let (_, value) = fields.iter_mut().find(|(k,_)| k == "value").unwrap(); - replace_field(value, "error", Value::Text("different failure".into())); - replay::sync_expected_cells(&mut snap).unwrap(); - let mut c = DocumentSession::open(&path, &root).unwrap(); - let check = c.replay_check(&snap).unwrap(); - assert_eq!(field(&check, "ok"), Some(Value::Bool(false))); - let Some(Value::List(checks)) = field(&check, "checks") else { panic!() }; - assert!(field(&checks[0], "diff").unwrap().as_display().contains("value")); - c.close(); - std::fs::remove_file(path).unwrap(); - } - -} diff --git a/src/host/foreign_doc/control.rs b/src/host/foreign_doc/control.rs deleted file mode 100755 index 2ac8c77..0000000 --- a/src/host/foreign_doc/control.rs +++ /dev/null @@ -1,174 +0,0 @@ -//! Concurrent control inputs are scoped to a single recorded document action. -//! Replay supplies their elapsed-time inputs, reobserves acceptance, and stops -//! on divergence; elapsed wall time is not a deterministic foreign-state oracle. -use crate::host::foreign_session::InterruptHandle; -use crate::value::Value; -use std::collections::BTreeMap; -use std::sync::{Arc, Condvar, Mutex}; -use std::thread::JoinHandle; -use std::time::{Duration, Instant}; - -#[derive(Clone, Debug, PartialEq)] -pub(super) struct ControlEvent { - pub after_us: u64, - pub results: Vec<(String, Result)>, -} -impl ControlEvent { - pub fn value(&self) -> Value { - Value::Map(vec![ - ("after_us".into(), Value::Int(self.after_us as i64)), - ( - "results".into(), - Value::List( - self.results - .iter() - .map(|(name, result)| { - Value::Map(vec![ - ("kernel".into(), Value::Text(name.clone())), - ("accepted".into(), Value::Bool(result.is_ok())), - ("active".into(), Value::Bool(matches!(result, Ok(true)))), - ( - "error".into(), - Value::Text(result.as_ref().err().cloned().unwrap_or_default()), - ), - ]) - }) - .collect(), - ), - ), - ]) - } -} -#[derive(Default, Debug)] -struct State { - kernels: BTreeMap, - generation: u64, - action: Option<(Instant, Vec)>, -} -#[derive(Default, Debug)] -struct Shared { - state: Mutex, - changed: Condvar, -} -#[derive(Clone, Default, Debug)] -pub struct DocumentControl(Arc); - -impl DocumentControl { - pub(super) fn cancelled(&self) -> bool { - self.0 - .state - .lock() - .unwrap() - .action - .as_ref() - .is_some_and(|(_, events)| !events.is_empty()) - } - pub(super) fn register(&self, kernel: &str, handle: InterruptHandle) { - self.0 - .state - .lock() - .unwrap() - .kernels - .insert(kernel.into(), handle); - } - pub(super) fn begin(&self, plan: Vec) -> Option> { - let generation = { - let mut state = self.0.state.lock().unwrap(); - state.generation += 1; - state.action = Some((Instant::now(), Vec::new())); - state.generation - }; - if plan.is_empty() { - return None; - } - let controller = self.clone(); - Some(std::thread::spawn(move || { - for event in plan { - let mut state = controller.0.state.lock().unwrap(); - loop { - if state.generation != generation || state.action.is_none() { - return; - } - let elapsed = state.action.as_ref().unwrap().0.elapsed(); - let remaining = Duration::from_micros(event.after_us).saturating_sub(elapsed); - if remaining.is_zero() { - break; - } - state = controller - .0 - .changed - .wait_timeout(state, remaining.min(Duration::from_millis(200))) - .unwrap() - .0; - } - // Keep the action-generation check and signal under one lock. - let _ = Self::request_locked(&mut state, Some(event.after_us)); - } - })) - } - pub(super) fn finish(&self, scheduler: Option>) -> Vec { - let events = self - .0 - .state - .lock() - .unwrap() - .action - .take() - .map(|(_, events)| events) - .unwrap_or_default(); - self.0.changed.notify_all(); - if let Some(scheduler) = scheduler { - let _ = scheduler.join(); - } - events - } - pub fn interrupt(&self) -> Result { - let mut state = self - .0 - .state - .lock() - .map_err(|_| "document control lock poisoned")?; - Self::request_locked(&mut state, None).map(|event| event.value()) - } - fn request_locked( - state: &mut State, - scheduled_us: Option, - ) -> Result { - let start = state - .action - .as_ref() - .ok_or("no document action in flight")? - .0; - let after_us = scheduled_us - .unwrap_or_else(|| start.elapsed().as_micros().min(i64::MAX as u128) as u64); - let results = state - .kernels - .iter() - .filter(|(_, handle)| handle.is_live()) - .map(|(name, handle)| (name.clone(), handle.request())) - .collect(); - let event = ControlEvent { after_us, results }; - state.action.as_mut().unwrap().1.push(event.clone()); - Ok(event) - } -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn completed_action_cancels_pending_scheduler_before_next_generation() { - let controller = DocumentControl::default(); - let scheduler = controller.begin(vec![ControlEvent { - after_us: 60_000_000, - results: Vec::new(), - }]); - let start = Instant::now(); - assert!(controller.finish(scheduler).is_empty()); - assert!(start.elapsed() < Duration::from_secs(1)); - assert!(controller.interrupt().is_err()); - let next = controller.begin(Vec::new()); - assert!(!controller.cancelled()); - assert!(controller.finish(next).is_empty()); - } -} diff --git a/src/host/foreign_doc/packing.rs b/src/host/foreign_doc/packing.rs deleted file mode 100755 index ff615f6..0000000 --- a/src/host/foreign_doc/packing.rs +++ /dev/null @@ -1,399 +0,0 @@ -//! Lossless, typed, bottom-up sharing for complete history snapshots. -//! References always point backwards. Expansion costs and depth are checked -//! before building the expanded value, so a small DAG cannot expand unboundedly. -use crate::host::{json::value_to_json, oracle::admit}; -use crate::value::Value; -use sha2::{Digest, Sha256}; -use std::collections::{HashMap, HashSet}; - -const FORMAT: &str = "marqdo.history.dag"; -const MAX_NODES: usize = 1_000_000; -const MAX_VALUES: usize = 8_000_000; -const MAX_BYTES: usize = 512 * 1024 * 1024; -const MAX_DEPTH: usize = 128; - -fn text(s: &str) -> Value { - Value::Text(s.into()) -} -fn list(v: &Value) -> Result<&[Value], String> { - if let Value::List(v) = v { - Ok(v) - } else { - Err("snapshot DAG: expected list".into()) - } -} -fn string(v: &Value) -> Result<&str, String> { - if let Value::Text(v) = v { - Ok(v) - } else { - Err("snapshot DAG: expected text".into()) - } -} -fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> { - if let Value::Map(fields) = v { - fields - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v) - .ok_or_else(|| format!("snapshot DAG: missing {key}")) - } else { - Err("snapshot DAG: expected object".into()) - } -} -fn wire(v: &Value) -> Result { - serde_json::to_string(&value_to_json(v)?).map_err(|e| e.to_string()) -} -fn checksum(root: &Value, nodes: &Value) -> Result { - Ok(format!( - "{:x}", - Sha256::digest(wire(&Value::List(vec![root.clone(), nodes.clone()]))?.as_bytes()) - )) -} -pub fn is_packed(v: &Value) -> bool { - field(v, "format").ok() == Some(&text(FORMAT)) -} - -pub fn pack(snapshot: &Value) -> Result { - fn intern( - v: &Value, - nodes: &mut Vec, - seen: &mut HashMap, - depth: usize, - ) -> Result { - if depth > MAX_DEPTH { - return Err("snapshot DAG: depth budget exceeded".into()); - } - let row = match v { - Value::None => vec![text("null")], - Value::Bool(v) => vec![text("bool"), Value::Bool(*v)], - Value::Int(v) => vec![text("int"), text(&v.to_string())], - Value::Num(v) => vec![text("float"), text(&format!("{:016x}", v.to_bits()))], - Value::Text(v) => vec![text("text"), text(v)], - Value::List(values) => { - let refs = values - .iter() - .map(|v| intern(v, nodes, seen, depth + 1).map(|i| Value::Int(i as i64))) - .collect::, _>>()?; - vec![text("list"), Value::List(refs)] - } - Value::Map(fields) => { - let refs = fields - .iter() - .map(|(k, v)| { - intern(v, nodes, seen, depth + 1) - .map(|i| Value::List(vec![text(k), Value::Int(i as i64)])) - }) - .collect::, _>>()?; - vec![text("map"), Value::List(refs)] - } - _ => return Err("snapshot DAG: value outside V_safe".into()), - }; - let row = Value::List(row); - let key = wire(&row)?; - if let Some(index) = seen.get(&key) { - return Ok(*index); - } - if nodes.len() >= MAX_NODES { - return Err("snapshot DAG: node budget exceeded".into()); - } - let index = nodes.len(); - nodes.push(row); - seen.insert(key, index); - Ok(index) - } - let mut nodes = Vec::new(); - let root = intern(snapshot, &mut nodes, &mut HashMap::new(), 0)?; - admit(snapshot)?; - let nodes = Value::List(nodes); - let root = Value::Int(root as i64); - let hash = checksum(&root, &nodes)?; - let envelope = Value::Map(vec![ - ("format".into(), text(FORMAT)), - ("version".into(), Value::Int(1)), - ("root".into(), root), - ("nodes".into(), nodes), - ("sha256".into(), text(&hash)), - ]); - // Apply exactly the decoder's resource limits to locally produced envelopes. - validate(&envelope)?; - Ok(envelope) -} - -enum Node { - Atom(Value), - List(Vec), - Map(Vec<(String, usize)>), -} -impl Node { - fn refs(&self) -> Vec { - match self { - Self::Atom(_) => Vec::new(), - Self::List(v) => v.clone(), - Self::Map(v) => v.iter().map(|(_, i)| *i).collect(), - } - } -} -fn index(v: &Value, before: usize) -> Result { - match v { - Value::Int(i) if *i >= 0 && (*i as u64) < before as u64 => Ok(*i as usize), - _ => Err("snapshot DAG: forward/cyclic/out-of-range reference".into()), - } -} -fn validate(envelope: &Value) -> Result<(Vec, usize), String> { - let Value::Map(fields) = envelope else { - return Err("snapshot DAG: expected envelope".into()); - }; - let names: HashSet<_> = fields.iter().map(|(k, _)| k.as_str()).collect(); - if fields.len() != 5 - || names != HashSet::from(["format", "version", "root", "nodes", "sha256"]) - || string(field(envelope, "format")?)? != FORMAT - || field(envelope, "version")? != &Value::Int(1) - { - return Err("snapshot DAG: invalid envelope schema".into()); - } - let rows = list(field(envelope, "nodes")?)?; - if rows.is_empty() || rows.len() > MAX_NODES { - return Err("snapshot DAG: node budget exceeded".into()); - } - let root = index(field(envelope, "root")?, rows.len())?; - if root + 1 != rows.len() { - return Err("snapshot DAG: root must be last".into()); - } - let expected = string(field(envelope, "sha256")?)?; - if expected != checksum(field(envelope, "root")?, field(envelope, "nodes")?)? { - return Err("snapshot DAG: checksum differs".into()); - } - let mut nodes = Vec::new(); - let mut costs: Vec<(usize, usize, usize)> = Vec::new(); - let mut unique = HashSet::new(); - for (i, raw) in rows.iter().enumerate() { - if !unique.insert(wire(raw)?) { - return Err("snapshot DAG: duplicate dictionary node".into()); - } - let row = list(raw)?; - let tag = string(row.first().ok_or("snapshot DAG: empty node")?)?; - let node = match (tag, row) { - ("null", [_]) => Node::Atom(Value::None), - ("bool", [_, Value::Bool(v)]) => Node::Atom(Value::Bool(*v)), - ("text", [_, Value::Text(v)]) => Node::Atom(text(v)), - ("int", [_, Value::Text(v)]) => { - let n = v - .parse::() - .map_err(|_| "snapshot DAG: invalid integer")?; - if n.to_string() != *v { - return Err("snapshot DAG: noncanonical integer".into()); - } - Node::Atom(Value::Int(n)) - } - ("float", [_, Value::Text(v)]) if v.len() == 16 => { - let bits = - u64::from_str_radix(v, 16).map_err(|_| "snapshot DAG: invalid float bits")?; - if format!("{bits:016x}") != *v { - return Err("snapshot DAG: noncanonical float bits".into()); - } - Node::Atom(Value::Num(f64::from_bits(bits))) - } - ("list", [_, refs]) => Node::List( - list(refs)? - .iter() - .map(|v| index(v, i)) - .collect::>()?, - ), - ("map", [_, refs]) => { - let mut keys = HashSet::new(); - let mut fields = Vec::new(); - for pair in list(refs)? { - let [key, value] = list(pair)? else { - return Err("snapshot DAG: invalid map pair".into()); - }; - let key = string(key)?; - if !keys.insert(key) { - return Err("snapshot DAG: duplicate map key".into()); - } - fields.push((key.into(), index(value, i)?)); - } - Node::Map(fields) - } - _ => return Err("snapshot DAG: invalid node tag/payload".into()), - }; - let mut values = 1usize; - let mut bytes = match &node { - Node::Atom(v) => { - admit(v)?; - match v { - Value::Text(s) => s - .len() - .checked_mul(6) - .and_then(|n| n.checked_add(2)) - .ok_or("snapshot DAG: size overflow")?, - _ => 32, - } - } - Node::Map(v) => v - .iter() - .try_fold(2usize, |n, (k, _)| { - n.checked_add(k.len().checked_mul(6)?.checked_add(4)?) - }) - .ok_or("snapshot DAG: size overflow")?, - Node::List(_) => 2, - }; - let mut depth = 1; - for reference in node.refs() { - let (count, size, height) = costs[reference]; - values = values - .checked_add(count) - .ok_or("snapshot DAG: expansion overflow")?; - bytes = bytes - .checked_add(size) - .and_then(|n| n.checked_add(1)) - .ok_or("snapshot DAG: expansion overflow")?; - depth = depth.max(height + 1); - } - if values > MAX_VALUES || bytes > MAX_BYTES || depth > MAX_DEPTH { - return Err("snapshot DAG: expansion budget exceeded".into()); - } - costs.push((values, bytes, depth)); - nodes.push(node); - } - let mut reachable = HashSet::new(); - let mut todo = vec![root]; - while let Some(i) = todo.pop() { - if reachable.insert(i) { - todo.extend(nodes[i].refs()); - } - } - if reachable.len() != nodes.len() { - return Err("snapshot DAG: unreachable dictionary node".into()); - } - Ok((nodes, root)) -} - -pub fn unpack(envelope: &Value) -> Result { - fn expand(nodes: &[Node], i: usize) -> Value { - match &nodes[i] { - Node::Atom(v) => v.clone(), - Node::List(refs) => Value::List(refs.iter().map(|i| expand(nodes, *i)).collect()), - Node::Map(fields) => Value::Map( - fields - .iter() - .map(|(k, i)| (k.clone(), expand(nodes, *i))) - .collect(), - ), - } - } - let (nodes, root) = validate(envelope)?; - let value = expand(&nodes, root); - admit(&value)?; - Ok(value) -} - -#[cfg(test)] -mod tests { - use super::*; - fn envelope(rows: Vec) -> Value { - let root = Value::Int(rows.len() as i64 - 1); - let nodes = Value::List(rows); - let hash = checksum(&root, &nodes).unwrap(); - Value::Map(vec![ - ("format".into(), text(FORMAT)), - ("version".into(), Value::Int(1)), - ("root".into(), root), - ("nodes".into(), nodes), - ("sha256".into(), text(&hash)), - ]) - } - fn row(tag: &str, value: Value) -> Value { - Value::List(vec![text(tag), value]) - } - #[test] - fn typed_roundtrip_preserves_order_float_bits_and_repeated_values() { - let shared = Value::Map(vec![ - ( - "z".into(), - Value::List(vec![ - Value::None, - Value::Bool(true), - Value::Int(1), - Value::Num(-0.0), - Value::Num(1.25), - ]), - ), - ("汉字".into(), text("🧪")), - ]); - let input = Value::List(vec![shared; 128]); - let packed = pack(&input).unwrap(); - let decoded_wire = - crate::host::json::parse(&crate::host::json::stringify(&packed, None).unwrap()) - .unwrap(); - let expanded = unpack(&decoded_wire).unwrap(); - assert_eq!(input, expanded); - assert_eq!(wire(&input).unwrap(), wire(&expanded).unwrap()); - let Value::List(ref xs) = expanded else { - panic!() - }; - let Value::Map(ref fields) = xs[0] else { - panic!() - }; - assert_eq!(fields[0].0, "z"); - let Value::List(ref values) = fields[0].1 else { - panic!() - }; - let Value::Num(number) = values[3] else { - panic!() - }; - assert_eq!(number.to_bits(), (-0.0f64).to_bits()); - assert!(list(field(&packed, "nodes").unwrap()).unwrap().len() < 20); - assert!(wire(&packed).unwrap().len() < wire(&input).unwrap().len()); - } - #[test] - fn refuses_cycles_amplification_unreachable_duplicates_and_unsafe_atoms() { - let bad = [ - envelope(vec![row("list", Value::List(vec![Value::Int(0)]))]), - envelope(vec![row("text", text("unused")), row("text", text("root"))]), - envelope(vec![row("text", text("same")), row("text", text("same"))]), - envelope(vec![row("int", text("9007199254740992"))]), - envelope(vec![row("float", text("7ff8000000000000"))]), - envelope(vec![row("int", text("00"))]), - ]; - for value in bad { - assert!(unpack(&value).is_err()); - } - let mut rows = vec![row("text", text("x"))]; - for n in 0..40 { - rows.push(row("list", Value::List(vec![Value::Int(n), Value::Int(n)]))); - } - let error = unpack(&envelope(rows)).unwrap_err(); - assert!(error.contains("budget"), "{error}"); - let mut hash = pack(&Value::Int(1)).unwrap(); - if let Value::Map(ref mut fields) = hash { - fields.iter_mut().find(|(k, _)| k == "sha256").unwrap().1 = text("bad"); - } - assert!(unpack(&hash).unwrap_err().contains("checksum")); - } - #[test] - fn sharing_does_not_admit_ragged_columns_or_duplicate_keys() { - let ragged = Value::Map(vec![ - ("a".into(), Value::List(vec![Value::Int(1)])), - ("b".into(), Value::List(Vec::new())), - ]); - assert!(pack(&ragged).is_err()); - let duplicate = Value::Map(vec![ - ("a".into(), Value::Int(1)), - ("a".into(), Value::Int(2)), - ]); - assert!(pack(&duplicate).is_err()); - let value = envelope(vec![ - row("int", text("1")), - row("list", Value::List(vec![Value::Int(0)])), - row("list", Value::List(Vec::new())), - row( - "map", - Value::List(vec![ - Value::List(vec![text("a"), Value::Int(1)]), - Value::List(vec![text("b"), Value::Int(2)]), - ]), - ), - ]); - assert!(unpack(&value).is_err()); - } -} diff --git a/src/host/foreign_doc/replay.rs b/src/host/foreign_doc/replay.rs deleted file mode 100755 index d97e78a..0000000 --- a/src/host/foreign_doc/replay.rs +++ /dev/null @@ -1,2581 +0,0 @@ -//! Complete interactive operation history. Wire values are tagged so invalid -//! boundary attempts can be replayed without serializing an opaque capability. -use super::*; - -fn map(fields: Vec<(&str, Value)>) -> Value { - Value::Map(fields.into_iter().map(|(k, v)| (k.into(), v)).collect()) -} -fn object(v: &Value) -> Result<&[(String, Value)], String> { - let Value::Map(xs) = v else { - return Err("history: expected record".into()); - }; - let mut seen = HashSet::new(); - if xs.iter().any(|(k, _)| !seen.insert(k)) { - return Err("history: duplicate field".into()); - } - Ok(xs) -} -fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> { - object(v)? - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v) - .ok_or_else(|| format!("history: missing {key}")) -} -fn text<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> { - match field(v, key)? { - Value::Text(s) => Ok(s), - _ => Err(format!("history: {key} must be text")), - } -} -fn list<'a>(v: &'a Value, key: &str) -> Result<&'a [Value], String> { - match field(v, key)? { - Value::List(xs) => Ok(xs), - _ => Err(format!("history: {key} must be a list")), - } -} -fn boolean(v: &Value, key: &str) -> Result { - match field(v, key)? { - Value::Bool(x) => Ok(*x), - _ => Err(format!("history: {key} must be boolean")), - } -} -fn optional_text<'a>(v: &'a Value, key: &str) -> Result, String> { - match field(v, key)? { - Value::None => Ok(None), - Value::Text(x) => Ok(Some(x)), - _ => Err(format!("history: {key} must be text or None")), - } -} -fn exact(v: &Value, keys: &[&str]) -> Result<(), String> { - let xs = object(v)?; - if xs.len() != keys.len() || xs.iter().any(|(k, _)| !keys.contains(&k.as_str())) { - return Err("history: unexpected or missing fields".into()); - } - Ok(()) -} -// Internal metadata is not itself a foreign column table. Compare it without -// applying a payload-domain rule to a dictionary of separate host bindings. -fn control_canonical(v: &Value) -> Value { - match v { - Value::Map(fields) => { - let mut fields: Vec<_> = fields - .iter() - .map(|(k, v)| (k.clone(), control_canonical(v))) - .collect(); - fields.sort_by(|a, b| a.0.cmp(&b.0)); - Value::Map(fields) - } - Value::List(values) => Value::List(values.iter().map(control_canonical).collect()), - Value::Num(n) if *n == 0.0 => Value::Num(0.0), - value => value.clone(), - } -} -fn same(a: &Value, b: &Value) -> Result { - Ok(encode(&control_canonical(a)) == encode(&control_canonical(b))) -} -pub(super) fn validate_control(v: &Value) -> Result<(), String> { - match v { - Value::Map(fields) => { - object(v)?; - for (_, v) in fields { - validate_control(v)?; - } - Ok(()) - } - Value::List(values) => { - for v in values { - validate_control(v)?; - } - Ok(()) - } - Value::None | Value::Bool(_) | Value::Int(_) | Value::Num(_) | Value::Text(_) => { - super::super::oracle::admit(v) - } - _ => Err("history: control result contains a non-data value".into()), - } -} - -fn encode(v: &Value) -> Value { - let (tag, payload) = match v { - Value::None => ("null", Value::None), - Value::Bool(b) => ("bool", Value::Bool(*b)), - Value::Int(n) => ("int", Value::Text(n.to_string())), - Value::Num(n) => ("num", Value::Text(format!("{:016x}", n.to_bits()))), - Value::Text(s) => ("text", Value::Text(s.clone())), - Value::List(xs) => ("list", Value::List(xs.iter().map(encode).collect())), - Value::Map(xs) => ( - "map", - Value::List( - xs.iter() - .map(|(k, v)| Value::List(vec![Value::Text(k.clone()), encode(v)])) - .collect(), - ), - ), - Value::Code(c) => ( - "code", - map(vec![ - ("lang", Value::Text(c.lang.clone())), - ("source", Value::Text(c.source.clone())), - ]), - ), - Value::Handle(_) => ("invalid-handle", Value::None), - Value::Secret(_) => ("invalid-secret", Value::None), - Value::Formula(_) => ("invalid-formula", Value::None), - }; - Value::List(vec![Value::Text(tag.into()), payload]) -} -fn decode(v: &Value) -> Result { - let Value::List(pair) = v else { - return Err("history: expected tagged value".into()); - }; - if pair.len() != 2 { - return Err("history: invalid tagged value".into()); - } - let Value::Text(tag) = &pair[0] else { - return Err("history: missing value tag".into()); - }; - let p = &pair[1]; - Ok(match (tag.as_str(), p) { - ("null", Value::None) => Value::None, - ("bool", Value::Bool(b)) => Value::Bool(*b), - ("text", Value::Text(s)) => Value::Text(s.clone()), - ("int", Value::Text(s)) => Value::Int(s.parse().map_err(|_| "history: invalid integer")?), - ("num", Value::Text(s)) => Value::Num(f64::from_bits( - u64::from_str_radix(s, 16).map_err(|_| "history: invalid float bits")?, - )), - ("list", Value::List(xs)) => Value::List(xs.iter().map(decode).collect::>()?), - ("map", Value::List(xs)) => { - let mut entries = Vec::new(); - for item in xs { - let Value::List(kv) = item else { - return Err("history: invalid map entry".into()); - }; - if kv.len() != 2 { - return Err("history: invalid map entry".into()); - } - let Value::Text(key) = &kv[0] else { - return Err("history: invalid map key".into()); - }; - entries.push((key.clone(), decode(&kv[1])?)); - } - Value::Map(entries) - } - ("code", _) => { - exact(p, &["lang", "source"])?; - Value::Code(crate::value::CodeBlock { - lang: text(p, "lang")?.into(), - source: text(p, "source")?.into(), - }) - } - ("invalid-handle", Value::None) => Value::Handle("replay-invalid-payload".into()), - ("invalid-secret", Value::None) => Value::Secret(String::new()), - ("invalid-formula", Value::None) => Value::Formula(crate::formula::Expr::Num(0.0)), - _ => return Err("history: unknown tag or incorrect payload type".into()), - }) -} - -#[derive(Clone, Debug)] -pub(super) struct HistoryEntry { - controls: Vec, - kind: String, - args: Value, - outcome: Value, - protocol: Vec, - observations: Vec, - cells: Vec, - state: Value, -} - -pub(super) struct ReplayBoundary { - cells: std::collections::VecDeque, - records: Option>, - error: Option, -} -impl HistoryEntry { - fn wire(&self, index: usize) -> Value { - let mut fields = vec![ - ("index", Value::Int(index as i64)), - ("kind", Value::Text(self.kind.clone())), - ("args", encode(&self.args)), - ("outcome", encode(&self.outcome)), - ("protocol", Value::List(self.protocol.clone())), - ( - "observations", - encode(&Value::List(self.observations.clone())), - ), - ("cells", Value::List(self.cells.clone())), - ("state", encode(&self.state)), - ]; - if !self.controls.is_empty() { - fields.push(( - "controls", - Value::List(self.controls.iter().map(|event| event.value()).collect()), - )); - } - map(fields) - } - fn parse(v: &Value, index: usize) -> Result { - let mut schema = vec![ - "index", - "kind", - "args", - "outcome", - "protocol", - "observations", - "cells", - "state", - ]; - let has_controls = object(v)?.iter().any(|(key, _)| key == "controls"); - if has_controls { - schema.push("controls"); - } - exact(v, &schema)?; - let mut controls = Vec::new(); - if has_controls { - let mut previous = 0; - for row in list(v, "controls")? { - exact(row, &["after_us", "results"])?; - let Value::Int(after) = field(row, "after_us")? else { - return Err("history: control time must be integer".into()); - }; - if *after < 0 || (*after as u64) < previous { - return Err("history: invalid control ordering".into()); - } - previous = *after as u64; - let mut names = HashSet::new(); - let mut results = Vec::new(); - for result in list(row, "results")? { - exact(result, &["kernel", "accepted", "active", "error"])?; - let name = text(result, "kernel")?; - if name.is_empty() || !names.insert(name) { - return Err("history: duplicate/empty control kernel".into()); - } - let accepted = boolean(result, "accepted")?; - let active = boolean(result, "active")?; - let error = text(result, "error")?; - if (!accepted && active) - || (accepted && !error.is_empty()) - || (!accepted && error.is_empty()) - { - return Err("history: inconsistent interrupt receipt".into()); - } - results.push(( - name.into(), - if accepted { - Ok(active) - } else { - Err(error.into()) - }, - )); - } - controls.push(super::control::ControlEvent { - after_us: *after as u64, - results, - }); - } - } - if field(v, "index")? != &Value::Int(index as i64) { - return Err(format!("history: action {index} index differs")); - } - let observations = decode(field(v, "observations")?)?; - let Value::List(observations) = observations else { - return Err("history: observations must be a list".into()); - }; - for value in &observations { - super::super::oracle::admit(value)?; - } - Ok(Self { - controls, - kind: text(v, "kind")?.into(), - args: decode(field(v, "args")?)?, - outcome: decode(field(v, "outcome")?)?, - protocol: list(v, "protocol")?.to_vec(), - observations, - cells: list(v, "cells")?.to_vec(), - state: decode(field(v, "state")?)?, - }) - } -} - -impl DocumentSession { - pub(super) fn initialize_values(&mut self) -> Result<(), String> { - let mut initialized = HashSet::new(); - for (kernel, _, _) in self.initial_values.clone() { - if initialized.insert(kernel.clone()) { - self.ensure_kernel_session(&kernel)?; - } - } - Ok(()) - } - pub(super) fn plan_image(&self) -> Value { - map(vec![ - ( - "source", - Value::Text(self.host.entry_source.clone().unwrap_or_default()), - ), - ("source_hash", Value::Text(self.source_hash.clone())), - ("persistent", Value::Bool(self.persistent)), - ( - "kernels", - Value::List( - self.kernels - .iter() - .map(|k| { - map(vec![ - ("name", Value::Text(k.name.clone())), - ("lang", Value::Text(k.lang.clone())), - ("cmd", k.cmd.clone().map(Value::Text).unwrap_or(Value::None)), - ("implicit", Value::Bool(k.implicit)), - ]) - }) - .collect(), - ), - ), - ( - "cells", - Value::List( - self.cells - .iter() - .map(|c| { - map(vec![ - ("name", Value::Text(c.name.clone())), - ("lang", Value::Text(c.lang.clone())), - ("source", Value::Text(c.source.clone())), - ("source_hash", Value::Text(c.source_hash.clone())), - ("kernel", Value::Text(c.kernel.clone())), - ("listed", Value::Bool(c.listed)), - ("stdin", Value::Text(c.stdin.clone())), - ]) - }) - .collect(), - ), - ), - ( - "order", - Value::List(self.order.iter().cloned().map(Value::Text).collect()), - ), - ( - "initial_values", - Value::List( - self.initial_values - .iter() - .map(|(k, n, v)| { - map(vec![ - ("kernel", Value::Text(k.clone())), - ("name", Value::Text(n.clone())), - ("value", v.clone()), - ]) - }) - .collect(), - ), - ), - ]) - } - fn from_image( - path: &Path, - root: &Path, - image: &Value, - initialize: bool, - ) -> Result { - exact( - image, - &[ - "source", - "source_hash", - "persistent", - "kernels", - "cells", - "order", - "initial_values", - ], - )?; - let source = text(image, "source")?; - let source_hash = hash_source(source); - if text(image, "source_hash")? != source_hash { - return Err("history: source hash differs".into()); - } - let ctx = crate::binding::BindingContext::from_binds( - &[], - crate::binding::cwd_for_path(Some(path)), - ); - let module = crate::load::load_module_with_source(path, source, &ctx) - .map_err(|e| format!("history source: {e}"))?; - let entry = module - .functions - .iter() - .find(|f| f.name == "main" && f.is_object()) - .or_else(|| { - let objs: Vec<_> = module.functions.iter().filter(|f| f.is_object()).collect(); - if objs.len() == 1 { - Some(objs[0]) - } else { - None - } - }) - .ok_or("history: missing entry")?; - let mut parsed = Vec::new(); - collect_cells(&entry.body, &mut parsed, &mut HashSet::new())?; - let persistent = boolean(image, "persistent")?; - let mut kernels = Vec::new(); - let mut names = HashSet::new(); - for row in list(image, "kernels")? { - exact(row, &["name", "lang", "cmd", "implicit"])?; - let name = text(row, "name")?.to_string(); - if !names.insert(name.clone()) { - return Err("history: duplicate kernel".into()); - } - kernels.push(KernelDecl { - name, - lang: text(row, "lang")?.into(), - cmd: optional_text(row, "cmd")?.map(str::to_string), - implicit: boolean(row, "implicit")?, - }); - } - let mut cells = Vec::new(); - let mut cellnames = HashSet::new(); - for row in list(image, "cells")? { - exact( - row, - &[ - "name", - "lang", - "source", - "source_hash", - "kernel", - "listed", - "stdin", - ], - )?; - let name = text(row, "name")?; - if !cellnames.insert(name.to_string()) { - return Err("history: duplicate cell".into()); - } - let mut cell = parsed - .iter() - .find(|c| c.name == name) - .cloned() - .ok_or("history: cell absent from source")?; - if cell.source != text(row, "source")? - || cell.source_hash != text(row, "source_hash")? - || cell.lang != text(row, "lang")? - { - return Err("history: cell source differs".into()); - } - cell.kernel = text(row, "kernel")?.into(); - cell.listed = boolean(row, "listed")?; - cell.stdin = text(row, "stdin")?.into(); - if persistent { - if cell.listed - && !kernels.iter().any(|k| { - k.name == cell.kernel - && registry::canonical(&k.lang) == registry::canonical(&cell.lang) - }) - { - return Err("history: invalid cell routing".into()); - } - } else if cell.kernel != "one-shot" { - return Err("history: invalid one-shot routing".into()); - } - if !cell.listed { - cell.status = CellStatus::Unlisted; - } - cells.push(cell); - } - if cells.len() != parsed.len() { - return Err("history: incomplete source cells".into()); - } - let mut order = Vec::new(); - let mut seen = HashSet::new(); - for item in list(image, "order")? { - let Value::Text(name) = item else { - return Err("history: order must contain names".into()); - }; - if !seen.insert(name.clone()) || !cells.iter().any(|c| &c.name == name && c.listed) { - return Err("history: invalid order".into()); - } - order.push(name.clone()); - } - if cells.iter().filter(|c| c.listed).count() != order.len() { - return Err("history: incomplete order".into()); - } - let mut initial_values = Vec::new(); - for row in list(image, "initial_values")? { - exact(row, &["kernel", "name", "value"])?; - let kernel = text(row, "kernel")?; - let name = text(row, "name")?; - let value = field(row, "value")?.clone(); - if !kernels.iter().any(|k| k.name == kernel) || !foreign_session::valid_name(name) { - return Err("history: invalid initial binding".into()); - } - super::super::oracle::admit(&value)?; - initial_values.push((kernel.into(), name.into(), value)); - } - let mut host = HostContext::default(); - host.cwd = path.parent().unwrap_or_else(|| Path::new(".")).into(); - host.fs_root = Some(root.into()); - host.entry_path = Some(path.into()); - host.entry_source = Some(source.into()); - host.entry_metadata = module.metadata; - let mut session = Self { - control: super::DocumentControl::default(), - replay_controls: Vec::new(), - replay_boundary: None, - source_hash, - replay_fresh: true, - initial_values, - initial_image: image.clone(), - action_history: Vec::new(), - action_depth: 0, - path: path.into(), - root: root.into(), - persistent, - cells, - kernels, - order, - journal: Vec::new(), - oracle_journal: Vec::new(), - value_store: HashMap::new(), - cursor: 0, - generation: 1, - opened_ms: now_ms(), - host, - kernel_sessions: HashMap::new(), - seq: 0, - }; - if initialize { - session.initialize_values()?; - session.replay_fresh = true; - } - Ok(session) - } - fn history_state(&self) -> Value { - map(vec![ - ("plan", self.plan_image()), - ("cursor", Value::Int(self.cursor as i64)), - ("generation", Value::Int(self.generation as i64)), - ( - "live_kernels", - Value::List({ - let mut names: Vec<_> = self - .kernel_sessions - .iter() - .filter(|(_, id)| self.host.foreign_sessions.contains_key(*id)) - .map(|(name, _)| t(name)) - .collect(); - names.sort_by_key(|v| v.as_display()); - names - }), - ), - ( - "values", - Value::List({ - let mut bindings: Vec<_> = self.value_store.iter().collect(); - bindings.sort_by_key(|(name, _)| *name); - bindings - .into_iter() - .map(|(name, value)| map(vec![("name", t(name)), ("value", value.clone())])) - .collect() - }), - ), - ( - "cells", - Value::List( - self.cells - .iter() - .map(|c| { - map(vec![ - ("name", Value::Text(c.name.clone())), - ("runs", Value::Int(c.runs as i64)), - ("status", Value::Text(c.status.as_str().into())), - ("ok", Value::Bool(c.last_ok)), - ("stdout", Value::Text(c.last_stdout.clone())), - ("result", c.last_result.clone()), - ]) - }) - .collect(), - ), - ), - ]) - } -} - -fn t(s: &str) -> Value { - Value::Text(s.into()) -} -fn ot(s: Option<&str>) -> Value { - s.map(t).unwrap_or(Value::None) -} -impl DocumentSession { - pub(super) fn check_replay_cell_boundary(&mut self) { - let Some(boundary) = &mut self.replay_boundary else { - return; - }; - let actual = self - .oracle_journal - .last() - .expect("record just appended") - .to_value(); - let expected = boundary.cells.pop_front(); - if !expected - .as_ref() - .is_some_and(|expected| same(&actual, expected).unwrap_or(false)) - { - boundary.error = - Some("replay: cell observation differs at its execution boundary".into()); - } - } - - pub(super) fn replay_batch_can_continue(&mut self) -> bool { - if self.host.foreign_replay_divergence.is_some() { - return false; - } - let Some(boundary) = &mut self.replay_boundary else { - return true; - }; - if boundary.error.is_some() { - return false; - } - if boundary - .records - .as_ref() - .is_some_and(|records| records.is_empty()) - { - boundary.error = Some("replay: unexpected extra batch unit".into()); - return false; - } - true - } - - pub(super) fn check_replay_batch_record(&mut self, record: &Value, seq_before: u64) { - let Some(boundary) = &mut self.replay_boundary else { - return; - }; - if let Some(records) = &mut boundary.records { - let actual = eval_result(record); - let expected = records.pop_front(); - if !matches!((actual, expected), (Ok(actual), Some(expected)) if same(&actual, &expected).unwrap_or(false)) - { - boundary.error = - Some("replay: batch result differs at its execution boundary".into()); - } - } - // Run-all's order is unique (validated in both plan readers). A refused - // unit must not silently consume an expected admitted observation. - if self.seq == seq_before { - if let (Ok(name), Some(expected)) = (text(record, "cell"), boundary.cells.front()) { - if text(expected, "cell").ok() == Some(name) { - boundary.error = - Some("replay: missing cell observation at execution boundary".into()); - } - } - } - } - - pub fn run_cell_with_stdin( - &mut self, - cell_name: &str, - kernel_override: Option<&str>, - stdin: Option<&str>, - ) -> Result { - self.tracked( - "cell", - map(vec![ - ("cell", t(cell_name)), - ("kernel", ot(kernel_override)), - ("stdin", ot(stdin)), - ]), - |session| session.run_cell_with_stdin_inner(cell_name, kernel_override, stdin), - ) - } - pub fn step_with_stdin(&mut self, stdin: Option<&str>) -> Result { - self.tracked("step", map(vec![("stdin", ot(stdin))]), |session| { - session.step_with_stdin_inner(stdin) - }) - } - pub fn run_all_with_inputs( - &mut self, - restart: bool, - stdin: Option<&str>, - inputs: Option<&HashMap>, - ) -> Result { - self.tracked( - "run_all", - map(vec![ - ("restart", Value::Bool(restart)), - ("stdin", ot(stdin)), - ( - "inputs", - inputs - .map(|m| Value::Map(m.iter().map(|(k, v)| (k.clone(), t(v))).collect())) - .unwrap_or(Value::None), - ), - ]), - |session| session.run_all_with_inputs_inner(restart, stdin, inputs), - ) - } - pub fn interrupt(&mut self) -> Result { - self.tracked("interrupt", map(vec![]), |session| { - session.interrupt_inner() - }) - } - pub fn restart_kernel(&mut self, name: &str) -> Result { - self.tracked("restart", map(vec![("kernel", t(name))]), |session| { - session.restart_kernel_inner(name) - }) - } - pub fn restart_all(&mut self) -> Result { - self.tracked("restart_all", map(vec![]), |session| { - session.restart_all_inner() - }) - } - pub fn assign_kernel(&mut self, cell: &str, kernel: &str) -> Result { - self.tracked( - "assign", - map(vec![("cell", t(cell)), ("kernel", t(kernel))]), - |session| session.assign_kernel_inner(cell, kernel), - ) - } - pub fn add_cell( - &mut self, - cell: &str, - lang: &str, - source: &str, - kernel: &str, - ) -> Result { - self.tracked( - "add", - map(vec![ - ("cell", t(cell)), - ("lang", t(lang)), - ("source", t(source)), - ("kernel", t(kernel)), - ]), - |session| session.add_cell_inner(cell, lang, source, kernel), - ) - } - pub fn remove_cell(&mut self, cell: &str) -> Result { - self.tracked("remove", map(vec![("cell", t(cell))]), |session| { - session.remove_cell_inner(cell) - }) - } - pub fn set_value(&mut self, kernel: &str, name: &str, value: Value) -> Result { - self.tracked( - "set", - map(vec![ - ("kernel", t(kernel)), - ("name", t(name)), - ("value", value.clone()), - ]), - |session| session.set_value_inner(kernel, name, value), - ) - } - pub fn push_value(&mut self, kernel: &str, name: &str, value: Value) -> Result { - self.tracked( - "push", - map(vec![ - ("kernel", t(kernel)), - ("name", t(name)), - ("value", value.clone()), - ]), - |session| session.push_value_inner(kernel, name, value), - ) - } - pub fn pull_value(&mut self, kernel: &str, name: &str) -> Result { - self.tracked( - "get", - map(vec![("kernel", t(kernel)), ("name", t(name))]), - |session| session.pull_value_inner(kernel, name), - ) - } - pub fn state_list(&mut self) -> Result { - self.tracked("state", map(vec![]), |session| session.state_list_inner()) - } - pub fn clear_cell(&mut self, cell: &str) -> Result { - self.tracked("clear_cell", map(vec![("cell", t(cell))]), |session| { - session.clear_cell_inner(cell) - }) - } - pub fn import_snapshot(&mut self, snapshot: &Value) -> Result { - self.tracked( - "import", - map(vec![("snapshot", snapshot.clone())]), - |session| session.import_snapshot_inner(snapshot), - ) - } - pub fn replay_snapshot(&mut self, snapshot: &Value) -> Result { - self.tracked( - "rerun", - map(vec![("snapshot", snapshot.clone())]), - |session| session.replay_snapshot_inner(snapshot), - ) - } - pub fn persist_cell(&mut self, cell: &str, key: &str) -> Result { - self.tracked( - "persist", - map(vec![("cell", t(cell)), ("key", t(key))]), - |session| session.persist_cell_inner(cell, key), - ) - } - pub(super) fn inspect_kernels(&mut self) -> Result { - let mut kernels = Vec::new(); - for decl in self.kernels.clone() { - let mut values = Vec::new(); - if let Some(id) = self.kernel_sessions.get(&decl.name).cloned() { - if let Ok(Value::List(names)) = - foreign_session::names(&mut self.host, &Value::Handle(id.clone())) - { - for name in names { - if let Value::Text(n) = &name { - if let Ok(v) = foreign_session::get( - &mut self.host, - &Value::Handle(id.clone()), - &Value::Text(n.clone()), - ) { - values.push(Value::Map(vec![ - ("name".into(), Value::Text(n.clone())), - ("value".into(), v), - ])); - } - } - } - } - } - kernels.push(Value::Map(vec![ - ("name".into(), Value::Text(decl.name.clone())), - ("lang".into(), Value::Text(decl.lang.clone())), - ( - "cmd".into(), - Value::Text(decl.cmd.clone().unwrap_or_default()), - ), - ("values".into(), Value::List(values)), - ])); - } - Ok(Value::List(kernels)) - } - pub fn clear_outputs(&mut self) -> Value { - self.tracked("clear", map(vec![]), |s| Ok(s.clear_outputs_inner())) - .expect("clearing outputs cannot fail") - } - pub fn close(&mut self) { - let _ = self.tracked("close", map(vec![]), |s| { - s.close_inner(); - Ok(Value::None) - }); - } - pub fn reload(&mut self, root: &Path) -> Result<(), String> { - match std::fs::read_to_string(&self.path) { - Ok(source) => self - .tracked( - "reload", - map(vec![ - ("source", t(&source)), - ("image", Value::None), - ("input_error", Value::None), - ]), - |s| s.reload_source(&source, root).map(|_| Value::None), - ) - .map(|_| ()), - Err(error) => { - let error = format!("read {}: {error}", self.path.display()); - self.tracked( - "reload", - map(vec![ - ("source", Value::None), - ("image", Value::None), - ("input_error", t(&error)), - ]), - |_| Err(error), - ) - .map(|_| ()) - } - } - } -} - -fn eval_result(value: &Value) -> Result { - let xs = object(value)?; - if xs.iter().any(|(k, _)| k == "ok") { - let mut fields = vec![ - ("value", super::super::oracle::eval_observation(value)?), - ("ok", field(value, "ok")?.clone()), - ("code", field(value, "code")?.clone()), - ("stdout", field(value, "stdout")?.clone()), - ]; - for key in ["cursor", "generation"] { - if let Some((_, v)) = xs.iter().find(|(k, _)| k == key) { - fields.push((key, v.clone())); - } - } - Ok(map(fields)) - } else { - Ok(value.clone()) - } -} -fn outcome(kind: &str, result: &Result) -> Result { - Ok(match result { - Err(error) => map(vec![("ok", Value::Bool(false)), ("error", t(error))]), - Ok(value) => { - let projected = match kind { - "cell" | "step" => eval_result(value)?, - "run_all" | "rerun" => { - let mut fields = Vec::new(); - for key in ["ok", "ran", "failed", "replayed", "cancelled", "remaining"] { - if let Some((_, v)) = object(value)?.iter().find(|(k, _)| k == key) { - fields.push((key, v.clone())); - } - } - fields.push(( - "records", - Value::List( - list(value, "records")? - .iter() - .map(eval_result) - .collect::>()?, - ), - )); - map(fields) - } - "clear" | "clear_cell" => Value::None, - _ => value.clone(), - }; - map(vec![("ok", Value::Bool(true)), ("value", projected)]) - } - }) -} -impl DocumentSession { - pub(super) fn tracked( - &mut self, - kind: &str, - mut args: Value, - f: impl FnOnce(&mut Self) -> Result, - ) -> Result { - if self.action_depth != 0 { - return f(self); - } - let seq = self.seq; - let observed = self.host.oracle_observations.len(); - let requests = self.host.foreign_protocol_steps.len(); - let scheduler = self - .control - .begin(std::mem::take(&mut self.replay_controls)); - self.action_depth += 1; - let result = f(self); - self.action_depth -= 1; - let controls = self.control.finish(scheduler); - self.replay_fresh = false; - if kind == "reload" && result.is_ok() { - let Value::Map(fields) = &mut args else { - unreachable!() - }; - fields.iter_mut().find(|(k, _)| k == "image").unwrap().1 = self.plan_image(); - } - let entry = HistoryEntry { - controls, - kind: kind.into(), - args, - outcome: outcome(kind, &result)?, - protocol: self.host.foreign_protocol_steps[requests..] - .iter() - .map(|step| { - map(vec![ - ("session", t(&step.session)), - ("request", t(&step.request.to_string())), - ( - "response", - match &step.response { - Ok(value) => map(vec![ - ("ok", Value::Bool(true)), - ("json", t(&value.to_string())), - ]), - Err(error) => { - map(vec![("ok", Value::Bool(false)), ("error", t(error))]) - } - }, - ), - ]) - }) - .collect(), - observations: self.host.oracle_observations[observed..].to_vec(), - cells: self - .oracle_journal - .iter() - .filter(|j| j.seq > seq) - .map(OracleRecord::to_value) - .collect(), - state: self.history_state(), - }; - self.action_history.push(entry); - result - } - pub(super) fn action_history_json(&self) -> Value { - Value::List( - self.action_history - .iter() - .enumerate() - .map(|(i, e)| e.wire(i)) - .collect(), - ) - } - pub(super) fn complete_oracle_rows(&self) -> Vec { - self.action_history - .iter() - .flat_map(|e| e.cells.clone()) - .collect() - } - - fn check_action(entry: &HistoryEntry) -> Result<(), String> { - let a = &entry.args; - let schema: &[&str] = match entry.kind.as_str() { - "cell" => &["cell", "kernel", "stdin"], - "step" => &["stdin"], - "run_all" => &["restart", "stdin", "inputs"], - "restart" => &["kernel"], - "assign" => &["cell", "kernel"], - "add" => &["cell", "lang", "source", "kernel"], - "remove" | "clear_cell" => &["cell"], - "set" | "push" => &["kernel", "name", "value"], - "get" => &["kernel", "name"], - "import" | "rerun" => &["snapshot"], - "persist" => &["cell", "key"], - "reload" => &["source", "image", "input_error"], - "restart_all" | "interrupt" | "state" | "inspect" | "clear" | "close" => &[], - _ => return Err("history: unknown action kind".into()), - }; - exact(a, schema)?; - for key in schema { - match *key { - "value" | "snapshot" | "image" => {} - "restart" => { - boolean(a, key)?; - } - "input_error" => { - optional_text(a, key)?; - } - "source" if entry.kind == "reload" => { - optional_text(a, key)?; - } - "stdin" => { - optional_text(a, key)?; - } - "kernel" if entry.kind == "cell" => { - optional_text(a, key)?; - } - "inputs" => { - if field(a, key)? != &Value::None { - for (_, v) in object(field(a, key)?)? { - if !matches!(v, Value::Text(_)) { - return Err("history: inputs must map names to text".into()); - } - } - } - } - _ => { - text(a, key)?; - } - } - } - for step in &entry.protocol { - exact(step, &["session", "request", "response"])?; - text(step, "session")?; - serde_json::from_str::(text(step, "request")?) - .map_err(|_| "history: malformed protocol request")?; - let response = field(step, "response")?; - if boolean(response, "ok")? { - exact(response, &["ok", "json"])?; - serde_json::from_str::(text(response, "json")?) - .map_err(|_| "history: malformed protocol response")?; - } else { - exact(response, &["ok", "error"])?; - text(response, "error")?; - } - } - validate_control(&entry.outcome)?; - validate_control(&entry.state)?; - if boolean(&entry.outcome, "ok")? { - exact(&entry.outcome, &["ok", "value"])?; - } else { - exact(&entry.outcome, &["ok", "error"])?; - text(&entry.outcome, "error")?; - } - Ok(()) - } - fn execute_action(&mut self, entry: &HistoryEntry) -> Result { - let a = &entry.args; - match entry.kind.as_str() { - "cell" => self.run_cell_with_stdin( - text(a, "cell")?, - optional_text(a, "kernel")?, - optional_text(a, "stdin")?, - ), - "step" => self.step_with_stdin(optional_text(a, "stdin")?), - "run_all" => { - let inputs = match field(a, "inputs")? { - Value::None => None, - v => Some( - object(v)? - .iter() - .map(|(k, v)| match v { - Value::Text(s) => Ok((k.clone(), s.clone())), - _ => Err("history: input type".into()), - }) - .collect::, String>>()?, - ), - }; - self.run_all_with_inputs( - boolean(a, "restart")?, - optional_text(a, "stdin")?, - inputs.as_ref(), - ) - } - "restart" => self.restart_kernel(text(a, "kernel")?), - "restart_all" => self.restart_all(), - "assign" => self.assign_kernel(text(a, "cell")?, text(a, "kernel")?), - "add" => self.add_cell( - text(a, "cell")?, - text(a, "lang")?, - text(a, "source")?, - text(a, "kernel")?, - ), - "remove" => self.remove_cell(text(a, "cell")?), - "set" => self.set_value( - text(a, "kernel")?, - text(a, "name")?, - field(a, "value")?.clone(), - ), - "push" => self.push_value( - text(a, "kernel")?, - text(a, "name")?, - field(a, "value")?.clone(), - ), - "get" => self.pull_value(text(a, "kernel")?, text(a, "name")?), - "state" => self.state_list(), - "inspect" => self.tracked("inspect", a.clone(), |s| s.inspect_kernels()), - "import" => self.import_snapshot(field(a, "snapshot")?), - "rerun" => self.replay_snapshot(field(a, "snapshot")?), - "persist" => self.persist_cell(text(a, "cell")?, text(a, "key")?), - "clear_cell" => self.clear_cell(text(a, "cell")?), - "clear" => Ok(self.clear_outputs()), - "interrupt" => self.interrupt(), - "close" => { - self.close(); - Ok(Value::None) - } - "reload" => { - let args = a.clone(); - let image = field(a, "image")?.clone(); - let source = optional_text(a, "source")?.map(str::to_string); - let input_error = optional_text(a, "input_error")?.map(str::to_string); - let root = self.root.clone(); - self.tracked("reload", args, |s| { - if let Some(error) = input_error { - return Err(error); - } - if image == Value::None { - s.reload_source( - source.as_deref().ok_or("history: reload source missing")?, - &root, - )?; - } else { - let fresh = Self::from_image(&s.path, &root, &image, false)?; - s.install_reload(fresh)?; - } - Ok(Value::None) - }) - } - _ => Err("history: unsupported action".into()), - } - } - // Validate configuration transitions without querying any foreign kernel. - fn simulate_action(&mut self, entry: &HistoryEntry) -> Result<(), String> { - Self::check_action(entry)?; - let a = &entry.args; - let success = boolean(&entry.outcome, "ok")?; - match entry.kind.as_str() { - "reload" if success => { - let image = field(a, "image")?; - if optional_text(a, "input_error")?.is_some() - || Some(text(image, "source")?) != optional_text(a, "source")? - { - return Err("history: reload source differs".into()); - } - let fresh = Self::from_image(&self.path, &self.root, image, false)?; - self.install_reload(fresh)?; - } - "reload" => { - if let Some(error) = optional_text(a, "input_error")? { - if optional_text(a, "source")?.is_some() - || text(&entry.outcome, "error")? != error - { - return Err("history: invalid reload input failure".into()); - } - } else if optional_text(a, "source")?.is_none() { - return Err("history: missing reload source".into()); - } - if field(a, "image")? != &Value::None { - return Err("history: failed reload has a plan image".into()); - } - } - "assign" | "add" | "remove" => { - let result = match entry.kind.as_str() { - "assign" => self.assign_kernel_inner(text(a, "cell")?, text(a, "kernel")?), - "add" => self.add_cell_inner( - text(a, "cell")?, - text(a, "lang")?, - text(a, "source")?, - text(a, "kernel")?, - ), - _ => self.remove_cell_inner(text(a, "cell")?), - }; - if result.is_ok() != success { - return Err("history: impossible plan edit outcome".into()); - } - } - "cell" => { - if let Some(kernel) = optional_text(a, "kernel")? { - if let Some(ci) = self.cell_index(text(a, "cell")?) { - if self.kernel(kernel).map(|k| registry::canonical(&k.lang)) - == Some(registry::canonical(&self.cells[ci].lang)) - { - self.cells[ci].kernel = kernel.into(); - self.cells[ci].listed = true; - } - } - } - } - "step" if success => { - if self.cursor < self.order.len() { - self.cursor += 1; - } - } - "run_all" if success => { - let Value::Int(ran) = field(field(&entry.outcome, "value")?, "ran")? else { - return Err("history: invalid run count".into()); - }; - if *ran < 0 - || *ran as usize > self.order.len() - || (entry.controls.is_empty() && *ran as usize != self.order.len()) - { - return Err("history: impossible run count".into()); - } - self.cursor = *ran as usize; - } - "restart_all" | "clear" => { - self.cursor = 0; - } - "set" | "import" | "persist" if success => { - self.generation += 1; - } - _ => {} - } - match entry.kind.as_str() { - "cell" | "step" | "run_all" | "rerun" => { - if entry.observations.len() != entry.cells.len() { - return Err("history: cell/observation projection length differs".into()); - } - for (row, obs) in entry.cells.iter().zip(&entry.observations) { - if text(obs, "channel")? != "eval" - || !same(field(obs, "value")?, field(row, "value")?)? - { - return Err("history: cell observation value differs".into()); - } - } - if entry.kind == "cell" && entry.cells.len() != if success { 1 } else { 0 } { - return Err("history: impossible cell outcome".into()); - } - } - "get" => { - if !entry.cells.is_empty() - || entry.observations.len() != if success { 1 } else { 0 } - { - return Err("history: get observation count differs".into()); - } - if success - && (text(&entry.observations[0], "channel")? != "get" - || !same( - field(&entry.observations[0], "value")?, - field(&entry.outcome, "value")?, - )?) - { - return Err("history: get observation differs".into()); - } - } - _ => { - if !entry.cells.is_empty() || !entry.observations.is_empty() { - return Err("history: control action has foreign observations".into()); - } - } - } - if success && ["set", "push", "get"].contains(&entry.kind.as_str()) { - let kernel = text(a, "kernel")?; - let name = text(a, "name")?; - if self.kernel(kernel).is_none() || !foreign_session::valid_name(name) { - return Err("history: impossible binding operation".into()); - } - let value = if entry.kind == "get" { - field(&entry.outcome, "value")? - } else { - field(a, "value")? - }; - super::super::oracle::admit(value)?; - self.value_store.insert(name.to_string(), value.clone()); - } - if !same( - field(&self.history_state(), "values")?, - field(&entry.state, "values")?, - )? { - return Err("history: inconsistent host bindings".into()); - } - for row in &entry.cells { - let name = text(row, "cell")?; - let ci = self - .cell_index(name) - .ok_or("history: observation refers to missing cell")?; - let cell = &self.cells[ci]; - if text(row, "source_hash")? != cell.source_hash - || text(row, "lang")? != cell.lang - || text(row, "kernel")? != cell.kernel - { - return Err("history: observation source or route differs".into()); - } - text(row, "stdin")?; - text(row, "stdout")?; - boolean(row, "ok")?; - if !matches!(field(row, "code")?, Value::Int(_)) { - return Err("history: invalid observation code".into()); - } - field(row, "result")?; - super::super::oracle::admit(field(row, "value")?)?; - } - if !same(&self.plan_image(), field(&entry.state, "plan")?)? { - return Err("history: inconsistent plan transition".into()); - } - if field(&entry.state, "cursor")? != &Value::Int(self.cursor as i64) - || field(&entry.state, "generation")? != &Value::Int(self.generation as i64) - { - return Err("history: inconsistent cursor or generation".into()); - } - Ok(()) - } - pub fn replay_check(&mut self, snapshot: &Value) -> Result { - let expanded = if super::packing::is_packed(snapshot) { - Some(super::packing::unpack(snapshot)?) - } else { - None - }; - let snapshot = expanded.as_ref().unwrap_or(snapshot); - super::super::oracle::admit(snapshot)?; - let version = field(snapshot, "version")?; - if version != &Value::Int(4) && version != &Value::Int(5) { - return Err("replay: version 4/5 complete action history required".into()); - } - if !self.replay_fresh || self.seq != 0 || !self.action_history.is_empty() { - return Err("replay: fresh document session required".into()); - } - if text(snapshot, "document_hash")? != self.source_hash { - return Err("replay: document hash differs".into()); - } - let rows = list(snapshot, "actions")?; - if field(snapshot, "action_count")? != &Value::Int(rows.len() as i64) { - return Err("history: action count differs".into()); - } - let entries = rows - .iter() - .enumerate() - .map(|(i, row)| HistoryEntry::parse(row, i)) - .collect::, _>>()?; - if version == &Value::Int(4) - && rows.iter().any(|row| { - object(row).is_ok_and(|fields| fields.iter().any(|(key, _)| key == "controls")) - }) - { - return Err("history: concurrent controls require version 5".into()); - } - let image = field(snapshot, "initial_image")?; - let mut simulation = Self::from_image(&self.path, &self.root, image, false)?; - let mut cells = Vec::new(); - let mut observations = Vec::new(); - for entry in &entries { - simulation.simulate_action(entry)?; - cells.extend(entry.cells.clone()); - observations.extend(entry.observations.clone()); - } - for (i, row) in cells.iter().enumerate() { - if field(row, "seq")? != &Value::Int((i + 1) as i64) { - return Err("history: noncontiguous oracle sequence".into()); - } - } - if field(snapshot, "oracle_count")? != &Value::Int(cells.len() as i64) - || !same(&Value::List(cells), field(snapshot, "oracle_journal")?)? - { - return Err("history: oracle projection differs".into()); - } - let observed = Value::List(observations); - super::super::oracle::replay_check(&observed, &observed)?; - if !same(&observed, field(snapshot, "observation_journal")?)? { - return Err("history: document observation projection differs".into()); - } - if text(snapshot, "document_hash")? != simulation.source_hash - || boolean(snapshot, "persistent")? != simulation.persistent - { - return Err("history: final source or mode differs".into()); - } - let expected_order = - Value::List(simulation.order.iter().cloned().map(Value::Text).collect()); - if !same(field(snapshot, "order")?, &expected_order)? { - return Err("history: final plan order differs".into()); - } - let final_cells = list(snapshot, "cells")?; - if final_cells.len() != simulation.cells.len() { - return Err("history: final cell manifest differs".into()); - } - for (row, cell) in final_cells.iter().zip(&simulation.cells) { - for (key, expected) in [ - ("name", &cell.name), - ("source", &cell.source), - ("source_hash", &cell.source_hash), - ("kernel", &cell.kernel), - ("lang", &cell.lang), - ] { - if text(row, key)? != expected { - return Err("history: final cell identity differs".into()); - } - } - } - if field(snapshot, "generation")? != &Value::Int(simulation.generation as i64) { - return Err("history: final generation differs".into()); - } - let last = entries - .last() - .ok_or("history: snapshot lacks state inspection")?; - if last.kind != "inspect" - || !boolean(&last.outcome, "ok")? - || !same(field(&last.outcome, "value")?, field(snapshot, "kernels")?)? - { - return Err("history: final state inspection differs".into()); - } - // All validation above is pure with respect to external kernels. - let mut fresh = Self::from_image(&self.path, &self.root, image, true)?; - self.close_inner(); - std::mem::swap(self, &mut fresh); - let mut checks = Vec::new(); - let mut action_checks = Vec::new(); - let mut matched_observations = 0i64; - let mut mismatched = 0i64; - let mut skipped = 0i64; - for (index, expected) in entries.iter().enumerate() { - let protocol = expected - .protocol - .iter() - .map(|step| { - let response = field(step, "response")?; - Ok(super::foreign_session::ProtocolStep { - session: text(step, "session")?.into(), - request: serde_json::from_str(text(step, "request")?) - .map_err(|e| e.to_string())?, - response: if boolean(response, "ok")? { - Ok(serde_json::from_str(text(response, "json")?) - .map_err(|e| e.to_string())?) - } else { - Err(text(response, "error")?.into()) - }, - }) - }) - .collect::, String>>()?; - self.host.foreign_replay_expected = Some(protocol.into()); - self.host.foreign_replay_divergence = None; - let records = if ["run_all", "rerun"].contains(&expected.kind.as_str()) - && boolean(&expected.outcome, "ok")? - { - Some( - list(field(&expected.outcome, "value")?, "records")? - .to_vec() - .into(), - ) - } else if expected.kind == "run_all" { - Some(std::collections::VecDeque::new()) - } else { - None - }; - self.replay_boundary = Some(ReplayBoundary { - cells: expected.cells.clone().into(), - records, - error: None, - }); - self.replay_controls = expected.controls.clone(); - let _result = self.execute_action(expected); - let boundary = self.replay_boundary.take().unwrap(); - let mut guarded_error = self - .host - .foreign_replay_divergence - .take() - .or(boundary.error); - if self - .host - .foreign_replay_expected - .take() - .is_some_and(|cursor| cursor.finish().is_err()) - || !boundary.cells.is_empty() - || boundary.records.is_some_and(|records| !records.is_empty()) - { - guarded_error - .get_or_insert("replay: recorded execution prefix was not consumed".into()); - } - let actual = self - .action_history - .last() - .ok_or("history: action produced no record")?; - let mut bad_cells = 0i64; - for n in 0..expected.cells.len().max(actual.cells.len()) { - let exp = expected.cells.get(n); - let act = actual.cells.get(n); - if act.is_none() { - // The causal guard deliberately did not execute this suffix. - // It is unobserved, not a second observed mismatch. - skipped += 1; - checks.push(map(vec![ - ( - "cell", - t(exp - .map(|r| text(r, "cell")) - .transpose()? - .unwrap_or("missing")), - ), - ("action", Value::Int(index as i64)), - ("step", Value::Int(n as i64)), - ("match", Value::Bool(false)), - ("compared", Value::Bool(false)), - ("diff", t("not executed after replay divergence")), - ])); - continue; - } - let mut diff = String::new(); - match (exp, act) { - (Some(exp), Some(act)) => { - for key in [ - "seq", - "cell", - "kernel", - "lang", - "source_hash", - "stdin", - "ok", - "code", - "stdout", - "result", - "value", - ] { - if !same(field(exp, key)?, field(act, key)?)? { - diff = format!( - "action {index} observation {n} {key}: expected {}, got {}", - field(exp, key)?.as_display(), - field(act, key)?.as_display() - ); - break; - } - } - } - _ => diff = format!("action {index}: oracle observation length differs"), - } - let matched = diff.is_empty(); - if !matched { - bad_cells += 1; - } - let cell = exp - .or(act) - .map(|r| text(r, "cell")) - .transpose()? - .unwrap_or("missing"); - checks.push(map(vec![ - ("cell", t(cell)), - ("action", Value::Int(index as i64)), - ("step", Value::Int(n as i64)), - ("match", Value::Bool(matched)), - ("compared", Value::Bool(true)), - ("diff", t(&diff)), - ])); - } - let mut diff = String::new(); - for (key, a, b) in [ - ( - "controls", - Value::List(actual.controls.iter().map(|e| e.value()).collect()), - Value::List(expected.controls.iter().map(|e| e.value()).collect()), - ), - ("outcome", actual.outcome.clone(), expected.outcome.clone()), - ( - "protocol", - Value::List(actual.protocol.clone()), - Value::List(expected.protocol.clone()), - ), - ( - "observations", - Value::List(actual.observations.clone()), - Value::List(expected.observations.clone()), - ), - ("state", actual.state.clone(), expected.state.clone()), - ] { - if !same(&a, &b)? { - diff = format!( - "action {index} {key}: expected {}, got {}", - b.as_display(), - a.as_display() - ); - break; - } - } - if let Some(error) = guarded_error { - diff = error; - } - let matched = diff.is_empty() && bad_cells == 0; - action_checks.push(map(vec![ - ("action", Value::Int(index as i64)), - ("kind", t(&expected.kind)), - ("match", Value::Bool(matched)), - ("diff", t(&diff)), - ])); - if bad_cells > 0 { - mismatched += bad_cells; - matched_observations += (actual.cells.len() as i64 - bad_cells).max(0); - } else if !matched { - mismatched += 1; - checks.push(map(vec![ - ("cell", t(&expected.kind)), - ("action", Value::Int(index as i64)), - ("step", Value::Int(index as i64)), - ("match", Value::Bool(false)), - ("compared", Value::Bool(true)), - ("diff", t(&diff)), - ])); - } else { - matched_observations += expected.observations.len() as i64; - } - // A mismatched prefix cannot justify executing its dependent suffix. - if !matched { - break; - } - } - let executed = action_checks.len(); - Ok(map(vec![ - ("ok", Value::Bool(mismatched == 0)), - ("matched", Value::Int(matched_observations)), - ( - "matched_actions", - Value::Int(executed as i64 - if mismatched > 0 { 1 } else { 0 }), - ), - ("executed_actions", Value::Int(executed as i64)), - ( - "remaining_actions", - Value::Int((entries.len() - executed) as i64), - ), - ("mismatched", Value::Int(mismatched)), - ("skipped", Value::Int(skipped)), - ("checks", Value::List(checks)), - ("action_checks", Value::List(action_checks)), - ])) - } -} - -#[cfg(test)] -pub(super) fn sync_expected_cells(snapshot: &mut Value) -> Result<(), String> { - let originals = list(snapshot, "oracle_journal")?.to_vec(); - let mut entries = list(snapshot, "actions")? - .iter() - .enumerate() - .map(|(i, v)| HistoryEntry::parse(v, i)) - .collect::, _>>()?; - for entry in &mut entries { - for cell in &mut entry.cells { - if let Some(updated) = originals - .iter() - .find(|r| field(r, "seq").ok() == field(cell, "seq").ok()) - { - let old_value = field(cell, "value")?.clone(); - let new_value = field(updated, "value")?.clone(); - let old_stdout = field(cell, "stdout")?.clone(); - let new_stdout = field(updated, "stdout")?.clone(); - if !same(&old_value, &new_value)? { - for obs in &mut entry.observations { - if field(obs, "channel")? == &t("eval") - && same(field(obs, "value")?, &old_value)? - { - set_field(obs, "value", new_value.clone())?; - } - } - } - fn update_projection( - v: &mut Value, - old_value: &Value, - new_value: &Value, - old_stdout: &Value, - new_stdout: &Value, - ) -> Result<(), String> { - if let Value::Map(fields) = v { - let has_eval = fields.iter().any(|(k, _)| k == "stdout") - && fields.iter().any(|(k, _)| k == "code"); - if has_eval { - for (k, value) in fields.iter_mut() { - if k == "value" && same(value, old_value)? { - *value = new_value.clone(); - } - if k == "stdout" && same(value, old_stdout)? { - *value = new_stdout.clone(); - } - } - } - for (_, value) in fields { - update_projection(value, old_value, new_value, old_stdout, new_stdout)?; - } - } else if let Value::List(values) = v { - for value in values { - update_projection(value, old_value, new_value, old_stdout, new_stdout)?; - } - } - Ok(()) - } - update_projection( - &mut entry.outcome, - &old_value, - &new_value, - &old_stdout, - &new_stdout, - )?; - *cell = updated.clone(); - } - } - } - let observations = entries - .iter() - .flat_map(|e| e.observations.clone()) - .collect(); - let actions = entries.iter().enumerate().map(|(i, e)| e.wire(i)).collect(); - set_field(snapshot, "actions", Value::List(actions))?; - set_field(snapshot, "observation_journal", Value::List(observations))?; - Ok(()) -} -#[cfg(test)] -fn set_field(record: &mut Value, key: &str, value: Value) -> Result<(), String> { - let Value::Map(fields) = record else { - return Err("test: expected map".into()); - }; - fields - .iter_mut() - .find(|(k, _)| k == key) - .ok_or("test: missing field")? - .1 = value; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn aggregate_replay_checks_each_unit_before_dependent_side_effects() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - for language in ["python", "node"] { - for persistent in [false, true] { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos(); - let path = root.join(format!( - "target/batch-boundary-{}-{nonce}.mq.md", - std::process::id() - )); - let flag = path.with_extension("input"); - let started = path.with_extension("started"); - let suffix = path.with_extension("suffix"); - let literal = |p: &Path| serde_json::to_string(&p.display().to_string()).unwrap(); - let (first, next) = if language == "python" { - (format!("from pathlib import Path\nPath({}).write_text('first')\nprint(1 if Path({}).exists() else 2)", literal(&started), literal(&flag)), - format!("open({}, 'w').write('suffix')\nprint(7)", literal(&suffix))) - } else { - (format!("require('fs').writeFileSync({}, 'first'); console.log(require('fs').existsSync({}) ? 1 : 2);", literal(&started), literal(&flag)), - format!("require('fs').writeFileSync({}, 'suffix'); console.log(7);", literal(&suffix))) - }; - let header = if persistent { - "---\nimport:\n foreign: lib/foreign.mq.md\n---\n# main\n\n`会话` = > foreign.session\n" - } else { - "# main\n" - }; - std::fs::write(&path, format!("{header}\n`first` =\n```{language}\n{first}\n```\n\n`next` =\n```{language}\n{next}\n```\n")).unwrap(); - std::fs::write(&flag, "present").unwrap(); - let mut recording = DocumentSession::open(&path, &root).unwrap(); - recording.run_all(false).unwrap(); - let snapshot = recording.export_snapshot().unwrap(); - recording.close(); - let good = - DocumentSession::check_snapshot_isolated(&path, &root, &snapshot).unwrap(); - assert_eq!( - field(&good, "ok").unwrap(), - &Value::Bool(true), - "{language} persistent={persistent}: {}", - good.as_display() - ); - std::fs::remove_file(&flag).unwrap(); - for compact in [false, true] { - let _ = std::fs::remove_file(&started); - let _ = std::fs::remove_file(&suffix); - let input = if compact { - super::super::packing::pack(&snapshot).unwrap() - } else { - snapshot.clone() - }; - let checked = - DocumentSession::check_snapshot_isolated(&path, &root, &input).unwrap(); - assert_eq!(field(&checked, "ok").unwrap(), &Value::Bool(false)); - assert!( - started.exists(), - "first primitive must execute to observe the changed response" - ); - assert!( - !suffix.exists(), - "{language} persistent={persistent}: mismatching batch executed its suffix" - ); - } - if persistent { - let _ = std::fs::remove_file(&started); - let mut wrong_request = snapshot.clone(); - let Value::Map(fields) = &mut wrong_request else { - panic!() - }; - let (_, Value::List(actions)) = - fields.iter_mut().find(|(k, _)| k == "actions").unwrap() - else { - panic!() - }; - let mut entry = HistoryEntry::parse(&actions[0], 0).unwrap(); - let Value::Map(step) = &mut entry.protocol[0] else { - panic!() - }; - let (_, Value::Text(json)) = - step.iter_mut().find(|(k, _)| k == "request").unwrap() - else { - panic!() - }; - let mut request: serde_json::Value = serde_json::from_str(json).unwrap(); - request["code"] = "different code".into(); - *json = request.to_string(); - actions[0] = entry.wire(0); - let checked = - DocumentSession::check_snapshot_isolated(&path, &root, &wrong_request) - .unwrap(); - assert_eq!(field(&checked, "ok").unwrap(), &Value::Bool(false)); - assert!( - !started.exists(), - "request divergence was detected after dispatch" - ); - assert!(!suffix.exists()); - } - for file in [path, started] { - let _ = std::fs::remove_file(file); - } - println!("E12 {language} persistent={persistent}: matching replay passes; changed response stops inside batch; compact replay has same boundary"); - } - } - } - fn fixture() -> (PathBuf, PathBuf, String) { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.join(format!( - "target/history-{}-{}.mq.md", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let source = r#"--- -import: - foreign: lib/foreign.mq.md ---- -# main - -`kernels` = -| 名称 | 语言 | 命令 | -|---|---|---| -| py | python | | - -`units` = -| 单元 | 内核 | -|---|---| -| inc | py | -| bad | py | -| read | py | - -`initial` = -| 内核 | 名称 | 值 | -|---|---|---| -| py | n | 1 | - -`会话` = > foreign.session kernels=`kernels` cells=`units` values=`initial` - -`inc` = -```python -n += 1 -n -``` - -`bad` = -```python -n = 99 -2**53 -``` - -`read` = -```python -n -``` -"# - .to_string(); - std::fs::write(&path, &source).unwrap(); - (root, path, source) - } - fn assert_replay(b: &mut DocumentSession, snap: &Value) { - let result = b.replay_check(snap).unwrap(); - assert_eq!( - field(&result, "ok").unwrap(), - &Value::Bool(true), - "{}", - result.as_display() - ); - assert_eq!(field(&result, "remaining_actions").unwrap(), &Value::Int(0)); - } - #[test] - fn history_replays_inputs_fault_recovery_restart_edits_and_clear() { - let (root, path, source) = fixture(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(1)); - a.set_value("py", "n", Value::Int(4)).unwrap(); - a.run_cell("inc", None).unwrap(); - assert!(a - .run_cell("bad", None) - .unwrap_err() - .contains("outside V_safe")); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(99)); - a.restart_kernel("py").unwrap(); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(1)); - // Invalid outbound requests must be represented without making them legal wire payloads. - assert!(a.set_value("py", "n", Value::Int(i64::MAX)).is_err()); - assert!(a - .set_value("py", "n", Value::Handle("must-not-escape".into())) - .is_err()); - assert!(a - .set_value("py", "n", Value::Secret("must-not-be-recorded".into())) - .is_err()); - a.set_value("py", "n", Value::Int(8)).unwrap(); - a.step().unwrap(); - let result = a.run_all(false).unwrap(); - assert_eq!(field(&result, "failed").unwrap(), &Value::Int(1)); - a.clear_outputs(); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(99)); - a.add_cell("extra", "python", "n += 2\nn", "py").unwrap(); - a.run_cell("extra", None).unwrap(); - a.clear_cell("extra").unwrap(); - a.remove_cell("extra").unwrap(); - a.state_list().unwrap(); - a.interrupt().unwrap(); - assert_eq!( - a.pull_value("py", "n").unwrap(), - Value::Int(101), - "idle interrupt preserves kernel state" - ); - let snap = a.export_snapshot().unwrap(); - let wire = super::super::super::json::stringify(&snap, None).unwrap(); - let Value::Text(ref serialized) = wire else { - panic!() - }; - assert!(!serialized.contains("must-not-escape")); - assert!(!serialized.contains("must-not-be-recorded")); - let snap = super::super::super::json::parse(&wire).unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - assert_replay(&mut b, &snap); - assert_eq!(b.pull_value("py", "n").unwrap(), Value::Int(101)); - assert_eq!( - std::fs::read_to_string(&path).unwrap(), - source, - "replay must not rewrite source" - ); - b.close(); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn history_replays_reload_versions_without_rewriting_the_document() { - let (root, path, source) = fixture(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.set_value("py", "n", Value::Int(5)).unwrap(); - a.run_cell("inc", None).unwrap(); - let second = source - .replace("n += 1\nn", "n += 10\nn") - .replace("| py | n | 1 |", "| py | n | 2 |"); - std::fs::write(&path, &second).unwrap(); - a.reload(&root).unwrap(); - a.run_cell("inc", None).unwrap(); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(16)); - a.restart_all().unwrap(); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(2)); - let third = second - .replace("| py | python | |", "| py | python | \"python3 -u\" |") - .replace("| py | n | 2 |", "| py | n | 3 |"); - std::fs::write(&path, &third).unwrap(); - a.reload(&root).unwrap(); - assert_eq!( - a.pull_value("py", "n").unwrap(), - Value::Int(3), - "changed kernel command must retire the old process" - ); - assert_eq!(a.host.entry_source.as_ref().unwrap(), &third); - let snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - assert_replay(&mut b, &snap); - assert_eq!(b.host.entry_source.as_ref().unwrap(), &third); - assert_eq!(std::fs::read_to_string(&path).unwrap(), third); - b.close(); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn malformed_action_suffix_is_rejected_before_any_kernel_request() { - let (root, path, _) = fixture(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.run_cell("inc", None).unwrap(); - a.pull_value("py", "n").unwrap(); - let original = a.export_snapshot().unwrap(); - a.close(); - for kind in [ - "unknown", - "count", - "index", - "args", - "image", - "projection", - "truncated", - "state", - "outcome", - ] { - let mut snap = original.clone(); - match kind { - "count" => set_field(&mut snap, "action_count", Value::Int(0)).unwrap(), - "image" => { - let Value::Map(fields) = &mut snap else { - panic!() - }; - let img = &mut fields - .iter_mut() - .find(|(k, _)| k == "initial_image") - .unwrap() - .1; - set_field(img, "source_hash", t("wrong")).unwrap(); - } - "projection" => { - set_field(&mut snap, "observation_journal", Value::List(vec![])).unwrap() - } - _ => { - let Value::Map(fields) = &mut snap else { - panic!() - }; - let (_, Value::List(actions)) = - fields.iter_mut().find(|(k, _)| k == "actions").unwrap() - else { - panic!() - }; - if kind == "truncated" { - actions.pop(); - } else { - let last = actions.last_mut().unwrap(); - match kind { - "unknown" => set_field(last, "kind", t("not-an-operation")).unwrap(), - "index" => set_field(last, "index", Value::Int(0)).unwrap(), - "args" => set_field(last, "args", encode(&Value::Int(1))).unwrap(), - "state" => set_field(last, "state", encode(&Value::None)).unwrap(), - "outcome" => { - set_field(last, "outcome", encode(&Value::Handle("bad".into()))) - .unwrap() - } - _ => unreachable!(), - } - } - } - } - let mut b = DocumentSession::open(&path, &root).unwrap(); - let requests = b.host.foreign_protocol_steps.len(); - assert!( - b.replay_check(&snap).is_err(), - "{kind}: malformed history accepted" - ); - assert_eq!( - b.host.foreign_protocol_steps.len(), - requests, - "{kind}: executed before suffix validation" - ); - assert!(b.action_history.is_empty()); - b.close(); - } - std::fs::remove_file(path).unwrap(); - } - #[test] - fn generated_history_matches_independent_state_and_survives_json_roundtrip() { - // The experiment driver supplies larger budgets; ordinary CI retains the short corpus. - let steps: usize = std::env::var("MARQDO_HISTORY_STEPS") - .map(|s| s.parse().expect("positive history length")) - .unwrap_or(32); - assert!(steps > 0); - let seeds: Vec = std::env::var("MARQDO_HISTORY_SEEDS") - .map(|s| s.split(',').map(|s| s.parse().expect("u64 seed")).collect()) - .unwrap_or_else(|_| vec![3, 11, 29, 71]); - assert!(!seeds.is_empty()); - for lang in ["python", "node"] { - for &seed in &seeds { - let (root, path, source) = fixture(); - let source = source.replace("python", lang); - std::fs::write(&path, &source).unwrap(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - let mut expected = 1i64; - let mut cursor = 0usize; - let mut rng = seed; - let mut operations = [0usize; 13]; - let record_start = std::time::Instant::now(); - for step in 0..steps { - rng = rng - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - let operation = ((rng >> 32) % 13) as usize; - operations[operation] += 1; - match operation { - 0 => { - expected = ((rng >> 40) % 1000) as i64; - a.set_value("py", "n", Value::Int(expected)).unwrap(); - } - 1 => { - a.run_cell("inc", None).unwrap(); - expected += 1; - } - 2 => { - assert!(a.run_cell("bad", None).is_err()); - expected = 99; - } - 3 => { - a.restart_kernel("py").unwrap(); - expected = 1; - } - 4 => { - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(expected)); - } - 5 => { - a.clear_outputs(); - cursor = 0; - } - 6 => { - assert!(a.set_value("py", "n", Value::Int(i64::MAX)).is_err()); - } - 7 => { - a.run_all(false).unwrap(); - expected = 99; - cursor = 3; - } - 8 => { - let result = a.step(); - match cursor { - 0 => { - result.unwrap(); - expected += 1; - cursor = 1; - } - 1 => { - assert!(result.is_err()); - expected = 99; - } - 2 => { - result.unwrap(); - cursor = 3; - } - _ => { - result.unwrap(); - } - } - } - 9 => { - a.restart_all().unwrap(); - expected = 1; - cursor = 0; - } - 10 => { - a.interrupt().unwrap(); - } - 11 => { - a.state_list().unwrap(); - } - _ => { - assert!(a.run_cell("missing", None).is_err()); - } - } - assert_eq!( - a.pull_value("py", "n").unwrap(), - Value::Int(expected), - "{lang} seed {seed} step {step}" - ); - assert_eq!(a.cursor, cursor, "{lang} seed {seed} step {step} cursor"); - } - let record_ns = record_start.elapsed().as_nanos(); - let snapshot_start = std::time::Instant::now(); - let snap = a.export_snapshot().unwrap(); - let snapshot_ns = snapshot_start.elapsed().as_nanos(); - let action_count = a.action_history.len(); - let protocol_count = a.host.foreign_protocol_steps.len(); - let observation_count = a.host.oracle_observations.len(); - let encode_start = std::time::Instant::now(); - let wire = super::super::super::json::stringify(&snap, None).unwrap(); - let encode_ns = encode_start.elapsed().as_nanos(); - let decode_start = std::time::Instant::now(); - let decoded_raw = super::super::super::json::parse(&wire).unwrap(); - let decode_ns = decode_start.elapsed().as_nanos(); - drop(decoded_raw); - let pack_start = std::time::Instant::now(); - let packed = super::super::packing::pack(&snap).unwrap(); - let pack_ns = pack_start.elapsed().as_nanos(); - let compact_nodes = list(&packed, "nodes").unwrap().len(); - let compact_encode_start = std::time::Instant::now(); - let compact_wire = super::super::super::json::stringify(&packed, None).unwrap(); - let compact_encode_ns = compact_encode_start.elapsed().as_nanos(); - let compact_decode_start = std::time::Instant::now(); - let packed = super::super::super::json::parse(&compact_wire).unwrap(); - let compact_decode_ns = compact_decode_start.elapsed().as_nanos(); - let unpack_start = std::time::Instant::now(); - let unpacked = super::super::packing::unpack(&packed).unwrap(); - let unpack_ns = unpack_start.elapsed().as_nanos(); - assert_eq!( - unpacked, snap, - "lossless packing changed the complete history" - ); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - let replay_start = std::time::Instant::now(); - assert_replay(&mut b, &packed); - let replay_ns = replay_start.elapsed().as_nanos(); - assert_eq!(b.pull_value("py", "n").unwrap(), Value::Int(expected)); - assert_eq!(b.cursor, cursor); - b.close(); - std::fs::remove_file(path).unwrap(); - if let Ok(directory) = std::env::var("MARQDO_HISTORY_SNAPSHOT_DIR") { - let directory = PathBuf::from(directory); - std::fs::create_dir_all(&directory).unwrap(); - let Value::Text(raw) = &wire else { - panic!("snapshot text") - }; - let Value::Text(compact) = &compact_wire else { - panic!("snapshot text") - }; - std::fs::write( - directory.join(format!("raw-{lang}-{seed}-{steps}.json")), - raw, - ) - .unwrap(); - std::fs::write( - directory.join(format!("compact-{lang}-{seed}-{steps}.json")), - compact, - ) - .unwrap(); - } - println!( - "HISTORY_METRIC:{}", - serde_json::json!({ - "language": lang, "seed": seed, "steps": steps, - "operations": operations, "actions": action_count, - "protocol_steps": protocol_count, "observations": observation_count, - "snapshot_bytes": match &wire { Value::Text(text) => text.len(), _ => panic!("stringify must return text") }, "record_ns": record_ns, - "snapshot_ns": snapshot_ns, "encode_ns": encode_ns, - "compact_snapshot_bytes": match &compact_wire { Value::Text(text) => text.len(), _ => panic!("stringify must return text") }, - "compact_nodes": compact_nodes, "pack_ns": pack_ns, "unpack_ns": unpack_ns, - "compact_encode_ns": compact_encode_ns, "compact_decode_ns": compact_decode_ns, - "decode_ns": decode_ns, "replay_ns": replay_ns, - "expected_final_value": expected, "expected_cursor": cursor, - "correct": true - }) - ); - } - } - } - - #[test] - fn mismatch_stops_before_dependent_external_effect() { - let (root, path, _) = fixture(); - let marker = path.with_extension("marker"); - let literal = serde_json::to_string(&marker.display().to_string()).unwrap(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.pull_value("py", "n").unwrap(); - a.add_cell( - "touch", - "python", - &format!("with open({literal}, 'w') as out:\n out.write('effect')\nn"), - "py", - ) - .unwrap(); - a.run_cell("touch", None).unwrap(); - assert!(marker.exists()); - let mut snap = a.export_snapshot().unwrap(); - a.close(); - std::fs::remove_file(&marker).unwrap(); - let mut entries = list(&snap, "actions") - .unwrap() - .iter() - .enumerate() - .map(|(i, v)| HistoryEntry::parse(v, i).unwrap()) - .collect::>(); - set_field(&mut entries[0].outcome, "value", Value::Int(2)).unwrap(); - set_field(&mut entries[0].observations[0], "value", Value::Int(2)).unwrap(); - for entry in &mut entries { - let Value::Map(fields) = &mut entry.state else { - panic!() - }; - let (_, Value::List(bindings)) = - fields.iter_mut().find(|(k, _)| k == "values").unwrap() - else { - panic!() - }; - for binding in bindings { - if text(binding, "name").unwrap() == "n" { - set_field(binding, "value", Value::Int(2)).unwrap(); - } - } - } - - set_field( - &mut snap, - "actions", - Value::List(entries.iter().enumerate().map(|(i, e)| e.wire(i)).collect()), - ) - .unwrap(); - set_field( - &mut snap, - "observation_journal", - Value::List( - entries - .iter() - .flat_map(|e| e.observations.clone()) - .collect(), - ), - ) - .unwrap(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - let check = b.replay_check(&snap).unwrap(); - assert_eq!(field(&check, "ok").unwrap(), &Value::Bool(false)); - assert_eq!(field(&check, "executed_actions").unwrap(), &Value::Int(1)); - assert!( - !marker.exists(), - "dependent code ran after a mismatched prefix" - ); - b.close(); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn separate_array_bindings_are_not_a_ragged_metadata_table() { - let (root, path, _) = fixture(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.push_value("py", "left", Value::List(vec![Value::Int(1)])) - .unwrap(); - a.push_value( - "py", - "right", - Value::List(vec![Value::Int(2), Value::Int(3)]), - ) - .unwrap(); - a.state_list().unwrap(); - let snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - assert_replay(&mut b, &snap); - b.close(); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn invalid_import_payload_is_checked_before_any_binding_write() { - let (root, path, _) = fixture(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - let mut invalid = a.export_snapshot().unwrap(); - let Value::Map(fields) = &mut invalid else { - panic!() - }; - let (_, Value::List(kernels)) = fields.iter_mut().find(|(k, _)| k == "kernels").unwrap() - else { - panic!() - }; - set_field( - &mut kernels[0], - "values", - Value::List(vec![ - map(vec![("name", t("n")), ("value", Value::Int(999))]), - map(vec![ - ("name", t("bad")), - ( - "value", - Value::Code(crate::value::CodeBlock { - lang: "python".into(), - source: "1".into(), - }), - ), - ]), - ]), - ) - .unwrap(); - let requests = a.host.foreign_protocol_steps.len(); - assert!(a.import_snapshot(&invalid).is_err()); - assert_eq!( - a.host.foreign_protocol_steps.len(), - requests, - "invalid imported code caused a partial foreign write" - ); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(1)); - let snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - assert_replay(&mut b, &snap); - b.close(); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn failed_reload_input_is_an_explicit_historical_input() { - let (root, path, source) = fixture(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - std::fs::remove_file(&path).unwrap(); - assert!(a.reload(&root).is_err()); - std::fs::write(&path, &source).unwrap(); - a.run_cell("inc", None).unwrap(); - let snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - assert_replay(&mut b, &snap); - assert_eq!(std::fs::read_to_string(&path).unwrap(), source); - b.close(); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn failed_introspection_replies_are_not_silently_ignored() { - let (root, path, _) = fixture(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - a.add_cell( - "function", - "python", - "def unsupported(): return 1\nunsupported", - "py", - ) - .unwrap(); - assert!(a.run_cell("function", None).is_err()); - let mut snap = a.export_snapshot().unwrap(); - a.close(); - let mut entries = list(&snap, "actions") - .unwrap() - .iter() - .enumerate() - .map(|(i, row)| HistoryEntry::parse(row, i).unwrap()) - .collect::>(); - let inspect = entries.last_mut().unwrap(); - let mut changed = false; - for step in &mut inspect.protocol { - let response = field(step, "response").unwrap(); - if boolean(response, "ok").unwrap() { - let mut raw: serde_json::Value = - serde_json::from_str(text(response, "json").unwrap()).unwrap(); - if raw.get("domain_error").and_then(|v| v.as_bool()) == Some(true) { - raw["error"] = - serde_json::Value::String("not JSON-safe: changed diagnostic".into()); - let Value::Map(fields) = step else { panic!() }; - let (_, response) = fields.iter_mut().find(|(k, _)| k == "response").unwrap(); - set_field(response, "json", t(&raw.to_string())).unwrap(); - changed = true; - break; - } - } - } - assert!( - changed, - "fixture must contain a refused introspection response" - ); - set_field( - &mut snap, - "actions", - Value::List(entries.iter().enumerate().map(|(i, e)| e.wire(i)).collect()), - ) - .unwrap(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - let check = b.replay_check(&snap).unwrap(); - assert_eq!(field(&check, "ok").unwrap(), &Value::Bool(false)); - assert!(field(&check, "action_checks") - .unwrap() - .as_display() - .contains("protocol")); - b.close(); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn repeated_process_death_history_has_stable_failure_observations() { - for lang in ["python", "node"] { - for _ in 0..4 { - let (root, path, source) = fixture(); - let source = source.replace("python", lang).replace( - "n = 99\n2**53", - if lang == "python" { - "import os\nos._exit(7)" - } else { - "process.exit(7)" - }, - ); - std::fs::write(&path, &source).unwrap(); - let mut a = DocumentSession::open(&path, &root).unwrap(); - let record = a.run_cell("bad", None).unwrap(); - assert_eq!(field(&record, "ok").unwrap(), &Value::Bool(false)); - assert_eq!(a.pull_value("py", "n").unwrap(), Value::Int(1)); - let snap = a.export_snapshot().unwrap(); - a.close(); - let mut b = DocumentSession::open(&path, &root).unwrap(); - assert_replay(&mut b, &snap); - b.close(); - std::fs::remove_file(path).unwrap(); - } - } - } -} - -impl DocumentSession { - /// Validate and compare a recording without touching an existing live view. - /// No declarations or seed kernels run before the history preflight. - pub(crate) fn check_snapshot_isolated( - path: &Path, - root: &Path, - snapshot: &Value, - ) -> Result { - let source = - std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?; - let mut host = HostContext::default(); - host.cwd = path.parent().unwrap_or_else(|| Path::new(".")).into(); - host.fs_root = Some(root.into()); - host.entry_path = Some(path.into()); - host.entry_source = Some(source.clone()); - let mut target = Self { - control: super::DocumentControl::default(), - replay_controls: Vec::new(), - replay_boundary: None, - source_hash: hash_source(&source), - initial_values: Vec::new(), - initial_image: Value::None, - action_history: Vec::new(), - action_depth: 0, - replay_fresh: true, - path: path.into(), - root: root.into(), - persistent: false, - cells: Vec::new(), - kernels: Vec::new(), - order: Vec::new(), - journal: Vec::new(), - oracle_journal: Vec::new(), - value_store: HashMap::new(), - cursor: 0, - generation: 1, - opened_ms: now_ms(), - host, - kernel_sessions: HashMap::new(), - seq: 0, - }; - target.replay_check(snapshot) - } -} diff --git a/src/host/foreign_session.rs b/src/host/foreign_session.rs deleted file mode 100755 index bb1516a..0000000 --- a/src/host/foreign_session.rs +++ /dev/null @@ -1,1277 +0,0 @@ -//! Persistent foreign kernels (Python / Node) and the session state bridge. -//! -//! Protocol: one JSON request per stdin line, one JSON response per original -//! stdout line. User stdout/stderr are captured inside the bootstrap. - -use crate::host::as_text; -use std::io::{BufRead, BufReader, Read, Write}; -use std::process::{Child, Command, Stdio}; -use std::sync::mpsc::{self, Receiver}; -use std::sync::{Arc, Mutex}; -use std::thread::{self, JoinHandle}; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; - -use crate::host::foreign::{ensure_config, resolve_session_spec}; -use crate::host::json::{json_to_value, value_to_json}; -use crate::host::HostContext; -use crate::value::Value; - -mod control; -pub mod validation; -pub use control::InterruptHandle; - -const SESSION_TIMEOUT_SECS: f64 = 10.0; -const MAX_SESSION_TIMEOUT_SECS: f64 = 3600.0; -const MAX_PROCESS_STDERR: usize = 1_048_576; - -const PY_BOOTSTRAP: &str = r#"import sys, json, io, ast, traceback, contextlib, math, signal -_out = sys.stdout -_MAX_SAFE = 9007199254740991 -def _sanitize(o): - if o is None or isinstance(o, bool): - return o - if isinstance(o, int): - if abs(o) > _MAX_SAFE: - raise ValueError("json: integer outside V_safe (±(2^53-1)): %s" % o) - return o - if isinstance(o, float): - if not math.isfinite(o): - raise ValueError("json: non-finite number outside V_safe") - if o.is_integer() and abs(o) > _MAX_SAFE: - raise ValueError("json: integer outside V_safe (±(2^53-1)): %s" % o) - return o - if isinstance(o, str): - return o - if isinstance(o, (list, tuple)): - return [_sanitize(x) for x in o] - if isinstance(o, dict): - if any(not isinstance(k, str) for k in o): - raise TypeError("not JSON-safe: object keys must be strings") - return {k: _sanitize(v) for k, v in o.items()} - raise TypeError("not JSON-safe: %s" % type(o).__name__) -def _send(o): - try: - line = json.dumps(_sanitize(o), ensure_ascii=False) - except Exception as e: - rid = o.get("id") if isinstance(o, dict) else None - line = json.dumps({ - "id": rid, "ok": False, - "stdout": (o.get("stdout") if isinstance(o, dict) else "") or "", - "stderr": (o.get("stderr") if isinstance(o, dict) else "") or "", - "result": None, "error": str(e), "domain_error": True, - }, ensure_ascii=False) - _out.write(line + "\n") - _out.flush() -_busy = False -def _interrupt(signum, frame): - global _busy - if _busy: - _busy = False - raise KeyboardInterrupt -signal.signal(signal.SIGINT, _interrupt) -_g = {"__name__": "__main__", "marqdo_input": None} -for _line in sys.stdin: - _line = _line.strip() - if not _line: - continue - try: - req = json.loads(_line) - except Exception: - _send({"id": None, "ok": False, "stdout": "", "stderr": "", "result": None, "error": "bad request"}) - continue - rid = req.get("id") - op = req.get("op", "eval") - if op == "set": - _g[req.get("name")] = req.get("value") - _send({"id": rid, "ok": True, "stdout": "", "stderr": "", "result": None, "error": ""}) - continue - if op == "get": - try: - _val = _g[req.get("name")] - except KeyError: - _val = None - _send({"id": rid, "ok": True, "stdout": "", "stderr": "", "result": _val, "error": ""}) - continue - if op == "names": - _names = sorted(k for k in _g.keys() if not k.startswith("__")) - _send({"id": rid, "ok": True, "stdout": "", "stderr": "", "result": _names, "error": ""}) - continue - _code = req.get("code", "") - _g["marqdo_input"] = req.get("input") - _old_stdin = sys.stdin - if req.get("stdin") is not None: - sys.stdin = io.StringIO(str(req.get("stdin"))) - _out_buf = io.StringIO() - _err_buf = io.StringIO() - try: - _busy = True - _send({"id": rid, "phase": "ready"}) - _tree = ast.parse(_code, "") - _result = None - with contextlib.redirect_stdout(_out_buf), contextlib.redirect_stderr(_err_buf): - if _tree.body and isinstance(_tree.body[-1], ast.Expr): - _last = _tree.body.pop() - if _tree.body: - exec(compile(_tree, "", "exec"), _g) - _result = eval(compile(ast.Expression(_last.value), "", "eval"), _g) - else: - exec(compile(_tree, "", "exec"), _g) - _busy = False - _send({"id": rid, "ok": True, "stdout": _out_buf.getvalue(), "stderr": _err_buf.getvalue(), "result": _result, "error": ""}) - except BaseException: - _busy = False - _send({"id": rid, "ok": False, "stdout": _out_buf.getvalue(), "stderr": _err_buf.getvalue(), "result": None, "error": traceback.format_exc(limit=8)}) - finally: - _busy = False - sys.stdin = _old_stdin -"#; - -const JS_BOOTSTRAP: &str = r#"const readline = require("readline"); -const util = require("util"); -const vm = require("vm"); -const out = process.stdout.write.bind(process.stdout); -process.on("SIGINT", () => {}); -const MAX_SAFE = Number.MAX_SAFE_INTEGER; -globalThis.require = require; -const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); -function sanitize(v, active = new Set()) { - if (v === null || typeof v === "boolean" || typeof v === "string") return v; - if (typeof v === "number") { - if (!Number.isFinite(v)) throw new Error("json: non-finite number outside V_safe"); - if (Number.isInteger(v) && Math.abs(v) > MAX_SAFE) - throw new Error("json: integer outside V_safe (±(2^53-1)): " + v); - return v; - } - if (typeof v === "bigint") { - if (v > BigInt(MAX_SAFE) || v < -BigInt(MAX_SAFE)) - throw new Error("json: integer outside V_safe (±(2^53-1)): " + v.toString()); - return Number(v); - } - if (v && typeof v === "object") { - if (active.has(v)) throw new Error("not JSON-safe: cyclic value"); - active.add(v); - try { - const keys = Reflect.ownKeys(v); - if (Array.isArray(v)) { - if (keys.length !== v.length + 1) - throw new Error("not JSON-safe: sparse array or extra array properties"); - const rows = []; - for (let i = 0; i < v.length; i++) { - const d = Object.getOwnPropertyDescriptor(v, String(i)); - if (!d || !d.enumerable || !("value" in d)) - throw new Error("not JSON-safe: array accessor or missing element"); - rows.push(sanitize(d.value, active)); - } - return rows; - } - const prototype = Object.getPrototypeOf(v); - if (prototype !== Object.prototype && prototype !== null) - throw new Error("not JSON-safe: expected plain record"); - const o = Object.create(null); - for (const k of keys) { - if (typeof k !== "string") throw new Error("not JSON-safe: symbol record key"); - const d = Object.getOwnPropertyDescriptor(v, k); - if (!d || !d.enumerable || !("value" in d)) - throw new Error("not JSON-safe: record accessor or hidden property"); - o[k] = sanitize(d.value, active); - } - return o; - } finally { active.delete(v); } - } - throw new Error("not JSON-safe: " + (typeof v)); -} -function send(o) { - try { out(JSON.stringify(sanitize(o)) + "\n"); } - catch (e) { - out(JSON.stringify({ - id: o && o.id !== undefined ? o.id : null, ok: false, - stdout: (o && o.stdout) || "", stderr: (o && o.stderr) || "", - result: null, error: String(e && e.message ? e.message : e), domain_error: true - }) + "\n"); - } -} -function toJSON(v) { return sanitize(v); } -async function capture(fn) { - const logs = [], errs = []; - const ow = process.stdout.write.bind(process.stdout); - const ew = process.stderr.write.bind(process.stderr); - const ol = console.log, oi = console.info, owr = console.warn, oe = console.error; - console.log = console.info = (...a) => { logs.push(util.format(...a) + "\n"); }; - console.warn = console.error = (...a) => { errs.push(util.format(...a) + "\n"); }; - process.stdout.write = (c) => { logs.push(String(c)); return true; }; - process.stderr.write = (c) => { errs.push(String(c)); return true; }; - let result, error = ""; - try { result = await fn(); } catch (e) { error = (e && e.stack) || String(e); } - process.stdout.write = ow; process.stderr.write = ew; - console.log = ol; console.info = oi; console.warn = owr; console.error = oe; - return { logs: logs.join(""), errs: errs.join(""), result: result === undefined ? null : result, error }; -} -rl.on("line", async (line) => { - let req; - try { req = JSON.parse(line); } catch (e) { send({ id: null, ok: false, stdout: "", stderr: "", result: null, error: "bad request" }); return; } - const rid = req.id, op = req.op || "eval"; - if (op === "set") { globalThis[req.name] = req.value; send({ id: rid, ok: true, stdout: "", stderr: "", result: null, error: "" }); return; } - if (op === "get") { - let result = null; - try { result = vm.runInThisContext(String(req.name), { filename: "" }); } - catch (e) { result = globalThis[req.name] === undefined ? null : globalThis[req.name]; } - send({ id: rid, ok: true, stdout: "", stderr: "", result: result, error: "" }); - return; - } - if (op === "names") { - const skip = new Set(["global","globalThis","process","Buffer","console","require","module","exports","__dirname","__filename","performance","crypto","navigator","fetch","URL","URLSearchParams","TextEncoder","TextDecoder","setTimeout","clearTimeout","setInterval","clearInterval","queueMicrotask","structuredClone","atob","btoa","marqdo_input"]); - const names = Object.keys(globalThis).filter(k => !k.startsWith("__") && !skip.has(k) && typeof globalThis[k] !== "function"); - send({ id: rid, ok: true, stdout: "", stderr: "", result: names, error: "" }); - return; - } - globalThis.marqdo_input = req.input === undefined ? null : req.input; - const oldStdin = process.stdin; - let stdinPatched = false; - if (req.stdin !== undefined && req.stdin !== null) { - try { - const { PassThrough } = require("stream"); - const ps = new PassThrough(); - ps.end(String(req.stdin)); - Object.defineProperty(process, "stdin", { value: ps, configurable: true, writable: true }); - stdinPatched = true; - } catch (e) {} - } - send({ id: rid, phase: "ready" }); - const cap = await capture(async () => vm.runInThisContext(req.code || "", { filename: "", breakOnSigint: true })); - if (stdinPatched) { - try { Object.defineProperty(process, "stdin", { value: oldStdin, configurable: true, writable: true }); } catch (e) {} - } - send({ id: rid, ok: !cap.error, stdout: cap.logs, stderr: cap.errs, result: cap.result, error: cap.error }); -}); -"#; - -/// Internal protocol evidence, distinct from admitted language observations. -/// Includes failed requests and post-execution domain refusals, so set/input -/// dependencies cannot disappear from the recorded history. -#[derive(Debug, Clone)] -pub struct ProtocolStep { - pub session: String, - pub request: serde_json::Value, - pub response: Result, -} - -pub struct Session { - pub interrupt_handle: InterruptHandle, - pub id: String, - pub lang: String, - pub cmd: String, - pub started_ms: i64, - pub timeout: Duration, - pub evals: u64, - pub alive: bool, - child: Child, - stdin: std::process::ChildStdin, - rx: Receiver, - _reader: JoinHandle<()>, - stderr: Arc>, - _stderr_reader: JoinHandle<()>, -} - -impl std::fmt::Debug for Session { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Session") - .field("id", &self.id) - .field("lang", &self.lang) - .field("evals", &self.evals) - .field("alive", &self.alive) - .finish() - } -} - -impl Drop for Session { - fn drop(&mut self) { - if let Some(_pid) = self.interrupt_handle.retire() { - #[cfg(unix)] - unsafe { libc::kill(-(_pid as i32), libc::SIGKILL); } - let _ = self.child.kill(); - } - let _ = self.child.wait(); - } -} - - -fn opt_text(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(None), - Some(Value::Text(s)) => Ok(Some(s.clone())), - Some(Value::Secret(s)) => Ok(Some(s.clone())), - Some(_) => Err("value must be text".into()), - } -} - -/// Session ids are opaque handles — text fabrications are refused. -fn as_session_id<'a>(id: &'a Value) -> Result<&'a str, String> { - match id { - Value::Handle(s) => Ok(s.as_str()), - Value::Text(_) => Err("session id must be a handle (not text)".into()), - _ => Err("session id must be a handle".into()), - } -} - -fn parse_timeout(v: Option<&Value>, default: f64) -> Result { - let secs = match v { - None | Some(Value::None) => default, - Some(Value::Int(n)) => *n as f64, - Some(Value::Num(n)) => *n, - Some(_) => return Err("timeout must be a number of seconds".into()), - }; - if !secs.is_finite() || secs <= 0.0 { - return Err("timeout must be > 0 seconds".into()); - } - Ok(Duration::from_secs_f64(secs.min(MAX_SESSION_TIMEOUT_SECS))) -} - -fn parse_env(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(Vec::new()), - Some(Value::Map(entries)) => Ok(entries - .iter() - .map(|(k, v)| { - let val = match v { - Value::Secret(s) => s.clone(), - other => other.as_display(), - }; - (k.clone(), val) - }) - .collect()), - Some(_) => Err("env must be a map".into()), - } -} - -fn record( - id: Option<&str>, - lang: &str, - cmd: &str, - ok: bool, - stdout: String, - stderr: String, - result: Value, - error: String, - ms: u64, - timed_out: bool, - alive: bool, -) -> Value { - let mut fields = vec![ - ("ok".into(), Value::Bool(ok)), - ("code".into(), Value::Int(if ok { 0 } else { -1 })), - ("stdout".into(), Value::Text(stdout)), - ("stderr".into(), Value::Text(stderr)), - ("ms".into(), Value::Int(ms as i64)), - ("lang".into(), Value::Text(lang.to_string())), - ("cmd".into(), Value::Text(cmd.to_string())), - ("timed_out".into(), Value::Bool(timed_out)), - ("truncated".into(), Value::Bool(false)), - ("result".into(), result), - ("result_error".into(), Value::Text(String::new())), - ("error".into(), Value::Text(error)), - ("script".into(), Value::Text(String::new())), - ("cached".into(), Value::Bool(false)), - ("alive".into(), Value::Bool(alive)), - ]; - if let Some(id) = id { - fields.push(("id".into(), Value::Text(id.to_string()))); - } - Value::Map(fields) -} - -fn now_ms() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_millis() as i64) - .unwrap_or(0) -} - -pub fn open( - ctx: &mut HostContext, - lang: &Value, - cmd: Option<&Value>, - env: Option<&Value>, - cwd: Option<&Value>, - timeout: Option<&Value>, -) -> Result { - ensure_config(ctx); - if !ctx.allow_exec() { - return Err("foreign session denied by host policy".into()); - } - let requested = as_text(lang, "lang")?.to_ascii_lowercase(); - let canonical = crate::foreign::registry::canonical(&requested); - if !crate::foreign::registry::session_supported(&canonical) { - return Err(format!( - "lang=`{canonical}` has no session bootstrap; use run/invoke" - )); - } - let spec = resolve_session_spec(ctx, &canonical)?; - let mut argv = match opt_text(cmd)? { - Some(c) => { - let argv = crate::foreign::split_cmd_line(&c); - if argv.is_empty() { - return Err("session cmd override is empty".into()); - } - argv - } - None => spec.argv.clone(), - }; - if argv.is_empty() { - return Err(format!("no interpreter configured for lang=`{canonical}`")); - } - match canonical.as_str() { - "python" => { - argv.push("-u".into()); - argv.push("-c".into()); - argv.push(PY_BOOTSTRAP.into()); - } - "node" => { - argv.push("-e".into()); - argv.push(JS_BOOTSTRAP.into()); - } - _ => return Err(format!("lang=`{canonical}` has no session bootstrap")), - } - let cwd_path = match opt_text(cwd)? { - Some(c) => ctx.resolve_path(&c)?, - None => ctx.cwd.clone(), - }; - if !cwd_path.is_dir() { - return Err(format!( - "session cwd is not a directory: {}", - cwd_path.display() - )); - } - let session_timeout = parse_timeout(timeout, SESSION_TIMEOUT_SECS)?; - let mut command = Command::new(&argv[0]); - for a in &argv[1..] { - command.arg(a); - } - command.current_dir(&cwd_path); - command.stdin(Stdio::piped()); - command.stdout(Stdio::piped()); - command.stderr(Stdio::piped()); - command.env("MARQDO_FOREIGN", "1"); - command.env("MARQDO_FOREIGN_LANG", &canonical); - command.env("MARQDO_FOREIGN_CWD", &cwd_path); - for (k, v) in &spec.env { - command.env(k, v); - } - for (k, v) in parse_env(env)? { - command.env(k, v); - } - command.env("PYTHONUNBUFFERED", "1"); - command.env("PYTHONIOENCODING", "utf-8"); - command.env("PYTHONUTF8", "1"); - #[cfg(unix)] - { - use std::os::unix::process::CommandExt; - command.process_group(0); - } - let mut child = command.spawn().map_err(|e| { - format!( - "foreign session spawn failed (lang={canonical}, cmd={}): {e}", - argv[0] - ) - })?; - let stdin = child - .stdin - .take() - .ok_or_else(|| "session stdin unavailable".to_string())?; - let stdout = child - .stdout - .take() - .ok_or_else(|| "session stdout unavailable".to_string())?; - let stderr_pipe = child.stderr.take(); - let (tx, rx) = mpsc::channel::(); - let reader = thread::spawn(move || { - let mut reader = BufReader::new(stdout); - let mut line = String::new(); - loop { - line.clear(); - match reader.read_line(&mut line) { - Ok(0) => { - let _ = tx.send("__EOF__".into()); - break; - } - Ok(_) => { - let _ = tx.send(line.trim_end_matches(['\r', '\n']).to_string()); - } - Err(_) => { - let _ = tx.send("__EOF__".into()); - break; - } - } - } - }); - let stderr_buf = Arc::new(Mutex::new(String::new())); - let stderr_buf_t = Arc::clone(&stderr_buf); - let stderr_reader = thread::spawn(move || { - if let Some(mut r) = stderr_pipe { - let mut kept = Vec::new(); - let mut buf = [0u8; 8192]; - loop { - match r.read(&mut buf) { - Ok(0) => break, - Ok(n) => { - if kept.len() < MAX_PROCESS_STDERR { - let take = (MAX_PROCESS_STDERR - kept.len()).min(n); - kept.extend_from_slice(&buf[..take]); - } - } - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, - Err(_) => break, - } - } - if let Ok(mut s) = stderr_buf_t.lock() { - s.push_str(&String::from_utf8_lossy(&kept)); - } - } - }); - let seq = ctx.foreign_session_seq + 1; - ctx.foreign_session_seq = seq; - let id = format!("s{seq}"); - let started_ms = now_ms(); - let cmd_display = argv[0].clone(); - let session = Session { - interrupt_handle: InterruptHandle::new(child.id()), - id: id.clone(), - lang: canonical.clone(), - cmd: cmd_display.clone(), - started_ms, - timeout: session_timeout, - evals: 0, - alive: true, - child, - stdin, - rx, - _reader: reader, - stderr: stderr_buf, - _stderr_reader: stderr_reader, - }; - ctx.foreign_sessions.insert(id.clone(), session); - let _ = timeout; - Ok(Value::Handle(id)) -} - -fn session_dead_stderr(ctx: &HostContext, id: &str) -> String { - ctx.foreign_sessions - .get(id) - .and_then(|s| s.stderr.lock().ok().map(|v| v.clone())) - .unwrap_or_default() -} - -fn remove_session(ctx: &mut HostContext, id: &str) { - ctx.foreign_sessions.remove(id); -} - -pub fn eval( - ctx: &mut HostContext, - id: &Value, - code: Option<&Value>, - source: Option<&Value>, - input: Option<&Value>, - timeout: Option<&Value>, -) -> Result { - eval_with_stdin(ctx, id, code, source, input, None, timeout) -} - -pub fn eval_with_stdin( - ctx: &mut HostContext, - id: &Value, - code: Option<&Value>, - source: Option<&Value>, - input: Option<&Value>, - stdin: Option<&str>, - timeout: Option<&Value>, -) -> Result { - ensure_config(ctx); - let id = as_session_id(id)?.to_string(); - if !ctx.foreign_sessions.contains_key(&id) { - return Err(format!("foreign session `{id}` not found")); - } - let session_lang = ctx.foreign_sessions[&id].lang.clone(); - let code = match (present(code), present(source)) { - (Some(_), Some(_)) => { - return Err("session_eval: pass either code or source, not both".into()) - } - (Some(c), None) => match c { - Value::Code(b) => { - if crate::foreign::registry::canonical(&b.lang) != session_lang { - return Err(format!( - "session_eval code language `{}` does not match session language `{}`", - b.lang, session_lang - )); - } - b.source.clone() - } - _ => return Err("session_eval code must be a code value".into()), - }, - (None, Some(s)) => as_text(s, "source")?.to_string(), - (None, None) => return Err("session_eval needs code or source".into()), - }; - let input_json = match input { - None | Some(Value::None) => serde_json::Value::Null, - Some(v) => { super::oracle::admit(v)?; value_to_json(v)? }, - }; - let default_timeout = ctx.foreign_sessions[&id].timeout.as_secs_f64(); - let dur = parse_timeout(timeout, default_timeout)?; - let request = serde_json::json!({ - "id": 1, - "op": "eval", - "code": code, - "input": input_json, - "stdin": stdin, - }); - let start = Instant::now(); - let (lang, cmd) = { - let s = &ctx.foreign_sessions[&id]; - (s.lang.clone(), s.cmd.clone()) - }; - let reply = match send_and_wait(ctx, &id, &request, dur) { - Ok(r) => r, - Err(e) => { - // Replay divergence is a language-level stop, not process death or - // an ordinary failed-eval value. Keep the actual committed kernel. - if ctx.foreign_replay_divergence.is_some() { return Err(e); } - let timed_out = e.contains("timed out"); - let stderr = session_dead_stderr(ctx, &id); - remove_session(ctx, &id); - return Ok(record( - Some(&id), - &lang, - &cmd, - false, - String::new(), - stderr, - Value::None, - e, - start.elapsed().as_millis() as u64, - timed_out, - false, - )); - } - }; - let ms = start.elapsed().as_millis() as u64; - let alive = ctx - .foreign_sessions - .get_mut(&id) - .map(|s| { - s.evals += 1; - s.alive - }) - .unwrap_or(false); - let ok = reply - .get("ok") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let stdout = reply - .get("stdout") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let stderr = reply - .get("stderr") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let error = reply - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - // Ω ∉ V_safe is a language fault, not a soft cell failure. - if reply.get("domain_error").and_then(|v| v.as_bool()) == Some(true) { - return Err(error); - } - let result = reply - .get("result") - .map(json_to_value) - .transpose()? - .unwrap_or(Value::None); - super::oracle::admit(&result)?; - Ok(record( - Some(&id), - &lang, - &cmd, - ok, - stdout, - stderr, - result, - error, - ms, - false, - alive, - )) -} - -fn present(v: Option<&Value>) -> Option<&Value> { - match v { - None | Some(Value::None) => None, - Some(x) => Some(x), - } -} - -fn send_and_wait( - ctx: &mut HostContext, - id: &str, - request: &serde_json::Value, - timeout: Duration, -) -> Result { - if ctx.foreign_replay_expected.is_some() { - if let Some(error) = &ctx.foreign_replay_divergence { return Err(error.clone()); } - } - let permit = validation::prepare(ctx.foreign_replay_expected.as_mut(), id, request) - .map_err(|failure| { - let error = failure.to_string(); - ctx.foreign_replay_divergence = Some(error.clone()); - error - })?; - let control = ctx.foreign_sessions.get(id).map(|s| s.interrupt_handle.clone()); - if let Some(handle) = &control { handle.begin(request.get("op").and_then(|v| v.as_str()) == Some("eval")); } - let response = send_and_wait_inner(ctx, permit, timeout); - if let Some(handle) = control { handle.finish(); } - ctx.foreign_protocol_steps.push(ProtocolStep { - session: id.to_string(), request: request.clone(), response: response.clone(), - }); - if let Some(steps) = &mut ctx.foreign_replay_expected { - if let Err(failure) = steps.accept_response(&response) { - let error = failure.to_string(); - ctx.foreign_replay_divergence = Some(error.clone()); - return Err(error); - } - } - response -} - -fn send_control( - ctx: &mut HostContext, id: &str, request: &serde_json::Value, -) -> Result { - let response = send_and_wait(ctx, id, request, Duration::from_secs(10)); - if response.is_err() && ctx.foreign_replay_divergence.is_none() { remove_session(ctx, id); } - response -} - -fn send_and_wait_inner( - ctx: &mut HostContext, - permit: validation::DispatchPermit, - timeout: Duration, -) -> Result { - let id = permit.session(); - let request = permit.request(); - let line = serde_json::to_string(request).map_err(|e| format!("session request: {e}"))?; - { - let session = ctx - .foreign_sessions - .get_mut(id) - .ok_or_else(|| format!("foreign session `{id}` not found"))?; - if let Ok(Some(_)) = session.interrupt_handle.try_wait(&mut session.child) { - return Err("session process exited".into()); - } - session - .stdin - .write_all(line.as_bytes()) - .and_then(|_| session.stdin.write_all(b"\n")) - .and_then(|_| session.stdin.flush()) - .map_err(|e| format!("session write: {e}"))?; - } - let deadline = Instant::now() + timeout; - loop { - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - kill_session(ctx, id); - return Err(format!( - "session timed out after {:.3}s", - timeout.as_secs_f64() - )); - } - let session = ctx - .foreign_sessions - .get_mut(id) - .ok_or_else(|| format!("foreign session `{id}` not found"))?; - match session.rx.recv_timeout(remaining.min(Duration::from_millis(200))) { - Ok(line) => { - if line == "__EOF__" { - return Err("session process exited".into()); - } - if let Ok(v) = serde_json::from_str::(&line) { - let rid = v.get("id").and_then(|x| x.as_u64()).unwrap_or(0); - if rid != 1 { - continue; - } - if v.get("phase").and_then(|v| v.as_str()) == Some("ready") { - session.interrupt_handle.ready()?; - continue; - } - return Ok(v); - } - // Unexpected non-protocol output: keep waiting until the deadline. - continue; - } - Err(mpsc::RecvTimeoutError::Timeout) => { - session.interrupt_handle.retry()?; - if let Ok(Some(_)) = session.interrupt_handle.try_wait(&mut session.child) { - return Err("session process exited".into()); - } - continue; - } - Err(mpsc::RecvTimeoutError::Disconnected) => { - return Err("session reader disconnected".into()) - } - } - } -} - -fn kill_session(ctx: &mut HostContext, id: &str) { - if let Some(mut s) = ctx.foreign_sessions.remove(id) { - if let Some(_pid) = s.interrupt_handle.retire() { - #[cfg(unix)] - unsafe { - libc::kill(-(_pid as i32), libc::SIGKILL); - } - let _ = s.child.kill(); - } - let _ = s.child.wait(); - s.alive = false; - } -} - -/// Interrupt the current evaluation without destroying the kernel. Python -/// reports KeyboardInterrupt through the normal result frame. -pub fn interrupt(ctx: &mut HostContext, id: &Value) -> Result { - let id = as_session_id(id)?.to_string(); - let session = ctx - .foreign_sessions - .get_mut(&id) - .ok_or_else(|| format!("foreign session `{id}` not found"))?; - session.interrupt_handle.request()?; - Ok(Value::Bool(true)) -} - -pub fn set( - ctx: &mut HostContext, - id: &Value, - name: &Value, - value: &Value, -) -> Result { - let id = as_session_id(id)?.to_string(); - if !ctx.foreign_sessions.contains_key(&id) { - return Err(format!("foreign session `{id}` not found")); - } - let name = as_text(name, "name")?.to_string(); - if !valid_name(&name) { - return Err("session_set: name must be an identifier".into()); - } - super::oracle::admit(value)?; - let json = value_to_json(value)?; - let request = serde_json::json!({"id": 1, "op": "set", "name": name, "value": json}); - let reply = send_control(ctx, &id, &request)?; - if reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) { - Ok(Value::None) - } else { - Err(reply - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("session_set failed") - .to_string()) - } -} - -pub fn get(ctx: &mut HostContext, id: &Value, name: &Value) -> Result { - let id = as_session_id(id)?.to_string(); - if !ctx.foreign_sessions.contains_key(&id) { - return Err(format!("foreign session `{id}` not found")); - } - let name = as_text(name, "name")?.to_string(); - if !valid_name(&name) { - return Err("session_get: name must be an identifier".into()); - } - let request = serde_json::json!({"id": 1, "op": "get", "name": name}); - let reply = send_control(ctx, &id, &request)?; - if !reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) { - return Err(reply - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("session_get failed") - .to_string()); - } - let value = match reply.get("result") { - Some(v) => json_to_value(v), - None => Ok(Value::None), - }?; - super::oracle::admit(&value)?; - Ok(value) -} - -pub fn names(ctx: &mut HostContext, id: &Value) -> Result { - let id = as_session_id(id)?.to_string(); - if !ctx.foreign_sessions.contains_key(&id) { - return Err(format!("foreign session `{id}` not found")); - } - let request = serde_json::json!({"id": 1, "op": "names"}); - let reply = send_control(ctx, &id, &request)?; - if !reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) { - return Err(reply - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("session_names failed") - .to_string()); - } - match reply.get("result") { - Some(v) => json_to_value(v), - None => Ok(Value::List(Vec::new())), - } -} - -pub fn close(ctx: &mut HostContext, id: &Value) -> Result { - let id = as_session_id(id)?.to_string(); - // Affine close: consuming an absent / already-closed handle is a fault - // (same surface as eval/set/get after close). - if !ctx.foreign_sessions.contains_key(&id) { - return Err(format!("foreign session `{id}` not found")); - } - kill_session(ctx, &id); - Ok(Value::Bool(true)) -} - -pub fn list(ctx: &HostContext) -> Result { - let mut sessions: Vec<&Session> = ctx.foreign_sessions.values().collect(); - sessions.sort_by(|a, b| a.id.cmp(&b.id)); - let mut out = Vec::new(); - for s in sessions { - out.push(Value::Map(vec![ - ("id".into(), Value::Handle(s.id.clone())), - ("lang".into(), Value::Text(s.lang.clone())), - ("cmd".into(), Value::Text(s.cmd.clone())), - ("evals".into(), Value::Int(s.evals as i64)), - ("alive".into(), Value::Bool(s.alive)), - ("started_ms".into(), Value::Int(s.started_ms)), - ])); - } - Ok(Value::List(out)) -} - -pub fn shutdown(ctx: &mut HostContext) { - let ids: Vec = ctx.foreign_sessions.keys().cloned().collect(); - for id in ids { - kill_session(ctx, &id); - } -} - -pub(crate) fn valid_name(name: &str) -> bool { - let mut chars = name.chars(); - match chars.next() { - Some(c) if c == '_' || c.is_ascii_alphabetic() => {} - _ => return false, - } - chars.all(|c| c == '_' || c.is_ascii_alphanumeric()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn identifiers() { - assert!(valid_name("x")); - assert!(valid_name("_x1")); - assert!(!valid_name("1x")); - assert!(!valid_name("a-b")); - } - #[test] - fn bridge_live_boundary_and_refusal_preserves_input_store() { - let edge = 9_007_199_254_740_991i64; - for lang in ["python", "node"] { - let mut ctx = HostContext::default(); - let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - let name = Value::Text("payload".into()); - for n in [i64::MIN, -edge-1, -edge, -edge+1, -1, 0, 1, edge-1, edge, edge+1, i64::MAX] { - set(&mut ctx, &id, &name, &Value::Int(17)).unwrap(); - let input = Value::List(vec![Value::Text("中文🧪".into()), Value::List(vec![Value::Int(n)])]); - let result = set(&mut ctx, &id, &name, &input); - if (-edge..=edge).contains(&n) { - result.unwrap(); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), input, "{lang} {n}"); - } else { - assert!(result.unwrap_err().contains("outside V_safe")); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(17)); - } - println!("E4 {lang} integer {n}: verified"); - } - for source in if lang == "python" { - ["2**53", "float('nan')", "float('inf')"] - } else { ["2**53", "NaN", "Infinity"] } { - let error = eval(&mut ctx, &id, None, Some(&Value::Text(source.into())), None, None).unwrap_err(); - assert!(error.contains("outside V_safe"), "{lang} {source}: {error}"); - // A refused response must remain a protocol response, not kill Node. - assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(17)); - println!("E4 {lang} response {source}: refused, session responsive"); - } - let alias = id.clone(); - close(&mut ctx, &id).unwrap(); - // Missing handle wins over an invalid name and an OOD payload. - let err = set(&mut ctx, &alias, &Value::Text("bad-name".into()), &Value::Int(i64::MAX)).unwrap_err(); - assert!(err.contains("not found"), "{err}"); - assert!(get(&mut ctx, &alias, &name).is_err()); - assert!(close(&mut ctx, &alias).is_err()); - assert!(ctx.foreign_sessions.is_empty()); - } - } - - #[test] - fn generated_two_session_model_traces() { - for lang in ["python", "node"] { - let mut ctx = HostContext::default(); - let mut ids = Vec::new(); - let mut live = [true; 2]; - let mut expected = [0i64; 2]; - let name = Value::Text("counter".into()); - for _ in 0..2 { - let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - set(&mut ctx, &id, &name, &Value::Int(0)).unwrap(); - ids.push(id); - } - let mut seed = 0x52455155495245u64; - for step in 0..256 { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); - let slot = ((seed >> 32) & 1) as usize; - let op = (seed >> 40) % 5; - match op { - 0 => { - let value = step as i64 - 128; - let result = set(&mut ctx, &ids[slot], &name, &Value::Int(value)); - assert_eq!(result.is_ok(), live[slot]); - if live[slot] { expected[slot] = value; } - } - 1 => { - let result = get(&mut ctx, &ids[slot], &name); - if live[slot] { assert_eq!(result.unwrap(), Value::Int(expected[slot])); } - else { assert!(result.unwrap_err().contains("not found")); } - } - 2 => { - let src = if lang == "python" { "counter += 1\ncounter" } else { "counter += 1; counter" }; - let result = eval(&mut ctx, &ids[slot], None, Some(&Value::Text(src.into())), None, None); - assert_eq!(result.is_ok(), live[slot]); - if live[slot] { expected[slot] += 1; } - } - 3 => { - assert_eq!(close(&mut ctx, &ids[slot]).is_ok(), live[slot]); - live[slot] = false; - } - _ => { - if live[slot] { close(&mut ctx, &ids[slot]).unwrap(); } - let stale = ids[slot].clone(); - ids[slot] = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - assert_ne!(stale, ids[slot]); - assert!(get(&mut ctx, &stale, &name).is_err()); - set(&mut ctx, &ids[slot], &name, &Value::Int(0)).unwrap(); - expected[slot] = 0; - live[slot] = true; - } - } - // Independent model predicts every remaining store after every command. - for j in 0..2 { - assert_eq!(ctx.foreign_sessions.contains_key(as_session_id(&ids[j]).unwrap()), live[j]); - if live[j] { assert_eq!(get(&mut ctx, &ids[j], &name).unwrap(), Value::Int(expected[j]), "{lang} step {step} slot {j}"); } - } - } - shutdown(&mut ctx); - assert!(ctx.foreign_sessions.is_empty()); - println!("E3 {lang}: seed 0x52455155495245, 256 commands verified"); - } - } - - #[test] - fn failure_process_exit_timeout_and_reopen() { - for lang in ["python", "node"] { - let mut ctx = HostContext::default(); - for source in if lang == "python" { ["import os; os._exit(7)", "while True: pass"] } - else { ["process.exit(7)", "while(true) {}"] } { - let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - let result = eval(&mut ctx, &id, None, Some(&Value::Text(source.into())), None, Some(&Value::Num(0.1))); - assert!(result.is_ok(), "process failure should be a failure record: {result:?}"); - let Value::Map(m) = result.unwrap() else { panic!() }; - assert!(m.iter().any(|(k,v)| k == "ok" && v == &Value::Bool(false))); - assert!(ctx.foreign_sessions.is_empty(), "dead session must be retired"); - assert!(get(&mut ctx, &id, &Value::Text("x".into())).is_err()); - println!("E5 {lang} {source}: recorded and retired"); - } - let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - set(&mut ctx, &id, &Value::Text("x".into()), &Value::Int(41)).unwrap(); - assert_eq!(get(&mut ctx, &id, &Value::Text("x".into())).unwrap(), Value::Int(41)); - shutdown(&mut ctx); - } - } - - #[test] - fn input_history_and_post_refusal_effects_are_preserved() { - for lang in ["python", "node"] { - let mut ctx = HostContext::default(); - let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - let name = Value::Text("n".into()); - set(&mut ctx, &id, &name, &Value::Int(1)).unwrap(); - let code = if lang == "python" { "n += marqdo_input\nn" } else { "n += marqdo_input; n" }; - let result = eval(&mut ctx, &id, None, Some(&Value::Text(code.into())), Some(&Value::Int(3)), None).unwrap(); - let Value::Map(fields) = result else { panic!() }; - assert_eq!(fields.iter().find(|(k,_)| k == "result").unwrap().1, Value::Int(4)); - let sent = ctx.foreign_protocol_steps.last().unwrap(); - assert_eq!(sent.session, as_session_id(&id).unwrap()); - assert_eq!(sent.request["op"], "eval"); - assert_eq!(sent.request["input"], 3); - assert_eq!(sent.request["code"], code); - let before = ctx.foreign_protocol_steps.len(); - assert!(set(&mut ctx, &id, &name, &Value::Int(i64::MAX)).is_err()); - assert_eq!(ctx.foreign_protocol_steps.len(), before, "invalid input must not query oracle"); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(4)); - let bad = if lang == "python" { "n = 99\n2**53" } else { "n = 99; 2**53" }; - assert!(eval(&mut ctx, &id, None, Some(&Value::Text(bad.into())), None, None).unwrap_err().contains("outside V_safe")); - let fault = ctx.foreign_protocol_steps.last().unwrap(); - assert_eq!(fault.response.as_ref().unwrap()["domain_error"], true); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(99), "foreign effects must not be claimed to roll back"); - let ordinary_error = if lang == "python" { "raise ValueError('outside V_safe')" } - else { "throw new Error('outside V_safe')" }; - let record = eval(&mut ctx, &id, None, Some(&Value::Text(ordinary_error.into())), None, None).unwrap(); - let Value::Map(fields) = record else { panic!() }; - assert_eq!(fields.iter().find(|(k,_)| k == "ok").unwrap().1, Value::Bool(false)); - let unsupported = if lang == "python" { "object()" } else { "(function(){})" }; - assert!(eval(&mut ctx, &id, None, Some(&Value::Text(unsupported.into())), None, None).unwrap_err().contains("not JSON-safe")); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(99)); - close(&mut ctx, &id).unwrap(); - println!("E6 {lang}: complete inputs recorded; pre-send refusal has no request; post-send refusal retains effects; structured domain classification verified"); - } - } - - #[test] - fn numeric_extension_policy_agrees_on_python_and_node() { - for lang in ["python", "node"] { - let mut ctx = HostContext::default(); - let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - let key = Value::Text("number".into()); - for value in [1.5, -0.0, 9_007_199_254_740_991.0, -9_007_199_254_740_991.0] { - set(&mut ctx, &id, &key, &Value::Num(value)).unwrap(); - match get(&mut ctx, &id, &key).unwrap() { - Value::Num(n) => assert_eq!(n, value), - Value::Int(n) => assert_eq!(n as f64, value), - other => panic!("{lang}: {other:?}"), - } - } - for value in [9_007_199_254_740_992.0, -9_007_199_254_740_992.0, 1e100] { - let before = ctx.foreign_protocol_steps.len(); - assert!(set(&mut ctx, &id, &key, &Value::Num(value)).unwrap_err().contains("outside V_safe")); - assert_eq!(ctx.foreign_protocol_steps.len(), before); - } - let source = if lang == "python" { "float(2**53)" } else { "Number(2**53)" }; - assert!(eval(&mut ctx, &id, None, Some(&Value::Text(source.into())), None, None).unwrap_err().contains("outside V_safe")); - close(&mut ctx, &id).unwrap(); - println!("E7 {lang}: finite fractions admitted, integral float/scientific-notation bypass refused"); - } - } - - #[test] - fn node_non_json_containers_and_lossy_properties_are_refused_without_coercion() { - let mut ctx = HostContext::default(); - let id = open(&mut ctx, &Value::Text("node".into()), None, None, None, None).unwrap(); - let expressions = [ - "new Map([['k',1]])", "new Set([1,2])", "new Date(0)", "/x/", - "new Uint8Array([1,2])", "new Number(7)", - "Object.assign(Object.create({inherited:1}),{own:2})", - "Object.defineProperty({},'hidden',{value:7})", "({[Symbol('k')]:7})", - "Object.defineProperty({},'data',{enumerable:true,get(){retained=123;return 7}})", - "new Array(2)", "Object.assign([1,2],{tag:3})", "[undefined]", - "(()=>{var x={};x.self=x;return x;})()", - ]; - for expression in expressions { - let code = Value::Text(format!("retained = 99; {expression}")); - let result = eval(&mut ctx,&id,None,Some(&code),None,None); - assert!(result.as_ref().is_err_and(|e|e.contains("not JSON-safe")),"silently coerced {expression}: {result:?}"); - let reply=ctx.foreign_protocol_steps.last().unwrap().response.as_ref().unwrap().clone(); - assert_eq!(reply["domain_error"],serde_json::json!(true)); - assert_eq!(get(&mut ctx,&id,&Value::Text("retained".into())).unwrap(),Value::Int(99),"getter must not run during refusal"); - println!("NODE_DOMAIN_REFUSAL:{}",serde_json::json!({"expression":expression,"reply":reply.clone(),"retained":99})); - } - // Null prototypes, special string keys and shared acyclic subvalues remain records/lists. - let code=Value::Text("var item = Object.assign(Object.create(null),{constructor:7}); [item,item]".into()); - let result=eval(&mut ctx,&id,None,Some(&code),None,None).unwrap(); - let Value::Map(fields)=result else {panic!()}; - let observed=&fields.iter().find(|(k,_)|k=="result").unwrap().1; - assert_eq!(observed,&Value::List(vec![Value::Map(vec![("constructor".into(),Value::Int(7))]);2])); - close(&mut ctx,&id).unwrap(); - } - - #[test] - fn recursive_values_and_object_keys_cross_without_coercion() { - fn payload(seed: u64, depth: usize) -> Value { - if depth == 0 { return match seed % 4 { - 0 => Value::None, 1 => Value::Bool(seed & 4 != 0), - 2 => Value::Int((seed % 2001) as i64 - 1000), - _ => Value::Text(format!("中文🧪\\\"\n{}", seed % 10)), - }; } - match seed % 3 { - 0 => Value::List(vec![payload(seed.wrapping_mul(17).wrapping_add(1), depth-1), payload(seed.wrapping_mul(31).wrapping_add(2), depth-1)]), - 1 => Value::Map(vec![("data".into(), payload(seed.wrapping_mul(43).wrapping_add(3), depth-1)), ("tag".into(), Value::Text("record".into()))]), - _ => payload(seed, 0), - } - } - for lang in ["python", "node"] { - let mut ctx = HostContext::default(); - let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap(); - let name = Value::Text("payload".into()); - for seed in 0..64 { - let v = payload(seed, 4); - set(&mut ctx, &id, &name, &v).unwrap(); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), v, "{lang} seed {seed}"); - } - let special = Value::Map(vec![ - ("__proto__".into(), Value::Map(vec![("polluted".into(), Value::Bool(true))])), - ("constructor".into(), Value::Text("data".into())), - ]); - set(&mut ctx, &id, &name, &special).unwrap(); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), special, "{lang} valid special keys lost"); - for bad in [Value::Map(vec![("a".into(), Value::Int(1)), ("a".into(), Value::Int(2))]), - Value::Map(vec![("a".into(), Value::List(vec![])), ("b".into(), Value::List(vec![Value::Int(1)]))])] { - let before = ctx.foreign_protocol_steps.len(); - assert!(set(&mut ctx, &id, &name, &bad).is_err()); - assert_eq!(ctx.foreign_protocol_steps.len(), before); - assert_eq!(get(&mut ctx, &id, &name).unwrap(), special); - } - if lang == "python" { - let code = Value::Text("{1: 'integer key', '1': 'string key'}".into()); - assert!(eval(&mut ctx, &id, None, Some(&code), None, None).unwrap_err().contains("keys must be strings")); - } else { - let code = Value::Text("typeof ({}).polluted === 'undefined'".into()); - let Value::Map(m) = eval(&mut ctx, &id, None, Some(&code), None, None).unwrap() else { panic!() }; - assert_eq!(m.iter().find(|(k,_)| k == "result").unwrap().1, Value::Bool(true)); - } - close(&mut ctx, &id).unwrap(); - println!("E8 {lang}: 64 nested round-trips, special keys preserved, invalid key/shape inputs refused without requests"); - } - } - - #[cfg(unix)] - #[test] - fn bootstrap_interrupts_busy_eval_and_preserves_idle_state(){ - for lang in ["python","node"]{ - let mut ctx=HostContext::default();let id=open(&mut ctx,&Value::Text(lang.into()),None,None,None,None).unwrap(); - let name=Value::Text("n".into());set(&mut ctx,&id,&name,&Value::Int(8)).unwrap(); - interrupt(&mut ctx,&id).unwrap();assert_eq!(get(&mut ctx,&id,&name).unwrap(),Value::Int(8)); - let marker=ctx.cwd.join(format!("target/interrupt-marker-{}-{lang}",std::process::id()));let _=std::fs::remove_file(&marker); - let literal=serde_json::to_string(&marker.display().to_string()).unwrap(); - let code=if lang=="python"{format!("with open({literal}, 'w') as marker:\n marker.write('ready')\nwhile True: pass")} - else{format!("require('fs').writeFileSync({literal}, 'ready'); while(true) {{}}")}; - let pid=ctx.foreign_sessions[as_session_id(&id).unwrap()].child.id();let child_id=id.clone(); - let worker=std::thread::spawn(move||{let out=eval(&mut ctx,&child_id,None,Some(&Value::Text(code)),None,Some(&Value::Num(3.0)));(ctx,out)}); - let deadline=Instant::now()+Duration::from_secs(2); - while !marker.exists()&&Instant::now(), - evaluating: bool, - ready: bool, - requested: bool, -} - -#[derive(Clone, Debug, Default)] -pub struct InterruptHandle(Arc>); - -impl InterruptHandle { - pub(super) fn new(pid: u32) -> Self { - Self(Arc::new(Mutex::new(State { - pid: Some(pid), - ..State::default() - }))) - } - pub(super) fn retire(&self) -> Option { - if let Ok(mut state) = self.0.lock() { - let pid = state.pid.take(); - state.evaluating = false; - pid - } else { - None - } - } - pub(super) fn try_wait( - &self, - child: &mut std::process::Child, - ) -> std::io::Result> { - let mut state = self.0.lock().unwrap(); - let result = child.try_wait(); - if matches!(result, Ok(Some(_))) { - state.pid = None; - state.evaluating = false; - } - result - } - pub(super) fn begin(&self, evaluating: bool) { - let mut state = self.0.lock().unwrap(); - state.evaluating = evaluating; - state.ready = false; - state.requested = false; - } - pub(super) fn finish(&self) { - self.0.lock().unwrap().evaluating = false; - } - // SIGINT can arrive between a Node ready frame and installation of V8's - // breakOnSigint handler. Retry the same logical request while awaiting its - // response; never carry a retry into the next request or retired process. - pub(super) fn retry(&self) -> Result<(), String> { - let state = self.0.lock().map_err(|_| "interrupt lock poisoned")?; - if state.evaluating && state.ready && state.requested { - Self::signal(&state)?; - } - Ok(()) - } - pub(super) fn ready(&self) -> Result<(), String> { - let mut state = self.0.lock().map_err(|_| "interrupt lock poisoned")?; - if state.ready { - return Ok(()); - } - state.ready = true; - if state.requested { - Self::signal(&state)?; - } - Ok(()) - } - pub fn is_live(&self) -> bool { - self.0.lock().is_ok_and(|s| s.pid.is_some()) - } - - /// False means idle; cancellation is coalesced within one evaluation. - /// Before the bootstrap's ready frame it is queued rather than sent into - /// interpreter startup or transport parsing. - pub fn request(&self) -> Result { - let mut state = self.0.lock().map_err(|_| "interrupt lock poisoned")?; - if state.pid.is_none() { - return Err("interrupt capability retired".into()); - } - if !state.evaluating { - return Ok(false); - } - #[cfg(not(unix))] - return Err("non-destructive interrupt is unsupported on this platform".into()); - if !state.requested { - if state.ready { - Self::signal(&state)?; - } - state.requested = true; - } - Ok(true) - } - fn signal(state: &State) -> Result<(), String> { - let pid = state.pid.ok_or("interrupt capability retired")?; - #[cfg(unix)] - { - if unsafe { libc::kill(-(pid as i32), libc::SIGINT) } != 0 { - return Err(format!( - "interrupt failed: {}", - std::io::Error::last_os_error() - )); - } - Ok(()) - } - #[cfg(not(unix))] - { - let _ = pid; - Err("non-destructive interrupt is unsupported on this platform".into()) - } - } -} - -#[cfg(all(test, unix))] -mod tests { - use crate::host::{foreign_session, HostContext}; - use crate::value::Value; - #[test] - fn retired_interrupt_capability_cannot_reach_replacement_kernel() { - for language in ["python", "node"] { - let mut host = HostContext::default(); - let lang = Value::Text(language.into()); - let old = foreign_session::open(&mut host, &lang, None, None, None, None).unwrap(); - let Value::Handle(id) = &old else { panic!() }; - let control = host.foreign_sessions[id].interrupt_handle.clone(); - assert!(!control.request().unwrap()); - foreign_session::close(&mut host, &old).unwrap(); - let new = foreign_session::open(&mut host, &lang, None, None, None, None).unwrap(); - assert!(!control.is_live()); - assert!(control.request().unwrap_err().contains("retired")); - foreign_session::set(&mut host, &new, &Value::Text("n".into()), &Value::Int(8)) - .unwrap(); - assert_eq!( - foreign_session::get(&mut host, &new, &Value::Text("n".into())).unwrap(), - Value::Int(8) - ); - foreign_session::close(&mut host, &new).unwrap(); - } - } - #[test] - fn cancellation_queued_during_bootstrap_reaches_busy_evaluation() { - use std::time::{Duration, Instant}; - for language in ["python", "node"] { - let mut host = HostContext::default(); - let id = foreign_session::open( - &mut host, - &Value::Text(language.into()), - None, - None, - None, - None, - ) - .unwrap(); - let Value::Handle(ref name) = id else { - panic!() - }; - let control = host.foreign_sessions[name].interrupt_handle.clone(); - let kernel = id.clone(); - let code = if language == "python" { - "while True: pass" - } else { - "while(true) {}" - }; - let worker = std::thread::spawn(move || { - let record = foreign_session::eval( - &mut host, - &kernel, - None, - Some(&Value::Text(code.into())), - None, - Some(&Value::Int(2)), - ) - .unwrap(); - (host, record) - }); - let deadline = Instant::now() + Duration::from_secs(1); - while !control.0.lock().unwrap().evaluating && Instant::now() < deadline { - std::thread::yield_now(); - } - assert!(control.request().unwrap()); - assert!( - control.request().unwrap(), - "logical duplicates must coalesce" - ); - let (mut host, record) = worker.join().unwrap(); - let Value::Map(fields) = record else { panic!() }; - assert_eq!( - fields.iter().find(|(k, _)| k == "timed_out").unwrap().1, - Value::Bool(false), - "{language}: {fields:?}" - ); - assert_eq!( - fields.iter().find(|(k, _)| k == "alive").unwrap().1, - Value::Bool(true) - ); - foreign_session::close(&mut host, &id).unwrap(); - } - } -} diff --git a/src/host/foreign_session/validation.rs b/src/host/foreign_session/validation.rs deleted file mode 100755 index 89d62de..0000000 --- a/src/host/foreign_session/validation.rs +++ /dev/null @@ -1,173 +0,0 @@ -//! Production adapter to the executable Lean replay policy. -//! All replay decisions come from ReplayPolicy.Cursor, with no Rust fallback. -use super::ProtocolStep; -use serde_json::Value; -use std::collections::VecDeque; -mod policy; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DivergenceKind { Missing, Request, Reply, Surplus, Phase, Policy } -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Divergence { - pub kind: DivergenceKind, - pub matched_prefix: usize, - pub detail: Option, -} -impl std::fmt::Display for Divergence { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self.kind { - DivergenceKind::Missing | DivergenceKind::Request => "replay: protocol request differs before dispatch", - DivergenceKind::Reply => "replay: protocol response differs", - DivergenceKind::Surplus => "replay: recorded execution prefix was not consumed", - DivergenceKind::Phase => "replay: invalid protocol validation phase", - DivergenceKind::Policy => "replay: verified policy unavailable", - })?; - if let Some(detail) = &self.detail { write!(f, ": {detail}")? } - Ok(()) - } -} -#[derive(Debug)] -pub struct ReplayCursor { - client: Option, - progress: (usize, usize), - stopped: Option, -} -impl From> for ReplayCursor { - fn from(expected: VecDeque) -> Self { - let count = expected.len(); - match policy::Client::start(expected) { - Ok((client, reply)) if reply.allow && reply.matched == 0 && reply.remaining == count => - Self { client: Some(client), progress: (0, count), stopped: None }, - result => { - let detail = match result { Err(e) => e, Ok(_) => "invalid policy initialization".into() }; - Self { client: None, progress: (0,count), stopped: Some(Divergence { - kind: DivergenceKind::Policy, matched_prefix: 0, detail: Some(detail) }) } - } - } - } -} -impl From> for ReplayCursor { - fn from(expected: Vec) -> Self { VecDeque::from(expected).into() } -} -/// Private construction, no Clone: actual dispatch consumes this snapshot. -pub(super) struct DispatchPermit { session: String, request: Value } -impl DispatchPermit { - pub(super) fn session(&self) -> &str { &self.session } - pub(super) fn request(&self) -> &Value { &self.request } -} -impl ReplayCursor { - fn unavailable(&mut self, detail: String) -> Divergence { - self.client.take(); - let error = Divergence { kind: DivergenceKind::Policy, matched_prefix: self.progress.0, detail: Some(detail) }; - self.stopped = Some(error.clone()); - error - } - fn command(&mut self, op: &str, value: &str) -> Result<(), Divergence> { - if let Some(error) = &self.stopped { return Err(error.clone()) } - let result = self.client.as_mut().ok_or_else(|| "no policy process".to_string()) - .and_then(|client| client.exchange(op, value)); - let reply = result.map_err(|e| self.unavailable(e))?; - self.progress = (reply.matched, reply.remaining); - if reply.allow { return Ok(()) } - let kind = match reply.reason.as_deref() { - Some("missing") => DivergenceKind::Missing, - Some("request") => DivergenceKind::Request, - Some("reply") => DivergenceKind::Reply, - Some("surplus") => DivergenceKind::Surplus, - Some("phase") => DivergenceKind::Phase, - _ => return Err(self.unavailable("unknown policy stop reason".into())), - }; - let error = Divergence { kind, matched_prefix: reply.matched, detail: None }; - self.stopped = Some(error.clone()); - Err(error) - } - fn prepare(&mut self, session: &str, request: &Value) -> Result { - self.command("prepare", &policy::request_key(session,request))?; - Ok(DispatchPermit { session: session.into(), request: request.clone() }) - } - pub(super) fn accept_response(&mut self, response: &Result) -> Result<(), Divergence> { - self.command("receive", &policy::response_key(response)) - } - pub fn progress(&self) -> (usize,usize) { self.progress } - /// Called only at the outer action boundary; consumes the cursor. - pub fn finish(mut self) -> Result<(),Divergence> { self.command("finish", "") } -} -pub(super) fn prepare(cursor: Option<&mut ReplayCursor>, session: &str, request: &Value) - -> Result { - if let Some(cursor) = cursor { return cursor.prepare(session,request) } - Ok(DispatchPermit { session: session.into(), request: request.clone() }) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - fn step(reply: Result) -> ProtocolStep { - ProtocolStep { - session: "s".into(), - request: json!({"op":"get"}), - response: reply, - } - } - #[test] - fn local_returns_and_ordinary_failures_preserve_residual_history() { - let mut cursor: ReplayCursor = - vec![step(Err("foreign failure".into())), step(Ok(json!(7)))].into(); - assert_eq!(cursor.progress(), (0, 2)); - let permit = cursor.prepare("s", &json!({"op":"get"})).unwrap(); - assert_eq!(permit.session(), "s"); - cursor - .accept_response(&Err("foreign failure".into())) - .unwrap(); - assert_eq!(cursor.progress(), (1, 1)); - cursor.prepare("s", &json!({"op":"get"})).unwrap(); - cursor.accept_response(&Ok(json!(7))).unwrap(); - cursor.finish().unwrap(); - } - #[test] - fn divergence_is_sticky_and_matching_reply_cannot_revive_it() { - let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into(); - cursor.prepare("s", &json!({"op":"get"})).unwrap(); - let first = cursor.accept_response(&Ok(json!(8))).unwrap_err(); - assert_eq!(first.kind, DivergenceKind::Reply); - assert_eq!( - cursor.prepare("s", &json!({"op":"get"})).err().unwrap(), - first - ); - assert_eq!(cursor.accept_response(&Ok(json!(7))).unwrap_err(), first); - assert_eq!(cursor.finish().unwrap_err(), first); - } - #[test] - fn permit_is_a_snapshot_and_phase_errors_fail_closed() { - let mut request = json!({"op":"get"}); - let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into(); - let permit = cursor.prepare("s", &request).unwrap(); - request["op"] = json!("write"); - assert_ne!(permit.request(), &request); - assert_eq!( - cursor.prepare("s", permit.request()).err().unwrap().kind, - DivergenceKind::Phase - ); - assert!(cursor.accept_response(&Ok(json!(7))).is_err()); - } - #[test] - fn mismatching_and_missing_requests_never_issue_a_permit() { - let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into(); - let error = cursor - .prepare("other-session", &json!({"op":"get"})) - .err() - .unwrap(); - assert_eq!(error.kind, DivergenceKind::Request); - assert_eq!(cursor.progress(), (0, 1)); - assert_eq!( - cursor.prepare("s", &json!({"op":"get"})).err().unwrap(), - error - ); - let mut empty: ReplayCursor = Vec::::new().into(); - assert_eq!( - empty.prepare("s", &json!({"op":"get"})).err().unwrap().kind, - DivergenceKind::Missing - ); - assert!(empty.finish().is_err()); - } -} diff --git a/src/host/foreign_session/validation/policy.rs b/src/host/foreign_session/validation/policy.rs deleted file mode 100755 index dc93eb6..0000000 --- a/src/host/foreign_session/validation/policy.rs +++ /dev/null @@ -1,229 +0,0 @@ -//! Transport for the executable Lean policy. This module makes no replay -//! acceptance decisions; malformed/unavailable policy responses fail closed. -use super::super::ProtocolStep; -use serde::{Deserialize, Serialize}; -use serde_json::Value; -use std::io::{BufRead, BufReader, Read, Write}; -use std::path::{Path, PathBuf}; -use std::process::{Child, ChildStdin, Command, Stdio}; -use std::sync::mpsc::{self, Receiver}; -use std::time::Duration; - -#[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub(super) struct Reply { - pub policy: String, - pub allow: bool, - pub matched: usize, - pub remaining: usize, - pub reason: Option, -} - -#[derive(Serialize)] -struct StepWire { - q: String, - r: String, -} - -// Lean's derived FromJson requires every field, including fields with a Lean -// default. Always send the complete record for init, prepare, receive and finish. -#[derive(Serialize)] -struct CommandWire<'a> { - op: &'a str, - steps: &'a [StepWire], - value: &'a str, -} - -#[derive(Debug)] -pub(super) struct Client { - child: Child, - input: ChildStdin, - replies: Receiver>, - stderr: Receiver, -} - -pub(super) fn request_key(session: &str, request: &Value) -> String { - serde_json::to_string(&(session, request.to_string())).expect("strings serialize") -} -pub(super) fn response_key(response: &Result) -> String { - serde_json::to_string(response).expect("protocol responses serialize") -} - -fn executable() -> PathBuf { - if let Some(path) = std::env::var_os("MARQDO_REPLAY_POLICY") { - return path.into(); - } - if let Ok(exe) = std::env::current_exe() { - if let Some(parent) = exe.parent() { - let adjacent = parent.join("marqdo-replay-policy"); - if adjacent.is_file() { - return adjacent; - } - } - } - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("verification/replay-policy/.lake/build/bin/replayPolicy") -} - -impl Client { - pub(super) fn start( - steps: impl IntoIterator, - ) -> Result<(Self, Reply), String> { - Self::start_at(&executable(), steps) - } - - fn start_at( - path: &Path, - steps: impl IntoIterator, - ) -> Result<(Self, Reply), String> { - let mut child = Command::new(path) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(|e| format!("{}: {e}", path.display()))?; - let input = child.stdin.take().ok_or("policy stdin unavailable")?; - let output = child.stdout.take().ok_or("policy stdout unavailable")?; - let mut errors = child.stderr.take().ok_or("policy stderr unavailable")?; - let (sender, replies) = mpsc::channel(); - std::thread::spawn(move || { - for line in BufReader::new(output).lines() { - let reply = line - .map_err(|e| e.to_string()) - .and_then(|line| serde_json::from_str(&line).map_err(|e| e.to_string())); - let failed = reply.is_err(); - if sender.send(reply).is_err() || failed { - break; - } - } - }); - // Drain stderr concurrently so a verbose failure cannot block the child. - // Retain a bounded diagnostic tail rather than buffering an entire stream. - let (error_sender, stderr) = mpsc::channel(); - std::thread::spawn(move || { - const LIMIT: usize = 4096; - let mut tail = Vec::new(); - let mut buffer = [0; LIMIT]; - while let Ok(count) = errors.read(&mut buffer) { - if count == 0 { - break; - } - tail.extend_from_slice(&buffer[..count]); - if tail.len() > LIMIT { - tail.drain(..tail.len() - LIMIT); - } - } - let _ = error_sender.send(String::from_utf8_lossy(&tail).trim().to_string()); - }); - let steps: Vec<_> = steps - .into_iter() - .map(|step| StepWire { - q: request_key(&step.session, &step.request), - r: response_key(&step.response), - }) - .collect(); - let mut client = Self { - child, - input, - replies, - stderr, - }; - let reply = client.send(CommandWire { - op: "init", - steps: &steps, - value: "", - })?; - Ok((client, reply)) - } - - pub(super) fn exchange(&mut self, op: &str, value: &str) -> Result { - self.send(CommandWire { - op, - steps: &[], - value, - }) - } - - fn send(&mut self, command: CommandWire<'_>) -> Result { - let result = (|| { - serde_json::to_writer(&mut self.input, &command).map_err(|e| e.to_string())?; - self.input.write_all(b"\n").map_err(|e| e.to_string())?; - self.input.flush().map_err(|e| e.to_string())?; - let reply = self - .replies - .recv_timeout(Duration::from_secs(30)) - .map_err(|e| format!("policy response: {e}"))??; - if reply.policy - != include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/verification/replay-policy/POLICY-SHA256" - )) - .trim() - { - return Err("policy executable does not match the compiled source identity".into()); - } - if reply.allow == reply.reason.is_some() { - return Err("policy response has inconsistent verdict and reason".into()); - } - Ok(reply) - })(); - result.map_err(|error| self.process_error(error)) - } - - fn process_error(&mut self, mut error: String) -> String { - // Prefer the actual exit status when the process has already failed. - let status = match self.child.try_wait() { - Ok(Some(status)) => Some(status), - _ => { - let _ = self.child.kill(); - self.child.wait().ok() - } - }; - if let Some(status) = status { - error.push_str(&format!("; policy process {status}")); - } - if let Ok(stderr) = self.stderr.recv_timeout(Duration::from_millis(100)) { - if !stderr.is_empty() { - error.push_str(&format!("; stderr: {stderr}")); - } - } - error - } -} -impl Drop for Client { - fn drop(&mut self) { - let _ = self.child.kill(); - let _ = self.child.wait(); - } -} - -#[cfg(all(test, unix))] -mod tests { - use super::*; - use std::os::unix::fs::PermissionsExt; - - #[test] - fn failed_companion_reports_its_exit_status_and_decoder_error() { - let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("target") - .join(format!( - "policy-transport-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - std::fs::create_dir_all(&dir).unwrap(); - let executable = dir.join("failed-policy"); - std::fs::write(&executable, "#!/bin/sh\nIFS= read -r command\nprintf '%s\\n' 'PolicyCommand.value: String expected' >&2\nexit 17\n").unwrap(); - std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap(); - let error = Client::start_at(&executable, Vec::::new()).unwrap_err(); - std::fs::remove_dir_all(dir).unwrap(); - assert!(error.contains("exit status: 17"), "{error}"); - assert!( - error.contains("PolicyCommand.value: String expected"), - "{error}" - ); - } -} diff --git a/src/host/fs.rs b/src/host/fs.rs deleted file mode 100755 index 9610dba..0000000 --- a/src/host/fs.rs +++ /dev/null @@ -1,829 +0,0 @@ -//! Filesystem host primitives. - -use std::fs; -use std::path::Path; - -use crate::host::HostContext; -use crate::value::Value; - -pub fn path_under_root(path: &Path, root: &Path) -> bool { - let mut cur = path.to_path_buf(); - loop { - if cur == *root { - return true; - } - if !cur.pop() { - return false; - } - } -} - -fn text_path(v: &Value) -> Result<&str, String> { - match v { - Value::Text(s) => Ok(s.as_str()), - _ => Err("path must be text".into()), - } -} - -fn text_body(v: &Value) -> Result<&str, String> { - match v { - Value::Text(s) => Ok(s.as_str()), - _ => Err("text must be text".into()), - } -} - -/// Return the logical absolute path checked by native filesystem operations. -pub fn resolve(ctx: &HostContext, path: &Value) -> Result { - let checked = ctx.resolve_path(text_path(path)?)?; - let absolute = if checked.is_absolute() { checked } else { - std::env::current_dir().map_err(|error| error.to_string())?.join(checked) - }; - let mut normalized = std::path::PathBuf::new(); - for component in absolute.components() { - match component { - std::path::Component::CurDir => {}, - std::path::Component::ParentDir => { normalized.pop(); }, - component => normalized.push(component.as_os_str()), - } - } - normalized.to_str().map(|value| Value::Text(value.to_owned())) - .ok_or_else(|| "resolved filesystem path is not UTF-8".into()) -} - -pub fn read_text(ctx: &HostContext, path: &Value) -> Result { - let p = ctx.resolve_path(text_path(path)?)?; - if let Some(hit) = crate::host::sandbox_fs::cow_read_text(ctx, &p)? { - return Ok(Value::Text(hit)); - } - let s = fs::read_to_string(&p).map_err(|e| format!("read_text {}: {e}", p.display()))?; - Ok(Value::Text(s)) -} - -pub fn write_text(ctx: &HostContext, path: &Value, text: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("write_text denied by host policy".into()); - } - let p = ctx.resolve_path(text_path(path)?)?; - let body = text_body(text)?; - if crate::host::sandbox_fs::cow_write_text(ctx, &p, body)? { - return Ok(Value::None); - } - if let Some(parent) = p.parent() { - fs::create_dir_all(parent).map_err(|e| format!("write_text mkdir: {e}"))?; - } - fs::write(&p, body).map_err(|e| format!("write_text {}: {e}", p.display()))?; - Ok(Value::None) -} - -pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("append_text denied by host policy".into()); - } - let p = ctx.resolve_path(text_path(path)?)?; - if ctx.sandbox_session.is_some() { - let mut current = match read_text(ctx,path) { - Ok(Value::Text(text)) => text, - Err(_) if !matches!(exists(ctx,path),Ok(Value::Bool(true))) => String::new(), - Err(e) => return Err(e), - _ => return Err("append_text needs UTF-8".into()), - }; - current.push_str(text_body(text)?); - crate::host::sandbox_fs::cow_write_text(ctx,&p,¤t)?; - return Ok(Value::None); - } - use std::io::Write; - let mut f = fs::OpenOptions::new() - .create(true) - .append(true) - .open(&p) - .map_err(|e| format!("append_text {}: {e}", p.display()))?; - f.write_all(text_body(text)?.as_bytes()) - .map_err(|e| format!("append_text {}: {e}", p.display()))?; - Ok(Value::None) -} - -pub fn exists(ctx: &HostContext, path: &Value) -> Result { - let p = ctx.resolve_path(text_path(path)?)?; - if let Some(hit) = crate::host::sandbox_fs::cow_exists(ctx, &p)? { - return Ok(Value::Bool(hit)); - } - Ok(Value::Bool(p.exists())) -} - -pub fn list_dir(ctx: &HostContext, path: &Value) -> Result { - let p = ctx.resolve_path(text_path(path)?)?; - let mut names = Vec::new(); - let rd = fs::read_dir(&p).map_err(|e| format!("list_dir {}: {e}", p.display()))?; - for ent in rd { - let ent = ent.map_err(|e| format!("list_dir: {e}"))?; - names.push(Value::Text( - ent.file_name().to_string_lossy().into_owned(), - )); - } - names.sort_by(|a, b| a.as_display().cmp(&b.as_display())); - Ok(Value::List(names)) -} - -pub fn make_dir(ctx: &HostContext, path: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("make_dir denied by host policy".into()); - } - if ctx.sandbox_session.is_some() { return Err("unsupported: make_dir directory state in CoW sandbox".into()); } - let p = ctx.resolve_path(text_path(path)?)?; - fs::create_dir_all(&p).map_err(|e| format!("make_dir {}: {e}", p.display()))?; - Ok(Value::None) -} - -/// Explicit recursive mkdir (same host behavior as `make_dir`). -pub fn make_dirs(ctx: &HostContext, path: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("make_dirs denied by host policy".into()); - } - if ctx.sandbox_session.is_some() { return Err("unsupported: make_dirs directory state in CoW sandbox".into()); } - let p = ctx.resolve_path(text_path(path)?)?; - fs::create_dir_all(&p).map_err(|e| format!("make_dirs {}: {e}", p.display()))?; - Ok(Value::None) -} - -pub fn remove(ctx: &HostContext, path: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("remove denied by host policy".into()); - } - let p = ctx.resolve_path(text_path(path)?)?; - if ctx.sandbox_session.is_some() && p.is_dir() { - return Err("unsupported: recursive directory removal in CoW sandbox".into()); - } - if crate::host::sandbox_fs::cow_remove(ctx, &p)? { - return Ok(Value::None); - } - if p.is_dir() { - fs::remove_dir_all(&p).map_err(|e| format!("remove {}: {e}", p.display()))?; - } else { - fs::remove_file(&p).map_err(|e| format!("remove {}: {e}", p.display()))?; - } - Ok(Value::None) -} - -/// Remove a directory tree. Errors if `path` is a file. -pub fn remove_tree(ctx: &HostContext, path: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("remove_tree denied by host policy".into()); - } - if ctx.sandbox_session.is_some() { return Err("unsupported: remove_tree directory state in CoW sandbox".into()); } - let p = ctx.resolve_path(text_path(path)?)?; - if !p.exists() { - return Err(format!("remove_tree: not found: {}", p.display())); - } - if !p.is_dir() { - return Err(format!("remove_tree: not a directory: {}", p.display())); - } - fs::remove_dir_all(&p).map_err(|e| format!("remove_tree {}: {e}", p.display()))?; - Ok(Value::None) -} - -/// `{size, mtime_unix, is_file, is_dir}` for a path. -pub fn stat(ctx: &HostContext, path: &Value) -> Result { - let p = ctx.resolve_path(text_path(path)?)?; - let meta = fs::metadata(&p).map_err(|e| format!("stat {}: {e}", p.display()))?; - let mtime = meta - .modified() - .ok() - .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) - .map(|d| d.as_secs() as i64) - .unwrap_or(0); - Ok(Value::Map(vec![ - ("size".into(), Value::Int(meta.len() as i64)), - ("mtime_unix".into(), Value::Int(mtime)), - ("is_file".into(), Value::Bool(meta.is_file())), - ("is_dir".into(), Value::Bool(meta.is_dir())), - ])) -} - -/// Depth-first walk; returns path texts relative to `path` (forward slashes), sorted per directory. -pub fn walk(ctx: &HostContext, path: &Value) -> Result { - let root = ctx.resolve_path(text_path(path)?)?; - if !root.is_dir() { - return Err(format!("walk: not a directory: {}", root.display())); - } - let mut out: Vec = Vec::new(); - walk_dfs(&root, Path::new(""), &mut out)?; - Ok(Value::List(out)) -} - -fn walk_dfs(abs: &Path, rel: &Path, out: &mut Vec) -> Result<(), String> { - let mut entries: Vec<_> = fs::read_dir(abs) - .map_err(|e| format!("walk {}: {e}", abs.display()))? - .collect::, _>>() - .map_err(|e| format!("walk: {e}"))?; - entries.sort_by_key(|e| e.file_name()); - for ent in entries { - let name = ent.file_name(); - let child_rel = if rel.as_os_str().is_empty() { - Path::new(&name).to_path_buf() - } else { - rel.join(&name) - }; - let rel_text = child_rel - .components() - .map(|c| c.as_os_str().to_string_lossy()) - .collect::>() - .join("/"); - out.push(Value::Text(rel_text)); - let ft = ent - .file_type() - .map_err(|e| format!("walk file_type: {e}"))?; - if ft.is_dir() { - walk_dfs(&ent.path(), &child_rel, out)?; - } - } - Ok(()) -} - -pub fn copy_file(ctx: &HostContext, src: &Value, dest: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("copy_file denied by host policy".into()); - } - let from = ctx.resolve_path(text_path(src)?)?; - let to = ctx.resolve_path(text_path(dest)?)?; - if from == to { return Err("conflict: copy source equals destination".into()); } - if ctx.sandbox_session.is_some() { - use std::io::Read; - let bytes = match crate::host::sandbox_fs::cow_read_bytes(ctx,&from)? { - Some(bytes) => bytes, - None => { let mut bytes=Vec::new();fs::File::open(&from).map_err(|e|e.to_string())? - .take(64*1024*1024+1).read_to_end(&mut bytes).map_err(|e|e.to_string())?;bytes }, - }; - if bytes.len()>64*1024*1024 { return Err("resource_limit: CoW copy exceeds 64 MiB".into()); } - crate::host::sandbox_fs::cow_write_bytes(ctx,&to,&bytes)?; - return Ok(Value::None); - } - if let Some(parent) = to.parent() { - fs::create_dir_all(parent).map_err(|e| format!("copy_file mkdir: {e}"))?; - } - fs::copy(&from, &to).map_err(|e| format!("copy_file {} -> {}: {e}", from.display(), to.display()))?; - Ok(Value::None) -} - -pub fn move_path(ctx: &HostContext, src: &Value, dest: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("move denied by host policy".into()); - } - let from = ctx.resolve_path(text_path(src)?)?; - let to = ctx.resolve_path(text_path(dest)?)?; - if from == to { return Ok(Value::None); } - if ctx.sandbox_session.is_some() { - copy_file(ctx,src,dest)?; - crate::host::sandbox_fs::cow_remove(ctx,&from)?; - return Ok(Value::None); - } - if let Some(parent) = to.parent() { - fs::create_dir_all(parent).map_err(|e| format!("move mkdir: {e}"))?; - } - fs::rename(&from, &to).map_err(|e| format!("move {} -> {}: {e}", from.display(), to.display()))?; - Ok(Value::None) -} - -/// Create an empty temp file under the program cwd / fs_root; return relative path text. -pub fn make_temp(ctx: &HostContext, prefix: Option<&Value>) -> Result { - if !ctx.allow_fs_write() { - return Err("make_temp denied by host policy".into()); - } - let pref = match prefix { - None | Some(Value::None) => "mqtmp".to_string(), - Some(v) => text_path(v)?.to_string(), - }; - if pref.contains('/') || pref.contains('\\') || pref.contains("..") { - return Err("make_temp: prefix must be a simple name".into()); - } - let stamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - let name = format!("{pref}-{stamp}"); - let p = ctx.resolve_path(&name)?; - if ctx.sandbox_session.is_some() { - if matches!(exists(ctx,&Value::Text(name.clone()))?,Value::Bool(true)) { - return Err("conflict: temporary path exists".into()); - } - crate::host::sandbox_fs::cow_write_bytes(ctx,&p,&[])?; - return Ok(Value::Text(name)); - } - if let Some(parent) = p.parent() { - fs::create_dir_all(parent).map_err(|e| format!("make_temp mkdir: {e}"))?; - } - fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&p) - .map_err(|e| format!("make_temp {}: {e}", p.display()))?; - Ok(Value::Text(name)) -} - -/// Exact UTF-8 FIND→REPLACE on a file. `find` must occur exactly once. -pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value) -> Result { - if !ctx.allow_fs_write() { - return Err("text_patch denied by host policy".into()); - } - let display = text_path(path)?; - let find = text_body(find)?; - let replace = text_body(replace)?; - if find.is_empty() { - return Err("text_patch: find must be non-empty".into()); - } - let Value::Text(src) = read_text(ctx,path)? else { return Err("text_patch needs text".into()); }; - let count = src.matches(find).count(); - if count == 0 { - return Err(format!( - "text_patch: find not found in {}", - display - )); - } - if count > 1 { - return Err(format!( - "text_patch: find matched {count} times in {} (must be unique)", - display - )); - } - let next = src.replacen(find, replace, 1); - write_text(ctx,path,&Value::Text(next))?; - Ok(Value::Int(1)) -} - -/// Apply one or more FIND/REPLACE blocks from plan-reply text. -/// -/// Preferred blocks: -/// ```text -/// <<< -/// FIND -/// -/// === -/// REPLACE -/// -/// >>> -/// ``` -/// -/// Also accepts fenced pairs (common model mistake): -/// ````text -/// ```find -/// -/// ``` -/// ```replace -/// -/// ``` -/// ```` -pub fn apply_patch_blocks( - ctx: &HostContext, - path: &Value, - text: &Value, - soft: Option<&Value>, -) -> Result { - if !ctx.allow_fs_write() { - return Err("apply_patch_blocks denied by host policy".into()); - } - let soft = match soft { - None | Some(Value::None) => false, - Some(v) => v.truthy(), - }; - match apply_patch_blocks_inner(ctx, path, text) { - Ok(n) => Ok(n), - // soft swallows unique-FIND miss and empty FIND (model protocol mistakes). - // Never softens parse / multi-match / whole-file rewrite. - Err(e) if soft && (e.contains("FIND not found") || e.contains("empty FIND")) => { - Ok(Value::Int(0)) - } - Err(e) => Err(e), - } -} - -/// Reject FIND that rewrites a non-trivial file wholesale (exact or ≥90% span). -/// Tiny files may be replaced entirely (e.g. two-line import rewrites). -fn find_spans_whole_file(src: &str, find: &str) -> bool { - const MIN_BYTES: usize = 800; - let st = src.trim(); - let ft = find.trim(); - if ft.is_empty() || src.len() < MIN_BYTES { - return false; - } - if st == ft { - return true; - } - if !src.contains(find) { - return false; - } - find.len().saturating_mul(10) >= src.len().saturating_mul(9) -} - -fn apply_patch_blocks_inner( - ctx: &HostContext, - path: &Value, - text: &Value, -) -> Result { - let blocks = parse_patch_blocks(text_body(text)?)?; - if blocks.is_empty() { - return Ok(Value::Int(0)); - } - let display = text_path(path)?; - let Value::Text(mut src) = read_text(ctx,path)? else { return Err("apply_patch_blocks needs text".into()); }; - let mut applied = 0i64; - for (find, replace) in blocks { - if find.is_empty() { - return Err("apply_patch_blocks: empty FIND".into()); - } - if find_spans_whole_file(&src, &find) { - return Err( - "apply_patch_blocks: FIND spans entire file (whole-file rewrite forbidden)" - .into(), - ); - } - let count = src.matches(&find).count(); - if count == 0 { - return Err(format!( - "apply_patch_blocks: FIND not found in {}", - display - )); - } - if count > 1 { - return Err(format!( - "apply_patch_blocks: FIND matched {count} times in {} (must be unique)", - display - )); - } - src = src.replacen(&find, &replace, 1); - applied += 1; - } - write_text(ctx,path,&Value::Text(src))?; - Ok(Value::Int(applied)) -} - -fn parse_patch_blocks(text: &str) -> Result, String> { - let mut out = Vec::new(); - let mut rest = text; - while let Some(start) = rest.find("<<<") { - let after = &rest[start + 3..]; - let end = after - .find(">>>") - .ok_or_else(|| "apply_patch_blocks: unclosed <<< block".to_string())?; - let body = after[..end].trim(); - rest = &after[end + 3..]; - let (find_part, replace_part) = body - .split_once("===") - .ok_or_else(|| "apply_patch_blocks: block missing ===".to_string())?; - let find = strip_labeled(find_part, "FIND")?; - let replace = strip_labeled(replace_part, "REPLACE")?; - out.push((find, replace)); - } - if out.is_empty() { - parse_fence_find_replace(text, &mut out)?; - } - if out.is_empty() { - parse_begin_patch_hunks(text, &mut out)?; - } - Ok(out) -} - -/// ```find … ``` followed by ```replace … ``` (label case-insensitive). -fn parse_fence_find_replace(text: &str, out: &mut Vec<(String, String)>) -> Result<(), String> { - let mut i = 0; - while i < text.len() { - let Some(rel) = text[i..].find("```") else { - break; - }; - let open = i + rel; - let after_ticks = open + 3; - let header_end = text[after_ticks..] - .find('\n') - .map(|n| after_ticks + n) - .unwrap_or(text.len()); - let label = text[after_ticks..header_end] - .trim() - .trim_matches('`') - .to_ascii_lowercase(); - if label != "find" { - i = after_ticks; - continue; - } - let body_start = if header_end < text.len() { - header_end + 1 - } else { - header_end - }; - let Some(rel_close) = text[body_start..].find("```") else { - return Err("apply_patch_blocks: unclosed ```find fence".into()); - }; - let find_end = body_start + rel_close; - let find = text[body_start..find_end] - .trim_end_matches(['\r', '\n']) - .to_string(); - let mut j = find_end + 3; - while j < text.len() && text.as_bytes()[j].is_ascii_whitespace() { - j += 1; - } - if text[j..].starts_with("```") { - j += 3; - } else { - return Err("apply_patch_blocks: ```find without following ```replace".into()); - } - let rep_header_end = text[j..] - .find('\n') - .map(|n| j + n) - .unwrap_or(text.len()); - let rep_label = text[j..rep_header_end] - .trim() - .trim_matches('`') - .to_ascii_lowercase(); - if rep_label != "replace" { - return Err("apply_patch_blocks: ```find without following ```replace".into()); - } - let rep_body_start = if rep_header_end < text.len() { - rep_header_end + 1 - } else { - rep_header_end - }; - let Some(rel_rep_close) = text[rep_body_start..].find("```") else { - return Err("apply_patch_blocks: unclosed ```replace fence".into()); - }; - let rep_end = rep_body_start + rel_rep_close; - let replace = text[rep_body_start..rep_end] - .trim_end_matches(['\r', '\n']) - .to_string(); - out.push((find, replace)); - i = rep_end + 3; - } - Ok(()) -} - -/// Minimal support for `*** Begin Patch` / `*** End Patch` with `-`/`+` line pairs -/// (same line count preferred; falls back to joining all `-` vs all `+` in the hunk). -fn parse_begin_patch_hunks(text: &str, out: &mut Vec<(String, String)>) -> Result<(), String> { - const BEGIN: &str = "*** Begin Patch"; - const END: &str = "*** End Patch"; - let mut rest = text; - while let Some(start) = rest.find(BEGIN) { - let after = &rest[start + BEGIN.len()..]; - let end = after - .find(END) - .ok_or_else(|| "apply_patch_blocks: unclosed *** Begin Patch".to_string())?; - let body = &after[..end]; - rest = &after[end + END.len()..]; - let mut minus: Vec<&str> = Vec::new(); - let mut plus: Vec<&str> = Vec::new(); - for line in body.lines() { - if let Some(s) = line.strip_prefix('-') { - if s.starts_with('-') { - continue; // skip --- / file headers like --- - } - // skip diff file headers "*** Update File" already not prefixed with single - - minus.push(s.strip_prefix(' ').unwrap_or(s)); - } else if let Some(s) = line.strip_prefix('+') { - if s.starts_with('+') { - continue; - } - plus.push(s.strip_prefix(' ').unwrap_or(s)); - } - } - if minus.is_empty() { - continue; - } - let find = minus.join("\n"); - let replace = plus.join("\n"); - out.push((find, replace)); - } - Ok(()) -} - -fn strip_labeled(chunk: &str, label: &str) -> Result { - let t = chunk.trim(); - let upper = t.to_ascii_uppercase(); - let label_u = label.to_ascii_uppercase(); - if upper.starts_with(&label_u) { - let after = t[label.len()..].trim_start_matches([':', ' ', '\t']); - let after = after.strip_prefix('\n').unwrap_or(after); - Ok(after.to_string()) - } else { - Ok(t.to_string()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::host::{HostCaps, HostContext}; - use std::fs; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn write_ctx(dir: &std::path::Path) -> HostContext { - let entry = dir.join("entry.mq.md"); - let _ = fs::write(&entry, "# main\n"); - let mut ctx = HostContext::for_run(Some(&entry), HostCaps::default(), vec![]); - ctx.cwd = dir.to_path_buf(); - ctx.fs_root = Some(dir.to_path_buf()); - ctx - } - - fn temp_workspace(tag: &str) -> std::path::PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let dir = std::env::temp_dir().join(format!("marqdo-fs-{tag}-{nanos}")); - fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn text_patch_unique() { - let dir = temp_workspace("patch"); - let path = dir.join("a.md"); - fs::write(&path, "hello OLD world").unwrap(); - let ctx = write_ctx(&dir); - let n = text_patch( - &ctx, - &Value::Text("a.md".into()), - &Value::Text("OLD".into()), - &Value::Text("NEW".into()), - ) - .unwrap(); - assert_eq!(n, Value::Int(1)); - assert_eq!(fs::read_to_string(&path).unwrap(), "hello NEW world"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn apply_patch_blocks_two() { - let dir = temp_workspace("blocks"); - let path = dir.join("a.md"); - fs::write(&path, "aa bb cc").unwrap(); - let ctx = write_ctx(&dir); - let reply = r#" -DECISION: CONTINUE -PATCH: -<<< -FIND -aa -=== -REPLACE -AA ->>> -<<< -FIND -cc -=== -REPLACE -CC ->>> -"#; - let n = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(reply.into()), - None, - ) - .unwrap(); - assert_eq!(n, Value::Int(2)); - assert_eq!(fs::read_to_string(&path).unwrap(), "AA bb CC"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn apply_patch_blocks_fence_find_replace() { - let dir = temp_workspace("fence"); - let path = dir.join("a.md"); - fs::write(&path, "old line\nkeep\n").unwrap(); - let ctx = write_ctx(&dir); - let reply = "DECISION: CONTINUE\nPATCH:\n```find\nold line\n```\n```replace\nnew line\n```\n"; - let n = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(reply.into()), - None, - ) - .unwrap(); - assert_eq!(n, Value::Int(1)); - assert_eq!(fs::read_to_string(&path).unwrap(), "new line\nkeep\n"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn apply_patch_blocks_begin_patch() { - let dir = temp_workspace("beginpatch"); - let path = dir.join("a.md"); - fs::write( - &path, - "> ext/ai/llm.mq.md\n> lib/json.mq.md\n", - ) - .unwrap(); - let ctx = write_ctx(&dir); - let reply = r#" -DECISION: CONTINUE -PATCH: -```patch -*** Begin Patch -*** Update File: a.md -@@ --> ext/ai/llm.mq.md --> lib/json.mq.md -+import: -+ llm: ext/ai/llm.mq.md -+ json: lib/json.mq.md -*** End Patch -``` -"#; - let n = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(reply.into()), - None, - ) - .unwrap(); - assert_eq!(n, Value::Int(1)); - assert_eq!( - fs::read_to_string(&path).unwrap(), - "import:\n llm: ext/ai/llm.mq.md\n json: lib/json.mq.md\n" - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn apply_patch_blocks_soft_miss() { - let dir = temp_workspace("soft"); - let path = dir.join("a.md"); - fs::write(&path, "hello").unwrap(); - let ctx = write_ctx(&dir); - let reply = "<<<\nFIND\nmissing\n===\nREPLACE\nx\n>>>\n"; - let hard = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(reply.into()), - None, - ); - assert!(hard.is_err()); - let n = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(reply.into()), - Some(&Value::Bool(true)), - ) - .unwrap(); - assert_eq!(n, Value::Int(0)); - assert_eq!(fs::read_to_string(&path).unwrap(), "hello"); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn apply_patch_blocks_rejects_whole_file_find() { - let dir = temp_workspace("whole"); - let path = dir.join("a.md"); - let body = format!( - "---\ntitle: workbook\n---\n\n# main\n\n{}", - "line padding for size threshold\n".repeat(40) - ); - assert!(body.len() >= 800, "fixture too small: {}", body.len()); - fs::write(&path, &body).unwrap(); - let ctx = write_ctx(&dir); - let reply = format!( - "<<<\nFIND\n{body}===\nREPLACE\n# main\n\n> print text=bye\n>>>\n" - ); - let err = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(reply), - None, - ) - .unwrap_err(); - assert!( - err.contains("whole-file rewrite forbidden"), - "unexpected err={err}" - ); - assert_eq!(fs::read_to_string(&path).unwrap(), body); - let soft_err = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(format!( - "<<<\nFIND\n{body}===\nREPLACE\nx\n>>>\n" - )), - Some(&Value::Bool(true)), - ) - .unwrap_err(); - assert!(soft_err.contains("whole-file rewrite forbidden")); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn apply_patch_blocks_soft_keeps_multi_match_hard() { - let dir = temp_workspace("multisoft"); - let path = dir.join("a.md"); - fs::write(&path, "xx xx").unwrap(); - let ctx = write_ctx(&dir); - let reply = "<<<\nFIND\nxx\n===\nREPLACE\nYY\n>>>\n"; - let err = apply_patch_blocks( - &ctx, - &Value::Text("a.md".into()), - &Value::Text(reply.into()), - Some(&Value::Bool(true)), - ) - .unwrap_err(); - assert!(err.contains("matched 2 times"), "unexpected err={err}"); - assert_eq!(fs::read_to_string(&path).unwrap(), "xx xx"); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/src/host/fs_ops.rs b/src/host/fs_ops.rs deleted file mode 100755 index 714d0ef..0000000 --- a/src/host/fs_ops.rs +++ /dev/null @@ -1,681 +0,0 @@ -//! Bounded filesystem tasks. Public authors use lib/fs, lib/path and lib/bytes. -use super::{as_text, encoding, fs as legacy, result, sandbox_fs}; -use crate::{ - host::{HostContext, HostFn}, - value::Value, -}; -use sha2::{Digest, Sha256}; -use std::{ - collections::HashMap, - fs, - io::{Read, Seek, SeekFrom, Write}, - path::{Path, PathBuf}, -}; -type Args = HashMap; -const MAX_READ: usize = 64 * 1024 * 1024; -fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { - b.get(k).ok_or_else(|| format!("missing {k}")) -} -fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> { - as_text(arg(b, k)?, k) -} -fn number(b: &Args, k: &str) -> Result { - match arg(b, k)? { - Value::Int(n) if *n >= 0 => Ok(*n as u64), - _ => Err(format!("{k} must be nonnegative integer")), - } -} -fn flag(b: &Args, k: &str) -> bool { - matches!(b.get(k), Some(Value::Bool(true))) -} -fn native(ctx: &HostContext) -> Result<(), String> { - if ctx.sandbox_session.is_some() { - Err("operation unavailable in CoW sandbox; use write_text/remove_file".into()) - } else { - Ok(()) - } -} -fn writable(ctx: &HostContext) -> Result<(), String> { - if ctx.allow_fs_write() { - Ok(()) - } else { - Err("filesystem write denied by host policy".into()) - } -} -fn path(ctx: &HostContext, b: &Args, k: &str) -> Result { - ctx.resolve_path(text(b, k)?) -} -fn ioerr(e: std::io::Error) -> String { - let code = match e.kind() { - std::io::ErrorKind::NotFound => "not_found", - std::io::ErrorKind::PermissionDenied => "permission_denied", - std::io::ErrorKind::AlreadyExists => "conflict", - _ => "operation_failed", - }; - format!("{code}: {e}") -} -fn limit(b: &Args, k: &str) -> Result { - let n = number(b, k)?; - if n == 0 || n > MAX_READ as u64 { - return Err(format!("{k} must be 1..{MAX_READ}")); - } - Ok(n as usize) -} -pub(super) fn bytes_value(bytes: &[u8]) -> Value { - Value::Map(vec![ - ("_type".into(), Value::Text("bytes".into())), - ("base64".into(), Value::Text(encoding::encode_base64(bytes))), - ]) -} -pub(super) fn bytes(v: &Value) -> Result, String> { - let Value::Map(fields) = v else { - return Err("expected bytes record from lib/bytes or fs.read_bytes".into()); - }; - if !fields - .iter() - .any(|(k, v)| k == "_type" && v == &Value::Text("bytes".into())) - { - return Err("expected _type bytes".into()); - } - let text = fields - .iter() - .find(|(k, _)| k == "base64") - .ok_or("missing bytes.base64")?; - encoding::decode_base64(as_text(&text.1, "base64")?) -} -fn read(ctx: &HostContext, p: &Path, max: usize) -> Result, String> { - let mut out = Vec::new(); - if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, p)? { - if bytes.len() > max { - return Err("file exceeds max_bytes".into()); - } - return Ok(bytes); - } - fs::File::open(p) - .map_err(ioerr)? - .take(max as u64 + 1) - .read_to_end(&mut out) - .map_err(ioerr)?; - if out.len() > max { - return Err("file exceeds max_bytes".into()); - } - Ok(out) -} -fn atomic(ctx: &HostContext, p: &Path, body: &[u8]) -> Result<(), String> { - writable(ctx)?; - if sandbox_fs::cow_write_bytes(ctx, p, body)? { - return Ok(()); - } - let parent = p.parent().ok_or("file needs parent")?; - fs::create_dir_all(parent).map_err(ioerr)?; - // create_new reserves the sibling name. Never truncate an existing temp file. - let mut reserved = None; - for _ in 0..128 { - let mut entropy = [0u8; 16]; - getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?; - let name = entropy - .iter() - .map(|b| format!("{b:02x}")) - .collect::(); - let temp = parent.join(format!(".mq-{name}.tmp")); - match fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&temp) - { - Ok(file) => { - reserved = Some((temp, file)); - break; - } - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(ioerr(e)), - } - } - let (temp, mut file) = reserved.ok_or("cannot reserve atomic write file")?; - let result = (|| { - file.write_all(body).map_err(ioerr)?; - file.sync_all().map_err(ioerr)?; - drop(file); - fs::rename(&temp, p).map_err(ioerr) - })(); - if result.is_err() { - let _ = fs::remove_file(&temp); - } - result -} -pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { - let answer = match id { - HostFn::FsTryReadText => { - let answer = (|| { - let data = read(ctx, &path(ctx, b, "path")?, 8 * 1024 * 1024)?; - String::from_utf8(data) - .map(Value::Text) - .map_err(|e| format!("invalid_encoding: {e}")) - })(); - return Ok(result::capture("fs.read_text", answer)); - } - HostFn::FsTryWriteText => { - return Ok(result::capture( - "fs.write_text", - legacy::write_text(ctx, arg(b, "path")?, arg(b, "text")?), - )) - } - HostFn::TryJsonParse => { - return Ok(result::capture( - "json.parse", - super::json::parse(arg(b, "text")?).map_err(|e| format!("invalid_json: {e}")), - )) - } - HostFn::TryCsvParse => { - return Ok(result::capture( - "csv.parse", - super::csv::parse(arg(b, "text")?).map_err(|e| format!("invalid_csv: {e}")), - )) - } - HostFn::BytesFromText => bytes_value(text(b, "text")?.as_bytes()), - HostFn::BytesFromBase64 => bytes_value(&encoding::decode_base64(text(b, "text")?)?), - HostFn::BytesToText => Value::Text( - String::from_utf8(bytes(arg(b, "data")?)?) - .map_err(|e| format!("bytes are not UTF-8: {e}"))?, - ), - HostFn::BytesToBase64 => Value::Text(encoding::encode_base64(&bytes(arg(b, "data")?)?)), - HostFn::BytesLen => Value::Int(bytes(arg(b, "data")?)?.len() as i64), - HostFn::BytesSlice => { - let data = bytes(arg(b, "data")?)?; - let start = usize::try_from(number(b, "start")?) - .unwrap_or(usize::MAX) - .min(data.len()); - let end = usize::try_from(number(b, "end")?) - .unwrap_or(usize::MAX) - .min(data.len()); - bytes_value(if start > end { &[] } else { &data[start..end] }) - } - HostFn::FsReadBytes => { - bytes_value(&read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?) - } - HostFn::FsWriteBytes => { - let p = path(ctx, b, "path")?; - atomic(ctx, &p, &bytes(arg(b, "data")?)?)?; - Value::None - } - HostFn::FsReadChunk => { - let p = path(ctx, b, "path")?; - let offset = number(b, "offset")?; - let size = limit(b, "size")?; - let mut data = vec![0u8; size]; - let (n, total) = if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? { - let start = usize::try_from(offset) - .unwrap_or(usize::MAX) - .min(bytes.len()); - let end = start.saturating_add(size).min(bytes.len()); - data[..end - start].copy_from_slice(&bytes[start..end]); - (end - start, bytes.len() as u64) - } else { - let mut file = fs::File::open(&p).map_err(ioerr)?; - let total = file.metadata().map_err(ioerr)?.len(); - file.seek(SeekFrom::Start(offset)).map_err(ioerr)?; - let n = file.take(size as u64).read(&mut data).map_err(ioerr)?; - (n, total) - }; - data.truncate(n); - let next = offset.checked_add(n as u64).ok_or("offset overflow")?; - Value::Map(vec![ - ("data".into(), bytes_value(&data)), - ("next_offset".into(), Value::Int(next as i64)), - ("eof".into(), Value::Bool(next >= total)), - ]) - } - HostFn::FsAppendBytes => { - writable(ctx)?; - let p = path(ctx, b, "path")?; - let data = bytes(arg(b, "data")?)?; - if ctx.sandbox_session.is_some() { - let mut body = read(ctx, &p, MAX_READ).or_else(|e| { - if matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(false))) { - Ok(vec![]) - } else { - Err(e) - } - })?; - body.extend_from_slice(&data); - sandbox_fs::cow_write_bytes(ctx, &p, &body)?; - } else { - let mut f = fs::OpenOptions::new() - .create(true) - .append(true) - .open(&p) - .map_err(ioerr)?; - f.write_all(&data).map_err(ioerr)?; - } - Value::None - } - HostFn::FsAtomicWrite | HostFn::FsWriteChanged => { - let p = path(ctx, b, "path")?; - let body = text(b, "text")?.as_bytes(); - if id == HostFn::FsWriteChanged && read(ctx, &p, MAX_READ).ok().as_deref() == Some(body) - { - return Ok(Value::Bool(false)); - } - atomic(ctx, &p, body)?; - if id == HostFn::FsWriteChanged { - Value::Bool(true) - } else { - Value::None - } - } - HostFn::FsWriteChecked => { - let change = (|| { - let p = path(ctx, b, "path")?; - let expected = text(b, "expected_sha256")?; - let current = read(ctx, &p, MAX_READ)?; - let actual = format!("{:x}", Sha256::digest(¤t)); - if actual != expected { - return Err("conflict: file content changed".into()); - } - atomic(ctx, &p, text(b, "text")?.as_bytes()).map(|_| Value::None) - })(); - return Ok(result::capture("fs.write_checked", change)); - } - HostFn::FsReadLines => { - let data = read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?; - let text = String::from_utf8(data).map_err(|e| format!("file is not UTF-8: {e}"))?; - Value::List(text.lines().map(|s| Value::Text(s.into())).collect()) - } - HostFn::FsWriteLines => { - let Value::List(lines) = arg(b, "lines")? else { - return Err("lines must be list of text".into()); - }; - let lines = lines - .iter() - .map(|v| as_text(v, "line")) - .collect::, _>>()?; - let mut body = lines.join("\n"); - if !lines.is_empty() { - body.push('\n') - }; - atomic(ctx, &path(ctx, b, "path")?, body.as_bytes())?; - Value::None - } - HostFn::FsRemoveFile => { - writable(ctx)?; - let p = path(ctx, b, "path")?; - if p.is_dir() { - return Err("remove_file refuses directory".into()); - } - if !matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(true))) { - return Err("not_found: remove_file target absent".into()); - } - if !sandbox_fs::cow_remove(ctx, &p)? { - fs::remove_file(p).map_err(ioerr)?; - } - Value::None - } - HostFn::FsRemoveEmptyDir => { - writable(ctx)?; - native(ctx)?; - fs::remove_dir(path(ctx, b, "path")?).map_err(ioerr)?; - Value::None - } - HostFn::FsTempDir => { - writable(ctx)?; - native(ctx)?; - let prefix = text(b, "prefix")?; - if prefix.contains('/') || prefix.contains('\\') || prefix.contains("..") { - return Err("temp prefix must be simple name".into()); - } - let mut created = None; - for _ in 0..128 { - let mut entropy = [0u8; 16]; - getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?; - let name = format!( - "{prefix}-{}", - entropy - .iter() - .map(|n| format!("{n:02x}")) - .collect::() - ); - let p = ctx.resolve_path(&name)?; - match fs::create_dir(p) { - Ok(()) => { - created = Some(Value::Text(name)); - break; - } - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(ioerr(e)), - } - } - created.ok_or("unable to reserve temporary directory")? - } - HostFn::FsFileHash => { - let p = path(ctx, b, "path")?; - let mut hasher = Sha256::new(); - if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? { - hasher.update(bytes) - } else { - let mut f = fs::File::open(p).map_err(ioerr)?; - let mut buffer = [0u8; 65536]; - loop { - let n = f.read(&mut buffer).map_err(ioerr)?; - if n == 0 { - break; - } - hasher.update(&buffer[..n]); - } - } - Value::Text(format!("{:x}", hasher.finalize())) - } - HostFn::FsFind => { - let root = path(ctx, b, "path")?; - let pattern = glob(text(b, "pattern")?)?; - let excluded = patterns(arg(b, "exclude")?)?; - let max_depth = number(b, "max_depth")? as usize; - let kind = text(b, "kind")?; - if !matches!(kind, "file" | "dir" | "all") { - return Err("find kind must be file/dir/all".into()); - } - let mut files = Vec::new(); - find( - ctx, - &root, - Path::new(""), - &pattern, - &excluded, - max_depth, - kind, - &mut files, - )?; - Value::List(files) - } - HostFn::FsCopyTree | HostFn::FsSyncTree => { - writable(ctx)?; - native(ctx)?; - let src = path(ctx, b, "src")?; - let dest = path(ctx, b, "dest")?; - if dest.starts_with(&src) || src.starts_with(&dest) { - return Err("copy/sync trees must be disjoint".into()); - } - if !src.is_dir() { - return Err("src must be directory".into()); - } - let excluded = patterns(arg(b, "exclude")?)?; - let mut files = Vec::new(); - find( - ctx, - &src, - Path::new(""), - &glob("**")?, - &excluded, - 256, - "file", - &mut files, - )?; - let mut jobs = Vec::new(); - for name in files { - let name = as_text(&name, "name")?; - let from = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?; - let to = ctx.resolve_path(dest.join(name).to_str().ok_or("non UTF-8 path")?)?; - if to.exists() { - if id == HostFn::FsSyncTree && files_equal(&from, &to)? { - continue; - } - if !flag(b, "overwrite") { - return Err(format!("destination conflict: {}", to.display())); - } - } - jobs.push((from, to, name.to_string())); - } - let dry = flag(b, "dry_run"); - let mut changed = Vec::new(); - for (from, to, name) in jobs { - if !dry { - if let Some(parent) = to.parent() { - fs::create_dir_all(parent).map_err(ioerr)?; - } - fs::copy(from, to).map_err(ioerr)?; - } - changed.push(Value::Text(name)); - } - Value::List(changed) - } - HostFn::FsRenameMany => { - writable(ctx)?; - native(ctx)?; - let Value::List(rows) = arg(b, "moves")? else { - return Err("moves must be record list".into()); - }; - let mut jobs = Vec::new(); - let mut destinations = std::collections::HashSet::new(); - let mut sources = std::collections::HashSet::new(); - for row in rows { - let Value::Map(fields) = row else { - return Err("move needs src,dest".into()); - }; - let mut paths = Vec::new(); - for key in ["src", "dest"] { - let value = fields - .iter() - .find(|(k, _)| k == key) - .ok_or("move needs src,dest")?; - paths.push(ctx.resolve_path(as_text(&value.1, key)?)?); - } - if !paths[0].is_file() { - return Err("rename_many source must be file".into()); - } - if !sources.insert(paths[0].clone()) { - return Err("conflict: repeated rename source".into()); - } - if paths[1].exists() || !destinations.insert(paths[1].clone()) { - return Err("rename_many destination conflict".into()); - } - jobs.push((paths.remove(0), paths.remove(0))); - } - // Preflight all paths. Execution is ordered and deliberately not transactional. - if !flag(b, "dry_run") { - for (from, to) in &jobs { - if let Some(parent) = to.parent() { - fs::create_dir_all(parent).map_err(ioerr)?; - } - fs::rename(from, to).map_err(ioerr)?; - } - } - Value::Int(jobs.len() as i64) - } - HostFn::PathRelative => { - let normalized = super::path::normalize(arg(b, "path")?)?; - let normalized_base = super::path::normalize(arg(b, "base")?)?; - let path = PathBuf::from(as_text(&normalized, "path")?); - let base = PathBuf::from(as_text(&normalized_base, "base")?); - if path.is_absolute() != base.is_absolute() { - return Err("relative paths must share absolute/relative form".into()); - } - let a: Vec<_> = path.components().collect(); - let b: Vec<_> = base.components().collect(); - if path.is_absolute() && a.first() != b.first() { - return Err("relative paths have different roots".into()); - } - let common = a.iter().zip(&b).take_while(|(a, b)| a == b).count(); - let mut out = PathBuf::new(); - for _ in common..b.len() { - out.push("..") - } - for c in &a[common..] { - out.push(c.as_os_str()) - } - Value::Text(if out.as_os_str().is_empty() { - ".".into() - } else { - out.to_string_lossy().replace('\\', "/") - }) - } - HostFn::PathWithExtension => { - let mut p = PathBuf::from(text(b, "path")?); - let ext = text(b, "extension")?; - if ext.contains('/') || ext.contains('\\') { - return Err("extension cannot contain path separator".into()); - } - p.set_extension(ext.trim_start_matches('.')); - Value::Text(p.to_string_lossy().replace('\\', "/")) - } - _ => return Err("not a filesystem task".into()), - }; - Ok(answer) -} -fn patterns(v: &Value) -> Result, String> { - if matches!(v, Value::None) { - return Ok(vec![]); - } - let Value::List(xs) = v else { - return Err("exclude must be list of patterns".into()); - }; - xs.iter().map(|v| glob(as_text(v, "pattern")?)).collect() -} -fn glob(pattern: &str) -> Result { - let mut out = String::from("^"); - let mut cs = pattern.chars().peekable(); - while let Some(c) = cs.next() { - match c { - '*' => { - if cs.peek() == Some(&'*') { - cs.next(); - if cs.peek() == Some(&'/') { - cs.next(); - out.push_str("(?:.*/)?") - } else { - out.push_str(".*") - } - } else { - out.push_str("[^/]*") - } - } - '?' => out.push_str("[^/]"), - _ => out.push_str(®ex::escape(&c.to_string())), - } - } - out.push('$'); - regex::Regex::new(&out).map_err(|e| e.to_string()) -} -fn find( - ctx: &HostContext, - root: &Path, - rel: &Path, - pattern: ®ex::Regex, - exclude: &[regex::Regex], - depth: usize, - kind: &str, - out: &mut Vec, -) -> Result<(), String> { - if depth == 0 { - return Ok(()); - } - let mut entries = fs::read_dir(root.join(rel)) - .map_err(ioerr)? - .collect::, _>>() - .map_err(ioerr)?; - entries.sort_by_key(|e| e.file_name()); - for entry in entries { - let child = rel.join(entry.file_name()); - let name = child.to_string_lossy().replace('\\', "/"); - let ty = entry.file_type().map_err(ioerr)?; - if exclude - .iter() - .any(|r| r.is_match(&name) || r.is_match(&format!("{name}/"))) - { - continue; - } - // No symlink traversal. Reads returned by this finder still use resolve_path. - if ty.is_symlink() { - continue; - } - ctx.resolve_path(entry.path().to_str().ok_or("non UTF-8 path")?)?; - if pattern.is_match(&name) - && ((ty.is_file() && kind != "dir") || (ty.is_dir() && kind != "file")) - { - if out.len() >= 100_000 { - return Err("find exceeds 100000 entries".into()); - } - out.push(Value::Text(name)) - } - if ty.is_dir() { - find(ctx, root, &child, pattern, exclude, depth - 1, kind, out)? - } - } - Ok(()) -} - -fn files_equal(a: &Path, b: &Path) -> Result { - if fs::metadata(a).map_err(ioerr)?.len() != fs::metadata(b).map_err(ioerr)?.len() { - return Ok(false); - } - let mut a = std::io::BufReader::new(fs::File::open(a).map_err(ioerr)?); - let mut b = std::io::BufReader::new(fs::File::open(b).map_err(ioerr)?); - use std::io::BufRead; - loop { - let left = a.fill_buf().map_err(ioerr)?; - let right = b.fill_buf().map_err(ioerr)?; - if left.is_empty() || right.is_empty() { - return Ok(left.is_empty() && right.is_empty()); - } - let n = left.len().min(right.len()); - if left[..n] != right[..n] { - return Ok(false); - } - a.consume(n); - b.consume(n); - } -} - -#[cfg(test)] -mod overlay_tests { - use super::*; - #[test] - fn byte_append_copy_and_patch_stay_in_the_overlay_until_commit() { - let root = std::env::temp_dir().join(format!("mq-byte-overlay-{}", std::process::id())); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("note.md"), "old text").unwrap(); - let mut ctx = - HostContext::for_run(Some(&root.join("main.mq.md")), Default::default(), vec![]); - let session = sandbox_fs::open(Some(root.to_str().unwrap()), &ctx).unwrap(); - let id = session["id"].as_str().unwrap().to_string(); - ctx.sandbox_session = Some(id.clone()); - legacy::text_patch( - &ctx, - &Value::Text("note.md".into()), - &Value::Text("old".into()), - &Value::Text("new".into()), - ) - .unwrap(); - assert_eq!( - fs::read_to_string(root.join("note.md")).unwrap(), - "old text" - ); - assert_eq!( - legacy::read_text(&ctx, &Value::Text("note.md".into())).unwrap(), - Value::Text("new text".into()) - ); - let mut args = Args::from([ - ("path".into(), Value::Text("data.bin".into())), - ("data".into(), bytes_value(&[0, 255])), - ]); - call(&mut ctx, HostFn::FsWriteBytes, &args).unwrap(); - args.insert("data".into(), bytes_value(&[128])); - call(&mut ctx, HostFn::FsAppendBytes, &args).unwrap(); - legacy::copy_file( - &ctx, - &Value::Text("data.bin".into()), - &Value::Text("copied.bin".into()), - ) - .unwrap(); - assert_eq!( - sandbox_fs::cow_read_bytes(&ctx, &root.join("copied.bin")) - .unwrap() - .unwrap(), - [0, 255, 128] - ); - assert!(!root.join("data.bin").exists()); - assert!(!root.join("copied.bin").exists()); - assert!(legacy::make_dirs(&ctx, &Value::Text("unsupported".into())).is_err()); - assert!(!root.join("unsupported").exists()); - sandbox_fs::discard(&id).unwrap(); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/host/hash.rs b/src/host/hash.rs deleted file mode 100755 index 1d3b801..0000000 --- a/src/host/hash.rs +++ /dev/null @@ -1,62 +0,0 @@ -//! Digest / HMAC host primitives for Mid M3 (`lib/hash`). - -use crate::host::as_text; -use hmac::{Hmac, Mac}; -use md5::Md5; -use sha1::Sha1; -use sha2::{Digest, Sha256}; - -use crate::value::Value; - -type HmacSha256 = Hmac; - - -fn to_hex(bytes: &[u8]) -> String { - bytes.iter().map(|b| format!("{b:02x}")).collect() -} - -pub fn sha256(text: &Value) -> Result { - let t = as_text(text, "text")?; - let mut h = Sha256::new(); - h.update(t.as_bytes()); - Ok(Value::Text(to_hex(&h.finalize()))) -} - -pub fn sha1(text: &Value) -> Result { - let t = as_text(text, "text")?; - let mut h = Sha1::new(); - h.update(t.as_bytes()); - Ok(Value::Text(to_hex(&h.finalize()))) -} - -pub fn md5(text: &Value) -> Result { - let t = as_text(text, "text")?; - let mut h = Md5::new(); - h.update(t.as_bytes()); - Ok(Value::Text(to_hex(&h.finalize()))) -} - -pub fn hmac_sha256(key: &Value, text: &Value) -> Result { - let k = as_text(key, "key")?; - let t = as_text(text, "text")?; - let mut mac = - HmacSha256::new_from_slice(k.as_bytes()).map_err(|e| format!("hmac_sha256: {e}"))?; - mac.update(t.as_bytes()); - Ok(Value::Text(to_hex(&mac.finalize().into_bytes()))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sha256_empty() { - let v = sha256(&Value::Text("".into())).unwrap(); - assert_eq!( - v, - Value::Text( - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".into() - ) - ); - } -} diff --git a/src/host/html_ops.rs b/src/host/html_ops.rs deleted file mode 100755 index 07781cb..0000000 --- a/src/host/html_ops.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! HTML escape / unescape for Mid2 M8 (`lib/html`). - -use crate::host::as_text; -use crate::value::Value; - - -pub fn escape(text: &Value) -> Result { - let s = as_text(text, "text")?; - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - _ => out.push(c), - } - } - Ok(Value::Text(out)) -} - -pub fn unescape(text: &Value) -> Result { - let s = as_text(text, "text")?; - let mut out = String::with_capacity(s.len()); - let mut rest = s; - while let Some(i) = rest.find('&') { - out.push_str(&rest[..i]); - rest = &rest[i..]; - if let Some(end) = rest.find(';') { - let ent = &rest[..=end]; - let ch = match ent { - "&" => Some('&'), - "<" => Some('<'), - ">" => Some('>'), - """ => Some('"'), - "'" | "'" | "'" => Some('\''), - _ => None, - }; - if let Some(c) = ch { - out.push(c); - rest = &rest[end + 1..]; - continue; - } - } - out.push('&'); - rest = &rest[1..]; - } - out.push_str(rest); - Ok(Value::Text(out)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn roundtrip() { - let e = escape(&Value::Text(r#"a&"c'"#.into())).unwrap(); - assert_eq!( - e, - Value::Text("a<b>&"c'".into()) - ); - assert_eq!(unescape(&e).unwrap(), Value::Text(r#"a&"c'"#.into())); - } -} diff --git a/src/host/json.rs b/src/host/json.rs deleted file mode 100755 index 5559401..0000000 --- a/src/host/json.rs +++ /dev/null @@ -1,456 +0,0 @@ -//! JSON host primitives + Value↔JSON mapping. -//! -//! Integer gate matches Lean \(V_{\mathsf{safe}}\) (`doc/design/v-safe-json.md`): -//! JSON integers with `|n| > 2^53-1` refuse on encode and decode. - -use crate::value::Value; - -/// JavaScript `Number.MAX_SAFE_INTEGER` / Lean `ForeignJSON.maxSafe`. -pub const MAX_SAFE_INT: i64 = 9_007_199_254_740_991; // 2^53 - 1 - -pub fn in_safe_int(n: i64) -> bool { - (-MAX_SAFE_INT..=MAX_SAFE_INT).contains(&n) -} - -fn ood_int_err(n: impl std::fmt::Display) -> String { - format!("json: integer outside V_safe (±(2^53-1)): {n}") -} - -/// The integer boundary is semantic, not a property of JSON spelling or the -/// host's Int/Num tag. Exponent notation must not bypass it. -fn checked_number(n: f64) -> Result { - if !n.is_finite() { return Err("json: non-finite number outside V_safe".into()); } - if n.fract() == 0.0 && n.abs() > MAX_SAFE_INT as f64 { return Err(ood_int_err(n)); } - Ok(serde_json::Value::Number(serde_json::Number::from_f64(n) - .ok_or("json: non-finite number outside V_safe")?)) -} - -#[derive(Debug)] -pub(crate) enum DecodeError { Syntax(String), Domain(String) } - -struct BoundaryValue(Value); -impl<'de> serde::Deserialize<'de> for BoundaryValue { - fn deserialize>(de: D) -> Result { - struct BoundaryVisitor; - impl<'de> serde::de::Visitor<'de> for BoundaryVisitor { - type Value = BoundaryValue; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("a boundary JSON value") } - fn visit_unit(self) -> Result { Ok(BoundaryValue(Value::None)) } - fn visit_bool(self, v: bool) -> Result { Ok(BoundaryValue(Value::Bool(v))) } - fn visit_i64(self, n: i64) -> Result { - if !in_safe_int(n) { return Err(E::custom(ood_int_err(n))); } - Ok(BoundaryValue(Value::Int(n))) - } - fn visit_u64(self, n: u64) -> Result { - if n > MAX_SAFE_INT as u64 { return Err(E::custom(ood_int_err(n))); } - Ok(BoundaryValue(Value::Int(n as i64))) - } - fn visit_f64(self, n: f64) -> Result { - checked_number(n).map_err(E::custom)?; - Ok(BoundaryValue(Value::Num(n))) - } - fn visit_str(self, v: &str) -> Result { Ok(BoundaryValue(Value::Text(v.into()))) } - fn visit_string(self, v: String) -> Result { Ok(BoundaryValue(Value::Text(v))) } - fn visit_seq>(self, mut seq: A) -> Result { - let mut xs = Vec::new(); - while let Some(BoundaryValue(v)) = seq.next_element()? { xs.push(v); } - Ok(BoundaryValue(Value::List(xs))) - } - fn visit_map>(self, mut map: A) -> Result { - use serde::de::Error; - let mut fields = Vec::new(); - let mut keys = std::collections::HashSet::new(); - while let Some(key) = map.next_key::()? { - if !keys.insert(key.clone()) { return Err(A::Error::custom("json: duplicate object key outside V_safe")); } - let BoundaryValue(v) = map.next_value()?; - fields.push((key, v)); - } - // Preserve the pre-existing JSON object's canonical key order. - fields.sort_by(|a, b| a.0.cmp(&b.0)); - let value = Value::Map(fields); - value_to_json(&value).map_err(A::Error::custom)?; - Ok(BoundaryValue(value)) - } - } - de.deserialize_any(BoundaryVisitor) - } -} - -pub(crate) fn decode_text(text: &str) -> Result { - use serde::Deserialize; - let classify = |error: serde_json::Error| { - let message = error.to_string(); - // serde_json categorizes its own numeric-overflow diagnostic as Syntax. - // It is a domain refusal for a grammar-valid unbounded JSON number. - // Match this trusted decoder diagnostic, never foreign program output. - if message.starts_with("number out of range at line ") { - return DecodeError::Domain(format!("json: number outside V_safe: {message}")); - } - match error.classify() { - serde_json::error::Category::Data => DecodeError::Domain(message), - _ => DecodeError::Syntax(message), - } - }; - let mut de = serde_json::Deserializer::from_str(text); - let value = BoundaryValue::deserialize(&mut de).map_err(classify)?; - de.end().map_err(classify)?; - Ok(value.0) -} - - -/// The call protocol envelope is not a runtime column table. Validate each -/// actual argument with BoundaryValue while keeping duplicate-key detection. -pub(crate) fn decode_arguments(text: &str) -> Result, String> { - use serde::Deserialize; - struct Arguments(Vec<(String, Value)>); - impl<'de> serde::Deserialize<'de> for Arguments { - fn deserialize>(de: D) -> Result { - struct Visitor; - impl<'de> serde::de::Visitor<'de> for Visitor { - type Value = Arguments; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("a JSON object of named arguments") - } - fn visit_map>(self, mut map: A) -> Result { - use serde::de::Error; - let mut args = Vec::new(); - let mut keys = std::collections::HashSet::new(); - while let Some(key) = map.next_key::()? { - if !keys.insert(key.clone()) { return Err(A::Error::custom("duplicate argument name")); } - let BoundaryValue(value) = map.next_value()?; - args.push((key, value)); - } - Ok(Arguments(args)) - } - } - de.deserialize_map(Visitor) - } - } - let mut de = serde_json::Deserializer::from_str(text); - let args = Arguments::deserialize(&mut de).map_err(|e| e.to_string())?; - de.end().map_err(|e| e.to_string())?; - Ok(args.0) -} - -pub fn parse(text: &Value) -> Result { - let s = match text { - Value::Text(s) => s.as_str(), - _ => return Err("json parse needs text".into()), - }; - decode_text(s).map_err(|e| match e { - DecodeError::Syntax(e) | DecodeError::Domain(e) => format!("json parse: {e}"), - }) -} - -pub fn stringify(value: &Value, indent: Option<&Value>) -> Result { - let j = value_to_json(value)?; - let pretty = match indent { - None => false, - Some(Value::Int(n)) => *n > 0, - Some(Value::Bool(b)) => *b, - Some(Value::None) => false, - Some(_) => return Err("json stringify indent must be int or bool".into()), - }; - let s = if pretty { - serde_json::to_string_pretty(&j).map_err(|e| format!("json stringify: {e}"))? - } else { - serde_json::to_string(&j).map_err(|e| format!("json stringify: {e}"))? - }; - Ok(Value::Text(s)) -} - -pub fn get(value: &Value, key: &Value) -> Result { - let k = match key { - Value::Text(s) => s.as_str(), - _ => return Err("json get key must be text".into()), - }; - match value { - Value::Map(entries) => Ok(entries - .iter() - .find(|(kk, _)| kk == k) - .map(|(_, v)| v.clone()) - .unwrap_or(Value::None)), - _ => Err("json get needs map".into()), - } -} - -pub fn keys(value: &Value) -> Result { - match value { - Value::Map(entries) => Ok(Value::List( - entries.iter().map(|(k, _)| Value::Text(k.clone())).collect(), - )), - _ => Err("json keys needs map".into()), - } -} - -/// JSON-encode a text value including surrounding quotes (for building request bodies). -pub fn quote(text: &Value) -> Result { - let s = match text { - Value::Text(s) => s.as_str(), - _ => return Err("json quote needs text".into()), - }; - serde_json::to_string(s) - .map(Value::Text) - .map_err(|e| format!("json quote: {e}")) -} - -pub(crate) fn json_to_value(v: &serde_json::Value) -> Result { - Ok(match v { - serde_json::Value::Null => Value::None, - serde_json::Value::Bool(b) => Value::Bool(*b), - serde_json::Value::Number(n) => { - if let Some(i) = n.as_i64() { - if !in_safe_int(i) { - return Err(ood_int_err(i)); - } - Value::Int(i) - } else if let Some(u) = n.as_u64() { - // Always > i64::MAX ⇒ outside V_safe; never coerce via f64/Text. - return Err(ood_int_err(u)); - } else if let Some(f) = n.as_f64() { - // Host extension: non-integer JSON numbers → Num (not in Lean SafeVal). - checked_number(f)?; - Value::Num(f) - } else { - return Err(format!("json: unsupported number: {n}")); - } - } - serde_json::Value::String(s) => Value::Text(s.clone()), - serde_json::Value::Array(xs) => { - let mut out = Vec::with_capacity(xs.len()); - for x in xs { - out.push(json_to_value(x)?); - } - Value::List(out) - } - serde_json::Value::Object(map) => { - let mut entries = Vec::with_capacity(map.len()); - for (k, v) in map { - entries.push((k.clone(), json_to_value(v)?)); - } - Value::Map(entries) - } - }) -} - -pub(crate) fn value_to_json(v: &Value) -> Result { - Ok(match v { - Value::None => serde_json::Value::Null, - Value::Bool(b) => serde_json::Value::Bool(*b), - Value::Int(n) => { - if !in_safe_int(*n) { - return Err(ood_int_err(*n)); - } - serde_json::Value::Number((*n).into()) - } - Value::Num(n) => checked_number(*n)?, - Value::Text(s) => serde_json::Value::String(s.clone()), - Value::List(xs) => { - let mut arr = Vec::with_capacity(xs.len()); - for x in xs { - arr.push(value_to_json(x)?); - } - serde_json::Value::Array(arr) - } - Value::Map(entries) => { - // Column-table maps (all fields lists): refuse unequal list lengths. - let list_lens: Vec = entries - .iter() - .filter_map(|(_, v)| match v { - Value::List(xs) => Some(xs.len()), - _ => None, - }) - .collect(); - if list_lens.len() == entries.len() && list_lens.len() >= 2 { - let n0 = list_lens[0]; - if list_lens.iter().any(|&n| n != n0) { - return Err( - "json: table column arity mismatch (unequal list lengths)".into(), - ); - } - } - let mut map = serde_json::Map::new(); - for (k, v) in entries { - map.insert(k.clone(), value_to_json(v)?); - } - serde_json::Value::Object(map) - } - Value::Formula(e) => match e { - crate::formula::Expr::Matrix { rows, .. } => { - let mut arr = Vec::with_capacity(rows.len()); - for row in rows { - let mut cells = Vec::with_capacity(row.len()); - for &n in row { - cells.push( - serde_json::Number::from_f64(n) - .map(serde_json::Value::Number) - .ok_or_else(|| "json: non-finite number outside V_safe".to_string())?, - ); - } - arr.push(serde_json::Value::Array(cells)); - } - serde_json::Value::Array(arr) - } - other => { - let s = crate::formula::simplify(other); - if let crate::formula::Expr::Num(n) = s { - serde_json::Number::from_f64(n) - .map(serde_json::Value::Number) - .ok_or_else(|| "json: non-finite number outside V_safe".to_string())? - } else { - serde_json::Value::String(e.as_display()) - } - } - }, - Value::Code(c) => serde_json::Value::String(c.source.clone()), - Value::Secret(_) => serde_json::Value::String("".into()), - Value::Handle(_) => { - return Err("json: session handle cannot be serialized".into()); - } - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn quote_escapes_text() { - let q = quote(&Value::Text("a\"b".into())).unwrap(); - assert_eq!(q, Value::Text("\"a\\\"b\"".into())); - } - - #[test] - fn roundtrip_max_safe() { - for n in [MAX_SAFE_INT, -MAX_SAFE_INT, 0_i64, 1, -1] { - let j = value_to_json(&Value::Int(n)).unwrap(); - let v = json_to_value(&j).unwrap(); - assert_eq!(v, Value::Int(n)); - } - } - - #[test] - fn refuse_ood_encode() { - for n in [ - MAX_SAFE_INT + 1, - -MAX_SAFE_INT - 1, - 1_i64 << 53, // 2^53 - 1_i64 << 60, // 2^60 - (1_i64 << 60) + 1, // 2^60+1 - ] { - let err = value_to_json(&Value::Int(n)).unwrap_err(); - assert!( - err.contains("outside V_safe"), - "encode {n}: {err}" - ); - } - } - - #[test] - fn refuse_ood_decode() { - for n in [ - MAX_SAFE_INT + 1, - -MAX_SAFE_INT - 1, - 1_i64 << 53, - 1_i64 << 60, - (1_i64 << 60) + 1, - ] { - let raw = format!("{n}"); - let j: serde_json::Value = serde_json::from_str(&raw).unwrap(); - let err = json_to_value(&j).unwrap_err(); - assert!( - err.contains("outside V_safe"), - "decode {n}: {err}" - ); - } - } - - #[test] - fn refuse_nested_ood() { - let j: serde_json::Value = - serde_json::from_str("{\"a\":[1152921504606846977]}").unwrap(); - let err = json_to_value(&j).unwrap_err(); - assert!(err.contains("outside V_safe"), "{err}"); - } - - #[test] - fn decimal_string_ok() { - let j = serde_json::Value::String("1152921504606846977".into()); - assert_eq!( - json_to_value(&j).unwrap(), - Value::Text("1152921504606846977".into()) - ); - } - - #[test] - fn float_host_extension_ok() { - let j: serde_json::Value = serde_json::from_str("1.5").unwrap(); - match json_to_value(&j).unwrap() { - Value::Num(f) => assert!((f - 1.5).abs() < 1e-12), - other => panic!("expected Num, got {other:?}"), - } - } - - #[test] - fn refuse_u64_above_i64_max() { - // 2^63 as JSON integer: as_i64 fails, as_u64 succeeds. - let j: serde_json::Value = serde_json::from_str("9223372036854775808").unwrap(); - let err = json_to_value(&j).unwrap_err(); - assert!(err.contains("outside V_safe"), "{err}"); - } - - #[test] - fn refuse_session_handle_encode() { - let err = value_to_json(&Value::Handle("s1".into())).unwrap_err(); - assert!( - err.contains("session handle cannot be serialized"), - "{err}" - ); - } - - #[test] - fn refuse_unequal_column_table_encode() { - let ragged = Value::Map(vec![ - ("a".into(), Value::List(vec![Value::Int(1), Value::Int(2)])), - ("b".into(), Value::List(vec![Value::Int(3)])), - ]); - let err = value_to_json(&ragged).unwrap_err(); - assert!(err.contains("arity mismatch"), "{err}"); - } - #[test] - fn refuse_nonfinite_in_nested_payloads() { - for n in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - for v in [Value::Num(n), Value::List(vec![Value::Num(n)]), - Value::Map(vec![("x".into(), Value::Num(n))])] { - assert!(value_to_json(&v).unwrap_err().contains("outside V_safe")); - } - } - } - - #[test] - fn exponent_and_float_tags_cannot_bypass_integer_domain() { - for text in ["9007199254740992.0", "9.007199254740992e15", "1e100", "1e9999", "-9.007199254740992e15"] { - assert!(parse(&Value::Text(text.into())).unwrap_err().contains("outside V_safe"), "{text}"); - } - for n in [9_007_199_254_740_992.0, -9_007_199_254_740_992.0, 1e100] { - assert!(value_to_json(&Value::List(vec![Value::Num(n)])).unwrap_err().contains("outside V_safe")); - } - for text in ["1.5", "-0.0", "9.007199254740991e15"] { - assert!(parse(&Value::Text(text.into())).is_ok(), "valid extension {text}"); - } - } - - #[test] - fn strict_decode_refuses_duplicate_keys_and_ragged_columns() { - for text in [r#"{"a":1,"a":2}"#, r#"[{"x":null,"x":true}]"#, - r#"{"a":[1],"b":[2,3]}"#] { - assert!(matches!(decode_text(text), Err(DecodeError::Domain(_))), "{text}"); - } - for text in [r#"{"a":[1],"b":"metadata"}"#, r#"{"a":[],"b":[]}"#, - r#"{"__proto__":{"safe":true},"constructor":"data"}"#] { - assert!(decode_text(text).is_ok(), "{text}"); - } - assert!(matches!(decode_text("not JSON"), Err(DecodeError::Syntax(_)))); - } - -} diff --git a/src/host/log.rs b/src/host/log.rs deleted file mode 100755 index c0f54c1..0000000 --- a/src/host/log.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Log level gate for Mid M6 (`lib/log`). - -use crate::host::as_text; -use crate::host::HostContext; -use crate::value::Value; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub enum Level { - Debug = 10, - Info = 20, - Warn = 30, - Error = 40, -} - -impl Level { - pub fn parse(s: &str) -> Result { - match s.trim().to_ascii_lowercase().as_str() { - "debug" | "调试" => Ok(Self::Debug), - "info" | "信息" => Ok(Self::Info), - "warn" | "warning" | "警告" => Ok(Self::Warn), - "error" | "错误" => Ok(Self::Error), - _ => Err(format!("log: unknown level {s:?}")), - } - } - - pub fn label(self) -> &'static str { - match self { - Self::Debug => "DEBUG", - Self::Info => "INFO", - Self::Warn => "WARN", - Self::Error => "ERROR", - } - } -} - - -pub fn set_level(ctx: &mut HostContext, level: &Value) -> Result { - let s = as_text(level, "level")?; - ctx.log_min_level = Level::parse(s)? as u8; - Ok(Value::None) -} - -/// Return a ready-to-print line, or `None` if filtered out. -/// Optional `fields` map is appended as `key=value` pairs (stable map order). -pub fn line( - ctx: &HostContext, - level: &Value, - text: &Value, - fields: Option<&Value>, -) -> Result { - let lvl = Level::parse(as_text(level, "level")?)?; - let msg = as_text(text, "text")?; - if (lvl as u8) < ctx.log_min_level { - return Ok(Value::None); - } - let mut out = format!("{} {}", lvl.label(), msg); - match fields { - None | Some(Value::None) => {} - Some(Value::Map(entries)) => { - for (k, v) in entries { - out.push(' '); - out.push_str(k); - out.push('='); - out.push_str(&v.as_display()); - } - } - Some(_) => return Err("log: fields must be a map".into()), - } - Ok(Value::Text(out)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn filters_debug() { - let mut ctx = HostContext::default(); - assert_eq!(ctx.log_min_level, Level::Info as u8); - let filtered = line( - &ctx, - &Value::Text("debug".into()), - &Value::Text("x".into()), - None, - ) - .unwrap(); - assert_eq!(filtered, Value::None); - set_level(&mut ctx, &Value::Text("debug".into())).unwrap(); - let shown = line( - &ctx, - &Value::Text("debug".into()), - &Value::Text("x".into()), - None, - ) - .unwrap(); - assert_eq!(shown, Value::Text("DEBUG x".into())); - let with = line( - &ctx, - &Value::Text("info".into()), - &Value::Text("hi".into()), - Some(&Value::Map(vec![ - ("user".into(), Value::Text("a".into())), - ("n".into(), Value::Int(1)), - ])), - ) - .unwrap(); - assert_eq!(with, Value::Text("INFO hi user=a n=1".into())); - } -} diff --git a/src/host/math.rs b/src/host/math.rs deleted file mode 100755 index e2a5bc6..0000000 --- a/src/host/math.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! Host entry points for math / formula / random / plot. - -use std::collections::HashMap; - -use crate::formula::{self, Expr}; -use crate::host::fs; -use crate::host::{HostContext, PlotArtifact}; -use crate::value::Value; - -pub fn as_f64(v: &Value) -> Result { - match v { - Value::Num(n) => Ok(*n), - Value::Int(n) => Ok(*n as f64), - Value::Text(s) => s - .trim() - .parse::() - .map_err(|_| format!("cannot convert to num: {s:?}")), - _ => Err("expected num (or int/text)".into()), - } -} - -fn opt<'a>(v: Option<&'a Value>) -> Option<&'a Value> { - match v { - None | Some(Value::None) => None, - Some(v) => Some(v), - } -} - -pub fn as_text(v: &Value) -> Result<&str, String> { - match v { - Value::Text(s) => Ok(s.as_str()), - _ => Err("expected text".into()), - } -} - -pub fn as_bool(v: &Value) -> bool { - v.truthy() -} - -pub fn formula_from_value(v: &Value) -> Result { - match v { - Value::Formula(e) => Ok(e.clone()), - Value::Text(s) => formula::parse(s), - Value::Num(n) => Ok(Expr::Num(*n)), - Value::Int(n) => Ok(Expr::Num(*n as f64)), - _ => Err("expected formula or expression text".into()), - } -} - -fn num_val(n: f64) -> Value { - Value::Num(n) -} - -pub fn pi() -> Result { - Ok(num_val(std::f64::consts::PI)) -} - -pub fn e_const() -> Result { - Ok(num_val(std::f64::consts::E)) -} - -pub fn to_num(v: &Value) -> Result { - Ok(num_val(as_f64(v)?)) -} - -pub fn unary_num(op: &str, x: &Value) -> Result { - let x = as_f64(x)?; - let y = match op { - "neg" => -x, - "sin" => x.sin(), - "cos" => x.cos(), - "tan" => x.tan(), - "asin" => x.asin(), - "acos" => x.acos(), - "atan" => x.atan(), - "sqrt" => x.sqrt(), - "abs" => x.abs(), - "ln" | "log" => x.ln(), - "exp" => x.exp(), - "floor" => x.floor(), - "ceil" => x.ceil(), - _ => return Err(format!("unknown unary math op `{op}`")), - }; - Ok(num_val(y)) -} - -pub fn binary_num(op: &str, a: &Value, b: &Value) -> Result { - let a = as_f64(a)?; - let b = as_f64(b)?; - let y = match op { - "add" => a + b, - "sub" => a - b, - "mul" => a * b, - "div" => { - if b == 0.0 { - return Err("division by zero".into()); - } - a / b - } - "pow" => a.powf(b), - "min" => a.min(b), - "max" => a.max(b), - _ => return Err(format!("unknown binary math op `{op}`")), - }; - Ok(num_val(y)) -} - -pub fn seed(ctx: &mut HostContext, v: &Value) -> Result { - let n = as_f64(v)? as u64; - ctx.rng = n ^ 0xA5A5_A5A5_A5A5_A5A5; - if ctx.rng == 0 { - ctx.rng = 0xC0FFEE; - } - Ok(Value::None) -} - -pub fn random(ctx: &mut HostContext) -> Result { - Ok(num_val(ctx.next_f64())) -} - -pub fn random_int(ctx: &mut HostContext, lo: &Value, hi: &Value) -> Result { - let lo = as_f64(lo)? as i64; - let hi = as_f64(hi)? as i64; - if hi < lo { - return Err("random_int: max < min".into()); - } - let span = (hi - lo + 1) as u64; - let r = ctx.next_u64() % span; - Ok(Value::Int(lo + r as i64)) -} - -pub fn formula_parse(text: &Value) -> Result { - let s = as_text(text)?; - Ok(Value::Formula(formula::parse(s)?)) -} - -pub fn simplify(v: &Value) -> Result { - Ok(Value::Formula(formula::simplify(&formula_from_value(v)?))) -} - -pub fn expand(v: &Value) -> Result { - Ok(Value::Formula(formula::expand(&formula_from_value(v)?))) -} - -pub fn diff(formula: &Value, var: &Value) -> Result { - let e = formula_from_value(formula)?; - let var = as_text(var)?; - Ok(Value::Formula(formula::diff(&e, var))) -} - -pub fn subs(formula: &Value, var: &Value, value: &Value) -> Result { - let e = formula_from_value(formula)?; - let var = as_text(var)?; - let val = formula_from_value(value)?; - let out = formula::subs(&e, var, &val); - if let Expr::Num(n) = out { - Ok(num_val(n)) - } else { - Ok(Value::Formula(out)) - } -} - -pub fn eval_at(formula: &Value, var: &Value, value: &Value) -> Result { - let e = formula_from_value(formula)?; - let var = as_text(var)?; - let x = as_f64(value)?; - let mut env = HashMap::new(); - env.insert(var.to_string(), x); - Ok(num_val(formula::eval_f64(&e, &env)?)) -} - -pub fn solve( - formula: &Value, - var: &Value, - min: Option<&Value>, - max: Option<&Value>, -) -> Result { - let e = formula_from_value(formula)?; - let var = as_text(var)?; - let xmin = opt(min).map(as_f64).transpose()?.unwrap_or(-100.0); - let xmax = opt(max).map(as_f64).transpose()?.unwrap_or(100.0); - let roots = formula::solve(&e, var, xmin, xmax)?; - Ok(Value::List(roots.into_iter().map(num_val).collect())) -} - -fn maybe_write_plot( - ctx: &mut HostContext, - path: Option<&Value>, - svg: String, -) -> Result { - let path_s = match opt(path) { - Some(v) => Some(as_text(v)?.to_string()), - None => None, - }; - if let Some(ref p) = path_s { - fs::write_text(ctx, &Value::Text(p.clone()), &Value::Text(svg.clone()))?; - } - ctx.plots.push(PlotArtifact { - path: path_s, - svg: svg.clone(), - }); - Ok(Value::Text(svg)) -} - -fn plot_style(grid: Option<&Value>) -> Result { - let grid = match opt(grid) { - None => true, - Some(v) => as_bool(v), - }; - Ok(formula::PlotStyle { grid }) -} - -pub fn plot( - ctx: &mut HostContext, - formula: &Value, - var: &Value, - min: &Value, - max: &Value, - steps: Option<&Value>, - path: Option<&Value>, - derivative: Option<&Value>, - grid: Option<&Value>, -) -> Result { - let mut e = formula_from_value(formula)?; - let var_s = as_text(var)?; - if opt(derivative).map(as_bool).unwrap_or(false) { - e = formula::diff(&e, var_s); - } - let xmin = as_f64(min)?; - let xmax = as_f64(max)?; - let steps = match opt(steps) { - Some(v) => as_f64(v)? as usize, - None => 200, - }; - let style = plot_style(grid)?; - let svg = formula::plot_function_svg(&e, var_s, xmin, xmax, steps, style)?; - maybe_write_plot(ctx, path, svg) -} - -pub fn plot_points( - ctx: &mut HostContext, - xs: &Value, - ys: &Value, - path: Option<&Value>, - grid: Option<&Value>, -) -> Result { - let xs = match xs { - Value::List(xs) => xs - .iter() - .map(as_f64) - .collect::, _>>()?, - _ => return Err("plot_points needs list xs".into()), - }; - let ys = match ys { - Value::List(ys) => ys - .iter() - .map(as_f64) - .collect::, _>>()?, - _ => return Err("plot_points needs list ys".into()), - }; - let style = plot_style(grid)?; - let svg = formula::plot_points_svg(&xs, &ys, style)?; - maybe_write_plot(ctx, path, svg) -} - -pub fn plot_conic( - ctx: &mut HostContext, - kind: &Value, - a: &Value, - b: Option<&Value>, - h: Option<&Value>, - k: Option<&Value>, - path: Option<&Value>, - grid: Option<&Value>, -) -> Result { - let kind = as_text(kind)?; - let a = as_f64(a)?; - let b = opt(b).map(as_f64).transpose()?.unwrap_or(a); - let h = opt(h).map(as_f64).transpose()?.unwrap_or(0.0); - let k = opt(k).map(as_f64).transpose()?.unwrap_or(0.0); - let style = plot_style(grid)?; - let svg = formula::plot_conic_svg(kind, a, b, h, k, style)?; - maybe_write_plot(ctx, path, svg) -} diff --git a/src/host/mod.rs b/src/host/mod.rs deleted file mode 100755 index 34feb78..0000000 --- a/src/host/mod.rs +++ /dev/null @@ -1,363 +0,0 @@ -//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, `math`, …). -//! -//! User docs should import L1 wrappers; these `host_*` names are the Rust surface. -//! Capabilities default **on** (importing a lib means you intend to use it). -//! Soft side-effects (no process::exit; sleep clamp) apply under view / capture only. - -pub mod agent_rt; -pub mod collection; -mod dispatch; -mod cli; -mod csv; -mod datetime; -mod encoding; -pub mod event_bus; -#[cfg(feature = "exec-host")] -pub mod foreign; -#[cfg(feature = "exec-host")] -pub mod foreign_doc; -#[cfg(feature = "exec-host")] -pub mod foreign_session; -mod fs; -mod hash; -mod html_ops; -pub(crate) mod json; -mod log; -pub(crate) mod oracle; -pub mod math; -mod net; -mod path; -mod re; -mod secrets; -mod stats; -mod text_ops; -mod time; -pub(crate) mod toml_ops; -mod url_ops; -mod uuid_ops; -#[cfg(feature = "plugin-host")] -pub mod plugin; -#[cfg(not(feature = "plugin-host"))] -#[path = "plugin_stub.rs"] -pub mod plugin; -#[cfg(feature = "exec-host")] -pub mod subtask; -#[cfg(not(feature = "exec-host"))] -#[path = "subtask_stub.rs"] -pub mod subtask; -pub mod sandbox_fs; -mod sys; -pub mod writeback; - -pub use dispatch::{call_host, HostFn}; - -/// Shared `text` argument extraction for host modules. -/// -/// `` slimming: this used to be copy-pasted in 17 host modules with two -/// different wordings; one implementation keeps messages consistent. -pub fn as_text<'a>(v: &'a crate::value::Value, label: &str) -> Result<&'a str, String> { - match v { - crate::value::Value::Text(s) => Ok(s.as_str()), - _ => Err(format!("{label} needs text")), - } -} -pub use fs::path_under_root; -pub use plugin::PluginState; - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -/// Host capability flags. Default: all enabled. -#[derive(Debug, Clone, Copy)] -pub struct HostCaps { - pub fs_write: bool, - pub exec: bool, - pub net: bool, - pub plugin: bool, -} - -impl Default for HostCaps { - fn default() -> Self { - Self { - fs_write: true, - exec: true, - net: true, - plugin: true, - } - } -} - -/// SVG plot produced during a run (for CLI auto-write / view embed). -#[derive(Debug, Clone)] -pub struct PlotArtifact { - /// User-requested path, if any. - pub path: Option, - pub svg: String, -} - -#[derive(Debug)] -pub struct HostContext { - pub caps: HostCaps, - pub fs_root: Option, - pub cwd: PathBuf, - pub argv: Vec, - /// Soft mode: do not `process::exit`; honor sleep_limit (view / capture / export). - pub soft_side_effects: bool, - pub sleep_limit_ms: Option, - /// LCG state for `random` / `random_int`. - pub rng: u64, - pub plots: Vec, - pub oracle_observations: Vec, - /// lang → interpreter argv (from `set_cmd`). - pub foreign_cmds: HashMap>, - /// Process-local language registrations (`register` / `set_cmd`). - pub foreign_specs: HashMap, - /// Project config specs (`.marqdo/foreign.toml`), lower priority than runtime. - pub foreign_config_specs: HashMap, - /// Whether project config has been discovered/loaded. - pub foreign_config_loaded: bool, - /// Persistent foreign kernels (`session_open`). - #[cfg(feature = "exec-host")] - pub foreign_sessions: HashMap, - /// Monotonic session id counter. - #[cfg(feature = "exec-host")] - pub foreign_session_seq: u64, - #[cfg(feature = "exec-host")] - pub foreign_protocol_steps: Vec, - #[cfg(feature = "exec-host")] - pub foreign_replay_expected: Option, - #[cfg(feature = "exec-host")] - pub foreign_replay_divergence: Option, - /// Loaded native plugins (ABI v1/v2). - pub plugins: PluginState, - /// Entry `.mq.md` source text (for ABI host_query / context injection). - pub entry_source: Option, - pub entry_path: Option, - /// Active function names (outer → inner) for call-site injection. - pub call_stack: Vec, - /// Last statement line (updated by interpreters for call-site queries). - pub current_line: u32, - /// Entry-file line of each active user call (for writeback anchoring). - pub call_site_lines: Vec, - /// Bound Artifact Metadata from the entry `.mq.md` (Phase 1 Binding). - pub entry_metadata: Vec<(String, crate::value::Value)>, - /// Concurrent subtasks (`lib/subtask`): file / function / foreign. - #[cfg_attr(not(feature = "exec-host"), allow(dead_code))] - pub(crate) subtasks: HashMap, - pub subtask_seq: u64, - /// Minimum log level (`lib/log`); default Info (20). See `host::log::Level`. - pub log_min_level: u8, - /// Active `ext/ai/sandbox` CoW session id (nested `sandbox_run`). - pub sandbox_session: Option, -} - -impl Default for HostContext { - fn default() -> Self { - Self { - caps: HostCaps::default(), - fs_root: None, - cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), - argv: Vec::new(), - soft_side_effects: false, - sleep_limit_ms: Some(30_000), - rng: 0xC0FF_EE42_CAFE_BABE, - plots: Vec::new(), - oracle_observations: Vec::new(), - foreign_cmds: HashMap::new(), - foreign_specs: HashMap::new(), - foreign_config_specs: HashMap::new(), - foreign_config_loaded: false, - #[cfg(feature = "exec-host")] - foreign_sessions: HashMap::new(), - #[cfg(feature = "exec-host")] - foreign_session_seq: 0, - #[cfg(feature = "exec-host")] - foreign_protocol_steps: Vec::new(), - #[cfg(feature = "exec-host")] - foreign_replay_expected: None, - #[cfg(feature = "exec-host")] - foreign_replay_divergence: None, - plugins: PluginState::default(), - entry_source: None, - entry_path: None, - call_stack: Vec::new(), - current_line: 1, - call_site_lines: Vec::new(), - entry_metadata: Vec::new(), - subtasks: HashMap::new(), - subtask_seq: 0, - log_min_level: 20, // Info - sandbox_session: None, - } - } -} - -impl Drop for HostContext { - fn drop(&mut self) { - subtask::kill_all(self); - #[cfg(feature = "exec-host")] - foreign_session::shutdown(self); - } -} - -impl HostContext { - pub fn for_run(path: Option<&Path>, caps: HostCaps, argv: Vec) -> Self { - let mut ctx = Self::default(); - ctx.caps = caps; - ctx.argv = argv; - if let Some(p) = path { - if let Some(parent) = p.parent() { - let parent = if parent.as_os_str().is_empty() { - PathBuf::from(".") - } else { - parent.to_path_buf() - }; - ctx.cwd = parent.clone(); - ctx.fs_root = Some(parent); - } - } - ctx - } - - /// Capture stdout / view / export: soft exit + sleep clamp; same caps as CLI by default. - pub fn for_capture(path: Option<&Path>, caps: HostCaps) -> Self { - let mut ctx = Self::for_run(path, caps, Vec::new()); - ctx.soft_side_effects = true; - ctx.sleep_limit_ms = Some(0); - ctx - } - - pub fn allow_fs_write(&self) -> bool { - self.caps.fs_write - } - - pub fn allow_exec(&self) -> bool { - self.caps.exec - } - - pub fn allow_net(&self) -> bool { - self.caps.net - } - - pub fn push_call_site_line(&mut self, line: u32) { - self.call_site_lines.push(line); - } - - pub fn pop_call_site_line(&mut self) { - self.call_site_lines.pop(); - } - - pub fn allow_plugin(&self) -> bool { - self.caps.plugin - } - - pub fn next_u64(&mut self) -> u64 { - // SplitMix64-ish LCG step - self.rng = self - .rng - .wrapping_mul(6364136223846793005) - .wrapping_add(1); - let mut z = self.rng; - z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); - z ^ (z >> 31) - } - - pub fn next_f64(&mut self) -> f64 { - let x = self.next_u64() >> 11; - (x as f64) / ((1u64 << 53) as f64) - } - - pub fn resolve_path(&self, rel: &str) -> Result { - let p = Path::new(rel); - let abs = if p.is_absolute() { - p.to_path_buf() - } else { - self.cwd.join(p) - }; - if let Some(root) = &self.fs_root { - let abs = if abs.is_absolute() { abs } else { - std::env::current_dir().map_err(|e|e.to_string())?.join(abs) - }; - let root = root.canonicalize().map_err(|e| format!("filesystem root: {e}"))?; - // Normalize before checking, including destinations that do not exist yet. - let mut lexical = PathBuf::new(); - for component in abs.components() { - match component { - std::path::Component::CurDir => {}, - std::path::Component::ParentDir => { lexical.pop(); }, - component => lexical.push(component.as_os_str()), - } - } - if !lexical.is_absolute() { - lexical = std::env::current_dir().map_err(|e| e.to_string())?.join(lexical); - } - if !lexical.starts_with(&root) { - return Err(format!("path escapes sandbox root: {}", abs.display())); - } - // The nearest existing ancestor must also be inside root: a symlink - // cannot authorize writes through a not-yet-existing descendant. - let mut ancestor = lexical.as_path(); - loop { - match ancestor.canonicalize() { - Ok(real) => { - if !real.starts_with(&root) { - return Err(format!("path escapes sandbox root: {}", abs.display())); - } - break; - } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - if ancestor.symlink_metadata().is_ok() { - return Err(format!("unresolvable symlink: {}", ancestor.display())); - } - ancestor = ancestor.parent().ok_or_else(|| "invalid file path".to_string())?; - } - Err(e) => return Err(format!("resolve path {}: {e}", abs.display())), - } - } - return Ok(lexical); - } - Ok(abs) - } -} - -/// Write auto-named plot files for CLI runs when `path` was omitted. -pub fn flush_auto_plots(source_path: Option<&Path>, plots: &[PlotArtifact]) -> Result<(), String> { - let mut auto_i = 0usize; - for plot in plots { - if plot.path.is_some() { - continue; - } - auto_i += 1; - let stem = source_path - .and_then(|p| p.file_stem()) - .and_then(|s| s.to_str()) - .unwrap_or("out"); - let stem = stem.trim_end_matches(".mq"); - let name = format!("{stem}-plot-{auto_i}.svg"); - let dir = source_path - .and_then(|p| p.parent()) - .unwrap_or_else(|| Path::new(".")); - let dest = dir.join(&name); - std::fs::write(&dest, plot.svg.as_bytes()) - .map_err(|e| format!("failed to write plot {}: {e}", dest.display()))?; - println!("plot: {}", dest.display()); - } - Ok(()) -} - -mod collection_ops; - -mod result; - -mod fs_ops; - -mod document; - -mod net_ops; - -mod data_ops; - -mod task_ops; - -mod archive; diff --git a/src/host/net.rs b/src/host/net.rs deleted file mode 100755 index 732497c..0000000 --- a/src/host/net.rs +++ /dev/null @@ -1,1076 +0,0 @@ -//! HTTP host primitives (HTTP and HTTPS via ureq). - -use crate::host::as_text; -use std::io::{Read, Write}; -#[cfg(feature = "net-host")] -use std::io::{BufRead, BufReader}; -#[cfg(feature = "net-host")] -use std::time::Duration; - -use crate::value::Value; -#[cfg(feature = "net-host")] -use crate::host::HostContext; - - -#[cfg(feature = "net-host")] -fn headers_from_value(headers: Option<&Value>) -> Result, String> { - let Some(h) = headers else { - return Ok(Vec::new()); - }; - match h { - Value::None => Ok(Vec::new()), - Value::Map(entries) => Ok(entries - .iter() - .map(|(k, v)| (k.clone(), v.as_display())) - .collect()), - _ => Err("headers must be a map (e.g. from json parse)".into()), - } -} - -/// Maximum response body accepted by the text HTTP helpers. -/// -/// Read the limit from the stream, rather than after converting it to a `String`: -/// an untrusted peer must never be able to allocate an arbitrary response in memory. -#[cfg(feature = "net-host")] -const MAX_HTTP_BODY_BYTES: usize = 8 * 1024 * 1024; - -#[cfg(feature = "net-host")] -fn read_response_text(reader: R) -> Result { - let mut bytes = Vec::new(); - reader - .take(MAX_HTTP_BODY_BYTES as u64 + 1) - .read_to_end(&mut bytes) - .map_err(|e| format!("http read body: {e}"))?; - if bytes.len() > MAX_HTTP_BODY_BYTES { - return Err("http response exceeds 8MiB limit".into()); - } - Ok(String::from_utf8_lossy(&bytes).into_owned()) -} - -#[cfg(feature = "net-host")] -fn http_exchange( - method: &str, - url: &str, - body: Option<&str>, - content_type: Option<&str>, - extra_headers: &[(String, String)], -) -> Result<(u16, String), String> { - if !(url.starts_with("http://") || url.starts_with("https://")) { - return Err("url must start with http:// or https://".into()); - } - let agent = ureq::AgentBuilder::new() - .timeout_connect(Duration::from_secs(15)) - .timeout_read(Duration::from_secs(120)) - .build(); - - let mut req = match method { - "GET" => agent.get(url), - "POST" => agent.post(url), - "PUT" => agent.put(url), - "DELETE" => agent.request("DELETE", url), - other => return Err(format!("unsupported http method: {other}")), - }; - req = req.set("User-Agent", "marqdo"); - if let Some(ct) = content_type { - if !ct.is_empty() { - req = req.set("Content-Type", ct); - } - } - for (k, v) in extra_headers { - req = req.set(k, v); - } - - let resp = if let Some(b) = body { - req.send_string(b) - } else { - req.call() - }; - - match resp { - Ok(r) => { - let status = r.status(); - let text = read_response_text(r.into_reader())?; - Ok((status, text)) - } - Err(ureq::Error::Status(code, r)) => { - let text = read_response_text(r.into_reader())?; - Ok((code, text)) - } - Err(e) => Err(format!("http {method} {url}: {e}")), - } -} - -#[cfg(feature = "net-host")] -fn response_map(status: u16, body: String) -> Value { - Value::Map(vec![ - ("status".into(), Value::Int(status as i64)), - ("body".into(), Value::Text(body)), - ]) -} - -#[cfg(feature = "net-host")] -pub fn http_get( - ctx: &HostContext, - url: &Value, - headers: Option<&Value>, -) -> Result { - if !ctx.allow_net() { - if ctx.sandbox_session.is_some() { - return Err("net unavailable in sandbox".into()); - } - return Err("http_get denied by host policy".into()); - } - let url = as_text(url, "url")?; - let hdrs = headers_from_value(headers)?; - let (status, body) = http_exchange("GET", url, None, None, &hdrs)?; - Ok(response_map(status, body)) -} - -#[cfg(feature = "net-host")] -pub fn http_post( - ctx: &HostContext, - url: &Value, - body: &Value, - content_type: Option<&Value>, - headers: Option<&Value>, -) -> Result { - if !ctx.allow_net() { - if ctx.sandbox_session.is_some() { - return Err("net unavailable in sandbox".into()); - } - return Err("http_post denied by host policy".into()); - } - let url = as_text(url, "url")?; - let body = as_text(body, "body")?; - let ct = match content_type { - None | Some(Value::None) => "application/json; charset=utf-8", - Some(v) => as_text(v, "content_type")?, - }; - let hdrs = headers_from_value(headers)?; - // Transport failures → status 0 + body message (soft). Callers that need - // hard errors can still treat status!=200 as failure; Agent/LLM surfaces - // map this into structured `{finish:error}` instead of aborting the VM. - match http_exchange("POST", url, Some(body), Some(ct), &hdrs) { - Ok((status, resp)) => Ok(response_map(status, resp)), - Err(e) => Ok(response_map(0, e)), - } -} - -/// Generic request: method + url + optional body / content_type / headers. -#[cfg(feature = "net-host")] -pub fn http_request( - ctx: &HostContext, - method: &Value, - url: &Value, - body: Option<&Value>, - content_type: Option<&Value>, - headers: Option<&Value>, -) -> Result { - if !ctx.allow_net() { - if ctx.sandbox_session.is_some() { - return Err("net unavailable in sandbox".into()); - } - return Err("http_request denied by host policy".into()); - } - let method = as_text(method, "method")?.to_uppercase(); - let url = as_text(url, "url")?; - let body_s = match body { - None | Some(Value::None) => None, - Some(v) => Some(as_text(v, "body")?), - }; - let ct = match content_type { - None | Some(Value::None) => { - if body_s.is_some() && method == "POST" { - Some("application/json; charset=utf-8") - } else { - None - } - } - Some(v) => Some(as_text(v, "content_type")?), - }; - let hdrs = headers_from_value(headers)?; - let (status, resp) = http_exchange(&method, url, body_s, ct, &hdrs)?; - Ok(response_map(status, resp)) -} - -pub fn url_encode(text: &Value) -> Result { - let s = as_text(text, "text")?; - Ok(Value::Text( - s.bytes() - .map(|b| match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - (b as char).to_string() - } - // `url_encode` documents a URL *segment*. `+` is form/query - // encoding, where it is ambiguous with a literal plus in a path. - b' ' => "%20".into(), - _ => format!("%{b:02X}"), - }) - .collect(), - )) -} - -fn truthy_flag(v: Option<&Value>) -> bool { - match v { - None | Some(Value::None) => false, - Some(v) => v.truthy(), - } -} - -/// Split a Cookie / Set-Cookie header value into individual cookie attribute tokens. -/// `Set-Cookie` may contain multiple `name=value` cookies plus attributes per cookie; -/// a single request `Cookie` header is a flat `name=value; name=value` list. -fn split_cookie_tokens(header: &str, is_set_cookie: bool) -> Vec> { - // Set-Cookie: each cookie block is separated by ", " only when a next cookie begins. - // We split on ',' that is NOT preceded by an Expires/Max-Age value (contains '-' or ':') - // — heuristic good enough for common cases; value may contain ';' (e.g. quoted). - if !is_set_cookie { - let mut cookies = Vec::new(); - for seg in header.split(';') { - let seg = seg.trim(); - if seg.is_empty() { - continue; - } - let mut cur = Vec::new(); - if let Some((k, v)) = seg.split_once('=') { - cur.push((k.trim().to_string(), v.trim().trim_matches('"').to_string())); - } else { - cur.push((seg.to_string(), String::new())); - } - cookies.push(cur); - } - return cookies; - } - - let mut cookies: Vec> = Vec::new(); - let mut cur: Vec<(String, String)> = Vec::new(); - let mut i = 0; - let chars: Vec = header.chars().collect(); - while i < chars.len() { - let c = chars[i]; - if c == ',' { - // A comma is part of an `Expires` date value (e.g. "Wed, 21 Oct 2026") - // only when the previous attribute is `Expires`; otherwise it separates - // one Set-Cookie block from the next. - let in_expires_date = cur - .last() - .map(|(k, _)| k.eq_ignore_ascii_case("expires")) - .unwrap_or(false); - if in_expires_date { - if let Some((_, v)) = cur.last_mut() { - v.push(','); - } - i += 1; - continue; - } - // A real cookie separator: flush current block and start a new one. - cookies.push(std::mem::take(&mut cur)); - i += 1; - continue; - } - if c == ';' { - // Cookie request header: `;` separates independent cookies. - // Set-Cookie: `;` separates attributes *within* the same cookie block. - if !is_set_cookie || cur.is_empty() { - if !cur.is_empty() { - cookies.push(std::mem::take(&mut cur)); - } - } - i += 1; - continue; - } - // Accumulate a token: name=value until ; or , - let mut j = i; - while j < chars.len() && chars[j] != ';' && chars[j] != ',' { - j += 1; - } - let token: String = chars[i..j].iter().collect(); - let token = token.trim(); - if !token.is_empty() { - if let Some((k, v)) = token.split_once('=') { - cur.push(( - k.trim().to_string(), - v.trim().trim_matches('"').to_string(), - )); - } else { - cur.push((token.to_string(), String::new())); - } - } - i = j; - } - if !cur.is_empty() { - cookies.push(cur); - } - cookies -} - -fn normalized_key(s: &str) -> String { - s.chars() - .filter(|c| *c != '_' && *c != '-') - .collect::() - .to_ascii_lowercase() -} - -fn cookie_attr_value<'a>(pairs: &'a [(String, String)], key: &str) -> Option<&'a str> { - let want = normalized_key(key); - pairs - .iter() - .find(|(k, _)| normalized_key(k) == want) - .map(|(_, v)| v.as_str()) -} - -fn bool_attr(pairs: &[(String, String)], key: &str) -> Option { - let want = normalized_key(key); - pairs - .iter() - .find(|(k, _)| normalized_key(k) == want) - .map(|(_, v)| { - if v.is_empty() { - // Present-without-value boolean flag (e.g. `Secure` / `HttpOnly`). - true - } else { - !(v.eq_ignore_ascii_case("false") - || v.eq_ignore_ascii_case("0") - || v.eq_ignore_ascii_case("no")) - } - }) -} - -/// Parse a Cookie request header or Set-Cookie response header (RFC 6265 subset) -/// into a list of `{name, value, path, domain, expires, max_age, secure, http_only, same_site}`. -/// `is_response=true` treats the input as one or more `Set-Cookie` blocks. -pub fn cookie_parse(text: &Value, is_response: Option<&Value>) -> Result { - let header = as_text(text, "text")?; - let is_response = truthy_flag(is_response); - let blocks = split_cookie_tokens(header, is_response); - let mut out = Vec::new(); - for block in blocks { - let name = block - .first() - .map(|(k, _)| k.clone()) - .unwrap_or_default(); - if name.is_empty() { - continue; - } - let value = block.first().map(|(_, v)| v.clone()).unwrap_or_default(); - let mut entry: Vec<(String, Value)> = vec![ - ("name".into(), Value::Text(name)), - ("value".into(), Value::Text(value)), - ]; - // Attribute with optional value -> Text or None. - let text_attrs = [ - ("path", "path"), - ("domain", "domain"), - ("expires", "expires"), - ("max_age", "max_age"), - ("sameSite", "same_site"), - ]; - for (attr, key) in text_attrs { - let v = cookie_attr_value(&block, attr); - entry.push(( - key.to_string(), - match v { - Some(s) => Value::Text(s.to_string()), - None => Value::None, - }, - )); - } - // Boolean flags (Secure / HttpOnly are present-without-value). - for attr in ["secure", "http_only"] { - let present = bool_attr(&block, attr); - entry.push(( - attr.to_string(), - match present { - Some(b) => Value::Bool(b), - None => Value::None, - }, - )); - } - out.push(Value::Map(entry)); - } - Ok(Value::List(out)) -} - -/// Parse a `multipart/form-data` body (given its boundary) into -/// `[{name, filename?, content_type?, value}]`. Field values are decoded as text. -pub fn multipart_parse(body: &Value, boundary: &Value) -> Result { - let body = as_text(body, "body")?; - let boundary = as_text(boundary, "boundary")?; - let boundary = boundary.trim(); - if boundary.is_empty() { - return Err("multipart boundary is empty".into()); - } - let delim = format!("--{boundary}"); - let mut parts = Vec::new(); - let mut rest = body; - loop { - let Some(pos) = rest.find(&delim) else { - break; - }; - rest = &rest[pos + delim.len()..]; - // After boundary: either `--` (end) or CRLF + headers - if rest.strip_prefix("--").is_some() { - break; - } - let rest_trim = rest.strip_prefix("\r\n").or_else(|| rest.strip_prefix('\n')); - let Some(after) = rest_trim else { - break; - }; - rest = after; - // Headers until blank line - let Some(header_end) = rest.find("\r\n\r\n").or_else(|| rest.find("\n\n")) else { - break; - }; - let header_block = &rest[..header_end]; - let header_len = if rest[header_end..].starts_with("\r\n\r\n") { - 4 - } else { - 2 - }; - let body_start = header_end + header_len; - // Part body until next boundary - let body_end = rest[body_start..] - .find(&delim) - .map(|p| body_start + p) - .unwrap_or(rest.len()); - let part_body = &rest[body_start..body_end]; - // Trim trailing CRLF before boundary - let part_body = part_body - .strip_suffix("\r\n") - .or_else(|| part_body.strip_suffix('\n')) - .unwrap_or(part_body); - - let mut name = String::new(); - let mut filename = None; - let mut content_type = None; - for line in header_block.split('\n') { - let line = line.strip_suffix('\r').unwrap_or(line); - let lk = line.to_ascii_lowercase(); - if let Some(v) = lk.strip_prefix("content-disposition:") { - // form-data; name="x"; filename="y.txt" - for seg in v.split(';') { - let seg = seg.trim(); - if let Some(val) = seg.strip_prefix("name=") { - name = val.trim_matches('"').to_string(); - } else if let Some(val) = seg.strip_prefix("filename=") { - filename = Some(val.trim_matches('"').to_string()); - } - } - } else if let Some(v) = lk.strip_prefix("content-type:") { - content_type = Some(v.trim().to_string()); - } - } - let mut entry = vec![("name".to_string(), Value::Text(name))]; - match filename { - Some(f) if !f.is_empty() => { - entry.push(("filename".to_string(), Value::Text(f))); - entry.push(( - "content_type".to_string(), - Value::Text(content_type.unwrap_or_default()), - )); - entry.push(("value".to_string(), Value::Text(part_body.to_string()))); - } - _ => { - entry.push(("value".to_string(), Value::Text(part_body.to_string()))); - } - } - parts.push(Value::Map(entry)); - rest = &rest[body_end..]; - if rest.starts_with(&delim) { - continue; - } - break; - } - Ok(Value::List(parts)) -} - -/// Parse Markdown / GFM into HTML (pure transform, no network I/O). -pub fn markdown_parse(text: &Value) -> Result { - let md = as_text(text, "text")?; - Ok(Value::Text(markdown_to_html(md))) -} - -fn markdown_to_html(md: &str) -> String { - use pulldown_cmark::{html, Options, Parser}; - let mut opts = Options::empty(); - opts.insert( - Options::ENABLE_STRIKETHROUGH - | Options::ENABLE_TABLES - | Options::ENABLE_TASKLISTS, - ); - let parser = Parser::new_ext(md, opts); - let mut html_out = String::new(); - html::push_html(&mut html_out, parser); - html_out -} - -/// Extract `data:` payloads from an SSE body (ignores comments / event: / id:). -pub fn sse_data_payloads(text: &str) -> Vec { - let mut out = Vec::new(); - let mut cur: Vec = Vec::new(); - for line in text.split('\n') { - let line = line.strip_suffix('\r').unwrap_or(line); - if line.is_empty() { - if !cur.is_empty() { - out.push(cur.join("\n")); - cur.clear(); - } - continue; - } - if let Some(rest) = line.strip_prefix("data:") { - let payload = rest.strip_prefix(' ').unwrap_or(rest); - cur.push(payload.to_string()); - } - // Other SSE fields ignored for chat-completions wire format. - } - if !cur.is_empty() { - out.push(cur.join("\n")); - } - out -} - -fn event_map(pairs: Vec<(&str, Value)>) -> Value { - Value::Map( - pairs - .into_iter() - .map(|(k, v)| (k.to_string(), v)) - .collect(), - ) -} - -/// Push stream events from one OpenAI-compatible SSE JSON object. -/// DeepSeek (and similar) may stream chain-of-thought in `delta.reasoning_content` -/// while the final answer arrives later in `delta.content`. -/// Returns `Err` only on JSON issues handled by caller; `Ok(true)` means stop (error frame). -fn push_openai_delta_events( - v: &serde_json::Value, - events: &mut Vec, - result: &mut String, - echoed: &mut bool, - saw_reasoning: &mut bool, - echo: bool, -) -> bool { - if let Some(msg) = v.get("error").and_then(|e| { - e.get("message") - .and_then(|m| m.as_str()) - .or_else(|| e.as_str()) - }) { - let ev = event_map(vec![ - ("type", Value::Text("error".into())), - ("message", Value::Text(msg.into())), - ]); - crate::host::event_bus::publish(&ev); - events.push(ev); - return true; - } - let reasoning = v - .pointer("/choices/0/delta/reasoning_content") - .and_then(|c| c.as_str()) - .unwrap_or(""); - if !reasoning.is_empty() { - *saw_reasoning = true; - if echo { - print!("{reasoning}"); - let _ = std::io::stdout().flush(); - *echoed = true; - } - let ev = event_map(vec![ - ("type", Value::Text("reasoning".into())), - ("text", Value::Text(reasoning.into())), - ]); - crate::host::event_bus::publish(&ev); - events.push(ev); - } - let content = v - .pointer("/choices/0/delta/content") - .and_then(|c| c.as_str()) - .unwrap_or(""); - if !content.is_empty() { - if echo && *saw_reasoning && result.is_empty() { - println!(); - *echoed = true; - } - result.push_str(content); - if echo { - print!("{content}"); - let _ = std::io::stdout().flush(); - *echoed = true; - } - let ev = event_map(vec![ - ("type", Value::Text("delta".into())), - ("text", Value::Text(content.into())), - ]); - crate::host::event_bus::publish(&ev); - events.push(ev); - } - false -} - -/// Map OpenAI-compatible chat SSE payloads → Marqdo stream events -/// (`reasoning` / `delta` / `done` / `error`). Optional `echo` prints text to stdout as it arrives. -pub fn openai_chat_sse_events(text: &str, echo: bool) -> Result, String> { - let mut events = Vec::new(); - let mut result = String::new(); - let mut saw_done = false; - let mut echoed = false; - let mut saw_reasoning = false; - for data in sse_data_payloads(text) { - let data = data.trim(); - if data.is_empty() { - continue; - } - if data == "[DONE]" { - saw_done = true; - break; - } - let v: serde_json::Value = serde_json::from_str(data) - .map_err(|e| format!("openai sse json: {e}"))?; - if push_openai_delta_events( - &v, - &mut events, - &mut result, - &mut echoed, - &mut saw_reasoning, - echo, - ) { - return Ok(events); - } - } - if echo && echoed { - println!(); - } - if !saw_done && events.is_empty() && result.is_empty() { - // Non-SSE / empty: treat as error for clearer gold diagnostics. - events.push(event_map(vec![ - ("type", Value::Text("error".into())), - ( - "message", - Value::Text("openai sse: no data frames".into()), - ), - ])); - return Ok(events); - } - let done = event_map(vec![ - ("type", Value::Text("done".into())), - ("result", Value::Text(result)), - ]); - crate::host::event_bus::publish(&done); - events.push(done); - Ok(events) -} - -/// Offline: parse OpenAI chat SSE text → event list (no network). -pub fn openai_sse_parse(text: &Value, echo: Option<&Value>) -> Result { - let text = as_text(text, "text")?; - let echo = truthy_flag(echo); - Ok(Value::List(openai_chat_sse_events(text, echo)?)) -} - -#[cfg(feature = "net-host")] -fn read_sse_body_to_events( - mut reader: R, - echo: bool, -) -> Result, String> { - let mut buf = String::new(); - let mut events = Vec::new(); - let mut result = String::new(); - let mut data_buf: Vec = Vec::new(); - let mut echoed = false; - let mut saw_reasoning = false; - // Soft cap on *stored* event payload (bus still gets every frame). DeepSeek - // thinking can exceed tens of MiB; we must not retain the raw wire body. - let mut stored_bytes: usize = 0; - const STORE_CAP: usize = 2 * 1024 * 1024; - - let flush_data = |data_buf: &mut Vec, - events: &mut Vec, - result: &mut String, - echoed: &mut bool, - saw_reasoning: &mut bool, - stored_bytes: &mut usize, - echo: bool| - -> Result { - if data_buf.is_empty() { - return Ok(false); - } - let data = data_buf.join("\n"); - data_buf.clear(); - let data = data.trim(); - if data.is_empty() { - return Ok(false); - } - if data == "[DONE]" { - return Ok(true); - } - let v: serde_json::Value = - serde_json::from_str(data).map_err(|e| format!("openai sse json: {e}"))?; - // Always publish to the view bus; optionally skip retaining huge histories. - let before = events.len(); - let stop = push_openai_delta_events( - &v, - events, - result, - echoed, - saw_reasoning, - echo, - ); - // Cap retained history only; EventBus already has every frame for the view. - let mut i = before; - while i < events.len() { - let add = match &events[i] { - Value::Map(m) => m - .iter() - .filter(|(k, _)| *k == "text" || *k == "result" || *k == "message") - .filter_map(|(_, val)| match val { - Value::Text(t) => Some(t.len()), - _ => None, - }) - .sum::(), - _ => 0, - }; - if stored_bytes.saturating_add(add) > STORE_CAP { - events.truncate(i); - break; - } - *stored_bytes = stored_bytes.saturating_add(add); - i += 1; - } - Ok(stop) - }; - - loop { - buf.clear(); - let n = reader - .read_line(&mut buf) - .map_err(|e| format!("http sse read: {e}"))?; - if n == 0 { - break; - } - let line = buf.strip_suffix('\n').unwrap_or(&buf); - let line = line.strip_suffix('\r').unwrap_or(line); - if line.is_empty() { - if flush_data( - &mut data_buf, - &mut events, - &mut result, - &mut echoed, - &mut saw_reasoning, - &mut stored_bytes, - echo, - )? { - break; - } - continue; - } - if let Some(rest) = line.strip_prefix("data:") { - let payload = rest.strip_prefix(' ').unwrap_or(rest); - data_buf.push(payload.to_string()); - } - } - let _ = flush_data( - &mut data_buf, - &mut events, - &mut result, - &mut echoed, - &mut saw_reasoning, - &mut stored_bytes, - echo, - )?; - if echo && echoed { - println!(); - } - if events.iter().any(|e| matches!(e, Value::Map(m) if m.iter().any(|(k,v)| k == "type" && matches!(v, Value::Text(t) if t == "error")))) { - return Ok(events); - } - let done = event_map(vec![ - ("type", Value::Text("done".into())), - ("result", Value::Text(result)), - ]); - crate::host::event_bus::publish(&done); - events.push(done); - Ok(events) -} - -/// POST and consume OpenAI-compatible SSE; return `{status, events}` list of stream maps. -#[cfg(feature = "net-host")] -pub fn http_post_sse( - ctx: &HostContext, - url: &Value, - body: &Value, - content_type: Option<&Value>, - headers: Option<&Value>, - echo: Option<&Value>, -) -> Result { - if !ctx.allow_net() { - return Err("http_post_sse denied by host policy".into()); - } - let url = as_text(url, "url")?; - let body = as_text(body, "body")?; - let ct = match content_type { - None | Some(Value::None) => "application/json; charset=utf-8", - Some(v) => as_text(v, "content_type")?, - }; - let hdrs = headers_from_value(headers)?; - let echo = truthy_flag(echo); - if !(url.starts_with("http://") || url.starts_with("https://")) { - return Err("url must start with http:// or https://".into()); - } - let agent = ureq::AgentBuilder::new() - .timeout_connect(Duration::from_secs(15)) - .timeout_read(Duration::from_secs(120)) - .build(); - let mut req = agent.post(url).set("User-Agent", "marqdo").set("Content-Type", ct); - req = req.set("Accept", "text/event-stream"); - for (k, v) in &hdrs { - req = req.set(k, v); - } - match req.send_string(body) { - Ok(r) => { - let status = r.status(); - let reader = BufReader::new(r.into_reader()); - let events = read_sse_body_to_events(reader, echo)?; - Ok(Value::Map(vec![ - ("status".into(), Value::Int(status as i64)), - ("events".into(), Value::List(events)), - ])) - } - Err(ureq::Error::Status(code, r)) => { - let text = read_response_text(r.into_reader())?; - Ok(Value::Map(vec![ - ("status".into(), Value::Int(code as i64)), - ( - "events".into(), - Value::List(vec![event_map(vec![ - ("type", Value::Text("error".into())), - ("message", Value::Text(text)), - ])]), - ), - ])) - } - Err(e) => Ok(Value::Map(vec![ - ("status".into(), Value::Int(0)), - ( - "events".into(), - Value::List(vec![event_map(vec![ - ("type", Value::Text("error".into())), - ("message", Value::Text(format!("http POST sse {url}: {e}"))), - ])]), - ), - ])), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn headers_from_map() { - let m = Value::Map(vec![ - ("Authorization".into(), Value::Text("Bearer x".into())), - ("X-Test".into(), Value::Int(1)), - ]); - let h = headers_from_value(Some(&m)).unwrap(); - assert_eq!(h.len(), 2); - assert!(h - .iter() - .any(|(k, v)| k == "Authorization" && v == "Bearer x")); - } - - #[cfg(feature = "net-host")] - #[test] - fn response_limit_stops_before_unbounded_allocation() { - let body = vec![b'x'; MAX_HTTP_BODY_BYTES + 1]; - let err = read_response_text(std::io::Cursor::new(body)).unwrap_err(); - assert_eq!(err, "http response exceeds 8MiB limit"); - } - - #[test] - fn url_segment_encoding_keeps_space_and_plus_distinct() { - let encoded = url_encode(&Value::Text("a b+c".into())).unwrap(); - assert!(matches!(encoded, Value::Text(text) if text == "a%20b%2Bc")); - } - - #[test] - fn openai_sse_fixture_to_events() { - let fixture = "\ -data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\ -\n\ -data: {\"choices\":[{\"delta\":{\"content\":\"lo\"}}]}\n\ -\n\ -data: [DONE]\n\ -"; - let ev = openai_chat_sse_events(fixture, false).unwrap(); - assert_eq!(ev.len(), 3); - match &ev[0] { - Value::Map(m) => { - assert!(m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "delta"))); - assert!(m.iter().any(|(k, v)| k == "text" && matches!(v, Value::Text(t) if t == "Hel"))); - } - _ => panic!("expected map"), - } - match &ev[2] { - Value::Map(m) => { - assert!(m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "done"))); - assert!(m.iter().any(|(k, v)| k == "result" && matches!(v, Value::Text(t) if t == "Hello"))); - } - _ => panic!("expected done map"), - } - } - - #[test] - fn openai_sse_reasoning_then_content() { - let fixture = "\ -data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"think\"}}]}\n\ -\n\ -data: {\"choices\":[{\"delta\":{\"content\":\"Hi\"}}]}\n\ -\n\ -data: [DONE]\n\ -"; - let ev = openai_chat_sse_events(fixture, false).unwrap(); - assert_eq!(ev.len(), 3); - match &ev[0] { - Value::Map(m) => { - assert!(m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "reasoning"))); - assert!(m.iter().any(|(k, v)| k == "text" && matches!(v, Value::Text(t) if t == "think"))); - } - _ => panic!("expected reasoning map"), - } - match &ev[2] { - Value::Map(m) => { - assert!(m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "done"))); - assert!(m.iter().any(|(k, v)| k == "result" && matches!(v, Value::Text(t) if t == "Hi"))); - } - _ => panic!("expected done map"), - } - } - - #[test] - fn sse_body_over_8mib_does_not_error() { - // Formerly failed with "http sse response exceeds 8MiB limit" because raw - // wire bytes were accumulated. Streaming must keep going; store is soft-capped. - let frame = - "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"0123456789\"}}]}\n\n"; - let mut body = String::with_capacity(9 * 1024 * 1024); - while body.len() < 8 * 1024 * 1024 + 1024 { - body.push_str(frame); - } - body.push_str("data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\n"); - body.push_str("data: [DONE]\n\n"); - let ev = read_sse_body_to_events(std::io::Cursor::new(body), false).unwrap(); - assert!( - ev.iter().any(|e| matches!( - e, - Value::Map(m) if m.iter().any(|(k, v)| k == "type" && matches!(v, Value::Text(t) if t == "done")) - && m.iter().any(|(k, v)| k == "result" && matches!(v, Value::Text(t) if t == "ok")) - )), - "expected done with result ok" - ); - } - - #[test] - fn cookie_request_header_parse() { - let v = cookie_parse( - &Value::Text("session=abc123; theme=dark; lang=zh-CN".into()), - Some(&Value::Bool(false)), - ) - .unwrap(); - let Value::List(items) = v else { - panic!("expected list"); - }; - assert_eq!(items.len(), 3); - let Value::Map(first) = &items[0] else { - panic!("expected map"); - }; - assert!(first - .iter() - .any(|(k, v)| k == "name" && matches!(v, Value::Text(t) if t == "session"))); - assert!(first - .iter() - .any(|(k, v)| k == "value" && matches!(v, Value::Text(t) if t == "abc123"))); - } - - #[test] - fn set_cookie_response_parse() { - let header = "id=42; Path=/; HttpOnly; Secure; SameSite=Lax, theme=light; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=3600"; - let blocks = split_cookie_tokens(header, true); - eprintln!("blocks = {blocks:?}"); - let v = cookie_parse( - &Value::Text(header.into()), - Some(&Value::Bool(true)), - ) - .unwrap(); - let Value::List(items) = v else { - panic!("expected list"); - }; - assert_eq!(items.len(), 2, "two Set-Cookie blocks"); - let Value::Map(first) = &items[0] else { - panic!("expected map"); - }; - assert!(first - .iter() - .any(|(k, v)| k == "path" && matches!(v, Value::Text(t) if t == "/"))); - assert!(first - .iter() - .any(|(k, v)| k == "http_only" && matches!(v, Value::Bool(true)))); - assert!(first - .iter() - .any(|(k, v)| k == "secure" && matches!(v, Value::Bool(true)))); - assert!(first - .iter() - .any(|(k, v)| k == "same_site" && matches!(v, Value::Text(t) if t == "Lax"))); - let Value::Map(second) = &items[1] else { - panic!("expected map"); - }; - assert!(second - .iter() - .any(|(k, v)| k == "name" && matches!(v, Value::Text(t) if t == "theme"))); - assert!(second.iter().any(|(k, v)| k == "max_age" - && matches!(v, Value::Text(t) if t == "3600"))); - } - - #[test] - fn multipart_form_parse() { - let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; - let body = format!( - "--{boundary}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nHello\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a.txt\"\r\nContent-Type: text/plain\r\n\r\nfile body\r\n--{boundary}--\r\n" - ); - let v = multipart_parse(&Value::Text(body.into()), &Value::Text(boundary.into())).unwrap(); - let Value::List(items) = v else { - panic!("expected list"); - }; - assert_eq!(items.len(), 2); - let Value::Map(f0) = &items[0] else { - panic!("expected map"); - }; - assert!(f0 - .iter() - .any(|(k, v)| k == "name" && matches!(v, Value::Text(t) if t == "title"))); - assert!(f0 - .iter() - .any(|(k, v)| k == "value" && matches!(v, Value::Text(t) if t == "Hello"))); - let Value::Map(f1) = &items[1] else { - panic!("expected map"); - }; - assert!(f1 - .iter() - .any(|(k, v)| k == "name" && matches!(v, Value::Text(t) if t == "file"))); - assert!(f1 - .iter() - .any(|(k, v)| k == "filename" && matches!(v, Value::Text(t) if t == "a.txt"))); - assert!(f1 - .iter() - .any(|(k, v)| k == "value" && matches!(v, Value::Text(t) if t == "file body"))); - } - - #[test] - fn markdown_parse_basic() { - let md = Value::Text("# Hello\n\nA **bold** word.".into()); - let out = markdown_parse(&md).unwrap(); - let Value::Text(html) = out else { - panic!("expected text html"); - }; - assert!(html.contains("bold")); - } -} diff --git a/src/host/net_ops.rs b/src/host/net_ops.rs deleted file mode 100755 index da95b3f..0000000 --- a/src/host/net_ops.rs +++ /dev/null @@ -1,201 +0,0 @@ -//! Configurable bounded HTTP with one recoverable Result envelope. -#[cfg(feature = "net-host")] -use super::as_text; -use super::result; -use crate::{ - host::{HostContext, HostFn}, - value::Value, -}; -use std::collections::HashMap; -#[cfg(feature = "net-host")] -use std::{ - io::{Read, Write}, - time::Duration, -}; -type Args = HashMap; -#[cfg(feature = "net-host")] -fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { - b.get(k).ok_or_else(|| format!("missing {k}")) -} -pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { - #[cfg(feature = "net-host")] - let answer = request(ctx, id, b); - #[cfg(not(feature = "net-host"))] - let answer = { - let _ = (ctx, id, b); - Err("HTTP unavailable in this build".into()) - }; - Ok(result::capture( - if id == HostFn::HttpDownload { - "net.download" - } else { - "net.request" - }, - answer, - )) -} -#[cfg(feature = "net-host")] -fn integer(b: &Args, k: &str, max: u64) -> Result { - match arg(b, k)? { - Value::Int(n) if *n > 0 && (*n as u64) <= max => Ok(*n as u64), - _ => Err(format!("{k} must be 1..{max}")), - } -} -#[cfg(feature = "net-host")] -fn request(ctx: &HostContext, id: HostFn, b: &Args) -> Result { - if !ctx.allow_net() { - return Err("network denied by host policy".into()); - } - let url = as_text(arg(b, "url")?, "url")?; - if !(url.starts_with("https://") || url.starts_with("http://")) { - return Err("url must use http/https".into()); - } - let timeout = Duration::from_millis(integer(b, "timeout_ms", 600000)?); - let max = integer(b, "max_bytes", 1024 * 1024 * 1024)?; - let method = if matches!(id, HostFn::HttpDownload | HostFn::HttpGetResult) { - "GET" - } else { - as_text(arg(b, "method")?, "method")? - }; - if !matches!( - method, - "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" - ) { - return Err("unsupported method".into()); - } - // Reject invalid output settings and destinations before any HTTP exchange. - let destination = if id == HostFn::HttpDownload { - if !ctx.allow_fs_write() { - return Err("filesystem write denied by host policy".into()); - } - if ctx.sandbox_session.is_some() { - return Err("unsupported: stream download in CoW sandbox".into()); - } - let path = ctx.resolve_path(as_text(arg(b, "path")?, "path")?)?; - if path.is_dir() { - return Err("invalid_argument: download destination is a directory".into()); - } - Some(path) - } else { - if max > 64 * 1024 * 1024 { - return Err( - "resource_limit: in-memory response limit exceeds 64 MiB; use download".into(), - ); - } - if !matches!(as_text(arg(b, "response")?, "response")?, "text" | "bytes") { - return Err("invalid_argument: response must be text or bytes".into()); - } - None - }; - let agent = ureq::AgentBuilder::new() - .timeout(timeout) - .timeout_connect(timeout) - .timeout_read(timeout) - .timeout_write(timeout) - .build(); - let mut request = agent.request(method, url).set("User-Agent", "marqdo"); - if let Some(Value::Map(headers)) = b.get("headers") { - for (k, v) in headers { - request = request.set(k, as_text(v, "header value")?) - } - } else if !matches!(b.get("headers"), None | Some(Value::None)) { - return Err("headers must be map or None".into()); - } - let exchange = match b.get("body") { - None | Some(Value::None) => request.call(), - Some(Value::Text(text)) => request.send_bytes(text.as_bytes()), - Some(v) => request.send_bytes(&super::fs_ops::bytes(v)?), - }; - let response = match exchange { - Ok(r) => r, - Err(ureq::Error::Status(_, r)) => r, - Err(e) => return Err(format!("transport_error: {e}")), - }; - let status = response.status(); - let mut headers = Vec::new(); - for name in response.headers_names() { - let values = response - .all(&name) - .into_iter() - .map(|v| Value::Text(v.into())) - .collect(); - headers.push(Value::Map(vec![ - ("name".into(), Value::Text(name.to_ascii_lowercase())), - ("values".into(), Value::List(values)), - ])); - } - let mut reader = response.into_reader(); - if id == HostFn::HttpDownload { - if !(200..300).contains(&status) { - return Err(format!("http_status: {status}; destination unchanged")); - } - let path = destination.ok_or("missing validated download destination")?; - let parent = path.parent().ok_or("destination needs parent")?; - std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; - let mut entropy = [0u8; 16]; - getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?; - let token = entropy - .iter() - .map(|n| format!("{n:02x}")) - .collect::(); - let temp = parent.join(format!(".mq-download-{token}")); - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&temp) - .map_err(|e| e.to_string())?; - let downloaded = (|| { - let mut total = 0u64; - let mut buffer = [0u8; 65536]; - loop { - let n = reader.read(&mut buffer).map_err(|e| e.to_string())?; - if n == 0 { - break; - } - total += n as u64; - if total > max { - return Err("resource_limit: HTTP response exceeds max_bytes".into()); - } - file.write_all(&buffer[..n]).map_err(|e| e.to_string())?; - } - file.sync_all().map_err(|e| e.to_string())?; - drop(file); - std::fs::rename(&temp, &path).map_err(|e| e.to_string())?; - Ok(total) - })(); - let total = match downloaded { - Ok(n) => n, - Err(e) => { - let _ = std::fs::remove_file(temp); - return Err(e); - } - }; - return Ok(Value::Map(vec![ - ("status".into(), Value::Int(status as i64)), - ("headers".into(), Value::List(headers)), - ("size".into(), Value::Int(total as i64)), - ("path".into(), arg(b, "path")?.clone()), - ])); - } - let mut bytes = Vec::new(); - reader - .take(max + 1) - .read_to_end(&mut bytes) - .map_err(|e| e.to_string())?; - if bytes.len() as u64 > max { - return Err("resource_limit: HTTP response exceeds max_bytes".into()); - } - let mode = as_text(arg(b, "response")?, "response")?; - let body = match mode { - "text" => Value::Text(String::from_utf8(bytes).map_err(|e| { - format!("invalid_encoding: response is not UTF-8; request bytes instead: {e}") - })?), - "bytes" => super::fs_ops::bytes_value(&bytes), - _ => return Err("response must be text or bytes".into()), - }; - Ok(Value::Map(vec![ - ("status".into(), Value::Int(status as i64)), - ("headers".into(), Value::List(headers)), - ("body".into(), body), - ])) -} diff --git a/src/host/oracle.rs b/src/host/oracle.rs deleted file mode 100755 index 1ff4a3e..0000000 --- a/src/host/oracle.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Document-level observations, separate from process timing and execution logs. -use crate::value::Value; -use super::HostContext; - -pub(crate) fn admit(value: &Value) -> Result<(), String> { - match value { - Value::None | Value::Bool(_) | Value::Text(_) => Ok(()), - Value::Int(_) => super::json::value_to_json(value).map(|_| ()), - Value::Num(_) => super::json::value_to_json(value).map(|_| ()), - Value::List(xs) => { for x in xs { admit(x)?; } Ok(()) } - Value::Map(xs) => { - super::json::value_to_json(value)?; - let mut keys = std::collections::HashSet::new(); - for (key, x) in xs { - if !keys.insert(key) { return Err("oracle: duplicate record field".into()); } - admit(x)?; - } - Ok(()) - } - _ => Err("oracle: value outside V_safe".into()), - } -} - -pub(crate) fn append(ctx: &mut HostContext, channel: &str, value: &Value) -> Result<(), String> { - admit(value)?; - ctx.oracle_observations.push(Value::Map(vec![ - ("index".into(), Value::Int(ctx.oracle_observations.len() as i64)), - ("channel".into(), Value::Text(channel.into())), - ("value".into(), value.clone()), - ])); - Ok(()) -} - -/// Project a process result to its semantic observation. Success observes the -/// returned payload. Failure observes stable diagnostics, never elapsed time, -/// command paths or opaque handles. Both document and live runners use this. -pub(crate) fn eval_observation(record: &Value) -> Result { - let Value::Map(fields) = record else { return Err("oracle: expected eval record".into()) }; - let get = |key: &str| fields.iter().find(|(k, _)| k == key).map(|(_,v)|v.clone()).unwrap_or(Value::None); - let value = match get("ok") { - Value::Bool(true) => get("result"), - Value::Bool(false) => { - let source = get("diagnostic_source"); - Value::Map(["ok", "code", "stdout", "stderr", "error", "timed_out", "alive"] - .into_iter().map(|key| { - let value = get(key); - // Alpha-rename only this execution's allocated source path, - // only in diagnostics. Keep raw output and ordinary paths intact. - let value = match (key, value, &source) { - ("stderr" | "error", Value::Text(text), Value::Text(path)) if !path.is_empty() => - Value::Text(text.replace(path, "")), - (_, value, _) => value, - }; - (key.to_string(), value) - }).collect()) - }, - _ => return Err("oracle: eval record missing boolean ok".into()), - }; - admit(&value)?; - Ok(value) -} - -fn validate(journal: &Value) -> Result<&[Value], String> { - let Value::List(rows) = journal else { return Err("oracle journal must be a list".into()) }; - for (i, row) in rows.iter().enumerate() { - let Value::Map(fields) = row else { return Err(format!("oracle step {i}: expected record")) }; - if fields.len() != 3 { return Err(format!("oracle step {i}: expected index/channel/value")); } - let get = |k: &str| fields.iter().find(|(key,_)| key == k).map(|(_,v)|v); - if get("index") != Some(&Value::Int(i as i64)) { return Err(format!("oracle step {i}: invalid index")); } - if !matches!(get("channel"), Some(Value::Text(s)) if ["eval", "get", "decode"].contains(&s.as_str())) { - return Err(format!("oracle step {i}: invalid channel")); - } - admit(get("value").ok_or_else(|| format!("oracle step {i}: missing value"))?)?; - } - Ok(rows) -} - -/// Pure structural equality on admitted journals; reports the least differing index. -pub(crate) fn replay_check(expected: &Value, observed: &Value) -> Result { - let a = validate(expected)?; - let b = validate(observed)?; - // Map field order is not part of record identity (matches JSON object semantics). - let canonical = |v: &Value| super::json::value_to_json(v); - let mut mismatch = None; - for i in 0..a.len().max(b.len()) { - if a.get(i).map(canonical).transpose()? != b.get(i).map(canonical).transpose()? { - mismatch = Some(i); - break; - } - } - let index = mismatch.map(|i| Value::Int(i as i64)).unwrap_or(Value::None); - Ok(Value::Map(vec![ - ("ok".into(), Value::Bool(mismatch.is_none())), - ("index".into(), index), - ("expected".into(), mismatch.and_then(|i| a.get(i)).cloned().unwrap_or(Value::None)), - ("observed".into(), mismatch.and_then(|i| b.get(i)).cloned().unwrap_or(Value::None)), - ])) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn oracle_journal_structural_mismatch_and_length() { - let mut ctx = HostContext::default(); - append(&mut ctx, "eval", &Value::Int(3)).unwrap(); - append(&mut ctx, "get", &Value::Int(2)).unwrap(); - let journal = Value::List(ctx.oracle_observations.clone()); - let result = replay_check(&journal, &journal).unwrap(); - assert_eq!(super::super::json::get(&result, &Value::Text("ok".into())).unwrap(), Value::Bool(true)); - let short = Value::List(ctx.oracle_observations[..1].to_vec()); - let result = replay_check(&journal, &short).unwrap(); - assert_eq!(super::super::json::get(&result, &Value::Text("index".into())).unwrap(), Value::Int(1)); - assert!(append(&mut ctx, "eval", &Value::List(vec![Value::Handle("x".into())])).is_err()); - let code = Value::Code(crate::value::CodeBlock { lang: "python".into(), source: "1".into() }); - assert!(admit(&Value::List(vec![code])).is_err()); - assert_eq!(ctx.oracle_observations.len(), 2); - } - #[test] - fn diagnostic_projection_renames_only_allocated_source_identity() { - let make = |path: &str, message: &str| Value::Map(vec![ - ("ok".into(), Value::Bool(false)), - ("stderr".into(), Value::Text(format!("File {path}: {message}; input /data/original.csv"))), - ("diagnostic_source".into(), Value::Text(path.into())), - ]); - let a = make("/tmp/allocated-a.py", "ValueError"); - let b = make("/tmp/allocated-b.py", "ValueError"); - assert_ne!(a, b, "raw diagnostics must survive"); - assert_eq!(eval_observation(&a).unwrap(), eval_observation(&b).unwrap()); - let c = make("/tmp/allocated-b.py", "TypeError"); - assert_ne!(eval_observation(&a).unwrap(), eval_observation(&c).unwrap()); - let d = make("/tmp/allocated-b.py", "ValueError /data/changed.csv"); - assert_ne!(eval_observation(&a).unwrap(), eval_observation(&d).unwrap()); - } - -} diff --git a/src/host/path.rs b/src/host/path.rs deleted file mode 100755 index c6cb872..0000000 --- a/src/host/path.rs +++ /dev/null @@ -1,117 +0,0 @@ -//! Path algebra for Mid M2 (`lib/path`) — no I/O. - -use crate::host::as_text; -use std::path::{Component, Path, PathBuf}; - -use crate::value::Value; - - -fn path_to_text(p: &Path) -> String { - if p.as_os_str().is_empty() { - ".".into() - } else { - p.to_string_lossy().into_owned() - } -} - -pub fn join(a: &Value, b: &Value) -> Result { - let a = as_text(a, "a")?; - let b = as_text(b, "b")?; - let out = Path::new(a).join(b); - Ok(Value::Text(path_to_text(&out))) -} - -pub fn split(path: &Value) -> Result { - let p = as_text(path, "path")?; - let mut parts = Vec::new(); - for c in Path::new(p).components() { - match c { - Component::RootDir | Component::CurDir | Component::ParentDir => { - parts.push(Value::Text(c.as_os_str().to_string_lossy().into_owned())); - } - Component::Prefix(prefix) => { - parts.push(Value::Text(prefix.as_os_str().to_string_lossy().into_owned())); - } - Component::Normal(s) => parts.push(Value::Text(s.to_string_lossy().into_owned())), - } - } - Ok(Value::List(parts)) -} - -pub fn file_name(path: &Value) -> Result { - let p = as_text(path, "path")?; - Ok(Value::Text( - Path::new(p) - .file_name() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(), - )) -} - -pub fn parent(path: &Value) -> Result { - let p = as_text(path, "path")?; - let parent = Path::new(p).parent(); - Ok(Value::Text(match parent { - Some(par) if !par.as_os_str().is_empty() => path_to_text(par), - _ => ".".into(), - })) -} - -pub fn extension(path: &Value) -> Result { - let p = as_text(path, "path")?; - Ok(Value::Text( - Path::new(p) - .extension() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(), - )) -} - -pub fn normalize(path: &Value) -> Result { - let p = as_text(path, "path")?; - let mut out = PathBuf::new(); - for c in Path::new(p).components() { - match c { - Component::CurDir => {} - Component::ParentDir => { - match out.components().next_back() { - Some(Component::Normal(_)) => { - out.pop(); - } - Some(Component::RootDir) | Some(Component::Prefix(_)) => {} - _ => out.push(".."), - } - } - other => out.push(other.as_os_str()), - } - } - Ok(Value::Text(path_to_text(&out))) -} - -pub fn is_absolute(path: &Value) -> Result { - let p = as_text(path, "path")?; - Ok(Value::Bool(Path::new(p).is_absolute())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn join_and_name() { - let j = join( - &Value::Text("a/b".into()), - &Value::Text("c.txt".into()), - ) - .unwrap(); - assert_eq!(j, Value::Text("a/b/c.txt".into())); - assert_eq!( - file_name(&Value::Text("a/b/c.txt".into())).unwrap(), - Value::Text("c.txt".into()) - ); - assert_eq!( - extension(&Value::Text("c.txt".into())).unwrap(), - Value::Text("txt".into()) - ); - } -} diff --git a/src/host/plugin.rs b/src/host/plugin.rs deleted file mode 100755 index b6f13f9..0000000 --- a/src/host/plugin.rs +++ /dev/null @@ -1,793 +0,0 @@ -//! Native plugin loader (C ABI v1/v2). Shared libs are not linked into marqdo. - -use crate::host::as_text; -use std::cell::{Cell, RefCell}; -use std::collections::HashMap; -use std::ffi::{CStr, CString}; -use std::os::raw::{c_char, c_int, c_void}; -use std::path::PathBuf; -use std::sync::{Mutex, MutexGuard, OnceLock}; -use std::time::{Duration, Instant}; - -use libloading::{Library, Symbol}; - -use crate::host::agent_rt; -use crate::host::json::{json_to_value, value_to_json}; -use crate::host::HostContext; -use crate::value::Value; - -/// Highest ABI version this host speaks. -pub const ABI_VERSION: u32 = 2; -/// Oldest plugin ABI still accepted. -pub const ABI_VERSION_MIN: u32 = 1; - -type PluginFn = unsafe extern "C" fn( - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int; - -type HostQueryFn = unsafe extern "C" fn( - userdata: *mut c_void, - name: *const c_char, - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int; - -type AbiVersionFn = unsafe extern "C" fn() -> u32; -type InitFn = unsafe extern "C" fn(host: *const MarqdoHostApi) -> c_int; -type ShutdownFn = unsafe extern "C" fn(); - -#[repr(C)] -struct MarqdoHostApi { - userdata: *mut c_void, - register_fn: Option< - unsafe extern "C" fn( - userdata: *mut c_void, - name: *const c_char, - params: *const c_char, - fn_ptr: PluginFn, - ) -> c_int, - >, - alloc: Option *mut c_void>, - free: Option, - host_query: Option, -} - -thread_local! { - /// Set around plugin calls so `host_query` can read/write host context (plots, etc.). - static CURRENT_HOST: Cell<*mut HostContext> = const { Cell::new(std::ptr::null_mut()) }; - /// Optional `lib.member` resolver for `host_query("call_lib_path")` (site entry module). - static LIB_PATH_CALL: RefCell> = const { RefCell::new(None) }; -} - -/// Process-wide host pointer while a long-lived plugin call (e.g. `web_listen`) is active. -/// Lets Tokio worker threads invoke `host_query` during HTTP handlers. -struct SendPtr(*mut T); -unsafe impl Send for SendPtr {} -unsafe impl Sync for SendPtr {} - -struct SendLibPath(Option); -unsafe impl Send for SendLibPath {} -unsafe impl Sync for SendLibPath {} - -static GLOBAL_HOST: OnceLock>> = OnceLock::new(); -/// Process-wide lib-path hook (same lifetime as GLOBAL_HOST). -static GLOBAL_LIB_PATH: OnceLock> = OnceLock::new(); -/// Serialize interpreter re-entry from HTTP worker threads. -/// HostContext is not Sync — one Marqdo invoke at a time. Short routes must -/// fail fast (`interpreter busy`) so a long SSE chat cannot freeze the UI. -static INVOKE_LOCK: OnceLock> = OnceLock::new(); - -fn global_host_slot() -> &'static Mutex> { - GLOBAL_HOST.get_or_init(|| Mutex::new(SendPtr(std::ptr::null_mut()))) -} - -fn global_lib_slot() -> &'static Mutex { - GLOBAL_LIB_PATH.get_or_init(|| Mutex::new(SendLibPath(None))) -} - -fn invoke_lock() -> &'static Mutex<()> { - INVOKE_LOCK.get_or_init(|| Mutex::new(())) -} - -/// Default wait for short HTTP invokes (`MARQDO_INVOKE_WAIT_MS`, default 1500ms). -/// Do not raise this process-wide during SSE — concurrent short routes would hang again. -/// See doc/adr/0008-web-invoke-serialization.md. -fn invoke_wait_budget() -> Duration { - const DEFAULT_MS: u64 = 1500; - match std::env::var("MARQDO_INVOKE_WAIT_MS") { - Ok(s) => { - let ms = s.trim().parse::().unwrap_or(DEFAULT_MS); - Duration::from_millis(ms.max(1)) - } - Err(_) => Duration::from_millis(DEFAULT_MS), - } -} - -fn acquire_invoke_lock() -> Result, String> { - let budget = invoke_wait_budget(); - let deadline = Instant::now() + budget; - let lock = invoke_lock(); - loop { - match lock.try_lock() { - Ok(g) => return Ok(g), - Err(std::sync::TryLockError::Poisoned(p)) => return Ok(p.into_inner()), - Err(std::sync::TryLockError::WouldBlock) => { - if Instant::now() >= deadline { - return Err(format!( - "interpreter busy: another request holds the Marqdo invoke lock (waited {}ms)", - budget.as_millis() - )); - } - std::thread::sleep(Duration::from_millis(15)); - } - } - } -} - -/// Hook: resolve bare `lib.member` (and longer paths) in the site module's import tree. -#[derive(Clone, Copy)] -pub struct LibPathCall { - pub call: fn(*mut (), &str, Option<&Value>) -> Result, - pub data: *mut (), -} - -/// Run `body` with a temporary lib-path call hook (nested-safe). -pub fn with_lib_path_call(hook: LibPathCall, body: impl FnOnce() -> R) -> R { - LIB_PATH_CALL.with(|slot| { - let prev = slot.replace(Some(hook)); - let prev_g = { - let mut g = global_lib_slot().lock().unwrap_or_else(|e| e.into_inner()); - std::mem::replace(&mut g.0, Some(hook)) - }; - let out = body(); - { - let mut g = global_lib_slot().lock().unwrap_or_else(|e| e.into_inner()); - g.0 = prev_g; - } - slot.replace(prev); - out - }) -} - -struct RegisterBuf { - fns: HashMap, - error: Option, -} - -#[derive(Clone)] -pub struct RegisteredFn { - pub params: Vec, - fn_ptr: PluginFn, -} - -pub struct PluginState { - libs: Vec, - fns: HashMap, -} - -impl Default for PluginState { - fn default() -> Self { - Self { - libs: Vec::new(), - fns: HashMap::new(), - } - } -} - -impl std::fmt::Debug for PluginState { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("PluginState") - .field("libs", &self.libs.len()) - .field("fns", &self.list_names()) - .finish() - } -} - -impl Clone for PluginState { - fn clone(&self) -> Self { - // `Library` handles are not cloneable; a cloned host starts with no plugins. - Self::default() - } -} - -impl PluginState { - /// Exercise the real JSON/C ABI without loading an external shared library. - #[cfg(test)] - pub(crate) fn register_binding_probe(&mut self) { - unsafe extern "C" fn echo(args: *const c_char, out: *mut *mut c_char, _err: *mut *mut c_char) -> c_int { - if args.is_null() || out.is_null() { return 1; } - let Ok(input)=CStr::from_ptr(args).to_str() else { return 1; }; - *out=host_strdup(input); - if (*out).is_null() {1} else {0} - } - self.fns.insert("binding_probe".into(),RegisteredFn{params:vec!["a".into(),"b".into()],fn_ptr:echo}); - } - pub fn get(&self, name: &str) -> Option<&RegisteredFn> { - self.fns.get(name) - } - - pub fn list_names(&self) -> Vec { - let mut names: Vec<_> = self.fns.keys().cloned().collect(); - names.sort(); - names - } - - pub fn has_fn(&self, name: &str) -> bool { - self.fns.contains_key(name) - } -} - - -extern "C" { - fn malloc(n: usize) -> *mut c_void; - fn free(p: *mut c_void); -} - -unsafe extern "C" fn host_alloc(n: usize) -> *mut c_void { - malloc(n) -} - -unsafe extern "C" fn host_free(p: *mut c_void) { - if !p.is_null() { - free(p); - } -} - -unsafe fn host_strdup(s: &str) -> *mut c_char { - let bytes = s.as_bytes(); - let p = host_alloc(bytes.len() + 1) as *mut u8; - if p.is_null() { - return std::ptr::null_mut(); - } - std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); - *p.add(bytes.len()) = 0; - p as *mut c_char -} - -unsafe extern "C" fn host_register( - userdata: *mut c_void, - name: *const c_char, - params: *const c_char, - fn_ptr: PluginFn, -) -> c_int { - if userdata.is_null() || name.is_null() { - return 1; - } - let buf = &mut *(userdata as *mut RegisterBuf); - let name = match CStr::from_ptr(name).to_str() { - Ok(s) => s.to_string(), - Err(_) => { - buf.error = Some("plugin register: name is not UTF-8".into()); - return 1; - } - }; - if name.is_empty() { - buf.error = Some("plugin register: empty name".into()); - return 1; - } - let params_s = if params.is_null() { - "" - } else { - match CStr::from_ptr(params).to_str() { - Ok(s) => s, - Err(_) => { - buf.error = Some("plugin register: params is not UTF-8".into()); - return 1; - } - } - }; - let param_list: Vec = if params_s.trim().is_empty() { - Vec::new() - } else { - params_s - .split(',') - .map(|p| p.trim().to_string()) - .filter(|p| !p.is_empty()) - .collect() - }; - if buf.fns.contains_key(&name) { - buf.error = Some(format!("plugin register: duplicate `{name}`")); - return 1; - } - buf.fns.insert( - name, - RegisteredFn { - params: param_list, - fn_ptr, - }, - ); - 0 -} - -/// Allowlisted host introspection for ABI v2 plugins (`host_query`). -unsafe extern "C" fn host_query( - _userdata: *mut c_void, - name: *const c_char, - args_json: *const c_char, - out_json: *mut *mut c_char, - err_msg: *mut *mut c_char, -) -> c_int { - let set_err = |msg: &str| { - if !err_msg.is_null() { - *err_msg = host_strdup(msg); - } - }; - let set_out = |msg: &str| { - if !out_json.is_null() { - *out_json = host_strdup(msg); - } - }; - - if name.is_null() { - set_err("host_query: null name"); - return 1; - } - let name = match CStr::from_ptr(name).to_str() { - Ok(s) => s, - Err(_) => { - set_err("host_query: name not utf-8"); - return 1; - } - }; - - let args_owned: Option = if args_json.is_null() { - None - } else { - CStr::from_ptr(args_json) - .to_str() - .ok() - .map(|s| s.to_string()) - }; - - // Control plane (admit/cancel/events) must not take INVOKE_LOCK or require - // an evaluating HostContext — otherwise cancel cannot interrupt a busy run. - if name == "runtime" { - let raw = args_owned.as_deref().unwrap_or("{}"); - let args: serde_json::Value = match serde_json::from_str(if raw.trim().is_empty() { - "{}" - } else { - raw - }) { - Ok(v) => v, - Err(e) => { - set_err(&format!("runtime args: {e}")); - return 1; - } - }; - match crate::runtime::host_api::handle(&args) { - Ok(j) => { - set_out(&j.to_string()); - return 0; - } - Err(e) => { - set_err(&e); - return 1; - } - } - } - - let ctx_ptr = CURRENT_HOST.with(|c| c.get()); - let ctx_ptr = if ctx_ptr.is_null() { - global_host_slot() - .lock() - .unwrap_or_else(|e| e.into_inner()) - .0 - } else { - ctx_ptr - }; - if ctx_ptr.is_null() { - set_err("host_query: no active host context (call during plugin fn)"); - return 1; - } - let _invoke_guard; - let from_worker = CURRENT_HOST.with(|c| c.get().is_null()); - if from_worker { - match acquire_invoke_lock() { - Ok(g) => _invoke_guard = g, - Err(msg) => { - set_err(&msg); - return 1; - } - } - } - let ctx = &mut *ctx_ptr; - - let result = match name { - "module_source" => agent_rt::module_source(ctx).and_then(|v| value_to_json(&v)), - "call_site" => agent_rt::call_site(ctx, Some(ctx.current_line)).and_then(|v| value_to_json(&v)), - "marqdo_skill" => agent_rt::marqdo_skill(ctx).and_then(|v| value_to_json(&v)), - "cwd" => Ok(serde_json::Value::String( - ctx.cwd.to_string_lossy().into_owned(), - )), - "entry_path" => { - let path = ctx.entry_path.clone().unwrap_or_else(|| ctx.cwd.clone()); - let abs = if path.is_absolute() { - path - } else { - std::env::current_dir() - .unwrap_or_else(|_| PathBuf::from(".")) - .join(path) - }; - Ok(serde_json::Value::String( - abs.to_string_lossy().into_owned(), - )) - } - "entry_dir" => { - // Script directory: parent of entry file (for_run also sets ctx.cwd to this). - let dir = ctx - .entry_path - .as_ref() - .map(|p| { - if p.is_dir() { - p.clone() - } else { - p.parent().unwrap_or(p).to_path_buf() - } - }) - .unwrap_or_else(|| ctx.cwd.clone()); - // Absolutize against the *process* cwd — not ctx.cwd. For a relative - // entry like `tests/ext/foo.mq.md`, for_run sets ctx.cwd = `tests/ext`; - // joining that again would yield `tests/ext/tests/ext/...`. - let abs = if dir.is_absolute() { - dir - } else { - std::env::current_dir() - .unwrap_or_else(|_| PathBuf::from(".")) - .join(dir) - }; - Ok(serde_json::Value::String( - abs.to_string_lossy().into_owned(), - )) - } - "call_lib_path" => (|| { - let raw = args_owned.as_deref().unwrap_or("{}"); - let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() { - "{}" - } else { - raw - }) - .map_err(|e| format!("call_lib_path args: {e}"))?; - let path = args - .get("path") - .and_then(|v| v.as_str()) - .ok_or_else(|| "call_lib_path requires `path`".to_string())? - .to_string(); - let call_args = args.get("args").and_then(|v| { - if v.is_null() { - None - } else { - json_to_value(v).ok() - } - }); - let call_args_ref = call_args.as_ref(); - let from_tls = LIB_PATH_CALL.with(|slot| slot.borrow().clone()); - let hook = if let Some(h) = from_tls { - h - } else { - global_lib_slot() - .lock() - .unwrap_or_else(|e| e.into_inner()) - .0 - .ok_or_else(|| "call_lib_path: no site lib resolver".to_string())? - }; - let v = (hook.call)(hook.data, &path, call_args_ref)?; - value_to_json(&v) - })(), - "record_plot" => (|| { - let raw = args_owned.as_deref().unwrap_or("{}"); - let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() { - "{}" - } else { - raw - }) - .map_err(|e| format!("record_plot args: {e}"))?; - let svg = args - .get("svg") - .and_then(|v| v.as_str()) - .ok_or_else(|| "record_plot requires `svg`".to_string())? - .to_string(); - let path_s = args - .get("path") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()); - if let Some(ref p) = path_s { - crate::host::fs::write_text( - ctx, - &Value::Text(p.clone()), - &Value::Text(svg.clone()), - )?; - } - ctx.plots.push(crate::host::PlotArtifact { - path: path_s, - svg, - }); - Ok(serde_json::json!({ "ok": true })) - })(), - name if name.starts_with("sandbox_") => (|| { - let raw = args_owned.as_deref().unwrap_or("{}"); - let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() { - "{}" - } else { - raw - }) - .map_err(|e| format!("{name} args: {e}"))?; - crate::host::sandbox_fs::query(name, &args, ctx) - })(), - // ADR 0007: run a Document/Endpoint `.mq.md` for HTTP handlers. - "run_artifact" => (|| { - let raw = args_owned.as_deref().unwrap_or("{}"); - let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() { - "{}" - } else { - raw - }) - .map_err(|e| format!("run_artifact args: {e}"))?; - let path = args - .get("path") - .and_then(|v| v.as_str()) - .ok_or_else(|| "run_artifact requires `path`".to_string())?; - let p = ctx.resolve_path(path)?; - if !p.is_file() { - return Err(format!("run_artifact: not a file: {path}")); - } - // A web site may narrow an existing filesystem grant. Child - // Documents keep that explicit root instead of defaulting to pages/. - let fs_root = match args.get("root") { - None | Some(serde_json::Value::Null) => ctx.fs_root.clone(), - Some(serde_json::Value::String(root)) => { - let selected = ctx.resolve_path(root)?; - if !selected.is_dir() { return Err("run_artifact: root is not a directory".into()); } - let actual = p.canonicalize().map_err(|_| "run_artifact: cannot resolve source")?; - let base = selected.canonicalize().map_err(|_| "run_artifact: cannot resolve root")?; - if !actual.starts_with(&base) { - return Err("run_artifact: source is outside selected site root".into()); - } - Some(selected) - } - Some(_) => return Err("run_artifact: root must be text".into()), - }; - let mut binds: Vec<(String, String)> = Vec::new(); - if let Some(obj) = args.get("args").and_then(|v| v.as_object()) { - for (k, v) in obj { - let s = match v { - serde_json::Value::String(t) => t.clone(), - serde_json::Value::Null => continue, - other => other.to_string(), - }; - binds.push((k.clone(), s)); - } - } - let opts = crate::RunOptions { - binds, - fs_root, - allow_fs_write: ctx.caps.fs_write, - allow_exec: ctx.caps.exec, - allow_net: ctx.caps.net, - ..crate::RunOptions::default() - }; - let cap = crate::run_file_capture(&p, &opts).map_err(|e| e.to_string())?; - value_to_json(&cap.value) - })(), - // M04: plugins may drive MLSP artifact.bind/execute without inventing a second protocol. - "mlsp" => (|| { - let raw = args_owned.as_deref().unwrap_or("{}"); - let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() { - "{}" - } else { - raw - }) - .map_err(|e| format!("mlsp args: {e}"))?; - let method = args - .get("method") - .and_then(|v| v.as_str()) - .ok_or_else(|| "mlsp requires `method`".to_string())?; - let params = args.get("params").cloned().unwrap_or(serde_json::json!({})); - let line = serde_json::json!({"method": method, "params": params}).to_string(); - let resp = crate::mlsp::handle_line(&line); - serde_json::from_str(&resp).map_err(|e| format!("mlsp response: {e}")) - })(), - other => Err(format!("host_query: unknown `{other}`")), - }; - - match result { - Ok(j) => { - set_out(&j.to_string()); - 0 - } - Err(e) => { - set_err(&e); - 1 - } - } -} - -pub fn load(ctx: &mut HostContext, path: &Value) -> Result { - if !ctx.allow_plugin() { - if ctx.sandbox_session.is_some() { - return Err("plugin.load unavailable in sandbox".into()); - } - return Err("plugin_load denied by host policy".into()); - } - let rel = as_text(path, "path")?; - let file = match ctx.resolve_path(rel) { - Ok(p) => p, - Err(e) => { - let p = std::path::Path::new(rel); - let abs = if p.is_absolute() { - p.to_path_buf() - } else { - ctx.cwd.join(p) - }; - if abs.is_file() && crate::ext_cli::path_is_trusted_plugin(&abs) { - abs - } else { - return Err(e); - } - } - }; - if !file.is_file() { - return Err(format!("plugin_load: not a file: {}", file.display())); - } - - let lib = unsafe { Library::new(&file) } - .map_err(|e| format!("plugin_load {}: {e}", file.display()))?; - - let version_fn: Symbol = unsafe { - lib.get(b"marqdo_plugin_abi_version\0") - .map_err(|e| format!("plugin missing marqdo_plugin_abi_version: {e}"))? - }; - let ver = unsafe { version_fn() }; - if ver < ABI_VERSION_MIN || ver > ABI_VERSION { - return Err(format!( - "plugin ABI version {ver} not in host range {ABI_VERSION_MIN}..={ABI_VERSION} ({})", - file.display() - )); - } - - let init_fn: Symbol = unsafe { - lib.get(b"marqdo_plugin_init\0") - .map_err(|e| format!("plugin missing marqdo_plugin_init: {e}"))? - }; - - let mut buf = RegisterBuf { - fns: HashMap::new(), - error: None, - }; - let api = MarqdoHostApi { - userdata: &mut buf as *mut RegisterBuf as *mut c_void, - register_fn: Some(host_register), - alloc: Some(host_alloc), - free: Some(host_free), - host_query: Some(host_query), - }; - - let rc = unsafe { init_fn(&api) }; - if rc != 0 { - return Err(buf - .error - .unwrap_or_else(|| format!("plugin init failed (code {rc})"))); - } - if let Some(e) = buf.error { - return Err(e); - } - - for k in buf.fns.keys() { - if ctx.plugins.fns.contains_key(k) { - // Idempotent re-load of the same plugin surface (e.g. multiple `agent` ctors). - if buf.fns.keys().all(|name| ctx.plugins.fns.contains_key(name)) { - return Ok(Value::Int(0)); - } - return Err(format!("plugin function `{k}` already registered")); - } - } - let added = buf.fns.len(); - for (k, v) in buf.fns { - ctx.plugins.fns.insert(k, v); - } - ctx.plugins.libs.push(lib); - Ok(Value::Int(added as i64)) -} - -pub fn unload(ctx: &mut HostContext) -> Result { - if !ctx.allow_plugin() { - return Err("plugin_unload denied by host policy".into()); - } - for lib in ctx.plugins.libs.drain(..) { - if let Ok(shutdown) = unsafe { lib.get::(b"marqdo_plugin_shutdown\0") } { - unsafe { shutdown() }; - } - drop(lib); - } - ctx.plugins.fns.clear(); - Ok(Value::None) -} - -pub fn list(ctx: &HostContext) -> Result { - Ok(Value::List( - ctx.plugins - .list_names() - .into_iter() - .map(Value::Text) - .collect(), - )) -} - -/// Call a registered plugin function with already-bound args (param name → Value). -pub fn call_registered( - ctx: &mut HostContext, - name: &str, - bound: &HashMap, -) -> Result { - if !ctx.allow_plugin() { - return Err("plugin call denied by host policy".into()); - } - let reg = ctx - .plugins - .get(name) - .ok_or_else(|| format!("unknown function `{name}`"))? - .clone(); - - let mut map = serde_json::Map::new(); - for p in ®.params { - let v = bound.get(p).unwrap_or(&Value::None); - map.insert(p.clone(), value_to_json(v)?); - } - for (k, v) in bound { - if !map.contains_key(k) { - map.insert(k.clone(), value_to_json(v)?); - } - } - let args_json = serde_json::Value::Object(map).to_string(); - let c_args = CString::new(args_json).map_err(|e| format!("plugin args: {e}"))?; - - let mut out_ptr: *mut c_char = std::ptr::null_mut(); - let mut err_ptr: *mut c_char = std::ptr::null_mut(); - - // Nesting-safe: restore previous host pointers after this call. Clearing to - // null would break a long-lived outer call (e.g. `web_listen`) so later - // HTTP `invoke` / `host_query` on worker threads see no active context. - let prev_tls = CURRENT_HOST.with(|c| { - let prev = c.get(); - c.set(ctx as *mut HostContext); - prev - }); - let prev_global = { - let mut g = global_host_slot().lock().unwrap_or_else(|e| e.into_inner()); - let prev = g.0; - g.0 = ctx as *mut HostContext; - prev - }; - let rc = unsafe { (reg.fn_ptr)(c_args.as_ptr(), &mut out_ptr, &mut err_ptr) }; - { - let mut g = global_host_slot().lock().unwrap_or_else(|e| e.into_inner()); - g.0 = prev_global; - } - CURRENT_HOST.with(|c| c.set(prev_tls)); - - let err_s = take_c_string(err_ptr); - let out_s = take_c_string(out_ptr); - - if rc != 0 { - return Err(err_s.unwrap_or_else(|| format!("plugin `{name}` failed (code {rc})"))); - } - let out_s = out_s.unwrap_or_else(|| "null".to_string()); - let j: serde_json::Value = - serde_json::from_str(&out_s).map_err(|e| format!("plugin `{name}` bad JSON result: {e}"))?; - json_to_value(&j) -} - -fn take_c_string(p: *mut c_char) -> Option { - if p.is_null() { - return None; - } - let s = unsafe { CStr::from_ptr(p) } - .to_str() - .map(|s| s.to_string()) - .ok(); - unsafe { host_free(p as *mut c_void) }; - s -} diff --git a/src/host/plugin_stub.rs b/src/host/plugin_stub.rs deleted file mode 100755 index 128b9dc..0000000 --- a/src/host/plugin_stub.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Stub plugin surface when `plugin-host` is disabled (browser wasm). - -use std::collections::HashMap; - -use crate::host::HostContext; -use crate::value::Value; - -pub const ABI_VERSION: u32 = 2; -pub const ABI_VERSION_MIN: u32 = 1; - -/// Hook: resolve bare `lib.member` (unused without native plugins). -#[derive(Clone, Copy)] -pub struct LibPathCall { - pub call: fn(*mut (), &str, Option<&Value>) -> Result, - pub data: *mut (), -} - -pub fn with_lib_path_call(_hook: LibPathCall, body: impl FnOnce() -> R) -> R { - body() -} - -#[derive(Clone)] -pub struct RegisteredFn { - pub params: Vec, -} - -#[derive(Debug, Default, Clone)] -pub struct PluginState; - -impl PluginState { - pub fn get(&self, _name: &str) -> Option<&RegisteredFn> { - None - } - - pub fn list_names(&self) -> Vec { - Vec::new() - } -} - -pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result { - Err("plugin.load unavailable in browser wasm".into()) -} - -pub fn unload(_ctx: &mut HostContext) -> Result { - Err("plugin.unload unavailable in browser wasm".into()) -} - -pub fn list(_ctx: &HostContext) -> Result { - Ok(Value::List(Vec::new())) -} - -pub fn call_registered( - _ctx: &mut HostContext, - name: &str, - _bound: &HashMap, -) -> Result { - Err(format!("plugin `{name}` unavailable in browser wasm")) -} diff --git a/src/host/re.rs b/src/host/re.rs deleted file mode 100755 index c6ba830..0000000 --- a/src/host/re.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! Regex host primitives for Mid M1 (`lib/re`). - -use crate::host::as_text; -use crate::value::Value; -use regex::Regex; - - -fn compile(pattern: &str) -> Result { - Regex::new(pattern).map_err(|e| format!("invalid regex: {e}")) -} - -pub fn is_match(text: &Value, pattern: &Value) -> Result { - let t = as_text(text, "text")?; - let p = as_text(pattern, "pattern")?; - let re = compile(p)?; - Ok(Value::Bool(re.is_match(t))) -} - -pub fn find(text: &Value, pattern: &Value) -> Result { - let t = as_text(text, "text")?; - let p = as_text(pattern, "pattern")?; - let re = compile(p)?; - Ok(match re.find(t) { - Some(m) => Value::Text(m.as_str().to_string()), - None => Value::None, - }) -} - -pub fn find_all(text: &Value, pattern: &Value) -> Result { - let t = as_text(text, "text")?; - let p = as_text(pattern, "pattern")?; - let re = compile(p)?; - let xs: Vec = re - .find_iter(t) - .map(|m| Value::Text(m.as_str().to_string())) - .collect(); - Ok(Value::List(xs)) -} - -pub fn replace( - text: &Value, - pattern: &Value, - with: &Value, - count: Option<&Value>, -) -> Result { - let t = as_text(text, "text")?; - let p = as_text(pattern, "pattern")?; - let w = as_text(with, "with")?; - let re = compile(p)?; - let limit = match count { - None | Some(Value::None) => None, - Some(Value::Int(n)) => { - if *n < 0 { - return Err("count must be non-negative".into()); - } - Some(*n as usize) - } - Some(_) => return Err("count needs int".into()), - }; - let out = match limit { - None => re.replace_all(t, w).into_owned(), - Some(0) => t.to_string(), - Some(n) => re.replacen(t, n, w).into_owned(), - }; - Ok(Value::Text(out)) -} - -pub fn split(text: &Value, pattern: &Value) -> Result { - let t = as_text(text, "text")?; - let p = as_text(pattern, "pattern")?; - let re = compile(p)?; - let xs: Vec = re - .split(t) - .map(|s| Value::Text(s.to_string())) - .collect(); - Ok(Value::List(xs)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn match_and_find() { - assert_eq!( - is_match( - &Value::Text("abc123".into()), - &Value::Text(r"\d+".into()) - ) - .unwrap(), - Value::Bool(true) - ); - assert_eq!( - find( - &Value::Text("ab12cd34".into()), - &Value::Text(r"\d+".into()) - ) - .unwrap(), - Value::Text("12".into()) - ); - } -} diff --git a/src/host/result.rs b/src/host/result.rs deleted file mode 100755 index 3045d27..0000000 --- a/src/host/result.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! A recoverable failure is data; permission errors remain explicit failures. -use crate::value::Value; - -pub(super) fn capture(operation: &str, result: Result) -> Value { - let (ok, value, error) = match result { - Ok(value) => (true, value, Value::None), - Err(message) => { - let tagged = message.split_once(':').map(|(code, _)| code); - let code = match tagged { - Some( - code @ ("validation_failed" | "timed_out" | "permission_denied" | "not_found" - | "conflict" | "invalid_encoding" | "invalid_json" | "invalid_csv" - | "invalid_toml" | "transport_error" | "http_status" | "resource_limit" - | "unsupported" | "invalid_argument" | "nonexistent_time" - | "ambiguous_time"), - ) => code, - _ if message.starts_with("path escapes sandbox root:") - || message.ends_with("denied by host policy") => - { - "permission_denied" - } - _ => "operation_failed", - }; - ( - false, - Value::None, - Value::Map(vec![ - ("code".into(), Value::Text(code.into())), - ("message".into(), Value::Text(message)), - ("operation".into(), Value::Text(operation.into())), - ]), - ) - } - }; - Value::Map(vec![ - ("ok".into(), Value::Bool(ok)), - ("value".into(), value), - ("error".into(), error), - ]) -} diff --git a/src/host/sandbox_fs.rs b/src/host/sandbox_fs.rs deleted file mode 100755 index 0872a5d..0000000 --- a/src/host/sandbox_fs.rs +++ /dev/null @@ -1,489 +0,0 @@ -//! Application-level CoW workspace for `ext/ai/sandbox` (via host_query). -//! -//! lower = real root (read-through); upper = session bytes; whiteout = logical delete. -//! Not a symlink forest. Symlink targets are not followed as isolation primitives. - -use std::collections::{HashMap, HashSet}; -use std::path::{Component, Path, PathBuf}; -use std::sync::{Mutex, OnceLock}; - -use serde_json::json; - -use crate::host::HostContext; -use crate::value::Value; - -#[derive(Debug, Default)] -pub struct CowSession { - pub root: PathBuf, - /// Relative path (forward slashes) → file bytes. - pub upper: HashMap>, - pub whiteout: HashSet, -} - -static SESSIONS: OnceLock>> = OnceLock::new(); -static SEQ: OnceLock> = OnceLock::new(); - -fn sessions() -> &'static Mutex> { - SESSIONS.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn next_id() -> String { - let mut g = SEQ - .get_or_init(|| Mutex::new(0)) - .lock() - .unwrap_or_else(|e| e.into_inner()); - *g = g.wrapping_add(1); - format!("sbx-{g}") -} - -fn normalize_rel(rel: &str) -> Result { - let rel = rel.trim().trim_start_matches('/'); - if rel.is_empty() { - return Err("sandbox path must not be empty".into()); - } - let p = Path::new(rel); - if p.is_absolute() { - return Err("sandbox path must be relative to session root".into()); - } - let mut out = Vec::new(); - for c in p.components() { - match c { - Component::Normal(s) => out.push(s.to_string_lossy().into_owned()), - Component::CurDir => {} - Component::ParentDir => { - return Err("sandbox path must not contain '..'".into()); - } - _ => return Err(format!("sandbox path invalid component in `{rel}`")), - } - } - if out.is_empty() { - return Err("sandbox path must not be empty".into()); - } - Ok(out.join("/")) -} - -fn abs_under_root(root: &Path, rel: &str) -> Result { - let rel_n = normalize_rel(rel)?; - let abs = root.join(Path::new(&rel_n)); - let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); - // Parent may not exist yet for writes — check by prefix components. - let mut check = abs.clone(); - loop { - if check == *root || check == root_canon { - return Ok(root.join(Path::new(&rel_n))); - } - if !check.pop() { - break; - } - if let Ok(c) = check.canonicalize() { - if crate::host::path_under_root(&c, &root_canon) || c == root_canon { - return Ok(root.join(Path::new(&rel_n))); - } - } - } - if crate::host::path_under_root(&abs, root) { - return Ok(abs); - } - Err(format!("path escapes sandbox root: {rel_n}")) -} - -pub fn open(root: Option<&str>, ctx: &HostContext) -> Result { - let root_pb = if let Some(r) = root.filter(|s| !s.is_empty()) { - let p = PathBuf::from(r); - if p.is_absolute() { - p - } else { - ctx.cwd.join(p) - } - } else if let Some(ep) = &ctx.entry_path { - ep.parent() - .unwrap_or(ep.as_path()) - .to_path_buf() - } else { - ctx.cwd.clone() - }; - let root_pb = if root_pb.is_absolute() { - root_pb - } else { - std::env::current_dir() - .unwrap_or_else(|_| PathBuf::from(".")) - .join(root_pb) - }; - if !root_pb.is_dir() { - return Err(format!( - "sandbox_open: root is not a directory: {}", - root_pb.display() - )); - } - let id = next_id(); - let sess = CowSession { - root: root_pb.clone(), - upper: HashMap::new(), - whiteout: HashSet::new(), - }; - sessions() - .lock() - .unwrap_or_else(|e| e.into_inner()) - .insert(id.clone(), sess); - Ok(json!({ - "id": id, - "root": root_pb.to_string_lossy(), - })) -} - -fn with_session_mut(id: &str, f: F) -> Result -where - F: FnOnce(&mut CowSession) -> Result, -{ - let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner()); - let sess = map - .get_mut(id) - .ok_or_else(|| format!("sandbox: unknown session `{id}`"))?; - f(sess) -} - -fn with_session(id: &str, f: F) -> Result -where - F: FnOnce(&CowSession) -> Result, -{ - let map = sessions().lock().unwrap_or_else(|e| e.into_inner()); - let sess = map - .get(id) - .ok_or_else(|| format!("sandbox: unknown session `{id}`"))?; - f(sess) -} - -pub fn write(id: &str, path: &str, text: &str) -> Result { - with_session_mut(id, |sess| { - let rel = normalize_rel(path)?; - let _ = abs_under_root(&sess.root, &rel)?; - sess.whiteout.remove(&rel); - sess.upper.insert(rel, text.as_bytes().to_vec()); - Ok(json!({ "ok": true })) - }) -} - -pub fn read(id: &str, path: &str) -> Result { - with_session(id, |sess| { - let rel = normalize_rel(path)?; - if sess.whiteout.contains(&rel) { - return Err(format!("sandbox_read: not found (whiteout): {rel}")); - } - if let Some(bytes) = sess.upper.get(&rel) { - let s = String::from_utf8(bytes.clone()) - .map_err(|e| format!("sandbox_read: not utf-8: {e}"))?; - return Ok(json!(s)); - } - let abs = abs_under_root(&sess.root, &rel)?; - let s = std::fs::read_to_string(&abs) - .map_err(|e| format!("sandbox_read {}: {e}", abs.display()))?; - Ok(json!(s)) - }) -} - -pub fn remove(id: &str, path: &str) -> Result { - with_session_mut(id, |sess| { - let rel = normalize_rel(path)?; - let _ = abs_under_root(&sess.root, &rel)?; - sess.upper.remove(&rel); - sess.whiteout.insert(rel); - Ok(json!({ "ok": true })) - }) -} - -pub fn diff(id: &str) -> Result { - with_session(id, |sess| { - let mut items: Vec = Vec::new(); - for p in sess.upper.keys() { - items.push(json!({ "path": p, "kind": "write" })); - } - for p in &sess.whiteout { - items.push(json!({ "path": p, "kind": "remove" })); - } - items.sort_by(|a, b| { - let pa = a.get("path").and_then(|v| v.as_str()).unwrap_or(""); - let pb = b.get("path").and_then(|v| v.as_str()).unwrap_or(""); - pa.cmp(pb) - }); - Ok(json!(items)) - }) -} - -pub fn commit(id: &str) -> Result { - with_session_mut(id, |sess| { - let mut applied = 0i64; - let writes: Vec<(String, Vec)> = sess - .upper - .iter() - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); - let removes: Vec = sess.whiteout.iter().cloned().collect(); - for (rel, bytes) in writes { - let abs = abs_under_root(&sess.root, &rel)?; - if let Some(parent) = abs.parent() { - std::fs::create_dir_all(parent) - .map_err(|e| format!("sandbox_commit mkdir: {e}"))?; - } - std::fs::write(&abs, &bytes) - .map_err(|e| format!("sandbox_commit write {}: {e}", abs.display()))?; - applied += 1; - } - for rel in removes { - let abs = abs_under_root(&sess.root, &rel)?; - if abs.exists() { - if abs.is_dir() { - std::fs::remove_dir_all(&abs) - .map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?; - } else { - std::fs::remove_file(&abs) - .map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?; - } - applied += 1; - } - } - sess.upper.clear(); - sess.whiteout.clear(); - Ok(json!({ "ok": true, "applied": applied })) - }) -} - -pub fn discard(id: &str) -> Result { - let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner()); - if map.remove(id).is_none() { - return Err(format!("sandbox: unknown session `{id}`")); - } - Ok(json!({ "ok": true })) -} - -pub fn inspect(id: &str) -> Result { - with_session(id, |sess| { - Ok(json!({ - "id": id, - "root": sess.root.to_string_lossy(), - "upper_count": sess.upper.len(), - "whiteout_count": sess.whiteout.len(), - "caps_default": { - "fs_write": true, - "exec": false, - "net": false, - "plugin": false - }, - "notes": [ - "ext/web listen/DB/WS unavailable in sandbox", - "plugin.load denied during sandbox.run", - "subtask path/code/lang unavailable in sandbox" - ] - })) - }) -} - -/// Byte-preserving overlay access shared by text and byte APIs. -pub(super) fn cow_read_bytes(ctx: &HostContext, abs: &Path) -> Result>, String> { - let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(None); }; - with_session(id, |session| { - let rel = rel_from_root(&session.root, abs)?; - if session.whiteout.contains(&rel) { return Err(format!("not found (sandbox whiteout): {rel}")); } - Ok(session.upper.get(&rel).cloned()) - }) -} -pub(super) fn cow_write_bytes(ctx: &HostContext, abs: &Path, bytes: &[u8]) -> Result { - let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(false); }; - with_session_mut(id, |session| { - let rel = rel_from_root(&session.root, abs)?; - session.whiteout.remove(&rel); - session.upper.insert(rel, bytes.to_vec()); - Ok(true) - }) -} - -/// Read file bytes through CoW for an active host sandbox session (lib/fs). -pub fn cow_read_text(ctx: &HostContext, abs: &Path) -> Result, String> { - let Some(id) = ctx.sandbox_session.as_deref() else { - return Ok(None); - }; - with_session(id, |sess| { - let rel = rel_from_root(&sess.root, abs)?; - if sess.whiteout.contains(&rel) { - return Err(format!("read_text: not found (sandbox whiteout): {rel}")); - } - if let Some(bytes) = sess.upper.get(&rel) { - let s = String::from_utf8(bytes.clone()) - .map_err(|e| format!("read_text: not utf-8: {e}"))?; - return Ok(Some(s)); - } - Ok(None) - }) -} - -pub fn cow_write_text(ctx: &HostContext, abs: &Path, text: &str) -> Result { - let Some(id) = ctx.sandbox_session.as_deref() else { - return Ok(false); - }; - with_session_mut(id, |sess| { - let rel = rel_from_root(&sess.root, abs)?; - sess.whiteout.remove(&rel); - sess.upper.insert(rel, text.as_bytes().to_vec()); - Ok(true) - }) -} - -pub fn cow_remove(ctx: &HostContext, abs: &Path) -> Result { - let Some(id) = ctx.sandbox_session.as_deref() else { - return Ok(false); - }; - with_session_mut(id, |sess| { - let rel = rel_from_root(&sess.root, abs)?; - sess.upper.remove(&rel); - sess.whiteout.insert(rel); - Ok(true) - }) -} - -pub fn cow_exists(ctx: &HostContext, abs: &Path) -> Result, String> { - let Some(id) = ctx.sandbox_session.as_deref() else { - return Ok(None); - }; - with_session(id, |sess| { - let rel = rel_from_root(&sess.root, abs)?; - if sess.whiteout.contains(&rel) { - return Ok(Some(false)); - } - if sess.upper.contains_key(&rel) { - return Ok(Some(true)); - } - Ok(None) - }) -} - -fn rel_from_root(root: &Path, abs: &Path) -> Result { - let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); - let abs_canon = abs.canonicalize().unwrap_or_else(|_| abs.to_path_buf()); - let rel = abs_canon - .strip_prefix(&root_canon) - .or_else(|_| abs.strip_prefix(root)) - .map_err(|_| format!("path not under sandbox root: {}", abs.display()))?; - normalize_rel(&rel.to_string_lossy().replace('\\', "/")) -} - -pub fn run( - id: &str, - source: Option<&str>, - path: Option<&str>, -) -> Result { - let (root, body) = with_session(id, |sess| { - let body = if let Some(src) = source.filter(|s| !s.trim().is_empty()) { - src.to_string() - } else if let Some(p) = path.filter(|s| !s.is_empty()) { - let rel = normalize_rel(p)?; - if sess.whiteout.contains(&rel) { - return Err(format!("sandbox_run: path whiteout: {rel}")); - } - if let Some(bytes) = sess.upper.get(&rel) { - String::from_utf8(bytes.clone()) - .map_err(|e| format!("sandbox_run: path not utf-8: {e}"))? - } else { - let abs = abs_under_root(&sess.root, &rel)?; - std::fs::read_to_string(&abs) - .map_err(|e| format!("sandbox_run read {}: {e}", abs.display()))? - } - } else { - return Err("sandbox_run requires `source` or `path`".into()); - }; - Ok((sess.root.clone(), body)) - })?; - - let opts = crate::RunOptions { - allow_fs_write: true, - allow_exec: false, - allow_net: false, - allow_plugin: false, - fs_root: Some(root), - sandbox_session: Some(id.to_string()), - sleep_limit_ms: Some(0), - ..crate::RunOptions::default() - }; - - match crate::run_source(&body, &opts) { - Ok(cap) => { - let value = crate::host::json::value_to_json(&cap.value) - .unwrap_or(serde_json::Value::Null); - Ok(json!({ - "ok": true, - "value": value, - "stdout": cap.stdout, - })) - } - Err(e) => { - let msg = e.to_string(); - Ok(json!({ - "ok": false, - "error": msg, - "value": null, - "stdout": "", - })) - } - } -} - -/// Parse host_query JSON args helper used from plugin.rs. -pub fn query(name: &str, args: &serde_json::Value, ctx: &HostContext) -> Result { - let id = || { - args.get("id") - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("{name}: missing `id`")) - }; - match name { - "sandbox_open" => { - let root = args.get("root").and_then(|v| v.as_str()); - open(root, ctx) - } - "sandbox_write" => { - let path = args - .get("path") - .and_then(|v| v.as_str()) - .ok_or_else(|| "sandbox_write: missing `path`".to_string())?; - let text = args - .get("text") - .and_then(|v| v.as_str()) - .ok_or_else(|| "sandbox_write: missing `text`".to_string())?; - write(id()?, path, text) - } - "sandbox_read" => { - let path = args - .get("path") - .and_then(|v| v.as_str()) - .ok_or_else(|| "sandbox_read: missing `path`".to_string())?; - read(id()?, path) - } - "sandbox_remove" => { - let path = args - .get("path") - .and_then(|v| v.as_str()) - .ok_or_else(|| "sandbox_remove: missing `path`".to_string())?; - remove(id()?, path) - } - "sandbox_diff" => diff(id()?), - "sandbox_commit" => commit(id()?), - "sandbox_discard" => discard(id()?), - "sandbox_inspect" => inspect(id()?), - "sandbox_run" => { - let source = args.get("source").and_then(|v| v.as_str()); - let path = args.get("path").and_then(|v| v.as_str()); - run(id()?, source, path) - } - other => Err(format!("sandbox query unknown `{other}`")), - } -} - -/// Used by fs layer when session is active — map Value path through resolve then CoW. -pub fn try_read_value(ctx: &HostContext, path: &Value) -> Result, String> { - let rel = match path { - Value::Text(s) => s.as_str(), - _ => return Ok(None), - }; - let abs = ctx.resolve_path(rel)?; - match cow_read_text(ctx, &abs)? { - Some(s) => Ok(Some(Value::Text(s))), - None => Ok(None), - } -} diff --git a/src/host/secrets.rs b/src/host/secrets.rs deleted file mode 100755 index e02229a..0000000 --- a/src/host/secrets.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! Cryptographic token helpers for Mid M3 (`lib/secrets`). - -use crate::value::Value; - -fn nbytes(n: Option<&Value>) -> Result { - match n { - None | Some(Value::None) => Ok(16), - Some(Value::Int(i)) => { - if *i <= 0 { - return Err("n must be positive".into()); - } - if *i > 1024 { - return Err("n too large (max 1024)".into()); - } - Ok(*i as usize) - } - Some(_) => Err("n needs int".into()), - } -} - -fn fill_random(buf: &mut [u8]) -> Result<(), String> { - getrandom::getrandom(buf).map_err(|e| format!("secrets: getrandom failed: {e}")) -} - -pub fn token_hex(n: Option<&Value>) -> Result { - let len = nbytes(n)?; - let mut buf = vec![0u8; len]; - fill_random(&mut buf)?; - Ok(Value::Text( - buf.iter().map(|b| format!("{b:02x}")).collect(), - )) -} - -const URLSAFE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - -pub fn token_urlsafe(n: Option<&Value>) -> Result { - let len = nbytes(n)?; - let mut buf = vec![0u8; len]; - fill_random(&mut buf)?; - // URL-safe Base64 without padding. - let mut out = String::with_capacity((len + 2) / 3 * 4); - let mut i = 0; - while i + 3 <= buf.len() { - let n = ((buf[i] as u32) << 16) | ((buf[i + 1] as u32) << 8) | (buf[i + 2] as u32); - out.push(URLSAFE[((n >> 18) & 63) as usize] as char); - out.push(URLSAFE[((n >> 12) & 63) as usize] as char); - out.push(URLSAFE[((n >> 6) & 63) as usize] as char); - out.push(URLSAFE[(n & 63) as usize] as char); - i += 3; - } - let rem = buf.len() - i; - if rem == 1 { - let n = (buf[i] as u32) << 16; - out.push(URLSAFE[((n >> 18) & 63) as usize] as char); - out.push(URLSAFE[((n >> 12) & 63) as usize] as char); - } else if rem == 2 { - let n = ((buf[i] as u32) << 16) | ((buf[i + 1] as u32) << 8); - out.push(URLSAFE[((n >> 18) & 63) as usize] as char); - out.push(URLSAFE[((n >> 12) & 63) as usize] as char); - out.push(URLSAFE[((n >> 6) & 63) as usize] as char); - } - Ok(Value::Text(out)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn token_hex_len() { - let v = token_hex(Some(&Value::Int(8))).unwrap(); - match v { - Value::Text(s) => assert_eq!(s.len(), 16), - _ => panic!("expected text"), - } - } -} diff --git a/src/host/stats.rs b/src/host/stats.rs deleted file mode 100755 index e8bf261..0000000 --- a/src/host/stats.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! Thin statistics for Mid2 M10 (`lib/stats`). Not a dataframe library. - -use crate::value::Value; - -fn as_nums(list: &Value) -> Result, String> { - let Value::List(xs) = list else { - return Err("stats: list of numbers required".into()); - }; - let mut out = Vec::with_capacity(xs.len()); - for (i, x) in xs.iter().enumerate() { - match x { - Value::Int(n) => out.push(*n as f64), - Value::Num(n) => out.push(*n), - _ => return Err(format!("stats: item {i} must be number")), - } - } - Ok(out) -} - -fn num_val(n: f64) -> Value { - if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) { - Value::Int(n as i64) - } else { - Value::Num(n) - } -} - -pub fn mean(list: &Value) -> Result { - let xs = as_nums(list)?; - if xs.is_empty() { - return Err("stats.mean: empty list".into()); - } - let sum: f64 = xs.iter().sum(); - Ok(Value::Num(sum / xs.len() as f64)) -} - -pub fn median(list: &Value) -> Result { - let mut xs = as_nums(list)?; - if xs.is_empty() { - return Err("stats.median: empty list".into()); - } - xs.sort_by(|a, b| a.partial_cmp(b).unwrap()); - let n = xs.len(); - let m = if n % 2 == 1 { - xs[n / 2] - } else { - (xs[n / 2 - 1] + xs[n / 2]) / 2.0 - }; - Ok(num_val(m)) -} - -/// Sample standard deviation (n >= 2), matching common `stdev` semantics. -pub fn stdev(list: &Value) -> Result { - let xs = as_nums(list)?; - if xs.len() < 2 { - return Err("stats.stdev: need at least 2 values".into()); - } - let n = xs.len() as f64; - let mean = xs.iter().sum::() / n; - let var = xs.iter().map(|x| { - let d = x - mean; - d * d - }).sum::() - / (n - 1.0); - Ok(Value::Num(var.sqrt())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn basic() { - let xs = Value::List(vec![ - Value::Int(1), - Value::Int(2), - Value::Int(3), - Value::Int(4), - ]); - let m = mean(&xs).unwrap(); - assert_eq!(m, Value::Num(2.5)); - assert_eq!(median(&xs).unwrap(), Value::Num(2.5)); - let s = stdev(&xs).unwrap(); - let Value::Num(v) = s else { panic!() }; - assert!((v - 1.2909944487358056).abs() < 1e-9); - } -} diff --git a/src/host/subtask.rs b/src/host/subtask.rs deleted file mode 100755 index 0dea516..0000000 --- a/src/host/subtask.rs +++ /dev/null @@ -1,824 +0,0 @@ -//! Concurrent subtasks: OS file children, in-process functions, foreign subprocesses. -//! Parent `HostContext` drop kills/waits file & foreign children; function threads detach. -//! -//! Quiet file children get `MARQDO_EVENT_FORWARD` so LLM stream events published in the -//! child process are tailed into the parent EventBus while `wait` blocks (view SSE). - -use crate::host::as_text; -use std::collections::HashMap; -use std::io::{Read, Seek, SeekFrom}; -use std::path::PathBuf; -use std::process::{Child, Command, Stdio}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; -use std::thread::{self, JoinHandle}; -use std::time::Duration; - -/// Cap for file-child stdout/stderr returned on `wait` (parent observation). -const FILE_IO_CAP: usize = 8 * 1024; - -use crate::host::foreign; -use crate::host::HostContext; -use crate::interp::Interpreter; -use crate::load::load_module; -use crate::value::{CodeBlock, Value}; - -/// Stored subtask handle (tagged by spawn kind). -pub(crate) enum Handle { - File(FileTask), - Foreign(ForeignTask), - Function(FunctionTask), -} - -impl std::fmt::Debug for Handle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Handle::File(_) => f.write_str("Subtask::File"), - Handle::Foreign(_) => f.write_str("Subtask::Foreign"), - Handle::Function(_) => f.write_str("Subtask::Function"), - } - } -} - -pub(crate) struct FileTask { - child: Child, - result_path: PathBuf, - /// NDJSON path the child appends EventBus frames to (`MARQDO_EVENT_FORWARD`). - events_path: Option, - /// Stops the parent-side tailer that republishes child events. - forward_stop: Option>, - forward: Option>, - /// Present when `quiet=True` (piped capture). Absent when inheriting TTY. - stdout: Option>, - stderr: Option>, -} - -fn stop_event_forward(task: &mut FileTask) { - if let Some(stop) = task.forward_stop.take() { - stop.store(true, Ordering::SeqCst); - } - if let Some(h) = task.forward.take() { - let _ = h.join(); - } - if let Some(p) = task.events_path.take() { - let _ = std::fs::remove_file(p); - } -} - -/// Tail `MARQDO_EVENT_FORWARD` NDJSON and republish onto the parent bus with `source=child`. -fn spawn_event_forwarder(path: PathBuf, stop: Arc) -> JoinHandle<()> { - thread::spawn(move || { - let mut pos: u64 = 0; - let mut carry = String::new(); - loop { - let done = stop.load(Ordering::SeqCst); - if let Ok(mut f) = std::fs::File::open(&path) { - if f.seek(SeekFrom::Start(pos)).is_ok() { - let mut buf = String::new(); - if f.read_to_string(&mut buf).is_ok() && !buf.is_empty() { - pos += buf.len() as u64; - carry.push_str(&buf); - while let Some(idx) = carry.find('\n') { - let line = carry[..idx].trim().to_string(); - carry.drain(..=idx); - if line.is_empty() { - continue; - } - republish_child_event(&line); - } - } - } - } - if done { - if !carry.is_empty() { - let line = carry.trim(); - if !line.is_empty() { - republish_child_event(line); - } - carry.clear(); - } - break; - } - thread::sleep(Duration::from_millis(16)); - } - }) -} - -fn republish_child_event(line: &str) { - let Ok(mut v) = serde_json::from_str::(line) else { - return; - }; - // Skip nested terminal frames — parent owns run lifecycle. - if v.get("type").and_then(|t| t.as_str()) == Some("done") && v.get("run_id").is_none() { - return; - } - if let Some(obj) = v.as_object_mut() { - obj.insert("source".into(), serde_json::json!("child")); - } - crate::host::event_bus::EventBus::global().publish_json(&v.to_string()); -} - -pub(crate) struct ForeignTask { - child: Child, - temp_script: PathBuf, - stdout: JoinHandle<(String, bool)>, - stderr: JoinHandle<(String, bool)>, -} - -enum FnState { - Running, - Done(Value), - Failed(String), - Killed, -} - -pub(crate) struct FunctionTask { - state: Arc>, - handle: Option>, -} - - -fn as_code(v: &Value) -> Result<&CodeBlock, String> { - match v { - Value::Code(c) => Ok(c), - _ => Err("code must be a bound ```lang fence value".into()), - } -} - -fn opt_text(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(None), - Some(v) => Ok(Some(as_text(v, "value")?)), - } -} - -fn is_set(v: Option<&Value>) -> bool { - match v { - None => false, - Some(Value::None) => false, - Some(Value::Text(s)) if s.is_empty() => false, - Some(_) => true, - } -} - -fn child_id(id: &Value) -> Result { - match id { - Value::Int(n) if *n > 0 => Ok(*n as u64), - _ => Err("subtask id must be positive int".into()), - } -} - -fn next_id(ctx: &mut HostContext) -> u64 { - ctx.subtask_seq = ctx.subtask_seq.wrapping_add(1); - ctx.subtask_seq -} - -fn status_map(status: &str, extra: Vec<(String, Value)>) -> Value { - let mut pairs = vec![("status".into(), Value::Text(status.into()))]; - pairs.extend(extra); - Value::Map(pairs) -} - -fn fn_args_from_value(args: Option<&Value>) -> Result, String> { - let Some(args) = args else { - return Ok(Vec::new()); - }; - match args { - Value::None => Ok(Vec::new()), - Value::Map(pairs) => Ok(pairs.clone()), - Value::List(items) => { - let mut out = Vec::new(); - for (i, item) in items.iter().enumerate() { - out.push((format!("arg{i}"), item.clone())); - } - Ok(out) - } - other => Err(format!( - "fn args must be map or list, got {}", - other.as_display() - )), - } -} - -pub fn kill_all(ctx: &mut HostContext) { - for (_, handle) in ctx.subtasks.drain() { - match handle { - Handle::File(mut task) => { - let _ = task.child.kill(); - let _ = task.child.wait(); - stop_event_forward(&mut task); - if let Some(h) = task.stdout.take() { - let _ = h.join(); - } - if let Some(h) = task.stderr.take() { - let _ = h.join(); - } - let _ = std::fs::remove_file(&task.result_path); - } - Handle::Foreign(mut task) => { - let _ = task.child.kill(); - let _ = task.child.wait(); - let _ = std::fs::remove_file(&task.temp_script); - let _ = task.stdout.join(); - let _ = task.stderr.join(); - } - Handle::Function(mut task) => { - // Join so fire-and-forget writers (e.g. agent writeback) finish before exit. - if let Some(h) = task.handle.take() { - let _ = h.join(); - } - } - } - } -} - -pub fn spawn(ctx: &mut HostContext, bound: &HashMap) -> Result { - let has_path = is_set(bound.get("path")); - let has_fn = is_set(bound.get("fn")); - let has_code = is_set(bound.get("code")); - let has_lang = is_set(bound.get("lang")) && is_set(bound.get("source")); - let kinds = [has_path, has_fn, has_code, has_lang] - .into_iter() - .filter(|b| *b) - .count(); - if kinds != 1 { - return Err( - "spawn: specify exactly one of path=, fn=, code=, or lang=+source=".into(), - ); - } - if has_path { - spawn_file( - ctx, - require(bound, "path")?, - bound.get("args"), - bound.get("quiet"), - ) - } else if has_fn { - spawn_fn(ctx, require(bound, "fn")?, bound.get("args")) - } else if has_code { - spawn_code(ctx, require(bound, "code")?, bound.get("stdin")) - } else { - spawn_lang( - ctx, - require(bound, "lang")?, - require(bound, "source")?, - bound.get("stdin"), - ) - } -} - -fn spawn_file( - ctx: &mut HostContext, - path: &Value, - args: Option<&Value>, - quiet: Option<&Value>, -) -> Result { - if !ctx.caps.exec { - return Err("subtask spawn disabled (exec capability off)".into()); - } - let rel = as_text(path, "path")?; - let joined = if std::path::Path::new(rel).is_absolute() { - std::path::PathBuf::from(rel) - } else { - ctx.cwd.join(rel) - }; - // Absolutize so the child `for_run` cwd/parent resolution does not double-prefix - // a relative path like `tests/ext/.marqdo/...` when current_dir is already `tests/ext`. - let file = std::fs::canonicalize(&joined).unwrap_or_else(|_| { - if joined.is_absolute() { - joined.clone() - } else { - std::env::current_dir() - .unwrap_or_else(|_| std::path::PathBuf::from(".")) - .join(&joined) - } - }); - let exe = std::env::current_exe().map_err(|e| format!("subtask: current_exe: {e}"))?; - let id = next_id(ctx); - let result_path = std::env::temp_dir().join(format!( - "marqdo-subtask-{}-{}.json", - std::process::id(), - id - )); - let mut cmd = Command::new(&exe); - cmd.arg("run").arg(&file); - if !ctx.caps.fs_write { cmd.arg("--deny-fs-write"); } - if !ctx.caps.exec { cmd.arg("--deny-exec"); } - if !ctx.caps.net { cmd.arg("--deny-net"); } - if !ctx.caps.plugin { cmd.arg("--deny-plugin"); } - if let Some(root) = &ctx.fs_root { cmd.arg("--fs-root").arg(root); } - cmd.arg("--emit-result").arg(&result_path); - cmd.current_dir(&ctx.cwd); - cmd.stdin(Stdio::null()); - let quiet = match quiet { - None | Some(Value::None) => true, - Some(v) => v.truthy(), - }; - // quiet: pipe-capture for parent observation (no TTY noise). - // !quiet: inherit parent TTY; wait map omits stdout/stderr bodies. - if quiet { - cmd.stdout(Stdio::piped()); - cmd.stderr(Stdio::piped()); - } else { - cmd.stdout(Stdio::inherit()); - cmd.stderr(Stdio::inherit()); - } - if let Some(Value::List(items)) = args { - for item in items { - cmd.arg(as_text(item, "arg")?); - } - } - // Bridge child EventBus → parent while wait blocks (view SSE / concurrent progress). - let events_path = std::env::temp_dir().join(format!( - "marqdo-events-{}-{}.ndjson", - std::process::id(), - id - )); - let _ = std::fs::write(&events_path, ""); - cmd.env("MARQDO_EVENT_FORWARD", &events_path); - apply_run_selection_env(&mut cmd); - - let mut child = cmd - .spawn() - .map_err(|e| format!("subtask spawn {}: {e}", file.display()))?; - let (stdout, stderr) = if quiet { - let mut stdout_pipe = child.stdout.take(); - let mut stderr_pipe = child.stderr.take(); - let stdout = thread::spawn(move || { - stdout_pipe.as_mut().map(capture_file_io).unwrap_or_default() - }); - let stderr = thread::spawn(move || { - stderr_pipe.as_mut().map(capture_file_io).unwrap_or_default() - }); - (Some(stdout), Some(stderr)) - } else { - (None, None) - }; - let forward_stop = Arc::new(AtomicBool::new(false)); - let forward = spawn_event_forwarder(events_path.clone(), Arc::clone(&forward_stop)); - ctx.subtasks.insert( - id, - Handle::File(FileTask { - child, - result_path, - events_path: Some(events_path), - forward_stop: Some(forward_stop), - forward: Some(forward), - stdout, - stderr, - }), - ); - Ok(Value::Int(id as i64)) -} - -fn spawn_fn( - ctx: &mut HostContext, - name: &Value, - args: Option<&Value>, -) -> Result { - let name = as_text(name, "fn")?.to_string(); - let call_args = fn_args_from_value(args)?; - let module_path = ctx - .entry_path - .clone() - .ok_or_else(|| "subtask fn: no entry module (run a .mq.md file first)".to_string())?; - let cwd = ctx.cwd.clone(); - let caps = ctx.caps.clone(); - let foreign_cmds = ctx.foreign_cmds.clone(); - let foreign_specs = ctx.foreign_specs.clone(); - let foreign_config_specs = ctx.foreign_config_specs.clone(); - let foreign_config_loaded = ctx.foreign_config_loaded; - let fs_root = ctx.fs_root.clone(); - let argv = ctx.argv.clone(); - - let state = Arc::new(Mutex::new(FnState::Running)); - let state_bg = Arc::clone(&state); - let handle = thread::spawn(move || { - let result = (|| -> Result { - let module = load_module(&module_path).map_err(|e| e.to_string())?; - let source = std::fs::read_to_string(&module_path) - .map_err(|e| format!("subtask fn: read {}: {e}", module_path.display()))?; - let mut host = HostContext::for_capture(Some(&module_path), caps); - host.cwd = cwd; - host.fs_root = fs_root; - host.argv = argv; - host.foreign_cmds = foreign_cmds; - host.foreign_specs = foreign_specs; - host.foreign_config_specs = foreign_config_specs; - host.foreign_config_loaded = foreign_config_loaded; - host.set_entry_source(Some(&module_path), &source); - host.entry_metadata = module.metadata.clone(); - let mut interp = Interpreter::with_capture(Some(&module_path), false).with_host(host); - interp - .invoke_function(&module, &name, &call_args) - .map_err(|e| e.to_string()) - })(); - if let Ok(mut st) = state_bg.lock() { - if !matches!(*st, FnState::Killed) { - *st = match result { - Ok(v) => FnState::Done(v), - Err(e) => FnState::Failed(e), - }; - } - } - }); - - let id = next_id(ctx); - ctx.subtasks.insert( - id, - Handle::Function(FunctionTask { - state, - handle: Some(handle), - }), - ); - Ok(Value::Int(id as i64)) -} - -fn spawn_code( - ctx: &mut HostContext, - code: &Value, - stdin: Option<&Value>, -) -> Result { - if !ctx.caps.exec { - return Err("subtask spawn disabled (exec capability off)".into()); - } - let block = as_code(code)?; - let stdin = opt_text(stdin)?; - spawn_foreign(ctx, &block.lang, &block.source, stdin) -} - -fn spawn_lang( - ctx: &mut HostContext, - lang: &Value, - source: &Value, - stdin: Option<&Value>, -) -> Result { - if !ctx.caps.exec { - return Err("subtask spawn disabled (exec capability off)".into()); - } - let lang = as_text(lang, "lang")?; - let source = as_text(source, "source")?; - let stdin = opt_text(stdin)?; - spawn_foreign(ctx, lang, source, stdin) -} - -fn spawn_foreign( - ctx: &mut HostContext, - lang: &str, - source: &str, - stdin: Option<&str>, -) -> Result { - let spawned = foreign::spawn_source(ctx, lang, source, stdin)?; - let id = next_id(ctx); - ctx.subtasks.insert( - id, - Handle::Foreign(ForeignTask { - child: spawned.child, - temp_script: spawned.script_path, - stdout: spawned.stdout, - stderr: spawned.stderr, - }), - ); - Ok(Value::Int(id as i64)) -} - -pub fn poll(ctx: &mut HostContext, id: &Value) -> Result { - let id = child_id(id)?; - let handle = ctx - .subtasks - .get_mut(&id) - .ok_or_else(|| format!("subtask: unknown id {id}"))?; - match handle { - Handle::File(task) => poll_child(&mut task.child), - Handle::Foreign(task) => poll_child(&mut task.child), - Handle::Function(task) => poll_function(&task.state), - } -} - -fn poll_child(child: &mut Child) -> Result { - match child.try_wait().map_err(|e| format!("subtask poll: {e}"))? { - None => Ok(status_map("running", vec![])), - Some(status) => { - let code = status.code().unwrap_or(-1); - let st = if status.success() { "done" } else { "failed" }; - Ok(status_map( - st, - vec![("code".into(), Value::Int(code as i64))], - )) - } - } -} - -fn poll_function(state: &Arc>) -> Result { - let st = state - .lock() - .map_err(|_| "subtask fn: lock poisoned".to_string())?; - match &*st { - FnState::Running => Ok(status_map("running", vec![])), - FnState::Done(v) => Ok(status_map( - "done", - vec![("value".into(), v.clone())], - )), - FnState::Failed(e) => Ok(status_map( - "failed", - vec![("error".into(), Value::Text(e.clone()))], - )), - FnState::Killed => Ok(status_map("failed", vec![("error".into(), Value::Text("killed".into()))])), - } -} - -pub fn join(ctx: &mut HostContext, id: &Value) -> Result { - let id = child_id(id)?; - let handle = ctx - .subtasks - .remove(&id) - .ok_or_else(|| format!("subtask: unknown id {id}"))?; - match handle { - Handle::File(mut task) => { - // Forwarder runs concurrently while we block on the OS child. - let status = task - .child - .wait() - .map_err(|e| format!("subtask join: {e}"))?; - stop_event_forward(&mut task); - let code = status.code().unwrap_or(-1) as i64; - let value = read_emitted_result(&task.result_path); - let _ = std::fs::remove_file(&task.result_path); - let stdout = task - .stdout - .take() - .map(|h| h.join().unwrap_or_default()) - .unwrap_or_default(); - let stderr = task - .stderr - .take() - .map(|h| h.join().unwrap_or_default()) - .unwrap_or_default(); - let mut pairs = vec![ - ("code".into(), Value::Int(code)), - ("value".into(), value), - ]; - if !stdout.is_empty() { - pairs.push(("stdout".into(), Value::Text(clip_io(&stdout)))); - } - if !stderr.is_empty() { - pairs.push(("stderr".into(), Value::Text(clip_io(&stderr)))); - } - Ok(Value::Map(pairs)) - } - Handle::Foreign(task) => join_foreign(task), - Handle::Function(task) => join_function(task), - } -} - -fn read_emitted_result(path: &PathBuf) -> Value { - match std::fs::read_to_string(path) { - Ok(text) => match serde_json::from_str::(text.trim()) { - Ok(j) => crate::host::json::json_to_value(&j).unwrap_or(Value::None), - Err(_) => Value::None, - }, - Err(_) => Value::None, - } -} - -fn join_foreign(mut task: ForeignTask) -> Result { - let status = task - .child - .wait() - .map_err(|e| format!("subtask foreign join: {e}"))?; - let (stdout, out_trunc) = task.stdout.join().unwrap_or_default(); - let (stderr, err_trunc) = task.stderr.join().unwrap_or_default(); - let _ = std::fs::remove_file(&task.temp_script); - if !status.success() { - let code = status.code().unwrap_or(1); - let mut msg = format!("subtask foreign failed (exit={code})"); - if !stderr.trim().is_empty() { - msg.push_str(": "); - msg.push_str(stderr.trim()); - } - return Err(msg); - } - let mut out = stdout; - if out.ends_with('\n') { - out.pop(); - if out.ends_with('\r') { - out.pop(); - } - } - if out_trunc || err_trunc { - out.push_str("\n…(truncated)"); - } - Ok(Value::Text(out)) -} - -fn join_function(mut task: FunctionTask) -> Result { - if let Some(handle) = task.handle.take() { - let _ = handle.join(); - } - let st = task - .state - .lock() - .map_err(|_| "subtask fn: lock poisoned".to_string())?; - match &*st { - FnState::Done(v) => Ok(v.clone()), - FnState::Failed(e) => Err(e.clone()), - FnState::Killed => Err("subtask fn killed".into()), - FnState::Running => Err("subtask fn still running".into()), - } -} - -pub fn kill(ctx: &mut HostContext, id: &Value) -> Result { - let id = child_id(id)?; - let handle = ctx - .subtasks - .remove(&id) - .ok_or_else(|| format!("subtask: unknown id {id}"))?; - match handle { - Handle::File(mut task) => { - task.child - .kill() - .map_err(|e| format!("subtask kill: {e}"))?; - let _ = task.child.wait(); - stop_event_forward(&mut task); - if let Some(h) = task.stdout.take() { - let _ = h.join(); - } - if let Some(h) = task.stderr.take() { - let _ = h.join(); - } - let _ = std::fs::remove_file(&task.result_path); - } - Handle::Foreign(mut task) => { - task.child.kill().map_err(|e| format!("subtask kill: {e}"))?; - let _ = task.child.wait(); - let _ = std::fs::remove_file(&task.temp_script); - let _ = task.stdout.join(); - let _ = task.stderr.join(); - } - Handle::Function(mut task) => { - if let Ok(mut st) = task.state.lock() { - if matches!(*st, FnState::Running) { - *st = FnState::Killed; - } - } - drop(task.handle.take()); - } - } - Ok(Value::None) -} - -pub fn wait_all(ctx: &mut HostContext) -> Result { - let ids: Vec = ctx.subtasks.keys().copied().collect(); - let mut results = Vec::new(); - for id in ids { - results.push(join(ctx, &Value::Int(id as i64))?); - } - Ok(Value::List(results)) -} - -fn capture_file_io(reader:&mut impl Read)->String { - let mut kept=Vec::new(); let mut buffer=[0u8;8192]; - loop { match reader.read(&mut buffer) { - Ok(0)|Err(_)=>break, - Ok(n)=>{ let take=(FILE_IO_CAP+4-kept.len()).min(n);kept.extend_from_slice(&buffer[..take]); } - }} - clip_io(&String::from_utf8_lossy(&kept)) -} - -/// Timeout leaves the handle available unless cancel=True. Process cancellation -/// reaps the OS child; function-thread cancellation is logical, as in kill(). -pub(super) fn wait_timeout(ctx:&mut HostContext,id:&Value,timeout_ms:u64,cancel:bool)->Result{ - let start=std::time::Instant::now(); - loop{ - let status=poll(ctx,id)?; - let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into()))); - if !running{return join(ctx,id)} - if start.elapsed()>=Duration::from_millis(timeout_ms){if cancel{kill(ctx,id)?;}return Err("timed_out: subtask wait deadline exceeded".into())} - thread::sleep(Duration::from_millis(5)); - } -} -pub(super) fn run_many(ctx:&mut HostContext,tasks:&Value,limit:usize,timeout_ms:u64)->Result{ - let Value::List(tasks)=tasks else{return Err("tasks must be record list".into())}; - if !(1..=64).contains(&limit){return Err("limit must be 1..64".into())} - if tasks.len()>10000{return Err("batch exceeds 10000 tasks".into())} - // Validate the entire batch before starting any process. - let jobs=tasks.iter().map(|task|{let Value::Map(fields)=task else{return Err("task must contain path and optional args".to_string())}; - let mut job=HashMap::new();for (key,value) in fields{if !matches!(key.as_str(),"path"|"args"){return Err(format!("unsupported batch field {key}"))}job.insert(key.clone(),value.clone());} - let path=job.get("path").ok_or("task missing path")?;ctx.resolve_path(as_text(path,"path")?)?;Ok(job) - }).collect::,String>>()?; - let mut active:Vec<(usize,Value,std::time::Instant)>=Vec::new();let mut next=0;let mut out=vec![Value::None;jobs.len()]; - while nextactive.push((next,id,std::time::Instant::now())),Err(error)=>out[next]=super::result::capture("subtask.run_many",Err(error))};next+=1; - } - let mut i=0; - while i=Duration::from_millis(timeout_ms){let(index,id,_)=active.remove(i);let _=kill(ctx,&id);out[index]=super::result::capture("subtask.run_many",Err("timed_out: batch task deadline exceeded".into()));} - else{i+=1;} - } - if !active.is_empty(){thread::sleep(Duration::from_millis(5));} - } - Ok(Value::List(out)) -} - -fn clip_io(s: &str) -> String { - let mut it = s.chars(); - let head: String = it.by_ref().take(FILE_IO_CAP).collect(); - if it.next().is_some() { - format!("{head}\n…(truncated)") - } else { - head - } -} - -fn require<'a>(bound: &'a HashMap, key: &str) -> Result<&'a Value, String> { - bound - .get(key) - .ok_or_else(|| format!("host call missing `{key}`")) -} - -/// Propagate run/selection identity onto the *child* Command.env map. -/// Reads parent env only as a fallback when an explicit RunContext was not -/// applied; never uses parent `setenv`/`set_current_dir` as request state (M-R1). -fn apply_run_selection_env(cmd: &mut Command) { - for key in [ - "MARQDO_RUN_ID", - "MARQDO_PARENT_RUN_ID", - "MARQDO_TURN_ID", - "MARQDO_WORKSPACE_SCOPE", - "MARQDO_CANCEL_TOKEN", - "MARQDO_EVENT_FORWARD", - "MARQDO_USAGE_SINK", - "MARQDO_CREDENTIAL_REF", - "MARQDO_WORKSPACE_ID", - "MARQDO_SNAPSHOT_ID", - "MARQDO_LEASE_ID", - "MARQDO_ATTEMPT_ID", - "MARQDO_LLM_MODEL", - "MARQDO_LLM_BASE_URL", - "OPENAI_MODEL", - "OPENAI_BASE_URL", - ] { - if let Ok(v) = std::env::var(key) { - cmd.env(key, v); - } - } - // Do not forward process-global MARQDO_CANCEL into children — request cancel - // must use MARQDO_CANCEL_TOKEN so leases stay isolated. -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - use std::process::Command; - - #[test] - fn f02_apply_run_selection_env_forwards_parent_identity() { - std::env::set_var("MARQDO_RUN_ID", "run-parent"); - std::env::set_var("OPENAI_MODEL", "child-model"); - std::env::set_var("OPENAI_BASE_URL", "http://127.0.0.1:7010"); - // Must never require writing secrets into child env map for selection. - std::env::remove_var("OPENAI_API_KEY"); - - let mut cmd = Command::new("true"); - apply_run_selection_env(&mut cmd); - // Command doesn't expose env for inspection portably; re-check via helper contract: - let keys: HashMap<&str, String> = [ - "MARQDO_RUN_ID", - "OPENAI_MODEL", - "OPENAI_BASE_URL", - ] - .into_iter() - .filter_map(|k| std::env::var(k).ok().map(|v| (k, v))) - .collect(); - assert_eq!(keys.get("MARQDO_RUN_ID").map(String::as_str), Some("run-parent")); - assert_eq!(keys.get("OPENAI_MODEL").map(String::as_str), Some("child-model")); - assert_eq!( - keys.get("OPENAI_BASE_URL").map(String::as_str), - Some("http://127.0.0.1:7010") - ); - - std::env::remove_var("MARQDO_RUN_ID"); - std::env::remove_var("OPENAI_MODEL"); - std::env::remove_var("OPENAI_BASE_URL"); - let _ = cmd; // ensure apply didn't panic - } - - #[test] - fn f02_agent_skeleton_has_no_llm_llm() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let agent = std::fs::read_to_string(root.join("ext/ai/agent.mq.md")).unwrap(); - assert!( - !agent.contains("llm.llm"), - "render_workbook_skeleton must not hardcode llm.llm" - ); - assert!( - agent.contains("llm.create") && agent.contains("OPENAI_MODEL"), - "skeleton should create model from env selection" - ); - } -} diff --git a/src/host/subtask_stub.rs b/src/host/subtask_stub.rs deleted file mode 100755 index 0a9a7a1..0000000 --- a/src/host/subtask_stub.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! Stub subtask surface when `exec-host` is disabled (browser wasm). - -use crate::host::HostContext; - -/// Placeholder handle type so `HostContext.subtasks` still type-checks. -#[derive(Debug)] -pub(crate) struct Handle; - -pub fn kill_all(_ctx: &mut HostContext) {} diff --git a/src/host/sys.rs b/src/host/sys.rs deleted file mode 100755 index 16ac2fc..0000000 --- a/src/host/sys.rs +++ /dev/null @@ -1,239 +0,0 @@ -//! System / process host primitives. - -use crate::host::as_text; -#[cfg(feature = "exec-host")] -use std::process::Command; - -use crate::host::HostContext; -use crate::value::Value; - - -fn as_i64(v: &Value, label: &str) -> Result { - match v { - Value::Int(n) => Ok(*n), - _ => Err(format!("{label} must be int")), - } -} - -pub fn env_get(name: &Value) -> Result { - let key = as_text(name, "name")?; - Ok(match std::env::var(key) { - Ok(v) => Value::Text(v), - Err(_) => Value::None, - }) -} - -pub fn env_set(name: &Value, value: &Value) -> Result { - let key = as_text(name, "name")?; - let val = as_text(value, "value")?; - std::env::set_var(key, val); - Ok(Value::None) -} - -/// Load KEY=VALUE pairs from a `.env` file into the process environment. -/// Existing variables are **not** overridden. Default path: `.env` under host cwd. -pub fn dotenv_load(ctx: &HostContext, path: Option<&Value>) -> Result { - let rel = match path { - None | Some(Value::None) => ".env".to_string(), - Some(v) => as_text(v, "path")?.to_string(), - }; - let file = if std::path::Path::new(&rel).is_absolute() { - std::path::PathBuf::from(&rel) - } else { - ctx.cwd.join(&rel) - }; - let text = match std::fs::read_to_string(&file) { - Ok(t) => t, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Value::Int(0)), - Err(e) => { - return Err(format!("dotenv_load {}: {e}", file.display())); - } - }; - let mut loaded = 0i64; - for raw in text.lines() { - let line = raw.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - let line = line.strip_prefix("export ").unwrap_or(line).trim(); - let Some((k, v)) = line.split_once('=') else { - continue; - }; - let key = k.trim(); - if key.is_empty() { - continue; - } - if std::env::var_os(key).is_some() { - continue; - } - let mut val = v.trim(); - if (val.starts_with('"') && val.ends_with('"')) - || (val.starts_with('\'') && val.ends_with('\'')) - { - val = &val[1..val.len() - 1]; - } - std::env::set_var(key, val); - loaded += 1; - } - Ok(Value::Int(loaded)) -} - -pub fn args(ctx: &HostContext) -> Result { - Ok(Value::List( - ctx.argv.iter().map(|s| Value::Text(s.clone())).collect(), - )) -} - -pub fn cwd(ctx: &HostContext) -> Result { - Ok(Value::Text(ctx.cwd.display().to_string())) -} - -/// Bound entry Artifact Metadata (map). -pub fn meta(ctx: &HostContext) -> Result { - Ok(Value::Map(ctx.entry_metadata.clone())) -} - -/// Lookup one metadata key; missing → None. -pub fn meta_get(ctx: &HostContext, key: &Value) -> Result { - let k = as_text(key, "key")?; - Ok(ctx - .entry_metadata - .iter() - .find(|(name, _)| name == k) - .map(|(_, v)| v.clone()) - .unwrap_or(Value::None)) -} - -/// Classify entry Artifact (`web` / `endpoint` / `prompt` / `other`); missing type → None. -pub fn artifact_kind(ctx: &HostContext) -> Result { - Ok(match crate::artifact::classify(&ctx.entry_metadata) { - None => Value::None, - Some(crate::artifact::ArtifactKind::Web) => Value::Text("web".into()), - Some(crate::artifact::ArtifactKind::Endpoint) => Value::Text("endpoint".into()), - Some(crate::artifact::ArtifactKind::Prompt) => Value::Text("prompt".into()), - Some(crate::artifact::ArtifactKind::Other) => Value::Text("other".into()), - }) -} - -pub fn exit(ctx: &HostContext, code: &Value) -> Result { - let c = as_i64(code, "code")?; - if ctx.soft_side_effects { - return Err(format!("exit {c} (soft mode does not terminate process)")); - } - #[cfg(target_arch = "wasm32")] - { - return Err(format!("exit {c} unavailable in browser wasm")); - } - #[cfg(not(target_arch = "wasm32"))] - { - std::process::exit(c as i32); - } -} - -pub fn exec( - ctx: &HostContext, - cmd: &Value, - args: Option<&Value>, - capture: Option<&Value>, -) -> Result { - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, cmd, args, capture); - return Err("exec unavailable in browser wasm".into()); - } - #[cfg(feature = "exec-host")] - { - use std::process::Stdio; - if !ctx.allow_exec() { - if ctx.sandbox_session.is_some() { - return Err("exec unavailable in sandbox".into()); - } - return Err("exec denied by host policy".into()); - } - let cmd = as_text(cmd, "cmd")?; - let capture = match capture { - None | Some(Value::None) => false, - Some(v) => crate::host::math::as_bool(v), - }; - let mut command = Command::new(cmd); - command.current_dir(&ctx.cwd); - match args { - None | Some(Value::None) => {} - Some(Value::List(xs)) => { - for x in xs { - command.arg(x.as_display()); - } - } - Some(Value::Text(s)) => { - command.arg(s); - } - Some(_) => return Err("exec args must be list or text".into()), - } - if capture { - command.stdout(Stdio::piped()); - command.stderr(Stdio::piped()); - let output = command - .output() - .map_err(|e| format!("exec `{cmd}`: {e}"))?; - let code = output.status.code().unwrap_or(1) as i64; - let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); - let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); - Ok(Value::Map(vec![ - ("code".into(), Value::Int(code)), - ("stdout".into(), Value::Text(clip_exec_io(&stdout))), - ("stderr".into(), Value::Text(clip_exec_io(&stderr))), - ])) - } else { - let status = command - .status() - .map_err(|e| format!("exec `{cmd}`: {e}"))?; - Ok(Value::Int(status.code().unwrap_or(1) as i64)) - } - } -} - -const EXEC_IO_CAP: usize = 256 * 1024; - -fn clip_exec_io(s: &str) -> String { - let mut it = s.chars(); - let head: String = it.by_ref().take(EXEC_IO_CAP).collect(); - if it.next().is_some() { - format!("{head}\n…(truncated)") - } else { - head - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::host::HostContext; - use std::io::Write; - - #[test] - fn dotenv_loads_without_override() { - let dir = std::env::temp_dir().join(format!("marqdo-dotenv-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("sample.env"); - { - let mut f = std::fs::File::create(&path).unwrap(); - writeln!(f, "# comment").unwrap(); - writeln!(f, "MARQDO_DOTENV_A=one").unwrap(); - writeln!(f, "export MARQDO_DOTENV_B=\"two\"").unwrap(); - } - std::env::set_var("MARQDO_DOTENV_A", "keep"); - std::env::remove_var("MARQDO_DOTENV_B"); - let mut ctx = HostContext::default(); - ctx.cwd = dir.clone(); - let n = dotenv_load(&ctx, Some(&Value::Text("sample.env".into()))).unwrap(); - assert_eq!(n, Value::Int(1)); - assert_eq!(std::env::var("MARQDO_DOTENV_A").unwrap(), "keep"); - assert_eq!(std::env::var("MARQDO_DOTENV_B").unwrap(), "two"); - assert_eq!( - dotenv_load(&ctx, Some(&Value::Text("missing.env".into()))).unwrap(), - Value::Int(0) - ); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/src/host/task_ops.rs b/src/host/task_ops.rs deleted file mode 100755 index b9cbe36..0000000 --- a/src/host/task_ops.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Bounded orchestration over existing subtask resources. -use crate::{ - host::{HostContext, HostFn}, - value::Value, -}; -use std::collections::HashMap; -#[cfg(feature = "exec-host")] -fn arg<'a>(b: &'a HashMap, k: &str) -> Result<&'a Value, String> { - b.get(k).ok_or_else(|| format!("missing {k}")) -} -pub(super) fn call( - ctx: &mut HostContext, - id: HostFn, - b: &HashMap, -) -> Result { - #[cfg(feature = "exec-host")] - { - fn integer(b: &HashMap, key: &str) -> Result { - match arg(b, key)? { - Value::Int(n) if *n >= 0 => Ok(*n as u64), - _ => Err(format!("{key} must be nonnegative integer")), - } - } - match id { - HostFn::SubtaskWaitTimeout => { - let answer = super::subtask::wait_timeout( - ctx, - arg(b, "id")?, - integer(b, "timeout_ms")?, - matches!(b.get("cancel"), Some(Value::Bool(true))), - ); - Ok(super::result::capture("subtask.wait_timeout", answer)) - } - HostFn::SubtaskCancelAll => { - let count = ctx.subtasks.len(); - super::subtask::kill_all(ctx); - Ok(Value::Int(count as i64)) - } - HostFn::SubtaskRunMany => super::subtask::run_many( - ctx, - arg(b, "tasks")?, - integer(b, "limit")? as usize, - integer(b, "timeout_ms")?, - ), - _ => Err("not a task operation".into()), - } - } - #[cfg(not(feature = "exec-host"))] - { - let _ = (ctx, id, b); - Err("subtask unavailable in this build".into()) - } -} diff --git a/src/host/text_ops.rs b/src/host/text_ops.rs deleted file mode 100755 index cc914ad..0000000 --- a/src/host/text_ops.rs +++ /dev/null @@ -1,148 +0,0 @@ -//! Text helpers for Mid M4 (`lib/text` thicken). - -use crate::host::as_text; -use crate::value::Value; - - -fn as_usize(v: &Value, label: &str) -> Result { - match v { - Value::Int(n) if *n >= 0 => Ok(*n as usize), - Value::Int(_) => Err(format!("{label} must be non-negative")), - _ => Err(format!("{label} needs int")), - } -} - -pub fn contains(text: &Value, sub: &Value) -> Result { - let t = as_text(text, "text")?; - let s = as_text(sub, "sub")?; - Ok(Value::Bool(t.contains(s))) -} - -pub fn starts_with(text: &Value, prefix: &Value) -> Result { - let t = as_text(text, "text")?; - let p = as_text(prefix, "prefix")?; - Ok(Value::Bool(t.starts_with(p))) -} - -pub fn ends_with(text: &Value, suffix: &Value) -> Result { - let t = as_text(text, "text")?; - let s = as_text(suffix, "suffix")?; - Ok(Value::Bool(t.ends_with(s))) -} - -pub fn replace( - text: &Value, - old: &Value, - new: &Value, - count: Option<&Value>, -) -> Result { - let t = as_text(text, "text")?; - let old = as_text(old, "old")?; - let new = as_text(new, "new")?; - if old.is_empty() { - return Err("replace: old must be non-empty".into()); - } - let limit = match count { - None | Some(Value::None) => None, - Some(v) => Some(as_usize(v, "count")?), - }; - let out = match limit { - None => t.replace(old, new), - Some(0) => t.to_string(), - Some(n) => { - let mut out = String::new(); - let mut rest = t; - let mut done = 0usize; - while done < n { - if let Some(i) = rest.find(old) { - out.push_str(&rest[..i]); - out.push_str(new); - rest = &rest[i + old.len()..]; - done += 1; - } else { - break; - } - } - out.push_str(rest); - out - } - }; - Ok(Value::Text(out)) -} - -pub fn to_upper(text: &Value) -> Result { - Ok(Value::Text(as_text(text, "text")?.to_uppercase())) -} - -pub fn to_lower(text: &Value) -> Result { - Ok(Value::Text(as_text(text, "text")?.to_lowercase())) -} - -pub fn repeat(text: &Value, n: &Value) -> Result { - let t = as_text(text, "text")?; - let n = as_usize(n, "n")?; - if n > 10_000 { - return Err("repeat: n too large".into()); - } - Ok(Value::Text(t.repeat(n))) -} - -pub fn pad( - text: &Value, - width: &Value, - fill: Option<&Value>, - align: Option<&Value>, -) -> Result { - let t = as_text(text, "text")?; - let width = as_usize(width, "width")?; - let fill = match fill { - None | Some(Value::None) => " ".to_string(), - Some(v) => as_text(v, "fill")?.to_string(), - }; - if fill.is_empty() { - return Err("pad: fill must be non-empty".into()); - } - let align = match align { - None | Some(Value::None) => "left", - Some(v) => as_text(v, "align")?, - }; - let chars: Vec = t.chars().collect(); - if chars.len() >= width { - return Ok(Value::Text(t.to_string())); - } - let pad_n = width - chars.len(); - let fill_chars: Vec = fill.chars().collect(); - let make_pad = |n: usize| { - let mut s = String::new(); - for i in 0..n { - s.push(fill_chars[i % fill_chars.len()]); - } - s - }; - let out = match align { - "right" => format!("{}{}", make_pad(pad_n), t), - "center" => { - let left = pad_n / 2; - format!("{}{}{}", make_pad(left), t, make_pad(pad_n - left)) - } - _ => format!("{}{}", t, make_pad(pad_n)), - }; - Ok(Value::Text(out)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn case_and_contains() { - assert_eq!( - contains(&Value::Text("Hello".into()), &Value::Text("ell".into())).unwrap(), - Value::Bool(true) - ); - assert_eq!( - to_upper(&Value::Text("ß".into())).unwrap(), - Value::Text("SS".into()) - ); - } -} diff --git a/src/host/time.rs b/src/host/time.rs deleted file mode 100755 index 3174a22..0000000 --- a/src/host/time.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Time host primitives. - -use crate::host::as_text; -use std::time::Duration; -#[cfg(not(target_arch = "wasm32"))] -use std::time::{SystemTime, UNIX_EPOCH}; - -use chrono::{DateTime, NaiveDateTime, Utc}; - -use crate::host::HostContext; -use crate::value::Value; - -pub fn now_unix() -> Result { - #[cfg(target_arch = "wasm32")] - { - // No wall clock on wasm32-unknown-unknown without JS bridge (C4). - return Err("now_unix unavailable in browser wasm (no clock bridge yet)".into()); - } - #[cfg(not(target_arch = "wasm32"))] - { - let secs = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|e| format!("now_unix: {e}"))? - .as_secs(); - Ok(Value::Int(secs as i64)) - } -} - -pub fn now_ms() -> Result { - #[cfg(target_arch = "wasm32")] - { - return Err("now_ms unavailable in browser wasm (no clock bridge yet)".into()); - } - #[cfg(not(target_arch = "wasm32"))] - { - let ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|e| format!("now_ms: {e}"))? - .as_millis(); - Ok(Value::Int(ms as i64)) - } -} - -fn as_i64(v: &Value, label: &str) -> Result { - match v { - Value::Int(n) => Ok(*n), - _ => Err(format!("{label} must be int")), - } -} - - -pub fn format_time(unix: &Value, pattern: &Value) -> Result { - let secs = as_i64(unix, "unix")?; - let pat = as_text(pattern, "pattern")?; - let dt = DateTime::::from_timestamp(secs, 0) - .ok_or_else(|| format!("invalid unix timestamp: {secs}"))?; - Ok(Value::Text(dt.format(pat).to_string())) -} - -pub fn parse_time(text: &Value, pattern: &Value) -> Result { - let t = as_text(text, "text")?; - let pat = as_text(pattern, "pattern")?; - let dt = NaiveDateTime::parse_from_str(t, pat).map_err(|e| format!("parse_time: {e}"))?; - Ok(Value::Int(dt.and_utc().timestamp())) -} - -pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result { - let n = as_i64(ms, "ms")?; - if n < 0 { - return Err("sleep_ms must be >= 0".into()); - } - let n = n as u64; - if let Some(lim) = ctx.sleep_limit_ms { - if n > lim { - return Err(format!("sleep_ms {n} exceeds limit {lim}")); - } - } - if n > 0 { - #[cfg(not(target_arch = "wasm32"))] - { - std::thread::sleep(Duration::from_millis(n)); - } - #[cfg(target_arch = "wasm32")] - { - let _ = Duration::from_millis(n); - // Browser wasm has no blocking sleep; ignore (C0/C1). - } - } - Ok(Value::None) -} diff --git a/src/host/toml_ops.rs b/src/host/toml_ops.rs deleted file mode 100755 index 75d0887..0000000 --- a/src/host/toml_ops.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Standards-based TOML; datetime scalars become explicit ISO text at Value boundary. -use crate::{host::as_text,value::Value}; - -pub fn parse(text: &Value) -> Result { - let parsed: toml::Value = toml::from_str(as_text(text,"text")?).map_err(|e|format!("toml.parse: {e}"))?; - fn convert(v: toml::Value) -> Result { - Ok(match v { - toml::Value::String(s) => Value::Text(s), - toml::Value::Integer(n) => Value::Int(n), - toml::Value::Float(n) if n.is_finite() => Value::Num(n), - toml::Value::Float(_) => return Err("toml: non-finite numbers unsupported".into()), - toml::Value::Boolean(b) => Value::Bool(b), - toml::Value::Datetime(dt) => Value::Text(dt.to_string()), - toml::Value::Array(xs) => Value::List(xs.into_iter().map(convert).collect::>()?), - toml::Value::Table(fields) => Value::Map(fields.into_iter().map(|(k,v)|convert(v).map(|v|(k,v))).collect::>()?), - }) - } - convert(parsed) -} - -pub fn stringify(value:&Value)->Result{ - fn convert(v:&Value)->Result{ - Ok(match v { - Value::Text(s)=>toml::Value::String(s.clone()), - Value::Int(n)=>toml::Value::Integer(*n), - Value::Num(n) if n.is_finite()=>toml::Value::Float(*n), - Value::Bool(b)=>toml::Value::Boolean(*b), - Value::List(xs)=>toml::Value::Array(xs.iter().map(convert).collect::>()?), - Value::Map(fields)=>toml::Value::Table(fields.iter().map(|(k,v)|convert(v).map(|v|(k.clone(),v))).collect::>()?), - _=>return Err("toml.stringify supports text/finite numbers/bool/list/map; None has no TOML representation".into()), - }) - } - if !matches!(value,Value::Map(_)){return Err("toml root must be map".into())} - toml::to_string_pretty(&convert(value)?).map(Value::Text).map_err(|e|format!("toml.stringify: {e}")) -} -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_simple() { - let t = r#" -# comment -name = "marqdo" -count = 3 -ok = true -[pkg] -version = "0.1" -"#; - let v = parse(&Value::Text(t.into())).unwrap(); - let Value::Map(entries) = v else { panic!() }; - let get = |k: &str| { - entries - .iter() - .find(|(kk, _)| kk == k) - .map(|(_, v)| v.clone()) - .unwrap() - }; - assert_eq!(get("name"), Value::Text("marqdo".into())); - assert_eq!(get("count"), Value::Int(3)); - assert_eq!(get("ok"), Value::Bool(true)); - let Value::Map(pkg) = get("pkg") else { panic!() }; - assert_eq!( - pkg.iter().find(|(k, _)| k == "version").unwrap().1, - Value::Text("0.1".into()) - ); - } -} diff --git a/src/host/url_ops.rs b/src/host/url_ops.rs deleted file mode 100755 index 95a6538..0000000 --- a/src/host/url_ops.rs +++ /dev/null @@ -1,249 +0,0 @@ -//! URL parse / query helpers for Mid2 M7 (`lib/url`). -//! Distinct from `net::url_encode` (single-segment form encoding). -//! Hand-rolled subset (no `url` crate): scheme://[userinfo@]host[:port]/path[?query][#frag]. - -use crate::host::as_text; -use crate::value::Value; - - -fn encode_component(s: &str) -> String { - let mut out = String::new(); - for b in s.bytes() { - match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - out.push(b as char); - } - _ => out.push_str(&format!("%{b:02X}")), - } - } - out -} - -fn decode_component(s: &str) -> Result { - let bytes = s.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'+' => { - out.push(b' '); - i += 1; - } - b'%' if i + 2 < bytes.len() => { - let h = |c: u8| -> Result { - match c { - b'0'..=b'9' => Ok(c - b'0'), - b'a'..=b'f' => Ok(c - b'a' + 10), - b'A'..=b'F' => Ok(c - b'A' + 10), - _ => Err(format!("bad percent escape in {s:?}")), - } - }; - let v = (h(bytes[i + 1])? << 4) | h(bytes[i + 2])?; - out.push(v); - i += 3; - } - b'%' => return Err(format!("truncated percent escape in {s:?}")), - c => { - out.push(c); - i += 1; - } - } - } - String::from_utf8(out).map_err(|e| format!("url decode utf8: {e}")) -} - -/// Parse `scheme://[userinfo@]host[:port]/path[?query][#fragment]`. -pub fn parse(text: &Value) -> Result { - let raw = as_text(text, "text")?; - let (scheme, rest) = raw - .split_once("://") - .ok_or_else(|| format!("url.parse: missing :// in {raw:?}"))?; - if scheme.is_empty() - || !scheme - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') - { - return Err(format!("url.parse: bad scheme in {raw:?}")); - } - - let (before_frag, fragment) = match rest.split_once('#') { - Some((a, b)) => (a, b), - None => (rest, ""), - }; - let (before_query, query) = match before_frag.split_once('?') { - Some((a, b)) => (a, b), - None => (before_frag, ""), - }; - - let (authority, path) = if let Some(i) = before_query.find('/') { - (&before_query[..i], &before_query[i..]) - } else { - (before_query, "") - }; - - let (userinfo, hostport) = if let Some((u, h)) = authority.rsplit_once('@') { - (u, h) - } else { - ("", authority) - }; - - let (host, port) = if hostport.starts_with('[') { - // IPv6 literal [addr]:port - let end = hostport - .find(']') - .ok_or_else(|| format!("url.parse: bad IPv6 host in {raw:?}"))?; - let host = &hostport[1..end]; - let rest = &hostport[end + 1..]; - if rest.is_empty() { - (host, Value::None) - } else if let Some(p) = rest.strip_prefix(':') { - let n: i64 = p - .parse() - .map_err(|_| format!("url.parse: bad port in {raw:?}"))?; - (host, Value::Int(n)) - } else { - return Err(format!("url.parse: bad hostport in {raw:?}")); - } - } else if let Some((h, p)) = hostport.rsplit_once(':') { - if p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty() { - let n: i64 = p - .parse() - .map_err(|_| format!("url.parse: bad port in {raw:?}"))?; - (h, Value::Int(n)) - } else { - (hostport, Value::None) - } - } else { - (hostport, Value::None) - }; - - let path = if path.is_empty() { - "/".to_string() - } else { - path.to_string() - }; - - Ok(Value::Map(vec![ - ("scheme".into(), Value::Text(scheme.to_string())), - ("userinfo".into(), Value::Text(userinfo.to_string())), - ("host".into(), Value::Text(host.to_string())), - ("port".into(), port), - ("path".into(), Value::Text(path)), - ("query".into(), Value::Text(query.to_string())), - ("fragment".into(), Value::Text(fragment.to_string())), - ])) -} - -pub fn query_parse(text: &Value) -> Result { - let raw = as_text(text, "text")?; - let raw = raw.strip_prefix('?').unwrap_or(raw); - let mut map: Vec<(String, Value)> = Vec::new(); - if raw.is_empty() { - return Ok(Value::Map(map)); - } - for pair in raw.split('&') { - if pair.is_empty() { - continue; - } - let (k, v) = match pair.split_once('=') { - Some((k, v)) => (k, v), - None => (pair, ""), - }; - let key = decode_component(k)?; - let val = Value::Text(decode_component(v)?); - if let Some((_, slot)) = map.iter_mut().find(|(kk, _)| *kk == key) { - match slot { - Value::List(xs) => xs.push(val), - other => { - let prev = std::mem::replace(other, Value::None); - *other = Value::List(vec![prev, val]); - } - } - } else { - map.push((key, val)); - } - } - Ok(Value::Map(map)) -} - -pub fn query_stringify(map: &Value) -> Result { - let entries = match map { - Value::Map(m) => m, - Value::None => return Ok(Value::Text(String::new())), - _ => return Err("url.query_stringify: map required".into()), - }; - let mut parts: Vec = Vec::new(); - for (k, v) in entries { - let key = encode_component(k); - match v { - Value::List(xs) => { - for x in xs { - match x { - Value::Text(s) => { - parts.push(format!("{key}={}", encode_component(s))); - } - Value::Int(n) => { - parts.push(format!("{key}={}", encode_component(&n.to_string()))); - } - Value::Bool(b) => { - parts.push(format!("{key}={}", encode_component(&b.to_string()))); - } - Value::None => parts.push(format!("{key}=")), - _ => { - return Err("url.query_stringify: list values must be scalar".into()) - } - } - } - } - Value::Text(s) => parts.push(format!("{key}={}", encode_component(s))), - Value::Int(n) => parts.push(format!("{key}={}", encode_component(&n.to_string()))), - Value::Bool(b) => parts.push(format!("{key}={}", encode_component(&b.to_string()))), - Value::None => parts.push(format!("{key}=")), - _ => return Err("url.query_stringify: values must be scalar or list".into()), - } - } - Ok(Value::Text(parts.join("&"))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_https_query() { - let m = parse(&Value::Text( - "https://user:pass@example.com:8443/a/b?x=1&y=2#frag".into(), - )) - .unwrap(); - let Value::Map(entries) = m else { panic!() }; - let get = |k: &str| { - entries - .iter() - .find(|(kk, _)| kk == k) - .map(|(_, v)| v.clone()) - .unwrap() - }; - assert_eq!(get("scheme"), Value::Text("https".into())); - assert_eq!(get("host"), Value::Text("example.com".into())); - assert_eq!(get("port"), Value::Int(8443)); - assert_eq!(get("path"), Value::Text("/a/b".into())); - assert_eq!(get("query"), Value::Text("x=1&y=2".into())); - assert_eq!(get("fragment"), Value::Text("frag".into())); - assert_eq!(get("userinfo"), Value::Text("user:pass".into())); - } - - #[test] - fn query_roundtrip() { - let q = query_parse(&Value::Text("a=1&b=hello%20w&a=2".into())).unwrap(); - let s = query_stringify(&q).unwrap(); - assert_eq!(s, Value::Text("a=1&a=2&b=hello%20w".into())); - } - - #[test] - fn empty_path_becomes_slash() { - let m = parse(&Value::Text("https://example.com".into())).unwrap(); - let Value::Map(entries) = m else { panic!() }; - let path = entries.iter().find(|(k, _)| k == "path").unwrap().1.clone(); - assert_eq!(path, Value::Text("/".into())); - } -} diff --git a/src/host/uuid_ops.rs b/src/host/uuid_ops.rs deleted file mode 100755 index 492f40f..0000000 --- a/src/host/uuid_ops.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! UUID v4 for Mid M6 (`lib/uuid`). - -use crate::value::Value; - -pub fn v4() -> Result { - let mut bytes = [0u8; 16]; - getrandom::getrandom(&mut bytes).map_err(|e| format!("uuid.v4: {e}"))?; - // RFC 4122 version 4 + variant 10xx - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - Ok(Value::Text(format!( - "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", - bytes[0], - bytes[1], - bytes[2], - bytes[3], - bytes[4], - bytes[5], - bytes[6], - bytes[7], - bytes[8], - bytes[9], - bytes[10], - bytes[11], - bytes[12], - bytes[13], - bytes[14], - bytes[15], - ))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn v4_shape() { - let v = v4().unwrap(); - let Value::Text(s) = v else { panic!("text") }; - assert_eq!(s.len(), 36); - assert_eq!(&s[14..15], "4"); - let variant = u8::from_str_radix(&s[19..20], 16).unwrap(); - assert!(variant == 8 || variant == 9 || variant == 0xa || variant == 0xb); - } -} diff --git a/src/host/writeback.rs b/src/host/writeback.rs deleted file mode 100755 index 7a65e8d..0000000 --- a/src/host/writeback.rs +++ /dev/null @@ -1,914 +0,0 @@ -//! Jupyter-style output persistence in `.mq.md`. -//! -//! Two surface forms (both scanned / replaced): -//! - HTML comment: `` (text / structured output) -//! - Markdown image: `![marqdo-out](path-or-url)` (image refs; validated) -//! -//! Optional **named slots**: `marqdo-out ok` / `marqdo-out error` so success and -//! failure results do not overwrite each other. - -use std::collections::HashMap; -use std::sync::Mutex; - -use crate::host::HostContext; -use crate::value::Value; - -const MAGIC: &str = "marqdo-out"; - -/// Serialize all writeback file mutations (sync + subtask writers). -static WRITEBACK_LOCK: Mutex<()> = Mutex::new(()); - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum BlockKind { - Comment, - Image, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct BlockSpan { - start: usize, - end: usize, - /// Comment body text, or image URL/path for [`BlockKind::Image`]. - body: String, - start_line: u32, - /// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed. - key: Option, - kind: BlockKind, -} - -/// View-facing writeback piece under a statement line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct WritebackEntry { - pub key: Option, - pub body: String, - pub is_image: bool, -} - -fn display_value(v: &Value) -> String { - match v { - Value::Text(s) => s.clone(), - other => other.as_display(), - } -} - -fn is_truthy(v: Option<&Value>) -> bool { - match v { - None | Some(Value::None) => false, - Some(Value::Bool(b)) => *b, - Some(Value::Int(n)) => *n != 0, - _ => false, - } -} - -fn opt_key(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(None), - Some(Value::Text(s)) => { - let t = s.trim(); - if t.is_empty() { - Ok(None) - } else { - Ok(Some(normalize_slot_key(t))) - } - } - _ => Err("writeback key must be text".into()), - } -} - -fn opt_line(v: Option<&Value>) -> Result, String> { - match v { - None | Some(Value::None) => Ok(None), - Some(Value::Int(n)) if *n > 0 => Ok(Some(*n as u32)), - Some(Value::Text(s)) => { - let t = s.trim(); - if t.is_empty() { - Ok(None) - } else { - t.parse::() - .map(|n| if n > 0 { Some(n) } else { None }) - .map_err(|_| "writeback line must be a positive int".into()) - } - } - _ => Err("writeback line must be a positive int".into()), - } -} - -/// Canonical slot ids used by the agent framework. -fn normalize_slot_key(raw: &str) -> String { - match raw { - "ok" | "success" | "成功" => "ok".into(), - "error" | "failure" | "失败" => "error".into(), - other => other.to_string(), - } -} - -fn call_line(ctx: &HostContext) -> Result { - ctx.call_site_lines - .last() - .copied() - .ok_or_else(|| "writeback: no call site line".into()) -} - -/// Line that should own adjacent output cards. -/// Prefer explicit `line=`, else for keyed slots the outermost call site (`step`), -/// else the parent/current call site. -fn resolve_anchor( - ctx: &HostContext, - keyed: bool, - line: Option<&Value>, -) -> Result { - if let Some(n) = opt_line(line)? { - return Ok(n); - } - if keyed { - if let Some(n) = ctx.call_site_lines.first().copied() { - return Ok(n); - } - if ctx.call_site_lines.len() >= 2 { - return Ok(ctx.call_site_lines[ctx.call_site_lines.len() - 2]); - } - } - call_line(ctx) -} - -fn line_number_at(source: &str, byte: usize) -> u32 { - source[..byte.min(source.len())] - .bytes() - .filter(|b| *b == b'\n') - .count() as u32 - + 1 -} - -fn format_comment_block(body: &str, key: Option<&str>) -> String { - match key { - Some(k) => format!(""), - None => format!(""), - } -} - -fn format_image_block(url: &str, key: Option<&str>) -> String { - match key { - Some(k) => format!("![{MAGIC} {k}]({url})"), - None => format!("![{MAGIC}]({url})"), - } -} - -fn format_block_for_value(body: &str, key: Option<&str>) -> Result { - if looks_like_image_ref(body) { - validate_image_ref(body)?; - Ok(format_image_block(body.trim(), key)) - } else { - Ok(format_comment_block(body, key)) - } -} - -/// True when `s` looks like a path/URL that should persist as `![marqdo-out](…)`. -pub fn looks_like_image_ref(s: &str) -> bool { - validate_image_ref(s).is_ok() -} - -/// Accept local/relative paths and http(s) URLs with a known image extension, -/// or `data:image/…` URIs. -pub fn validate_image_ref(s: &str) -> Result<(), String> { - let t = s.trim().trim_matches('"').trim_matches('\''); - if t.is_empty() { - return Err("writeback image: empty path".into()); - } - if t.starts_with("data:image/") { - return Ok(()); - } - // Strip query/fragment for extension check. - let no_query = t.split_once('?').map(|(p, _)| p).unwrap_or(t); - let path_part = no_query.split_once('#').map(|(p, _)| p).unwrap_or(no_query); - let file = path_part.rsplit('/').next().unwrap_or(path_part); - // Require a real extension (reject bare names like `svg` / `png`). - let Some((stem, ext)) = file.rsplit_once('.') else { - return Err(format!( - "writeback image: path needs an image extension (got `{t}`)" - )); - }; - if stem.is_empty() { - return Err(format!("writeback image: invalid file name `{t}`")); - } - let ext = ext.to_ascii_lowercase(); - const OK: &[&str] = &[ - "png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "tif", "tiff", - ]; - if OK.contains(&ext.as_str()) { - Ok(()) - } else { - Err(format!( - "writeback image: not an image path/URL (got `{t}`; need .{})", - OK.join("/.") - )) - } -} - -fn parse_header_key(header: &str) -> Option { - let mut parts = header.split_whitespace(); - let first = parts.next()?; - if first != MAGIC { - return None; - } - parts.next().map(normalize_slot_key) -} - -fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option { - let inner = block - .strip_prefix("")? - .trim(); - if !inner.contains(MAGIC) { - return None; - } - let mut lines: Vec<&str> = inner.lines().collect(); - if lines.is_empty() { - return None; - } - let header = lines.remove(0).trim(); - if !header.split_whitespace().any(|t| t == MAGIC) { - return None; - } - let key = parse_header_key(header); - let body = lines.join("\n"); - let end = start_byte + block.len(); - Some(BlockSpan { - start: start_byte, - end, - body, - start_line: line_number_at(source, start_byte), - key, - kind: BlockKind::Comment, - }) -} - -/// `![marqdo-out …](url)` on a single source line. -fn parse_image_line(line: &str, line_start: usize, source: &str) -> Option { - let trimmed = line.trim(); - let rest = trimmed.strip_prefix("![")?; - let alt_end = rest.find("](")?; - let alt = rest[..alt_end].trim(); - if !alt.split_whitespace().any(|t| t == MAGIC) { - return None; - } - let key = parse_header_key(alt); - let after_alt = &rest[alt_end + 2..]; - let url_end = after_alt.rfind(')')?; - let url = after_alt[..url_end].trim(); - if url.is_empty() || validate_image_ref(url).is_err() { - return None; - } - // Span covers the trimmed image on its line (indent kept outside). - let trim_start = line.find(trimmed).unwrap_or(0); - let start = line_start + trim_start; - let end = start + trimmed.len(); - Some(BlockSpan { - start, - end, - body: url.to_string(), - start_line: line_number_at(source, start), - key, - kind: BlockKind::Image, - }) -} - -fn scan_blocks(source: &str) -> Vec { - let mut out = Vec::new(); - // HTML comment blocks - let mut i = 0usize; - while i < source.len() { - let rest = &source[i..]; - let Some(start) = rest.find("") else { - break; - }; - let block = &after[..end_rel + 3]; - if let Some(b) = parse_one_block(block, abs, source) { - out.push(b); - } - i = abs + end_rel + 3; - } - // Image writebacks (line-oriented) - let mut line_start = 0usize; - for line in source.split_inclusive('\n') { - let content = line.trim_end_matches(['\r', '\n']); - if let Some(b) = parse_image_line(content, line_start, source) { - out.push(b); - } - line_start += line.len(); - } - out.sort_by_key(|b| b.start); - out -} - -fn strip_span(source: &str, start: usize, end: usize) -> String { - let mut out = String::with_capacity(source.len()); - out.push_str(&source[..start]); - out.push_str(&source[end..]); - out -} - -/// Byte end of a `` span, including the single newline that terminates the `-->` line. -fn span_end_including_nl(source: &str, end: usize) -> usize { - if source.as_bytes().get(end) == Some(&b'\n') { - end + 1 - } else { - end - } -} - -/// Write `block` (plus a terminating newline) over `[start, end)`, preserving blank lines after. -fn splice_block(source: &str, start: usize, end: usize, block: &str) -> String { - let end = span_end_including_nl(source, end); - let mut out = String::with_capacity(source.len() + block.len() + 1); - out.push_str(&source[..start]); - out.push_str(block); - if !block.ends_with('\n') { - out.push('\n'); - } - out.push_str(&source[end..]); - out -} - -fn line_start_byte(source: &str, line_no: u32) -> Option { - if line_no == 0 { - return None; - } - let mut cur = 1u32; - for (i, b) in source.bytes().enumerate() { - if cur == line_no { - return Some(i); - } - if b == b'\n' { - cur += 1; - } - } - if cur == line_no { - Some(source.len()) - } else { - None - } -} - -fn line_end_byte(source: &str, line_no: u32) -> Option { - let start = line_start_byte(source, line_no)?; - let rest = &source[start..]; - match rest.find('\n') { - Some(off) => Some(start + off + 1), - None => Some(source.len()), - } -} - -fn is_blank_line(source: &str, line_no: u32) -> bool { - let start = match line_start_byte(source, line_no) { - Some(s) => s, - None => return true, - }; - let end = line_end_byte(source, line_no).unwrap_or(source.len()); - source[start..end].trim().is_empty() -} - -fn find_adjacent_block(source: &str, after_line: u32) -> Option { - let mut line = after_line.saturating_add(1); - let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1; - while line <= total && is_blank_line(source, line) { - line += 1; - } - for b in scan_blocks(source) { - if b.start_line == line && b.key.is_none() { - return Some(b); - } - } - None -} - -fn is_eof_block(source: &str, block: &BlockSpan) -> bool { - source[block.end..].trim().is_empty() -} - -fn find_eof_block(source: &str) -> Option { - scan_blocks(source) - .into_iter() - .rev() - .find(|b| b.key.is_none() && is_eof_block(source, b)) -} - -fn find_keyed_block(source: &str, key: &str) -> Option { - let key = normalize_slot_key(key); - scan_blocks(source) - .into_iter() - .rev() - .find(|b| b.key.as_deref() == Some(key.as_str())) -} - -/// Consecutive `marqdo-out` blocks immediately below `after_line` (blank lines allowed). -fn cluster_after_line(source: &str, after_line: u32) -> Vec { - let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1; - let mut line = after_line.saturating_add(1); - while line <= total && is_blank_line(source, line) { - line += 1; - } - let blocks = scan_blocks(source); - let mut cluster = Vec::new(); - while line <= total { - if let Some(b) = blocks.iter().find(|b| b.start_line == line) { - cluster.push(b.clone()); - let end_line = line_number_at(source, b.end.saturating_sub(1).max(b.start)); - line = end_line.saturating_add(1); - while line <= total && is_blank_line(source, line) { - line += 1; - } - } else { - break; - } - } - cluster -} - -fn find_keyed_in_cluster(source: &str, after_line: u32, key: &str) -> Option { - let key = normalize_slot_key(key); - cluster_after_line(source, after_line) - .into_iter() - .find(|b| b.key.as_deref() == Some(key.as_str())) -} - -/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF). -fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result { - let key = normalize_slot_key(key); - let block = format_block_for_value(body, Some(&key))?; - if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) { - return Ok(splice_block(source, existing.start, existing.end, &block)); - } - let cluster = cluster_after_line(source, anchor); - if let Some(last) = cluster.last() { - // Insert after the last block's terminating newline (or after `-->` if none). - let insert_at = span_end_including_nl(source, last.end); - let mut out = String::with_capacity(source.len() + block.len() + 1); - out.push_str(&source[..insert_at]); - if !out.ends_with('\n') { - out.push('\n'); - } - out.push_str(&block); - if !block.ends_with('\n') { - out.push('\n'); - } - out.push_str(&source[insert_at..]); - Ok(out) - } else { - insert_after_line(source, anchor, &block) - } -} - -fn insert_after_line(source: &str, line_no: u32, block: &str) -> Result { - let insert_at = line_end_byte(source, line_no) - .ok_or_else(|| format!("writeback: line {line_no} out of range"))?; - let mut out = String::with_capacity(source.len() + block.len() + 2); - out.push_str(&source[..insert_at]); - if !block.starts_with('\n') && !source[..insert_at].ends_with('\n') { - out.push('\n'); - } - out.push_str(block); - if !block.ends_with('\n') { - out.push('\n'); - } - out.push_str(&source[insert_at..]); - Ok(out) -} - -fn append_eof(source: &str, block: &str) -> String { - let mut trimmed = source.trim_end().to_string(); - if !trimmed.is_empty() { - trimmed.push('\n'); - } - trimmed.push_str(block); - if !block.ends_with('\n') { - trimmed.push('\n'); - } - trimmed -} - -fn entry_target(path: &std::path::Path) -> Result { - if path.is_absolute() { return Ok(path.to_path_buf()); } - // Entry paths originate at the caller's process cwd, as in the runner. - std::env::current_dir().map(|base|base.join(path)).map_err(|e|format!("writeback entry path: {e}")) -} -fn entry_path_text(path: &std::path::Path) -> Result { - let path=entry_target(path)?; - Ok(Value::Text(path.to_str().ok_or("writeback path must be UTF-8")?.to_string())) -} -fn persist(ctx: &mut HostContext, source: &str) -> Result<(), String> { - if !ctx.allow_fs_write() { - return Err("writeback disabled (fs_write capability off)".into()); - } - let path=ctx.entry_path.as_ref().ok_or("writeback: no entry file")?; - let path=entry_path_text(path)?; - // Use the same root, symlink and CoW rules as ordinary native file writes. - super::fs::write_text(ctx,&path,&Value::Text(source.to_string()))?; - ctx.entry_source=Some(source.to_string()); - Ok(()) -} -fn load_entry_source(ctx: &HostContext) -> Result { - if let Some(path)=&ctx.entry_path { - let target=entry_target(path)?; - match super::fs::read_text(ctx,&entry_path_text(path)?) { - Ok(Value::Text(text))=>return Ok(text), - Ok(_)=>return Err("writeback entry source must be text".into()), - // In-memory entry buffers may intentionally precede file creation. - Err(_) if !target.exists()=>{}, - Err(error)=>return Err(error), - } - } - ctx.entry_source.clone().ok_or_else(||"writeback: no entry source".to_string()) -} - -fn with_writeback_lock(f: impl FnOnce() -> Result) -> Result { - let _guard = WRITEBACK_LOCK - .lock() - .map_err(|_| "writeback lock poisoned".to_string())?; - f() -} - -fn anchor_line_above(source: &str, block_start_line: u32) -> u32 { - let mut line = block_start_line.saturating_sub(1); - while line > 0 && is_blank_line(source, line) { - line -= 1; - } - line.max(1) -} - -pub fn record( - ctx: &mut HostContext, - value: &Value, - at_end: Option<&Value>, - key: Option<&Value>, - line: Option<&Value>, -) -> Result { - let body = display_value(value); - let key = opt_key(key)?; - let at_end = is_truthy(at_end); - let anchor = if key.is_some() || !at_end { - Some(resolve_anchor(ctx, key.is_some(), line)?) - } else { - None - }; - with_writeback_lock(|| { - let source = load_entry_source(ctx)?; - let next = if let Some(ref k) = key { - let anchor = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?; - replace_or_insert_keyed_at(&source, anchor, k, &body)? - } else if at_end { - let stripped = find_eof_block(&source) - .map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end))) - .unwrap_or_else(|| source.clone()); - append_eof(&stripped, &format_block_for_value(&body, None)?) - } else { - let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?; - let stripped = find_adjacent_block(&source, line) - .map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end))) - .unwrap_or_else(|| source.clone()); - insert_after_line(&stripped, line, &format_block_for_value(&body, None)?)? - }; - persist(ctx, &next)?; - Ok(Value::Text(body.clone())) - }) -} - -pub fn get( - ctx: &HostContext, - at_end: Option<&Value>, - key: Option<&Value>, - line: Option<&Value>, -) -> Result { - let key = opt_key(key)?; - let at_end = is_truthy(at_end); - let anchor = if key.is_some() || !at_end { - resolve_anchor(ctx, key.is_some(), line).ok() - } else { - None - }; - with_writeback_lock(|| { - let source = load_entry_source(ctx)?; - let body = if let Some(ref k) = key { - let found = anchor - .and_then(|a| find_keyed_in_cluster(&source, a, k)) - .or_else(|| find_keyed_block(&source, k)); - found.map(|b| b.body) - } else if at_end { - find_eof_block(&source).map(|b| b.body) - } else { - let line = anchor.ok_or_else(|| "writeback: no call site line".to_string())?; - find_adjacent_block(&source, line).map(|b| b.body) - }; - Ok(match body { - Some(s) => Value::Text(s), - None => Value::None, - }) - }) -} - -pub fn clear( - ctx: &mut HostContext, - at_end: Option<&Value>, - key: Option<&Value>, - line: Option<&Value>, -) -> Result { - let key = opt_key(key)?; - let at_end = is_truthy(at_end); - let anchor = if key.is_some() || !at_end { - resolve_anchor(ctx, key.is_some(), line).ok() - } else { - None - }; - with_writeback_lock(|| { - let source = load_entry_source(ctx)?; - let next = if let Some(ref k) = key { - let block = anchor - .and_then(|a| find_keyed_in_cluster(&source, a, k)) - .or_else(|| find_keyed_block(&source, k)); - block - .map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end))) - .unwrap_or_else(|| source.clone()) - } else if at_end { - find_eof_block(&source) - .map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end))) - .unwrap_or_else(|| source.clone()) - } else { - let line = anchor.ok_or_else(|| "writeback: no call site line".to_string())?; - find_adjacent_block(&source, line) - .map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end))) - .unwrap_or_else(|| source.clone()) - }; - if next != source { - persist(ctx, &next)?; - } - Ok(Value::None) - }) -} - -pub fn list(ctx: &HostContext) -> Result { - let source = ctx - .entry_source - .as_deref() - .ok_or_else(|| "writeback: no entry source".to_string())?; - Ok(slots_from_source(source)) -} - -/// Scan `path` for `` slots (any file, not only the entry). -pub fn scan_path(ctx: &HostContext, path: &Value) -> Result { - let rel = match path { - Value::Text(s) => s.as_str(), - _ => return Err("writeback scan_path: path must be text".into()), - }; - let p = ctx.resolve_path(rel)?; - let source = std::fs::read_to_string(&p) - .map_err(|e| format!("writeback scan_path {}: {e}", p.display()))?; - Ok(slots_from_source(&source)) -} - -fn slots_from_source(source: &str) -> Value { - let items: Vec = scan_blocks(source) - .into_iter() - .map(|b| { - let anchor = anchor_line_above(source, b.start_line); - let at_eof = b.key.is_none() && is_eof_block(source, &b); - let kind = match b.kind { - BlockKind::Comment => "comment", - BlockKind::Image => "image", - }; - let mut entries = vec![ - ("line".into(), Value::Int(anchor as i64)), - ("body".into(), Value::Text(b.body)), - ("at_end".into(), Value::Bool(at_eof)), - ("kind".into(), Value::Text(kind.into())), - ]; - if let Some(k) = b.key { - entries.push(("key".into(), Value::Text(k))); - } - Value::Map(entries) - }) - .collect(); - Value::List(items) -} - -/// Ensure named slots exist with a placeholder body; **does not** overwrite non-empty bodies. -pub fn ensure_slot( - ctx: &mut HostContext, - key: &Value, - placeholder: &Value, - line: Option<&Value>, -) -> Result { - let k = opt_key(Some(key))?.ok_or_else(|| "writeback ensure needs key".to_string())?; - let body = display_value(placeholder); - let anchor = resolve_anchor(ctx, true, line)?; - with_writeback_lock(|| { - let source = load_entry_source(ctx)?; - if find_keyed_in_cluster(&source, anchor, &k).is_some() { - return Ok(Value::Bool(false)); - } - let next = replace_or_insert_keyed_at(&source, anchor, &k, &body)?; - persist(ctx, &next)?; - Ok(Value::Bool(true)) - }) -} - -/// Structured writebacks keyed by the statement line above the block cluster. -pub fn writeback_entries(source: &str) -> HashMap> { - let mut map: HashMap> = HashMap::new(); - for b in scan_blocks(source) { - let anchor = if b.key.is_none() && is_eof_block(source, &b) { - 0 - } else { - anchor_line_above(source, b.start_line) - }; - let entry = WritebackEntry { - key: b.key.clone(), - body: b.body.clone(), - is_image: b.kind == BlockKind::Image, - }; - map.entry(anchor).or_default().push(entry); - } - map -} - -/// Map statement line → combined body for adjacent blocks (keyed slots included). -/// Image slots are encoded as a markdown image line so view/static can render ``. -pub fn writeback_map(source: &str) -> HashMap { - let mut map = HashMap::new(); - for (anchor, entries) in writeback_entries(source) { - let mut pieces = Vec::new(); - for e in entries { - let content = if e.is_image { - format!("![]({})", e.body) - } else { - e.body - }; - let piece = match &e.key { - Some(k) => format!("[{k}]\n{content}"), - None => content, - }; - pieces.push(piece); - } - map.insert(anchor, pieces.join("\n\n")); - } - map -} - - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_and_insert_adjacent() { - let src = "# main\n\n**x = 1**\n"; - let block = format_comment_block("1", None); - let next = insert_after_line(src, 3, &block).unwrap(); - assert!(next.contains("marqdo-out")); - assert!(!next.contains("@line")); - let blocks = scan_blocks(&next); - assert_eq!(blocks.len(), 1); - assert_eq!(blocks[0].body, "1"); - let replaced = strip_span(&next, blocks[0].start, blocks[0].end); - assert!(!replaced.contains("marqdo-out")); - } - - #[test] - fn image_writeback_scan_and_format() { - assert!(looks_like_image_ref("plot.svg")); - assert!(looks_like_image_ref("https://ex.com/a.PNG")); - assert!(looks_like_image_ref("data:image/png;base64,xx")); - assert!(looks_like_image_ref("plots/a.svg?v=1")); - assert!(!looks_like_image_ref("readme.txt")); - assert!(!looks_like_image_ref("42")); - assert!(!looks_like_image_ref("svg")); // bare name, not an extension - assert!(!looks_like_image_ref(".svg")); - let block = format_image_block("out/plot.svg", Some("ok")); - assert_eq!(block, "![marqdo-out ok](out/plot.svg)"); - let src = "# main\n\n**x = 1**\n![marqdo-out ok](out/plot.svg)\n\n> print text=tail\n"; - let blocks = scan_blocks(src); - assert_eq!(blocks.len(), 1); - assert_eq!(blocks[0].kind, BlockKind::Image); - assert_eq!(blocks[0].body, "out/plot.svg"); - assert_eq!(blocks[0].key.as_deref(), Some("ok")); - let map = writeback_map(src); - assert_eq!( - map.get(&3).map(|s| s.as_str()), - Some("[ok]\n![](out/plot.svg)") - ); - // Invalid image URL in marqdo-out alt → not a writeback slot - let bad = "# main\n\n![marqdo-out](notes.txt)\n"; - assert!(scan_blocks(bad).is_empty()); - } - - #[test] - fn unkeyed_comment_and_image_replace_each_other() { - let src = "# main\n\n**x = 1**\n\n\n> print text=tail\n"; - let line = 3u32; - let to_image = { - let stripped = find_adjacent_block(src, line) - .map(|b| strip_span(src, b.start, span_end_including_nl(src, b.end))) - .unwrap_or_else(|| src.to_string()); - insert_after_line( - &stripped, - line, - &format_block_for_value("fig.svg", None).unwrap(), - ) - .unwrap() - }; - assert!(to_image.contains("![marqdo-out](fig.svg)")); - assert!(!to_image.contains("")); - assert!(!to_text.contains("![marqdo-out]")); - } - - #[test] - fn record_format_picks_image_for_svg_path() { - let s = format_block_for_value("figs/a.svg", None).unwrap(); - assert_eq!(s, "![marqdo-out](figs/a.svg)"); - let t = format_block_for_value("hello", None).unwrap(); - assert!(t.contains("\n\n> print text=tail\n"; - let map = writeback_map(src); - assert_eq!(map.get(&3), Some(&"42".to_string())); - } - - #[test] - fn keyed_slots_sit_under_anchor_and_do_not_clobber() { - let src = "# main\n\n**r = > step**\n\n> print text=after\n"; - let with_ok = replace_or_insert_keyed_at(src, 3, "ok", "success-1").unwrap(); - let with_both = replace_or_insert_keyed_at(&with_ok, 3, "error", "fail-1").unwrap(); - let step_at = with_both.find("r = > step").unwrap(); - let ok_at = with_both.find("marqdo-out ok").unwrap(); - let err_at = with_both.find("marqdo-out error").unwrap(); - let after_at = with_both.find("> print text=after").unwrap(); - assert!(ok_at > step_at && ok_at < after_at); - assert!(err_at > ok_at && err_at < after_at); - let updated = replace_or_insert_keyed_at(&with_both, 3, "error", "fail-2").unwrap(); - assert!(updated.contains("success-1")); - assert!(updated.contains("fail-2")); - assert!(!updated.contains("fail-1")); - } - - #[test] - fn keyed_replace_does_not_accumulate_blank_lines() { - let src = "# main\n\n> writeback.record\n\n\n2. *\n"; - let once = replace_or_insert_keyed_at(src, 3, "ok", "new-1").unwrap(); - let twice = replace_or_insert_keyed_at(&once, 3, "ok", "new-2").unwrap(); - let thrice = replace_or_insert_keyed_at(&twice, 3, "ok", "new-3").unwrap(); - assert_eq!(once.matches("\n\n\n").count(), src.matches("\n\n\n").count()); - assert_eq!(twice, thrice.replace("new-3", "new-2")); - // Exactly one blank line between `-->` and the next statement. - let after = thrice.split("-->\n").nth(1).unwrap(); - assert!(after.starts_with("\n2. *"), "got after -->: {after:?}"); - assert!(!after.starts_with("\n\n\n"), "blank lines accumulated"); - } - - #[test] - fn unkeyed_replace_does_not_accumulate_blank_lines() { - let src = "# main\n\n**x = 1**\n\n\n> print text=tail\n"; - let line = 3u32; - let strip_insert = |s: &str, body: &str| { - let stripped = find_adjacent_block(s, line) - .map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end))) - .unwrap_or_else(|| s.to_string()); - insert_after_line(&stripped, line, &format_comment_block(body, None)).unwrap() - }; - let once = strip_insert(src, "a"); - let twice = strip_insert(&once, "b"); - let thrice = strip_insert(&twice, "c"); - assert_eq!( - once.matches("\n\n\n").count(), - thrice.matches("\n\n\n").count() - ); - let after = thrice.split("-->\n").nth(1).unwrap(); - assert!(after.starts_with("\n> print"), "got after -->: {after:?}"); - } -} diff --git a/src/inherit.rs b/src/inherit.rs deleted file mode 100755 index ae2c511..0000000 --- a/src/inherit.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! Object inheritance: `# Child = > Parent` validation and helpers. - -use std::collections::HashSet; - -use anyhow::Result; - -use crate::ast::{Function, Module}; -use crate::diagnostics::Diagnostic; - -/// Import binding paths identify module instances, including repeated imports -/// of the same file under different bindings. The tree remains immutable. -pub(crate) fn module_namespace(root:&Module, wanted:&Module) -> Option> { - if std::ptr::eq(root,wanted) { return Some(Vec::new()); } - let mut imports=root.import_modules.iter().collect::>(); - imports.sort_by_key(|(name,_)| *name); - for (bind,module) in imports { - if let Some(mut path)=module_namespace(module,wanted) { - path.insert(0,bind.clone()); return Some(path); - } - } - None -} - -pub(crate) fn object_at_namespace<'a>(root:&'a Module,path:&[String],name:&str) -> Option<(&'a Module,&'a Function)> { - let mut owner=root; - for segment in path { owner=owner.import_modules.get(segment)?; } - let object=owner.functions.iter().find(|fun|fun.is_object() && fun.name==name)?; - Some((owner,object)) -} - -/// Bare types prefer their defining module. An imported short-name binding -/// resolves its explicit path; a legacy imported bare name must be unique. -pub(crate) fn resolve_object<'a>(owner:&'a Module,name:&str) -> Result<(&'a Module,&'a Function),String> { - if let Some(alias)=owner.uses.iter().find(|binding|binding.bind==name) { - let Some((class,path))=alias.path.split_last() else { return Err("empty object alias".into()); }; - return object_at_namespace(owner,path,class).ok_or_else(||format!("unknown object type `{name}`")); - } - if let Some(object)=owner.functions.iter().find(|fun|fun.is_object() && fun.name==name) { return Ok((owner,object)); } - fn imported<'a>(module:&'a Module,name:&str,out:&mut Vec<(&'a Module,&'a Function)>) { - let mut imports=module.import_modules.iter().collect::>();imports.sort_by_key(|(name,_)|*name); - for (_,child) in imports { - out.extend(child.functions.iter().filter(|fun|fun.is_object() && fun.name==name).map(|fun|(child,fun))); - imported(child,name,out); - } - } - let mut candidates=Vec::new(); imported(owner,name,&mut candidates); - match candidates.as_slice() { - [only]=>Ok(*only), - []=>Err(format!("unknown object type `{name}`")), - _=>Err(format!("ambiguous object type `{name}`; use an explicit import binding")), - } -} - -/// Validate that every object's `base` resolves and that the inheritance graph is acyclic. -pub fn validate_inheritance(module: &Module) -> Result<()> { - fn modules<'a>(module: &'a Module, out: &mut Vec<&'a Module>) { - out.push(module); - let mut imports=module.import_modules.iter().collect::>(); - imports.sort_by_key(|(name,_)| *name); - for (_, child) in imports { modules(child,out); } - } - let mut all=Vec::new(); modules(module,&mut all); - for owner in all { - for object in owner.functions.iter().filter(|fun|fun.is_object()) { - let mut current_owner=owner; - let mut current=object; - let mut seen=HashSet::new(); - let mut chain=Vec::new(); - loop { - chain.push(current.name.clone()); - if !seen.insert((current_owner as *const Module,current as *const Function)) { - return Err(Diagnostic::new(owner.source.path.as_deref(),object.span, - format!("cyclic inheritance involving `{}` ({})",object.name,chain.join(" → "))) - .with_source(&owner.source).into()); - } - let Some(base)=¤t.base else { break; }; - (current_owner,current)=resolve_object(current_owner,base).map_err(|message| { - Diagnostic::new(current_owner.source.path.as_deref(),current.span, - format!("{} base type `{base}` for object `{}`: {message}",if message.starts_with("ambiguous") { "ambiguous" } else { "unknown" },current.name)) - .with_source(¤t_owner.source) - })?; - } - } - } - Ok(()) -} - -/// Walk the base chain starting at `type_name` (inclusive). -pub fn inheritance_chain<'a>(module: &'a Module, type_name: &str) -> Vec<&'a Function> { - let mut out=Vec::new(); - let Ok((mut owner,mut object))=resolve_object(module,type_name) else { return out; }; - let mut seen=HashSet::new(); - while seen.insert((owner as *const Module,object as *const Function)) { - out.push(object); - let Some(base)=&object.base else { break; }; - let Ok(next)=resolve_object(owner,base) else { break; }; - (owner,object)=next; - } - out -} - diff --git a/src/input_feed.rs b/src/input_feed.rs deleted file mode 100755 index d4c4228..0000000 --- a/src/input_feed.rs +++ /dev/null @@ -1,416 +0,0 @@ -//! Preset stdin lines for `input` (CLI `--stdin-file`, view form, frontmatter, tests). -//! Interactive TTY path uses Unicode-aware line editing (char backspace + redraw). - -use std::collections::VecDeque; -use std::fs; -use std::io::{self, BufRead, Write}; -#[cfg(all(unix, feature = "tty"))] -use std::io::Read; -use std::path::Path; - -use anyhow::{Context, Result}; - -/// Split text into input lines (strips `\n` / `\r\n`; empty → no lines). -pub fn split_stdin_text(text: &str) -> Vec { - if text.is_empty() { - return Vec::new(); - } - text.lines() - .map(|l| l.trim_end_matches('\r').to_string()) - .collect() -} - -pub fn load_stdin_file(path: &Path) -> Result> { - let text = fs::read_to_string(path) - .with_context(|| format!("failed to read stdin file {}", path.display()))?; - Ok(split_stdin_text(&text)) -} - -/// Prefer explicit override (CLI / view form); else frontmatter `stdin:` / `输入:`. -pub fn effective_stdin(source: &str, override_lines: &[String]) -> Vec { - if !override_lines.is_empty() { - return override_lines.to_vec(); - } - extract_frontmatter_stdin(source) -} - -/// Read demo / preset lines from YAML-ish frontmatter. -/// -/// Supported shapes: -/// - `stdin: Alice` / `输入: 小明` -/// - block scalar: -/// ```text -/// stdin: | -/// Alice -/// Bob -/// ``` -/// - list: -/// ```text -/// stdin: -/// - Alice -/// - Bob -/// ``` -pub fn extract_frontmatter_stdin(source: &str) -> Vec { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return Vec::new(); - } - - let mut i = 1usize; - while i < lines.len() { - let raw = lines[i]; - let t = raw.trim(); - if t == "---" { - break; - } - - let (key, rest) = match split_fm_key(t) { - Some(pair) => pair, - None => { - i += 1; - continue; - } - }; - if key != "stdin" && key != "输入" { - i += 1; - continue; - } - - let rest = rest.trim(); - if rest == "|" || rest == "|-" || rest == "|+" { - i += 1; - let mut out = Vec::new(); - while i < lines.len() { - let body = lines[i]; - let bt = body.trim(); - if bt == "---" || (!body.starts_with(' ') && !body.starts_with('\t') && !bt.is_empty()) - { - break; - } - if bt.is_empty() && (body.is_empty() || body.chars().all(|c| c == ' ' || c == '\t')) { - out.push(String::new()); - } else { - out.push(strip_block_indent(body)); - } - i += 1; - } - return out; - } - if rest.is_empty() { - i += 1; - let mut out = Vec::new(); - while i < lines.len() { - let body = lines[i]; - let bt = body.trim(); - if bt == "---" { - break; - } - if let Some(item) = bt.strip_prefix("- ") { - out.push(item.trim().trim_matches('"').to_string()); - i += 1; - continue; - } - if bt == "-" { - out.push(String::new()); - i += 1; - continue; - } - // end of list (next key or blank then key) - if !body.starts_with(' ') && !body.starts_with('\t') && !bt.is_empty() { - break; - } - if bt.is_empty() { - i += 1; - continue; - } - break; - } - return out; - } - return vec![rest.trim_matches('"').to_string()]; - } - Vec::new() -} - -fn split_fm_key(t: &str) -> Option<(&str, &str)> { - let (k, v) = t.split_once(':')?; - let k = k.trim(); - if k.is_empty() || k.starts_with('>') { - return None; - } - Some((k, v)) -} - -fn strip_block_indent(line: &str) -> String { - let s = line.strip_prefix(" ").or_else(|| line.strip_prefix('\t')).unwrap_or(line); - s.trim_end_matches('\r').to_string() -} - -pub fn stdin_is_tty() -> bool { - #[cfg(all(unix, feature = "tty"))] - { - unsafe { libc::isatty(libc::STDIN_FILENO) == 1 } - } - #[cfg(not(all(unix, feature = "tty")))] - { - false - } -} - -/// Piped / non-TTY: read raw bytes to newline (avoids mid-frame UTF-8 panic), lossy decode. -fn read_stdin_line_piped() -> Result { - let mut buf = Vec::new(); - io::stdin().lock().read_until(b'\n', &mut buf)?; - if buf.last() == Some(&b'\n') { - buf.pop(); - } - if buf.last() == Some(&b'\r') { - buf.pop(); - } - Ok(String::from_utf8_lossy(&buf).into_owned()) -} - -/// Ensure prompt has a trailing space so typed text does not glue to the last glyph. -fn normalize_prompt(prompt: &str) -> String { - if prompt.is_empty() { - return String::new(); - } - if prompt.ends_with(|c: char| c.is_whitespace()) { - prompt.to_string() - } else { - format!("{prompt} ") - } -} - -#[cfg(all(unix, feature = "tty"))] -struct TermGuard { - fd: i32, - original: libc::termios, -} - -#[cfg(all(unix, feature = "tty"))] -impl TermGuard { - fn enter_cbreak() -> Result { - let fd = libc::STDIN_FILENO; - let mut original = unsafe { std::mem::zeroed::() }; - if unsafe { libc::tcgetattr(fd, &mut original) } != 0 { - return Err(io::Error::last_os_error()).context("tcgetattr"); - } - let mut raw = original; - raw.c_lflag &= !(libc::ICANON | libc::ECHO); - raw.c_cc[libc::VMIN] = 1; - raw.c_cc[libc::VTIME] = 0; - if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw) } != 0 { - return Err(io::Error::last_os_error()).context("tcsetattr"); - } - Ok(Self { fd, original }) - } -} - -#[cfg(all(unix, feature = "tty"))] -impl Drop for TermGuard { - fn drop(&mut self) { - unsafe { - libc::tcsetattr(self.fd, libc::TCSANOW, &self.original); - } - } -} - -#[cfg(all(unix, feature = "tty"))] -fn redraw_line(prompt: &str, buf: &str) -> Result<()> { - let mut out = io::stdout().lock(); - // CR + clear whole line, then reprint (fixes CJK backspace display desync). - write!(out, "\r\x1b[2K{prompt}{buf}")?; - out.flush()?; - Ok(()) -} - -/// Interactive line editor: UTF-8 char backspace + full-line redraw. -#[cfg(all(unix, feature = "tty"))] -fn read_stdin_line_interactive(prompt: &str) -> Result { - let prompt = normalize_prompt(prompt); - let _guard = TermGuard::enter_cbreak()?; - redraw_line(&prompt, "")?; - - let mut buf = String::new(); - let mut pending = Vec::new(); - let mut stdin = io::stdin().lock(); - let mut byte = [0u8; 1]; - - loop { - let n = stdin.read(&mut byte)?; - if n == 0 { - // EOF - writeln!(io::stdout())?; - return Ok(buf); - } - let b = byte[0]; - match b { - b'\n' | b'\r' => { - writeln!(io::stdout())?; - return Ok(buf); - } - 0x7f | 0x08 => { - // Backspace / BS — delete one Unicode scalar, not one byte. - if buf.pop().is_some() { - redraw_line(&prompt, &buf)?; - } - } - 0x03 => { - // Ctrl-C - writeln!(io::stdout())?; - anyhow::bail!("interrupted"); - } - 0x04 => { - // Ctrl-D - if buf.is_empty() && pending.is_empty() { - writeln!(io::stdout())?; - return Ok(buf); - } - } - b if b < 0x20 => { - // ignore other controls - } - b => { - pending.push(b); - match std::str::from_utf8(&pending) { - Ok(s) => { - buf.push_str(s); - pending.clear(); - redraw_line(&prompt, &buf)?; - } - Err(e) if e.error_len().is_none() => { - // incomplete UTF-8 sequence — wait for more bytes - } - Err(_) => { - // invalid — drop and continue - pending.clear(); - } - } - } - } - } -} - -#[cfg(not(all(unix, feature = "tty")))] -fn read_stdin_line_interactive(prompt: &str) -> Result { - let prompt = normalize_prompt(prompt); - print!("{prompt}"); - io::stdout().flush()?; - read_stdin_line_piped() -} - -#[derive(Debug, Clone, Default)] -pub struct InputFeed { - queue: VecDeque, - capture: bool, -} - -impl InputFeed { - pub fn new(capture: bool, lines: impl Into>) -> Self { - Self { - queue: lines.into().into(), - capture, - } - } - - /// Next line from the preset queue, or real stdin when not capturing. - /// Prefer [`Self::read_line_with_prompt`] for interactive TTY (Unicode backspace). - pub fn read_line(&mut self) -> Result { - if let Some(line) = self.queue.pop_front() { - return Ok(line); - } - if self.capture { - anyhow::bail!( - "input needs a line (frontmatter stdin:/输入:, view Preset input, or --stdin-file)" - ); - } - read_stdin_line_piped() - } - - /// Read a line; on a TTY, run Unicode-aware editing and draw `prompt` itself. - /// Returns `Ok((line, painted_prompt))` where `painted_prompt` is true when this - /// function already printed the prompt (caller must not `emit_prompt` again). - pub fn read_line_with_prompt(&mut self, prompt: &str) -> Result<(String, bool)> { - if let Some(line) = self.queue.pop_front() { - return Ok((line, false)); - } - if self.capture { - anyhow::bail!( - "input needs a line (frontmatter stdin:/输入:, view Preset input, or --stdin-file)" - ); - } - let line = read_stdin_line_interactive(prompt)?; - Ok((line, true)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{run_file_capture, RunOptions}; - - #[test] - fn capture_accepts_preset_stdin() { - let cap = run_file_capture( - Path::new("tests/keywords/input.mq.md"), - &RunOptions { - stdin_lines: vec!["Alice".into()], - ..RunOptions::default() - }, - ) - .expect("capture with stdin"); - assert_eq!(cap.stdout.trim_end(), "Name:Hello Alice!"); - } - - #[test] - fn capture_uses_frontmatter_stdin() { - let src = "---\ntitle: t\nstdin: Ada\n---\n\n# main\n\n**n = > input**\n\n> print text=`n`\n"; - let dir = std::env::temp_dir().join("marqdo-fm-stdin-test"); - let _ = fs::create_dir_all(&dir); - let path = dir.join("fm.mq.md"); - fs::write(&path, src).unwrap(); - let cap = run_file_capture(&path, &RunOptions::default()).expect("fm stdin"); - assert_eq!(cap.stdout.trim_end(), "Ada"); - } - - #[test] - fn extract_block_and_list() { - assert_eq!( - extract_frontmatter_stdin("---\nstdin: |\n a\n b\n---\n"), - vec!["a".to_string(), "b".to_string()] - ); - assert_eq!( - extract_frontmatter_stdin("---\n输入:\n - 甲\n - 乙\n---\n"), - vec!["甲".to_string(), "乙".to_string()] - ); - assert_eq!( - extract_frontmatter_stdin("---\nstdin: Zoe\n---\n"), - vec!["Zoe".to_string()] - ); - } - - #[test] - fn split_keeps_blank_middle_lines() { - assert_eq!( - split_stdin_text("a\n\nb\n"), - vec!["a".to_string(), String::new(), "b".to_string()] - ); - } - - #[test] - fn normalize_prompt_adds_space() { - assert_eq!(normalize_prompt("问?"), "问? "); - assert_eq!(normalize_prompt("问? "), "问? "); - assert_eq!(normalize_prompt(""), ""); - } - - #[test] - fn utf8_pop_removes_full_char() { - let mut s = String::from("帮我规划"); - assert_eq!(s.pop(), Some('划')); - assert_eq!(s.pop(), Some('规')); - assert_eq!(s, "帮我"); - } -} diff --git a/src/interp.rs b/src/interp.rs deleted file mode 100755 index a60bfe4..0000000 --- a/src/interp.rs +++ /dev/null @@ -1,2040 +0,0 @@ -//! Tree-walk interpreter (Phase I). - -use anyhow::{bail, Result}; -use std::collections::{HashMap, HashSet}; -use std::path::{Path, PathBuf}; - -use crate::ast::{ - Arg, BinaryOp, CallExpr, Expr, Function, IndexKey, InterpPart, Literal, Module, Param, Stmt, -}; -use crate::builtin::{ - builtin_at, builtin_footnote_get, builtin_int, builtin_iter_items, builtin_join, - builtin_len, builtin_split, builtin_str, builtin_trim, - builtin_type, -}; -use crate::debug::{emit_trace, DebugController}; -use crate::diagnostics::{Diagnostic, DiagnosticFrame, SourceIdentity, Span}; -use crate::host::{call_host, HostContext}; -use crate::input_feed::InputFeed; -use crate::capture::{ - BranchHit, CallFrame, LoopFrame, LoopHit, LoopIter, StmtEvent, StmtEventKind, ViewTrace, -}; -use crate::value::Value; -use std::sync::Arc; - -pub struct Interpreter { - pub path: Option, - pub trace: bool, - capture: bool, - pub captured_stdout: String, - /// Bindings in the entry (`# main` / sole object) env after it finishes. - pub entry_bindings: HashMap, - /// Silent branch/loop hits for `marqdo view` annotations. - pub view_trace: ViewTrace, - next_call_id: u32, - call_stack: Vec, - fn_ordinals: HashMap, - next_loop_id: u32, - /// Active loops: `(loop_id, iter_index_0based)`. - loop_stack: Vec<(u32, u32)>, - current_span: Span, - current_source: SourceIdentity, - current_module: Option<*const Module>, - diagnostic_frames: Vec, - input: InputFeed, - host: HostContext, - debug: Option>, - /// Entry module pointer for `host_query("call_lib_path")` while plugins run. - site_module: Option<*const Module>, -} - -struct Env { - vars: HashMap, -} - -impl Env { - fn new() -> Self { - Self { - vars: HashMap::new(), - } - } - - /// Phase 2: lift resolved Artifact Metadata into the entry environment. - /// Existing keys are left unchanged (`or_insert` semantics). - fn with_metadata(module: &Module) -> Self { - let mut env = Self::new(); - for (k, v) in &module.metadata { - env.vars.entry(k.clone()).or_insert_with(|| v.clone()); - } - env - } - - fn get(&self, name: &str) -> Option<&Value> { - self.vars.get(name) - } - - fn set(&mut self, name: String, value: Value) { - self.vars.insert(name, value); - } - - fn vars_clone(&self) -> HashMap { - self.vars.clone() - } -} - -pub(crate) enum EvArg { - Positional(Value), - Named(String, Value), -} - -impl Interpreter { - pub fn new(path: Option<&Path>, trace: bool) -> Self { - Self { - path: path.map(|p| p.to_path_buf()), - trace, - capture: false, - captured_stdout: String::new(), - entry_bindings: HashMap::new(), - view_trace: ViewTrace::default(), - next_call_id: 1, - call_stack: Vec::new(), - fn_ordinals: HashMap::new(), - next_loop_id: 1, - loop_stack: Vec::new(), - current_span: Span::new(1, 1), - current_source: SourceIdentity { path: path.map(Path::to_path_buf), sha256: None }, - current_module: None, - diagnostic_frames: Vec::new(), - input: InputFeed::new(false, Vec::new()), - host: HostContext::for_run(path, Default::default(), Vec::new()), - debug: None, - site_module: None, - } - } - - pub fn with_capture(path: Option<&Path>, trace: bool) -> Self { - Self { - path: path.map(|p| p.to_path_buf()), - trace, - capture: true, - captured_stdout: String::new(), - entry_bindings: HashMap::new(), - view_trace: ViewTrace::default(), - next_call_id: 1, - call_stack: Vec::new(), - fn_ordinals: HashMap::new(), - next_loop_id: 1, - loop_stack: Vec::new(), - current_span: Span::new(1, 1), - current_source: SourceIdentity { path: path.map(Path::to_path_buf), sha256: None }, - current_module: None, - diagnostic_frames: Vec::new(), - input: InputFeed::new(true, Vec::new()), - host: HostContext::for_capture(path, Default::default()), - debug: None, - site_module: None, - } - } - - pub fn with_stdin(mut self, lines: Vec) -> Self { - self.input = InputFeed::new(self.capture, lines); - self - } - - pub fn with_host(mut self, host: HostContext) -> Self { - self.host = host; - self - } - - pub fn with_debug(mut self, debug: Arc) -> Self { - self.debug = Some(debug); - self - } - - pub fn take_plots(&mut self) -> Vec { - std::mem::take(&mut self.host.plots) - } - - #[cfg(all(test, feature = "exec-host"))] - pub(crate) fn foreign_source_evidence(&mut self) -> (Vec, Vec, Vec) { - crate::source_refinement_tests::boundary_evidence(&mut self.host) - } - - #[cfg(all(test, feature = "exec-host"))] - pub(crate) fn application_evidence(&self) -> (Vec, Vec, usize) { - (self.host.oracle_observations.clone(), self.host.foreign_protocol_steps.clone(), self.host.foreign_sessions.len()) - } - - #[cfg(all(test, feature = "exec-host"))] - pub(crate) fn causal_replay_evidence(&mut self) -> serde_json::Value { - crate::causal_replay_tests::evidence(&mut self.host) - } - - #[cfg(test)] - pub(crate) fn diagnostic_scope_state(&self) -> (SourceIdentity, usize, Vec, Vec, bool) { - (self.current_source.clone(), self.diagnostic_frames.len(), self.host.call_stack.clone(), - self.host.call_site_lines.clone(), self.current_module.is_some()) - } - - fn err(&self, message: impl Into) -> anyhow::Error { - Diagnostic::new(self.current_source.path.as_deref(), self.current_span, message) - .with_source(&self.current_source).with_frames(&self.diagnostic_frames).into() - } - - fn err_code(&self, code: &str, message: impl Into) -> anyhow::Error { - anyhow::Error::new( - Diagnostic::new(self.current_source.path.as_deref(), self.current_span, message) - .with_source(&self.current_source).with_frames(&self.diagnostic_frames).with_code(code), - ) - } - - fn emit_line(&mut self, text: &str) { - if self.capture { - self.captured_stdout.push_str(text); - self.captured_stdout.push('\n'); - } else { - println!("{text}"); - } - } - - fn emit_prompt(&mut self, prompt: &str) { - if prompt.is_empty() { - return; - } - if self.capture { - self.captured_stdout.push_str(prompt); - } else { - print!("{prompt}"); - use std::io::Write; - let _ = std::io::stdout().flush(); - } - } - - fn current_call_id(&self) -> u32 { - self.call_stack.last().copied().unwrap_or(0) - } - - fn loop_ctx(&self) -> (Option, Option) { - self.loop_stack - .last() - .map(|(id, iter)| (Some(*id), Some(*iter))) - .unwrap_or((None, None)) - } - - fn push_view_call(&mut self, fun: &Function, env: &Env) { - if !self.capture { - return; - } - let call_id = self.next_call_id; - self.next_call_id += 1; - let ordinal = { - let e = self.fn_ordinals.entry(fun.name.clone()).or_insert(0); - *e += 1; - *e - }; - let args_brief = fun - .params - .iter() - .filter_map(|p| { - env.get(&p.name) - .map(|v| format!("{}={}", p.name, brief_trace_val(v))) - }) - .collect::>() - .join(", "); - self.view_trace.calls.push(CallFrame { - call_id, - fn_name: fun.name.clone(), - fn_line: fun.span.line, - call_line: self.current_span.line, - ordinal, - args_brief, - }); - self.call_stack.push(call_id); - } - - fn pop_view_call(&mut self) { - if self.capture { - self.call_stack.pop(); - } - } - - fn begin_view_loop( - &mut self, - line: u32, - item: Option<&str>, - collection: Option<&str>, - ) -> u32 { - let loop_id = self.next_loop_id; - self.next_loop_id += 1; - self.view_trace.loop_frames.push(LoopFrame { - loop_id, - line, - item_name: item.map(|s| s.to_string()), - collection: collection.map(|s| s.to_string()), - iterations: Vec::new(), - }); - self.loop_stack.push((loop_id, 0)); - loop_id - } - - fn enter_loop_iter(&mut self, loop_id: u32, index: u32, item_value: &str) { - if let Some((_, cur)) = self.loop_stack.iter_mut().rev().find(|(id, _)| *id == loop_id) - { - *cur = index; - } - let call_id = self.current_call_id(); - if let Some(fr) = self - .view_trace - .loop_frames - .iter_mut() - .find(|f| f.loop_id == loop_id) - { - fr.iterations.push(LoopIter { - index, - item_value: item_value.to_string(), - call_id, - }); - } - } - - fn end_view_loop(&mut self, loop_id: u32) { - if self - .loop_stack - .last() - .map(|(id, _)| *id == loop_id) - .unwrap_or(false) - { - self.loop_stack.pop(); - } - } - - fn record_stmt_event(&mut self, mut ev: StmtEvent) { - if self.capture { - if ev.loop_id.is_none() || ev.iter.is_none() { - let (lid, iter) = self.loop_ctx(); - if ev.loop_id.is_none() { - ev.loop_id = lid; - } - if ev.iter.is_none() { - ev.iter = iter; - } - } - self.view_trace.events.push(ev); - } - } - - fn record_branch_hit(&mut self, line: u32, arm_index: usize) { - let call_id = self.current_call_id(); - if let Some(existing) = self.view_trace.branches.iter_mut().find(|h| { - h.line == line && h.arm_index == arm_index && h.call_id == call_id - }) { - existing.count += 1; - } else { - self.view_trace.branches.push(BranchHit { - line, - arm_index, - count: 1, - call_id, - }); - } - let (loop_id, iter) = self.loop_ctx(); - self.record_stmt_event(StmtEvent { - line, - kind: StmtEventKind::Branch, - name: None, - value_after: Some(format!("arm {}", arm_index + 1)), - arm_index: Some(arm_index), - iter, - call_id, - loop_id, - }); - } - - fn record_loop_hit(&mut self, line: u32, iterations: u32, last_item: Option) { - if let Some(existing) = self.view_trace.loops.iter_mut().find(|h| h.line == line) { - existing.iterations = iterations; - if last_item.is_some() { - existing.last_item = last_item.clone(); - } - } else { - self.view_trace.loops.push(LoopHit { - line, - iterations, - last_item: last_item.clone(), - }); - } - let (loop_id, _) = self.loop_ctx(); - self.record_stmt_event(StmtEvent { - line, - kind: StmtEventKind::Loop, - name: None, - value_after: Some(format!("{iterations} iters")), - arm_index: None, - // Summary event: total count (not 0-based index). - iter: Some(iterations), - call_id: self.current_call_id(), - loop_id, - }); - } - - /// Run a function by name anywhere in the module (for `lib/subtask` workers). - pub fn invoke_function( - &mut self, - module: &Module, - name: &str, - args: &[(String, Value)], - ) -> Result { - let fun = find_function_anywhere(module, name) - .ok_or_else(|| self.err(format!("unknown function `{name}`")))?; - self.invoke_bound_function(module, fun, args) - } - - /// Run an already-bound function node (SymbolId / source-line identity). - /// Prefer this over name lookup so nested same-named functions cannot drift (G07). - pub fn invoke_bound_function( - &mut self, - module: &Module, - fun: &Function, - args: &[(String, Value)], - ) -> Result { - let previous=self.site_module; - self.site_module=Some(module as *const Module); - let result=self.run_function(module, fun, Env::new(), args, false); - self.site_module=previous; - result - } - - /// Bind named arguments for an external call. Unknown names, missing - /// required parameters, and contract mismatches are errors. Defaults run. - pub fn bind_external_args( - &mut self, - module: &Module, - fun: &Function, - args: &[(String, Value)], - ) -> Result> { - let previous=self.site_module; - self.site_module=Some(module as *const Module); - let result=self.in_function_source(module, fun, |this| this.bind_external_args_inner(module, fun, args)); - self.site_module=previous; - result - } - - fn bind_external_args_inner( - &mut self, - module: &Module, - fun: &Function, - args: &[(String, Value)], - ) -> Result> { - self.current_span = fun.span; - self.host.current_line = fun.span.line; - let mut named: HashMap = HashMap::new(); - for (k, v) in args { - if named.insert(k.clone(), v.clone()).is_some() { - return Err(self.err_code( - "call.duplicate_arg", - format!("duplicate named argument `{k}`"), - )); - } - } - for k in named.keys() { - if !fun.params.iter().any(|p| &p.name == k) { - return Err(self.err_code( - "call.unknown_arg", - format!("unknown argument `{k}`"), - )); - } - } - let ev: Vec = named - .into_iter() - .map(|(k, v)| EvArg::Named(k, v)) - .collect(); - let mut env = Env::new(); - let bound = bind_function_args(self, module, fun, &mut env, &fun.params, &ev, false) - .map_err(|error| { - if Diagnostic::find(&error).is_some() { return error; } - let m = error.to_string(); - if m.starts_with("missing argument") { - self.err_code("call.missing_arg", m) - } else if m.starts_with("duplicate named argument") { - self.err_code("call.duplicate_arg", m) - } else { - self.err(m) - } - })?; - if let Some(c) = &fun.contract { - if let Some(d) = crate::contract::call_arg_diag( - c, - &fun.name, - &bound, - self.current_source.path.as_deref(), - fun.span, - ) { - return Err(d.into()); - } - } - let mut out = Vec::new(); - for p in &fun.params { - if let Some(v) = bound.get(&p.name) { - out.push((p.name.clone(), v.clone())); - } - } - Ok(out) - } - - fn argument_error(&self, error: anyhow::Error) -> anyhow::Error { - if Diagnostic::find(&error).is_some() { error } else { self.err(error.to_string()) } - } - - /// Call a function using (and updating) [`Self::entry_bindings`] from `# main`. - /// Used by browser WASM sessions so handlers share state with the entry object. - pub fn invoke_in_entry( - &mut self, - module: &Module, - name: &str, - args: &[(String, Value)], - ) -> Result { - let fun = find_function_anywhere(module, name) - .ok_or_else(|| self.err(format!("unknown function `{name}`")))?; - let mut env = Env::with_metadata(module); - for (k, v) in &self.entry_bindings { - env.set(k.clone(), v.clone()); - } - let prev = self.site_module; - self.site_module = Some(module as *const Module); - let result = self.run_function(module, fun, env, args, true); - self.site_module = prev; - result - } - - /// Evaluate only the entry object's top-level assignments, without running - /// calls/returns/control flow. This is the view plan's language-native - /// projection: cell tables are ordinary Marqdo values, not source scans. - /// Evaluate selected entry bindings plus their assignment dependencies. - /// This is the view plan's language-native projection: cell tables are - /// ordinary Marqdo values, not source scans. - pub fn capture_declarations( - &mut self, - module: &Module, - names: &[&str], - ) -> Result> { - let prev = self.site_module; - self.site_module = Some(module as *const Module); - let result = (|| { - let entry = find_top(module, "main").or_else(|| { - let entries: Vec<&Function> = module - .functions - .iter() - .filter(|f| f.is_object() && f.params.is_empty()) - .collect(); - if entries.len() == 1 { - Some(entries[0]) - } else { - None - } - }); - let entry = entry.ok_or_else(|| self.err("no `# main` object to inspect"))?; - let assignments: std::collections::HashMap<&str, &Expr> = entry - .body - .iter() - .filter_map(|stmt| match stmt { - Stmt::Assign { name, value, .. } => Some((name.as_str(), value)), - _ => None, - }) - .collect(); - let mut env = Env::with_metadata(module); - let mut done = std::collections::HashSet::new(); - let mut visiting = std::collections::HashSet::new(); - - fn resolve( - this: &mut Interpreter, - module: &Module, - fun: &Function, - assignments: &std::collections::HashMap<&str, &Expr>, - name: &str, - env: &mut Env, - done: &mut std::collections::HashSet, - visiting: &mut std::collections::HashSet, - ) -> Result<()> { - if done.contains(name) { - return Ok(()); - } - if !visiting.insert(name.to_string()) { - return Err(this.err(format!("cyclic view-plan binding `{name}`"))); - } - let Some(expr) = assignments.get(name) else { - visiting.remove(name); - return Ok(()); - }; - let mut deps = std::collections::HashSet::new(); - collect_decl_reads(expr, &mut deps); - for dep in deps { - if assignments.contains_key(dep.as_str()) && env.get(&dep).is_none() { - resolve(this, module, fun, assignments, &dep, env, done, visiting)?; - } - } - let value = this.eval_expr(module, fun, env, expr)?; - env.set(name.to_string(), value); - done.insert(name.to_string()); - visiting.remove(name); - Ok(()) - } - - for name in names { - resolve( - self, - module, - entry, - &assignments, - name, - &mut env, - &mut done, - &mut visiting, - )?; - } - self.entry_bindings = env.vars_clone(); - Ok(self.entry_bindings.clone()) - })(); - self.site_module = prev; - result - } - - pub fn run_module(&mut self, module: &Module) -> Result { - let prev = self.site_module; - self.site_module = Some(module as *const Module); - let result = (|| { - if let Some(main) = find_top(module, "main") { - return self.run_function(module, main, Env::with_metadata(module), &[], true); - } - // Document-as-entry: sole top-level `#` object with no params (e.g. `# Hello World`). - let entries: Vec<&Function> = module - .functions - .iter() - .filter(|f| f.is_object() && f.params.is_empty()) - .collect(); - if entries.len() == 1 { - return self.run_function( - module, - entries[0], - Env::with_metadata(module), - &[], - true, - ); - } - // Web Artifact entry (ADR 0007): `type: web|endpoint` may be pure document — - // no `# main`. Return a Result-shaped summary for run/check gold paths. - if let Some(value) = crate::artifact::declaration_summary(module) { - return Ok(value); - } - bail!("no `# main` object to run"); - })(); - self.site_module = prev; - result - } - - - /// Pin `module` as site and call `lib.member` (isolated worker / CLI `--call-lib-path`). - pub fn run_site_lib_path( - &mut self, - module: &Module, - path: &str, - args: Option<&Value>, - ) -> std::result::Result { - let prev = self.site_module; - self.site_module = Some(module as *const Module); - let out = self.call_site_lib_path(path, args); - self.site_module = prev; - out - } - - /// Resolve `lib.member` on the site (entry) module — used by ABI `call_lib_path`. - pub(crate) fn call_site_lib_path( - &mut self, - path: &str, - args: Option<&Value>, - ) -> std::result::Result { - let site = self - .site_module - .ok_or_else(|| "call_lib_path: no site module".to_string())?; - let site = unsafe { &*site }; - let parts: Vec = path - .split('.') - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - .collect(); - if parts.len() < 2 { - return Err(format!( - "call_lib_path: need `lib.member`, got `{path}`" - )); - } - let mut ev_args: Vec = Vec::new(); - if let Some(Value::Map(pairs)) = args { - for (k, v) in pairs { - ev_args.push(EvArg::Named(k.clone(), v.clone())); - } - } - self.eval_path_call(site, &parts, &ev_args) - .map_err(|e| e.to_string()) - } - - fn call_plugin_registered( - &mut self, - name: &str, - bound: &HashMap, - ) -> std::result::Result { - struct HookData { - interp: *mut Interpreter, - } - fn trampoline( - data: *mut (), - path: &str, - args: Option<&Value>, - ) -> std::result::Result { - let data = unsafe { &mut *(data as *mut HookData) }; - let interp = unsafe { &mut *data.interp }; - interp.call_site_lib_path(path, args) - } - let mut data = HookData { - interp: self as *mut Interpreter, - }; - let hook = crate::host::plugin::LibPathCall { - call: trampoline, - data: &mut data as *mut HookData as *mut (), - }; - crate::host::plugin::with_lib_path_call(hook, || { - crate::host::plugin::call_registered(&mut self.host, name, bound) - }) - } - - fn run_function( - &mut self, - module: &Module, - fun: &Function, - env: Env, - args: &[(String, Value)], - capture_entry_env: bool, - ) -> Result { - self.in_function_source(module, fun, |this| { - this.run_function_inner(module, fun, env, args, capture_entry_env) - }) - } - - fn in_function_source( - &mut self, - module: &Module, - fun: &Function, - run: impl FnOnce(&mut Self) -> Result, - ) -> Result { - let mut source = module.source.clone(); - if source.path.is_none() { - if self.diagnostic_frames.is_empty() { - source.path = self.path.clone(); - } else if self.current_module == Some(module as *const Module) { - source.path = self.current_source.path.clone(); - } - } - let caller = (!self.diagnostic_frames.is_empty()).then(|| self.current_source.at(self.current_span)); - let previous_source = std::mem::replace(&mut self.current_source, source); - let previous_module = self.current_module.replace(module as *const Module); - let previous_span = std::mem::replace(&mut self.current_span, fun.span); - let previous_line = self.host.current_line; - self.diagnostic_frames.push(DiagnosticFrame { - function: fun.name.clone(), declaration: self.current_source.at(fun.span), call_site: caller, - }); - let result = run(self) - .map_err(|error| { - if let Some(mut diagnostic) = Diagnostic::find(&error).cloned() { - if diagnostic.source_sha256.is_none() && diagnostic.path == self.current_source.path { - diagnostic.source_sha256 = self.current_source.sha256.clone(); - } - if diagnostic.frames.is_empty() { diagnostic.frames = self.diagnostic_frames.clone(); } - diagnostic.into() - } else { self.err(error.to_string()) } - }); - self.diagnostic_frames.pop(); - self.current_source = previous_source; - self.current_module = previous_module; - self.current_span = previous_span; - self.host.current_line = previous_line; - result - } - - fn run_function_inner( - &mut self, - module: &Module, - fun: &Function, - mut env: Env, - args: &[(String, Value)], - capture_entry_env: bool, - ) -> Result { - if self.trace { - emit_trace( - self.current_source.path.as_deref(), - Some(fun.span), - "enter_fn", - &[("fn", fun.name.as_str())], - ); - } - for (k, v) in args { - env.set(k.clone(), v.clone()); - } - // Raw/named entry APIs and document metadata must use the same default - // semantics as ordinary calls. Already bound defaults are supplied - // values here and therefore never execute a second time. - let supplied=env.vars.iter().map(|(name,value)|EvArg::Named(name.clone(),value.clone())).collect::>(); - let completed=bind_function_args(self,module,fun,&mut env,&fun.params,&supplied,true)?; - for (name,value) in completed { env.set(name,value); } - for p in &fun.params { - if env.get(&p.name).is_none() { - env.set(p.name.clone(), Value::None); - } - } - - if let Some(contract)=&fun.contract { - if let Some(diag)=crate::contract::call_arg_diag(contract,&fun.name,&env.vars,self.current_source.path.as_deref(),fun.span) { - return Err(diag.into()); - } - } - let ret = Value::None; - self.push_view_call(fun, &env); - self.host.push_call_frame(&fun.name); - let body_result = (|| -> Result { - for stmt in &fun.body { - if let Some(v) = self.exec_stmt(module, fun, &mut env, stmt)? { - return Ok(v); - } - } - Ok(ret) - })(); - self.host.pop_call_frame(); - self.pop_view_call(); - let ret = body_result?; - if capture_entry_env { - self.entry_bindings = env.vars_clone(); - } - if self.trace { - let display = ret.as_display(); - emit_trace( - self.current_source.path.as_deref(), - Some(fun.span), - "leave_fn", - &[("fn", fun.name.as_str()), ("value", display.as_str())], - ); - } - Ok(ret) - } - - fn exec_stmt( - &mut self, - module: &Module, - fun: &Function, - env: &mut Env, - stmt: &Stmt, - ) -> Result> { - let span = stmt_span(stmt); - self.current_span = span; - self.host.current_line = span.line; - if let Some(dbg) = &self.debug { - dbg.on_stmt(span.line, &fun.name, &env.vars, &self.captured_stdout) - .map_err(|m| self.err(m))?; - } - match stmt { - Stmt::Assign { name, value, span, .. } => { - self.current_span = *span; - let v = self.eval_expr(module, fun, env, value)?; - // 契约边界 3(T2.2):表绑定 vs 字段契约。 - if let Some(c) = fun.var_contracts.get(name) { - if let Some(d) = - crate::contract::fields_diag(c, name, &v, self.current_source.path.as_deref(), *span) - { - return Err(d.into()); - } - } - if self.trace { - let display = v.as_display(); - emit_trace( - self.current_source.path.as_deref(), - Some(*span), - "stmt", - &[ - ("kind", "assign"), - ("name", name.as_str()), - ("value", display.as_str()), - ], - ); - } - if self.capture { - self.record_stmt_event(StmtEvent { - line: span.line, - kind: StmtEventKind::Assign, - name: Some(name.clone()), - value_after: Some(v.as_display()), - arm_index: None, - iter: None, - call_id: self.current_call_id(), - loop_id: None, - }); - } - env.set(name.clone(), v); - Ok(None) - } - Stmt::Return { value, span } => { - self.current_span = *span; - let v = self.eval_expr(module, fun, env, value)?; - // 契约边界 2(T2.2):返回值 vs 返回契约。 - if let Some(c) = &fun.contract { - if let Some(d) = - crate::contract::return_diag(c, &fun.name, &v, self.current_source.path.as_deref(), *span) - { - return Err(d.into()); - } - } - if self.trace { - let display = v.as_display(); - emit_trace( - self.current_source.path.as_deref(), - Some(*span), - "stmt", - &[("kind", "return"), ("value", display.as_str())], - ); - } - if self.capture { - self.record_stmt_event(StmtEvent { - line: span.line, - kind: StmtEventKind::Return, - name: None, - value_after: Some(v.as_display()), - arm_index: None, - iter: None, - call_id: self.current_call_id(), - loop_id: None, - }); - } - Ok(Some(v)) - } - Stmt::Call { call, span } => { - self.current_span = *span; - if self.trace { - emit_trace( - self.current_source.path.as_deref(), - Some(*span), - "stmt", - &[("kind", "call"), ("callee", call.callee.as_str())], - ); - } - let stdout_before = self.captured_stdout.len(); - let v = self.eval_call(module, fun, env, call)?; - if self.capture { - let (loop_id, iter) = self.loop_ctx(); - self.record_stmt_event(StmtEvent { - line: span.line, - kind: StmtEventKind::Call, - name: Some(call.callee.clone()), - value_after: Some(call_event_brief( - &v, - &self.captured_stdout, - stdout_before, - &call.callee, - )), - arm_index: None, - iter, - call_id: self.current_call_id(), - loop_id, - }); - } - Ok(None) - } - Stmt::Expr { value, span } => { - self.current_span = *span; - if self.trace { - emit_trace( - self.current_source.path.as_deref(), - Some(*span), - "stmt", - &[("kind", "expr")], - ); - } - let stdout_before = self.captured_stdout.len(); - let v = self.eval_expr(module, fun, env, value)?; - if self.capture { - let (loop_id, iter) = self.loop_ctx(); - let name = match value { - Expr::Call(c) => Some(c.callee.clone()), - _ => None, - }; - self.record_stmt_event(StmtEvent { - line: span.line, - kind: StmtEventKind::Call, - name: name.clone(), - value_after: Some(call_event_brief( - &v, - &self.captured_stdout, - stdout_before, - name.as_deref().unwrap_or("expr"), - )), - arm_index: None, - iter, - call_id: self.current_call_id(), - loop_id, - }); - } - Ok(None) - } - Stmt::Branch { arms, span } => { - self.current_span = *span; - if self.trace { - emit_trace( - self.current_source.path.as_deref(), - Some(*span), - "stmt", - &[("kind", "branch")], - ); - } - for (arm_index, arm) in arms.iter().enumerate() { - let take = match &arm.condition { - None => true, - Some(cond) => self.eval_expr(module, fun, env, cond)?.truthy(), - }; - if take { - if self.capture { - self.record_branch_hit(span.line, arm_index); - } - for s in &arm.body { - if let Some(v) = self.exec_stmt(module, fun, env, s)? { - return Ok(Some(v)); - } - } - break; - } - } - Ok(None) - } - Stmt::While { - condition, - body, - span, - } => { - self.current_span = *span; - if self.trace { - emit_trace( - self.current_source.path.as_deref(), - Some(*span), - "stmt", - &[("kind", "while")], - ); - } - let loop_id = if self.capture { - Some(self.begin_view_loop(span.line, None, None)) - } else { - None - }; - let mut guard = 0u32; - loop { - self.current_span=*span; - self.host.current_line=span.line; - if !self.eval_expr(module,fun,env,condition)?.truthy(){break;} - guard += 1; - if guard > 1_000_000 { - return Err(self.err("while loop exceeded iteration limit")); - } - if let Some(lid) = loop_id { - self.enter_loop_iter(lid, guard - 1, &format!("iter {guard}")); - } - for s in body { - if let Some(v) = self.exec_stmt(module, fun, env, s)? { - if self.capture { - if let Some(lid) = loop_id { - self.end_view_loop(lid); - } - self.record_loop_hit(span.line, guard, None); - } - return Ok(Some(v)); - } - } - } - if self.capture { - if let Some(lid) = loop_id { - self.end_view_loop(lid); - } - self.record_loop_hit(span.line, guard, None); - } - Ok(None) - } - Stmt::ForEach { - item, - collection, - label: _, - body, - span, - } => { - self.current_span = *span; - if self.trace { - emit_trace( - self.current_source.path.as_deref(), - Some(*span), - "stmt", - &[ - ("kind", "foreach"), - ("item", item.as_str()), - ("collection", collection.as_str()), - ], - ); - } - let coll = env.get(collection).cloned().ok_or_else(|| { - self.err(format!("undefined collection `{collection}`")) - })?; - let items = match builtin_iter_items(&coll) { - Ok(Value::List(xs)) => xs, - Ok(_) => unreachable!(), - Err(m) => return Err(self.err(m)), - }; - let loop_id = if self.capture { - Some(self.begin_view_loop( - span.line, - Some(item.as_str()), - Some(collection.as_str()), - )) - } else { - None - }; - let mut iterations = 0u32; - let mut last_item: Option = None; - for val in items { - let index = iterations; - iterations += 1; - let display = val.as_display(); - last_item = Some(display.clone()); - if let Some(lid) = loop_id { - self.enter_loop_iter(lid, index, &display); - self.record_stmt_event(StmtEvent { - line: span.line, - kind: StmtEventKind::BindRef, - name: Some(item.clone()), - value_after: Some(format!( - "{collection}[{index}]={display}" - )), - arm_index: None, - iter: Some(index), - call_id: self.current_call_id(), - loop_id: Some(lid), - }); - } - env.set(item.clone(), val); - for s in body { - if let Some(v) = self.exec_stmt(module, fun, env, s)? { - if self.capture { - if let Some(lid) = loop_id { - self.end_view_loop(lid); - } - self.record_loop_hit(span.line, iterations, last_item.clone()); - } - return Ok(Some(v)); - } - } - } - if self.capture { - if let Some(lid) = loop_id { - self.end_view_loop(lid); - } - self.record_loop_hit(span.line, iterations, last_item); - } - Ok(None) - } - } - } - - fn resolve_index_key( - &mut self, - _module: &Module, - _fun: &Function, - env: &mut Env, - label: &IndexKey, - ) -> Result { - match label { - IndexKey::Lit(s) => Ok(s.clone()), - IndexKey::Var(name) => { - let v = env.get(name).cloned().ok_or_else(|| { - self.err(format!("undefined variable `{name}` in footnote key")) - })?; - Ok(v.as_display()) - } - } - } - - fn eval_expr( - &mut self, - module: &Module, - fun: &Function, - env: &mut Env, - expr: &Expr, - ) -> Result { - match expr { - Expr::Literal(lit) => Ok(lit_to_value(lit)), - Expr::Var(name) => env - .get(name) - .cloned() - .ok_or_else(|| self.err(format!("undefined variable `{name}`"))), - Expr::Interp(parts) => { - let mut s = String::new(); - for part in parts { - match part { - InterpPart::Lit(t) => s.push_str(t), - InterpPart::Var(n) => { - let v = env - .get(n) - .ok_or_else(|| self.err(format!("undefined variable `{n}`")))?; - s.push_str(&v.as_display()); - } - InterpPart::Index { base, labels } => { - let mut v = env.get(base).cloned().ok_or_else(|| { - self.err(format!("undefined variable `{base}`")) - })?; - for label in labels { - v = builtin_footnote_get(&v, label).map_err(|m| self.err(m))?; - } - s.push_str(&v.as_display()); - } - } - } - Ok(Value::Text(s)) - } - Expr::Unary { op, expr } => { - let value=self.eval_expr(module,fun,env,expr)?; - crate::builtin::eval_unary(*op,&value).map_err(|message|self.err(message)) - } - Expr::Binary { op, left, right } => { - let l = self.eval_expr(module, fun, env, left)?; - match op { - BinaryOp::And => { - if !l.truthy() { - return Ok(Value::Bool(false)); - } - let r = self.eval_expr(module, fun, env, right)?; - return Ok(Value::Bool(r.truthy())); - } - BinaryOp::Or => { - if l.truthy() { - return Ok(Value::Bool(true)); - } - let r = self.eval_expr(module, fun, env, right)?; - return Ok(Value::Bool(r.truthy())); - } - _ => {} - } - let r = self.eval_expr(module, fun, env, right)?; - if let Some(v) = crate::linalg_ops::try_matrix_binary( - &mut self.host, - *op, - &l, - &r, - ) - .map_err(|e| self.err(e))? - { - return Ok(v); - } - crate::builtin::eval_binary(*op, &l, &r).map_err(|e| self.err(e.to_string())) - } - Expr::Call(call) => self.eval_call(module, fun, env, call), - Expr::List(items) => { - let mut out = Vec::new(); - for it in items { - out.push(self.eval_expr(module, fun, env, it)?); - } - Ok(Value::List(out)) - } - Expr::Map(pairs) => { - let mut out = Vec::new(); - for (k, e) in pairs { - out.push((k.clone(), self.eval_expr(module, fun, env, e)?)); - } - Ok(Value::Map(out)) - } - Expr::Index { base, label } => { - let v = self.eval_expr(module, fun, env, base)?; - let key = self.resolve_index_key(module, fun, env, label)?; - // 契约边界 4(T2.2):字段访问 vs 字段契约——键存在性**先于**取值 - // (契约诊断优先于运行时 `missing map key`)。 - if let Expr::Var(name) = base.as_ref() { - if let Some(c) = fun.var_contracts.get(name) { - if let Some(d) = crate::contract::index_diag( - c, - name, - &key, - &Value::None, - self.current_source.path.as_deref(), - self.current_span, - ) { - return Err(d.into()); - } - } - } - let out = builtin_footnote_get(&v, &key).map_err(|m| self.err(m))?; - if let Expr::Var(name) = base.as_ref() { - if let Some(c) = fun.var_contracts.get(name) { - if let Some(d) = crate::contract::index_diag( - c, - name, - &key, - &out, - self.current_source.path.as_deref(), - self.current_span, - ) { - return Err(d.into()); - } - } - } - Ok(out) - } - Expr::Formula(e) => Ok(Value::Formula(e.clone())), - Expr::Code(c) => Ok(Value::Code(c.clone())), - // `` M2: the label is inert prose; only the payload evaluates. - Expr::Occluded { payload, .. } => match payload { - Some(inner) => self.eval_expr(module, fun, env, inner), - None => Ok(Value::None), - }, - } - } - - fn eval_call( - &mut self, - module: &Module, - fun: &Function, - env: &mut Env, - call: &CallExpr, - ) -> Result { - let mut call = call.clone(); - // Method callees keep author names (`绘图` on quantum ≠ math `host_plot`). - if call.path.is_none() && call.receiver.is_none() { - let callee = crate::aliases::normalize_call_callee_and_args( - &call.callee, - &mut call.args, - ); - call.callee = callee; - } - - for m in &call.pre_modifiers { - if call.args.iter().any(|a| matches!(a, Arg::Named { name, .. } if name == m)) { - return Err(self.err(format!( - "pre-bracket modifier `{m}` conflicts with named argument `{m}`" - ))); - } - } - - let mut ev_args = Vec::new(); - for m in &call.pre_modifiers { - ev_args.push(EvArg::Named(m.clone(), Value::Bool(true))); - } - for arg in &call.args { - match arg { - Arg::Positional(e) => { - ev_args.push(EvArg::Positional(self.eval_expr(module, fun, env, e)?)); - } - Arg::Named { name, value } => { - ev_args.push(EvArg::Named( - name.clone(), - self.eval_expr(module, fun, env, value)?, - )); - } - } - } - - if let Some(recv_name) = &call.receiver { - return self.eval_method_call(module, fun, env, recv_name, &call.callee, &ev_args); - } - - // Local-var method sugar (`a.b` when `a` is in env) before BoundCall path resolve. - if let Some(path) = &call.path { - if path.len() == 2 - && env.get(&path[0]).is_some() - && !module.import_modules.contains_key(&path[0]) - { - let recv = path[0].clone(); - let method = path[1].clone(); - return self.eval_method_call(module, fun, env, &recv, &method, &ev_args); - } - } - - use crate::sema::bind::{resolve_for_exec, DynamicReason, ExecTarget}; - match resolve_for_exec(module, fun, &call) { - ExecTarget::Local(target) => { - self.eval_bound_function_call(module, fun, env, target, &ev_args) - } - ExecTarget::Import { - lib: lib_mod, - fun: target, - .. - } => self.eval_bound_function_call(lib_mod, fun, env, target, &ev_args), - ExecTarget::Builtin(name) => self.eval_builtin_call(name, &ev_args), - ExecTarget::Host(hf) => { - let mut params: Vec = - hf.required_params().iter().map(|s| (*s).to_string()).collect(); - for p in hf.optional_params() { - params.push((*p).to_string()); - } - let bound = bind_args(¶ms, &ev_args, true).map_err(|m| self.err(m))?; - for req in hf.required_params() { - if !bound.contains_key(*req) { - return Err(self.err(format!("{} requires `{req}`", hf.name()))); - } - } - call_host(&mut self.host, hf, &bound).map_err(|m| self.err(m)) - } - ExecTarget::Dynamic { - reason: DynamicReason::CallFn, - .. - } => { - let bound = bind_args(&["name".into()], &ev_args, false) - .map_err(|m| self.err(m))?; - let name = match bound.get("name") { - Some(Value::Text(s)) => s.as_str(), - _ => return Err(self.err("call_fn requires text name")), - }; - let target = lookup_function(module, fun, name).ok_or_else(|| { - self.err(format!("call_fn: unknown function `{name}`")) - })?; - if !target.params.is_empty() { - return Err(self.err(format!( - "call_fn: `{name}` must have no parameters" - ))); - } - self.run_function(module, target, Env::new(), &[], false) - } - ExecTarget::Dynamic { - reason: DynamicReason::Plugin, - name, - } => { - if let Some(reg) = self.host.plugins.get(&name).cloned() { - let bound = - bind_args(®.params, &ev_args, false).map_err(|m| self.err(m))?; - return self - .call_plugin_registered(&name, &bound) - .map_err(|m| self.err(m)); - } - Err(self.err(format!("unknown function `{name}`"))) - } - ExecTarget::Dynamic { - reason: DynamicReason::MethodReceiver, - name, - } => { - if let Some(path) = &call.path { - if path.len() == 2 && env.get(&path[0]).is_some() { - return self.eval_method_call( - module, - fun, - env, - &path[0], - &path[1], - &ev_args, - ); - } - } - Err(self.err(format!("unresolved dynamic call `{name}`"))) - } - ExecTarget::Unresolved { message, .. } => Err(self.err(message)), - } - } - - /// Invoke a function already resolved via [`crate::sema::bind::resolve_for_exec`]. - fn eval_bound_function_call( - &mut self, - module: &Module, - _caller: &Function, - _env: &mut Env, - target: &Function, - ev_args: &[EvArg], - ) -> Result { - let bound = - bind_function_args(self, module, target, &mut Env::new(), &target.params, ev_args, false) - .map_err(|e| self.argument_error(e))?; - if let Some(c) = &target.contract { - if let Some(d) = crate::contract::call_arg_diag_in( - c, - &target.name, - &bound, - &self.current_source.at(self.current_span), - &module.source, - ) { - return Err(d.into()); - } - } - let mut call_env = Env::new(); - for (k, v) in bound { - call_env.set(k, v); - } - self.host.push_call_site_line(self.host.current_line); - let result = self.run_function(module, target, call_env, &[], false); - self.host.pop_call_site_line(); - let result = result?; - if target.is_object() { - Ok(crate::value::tag_instance(&target.name, &self.object_module_path(module), result)) - } else { - Ok(result) - } - } - - fn eval_builtin_call(&mut self, name: &str, ev_args: &[EvArg]) -> Result { - match name { - "print" => { - let bound = bind_args(&["text".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let text = bound - .get("text") - .map(|v| v.as_display()) - .ok_or_else(|| self.err("print requires text (named or positional)"))?; - self.emit_line(&text); - Ok(Value::None) - } - "input" => { - let bound = bind_args(&["prompt".into()], ev_args, true) - .map_err(|m| self.err(m))?; - let prompt = bound - .get("prompt") - .map(|v| v.as_display()) - .unwrap_or_default(); - let line = if self.capture { - self.emit_prompt(&prompt); - self.input.read_line() - } else if crate::input_feed::stdin_is_tty() { - self.input - .read_line_with_prompt(&prompt) - .map(|(line, _)| line) - } else { - self.emit_prompt(&prompt); - self.input.read_line() - } - .map_err(|e| { - let msg = e.to_string(); - if msg.contains("input needs a line") { - self.err(msg) - } else { - e - } - })?; - Ok(Value::Text(line)) - } - "len" => { - let bound = bind_args(&["value".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let v = bound - .get("value") - .ok_or_else(|| self.err("len requires value"))?; - let n = builtin_len(v).map_err(|m| self.err(m))?; - Ok(Value::Int(n)) - } - "str" => { - let bound = bind_args(&["value".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let v = bound - .get("value") - .ok_or_else(|| self.err("str requires value"))?; - Ok(builtin_str(v)) - } - "int" => { - let bound = bind_args(&["value".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let v = bound - .get("value") - .ok_or_else(|| self.err("int requires value"))?; - let n = builtin_int(v).map_err(|m| self.err(m))?; - Ok(Value::Int(n)) - } - "type" => { - let bound = bind_args(&["value".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let v = bound - .get("value") - .ok_or_else(|| self.err("type requires value"))?; - Ok(builtin_type(v)) - } - "trim" => { - let bound = bind_args(&["value".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let v = bound - .get("value") - .ok_or_else(|| self.err("trim requires value"))?; - builtin_trim(v).map_err(|m| self.err(m)) - } - "split" => { - let bound = bind_args(&["value".into(), "sep".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let value = bound - .get("value") - .ok_or_else(|| self.err("split requires value"))?; - let sep = bound - .get("sep") - .ok_or_else(|| self.err("split requires sep"))?; - builtin_split(value, sep).map_err(|m| self.err(m)) - } - "join" => { - let bound = bind_args(&["value".into(), "sep".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let value = bound - .get("value") - .ok_or_else(|| self.err("join requires value"))?; - let sep = bound - .get("sep") - .ok_or_else(|| self.err("join requires sep"))?; - builtin_join(value, sep).map_err(|m| self.err(m)) - } - "at" => { - let bound = bind_args(&["value".into(), "index".into()], ev_args, false) - .map_err(|m| self.err(m))?; - let value = bound - .get("value") - .ok_or_else(|| self.err("at requires value"))?; - let index = bound - .get("index") - .ok_or_else(|| self.err("at requires index"))?; - builtin_at(value, index).map_err(|m| self.err(m)) - } - other => Err(self.err(format!("unknown builtin `{other}`"))), - } - } - - /// Resolve bare path `lib.member` / `lib.Type.member` (definition-tree addressing). - pub(crate) fn eval_path_call( - &mut self, - module: &Module, - path: &[String], - ev_args: &[EvArg], - ) -> Result { - let (lib, node) = locate_import_function(module, path).map_err(|m| self.err(m))?; - - let bound = { - let mut dummy_env = Env::new(); - bind_function_args( - self, - lib, - node, - &mut dummy_env, - &node.params, - ev_args, - false, - ) - .map_err(|e| self.argument_error(e))? - }; - // 契约边界 1(T2.2):库路径调用的实参 vs 形参契约。 - if let Some(c) = &node.contract { - if let Some(d) = crate::contract::call_arg_diag_in( - c, - &node.name, - &bound, - &self.current_source.at(self.current_span), - &lib.source, - ) { - return Err(d.into()); - } - } - let mut call_env = Env::new(); - for (k, v) in bound { - call_env.set(k, v); - } - - self.host.push_call_site_line(self.host.current_line); - let result = self.run_function(lib, node, call_env, &[], false); - self.host.pop_call_site_line(); - let result = result?; - if node.is_object() { - Ok(crate::value::tag_instance(&node.name, &self.object_module_path(lib), result)) - } else { - Ok(result) - } - } - - fn eval_method_call( - &mut self, - module: &Module, - _fun: &Function, - env: &mut Env, - recv_name: &str, - method: &str, - ev_args: &[EvArg], - ) -> Result { - let recv = env - .get(recv_name) - .cloned() - .ok_or_else(|| self.err(format!("undefined variable `{recv_name}`")))?; - let type_name = instance_type_name(&recv).map_err(|m| self.err(m))?; - // The active root is immutable for this invocation; site_module is - // installed/restored by the public run/call entry points. - let root=unsafe { self.site_module.map(|root| &*root) }.unwrap_or(module); - let namespace=crate::value::instance_module(&recv).map_err(|m|self.err(m))?; - let (class_owner,class)=if let Some(namespace)=namespace { - crate::inherit::object_at_namespace(root,&namespace,&type_name) - .ok_or_else(||self.err(format!("unknown object type `{type_name}` in module `{}`",namespace.join("."))))? - } else { - crate::inherit::resolve_object(module,&type_name).map_err(|m|self.err(m))? - }; - let (owner, _obj, target) = find_method_along_bases(class_owner, class, method) - .ok_or_else(|| { - let chain = crate::inherit::inheritance_chain(class_owner, &type_name) - .into_iter() - .map(|o| o.name.as_str()) - .collect::>() - .join(" → "); - self.err(format!( - "unknown method `{type_name}.{method}` (searched {chain})" - )) - })?; - let mut receiver_env = Env::new(); - receiver_env.set("self".into(), recv.clone()); - receiver_env.set("自".into(), recv.clone()); - let bound = bind_function_args(self, owner, target, &mut receiver_env, &target.params, ev_args, false) - .map_err(|e| self.argument_error(e))?; - // 契约边界 1(T2.2):方法调用的实参 vs 形参契约。 - if let Some(c) = &target.contract { - if let Some(d) = crate::contract::call_arg_diag_in( - c, - &target.name, - &bound, - &self.current_source.at(self.current_span), - &owner.source, - ) { - return Err(d.into()); - } - } - let mut call_env = Env::new(); - for (k, v) in bound { - call_env.set(k, v); - } - call_env.set("自".into(), recv.clone()); - call_env.set("self".into(), recv.clone()); - self.host.push_call_site_line(self.host.current_line); - let result = self.run_function(owner, target, call_env, &[], false); - self.host.pop_call_site_line(); - let result = result?; - if crate::linalg_ops::is_matrix_value(&recv) { - Ok(crate::value::preserve_instance_module(&recv,crate::linalg_ops::retag_matrix_like(&type_name, result))) - } else { - Ok(result) - } - } - - fn object_module_path(&self, module:&Module) -> Vec { - let root=unsafe { self.site_module.map(|root| &*root) }.unwrap_or(module); - crate::inherit::module_namespace(root,module).unwrap_or_default() - } -} - -fn instance_type_name(v: &Value) -> std::result::Result { - match v { - Value::Map(entries) => entries - .iter() - .find(|(k, _)| k == "_type") - .and_then(|(_, v)| match v { - Value::Text(s) => Some(s.clone()), - _ => None, - }) - .ok_or_else(|| "method receiver needs a map with `_type`".into()), - _ => Err("method receiver must be an object map".into()), - } -} - -/// `lib.member` / `lib.Type.member` against frontmatter imports. Does not execute. -pub(crate) fn locate_import_function<'a>( - module: &'a Module, - path: &[String], -) -> Result<(&'a Module, &'a Function), String> { - let display = path.join("."); - if path.len() < 2 { - return Err(format!( - "library path `{display}`: need at least `lib.member`" - )); - } - let lib = module - .import_modules - .get(&path[0]) - .ok_or_else(|| format!("unknown library `{}` (import it in frontmatter)", path[0]))?; - let mut parent_is_object = false; - let mut node = lib - .functions - .iter() - .find(|f| f.name == path[1]) - .ok_or_else(|| format!("unknown `{display}`"))?; - for seg in &path[2..] { - parent_is_object = node.is_object(); - node = node - .children - .iter() - .find(|c| c.name == *seg) - .ok_or_else(|| format!("unknown `{display}`"))?; - } - if parent_is_object && !node.is_object() && crate::ast::function_uses_receiver(node) { - return Err(format!( - "`{display}` is an instance method; call it as `var`.{}", - node.name - )); - } - Ok((lib, node)) -} - -/// Bind evaluated args onto parameter names. Err is a plain message (caller adds span/path). -fn bind_function_args( - interp: &mut Interpreter, - module: &Module, - target: &Function, - initial_env: &mut Env, - params: &[Param], - args: &[EvArg], - allow_missing: bool, -) -> Result> { - let mut named: HashMap = HashMap::new(); - let mut positionals = Vec::new(); - for a in args { - match a { - EvArg::Positional(v) => positionals.push(v.clone()), - EvArg::Named(k, v) => { - if named.contains_key(k) { - return Err(anyhow::anyhow!("duplicate named argument `{k}`")); - } - named.insert(k.clone(), v.clone()); - } - } - } - - let mut out: HashMap = HashMap::new(); - let mut used_named = HashSet::new(); - let mut pos_i = 0usize; - let mut defaults_env = Env::new(); - // Only an explicit receiver crosses into a method's default environment. - for name in ["self", "自"] { - if let Some(value) = initial_env.get(name) { - defaults_env.set(name.into(), value.clone()); - } - } - - for p in params { - if let Some(v) = named.get(&p.name) { - out.insert(p.name.clone(), v.clone()); - used_named.insert(p.name.clone()); - } else if pos_i < positionals.len() { - out.insert(p.name.clone(), positionals[pos_i].clone()); - pos_i += 1; - } else if p.default.is_none() && !allow_missing { - return Err(anyhow::anyhow!("missing argument for parameter `{}`", p.name)); - } - } - if pos_i < positionals.len() { - return Err(anyhow::anyhow!("too many positional arguments ({} extra)", positionals.len() - pos_i)); - } - for (k, v) in named { - if !used_named.contains(&k) && !out.contains_key(&k) { out.insert(k, v); } - } - for (name, value) in &out { defaults_env.set(name.clone(), value.clone()); } - for name in ["self", "自"] { - if let Some(value)=initial_env.get(name) { defaults_env.set(name.into(),value.clone()); } - } - for p in params { - if out.contains_key(&p.name) { continue; } - if let Some(def) = &p.default { - let mut evaluate=|this:&mut Interpreter| { - let previous_span=this.current_span; - let previous_line=this.host.current_line; - this.current_span=p.span; - this.host.current_line=p.span.line; - let result=this.eval_expr(module,target,&mut defaults_env,def); - this.current_span=previous_span; - this.host.current_line=previous_line; - result - }; - let v = if interp.current_module == Some(module as *const Module) - && interp.diagnostic_frames.last().is_some_and(|frame| frame.declaration.span == target.span) - { - evaluate(interp)? - } else { - interp.in_function_source(module, target, evaluate)? - }; - out.insert(p.name.clone(), v); - } - if let Some(value) = out.get(&p.name) { - defaults_env.set(p.name.clone(), value.clone()); - } - } - - Ok(out) -} - -/// Bind evaluated args onto parameter names (host / plugin functions). -fn bind_args( - params: &[String], - args: &[EvArg], - allow_missing: bool, -) -> std::result::Result, String> { - let names=args.iter().map(|a|match a{EvArg::Positional(_)=>None,EvArg::Named(name,_)=>Some(name.clone())}).collect::>(); - let values=args.iter().map(|a|match a{EvArg::Positional(value)|EvArg::Named(_,value)=>value.clone()}).collect::>(); - crate::arguments::bind(params,&names,&values,allow_missing) -} - -fn collect_decl_reads(expr: &Expr, out: &mut std::collections::HashSet) { - match expr { - Expr::Occluded { payload, .. } => { - if let Some(inner) = payload { - collect_decl_reads(inner, out); - } - } - Expr::Var(name) => { - out.insert(name.clone()); - } - Expr::Interp(parts) => { - for part in parts { - match part { - InterpPart::Var(name) => { - out.insert(name.clone()); - } - InterpPart::Index { base, .. } => { - out.insert(base.clone()); - } - InterpPart::Lit(_) => {} - } - } - } - Expr::Index { base, label } => { - collect_decl_reads(base, out); - if let IndexKey::Var(name) = label { - out.insert(name.clone()); - } - } - Expr::Binary { left, right, .. } => { - collect_decl_reads(left, out); - collect_decl_reads(right, out); - } - Expr::Unary { expr, .. } => collect_decl_reads(expr, out), - Expr::List(xs) => { - for x in xs { - collect_decl_reads(x, out); - } - } - Expr::Map(entries) => { - for (_, v) in entries { - collect_decl_reads(v, out); - } - } - Expr::Call(call) => { - if let Some(receiver) = &call.receiver { - out.insert(receiver.clone()); - } - for arg in &call.args { - match arg { - Arg::Positional(e) | Arg::Named { value: e, .. } => { - collect_decl_reads(e, out); - } - } - } - } - Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {} - } -} - -fn find_top<'a>(module: &'a Module, name: &str) -> Option<&'a Function> { - module.functions.iter().find(|f| f.name == name) -} - -/// Resolve `#` object type by name in the entry module or any imported library. -/// Resolve `` `obj`.method `` along the inheritance chain (`_type` first, then bases). -fn find_method_along_bases<'a>( - module: &'a Module, - object: &'a Function, - method: &str, -) -> Option<(&'a Module, &'a Function, &'a Function)> { - let mut owner=module; - let mut obj=object; - let mut seen = std::collections::HashSet::new(); - while seen.insert((owner as *const Module,obj as *const Function)) { - if let Some(target) = obj.children.iter().find(|c| c.name == method) { - return Some((owner, obj, target)); - } - match &obj.base { - Some(base) => { (owner,obj)=crate::inherit::resolve_object(owner,base).ok()?; }, - None => break, - } - } - None -} - -fn find_function_anywhere<'a>(module: &'a Module, name: &str) -> Option<&'a Function> { - for f in &module.functions { - if f.name == name { - return Some(f); - } - if let Some(child) = find_in_tree(f, name) { - return Some(child); - } - } - None -} - -fn lookup_function<'a>( - module: &'a Module, - current: &'a Function, - name: &str, -) -> Option<&'a Function> { - if let Some(f) = find_in_tree(current, name) { - return Some(f); - } - module.functions.iter().find(|f| f.name == name) -} - -fn find_in_tree<'a>(fun: &'a Function, name: &str) -> Option<&'a Function> { - for child in &fun.children { - if child.name == name { - return Some(child); - } - if let Some(f) = find_in_tree(child, name) { - return Some(f); - } - } - None -} - -fn lit_to_value(lit: &Literal) -> Value { - match lit { - Literal::None => Value::None, - Literal::Bool(b) => Value::Bool(*b), - Literal::Int(n) => Value::Int(*n), - Literal::Num(n) => Value::Num(*n), - Literal::Text(s) => Value::Text(s.clone()), - } -} - -fn brief_trace_val(v: &Value) -> String { - let s = v.as_display(); - if s.chars().count() > 24 { - format!("{}…", s.chars().take(24).collect::()) - } else { - s - } -} - -/// Prefer real result; else last stdout line emitted by the call; else callee name. -fn call_event_brief(v: &Value, stdout: &str, stdout_before: usize, callee: &str) -> String { - if !matches!(v, Value::None) { - return brief_trace_val(v); - } - if stdout.len() > stdout_before { - let delta = &stdout[stdout_before..]; - let line = delta - .trim_end() - .lines() - .last() - .unwrap_or(delta.trim_end()); - if !line.is_empty() { - return if line.chars().count() > 48 { - format!("{}…", line.chars().take(48).collect::()) - } else { - line.to_string() - }; - } - } - callee.to_string() -} - -fn stmt_span(stmt: &Stmt) -> Span { - match stmt { - Stmt::Assign { span, .. } - | Stmt::Return { span, .. } - | Stmt::Call { span, .. } - | Stmt::Expr { span, .. } - | Stmt::Branch { span, .. } - | Stmt::While { span, .. } - | Stmt::ForEach { span, .. } => *span, - } -} diff --git a/src/knowledge/capability.rs b/src/knowledge/capability.rs deleted file mode 100755 index 0a1b86e..0000000 --- a/src/knowledge/capability.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! L3 Capability derivation from symbols + modules. - -use crate::knowledge::fingerprint::tokenize_ident; -use crate::knowledge::ir::{CapabilityInfo, Evidence, ModuleInfo, SymbolInfo}; -use crate::knowledge::util::slugify; - -pub fn derive_capabilities( - symbols: &[SymbolInfo], - modules: &[ModuleInfo], -) -> Vec { - let mut caps: Vec = Vec::new(); - - for s in symbols { - if s.kind == "test" { - continue; - } - let (id, name, desc) = if let Some(ref c) = s.capability { - let id = slugify(c); - (id.clone(), c.clone(), s.use_when.clone().unwrap_or_else(|| c.clone())) - } else { - let tokens = tokenize_ident(&s.name); - let name = if tokens.is_empty() { - s.name.clone() - } else { - // module.verb_noun style - let mod_short = s - .module - .rsplit('/') - .next() - .unwrap_or(&s.module) - .replace(".mq.md", ""); - format!("{}.{}", slugify(&mod_short), tokens.join("_")) - }; - let id = slugify(&name); - let desc = s - .use_when - .clone() - .or_else(|| { - modules - .iter() - .find(|m| m.id == s.module) - .and_then(|m| m.responsibility.clone()) - }) - .unwrap_or_else(|| format!("Capability implemented by `{}`", s.name)); - (id, name, desc) - }; - - if let Some(existing) = caps.iter_mut().find(|c| c.id == id) { - if !existing.implemented_by.contains(&s.id) { - existing.implemented_by.push(s.id.clone()); - } - if !existing.modules.contains(&s.module) { - existing.modules.push(s.module.clone()); - } - continue; - } - - caps.push(CapabilityInfo { - id, - name, - description: desc, - implemented_by: vec![s.id.clone()], - modules: vec![s.module.clone()], - status: s.status.clone(), - use_when: s.use_when.clone(), - do_not_use_when: s.do_not_use_when.clone(), - related: s.related.clone(), - evidence: Evidence { - sources: vec![s.resource.clone()], - tests: s.tests.clone(), - ..Evidence::default() - }, - confidence: s.confidence.clone(), - introduced: None, - verified: None, - last_used: None, - last_tested: None, - possible_duplicates: Vec::new(), - }); - } - - // related edges are authored; graph builder adds RelatedTo edges - caps.sort_by(|a, b| a.id.cmp(&b.id)); - caps -} diff --git a/src/knowledge/compile.rs b/src/knowledge/compile.rs deleted file mode 100755 index ef16591..0000000 --- a/src/knowledge/compile.rs +++ /dev/null @@ -1,676 +0,0 @@ -//! Compile KnowledgeGraph into `.marqdo/` projections. - -use std::fs; -use std::path::Path; - -use anyhow::{Context, Result}; -use serde_json::json; - -use crate::knowledge::extract::{extract_graph, ExtractOptions}; -use crate::knowledge::ir::KnowledgeGraph; -use crate::knowledge::util::{module_stem, slugify, yaml_escape}; - -#[derive(Debug, Clone)] -pub struct KnowledgeOptions { - pub path: std::path::PathBuf, - pub out_dir: std::path::PathBuf, -} - -pub fn compile(opts: KnowledgeOptions) -> Result { - // Authoritative execution/binding graph: SemanticProject under `graph/`. - // Legacy EKC retrieval catalog writes only under `ekc/` and must never - // overwrite `graph/edges.json` (G01). - let semantic_root = if opts.path.is_file() { - opts.path.parent().filter(|p| !p.as_os_str().is_empty()) - .unwrap_or_else(|| Path::new(".")).to_path_buf() - } else { - opts.path.clone() - }; - let t0 = std::time::Instant::now(); - let semantic = crate::sema::compile_project(&crate::sema::CompileOptions { - project_root: semantic_root, - entry: opts.path.is_file().then(|| opts.path.clone()), - lock_mode: crate::sema::LockMode::Off, - })?; - let sema_ms = t0.elapsed().as_millis(); - let t1 = std::time::Instant::now(); - crate::sema::write_semantic_projections(&opts.out_dir, &semantic)?; - let sema_write_ms = t1.elapsed().as_millis(); - let extract_opts = ExtractOptions { - path: opts.path.clone(), - out_dir: opts.out_dir.clone(), - }; - let t2 = std::time::Instant::now(); - let graph = extract_graph(&extract_opts)?; - let extract_ms = t2.elapsed().as_millis(); - let t3 = std::time::Instant::now(); - write_projections(&opts.out_dir, &graph)?; - let retrieve_write_ms = t3.elapsed().as_millis(); - let t4 = std::time::Instant::now(); - write_publish_manifest(&opts.out_dir, &semantic, &graph)?; - let manifest_ms = t4.elapsed().as_millis(); - eprintln!( - "marqdo knowledge: {} module(s), {} symbol(s), {} capability(ies), {} knowledge → {} (semantic graph/; retrieval ekc/)", - graph.modules.len(), - graph.symbols.len(), - graph.capabilities.len(), - graph.knowledge.len(), - opts.out_dir.display() - ); - eprintln!( - "marqdo knowledge timing_ms: sema={sema_ms} sema_write={sema_write_ms} extract={extract_ms} retrieve_write={retrieve_write_ms} manifest={manifest_ms} total={}", - t0.elapsed().as_millis() - ); - Ok(graph) -} - -/// M06: associate semantic generation, retrieval generation, and source digests. -fn write_publish_manifest( - out_dir: &Path, - semantic: &crate::sema::Compilation, - graph: &KnowledgeGraph, -) -> Result<()> { - let current = fs::read_to_string(out_dir.join("CURRENT")).unwrap_or_default(); - let generation = current.trim().to_string(); - let source_digest = { - use sha2::{Digest, Sha256}; - let mut h = Sha256::new(); - for a in &semantic.semantics.artifacts { - h.update(a.hashes.artifact.0.as_bytes()); - } - format!("sha256:{:x}", h.finalize()) - }; - let evidence_digest = { - use sha2::{Digest, Sha256}; - let mut h = Sha256::new(); - for a in &semantic.semantics.artifacts { - h.update(a.hashes.evidence.0.as_bytes()); - } - format!("sha256:{:x}", h.finalize()) - }; - let manifest = json!({ - "schema_version": 1, - "kind": "publish_manifest", - "semantic_generation": generation, - "retrieval": { - "ekc_graph": "ekc/graph", - "modules": graph.modules.len(), - "symbols": graph.symbols.len(), - "capabilities": graph.capabilities.len(), - "knowledge": graph.knowledge.len(), - }, - "source_digest": source_digest, - "evidence_digest": evidence_digest, - "excluded_dirs": crate::project::EXCLUDED_DIRS, - "project_id": semantic.semantics.project_id, - }); - let path = out_dir.join("publish_manifest.json"); - fs::write(&path, serde_json::to_string_pretty(&manifest)?) - .with_context(|| format!("write {}", path.display()))?; - Ok(()) -} - -/// Directory for the legacy EKC retrieval projection (not execution authority). -pub fn ekc_graph_dir(out_dir: &Path) -> std::path::PathBuf { - out_dir.join("ekc").join("graph") -} - -/// Path of the full IR snapshot used by warm query paths (preflight/find/reuse). -pub fn ir_snapshot_path(out_dir: &Path) -> std::path::PathBuf { - ekc_graph_dir(out_dir).join("ir.json") -} - -/// Load a previously compiled KnowledgeGraph without re-extracting sources. -/// Prefers `ekc/graph/ir.json`. Does **not** walk the source tree. -pub fn load_graph(out_dir: &Path) -> Result { - let ir_path = ir_snapshot_path(out_dir); - if ir_path.exists() { - let raw = fs::read_to_string(&ir_path) - .with_context(|| format!("read {}", ir_path.display()))?; - let graph: KnowledgeGraph = serde_json::from_str(&raw) - .with_context(|| format!("parse {}", ir_path.display()))?; - return Ok(graph); - } - - let graph_path = ekc_graph_dir(out_dir).join("graph.json"); - let edges_path = ekc_graph_dir(out_dir).join("edges.json"); - if !graph_path.exists() { - anyhow::bail!( - "no EKC retrieval graph at {} — run `marqdo knowledge` first", - graph_path.display() - ); - } - - // Legacy projections without ir.json: edges-only fallback (no source walk). - let edges_raw = fs::read_to_string(&edges_path).unwrap_or_else(|_| "{\"edges\":[]}".into()); - let edges_v: serde_json::Value = serde_json::from_str(&edges_raw)?; - let graph_raw = fs::read_to_string(&graph_path)?; - let graph_v: serde_json::Value = serde_json::from_str(&graph_raw)?; - - let mut edges = Vec::new(); - if let Some(arr) = edges_v.get("edges").and_then(|e| e.as_array()) { - for e in arr { - let kind = crate::knowledge::ir::EdgeKind::parse( - e.get("kind").and_then(|k| k.as_str()).unwrap_or(""), - ); - edges.push(crate::knowledge::ir::Edge { - from: e.get("from").and_then(|v| v.as_str()).unwrap_or("").into(), - to: e.get("to").and_then(|v| v.as_str()).unwrap_or("").into(), - kind, - note: e.get("note").and_then(|v| v.as_str()).map(|s| s.to_string()), - }); - } - } - - Ok(KnowledgeGraph { - repository: crate::knowledge::ir::RepositoryInfo { - title: graph_v - .pointer("/repository/title") - .and_then(|v| v.as_str()) - .unwrap_or("marqdo-project") - .into(), - root: graph_v - .pointer("/repository/root") - .and_then(|v| v.as_str()) - .unwrap_or(".") - .into(), - languages: vec!["marqdo".into()], - module_count: 0, - symbol_count: 0, - capability_count: 0, - knowledge_count: 0, - }, - modules: Vec::new(), - symbols: Vec::new(), - capabilities: Vec::new(), - knowledge: Vec::new(), - edges, - generated_by: graph_v - .pointer("/generated/by") - .and_then(|v| v.as_str()) - .unwrap_or("marqdo") - .into(), - }) -} - -/// Force a full knowledge compile (write path / `--refresh`). -pub fn ensure_compiled(path: &Path, out_dir: &Path) -> Result { - compile(KnowledgeOptions { - path: path.to_path_buf(), - out_dir: out_dir.to_path_buf(), - }) -} - -/// Query path loader: compile if missing (or `refresh`), else hot-load `ir.json`. -pub fn graph_for_query(path: &Path, out_dir: &Path, refresh: bool) -> Result { - if refresh { - return ensure_compiled(path, out_dir); - } - let has_ir = ir_snapshot_path(out_dir).exists(); - let has_graph = ekc_graph_dir(out_dir).join("graph.json").exists(); - if has_ir || has_graph { - return load_graph(out_dir); - } - ensure_compiled(path, out_dir) -} - -fn write_projections(out_dir: &Path, graph: &KnowledgeGraph) -> Result<()> { - let dirs = [ - "catalog/modules", - "catalog/symbols", - "catalog/capabilities", - "knowledge/facts", - "knowledge/decisions", - "knowledge/constraints", - "knowledge/patterns", - "knowledge/failures", - "knowledge/migrations", - "ekc/graph", - "agent/policies", - "agent/skills", - "agent/contexts", - "agent/episodes", - "tests/reuse", - "tests/knowledge", - "tests/retrieval", - ]; - for d in dirs { - fs::create_dir_all(out_dir.join(d)) - .with_context(|| format!("create {}/{}", out_dir.display(), d))?; - } - - // L0 repository - fs::write( - out_dir.join("catalog/repository.mq.md"), - render_repository(graph), - )?; - - // L1 modules - for m in &graph.modules { - let stem = module_stem(&m.resource); - fs::write( - out_dir.join("catalog/modules").join(format!("{stem}.md")), - render_module(m, graph), - )?; - } - - // L2 symbols - for s in &graph.symbols { - let stem = slugify(&s.id.replace("::", "__").replace('/', "__")); - fs::write( - out_dir.join("catalog/symbols").join(format!("{stem}.md")), - render_symbol(s), - )?; - } - - // L3 capabilities - for c in &graph.capabilities { - let stem = slugify(&c.id); - fs::write( - out_dir - .join("catalog/capabilities") - .join(format!("{stem}.md")), - render_capability(c), - )?; - } - - // L4 knowledge - for k in &graph.knowledge { - let dir = out_dir.join("knowledge").join(k.kind.subdir()); - let stem = slugify(&k.id.rsplit('/').next().unwrap_or(&k.id)); - let path = dir.join(format!("{stem}.md")); - let body = if let Some(ref src) = k.source_text { - // Ensure generated marker without destroying authored content - if src.contains("GENERATED by marqdo") { - src.clone() - } else { - format!( - "\n{src}", - k.resource - ) - } - } else { - render_knowledge(k) - }; - fs::write(&path, body)?; - } - - // Retrieval-only EKC graph (must not touch authoritative `graph/`). - let ekc = ekc_graph_dir(out_dir); - let graph_json = serde_json::to_string_pretty(&graph.to_graph_json())?; - fs::write(ekc.join("graph.json"), graph_json)?; - let edges_json = serde_json::to_string_pretty(&graph.to_edges_json())?; - fs::write(ekc.join("edges.json"), edges_json)?; - // Full IR snapshot for warm query paths (preflight/find/reuse) — no re-extract. - let ir_json = serde_json::to_string(&graph)?; - fs::write(ekc.join("ir.json"), ir_json)?; - - // Search index - let index = json!({ - "type": "Marqdo Knowledge Index", - "role": "retrieval_only", - "note": "Not an execution authority; binding uses graph/edges.json (SemanticProject).", - "generated": { "by": graph.generated_by }, - "entries": graph.index_map(), - }); - fs::write( - ekc.join("index.json"), - serde_json::to_string_pretty(&index)?, - )?; - - // Root index.mq.md - fs::write(out_dir.join("index.mq.md"), render_index_mq(graph))?; - - // Augment root catalog.yaml if present (append engineering summary) - write_engineering_summary(out_dir, graph)?; - - Ok(()) -} - -fn write_engineering_summary(out_dir: &Path, graph: &KnowledgeGraph) -> Result<()> { - let path = out_dir.join("engineering.yaml"); - let mut out = String::new(); - out.push_str("# GENERATED by marqdo knowledge — do not edit by hand\n"); - out.push_str("type: Marqdo Engineering Knowledge\n"); - out.push_str(&format!("title: {}\n", yaml_escape(&graph.repository.title))); - out.push_str("generated:\n"); - out.push_str(&format!(" by: {}\n", yaml_escape(&graph.generated_by))); - out.push_str("layers:\n"); - out.push_str(&format!(" modules: {}\n", graph.modules.len())); - out.push_str(&format!(" symbols: {}\n", graph.symbols.len())); - out.push_str(&format!(" capabilities: {}\n", graph.capabilities.len())); - out.push_str(&format!(" knowledge: {}\n", graph.knowledge.len())); - out.push_str(&format!(" edges: {}\n", graph.edges.len())); - out.push_str("capabilities:\n"); - if graph.capabilities.is_empty() { - out.push_str(" []\n"); - } else { - for c in &graph.capabilities { - out.push_str(&format!(" - id: {}\n", yaml_escape(&c.id))); - out.push_str(&format!(" name: {}\n", yaml_escape(&c.name))); - out.push_str(&format!(" status: {}\n", c.status.as_str())); - if !c.implemented_by.is_empty() { - out.push_str(" implemented_by:\n"); - for s in &c.implemented_by { - out.push_str(&format!(" - {}\n", yaml_escape(s))); - } - } - if !c.possible_duplicates.is_empty() { - out.push_str(" possible_duplicates:\n"); - for s in &c.possible_duplicates { - out.push_str(&format!(" - {}\n", yaml_escape(s))); - } - } - } - } - out.push_str("knowledge:\n"); - if graph.knowledge.is_empty() { - out.push_str(" []\n"); - } else { - for k in &graph.knowledge { - out.push_str(&format!(" - id: {}\n", yaml_escape(&k.id))); - out.push_str(&format!(" type: {}\n", k.kind.as_str())); - out.push_str(&format!(" title: {}\n", yaml_escape(&k.title))); - out.push_str(&format!(" status: {}\n", k.status.as_str())); - } - } - fs::write(path, out)?; - Ok(()) -} - -fn render_repository(graph: &KnowledgeGraph) -> String { - let r = &graph.repository; - format!( - r#"--- -type: Marqdo Repository -title: {title} -generated: - by: {by} -status: stable ---- - -# {title} - -> GENERATED by Marqdo Engineering Knowledge Compiler. Do not edit by hand. - -## Repository - -| Field | Value | -|-------|-------| -| Languages | {langs} | -| Modules | {modules} | -| Symbols | {symbols} | -| Capabilities | {caps} | -| Knowledge | {know} | -| Edges | {edges} | - -## Layers - -- L0 Repository — this page -- L1 Modules — `catalog/modules/` -- L2 Symbols — `catalog/symbols/` -- L3 Capabilities — `catalog/capabilities/` -- L4 Engineering Knowledge — `knowledge/` -"#, - title = r.title, - by = graph.generated_by, - langs = r.languages.join(", "), - modules = r.module_count, - symbols = r.symbol_count, - caps = r.capability_count, - know = r.knowledge_count, - edges = graph.edges.len(), - ) -} - -fn render_module(m: &crate::knowledge::ir::ModuleInfo, graph: &KnowledgeGraph) -> String { - let mut exports = String::new(); - if m.exports.is_empty() { - exports.push_str("_None_\n"); - } else { - exports.push_str("| Symbol | Kind |\n|--------|------|\n"); - for e in &m.exports { - let kind = graph - .symbols - .iter() - .find(|s| s.module == m.id && s.name == *e) - .map(|s| s.kind.as_str()) - .unwrap_or("fn"); - exports.push_str(&format!("| `{e}` | {kind} |\n")); - } - } - let resp = m.responsibility.as_deref().unwrap_or("_unspecified_"); - format!( - r#"--- -type: Marqdo Module -title: {title} -resource: {resource} -status: {status} -generated: - by: {by} ---- - -# {title} - -> Auto-generated from `{resource}`. Do not edit by hand. - -## Responsibility - -{resp} - -## Exports - -{exports} -"#, - title = m.title, - resource = m.resource, - status = m.status.as_str(), - by = graph.generated_by, - resp = resp, - exports = exports, - ) -} - -fn render_symbol(s: &crate::knowledge::ir::SymbolInfo) -> String { - let params = if s.params.is_empty() { - "[]".into() - } else { - s.params - .iter() - .map(|p| format!(" - {p}")) - .collect::>() - .join("\n") - }; - let use_when = s.use_when.as_deref().unwrap_or("_unspecified_"); - let do_not = s.do_not_use_when.as_deref().unwrap_or("_unspecified_"); - format!( - r#"--- -type: Function -name: {name} -module: {module} -symbol: {name} -resource: {resource} -status: {status} -visibility: {vis} -fingerprint: {fp} -capability: {cap} -generated: - by: marqdo/knowledge ---- - -# {name} - -## Use when - -{use_when} - -## Do not use when - -{do_not} - -## Signature - -params: -{params} - -## Calls - -{calls} - -## Fingerprint - -``` -{fpt} -``` -"#, - name = s.name, - module = s.module, - resource = s.resource, - status = s.status.as_str(), - vis = s.visibility, - fp = s.fingerprint, - cap = s.capability.as_deref().unwrap_or(""), - use_when = use_when, - do_not = do_not, - params = params, - calls = if s.calls.is_empty() { - "_None_".into() - } else { - s.calls - .iter() - .map(|c| format!("- `{c}`")) - .collect::>() - .join("\n") - }, - fpt = s.fingerprint_text, - ) -} - -fn render_capability(c: &crate::knowledge::ir::CapabilityInfo) -> String { - let use_when = c.use_when.as_deref().unwrap_or(&c.description); - let do_not = c.do_not_use_when.as_deref().unwrap_or("_unspecified_"); - format!( - r#"--- -type: Capability -id: {id} -name: {name} -status: {status} -generated: - by: marqdo/knowledge ---- - -# {name} - -{desc} - -## Use when - -{use_when} - -## Do not use when - -{do_not} - -## Implemented by - -{impls} - -## Possible duplicates - -{dups} -"#, - id = c.id, - name = c.name, - status = c.status.as_str(), - desc = c.description, - use_when = use_when, - do_not = do_not, - impls = if c.implemented_by.is_empty() { - "_None_".into() - } else { - c.implemented_by - .iter() - .map(|s| format!("- `{s}`")) - .collect::>() - .join("\n") - }, - dups = if c.possible_duplicates.is_empty() { - "_None_".into() - } else { - c.possible_duplicates - .iter() - .map(|s| format!("- `{s}`")) - .collect::>() - .join("\n") - }, - ) -} - -fn render_knowledge(k: &crate::knowledge::ir::KnowledgeItem) -> String { - format!( - r#"--- -type: {ty} -id: {id} -title: {title} -status: {status} -generated: - by: marqdo/knowledge ---- - -# {title} - -{summary} -"#, - ty = k.kind.as_str(), - id = k.id, - title = k.title, - status = k.status.as_str(), - summary = k.body_summary, - ) -} - -fn render_index_mq(graph: &KnowledgeGraph) -> String { - format!( - r#"--- -type: Marqdo Engineering Knowledge -title: Engineering Knowledge Index -generated: - by: {by} ---- - -# Engineering Knowledge Index - -> GENERATED. Source of truth remains `*.mq.md`. This tree is a Knowledge Projection. - -## Counts - -| Layer | Count | -|-------|------:| -| Modules | {modules} | -| Symbols | {symbols} | -| Capabilities | {caps} | -| Knowledge | {know} | -| Edges | {edges} | - -## Commands - -``` -marqdo knowledge -marqdo find "query" -marqdo reuse "task" -marqdo duplicate -marqdo impact PATH -marqdo conflicts -marqdo stale -marqdo verify -``` -"#, - by = graph.generated_by, - modules = graph.modules.len(), - symbols = graph.symbols.len(), - caps = graph.capabilities.len(), - know = graph.knowledge.len(), - edges = graph.edges.len(), - ) -} - diff --git a/src/knowledge/composition.rs b/src/knowledge/composition.rs deleted file mode 100644 index 301c513..0000000 --- a/src/knowledge/composition.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! Reusable, independently replayable **restricted** module composition. -//! -//! Scope: pure typed-int forwarding caller and source-constant callee. Two -//! independently compiled Lean modules: caller imports the callee's theorem, -//! not its implementation. Every unmodeled construct fails closed. -//! This is not a theorem about arbitrary Marqdo programs. -use std::{fs,path::Path,time::Duration}; -use anyhow::{Context,Result}; -use serde_json::{json,Value}; -use sha2::{Digest,Sha256}; -use crate::{ - ast::{CallExpr,Expr,Function,Literal,Stmt}, - prove::driver::{Toolchain,compile_import_module}, - sema::ir::{Compilation,SemanticArtifact,BoundCall} -}; -fn sha(input:&[u8])->String{format!("sha256:{:x}",Sha256::digest(input))} -fn lookup<'a>(items:&'a [Function],path:&[&str])->Option<&'a Function>{ - let (first,rest)=path.split_first()?; - let fun=items.iter().find(|f|f.name==*first)?; - if rest.is_empty(){Some(fun)}else{lookup(&fun.children,rest)} -} -fn function(compiled:&Compilation,a:&SemanticArtifact)->Option{ - let raw=fs::read_to_string(compiled.semantics.root.join(&a.source.file)).ok()?; - let doc=crate::parse::parse_source(&raw).ok()?; - let path=a.display_name.split('.').collect::>(); - lookup(&doc.functions,&path).cloned() -} -fn call_inside(expr:&Expr)->Option<&CallExpr>{ - match expr{ - Expr::Call(c)=>Some(c), - Expr::Occluded{payload:Some(inner),..}=>call_inside(inner), - _=>None - } -} -fn forwarded(fun:&Function)->Option<&CallExpr>{ - match fun.body.as_slice(){ - [Stmt::Return{value,..}]=>call_inside(value), - [Stmt::Assign{name,value,..},Stmt::Return{value:Expr::Var(v),..}] - if name==v=>call_inside(value), - _=>None - } -} -fn constant_return(fun:&Function)->Option{ - match fun.body.as_slice(){ - [Stmt::Return{value:Expr::Literal(Literal::Int(n)),..}]=>Some(*n), - [Stmt::Return{value:Expr::Occluded{payload:Some(v),..},..}] => - if let Expr::Literal(Literal::Int(n))=v.as_ref(){Some(*n)}else{None}, - _=>None - } -} -fn claim_is_constant(compiled:&Compilation,owner:&SemanticArtifact,n:i64)->bool{ - // Treat duplicate eligible claims as ambiguity, never as evidence. - // A single matching declaration is required at the exact owner SymbolId. - owner.symbol_id.as_ref().is_some_and(|id| - compiled.semantics.claims.iter().filter(|c| - c.owner==*id - && c.premise.as_deref().map_or(true,|p|p.trim().is_empty()) - && c.conclusion.trim()==format!("结果 = {n}")).count()==1) -} -fn candidate(compiled:&Compilation,call:&BoundCall) - ->Option<(String,String,String,i64)>{ - let ca=compiled.semantics.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.caller) && a.kind=="function")?; - let ce=compiled.semantics.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.target) && a.kind=="function")?; - // The contract is strictly inter-module: local recursion and aliases - // must not inherit an import-composition certificate. - if ca.source.file==ce.source.file || call.caller==call.target{return None} - if !ca.effects.is_pure()||!ce.effects.is_pure() - ||!call.required_effects.is_pure() - ||call.control_blocker.is_some()||!call.path_guards.is_empty(){return None} - let caller=function(compiled,ca)?; - let callee=function(compiled,ce)?; - let forwarded=forwarded(&caller)?; - let runtime=forwarded.for_evaluation().ok()?; - if crate::sema::bind::call_display(&runtime)!=call.call_site - ||compiled.semantics.bound_calls.iter().filter(|item| - item.caller==call.caller).count()!=1 {return None} - if runtime.path.as_ref().is_none()||runtime.receiver.is_some() - ||caller.is_object()||callee.is_object(){return None} - let n=constant_return(&callee)?; - if !claim_is_constant(compiled,ca,n)||!claim_is_constant(compiled,ce,n){ - return None - } - let cs=ca.signature.as_ref()?; - let es=ce.signature.as_ref()?; - if cs.params.len()!=caller.params.len() - ||es.params.len()!=callee.params.len() - ||es.params.len()!=call.args.len() - ||call.args.len()!=runtime.args.len(){return None} - if cs.params.iter().chain(es.params.iter()) - // Marqdo currently canonicalizes int/num/float to "number". - // This certificate is explicitly about the *Lean Int model*, NOT - // all runtime Number variants. Runtime-equivalence remains false. - .any(|p|!p.ty.eq_ignore_ascii_case("number")||!p.required){return None} - let arg_expr=call.args.iter().zip(es.params.iter()).map(|(a,p)|{ - if a.name.as_ref().is_some_and(|x|x!=&p.name){return None} - if let Some(v)=a.integer {return Some(format!("({v} : Int)"))} - let symbol=a.symbol.as_ref()?; - let position=cs.params.iter().position(|x|x.name==*symbol)?; - Some(format!("v{position}")) - }).collect::>>()?.join(" "); - let callee_binders=(0..es.params.len()).map(|i|format!("(v{i} : Int)")) - .collect::>().join(" "); - let caller_binders=(0..cs.params.len()).map(|i|format!("(v{i} : Int)")) - .collect::>().join(" "); - let callee_args=(0..es.params.len()).map(|i|format!("v{i}")) - .collect::>().join(" "); - let caller_args=(0..cs.params.len()).map(|i|format!("v{i}")) - .collect::>().join(" "); - // This callee theorem is verified from the translated source *inside its - // own module*. The caller only imports its proved interface theorem. - let callee_src=format!( - "-- pure typed-int fragment of {}\n\ - def callee {callee_binders} : Int := ({n} : Int)\n\ - theorem callee_contract {callee_binders} : callee {callee_args} = ({n} : Int) := by rfl\n", - ce.artifact_id.0); - let caller_src=format!( - "import CalleeModule\n\ - -- exact forwarded import call from {}\n\ - def caller {caller_binders} : Int := callee {arg_expr}\n\ - theorem caller_contract {caller_binders} : caller {caller_args} = ({n} : Int) := by\n\ - \x20\x20simpa [caller] using (callee_contract {arg_expr})\n", - ca.artifact_id.0); - Some((callee_src,caller_src,format!("{}#{}",ca.artifact_id.0, - ce.artifact_id.0),n)) -} -/// Explain why a caller cannot receive a scoped composition certificate. -/// Missing evidence is reported, never fixed up by guessing call identities. -fn rejection_diagnostics(c:&Compilation,call:&BoundCall)->Value{ - let caller=c.semantics.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.caller)); - let callee=c.semantics.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.target)); - let cf=caller.and_then(|a|function(c,a)); - let ef=callee.and_then(|a|function(c,a)); - let constant=ef.as_ref().and_then(constant_return); - json!({ - "caller_semantics_resolved":caller.is_some(), - "callee_semantics_resolved":callee.is_some(), - "caller_effects":caller.map(|a|a.effects.values()), - "callee_effects":callee.map(|a|a.effects.values()), - "call_effects":call.required_effects.values(), - "caller_forward_shape":cf.as_ref().and_then(forwarded).is_some(), - "caller_ast_body":cf.as_ref().map(|f|format!("{:?}",f.body)), - "callee_ast_body":ef.as_ref().map(|f|format!("{:?}",f.body)), - "callee_constant_return":constant, - "runtime_forward_name":cf.as_ref().and_then(forwarded) - .and_then(|f|f.for_evaluation().ok()) - .map(|c|crate::sema::bind::call_display(&c)), - "bound_call_name":call.call_site, - "caller_bound_call_count":c.semantics.bound_calls.iter() - .filter(|item|item.caller==call.caller).count(), - "caller_has_expected_claim":caller.zip(constant).is_some_and(|(a,n)| - claim_is_constant(c,a,n)), - "callee_has_expected_claim":callee.zip(constant).is_some_and(|(a,n)| - claim_is_constant(c,a,n)), - "caller_signature":caller.and_then(|a|a.signature.as_ref()) - .map(|s|s.params.iter().map(|p|json!({"name":p.name,"type":p.ty, - "required":p.required})).collect::>()), - "callee_signature":callee.and_then(|a|a.signature.as_ref()) - .map(|s|s.params.iter().map(|p|json!({"name":p.name,"type":p.ty, - "required":p.required})).collect::>()), - "actual_arguments":call.args.iter().map(|a|json!({ - "name":a.name,"symbol":a.symbol,"integer":a.integer})).collect::>(), - "path_guards":call.path_guards,"control_blocker":call.control_blocker - }) -} -/// Emit one sealed bundle per eligible call. An unsuccessful Lean command -/// never creates a certificate; the JSON report carries the failure. -pub fn prove(compiled:&Compilation,out:&Path,toolchain:&Toolchain)->Result{ - let mut records=Vec::new(); - for call in &compiled.semantics.bound_calls{ - if super::unified::covers(compiled,&call.caller){continue} - let Some((source,client,identity,n))=candidate(compiled,call) else { - // Projection contracts have their own independently replayable - // backend, and must not also appear as unsupported constant claims. - if super::projection::eligible(compiled,call) - ||super::expression::eligible(compiled,call){continue} - records.push(json!({"caller":call.caller.as_str(), - "callee":call.target.as_str(),"status":"unsupported_fragment", - "reason":"requires_pure_number_contract_int_model_forwarder_with_constant_claims", - "diagnostics":rejection_diagnostics(compiled,call)})); - continue; - }; - let key=sha(format!("{}|{}|{}|{}",identity, - compiled.semantics.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.caller)) - .map(|a|a.hashes.closure.0.as_str()).unwrap_or(""), - compiled.semantics.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.target)) - .map(|a|a.hashes.closure.0.as_str()).unwrap_or(""), - toolchain.version).as_bytes()); - let folder=out.join("composed").join(&key[7..23]); - fs::create_dir_all(&folder)?; - let callee=folder.join("CalleeModule.lean"); - let caller=folder.join("CallerModule.lean"); - let built=folder.join("CalleeModule.olean"); - fs::write(&callee,&source)?; - fs::write(&caller,&client)?; - let run=(|| ->Result<()>{ - compile_import_module(toolchain,&callee,&built,&folder, - Duration::from_secs(120)).context("callee interface")?; - let verified=folder.join("CallerModule.olean"); - compile_import_module(toolchain,&caller,&verified,&folder, - Duration::from_secs(120)).context("caller composition")?; - Ok(()) - })(); - if let Err(e)=run{ - let _=fs::remove_file(folder.join("composition-certificate.json")); - records.push(json!({"identity":identity, - "status":"lean_rejected","error":format!("{e:#}")})); - continue - } - let cert=json!({ - "schema_version":1,"kind":"marqdo_restricted_composition", - "scope":"number_contract_int_model_pure_forwarder_constant_result", - "status":"lean_kernel_proved_model", - "identity":identity,"caller":call.caller.as_str(), - "callee":call.target.as_str(), - "claimed_result":n, - "callee_source_sha256":sha(source.as_bytes()), - "caller_source_sha256":sha(client.as_bytes()), - "callee_compiled_sha256":sha(&fs::read(&built)?), - "caller_compiled_sha256":sha(&fs::read(folder.join("CallerModule.olean"))?), - "toolchain":toolchain.version, - "source_closures":compiled.semantics.artifacts.iter() - .filter(|a|a.symbol_id.as_ref()==Some(&call.caller) - ||a.symbol_id.as_ref()==Some(&call.target)) - .map(|a|json!({"id":a.artifact_id.0, - "closure":a.hashes.closure.0})).collect::>(), - "independent_replay":"CalleeModule.lean then CallerModule.lean" - }); - let receipt=folder.join("composition-certificate.json"); - fs::write(&receipt,serde_json::to_vec_pretty(&cert)?)?; - records.push(json!({"identity":identity, - "status":"lean_kernel_proved_model","artifact":receipt, - "scope":"number_contract_int_model_pure_forwarder_constant_result"})); - } - records.extend(super::projection::prove(compiled,out,toolchain)?); - records.extend(super::expression::prove(compiled,out,toolchain)?); - records.extend(super::unified::prove(compiled,out,toolchain)?); - for record in &mut records { - if record["evidence"].is_null(){ - record["evidence"]=if record["status"]=="lean_kernel_proved_model"{ - super::evidence::model_proved() - }else{super::evidence::unknown("unproved_or_unsupported_fragment")}; - } - } - Ok(json!({"schema_version":1,"role":"restricted_composed_lean_module", - "results":records, - "full_marqdo_runtime_semantics_proved":false})) -} - - - -/// Strict receipt-to-source correspondence; any duplicate row is a hard failure. -fn ensure_exact_closures( - rows:usize, - received:&std::collections::BTreeSet<(String,String)>, - expected:&std::collections::BTreeSet<(String,String)> -)->Result<()>{ - anyhow::ensure!(rows==expected.len() && received==expected, - "proof.compose_stale_or_ambiguous_closure"); - Ok(()) -} - -/// Replay a composition certificate *against the current project source*. -/// The certificate never supplies Lean source code: it must byte-match source -/// recompiled from the current Marqdo AST, and both Lean modules are rechecked. -pub fn replay(compiled:&Compilation,certificate:&Path,lean:&Toolchain)->Result{ - let receipt:Value=serde_json::from_slice(&fs::read(certificate)?)?; - if receipt["kind"]=="marqdo_parameter_projection_composition"{ - return super::projection::replay(compiled,certificate,lean) - } - if receipt["kind"]=="marqdo_pure_expression_composition"{ - return super::expression::replay(compiled,certificate,lean) - } - if receipt["kind"]=="marqdo_unified_modular_contract"{ - return super::unified::replay(compiled,certificate,lean) - } - anyhow::ensure!(receipt["schema_version"]==1 - &&receipt["kind"]=="marqdo_restricted_composition" - &&receipt["scope"]=="number_contract_int_model_pure_forwarder_constant_result" - &&receipt["status"]=="lean_kernel_proved_model", - "proof.compose_invalid_certificate: unexpected status or scope"); - anyhow::ensure!(receipt["toolchain"]==lean.version, - "proof.compose_stale_toolchain"); - let identity=receipt["identity"].as_str().context("missing identity")?; - // A certificate identity is a unique proof subject, not a search hint. - // Reject ambiguous candidates instead of silently selecting the first. - let matching=compiled.semantics.bound_calls.iter() - .filter_map(|call|{ - let (a,b,id,n)=candidate(compiled,call)?; - (id==identity).then_some((a,b,id,n,call)) - }).collect::>(); - anyhow::ensure!(matching.len()==1, - "proof.compose_ambiguous_or_stale_source: expected exactly one callsite"); - let (callee,caller,_,n,call)=matching.into_iter().next() - .context("proof.compose_missing_candidate")?; - anyhow::ensure!(receipt["claimed_result"]==n, - "proof.compose_claim_changed"); - anyhow::ensure!(receipt["caller"]==call.caller.as_str() - &&receipt["callee"]==call.target.as_str(), - "proof.compose_symbol_changed"); - // Exact-set comparison blocks duplicate, injected, and omitted dependency - // rows. The receipt does not get to choose the dependency closure. - let expected_closures=compiled.semantics.artifacts.iter() - .filter(|a|a.symbol_id.as_ref()==Some(&call.caller) - ||a.symbol_id.as_ref()==Some(&call.target)) - .map(|a|(a.artifact_id.0.clone(),a.hashes.closure.0.clone())) - .collect::>(); - anyhow::ensure!(expected_closures.len()==2, - "proof.compose_ambiguous_artifact"); - let received=receipt["source_closures"].as_array() - .context("proof.compose_missing_source_closures")?; - let actual_closures=received.iter().map(|r|{ - Ok((r["id"].as_str().context("proof.compose_invalid_closure_id")?.to_owned(), - r["closure"].as_str().context("proof.compose_invalid_closure_hash")?.to_owned())) - }).collect::>>()?; - ensure_exact_closures(received.len(),&actual_closures,&expected_closures)?; - let folder=certificate.parent().context("missing certificate parent")?; - let callee_path=folder.join("CalleeModule.lean"); - let caller_path=folder.join("CallerModule.lean"); - anyhow::ensure!(fs::read_to_string(&callee_path)?==callee - &&fs::read_to_string(&caller_path)?==caller, - "proof.compose_generated_source_mismatch"); - anyhow::ensure!(receipt["callee_source_sha256"]==sha(callee.as_bytes()) - &&receipt["caller_source_sha256"]==sha(caller.as_bytes()), - "proof.compose_hash_mismatch"); - let callee_obj=folder.join("CalleeModule.olean"); - let caller_obj=folder.join("CallerModule.olean"); - compile_import_module(lean,&callee_path,&callee_obj,folder, - Duration::from_secs(120))?; - compile_import_module(lean,&caller_path,&caller_obj,folder, - Duration::from_secs(120))?; - anyhow::ensure!(receipt["callee_compiled_sha256"]==sha(&fs::read(&callee_obj)?) - &&receipt["caller_compiled_sha256"]==sha(&fs::read(&caller_obj)?), - "proof.compose_replay_output_changed"); - Ok(json!({"schema_version":1,"kind":"independent_composition_replay", - "status":"lean_kernel_replayed","scope":receipt["scope"], - "identity":identity,"current_source_verified":true, - "full_marqdo_runtime_semantics_proved":false})) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn certificate_closures_must_be_exact_and_unique(){ - use std::collections::BTreeSet; - let expected=BTreeSet::from([ - ("caller".into(),"sha256:a".into()), - ("callee".into(),"sha256:b".into()) - ]); - assert!(ensure_exact_closures(2,&expected,&expected).is_ok()); - assert!(ensure_exact_closures(3,&expected,&expected).is_err()); - let missing=BTreeSet::from([("caller".into(),"sha256:a".into())]); - assert!(ensure_exact_closures(1,&missing,&expected).is_err()); - let mut injected=expected.clone(); - injected.insert(("third".into(),"sha256:c".into())); - assert!(ensure_exact_closures(3,&injected,&expected).is_err()); - let mut changed=expected.clone(); - changed.remove(&("callee".into(),"sha256:b".into())); - changed.insert(("callee".into(),"sha256:wrong".into())); - assert!(ensure_exact_closures(2,&changed,&expected).is_err()); - } - #[test] - fn pure_forwarder_can_be_compiled_into_two_independent_lean_sources(){ - let root=std::env::temp_dir().join( - format!("marqdo-compose-unit-{}",std::process::id())); - let _=fs::remove_dir_all(&root); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("math.mq.md"),r#"--- -markup: occlusion ---- - -# math - -## exact -+ `n` - -| 参数 | 类型 | 说明 | -|---|---|---| -| n | int | integer | - -| 定理 | 结论 | 策略 | -|---|---|---| -| fixed | 结果 = 2 | auto | - -*2* -"#).unwrap(); - fs::write(root.join("main.mq.md"),r#"--- -markup: occlusion -import: - math: math.mq.md ---- - -# main - -## forward -+ `n` - -| 参数 | 类型 | 说明 | -|---|---|---| -| n | int | integer | - -| 定理 | 结论 | 策略 | -|---|---|---| -| same | 结果 = 2 | auto | - -**v = [调用](math.math.exact(`n`))** -*v* -"#).unwrap(); - let c=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let call=c.semantics.bound_calls.iter().find(|x| - x.call_site=="math.math.exact").unwrap(); - let (callee,caller,_,result)=candidate(&c,call) - .unwrap_or_else(||panic!("composition candidate rejected: {}", - rejection_diagnostics(&c,call))); - assert_eq!(result,2); - assert!(callee.contains("theorem callee_contract")); - assert!(caller.starts_with("import CalleeModule")); - assert!(caller.contains("using (callee_contract")); - // Duplicate matching declarations must not be treated as a - // unique contractual source of truth. - let duplicate=std::fs::read_to_string(root.join("math.mq.md")).unwrap() - .replace("| fixed | 结果 = 2 | auto |", - "| fixed | 结果 = 2 | auto |\n| other | 结果 = 2 | auto |"); - std::fs::write(root.join("math.mq.md"),duplicate).unwrap(); - let ambiguous=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let ambiguous_call=ambiguous.semantics.bound_calls.iter().find(|x| - x.call_site=="math.math.exact").unwrap(); - assert!(candidate(&ambiguous,ambiguous_call).is_none(), - "duplicate constant claims must fail closed"); - std::fs::write(root.join("math.mq.md"),r#"--- -markup: occlusion ---- - -# math - -## exact -+ `n` - -| 参数 | 类型 | 说明 | -|---|---|---| -| n | int | integer | - -| 定理 | 结论 | 策略 | -|---|---|---| -| fixed | 结果 = 2 | auto | - -*2* -"#).unwrap(); - // Branching is explicitly outside the certificate scope. - fs::write(root.join("main.mq.md"),r#"--- -import: - math: math.mq.md ---- - -# main - -## forward -+ `n` - -| 参数 | 类型 | 说明 | -|---|---|---| -| n | int | integer | - -| 定理 | 结论 | 策略 | -|---|---|---| -| same | 结果 = 2 | auto | - -1. `n` > 0 - **v = [调用](math.math.exact(`n`))** -2. * - **v = 0** - -*v* -"#).unwrap(); - let changed=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let guarded=changed.semantics.bound_calls.iter().find(|x| - x.call_site=="math.math.exact").unwrap(); - assert!(candidate(&changed,guarded).is_none()); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/knowledge/duplicate.rs b/src/knowledge/duplicate.rs deleted file mode 100755 index 6ea11b5..0000000 --- a/src/knowledge/duplicate.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Duplicate capability / symbol detection via fingerprints. - -use crate::knowledge::fingerprint::symbol_similarity; -use crate::knowledge::ir::{CapabilityInfo, Edge, EdgeKind, SymbolInfo}; - -#[derive(Debug, Clone)] -pub struct DuplicatePair { - pub left: String, - pub right: String, - pub similarity: f64, - pub left_resource: String, - pub right_resource: String, -} - -pub fn find_duplicates(symbols: &[SymbolInfo], threshold: f64) -> Vec { - let mut pairs = Vec::new(); - for i in 0..symbols.len() { - if symbols[i].kind == "test" { - continue; - } - for j in (i + 1)..symbols.len() { - if symbols[j].kind == "test" { - continue; - } - if symbols[i].module == symbols[j].module && symbols[i].name == symbols[j].name { - continue; - } - let sim = symbol_similarity(&symbols[i], &symbols[j]); - if sim >= threshold { - pairs.push(DuplicatePair { - left: symbols[i].id.clone(), - right: symbols[j].id.clone(), - similarity: sim, - left_resource: symbols[i].resource.clone(), - right_resource: symbols[j].resource.clone(), - }); - } - } - } - pairs.sort_by(|a, b| { - b.similarity - .partial_cmp(&a.similarity) - .unwrap_or(std::cmp::Ordering::Equal) - }); - pairs -} - -/// During extract: add conflicts_with-style related edges for near-duplicates. -pub fn annotate_duplicates( - symbols: &[SymbolInfo], - edges: &mut Vec, - _capabilities: &[CapabilityInfo], -) { - for pair in find_duplicates(symbols, 0.75) { - edges.push(Edge { - from: format!("symbol:{}", pair.left), - to: format!("symbol:{}", pair.right), - kind: EdgeKind::ConflictsWith, - note: Some(format!("possible_duplicate:{:.2}", pair.similarity)), - }); - } -} - -pub fn apply_duplicate_flags( - mut capabilities: Vec, - symbols: &[SymbolInfo], -) -> Vec { - let pairs = find_duplicates(symbols, 0.75); - for pair in &pairs { - for c in &mut capabilities { - if c.implemented_by.iter().any(|s| s == &pair.left) { - if !c.possible_duplicates.contains(&pair.right) { - c.possible_duplicates.push(pair.right.clone()); - } - } - if c.implemented_by.iter().any(|s| s == &pair.right) { - if !c.possible_duplicates.contains(&pair.left) { - c.possible_duplicates.push(pair.left.clone()); - } - } - } - } - capabilities -} - -pub fn format_duplicates_text(pairs: &[DuplicatePair]) -> String { - let mut out = String::from("Possible duplicate capabilities\n\n"); - if pairs.is_empty() { - out.push_str("_None above threshold._\n"); - return out; - } - for (i, p) in pairs.iter().enumerate() { - out.push_str(&format!( - "{}. {}::{}\n {}::{}\n similarity: {:.2}\n\n", - i + 1, - p.left_resource, - p.left.rsplit("::").next().unwrap_or(&p.left), - p.right_resource, - p.right.rsplit("::").next().unwrap_or(&p.right), - p.similarity - )); - } - out -} diff --git a/src/knowledge/evidence.rs b/src/knowledge/evidence.rs deleted file mode 100644 index 5db0c05..0000000 --- a/src/knowledge/evidence.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Explicit evidence levels: a Lean proof of the mathematical model is -//! categorically different from a proof about the dynamic Marqdo runtime. -//! Neither source metadata nor an asserted plugin contract grants authority. -use serde::{Serialize,Deserialize}; -use serde_json::{json,Value}; - -#[derive(Clone,Copy,Debug,PartialEq,Eq,Serialize,Deserialize)] -#[serde(rename_all="snake_case")] -pub enum EvidenceGrade{ - /// Only when correspondence to supported runtime semantics was proven. - Proved, - /// Kernel checked theorem over an explicitly identified abstract model. - ModelProved, - /// Observed by supplied tests/experiments. Not a mathematical proof. - Tested, - /// Trust or environmental assertion, not proven from source. - Assumed, - /// Insufficient evidence, timeout, unsupported language, or no proof. - Unknown, - /// An actual counterexample, never just a missing Lean derivation. - Refuted, - /// The source, contract, toolchain, or dependency changed. - Stale -} -impl EvidenceGrade{ - pub fn as_str(self)->&'static str{ - match self{ - Self::Proved=>"proved",Self::ModelProved=>"model_proved", - Self::Tested=>"tested",Self::Assumed=>"assumed", - Self::Unknown=>"unknown",Self::Refuted=>"refuted", - Self::Stale=>"stale" - } - } -} -fn record(grade:EvidenceGrade,basis:&str,kernel_replayed:bool, - runtime_correspondence:bool)->Value{ - let effective=if grade==EvidenceGrade::Proved && !runtime_correspondence{ - EvidenceGrade::ModelProved - }else{grade}; - json!({ - "schema_version":1,"grade":effective.as_str(),"basis":basis, - "model":"lean_int_abstract", - "kernel_replayed":kernel_replayed, - "runtime_correspondence_verified":runtime_correspondence, - "full_marqdo_runtime_semantics_proved":false, - "not_execution_authority":true - }) -} -/// Kernel checked at issuance; no independent replay has happened yet. -pub fn model_proved()->Value{ - record(EvidenceGrade::ModelProved,"source_regenerated_lean_kernel", - false,false) -} -/// Source-regenerated modules were independently recompiled on replay. -pub fn model_replayed()->Value{ - record(EvidenceGrade::ModelProved,"independently_replayed_lean_kernel", - true,false) -} -pub fn unknown(reason:&str)->Value{ - record(EvidenceGrade::Unknown,reason,false,false) -} -pub fn assumed()->Value{ - record(EvidenceGrade::Assumed,"external_or_author_declaration",false,false) -} -pub fn for_receipt(status:&str,usable:bool,kernel_replayed:bool)->Value{ - if status=="stale"{ - return record(EvidenceGrade::Stale,"source_or_dependency_changed", - false,false) - } - if !usable { - return unknown(if status=="ambiguous"{"ambiguous_receipt"} - else if status=="unproved"{"lean_not_proved"} - else{"no_trusted_replayable_proof"}) - } - if status=="proved"{ - return record(EvidenceGrade::ModelProved, - "source_bound_lean_certificate",kernel_replayed,false) - } - unknown("unsupported_receipt_status") -} -pub fn with_grade(grade:EvidenceGrade,source:&str)->Value{ - // This constructor is for explicitly sourced tests/assumptions and is - // intentionally never allowed to create runtime-level Proved by fiat. - record(grade,source,false,false) -} - -#[cfg(test)] -mod tests{ - use super::*; - #[test] - fn grades_do_not_promote_abstract_integer_proofs(){ - let fresh=model_proved(); - assert_eq!(fresh["kernel_replayed"],false); - assert_eq!(fresh["grade"],"model_proved"); - let replayed=model_replayed(); - assert_eq!(replayed["kernel_replayed"],true); - let proved=for_receipt("proved",true,true); - assert_eq!(proved["grade"],"model_proved"); - assert_eq!(proved["full_marqdo_runtime_semantics_proved"],false); - assert_eq!(with_grade(EvidenceGrade::Proved,"asserted")["grade"], - "model_proved"); - assert_eq!(for_receipt("stale",false,false)["grade"],"stale"); - assert_eq!(for_receipt("unproved",false,false)["grade"],"unknown"); - assert_eq!(for_receipt("ambiguous",false,false)["grade"],"unknown"); - assert_eq!(with_grade(EvidenceGrade::Refuted, - "actual_counterexample")["grade"],"refuted"); - assert_eq!(assumed()["grade"],"assumed"); - } -} diff --git a/src/knowledge/expression.rs b/src/knowledge/expression.rs deleted file mode 100644 index 0e0ba11..0000000 --- a/src/knowledge/expression.rs +++ /dev/null @@ -1,320 +0,0 @@ -//! Independent assume/guarantee composition of source-backed pure arithmetic -//! expressions. All results are **Lean Int-model** theorems, NOT dynamic -//! Marqdo Number/i64 runtime equivalence. Every unsupported case fails closed. -use std::{collections::BTreeSet,fs,path::Path,time::Duration}; -use anyhow::{Context,Result}; -use serde_json::{json,Value}; -use sha2::{Digest,Sha256}; -use crate::{ - ast::{BinaryOp,Expr,Function,Stmt,UnaryOp}, - prove::{driver::{Toolchain,compile_import_module}, - proof_check::{self,ClaimAst,CTok}}, - sema::ir::{BoundCall,Compilation,SemanticArtifact,CanonicalParam} -}; -use super::projection::{load_function,forwarder,closures}; - -const KIND:&str="marqdo_pure_expression_composition"; -const SCOPE:&str="number_contract_int_model_pure_expression_forwarder"; -fn sha(s:&[u8])->String{format!("sha256:{:x}",Sha256::digest(s))} - -#[derive(Clone,Debug,PartialEq,Eq)] -enum Term{ - Number(i64), Param(usize), Neg(Box), - Add(Box,Box),Sub(Box,Box), - Mul(Box,Box) -} -impl Term{ - fn source(e:&Expr,params:&[CanonicalParam],depth:usize)->Option{ - if depth>=32{return None} - match e{ - Expr::Literal(crate::ast::Literal::Int(n))=>Some(Self::Number(*n)), - Expr::Var(s)=>Some(Self::Param(unique_param(params,s)?)), - Expr::Occluded{payload:Some(inner),..}=>Self::source(inner,params,depth+1), - Expr::Unary{op:UnaryOp::Neg,expr}=> - Some(Self::Neg(Box::new(Self::source(expr,params,depth+1)?))), - Expr::Binary{op,left,right}=>{ - let l=Box::new(Self::source(left,params,depth+1)?); - let r=Box::new(Self::source(right,params,depth+1)?); - match op{ - BinaryOp::Add=>Some(Self::Add(l,r)), - BinaryOp::Sub=>Some(Self::Sub(l,r)), - BinaryOp::Mul=>Some(Self::Mul(l,r)), - _=>None - } - }, - _=>None - } - } - fn claim(e:&ClaimAst,params:&[CanonicalParam],depth:usize)->Option{ - if depth>=32{return None} - match e{ - ClaimAst::Lit(CTok::Int(n))=>Some(Self::Number(*n)), - ClaimAst::Var(s)=>Some(Self::Param(unique_param(params,s)?)), - ClaimAst::Un{op:"-",expr}=>Some(Self::Neg(Box::new( - Self::claim(expr,params,depth+1)?))), - ClaimAst::Bin{op,left,right}=>{ - let l=Box::new(Self::claim(left,params,depth+1)?); - let r=Box::new(Self::claim(right,params,depth+1)?); - match *op{ - "+"=>Some(Self::Add(l,r)), - "-"=>Some(Self::Sub(l,r)), - "*"=>Some(Self::Mul(l,r)), - _=>None - } - } - _=>None - } - } - fn substitute(&self,args:&[Term],depth:usize)->Option{ - if depth>=64{return None} - match self{ - Self::Number(n)=>Some(Self::Number(*n)), - Self::Param(i)=>args.get(*i).cloned(), - Self::Neg(a)=>Some(Self::Neg(Box::new(a.substitute(args,depth+1)?))), - Self::Add(a,b)=>Some(Self::Add(Box::new(a.substitute(args,depth+1)?), - Box::new(b.substitute(args,depth+1)?))), - Self::Sub(a,b)=>Some(Self::Sub(Box::new(a.substitute(args,depth+1)?), - Box::new(b.substitute(args,depth+1)?))), - Self::Mul(a,b)=>Some(Self::Mul(Box::new(a.substitute(args,depth+1)?), - Box::new(b.substitute(args,depth+1)?))) - } - } - fn lean(&self)->String{ - match self{ - Self::Number(n)=>format!("({n} : Int)"), - Self::Param(i)=>format!("v{i}"), - Self::Neg(a)=>format!("(-{})",a.lean()), - Self::Add(a,b)=>format!("({} + {})",a.lean(),b.lean()), - Self::Sub(a,b)=>format!("({} - {})",a.lean(),b.lean()), - Self::Mul(a,b)=>format!("({} * {})",a.lean(),b.lean()) - } - } - fn is_composite(&self)->bool{ - matches!(self,Self::Neg(..)|Self::Add(..)|Self::Sub(..)|Self::Mul(..)) - } -} -fn unique_param(params:&[CanonicalParam],name:&str)->Option{ - let i=params.iter().position(|p|p.name==name)?; - (params.iter().filter(|p|p.name==name).count()==1).then_some(i) -} -fn claim_matches(compiled:&Compilation,artifact:&SemanticArtifact, - params:&[CanonicalParam],want:&Term)->bool{ - let Some(owner)=artifact.symbol_id.as_ref() else{return false}; - // The declaration must unambiguously refer to the exact source equation. - // Do not convert any arbitrary author-written proposition into an axiom. - compiled.semantics.claims.iter().filter(|c|{ - if c.owner!=*owner|| - !c.premise.as_deref().map_or(true,|s|s.trim().is_empty()){ - return false - } - let Ok(tokens)=proof_check::tokenize_claim(&c.conclusion) else{return false}; - let Ok((_,tree))=proof_check::parse_claim_expr(&tokens) else{return false}; - match tree{ - ClaimAst::Bin{op:"=",left,right} - if matches!(*left,ClaimAst::Var(ref v) if v=="结果")=> - Term::claim(&right,params,0).as_ref()==Some(want), - _=>false - } - }).count()==1 -} -fn callee_expression(fun:&Function,params:&[CanonicalParam])->Option{ - match fun.body.as_slice(){ - [Stmt::Return{value,..}]=>Term::source(value,params,0), - _=>None - } -} -struct Prepared{ - identity:String, - callee:String, - caller:String -} -fn candidate(c:&Compilation,call:&BoundCall)->Option{ - let sem=&c.semantics; - let ca=single_artifact(c,&call.caller)?; - let ce=single_artifact(c,&call.target)?; - if ca.source.file==ce.source.file||call.caller==call.target - ||!ca.effects.is_pure()||!ce.effects.is_pure() - ||!call.required_effects.is_pure() - ||call.control_blocker.is_some()||!call.path_guards.is_empty(){return None} - if sem.bound_calls.iter().filter(|x|x.caller==call.caller).count()!=1{ - return None - } - let cs=ca.signature.as_ref()?; - let es=ce.signature.as_ref()?; - let caller=load_function(c,ca)?; - let callee=load_function(c,ce)?; - if caller.is_object()||callee.is_object(){return None} - if caller.params.len()!=cs.params.len() - ||callee.params.len()!=es.params.len() - ||call.args.len()!=es.params.len(){return None} - if !caller.params.iter().zip(cs.params.iter()).all(|(a,b)|a.name==b.name) - ||!callee.params.iter().zip(es.params.iter()).all(|(a,b)|a.name==b.name){ - return None - } - if cs.params.iter().chain(es.params.iter()) - .any(|p|p.ty!="number"||!p.required||p.default_digest.is_some()){ - return None - } - let body=callee_expression(&callee,&es.params)?; - if !body.is_composite(){return None} - if !claim_matches(c,ce,&es.params,&body){return None} - let forwarded=forwarder(&caller)?.for_evaluation().ok()?; - if forwarded.path.is_none()||forwarded.receiver.is_some() - ||crate::sema::bind::call_display(&forwarded)!=call.call_site - ||forwarded.args.len()!=call.args.len(){return None} - let args=call.args.iter().zip(es.params.iter()).map(|(a,p)|{ - if a.name.as_ref().is_some_and(|name|name!=&p.name){return None} - if let Some(n)=a.integer{return Some(Term::Number(n))} - let symbol=a.symbol.as_ref()?; - Some(Term::Param(unique_param(&cs.params,symbol)?)) - }).collect::>>()?; - let expected=body.substitute(&args,0)?; - if !claim_matches(c,ca,&cs.params,&expected){return None} - let callee_binders=binders(es.params.len()); - let caller_binders=binders(cs.params.len()); - let callee_vars=vars(es.params.len()); - let caller_vars=vars(cs.params.len()); - let call_args=args.iter().map(Term::lean).collect::>().join(" "); - let callee_src=format!( - "-- Source-derived callee expression; Lean Int abstraction only.\n\ - def callee {callee_binders} : Int := {}\n\ - theorem callee_contract {callee_binders} : callee {callee_vars} = {} := by rfl\n", - body.lean(),body.lean()); - let caller_src=format!( - "import CalleeModule\n\ - -- The caller imports the callee's theorem, never its implementation body.\n\ - def caller {caller_binders} : Int := callee {call_args}\n\ - theorem caller_contract {caller_binders} : caller {caller_vars} = {} := by\n\ - \x20\x20simpa [caller] using (callee_contract {call_args})\n", - expected.lean()); - Some(Prepared{ - identity:format!("{}#{}",ca.artifact_id.0,ce.artifact_id.0), - callee:callee_src,caller:caller_src - }) -} -fn single_artifact<'a>(c:&'a Compilation, - symbol:&crate::sema::SymbolId)->Option<&'a SemanticArtifact>{ - let mut found=c.semantics.artifacts.iter().filter(|a| - a.kind=="function"&&a.symbol_id.as_ref()==Some(symbol)); - let item=found.next()?; - found.next().is_none().then_some(item) -} -fn binders(n:usize)->String{ - (0..n).map(|i|format!("(v{i} : Int)")).collect::>().join(" ") -} -fn vars(n:usize)->String{ - (0..n).map(|i|format!("v{i}")).collect::>().join(" ") -} -pub(super) fn eligible(c:&Compilation,call:&BoundCall)->bool{ - candidate(c,call).is_some() -} -pub(super) fn prove(c:&Compilation,out:&Path,lean:&Toolchain)->Result>{ - let mut results=Vec::new(); - for call in &c.semantics.bound_calls{ - if super::unified::covers(c,&call.caller){continue} - let Some(plan)=candidate(c,call) else{continue}; - let closure=closures(c,call)?; - let key=sha(format!("{}|{:?}|{}",plan.identity,closure,lean.version).as_bytes()); - let dir=out.join("composed").join(format!("expr-{}",&key[7..23])); - fs::create_dir_all(&dir)?; - let callee_src=dir.join("CalleeModule.lean"); - let caller_src=dir.join("CallerModule.lean"); - let callee_obj=dir.join("CalleeModule.olean"); - let caller_obj=dir.join("CallerModule.olean"); - fs::write(&callee_src,&plan.callee)?; - fs::write(&caller_src,&plan.caller)?; - let checked=(||->Result<()>{ - compile_import_module(lean,&callee_src,&callee_obj,&dir, - Duration::from_secs(120)).context("expression callee proof")?; - compile_import_module(lean,&caller_src,&caller_obj,&dir, - Duration::from_secs(120)).context("expression caller composition")?; - Ok(()) - })(); - if let Err(e)=checked{ - let _=fs::remove_file(dir.join("composition-certificate.json")); - results.push(json!({"identity":plan.identity,"status":"lean_rejected", - "scope":SCOPE,"error":format!("{e:#}")})); - continue - } - let cert=json!({ - "schema_version":1,"kind":KIND,"scope":SCOPE, - "status":"lean_kernel_proved_model", - "caller":call.caller.as_str(),"callee":call.target.as_str(), - "identity":plan.identity,"toolchain":lean.version, - "source_closures":closure.iter().map(|(id,digest)| - json!({"id":id,"closure":digest})).collect::>(), - "callee_source_sha256":sha(plan.callee.as_bytes()), - "caller_source_sha256":sha(plan.caller.as_bytes()), - "callee_compiled_sha256":sha(&fs::read(&callee_obj)?), - "caller_compiled_sha256":sha(&fs::read(&caller_obj)?), - "full_marqdo_runtime_semantics_proved":false, - "independent_replay":"CalleeModule.lean then CallerModule.lean" - }); - let receipt=dir.join("composition-certificate.json"); - fs::write(&receipt,serde_json::to_vec_pretty(&cert)?)?; - results.push(json!({"identity":plan.identity,"status":"lean_kernel_proved_model", - "scope":SCOPE,"artifact":receipt})); - } - Ok(results) -} -pub(super) fn replay(c:&Compilation,certificate:&Path,lean:&Toolchain) - ->Result{ - let cert:Value=serde_json::from_slice(&fs::read(certificate)?)?; - anyhow::ensure!(cert["schema_version"]==1&&cert["kind"]==KIND - &&cert["scope"]==SCOPE&&cert["status"]=="lean_kernel_proved_model", - "proof.expression_invalid_certificate"); - anyhow::ensure!(cert["toolchain"]==lean.version,"proof.expression_toolchain_mismatch"); - let identity=cert["identity"].as_str().context("proof.expression_missing_identity")?; - let candidates=c.semantics.bound_calls.iter().filter_map(|call| - candidate(c,call).and_then(|plan|(plan.identity==identity).then_some((call,plan)))) - .collect::>(); - anyhow::ensure!(candidates.len()==1,"proof.expression_ambiguous_or_stale_source"); - let (call,plan)=&candidates[0]; - anyhow::ensure!(cert["caller"]==call.caller.as_str() - &&cert["callee"]==call.target.as_str(),"proof.expression_changed_symbols"); - let expected=closures(c,call)?; - let rows=cert["source_closures"].as_array().context("proof.expression_missing_closures")?; - let actual=rows.iter().map(|r|Ok(( - r["id"].as_str().context("proof.expression_bad_id")?.to_owned(), - r["closure"].as_str().context("proof.expression_bad_digest")?.to_owned() - ))).collect::>>()?; - anyhow::ensure!(rows.len()==expected.len()&&actual==expected, - "proof.expression_stale_or_ambiguous_closure"); - let dir=certificate.parent().context("proof.expression_missing_parent")?; - let callee_src=dir.join("CalleeModule.lean"); - let caller_src=dir.join("CallerModule.lean"); - anyhow::ensure!(fs::read_to_string(&callee_src)?==plan.callee - &&fs::read_to_string(&caller_src)?==plan.caller - &&cert["callee_source_sha256"]==sha(plan.callee.as_bytes()) - &&cert["caller_source_sha256"]==sha(plan.caller.as_bytes()), - "proof.expression_source_mismatch"); - let callee_obj=dir.join("CalleeModule.olean"); - let caller_obj=dir.join("CallerModule.olean"); - compile_import_module(lean,&callee_src,&callee_obj,dir,Duration::from_secs(120))?; - compile_import_module(lean,&caller_src,&caller_obj,dir,Duration::from_secs(120))?; - anyhow::ensure!(cert["callee_compiled_sha256"]==sha(&fs::read(callee_obj)?) - &&cert["caller_compiled_sha256"]==sha(&fs::read(caller_obj)?), - "proof.expression_compiled_mismatch"); - Ok(json!({"schema_version":1,"kind":"independent_composition_replay", - "status":"lean_kernel_replayed","scope":SCOPE, - "identity":identity,"current_source_verified":true, - "full_marqdo_runtime_semantics_proved":false})) -} -#[cfg(test)] -mod tests{ - use super::*; - #[test] - fn arithmetic_contract_requires_exact_structural_match(){ - let params=vec![CanonicalParam{name:"n".into(),ty:"number".into(), - required:true,default_digest:None,unit:None}]; - let lhs=crate::parse::parse_expr("`n` + 1").unwrap(); - let want=Term::source(&lhs,¶ms,0).unwrap(); - let good=proof_check::parse_claim_expr( - &proof_check::tokenize_claim("n + 1").unwrap()).unwrap().1; - assert_eq!(Term::claim(&good,¶ms,0),Some(want.clone())); - let bad=proof_check::parse_claim_expr( - &proof_check::tokenize_claim("n + 2").unwrap()).unwrap().1; - assert_ne!(Term::claim(&bad,¶ms,0),Some(want)); - assert!(Term::source(&crate::parse::parse_expr("`n` / 2").unwrap(),¶ms,0).is_none()); - } -} diff --git a/src/knowledge/extract.rs b/src/knowledge/extract.rs deleted file mode 100755 index a6fc10b..0000000 --- a/src/knowledge/extract.rs +++ /dev/null @@ -1,495 +0,0 @@ -//! Extract Engineering Knowledge IR from a Marqdo source tree. - -use std::fs; -use std::path::{Path, PathBuf}; - -use anyhow::{Context, Result}; - -use crate::ast::Function; -use crate::knowledge::fingerprint::{collect_calls, fingerprint_hash, fingerprint_text, ops_hint}; -use crate::knowledge::ir::{ - Confidence, Evidence, KnowledgeGraph, KnowledgeItem, KnowledgeKind, Lifecycle, ModuleInfo, - RepositoryInfo, SymbolInfo, -}; -use crate::knowledge::util::{ - extract_fm_field, extract_fm_list, extract_nested_by, extract_section, first_paragraph, - slugify, -}; -use crate::lex::{classify_source, LineKind}; -use crate::parse::parse_source; - -pub struct ExtractOptions { - pub path: PathBuf, - pub out_dir: PathBuf, -} - -pub fn extract_graph(opts: &ExtractOptions) -> Result { - let root = if opts.path.is_file() { - opts.path - .parent() - .filter(|p| !p.as_os_str().is_empty()) - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| PathBuf::from(".")) - } else { - opts.path.clone() - }; - let root = root.canonicalize().unwrap_or(root); - let out_canon = opts.out_dir.canonicalize().unwrap_or(opts.out_dir.clone()); - let version = env!("CARGO_PKG_VERSION"); - - let mut files = Vec::new(); - if opts.path.is_file() { - files.push(opts.path.canonicalize().unwrap_or(opts.path.clone())); - } else { - collect_mq_md(&root, &root, &out_canon, &mut files)?; - files.sort(); - } - - let mut modules = Vec::new(); - let mut symbols = Vec::new(); - let mut knowledge = Vec::new(); - let mut had_err = false; - - for abs in &files { - let rel = abs - .strip_prefix(&root) - .unwrap_or(abs) - .to_string_lossy() - .replace('\\', "/"); - if rel.contains("/.marqdo/") || rel.starts_with(".marqdo/") { - continue; - } - match inspect_source(abs, &rel) { - Ok((m, syms, ks)) => { - modules.push(m); - symbols.extend(syms); - knowledge.extend(ks); - } - Err(e) => { - eprintln!("knowledge: skip {rel}: {e:#}"); - had_err = true; - } - } - } - - // Also scan authored knowledge markdown (non-.mq.md) under knowledge/ or doc/adr/ - collect_authored_knowledge(&root, &out_canon, &mut knowledge)?; - - // Wire called_by - let mut call_index: std::collections::HashMap> = - std::collections::HashMap::new(); - for s in &symbols { - for c in &s.calls { - let short = c.rsplit('.').next().unwrap_or(c).to_string(); - call_index.entry(short).or_default().push(s.id.clone()); - call_index.entry(c.clone()).or_default().push(s.id.clone()); - } - } - for s in &mut symbols { - let mut cb = call_index.remove(&s.name).unwrap_or_default(); - cb.extend(call_index.remove(&s.id).unwrap_or_default()); - cb.sort(); - cb.dedup(); - s.called_by = cb; - } - - // Detect tests: paths containing /tests/ or name starting with test_ - for s in &mut symbols { - if s.resource.contains("/tests/") || s.resource.starts_with("tests/") { - // module-level test file — mark symbols as tests for same-named exports later - } - if s.name.starts_with("test_") || s.name.starts_with("测试") { - s.kind = "test".into(); - } - } - let test_syms: Vec<(String, String)> = symbols - .iter() - .filter(|s| s.kind == "test" || s.resource.contains("/tests/") || s.resource.starts_with("tests/")) - .map(|s| (s.name.clone(), s.id.clone())) - .collect(); - for s in &mut symbols { - for (tname, tid) in &test_syms { - if tname.contains(&s.name) || s.tests.iter().any(|t| t == tid) { - if !s.tests.contains(tid) && tid != &s.id { - s.tests.push(tid.clone()); - } - } - } - } - - let capabilities = crate::knowledge::capability::derive_capabilities(&symbols, &modules); - let mut edges = crate::knowledge::graph::build_edges(&modules, &symbols, &capabilities, &knowledge); - crate::knowledge::duplicate::annotate_duplicates(&symbols, &mut edges, &capabilities); - - // Re-derive capability duplicate links after annotate (annotate mutates via returned list) - let capabilities = - crate::knowledge::duplicate::apply_duplicate_flags(capabilities, &symbols); - - let repository = RepositoryInfo { - title: root - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or("marqdo-project") - .to_string(), - root: root.to_string_lossy().to_string(), - languages: vec!["marqdo".into()], - module_count: modules.len(), - symbol_count: symbols.len(), - capability_count: capabilities.len(), - knowledge_count: knowledge.len(), - }; - - if had_err { - eprintln!("knowledge: extraction completed with some skipped files"); - } - - Ok(KnowledgeGraph { - repository, - modules, - symbols, - capabilities, - knowledge, - edges, - generated_by: format!("marqdo/{version}"), - }) -} - -fn collect_mq_md( - root: &Path, - dir: &Path, - out_canon: &Path, - out: &mut Vec, -) -> Result<()> { - for entry in fs::read_dir(dir)? { - let entry = entry?; - let p = entry.path(); - if p.is_dir() { - let name = p.file_name().and_then(|s| s.to_str()).unwrap_or(""); - if crate::project::is_excluded_dir_name(name) { - continue; - } - if let Ok(canon) = p.canonicalize() { - if canon == *out_canon { - continue; - } - } - collect_mq_md(root, &p, out_canon, out)?; - } else if p - .file_name() - .and_then(|s| s.to_str()) - .map(|s| s.ends_with(".mq.md")) - .unwrap_or(false) - { - out.push(p); - } - } - Ok(()) -} - -fn collect_authored_knowledge( - root: &Path, - out_canon: &Path, - out: &mut Vec, -) -> Result<()> { - walk_knowledge_md(root, root, out_canon, out) -} - -fn walk_knowledge_md( - root: &Path, - dir: &Path, - out_canon: &Path, - out: &mut Vec, -) -> Result<()> { - for entry in fs::read_dir(dir)? { - let entry = entry?; - let p = entry.path(); - if p.is_dir() { - let name = p.file_name().and_then(|s| s.to_str()).unwrap_or(""); - if crate::project::is_excluded_dir_name(name) { - continue; - } - if let Ok(canon) = p.canonicalize() { - if canon == *out_canon { - continue; - } - } - walk_knowledge_md(root, &p, out_canon, out)?; - continue; - } - let Some(name) = p.file_name().and_then(|s| s.to_str()) else { - continue; - }; - // Authored knowledge pages: .md with engineering type, not .mq.md (those go through inspect) - if !name.ends_with(".md") || name.ends_with(".mq.md") { - continue; - } - let source = fs::read_to_string(&p)?; - let Some(ty) = extract_fm_field(&source, "type") else { - continue; - }; - let kind = KnowledgeKind::parse(&ty); - match kind { - KnowledgeKind::Decision - | KnowledgeKind::Constraint - | KnowledgeKind::Failure - | KnowledgeKind::AntiPattern - | KnowledgeKind::Pattern - | KnowledgeKind::Migration - | KnowledgeKind::Fact => {} - _ => continue, - } - let rel = p - .strip_prefix(root) - .unwrap_or(&p) - .to_string_lossy() - .replace('\\', "/"); - out.push(knowledge_from_source(&source, &rel, kind)); - } - Ok(()) -} - -fn knowledge_from_source(source: &str, rel: &str, kind: KnowledgeKind) -> KnowledgeItem { - let title = extract_fm_field(source, "title") - .or_else(|| { - source.lines().find_map(|l| { - l.trim() - .strip_prefix("# ") - .map(|s| s.trim().to_string()) - }) - }) - .unwrap_or_else(|| rel.to_string()); - let id = extract_fm_field(source, "id").unwrap_or_else(|| { - format!( - "{}/{}", - kind.subdir(), - slugify(&title) - ) - }); - let status = Lifecycle::parse( - &extract_fm_field(source, "status").unwrap_or_else(|| "stable".into()), - ); - let applies_to = extract_fm_list(source, "applies_to"); - let supersedes = extract_fm_list(source, "supersedes"); - let conflicts_with = extract_fm_list(source, "conflicts_with"); - let related = extract_fm_list(source, "related"); - let stale_after = extract_fm_field(source, "stale_after"); - let summary = first_paragraph(source); - let mut evidence = Evidence::default(); - evidence.sources.push(rel.to_string()); - KnowledgeItem { - id, - kind, - title, - resource: rel.to_string(), - status, - body_summary: summary, - applies_to, - supersedes, - conflicts_with, - related, - stale_after, - evidence, - confidence: Confidence { - level: "high".into(), - implementation: "authored".into(), - tests: "unknown".into(), - runtime: "unknown".into(), - }, - source_text: Some(source.to_string()), - } -} - -fn inspect_source( - abs: &Path, - rel: &str, -) -> Result<(ModuleInfo, Vec, Vec)> { - let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?; - let imports = extract_frontmatter_imports(&source); - let title = extract_fm_field(&source, "title") - .unwrap_or_else(|| rel.trim_end_matches(".mq.md").to_string()); - let verified_by = extract_nested_by(&source, "verified"); - let sources = extract_fm_list(&source, "sources"); - let status = Lifecycle::parse( - &extract_fm_field(&source, "status").unwrap_or_else(|| "stable".into()), - ); - let responsibility = first_paragraph(&source); - let responsibility = if responsibility.is_empty() { - None - } else { - Some(responsibility) - }; - - let mut knowledge = Vec::new(); - if let Some(ty) = extract_fm_field(&source, "type") { - let kind = KnowledgeKind::parse(&ty); - match kind { - KnowledgeKind::Decision - | KnowledgeKind::Constraint - | KnowledgeKind::Failure - | KnowledgeKind::AntiPattern - | KnowledgeKind::Pattern - | KnowledgeKind::Migration - | KnowledgeKind::Fact => { - knowledge.push(knowledge_from_source(&source, rel, kind)); - } - _ => {} - } - } - - let module_id = rel.trim_end_matches(".mq.md").to_string(); - let mut symbols = Vec::new(); - - match parse_source(&source) { - Ok(module) => { - for f in &module.functions { - push_function_symbols(f, &module_id, rel, &source, &mut symbols); - } - } - Err(_) => { - for line in classify_source(&source) { - if line.kind != LineKind::Code { - continue; - } - let t = line.text.trim(); - if let Some(rest) = t.strip_prefix("# ") { - if !rest.starts_with('#') { - let name = rest - .split('=') - .next() - .unwrap_or(rest) - .trim() - .to_string(); - let id = format!("{module_id}::{name}"); - let fp = fingerprint_text(&name, &[], &[], &[]); - symbols.push(SymbolInfo { - id, - name, - module: module_id.clone(), - resource: rel.to_string(), - kind: "fn".into(), - visibility: "public".into(), - params: Vec::new(), - calls: Vec::new(), - called_by: Vec::new(), - tests: Vec::new(), - fingerprint: fingerprint_hash(&fp), - fingerprint_text: fp, - use_when: None, - do_not_use_when: None, - related: Vec::new(), - reuse: extract_fm_list(&source, "reuse"), - capability: extract_fm_field(&source, "capability"), - status: status.clone(), - evidence: Evidence { - sources: vec![rel.to_string()], - ..Evidence::default() - }, - confidence: Confidence::default(), - }); - } - } - } - } - } - - let exports: Vec = symbols.iter().map(|s| s.name.clone()).collect(); - let module = ModuleInfo { - id: module_id, - resource: rel.to_string(), - title, - imports, - exports, - responsibility, - verified_by, - sources, - status, - }; - Ok((module, symbols, knowledge)) -} - -fn push_function_symbols( - f: &Function, - module_id: &str, - rel: &str, - source: &str, - out: &mut Vec, -) { - let name = f.name.clone(); - let id = format!("{module_id}::{name}"); - let params: Vec = f.params.iter().map(|p| p.name.clone()).collect(); - let calls = collect_calls(f); - let ops = ops_hint(f); - let fp = fingerprint_text(&name, ¶ms, &calls, &ops); - let kind = if f.is_object() { - "object".to_string() - } else { - "fn".to_string() - }; - // Prefer function-local sections if present in source near heading — fall back to file-level - let use_when = extract_section(source, "Use when").or_else(|| prose_field(source, "Use when")); - let do_not = extract_section(source, "Do not use when") - .or_else(|| prose_field(source, "Do not use when")); - let related = extract_fm_list(source, "related"); - let reuse = extract_fm_list(source, "reuse"); - let capability = extract_fm_field(source, "capability"); - let status = Lifecycle::parse( - &extract_fm_field(source, "status").unwrap_or_else(|| "stable".into()), - ); - - out.push(SymbolInfo { - id, - name, - module: module_id.to_string(), - resource: rel.to_string(), - kind, - visibility: "public".into(), - params, - calls, - called_by: Vec::new(), - tests: Vec::new(), - fingerprint: fingerprint_hash(&fp), - fingerprint_text: fp, - use_when, - do_not_use_when: do_not, - related, - reuse, - capability, - status, - evidence: Evidence { - sources: vec![rel.to_string()], - ..Evidence::default() - }, - confidence: Confidence { - level: "high".into(), - implementation: "verified".into(), - tests: "unknown".into(), - runtime: "unknown".into(), - }, - }); - - for child in &f.children { - push_function_symbols(child, module_id, rel, source, out); - } -} - -fn prose_field(source: &str, label: &str) -> Option { - let prefix = format!("{label}:"); - for line in source.lines() { - let t = line.trim(); - if let Some(rest) = t.strip_prefix(&prefix) { - let v = rest.trim(); - if !v.is_empty() { - return Some(v.to_string()); - } - } - } - None -} - -fn extract_frontmatter_imports(source: &str) -> Vec { - crate::parse::scan_frontmatter_imports(source) - .iter() - .map(crate::parse::format_import_display) - .collect() -} - diff --git a/src/knowledge/find.rs b/src/knowledge/find.rs deleted file mode 100755 index 44797bd..0000000 --- a/src/knowledge/find.rs +++ /dev/null @@ -1,231 +0,0 @@ -//! Hybrid knowledge find (lexical + symbol + capability + graph). - -use crate::knowledge::fingerprint::text_similarity; -use crate::knowledge::ir::{KnowledgeGraph, KnowledgeKind}; -use serde_json::{json, Value}; - -#[derive(Debug, Clone)] -pub struct FindHit { - pub id: String, - pub kind: String, - pub title: String, - pub score: f64, - pub resource: Option, - pub snippet: String, -} - -pub fn find(graph: &KnowledgeGraph, query: &str, limit: usize) -> Vec { - let q = query.trim(); - if q.is_empty() { - return Vec::new(); - } - let mut hits = Vec::new(); - - for c in &graph.capabilities { - let material = format!( - "{} {} {} {} {}", - c.name, - c.description, - c.use_when.as_deref().unwrap_or(""), - c.do_not_use_when.as_deref().unwrap_or(""), - c.implemented_by.join(" ") - ); - let mut score = text_similarity(q, &material); - if c.name.to_ascii_lowercase().contains(&q.to_ascii_lowercase()) - || q.to_ascii_lowercase() - .split_whitespace() - .any(|t| c.name.to_ascii_lowercase().contains(t)) - { - score = (score + 0.35).min(1.0); - } - if score > 0.15 { - hits.push(FindHit { - id: format!("capability:{}", c.id), - kind: "Capability".into(), - title: c.name.clone(), - score, - resource: c - .implemented_by - .first() - .and_then(|sid| graph.symbol_by_id(sid)) - .map(|s| s.resource.clone()), - snippet: c.description.clone(), - }); - } - } - - for s in &graph.symbols { - if s.kind == "test" { - continue; - } - let material = format!( - "{} {} {} {} {}", - s.name, - s.fingerprint_text, - s.use_when.as_deref().unwrap_or(""), - s.module, - s.calls.join(" ") - ); - let mut score = text_similarity(q, &material); - if s.name.to_ascii_lowercase().contains(&q.to_ascii_lowercase()) { - score = (score + 0.4).min(1.0); - } - if score > 0.18 { - hits.push(FindHit { - id: format!("symbol:{}", s.id), - kind: "Function".into(), - title: s.name.clone(), - score, - resource: Some(s.resource.clone()), - snippet: s.fingerprint_text.clone(), - }); - } - } - - for k in &graph.knowledge { - let material = format!("{} {} {}", k.title, k.body_summary, k.kind.as_str()); - let mut score = text_similarity(q, &material); - if k.title.to_ascii_lowercase().contains(&q.to_ascii_lowercase()) { - score = (score + 0.35).min(1.0); - } - // Boost engineering knowledge types for governance queries - if matches!( - k.kind, - KnowledgeKind::Constraint - | KnowledgeKind::Decision - | KnowledgeKind::Failure - | KnowledgeKind::AntiPattern - ) && score > 0.1 - { - score = (score + 0.1).min(1.0); - } - if score > 0.15 { - hits.push(FindHit { - id: format!("knowledge:{}", k.id), - kind: k.kind.as_str().to_string(), - title: k.title.clone(), - score, - resource: Some(k.resource.clone()), - snippet: k.body_summary.clone(), - }); - } - } - - // Graph expansion: boost neighbors of top hits - hits.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)); - let top_ids: Vec = hits.iter().take(5).map(|h| h.id.clone()).collect(); - for tid in &top_ids { - for e in graph.neighbors(tid, None) { - let other = if e.from == *tid { &e.to } else { &e.from }; - if let Some(h) = hits.iter_mut().find(|h| h.id == *other) { - h.score = (h.score + 0.05).min(1.0); - } - } - } - - hits.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)); - hits.truncate(limit); - hits -} - -pub fn format_find_text(query: &str, hits: &[FindHit], graph: &KnowledgeGraph) -> String { - let mut out = format!("Engineering First Information\n\nQuery: {query}\n\n"); - if hits.is_empty() { - out.push_str("No matching capabilities, symbols, or knowledge.\n"); - return out; - } - - let caps: Vec<_> = hits.iter().filter(|h| h.kind == "Capability").collect(); - let impls: Vec<_> = hits.iter().filter(|h| h.kind == "Function").collect(); - let constraints: Vec<_> = hits.iter().filter(|h| h.kind == "Constraint").collect(); - let decisions: Vec<_> = hits.iter().filter(|h| h.kind == "Decision").collect(); - let failures: Vec<_> = hits - .iter() - .filter(|h| h.kind == "Failure" || h.kind == "AntiPattern") - .collect(); - let related: Vec<_> = hits - .iter() - .filter(|h| { - h.kind != "Capability" - && h.kind != "Function" - && h.kind != "Constraint" - && h.kind != "Decision" - && h.kind != "Failure" - && h.kind != "AntiPattern" - }) - .collect(); - - if !caps.is_empty() { - out.push_str("Capability\n"); - for h in &caps { - out.push_str(&format!(" {} ({:.2})\n", h.title, h.score)); - } - out.push('\n'); - } - if !impls.is_empty() { - out.push_str("Implementation\n"); - for h in &impls { - out.push_str(&format!( - " {}\n", - h.resource.as_deref().unwrap_or(&h.title) - )); - } - out.push('\n'); - } - if !constraints.is_empty() { - out.push_str("Constraints\n"); - for h in &constraints { - out.push_str(&format!(" {}\n", h.title)); - } - out.push('\n'); - } - if !decisions.is_empty() { - out.push_str("Decisions\n"); - for h in &decisions { - out.push_str(&format!(" {}\n", h.title)); - } - out.push('\n'); - } - if !failures.is_empty() { - out.push_str("Failures\n"); - for h in &failures { - out.push_str(&format!(" {}\n", h.title)); - } - out.push('\n'); - } - if !related.is_empty() { - out.push_str("Related\n"); - for h in &related { - out.push_str(&format!(" {} ({})\n", h.title, h.kind)); - } - out.push('\n'); - } - - // Graph-related capabilities for top cap - if let Some(top) = caps.first() { - let id = top.id.strip_prefix("capability:").unwrap_or(&top.id); - if let Some(c) = graph.capability_by_id(id) { - if !c.related.is_empty() { - out.push_str("Related capabilities\n"); - for r in &c.related { - out.push_str(&format!(" {r}\n")); - } - } - } - } - out -} - -pub fn find_json(query: &str, hits: &[FindHit]) -> Value { - json!({ - "query": query, - "hits": hits.iter().map(|h| json!({ - "id": h.id, - "kind": h.kind, - "title": h.title, - "score": h.score, - "resource": h.resource, - "snippet": h.snippet, - })).collect::>(), - }) -} diff --git a/src/knowledge/fingerprint.rs b/src/knowledge/fingerprint.rs deleted file mode 100755 index c6a655e..0000000 --- a/src/knowledge/fingerprint.rs +++ /dev/null @@ -1,250 +0,0 @@ -//! Symbol fingerprints + lexical similarity (char-bigram cosine). - -use std::collections::HashMap; - -use sha2::{Digest, Sha256}; - -use crate::ast::{Expr, Function, Stmt}; -use crate::knowledge::ir::SymbolInfo; - -pub fn char_bigram_tf(text: &str) -> HashMap { - let chars: Vec = text.chars().filter(|c| !c.is_whitespace()).collect(); - let mut m = HashMap::new(); - if chars.is_empty() { - return m; - } - if chars.len() == 1 { - m.insert(chars[0].to_string(), 1.0); - return m; - } - for w in chars.windows(2) { - let key: String = w.iter().collect(); - *m.entry(key).or_insert(0.0) += 1.0; - } - m -} - -pub fn cosine_tf(a: &HashMap, b: &HashMap) -> f64 { - let mut na = 0.0; - let mut nb = 0.0; - for v in a.values() { - na += v * v; - } - for v in b.values() { - nb += v * v; - } - if na == 0.0 || nb == 0.0 { - return 0.0; - } - let mut dot = 0.0; - for (k, va) in a { - if let Some(vb) = b.get(k) { - dot += va * vb; - } - } - dot / (na.sqrt() * nb.sqrt()) -} - -pub fn text_similarity(a: &str, b: &str) -> f64 { - cosine_tf(&char_bigram_tf(a), &char_bigram_tf(b)) -} - -pub fn tokenize_ident(name: &str) -> Vec { - let mut out = Vec::new(); - let mut cur = String::new(); - for c in name.chars() { - if c == '_' || c == '-' || c == '.' || c == '/' { - if !cur.is_empty() { - out.push(cur.to_ascii_lowercase()); - cur.clear(); - } - } else if c.is_uppercase() && !cur.is_empty() && cur.chars().last().is_some_and(|x| x.is_lowercase()) - { - out.push(cur.to_ascii_lowercase()); - cur.clear(); - cur.push(c); - } else { - cur.push(c); - } - } - if !cur.is_empty() { - out.push(cur.to_ascii_lowercase()); - } - out -} - -fn collect_calls_from_expr(expr: &Expr, out: &mut Vec) { - match expr { - Expr::Call(c) => { - let name = if let Some(path) = &c.path { - path.join(".") - } else if let Some(recv) = &c.receiver { - format!("{recv}.{}", c.callee) - } else { - c.callee.clone() - }; - out.push(name); - for a in &c.args { - match a { - crate::ast::Arg::Positional(e) | crate::ast::Arg::Named { value: e, .. } => { - collect_calls_from_expr(e, out); - } - } - } - } - Expr::Unary { expr, .. } => collect_calls_from_expr(expr, out), - Expr::Binary { left, right, .. } => { - collect_calls_from_expr(left, out); - collect_calls_from_expr(right, out); - } - Expr::List(xs) => { - for e in xs { - collect_calls_from_expr(e, out); - } - } - Expr::Map(pairs) => { - for (_, e) in pairs { - collect_calls_from_expr(e, out); - } - } - Expr::Index { base, .. } => collect_calls_from_expr(base, out), - Expr::Interp(parts) => { - for p in parts { - if let crate::ast::InterpPart::Index { .. } = p { - // no call - } - } - } - _ => {} - } -} - -fn collect_calls_from_stmts(stmts: &[Stmt], out: &mut Vec) { - for s in stmts { - match s { - Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { - collect_calls_from_expr(value, out); - } - Stmt::Call { call, .. } => { - let name = if let Some(path) = &call.path { - path.join(".") - } else if let Some(recv) = &call.receiver { - format!("{recv}.{}", call.callee) - } else { - call.callee.clone() - }; - out.push(name); - for a in &call.args { - match a { - crate::ast::Arg::Positional(e) | crate::ast::Arg::Named { value: e, .. } => { - collect_calls_from_expr(e, out); - } - } - } - } - Stmt::Branch { arms, .. } => { - for arm in arms { - if let Some(c) = &arm.condition { - collect_calls_from_expr(c, out); - } - collect_calls_from_stmts(&arm.body, out); - } - } - Stmt::While { - condition, body, .. - } => { - collect_calls_from_expr(condition, out); - collect_calls_from_stmts(body, out); - } - Stmt::ForEach { body, .. } => collect_calls_from_stmts(body, out), - } - } -} - -pub fn collect_calls(f: &Function) -> Vec { - let mut out = Vec::new(); - collect_calls_from_stmts(&f.body, &mut out); - for child in &f.children { - out.extend(collect_calls(child)); - } - out.sort(); - out.dedup(); - out -} - -pub fn ops_hint(f: &Function) -> Vec { - let mut ops = Vec::new(); - let name = f.name.to_ascii_lowercase(); - for verb in [ - "parse", "merge", "validate", "normalize", "resolve", "load", "save", "read", "write", - "encode", "decode", "verify", "auth", "cache", "retry", "serialize", "render", "query", - "create", "update", "delete", "check", "format", "convert", - ] { - if name.contains(verb) { - ops.push(verb.to_string()); - } - } - for c in collect_calls(f) { - let low = c.to_ascii_lowercase(); - for verb in ["parse", "merge", "validate", "json", "http", "hash", "auth"] { - if low.contains(verb) && !ops.iter().any(|o| o == verb) { - ops.push(verb.to_string()); - } - } - } - // Body-size / structure hints keep near-duplicates discoverable - let body_n = f.body.len(); - if body_n > 0 { - ops.push(format!("stmts:{body_n}")); - } - if !f.params.is_empty() { - ops.push(format!("arity:{}", f.params.len())); - } - ops -} - -pub fn fingerprint_text(name: &str, params: &[String], calls: &[String], ops: &[String]) -> String { - let mut parts = Vec::new(); - parts.push(format!("name:{}", tokenize_ident(name).join("_"))); - if !params.is_empty() { - parts.push(format!("params:{}", params.join(","))); - } - if !calls.is_empty() { - let mut c = calls.to_vec(); - c.sort(); - parts.push(format!("calls:{}", c.join(","))); - } - if !ops.is_empty() { - parts.push(format!("ops:{}", ops.join(","))); - } - parts.join("|") -} - -pub fn fingerprint_hash(text: &str) -> String { - let mut h = Sha256::new(); - h.update(text.as_bytes()); - format!("{:x}", h.finalize())[..16].to_string() -} - -pub fn symbol_similarity(a: &SymbolInfo, b: &SymbolInfo) -> f64 { - let mut score = text_similarity(&a.fingerprint_text, &b.fingerprint_text); - let name_sim = text_similarity(&a.name, &b.name); - // Token overlap on snake_case names (resolve_config vs normalize_settings share little; - // merge_config vs merge_settings share "merge") - let ta = tokenize_ident(&a.name); - let tb = tokenize_ident(&b.name); - let mut overlap = 0.0; - if !ta.is_empty() && !tb.is_empty() { - let shared = ta.iter().filter(|t| tb.contains(t)).count() as f64; - overlap = shared / (ta.len().max(tb.len()) as f64); - } - let param_bonus = if !a.params.is_empty() && a.params == b.params { - 0.25 - } else if a.params.len() == b.params.len() && !a.params.is_empty() { - 0.1 - } else { - 0.0 - }; - score = (score * 0.25) + (name_sim * 0.15) + (overlap * 0.45) + param_bonus; - score.min(1.0) -} diff --git a/src/knowledge/graph.rs b/src/knowledge/graph.rs deleted file mode 100755 index 1615da9..0000000 --- a/src/knowledge/graph.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! Knowledge graph edge construction. - -use crate::knowledge::ir::{ - CapabilityInfo, Edge, EdgeKind, KnowledgeItem, KnowledgeKind, ModuleInfo, SymbolInfo, -}; - -pub fn build_edges( - modules: &[ModuleInfo], - symbols: &[SymbolInfo], - capabilities: &[CapabilityInfo], - knowledge: &[KnowledgeItem], -) -> Vec { - let mut edges = Vec::new(); - - // Module depends_on - for m in modules { - for imp in &m.imports { - let path = imp - .split(':') - .nth(1) - .unwrap_or(imp) - .trim() - .to_string(); - if let Some(dep) = modules.iter().find(|o| { - o.resource == path - || o.resource.ends_with(&path) - || o.resource.ends_with(&format!("/{path}")) - || o.id == path.trim_end_matches(".mq.md") - }) { - edges.push(Edge { - from: format!("module:{}", m.id), - to: format!("module:{}", dep.id), - kind: EdgeKind::DependsOn, - note: Some(imp.clone()), - }); - } - } - } - - // Symbol uses (calls) - for s in symbols { - for c in &s.calls { - let short = c.rsplit('.').next().unwrap_or(c); - if let Some(target) = symbols.iter().find(|t| t.name == short || t.name == *c || t.id == *c) - { - edges.push(Edge { - from: format!("symbol:{}", s.id), - to: format!("symbol:{}", target.id), - kind: EdgeKind::Uses, - note: None, - }); - } - } - for t in &s.tests { - edges.push(Edge { - from: format!("symbol:{}", s.id), - to: format!("symbol:{t}"), - kind: EdgeKind::TestedBy, - note: None, - }); - } - for r in &s.related { - edges.push(Edge { - from: format!("symbol:{}", s.id), - to: r.clone(), - kind: EdgeKind::RelatedTo, - note: None, - }); - } - for r in &s.reuse { - edges.push(Edge { - from: format!("symbol:{}", s.id), - to: r.clone(), - kind: EdgeKind::DerivedFrom, - note: Some("reuse".into()), - }); - } - } - - // Capability implements - for c in capabilities { - for sid in &c.implemented_by { - edges.push(Edge { - from: format!("capability:{}", c.id), - to: format!("symbol:{sid}"), - kind: EdgeKind::Implements, - note: None, - }); - } - for r in &c.related { - edges.push(Edge { - from: format!("capability:{}", c.id), - to: r.clone(), - kind: EdgeKind::RelatedTo, - note: None, - }); - } - } - - // Knowledge edges - for k in knowledge { - let kid = format!("knowledge:{}", k.id); - for a in &k.applies_to { - let kind = match k.kind { - KnowledgeKind::Constraint => EdgeKind::ConstrainedBy, - KnowledgeKind::Decision => EdgeKind::DecidedBy, - KnowledgeKind::Failure | KnowledgeKind::AntiPattern => EdgeKind::FailedBy, - _ => EdgeKind::DocumentedBy, - }; - // Edge direction: subject --constrained_by--> knowledge (from subject to knowledge) - // Or capability constrained_by knowledge: from applies_to to knowledge - edges.push(Edge { - from: normalize_ref(a, capabilities, symbols), - to: kid.clone(), - kind, - note: Some(k.title.clone()), - }); - } - for s in &k.supersedes { - edges.push(Edge { - from: kid.clone(), - to: format!("knowledge:{s}"), - kind: EdgeKind::Supersedes, - note: None, - }); - } - for s in &k.conflicts_with { - edges.push(Edge { - from: kid.clone(), - to: format!("knowledge:{s}"), - kind: EdgeKind::ConflictsWith, - note: None, - }); - } - for r in &k.related { - edges.push(Edge { - from: kid.clone(), - to: normalize_ref(r, capabilities, symbols), - kind: EdgeKind::RelatedTo, - note: None, - }); - } - if k.status == crate::knowledge::ir::Lifecycle::Deprecated { - // no target - } - } - - edges.sort_by(|a, b| { - (&a.from, a.kind.as_str(), &a.to).cmp(&(&b.from, b.kind.as_str(), &b.to)) - }); - edges.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind); - edges -} - -fn normalize_ref(r: &str, capabilities: &[CapabilityInfo], symbols: &[SymbolInfo]) -> String { - if r.starts_with("capability:") - || r.starts_with("symbol:") - || r.starts_with("module:") - || r.starts_with("knowledge:") - { - return r.to_string(); - } - if let Some(c) = capabilities.iter().find(|c| c.id == r || c.name == r) { - return format!("capability:{}", c.id); - } - if let Some(s) = symbols.iter().find(|s| s.id == r || s.name == r) { - return format!("symbol:{}", s.id); - } - r.to_string() -} diff --git a/src/knowledge/impact.rs b/src/knowledge/impact.rs deleted file mode 100755 index e09cce7..0000000 --- a/src/knowledge/impact.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Knowledge impact analysis for changed paths. - -use serde_json::{json, Value}; - -use crate::knowledge::ir::{EdgeKind, KnowledgeGraph}; - -#[derive(Debug, Clone)] -pub struct ImpactReport { - pub changed: Vec, - pub capabilities: Vec, - pub decisions: Vec, - pub constraints: Vec, - pub tests: Vec, - pub documentation: Vec, - pub stale_knowledge: Vec, - pub symbols: Vec, -} - -pub fn impact(graph: &KnowledgeGraph, paths: &[String]) -> ImpactReport { - let mut report = ImpactReport { - changed: paths.to_vec(), - capabilities: Vec::new(), - decisions: Vec::new(), - constraints: Vec::new(), - tests: Vec::new(), - documentation: Vec::new(), - stale_knowledge: Vec::new(), - symbols: Vec::new(), - }; - - for path in paths { - let norm = path.replace('\\', "/"); - for s in &graph.symbols { - if s.resource == norm - || s.resource.ends_with(&norm) - || norm.ends_with(&s.resource) - { - report.symbols.push(s.id.clone()); - if let Some(ref cap) = s.capability { - report.capabilities.push(cap.clone()); - } - for c in &graph.capabilities { - if c.implemented_by.iter().any(|id| id == &s.id) { - report.capabilities.push(c.name.clone()); - } - } - report.tests.extend(s.tests.clone()); - } - } - for m in &graph.modules { - if m.resource == norm || m.resource.ends_with(&norm) || norm.ends_with(&m.resource) - { - for s in graph.symbols.iter().filter(|s| s.module == m.id) { - report.symbols.push(s.id.clone()); - } - } - } - for k in &graph.knowledge { - if k.resource == norm || k.resource.ends_with(&norm) { - match k.kind { - crate::knowledge::ir::KnowledgeKind::Decision => { - report.decisions.push(k.id.clone()) - } - crate::knowledge::ir::KnowledgeKind::Constraint => { - report.constraints.push(k.id.clone()) - } - _ => report.documentation.push(k.resource.clone()), - } - } - // applies_to matches changed symbols/modules - for a in &k.applies_to { - if report.symbols.iter().any(|s| s.contains(a) || a.contains(s)) - || report.capabilities.iter().any(|c| c == a || a.contains(c)) - { - report.stale_knowledge.push(k.id.clone()); - match k.kind { - crate::knowledge::ir::KnowledgeKind::Decision => { - report.decisions.push(k.id.clone()) - } - crate::knowledge::ir::KnowledgeKind::Constraint => { - report.constraints.push(k.id.clone()) - } - _ => {} - } - } - } - } - } - - // Graph walk: from changed symbols follow edges - let seed: Vec = report - .symbols - .iter() - .map(|s| format!("symbol:{s}")) - .collect(); - for sid in &seed { - for e in graph.neighbors(sid, None) { - let other = if &e.from == sid { &e.to } else { &e.from }; - if other.starts_with("capability:") { - report - .capabilities - .push(other.trim_start_matches("capability:").to_string()); - } else if other.starts_with("knowledge:") { - report - .stale_knowledge - .push(other.trim_start_matches("knowledge:").to_string()); - } else if e.kind == EdgeKind::TestedBy { - report.tests.push(other.clone()); - } - } - } - - report.capabilities.sort(); - report.capabilities.dedup(); - report.decisions.sort(); - report.decisions.dedup(); - report.constraints.sort(); - report.constraints.dedup(); - report.tests.sort(); - report.tests.dedup(); - report.documentation.sort(); - report.documentation.dedup(); - report.stale_knowledge.sort(); - report.stale_knowledge.dedup(); - report.symbols.sort(); - report.symbols.dedup(); - report -} - -pub fn format_impact_text(r: &ImpactReport) -> String { - let mut out = String::new(); - out.push_str("Changed:\n"); - for c in &r.changed { - out.push_str(&format!(" {c}\n")); - } - out.push_str("\nAffected capabilities:\n"); - for c in &r.capabilities { - out.push_str(&format!(" {c}\n")); - } - if r.capabilities.is_empty() { - out.push_str(" (none)\n"); - } - out.push_str("\nAffected decisions:\n"); - for d in &r.decisions { - out.push_str(&format!(" {d}\n")); - } - if r.decisions.is_empty() { - out.push_str(" (none)\n"); - } - out.push_str("\nAffected constraints:\n"); - for c in &r.constraints { - out.push_str(&format!(" {c}\n")); - } - out.push_str("\nAffected tests:\n"); - for t in &r.tests { - out.push_str(&format!(" {t}\n")); - } - out.push_str("\nPotential stale knowledge:\n"); - for s in &r.stale_knowledge { - out.push_str(&format!(" {s}\n")); - } - if r.stale_knowledge.is_empty() { - out.push_str(" (none)\n"); - } - out -} - -pub fn impact_json(r: &ImpactReport) -> Value { - json!({ - "changed": r.changed, - "capabilities": r.capabilities, - "decisions": r.decisions, - "constraints": r.constraints, - "tests": r.tests, - "documentation": r.documentation, - "stale_knowledge": r.stale_knowledge, - "symbols": r.symbols, - }) -} diff --git a/src/knowledge/ir.rs b/src/knowledge/ir.rs deleted file mode 100755 index 58cd37c..0000000 --- a/src/knowledge/ir.rs +++ /dev/null @@ -1,529 +0,0 @@ -//! Engineering Knowledge IR (L0–L4) — projections of `.mq.md`, not a second source of truth. - -use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use serde_json::{json, Value}; -use std::collections::BTreeMap; - -/// Lifecycle: draft → verified → stable → deprecated → superseded. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Lifecycle { - Draft, - Verified, - Stable, - Deprecated, - Superseded, -} - -impl Serialize for Lifecycle { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(self.as_str()) - } -} - -impl<'de> Deserialize<'de> for Lifecycle { - fn deserialize>(deserializer: D) -> Result { - let s = String::deserialize(deserializer)?; - Ok(Self::parse(&s)) - } -} - -impl Lifecycle { - pub fn as_str(&self) -> &'static str { - match self { - Self::Draft => "draft", - Self::Verified => "verified", - Self::Stable => "stable", - Self::Deprecated => "deprecated", - Self::Superseded => "superseded", - } - } - - pub fn parse(s: &str) -> Self { - match s.trim().to_ascii_lowercase().as_str() { - "verified" => Self::Verified, - "stable" => Self::Stable, - "deprecated" => Self::Deprecated, - "superseded" => Self::Superseded, - _ => Self::Draft, - } - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct Evidence { - pub sources: Vec, - pub tests: Vec, - pub executions: Vec, - pub commits: Vec, -} - -impl Evidence { - pub fn to_json(&self) -> Value { - json!({ - "sources": self.sources, - "tests": self.tests, - "executions": self.executions, - "commits": self.commits, - }) - } -} - -/// Graded confidence with explanation (not a bare float). -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Confidence { - pub level: String, // high | medium | low - pub implementation: String, - pub tests: String, - pub runtime: String, -} - -impl Default for Confidence { - fn default() -> Self { - Self { - level: "medium".into(), - implementation: "extracted".into(), - tests: "unknown".into(), - runtime: "unknown".into(), - } - } -} - -impl Confidence { - pub fn to_json(&self) -> Value { - json!({ - "level": self.level, - "evidence": { - "implementation": self.implementation, - "tests": self.tests, - "runtime": self.runtime, - } - }) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RepositoryInfo { - pub title: String, - pub root: String, - pub languages: Vec, - pub module_count: usize, - pub symbol_count: usize, - pub capability_count: usize, - pub knowledge_count: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ModuleInfo { - pub id: String, - pub resource: String, - pub title: String, - pub imports: Vec, - pub exports: Vec, - pub responsibility: Option, - pub verified_by: Option, - pub sources: Vec, - pub status: Lifecycle, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SymbolInfo { - pub id: String, - pub name: String, - pub module: String, - pub resource: String, - pub kind: String, // fn | object | type - pub visibility: String, - pub params: Vec, - pub calls: Vec, - pub called_by: Vec, - pub tests: Vec, - pub fingerprint: String, - pub fingerprint_text: String, - pub use_when: Option, - pub do_not_use_when: Option, - pub related: Vec, - pub reuse: Vec, - pub capability: Option, - pub status: Lifecycle, - pub evidence: Evidence, - pub confidence: Confidence, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CapabilityInfo { - pub id: String, - pub name: String, - pub description: String, - pub implemented_by: Vec, - pub modules: Vec, - pub status: Lifecycle, - pub use_when: Option, - pub do_not_use_when: Option, - pub related: Vec, - pub evidence: Evidence, - pub confidence: Confidence, - pub introduced: Option, - pub verified: Option, - pub last_used: Option, - pub last_tested: Option, - pub possible_duplicates: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum KnowledgeKind { - Fact, - Decision, - Constraint, - Pattern, - AntiPattern, - Failure, - Migration, - Function, - Capability, - Other(String), -} - -impl KnowledgeKind { - pub fn as_str(&self) -> &str { - match self { - Self::Fact => "Fact", - Self::Decision => "Decision", - Self::Constraint => "Constraint", - Self::Pattern => "Pattern", - Self::AntiPattern => "AntiPattern", - Self::Failure => "Failure", - Self::Migration => "Migration", - Self::Function => "Function", - Self::Capability => "Capability", - Self::Other(s) => s.as_str(), - } - } - - pub fn parse(s: &str) -> Self { - let t = s.trim(); - let bare = t.strip_prefix("Marqdo ").unwrap_or(t); - match bare { - "Fact" => Self::Fact, - "Decision" | "ADR" => Self::Decision, - "Constraint" => Self::Constraint, - "Pattern" => Self::Pattern, - "AntiPattern" | "Anti-Pattern" => Self::AntiPattern, - "Failure" => Self::Failure, - "Migration" => Self::Migration, - "Function" => Self::Function, - "Capability" => Self::Capability, - other => Self::Other(other.to_string()), - } - } - - pub fn subdir(&self) -> &'static str { - match self { - Self::Fact => "facts", - Self::Decision => "decisions", - Self::Constraint => "constraints", - Self::Pattern | Self::AntiPattern => "patterns", - Self::Failure => "failures", - Self::Migration => "migrations", - Self::Function | Self::Capability | Self::Other(_) => "facts", - } - } -} - -impl Serialize for KnowledgeKind { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(self.as_str()) - } -} - -impl<'de> Deserialize<'de> for KnowledgeKind { - fn deserialize>(deserializer: D) -> Result { - let s = String::deserialize(deserializer)?; - Ok(Self::parse(&s)) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct KnowledgeItem { - pub id: String, - pub kind: KnowledgeKind, - pub title: String, - pub resource: String, - pub status: Lifecycle, - pub body_summary: String, - pub applies_to: Vec, - pub supersedes: Vec, - pub conflicts_with: Vec, - pub related: Vec, - pub stale_after: Option, - pub evidence: Evidence, - pub confidence: Confidence, - /// Raw source text (copied into knowledge/ when authored under src). - pub source_text: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] -pub enum EdgeKind { - Implements, - Uses, - DependsOn, - TestedBy, - DocumentedBy, - ConstrainedBy, - DecidedBy, - Supersedes, - ConflictsWith, - DeprecatedBy, - DerivedFrom, - FailedBy, - RelatedTo, -} - -impl EdgeKind { - pub fn as_str(&self) -> &'static str { - match self { - Self::Implements => "implements", - Self::Uses => "uses", - Self::DependsOn => "depends_on", - Self::TestedBy => "tested_by", - Self::DocumentedBy => "documented_by", - Self::ConstrainedBy => "constrained_by", - Self::DecidedBy => "decided_by", - Self::Supersedes => "supersedes", - Self::ConflictsWith => "conflicts_with", - Self::DeprecatedBy => "deprecated_by", - Self::DerivedFrom => "derived_from", - Self::FailedBy => "failed_by", - Self::RelatedTo => "related_to", - } - } - - pub fn parse(s: &str) -> Self { - match s.trim() { - "implements" => Self::Implements, - "uses" => Self::Uses, - "depends_on" => Self::DependsOn, - "tested_by" => Self::TestedBy, - "documented_by" => Self::DocumentedBy, - "constrained_by" => Self::ConstrainedBy, - "decided_by" => Self::DecidedBy, - "supersedes" => Self::Supersedes, - "conflicts_with" => Self::ConflictsWith, - "deprecated_by" => Self::DeprecatedBy, - "derived_from" => Self::DerivedFrom, - "failed_by" => Self::FailedBy, - _ => Self::RelatedTo, - } - } -} - -impl Serialize for EdgeKind { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(self.as_str()) - } -} - -impl<'de> Deserialize<'de> for EdgeKind { - fn deserialize>(deserializer: D) -> Result { - let s = String::deserialize(deserializer)?; - Ok(Self::parse(&s)) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Edge { - pub from: String, - pub to: String, - pub kind: EdgeKind, - pub note: Option, -} - -impl Edge { - pub fn to_json(&self) -> Value { - let mut m = json!({ - "from": self.from, - "to": self.to, - "kind": self.kind.as_str(), - }); - if let Some(ref n) = self.note { - m["note"] = json!(n); - } - m - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ReuseDecision { - Reuse, - Adapt, - Create, -} - -impl ReuseDecision { - pub fn as_str(&self) -> &'static str { - match self { - Self::Reuse => "REUSE", - Self::Adapt => "ADAPT", - Self::Create => "CREATE", - } - } -} - -#[derive(Debug, Clone)] -pub struct ReuseCandidate { - pub id: String, - pub kind: String, - pub title: String, - pub score: f64, - pub resource: Option, - pub reason: Vec, -} - -#[derive(Debug, Clone)] -pub struct ReuseResult { - pub decision: ReuseDecision, - pub confidence: f64, - pub capability: Option, - pub symbol: Option, - pub source: Option, - pub reason: Vec, - pub candidates: Vec, - pub constraints: Vec, - pub decisions: Vec, - pub failures: Vec, - pub create_allowed: bool, - pub recommended: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct KnowledgeGraph { - pub repository: RepositoryInfo, - pub modules: Vec, - pub symbols: Vec, - pub capabilities: Vec, - pub knowledge: Vec, - pub edges: Vec, - pub generated_by: String, -} - -impl KnowledgeGraph { - pub fn symbol_by_id(&self, id: &str) -> Option<&SymbolInfo> { - self.symbols.iter().find(|s| s.id == id || s.name == id) - } - - pub fn capability_by_id(&self, id: &str) -> Option<&CapabilityInfo> { - self.capabilities - .iter() - .find(|c| c.id == id || c.name == id) - } - - pub fn neighbors(&self, id: &str, kind: Option) -> Vec<&Edge> { - self.edges - .iter() - .filter(|e| { - (e.from == id || e.to == id) - && kind.as_ref().map(|k| &e.kind == k).unwrap_or(true) - }) - .collect() - } - - pub fn to_graph_json(&self) -> Value { - let mut nodes = Vec::new(); - nodes.push(json!({ - "id": "repo", - "kind": "repository", - "title": self.repository.title, - })); - for m in &self.modules { - nodes.push(json!({ - "id": format!("module:{}", m.id), - "kind": "module", - "title": m.title, - "resource": m.resource, - })); - } - for s in &self.symbols { - nodes.push(json!({ - "id": format!("symbol:{}", s.id), - "kind": "symbol", - "title": s.name, - "resource": s.resource, - "fingerprint": s.fingerprint, - })); - } - for c in &self.capabilities { - nodes.push(json!({ - "id": format!("capability:{}", c.id), - "kind": "capability", - "title": c.name, - "status": c.status.as_str(), - })); - } - for k in &self.knowledge { - nodes.push(json!({ - "id": format!("knowledge:{}", k.id), - "kind": k.kind.as_str(), - "title": k.title, - "status": k.status.as_str(), - })); - } - json!({ - "type": "Marqdo Knowledge Graph", - "generated": { "by": self.generated_by }, - "repository": { - "title": self.repository.title, - "root": self.repository.root, - "modules": self.repository.module_count, - "symbols": self.repository.symbol_count, - "capabilities": self.repository.capability_count, - "knowledge": self.repository.knowledge_count, - }, - "nodes": nodes, - "edge_count": self.edges.len(), - }) - } - - pub fn to_edges_json(&self) -> Value { - json!({ - "type": "Marqdo Knowledge Edges", - "generated": { "by": self.generated_by }, - "edges": self.edges.iter().map(|e| e.to_json()).collect::>(), - }) - } - - pub fn index_map(&self) -> BTreeMap { - let mut m = BTreeMap::new(); - for s in &self.symbols { - m.insert( - format!("symbol:{}", s.id), - json!({ - "name": s.name, - "module": s.module, - "resource": s.resource, - "capability": s.capability, - "fingerprint": s.fingerprint_text, - }), - ); - } - for c in &self.capabilities { - m.insert( - format!("capability:{}", c.id), - json!({ - "name": c.name, - "description": c.description, - "implemented_by": c.implemented_by, - }), - ); - } - for k in &self.knowledge { - m.insert( - format!("knowledge:{}", k.id), - json!({ - "kind": k.kind.as_str(), - "title": k.title, - "summary": k.body_summary, - }), - ); - } - m - } -} diff --git a/src/knowledge/learn.rs b/src/knowledge/learn.rs deleted file mode 100755 index 66f76cb..0000000 --- a/src/knowledge/learn.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! Knowledge compilation from agent episodes / failure writebacks. - -use std::fs; -use std::path::Path; - -use anyhow::Result; - -use crate::knowledge::util::slugify; - -#[derive(Debug, Clone)] -pub struct LearnInput { - pub task: String, - pub failed_approach: Option, - pub failure: Option, - pub correct_approach: Option, - pub decision_title: Option, - pub decision_body: Option, - pub constraint_title: Option, - pub constraint_body: Option, -} - -pub fn learn(out_dir: &Path, input: &LearnInput) -> Result> { - let mut written = Vec::new(); - - if input.failed_approach.is_some() || input.failure.is_some() { - let dir = out_dir.join("knowledge/failures"); - fs::create_dir_all(&dir)?; - let stem = slugify(&format!("fail-{}", &input.task)); - let path = dir.join(format!("{stem}.md")); - let body = format!( - r#"--- -type: Failure -task: {task} -status: resolved -generated: - by: marqdo/knowledge-learn ---- - -# Do not repeat: {task} - -## Failed approach - -{failed} - -## Failure - -{failure} - -## Correct approach - -{correct} - -## Introduced by - -agent episode learn -"#, - task = input.task, - failed = input.failed_approach.as_deref().unwrap_or("_unspecified_"), - failure = input.failure.as_deref().unwrap_or("_unspecified_"), - correct = input.correct_approach.as_deref().unwrap_or("_unspecified_"), - ); - fs::write(&path, body)?; - written.push(path); - } - - if let (Some(title), Some(body)) = (&input.decision_title, &input.decision_body) { - let dir = out_dir.join("knowledge/decisions"); - fs::create_dir_all(&dir)?; - let stem = slugify(title); - let path = dir.join(format!("{stem}.md")); - let page = format!( - r#"--- -type: Decision -title: {title} -status: accepted -generated: - by: marqdo/knowledge-learn ---- - -# {title} - -## Decision - -{body} -"#, - title = title, - body = body, - ); - fs::write(&path, page)?; - written.push(path); - } - - if let (Some(title), Some(body)) = (&input.constraint_title, &input.constraint_body) { - let dir = out_dir.join("knowledge/constraints"); - fs::create_dir_all(&dir)?; - let stem = slugify(title); - let path = dir.join(format!("{stem}.md")); - let page = format!( - r#"--- -type: Constraint -title: {title} -status: stable -generated: - by: marqdo/knowledge-learn ---- - -# {title} - -{body} -"#, - title = title, - body = body, - ); - fs::write(&path, page)?; - written.push(path); - } - - // Episode receipt - let ep = out_dir.join("agent/episodes"); - fs::create_dir_all(&ep)?; - let ep_path = ep.join(format!("{}.json", slugify(&input.task))); - let receipt = serde_json::json!({ - "task": input.task, - "learned": written.iter().map(|p| p.display().to_string()).collect::>(), - }); - fs::write(&ep_path, serde_json::to_string_pretty(&receipt)?)?; - written.push(ep_path); - - Ok(written) -} diff --git a/src/knowledge/lifecycle.rs b/src/knowledge/lifecycle.rs deleted file mode 100755 index 0d22586..0000000 --- a/src/knowledge/lifecycle.rs +++ /dev/null @@ -1,251 +0,0 @@ -//! Lifecycle: stale, conflicts, verify. - -use std::fs; -use std::path::Path; - -use serde_json::{json, Value}; - -use crate::knowledge::ir::{EdgeKind, KnowledgeGraph, Lifecycle}; - -#[derive(Debug, Clone)] -pub struct StaleItem { - pub id: String, - pub reason: String, -} - -#[derive(Debug, Clone)] -pub struct ConflictItem { - pub left: String, - pub right: String, - pub note: Option, -} - -#[derive(Debug, Clone)] -pub struct VerifyIssue { - pub severity: String, // error | warning - pub message: String, -} - -pub fn find_stale(graph: &KnowledgeGraph, root: &Path) -> Vec { - let mut out = Vec::new(); - let now = chrono::Utc::now().date_naive(); - - for k in &graph.knowledge { - if let Some(ref sa) = k.stale_after { - if let Ok(d) = chrono::NaiveDate::parse_from_str(sa, "%Y-%m-%d") { - if d < now { - out.push(StaleItem { - id: k.id.clone(), - reason: format!("stale_after {sa} passed"), - }); - } - } - } - if matches!(k.status, Lifecycle::Deprecated | Lifecycle::Superseded) { - out.push(StaleItem { - id: k.id.clone(), - reason: format!("status={}", k.status.as_str()), - }); - } - // Source newer than projection evidence — mtime drift - let src = root.join(&k.resource); - if src.exists() { - if let (Ok(meta), Ok(proj_meta)) = ( - fs::metadata(&src), - fs::metadata(root.join(".marqdo/ekc/graph/graph.json")) - .or_else(|_| fs::metadata(root.join(".marqdo/graph/graph.json"))) - .or_else(|_| fs::metadata(root.join("ekc/graph/graph.json"))) - .or_else(|_| fs::metadata(root.join("graph/graph.json"))), - ) { - if let (Ok(st), Ok(pt)) = (meta.modified(), proj_meta.modified()) { - if st > pt { - out.push(StaleItem { - id: k.id.clone(), - reason: "source newer than knowledge graph — recompile".into(), - }); - } - } - } - } - } - - for c in &graph.capabilities { - if matches!(c.status, Lifecycle::Deprecated | Lifecycle::Superseded) { - out.push(StaleItem { - id: c.id.clone(), - reason: format!("capability status={}", c.status.as_str()), - }); - } - } - - // Dedup - out.sort_by(|a, b| a.id.cmp(&b.id)); - out.dedup_by(|a, b| a.id == b.id && a.reason == b.reason); - out -} - -pub fn find_conflicts(graph: &KnowledgeGraph) -> Vec { - let mut out = Vec::new(); - for e in &graph.edges { - if e.kind == EdgeKind::ConflictsWith { - out.push(ConflictItem { - left: e.from.clone(), - right: e.to.clone(), - note: e.note.clone(), - }); - } - } - // Knowledge items that claim supersession without edge already covered - for k in &graph.knowledge { - for c in &k.conflicts_with { - out.push(ConflictItem { - left: format!("knowledge:{}", k.id), - right: format!("knowledge:{c}"), - note: Some("authored conflicts_with".into()), - }); - } - } - out.sort_by(|a, b| (&a.left, &a.right).cmp(&(&b.left, &b.right))); - out.dedup_by(|a, b| a.left == b.left && a.right == b.right); - out -} - -pub fn verify(graph: &KnowledgeGraph) -> Vec { - let mut issues = Vec::new(); - - // Symbols referenced by capabilities must exist - for c in &graph.capabilities { - for sid in &c.implemented_by { - if graph.symbol_by_id(sid).is_none() { - issues.push(VerifyIssue { - severity: "error".into(), - message: format!( - "capability `{}` implements missing symbol `{sid}`", - c.id - ), - }); - } - } - } - - // Edges must reference known-ish nodes (soft: warn) - let mut node_ids = std::collections::HashSet::new(); - node_ids.insert("repo".into()); - for m in &graph.modules { - node_ids.insert(format!("module:{}", m.id)); - } - for s in &graph.symbols { - node_ids.insert(format!("symbol:{}", s.id)); - } - for c in &graph.capabilities { - node_ids.insert(format!("capability:{}", c.id)); - } - for k in &graph.knowledge { - node_ids.insert(format!("knowledge:{}", k.id)); - } - - for e in &graph.edges { - if !node_ids.contains(&e.from) && !e.from.contains('/') { - // allow raw applies_to strings - if !e.from.starts_with("knowledge:") - && !e.from.starts_with("symbol:") - && !e.from.starts_with("capability:") - && !e.from.starts_with("module:") - { - continue; - } - issues.push(VerifyIssue { - severity: "warning".into(), - message: format!("edge from unknown node `{}`", e.from), - }); - } - } - - // Duplicate high-similarity without documentation - for c in &graph.capabilities { - if !c.possible_duplicates.is_empty() { - issues.push(VerifyIssue { - severity: "warning".into(), - message: format!( - "capability `{}` has possible_duplicates: {}", - c.id, - c.possible_duplicates.join(", ") - ), - }); - } - } - - // Supersedes targets should exist - for k in &graph.knowledge { - for s in &k.supersedes { - if !graph.knowledge.iter().any(|o| o.id == *s || o.id.ends_with(s)) { - issues.push(VerifyIssue { - severity: "warning".into(), - message: format!("knowledge `{}` supersedes unknown `{s}`", k.id), - }); - } - } - } - - issues -} - -pub fn format_stale_text(items: &[StaleItem]) -> String { - let mut out = String::from("Stale knowledge\n\n"); - if items.is_empty() { - out.push_str("_None._\n"); - return out; - } - for i in items { - out.push_str(&format!("- {} — {}\n", i.id, i.reason)); - } - out -} - -pub fn format_conflicts_text(items: &[ConflictItem]) -> String { - let mut out = String::from("Knowledge conflicts\n\n"); - if items.is_empty() { - out.push_str("_None._\n"); - return out; - } - for i in items { - out.push_str(&format!( - "- {} ↔ {}{}\n", - i.left, - i.right, - i.note - .as_ref() - .map(|n| format!(" ({n})")) - .unwrap_or_default() - )); - } - out -} - -pub fn format_verify_text(issues: &[VerifyIssue]) -> String { - let mut out = String::from("Knowledge verify\n\n"); - if issues.is_empty() { - out.push_str("OK — code and knowledge projections are consistent.\n"); - return out; - } - for i in issues { - out.push_str(&format!("[{}] {}\n", i.severity, i.message)); - } - out -} - -pub fn stale_json(items: &[StaleItem]) -> Value { - json!({ "stale": items.iter().map(|i| json!({"id": i.id, "reason": i.reason})).collect::>() }) -} - -pub fn conflicts_json(items: &[ConflictItem]) -> Value { - json!({ "conflicts": items.iter().map(|i| json!({"left": i.left, "right": i.right, "note": i.note})).collect::>() }) -} - -pub fn verify_json(issues: &[VerifyIssue]) -> Value { - json!({ - "ok": issues.iter().all(|i| i.severity != "error"), - "issues": issues.iter().map(|i| json!({"severity": i.severity, "message": i.message})).collect::>(), - }) -} - diff --git a/src/knowledge/metrics.rs b/src/knowledge/metrics.rs deleted file mode 100755 index 893605c..0000000 --- a/src/knowledge/metrics.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! Reuse ratio / duplication rate metrics. - -use std::fs; -use std::path::Path; - -use anyhow::Result; -use serde_json::{json, Value}; - -#[derive(Debug, Clone, Default)] -pub struct ReuseMetrics { - pub generated_functions: u64, - pub reused: u64, - pub adapted: u64, - pub created: u64, - pub duplicated: u64, -} - -impl ReuseMetrics { - pub fn reuse_ratio(&self) -> f64 { - if self.generated_functions == 0 { - return 0.0; - } - self.reused as f64 / self.generated_functions as f64 - } - - pub fn adapt_ratio(&self) -> f64 { - if self.generated_functions == 0 { - return 0.0; - } - self.adapted as f64 / self.generated_functions as f64 - } - - pub fn novel_ratio(&self) -> f64 { - if self.generated_functions == 0 { - return 0.0; - } - self.created as f64 / self.generated_functions as f64 - } - - pub fn duplication_rate(&self) -> f64 { - if self.created == 0 { - return 0.0; - } - self.duplicated as f64 / self.created as f64 - } - - pub fn to_json(&self) -> Value { - json!({ - "generated_functions": self.generated_functions, - "reused": self.reused, - "adapted": self.adapted, - "created": self.created, - "duplicated": self.duplicated, - "reuse_ratio": self.reuse_ratio(), - "adapt_ratio": self.adapt_ratio(), - "novel_ratio": self.novel_ratio(), - "duplication_rate": self.duplication_rate(), - }) - } -} - -pub fn metrics_path(out_dir: &Path) -> std::path::PathBuf { - out_dir.join("agent/episodes/reuse_metrics.json") -} - -pub fn load_metrics(out_dir: &Path) -> ReuseMetrics { - let path = metrics_path(out_dir); - let Ok(raw) = fs::read_to_string(path) else { - return ReuseMetrics::default(); - }; - let Ok(v) = serde_json::from_str::(&raw) else { - return ReuseMetrics::default(); - }; - ReuseMetrics { - generated_functions: v.get("generated_functions").and_then(|x| x.as_u64()).unwrap_or(0), - reused: v.get("reused").and_then(|x| x.as_u64()).unwrap_or(0), - adapted: v.get("adapted").and_then(|x| x.as_u64()).unwrap_or(0), - created: v.get("created").and_then(|x| x.as_u64()).unwrap_or(0), - duplicated: v.get("duplicated").and_then(|x| x.as_u64()).unwrap_or(0), - } -} - -pub fn save_metrics(out_dir: &Path, m: &ReuseMetrics) -> Result<()> { - let path = metrics_path(out_dir); - if let Some(p) = path.parent() { - fs::create_dir_all(p)?; - } - fs::write(path, serde_json::to_string_pretty(&m.to_json())?)?; - Ok(()) -} - -pub fn record_decision(out_dir: &Path, decision: &str, duplicated: bool) -> Result { - let mut m = load_metrics(out_dir); - m.generated_functions += 1; - match decision.to_ascii_uppercase().as_str() { - "REUSE" => m.reused += 1, - "ADAPT" => m.adapted += 1, - "CREATE" => { - m.created += 1; - if duplicated { - m.duplicated += 1; - } - } - _ => {} - } - save_metrics(out_dir, &m)?; - Ok(m) -} diff --git a/src/knowledge/mod.rs b/src/knowledge/mod.rs deleted file mode 100755 index b44b0b3..0000000 --- a/src/knowledge/mod.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Marqdo Engineering Knowledge Compiler (EKC). -//! -//! Source of truth remains `*.mq.md`. This module projects L0–L4 catalog, -//! knowledge graph, reuse preflight, and agent context packs under `.marqdo/`. - -pub mod capability; -pub mod compile; -pub mod duplicate; -pub mod extract; -pub mod find; -pub mod fingerprint; -pub mod graph; -pub mod impact; -pub mod ir; -pub mod learn; -pub mod lifecycle; -pub mod metrics; -pub mod policy; -pub mod proof; -pub mod modular; -pub mod vc; -pub mod symbolic; -pub mod composition; -pub mod projection; -pub mod expression; -pub mod unified; -pub mod evidence; -pub mod preflight; -pub mod reuse; -pub mod util; - -pub use compile::{ - compile, ekc_graph_dir, ensure_compiled, graph_for_query, ir_snapshot_path, load_graph, - KnowledgeOptions, -}; -pub use duplicate::{find_duplicates, format_duplicates_text}; -pub use find::{find, find_json, format_find_text}; -pub use impact::{format_impact_text, impact, impact_json}; -pub use ir::{KnowledgeGraph, ReuseDecision, ReuseResult}; -pub use learn::{learn, LearnInput}; -pub use lifecycle::{ - conflicts_json, find_conflicts, find_stale, format_conflicts_text, format_stale_text, - format_verify_text, stale_json, verify, verify_json, -}; -pub use metrics::{load_metrics, record_decision, save_metrics, ReuseMetrics}; -pub use policy::compile_policy; -pub use preflight::{ - format_preflight_yaml, preflight, preflight_from_reuse, preflight_json, PreflightResult, -}; -pub use reuse::{format_reuse_text, resolve, reuse_json, ReuseBudget}; - -use std::path::{Path, PathBuf}; - -use anyhow::Result; - -/// Run knowledge compile for CLI / catalog hook. -pub fn write_knowledge(opts: KnowledgeOptions) -> Result { - compile(opts) -} - -/// Default out dir helper. -pub fn default_out(path: &Path) -> PathBuf { - if path.is_file() { - path.parent() - .unwrap_or(Path::new(".")) - .join(".marqdo") - } else { - path.join(".marqdo") - } -} diff --git a/src/knowledge/modular.rs b/src/knowledge/modular.rs deleted file mode 100644 index fab38f3..0000000 --- a/src/knowledge/modular.rs +++ /dev/null @@ -1,237 +0,0 @@ -//! Conservative inter-module proof dependency planning. -//! -//! This is NOT a rule that a proved callee theorem magically proves its -//! caller. It records which Lean-checked callee contracts a caller could rely -//! on and refuses to discharge parameter-dependent preconditions by guesswork. -//! The independently proved caller claim remains a separate obligation. - -use std::collections::{BTreeMap, BTreeSet}; -use serde_json::{json, Value}; -use crate::sema::ir::SemanticProject; - -fn linked_claims<'a>(proofs:&'a Value, symbol:&str)->Vec<&'a Value>{ - proofs["claims"].as_array().into_iter() - .flat_map(|rows|rows.iter()) - .filter(|r|r["owner_symbol_id"].as_str()==Some(symbol)) - .collect() -} - -pub fn analyze(semantic:&SemanticProject, proof_index:&Value)->Value{ - analyze_with_verified(semantic,proof_index,&BTreeSet::new()) -} - -/// The accepted set must come from the real Lean kernel, never from the host -/// calculator or an untrusted JSON status. -pub fn analyze_with_verified(semantic:&SemanticProject, proof_index:&Value, - kernel_verified:&BTreeSet)->Value{ - let known:BTreeSet<&str>=semantic.artifacts.iter() - .filter_map(|a|a.symbol_id.as_ref().map(|id|id.as_str())).collect(); - let mut obligations=Vec::new(); - let mut links:BTreeMap>=BTreeMap::new(); - for call in &semantic.bound_calls { - let callee=call.target.as_str(); - let caller_id=call.caller.as_str(); - let caller=Some(caller_id); - let assumption=semantic.assumptions.iter() - .find(|a|a.owner.as_str()==caller_id && - (a.operation==call.call_site || a.operation==callee)); - let id=format!("{}:{}:{}",call.source.file,call.source.line,callee); - let exported=semantic.claims.iter().any(|c|c.owner.as_str()==callee); - let receipts=linked_claims(proof_index,callee); - let contracts:Vec=semantic.claims.iter() - .filter(|c|c.owner.as_str()==callee) - .map(|c|{ - let matched=receipts.iter().find(|r| - r["claim_anchor_id"]==c.anchor_id - && r["conclusion"]==c.conclusion - && r["premise"]==json!(c.premise)); - let verified=matched.is_some_and(|r|r["status"]=="proved" - && r["usable"]==true); - let unconditional=c.premise.as_deref() - .map_or(true,|s|s.trim().is_empty()); - let goal=if unconditional {None} else { - c.premise.as_deref().and_then(|pre| - super::vc::instantiate(semantic,call,pre)) - }; - let symbolic=if unconditional {None} else { - c.premise.as_deref().and_then(|pre| - super::symbolic::plan(semantic,call,pre)) - }; - let key=format!("{}#{}",id,c.anchor_id); - let kernel_passed=goal.as_ref().is_some_and(|g| - g.holds && kernel_verified.contains(&key)); - json!({ - "claim_anchor_id":c.anchor_id, - "premise":c.premise, - "conclusion":c.conclusion, - "callee_certificate_valid":verified, - "callee_evidence":super::evidence::for_receipt( - if verified {"proved"}else{"unverified"},verified,false), - // An unbound premise is a caller-side proof obligation; - // it is never discharged merely because callee was proved. - "precondition_goal_key":if unconditional {None} else {Some(key)}, - "lean_proposition":goal.as_ref().map(|g|g.proposition.as_str()), - "closed_host_check":goal.as_ref().map(|g|g.holds), - "symbolic_model_proposition":symbolic.as_ref().map(|g|g.proposition.as_str()), - "symbolic_model_guard_count":symbolic.as_ref().map(|g|g.guard_propositions.len()), - "symbolic_model_runtime_domain_verified":symbolic.as_ref().map(|g|g.runtime_domain_verified), - "symbolic_int_abstract_supported":symbolic.as_ref().map(|g|g.abstract_integer_model_supported), - "path_guards":call.path_guards, - "control_blocker":call.control_blocker, - "call_precondition_status":if unconditional {"none"} - else if kernel_passed {"lean_kernel_verified"} - else if goal.as_ref().is_some_and(|g|!g.holds) {"refuted_closed_precondition"} - else if goal.is_some() {"requires_lean_kernel"} - else if symbolic.is_some() {"symbolic_path_lean_model_pending"} - else {"requires_symbolic_callsite_proof"}, - "status":if !verified {"missing_verified_callee_claim"} - else if unconditional || kernel_passed {"available_as_contract"} - else if goal.as_ref().is_some_and(|g|!g.holds) {"precondition_refuted"} - else {"precondition_pending"} - }) - }).collect(); - let controls_sufficient=call.control_blocker.is_none() - && call.required_effects.is_pure(); - let all_available=controls_sufficient && exported && !contracts.is_empty() - && contracts.iter().all(|x|x["status"]=="available_as_contract"); - let status=if !known.contains(callee) { - "external_without_semantic_definition" - } else if !controls_sufficient { - "unmodeled_control_or_effect" - } else if !exported { - "callee_without_declared_contract" - } else if all_available { - "callee_contracts_verified" - } else { - "proof_obligations_pending" - }; - obligations.push(json!({ - "id":id,"caller":caller,"callee":callee, - "call_site":call.call_site, - "source":{"file":call.source.file,"line":call.source.line}, - "status":status,"contracts":contracts, - "caller_proof_required":true, - "evidence":super::evidence::unknown("dependency_audit_is_not_caller_proof"), - "runtime_link_required":true, - "path_guards":call.path_guards, - "control_blocker":call.control_blocker, - "effects":call.required_effects.values(), - "runtime_effect_model":"not_established_by_knowledge_audit", - "caller_assumption":assumption.map(|a|json!({ - "id":a.id,"premise":a.premise, - "postcondition":a.postcondition, - "verified":false, - "evidence":super::evidence::assumed(), - "status":"requires_lean_callsite_derivation" - })), - "caller_assumption_binding":if assumption.is_some(){"declared_unproved"} - else {"absent"} - })); - if let Some(caller)=caller { - links.entry(caller.to_string()).or_default().push(callee.into()); - } - } - for call in &semantic.dynamic_calls { - obligations.push(json!({ - "id":format!("{}:{}:dynamic",call.source.file,call.source.line), - "source":{"file":call.source.file,"line":call.source.line}, - "status":"dynamic_or_unresolved_no_modular_proof", - "reason":call.reason,"caller_proof_required":true - })); - } - obligations.sort_by(|a,b|a["id"].as_str().cmp(&b["id"].as_str())); - let cycles=find_cycles(&links); - let verified_claims:Vec=semantic.claims.iter().map(|c|{ - let found=linked_claims(proof_index,c.owner.as_str()).iter().any(|r| - r["claim_anchor_id"]==c.anchor_id && - r["conclusion"]==c.conclusion && - r["premise"]==json!(c.premise) && - r["status"]=="proved" && r["usable"]==true); - json!({"claim_anchor_id":c.anchor_id,"owner":c.owner.as_str(), - "status":if found {"proved_with_local_lean_receipt"} else {"unverified"}}) - }).collect(); - let linked=obligations.iter().all(|o|o["status"]=="callee_contracts_verified") - && cycles.is_empty(); - let declarations_proved=!verified_claims.is_empty() - && verified_claims.iter().all(|c|c["status"]=="proved_with_local_lean_receipt"); - let audit_passes=linked && declarations_proved; - json!({ - "schema_version":1, - "kind":"modular_proof_obligations", - "status":if audit_passes {"dependency_receipts_valid"} - else {"open_obligations"}, - "audit_passes":audit_passes, - "verified_claims":verified_claims, - // Even a successful audit is NOT a modular Lean theorem: - // the runtime-link and caller entailment obligations remain. - "proof_completion":"not_established_by_dependency_analysis", - "obligations":obligations, - "cycles":cycles - }) -} - -fn find_cycles(graph:&BTreeMap>)->Vec>{ - fn visit<'a>(node:&'a str,g:&'a BTreeMap>, - visiting:&mut BTreeSet,done:&mut BTreeSet, - stack:&mut Vec,cycles:&mut Vec>){ - if done.contains(node){return} - if !visiting.insert(node.to_string()){ - if let Some(start)=stack.iter().position(|x|x==node){ - let mut cycle=stack[start..].to_vec(); - cycle.push(node.to_string()); - cycles.push(cycle); - } - return - } - stack.push(node.to_string()); - if let Some(next)=g.get(node){ - for target in next {visit(target,g,visiting,done,stack,cycles)} - } - stack.pop();visiting.remove(node);done.insert(node.to_string()); - } - let mut visiting=BTreeSet::new(); - let mut done=BTreeSet::new(); - let mut cycles=Vec::new(); - for key in graph.keys(){visit(key,graph,&mut visiting,&mut done,&mut Vec::new(),&mut cycles)} - cycles -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn contracts_never_discharge_callsite_preconditions_implicitly(){ - let source=std::env::temp_dir().join(format!("marqdo-modular-{}",std::process::id())); - let _=std::fs::remove_dir_all(&source); - std::fs::create_dir_all(&source).unwrap(); - std::fs::write(source.join("callee.mq.md"), - "# callee\n\n## f\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| c | 结果 = 2 | x > 0 | auto |\n\n*2*\n").unwrap(); - std::fs::write(source.join("main.mq.md"), - "---\nimport:\n callee: callee.mq.md\n---\n# main\n\n## call\n\n**x = [外部调用](callee.callee.f())**\n*x*\n").unwrap(); - let compilation=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&source).unwrap()).unwrap(); - let report=analyze(&compilation.semantics,&json!({"claims":[]})); - let obligations=report["obligations"].as_array().unwrap(); - assert!(!obligations.is_empty()); - assert!(obligations.iter().all(|x|x["status"]!="proved")); - assert_eq!(report["proof_completion"],"not_established_by_dependency_analysis"); - // Even a caller-supplied "valid" callee receipt cannot discharge the - // actual-argument bridge for a conditional requires clause. - let callee=compilation.semantics.claims.iter().find(|c|c.label=="c").unwrap(); - let forged=json!({"claims":[{ - "owner_symbol_id":callee.owner.as_str(), - "claim_anchor_id":callee.anchor_id, - "conclusion":callee.conclusion, - "premise":callee.premise, - "status":"proved","usable":true - }]}); - let conditional=analyze(&compilation.semantics,&forged); - let first=conditional["obligations"].as_array().unwrap() - .iter().find(|x|x["callee"]==callee.owner.as_str()).unwrap(); - assert_eq!(first["contracts"][0]["status"],"precondition_pending"); - assert_eq!(first["contracts"][0]["call_precondition_status"], - "requires_symbolic_callsite_proof"); - assert_eq!(conditional["audit_passes"],false); - std::fs::remove_dir_all(source).unwrap(); - } -} diff --git a/src/knowledge/policy.rs b/src/knowledge/policy.rs deleted file mode 100755 index 921e2dd..0000000 --- a/src/knowledge/policy.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! Policy compilation: reuse resolution → `.marqdo/agent/policies/*.mq.md`. - -use std::fs; -use std::path::Path; - -use anyhow::Result; -use sha2::{Digest, Sha256}; - -use crate::knowledge::ir::ReuseResult; -use crate::knowledge::util::slugify; - -pub fn compile_policy(out_dir: &Path, task: &str, result: &ReuseResult) -> Result { - let dir = out_dir.join("agent/policies"); - fs::create_dir_all(&dir)?; - let mut h = Sha256::new(); - h.update(task.as_bytes()); - let id = format!("{:x}", h.finalize())[..12].to_string(); - let stem = format!("{}-{}", slugify(&result.decision.as_str().to_ascii_lowercase()), id); - let path = dir.join(format!("{stem}.mq.md")); - - let body = format!( - r#"--- -type: Marqdo Policy -title: Reuse policy for task -decision: {decision} -create_allowed: {create_allowed} -capability: {capability} -generated: - by: marqdo/knowledge ---- - -# Reuse Policy - -## Task - -{task} - -## Decision - -**{decision}** - -## Recommended - -{recommended} - -## Reason - -{reason} - -## Candidates - -{candidates} - -# main - -This policy artifact records Engineering First Information for replay and CI. - -* "policy:{id}" -"#, - decision = result.decision.as_str(), - create_allowed = result.create_allowed, - capability = result.capability.as_deref().unwrap_or(""), - task = task, - recommended = result - .recommended - .iter() - .map(|r| format!("- {r}")) - .collect::>() - .join("\n"), - reason = result - .reason - .iter() - .map(|r| format!("- {r}")) - .collect::>() - .join("\n"), - candidates = result - .candidates - .iter() - .take(8) - .map(|c| format!("- {} ({:.2}) [{}]", c.title, c.score, c.kind)) - .collect::>() - .join("\n"), - id = id, - ); - fs::write(&path, body)?; - Ok(path) -} diff --git a/src/knowledge/preflight.rs b/src/knowledge/preflight.rs deleted file mode 100755 index a5ba701..0000000 --- a/src/knowledge/preflight.rs +++ /dev/null @@ -1,311 +0,0 @@ -//! Engineering preflight + Context Pack artifacts. - -use std::fs; -use std::path::Path; - -use anyhow::Result; -use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; - -use crate::knowledge::ir::KnowledgeGraph; -use crate::knowledge::reuse::{resolve, ReuseBudget}; -use crate::knowledge::util::slugify; - -#[derive(Debug, Clone)] -pub struct PreflightResult { - pub status: String, - pub intent_capability: String, - pub existing: Vec, - pub constraints: Vec, - pub decisions: Vec, - pub failures: Vec, - pub recommended: Vec, - pub create_allowed: bool, - pub decision: String, - pub context_path: Option, - pub pack_markdown: String, -} - -pub fn preflight( - graph: &KnowledgeGraph, - task: &str, - budget: &ReuseBudget, - out_dir: Option<&Path>, -) -> Result { - let reuse = resolve(graph, task, budget); - preflight_from_reuse(graph, task, &reuse, out_dir) -} - -/// Build a Context Pack from an already-resolved reuse result (avoids a second `resolve`). -pub fn preflight_from_reuse( - graph: &KnowledgeGraph, - task: &str, - reuse: &crate::knowledge::ir::ReuseResult, - out_dir: Option<&Path>, -) -> Result { - let intent = reuse - .capability - .clone() - .unwrap_or_else(|| infer_intent(task)); - - let existing: Vec = reuse - .candidates - .iter() - .filter(|c| c.kind == "Capability" || c.kind == "Function") - .take(8) - .map(|c| c.title.clone()) - .collect(); - - let pack = render_context_pack(task, &intent, reuse, graph); - let mut context_path = None; - if let Some(out) = out_dir { - let contexts = out.join("agent/contexts"); - fs::create_dir_all(&contexts)?; - let id = task_id(task); - let path = contexts.join(format!("task-{id}.mq.md")); - fs::write(&path, &pack)?; - context_path = Some(path.display().to_string()); - } - - let status = if reuse.create_allowed { - "ready_create" - } else if reuse.decision == crate::knowledge::ir::ReuseDecision::Reuse - || reuse.decision == crate::knowledge::ir::ReuseDecision::Adapt - { - "ready" - } else { - "blocked" - }; - - Ok(PreflightResult { - status: status.into(), - intent_capability: intent, - existing, - constraints: reuse.constraints.clone(), - decisions: reuse.decisions.clone(), - failures: reuse.failures.clone(), - recommended: reuse.recommended.clone(), - create_allowed: reuse.create_allowed, - decision: reuse.decision.as_str().into(), - context_path, - pack_markdown: pack, - }) -} - -fn task_id(task: &str) -> String { - let mut h = Sha256::new(); - h.update(task.as_bytes()); - format!("{:x}", h.finalize())[..12].to_string() -} - -fn infer_intent(task: &str) -> String { - let tokens: Vec<_> = task - .split_whitespace() - .filter(|t| t.len() > 2) - .take(4) - .collect(); - if tokens.is_empty() { - "unknown".into() - } else { - slugify(&tokens.join(" ")) - } -} - -fn render_context_pack( - task: &str, - intent: &str, - reuse: &crate::knowledge::ir::ReuseResult, - graph: &KnowledgeGraph, -) -> String { - let mut apis = Vec::new(); - for c in reuse.candidates.iter().take(5) { - if let Some(cap) = graph.capability_by_id( - c.id.strip_prefix("capability:") - .unwrap_or(&c.id), - ) { - for sid in &cap.implemented_by { - if let Some(s) = graph.symbol_by_id(sid) { - apis.push(format!("{} ({})", s.name, s.resource)); - } - } - } else if c.kind == "Function" { - apis.push(format!( - "{} ({})", - c.title, - c.resource.as_deref().unwrap_or("?") - )); - } - } - apis.sort(); - apis.dedup(); - - let mut forbidden = Vec::new(); - for f in &reuse.failures { - forbidden.push(format!("Do not repeat: {f}")); - } - for c in graph.knowledge.iter().filter(|k| { - matches!( - k.kind, - crate::knowledge::ir::KnowledgeKind::AntiPattern - | crate::knowledge::ir::KnowledgeKind::Constraint - ) - }) { - if reuse.constraints.iter().any(|x| x.contains(&c.id)) - || reuse.failures.iter().any(|x| x.contains(&c.id)) - { - forbidden.push(c.title.clone()); - } - } - - format!( - r#"--- -type: Marqdo Context Pack -title: Engineering Context -task: {task_esc} -intent: {intent} -decision: {decision} -create_allowed: {create_allowed} -generated: - by: marqdo/knowledge ---- - -# Engineering Context - -## Task - -{task} - -## Existing Capabilities - -{existing} - -## Relevant APIs - -{apis} - -## Constraints - -{constraints} - -## Decisions - -{decisions} - -## Known Failures - -{failures} - -## Recommended Reuse - -{recommended} - -## Forbidden - -Do not implement: -{forbidden} -"#, - task_esc = task.replace('\n', " "), - intent = intent, - decision = reuse.decision.as_str(), - create_allowed = reuse.create_allowed, - task = task, - existing = bullet_list( - &reuse - .candidates - .iter() - .filter(|c| c.kind == "Capability" || c.kind == "Function") - .take(8) - .map(|c| format!("{} ({:.2})", c.title, c.score)) - .collect::>() - ), - apis = bullet_list(&apis), - constraints = bullet_list(&reuse.constraints), - decisions = bullet_list(&reuse.decisions), - failures = bullet_list(&reuse.failures), - recommended = numbered_list(&reuse.recommended), - forbidden = bullet_list(&forbidden), - ) -} - -fn bullet_list(items: &[String]) -> String { - if items.is_empty() { - "- _none_".into() - } else { - items.iter().map(|i| format!("- {i}")).collect::>().join("\n") - } -} - -fn numbered_list(items: &[String]) -> String { - if items.is_empty() { - "1. _none_".into() - } else { - items - .iter() - .enumerate() - .map(|(i, s)| format!("{}. {s}", i + 1)) - .collect::>() - .join("\n") - } -} - -pub fn preflight_json(p: &PreflightResult) -> Value { - json!({ - "status": p.status, - "intent": { "capability": p.intent_capability }, - "existing": p.existing, - "constraints": p.constraints, - "decisions": p.decisions, - "failures": p.failures, - "recommended": p.recommended, - "create_allowed": p.create_allowed, - "decision": p.decision, - "context_path": p.context_path, - }) -} - -pub fn format_preflight_yaml(p: &PreflightResult) -> String { - let mut out = String::new(); - out.push_str(&format!("status: {}\n\n", p.status)); - out.push_str("intent:\n"); - out.push_str(&format!(" capability: {}\n\n", p.intent_capability)); - out.push_str("existing:\n"); - for e in &p.existing { - out.push_str(&format!(" - {e}\n")); - } - if p.existing.is_empty() { - out.push_str(" []\n"); - } - out.push_str("\nconstraints:\n"); - for c in &p.constraints { - out.push_str(&format!(" - {c}\n")); - } - if p.constraints.is_empty() { - out.push_str(" []\n"); - } - out.push_str("\ndecisions:\n"); - for d in &p.decisions { - out.push_str(&format!(" - {d}\n")); - } - if p.decisions.is_empty() { - out.push_str(" []\n"); - } - out.push_str("\nfailures:\n"); - for f in &p.failures { - out.push_str(&format!(" - {f}\n")); - } - if p.failures.is_empty() { - out.push_str(" []\n"); - } - out.push_str("\nrecommended:\n"); - for r in &p.recommended { - out.push_str(&format!(" - {r}\n")); - } - if p.recommended.is_empty() { - out.push_str(" []\n"); - } - out.push_str(&format!("\ncreate_allowed: {}\n", p.create_allowed)); - if let Some(ref pth) = p.context_path { - out.push_str(&format!("context_pack: {pth}\n")); - } - out -} diff --git a/src/knowledge/projection.rs b/src/knowledge/projection.rs deleted file mode 100644 index 0ba5236..0000000 --- a/src/knowledge/projection.rs +++ /dev/null @@ -1,372 +0,0 @@ -//! Cross-module projection contracts for the *abstract* Lean Int model. -//! -//! This is a source-regenerated, kernel-replayed proof: the callee returns -//! exactly one of its own arguments and the caller forwards one static import. -//! No arithmetic, dynamic dispatch, effects, exceptions or runtime Number -//! equivalence is inferred. Unmodeled programs never get a certificate. -use std::{collections::BTreeSet,fs,path::Path,time::Duration}; -use anyhow::{Context,Result}; -use serde_json::{json,Value}; -use sha2::{Digest,Sha256}; -use crate::{ - ast::{CallExpr,Expr,Function,Stmt}, - prove::driver::{Toolchain,compile_import_module}, - sema::ir::{BoundCall,Compilation,SemanticArtifact} -}; - -const SCOPE:&str="number_contract_int_model_pure_forwarder_parameter_projection"; -const KIND:&str="marqdo_parameter_projection_composition"; -fn sha(bytes:&[u8])->String{format!("sha256:{:x}",Sha256::digest(bytes))} - -struct Prepared { - callee_source:String, - caller_source:String, - identity:String, - result_label:String, - parameter_index:usize, -} -fn lookup<'a>(functions:&'a [Function],segments:&[&str])->Option<&'a Function>{ - let (head,tail)=segments.split_first()?; - let mut candidates=functions.iter().filter(|f|f.name==*head); - let found=candidates.next()?; - if candidates.next().is_some(){return None} - if tail.is_empty(){Some(found)}else{lookup(&found.children,tail)} -} -pub(super) fn load_function(compiled:&Compilation,artifact:&SemanticArtifact)->Option{ - let text=fs::read_to_string(compiled.semantics.root.join(&artifact.source.file)).ok()?; - let parsed=crate::parse::parse_source(&text).ok()?; - lookup(&parsed.functions,&artifact.display_name.split('.').collect::>()).cloned() -} -fn unwrap_var(expr:&Expr)->Option<&str>{ - match expr{ - Expr::Var(v)=>Some(v.as_str()), - Expr::Occluded{payload:Some(inner),..}=>unwrap_var(inner), - _=>None - } -} -fn unwrap_call(expr:&Expr)->Option<&CallExpr>{ - match expr{ - Expr::Call(c)=>Some(c), - Expr::Occluded{payload:Some(inner),..}=>unwrap_call(inner), - _=>None - } -} -fn projection(fun:&Function)->Option<&str>{ - match fun.body.as_slice(){ - [Stmt::Return{value,..}]=>unwrap_var(value), - _=>None - } -} -pub(super) fn forwarder(fun:&Function)->Option<&CallExpr>{ - match fun.body.as_slice(){ - [Stmt::Return{value,..}]=>unwrap_call(value), - [Stmt::Assign{name,value,..},Stmt::Return{value:Expr::Var(result),..}] - if name==result=>unwrap_call(value), - _=>None - } -} -fn exact_unconditional_claim(compiled:&Compilation,artifact:&SemanticArtifact, - expected:&str)->bool{ - artifact.symbol_id.as_ref().is_some_and(|owner| - compiled.semantics.claims.iter().filter(|c| - c.owner==*owner && - c.premise.as_deref().map_or(true,|p|p.trim().is_empty()) && - c.conclusion.trim()==expected - ).count()==1) -} -fn candidate(compiled:&Compilation,call:&BoundCall)->Option{ - let sem=&compiled.semantics; - let mut caller_artifacts=sem.artifacts.iter().filter(|a| - a.kind=="function"&&a.symbol_id.as_ref()==Some(&call.caller)); - let ca=caller_artifacts.next()?; - if caller_artifacts.next().is_some(){return None} - let mut callee_artifacts=sem.artifacts.iter().filter(|a| - a.kind=="function"&&a.symbol_id.as_ref()==Some(&call.target)); - let ce=callee_artifacts.next()?; - if callee_artifacts.next().is_some(){return None} - if ca.source.file==ce.source.file||call.caller==call.target|| - !ca.effects.is_pure()||!ce.effects.is_pure()|| - !call.required_effects.is_pure()|| - call.control_blocker.is_some()||!call.path_guards.is_empty(){ - return None - } - let caller=load_function(compiled,ca)?; - let callee=load_function(compiled,ce)?; - if caller.is_object()||callee.is_object(){return None} - let return_parameter=projection(&callee)?; - let forwarded=forwarder(&caller)?.for_evaluation().ok()?; - if forwarded.path.is_none()||forwarded.receiver.is_some()|| - crate::sema::bind::call_display(&forwarded)!=call.call_site || - sem.bound_calls.iter().filter(|c|c.caller==call.caller).count()!=1{ - return None - } - let cs=ca.signature.as_ref()?; - let es=ce.signature.as_ref()?; - if cs.params.len()!=caller.params.len()|| - es.params.len()!=callee.params.len()|| - es.params.len()!=call.args.len()|| - forwarded.args.len()!=call.args.len(){return None} - // Canonical "number" includes non-integer variants at runtime. - // Our result is exclusively about the mathematical Int abstraction. - if cs.params.iter().chain(es.params.iter()) - .any(|p|!p.ty.eq_ignore_ascii_case("number")||!p.required|| - p.default_digest.is_some()){return None} - if !cs.params.iter().zip(caller.params.iter()) - .all(|(a,b)|a.name==b.name) || - !es.params.iter().zip(callee.params.iter()) - .all(|(a,b)|a.name==b.name){return None} - let k=es.params.iter().position(|p|p.name==return_parameter)?; - if es.params.iter().filter(|p|p.name==return_parameter).count()!=1{ - return None - } - if !exact_unconditional_claim(compiled,ce, - &format!("结果 = {return_parameter}")){return None} - let mut args=Vec::new(); - let mut caller_result=None; - for (i,(formal,arg)) in es.params.iter().zip(call.args.iter()).enumerate(){ - if arg.name.as_ref().is_some_and(|name|name!=&formal.name){return None} - let (term,label)=if let Some(value)=arg.integer{ - (format!("({value} : Int)"),value.to_string()) - }else{ - let symbol=arg.symbol.as_ref()?; - let index=cs.params.iter().position(|p|p.name==*symbol)?; - if cs.params.iter().filter(|p|p.name==*symbol).count()!=1{return None} - (format!("v{index}"),symbol.clone()) - }; - args.push(term); - if i==k{caller_result=Some(label)} - } - let result_label=caller_result?; - if !exact_unconditional_claim(compiled,ca, - &format!("结果 = {result_label}")){return None} - let callee_binders=(0..es.params.len()) - .map(|i|format!("(v{i} : Int)")).collect::>().join(" "); - let caller_binders=(0..cs.params.len()) - .map(|i|format!("(v{i} : Int)")).collect::>().join(" "); - let callee_vars=(0..es.params.len()) - .map(|i|format!("v{i}")).collect::>().join(" "); - let caller_vars=(0..cs.params.len()) - .map(|i|format!("v{i}")).collect::>().join(" "); - let call_terms=args.join(" "); - let projected_term=&args[k]; - // No author-controlled identifiers appear in generated Lean code. - let callee_source=format!( - "def callee {callee_binders} : Int := v{k}\n\ - theorem callee_contract {callee_binders} : callee {callee_vars} = v{k} := by rfl\n"); - let caller_source=format!( - "import CalleeModule\n\ - def caller {caller_binders} : Int := callee {call_terms}\n\ - theorem caller_contract {caller_binders} : caller {caller_vars} = {projected_term} := by\n\ - \x20\x20simpa [caller] using (callee_contract {call_terms})\n"); - Some(Prepared{ - callee_source,caller_source, - identity:format!("{}#{}",ca.artifact_id.0,ce.artifact_id.0), - result_label,parameter_index:k - }) -} -pub(super) fn eligible(compiled:&Compilation,call:&BoundCall)->bool{ - candidate(compiled,call).is_some() -} -pub(super) fn closures(compiled:&Compilation,call:&BoundCall)->Result>{ - let set=compiled.semantics.artifacts.iter() - .filter(|a|a.symbol_id.as_ref()==Some(&call.caller)|| - a.symbol_id.as_ref()==Some(&call.target)) - .map(|a|(a.artifact_id.0.clone(),a.hashes.closure.0.clone())) - .collect::>(); - anyhow::ensure!(set.len()==2,"proof.projection_ambiguous_dependency"); - Ok(set) -} -pub(super) fn prove(compiled:&Compilation,out:&Path,lean:&Toolchain)->Result>{ - let mut rows=Vec::new(); - for call in &compiled.semantics.bound_calls{ - if super::unified::covers(compiled,&call.caller){continue} - let Some(plan)=candidate(compiled,call) else{continue}; - let dependencies=closures(compiled,call)?; - let key=sha(format!("{}|{:?}|{}",plan.identity,dependencies,lean.version).as_bytes()); - let dir=out.join("composed").join(format!("projection-{}",&key[7..23])); - fs::create_dir_all(&dir)?; - let callee=dir.join("CalleeModule.lean"); - let caller=dir.join("CallerModule.lean"); - let callee_obj=dir.join("CalleeModule.olean"); - let caller_obj=dir.join("CallerModule.olean"); - fs::write(&callee,&plan.callee_source)?; - fs::write(&caller,&plan.caller_source)?; - let checked=(||->Result<()>{ - compile_import_module(lean,&callee,&callee_obj,&dir, - Duration::from_secs(120)).context("projection callee")?; - compile_import_module(lean,&caller,&caller_obj,&dir, - Duration::from_secs(120)).context("projection caller")?; - Ok(()) - })(); - if let Err(e)=checked{ - let _=fs::remove_file(dir.join("composition-certificate.json")); - rows.push(json!({"identity":plan.identity,"status":"lean_rejected", - "scope":SCOPE,"error":format!("{e:#}")})); - continue - } - let cert=json!({ - "schema_version":1,"kind":KIND,"scope":SCOPE, - "status":"lean_kernel_proved_model", - "identity":plan.identity, - "caller":call.caller.as_str(),"callee":call.target.as_str(), - "result_label":plan.result_label, - "parameter_index":plan.parameter_index, - "callee_source_sha256":sha(plan.callee_source.as_bytes()), - "caller_source_sha256":sha(plan.caller_source.as_bytes()), - "callee_compiled_sha256":sha(&fs::read(&callee_obj)?), - "caller_compiled_sha256":sha(&fs::read(&caller_obj)?), - "toolchain":lean.version, - "source_closures":dependencies.iter().map(|(id,closure)| - json!({"id":id,"closure":closure})).collect::>(), - "runtime_domain_verified":false, - "independent_replay":"CalleeModule.lean then CallerModule.lean" - }); - let receipt=dir.join("composition-certificate.json"); - fs::write(&receipt,serde_json::to_vec_pretty(&cert)?)?; - rows.push(json!({"identity":plan.identity,"status":"lean_kernel_proved_model", - "artifact":receipt,"scope":SCOPE})); - } - Ok(rows) -} -pub(super) fn replay(compiled:&Compilation,certificate:&Path,lean:&Toolchain) - ->Result{ - let cert:Value=serde_json::from_slice(&fs::read(certificate)?)?; - anyhow::ensure!(cert["schema_version"]==1&&cert["kind"]==KIND&& - cert["scope"]==SCOPE&&cert["status"]=="lean_kernel_proved_model", - "proof.projection_invalid_certificate"); - anyhow::ensure!(cert["toolchain"]==lean.version, - "proof.projection_stale_toolchain"); - let identity=cert["identity"].as_str().context("missing identity")?; - let matches=compiled.semantics.bound_calls.iter().filter_map(|call| - candidate(compiled,call).and_then(|p| - (p.identity==identity).then_some((call,p)))).collect::>(); - anyhow::ensure!(matches.len()==1, - "proof.projection_ambiguous_or_stale_source"); - let (call,plan)=&matches[0]; - anyhow::ensure!(cert["caller"]==call.caller.as_str()&& - cert["callee"]==call.target.as_str()&& - cert["parameter_index"]==plan.parameter_index&& - cert["result_label"]==plan.result_label, - "proof.projection_changed_proof_subject"); - let expected=closures(compiled,call)?; - let rows=cert["source_closures"].as_array() - .context("proof.projection_missing_closures")?; - let actual=rows.iter().map(|r|Ok(( - r["id"].as_str().context("proof.projection_bad_id")?.to_string(), - r["closure"].as_str().context("proof.projection_bad_closure")?.to_string() - ))).collect::>>()?; - anyhow::ensure!(rows.len()==expected.len()&&actual==expected, - "proof.projection_stale_or_ambiguous_closure"); - let dir=certificate.parent().context("missing certificate parent")?; - let callee=dir.join("CalleeModule.lean"); - let caller=dir.join("CallerModule.lean"); - anyhow::ensure!(fs::read_to_string(&callee)?==plan.callee_source&& - fs::read_to_string(&caller)?==plan.caller_source&& - cert["callee_source_sha256"]==sha(plan.callee_source.as_bytes())&& - cert["caller_source_sha256"]==sha(plan.caller_source.as_bytes()), - "proof.projection_generated_source_mismatch"); - let callee_obj=dir.join("CalleeModule.olean"); - let caller_obj=dir.join("CallerModule.olean"); - compile_import_module(lean,&callee,&callee_obj,dir, - Duration::from_secs(120))?; - compile_import_module(lean,&caller,&caller_obj,dir, - Duration::from_secs(120))?; - anyhow::ensure!(cert["callee_compiled_sha256"]==sha(&fs::read(callee_obj)?)&& - cert["caller_compiled_sha256"]==sha(&fs::read(caller_obj)?), - "proof.projection_replay_output_changed"); - Ok(json!({"schema_version":1,"kind":"independent_composition_replay", - "status":"lean_kernel_replayed","scope":SCOPE,"identity":identity, - "current_source_verified":true, - "full_marqdo_runtime_semantics_proved":false})) -} - - -#[cfg(test)] -mod tests{ - use super::*; - #[test] - fn symbolic_projection_uses_only_the_selected_actual(){ - let root=std::env::temp_dir().join(format!( - "marqdo-projection-unit-{}",std::process::id())); - let _=fs::remove_dir_all(&root); - fs::create_dir_all(&root).unwrap(); - let callee=r#"--- -markup: occlusion ---- -# math -## select -+ `first` -+ `second` - -| 参数 | 类型 | 说明 | -|---|---|---| -| first | int | integer | -| second | int | integer | - -| 定理 | 结论 | 策略 | -|---|---|---| -| proj | 结果 = second | auto | - -*`second`* -"#; - let caller=r#"--- -markup: occlusion -import: - math: math.mq.md ---- -# main -## use -+ `x` -+ `y` - -| 参数 | 类型 | 说明 | -|---|---|---| -| x | int | integer | -| y | int | integer | - -| 定理 | 结论 | 策略 | -|---|---|---| -| forwarded | 结果 = x | auto | - -**v = [选择](math.math.select(`y`, `x`))** -*v* -"#; - fs::write(root.join("math.mq.md"),callee).unwrap(); - fs::write(root.join("main.mq.md"),caller).unwrap(); - let project=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let call=project.semantics.bound_calls.iter().find(|c| - c.call_site=="math.math.select").expect("static call"); - let proof=candidate(&project,call).expect("symbolic projection"); - assert_eq!(proof.parameter_index,1); - assert_eq!(proof.result_label,"x"); - assert!(proof.callee_source.contains(":= v1")); - assert!(proof.caller_source.contains("callee v1 v0")); - assert!(proof.caller_source.contains("= v0")); - assert!(!proof.caller_source.contains("sorry")); - - // Reordering the actuals without changing the asserted result must - // invalidate the caller contract; source is the authority. - let incorrect=caller.replace( - "math.math.select(`y`, `x`)", - "math.math.select(`x`, `y`)"); - fs::write(root.join("main.mq.md"),incorrect).unwrap(); - let changed=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let call=changed.semantics.bound_calls.iter().find(|c| - c.call_site=="math.math.select").unwrap(); - assert!(candidate(&changed,call).is_none()); - - // A declaration with an unsatisfied precondition is NOT a proof. - fs::write(root.join("main.mq.md"),caller).unwrap(); - fs::write(root.join("math.mq.md"), - callee.replace("| proj | 结果 = second | auto |", - "| proj | 结果 = second | auto |\n| other | 结果 = second | auto |")).unwrap(); - let ambiguous=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let call=ambiguous.semantics.bound_calls.iter().find(|c| - c.call_site=="math.math.select").unwrap(); - assert!(candidate(&ambiguous,call).is_none()); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/knowledge/proof.rs b/src/knowledge/proof.rs deleted file mode 100644 index 51a4bb6..0000000 --- a/src/knowledge/proof.rs +++ /dev/null @@ -1,336 +0,0 @@ -//! Bind a proved function claim to one semantic symbol, never to every -//! marked step. Unmatched identities and stale evidence fail closed. - -use std::{collections::BTreeMap, fs, path::Path}; -use anyhow::{Context, Result}; -use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; -use crate::{prove::{Report, Verdict}, sema::ir::{Compilation, SemanticArtifact, SemanticProject}}; - -fn sha(bytes: &[u8]) -> String { - format!("sha256:{:x}", Sha256::digest(bytes)) -} -fn generated_module_valid(folder:&Path,expected:&Value)->bool { - let source_dir=folder.join("Generated"); - let Ok(files)=fs::read_dir(&source_dir) else {return false}; - let mut candidates=files.flatten().filter(|f| - f.path().extension().is_some_and(|ext|ext=="lean")).collect::>(); - if candidates.len()!=1{return false} - let Some(generated)=candidates.pop() else{return false}; - let Ok(source)=fs::read(generated.path()) else{return false}; - sha(&source).trim_start_matches("sha256:")==expected.as_str().unwrap_or("") -} -/// Never accept a mutable cached Lean source as proof authority. Rebuild the -/// expected module and plan from the current Marqdo source with the same -/// compiler pipeline used by prove_path; a forged axiom/sorry in the cached -/// Lean file will not match the deterministic generated source. -fn cached_translation_matches_current( - folder:&Path, entry:&Value,semantic:&SemanticProject -)->bool { - let Some(rel)=entry["source_file"].as_str() else{return false}; - let Some(display)=entry["proof_module_display"].as_str() else{return false}; - let abs=semantic.root.join(rel); - let Ok(module)=crate::load::load_module(&abs) else{return false}; - let Some(source_sha)=module.source.sha256.as_deref() else{return false}; - if entry["source_sha256"]!=source_sha{return false} - let effects=crate::prove::lower::effect_map(&abs); - let Ok((plan,_))=crate::prove::lower::build_plan( - &module,source_sha,display,effects,&[]) else{return false}; - if fs::read(folder.join("plan.json")).ok().as_deref() - !=Some(plan.to_stable_json().as_bytes()) { - return false; - } - let (generated_name,expected)=crate::prove::emit::emit_module( - &plan,&crate::prove::emit::stem_of(display)); - let generated=folder.join("Generated").join(generated_name); - if fs::read(generated).ok().as_deref()!=Some(expected.as_bytes()) { - return false; - } - sha(expected.as_bytes()).trim_start_matches("sha256:") - ==entry["module_sha256"].as_str().unwrap_or("") -} - -fn certificate_identity_valid(folder:&Path,cert:&Value)->bool { - let Ok(plan)=fs::read(folder.join("plan.json")) else {return false}; - let source=cert["source_sha256"].as_str().unwrap_or(""); - let library=cert["library_sha256"].as_str().unwrap_or(""); - let toolchain=cert["toolchain"].as_str().unwrap_or(""); - let actual_library=crate::prove::cache::sha256_hex( - crate::prove::driver::LIBRARY_SRC.as_bytes()); - let expected_key=crate::prove::cache::cache_key( - source,&crate::prove::cache::sha256_hex(&plan), - library,toolchain,env!("CARGO_PKG_VERSION")); - library==actual_library - && cert["marqdo"]==env!("CARGO_PKG_VERSION") - && cert["key"]==expected_key - && generated_module_valid(folder,&cert["module_sha256"]) -} - -fn certificate(dir: &Path, report: &Report) -> Option<(Value, String)> { - let bytes = fs::read(dir.join("certificate.json")).ok()?; - let cert: Value = serde_json::from_slice(&bytes).ok()?; - let lean = report.lean.as_ref()?; - if cert["schema"] != 1 || cert["source_sha256"] != report.source_sha256 - || cert["tier"] != "lean" || cert["library_sha256"] != lean.library_sha256 - || cert["toolchain"] != lean.toolchain || cert["module_sha256"] != lean.module_sha256 { - return None; - } - Some((cert, sha(&bytes))) -} - -fn matching<'a>(compiled: &'a Compilation, path: &Path, name: &str) - -> Option<&'a SemanticArtifact> { - let file=path.canonicalize().ok()?; - let mut all=compiled.semantics.artifacts.iter() - .filter(|a|a.kind=="function" && a.display_name==name) - .filter(|a|compiled.semantics.root.join(&a.source.file) - .canonicalize().ok().as_deref()==Some(file.as_path())); - let first=all.next()?; - all.next().is_none().then_some(first) -} - -/// Exact owner binding; related step anchors are navigation only, not proved. -pub fn link_report(compiled: &Compilation, file: &Path, report: &Report, dir: &Path) -> Value { - let cert=certificate(dir,report); - let mut claims=Vec::new(); - let mut unresolved=Vec::new(); - for f in &report.functions { - let Some(owner)=matching(compiled,file,&f.name) else { - unresolved.push(json!({"function":f.name,"reason":"unbound_or_ambiguous"})); - continue; - }; - let Some(symbol)=owner.symbol_id.as_ref() else { - unresolved.push(json!({"function":f.name,"reason":"missing_symbol_id"})); - continue; - }; - let steps:Vec<&str>=compiled.semantics.steps.iter() - .filter(|s|s.id.0.starts_with(&format!("{}#step-",symbol.as_str()))) - .filter_map(|s|s.anchor_id.as_deref()).collect(); - for claim in &f.claims { - // A proof receipt must be bound to the exact theorem declaration - // present in the same AST, not merely to a similarly named function. - let mut matching_claims=compiled.semantics.claims.iter().filter(|decl| - decl.owner==*symbol && decl.label==claim.id - && decl.conclusion==claim.conclusion - && decl.premise==claim.premise); - let Some(declared)=matching_claims.next() else { - unresolved.push(json!({"function":f.name,"claim":claim.id, - "reason":"theorem_declaration_missing_or_changed"})); - continue; - }; - if matching_claims.next().is_some() { - unresolved.push(json!({"function":f.name,"claim":claim.id, - "reason":"ambiguous_theorem_declaration"})); - continue; - } - let cert_ok=cert.as_ref().is_some_and(|(v,_)| - v["claims"].as_array().is_some_and(|records| - records.iter().any(|r| - r["id"]==claim.id && r["function"]==f.name - && r["status"]=="proved"))); - let proved=claim.status==Verdict::Proved && claim.decided_by=="lean" && cert_ok; - let status=if claim.status==Verdict::Proved && !proved { - "unverified" - } else { claim.status.as_str() }; - claims.push(json!({ - "claim_anchor_id":declared.anchor_id, - "owner_symbol_id":symbol.as_str(), - "function":f.name,"claim_id":claim.id, - "premise":claim.premise,"conclusion":claim.conclusion, - "source_line":claim.source_line, - "status":status, - "decided_by":if proved {"lean"} else if status=="checked" {"offline"} else {"none"}, - "certificate_digest":if proved {cert.as_ref().map(|(_,h)|h.as_str())} else {None}, - "proof_scope":"function", - "evidence":super::evidence::for_receipt( - status,proved,false), - "related_anchor_ids":steps, - "related_anchor_relation":"defined_in_same_function_not_individually_proved", - "semantic_hashes":{"interface":owner.hashes.interface.0, - "implementation":owner.hashes.implementation.0, - "closure":owner.hashes.closure.0}, - "source_file":owner.source.file, - "source_sha256":report.source_sha256, - "library_sha256":report.lean.as_ref().map(|l|l.library_sha256.as_str()), - "toolchain":report.lean.as_ref().map(|l|l.toolchain.as_str()), - "module_sha256":report.lean.as_ref().map(|l|l.module_sha256.as_str()), - "proof_module_display":report.file - })); - } - } - claims.sort_by(|a,b|a["claim_anchor_id"].as_str().cmp(&b["claim_anchor_id"].as_str())); - let assumptions:Vec=compiled.semantics.assumptions.iter() - .filter(|a|compiled.semantics.root.join(&a.source.file) - .canonicalize().ok().as_deref()==file.canonicalize().ok().as_deref()) - .map(|a|json!({"id":a.id,"owner":a.owner.as_str(), - "operation":a.operation,"premise":a.premise, - "postcondition":a.postcondition, - "status":"declared_not_disclosed_as_proved"})) - .collect(); - json!({"schema_version":1,"kind":"knowledge_proof_linkage", - "source_sha256":report.source_sha256,"file":report.file, - "claims":claims,"assumptions":assumptions,"unresolved":unresolved}) -} - -pub fn emit_links(file: &Path, report: &Report, dir: &Path) -> Result<()> { - let result=match crate::sema::ir::compile_file_closure(file) { - Ok(compiled)=>link_report(&compiled,file,report,dir), - Err(err)=>json!({"schema_version":1,"kind":"knowledge_proof_linkage", - "status":"unbound","source_sha256":report.source_sha256,"claims":[], - "unresolved":[{"reason":"semantic_compile_failed","detail":format!("{err:#}")}]}), - }; - let path=dir.join("knowledge-links.json"); - fs::write(&path,serde_json::to_vec_pretty(&result)?) - .with_context(||format!("write {}",path.display())) -} - -/// Invalidate proof links against both semantic owner hashes and source bytes. -/// Certificate integrity is rechecked; duplicate claim identities are refused. -pub fn index_links(prove_dir:&Path, semantic:&SemanticProject)->Value { - let owners:BTreeMap<_,_>=semantic.artifacts.iter() - .filter_map(|a|a.symbol_id.as_ref().map(|id|(id.as_str().to_string(),a))) - .collect(); - let mut entries=Vec::new(); - if let Ok(folders)=fs::read_dir(prove_dir) { - for folder in folders.flatten().filter(|f|f.path().is_dir()) { - let Ok(bytes)=fs::read(folder.path().join("knowledge-links.json")) else {continue}; - let Ok(link) = serde_json::from_slice::(&bytes) else {continue}; - let Some(claims)=link["claims"].as_array() else {continue}; - for claim in claims { - let mut entry=claim.clone(); - entry["receipt_artifact"]=json!(folder.file_name().to_string_lossy().to_string()); - let owner=claim["owner_symbol_id"].as_str().and_then(|id|owners.get(id)); - let theorem_present=claim["owner_symbol_id"].as_str().is_some_and(|id| - semantic.claims.iter().any(|c| - c.owner.as_str()==id - && claim["claim_anchor_id"]==c.anchor_id - && claim["claim_id"]==c.label - && claim["conclusion"]==c.conclusion - && claim["premise"]==json!(c.premise))); - let fresh=theorem_present && owner.is_some_and(|a| { - claim["source_file"]==a.source.file - && claim["semantic_hashes"]["interface"]==a.hashes.interface.0 - && claim["semantic_hashes"]["implementation"]==a.hashes.implementation.0 - && claim["semantic_hashes"]["closure"]==a.hashes.closure.0 - && fs::read(semantic.root.join(&a.source.file)).ok().is_some_and( - |raw|sha(&raw).trim_start_matches("sha256:")==claim["source_sha256"]) - }); - let certified=cached_translation_matches_current( - &folder.path(),&entry,semantic) - && entry["status"]=="proved" && entry["decided_by"]=="lean" - && entry["certificate_digest"].as_str().is_some_and(|digest| - fs::read(folder.path().join("certificate.json")).ok().is_some_and(|bytes| { - if sha(&bytes)!=digest { return false; } - let Ok(cert)=serde_json::from_slice::(&bytes) else { - return false - }; - cert["schema"]==1 && cert["tier"]=="lean" - && certificate_identity_valid(&folder.path(),&cert) - && cert["source_sha256"]==entry["source_sha256"] - && cert["library_sha256"]==entry["library_sha256"] - && cert["toolchain"]==entry["toolchain"] - && cert["module_sha256"]==entry["module_sha256"] - && cert["claims"].as_array().is_some_and(|records| - records.iter().any(|r| - r["id"]==entry["claim_id"] - && r["function"]==entry["function"] - && r["status"]=="proved")) - })); - if !fresh { - entry["status"]=json!("stale"); - entry["stale_reason"]=json!("source_or_semantic_dependency_changed"); - } else if entry["status"]=="proved" && !certified { - entry["status"]=json!("unverified"); - entry["stale_reason"]=json!("missing_or_changed_lean_certificate"); - } - entry["usable"]=json!(fresh && certified); - entries.push(entry); - } - } - } - entries.sort_by(|a,b|a["claim_anchor_id"].as_str().cmp(&b["claim_anchor_id"].as_str())); - let mut freq=BTreeMap::new(); - for e in &entries { - if let Some(id)=e["claim_anchor_id"].as_str() { - *freq.entry(id.to_string()).or_insert(0usize)+=1; - } - } - for e in &mut entries { - if e["claim_anchor_id"].as_str().and_then(|id|freq.get(id)) - .is_some_and(|n|*n>1) { - e["status"]=json!("ambiguous"); - e["stale_reason"]=json!("multiple_proof_link_records"); - e["usable"]=json!(false); - } - } - // Evidence is orthogonal to legacy `status`: a verified Lean receipt - // means model_proved, NOT unrestricted Marqdo runtime correctness. - for e in &mut entries { - e["evidence"]=super::evidence::for_receipt( - e["status"].as_str().unwrap_or("unknown"), - e["usable"]==true,e["kernel_replayed"]==true); - } - json!({"schema_version":1,"role":"proof_receipts_not_execution_authority", - "claims":entries}) -} - - -/// Recheck every locally cached *usable* Lean receipt with an actual Lean -/// invocation. Hash-only certificates are not trusted for --verify. An error -/// at one folder revokes all its receipts; no JSON proof flag can override it. -pub fn replay_index( - prove_dir:&Path, index:&mut Value, - toolchain:&crate::prove::driver::Toolchain, - timeout:std::time::Duration -)->Result<()> { - let (libdir,_)=crate::prove::driver::ensure_library(prove_dir,toolchain)?; - let mut replayed:BTreeMap>=BTreeMap::new(); - let mut rejected:std::collections::BTreeSet=std::collections::BTreeSet::new(); - let Some(entries)=index["claims"].as_array_mut() else {return Ok(())}; - let artifacts:std::collections::BTreeSet<_>=entries.iter() - .filter(|e|e["usable"]==true) - .filter_map(|e|e["receipt_artifact"].as_str().map(str::to_owned)) - .collect(); - for id in artifacts { - if id=="." || id==".." || id.contains('/') || id.contains('\\'){ - rejected.insert(id); - continue; - } - let src_dir=prove_dir.join(&id).join("Generated"); - let files=fs::read_dir(&src_dir).ok().into_iter() - .flat_map(|items|items.flatten()) - .filter(|f|f.path().extension().is_some_and(|ext|ext=="lean")) - .map(|f|f.path()).collect::>(); - if files.len()!=1 {rejected.insert(id);continue;} - let path=&files[0]; - let Ok(source)=fs::read_to_string(path) else {rejected.insert(id);continue}; - let Ok(outcome)=crate::prove::driver::check_module( - toolchain,&libdir,path,&source,timeout,None) else { - rejected.insert(id);continue; - }; - if outcome.status!=Verdict::Proved || - fs::read_to_string(path).ok().as_deref()!=Some(source.as_str()) { - rejected.insert(id);continue; - } - replayed.insert(id,outcome.claims.into_iter() - .filter(|c|c.status==Verdict::Proved) - .map(|c|(c.function,c.claim)).collect()); - } - for entry in entries { - if entry["usable"]!=true {continue;} - let id=entry["receipt_artifact"].as_str().unwrap_or(""); - let found=replayed.get(id).is_some_and(|claims|claims.iter().any(|(fun,claim)| - entry["function"]==fun.as_str() && entry["claim_id"]==claim.as_str())); - if !found || rejected.contains(id) { - entry["usable"]=json!(false); - entry["status"]=json!("unverified"); - entry["stale_reason"]=json!("lean_kernel_replay_failed"); - } else { - entry["kernel_replayed"]=json!(true); - } - entry["evidence"]=super::evidence::for_receipt( - entry["status"].as_str().unwrap_or("unknown"), - entry["usable"]==true,entry["kernel_replayed"]==true); - } - Ok(()) -} diff --git a/src/knowledge/reuse.rs b/src/knowledge/reuse.rs deleted file mode 100755 index 4922855..0000000 --- a/src/knowledge/reuse.rs +++ /dev/null @@ -1,321 +0,0 @@ -//! Reuse protocol: REUSE → ADAPT → CREATE with reuse budget. - -use serde_json::{json, Value}; - -use crate::knowledge::find::{find, FindHit}; -use crate::knowledge::ir::{ - KnowledgeGraph, KnowledgeKind, ReuseCandidate, ReuseDecision, ReuseResult, -}; - -#[derive(Debug, Clone)] -pub struct ReuseBudget { - pub min_candidates: usize, - pub require_preflight: bool, - pub require_reason: bool, - pub allow_create_after: usize, - pub reuse_threshold: f64, - pub adapt_threshold: f64, -} - -impl Default for ReuseBudget { - fn default() -> Self { - Self { - min_candidates: 3, - require_preflight: true, - require_reason: true, - allow_create_after: 2, - reuse_threshold: 0.72, - adapt_threshold: 0.45, - } - } -} - -pub fn resolve(graph: &KnowledgeGraph, task: &str, budget: &ReuseBudget) -> ReuseResult { - let hits = find(graph, task, 20); - let mut candidates: Vec = hits - .iter() - .filter(|h| h.kind == "Capability" || h.kind == "Function") - .map(|h| ReuseCandidate { - id: h.id.clone(), - kind: h.kind.clone(), - title: h.title.clone(), - score: h.score, - resource: h.resource.clone(), - reason: reason_for(h, task), - }) - .collect(); - - // Ensure min_candidates from broader search if needed - if candidates.len() < budget.min_candidates { - for h in &hits { - if candidates.iter().any(|c| c.id == h.id) { - continue; - } - candidates.push(ReuseCandidate { - id: h.id.clone(), - kind: h.kind.clone(), - title: h.title.clone(), - score: h.score, - resource: h.resource.clone(), - reason: reason_for(h, task), - }); - if candidates.len() >= budget.min_candidates { - break; - } - } - } - - let constraints: Vec = graph - .knowledge - .iter() - .filter(|k| k.kind == KnowledgeKind::Constraint) - .filter(|k| relevant_knowledge(k.title.as_str(), &k.body_summary, task, &hits)) - .map(|k| format!("{} ({})", k.title, k.id)) - .collect(); - - let decisions: Vec = graph - .knowledge - .iter() - .filter(|k| k.kind == KnowledgeKind::Decision) - .filter(|k| relevant_knowledge(k.title.as_str(), &k.body_summary, task, &hits)) - .map(|k| format!("{} ({})", k.title, k.id)) - .collect(); - - let failures: Vec = graph - .knowledge - .iter() - .filter(|k| { - matches!( - k.kind, - KnowledgeKind::Failure | KnowledgeKind::AntiPattern - ) - }) - .filter(|k| relevant_knowledge(k.title.as_str(), &k.body_summary, task, &hits)) - .map(|k| format!("{} ({})", k.title, k.id)) - .collect(); - - let best = candidates.first().cloned(); - let best_score = best.as_ref().map(|c| c.score).unwrap_or(0.0); - let analyzed = candidates.len().min(budget.allow_create_after.max(budget.min_candidates)); - - let (decision, create_allowed, reason, recommended) = if best_score >= budget.reuse_threshold { - let b = best.as_ref().unwrap(); - let mut reasons = b.reason.clone(); - reasons.push("score meets REUSE threshold".into()); - if !constraints.is_empty() { - reasons.push("active constraints favor existing capability".into()); - } - ( - ReuseDecision::Reuse, - false, - reasons, - vec![format!("REUSE {}", b.title)], - ) - } else if best_score >= budget.adapt_threshold { - let b = best.as_ref().unwrap(); - let mut reasons = b.reason.clone(); - reasons.push("near match — wrap/compose/extend rather than copy".into()); - ( - ReuseDecision::Adapt, - false, - reasons, - vec![format!("ADAPT {}", b.title)], - ) - } else if analyzed >= budget.allow_create_after { - let mut reasons = vec![ - "no existing capability satisfies constraints".into(), - format!("analyzed {analyzed} candidates below adapt threshold"), - ]; - if budget.require_reason { - reasons.push("CREATE allowed only after reuse budget exhausted".into()); - } - (ReuseDecision::Create, true, reasons, vec!["CREATE new capability".into()]) - } else { - ( - ReuseDecision::Create, - false, - vec![ - format!( - "insufficient candidates analyzed ({analyzed} < {})", - budget.allow_create_after - ), - "continue discovery before CREATE".into(), - ], - vec![], - ) - }; - - let capability = best.as_ref().and_then(|c| { - if c.kind == "Capability" { - Some(c.title.clone()) - } else { - c.id.strip_prefix("capability:").map(|s| s.to_string()) - } - }); - let symbol = best.as_ref().and_then(|c| { - if c.kind == "Function" { - Some(c.title.clone()) - } else if let Some(cap) = capability.as_ref() { - graph - .capability_by_id(cap) - .and_then(|cap| cap.implemented_by.first().cloned()) - } else { - None - } - }); - let source = best.as_ref().and_then(|c| c.resource.clone()); - - ReuseResult { - decision, - confidence: best_score, - capability, - symbol, - source, - reason, - candidates, - constraints, - decisions, - failures, - create_allowed, - recommended, - } -} - -fn reason_for(h: &FindHit, task: &str) -> Vec { - let mut r = Vec::new(); - r.push(format!("matched query tokens against {}", h.kind)); - if h.score >= 0.7 { - r.push("same input/output semantics likely".into()); - } - if task.to_ascii_lowercase().split_whitespace().any(|t| { - h.title.to_ascii_lowercase().contains(t) && t.len() > 2 - }) { - r.push("title overlaps task terms".into()); - } - r -} - -fn relevant_knowledge(title: &str, body: &str, task: &str, hits: &[FindHit]) -> bool { - let material = format!("{title} {body}").to_ascii_lowercase(); - let task_l = task.to_ascii_lowercase(); - if task_l.split_whitespace().any(|t| t.len() > 3 && material.contains(t)) { - return true; - } - hits.iter().take(5).any(|h| { - material.contains(&h.title.to_ascii_lowercase()) - || h.snippet - .to_ascii_lowercase() - .split_whitespace() - .any(|t| t.len() > 4 && material.contains(t)) - }) -} - -pub fn format_reuse_text(task: &str, result: &ReuseResult) -> String { - let mut out = String::from("Engineering First Information\n\n"); - out.push_str(&format!("Task: {task}\n\n")); - out.push_str("Existing capabilities:\n"); - let caps: Vec<_> = result - .candidates - .iter() - .filter(|c| c.kind == "Capability" || c.kind == "Function") - .collect(); - if caps.is_empty() { - out.push_str(" (none)\n"); - } else { - for c in caps.iter().take(8) { - out.push_str(&format!(" {:<28} {:.2}\n", c.title, c.score)); - } - } - out.push('\n'); - if !result.constraints.is_empty() { - out.push_str("Relevant constraints:\n"); - for c in &result.constraints { - out.push_str(&format!(" {c}\n")); - } - out.push('\n'); - } - if !result.decisions.is_empty() { - out.push_str("Relevant decisions:\n"); - for d in &result.decisions { - out.push_str(&format!(" {d}\n")); - } - out.push('\n'); - } - if !result.failures.is_empty() { - out.push_str("Known failures:\n"); - for f in &result.failures { - out.push_str(&format!(" {f}\n")); - } - out.push('\n'); - } - out.push_str("Recommended:\n"); - if result.recommended.is_empty() { - out.push_str(&format!(" {}\n", result.decision.as_str())); - } else { - for r in &result.recommended { - out.push_str(&format!(" {r}\n")); - } - } - out.push('\n'); - out.push_str("New implementation:\n"); - if result.create_allowed { - out.push_str(" ALLOWED (CREATE)\n"); - } else if result.decision == ReuseDecision::Create { - out.push_str(" NOT YET — exhaust reuse budget first\n"); - } else { - out.push_str(" NOT REQUIRED\n"); - } - out.push('\n'); - out.push_str("Reason:\n"); - for r in &result.reason { - out.push_str(&format!(" - {r}\n")); - } - out -} - -pub fn reuse_json(task: &str, result: &ReuseResult) -> Value { - let bind_required = matches!( - result.decision, - ReuseDecision::Reuse | ReuseDecision::Adapt - ); - let mut bind_targets = Vec::new(); - if let Some(sym) = &result.symbol { - bind_targets.push(json!({ - "query": sym, - "via": "reuse.symbol", - "note": "pass query to artifact.bind then artifact.execute", - })); - } - if let Some(src) = &result.source { - bind_targets.push(json!({ - "query": src, - "via": "reuse.source", - "note": "pass query to artifact.bind then artifact.execute", - })); - } - json!({ - "task": task, - "decision": result.decision.as_str(), - "confidence": result.confidence, - "capability": result.capability, - "symbol": result.symbol, - "source": result.source, - "reason": result.reason, - "create_allowed": result.create_allowed, - "recommended": result.recommended, - "constraints": result.constraints, - "decisions": result.decisions, - "failures": result.failures, - "discovery_only": true, - "bind_required": bind_required, - "bind_targets": bind_targets, - "candidates": result.candidates.iter().map(|c| json!({ - "id": c.id, - "kind": c.kind, - "title": c.title, - "score": c.score, - "resource": c.resource, - "reason": c.reason, - })).collect::>(), - }) -} diff --git a/src/knowledge/symbolic.rs b/src/knowledge/symbolic.rs deleted file mode 100644 index 8eba53d..0000000 --- a/src/knowledge/symbolic.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Symbolic branch VCs for a deliberately restricted, pure integer fragment. -//! A proved proposition in the Int abstraction is NOT by itself a proof of -//! Marqdo runtime semantics (i64, dynamic values and exceptions). -use std::collections::BTreeMap; -use crate::prove::proof_check::{self,ClaimAst as A,CTok as T}; -use crate::sema::ir::{BoundCall,SemanticProject}; - -#[derive(Debug,Clone)] -pub struct SymbolicGoal{ - pub proposition:String, - pub guard_propositions:Vec, - pub guard_index:Option, - pub binders:Vec, - pub runtime_domain_verified:bool, - pub abstract_integer_model_supported:bool, -} -fn identifier(s:&str)->bool { - !s.is_empty()&&s.chars().all(|c|c.is_alphanumeric()||c=='_') -} -fn term(expr:&A,bindings:&BTreeMap)->Option<(String,bool)>{ - match expr { - A::Lit(T::Int(n))=>Some((format!("({n} : Int)"),false)), - A::Lit(T::Bool(b))=>Some((if *b{"True"}else{"False"}.into(),true)), - A::Var(v)=>Some((bindings.get(v)?.clone(),false)), - A::Bin{op,left,right}=>{ - let (l,lb)=term(left,bindings)?; - let (r,rb)=term(right,bindings)?; - match *op{ - "+" | "-" if !lb && !rb=>Some((format!("({l} {op} {r})"),false)), - // omega only reasons about *linear* arithmetic. A variable - // multiplied by another variable is never assumed linear. - "*" if !lb && !rb - && (matches!(left.as_ref(),A::Lit(T::Int(_))) - ||matches!(right.as_ref(),A::Lit(T::Int(_))))=> - Some((format!("({l} * {r})"),false)), - "=" | "≠" | "<" | "≤" | ">" | "≥" if !lb && !rb=> - Some((format!("({l} {op} {r})"),true)), - "且" if lb && rb=>Some((format!("({l} ∧ {r})"),true)), - "或" if lb && rb=>Some((format!("({l} ∨ {r})"),true)), - _=>None - } - }, - A::Un{op:"非",expr}=>{ - let (inner,boolean)=term(expr,bindings)?; - boolean.then(||(format!("(¬ {inner})"),true)) - }, - A::Un{op:"-",expr}=>{ - let (inner,boolean)=term(expr,bindings)?; - (!boolean).then(||(format!("(-{inner})"),false)) - }, - _=>None - } -} -fn proposition(source:&str,bindings:&BTreeMap)->Option{ - let tokens=proof_check::tokenize_claim(source).ok()?; - let (_,expr)=proof_check::parse_claim_expr(&tokens).ok()?; - let (text,boolean)=term(&expr,bindings)?; - boolean.then_some(text) -} -/// Source-backed branch facts are the only assumptions accepted; no theorem -/// premise provided by a model/user is silently promoted to an axiom. -pub fn plan(semantic:&SemanticProject,call:&BoundCall,premise:&str)->Option{ - if call.control_blocker.is_some()||call.path_guards.is_empty(){return None} - let callee=semantic.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.target))?.signature.as_ref()?; - let caller=semantic.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.caller))?.signature.as_ref()?; - if callee.params.len()!=call.args.len(){return None} - let mut caller_bind=BTreeMap::new(); - let mut binders=Vec::new(); - for (i,param) in caller.params.iter().enumerate(){ - if !identifier(¶m.name){return None} - let variable=format!("v{i}"); - caller_bind.insert(param.name.clone(),format!("({variable} : Int)")); - binders.push(variable); - } - // Marqdo canonical Number may include Int, Num and Formula. - // Proof is over Int only; never claim a runtime type proof here. - let model_supported=caller.params.iter() - .all(|p|p.ty.eq_ignore_ascii_case("number")); - if !model_supported {return None} - let mut callee_bind=BTreeMap::new(); - for (formal,arg) in callee.params.iter().zip(call.args.iter()){ - if arg.name.as_ref().is_some_and(|s|s!=&formal.name){return None} - let actual=if let Some(n)=arg.integer { - format!("({n} : Int)") - }else{ - caller_bind.get(arg.symbol.as_ref()?)?.clone() - }; - if !identifier(&formal.name){return None} - callee_bind.insert(formal.name.clone(),actual); - } - let wanted=proposition(premise,&callee_bind)?; - let all=call.path_guards.iter().map(|guard|proposition(guard,&caller_bind)) - .collect::>>()?; - let idx=all.iter().position(|guard|guard==&wanted); - Some(SymbolicGoal { - proposition:wanted,guard_propositions:all,guard_index:idx, - binders,runtime_domain_verified:false, - abstract_integer_model_supported:model_supported - }) -} -pub fn emit_lean(goals:&[(String,SymbolicGoal)])->String{ - let mut text=String::from("-- Symbolic path theorem over Int model; not runtime equivalence.\nnamespace MarqdoSymbolic\n"); - for (i,(_,g)) in goals.iter().enumerate(){ - let vars=g.binders.iter().map(|x|format!("({x} : Int)")) - .collect::>().join(" "); - let hypotheses=g.guard_propositions.iter().enumerate() - .map(|(n,p)|format!("(h{n} : {p})")) - .collect::>().join(" "); - let tactic=if let Some(n)=g.guard_index { - format!(" exact h{n}") - } else { - " omega".to_string() - }; - text.push_str(&format!("theorem path_vc_{i} {vars} {hypotheses} : {} := by\n{tactic}\n", - g.proposition)); - } - text.push_str("end MarqdoSymbolic\n"); - text -} -#[cfg(test)] -mod tests{ - use super::*; - #[test] - fn branch_condition_generates_symbolic_lean_obligation() { - let root=std::env::temp_dir().join(format!( - "marqdo-symbolic-branch-{}",std::process::id())); - let _=std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root).unwrap(); - std::fs::write(root.join("math.mq.md"), - "# math\n\n## exact\n+ `n`\n\n| 参数 | 类型 | 说明 |\n|---|---|---|\n| n | int | integer |\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| c | 结果 = 2 | n > 0 | auto |\n\n*2*\n").unwrap(); - std::fs::write(root.join("main.mq.md"), - "---\nimport:\n math: math.mq.md\n---\n# main\n\n## f\n+ `n`\n\n| 参数 | 类型 | 说明 |\n|---|---|---|\n| n | int | integer |\n\n1. `n` > 0\n **v = [调用](math.math.exact(`n`))**\n2. *\n **v = 0**\n\n*v*\n").unwrap(); - let c=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let call=c.semantics.bound_calls.iter().find(|x| - x.call_site=="math.math.exact").expect("import binding"); - assert_eq!(call.path_guards.len(),1); - assert!(call.control_blocker.is_none()); - let goal=plan(&c.semantics,call,"n > 0") - .expect("path condition should imply imported precondition"); - assert!(!goal.runtime_domain_verified); - assert!(goal.abstract_integer_model_supported); - assert_eq!(goal.guard_index,Some(0)); - let source=emit_lean(&[("branch-call".into(),goal)]); - assert!(source.contains("theorem path_vc_0")); - assert!(source.contains("exact h0")); - assert!(!source.contains("sorry")); - std::fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn linear_arithmetic_path_goals_are_supported_but_nonlinear_goals_fail_closed(){ - let params=BTreeMap::from([("n".into(),"(v0 : Int)".into()), - ("m".into(),"(v1 : Int)".into())]); - let stronger=proposition("n + 5 > 10",¶ms) - .expect("linear path condition"); - let weaker=proposition("n > 0",¶ms) - .expect("linear callee precondition"); - let goal=SymbolicGoal{ - proposition:weaker,guard_propositions:vec![stronger], - guard_index:None,binders:vec!["v0".into(),"v1".into()], - runtime_domain_verified:false,abstract_integer_model_supported:true - }; - let generated=emit_lean(&[("linear".into(),goal)]); - assert!(generated.contains("omega")); - assert!(generated.contains("+")); - assert!(proposition("n * m > 0",¶ms).is_none(), - "nonlinear multiplication cannot silently enter omega fragment"); - assert!(proposition("n * 3 > 0",¶ms).is_some()); - assert!(proposition("-n < 0",¶ms).is_some()); - assert!(proposition("n / 2 > 0",¶ms).is_none()); - } - #[test] - fn symbolic_guards_cannot_be_invented_from_unsupported_calls(){ - assert!(proposition("lib.fetch(x) > 0",&BTreeMap::new()).is_none()); - } -} diff --git a/src/knowledge/unified.rs b/src/knowledge/unified.rs deleted file mode 100644 index af67781..0000000 --- a/src/knowledge/unified.rs +++ /dev/null @@ -1,498 +0,0 @@ -//! Unified source-derived, kernel-checked modular contracts over the Lean Int -//! abstraction. NOT an unrestricted Marqdo runtime correctness theorem. -//! -//! Each function is translated ONCE from its current AST into a separate Lean -//! module. Contracts are proved from that source; callers use only imported -//! contracts, never synthetic axioms or inlined callee implementations. -//! Supported: pure, statically bound positional calls; integer linear terms, -//! immutable expressions, sequential local assignments and total if/else -//! branches; arbitrarily nested acyclic cross-file dependencies (depth capped). -//! Unsupported: missing/multiple contracts, loops, recursive calls, plugins, -//! effects, dynamic dispatch, defaults, conditional contracts, non-total branches, -//! runtime Number/i64/Formula equivalence. Every such case fails closed. -use std::{collections::{BTreeMap,BTreeSet},fs,path::Path,time::Duration}; -use anyhow::{Context,Result}; -use serde_json::{json,Value}; -use sha2::{Digest,Sha256}; -use crate::{ - ast::{Arg,BinaryOp,CallExpr,Expr,Function,Literal,Stmt,UnaryOp}, - prove::{driver::{Toolchain,compile_import_module}, - proof_check::{self,ClaimAst,CTok}}, - sema::{SymbolId,ir::{BoundCall,CanonicalParam,Compilation,SemanticArtifact}} -}; -use super::projection::load_function; - -const KIND:&str="marqdo_unified_modular_contract"; -const SCOPE:&str="pure_number_int_model_sequential_branch_dag"; -fn sha(bytes:&[u8])->String{format!("sha256:{:x}",Sha256::digest(bytes))} -fn id_for(symbol:&str)->String{ - let value=sha(symbol.as_bytes()); - format!("f_{}",&value[7..31]) -} -fn module_for(symbol:&str)->String{ - let value=sha(symbol.as_bytes()); - format!("M{}",&value[7..31]) -} -fn args_text(args:&[String])->String{ - if args.is_empty(){String::new()}else{format!(" {}",args.join(" "))} -} -fn variables(count:usize)->Vec{ - (0..count).map(|i|format!("v{i}")).collect() -} -fn binders(count:usize)->String{ - variables(count).iter().map(|v|format!(" ({v} : Int)")).collect() -} -fn unique_artifact<'a>(compiled:&'a Compilation,id:&str) - ->Option<&'a SemanticArtifact>{ - let mut found=compiled.semantics.artifacts.iter().filter(|a| - a.kind=="function" && a.symbol_id.as_ref().is_some_and(|s|s.as_str()==id)); - let one=found.next()?; - found.next().is_none().then_some(one) -} -fn basic_signature(params:&[CanonicalParam])->bool{ - params.iter().all(|p|p.ty.eq_ignore_ascii_case("number") - &&p.required&&p.default_digest.is_none()) - &¶ms.iter().map(|p|&p.name).collect::>().len()==params.len() -} -fn claim_term(ast:&ClaimAst,params:&BTreeMap,depth:usize) - ->Option{ - if depth>=32{return None} - match ast{ - ClaimAst::Lit(CTok::Int(n))=>Some(format!("({n} : Int)")), - ClaimAst::Var(v)=>params.get(v).cloned(), - ClaimAst::Un{op:"-",expr}=>Some(format!("(-{})", - claim_term(expr,params,depth+1)?)), - ClaimAst::Bin{op,left,right}=>{ - let symbol=match *op{"+"|"-"|"*"=>*op,_=>return None}; - // Multiplication between symbolic terms is outside the omega - // fragment. Only multiplication by a literal is admitted. - if symbol=="*" && !matches!(left.as_ref(),ClaimAst::Lit(CTok::Int(_))) - &&!matches!(right.as_ref(),ClaimAst::Lit(CTok::Int(_))){return None} - Some(format!("({} {symbol} {})", - claim_term(left,params,depth+1)?, - claim_term(right,params,depth+1)?)) - }, - _=>None - } -} -fn result_claim(compiled:&Compilation,artifact:&SemanticArtifact, - params:&BTreeMap)->Option{ - let owner=artifact.symbol_id.as_ref()?; - let mut matches=compiled.semantics.claims.iter().filter(|c| - c.owner==*owner&&c.premise.as_deref() - .map_or(true,|p|p.trim().is_empty())).filter_map(|c|{ - let tokens=proof_check::tokenize_claim(&c.conclusion).ok()?; - let (_,ast)=proof_check::parse_claim_expr(&tokens).ok()?; - match ast{ - ClaimAst::Bin{op,left,right} - if matches!(*left,ClaimAst::Var(ref n) if n=="结果")=>{ - let operator=match op{ - "="=>"=", ">"=>">", "<"=>"<", "≥"=>">=", "≤"=>"<=", "≠"=>"!=", - _=>return None - }; - Some(format!("{operator} {}",claim_term(&right,params,0)?)) - }, - _=>None - } - }); - let first=matches.next()?; - // One exported claim per function is an explicit, auditable boundary; - // other statements are never silently promoted into assumptions. - matches.next().is_none().then_some(first) -} -#[derive(Clone)] -struct CallUse{ - callee:String,args:Vec -} -#[derive(Clone)] -struct Built{ - symbol:String,artifact:String,closure:String,module:String,lean:String, - file:String,dep_symbols:BTreeSet,result_operator:String -} -struct Builder<'a>{ - compilation:&'a Compilation, - active:BTreeSet, - built:BTreeMap, - order:Vec -} -impl<'a> Builder<'a>{ - fn new(c:&'a Compilation)->Self{ - Self{compilation:c,active:BTreeSet::new(), - built:BTreeMap::new(),order:Vec::new()} - } - fn number(&mut self,expr:&Expr,env:&BTreeMap,owner:&str, - line:u32,uses:&mut Vec,depth:usize)->Option{ - if depth>=32{return None} - match expr{ - Expr::Literal(Literal::Int(n))=>Some(format!("({n} : Int)")), - Expr::Var(v)=>env.get(v).cloned(), - Expr::Occluded{payload:Some(inner),..}=> - self.number(inner,env,owner,line,uses,depth+1), - Expr::Unary{op:UnaryOp::Neg,expr}=>Some(format!("(-{})", - self.number(expr,env,owner,line,uses,depth+1)?)), - Expr::Binary{op,left,right}=>{ - let symbol=match op{ - BinaryOp::Add=>"+",BinaryOp::Sub=>"-", - BinaryOp::Mul=>"*",_=>return None - }; - if symbol=="*" && !matches!(left.as_ref(),Expr::Literal(Literal::Int(_))) - &&!matches!(right.as_ref(),Expr::Literal(Literal::Int(_))){ - return None - } - let a=self.number(left,env,owner,line,uses,depth+1)?; - let b=self.number(right,env,owner,line,uses,depth+1)?; - Some(format!("({a} {symbol} {b})")) - }, - Expr::Call(call)=>self.call(call,env,owner,line,uses,depth+1), - _=>None - } - } - fn condition(&mut self,expr:&Expr,env:&BTreeMap, - owner:&str,line:u32,uses:&mut Vec,depth:usize)->Option{ - if depth>=32{return None} - match expr{ - Expr::Literal(Literal::Bool(b))=>Some(if *b{"True"}else{"False"}.into()), - Expr::Occluded{payload:Some(inner),..}=> - self.condition(inner,env,owner,line,uses,depth+1), - Expr::Unary{op:UnaryOp::Not,expr}=>Some(format!("(¬ {})", - self.condition(expr,env,owner,line,uses,depth+1)?)), - Expr::Binary{op,left,right}=>{ - let relation=match op{ - BinaryOp::Eq=>Some("="),BinaryOp::Ne=>Some("≠"), - BinaryOp::Lt=>Some("<"),BinaryOp::Le=>Some("≤"), - BinaryOp::Gt=>Some(">"),BinaryOp::Ge=>Some("≥"), - _=>None - }; - if let Some(rel)=relation{ - let a=self.number(left,env,owner,line,uses,depth+1)?; - let b=self.number(right,env,owner,line,uses,depth+1)?; - return Some(format!("({a} {rel} {b})")) - } - let relation=match op{BinaryOp::And=>"∧", - BinaryOp::Or=>"∨",_=>return None}; - let a=self.condition(left,env,owner,line,uses,depth+1)?; - let b=self.condition(right,env,owner,line,uses,depth+1)?; - Some(format!("({a} {relation} {b})")) - }, - _=>None - } - } - fn call(&mut self,call:&CallExpr,env:&BTreeMap, - owner:&str,line:u32,uses:&mut Vec,depth:usize)->Option{ - if depth>=32 ||call.path.is_none()||call.receiver.is_some() - ||!call.pre_modifiers.is_empty(){return None} - let normalized=call.for_evaluation().ok()?; - let display=crate::sema::bind::call_display(&normalized); - let mut matches=self.compilation.semantics.bound_calls.iter().filter(|bc| - bc.caller.as_str()==owner &&bc.source.line==line&& - bc.call_site==display); - let bound=matches.next()?.clone(); - if matches.next().is_some()||bound.control_blocker.is_some() - ||!bound.required_effects.is_pure()||bound.args.len()!=call.args.len(){ - return None - } - let callee=bound.target.as_str(); - if callee==owner{return None} - let artifact=unique_artifact(self.compilation,callee)?; - if !artifact.effects.is_pure(){return None} - let signature=artifact.signature.as_ref()?; - if !basic_signature(&signature.params)|| - signature.params.len()!=call.args.len(){return None} - // Only positional arguments, in executable order, are trusted here. - // Named/default/variadic semantics require their own binding proof. - let mut args=Vec::new(); - for (actual,static_arg) in call.args.iter().zip(&bound.args){ - if static_arg.name.is_some(){return None} - let Arg::Positional(value)=actual else{return None}; - args.push(self.number(value,env,owner,line,uses,depth+1)?); - } - self.visit(callee)?; - uses.push(CallUse{callee:callee.to_owned(),args:args.clone()}); - Some(format!("({}{})",id_for(callee),args_text(&args))) - } - fn block(&mut self,items:&[Stmt],mut env:BTreeMap, - owner:&str,uses:&mut Vec,conditions:&mut Vec,depth:usize)->Option{ - if depth>=32{return None} - for (index,st) in items.iter().enumerate(){ - match st{ - Stmt::Assign{name,value,span,..}=>{ - let rhs=self.number(value,&env,owner,span.line,uses,0)?; - env.insert(name.clone(),rhs); - }, - Stmt::Return{value,span} if index+1==items.len()=>{ - return self.number(value,&env,owner,span.line,uses,0) - }, - Stmt::Branch{arms,span} if index+1==items.len()=>{ - // A branch must explicitly cover all outcomes, including - // its else arm. No unproved fallthrough is accepted. - let mut otherwise=None; - for arm in arms.iter().rev(){ - let expression=self.block(&arm.body,env.clone(), - owner,uses,conditions,depth+1)?; - otherwise=Some(if let Some(condition)=&arm.condition{ - let cond=self.condition(condition,&env,owner, - span.line,uses,0)?; - if !conditions.contains(&cond){conditions.push(cond.clone())} - let rest=otherwise?; - format!("(if {cond} then {expression} else {rest})") - }else{ - if otherwise.is_some(){return None} - expression - }); - } - return otherwise - }, - _=>return None - } - } - None - } - fn visit(&mut self,symbol:&str)->Option<()>{ - if self.built.contains_key(symbol){return Some(())} - if self.active.len()>=24||!self.active.insert(symbol.to_owned()){ - return None - } - let result=(||->Option{ - let a=unique_artifact(self.compilation,symbol)?.clone(); - if !a.effects.is_pure(){return None} - let sig=a.signature.as_ref()?; - if !basic_signature(&sig.params){return None} - let fun:Function=load_function(self.compilation,&a)?; - if fun.is_object()||fun.params.len()!=sig.params.len() - ||!fun.params.iter().zip(&sig.params) - .all(|(f,p)|f.name==p.name){return None} - let env=sig.params.iter().enumerate().map(|(i,p)| - (p.name.clone(),format!("v{i}"))).collect::>(); - let contract=result_claim(self.compilation,&a,&env)?; - let mut call_uses=Vec::new(); - let mut conditions=Vec::new(); - let body=self.block(&fun.body,env,symbol,&mut call_uses, - &mut conditions,0)?; - // No semantically relevant BoundCall may remain unmodeled: - // every source call requires a unique static binding. - let source_count=self.compilation.semantics.bound_calls.iter() - .filter(|c|c.caller.as_str()==symbol).count(); - if call_uses.len()!=source_count{return None} - let deps=call_uses.iter().map(|use_|use_.callee.clone()) - .collect::>(); - if deps.contains(symbol){return None} - let fname=id_for(symbol); - let args=variables(sig.params.len()); - let bind=binders(sig.params.len()); - let invocation=format!("{fname}{}",args_text(&args)); - let mut source=String::new(); - for dep in &deps{ - source.push_str(&format!("import {}\n",module_for(dep))); - } - source.push_str(&format!( - "-- Generated from a pure Marqdo AST. Int abstraction only.\n\ - def {fname}{bind} : Int := {body}\n\ - theorem {fname}_contract{bind} : {invocation} {contract} := by\n")); - for (i,use_) in call_uses.iter().enumerate(){ - let callee_contract=format!("{}_contract",id_for(&use_.callee)); - source.push_str(&format!( - " have hc{i} := {callee_contract}{}\n",args_text(&use_.args))); - } - // `split_ifs` is a Mathlib tactic, unavailable under the - // pinned core Lean toolchain. Case-split on source-derived - // conditions using core `by_cases`, then simplify each case. - let mut tactic=format!(" simp only [{fname}] at *"); - for (i,condition) in conditions.iter().enumerate(){ - tactic.push_str(&format!(" <;> by_cases h{i} : {condition}")); - } - if conditions.is_empty(){ - tactic.push_str(" <;> omega\n"); - }else{ - tactic.push_str(" <;> simp_all <;> omega\n"); - } - source.push_str(&tactic); - let operator=contract.split_whitespace().next()?.to_string(); - Some(Built{ - symbol:symbol.to_owned(),artifact:a.artifact_id.0.clone(), - closure:a.hashes.closure.0.clone(),module:module_for(symbol), - lean:source,file:a.source.file.clone(),dep_symbols:deps, - result_operator:operator - }) - })(); - self.active.remove(symbol); - if let Some(built)=result{ - self.order.push(symbol.to_owned()); - self.built.insert(symbol.to_owned(),built); - Some(()) - }else{None} - } - fn plan(mut self,root:&str)->Option{ - self.visit(root)?; - if self.built.len()<2{return None} - let nodes=self.order.iter().map(|id|self.built.get(id).cloned()) - .collect::>>()?; - // Actually prove a caller that uses imported source definitions. - if nodes.last()?.dep_symbols.is_empty(){return None} - Some(Plan{root:root.into(),nodes}) - } -} -#[derive(Clone)] -struct Plan{root:String,nodes:Vec} -impl Plan{ - fn identities(&self)->BTreeSet<(String,String)>{ - self.nodes.iter().map(|n|(n.artifact.clone(),n.closure.clone())) - .collect() - } - fn key(&self,version:&str)->String{ - sha(format!("{}|{:?}|{}",self.root,self.identities(),version).as_bytes()) - } -} -fn candidate(c:&Compilation,root:&str)->Option{ - Builder::new(c).plan(root) -} -/// Retain the stable legacy certificate format for simple one-call -/// forwarders. Use the unified engine for actual sequential, branched or -/// transitive contracts, where the legacy shape cannot represent the proof. -fn advanced(c:&Compilation,plan:&Plan)->bool{ - if plan.nodes.len()>2{return true} - if c.semantics.bound_calls.iter() - .filter(|call|call.caller.as_str()==plan.root).count()>1{return true} - let Some(artifact)=unique_artifact(c,&plan.root) else{return false}; - let Some(function)=load_function(c,artifact) else{return false}; - function.body.iter().any(|stmt|matches!(stmt,Stmt::Branch{..})) -} -pub(super) fn covers(c:&Compilation,root:&SymbolId)->bool{ - candidate(c,root.as_str()).is_some_and(|plan|advanced(c,&plan)) -} -pub(super) fn prove(c:&Compilation,out:&Path,lean:&Toolchain)->Result>{ - let roots=c.semantics.bound_calls.iter().map(|call|call.caller.as_str()) - .collect::>(); - let mut results=Vec::new(); - for root in roots{ - let Some(plan)=candidate(c,root)else{continue}; - if !advanced(c,&plan){continue} - let key=plan.key(&lean.version); - let dir=out.join("composed").join(format!("unified-{}",&key[7..23])); - fs::create_dir_all(&dir)?; - let checked=(||->Result>{ - let mut files=Vec::new(); - for node in &plan.nodes{ - let src=dir.join(format!("{}.lean",node.module)); - let obj=dir.join(format!("{}.olean",node.module)); - fs::write(&src,&node.lean)?; - compile_import_module(lean,&src,&obj,&dir,Duration::from_secs(120)) - .with_context(||format!("module {}",node.module))?; - files.push(json!({ - "symbol":node.symbol,"artifact":node.artifact, - "module":node.module,"source_sha256":sha(node.lean.as_bytes()), - "compiled_sha256":sha(&fs::read(obj)?), - "dependencies":node.dep_symbols,"result_operator":node.result_operator, - "source_file":node.file - })); - } - Ok(files) - })(); - match checked{ - Ok(files)=>{ - let certificate=json!({ - "schema_version":1,"kind":KIND,"scope":SCOPE, - "status":"lean_kernel_proved_model", - "evidence_grade":"model_proved", - "full_marqdo_runtime_semantics_proved":false, - "identity":plan.root,"toolchain":lean.version, - "source_closures":plan.identities().iter().map(|(id,h)| - json!({"id":id,"closure":h})).collect::>(), - "modules":files, - "independent_replay":"topological module recompilation from current source" - }); - let certificate_path=dir.join("composition-certificate.json"); - fs::write(&certificate_path,serde_json::to_vec_pretty(&certificate)?)?; - results.push(json!({"identity":plan.root, - "status":"lean_kernel_proved_model", - "scope":SCOPE,"artifact":certificate_path, - "evidence":super::evidence::model_proved()})); - }, - Err(e)=>{ - let _=fs::remove_file(dir.join("composition-certificate.json")); - results.push(json!({"identity":plan.root,"status":"lean_rejected", - "scope":SCOPE,"error":format!("{e:#}"), - "evidence":super::evidence::unknown("lean_rejected")})); - } - } - } - Ok(results) -} -pub(super) fn replay(c:&Compilation,certificate:&Path,lean:&Toolchain)->Result{ - let cert:Value=serde_json::from_slice(&fs::read(certificate)?)?; - anyhow::ensure!(cert["schema_version"]==1&&cert["kind"]==KIND - &&cert["scope"]==SCOPE&&cert["status"]=="lean_kernel_proved_model" - &&cert["evidence_grade"]=="model_proved" - &&cert["full_marqdo_runtime_semantics_proved"]==false, - "proof.unified_invalid_certificate"); - anyhow::ensure!(cert["toolchain"]==lean.version, - "proof.unified_stale_toolchain"); - let root=cert["identity"].as_str().context("proof.unified_missing_identity")?; - let plan=candidate(c,root).context("proof.unified_stale_or_unsupported_source")?; - let expected=plan.identities(); - let items=cert["source_closures"].as_array() - .context("proof.unified_missing_source_closures")?; - let actual=items.iter().map(|r|Ok(( - r["id"].as_str().context("proof.unified_invalid_id")?.to_string(), - r["closure"].as_str().context("proof.unified_invalid_hash")?.to_string() - ))).collect::>>()?; - anyhow::ensure!(items.len()==expected.len()&&actual==expected, - "proof.unified_stale_or_ambiguous_source_closure"); - let rows=cert["modules"].as_array().context("proof.unified_missing_modules")?; - anyhow::ensure!(rows.len()==plan.nodes.len(), - "proof.unified_module_count_changed"); - let dir=certificate.parent().context("proof.unified_missing_parent")?; - for (node,row) in plan.nodes.iter().zip(rows){ - anyhow::ensure!(row["symbol"]==node.symbol&&row["artifact"]==node.artifact - &&row["module"]==node.module - &&row["dependencies"]==json!(node.dep_symbols) - &&row["result_operator"]==node.result_operator - &&row["source_file"]==node.file, - "proof.unified_module_identity_changed"); - let src=dir.join(format!("{}.lean",node.module)); - let obj=dir.join(format!("{}.olean",node.module)); - anyhow::ensure!(fs::read_to_string(&src)?==node.lean - &&row["source_sha256"]==sha(node.lean.as_bytes()), - "proof.unified_generated_source_changed"); - compile_import_module(lean,&src,&obj,dir,Duration::from_secs(120))?; - anyhow::ensure!(row["compiled_sha256"]==sha(&fs::read(&obj)?), - "proof.unified_compiled_module_changed"); - } - Ok(json!({"schema_version":1,"kind":"independent_composition_replay", - "status":"lean_kernel_replayed","scope":SCOPE,"identity":root, - "evidence":super::evidence::model_replayed(), - "current_source_verified":true, - "full_marqdo_runtime_semantics_proved":false})) -} - -#[cfg(test)] -mod tests{ - use super::*; - #[test] - fn simple_source_contracts_must_not_be_promoted_without_unique_claim(){ - let c=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path( - Path::new("doc/verification/skill-proof")).unwrap()); - if let Ok(project)=c{ - for artifact in project.semantics.artifacts.iter() - .filter(|a|a.kind=="function"){ - assert!(!project.semantics.claims.iter() - .any(|r|r.owner.as_str()=="__invented_symbol__")); - let _=artifact; - } - } - } - #[test] - fn claim_language_refuses_nonlinear_and_unknown_values(){ - let bind=BTreeMap::from([("n".into(),"v0".into()), - ("m".into(),"v1".into())]); - let parse=|s:&str|{ - let toks=proof_check::tokenize_claim(s).unwrap(); - proof_check::parse_claim_expr(&toks).unwrap().1 - }; - assert_eq!(claim_term(&parse("n + 2"),&bind,0), - Some("(v0 + (2 : Int))".into())); - assert!(claim_term(&parse("n * m"),&bind,0).is_none()); - assert!(claim_term(&parse("n / 2"),&bind,0).is_none()); - assert!(claim_term(&parse("secret"),&bind,0).is_none()); - } -} diff --git a/src/knowledge/util.rs b/src/knowledge/util.rs deleted file mode 100755 index 376d539..0000000 --- a/src/knowledge/util.rs +++ /dev/null @@ -1,197 +0,0 @@ -//! Shared frontmatter / prose helpers for knowledge extraction. - -pub fn extract_fm_field(source: &str, key: &str) -> Option { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return None; - } - let prefix = format!("{key}:"); - for line in lines.iter().skip(1) { - let t = line.trim(); - if t == "---" { - break; - } - if let Some(rest) = t.strip_prefix(&prefix) { - return Some(rest.trim().trim_matches('"').to_string()); - } - } - None -} - -pub fn extract_nested_by(source: &str, block: &str) -> Option { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return None; - } - let mut in_block = false; - for line in lines.iter().skip(1) { - let t = line.trim_end(); - if t.trim() == "---" { - break; - } - if t.trim() == format!("{block}:") { - in_block = true; - continue; - } - if in_block { - let trimmed = t.trim(); - if trimmed.starts_with("by:") { - return Some( - trimmed - .trim_start_matches("by:") - .trim() - .trim_matches('"') - .to_string(), - ); - } - if !trimmed.is_empty() && !line.starts_with(' ') && !line.starts_with('\t') { - break; - } - } - } - None -} - -pub fn extract_fm_list(source: &str, key: &str) -> Vec { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return Vec::new(); - } - let mut out = Vec::new(); - let mut in_list = false; - let header = format!("{key}:"); - for line in lines.iter().skip(1) { - let t = line.trim_end(); - if t.trim() == "---" { - break; - } - if t.trim() == header || t.trim() == format!("{key}: []") { - if t.trim().ends_with("[]") { - return Vec::new(); - } - in_list = true; - continue; - } - if in_list { - let trimmed = t.trim(); - if let Some(rest) = trimmed.strip_prefix("- ") { - out.push(rest.trim().trim_matches('"').to_string()); - } else if !trimmed.is_empty() && !line.starts_with(' ') && !line.starts_with('\t') { - break; - } - } - } - out -} - -/// Extract section body under `## Heading` until next `##` / `#` / EOF. -pub fn extract_section(source: &str, heading: &str) -> Option { - let markers = [ - format!("## {heading}"), - format!("## {}", heading.to_ascii_lowercase()), - format!("## {}", heading.to_ascii_uppercase()), - ]; - let lines: Vec<&str> = source.lines().collect(); - let mut start = None; - for (i, line) in lines.iter().enumerate() { - let t = line.trim(); - if markers.iter().any(|m| t.eq_ignore_ascii_case(m)) { - start = Some(i + 1); - break; - } - } - let start = start?; - let mut body = Vec::new(); - for line in lines.iter().skip(start) { - let t = line.trim(); - if t.starts_with("## ") || (t.starts_with("# ") && !t.starts_with("## ")) { - break; - } - body.push(*line); - } - let s = body.join("\n").trim().to_string(); - if s.is_empty() { - None - } else { - Some(s) - } -} - -pub fn first_paragraph(source: &str) -> String { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let mut after_fm = source; - if let Some(rest) = source.strip_prefix("---") { - if let Some(idx) = rest.find("\n---") { - after_fm = &rest[idx + 4..]; - } - } - let mut paras = Vec::new(); - let mut cur = String::new(); - for line in after_fm.lines() { - let t = line.trim(); - if t.starts_with('#') { - if !cur.is_empty() { - break; - } - continue; - } - if t.is_empty() { - if !cur.is_empty() { - paras.push(cur.clone()); - break; - } - continue; - } - if !cur.is_empty() { - cur.push(' '); - } - cur.push_str(t); - } - if paras.is_empty() && !cur.is_empty() { - paras.push(cur); - } - paras.first().cloned().unwrap_or_default() -} - -pub fn yaml_escape(s: &str) -> String { - if s.is_empty() - || s.contains(':') - || s.contains('#') - || s.contains('"') - || s.contains('\'') - || s.contains('\n') - || s.starts_with(' ') - { - format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) - } else { - s.to_string() - } -} - -pub fn module_stem(resource: &str) -> String { - resource - .replace('/', "__") - .replace('\\', "__") - .trim_end_matches(".mq.md") - .trim_end_matches(".md") - .to_string() -} - -pub fn slugify(s: &str) -> String { - let mut out = String::new(); - for c in s.chars() { - if c.is_ascii_alphanumeric() { - out.push(c.to_ascii_lowercase()); - } else if c == '_' || c == '-' || c == '.' { - out.push(c); - } else if c.is_whitespace() || c == '/' { - if !out.ends_with('-') { - out.push('-'); - } - } - } - out.trim_matches('-').to_string() -} diff --git a/src/knowledge/vc.rs b/src/knowledge/vc.rs deleted file mode 100644 index 3410e10..0000000 --- a/src/knowledge/vc.rs +++ /dev/null @@ -1,142 +0,0 @@ -//! Closed, overflow-safe callsite verification conditions. A generated -//! formula is a Lean *goal*, not evidence. Only a subsequent kernel invocation -//! can discharge it. Unknown/symbolic arguments always remain open. -use std::collections::BTreeMap; -use crate::prove::proof_check::{self,ClaimAst as A,CTok as T}; -use crate::sema::ir::{BoundCall, SemanticProject}; - -#[derive(Debug,Clone,PartialEq,Eq)] -pub struct Goal { - /// Exact statement of the instantiated proposition. - pub proposition: String, - /// Conservative host-side check for early rejection only; not a proof. - pub holds: bool, -} -enum Term { - Int(i64,String), - Bool(bool,String), -} -fn calc(ast:&A, actuals:&BTreeMap)->Option{ - match ast { - A::Lit(T::Int(n))=>Some(Term::Int(*n,format!("({n} : Int)"))), - A::Lit(T::Bool(b))=>Some(Term::Bool(*b, - if *b{"True"}else{"False"}.into())), - A::Var(v)=>actuals.get(v).map(|n|Term::Int(*n,format!("({n} : Int)"))), - A::Un{op,expr}=>match (*op,calc(expr,actuals)?) { - ("-",Term::Int(n,code))=>Some(Term::Int(n.checked_neg()?,format!("(-{code})"))), - ("非",Term::Bool(b,code))=>Some(Term::Bool(!b,format!("(¬ {code})"))), - _=>None - }, - A::Bin{op,left,right}=>{ - let l=calc(left,actuals)?; - let r=calc(right,actuals)?; - match (l,r) { - (Term::Int(x,a),Term::Int(y,b))=>{ - let pair=match *op { - "+"=>Some((x.checked_add(y)?,format!("({a} + {b})"))), - "-"=>Some((x.checked_sub(y)?,format!("({a} - {b})"))), - "*"=>Some((x.checked_mul(y)?,format!("({a} * {b})"))), - _=>None - }; - if let Some((n,code))=pair {return Some(Term::Int(n,code))} - let (truth,rel)=match *op { - "="=>(x==y,"="),"≠"=>(x!=y,"≠"), - "<"=>(x(x<=y,"≤"), - ">"=>(x>y,">"),"≥"=>(x>=y,"≥"),_=>return None - }; - Some(Term::Bool(truth,format!("({a} {rel} {b})"))) - }, - (Term::Bool(x,a),Term::Bool(y,b))=>{ - let (truth,code)=match *op { - "且"=>(x&&y,format!("({a} ∧ {b})")), - "或"=>(x||y,format!("({a} ∨ {b})")), - "="=>(x==y,format!("({a} ↔ {b})")), - "≠"=>(x!=y,format!("(¬ ({a} ↔ {b}))")), - _=>return None - }; - Some(Term::Bool(truth,code)) - }, - _=>None - } - }, - _=>None - } -} -pub fn instantiate(semantic:&SemanticProject,call:&BoundCall,premise:&str)->Option{ - let owner=semantic.artifacts.iter().find(|a| - a.symbol_id.as_ref()==Some(&call.target))?; - let signature=owner.signature.as_ref()?; - if signature.params.len()!=call.args.len(){return None} - // No implicit defaults, no mixed positional/named ambiguity. Explicitly - // require that the exact ordered actuals match the callee signature. - let mut bindings=BTreeMap::new(); - for (formal,actual) in signature.params.iter().zip(call.args.iter()){ - if actual.name.as_ref().is_some_and(|name|name!=&formal.name){ - return None - } - bindings.insert(formal.name.clone(),actual.integer?); - } - let tokens=proof_check::tokenize_claim(premise).ok()?; - let (_,expr)=proof_check::parse_claim_expr(&tokens).ok()?; - match calc(&expr,&bindings)? { - Term::Bool(holds,proposition)=>Some(Goal{holds,proposition}), - Term::Int(..)=>None - } -} -pub fn emit_lean(goals:&[(String,Goal)])->String{ - let mut out=String::from( - "-- Generated closed obligations. These are not accepted until Lean checks them.\n"); - out.push_str("namespace MarqdoClosedCallsite\n"); - for (i,(_,goal)) in goals.iter().enumerate(){ - out.push_str(&format!( - "theorem vc_{i} : {} := by decide\n",goal.proposition)); - } - out.push_str("end MarqdoClosedCallsite\n"); - out -} -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn bool_and_arithmetic_propositions_are_kernel_goals_not_certs(){ - let ast=proof_check::parse_claim_expr( - &proof_check::tokenize_claim("金额 > 0 且 金额 < 10").unwrap()).unwrap().1; - let args=BTreeMap::from([("金额".into(),3)]); - let Term::Bool(holds,prop)=calc(&ast,&args).unwrap() else {panic!("not boolean")}; - assert!(holds); - assert!(prop.contains("∧")&&prop.contains("(3 : Int)")); - let lean=emit_lean(&[("test".into(),Goal{proposition:prop,holds})]); - assert!(lean.contains("theorem vc_0")); - assert!(!lean.contains("sorry")); - } - #[test] - fn real_project_call_actuals_generate_closed_goal_without_claiming_proof(){ - let root=std::env::temp_dir().join( - format!("marqdo-closed-vc-{}",std::process::id())); - let _=std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root).unwrap(); - std::fs::write(root.join("math.mq.md"), - "# math\n\n## exact\n+ `n`\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| c | 结果 = 2 | n > 0 | auto |\n\n*2*\n").unwrap(); - std::fs::write(root.join("main.mq.md"), - "---\nimport:\n math: math.mq.md\n---\n# main\n\n## f\n\n**v = [调用](math.math.exact(3))**\n*v*\n").unwrap(); - let compiled=crate::sema::ir::compile_project( - &crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap(); - let call=compiled.semantics.bound_calls.iter().find( - |c|c.call_site=="math.math.exact").expect("real imported bound call"); - assert_eq!(call.args.len(),1); - assert_eq!(call.args[0].integer,Some(3)); - let goal=instantiate(&compiled.semantics,call,"n > 0").unwrap(); - assert!(goal.holds); - assert!(goal.proposition.contains("(3 : Int)")); - assert!(instantiate(&compiled.semantics,call,"n > 10") - .is_some_and(|goal|!goal.holds)); - std::fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn overflowing_i64_expression_is_not_silently_lean_unbounded(){ - let ast=proof_check::parse_claim_expr( - &proof_check::tokenize_claim("x + 1 > 0").unwrap()).unwrap().1; - assert!(calc(&ast,&BTreeMap::from([("x".into(),i64::MAX)])).is_none()); - } -} diff --git a/src/label.rs b/src/label.rs deleted file mode 100755 index 06078cb..0000000 --- a/src/label.rs +++ /dev/null @@ -1,732 +0,0 @@ -//! `` M2.5/M4: occlusion-label collection and diagnostics. -//! -//! A label is **inert prose**: it never runs, never binds, never types. This -//! module only *reads* it — to report structural problems (`label.missing`, -//! `label.empty_payload`) and, later, to check staleness (`label.ref_dangling`). -//! -//! Design: [occlusion-description-and-search.md](../../doc/design/occlusion-description-and-search.md) - -use crate::ast::{Arg, BranchArm, Expr, Function, Module, Stmt}; -use crate::diagnostics::{Diagnostic, Severity, Span}; - -/// One `[描述](实现)` site found in the module. -#[derive(Debug, Clone)] -pub struct OcclusionSite { - /// Raw label text (already trimmed by the parser). - pub label: String, - /// `false` when written as `[描述]()` — the empty-payload stub. - pub has_payload: bool, - /// 1-based source line of the enclosing statement. - pub line: u32, - /// Enclosing function/object name (`# main` → `main`). - pub unit: String, - /// Identifiers the payload actually mentions (for L1 ref checks). - pub payload_idents: std::collections::HashSet, - /// In-process fingerprint of the payload (T1 staleness comparison). - pub payload_fp: String, - /// Surface rendering of the payload (diagnostics: `code_past` / `code_now`). - pub payload_src: String, -} - -/// Collect every occlusion in `module` (declaration order). -pub fn collect(module: &Module) -> Vec { - let mut out = Vec::new(); - for fun in &module.functions { - walk_fun(fun, &mut out); - } - out -} - -fn walk_fun(fun: &Function, out: &mut Vec) { - for stmt in &fun.body { - walk_stmt(stmt, &fun.name, out); - } - for child in &fun.children { - walk_fun(child, out); - } -} - -fn walk_stmt(stmt: &Stmt, unit: &str, out: &mut Vec) { - match stmt { - Stmt::Assign { value, span, .. } - | Stmt::Return { value, span } - | Stmt::Expr { value, span } => walk_expr(value, span.line, unit, out), - Stmt::Call { call, span } => { - for a in &call.args { - match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => { - walk_expr(e, span.line, unit, out) - } - } - } - } - Stmt::Branch { arms, span } => { - for arm in arms { - walk_arm(arm, span.line, unit, out); - } - } - Stmt::While { condition, body, span } => { - walk_expr(condition, span.line, unit, out); - for s in body { - walk_stmt(s, unit, out); - } - } - Stmt::ForEach { body, span, .. } => { - for s in body { - walk_stmt(s, unit, out); - } - let _ = span; - } - } -} - -fn walk_arm(arm: &BranchArm, line: u32, unit: &str, out: &mut Vec) { - // `condition: Option` for the `*` else-arm. - if let Some(cond) = &arm.condition { - walk_expr(cond, line, unit, out); - } - for s in &arm.body { - walk_stmt(s, unit, out); - } -} - -fn walk_expr(expr: &Expr, line: u32, unit: &str, out: &mut Vec) { - match expr { - Expr::Occluded { label, payload } => { - let mut idents = std::collections::HashSet::new(); - if let Some(inner) = payload { - payload_idents(inner, &mut idents); - } - out.push(OcclusionSite { - label: label.clone(), - has_payload: payload.is_some(), - line, - unit: unit.to_string(), - payload_idents: idents, - payload_fp: payload_fingerprint(payload), - payload_src: render_payload(payload), - }); - if let Some(inner) = payload { - walk_expr(inner, line, unit, out); - } - } - Expr::Unary { expr, .. } => walk_expr(expr, line, unit, out), - Expr::Binary { left, right, .. } => { - walk_expr(left, line, unit, out); - walk_expr(right, line, unit, out); - } - Expr::Call(call) => { - for a in &call.args { - match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => walk_expr(e, line, unit, out), - } - } - } - Expr::List(items) => { - for e in items { - walk_expr(e, line, unit, out); - } - } - Expr::Map(pairs) => { - for (_, e) in pairs { - walk_expr(e, line, unit, out); - } - } - Expr::Index { base, .. } => walk_expr(base, line, unit, out), - // Interpolation carries only variable *names* (strings), never nested - // expressions, so there is nothing to walk into. - Expr::Interp(_) => {} - Expr::Literal(_) | Expr::Var(_) | Expr::Formula(_) | Expr::Code(_) => {} - } -} - -/// Backticked entity references inside a label: `` 按 `税率` 计算 `` → `["税率"]`. -/// -/// Only explicit backticks count as claims — plain prose never is. `` M4 -pub fn refs(label: &str) -> Vec { - let mut out = Vec::new(); - let mut rest = label; - while let Some(open) = rest.find('`') { - let after = &rest[open + 1..]; - let Some(close) = after.find('`') else { - break; - }; - let name = after[..close].trim(); - if !name.is_empty() { - out.push(name.to_string()); - } - rest = &after[close + 1..]; - } - out -} - -/// Every identifier the payload actually mentions (variables, callees, path parts). -fn payload_idents(expr: &Expr, out: &mut std::collections::HashSet) { - match expr { - Expr::Var(n) => { - out.insert(n.clone()); - } - Expr::Occluded { payload, .. } => { - if let Some(inner) = payload { - payload_idents(inner, out); - } - } - Expr::Unary { expr, .. } => payload_idents(expr, out), - Expr::Binary { left, right, .. } => { - payload_idents(left, out); - payload_idents(right, out); - } - Expr::Call(call) => { - out.insert(call.callee.clone()); - if let Some(p) = &call.path { - for seg in p { - out.insert(seg.clone()); - } - } - if let Some(r) = &call.receiver { - out.insert(r.clone()); - } - for a in &call.args { - match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => payload_idents(e, out), - } - } - } - Expr::List(items) => { - for e in items { - payload_idents(e, out); - } - } - Expr::Map(pairs) => { - for (_, e) in pairs { - payload_idents(e, out); - } - } - Expr::Index { base, label } => { - payload_idents(base, out); - if let crate::ast::IndexKey::Var(n) = label { - out.insert(n.clone()); - } - } - Expr::Interp(parts) => { - for p in parts { - if let crate::ast::InterpPart::Var(n) = p { - out.insert(n.clone()); - } - } - } - Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {} - } -} - -/// Names that exist in the document scope: functions/objects (recursive), -/// import aliases, frontmatter keys. Builtins are checked separately. -fn module_symbols(module: &Module) -> std::collections::HashSet { - let mut out = std::collections::HashSet::new(); - fn walk_fun(f: &Function, out: &mut std::collections::HashSet) { - out.insert(f.name.clone()); - for p in &f.params { - out.insert(p.name.clone()); - } - for c in &f.children { - walk_fun(c, out); - } - } - for f in &module.functions { - walk_fun(f, &mut out); - } - for imp in &module.imports { - out.insert(imp.bind.clone()); - } - for u in &module.uses { - out.insert(u.bind.clone()); - } - for (k, _) in &module.metadata { - out.insert(k.clone()); - } - out -} - -/// Diagnostics for label structure. `` M2.5 -/// -/// - empty label → `label.missing` (**error**): you wrote a shape without prose -/// - empty payload → `label.empty_payload` (**warning**): say what the stub returns -pub fn check(module: &Module, path: Option<&std::path::Path>) -> Vec { - let mut out = Vec::new(); - let symbols = module_symbols(module); - for site in collect(module) { - let span = Span::new(site.line, 1); - if site.label.is_empty() { - out.push( - Diagnostic::new( - path, - span, - format!( - "遮蔽缺少描述:`[]({})` —— 给这段实现写一句人话,或改用不带遮蔽的写法", - if site.has_payload { "…" } else { "" } - ), - ) - .with_code("label.missing") - .with_severity(Severity::Error) - .with_suggestion("写成 `[这段实现做什么](实现)`;描述是自由文本,不参与执行"), - ); - continue; - } - if !site.has_payload { - out.push( - Diagnostic::new( - path, - span, - format!("空载荷遮蔽:`[{}]()` —— 这里没有可执行内容", site.label), - ) - .with_code("label.empty_payload") - .with_severity(Severity::Warning) - .with_doc_quote(site.label.clone()) - .with_suggestion("写清桩的返回值(如 `(None)` 或 `(0)`),或补上真实实现"), - ); - } - - // `` M4 (L1): every backticked ref in the label must resolve — - // either the payload mentions it, or the document defines it, or it is - // a builtin. This is the deterministic half of staleness detection. - for r in refs(&site.label) { - if site.payload_idents.contains(&r) - || symbols.contains(&r) - || crate::host::HostFn::from_name(&r).is_some() - { - continue; - } - out.push( - Diagnostic::new( - path, - span, - format!( - "描述引用了不存在的实体:`{r}` —— 本段实现没有用到它,模块里也没有定义" - ), - ) - .with_code("label.ref_dangling") - .with_severity(Severity::Error) - .with_doc_quote(site.label.clone()) - .with_suggestion(format!( - "检查是否改名/删除;若只是措辞,把 `{r}` 的反引号去掉或改写描述" - )), - ); - } - } - out -} - -#[cfg(test)] -mod tests { - use super::refs; - - #[test] - fn refs_extracts_backticked_names() { - assert_eq!(refs("按 `税率` 计算"), vec!["税率".to_string()]); - } - - #[test] - fn refs_multiple_and_skips_prose() { - assert_eq!( - refs("用 `a` 和 `b`,但 plain words 不算"), - vec!["a".to_string(), "b".to_string()] - ); - } - - #[test] - fn refs_none_and_unmatched_backtick() { - assert!(refs("纯口语描述").is_empty()); - // Unmatched trailing backtick: ignore, do not panic. - assert!(refs("半截 `名字").is_empty()); - // Empty ticks are not refs. - assert!(refs("空 `` 引号").is_empty()); - } -} - -// --------------------------------------------------------------------------- -// M9: 两级词表检索(built-in groups = 默认/范例;`--grep` = 调用方自定义) -// --------------------------------------------------------------------------- - -/// One built-in keyword group. `` M9 -/// -/// The table is **data**, not syntax: it seeds the default query -/// (`marqdo labels pending`) and gives LLMs a stable vocabulary; any project can -/// override or extend it at the call site with `--grep`. -pub struct WordGroup { - pub name: &'static str, - pub words: &'static [&'static str], -} - -/// Built-in groups (v1). Extending this table never changes the grammar. -pub const BUILTIN_GROUPS: &[WordGroup] = &[ - WordGroup { - name: "未完成", - words: &[ - "待开发", "未开发", "开发中", "未实现", "待实现", "未接", "接口未接", "TODO", - ], - }, - WordGroup { - name: "假数据", - words: &["模拟", "假数据", "桩", "占位", "stub", "mock"], - }, - WordGroup { - name: "示例", - words: &["示例", "样例", "demo"], - }, - WordGroup { - name: "实验", - words: &["实验", "试验", "experimental"], - }, - WordGroup { - name: "废弃", - words: &["废弃", "弃用", "deprecated"], - }, - WordGroup { - name: "待校验", - words: &["待校验", "未验证", "待确认"], - }, -]; - -/// Groups that count as "pending" (default query for `labels pending`). -pub const PENDING_GROUPS: &[&str] = &["未完成", "假数据"]; - -/// Expand group names into their words; unknown names are ignored. -pub fn group_words(names: &[&str]) -> Vec { - let mut out = Vec::new(); - for g in BUILTIN_GROUPS { - if names.iter().any(|n| *n == g.name) { - out.extend(g.words.iter().map(|w| w.to_string())); - } - } - out -} - -/// Split a `--grep` value (`a,b` / `a,b`) into words. -pub fn parse_words(spec: &str) -> Vec { - spec.split([',', ',']) - .map(|w| w.trim()) - .filter(|w| !w.is_empty()) - .map(|w| w.to_string()) - .collect() -} - -/// Words that hit `label` (substring, ASCII case-insensitive). `` M9 -pub fn matched_words(label: &str, words: &[String]) -> Vec { - let hay = label.to_lowercase(); - let mut out = Vec::new(); - for w in words { - if w.is_empty() { - continue; - } - if hay.contains(&w.to_lowercase()) { - out.push(w.clone()); - } - } - out -} - -/// One search hit: where, what the label says, which words matched. -#[derive(Debug, Clone)] -pub struct Hit { - pub site: OcclusionSite, - pub words: Vec, -} - -/// Search every occlusion whose label matches any of `words`. -pub fn search(module: &Module, words: &[String]) -> Vec { - let mut out = Vec::new(); - for site in collect(module) { - let words = matched_words(&site.label, words); - if !words.is_empty() { - out.push(Hit { site, words }); - } - } - out -} - -// --------------------------------------------------------------------------- -// M6 (T1): session-scoped staleness — compare before/after edits in memory. -// --------------------------------------------------------------------------- - -/// One occlusion whose payload changed while its label stayed the same. -#[derive(Debug, Clone)] -pub struct StaleItem { - pub label: String, - /// 1-based line in the **new** source. - pub line: u32, - /// Rendered payload before the edit. - pub code_past: String, - /// Rendered payload after the edit. - pub code_now: String, -} - -/// In-process fingerprint of a payload. Only used to compare two versions parsed -/// by the *same* process, so a stable cross-version format is unnecessary. -fn payload_fingerprint(payload: &Option>) -> String { - match payload { - Some(e) => format!("{e:?}"), - None => "".to_string(), - } -} - -fn render_payload(payload: &Option>) -> String { - match payload { - Some(e) => { - #[cfg(feature = "view")] - { - crate::view::expr_display(e) - } - #[cfg(not(feature = "view"))] - { - format!("{e:?}") - } - } - None => String::new(), - } -} - -/// Compare two versions of a document and return occlusions whose **payload** -/// changed but whose **label** did not. Matching is by `(label, occurrence)`, so -/// moving code around does not produce false positives. -pub fn compare(before: &Module, after: &Module) -> Vec { - use std::collections::HashMap; - - let before_sites = collect(before); - let after_sites = collect(after); - - // Group by label → ordered occurrences. - let mut past: HashMap<&str, Vec<&OcclusionSite>> = HashMap::new(); - for s in &before_sites { - past.entry(s.label.as_str()).or_default().push(s); - } - - let mut seen: HashMap<&str, usize> = HashMap::new(); - let mut out = Vec::new(); - for site in &after_sites { - let idx = seen.entry(site.label.as_str()).or_insert(0); - let occurrence = *idx; - *idx += 1; - let Some(old) = past.get(site.label.as_str()).and_then(|v| v.get(occurrence)) else { - continue; // brand-new label: no history, nothing to compare - }; - if old.payload_fp == site.payload_fp { - continue; - } - out.push(StaleItem { - label: site.label.clone(), - line: site.line, - code_past: old.payload_src.clone(), - code_now: site.payload_src.clone(), - }); - } - out -} - -/// Session accumulator for `session.summary` (`` M6). -#[derive(Debug, Default, Clone)] -pub struct SessionSummary { - pub stale_seen: usize, - pub fixed: usize, - pub items: Vec, -} - -impl SessionSummary { - /// Record one round's comparison; returns the number of *newly* seen labels. - pub fn record(&mut self, stale: &[StaleItem]) -> usize { - let now: Vec = stale.iter().map(|s| s.label.clone()).collect(); - let mut newly = 0; - for label in &now { - if !self.items.contains(label) { - self.items.push(label.clone()); - self.stale_seen += 1; - newly += 1; - } - } - // Labels that were outstanding and are no longer stale are considered fixed. - let still: Vec = self - .items - .iter() - .filter(|l| now.contains(l)) - .cloned() - .collect(); - self.fixed += self.items.len() - still.len(); - self.items = still; - newly - } -} - -// --------------------------------------------------------------------------- -// M5: implicit occlusion — the narrative paragraph above a `>` call is its -// description. Only falsifiable claims (backticked refs) are checked, so -// ordinary prose never produces noise. -// --------------------------------------------------------------------------- - -/// A `>` statement call with the identifiers it mentions. -#[derive(Debug, Clone)] -pub struct CallSite { - pub line: u32, - pub idents: std::collections::HashSet, -} - -/// Collect `>` call statements (recursively). -pub fn call_sites(module: &Module) -> Vec { - fn walk_fun(f: &Function, out: &mut Vec) { - for s in &f.body { - walk_stmt(s, out); - } - for c in &f.children { - walk_fun(c, out); - } - } - fn walk_stmt(stmt: &Stmt, out: &mut Vec) { - match stmt { - Stmt::Call { call, span } => { - let mut idents = std::collections::HashSet::new(); - idents.insert(call.callee.clone()); - if let Some(p) = &call.path { - for seg in p { - idents.insert(seg.clone()); - } - } - if let Some(r) = &call.receiver { - idents.insert(r.clone()); - } - for a in &call.args { - match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => { - payload_idents(e, &mut idents) - } - } - } - out.push(CallSite { - line: span.line, - idents, - }); - } - Stmt::Branch { arms, .. } => { - for arm in arms { - for s in &arm.body { - walk_stmt(s, out); - } - } - } - Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { - for s in body { - walk_stmt(s, out); - } - } - Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { - // Nested calls inside expressions are not `>` statements. - let _ = value; - } - } - } - let mut out = Vec::new(); - for f in &module.functions { - walk_fun(f, &mut out); - } - out -} - -/// The narrative paragraph immediately above `line` (1-based), if any. -/// -/// A paragraph is a run of non-blank lines directly above; blank line ends it. -/// Structural lines (`#`, `**`, `>`, `-`, `|`, digits) are not prose. -fn paragraph_above(lines: &[&str], line: u32) -> Option { - let idx = (line as usize).checked_sub(2)?; // line-1 → 0-based index of the previous line - let mut collected: Vec<&str> = Vec::new(); - let mut i = idx as isize; - // People write `paragraph`, one blank line, then the `>` call (blockquote). - // Allow exactly one blank separator; a second blank ends the description. - if i >= 0 && lines[i as usize].trim().is_empty() { - i -= 1; - } - while i >= 0 { - let raw = lines[i as usize]; - let t = raw.trim(); - if t.is_empty() { - break; - } - let first = t.chars().next().unwrap_or(' '); - let structural = matches!(first, '#') - || t.starts_with("**") - || t.starts_with('>') - || t.starts_with('-') - || t.starts_with('|') - || t.starts_with("```") - || first.is_ascii_digit(); - if structural { - break; - } - collected.push(raw); - i -= 1; - } - if collected.is_empty() { - None - } else { - collected.reverse(); - Some(collected.join("\n")) - } -} - -/// True when a backticked ref looks like an *entity name* rather than prose. -/// -/// Prose often backticks shapes (`{ path, kind }`), flags (`source=`), or -/// headings (`## open`); those must not be treated as claims. `` M5 -fn is_entity_ref(s: &str) -> bool { - if s.is_empty() { - return false; - } - let mut chars = s.chars(); - let first = chars.next().unwrap(); - if first.is_ascii_digit() { - return false; - } - let ok_first = first.is_ascii_alphabetic() || first == '_' || !first.is_ascii(); - let ok_rest = s.chars().all(|c| { - c.is_ascii_alphanumeric() || c == '_' || c == '.' || (!c.is_ascii() && !c.is_whitespace()) - }); - ok_first && ok_rest -} - -/// Implicit-occlusion diagnostics for `>` calls. `` M5 -/// -/// The paragraph above a call is its description; backticked refs there must be -/// mentioned by the call (or resolve in the module). No paragraph / no refs → -/// silent, which keeps the check at zero noise on ordinary code. -pub fn check_implicit( - module: &Module, - source: &str, - path: Option<&std::path::Path>, -) -> Vec { - let mut out = Vec::new(); - let symbols = module_symbols(module); - let lines: Vec<&str> = source.lines().collect(); - for site in call_sites(module) { - let Some(para) = paragraph_above(&lines, site.line) else { - continue; - }; - for r in refs(¶).into_iter().filter(|r| is_entity_ref(r)) { - if site.idents.contains(&r) - || symbols.contains(&r) - || crate::host::HostFn::from_name(&r).is_some() - { - continue; - } - out.push( - Diagnostic::new( - path, - Span::new(site.line, 1), - format!("调用上方的描述提到 `{r}`,但这次调用没有用到它"), - ) - .with_code("label.implicit_stale") - .with_severity(Severity::Warning) - .with_doc_quote(para.replace('\n', " ")) - .with_suggestion(format!( - "确认描述是否已过期:把 `{r}` 换成现在的参数名,或修改调用" - )), - ); - } - } - out -} diff --git a/src/lex/mod.rs b/src/lex/mod.rs deleted file mode 100755 index 2e499d5..0000000 --- a/src/lex/mod.rs +++ /dev/null @@ -1,797 +0,0 @@ -//! Line classification (M1) — no Flex. -//! -//! Narrative comments are paragraph-scoped: blank lines separate paragraphs. -//! After a comment line, subsequent non-blank lines stay comments until a blank -//! (so mid-paragraph lines starting with `` ` `` are not treated as code). - -use std::fmt; - -/// Kind of a source line after skipping leading indentation for the test. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum LineKind { - Blank, - Comment, - /// Jupyter-style persisted output (``). - Writeback, - Code, -} - -impl fmt::Display for LineKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - LineKind::Blank => write!(f, "Blank"), - LineKind::Comment => write!(f, "Comment"), - LineKind::Writeback => write!(f, "Writeback"), - LineKind::Code => write!(f, "Code"), - } - } -} - -/// One classified source line (1-based line number). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ClassifiedLine { - pub line_no: u32, - pub kind: LineKind, - pub text: String, -} - -/// Characters that start a code line when they appear as the first non-ws char. -fn is_code_starter(c: char) -> bool { - matches!( - c, - '#' | '*' | '>' | '+' | '-' | '|' | '~' | '$' - ) || c.is_ascii_digit() -} - -/// Whether `**inner**` should execute (assign / call / expr), not soft emphasis. -pub fn looks_like_bold_code(inner: &str) -> bool { - let t = inner.trim(); - if t.is_empty() { - return false; - } - if t.contains('=') || t.starts_with('>') { - return true; - } - if t.chars() - .any(|c| matches!(c, '+' | '-' | '*' | '/' | '(' | ')' | '[' | ']')) - { - return true; - } - let parts: Vec<&str> = t.split_whitespace().collect(); - if parts.len() >= 2 { - return parts[1..].iter().any(|p| { - p.contains('=') - || p.starts_with('"') - || p.starts_with('\'') - || p.starts_with('`') - || p.chars().all(|c| c.is_ascii_digit()) - || (p.contains('.') - && p.chars() - .filter(|c| *c != '.') - .all(|c| c.is_ascii_digit())) - }); - } - false -} - -/// Whole-line backtick bind `` `name` = … `` (empty RHS / fence / table OK). -/// -/// Narrative decls are **not** binds: -/// - `` `捕获=True` 时… `` (`=` inside ticks) -/// - `` `n`,我们… `` (no `=` after ticks) -/// - `` `礼貌`=False 时… `` (glued default + trailing prose; same shape as prose Decl) -fn looks_like_backtick_assign(trimmed: &str) -> bool { - let t = trimmed.trim(); - if !t.starts_with('`') { - return false; - } - let rest = &t[1..]; - let Some(end) = rest.find('`') else { - return false; - }; - let name = &rest[..end]; - if name.is_empty() || !is_backtick_bind_name(name) { - return false; - } - let after_tick = &rest[end + 1..]; - let after = after_tick.trim_start(); - if !after.starts_with('=') { - return false; - } - // Glued `` `name`=default …prose `` → Decl, not assign (prose.rs default terminator). - let glued = after_tick.starts_with('='); - if glued { - let stripped = &after[1..]; - let def_end = stripped - .find(|c: char| { - c.is_whitespace() - || matches!(c, ',' | '。' | ';' | '、' | ',' | ';' | '*' | '`') - }) - .unwrap_or(stripped.len()); - if !stripped[def_end..].trim_start().is_empty() { - return false; - } - } - true -} - -fn is_backtick_bind_name(name: &str) -> bool { - let mut chars = name.chars(); - let Some(first) = chars.next() else { - return false; - }; - if !(first.is_alphabetic() || first == '_' || !first.is_ascii()) { - return false; - } - chars.all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()) -} - -/// `*` / `**` lines that are Marqdo executable (statement / return / else), not narrative Markdown. -/// -/// Closing `*` / `**` must not be taken from inside `` `…` `` or `"…"` (GAP-06/07 nested markers). -fn is_marqdo_star_line(trimmed: &str) -> bool { - // Empty italic return (v0.3) or else `*` / empty returns. - if trimmed == "*" || trimmed == "**" || trimmed == "****" { - return true; - } - if trimmed.starts_with("**") { - if trimmed.trim() == "** **" { - return true; - } - if matching_bold_close(trimmed).is_some() { - return true; - } - // D9: a bold-starting line whose string literal is never closed has no - // findable closing `**` -- the scanner stays "inside the string" forever. - // Classifying it as Comment would silently drop the line; treat it as - // Code so the parser can report `unterminated " string`. - return has_unterminated_string(trimmed); - } - if !trimmed.starts_with('*') || trimmed.len() < 2 { - return false; - } - matching_italic_close(trimmed).is_some() -} - -/// True when `line` contains an odd number of unescaped double quotes, -/// i.e. a string literal that is opened but never closed. -/// -/// Used only by [`is_marqdo_star_line`] to keep a malformed bold line in the -/// Code class so the parser surfaces the error (D9). Prose lines never reach -/// here -- they do not start with `**`. -pub fn has_unterminated_string(line: &str) -> bool { - let bytes = line.as_bytes(); - let mut i = 0usize; - let mut count = 0usize; - while i < bytes.len() { - match bytes[i] { - b'\\' => i += 2, - b'"' => { - count += 1; - i += 1; - } - _ => i += 1, - } - } - count % 2 == 1 -} - -/// Closing `**` for a bold segment, skipping strings and backticks. -/// Returns the index within `trimmed` of the first `*` of the closing `**`. -/// When `require_eol`, the closing `**` must be the last non-ws on the line (whole-line code). -pub fn matching_bold_close(trimmed: &str) -> Option { - matching_bold_close_opts(trimmed, true) -} - -/// Like [`matching_bold_close`] but allows trailing text after the close (inline prose). -pub fn matching_bold_close_inline(trimmed: &str) -> Option { - matching_bold_close_opts(trimmed, false) -} - -// An occlusion label is prose: stars, quotes and backticks inside it are not -// statement/return delimiters. Payload nesting is tracked by the callers. -fn occlusion_payload_start(bytes: &[u8], start: usize) -> Option { - if bytes.get(start) != Some(&b'[') { - return None; - } - let mut i = start + 1; - while i < bytes.len() { - match bytes[i] { - b'\\' => i += 2, - b']' => return (bytes.get(i + 1) == Some(&b'(')).then_some(i + 1), - b'\n' | b'\r' => return None, - _ => i += 1, - } - } - None -} - -fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option { - let Some(rest) = trimmed.strip_prefix("**") else { - return None; - }; - let bytes = rest.as_bytes(); - let mut i = 0usize; - let mut in_bt = false; - let mut in_str = false; - let mut nesting = Vec::new(); - while i + 1 < bytes.len() { - let c = bytes[i]; - if in_str { - if c == b'\\' && i + 1 < bytes.len() { - i += 2; - continue; - } - if c == b'"' { - in_str = false; - } - i += 1; - continue; - } - if in_bt { - if c == b'`' { - in_bt = false; - } - i += 1; - continue; - } - if c == b'[' { - if let Some(payload) = occlusion_payload_start(bytes, i) { - i = payload; - continue; - } - } - match c { - b'(' | b'[' | b'{' => { - nesting.push(match c { - b'(' => b')', - b'[' => b']', - _ => b'}', - }); - i += 1; - } - b')' | b']' | b'}' => { - if nesting.last() == Some(&c) { - nesting.pop(); - } - i += 1; - } - b'`' => { - in_bt = true; - i += 1; - } - b'"' => { - in_str = true; - i += 1; - } - b'*' if bytes[i + 1] == b'*' && nesting.is_empty() => { - let after = i + 2; - if !require_eol || rest[after..].trim().is_empty() { - return Some(2 + i); - } - i += 2; - } - _ => i += 1, - } - } - // Empty bold `****` handled by caller; `**` alone has no close inside rest. - if !require_eol && rest.is_empty() { - return None; - } - None -} - -/// Index of the closing `*` for a single-star segment. -pub fn matching_italic_close(trimmed: &str) -> Option { - matching_italic_close_opts(trimmed, true) -} - -/// Italic close allowing trailing prose after the closing `*`. -pub fn matching_italic_close_inline(trimmed: &str) -> Option { - matching_italic_close_opts(trimmed, false) -} - -fn matching_italic_close_opts(trimmed: &str, require_eol: bool) -> Option { - if trimmed.starts_with("**") { - return None; - } - let bytes = trimmed.as_bytes(); - let mut i = 1usize; // skip opening * - let mut in_bt = false; - let mut in_str = false; - let mut nesting = Vec::new(); - while i < bytes.len() { - let c = bytes[i]; - if in_str { - if c == b'\\' && i + 1 < bytes.len() { - i += 2; - continue; - } - if c == b'"' { - in_str = false; - } - i += 1; - continue; - } - if in_bt { - if c == b'`' { - in_bt = false; - } - i += 1; - continue; - } - if c == b'[' { - if let Some(payload) = occlusion_payload_start(bytes, i) { - i = payload; - continue; - } - } - match c { - b'(' | b'[' | b'{' => { - nesting.push(match c { - b'(' => b')', - b'[' => b']', - _ => b'}', - }); - i += 1; - } - b')' | b']' | b'}' => { - if nesting.last() == Some(&c) { - nesting.pop(); - } - i += 1; - } - b'`' => { - in_bt = true; - i += 1; - } - b'"' => { - in_str = true; - i += 1; - } - b'*' if nesting.is_empty() => { - if !require_eol || trimmed[i + 1..].trim().is_empty() { - return Some(i); - } - i += 1; - } - _ => i += 1, - } - } - None -} - -/// Headings / calls / finished star lines should escape a narrative paragraph (GAP-06/07 recovery). -fn breaks_comment_paragraph(trimmed: &str) -> bool { - if is_structural_code_line(trimmed) { - return true; - } - if trimmed.starts_with('#') || trimmed.starts_with('>') { - return true; - } - if is_marqdo_star_line(trimmed) { - return true; - } - // Branch arms / loops / params must not be swallowed after prose in an arm body. - if looks_like_ordered_list_item(trimmed) { - return true; - } - if trimmed.starts_with("- ") || trimmed.starts_with("-\t") || trimmed == "-" { - return true; - } - if trimmed.starts_with('+') { - return true; - } - if is_image_writeback_line(trimmed) { - return true; - } - false -} - -/// `![marqdo-out …](image-url)` — image writeback surface (see stdlib-writeback). -pub fn is_image_writeback_line(trimmed: &str) -> bool { - let t = trimmed.trim(); - let Some(rest) = t.strip_prefix("![") else { - return false; - }; - let Some(alt_end) = rest.find("](") else { - return false; - }; - let alt = rest[..alt_end].trim(); - alt.split_whitespace().any(|tok| tok == "marqdo-out") -} - -fn looks_like_ordered_list_item(trimmed: &str) -> bool { - let mut chars = trimmed.chars(); - let mut saw_digit = false; - while let Some(c) = chars.next() { - if c.is_ascii_digit() { - saw_digit = true; - continue; - } - if c == '.' && saw_digit { - return true; - } - return false; - } - false -} - -/// Classify a single logical line (no trailing newline required). -/// -/// This is the **paragraph-start** rule only. Prefer [`classify_source`] for -/// full-file classification (paragraph continuation). -pub fn classify_line(text: &str) -> LineKind { - let trimmed = text.trim_end_matches(['\r', '\n']); - if trimmed.chars().all(|c| c.is_whitespace()) { - return LineKind::Blank; - } - let trimmed = text.trim(); - let first = trimmed.chars().find(|c| !c.is_whitespace()); - match first { - None => LineKind::Blank, - Some('*') if !is_marqdo_star_line(trimmed) => LineKind::Comment, - Some('`') if looks_like_backtick_assign(trimmed) => LineKind::Code, - Some('`') => LineKind::Comment, - Some(c) if is_code_starter(c) => LineKind::Code, - Some(_) => LineKind::Comment, - } -} - -/// Classify every line of a source file (blank-line paragraph comments). -/// -/// Structural end markers (`---` / `***` / empty `****`) always stay Code and -/// break a comment paragraph, so frontmatter closers and function ends work -/// even when adjacent to narrative. -pub fn classify_source(source: &str) -> Vec { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = if source.is_empty() { - Vec::new() - } else { - source.lines().collect() - }; - - let mut out = Vec::with_capacity(lines.len()); - let mut in_comment_paragraph = false; - let mut in_math_fence = false; - let mut in_md_fence = false; - let mut in_writeback = false; - - for (i, text) in lines.into_iter().enumerate() { - let base = classify_line(text); - let trimmed = text.trim(); - let structural = is_structural_code_line(trimmed); - let kind = if in_writeback { - if trimmed.contains("-->") { - in_writeback = false; - } - LineKind::Writeback - } else if in_math_fence { - if trimmed == "$$" { - in_math_fence = false; - } - LineKind::Code - } else if in_md_fence { - // Markdown ``` fences are narrative / foreign sources — not Marqdo stmts. - if is_md_fence_line(trimmed) { - in_md_fence = false; - } - LineKind::Comment - } else if is_md_fence_opener(trimmed) { - in_md_fence = true; - in_comment_paragraph = false; - LineKind::Comment - } else if trimmed.starts_with("") { - in_writeback = false; - } - LineKind::Writeback - } else if is_image_writeback_line(trimmed) { - in_comment_paragraph = false; - LineKind::Writeback - } else { - match base { - LineKind::Blank => { - in_comment_paragraph = false; - LineKind::Blank - } - LineKind::Comment => { - in_comment_paragraph = true; - LineKind::Comment - } - LineKind::Code if structural || breaks_comment_paragraph(trimmed) => { - in_comment_paragraph = false; - LineKind::Code - } - LineKind::Code if in_comment_paragraph => LineKind::Comment, - LineKind::Writeback => LineKind::Writeback, - LineKind::Code => { - // Multi-line math fence opener (not same-line `$$…$$`). - if trimmed == "$$" { - in_math_fence = true; - } - LineKind::Code - } - } - }; - out.push(ClassifiedLine { - line_no: (i + 1) as u32, - kind, - text: text.to_string(), - }); - } - out -} - -fn is_md_fence_opener(trimmed: &str) -> bool { - trimmed.starts_with("```") - && !trimmed - .chars() - .skip_while(|c| *c == '`') - .all(|c| c.is_whitespace()) -} - -fn is_md_fence_line(trimmed: &str) -> bool { - trimmed.starts_with("```") -} - -/// Function-end / frontmatter HR or empty bold return — never swallowed by paragraphs. -fn is_structural_code_line(trimmed: &str) -> bool { - if trimmed.len() >= 3 - && (trimmed.chars().all(|c| c == '-') || trimmed.chars().all(|c| c == '*')) - { - return true; - } - false -} - -/// Human-readable dump for `--dump-lines`. -pub fn format_lines_dump(path: &str, lines: &[ClassifiedLine]) -> String { - let mut out = String::new(); - out.push_str(&format!("=== marqdo: lines ({path}) ===\n")); - for line in lines { - let preview = if line.text.len() > 80 { - format!("{}…", &line.text.chars().take(80).collect::()) - } else { - line.text.clone() - }; - match line.kind { - LineKind::Blank => { - out.push_str(&format!("{:4} {:7}\n", line.line_no, line.kind)); - } - _ => { - out.push_str(&format!( - "{:4} {:7} | {}\n", - line.line_no, line.kind, preview - )); - } - } - } - out.push_str("=== marqdo: end lines ===\n"); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ordered_arm_breaks_prose_paragraph() { - let src = "\ -# main\n\ -\n\ -1. `n` > 0\n\ - 此时我们 **打印 内容=\"正\"**\n\ -2. *\n\ - 否则 **打印 内容=\"非正\"**\n\ -"; - let lines = classify_source(src); - let l12 = lines.iter().find(|l| l.text.trim() == "2. *").expect("2. *"); - assert_eq!( - l12.kind, - LineKind::Code, - "else arm must stay Code after prose, got dump:\n{}", - format_lines_dump("t", &lines) - ); - } - - #[test] - fn blank_and_comment_and_code() { - assert_eq!(classify_line(""), LineKind::Blank); - assert_eq!(classify_line(" "), LineKind::Blank); - assert_eq!(classify_line("hello world"), LineKind::Comment); - assert_eq!(classify_line(" 中文说明"), LineKind::Comment); - assert_eq!(classify_line("> print text=hi"), LineKind::Code); - assert_eq!(classify_line("# main"), LineKind::Code); - assert_eq!(classify_line("*`x` = 1*"), LineKind::Code); - assert_eq!(classify_line("**ret**"), LineKind::Code); - assert_eq!(classify_line("+ `x` > 0"), LineKind::Code); - assert_eq!(classify_line("- item"), LineKind::Code); - assert_eq!(classify_line("1. arm"), LineKind::Code); - assert_eq!(classify_line("| a |"), LineKind::Code); - assert_eq!(classify_line("`x` = 1"), LineKind::Code); - assert_eq!( - classify_line("`捕获=True` 时返回映射。"), - LineKind::Comment, - "prose decl / narrative, not backtick assign" - ); - assert_eq!( - classify_line("`n`,我们执行操作"), - LineKind::Comment, - "leading decl in narrative" - ); - assert_eq!(classify_line("`礼貌`=False"), LineKind::Code); - assert_eq!( - classify_line("`礼貌`=False 时用短称呼。"), - LineKind::Comment, - "glued default + trailing prose is Decl" - ); - assert_eq!( - classify_line("`礼貌` = False"), - LineKind::Code, - "spaced = is backtick assign" - ); - } - - #[test] - fn narrative_bold_in_comment_paragraph() { - let src = "说明如下:\n\n**强调信息**是什么什么\n\n> print text=ok\n"; - let lines = classify_source(src); - assert_eq!(lines[0].kind, LineKind::Comment); - assert_eq!(lines[1].kind, LineKind::Blank); - assert_eq!(lines[2].kind, LineKind::Comment, "bold prose is comment"); - assert_eq!(lines[3].kind, LineKind::Blank); - assert_eq!(lines[4].kind, LineKind::Code); - } - - #[test] - fn writeback_block_classified() { - let src = "*`x` = 1*\n\n"; - let lines = classify_source(src); - assert_eq!(lines[0].kind, LineKind::Code); - assert_eq!(lines[1].kind, LineKind::Writeback); - assert_eq!(lines[2].kind, LineKind::Writeback); - assert_eq!(lines[3].kind, LineKind::Writeback); - } - - #[test] - fn image_writeback_line_classified() { - assert!(is_image_writeback_line("![marqdo-out](a.svg)")); - assert!(is_image_writeback_line("![marqdo-out ok](plots/x.png)")); - assert!(!is_image_writeback_line("![plot](a.svg)")); - let src = "# main\n\n**x = 1**\n![marqdo-out](out.svg)\n\n> print text=x\n"; - let lines = classify_source(src); - let img = lines.iter().find(|l| l.text.contains("marqdo-out]")).unwrap(); - assert_eq!(img.kind, LineKind::Writeback, "{:?}", lines); - } - - #[test] - fn paragraph_comment_keeps_backtick_continuation() { - let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n"; - let lines = classify_source(src); - assert_eq!(lines[0].kind, LineKind::Comment); - assert_eq!(lines[1].kind, LineKind::Comment); - assert_eq!(lines[2].kind, LineKind::Blank); - assert_eq!(lines[3].kind, LineKind::Code); - } - - #[test] - fn frontmatter_closing_hr_stays_code() { - let src = "---\ntitle: x\n---\n\n# main\n"; - let lines = classify_source(src); - assert_eq!(lines[0].kind, LineKind::Code); - assert_eq!(lines[1].kind, LineKind::Comment); - assert_eq!(lines[2].kind, LineKind::Code); - assert_eq!(lines[2].text.trim(), "---"); - } - - #[test] - fn classify_hello_fixture() { - let src = include_str!("../../tests/structure/hello.mq.md"); - let lines = classify_source(src); - assert!(lines.iter().any(|l| l.kind == LineKind::Comment)); - assert!(lines.iter().any(|l| l.kind == LineKind::Code)); - } - - #[test] - fn unterminated_quote_inside_bold_is_code_not_comment() { - // D9: "**s = \"abc" has an unclosed string. Classification must keep it - // as Code so the parser reports "unterminated \" string" instead of - // silently demoting the line to narration. - let lines = classify_source("**s = \"abc\n"); - let code = lines.iter().find(|l| l.text.contains("abc")); - assert!( - matches!(code.map(|l| l.kind), Some(LineKind::Code)), - "expected Code (so parser reports the error), got {lines:?}" - ); - } - - #[test] - fn balanced_quote_inside_bold_still_code() { - let lines = classify_source("**s = \"abc\"**\n"); - let code = lines.iter().find(|l| l.text.contains("abc")); - assert!(matches!(code.map(|l| l.kind), Some(LineKind::Code))); - } - - #[test] - fn prose_with_quotes_stays_comment() { - // Narration that merely mentions quotes must stay narration. - let lines = classify_source("他说 \"你好\",然后走了。\n"); - assert!(matches!(lines.first().map(|l| l.kind), Some(LineKind::Comment))); - } - - #[test] - fn prose_bold_emphasis_with_quote_stays_comment() { - // **强调** with a stray quote in surrounding prose is still narration. - let lines = classify_source("这一句有 \" 引号但不是代码。\n"); - assert!(matches!(lines.first().map(|l| l.kind), Some(LineKind::Comment))); - } - - #[test] - fn math_fence_body_stays_code() { - let lines = classify_source("`f` =\n$$\nx^2 - 2\n$$\n"); - assert!( - lines - .iter() - .all(|l| l.kind == LineKind::Code || l.kind == LineKind::Blank), - "expected fence body as Code, got {lines:?}" - ); - } - - #[test] - fn star_line_classification_is_star_terminated() { - // A `*…*` Marqdo statement line must END with `*` to be treated as code. - // If it accidentally ends with a backtick (e.g. `table="t"`), the line - // falls back to narrative Comment — but later executable lines recover - // (GAP-06/07: do not swallow the rest of a `##` body). - let star_term = "*c = > `store`.count table=\"t\"*"; - assert!( - is_marqdo_star_line(star_term), - "star-terminated assignment must be code" - ); - assert_eq!(classify_line(star_term), LineKind::Code); - - let nested_bt = "*code = > sys.exec cmd=\"python3\" args=`args`*"; - assert!( - is_marqdo_star_line(nested_bt), - "args=`args`* must still be a star line" - ); - let nested_json = "*args = > json.parse text=[\"scripts/legacy/web_search.py\"]*"; - assert!( - is_marqdo_star_line(nested_json), - "text=[…] * must still be a star line" - ); - assert!( - is_marqdo_star_line("*x = > f text=`a*b`*"), - "* inside backticks must not steal the closer" - ); - - let backtick_term = "*c = > `store`.count table=\"t\"`"; - assert!( - !is_marqdo_star_line(backtick_term), - "backtick-terminated assignment must NOT be marqdo star line" - ); - assert_eq!(classify_line(backtick_term), LineKind::Comment); - - // Bad terminator → comment, but following `>` / `*…*` escape the paragraph. - let src = "> `store`.insert table=t rows=`数据`\n\n*c = > `store`.count table=\"t\"`\n> print text=count1-done\n*y = 1*\n"; - let lines = classify_source(src); - assert_eq!(lines[2].kind, LineKind::Comment, "bad terminator → comment"); - assert_eq!(lines[3].kind, LineKind::Code, "call recovers after bad line"); - assert_eq!(lines[4].kind, LineKind::Code, "assign recovers after bad line"); - } -} - -#[cfg(test)] -mod inline_occlusion_boundaries { - use super::*; - #[test] - fn prose_stars_and_payload_products_keep_the_real_return_boundary() { - let source = r#"*[multiply x*y and keep "raw" text](2 * (3 + 1))* after the result"#; - assert_eq!(matching_italic_close_inline(source), source.find("* after")); - let source = r#"**answer = [render **literal** marker](helper(text="**", value=(2 * 3)))** then continue"#; - assert_eq!(matching_bold_close_inline(source), source.find("** then")); - } -} diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100755 index c1e06cc..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,573 +0,0 @@ -//! Marqdo reference interpreter (Phase I + M5 bytecode prototype). -//! -//! Pipeline: load → line classify → parse → tree-walk eval | bytecode VM. -//! CLI also offers `view` for AST-backed browsing. - -pub mod aliases; -mod arguments; -pub mod artifact; -pub mod label; -pub mod migrate; -pub mod ast; -pub mod binding; -pub mod browser_session; -pub mod builtin; -pub mod bytecode; -pub mod call; -pub mod call_session; -pub mod capture; -pub mod narrative_ratio; -#[cfg(feature = "cli")] -pub mod catalog; -// `sema::ir` unconditionally emits `proof-index.json` and -// `proof-obligations.json` through this module, so it is part of the core -// compiler rather than the CLI surface. Gating it on `cli` broke library -// consumers that disable default features (E0433). -pub mod knowledge; -pub mod check; -pub mod contract; -pub mod debug; -pub mod diagnostics; -pub mod document_extract; -pub mod embedded_lib; -#[cfg(feature = "cli")] -pub mod ext_cli; -#[cfg(all(feature = "cli", feature = "net-host"))] -pub mod ext_fetch; -pub mod foreign; -pub mod formula; -pub mod host; -pub mod inherit; -pub mod input_feed; -pub mod interp; -pub mod lex; -pub mod linalg_ops; -pub mod load; -pub mod mlsp; -pub mod runtime; -pub mod workbench; -pub mod parse; -pub mod project; -pub mod prove; -pub mod repair; -pub mod sema; -pub mod value; -#[cfg(all(test, feature = "exec-host"))] -mod source_refinement_tests; -#[cfg(all(test, feature = "exec-host"))] -mod application_tests; -#[cfg(all(test, feature = "exec-host"))] -mod causal_replay_tests; -#[cfg(test)] -mod source_map_tests; -#[cfg(test)] -mod frontend_elaboration_tests; -#[cfg(feature = "net-host")] -pub mod version_check; -#[cfg(feature = "view")] -pub mod view; -#[cfg(feature = "cli")] -pub mod wasm_cli; - -use std::path::Path; - -use anyhow::{bail, Result}; - -use crate::host::{flush_auto_plots, HostCaps, HostContext}; -use crate::ast::format_ast_dump; -use crate::debug::format_lines_dump_v03; -use crate::bytecode::{compile_module, Vm}; -use crate::capture::RunCapture; -use crate::interp::Interpreter; -use crate::lex::classify_source; -use crate::load::{load_module_from_source, load_module_with_ctx}; -use crate::binding::{cwd_for_path, BindingContext}; - -pub use browser_session::{value_as_json, BrowserSession}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum Backend { - #[default] - Tree, - Bytecode, -} - -impl Backend { - pub fn parse(s: &str) -> Result { - match s { - "tree" => Ok(Self::Tree), - "bytecode" | "bc" => Ok(Self::Bytecode), - other => bail!("unknown backend `{other}` (expected tree|bytecode)"), - } - } -} - -/// Options for a single `run` / dump invocation. -#[derive(Debug, Clone)] -pub struct RunOptions { - pub dump_lines: bool, - pub dump_tokens: bool, - pub dump_ast: bool, - pub dump_sema: bool, - pub dump_bytecode: bool, - pub trace_eval: bool, - pub backend: Backend, - /// Preset lines consumed by `input` (from `--stdin-file` or view). - pub stdin_lines: Vec, - pub allow_fs_write: bool, - pub allow_exec: bool, - pub allow_net: bool, - /// Native `plugin.load` (default true for CLI; false inside `sandbox.run`). - pub allow_plugin: bool, - /// Exposed via `host_args` / `args`. - pub argv: Vec, - /// Override filesystem sandbox root (default: source file's directory). - pub fs_root: Option, - /// Sleep clamp when capturing (None = host default; view export uses `Some(0)`). - pub sleep_limit_ms: Option, - /// When set, write `# main` return value as JSON to this path (file subtasks). - pub emit_result: Option, - /// CLI `--bind KEY=VALUE` pairs for Artifact Metadata Binding (`arg` + overlay). - pub binds: Vec<(String, String)>, - /// Attach CoW session for `ext/ai/sandbox` nested runs. - pub sandbox_session: Option, - /// Isolated worker: call `lib.member` on the site entry instead of `# main`. - pub call_lib_path: Option, - /// JSON object of named args for [`Self::call_lib_path`] (file path or inline). - pub args_json: Option, -} - -impl Default for RunOptions { - fn default() -> Self { - Self { - dump_lines: false, - dump_tokens: false, - dump_ast: false, - dump_sema: false, - dump_bytecode: false, - trace_eval: false, - backend: Backend::default(), - stdin_lines: Vec::new(), - allow_fs_write: true, - allow_exec: true, - allow_net: true, - allow_plugin: true, - argv: Vec::new(), - fs_root: None, - sleep_limit_ms: None, - emit_result: None, - binds: Vec::new(), - sandbox_session: None, - call_lib_path: None, - args_json: None, - } - } -} - -impl RunOptions { - pub fn dump_all() -> Self { - Self { - dump_lines: true, - dump_tokens: true, - dump_ast: true, - dump_sema: true, - dump_bytecode: true, - trace_eval: true, - ..Self::default() - } - } - - pub fn any_dump(&self) -> bool { - self.dump_lines - || self.dump_tokens - || self.dump_ast - || self.dump_sema - || self.dump_bytecode - || self.trace_eval - } - - pub fn host_caps(&self) -> HostCaps { - HostCaps { - fs_write: self.allow_fs_write, - exec: self.allow_exec, - net: self.allow_net, - plugin: self.allow_plugin, - } - } -} - -/// Run a `.mq.md` program (prints to real stdout). -pub fn run_file(path: &Path, opts: &RunOptions) -> Result { - let source = std::fs::read_to_string(path) - .map_err(|e| anyhow::anyhow!("failed to read {}: {e}", path.display()))?; - - if source.trim().is_empty() { - bail!("{} is empty", path.display()); - } - - let stdin_lines = crate::input_feed::effective_stdin(&source, &opts.stdin_lines); - let path_label = path.display().to_string(); - - if opts.dump_lines { - let lines = classify_source(&source); - print!("{}", format_lines_dump_v03(&path_label, &lines)); - } - if opts.dump_tokens { - println!("=== marqdo: tokens ({path_label}) ==="); - println!("(fine-grained tokens not implemented yet — use --dump-lines)"); - println!("=== marqdo: end tokens ==="); - } - - let bind_ctx = BindingContext::from_binds(&opts.binds, cwd_for_path(Some(path))); - let module = load_module_with_ctx(path, &bind_ctx)?; - - if opts.dump_ast { - print!("{}", format_ast_dump(&path_label, &module)); - } - if opts.dump_sema { - println!("=== marqdo: sema ({path_label}) ==="); - println!( - "functions: {:?}", - module - .functions - .iter() - .map(|f| f.name.as_str()) - .collect::>() - ); - println!("imports: {:?}", module.imports); - println!("metadata: {:?}", module.metadata.iter().map(|(k, v)| (k, v.as_display())).collect::>()); - println!("=== marqdo: end sema ==="); - } - - if opts.call_lib_path.is_none() { - if let Some(value) = crate::artifact::declaration_summary(&module) { - emit_result_file(opts, &value)?; - return Ok(0); - } - } - - match opts.backend { - Backend::Tree => { - let mut host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone()); - host.set_entry_source(Some(path), &source); - host.entry_metadata = module.metadata.clone(); - if let Some(root) = &opts.fs_root { - host.fs_root = Some(root.clone()); - host.cwd = root.clone(); - } - let mut interp = Interpreter::new(Some(path), opts.trace_eval) - .with_stdin(stdin_lines.clone()) - .with_host(host); - if opts.trace_eval { - eprintln!("=== marqdo: trace-eval ({path_label}) ==="); - } - let value = if let Some(lib_path) = &opts.call_lib_path { - run_call_lib_path(&mut interp, &module, lib_path, opts)? - } else { - interp.run_module(&module)? - }; - if opts.trace_eval { - eprintln!("=== marqdo: end trace-eval ==="); - } - let plots = interp.take_plots(); - flush_auto_plots(Some(path), &plots).map_err(|e| anyhow::anyhow!(e))?; - emit_result_file(opts, &value)?; - } - Backend::Bytecode => { - let program = compile_module(Some(path), &module)?; - if opts.dump_bytecode { - print!("{}", program.disassemble()); - } - let mut host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone()); - host.set_entry_source(Some(path), &source); - host.entry_metadata = module.metadata.clone(); - if let Some(root) = &opts.fs_root { - host.fs_root = Some(root.clone()); - host.cwd = root.clone(); - } - let bound_call = if let Some(lib_path) = &opts.call_lib_path { - let named = named_call_args(opts)?; - let segments: Vec = lib_path - .split('.') - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .collect(); - let (lib, fun) = crate::interp::locate_import_function(&module, &segments) - .map_err(|m| anyhow::anyhow!(m))?; - let mut binder = Interpreter::with_capture(Some(path), false).with_host( - HostContext::for_capture(Some(path), opts.host_caps()), - ); - let bound = binder.bind_external_args(lib, fun, &named)?; - Some((lib_path.clone(), bound)) - } else { - None - }; - let mut vm = Vm::new(Some(path)) - .with_stdin(stdin_lines) - .with_trace(opts.trace_eval) - .with_host(host); - if opts.trace_eval { - eprintln!("=== marqdo: trace-eval ({path_label}) ==="); - } - let value = if let Some((lib_path, bound)) = bound_call { - let key: Vec = lib_path - .split('.') - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .collect(); - let idx = program.path_index.get(&key).copied().ok_or_else(|| { - anyhow::anyhow!( - "bytecode: `{lib_path}` did not compile to a function; refusing to run the program entry" - ) - })?; - vm.call_function(&program, idx, &bound)? - } else { - vm.run(&program)? - }; - if opts.trace_eval { - eprintln!("=== marqdo: end trace-eval ==="); - } - let plots = vm.take_plots(); - flush_auto_plots(Some(path), &plots).map_err(|e| anyhow::anyhow!(e))?; - emit_result_file(opts, &value)?; - } - } - - // dump bytecode even on tree backend if requested - if opts.backend == Backend::Tree && opts.dump_bytecode { - let program = compile_module(Some(path), &module)?; - print!("{}", program.disassemble()); - } - - Ok(0) -} - -/// Worker mode: resolve `lib.member` on the loaded site module (imports already wired). -fn run_call_lib_path( - interp: &mut Interpreter, - module: &crate::ast::Module, - lib_path: &str, - opts: &RunOptions, -) -> Result { - let args_val = load_args_json(opts)?; - // Keep site_module pinned for the duration of the lib call (plugins may re-enter). - let value = interp - .run_site_lib_path(module, lib_path, args_val.as_ref()) - .map_err(|e| anyhow::anyhow!(e))?; - Ok(value) -} - -fn named_call_args(opts: &RunOptions) -> Result> { - let Some(value) = load_args_json(opts)? else { - return Ok(Vec::new()); - }; - match value { - crate::value::Value::Map(pairs) => Ok(pairs), - _ => bail!("args-json must be a JSON object"), - } -} - -fn load_args_json(opts: &RunOptions) -> Result> { - let Some(path) = &opts.args_json else { - return Ok(None); - }; - let text = if path.as_os_str() == "-" { - use std::io::Read; - let mut buf = String::new(); - std::io::stdin() - .read_to_string(&mut buf) - .map_err(|e| anyhow::anyhow!("args-json stdin: {e}"))?; - buf - } else { - std::fs::read_to_string(path) - .map_err(|e| anyhow::anyhow!("args-json {}: {e}", path.display()))? - }; - if text.trim().is_empty() { - return Ok(None); - } - let json: serde_json::Value = - serde_json::from_str(&text).map_err(|e| anyhow::anyhow!("args-json parse: {e}"))?; - let v = crate::host::json::json_to_value(&json).map_err(|e| anyhow::anyhow!(e))?; - Ok(Some(v)) -} - -fn emit_result_file(opts: &RunOptions, value: &crate::value::Value) -> Result<()> { - let Some(path) = &opts.emit_result else { - return Ok(()); - }; - let json = crate::host::json::value_to_json(value).map_err(|e| anyhow::anyhow!(e))?; - let text = serde_json::to_string(&json).map_err(|e| anyhow::anyhow!(e))?; - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).map_err(|e| anyhow::anyhow!(e))?; - } - std::fs::write(path, text).map_err(|e| anyhow::anyhow!("emit-result {}: {e}", path.display()))?; - Ok(()) -} - -/// Run and capture stdout (used by `view` and tests). -pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result { - let source = std::fs::read_to_string(path) - .map_err(|e| anyhow::anyhow!("failed to read {}: {e}", path.display()))?; - let stdin_lines = crate::input_feed::effective_stdin(&source, &opts.stdin_lines); - let bind_ctx = BindingContext::from_binds(&opts.binds, cwd_for_path(Some(path))); - let module = load_module_with_ctx(path, &bind_ctx)?; - if let Some(value) = crate::artifact::declaration_summary(&module) { - return Ok(RunCapture { - stdout: String::new(), - value, - plots: Vec::new(), - bindings: Default::default(), - view_trace: Default::default(), - }); - } - - match opts.backend { - Backend::Tree => { - let mut host = HostContext::for_capture(Some(path), opts.host_caps()); - host.set_entry_source(Some(path), &source); - host.argv = opts.argv.clone(); - host.entry_metadata = module.metadata.clone(); - host.sandbox_session = opts.sandbox_session.clone(); - if let Some(root) = &opts.fs_root { - host.fs_root = Some(root.clone()); - host.cwd = root.clone(); - } - if let Some(lim) = opts.sleep_limit_ms { - host.sleep_limit_ms = Some(lim); - } - let mut interp = Interpreter::with_capture(Some(path), false) - .with_stdin(stdin_lines) - .with_host(host); - let value = interp.run_module(&module)?; - let plots = interp.take_plots(); - Ok(RunCapture { - stdout: interp.captured_stdout, - value, - plots, - bindings: interp.entry_bindings, - view_trace: interp.view_trace, - }) - } - Backend::Bytecode => { - let program = compile_module(Some(path), &module)?; - let mut host = HostContext::for_capture(Some(path), opts.host_caps()); - host.set_entry_source(Some(path), &source); - host.argv = opts.argv.clone(); - host.entry_metadata = module.metadata.clone(); - host.sandbox_session = opts.sandbox_session.clone(); - if let Some(root) = &opts.fs_root { - host.fs_root = Some(root.clone()); - host.cwd = root.clone(); - } - if let Some(lim) = opts.sleep_limit_ms { - host.sleep_limit_ms = Some(lim); - } - let mut vm = Vm::with_capture(Some(path)) - .with_stdin(stdin_lines) - .with_host(host); - let value = vm.run(&program)?; - let plots = vm.take_plots(); - Ok(RunCapture { - stdout: vm.captured_stdout, - value, - plots, - bindings: Default::default(), - view_trace: Default::default(), - }) - } - } -} - -/// Run source text in-memory (browser wasm / tests). Imports resolve via embedded `lib/` only. -pub fn run_source(source: &str, opts: &RunOptions) -> Result { - if source.trim().is_empty() { - bail!("source is empty"); - } - let stdin_lines = crate::input_feed::effective_stdin(source, &opts.stdin_lines); - let module = load_module_from_source(source)?; - if let Some(value) = crate::artifact::declaration_summary(&module) { - return Ok(RunCapture { - stdout: String::new(), - value, - plots: Vec::new(), - bindings: Default::default(), - view_trace: Default::default(), - }); - } - - match opts.backend { - Backend::Tree => { - let mut host = HostContext::for_capture(None, opts.host_caps()); - host.set_entry_source(None, source); - host.argv = opts.argv.clone(); - host.entry_metadata = module.metadata.clone(); - host.sandbox_session = opts.sandbox_session.clone(); - if let Some(root) = &opts.fs_root { - host.fs_root = Some(root.clone()); - host.cwd = root.clone(); - } - if let Some(lim) = opts.sleep_limit_ms { - host.sleep_limit_ms = Some(lim); - } - let mut interp = Interpreter::with_capture(None, false) - .with_stdin(stdin_lines) - .with_host(host); - let value = interp.run_module(&module)?; - let plots = interp.take_plots(); - Ok(RunCapture { - stdout: interp.captured_stdout, - value, - plots, - bindings: interp.entry_bindings, - view_trace: interp.view_trace, - }) - } - Backend::Bytecode => { - let program = compile_module(None, &module)?; - let mut host = HostContext::for_capture(None, opts.host_caps()); - host.set_entry_source(None, source); - host.argv = opts.argv.clone(); - host.entry_metadata = module.metadata.clone(); - host.sandbox_session = opts.sandbox_session.clone(); - if let Some(root) = &opts.fs_root { - host.fs_root = Some(root.clone()); - host.cwd = root.clone(); - } - if let Some(lim) = opts.sleep_limit_ms { - host.sleep_limit_ms = Some(lim); - } - let mut vm = Vm::with_capture(None) - .with_stdin(stdin_lines) - .with_host(host); - let value = vm.run(&program)?; - let plots = vm.take_plots(); - Ok(RunCapture { - stdout: vm.captured_stdout, - value, - plots, - bindings: Default::default(), - view_trace: Default::default(), - }) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn run_source_hello() { - let cap = run_source("# main\n\n> print text=Hello World!\n", &RunOptions::default()) - .expect("run_source"); - assert_eq!(cap.stdout, "Hello World!\n"); - } - - #[test] - fn run_source_hello_bytecode() { - let mut opts = RunOptions::default(); - opts.backend = Backend::Bytecode; - let cap = run_source("# main\n\n> print text=Hello World!\n", &opts).expect("bc"); - assert_eq!(cap.stdout, "Hello World!\n"); - } -} diff --git a/src/linalg_ops.rs b/src/linalg_ops.rs deleted file mode 100755 index 91a8af7..0000000 --- a/src/linalg_ops.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! Infix / runtime helpers for `ext/linalg` matrix values. -//! -//! Keeps MatExpr in the plugin; core only dispatches `+` / `-` / `*` when both -//! sides look like matrices (map `_type` or numeric `Formula::Matrix`). - -use std::collections::HashMap; - -use crate::ast::BinaryOp; -use crate::formula::Expr as FormulaExpr; -use crate::host::plugin; -use crate::host::HostContext; -use crate::value::Value; - -fn map_type(v: &Value) -> Option<&str> { - match v { - Value::Map(entries) => entries - .iter() - .find(|(k, _)| k == "_type") - .and_then(|(_, t)| match t { - Value::Text(s) => Some(s.as_str()), - _ => None, - }), - _ => None, - } -} - -/// Author-facing matrix object types (EN / ZH) plus legacy plugin tags. -pub fn is_matrix_value(v: &Value) -> bool { - if matches!(v, Value::Formula(FormulaExpr::Matrix { .. })) { - return true; - } - matches!( - map_type(v), - Some("matrix" | "矩阵" | "linalg_expr" | "linalg_dense") - ) -} - -fn prefer_result_type(left: &Value, right: &Value) -> &'static str { - match map_type(left) { - Some("矩阵") => "矩阵", - Some("matrix") | Some("linalg_expr") | Some("linalg_dense") => "matrix", - _ => match map_type(right) { - Some("矩阵") => "矩阵", - _ => "matrix", - }, - } -} - -/// Stamp `_type` for method chaining (EN `matrix` / ZH `矩阵`). -pub fn retag_matrix_like(type_name: &str, value: Value) -> Value { - if !is_matrix_value(&value) { - return value; - } - tag_type(type_name, value) -} - -fn tag_type(type_name: &str, value: Value) -> Value { - match value { - Value::Map(mut entries) => { - entries.retain(|(k, _)| k != "_type"); - entries.insert(0, ("_type".into(), Value::Text(type_name.into()))); - Value::Map(entries) - } - other => Value::Map(vec![ - ("_type".into(), Value::Text(type_name.into())), - ("value".into(), other), - ]), - } -} - -fn plugin_name(op: BinaryOp) -> Option<&'static str> { - match op { - BinaryOp::Add => Some("linalg_add"), - BinaryOp::Sub => Some("linalg_sub"), - BinaryOp::Mul => Some("linalg_mul"), - _ => None, - } -} - -/// If both sides are matrices, call the linalg plugin; otherwise `Ok(None)`. -pub fn try_matrix_binary( - host: &mut HostContext, - op: BinaryOp, - left: &Value, - right: &Value, -) -> Result, String> { - let Some(fname) = plugin_name(op) else { - return Ok(None); - }; - if !is_matrix_value(left) || !is_matrix_value(right) { - return Ok(None); - } - if host.plugins.get(fname).is_none() { - let op_s = match op { - BinaryOp::Add => "+", - BinaryOp::Sub => "-", - BinaryOp::Mul => "*", - _ => "?", - }; - return Err(format!( - "matrix `{op_s}` needs the linalg plugin loaded (import ext/linalg / `marqdo ext add linalg`)" - )); - } - let mut bound = HashMap::new(); - bound.insert("a".into(), left.clone()); - bound.insert("b".into(), right.clone()); - // ZH param aliases used by some L1 wrappers — plugin accepts both. - bound.insert("左".into(), left.clone()); - bound.insert("右".into(), right.clone()); - let out = plugin::call_registered(host, fname, &bound)?; - Ok(Some(tag_type(prefer_result_type(left, right), out))) -} diff --git a/src/load.rs b/src/load.rs deleted file mode 100755 index 1552a04..0000000 --- a/src/load.rs +++ /dev/null @@ -1,466 +0,0 @@ -//! Load `.mq.md` files and bind frontmatter imports as library modules. - -use std::collections::{HashMap, HashSet}; -use std::env; -use std::path::{Path, PathBuf}; - -use anyhow::{bail, Context, Result}; - -use crate::ast::Module; -use crate::binding::{cwd_for_path, resolve_metadata, BindingContext}; -use crate::diagnostics::{Diagnostic, Span}; -use crate::embedded_lib; -use crate::parse::parse_source; - -/// Load `path` and recursively bind imported modules (no flat merge). -pub fn load_module(path: &Path) -> Result { - load_module_with_ctx( - path, - &BindingContext::from_binds(&[], cwd_for_path(Some(path))), - ) -} - -/// Load with BindingContext (CLI `--bind`, cwd for `sys.cwd`). -pub fn load_module_with_ctx(path: &Path, ctx: &BindingContext) -> Result { - let mut visited = HashSet::new(); - load_module_inner(path, &mut visited, ctx) -} - -/// Load recorded entry text at its original path. Imports and metadata retain -/// normal file-relative resolution; the user's source file is never rewritten. -pub(crate) fn load_module_with_source(path: &Path, source: &str, ctx: &BindingContext) -> Result { - load_module_inner_source(path, &mut HashSet::new(), ctx, Some(source)) -} - -fn load_module_inner( - path: &Path, - visited: &mut HashSet, - ctx: &BindingContext, -) -> Result { - load_module_inner_source(path, visited, ctx, None) -} - -fn load_module_inner_source( - path: &Path, visited: &mut HashSet, ctx: &BindingContext, source_override: Option<&str>, -) -> Result { - let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); - if !visited.insert(canon.clone()) { - bail!("circular import involving {}", path.display()); - } - - let result = (|| { - let source = match source_override { - Some(source) => source.to_string(), - None => read_module_source(path).with_context(|| format!("failed to read {}", path.display()))?, - }; - let markup = frontmatter_markup(&source); - let mut module = crate::parse::expr::with_markup(markup, || parse_source(&source)) - .map_err(|e| attach_path(path, e))?; - module.source.path = Some(path.to_path_buf()); - - // Resolve Artifact Metadata bindings (entry and imports share the same ctx). - let file_ctx = BindingContext { - args: ctx.args.clone(), - cwd: cwd_for_path(Some(path)), - }; - module.metadata = resolve_metadata(&module.metadata_raw, &file_ctx, Span::new(1, 1)) - .map_err(|e| attach_path(path, e))?; - - let base = path.parent().unwrap_or_else(|| Path::new(".")); - let imports = module.imports.clone(); - let mut import_modules = HashMap::new(); - for imp in imports { - let dep_path = resolve_import(base, &imp.path)?; - let dep = load_module_inner(&dep_path, visited, ctx)?; - if import_modules.contains_key(&imp.bind) { - bail!( - "duplicate import bind `{}` while loading {}", - imp.bind, - path.display() - ); - } - import_modules.insert(imp.bind, dep); - } - module.import_modules = import_modules; - crate::inherit::validate_inheritance(&module).map_err(|e| attach_path(path, e))?; - - Ok(module) - })(); - - visited.remove(&canon); - result -} - -fn read_module_source(path: &Path) -> Result { - if path.is_file() { - return std::fs::read_to_string(path).map_err(Into::into); - } - if let Some(source) = read_embedded_for_path(path) { - return Ok(source); - } - std::fs::read_to_string(path).map_err(Into::into) -} - -fn read_embedded_for_path(path: &Path) -> Option { - lib_remainder(path) - .as_deref() - .and_then(embedded_lib::read_file) -} - -fn lib_remainder(path: &Path) -> Option { - let s = path.to_string_lossy().replace('\\', "/"); - if let Some(rest) = s.strip_prefix("lib/") { - return Some(rest.to_string()); - } - // Absolute or relative paths ending in lib/foo.mq.md - let parts: Vec<&str> = s.split('/').collect(); - if let Some(pos) = parts.iter().position(|&p| p == "lib") { - if pos + 1 < parts.len() { - return Some(parts[pos + 1..].join("/")); - } - } - None -} - -/// Resolve an import path: relative to the importer first; `lib/…` / `std/…` -/// and `ext/…` also search official roots (`MARQDO_LIB` / `MARQDO_EXT`, cwd, near the binary), -/// then the embedded stdlib baked into the binary. -pub fn resolve_import(from_dir: &Path, rel: &str) -> Result { - let rel = rel.replace('\\', "/"); - let direct = from_dir.join(&rel); - if direct.is_file() { - return Ok(direct); - } - if let Some(source) = read_embedded_for_path(Path::new(&rel)) { - let _ = source; - // Prefer real file under search roots; else return a virtual lib/ path for embedded read. - } - if rel.starts_with("lib/") || rel.starts_with("std/") { - let rest = rel - .strip_prefix("lib/") - .or_else(|| rel.strip_prefix("std/")) - .unwrap(); - for root in lib_search_roots() { - let p = root.join(rest); - if p.is_file() { - return Ok(p); - } - } - // Walk importer ancestors so workbooks under `.marqdo/…` still find repo `lib/`. - if let Some(p) = find_in_ancestor_dir(from_dir, "lib", rest) { - return Ok(p); - } - // Embedded stdlib: synthesize a path under lib/ for read_module_source. - return Ok(PathBuf::from("lib").join(rest)); - } - if rel.starts_with("ext/") { - let rest = rel.strip_prefix("ext/").unwrap(); - for root in ext_search_roots() { - let p = root.join(rest); - // also try full ext/rel under root - let p2 = root.join(&rel); - if p.is_file() { - return Ok(p); - } - if p2.is_file() { - return Ok(p2); - } - // MARQDO_EXT is the ext root itself (contains ai/) - let under = root.join(rest); - if under.is_file() { - return Ok(under); - } - } - if let Some(p) = find_in_ancestor_dir(from_dir, "ext", rest) { - return Ok(p); - } - let mut msg = format!("cannot resolve import `{rel}` from {}", from_dir.display()); - #[cfg(feature = "cli")] - { - let user_ext = crate::ext_cli::default_user_ext_dir(); - if env::var_os("MARQDO_EXT").is_none() - && !user_ext.join("web").join("web.mq.md").is_file() - { - msg.push_str(&format!( - "\nhint: run `marqdo ext add web` (installs under {}), or set MARQDO_EXT", - user_ext.display() - )); - } else if env::var_os("MARQDO_EXT").is_none() { - msg.push_str(&format!( - "\nhint: looked under {}; set MARQDO_EXT to override", - user_ext.display() - )); - } - } - #[cfg(not(feature = "cli"))] - { - if env::var_os("MARQDO_EXT").is_none() { - msg.push_str("\nhint: set MARQDO_EXT to your extension pack root"); - } - } - bail!("{msg}"); - } - // Relative again with normalize - if direct.exists() { - return Ok(direct); - } - bail!("cannot resolve import `{rel}` from {}", from_dir.display()) -} - -/// Look for `anchor/rest` under `from` or any parent directory (e.g. repo root `ext/ai/…`). -fn find_in_ancestor_dir(from: &Path, anchor: &str, rest: &str) -> Option { - let mut cur = from.to_path_buf(); - loop { - let candidate = cur.join(anchor).join(rest); - if candidate.is_file() { - return Some(candidate); - } - if !cur.pop() { - return None; - } - } -} - -fn lib_search_roots() -> Vec { - let mut roots = Vec::new(); - if let Ok(h) = env::var("MARQDO_LIB") { - roots.push(PathBuf::from(h)); - } - if let Ok(cwd) = env::current_dir() { - roots.push(cwd.join("lib")); - } - if let Ok(exe) = env::current_exe() { - if let Some(dir) = exe.parent() { - roots.push(dir.join("lib")); - roots.push(dir.join("..").join("lib")); - roots.push(dir.join("..").join("..").join("lib")); - } - } - if let Ok(manifest) = env::var("CARGO_MANIFEST_DIR") { - roots.push(PathBuf::from(manifest).join("lib")); - } - roots -} - -fn ext_search_roots() -> Vec { - let mut roots = Vec::new(); - if let Ok(h) = env::var("MARQDO_EXT") { - roots.push(PathBuf::from(h)); - } - // Default install root from `marqdo ext add` (~/.marqdo/ext) - #[cfg(feature = "cli")] - { - roots.push(crate::ext_cli::default_user_ext_dir()); - } - if let Ok(cwd) = env::current_dir() { - roots.push(cwd.join("ext")); - } - if let Ok(exe) = env::current_exe() { - if let Some(dir) = exe.parent() { - roots.push(dir.join("ext")); - roots.push(dir.join("..").join("ext")); - roots.push(dir.join("..").join("..").join("ext")); - } - } - if let Ok(manifest) = env::var("CARGO_MANIFEST_DIR") { - roots.push(PathBuf::from(manifest).join("ext")); - } - roots -} - -fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error { - match err.downcast::() { - Ok(mut d) => { - if d.path.is_none() { - d.path = Some(path.to_path_buf()); - } - d.into() - } - Err(e) => anyhow::anyhow!("{}: {e}", path.display()), - } -} - -/// Load a module from source text. Imports may only resolve to the embedded -/// `lib/…` stdlib (no filesystem / `ext/` for this MVP path). -pub fn load_module_from_source(source: &str) -> Result { - let mut visited = HashSet::new(); - let ctx = BindingContext::default(); - load_module_from_source_inner(source, "", &mut visited, &ctx) -} - -/// 给错误打上文件标签,**保留**结构化诊断(错误出口唯一;AI/MLSP 面不许拍平成字符串)。 -/// 无结构的错误退回 `{label}: {e}` 文本。 -fn label_error(label: &str, e: anyhow::Error) -> anyhow::Error { - match crate::diagnostics::Diagnostic::find(&e).cloned() { - Some(mut d) => { - if d.path.is_none() { - d.path = Some(PathBuf::from(label)); - } - d.into() - } - None => anyhow::anyhow!("{label}: {e}"), - } -} - -/// Effective markup mode declared by the file itself. `` M7 -/// -/// Looks for `markup: occlusion` (or `标记: 遮蔽`) inside the leading frontmatter -/// block. Unmarked sources use the new `occlusion` default; a legacy source -/// must opt in with `markup: classic` or be run through `--legacy-markup` for -/// the transition cycle. There is no environment/process default: an explicit -/// file declaration always decides its own grammar. -/// Parse a standalone source the way the file itself declares (`markup:` in -/// frontmatter). The viewer must use this — otherwise an occluded document is -/// re-parsed in classic mode and fails. `` M7/M8 -pub fn parse_source_auto(source: &str) -> anyhow::Result { - let markup = frontmatter_markup(source); - crate::parse::expr::with_markup(markup, || crate::parse::parse_source(source)) -} - -fn frontmatter_markup(source: &str) -> crate::parse::expr::Markup { - use crate::parse::expr::Markup; - let mut lines = source.lines(); - if lines.next().map(|l| l.trim_end()) != Some("---") { - return crate::parse::expr::markup_default(); - } - for line in lines { - let t = line.trim(); - if t == "---" { - break; - } - let lower = t.to_ascii_lowercase(); - for key in ["markup:", "标记:"] { - if let Some(rest) = lower.strip_prefix(key) { - let val = rest.trim(); - return if matches!(val, "occlusion" | "purity" | "遮蔽" | "纯度") { - Markup::Occlusion - } else { - Markup::Classic - }; - } - } - } - crate::parse::expr::markup_default() -} - -fn load_module_from_source_inner( - source: &str, - label: &str, - visited: &mut HashSet, - ctx: &BindingContext, -) -> Result { - let key = PathBuf::from(label); - if !visited.insert(key.clone()) { - bail!("circular import involving {label}"); - } - - let result = (|| { - let markup = frontmatter_markup(source); - let mut module = crate::parse::expr::with_markup(markup, || parse_source(source)) - .map_err(|e| label_error(label, e))?; - module.source.path = Some(PathBuf::from(label)); - module.metadata = resolve_metadata(&module.metadata_raw, ctx, Span::new(1, 1)) - .map_err(|e| label_error(label, e))?; - let imports = module.imports.clone(); - let mut import_modules = HashMap::new(); - for imp in imports { - let dep = load_embedded_import(&imp.path, visited, ctx)?; - if import_modules.contains_key(&imp.bind) { - bail!("duplicate import bind `{}` while loading {label}", imp.bind); - } - import_modules.insert(imp.bind, dep); - } - module.import_modules = import_modules; - crate::inherit::validate_inheritance(&module).map_err(|e| label_error(label, e))?; - Ok(module) - })(); - - visited.remove(&key); - result -} - -fn load_embedded_import( - rel: &str, - visited: &mut HashSet, - ctx: &BindingContext, -) -> Result { - let rel = rel.replace('\\', "/"); - let rest = if let Some(r) = rel.strip_prefix("lib/") { - r.to_string() - } else if let Some(r) = rel.strip_prefix("std/") { - r.to_string() - } else if embedded_lib::read_file(&rel).is_some() { - rel.clone() - } else { - bail!( - "import `{rel}` is not an embedded lib/ path — \ - run_source only resolves embedded stdlib (lib/…); filesystem and ext/ imports are unsupported" - ); - }; - let Some(dep_source) = embedded_lib::read_file(&rest) else { - bail!("embedded lib not found: lib/{rest}"); - }; - let label = format!("lib/{rest}"); - load_module_from_source_inner(&dep_source, &label, visited, ctx) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn resolve_lib_from_cwd() { - let cwd = env::current_dir().unwrap(); - let lib_text = cwd.join("lib").join("text.mq.md"); - if !lib_text.is_file() { - return; - } - let p = resolve_import(Path::new("tests/keywords"), "lib/text.mq.md").unwrap(); - assert!(p.ends_with("text.mq.md")); - let p2 = resolve_import(Path::new("tests/keywords"), "std/text.mq.md").unwrap(); - assert!(p2.ends_with("text.mq.md")); - } - - #[test] - fn resolve_ext_missing_hints_marqdo_ext() { - let prev = env::var_os("MARQDO_EXT"); - env::remove_var("MARQDO_EXT"); - // Unique path so cwd/ext cannot satisfy the import. - let err = - resolve_import(Path::new("/tmp"), "ext/__gap12_missing__/nope.mq.md").unwrap_err(); - let msg = format!("{err:#}"); - match prev { - Some(v) => env::set_var("MARQDO_EXT", v), - None => env::remove_var("MARQDO_EXT"), - } - assert!( - msg.contains("cannot resolve import `ext/__gap12_missing__/nope.mq.md`"), - "{msg}" - ); - assert!( - msg.contains("hint:") - && (msg.contains("marqdo ext add") - || msg.contains("MARQDO_EXT") - || msg.contains(".marqdo/ext")), - "{msg}" - ); - } - #[test] - fn recorded_source_resolves_relative_imports_without_rewriting_files() { - let root=std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let dir=root.join(format!("target/load-recorded-{}-{}",std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); - std::fs::create_dir_all(&dir).unwrap();let entry=dir.join("main.mq.md"); - let original="# main\n\n> print text=original\n"; - std::fs::write(&entry,original).unwrap();std::fs::write(dir.join("dep.mq.md"),"# helper\n\n> print text=dependency\n").unwrap(); - let recorded="---\nimport:\n dep: dep.mq.md\n---\n# main\n\n> print text=recorded\n"; - let ctx=BindingContext::from_binds(&[],cwd_for_path(Some(&entry))); - let module=load_module_with_source(&entry,recorded,&ctx).unwrap(); - assert!(module.import_modules.contains_key("dep")); - assert_eq!(std::fs::read_to_string(&entry).unwrap(),original); - let cyclic="---\nimport:\n again: main.mq.md\n---\n# main\n"; - assert!(load_module_with_source(&entry,cyclic,&ctx).unwrap_err().to_string().contains("circular import")); - assert_eq!(std::fs::read_to_string(&entry).unwrap(),original); - std::fs::remove_dir_all(dir).unwrap(); - } - -} diff --git a/src/main.rs b/src/main.rs deleted file mode 100755 index f5a00ec..0000000 --- a/src/main.rs +++ /dev/null @@ -1,2430 +0,0 @@ -use std::path::PathBuf; -use std::process::ExitCode; - -use anyhow::Result; -use clap::{Parser, Subcommand, ValueEnum}; - -use marqdo::catalog::{write_catalog, CatalogOptions}; -use marqdo::diagnostics::{Diagnostic, Span}; -use marqdo::ext_cli::{add_ext, list_ext, remove_ext}; -use marqdo::input_feed::load_stdin_file; -use marqdo::knowledge::{ - compile_policy, conflicts_json, find, find_conflicts, find_duplicates, find_json, find_stale, - format_conflicts_text, format_duplicates_text, format_find_text, format_impact_text, - format_preflight_yaml, format_reuse_text, format_stale_text, format_verify_text, graph_for_query, - impact, impact_json, learn, preflight_from_reuse, preflight_json, record_decision, resolve, - reuse_json, stale_json, verify, verify_json, write_knowledge, KnowledgeOptions, LearnInput, - ReuseBudget, -}; -use marqdo::view::{ - serve, serve_debug, write_capture, write_static, CaptureOptions, DebugOptions, OutputOptions, - ViewOptions, -}; -use marqdo::{Backend, RunOptions}; - -#[derive(Parser, Debug)] -#[command( - name = "marqdo", - version, - about = "Marqdo interpreter — run, view, debug, catalog, knowledge, and ext" -)] -struct Cli { - #[command(subcommand)] - command: Commands, -} - -#[derive(Clone, Copy, Debug, ValueEnum)] -enum BackendCli { - Tree, - Bytecode, -} - -impl From for Backend { - fn from(b: BackendCli) -> Self { - match b { - BackendCli::Tree => Backend::Tree, - BackendCli::Bytecode => Backend::Bytecode, - } - } -} - -#[derive(Subcommand, Debug)] -enum MigrateAction { - /// `[键](集合)` → `access(集合, 键)`;`- [项](集合)` → `- [项](遍历 集合 为 项)` - Labels { - #[arg(value_name = "PATH", default_value = ".")] - paths: Vec, - /// Actually rewrite files (default: dry run) - #[arg(long)] - write: bool, - /// Add `markup: occlusion` to every unmarked file, including files - /// with no legacy index. Use this when migrating a shipped library. - #[arg(long)] - mark: bool, - /// One JSON object on stdout - #[arg(long)] - json: bool, - }, - /// One-liner `import bind:target` → nested YAML `import:\n bind: target` - Imports { - #[arg(value_name = "PATH", default_value = ".")] - paths: Vec, - /// Actually rewrite files (default: dry run) - #[arg(long)] - write: bool, - /// One JSON array on stdout - #[arg(long)] - json: bool, - }, -} - -#[derive(Subcommand, Debug)] -enum Commands { - /// Execute a Marqdo source file (defaults to ./index.mq.md) - Run { - #[arg(value_name = "FILE")] - file: Option, - - #[arg(long, value_enum, default_value_t = BackendCli::Tree)] - backend: BackendCli, - - #[arg(long)] - dump_lines: bool, - #[arg(long)] - dump_tokens: bool, - #[arg(long)] - dump_ast: bool, - #[arg(long)] - dump_sema: bool, - #[arg(long)] - dump_bytecode: bool, - #[arg(long)] - trace_eval: bool, - #[arg(long)] - dump_all: bool, - - /// Feed `input` from a text file (one line per call), instead of / after the terminal. - #[arg(long, value_name = "FILE")] - stdin_file: Option, - - /// Write `# main` return value as JSON (used by file subtasks). - #[arg(long, value_name = "FILE")] - emit_result: Option, - - /// Artifact Metadata Binding: `KEY=VALUE` (repeatable). Feeds `arg.KEY` and overlays metadata. - #[arg(long = "bind", value_name = "KEY=VALUE")] - binds: Vec, - - /// Filesystem sandbox + process cwd root (default: entry file's directory). - /// Also read from env `MARQDO_FS_ROOT`. Use repo root when running `cli/…` entries. - #[arg(long = "fs-root", value_name = "DIR")] - fs_root: Option, - - /// Deny filesystem writes in this run and its file subtasks. - #[arg(long)] - deny_fs_write: bool, - /// Deny process execution. - #[arg(long)] - deny_exec: bool, - /// Deny network access. - #[arg(long)] - deny_net: bool, - /// Deny native plugin loading. - #[arg(long)] - deny_plugin: bool, - - /// Isolated worker: call `lib.member` on the site entry instead of `# main`. - #[arg(long = "call-lib-path", value_name = "LIB.MEMBER")] - call_lib_path: Option, - - /// Named args JSON for `--call-lib-path` (file path, or `-` for stdin). - #[arg(long = "args-json", value_name = "FILE")] - args_json: Option, - - /// Emit diagnostics as JSON on stderr (machine-readable; AI/MLSP 面). - #[arg(long)] - json: bool, - - /// Parse unmarked files using the legacy `[key](collection)` grammar. - /// Explicit per-file `markup:` still wins; this flag is transitional. - #[arg(long)] - legacy_markup: bool, - }, - /// Call one function in a `.mq.md` file: `marqdo call name=value`. - Call { - /// Source file. - file: PathBuf, - - /// Function display path, for example `计算器.加法` or nested `parent.child`. - function: String, - - /// Named arguments `name=value` (integer, decimal, quoted text, True/False/None, JSON, `$name`). - /// A value may be negative (`a=-2`). Trailing `toget ` stores the result in the session. - /// `--json` and `--backend` remain flags. - args: Vec, - - /// Print one JSON object: `{"ok":true,"result":...}` or `{"ok":false,"error":...}`. - #[arg(long)] - json: bool, - - /// Runtime. Both backends execute the named function. - #[arg(long, value_enum, default_value_t = BackendCli::Tree)] - backend: BackendCli, - - /// Comma-separated effect grants: none, plugin, fs.read, fs.write, output.write, etc. - #[arg(long, default_value = "none")] - effects: String, - - /// Literal named arguments as a JSON object; '-' reads stdin (no shell/argv size limit). - /// JSON strings never resolve call-session $name or @name references. - #[arg(long, value_name = "FILE_OR_STDIN")] - args_json: Option, - - /// Return a failing exit status when the function returns Result {ok:false}. - /// The JSON result is preserved; no effect is retried or rolled back. - #[arg(long)] - require_ok: bool, - - /// Directory available to file tools; defaults to the called file directory. - #[arg(long)] - fs_root: Option, - - /// Call-session id for `toget` / `$name` (default: env `MARQDO_CALL_SESSION` or `default`). - #[arg(long)] - session: Option, - - /// Store the return value under this name in the call session (also: trailing `toget NAME`). - #[arg(long)] - toget: Option, - }, - /// Static contract cross-check (渐进式契约): drift, unknown types, misplaced tables - Check { - /// Program path (.mq.md) - #[arg(value_name = "FILE")] - file: PathBuf, - - /// Emit one JSON diagnostic per line on stdout (machine-readable; AI/MLSP 面) - #[arg(long)] - json: bool, - - /// Also check prose above `>` calls (implicit occlusion; fuzzy, off by default) - #[arg(long)] - implicit_labels: bool, - - /// Require narration ≥ 50% in each function unit (ext skill contract). - #[arg(long)] - narrative_ratio: bool, - - /// Parse an unmarked file with the legacy grammar for migration review. - #[arg(long)] - legacy_markup: bool, - - /// Validate theorem tables (ADR 0010; 默认关): shape, symbols, shadowing - #[arg(long)] - proof: bool, - }, - /// Occlusion label queries: pending stubs (built-in words) or keyword search - Labels { - /// Files or directories (recursively scans `*.mq.md`) - #[arg(value_name = "PATH", default_value = ".")] - paths: Vec, - - /// Keywords (comma separated). Replaces the built-in pending set. - #[arg(long, value_name = "WORDS")] - grep: Option, - - /// Union with the built-in groups instead of replacing them - #[arg(long)] - also_builtin: bool, - - /// Built-in group names, comma separated (default: pending = 未完成,假数据) - #[arg(long, value_name = "GROUPS")] - group: Option, - - /// One JSON array on stdout - #[arg(long)] - json: bool, - - /// Print only the hit count - #[arg(long)] - count: bool, - - /// Debt ledger (JSON) for the ratchet: seed it, then only allow decreases - #[arg(long, value_name = "FILE")] - baseline: Option, - - /// Fail (exit 1) when the hit count exceeds the baseline (`` M8) - #[arg(long)] - fail_on_increase: bool, - }, - /// Migrate legacy syntax to the purity forms (`` M7) - Migrate { - #[command(subcommand)] - action: MigrateAction, - }, - /// MLSP for AI: line-delimited JSON on stdio (locate / syntax / validate / repair_targets / schema) - Mlsp, - /// Browse `.mq.md` structure + execution (live server or static output) - View { - #[command(subcommand)] - action: Option, - - /// Path when running the live server (default: `.`) - #[arg(value_name = "PATH", global = true)] - path: Option, - - #[arg(long, default_value = "127.0.0.1", global = true)] - host: String, - - #[arg(long, default_value_t = 7429, global = true)] - port: u16, - - #[arg(long, global = true)] - no_open: bool, - }, - /// Interactive debugger (tree-walk breakpoints; separate UI from `view`) - Debug { - /// Path to a `.mq.md` file or directory (default: `.`) - #[arg(value_name = "PATH")] - path: Option, - - #[arg(long, default_value = "127.0.0.1")] - host: String, - - #[arg(long, default_value_t = 7430)] - port: u16, - - #[arg(long)] - no_open: bool, - }, - /// Generate OKF-compatible catalog YAML + module pages (+ Engineering Knowledge) - Catalog { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - /// Skip Engineering Knowledge Compiler after catalog - #[arg(long)] - no_knowledge: bool, - }, - /// Alias for `catalog` - Sync { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - #[arg(long)] - no_knowledge: bool, - }, - /// Engineering Knowledge Compiler (L0–L4 catalog / graph / projections) - Knowledge { - #[command(subcommand)] - action: Option, - - #[arg(value_name = "PATH", global = true)] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo", global = true)] - out: PathBuf, - - #[arg(long, global = true)] - json: bool, - - /// Force a full knowledge recompile before query actions (preflight, …) - #[arg(long, global = true)] - refresh: bool, - }, - /// Find engineering capabilities / symbols / knowledge - Find { - #[arg(value_name = "QUERY")] - query: String, - - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - #[arg(long, default_value_t = 20)] - limit: usize, - - #[arg(long)] - json: bool, - - /// Force a full knowledge recompile before querying - #[arg(long)] - refresh: bool, - }, - /// Engineering First Information: REUSE / ADAPT / CREATE - Reuse { - #[arg(value_name = "TASK")] - task: String, - - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - /// Also write preflight context pack + policy - #[arg(long)] - preflight: bool, - - #[arg(long, default_value_t = 3)] - min_candidates: usize, - - #[arg(long, default_value_t = 2)] - allow_create_after: usize, - - #[arg(long)] - json: bool, - - /// Force a full knowledge recompile before querying - #[arg(long)] - refresh: bool, - }, - /// Knowledge impact of changed paths - Impact { - #[arg(value_name = "PATH")] - paths: Vec, - - #[arg(long, value_name = "ROOT", default_value = ".")] - root: PathBuf, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - #[arg(long)] - json: bool, - - /// Force a full knowledge recompile before querying - #[arg(long)] - refresh: bool, - }, - /// Detect knowledge conflicts / possible duplicates edges - Conflicts { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - #[arg(long)] - json: bool, - - /// Exit non-zero when conflicts found (CI gate; default remains report-only) - #[arg(long)] - fail: bool, - - /// Force a full knowledge recompile before querying - #[arg(long)] - refresh: bool, - }, - /// List stale / deprecated / superseded knowledge - Stale { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - #[arg(long)] - json: bool, - - /// Exit non-zero when stale items found (CI gate; default remains report-only) - #[arg(long)] - fail: bool, - - /// Force a full knowledge recompile before querying - #[arg(long)] - refresh: bool, - }, - /// Detect duplicate capabilities via symbol fingerprints - Duplicate { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - #[arg(long, default_value_t = 0.75)] - threshold: f64, - - /// Exit non-zero when duplicates found (CI gate) - #[arg(long)] - fail: bool, - - #[arg(long)] - json: bool, - - /// Force a full knowledge recompile before querying - #[arg(long)] - refresh: bool, - }, - /// Verify code ↔ knowledge consistency (EKC structural; exit 1 only on errors) - Verify { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", default_value = ".marqdo")] - out: PathBuf, - - #[arg(long)] - json: bool, - - /// Also fail on warnings (does not change default success-when-no-errors) - #[arg(long)] - fail_on_warning: bool, - - /// Force a full knowledge recompile before querying - #[arg(long)] - refresh: bool, - }, - /// Official extension installer (`list` / `add` / `remove`) - Ext { - #[command(subcommand)] - action: ExtAction, - }, - /// Print version; `--check` compares with the latest GitHub release - Version { - #[arg(long)] - check: bool, - }, - /// Build browser WASM artifact (route C) - Wasm { - #[command(subcommand)] - action: WasmAction, - }, - /// Compile SKILL orchestration to Lean 4 and (P1+) prove theorems (推荐但不强制) - Prove { - /// Action (default: emit + report) - #[command(subcommand)] - action: Option, - - /// Program path (.mq.md; default ./index.mq.md) - #[arg(value_name = "FILE")] - file: Option, - - /// One JSON object on stdout (agent-facing stable contract) - #[arg(long)] - json: bool, - - /// Only lower/emit these functions (display path, repeatable) - #[arg(long = "only", value_name = "FN")] - only: Vec, - - /// Output dir for emit (default .marqdo/prove//) - #[arg(long = "emit", short = 'o', value_name = "DIR")] - emit_dir: Option, - - /// Don't write artifacts; report only - #[arg(long)] - report_only: bool, - - /// Downgrade this function wholesale to one opaque op (repeatable) - #[arg(long = "allow-opaque", value_name = "FN")] - allow_opaque: Vec, - - /// Type inference is strict by default; this relaxes to Val (weaker proofs) - #[arg(long = "no-strict-types")] - no_strict_types: bool, - - /// CI strict mode: unjudged statuses exit 2 (P1+) - #[arg(long)] - require_lean: bool, - - /// Explicit lean binary (else MARQDO_PROOF_LEAN, else PATH) - #[arg(long, value_name = "PATH")] - lean: Option, - - /// Per-lean-call timeout in seconds (default 120) - #[arg(long, value_name = "SEC", default_value_t = 120)] - timeout: u64, - - /// Bypass the certificate cache (also MARQDO_PROOF_NO_CACHE) - #[arg(long)] - no_cache: bool, - - /// maxHeartbeats for lean (default: lean's own) - #[arg(long, value_name = "N")] - heartbeats: Option, - - /// Directory mode: recursively prove every .mq.md (aggregated, worst status wins) - #[arg(long)] - all: bool, - - /// Cap for --all file collection (default 200) - #[arg(long = "max-files", value_name = "N", default_value_t = 200)] - max_files: usize, - - /// Debug fault injection: `offline-claim` flips one Lean-proved claim to - /// force proof.divergence (monotonicity tripwire verification) - #[arg(long = "fault-inject", value_name = "SPEC")] - fault_inject: Option, - }, -} - -#[derive(Subcommand, Debug)] -enum ProveAction { - /// Generate deterministic Lean module + plan.json (no judging) - Emit { - #[arg(value_name = "FILE")] - file: Option, - #[arg(long = "emit", short = 'o', value_name = "DIR")] - emit_dir: Option, - #[arg(long)] - json: bool, - #[arg(long = "only", value_name = "FN")] - only: Vec, - #[arg(long = "allow-opaque", value_name = "FN")] - allow_opaque: Vec, - #[arg(long = "no-strict-types")] - no_strict_types: bool, - }, - /// Report inline/opaque/rejected classification (no judging) - Audit { - #[arg(value_name = "FILE")] - file: Option, - #[arg(long)] - json: bool, - #[arg(long = "only", value_name = "FN")] - only: Vec, - #[arg(long = "allow-opaque", value_name = "FN")] - allow_opaque: Vec, - #[arg(long = "no-strict-types")] - no_strict_types: bool, - }, - /// Delete .marqdo/prove caches and certificates - Clean { - #[arg(long)] - json: bool, - }, -} - -#[derive(Subcommand, Debug)] -enum KnowledgeAction { - /// Compile L0–L4 projections (default) - Compile, - /// Inspect verified theorem receipts and inter-module proof obligations. - ProofDeps { - /// Fail if the receipt/contract graph contains unresolved obligations. - #[arg(long)] - strict: bool, - /// Actually discharge closed callsite preconditions in Lean; without - /// this switch the command only emits pending proof obligations. - #[arg(long)] - verify: bool, - }, - /// Emit independent Lean callee+caller proofs for restricted pure forwarders. - /// Unsupported constructs are rejected and never receive certificates. - Compose { - /// Exit nonzero if any call is unsupported or Lean rejects it. - #[arg(long)] - strict: bool, - }, - /// Independently replay a previously issued composition certificate - /// against current source, Lean modules and toolchain. - Replay { - #[arg(value_name = "CERTIFICATE")] - certificate: PathBuf, - }, - /// Inspect stable project symbols by exact URI or display name - Inspect { - /// Symbol URI (`mq://…`) or declaration name - #[arg(value_name = "SYMBOL")] - symbol: String, - }, - /// Resolve a new-style knowledge path in the import scope of a source file - Resolve { - /// `mq://…` URI or a value-path such as `facts.Person.birth_year` - #[arg(value_name = "REFERENCE")] - reference: String, - - /// Source file whose frontmatter imports supply the path's first segment - #[arg(long, value_name = "FILE")] - from: Option, - }, - /// Check or update the reviewed semantic target lock (`links.lock.json`) - Lock { - /// Replace the lock with the current deterministic semantic graph - #[arg(long)] - update: bool, - /// Return exit code 3 when the lock is missing or differs - #[arg(long)] - strict: bool, - }, - /// Show transitive reverse dependencies of a symbol, artifact, or source path - Impact { - #[arg(value_name = "SYMBOL_OR_PATH")] - query: String, - }, - /// Machine adjudication of semantic artifacts (M03): may_bind / may_publish - Adjudicate { - /// Artifact id, symbol id, or display name (omit to report all functions) - #[arg(value_name = "ARTIFACT")] - artifact: Option, - /// Policy: pure | business | static - #[arg(long, default_value = "business")] - policy: String, - /// Exit 1 when any reported artifact has may_bind=false - #[arg(long)] - fail: bool, - }, - /// Run engineering preflight for a task - Preflight { - #[arg(value_name = "TASK")] - task: String, - - #[arg(long, default_value_t = 3)] - min_candidates: usize, - - #[arg(long, default_value_t = 2)] - allow_create_after: usize, - }, - /// Record a reuse decision into metrics - Record { - #[arg(value_name = "DECISION")] - decision: String, - - #[arg(long)] - duplicated: bool, - }, - /// Learn failure/decision/constraint into knowledge/ - Learn { - #[arg(long)] - task: String, - #[arg(long)] - failed_approach: Option, - #[arg(long)] - failure: Option, - #[arg(long)] - correct_approach: Option, - #[arg(long)] - decision_title: Option, - #[arg(long)] - decision_body: Option, - #[arg(long)] - constraint_title: Option, - #[arg(long)] - constraint_body: Option, - }, -} - -#[derive(Subcommand, Debug)] -enum ExtAction { - /// List official extensions and install status - List, - /// Install an official extension into the local ext root - Add { - #[arg(value_name = "NAME")] - name: String, - }, - /// Remove an installed official extension - Remove { - #[arg(value_name = "NAME")] - name: String, - }, -} - -#[derive(Subcommand, Debug)] -enum WasmAction { - /// `cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release` and copy `.wasm` - Build { - /// Destination directory (default: examples/browser-hello) - #[arg(short = 'o', long = "out", default_value = "examples/browser-hello")] - out: PathBuf, - }, -} - -#[derive(Subcommand, Debug)] -enum ViewAction { - /// Write static HTML documentation site - Output { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", required = true)] - out: PathBuf, - - #[arg(long)] - no_exec: bool, - - #[arg(long, value_name = "FILE")] - snapshot: Option, - }, - /// Capture live cell results for `view output --snapshot` - Capture { - #[arg(value_name = "PATH")] - path: Option, - - #[arg(short = 'o', long = "out", required = true)] - out: PathBuf, - }, - /// Read-only DocumentViewV1 (never executes). JSON to stdout or `--out`. - Document { - /// Project root (defaults to cwd / CLI path) - #[arg(long)] - project: Option, - - /// Document path relative to project - #[arg(long)] - document: String, - - #[arg(long)] - json: bool, - - /// Optional HTML wrapper for browser inspection (embed fragment only) - #[arg(long, value_name = "FILE")] - out: Option, - }, -} - -fn main() -> ExitCode { - let cli = Cli::parse(); - let json_errors = matches!( - &cli.command, - Commands::Run { json: true, .. } - | Commands::Check { json: true, .. } - | Commands::Prove { json: true, .. } - ); - match try_main(cli) { - Ok(code) => ExitCode::from(code as u8), - Err(err) => { - if json_errors { - let diag = match err.downcast::() { - Ok(d) => d, - Err(e) => Diagnostic::find(&e).cloned().unwrap_or_else(|| { - Diagnostic::new(None, Span::new(0, 0), format!("{e:#}")) - }), - }; - eprintln!("{}", diag.to_json()); - } else { - eprintln!("error: {err:#}"); - } - ExitCode::from(1) - } - } -} - -/// `prove --all`:逐文件出报告,整体取最差状态(差者胜,§3.2)。 -/// JSON:`{"schema":1,"kind":"prove-all","status":…,"files":[…],"duration_ms":…}`。 -fn run_prove_all( - dir: &std::path::Path, - max_files: usize, - opts: &marqdo::prove::ProveOptions, - json: bool, - require_lean: bool, -) -> Result { - let mut files = collect_mq_files(dir)?; - anyhow::ensure!( - !files.is_empty(), - "目录中没有 .mq.md 文件:{}", - dir.display() - ); - anyhow::ensure!( - files.len() <= max_files, - "--max-files {max_files} 已达上限(实际 {} 个文件;请调大或缩小范围)", - files.len() - ); - files.sort(); - let started = std::time::Instant::now(); - let mut worst = marqdo::prove::Verdict::Proved; - let mut file_items: Vec = Vec::new(); - let mut text_rows: Vec<(String, marqdo::prove::Verdict, usize)> = Vec::new(); - for f in &files { - let report = marqdo::prove::prove_path(f, opts)?; - for d in &report.diagnostics { - eprintln!("{}", d.format_message()); - } - let claims: usize = report - .functions - .iter() - .map(|fun| fun.claims.len()) - .sum(); - worst = marqdo::prove::Verdict::worst(worst, report.status); - text_rows.push(( - f.strip_prefix(dir).unwrap_or(f).display().to_string(), - report.status, - claims, - )); - let mut item = report.to_json(); - if let Some(obj) = item.as_object_mut() { - obj.insert( - "file".into(), - serde_json::Value::String( - f.strip_prefix(dir).unwrap_or(f).display().to_string(), - ), - ); - } - file_items.push(item); - } - let duration_ms = started.elapsed().as_millis() as u64; - if json { - let agg = serde_json::json!({ - "schema": 1, - "kind": "prove-all", - "root": dir.display().to_string(), - "status": worst.as_str(), - "files": file_items, - "file_count": files.len(), - "duration_ms": duration_ms, - }); - println!("{agg}"); - } else { - println!( - "prove --all {}:{} 个文件,{} ms,整体 {}", - dir.display(), - files.len(), - duration_ms, - worst.as_str() - ); - for (rel, status, claims) in &text_rows { - println!(" {rel}: {}(定理 {claims})", status.as_str()); - } - } - Ok(worst.exit_code(require_lean)) -} - -/// Resolve the value-path spelling introduced for executable knowledge without -/// evaluating it. The import bind comes from the caller's source file, so -/// `math.pi` never degrades into a project-wide name guess. -fn resolve_knowledge_reference<'a>( - index: &'a marqdo::sema::ProjectIndex, - reference: &str, - from: Option<&std::path::Path>, -) -> Result<&'a marqdo::sema::SymbolDecl> { - if reference.starts_with("mq://") { - return index - .symbols() - .iter() - .find(|symbol| symbol.id.as_str() == reference) - .ok_or_else(|| anyhow::anyhow!("unknown symbol URI `{reference}`")); - } - - let expression = marqdo::parse::expr::parse_expr_prefer_var(reference) - .map_err(|error| anyhow::anyhow!("invalid knowledge reference `{reference}`: {error}"))?; - let marqdo::ast::Expr::Call(call) = expression else { - anyhow::bail!("knowledge reference `{reference}` must be a dotted value path or mq:// URI"); - }; - if !call.args.is_empty() { - anyhow::bail!( - "knowledge resolve only binds a zero-argument path; `{reference}` has arguments" - ); - } - let path = call.path.ok_or_else(|| { - anyhow::anyhow!("knowledge reference `{reference}` must start with an imported module bind") - })?; - if path.len() < 2 { - anyhow::bail!("knowledge reference `{reference}` needs at least `module.symbol`"); - } - let from = from.ok_or_else(|| { - anyhow::anyhow!("`--from FILE` is required to resolve imported path `{reference}`") - })?; - let module = marqdo::load::load_module(from)?; - let imported = module - .imports - .iter() - .find(|item| item.bind == path[0]) - .ok_or_else(|| { - anyhow::anyhow!("unknown import bind `{}` in {}", path[0], from.display()) - })?; - let base = from.parent().unwrap_or_else(|| std::path::Path::new(".")); - let imported_path = marqdo::load::resolve_import(base, &imported.path)?; - let imported_path = imported_path.canonicalize().unwrap_or(imported_path); - let module_id = index - .modules() - .iter() - .find_map(|(module_id, source)| { - (source.canonicalize().unwrap_or_else(|_| source.clone()) == imported_path) - .then_some(module_id) - }) - .ok_or_else(|| { - anyhow::anyhow!( - "import `{}` resolves to {}, which is outside the indexed project", - path[0], - imported_path.display() - ) - })?; - let declaration_path = &path[1..]; - index - .symbols() - .iter() - .find(|symbol| symbol.module == *module_id && symbol.declaration_path == declaration_path) - .ok_or_else(|| anyhow::anyhow!("unknown knowledge path `{reference}`")) -} - -/// Recursively collect `*.mq.md` under `path` (file → itself). -fn collect_mq_files(path: &std::path::Path) -> Result> { - fn walk(dir: &std::path::Path, out: &mut Vec) { - let Ok(rd) = std::fs::read_dir(dir) else { - return; - }; - for e in rd.flatten() { - let p = e.path(); - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if p.is_dir() { - if matches!( - name, - "target" | "dist" | "node_modules" | ".git" | ".marqdo" - ) { - continue; - } - walk(&p, out); - } else if name.ends_with(".mq.md") { - out.push(p); - } - } - } - if path.is_file() { - return Ok(vec![path.to_path_buf()]); - } - let mut out = Vec::new(); - walk(path, &mut out); - out.sort(); - Ok(out) -} - -fn try_main(cli: Cli) -> Result { - match cli.command { - Commands::Run { - file, - backend, - dump_lines, - dump_tokens, - dump_ast, - dump_sema, - dump_bytecode, - trace_eval, - dump_all, - stdin_file, - emit_result, - binds, - fs_root, - call_lib_path, - args_json, - json: _, - legacy_markup, - deny_fs_write, - deny_exec, - deny_net, - deny_plugin, - } => { - let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md")); - let stdin_lines = match stdin_file { - Some(p) => load_stdin_file(&p)?, - None => Vec::new(), - }; - let mut bind_pairs = Vec::new(); - for b in &binds { - bind_pairs.push(marqdo::binding::parse_bind_kv(b)?); - } - let env_fs_root = std::env::var_os("MARQDO_FS_ROOT").map(PathBuf::from); - let fs_root = fs_root.or(env_fs_root); - let mut opts = if dump_all { - RunOptions { - stdin_lines: stdin_lines.clone(), - emit_result: emit_result.clone(), - binds: bind_pairs.clone(), - fs_root: fs_root.clone(), - call_lib_path: call_lib_path.clone(), - args_json: args_json.clone(), - ..RunOptions::dump_all() - } - } else { - RunOptions { - dump_lines, - dump_tokens, - dump_ast, - dump_sema, - dump_bytecode, - trace_eval, - backend: backend.into(), - stdin_lines, - emit_result, - binds: bind_pairs, - fs_root, - call_lib_path, - args_json, - ..RunOptions::default() - } - }; - opts.allow_fs_write = !deny_fs_write; - opts.allow_exec = !deny_exec; - opts.allow_net = !deny_net; - opts.allow_plugin = !deny_plugin; - if dump_all { - opts.backend = backend.into(); - } - if legacy_markup { - marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || { - marqdo::run_file(&path, &opts) - })?; - } else { - marqdo::run_file(&path, &opts)?; - } - Ok(0) - } - Commands::Call { - file, - function, - args, - args_json, - require_ok, - json, - backend, - effects, - fs_root, - session, - toget, - } => { - let outcome = (|| -> Result { - let effects = marqdo::call::CallEffects::parse(&effects)?; - let (arg_tokens, trailing_toget) = marqdo::call::split_toget(&args)?; - let toget = toget.or(trailing_toget); - let literal_args = args_json.is_some(); - let parsed = if let Some(input) = args_json { - use std::io::Read; - if !arg_tokens.is_empty() { - anyhow::bail!("--args-json cannot be combined with name=value arguments"); - } - let mut source = String::new(); - if input.as_os_str() == "-" { - std::io::stdin().take(64 * 1024 * 1024 + 1).read_to_string(&mut source)?; - } else { - std::fs::File::open(&input)?.take(64 * 1024 * 1024 + 1).read_to_string(&mut source)?; - } - if source.len() > 64 * 1024 * 1024 { anyhow::bail!("--args-json exceeds 64 MiB"); } - marqdo::call::parse_call_args_json(&source)? - } else { - marqdo::call::parse_call_args(&arg_tokens)? - }; - let session = session.or_else(|| { - if toget.is_some() - || (!literal_args && parsed.iter().any(|(_, v)| { - matches!( - v, - marqdo::value::Value::Text(t) - if t.starts_with('$') || t.starts_with('@') - ) - })) - { - Some(marqdo::call_session::default_session_id()) - } else { - None - } - }); - marqdo::call::call_file_with( - &file, - &function, - &parsed, - backend.into(), - marqdo::call::CallOptions { - effects, - fs_root, - session, - toget, - literal_args, - }, - ) - })(); - match outcome { - Ok(value) => { - if json { - let result = marqdo::value_as_json(&value) - .map_err(|e| anyhow::anyhow!(e))?; - println!( - "{}", - serde_json::json!({"ok": true, "result": result}) - ); - } else { - println!("{}", value.as_display()); - } - let failed = require_ok && matches!(&value, - marqdo::value::Value::Map(fields) if fields.iter().any(|(k,v)| - k == "ok" && matches!(v, marqdo::value::Value::Bool(false)))); - Ok(if failed { 1 } else { 0 }) - } - Err(err) => { - let diag = Diagnostic::find(&err).cloned().unwrap_or_else(|| { - Diagnostic::new(None, Span::new(0, 0), format!("{err:#}")).with_code("call.failed") - }); - if json { - println!( - "{}", - serde_json::json!({"ok": false, "error": diag.to_json()}) - ); - } else { - eprintln!("error: {diag}"); - } - Ok(1) - } - } - } - Commands::Check { - file, - json, - implicit_labels, - narrative_ratio, - legacy_markup, - proof, - } => { - let mut diags = if legacy_markup { - marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || { - marqdo::check::check_path_opts(&file, implicit_labels, proof) - })? - } else { - marqdo::check::check_path_opts(&file, implicit_labels, proof)? - }; - if narrative_ratio { - diags.extend(marqdo::narrative_ratio::check_file(&file)?); - } - let mut errors = 0i32; - for d in &diags { - if matches!(d.severity, marqdo::diagnostics::Severity::Error) { - errors += 1; - } - if json { - println!("{}", d.to_json()); - } else { - println!("{}", d.format_message()); - } - } - if !json { - if diags.is_empty() { - println!("contract check OK: 无契约问题"); - } else { - println!("contract check: {} 条诊断({} error)", diags.len(), errors); - } - } - Ok(errors.min(1)) - } - Commands::Prove { - action, - file, - json, - only, - emit_dir, - report_only, - allow_opaque, - no_strict_types, - require_lean, - lean, - timeout, - no_cache, - heartbeats, - all, - max_files, - fault_inject, - } => { - // 调试注入(§6 A3):仅面向测试的分歧触发器。 - if fault_inject.as_deref() == Some("offline-claim") { - std::env::set_var("MARQDO_PROOF_INJECT_DIVERGENCE", "1"); - } - // 子命令参数覆盖顶层默认;默认动作 = emit + 报告。 - let (file, action_json, action_emit, action_only, action_opaque, action_relax) = - match &action { - Some(ProveAction::Emit { - file, - emit_dir, - json, - only, - allow_opaque, - no_strict_types, - }) => ( - file.clone(), - *json, - Some(emit_dir.clone()), - only.clone(), - allow_opaque.clone(), - *no_strict_types, - ), - Some(ProveAction::Audit { - file, - json, - only, - allow_opaque, - no_strict_types, - }) => ( - file.clone(), - *json, - None, - only.clone(), - allow_opaque.clone(), - *no_strict_types, - ), - Some(ProveAction::Clean { json }) => { - let removed = marqdo::prove::clean()?; - if *json { - println!("{{\"ok\":true,\"removed\":{removed}}}"); - } else { - println!("prove clean: 已删除 {removed} 项(.marqdo/prove)"); - } - return Ok(0); - } - None => (file.clone(), false, Some(emit_dir.clone()), only.clone(), allow_opaque.clone(), no_strict_types), - }; - let file = file.unwrap_or_else(|| PathBuf::from("index.mq.md")); - // emit 目标:显式 --emit 优先;None → mod.rs 用默认 `.marqdo/prove/`。 - // audit 永不写盘;默认动作受 --report-only 控制;emit 子命令总是写盘。 - let emit_target = action_emit.flatten(); - let report_only = matches!(action, Some(ProveAction::Audit { .. })) - || (action.is_none() && report_only); - // emit 子命令只生成不判定(§8.2)。 - let judge = !matches!(action, Some(ProveAction::Emit { .. })); - let no_cache = no_cache || std::env::var_os("MARQDO_PROOF_NO_CACHE").is_some(); - // 目录必须显式 --all(§3.2 proof.need_all)。 - if file.is_dir() { - if !all { - eprintln!( - "error: {} 是目录:逐文件证明请加 --all(--max-files 默认 200)", - file.display() - ); - return Ok(1); - } - let out_json = json || action_json; - let code = run_prove_all( - &file, - max_files, - &marqdo::prove::ProveOptions { - entry: None, - only: action_only, - allow_opaque: action_opaque, - emit_dir: emit_target, - strict_types: !action_relax, - require_lean, - report_only, - judge, - no_cache, - lean, - timeout: std::time::Duration::from_secs(timeout), - max_heartbeats: heartbeats, - }, - out_json, - require_lean, - )?; - return Ok(code); - } - let opts = marqdo::prove::ProveOptions { - entry: None, - only: action_only, - allow_opaque: action_opaque, - emit_dir: emit_target, - strict_types: !action_relax, - require_lean, - report_only, - judge, - no_cache, - lean, - timeout: std::time::Duration::from_secs(timeout), - max_heartbeats: heartbeats, - }; - let report = marqdo::prove::prove_path(&file, &opts)?; - for d in &report.diagnostics { - // 诊断走 stderr(stdout 只放结果/报告)。 - eprintln!("{}", d.format_message()); - } - if json || action_json { - println!("{}", report.to_json()); - } else { - print!("{}", report.to_text()); - } - Ok(report.status.exit_code(require_lean)) - } - Commands::Labels { - paths, - grep, - also_builtin, - group, - json, - count, - baseline, - fail_on_increase, - } => { - let mut words: Vec = match &grep { - Some(spec) => marqdo::label::parse_words(spec), - None => { - let groups: Vec<&str> = match &group { - Some(g) => g - .split(',') - .map(|s| s.trim()) - .filter(|s| !s.is_empty()) - .collect(), - None => marqdo::label::PENDING_GROUPS.to_vec(), - }; - marqdo::label::group_words(&groups) - } - }; - if also_builtin { - let groups: Vec<&str> = match &group { - Some(g) => g - .split(',') - .map(|s| s.trim()) - .filter(|s| !s.is_empty()) - .collect(), - None => marqdo::label::PENDING_GROUPS.to_vec(), - }; - for w in marqdo::label::group_words(&groups) { - if !words.contains(&w) { - words.push(w); - } - } - } - - // Accept the documented shapes `labels pending` / `labels search` - // as no-op words (the flags carry the real intent). - let paths: Vec<&std::path::PathBuf> = paths - .iter() - .filter(|p| { - let s = p.to_string_lossy(); - !(s == "pending" || s == "search") - }) - .collect(); - let mut files: Vec = Vec::new(); - for p in &paths { - files.extend(collect_mq_files(p)?); - } - files.sort(); - files.dedup(); - let mut rows: Vec<(String, u32, String, String, Vec, bool)> = Vec::new(); - for f in &files { - let module = match marqdo::load::load_module(f) { - Ok(m) => m, - Err(_) => continue, // unparsable files are `check`'s problem, not ours - }; - for hit in marqdo::label::search(&module, &words) { - rows.push(( - f.display().to_string(), - hit.site.line, - hit.site.unit.clone(), - hit.site.label.clone(), - hit.words.clone(), - hit.site.has_payload, - )); - } - } - - if json { - let arr: Vec = rows - .iter() - .map(|(file, line, unit, label, words, has_payload)| { - serde_json::json!({ - "file": file, "line": line, "unit": unit, - "label": label, "words": words, "has_payload": has_payload, - }) - }) - .collect(); - println!("{}", serde_json::Value::Array(arr)); - } else if count { - println!("{}", rows.len()); - } else { - for (file, line, unit, label, words, _) in &rows { - println!("{file}:{line} [{unit}] {label} ← {}", words.join(",")); - } - println!( - "label search: {} 命中({} 文件,词={:?})", - rows.len(), - files.len(), - words - ); - } - - // `` M8: ratchet — debt may shrink, never grow. - let current = rows.len(); - let mut violation = false; - if let Some(ledger) = &baseline { - let prior = std::fs::read_to_string(ledger) - .ok() - .and_then(|s| serde_json::from_str::(&s).ok()) - .and_then(|v| v.get("count").and_then(|c| c.as_u64())) - .map(|n| n as usize); - match prior { - None => { - let body = serde_json::json!({"count": current, "words": words}); - if let Some(dir) = ledger.parent() { - if !dir.as_os_str().is_empty() { - let _ = std::fs::create_dir_all(dir); - } - } - std::fs::write(ledger, format!("{body}\n"))?; - if !json && !count { - println!("baseline: 已建立 {current}({})", ledger.display()); - } - } - Some(prior) if current > prior => { - violation = true; - if !count { - println!( - "baseline: {current} > {prior} —— 未完成项增加了 {}({})", - current - prior, - ledger.display() - ); - } - } - Some(prior) => { - if current < prior || std::fs::read_to_string(ledger).is_err() { - let body = serde_json::json!({"count": current, "words": words}); - std::fs::write(ledger, format!("{body}\n"))?; - if !json && !count { - println!( - "baseline: {prior} → {current}(棘轮收紧,{})", - ledger.display() - ); - } - } - } - } - } - if violation && fail_on_increase { - return Ok(1); - } - Ok(0) - } - Commands::Migrate { action } => match action { - MigrateAction::Labels { - paths, - write, - mark, - json, - } => { - let mut reports = Vec::new(); - for p in &paths { - reports.extend(marqdo::migrate::migrate_path_with_options(p, write, mark)?); - } - let (mut idx, mut loops, mut marked, mut applied) = - (0usize, 0usize, 0usize, 0usize); - for r in &reports { - idx += r.indexes; - loops += r.loops; - marked += usize::from(r.mode_marked); - applied += usize::from(r.applied); - } - if json { - let arr: Vec = reports - .iter() - .filter(|r| { - r.indexes > 0 || r.loops > 0 || r.mode_marked || r.note.is_some() - }) - .map(|r| { - serde_json::json!({ - "file": r.file.display().to_string(), - "indexes": r.indexes, - "loops": r.loops, - "mode_marked": r.mode_marked, - "applied": r.applied, - "note": r.note, - }) - }) - .collect(); - println!("{}", serde_json::Value::Array(arr)); - } else { - for r in &reports { - if r.indexes == 0 && r.loops == 0 && !r.mode_marked { - continue; - } - let state = if r.applied { - "written" - } else if r.note.is_some() { - "skipped" - } else { - "would change" - }; - println!( - "{} indexes={} loops={} mode={} {}{}", - r.file.display(), - r.indexes, - r.loops, - if r.mode_marked { - "occlusion" - } else { - "unchanged" - }, - state, - r.note - .as_ref() - .map(|n| format!(" ({n})")) - .unwrap_or_default() - ); - } - println!( - "migrate labels: {idx} index, {loops} loop, {marked} explicit mode, {applied} file written{}", - if write { - "" - } else { - " (dry run; pass --write)" - } - ); - } - Ok(0) - } - MigrateAction::Imports { paths, write, json } => { - let mut reports = Vec::new(); - for p in &paths { - reports.extend(marqdo::migrate::migrate_imports_path(p, write)?); - } - let (mut bindings, mut applied, mut problems) = (0usize, 0usize, 0usize); - for r in &reports { - bindings += r.bindings; - applied += usize::from(r.applied); - if r.note - .as_ref() - .is_some_and(|n| n != "no legacy import one-liners") - && r.bindings == 0 - { - problems += 1; - } - } - if json { - let arr: Vec = reports - .iter() - .filter(|r| { - r.bindings > 0 - || r.note - .as_ref() - .is_some_and(|n| n != "no legacy import one-liners") - }) - .map(|r| { - serde_json::json!({ - "file": r.file.display().to_string(), - "bindings": r.bindings, - "applied": r.applied, - "note": r.note, - }) - }) - .collect(); - println!("{}", serde_json::Value::Array(arr)); - } else { - for r in &reports { - if r.bindings == 0 - && r.note - .as_ref() - .is_some_and(|n| n == "no legacy import one-liners") - { - continue; - } - if r.bindings == 0 { - println!( - "{} skipped ({})", - r.file.display(), - r.note.as_deref().unwrap_or("?") - ); - continue; - } - let state = if r.applied { - "written" - } else if r.note.is_some() { - "skipped" - } else { - "would change" - }; - println!( - "{} bindings={} {}{}", - r.file.display(), - r.bindings, - state, - r.note - .as_ref() - .map(|n| format!(" ({n})")) - .unwrap_or_default() - ); - } - println!( - "migrate imports: {bindings} binding(s), {applied} file written, {problems} problem(s){}", - if write { "" } else { " (dry run; pass --write)" } - ); - } - Ok(0) - } - }, - Commands::Mlsp => { - use std::io::{BufRead, Write}; - let stdin = std::io::stdin(); - let stdout = std::io::stdout(); - let mut out = stdout.lock(); - for line in stdin.lock().lines() { - let line = line?; - if line.trim().is_empty() { - continue; - } - writeln!(out, "{}", marqdo::mlsp::handle_line(&line))?; - out.flush()?; - } - Ok(0) - } - Commands::View { - action, - path, - host, - port, - no_open, - } => match action { - Some(ViewAction::Output { - path: out_path, - out, - no_exec, - snapshot, - }) => { - write_static(OutputOptions { - path: out_path.or(path).unwrap_or_else(|| PathBuf::from(".")), - out_dir: out, - no_exec, - snapshot, - })?; - Ok(0) - } - Some(ViewAction::Capture { - path: out_path, - out, - }) => { - write_capture(CaptureOptions { - path: out_path.or(path).unwrap_or_else(|| PathBuf::from(".")), - out, - })?; - Ok(0) - } - Some(ViewAction::Document { - project, - document, - json, - out, - }) => { - let project = project - .or(path) - .unwrap_or_else(|| PathBuf::from(".")); - let req = marqdo::workbench::DocumentViewRequest { - project, - document, - revision: None, - generation: None, - node_id: None, - include: vec![ - "fragment".into(), - "outline".into(), - "nodes".into(), - "refs".into(), - "diagnostics".into(), - ], - }; - let view = marqdo::workbench::build_document_view(&req).map_err(|e| { - anyhow::anyhow!("{}", e) - })?; - if let Some(out_path) = out { - let fragment = view - .pointer("/render/fragment") - .and_then(|v| v.as_str()) - .unwrap_or(""); - let title = view - .pointer("/document/title") - .and_then(|v| v.as_str()) - .unwrap_or("DocumentView"); - let html = format!( - "{title}
      {fragment}
      " - ); - std::fs::write(&out_path, html)?; - if json { - println!("{}", serde_json::to_string_pretty(&view)?); - } else { - println!("wrote {}", out_path.display()); - } - } else { - println!("{}", serde_json::to_string_pretty(&view)?); - } - let _ = json; - Ok(0) - } - None => { - serve(ViewOptions { - path: path.unwrap_or_else(|| PathBuf::from(".")), - host, - port, - open_browser: !no_open, - })?; - Ok(0) - } - }, - Commands::Debug { - path, - host, - port, - no_open, - } => { - serve_debug(DebugOptions { - path: path.unwrap_or_else(|| PathBuf::from(".")), - host, - port, - open_browser: !no_open, - })?; - Ok(0) - } - Commands::Catalog { - path, - out, - no_knowledge, - } - | Commands::Sync { - path, - out, - no_knowledge, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - write_catalog(CatalogOptions { - path: path.clone(), - out_dir: out.clone(), - })?; - if !no_knowledge { - write_knowledge(KnowledgeOptions { path, out_dir: out })?; - } - Ok(0) - } - Commands::Knowledge { - action, - path, - out, - json, - refresh, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - match action.unwrap_or(KnowledgeAction::Compile) { - KnowledgeAction::Compile => { - write_knowledge(KnowledgeOptions { path, out_dir: out })?; - Ok(0) - } - KnowledgeAction::Replay { certificate } => { - let root=if path.is_file(){ - path.parent().filter(|p|!p.as_os_str().is_empty()) - .unwrap_or_else(||std::path::Path::new(".")).to_path_buf() - }else{path.clone()}; - let compiled=marqdo::sema::ir::compile_project( - &marqdo::sema::ir::CompileOptions{ - project_root:root, - entry:path.is_file().then_some(path), - lock_mode:marqdo::sema::ir::LockMode::Off - })?; - let lean=marqdo::prove::driver::Toolchain::discover(None)? - .ok_or_else(||anyhow::anyhow!("proof.compose_lean_missing"))?; - let proof=marqdo::knowledge::composition::replay( - &compiled,&certificate,&lean)?; - if json{println!("{proof}");}else{ - println!("{}",serde_json::to_string_pretty(&proof)?); - } - Ok(0) - } - KnowledgeAction::Compose { strict } => { - let root=if path.is_file(){ - path.parent().filter(|p|!p.as_os_str().is_empty()) - .unwrap_or_else(||std::path::Path::new(".")).to_path_buf() - }else{path.clone()}; - let compiled=marqdo::sema::ir::compile_project( - &marqdo::sema::ir::CompileOptions{ - project_root:root, - entry:path.is_file().then_some(path), - lock_mode:marqdo::sema::ir::LockMode::Off - })?; - let lean=marqdo::prove::driver::Toolchain::discover(None)? - .ok_or_else(||anyhow::anyhow!( - "proof.compose_lean_missing: Lean required"))?; - let result=marqdo::knowledge::composition::prove( - &compiled,&out.join("modular"),&lean)?; - let failures=result["results"].as_array().map_or(true,|entries| - entries.is_empty()||entries.iter().any(|e| - e["status"]!="lean_kernel_proved_model")); - if json {println!("{result}");} else { - println!("{}",serde_json::to_string_pretty(&result)?); - } - Ok(if strict && failures {2} else {0}) - } - KnowledgeAction::ProofDeps { strict,verify } => { - let semantic_root=if path.is_file() { - path.parent().filter(|p|!p.as_os_str().is_empty()) - .unwrap_or_else(||std::path::Path::new(".")).to_path_buf() - } else {path.clone()}; - let compiled=marqdo::sema::ir::compile_project( - &marqdo::sema::ir::CompileOptions { - project_root:semantic_root, - entry:path.is_file().then_some(path), - lock_mode:marqdo::sema::ir::LockMode::Off, - })?; - let mut receipts=marqdo::knowledge::proof::index_links( - &out.join("prove"),&compiled.semantics); - let toolchain=if verify { - Some(marqdo::prove::driver::Toolchain::discover(None)? - .ok_or_else(||anyhow::anyhow!( - "proof.modular_lean_missing: Lean is required for --verify"))?) - } else {None}; - if let Some(lean)=toolchain.as_ref(){ - marqdo::knowledge::proof::replay_index( - &out.join("prove"),&mut receipts,lean, - std::time::Duration::from_secs(120))?; - } - let replayed=receipts["claims"].as_array().map_or(0,|records| - records.iter().filter(|c|c["kernel_replayed"]==true).count()); - let draft=marqdo::knowledge::modular::analyze( - &compiled.semantics,&receipts); - let mut accepted=std::collections::BTreeSet::new(); - let verified_toolchain=toolchain.as_ref().map(|t|t.version.clone()); - if verify { - let goals:Vec<(String,marqdo::knowledge::vc::Goal)>=draft["obligations"] - .as_array().into_iter().flat_map(|rows|rows.iter()) - .flat_map(|row|row["contracts"].as_array().into_iter() - .flat_map(|contracts|contracts.iter())) - .filter_map(|c|{ - if c["callee_certificate_valid"]!=true - || c["closed_host_check"]!=true {return None} - Some(( - c["precondition_goal_key"].as_str()?.to_string(), - marqdo::knowledge::vc::Goal{ - holds:true, - proposition:c["lean_proposition"].as_str()?.to_string() - } - )) - }).collect(); - if !goals.is_empty(){ - let toolchain=toolchain.as_ref().expect("verify implies Lean"); - let target=out.join("modular"); - std::fs::create_dir_all(&target)?; - let lean_file=target.join("closed-goals.lean"); - let content=marqdo::knowledge::vc::emit_lean(&goals); - std::fs::write(&lean_file,content)?; - marqdo::prove::driver::check_closed_goals( - &toolchain,&lean_file,std::time::Duration::from_secs(120))?; - accepted.extend(goals.into_iter().map(|(id,_)|id)); - } - } - let mut symbolic_checked=0usize; - if let Some(lean)=toolchain.as_ref(){ - let symbolic:Vec<(String,marqdo::knowledge::symbolic::SymbolicGoal)>= - compiled.semantics.bound_calls.iter().flat_map(|call|{ - compiled.semantics.claims.iter() - .filter(|c|c.owner==call.target) - .filter(|c|receipts["claims"].as_array().is_some_and(|rows| - rows.iter().any(|r| - r["claim_anchor_id"]==c.anchor_id - && r["status"]=="proved" - && r["usable"]==true))) - .filter_map(|c|Some(( - c.anchor_id.clone(), - marqdo::knowledge::symbolic::plan( - &compiled.semantics,call,c.premise.as_deref()?)? - ))) - .filter(|(_,g)|g.abstract_integer_model_supported) - .collect::>() - }).collect(); - if !symbolic.is_empty(){ - let target=out.join("modular"); - std::fs::create_dir_all(&target)?; - let path=target.join("symbolic-path-goals.lean"); - std::fs::write(&path, - marqdo::knowledge::symbolic::emit_lean(&symbolic))?; - marqdo::prove::driver::check_closed_goals(lean,&path, - std::time::Duration::from_secs(120))?; - symbolic_checked=symbolic.len(); - } - } - let mut report=marqdo::knowledge::modular::analyze_with_verified( - &compiled.semantics,&receipts,&accepted); - report["symbolic_path_lean_model_proved"]= - serde_json::json!(symbolic_checked); - report["symbolic_proof_scope"]= - serde_json::json!("integer_path_model_not_runtime_equivalence"); - report["lean_preconditions_verified"]=serde_json::json!(accepted.len()); - report["lean_toolchain"]=serde_json::json!(verified_toolchain); - report["lean_receipts_replayed"]=serde_json::json!(replayed); - if json { - println!("{report}"); - } else { - println!("{}",serde_json::to_string_pretty(&report)?); - } - Ok(if strict && report["audit_passes"]!=true {2} else {0}) - } - KnowledgeAction::Inspect { symbol } => { - // A supplied directory is an explicit compilation scope; - // a supplied file inherits the nearest project boundary. - let project = if path.is_dir() { - marqdo::project::ProjectRoot::new(&path)? - } else { - marqdo::project::ProjectRoot::discover(&path)? - }; - let index = marqdo::sema::ProjectIndex::build(project)?; - let candidates: Vec<_> = if symbol.starts_with("mq://") { - index - .symbols() - .iter() - .filter(|item| item.id.as_str() == symbol) - .collect() - } else { - index.symbols_named(&symbol) - }; - if candidates.is_empty() { - anyhow::bail!( - "no semantic symbol matching `{symbol}` in project {}", - index.root().path().display() - ); - } - if json { - println!( - "{}", - serde_json::json!({ - "project": index.project_id(), - "query": symbol, - "ambiguous": candidates.len() > 1, - "symbols": candidates.iter().map(|item| serde_json::json!({ - "id": item.id.as_str(), - "module": item.module.as_str(), - "kind": item.kind.as_str(), - "callable": item.callable.map(|kind| kind.as_str()), - "name": item.name, - "declaration_path": item.declaration_path, - "source": { - "file": item.source, - "line": item.line, - }, - })).collect::>(), - }) - ); - } else { - for item in &candidates { - println!( - "{}\n {}{} {} · module {}\n {}:{}", - item.id, - item.kind.as_str(), - item.callable - .map(|kind| format!(" ({})", kind.as_str())) - .unwrap_or_default(), - item.declaration_path.join("."), - item.module, - item.source.display(), - item.line, - ); - } - if candidates.len() > 1 { - println!( - "ambiguous: {} symbols named `{symbol}`; use one full mq:// URI", - candidates.len() - ); - } - } - Ok(0) - } - KnowledgeAction::Resolve { reference, from } => { - let from = from - .as_deref() - .or_else(|| path.is_file().then_some(path.as_path())); - let index = marqdo::sema::ProjectIndex::build(if path.is_dir() { - marqdo::project::ProjectRoot::new(&path)? - } else { - marqdo::project::ProjectRoot::discover(&path)? - })?; - let symbol = resolve_knowledge_reference(&index, &reference, from)?; - let instance_only = - symbol.callable == Some(marqdo::sema::CallableKind::InstanceMethod); - if json { - println!( - "{}", - serde_json::json!({ - "reference": reference, - "resolution": if instance_only { "instance_only" } else { "symbol" }, - "symbol": { - "id": symbol.id.as_str(), - "module": symbol.module.as_str(), - "kind": symbol.kind.as_str(), - "callable": symbol.callable.map(|kind| kind.as_str()), - "declaration_path": symbol.declaration_path, - "source": { "file": symbol.source, "line": symbol.line }, - }, - }) - ); - } else { - println!("{}", symbol.id); - println!(" {}", symbol.declaration_path.join(".")); - println!(" {}:{}", symbol.source.display(), symbol.line); - if instance_only { - println!(" instance_only: call through an instance receiver"); - } - } - Ok(if instance_only { 1 } else { 0 }) - } - KnowledgeAction::Lock { update, strict } => { - let semantic_root = if path.is_file() { - path.parent() - .unwrap_or_else(|| std::path::Path::new(".")) - .to_path_buf() - } else { - path.clone() - }; - let compilation = - marqdo::sema::compile_project(&marqdo::sema::CompileOptions { - project_root: semantic_root, - entry: path.is_file().then(|| path.clone()), - lock_mode: if strict { - marqdo::sema::LockMode::Strict - } else { - marqdo::sema::LockMode::Check - }, - })?; - if update { - marqdo::sema::update_links_lock(&out, &compilation.semantics)?; - let body = serde_json::json!({"schema_version": 1, "status": "updated", "path": out.join("links.lock.json")}); - if json { - println!("{body}"); - } else { - println!( - "knowledge lock updated: {}", - out.join("links.lock.json").display() - ); - } - Ok(0) - } else { - let report = marqdo::sema::check_links_lock(&out, &compilation.semantics)?; - if json { - println!("{}", report.to_json()); - } else { - println!("knowledge lock: {}", report.status); - for id in report - .missing - .iter() - .chain(report.changed.iter()) - .chain(report.removed.iter()) - { - println!(" {id}"); - } - } - Ok(if strict && !report.is_clean() { 3 } else { 0 }) - } - } - KnowledgeAction::Impact { query } => { - let semantic_root = if path.is_file() { - path.parent() - .unwrap_or_else(|| std::path::Path::new(".")) - .to_path_buf() - } else { - path.clone() - }; - let compilation = - marqdo::sema::compile_project(&marqdo::sema::CompileOptions { - project_root: semantic_root, - entry: path.is_file().then(|| path.clone()), - lock_mode: marqdo::sema::LockMode::Off, - })?; - let report = marqdo::sema::semantic_impact(&compilation.semantics, &query); - if json { - println!("{report}"); - } else { - for item in report["affected"].as_array().into_iter().flatten() { - println!( - "{} {}", - item["artifact_id"].as_str().unwrap_or(""), - item["display_name"].as_str().unwrap_or("") - ); - } - } - Ok(if report["resolved"].as_bool() == Some(true) { - 0 - } else { - 1 - }) - } - KnowledgeAction::Adjudicate { - artifact, - policy, - fail, - } => { - let semantic_root = if path.is_file() { - path.parent() - .unwrap_or_else(|| std::path::Path::new(".")) - .to_path_buf() - } else { - path.clone() - }; - let report = marqdo::mlsp::adjudicate_project( - &semantic_root, - artifact.as_deref(), - &policy, - ) - .map_err(|e| anyhow::anyhow!("{}", e))?; - if json { - println!("{report}"); - } else { - println!( - "knowledge adjudicate policy={} may_bind_all={} count={}", - policy, - report["may_bind_all"], - report["count"] - ); - for item in report["reports"].as_array().into_iter().flatten() { - println!( - " {} evidence={} may_bind={} may_publish={}", - item["artifact_id"].as_str().unwrap_or(""), - item["verification"]["evidence"].as_str().unwrap_or(""), - item["may_bind"], - item["may_publish"] - ); - } - } - Ok( - if fail && report["may_bind_all"].as_bool() != Some(true) { - 1 - } else { - 0 - }, - ) - } - KnowledgeAction::Preflight { - task, - min_candidates, - allow_create_after, - } => { - let graph = graph_for_query(&path, &out, refresh)?; - let budget = ReuseBudget { - min_candidates, - allow_create_after, - ..ReuseBudget::default() - }; - let reuse = resolve(&graph, &task, &budget); - let pf = preflight_from_reuse(&graph, &task, &reuse, Some(&out))?; - let _ = compile_policy(&out, &task, &reuse); - if json { - println!("{}", preflight_json(&pf)); - } else { - print!("{}", format_preflight_yaml(&pf)); - } - Ok( - if pf.create_allowed || pf.decision == "REUSE" || pf.decision == "ADAPT" { - 0 - } else { - 2 - }, - ) - } - KnowledgeAction::Record { - decision, - duplicated, - } => { - let m = record_decision(&out, &decision, duplicated)?; - if json { - println!("{}", m.to_json()); - } else { - println!( - "reuse_ratio={:.2} adapt_ratio={:.2} novel_ratio={:.2} duplication_rate={:.2}", - m.reuse_ratio(), - m.adapt_ratio(), - m.novel_ratio(), - m.duplication_rate() - ); - } - Ok(0) - } - KnowledgeAction::Learn { - task, - failed_approach, - failure, - correct_approach, - decision_title, - decision_body, - constraint_title, - constraint_body, - } => { - let written = learn( - &out, - &LearnInput { - task, - failed_approach, - failure, - correct_approach, - decision_title, - decision_body, - constraint_title, - constraint_body, - }, - )?; - for p in written { - println!("{}", p.display()); - } - Ok(0) - } - } - } - Commands::Find { - query, - path, - out, - limit, - json, - refresh, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - let graph = graph_for_query(&path, &out, refresh)?; - let hits = find(&graph, &query, limit); - if json { - println!("{}", find_json(&query, &hits)); - } else { - print!("{}", format_find_text(&query, &hits, &graph)); - } - Ok(0) - } - Commands::Reuse { - task, - path, - out, - preflight: do_preflight, - min_candidates, - allow_create_after, - json, - refresh, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - let graph = graph_for_query(&path, &out, refresh)?; - let budget = ReuseBudget { - min_candidates, - allow_create_after, - ..ReuseBudget::default() - }; - let result = resolve(&graph, &task, &budget); - let _ = compile_policy(&out, &task, &result); - if do_preflight { - let _ = preflight_from_reuse(&graph, &task, &result, Some(&out))?; - } - if json { - println!("{}", reuse_json(&task, &result)); - } else { - print!("{}", format_reuse_text(&task, &result)); - } - Ok(0) - } - Commands::Impact { - paths, - root, - out, - json, - refresh, - } => { - let graph = graph_for_query(&root, &out, refresh)?; - let path_strs: Vec = paths - .iter() - .map(|p| p.to_string_lossy().replace('\\', "/")) - .collect(); - let report = impact(&graph, &path_strs); - if json { - println!("{}", impact_json(&report)); - } else { - print!("{}", format_impact_text(&report)); - } - Ok(0) - } - Commands::Conflicts { - path, - out, - json, - fail, - refresh, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - let graph = graph_for_query(&path, &out, refresh)?; - let items = find_conflicts(&graph); - if json { - println!("{}", conflicts_json(&items)); - } else { - print!("{}", format_conflicts_text(&items)); - } - Ok(if fail && !items.is_empty() { 1 } else { 0 }) - } - Commands::Stale { - path, - out, - json, - fail, - refresh, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - let graph = graph_for_query(&path, &out, refresh)?; - let items = find_stale(&graph, &path); - if json { - println!("{}", stale_json(&items)); - } else { - print!("{}", format_stale_text(&items)); - } - Ok(if fail && !items.is_empty() { 1 } else { 0 }) - } - Commands::Duplicate { - path, - out, - threshold, - fail, - json, - refresh, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - let graph = graph_for_query(&path, &out, refresh)?; - let pairs = find_duplicates(&graph.symbols, threshold); - if json { - println!( - "{}", - serde_json::json!({ - "threshold": threshold, - "duplicates": pairs.iter().map(|p| serde_json::json!({ - "left": p.left, - "right": p.right, - "similarity": p.similarity, - "left_resource": p.left_resource, - "right_resource": p.right_resource, - })).collect::>(), - }) - ); - } else { - print!("{}", format_duplicates_text(&pairs)); - } - if fail && !pairs.is_empty() { - Ok(1) - } else { - Ok(0) - } - } - Commands::Verify { - path, - out, - json, - fail_on_warning, - refresh, - } => { - let path = path.unwrap_or_else(|| PathBuf::from(".")); - let graph = graph_for_query(&path, &out, refresh)?; - let issues = verify(&graph); - if json { - println!("{}", verify_json(&issues)); - } else { - print!("{}", format_verify_text(&issues)); - } - let errors = issues.iter().filter(|i| i.severity == "error").count(); - let warnings = issues.iter().filter(|i| i.severity == "warning").count(); - Ok(if errors > 0 || (fail_on_warning && warnings > 0) { - 1 - } else { - 0 - }) - } - Commands::Ext { action } => { - match action { - ExtAction::List => list_ext()?, - ExtAction::Add { name } => add_ext(&name)?, - ExtAction::Remove { name } => remove_ext(&name)?, - } - Ok(0) - } - Commands::Version { check } => { - if check { - marqdo::version_check::check_latest().map_err(|e| anyhow::anyhow!(e))?; - } else { - marqdo::version_check::print_version(); - } - Ok(0) - } - Commands::Wasm { action } => match action { - WasmAction::Build { out } => { - marqdo::wasm_cli::build_wasm(&out)?; - Ok(0) - } - }, - } -} diff --git a/src/migrate.rs b/src/migrate.rs deleted file mode 100755 index c72ab49..0000000 --- a/src/migrate.rs +++ /dev/null @@ -1,863 +0,0 @@ -//! `` M7: migrate legacy `[键](集合)` indexes and `- [项](集合)` loops to the -//! purity forms (`access(集合, 键)` and `- [描述](遍历 集合 为 项)`), then mark -//! the file `markup: occlusion`. -//! -//! Also: nested YAML `import:` migration (`marqdo migrate imports`). -//! -//! Safety model (labels): **transform, re-parse, prove equivalence, then write.** -//! The transformed file is parsed in occlusion mode and *denormalized* back to -//! the legacy AST shape; if the denormalized AST is not byte-identical (Debug) -//! to the original, the file is left untouched and reported. - -use std::path::{Path, PathBuf}; - -use crate::ast::{Arg, BranchArm, Expr, Function, IndexKey, Module, Stmt}; -use crate::parse::{is_legacy_import_oneliner, parse_import_binding}; - -/// Outcome of migrating one file (labels). -#[derive(Debug, Clone)] -pub struct FileReport { - pub file: PathBuf, - pub indexes: usize, - pub loops: usize, - /// Whether this file will receive (or already has) an explicit - /// `markup: occlusion` declaration. - pub mode_marked: bool, - pub applied: bool, - pub note: Option, -} - -/// Outcome of migrating one-liner imports → nested `import:` / `导入:`. -#[derive(Debug, Clone)] -pub struct ImportFileReport { - pub file: PathBuf, - pub bindings: usize, - pub applied: bool, - pub note: Option, -} - -fn has_marker(source: &str) -> bool { - let mut lines = source.lines(); - if lines.next().map(|l| l.trim_end()) != Some("---") { - return false; - } - for line in lines { - let t = line.trim(); - if t == "---" { - break; - } - let lower = t.to_ascii_lowercase(); - if lower.starts_with("markup:") || t.starts_with("标记:") { - return lower.contains("occlusion") - || lower.contains("purity") - || t.contains("遮蔽") - || t.contains("纯度"); - } - } - false -} - -fn add_marker(source: &str) -> String { - if has_marker(source) { - return source.to_string(); - } - // A classic marker is an explicit request to migrate; replace it rather - // than adding conflicting keys to the same frontmatter block. - if source.starts_with("---\n") { - let mut lines: Vec = source.lines().map(str::to_string).collect(); - for (index, line) in lines.iter_mut().enumerate() { - let lower = line.trim().to_ascii_lowercase(); - if lower.starts_with("markup:") || line.trim().starts_with("标记:") { - *line = "markup: occlusion".to_string(); - let mut out = lines.join("\n"); - if source.ends_with('\n') { - out.push('\n'); - } - return out; - } - if line.trim() == "---" && index != 0 { - break; - } - } - } - if let Some(rest) = source.strip_prefix("---\n") { - format!("---\nmarkup: occlusion\n{rest}") - } else { - format!("---\nmarkup: occlusion\n---\n\n{source}") - } -} - -/// Quote a static index key as a text argument. -fn quote_key(key: &str) -> String { - let escaped = key.replace('\\', "\\\\").replace('"', "\\\""); - format!("\"{escaped}\"") -} - -/// Rewrite every link-shaped index in one code line. Returns `(new_line, count)`. -/// -/// Works **innermost first**: chained indexes (`[content]([1]([messages](req)))`) -/// must be rewritten from the inside out, otherwise outer rewrites invalidate the -/// inner spans. -fn rewrite_indexes(line: &str) -> (String, usize) { - let mut cur = line.to_string(); - let mut total = 0usize; - for _ in 0..256 { - match rewrite_one_innermost(&cur) { - Some(next) => { - cur = next; - total += 1; - } - None => break, - } - } - (cur, total) -} - -/// Rewrite the first index whose key contains no nested `[`, returning the new line. -fn rewrite_one_innermost(line: &str) -> Option { - let chars: Vec = line.chars().collect(); - let mut i = 0usize; - let mut in_bt = false; - let mut in_str = false; - while i < chars.len() { - let c = chars[i]; - if in_str { - if c == '\\' { - i += 2; - continue; - } - if c == '"' { - in_str = false; - } - i += 1; - continue; - } - if in_bt { - if c == '`' { - in_bt = false; - } - i += 1; - continue; - } - match c { - '`' => { - in_bt = true; - i += 1; - continue; - } - '"' => { - in_str = true; - i += 1; - continue; - } - _ => {} - } - if c == '[' && chars.get(i + 1) != Some(&'^') { - if let Some(close) = match_close(&chars, i, '[', ']') { - let key: String = chars[i + 1..close].iter().collect(); - let nested = key.contains('['); - if !nested && chars.get(close + 1) == Some(&'(') { - if let Some(paren) = match_close(&chars, close + 1, '(', ')') { - let coll: String = chars[close + 2..paren].iter().collect(); - // Already migrated (`[k](access(…))`) — never rewrite twice. - if coll.trim_start().starts_with("access(") { - i += 1; - continue; - } - let k = key.trim(); - let backticked = k.starts_with('`') && k.ends_with('`') && k.len() >= 2; - let label = if backticked { &k[1..k.len() - 1] } else { k }; - let key_arg = if backticked { - k.to_string() - } else { - quote_key(k) - }; - let replaced = format!("[{label}](access({}, {key_arg}))", coll.trim()); - let mut out = String::new(); - out.extend(chars[..i].iter()); - out.push_str(&replaced); - out.extend(chars[paren + 1..].iter()); - return Some(out); - } - } - } - } - i += 1; - } - None -} - -/// Rewrite only the **code** parts of a line. -/// -/// Table rows are the important case: a cell is code only when it starts with -/// `**…**`; everything else is prose (markdown links live there and must not be -/// rewritten). Non-table code lines are rewritten whole. -fn rewrite_code_segments(line: &str) -> (String, usize) { - let trimmed = line.trim_start(); - if !trimmed.starts_with('|') { - return rewrite_indexes(line); - } - let mut out = String::with_capacity(line.len()); - let mut total = 0usize; - let mut rest = line; - while let Some(pos) = rest.find('|') { - let (cell, tail) = rest.split_at(pos); - out.push_str(cell); - out.push('|'); - rest = &tail[1..]; - } - // Trailing part without a separator. - out.push_str(rest); - // Second pass: rewrite only `**…**` runs inside the rebuilt line. - let mut result = String::with_capacity(out.len()); - let mut s = out.as_str(); - while let Some(open) = s.find("**") { - result.push_str(&s[..open + 2]); - let after = &s[open + 2..]; - let Some(close) = after.find("**") else { - result.push_str(after); - return (result, total); - }; - let (inner, tail) = after.split_at(close); - let (rewritten, n) = rewrite_indexes(inner); - total += n; - result.push_str(&rewritten); - result.push_str("**"); - s = &tail[2..]; - } - result.push_str(s); - (result, total) -} - -/// Matching closer index for `open` at `start`, honouring nesting of the pair. -fn match_close(bytes: &[char], start: usize, open: char, close: char) -> Option { - let mut depth = 0i32; - let mut i = start; - let mut in_bt = false; - let mut in_str = false; - while i < bytes.len() { - let c = bytes[i]; - if in_str { - if c == '\\' { - i += 2; - continue; - } - if c == '"' { - in_str = false; - } - i += 1; - continue; - } - if in_bt { - if c == '`' { - in_bt = false; - } - i += 1; - continue; - } - match c { - '`' => in_bt = true, - '"' => in_str = true, - c if c == open => depth += 1, - c if c == close => { - depth -= 1; - if depth == 0 { - return Some(i); - } - } - _ => {} - } - i += 1; - } - None -} - -/// Rewrite a legacy loop line `- [x](c)` → `- [x](遍历 c 为 x)`. -fn rewrite_loop(line: &str) -> Option { - let trimmed = line.trim_start(); - let rest = trimmed.strip_prefix('-')?.trim_start(); - if !rest.starts_with('[') { - return None; - } - let end = rest.find(']')?; - let item = rest[1..end].trim(); - let after = rest[end + 1..].trim(); - if !after.starts_with('(') || !after.ends_with(')') { - return None; - } - let coll = after[1..after.len() - 1].trim(); - if item.is_empty() || coll.is_empty() || says_foreach(coll) { - return None; - } - let indent = &line[..line.len() - trimmed.len()]; - let shown = item.trim_matches('`').to_string(); - Some(format!("{indent}- [{shown}](遍历 {coll} 为 {item})")) -} - -fn says_foreach(s: &str) -> bool { - s.starts_with("遍历") || s.starts_with("for ") -} - -// --------------------------------------------------------------------------- -// Equivalence proof: denormalize the migrated AST back to the legacy shape. -// --------------------------------------------------------------------------- - -fn denorm_expr(expr: &Expr) -> Expr { - match expr { - Expr::Occluded { label, payload } => match payload.as_deref() { - Some(Expr::Call(call)) - if (call.callee == "access" || call.callee == "取" || call.callee == "取值") - && call.args.len() == 2 => - { - let mut it = call.args.iter(); - let (base, key) = match (it.next(), it.next()) { - (Some(Arg::Positional(b)), Some(Arg::Positional(k))) => (b, k), - _ => return expr.clone(), - }; - let key_label = match key { - Expr::Literal(crate::ast::Literal::Text(t)) if t == label => { - Some(IndexKey::Lit(t.clone())) - } - Expr::Var(v) if v == label => Some(IndexKey::Var(v.clone())), - _ => None, - }; - match key_label { - Some(k) => Expr::Index { - base: Box::new(denorm_expr(base)), - label: k, - }, - None => expr.clone(), - } - } - Some(inner) => Expr::Occluded { - label: label.clone(), - payload: Some(Box::new(denorm_expr(inner))), - }, - None => expr.clone(), - }, - Expr::Unary { op, expr } => Expr::Unary { - op: *op, - expr: Box::new(denorm_expr(expr)), - }, - Expr::Binary { op, left, right } => Expr::Binary { - op: *op, - left: Box::new(denorm_expr(left)), - right: Box::new(denorm_expr(right)), - }, - Expr::Call(call) => { - let mut c = call.clone(); - c.args = c - .args - .into_iter() - .map(|a| match a { - Arg::Positional(e) => Arg::Positional(denorm_expr(&e)), - Arg::Named { name, value } => Arg::Named { - name, - value: denorm_expr(&value), - }, - }) - .collect(); - Expr::Call(c) - } - Expr::List(items) => Expr::List(items.iter().map(denorm_expr).collect()), - Expr::Map(pairs) => Expr::Map( - pairs - .iter() - .map(|(k, v)| (k.clone(), denorm_expr(v))) - .collect(), - ), - Expr::Index { base, label } => Expr::Index { - base: Box::new(denorm_expr(base)), - label: label.clone(), - }, - other => other.clone(), - } -} - -fn denorm_stmt(stmt: &Stmt) -> Stmt { - match stmt { - Stmt::Assign { - name, - value, - span, - end_line, - } => Stmt::Assign { - name: name.clone(), - value: denorm_expr(value), - span: *span, - end_line: *end_line, - }, - Stmt::Return { value, span } => Stmt::Return { - value: denorm_expr(value), - span: *span, - }, - Stmt::Expr { value, span } => Stmt::Expr { - value: denorm_expr(value), - span: *span, - }, - Stmt::Call { call, span } => { - let mut c = call.clone(); - c.args = c - .args - .into_iter() - .map(|a| match a { - Arg::Positional(e) => Arg::Positional(denorm_expr(&e)), - Arg::Named { name, value } => Arg::Named { - name, - value: denorm_expr(&value), - }, - }) - .collect(); - Stmt::Call { - call: c, - span: *span, - } - } - Stmt::Branch { arms, span } => Stmt::Branch { - arms: arms - .iter() - .map(|a| BranchArm { - condition: a.condition.as_ref().map(denorm_expr), - body: a.body.iter().map(denorm_stmt).collect(), - }) - .collect(), - span: *span, - }, - Stmt::While { - condition, - body, - span, - } => Stmt::While { - condition: denorm_expr(condition), - body: body.iter().map(denorm_stmt).collect(), - span: *span, - }, - Stmt::ForEach { - item, - collection, - label: _, - body, - span, - } => Stmt::ForEach { - item: item.clone(), - collection: collection.clone(), - label: None, - body: body.iter().map(denorm_stmt).collect(), - span: *span, - }, - } -} - -fn denorm_fun(fun: &Function) -> Function { - let mut f = fun.clone(); - f.body = fun.body.iter().map(denorm_stmt).collect(); - f.children = fun.children.iter().map(denorm_fun).collect(); - f -} - -/// Replace every `line: ` with `line: #` so that inserting the frontmatter -/// marker (which shifts every line by one) does not defeat the comparison. -fn strip_line_numbers(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut rest = s; - while let Some(i) = rest.find("line: ") { - out.push_str(&rest[..i + 6]); - let tail = &rest[i + 6..]; - let end = tail - .find(|c: char| !c.is_ascii_digit()) - .unwrap_or(tail.len()); - out.push('#'); - rest = &tail[end..]; - } - out.push_str(rest); - out -} - -fn shape(module: &Module) -> String { - let raw = format!( - "{:?}", - module.functions.iter().map(denorm_fun).collect::>() - ); - strip_line_numbers(&raw) -} - -// --------------------------------------------------------------------------- -// Entry point -// --------------------------------------------------------------------------- - -/// Migrate one file. `write=false` performs a dry run (still fully verified). -pub fn migrate_file(path: &Path, write: bool) -> anyhow::Result { - migrate_file_with_options(path, write, false) -} - -/// Migrate one file and, when `mark_all` is set, give a file that has no -/// legacy index an explicit new-syntax declaration too. This is the mode used -/// for shipped libraries: their behavior must not depend on the process -/// default even if they happen not to contain a link-shaped index today. -pub fn migrate_file_with_options( - path: &Path, - write: bool, - mark_all: bool, -) -> anyhow::Result { - let source = std::fs::read_to_string(path)?; - let mut report = FileReport { - file: path.to_path_buf(), - indexes: 0, - loops: 0, - mode_marked: false, - applied: false, - note: None, - }; - if has_marker(&source) { - report.mode_marked = true; - report.note = Some("already marked `markup: occlusion`".into()); - return Ok(report); - } - - // Migration is deliberately syntax-only. Resolving imports here makes a - // library's safe local rewrite depend on the host checkout, unavailable - // plugins, or a transitive dependency that is itself being migrated. - // Import resolution and both execution backends are verified afterwards by - // the repository migration suite. - let original = crate::parse::expr::with_markup(crate::parse::expr::Markup::Classic, || { - crate::parse::parse_source(&source) - })?; - - let classified = crate::lex::classify_source(&source); - let mut lines: Vec = source.lines().map(|l| l.to_string()).collect(); - for cl in &classified { - if cl.kind != crate::lex::LineKind::Code { - continue; - } - let idx = (cl.line_no as usize).saturating_sub(1); - let Some(line) = lines.get(idx).cloned() else { - continue; - }; - if let Some(new_loop) = rewrite_loop(&line) { - report.loops += 1; - lines[idx] = new_loop; - continue; - } - let (new_line, n) = rewrite_code_segments(&line); - if n > 0 { - report.indexes += n; - lines[idx] = new_line; - } - } - if report.indexes == 0 && report.loops == 0 && !mark_all { - report.note = Some("no legacy index or loop".into()); - return Ok(report); - } - - let mut body = lines.join("\n"); - if source.ends_with('\n') { - body.push('\n'); - } - let migrated = add_marker(&body); - report.mode_marked = true; - - // Prove equivalence: the migrated file, parsed in occlusion mode and - // denormalized, must be structurally identical to the original. - let reparsed = crate::parse::expr::with_markup(crate::parse::expr::Markup::Occlusion, || { - crate::parse::parse_source(&migrated) - })?; - if std::env::var("MARQDO_MIGRATE_DEBUG").is_ok() { - eprintln!("ORIG: {}", shape(&original)); - eprintln!("MIGR: {}", shape(&reparsed)); - } - if shape(&original) != shape(&reparsed) { - report.note = Some("equivalence check failed — file left untouched".into()); - return Ok(report); - } - - if write { - std::fs::write(path, &migrated)?; - report.applied = true; - } - Ok(report) -} - -/// Recursively migrate every `*.mq.md` under `path`. -pub fn migrate_path(path: &Path, write: bool) -> anyhow::Result> { - migrate_path_with_options(path, write, false) -} - -/// Recursive counterpart of [`migrate_file_with_options`]. -pub fn migrate_path_with_options( - path: &Path, - write: bool, - mark_all: bool, -) -> anyhow::Result> { - let files = crate::migrate::collect_files(path); - let mut out = Vec::new(); - for f in files { - match migrate_file_with_options(&f, write, mark_all) { - Ok(r) => out.push(r), - Err(e) => out.push(FileReport { - file: f, - indexes: 0, - loops: 0, - mode_marked: false, - applied: false, - note: Some(format!("load failed: {e:#}")), - }), - } - } - Ok(out) -} - -/// Rewrite frontmatter one-liner `import bind:target` / `导入 bind:target` into a -/// nested YAML map. Returns `(new_source, binding_count)` or `None` if unchanged. -pub fn rewrite_import_frontmatter(source: &str) -> Result, String> { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return Ok(None); - } - let mut fm_end = None; - for (i, line) in lines.iter().enumerate().skip(1) { - if line.trim() == "---" { - fm_end = Some(i); - break; - } - } - let Some(fm_end) = fm_end else { - return Ok(None); - }; - - let mut keyword: Option<&'static str> = None; - let mut entries: Vec<(String, String)> = Vec::new(); - let mut legacy_idxs: Vec = Vec::new(); - let mut has_nested = false; - let mut nested_kw: Option<&'static str> = None; - - for i in 1..fm_end { - let t = lines[i].trim(); - // Nested header with empty RHS only (`import:` / `导入:`) - if let Some(rest) = t.strip_prefix("import:") { - if rest.trim().is_empty() { - has_nested = true; - nested_kw = Some("import"); - continue; - } - } - if let Some(rest) = t.strip_prefix("导入:") { - if rest.trim().is_empty() { - has_nested = true; - nested_kw = Some("导入"); - continue; - } - } - if !is_legacy_import_oneliner(t) { - continue; - } - let (kw, after) = if t.starts_with("import") { - ("import", t[6..].trim()) - } else if let Some(a) = t.strip_prefix("导入") { - ("导入", a.trim()) - } else { - return Err(format!("internal: not a legacy import: {t}")); - }; - // Pre-existing EN/ZH one-liner mixes: fold under the first keyword seen. - if keyword.is_none() { - keyword = Some(kw); - } - let _ = kw; - let Some((bind_raw, target_raw)) = after.split_once(':') else { - return Err(format!("expected bind:target in `{t}`")); - }; - let bind = bind_raw.trim().to_string(); - let target = target_raw.trim().to_string(); - parse_import_binding(&bind, &target).map_err(|e| e.to_string())?; - if entries.iter().any(|(b, _)| b == &bind) { - return Err(format!("duplicate import bind `{bind}`")); - } - entries.push((bind, target)); - legacy_idxs.push(i); - } - - if entries.is_empty() { - return Ok(None); - } - if has_nested { - return Err(format!( - "file already has `{}:` block and legacy one-liners — resolve manually", - nested_kw.unwrap_or("import") - )); - } - - let kw = keyword.unwrap_or("import"); - let insert_at = legacy_idxs[0]; - let skip: std::collections::HashSet = legacy_idxs.into_iter().collect(); - - let mut out: Vec = Vec::new(); - for (i, line) in lines.iter().enumerate() { - if i == insert_at { - out.push(format!("{kw}:")); - for (bind, target) in &entries { - out.push(format!(" {bind}: {target}")); - } - } - if skip.contains(&i) { - continue; - } - out.push((*line).to_string()); - } - - let mut body = out.join("\n"); - if source.ends_with('\n') { - body.push('\n'); - } - Ok(Some((body, entries.len()))) -} - -/// Migrate one file's import frontmatter. `write=false` is dry-run. -pub fn migrate_imports_file(path: &Path, write: bool) -> anyhow::Result { - let source = std::fs::read_to_string(path)?; - let mut report = ImportFileReport { - file: path.to_path_buf(), - bindings: 0, - applied: false, - note: None, - }; - match rewrite_import_frontmatter(&source) { - Ok(None) => { - report.note = Some("no legacy import one-liners".into()); - Ok(report) - } - Err(e) => { - report.note = Some(e); - Ok(report) - } - Ok(Some((new_src, n))) => { - report.bindings = n; - // Soft smoke: nested map must extract the same binding count. - let scanned = crate::parse::scan_frontmatter_imports(&new_src); - if scanned.len() != n { - report.note = Some(format!( - "scan mismatch after rewrite: got {} expected {n}", - scanned.len() - )); - return Ok(report); - } - if write { - std::fs::write(path, &new_src)?; - report.applied = true; - } - Ok(report) - } - } -} - -/// Recursively migrate import one-liners under `path`. -pub fn migrate_imports_path(path: &Path, write: bool) -> anyhow::Result> { - let files = collect_files(path); - let mut out = Vec::new(); - for f in files { - match migrate_imports_file(&f, write) { - Ok(r) => out.push(r), - Err(e) => out.push(ImportFileReport { - file: f, - bindings: 0, - applied: false, - note: Some(format!("read failed: {e:#}")), - }), - } - } - Ok(out) -} - -/// Collect `*.mq.md` under `path` (file → itself). -pub fn collect_files(path: &Path) -> Vec { - fn walk(dir: &Path, out: &mut Vec) { - let Ok(rd) = std::fs::read_dir(dir) else { - return; - }; - for e in rd.flatten() { - let p = e.path(); - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if p.is_dir() { - if matches!( - name, - "target" | "dist" | "node_modules" | ".git" | ".marqdo" - ) { - continue; - } - walk(&p, out); - } else if name.ends_with(".mq.md") { - out.push(p); - } - } - } - if path.is_file() { - return vec![path.to_path_buf()]; - } - let mut out = Vec::new(); - walk(path, &mut out); - out.sort(); - out -} - -#[cfg(test)] -mod tests { - use super::{rewrite_import_frontmatter, rewrite_indexes, rewrite_loop}; - - #[test] - fn rewrites_import_oneliners_to_nested() { - let src = - "---\ntitle: t\nimport json:lib/json.mq.md\nimport fmt:time.format\n---\n\n# main\n"; - let (out, n) = rewrite_import_frontmatter(src).unwrap().unwrap(); - assert_eq!(n, 2); - assert!(out.contains("import:\n json: lib/json.mq.md\n fmt: time.format\n")); - assert!(!out.contains("import json:")); - } - - #[test] - fn rewrites_static_key() { - let (out, n) = rewrite_indexes("**v = [键](`表`)**"); - assert_eq!(n, 1); - assert_eq!(out, "**v = [键](access(`表`, \"键\"))**"); - } - - #[test] - fn rewrites_dynamic_key_without_backticks_in_label() { - let (out, n) = rewrite_indexes("**v = [`名`](`表`)**"); - assert_eq!(n, 1); - assert_eq!(out, "**v = [名](access(`表`, `名`))**"); - } - - #[test] - fn rewrites_nested_indexes_inside_out() { - let (out, n) = rewrite_indexes("**v = [content]([1]([messages](`req`)))**"); - assert_eq!(n, 3); - assert_eq!( - out, - "**v = [content](access([1](access([messages](access(`req`, \"messages\")), \"1\")), \"content\"))**" - ); - } - - #[test] - fn never_rewrites_already_migrated() { - let (out, n) = rewrite_indexes("**v = [键](access(`表`, \"键\"))**"); - assert_eq!(n, 0); - assert_eq!(out, "**v = [键](access(`表`, \"键\"))**"); - } - - #[test] - fn leaves_prose_links_alone() { - let (out, n) = rewrite_indexes("see [docs](https://example.com) for more"); - assert_eq!(n, 1, "plain code lines are rewritten…"); - // …but the table-cell path only touches `**…**` runs, which is what the - // real corpus needs (see rewrite_code_segments). - let _ = out; - } - - #[test] - fn rewrites_loop() { - let got = rewrite_loop("- [果](`列`)").unwrap(); - assert_eq!(got, "- [果](遍历 `列` 为 果)"); - // Already migrated / narrative loops stay untouched. - assert!(rewrite_loop("- [果](遍历 `列` 为 果)").is_none()); - assert!(rewrite_loop("not a loop").is_none()); - } -} diff --git a/src/mlsp.rs b/src/mlsp.rs deleted file mode 100755 index 33264b0..0000000 --- a/src/mlsp.rs +++ /dev/null @@ -1,1354 +0,0 @@ -//! Marqdo Language Server for AI(MLSP)—— AI 的可查询工具面(T3.1/T3.2,T2.6 并入 `schema`)。 -//! -//! 目标([three-problems.md](../../doc/roadmap/three-problems.md) §3):**AI 不必背 Marqdo -//! 语法细节**——把「记语法」换成「查工具」。语法唯一事实来源是 `parse::CORE_CONSTRUCTS` -//! (与 `doc/design/core-surface.md` 由 CI 守卫同步);本模块只加**检索别名**,不定义语法。 -//! -//! 行分隔 JSON 协议:每行一个请求 `{"id":…,"method":…,"params":{…}}`, -//! 每行一个响应 `{"id":…,"ok":true,"result":{…}}` / `{"id":…,"ok":false,"error":{…}}`。 -//! -//! | method | 作用 | -//! |--------|------| -//! | `locate` | 语法/符号定位:构造卡片,或定义位置 + 契约 | -//! | `syntax` | 语法问答:关键字/别名 → 构造卡片 | -//! | `validate` | 程序校验:结构化诊断数组(parse + 契约 check) | -//! | `repair_targets` | 修复靶点:错误 → **有界**修复目标(越界必拒,护栏) | -//! | `repair_apply` | 应用行编辑(全有或全无;越界 ⇒ `mlsp.repair_out_of_scope` abstain) | -//! | `schema` | 契约查询(T2.6):单元名 → 形参/返回/字段契约 | - -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -use crate::ast::{Function, Module}; -use crate::check::check_module; -use crate::contract::{Contract, Ty}; -use crate::diagnostics::Diagnostic; -use crate::load; -use crate::parse::CORE_CONSTRUCTS; - -/// 行分隔 JSON:一行请求 → 一行响应(永不 panic;错误也是结构化 JSON)。 -pub fn handle_line(line: &str) -> String { - let trimmed = line.trim(); - let id = match serde_json::from_str::(trimmed) { - Ok(req) => req.get("id").cloned().unwrap_or(Value::Null), - Err(e) => { - return json!({ - "id": null, - "ok": false, - "error": {"code": "mlsp.bad_request", "message": format!("请求不是合法 JSON: {e}")} - }) - .to_string(); - } - }; - let req: Value = serde_json::from_str(trimmed).expect("already parsed"); - match dispatch(&req) { - Ok(result) => json!({"id": id, "ok": true, "result": result}).to_string(), - Err(error) => json!({"id": id, "ok": false, "error": error}).to_string(), - } -} - -fn dispatch(req: &Value) -> Result { - let params = req.get("params").cloned().unwrap_or(json!({})); - match req.get("method").and_then(|m| m.as_str()) { - Some("locate") => locate(¶ms), - Some("syntax") => syntax(¶ms), - Some("validate") => validate(¶ms), - Some("repair_targets") => repair_targets(¶ms), - Some("repair_apply") => repair_apply(¶ms), - Some("schema") => schema(¶ms), - Some("artifact.find") => artifact_find(¶ms), - Some("artifact.inspect") => artifact_inspect(¶ms), - Some("link.resolve") => link_resolve(¶ms), - Some("artifact.verify") => artifact_verify(¶ms), - Some("artifact.impact") => artifact_impact(¶ms), - Some("artifact.bind") => artifact_bind(¶ms), - Some("artifact.execute") => artifact_execute(¶ms), - Some("artifact.reuse_execute") => artifact_reuse_execute(¶ms), - Some("document.extract") => document_extract(¶ms), - Some("artifact.patch") => artifact_patch(¶ms), - Some("artifact.extract_pure") => artifact_extract_pure(¶ms), - // Workbench M00–M04: capability probe + read-only view + locator. - Some("capabilities") => Ok(crate::workbench::probe_capabilities(¶ms)), - #[cfg(feature = "view")] - Some("view.document") => view_document(¶ms), - #[cfg(not(feature = "view"))] - Some("view.document") => Err(err( - "mlsp.unsupported", - "view.document requires the view feature", - )), - #[cfg(feature = "view")] - Some("resource.view") => resource_view(¶ms), - #[cfg(not(feature = "view"))] - Some("resource.view") => Err(err( - "mlsp.unsupported", - "resource.view requires the view feature", - )), - Some("view.reference_resolve") => crate::workbench::resolve_reference(¶ms), - // `` M9: occlusion label search (two-tier vocabulary). - Some("labels.search") => labels_search(¶ms), - // `` M6: one-shot session summary (T1 staleness seen/fixed). - Some("session.summary") => session_summary(), - other => Err(err( - "mlsp.unknown_method", - format!("未知方法 {other:?};可用:locate / syntax / validate / repair_targets / repair_apply / schema / artifact.find / artifact.inspect / link.resolve / artifact.verify / artifact.impact / artifact.bind / artifact.execute / artifact.reuse_execute / artifact.patch / artifact.extract_pure / document.extract / capabilities / view.document / resource.view / view.reference_resolve"), - )), - } -} - -#[cfg(feature = "view")] -fn view_document(params: &Value) -> Result { - let req = crate::workbench::DocumentViewRequest::from_params(params) - .map_err(|e| err("mlsp.bad_request", e))?; - crate::workbench::build_document_view(&req) -} - -#[cfg(feature = "view")] -fn resource_view(params: &Value) -> Result { - let req = crate::workbench::ResourceViewRequest::from_params(params) - .map_err(|e| err("mlsp.bad_request", e))?; - crate::workbench::build_resource_view(&req) -} - -fn artifact_extract_pure(params: &Value) -> Result { - let name = params - .get("name") - .and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "artifact.extract_pure 需要 name"))?; - let expression = params - .get("expression") - .and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "artifact.extract_pure 需要 expression"))?; - match crate::sema::plan_pure_extract(name, expression) { - Ok(plan) => Ok(json!({ - "schema_version": 1, - "name": plan.name, - "params": plan.params, - "expression": plan.expression, - "heading": plan.heading, - "call": plan.call, - "effects": ["pure"], - "note": "预览补丁;写入请配合 artifact.patch / 人工审阅", - })), - Err(e) => Err(json!({"code": e.code, "message": e.message})), - } -} - -// ---------- Executable-knowledge artifact protocol ---------- - -/// All artifact methods compile the same semantic project as the CLI. They -/// never fall back to EKC's lexical search when a binding decision is needed. -fn semantic_project(params: &Value) -> Result { - if params.get("source").is_some() { - return Err(err("mlsp.overlay_requires_path", "artifact 方法需要 params.project/path;内存 overlay 尚未持久化到项目边界")); - } - let root = params.get("project").or_else(|| params.get("path")) - .and_then(Value::as_str).unwrap_or("."); - let root = PathBuf::from(root); - let project_root = if root.is_file() { - root.parent().unwrap_or_else(|| Path::new(".")).to_path_buf() - } else { root.clone() }; - crate::sema::compile_project(&crate::sema::CompileOptions { - project_root, - entry: root.is_file().then_some(root), - lock_mode: crate::sema::LockMode::Off, - }).map_err(|e| err("mlsp.semantic_compile", format!("{e:#}"))) -} - -fn artifact_query<'a>(project: &'a crate::sema::SemanticProject, query: &str) -> Vec<&'a crate::sema::SemanticArtifact> { - project.artifacts.iter().filter(|artifact| { - artifact.artifact_id.0 == query || artifact.symbol_id.as_ref().is_some_and(|id| id.as_str() == query) - || artifact.display_name == query || artifact.artifact_id.0.ends_with(query) - }).collect() -} - -fn document_extract(params: &Value) -> Result { - let path = params - .get("path") - .and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "document.extract 需要 path"))?; - let hint = params - .get("format") - .and_then(Value::as_str) - .map(|s| s.to_string()); - let doc = crate::document_extract::extract_document(&crate::document_extract::DocumentSource { - path: PathBuf::from(path), - format_hint: hint, - }); - Ok(doc.to_json()) -} - -fn artifact_find(params: &Value) -> Result { - let compilation = semantic_project(params)?; - let query = params.get("query").and_then(Value::as_str).unwrap_or("").to_ascii_lowercase(); - let kind = params.get("kind").and_then(Value::as_str); - let limit = params.get("limit").and_then(Value::as_u64).unwrap_or(20) as usize; - let mut matches: Vec = compilation.semantics.artifacts.iter().filter(|artifact| { - kind.map(|kind| kind == artifact.kind).unwrap_or(true) && (query.is_empty() - || artifact.display_name.to_ascii_lowercase().contains(&query) - || artifact.artifact_id.0.to_ascii_lowercase().contains(&query)) - }).take(limit).map(|artifact| json!({ - "artifact_id": artifact.artifact_id.0, "symbol_id": artifact.symbol_id.as_ref().map(|id| id.as_str()), - "display_name": artifact.display_name, "kind": artifact.kind, - "effects": artifact.effects.values(), "source": {"file":artifact.source.file,"line":artifact.source.line}, - })).collect(); - matches.sort_by(|a, b| a["artifact_id"].as_str().cmp(&b["artifact_id"].as_str())); - Ok(json!({"schema_version":1,"discovery_only":true,"candidates":matches})) -} - -fn artifact_inspect(params: &Value) -> Result { - let compilation = semantic_project(params)?; - let query = params.get("artifact_id").or_else(|| params.get("symbol_id")).or_else(|| params.get("id")) - .and_then(Value::as_str).ok_or_else(|| err("mlsp.bad_request", "artifact.inspect 需要 artifact_id 或 symbol_id"))?; - let candidates = artifact_query(&compilation.semantics, query); - if candidates.is_empty() { return Err(err("artifact.unresolved", format!("没有制品 `{query}`"))); } - if candidates.len() != 1 { return Err(json!({"code":"artifact.ambiguous","message":format!("制品 `{query}` 不唯一"),"candidates":candidates.iter().map(|a|&a.artifact_id.0).collect::>() })); } - let artifact = candidates[0]; - // Version contract: expected source/generation mismatch must not silently return current. - check_artifact_version_params(params, &compilation, artifact)?; - Ok(crate::sema::artifact_json(artifact)) -} - -/// Reject inspect when caller pinned an expected source revision or generation that -/// does not match the current project snapshot (`artifact.version_mismatch`). -fn check_artifact_version_params( - params: &Value, - compilation: &crate::sema::Compilation, - artifact: &crate::sema::SemanticArtifact, -) -> Result<(), Value> { - let expected_rev = params - .get("expected_source_revision") - .and_then(Value::as_str) - .filter(|s| !s.is_empty()); - if let Some(expected) = expected_rev { - let project_root = params - .get("project") - .or_else(|| params.get("path")) - .and_then(Value::as_str) - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(".")); - let root = if project_root.is_file() { - project_root - .parent() - .unwrap_or_else(|| Path::new(".")) - .to_path_buf() - } else { - project_root - }; - let abs = root.join(&artifact.source.file); - match std::fs::read(&abs) { - Ok(raw) => { - use sha2::{Digest, Sha256}; - let actual = format!("sha256:{:x}", Sha256::digest(&raw)); - if actual != expected { - return Err(json!({ - "code": "artifact.version_mismatch", - "message": format!( - "expected source_revision {expected}, actual {actual}; refusing silent downgrade" - ), - "expected_source_revision": expected, - "actual_source_revision": actual, - "artifact_id": artifact.artifact_id.0, - })); - } - } - Err(e) => { - return Err(json!({ - "code": "artifact.version_mismatch", - "message": format!( - "cannot verify source_revision for {}: {e}; refusing silent downgrade", - artifact.source.file - ), - "expected_source_revision": expected, - "artifact_id": artifact.artifact_id.0, - })); - } - } - } - - let expected_gen = params - .get("expected_generation") - .or_else(|| params.get("generation_id")) - .and_then(Value::as_str) - .filter(|s| !s.is_empty()); - if let Some(expected) = expected_gen { - let actual = semantic_generation_id(&compilation.semantics); - if actual != expected { - return Err(json!({ - "code": "artifact.version_mismatch", - "message": format!( - "expected generation {expected}, current projection is {actual}; refusing silent downgrade" - ), - "expected_generation": expected, - "actual_generation": actual, - "artifact_id": artifact.artifact_id.0, - })); - } - } - Ok(()) -} - -/// Semantic generation token matching KnowledgePresentation / DocumentView. -fn semantic_generation_id(project: &crate::sema::SemanticProject) -> String { - use sha2::{Digest, Sha256}; - let mut gh = Sha256::new(); - gh.update(project.project_id.as_bytes()); - for a in &project.artifacts { - gh.update(a.hashes.artifact.0.as_bytes()); - } - format!("{:x}", gh.finalize())[..16].to_string() -} - -fn link_resolve(params: &Value) -> Result { - let compilation = semantic_project(params)?; - let reference = params.get("payload").or_else(|| params.get("reference")).and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "link.resolve 需要 payload/reference"))?; - let candidates = artifact_query(&compilation.semantics, reference); - let resolution = if candidates.is_empty() { "unresolved" } else if candidates.len() == 1 { "symbol" } else { "ambiguous" }; - Ok(json!({"schema_version":1,"reference":reference,"resolution":resolution,"candidates":candidates.iter().map(|a|json!({"artifact_id":a.artifact_id.0,"symbol_id":a.symbol_id.as_ref().map(|id|id.as_str()),"display_name":a.display_name,"effects":a.effects.values()})).collect::>() })) -} - -fn artifact_verify(params: &Value) -> Result { - let compilation = semantic_project(params)?; - let query = params.get("artifact_id").or_else(|| params.get("symbol_id")).and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "artifact.verify 需要 artifact_id 或 symbol_id"))?; - let candidates = artifact_query(&compilation.semantics, query); - if candidates.len() != 1 { return Err(err(if candidates.is_empty() { "artifact.unresolved" } else { "artifact.ambiguous" }, format!("无法唯一验证 `{query}`"))); } - let artifact = candidates[0]; - let policy = params.get("policy").and_then(Value::as_str).unwrap_or("static"); - Ok(build_verification_report(artifact, policy)) -} - -/// CLI / product machine adjudication over semantic artifacts (M03). -pub fn adjudicate_project(project: &std::path::Path, artifact: Option<&str>, policy: &str) -> Result { - let compilation = semantic_project(&json!({"project": project}))?; - let targets: Vec<&crate::sema::SemanticArtifact> = if let Some(q) = artifact { - let c = artifact_query(&compilation.semantics, q); - if c.is_empty() { - return Err(err("artifact.unresolved", format!("没有制品 `{q}`"))); - } - c - } else { - compilation - .semantics - .artifacts - .iter() - .filter(|a| a.kind == "function") - .collect() - }; - let reports: Vec = targets - .iter() - .map(|a| build_verification_report(a, policy)) - .collect(); - let any_denied = reports.iter().any(|r| r["may_bind"] == false); - Ok(json!({ - "schema_version": 1, - "policy": policy, - "count": reports.len(), - "may_bind_all": !any_denied, - "reports": reports, - })) -} - -/// Known bind/verify policies (M03). Unknown strings are rejected. -fn parse_policy(policy: &str) -> Result<&str, Value> { - match policy { - "pure" | "business" | "static" => Ok(policy), - other => Err(json!({ - "code": "artifact.unknown_policy", - "message": format!("未知政策 `{other}`;允许 pure / business / static"), - "policy": other, - })), - } -} - -fn evidence_allows_business(status: &str) -> bool { - matches!(status, "sourced" | "verified") -} - -fn build_verification_report(artifact: &crate::sema::SemanticArtifact, policy: &str) -> Value { - let policy = match parse_policy(policy) { - Ok(p) => p, - Err(e) => { - return json!({ - "schema_version": 1, - "artifact_id": artifact.artifact_id.0, - "policy": policy, - "checks": {}, - "blockers": [e], - "may_bind": false, - "may_publish": false, - "verification": crate::sema::artifact_json(artifact)["verification"].clone(), - }); - } - }; - let region_status = if artifact.applicability.contains("region=") { - "declared" - } else { - "unknown" - }; - let checks = json!({ - "parse": {"status": artifact.verification.parse, "detail": "static_project_compile"}, - "resolve": {"status": artifact.verification.resolve, "detail": "symbol_bound"}, - "contract": {"status": artifact.verification.contract, "detail": "not_executed_by_verify"}, - "execution": {"status": artifact.verification.execution, "detail": "not_run"}, - "tests": {"status": artifact.verification.tests, "detail": "no_test_runner_invoked"}, - "evidence": {"status": artifact.verification.evidence, "detail": "compile_time_provenance"}, - "domain": {"status": artifact.verification.domain, "detail": "unreviewed"}, - "region": {"status": region_status, "detail": "input_domain_not_checked"}, - "input_domain": {"status": "unknown", "detail": "not_checked_by_static_verify"}, - }); - let mut blockers = Vec::new(); - // Never upgrade tests/execution to passed without a runner (M03). - if matches!( - artifact.verification.tests.as_str(), - "passed" | "verified" - ) && artifact - .verification - .methods - .iter() - .all(|m| m == "static_project_compile") - { - blockers.push(json!({ - "code": "artifact.tests_unproven", - "check": "tests", - "status": artifact.verification.tests, - "detail": "static compile must not claim tests passed", - })); - } - if policy == "business" && !evidence_allows_business(&artifact.verification.evidence) { - blockers.push(json!({ - "code": "artifact.evidence_denied", - "check": "evidence", - "status": artifact.verification.evidence, - })); - } - if policy == "pure" - && artifact - .effects - .values() - .iter() - .any(|e| e != "pure") - { - blockers.push(json!({ - "code": "artifact.effect_denied", - "check": "effects", - "effects": artifact.effects.values(), - })); - } - let may_bind = blockers.is_empty() - && match policy { - "business" => evidence_allows_business(&artifact.verification.evidence), - "pure" => artifact.effects.values().iter().all(|e| e == "pure"), - _ => true, - }; - // Publish requires stronger evidence than bind; static verify never claims tests passed. - let may_publish = may_bind - && artifact.verification.tests != "unknown" - && artifact.verification.tests != "not_run" - && artifact.verification.execution != "not_run" - && !matches!( - artifact.verification.evidence.as_str(), - "unverified" | "missing_source" | "anchor_missing" | "expired" | "invalid_date" - ); - json!({ - "schema_version": 1, - "artifact_id": artifact.artifact_id.0, - "symbol_id": artifact.symbol_id.as_ref().map(|id| id.as_str()), - "digest": artifact.hashes.artifact.0, - "evidence_digest": artifact.hashes.evidence.0, - "closure_digest": artifact.hashes.closure.0, - "policy": policy, - "checks": checks, - "blockers": blockers, - "may_bind": may_bind, - "may_publish": may_publish, - "verification": { - "parse": artifact.verification.parse, - "resolve": artifact.verification.resolve, - "contract": artifact.verification.contract, - "execution": artifact.verification.execution, - "tests": artifact.verification.tests, - "evidence": artifact.verification.evidence, - "domain": artifact.verification.domain, - "methods": artifact.verification.methods, - }, - }) -} - -/// M04: bind then execute in one call (actual reuse, not discovery scores). -fn artifact_reuse_execute(params: &Value) -> Result { - let project = params - .get("project") - .or_else(|| params.get("path")) - .cloned() - .ok_or_else(|| err("mlsp.bad_request", "artifact.reuse_execute 需要 project"))?; - let query = params - .get("artifact_id") - .or_else(|| params.get("symbol_id")) - .or_else(|| params.get("query")) - .and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "artifact.reuse_execute 需要 artifact_id"))?; - let policy = params.get("policy").and_then(Value::as_str).unwrap_or("pure"); - let inputs = params.get("inputs").cloned().unwrap_or(json!({})); - let bound = artifact_bind(&json!({ - "project": project, - "artifact_id": query, - "policy": policy, - "expected_digest": params.get("expected_digest"), - }))?; - let handle = bound - .get("handle") - .cloned() - .ok_or_else(|| err("artifact.bind_failed", "bind 未返回 handle"))?; - let executed = artifact_execute(&json!({ - "handle": handle, - "inputs": inputs, - "allow_effects": params.get("allow_effects"), - }))?; - Ok(json!({ - "schema_version": 1, - "actual_reuse": true, - "discovery_only": false, - "artifact_id": executed.get("artifact_id"), - "symbol_id": executed.get("symbol_id"), - "digest": executed.get("digest"), - "result": executed.get("result"), - "stdout": executed.get("stdout"), - "effects": executed.get("effects"), - "trace": { - "artifact_id": executed.get("artifact_id"), - "symbol_id": executed.get("symbol_id"), - "digest": executed.get("digest"), - "inputs": inputs, - "value": executed.get("result"), - "stdout": executed.get("stdout"), - }, - })) -} - -fn artifact_impact(params: &Value) -> Result { - let compilation = semantic_project(params)?; - let query = params.get("artifact_id").or_else(|| params.get("symbol_id")).or_else(|| params.get("path")).and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "artifact.impact 需要 artifact_id、symbol_id 或 path"))?; - Ok(crate::sema::semantic_impact(&compilation.semantics, query)) -} - -fn artifact_bind(params: &Value) -> Result { - let compilation = semantic_project(params)?; - let query = params.get("artifact_id").or_else(|| params.get("symbol_id")).and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "artifact.bind 需要 artifact_id 或 symbol_id"))?; - let candidates = artifact_query(&compilation.semantics, query); - if candidates.len() != 1 { return Err(err(if candidates.is_empty() { "artifact.unresolved" } else { "artifact.ambiguous" }, format!("无法唯一绑定 `{query}`"))); } - let artifact = candidates[0]; - let expected = params.get("expected_digest").and_then(Value::as_str); - if expected.is_some() && expected != Some(artifact.hashes.artifact.0.as_str()) { - return Err(json!({"code":"artifact.digest_mismatch","message":"目标摘要已变化,拒绝绑定","expected":expected,"actual":artifact.hashes.artifact.0})); - } - let policy = parse_policy( - params - .get("policy") - .and_then(Value::as_str) - .unwrap_or("pure"), - )?; - let effects = artifact.effects.values(); - if policy == "pure" - && effects.iter().any(|effect| effect != "pure") - { - return Err(json!({ - "code": "artifact.effect_denied", - "message": "pure 策略下不能绑定含非纯/未知效应的制品", - "policy": policy, - "effects": effects, - })); - } - if policy == "business" && !evidence_allows_business(&artifact.verification.evidence) { - return Err(json!({ - "code": "artifact.evidence_denied", - "message": "business 策略要求来源已关联且锚点有效、未过期;当前证据状态不足", - "policy": policy, - "evidence": artifact.verification.evidence, - })); - } - let symbol_id = artifact - .symbol_id - .as_ref() - .map(|id| id.as_str().to_string()) - .unwrap_or_else(|| artifact.artifact_id.0.clone()); - let valid_until = artifact - .applicability - .split(';') - .find_map(|part| { - part.trim() - .strip_prefix("valid_until=") - .map(|s| s.trim().to_string()) - }); - let provenance_digests: Vec = artifact - .provenance - .iter() - .filter(|p| p.relation == "supports") - .map(|p| { - json!({ - "uri": p.uri, - "locator": p.locator, - "content_digest": p.content_digest.as_ref().map(|d| &d.0), - }) - }) - .collect(); - Ok(json!({"schema_version":1,"handle":{ - "artifact_id": artifact.artifact_id.0, - "symbol_id": symbol_id, - "digest": artifact.hashes.artifact.0, - "closure_digest": artifact.hashes.closure.0, - "evidence_digest": artifact.hashes.evidence.0, - "project": compilation.semantics.root, - "policy": policy, - "effects": effects, - "evidence": artifact.verification.evidence, - "valid_until": valid_until, - "provenance": provenance_digests, - "source": {"file": artifact.source.file, "line": artifact.source.line}, - }})) -} - -/// Digest-guarded local patch (S3/G09). `intent: wording` refuses signature/effect drift. -fn artifact_patch(params: &Value) -> Result { - let compilation = semantic_project(params)?; - let query = params - .get("artifact_id") - .or_else(|| params.get("symbol_id")) - .and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "artifact.patch 需要 artifact_id 或 symbol_id"))?; - let candidates = artifact_query(&compilation.semantics, query); - if candidates.len() != 1 { - return Err(err( - if candidates.is_empty() { - "artifact.unresolved" - } else { - "artifact.ambiguous" - }, - format!("无法唯一修补 `{query}`"), - )); - } - let before = candidates[0]; - let expected = params - .get("expected_digest") - .and_then(Value::as_str) - .ok_or_else(|| { - err( - "mlsp.bad_request", - "artifact.patch 需要 expected_digest(hashes.implementation)", - ) - })?; - if expected != before.hashes.implementation.0 { - return Err(json!({ - "code": "artifact.digest_mismatch", - "message": "源码实现摘要已变化,拒绝覆盖", - "expected": expected, - "actual": before.hashes.implementation.0, - })); - } - let path = compilation.semantics.root.join(&before.source.file); - let original = std::fs::read_to_string(&path) - .map_err(|e| err("artifact.load", format!("读源失败: {e}")))?; - let edits_v = params - .get("edits") - .and_then(Value::as_array) - .ok_or_else(|| err("mlsp.bad_request", "artifact.patch 需要 edits"))?; - let mut edits = Vec::new(); - for e in edits_v { - let line = e - .get("line") - .and_then(Value::as_u64) - .ok_or_else(|| err("mlsp.bad_request", "edit.line 必填"))? as u32; - let kind = e.get("op").and_then(Value::as_str).unwrap_or("replace"); - match kind { - "replace" => { - let text = e - .get("text") - .and_then(Value::as_str) - .ok_or_else(|| err("mlsp.bad_request", "replace 需要 text"))? - .to_string(); - edits.push(crate::repair::Edit::Replace { line, text }); - } - "delete" => edits.push(crate::repair::Edit::Delete { line }), - "insert_before" => { - let text = e - .get("text") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - edits.push(crate::repair::Edit::InsertBefore { line, text }); - } - other => { - return Err(err( - "mlsp.bad_request", - format!("未知 edit.op `{other}`"), - )) - } - } - } - let start = before.source.line; - let end = before.source.end_line.max(start); - let ranges = [(start, end.max(start + 40))]; - let patched = crate::repair::apply_edits(&original, &ranges, &edits).map_err(|o| { - json!({ - "code": "mlsp.repair_out_of_scope", - "message": "补丁超出制品源码范围", - "lines": o.lines, - "ranges": o.ranges, - }) - })?; - std::fs::write(&path, &patched) - .map_err(|e| err("artifact.write", format!("写源失败: {e}")))?; - let after_comp = semantic_project(params)?; - let after_cands = artifact_query(&after_comp.semantics, query); - if after_cands.len() != 1 { - // roll back - let _ = std::fs::write(&path, &original); - return Err(err( - "artifact.patch_ambiguous", - "补丁后制品无法唯一解析;已回滚", - )); - } - let after = after_cands[0]; - let signature_changed = before.hashes.interface.0 != after.hashes.interface.0; - let effects_changed = before.effects.values() != after.effects.values(); - let implementation_changed = - before.hashes.implementation.0 != after.hashes.implementation.0; - let intent = params.get("intent").and_then(Value::as_str).unwrap_or("edit"); - if intent == "wording" && (signature_changed || effects_changed) { - let _ = std::fs::write(&path, &original); - return Err(json!({ - "code": "artifact.wording_broke_contract", - "message": "intent=wording 但签名或效应已变;已回滚", - "signature_changed": signature_changed, - "effects_changed": effects_changed, - })); - } - Ok(json!({ - "schema_version": 1, - "artifact_id": after.artifact_id.0, - "symbol_id": after.symbol_id.as_ref().map(|id| id.as_str()), - "applied": true, - "diff": { - "signature_changed": signature_changed, - "effects_changed": effects_changed, - "implementation_changed": implementation_changed, - "before": { - "interface": before.hashes.interface.0, - "implementation": before.hashes.implementation.0, - "effects": before.effects.values(), - }, - "after": { - "interface": after.hashes.interface.0, - "implementation": after.hashes.implementation.0, - "effects": after.effects.values(), - }, - }, - })) -} - -fn artifact_execute(params: &Value) -> Result { - let handle = params.get("handle").ok_or_else(|| err("mlsp.bad_request", "artifact.execute 需要 artifact.bind 返回的 handle"))?; - let artifact_id = handle.get("artifact_id").and_then(Value::as_str).ok_or_else(|| err("mlsp.bad_handle", "handle 缺少 artifact_id"))?; - let digest = handle.get("digest").and_then(Value::as_str).ok_or_else(|| err("mlsp.bad_handle", "handle 缺少 digest"))?; - let project_path = handle.get("project").and_then(Value::as_str).or_else(|| params.get("project").and_then(Value::as_str)).ok_or_else(|| err("mlsp.bad_handle", "handle 缺少 project"))?; - let compilation = semantic_project(&json!({"project":project_path}))?; - let candidates = artifact_query(&compilation.semantics, artifact_id); - if candidates.len() != 1 { return Err(err("artifact.stale_handle", "制品不再可唯一解析;请重新 bind")); } - let artifact = candidates[0]; - if artifact.hashes.artifact.0 != digest { return Err(json!({"code":"artifact.stale_handle","message":"源码、契约或来源证据已改变;拒绝执行过期 handle","expected":digest,"actual":artifact.hashes.artifact.0})); } - if let Some(bound_closure) = handle.get("closure_digest").and_then(Value::as_str) { - if bound_closure != artifact.hashes.closure.0 { - return Err(json!({ - "code": "artifact.stale_handle", - "message": "依赖闭包已改变;拒绝执行过期 handle", - "expected": bound_closure, - "actual": artifact.hashes.closure.0, - })); - } - } - if let Some(bound_evidence) = handle.get("evidence_digest").and_then(Value::as_str) { - if bound_evidence != artifact.hashes.evidence.0 { - return Err(json!({ - "code": "artifact.stale_handle", - "message": "来源证据摘要已改变;拒绝执行过期 handle", - "expected": bound_evidence, - "actual": artifact.hashes.evidence.0, - })); - } - } - if let Some(bound_symbol) = handle.get("symbol_id").and_then(Value::as_str) { - let current = artifact - .symbol_id - .as_ref() - .map(|id| id.as_str()) - .unwrap_or(artifact.artifact_id.0.as_str()); - if bound_symbol != current { - return Err(json!({ - "code": "artifact.stale_handle", - "message": "handle 绑定的 SymbolId 与当前制品不一致", - "expected": bound_symbol, - "actual": current, - })); - } - } - // Re-check policy at execute time (M02) — do not trust bind-time evidence string alone. - let policy = handle.get("policy").and_then(Value::as_str).unwrap_or("pure"); - let _ = parse_policy(policy)?; - if policy == "business" && !evidence_allows_business(&artifact.verification.evidence) { - return Err(json!({ - "code": "artifact.evidence_denied", - "message": "business 句柄在执行时证据状态不足(来源缺失、锚点失效或已过期)", - "policy": policy, - "evidence": artifact.verification.evidence, - })); - } - if policy == "pure" - && artifact - .effects - .values() - .iter() - .any(|effect| effect != "pure") - { - return Err(json!({ - "code": "artifact.effect_denied", - "message": "pure 句柄在执行时出现非纯效应", - "policy": policy, - "effects": artifact.effects.values(), - })); - } - if let Some(until) = handle.get("valid_until").and_then(Value::as_str) { - if crate::sema::provenance::valid_until_expired(until) { - return Err(json!({ - "code": "artifact.expired", - "message": "句柄适用期已过", - "valid_until": until, - })); - } - } - if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") { return Err(err("artifact.not_executable", "只有非实例函数制品可由 artifact.execute 直接执行")); } - let allowed: Vec<&str> = params.get("allow_effects").and_then(Value::as_array).map(|items| items.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - let denied: Vec = artifact.effects.values().into_iter().filter(|effect| effect != "pure" && !allowed.contains(&effect.as_str())).collect(); - if !denied.is_empty() { return Err(json!({"code":"artifact.effect_denied","message":"效果策略拒绝执行","denied":denied,"effects":artifact.effects.values()})); } - let path = compilation.semantics.root.join(&artifact.source.file); - let input = params.get("inputs").cloned().unwrap_or_else(|| json!({})); - let object = input.as_object().ok_or_else(|| err("mlsp.bad_request", "inputs 必须是 JSON 对象"))?; - let mut args = Vec::new(); - for (name, value) in object { args.push((name.clone(), crate::host::json::json_to_value(value).map_err(|e| err("mlsp.bad_input", e))?)); } - let caps = crate::host::HostCaps { fs_write: allowed.contains(&"fs.write"), exec: allowed.iter().any(|e| matches!(*e, "process.exec" | "plugin.call" | "llm.call")), net: allowed.iter().any(|e| matches!(*e, "network.read" | "network.write" | "llm.call")), plugin: allowed.contains(&"plugin.call") }; - // Same line identity, argument binding, and runtime as `marqdo call`. - let (value, stdout) = crate::call::execute_source_function( - &path, - artifact.source.line, - &artifact.display_name, - &args, - caps, - crate::Backend::Tree, - false, - ) - .map_err(|e| diagnostic_err("artifact.execution_failed", &e))?; - Ok(json!({ - "schema_version": 1, - "artifact_id": artifact.artifact_id.0, - "symbol_id": artifact.symbol_id.as_ref().map(|id| id.as_str()), - "digest": digest, - "result": crate::value_as_json(&value).map_err(|e| err("artifact.serialization", e))?, - "stdout": stdout, - "effects": artifact.effects.values(), - })) -} - -fn err(code: &str, message: impl Into) -> Value { - json!({"code": code, "message": message.into()}) -} - -// ---------- 构造卡片(语法唯一事实来源 = CORE_CONSTRUCTS) ---------- - -/// 检索别名(中/英关键字)——只做匹配,不定义语法。 -const ALIASES: &[(&str, &[&str])] = &[ - ("narrative", &["叙述", "文字", "说明", "注释", "narrative", "prose"]), - ("blank", &["空行", "blank"]), - ("heading-unit", &["标题", "单元", "函数", "对象", "heading", "定义"]), - ("call-line", &["调用", "call"]), - ("branch-list", &["分支", "条件", "判断", "branch", "if"]), - ("loop-list", &["循环", "遍历", "loop", "for", "while"]), - ("param", &["参数", "形参", "param"]), - ("table", &["表", "表格", "table", "集合", "数据"]), - ("fence", &["代码块", "围栏", "fence", "公式", "code"]), - ("hr", &["分隔线", "水平线", "hr"]), - ("writeback", &["回写", "输出块", "writeback"]), - ("ident", &["变量", "标识符", "ident", "名字"]), - ("bold-code", &["粗体", "赋值", "语句", "bold", "执行"]), - ("italic-return", &["返回", "return", "斜体"]), - ("empty-return", &["空返回", "none", "结束", "副作用"]), - ("link-index", &["取元", "索引", "index", "键", "行"]), - ("bracket-call", &["修饰", "括号", "bracket", "开关参数"]), - ("footnote-index", &["脚注", "footnote", "取列", "列"]), - ("soft-emphasis", &["强调", "emphasis", "软强调"]), -]; - -/// core-surface.md 全文(与 `tests/core_surface.rs` 守卫同源)——卡片机械携带 -/// 语义/戒律/样例**原文**,AI 一次查询即可自持,不必回读文档(three-problems.md §3.2「单构造戒律」)。 -const SURFACE_MD: &str = include_str!("../doc/design/core-surface.md"); - -/// 机械提取 core-surface.md 清单行:`| \`id\` | 外形 | 语义 | 戒律 | 样例 |` → -///(语义, 戒律, 样例, 行原文);只读不改,卡片内容与文档永不漂移。 -fn surface_row(id: &str) -> Option<(String, String, String, String)> { - for line in SURFACE_MD.lines() { - let t = line.trim(); - if !t.starts_with('|') { - continue; - } - let cells: Vec<&str> = t.trim_matches('|').split('|').map(str::trim).collect(); - if cells.len() != 5 { - continue; - } - let rid = cells[0].trim_matches('`'); - if rid == id && !rid.is_empty() && !rid.contains(' ') && !rid.starts_with('-') { - return Some(( - cells[2].to_string(), - cells[3].to_string(), - cells[4].to_string(), - t.to_string(), - )); - } - } - None -} - -fn card(id: &str) -> Value { - let form = CORE_CONSTRUCTS - .iter() - .find(|(cid, _)| *cid == id) - .map(|(_, f)| *f) - .unwrap_or("?"); - let mut v = json!({ - "id": id, - "form": form, - "manual": "doc/design/core-surface.md", - }); - if let Some((semantics, rule, sample, quote)) = surface_row(id) { - v["semantics"] = semantics.into(); - v["rule"] = rule.into(); - v["sample"] = sample.into(); - v["doc_quote"] = quote.into(); - } - v -} - -fn match_constructs(query: &str) -> Vec { - let q = query.trim().to_lowercase(); - if q.is_empty() { - return ALIASES.iter().map(|(id, _)| card(id)).collect(); - } - ALIASES - .iter() - .filter(|(_, keys)| { - keys.iter() - .any(|k| k.to_lowercase().contains(&q) || q.contains(&k.to_lowercase())) - }) - .map(|(id, _)| card(id)) - .collect() -} - -fn syntax(params: &Value) -> Result { - let query = params.get("query").and_then(|q| q.as_str()).unwrap_or(""); - let cards = match_constructs(query); - if cards.is_empty() { - return Err(err( - "mlsp.no_match", - format!("没有匹配「{query}」的语法构造;换关键字(如 返回/表/调用)或省略 query 列出全部"), - )); - } - Ok(json!({"cards": cards})) -} - -fn locate(params: &Value) -> Result { - if params.get("path").is_some() || params.get("source").is_some() { - let (module, path) = module_from_params(params)?; - let symbol = params - .get("symbol") - .and_then(|s| s.as_str()) - .ok_or_else(|| err("mlsp.bad_request", "locate 定位符号需要 params.symbol"))?; - let fun = find_fn(&module, symbol) - .ok_or_else(|| err("mlsp.unknown_unit", format!("没有名为 `{symbol}` 的单元")))?; - return Ok(json!({ - "unit": fun.name, - "level": fun.level, - "span": span_json(path.as_deref(), fun.span), - "params": fun.params.iter().map(|p| p.name.clone()).collect::>(), - "contract": fun.contract.as_ref().map(|c| contract_json(c, path.as_deref())), - "manual": "doc/design/core-surface.md", - })); - } - Ok(json!({"cards": match_constructs( - params.get("query").and_then(|q| q.as_str()).unwrap_or("") - )})) -} - -fn validate(params: &Value) -> Result { - let (module, path) = module_from_params(params)?; - let mut diags = check_module(&module, path.as_deref()); - diags.sort_by_key(|d| (d.span.line, d.span.col)); - let jsons: Vec = diags.iter().map(|d| d.to_json()).collect(); - let ok = !diags - .iter() - .any(|d| matches!(d.severity, crate::diagnostics::Severity::Error)); - Ok(json!({"ok": ok, "diagnostics": jsons})) -} - -/// 修复靶点(T3.3 护栏):锚点局部修复,**越界必拒**(禁止整文件重写/无关重构)。 -fn repair_targets(params: &Value) -> Result { - let code = params.get("code").and_then(|c| c.as_str()).unwrap_or(""); - let anchor = params.get("doc_anchor").and_then(|a| a.as_str()); - let suggestion = params.get("suggestion").and_then(|s| s.as_str()); - if code.is_empty() { - return Err(err("mlsp.bad_request", "repair_targets 需要 params.code")); - } - Ok(json!({ - "targets": [{ - "code": code, - "doc_anchor": anchor, - "span": params.get("span").cloned().unwrap_or(Value::Null), - }], - "repair": { - "strategy": "anchored-local", - "bounded": true, - "max_attempts": 2, - "scope": "doc_anchor 所锚定的契约表/语句行", - "suggestion": suggestion, - "on_violation": "abstain", - "note": "只许改动锚定范围内的行;越界改动必须拒绝并报 abstain" - } - })) -} - -/// 应用有界修复(T3.3):行编辑全有或全无;越界 ⇒ `mlsp.repair_out_of_scope`(abstain),源零字节不改。 -fn repair_apply(params: &Value) -> Result { - let source = source_text(params)?; - let ranges = params - .get("ranges") - .and_then(|r| r.as_array()) - .ok_or_else(|| err("mlsp.bad_request", "repair_apply 需要 params.ranges([[起,止],…])"))? - .iter() - .map(|pair| { - let a = pair.as_array()?; - Some((a.first()?.as_u64()? as u32, a.get(1)?.as_u64()? as u32)) - }) - .collect::>>() - .ok_or_else(|| err("mlsp.bad_request", "ranges 必须是 [[起,止],…]"))?; - - let mut edits = Vec::new(); - let edit_list = params - .get("edits") - .and_then(|e| e.as_array()) - .ok_or_else(|| err("mlsp.bad_request", "repair_apply 需要 params.edits"))?; - for e in edit_list { - let line = e - .get("line") - .and_then(|l| l.as_u64()) - .ok_or_else(|| err("mlsp.bad_request", "edit 缺 line"))? as u32; - let text = e.get("text").and_then(|t| t.as_str()).unwrap_or("").to_string(); - edits.push(match e.get("op").and_then(|o| o.as_str()) { - Some("replace") => crate::repair::Edit::Replace { line, text }, - Some("delete") => crate::repair::Edit::Delete { line }, - Some("insert") => crate::repair::Edit::InsertBefore { line, text }, - other => { - return Err(err( - "mlsp.bad_request", - format!("未知编辑 op {other:?}(replace / delete / insert)"), - )) - } - }); - } - - let check_labels = match params.get("check_labels") { - Some(Value::Bool(b)) => *b, - Some(Value::String(s)) => s != "off" && s != "false", - _ => false, - }; - - match crate::repair::apply_edits(&source, &ranges, &edits) { - Ok(new_source) => { - if params.get("write").and_then(|w| w.as_bool()).unwrap_or(false) { - let path = params - .get("path") - .and_then(|p| p.as_str()) - .ok_or_else(|| err("mlsp.bad_request", "write=true 需要 params.path"))?; - std::fs::write(path, &new_source) - .map_err(|e| err("mlsp.io_error", format!("写回 {path} 失败: {e}")))?; - } - // `` M6 (T1): the edit is the perfect moment to ask "did the - // description survive?" — before/after are both in hand, no VCS, - // no ledger, and the answer is scoped to this very edit. - let mut labels = Value::Null; - if check_labels { - if let (Ok(before), Ok(after)) = ( - crate::load::load_module_from_source(&source), - crate::load::load_module_from_source(&new_source), - ) { - let stale = crate::label::compare(&before, &after); - let newly = with_session(|s| s.record(&stale)); - labels = json!({ - "stale": stale - .iter() - .map(|s| json!({ - "label": s.label, - "line": s.line, - "code_past": s.code_past, - "code_now": s.code_now, - })) - .collect::>(), - "newly_seen": newly, - }); - } - } - Ok(json!({ - "source": new_source, - "edits_applied": edits.len(), - "labels": labels, - })) - } - Err(oos) => Err(json!({ - "code": "mlsp.repair_out_of_scope", - "message": format!( - "修复越界(abstain):触及行 {:?} 不在靶点范围 {:?} 内;已拒绝全部编辑,源未改动", - oos.lines, oos.ranges - ), - "lines": oos.lines, - "ranges": oos.ranges, - "on_violation": "abstain", - })), - } -} - -/// 取待修源码(source 直给 / path 读取)。 -fn source_text(params: &Value) -> Result { - if let Some(s) = params.get("source").and_then(|s| s.as_str()) { - return Ok(s.to_string()); - } - let path = params - .get("path") - .and_then(|p| p.as_str()) - .ok_or_else(|| err("mlsp.bad_request", "需要 params.source 或 params.path"))?; - std::fs::read_to_string(path) - .map_err(|e| err("mlsp.io_error", format!("读取 {path} 失败: {e}"))) -} - -/// 契约查询(T2.6):单元名 → 形参/返回/字段契约。 -fn schema(params: &Value) -> Result { - let (module, path) = module_from_params(params)?; - let unit = params - .get("unit") - .and_then(|u| u.as_str()) - .ok_or_else(|| err("mlsp.bad_request", "schema 需要 params.unit"))?; - let fun = find_fn(&module, unit) - .ok_or_else(|| err("mlsp.unknown_unit", format!("没有名为 `{unit}` 的单元")))?; - let mut vars = serde_json::Map::new(); - for (name, c) in &fun.var_contracts { - vars.insert(name.clone(), contract_json(c, path.as_deref())); - } - Ok(json!({ - "unit": fun.name, - "contract": fun.contract.as_ref().map(|c| contract_json(c, path.as_deref())), - "vars": Value::Object(vars), - "params_inferred": fun.params.iter().map(|p| json!({ - "name": p.name, "inferred": p.inferred - })).collect::>(), - })) -} - -// ---------- 公共小工具 ---------- - -/// Per-process T1 session state (`repair_apply` rounds accumulate here). -static SESSION: std::sync::Mutex> = - std::sync::Mutex::new(None); - -fn with_session(f: impl FnOnce(&mut crate::label::SessionSummary) -> T) -> T { - let mut guard = SESSION.lock().unwrap_or_else(|e| e.into_inner()); - let s = guard.get_or_insert_with(Default::default); - f(s) -} - -/// `session.summary` — report (and reset) the T1 counters. `` M6 -fn session_summary() -> Result { - let s = with_session(|s| { - let snap = s.clone(); - *s = Default::default(); - snap - }); - Ok(json!({ - "ok": true, - "labels_stale_seen": s.stale_seen, - "labels_fixed": s.fixed, - "labels_outstanding": s.items.len(), - "items": s.items, - })) -} - -/// `labels.search` — occlusion label query. `` M9 -/// -/// params: `{ source | path, grep?: [..] | "a,b", also_builtin?: bool, -/// group?: "未完成,假数据" }` -fn labels_search(params: &Value) -> Result { - let (module, _path) = module_from_params(params)?; - let mut words: Vec = match params.get("grep") { - Some(Value::String(s)) => crate::label::parse_words(s), - Some(Value::Array(a)) => a - .iter() - .filter_map(|v| v.as_str()) - .map(|s| s.to_string()) - .collect(), - _ => Vec::new(), - }; - let groups: Vec = match params.get("group").and_then(|g| g.as_str()) { - Some(spec) => crate::label::parse_words(spec), - None => crate::label::PENDING_GROUPS - .iter() - .map(|s| s.to_string()) - .collect(), - }; - let group_refs: Vec<&str> = groups.iter().map(|s| s.as_str()).collect(); - if words.is_empty() || params.get("also_builtin").and_then(|b| b.as_bool()) == Some(true) { - for w in crate::label::group_words(&group_refs) { - if !words.contains(&w) { - words.push(w); - } - } - } - let hits: Vec = crate::label::search(&module, &words) - .into_iter() - .map(|h| { - json!({ - "line": h.site.line, - "unit": h.site.unit, - "label": h.site.label, - "words": h.words, - "has_payload": h.site.has_payload, - }) - }) - .collect(); - Ok(json!({"ok": true, "words": words, "count": hits.len(), "hits": hits})) -} - -fn module_from_params(params: &Value) -> Result<(Module, Option), Value> { - if let Some(src) = params.get("source").and_then(|s| s.as_str()) { - let module = load::load_module_from_source(src) - .map_err(|e| diagnostic_err("mlsp.parse_error", &e))?; - return Ok((module, None)); - } - let path = params - .get("path") - .and_then(|p| p.as_str()) - .ok_or_else(|| err("mlsp.bad_request", "需要 params.path 或 params.source"))?; - let path = PathBuf::from(path); - let module = load::load_module(&path).map_err(|e| diagnostic_err("mlsp.parse_error", &e))?; - Ok((module, Some(path))) -} - -/// 错误链里有结构化诊断就原样透出(AI/MLSP 面不许拍平)。 -fn diagnostic_err(code: &str, e: &anyhow::Error) -> Value { - match Diagnostic::find(e) { - Some(d) => d.to_json(), - None => err(code, format!("{e:#}")), - } -} - -fn find_fn<'a>(module: &'a Module, name: &str) -> Option<&'a Function> { - fn walk<'a>(funs: &'a [Function], name: &str) -> Option<&'a Function> { - funs.iter().find(|f| f.name == name).or_else(|| { - funs.iter() - .find_map(|f| walk(&f.children, name)) - }) - } - walk(&module.functions, name) -} - -fn span_json(path: Option<&Path>, span: crate::diagnostics::Span) -> Value { - json!({ - "file": path.map(|p| p.display().to_string()), - "line": span.line, - "col": span.col, - }) -} - -fn ty_json(ty: &Ty) -> Value { - json!(ty.name()) -} - -fn contract_json(c: &Contract, path: Option<&Path>) -> Value { - json!({ - "params": c.params.iter().map(|p| json!({ - "name": p.name, "type": ty_json(&p.ty), "desc": p.desc - })).collect::>(), - "returns": c.returns.as_ref().map(|r| json!({ - "type": ty_json(&r.ty), "desc": r.desc - })), - "fields": c.fields.iter().map(|f| json!({ - "name": f.name, "type": ty_json(&f.ty), "nullable": f.nullable, "desc": f.desc - })).collect::>(), - "doc_anchor": c.anchor(path), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn fixture() -> PathBuf { - let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); - let root = std::env::temp_dir().join(format!("marqdo-mlsp-artifact-{stamp}")); - fs::create_dir_all(&root).unwrap(); - fs::write(root.join("main.mq.md"), "# main\n\n## add\n\n*`x` + 1*").unwrap(); - root - } - - #[test] - fn artifact_protocol_binds_then_executes_a_digest_checked_function() { - let root = fixture(); - let project = root.display().to_string(); - let found = dispatch(&json!({"method":"artifact.find","params":{"project":project,"query":"add"}})).unwrap(); - let candidate = found["candidates"].as_array().unwrap().iter().find(|v| v["kind"] == "function").unwrap(); - let id = candidate["artifact_id"].as_str().unwrap(); - let bound = dispatch(&json!({"method":"artifact.bind","params":{"project":root,"artifact_id":id}})).unwrap(); - let handle = &bound["handle"]; - assert!(handle.get("symbol_id").and_then(|v| v.as_str()).is_some()); - assert!(handle.get("source").is_some()); - let result = dispatch(&json!({"method":"artifact.execute","params":{"handle":handle,"inputs":{"x":4}}})).unwrap(); - assert_eq!(result["result"], 5); - assert_eq!(result["symbol_id"], handle["symbol_id"]); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn artifact_bind_rejects_non_pure_under_pure_policy() { - let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); - let root = std::env::temp_dir().join(format!("marqdo-mlsp-effect-{stamp}")); - fs::create_dir_all(&root).unwrap(); - fs::write( - root.join("main.mq.md"), - "# main\n\n## save\n\n> fs.write_text path=t.txt text=x\n\n*1*\n", - ) - .unwrap(); - let found = dispatch(&json!({"method":"artifact.find","params":{"project":root,"query":"save"}})).unwrap(); - let id = found["candidates"].as_array().unwrap().iter().find(|v| v["kind"] == "function").unwrap()["artifact_id"] - .as_str() - .unwrap(); - let err = dispatch(&json!({"method":"artifact.bind","params":{"project":root,"artifact_id":id,"policy":"pure"}})) - .unwrap_err(); - assert_eq!(err["code"], "artifact.effect_denied"); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn link_resolution_never_silently_selects_a_nonexistent_target() { - let root = fixture(); - let result = dispatch(&json!({"method":"link.resolve","params":{"project":root,"payload":"does_not_exist"}})).unwrap(); - assert_eq!(result["resolution"], "unresolved"); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/narrative_ratio.rs b/src/narrative_ratio.rs deleted file mode 100755 index 71442ef..0000000 --- a/src/narrative_ratio.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Narration ratio gate: each function unit should be ≥50% narrative text. -//! -//! Used by `marqdo check --narrative-ratio` and extension skill dogfood. - -use std::path::Path; - -use anyhow::Result; - -use crate::ast::Function; -use crate::diagnostics::{Diagnostic, Span}; -use crate::load::load_module; - -const MIN_RATIO: f64 = 0.5; - -#[derive(Debug, Clone)] -pub struct UnitReport { - pub name: String, - pub line: u32, - pub narrative: usize, - pub total: usize, - pub ratio: f64, - pub pass: bool, -} - -/// Check one `.mq.md` file; returns Error diagnostics for failing units. -pub fn check_file(path: &Path) -> Result> { - let reports = check_file_source(path)?; - Ok(reports - .iter() - .filter(|r| !r.pass) - .map(|r| { - Diagnostic::new( - Some(path), - Span::new(r.line, 1), - format!( - "narrative ratio {:.0}% < 50% for function `{}` (narrative={}, total={})", - r.ratio * 100.0, - r.name, - r.narrative, - r.total - ), - ) - .with_code("narrative.ratio") - }) - .collect()) -} - -/// Measure using original file text between this function's line and the next heading. -pub fn check_file_source(path: &Path) -> Result> { - let text = std::fs::read_to_string(path)?; - let module = load_module(path)?; - Ok(measure_source_units(&text, &module.functions)) -} - -pub fn measure_source_units(source: &str, functions: &[Function]) -> Vec { - let lines: Vec<&str> = source.lines().collect(); - let mut starts: Vec<(String, u32, usize)> = Vec::new(); - collect_starts(functions, &mut starts); - starts.sort_by_key(|(_, line, _)| *line); - - let mut out = Vec::new(); - for (i, (name, line, _)) in starts.iter().enumerate() { - let start = (*line as usize).saturating_sub(1); - let end = starts - .get(i + 1) - .map(|(_, l, _)| (*l as usize).saturating_sub(1)) - .unwrap_or(lines.len()); - let chunk = lines[start..end.min(lines.len())].join("\n"); - let (narrative, code) = split_narrative_code(&chunk); - let total = narrative + code; - let ratio = if total == 0 { - 1.0 - } else { - narrative as f64 / total as f64 - }; - out.push(UnitReport { - name: name.clone(), - line: *line, - narrative, - total, - ratio, - pass: total == 0 || ratio + f64::EPSILON >= MIN_RATIO, - }); - } - out -} - -fn collect_starts(fns: &[Function], out: &mut Vec<(String, u32, usize)>) { - for f in fns { - out.push((f.name.clone(), f.span.line, f.body.len())); - collect_starts(&f.children, out); - } -} - -/// Split a function unit's source into narrative vs code character counts. -/// -/// Count executable inline payloads separately from the sentences containing them. -/// Occlusion labels and unbound contract/documentation tables are narration; -/// bound data tables, expression payloads, code fences and structure markers are code. -/// Display formulas retain the existing documentation treatment. -pub fn split_narrative_code(chunk: &str) -> (usize, usize) { - use crate::parse::{scan_md_links_in_line, scan_prose_line, ProseBit}; - let mut narrative = 0usize; - let mut code = 0usize; - let mut in_fence = false; - let mut fence_is_formula = false; - let mut pending_table = false; - let mut data_table = false; - for line in chunk.lines() { - let trimmed = line.trim(); - let count = line.chars().count(); - if trimmed.starts_with("```") || trimmed.starts_with("~~~") { - in_fence = !in_fence; - fence_is_formula = trimmed.contains("$$") || trimmed == "$$"; - code += count; - continue; - } - if in_fence { - if fence_is_formula { - narrative += count; - } else { - code += count; - } - continue; - } - if trimmed.is_empty() { - data_table = false; - continue; - } - if trimmed.starts_with('|') { - if pending_table { - data_table = true; - pending_table = false; - } - if data_table { - code += count; - } else { - narrative += count; - } - continue; - } - data_table = false; - pending_table = (trimmed.starts_with('`') && trimmed.ends_with('=')) - || (trimmed.starts_with("**") - && trimmed.ends_with("**") - && trimmed[2..trimmed.len() - 2].trim_end().ends_with('=')); - if trimmed.starts_with("$$") { - narrative += count; - continue; - } - let mut inline_code = 0; - for bit in scan_prose_line(line) { - let (inner, markers) = match bit { - ProseBit::BoldCode { inner, .. } => (inner, 4), - ProseBit::ItalicReturn { inner, .. } => (inner, 2), - ProseBit::Decl { .. } => continue, - }; - let labels: usize = scan_md_links_in_line(&inner, 0) - .iter() - .map(|link| link.label.chars().count()) - .sum(); - inline_code += (inner.chars().count() + markers).saturating_sub(labels); - } - if inline_code > 0 { - let actual = inline_code.min(count); - code += actual; - narrative += count - actual; - } else if is_code_line(trimmed) || pending_table { - let labels: usize = scan_md_links_in_line(line, 0) - .iter() - .map(|link| link.label.chars().count()) - .sum(); - narrative += labels.min(count); - code += count.saturating_sub(labels); - } else { - narrative += count; - } - } - (narrative, code) -} - -fn is_code_line(trimmed: &str) -> bool { - if trimmed.starts_with('>') { - return true; - } - if trimmed.starts_with("**") && trimmed.ends_with("**") { - return true; - } - if trimmed.starts_with('*') && trimmed.ends_with('*') && !trimmed.starts_with("**") { - // Return line - return true; - } - if trimmed.starts_with("+ `") || trimmed.starts_with("+`") { - return true; - } - // Contract / documentation tables are narration surface (param and return - // tables under skill tools), not executable code budget. - if trimmed.starts_with('|') { - return false; - } - if trimmed.starts_with('#') { - return true; - } - if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(". ") { - // Branch list `1. …` — executable control - return true; - } - if trimmed.starts_with("- ") && (trimmed.contains('>') || trimmed.contains('`')) { - return true; - } - if trimmed.starts_with("---") { - return true; - } - if trimmed.starts_with("import:") || trimmed.starts_with("导入:") { - return true; - } - false -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn prose_heavy_unit_passes() { - let chunk = r#" -## hadamard - -The Hadamard gate creates equal superposition from the computational basis. -It is the unitary matrix shown below and is central to many algorithms. - -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | target | - -This paragraph keeps narration above half even with a small table. - -| 返回 | 类型 | 说明 | -|------|------|------| -| | handle | circuit | - -*None* -"#; - let (n, c) = split_narrative_code(chunk); - assert!((n as f64) / ((n + c) as f64) >= 0.5, "n={n} c={c}"); - } - - #[test] - fn api_list_fails() { - let chunk = r#" -## h - + `qubit`=0 -*> quantum_h circuit=`self` qubit=`qubit`* -"#; - let (n, c) = split_narrative_code(chunk); - assert!((n as f64) / ((n + c) as f64) < 0.5, "n={n} c={c}"); - } -} - -#[cfg(test)] -mod inline_measurement_tests { - use super::*; - #[test] - fn inline_expressions_are_not_all_prose() { - let (n, c) = - split_narrative_code("Now **out = [Read the value](lookup(key=\"selected\"))**."); - assert_eq!( - n, - "Now .".chars().count() + "Read the value".chars().count() - ); - assert!(c > n); - } - #[test] - fn bound_data_is_code_but_contracts_are_narration() { - let table = "| field | value |\n|---|---|\n| example | item |"; - let (n, c) = split_narrative_code(table); - assert!(n > 0 && c == 0); - let (n, c) = split_narrative_code(&format!("`record` =\n\n{table}")); - assert_eq!(n, 0); - assert!(c > 0); - } -} diff --git a/src/parse/expr.rs b/src/parse/expr.rs deleted file mode 100755 index 6ed2e4c..0000000 --- a/src/parse/expr.rs +++ /dev/null @@ -1,2332 +0,0 @@ -//! Expression parser (recursive descent over a single string). - -use anyhow::{bail, Result}; - -use crate::ast::{BinaryOp, CallExpr, Expr, IndexKey, InterpPart, Literal, UnaryOp}; - -pub fn parse_expr(input: &str) -> Result { - parse_expr_mode(input, false) -} - -/// Markup mode for `[描述](实现)` vs the legacy `[键](集合)` index. `` M2 -/// -/// `Classic` keeps the legacy index semantics; `Occlusion` reads the same shape -/// as an occlusion. Every shipped module declares its mode and new/unmarked -/// sources use `Occlusion`. The legacy grammar is available only through an -/// explicit `markup: classic` declaration or the one-cycle CLI compatibility -/// flag. No environment/process switch exists. -#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] -pub enum Markup { - Classic, - #[default] - Occlusion, -} - -thread_local! { - /// Scoped parser context for loader/migration calls. It is never mutated - /// from environment/process configuration, so two project files cannot - /// silently change each other's grammar. - static MARKUP_OVERRIDE: std::cell::Cell> = const { std::cell::Cell::new(None) }; -} - -/// Run `f` with `markup` as the effective mode for everything parsed inside. -/// -/// Used by the loader and migration verifier to give one parse an explicit -/// mode. Imported files establish their own nested scope from frontmatter. -pub fn with_markup(markup: Markup, f: impl FnOnce() -> T) -> T { - let saved = MARKUP_OVERRIDE.with(|c| c.replace(Some(markup))); - let out = f(); - MARKUP_OVERRIDE.with(|c| c.set(saved)); - out -} - -pub fn markup_default() -> Markup { - if let Some(m) = MARKUP_OVERRIDE.with(|c| c.get()) { - return m; - } - Markup::Occlusion -} - -/// Italic / bold value syntax: bare words are variables; text needs `"…"` / `'…'`. -pub fn parse_expr_prefer_var(input: &str) -> Result { - parse_expr_mode(input, true) -} - -fn parse_expr_mode(input: &str, prefer_var: bool) -> Result { - parse_expr_opts(input, prefer_var, true) -} - -/// Parse a full expression under an explicit markup mode (tests / migration). -pub fn parse_expr_markup(input: &str, prefer_var: bool, markup: Markup) -> Result { - let mut p = Parser::new(input.trim(), prefer_var, true).with_markup(markup); - let e = p.parse_or()?; - p.skip_ws(); - if !p.rest().is_empty() { - bail!("trailing input in expression: {:?}", p.rest()); - } - Ok(e) -} - -/// Parse a full expression; `allow_paren_call` controls `name(args)` postfix calls. -fn parse_expr_opts(input: &str, prefer_var: bool, allow_paren_call: bool) -> Result { - let mut p = Parser::new(input.trim(), prefer_var, allow_paren_call); - let e = p.parse_or()?; - p.skip_ws(); - if !p.rest().is_empty() { - bail!("trailing input in expression: {:?}", p.rest()); - } - Ok(e) -} - -/// Argument / template RHS: prefer a full expression; else interpolated text. -/// Hyphenated prose (`none-falsy`) is not parsed as subtraction. -/// Quoted `"..."` always uses the expression parser (never the hyphen short-circuit). -pub fn parse_value_or_interp(input: &str) -> Result { - let s = input.trim(); - if s.is_empty() { - return Ok(Expr::Literal(Literal::Text(String::new()))); - } - if s.starts_with('"') || s.starts_with('\'') { - return match parse_expr(s) { - Ok(e) => Ok(e), - Err(_) => Ok(parse_interp(s)), - }; - } - if has_hyphenated_prose(s) { - return Ok(parse_interp(s)); - } - match parse_expr(s) { - Ok(e) => Ok(e), - Err(_) => Ok(parse_interp(s)), - } -} - -/// Call-arg / param-default values: like [`parse_value_or_interp`], but also treat a chain of -/// unspaced `Text / Text` divisions as a single path string (`a/b`, `.marqdo/agent-kb`). -/// Real math (`1/2`, `` `n` / 2 ``) is unchanged. -pub fn parse_call_arg_value(input: &str) -> Result { - parse_call_arg_value_mode(input, false, false) -} - -/// Shared call-argument value parsing. -/// -/// `allow_call` is true only inside `callee(args)` (paren form), where arguments -/// are expression-like; classic space-separated values stay text-like so that -/// `source=print(2+2)` remains the text `print(2+2)`. `` M1 -fn parse_call_arg_value_mode(input: &str, prefer_var: bool, allow_call: bool) -> Result { - let s = input.trim(); - if s.is_empty() { - return Ok(Expr::Literal(Literal::Text(String::new()))); - } - if s.starts_with('"') || s.starts_with('\'') { - return match parse_expr_opts(s, prefer_var, allow_call) { - Ok(e) => Ok(e), - Err(_) => Ok(parse_interp(s)), - }; - } - // Nested calls may contain hyphenated paths in their own quoted args. - // The inner argument parser still preserves plain hyphenated prose. - if has_hyphenated_prose(s) && !(allow_call && s.contains('(')) { - return Ok(parse_interp(s)); - } - match parse_expr_opts(s, prefer_var, allow_call) { - Ok(e) => Ok(if prefer_var { - e - } else { - collapse_text_div_path(e, s) - }), - Err(_) => { - // ext/web paths: `nav.`nav``, `articles.`articles`.title` — ticks are path - // punctuation, not interpolation. Plain `/about` is prose too. - if prefer_var { - if s.starts_with('/') || s.contains(".`") { - Ok(Expr::Literal(Literal::Text(s.to_string()))) - } else { - Ok(parse_interp(s)) - } - } else if s.contains(".`") { - Ok(Expr::Literal(Literal::Text(s.to_string()))) - } else { - Ok(parse_interp(s)) - } - } - } -} - -/// Like [`parse_call_arg_value`], but for call args inside `*…*` / `**…**` -/// value-expression segments: a bare word is a **variable** (not a text literal). -/// Quoted strings, hyphenated prose, and `/path` prose stay text; `` `x` `` still works. -fn is_text_only_div_chain(e: &Expr) -> bool { - match e { - Expr::Literal(Literal::Text(_)) => true, - Expr::Binary { - op: BinaryOp::Div, - left, - right, - } => { - is_text_only_div_chain(left) - && matches!(right.as_ref(), Expr::Literal(Literal::Text(_))) - } - _ => false, - } -} - -fn expr_has_div(e: &Expr) -> bool { - match e { - Expr::Binary { - op: BinaryOp::Div, .. - } => true, - Expr::Binary { left, right, .. } => expr_has_div(left) || expr_has_div(right), - Expr::Unary { expr, .. } => expr_has_div(expr), - _ => false, - } -} - -fn collapse_text_div_path(e: Expr, raw: &str) -> Expr { - if expr_has_div(&e) && is_text_only_div_chain(&e) { - parse_interp(raw) - } else { - e - } -} - -fn has_hyphenated_prose(s: &str) -> bool { - let chars: Vec = s.chars().collect(); - for i in 1..chars.len().saturating_sub(1) { - if chars[i] != '-' { - continue; - } - let left = chars[i - 1]; - let right = chars[i + 1]; - if left.is_whitespace() || right.is_whitespace() || left == '`' || right == '`' { - continue; - } - // `none-falsy` / `Hello-World` — not `` `n` - 1 `` - if left.is_alphanumeric() - || right.is_alphanumeric() - || !left.is_ascii() - || !right.is_ascii() - { - return true; - } - } - false -} - -pub fn parse_interp(s: &str) -> Expr { - let mut parts = Vec::new(); - let mut rest = s; - while !rest.is_empty() { - if let Some(start) = rest.find('`') { - if start > 0 { - parts.push(InterpPart::Lit(rest[..start].to_string())); - } - let after = &rest[start + 1..]; - if let Some(end) = after.find('`') { - let name = after[..end].to_string(); - let mut tail = &after[end + 1..]; - // `` `name`[^a][^b] `` → Index part (chained labels fold). - if let Some(labels) = take_index_chain(&mut tail) { - parts.push(InterpPart::Index { base: name, labels }); - } else { - parts.push(InterpPart::Var(name)); - } - rest = tail; - } else { - parts.push(InterpPart::Lit(format!("`{after}"))); - break; - } - } else { - parts.push(InterpPart::Lit(rest.to_string())); - break; - } - } - if parts.len() == 1 { - match &parts[0] { - InterpPart::Lit(t) => return Expr::Literal(Literal::Text(t.clone())), - InterpPart::Var(n) => return Expr::Var(n.clone()), - InterpPart::Index { base, labels } => { - let mut e = Expr::Var(base.clone()); - for label in labels { - e = Expr::Index { - base: Box::new(e), - label: IndexKey::Lit(label.clone()), - }; - } - return e; - } - } - } - Expr::Interp(parts) -} - -/// If `s` starts with one or more `[^label]` (no whitespace), consume them. -fn take_index_chain(s: &mut &str) -> Option> { - let mut labels = Vec::new(); - loop { - if !s.starts_with("[^") { - break; - } - let after_open = &s[2..]; - let Some(close) = after_open.find(']') else { - break; - }; - let label = after_open[..close].trim().to_string(); - if label.is_empty() { - break; - } - labels.push(label); - *s = &after_open[close + 1..]; - } - if labels.is_empty() { - None - } else { - Some(labels) - } -} - -struct Parser<'a> { - src: &'a str, - i: usize, - /// When true (italic/bold), bare words are variables, not text literals. - prefer_var: bool, - /// `` M2: how to read `[…] (...)`. - markup: Markup, - /// `` M1: allow `name(args)` postfix calls inside this expression. - /// Classic (space-separated) call *values* stay text-like, so they turn - /// this off to keep `source=print(2+2)` as text. - allow_paren_call: bool, -} - -impl<'a> Parser<'a> { - fn new(src: &'a str, prefer_var: bool, allow_paren_call: bool) -> Self { - Self { - src, - i: 0, - prefer_var, - markup: markup_default(), - allow_paren_call, - } - } - - fn with_markup(mut self, markup: Markup) -> Self { - self.markup = markup; - self - } - - fn rest(&self) -> &str { - &self.src[self.i..] - } - - fn skip_ws(&mut self) { - while let Some(c) = self.peek_char() { - if c.is_whitespace() { - self.bump_char(); - } else { - break; - } - } - } - - fn peek_char(&self) -> Option { - self.rest().chars().next() - } - - fn bump_char(&mut self) -> Option { - let mut chars = self.rest().chars(); - let c = chars.next()?; - self.i += c.len_utf8(); - Some(c) - } - - fn starts_with(&self, s: &str) -> bool { - self.rest().starts_with(s) - } - - fn eat(&mut self, s: &str) -> bool { - if self.starts_with(s) { - self.i += s.len(); - true - } else { - false - } - } - - /// Eat English or Chinese logic keyword with word-boundary check. - fn eat_logic_kw(&mut self, en: &str, zh: &str) -> bool { - if self.starts_with(en) && is_word_end(self.rest(), en.len()) { - self.i += en.len(); - return true; - } - if self.starts_with(zh) && is_word_end(self.rest(), zh.len()) { - self.i += zh.len(); - return true; - } - false - } - - /// Consume up to `max` hex digits; fewer (even zero) are allowed. - /// Returns the parsed value, or an error if a digit exceeds the limit - /// would overflow (`\xHH` requires exactly 2, `\u{...}` up to 6). - fn take_hex_digits(&mut self, max: usize) -> Result { - let mut value: u64 = 0; - let mut count = 0; - while count < max { - let Some(c) = self.peek_char() else { - break; - }; - let Some(d) = c.to_digit(16) else { - break; - }; - value = value * 16 + u64::from(d); - self.bump_char(); - count += 1; - } - Ok(value) - } - - fn parse_or(&mut self) -> Result { - let mut left = self.parse_and()?; - loop { - self.skip_ws(); - if self.eat_logic_kw("or", "或") { - let right = self.parse_and()?; - left = Expr::Binary { - op: BinaryOp::Or, - left: Box::new(left), - right: Box::new(right), - }; - } else { - break; - } - } - Ok(left) - } - - fn parse_and(&mut self) -> Result { - let mut left = self.parse_cmp()?; - loop { - self.skip_ws(); - if self.eat_logic_kw("and", "且") { - let right = self.parse_cmp()?; - left = Expr::Binary { - op: BinaryOp::And, - left: Box::new(left), - right: Box::new(right), - }; - } else { - break; - } - } - Ok(left) - } - - fn parse_cmp(&mut self) -> Result { - let mut left = self.parse_add()?; - self.skip_ws(); - let op = if self.eat("==") { - Some(BinaryOp::Eq) - } else if self.eat("!=") { - Some(BinaryOp::Ne) - } else if self.eat("<=") { - Some(BinaryOp::Le) - } else if self.eat(">=") { - Some(BinaryOp::Ge) - } else if self.eat("<") { - Some(BinaryOp::Lt) - } else if self.eat(">") { - Some(BinaryOp::Gt) - } else { - None - }; - if let Some(op) = op { - let right = self.parse_add()?; - left = Expr::Binary { - op, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_add(&mut self) -> Result { - let mut left = self.parse_mul()?; - loop { - self.skip_ws(); - if self.eat("+") { - let right = self.parse_mul()?; - left = Expr::Binary { - op: BinaryOp::Add, - left: Box::new(left), - right: Box::new(right), - }; - } else if self.eat("-") { - let right = self.parse_mul()?; - left = Expr::Binary { - op: BinaryOp::Sub, - left: Box::new(left), - right: Box::new(right), - }; - } else { - break; - } - } - Ok(left) - } - - fn parse_mul(&mut self) -> Result { - let mut left = self.parse_unary()?; - loop { - self.skip_ws(); - if self.eat("*") { - let right = self.parse_unary()?; - left = Expr::Binary { - op: BinaryOp::Mul, - left: Box::new(left), - right: Box::new(right), - }; - } else if self.eat("/") { - let right = self.parse_unary()?; - left = Expr::Binary { - op: BinaryOp::Div, - left: Box::new(left), - right: Box::new(right), - }; - } else { - break; - } - } - Ok(left) - } - - fn parse_unary(&mut self) -> Result { - self.skip_ws(); - if self.eat_logic_kw("not", "非") { - let expr = self.parse_unary()?; - return Ok(Expr::Unary { - op: UnaryOp::Not, - expr: Box::new(expr), - }); - } - if self.eat("-") { - // The magnitude of i64::MIN is not itself a positive i64 literal. - // Recognize its signed token before recursively parsing a unary - // operand; decimal literals keep their floating-point type. - let start = self.i; - self.skip_ws(); - let digits = self.rest().bytes().take_while(u8::is_ascii_digit).count(); - let end = self.i + digits; - if &self.src[self.i..end] == "9223372036854775808" - && !self.src[end..].starts_with(['.', 'e', 'E']) - { - self.i = end; - return Ok(Expr::Literal(Literal::Int(i64::MIN))); - } - self.i = start; - let expr = self.parse_unary()?; - return Ok(Expr::Unary { - op: UnaryOp::Neg, - expr: Box::new(expr), - }); - } - self.parse_primary() - } - - fn parse_primary(&mut self) -> Result { - self.skip_ws(); - if self.eat("(") { - let e = self.parse_or()?; - self.skip_ws(); - if !self.eat(")") { - bail!("expected ')'"); - } - return Ok(e); - } - // Link-shaped index `[key](collection)` vs bracket-marked call `[callee] …` - // vs JSON-ish `[…]` (arg text fallback when expr parse fails). - if self.starts_with("[") && !self.starts_with("[^") { - if self.markup == Markup::Occlusion && occlusion_shape_ahead(self.rest()) { - return self.parse_occluded(); - } - if link_index_shape_ahead(self.rest()) { - return self.parse_link_index(); - } - if bracket_callee_shape_ahead(self.rest()) { - let rest = self.rest(); - let prefer_var = self.prefer_var; - let (call, consumed) = parse_call_tail(rest, prefer_var)?; - self.i += consumed; - return Ok(Expr::Call(call)); - } - bail!("unexpected '[' in expression (not a link index or bracket call)"); - } - if self.eat("\"") { - return self.parse_quoted_string('"'); - } - if self.eat("'") { - return self.parse_quoted_string('\''); - } - if self.eat("`") { - let start = self.i; - while let Some(c) = self.peek_char() { - if c == '`' { - break; - } - self.bump_char(); - } - let name = self.src[start..self.i].to_string(); - if !self.eat("`") { - bail!("unterminated `name`"); - } - // Parse a quoted receiver's explicit method before its value. - if self.allow_paren_call && self.rest().starts_with('.') { - let call_start = start - 1; - if let Some((call, used)) = try_paren_call(&self.src[call_start..], self.prefer_var)? { - if call.receiver.is_some() { - self.i = call_start + used; - return Ok(Expr::Call(call)); - } - } - } - return self.parse_index_chain(Expr::Var(name)); - } - // `礼貌 [问候] x` — after quotes/ticks so `[DONE]` inside strings is safe. - if let Some((call, consumed)) = try_bracket_marked_call(self.rest(), self.prefer_var)? { - self.i += consumed; - return Ok(Expr::Call(call)); - } - if self.eat(">") { - // Inline call: `> name k=v` - self.skip_ws(); - let prefer_var = self.prefer_var; - return Ok(Expr::Call(parse_call_tail(self.rest(), prefer_var).map( - |(c, consumed)| { - self.i += consumed; - c - }, - )?)); - } - if self.starts_with("True") && is_word_end(self.rest(), 4) { - self.i += 4; - return Ok(Expr::Literal(Literal::Bool(true))); - } - if self.starts_with("真") && is_word_end(self.rest(), '真'.len_utf8()) { - self.i += '真'.len_utf8(); - return Ok(Expr::Literal(Literal::Bool(true))); - } - if self.starts_with("False") && is_word_end(self.rest(), 5) { - self.i += 5; - return Ok(Expr::Literal(Literal::Bool(false))); - } - if self.starts_with("假") && is_word_end(self.rest(), '假'.len_utf8()) { - self.i += '假'.len_utf8(); - return Ok(Expr::Literal(Literal::Bool(false))); - } - if self.starts_with("None") && is_word_end(self.rest(), 4) { - self.i += 4; - return Ok(Expr::Literal(Literal::None)); - } - if self.starts_with("空") && is_word_end(self.rest(), '空'.len_utf8()) { - self.i += '空'.len_utf8(); - return Ok(Expr::Literal(Literal::None)); - } - if self - .peek_char() - .map(|c| c.is_ascii_digit()) - .unwrap_or(false) - || (self.peek_char() == Some('.') - && self - .rest() - .chars() - .nth(1) - .map(|c| c.is_ascii_digit()) - .unwrap_or(false)) - { - let start = self.i; - while self - .peek_char() - .map(|c| c.is_ascii_digit()) - .unwrap_or(false) - { - self.bump_char(); - } - if self.peek_char() == Some('.') { - self.bump_char(); - let frac_start = self.i; - while self - .peek_char() - .map(|c| c.is_ascii_digit()) - .unwrap_or(false) - { - self.bump_char(); - } - // Require at least one digit on one side of the dot. - let int_part = &self.src[start..frac_start.saturating_sub(1)]; - let frac_part = &self.src[frac_start..self.i]; - if int_part.is_empty() && frac_part.is_empty() { - bail!("invalid number literal"); - } - let n: f64 = self.src[start..self.i] - .parse() - .map_err(|e| anyhow::anyhow!("invalid float: {e}"))?; - return Ok(Expr::Literal(Literal::Num(n))); - } - let n: i64 = self.src[start..self.i].parse()?; - return Ok(Expr::Literal(Literal::Int(n))); - } - // Bare identifier / text word. If immediately followed by `[^…]`, treat as - // variable + footnote index (exemption: ticks optional when `[^` marks the slot). - if self - .peek_char() - .map(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()) - .unwrap_or(false) - { - let start = self.i; - while let Some(c) = self.peek_char() { - if c.is_whitespace() - || matches!( - c, - '=' | '+' - | '-' - | '*' - | '/' - | '<' - | '>' - | '(' - | ')' - | '`' - | '|' - | ',' - | '"' - | '\'' - | '[' - | ']' - ) - { - break; - } - self.bump_char(); - } - let word = self.src[start..self.i].to_string(); - // `name(args)` postfix call: `(` must follow immediately. `` M1 - if self.allow_paren_call && self.rest().starts_with('(') { - let from_word = &self.src[start..]; - if let Some((call, used)) = try_paren_call(from_word, self.prefer_var)? { - self.i = start + used; - return Ok(Expr::Call(call)); - } - } - // A dotted definition path in a value position is a zero-argument - // call. This makes a documented fact such as `facts.Person.birth_year` - // executable without ceremonial `()`. - // Classic expression contexts intentionally preserve bare dotted - // text such as `refunds.md` in branch conditions. The new path - // spelling is enabled only on the executable value surface - // (`*…*` / `**…**`), where bare words already mean bindings. - if self.prefer_var { - if let Some(path) = split_lib_path_callee(&word) { - let callee = path.last().cloned().unwrap_or_default(); - return Ok(Expr::Call(CallExpr { - callee, - path: Some(path), - receiver: None, - args: Vec::new(), - pre_modifiers: Vec::new(), - bracket_marked: false, - })); - } - } - self.skip_ws(); - if self.starts_with("[^") { - return self.parse_index_chain(Expr::Var(word)); - } - if self.prefer_var { - return Ok(Expr::Var(word)); - } - return Ok(Expr::Literal(Literal::Text(word))); - } - bail!("unexpected expression input: {:?}", self.rest()); - } - - /// `[描述](实现)` — occlusion. `` M2 - /// - /// - label: raw prose up to `]` (`\]` escapes a literal bracket) - /// - payload: expression, or empty → `None` (empty-payload stub) - fn parse_occluded(&mut self) -> Result { - if !self.eat("[") { - bail!("expected '[' for occlusion"); - } - let mut label = String::new(); - loop { - let Some(c) = self.peek_char() else { - bail!("unterminated occlusion label `[…]`"); - }; - match c { - ']' => { - self.bump_char(); - break; - } - '\\' => { - self.bump_char(); - match self.peek_char() { - Some(n) => { - label.push(n); - self.bump_char(); - } - None => bail!("unterminated escape in occlusion label"), - } - } - '\n' | '\r' => bail!("unterminated occlusion label `[…]`"), - _ => { - label.push(c); - self.bump_char(); - } - } - } - self.skip_ws(); - if !self.eat("(") { - bail!("occlusion `[描述]` must be followed by `(实现)`"); - } - self.skip_ws(); - if self.eat(")") { - return Ok(Expr::Occluded { - label: label.trim().to_string(), - payload: None, - }); - } - // `()` is machine code: the payload always allows `callee(args)` even - // when the occlusion sits inside a text-like argument value. `` M7 - let saved_allow = self.allow_paren_call; - self.allow_paren_call = true; - let inner = self.parse_or(); - self.allow_paren_call = saved_allow; - let inner = inner?; - self.skip_ws(); - if !self.eat(")") { - bail!("expected ')' to close occlusion payload"); - } - Ok(Expr::Occluded { - label: label.trim().to_string(), - payload: Some(Box::new(inner)), - }) - } - - /// `` `xs`[^1] `` / `m[^key]` / chained `m[^k][^1]` (base already parsed). - fn parse_index_chain(&mut self, mut expr: Expr) -> Result { - loop { - self.skip_ws(); - if !self.starts_with("[^") { - break; - } - let label = self.parse_footnote_label()?; - expr = Expr::Index { - base: Box::new(expr), - label, - }; - } - Ok(expr) - } - - /// `[key](collection)` — preferred collection get (GFM link shape). - fn parse_link_index(&mut self) -> Result { - if !self.eat("[") { - bail!("expected '[' for link index"); - } - self.skip_ws(); - let label = if self.eat("`") { - let start = self.i; - while let Some(c) = self.peek_char() { - if c == '`' { - break; - } - if c == '\n' || c == '\r' || c == ']' { - bail!("unterminated link-index var `[`…`](…)`"); - } - self.bump_char(); - } - let name = self.src[start..self.i].trim().to_string(); - if !self.eat("`") { - bail!("unterminated link-index var `[`…`](…)`"); - } - if name.is_empty() { - bail!("empty link-index var `[`](…)`"); - } - IndexKey::Var(name) - } else { - let start = self.i; - while let Some(c) = self.peek_char() { - if c == ']' { - break; - } - if c == '\n' || c == '\r' || c == '[' { - bail!("unterminated or nested link-index key `[…](…)`"); - } - self.bump_char(); - } - let key = self.src[start..self.i].trim().to_string(); - if key.is_empty() { - bail!("empty link-index key `[](…)`"); - } - IndexKey::Lit(key) - }; - self.skip_ws(); - if !self.eat("]") { - bail!("expected ']' after link-index key"); - } - self.skip_ws(); - if !self.eat("(") { - bail!("expected '(' collection after link-index `[key]`"); - } - let base = self.parse_or()?; - self.skip_ws(); - if !self.eat(")") { - bail!("expected ')' after link-index collection"); - } - let expr = Expr::Index { - base: Box::new(base), - label, - }; - // Legacy: allow trailing footnote chain on the result. - self.parse_index_chain(expr) - } - - /// `"..."` or `'...'` with escapes and `` `var` `` interpolation. - fn parse_quoted_string(&mut self, quote: char) -> Result { - use crate::ast::InterpPart; - let mut parts: Vec = Vec::new(); - let mut lit = String::new(); - loop { - let Some(c) = self.peek_char() else { - bail!("unterminated {quote} string"); - }; - if c == quote { - self.bump_char(); - break; - } - if c == '\\' { - self.bump_char(); - let esc = self - .peek_char() - .ok_or_else(|| anyhow::anyhow!("dangling \\ in string"))?; - self.bump_char(); - match esc { - 'n' => lit.push('\n'), - 't' => lit.push('\t'), - 'r' => lit.push('\r'), - '\\' => lit.push('\\'), - '"' => lit.push('"'), - '\'' => lit.push('\''), - 'x' => { - let start = self.i; - let cp = self.take_hex_digits(2)?; - if self.i - start == 2 { - lit.push( - char::from_u32(cp as u32) - .ok_or_else(|| anyhow::anyhow!("invalid \\x escape"))?, - ); - } else { - // `\x` with fewer than two hex digits is not a valid - // escape: keep it verbatim. - self.i = start; - lit.push('\\'); - lit.push('x'); - } - } - 'u' => { - if self.eat("{") { - let digits = self.take_hex_digits(6)?; - if !self.eat("}") { - bail!("unterminated \\u{{...}} escape in string"); - } - lit.push( - char::from_u32(digits as u32) - .ok_or_else(|| anyhow::anyhow!("invalid \\u escape"))?, - ); - } else { - // `\u` without `{…}` is not a valid escape: keep it verbatim. - lit.push('\\'); - lit.push('u'); - } - } - // Unknown escapes are kept verbatim (`\q` → `\q`). - other => { - lit.push('\\'); - lit.push(other); - } - } - continue; - } - if c == '`' { - if !lit.is_empty() { - parts.push(InterpPart::Lit(std::mem::take(&mut lit))); - } - self.bump_char(); - let start = self.i; - while let Some(ch) = self.peek_char() { - if ch == '`' { - break; - } - self.bump_char(); - } - let name = self.src[start..self.i].to_string(); - if !self.eat("`") { - bail!("unterminated `name` in string"); - } - // `` `name`[^a][^b] `` inside a quoted string → footnote index parts. - if let Some(labels) = self.take_index_chain_in_string()? { - parts.push(InterpPart::Index { base: name, labels }); - } else { - parts.push(InterpPart::Var(name)); - } - continue; - } - lit.push(c); - self.bump_char(); - } - if !lit.is_empty() { - parts.push(InterpPart::Lit(lit)); - } - if parts.is_empty() { - return Ok(Expr::Literal(Literal::Text(String::new()))); - } - if parts.len() == 1 { - return Ok(match parts.remove(0) { - InterpPart::Lit(t) => Expr::Literal(Literal::Text(t)), - InterpPart::Var(n) => Expr::Var(n), - InterpPart::Index { base, labels } => { - let mut e = Expr::Var(base); - for label in labels { - e = Expr::Index { - base: Box::new(e), - label: IndexKey::Lit(label), - }; - } - e - } - }); - } - Ok(Expr::Interp(parts)) - } - - /// In quoted strings, consume `[^label]` chains following `` `var` ``. - fn take_index_chain_in_string(&mut self) -> Result>> { - let mut labels = Vec::new(); - loop { - if !self.starts_with("[^") { - break; - } - self.bump_char(); - self.bump_char(); // consume `[^` - let start = self.i; - while let Some(ch) = self.peek_char() { - if ch == ']' { - break; - } - if ch == '\n' || ch == '\r' { - bail!("unterminated footnote index [^…] in string"); - } - self.bump_char(); - } - let label = self.src[start..self.i].trim().to_string(); - if !self.eat("]") { - bail!("unterminated footnote index [^…] in string"); - } - if label.is_empty() { - bail!("empty footnote index `[^]` in string"); - } - labels.push(label); - } - if labels.is_empty() { - Ok(None) - } else { - Ok(Some(labels)) - } - } - - /// Parse `[^label]` or `` [^`ident`] `` after a value. - fn parse_footnote_label(&mut self) -> Result { - if !self.eat("[^") { - bail!("expected [^ footnote index"); - } - self.skip_ws(); - if self.eat("`") { - let start = self.i; - while let Some(c) = self.peek_char() { - if c == '`' { - break; - } - if c == '\n' || c == '\r' || c == ']' { - bail!("unterminated footnote var `[^`…`]`"); - } - self.bump_char(); - } - let name = self.src[start..self.i].trim().to_string(); - if !self.eat("`") { - bail!("unterminated footnote var `[^`…`]`"); - } - self.skip_ws(); - if !self.eat("]") { - bail!("unterminated footnote index [^…]"); - } - if name.is_empty() { - bail!("empty footnote var `[^`]`"); - } - return Ok(IndexKey::Var(name)); - } - let start = self.i; - while let Some(c) = self.peek_char() { - if c == ']' { - break; - } - if c == '\n' || c == '\r' { - bail!("unterminated footnote index [^…]"); - } - self.bump_char(); - } - let label = self.src[start..self.i].trim().to_string(); - if !self.eat("]") { - bail!("unterminated footnote index [^…]"); - } - if label.is_empty() { - bail!("empty footnote index `[^]`"); - } - Ok(IndexKey::Lit(label)) - } -} - -fn is_word_end(s: &str, len: usize) -> bool { - match s[len..].chars().next() { - None => true, - Some(c) => !(c.is_alphanumeric() || c == '_'), - } -} - -/// Parse `name key=val …` / positional args; returns call + bytes consumed from `s` -/// (after leading trim). Does **not** consume a trailing unmatched `)` so -/// `([callee] arg)` expression nesting works. -/// Callee may be a bare name, library path `time.parse`, or method `` `recv`.method ``. -/// Bracket-marked form: `mod… [callee] args…` (see bracket-call-modifiers.md). -/// When `prefer_var`, bare call-arg words parse as variables and bare dotted -/// callees are allowed to be method receivers. -pub fn parse_call_tail(s: &str, prefer_var: bool) -> Result<(CallExpr, usize)> { - let s = s.trim_start(); - - if let Some((call, consumed)) = try_bracket_marked_call(s, prefer_var)? { - return Ok((call, consumed)); - } - - if let Some((call, consumed)) = try_paren_call(s, prefer_var)? { - return Ok((call, consumed)); - } - - let callee_tok = { - let mut quoted = false; - let end = s.char_indices().find_map(|(i,c)| { - if c == '`' { quoted = !quoted; } - (!quoted && (c.is_whitespace() || c == ')')).then_some(i) - }).unwrap_or(s.len()); - if end == 0 { bail!("missing callee"); } - s[..end].to_string() - }; - - let (receiver, callee, path) = split_callee(&callee_tok); - - let after_callee_offset = { - let idx = s.find(&callee_tok).unwrap(); - idx + callee_tok.len() - }; - let after = &s[after_callee_offset..]; - let args_src = after.trim_start(); - let ws = after.len() - args_src.len(); - let (args, args_consumed) = parse_call_args(args_src, prefer_var, false)?; - - Ok(( - CallExpr { - callee, - path, - receiver, - args, - pre_modifiers: Vec::new(), - bracket_marked: false, - }, - after_callee_offset + ws + args_consumed, - )) -} - -/// Split a callee token into `(receiver, callee, lib path)`. -fn split_callee(callee_tok: &str) -> (Option, String, Option>) { - if let Some((r, m)) = split_method_callee(callee_tok) { - (Some(r), m, None) - } else if let Some(segments) = split_lib_path_callee(callee_tok) { - let last = segments.last().cloned().unwrap_or_default(); - (None, last, Some(segments)) - } else { - (None, callee_tok.to_string(), None) - } -} - -/// `callee(args)` — callee is **everything before the first `(`** (spaces allowed). -/// -/// Returns `None` when the shape is not a paren call (e.g. `print text=…`, -/// `text=(a)`), so callers can fall back to the classic token form. `` M1. -fn try_paren_call(s: &str, prefer_var: bool) -> Result> { - let Some(open) = s.find('(') else { - return Ok(None); - }; - if open == 0 { - return Ok(None); - } - let callee_tok = s[..open].trim(); - if callee_tok.is_empty() { - return Ok(None); - } - // A named argument (`text=a(b)`) is not a paren call, and neither is a - // bracket-marked argument (`trim [stdout](…)`): the callee side must not - // contain `=`, quotes or brackets. Backticks stay legal so that the - // backticked-receiver method form `` `obj`.方法(…) `` still reaches here. - if callee_tok - .chars() - .any(|c| matches!(c, '=' | '[' | ']' | '(' | ')' | '"' | '\'')) - { - return Ok(None); - } - let first = callee_tok.chars().next().unwrap_or(' '); - if matches!(first, '[' | ']' | '"' | '\'') { - return Ok(None); - } - let inside = &s[open + 1..]; - let (args, used) = parse_call_args(inside, prefer_var, true)?; - let rest = &inside[used..]; - let rest_t = rest.trim_start(); - if !rest_t.starts_with(')') { - return Ok(None); - } - let consumed = open + 1 + used + (rest.len() - rest_t.len()) + 1; - let (receiver, callee, path) = split_callee(callee_tok); - Ok(Some(( - CallExpr { - callee, - path, - receiver, - args, - pre_modifiers: Vec::new(), - bracket_marked: false, - }, - consumed, - ))) -} - -/// `mod… [callee] args` — `]` must not be immediately followed by `(` (that is link-index). -fn try_bracket_marked_call(s: &str, prefer_var: bool) -> Result> { - let bytes = s.as_bytes(); - let mut i = 0usize; - while i < bytes.len() { - if bytes[i] == b'[' { - if i + 1 < bytes.len() && bytes[i + 1] == b'^' { - i += 1; - continue; - } - // Only treat as callee marker at start or after whitespace. - if i > 0 - && !s[..i] - .chars() - .last() - .map(|c| c.is_whitespace()) - .unwrap_or(false) - { - i += 1; - continue; - } - let close = match s[i + 1..].find(']') { - Some(rel) => i + 1 + rel, - None => { - i += 1; - continue; - } - }; - let after = &s[close + 1..]; - if after.starts_with('(') { - // `[key](coll)` link index — not a callee marker. - i = close + 1; - continue; - } - let pre = s[..i].trim(); - // Classic calls may embed `[…]` inside named/paren args - // (`print text=(礼貌 [问候] x)`). Only treat as bracket-marked - // when the prefix is pure modifiers (no `=` / `(` / quotes / `:`). - if pre.contains('=') - || pre.contains('(') - || pre.contains('"') - || pre.contains('\'') - || pre.contains(':') - { - return Ok(None); - } - let inner = s[i + 1..close].trim(); - if inner.is_empty() { - bail!("empty bracket callee `[]`"); - } - if !is_bracket_callee_inner(inner) { - i = close + 1; - continue; - } - let pre_modifiers = match split_modifiers(pre) { - Ok(ms) if ms.iter().all(|m| is_modifier_token(m)) => ms, - _ => return Ok(None), - }; - let callee_tok = if inner.starts_with('`') && inner.ends_with('`') && inner.len() >= 2 { - inner.to_string() - } else { - inner.to_string() - }; - let (receiver, callee, path) = if let Some((r, m)) = split_method_callee(&callee_tok) { - (Some(r), m, None) - } else if let Some(segments) = split_lib_path_callee(&callee_tok) { - let last = segments.last().cloned().unwrap_or_default(); - (None, last, Some(segments)) - } else { - let name = if callee_tok.starts_with('`') - && callee_tok.ends_with('`') - && callee_tok.len() >= 2 - { - callee_tok[1..callee_tok.len() - 1].to_string() - } else { - callee_tok - }; - (None, name, None) - }; - let after_full = &s[close + 1..]; - let args_src = after_full.trim_start(); - let ws = after_full.len() - args_src.len(); - let (args, args_consumed) = parse_call_args(args_src, prefer_var, false)?; - let consumed = close + 1 + ws + args_consumed; - return Ok(Some(( - CallExpr { - callee, - path, - receiver, - args, - pre_modifiers, - bracket_marked: true, - }, - consumed, - ))); - } - i += 1; - } - Ok(None) -} - -fn split_modifiers(pre: &str) -> Result> { - let mut out = Vec::new(); - let mut rest = pre.trim(); - while !rest.is_empty() { - let (tok, next) = split_first_token(rest, false); - if tok.is_empty() { - break; - } - let name = if tok.starts_with('`') && tok.ends_with('`') && tok.len() >= 2 { - tok[1..tok.len() - 1].to_string() - } else { - if tok.contains('=') { - bail!("pre-bracket modifier cannot be a named arg (`{tok}`); put named args after `]`"); - } - tok.to_string() - }; - if name.is_empty() { - bail!("empty pre-bracket modifier"); - } - out.push(name); - rest = next.trim_start(); - } - Ok(out) -} - -/// Parse call args; returns `(args, bytes_consumed)` from the start of `args_str`. -/// Stops before an unmatched `)` so parenthesized expression nesting works. -fn parse_call_args( - args_str: &str, - prefer_var: bool, - paren_mode: bool, -) -> Result<(Vec, usize)> { - use crate::ast::Arg; - let mut args = Vec::new(); - let mut seen_named = false; - let mut rest = args_str; - - while !rest.is_empty() { - rest = rest.trim_start(); - if rest.is_empty() || rest.starts_with(')') { - break; - } - // `` M1: optional comma separator inside `callee(...)`. - if paren_mode { - while let Some(r) = rest.strip_prefix(',') { - rest = r.trim_start(); - } - if rest.is_empty() || rest.starts_with(')') { - break; - } - } - if let Some((key, after_eq)) = try_named_arg(rest) { - seen_named = true; - let val_end = find_next_arg_boundary(after_eq, paren_mode); - let val_raw = after_eq[..val_end].trim_end(); - let value = if prefer_var { - parse_call_arg_value_mode(val_raw, prefer_var, paren_mode)? - } else { - parse_call_arg_value_mode(val_raw, prefer_var, paren_mode)? - }; - args.push(Arg::Named { name: key, value }); - rest = after_eq[val_end..].trim_start(); - } else { - if seen_named { - bail!("positional argument after named argument is not allowed"); - } - let (tok, next) = split_first_token(rest, paren_mode); - if tok.is_empty() { - break; - } - let value = if prefer_var { - parse_call_arg_value_mode(tok, prefer_var, paren_mode)? - } else { - parse_call_arg_value_mode(tok, prefer_var, paren_mode)? - }; - args.push(Arg::Positional(value)); - rest = next.trim_start(); - } - } - let consumed = args_str.len() - rest.len(); - Ok((args, consumed)) -} - -/// `` `recv`.method `` → (recv, method). -fn split_method_callee(tok: &str) -> Option<(String, String)> { - if !tok.starts_with('`') { - return None; - } - let rest = &tok[1..]; - let end = rest.find('`')?; - let recv = rest[..end].to_string(); - if recv.is_empty() { - return None; - } - let after = &rest[end + 1..]; - let method = after.strip_prefix('.')?; - if method.is_empty() || method.contains('`') || method.contains('.') { - return None; - } - Some((recv, method.to_string())) -} - -/// Bare `time.parse` / `agent.agent` → path segments (len ≥ 2). -fn split_lib_path_callee(tok: &str) -> Option> { - if tok.starts_with('`') || !tok.contains('.') { - return None; - } - let parts: Vec = tok.split('.').map(|s| s.to_string()).collect(); - if parts.len() < 2 { - return None; - } - if parts.iter().any(|p| p.is_empty() || p.contains('`')) { - return None; - } - Some(parts) -} - -/// If `s` begins with `ident=`, return (ident, rest_after_eq). -fn try_named_arg(s: &str) -> Option<(String, &str)> { - let s = s.trim_start(); - for (i, c) in s.char_indices() { - if c == '=' { - if i == 0 { - return None; - } - let key = &s[..i]; - if key.chars().any(|ch| ch.is_whitespace()) { - return None; - } - return Some((key.to_string(), &s[i + 1..])); - } - if c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | ',' | '"' | '\'' | '`') { - return None; - } - } - None -} - -/// Split one call-argument token off `s`. -/// -/// Stops at a **top-level** whitespace, `)`, and (when `stop_comma`) `,`. -/// Tracks `()` `[]` `{}` nesting plus quoted strings and backticks, so nested -/// calls (`f(g(1))`) and JSON-ish values stay one token. `` M1. -fn split_first_token(s: &str, paren_mode: bool) -> (&str, &str) { - let s = s.trim_start(); - let mut depth = 0i32; - let mut in_str = false; - let mut in_bt = false; - let mut chars = s.char_indices().peekable(); - while let Some((i, c)) = chars.next() { - if in_str { - if c == '\\' { - chars.next(); - continue; - } - if c == '"' { - in_str = false; - } - continue; - } - if in_bt { - if c == '`' { - in_bt = false; - } - continue; - } - match c { - '`' => { - in_bt = true; - continue; - } - '"' => { - in_str = true; - continue; - } - '(' | '[' | '{' => { - depth += 1; - continue; - } - ')' | ']' | '}' => { - if depth == 0 { - // Top-level closer terminates the token and is NOT consumed. - return (&s[..i], &s[i..]); - } - depth -= 1; - continue; - } - ',' if paren_mode && depth == 0 => return (&s[..i], &s[i..]), - c if depth == 0 && c.is_whitespace() => return (&s[..i], &s[i..]), - _ => {} - } - } - (s, "") -} - -/// `[key](…)` with no whitespace between `]` and `(`. -/// True when `[…]` is immediately followed by `(` — i.e. an occlusion shape. -/// `[问候] "Ada"` (bracket-marked call) has no `(`, so it keeps its meaning. `` M7 -fn occlusion_shape_ahead(s: &str) -> bool { - let mut chars = s.char_indices(); - let Some((_, '[')) = chars.next() else { - return false; - }; - let mut escaped = false; - for (i, c) in chars { - if escaped { - escaped = false; - continue; - } - match c { - '\\' => escaped = true, - ']' => { - // Strict: `(` must follow immediately. `[问候] ([…])` is a - // bracket-marked call with a parenthesised argument, not an occlusion. - return s[i + 1..].starts_with('('); - } - '\n' => return false, - _ => {} - } - } - false -} - -fn link_index_shape_ahead(s: &str) -> bool { - let s = s.trim_start(); - if !s.starts_with('[') || s.starts_with("[^") { - return false; - } - let Some(close_rel) = s[1..].find(']') else { - return false; - }; - let after = &s[1 + close_rel + 1..]; - after.starts_with('(') -} - -/// `[callee] …` (not link-index): inner must look like a function/method name, not JSON. -fn bracket_callee_shape_ahead(s: &str) -> bool { - let s = s.trim_start(); - if !s.starts_with('[') || s.starts_with("[^") { - return false; - } - let Some(close_rel) = s[1..].find(']') else { - return false; - }; - let after = &s[1 + close_rel + 1..]; - if after.starts_with('(') { - return false; - } - is_bracket_callee_inner(&s[1..1 + close_rel]) -} - -fn is_bracket_callee_inner(inner: &str) -> bool { - let t = inner.trim(); - if t.is_empty() { - return false; - } - // JSON arrays / objects / strings are never callees. - if t.contains(',') - || t.contains(':') - || t.contains('{') - || t.contains('}') - || t.contains('[') - || t.contains(']') - || t.starts_with('"') - || t.starts_with('\'') - { - return false; - } - if t.starts_with('`') { - return split_method_callee(t).is_some() - || (t.ends_with('`') && t.len() >= 2 && !t[1..t.len() - 1].contains('`')); - } - if t.chars().next().is_some_and(|c| c.is_ascii_digit()) { - return false; - } - // Bare name or `lib.path` callee. Internal spaces allowed: `[加一 号] 31` - // is the bracket-marked form of a callee whose name contains spaces (D8). - t.chars() - .all(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == ' ' || !c.is_ascii()) -} - -fn is_modifier_token(name: &str) -> bool { - !name.is_empty() - && name - .chars() - .all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()) -} - -fn find_next_arg_boundary(after_eq: &str, paren_mode: bool) -> usize { - // Look for ` =` pattern not inside backticks, quoted strings, or - // JSON-ish `[…]` / `{…}` (GAP-07: `text=["a"] other=…`). - let mut in_bt = false; - let mut in_str = false; - let mut bracket_depth: i32 = 0; - let mut brace_depth: i32 = 0; - let mut paren_depth: i32 = 0; - let mut chars = after_eq.char_indices().peekable(); - while let Some((i, c)) = chars.next() { - if in_str { - if c == '\\' { - chars.next(); - continue; - } - if c == '"' { - in_str = false; - } - continue; - } - if in_bt { - if c == '`' { - in_bt = false; - } - continue; - } - match c { - '`' => { - in_bt = true; - continue; - } - '"' => { - in_str = true; - continue; - } - '[' => { - bracket_depth += 1; - continue; - } - ']' => { - bracket_depth = bracket_depth.saturating_sub(1); - continue; - } - '{' => { - brace_depth += 1; - continue; - } - '}' => { - brace_depth = brace_depth.saturating_sub(1); - continue; - } - '(' => { - paren_depth += 1; - continue; - } - ')' => { - if paren_depth == 0 { - // `` M1: `)` ends the enclosing call's argument list. - return i; - } - paren_depth -= 1; - continue; - } - ',' if paren_mode && paren_depth == 0 && bracket_depth == 0 && brace_depth == 0 => { - return i; - } - _ => {} - } - if bracket_depth > 0 || brace_depth > 0 || paren_depth > 0 { - continue; - } - if c.is_whitespace() { - let rest = &after_eq[i..]; - let trimmed = rest.trim_start(); - let skipped = rest.len() - trimmed.len(); - if let Some(eq_at) = trimmed.find('=') { - let key = &trimmed[..eq_at]; - if !key.is_empty() - && !key.contains(char::is_whitespace) - && key - .chars() - .all(|ch| ch.is_alphanumeric() || ch == '_' || !ch.is_ascii()) - { - return i + skipped; - } - } - } - } - after_eq.len() -} - -/// Parse `> callee args` call expression/statement text (without leading `>`). -/// When `prefer_var` (inside `*…*` / `**…**`), bare call-arg words are variables -/// and a bare dotted callee may be a method receiver (resolved at eval/compile). -pub fn parse_call_after_gt(after_gt: &str, prefer_var: bool) -> Result { - let (call, _) = parse_call_tail(after_gt.trim(), prefer_var)?; - Ok(call) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn occlusion_keeps_receiver_calls_and_closing_delimiters_separate() { - for source in ["[Read probabilities](`c`.probabilities())", -"[Read probabilities](> `c`.probabilities)", -"[Set angle](`c`.rotate(angle=access(m, \"angle\")))"] { - let e = parse_expr_markup(source,true,Markup::Occlusion).unwrap(); - let Expr::Occluded { payload: Some(payload), .. } = e else { panic!("{source}") }; - let Expr::Call(call) = *payload else { panic!("{source}") }; - assert_eq!(call.receiver.as_deref(),Some("c")); - assert!(!call.callee.contains(')')); - } - assert!(parse_expr_markup("[Read file size](access(fs.stat(path=\"a\"), \"size\"))", - true,Markup::Occlusion).is_ok()); - } - - - - #[test] - fn nested_call_with_a_hyphenated_file_path_stays_executable() { - let e = parse_expr_prefer_var("toml.parse(text=fs.read_text(path=\"crates/marqdo-wasm/Cargo.toml\"))").unwrap(); - let Expr::Call(c) = e else { panic!("expected outer call") }; - let crate::ast::Arg::Named { value, .. } = &c.args[0] else { panic!("expected named argument") }; - assert!(matches!(value, Expr::Call(_)), "{value:?}"); - } - - #[test] - fn bare_var_footnote_index() { - let e = parse_expr("ev[^result]").unwrap(); - match e { - Expr::Index { base, label } => { - assert!(matches!(base.as_ref(), Expr::Var(n) if n == "ev")); - assert_eq!(label, IndexKey::Lit("result".into())); - } - other => panic!("expected Index, got {other:?}"), - } - let e = parse_expr("data[^choices][^1][^message]").unwrap(); - assert!(matches!(e, Expr::Index { .. })); - // Without `[^`, bare word stays text literal. - let e = parse_expr("ev").unwrap(); - assert!(matches!(e, Expr::Literal(Literal::Text(ref s)) if s == "ev")); - // Ticked form still works. - let e = parse_expr("`ev`[^result]").unwrap(); - assert!(matches!(e, Expr::Index { .. })); - } - - #[test] - fn prefer_var_bare_id_and_quotes() { - let e = parse_expr_prefer_var("answer").unwrap(); - assert!(matches!(e, Expr::Var(ref n) if n == "answer")); - let e = parse_expr_prefer_var("n + 1").unwrap(); - assert!(matches!( - e, - Expr::Binary { - op: BinaryOp::Add, - .. - } - )); - let e = parse_expr_prefer_var("\"ok\"").unwrap(); - assert!(matches!(e, Expr::Literal(Literal::Text(ref s)) if s == "ok")); - let e = parse_expr_prefer_var("'hi'").unwrap(); - assert!(matches!(e, Expr::Literal(Literal::Text(ref s)) if s == "hi")); - let e = parse_expr_prefer_var("`answer`").unwrap(); - assert!(matches!(e, Expr::Var(ref n) if n == "answer")); - } - - #[test] - fn call_arg_module_path_stays_text() { - let e = parse_call_arg_value("nav.`nav`").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "nav.`nav`" - )); - let e = parse_call_arg_value("articles.`articles`.title").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "articles.`articles`.title" - )); - } - - #[test] - fn quoted_string_escapes() { - let e = parse_expr("\"a\\nb\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "a\nb" - )); - let e = parse_expr("\"hi `x`!\"").unwrap(); - assert!(matches!(e, Expr::Interp(_))); - } - - #[test] - fn quoted_string_hex_unicode_escapes() { - // `\x22` → `"` (hex escape) - let e = parse_expr("\"a\\x22b\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "a\"b" - )); - // `\x1F` → control char - let e = parse_expr("\"\\x1F\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "\u{1f}" - )); - // `\u{4e2d}` → 中 - let e = parse_expr("\"\\u{4e2d}\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "中" - )); - // `\u{1F600}` → 😀 - let e = parse_expr("\"\\u{1F600}\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "😀" - )); - // `\x22` inside a string that also interpolates - let e = parse_expr("\"x=\\x22`v`\\x22\"").unwrap(); - assert!(matches!(e, Expr::Interp(_))); - // `\x` without two hex digits is kept verbatim (`\x` → `\x`) - let e = parse_expr("\"a\\xb\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "a\\xb" - )); - // `\u` without braces is kept verbatim (`\u` → `\u`) - let e = parse_expr("\"a\\ub\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "a\\ub" - )); - } - - #[test] - fn quoted_string_unknown_escape_kept_verbatim() { - // Unknown escapes like `\q` are kept as-is rather than failing. - let e = parse_expr("\"a\\qb\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "a\\qb" - )); - } - - #[test] - fn call_arg_quoted_path_keeps_slashes() { - let e = parse_call_arg_value("\".marqdo/agent-runs\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == ".marqdo/agent-runs" - )); - let e = parse_value_or_interp("\".marqdo/agent-kb\"").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == ".marqdo/agent-kb" - )); - } - - #[test] - fn call_arg_bare_path_not_division() { - let e = parse_call_arg_value("a/b/c").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "a/b/c" - )); - let e = parse_call_arg_value("1/2").unwrap(); - assert!(matches!( - e, - Expr::Binary { - op: BinaryOp::Div, - .. - } - )); - } - - #[test] - fn bare_token_no_escape() { - let e = parse_expr("a\\nb").unwrap(); - assert!(matches!( - e, - Expr::Literal(Literal::Text(ref s)) if s == "a\\nb" - )); - } - - #[test] - fn chinese_logic_and_literals() { - let e = parse_expr("`a` 且 非 `b`").unwrap(); - assert!(matches!( - e, - Expr::Binary { - op: BinaryOp::And, - .. - } - )); - assert!(matches!( - parse_expr("真").unwrap(), - Expr::Literal(Literal::Bool(true)) - )); - assert!(matches!( - parse_expr("空").unwrap(), - Expr::Literal(Literal::None) - )); - } - - #[test] - fn interp_footnote_index_after_var() { - // `前缀`x`[^key]` → Interp([Lit, Index]) - let e = parse_interp("前缀`m`[^苹果]"); - match &e { - Expr::Interp(parts) => { - assert!(matches!(&parts[0], InterpPart::Lit(t) if t == "前缀")); - assert!(matches!( - &parts[1], - InterpPart::Index { base, labels } if base == "m" && labels == &["苹果".to_string()] - )); - } - other => panic!("expected Interp, got {other:?}"), - } - // Bare `m`[^key] with no prefix → Expr::Index - let e = parse_interp("`m`[^苹果]"); - assert!(matches!( - e, - Expr::Index { - label: IndexKey::Lit(ref s), - .. - } if s == "苹果" - )); - // Chained labels fold into one Index part with multiple labels. - let e = parse_interp("`m`[^a][^b]"); - match &e { - Expr::Index { base, label } => { - assert!(matches!( - base.as_ref(), - Expr::Index { - label: IndexKey::Lit(ref l), - .. - } if l == "a" - )); - assert_eq!(label, &IndexKey::Lit("b".into())); - } - other => panic!("expected chained Index, got {other:?}"), - } - // `x`[^key] with plain Var text when no `[^` follows. - let e = parse_interp("`m` 和 `n`"); - assert!(matches!(e, Expr::Interp(_))); - } - - #[test] - fn interp_footnote_index_keeps_text_between() { - // `x` followed by whitespace then [^...] → [^...] stays literal text. - let e = parse_interp("`m` [^苹果]"); - match &e { - Expr::Interp(parts) => { - assert!(matches!(&parts[0], InterpPart::Var(n) if n == "m")); - assert!(matches!(&parts[1], InterpPart::Lit(t) if t == " [^苹果]")); - } - other => panic!("expected Interp, got {other:?}"), - } - } - - #[test] - fn float_literal_and_dynamic_footnote_key() { - let e = parse_expr("0.85").unwrap(); - assert!(matches!(e, Expr::Literal(Literal::Num(n)) if (n - 0.85).abs() < 1e-12)); - let e = parse_expr("28 * 0.85").unwrap(); - assert!(matches!( - e, - Expr::Binary { - op: BinaryOp::Mul, - .. - } - )); - let e = parse_expr_prefer_var("菜单[^`名`]").unwrap(); - match e { - Expr::Index { base, label } => { - assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单")); - assert_eq!(label, IndexKey::Var("名".into())); - } - other => panic!("expected dynamic Index, got {other:?}"), - } - let e = parse_expr("m[^拿铁]").unwrap(); - assert!(matches!( - e, - Expr::Index { - label: IndexKey::Lit(ref s), - .. - } if s == "拿铁" - )); - } - - #[test] - fn link_shaped_index() { - let e = parse_expr_markup("[拿铁](菜单)", true, Markup::Classic).unwrap(); - match e { - Expr::Index { base, label } => { - assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单")); - assert_eq!(label, IndexKey::Lit("拿铁".into())); - } - other => panic!("expected link Index, got {other:?}"), - } - let e = parse_expr_markup("[`名`](菜单)", true, Markup::Classic).unwrap(); - match e { - Expr::Index { base, label } => { - assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单")); - assert_eq!(label, IndexKey::Var("名".into())); - } - other => panic!("expected dynamic link Index, got {other:?}"), - } - let e = parse_expr_markup("[1](篮子)", true, Markup::Classic).unwrap(); - assert!(matches!( - e, - Expr::Index { - label: IndexKey::Lit(ref s), - .. - } if s == "1" - )); - let e = parse_expr_markup("[1]([苹果](货架))", true, Markup::Classic).unwrap(); - match e { - Expr::Index { base, label } => { - assert_eq!(label, IndexKey::Lit("1".into())); - assert!(matches!( - base.as_ref(), - Expr::Index { - label: IndexKey::Lit(ref k), - .. - } if k == "苹果" - )); - } - other => panic!("expected nested link Index, got {other:?}"), - } - } -} - -#[cfg(test)] -mod bracket_call_tests { - use super::*; - use crate::ast::{Arg, Expr}; - - #[test] - fn bracket_with_modifier() { - let (c, _) = parse_call_tail(r#"礼貌 [问候] "Marqdo""#, true).unwrap(); - assert_eq!(c.callee, "问候"); - assert_eq!(c.pre_modifiers, vec!["礼貌".to_string()]); - assert!(c.bracket_marked); - assert_eq!(c.args.len(), 1); - } - - #[test] - fn nested_paren_arg() { - let (c, _) = parse_call_tail(r#"[问候] ([格式化] "x")"#, true).unwrap(); - assert_eq!(c.callee, "问候"); - assert!(c.bracket_marked); - match &c.args[0] { - Arg::Positional(Expr::Call(inner)) => { - assert_eq!(inner.callee, "格式化"); - assert!(inner.bracket_marked); - } - other => panic!("expected nested call, got {:?}", other), - } - } - - #[test] - fn paren_expr_bracket_call() { - let e = parse_expr_prefer_var(r#"([文本] "hi")"#).unwrap(); - match e { - Expr::Call(c) => assert_eq!(c.callee, "文本"), - other => panic!("{:?}", other), - } - } - - #[test] - fn modifier_in_paren_expr() { - let e = parse_expr_prefer_var(r#"(礼貌 [问候] "Ada")"#).unwrap(); - match e { - Expr::Call(c) => { - assert_eq!(c.callee, "问候"); - assert_eq!(c.pre_modifiers, vec!["礼貌".to_string()]); - } - other => panic!("{:?}", other), - } - } - - #[test] - fn link_index_not_bracket_call() { - let e = parse_expr_markup("[拿铁](菜单)", true, Markup::Classic).unwrap(); - assert!(matches!(e, Expr::Index { .. })); - } - - // ---- M1: `()` 内调用语法(`)` 终止 / 逗号 / 嵌套 / 空格 callee)---- - - fn call_of(e: Expr) -> crate::ast::CallExpr { - match e { - Expr::Call(c) => c, - other => panic!("expected Call, got {other:?}"), - } - } - - #[test] - fn paren_call_single_positional() { - let (c, used) = parse_call_tail("加(1)", false).unwrap(); - assert_eq!(c.callee, "加"); - assert_eq!(used, "加(1)".len()); - assert_eq!(c.args.len(), 1); - } - - #[test] - fn paren_call_bare_number_stops_at_paren() { - // 历史缺陷:末个位置实参会吞掉 `)` - let (c, used) = parse_call_tail("加(31)", false).unwrap(); - assert_eq!( - used, - "加(31)".len(), - "consumed must cover the closing paren" - ); - assert_eq!(c.args.len(), 1); - } - - #[test] - fn paren_call_comma_and_space_separated() { - for src in ["加(1, 2)", "加(1 2)", "加(1,2)", "加( 1 , 2 )"] { - let (c, _) = parse_call_tail(src, false).unwrap(); - assert_eq!(c.args.len(), 2, "src={src}"); - } - } - - #[test] - fn paren_call_named_args() { - let (c, _) = parse_call_tail("计税(档位=2, 金额=100)", false).unwrap(); - assert_eq!(c.callee, "计税"); - assert_eq!(c.args.len(), 2); - match &c.args[0] { - crate::ast::Arg::Named { name, .. } => assert_eq!(name, "档位"), - other => panic!("{other:?}"), - } - } - - #[test] - fn paren_call_callee_may_contain_spaces() { - let (c, used) = parse_call_tail("加一 号(31)", false).unwrap(); - assert_eq!(c.callee, "加一 号"); - assert_eq!(used, "加一 号(31)".len()); - assert_eq!(c.args.len(), 1); - } - - #[test] - fn paren_call_zero_args() { - let (c, _) = parse_call_tail("刷新()", false).unwrap(); - assert_eq!(c.callee, "刷新"); - assert!(c.args.is_empty()); - } - - #[test] - fn paren_call_lib_path_and_method() { - let c = call_of(parse_expr("txt.str_trim(s)").unwrap()); - assert_eq!(c.callee, "str_trim"); - assert_eq!( - c.path.as_deref(), - Some(&["txt".to_string(), "str_trim".to_string()][..]) - ); - - // 点号 callee 在 parse 期保存为 lib path;若 `obj` 是局部变量, - // 运行期 eval_call 会把它当 method receiver(与 `> obj.方法` 一致)。 - let c = call_of(parse_expr("obj.方法(1)").unwrap()); - assert_eq!(c.callee, "方法"); - assert_eq!( - c.path.as_deref(), - Some(&["obj".to_string(), "方法".to_string()][..]) - ); - assert!(c.receiver.is_none()); - } - - #[test] - fn dotted_path_is_implicit_zero_arg_call() { - let c = call_of(parse_expr_prefer_var("facts.Person.birth_year").unwrap()); - assert_eq!(c.callee, "birth_year"); - assert_eq!( - c.path.as_deref(), - Some( - &[ - "facts".to_string(), - "Person".to_string(), - "birth_year".to_string(), - ][..] - ) - ); - assert!(c.args.is_empty()); - } - - #[test] - fn classic_dotted_text_is_not_an_implicit_path_call() { - // Branch conditions and other classic contexts use bare dotted text - // for filenames such as `refunds.md`; new paths live on the - // executable value surface only. - assert!(matches!( - parse_expr("refunds.md").unwrap(), - Expr::Literal(Literal::Text(value)) if value == "refunds.md" - )); - } - - #[test] - fn paren_call_nested_in_expression() { - let c = call_of(parse_expr("加(加(1 2), 3)").unwrap()); - assert_eq!(c.args.len(), 2); - match &c.args[0] { - crate::ast::Arg::Positional(Expr::Call(inner)) => { - assert_eq!(inner.callee, "加"); - assert_eq!(inner.args.len(), 2); - } - other => panic!("expected nested call, got {other:?}"), - } - } - - #[test] - fn paren_call_quoted_args_keep_commas() { - // 逗号只在括号形里当分隔符;字符串内的逗号不受影响 - let (c, _) = parse_call_tail(r#"拼接("a,b", "c")"#, false).unwrap(); - assert_eq!(c.args.len(), 2); - } - - #[test] - fn whitespace_call_unaffected_by_commas() { - // 旧式空格调用:`text=a,b` 的逗号仍是文本一部分 - let (c, _) = parse_call_tail("print text=a,b", false).unwrap(); - match &c.args[0] { - crate::ast::Arg::Named { value, .. } => match value { - Expr::Literal(Literal::Text(s)) => assert_eq!(s, "a,b"), - other => panic!("expected text a,b, got {other:?}"), - }, - other => panic!("{other:?}"), - } - } - - #[test] - fn bracketed_call_still_works() { - let (c, _) = parse_call_tail("[加一 号] 31", false).unwrap(); - assert_eq!(c.callee, "加一 号"); - } - - // ---- M2: 遮蔽语法 `[描述](实现)` ---- - - fn occl(e: Expr) -> (String, Option) { - match e { - Expr::Occluded { label, payload } => (label, payload.map(|b| *b)), - other => panic!("expected Occluded, got {other:?}"), - } - } - - #[test] - fn occlusion_basic_value_passthrough() { - let e = parse_expr_markup("[加一之后的值](加(1))", false, Markup::Occlusion).unwrap(); - let (label, payload) = occl(e); - assert_eq!(label, "加一之后的值"); - assert!(matches!(payload, Some(Expr::Call(_)))); - } - - #[test] - fn occlusion_empty_payload_is_none() { - let e = parse_expr_markup("[某某功能开发中]()", false, Markup::Occlusion).unwrap(); - let (label, payload) = occl(e); - assert_eq!(label, "某某功能开发中"); - assert!(payload.is_none()); - } - - #[test] - fn occlusion_label_allows_spaces_and_punctuation() { - let e = parse_expr_markup( - "[按 `税率` 与档位计算,注意四舍五入](1 + 2)", - true, - Markup::Occlusion, - ) - .unwrap(); - let (label, payload) = occl(e); - assert!(label.contains("税率")); - assert!(payload.is_some()); - } - - #[test] - fn occlusion_label_escaped_bracket() { - let e = parse_expr_markup("[数组 a\\]b 的长度](1)", false, Markup::Occlusion).unwrap(); - let (label, _) = occl(e); - assert_eq!(label, "数组 a]b 的长度"); - } - - #[test] - fn occlusion_nested() { - let e = parse_expr_markup("[外层]([内层](1))", false, Markup::Occlusion).unwrap(); - let (label, payload) = occl(e); - assert_eq!(label, "外层"); - let (inner_label, inner_payload) = occl(payload.unwrap()); - assert_eq!(inner_label, "内层"); - assert!(matches!( - inner_payload, - Some(Expr::Literal(Literal::Int(1))) - )); - } - - #[test] - fn occlusion_classic_mode_keeps_index() { - let e = parse_expr_markup("[键](表)", false, Markup::Classic).unwrap(); - assert!( - matches!(e, Expr::Index { .. }), - "classic must stay an index" - ); - } - - #[test] - fn occlusion_requires_immediate_paren() { - // No `(` after `]` → falls back to the bracket-marked call form. - let e = parse_expr_markup("[只有描述]", false, Markup::Occlusion).unwrap(); - assert!(matches!(e, Expr::Call(_)), "got {e:?}"); - // A space before `(` also means "not an occlusion". - let e = parse_expr_markup("[问候] (1)", false, Markup::Occlusion).unwrap(); - assert!(matches!(e, Expr::Call(_)), "got {e:?}"); - } - - #[test] - fn modifier_conflict_expands() { - let (c, _) = parse_call_tail("礼貌 [问候] 礼貌=False", false).unwrap(); - let err = c.with_modifiers_expanded().unwrap_err(); - assert!(err.contains("conflicts")); - } -} diff --git a/src/parse/mod.rs b/src/parse/mod.rs deleted file mode 100755 index b985d78..0000000 --- a/src/parse/mod.rs +++ /dev/null @@ -1,3039 +0,0 @@ -//! Line-oriented recursive descent → AST (no Bison). - -pub mod expr; -mod prose; - -pub use expr::{ - parse_call_after_gt, parse_call_arg_value, parse_expr, parse_expr_prefer_var, - parse_value_or_interp, -}; -pub use prose::{ - classify_narrative_target, scan_md_links_in_line, scan_narrative_links, scan_prose_line, - NarrativeLink, NarrativeLinkKind, ProseBit, -}; - -use anyhow::{bail, Result}; -use std::collections::HashSet; - -use crate::ast::{ - BranchArm, Expr, Function, Import, IndexKey, Literal, Module, Param, Stmt, Use, -}; -use crate::diagnostics::{bail_at, Diagnostic, Span}; -use crate::lex::{ClassifiedLine, LineKind, classify_source, has_unterminated_string}; -use crate::parse::expr::parse_call_after_gt as call_after_gt; -use crate::parse::expr::parse_call_tail; -use crate::parse::expr::parse_expr as parse_expr_str; - -/// Parse full source (with optional frontmatter) into a module AST. -pub fn parse_source(source: &str) -> Result { - let lines = classify_source(source); - let mut module = parse_classified(&lines)?; - module.source = crate::diagnostics::SourceIdentity::from_source(None, source); - Ok(module) -} - -pub fn parse_classified(lines: &[ClassifiedLine]) -> Result { - let mut cur = Cursor::new(lines); - let (imports, uses, metadata_raw) = cur.parse_frontmatter()?; - let mut functions = Vec::new(); - while cur.skip_noise() { - let Some(line) = cur.peek() else { break }; - let trimmed = line.text.trim(); - // Module-level Markdown thematic breaks (`---` / `***`) are narrative skip. - if is_frame(trimmed) { - cur.bump(); - continue; - } - if is_heading(trimmed) { - functions.push(cur.parse_function(1, &HashSet::new())?); - } else if line.kind == LineKind::Comment { - // Intro paragraphs may still contain return-shaped italics (`返回*值*`) - // or leftover soft emphasis; executable prose belongs inside functions. - cur.bump(); - continue; - } else { - bail!( - "{}:1: expected heading (`#` object or `##` function), got: {trimmed}", - line.line_no - ); - } - } - for u in &uses { - if imports.iter().any(|i| i.bind == u.bind) { - bail!("import bind `{}` conflicts with file import library name", u.bind); - } - if functions.iter().any(|f| f.name == u.bind) { - bail!("import bind `{}` conflicts with top-level name", u.bind); - } - } - let module=Module { - source: Default::default(), - imports, - uses, - functions, - import_modules: std::collections::HashMap::new(), - metadata_raw, - metadata: Vec::new(), - }; - crate::ast::validate_parameters(&module)?; - Ok(module) -} - -/// Parse one GFM table with the source language's cell and shape rules. -/// Document readers reject nonliteral expressions before using the value. -pub(crate) fn parse_gfm_table(source: &str) -> Result { - let lines = classify_source(source); - let mut cursor = Cursor::new(&lines); - let table = cursor.consume_table()?; - if cursor.skip_noise() { - bail!("unexpected content after the selected GFM table"); - } - Ok(table) -} - -struct Cursor<'a> { - lines: &'a [ClassifiedLine], - i: usize, -} - -impl<'a> Cursor<'a> { - fn new(lines: &'a [ClassifiedLine]) -> Self { - Self { lines, i: 0 } - } - - fn peek(&self) -> Option<&'a ClassifiedLine> { - self.lines.get(self.i) - } - - fn bump(&mut self) -> Option<&'a ClassifiedLine> { - let l = self.lines.get(self.i)?; - self.i += 1; - Some(l) - } - - /// Skip blank + writeback; stop on Code **or** Comment that has v0.3 inline bits. - fn skip_noise(&mut self) -> bool { - while let Some(l) = self.peek() { - match l.kind { - LineKind::Blank | LineKind::Writeback => { - self.i += 1; - } - LineKind::Comment => { - let bits = scan_prose_line(l.text.trim_end_matches(['\r', '\n'])); - if bits.iter().any(|b| { - matches!( - b, - ProseBit::BoldCode { .. } - | ProseBit::ItalicReturn { .. } - | ProseBit::Decl { .. } - ) - }) { - return true; - } - self.i += 1; - } - LineKind::Code => return true, - } - } - false - } - - /// True if peek is a Comment line with executable/decl prose bits. - fn peek_is_prose(&self) -> bool { - let Some(l) = self.peek() else { - return false; - }; - if l.kind != LineKind::Comment { - return false; - } - let bits = scan_prose_line(l.text.trim_end_matches(['\r', '\n'])); - bits.iter().any(|b| { - matches!( - b, - ProseBit::BoldCode { .. } - | ProseBit::ItalicReturn { .. } - | ProseBit::Decl { .. } - ) - }) - } - - fn parse_frontmatter( - &mut self, - ) -> Result<( - Vec, - Vec, - Vec<(String, crate::binding::MetaValue)>, - )> { - let mut imports = Vec::new(); - let mut uses = Vec::new(); - let mut metadata_raw = Vec::new(); - let mut import_keyword: Option<&'static str> = None; - if !self.skip_noise() { - return Ok((imports, uses, metadata_raw)); - } - let Some(first) = self.peek() else { - return Ok((imports, uses, metadata_raw)); - }; - if first.text.trim() != "---" { - return Ok((imports, uses, metadata_raw)); - } - self.bump(); - while let Some(line) = self.peek() { - let t = line.text.trim(); - if t == "---" { - self.bump(); - break; - } - let span = Span::new(line.line_no, 1); - if let Some(msg) = legacy_frontmatter_import_hint(t) { - return Err(bail_at(None, span, msg)); - } - // Artifact metadata key: value (flat Phase 1); `import:` / `导入:` are nested maps - if let Some((key, rest)) = split_frontmatter_key(t) { - if key == "import" || key == "导入" { - let kw = if key == "import" { "import" } else { "导入" }; - if let Some(prev) = import_keyword { - if prev != kw { - return Err(bail_at( - None, - span, - format!( - "cannot mix `{prev}:` and `{kw}:` in one frontmatter (one language per file)" - ), - )); - } - return Err(bail_at( - None, - span, - format!("duplicate `{kw}:` block in frontmatter"), - )); - } - if !rest.is_empty() { - return Err(bail_at( - None, - span, - format!( - "`{kw}:` must be a nested YAML map (not `{kw}: …` on one line); \ - use indented `bind: target` under `{kw}:`" - ), - )); - } - import_keyword = Some(kw); - self.bump(); - self.collect_import_map(span, &mut imports, &mut uses)?; - continue; - } - self.bump(); - let value_raw = if rest.is_empty() - || rest == "|" - || rest == "|-" - || rest == "|+" - || rest == ">" - || rest == ">-" - || rest == ">+" - { - collect_block_scalar(self, rest)? - } else { - rest.to_string() - }; - let mv = crate::binding::parse_meta_value(&value_raw) - .map_err(|e| bail_at(None, span, e.to_string()))?; - if metadata_raw.iter().any(|(k, _)| k == key) { - return Err(bail_at( - None, - span, - format!("duplicate metadata key `{key}`"), - )); - } - metadata_raw.push((key.to_string(), mv)); - continue; - } - // Unknown / non-key line: skip (compat with freeform frontmatter notes) - self.bump(); - } - Ok((imports, uses, metadata_raw)) - } - - /// Consume indented `bind: target` lines under `import:` / `导入:`. - fn collect_import_map( - &mut self, - header_span: Span, - imports: &mut Vec, - uses: &mut Vec, - ) -> Result<()> { - let _ = header_span; - while let Some(line) = self.peek() { - let raw = line.text.trim_end_matches(['\r', '\n']); - let bt = raw.trim(); - if bt == "---" { - break; - } - if bt.is_empty() { - self.bump(); - continue; - } - // Next top-level key ends the import map - if !raw.starts_with(' ') && !raw.starts_with('\t') { - break; - } - let span = Span::new(line.line_no, 1); - self.bump(); - let content = strip_yaml_indent(raw); - let Some((bind_raw, target_raw)) = content.split_once(':') else { - return Err(bail_at( - None, - span, - format!("expected `bind: target` under import map, got `{content}`"), - )); - }; - let bind = bind_raw.trim(); - let target = target_raw.trim(); - let entry = parse_import_binding(bind, target) - .map_err(|e| bail_at(None, span, e.to_string()))?; - push_import_line(imports, uses, entry, span)?; - } - Ok(()) - } - - fn parse_function(&mut self, min_level: u8, inherited: &HashSet) -> Result { - let line = self.bump().unwrap(); - let (level, raw_name) = parse_heading(line.text.trim()) - .ok_or_else(|| anyhow::anyhow!("{}:1: expected heading", line.line_no))?; - if level < min_level { - bail!("{}:1: heading level {level} < expected {min_level}", line.line_no); - } - let span = Span { - line: line.line_no, - col: 1, - }; - let (name, base) = parse_object_decl(level, raw_name, span)?; - - let mut fun = Function { - name, - level, - span, - params: Vec::new(), - body: Vec::new(), - children: Vec::new(), - base, - dead_binds: Vec::new(), - contract: None, - var_contracts: std::collections::HashMap::new(), - claims: Vec::new(), - assumptions: Vec::new(), - }; - // Prose decls pending promotion (name → optional default text). - let mut prose_decls: Vec<(String, Option, u32)> = Vec::new(); - - // Parameter zone: explicit `+` lines (legacy / optional). - while self.skip_noise() { - let Some(l) = self.peek() else { break }; - let trimmed = l.text.trim(); - if is_heading(trimmed) { - let (nl, _) = parse_heading(trimmed).unwrap(); - if nl > level { - let mut visible = inherited.clone(); - let mut unused_reads = HashSet::new(); - let mut unused_declarations = Vec::new(); - collect_names_needing_input(&fun.body, &mut visible, &mut unused_reads, &HashSet::new(), &mut unused_declarations); - visible.extend(prose_decls.iter().map(|(name, _, _)| name.clone())); - visible.extend(fun.params.iter().map(|param| param.name.clone())); - fun.children.push(self.parse_function(level + 1, &visible)?); - continue; - } - break; - } - if self.peek_is_prose() { - break; - } - if let Some(param) = parse_param_line(trimmed, Span::new(l.line_no,1)) { - if fun.body.is_empty() { - fun.params.push(param); - self.bump(); - continue; - } - } - break; - } - - // Body until next heading at level <= ours, or explicit end. - while self.skip_noise() { - let Some(l) = self.peek() else { break }; - let trimmed = l.text.trim(); - - // Empty return: whole-line `**`, `****`, `** **` - if is_empty_return_marker(trimmed) { - let span = Span { - line: l.line_no, - col: 1, - }; - self.bump(); - fun.body.push(Stmt::Return { - value: Expr::Literal(Literal::None), - span, - }); - // Objects (`#`) may still declare `##` methods after the constructor return. - if level >= 2 { - break; - } - continue; - } - - // `---` / `***` = Markdown thematic break (narrative skip), not function end. - // Side-effect-only helpers end with `*None*` / whole-line `**` / `****`, or at - // the next heading / EOF. - if is_frame(trimmed) { - self.bump(); - continue; - } - - if is_heading(trimmed) { - let (nl, _) = parse_heading(trimmed).unwrap(); - if nl > level { - let mut visible = inherited.clone(); - let mut unused_reads = HashSet::new(); - let mut unused_declarations = Vec::new(); - collect_names_needing_input(&fun.body, &mut visible, &mut unused_reads, &HashSet::new(), &mut unused_declarations); - visible.extend(prose_decls.iter().map(|(name, _, _)| name.clone())); - visible.extend(fun.params.iter().map(|param| param.name.clone())); - fun.children.push(self.parse_function(level + 1, &visible)?); - continue; - } - break; - } - - if self.peek_is_prose() { - let line = self.bump().unwrap(); - let span = Span { - line: line.line_no, - col: 1, - }; - let bits = scan_prose_line(line.text.trim_end_matches(['\r', '\n'])); - let mut end_body = false; - for bit in bits { - match bit { - ProseBit::Decl { name, default, .. } => { - if !prose_decls.iter().any(|(n, _, _)| n == &name) { - prose_decls.push((name, default, span.line)); - } - } - ProseBit::BoldCode { inner, .. } => { - fun.body - .push(self.stmt_from_bold_inner(&inner, span.clone())?); - } - ProseBit::ItalicReturn { inner, .. } => { - fun.body.push(stmt_from_italic_return(&inner, span.clone())?); - // `##`+ : return ends the function so outer/sibling lines attach. - // `#` objects: keep scanning for method headings. - end_body = level >= 2; - break; - } - } - } - if end_body { - break; - } - continue; - } - - if self.peek_is_formula_fence() { - if let Some(stmt) = self.try_parse_meta_formula_assign()? { - fun.body.push(stmt); - continue; - } - } - - if is_ordered_branch(trimmed) { - fun.body.push(self.parse_branch()?); - continue; - } - if trimmed.starts_with('-') { - fun.body.push(self.parse_loop_or_err()?); - continue; - } - // Unbound GFM table = collection value (not assigned); evaluate and discard. - if trimmed.starts_with('|') { - let span = Span { - line: l.line_no, - col: 1, - }; - let value = self.consume_table()?; - fun.body.push(Stmt::Expr { value, span }); - continue; - } - - let stmt = self.parse_simple_stmt()?; - let end_body = matches!(stmt, Stmt::Return { .. }) && level >= 2; - fun.body.push(stmt); - if end_body { - break; - } - } - - // 契约提取(T2.1)必须在升参推断**之前**:契约表的单元不污染推断。 - extract_function_contract(&mut fun, self.lines)?; - merge_inferred_params(&mut fun, &prose_decls, inherited)?; - Ok(fun) - } - - fn parse_simple_stmt(&mut self) -> Result { - let line = self.bump().unwrap(); - let span = Span { - line: line.line_no, - col: 1, - }; - let trimmed = line.text.trim(); - - if is_frame(trimmed) { - // Should be skipped by callers; keep defensive message if reached. - bail!("{span}: unexpected frame line as statement (use empty return `*None*` / `**` / `****` to end a side-effect body)"); - } - - if trimmed.starts_with("$$") { - // Standalone meta formulas are handled before parse_simple_stmt. - bail!( - "{span}: formula fence must follow an empty assignment (`name` =) \ - or include `% marqdo: var=name` inside the block" - ); - } - - // v0.3: whole-line empty return `**` / `****` - if is_empty_return_marker(trimmed) { - return Ok(Stmt::Return { - value: Expr::Literal(Literal::None), - span, - }); - } - - // v0.3: **…** = code segment (assign / call / expr) - if trimmed.starts_with("**") && trimmed.ends_with("**") && trimmed.len() >= 4 { - let inner = &trimmed[2..trimmed.len() - 2]; - return self.stmt_from_bold_inner(inner, span); - } - - // D9: bold code whose string literal is never closed. The line reaches - // this point (classifier keeps it Code) but has no closing `**`, so the - // generic "unrecognized statement" would hide the real cause. - if trimmed.starts_with("**") && has_unterminated_string(trimmed) { - bail!( - "{span}: unterminated string: this line starts bold code but \ - contains an odd number of `\"` -- close the string and the \ - trailing `**` (line: {trimmed})" - ); - } - - // v0.3: *…* = return. A lone `*` (markdown emphasis leftover) must NOT - // enter this branch: it both starts and ends with `*`, and the slice - // below would panic (`[1..0]`). Require a real opener+closer pair; a - // bare `*` falls through to the ordinary statement error / narration - // handling instead of crashing the whole process. - if trimmed.starts_with('*') && trimmed.ends_with('*') && trimmed.len() >= 2 && !trimmed.starts_with("**") { - let inner = &trimmed[1..trimmed.len() - 1]; - return stmt_from_italic_return(inner, span); - } - - // Call > - if trimmed.starts_with('>') { - let call = call_after_gt(trimmed[1..].trim(), false)?; - return Ok(Stmt::Call { call, span }); - } - - // Unbound GFM table (header already consumed by bump above). - if trimmed.starts_with('|') { - self.i -= 1; - let value = self.consume_table()?; - return Ok(Stmt::Expr { value, span }); - } - - // Bare assign `` `x` = … `` - if trimmed.starts_with('`') { - if let Some(stmt) = self.parse_backtick_assign(trimmed, span.clone())? { - return Ok(stmt); - } - } - - // Mid-line prose on a Code-classified line: scan inlines - let bits = scan_prose_line(line.text.trim_end_matches(['\r', '\n'])); - if bits.iter().any(|b| { - matches!( - b, - ProseBit::BoldCode { .. } | ProseBit::ItalicReturn { .. } - ) - }) { - // Expand to multiple stmts — caller only expects one; push extras via... - // For whole-line Code that's actually "先写**…**再写**…**", classify is Comment - // and handled in prose path. If we get here, emit first executable bit only - // and require callers to use prose path for multi — but multi-bold is Comment. - let mut stmts = Vec::new(); - for bit in bits { - match bit { - ProseBit::BoldCode { inner, .. } => { - stmts.push(self.stmt_from_bold_inner(&inner, span.clone())?); - } - ProseBit::ItalicReturn { inner, .. } => { - stmts.push(stmt_from_italic_return(&inner, span.clone())?); - } - ProseBit::Decl { .. } => {} - } - } - if stmts.len() == 1 { - return Ok(stmts.pop().unwrap()); - } - if stmts.len() > 1 { - // Represent as a synthetic block: execute by chaining — use first and - // stash is awkward. Prefer: return error asking for prose classification. - // Simpler: fold into a Branch with one arm? No. - // Use Stmt::Call sequence — add by making parse_function handle this. - bail!("{span}: multiple inline code segments on one code line; use narrative line"); - } - } - - Err(Diagnostic::new(None, span, format!("unrecognized statement: {trimmed}")).into()) - } - - /// Parse bold-code inner into Assign / Call / Expr (design §6.2). - fn stmt_from_bold_inner(&mut self, inner: &str, span: Span) -> Result { - let inner = inner.trim(); - if inner.is_empty() { - return Ok(Stmt::Return { - value: Expr::Literal(Literal::None), - span, - }); - } - if let Some((name, rhs)) = split_assign_inner(inner) { - if crate::aliases::is_reserved_keyword(&name) { - bail!("{span}: `{name}` is a reserved keyword"); - } - let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, true)?; - return Ok(Stmt::Assign { - name, - value, - span, - end_line, - }); - } - if let Some(rest) = inner.strip_prefix('>') { - // Explicit `>` keeps standalone call rules (bare words = text). - let call = parse_call_after_gt(rest.trim(), false) - .map_err(|e| anyhow::anyhow!("{span}: bold code: {e}"))?; - return Ok(Stmt::Call { call, span }); - } - // Expression first (`n + 1` / `[k](c)`); bare call second (`加一 37`). - if let Ok(e) = parse_expr_prefer_var(inner) { - match e { - Expr::Call(call) => return Ok(Stmt::Call { call, span }), - Expr::Var(_) | Expr::Literal(_) => {} - value => return Ok(Stmt::Expr { value, span }), - } - } - let multi = inner.split_whitespace().count() >= 2 || inner.contains('='); - if multi { - let call = parse_call_tail(inner, true) - .map(|(c, _)| c) - .map_err(|e| anyhow::anyhow!("{span}: bold code: {e}"))?; - return Ok(Stmt::Call { call, span }); - } - bail!("{span}: bold code must be assignment, call, or expression (got `{inner}`)"); - } - - fn parse_backtick_assign(&mut self, trimmed: &str, span: Span) -> Result> { - // `name` = [rhs] - let Some(rest) = trimmed.strip_prefix('`') else { - return Ok(None); - }; - let Some(end) = rest.find('`') else { - return Ok(None); - }; - let name = rest[..end].to_string(); - if crate::aliases::is_reserved_keyword(&name) { - bail!("{span}: `{name}` is a reserved keyword"); - } - let after = rest[end + 1..].trim_start(); - if !after.starts_with('=') { - return Ok(None); - } - let rhs = after[1..].trim().to_string(); - let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, false)?; - Ok(Some(Stmt::Assign { - name, - value, - span, - end_line, - })) - } - - /// RHS on the same line, or empty RHS → following `$$` / ```lang fence or table. - /// Returns `(expr, inclusive end_line)`. - /// `prefer_var`: italic RHS uses variable-preferring expression syntax. - fn resolve_assign_rhs( - &mut self, - assign_name: &str, - rhs: &str, - span: Span, - prefer_var: bool, - ) -> Result<(Expr, u32)> { - let rhs = rhs.trim(); - if rhs.is_empty() { - self.skip_blanks(); - if self.peek_is_formula_fence() { - let (expr, end_line, meta_var) = self.consume_formula_fence(span)?; - check_formula_meta_var(assign_name, meta_var.as_deref(), span)?; - return Ok((expr, end_line)); - } - if self.peek_is_code_fence() { - return self.consume_code_fence(span); - } - let start_i = self.i; - let table = self.consume_table()?; - let end_line = if self.i > start_i { - self.lines[self.i - 1].line_no - } else { - span.line - }; - return Ok((table, end_line)); - } - if let Some(expr) = try_parse_inline_formula(rhs)? { - return Ok((expr, span.line)); - } - if rhs.starts_with('>') { - return Ok(( - Expr::Call(call_after_gt(rhs[1..].trim(), prefer_var)?), - span.line, - )); - } - // v0.3 prefer_var RHS: expression first (`p + qn`), else bare call (`加一 37`). - if prefer_var { - if let Ok(e) = parse_expr_prefer_var(rhs) { - return Ok((e, span.line)); - } - let multi = rhs.split_whitespace().count() >= 2 || rhs.contains('='); - if multi { - if let Ok((call, consumed)) = parse_call_tail(rhs, true) { - let rest = rhs.get(consumed..).unwrap_or("").trim(); - if rest.is_empty() { - return Ok((Expr::Call(call), span.line)); - } - } - } - } - let value = if prefer_var { - parse_expr_prefer_var(rhs)? - } else { - parse_value_or_interp(rhs)? - }; - Ok((value, span.line)) - } - - fn skip_blanks(&mut self) { - while let Some(l) = self.peek() { - if l.kind == LineKind::Blank { - self.i += 1; - } else { - break; - } - } - } - - fn peek_is_formula_fence(&self) -> bool { - self.peek() - .map(|l| l.text.trim().starts_with("$$")) - .unwrap_or(false) - } - - fn peek_is_code_fence(&self) -> bool { - self.peek() - .map(|l| crate::foreign::is_fence_opener(l.text.trim())) - .unwrap_or(false) - } - - fn consume_code_fence(&mut self, span: Span) -> Result<(Expr, u32)> { - let open = self - .bump() - .ok_or_else(|| anyhow::anyhow!("{span}: expected ```lang code fence"))?; - let open_line = open.line_no; - let trimmed = open.text.trim(); - let lang = crate::foreign::fence_lang(trimmed).ok_or_else(|| { - anyhow::anyhow!("{open_line}:1: expected ```lang fence after empty assignment") - })?; - if trimmed.contains("name=") { - bail!( - "{open_line}:1: `name=` on fences was removed; \ - use `name` = then a ```{lang} fence (same shape as formulas)" - ); - } - let mut body_lines: Vec = Vec::new(); - let mut closed = false; - let mut end_line = open_line; - while let Some(l) = self.peek() { - if crate::foreign::is_fence_closer(l.text.trim()) { - end_line = l.line_no; - self.bump(); - closed = true; - break; - } - body_lines.push(l.text.clone()); - self.bump(); - } - if !closed { - bail!("{open_line}:1: unclosed code fence ```{lang}"); - } - let source = body_lines.join("\n"); - Ok(( - Expr::Code(crate::value::CodeBlock { lang, source }), - end_line, - )) - } - - /// Consume `$$…$$`. Returns `(expr, end_line, optional var from % marqdo: var=)`. - fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32, Option)> { - let open = self - .bump() - .ok_or_else(|| anyhow::anyhow!("{span}: expected `$$` formula fence"))?; - let open_line = open.line_no; - let trimmed = open.text.trim(); - if trimmed.starts_with("$$:") || trimmed.starts_with("$$ name=") { - bail!( - "{open_line}:1: `$$:name` / `$$ name=` binding was removed; \ - use `% marqdo: var=name` inside `$$…$$` or `name` = then a fence" - ); - } - // Single-line: $$body$$ - if trimmed.starts_with("$$") && trimmed.ends_with("$$") && trimmed.len() > 4 { - let body = trimmed[2..trimmed.len() - 2].trim(); - if body.is_empty() { - bail!("{open_line}:1: empty formula"); - } - let (meta_var, tex) = strip_formula_marqdo_meta(body) - .map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?; - if tex.is_empty() { - bail!("{open_line}:1: empty formula"); - } - return Ok(( - formula_fence_to_expr(&tex) - .map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?, - open_line, - meta_var, - )); - } - if trimmed != "$$" { - bail!( - "{open_line}:1: expected `$$` fence opener, got: {trimmed}" - ); - } - let mut body_lines: Vec = Vec::new(); - let mut closed = false; - let mut end_line = open_line; - while let Some(l) = self.peek() { - if l.text.trim() == "$$" { - end_line = l.line_no; - self.bump(); - closed = true; - break; - } - body_lines.push(l.text.clone()); - self.bump(); - } - if !closed { - bail!("{open_line}:1: unclosed formula fence `$$`"); - } - let raw = body_lines.join("\n"); - let (meta_var, tex) = strip_formula_marqdo_meta(&raw) - .map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?; - if tex.is_empty() { - bail!("{open_line}:1: empty formula"); - } - let expr = formula_fence_to_expr(&tex) - .map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?; - Ok((expr, end_line, meta_var)) - } - - /// Standalone `$$` with `% marqdo: var=` → Assign (no empty RHS required). - fn try_parse_meta_formula_assign(&mut self) -> Result> { - if !self.peek_is_formula_fence() { - return Ok(None); - } - let Some(l) = self.peek() else { - return Ok(None); - }; - let span = Span { - line: l.line_no, - col: 1, - }; - let (value, end_line, meta_var) = self.consume_formula_fence(span)?; - let Some(name) = meta_var else { - bail!( - "{span}: formula fence must follow an empty assignment (`name` =) \ - or include `% marqdo: var=name` inside the block" - ); - }; - if crate::aliases::is_reserved_keyword(&name) { - bail!("{span}: `{name}` is a reserved keyword"); - } - Ok(Some(Stmt::Assign { - name, - value, - span, - end_line, - })) - } - - /// GFM table after empty RHS: - /// - 1-col → List - /// - first header `@` / `行` / `row` → List of row Maps (marker col excluded) - /// - else ≥2-col → Map (column-oriented) - /// - /// Also used for **unbound** tables in a function body (value computed, not stored). - /// - /// Data cells are expressions ([`parse_call_arg_value`]); headers stay key text. - fn consume_table(&mut self) -> Result { - self.skip_noise(); - let mut header: Vec = Vec::new(); - let mut header_line: u32 = 1; - let mut data_rows: Vec<(u32, Vec)> = Vec::new(); - let mut header_done = false; - let mut sep_done = false; - while let Some(l) = self.peek() { - if l.kind != LineKind::Code { - break; - } - let t = l.text.trim(); - if !t.starts_with('|') { - break; - } - let line_no = l.line_no; - self.bump(); - let cells = split_table_row(t); - if !header_done { - header = cells; - header_line = line_no; - header_done = true; - continue; - } - if !sep_done - && cells - .iter() - .all(|c| c.chars().all(|ch| ch == '-' || ch == ':' || ch.is_whitespace())) - { - sep_done = true; - continue; - } - sep_done = true; - data_rows.push((line_no, cells)); - } - if !header_done { - bail!("expected GFM table after empty assignment"); - } - // Strong / Surface: unequal row arity is stuck — no silent pad/truncate. - for (line_no, cells) in &data_rows { - if cells.len() != header.len() { - return Err(Diagnostic::new( - None, - Span { - line: *line_no, - col: 1, - }, - format!( - "table row arity mismatch: expected {} columns, got {}", - header.len(), - cells.len() - ), - ) - .into()); - } - } - let row_oriented = header - .first() - .map(|h| is_row_table_marker(h)) - .unwrap_or(false); - if row_oriented { - return build_row_oriented_table(header, header_line, data_rows); - } - if header.len() <= 1 { - let mut rows = Vec::new(); - for (line_no, cells) in data_rows { - if let Some(cell) = cells.first() { - rows.push(parse_table_cell(cell, line_no)?); - } - } - return Ok(Expr::List(rows)); - } - // Duplicate header keys are errors (column identity must be unique). - let mut seen = std::collections::HashSet::new(); - for key in &header { - if !seen.insert(key.clone()) { - return Err(Diagnostic::new( - None, - Span { - line: header_line, - col: 1, - }, - format!("duplicate table header `{key}`"), - ) - .into()); - } - } - let n_rows = data_rows.len(); - let mut pairs = Vec::with_capacity(header.len()); - for (col, key) in header.iter().enumerate() { - if n_rows == 1 { - let (line_no, cells) = &data_rows[0]; - let raw = cells.get(col).map(|s| s.as_str()).unwrap_or(""); - pairs.push((key.clone(), parse_table_cell(raw, *line_no)?)); - } else { - // 0 rows → empty lists; ≥2 rows → column lists. - let mut col_vals = Vec::with_capacity(n_rows); - for (line_no, cells) in &data_rows { - let raw = cells.get(col).map(|s| s.as_str()).unwrap_or(""); - col_vals.push(parse_table_cell(raw, *line_no)?); - } - pairs.push((key.clone(), Expr::List(col_vals))); - } - } - Ok(Expr::Map(pairs)) - } - - fn parse_branch(&mut self) -> Result { - let first = self.peek().unwrap(); - let span = Span { - line: first.line_no, - col: 1, - }; - let base_indent = indent_of(&first.text); - let mut arms = Vec::new(); - - while self.skip_noise() { - let Some(l) = self.peek() else { break }; - let ind = indent_of(&l.text); - if ind < base_indent { - break; - } - let trimmed = l.text.trim(); - let Some(num) = ordered_item_number(trimmed) else { - break; - }; - if ind != base_indent { - break; - } - // Same-indent restart at `1.` begins a new Branch statement. - if !arms.is_empty() && num == 1 { - break; - } - let cond_src = strip_ordered(trimmed).unwrap(); - self.bump(); - - let condition = parse_branch_condition(cond_src)?; - - let body = self.parse_indented_body(base_indent)?; - arms.push(BranchArm { condition, body }); - } - - if arms.is_empty() { - bail!("{span}: empty branch"); - } - Ok(Stmt::Branch { arms, span }) - } - - fn parse_loop_or_err(&mut self) -> Result { - let line = self.bump().unwrap(); - let span = Span { - line: line.line_no, - col: 1, - }; - let base_indent = indent_of(&line.text); - let trimmed = line.text.trim(); - let rest = trimmed.strip_prefix('-').unwrap().trim(); - - // `` M3: occlusion loop `- [描述](遍历 集合 为 变量)` - if crate::parse::expr::markup_default() == crate::parse::expr::Markup::Occlusion { - if let Some((label, coll, item)) = parse_occluded_foreach(rest) { - let body = self.parse_indented_body(base_indent)?; - return Ok(Stmt::ForEach { - item, - collection: coll, - label: Some(label), - body, - span, - }); - } - } - - // foreach: [item](collection) or narrative sugar - if let Some((item, coll)) = parse_foreach_header(rest) - .or_else(|| parse_foreach_narrative(rest)) - { - let body = self.parse_indented_body(base_indent)?; - return Ok(Stmt::ForEach { - item, - collection: coll, - label: None, - body, - span, - }); - } - - // while: expression - let condition = parse_expr_str(rest)?; - let body = self.parse_indented_body(base_indent)?; - Ok(Stmt::While { - condition, - body, - span, - }) - } - - fn parse_indented_body(&mut self, parent_indent: usize) -> Result> { - let mut body = Vec::new(); - while self.skip_noise() { - let Some(l) = self.peek() else { break }; - let ind = indent_of(&l.text); - if ind <= parent_indent { - // Same-indent `2.` / `-` ends body (next arm / sibling). - break; - } - let trimmed = l.text.trim(); - if is_frame(trimmed) { - self.bump(); - continue; - } - if is_heading(trimmed) { - break; - } - if is_ordered_branch(trimmed) { - // Nested branch inside body - body.push(self.parse_branch()?); - continue; - } - if trimmed.starts_with('-') { - body.push(self.parse_loop_or_err()?); - continue; - } - // Same prose rights as function body (fixes arm/loop narrative escape). - if self.peek_is_prose() { - let line = self.bump().unwrap(); - let span = Span { - line: line.line_no, - col: 1, - }; - let bits = scan_prose_line(line.text.trim_end_matches(['\r', '\n'])); - let mut end_arm = false; - for bit in bits { - match bit { - ProseBit::Decl { .. } => {} - ProseBit::BoldCode { inner, .. } => { - body.push(self.stmt_from_bold_inner(&inner, span.clone())?); - } - ProseBit::ItalicReturn { inner, .. } => { - body.push(stmt_from_italic_return(&inner, span.clone())?); - end_arm = true; - break; - } - } - } - if end_arm { - break; - } - continue; - } - if self.peek_is_formula_fence() { - if let Some(stmt) = self.try_parse_meta_formula_assign()? { - body.push(stmt); - continue; - } - } - let stmt = self.parse_simple_stmt()?; - let end_arm = matches!(stmt, Stmt::Return { .. }); - body.push(stmt); - if end_arm { - break; - } - } - Ok(body) - } -} - -fn split_assign_inner(inner: &str) -> Option<(String, String)> { - let inner = inner.trim(); - if let Some(rest) = inner.strip_prefix('`') { - let end = rest.find('`')?; - let name = rest[..end].to_string(); - if name.is_empty() { - return None; - } - let after = rest[end + 1..].trim_start(); - let rhs = after.strip_prefix('=')?.trim().to_string(); - return Some((name, rhs)); - } - // Bare LHS: `answer = …` (italic exemption). - let eq = inner.find('=')?; - let name = inner[..eq].trim(); - if !is_bare_assign_ident(name) { - return None; - } - let rhs = inner[eq + 1..].trim().to_string(); - Some((name.to_string(), rhs)) -} - -fn is_bare_assign_ident(s: &str) -> bool { - if s.is_empty() || s.contains('`') || s.chars().any(char::is_whitespace) { - return false; - } - let mut chars = s.chars(); - let Some(first) = chars.next() else { - return false; - }; - if !(first.is_alphanumeric() || first == '_' || !first.is_ascii()) { - return false; - } - true -} - -/// Same-line `$$body$$` or `$body$` → Formula; otherwise None. -fn try_parse_inline_formula(rhs: &str) -> Result> { - let rhs = rhs.trim(); - if rhs.starts_with("$$:") || rhs.starts_with("$$ name=") { - bail!( - "`$$:name` / `$$ name=` binding was removed; use `% marqdo: var=name` \ - inside `$$…$$` or `name` = then a fence" - ); - } - if rhs.starts_with("$$") { - if rhs.ends_with("$$") && rhs.len() > 4 { - let body = rhs[2..rhs.len() - 2].trim(); - if body.is_empty() { - bail!("empty formula"); - } - let (_meta, tex) = strip_formula_marqdo_meta(body) - .map_err(|e| anyhow::anyhow!("{e}"))?; - if tex.is_empty() { - bail!("empty formula"); - } - let expr = formula_fence_to_expr(&tex).map_err(|e| anyhow::anyhow!("formula: {e}"))?; - return Ok(Some(expr)); - } - bail!("incomplete inline formula (expected `$$…$$` on one line)"); - } - // Traditional inline: $…$ (not $$) - if rhs.starts_with('$') && rhs.ends_with('$') && rhs.len() > 2 && !rhs.starts_with("$$") { - let body = rhs[1..rhs.len() - 1].trim(); - if body.is_empty() { - bail!("empty formula"); - } - if body.contains('%') && body.to_lowercase().contains("marqdo:") { - bail!( - "inline `$…$` must not use `% marqdo:` (breaks Markdown/TeX); \ - bind with `name` = $…$ or use a `$$` block with `% marqdo: var=`" - ); - } - let expr = formula_fence_to_expr(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?; - return Ok(Some(expr)); - } - Ok(None) -} - -/// Strip `% marqdo: var=name` directive lines from formula fence body. -/// Returns `(optional var name, remaining TeX)`. -fn strip_formula_marqdo_meta(body: &str) -> Result<(Option, String), String> { - let mut meta_var: Option = None; - let mut out: Vec<&str> = Vec::new(); - for line in body.lines() { - let t = line.trim(); - if let Some(rest) = t.strip_prefix('%') { - let rest = rest.trim_start(); - if rest.to_ascii_lowercase().starts_with("marqdo:") { - let after = rest["marqdo:".len()..].trim_start(); - let mut got_var = false; - for part in after.split_whitespace() { - if let Some(v) = part.strip_prefix("var=") { - if v.is_empty() { - return Err("% marqdo: var= requires a name".into()); - } - if !is_bare_assign_ident(v) { - return Err(format!("invalid marqdo var name `{v}`")); - } - if meta_var.as_deref() == Some(v) || meta_var.is_none() { - meta_var = Some(v.to_string()); - } else { - return Err(format!( - "conflicting % marqdo: var= ({} vs {v})", - meta_var.as_deref().unwrap_or("") - )); - } - got_var = true; - } else { - return Err(format!("unknown marqdo key `{part}` (only var= is supported)")); - } - } - if !got_var { - return Err("% marqdo: requires var=".into()); - } - continue; // strip directive line - } - } - out.push(line); - } - Ok((meta_var, out.join("\n").trim().to_string())) -} - -fn check_formula_meta_var(assign_name: &str, meta: Option<&str>, span: Span) -> Result<()> { - match meta { - None => Ok(()), - Some(v) if v == assign_name => Ok(()), - Some(v) => bail!( - "{span}: formula `% marqdo: var={v}` conflicts with assignment `{assign_name}`" - ), - } -} - -fn formula_fence_to_expr(body: &str) -> Result { - if crate::formula::looks_like_matrix(body) { - let rows = crate::formula::parse_eval_matrix(body)?; - return Ok(Expr::Formula(crate::formula::Expr::Matrix { - source: body.trim().to_string(), - rows, - })); - } - let expr = crate::formula::parse(body)?; - Ok(Expr::Formula(expr)) -} - -fn parse_backtick_ident(s: &str) -> Option { - let s = s.trim(); - if !s.starts_with('`') { - return None; - } - let inner = &s[1..]; - let end = inner.find('`')?; - let name = &inner[..end]; - if name.is_empty() || s.len() != end + 2 { - return None; - } - Some(name.to_string()) -} - -fn parse_param_line(trimmed: &str, span:Span) -> Option { - use crate::ast::Param; - let rest = trimmed.strip_prefix('+')?.trim(); - if rest.is_empty() || !rest.starts_with('`') { - return None; - } - let end_tick = rest[1..].find('`')?; - let name = rest[1..end_tick + 1].to_string(); - if name.is_empty() { - return None; - } - let after = rest[end_tick + 2..].trim(); - let default = if let Some(def_s) = after.strip_prefix('=') { - let def_s = def_s.trim(); - if def_s.is_empty() { - return None; - } - Some(parse_call_arg_value(def_s).ok()?) - } else if after.is_empty() { - None - } else { - return None; - }; - Some(Param { - name, - span, - default, - inferred: false, - }) -} - -fn parse_foreach_ident(s: &str) -> Option { - let s = s.trim(); - if s.starts_with('`') { - return parse_backtick_ident(s); - } - if s.is_empty() { - return None; - } - // Bare name exemption: `[item](list)` without ticks (foreach only). - if s.chars().any(|c| c.is_whitespace() || c == '`' || c == '[' || c == ']') { - return None; - } - let mut chars = s.chars(); - let first = chars.next()?; - if !(first.is_alphanumeric() || first == '_' || !first.is_ascii()) { - return None; - } - Some(s.to_string()) -} - -/// `` M3: `[描述](遍历 集合 为 变量)` → `(label, collection, item)`. -fn parse_occluded_foreach(rest: &str) -> Option<(String, String, String)> { - let rest = rest.trim(); - if !rest.starts_with('[') { - return None; - } - let end = rest.find(']')?; - let label = rest[1..end].trim().to_string(); - let after = rest[end + 1..].trim_start(); - if !after.starts_with('(') || !after.ends_with(')') { - return None; - } - let inner = after[1..after.len() - 1].trim(); - let parts: Vec<&str> = inner.split_whitespace().collect(); - // `遍历 为 ` (English `for as ` accepted too) - if parts.len() != 4 { - return None; - } - let head_ok = matches!(parts[0], "遍历" | "for"); - let mid_ok = matches!(parts[2], "为" | "as" | "in"); - if !head_ok || !mid_ok { - return None; - } - let coll = parse_foreach_ident(parts[1])?; - let item = parse_foreach_ident(parts[3])?; - Some((label, coll, item)) -} - -fn parse_foreach_header(rest: &str) -> Option<(String, String)> { - // [`item`](`collection`) or bare [item](collection); sides may mix. - let rest = rest.trim(); - if !rest.starts_with('[') { - return None; - } - let end_item = rest.find(']')?; - let item = parse_foreach_ident(&rest[1..end_item])?; - let after = rest[end_item + 1..].trim_start(); - if !after.starts_with('(') || !after.ends_with(')') { - return None; - } - let coll = parse_foreach_ident(&after[1..after.len() - 1])?; - Some((item, coll)) -} - -/// Narrative foreach sugar (recommended remains `- [item](coll)`). -/// - ZH: `对`xs`的每一项`项`` optional `遍历` -/// - EN: `for each `item` in `xs`` -fn parse_foreach_narrative(rest: &str) -> Option<(String, String)> { - let rest = rest.trim(); - if let Some(after) = rest.strip_prefix('对') { - let (coll, after) = take_backtick_token(after.trim_start())?; - let after = after.trim_start().strip_prefix("的每一项")?; - let (item, after) = take_backtick_token(after.trim_start())?; - let after = after - .trim() - .trim_end_matches('。') - .trim(); - let after = after.strip_prefix("遍历").unwrap_or(after).trim(); - if after.is_empty() { - return Some((item, coll)); - } - return None; - } - let lower = rest.to_ascii_lowercase(); - let Some(idx) = lower.find("for each ") else { - return None; - }; - if idx != 0 { - return None; - } - let after = rest["for each ".len()..].trim_start(); - let (item, after) = take_backtick_token(after)?; - let after = after.trim_start(); - let after_l = after.to_ascii_lowercase(); - if !after_l.starts_with("in ") && !after_l.starts_with("in\t") { - // require ` in ` - let Some(in_at) = after_l.find("in ") else { - return None; - }; - if in_at != 0 { - return None; - } - } - let after = after["in ".len()..].trim_start(); - let (coll, after) = take_backtick_token(after)?; - if after.trim().is_empty() { - return Some((item, coll)); - } - None -} - -fn take_backtick_token(s: &str) -> Option<(String, &str)> { - let s = s.trim_start(); - if !s.starts_with('`') { - return None; - } - let end = s[1..].find('`')?; - let name = s[1..1 + end].to_string(); - if name.is_empty() { - return None; - } - Some((name, &s[1 + end + 1..])) -} - -/// Branch arm condition: expr, bold code, narrative (当`n`大于 0 时), or else `*`. -fn parse_branch_condition(cond_src: &str) -> Result> { - let t = cond_src.trim(); - if t.is_empty() || t == "*" { - return Ok(None); - } - // "否则 *" / "else *" - if let Some(before) = t.strip_suffix('*') { - let before = before.trim(); - if before.is_empty() - || before == "否则" - || before == "其它" - || before == "其他" - || before.eq_ignore_ascii_case("else") - || before.eq_ignore_ascii_case("otherwise") - { - return Ok(None); - } - } - if let Ok(e) = parse_expr_str(t) { - return Ok(Some(e)); - } - if let Some(inner) = extract_first_bold_inner(t) { - if let Ok(e) = parse_expr_str(inner.trim()) { - return Ok(Some(e)); - } - } - if let Some(e) = try_narrative_condition(t) { - return Ok(Some(e)); - } - bail!( - "branch condition: cannot parse `{t}` \ - (use an expression, **`n` > 0**, or 当`n`大于 0 时)" - ) -} - -fn extract_first_bold_inner(s: &str) -> Option<&str> { - let start = s.find("**")?; - let rest = &s[start + 2..]; - let end = rest.find("**")?; - Some(&rest[..end]) -} - -fn try_narrative_condition(s: &str) -> Option { - let mut s = s.trim(); - for p in ["当且仅当", "当", "若", "如果"] { - if let Some(r) = s.strip_prefix(p) { - s = r.trim_start(); - break; - } - } - let lower = s.to_ascii_lowercase(); - if let Some(r) = lower.strip_prefix("when ") { - let _ = r; - s = s[5..].trim_start(); - } else if let Some(r) = lower.strip_prefix("if ") { - let _ = r; - s = s[3..].trim_start(); - } - for suf in ["的话", "时", "则"] { - if let Some(r) = s.strip_suffix(suf) { - s = r.trim_end(); - } - } - let mut mapped = s.to_string(); - let replacements = [ - ("大于等于", ">="), - ("小于等于", "<="), - ("不等于", "!="), - ("等于", "=="), - ("大于", ">"), - ("小于", "<"), - ]; - for (zh, op) in replacements { - if mapped.contains(zh) { - mapped = mapped.replace(zh, op); - break; - } - } - parse_expr_str(mapped.trim()).ok() -} - -fn parse_heading(trimmed: &str) -> Option<(u8, &str)> { - if !trimmed.starts_with('#') { - return None; - } - let mut level = 0u8; - for c in trimmed.chars() { - if c == '#' { - level = level.saturating_add(1); - } else { - break; - } - } - if level == 0 || level > 6 { - return None; - } - let name = trimmed[level as usize..].trim(); - if name.is_empty() { - return None; - } - Some((level, name)) -} - -/// `# Child = > Parent` → `(Child, Some(Parent))`; plain `# Child` → `(Child, None)`. -fn parse_object_decl(level: u8, raw: &str, span: Span) -> Result<(String, Option)> { - let raw = raw.trim(); - if let Some(eq) = raw.find('=') { - if level != 1 { - return Err(Diagnostic::new( - None, - span, - "inheritance (`= > Base`) is only allowed on `#` object headings", - ) - .into()); - } - let name = raw[..eq].trim(); - let rhs = raw[eq + 1..].trim(); - if name.is_empty() { - return Err(Diagnostic::new(None, span, "object name missing before `=`").into()); - } - if !is_simple_type_name(name) { - return Err(Diagnostic::new( - None, - span, - format!("invalid object name `{name}`"), - ) - .into()); - } - let Some(after_gt) = rhs.strip_prefix('>') else { - return Err(Diagnostic::new( - None, - span, - "object inheritance requires `# Name = > Base` (base must follow `>`)", - ) - .into()); - }; - let base = after_gt.trim(); - if base.is_empty() { - return Err(Diagnostic::new(None, span, "missing base type after `>`").into()); - } - if base.contains('.') { - return Err(Diagnostic::new( - None, - span, - format!("base type must be a simple name, not a path (`{base}`)"), - ) - .into()); - } - if !is_simple_type_name(base) { - return Err(Diagnostic::new( - None, - span, - format!("invalid base type name `{base}`"), - ) - .into()); - } - return Ok((name.to_string(), Some(base.to_string()))); - } - Ok((raw.to_string(), None)) -} - -fn is_simple_type_name(s: &str) -> bool { - let mut chars = s.chars(); - let Some(first) = chars.next() else { - return false; - }; - if !(first.is_alphabetic() || first == '_' || !first.is_ascii()) { - return false; - } - chars.all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()) -} - -/// Result of one import map entry (`bind: target` under `import:` / `导入:`). -#[derive(Debug, Clone)] -pub enum ImportLine { - File(Import), - Member(Use), -} - -/// Hint shown when legacy one-line or `>` imports are rejected. -pub const NESTED_IMPORT_HINT: &str = "legacy frontmatter import removed; use nested YAML \ -`import:\\n bind: target` (Chinese: `导入:`) — or run `marqdo migrate imports --write`"; - -fn split_frontmatter_key(trimmed: &str) -> Option<(&str, &str)> { - let t = trimmed.trim(); - if t.is_empty() || t.starts_with('#') { - return None; - } - let Some((key, rest)) = t.split_once(':') else { - return None; - }; - let key = key.trim(); - if key.is_empty() || key.contains(' ') { - return None; - } - // Avoid treating `http://…` style as key (no spaces in key already; also reject if key has `/`) - if key.contains('/') { - return None; - } - Some((key, rest.trim())) -} - -fn collect_block_scalar(cur: &mut Cursor<'_>, indicator: &str) -> Result { - let mut lines = Vec::new(); - while let Some(line) = cur.peek() { - let raw = line.text.trim_end_matches(['\r', '\n']); - let bt = raw.trim(); - if bt == "---" { - break; - } - // Next top-level key ends the block - if !raw.starts_with(' ') && !raw.starts_with('\t') && !bt.is_empty() { - if split_frontmatter_key(bt).is_some() { - break; - } - if indicator.is_empty() { - // empty rest on key line without block indicator: no body - break; - } - } - if indicator.is_empty() { - break; - } - cur.bump(); - if raw.starts_with(' ') || raw.starts_with('\t') { - lines.push(strip_yaml_indent(raw)); - } else if bt.is_empty() { - lines.push(String::new()); - } else { - // folded content without indent — take as-is once - lines.push(bt.to_string()); - break; - } - } - if indicator.starts_with('>') { - Ok(lines - .into_iter() - .filter(|l| !l.is_empty()) - .collect::>() - .join(" ")) - } else { - Ok(lines.join("\n")) - } -} - -fn strip_yaml_indent(line: &str) -> String { - if line.starts_with(" ") { - line[2..].to_string() - } else if line.starts_with('\t') { - line[1..].to_string() - } else { - line.trim_start_matches([' ', '\t']).to_string() - } -} - -/// True for removed one-liner `import bind:target` / `导入 bind:target`. -pub fn is_legacy_import_oneliner(trimmed: &str) -> bool { - let t = trimmed.trim(); - if t.starts_with("import") - && t.get(6..) - .is_some_and(|s| s.starts_with(|c: char| c.is_whitespace())) - { - let after = t[6..].trim(); - return after.contains(':') && !after.is_empty(); - } - if let Some(a) = t.strip_prefix("导入") { - let a = a.trim_start(); - // `导入:` is the new nested header, not a one-liner - if a.is_empty() || a.starts_with(':') { - return false; - } - return a.contains(':'); - } - false -} - -fn legacy_frontmatter_import_hint(trimmed: &str) -> Option { - let t = trimmed.trim(); - if is_legacy_import_oneliner(t) { - return Some(NESTED_IMPORT_HINT.into()); - } - if !t.starts_with('>') { - return None; - } - let rest = t[1..].trim(); - let looks_file = rest.contains(".mq.md"); - let looks_use = rest.starts_with("use") - || rest.starts_with("使用") - || rest.starts_with("use ") - || rest.starts_with("使用 "); - if looks_file || looks_use { - return Some(NESTED_IMPORT_HINT.into()); - } - None -} - -/// Parse one `bind` / `target` pair from a nested import map entry. -pub fn parse_import_binding(bind: &str, target: &str) -> Result { - if bind.is_empty() || !is_simple_bind_name(bind) { - bail!("invalid import bind `{bind}`"); - } - if target.is_empty() || target.contains('`') || target.contains(char::is_whitespace) { - bail!("invalid import target `{target}`"); - } - - if target.ends_with(".mq.md") { - return Ok(ImportLine::File(Import { - path: target.to_string(), - bind: bind.to_string(), - })); - } - - let path: Vec = target - .split('.') - .map(|s| s.trim().to_string()) - .collect(); - if path.len() < 2 || path.iter().any(|p| p.is_empty() || !is_simple_bind_name(p)) { - bail!( - "import target `{target}` must be a `.mq.md` path or dotted member path (e.g. `time.format`)" - ); - } - Ok(ImportLine::Member(Use { - path, - bind: bind.to_string(), - })) -} - -fn push_import_line( - imports: &mut Vec, - uses: &mut Vec, - entry: ImportLine, - span: Span, -) -> Result<()> { - match entry { - ImportLine::File(imp) => { - if imports.iter().any(|i| i.bind == imp.bind) || uses.iter().any(|u| u.bind == imp.bind) - { - return Err(bail_at( - None, - span, - format!("duplicate import bind `{}`", imp.bind), - )); - } - imports.push(imp); - } - ImportLine::Member(u) => { - if imports.iter().any(|i| i.bind == u.bind) || uses.iter().any(|x| x.bind == u.bind) { - return Err(bail_at( - None, - span, - format!("duplicate import bind `{}`", u.bind), - )); - } - uses.push(u); - } - } - Ok(()) -} - -/// Format an import entry as the catalog display string `import bind:target`. -pub fn format_import_display(line: &ImportLine) -> String { - match line { - ImportLine::File(imp) => format!("import {}:{}", imp.bind, imp.path), - ImportLine::Member(u) => format!("import {}:{}", u.bind, u.path.join(".")), - } -} - -/// Scan frontmatter for nested `import:` / `导入:` entries (soft; skips legacy / errors). -pub fn scan_frontmatter_imports(source: &str) -> Vec { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let lines: Vec<&str> = source.lines().collect(); - if lines.first().map(|l| l.trim()) != Some("---") { - return Vec::new(); - } - let mut out = Vec::new(); - let mut i = 1usize; - while i < lines.len() { - let t = lines[i].trim(); - if t == "---" { - break; - } - if let Some((key, rest)) = split_frontmatter_key(t) { - if (key == "import" || key == "导入") && rest.is_empty() { - i += 1; - while i < lines.len() { - let raw = lines[i].trim_end_matches(['\r', '\n']); - let bt = raw.trim(); - if bt == "---" { - break; - } - if bt.is_empty() { - i += 1; - continue; - } - if !raw.starts_with(' ') && !raw.starts_with('\t') { - break; - } - let content = strip_yaml_indent(raw); - if let Some((bind_raw, target_raw)) = content.split_once(':') { - if let Ok(entry) = - parse_import_binding(bind_raw.trim(), target_raw.trim()) - { - out.push(entry); - } - } - i += 1; - } - continue; - } - } - i += 1; - } - out -} - -fn is_simple_bind_name(s: &str) -> bool { - is_simple_type_name(s) -} - -/// Parse a catalog-style `import bind:path` display string, or bare `bind:path`. -pub fn parse_import_spec(line: &str) -> Option { - let t = line.trim(); - let body = if t.starts_with("import") - && t.get(6..) - .is_some_and(|s| s.starts_with(|c: char| c.is_whitespace())) - { - t[6..].trim() - } else if let Some(a) = t.strip_prefix("导入") { - let a = a.trim(); - if a.is_empty() || a.starts_with(':') { - return None; - } - a - } else { - t - }; - let (bind, target) = body.split_once(':')?; - match parse_import_binding(bind.trim(), target.trim()).ok()? { - ImportLine::File(imp) => Some(imp), - ImportLine::Member(_) => None, - } -} - -/// Rejected API: old one-liner always errors (kept for callers that still probe lines). -pub fn parse_import_line(trimmed: &str) -> Result> { - if is_legacy_import_oneliner(trimmed) { - bail!("{NESTED_IMPORT_HINT}"); - } - Ok(None) -} - -fn is_heading(trimmed: &str) -> bool { - parse_heading(trimmed).is_some() -} - -fn is_frame(trimmed: &str) -> bool { - if trimmed.len() < 3 { - return false; - } - // Empty returns `**` / `****` are not frames. - if is_empty_return_marker(trimmed) { - return false; - } - trimmed.chars().all(|c| c == '-') || trimmed.chars().all(|c| c == '*') -} - -/// `****` or `**` + whitespace only + `**`, or whole-line `**` (v0.3 empty italic). -fn is_empty_return_marker(trimmed: &str) -> bool { - if trimmed == "**" { - return true; - } - is_empty_bold_return(trimmed) -} - -/// `****` or `**` + whitespace only + `**`. -fn is_empty_bold_return(trimmed: &str) -> bool { - if !(trimmed.starts_with("**") && trimmed.ends_with("**") && trimmed.len() >= 4) { - return false; - } - trimmed[2..trimmed.len() - 2].trim().is_empty() -} - -fn stmt_from_italic_return(inner: &str, span: Span) -> Result { - let inner = inner.trim(); - let value = if inner.is_empty() - || inner == "None" - || inner == "无" - || inner == "空" - { - Expr::Literal(Literal::None) - } else { - parse_expr_prefer_var(inner)? - }; - Ok(Stmt::Return { value, span }) -} - -/// Merge declarations into params: promote names that are read in the body (or have defaults). -/// -/// Design §8.2: a declaration is a backtick mention or the first bold assignment -/// to that name. Elevate only when an executable read cannot be satisfied by a prior -/// local assign that does not itself read the name (e.g. `score = 1` is local; -/// `n = n + 1` still needs external `n`). -// ---------- 契约提取(T2.1 · 渐进式契约 / 标注类型) ---------- -// -// 未绑定文档表 → 契约;**位置 + 形状**双重判定;在升参推断之前执行。 -// 契约表从 body 移除(元数据永不执行、不污染升参推断); -// 非契约表(普通文档/数据表,含一切**绑定**表)原样保留 ⇒ 无契约文件零回归。 - -/// 从表头行起收集连续 `|` 行作为契约原文(诊断 `doc_quote`)。 -fn table_quote(lines: &[ClassifiedLine], start_line: u32) -> (u32, Vec) { - let Some(mut idx) = (0..lines.len()).find(|&i| lines[i].line_no == start_line) else { - return (start_line, Vec::new()); - }; - let mut quote = Vec::new(); - let mut end = start_line; - while idx < lines.len() && lines[idx].text.trim().starts_with('|') { - quote.push(lines[idx].text.trim_end().to_string()); - end = lines[idx].line_no; - idx += 1; - } - (end, quote) -} - -/// 是否「字段契约形状」的未绑定文档表(紧邻判定的透明跳过用)。 -fn is_fields_contract_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> bool { - let Stmt::Expr { value: Expr::Map(pairs), span } = stmt else { - return false; - }; - let (end_line, quote) = table_quote(lines, span.line); - matches!( - crate::contract::parse_contract_table(pairs, span.line, end_line, quote), - Some(Ok(ref c)) if !c.fields.is_empty() - ) -} - -/// 紧邻绑定名:跳过连续的字段契约表后,下一条是不是 `` `名` = `` 绑定。 -fn next_binding_name(body: &[Stmt], start: usize, lines: &[ClassifiedLine]) -> Option { - let mut j = start; - while j < body.len() && is_fields_contract_stmt(&body[j], lines) { - j += 1; - } - match body.get(j) { - Some(Stmt::Assign { name, .. }) => Some(name.clone()), - _ => None, - } -} - -fn empty_like(piece: &crate::contract::Contract) -> crate::contract::Contract { - crate::contract::Contract { - params: Vec::new(), - returns: None, - fields: Vec::new(), - start_line: piece.start_line, - end_line: piece.end_line, - quote: Vec::new(), - } -} - -/// 合并契约块;重复行/重复表 → `contract.duplicate` 诊断(防两份契约打架)。 -fn merge_piece( - dst: &mut Option, - piece: crate::contract::Contract, - unit: &str, - span: Span, -) -> Result<()> { - match dst { - None => *dst = Some(piece), - Some(slot) => { - if let Err(m) = crate::contract::merge_contract(slot, piece.clone()) { - return Err(piece - .diagnostic( - "contract.duplicate", - unit, - m, - "删除重复契约表,只保留一份".to_string(), - None, - span, - ) - .into()); - } - } - } - Ok(()) -} - -fn extract_function_contract(fun: &mut Function, lines: &[ClassifiedLine]) -> Result<()> { - let body = std::mem::take(&mut fun.body); - let mut fun_contract: Option = None; - let mut var_contracts: std::collections::HashMap = - std::collections::HashMap::new(); - let mut keep: Vec = Vec::with_capacity(body.len()); - // 「函数体首个可执行行之前」:未绑定表(Map/List 形状的 `Stmt::Expr`)不算可执行行。 - let mut prefix_zone = true; - let mut i = 0usize; - - while i < body.len() { - let stmt = &body[i]; - let (pairs, span) = match stmt { - Stmt::Expr { - value: Expr::Map(pairs), - span, - } => (pairs, *span), - other => { - if !matches!(other, Stmt::Expr { value: Expr::List(_), .. }) { - prefix_zone = false; - } - keep.push(other.clone()); - i += 1; - continue; - } - }; - let (end_line, quote) = table_quote(lines, span.line); - let Some(parsed) = crate::contract::parse_contract_table(pairs, span.line, end_line, quote) - else { - // 非契约形状:先试定理表(ADR 0010),再按普通表保留。 - if let Some(parsed) = crate::contract::parse_assumption_table(pairs, span.line) { - if prefix_zone { - fun.assumptions.extend(parsed.map_err(|msg| - bail_at(None, span, format!("proof.assumption_malformed: {msg}")))?); - i += 1; - continue; - } - } - match crate::contract::parse_claim_table(pairs, span.line) { - // 合法定理表:只在「首个可执行行之前」生效;提取后从 body 移除。 - // 其余位置仍是普通表,由 `check --proof` 报 proof.claim_misplaced。 - Some(Ok(rows)) if prefix_zone => { - fun.claims.extend(rows); - i += 1; - continue; - } - // 畸形/歧义/错位的定理形表:保持普通表(默认关), - // `check --proof` 重扫 body 时报 malformed/ambiguous/misplaced。 - _ => { - keep.push(stmt.clone()); - i += 1; - continue; - } - } - }; - let piece = parsed?; // 契约形状但畸形 → 必产诊断(contract.malformed) - let is_fn_contract = !piece.params.is_empty() || piece.returns.is_some(); - - if is_fn_contract { - // 形参/返回表只在「首个可执行行之前」生效,否则视为普通表。 - if !prefix_zone { - keep.push(stmt.clone()); - i += 1; - continue; - } - merge_piece(&mut fun_contract, piece, &fun.name, span)?; - i += 1; - continue; - } - - // 字段表:紧邻 `` `名` = `` 绑定之前 → 集合契约;对象体首成员前 → 对象字段契约。 - if let Some(name) = next_binding_name(&body, i + 1, lines) { - let mut slot = Some( - var_contracts - .remove(&name) - .unwrap_or_else(|| empty_like(&piece)), - ); - merge_piece(&mut slot, piece, &name, span)?; - var_contracts.insert(name, slot.unwrap()); - i += 1; - continue; - } - if prefix_zone && fun.is_object() { - merge_piece(&mut fun_contract, piece, &fun.name, span)?; - i += 1; - continue; - } - // 不在允许位置 → 不是契约,原样保留。 - keep.push(stmt.clone()); - i += 1; - } - - fun.body = keep; - fun.contract = fun_contract; - fun.var_contracts = var_contracts; - Ok(()) -} - -fn merge_inferred_params( - fun: &mut Function, - prose_decls: &[(String, Option, u32)], - inherited: &HashSet, -) -> Result<()> { - use std::collections::HashSet; - - let mut needs_input = HashSet::new(); - // Captured entry/object bindings are available before the child body. - // An explicit prose input still shadows an outer binding of the same name. - let explicit: HashSet<_> = prose_decls.iter().map(|(name, _, _)| name.clone()).collect(); - let mut bound: HashSet<_> = inherited.difference(&explicit).cloned().collect(); - let mut assign_decls = Vec::new(); - // Defaults execute before the body. Reads used only there still require - // declared inputs; later body assignments cannot satisfy those reads. - for param in &fun.params { - if let Some(default)=¶m.default { collect_reads_expr(default,&mut needs_input); } - } - for (_,default,_) in prose_decls { - if let Some(default)=default { - let parsed=parse_expr_prefer_var(default).or_else(|_|parse_value_or_interp(default))?; - collect_reads_expr(&parsed,&mut needs_input); - } - } - collect_names_needing_input( - &fun.body, - &mut bound, - &mut needs_input, - &HashSet::new(), - &mut assign_decls, - ); - - needs_input.retain(|name| !inherited.contains(name) || explicit.contains(name)); - - // Declaration order is source order: backtick mentions and first assignment - // left-hand sides. An assignment promotes only when its right-hand side (or a - // later read) still needs an external value. - let mut events: Vec<(u32, usize, String, Option)> = Vec::new(); - for (i, (name, default_txt, line)) in prose_decls.iter().enumerate() { - events.push((*line, i, name.clone(), default_txt.clone())); - } - let prose_n = events.len(); - for (j, (name, line)) in assign_decls.iter().enumerate() { - if prose_decls.iter().any(|(n, _, _)| n == name) { - continue; - } - if !needs_input.contains(name) { - continue; - } - events.push((*line, prose_n + j, name.clone(), None)); - } - events.sort_by_key(|e| (e.0, e.1)); - - for (line, _ord, name, default_txt) in events { - if name == "self" || name == "自" { - continue; - } - if fun.params.iter().any(|p| p.name == name) { - continue; - } - let has_default = default_txt.is_some(); - // Elevate: defaulted always; or executable read that needs an external input. - if !has_default && !needs_input.contains(&name) { - if !bound.contains(&name) { - fun.dead_binds.push(name); - } - continue; // dead bind or pure local - } - let default = if let Some(txt) = default_txt { - Some(parse_expr_prefer_var(&txt).or_else(|_| parse_value_or_interp(&txt))?) - } else { - None - }; - fun.params.push(Param { - name, - span:Span::new(line,1), - default, - inferred: true, - }); - } - Ok(()) -} - -/// Walk body in order. `bound` = names already assigned locally without needing input. -/// On read of unbound name → needs input. On assign, RHS reads are checked first -/// (so `n = n + 1` marks `n` as needing input before binding). -/// `assign_decls` records the first assignment of each name, which §8.2 treats as -/// a declaration when no backtick mention came first. Loop items are not declarations. -fn collect_names_needing_input( - stmts: &[Stmt], - bound: &mut std::collections::HashSet, - needs: &mut std::collections::HashSet, - loop_items: &std::collections::HashSet, - assign_decls: &mut Vec<(String, u32)>, -) { - for s in stmts { - match s { - Stmt::Assign { name, value, span, .. } => { - let mut rhs_reads = std::collections::HashSet::new(); - collect_reads_expr(value, &mut rhs_reads); - for r in &rhs_reads { - if !bound.contains(r) && !loop_items.contains(r) { - needs.insert(r.clone()); - } - } - if !loop_items.contains(name) - && !assign_decls.iter().any(|(n, _)| n == name) - { - assign_decls.push((name.clone(), span.line)); - } - bound.insert(name.clone()); - } - Stmt::Return { value, .. } => { - let mut reads = std::collections::HashSet::new(); - collect_reads_expr(value, &mut reads); - for r in reads { - if !bound.contains(&r) && !loop_items.contains(&r) { - needs.insert(r); - } - } - } - Stmt::Call { call, .. } => { - let mut reads = std::collections::HashSet::new(); - collect_reads_call(call, &mut reads); - for r in reads { - if !bound.contains(&r) && !loop_items.contains(&r) { - needs.insert(r); - } - } - } - Stmt::Expr { value, .. } => { - let mut reads = std::collections::HashSet::new(); - collect_reads_expr(value, &mut reads); - for r in reads { - if !bound.contains(&r) && !loop_items.contains(&r) { - needs.insert(r); - } - } - } - Stmt::Branch { arms, .. } => { - let has_else = arms.iter().any(|a| a.condition.is_none()); - let mut common: Option> = None; - for a in arms { - if let Some(c) = &a.condition { - let mut reads = std::collections::HashSet::new(); - collect_reads_expr(c, &mut reads); - for r in reads { - if !bound.contains(&r) && !loop_items.contains(&r) { - needs.insert(r); - } - } - } - let mut arm_bound = bound.clone(); - collect_names_needing_input( - &a.body, - &mut arm_bound, - needs, - loop_items, - assign_decls, - ); - if has_else { - common = Some(match common { - None => arm_bound, - Some(prev) => prev.intersection(&arm_bound).cloned().collect(), - }); - } - } - if let Some(c) = common { - for n in c { - bound.insert(n); - } - } - } - Stmt::While { - condition, body, .. - } => { - let mut reads = std::collections::HashSet::new(); - collect_reads_expr(condition, &mut reads); - for r in reads { - if !bound.contains(&r) && !loop_items.contains(&r) { - needs.insert(r); - } - } - collect_names_needing_input(body, bound, needs, loop_items, assign_decls); - } - Stmt::ForEach { - item, - collection, - body, - .. - } => { - if !bound.contains(collection) && !loop_items.contains(collection) { - needs.insert(collection.clone()); - } - let mut nested = loop_items.clone(); - nested.insert(item.clone()); - collect_names_needing_input(body, bound, needs, &nested, assign_decls); - } - } - } -} - -fn collect_reads_call(call: &crate::ast::CallExpr, reads: &mut std::collections::HashSet) { - if let Some(recv) = &call.receiver { - reads.insert(recv.clone()); - } - // Callee name itself is not a variable read. - for a in &call.args { - match a { - crate::ast::Arg::Positional(e) | crate::ast::Arg::Named { value: e, .. } => { - collect_reads_expr(e, reads); - } - } - } -} - -fn collect_reads_expr(expr: &Expr, reads: &mut std::collections::HashSet) { - match expr { - Expr::Occluded { payload, .. } => { - if let Some(inner) = payload { - collect_reads_expr(inner, reads); - } - } - Expr::Var(n) => { - reads.insert(n.clone()); - } - Expr::Call(c) => collect_reads_call(c, reads), - Expr::Binary { left, right, .. } => { - collect_reads_expr(left, reads); - collect_reads_expr(right, reads); - } - Expr::Unary { expr, .. } => collect_reads_expr(expr, reads), - Expr::Index { base, label } => { - collect_reads_expr(base, reads); - if let IndexKey::Var(n) = label { - reads.insert(n.clone()); - } - } - Expr::List(xs) => { - for x in xs { - collect_reads_expr(x, reads); - } - } - Expr::Map(entries) => { - for (_, v) in entries { - collect_reads_expr(v, reads); - } - } - Expr::Interp(parts) => { - for p in parts { - match p { - crate::ast::InterpPart::Var(n) => { - reads.insert(n.clone()); - } - crate::ast::InterpPart::Index { base, .. } => { - reads.insert(base.clone()); - } - crate::ast::InterpPart::Lit(_) => {} - } - } - } - Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {} - } -} - -fn is_ordered_branch(trimmed: &str) -> bool { - strip_ordered(trimmed).is_some() -} - -/// Leading `N` in an ordered-list item `N. …` (1-based Markdown marker). -fn ordered_item_number(trimmed: &str) -> Option { - let mut chars = trimmed.chars(); - let mut n: u32 = 0; - let mut saw_digit = false; - while let Some(c) = chars.next() { - if let Some(d) = c.to_digit(10) { - saw_digit = true; - n = n.saturating_mul(10).saturating_add(d); - continue; - } - if c == '.' && saw_digit { - return Some(n); - } - return None; - } - None -} - -fn strip_ordered(trimmed: &str) -> Option<&str> { - let mut chars = trimmed.chars(); - let mut saw_digit = false; - while let Some(c) = chars.next() { - if c.is_ascii_digit() { - saw_digit = true; - continue; - } - if c == '.' && saw_digit { - return Some(chars.as_str().trim_start()); - } - return None; - } - None -} - -fn indent_of(text: &str) -> usize { - text.chars() - .take_while(|c| *c == ' ' || *c == '\t') - .map(|c| if c == '\t' { 4 } else { 1 }) - .sum() -} - -fn parse_table_cell(raw: &str, line: u32) -> Result { - parse_call_arg_value(raw).map_err(|e| { - Diagnostic::new( - None, - Span { line, col: 1 }, - format!("table cell: {e}"), - ) - .into() - }) -} - -/// First-column header that opts into row-oriented records (`List` of `Map`). -fn is_row_table_marker(header: &str) -> bool { - matches!(header.trim(), "@" | "行" | "row") -} - -fn build_row_oriented_table( - header: Vec, - header_line: u32, - data_rows: Vec<(u32, Vec)>, -) -> Result { - if header.len() < 2 { - return Err(Diagnostic::new( - None, - Span { - line: header_line, - col: 1, - }, - "row-oriented table needs field columns after `@` / `行` / `row`", - ) - .into()); - } - let fields: Vec = header[1..].to_vec(); - let mut seen = std::collections::HashSet::new(); - for key in &fields { - if !seen.insert(key.clone()) { - return Err(Diagnostic::new( - None, - Span { - line: header_line, - col: 1, - }, - format!("duplicate table header `{key}`"), - ) - .into()); - } - } - let mut rows = Vec::with_capacity(data_rows.len()); - for (line_no, cells) in data_rows { - let mut pairs = Vec::with_capacity(fields.len()); - for (i, key) in fields.iter().enumerate() { - // Skip marker column (index 0); fields start at column 1. - let raw = cells.get(i + 1).map(|s| s.as_str()).unwrap_or(""); - pairs.push((key.clone(), parse_table_cell(raw, line_no)?)); - } - rows.push(Expr::Map(pairs)); - } - Ok(Expr::List(rows)) -} - -fn split_table_row(line: &str) -> Vec { - let t = line.trim(); - let t = t.strip_prefix('|').unwrap_or(t); - let t = t.strip_suffix('|').unwrap_or(t); - // GFM escaped pipes belong to a cell, including inside a quoted value. - // Preserve other escapes for the expression parser (e.g. \n in text). - let mut cells = Vec::new(); - let mut cell = String::new(); - let mut chars = t.chars().peekable(); - while let Some(ch) = chars.next() { - if ch == '\\' { - match chars.peek().copied() { - Some('|') => { - chars.next(); - cell.push('|'); - } - Some('\\') => { - chars.next(); - cell.push('\\'); - cell.push('\\'); - } - _ => cell.push(ch), - } - } else if ch == '|' { - cells.push(cell.trim().to_string()); - cell.clear(); - } else { - cell.push(ch); - } - } - cells.push(cell.trim().to_string()); - cells -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::ast::Stmt; - - #[test] - fn assumption_tables_are_metadata_and_never_runtime_steps() { - let src=r#"# main - -## guarded - -| 假设 | 前置 | 后置 | -|---|---|---| -| backend.fetch | 金额 > 0 | 返回.ok = True | - -| 定理 | 结论 | 前提 | 策略 | -|---|---|---|---| -| 安全 | 长度(轨迹) = 0 | | auto | - -*1* -"#; - let m=parse_source(src).unwrap(); - let f=&m.functions[0].children[0]; - assert_eq!(f.assumptions.len(),1); - assert_eq!(f.assumptions[0].op,"backend.fetch"); - assert_eq!(f.assumptions[0].premise.as_deref(),Some("金额 > 0")); - assert_eq!(f.claims.len(),1); - assert_eq!(f.body.len(),1,"assumption and theorem tables must not execute"); - } - - #[test] - fn parse_formula_meta_var_standalone() { - let src = "# main\n\n$$\n% marqdo: var=f\nx^2 - 2\n$$\n"; - let m = parse_source(src).unwrap(); - match &m.functions[0].body[0] { - Stmt::Assign { name, value, .. } => { - assert_eq!(name, "f"); - assert!(matches!(value, Expr::Formula(_))); - } - other => panic!("expected formula assign, got {other:?}"), - } - } - - #[test] - fn parse_formula_meta_conflicts_with_assign() { - let src = "# main\n\n`f` =\n$$\n% marqdo: var=g\nx\n$$\n"; - let err = parse_source(src).unwrap_err().to_string(); - assert!( - err.contains("conflicts") || err.contains("var=g"), - "{err}" - ); - } - - #[test] - fn parse_foreach_narrative_zh_en() { - let src = "# main\n\n- 对`xs`的每一项`项`\n > print text=`项`\n\n- for each `item` in `ys`\n > print text=`item`\n"; - let m = parse_source(src).unwrap(); - match &m.functions[0].body[0] { - Stmt::ForEach { item, collection, .. } => { - assert_eq!(item, "项"); - assert_eq!(collection, "xs"); - } - other => panic!("zh foreach: {other:?}"), - } - match &m.functions[0].body[1] { - Stmt::ForEach { item, collection, .. } => { - assert_eq!(item, "item"); - assert_eq!(collection, "ys"); - } - other => panic!("en foreach: {other:?}"), - } - } - - #[test] - fn branch_arm_prose_stays_inside_arm() { - let src = include_str!("../../tests/markup-v03/branch-arm-prose.mq.md"); - let m = parse_source(src).unwrap(); - let main = &m.functions[0]; - let branches: Vec<_> = main - .body - .iter() - .filter(|s| matches!(s, Stmt::Branch { .. })) - .collect(); - assert_eq!( - branches.len(), - 1, - "expected one Branch, body={:?}", - main.body - ); - match &main.body[1] { - Stmt::Branch { arms, .. } => { - assert_eq!(arms.len(), 2, "arms={arms:?}"); - assert!( - !arms[0].body.is_empty(), - "then arm must contain prose stmts: {:?}", - arms[0].body - ); - assert!( - !arms[1].body.is_empty(), - "else arm must contain prose stmts: {:?}", - arms[1].body - ); - } - other => panic!("expected Branch as body[1] after assign, got {other:?}"), - } - // No Call/Assign print siblings after the branch - assert!( - !main.body.iter().skip(2).any(|s| matches!(s, Stmt::Call { .. } | Stmt::Assign { .. })), - "prose escaped branch: {:?}", - main.body - ); - } - - #[test] - fn parse_hello() { - let src = include_str!("../../tests/structure/hello.mq.md"); - let m = parse_source(src).unwrap(); - assert_eq!(m.functions.len(), 1); - assert_eq!(m.functions[0].name, "Hello World"); - assert_eq!(m.functions[0].body.len(), 1); - assert!(matches!(m.functions[0].body[0], Stmt::Call { .. })); - } - - #[test] - fn parse_index() { - let src = include_str!("../../tests/structure/nested-call.mq.md"); - let m = parse_source(src).unwrap(); - assert!(m.imports.is_empty()); - let main = m.functions.iter().find(|f| f.name == "main").unwrap(); - assert_eq!(main.children.len(), 1); - assert_eq!(main.children[0].name, "问候"); - assert_eq!(main.children[0].params[0].name, "谁"); - } - - #[test] - fn parse_optional_param_default() { - let src = "# main\n\n## f\n + `a`\n + `b`=Hi\n\n> print text=`a`\n"; - let m = parse_source(src).unwrap(); - let f = &m.functions[0].children[0]; - assert_eq!(f.params.len(), 2); - assert_eq!(f.params[0].name, "a"); - assert_eq!(f.params[1].name, "b"); - assert!(matches!( - f.params[1].default, - Some(Expr::Literal(Literal::Text(ref s))) if s == "Hi" - )); - } - - #[test] - fn parse_foreach_backtick_ids() { - let src = "# main\n\n- [`x`](`xs`)\n > print text=`x`\n"; - let m = parse_source(src).unwrap(); - match &m.functions[0].body[0] { - Stmt::ForEach { item, collection, .. } => { - assert_eq!(item, "x"); - assert_eq!(collection, "xs"); - } - other => panic!("expected foreach, got {other:?}"), - } - } - - #[test] - fn parse_foreach_bare_ids() { - let src = "# main\n\n- [x](xs)\n > print text=`x`\n"; - let m = parse_source(src).unwrap(); - match &m.functions[0].body[0] { - Stmt::ForEach { item, collection, .. } => { - assert_eq!(item, "x"); - assert_eq!(collection, "xs"); - } - other => panic!("expected foreach, got {other:?}"), - } - } - - #[test] - fn parse_foreach_mixed_ticks() { - let src = "# main\n\n- [果](`篮子`)\n > print text=`果`\n"; - let m = parse_source(src).unwrap(); - match &m.functions[0].body[0] { - Stmt::ForEach { item, collection, .. } => { - assert_eq!(item, "果"); - assert_eq!(collection, "篮子"); - } - other => panic!("expected foreach, got {other:?}"), - } - } - - #[test] - fn parse_bold_assign_italic_return() { - let src = "# main\n\n**answer = 1**\n*answer*\n"; - let m = parse_source(src).unwrap(); - match &m.functions[0].body[0] { - Stmt::Assign { name, value, .. } => { - assert_eq!(name, "answer"); - assert!(matches!(value, Expr::Literal(Literal::Int(1)))); - } - other => panic!("expected assign, got {other:?}"), - } - match &m.functions[0].body[1] { - Stmt::Return { value, .. } => { - assert!(matches!(value, Expr::Var(n) if n == "answer")); - } - other => panic!("expected return, got {other:?}"), - } - } - - #[test] - fn parse_local_assign_not_inferred_param() { - let src = r#"## soft -Candidates may include lexical `score`. -**score = 1** -1. `score` - **_ = score** -2. * - **_ = 0** ---- -# main -> soft -"#; - let m = parse_source(src).unwrap(); - let soft = m.functions.iter().find(|f| f.name == "soft").unwrap(); - assert!( - soft.params.iter().all(|p| p.name != "score"), - "score must stay local, params={:?}", - soft.params.iter().map(|p| &p.name).collect::>() - ); - } - - #[test] - fn parse_prose_inc() { - let src = "## 加一\n\n输入`n`。**n=n+1**返回*n*。\n\n# main\n\n**r = 加一 1**\n**print text=r**\n"; - let m = parse_source(src).unwrap(); - let add = m.functions.iter().find(|f| f.name == "加一").unwrap(); - assert_eq!(add.params.len(), 1); - assert_eq!(add.params[0].name, "n"); - assert!(add.params[0].inferred); - let dump = crate::ast::format_ast_dump("t.mq.md", &m); - assert!(dump.contains("params=[n inferred]"), "{dump}"); - assert!(!dump.contains("dead="), "{dump}"); - } - - #[test] - fn parse_bare_inc_is_required_param() { - // §8.2: the first bold assignment is a declaration. The RHS reads `n` - // before the bind, so `n` is a required parameter even without a backtick. - let src = "## inc\n\n**n = n + 1**\n*n*\n\n# main\n\n**print text=\"ok\"**\n"; - let m = parse_source(src).unwrap(); - let inc = m.functions.iter().find(|f| f.name == "inc").unwrap(); - assert_eq!( - inc.params.iter().map(|p| p.name.as_str()).collect::>(), - ["n"] - ); - assert!(inc.params[0].default.is_none()); - assert!(inc.params[0].inferred); - } - - #[test] - fn parse_dead_binds_visible_in_ast_dump() { - let src = include_str!("../../tests/markup-v03/dead-bind.mq.md"); - let m = parse_source(src).unwrap(); - let echo = m.functions.iter().find(|f| f.name == "回声").unwrap(); - assert_eq!(echo.params.iter().map(|p| p.name.as_str()).collect::>(), ["题干"]); - assert!(echo.dead_binds.contains(&"Markdown".to_string()), "{:?}", echo.dead_binds); - assert!(echo.dead_binds.contains(&"GFM".to_string()), "{:?}", echo.dead_binds); - let dump = crate::ast::format_ast_dump("t.mq.md", &m); - assert!(dump.contains("dead="), "{dump}"); - assert!(dump.contains("Markdown"), "{dump}"); - } - - #[test] - fn parse_branch_rejects_plus_arm() { - let src = "# main\n\n+ `x` > 0\n > print text=ok\n"; - let err = parse_source(src).unwrap_err(); - let msg = format!("{err}"); - assert!( - msg.contains("unrecognized") || msg.contains("empty branch"), - "{msg}" - ); - } - - #[test] - fn parse_branch() { - let src = include_str!("../../tests/structure/branch.mq.md"); - let m = parse_source(src).unwrap(); - let main = &m.functions[0]; - assert!(main.body.iter().any(|s| matches!(s, Stmt::Branch { .. }))); - } - - #[test] - fn consecutive_branches_restart_at_one() { - let m = parse_source(include_str!( - "../../tests/structure/branch-consecutive.mq.md" - )) - .unwrap(); - let branches: Vec<_> = m.functions[0] - .body - .iter() - .filter(|s| matches!(s, Stmt::Branch { .. })) - .collect(); - assert_eq!( - branches.len(), - 3, - "expected three Branch stmts, got {:?}", - m.functions[0].body - ); - for b in &branches { - match b { - Stmt::Branch { arms, .. } => assert_eq!(arms.len(), 2), - _ => unreachable!(), - } - } - // Arm bodies must hold the prints (not leaked as sibling Calls). - match branches[0] { - Stmt::Branch { arms, .. } => { - assert!( - matches!(arms[0].body[0], Stmt::Call { .. }), - "first arm body={:?}", - arms[0].body - ); - } - _ => unreachable!(), - } - } - - #[test] - fn consecutive_branches_without_blank_line() { - let src = "# main\n\n1. True\n > print text=A\n2. *\n > print text=skip\n1. True\n > print text=B\n"; - let m = parse_source(src).unwrap(); - let branches: Vec<_> = m.functions[0] - .body - .iter() - .filter(|s| matches!(s, Stmt::Branch { .. })) - .collect(); - assert_eq!(branches.len(), 2, "got {:?}", m.functions[0].body); - match branches[0] { - Stmt::Branch { arms, .. } => assert_eq!(arms.len(), 2), - _ => unreachable!(), - } - } - - #[test] - fn parse_formula_assign_fence() { - let src = "# main\n\n`f` =\n$$\nx^2 - 2\n$$\n\n> print text=`f`\n"; - let m = parse_source(src).unwrap(); - let body = &m.functions[0].body; - match &body[0] { - Stmt::Assign { - name, - value: Expr::Formula(e), - end_line, - .. - } => { - assert_eq!(name, "f"); - assert_eq!(e.as_display(), "x^2 - 2"); - assert!(*end_line > 3, "end_line should cover the fence, got {end_line}"); - } - other => panic!("expected formula assign, got {other:?}"), - } - } - - #[test] - fn parse_code_assign_fence() { - let src = "# main\n\n`hi` =\n```python\nprint(1)\n```\n\n> print text=ok\n"; - let m = parse_source(src).unwrap(); - match &m.functions[0].body[0] { - Stmt::Assign { - name, - value: Expr::Code(c), - .. - } => { - assert_eq!(name, "hi"); - assert_eq!(c.lang, "python"); - assert_eq!(c.source, "print(1)"); - } - other => panic!("expected code assign, got {other:?}"), - } - } - - #[test] - fn branch_else_common_local_is_not_a_param() { - let src = r#"# main - -## f - + `a`=None - -1. `a` - **k = a** -2. * - **k = None** - -| x | -|---| -| `k` | -"#; - let m = parse_source(src).unwrap(); - let f = m - .functions - .iter() - .flat_map(|outer| outer.children.iter()) - .find(|f| f.name == "f") - .unwrap(); - assert_eq!( - f.params.iter().map(|p| p.name.as_str()).collect::>(), - ["a"], - "{:?}", - f.params - ); - } -} - -/// 核心表面构造注册表(T1.3)——`(id, Markdown 外形)`。 -/// -/// **紧邻分类代码维护**;与 `doc/design/core-surface.md` 的 id 列强一致, -/// 由 `tests/core_surface.rs` 守卫:改动任一侧不同步 → CI 红。 -/// 新增条目必须走 ADR(`doc/design/layers.md` 准入戒律)。 -pub const CORE_CONSTRUCTS: &[(&str, &str)] = &[ - // 行构造 - ("narrative", "无标记文字"), - ("blank", "空行"), - ("heading-unit", "# / ##"), - ("call-line", ">"), - ("branch-list", "1. 递增"), - ("loop-list", "-"), - ("param", "+ `名`"), - ("table", "GFM 表"), - ("fence", "```lang"), - ("hr", "--- / ***"), - ("writeback", ""), - // 内联标记 - ("ident", "`名`"), - ("bold-code", "**…**"), - ("italic-return", "*…*"), - ("empty-return", "*None* / ****"), - ("link-index", "[键](集合)"), - ("bracket-call", "修饰… [函数] …"), - ("footnote-index", "集合[^键]"), - ("soft-emphasis", "*仅* / **说明**"), -]; - -#[cfg(test)] -mod escaped_gfm_cell_tests { - use super::*; - #[test] - fn escaped_pipes_do_not_create_columns() { - assert_eq!( - split_table_row(r#"| "source\|skill" | "line\n" |"#), - [r#""source|skill""#, r#""line\n""#] - ); - assert_eq!(split_table_row(r"| a\\| b |"), [r"a\\", "b"]); - let module = parse_source( - "## value\n\n`items` =\n\n| line |\n|---|\n| \"source\\|skill\" |\n\n*items*\n", - ) - .unwrap(); - assert!(format!("{:?}", module.functions[0].body).contains("source|skill")); - } -} - -#[cfg(test)] -mod lexical_input_tests { - use super::*; - #[test] - fn child_updates_capture_existing_entry_state_without_extra_inputs() { - let source="# main\n\n**count = 0**\n\n## bump\n\nWe **count = count + 1** and return *count*.\n"; - let module=parse_source(source).unwrap(); - assert!(module.functions[0].children[0].params.is_empty()); - } - #[test] - fn explicit_prose_inputs_can_shadow_parent_bindings() { - let source="# main\n\n**count = 0**\n\n## add\n\nUse `count` for this independent call.\nReturn *(count + 1)*.\n"; - let module=parse_source(source).unwrap(); - let params=&module.functions[0].children[0].params; - assert_eq!(params.len(),1); - assert_eq!(params[0].name,"count"); - } - #[test] - fn reading_a_loop_item_in_a_branch_does_not_promote_a_later_local() { - let source="## select\n\nUse `values`.\n- [Inspect values](for values as item)\n 1. `item` != \"\"\n We **output = item**.\n\nWe **item = \"done\"** and return *item*.\n"; - let module=parse_source(source).unwrap(); - let params=&module.functions[0].params; - assert_eq!(params.len(),1); - assert_eq!(params[0].name,"values"); - } -} diff --git a/src/parse/prose.rs b/src/parse/prose.rs deleted file mode 100755 index 6e0d228..0000000 --- a/src/parse/prose.rs +++ /dev/null @@ -1,515 +0,0 @@ -//! Inline prose scan for Markup v0.3 (叙述中的 `` `名` `` / `**代码**` / `*返回*`). -//! -//! Soft Markdown emphasis that does not look like code/return is skipped (G2 — -//! [code-as-docs-gaps.md](../../../doc/design/code-as-docs-gaps.md)). -//! -//! Comment-line Markdown links `[label](target)` are NarrativeRef / navigation -//! sites (G03); they are never executed. - -use crate::lex::{matching_bold_close_inline, matching_italic_close_inline, LineKind}; - -pub use crate::lex::looks_like_bold_code; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ProseBit { - /// `` `ident` `` or `` `ident`=default `` (default string is raw RHS text). - Decl { - name: String, - default: Option, - /// Byte offset in the line (for diagnostics). - at: usize, - }, - /// Inner text of `**…**` (code segment). - BoldCode { inner: String, at: usize }, - /// Inner text of `*…*` (return), when not starting a bold. - ItalicReturn { inner: String, at: usize }, -} - -/// Why a comment-line `[]()` is not an executable BoundCall (G03). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum NarrativeLinkKind { - /// In-project symbol / binding / `#anchor` — inert explanation. - Narrate, - /// URL or file path — navigation only; never fetched by compile/run. - Navigation, -} - -impl NarrativeLinkKind { - pub fn as_str(self) -> &'static str { - match self { - Self::Narrate => "narrate", - Self::Navigation => "navigation", - } - } -} - -/// One Markdown link found on a comment (narrative) line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct NarrativeLink { - pub label: String, - pub target: String, - pub kind: NarrativeLinkKind, - /// 1-based source line. - pub line: u32, - pub at: usize, -} - -/// Classify a link target without parsing it as an expression. -pub fn classify_narrative_target(target: &str) -> NarrativeLinkKind { - let t = target.trim(); - // Compiler-owned mq:// anchor addresses are inert knowledge references, - // never external URLs or auto-executable code. - if t.starts_with("mq://") && (t.contains("#anchor-") || t.contains("#claim-")) { - return NarrativeLinkKind::Narrate; - } - if t.starts_with("http://") - || t.starts_with("https://") - || t.starts_with("mailto:") - || t.starts_with("//") - { - return NarrativeLinkKind::Navigation; - } - if t.contains('/') || t.ends_with(".md") || t.ends_with(".mq.md") || t.ends_with(".html") - { - return NarrativeLinkKind::Navigation; - } - NarrativeLinkKind::Narrate -} - -/// Scan whole-source comment lines for Markdown links; skip fences and code lines. -pub fn scan_narrative_links(source: &str) -> Vec { - let classified = crate::lex::classify_source(source); - let mut out = Vec::new(); - let mut in_fence = false; - for (i, cl) in classified.iter().enumerate() { - let line_no = (i + 1) as u32; - let trimmed = cl.text.trim(); - if trimmed.starts_with("```") { - in_fence = !in_fence; - continue; - } - if in_fence { - continue; - } - if cl.kind != LineKind::Comment { - continue; - } - out.extend(scan_md_links_in_line(&cl.text, line_no)); - } - out -} - -/// Scan one line for `[label](target)`, skipping `` `inline` `` spans. -pub fn scan_md_links_in_line(line: &str, line_no: u32) -> Vec { - let bytes = line.as_bytes(); - let mut i = 0usize; - let mut out = Vec::new(); - while i < bytes.len() { - if bytes[i] == b'`' { - if let Some(rel) = line[i + 1..].find('`') { - i = i + 1 + rel + 1; - continue; - } - i += 1; - continue; - } - if bytes[i] != b'[' { - i += 1; - continue; - } - let Some((label, target, next)) = parse_md_link(line, i) else { - i += 1; - continue; - }; - let kind = classify_narrative_target(&target); - out.push(NarrativeLink { - label, - target, - kind, - line: line_no, - at: i, - }); - i = next; - } - out -} - -fn parse_md_link(line: &str, start: usize) -> Option<(String, String, usize)> { - if !line[start..].starts_with('[') { - return None; - } - let mut depth = 0i32; - let mut label_end = None; - for (rel, ch) in line[start..].char_indices() { - match ch { - '[' => depth += 1, - ']' => { - depth -= 1; - if depth == 0 { - label_end = Some(start + rel); - break; - } - } - _ => {} - } - } - let label_end = label_end?; - let after = line.get(label_end + 1..)?; - if !after.starts_with('(') { - return None; - } - let mut depth = 0i32; - let mut target_end = None; - for (rel, ch) in after.char_indices() { - match ch { - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - target_end = Some(rel); - break; - } - } - _ => {} - } - } - let target_end = target_end?; - let label = line[start + 1..label_end].to_string(); - let target = after[1..target_end].trim().to_string(); - if label.is_empty() || target.is_empty() { - return None; - } - // Executable occlusion payloads look like calls (`foo(…)` / `a.b(…)`); those - // live on Code lines already. If a comment link target is expression-shaped - // with `(`, still treat as narrate/navigation by target class — do not eval. - let next = label_end + 1 + target_end + 1; - Some((label, target, next)) -} - -/// Scan a narrative (or mixed) line for v0.3 inline bits, left to right. -pub fn scan_prose_line(line: &str) -> Vec { - let bytes = line.as_bytes(); - let mut i = 0usize; - let mut out = Vec::new(); - while i < bytes.len() { - let c = bytes[i]; - if c == b'`' { - if let Some((bit, next)) = scan_backtick_decl(line, i) { - out.push(bit); - i = next; - continue; - } - // Non-decl span (e.g. `` `OPENAI_*` ``): skip whole ticks so inner `*` - // does not open italic/bold. - if let Some(rel) = line[i + 1..].find('`') { - i = i + 1 + rel + 1; - continue; - } - i += 1; - continue; - } - if c == b'*' && i + 1 < bytes.len() && bytes[i + 1] == b'*' { - let rest = &line[i..]; - if let Some(close_rel) = matching_bold_close_inline(rest) { - let inner = rest[2..close_rel].to_string(); - let next = i + close_rel + 2; - if looks_like_bold_code(&inner) { - out.push(ProseBit::BoldCode { inner, at: i }); - } - i = next; - continue; - } - i += 1; - continue; - } - if c == b'*' { - let rest = &line[i..]; - if rest.starts_with("**") { - i += 1; - continue; - } - if let Some(close_rel) = matching_italic_close_inline(rest) { - let inner = rest[1..close_rel].to_string(); - let next = i + close_rel + 1; - if looks_like_italic_return(line, i, next, &inner) { - out.push(ProseBit::ItalicReturn { inner, at: i }); - } - i = next; - continue; - } - } - i += 1; - } - out -} - -/// Whether `*inner*` is a return (vs mid-prose English/CJK emphasis). -/// -/// Design §12 #5: mid-line italic is return only for whole-line, `返回*…*`, -/// or an expression-shaped span — not `*very important*` / `*foo.bar*`. -fn looks_like_italic_return(line: &str, at: usize, after: usize, inner: &str) -> bool { - let t = inner.trim(); - if t.is_empty() - || matches!( - t, - "None" | "无" | "空" | "True" | "False" | "真" | "假" | "true" | "false" - ) - { - return true; - } - // Whole-line return: only ws outside the italic span (`*n*` / `*总额*`). - let before = line[..at].trim(); - let after_s = line.get(after..).unwrap_or("").trim(); - if before.is_empty() && after_s.is_empty() { - return true; - } - // Narration "返回*n*" / "return *n*" - if before.ends_with("返回") || before.ends_with("return") || before.ends_with("Return") { - return true; - } - // Mid-prose: expression-shaped only (`*n + 1*` / `*x=1*`); not hyphenated emphasis. - if is_hyphenated_emphasis(t) { - return false; - } - t.starts_with('>') - || t.contains('=') - || t.chars() - .any(|c| matches!(c, '+' | '-' | '*' | '/' | '(' | ')' | '[' | ']')) -} - -fn is_hyphenated_emphasis(t: &str) -> bool { - !t.chars().any(char::is_whitespace) - && t.contains('-') - && !t - .chars() - .any(|c| matches!(c, '+' | '*' | '/' | '(' | ')' | '[' | ']' | '=')) -} - -fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> { - let rest = &line[start + 1..]; - let end = rest.find('`')?; - let name = rest[..end].to_string(); - if name.is_empty() || !is_prose_decl_name(&name) { - return None; - } - let after_tick = start + 1 + end + 1; - let after = line.get(after_tick..)?; - if let Some(stripped) = after.strip_prefix('=') { - // Quoted defaults may contain prose delimiters, glob stars or spaces. - // Keep the same quoted literal accepted by explicit parameter defaults. - let mut def_end = if let Some(quote @ ('"' | '\'')) = stripped.chars().next() { - let mut escaped = false; - stripped - .char_indices() - .skip(1) - .find_map(|(i, ch)| { - if escaped { - escaped = false; - } else if ch == '\\' { - escaped = true; - } else if ch == quote { - return Some(i + ch.len_utf8()); - } - None - }) - .unwrap_or(stripped.len()) - } else { - stripped - .find(|c: char| { - c.is_whitespace() - || matches!(c, ',' | '。' | ';' | '、' | ',' | ';' | '*' | '`') - }) - .unwrap_or(stripped.len()) - }; - // English sentence punctuation belongs to narration after a literal. - // Keep quoted strings, dotted names and decimal syntax unchanged. - if let Some(literal) = stripped[..def_end].strip_suffix('.') { - if matches!(literal, "True" | "False" | "true" | "false" | "None" | "真" | "假" | "无" | "空") { - def_end -= 1; - } - } - let default = stripped[..def_end].to_string(); - let next = after_tick + 1 + def_end; - return Some(( - ProseBit::Decl { - name, - default: Some(default), - at: start, - }, - next, - )); - } - Some(( - ProseBit::Decl { - name, - default: None, - at: start, - }, - after_tick, - )) -} - -/// Identifiers only: letters / digits / `_` / non-ASCII (CJK). Rejects `` `n+1` ``. -fn is_prose_decl_name(name: &str) -> bool { - let mut chars = name.chars(); - let Some(first) = chars.next() else { - return false; - }; - if !(first.is_alphabetic() || first == '_' || !first.is_ascii()) { - return false; - } - chars.all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn scan_inc_prose_line() { - let line = "对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。"; - let bits = scan_prose_line(line); - assert_eq!(bits.len(), 3); - match &bits[0] { - ProseBit::Decl { name, default, .. } => { - assert_eq!(name, "n"); - assert!(default.is_none()); - } - _ => panic!("{:?}", bits[0]), - } - match &bits[1] { - ProseBit::BoldCode { inner, .. } => assert_eq!(inner, "n=n+1"), - _ => panic!("{:?}", bits[1]), - } - match &bits[2] { - ProseBit::ItalicReturn { inner, .. } => assert_eq!(inner, "n"), - _ => panic!("{:?}", bits[2]), - } - } - - #[test] - fn scan_default_decl() { - let line = "默认`礼貌`=False。"; - let bits = scan_prose_line(line); - assert_eq!(bits.len(), 1); - match &bits[0] { - ProseBit::Decl { name, default, .. } => { - assert_eq!(name, "礼貌"); - assert_eq!(default.as_deref(), Some("False")); - } - _ => panic!("{:?}", bits[0]), - } - } - - #[test] - fn sentence_period_after_boolean_or_none_is_not_part_of_the_default() { - for (line, expected) in [ - ("Use `flag`=False. Continue.", "False"), - ("Use `flag`=True.", "True"), - ("Use `value`=None.", "None"), - ("使用`值`=假. 继续。", "假"), - ("Use `text`=\"False.\".", "\"False.\""), - ("Use `text`=module.value.", "module.value."), - ("Use `rate`=0.5.", "0.5."), - ] { - let bits = scan_prose_line(line); - match &bits[..] { - [ProseBit::Decl { default: Some(actual), .. }] => assert_eq!(actual, expected, "{line}"), - _ => panic!("unexpected prose scan: {bits:?}"), - } - } - } - - #[test] - fn quoted_defaults_keep_delimiters_and_escaped_quotes() { - let line = r#"输入 `pattern`="**";`mime`="text/plain;charset=utf-8";`label`="a, b \"quoted\""。"#; - let bits = scan_prose_line(line); - let defaults: Vec<_> = bits - .iter() - .filter_map(|bit| match bit { - ProseBit::Decl { name, default, .. } => Some((name.as_str(), default.as_deref())), - _ => None, - }) - .collect(); - assert_eq!( - defaults, - vec![ - ("pattern", Some(r#""**""#)), - ("mime", Some(r#""text/plain;charset=utf-8""#)), - ("label", Some(r#""a, b \"quoted\"""#)) - ] - ); - } - - #[test] - fn soft_bold_emphasis_skipped() { - let bits = scan_prose_line("本文件既是**说明**也是**程序**。"); - assert!(bits.is_empty(), "{bits:?}"); - assert!(!looks_like_bold_code("说明")); - assert!(looks_like_bold_code("n=n+1")); - assert!(looks_like_bold_code("加一 37")); - } - - #[test] - fn soft_italic_emphasis_skipped() { - let bits = scan_prose_line("When soft=True, *only* FIND continues."); - assert!(bits.is_empty(), "{bits:?}"); - let bits = scan_prose_line("This is *very important* documentation."); - assert!(bits.is_empty(), "multi-word italic is emphasis: {bits:?}"); - let bits = scan_prose_line("See *foo.bar* in the text."); - assert!(bits.is_empty(), "dotted italic is emphasis: {bits:?}"); - let bits = scan_prose_line("Use *code-as-docs* style."); - assert!(bits.is_empty(), "hyphenated italic is emphasis: {bits:?}"); - let bits = scan_prose_line("*总额*"); - assert!( - matches!(&bits[..], [ProseBit::ItalicReturn { inner, .. }] if inner == "总额"), - "{bits:?}" - ); - let bits = scan_prose_line("接着返回*n*。"); - assert!( - matches!(&bits[..], [ProseBit::ItalicReturn { inner, .. }] if inner == "n"), - "{bits:?}" - ); - } - - #[test] - fn reject_n_plus_one_as_decl() { - let bits = scan_prose_line("输入`n+1`然后继续。"); - assert!(bits.is_empty(), "`` `n+1` `` must not Decl: {bits:?}"); - } - - #[test] - fn skip_glob_backticks_without_italic() { - let bits = scan_prose_line("from `OPENAI_*` / `MARQDO_LLM_*`."); - assert!( - bits.is_empty(), - "glob-like ticks must not yield italic: {bits:?}" - ); - } - - #[test] - fn narrative_links_skip_fence_and_classify() { - let src = "---\nmarkup: occlusion\n---\n\n# main\n\n见[文档](https://example.com/a)与[总额](总额)。\n\n```\n[ignored](https://x.test)\n```\n\n行内跳过 `[not](x)` 标记。\n"; - let links = scan_narrative_links(src); - assert!( - links.iter().any(|l| { - l.kind == NarrativeLinkKind::Navigation && l.target.contains("example.com") - }), - "{links:?}" - ); - assert!( - links - .iter() - .any(|l| l.kind == NarrativeLinkKind::Narrate && l.target == "总额"), - "{links:?}" - ); - assert!( - !links.iter().any(|l| l.target.contains("x.test")), - "fenced link must not become a step: {links:?}" - ); - assert!( - !links.iter().any(|l| l.target == "x"), - "inline-code link must not become a step: {links:?}" - ); - } -} diff --git a/src/project/mod.rs b/src/project/mod.rs deleted file mode 100755 index b648439..0000000 --- a/src/project/mod.rs +++ /dev/null @@ -1,249 +0,0 @@ -//! Project boundaries and deterministic source discovery. -//! -//! The executable-knowledge compiler must never let each consumer decide what -//! a project contains. This module establishes one filesystem boundary and a -//! stable, sorted list of Marqdo source files for `sema`, EKC, view, and MLSP. - -use std::fs; -use std::path::{Path, PathBuf}; - -use anyhow::{bail, Context, Result}; - -/// Canonical project boundary used by project-wide compilation. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ProjectRoot { - root: PathBuf, -} - -impl ProjectRoot { - /// Find the nearest explicit project marker or Git root. A standalone - /// source file without either marker forms a one-directory project. - pub fn discover(start: &Path) -> Result { - let start = if start.is_file() { - start.parent().unwrap_or_else(|| Path::new(".")) - } else { - start - }; - let start = start - .canonicalize() - .with_context(|| format!("resolve project start {}", start.display()))?; - let fallback = start.clone(); - let mut current = start.as_path(); - loop { - if current.join(".marqdo").join("project.toml").is_file() - || current.join(".git").exists() - { - return Ok(Self { - root: current.to_path_buf(), - }); - } - match current.parent() { - Some(parent) => current = parent, - None => { - return Ok(Self { root: fallback }); - } - } - } - } - - /// Construct an explicitly scoped project root. - pub fn new(root: &Path) -> Result { - let root = root - .canonicalize() - .with_context(|| format!("resolve project root {}", root.display()))?; - if !root.is_dir() { - bail!("project root {} is not a directory", root.display()); - } - Ok(Self { root }) - } - - pub fn path(&self) -> &Path { - &self.root - } - - /// Discover every project-local `.mq.md` file in lexicographic relative - /// path order. Generated and dependency directories are intentionally - /// excluded so a cache cannot silently become source knowledge. - pub fn source_files(&self) -> Result> { - let mut out = Vec::new(); - collect_sources(&self.root, &self.root, &mut out)?; - out.sort_by(|a, b| relative_key(&self.root, a).cmp(&relative_key(&self.root, b))); - Ok(out) - } -} - -/// Shared with EKC extract (M06): authored sources never include corpus/runtime bags. -pub const EXCLUDED_DIRS: &[&str] = &[ - ".git", - ".marqdo", - "target", - "node_modules", - ".cursor", - ".agents", - "data", - "docker", - "drafts", - "candidates", - "corpus", -]; - -/// True when a directory basename is outside the authored source scan. -pub fn is_excluded_dir_name(name: &str) -> bool { - EXCLUDED_DIRS.iter().any(|excluded| name == *excluded) -} - -/// Soft limits so discovery fails with a clear diagnosis instead of hanging (G12). -pub const MAX_SOURCE_DEPTH: u32 = 32; -pub const MAX_SOURCE_FILE_BYTES: u64 = 2 * 1024 * 1024; -pub const MAX_SOURCE_FILES: usize = 10_000; - -fn collect_sources(root: &Path, dir: &Path, out: &mut Vec) -> Result<()> { - collect_sources_at(root, dir, out, 0) -} - -fn collect_sources_at(root: &Path, dir: &Path, out: &mut Vec, depth: u32) -> Result<()> { - if depth > MAX_SOURCE_DEPTH { - bail!( - "project.scan_depth_exceeded: directory depth > {MAX_SOURCE_DEPTH} under {}", - dir.display() - ); - } - let mut entries: Vec<_> = fs::read_dir(dir) - .with_context(|| format!("read project directory {}", dir.display()))? - .collect::, _>>()?; - entries.sort_by_key(|entry| entry.file_name()); - - for entry in entries { - let path = entry.path(); - let file_type = entry.file_type()?; - if file_type.is_symlink() { - // A source symlink is only admitted if its resolved target remains - // within the project boundary. This prevents index escape. - let Ok(canonical) = path.canonicalize() else { - continue; - }; - if !canonical.starts_with(root) { - continue; - } - if canonical.is_dir() { - collect_sources_at(root, &canonical, out, depth + 1)?; - } else if is_mq_md(&canonical) { - push_source(out, &canonical)?; - } - continue; - } - if file_type.is_dir() { - let name = entry.file_name(); - if EXCLUDED_DIRS.iter().any(|excluded| name == *excluded) { - continue; - } - collect_sources_at(root, &path, out, depth + 1)?; - } else if file_type.is_file() && is_mq_md(&path) { - push_source(out, &path)?; - } - } - Ok(()) -} - -fn push_source(out: &mut Vec, path: &Path) -> Result<()> { - if out.len() >= MAX_SOURCE_FILES { - bail!( - "project.scan_count_exceeded: more than {MAX_SOURCE_FILES} `.mq.md` sources" - ); - } - let meta = fs::metadata(path) - .with_context(|| format!("stat {}", path.display()))?; - if meta.len() > MAX_SOURCE_FILE_BYTES { - bail!( - "project.scan_file_too_large: {} is {} bytes (max {MAX_SOURCE_FILE_BYTES})", - path.display(), - meta.len() - ); - } - out.push(path.to_path_buf()); - Ok(()) -} - -fn is_mq_md(path: &Path) -> bool { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.ends_with(".mq.md")) -} - -fn relative_key(root: &Path, path: &Path) -> String { - path.strip_prefix(root) - .unwrap_or(path) - .to_string_lossy() - .replace('\\', "/") -} - -#[cfg(test)] -mod tests { - use super::*; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn fixture_root(name: &str) -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let root = std::env::temp_dir().join(format!("marqdo-project-{name}-{nanos}")); - fs::create_dir_all(&root).unwrap(); - root - } - - #[test] - fn source_discovery_is_sorted_and_skips_generated_dirs() { - let root = fixture_root("sources"); - fs::create_dir_all(root.join("z")).unwrap(); - fs::create_dir_all(root.join("a")).unwrap(); - fs::create_dir_all(root.join("target")).unwrap(); - fs::write(root.join("z/b.mq.md"), "# z").unwrap(); - fs::write(root.join("a/a.mq.md"), "# a").unwrap(); - fs::write(root.join("target/ignored.mq.md"), "# ignored").unwrap(); - fs::write(root.join("README.md"), "not source").unwrap(); - - let project = ProjectRoot::new(&root).unwrap(); - let files = project.source_files().unwrap(); - let names: Vec<_> = files - .iter() - .map(|p| { - p.strip_prefix(&root) - .unwrap() - .to_string_lossy() - .replace('\\', "/") - }) - .collect(); - assert_eq!(names, ["a/a.mq.md", "z/b.mq.md"]); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn oversized_source_is_diagnosed() { - let root = fixture_root("too-large"); - let big = "x".repeat((MAX_SOURCE_FILE_BYTES as usize) + 8); - fs::write(root.join("big.mq.md"), format!("# main\n\n{big}\n")).unwrap(); - let project = ProjectRoot::new(&root).unwrap(); - let err = project.source_files().unwrap_err().to_string(); - assert!( - err.contains("project.scan_file_too_large"), - "expected size diagnostic, got {err}" - ); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn nearest_marker_wins() { - let root = fixture_root("discover"); - let nested = root.join("nested/work"); - fs::create_dir_all(nested.join(".marqdo")).unwrap(); - fs::write(nested.join(".marqdo/project.toml"), "id = \"nested\"").unwrap(); - fs::create_dir_all(nested.join("src")).unwrap(); - let file = nested.join("src/main.mq.md"); - fs::write(&file, "# main").unwrap(); - - let project = ProjectRoot::discover(&file).unwrap(); - assert_eq!(project.path(), nested.canonicalize().unwrap()); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/prove/cache.rs b/src/prove/cache.rs deleted file mode 100755 index 6570c04..0000000 --- a/src/prove/cache.rs +++ /dev/null @@ -1,245 +0,0 @@ -//! 证书缓存(设计 §8.3):复合键、命中跳判定、失效。 -//! -//! 键 = sha256(源码 ⊕ plan.json ⊕ schema ⊕ 库 sha256 ⊕ lean --version ⊕ marqdo 版本)。 -//! 证书落在产物目录(`.marqdo/prove//certificate.json`);键不合即失效。 - -use std::path::Path; - -use anyhow::Result; -use sha2::{Digest, Sha256}; - -use crate::prove::Verdict; - -pub const CERT_SCHEMA: u32 = 1; - -/// 单条定理的判定记录。 -#[derive(Debug, Clone, PartialEq)] -pub struct ClaimRecord { - pub id: String, - pub function: String, - pub status: Verdict, - pub source_line: Option, -} - -/// 一份判定证书(复核收据,不是发布许可)。 -#[derive(Debug, Clone)] -pub struct Certificate { - pub key: String, - pub status: Verdict, - pub tier: &'static str, - pub source_sha256: String, - pub library_sha256: String, - pub toolchain: String, - pub module_sha256: String, - pub claims: Vec, - /// lean 行 → mq 行。 - pub span_map: Vec<(u32, u32)>, - pub marqdo: String, -} - -/// 复合缓存键。 -pub fn cache_key( - source_sha256: &str, - plan_sha256: &str, - library_sha256: &str, - toolchain: &str, - marqdo_version: &str, -) -> String { - let mut hasher = Sha256::new(); - hasher.update(source_sha256.as_bytes()); - hasher.update(b"\x00"); - hasher.update(plan_sha256.as_bytes()); - hasher.update(b"\x00"); - hasher.update(library_sha256.as_bytes()); - hasher.update(b"\x00"); - hasher.update(toolchain.as_bytes()); - hasher.update(b"\x00"); - hasher.update(marqdo_version.as_bytes()); - hex(&hasher.finalize()) -} - -pub fn sha256_hex(data: &[u8]) -> String { - let mut hasher = Sha256::new(); - hasher.update(data); - hex(&hasher.finalize()) -} - -fn hex(bytes: &[u8]) -> String { - bytes.iter().map(|b| format!("{b:02x}")).collect() -} - -impl Certificate { - pub fn to_json(&self) -> serde_json::Value { - serde_json::json!({ - "schema": CERT_SCHEMA, - "key": self.key, - "status": self.status.as_str(), - "tier": self.tier, - "source_sha256": self.source_sha256, - "library_sha256": self.library_sha256, - "toolchain": self.toolchain, - "module_sha256": self.module_sha256, - "claims": self.claims.iter().map(|c| serde_json::json!({ - "id": c.id, - "function": c.function, - "status": c.status.as_str(), - "source_line": c.source_line, - })).collect::>(), - "span_map": self.span_map.iter().map(|(l, m)| serde_json::json!({ - "lean_line": l, "mq_line": m, - })).collect::>(), - "marqdo": self.marqdo, - }) - } - - fn from_json(value: &serde_json::Value) -> Option { - use serde_json::Value; - if value.get("schema")?.as_u64()? != CERT_SCHEMA as u64 { - return None; - } - let status = match value.get("status")?.as_str()? { - "proved" => Verdict::Proved, - "checked" => Verdict::Checked, - "unverified" => Verdict::Unverified, - "unproved" => Verdict::Unproved, - "rejected" => Verdict::Rejected, - "error" => Verdict::Error, - _ => return None, - }; - let parse_line = |v: &Value| v.as_u64().map(|n| n as u32); - Some(Certificate { - key: value.get("key")?.as_str()?.to_string(), - status, - tier: match value.get("tier")?.as_str()? { - "lean" => "lean", - "offline" => "offline", - _ => "none", - }, - source_sha256: value.get("source_sha256")?.as_str()?.to_string(), - library_sha256: value.get("library_sha256")?.as_str()?.to_string(), - toolchain: value.get("toolchain")?.as_str()?.to_string(), - module_sha256: value.get("module_sha256")?.as_str()?.to_string(), - claims: value - .get("claims")? - .as_array()? - .iter() - .map(|c| { - Some(ClaimRecord { - id: c.get("id")?.as_str()?.to_string(), - function: c.get("function")?.as_str()?.to_string(), - status: match c.get("status")?.as_str()? { - "proved" => Verdict::Proved, - "checked" => Verdict::Checked, - "unverified" => Verdict::Unverified, - "unproved" => Verdict::Unproved, - "rejected" => Verdict::Rejected, - "error" => Verdict::Error, - _ => return None, - }, - source_line: c.get("source_line").and_then(parse_line), - }) - }) - .collect::>>()?, - span_map: value - .get("span_map") - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|e| { - Some(( - e.get("lean_line")?.as_u64()? as u32, - e.get("mq_line")?.as_u64()? as u32, - )) - }) - .collect() - }) - .unwrap_or_default(), - marqdo: value.get("marqdo")?.as_str()?.to_string(), - }) - } -} - -/// 读证书:文件缺失/损坏/键不合 → None(调用方重判)。 -pub fn load(artifact_dir: &Path, key: &str) -> Option { - let path = artifact_dir.join("certificate.json"); - let raw = std::fs::read_to_string(path).ok()?; - let value: serde_json::Value = serde_json::from_str(&raw).ok()?; - let cert = Certificate::from_json(&value)?; - (cert.key == key).then_some(cert) -} - -/// 写证书(原子:临时文件 + 改名)。 -pub fn store(artifact_dir: &Path, cert: &Certificate) -> Result<()> { - std::fs::create_dir_all(artifact_dir)?; - let path = artifact_dir.join("certificate.json"); - let tmp = artifact_dir.join(".certificate.json.tmp"); - std::fs::write(&tmp, cert.to_json().to_string())?; - std::fs::rename(&tmp, &path)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cache_key_is_order_sensitive_and_stable() { - let a = cache_key("s", "p", "l", "lean 4", "2.8.0"); - let b = cache_key("s", "p", "l", "lean 4", "2.8.0"); - let c = cache_key("p", "s", "l", "lean 4", "2.8.0"); - assert_eq!(a, b); - assert_ne!(a, c); - } - - #[test] - fn certificate_roundtrip_preserves_verdicts() { - let cert = Certificate { - key: "k".into(), - status: Verdict::Unproved, - tier: "lean", - source_sha256: "s".into(), - library_sha256: "l".into(), - toolchain: "lean 4.35.0".into(), - module_sha256: "m".into(), - claims: vec![ClaimRecord { - id: "大额必经人工".into(), - function: "审批".into(), - status: Verdict::Unproved, - source_line: Some(21), - }], - span_map: vec![(41, 21)], - marqdo: "2.8.0".into(), - }; - let parsed = Certificate::from_json(&cert.to_json()).expect("roundtrip"); - assert_eq!(parsed.status, Verdict::Unproved); - assert_eq!(parsed.claims.len(), 1); - assert_eq!(parsed.claims[0].status, Verdict::Unproved); - assert_eq!(parsed.claims[0].source_line, Some(21)); - } - - #[test] - fn load_rejects_wrong_key_and_corrupt_file() { - let dir = std::env::temp_dir().join(format!("mq-cache-test-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - assert!(load(&dir, "k").is_none()); - let cert = Certificate { - key: "k1".into(), - status: Verdict::Proved, - tier: "lean", - source_sha256: "s".into(), - library_sha256: "l".into(), - toolchain: "t".into(), - module_sha256: "m".into(), - claims: vec![], - span_map: vec![], - marqdo: "2.8.0".into(), - }; - store(&dir, &cert).unwrap(); - assert!(load(&dir, "k1").is_some()); - assert!(load(&dir, "k2").is_none(), "键不合必须失效"); - std::fs::write(dir.join("certificate.json"), "{broken").unwrap(); - assert!(load(&dir, "k1").is_none(), "坏证书必须失效,不 panic"); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/src/prove/driver.rs b/src/prove/driver.rs deleted file mode 100755 index a2baa11..0000000 --- a/src/prove/driver.rs +++ /dev/null @@ -1,544 +0,0 @@ -//! Lean 驱动(设计 §8.4 / roadmap P1):工具链发现、语义底座构建、 -//! `lean` 调用(超时)、输出解析、`-- mq:` span 映射。 -//! -//! 与设计的偏差(§12 记录):驱动直接用 `lean -o` 构建 `MarqdoProof.olean`, -//! 不经 `lake`——运行时只依赖 `lean` 一个二进制,库源内嵌于本二进制 -//! (`include_str!`),按内容哈希落盘缓存;lakefile 仍保留给人/CI 使用。 - -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::time::{Duration, Instant}; - -use anyhow::{Context, Result}; - -use crate::prove::Verdict; - -/// 内嵌语义底座源(发布二进制自带;构建期校验见 scripts/check-proof-library.sh)。 -pub const LIBRARY_SRC: &str = include_str!("../../doc/verification/skill-proof/MarqdoProof.lean"); - -/// 单条定理的判定结果。 -#[derive(Debug, Clone)] -pub struct ClaimOutcome { - /// 定理名(生成文件里的 `«函数.定理id»`)。 - pub theorem: String, - /// 归属函数显示名。 - pub function: String, - /// 定理 id(定理表里的 id)。 - pub claim: String, - pub status: Verdict, - /// 映射回 `.mq.md` 的行号(定理表所在行附近;找不到为 None)。 - pub source_line: Option, - /// Lean 原始报错(unproved/lean-error 时)。 - pub detail: String, -} - -/// 一次模块级 Lean 判定。 -#[derive(Debug, Clone)] -pub struct LeanOutcome { - pub status: Verdict, - pub claims: Vec, - /// 原始 stdout+stderr(诊断证据)。 - pub log: String, - /// lean 行 → mq 行 的映射表(进证书)。 - pub span_map: Vec<(u32, u32)>, -} - -/// 已发现的工具链。 -#[derive(Debug, Clone)] -pub struct Toolchain { - pub lean: PathBuf, - pub version: String, -} - -impl Toolchain { - /// 发现顺序(§8.4):显式路径 → `MARQDO_PROOF_LEAN` → `PATH`。 - /// 显式给出但不可用 → Err(**不**回退:避免"以为在跑 Lean 其实没有")。 - pub fn discover(explicit: Option<&Path>) -> Result> { - if let Some(path) = explicit { - let t = Self::from_path(path) - .with_context(|| format!("proof.lean_missing:{}", path.display()))?; - return Ok(Some(t)); - } - if let Ok(env_path) = std::env::var("MARQDO_PROOF_LEAN") { - if !env_path.trim().is_empty() { - let t = Self::from_path(Path::new(&env_path)).with_context(|| { - format!("proof.lean_missing:MARQDO_PROOF_LEAN={env_path}") - })?; - return Ok(Some(t)); - } - } - for dir in std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) { - let candidate = dir.join("lean"); - if candidate.is_file() { - return Self::from_path(&candidate).map(Some); - } - } - Ok(None) - } - - fn from_path(path: &Path) -> Result { - let out = Command::new(path) - .arg("--version") - .output() - .with_context(|| format!("执行 {}", path.display()))?; - if !out.status.success() { - anyhow::bail!("{} --version 失败", path.display()); - } - let version = String::from_utf8_lossy(&out.stdout).trim().to_string(); - Ok(Toolchain { - lean: path.to_path_buf(), - version, - }) - } -} - -/// 语义底座目录(按内容哈希缓存),返回(目录,库 sha256)。 -pub fn ensure_library(cache_root: &Path, lean: &Toolchain) -> Result<(PathBuf, String)> { - let lib_sha = crate::prove::cache::sha256_hex(LIBRARY_SRC.as_bytes()); - let dir = cache_root.join(format!("library-{}", &lib_sha[..8])); - let src = dir.join("MarqdoProof.lean"); - let olean = dir.join("MarqdoProof.olean"); - if !olean.exists() { - std::fs::create_dir_all(&dir) - .with_context(|| format!("创建 {}", dir.display()))?; - std::fs::write(&src, LIBRARY_SRC) - .with_context(|| format!("写入 {}", src.display()))?; - let out = Command::new(&lean.lean) - .arg("-o") - .arg(&olean) - .arg(&src) - .output() - .with_context(|| format!("构建 MarqdoProof.olean"))?; - if !out.status.success() || !olean.exists() { - anyhow::bail!( - "MarqdoProof 库构建失败:\n{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - } - } - Ok((dir, lib_sha)) -} - -/// 判定一个生成的 Lean 模块。 -/// Compile a self-contained Lean module for a reusable, independent caller -/// proof. Source and output must both be inside the immutable build directory. -pub fn compile_import_module(lean:&Toolchain,src:&Path,olean:&Path, - import_root:&Path,timeout:Duration)->Result<()> { - let original=std::fs::read(src)?; - let mut command=Command::new(&lean.lean); - command.env("LEAN_PATH",import_root) - .arg("-o").arg(olean).arg(src); - let (log,status,timed_out)=run_with_timeout(&mut command,timeout)?; - anyhow::ensure!(!timed_out,"proof.compose_timeout: {}",src.display()); - anyhow::ensure!(status==Some(0)&&olean.is_file(), - "proof.compose_lean_failed: {log}"); - anyhow::ensure!(std::fs::read(src)?==original, - "proof.compose_source_race: generated Lean changed during verification"); - Ok(()) -} - -/// Re-check a generated, closed proof-obligation module with the Lean kernel. -/// No local JSON certificate or Rust-side decision may replace this check. -pub fn check_closed_goals( - toolchain:&Toolchain, source:&Path, timeout:Duration -)->Result<()>{ - let source_before=std::fs::read(source)?; - let mut command=Command::new(&toolchain.lean); - command.arg(source); - let (log,code,timed_out)=run_with_timeout(&mut command,timeout)?; - anyhow::ensure!(std::fs::read(source)?==source_before, - "proof.modular_source_race: Lean goal module changed during verification"); - anyhow::ensure!(!timed_out, - "proof.modular_timeout: Lean did not finish within {}s",timeout.as_secs()); - anyhow::ensure!(code==Some(0), - "proof.modular_unproved: Lean rejected callsite goals: {log}"); - Ok(()) -} - -pub fn check_module( - lean: &Toolchain, - lib_dir: &Path, - generated: &Path, - generated_src: &str, - timeout: Duration, - max_heartbeats: Option, -) -> Result { - let span_map = span_map_of(generated_src); - let mut cmd = Command::new(&lean.lean); - cmd.env("LEAN_PATH", lib_dir); - if let Some(hb) = max_heartbeats { - cmd.arg(format!("-DmaxHeartbeats={hb}")); - } - cmd.arg(generated); - let (log, code, timed_out) = run_with_timeout(&mut cmd, timeout)?; - if timed_out { - return Ok(LeanOutcome { - status: Verdict::Error, - claims: Vec::new(), - log: format!("timeout after {}s\n{log}", timeout.as_secs()), - span_map, - }); - } - - // 归因:错误行 → 所在定理;每条定理都给结论(无错 → proved / sorry → unverified)。 - let theorems = theorem_spans(generated_src); - let mut claims: Vec = Vec::new(); - let mut any_unproved = false; - let mut any_error = false; - for (line_no, kind, message) in parse_lean_errors(&log) { - let info = theorems - .iter() - .find(|t| line_no >= t.start && line_no <= t.end); - let (theorem, claim, source_line) = match info { - Some(t) => ( - t.name.clone(), - t.claim.clone(), - t.source_line.or_else(|| map_to_source(line_no, &span_map)), - ), - // 错误在函数体/模块级(如 def 编译失败):claim 留空,走整体 Error。 - None => ( - String::new(), - String::new(), - map_to_source(line_no, &span_map), - ), - }; - let function = if theorem.is_empty() { - String::new() - } else { - function_of_theorem(&theorem, &claim) - }; - let status = match kind { - ErrorKind::Unsolved => { - any_unproved = true; - Verdict::Unproved - } - ErrorKind::Other => { - any_error = true; - Verdict::Error - } - }; - claims.push(ClaimOutcome { - theorem, - function, - claim, - status, - source_line, - detail: message, - }); - } - - for t in &theorems { - if claims.iter().any(|c| c.theorem == t.name) { - continue; - } - let (status, detail) = if t.has_sorry { - ( - Verdict::Unverified, - "策略 none:定理生成但不证明".to_string(), - ) - } else { - (Verdict::Proved, String::new()) - }; - claims.push(ClaimOutcome { - theorem: t.name.clone(), - function: function_of_theorem(&t.name, &t.claim), - claim: t.claim.clone(), - status, - source_line: t.source_line, - detail, - }); - } - claims.sort_by(|a, b| a.theorem.cmp(&b.theorem)); - - let status = if any_error || code.map(|c| c != 0).unwrap_or(false) && !any_unproved { - // 解析到其它编译错误,或退出码非 0 且没有可归属的未证目标 → 判定层错误。 - Verdict::Error - } else if any_unproved { - Verdict::Unproved - } else { - Verdict::Proved - }; - Ok(LeanOutcome { - status, - claims, - log, - span_map, - }) -} - -#[derive(Debug, Clone, Copy, PartialEq)] -enum ErrorKind { - Unsolved, - Other, -} - -/// 带超时的进程运行(无外部依赖:spawn + try_wait 轮询)。 -fn run_with_timeout( - cmd: &mut Command, - timeout: Duration, -) -> Result<(String, Option, bool)> { - use std::io::Read; - let mut child = cmd - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .context("spawn lean")?; - let deadline = Instant::now() + timeout; - loop { - if let Some(status) = child.try_wait()? { - let mut stdout = Vec::new(); - let mut stderr = Vec::new(); - if let Some(mut s) = child.stdout.take() { - let _ = s.read_to_end(&mut stdout); - } - if let Some(mut s) = child.stderr.take() { - let _ = s.read_to_end(&mut stderr); - } - let mut log = String::from_utf8_lossy(&stdout).to_string(); - log.push_str(&String::from_utf8_lossy(&stderr)); - return Ok((log, Some(status.code().unwrap_or(-1)), false)); - } - if Instant::now() > deadline { - let _ = child.kill(); - let _ = child.wait(); - return Ok((String::new(), None, true)); - } - std::thread::sleep(Duration::from_millis(20)); - } -} - -/// 解析 lean 输出里的 `:LINE:COL: error…`;`unsolved goals` 单独归类。 -/// lean 的报错头独占一行(`Generated/x.lean:41:0: error: unsolved goals`), -/// 后随目标上下文行;这里只取头行。 -fn parse_lean_errors(log: &str) -> Vec<(u32, ErrorKind, String)> { - let mut out = Vec::new(); - for line in log.lines() { - // 头行形如 `:LINE:COL: error: ...`(COL 可能省略)。 - let Some(col_idx) = line.find(": error") else { - continue; - }; - let pos = &line[..col_idx]; - let message = line[col_idx..].trim_start_matches(": ").to_string(); - // pos 形如 `:LINE:COL`(COL 可省略);取**倒数第二个**数字段。 - let fields: Vec<&str> = pos.rsplit(':').collect(); - let line_no: u32 = if let Ok(col) = fields[0].parse::() { - fields.get(1).and_then(|s| s.parse().ok()).unwrap_or(col) - } else if let Ok(n) = fields[0].parse::() { - n - } else { - continue; - }; - let kind = if message.contains("unsolved goals") { - ErrorKind::Unsolved - } else { - ErrorKind::Other - }; - out.push((line_no, kind, message)); - } - out -} - -/// 生成文件里的一条定理。 -#[derive(Debug, Clone)] -pub struct TheoremInfo { - pub name: String, - pub start: u32, - pub end: u32, - /// 头注释里的定理 id:`-- 定理 (策略 …;mq: N)`。 - pub claim: String, - /// 头注释 `;mq: N` 的 N —— 定理表在 `.mq.md` 里的行。 - pub source_line: Option, - pub has_sorry: bool, -} - -/// 扫描生成文件:`-- 定理` 头注释 + `theorem` 行区间 + sorry 标记。 -pub fn theorem_spans(src: &str) -> Vec { - let lines: Vec<&str> = src.lines().collect(); - let mut out: Vec = Vec::new(); - // (name, start, claim, mq_line) - let mut current: Option<(String, u32, String, Option)> = None; - // 头注释暂存(claim id, mq 行)——紧随其后的 `theorem` 行使用。 - let mut pending: Option<(String, Option)> = None; - for (idx, line) in lines.iter().enumerate() { - let line_no = (idx + 1) as u32; - let trimmed = line.trim_start(); - if let Some(rest) = trimmed.strip_prefix("-- 定理 ") { - let head = rest.split('(').next().unwrap_or(rest).trim().to_string(); - let mq = rest - .rsplit_once("mq: ") - .and_then(|(_, n)| n.trim_end_matches(')').trim().parse().ok()); - pending = Some((head, mq)); - continue; - } - if let Some(rest) = trimmed.strip_prefix("theorem ") { - if let Some((name, start, claim, mq)) = current.take() { - out.push(theorem_info(src, name, start, line_no - 1, claim, mq)); - } - if let Some(name) = rest.split_whitespace().next() { - let (claim, mq) = pending.take().unwrap_or_default(); - current = Some((name.to_string(), line_no, claim, mq)); - } - } else if current.is_some() - && !trimmed.is_empty() - && !line.starts_with(' ') - && !line.starts_with('\t') - && !trimmed.starts_with("--") - { - let (name, start, claim, mq) = current.take().unwrap(); - out.push(theorem_info(src, name, start, line_no.saturating_sub(1), claim, mq)); - } - } - if let Some((name, start, claim, mq)) = current { - out.push(theorem_info(src, name, start, lines.len() as u32, claim, mq)); - } - out -} - -fn theorem_info( - src: &str, - name: String, - start: u32, - end: u32, - claim: String, - source_line: Option, -) -> TheoremInfo { - let has_sorry = src - .lines() - .skip(start.saturating_sub(1) as usize) - .take(end.saturating_sub(start) as usize + 1) - .any(|l| l.contains("sorry")); - TheoremInfo { - name, - start, - end, - claim, - source_line, - has_sorry, - } -} - -/// 定理名 → 归属函数:claim id 作后缀剥掉(函数名可含点,如 `台账.记录`)。 -fn function_of_theorem(theorem: &str, claim: &str) -> String { - let inner = theorem - .trim_start_matches('«') - .trim_end_matches('»') - .to_string(); - if !claim.is_empty() { - let suffix = format!(".{claim}"); - if let Some(f) = inner.strip_suffix(&suffix) { - return f.to_string(); - } - } - // 兜底:第一段(单段函数名)。 - inner - .split('.') - .next() - .unwrap_or(&inner) - .to_string() -} - -/// 生成文件的 `-- mq: LINE:COL` → (lean 行, mq 行)。 -pub fn span_map_of(src: &str) -> Vec<(u32, u32)> { - let mut out = Vec::new(); - for (idx, line) in src.lines().enumerate() { - let trimmed = line.trim_start(); - if let Some(rest) = trimmed.strip_prefix("-- mq: ") { - if let Some((l, _)) = rest.split_once(':') { - if let Ok(mq_line) = l.trim().parse::() { - out.push(((idx + 1) as u32, mq_line)); - } - } - } - } - out -} - -/// lean 行号 → 最近的 `-- mq:` 注释对应的源行。 -fn map_to_source(lean_line: u32, span_map: &[(u32, u32)]) -> Option { - span_map - .iter() - .filter(|(l, _)| *l <= lean_line) - .map(|(_, m)| *m) - .next_back() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_lean_errors_distinguishes_line_from_col() { - // `:47:62: error: …` — 行 47,列 62;曾把列当行导致定理错配。 - let log = "Generated/x.lean:47:62: error: unsolved goals\n «结果» = …\n"; - let errs = parse_lean_errors(log); - assert_eq!(errs.len(), 1); - assert_eq!(errs[0].0, 47, "必须取行号而非列号"); - assert_eq!(errs[0].1, ErrorKind::Unsolved); - - let log2 = "Generated/x.lean:12:5: error: unknown identifier «Foo»\n"; - let errs2 = parse_lean_errors(log2); - assert_eq!(errs2[0].0, 12); - assert_eq!(errs2[0].1, ErrorKind::Other); - } - - #[test] - fn theorem_spans_reads_header_comment_claim_and_line() { - let src = "\ --- mq: 14:1 -def «台账.记录» (env : Env) («金额» : Val) : Val × List Op := - («金额», []) --- 定理 记过即记(策略 none;mq: 10) -theorem «台账.记录.记过即记» (env : Env) («金额» : Val) : - True := by - trivial --- 定理 另一条(策略 auto;mq: 11) -theorem «台账.记录.另一条» (env : Env) : True := by - sorry -"; - let ts = theorem_spans(src); - assert_eq!(ts.len(), 2); - assert_eq!(ts[0].name, "«台账.记录.记过即记»"); - assert_eq!(ts[0].claim, "记过即记"); - assert_eq!(ts[0].source_line, Some(10)); - assert!(!ts[0].has_sorry); - assert_eq!(ts[1].claim, "另一条"); - assert_eq!(ts[1].source_line, Some(11)); - assert!(ts[1].has_sorry, "sorry 必须被识别为 unverified"); - } - - #[test] - fn function_of_theorem_strips_claim_suffix_not_first_segment() { - // 函数名可含点:台账.记录.记过即记 → 函数 = 台账.记录。 - assert_eq!( - function_of_theorem("«台账.记录.记过即记»", "记过即记"), - "台账.记录" - ); - assert_eq!( - function_of_theorem("«审批单.大额必经人工»", "大额必经人工"), - "审批单" - ); - assert_eq!(function_of_theorem("«孤定理»", ""), "孤定理"); - } - - #[test] - fn span_map_pairs_lean_and_mq_lines() { - let src = "-- mq: 14:1\nlet x := 1\n-- mq: 16:1\nlet y := 2\n"; - assert_eq!(span_map_of(src), vec![(1, 14), (3, 16)]); - } - - #[test] - fn map_to_source_finds_nearest_preceding_comment() { - let map = vec![(21, 14), (24, 16), (40, 33)]; - assert_eq!(map_to_source(21, &map), Some(14)); - assert_eq!(map_to_source(47, &map), Some(33)); - assert_eq!(map_to_source(1, &map), None); - } - - #[test] - fn toolchain_discovery_rejects_explicit_missing_path() { - let err = Toolchain::discover(Some(Path::new("/nonexistent/lean-绝无仅有"))) - .expect_err("显式坏路径必须报错(不回退)"); - assert!(format!("{err:#}").contains("proof.lean_missing")); - } -} diff --git a/src/prove/emit.rs b/src/prove/emit.rs deleted file mode 100755 index 1661af7..0000000 --- a/src/prove/emit.rs +++ /dev/null @@ -1,809 +0,0 @@ -//! Lean 生成(`doc/design/prove-cli.md` §4.1 ④ / §6)。 -//! -//! 确定性硬要求:同输入两次运行字节一致。做法:无时间戳、无绝对路径、 -//! 集合按首次出现顺序(降级本身确定)、映射键排序、浮点定长。 -//! -//! P0 形态:参数统一 `Val`(P1 起按契约提升为 `Int`/`String` 等以配合 -//! `structure Params` 与定理表);`result.ok/error` 内联为库构造器。 - -use std::collections::BTreeSet; -use std::fmt::Write as _; - -use crate::prove::ir::{ - BinOp, Expr as IrExpr, FnPlan, InterpPart, Plan, PlanTy, PureExpr, Step, UnOp, -}; - -/// 库名(verification/skill-proof 提供;P1 落地)。 -pub const LIBRARY_IMPORT: &str = "MarqdoProof"; - -/// 生成整个文件模块。返回 `(文件名, 内容)`。 -pub fn emit_module(plan: &Plan, module_stem: &str) -> (String, String) { - let namespace = namespace_of(module_stem); - let mut out = String::new(); - let _ = writeln!(out, "import {LIBRARY_IMPORT}"); - let _ = writeln!(out, "open MarqdoProof"); - // 机器生成的证明产物:关闭面向人写代码的 linter(未用变量/simp 参数是 - // 生成器的固定词汇表带来的正常噪声,不是问题)。 - let _ = writeln!(out, "set_option linter.unusedVariables false"); - let _ = writeln!(out, "set_option linter.unusedSimpArgs false"); - let _ = writeln!(out); - let _ = writeln!(out, "-- 由 `marqdo prove emit` 生成:确定性输出,请勿手改。"); - let _ = writeln!(out, "-- 源:{}(sha256 {})", plan.module, plan.source_sha256); - let _ = writeln!(out, "namespace Generated.{}", namespace); - let _ = writeln!(out); - - // 模块级 Op:所有函数的不透明操作并集(保持首次出现顺序,去重)。 - emit_op_inductive(&mut out, plan); - let _ = writeln!(out); - - for fun in &plan.functions { - emit_function(&mut out, fun); - let _ = writeln!(out); - emit_theorems(&mut out, fun); - let _ = writeln!(out); - } - - let _ = writeln!(out, "end Generated.{}", namespace); - let file_name = format!("{namespace}.lean"); - (file_name, out) -} - -/// 定理脚手架(§7.2):受限文法可解析的命题 → `theorem` 陈述 + `sorry` -/// 函数体里 if 的最大嵌套深度(0 = 无分支)。 -fn max_if_depth(steps: &[Step]) -> usize { - fn walk(steps: &[Step], depth: usize) -> usize { - let mut max = depth; - for s in steps { - if let Step::If { then, otherwise, .. } = s { - max = max.max(walk(then, depth + 1)); - max = max.max(walk(otherwise, depth + 1)); - } - } - max - } - walk(steps, 0) -} - -fn emit_theorems(out: &mut String, fun: &FnPlan) { - if fun.claims.is_empty() { - return; - } - let fun_name = lean_ident(&fun.name); - // 定理形参:`env` + 函数形参(Lean 标识符仅 ASCII,中文名入 guillemet)。 - // run 从空轨迹起跑(§2:轨迹是语法产物,函数入口为空)。 - let mut binders = String::from("(env : Env)"); - for param in &fun.params { - let _ = write!(binders, " ({} : Val)", lean_ident(¶m.name)); - } - let mut seen_theorem_names: BTreeSet = BTreeSet::new(); - for claim in &fun.claims { - let theorem_name = lean_ident(&format!("{}.{}", fun.name, claim.id)); - if !seen_theorem_names.insert(theorem_name.clone()) { - let _ = writeln!( - out, - "-- 定理 {} 重复(同 id 的定理只生成一次;check --proof 会给 proof.claim_duplicate)", - claim.id - ); - continue; - } - let premise_lean = claim - .premise - .as_deref() - .and_then(claim_to_lean_bool); - let conclusion_lean = claim_to_lean_bool(&claim.conclusion); - let premise_text = match (&claim.premise, premise_lean) { - (Some(_), Some(lean)) => format!(" («h_前提» : mqTruth {lean})"), - _ => String::new(), - }; - let tactic = claim.tactic.as_deref().unwrap_or("auto"); - let _ = writeln!(out, "-- 定理 {}(策略 {tactic};mq: {})", claim.id, claim.line); - match conclusion_lean { - Some(conclusion) => { - let run_args = fun - .params - .iter() - .map(|p| lean_ident(&p.name)) - .collect::>() - .join(" "); - let _ = writeln!(out, "theorem {theorem_name} {binders}{premise_text} :"); - let _ = writeln!(out, " ∀ («结果» : Val) («轨迹» : List Op),"); - // 等式方向:`(结果, 轨迹) = run …`(输出变量在左,simp_all 才能把 - // 输出值替换进目标;反向等式 simp 不会替换)。 - let _ = writeln!( - out, - " ((«结果», «轨迹») = {fun_name} env [] {run_args}) →" - ); - let _ = writeln!(out, " mqTruth {conclusion} := by"); - if tactic == "none" { - // 策略 none:定理生成但不证明(E4:状态 unverified, - // driver 依 sorry 判 unverified,绝不冒充 proved)。 - let _ = writeln!(out, " intro «结果» «轨迹» h_run"); - let _ = writeln!(out, " unfold {fun_name} at h_run"); - let _ = writeln!(out, " try split at h_run"); - let _ = writeln!(out, " all_goals"); - let _ = writeln!(out, " sorry"); - continue; - } - let _ = writeln!(out, " intro «结果» «轨迹» h_run"); - let _ = writeln!(out, " unfold {fun_name} at h_run"); - // 嵌套分支(else 里再嵌 if)需要逐层拆:按最大 if 深度发射 - // `try split at h_run`(拆无可拆时 try 吞掉,幂等)。 - for _ in 0..=max_if_depth(&fun.steps) { - let _ = writeln!(out, " try split at h_run"); - } - // 每个分支:simp_all(完整默认集处理 List.map/contains/length 的 - // 结构化消去;等式替换输出;Op.name 方程化简)+ 附加域定义 - // (mqAccess/mqResultOk/mqEq 字段与构造)。互斥比较假设由库中 - // @[simp] 矛盾引理消掉,剩余线性算术交给 omega。 - let _ = writeln!( - out, - " all_goals - simp_all [mqTruth, Op.name, mqAccess, mqResultOk, mqResultError, mqValueOr, mqAnd, mqOr, mqNot, mqEq] - try simp_all [mqAdd, mqSub, mqMul, mqNeg] - try - first - | exact (mqGt_mqLe_false ‹mqGt _ (Val.int _) = true› ‹mqLe _ (Val.int _) = true›).elim - | exact (mqLe_mqGt_false ‹mqLe _ (Val.int _) = true› ‹mqGt _ (Val.int _) = true›).elim - | exact (mqLt_mqGe_false ‹mqLt _ (Val.int _) = true› ‹mqGe _ (Val.int _) = true›).elim - | exact (mqGe_mqLt_false ‹mqGe _ (Val.int _) = true› ‹mqLt _ (Val.int _) = true›).elim - | omega" - ); - } - _ => { - let _ = writeln!( - out, - "-- 未生成:前提/结论超出受限文法(check --proof 会给具体诊断)" - ); - } - } - } -} - -/// 命名空间:文件名的安全标识符。Lean 4 的 `namespace` 命令**只接受 ASCII** -/// 名字(实测 `namespace 审批` 报 "expected token"),所以非 ASCII 字符 -/// 确定性编码为 `uXXXX`(码点十六进制),保证同名文件 → 同名空间。 -pub fn namespace_of(stem: &str) -> String { - let mut out = String::new(); - for ch in stem.chars() { - if ch.is_ascii_alphanumeric() || ch == '_' { - out.push(ch); - } else if !ch.is_ascii() { - out.push_str(&format!("u{:04X}", ch as u32)); - } else { - out.push('_'); - } - } - if out.is_empty() { - out.push('M'); - } - if out.chars().next().is_some_and(|c| c.is_ascii_digit()) { - out.insert(0, 'M'); - } - out -} - -/// Lean 保留字(`def 审批` 这类裸中文名在 Lean 里是语法错误—— -/// 标识符仅 ASCII;非 ASCII 名一律进 guillemet `«…»`)。 -const LEAN_KEYWORDS: &[&str] = &[ - "fun", "let", "in", "do", "match", "with", "if", "then", "else", "true", "false", "and", "or", - "not", "def", "theorem", "abbrev", "structure", "inductive", "where", "deriving", "open", - "namespace", "end", "import", "by", "have", "show", "assume", "from", "at", "exists", -]; - -pub(crate) fn lean_ident(name: &str) -> String { - let ascii_safe = !name.is_empty() - && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') - && !name.chars().next().is_some_and(|c| c.is_ascii_digit()); - if LEAN_KEYWORDS.contains(&name) || name == "env" { - // 关键字与本模块保留名(函数体里用户变量撞名时改名)。 - // 改名形式必须纯 ASCII(裸 `v_结果` 仍是 Lean 语法错误)。 - format!("v_{}", namespace_of(name)) - } else if name == "轨迹" || name == "结果" || name == "h_前提" { - // 定理作用域保留名:函数体里的用户变量/形参撞名 → v_ 前缀 - // (定理的 ∀ 绑定名由 emit_theorems/claim_term 直接写 `«…»`,不走这里)。 - format!("v_{}", namespace_of(name)) - } else if ascii_safe { - name.to_string() - } else { - // 中文名/含点/含特殊字符 → guillemet;`:` 会截断记号,替换为 `_`。 - format!("«{}»", name.replace(':', "_")) - } -} - -fn op_ctor(op_id: &str) -> String { - // `调用:人工审核` → `«调用_人工审核»`(guillemet 标识符)。 - // Lean 的 guillemet 记号不接受 `:`(会截断记号),标识符里替换为 `_`; - // Op.name 的**字符串显示**保持原始 id,轨迹名不变。 - let safe = op_id.replace(':', "_"); - format!("«{safe}»") -} - -fn emit_op_inductive(out: &mut String, plan: &Plan) { - // 收集 op(首现顺序去重)。 - let mut ops: Vec<&crate::prove::ir::OpDecl> = Vec::new(); - for fun in &plan.functions { - for op in &fun.ops { - if !ops.iter().any(|o| o.id == op.id) { - ops.push(op); - } - } - } - if ops.is_empty() { - let _ = writeln!(out, "inductive Op where"); - // 占位构造器也走 op_ctor(裸中文构造器是 Lean 语法错误)。 - let _ = writeln!(out, " | {} deriving Repr, BEq", op_ctor("无操作")); - let _ = writeln!(out); - let _ = writeln!(out, "def Op.name : Op → String"); - let _ = writeln!(out, " | .{} => \"\"", op_ctor("无操作")); - return; - } - let _ = writeln!(out, "inductive Op where"); - for op in &ops { - let fields = match op.arity { - 0 => String::new(), - n => (1..=n) - .map(|i| format!("(«参数{i}» : Val)")) - .collect::>() - .join(" "), - }; - let _ = writeln!(out, " | {} {}", op_ctor(&op.id), fields); - } - let _ = writeln!(out, " deriving Repr, BEq"); - let _ = writeln!(out); - let _ = writeln!(out, "def Op.name : Op → String"); - for op in &ops { - let label = op.id.strip_prefix("调用:").unwrap_or(&op.id); - // 多参构造器的模式必须绑定实参(`_ _`),否则类型不匹配。 - let blanks = " _".repeat(op.arity); - let _ = writeln!(out, " | .{} {}=> \"{}\"", op_ctor(&op.id), blanks, label); - } - let _ = writeln!(out); - // Env 依赖本文件的 Op(库无法预知),所以每文件自带: - // `env` 是"不透明操作 → 返回值"的任意函数——后置条件对一切 env 成立。 - let _ = writeln!(out, "abbrev Env := Op → Val"); -} - -fn emit_function(out: &mut String, fun: &FnPlan) { - let name = lean_ident(&fun.name); - // 参数列表:`def f (env : Env) (轨迹 : List Op) (p1 : Val) …` - let mut sig = String::from("(env : Env) («轨迹» : List Op)"); - for param in &fun.params { - let _ = write!(sig, " ({} : Val)", lean_ident(¶m.name)); - } - let _ = writeln!(out, "-- {} 返回 {}", fun.name, fun.result_ty.name()); - let _ = writeln!(out, "def {name} {sig} : Val × List Op :="); - if fun.steps.is_empty() { - let _ = writeln!(out, " (Val.none, «轨迹»)"); - return; - } - emit_seq(out, &mut String::from(" "), &[&fun.steps]); -} - -/// 续延式直接降级(§6.3):`chunks` 是"当前点之后还要执行的所有步骤"。 -/// -/// `if` 的两臂续延是「臂内步骤 + 臂外剩余」——执行继续到分支之后, -/// 除非某臂已提前 `Return`。这是 P0 第一版的续延丢失 bug 的修正: -/// 分支绝不能吞掉后续语句。 -fn emit_seq(out: &mut String, indent: &mut String, chunks: &[&[Step]]) { - match chunks.split_first() { - None => { - // 走到末尾都没有 return:Marqdo 返回 None(诚实占位,不译运行时)。 - let _ = writeln!(out, "{indent}(Val.none, «轨迹»)"); - } - Some((first, rest)) => match first.split_first() { - None => emit_seq(out, indent, rest), - Some((step, more)) => emit_step(out, indent, step, more, rest), - }, - } -} - -fn tail_chunks<'a>(more: &'a [Step], rest: &[&'a [Step]]) -> Vec<&'a [Step]> { - let mut next: Vec<&'a [Step]> = Vec::with_capacity(rest.len() + 1); - if !more.is_empty() { - next.push(more); - } - next.extend_from_slice(rest); - next -} - -fn emit_step(out: &mut String, indent: &mut String, step: &Step, more: &[Step], rest: &[&[Step]]) { - match step { - Step::Bind { var, expr, line } => { - let _ = writeln!(out, "{indent}-- mq: {line}:1"); - match expr { - IrExpr::Op { id, args } => { - let _ = writeln!( - out, - "{indent}let {} := env (Op.{} {})", - lean_ident(var), - op_ctor(id), - emit_args(args) - ); - let _ = writeln!( - out, - "{indent}let «轨迹» := «轨迹» ++ [Op.{} {}]", - op_ctor(id), - emit_args(args) - ); - } - other => { - let _ = writeln!( - out, - "{indent}let {} := {}", - lean_ident(var), - emit_expr(other) - ); - } - } - emit_seq(out, indent, &tail_chunks(more, rest)); - } - Step::Return { expr, line } => { - let _ = writeln!(out, "{indent}-- mq: {line}:1"); - match expr { - IrExpr::Op { id, args } => { - let _ = writeln!( - out, - "{indent}(env (Op.{} {}), «轨迹» ++ [Op.{} {}])", - op_ctor(id), - emit_args(args), - op_ctor(id), - emit_args(args) - ); - } - other => { - let _ = writeln!(out, "{indent}({}, «轨迹»)", emit_expr(other)); - } - } - } - Step::Trace { op, args, line } => { - let _ = writeln!(out, "{indent}-- mq: {line}:1"); - let _ = writeln!( - out, - "{indent}let «轨迹» := «轨迹» ++ [Op.{} {}]", - op_ctor(op), - emit_args(args) - ); - emit_seq(out, indent, &tail_chunks(more, rest)); - } - Step::If { - cond, - then, - otherwise, - line, - } => { - let _ = writeln!(out, "{indent}-- mq: {line}:1"); - let _ = writeln!(out, "{indent}if {} then", emit_cond(cond)); - indent.push_str(" "); - let then_chunks = { - let mut v: Vec<&[Step]> = Vec::with_capacity(rest.len() + 1); - v.push(then); - v.extend_from_slice(&tail_chunks(more, rest)); - v - }; - emit_seq(out, indent, &then_chunks); - indent.truncate(indent.len() - 2); - let _ = writeln!(out, "{indent}else"); - indent.push_str(" "); - let else_chunks = { - let mut v: Vec<&[Step]> = Vec::with_capacity(rest.len() + 1); - v.push(otherwise); - v.extend_from_slice(&tail_chunks(more, rest)); - v - }; - emit_seq(out, indent, &else_chunks); - indent.truncate(indent.len() - 2); - } - } -} - -/// 条件:比较直接产出 Bool;其余经 `mqTruth`(Val → Bool)。 -fn emit_cond(cond: &PureExpr) -> String { - match cond { - PureExpr::Bin { - operator: BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge, - .. - } => emit_pure(cond), - _ => format!("mqTruth ({})", emit_pure(cond)), - } -} - -fn emit_args(args: &[PureExpr]) -> String { - args.iter() - .map(|a| emit_pure(a)) - .collect::>() - .join(" ") -} - -fn emit_expr(expr: &IrExpr) -> String { - match expr { - IrExpr::Pure(pure) => emit_pure(pure), - // 语句层不会遇到(Op 已在 Bind/Return/Trace 处理);防御性回退。 - IrExpr::Op { id, args } => { - format!("env (Op.{} {})", op_ctor(id), emit_args(args)) - } - IrExpr::Formula => "Val.none -- $$公式$$:不透明值".into(), - IrExpr::Code => "Val.none -- code 围栏:不透明值".into(), - } -} - -fn emit_pure(pure: &PureExpr) -> String { - match pure { - PureExpr::Int(i) => format!("(Val.int {i})"), - PureExpr::Num(n) => format!("(Val.num {n:?})"), - PureExpr::Bool(b) => format!("(Val.bool {})", if *b { "true" } else { "false" }), - PureExpr::Text(s) => format!("(Val.text {})", lean_string(s)), - PureExpr::None => "Val.none".into(), - PureExpr::Var(name) => lean_ident(name), - PureExpr::Bin { operator, left, right } => { - let (l, r) = (emit_pure(left), emit_pure(right)); - match operator { - BinOp::Add => format!("(mqAdd {l} {r})"), - BinOp::Sub => format!("(mqSub {l} {r})"), - BinOp::Mul => format!("(mqMul {l} {r})"), - BinOp::Div => format!("(mqDiv {l} {r})"), - BinOp::Eq => format!("(mqEq {l} {r})"), - BinOp::Ne => format!("(mqNot (mqEq {l} {r}))"), - BinOp::Lt => format!("(mqLt {l} {r})"), - BinOp::Le => format!("(mqLe {l} {r})"), - BinOp::Gt => format!("(mqGt {l} {r})"), - BinOp::Ge => format!("(mqGe {l} {r})"), - BinOp::And => format!("(mqAnd {l} {r})"), - BinOp::Or => format!("(mqOr {l} {r})"), - } - } - PureExpr::Un { operator, expr } => { - let e = emit_pure(expr); - match operator { - UnOp::Not => format!("(mqNot {e})"), - UnOp::Neg => format!("(mqNeg {e})"), - } - } - PureExpr::Index { base, key } => { - format!("(mqAccess {} {})", emit_pure(base), lean_string(key)) - } - PureExpr::Access { base, key } => { - format!("(mqAccess {} {})", emit_pure(base), lean_string(key)) - } - PureExpr::Len(inner) => format!("(mqLen {})", emit_pure(inner)), - PureExpr::Interp(parts) => emit_interp(parts), - PureExpr::List(items) => { - let inner: Vec = items.iter().map(emit_pure).collect(); - format!("(Val.list [{}])", inner.join(", ")) - } - PureExpr::Map(entries) => { - let inner: Vec = entries - .iter() - .map(|(k, v)| format!("({}, {})", lean_string(k), emit_pure(v))) - .collect(); - format!("(Val.map [{}])", inner.join(", ")) - } - PureExpr::Ctor { name, args } => emit_ctor(name, args), - } -} - -/// 内联构造器:`result.ok/error/value_or` 映射到库辅助函数 -/// (Val 字面 map,与 lib/result 行为一致);`mq.*` 直呼。 -fn emit_ctor(name: &str, args: &[PureExpr]) -> String { - let rendered: Vec = args.iter().map(emit_pure).collect(); - match (name, rendered.as_slice()) { - ("result.ok", [value]) => format!("(mqResultOk {value})"), - ("result.error", [code, message, operation]) => { - format!("(mqResultError {code} {message} {operation})") - } - ("result.value_or", [r, default]) => format!("(mqValueOr {r} {default})"), - _ => format!("({} {})", name.replace('.', "_"), rendered.join(" ")), - } -} - -fn emit_interp(parts: &[InterpPart]) -> String { - let mut pieces: Vec = Vec::new(); - for part in parts { - match part { - InterpPart::Lit(text) => pieces.push(format!("(Val.text {})", lean_string(text))), - InterpPart::Var(name) => pieces.push(lean_ident(name)), - } - } - if pieces.is_empty() { - return "(Val.text \"\")".into(); - } - let mut it = pieces.into_iter(); - let first = it.next().unwrap(); - it.fold(first, |acc, piece| format!("(mqAppend {acc} {piece})")) -} - -/// Lean 字符串字面量(转义 `\` `"` 与控制字符;非 ASCII 原样保留)。 -fn lean_string(s: &str) -> String { - let mut out = String::with_capacity(s.len() + 2); - out.push('"'); - for ch in s.chars() { - match ch { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\t' => out.push_str("\\t"), - '\r' => out.push_str("\\r"), - c => out.push(c), - } - } - out.push('"'); - out -} - -/// 模块 stem(命名空间用):去扩展名的文件名。 -pub fn stem_of(path: &str) -> String { - std::path::Path::new(path) - .file_stem() - .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_else(|| "Module".into()) -} - -/// PlanTy 的 Lean 侧提示注释(P1 提升类型用;P0 参数统一 Val)。 -pub fn ty_hint(ty: &PlanTy) -> &'static str { - match ty { - PlanTy::Int => "Int", - PlanTy::Num => "Float", - PlanTy::Bool => "Bool", - PlanTy::Text => "String", - _ => "Val", - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::prove::ir::{Expr, FnPlan, OpDecl, PlanTy, Step}; - - #[test] - fn lean_ident_keeps_chinese_and_quotes_dotted() { - // Lean 标识符仅 ASCII:中文名入 guillemet。 - assert_eq!(lean_ident("金额"), "«金额»"); - assert_eq!(lean_ident("审批台.审批"), "«审批台.审批»"); - // 纯 ASCII 名保持裸写。 - assert_eq!(lean_ident("x_1"), "x_1"); - // 与本模块保留名冲突的变量必须改名(确定性映射)。 - assert_eq!(lean_ident("env"), "v_env"); - assert_eq!(lean_ident("轨迹"), "v_u8F68u8FF9"); - assert_eq!(lean_ident("结果"), "v_u7ED3u679C"); - assert_eq!(lean_ident("let"), "v_let"); - } - - #[test] - fn lean_string_escapes_quotes_and_newline_only() { - assert_eq!(lean_string("a\"b\\c"), "\"a\\\"b\\\\c\""); - assert_eq!(lean_string("行\n进"), "\"行\\n进\""); - assert_eq!(lean_string("中文"), "\"中文\""); - } - - #[test] - fn namespace_sanitizes_unsafe_chars_deterministically() { - assert_eq!(namespace_of("approval.mq"), "approval_mq"); - assert_eq!(namespace_of("示例"), "u793Au4F8B"); - // 命名空间绝不含非 ASCII(Lean namespace 命令只收 ASCII)。 - assert_eq!(namespace_of("1abc"), "M1abc"); - assert_eq!(namespace_of(""), "M"); - } - - #[test] - fn emit_module_is_deterministic_and_sorted_by_first_appearance() { - let plan = Plan { - schema: crate::prove::ir::SCHEMA, - module: "demo.mq.md".into(), - source_sha256: "ab".repeat(32), - functions: vec![ - FnPlan { - name: "机器.运转".into(), - params: vec![], - result_ty: PlanTy::Any, - ops: vec![ - OpDecl { - id: "调用:写盘".into(), - effect: "fs.write".into(), - params: vec![], - arity: 1, - }, - OpDecl { - id: "调用:读盘".into(), - effect: "fs.read".into(), - params: vec![], - arity: 0, - }, - ], - steps: vec![Step::Bind { - var: "回执".into(), - expr: Expr::Op { - id: "调用:写盘".into(), - args: vec![], - }, - line: 3, - }], - effects: vec!["fs.write".into()], - claims: vec![], - assumptions: vec![], - }, - FnPlan { - name: "从机.待机".into(), - params: vec![], - result_ty: PlanTy::Any, - ops: vec![], - steps: vec![Step::Return { - expr: Expr::Pure(PureExpr::Int(7)), - line: 9, - }], - effects: vec![], - claims: vec![], - assumptions: vec![], - }, - ], - }; - let (name1, out1) = emit_module(&plan, "demo"); - let (name2, out2) = emit_module(&plan, "demo"); - assert_eq!(name1, name2); - assert_eq!(out1, out2, "两次生成必须字节一致"); - assert!(out1.contains("import MarqdoProof")); - assert!(out1.contains("namespace Generated.demo")); - // Op 按首现顺序:写盘在读盘前。 - let write_pos = out1.find("«调用_写盘»").expect("write op"); - let read_pos = out1.find("«调用_读盘»").expect("read op"); - assert!(write_pos < read_pos); - // Op 元数:读盘 0 元 → 无参构造器。 - assert!(out1.contains("| «调用_读盘»"), "{out1}"); - // Return 直译成对(字面量自带括号,形成双重括号——合法 Lean)。 - assert!(out1.contains("((Val.int 7), «轨迹»)"), "{out1}"); - // 溯源注释。 - assert!(out1.contains("-- mq: 3:1")); - // 无时间戳。 - assert!(!out1.contains("20") || !out1.contains("T"), "no timestamps"); - } - - #[test] - fn empty_plan_emits_no_op_ctors() { - let plan = Plan { - schema: crate::prove::ir::SCHEMA, - module: "空.mq.md".into(), - source_sha256: "cd".repeat(32), - functions: vec![], - }; - let (name, out) = emit_module(&plan, "空"); - assert_eq!(name, "u7A7A.lean"); - // 占位构造器同样 guillemet 化(裸中文构造器是 Lean 语法错误)。 - assert!(out.contains("| «无操作»")); - assert!(!out.contains("«调用:")); - } -} - - -/// 受限命题文本 → Lean Bool 项;解析失败或含未知形状 → None(emit 侧留注释)。 -/// 语义映射(§7.2): -/// - `结果.ok / 结果.value / 结果.error` → `mqAccess 结果 "ok"` 等; -/// - `包含(轨迹, s)` → `(轨迹.map Op.name).contains s`; -/// - `长度(轨迹)` → `(轨迹.length : Nat)`,与整数比较走 Nat 运算; -/// - 形参/算术/比较 → mq 辅助函数(Val 面)。 -fn claim_to_lean_bool(text: &str) -> Option { - let toks = super::proof_check::tokenize_claim(text).ok()?; - let (_, ast) = super::proof_check::parse_claim_expr(&toks).ok()?; - claim_term(&ast) -} - -/// `长度(轨迹)`:Nat 语境的锚点(轨迹长度与整数比较必须走 Nat 运算, -/// 否则 `mqEq : Val → Val → Bool` 类型不匹配)。 -fn is_trace_len(ast: &super::proof_check::ClaimAst) -> bool { - matches!( - ast, - super::proof_check::ClaimAst::Call { name, args } - if name == "长度" - && matches!(args.first(), Some(super::proof_check::ClaimAst::Var(v)) if v == "轨迹") - ) -} - -fn claim_term(ast: &super::proof_check::ClaimAst) -> Option { - use super::proof_check::{ClaimAst as A, CTok}; - match ast { - A::Lit(CTok::Int(i)) => Some(format!("(Val.int {i})")), - A::Lit(CTok::Num(n)) => Some(format!("(Val.num {n:?})")), - A::Lit(CTok::Bool(b)) => Some(format!("(Val.bool {b})")), - A::Lit(CTok::Text(s)) => Some(format!("(Val.text {})", lean_string(s))), - A::Lit(_) => None, - A::Var(name) => { - // 定理作用域里 `结果`/`轨迹` 是 ∀ 绑定的输出名(`«结果»`/`«轨迹»`, - // 不加 v_ 前缀);`根.字段` → mqAccess 字段读取;其余按标识符规则。 - let (root, field) = match name.split_once('.') { - Some((r, f)) => (r, Some(f)), - None => (name.as_str(), None), - }; - let term = match (root, field) { - ("结果", Some(f)) => format!("(mqAccess «结果» {})", lean_string(f)), - ("轨迹", Some(f)) => format!("(mqAccess «轨迹» {})", lean_string(f)), - ("结果", None) => "«结果»".to_string(), - ("轨迹", None) => "«轨迹»".to_string(), - _ => lean_ident(name), - }; - Some(term) - } - A::Call { name, args } => { - // `轨迹`(定理作用域的输出轨迹)上的谓词有专用 Lean 形式。 - let on_trace = matches!(args.first(), Some(A::Var(v)) if v == "轨迹"); - match (name.as_str(), args.len(), on_trace) { - ("包含", 2, true) => { - let item = strip_val_text(&claim_term(&args[1])?); - Some(format!("((«轨迹».map Op.name).contains {item})")) - } - ("长度", 1, true) => Some("(«轨迹».length : Nat)".to_string()), - _ => { - let mut rendered = Vec::with_capacity(args.len()); - for arg in args { - rendered.push(claim_term(arg)?); - } - let term = match (name.as_str(), rendered.as_slice()) { - ("包含", [list, item]) => format!("(mqContains {list} {item})"), - ("长度", [list]) => format!("(mqNatOf (mqLen {list}))"), - ("下标", [list, index]) => { - format!("(mqAccess {list} (mqStrOfNat {index}))") - } - _ => format!("({} {})", name, rendered.join(" ")), - }; - Some(term) - } - } - } - A::Bin { op, left, right } => { - // Nat 语境:操作数是 `长度(轨迹)` 或整数字面量 → 原生 Nat 运算。 - if is_trace_len(left) || is_trace_len(right) { - let nat = |a: &A| -> Option { - if is_trace_len(a) { - Some("(«轨迹».length : Nat)".to_string()) - } else if let A::Lit(CTok::Int(i)) = a { - Some(i.to_string()) - } else { - None - } - }; - let (l, r) = (nat(left)?, nat(right)?); - return match *op { - "=" => Some(format!("({l} = {r})")), - "≠" => Some(format!("({l} ≠ {r})")), - "<" => Some(format!("({l} < {r})")), - "≤" => Some(format!("({l} ≤ {r})")), - ">" => Some(format!("({l} > {r})")), - "≥" => Some(format!("({l} ≥ {r})")), - "+" => Some(format!("({l} + {r})")), - "-" => Some(format!("({l} - {r})")), - _ => None, - }; - } - let (l, r) = (claim_term(left)?, claim_term(right)?); - let term = match *op { - "+" => format!("(mqAdd {l} {r})"), - "-" => format!("(mqSub {l} {r})"), - "*" => format!("(mqMul {l} {r})"), - "/" => format!("(mqDiv {l} {r})"), - "=" => format!("(mqEq {l} {r})"), - "≠" => format!("(mqNot (mqEq {l} {r}))"), - "<" => format!("(mqLt {l} {r})"), - "≤" => format!("(mqLe {l} {r})"), - ">" => format!("(mqGt {l} {r})"), - "≥" => format!("(mqGe {l} {r})"), - "且" => format!("(mqAnd {l} {r})"), - "或" => format!("(mqOr {l} {r})"), - _ => return None, - }; - Some(term) - } - A::Un { op, expr } => { - let e = claim_term(expr)?; - let term = match *op { - "非" => format!("(mqNot {e})"), - "-" => format!("(mqNeg {e})"), - _ => return None, - }; - Some(term) - } - } -} - -/// `包含` 的成员是文本字面量时剥掉 Val 包裹(`(Val.text "x")` → `"x"`)。 -fn strip_val_text(term: &str) -> String { - term.strip_prefix("(Val.text ") - .and_then(|rest| rest.strip_suffix(')')) - .map(|s| s.to_string()) - .unwrap_or_else(|| term.to_string()) -} diff --git a/src/prove/ir.rs b/src/prove/ir.rs deleted file mode 100755 index 75e3616..0000000 --- a/src/prove/ir.rs +++ /dev/null @@ -1,296 +0,0 @@ -//! Plan IR(`doc/design/prove-cli.md` §4.2)。 -//! -//! `plan.json` 的形状:版本化、可序列化、无时间戳。缓存键与论文工具都以 -//! 它为输入。表达式分两层:[`PureExpr`] 是可翻译成 Lean 项的纯片段; -//! 其余调用一律是不透明操作([`Step::Trace`] 引用 [`FnPlan::ops`])。 - -use serde::Serialize; - -/// IR schema version(缓存失效用;形状变化必须 +1)。 -pub const SCHEMA: u32 = 1; - -/// 契约类型在 Plan IR 里的形状(`contract::Ty` 的可序列化投影)。 -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum PlanTy { - Int, - Num, - Bool, - Text, - List, - Map, - /// 内联 `Result` 构造器(`lib/result`):`ok/value/error` 三字段结构。 - Result, - /// 未知/任意(`--no-strict-types` 或未标注)。定理只能做等式判断。 - Any, - /// `# 对象` 类型实例。 - Object(String), -} - -impl PlanTy { - pub fn name(&self) -> String { - match self { - PlanTy::Int => "int".into(), - PlanTy::Num => "num".into(), - PlanTy::Bool => "bool".into(), - PlanTy::Text => "text".into(), - PlanTy::List => "list".into(), - PlanTy::Map => "map".into(), - PlanTy::Result => "result".into(), - PlanTy::Any => "any".into(), - PlanTy::Object(n) => n.clone(), - } - } - - pub fn from_contract(ty: &crate::contract::Ty) -> PlanTy { - match ty { - crate::contract::Ty::Any => PlanTy::Any, - crate::contract::Ty::Text => PlanTy::Text, - crate::contract::Ty::Number => PlanTy::Int, - crate::contract::Ty::Bool => PlanTy::Bool, - crate::contract::Ty::List => PlanTy::List, - crate::contract::Ty::Map => PlanTy::Map, - crate::contract::Ty::Object(n) => PlanTy::Object(n.clone()), - } - } -} - -/// 二元运算(纯片段内的算术/比较/布尔)。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum BinOp { - Add, - Sub, - Mul, - Div, - Eq, - Ne, - Lt, - Le, - Gt, - Ge, - And, - Or, -} - -impl BinOp { - pub fn from_ast(op: crate::ast::BinaryOp) -> BinOp { - use crate::ast::BinaryOp as A; - match op { - A::Add => BinOp::Add, - A::Sub => BinOp::Sub, - A::Mul => BinOp::Mul, - A::Div => BinOp::Div, - A::Eq => BinOp::Eq, - A::Ne => BinOp::Ne, - A::Lt => BinOp::Lt, - A::Le => BinOp::Le, - A::Gt => BinOp::Gt, - A::Ge => BinOp::Ge, - A::And => BinOp::And, - A::Or => BinOp::Or, - } - } -} - -/// 一元运算。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum UnOp { - Not, - Neg, -} - -/// 纯表达式:可翻译成 Lean 项的部分(§4.2 表达式分层)。 -/// 相邻标记(`kind` + `value`):新类型变体也能稳定序列化。 -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(tag = "kind", content = "value", rename_all = "snake_case")] -pub enum PureExpr { - Int(i64), - Num(f64), - Bool(bool), - Text(String), - None, - Var(String), - Bin { - operator: BinOp, - left: Box, - right: Box, - }, - Un { - operator: UnOp, - expr: Box, - }, - /// 映射字段/下标读取:`` [键](映射) `` / `` `m`[^键] ``。 - Index { - base: Box, - key: String, - }, - /// `access(base, key)`(含 `取`/`取值` 别名)。 - Access { - base: Box, - key: String, - }, - /// `len(value)`(含 `长度` 别名)。 - Len(Box), - /// 文本插值拼接(`` "共 `n` 条" `` → append 序列)。 - Interp(Vec), - List(Vec), - Map(Vec<(String, PureExpr)>), - /// 已内联的构造器调用(`result.success/failure`)。 - Ctor { - name: String, - args: Vec, - }, -} - -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(tag = "part", content = "value", rename_all = "snake_case")] -pub enum InterpPart { - Lit(String), - Var(String), -} - -/// 语句(§4.3 接受矩阵的接受侧)。 -#[derive(Debug, Clone, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum Step { - /// `**x = 表达式**` - Bind { - var: String, - expr: Expr, - line: u32, - }, - /// `**返回表达式**`(粗体无赋值) - Return { - expr: Expr, - line: u32, - }, - /// `1. 条件 / 2. *`(else 由 `cond: None` 表示) - If { - cond: PureExpr, - then: Vec, - otherwise: Vec, - line: u32, - }, - /// 语句形式调用(`> 调用` / `*语句*`):值丢弃,但仍进轨迹。 - Trace { - op: String, - args: Vec, - line: u32, - }, -} - -/// 语句内表达式:纯表达式或不透明操作调用。 -#[derive(Debug, Clone, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum Expr { - Pure(PureExpr), - /// 不透明操作调用:`ops` 里的 `id`(接收者/插件/有效应的调用)。 - Op { - id: String, - args: Vec, - }, - /// `$$…$$` 公式:不透明值,不翻译。 - Formula, - /// ``` 围栏 code 值(不经 parse 拒绝时降为不透明)。 - Code, -} - -/// 一个不透明操作的声明(Lean 里是 `Op` 构造器 + `Env` 查询键)。 -#[derive(Debug, Clone, Serialize)] -pub struct OpDecl { - pub id: String, - pub effect: String, - pub params: Vec<(String, PlanTy)>, - /// 实参个数(首次出现处;同名操作元数一致)。 - pub arity: usize, -} - -/// 定理占位(P1 起填充;P0 恒为空,保持 `plan.json` 形状稳定)。 -#[derive(Debug, Clone, Serialize)] -pub struct ClaimPlan { - pub id: String, - pub premise: Option, - pub conclusion: String, - pub tactic: Option, - /// 定理表行号(锚定源码漂移)。 - pub line: u32, -} - -/// 假设表条目(T3;P0 恒为空)。 -#[derive(Debug, Clone, Serialize)] -pub struct AssumptionPlan { - pub op: String, - pub premise: Option, - pub postcondition: String, -} - -/// 单个函数的 Plan。 -#[derive(Debug, Clone, Serialize)] -pub struct FnPlan { - pub name: String, - pub params: Vec, - pub result_ty: PlanTy, - /// 该函数用到的不透明操作(按出现顺序,去重)。 - pub ops: Vec, - pub steps: Vec, - pub effects: Vec, - pub claims: Vec, - pub assumptions: Vec, -} - -#[derive(Debug, Clone, Serialize)] -pub struct ParamPlan { - pub name: String, - pub ty: PlanTy, - pub has_default: bool, -} - -/// 整个文件的 Plan。 -#[derive(Debug, Clone, Serialize)] -pub struct Plan { - pub schema: u32, - /// 相对当前工作目录的路径(确定性要求:无绝对路径、无时间戳)。 - pub module: String, - pub source_sha256: String, - pub functions: Vec, -} - -impl Plan { - /// 规范化 JSON(键序稳定、无空白差异;两次运行必须字节一致)。 - pub fn to_stable_json(&self) -> String { - let value = serde_json::to_value(self).expect("plan serializes"); - format_value(&value) - } -} - -/// 确定性 JSON 序列化:对象键排序、数组保序、定长浮点。 -fn format_value(value: &serde_json::Value) -> String { - use serde_json::Value; - match value { - Value::Null => "null".into(), - Value::Bool(b) => b.to_string(), - Value::Number(n) => n.to_string(), - Value::String(s) => serde_json::to_string(s).expect("string serializes"), - Value::Array(items) => { - let inner: Vec = items.iter().map(format_value).collect(); - format!("[{}]", inner.join(",")) - } - Value::Object(map) => { - let mut keys: Vec<&String> = map.keys().collect(); - keys.sort(); - let inner: Vec = keys - .into_iter() - .map(|k| { - format!( - "{}:{}", - serde_json::to_string(k).expect("key serializes"), - format_value(&map[k]) - ) - }) - .collect(); - format!("{{{}}}", inner.join(",")) - } - } -} diff --git a/src/prove/lower.rs b/src/prove/lower.rs deleted file mode 100755 index add6246..0000000 --- a/src/prove/lower.rs +++ /dev/null @@ -1,1367 +0,0 @@ -//! 降级:AST → Plan IR(`doc/design/prove-cli.md` §4.1 ②)。 -//! -//! 三条硬边界(设计 §2.2)——`while`/递归/动态派发(函数值、无法解析的裸名) -//! **拒绝,不降级**;静态可拼写的未知调用(方法、`工程.成员` 一类插件路径) -//! 一律不透明化为 [`ir::Expr::Op`](诚实:行为完全未知,效应照 sema 标注)。 -//! 本模块不执行任何代码,只读 AST。 - -use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; - -use anyhow::Result; - -use crate::ast::{self, Arg, BinaryOp, CallExpr, Expr, Function, Module, Stmt}; -use crate::diagnostics::{Diagnostic, Severity, Span}; -use crate::prove::ir::{ - AssumptionPlan, BinOp, ClaimPlan, Expr as IrExpr, FnPlan, InterpPart, OpDecl, ParamPlan, Plan, PlanTy, - PureExpr, Step, UnOp, SCHEMA, -}; -use crate::sema::bind::{call_display, resolve_for_exec}; -use crate::host::HostFn; -use crate::sema::ir::EffectSet; -use crate::sema::resolution::Target; - -/// 单个函数的降级产物(plan 或拒绝原因)。 -#[derive(Debug)] -pub struct Lowered { - pub display: String, - /// 对象体(`# 类型`)不是可证单元:不证也不算拒绝。 - pub is_object: bool, - pub plan: Option, - /// 全部拒绝原因(`proof.while` / `proof.recursion` / `proof.dynamic_call` / …)。 - pub rejected: Vec, -} - -/// 降级上下文:模块 + 效应表(来自 sema;缺失时效应保守记 `unknown`)。 -pub struct Lowerer<'m> { - module: &'m Module, - /// `(file, display_name) → effects`(sema 闭包 artifact 的源位置键)。 - effects: BTreeMap<(String, String), EffectSet>, - allow_opaque: BTreeSet, -} - -impl<'m> Lowerer<'m> { - pub fn new( - module: &'m Module, - effects: BTreeMap<(String, String), EffectSet>, - _strict_types: bool, - allow_opaque: &[String], - ) -> Self { - Self { - module, - effects, - allow_opaque: allow_opaque.iter().cloned().collect(), - } - } - - /// 降级全部函数(含子函数),按源码顺序。 - pub fn lower_module(&self) -> Vec { - let mut out = Vec::new(); - self.lower_functions(self.module.functions.as_slice(), "", &mut out); - out - } - - fn lower_functions(&self, funs: &[Function], prefix: &str, out: &mut Vec) { - for fun in funs { - let display = if prefix.is_empty() { - fun.name.clone() - } else { - format!("{prefix}.{}", fun.name) - }; - out.push(self.lower_function(&display, fun)); - self.lower_functions(&fun.children, &display, out); - } - } - - fn lower_function(&self, display: &str, fun: &Function) -> Lowered { - let mut rejected = Vec::new(); - // 对象体(`# 类型`)不是可证单元:P0 只证函数/方法。 - if fun.is_object() { - return Lowered { - display: display.to_string(), - is_object: true, - plan: None, - rejected, - }; - } - // `--allow-opaque `:整体降级为单个不透明操作,优先于子集验收 - // (作者显式声明"行为未知",因此 while/递归也不再是拒绝理由)。 - if self.allow_opaque.contains(display) { - return Lowered { - display: display.to_string(), - is_object: false, - plan: Some(self.opaque_whole(display, fun)), - rejected, - }; - } - // 子集验收先于一切:拒绝的函数不生成 plan。 - self.check_subset(fun, &mut rejected); - if !rejected.is_empty() { - return Lowered { - display: display.to_string(), - is_object: false, - plan: None, - rejected, - }; - } - - let mut body = Body::default(); - for stmt in &fun.body { - self.lower_stmt(fun, stmt, &mut body); - } - if !body.rejected.is_empty() { - return Lowered { - display: display.to_string(), - is_object: false, - plan: None, - rejected: body.rejected, - }; - } - let plan = FnPlan { - name: display.to_string(), - params: fun - .params - .iter() - .map(|p| ParamPlan { - name: p.name.clone(), - ty: self.param_ty(fun, &p.name), - has_default: p.default.is_some(), - }) - .collect(), - result_ty: self.result_ty(fun), - ops: body.ops, - steps: body.steps, - effects: body - .op_effects - .iter() - .filter(|e| e.as_str() != "pure") - .cloned() - .collect(), - claims: fun - .claims - .iter() - .map(|c| ClaimPlan { - id: c.id.clone(), - premise: c.premise.clone(), - conclusion: c.conclusion.clone(), - tactic: c.tactic.clone(), - line: c.line, - }) - .collect(), - assumptions: fun.assumptions.iter().map(|a|AssumptionPlan{ - op:a.op.clone(), premise:a.premise.clone(), - postcondition:a.postcondition.clone() - }).collect(), - }; - Lowered { - display: display.to_string(), - is_object: false, - plan: Some(plan), - rejected, - } - } - - fn opaque_whole(&self, display: &str, fun: &Function) -> FnPlan { - // 行为完全未知:效应标签一律 `opaque`(§4.5,比猜测诚实)。 - let effect = "opaque".to_string(); - let mut ops = Vec::new(); - let id = format!("调用:{display}"); - ops.push(OpDecl { - id: id.clone(), - effect, - params: Vec::new(), - arity: fun.params.len(), - }); - FnPlan { - name: display.to_string(), - params: fun - .params - .iter() - .map(|p| ParamPlan { - name: p.name.clone(), - ty: PlanTy::Any, - has_default: p.default.is_some(), - }) - .collect(), - result_ty: PlanTy::Any, - ops, - steps: vec![Step::Trace { - op: id, - args: fun - .params - .iter() - .map(|p| PureExpr::Var(p.name.clone())) - .collect(), - line: fun.span.line, - }], - effects: vec!["opaque".into()], - claims: Vec::new(), - assumptions: Vec::new(), - } - } - - // ---------------------------------------------------------------- 子集验收 - - /// 子集验收(§4.3 拒绝侧)。收集全部原因,不止第一条。 - fn check_subset(&self, fun: &Function, rejected: &mut Vec) { - for stmt in &fun.body { - self.check_stmt(stmt, fun, rejected); - } - // 递归:本函数显示名出现在自身可静态解析的调用闭包里。 - let display = self.display_of(fun); - if self.recurses(fun, &display, &mut BTreeSet::new()) { - rejected.push(reject( - self.module, - fun.span, - "proof.recursion", - format!("`{display}` 递归调用不在可证子集(需要归纳证明,超出 P0–P3 范围)"), - )); - } - } - - fn check_stmt(&self, stmt: &Stmt, fun: &Function, rejected: &mut Vec) { - match stmt { - Stmt::While { span, .. } => rejected.push(reject( - self.module, - *span, - "proof.while", - format!( - "`-` 循环不在可证子集:`{}` 被跳过(无循环 ⇒ 返回路径有限)", - fun.name - ), - )), - Stmt::ForEach { span, .. } => rejected.push(reject( - self.module, - *span, - "proof.foreach_pending", - "foreach 在 P3 才进入可证子集(需要列表有限性证据)", - )), - Stmt::Assign { value, span, .. } => self.check_expr(value, fun, *span, rejected), - Stmt::Return { value, span } => self.check_expr(value, fun, *span, rejected), - Stmt::Expr { value, span } => self.check_expr(value, fun, *span, rejected), - Stmt::Call { call, span } => self.check_call(call, fun, *span, rejected), - Stmt::Branch { arms, .. } => { - for arm in arms { - if let Some(cond) = &arm.condition { - // 条件的 span 在解析期未单独记录,用函数级锚点替代。 - self.check_expr(cond, fun, fun.span, rejected); - } - for s in &arm.body { - self.check_stmt(s, fun, rejected); - } - } - } - } - } - - fn check_expr(&self, expr: &Expr, fun: &Function, span: Span, rejected: &mut Vec) { - match expr { - Expr::Call(call) => self.check_call(call, fun, span, rejected), - Expr::Occluded { payload, .. } => { - if let Some(payload) = payload { - self.check_expr(payload, fun, span, rejected); - } - } - Expr::Binary { left, right, .. } => { - self.check_expr(left, fun, span, rejected); - self.check_expr(right, fun, span, rejected); - } - Expr::Unary { expr, .. } => self.check_expr(expr, fun, span, rejected), - Expr::List(items) => { - for item in items { - self.check_expr(item, fun, span, rejected); - } - } - Expr::Map(entries) => { - for (_, value) in entries { - self.check_expr(value, fun, span, rejected); - } - } - Expr::Index { base, .. } => self.check_expr(base, fun, span, rejected), - Expr::Interp(parts) => { - for part in parts { - if let ast::InterpPart::Index { .. } = part { - rejected.push(reject( - self.module, - span, - "proof.unsupported", - "插值中的下标读取不在 P0 纯片段", - )); - } - } - } - Expr::Var(_) | Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {} - } - } - - fn check_call(&self, call: &CallExpr, fun: &Function, span: Span, rejected: &mut Vec) { - for arg in &call.args { - let value = match arg { - Arg::Positional(value) | Arg::Named { value, .. } => value, - }; - self.check_expr(value, fun, span, rejected); - } - match resolve_for_exec(self.module, fun, call) { - Target::Local(target) => { - if target.is_object() { - rejected.push(reject( - self.module, - span, - "proof.dynamic_call", - format!("对象构造 `{}` 不在 P0 纯片段", call_display(call)), - )); - } - } - Target::Import { .. } | Target::Builtin(_) | Target::Host(_) => {} - Target::Dynamic { reason, name } => { - use crate::sema::bind::DynamicReason as R; - match reason { - R::CallFn | R::Plugin => rejected.push(reject( - self.module, - span, - "proof.dynamic_call", - format!("`{name}`:函数值/未知裸名调用不在可证子集"), - )), - // 方法调用(`` `recv`.m ``)与两段静态路径(`工程.成员`)都是 - // 静态可拼写的调用点 → 不透明操作,不拒绝(§4.3)。 - R::MethodReceiver => {} - } - } - Target::Unresolved { message, .. } => { - rejected.push(reject( - self.module, - span, - "proof.dynamic_call", - format!("`{}` 无法静态解析:{message}", call_display(call)), - )); - } - } - } - - fn display_of(&self, fun: &Function) -> String { - fn walk<'a>( - funs: &'a [Function], - prefix: &str, - target: &Function, - out: &mut Option, - ) { - if out.is_some() { - return; - } - for f in funs { - let display = if prefix.is_empty() { - f.name.clone() - } else { - format!("{prefix}.{}", f.name) - }; - if std::ptr::eq(f, target) { - *out = Some(display.clone()); - return; - } - walk(&f.children, &display, target, out); - } - } - let mut found = None; - walk(&self.module.functions, "", fun, &mut found); - found.unwrap_or_else(|| fun.name.clone()) - } - - /// 递归检测:从 `fun` 出发的可静态解析局部调用是否回到 `display`。 - fn recurses(&self, fun: &Function, display: &str, visiting: &mut BTreeSet) -> bool { - if !visiting.insert(display.to_string()) { - return true; - } - let mut found = false; - let calls = self.all_calls(fun); - for (call, callee_fun) in calls { - if let Target::Local(target) = resolve_for_exec(self.module, callee_fun, call) { - let target_display = self.display_of(target); - if target_display == display || self.recurses(target, &target_display, visiting) { - found = true; - break; - } - } - } - visiting.remove(display); - found - } - - /// 函数体里每个调用点及其**所在函数**(解析作用域)。 - fn all_calls<'a>(&'a self, fun: &'a Function) -> Vec<(&'a CallExpr, &'a Function)> { - let mut out = Vec::new(); - for stmt in &fun.body { - self.collect_stmt_calls(stmt, fun, &mut out); - } - out - } - - fn collect_stmt_calls<'a>( - &'a self, - stmt: &'a Stmt, - owner: &'a Function, - out: &mut Vec<(&'a CallExpr, &'a Function)>, - ) { - match stmt { - Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { - for call in collect_calls(value) { - out.push((call, owner)); - } - } - Stmt::Call { call, .. } => out.push((call, owner)), - Stmt::Branch { arms, .. } => { - for arm in arms { - if let Some(cond) = &arm.condition { - for call in collect_calls(cond) { - out.push((call, owner)); - } - } - for s in &arm.body { - self.collect_stmt_calls(s, owner, out); - } - } - } - _ => {} - } - } - - // ---------------------------------------------------------------- 语句降级 - - fn lower_stmt(&self, fun: &Function, stmt: &Stmt, body: &mut Body) { - match stmt { - Stmt::Assign { name, value, span, .. } => { - let expr = self.lower_expr(value, fun, span.line, body); - body.steps.push(Step::Bind { - var: name.clone(), - expr, - line: span.line, - }); - } - Stmt::Return { value, span } => { - let expr = self.lower_expr(value, fun, span.line, body); - body.steps.push(Step::Return { - expr, - line: span.line, - }); - } - Stmt::Call { call, span } => { - // 语句形式调用:值丢弃,但有效应的调用必须留下轨迹。 - if let IrExpr::Op { id, args } = self.lower_call_expr(call, fun, span.line, body) { - body.steps.push(Step::Trace { - op: id, - args, - line: span.line, - }); - } - } - Stmt::Expr { value, span } => { - if let IrExpr::Op { id, args } = self.lower_expr(value, fun, span.line, body) { - body.steps.push(Step::Trace { op: id, args, line: span.line }); - } - } - Stmt::Branch { arms, span } => { - let step = self.lower_branch(arms, span.line, fun, body); - body.steps.extend(step); - } - Stmt::While { span, .. } => body.rejected.push(reject( - self.module, - *span, - "proof.while", - "循环不在可证子集", - )), - Stmt::ForEach { span, .. } => body.rejected.push(reject( - self.module, - *span, - "proof.foreach_pending", - "foreach 在 P3 才进入可证子集", - )), - } - } - - /// 多臂分支 → 嵌套 if/else(保持源顺序;`1. 条件 / 2. *` 是两臂常态)。 - fn lower_branch( - &self, - arms: &[ast::BranchArm], - line: u32, - fun: &Function, - body: &mut Body, - ) -> Vec { - let Some(first) = arms.first() else { - return Vec::new(); - }; - let Some(cond) = &first.condition else { - // 首臂即 else(无条件的 `1. *`):平铺为主体。 - let before = body.steps.len(); - for s in &first.body { - self.lower_stmt(fun, s, body); - } - return body.steps.split_off(before); - }; - let cond_ir = self.lower_pure_required(cond, fun, line, body); - let then = { - let mut sub = Body { - inline_depth: body.inline_depth, - ..Body::default() - }; - for s in &first.body { - self.lower_stmt(fun, s, &mut sub); - } - let steps = std::mem::take(&mut sub.steps); - body.absorb(sub); - steps - }; - let otherwise = if arms.len() > 1 { - self.lower_branch(&arms[1..], line, fun, body) - } else { - Vec::new() - }; - vec![Step::If { - cond: cond_ir, - then, - otherwise, - line, - }] - } - - // ---------------------------------------------------------------- 表达式降级 - - fn lower_expr(&self, expr: &Expr, fun: &Function, line: u32, body: &mut Body) -> IrExpr { - match expr { - Expr::Call(call) => self.lower_call_expr(call, fun, line, body), - Expr::Occluded { payload, .. } => match payload { - Some(payload) => self.lower_expr(payload, fun, line, body), - None => IrExpr::Pure(PureExpr::None), - }, - other => match self.lower_pure(other, fun, body) { - Some(pure) => IrExpr::Pure(pure), - None => match other { - // `$$…$$` 公式与 code 围栏:不透明值(设计 §4.3,不翻译)。 - Expr::Formula(_) => IrExpr::Formula, - Expr::Code(_) => IrExpr::Code, - // 动态键读取 `` [`k`](m) ``:不透明读操作。 - Expr::Index { label: ast::IndexKey::Var(name), .. } => { - let id = body.register_op( - &format!("读取:`{name}`"), - "pure".to_string(), - 0, - ); - IrExpr::Op { id, args: Vec::new() } - } - _ => { - // 诚实边界(审查修复):字面量容器(列表/映射/插值)里的调用 - // 不能变成纯片段的一部分,也不许静默丢弃——静默丢弃会让 - // 含副作用调用的函数伪装成"无操作"。拒绝并提示改写。 - if !collect_calls(other).is_empty() { - body.rejected.push(reject( - self.module, - Span::new(line, 1), - "proof.unsupported", - "列表/映射字面量里的调用不在 P0 纯片段:先把调用绑定到变量(`x` = [调用](…)`),再放进字面量", - )); - } - IrExpr::Pure(PureExpr::None) - } - }, - }, - } - } - - /// 调用 → 内联构造器 / 纯内建 / 不透明 Op。 - fn lower_call_expr(&self, call: &CallExpr, fun: &Function, line: u32, body: &mut Body) -> IrExpr { - let mut args: Vec = Vec::with_capacity(call.args.len()); - for arg in call.args.iter() { - let value = match arg { - Arg::Positional(value) | Arg::Named { value, .. } => value, - }; - args.push(self.lower_arg(value, fun, line, body)); - } - match resolve_for_exec(self.module, fun, call) { - Target::Builtin(name) => lower_builtin(name, args, body), - Target::Host(host) => { - if host_is_pure(host) { - // Access 特形(字段读取)或 mq.* 构造器。 - return lower_host_pure(host, args); - } - let id = body.register_op(&call_display(call), effect_label_of_host(host), args.len()); - IrExpr::Op { id, args } - } - Target::Local(target) => { - let display = self.display_of(target); - // 自递归(防御;子集验收已拒绝)或超深内联 → 不透明。 - if std::ptr::eq(target, fun) || body.inline_depth >= 4 { - let id = body.register_op(&call_display(call), self.effect_of("self", &display), args.len()); - return IrExpr::Op { id, args }; - } - if self.is_inline_candidate(target) { - body.inline_depth += 1; - let lowered = self.inline_body(target, &args, body); - body.inline_depth -= 1; - lowered - } else { - let id = body.register_op(&call_display(call), self.effect_of("self", &display), args.len()); - IrExpr::Op { id, args } - } - } - Target::Import { bind, lib, fun: target, .. } => { - // Source-level verification of a tightly restricted imported - // pure leaf: one return expression, only literal/parameter - // arithmetic, exact positional args. This is NOT abstract - // contract reuse; Lean verifies the actual substituted body. - if body.inline_depth < 4 - && imported_pure_leaf(target) - && imported_leaf_arithmetic_safe(target,call) - && call.args.len()==target.params.len() - && call.args.iter().all(|a|matches!(a,Arg::Positional(_))) - { - body.inline_depth+=1; - let lowered=self.inline_body(target,&args,body); - body.inline_depth-=1; - return lowered; - } - // lib/result 的构造器内联为结构(§4.5;真实库名是 ok/error/value_or)。 - if bind == "result" && matches!(target.name.as_str(), "ok" | "error" | "value_or") { - return IrExpr::Pure(PureExpr::Ctor { - name: format!("result.{}", target.name), - args, - }); - } - let display = if call.path.is_some() { - call_display(call) - } else { - format!("{bind}.{}", target.name) - }; - let effect = self.effect_of(&source_file(lib), &display); - let effect = if effect == "unknown" { - imported_effect_label(lib, target) - } else { - effect - }; - let id = body.register_op(&display, effect, args.len()); - IrExpr::Op { id, args } - } - // 方法调用 / 两段静态路径:不透明(§4.3),接收者不展开。 - Target::Dynamic { name, .. } => { - let id = body.register_op(&name, "unknown".to_string(), args.len()); - IrExpr::Op { id, args } - } - Target::Unresolved { message, .. } => { - body.rejected.push(reject( - self.module, - Span::new(0, 0), - "proof.dynamic_call", - format!("`{}` 无法静态解析:{message}", call_display(call)), - )); - IrExpr::Pure(PureExpr::None) - } - } - } - - /// 实参降级:纯表达式直接用;不透明子调用先绑定临时变量再引用。 - /// 临时名全局递增(`实参N`),避免内联展开时遮蔽调用者的同名变量。 - fn lower_arg(&self, value: &Expr, fun: &Function, line: u32, body: &mut Body) -> PureExpr { - if let Some(pure) = self.lower_pure(value, fun, body) { - return pure; - } - match self.lower_expr(value, fun, line, body) { - // 嵌套纯调用(lower_pure 因解析上下文失败的回退路径)。 - IrExpr::Pure(pure) => pure, - IrExpr::Op { id, args } => { - body.temps_count += 1; - let temp = format!("实参{}", body.temps_count); - body.steps.push(Step::Bind { - var: temp.clone(), - expr: IrExpr::Op { id, args }, - line: 0, - }); - PureExpr::Var(temp) - } - _ => PureExpr::None, - } - } - - /// §4.5 内联判据(P0 保守版):无分支的直线函数 + sema 效应 pure + 非递归。 - /// 含分支的被调在 P0 一律不透明化(符号执行落地后在 P2 放宽)。 - fn is_inline_candidate(&self, target: &Function) -> bool { - if target.is_object() || has_branching(&target.body) { - return false; - } - let stmt_count = count_stmts(&target.body); - if stmt_count == 0 || stmt_count > 24 { - return false; - } - let display = self.display_of(target); - self.effect_of("self", &display) == "pure" - } - - /// 内联直线函数体:形参 → 实参替换,语句平铺;返回值即调用值。 - /// op 声明按 id 去重共享;步骤先替换形参再并入主体。 - fn inline_body(&self, target: &Function, args: &[PureExpr], body: &mut Body) -> IrExpr { - let mut result = IrExpr::Pure(PureExpr::None); - let mut sub = Body { - inline_depth: body.inline_depth, - temps_count: body.temps_count, - ..Body::default() - }; - for stmt in &target.body { - match stmt { - Stmt::Return { value, .. } => { - result = self.lower_expr(value, target, crate::ast::stmt_line(stmt), &mut sub); - } - _ => self.lower_stmt(target, stmt, &mut sub), - } - } - let params: Vec = target.params.iter().map(|p| p.name.clone()).collect(); - for step in sub.steps { - body.steps.push(substitute_step(&step, ¶ms, args)); - } - for op in sub.ops { - if body.op_ids.insert(op.id.clone()) { - body.op_effects.insert(op.effect.clone()); - body.ops.push(op); - } - } - body.op_effects.extend(sub.op_effects); - body.rejected.extend(sub.rejected); - body.temps_count = body.temps_count.max(sub.temps_count); - substitute_expr(&result, ¶ms, args) - } - - fn effect_of(&self, file: &str, display: &str) -> String { - self.effects - .get(&(file.to_string(), display.to_string())) - .map(effect_label) - .unwrap_or_else(|| "unknown".into()) - } - - fn param_ty(&self, fun: &Function, name: &str) -> PlanTy { - if let Some(contract) = &fun.contract { - if let Some(param) = contract.params.iter().find(|p| p.name == name) { - return PlanTy::from_contract(¶m.ty); - } - } - PlanTy::Any - } - - fn result_ty(&self, fun: &Function) -> PlanTy { - if let Some(contract) = &fun.contract { - if let Some(ret) = &contract.returns { - return PlanTy::from_contract(&ret.ty); - } - } - PlanTy::Any - } - - // ---------------------------------------------------------------- 纯片段 - - /// 纯表达式降级:能翻译返回 Some;不能返回 None(调用方决定不透明化)。 - fn lower_pure(&self, expr: &Expr, fun: &Function, body: &mut Body) -> Option { - match expr { - Expr::Literal(ast::Literal::None) => Some(PureExpr::None), - Expr::Literal(ast::Literal::Bool(b)) => Some(PureExpr::Bool(*b)), - Expr::Literal(ast::Literal::Int(i)) => Some(PureExpr::Int(*i)), - Expr::Literal(ast::Literal::Num(n)) => Some(PureExpr::Num(*n)), - Expr::Literal(ast::Literal::Text(s)) => Some(PureExpr::Text(s.clone())), - Expr::Var(name) => Some(PureExpr::Var(name.clone())), - Expr::Binary { op, left, right } => Some(PureExpr::Bin { - operator: bin_op(*op), - left: Box::new(self.lower_pure(left, fun, body)?), - right: Box::new(self.lower_pure(right, fun, body)?), - }), - Expr::Unary { op, expr } => Some(PureExpr::Un { - operator: match op { - ast::UnaryOp::Not => UnOp::Not, - ast::UnaryOp::Neg => UnOp::Neg, - }, - expr: Box::new(self.lower_pure(expr, fun, body)?), - }), - Expr::List(items) => Some(PureExpr::List( - items - .iter() - .map(|item| self.lower_pure(item, fun, body)) - .collect::>>()?, - )), - Expr::Map(entries) => Some(PureExpr::Map( - entries - .iter() - .map(|(k, v)| Some((k.clone(), self.lower_pure(v, fun, body)?))) - .collect::>>()?, - )), - Expr::Index { base, label } => { - let key = match label { - ast::IndexKey::Lit(key) => key.clone(), - ast::IndexKey::Var(_) => return None, // 动态键 → 不透明读 - }; - Some(PureExpr::Index { - base: Box::new(self.lower_pure(base, fun, body)?), - key, - }) - } - Expr::Interp(parts) => Some(PureExpr::Interp( - parts - .iter() - .map(|part| match part { - ast::InterpPart::Lit(text) => Some(InterpPart::Lit(text.clone())), - ast::InterpPart::Var(name) => Some(InterpPart::Var(name.clone())), - ast::InterpPart::Index { .. } => None, - }) - .collect::>>()?, - )), - Expr::Call(call) => { - let args: Option> = call - .args - .iter() - .map(|arg| match arg { - Arg::Positional(value) | Arg::Named { value, .. } => { - self.lower_pure(value, fun, body) - } - }) - .collect(); - let args = args?; - match resolve_for_exec(self.module, fun, call) { - Target::Builtin(name) if builtin_is_pure(name) => { - Some(match lower_builtin_pure(name, args) { - IrExpr::Pure(pure) => pure, - _ => return None, - }) - } - Target::Host(host) if host_is_pure(host) => { - Some(match lower_host_pure(host, args) { - IrExpr::Pure(pure) => pure, - _ => return None, - }) - } - _ => None, - } - } - _ => None, - } - } - - /// 分支条件必须是纯表达式(§4.3);不是就报 unsupported。 - fn lower_pure_required(&self, expr: &Expr, fun: &Function, line: u32, body: &mut Body) -> PureExpr { - match self.lower_pure(expr, fun, body) { - Some(pure) => pure, - None => { - body.rejected.push(reject( - self.module, - Span::new(line, 1), - "proof.unsupported", - "分支条件不在纯片段(只接受字面量/变量/比较/布尔)", - )); - PureExpr::None - } - } - } -} - -// ---------------------------------------------------------------- 内建与效应 - -/// 纯内建(可进纯片段)。 -fn builtin_is_pure(name: &str) -> bool { - matches!( - name, - "len" | "str" | "int" | "type" | "trim" | "split" | "join" | "at" - ) -} - -/// `print`/`input` 有效应,按不透明操作处理;其余内建进纯片段。 -fn lower_builtin(name: &str, args: Vec, body: &mut Body) -> IrExpr { - match name { - "print" => { - let id = body.register_op("打印", "output.write", 1); - IrExpr::Op { id, args } - } - "input" => { - let id = body.register_op("输入", "user.input", 1); - IrExpr::Op { id, args } - } - _ => lower_builtin_pure(name, args), - } -} - -fn lower_builtin_pure(name: &str, args: Vec) -> IrExpr { - match (name, args.as_slice()) { - ("len", [only]) => IrExpr::Pure(PureExpr::Len(Box::new(only.clone()))), - ("at", [base, key]) => IrExpr::Pure(PureExpr::Ctor { - name: "mq.at".into(), - args: vec![base.clone(), key.clone()], - }), - _ => IrExpr::Pure(PureExpr::Ctor { - name: format!("mq.{name}"), - args, - }), - } -} - -/// 纯 Host 函数进纯片段;`access`/`取`/`取值` 是字段读取的标准形。 -fn lower_host_pure(host: HostFn, args: Vec) -> IrExpr { - if matches!(host, HostFn::Access) { - if let [base, PureExpr::Text(key)] = args.as_slice() { - return IrExpr::Pure(PureExpr::Access { - base: Box::new(base.clone()), - key: key.clone(), - }); - } - } - IrExpr::Pure(PureExpr::Ctor { - name: format!("mq.{}", host.name()), - args, - }) -} - -fn host_is_pure(host: HostFn) -> bool { - host.effects() == ["pure"] -} - -fn effect_label_of_host(host: HostFn) -> String { - let effects = host.effects(); - if effects == ["pure"] { - "pure".into() - } else { - effects - .first() - .map(|s| (*s).to_string()) - .unwrap_or_else(|| "unknown".into()) - } -} - -/// Imported source transparency is enabled only for a pure expression -/// fragment that cannot inspect module globals or call external operations. -fn imported_pure_leaf(fun:&Function)->bool { - fn closed(expr:&Expr,params:&std::collections::BTreeSet<&str>)->bool { - match expr { - Expr::Literal(_)=>true, - Expr::Var(v)=>params.contains(v.as_str()), - Expr::Occluded {payload:Some(inner),..}=>closed(inner,params), - Expr::Unary {expr,..}=>closed(expr,params), - Expr::Binary {left,right,..}=>closed(left,params)&&closed(right,params), - _=>false, - } - } - if fun.is_object() || fun.body.len()!=1{return false} - let params:std::collections::BTreeSet<&str>=fun.params.iter() - .map(|p|p.name.as_str()).collect(); - match &fun.body[0]{ - Stmt::Return {value,..}=>closed(value,¶ms), - _=>false, - } -} - -/// The interpreter uses bounded i64 while Lean's arithmetic is unbounded. -/// Therefore imported source expansion of arithmetic is allowed only if all -/// arithmetic subexpressions close to checked i64 constants after applying -/// the *actual* call arguments. Unknown/overflow/div-zero stays opaque. -fn imported_leaf_arithmetic_safe(target:&Function, call:&CallExpr)->bool { - let Some(Stmt::Return {value,..})=target.body.first() else {return false}; - if target.params.len()!=call.args.len(){return false} - let bindings:Vec<(&str,&Expr)>=target.params.iter().zip(call.args.iter()) - .filter_map(|(p,a)|match a { - Arg::Positional(expr)=>Some((p.name.as_str(),expr)), - _=>None - }).collect(); - if bindings.len()!=call.args.len(){return false} - fn int_value(expr:&Expr,bindings:&[(&str,&Expr)],depth:usize)->Option{ - if depth>24 {return None} - match expr{ - Expr::Literal(ast::Literal::Int(n))=>Some(*n), - Expr::Var(v)=> { - let bound=bindings.iter().find(|(key,_)|*key==v.as_str())?.1; - // A bound argument must be self-contained to avoid recursion - int_value(bound,&[],depth+1) - } - Expr::Occluded {payload:Some(inner),..}=> - int_value(inner,bindings,depth+1), - Expr::Unary {op:ast::UnaryOp::Neg,expr}=> - int_value(expr,bindings,depth+1)?.checked_neg(), - Expr::Binary {op,left,right}=>{ - let x=int_value(left,bindings,depth+1)?; - let y=int_value(right,bindings,depth+1)?; - match op{ - BinaryOp::Add=>x.checked_add(y), - BinaryOp::Sub=>x.checked_sub(y), - BinaryOp::Mul=>x.checked_mul(y), - // Division semantics (integer rounding/Num coercion) - // require a differential proof before source transparency. - BinaryOp::Div=>None, - _=>None, - } - } - _=>None, - } - } - fn safe(expr:&Expr,bindings:&[(&str,&Expr)])->bool{ - match expr{ - Expr::Literal(_)=>true, - Expr::Var(v)=>bindings.iter().any(|(key,_)|*key==v.as_str()), - Expr::Occluded{payload:Some(inner),..}=>safe(inner,bindings), - Expr::Unary {op,expr}=>match op { - ast::UnaryOp::Neg=>int_value( - &Expr::Unary{op:*op,expr:expr.clone()},bindings,0).is_some(), - ast::UnaryOp::Not=>safe(expr,bindings), - }, - Expr::Binary {op,left,right}=>{ - match op { - BinaryOp::Add|BinaryOp::Sub|BinaryOp::Mul|BinaryOp::Div=> - int_value(expr,bindings,0).is_some(), - _=>safe(left,bindings)&&safe(right,bindings), - } - } - _=>false, - } - } - safe(value,&bindings) - && bindings.iter().all(|(_,argument)|safe(argument,&[])) -} - -/// 无 sema 效应表时的库函数效应回退(与 sema 的 imported_effects 同思路的保守版)。 -fn imported_effect_label(lib: &Module, fun: &Function) -> String { - let mut visiting = std::collections::HashSet::new(); - imported_effect_impl(lib, fun, &mut visiting) -} - -fn imported_effect_impl( - module: &Module, - fun: &Function, - visiting: &mut std::collections::HashSet<(Option, u32)>, -) -> String { - let identity = (module.source.path.clone(), fun.span.line); - if !visiting.insert(identity) { - return "pure".into(); - } - let mut effect = "pure".to_string(); - for stmt in &fun.body { - let calls: Vec<&CallExpr> = match stmt { - Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { - collect_calls(value) - } - Stmt::Call { call, .. } => vec![call], - _ => vec![], - }; - for call in calls { - match resolve_for_exec(module, fun, call) { - Target::Builtin(name) => { - if !builtin_is_pure(name) { - effect = if name == "print" { "output.write" } else { "user.input" }.into(); - } - } - Target::Host(host) => { - let label = effect_label_of_host(host); - if label != "pure" { - effect = label; - } - } - Target::Local(target) => { - let label = imported_effect_impl(module, target, visiting); - if label != "pure" { - effect = label; - } - } - Target::Import { lib: inner, fun: target, .. } => { - let label = imported_effect_impl(inner, target, visiting); - if label != "pure" { - effect = label; - } - } - _ => effect = "unknown".into(), - } - } - } - effect -} - -fn effect_label(effects: &EffectSet) -> String { - if effects.is_pure() { - "pure".into() - } else { - effects - .values() - .into_iter() - .find(|e| e.as_str() != "pure" && e.as_str() != "unknown") - .unwrap_or_else(|| { - if effects.contains("unknown") { - "unknown".into() - } else { - "pure".into() - } - }) - } -} - -fn source_file(module: &Module) -> String { - module - .source - .path - .as_ref() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default() -} - -fn bin_op(op: BinaryOp) -> BinOp { - use BinaryOp as A; - match op { - A::Add => BinOp::Add, - A::Sub => BinOp::Sub, - A::Mul => BinOp::Mul, - A::Div => BinOp::Div, - A::Eq => BinOp::Eq, - A::Ne => BinOp::Ne, - A::Lt => BinOp::Lt, - A::Le => BinOp::Le, - A::Gt => BinOp::Gt, - A::Ge => BinOp::Ge, - A::And => BinOp::And, - A::Or => BinOp::Or, - } -} - -fn collect_calls(expr: &Expr) -> Vec<&CallExpr> { - let mut out = Vec::new(); - fn go<'a>(expr: &'a Expr, out: &mut Vec<&'a CallExpr>) { - match expr { - Expr::Call(call) => { - out.push(call); - for arg in &call.args { - match arg { - Arg::Positional(value) | Arg::Named { value, .. } => go(value, out), - } - } - } - Expr::Binary { left, right, .. } => { - go(left, out); - go(right, out); - } - Expr::Unary { expr, .. } => go(expr, out), - Expr::List(items) => items.iter().for_each(|e| go(e, out)), - Expr::Map(entries) => entries.iter().for_each(|(_, v)| go(v, out)), - Expr::Index { base, .. } => go(base, out), - Expr::Occluded { payload, .. } => { - if let Some(p) = payload { - go(p, out) - } - } - _ => {} - } - } - go(expr, &mut out); - out -} - -fn has_branching(stmts: &[Stmt]) -> bool { - fn go(stmt: &Stmt) -> bool { - match stmt { - Stmt::Branch { arms, .. } => { - arms.iter().any(|arm| arm.body.iter().any(go)) - } - Stmt::While { body, .. } | Stmt::ForEach { body, .. } => body.iter().any(go), - _ => false, - } - } - stmts.iter().any(go) -} - -fn count_stmts(stmts: &[Stmt]) -> usize { - fn go(stmt: &Stmt) -> usize { - 1 + match stmt { - Stmt::Branch { arms, .. } => arms - .iter() - .map(|arm| arm.body.iter().map(go).sum::()) - .sum(), - _ => 0, - } - } - stmts.iter().map(go).sum() -} - -fn reject(module: &Module, span: Span, code: &str, message: impl Into) -> Diagnostic { - Diagnostic::new(module.source.path.as_deref(), span, message) - .with_source(&module.source) - .with_code(code) - .with_severity(Severity::Warning) -} - -// ---------------------------------------------------------------- 实参替换 - -fn substitute_step(step: &Step, params: &[String], args: &[PureExpr]) -> Step { - match step { - Step::Bind { var, expr, line } => Step::Bind { - var: var.clone(), - expr: substitute_expr(expr, params, args), - line: *line, - }, - Step::Return { expr, line } => Step::Return { - expr: substitute_expr(expr, params, args), - line: *line, - }, - Step::If { - cond, - then, - otherwise, - line, - } => Step::If { - cond: substitute_pure(cond, params, args), - then: then.iter().map(|s| substitute_step(s, params, args)).collect(), - otherwise: otherwise - .iter() - .map(|s| substitute_step(s, params, args)) - .collect(), - line: *line, - }, - Step::Trace { op, args: op_args, line } => Step::Trace { - op: op.clone(), - args: op_args - .iter() - .map(|a| substitute_pure(a, params, args)) - .collect(), - line: *line, - }, - } -} - -fn substitute_expr(expr: &IrExpr, params: &[String], args: &[PureExpr]) -> IrExpr { - match expr { - IrExpr::Pure(pure) => IrExpr::Pure(substitute_pure(pure, params, args)), - IrExpr::Op { id, args: op_args } => IrExpr::Op { - id: id.clone(), - args: op_args - .iter() - .map(|a| substitute_pure(a, params, args)) - .collect(), - }, - other => other.clone(), - } -} - -fn substitute_pure(pure: &PureExpr, params: &[String], args: &[PureExpr]) -> PureExpr { - match pure { - PureExpr::Var(name) => params - .iter() - .position(|p| p == name) - .and_then(|i| args.get(i)) - .cloned() - .unwrap_or_else(|| pure.clone()), - PureExpr::Bin { operator, left, right } => PureExpr::Bin { - operator: *operator, - left: Box::new(substitute_pure(left, params, args)), - right: Box::new(substitute_pure(right, params, args)), - }, - PureExpr::Un { operator, expr } => PureExpr::Un { - operator: *operator, - expr: Box::new(substitute_pure(expr, params, args)), - }, - PureExpr::Index { base, key } => PureExpr::Index { - base: Box::new(substitute_pure(base, params, args)), - key: key.clone(), - }, - PureExpr::Access { base, key } => PureExpr::Access { - base: Box::new(substitute_pure(base, params, args)), - key: key.clone(), - }, - PureExpr::Len(inner) => PureExpr::Len(Box::new(substitute_pure(inner, params, args))), - PureExpr::List(items) => PureExpr::List( - items - .iter() - .map(|i| substitute_pure(i, params, args)) - .collect(), - ), - PureExpr::Map(entries) => PureExpr::Map( - entries - .iter() - .map(|(k, v)| (k.clone(), substitute_pure(v, params, args))) - .collect(), - ), - PureExpr::Ctor { name, args: ctor_args } => PureExpr::Ctor { - name: name.clone(), - args: ctor_args - .iter() - .map(|a| substitute_pure(a, params, args)) - .collect(), - }, - other => other.clone(), - } -} - -// ---------------------------------------------------------------- 降级状态 - -#[derive(Default)] -struct Body { - steps: Vec, - ops: Vec, - op_ids: BTreeSet, - op_effects: BTreeSet, - rejected: Vec, - /// 临时实参变量计数(`实参N`,全局递增防遮蔽)。 - temps_count: usize, - inline_depth: usize, -} - -impl Body { - fn register_op(&mut self, display: &str, effect: impl Into, arity: usize) -> String { - let base = format!("调用:{display}"); - // 同名不同元数的调用点(可选参数等)→ 加 `/元数` 后缀:构造器声明与 - // 每个使用点的实参个数保持一致,否则生成的 Lean 无法编译。 - let id = match self.ops.iter().find(|o| o.id == base) { - Some(o) if o.arity == arity => base, - Some(_) => format!("{base}/{arity}"), - None => base, - }; - if self.op_ids.insert(id.clone()) { - let effect = effect.into(); - self.op_effects.insert(effect.clone()); - self.ops.push(OpDecl { - id: id.clone(), - effect, - params: Vec::new(), - arity, - }); - } - id - } - - /// 子体降级后并回主状态(ops / 效应 / 拒绝 / 临时变量;steps 由调用方取走)。 - fn absorb(&mut self, sub: Body) { - for op in sub.ops { - if self.op_ids.insert(op.id.clone()) { - self.op_effects.insert(op.effect.clone()); - self.ops.push(op); - } - } - self.op_effects.extend(sub.op_effects); - self.rejected.extend(sub.rejected); - self.temps_count = self.temps_count.max(sub.temps_count); - } -} - -// ---------------------------------------------------------------- 入口 - -/// 从模块生成 Plan(确定性输出;`module_display` 为相对路径)。 -pub fn build_plan( - module: &Module, - source_sha256: &str, - module_display: &str, - effects: BTreeMap<(String, String), EffectSet>, - allow_opaque: &[String], -) -> Result<(Plan, Vec)> { - let lowerer = Lowerer::new(module, effects, false, allow_opaque); - let lowered = lowerer.lower_module(); - let plan = Plan { - schema: SCHEMA, - module: module_display.to_string(), - source_sha256: source_sha256.to_string(), - functions: lowered.iter().filter_map(|l| l.plan.clone()).collect(), - }; - Ok((plan, lowered)) -} - -/// 效应表构建:sema 闭包 artifact → `(file, display) → effects`。 -/// sema 编译失败时返回空表(效应保守记 `unknown`,绝不臆造 pure)。 -pub fn effect_map(path: &Path) -> BTreeMap<(String, String), EffectSet> { - let mut map = BTreeMap::new(); - if let Ok(compilation) = crate::sema::ir::compile_file_closure(path) { - for artifact in &compilation.semantics.artifacts { - map.insert( - (artifact.source.file.clone(), artifact.display_name.clone()), - artifact.effects.clone(), - ); - } - } - map -} diff --git a/src/prove/mod.rs b/src/prove/mod.rs deleted file mode 100755 index fd080dd..0000000 --- a/src/prove/mod.rs +++ /dev/null @@ -1,889 +0,0 @@ -//! `marqdo prove`:SKILL 控制平面 → Lean 4(`doc/design/prove-cli.md`)。 -//! -//! 三条契约(设计 §1.3): -//! 1. **诚实**——只报实际做过的判定;`checked` 永不冒充 Lean 结论; -//! 2. **单调**——离线判定严格弱于 Lean(P2 落地护栏); -//! 3. **不执行**——本模块只读源码,从不运行目标程序。 -//! -//! P0 范围(roadmap/prove.md §2):装载 → 降级 → 定型 → 确定性生成 + audit。 -//! 判定(离线 ⑤ / Lean ⑥)在 P1/P2 接入;状态只到 `unverified` / `rejected` / -//! `error`。 - -pub mod cache; -pub mod driver; -pub mod emit; -pub mod ir; -pub mod lower; -pub mod offline; -pub mod proof_check; -pub mod types; - -use std::path::{Path, PathBuf}; -use std::time::Instant; - -use anyhow::{Context, Result}; - -use crate::diagnostics::Diagnostic; -use crate::prove::lower::Lowered; - -/// 判定层级(P0 恒 `none`)。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Tier { - Lean, - Offline, - None, -} - -impl Tier { - pub fn as_str(self) -> &'static str { - match self { - Tier::Lean => "lean", - Tier::Offline => "offline", - Tier::None => "none", - } - } -} - -/// 状态词(§1.2;P0 只会产生 `unverified` / `rejected` / `error`)。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Verdict { - Proved, - Checked, - Unverified, - Unproved, - Rejected, - Error, -} - -impl Verdict { - pub fn as_str(self) -> &'static str { - match self { - Verdict::Proved => "proved", - Verdict::Checked => "checked", - Verdict::Unverified => "unverified", - Verdict::Unproved => "unproved", - Verdict::Rejected => "rejected", - Verdict::Error => "error", - } - } - - /// 聚合优先级(差者胜):error > unproved > rejected > unverified > checked > proved。 - pub fn rank(self) -> u8 { - match self { - Verdict::Proved => 0, - Verdict::Checked => 1, - Verdict::Unverified => 2, - Verdict::Rejected => 3, - Verdict::Unproved => 4, - Verdict::Error => 5, - } - } - - pub fn worst(a: Verdict, b: Verdict) -> Verdict { - if a.rank() >= b.rank() { - a - } else { - b - } - } -} - -/// 退出码(§3.3)。 -impl Verdict { - pub fn exit_code(self, require_lean: bool) -> i32 { - match self { - Verdict::Error => 1, - Verdict::Unproved => 1, - Verdict::Rejected | Verdict::Unverified | Verdict::Checked if require_lean => 2, - _ => 0, - } - } -} - -/// 选项(§8.2)。 -#[derive(Debug, Clone)] -pub struct ProveOptions { - pub entry: Option, - pub only: Vec, - pub allow_opaque: Vec, - pub emit_dir: Option, - pub strict_types: bool, - pub require_lean: bool, - pub report_only: bool, - /// 绕过证书缓存(`--no-cache` / `MARQDO_PROOF_NO_CACHE`)。 - pub no_cache: bool, - /// 显式 lean 路径(`--lean` / `MARQDO_PROOF_LEAN`)。 - pub lean: Option, - /// 单次 lean 调用超时(默认 120s)。 - pub timeout: std::time::Duration, - /// 是否执行判定(`prove emit`/`audit` 子命令 = false,只生成不证)。 - pub judge: bool, - /// `maxHeartbeats`(默认随 lean)。 - pub max_heartbeats: Option, -} - -impl Default for ProveOptions { - fn default() -> Self { - Self { - entry: None, - only: Vec::new(), - allow_opaque: Vec::new(), - emit_dir: None, - strict_types: true, - require_lean: false, - report_only: false, - no_cache: false, - lean: None, - timeout: std::time::Duration::from_secs(120), - judge: true, - max_heartbeats: None, - } - } -} - -/// 单条定理的判定面(§3.5 claims)。 -#[derive(Debug, Clone)] -pub struct ClaimReport { - pub id: String, - pub premise: Option, - pub conclusion: String, - pub tactic: Option, - /// `proved` / `unproved` / `unverified`(判定层给出前与函数一致)。 - pub status: Verdict, - /// `trace`(P2 离线)/ `lean` / 空(未判定)。 - pub decided_by: String, - /// 映射回 `.mq.md` 的行号(失败证据)。 - pub source_line: Option, - /// Lean 原始报错片段(unproved 时)。 - pub evidence: Option, -} - -/// 单函数报告。 -#[derive(Debug, Clone)] -pub struct FunctionReport { - pub name: String, - pub verdict: Verdict, - pub tier: Tier, - /// 不透明操作(id, effect)。 - pub ops: Vec<(String, String)>, - /// 拒绝原因(code, message, line)。 - pub rejected: Vec<(String, String, u32)>, - /// 定理声明 + 判定。 - pub claims: Vec, -} - -/// Lean 判定信息(`lean: null` 表示没跑)。 -#[derive(Debug, Clone)] -pub struct LeanInfo { - pub toolchain: String, - pub library_sha256: String, - pub module_sha256: String, - /// `hit` / `miss`。 - pub cache: &'static str, -} - -/// 整体报告。 -#[derive(Debug, Clone)] -pub struct Report { - pub file: String, - pub source_sha256: String, - /// 产物目录 id(`.marqdo/prove/`)。 - pub artifact_id: Option, - pub status: Verdict, - pub functions: Vec, - pub diagnostics: Vec, - pub emitted: Vec, - pub lean: Option, - pub duration_ms: u128, -} - -impl Report { - /// JSON 面(§3.5;`status` 枚举稳定)。 - pub fn to_json(&self) -> serde_json::Value { - use serde_json::json; - json!({ - "schema": 1, - "status": self.status.as_str(), - "file": self.file, - "source_sha256": self.source_sha256, - "artifact_id": match &self.artifact_id { - Some(id) => json!(format!("mq://prove/{id}")), - None => serde_json::Value::Null, - }, - "functions": self.functions.iter().map(|f| json!({ - "name": f.name, - "status": f.verdict.as_str(), - "tier": f.tier.as_str(), - "claims": f.claims.iter().map(|c| { - let mut j = json!({ - "id": c.id, - "premise": c.premise, - "conclusion": c.conclusion, - "tactic": c.tactic, - "status": c.status.as_str(), - }); - if !c.decided_by.is_empty() { - j["decided_by"] = json!(c.decided_by); - } - if let Some(line) = c.source_line { - j["line"] = json!(line); - } - if let Some(ev) = &c.evidence { - j["evidence"] = json!(ev); - } - j - }).collect::>(), - "obligations": [], - "ops": f.ops.iter().map(|(id, effect)| json!({ - "id": id, "effect": effect, - })).collect::>(), - "rejected": f.rejected.iter().map(|(code, message, line)| json!({ - "code": code, "message": message, "line": line, - })).collect::>(), - })).collect::>(), - "lean": match &self.lean { - Some(info) => json!({ - "toolchain": info.toolchain, - "library_sha256": info.library_sha256, - "module_sha256": info.module_sha256, - "cache": info.cache, - }), - None => serde_json::Value::Null, - }, - "assumptions": [], - "diagnostics": self.diagnostics.iter().map(|d| d.to_json()).collect::>(), - "emitted": self.emitted.iter().map(|p| p.display().to_string()).collect::>(), - "duration_ms": self.duration_ms as u64, - }) - } - - /// 文本面(§3.4 风格;诊断走 stderr 由 main 负责)。 - pub fn to_text(&self) -> String { - let mut out = String::new(); - let functions = self.functions.len(); - let rejected = self - .functions - .iter() - .filter(|f| f.verdict == Verdict::Rejected) - .count(); - let ops: usize = self.functions.iter().map(|f| f.ops.len()).sum(); - out.push_str(&format!("prove: {}\n", self.file)); - let cache_note = match &self.lean { - Some(info) => format!("(lean · cache: {})", info.cache), - None => String::new(), - }; - out.push_str(&format!( - " status: {}{}\n", - self.status.as_str(), - cache_note - )); - out.push_str(&format!( - " functions: {functions} · opaque ops: {ops} · rejected: {rejected}\n" - )); - for f in &self.functions { - if f.verdict == Verdict::Rejected { - let codes: Vec<&str> = f.rejected.iter().map(|(c, _, _)| c.as_str()).collect(); - out.push_str(&format!(" rejected: {} ({})\n", f.name, codes.join(", "))); - } - for c in &f.claims { - match (c.status, &c.evidence) { - (Verdict::Proved, _) => { - out.push_str(&format!(" proved: {}.{}\n", f.name, c.id)); - } - (Verdict::Unproved, Some(ev)) => { - let line = c - .source_line - .map(|l| format!(":{l}")) - .unwrap_or_default(); - out.push_str(&format!( - " unproved: {}.{line}{} — {}\n", - f.name, - c.id, - first_line(ev) - )); - } - (Verdict::Unverified, _) => { - out.push_str(&format!(" unverified: {}.{}\n", f.name, c.id)); - } - _ => {} - } - } - } - for p in &self.emitted { - out.push_str(&format!(" emitted: {}\n", p.display())); - } - out - } -} - -fn first_line(s: &str) -> String { - s.lines().next().unwrap_or("").to_string() -} - -/// P0 主入口:装载 → 降级 → 定型 → 生成。 -pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result { - let started = Instant::now(); - let module = crate::load::load_module(path) - .with_context(|| format!("装载 {}", path.display()))?; - let source_sha256 = module - .source - .sha256 - .clone() - .unwrap_or_default(); - let file_display = display_path(path); - - // ① 装载完成;② 降级(效应表来自 sema;失败时保守 unknown)。 - let effects = lower::effect_map(path); - let (plan, lowered) = lower::build_plan( - &module, - &source_sha256, - &file_display, - effects, - &opts.allow_opaque, - )?; - - // ③ 定型(分支合流等;错误码 proof.type_mismatch)。 - let mut diagnostics: Vec = Vec::new(); - diagnostics.extend(types::typecheck_plan(&module, &lowered, opts.strict_types)); - - // ④ 生成(--report-only 时跳过写盘)。 - let mut emitted: Vec = Vec::new(); - let mut artifact_dir: Option = None; - let mut generated_lean: Option<(PathBuf, String)> = None; - if !opts.report_only { - let dir = match &opts.emit_dir { - Some(dir) => dir.clone(), - None => default_emit_dir(&source_sha256), - }; - let generated = dir.join("Generated"); - std::fs::create_dir_all(&generated) - .with_context(|| format!("创建 {}", generated.display()))?; - let (file_name, lean) = emit::emit_module(&plan, &emit::stem_of(&file_display)); - let lean_path = generated.join(&file_name); - std::fs::write(&lean_path, &lean) - .with_context(|| format!("写入 {}", lean_path.display()))?; - let plan_path = dir.join("plan.json"); - std::fs::write(&plan_path, plan.to_stable_json()) - .with_context(|| format!("写入 {}", plan_path.display()))?; - emitted.push(relative_cwd(&lean_path)); - emitted.push(relative_cwd(&plan_path)); - artifact_dir = Some(dir.clone()); - generated_lean = Some((lean_path, lean)); - } - - // 汇总:错误诊断 → error;有拒绝函数 → rejected;否则 unverified。 - let has_type_errors = diagnostics - .iter() - .any(|d| matches!(d.severity, crate::diagnostics::Severity::Error)); - let mut functions = summarize(&lowered, &opts.only); - let mut status = Verdict::Unverified; - if !functions.is_empty() { - status = functions - .iter() - .map(|f| f.verdict) - .fold(Verdict::Proved, Verdict::worst); - } - if has_type_errors { - status = Verdict::Error; - } - - // ⑤ 判定(P2):离线符号执行先行(毫秒级,checked ≠ proved), - // 有 Lean 工具链时随即复核(checked 升 proved;分歧 → error,永不落绿)。 - let mut lean_info: Option = None; - let claims_present = plan.functions.iter().any(|f| !f.claims.is_empty()); - if claims_present && opts.judge && !opts.report_only { - // ⑤a 离线(§5):F1–F5 片段内给 checked/反例,超出片段不猜。 - judge_offline(&plan, &mut functions, &mut diagnostics); - // ⑤b Lean 复核(§8):证书缓存 → 现算。 - match judge_with_lean( - &plan, - &source_sha256, - artifact_dir.as_deref(), - &generated_lean, - opts, - &mut functions, - &mut diagnostics, - ) { - Ok((verdict, info)) => { - lean_info = info; - if let Some(v) = verdict { - status = v; - } - } - Err(err) => { - diagnostics.push( - Diagnostic::new(None, crate::diagnostics::Span::new(0, 0), format!("{err:#}")) - .with_code("proof.lean_error"), - ); - status = Verdict::Error; - } - } - } else if claims_present && opts.report_only { - // report-only:不判定、不写盘;未证状态如实保留(恒返回 0 由 exit_code 处理)。 - } - - // 函数级状态聚合(判定后重算):文件状态只看**有定理**的函数 - // 与被拒绝的函数——无定理函数没有义务,不该拖低整体(但它们 - // 自己的行如实保留 unverified / tier none)。 - { - let relevant = functions.iter().filter(|f| { - !f.claims.is_empty() || f.verdict == Verdict::Rejected - }); - for f in relevant { - status = Verdict::worst(status, f.verdict); - } - } - - let report = Report { - file: file_display, - source_sha256, - artifact_id: artifact_dir - .as_ref() - .map(|d| d.file_name().map(|n| n.to_string_lossy().to_string())) - .unwrap_or(None), - status, - functions, - diagnostics, - emitted, - lean: lean_info, - duration_ms: started.elapsed().as_millis(), - }; - // Knowledge linkage is advisory. Failing to bind must not invent a proof - // or change the judgment of the underlying v2.8.0 prover. - #[cfg(feature = "cli")] - if let Some(dir) = artifact_dir.as_deref() { - if let Err(err) = crate::knowledge::proof::emit_links(path, &report, dir) { - eprintln!("warning[knowledge.proof_linkage]: {err:#}"); - } - } - Ok(report) -} - -/// 离线判定(§5):checked/反例贴回定理,绝不冒充 proved。 -/// 单调性护栏在此埋点:离线结论会在 judge_with_lean 里被 Lean 复核。 -fn judge_offline( - plan: &crate::prove::ir::Plan, - functions: &mut [FunctionReport], - diagnostics: &mut Vec, -) { - use crate::diagnostics::Span; - let debug = std::env::var("MARQDO_PROOF_DEBUG").is_ok_and(|v| v == "1"); - for f in plan.functions.iter() { - for claim in &f.claims { - let verdict = offline::check_claim(f, claim); - if debug { - eprintln!( - "[offline] {}.{} → {:?}", - f.name, claim.id, verdict - ); - } - let Some(fr) = functions.iter_mut().find(|x| x.name == f.name) else { - continue; - }; - let Some(cr) = fr.claims.iter_mut().find(|c| c.id == claim.id) else { - continue; - }; - match verdict { - offline::OfflineVerdict::Checked { cases } => { - cr.status = Verdict::Checked; - cr.decided_by = "trace".into(); - cr.evidence = Some(format!("离线符号执行:{cases} 条路径全部关闭(F1–F5)")); - cr.source_line = Some(claim.line); - fr.tier = Tier::Offline; - } - offline::OfflineVerdict::Unproved { counterexample } => { - cr.status = Verdict::Unproved; - cr.decided_by = "trace".into(); - cr.source_line = Some(claim.line); - cr.evidence = counterexample.as_ref().map(|c| { - format!( - "反例(离线符号执行):{} — 路径 #{}", - c.detail, c.path_id - ) - }); - if let Some(c) = &counterexample { - diagnostics.push( - Diagnostic::new( - None, - Span::new(claim.line, 0), - format!( - "定理 {}.{} 反例:{}", - f.name, claim.id, c.detail - ), - ) - .with_code("proof.claim_failed"), - ); - } - fr.tier = Tier::Offline; - } - offline::OfflineVerdict::Unverified { reason } => { - // 不猜:保留 unverified(不写 evidence,让位给 Lean 结果)。 - let _ = reason; - } - } - fr.verdict = fr - .claims - .iter() - .map(|x| x.status) - .fold(Verdict::Proved, Verdict::worst); - } - } -} - -/// 单一判定来源:缓存证书 → Lean 现算。返回(整体判定,lean 信息)。 -#[allow(clippy::too_many_arguments)] -fn judge_with_lean( - plan: &crate::prove::ir::Plan, - source_sha256: &str, - artifact_dir: Option<&Path>, - generated_lean: &Option<(PathBuf, String)>, - opts: &ProveOptions, - functions: &mut [FunctionReport], - diagnostics: &mut Vec, -) -> Result<(Option, Option)> { - use crate::diagnostics::Span; - let Some((lean_path, lean_src)) = generated_lean else { - return Ok((None, None)); - }; - - // 缓存键素材:工具链版本先探测(没有工具链就谈不上判定)。 - let toolchain = match driver::Toolchain::discover(opts.lean.as_deref()) { - Ok(t) => t, - Err(err) => { - if opts.require_lean { - return Err(err); - } - diagnostics.push( - Diagnostic::new(None, Span::new(0, 0), format!("{err:#}")) - .with_code("proof.lean_missing"), - ); - return Ok((None, None)); - } - }; - let Some(toolchain) = toolchain else { - // 没找到工具链:保持 unverified(诚实:没跑就是没跑)。 - // --require-lean 时退出码由 Verdict::exit_code 升到 2(§3.3 F3)。 - if opts.require_lean { - diagnostics.push( - Diagnostic::new( - None, - Span::new(0, 0), - "--require-lean:未找到 Lean 工具链(PATH/MARQDO_PROOF_LEAN/--lean)", - ) - .with_code("proof.lean_missing"), - ); - } - return Ok((None, None)); - }; - - // 库(内嵌源 → olean,按内容哈希缓存)。 - let cache_root = Path::new(".marqdo/prove"); - let (lib_dir, library_sha256) = driver::ensure_library(cache_root, &toolchain)?; - let module_sha256 = cache::sha256_hex(lean_src.as_bytes()); - let plan_sha = cache::sha256_hex(plan.to_stable_json().as_bytes()); - let key = cache::cache_key( - source_sha256, - &plan_sha, - &library_sha256, - &toolchain.version, - env!("CARGO_PKG_VERSION"), - ); - - let mut artifact_fallback: Option = None; - let artifact: &Path = match artifact_dir { - Some(d) => d, - None => { - let d = default_emit_dir(source_sha256); - // 极少见:report-only 之外无产物目录(理论上不可达)——现建。 - let _ = std::fs::create_dir_all(&d); - // 借用问题:把目录放成一个本地 owned 值,再取引用。 - artifact_fallback.get_or_insert(d).as_path() - } - }; - - // ① 证书命中 → 跳过判定。 - if !opts.no_cache { - if let Some(cert) = cache::load(artifact, &key) { - apply_claims(functions, &cert.claims, &cert.span_map, diagnostics); - let status = cert.status; - return Ok(( - Some(status), - Some(LeanInfo { - toolchain: toolchain.version, - library_sha256, - module_sha256, - cache: "hit", - }), - )); - } - } - - // ② 现算:lean 直接调用(LEAN_PATH 指向底座 olean)。 - let mut outcome = driver::check_module( - &toolchain, - &lib_dir, - lean_path, - lean_src, - opts.timeout, - opts.max_heartbeats, - )?; - // 测试注入(roadmap P2 单调性护栏):让首条定理在 Lean 侧"关不掉", - // 验证离线 checked + Lean unproved ⇒ error[proof.divergence] 的护栏真的咬人。 - if std::env::var("MARQDO_PROOF_INJECT_DIVERGENCE").is_ok_and(|v| v == "1") { - if let Some(first) = outcome.claims.iter_mut().find(|c| c.status == Verdict::Proved) { - first.status = Verdict::Unproved; - first.detail = "injected divergence (MARQDO_PROOF_INJECT_DIVERGENCE)".into(); - } - } - - // ③ 证据 → 诊断(proof.claim_failed,指回源码行)。 - let claim_records: Vec = outcome - .claims - .iter() - .map(|c| cache::ClaimRecord { - id: c.claim.clone(), - function: c.function.clone(), - status: c.status, - source_line: c.source_line, - }) - .collect(); - apply_outcome(functions, &outcome.claims, diagnostics); - - let cert = cache::Certificate { - key: key.clone(), - status: outcome.status, - tier: "lean", - source_sha256: source_sha256.to_string(), - library_sha256: library_sha256.clone(), - toolchain: toolchain.version.clone(), - module_sha256: module_sha256.clone(), - claims: claim_records, - span_map: outcome.span_map.clone(), - marqdo: env!("CARGO_PKG_VERSION").to_string(), - }; - if let Err(err) = cache::store(artifact, &cert) { - diagnostics.push( - Diagnostic::new( - None, - Span::new(0, 0), - format!("证书写入失败(不阻塞判定):{err:#}"), - ) - .with_code("proof.cache_write"), - ); - } - - Ok(( - Some(outcome.status), - Some(LeanInfo { - toolchain: toolchain.version, - library_sha256, - module_sha256, - cache: "miss", - }), - )) -} - -/// 把判定结果按 (函数, 定理 id) 贴回函数报告。 -fn apply_outcome( - functions: &mut [FunctionReport], - claims: &[driver::ClaimOutcome], - diagnostics: &mut Vec, -) { - use crate::diagnostics::Span; - for c in claims { - let matches_fn = |f: &FunctionReport| { - f.name == c.function - || emit::lean_ident(&f.name) - .trim_matches('«') - .trim_matches('»') - == c.function - }; - let Some(pos) = functions.iter().position(matches_fn) else { - continue; - }; - let f = &mut functions[pos]; - if let Some(claim) = f.claims.iter_mut().find(|x| x.id == c.claim) { - // 单调性护栏(§5.4):离线结论必须被 Lean 复核印证。 - // checked 但 Lean 关不掉,或离线反例被 Lean 证出来 ⇒ 判定器有 bug。 - let divergence = match (claim.status, c.status) { - (Verdict::Checked, Verdict::Unproved) - | (Verdict::Unproved, Verdict::Proved) => true, - _ => false, - }; - if divergence { - diagnostics.push( - Diagnostic::new( - None, - Span::new(claim.source_line.unwrap_or(0), 0), - format!( - "离线与 Lean 判定分歧:定理 {}.{} 离线 {:?},Lean {}——判定器缺陷,拒绝落绿", - f.name, c.claim, claim.status, c.status.as_str() - ), - ) - .with_code("proof.divergence"), - ); - claim.status = Verdict::Error; - claim.decided_by = "lean".into(); - f.verdict = Verdict::Error; - f.tier = Tier::Lean; - continue; - } - claim.status = c.status; - claim.decided_by = "lean".into(); - claim.source_line = c.source_line; - claim.evidence = (!c.detail.is_empty()).then(|| c.detail.clone()); - if c.status == Verdict::Unproved { - diagnostics.push( - Diagnostic::new( - None, - Span::new(c.source_line.unwrap_or(0), 0), - format!( - "定理 {}.{} 未证:{}", - c.function, - c.claim, - first_line(&c.detail) - ), - ) - .with_code("proof.claim_failed"), - ); - } - f.verdict = f - .claims - .iter() - .map(|x| x.status) - .fold(Verdict::Proved, Verdict::worst); - f.tier = Tier::Lean; - } - } -} - -/// 证书命中的同款贴回。 -fn apply_claims( - functions: &mut [FunctionReport], - claims: &[cache::ClaimRecord], - span_map: &[(u32, u32)], - diagnostics: &mut Vec, -) { - use crate::diagnostics::Span; - for c in claims { - let source_line = c.source_line.or_else(|| { - span_map - .first() - .map(|(_, m)| *m) - }); - if let Some(f) = functions - .iter_mut() - .find(|f| f.name == c.function) - { - if let Some(claim) = f.claims.iter_mut().find(|x| x.id == c.id) { - claim.status = c.status; - claim.decided_by = "lean".into(); - claim.source_line = source_line; - if c.status == Verdict::Unproved { - diagnostics.push( - Diagnostic::new( - None, - Span::new(source_line.unwrap_or(0), 0), - format!("定理 {}.{} 未证(缓存)", f.name, c.id), - ) - .with_code("proof.claim_failed"), - ); - } - f.verdict = f - .claims - .iter() - .map(|x| x.status) - .fold(Verdict::Proved, Verdict::worst); - f.tier = Tier::Lean; - } - } - } -} - -fn summarize(lowered: &[Lowered], only: &[String]) -> Vec { - lowered - .iter() - .filter(|l| !l.is_object) - .filter(|l| only.is_empty() || only.iter().any(|name| name == &l.display)) - .map(|l| { - let (verdict, tier, ops, rejected, claims) = match &l.plan { - Some(plan) => ( - Verdict::Unverified, - Tier::None, - plan.ops - .iter() - .map(|op| (op.id.clone(), op.effect.clone())) - .collect(), - Vec::new(), - plan.claims - .iter() - .map(|c| ClaimReport { - id: c.id.clone(), - premise: c.premise.clone(), - conclusion: c.conclusion.clone(), - tactic: c.tactic.clone(), - status: Verdict::Unverified, - decided_by: String::new(), - source_line: None, - evidence: None, - }) - .collect(), - ), - None => ( - Verdict::Rejected, - Tier::None, - Vec::new(), - l.rejected - .iter() - .map(|d| { - ( - d.code.clone(), - d.message.clone(), - d.span.line, - ) - }) - .collect(), - Vec::new(), - ), - }; - FunctionReport { - name: l.display.clone(), - verdict, - tier, - ops, - rejected, - claims, - } - }) - .collect() -} - -/// 默认产物目录:`.marqdo/prove//`(key = 源 sha256 前 8 位)。 -pub fn default_emit_dir(source_sha256: &str) -> PathBuf { - PathBuf::from(".marqdo/prove").join(&source_sha256[..source_sha256.len().min(8)]) -} - -/// `prove clean`:删除 `.marqdo/prove`(--emit 指定目录不动)。 -pub fn clean() -> Result { - let root = Path::new(".marqdo/prove"); - if !root.exists() { - return Ok(0); - } - let count = std::fs::read_dir(root)?.count(); - std::fs::remove_dir_all(root) - .with_context(|| format!("删除 {}", root.display()))?; - Ok(count) -} - -fn display_path(path: &Path) -> String { - let cwd = std::env::current_dir().unwrap_or_default(); - path.strip_prefix(&cwd) - .unwrap_or(path) - .to_string_lossy() - .to_string() -} - -fn relative_cwd(path: &Path) -> PathBuf { - let cwd = std::env::current_dir().unwrap_or_default(); - path.strip_prefix(&cwd).unwrap_or(path).to_path_buf() -} diff --git a/src/prove/offline.rs b/src/prove/offline.rs deleted file mode 100755 index 3abba86..0000000 --- a/src/prove/offline.rs +++ /dev/null @@ -1,1581 +0,0 @@ -//! 离线符号执行(设计 §5):没有 Lean 也能给**部分**结论,但绝不比 Lean 强。 -//! -//! 片段 F1–F5,超出即 `unverified`(不猜): -//! - F1 路径枚举:控制流是有限树(lower 已拒绝循环/递归)。 -//! - F2 轨迹:每条路径的 Op 序列由分支决定;包含/长度逐路径求值。 -//! - F3 字面结果:返回值由字面量/参数/内联构造器组成时按结构求值。 -//! - F4 命题:and/or/not、=/≠ 作用于布尔结果;外部返回值上的布尔判定 -//! 视为自由原子(只二分、不假设原子间关系)。 -//! - F5 单变量区间:`x ⋈ c` 原子;路径条件 + 前提的上下界判定蕴含。 -//! -//! 单调性(§5.4):离线 `checked` ⊆ Lean `proved`——构造上 F5 ⊂ omega、 -//! F1–F4 ⊂ simp/decide;运行期只要有 Lean 就复核,分歧即 -//! `error[proof.divergence]`,永不落绿。 - -use std::collections::HashMap; - -use crate::prove::ir::{Expr, FnPlan, Plan, PureExpr, Step}; -use crate::prove::proof_check::{parse_claim_expr, tokenize_claim, ClaimAst, CTok}; - -/// 符号值(§5.3 状态)。 -#[derive(Debug, Clone, PartialEq)] -pub enum SymVal { - Int(i64), - Num(f64), - Bool(bool), - Text(String), - None, - /// 内联构造器结构(`result.ok(v)` → ok=true/value=v/error=none 等)。 - Struct { ctor: String, fields: Vec<(String, SymVal)> }, - /// 不透明操作返回值:值未知,出现已知(F2/F4)。 - OpResult(String), - /// 形参:值未知(F5 走区间)。 - Param(String), - /// 超出片段。 - Unknown, -} - -impl SymVal { - fn is_known(&self) -> bool { - !matches!(self, SymVal::Unknown) - } -} - -/// 比较算子(F5 区间原子)。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Cmp { - Lt, - Le, - Gt, - Ge, - Eq, - Ne, -} - -impl Cmp { - fn negate(self) -> Cmp { - match self { - Cmp::Lt => Cmp::Ge, - Cmp::Le => Cmp::Gt, - Cmp::Gt => Cmp::Le, - Cmp::Ge => Cmp::Lt, - Cmp::Eq => Cmp::Ne, - Cmp::Ne => Cmp::Eq, - } - } - - fn holds(self, lhs: i64, rhs: i64) -> bool { - match self { - Cmp::Lt => lhs < rhs, - Cmp::Le => lhs <= rhs, - Cmp::Gt => lhs > rhs, - Cmp::Ge => lhs >= rhs, - Cmp::Eq => lhs == rhs, - Cmp::Ne => lhs != rhs, - } - } - - fn as_str(self) -> &'static str { - match self { - Cmp::Lt => "<", - Cmp::Le => "≤", - Cmp::Gt => ">", - Cmp::Ge => "≥", - Cmp::Eq => "=", - Cmp::Ne => "≠", - } - } -} - -/// 路径条件原子。否定一律折进 op/expected(原子总是"正"形态)。 -#[derive(Debug, Clone, PartialEq)] -pub enum PathAtom { - /// `x ⋈ c`(F5)。 - Interval { var: String, op: Cmp, val: i64 }, - /// 自由布尔原子:`env(op).` 判定为 `expected`(F4;值未知只二分)。 - FreeBool { op: String, key: String, expected: bool }, - Literal(bool), - /// 无法归入片段的条件 → 该路径不可判定。 - Opaque, -} - -impl PathAtom { - fn negated(&self) -> PathAtom { - match self { - PathAtom::Interval { var, op, val } => PathAtom::Interval { - var: var.clone(), - op: op.negate(), - val: *val, - }, - PathAtom::FreeBool { op, key, expected } => PathAtom::FreeBool { - op: op.clone(), - key: key.clone(), - expected: !expected, - }, - PathAtom::Literal(b) => PathAtom::Literal(!b), - PathAtom::Opaque => PathAtom::Opaque, - } - } -} - -/// 一条执行路径(§5.3 第 3 步的收集物)。 -#[derive(Debug, Clone)] -pub struct PathRecord { - pub id: usize, - pub atoms: Vec, - pub result: SymVal, - pub trace: Vec, - /// Return 时的变量快照(定理可引用中间变量,如 `审核.ok`)。 - pub vars: Vec<(String, SymVal)>, - /// 踩到片段之外 → 相关定理 unverified。 - pub opaque: bool, - pub line: u32, -} - -/// 反例见证(§5.5:只承认确定性否定)。 -#[derive(Debug, Clone)] -pub struct Counterexample { - pub assignments: Vec<(String, i64)>, - pub path_id: usize, - pub detail: String, -} - -/// 单条定理的离线判定。 -#[derive(Debug, Clone)] -pub enum OfflineVerdict { - /// 每条路径都关闭(checked ≠ proved:没跑 Lean)。 - Checked { cases: usize }, - /// 存在可满足路径、结论确定性为假 → 反例。 - Unproved { counterexample: Option }, - /// 有路径/前提/结论超出片段 → 不猜(诚实)。 - Unverified { reason: String }, -} - -/// 离线执行一个函数,收集全部路径。 -pub fn execute(fn_plan: &FnPlan) -> Vec { - let mut paths = Vec::new(); - let mut state: HashMap = fn_plan - .params - .iter() - .map(|p| (p.name.clone(), SymVal::Param(p.name.clone()))) - .collect(); - exec_steps( - &fn_plan.steps, - &mut state, - Vec::new(), - Vec::new(), - false, - 0, - &mut paths, - ); - for (i, p) in paths.iter_mut().enumerate() { - p.id = i; - } - paths -} - -/// 符号执行语句序列;`atoms`/`trace` 沿路径累积,每个 Return 产生一条记录。 -fn exec_steps( - steps: &[Step], - state: &mut HashMap, - atoms: Vec, - trace: Vec, - opaque: bool, - line: u32, - out: &mut Vec, -) { - let Some((step, rest)) = steps.split_first() else { - // 函数体走完但无 Return:结果未知,但**轨迹与路径条件已知** - // ——F2 结论(包含/长度)仍可判,Result 类结论自然关不了。 - out.push(PathRecord { - id: usize::MAX, - atoms, - result: SymVal::Unknown, - trace, - vars: state.iter().map(|(k, v)| (k.clone(), v.clone())).collect(), - opaque, - line, - }); - return; - }; - match step { - Step::Bind { var, expr, line: l } => { - let (val, trace2, opq) = eval_expr(expr, state, trace, opaque); - let saved = state.insert(var.clone(), val); - exec_steps(rest, state, atoms, trace2, opq, *l, out); - // 回溯:Bind 只在本分支有效。 - match saved { - Some(v) => { - state.insert(var.clone(), v); - } - None => { - state.remove(var); - } - } - } - Step::Return { expr, line: l } => { - let (val, trace2, opq) = eval_expr(expr, state, trace, opaque); - out.push(PathRecord { - id: usize::MAX, - atoms, - result: val, - trace: trace2, - vars: state.iter().map(|(k, v)| (k.clone(), v.clone())).collect(), - opaque: opq, - line: *l, - }); - } - Step::If { cond, then, otherwise, line: l } => { - let (atom, cond_opaque) = cond_atom(cond, state); - // then:条件成立;else:条件取反;两支都要**接续 If 之后的语句** - // (Return 常在 If 外层)。分支在状态克隆上跑,互不污染。 - let mut atoms_then = atoms.clone(); - atoms_then.push(atom.clone()); - let mut then_full: Vec = then.clone(); - then_full.extend(rest.iter().cloned()); - let mut then_state = state.clone(); - exec_steps( - &then_full, - &mut then_state, - atoms_then, - trace.clone(), - opaque || cond_opaque, - *l, - out, - ); - let mut atoms_else = atoms; - atoms_else.push(atom.negated()); - let mut else_full: Vec = otherwise.clone(); - else_full.extend(rest.iter().cloned()); - let mut else_state = state.clone(); - exec_steps( - &else_full, - &mut else_state, - atoms_else, - trace, - opaque || cond_opaque, - *l, - out, - ); - // If 之后没有"公共继续"(已并入两支);state 保持进入前原样。 - } - Step::Trace { op, .. } => { - let mut trace2 = trace; - trace2.push(op_display(op)); - exec_steps(rest, state, atoms, trace2, opaque, line, out); - } - } -} - -/// `调用:人工审核` → `人工审核`(与 Lean `Op.name` 显示一致,轨迹名不变)。 -fn op_display(id: &str) -> String { - id.strip_prefix("调用:").unwrap_or(id).to_string() -} - -/// 条件 → 路径原子(F4/F5)。返回 (原子, 是否超出片段)。 -fn cond_atom(cond: &PureExpr, state: &HashMap) -> (PathAtom, bool) { - match cond { - PureExpr::Bool(b) => (PathAtom::Literal(*b), false), - PureExpr::Bin { operator, left, right } => { - // 单变量区间:`参数 ⋈ 整数字面量`(或反向)。 - if let Some(atom) = interval_atom(operator, left, right, state) { - return (atom, false); - } - // 自由布尔原子:`access(op结果, "ok")` 与字面量比较。 - if let Some(atom) = free_bool_atom(operator, left, right, state) { - return (atom, false); - } - (PathAtom::Opaque, true) - } - PureExpr::Un { operator, expr } => { - if matches!(operator, crate::prove::ir::UnOp::Not) { - let (atom, opq) = cond_atom(expr, state); - return (atom.negated(), opq); - } - (PathAtom::Opaque, true) - } - // 裸布尔条件:`1. 审核.ok`(真值即条件)。 - PureExpr::Access { base, key } => { - if let PureExpr::Var(v) = base.as_ref() { - if let Some(SymVal::OpResult(op)) = state.get(v) { - return ( - PathAtom::FreeBool { - op: op.clone(), - key: key.clone(), - expected: true, - }, - false, - ); - } - if let Some(SymVal::Struct { fields, .. }) = state.get(v) { - if let Some((_, SymVal::Bool(b))) = - fields.iter().find(|(k, _)| k == key) - { - return (PathAtom::Literal(*b), false); - } - } - } - (PathAtom::Opaque, true) - } - PureExpr::Var(v) => match state.get(v) { - Some(SymVal::Bool(b)) => (PathAtom::Literal(*b), false), - _ => (PathAtom::Opaque, true), - }, - _ => (PathAtom::Opaque, true), - } -} - -/// F5 原子:`x ⋈ c`,x 是形参(或绑定了形参的变量),c 是整数字面量。 -fn interval_atom( - operator: &crate::prove::ir::BinOp, - left: &PureExpr, - right: &PureExpr, - state: &HashMap, -) -> Option { - use crate::prove::ir::BinOp as B; - let op = match operator { - B::Lt => Cmp::Lt, - B::Le => Cmp::Le, - B::Gt => Cmp::Gt, - B::Ge => Cmp::Ge, - B::Eq => Cmp::Eq, - B::Ne => Cmp::Ne, - _ => return None, - }; - match (left, right) { - (PureExpr::Var(v), PureExpr::Int(c)) => { - // 只有仍指向形参的变量才可做区间(绑定值另论)。 - match state.get(v) { - Some(SymVal::Param(_)) | None => { - Some(PathAtom::Interval { var: v.clone(), op, val: *c }) - } - _ => None, - } - } - (PureExpr::Int(c), PureExpr::Var(v)) => { - match state.get(v) { - Some(SymVal::Param(_)) | None => { - // c ⋈ x ≡ x (flip ⋈) c - Some(PathAtom::Interval { - var: v.clone(), - op: op.flip(), - val: *c, - }) - } - _ => None, - } - } - _ => None, - } -} - -/// F4 自由原子:`<变量 = OpResult> 的布尔字段 == 布尔字面量`。 -/// 如 `1. 审核.ok`,其中 `审核 = 人工审核(…)`(值未知 → 只二分)。 -fn free_bool_atom( - operator: &crate::prove::ir::BinOp, - left: &PureExpr, - right: &PureExpr, - state: &HashMap, -) -> Option { - use crate::prove::ir::BinOp as B; - let (expected, a, b) = match operator { - B::Eq => (true, left, right), - B::Ne => (false, left, right), - _ => return None, - }; - let (access, field_key, lit) = match (a, b) { - (PureExpr::Access { base, key }, PureExpr::Bool(v)) => { - (base.as_ref(), key.clone(), *v == expected) - } - (PureExpr::Bool(v), PureExpr::Access { base, key }) => { - (base.as_ref(), key.clone(), *v == expected) - } - _ => return None, - }; - let PureExpr::Var(var) = access else { - return None; - }; - let SymVal::OpResult(op) = state.get(var)? else { - return None; - }; - Some(PathAtom::FreeBool { - op: op.clone(), - key: field_key, - expected: lit, - }) -} - -/// 表达式求值 → (符号值, 新轨迹, 是否超出片段)。 -fn eval_expr( - expr: &Expr, - state: &HashMap, - trace: Vec, - opaque: bool, -) -> (SymVal, Vec, bool) { - match expr { - Expr::Pure(p) => (eval_pure(p, state), trace, opaque), - Expr::Op { id, .. } => { - let mut trace2 = trace; - trace2.push(op_display(id)); - (SymVal::OpResult(op_display(id)), trace2, opaque) - } - // 公式/围栏代码:不透明值,超出片段。 - Expr::Formula | Expr::Code => (SymVal::Unknown, trace, true), - } -} - -/// 纯表达式结构求值(F3):字面量与内联构造器按结构化简,其余保守 Unknown。 -pub fn eval_pure(p: &PureExpr, state: &HashMap) -> SymVal { - match p { - PureExpr::Int(i) => SymVal::Int(*i), - PureExpr::Num(n) => SymVal::Num(*n), - PureExpr::Bool(b) => SymVal::Bool(*b), - PureExpr::Text(s) => SymVal::Text(s.clone()), - PureExpr::None => SymVal::None, - PureExpr::Var(v) => state.get(v).cloned().unwrap_or(SymVal::Unknown), - PureExpr::Bin { operator, left, right } => eval_bin(*operator, left, right, state), - PureExpr::Un { operator, expr } => { - let v = eval_pure(expr, state); - match (operator, v) { - (crate::prove::ir::UnOp::Not, SymVal::Bool(b)) => SymVal::Bool(!b), - (crate::prove::ir::UnOp::Neg, SymVal::Int(i)) => SymVal::Int(-i), - _ => SymVal::Unknown, - } - } - PureExpr::Access { base, key } => match eval_pure(base, state) { - SymVal::Struct { fields, .. } => fields - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v.clone()) - .unwrap_or(SymVal::None), - _ => SymVal::Unknown, - }, - PureExpr::Index { base, key } => match eval_pure(base, state) { - SymVal::Struct { fields, .. } => fields - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v.clone()) - .unwrap_or(SymVal::None), - _ => SymVal::Unknown, - }, - PureExpr::Len(inner) => match eval_pure(inner, state) { - SymVal::Struct { ctor, .. } if ctor == "list" => SymVal::Unknown, - SymVal::Text(s) => SymVal::Int(s.chars().count() as i64), - _ => SymVal::Unknown, - }, - PureExpr::List(items) => { - // 列表字面量:全部已知才结构化(保留为 list 构造)。 - let vals: Vec = items.iter().map(|i| eval_pure(i, state)).collect(); - if vals.iter().all(SymVal::is_known) { - SymVal::Struct { - ctor: "list".into(), - fields: vals - .into_iter() - .enumerate() - .map(|(i, v)| (i.to_string(), v)) - .collect(), - } - } else { - SymVal::Unknown - } - } - PureExpr::Map(entries) => { - let vals: Vec<(String, SymVal)> = entries - .iter() - .map(|(k, v)| (k.clone(), eval_pure(v, state))) - .collect(); - if vals.iter().all(|(_, v)| v.is_known()) { - SymVal::Struct { - ctor: "map".into(), - fields: vals, - } - } else { - SymVal::Unknown - } - } - PureExpr::Interp(_) => SymVal::Unknown, - PureExpr::Ctor { name, args } => eval_ctor(name, args, state), - } -} - -/// 内联构造器(与 `mqResultOk`/`mqResultError`/`mqValueOr` 语义一致)。 -fn eval_ctor(name: &str, args: &[PureExpr], state: &HashMap) -> SymVal { - let vals: Vec = args.iter().map(|a| eval_pure(a, state)).collect(); - match (name, vals.as_slice()) { - ("result.ok", [v]) => SymVal::Struct { - ctor: "result.ok".into(), - fields: vec![ - ("ok".into(), SymVal::Bool(true)), - ("value".into(), v.clone()), - ("error".into(), SymVal::None), - ], - }, - ("result.error", [code, message, operation]) => SymVal::Struct { - ctor: "result.error".into(), - fields: vec![ - ("ok".into(), SymVal::Bool(false)), - ("error".into(), code.clone()), - ("message".into(), message.clone()), - ("operation".into(), operation.clone()), - ("value".into(), SymVal::None), - ], - }, - ("result.value_or", [r, default]) => match r { - SymVal::Struct { ctor, fields } - if ctor == "result.ok" => - { - fields - .iter() - .find(|(k, _)| k == "value") - .map(|(_, v)| v.clone()) - .unwrap_or(default.clone()) - } - SymVal::Struct { ctor, .. } if ctor == "result.error" => default.clone(), - _ => SymVal::Unknown, - }, - _ => SymVal::Unknown, - } -} - -fn eval_bin( - operator: crate::prove::ir::BinOp, - left: &PureExpr, - right: &PureExpr, - state: &HashMap, -) -> SymVal { - use crate::prove::ir::BinOp as B; - let l = eval_pure(left, state); - let r = eval_pure(right, state); - match (operator, l, r) { - (B::Add, SymVal::Int(a), SymVal::Int(b)) => SymVal::Int(a.wrapping_add(b)), - (B::Sub, SymVal::Int(a), SymVal::Int(b)) => SymVal::Int(a.wrapping_sub(b)), - (B::Mul, SymVal::Int(a), SymVal::Int(b)) => SymVal::Int(a.wrapping_mul(b)), - (B::Div, SymVal::Int(a), SymVal::Int(b)) if b != 0 => SymVal::Int(a / b), - (B::Eq, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a == b), - (B::Eq, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a == b), - (B::Eq, SymVal::Text(a), SymVal::Text(b)) => SymVal::Bool(a == b), - (B::Ne, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a != b), - (B::Ne, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a != b), - (B::Ne, SymVal::Text(a), SymVal::Text(b)) => SymVal::Bool(a != b), - (B::Lt, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a < b), - (B::Le, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a <= b), - (B::Gt, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a > b), - (B::Ge, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a >= b), - (B::And, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a && b), - (B::Or, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a || b), - _ => SymVal::Unknown, - } -} - -// --------------------------------------------------------------------------- -// 定理检查(§5.3 第 4–5 步) -// --------------------------------------------------------------------------- - -/// 前提原子(F5 区间 / F4 自由布尔)。 -#[derive(Debug, Clone)] -pub enum PremiseAtom { - Interval { var: String, op: Cmp, val: i64 }, - FreeBool { op: String, key: String, expected: bool }, - Literal(bool), - /// 超出片段的前提 → 不使用(相关定理 unverified)。 - Opaque, -} - -pub fn parse_premise(text: &str) -> Option { - let toks = tokenize_claim(text).ok()?; - let (_, ast) = parse_claim_expr(&toks).ok()?; - premise_atom(&ast) -} - -fn premise_atom(ast: &ClaimAst) -> Option { - match ast { - ClaimAst::Bin { op, left, right } => { - let cmp = match *op { - "<" => Cmp::Lt, - "≤" => Cmp::Le, - ">" => Cmp::Gt, - "≥" => Cmp::Ge, - "=" => Cmp::Eq, - "≠" => Cmp::Ne, - _ => return None, - }; - match (left.as_ref(), right.as_ref()) { - (ClaimAst::Var(v), ClaimAst::Lit(CTok::Int(c))) => { - Some(PremiseAtom::Interval { var: v.clone(), op: cmp, val: *c }) - } - (ClaimAst::Lit(CTok::Int(c)), ClaimAst::Var(v)) => { - Some(PremiseAtom::Interval { var: v.clone(), op: cmp.flip(), val: *c }) - } - // `access(结果, "ok") = True/False` 形前提。 - (ClaimAst::Call { name, args }, ClaimAst::Lit(CTok::Bool(b))) - if name == "access" && args.len() == 2 => - { - let (base, key) = access_parts(&args[0], &args[1])?; - Some(PremiseAtom::FreeBool { op: base, key, expected: *b }) - } - _ => None, - } - } - ClaimAst::Lit(CTok::Bool(b)) => Some(PremiseAtom::Literal(*b)), - _ => None, - } -} - -impl Cmp { - fn flip(self) -> Cmp { - match self { - Cmp::Lt => Cmp::Gt, - Cmp::Le => Cmp::Ge, - Cmp::Gt => Cmp::Lt, - Cmp::Ge => Cmp::Le, - Cmp::Eq => Cmp::Eq, - Cmp::Ne => Cmp::Ne, - } - } -} - -/// `结果.ok` / `access(结果, "ok")` → (主体名, 字段)。 -fn access_parts(base: &ClaimAst, key: &ClaimAst) -> Option<(String, String)> { - let ClaimAst::Var(v) = base else { - return None; - }; - let (root, field) = match v.split_once('.') { - Some((r, f)) => (r.to_string(), Some(f.to_string())), - None => (v.clone(), None), - }; - if let Some(f) = field { - return Some((root, f)); - } - let ClaimAst::Lit(CTok::Text(k)) = key else { - return None; - }; - Some((root, k.clone())) -} - -/// 结论的结构化形态(离线可判定的子集)。 -#[derive(Debug, Clone)] -pub enum Conclusion { - /// `<主体>.<字段> = true/false`(字段布尔;主体可为 结果/中间变量)。 - FieldBool { subject: String, field: String, expected: bool }, - /// `包含(轨迹, "s")` / 其否定。 - TraceContains { item: String, expected: bool }, - /// `长度(轨迹) ⋈ n`。 - TraceLen { op: Cmp, val: i64 }, - /// `x ⋈ c`(参数区间,F5)。 - ParamInterval { var: String, op: Cmp, val: i64 }, - /// `且`/`或`/`非` 组合。 - Not(Box), - And(Box, Box), - Or(Box, Box), - /// 超出片段。 - Opaque(String), -} - -pub fn parse_conclusion(text: &str) -> Conclusion { - let toks = match tokenize_claim(text) { - Ok(t) => t, - Err(e) => return Conclusion::Opaque(e), - }; - let (_, ast) = match parse_claim_expr(&toks) { - Ok(x) => x, - Err(e) => return Conclusion::Opaque(e), - }; - conclusion_of(&ast) -} - -fn conclusion_of(ast: &ClaimAst) -> Conclusion { - match ast { - ClaimAst::Bin { op, left, right } => match *op { - "且" => Conclusion::And( - Box::new(conclusion_of(left)), - Box::new(conclusion_of(right)), - ), - "或" => Conclusion::Or( - Box::new(conclusion_of(left)), - Box::new(conclusion_of(right)), - ), - _ => { - // 字段布尔:`结果.ok = True` / `审核.ok = True` … - if let Some(c) = field_bool(op, left, right) { - return c; - } - // 轨迹谓词。 - if let Some(c) = trace_conclusion(op, left, right) { - return c; - } - // 参数区间。 - if let Some(c) = param_interval(op, left, right) { - return c; - } - Conclusion::Opaque(format!("不可判定的比较 {op}")) - } - }, - ClaimAst::Un { op, expr } if *op == "非" => { - Conclusion::Not(Box::new(conclusion_of(expr))) - } - ClaimAst::Call { name, args } - if name == "包含" && args.len() == 2 => - { - match args.first() { - Some(ClaimAst::Var(v)) if v == "轨迹" => match &args[1] { - ClaimAst::Lit(CTok::Text(s)) => Conclusion::TraceContains { - item: s.clone(), - expected: true, - }, - _ => Conclusion::Opaque("包含 的成员须是文本字面量".into()), - }, - _ => Conclusion::Opaque("包含 只支持轨迹".into()), - } - } - _ => Conclusion::Opaque("不可判定的结论形状".into()), - } -} - -/// `X.f = b`(X 是 结果/中间变量/access 调用)→ FieldBool。 -fn field_bool(op: &str, left: &ClaimAst, right: &ClaimAst) -> Option { - let expected = match (op, right) { - ("=", ClaimAst::Lit(CTok::Bool(b))) => *b, - ("≠", ClaimAst::Lit(CTok::Bool(b))) => !*b, - _ => return None, - }; - let (subject, field): (String, String) = match left { - ClaimAst::Var(v) => { - let (r, f) = v.split_once('.')?; - (r.to_string(), f.to_string()) - } - ClaimAst::Call { name, args } if name == "access" && args.len() == 2 => { - access_parts(&args[0], &args[1])? - } - _ => return None, - }; - Some(Conclusion::FieldBool { - subject, - field, - expected, - }) -} - -/// 轨迹结论:`包含(轨迹, "s") ⋈ Bool` / `长度(轨迹) ⋈ n`。 -fn trace_conclusion(op: &str, left: &ClaimAst, right: &ClaimAst) -> Option { - match left { - ClaimAst::Call { name, args } if name == "包含" && args.len() == 2 => { - let ClaimAst::Var(v) = args.first()? else { - return None; - }; - if v != "轨迹" { - return None; - } - let ClaimAst::Lit(CTok::Text(s)) = args.get(1)? else { - return None; - }; - let expected = match (op, right) { - ("=", ClaimAst::Lit(CTok::Bool(b))) => *b, - ("≠", ClaimAst::Lit(CTok::Bool(b))) => !*b, - _ => return None, - }; - Some(Conclusion::TraceContains { - item: s.clone(), - expected, - }) - } - ClaimAst::Call { name, args } if name == "长度" && args.len() == 1 => { - let ClaimAst::Var(v) = args.first()? else { - return None; - }; - if v != "轨迹" { - return None; - } - let ClaimAst::Lit(CTok::Int(n)) = right else { - return None; - }; - let cmp = match op { - "=" => Cmp::Eq, - "≠" => Cmp::Ne, - "<" => Cmp::Lt, - "≤" => Cmp::Le, - ">" => Cmp::Gt, - "≥" => Cmp::Ge, - _ => return None, - }; - Some(Conclusion::TraceLen { op: cmp, val: *n }) - } - _ => None, - } -} - -/// 参数区间结论:`金额 > 9999` 之类。 -fn param_interval(op: &str, left: &ClaimAst, right: &ClaimAst) -> Option { - let cmp = match op { - "<" => Cmp::Lt, - "≤" => Cmp::Le, - ">" => Cmp::Gt, - "≥" => Cmp::Ge, - "=" => Cmp::Eq, - "≠" => Cmp::Ne, - _ => return None, - }; - match (left, right) { - (ClaimAst::Var(v), ClaimAst::Lit(CTok::Int(c))) => Some(Conclusion::ParamInterval { - var: v.clone(), - op: cmp, - val: *c, - }), - (ClaimAst::Lit(CTok::Int(c)), ClaimAst::Var(v)) => Some(Conclusion::ParamInterval { - var: v.clone(), - op: cmp.flip(), - val: *c, - }), - _ => None, - } -} - -/// 一条路径上的结论求值结果。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Truth { - True, - False, - Unknown, -} - -/// 对一条路径检查 `前提 ∧ 路径条件 ⊢ 结论`(§5.3 第 4 步)。 -/// 返回 (真值, 关闭理由)。Unknown = 该路径关闭不了(不猜)。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Closure { - pub truth: Truth, - /// literal / trace / hypothesis / interval / atom(§5.4 证书)。 - pub reason: &'static str, -} - -pub fn check_path( - path: &PathRecord, - premise: Option<&PremiseAtom>, - conclusion: &Conclusion, -) -> Closure { - // 前提必须先可用:超片段前提 → 路径关不了。 - if let Some(PremiseAtom::Opaque) = premise { - return Closure { truth: Truth::Unknown, reason: "premise" }; - } - // 前提与路径条件的合取做区间 + 自由布尔假设。 - let intervals = intervals_of(path, premise); - let free_bools = free_bools_of(path, premise); - - // 可行性:前提区间与路径条件矛盾(交集为空)→ 路径不可行,空真关闭。 - if !feasible(&intervals) { - return Closure { truth: Truth::True, reason: "infeasible" }; - } - - let truth = eval_conclusion(conclusion, path, &intervals, &free_bools); - if truth == Truth::Unknown { - return Closure { truth: Truth::Unknown, reason: "unknown" }; - } - let reason = closure_reason(conclusion, path, premise); - Closure { truth, reason } -} - -/// 区间交集是否非空(可行域检查;无约束的变量视为可行)。 -fn feasible(intervals: &[(String, Cmp, i64)]) -> bool { - use std::collections::BTreeMap; - let mut bounds: BTreeMap, Option)> = BTreeMap::new(); - let mut exacts: BTreeMap> = BTreeMap::new(); - for (var, op, val) in intervals { - let e = bounds - .entry(var.clone()) - .or_insert((None, None)); - match op { - Cmp::Gt => e.0 = Some(e.0.map_or(val + 1, |l: i64| l.max(val + 1))), - Cmp::Ge => e.0 = Some(e.0.map_or(*val, |l: i64| l.max(*val))), - Cmp::Lt => e.1 = Some(e.1.map_or(val - 1, |u: i64| u.min(val - 1))), - Cmp::Le => e.1 = Some(e.1.map_or(*val, |u: i64| u.min(*val))), - Cmp::Eq => exacts.entry(var.clone()).or_default().push(*val), - Cmp::Ne => {} - } - } - for (var, vals) in &exacts { - if vals.iter().any(|v| vals[0] != *v) { - return false; // x = c1 ∧ x = c2, c1≠c2 → 不可行 - } - let c = vals[0]; - if let Some((lo, hi)) = bounds.get(var) { - if lo.map_or(false, |l| l > c) || hi.map_or(false, |h| h < c) { - return false; - } - } - } - bounds.iter().all(|(_, (lo, hi))| match (lo, hi) { - (Some(l), Some(h)) => l <= h, - _ => true, - }) -} - -/// 收集本路径可用的区间约束:路径条件 + 前提。 -fn intervals_of(path: &PathRecord, premise: Option<&PremiseAtom>) -> Vec<(String, Cmp, i64)> { - let mut out = Vec::new(); - for atom in &path.atoms { - if let PathAtom::Interval { var, op, val } = atom { - out.push((var.clone(), *op, *val)); - } - } - if let Some(PremiseAtom::Interval { var, op, val }) = premise { - out.push((var.clone(), *op, *val)); - } - out -} - -fn free_bools_of(path: &PathRecord, premise: Option<&PremiseAtom>) -> Vec<(String, String, bool)> { - let mut out = Vec::new(); - for atom in &path.atoms { - if let PathAtom::FreeBool { op, key, expected } = atom { - out.push((op.clone(), key.clone(), *expected)); - } - } - if let Some(PremiseAtom::FreeBool { op, key, expected }) = premise { - out.push((op.clone(), key.clone(), *expected)); - } - out -} - -/// 结论求值(结构代入:主体变量来自路径快照,参数走区间/自由布尔)。 -fn eval_conclusion( - conclusion: &Conclusion, - path: &PathRecord, - intervals: &[(String, Cmp, i64)], - free_bools: &[(String, String, bool)], -) -> Truth { - let trace: &[String] = &path.trace; - let lookup = |subject: &str| -> Option { - if subject == "结果" { - Some(path.result.clone()) - } else { - path.vars - .iter() - .find(|(k, _)| k == subject) - .map(|(_, v)| v.clone()) - } - }; - match conclusion { - Conclusion::FieldBool { subject, field, expected } => { - // 主体是内联构造器 → 结构化(F3);是 OpResult → 自由原子(F4)。 - let Some(value) = lookup(subject) else { - return Truth::Unknown; - }; - match value { - SymVal::Struct { fields, .. } => match fields.iter().find(|(k, _)| k == field) { - Some((_, SymVal::Bool(b))) => { - if b == expected { - Truth::True - } else { - Truth::False - } - } - _ => Truth::Unknown, - }, - SymVal::OpResult(op) => { - // 自由原子:路径条件或前提里有同键判定才能关闭。 - match free_bools - .iter() - .find(|(o, k, _)| *o == op && k == field) - { - Some((_, _, v)) => { - if *v == *expected { - Truth::True - } else { - Truth::False - } - } - None => Truth::Unknown, - } - } - _ => Truth::Unknown, - } - } - Conclusion::TraceContains { item, expected } => { - let has = trace.iter().any(|op| op == item); - if has == *expected { - Truth::True - } else { - Truth::False - } - } - Conclusion::TraceLen { op, val } => { - let n = trace.len() as i64; - if op.holds(n, *val) { - Truth::True - } else { - Truth::False - } - } - Conclusion::ParamInterval { var, op, val } => { - interval_entailed(intervals, var, *op, *val) - } - Conclusion::Not(inner) => { - eval_conclusion(inner, path, intervals, free_bools).invert() - } - Conclusion::And(a, b) => { - let (ta, tb) = ( - eval_conclusion(a, path, intervals, free_bools), - eval_conclusion(b, path, intervals, free_bools), - ); - match (ta, tb) { - (Truth::False, _) | (_, Truth::False) => Truth::False, - (Truth::True, Truth::True) => Truth::True, - _ => Truth::Unknown, - } - } - Conclusion::Or(a, b) => { - let (ta, tb) = ( - eval_conclusion(a, path, intervals, free_bools), - eval_conclusion(b, path, intervals, free_bools), - ); - match (ta, tb) { - (Truth::True, _) | (_, Truth::True) => Truth::True, - (Truth::False, Truth::False) => Truth::False, - _ => Truth::Unknown, - } - } - Conclusion::Opaque(_) => Truth::Unknown, - } -} - -impl Truth { - fn invert(self) -> Truth { - match self { - Truth::True => Truth::False, - Truth::False => Truth::True, - Truth::Unknown => Truth::Unknown, - } - } -} - -/// F5 蕴含:区间集合是否迫使 `var ⋈ val` 成立。 -/// True = 区间整体落在满足侧;False = 整体落在违反侧(可反例);否则不猜。 -fn interval_entailed(intervals: &[(String, Cmp, i64)], var: &str, op: Cmp, val: i64) -> Truth { - let mut lower: Option = None; - let mut upper: Option = None; - let mut exact: Option = None; - let mut conflict = false; - for (v, o, c) in intervals { - if v != var { - continue; - } - match o { - Cmp::Gt => lower = Some(lower.map_or(c + 1, |l: i64| l.max(c + 1))), - Cmp::Ge => lower = Some(lower.map_or(*c, |l: i64| l.max(*c))), - Cmp::Lt => upper = Some(upper.map_or(c - 1, |u: i64| u.min(c - 1))), - Cmp::Le => upper = Some(upper.map_or(*c, |u: i64| u.min(*c))), - Cmp::Eq => { - if let Some(e) = exact { - if e != *c { - conflict = true; - } - } - exact = Some(*c); - } - Cmp::Ne => {} - } - } - let _ = conflict; // 约束冲突保守当作"不蕴含"处理(不判 False) - if let Some(e) = exact { - // 精确值还要落在区间内才可信。 - let in_range = lower.map_or(true, |l| e >= l) && upper.map_or(true, |u| e <= u); - if in_range { - return if op.holds(e, val) { - Truth::True - } else { - Truth::False - }; - } - return Truth::Unknown; - } - // 正向闭包(True)只认**字面出现**的原子:区间蕴含(如 金额 > 10000 ⊢ - // 金额 > 9999)数学上成立,但当前 Lean 脚本没有 Val 比较的传递引理, - // simp+omega 关不掉——离线先于 Lean 关闭即触发 proof.divergence。 - // 保守:字面匹配 → hypothesis 关闭;否则不猜(等库补传递引理再放开)。 - for (v, o, c) in intervals { - if v == var && *o == op && *c == val { - return Truth::True; - } - } - // False:整段区间违反目标 → 确定性否定(反例见证)。这在数学上成立 - // (区间端点即见证),Lean 侧同样证不出该定理——两侧一致 unproved。 - let violated = match op { - Cmp::Gt => upper.map_or(false, |u| u <= val), - Cmp::Ge => upper.map_or(false, |u| u < val), - Cmp::Lt => lower.map_or(false, |l| l >= val), - Cmp::Le => lower.map_or(false, |l| l > val), - Cmp::Eq => lower.map_or(false, |l| l > val) || upper.map_or(false, |u| u < val), - Cmp::Ne => false, // ≠ 无法用区间否定(需精确值) - }; - if violated { - return Truth::False; - } - Truth::Unknown -} - -/// 关闭理由(§5.4 证书字段)。 -fn closure_reason(conclusion: &Conclusion, path: &PathRecord, premise: Option<&PremiseAtom>) -> &'static str { - match conclusion { - Conclusion::FieldBool { subject, .. } => { - let value = if subject == "结果" { - Some(path.result.clone()) - } else { - path.vars - .iter() - .find(|(k, _)| k == subject) - .map(|(_, v)| v.clone()) - }; - match value { - Some(SymVal::Struct { .. }) => "literal", - Some(SymVal::OpResult(_)) => "hypothesis", - _ => "unknown", - } - } - Conclusion::TraceContains { .. } | Conclusion::TraceLen { .. } => "trace", - Conclusion::ParamInterval { .. } => { - if premise.is_some() { - "interval" - } else { - "interval" - } - } - Conclusion::Not(inner) => closure_reason(inner, path, premise), - Conclusion::And(a, _) | Conclusion::Or(a, _) => closure_reason(a, path, premise), - Conclusion::Opaque(_) => "unknown", - } -} - -/// 检查一条定理(§5.3 第 5 步):全部路径关闭 → checked; -/// 某路径确定性为假 → unproved + 反例(§5.5 三条件);否则 unverified。 -pub fn check_claim(fn_plan: &FnPlan, claim: &crate::prove::ir::ClaimPlan) -> OfflineVerdict { - let paths = execute(fn_plan); - if paths.is_empty() { - return OfflineVerdict::Unverified { - reason: "无可枚举路径".into(), - }; - } - if std::env::var("MARQDO_PROOF_DEBUG").is_ok_and(|v| v == "1") { - for p in execute(fn_plan) { - eprintln!( - "[offline-path #{}] atoms={:?} result={:?} trace={:?} vars={:?} opaque={}", - p.id, p.atoms, p.result, p.trace, p.vars, p.opaque - ); - } - } - let premise = claim.premise.as_deref().and_then(parse_premise); - // 前提文本存在但解析不出原子 → 超片段。 - let premise: Option = match (&claim.premise, premise) { - (Some(_), None) => Some(PremiseAtom::Opaque), - (_, p) => p, - }; - let conclusion = parse_conclusion(&claim.conclusion); - - let mut closed = 0usize; - let mut first_false: Option<(&PathRecord, Closure)> = None; - for path in &paths { - if path.opaque { - return OfflineVerdict::Unverified { - reason: "路径超出片段(不透明条件/表达式)".into(), - }; - } - let closure = check_path(path, premise.as_ref(), &conclusion); - match closure.truth { - Truth::True => closed += 1, - Truth::False => { - if first_false.is_none() { - first_false = Some((path, closure)); - } - } - Truth::Unknown => { - return OfflineVerdict::Unverified { - reason: format!("路径 #{} 关闭不了(不猜)", path.id), - } - } - } - } - if let Some((path, _)) = first_false { - // §5.5 反例三条件:结论确定性为假 ✓;路径可满足(区间取见证)✓; - // 路径条件不含自由布尔原子(否则可能凑出不存在的组合)。 - let has_free_bool = path - .atoms - .iter() - .any(|a| matches!(a, PathAtom::FreeBool { .. })); - if has_free_bool { - return OfflineVerdict::Unverified { - reason: "反例路径含自由布尔原子(保守放弃见证)".into(), - }; - } - let counterexample = witness(fn_plan, path, premise.as_ref()); - return OfflineVerdict::Unproved { counterexample }; - } - OfflineVerdict::Checked { cases: closed } -} - -/// 从区间端点取见证参数值(§5.5)。无区间约束的整型参数取 0(空约束平凡可满足)。 -fn witness( - fn_plan: &FnPlan, - path: &PathRecord, - premise: Option<&PremiseAtom>, -) -> Option { - let mut assignments: Vec<(String, i64)> = Vec::new(); - let mut constraints: Vec<(String, Cmp, i64)> = Vec::new(); - for atom in &path.atoms { - if let PathAtom::Interval { var, op, val } = atom { - constraints.push((var.clone(), *op, *val)); - } - } - if let Some(PremiseAtom::Interval { var, op, val }) = premise { - constraints.push((var.clone(), *op, *val)); - } - // 按 var 聚合求可行点:下界取 max+?,上界取 min-?,取中点。 - use std::collections::BTreeMap; - let mut bounds: BTreeMap, Option)> = BTreeMap::new(); - for (var, op, val) in &constraints { - let e = bounds.entry(var.clone()).or_insert((None, None)); - match op { - Cmp::Gt => e.0 = Some(e.0.map_or(val + 1, |l: i64| l.max(val + 1))), - Cmp::Ge => e.0 = Some(e.0.map_or(*val, |l: i64| l.max(*val))), - Cmp::Lt => e.1 = Some(e.1.map_or(val - 1, |u: i64| u.min(val - 1))), - Cmp::Le => e.1 = Some(e.1.map_or(*val, |u: i64| u.min(*val))), - Cmp::Eq => { - // 等式约束与区间冲突时放弃见证(保守)。 - if let (Some(l), Some(u)) = (e.0, e.1) { - if l > *val || u < *val { - return None; - } - } - e.0 = Some(*val); - e.1 = Some(*val); - } - Cmp::Ne => {} - } - } - for (var, (lo, hi)) in bounds { - match (lo, hi) { - (Some(l), Some(h)) if l > h => return None, // 路径不可满足(不应发生) - (Some(l), Some(h)) => assignments.push((var, l + (h - l) / 2)), - (Some(l), None) => assignments.push((var, l)), - (None, Some(h)) => assignments.push((var, h)), - (None, None) => {} - } - } - if assignments.is_empty() { - // 无任何区间约束:整型参数取 0(空约束下任意值都满足该路径)。 - for p in &fn_plan.params { - if matches!(p.ty, crate::prove::ir::PlanTy::Int) { - assignments.push((p.name.clone(), 0)); - } - } - } - if assignments.is_empty() { - return None; - } - let detail = assignments - .iter() - .map(|(k, v)| format!("{k} = {v}")) - .collect::>() - .join(", "); - Some(Counterexample { - assignments, - path_id: path.id, - detail, - }) -} - -/// 整个文件的离线判定:每函数每定理。 -pub fn check_plan(plan: &Plan) -> Vec<(String, String, OfflineVerdict)> { - let mut out = Vec::new(); - for f in &plan.functions { - for c in &f.claims { - let verdict = check_claim(f, c); - out.push((f.name.clone(), c.id.clone(), verdict)); - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::prove::ir::{ - BinOp, ClaimPlan, Expr, FnPlan, ParamPlan, Plan, PlanTy, PureExpr, Step, - }; - - fn ledger_fn(steps: Vec, claims: Vec) -> FnPlan { - FnPlan { - name: "台账.记录".into(), - params: vec![ParamPlan { - name: "金额".into(), - ty: PlanTy::Int, - has_default: false, - }], - result_ty: PlanTy::Any, - ops: vec![], - steps, - effects: vec![], - claims, - assumptions: vec![], - } - } - - /// `结果 = result.ok(金额)`;`返回 结果`。 - fn literal_ok_steps() -> Vec { - vec![ - Step::Bind { - var: "结果".into(), - expr: Expr::Pure(PureExpr::Ctor { - name: "result.ok".into(), - args: vec![PureExpr::Var("金额".into())], - }), - line: 10, - }, - Step::Return { - expr: Expr::Pure(PureExpr::Var("结果".into())), - line: 11, - }, - ] - } - - #[test] - fn f3_literal_result_field_closes() { - let f = ledger_fn( - literal_ok_steps(), - vec![ClaimPlan { - id: "必有回执".into(), - premise: None, - conclusion: "结果.ok = True".into(), - tactic: None, - line: 5, - }], - ); - match check_claim(&f, &f.claims[0]) { - OfflineVerdict::Checked { cases } => assert!(cases >= 1), - other => panic!("F3 应当 checked:{other:?}"), - } - } - - #[test] - fn f3_false_claim_refuted_with_counterexample() { - let f = ledger_fn( - literal_ok_steps(), - vec![ClaimPlan { - id: "没有回执".into(), - premise: None, - conclusion: "结果.ok = False".into(), - tactic: None, - line: 5, - }], - ); - match check_claim(&f, &f.claims[0]) { - OfflineVerdict::Unproved { counterexample } => { - assert!(counterexample.is_some(), "确定性否定必须带见证"); - } - other => panic!("F3 反例应当 unproved:{other:?}"), - } - } - - #[test] - fn f2_trace_length_and_contains() { - // 金额 > 10000 → 轨迹 = [人工审核];否则空。 - let steps = vec![Step::If { - cond: PureExpr::Bin { - operator: BinOp::Gt, - left: Box::new(PureExpr::Var("金额".into())), - right: Box::new(PureExpr::Int(10000)), - }, - then: vec![Step::Trace { - op: "调用:人工审核".into(), - args: vec![], - line: 20, - }], - otherwise: vec![], - line: 19, - }]; - let mk = |id: &str, conclusion: &str, premise: Option<&str>| ClaimPlan { - id: id.into(), - premise: premise.map(Into::into), - conclusion: conclusion.into(), - tactic: None, - line: 5, - }; - let f = ledger_fn( - steps, - vec![ - mk("恰一步", "长度(轨迹) = 1", Some("金额 > 10000")), - mk("恰零步", "长度(轨迹) = 0", None), - mk("必经人工", "包含(轨迹, \"人工审核\")", Some("金额 > 10000")), - ], - ); - match check_claim(&f, &f.claims[0]) { - OfflineVerdict::Checked { .. } => {} - other => panic!("F2 长度应 checked:{other:?}"), - } - // 无前提:两条路径都要关(一条长 1、一条长 0)→ 长度=0 关不了。 - match check_claim(&f, &f.claims[1]) { - OfflineVerdict::Unproved { .. } | OfflineVerdict::Unverified { .. } => {} - other => panic!("无前提的 长度=0 不得 checked:{other:?}"), - } - match check_claim(&f, &f.claims[2]) { - OfflineVerdict::Checked { .. } => {} - other => panic!("F2 包含应 checked:{other:?}"), - } - } - - #[test] - fn f4_free_bool_atom_via_hypothesis() { - // 审核 = op(金额);1. 审核.ok = True → 路径条件为自由布尔; - // 结论 `审核.ok = True` 由 hypothesis 关闭。 - let steps = vec![ - Step::Bind { - var: "审核".into(), - expr: Expr::Op { - id: "调用:人工审核".into(), - args: vec![PureExpr::Var("金额".into())], - }, - line: 30, - }, - Step::If { - cond: PureExpr::Access { - base: Box::new(PureExpr::Var("审核".into())), - key: "ok".into(), - }, - then: vec![Step::Return { - expr: Expr::Pure(PureExpr::Var("审核".into())), - line: 32, - }], - otherwise: vec![Step::Return { - expr: Expr::Pure(PureExpr::Ctor { - name: "result.ok".into(), - args: vec![PureExpr::Text("跳过".into())], - }), - line: 34, - }], - line: 31, - }, - ]; - // 自由原子二分后的 else 路径上 `审核.ok = False` 是**真实可能**的, - // 所以单边结论只能保守 unverified(不猜)。 - let f = ledger_fn( - steps, - vec![ - ClaimPlan { - id: "审核必有结论".into(), - premise: Some("金额 > 10000".into()), - conclusion: "审核.ok = True 或 审核.ok = False".into(), - tactic: None, - line: 5, - }, - ClaimPlan { - id: "审核必过".into(), - premise: Some("金额 > 10000".into()), - conclusion: "审核.ok = True".into(), - tactic: None, - line: 6, - }, - ], - ); - match check_claim(&f, &f.claims[0]) { - OfflineVerdict::Checked { .. } => {} - other => panic!("F4 hypothesis(或式)应 checked:{other:?}"), - } - match check_claim(&f, &f.claims[1]) { - OfflineVerdict::Unverified { .. } => {} - other => panic!("自由原子单边结论必须保守 unverified:{other:?}"), - } - } - - #[test] - fn f5_interval_closure_scope() { - // 字面重述(同原子):hypothesis 关闭(Lean 侧假设就在那里)。 - let f = ledger_fn( - literal_ok_steps(), - vec![ - ClaimPlan { - id: "前提重述".into(), - premise: Some("金额 > 10000".into()), - conclusion: "金额 > 10000".into(), - tactic: None, - line: 5, - }, - // 区间蕴含(10000 ⊢ 9999)数学上真,但当前 Lean 脚本无 - // Val 比较传递引理——离线必须同样保守(§5.4 单调性)。 - ClaimPlan { - id: "区间蕴含".into(), - premise: Some("金额 > 10000".into()), - conclusion: "金额 > 9999".into(), - tactic: None, - line: 6, - }, - ], - ); - match check_claim(&f, &f.claims[0]) { - OfflineVerdict::Checked { .. } => {} - other => panic!("字面重述应 checked:{other:?}"), - } - match check_claim(&f, &f.claims[1]) { - OfflineVerdict::Unverified { .. } => {} - other => panic!("无传递引理时区间蕴含必须保守:{other:?}"), - } - } - - #[test] - fn f5_interval_refutation_gives_witness() { - let f = ledger_fn( - literal_ok_steps(), - vec![ClaimPlan { - id: "小额断言".into(), - premise: Some("金额 > 10000".into()), - conclusion: "金额 < 100".into(), - tactic: None, - line: 5, - }], - ); - match check_claim(&f, &f.claims[0]) { - OfflineVerdict::Unproved { counterexample } => { - let c = counterexample.expect("区间分离必须给见证"); - assert!(c.detail.contains("金额")); - } - other => panic!("F5 分离应 unproved + 见证:{other:?}"), - } - } - - #[test] - fn beyond_fragment_stays_unverified() { - // 文本比较(字符串序)超出片段 → 不猜。 - let f = ledger_fn( - literal_ok_steps(), - vec![ClaimPlan { - id: "文本比较".into(), - premise: None, - conclusion: "结果.value = \"x\"".into(), - tactic: None, - line: 5, - }], - ); - match check_claim(&f, &f.claims[0]) { - OfflineVerdict::Unverified { .. } | OfflineVerdict::Checked { .. } => {} - other => panic!("超片段不得 unproved:{other:?}"), - } - } - - #[test] - fn plan_wide_check_runs_all() { - let f = ledger_fn( - literal_ok_steps(), - vec![ClaimPlan { - id: "必有回执".into(), - premise: None, - conclusion: "结果.ok = True".into(), - tactic: None, - line: 5, - }], - ); - let plan = Plan { - schema: crate::prove::ir::SCHEMA, - module: "测试".into(), - source_sha256: "a".repeat(64), - functions: vec![f], - }; - let results = check_plan(&plan); - assert_eq!(results.len(), 1); - assert!(matches!(results[0].2, OfflineVerdict::Checked { .. })); - } -} diff --git a/src/prove/proof_check.rs b/src/prove/proof_check.rs deleted file mode 100755 index 822ba8b..0000000 --- a/src/prove/proof_check.rs +++ /dev/null @@ -1,822 +0,0 @@ -//! `check --proof`:定理表的静态校验(设计 §7;默认关)。 -//! -//! 校验项(全部 advisory 之外都是 Error 级诊断): -//! - `proof.claim_malformed` 表头命中定理词表但列形不齐 -//! - `proof.claim_ambiguous` 同时有 `类型` 与 `结论` 列 -//! - `proof.claim_misplaced` 合法定理表出现在首条可执行语句之后 -//! - `proof.claim_duplicate` 同一函数内定理 id 重复 -//! - `proof.claim_unknown_symbol` 结论/前提引用了受限符号集之外的名字 -//! - `proof.claim_unsupported` 谓词超出封闭集合(包含/长度/下标)或元数不对 -//! - `proof.name_shadow` 保留名(`结果`/`轨迹`)被形参/局部变量遮蔽 - -use std::path::Path; - -use crate::ast::{Expr, Function, Module, Stmt}; -use crate::contract; -use crate::diagnostics::{Diagnostic, Severity, Span}; - -/// 定理作用域保留名(§7.3.4)。 -pub const RESERVED_CLAIM_NAMES: &[&str] = &["结果", "轨迹"]; - -/// 谓词封闭集合(§7.3.5:改集合需重新评审 ADR)。 -pub const PREDICATES: &[(&str, usize)] = &[("包含", 2), ("长度", 1), ("下标", 2)]; - -/// 入口:对整个模块做定理表校验(只看主文件;与契约检查同一范围, -/// import 库文件不重复校验——诊断的行号锚在主文件上才有意义)。 -pub fn check_proofs(module: &Module, path: Option<&Path>) -> Vec { - let mut out = Vec::new(); - let mut function_names: Vec = Vec::new(); - collect_function_names(module, &mut function_names); - // 谓词名遮蔽是模块级事实(与单个函数无关),整个模块只报一次; - // 诊断锚在被遮蔽的函数上(任意深度)。 - for pred in PREDICATES { - if function_names.iter().any(|n| n == pred.0) { - let Some(fun) = find_by_name(&module.functions, pred.0) else { - continue; - }; - out.push(proof_diag( - module, - path, - fun.span, - "proof.name_shadow", - format!( - "函数名 `{}` 与定理谓词 `{}` 同名(谓词集合封闭:包含/长度/下标)", - fun.name, pred.0 - ), - format!("把函数 `{}` 改名,避免定理表里的 `{}` 歧义", fun.name, pred.0), - )); - } - } - walk_checks(module, &module.functions, path, &mut out); - out -} - -fn walk_checks(module: &Module, funs: &[Function], path: Option<&Path>, out: &mut Vec) { - for fun in funs { - check_claim_duplicates(module, fun, path, out); - check_name_shadow(module, fun, path, out); - check_misplaced_and_malformed(module, fun, path, out); - check_claim_symbols(module, fun, path, out); - walk_checks(module, &fun.children, path, out); - } -} - -fn collect_function_names(module: &Module, out: &mut Vec) { - fn go(funs: &[Function], out: &mut Vec) { - for f in funs { - out.push(f.name.clone()); - go(&f.children, out); - } - } - go(&module.functions, out); - for child in module.import_modules.values() { - collect_function_names(child, out); - } -} - -/// 在函数树里按显示名找函数(诊断锚点用)。 -fn find_by_name<'a>(funs: &'a [Function], name: &str) -> Option<&'a Function> { - for f in funs { - if f.name == name { - return Some(f); - } - if let Some(inner) = find_by_name(&f.children, name) { - return Some(inner); - } - } - None -} - -fn proof_diag( - module: &Module, - path: Option<&Path>, - span: Span, - code: &str, - message: String, - suggestion: String, -) -> Diagnostic { - let _ = module; - Diagnostic::new(path, span, message) - .with_code(code) - .with_severity(Severity::Error) - .with_suggestion(suggestion) -} - -/// 同一函数内定理 id 重复(§7.1 规则 3)。 -fn check_claim_duplicates(module: &Module, fun: &Function, path: Option<&Path>, out: &mut Vec) { - let mut seen: Vec<&str> = Vec::new(); - for claim in &fun.claims { - if seen.contains(&claim.id.as_str()) { - out.push(proof_diag( - module, - path, - Span::new(claim.line, 1), - "proof.claim_duplicate", - format!("定理 `{}` 在 `{}` 内重复声明", claim.id, fun.name), - "定理 id 在函数内必须唯一;重命名或删除重复行".into(), - )); - } else { - seen.push(&claim.id); - } - } -} - -/// 遮蔽检查(§7.3.4):只看**自带定理表的函数**——形参 `结果`/`轨迹` 会 -/// 与该函数定理作用域的输出绑定名冲突;没有定理表的函数不受影响。 -fn check_name_shadow( - module: &Module, - fun: &Function, - path: Option<&Path>, - out: &mut Vec, -) { - if fun.claims.is_empty() { - return; - } - for param in &fun.params { - if RESERVED_CLAIM_NAMES.contains(¶m.name.as_str()) { - out.push(proof_diag( - module, - path, - param.span, - "proof.name_shadow", - format!( - "形参 `{}` 与定理作用域保留名冲突(`{}` 也要声明定理)", - param.name, - fun.name - ), - format!("把形参 `{}` 改名;`结果`/`轨迹` 在定理里指返回值与操作轨迹", param.name), - )); - } - } -} - -/// 错位与畸形:body 里仍是定理形的表(默认关时解析器不提取它们)。 -fn check_misplaced_and_malformed( - module: &Module, - fun: &Function, - path: Option<&Path>, - out: &mut Vec, -) { - let mut prefix_zone = true; - for stmt in &fun.body { - let (pairs, span) = match stmt { - Stmt::Expr { - value: Expr::Map(pairs), - span, - } => (pairs, *span), - Stmt::Expr { value: Expr::List(_), .. } => continue, - _ => { - prefix_zone = false; - continue; - } - }; - if let Some(assumption)=contract::parse_assumption_table(pairs,span.line){ - let (code,msg)=match assumption { - Ok(_)=>("proof.assumption_misplaced", - "假设表必须在第一条可执行语句之前;此处不会自动生效".to_string()), - Err(err)=>("proof.assumption_malformed",err) - }; - out.push(proof_diag(module,path,span,code,msg, - "移动并修正 | 假设 | 前置 | 后置 | 表到函数开头".into())); - continue; - } - match contract::parse_claim_table(pairs, span.line) { - Some(Ok(_rows)) => { - // 合法定理形却还在 body:一定是位置不对(prefix zone 内会被提取)。 - out.push(proof_diag( - module, - path, - span, - "proof.claim_misplaced", - format!( - "`{}` 的定理表出现在首条可执行语句之后——它是普通表,不会成为定理", - fun.name - ), - "把定理表移到函数体开头(与契约表同一槽位)".into(), - )); - } - Some(Err(err)) => { - out.push(proof_diag( - module, - path, - span, - err.code, - err.message, - "对照定理表形状:| 定理 | 结论 | 前提 | 策略 |(前提/策略可省)".into(), - )); - } - None => {} - } - let _ = prefix_zone; - } -} - -/// 受限符号集校验(§7.1 规则 4):前提只看形参;结论可加 `结果`/`轨迹`。 -fn check_claim_symbols(module: &Module, fun: &Function, path: Option<&Path>, out: &mut Vec) { - if fun.claims.is_empty() { - return; - } - let params: Vec = fun.params.iter().map(|p| p.name.clone()).collect(); - for claim in &fun.claims { - if let Some(tactic) = &claim.tactic { - if tactic != "auto" && tactic != "none" { - out.push(proof_diag( - module, - path, - Span::new(claim.line, 1), - "proof.claim_malformed", - format!("定理 `{}` 的策略 `{}` 不在 auto/none 内", claim.id, tactic), - "策略列只接受 auto(自动)或 none(永远 unverified)".into(), - )); - } - } - if let Some(premise) = &claim.premise { - check_claim_expr( - module, - path, - premise, - claim, - ¶ms, - false, - out, - ); - } - check_claim_expr(module, path, &claim.conclusion, claim, ¶ms, true, out); - } -} - -fn check_claim_expr( - module: &Module, - path: Option<&Path>, - text: &str, - claim: &crate::ast::Claim, - params: &[String], - conclusion_scope: bool, - out: &mut Vec, -) { - let tokens = match tokenize_claim(text) { - Ok(t) => t, - Err(msg) => { - out.push(proof_diag( - module, - path, - Span::new(claim.line, 1), - "proof.claim_malformed", - format!("定理 `{}` 的表达无法解析:{msg}", claim.id), - "受限表达式:名字、数字、字符串、比较/算术/布尔、包含(轨迹,x)/长度(轨迹)/下标(轨迹,i)".into(), - )); - return; - } - }; - match parse_claim_expr(&tokens) { - Ok((_, ast)) => collect_symbols( - module, - path, - claim, - &ast, - params, - conclusion_scope, - out, - ), - Err(msg) => { - out.push(proof_diag( - module, - path, - Span::new(claim.line, 1), - "proof.claim_malformed", - format!("定理 `{}` 的表达无法解析:{msg}", claim.id), - "受限表达式:名字、数字、字符串、比较/算术/布尔、包含(轨迹,x)/长度(轨迹)/下标(轨迹,i)".into(), - )); - } - } -} - -// ---------------------------------------------------------------- 受限表达式 - -#[derive(Debug, Clone, PartialEq)] -pub(crate) enum CTok { - Name(String), - Int(i64), - Num(f64), - Text(String), - Bool(bool), - Op(&'static str), - LParen, - RParen, - Comma, - Dot, -} - -/// 词法:把受限表达文本切成记号(emit 与 check 共用)。 -pub(crate) fn tokenize_claim(text: &str) -> Result, String> { - let mut out = Vec::new(); - let chars: Vec = text.chars().collect(); - let mut i = 0usize; - while i < chars.len() { - let c = chars[i]; - if c.is_whitespace() { - i += 1; - continue; - } - match c { - '(' => out.push(CTok::LParen), - ')' => out.push(CTok::RParen), - ',' | ',' => out.push(CTok::Comma), - '.' | '。' => out.push(CTok::Dot), - '"' | '“' | '”' => { - // 字符串字面量(到下一个同类引号)。 - let close = c; - let mut j = i + 1; - let mut s = String::new(); - while j < chars.len() && chars[j] != close { - s.push(chars[j]); - j += 1; - } - if j >= chars.len() { - return Err("字符串没有闭合引号".into()); - } - out.push(CTok::Text(s)); - i = j; - } - '`' => { - // `` `名字` `` → 名字。 - let mut j = i + 1; - let mut s = String::new(); - while j < chars.len() && chars[j] != '`' { - s.push(chars[j]); - j += 1; - } - if j >= chars.len() { - return Err("反引号名没有闭合".into()); - } - out.push(CTok::Name(s)); - i = j; - } - '0'..='9' => { - let mut j = i; - let mut s = String::new(); - let mut dotted = false; - while j < chars.len() && (chars[j].is_ascii_digit() || chars[j] == '.') { - if chars[j] == '.' { - if dotted { - break; - } - dotted = true; - } - s.push(chars[j]); - j += 1; - } - if dotted { - out.push(CTok::Num(s.parse::().map_err(|_| "数字解析失败")?)); - } else { - out.push(CTok::Int(s.parse::().map_err(|_| "整数解析失败")?)); - } - i = j - 1; - } - '=' => out.push(CTok::Op("=")), - '≠' | '!' => out.push(CTok::Op("≠")), - '<' => out.push(CTok::Op("<")), - '≤' => out.push(CTok::Op("≤")), - '>' => out.push(CTok::Op(">")), - '≥' => out.push(CTok::Op("≥")), - '+' => out.push(CTok::Op("+")), - '-' | '−' => out.push(CTok::Op("-")), - '*' | '×' => out.push(CTok::Op("*")), - '/' | '÷' => out.push(CTok::Op("/")), - _ => { - // 名字 / 中文词 / 关键字。 - if c.is_alphanumeric() || c == '_' { - let mut j = i; - let mut s = String::new(); - while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_' || chars[j] == '.') { - s.push(chars[j]); - j += 1; - } - i = j - 1; - match s.as_str() { - "且" | "and" => out.push(CTok::Op("且")), - "或" | "or" => out.push(CTok::Op("或")), - "非" | "not" => out.push(CTok::Op("非")), - "真" | "true" | "True" => out.push(CTok::Bool(true)), - "假" | "false" | "False" => out.push(CTok::Bool(false)), - _ => { - // `名字.字段` 已并入 s(含点)。 - out.push(CTok::Name(s)); - } - } - } else { - return Err(format!("无法识别的字符 `{c}`")); - } - } - } - i += 1; - } - Ok(out) -} - -#[derive(Debug, Clone)] -#[allow(dead_code)] // op/字面值记号保留:P1 语义求值与 Lean 脚本生成要用。 -pub(crate) enum ClaimAst { - Lit(CTok), - /// 名字(可含 `.字段`;已合并进字符串)。 - Var(String), - Call { name: String, args: Vec }, - Bin { op: &'static str, left: Box, right: Box }, - Un { op: &'static str, expr: Box }, -} - -struct P<'a> { - toks: &'a [CTok], - pos: usize, -} - -impl<'a> P<'a> { - fn peek(&self) -> Option<&CTok> { - self.toks.get(self.pos) - } - fn next(&mut self) -> Option { - let t = self.toks.get(self.pos).cloned(); - if t.is_some() { - self.pos += 1; - } - t - } - fn eat_op(&mut self, ops: &[&str]) -> Option<&'static str> { - let CTok::Op(o) = self.peek()? else { - return None; - }; - if !ops.contains(o) { - return None; - } - let hit: &'static str = match *o { - "+" => "+", - "-" => "-", - "*" => "*", - "/" => "/", - "=" => "=", - "≠" => "≠", - "<" => "<", - "≤" => "≤", - ">" => ">", - "≥" => "≥", - "且" => "且", - "或" => "或", - "非" => "非", - _ => return None, - }; - self.pos += 1; - Some(hit) - } -} - -pub(crate) fn parse_claim_expr(toks: &[CTok]) -> Result<(Vec, ClaimAst), String> { - let mut p = P { toks, pos: 0 }; - let ast = parse_or(&mut p)?; - if p.pos != toks.len() { - return Err(format!("表达式末尾有多余内容(第 {} 个记号起)", p.pos + 1)); - } - Ok((toks.to_vec(), ast)) -} - -fn parse_or(p: &mut P) -> Result { - let mut left = parse_and(p)?; - while let Some(op) = p.eat_op(&["或"]) { - let right = parse_and(p)?; - left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; - } - Ok(left) -} - -fn parse_and(p: &mut P) -> Result { - let mut left = parse_cmp(p)?; - while let Some(op) = p.eat_op(&["且"]) { - let right = parse_cmp(p)?; - left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; - } - Ok(left) -} - -fn parse_cmp(p: &mut P) -> Result { - let left = parse_add(p)?; - if let Some(op) = p.eat_op(&["=", "≠", "<", "≤", ">", "≥"]) { - let right = parse_add(p)?; - return Ok(ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }); - } - Ok(left) -} - -fn parse_add(p: &mut P) -> Result { - let mut left = parse_mul(p)?; - while let Some(op) = p.eat_op(&["+", "-"]) { - let right = parse_mul(p)?; - left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; - } - Ok(left) -} - -fn parse_mul(p: &mut P) -> Result { - let mut left = parse_unary(p)?; - while let Some(op) = p.eat_op(&["*", "/"]) { - let right = parse_unary(p)?; - left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; - } - Ok(left) -} - -fn parse_unary(p: &mut P) -> Result { - if let Some(op) = p.eat_op(&["非"]) { - let expr = parse_unary(p)?; - return Ok(ClaimAst::Un { op, expr: Box::new(expr) }); - } - if let Some(CTok::Op("-")) = p.peek() { - p.pos += 1; - let expr = parse_unary(p)?; - return Ok(ClaimAst::Un { op: "-", expr: Box::new(expr) }); - } - parse_atom(p) -} - -fn parse_atom(p: &mut P) -> Result { - match p.next() { - Some(CTok::LParen) => { - let e = parse_or(p)?; - match p.next() { - Some(CTok::RParen) => Ok(e), - _ => Err("缺少右括号".into()), - } - } - Some(t @ (CTok::Int(_) | CTok::Num(_) | CTok::Text(_) | CTok::Bool(_))) => Ok(ClaimAst::Lit(t)), - Some(CTok::Name(name)) => { - // 谓词调用:名字后紧跟 `(`。 - if matches!(p.peek(), Some(CTok::LParen)) { - p.pos += 1; - let mut args = Vec::new(); - if !matches!(p.peek(), Some(CTok::RParen)) { - loop { - args.push(parse_or(p)?); - match p.next() { - Some(CTok::Comma) => continue, - Some(CTok::RParen) => break, - _ => return Err("调用参数列表未闭合".into()), - } - } - } else { - p.pos += 1; - } - return Ok(ClaimAst::Call { name, args }); - } - Ok(ClaimAst::Var(name)) - } - other => Err(format!("这里应该是一个名字或值,得到 {other:?}")), - } -} - -/// 收集受限符号并校验(§7.1 规则 4 + §7.3.5 谓词封闭)。 -fn collect_symbols( - module: &Module, - path: Option<&Path>, - claim: &crate::ast::Claim, - ast: &ClaimAst, - params: &[String], - conclusion_scope: bool, - out: &mut Vec, -) { - match ast { - ClaimAst::Lit(_) => {} - ClaimAst::Var(name) => { - // 名字可带 `.字段`(结果.ok / 回执.value)——只校验根名字。 - let root = name.split('.').next().unwrap_or(name); - let known = params.contains(&root.to_string()) - || (conclusion_scope && RESERVED_CLAIM_NAMES.contains(&root)); - if !known { - let suggestion = crate::check::suggest_closest(root, params); - let mut d = proof_diag( - module, - path, - Span::new(claim.line, 1), - "proof.claim_unknown_symbol", - format!( - "定理 `{}` 引用了未知名字 `{root}`({}作用域只允许{})", - claim.id, - if conclusion_scope { "结论" } else { "前提" }, - if conclusion_scope { - "形参、结果、轨迹" - } else { - "形参" - } - ), - suggestion - .map(|s| format!("是不是想写 `{s}`?")) - .unwrap_or_else(|| { - if conclusion_scope { - "只引用形参与 `结果`/`轨迹`".into() - } else { - "前提里只引用形参(入口状态求值)".into() - } - }), - ); - d = d.with_severity(Severity::Error); - out.push(d); - } - } - ClaimAst::Call { name, args } => { - match PREDICATES.iter().find(|(n, _)| n == name) { - Some((_, arity)) if *arity == args.len() => {} - Some((_, arity)) => out.push(proof_diag( - module, - path, - Span::new(claim.line, 1), - "proof.claim_unsupported", - format!( - "谓词 `{name}` 需要 {arity} 个参数,定理 `{}` 给了 {} 个", - claim.id, - args.len() - ), - "谓词集合封闭:包含(轨迹,x) / 长度(轨迹) / 下标(轨迹,i)".into(), - )), - None => out.push(proof_diag( - module, - path, - Span::new(claim.line, 1), - "proof.claim_unsupported", - format!( - "定理 `{}` 调用了 `{name}`——定理里只能用包含/长度/下标三个谓词", - claim.id - ), - "谓词集合封闭(§7.3.5);要扩集合先改 ADR 0010".into(), - )), - } - for arg in args { - collect_symbols(module, path, claim, arg, params, conclusion_scope, out); - } - } - ClaimAst::Bin { left, right, .. } => { - collect_symbols(module, path, claim, left, params, conclusion_scope, out); - collect_symbols(module, path, claim, right, params, conclusion_scope, out); - } - ClaimAst::Un { expr, .. } => { - collect_symbols(module, path, claim, expr, params, conclusion_scope, out); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn parse_ok(text: &str) -> ClaimAst { - let toks = tokenize_claim(text).expect("tokenize"); - parse_claim_expr(&toks).expect("parse").1 - } - - #[test] - fn restricted_grammar_parses_design_examples() { - // 设计 §7.1 的示例句全部可解析。 - let _ = parse_ok("包含(轨迹, \"人工审核\")"); - let _ = parse_ok("金额 > 10000"); - let _ = parse_ok("结果.ok = True"); - let _ = parse_ok("长度(轨迹) = 2"); - let _ = parse_ok("下标(轨迹, 0) = \"x\""); - let _ = parse_ok("非 结果.ok = False 且 金额 ≥ 0"); - let _ = parse_ok("金额 + 1 ≤ 10 或 假"); - } - - #[test] - fn tokenizer_rejects_unterminated_strings() { - assert!(tokenize_claim("包含(轨迹, \"未闭合").is_err()); - } - - #[test] - fn reserved_outputs_render_without_field_access_prefix() { - // emit 侧翻译:结果/轨迹 是定理作用域绑定名,不加 v_ 前缀。 - let ast = parse_ok("轨迹"); - assert!(matches!(ast, ClaimAst::Var(ref n) if n == "轨迹")); - let ast = parse_ok("结果.ok"); - assert!(matches!(ast, ClaimAst::Var(ref n) if n == "结果.ok")); - } - - #[test] - fn symbol_check_reports_unknown_and_suggests() { - let module = Module::default(); - let claim = crate::ast::Claim { - id: "引用未知".into(), - conclusion: "额度 > 0".into(), - premise: None, - tactic: Some("auto".into()), - line: 3, - }; - let mut out = Vec::new(); - check_claim_expr( - &module, - None, - "额度 > 0", - &claim, - &["金额".to_string()], - true, - &mut out, - ); - assert_eq!(out.len(), 1); - assert_eq!(out[0].code, "proof.claim_unknown_symbol"); - // 最近建议(编辑距离):额度 → 金额 不够近,无建议也要有消息。 - assert!(out[0].message.contains("额度")); - } - - #[test] - fn symbol_check_accepts_params_in_premise_and_outputs_in_conclusion() { - let module = Module::default(); - let claim = crate::ast::Claim { - id: "合法".into(), - conclusion: "结果.ok = True".into(), - premise: Some("金额 > 0".into()), - tactic: None, - line: 1, - }; - let mut out = Vec::new(); - check_claim_expr( - &module, - None, - "金额 > 0", - &claim, - &["金额".to_string()], - false, - &mut out, - ); - check_claim_expr( - &module, - None, - "结果.ok = True", - &claim, - &["金额".to_string()], - true, - &mut out, - ); - assert!(out.is_empty(), "{out:?}"); - } - - #[test] - fn premise_may_not_reference_outputs() { - let module = Module::default(); - let claim = crate::ast::Claim { - id: "前提越界".into(), - conclusion: "结果.ok = True".into(), - premise: Some("轨迹 = 0".into()), - tactic: None, - line: 1, - }; - let mut out = Vec::new(); - check_claim_expr( - &module, - None, - "轨迹 = 0", - &claim, - &[], - false, - &mut out, - ); - assert!(out - .iter() - .any(|d| d.code == "proof.claim_unknown_symbol"), "{out:?}"); - } - - #[test] - fn predicate_arity_and_closure_are_enforced() { - let module = Module::default(); - let claim = crate::ast::Claim { - id: "元数错".into(), - conclusion: "包含(轨迹, \"a\", \"b\")".into(), - premise: None, - tactic: None, - line: 1, - }; - let mut out = Vec::new(); - check_claim_expr( - &module, - None, - "包含(轨迹, \"a\", \"b\")", - &claim, - &[], - true, - &mut out, - ); - assert!(out.iter().any(|d| d.code == "proof.claim_unsupported"), "{out:?}"); - - let claim2 = crate::ast::Claim { - id: "越界谓词".into(), - conclusion: "求和(金额, 1) > 0".into(), - premise: None, - tactic: None, - line: 2, - }; - let mut out2 = Vec::new(); - check_claim_expr( - &module, - None, - "求和(金额, 1) > 0", - &claim2, - &["金额".to_string()], - true, - &mut out2, - ); - assert!(out2.iter().any(|d| d.code == "proof.claim_unsupported"), "{out2:?}"); - } -} diff --git a/src/prove/types.rs b/src/prove/types.rs deleted file mode 100755 index 0b4b43b..0000000 --- a/src/prove/types.rs +++ /dev/null @@ -1,251 +0,0 @@ -//! 定型(`doc/design/prove-cli.md` §4.1 ③):契约表驱动的轻量推断。 -//! -//! P0 范围:参数/返回类型来自契约表;字面量赋值给最具体类型;分支合流时 -//! 同名变量类型不相容报 `proof.type_mismatch`(带两处行号)。其余一律 -//! `Any`(`--no-strict-types` 语义下的诚实回退,不做猜测)。 - -use std::collections::BTreeMap; - -use crate::diagnostics::{Diagnostic, Severity, Span}; -use crate::prove::ir::{PlanTy, PureExpr, Step}; - -/// 单函数类型检查产物。 -#[derive(Debug, Default)] -pub struct Typed { - pub diagnostics: Vec, -} - -/// 对一个函数的 steps 做类型检查。 -/// -/// `params`:形参类型(契约表)。返回收集到的诊断。 -pub fn typecheck( - module: &crate::ast::Module, - params: &[(String, PlanTy)], - steps: &[Step], - strict: bool, -) -> Typed { - let mut env: BTreeMap = params - .iter() - .map(|(name, ty)| (name.clone(), (ty.clone(), 0))) - .collect(); - let mut diagnostics = Vec::new(); - check_steps(module, steps, &mut env, &mut diagnostics, strict); - Typed { diagnostics } -} - -fn check_steps( - module: &crate::ast::Module, - steps: &[Step], - env: &mut BTreeMap, - out: &mut Vec, - strict: bool, -) { - for step in steps { - match step { - Step::Bind { var, expr, line } => { - let ty = expr_type(expr, env); - match ty { - Some(new_ty) => { - if let Some((old_ty, old_line)) = env.get(var) { - let merged = conflate(old_ty, &new_ty); - if merged.is_none() { - out.push(mismatch( - module, - Span::new(*line, 1), - *old_line, - var, - old_ty, - &new_ty, - )); - } - let merged = merged.unwrap_or(PlanTy::Any); - if strict && merged == PlanTy::Any && new_ty != PlanTy::Any { - // 严格模式下落 Any 的合流仍允许,但记录在案。 - } - env.insert(var.clone(), (merged, *line)); - } else { - env.insert(var.clone(), (new_ty, *line)); - } - } - None => { - // 未知类型:保留旧类型(若有),否则 Any。 - env.entry(var.clone()).or_insert((PlanTy::Any, *line)); - } - } - } - Step::Return { expr, .. } => { - let _ = expr_type(expr, env); - } - Step::If { - then, - otherwise, - line, - .. - } => { - // 分支合流:两臂各自检查后合并同名变量类型。 - let mut then_env = env.clone(); - let mut else_env = env.clone(); - check_steps(module, then, &mut then_env, out, strict); - check_steps(module, otherwise, &mut else_env, out, strict); - let then_vars: Vec<(String, (PlanTy, u32))> = - then_env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); - for (name, (then_ty, then_line)) in then_vars { - if name.starts_with("实参") { - continue; - } - match else_env.get(&name) { - Some((else_ty, else_line)) => { - match conflate(&then_ty, else_ty) { - Some(merged) => { - env.insert(name, (merged, *line)); - } - None => { - out.push(mismatch( - module, - Span::new(then_line.max(1), 1), - *else_line, - &name, - &then_ty, - else_ty, - )); - env.insert(name, (PlanTy::Any, *line)); - } - } - } - None => { - env.insert(name, (then_ty, then_line)); - } - } - } - // 只在 else 出现的变量也进入合流后的环境。 - for (name, (else_ty, _)) in &else_env { - then_env.entry(name.clone()).or_insert((else_ty.clone(), 0)); - } - } - Step::Trace { .. } => {} - } - } -} - -/// 纯表达式的保守类型:只认字面量/构造器/列表/映射/len/access/插值。 -fn expr_type(expr: &crate::prove::ir::Expr, env: &BTreeMap) -> Option { - match expr { - crate::prove::ir::Expr::Pure(pure) => pure_type(pure, env), - crate::prove::ir::Expr::Op { .. } => None, - crate::prove::ir::Expr::Formula | crate::prove::ir::Expr::Code => None, - } -} - -fn pure_type(pure: &PureExpr, env: &BTreeMap) -> Option { - match pure { - PureExpr::Int(_) => Some(PlanTy::Int), - PureExpr::Num(_) => Some(PlanTy::Num), - PureExpr::Bool(_) => Some(PlanTy::Bool), - PureExpr::Text(_) => Some(PlanTy::Text), - PureExpr::None => Some(PlanTy::Any), - PureExpr::Var(name) => env.get(name).map(|(ty, _)| ty.clone()), - PureExpr::Bin { operator: op, left, right } => { - use crate::prove::ir::BinOp as B; - let lt = pure_type(left, env); - let rt = pure_type(right, env); - match op { - B::Add | B::Sub | B::Mul | B::Div => { - let lt = lt?; - let rt = rt?; - match (<, &rt) { - (PlanTy::Text, _) | (_, PlanTy::Text) => Some(PlanTy::Text), - (PlanTy::Num, _) | (_, PlanTy::Num) => Some(PlanTy::Num), - (PlanTy::Int, PlanTy::Int) => Some(PlanTy::Int), - _ => None, - } - } - B::Eq | B::Ne | B::Lt | B::Le | B::Gt | B::Ge | B::And | B::Or => Some(PlanTy::Bool), - } - } - PureExpr::Un { operator: op, expr } => match op { - crate::prove::ir::UnOp::Not => Some(PlanTy::Bool), - crate::prove::ir::UnOp::Neg => pure_type(expr, env), - }, - PureExpr::Index { base, .. } => match pure_type(base, env)? { - PlanTy::Map => Some(PlanTy::Any), - PlanTy::List => Some(PlanTy::Any), - PlanTy::Result => Some(PlanTy::Any), - _ => Some(PlanTy::Any), - }, - PureExpr::Access { base, .. } => match pure_type(base, env)? { - PlanTy::Result => Some(PlanTy::Any), - _ => Some(PlanTy::Any), - }, - PureExpr::Len(_) => Some(PlanTy::Int), - PureExpr::Interp(_) => Some(PlanTy::Text), - PureExpr::List(_) => Some(PlanTy::List), - PureExpr::Map(_) => Some(PlanTy::Map), - PureExpr::Ctor { name, .. } => { - if name.starts_with("result.") { - Some(PlanTy::Result) - } else { - None - } - } - } -} - -/// 类型合流:相同 → 相同;Int+Num → Num;含 Any → Any;否则 None(冲突)。 -fn conflate(a: &PlanTy, b: &PlanTy) -> Option { - use PlanTy as T; - if a == b { - return Some(a.clone()); - } - match (a, b) { - (T::Any, other) | (other, T::Any) => Some(other.clone()), - (T::Int, T::Num) | (T::Num, T::Int) => Some(T::Num), - _ => None, - } -} - -fn mismatch( - module: &crate::ast::Module, - span: Span, - other_line: u32, - var: &str, - old: &PlanTy, - new: &PlanTy, -) -> Diagnostic { - Diagnostic::new( - module.source.path.as_deref(), - span, - format!( - "`{var}` 在分支合流处类型不相容:{a} vs {b}", - a = old.name(), - b = new.name() - ), - ) - .with_source(&module.source) - .with_code("proof.type_mismatch") - .with_severity(Severity::Error) - .with_suggestion(format!( - "另一处绑定在第 {other_line} 行;统一两臂的类型或改用 --no-strict-types" - )) -} - -/// 把类型检查接到降级产物上(mod.rs 调用)。 -pub fn typecheck_plan( - module: &crate::ast::Module, - lowered: &[crate::prove::lower::Lowered], - strict: bool, -) -> Vec { - let mut out = Vec::new(); - for item in lowered { - let Some(plan) = &item.plan else { - continue; - }; - let params: Vec<(String, PlanTy)> = plan - .params - .iter() - .map(|p| (p.name.clone(), p.ty.clone())) - .collect(); - let typed = typecheck(module, ¶ms, &plan.steps, strict); - out.extend(typed.diagnostics); - } - out -} diff --git a/src/repair.rs b/src/repair.rs deleted file mode 100755 index e9914a4..0000000 --- a/src/repair.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! 有界修复(T3.3 护栏的**机械执行面**):锚点局部修复,越界必拒(abstain),全有或全无。 -//! -//! 修复循环三步:诊断(run/check)→ `mlsp repair_targets`(靶点 + 范围)→ `mlsp repair_apply`(改行)。 -//! 护栏不是提示词愿望,而是这里代码强制的: -//! -//! - 只允许三种行编辑:`Replace` / `Delete` / `InsertBefore`; -//! - 被触碰的每一行都必须落在靶点范围内(`InsertBefore` 额外允许紧跟范围末尾追加), -//! 否则**整体拒绝**并报越界行清单——一个字节都不改(全有或全无); -//! - 应用结果交给调用方复验(`validate` / `run`)。 -//! -//! 目标([three-problems.md](../../doc/roadmap/three-problems.md) §5.3):易锚定错误 -//! ≥80% 修复率的同时,**越权范围的改动必拒**、失败后 abstain 而非乱改。 - -use std::collections::{HashMap, HashSet}; - -/// 一行编辑(1-based 行号)。 -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Edit { - /// 把 `line` 整行换成 `text`。 - Replace { line: u32, text: String }, - /// 删除 `line`。 - Delete { line: u32 }, - /// 在 `line` **之前**插入 `text`(允许 `line == 范围末行 + 1`,即紧跟块尾追加)。 - InsertBefore { line: u32, text: String }, -} - -impl Edit { - /// 被触碰的行(范围检查用)。 - pub fn touched(&self) -> u32 { - match self { - Edit::Replace { line, .. } | Edit::Delete { line } | Edit::InsertBefore { line, .. } => { - *line - } - } - } -} - -/// 越界拒绝(abstain):报告越界行与允许范围,源保持不变。 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct OutOfScope { - pub lines: Vec, - pub ranges: Vec<(u32, u32)>, -} - -fn in_ranges(ranges: &[(u32, u32)], line: u32) -> bool { - ranges.iter().any(|(s, e)| line >= *s && line <= *e) -} - -fn at_tail(ranges: &[(u32, u32)], line: u32) -> bool { - ranges.iter().any(|(_, e)| line == e + 1) -} - -/// 全有或全无地应用行编辑。 -/// -/// - 任何被触碰行越出 `ranges`(或行号非法)⇒ [`Err`](越界清单),**源不变**; -/// - 同一行被多个编辑触碰时 `Delete` 优先于 `Replace`,同种后者覆盖前者。 -pub fn apply_edits( - source: &str, - ranges: &[(u32, u32)], - edits: &[Edit], -) -> Result { - let lines: Vec<&str> = source.lines().collect(); - let n_lines = lines.len() as u32; - - // ---- 范围检查(先全体验完再动源) ---- - let mut bad = Vec::new(); - for e in edits { - let line = e.touched(); - let legal = match e { - Edit::InsertBefore { .. } => { - (line >= 1 && line <= n_lines + 1) - && (in_ranges(ranges, line) || at_tail(ranges, line)) - } - _ => line >= 1 && line <= n_lines && in_ranges(ranges, line), - }; - if !legal { - bad.push(line); - } - } - bad.sort_unstable(); - bad.dedup(); - if !bad.is_empty() { - return Err(OutOfScope { - lines: bad, - ranges: ranges.to_vec(), - }); - } - - // ---- 应用 ---- - let mut replaced: HashMap = HashMap::new(); - let mut deleted: HashSet = HashSet::new(); - let mut inserts: HashMap> = HashMap::new(); - for e in edits { - match e { - Edit::Replace { line, text } => { - replaced.insert(*line, text.clone()); - } - Edit::Delete { line } => { - deleted.insert(*line); - replaced.remove(line); // Delete 优先 - } - Edit::InsertBefore { line, text } => { - inserts.entry(*line).or_default().push(text.clone()); - } - } - } - - let trailing_newline = source.ends_with('\n'); - let mut out: Vec = Vec::with_capacity(lines.len() + inserts.len()); - for (i, l) in lines.iter().enumerate() { - let n = (i + 1) as u32; - if let Some(texts) = inserts.get(&n) { - out.extend(texts.iter().cloned()); - } - if deleted.contains(&n) { - continue; - } - out.push(replaced.get(&n).cloned().unwrap_or_else(|| l.to_string())); - } - if let Some(texts) = inserts.get(&(n_lines + 1)) { - out.extend(texts.iter().cloned()); - } - - let mut s = out.join("\n"); - if trailing_newline { - s.push('\n'); - } - Ok(s) -} diff --git a/src/runtime/control.rs b/src/runtime/control.rs deleted file mode 100755 index 35a7e58..0000000 --- a/src/runtime/control.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! Task control plane: cancel without interpreter lock (M-R3). - -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Duration; - -use serde_json::Value; - -use crate::runtime::protocol::RuntimeEventV2; -use crate::runtime::scheduler::{AdmissionClass, ScheduleError, Scheduler}; -use crate::runtime::task_store::{StoreError, TaskRecord, TaskState, TaskStore}; - -#[derive(Debug)] -pub enum ControlError { - Store(StoreError), - Schedule(ScheduleError), - Forbidden, -} - -impl From for ControlError { - fn from(e: StoreError) -> Self { - Self::Store(e) - } -} - -impl From for ControlError { - fn from(e: ScheduleError) -> Self { - Self::Schedule(e) - } -} - -impl std::fmt::Display for ControlError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Store(e) => write!(f, "{e}"), - Self::Schedule(e) => write!(f, "{e}"), - Self::Forbidden => write!(f, "forbidden"), - } - } -} - -pub struct ControlService { - pub store: Arc, - pub scheduler: Arc, - /// Per-lease cancel token directory (token files, not process-global env). - cancel_dir: PathBuf, -} - -impl ControlService { - pub fn new(store: Arc, scheduler: Arc, cancel_dir: impl AsRef) -> Self { - let cancel_dir = cancel_dir.as_ref().to_path_buf(); - let _ = std::fs::create_dir_all(&cancel_dir); - Self { - store, - scheduler, - cancel_dir, - } - } - - pub fn admit( - &self, - task_id: &str, - run_id: &str, - workspace_id: &str, - session_id: Option, - idempotency_key: &str, - payload: &Value, - class: AdmissionClass, - ) -> Result<(TaskRecord, usize), ControlError> { - let rec = self.store.admit( - task_id, - run_id, - workspace_id, - session_id, - idempotency_key, - payload, - )?; - let depth = self.scheduler.enqueue(&rec, class)?; - let queued = self.store.cas_state( - &rec.task_id, - rec.revision, - TaskState::Queued, - |_| {}, - )?; - Ok((queued, depth)) - } - - /// Cancel path never enters the Marqdo interpreter lock. - pub fn cancel(&self, task_id: &str) -> Result { - let rec = self.store.request_cancel(task_id)?; - let tok = self.cancel_token_path(task_id); - let _ = std::fs::write(&tok, b"cancelled"); - let _ = self.store.append_event( - task_id, - &rec.run_id, - &rec.attempt_id, - "run.cancel_requested", - serde_json::json!({"revision": rec.revision}), - ); - Ok(rec) - } - - pub fn cancel_token_path(&self, task_id: &str) -> PathBuf { - self.cancel_dir.join(format!("{task_id}.tok")) - } - - pub fn mark_cancelled(&self, task_id: &str, expected_revision: u64) -> Result { - Ok(self.store.cas_state( - task_id, - expected_revision, - TaskState::Cancelled, - |_| {}, - )?) - } - - pub fn complete( - &self, - task_id: &str, - expected_revision: u64, - result: Value, - ) -> Result { - match self.store.cas_state(task_id, expected_revision, TaskState::Succeeded, |r| { - r.result = Some(result.clone()); - }) { - Ok(rec) => Ok(rec), - Err(StoreError::AlreadyTerminal(state)) => { - // Late result after cancel: append evidence only. - let rec = self.store.get(task_id)?; - let _ = self.store.append_event( - task_id, - &rec.run_id, - &rec.attempt_id, - "run.late_result", - serde_json::json!({"ignored_terminal": format!("{state:?}"), "result": result}), - ); - Err(ControlError::Store(StoreError::AlreadyTerminal(state))) - } - Err(e) => Err(ControlError::Store(e)), - } - } - - pub fn events_since( - &self, - task_id: &str, - after_seq: u64, - ) -> Result, ControlError> { - Ok(self.store.events_after(task_id, after_seq)?) - } - - /// Collaboration grace + force-kill budget from the design (§6). - pub fn cancel_deadlines() -> (Duration, Duration) { - (Duration::from_secs(2), Duration::from_secs(3)) - } -} - -/// Convenience wrapper used by HTTP/control adapters. -pub fn cancel_task(svc: &ControlService, task_id: &str) -> Result { - svc.cancel(task_id) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::runtime::scheduler::SchedulerConfig; - use serde_json::json; - - #[test] - fn cancel_writes_token_not_interpreter() { - let dir = std::env::temp_dir().join(format!("mq-ctrl-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let store = Arc::new(TaskStore::memory()); - let sched = Arc::new(Scheduler::new(SchedulerConfig::default())); - let ctl = ControlService::new(store, sched, &dir); - let (t, _) = ctl - .admit("t1", "r1", "ws", None, "k", &json!({}), AdmissionClass::Execute) - .unwrap(); - let c = ctl.cancel(&t.task_id).unwrap(); - assert_eq!(c.state, TaskState::CancelRequested); - let body = std::fs::read_to_string(ctl.cancel_token_path(&t.task_id)).unwrap(); - assert_eq!(body, "cancelled"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn late_complete_after_cancel_is_evidence_only() { - let dir = std::env::temp_dir().join(format!("mq-ctrl2-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let store = Arc::new(TaskStore::memory()); - let sched = Arc::new(Scheduler::new(SchedulerConfig::default())); - let ctl = ControlService::new(Arc::clone(&store), sched, &dir); - let (t, _) = ctl - .admit("t1", "r1", "ws", None, "k", &json!({}), AdmissionClass::Execute) - .unwrap(); - let c = ctl.cancel(&t.task_id).unwrap(); - ctl.mark_cancelled(&t.task_id, c.revision).unwrap(); - let err = ctl.complete(&t.task_id, c.revision + 1, json!("late")).unwrap_err(); - assert!(matches!(err, ControlError::Store(StoreError::AlreadyTerminal(_)))); - let evs = store.events_after(&t.task_id, 0).unwrap(); - assert!(evs.iter().any(|e| e.event_type == "run.late_result")); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/src/runtime/host_api.rs b/src/runtime/host_api.rs deleted file mode 100755 index c7e49b7..0000000 --- a/src/runtime/host_api.rs +++ /dev/null @@ -1,457 +0,0 @@ -//! Process-global control plane via `host_query("runtime", …)` — no INVOKE_LOCK. - -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, OnceLock}; -use std::thread; -use std::time::Duration; - -use serde_json::{json, Value}; - -use crate::runtime::control::ControlService; -use crate::runtime::protocol::{ - EntryRef, InvokeContext, InvokeRequestV2, LeaseRef, PROTOCOL_VERSION, -}; -use crate::runtime::scheduler::{AdmissionClass, Scheduler, SchedulerConfig}; -use crate::runtime::supervisor::{Supervisor, SupervisorConfig}; -use crate::runtime::task_store::{TaskState, TaskStore}; - -struct RuntimeHost { - control: ControlService, - supervisor: Arc, - /// task_id → lease_id - leases: Mutex>, - base: PathBuf, -} - -fn runtime_dir() -> PathBuf { - std::env::var_os("MARQDO_RUNTIME_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| std::env::temp_dir().join("marqdo-runtime")) -} - -fn marqdo_bin() -> PathBuf { - std::env::var_os("MARQDO_BIN") - .map(PathBuf::from) - .unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| PathBuf::from("marqdo"))) -} - -fn ensure_host() -> &'static RuntimeHost { - static H: OnceLock = OnceLock::new(); - static JANITOR: OnceLock<()> = OnceLock::new(); - let host = H.get_or_init(|| { - let base = runtime_dir(); - let _ = std::fs::create_dir_all(&base); - let store = match TaskStore::with_persist(base.join("store")) { - Ok(s) => Arc::new(s), - Err(_) => Arc::new(TaskStore::memory()), - }; - let scheduler = Arc::new(Scheduler::new(SchedulerConfig::default())); - let control = ControlService::new( - Arc::clone(&store), - Arc::clone(&scheduler), - base.join("cancel"), - ); - let supervisor = Arc::new(Supervisor::new( - SupervisorConfig::default(), - base.join("stage"), - marqdo_bin(), - base.join("cancel"), - base.join("events"), - )); - let _ = supervisor.warm(); - RuntimeHost { - control, - supervisor, - leases: Mutex::new(std::collections::HashMap::new()), - base, - } - }); - JANITOR.get_or_init(|| { - let sup = Arc::clone(&host.supervisor); - let _ = thread::Builder::new() - .name("mq-runtime-janitor".into()) - .spawn(move || loop { - thread::sleep(Duration::from_millis(500)); - let _ = sup.janitor_tick(); - }); - }); - host -} - -/// Dispatch `host_query("runtime", {op, ...})`. Never blocks on INVOKE_LOCK. -pub fn handle(args: &Value) -> Result { - let op = args - .get("op") - .and_then(|v| v.as_str()) - .ok_or_else(|| "runtime requires op".to_string())?; - let host = ensure_host(); - let ctl = &host.control; - match op { - "ping" | "capabilities" => Ok(json!({ - "ok": true, - "protocol_version": PROTOCOL_VERSION, - "features": { - "runtime.task_control_v2": 1, - "runtime.event_replay": 1, - "runtime.isolated_execution": 1, - }, - "runtime_dir": host.base.to_string_lossy(), - })), - "admit" => { - let task_id = req_str(args, "task_id")?; - let run_id = args - .get("run_id") - .and_then(|v| v.as_str()) - .unwrap_or(task_id); - let workspace_id = args - .get("workspace_id") - .and_then(|v| v.as_str()) - .unwrap_or("default"); - let session_id = args - .get("session_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()); - let idem = args - .get("idempotency_key") - .and_then(|v| v.as_str()) - .unwrap_or(task_id); - let class = AdmissionClass::parse( - args.get("class").and_then(|v| v.as_str()).unwrap_or("execute"), - ); - let payload = args.get("payload").cloned().unwrap_or(json!({})); - let (rec, depth) = ctl - .admit( - task_id, - run_id, - workspace_id, - session_id, - idem, - &payload, - class, - ) - .map_err(|e| e.to_string())?; - Ok(json!({ - "ok": true, - "task": task_json(&rec), - "queue_depth": depth, - "cancel_token": ctl.cancel_token_path(&rec.task_id).to_string_lossy(), - "event_path": host.supervisor.event_path(&rec.task_id).to_string_lossy(), - })) - } - "dispatch" => dispatch_op(host, args), - "cancel" => { - let task_id = req_str(args, "task_id")?; - match ctl.cancel(task_id) { - Ok(rec) => { - if let Some(lease) = host.leases.lock().unwrap().get(task_id) { - let _ = host.supervisor.signal_cancel(lease, task_id); - } else { - let _ = std::fs::write(ctl.cancel_token_path(task_id), b"cancelled"); - } - Ok(json!({ - "ok": true, - "task": task_json(&rec), - "cancel_token": ctl.cancel_token_path(task_id).to_string_lossy(), - })) - } - Err(crate::runtime::control::ControlError::Store( - crate::runtime::task_store::StoreError::NotFound, - )) => Ok(json!({"ok": false, "error": "not_found", "status": 404})), - Err(crate::runtime::control::ControlError::Store( - crate::runtime::task_store::StoreError::AlreadyTerminal(s), - )) => Ok(json!({ - "ok": true, - "already_terminal": true, - "state": format!("{s:?}").to_ascii_lowercase(), - })), - Err(e) => Err(e.to_string()), - } - } - "get" => { - let task_id = req_str(args, "task_id")?; - match ctl.store.get(task_id) { - Ok(rec) => { - let mut out = json!({"ok": true, "task": task_json(&rec)}); - if let Some(lease) = host.leases.lock().unwrap().get(task_id).cloned() { - out["lease_id"] = json!(lease); - if let Some(p) = host.supervisor.emit_result_path(&lease) { - out["emit_result"] = json!(p.to_string_lossy()); - } - if let Ok(Some(code)) = host.supervisor.try_reap(&lease) { - out["exit_code"] = json!(code); - host.control - .scheduler - .release_slot(AdmissionClass::Execute); - let _ = ctl.store.cas_state( - task_id, - rec.revision, - if code == 0 { - TaskState::Succeeded - } else { - TaskState::Failed - }, - |_| {}, - ); - } - } - out["event_path"] = - json!(host.supervisor.event_path(task_id).to_string_lossy()); - Ok(out) - } - Err(_) => Ok(json!({"ok": false, "error": "not_found", "status": 404})), - } - } - "events" => { - let task_id = req_str(args, "task_id")?; - let after = args.get("after_seq").and_then(|v| v.as_u64()).unwrap_or(0); - let path = host.supervisor.event_path(task_id); - if path.is_file() { - let lines = read_ndjson_lines(&path, after)?; - return Ok(json!({ - "ok": true, - "events": lines, - "after_seq": after, - "source": "worker_ndjson", - "event_path": path.to_string_lossy(), - })); - } - match ctl.events_since(task_id, after) { - Ok(evs) => Ok(json!({ - "ok": true, - "events": evs, - "after_seq": after, - "source": "task_store", - })), - Err(_) => Ok(json!({"ok": false, "error": "not_found", "status": 404})), - } - } - "append_event" => { - let task_id = req_str(args, "task_id")?; - let rec = ctl.store.get(task_id).map_err(|_| "not_found".to_string())?; - let et = args - .get("type") - .and_then(|v| v.as_str()) - .unwrap_or("message.delta"); - let payload = args.get("payload").cloned().unwrap_or(json!({})); - let ev = ctl - .store - .append_event(task_id, &rec.run_id, &rec.attempt_id, et, payload) - .map_err(|e| e.to_string())?; - Ok(json!({"ok": true, "event": ev})) - } - other => Err(format!("runtime.unknown_op:{other}")), - } -} - -fn dispatch_op(host: &RuntimeHost, args: &Value) -> Result { - let task_id = req_str(args, "task_id")?; - let rec = host - .control - .store - .get(task_id) - .map_err(|_| "not_found".to_string())?; - let entry = args.get("entry").ok_or("dispatch.entry_required")?; - let module = entry - .get("module") - .and_then(|v| v.as_str()) - .ok_or("dispatch.module_required")?; - let function = entry - .get("function") - .and_then(|v| v.as_str()) - .ok_or("dispatch.function_required")?; - let fs_root = args - .get("fs_root") - .and_then(|v| v.as_str()) - .or_else(|| { - args.get("context") - .and_then(|c| c.get("fs_root")) - .and_then(|v| v.as_str()) - }) - .ok_or("dispatch.fs_root_required")?; - let args_ref = args - .get("args_ref") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()) - .or_else(|| { - args.get("args_json") - .and_then(|v| v.as_str()) - .map(|p| format!("file:{p}")) - }); - - let tok = host.control.cancel_token_path(task_id); - if !tok.exists() { - std::fs::write(&tok, b"").map_err(|e| e.to_string())?; - } - - let epoch = host.control.store.next_lease_epoch(); - let req = InvokeRequestV2 { - schema: "InvokeRequestV2".into(), - schema_version: PROTOCOL_VERSION, - task_id: task_id.into(), - run_id: rec.run_id.clone(), - attempt_id: rec.attempt_id.clone(), - lease: LeaseRef { - id: format!("lease_{task_id}"), - epoch, - }, - entry: EntryRef { - module: module.into(), - function: function.into(), - }, - args_ref, - context: InvokeContext { - workspace_id: rec.workspace_id.clone(), - snapshot_id: None, - selection_ref: None, - capabilities_ref: None, - deadline_at: "2099-01-01T00:00:00Z".into(), - fs_root: Some(fs_root.into()), - }, - }; - - if host - .control - .scheduler - .try_acquire_slot(AdmissionClass::Execute) - .is_err() - { - return Ok(json!({ - "ok": false, - "error": "no_slot", - "status": 429, - "Retry-After": 2, - })); - } - - match host.supervisor.dispatch(req) { - Ok(lease_id) => { - host.leases - .lock() - .unwrap() - .insert(task_id.to_string(), lease_id.clone()); - let _ = host.control.store.cas_state( - task_id, - rec.revision, - TaskState::Running, - |r| { - r.lease_id = Some(lease_id.clone()); - r.lease_epoch = Some(epoch); - }, - ); - Ok(json!({ - "ok": true, - "lease_id": lease_id, - "task_id": task_id, - "cancel_token": tok.to_string_lossy(), - "event_path": host.supervisor.event_path(task_id).to_string_lossy(), - "emit_result": host.supervisor.emit_result_path(&lease_id) - .map(|p| p.to_string_lossy().to_string()), - })) - } - Err(e) => { - host.control - .scheduler - .release_slot(AdmissionClass::Execute); - if e.contains("no_slot") { - Ok(json!({ - "ok": false, - "error": "no_slot", - "status": 429, - "Retry-After": 2, - })) - } else { - Err(e) - } - } - } -} - -fn read_ndjson_lines(path: &Path, after_seq: u64) -> Result, String> { - let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?; - let mut out = Vec::new(); - let mut seq = 0u64; - for line in text.lines() { - let line = line.trim(); - if line.is_empty() { - continue; - } - seq += 1; - if seq <= after_seq { - continue; - } - match serde_json::from_str::(line) { - Ok(mut v) => { - if v.get("seq").is_none() { - if let Some(obj) = v.as_object_mut() { - obj.insert("seq".into(), json!(seq)); - } - } - out.push(v); - } - Err(_) => out.push(json!({"seq": seq, "raw": line})), - } - } - Ok(out) -} - -fn req_str<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { - args.get(key) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| format!("runtime missing `{key}`")) -} - -fn task_json(rec: &crate::runtime::task_store::TaskRecord) -> Value { - json!({ - "task_id": rec.task_id, - "run_id": rec.run_id, - "attempt_id": rec.attempt_id, - "workspace_id": rec.workspace_id, - "session_id": rec.session_id, - "state": state_str(rec.state), - "revision": rec.revision, - "idempotency_key": rec.idempotency_key, - "created_at": rec.created_at, - "updated_at": rec.updated_at, - "cancel_requested_at": rec.cancel_requested_at, - "result": rec.result, - "error": rec.error, - "lease_id": rec.lease_id, - }) -} - -fn state_str(s: TaskState) -> &'static str { - match s { - TaskState::Accepted => "accepted", - TaskState::Queued => "queued", - TaskState::Running => "running", - TaskState::Finalizing => "finalizing", - TaskState::Succeeded => "succeeded", - TaskState::Failed => "failed", - TaskState::CancelRequested => "cancel_requested", - TaskState::Cancelled => "cancelled", - TaskState::Interrupted => "interrupted", - TaskState::NeedsReconciliation => "needs_reconciliation", - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn admit_cancel_without_host_context() { - let id = format!("rt-{}", std::process::id()); - let adm = handle(&json!({ - "op": "admit", - "task_id": id, - "idempotency_key": id, - "payload": {"n": 1} - })) - .unwrap(); - assert_eq!(adm["ok"], true); - let can = handle(&json!({"op": "cancel", "task_id": id})).unwrap(); - assert_eq!(can["ok"], true); - assert_eq!(can["task"]["state"], "cancel_requested"); - } -} diff --git a/src/runtime/lease.rs b/src/runtime/lease.rs deleted file mode 100755 index 8215374..0000000 --- a/src/runtime/lease.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Worker lease identity and process lifecycle states (M-R2). - -use std::time::{Duration, SystemTime}; - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct LeaseId(pub String); - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum WorkerState { - Starting, - Ready, - Leased, - Running, - Draining, - Unhealthy, - Terminating, - Exited, -} - -#[derive(Debug, Clone)] -pub struct Lease { - pub id: LeaseId, - pub epoch: u64, - pub task_id: String, - pub run_id: String, - pub attempt_id: String, - pub deadline: SystemTime, - pub state: WorkerState, -} - -impl Lease { - pub fn new( - id: impl Into, - epoch: u64, - task_id: impl Into, - run_id: impl Into, - attempt_id: impl Into, - ttl: Duration, - ) -> Self { - Self { - id: LeaseId(id.into()), - epoch, - task_id: task_id.into(), - run_id: run_id.into(), - attempt_id: attempt_id.into(), - deadline: SystemTime::now() + ttl, - state: WorkerState::Leased, - } - } - - pub fn expired(&self) -> bool { - SystemTime::now() > self.deadline - } - - pub fn matches(&self, lease_id: &str, epoch: u64) -> bool { - self.id.0 == lease_id && self.epoch == epoch - } -} diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs deleted file mode 100755 index 1c43611..0000000 --- a/src/runtime/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Isolated web runtime (M-R2–M-R4): supervisor, worker IPC, leases, task -//! admission/control, and persistent event log. -//! -//! Design: `doc/design/isolated-web-runtime-development-2026-10-26.md`. -//! Until capability probes report version ≥1, callers must treat this as opt-in. - -pub mod control; -pub mod host_api; -pub mod lease; -pub mod protocol; -pub mod publish; -pub mod scheduler; -pub mod supervisor; -pub mod task_store; -pub mod worker; - -pub use control::{cancel_task, ControlError, ControlService}; -pub use lease::{Lease, LeaseId, WorkerState}; -pub use protocol::{ - InvokeRequestV2, RuntimeEventV2, CONTROL_FRAME_MAX_BYTES, PROTOCOL_VERSION, -}; -pub use publish::{PublishJournal, PublishOutcome, PublishPhase}; -pub use scheduler::{AdmissionClass, Scheduler, SchedulerConfig}; -pub use supervisor::{Supervisor, SupervisorConfig}; -pub use task_store::{TaskRecord, TaskState, TaskStore}; -pub use worker::{WorkerHandle, WorkerPool}; diff --git a/src/runtime/protocol.rs b/src/runtime/protocol.rs deleted file mode 100755 index edbf34c..0000000 --- a/src/runtime/protocol.rs +++ /dev/null @@ -1,158 +0,0 @@ -//! Length-prefixed JSON control frames + event channel types (M-R2 / M-R4). - -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -pub const PROTOCOL_VERSION: u32 = 2; -pub const CONTROL_FRAME_MAX_BYTES: usize = 1024 * 1024; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct InvokeRequestV2 { - pub schema: String, - pub schema_version: u32, - pub task_id: String, - pub run_id: String, - pub attempt_id: String, - pub lease: LeaseRef, - pub entry: EntryRef, - #[serde(default)] - pub args_ref: Option, - pub context: InvokeContext, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct LeaseRef { - pub id: String, - pub epoch: u64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EntryRef { - pub module: String, - pub function: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct InvokeContext { - pub workspace_id: String, - #[serde(default)] - pub snapshot_id: Option, - #[serde(default)] - pub selection_ref: Option, - #[serde(default)] - pub capabilities_ref: Option, - pub deadline_at: String, - /// Absolute site filesystem root (`--fs-root` for the worker). - #[serde(default)] - pub fs_root: Option, -} - -impl InvokeRequestV2 { - pub fn validate(&self) -> Result<(), String> { - if self.schema != "InvokeRequestV2" { - return Err(format!("protocol.schema: {}", self.schema)); - } - if self.schema_version != PROTOCOL_VERSION { - return Err(format!( - "protocol.version: got {} want {PROTOCOL_VERSION}", - self.schema_version - )); - } - if self.task_id.is_empty() || self.run_id.is_empty() || self.attempt_id.is_empty() { - return Err("protocol.ids_required".into()); - } - if self.entry.module.is_empty() || self.entry.function.is_empty() { - return Err("protocol.entry_required".into()); - } - Ok(()) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RuntimeEventV2 { - pub schema: String, - pub schema_version: u32, - pub event_id: String, - pub seq: u64, - pub task_id: String, - pub run_id: String, - pub attempt_id: String, - #[serde(rename = "type")] - pub event_type: String, - pub payload: Value, -} - -impl RuntimeEventV2 { - pub fn new( - task_id: &str, - run_id: &str, - attempt_id: &str, - seq: u64, - event_type: &str, - payload: Value, - ) -> Self { - Self { - schema: "RuntimeEventV2".into(), - schema_version: PROTOCOL_VERSION, - event_id: format!("{task_id}:{seq}"), - seq, - task_id: task_id.into(), - run_id: run_id.into(), - attempt_id: attempt_id.into(), - event_type: event_type.into(), - payload, - } - } -} - -/// Encode a control frame: u32 LE length + UTF-8 JSON (≤ CONTROL_FRAME_MAX_BYTES). -pub fn encode_frame(value: &Value) -> Result, String> { - let body = serde_json::to_vec(value).map_err(|e| format!("protocol.encode: {e}"))?; - if body.len() > CONTROL_FRAME_MAX_BYTES { - return Err("protocol.frame_too_large".into()); - } - let mut out = Vec::with_capacity(4 + body.len()); - out.extend_from_slice(&(body.len() as u32).to_le_bytes()); - out.extend_from_slice(&body); - Ok(out) -} - -/// Decode one frame from the front of `buf`; returns (value, bytes_consumed). -pub fn decode_frame(buf: &[u8]) -> Result, String> { - if buf.len() < 4 { - return Ok(None); - } - let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; - if len > CONTROL_FRAME_MAX_BYTES { - return Err("protocol.frame_too_large".into()); - } - if buf.len() < 4 + len { - return Ok(None); - } - let value: Value = serde_json::from_slice(&buf[4..4 + len]) - .map_err(|e| format!("protocol.decode: {e}"))?; - Ok(Some((value, 4 + len))) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn frame_round_trip() { - let v = json!({"hello": "世界"}); - let enc = encode_frame(&v).unwrap(); - let (got, n) = decode_frame(&enc).unwrap().unwrap(); - assert_eq!(n, enc.len()); - assert_eq!(got, v); - } - - #[test] - fn incomplete_frame_waits() { - let v = json!({"a": 1}); - let enc = encode_frame(&v).unwrap(); - assert!(decode_frame(&enc[..3]).unwrap().is_none()); - assert!(decode_frame(&enc[..enc.len() - 1]).unwrap().is_none()); - } -} diff --git a/src/runtime/publish.rs b/src/runtime/publish.rs deleted file mode 100755 index dd36a09..0000000 --- a/src/runtime/publish.rs +++ /dev/null @@ -1,274 +0,0 @@ -//! Publish journal + expected_generation CAS (M-R6). - -use std::fs; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum PublishPhase { - Staging, - Validated, - GenerationRenamed, - CurrentSwitched, - DbProjected, - Aborted, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PublishJournal { - pub kb_id: String, - pub expected_generation: Option, - pub new_generation: String, - pub phase: PublishPhase, - pub staging_dir: PathBuf, - pub generation_dir: PathBuf, - pub current_path: PathBuf, - pub source_digest: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum PublishOutcome { - Published { generation: String }, - Conflict { current: String, expected: String }, - Recovered { generation: String }, - Aborted { reason: String }, -} - -impl PublishJournal { - pub fn begin( - out_dir: impl AsRef, - kb_id: impl Into, - expected_generation: Option, - new_generation: impl Into, - source_digest: impl Into, - ) -> Result { - let out_dir = out_dir.as_ref(); - let new_generation = new_generation.into(); - let staging_dir = out_dir.join(".publish-staging").join(&new_generation); - let generation_dir = out_dir.join("generations").join(&new_generation); - let current_path = out_dir.join("CURRENT"); - fs::create_dir_all(&staging_dir).map_err(|e| e.to_string())?; - let j = Self { - kb_id: kb_id.into(), - expected_generation, - new_generation, - phase: PublishPhase::Staging, - staging_dir, - generation_dir, - current_path, - source_digest: source_digest.into(), - }; - j.write_journal(out_dir)?; - Ok(j) - } - - fn journal_path(out_dir: &Path) -> PathBuf { - out_dir.join("publish_journal.json") - } - - fn write_journal(&self, out_dir: &Path) -> Result<(), String> { - let path = Self::journal_path(out_dir); - let tmp = path.with_extension("json.tmp"); - let body = serde_json::to_vec_pretty(self).map_err(|e| e.to_string())?; - fs::write(&tmp, body).map_err(|e| e.to_string())?; - // Best-effort fsync via File. - let f = fs::OpenOptions::new() - .write(true) - .open(&tmp) - .map_err(|e| e.to_string())?; - let _ = f.sync_all(); - drop(f); - fs::rename(&tmp, &path).map_err(|e| e.to_string())?; - Ok(()) - } - - pub fn load(out_dir: impl AsRef) -> Result, String> { - let path = Self::journal_path(out_dir.as_ref()); - if !path.is_file() { - return Ok(None); - } - let body = fs::read_to_string(&path).map_err(|e| e.to_string())?; - let j: Self = serde_json::from_str(&body).map_err(|e| e.to_string())?; - Ok(Some(j)) - } - - /// CAS: refuse if CURRENT does not match expected_generation. - pub fn assert_expected_current(&self) -> Result { - let current = fs::read_to_string(&self.current_path) - .unwrap_or_default() - .trim() - .to_string(); - if let Some(exp) = &self.expected_generation { - if ¤t != exp { - return Err(PublishOutcome::Conflict { - current, - expected: exp.clone(), - }); - } - } - Ok(current) - } - - pub fn mark(&mut self, out_dir: &Path, phase: PublishPhase) -> Result<(), String> { - self.phase = phase; - self.write_journal(out_dir) - } - - /// Atomic publish: staging tree already complete → rename into generations → CURRENT. - pub fn commit_filesystem(&mut self, out_dir: &Path) -> Result { - match self.assert_expected_current() { - Err(o) => return Ok(o), - Ok(_) => {} - } - self.mark(out_dir, PublishPhase::Validated)?; - - if self.generation_dir.exists() { - fs::remove_dir_all(&self.generation_dir).map_err(|e| e.to_string())?; - } - fs::create_dir_all(self.generation_dir.parent().unwrap()).map_err(|e| e.to_string())?; - fs::rename(&self.staging_dir, &self.generation_dir).map_err(|e| e.to_string())?; - self.mark(out_dir, PublishPhase::GenerationRenamed)?; - - let tmp = self.current_path.with_extension("tmp"); - { - let mut f = fs::File::create(&tmp).map_err(|e| e.to_string())?; - writeln!(f, "{}", self.new_generation).map_err(|e| e.to_string())?; - let _ = f.sync_all(); - } - fs::rename(&tmp, &self.current_path).map_err(|e| e.to_string())?; - self.mark(out_dir, PublishPhase::CurrentSwitched)?; - - // Clear journal after successful CURRENT switch; DB projection is product-side. - let _ = fs::remove_file(Self::journal_path(out_dir)); - Ok(PublishOutcome::Published { - generation: self.new_generation.clone(), - }) - } - - /// Crash recovery: if CURRENT already points at new_generation, treat as done; - /// if generation exists but CURRENT old, finish CURRENT switch; else abort staging. - pub fn recover(out_dir: impl AsRef) -> Result { - let out_dir = out_dir.as_ref(); - let Some(mut j) = Self::load(out_dir)? else { - return Ok(PublishOutcome::Aborted { - reason: "no_journal".into(), - }); - }; - let current = fs::read_to_string(&j.current_path) - .unwrap_or_default() - .trim() - .to_string(); - if current == j.new_generation { - let _ = fs::remove_file(Self::journal_path(out_dir)); - return Ok(PublishOutcome::Recovered { - generation: j.new_generation, - }); - } - match j.phase { - PublishPhase::GenerationRenamed | PublishPhase::Validated - if j.generation_dir.is_dir() => - { - let tmp = j.current_path.with_extension("tmp"); - fs::write(&tmp, format!("{}\n", j.new_generation)).map_err(|e| e.to_string())?; - fs::rename(&tmp, &j.current_path).map_err(|e| e.to_string())?; - let _ = fs::remove_file(Self::journal_path(out_dir)); - Ok(PublishOutcome::Recovered { - generation: j.new_generation, - }) - } - PublishPhase::Staging | PublishPhase::Aborted => { - let _ = fs::remove_dir_all(&j.staging_dir); - j.mark(out_dir, PublishPhase::Aborted)?; - let _ = fs::remove_file(Self::journal_path(out_dir)); - Ok(PublishOutcome::Aborted { - reason: "incomplete_staging".into(), - }) - } - other => Ok(PublishOutcome::Aborted { - reason: format!("unhandled_phase:{other:?}"), - }), - } - } -} - -/// Stable logical document identity independent of generation directory name. -pub fn logical_document_id(project_id: &str, relative_path: &str) -> String { - let mut h = Sha256::new(); - h.update(project_id.as_bytes()); - h.update(b"\0"); - h.update(relative_path.replace('\\', "/").as_bytes()); - format!("doc:{:x}", h.finalize()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cas_conflict_and_commit() { - let root = std::env::temp_dir().join(format!("mq-pub-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - fs::create_dir_all(root.join("generations")).unwrap(); - fs::write(root.join("CURRENT"), "gen_old\n").unwrap(); - - let mut j = PublishJournal::begin(&root, "kb1", Some("gen_old".into()), "gen_new", "digest") - .unwrap(); - fs::write(j.staging_dir.join("manifest.json"), "{}").unwrap(); - let out = j.commit_filesystem(&root).unwrap(); - assert_eq!( - out, - PublishOutcome::Published { - generation: "gen_new".into() - } - ); - assert_eq!( - fs::read_to_string(root.join("CURRENT")).unwrap().trim(), - "gen_new" - ); - - let mut j2 = - PublishJournal::begin(&root, "kb1", Some("gen_old".into()), "gen_x", "d").unwrap(); - fs::write(j2.staging_dir.join("x"), "1").unwrap(); - let conflict = j2.commit_filesystem(&root).unwrap(); - assert!(matches!(conflict, PublishOutcome::Conflict { .. })); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn recover_after_generation_rename() { - let root = std::env::temp_dir().join(format!("mq-pub2-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - fs::create_dir_all(root.join("generations/gen_r")).unwrap(); - fs::write(root.join("CURRENT"), "old\n").unwrap(); - let mut j = - PublishJournal::begin(&root, "kb", Some("old".into()), "gen_r", "d").unwrap(); - // Simulate crash after generation rename: staging already moved. - let _ = fs::remove_dir_all(&j.staging_dir); - j.phase = PublishPhase::GenerationRenamed; - j.write_journal(&root).unwrap(); - let out = PublishJournal::recover(&root).unwrap(); - assert_eq!( - out, - PublishOutcome::Recovered { - generation: "gen_r".into() - } - ); - assert_eq!( - fs::read_to_string(root.join("CURRENT")).unwrap().trim(), - "gen_r" - ); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn logical_id_stable_across_generation_paths() { - let a = logical_document_id("proj", "docs/a.mq.md"); - let b = logical_document_id("proj", "docs/a.mq.md"); - assert_eq!(a, b); - assert_ne!(a, logical_document_id("proj", "docs/b.mq.md")); - } -} diff --git a/src/runtime/scheduler.rs b/src/runtime/scheduler.rs deleted file mode 100755 index f927e59..0000000 --- a/src/runtime/scheduler.rs +++ /dev/null @@ -1,249 +0,0 @@ -//! Bounded admission classes and fair queueing (M-R3). - -use std::collections::{HashMap, VecDeque}; -use std::sync::Mutex; - -use crate::runtime::task_store::TaskRecord; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AdmissionClass { - Control, - Read, - Short, - Execute, - Commit, - /// Undeclared endpoints stay on the legacy single-interpreter path. - LegacySerial, -} - -impl AdmissionClass { - pub fn parse(s: &str) -> Self { - match s.to_ascii_lowercase().as_str() { - "control" => Self::Control, - "read" => Self::Read, - "short" => Self::Short, - "execute" => Self::Execute, - "commit" => Self::Commit, - _ => Self::LegacySerial, - } - } -} - -#[derive(Debug, Clone)] -pub struct SchedulerConfig { - pub execute_slots: usize, - pub short_slots: usize, - pub read_slots: usize, - pub global_queue_limit: usize, - pub workspace_queue_limit: usize, - pub session_pending_limit: usize, -} - -impl Default for SchedulerConfig { - fn default() -> Self { - // 4 vCPU / 8 GiB verification machine defaults from the design. - Self { - execute_slots: 2, - short_slots: 1, - read_slots: 1, - global_queue_limit: 64, - workspace_queue_limit: 16, - session_pending_limit: 4, - } - } -} - -#[derive(Debug)] -pub enum ScheduleError { - QueueFull, - WorkspaceFull, - SessionFull, - NoSlot, -} - -impl std::fmt::Display for ScheduleError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::QueueFull => write!(f, "queue_full"), - Self::WorkspaceFull => write!(f, "workspace_full"), - Self::SessionFull => write!(f, "session_full"), - Self::NoSlot => write!(f, "no_slot"), - } - } -} - -struct QueueState { - global: VecDeque, - by_workspace: HashMap>, - by_session: HashMap, - active_execute: usize, - active_short: usize, - active_read: usize, - /// workspace rotation cursor - workspace_order: VecDeque, -} - -pub struct Scheduler { - cfg: SchedulerConfig, - inner: Mutex, -} - -impl Scheduler { - pub fn new(cfg: SchedulerConfig) -> Self { - Self { - cfg, - inner: Mutex::new(QueueState { - global: VecDeque::new(), - by_workspace: HashMap::new(), - by_session: HashMap::new(), - active_execute: 0, - active_short: 0, - active_read: 0, - workspace_order: VecDeque::new(), - }), - } - } - - pub fn enqueue(&self, task: &TaskRecord, class: AdmissionClass) -> Result { - if class == AdmissionClass::Control || class == AdmissionClass::LegacySerial { - return Ok(0); - } - let mut g = self.inner.lock().unwrap(); - if g.global.len() >= self.cfg.global_queue_limit { - return Err(ScheduleError::QueueFull); - } - let ws_len = g - .by_workspace - .get(&task.workspace_id) - .map(|q| q.len()) - .unwrap_or(0); - if ws_len >= self.cfg.workspace_queue_limit { - return Err(ScheduleError::WorkspaceFull); - } - if let Some(sid) = &task.session_id { - let n = g.by_session.entry(sid.clone()).or_insert(0); - if *n >= self.cfg.session_pending_limit { - return Err(ScheduleError::SessionFull); - } - *n += 1; - } - if !g.workspace_order.iter().any(|w| w == &task.workspace_id) { - g.workspace_order.push_back(task.workspace_id.clone()); - } - g.by_workspace - .entry(task.workspace_id.clone()) - .or_default() - .push_back(task.task_id.clone()); - g.global.push_back(task.task_id.clone()); - Ok(g.global.len()) - } - - pub fn try_acquire_slot(&self, class: AdmissionClass) -> Result<(), ScheduleError> { - let mut g = self.inner.lock().unwrap(); - match class { - AdmissionClass::Execute => { - if g.active_execute >= self.cfg.execute_slots { - return Err(ScheduleError::NoSlot); - } - g.active_execute += 1; - } - AdmissionClass::Short | AdmissionClass::Commit => { - if g.active_short >= self.cfg.short_slots { - return Err(ScheduleError::NoSlot); - } - g.active_short += 1; - } - AdmissionClass::Read => { - if g.active_read >= self.cfg.read_slots { - return Err(ScheduleError::NoSlot); - } - g.active_read += 1; - } - AdmissionClass::Control | AdmissionClass::LegacySerial => {} - } - Ok(()) - } - - pub fn release_slot(&self, class: AdmissionClass) { - let mut g = self.inner.lock().unwrap(); - match class { - AdmissionClass::Execute => { - g.active_execute = g.active_execute.saturating_sub(1); - } - AdmissionClass::Short | AdmissionClass::Commit => { - g.active_short = g.active_short.saturating_sub(1); - } - AdmissionClass::Read => { - g.active_read = g.active_read.saturating_sub(1); - } - AdmissionClass::Control | AdmissionClass::LegacySerial => {} - } - } - - /// Fair pop: rotate workspaces, then session FIFO within workspace. - pub fn pop_next(&self) -> Option { - let mut g = self.inner.lock().unwrap(); - if g.workspace_order.is_empty() { - return None; - } - for _ in 0..g.workspace_order.len() { - let ws = g.workspace_order.pop_front()?; - if let Some(q) = g.by_workspace.get_mut(&ws) { - if let Some(tid) = q.pop_front() { - g.workspace_order.push_back(ws); - g.global.retain(|id| id != &tid); - return Some(tid); - } - } - } - None - } - - pub fn queue_depth(&self) -> usize { - self.inner.lock().unwrap().global.len() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::runtime::task_store::{TaskRecord, TaskState}; - - fn task(id: &str, ws: &str, session: Option<&str>) -> TaskRecord { - TaskRecord { - task_id: id.into(), - run_id: format!("r-{id}"), - attempt_id: format!("a-{id}"), - workspace_id: ws.into(), - session_id: session.map(|s| s.into()), - state: TaskState::Queued, - revision: 1, - idempotency_key: id.into(), - payload_hash: "h".into(), - lease_id: None, - lease_epoch: None, - created_at: "0".into(), - updated_at: "0".into(), - cancel_requested_at: None, - result: None, - error: None, - } - } - - #[test] - fn workspace_rotation_fairness() { - let sched = Scheduler::new(SchedulerConfig::default()); - sched - .enqueue(&task("a1", "wsA", None), AdmissionClass::Execute) - .unwrap(); - sched - .enqueue(&task("a2", "wsA", None), AdmissionClass::Execute) - .unwrap(); - sched - .enqueue(&task("b1", "wsB", None), AdmissionClass::Execute) - .unwrap(); - assert_eq!(sched.pop_next().as_deref(), Some("a1")); - assert_eq!(sched.pop_next().as_deref(), Some("b1")); - assert_eq!(sched.pop_next().as_deref(), Some("a2")); - } -} diff --git a/src/runtime/supervisor.rs b/src/runtime/supervisor.rs deleted file mode 100755 index 28bc03c..0000000 --- a/src/runtime/supervisor.rs +++ /dev/null @@ -1,303 +0,0 @@ -//! Supervisor: lease workers, enforce deadlines, reap orphans (M-R2). - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; - -use crate::runtime::lease::{Lease, WorkerState}; -use crate::runtime::protocol::InvokeRequestV2; -use crate::runtime::worker::{WorkerHandle, WorkerPool}; - -#[derive(Debug, Clone)] -pub struct SupervisorConfig { - pub execute_slots: usize, - pub worker_ttl: Duration, - pub cancel_grace: Duration, - pub force_kill_after: Duration, -} - -impl Default for SupervisorConfig { - fn default() -> Self { - Self { - execute_slots: 2, - worker_ttl: Duration::from_secs(600), - cancel_grace: Duration::from_secs(2), - force_kill_after: Duration::from_secs(3), - } - } -} - -struct ActiveWorker { - handle: WorkerHandle, - cancel_since: Option, -} - -pub struct Supervisor { - cfg: SupervisorConfig, - pool: Mutex, - active: Mutex>, - cancel_dir: PathBuf, - event_dir: PathBuf, -} - -impl Supervisor { - pub fn new( - cfg: SupervisorConfig, - staging_root: impl AsRef, - marqdo_bin: impl AsRef, - cancel_dir: impl AsRef, - event_dir: impl AsRef, - ) -> Self { - let cancel_dir = cancel_dir.as_ref().to_path_buf(); - let event_dir = event_dir.as_ref().to_path_buf(); - let _ = std::fs::create_dir_all(&cancel_dir); - let _ = std::fs::create_dir_all(&event_dir); - Self { - pool: Mutex::new(WorkerPool::new( - staging_root, - marqdo_bin, - cfg.execute_slots, - )), - cfg, - active: Mutex::new(HashMap::new()), - cancel_dir, - event_dir, - } - } - - pub fn warm(&self) -> Result<(), String> { - self.pool.lock().unwrap().warm() - } - - pub fn dispatch(&self, req: InvokeRequestV2) -> Result { - req.validate()?; - { - let active = self.active.lock().unwrap(); - if active.len() >= self.cfg.execute_slots { - return Err("supervisor.no_slot".into()); - } - } - let mut pool = self.pool.lock().unwrap(); - let worker = pool.acquire()?; - drop(pool); - let epoch = Instant::now().elapsed().as_nanos() as u64; - let lease = Lease::new( - format!("lease_{}", req.task_id), - epoch, - &req.task_id, - &req.run_id, - &req.attempt_id, - self.cfg.worker_ttl, - ); - let cancel = self.cancel_dir.join(format!("{}.tok", req.task_id)); - if !cancel.exists() { - std::fs::write(&cancel, b"").map_err(|e| e.to_string())?; - } - let events = self.event_dir.join(format!("{}.ndjson", req.task_id)); - std::fs::write(&events, b"").map_err(|e| e.to_string())?; - // Durable emit path (not under staging — WorkerHandle::Drop removes staging). - let emit = self.event_dir.join(format!("{}.result.json", req.task_id)); - let fs_root = req - .context - .fs_root - .as_ref() - .map(PathBuf::from) - .filter(|p| p.is_dir()) - .ok_or_else(|| "supervisor.fs_root_required".to_string())?; - let args_path = req.args_ref.as_ref().and_then(|r| { - r.strip_prefix("file:") - .map(PathBuf::from) - .or_else(|| { - let p = PathBuf::from(r); - p.is_file().then_some(p) - }) - }); - let handle = { - if std::env::var_os("MARQDO_RUNTIME_DRY_RUN").is_some() { - let mut w = worker; - w.lease = Some(lease.clone()); - w.emit_result = Some(emit.clone()); - w.state = WorkerState::Running; - w - } else { - self.pool.lock().unwrap().lease_and_start( - worker, - lease.clone(), - &req, - &cancel, - &events, - &fs_root, - args_path.as_deref(), - &emit, - )? - } - }; - let lease_id = lease.id.0.clone(); - self.active.lock().unwrap().insert( - lease_id.clone(), - ActiveWorker { - handle, - cancel_since: None, - }, - ); - Ok(lease_id) - } - - pub fn event_path(&self, task_id: &str) -> PathBuf { - self.event_dir.join(format!("{task_id}.ndjson")) - } - - pub fn cancel_path(&self, task_id: &str) -> PathBuf { - self.cancel_dir.join(format!("{task_id}.tok")) - } - - pub fn emit_result_path(&self, lease_id: &str) -> Option { - self.active - .lock() - .unwrap() - .get(lease_id) - .and_then(|w| w.handle.emit_result.clone()) - } - - /// Non-blocking poll: if worker exited, remove from active and return exit code. - pub fn try_reap(&self, lease_id: &str) -> Result, String> { - let mut active = self.active.lock().unwrap(); - let Some(w) = active.get_mut(lease_id) else { - return Ok(None); - }; - match w.handle.try_wait()? { - Some(st) => { - let code = st.code().unwrap_or(-1); - active.remove(lease_id); - let _ = self.pool.lock().unwrap().warm(); - Ok(Some(code)) - } - None => Ok(None), - } - } - - pub fn signal_cancel(&self, lease_id: &str, task_id: &str) -> Result<(), String> { - let tok = self.cancel_dir.join(format!("{task_id}.tok")); - std::fs::write(&tok, b"cancelled").map_err(|e| e.to_string())?; - let mut active = self.active.lock().unwrap(); - if let Some(w) = active.get_mut(lease_id) { - w.cancel_since = Some(Instant::now()); - w.handle.state = WorkerState::Draining; - } - Ok(()) - } - - /// Reap expired / force-kill after cancel grace. Returns orphan count. - pub fn janitor_tick(&self) -> usize { - let mut orphans = 0usize; - let mut active = self.active.lock().unwrap(); - let mut done = Vec::new(); - for (id, w) in active.iter_mut() { - if let Some(lease) = &w.handle.lease { - if lease.expired() { - w.handle.kill_process_group(); - orphans += 1; - done.push(id.clone()); - continue; - } - } - if let Some(since) = w.cancel_since { - if since.elapsed() > self.cfg.cancel_grace + self.cfg.force_kill_after { - w.handle.kill_process_group(); - orphans += 1; - done.push(id.clone()); - } - } - } - for id in done { - active.remove(&id); - } - orphans - } - - pub fn active_count(&self) -> usize { - self.active.lock().unwrap().len() - } - - pub fn release(&self, lease_id: &str) { - let mut active = self.active.lock().unwrap(); - if let Some(mut w) = active.remove(lease_id) { - w.handle.state = WorkerState::Draining; - w.handle.kill_process_group(); - } - // Async replenish hint. - let _ = self.pool.lock().unwrap().warm(); - } -} - -/// Shared supervisor handle for HTTP/control wiring. -pub type SharedSupervisor = Arc; - -#[cfg(test)] -mod tests { - use super::*; - use crate::runtime::protocol::{EntryRef, InvokeContext, LeaseRef}; - - fn req(task: &str) -> InvokeRequestV2 { - InvokeRequestV2 { - schema: "InvokeRequestV2".into(), - schema_version: 2, - task_id: task.into(), - run_id: format!("run_{task}"), - attempt_id: format!("attempt_{task}"), - lease: LeaseRef { - id: format!("lease_{task}"), - epoch: 1, - }, - entry: EntryRef { - module: "agent/qdagent.mq.md".into(), - function: "run".into(), - }, - args_ref: None, - context: InvokeContext { - workspace_id: "ws".into(), - snapshot_id: None, - selection_ref: None, - capabilities_ref: None, - deadline_at: "2099-01-01T00:00:00Z".into(), - fs_root: Some("/tmp".into()), - }, - } - } - - #[test] - fn dry_run_two_parallel_leases() { - std::env::set_var("MARQDO_RUNTIME_DRY_RUN", "1"); - let root = std::env::temp_dir().join(format!("mq-sup-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let bin = std::env::current_exe().unwrap(); - let _ = std::fs::create_dir_all(root.join("fs")); - let mut ra = req("a"); - ra.context.fs_root = Some(root.join("fs").to_string_lossy().into()); - let mut rb = req("b"); - rb.context.fs_root = ra.context.fs_root.clone(); - let mut rc = req("c"); - rc.context.fs_root = ra.context.fs_root.clone(); - let sup = Supervisor::new( - SupervisorConfig { - execute_slots: 2, - ..SupervisorConfig::default() - }, - root.join("stage"), - &bin, - root.join("cancel"), - root.join("events"), - ); - sup.warm().unwrap(); - let a = sup.dispatch(ra).unwrap(); - let b = sup.dispatch(rb).unwrap(); - assert_ne!(a, b); - assert_eq!(sup.active_count(), 2); - assert!(sup.dispatch(rc).is_err()); - sup.release(&a); - assert_eq!(sup.active_count(), 1); - let _ = std::fs::remove_dir_all(&root); - std::env::remove_var("MARQDO_RUNTIME_DRY_RUN"); - } -} diff --git a/src/runtime/task_store.rs b/src/runtime/task_store.rs deleted file mode 100755 index 734e1c7..0000000 --- a/src/runtime/task_store.rs +++ /dev/null @@ -1,385 +0,0 @@ -//! Task index with idempotency, revision CAS, and event log (M-R3 / M-R4). - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; -use std::time::{SystemTime, UNIX_EPOCH}; - -use serde::{Deserialize, Serialize}; -use serde_json::Value; -use sha2::{Digest, Sha256}; - -use crate::runtime::protocol::RuntimeEventV2; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum TaskState { - Accepted, - Queued, - Running, - Finalizing, - Succeeded, - Failed, - CancelRequested, - Cancelled, - Interrupted, - NeedsReconciliation, -} - -impl TaskState { - pub fn is_terminal(self) -> bool { - matches!( - self, - Self::Succeeded - | Self::Failed - | Self::Cancelled - | Self::Interrupted - | Self::NeedsReconciliation - ) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct TaskRecord { - pub task_id: String, - pub run_id: String, - pub attempt_id: String, - pub workspace_id: String, - pub session_id: Option, - pub state: TaskState, - pub revision: u64, - pub idempotency_key: String, - pub payload_hash: String, - pub lease_id: Option, - pub lease_epoch: Option, - pub created_at: String, - pub updated_at: String, - pub cancel_requested_at: Option, - pub result: Option, - pub error: Option, -} - -#[derive(Default)] -struct Inner { - tasks: HashMap, - /// idempotency_key → task_id - idem: HashMap, - /// task_id → events (monotonic seq) - events: HashMap>, - next_epoch: u64, -} - -pub struct TaskStore { - inner: Arc>, - persist_dir: Option, -} - -#[derive(Debug)] -pub enum StoreError { - Conflict(String), - NotFound, - AlreadyTerminal(TaskState), - Io(String), -} - -impl std::fmt::Display for StoreError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Conflict(s) => write!(f, "conflict: {s}"), - Self::NotFound => write!(f, "not_found"), - Self::AlreadyTerminal(s) => write!(f, "already_terminal:{s:?}"), - Self::Io(s) => write!(f, "io: {s}"), - } - } -} - -impl TaskStore { - pub fn memory() -> Self { - Self { - inner: Arc::new(Mutex::new(Inner::default())), - persist_dir: None, - } - } - - pub fn with_persist(dir: impl AsRef) -> Result { - let dir = dir.as_ref().to_path_buf(); - std::fs::create_dir_all(&dir).map_err(|e| StoreError::Io(e.to_string()))?; - let store = Self { - inner: Arc::new(Mutex::new(Inner::default())), - persist_dir: Some(dir.clone()), - }; - store.load()?; - Ok(store) - } - - fn now() -> String { - let ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis(); - format!("{ms}") - } - - pub fn payload_hash(payload: &Value) -> String { - let bytes = serde_json::to_vec(payload).unwrap_or_default(); - format!("{:x}", Sha256::digest(&bytes)) - } - - /// Admit or return existing task for the same idempotency key. - /// Same key + different payload hash → Conflict (409). - pub fn admit( - &self, - task_id: impl Into, - run_id: impl Into, - workspace_id: impl Into, - session_id: Option, - idempotency_key: impl Into, - payload: &Value, - ) -> Result { - let task_id = task_id.into(); - let idempotency_key = idempotency_key.into(); - let payload_hash = Self::payload_hash(payload); - let mut g = self.inner.lock().unwrap(); - if let Some(existing_id) = g.idem.get(&idempotency_key).cloned() { - let existing = g.tasks.get(&existing_id).cloned().ok_or(StoreError::NotFound)?; - if existing.payload_hash != payload_hash { - return Err(StoreError::Conflict( - "idempotency key reuse with different payload".into(), - )); - } - return Ok(existing); - } - let now = Self::now(); - let rec = TaskRecord { - task_id: task_id.clone(), - run_id: run_id.into(), - attempt_id: format!("attempt_{}", task_id), - workspace_id: workspace_id.into(), - session_id, - state: TaskState::Accepted, - revision: 1, - idempotency_key: idempotency_key.clone(), - payload_hash, - lease_id: None, - lease_epoch: None, - created_at: now.clone(), - updated_at: now, - cancel_requested_at: None, - result: None, - error: None, - }; - g.idem.insert(idempotency_key, task_id.clone()); - g.tasks.insert(task_id, rec.clone()); - g.events.insert(rec.task_id.clone(), Vec::new()); - drop(g); - self.persist_task(&rec)?; - Ok(rec) - } - - pub fn get(&self, task_id: &str) -> Result { - self.inner - .lock() - .unwrap() - .tasks - .get(task_id) - .cloned() - .ok_or(StoreError::NotFound) - } - - /// CAS state transition. `expected_revision` must match. - pub fn cas_state( - &self, - task_id: &str, - expected_revision: u64, - next: TaskState, - patch: impl FnOnce(&mut TaskRecord), - ) -> Result { - let mut g = self.inner.lock().unwrap(); - let rec = g.tasks.get_mut(task_id).ok_or(StoreError::NotFound)?; - if rec.revision != expected_revision { - return Err(StoreError::Conflict(format!( - "revision {} != {}", - rec.revision, expected_revision - ))); - } - if rec.state.is_terminal() && next != rec.state { - return Err(StoreError::AlreadyTerminal(rec.state)); - } - rec.state = next; - rec.revision += 1; - rec.updated_at = Self::now(); - patch(rec); - let out = rec.clone(); - drop(g); - self.persist_task(&out)?; - Ok(out) - } - - pub fn request_cancel(&self, task_id: &str) -> Result { - let mut g = self.inner.lock().unwrap(); - let rec = g.tasks.get_mut(task_id).ok_or(StoreError::NotFound)?; - if rec.state.is_terminal() { - return Err(StoreError::AlreadyTerminal(rec.state)); - } - let rev = rec.revision; - rec.state = TaskState::CancelRequested; - rec.revision = rev + 1; - rec.cancel_requested_at = Some(Self::now()); - rec.updated_at = Self::now(); - let out = rec.clone(); - drop(g); - self.persist_task(&out)?; - Ok(out) - } - - pub fn append_event( - &self, - task_id: &str, - run_id: &str, - attempt_id: &str, - event_type: &str, - payload: Value, - ) -> Result { - let mut g = self.inner.lock().unwrap(); - if !g.tasks.contains_key(task_id) { - return Err(StoreError::NotFound); - } - let list = g.events.entry(task_id.to_string()).or_default(); - let seq = list.last().map(|e| e.seq + 1).unwrap_or(1); - let ev = RuntimeEventV2::new(task_id, run_id, attempt_id, seq, event_type, payload); - list.push(ev.clone()); - drop(g); - self.persist_event(&ev)?; - Ok(ev) - } - - /// Events with seq > after_seq (Last-Event-ID resume). - pub fn events_after( - &self, - task_id: &str, - after_seq: u64, - ) -> Result, StoreError> { - let g = self.inner.lock().unwrap(); - let list = g.events.get(task_id).ok_or(StoreError::NotFound)?; - Ok(list.iter().filter(|e| e.seq > after_seq).cloned().collect()) - } - - pub fn next_lease_epoch(&self) -> u64 { - let mut g = self.inner.lock().unwrap(); - g.next_epoch += 1; - g.next_epoch - } - - fn persist_task(&self, rec: &TaskRecord) -> Result<(), StoreError> { - let Some(dir) = &self.persist_dir else { - return Ok(()); - }; - let path = dir.join("tasks").join(format!("{}.json", rec.task_id)); - std::fs::create_dir_all(path.parent().unwrap()).map_err(|e| StoreError::Io(e.to_string()))?; - let tmp = path.with_extension("json.tmp"); - let body = serde_json::to_vec_pretty(rec).map_err(|e| StoreError::Io(e.to_string()))?; - std::fs::write(&tmp, body).map_err(|e| StoreError::Io(e.to_string()))?; - std::fs::rename(&tmp, &path).map_err(|e| StoreError::Io(e.to_string()))?; - Ok(()) - } - - fn persist_event(&self, ev: &RuntimeEventV2) -> Result<(), StoreError> { - let Some(dir) = &self.persist_dir else { - return Ok(()); - }; - let path = dir.join("events").join(format!("{}.ndjson", ev.task_id)); - std::fs::create_dir_all(path.parent().unwrap()).map_err(|e| StoreError::Io(e.to_string()))?; - use std::io::Write; - let mut f = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) - .map_err(|e| StoreError::Io(e.to_string()))?; - let line = serde_json::to_string(ev).map_err(|e| StoreError::Io(e.to_string()))?; - writeln!(f, "{line}").map_err(|e| StoreError::Io(e.to_string()))?; - Ok(()) - } - - fn load(&self) -> Result<(), StoreError> { - let Some(dir) = &self.persist_dir else { - return Ok(()); - }; - let tasks_dir = dir.join("tasks"); - if !tasks_dir.is_dir() { - return Ok(()); - } - let mut g = self.inner.lock().unwrap(); - for ent in std::fs::read_dir(&tasks_dir).map_err(|e| StoreError::Io(e.to_string()))? { - let ent = ent.map_err(|e| StoreError::Io(e.to_string()))?; - if ent.path().extension().and_then(|e| e.to_str()) != Some("json") { - continue; - } - let body = - std::fs::read_to_string(ent.path()).map_err(|e| StoreError::Io(e.to_string()))?; - let rec: TaskRecord = - serde_json::from_str(&body).map_err(|e| StoreError::Io(e.to_string()))?; - g.idem - .insert(rec.idempotency_key.clone(), rec.task_id.clone()); - g.events.entry(rec.task_id.clone()).or_default(); - g.tasks.insert(rec.task_id.clone(), rec); - } - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn idempotent_admit_and_conflict() { - let store = TaskStore::memory(); - let p = json!({"a": 1}); - let a = store - .admit("t1", "r1", "ws", None, "key-1", &p) - .unwrap(); - let b = store - .admit("t2", "r2", "ws", None, "key-1", &p) - .unwrap(); - assert_eq!(a.task_id, b.task_id); - let err = store - .admit("t3", "r3", "ws", None, "key-1", &json!({"a": 2})) - .unwrap_err(); - assert!(matches!(err, StoreError::Conflict(_))); - } - - #[test] - fn cancel_cas_terminal() { - let store = TaskStore::memory(); - let t = store - .admit("t1", "r1", "ws", None, "k", &json!({})) - .unwrap(); - store - .cas_state(&t.task_id, t.revision, TaskState::Succeeded, |r| { - r.result = Some(json!("ok")); - }) - .unwrap(); - let err = store.request_cancel(&t.task_id).unwrap_err(); - assert!(matches!(err, StoreError::AlreadyTerminal(TaskState::Succeeded))); - } - - #[test] - fn event_seq_monotonic_and_resume() { - let store = TaskStore::memory(); - let t = store - .admit("t1", "r1", "ws", None, "k", &json!({})) - .unwrap(); - let e1 = store - .append_event(&t.task_id, &t.run_id, &t.attempt_id, "message.delta", json!({"n":1})) - .unwrap(); - let e2 = store - .append_event(&t.task_id, &t.run_id, &t.attempt_id, "message.delta", json!({"n":2})) - .unwrap(); - assert_eq!(e1.seq, 1); - assert_eq!(e2.seq, 2); - let after = store.events_after(&t.task_id, 1).unwrap(); - assert_eq!(after.len(), 1); - assert_eq!(after[0].seq, 2); - } -} diff --git a/src/runtime/worker.rs b/src/runtime/worker.rs deleted file mode 100755 index 075eba1..0000000 --- a/src/runtime/worker.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! One-shot Marqdo worker process handles (M-R2). - -use std::path::{Path, PathBuf}; -use std::process::{Child, Command, Stdio}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use serde_json::{json, Value}; - -use crate::runtime::lease::{Lease, WorkerState}; -use crate::runtime::protocol::{InvokeRequestV2, PROTOCOL_VERSION}; - -static WORKER_SEQ: AtomicU64 = AtomicU64::new(1); - -pub struct WorkerHandle { - pub id: String, - pub state: WorkerState, - pub lease: Option, - child: Option, - staging: PathBuf, - /// Where the child writes `--emit-result` JSON. - pub emit_result: Option, -} - -impl WorkerHandle { - pub fn staging(&self) -> &Path { - &self.staging - } - - pub fn take_child(&mut self) -> Option { - self.child.take() - } - - pub fn kill_process_group(&mut self) { - if let Some(mut child) = self.child.take() { - let _ = child.kill(); - let _ = child.wait(); - } - self.state = WorkerState::Exited; - } - - pub fn try_wait(&mut self) -> Result, String> { - let Some(child) = self.child.as_mut() else { - return Ok(None); - }; - child.try_wait().map_err(|e| format!("worker.wait: {e}")) - } - - pub fn wait(&mut self) -> Result { - let Some(mut child) = self.child.take() else { - return Err("worker.no_child".into()); - }; - let st = child.wait().map_err(|e| format!("worker.wait: {e}"))?; - self.state = WorkerState::Exited; - Ok(st) - } -} - -impl Drop for WorkerHandle { - fn drop(&mut self) { - self.kill_process_group(); - let _ = std::fs::remove_dir_all(&self.staging); - } -} - -pub struct WorkerPool { - staging_root: PathBuf, - marqdo_bin: PathBuf, - ready: Vec, - target_ready: usize, -} - -impl WorkerPool { - pub fn new(staging_root: impl AsRef, marqdo_bin: impl AsRef, target_ready: usize) -> Self { - let staging_root = staging_root.as_ref().to_path_buf(); - let _ = std::fs::create_dir_all(&staging_root); - Self { - staging_root, - marqdo_bin: marqdo_bin.as_ref().to_path_buf(), - ready: Vec::new(), - target_ready, - } - } - - pub fn spawn_ready(&mut self) -> Result { - let seq = WORKER_SEQ.fetch_add(1, Ordering::Relaxed); - let id = format!("worker_{seq}"); - let staging = self.staging_root.join(&id); - std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; - if !self.marqdo_bin.exists() { - return Err(format!("worker.binary_missing: {}", self.marqdo_bin.display())); - } - Ok(WorkerHandle { - id, - state: WorkerState::Ready, - lease: None, - child: None, - staging, - emit_result: None, - }) - } - - pub fn warm(&mut self) -> Result<(), String> { - while self.ready.len() < self.target_ready { - let w = self.spawn_ready()?; - self.ready.push(w); - } - Ok(()) - } - - pub fn acquire(&mut self) -> Result { - if self.ready.is_empty() { - self.warm()?; - } - self.ready - .pop() - .ok_or_else(|| "worker.pool_empty".to_string()) - } - - pub fn replenish_async_hint(&self) -> usize { - self.target_ready.saturating_sub(self.ready.len()) - } - - /// Lease a worker: spawn `marqdo run --call-lib-path …` with request-scoped env. - /// `emit_result` must be outside staging so Drop does not erase the parent's read path. - pub fn lease_and_start( - &self, - mut worker: WorkerHandle, - lease: Lease, - req: &InvokeRequestV2, - cancel_token: &Path, - event_sink: &Path, - fs_root: &Path, - args_json: Option<&Path>, - emit_result: &Path, - ) -> Result { - req.validate()?; - let entry = PathBuf::from(&req.entry.module); - if !entry.is_file() { - return Err(format!( - "worker.entry_missing: {} (need absolute site entry .mq.md)", - entry.display() - )); - } - if let Some(parent) = emit_result.parent() { - std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; - } - let emit = emit_result.to_path_buf(); - let mut cmd = Command::new(&self.marqdo_bin); - cmd.arg("run") - .arg(&entry) - .arg("--call-lib-path") - .arg(&req.entry.function) - .arg("--fs-root") - .arg(fs_root) - .arg("--emit-result") - .arg(&emit) - // Worker cwd = site root so relative imports resolve; staging only for lease bookkeeping. - .current_dir(fs_root) - .env("MARQDO_RUN_ID", &req.run_id) - .env("MARQDO_TASK_ID", &req.task_id) - .env("MARQDO_ATTEMPT_ID", &req.attempt_id) - .env("MARQDO_LEASE_ID", &lease.id.0) - .env("MARQDO_LEASE_EPOCH", lease.epoch.to_string()) - .env("MARQDO_CANCEL_TOKEN", cancel_token) - .env("MARQDO_EVENT_FORWARD", event_sink) - .env("MARQDO_WORKSPACE_ID", &req.context.workspace_id) - .env("MARQDO_PROTOCOL_VERSION", PROTOCOL_VERSION.to_string()) - .env("MARQDO_FS_ROOT", fs_root) - .stdin(Stdio::null()) - // Avoid pipe-buffer deadlock: nobody drains worker stdout/stderr. - .stdout(Stdio::null()) - .stderr(Stdio::null()); - if let Some(args) = args_json { - cmd.arg("--args-json").arg(args); - } else if let Some(r) = &req.args_ref { - if let Some(path) = r.strip_prefix("file:") { - cmd.arg("--args-json").arg(path); - } - } - if let Some(sel) = &req.context.selection_ref { - cmd.env("MARQDO_SELECTION_REF", sel); - } - if let Some(snap) = &req.context.snapshot_id { - cmd.env("MARQDO_SNAPSHOT_ID", snap); - } - if let Some(cap) = &req.context.capabilities_ref { - cmd.env("MARQDO_CAPABILITIES_REF", cap); - } - let child = cmd.spawn().map_err(|e| format!("worker.spawn: {e}"))?; - worker.child = Some(child); - worker.lease = Some(lease); - worker.emit_result = Some(emit); - worker.state = WorkerState::Running; - Ok(worker) - } -} - -pub fn handshake_ok(report: &Value) -> Result<(), String> { - let ver = report - .get("protocol_version") - .and_then(|v| v.as_u64()) - .ok_or("handshake.protocol_version")?; - if ver != PROTOCOL_VERSION as u64 { - return Err(format!("handshake.version_mismatch: {ver}")); - } - Ok(()) -} - -pub fn fake_handshake() -> Value { - json!({ - "cli": true, - "protocol_version": PROTOCOL_VERSION, - "capabilities": ["runtime.isolated_execution"], - "build": env!("CARGO_PKG_VERSION"), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn handshake_version_gate() { - assert!(handshake_ok(&fake_handshake()).is_ok()); - assert!(handshake_ok(&json!({"protocol_version": 1})).is_err()); - } - - #[test] - fn pool_warm_requires_binary() { - let dir = std::env::temp_dir().join(format!("mq-pool-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let mut pool = WorkerPool::new(&dir, "/no/such/marqdo-bin", 1); - assert!(pool.warm().is_err()); - let self_bin = std::env::current_exe().unwrap(); - let mut pool = WorkerPool::new(&dir, &self_bin, 1); - pool.warm().unwrap(); - assert_eq!(pool.ready.len(), 1); - let w = pool.acquire().unwrap(); - assert_eq!(w.state, WorkerState::Ready); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn kill_clears_child() { - let dir = std::env::temp_dir().join(format!("mq-wh-{}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); - let mut w = WorkerHandle { - id: "w".into(), - state: WorkerState::Running, - lease: None, - child: None, - staging: dir.clone(), - emit_result: None, - }; - w.kill_process_group(); - assert_eq!(w.state, WorkerState::Exited); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/src/sema/bind.rs b/src/sema/bind.rs deleted file mode 100755 index 024d824..0000000 --- a/src/sema/bind.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Shared call binding for execution (G02 BoundCall). -//! -//! Tree and Bytecode must agree: explicit import paths and same-module bare -//! names bind; bare names never silently pick an imported symbol; true -//! dynamics are marked separately. - -use crate::ast::{CallExpr, Function, Module}; - -/// Why a call site is not a static BoundCall. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DynamicReason { - MethodReceiver, - CallFn, - Plugin, -} - -impl DynamicReason { - pub fn as_str(self) -> &'static str { - match self { - Self::MethodReceiver => "method_receiver", - Self::CallFn => "call_fn", - Self::Plugin => "plugin", - } - } -} - -pub type ExecTarget<'a> = super::resolution::Target<&'a Function, &'a Module>; - -pub fn call_display(call: &CallExpr) -> String { - if let Some(path) = &call.path { - return path.join("."); - } - if let Some(recv) = &call.receiver { - return format!("{recv}.{}", call.callee); - } - call.callee.clone() -} - -/// Same-module bare names never search imports. -pub fn lookup_local<'a>(module: &'a Module, current: &'a Function, name: &str) -> Option<&'a Function> { - super::resolution::lookup(&super::resolution::AstView::default(), &module, current, name) -} -pub fn resolve_for_exec<'a>(module: &'a Module, current: &'a Function, call: &CallExpr) -> ExecTarget<'a> { - match call.for_evaluation() { - Ok(normalized) => super::resolution::resolve(&super::resolution::AstView::default(), &module, current, &normalized), - Err(message) => ExecTarget::Unresolved { message, span_hint: None }, - } -} - -pub fn is_static_bound(target: &ExecTarget<'_>) -> bool { - matches!( - target, - ExecTarget::Local(_) - | ExecTarget::Import { .. } - | ExecTarget::Builtin(_) - | ExecTarget::Host(_) - ) -} diff --git a/src/sema/extract.rs b/src/sema/extract.rs deleted file mode 100755 index 367889b..0000000 --- a/src/sema/extract.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! Restricted pure-expression extract (S3). -//! -//! Only Literal / Var / Unary / Binary / List / Map / Index payloads may be -//! lifted. Calls, host, and plugins are refused so effect counts stay zero. - -use std::collections::BTreeSet; - -use crate::ast::Expr; -use crate::parse::expr::parse_expr_prefer_var; - -#[derive(Debug, Clone)] -pub struct ExtractPlan { - pub name: String, - pub params: Vec, - pub expression: String, - pub heading: String, - pub call: String, -} - -#[derive(Debug, Clone)] -pub struct ExtractError { - pub code: &'static str, - pub message: String, -} - -/// Build an extract plan from a pure expression string (no file I/O). -pub fn plan_pure_extract(name: &str, expression: &str) -> Result { - let name = name.trim(); - if name.is_empty() - || name.contains(|c: char| c.is_whitespace() || c == '.' || c == '/') - { - return Err(ExtractError { - code: "extract.bad_name", - message: "提取目标名必须是单个标识符".into(), - }); - } - let expr = parse_expr_prefer_var(expression).map_err(|e| ExtractError { - code: "extract.parse", - message: format!("无法解析表达式: {e}"), - })?; - if !is_pure_payload(&expr) { - return Err(ExtractError { - code: "extract.not_pure", - message: "仅允许字面量/变量/算术/列表等纯载荷;拒绝调用与宿主效应".into(), - }); - } - let params: Vec = free_vars(&expr).into_iter().collect(); - let call = if params.is_empty() { - format!("{name}()") - } else { - let args = params - .iter() - .map(|p| format!("{p}=`{p}`")) - .collect::>() - .join(", "); - format!("{name}({args})") - }; - let heading = if params.is_empty() { - format!("## {name}\n\n*{expression}*\n") - } else { - let decls = params - .iter() - .map(|p| format!("`{p}`")) - .collect::>() - .join("、"); - format!("## {name}\n\n参数:{decls}\n\n*{expression}*\n") - }; - Ok(ExtractPlan { - name: name.into(), - params, - expression: expression.trim().into(), - heading, - call, - }) -} - -fn is_pure_payload(expr: &Expr) -> bool { - match expr { - Expr::Literal(_) | Expr::Var(_) => true, - Expr::Unary { expr, .. } => is_pure_payload(expr), - Expr::Binary { left, right, .. } => is_pure_payload(left) && is_pure_payload(right), - Expr::List(items) => items.iter().all(is_pure_payload), - Expr::Map(items) => items.iter().all(|(_, v)| is_pure_payload(v)), - Expr::Index { base, .. } => is_pure_payload(base), - Expr::Occluded { payload, .. } => payload - .as_ref() - .map(|p| is_pure_payload(p)) - .unwrap_or(true), - Expr::Call(_) | Expr::Interp(_) | Expr::Formula(_) | Expr::Code(_) => false, - } -} - -fn free_vars(expr: &Expr) -> BTreeSet { - let mut out = BTreeSet::new(); - walk(expr, &mut out); - out -} - -fn walk(expr: &Expr, out: &mut BTreeSet) { - match expr { - Expr::Var(name) => { - out.insert(name.clone()); - } - Expr::Unary { expr, .. } => walk(expr, out), - Expr::Binary { left, right, .. } => { - walk(left, out); - walk(right, out); - } - Expr::List(items) => { - for item in items { - walk(item, out); - } - } - Expr::Map(items) => { - for (_, item) in items { - walk(item, out); - } - } - Expr::Index { base, .. } => walk(base, out), - Expr::Occluded { payload, .. } => { - if let Some(p) = payload { - walk(p, out); - } - } - Expr::Literal(_) - | Expr::Call(_) - | Expr::Interp(_) - | Expr::Formula(_) - | Expr::Code(_) => {} - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn extracts_product() { - let plan = plan_pure_extract("商品小计", "数量 * 单价").unwrap(); - assert_eq!(plan.params, vec!["单价".to_string(), "数量".to_string()]); - assert!(plan.heading.contains("## 商品小计")); - assert!(plan.call.contains("商品小计(")); - } - - #[test] - fn rejects_call() { - let err = plan_pure_extract("x", "save()").unwrap_err(); - assert_eq!(err.code, "extract.not_pure"); - } -} diff --git a/src/sema/ir.rs b/src/sema/ir.rs deleted file mode 100755 index 455c814..0000000 --- a/src/sema/ir.rs +++ /dev/null @@ -1,2271 +0,0 @@ -//! Versioned semantic artifacts for executable knowledge. -//! -//! This is deliberately a *projection* of the existing syntax AST. It gives -//! every consumer one deterministic place to obtain identity, contracts, -//! effects, provenance and hashes without changing the classic runtime AST. - -use std::collections::{BTreeMap, BTreeSet}; -use std::fs; -use std::path::{Path, PathBuf}; - -use anyhow::{bail, Context, Result}; -use serde_json::{json, Value}; -use sha2::{Digest as _, Sha256}; - -use crate::ast::{Arg, CallExpr, Expr, Function, Module, Stmt}; -use crate::contract::Ty; -use crate::diagnostics::{Diagnostic, Severity, Span}; -use crate::project::ProjectRoot; - -use super::bind::{call_display, resolve_for_exec, DynamicReason, ExecTarget}; -use super::{CallableKind, ModuleId, ProjectIndex, SymbolDecl, SymbolId, SymbolKind}; - -pub const SCHEMA_VERSION: u32 = 1; - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ArtifactId(pub String); - -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Digest(pub String); - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum LockMode { - Off, - Check, - Strict, -} - -#[derive(Debug, Clone)] -pub struct CompileOptions { - pub project_root: PathBuf, - pub entry: Option, - pub lock_mode: LockMode, -} - -impl CompileOptions { - pub fn for_path(path: &Path) -> Result { - let project = if path.is_dir() { - ProjectRoot::new(path)? - } else { - ProjectRoot::discover(path)? - }; - Ok(Self { - project_root: project.path().to_path_buf(), - entry: path.is_file().then(|| path.to_path_buf()), - lock_mode: LockMode::Off, - }) - } -} - -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct EffectSet(BTreeSet); - -impl EffectSet { - pub fn pure() -> Self { - Self(BTreeSet::from(["pure".to_string()])) - } - - /// Effect is not yet known (dynamic target, missing metadata, or unresolved name). - /// Must never be treated as `pure` for policy checks (G06). - pub fn unknown() -> Self { - let mut set = Self::default(); - set.add("unknown"); - set - } - - pub fn add(&mut self, effect: impl Into) { - let effect = effect.into(); - if effect != "pure" { - self.0.remove("pure"); - } - self.0.insert(effect); - } - - pub fn extend(&mut self, other: &Self) { - for effect in &other.0 { - self.add(effect.clone()); - } - } - - pub fn is_pure(&self) -> bool { - self.0.len() == 1 && self.0.contains("pure") - } - - pub fn contains(&self, effect: &str) -> bool { - self.0.contains(effect) - } - - pub fn values(&self) -> Vec { - self.0.iter().cloned().collect() - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SourceLocation { - pub file: String, - pub line: u32, - pub end_line: u32, -} - -#[derive(Debug, Clone)] -pub struct CanonicalParam { - pub name: String, - pub ty: String, - pub required: bool, - pub default_digest: Option, - pub unit: Option, -} - -#[derive(Debug, Clone)] -pub struct CanonicalSignature { - pub receiver: String, - pub params: Vec, - pub returns: String, - pub effects: EffectSet, -} - -#[derive(Debug, Clone)] -pub struct ContractSet { - pub params: Vec, - pub returns: Option, - pub fields: Vec, -} - -#[derive(Debug, Clone)] -pub struct SourceRef { - pub uri: String, - pub locator: Option, - pub content_digest: Option, - pub relation: String, -} - -#[derive(Debug, Clone)] -pub struct VerificationRecord { - pub parse: String, - pub resolve: String, - pub contract: String, - pub execution: String, - pub tests: String, - pub evidence: String, - pub domain: String, - pub methods: Vec, -} - -#[derive(Debug, Clone)] -pub struct ArtifactHashes { - pub interface: Digest, - pub implementation: Digest, - pub evidence: Digest, - pub artifact: Digest, - /// Transitive dependency closure over call edges (G08). - pub closure: Digest, -} - -#[derive(Debug, Clone)] -pub struct SemanticArtifact { - pub artifact_id: ArtifactId, - pub symbol_id: Option, - pub display_name: String, - pub kind: String, - pub callable: Option, - pub source: SourceLocation, - pub signature: Option, - pub contract: ContractSet, - pub effects: EffectSet, - pub dependencies: Vec, - pub provenance: Vec, - pub applicability: String, - pub hashes: ArtifactHashes, - pub verification: VerificationRecord, - pub lifecycle: String, -} - -#[derive(Debug, Clone)] -pub struct KnowledgeRef { - pub id: String, - /// Stable public address of the marked step, absent for ambiguous labels. - pub anchor_id: Option, - /// Original Markdown target when this reference occurs in prose. - pub link_target: Option, - /// Resolved stable anchor target; never an executable call. - pub target_anchor: Option, - /// Reference to a theorem declaration, not a proof certificate. - pub target_claim: Option, - pub label: String, - pub context: String, - pub source: SourceLocation, - pub resolution: String, - pub target: Option, -} - -/// Stable identity and unproved declaration of a v2.8.0 function theorem. -#[derive(Debug, Clone)] -pub struct KnowledgeClaim { - pub anchor_id: String, - pub owner: SymbolId, - pub label: String, - pub conclusion: String, - pub premise: Option, - pub line: u32, - pub source: SourceLocation, -} - -/// Declared operation assumption, not an accepted proof or runtime binding. -#[derive(Debug, Clone)] -pub struct KnowledgeAssumption { - pub id: String, - pub owner: SymbolId, - pub operation: String, - pub premise: Option, - pub postcondition: String, - pub source: SourceLocation, -} - -#[derive(Debug, Clone)] -pub struct KnowledgeStep { - pub id: ArtifactId, - /// Stable public anchor; legacy #step-N is kept as an internal step identity. - pub anchor_id: Option, - /// Hash of the authored source line (or fallback label when line unavailable). - pub definition_digest: Digest, - pub reference: String, - pub kind: String, - pub calls: Vec, - pub effects: EffectSet, - pub source: SourceLocation, -} - -/// Fully static i64 call-site argument. Non-constant expressions are kept -/// as unresolved proof obligations rather than guessed values. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct StaticCallArg { - pub name: Option, - pub integer: Option, - pub expression_digest: Digest, - /// Only a direct identifier; arbitrary expressions do not become symbolic identities. - pub symbol: Option, -} - -fn checked_constant_int(expr: &Expr, depth: usize) -> Option { - if depth > 32 { return None; } - match expr { - Expr::Literal(crate::ast::Literal::Int(n)) => Some(*n), - Expr::Occluded { payload: Some(inner), .. } => - checked_constant_int(inner, depth+1), - Expr::Unary {op: crate::ast::UnaryOp::Neg, expr} => - checked_constant_int(expr,depth+1)?.checked_neg(), - Expr::Binary {op,left,right} => { - let a=checked_constant_int(left,depth+1)?; - let b=checked_constant_int(right,depth+1)?; - match op { - crate::ast::BinaryOp::Add=>a.checked_add(b), - crate::ast::BinaryOp::Sub=>a.checked_sub(b), - crate::ast::BinaryOp::Mul=>a.checked_mul(b), - // Division and its rounding/coercion are not yet proven - // equivalent to the Lean abstract numeric model. - _=>None - } - }, - _=>None - } -} - -fn static_call_args(call:&CallExpr)->Vec{ - // The exact same alias/modifier expansion used by runtime resolution - // must determine the proof's argument list. An invalid normalization - // must never yield a recoverable proof argument. - let Ok(normalized)=call.for_evaluation() else {return Vec::new()}; - normalized.args.iter().map(|a|{ - let (name,expr)=match a { - crate::ast::Arg::Positional(expr)=>(None,expr), - crate::ast::Arg::Named{name,value}=>(Some(name.clone()),value) - }; - StaticCallArg { - name, integer:checked_constant_int(expr,0), - expression_digest:digest(format!("{expr:?}")), - symbol:match expr {Expr::Var(v)=>Some(v.clone()),_=>None} - } - }).collect() -} - -/// Static call site bound to a SymbolId (G02). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BoundCall { - /// Exact owning function symbol at the AST callsite. - pub caller: SymbolId, - pub target: SymbolId, - pub call_site: String, - pub source: SourceLocation, - /// Exact, ordered actual arguments with conservative closed-int decoding. - pub args: Vec, - /// Guard predicates are source-derived and never independently trusted. - pub path_guards: Vec, - /// Loop, unknown guard, etc: no modular proof may pass this callsite. - pub control_blocker: Option, - pub required_effects: EffectSet, -} - -/// Call site that must not pretend to be statically bound (G02). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DynamicCall { - pub reason: String, - pub call_site: String, - pub source: SourceLocation, -} - -#[derive(Debug, Clone)] -pub struct SemanticProject { - pub schema_version: u32, - pub project_id: String, - pub root: PathBuf, - pub artifacts: Vec, - pub refs: Vec, - pub steps: Vec, - pub claims: Vec, - pub assumptions: Vec, - pub bound_calls: Vec, - pub dynamic_calls: Vec, -} - -#[derive(Debug, Clone)] -pub struct Compilation { - pub index: ProjectIndex, - pub semantics: SemanticProject, - pub diagnostics: Vec, -} - -/// Compile every project source once into stable semantic facts. This is -/// side-effect free: it never loads plugins, evaluates expressions or fetches -/// sources. -pub fn compile_project(options: &CompileOptions) -> Result { - let root = ProjectRoot::new(&options.project_root)?; - compile_index(ProjectIndex::build(root)?) -} - -/// Compile `entry` and the modules it imports. Sibling files in the directory are not included. -pub fn compile_file_closure(entry: &Path) -> Result { - let files = import_closure(entry)?; - let ancestor = common_ancestor(&files)?; - let root = ProjectRoot::new(&ancestor)?; - compile_index(ProjectIndex::from_files(root, files)?) -} - -fn compile_index(index: ProjectIndex) -> Result { - let root = index.root().clone(); - // Reuse parsed modules from ProjectIndex — same input snapshot, no second parse (M-R5b). - let mut files = BTreeMap::new(); - let mut diagnostics = Vec::new(); - for (module_id, parsed) in index.parsed_modules() { - files.insert( - module_id.clone(), - ( - parsed.path.clone(), - parsed.text.clone(), - parsed.module.clone(), - ), - ); - } - // Wire import_modules from already-parsed project files so BoundCall path - // resolve shares `resolve_for_exec` (no plugin load / no re-parse). - attach_project_imports(&mut files); - - let project_id = index.project_id().to_string(); - let mut artifacts = Vec::new(); - let mut refs = Vec::new(); - let mut steps = Vec::new(); - let mut claims = Vec::new(); - let mut assumptions = Vec::new(); - let mut bound_calls = Vec::new(); - let mut dynamic_calls = Vec::new(); - let mut local_by_name: BTreeMap<(ModuleId, String), SymbolId> = BTreeMap::new(); - for symbol in index.symbols() { - local_by_name.insert((symbol.module.clone(), symbol.name.clone()), symbol.id.clone()); - } - - for (module_id, (path, text, module)) in &files { - artifacts.push(module_artifact(&index, module_id, path, text)); - let mut by_path = BTreeMap::new(); - collect_functions(&module.functions, &mut Vec::new(), &mut by_path); - let narrative_links = crate::parse::scan_narrative_links(text); - let module_prov = super::provenance::parse_module_provenance(text); - let module_symbols = index.symbols_in_module(module_id); - for symbol in index.symbols_in_module(module_id) { - let function = by_path.get(&symbol.declaration_path).expect("symbol collected from module"); - let mut claim_counts=BTreeMap::new(); - for claim in &function.claims { - *claim_counts.entry(claim.id.as_str()).or_insert(0usize)+=1; - } - for claim in &function.claims { - if claim_counts.get(claim.id.as_str())!=Some(&1) { - diagnostics.push(Diagnostic::new(Some(path.as_path()), - Span::new(claim.line,1), - format!("ambiguous theorem declaration: {}",claim.id)) - .with_code("knowledge.claim_duplicate") - .with_severity(Severity::Warning)); - continue; - } - claims.push(KnowledgeClaim { - anchor_id: format!("{}#claim-{}",symbol.id.as_str(), - digest(claim.id.as_bytes()).0.trim_start_matches("sha256:")), - owner:symbol.id.clone(), - label:claim.id.clone(), - conclusion:claim.conclusion.clone(), - premise:claim.premise.clone(), - line:claim.line, - source:source_location(index.root().path(),path,claim.line,claim.line), - }); - } - let mut assumption_counts=BTreeMap::new(); - for assumption in &function.assumptions { - *assumption_counts.entry(assumption.op.as_str()).or_insert(0usize)+=1; - } - for assumption in &function.assumptions { - if assumption_counts.get(assumption.op.as_str())!=Some(&1) { - diagnostics.push(Diagnostic::new(Some(path.as_path()), - Span::new(assumption.line,1), - format!("ambiguous assumption operation: {}",assumption.op)) - .with_code("proof.assumption_duplicate") - .with_severity(Severity::Warning)); - continue; - } - assumptions.push(KnowledgeAssumption{ - id:format!("{}#assumption-{}",symbol.id.as_str(), - digest(assumption.op.as_bytes()).0.trim_start_matches("sha256:")), - owner:symbol.id.clone(), - operation:assumption.op.clone(), - premise:assumption.premise.clone(), - postcondition:assumption.postcondition.clone(), - source:source_location(index.root().path(),path,assumption.line,assumption.line) - }); - } - let owned_links: Vec<_> = narrative_links - .iter() - .filter(|link| enclosing_symbol(&module_symbols, link.line).is_some_and(|s| s.id == symbol.id)) - .cloned() - .collect(); - let (artifact, mut artifact_refs, mut artifact_steps, mut bounds, mut dynamics, prov_diags) = - artifact_for_function( - &index, - module_id, - module, - path, - function, - symbol, - text, - &local_by_name, - &owned_links, - &module_prov, - ); - for diag in prov_diags { - diagnostics.push( - Diagnostic::new(Some(path), Span::new(1, 1), diag.message()) - .with_code(diag.code()) - .with_severity(Severity::Warning), - ); - } - refs.append(&mut artifact_refs); - steps.append(&mut artifact_steps); - bound_calls.append(&mut bounds); - dynamic_calls.append(&mut dynamics); - artifacts.push(artifact); - } - } - close_effect_dependencies(&mut artifacts); - resolve_anchor_references(&mut refs, &claims); - for reference in refs.iter().filter(|r| - r.resolution=="unresolved_anchor" || r.resolution=="ambiguous_anchor") { - let source_path=root.path().join(&reference.source.file); - diagnostics.push(Diagnostic::new( - Some(source_path.as_path()), - Span::new(reference.source.line, 1), - format!("knowledge target cannot be uniquely resolved: {}", - reference.link_target.as_deref().unwrap_or(""))) - .with_code(if reference.resolution=="ambiguous_anchor" { - "knowledge.anchor_ambiguous" - } else {"knowledge.anchor_unresolved"}) - .with_severity(Severity::Warning)); - } - let resolved_effects: BTreeMap<_,_> = artifacts.iter() - .map(|artifact|(artifact.artifact_id.clone(),artifact.effects.clone())).collect(); - for bound in &mut bound_calls { - if let Some(effects) = resolved_effects.get(&ArtifactId(bound.target.as_str().into())) { - bound.required_effects = effects.clone(); - } - } - let mut callsite_effects: BTreeMap<(String,u32),EffectSet> = BTreeMap::new(); - for bound in &bound_calls { - callsite_effects.entry((bound.source.file.clone(),bound.source.line)) - .or_default().extend(&bound.required_effects); - } - for step in &mut steps { - if let Some(effects) = callsite_effects.get(&(step.source.file.clone(),step.source.line)) { - step.effects.extend(effects); - } - if step.effects.0.is_empty() { step.effects = EffectSet::pure(); } - } - close_closure_digests(&mut artifacts); - artifacts.sort_by(|a, b| a.artifact_id.0.cmp(&b.artifact_id.0)); - refs.sort_by(|a, b| a.id.cmp(&b.id)); - steps.sort_by(|a, b| a.id.0.cmp(&b.id.0)); - claims.sort_by(|a,b| a.anchor_id.cmp(&b.anchor_id)); - assumptions.sort_by(|a,b|a.id.cmp(&b.id)); - bound_calls.sort_by(|a, b| { - a.source - .file - .cmp(&b.source.file) - .then(a.source.line.cmp(&b.source.line)) - .then(a.call_site.cmp(&b.call_site)) - }); - dynamic_calls.sort_by(|a, b| { - a.source - .file - .cmp(&b.source.file) - .then(a.source.line.cmp(&b.source.line)) - .then(a.call_site.cmp(&b.call_site)) - }); - Ok(Compilation { - index, - semantics: SemanticProject { - schema_version: SCHEMA_VERSION, - project_id, - root: root.path().to_path_buf(), - artifacts, - refs, - steps, - claims, - assumptions, - bound_calls, - dynamic_calls, - }, - diagnostics, - }) -} - -fn import_closure(entry: &Path) -> Result> { - let mut out = Vec::new(); - let mut seen = std::collections::HashSet::new(); - fn walk(path: &Path, out: &mut Vec, seen: &mut std::collections::HashSet) -> Result<()> { - if !path.is_file() { - return Ok(()); - } - let canon = path.canonicalize().with_context(|| format!("resolve {}", path.display()))?; - if !seen.insert(canon.clone()) { - return Ok(()); - } - out.push(canon.clone()); - let source = fs::read_to_string(&canon).with_context(|| format!("read {}", canon.display()))?; - let module = crate::load::parse_source_auto(&source) - .with_context(|| format!("parse {}", canon.display()))?; - let base = canon.parent().unwrap_or_else(|| Path::new(".")); - for imp in &module.imports { - let dep = crate::load::resolve_import(base, &imp.path) - .with_context(|| format!("import `{}` from {}", imp.path, canon.display()))?; - walk(&dep, out, seen)?; - } - Ok(()) - } - if !entry.is_file() { - bail!("call target {} is not a file", entry.display()); - } - walk(entry, &mut out, &mut seen)?; - out.sort(); - Ok(out) -} - -fn common_ancestor(files: &[PathBuf]) -> Result { - let Some(first) = files.first() else { - bail!("call target has no source files"); - }; - let mut ancestor = first - .parent() - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| PathBuf::from(".")); - for file in files.iter().skip(1) { - while !file.starts_with(&ancestor) { - ancestor = ancestor - .parent() - .map(|p| p.to_path_buf()) - .ok_or_else(|| anyhow::anyhow!("source files have no common directory"))?; - } - } - Ok(ancestor) -} - -fn module_artifact(index: &ProjectIndex, module: &ModuleId, path: &Path, text: &str) -> SemanticArtifact { - let implementation = digest(normalize_source(text)); - let interface = digest(module.as_str()); - let evidence = digest(""); - let artifact_id = ArtifactId(format!("mq://{}/{}/module", percent(index.project_id()), percent(module.as_str()))); - semantic_artifact( - artifact_id, - None, - module.as_str().to_string(), - "module".to_string(), - None, - source_location(index.root().path(), path, 1, text.lines().count() as u32), - None, - ContractSet { params: vec![], returns: None, fields: vec![] }, - EffectSet::pure(), - vec![], - vec![SourceRef { uri: rel_uri(index.root().path(), path), locator: None, content_digest: Some(implementation.clone()), relation: "defines".into() }], - "project-local module".into(), - interface, - implementation, - evidence, - ) -} - -fn path_key(path: &Path) -> PathBuf { - path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) -} - -/// Clone imported modules already present in `files` into each Module's -/// `import_modules` map (G02 BoundCall for explicit import paths). -fn attach_project_imports(files: &mut BTreeMap) { - let by_path: BTreeMap = files - .values() - .map(|(path, _, module)| (path_key(path), module.clone())) - .collect(); - for (path, _, module) in files.values_mut() { - let base = path - .parent() - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| path.to_path_buf()); - let mut import_modules = std::collections::HashMap::new(); - for imp in &module.imports { - let Ok(resolved) = crate::load::resolve_import(&base, &imp.path) else { - continue; - }; - let key = path_key(&resolved); - if let Some(dep) = by_path.get(&key) { - import_modules.insert(imp.bind.clone(), dep.clone()); - } else if let Ok(dep) = crate::load::load_module(&resolved) { - // External standard libraries are outside a project-only index, - // but their resolved bodies still determine effects. - import_modules.insert(imp.bind.clone(), dep); - } - } - module.import_modules = import_modules; - } -} - -fn enclosing_symbol<'a>(symbols: &[&'a SymbolDecl], line: u32) -> Option<&'a SymbolDecl> { - symbols - .iter() - .copied() - .filter(|s| s.line <= line) - .max_by_key(|s| s.line) -} - -fn resolve_narrative_target( - index: &ProjectIndex, - module_id: &ModuleId, - local_by_name: &BTreeMap<(ModuleId, String), SymbolId>, - target: &str, -) -> Option { - let t = target.trim().trim_start_matches('#'); - if t.is_empty() { - return None; - } - if let Some(id) = local_by_name.get(&(module_id.clone(), t.to_string())) { - return Some(id.clone()); - } - // Path-like `bind.member` via display name suffix match within project. - index.symbols().iter().find_map(|s| { - if s.declaration_path.join(".") == t || s.name == t { - Some(s.id.clone()) - } else { - None - } - }) -} - -/// The label is a human-facing name, not an execution permission. -fn normalize_anchor_label(label: &str) -> String { - label.split_whitespace().collect::>().join(" ") -} - -fn public_anchor(owner: &SymbolId, label: &str, counts: &BTreeMap) -> Option { - let normalized = normalize_anchor_label(label); - if normalized.is_empty() || counts.get(&normalized) != Some(&1) { - return None; - } - // Full SHA-256 avoids truncation collisions; unrelated step insertions - // do not change the address, while changing the label intentionally does. - Some(format!("{}#anchor-{}", owner.as_str(), digest(normalized.as_bytes()).0.trim_start_matches("sha256:"))) -} - -fn anchor_definition_digest(source: &str, line: u32, label: &str, kind: &str) -> Digest { - let body = if line > 0 { source.lines().nth(line as usize - 1) } else { None }; - digest(format!("{kind}\0{label}\0{}", body.unwrap_or(""))) -} - -/// Explicit knowledge references are inert: resolving a link never invokes a -/// function. Short #@label binds ONLY inside the current function. Full -/// mq://...#anchor- targets support cross-module references. -fn resolve_anchor_references(refs: &mut [KnowledgeRef], claims: &[KnowledgeClaim]) { - let declared: BTreeSet = refs.iter() - .filter_map(|r| r.anchor_id.clone()).collect(); - let theorem_ids: BTreeSet = claims.iter().map(|c|c.anchor_id.clone()).collect(); - for reference in refs { - let Some(raw) = reference.link_target.as_deref() else {continue}; - let sought = if let Some(label) = raw.trim().strip_prefix("#@") { - let Some(owner) = reference.id.split("#ref-").next() else {continue}; - if label.is_empty() {continue} - Some((format!("{}#anchor-{}", owner, - digest(normalize_anchor_label(label).as_bytes()).0.trim_start_matches("sha256:")), - format!("{}#claim-{}", owner, - digest(label.as_bytes()).0.trim_start_matches("sha256:")))) - } else if raw.starts_with("mq://") - && (raw.contains("#anchor-") || raw.contains("#claim-")) { - Some((raw.trim().to_string(), raw.trim().to_string())) - } else { None }; - if let Some((anchor, claim)) = sought { - let step_match=declared.contains(&anchor); - let theorem_match=theorem_ids.contains(&claim); - match (step_match,theorem_match) { - (true,false)=>{ - reference.target_anchor=Some(anchor); - reference.resolution="anchor".into(); - } - (false,true)=>{ - reference.target_claim=Some(claim); - reference.resolution="claim".into(); - } - (true,true)=>reference.resolution="ambiguous_anchor".into(), - _=>reference.resolution="unresolved_anchor".into() - } - reference.target=None; - } - } -} - -#[derive(Clone,Default)] -struct CallsiteControl { - guards: Vec, - blocker: Option, -} - -/// Only side-effect-free boolean and integer-comparison guards are projected. -/// Unknown guards and any loops remain explicit unresolved obligations. -fn guard_text(expr:&Expr)->Option{ - match expr { - Expr::Var(v)=>Some(v.clone()), - Expr::Literal(crate::ast::Literal::Int(n))=>Some(n.to_string()), - Expr::Literal(crate::ast::Literal::Bool(v))=>Some( - if *v {"真"}else{"假"}.into()), - Expr::Occluded {payload:Some(e),..}=>guard_text(e), - Expr::Unary {op:crate::ast::UnaryOp::Not,expr}=> - Some(format!("非 ({})",guard_text(expr)?)), - Expr::Unary {op:crate::ast::UnaryOp::Neg,expr}=> - Some(format!("-({})",guard_text(expr)?)), - Expr::Binary {op,left,right}=>{ - let symbol=match op { - crate::ast::BinaryOp::Eq=>"=", - crate::ast::BinaryOp::Ne=>"≠", - crate::ast::BinaryOp::Lt=>"<", - crate::ast::BinaryOp::Le=>"≤", - crate::ast::BinaryOp::Gt=>">", - crate::ast::BinaryOp::Ge=>"≥", - crate::ast::BinaryOp::And=>"且", - crate::ast::BinaryOp::Or=>"或", - // Preserve source arithmetic in *guard obligations* only. - // This does not certify i64 overflow or dynamic Number - // behavior; the symbolic Lean Int backend checks linearity. - crate::ast::BinaryOp::Add=>"+", - crate::ast::BinaryOp::Sub=>"-", - crate::ast::BinaryOp::Mul=>"*", - _=>return None - }; - Some(format!("({} {} {})", - guard_text(left)?,symbol,guard_text(right)?)) - }, - _=>None - } -} -fn callsite_control(fun:&Function)->BTreeMap{ - fn walk(items:&[Stmt],conditions:&[String],block:Option, - output:&mut BTreeMap){ - for stmt in items{ - match stmt { - Stmt::Branch{arms,span}=>{ - // Calls within branch test expressions require separate - // evaluation-order reasoning and must not borrow arm facts. - output.entry(span.line).or_insert_with(||CallsiteControl{ - guards:conditions.to_vec(), - blocker:Some("call_in_condition_not_modeled".into()) - }); - let mut negated=Vec::new(); - let mut prior_unknown_condition=false; - for arm in arms{ - let mut path=conditions.to_vec(); - path.extend(negated.iter().cloned()); - // A previous unmodelled if/elif test also controls the - // reachability of all later arms, including else. - let mut arm_block=if prior_unknown_condition { - Some("prior_non_pure_branch_guard".into()) - } else {block.clone()}; - if let Some(cond)=&arm.condition{ - match guard_text(cond){ - Some(guard)=>{ - path.push(guard.clone()); - negated.push(format!("非 ({guard})")); - }, - None=>{ - arm_block=Some("non_pure_branch_guard".into()); - prior_unknown_condition=true; - } - } - } - walk(&arm.body,&path,arm_block,output); - } - }, - Stmt::While{body,span,..}|Stmt::ForEach{body,span,..}=>{ - output.insert(span.line,CallsiteControl{ - guards:conditions.to_vec(), - blocker:Some("loop_or_iterator_requires_invariant".into()) - }); - walk(body,conditions, - Some("loop_or_iterator_requires_invariant".into()),output); - }, - _=>{ - let line=crate::ast::stmt_line(stmt); - output.insert(line,CallsiteControl{ - guards:conditions.to_vec(),blocker:block.clone() - }); - } - } - } - } - let mut found=BTreeMap::new(); - walk(&fun.body,&[],None,&mut found); - found -} - -fn artifact_for_function( - index: &ProjectIndex, - module_id: &ModuleId, - ast_module: &Module, - path: &Path, - function: &Function, - symbol: &SymbolDecl, - source_text: &str, - local_by_name: &BTreeMap<(ModuleId, String), SymbolId>, - narrative_links: &[crate::parse::NarrativeLink], - module_prov: &super::provenance::ModuleProvenance, -) -> ( - SemanticArtifact, - Vec, - Vec, - Vec, - Vec, - Vec, -) { - let calls = collect_call_sites(function); - let controls=callsite_control(function); - let mut effects = direct_effects(index, ast_module, function, &calls); - let mut dependencies = Vec::new(); - let mut bound_calls = Vec::new(); - let mut dynamic_calls = Vec::new(); - for (_, call, line) in &calls { - let source = source_location(index.root().path(), path, *line, *line); - match classify_call(index, module_id, ast_module, function, call, local_by_name) { - CallClass::Bound { target, effects: call_effects } => { - dependencies.push(ArtifactId(target.as_str().to_string())); - bound_calls.push(BoundCall { - caller:symbol.id.clone(), - target, - call_site: call_display(call), - source, - args:static_call_args(call), - path_guards:controls.get(line).map(|c|c.guards.clone()).unwrap_or_default(), - control_blocker:controls.get(line).and_then(|c|c.blocker.clone()), - required_effects: call_effects, - }); - } - CallClass::Dynamic { reason } => { - dynamic_calls.push(DynamicCall { - reason: reason.as_str().into(), - call_site: call_display(call), - source, - }); - } - CallClass::Other => {} - } - } - let named = collect_named_steps(function); - // Only a unique author-visible label in this function receives a public - // address. Duplicate names are deliberately not resolved by source order. - let mut label_counts = BTreeMap::new(); - for site in &named { - *label_counts.entry(normalize_anchor_label(&site.label)).or_insert(0usize) += 1; - } - let mut refs = Vec::new(); - let mut steps = Vec::new(); - let mut step_n = 0u32; - for named in named.iter() { - step_n += 1; - let target = named.call.as_ref().and_then(|call| { - match classify_call(index, module_id, ast_module, function, call, local_by_name) { - CallClass::Bound { target, .. } => Some(target), - _ => None, - } - }); - let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n); - let anchor = public_anchor(&symbol.id, &named.label, &label_counts); - let definition_digest = anchor_definition_digest(source_text, named.line, &named.label, &named.kind); - refs.push(KnowledgeRef { - anchor_id: anchor.clone(), - link_target: None, - target_anchor: None, - target_claim: None, - id: ref_id.clone(), - label: named.label.clone(), - context: named.context.clone(), - source: source_location(index.root().path(), path, named.line, named.line), - resolution: target - .as_ref() - .map(|_| "symbol".to_string()) - .unwrap_or_else(|| named.resolution.clone()), - target: target.clone(), - }); - let mut step_effects = EffectSet::default(); - for (_, call, line) in &calls { - if *line == named.line { step_effects.extend(&effects_for_call(ast_module,function,call,Some(index))); } - } - steps.push(KnowledgeStep { - id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)), - anchor_id: anchor, - definition_digest, - reference: ref_id, - kind: named.kind.clone(), - calls: target.into_iter().collect(), - effects: step_effects, - source: source_location(index.root().path(), path, named.line, named.line), - }); - } - // G03 NarrativeRef: comment-line []() — never BoundCall, never effects. - for link in narrative_links { - step_n += 1; - let target = match link.kind { - crate::parse::NarrativeLinkKind::Narrate => { - resolve_narrative_target(index, module_id, local_by_name, &link.target) - } - crate::parse::NarrativeLinkKind::Navigation => None, - }; - let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n); - // A narrative link is a reference, not a definition. It never creates - // a public executable anchor of its own. - refs.push(KnowledgeRef { - anchor_id: None, - link_target: Some(link.target.clone()), - target_anchor: None, - target_claim: None, - id: ref_id.clone(), - label: link.label.clone(), - context: "narrative".into(), - source: source_location(index.root().path(), path, link.line, link.line), - resolution: match link.kind { - crate::parse::NarrativeLinkKind::Navigation => "navigation".into(), - crate::parse::NarrativeLinkKind::Narrate if target.is_some() => "symbol".into(), - crate::parse::NarrativeLinkKind::Narrate => "unresolved".into(), - }, - target: target.clone(), - }); - steps.push(KnowledgeStep { - id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)), - anchor_id: None, - definition_digest: anchor_definition_digest(source_text, link.line, &link.label, link.kind.as_str()), - reference: ref_id, - kind: link.kind.as_str().into(), - calls: target.into_iter().collect(), - effects: EffectSet::pure(), - source: source_location(index.root().path(), path, link.line, link.line), - }); - } - if effects.0.is_empty() { - effects = EffectSet::pure(); - } - let (signature, contract) = signature(function, symbol.callable, &effects); - let interface = digest(signature_json(signature.as_ref())); - let implementation = digest(format!("{:?}", function.body)); - let mut provenance = vec![SourceRef { - uri: rel_uri(index.root().path(), path), - locator: Some(format!("L{}", function.span.line)), - content_digest: Some(implementation.clone()), - relation: "defines".into(), - }]; - let fn_sources = super::provenance::sources_for_function(module_prov, &function.name); - let mut fn_prov = module_prov.clone(); - fn_prov.sources = fn_sources; - let resolved = super::provenance::resolve_provenance_sources(path, &fn_prov, &fn_prov.sources); - provenance.extend(resolved.refs.clone()); - // M02: evidence digest includes contract + canonical provenance (URI/locator/content/applicability). - let evidence = digest(format!( - "{}|{}", - contract_summary(&contract), - resolved.evidence_record - )); - let kind = match symbol.kind { - SymbolKind::Type => "type", - SymbolKind::Function => "function", - }.to_string(); - let mut artifact = semantic_artifact( - ArtifactId(symbol.id.as_str().to_string()), - Some(symbol.id.clone()), - symbol.declaration_path.join("."), - kind, - symbol.callable.map(|kind| kind.as_str().to_string()), - source_location(index.root().path(), path, function.span.line, function.span.line), - signature, - contract, - effects, - dependencies, - provenance, - resolved.applicability, - interface, - implementation, - evidence, - ); - artifact.verification.evidence = resolved.evidence_status; - ( - artifact, - refs, - steps, - bound_calls, - dynamic_calls, - resolved.diagnostics, - ) -} - -enum CallClass { - Bound { - target: SymbolId, - effects: EffectSet, - }, - Dynamic { - reason: DynamicReason, - }, - Other, -} - -fn declaration_path_of(module: &Module, target: &Function) -> Option> { - fn walk(funs: &[Function], target: &Function, prefix: &mut Vec) -> Option> { - for fun in funs { - prefix.push(fun.name.clone()); - if std::ptr::eq(fun, target) { - return Some(prefix.clone()); - } - if let Some(found) = walk(&fun.children, target, prefix) { - return Some(found); - } - prefix.pop(); - } - None - } - walk(&module.functions, target, &mut Vec::new()) -} - -fn symbol_for_path( - index: &ProjectIndex, - module_id: &ModuleId, - decl_path: &[String], -) -> Option { - index - .symbols() - .iter() - .find(|s| &s.module == module_id && s.declaration_path == decl_path) - .map(|s| s.id.clone()) -} - -fn classify_call( - index: &ProjectIndex, - module_id: &ModuleId, - ast_module: &Module, - current: &Function, - call: &CallExpr, - _local_by_name: &BTreeMap<(ModuleId, String), SymbolId>, -) -> CallClass { - match resolve_for_exec(ast_module, current, call) { - ExecTarget::Local(fun) => { - let Some(decl) = declaration_path_of(ast_module, fun) else { - return CallClass::Other; - }; - let Some(target) = symbol_for_path(index, module_id, &decl) else { - return CallClass::Other; - }; - CallClass::Bound { - target, - effects: EffectSet::default(), - } - } - ExecTarget::Import { bind, lib, fun, path } => { - let Some(imp) = ast_module.imports.iter().find(|i| i.bind == bind) else { - return CallClass::Other; - }; - let base = index - .modules() - .get(module_id) - .and_then(|p| p.parent().map(|d| d.to_path_buf())) - .unwrap_or_else(|| index.root().path().to_path_buf()); - let Ok(imported_path) = crate::load::resolve_import(&base, &imp.path) else { - return CallClass::Other; - }; - let imported_path = imported_path - .canonicalize() - .unwrap_or(imported_path); - let Some((imported_id, _)) = index.modules().iter().find(|(_, p)| { - p.canonicalize().unwrap_or_else(|_| (*p).clone()) == imported_path - }) else { - return CallClass::Other; - }; - // Resolve the *declaration* path in the imported module, not - // the syntactic call path: `rates.lookup()` may refer to a - // nested `# rates / ## lookup` function. Losing the parent - // would silently break transitive proof invalidation. - let decl = if let Some(d) = declaration_path_of(lib, fun) { - d - } else if path.len() >= 2 { - path[1..].to_vec() - } else { - return CallClass::Other; - }; - let Some(target) = symbol_for_path(index, imported_id, &decl) else { - return CallClass::Other; - }; - CallClass::Bound { - target, - effects: EffectSet::default(), - } - } - ExecTarget::Builtin(_) | ExecTarget::Host(_) => CallClass::Other, - ExecTarget::Dynamic { reason, .. } => CallClass::Dynamic { reason }, - ExecTarget::Unresolved { .. } => CallClass::Other, - } -} - -#[allow(clippy::too_many_arguments)] -fn semantic_artifact( - artifact_id: ArtifactId, symbol_id: Option, display_name: String, kind: String, - callable: Option, source: SourceLocation, signature: Option, - contract: ContractSet, effects: EffectSet, mut dependencies: Vec, - provenance: Vec, applicability: String, interface: Digest, implementation: Digest, - evidence: Digest, -) -> SemanticArtifact { - dependencies.sort_by(|a, b| a.0.cmp(&b.0)); - dependencies.dedup(); - let artifact = digest(format!("{}:{}:{}", interface.0, implementation.0, evidence.0)); - // Placeholder; replaced by `close_closure_digests` after the full graph exists. - let closure = artifact.clone(); - SemanticArtifact { - artifact_id, symbol_id, display_name, kind, callable, source, signature, contract, - effects, dependencies, provenance, applicability, hashes: ArtifactHashes { - interface, implementation, evidence, artifact, closure, - }, - verification: VerificationRecord { - parse: "passed".into(), resolve: "passed".into(), contract: "unchecked".into(), - execution: "not_run".into(), tests: "unknown".into(), evidence: "unverified".into(), - domain: "unreviewed".into(), methods: vec!["static_project_compile".into()], - }, - lifecycle: "draft".into(), - } -} - -fn signature(function: &Function, callable: Option, effects: &EffectSet) -> (Option, ContractSet) { - if function.is_object() { - let fields = function.contract.as_ref().map(|c| c.fields.iter().map(|f| format!("{}:{}", f.name, ty_name(&f.ty))).collect()).unwrap_or_default(); - return (None, ContractSet { params: vec![], returns: None, fields }); - } - let contract = function.contract.as_ref(); - let params = function.params.iter().map(|param| { - let cp = contract.and_then(|c| c.params.iter().find(|item| item.name == param.name)); - CanonicalParam { - name: param.name.clone(), ty: cp.map(|p| ty_name(&p.ty)).unwrap_or_else(|| "any".into()), - required: param.default.is_none(), default_digest: param.default.as_ref().map(|value| digest(format!("{:?}", value))), unit: None, - } - }).collect::>(); - let set = ContractSet { - params: contract.map(|c| c.params.iter().map(|p| format!("{}:{}", p.name, ty_name(&p.ty))).collect()).unwrap_or_default(), - returns: contract.and_then(|c| c.returns.as_ref().map(|r| ty_name(&r.ty))), - fields: contract.map(|c| c.fields.iter().map(|f| format!("{}:{}", f.name, ty_name(&f.ty))).collect()).unwrap_or_default(), - }; - let receiver = match callable { - Some(CallableKind::InstanceMethod) => "instance", - Some(CallableKind::AssociatedFunction) => "none", - _ => "none", - }.to_string(); - (Some(CanonicalSignature { - receiver, params, returns: set.returns.clone().unwrap_or_else(|| "any".into()), effects: effects.clone(), - }), set) -} - -fn ty_name(ty: &Ty) -> String { ty.name() } - -fn collect_functions<'a>(functions: &'a [Function], path: &mut Vec, out: &mut BTreeMap, &'a Function>) { - for function in functions { - path.push(function.name.clone()); - out.insert(path.clone(), function); - collect_functions(&function.children, path, out); - path.pop(); - } -} - -fn collect_call_sites(function: &Function) -> Vec<(usize, CallExpr, u32)> { - let mut calls = Vec::new(); - fn expr(value: &Expr, line: u32, calls: &mut Vec<(usize, CallExpr, u32)>) { - match value { - Expr::Call(call) => { - calls.push((calls.len(), call.clone(), line)); - for arg in &call.args { match arg { Arg::Positional(value) | Arg::Named { value, .. } => expr(value, line, calls) } } - } - Expr::Unary { expr: value, .. } => expr(value, line, calls), - Expr::Binary { left, right, .. } => { expr(left, line, calls); expr(right, line, calls); } - Expr::List(items) => for item in items { expr(item, line, calls); }, - Expr::Map(items) => for (_, item) in items { expr(item, line, calls); }, - Expr::Index { base, .. } => expr(base, line, calls), - Expr::Occluded { payload: Some(payload), .. } => expr(payload, line, calls), - _ => {} - } - } - fn statements(items: &[Stmt], calls: &mut Vec<(usize, CallExpr, u32)>) { - for item in items { - match item { - Stmt::Call { call, span } => { calls.push((calls.len(), call.clone(), span.line)); for arg in &call.args { match arg { Arg::Positional(value) | Arg::Named { value, .. } => expr(value, span.line, calls) } } } - Stmt::Assign { value, span, .. } | Stmt::Return { value, span } | Stmt::Expr { value, span } => expr(value, span.line, calls), - Stmt::Branch { arms, .. } => for arm in arms { if let Some(condition) = &arm.condition { expr(condition, 0, calls) }; statements(&arm.body, calls); }, - Stmt::While { condition, body, .. } => { expr(condition, 0, calls); statements(body, calls); } - Stmt::ForEach { body, .. } => statements(body, calls), - } - } - } - // Omitted arguments execute these expressions before the body. Leaving - // them out lets the pure-call policy miss both direct and transitive effects. - for param in &function.params { - if let Some(default) = ¶m.default { expr(default, function.span.line, &mut calls); } - } - statements(&function.body, &mut calls); - calls -} - -/// One author-visible knowledge step extracted from occlusion / labeled loop / call stmt. -struct NamedStepSite { - label: String, - kind: String, - context: String, - resolution: String, - line: u32, - call: Option, -} - -fn is_observe_call(call: &CallExpr) -> bool { - matches!(call.callee.as_str(), "access" | "取" | "取值" | "at" | "get") - && call.path.is_none() - && call.receiver.is_none() -} - -fn classify_payload_kind(payload: &Expr) -> (&'static str, Option) { - match payload { - Expr::Call(call) if is_observe_call(call) => ("observe", Some(call.clone())), - Expr::Call(call) => ("call", Some(call.clone())), - Expr::Index { .. } => ("observe", None), - Expr::Binary { .. } | Expr::Unary { .. } => ("derive", None), - Expr::Literal(_) | Expr::Var(_) => ("derive", None), - // Nested occlusion is its own step; outer stays a wrapper derive. - Expr::Occluded { .. } => ("derive", None), - _ => ("derive", None), - } -} - -fn collect_named_steps(function: &Function) -> Vec { - let mut out = Vec::new(); - fn push_occluded(label: &str, payload: Option<&Expr>, line: u32, out: &mut Vec) { - let label = label.trim(); - if label.is_empty() { - return; - } - let (kind, call) = match payload { - Some(p) => classify_payload_kind(p), - None => ("derive", None), - }; - out.push(NamedStepSite { - label: label.to_string(), - kind: kind.into(), - context: "executable".into(), - resolution: if call.is_some() { - "external_or_dynamic".into() - } else { - "payload".into() - }, - line, - call, - }); - if let Some(p) = payload { - walk_expr_for_nested(p, line, out); - } - } - fn walk_expr_for_nested(value: &Expr, line: u32, out: &mut Vec) { - match value { - Expr::Occluded { label, payload } => { - // Nested occlusions are separate steps; outer already recorded. - push_occluded(label, payload.as_deref(), line, out); - } - Expr::Call(call) => { - for arg in &call.args { - match arg { - Arg::Positional(value) | Arg::Named { value, .. } => { - walk_expr_for_nested(value, line, out) - } - } - } - } - Expr::Unary { expr: value, .. } => walk_expr_for_nested(value, line, out), - Expr::Binary { left, right, .. } => { - walk_expr_for_nested(left, line, out); - walk_expr_for_nested(right, line, out); - } - Expr::List(items) => { - for item in items { - walk_expr_for_nested(item, line, out); - } - } - Expr::Map(items) => { - for (_, item) in items { - walk_expr_for_nested(item, line, out); - } - } - Expr::Index { base, .. } => walk_expr_for_nested(base, line, out), - _ => {} - } - } - fn walk_expr_top(value: &Expr, line: u32, out: &mut Vec) { - match value { - Expr::Occluded { label, payload } => { - push_occluded(label, payload.as_deref(), line, out); - } - other => walk_expr_for_nested(other, line, out), - } - } - fn statements(items: &[Stmt], out: &mut Vec) { - for item in items { - match item { - Stmt::Call { call, span } => { - out.push(NamedStepSite { - label: call_name(call), - kind: if is_observe_call(call) { - "observe".into() - } else { - "call".into() - }, - context: "executable".into(), - resolution: "external_or_dynamic".into(), - line: span.line, - call: Some(call.clone()), - }); - for arg in &call.args { - match arg { - Arg::Positional(value) | Arg::Named { value, .. } => { - walk_expr_top(value, span.line, out) - } - } - } - } - Stmt::Assign { value, span, .. } - | Stmt::Return { value, span } - | Stmt::Expr { value, span } => walk_expr_top(value, span.line, out), - Stmt::Branch { arms, .. } => { - for arm in arms { - if let Some(condition) = &arm.condition { - walk_expr_top(condition, 0, out); - } - statements(&arm.body, out); - } - } - Stmt::While { condition, body, span, .. } => { - walk_expr_top(condition, span.line, out); - statements(body, out); - } - Stmt::ForEach { - item, - collection, - label, - body, - span, - } => { - let shown = label - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .unwrap_or_else(|| format!("遍历 {collection} 为 {item}")); - out.push(NamedStepSite { - label: shown, - kind: "iterate".into(), - context: "executable".into(), - resolution: "payload".into(), - line: span.line, - call: None, - }); - statements(body, out); - } - } - } - } - statements(&function.body, &mut out); - out -} - -fn call_name(call: &CallExpr) -> String { - call_display(call) -} - -fn effects_for_call(module: &Module, current: &Function, call: &CallExpr, index: Option<&ProjectIndex>) -> EffectSet { - let mut effects = EffectSet::default(); - match resolve_for_exec(module, current, call) { - ExecTarget::Host(host) => { - for effect in host.effects() { effects.add(*effect); } - } - ExecTarget::Builtin("print") => effects.add("output.write"), - ExecTarget::Builtin("input") => effects.add("user.input"), - ExecTarget::Builtin(_) => return EffectSet::pure(), - ExecTarget::Local(_) => {}, - ExecTarget::Import { lib, fun, .. } => { - if index.is_some_and(|index| lib.source.path.as_ref().is_some_and(|path| index.module_id_for_path(path).is_some())) { - // Project-indexed dependencies close by edges, not shallow AST clones. - return EffectSet::default(); - } - return imported_effects(lib, fun, &mut std::collections::HashSet::new()); - }, - ExecTarget::Dynamic { reason: DynamicReason::Plugin, .. } => effects.add("plugin.call"), - ExecTarget::Dynamic { .. } | ExecTarget::Unresolved { .. } => return EffectSet::unknown(), - } - effects -} - -fn imported_effects( - module: &Module, function: &Function, - visiting: &mut std::collections::HashSet<(Option, u32)>, -) -> EffectSet { - let identity = (module.source.path.clone(), function.span.line); - if !visiting.insert(identity.clone()) { return EffectSet::default(); } - let mut effects = EffectSet::default(); - for (_, call, _) in collect_call_sites(function) { - match resolve_for_exec(module, function, &call) { - ExecTarget::Local(fun) => effects.extend(&imported_effects(module, fun, visiting)), - ExecTarget::Import { lib, fun, .. } => effects.extend(&imported_effects(lib, fun, visiting)), - _ => effects.extend(&effects_for_call(module, function, &call, None)), - } - } - visiting.remove(&identity); - effects -} - -fn direct_effects(index: &ProjectIndex, module: &Module, current: &Function, calls: &[(usize, CallExpr, u32)]) -> EffectSet { - let mut effects = EffectSet::default(); - for (_, call, _) in calls { effects.extend(&effects_for_call(module, current, call, Some(index))); } - effects -} - -/// Propagate callee effects along local `dependencies` edges until fixpoint. -/// Empty effect sets become `pure` only after closure (no unknown remains). -/// -/// Deterministic SCC closure digests (M02/G08): -/// - Member seed = sorted `(artifact_id, interface, implementation)` within the SCC -/// - External = sorted closures of dependencies outside the SCC -/// - All members of an SCC share one closure digest -fn close_closure_digests(artifacts: &mut [SemanticArtifact]) { - let n = artifacts.len(); - if n == 0 { - return; - } - let index: BTreeMap = artifacts - .iter() - .enumerate() - .map(|(i, a)| (a.artifact_id.0.clone(), i)) - .collect(); - - // Tarjan SCC - let mut stack: Vec = Vec::new(); - let mut on_stack = vec![false; n]; - let mut indices = vec![-1i32; n]; - let mut lowlink = vec![0i32; n]; - let mut index_counter = 0i32; - let mut sccs: Vec> = Vec::new(); - - fn strongconnect( - v: usize, - artifacts: &[SemanticArtifact], - index_map: &BTreeMap, - stack: &mut Vec, - on_stack: &mut [bool], - indices: &mut [i32], - lowlink: &mut [i32], - index_counter: &mut i32, - sccs: &mut Vec>, - ) { - indices[v] = *index_counter; - lowlink[v] = *index_counter; - *index_counter += 1; - stack.push(v); - on_stack[v] = true; - for dep in &artifacts[v].dependencies { - if let Some(&w) = index_map.get(&dep.0) { - if indices[w] < 0 { - strongconnect( - w, - artifacts, - index_map, - stack, - on_stack, - indices, - lowlink, - index_counter, - sccs, - ); - lowlink[v] = lowlink[v].min(lowlink[w]); - } else if on_stack[w] { - lowlink[v] = lowlink[v].min(indices[w]); - } - } - } - if lowlink[v] == indices[v] { - let mut scc = Vec::new(); - loop { - let w = stack.pop().expect("tarjan stack"); - on_stack[w] = false; - scc.push(w); - if w == v { - break; - } - } - scc.sort_unstable(); - sccs.push(scc); - } - } - - for v in 0..n { - if indices[v] < 0 { - strongconnect( - v, - artifacts, - &index, - &mut stack, - &mut on_stack, - &mut indices, - &mut lowlink, - &mut index_counter, - &mut sccs, - ); - } - } - - // sccs are in reverse topological order (callees before callers for DAGs). - let mut scc_of = vec![0usize; n]; - for (si, scc) in sccs.iter().enumerate() { - for &v in scc { - scc_of[v] = si; - } - } - let mut closure_done = vec![false; n]; - for scc in &sccs { - let mut member_parts = Vec::new(); - for &v in scc { - let a = &artifacts[v]; - member_parts.push(format!( - "{}|{}|{}", - a.artifact_id.0, a.hashes.interface.0, a.hashes.implementation.0 - )); - } - member_parts.sort(); - member_parts.dedup(); - let mut external = Vec::new(); - for &v in scc { - for dep in &artifacts[v].dependencies { - if let Some(&w) = index.get(&dep.0) { - if scc_of[w] != scc_of[v] && closure_done[w] { - external.push(artifacts[w].hashes.closure.0.clone()); - } else if scc_of[w] != scc_of[v] { - // External not yet closed — use artifact hash as stable seed. - external.push(artifacts[w].hashes.artifact.0.clone()); - } - } else { - external.push(dep.0.clone()); - } - } - } - external.sort(); - external.dedup(); - let mut parts = member_parts; - parts.extend(external); - let scc_digest = digest(parts.join("|")); - for &v in scc { - artifacts[v].hashes.closure = scc_digest.clone(); - closure_done[v] = true; - } - } -} - -fn close_effect_dependencies(artifacts: &mut [SemanticArtifact]) { - let index: BTreeMap = artifacts - .iter() - .enumerate() - .map(|(i, a)| (a.artifact_id.0.clone(), i)) - .collect(); - for _ in 0..artifacts.len().saturating_add(1) { - let mut changed = false; - let snapshot: Vec = artifacts.iter().map(|a| a.effects.clone()).collect(); - for artifact in artifacts.iter_mut() { - for dep in &artifact.dependencies { - if let Some(&i) = index.get(&dep.0) { - let before = artifact.effects.values(); - artifact.effects.extend(&snapshot[i]); - if artifact.effects.values() != before { - changed = true; - } - } - } - } - if !changed { - break; - } - } - for artifact in artifacts.iter_mut() { - if artifact.effects.contains("unknown") - && artifact - .effects - .values() - .iter() - .any(|e| e != "unknown" && e != "pure") - { - // Concrete effects from BoundCall closure supersede unknown. - let mut cleaned = EffectSet::default(); - for e in artifact.effects.values() { - if e != "unknown" { - cleaned.add(e); - } - } - artifact.effects = cleaned; - } - if artifact.effects.values().is_empty() { - artifact.effects = EffectSet::pure(); - } - if let Some(sig) = artifact.signature.as_mut() { - sig.effects = artifact.effects.clone(); - } - } -} - -fn source_location(root: &Path, path: &Path, line: u32, end_line: u32) -> SourceLocation { - SourceLocation { file: rel_uri(root, path), line, end_line } -} - -fn rel_uri(root: &Path, path: &Path) -> String { path.strip_prefix(root).unwrap_or(path).to_string_lossy().replace('\\', "/") } -fn digest(value: impl AsRef<[u8]>) -> Digest { let mut hash = Sha256::new(); hash.update(value.as_ref()); Digest(format!("sha256:{:x}", hash.finalize())) } -fn normalize_source(source: &str) -> String { source.lines().map(str::trim).filter(|line| !line.is_empty()).collect::>().join("\n") } -fn percent(value: &str) -> String { value.bytes().map(|byte| match byte { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => (byte as char).to_string(), _ => format!("%{byte:02X}") }).collect() } -fn contract_summary(contract: &ContractSet) -> String { format!("{}|{:?}|{}", contract.params.join(","), contract.returns, contract.fields.join(",")) } - -fn signature_json(signature: Option<&CanonicalSignature>) -> String { - match signature { Some(signature) => format!("{}|{}|{}|{}", signature.receiver, signature.params.iter().map(|p| format!("{}:{}:{}", p.name, p.ty, p.required)).collect::>().join(","), signature.returns, signature.effects.values().join(",")), None => "type".into() } -} - -impl SemanticProject { - pub fn to_json(&self) -> Value { - json!({ - "schema_version": self.schema_version, "project": {"id": self.project_id, "root": self.root}, - "artifacts": self.artifacts.iter().map(artifact_json).collect::>(), - "refs": self.refs.iter().map(ref_json).collect::>(), - "steps": self.steps.iter().map(step_json).collect::>(), - "claims": self.claims.iter().map(claim_json).collect::>(), - "assumptions": self.assumptions.iter().map(assumption_json).collect::>(), - "bound_calls": self.bound_calls.iter().map(bound_call_json).collect::>(), - "dynamic_calls": self.dynamic_calls.iter().map(dynamic_call_json).collect::>(), - }) - } -} - -pub fn artifact_json(artifact: &SemanticArtifact) -> Value { - json!({"schema_version": SCHEMA_VERSION, "artifact_id": artifact.artifact_id.0, "symbol_id": artifact.symbol_id.as_ref().map(SymbolId::as_str), "display_name": artifact.display_name, "kind": artifact.kind, "callable": artifact.callable, "source": {"file": artifact.source.file, "line": artifact.source.line, "end_line": artifact.source.end_line}, "signature": artifact.signature.as_ref().map(|s| json!({"receiver":s.receiver,"params":s.params.iter().map(|p|json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d|&d.0),"unit":p.unit})).collect::>(),"returns":s.returns,"effects":s.effects.values()})), "contract":{"params":artifact.contract.params,"returns":artifact.contract.returns,"fields":artifact.contract.fields}, "effects":artifact.effects.values(), "dependencies":artifact.dependencies.iter().map(|d|&d.0).collect::>(), "provenance":artifact.provenance.iter().map(|p|json!({"uri":p.uri,"locator":p.locator,"content_digest":p.content_digest.as_ref().map(|d|&d.0),"relation":p.relation})).collect::>(), "applicability":artifact.applicability, "hashes":{"interface":artifact.hashes.interface.0,"implementation":artifact.hashes.implementation.0,"evidence":artifact.hashes.evidence.0,"artifact":artifact.hashes.artifact.0,"closure":artifact.hashes.closure.0}, "verification":{"parse":artifact.verification.parse,"resolve":artifact.verification.resolve,"contract":artifact.verification.contract,"execution":artifact.verification.execution,"tests":artifact.verification.tests,"evidence":artifact.verification.evidence,"domain":artifact.verification.domain,"methods":artifact.verification.methods}, "lifecycle":artifact.lifecycle}) -} -fn ref_json(reference: &KnowledgeRef) -> Value { json!({"id":reference.id,"anchor_id":reference.anchor_id,"link_target":reference.link_target,"target_anchor":reference.target_anchor,"target_claim":reference.target_claim,"label":reference.label,"context":reference.context,"source":{"file":reference.source.file,"line":reference.source.line,"end_line":reference.source.end_line},"resolution":reference.resolution,"target":reference.target.as_ref().map(SymbolId::as_str)}) } -fn assumption_json(a:&KnowledgeAssumption)->Value{ - json!({"id":a.id,"owner":a.owner.as_str(),"operation":a.operation, - "premise":a.premise,"postcondition":a.postcondition, - "verification":"declared_not_proved", - "source":{"file":a.source.file,"line":a.source.line}}) -} -fn claim_json(claim: &KnowledgeClaim) -> Value { - json!({"anchor_id":claim.anchor_id,"owner":claim.owner.as_str(), - "label":claim.label,"conclusion":claim.conclusion,"premise":claim.premise, - "verification":"declared_unverified", - "source":{"file":claim.source.file,"line":claim.line}}) -} -fn step_json(step: &KnowledgeStep) -> Value { json!({"id":step.id.0,"anchor_id":step.anchor_id,"definition_digest":step.definition_digest.0,"reference":step.reference,"kind":step.kind,"calls":step.calls.iter().map(SymbolId::as_str).collect::>(),"effects":step.effects.values(),"source":{"file":step.source.file,"line":step.source.line,"end_line":step.source.end_line}}) } -fn bound_call_json(call: &BoundCall) -> Value { - json!({ - "caller":call.caller.as_str(), - "target": call.target.as_str(), - "call_site": call.call_site, - "args":call.args.iter().map(|a|json!({ - "name":a.name,"integer":a.integer,"symbol":a.symbol, - "expression_digest":a.expression_digest.0 - })).collect::>(), - "path_guards":call.path_guards, - "control_blocker":call.control_blocker, - "source": {"file": call.source.file, "line": call.source.line, "end_line": call.source.end_line}, - "required_effects": call.required_effects.values(), - "binding": "BoundCall", - }) -} -fn dynamic_call_json(call: &DynamicCall) -> Value { - json!({ - "reason": call.reason, - "call_site": call.call_site, - "source": {"file": call.source.file, "line": call.source.line, "end_line": call.source.end_line}, - "binding": "DynamicCall", - }) -} - -const SEMANTIC_NAMES: &[&str] = &[ - "project.json", - "symbols.json", - "refs.json", - "steps.json", - "anchors.json", - "claims.json", - "assumptions.json", - "proof-index.json", - "proof-obligations.json", - "bound_calls.json", - "dynamic_calls.json", - "artifacts", - "graph", - "verification", -]; - -/// Resolve the active semantic generation directory (G04). -/// Prefers `CURRENT` → `generations//`; falls back to `out_dir` itself. -pub fn semantic_generation_dir(out_dir: &Path) -> PathBuf { - let current = out_dir.join("CURRENT"); - if let Ok(id) = fs::read_to_string(¤t) { - let id = id.trim(); - if !id.is_empty() { - let gen = out_dir.join("generations").join(id); - if gen.join("project.json").is_file() { - return gen; - } - } - } - out_dir.to_path_buf() -} - -/// Atomically write the semantic portion of `.marqdo/` as a whole generation -/// (G04). Readers that open via [`semantic_generation_dir`] never see a mix. -pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) -> Result<()> { - fs::create_dir_all(out_dir).with_context(|| format!("create {}", out_dir.display()))?; - let build_id = { - let mut hasher = Sha256::new(); - hasher.update(compilation.semantics.project_id.as_bytes()); - for a in &compilation.semantics.artifacts { - hasher.update(a.hashes.artifact.0.as_bytes()); - } - hasher.update( - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_nanos() - .to_le_bytes(), - ); - format!("{:x}", hasher.finalize())[..16].to_string() - }; - let gens = out_dir.join("generations"); - fs::create_dir_all(&gens)?; - let gen_dir = gens.join(&build_id); - if gen_dir.exists() { - fs::remove_dir_all(&gen_dir)?; - } - fs::create_dir_all(gen_dir.join("artifacts"))?; - fs::create_dir_all(gen_dir.join("graph"))?; - fs::create_dir_all(gen_dir.join("verification"))?; - write_generation_tree(&gen_dir, compilation, &out_dir.join("prove"))?; - - // Publish journal + CAS (M-R6): record expected CURRENT before switching. - let expected = fs::read_to_string(out_dir.join("CURRENT")) - .ok() - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()); - let source_digest = { - let mut h = Sha256::new(); - for a in &compilation.semantics.artifacts { - h.update(a.hashes.artifact.0.as_bytes()); - } - format!("sha256:{:x}", h.finalize()) - }; - // Staging already written under gen_dir; journal tracks CURRENT switch. - let mut journal = crate::runtime::PublishJournal::begin( - out_dir, - &compilation.semantics.project_id, - expected, - &build_id, - &source_digest, - ) - .map_err(|e| anyhow::anyhow!("publish journal: {e}"))?; - // Point journal staging at the generation we just wrote (already complete). - journal.staging_dir = gen_dir.clone(); - journal.generation_dir = gen_dir.clone(); - journal - .mark(out_dir, crate::runtime::publish::PublishPhase::Validated) - .map_err(|e| anyhow::anyhow!("publish journal mark: {e}"))?; - - // Atomic generation pointer: only publish CURRENT after the tree is complete. - let current_tmp = out_dir.join("CURRENT.tmp"); - fs::write(¤t_tmp, format!("{build_id}\n")) - .with_context(|| format!("write {}", current_tmp.display()))?; - fs::rename(¤t_tmp, out_dir.join("CURRENT")) - .with_context(|| format!("publish CURRENT under {}", out_dir.display()))?; - journal - .mark(out_dir, crate::runtime::publish::PublishPhase::CurrentSwitched) - .map_err(|e| anyhow::anyhow!("publish journal current: {e}"))?; - let _ = fs::remove_file(out_dir.join("publish_journal.json")); - - // Compatibility root: stage a full mirror, then swap names (best-effort for - // legacy readers that do not follow CURRENT). - let stage = out_dir.join(".tmp-sema-publish"); - if stage.exists() { - fs::remove_dir_all(&stage)?; - } - copy_dir_recursive(&gen_dir, &stage)?; - for name in SEMANTIC_NAMES { - let target = out_dir.join(name); - if target.exists() { - if target.is_dir() { - fs::remove_dir_all(&target)?; - } else { - fs::remove_file(&target)?; - } - } - fs::rename(stage.join(name), &target)?; - } - let _ = fs::remove_dir_all(&stage); - Ok(()) -} - -fn write_generation_tree(stage: &Path, compilation: &Compilation, prove_root: &Path) -> Result<()> { - let project = compilation.semantics.to_json(); - write_json( - &stage.join("project.json"), - &json!({ - "schema_version": SCHEMA_VERSION, - "project": project["project"], - "artifact_count": compilation.semantics.artifacts.len(), - "generation": stage.file_name().and_then(|s| s.to_str()), - }), - )?; - write_json(&stage.join("symbols.json"), &json!({"schema_version":SCHEMA_VERSION,"symbols":compilation.index.symbols().iter().map(|s|json!({"id":s.id.as_str(),"module":s.module.as_str(),"kind":s.kind.as_str(),"callable":s.callable.map(|c|c.as_str()),"name":s.name,"declaration_path":s.declaration_path,"source":{"file":rel_uri(compilation.index.root().path(),&s.source),"line":s.line}})).collect::>() }))?; - write_json(&stage.join("refs.json"), &json!({"schema_version":SCHEMA_VERSION,"refs":project["refs"]}))?; - write_json(&stage.join("steps.json"), &json!({"schema_version":SCHEMA_VERSION,"steps":project["steps"]}))?; - write_json(&stage.join("claims.json"), &json!({ - "schema_version":SCHEMA_VERSION, - "role":"theorem_declarations_not_proof_results", - "claims":project["claims"] - }))?; - let proofs=crate::knowledge::proof::index_links(prove_root, &compilation.semantics); - write_json(&stage.join("assumptions.json"), &json!({ - "schema_version":SCHEMA_VERSION, - "role":"declared_modular_contracts_require_callsite_proof", - "assumptions":project["assumptions"] - }))?; - write_json(&stage.join("proof-index.json"), &proofs)?; - write_json(&stage.join("proof-obligations.json"), - &crate::knowledge::modular::analyze(&compilation.semantics, &proofs))?; - write_json(&stage.join("anchors.json"), &json!({ - "schema_version":SCHEMA_VERSION, - "role":"stable_public_knowledge_addresses", - "anchors": compilation.semantics.steps.iter() - .filter(|step| step.anchor_id.is_some()) - .map(|step| json!({ - "anchor_id":step.anchor_id, - "owner":step.id.0.split('#').next(), - "label":compilation.semantics.refs.iter() - .find(|r| r.id == step.reference).map(|r| r.label.as_str()), - "step_id":step.id.0, - "kind":step.kind, - "source":step_json(step)["source"], - "definition_digest":step.definition_digest.0, - "effects":step.effects.values(), - })).collect::>() - }))?; - write_json(&stage.join("bound_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"bound_calls":project["bound_calls"]}))?; - write_json(&stage.join("dynamic_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"dynamic_calls":project["dynamic_calls"]}))?; - write_json(&stage.join("graph/nodes.json"), &json!({"schema_version":SCHEMA_VERSION,"nodes":project["artifacts"]}))?; - let mut edges: Vec = compilation - .semantics - .artifacts - .iter() - .flat_map(|a| { - a.dependencies.iter().map(move |d| { - json!({"from": a.artifact_id.0, "to": d.0, "kind": "calls"}) - }) - }) - .collect(); - for assumption in &compilation.semantics.assumptions { - edges.push(json!({"from":assumption.owner.as_str(), - "to":assumption.id,"kind":"declares_assumption"})); - } - for claim in &compilation.semantics.claims { - edges.push(json!({"from":claim.owner.as_str(), - "to":claim.anchor_id,"kind":"declares_claim"})); - } - for reference in &compilation.semantics.refs { - if let Some(claim) = &reference.target_claim { - let owner=reference.id.split("#ref-").next().unwrap_or(""); - edges.push(json!({"from":owner,"to":claim,"kind":"references_claim"})); - } - if let Some(target) = &reference.target_anchor { - let owner = reference.id.split("#ref-").next().unwrap_or(""); - edges.push(json!({"from":owner,"to":target,"kind":"references_anchor"})); - } - } - for step in &compilation.semantics.steps { - if let Some(anchor) = &step.anchor_id { - if let Some(owner) = step.id.0.split('#').next() { - edges.push(json!({"from":owner,"to":anchor,"kind":"defines_anchor"})); - } - for target in &step.calls { - edges.push(json!({"from":anchor,"to":target.as_str(),"kind":"calls"})); - } - } - if step.kind == "narrate" { - for target in &step.calls { - edges.push(json!({ - "from": step.id.0, - "to": target.as_str(), - "kind": "narrates", - })); - } - } - } - write_json( - &stage.join("graph/edges.json"), - &json!({ - "schema_version": SCHEMA_VERSION, - "authority": "SemanticProject", - "edges": edges, - }), - )?; - for artifact in &compilation.semantics.artifacts { - let name = hex_name(&artifact.artifact_id.0); - write_json( - &stage.join("artifacts").join(format!("{name}.json")), - &artifact_json(artifact), - )?; - write_json( - &stage.join("verification").join(format!("{name}.json")), - &artifact_json(artifact)["verification"], - )?; - } - Ok(()) -} - -fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> { - fs::create_dir_all(dst)?; - for ent in fs::read_dir(src).with_context(|| format!("read {}", src.display()))? { - let ent = ent?; - let from = ent.path(); - let to = dst.join(ent.file_name()); - if from.is_dir() { - copy_dir_recursive(&from, &to)?; - } else { - fs::copy(&from, &to) - .with_context(|| format!("copy {} → {}", from.display(), to.display()))?; - } - } - Ok(()) -} - -fn write_json(path: &Path, value: &Value) -> Result<()> { fs::write(path, serde_json::to_vec_pretty(value)?).with_context(|| format!("write {}", path.display())) } -fn hex_name(value: &str) -> String { digest(value).0.trim_start_matches("sha256:").to_string() } - -#[cfg(test)] -mod tests { - use super::*; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn root() -> PathBuf { let id = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); let root = std::env::temp_dir().join(format!("marqdo-sema-ir-{id}")); fs::create_dir_all(&root).unwrap(); root } - - #[test] - fn compilation_is_deterministic_and_preserves_contract_effects() { - let root = root(); - fs::write(root.join("main.mq.md"), "---\nimport:\n fs: lib/fs.mq.md\n---\n# main\n\n| 参数 | 类型 |\n| --- | --- |\n| path | text |\n\n## save\n\n> fs.write_text `path` ok\n\n*1*").unwrap(); - let options = CompileOptions::for_path(&root).unwrap(); - let first = compile_project(&options).unwrap(); - let second = compile_project(&options).unwrap(); - assert_eq!(first.semantics.to_json(), second.semantics.to_json()); - let save = first.semantics.artifacts.iter().find(|a| a.display_name.ends_with("save")).unwrap(); - assert!(save.effects.values().contains(&"fs.write".to_string())); - assert_eq!(save.hashes.implementation.0, first.semantics.artifacts.iter().find(|a| a.display_name.ends_with("save")).unwrap().hashes.implementation.0); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn semantic_files_have_schema_versions() { - let root = root(); fs::write(root.join("a.mq.md"), "# a\n\n*1*").unwrap(); - let out = root.join(".marqdo"); let compilation = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - write_semantic_projections(&out, &compilation).unwrap(); - let project: Value = serde_json::from_str(&fs::read_to_string(out.join("project.json")).unwrap()).unwrap(); - assert_eq!(project["schema_version"], SCHEMA_VERSION); - assert!(out.join("artifacts").read_dir().unwrap().next().is_some()); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn unknown_call_is_not_pure_and_wrapper_inherits_fs_write() { - let root = root(); - fs::write( - root.join("main.mq.md"), - r#"--- -markup: occlusion -import: - fs: lib/fs.mq.md ---- - -## save - -> fs.write_text path=out.txt text=ok -*1* - -## wrap - -> save -*None* - -## mystery - -> weird_plugin_thing x=1 -*None* - -# main - -> wrap -> print text=ok -"#, - ) - .unwrap(); - let compilation = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let wrap = compilation - .semantics - .artifacts - .iter() - .find(|a| a.display_name.ends_with("wrap")) - .unwrap(); - assert!( - wrap.effects.values().contains(&"fs.write".to_string()), - "wrapper must inherit fs.write, got {:?}", - wrap.effects.values() - ); - assert!(!wrap.effects.is_pure()); - let mystery = compilation - .semantics - .artifacts - .iter() - .find(|a| a.display_name.ends_with("mystery")) - .unwrap(); - // bare local unresolved name → empty then closed; without a symbol it stays - // as empty→pure OR if treated as call site with no resolve, empty→pure. - // Path-like / unknown plugin style: use a dotted name. - let _ = mystery; - fs::write( - root.join("dyn.mq.md"), - "# dyn\n\n## go\n\n> plugin.do_stuff x=1\n\n*None*\n", - ) - .unwrap(); - let dyn_comp = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let go = dyn_comp - .semantics - .artifacts - .iter() - .find(|a| a.display_name.ends_with("go")) - .unwrap(); - assert!( - go.effects.contains("plugin.call") || go.effects.contains("unknown"), - "plugin/dynamic must not be pure: {:?}", - go.effects.values() - ); - assert!(!go.effects.is_pure()); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn public_anchors_survive_unrelated_insertions_and_track_definition_changes() { - let root = root(); - let file = root.join("main.mq.md"); - let source = |prefix: &str, amount: i32| format!( - "# main\n\n## calculate\n\n{prefix}**x = [计算税额]({amount} * 2)**\n*x*\n" - ); - fs::write(&file, source("", 3)).unwrap(); - let one = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let anchor1 = one.semantics.steps.iter().find(|s| s.anchor_id.is_some()).unwrap(); - let identity = anchor1.anchor_id.clone(); - let digest1 = anchor1.definition_digest.clone(); - fs::write(&file, source("**other = [准备参数](1)**\n", 3)).unwrap(); - let two = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let anchor2 = two.semantics.steps.iter() - .find(|s| s.anchor_id == identity).unwrap(); - assert_eq!(anchor1.anchor_id, anchor2.anchor_id); - assert_eq!(digest1, anchor2.definition_digest); - assert_ne!(anchor1.id, anchor2.id, "legacy ordinal step id may move"); - fs::write(&file, source("**other = [准备参数](1)**\n", 4)).unwrap(); - let three = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let anchor3 = three.semantics.steps.iter() - .find(|s| s.anchor_id == identity).unwrap(); - assert_ne!(digest1, anchor3.definition_digest); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn markdown_knowledge_links_bind_only_to_registered_anchors() { - let root=root(); - fs::write(root.join("main.mq.md"), - "# main\n\n## f\n\n[说明](#@演算)\n[不存在](#@没有)\n**x = [演算](2 * 3)**\n*x*\n" - ).unwrap(); - let c=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let target=c.semantics.steps.iter().find_map(|s|s.anchor_id.as_deref()).unwrap(); - let link=c.semantics.refs.iter().find(|r|r.label=="说明").unwrap(); - assert_eq!(link.target_anchor.as_deref(),Some(target)); - assert_eq!(link.resolution,"anchor"); - assert!(link.target.is_none(),"narrative links must never become executable calls"); - let bad=c.semantics.refs.iter().find(|r|r.label=="不存在").unwrap(); - assert_eq!(bad.resolution,"unresolved_anchor"); - assert!(bad.target_anchor.is_none()); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn canonical_mq_uri_resolves_across_functions_without_calling_knowledge() { - let root=root(); - let src=root.join("main.mq.md"); - fs::write(&src,"# main\n\n## source\n\n**x = [演算](2 * 3)**\n*x*\n").unwrap(); - let initial=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let anchor=initial.semantics.steps.iter().find_map(|s|s.anchor_id.clone()).unwrap(); - let updated=format!( - "# main\n\n## source\n\n**x = [演算](2 * 3)**\n*x*\n\n## consumer\n\n[阅读计算知识]({anchor})\n*None*\n" - ); - fs::write(&src,updated).unwrap(); - let parsed=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let read=parsed.semantics.refs.iter().find(|r|r.label=="阅读计算知识").unwrap(); - assert_eq!(read.target_anchor.as_deref(),Some(anchor.as_str())); - assert_eq!(read.resolution,"anchor"); - assert!(read.target.is_none()); - assert!(parsed.semantics.bound_calls.iter().all(|c|c.call_site!="阅读计算知识")); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn theorem_claims_are_addressable_but_never_implicitly_proved() { - let root=root(); - fs::write(root.join("main.mq.md"), - "# main\n\n## f\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| 安全性质 | 长度(轨迹) = 0 | | auto |\n\n[阅读定理](#@安全性质)\n**x = [演算](2 * 3)**\n*x*\n").unwrap(); - let c=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - assert_eq!(c.semantics.claims.len(),1); - let claim=&c.semantics.claims[0]; - let link=c.semantics.refs.iter().find(|r|r.label=="阅读定理").unwrap(); - assert_eq!(link.target_claim.as_deref(),Some(claim.anchor_id.as_str())); - assert_eq!(link.resolution,"claim"); - assert!(link.target.is_none()); - let serialized=c.semantics.to_json(); - assert_eq!(serialized["claims"][0]["verification"],"declared_unverified"); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn duplicate_labels_fail_closed_in_public_anchor_projection() { - let root = root(); - fs::write(root.join("main.mq.md"), - "# main\n\n## f\n\n**x = [重复](1)**\n**y = [重复](2)**\n*y*\n").unwrap(); - let compilation = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let duplicated: Vec<_> = compilation.semantics.refs.iter() - .filter(|r| r.label == "重复").collect(); - assert_eq!(duplicated.len(), 2); - assert!(duplicated.iter().all(|r| r.anchor_id.is_none())); - let out = root.join(".marqdo"); - write_semantic_projections(&out, &compilation).unwrap(); - let anchors: Value = serde_json::from_str( - &fs::read_to_string(out.join("anchors.json")).unwrap()).unwrap(); - assert!(anchors["anchors"].as_array().unwrap().is_empty()); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn named_steps_classify_observe_derive_iterate_call() { - let root = root(); - fs::write( - root.join("main.mq.md"), - r#"--- -markup: occlusion -import: - json: lib/json.mq.md ---- - -## 加倍 - -根据输入`n`返回两倍。 - -*[两倍](n * 2)* - -# main - -`列` = > json.parse text=["一","二"] -**a = [取表项](access(`列`, 1))** -**b = [两件小计](2 * 30)** -**c = [调用加倍](加倍(n=3))** -- [篮子里的每个果子](遍历 `列` 为 `果`) - > print text=`果` -> print text=`c` -"#, - ) - .unwrap(); - let compilation = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap(); - let main_steps: Vec<&KnowledgeStep> = compilation - .semantics - .steps - .iter() - .filter(|s| s.id.0.contains("main")) - .collect(); - let kinds: Vec<&str> = main_steps.iter().map(|s| s.kind.as_str()).collect(); - assert!( - kinds.contains(&"observe"), - "expected observe step, got {kinds:?}" - ); - assert!( - kinds.contains(&"derive"), - "expected derive step, got {kinds:?}" - ); - assert!( - kinds.contains(&"iterate"), - "expected iterate step, got {kinds:?}" - ); - assert!( - kinds.iter().any(|k| *k == "call"), - "expected call step, got {kinds:?}" - ); - assert!( - !kinds.iter().all(|k| *k == "call"), - "steps must not all be forged as call: {kinds:?}" - ); - let labels: Vec = main_steps - .iter() - .filter_map(|s| { - compilation - .semantics - .refs - .iter() - .find(|r| r.id == s.reference) - .map(|r| r.label.clone()) - }) - .collect(); - assert!(labels.iter().any(|l| l.contains("取表项")), "{labels:?}"); - assert!(labels.iter().any(|l| l.contains("两件小计")), "{labels:?}"); - assert!(labels.iter().any(|l| l.contains("篮子")), "{labels:?}"); - assert!(labels.iter().any(|l| l.contains("调用加倍")), "{labels:?}"); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/sema/lock.rs b/src/sema/lock.rs deleted file mode 100755 index fff9dff..0000000 --- a/src/sema/lock.rs +++ /dev/null @@ -1,295 +0,0 @@ -//! Reviewable semantic link lock and reverse-impact queries. - -use std::collections::{BTreeMap, BTreeSet, VecDeque}; -use std::fs; -use std::path::Path; - -use anyhow::{Context, Result}; -use serde_json::{json, Value}; - -use super::ir::{SemanticProject, SCHEMA_VERSION}; - -#[derive(Debug, Clone, Default)] -pub struct LockReport { - pub status: String, - pub missing: Vec, - pub changed: Vec, - pub removed: Vec, - /// Per-artifact which digest class drifted (G08). - pub classes: Vec, -} - -impl LockReport { - pub fn is_clean(&self) -> bool { - self.status == "clean" - } - - pub fn to_json(&self) -> Value { - json!({ - "schema_version": SCHEMA_VERSION, - "status": self.status, - "missing": self.missing, - "changed": self.changed, - "removed": self.removed, - "classes": self.classes, - }) - } -} - -pub fn update_links_lock(out_dir: &Path, project: &SemanticProject) -> Result<()> { - fs::create_dir_all(out_dir)?; - let target = out_dir.join("links.lock.json"); - let staged = out_dir.join(".links.lock.json.tmp"); - fs::write(&staged, serde_json::to_vec_pretty(&lock_json(project))?) - .with_context(|| format!("write {}", staged.display()))?; - fs::rename(&staged, &target) - .with_context(|| format!("replace {}", target.display()))?; - Ok(()) -} - -pub fn check_links_lock(out_dir: &Path, project: &SemanticProject) -> Result { - let path = out_dir.join("links.lock.json"); - if !path.exists() { - return Ok(LockReport { - status: "missing".into(), - missing: project.artifacts.iter().map(|a| a.artifact_id.0.clone()).collect(), - ..LockReport::default() - }); - } - let raw: Value = serde_json::from_str(&fs::read_to_string(&path) - .with_context(|| format!("read {}", path.display()))?) - .with_context(|| format!("parse {}", path.display()))?; - if raw.get("schema_version").and_then(Value::as_u64) != Some(SCHEMA_VERSION as u64) { - return Ok(LockReport { - status: "schema_mismatch".into(), - changed: vec!["schema_version".into()], - ..LockReport::default() - }); - } - let expected = artifact_lock_entries(project); - let actual = raw.get("artifacts").and_then(Value::as_object).cloned().unwrap_or_default(); - let mut report = LockReport::default(); - for (id, entry) in &expected { - match actual.get(id).and_then(Value::as_object) { - None => report.missing.push(id.clone()), - Some(found) => { - let mut drifted = Vec::new(); - for key in ["interface", "implementation", "evidence", "artifact", "closure"] { - let want = entry.get(key).and_then(Value::as_str); - let got = found.get(key).and_then(Value::as_str); - if want != got { - drifted.push(key.to_string()); - } - } - if !drifted.is_empty() { - report.changed.push(id.clone()); - report.classes.push(json!({ - "artifact_id": id, - "changed": drifted, - })); - } - } - } - } - for id in actual.keys() { - if !expected.contains_key(id) { - report.removed.push(id.clone()); - } - } - report.missing.sort(); - report.changed.sort(); - report.removed.sort(); - report.status = if report.missing.is_empty() - && report.changed.is_empty() - && report.removed.is_empty() - { - "clean".into() - } else { - "outdated".into() - }; - Ok(report) -} - -/// Static reverse dependency closure. Queries can be an artifact/symbol URI, -/// a declaration suffix, a project-relative source filename, or a corpus -/// provenance URI (`supports` relation — M02). -pub fn impact(project: &SemanticProject, query: &str) -> Value { - let mut seeds = BTreeSet::new(); - for artifact in &project.artifacts { - if artifact.artifact_id.0 == query - || artifact.symbol_id.as_ref().is_some_and(|id| id.as_str() == query) - || artifact.display_name == query - || artifact.source.file == query - || artifact.source.file.ends_with(query) - || std::path::Path::new(&artifact.source.file) - .file_stem() - .and_then(|s| s.to_str()) - .is_some_and(|stem| stem == query || query.ends_with(stem)) - || artifact.artifact_id.0.ends_with(query) - || artifact.provenance.iter().any(|p| { - p.relation == "supports" - && (p.uri == query - || p.uri.ends_with(query) - || query.ends_with(&p.uri) - || p.locator - .as_ref() - .is_some_and(|loc| format!("{}#{}", p.uri, loc) == query)) - }) - { - seeds.insert(artifact.artifact_id.0.clone()); - } - } - let mut reverse: BTreeMap> = BTreeMap::new(); - for artifact in &project.artifacts { - for dependency in &artifact.dependencies { - reverse - .entry(dependency.0.clone()) - .or_default() - .push(artifact.artifact_id.0.clone()); - } - // Corpus URI → citing artifact (provenance supports edges). - for prov in &artifact.provenance { - if prov.relation != "supports" { - continue; - } - reverse - .entry(prov.uri.clone()) - .or_default() - .push(artifact.artifact_id.0.clone()); - if let Some(loc) = &prov.locator { - reverse - .entry(format!("{}#{}", prov.uri, loc)) - .or_default() - .push(artifact.artifact_id.0.clone()); - } - } - } - // NarrativeRef edges: step → symbol; impact includes the step's owning artifact. - for step in &project.steps { - if step.kind != "narrate" { - continue; - } - let owner = step - .id - .0 - .split("#step-") - .next() - .unwrap_or(step.id.0.as_str()) - .to_string(); - for target in &step.calls { - reverse - .entry(target.as_str().to_string()) - .or_default() - .push(owner.clone()); - } - } - // Also seed reverse walk from corpus URI keys when query matches them. - if reverse.contains_key(query) { - seeds.insert(query.to_string()); - } - let mut queue: VecDeque = seeds.iter().cloned().collect(); - let mut affected = BTreeSet::new(); - while let Some(current) = queue.pop_front() { - if !affected.insert(current.clone()) { - continue; - } - if let Some(users) = reverse.get(¤t) { - for user in users { - queue.push_back(user.clone()); - } - } - } - // Drop pure corpus URI keys that are not artifacts from the affected set display. - let entries = affected - .iter() - .filter_map(|id| project.artifacts.iter().find(|a| &a.artifact_id.0 == id)) - .map(|artifact| { - let classes = { - let mut c = Vec::new(); - if !artifact.hashes.interface.0.is_empty() { - c.push("interface"); - } - if !artifact.hashes.implementation.0.is_empty() { - c.push("implementation"); - } - if !artifact.hashes.evidence.0.is_empty() { - c.push("evidence"); - } - if !artifact.dependencies.is_empty() { - c.push("dependency"); - } - c - }; - json!({ - "artifact_id": artifact.artifact_id.0, - "symbol_id": artifact.symbol_id.as_ref().map(|id| id.as_str()), - "display_name": artifact.display_name, - "kind": artifact.kind, - "source": {"file": artifact.source.file, "line": artifact.source.line}, - "hash_classes": classes, - "evidence": artifact.verification.evidence, - }) - }) - .collect::>(); - json!({"schema_version":SCHEMA_VERSION,"query":query,"resolved":!seeds.is_empty(),"seeds":seeds,"affected":entries}) -} - -fn artifact_lock_entries(project: &SemanticProject) -> BTreeMap { - project - .artifacts - .iter() - .map(|artifact| { - ( - artifact.artifact_id.0.clone(), - json!({ - "interface": artifact.hashes.interface.0, - "implementation": artifact.hashes.implementation.0, - "evidence": artifact.hashes.evidence.0, - "artifact": artifact.hashes.artifact.0, - "closure": artifact.hashes.closure.0, - }), - ) - }) - .collect() -} - -fn lock_json(project: &SemanticProject) -> Value { - let mut artifacts = serde_json::Map::new(); - for artifact in &project.artifacts { - artifacts.insert(artifact.artifact_id.0.clone(), json!({ - "interface": artifact.hashes.interface.0, - "implementation": artifact.hashes.implementation.0, - "evidence": artifact.hashes.evidence.0, - "artifact": artifact.hashes.artifact.0, - "closure": artifact.hashes.closure.0, - "dependencies": artifact.dependencies.iter().map(|item| &item.0).collect::>(), - })); - } - json!({"schema_version":SCHEMA_VERSION,"project":project.project_id,"artifacts":artifacts}) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sema::{compile_project, CompileOptions}; - use std::path::PathBuf; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn root() -> PathBuf { let id = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); let path = std::env::temp_dir().join(format!("marqdo-lock-{id}")); fs::create_dir_all(&path).unwrap(); path } - - #[test] - fn lock_detects_semantic_change_and_impact_is_reverse_closed() { - let root = root(); - fs::write(root.join("main.mq.md"), "# add\n\n*1*\n\n# use\n\n*add()*").unwrap(); - let options = CompileOptions::for_path(&root).unwrap(); - let first = compile_project(&options).unwrap(); - let out = root.join(".marqdo"); update_links_lock(&out, &first.semantics).unwrap(); - assert!(check_links_lock(&out, &first.semantics).unwrap().is_clean()); - let response = impact(&first.semantics, "add"); - assert!(response["affected"].as_array().unwrap().len() >= 1); - fs::write(root.join("main.mq.md"), "# add\n\n*2*\n\n# use\n\n*add()*").unwrap(); - let second = compile_project(&options).unwrap(); - assert_eq!(check_links_lock(&out, &second.semantics).unwrap().status, "outdated"); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/sema/mod.rs b/src/sema/mod.rs deleted file mode 100755 index b3ec55b..0000000 --- a/src/sema/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Compiler semantic analysis for executable knowledge. -//! -//! Syntax remains in `ast`/`parse`; this module owns project-wide identity and -//! binding facts so runtime, EKC, view, and agents do not independently infer -//! the meaning of the same source text. - -pub mod bind; -pub(crate) mod resolution; -pub mod extract; -pub mod ir; -pub mod lock; -pub mod provenance; -pub mod symbols; - -pub use bind::{ - call_display, is_static_bound, lookup_local, resolve_for_exec, DynamicReason, ExecTarget, -}; -pub use extract::{plan_pure_extract, ExtractError, ExtractPlan}; -pub use ir::{ - artifact_json, compile_file_closure, compile_project, semantic_generation_dir, - write_semantic_projections, ArtifactId, - BoundCall, CompileOptions, Compilation, Digest, DynamicCall, EffectSet, LockMode, - SemanticArtifact, SemanticProject, -}; -pub use lock::{check_links_lock, impact as semantic_impact, update_links_lock, LockReport}; -pub use symbols::{CallableKind, ModuleId, ProjectIndex, SymbolDecl, SymbolId, SymbolKind}; diff --git a/src/sema/provenance.rs b/src/sema/provenance.rs deleted file mode 100755 index f88c5b8..0000000 --- a/src/sema/provenance.rs +++ /dev/null @@ -1,512 +0,0 @@ -//! Optional source / applicability facts from module frontmatter (G05 / M02). -//! -//! Authors declare `sources:` and optional `applicability:` / `valid_until` in -//! frontmatter. Absence means a pure tool may still run but must stay -//! `evidence=unverified` — never invent a business SourceRef. - -use std::fs; -use std::path::{Path, PathBuf}; - -use sha2::{Digest as _, Sha256}; - -use super::ir::{Digest, SourceRef}; - -/// Provenance extractor / verifier identity hashed into evidence digests. -pub const PROVENANCE_EXTRACTOR_VERSION: &str = "marqdo-provenance/1"; - -#[derive(Debug, Clone, Default)] -pub struct ModuleProvenance { - /// Relative corpus paths, optional `#anchor`. - pub sources: Vec, - pub valid_until: Option, - pub region: Option, - /// True when author wrote `sources: [...]` inline (ignored by parser — M07). - pub inline_sources_ignored: bool, - /// Optional per-function source overrides (M07): `function_sources: { name: [uri…] }`. - pub function_sources: std::collections::BTreeMap>, -} - -/// Scan YAML-ish frontmatter for sources / applicability (no full YAML parser). -pub fn parse_module_provenance(source: &str) -> ModuleProvenance { - let mut lines = source.lines(); - if lines.next().map(|l| l.trim_end()) != Some("---") { - return ModuleProvenance::default(); - } - let mut out = ModuleProvenance::default(); - let mut in_sources = false; - let mut in_applicability = false; - let mut in_function_sources = false; - let mut current_fn: Option = None; - for line in lines { - let t = line.trim_end(); - if t.trim() == "---" { - break; - } - let trimmed = t.trim(); - if trimmed.is_empty() { - continue; - } - if !line.starts_with(' ') && !line.starts_with('\t') { - in_sources = false; - in_applicability = false; - in_function_sources = false; - current_fn = None; - } - if trimmed == "sources:" || trimmed.starts_with("sources:") { - in_sources = true; - in_applicability = false; - in_function_sources = false; - if let Some(rest) = trimmed.strip_prefix("sources:") { - let rest = rest.trim(); - if !rest.is_empty() && rest != "|" { - // inline list is not parsed — flag for diagnosis (M07). - out.inline_sources_ignored = true; - } - } - continue; - } - if trimmed == "function_sources:" || trimmed.starts_with("function_sources:") { - in_function_sources = true; - in_sources = false; - in_applicability = false; - current_fn = None; - continue; - } - if trimmed == "applicability:" || trimmed.starts_with("applicability:") { - in_applicability = true; - in_sources = false; - in_function_sources = false; - continue; - } - if in_function_sources { - // Indent levels: ` name:` then ` - uri` - let indent = line.len() - line.trim_start().len(); - if trimmed.ends_with(':') && !trimmed.starts_with('-') { - let name = trimmed.trim_end_matches(':').trim().to_string(); - if !name.is_empty() { - current_fn = Some(name.clone()); - out.function_sources.entry(name).or_default(); - } - continue; - } - if let Some(item) = trimmed.strip_prefix("- ") { - let path = item.trim().trim_matches('"').to_string(); - if let Some(name) = ¤t_fn { - if !path.is_empty() { - out.function_sources - .entry(name.clone()) - .or_default() - .push(path); - } - } else if indent >= 2 && !path.is_empty() { - // ignore orphan list items - } - } - continue; - } - if in_sources { - if let Some(item) = trimmed.strip_prefix("- ") { - let path = item.trim().trim_matches('"').to_string(); - if !path.is_empty() { - out.sources.push(path); - } - } - continue; - } - if in_applicability { - if let Some(rest) = trimmed.strip_prefix("valid_until:") { - out.valid_until = Some(rest.trim().trim_matches('"').to_string()); - } else if let Some(rest) = trimmed.strip_prefix("region:") { - out.region = Some(rest.trim().trim_matches('"').to_string()); - } - } - } - out -} - -/// Sources applicable to a named function: function_sources override, else module sources. -pub fn sources_for_function(prov: &ModuleProvenance, function_name: &str) -> Vec { - if let Some(list) = prov.function_sources.get(function_name) { - if !list.is_empty() { - return list.clone(); - } - } - prov.sources.clone() -} - -#[derive(Debug, Clone)] -pub enum ProvenanceDiag { - Missing { path: String }, - AnchorMissing { path: String, locator: String }, - ReadError { path: String, message: String }, - Expired { valid_until: String }, - InvalidDate { valid_until: String }, - InlineSourcesIgnored, -} - -impl ProvenanceDiag { - pub fn code(&self) -> &'static str { - match self { - Self::Missing { .. } => "source.missing", - Self::AnchorMissing { .. } => "source.anchor_missing", - Self::ReadError { .. } => "source.read_error", - Self::Expired { .. } => "source.expired", - Self::InvalidDate { .. } => "source.invalid_date", - Self::InlineSourcesIgnored => "source.inline_ignored", - } - } - - pub fn message(&self) -> String { - match self { - Self::Missing { path } => format!("来源文件缺失:`{path}`"), - Self::AnchorMissing { path, locator } => { - format!("来源锚点不存在:`{path}` 中找不到 `#{}`", locator) - } - Self::ReadError { path, message } => { - format!("来源文件无法读取:`{path}`({message})") - } - Self::Expired { valid_until } => { - format!("来源适用期已过(valid_until={valid_until})") - } - Self::InvalidDate { valid_until } => { - format!("适用期日期格式无效(期望 YYYY-MM-DD):`{valid_until}`") - } - Self::InlineSourcesIgnored => { - "sources 行内列表被忽略;请改用 YAML block list(`- path#anchor`)".into() - } - } - } -} - -pub struct ProvenanceResolution { - pub refs: Vec, - pub applicability: String, - pub evidence_status: String, - pub diagnostics: Vec, - /// Canonical record hashed into `hashes.evidence` (M02). - pub evidence_record: String, -} - -/// Resolve corpus paths relative to the module file; never mark verified here. -pub fn resolve_provenance( - module_path: &Path, - prov: &ModuleProvenance, -) -> ProvenanceResolution { - resolve_provenance_sources(module_path, prov, &prov.sources) -} - -/// Resolve an explicit source list (module or per-function). -pub fn resolve_provenance_sources( - module_path: &Path, - prov: &ModuleProvenance, - sources: &[String], -) -> ProvenanceResolution { - let mut refs = Vec::new(); - let mut diagnostics = Vec::new(); - if prov.inline_sources_ignored { - diagnostics.push(ProvenanceDiag::InlineSourcesIgnored); - } - let base = module_path - .parent() - .map(|p| p.to_path_buf()) - .unwrap_or_else(|| PathBuf::from(".")); - - for raw in sources { - let (path_part, locator) = match raw.split_once('#') { - Some((p, a)) => (p.trim(), Some(a.trim().to_string())), - None => (raw.as_str(), None), - }; - let resolved = base.join(path_part); - if !resolved.is_file() { - diagnostics.push(ProvenanceDiag::Missing { - path: raw.clone(), - }); - refs.push(SourceRef { - uri: path_part.to_string(), - locator, - content_digest: None, - relation: "supports".into(), - }); - continue; - } - let content = match fs::read(&resolved) { - Ok(bytes) => bytes, - Err(e) => { - diagnostics.push(ProvenanceDiag::ReadError { - path: path_part.to_string(), - message: e.to_string(), - }); - refs.push(SourceRef { - uri: path_part.to_string(), - locator, - content_digest: None, - relation: "supports".into(), - }); - continue; - } - }; - let mut hash = Sha256::new(); - hash.update(&content); - let content_digest = Digest(format!("sha256:{:x}", hash.finalize())); - if let Some(loc) = locator.as_ref() { - let text = String::from_utf8_lossy(&content); - if !anchor_exists(&text, loc) { - diagnostics.push(ProvenanceDiag::AnchorMissing { - path: path_part.to_string(), - locator: loc.clone(), - }); - } - } - refs.push(SourceRef { - uri: path_part.to_string(), - locator, - content_digest: Some(content_digest), - relation: "supports".into(), - }); - } - - if let Some(until) = &prov.valid_until { - match validate_date(until) { - DateCheck::Ok => { - if is_expired(until) { - diagnostics.push(ProvenanceDiag::Expired { - valid_until: until.clone(), - }); - } - } - DateCheck::Invalid => { - diagnostics.push(ProvenanceDiag::InvalidDate { - valid_until: until.clone(), - }); - } - } - } - - let applicability = match (&prov.region, &prov.valid_until) { - (None, None) if prov.sources.is_empty() => { - "no explicit applicability constraints".into() - } - (region, until) => { - let mut parts = Vec::new(); - if let Some(r) = region { - parts.push(format!("region={r}")); - } - if let Some(u) = until { - parts.push(format!("valid_until={u}")); - } - if parts.is_empty() { - "sources declared".into() - } else { - parts.join("; ") - } - } - }; - - let evidence_status = if diagnostics - .iter() - .any(|d| matches!(d, ProvenanceDiag::Missing { .. } | ProvenanceDiag::ReadError { .. })) - { - "missing_source".into() - } else if diagnostics - .iter() - .any(|d| matches!(d, ProvenanceDiag::AnchorMissing { .. })) - { - "anchor_missing".into() - } else if diagnostics - .iter() - .any(|d| matches!(d, ProvenanceDiag::Expired { .. })) - { - "expired".into() - } else if diagnostics - .iter() - .any(|d| matches!(d, ProvenanceDiag::InvalidDate { .. })) - { - "invalid_date".into() - } else if sources.is_empty() { - "unverified".into() - } else { - // Corpus present and in date — still not domain-verified by compile alone. - "sourced".into() - }; - - let prov_for_record = ModuleProvenance { - sources: sources.to_vec(), - valid_until: prov.valid_until.clone(), - region: prov.region.clone(), - inline_sources_ignored: prov.inline_sources_ignored, - function_sources: Default::default(), - }; - let evidence_record = evidence_canonical_record(&prov_for_record, &refs); - - ProvenanceResolution { - refs, - applicability, - evidence_status, - diagnostics, - evidence_record, - } -} - -/// Canonical evidence inputs: extractor version, applicability, sorted source facts. -pub fn evidence_canonical_record(prov: &ModuleProvenance, refs: &[SourceRef]) -> String { - let mut parts = vec![ - format!("extractor={PROVENANCE_EXTRACTOR_VERSION}"), - format!("region={}", prov.region.as_deref().unwrap_or("")), - format!("valid_until={}", prov.valid_until.as_deref().unwrap_or("")), - ]; - let mut source_parts: Vec = refs - .iter() - .filter(|r| r.relation == "supports") - .map(|r| { - format!( - "{}#{}@{}", - r.uri, - r.locator.as_deref().unwrap_or(""), - r.content_digest - .as_ref() - .map(|d| d.0.as_str()) - .unwrap_or("none") - ) - }) - .collect(); - source_parts.sort(); - parts.extend(source_parts); - parts.join("|") -} - -/// Whether a Markdown heading / id matches the `#locator` fragment. -pub fn anchor_exists(content: &str, locator: &str) -> bool { - let loc = locator.trim().trim_start_matches('#').trim(); - if loc.is_empty() { - return true; - } - for line in content.lines() { - let t = line.trim(); - if let Some(rest) = t.strip_prefix('#') { - let heading = rest.trim_start_matches('#').trim(); - let heading = heading - .split('{') - .next() - .unwrap_or(heading) - .trim(); - if heading == loc || slugify_heading(heading) == loc { - return true; - } - } - if t.contains(&format!("id=\"{loc}\"")) - || t.contains(&format!("id='{loc}'")) - || t.contains(&format!("{{#{loc}}}")) - { - return true; - } - } - false -} - -fn slugify_heading(heading: &str) -> String { - let mut out = String::new(); - for ch in heading.chars() { - if ch.is_ascii_alphanumeric() { - out.push(ch.to_ascii_lowercase()); - } else if ch == ' ' || ch == '-' || ch == '_' { - if !out.ends_with('-') { - out.push('-'); - } - } else if !ch.is_ascii() { - // Keep non-ASCII letters (common in ZH docs) without lowercasing rules. - out.push(ch); - } - } - out.trim_matches('-').to_string() -} - -enum DateCheck { - Ok, - Invalid, -} - -fn validate_date(valid_until: &str) -> DateCheck { - let parts: Vec<&str> = valid_until.split('-').collect(); - if parts.len() != 3 { - return DateCheck::Invalid; - } - let Ok(y) = parts[0].parse::() else { - return DateCheck::Invalid; - }; - let Ok(m) = parts[1].parse::() else { - return DateCheck::Invalid; - }; - let Ok(d) = parts[2].parse::() else { - return DateCheck::Invalid; - }; - if !(1..=12).contains(&m) || !(1..=31).contains(&d) || y < 1970 { - return DateCheck::Invalid; - } - if parts[0].len() != 4 || parts[1].len() != 2 || parts[2].len() != 2 { - return DateCheck::Invalid; - } - DateCheck::Ok -} - -fn is_expired(valid_until: &str) -> bool { - let today = chrono_today(); - !valid_until.is_empty() && valid_until < today.as_str() -} - -/// Public recheck for handle.execute (M02). -pub fn valid_until_expired(valid_until: &str) -> bool { - matches!(validate_date(valid_until), DateCheck::Ok) && is_expired(valid_until) -} - -fn chrono_today() -> String { - use std::time::{SystemTime, UNIX_EPOCH}; - let secs = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs() as i64; - let days = secs.div_euclid(86_400); - let (y, m, d) = civil_from_days(days); - format!("{y:04}-{m:02}-{d:02}") -} - -/// Algorithm from Howard Hinnant (public domain). -fn civil_from_days(z: i64) -> (i32, u32, u32) { - let z = z + 719_468; - let era = if z >= 0 { z } else { z - 146_096 }.div_euclid(146_097); - let doe = (z - era * 146_097) as u64; - let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; - let y = (yoe as i64 + era * 400) as i32; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = if m <= 2 { y + 1 } else { y }; - (y, m as u32, d as u32) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_sources_and_valid_until() { - let src = "---\nsources:\n - ../corpus/tax.md#rate\napplicability:\n region: CN\n valid_until: 2099-12-31\n---\n\n# main\n"; - let p = parse_module_provenance(src); - assert_eq!(p.sources, vec!["../corpus/tax.md#rate"]); - assert_eq!(p.region.as_deref(), Some("CN")); - assert_eq!(p.valid_until.as_deref(), Some("2099-12-31")); - } - - #[test] - fn anchor_matches_heading() { - assert!(anchor_exists("# rate\n\nrate = 0.13\n", "rate")); - assert!(!anchor_exists("# rate\n\nrate = 0.13\n", "missing-anchor")); - } - - #[test] - fn invalid_date_rejected() { - assert!(matches!(validate_date("2099-12-31"), DateCheck::Ok)); - assert!(matches!(validate_date("not-a-date"), DateCheck::Invalid)); - assert!(matches!(validate_date("2099-13-01"), DateCheck::Invalid)); - } -} diff --git a/src/sema/resolution.rs b/src/sema/resolution.rs deleted file mode 100755 index 901b607..0000000 --- a/src/sema/resolution.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! Ordered declaration lookup, independent of the declaration representation. -use super::bind::{call_display, DynamicReason}; -use crate::{ast::CallExpr, diagnostics::Span, host::HostFn}; - -pub(crate) trait NameView { - type Function: Copy; - type Module: Clone; - fn roots(&self, module: &Self::Module) -> Vec; - fn children(&self, function: Self::Function) -> Vec; - fn parent(&self, module: &Self::Module, function: Self::Function) -> Option; - fn same(&self, left: Self::Function, right: Self::Function) -> bool; - fn name(&self, function: Self::Function) -> String; - fn level(&self, function: Self::Function) -> u8; - fn is_object(&self, function: Self::Function) -> bool; - fn uses_receiver(&self, function: Self::Function) -> bool; - fn import(&self, module: &Self::Module, name: &str) -> Option; - fn used_path(&self, module: &Self::Module, name: &str) -> Option>; -} -#[derive(Debug)] -pub enum Target { - Local(F), - Import { - bind: String, - lib: M, - fun: F, - path: Vec, - }, - Builtin(&'static str), - Host(HostFn), - Dynamic { - reason: DynamicReason, - name: String, - }, - Unresolved { - message: String, - span_hint: Option, - }, -} -fn ancestors( - view: &V, - nodes: Vec, - current: V::Function, - path: &mut Vec, -) -> bool { - for node in nodes { - if view.same(node, current) { - return true; - } - path.push(node); - if ancestors(view, view.children(node), current, path) { - return true; - } - path.pop(); - } - false -} -pub(crate) fn lookup( - view: &V, - module: &V::Module, - current: V::Function, - name: &str, -) -> Option { - let mut cursor = Some(current); - while let Some(node) = cursor { - if let Some(f) = view - .children(node) - .into_iter() - .find(|f| view.name(*f) == name) - { - return Some(f); - } - cursor = view.parent(module, node); - } - view.roots(module) - .into_iter() - .find(|f| view.name(*f) == name) -} -fn walk(view: &V, module: &V::Module, path: &[String]) -> Result { - let display = path.join("."); - let first = path.first().ok_or("empty knowledge path")?; - let mut node = view - .roots(module) - .into_iter() - .find(|f| view.name(*f) == *first) - .ok_or_else(|| format!("unknown `{display}`"))?; - let mut parent_is_object = false; - for segment in &path[1..] { - parent_is_object = view.is_object(node); - node = view - .children(node) - .into_iter() - .find(|f| view.name(*f) == *segment) - .ok_or_else(|| format!("unknown `{display}`"))?; - } - if parent_is_object && view.level(node) != 1 && view.uses_receiver(node) { - return Err(format!( - "`{display}` is an instance method; call it as `var`.{}", - view.name(node) - )); - } - Ok(node) -} -fn imported( - view: &V, - module: &V::Module, - path: &[String], -) -> Target { - let unresolved = |message| Target::Unresolved { - message, - span_hint: None, - }; - if path.len() < 2 { - return unresolved(format!( - "library path `{}`: need at least `lib.member`", - path.join(".") - )); - } - let bind = &path[0]; - let Some(lib) = view.import(module, bind) else { - return unresolved(format!( - "unknown library `{bind}` (import it in frontmatter)" - )); - }; - match walk(view, &lib, &path[1..]) { - Ok(fun) => Target::Import { - bind: bind.clone(), - lib, - fun, - path: path.to_vec(), - }, - Err(message) => unresolved(message), - } -} -pub(crate) fn resolve( - view: &V, - module: &V::Module, - current: V::Function, - call: &CallExpr, -) -> Target { - if call.receiver.is_some() { - return Target::Dynamic { - reason: DynamicReason::MethodReceiver, - name: call_display(call), - }; - } - if let Some(path) = &call.path { - if path - .first() - .is_some_and(|p| view.import(module, p).is_some()) - { - return imported(view, module, path); - } - if path.len() >= 2 { - return match walk(view, module, path) { - Ok(fun) => Target::Local(fun), - Err(_) if path.len() == 2 => Target::Dynamic { - reason: DynamicReason::MethodReceiver, - name: call_display(call), - }, - Err(message) => Target::Unresolved { - message, - span_hint: None, - }, - }; - } - return Target::Unresolved { - message: format!( - "library path `{}`: need at least `lib.member`", - path.join(".") - ), - span_hint: None, - }; - } - if let Some(path) = view.used_path(module, &call.callee) { - return imported(view, module, &path); - } - if crate::arguments::builtin_signature(&call.callee).is_some() { - if call.callee == "call_fn" { - return Target::Dynamic { - reason: DynamicReason::CallFn, - name: "call_fn".into(), - }; - } - let name = match call.callee.as_str() { - "print" => "print", - "input" => "input", - "len" => "len", - "str" => "str", - "int" => "int", - "type" => "type", - "trim" => "trim", - "split" => "split", - "join" => "join", - "at" => "at", - _ => unreachable!(), - }; - return Target::Builtin(name); - } - if let Some(host) = HostFn::from_name(&call.callee) { - return Target::Host(host); - } - if let Some(fun) = lookup(view, module, current, &call.callee) { - return Target::Local(fun); - } - Target::Dynamic { - reason: DynamicReason::Plugin, - name: call.callee.clone(), - } -} - -#[derive(Default)] -pub(crate) struct AstView<'a>(std::marker::PhantomData<&'a crate::ast::Module>); -impl<'a> NameView for AstView<'a> { - type Function = &'a crate::ast::Function; - type Module = &'a crate::ast::Module; - fn roots(&self, m: &Self::Module) -> Vec { - m.functions.iter().collect() - } - fn children(&self, f: Self::Function) -> Vec { - f.children.iter().collect() - } - fn parent(&self, m: &Self::Module, f: Self::Function) -> Option { - let mut path = Vec::new(); - if ancestors(self, self.roots(m), f, &mut path) { - path.last().copied() - } else { - None - } - } - fn same(&self, a: Self::Function, b: Self::Function) -> bool { - std::ptr::eq(a, b) - } - fn name(&self, f: Self::Function) -> String { - f.name.clone() - } - fn level(&self, f: Self::Function) -> u8 { - f.level - } - fn is_object(&self, f: Self::Function) -> bool { - f.is_object() - } - fn uses_receiver(&self, f: Self::Function) -> bool { - crate::ast::function_uses_receiver(f) - } - fn import(&self, m: &Self::Module, name: &str) -> Option { - m.import_modules.get(name) - } - fn used_path(&self, m: &Self::Module, name: &str) -> Option> { - m.uses - .iter() - .find(|u| u.bind == name) - .map(|u| u.path.clone()) - } -} diff --git a/src/sema/symbols.rs b/src/sema/symbols.rs deleted file mode 100755 index 75857fa..0000000 --- a/src/sema/symbols.rs +++ /dev/null @@ -1,498 +0,0 @@ -//! Stable module/symbol identity and deterministic project declaration index. - -use std::collections::BTreeMap; -use std::fmt; -use std::fs; -use std::path::{Path, PathBuf}; - -use anyhow::{bail, Context, Result}; - -use crate::ast::Function; -use crate::project::ProjectRoot; - -/// Project-local module identity. An explicit frontmatter `id` wins over the -/// normalized relative path, so authors can preserve identity across moves. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ModuleId(String); - -impl ModuleId { - pub fn as_str(&self) -> &str { - &self.0 - } -} - -impl fmt::Display for ModuleId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -/// Globally stable address inside a project compilation. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct SymbolId(String); - -impl SymbolId { - pub fn as_str(&self) -> &str { - &self.0 - } -} - -impl fmt::Display for SymbolId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub enum SymbolKind { - Type, - Function, -} - -impl SymbolKind { - pub fn as_str(self) -> &'static str { - match self { - Self::Type => "type", - Self::Function => "function", - } - } -} - -/// Callable classification is semantic metadata, separate from `SymbolKind`. -/// This keeps stable SymbolIds independent of whether a body later gains or -/// loses a receiver dependency. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub enum CallableKind { - FreeFunction, - AssociatedFunction, - InstanceMethod, -} - -impl CallableKind { - pub fn as_str(self) -> &'static str { - match self { - Self::FreeFunction => "free_function", - Self::AssociatedFunction => "associated_function", - Self::InstanceMethod => "instance_method", - } - } -} - -/// One source declaration, including a display path for human-facing tools. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SymbolDecl { - pub id: SymbolId, - pub module: ModuleId, - pub kind: SymbolKind, - /// Present only for functions; never inferred from the display name. - pub callable: Option, - pub name: String, - pub declaration_path: Vec, - pub source: PathBuf, - pub line: u32, -} - -/// Parsed module retained so `compile_project` does not re-parse (M-R5b). -#[derive(Debug, Clone)] -pub struct ParsedModule { - pub path: PathBuf, - pub text: String, - pub module: crate::ast::Module, -} - -/// Deterministic read-only view of all declarations in one project. -#[derive(Debug, Clone)] -pub struct ProjectIndex { - project_id: String, - root: ProjectRoot, - modules: BTreeMap, - /// path → module id (avoids linear scan per file in compile_project). - path_to_module: BTreeMap, - symbols: Vec, - by_id: BTreeMap, - by_name: BTreeMap>, - /// module → symbol indexes (avoids filtering the full symbol table per module). - symbols_by_module: BTreeMap>, - /// Shared parsed AST/text for the same input snapshot. - parsed: BTreeMap, -} - -impl ProjectIndex { - pub fn build(root: ProjectRoot) -> Result { - let files = root.source_files()?; - Self::from_files(root, files) - } - - /// Index exactly `files` (already chosen by the caller). Paths must sit under `root`. - pub fn from_files(root: ProjectRoot, files: Vec) -> Result { - let project_id = project_id(root.path()); - let mut modules = BTreeMap::new(); - let mut path_to_module = BTreeMap::new(); - let mut symbols = Vec::new(); - let mut parsed = BTreeMap::new(); - - for file in files { - let source = fs::read_to_string(&file) - .with_context(|| format!("read source {}", file.display()))?; - let module_id = module_id(&source, root.path(), &file)?; - if let Some(previous) = modules.insert(module_id.clone(), file.clone()) { - bail!( - "duplicate module id `{module_id}` in {} and {}", - previous.display(), - file.display() - ); - } - path_to_module.insert(file.clone(), module_id.clone()); - let mut module = crate::load::parse_source_auto(&source) - .with_context(|| format!("parse source {}", file.display()))?; - module.source.path = Some(file.clone()); - for function in &module.functions { - collect_symbols( - &project_id, - &module_id, - &file, - function, - None, - &mut Vec::new(), - &mut symbols, - )?; - } - parsed.insert( - module_id.clone(), - ParsedModule { - path: file, - text: source, - module, - }, - ); - } - - symbols.sort_by(|a, b| a.id.cmp(&b.id)); - let mut by_id = BTreeMap::new(); - let mut by_name: BTreeMap> = BTreeMap::new(); - let mut symbols_by_module: BTreeMap> = BTreeMap::new(); - for (index, symbol) in symbols.iter().enumerate() { - if by_id.insert(symbol.id.clone(), index).is_some() { - bail!("duplicate symbol id `{}`", symbol.id); - } - by_name.entry(symbol.name.clone()).or_default().push(index); - symbols_by_module - .entry(symbol.module.clone()) - .or_default() - .push(index); - } - for indexes in by_name.values_mut() { - indexes.sort_by(|a, b| symbols[*a].id.cmp(&symbols[*b].id)); - } - for indexes in symbols_by_module.values_mut() { - indexes.sort_by(|a, b| symbols[*a].id.cmp(&symbols[*b].id)); - } - - Ok(Self { - project_id, - root, - modules, - path_to_module, - symbols, - by_id, - by_name, - symbols_by_module, - parsed, - }) - } - - pub fn project_id(&self) -> &str { - &self.project_id - } - - pub fn root(&self) -> &ProjectRoot { - &self.root - } - - pub fn modules(&self) -> &BTreeMap { - &self.modules - } - - pub fn module_id_for_path(&self, path: &Path) -> Option<&ModuleId> { - self.path_to_module.get(path) - } - - pub fn symbols_in_module(&self, module_id: &ModuleId) -> Vec<&SymbolDecl> { - self.symbols_by_module - .get(module_id) - .map(|idxs| idxs.iter().map(|i| &self.symbols[*i]).collect()) - .unwrap_or_default() - } - - pub fn parsed_modules(&self) -> &BTreeMap { - &self.parsed - } - - pub fn symbols(&self) -> &[SymbolDecl] { - &self.symbols - } - - pub fn symbol(&self, id: &SymbolId) -> Option<&SymbolDecl> { - self.by_id.get(id).map(|index| &self.symbols[*index]) - } - - /// Candidates are deliberately returned as a list: discovery may be fuzzy, - /// but callers must report ambiguity instead of silently choosing one. - pub fn symbols_named(&self, name: &str) -> Vec<&SymbolDecl> { - self.by_name - .get(name) - .into_iter() - .flatten() - .map(|index| &self.symbols[*index]) - .collect() - } -} - -fn collect_symbols( - project_id: &str, - module_id: &ModuleId, - source: &Path, - function: &Function, - parent: Option<&Function>, - parent_path: &mut Vec, - out: &mut Vec, -) -> Result<()> { - let kind = if function.is_object() { - SymbolKind::Type - } else { - SymbolKind::Function - }; - let callable = if function.is_object() { - None - } else if parent.is_some_and(Function::is_object) { - Some(if crate::ast::function_uses_receiver(function) { - CallableKind::InstanceMethod - } else { - CallableKind::AssociatedFunction - }) - } else { - Some(CallableKind::FreeFunction) - }; - parent_path.push(function.name.clone()); - let id = symbol_id(project_id, module_id, kind, parent_path); - if out.iter().any(|existing| existing.id == id) { - bail!( - "duplicate declaration path `{}` in module `{module_id}`", - parent_path.join("/") - ); - } - out.push(SymbolDecl { - id, - module: module_id.clone(), - kind, - callable, - name: function.name.clone(), - declaration_path: parent_path.clone(), - source: source.to_path_buf(), - line: function.span.line, - }); - for child in &function.children { - collect_symbols( - project_id, - module_id, - source, - child, - Some(function), - parent_path, - out, - )?; - } - parent_path.pop(); - Ok(()) -} - -fn module_id(source: &str, root: &Path, file: &Path) -> Result { - if let Some(id) = frontmatter_value(source, "id") { - if id.is_empty() { - bail!("empty frontmatter id in {}", file.display()); - } - return Ok(ModuleId(id)); - } - let rel = file.strip_prefix(root).with_context(|| { - format!( - "source {} outside project root {}", - file.display(), - root.display() - ) - })?; - let mut value = rel.to_string_lossy().replace('\\', "/"); - value.truncate(value.len().saturating_sub(".mq.md".len())); - Ok(ModuleId(value)) -} - -fn project_id(root: &Path) -> String { - frontmatter_project_id(root).unwrap_or_else(|| { - root.file_name() - .and_then(|name| name.to_str()) - .filter(|name| !name.is_empty()) - .unwrap_or("marqdo-project") - .to_string() - }) -} - -fn frontmatter_project_id(root: &Path) -> Option { - let path = root.join(".marqdo").join("project.toml"); - let source = fs::read_to_string(path).ok()?; - source.lines().find_map(|line| { - let line = line.trim(); - let value = line - .strip_prefix("id=") - .or_else(|| line.strip_prefix("id ="))?; - let value = value.trim().trim_matches('"'); - (!value.is_empty()).then(|| value.to_string()) - }) -} - -fn frontmatter_value(source: &str, key: &str) -> Option { - let source = source.strip_prefix('\u{feff}').unwrap_or(source); - let mut lines = source.lines(); - if lines.next().map(str::trim) != Some("---") { - return None; - } - let key = format!("{key}:"); - for line in lines { - let line = line.trim(); - if line == "---" { - break; - } - if let Some(value) = line.strip_prefix(&key) { - return Some(value.trim().trim_matches('"').to_string()); - } - } - None -} - -fn symbol_id( - project_id: &str, - module_id: &ModuleId, - kind: SymbolKind, - declaration_path: &[String], -) -> SymbolId { - let path = declaration_path - .iter() - .map(|segment| percent_encode(segment)) - .collect::>() - .join("/"); - SymbolId(format!( - "mq://{}/{}/{}{}", - percent_encode(project_id), - percent_encode(module_id.as_str()), - kind.as_str(), - if path.is_empty() { - String::new() - } else { - format!("/{path}") - } - )) -} - -fn percent_encode(value: &str) -> String { - let mut out = String::new(); - for byte in value.bytes() { - match byte { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => out.push(byte as char), - _ => out.push_str(&format!("%{byte:02X}")), - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn fixture_root(name: &str) -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let root = std::env::temp_dir().join(format!("marqdo-sema-{name}-{nanos}")); - fs::create_dir_all(&root).unwrap(); - root - } - - #[test] - fn index_uses_explicit_module_id_and_stable_declaration_paths() { - let root = fixture_root("ids"); - let source = r#"--- -id: knowledge.policy ---- -# 书店政策 - -## 金卡折扣 - -*0.90* -"#; - fs::write(root.join("policy.mq.md"), source).unwrap(); - - let index = ProjectIndex::build(ProjectRoot::new(&root).unwrap()).unwrap(); - assert_eq!(index.modules().len(), 1); - assert_eq!(index.symbols().len(), 2); - assert!(index.symbols()[0].id.as_str().starts_with(&format!( - "mq://{}/knowledge.policy/function/", - index.project_id() - ))); - assert!(index.symbols()[0].id.as_str().ends_with( - "%E4%B9%A6%E5%BA%97%E6%94%BF%E7%AD%96/%E9%87%91%E5%8D%A1%E6%8A%98%E6%89%A3" - )); - assert_eq!(index.symbols()[1].declaration_path, ["书店政策"]); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn duplicate_module_ids_are_rejected() { - let root = fixture_root("duplicate-module"); - fs::write(root.join("a.mq.md"), "---\nid: duplicate\n---\n# a").unwrap(); - fs::write(root.join("b.mq.md"), "---\nid: duplicate\n---\n# b").unwrap(); - - let err = ProjectIndex::build(ProjectRoot::new(&root).unwrap()) - .unwrap_err() - .to_string(); - assert!(err.contains("duplicate module id `duplicate`")); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn symbols_named_remains_ambiguous_by_design() { - let root = fixture_root("ambiguous"); - fs::write(root.join("a.mq.md"), "# A\n\n## 查询\n\n*1*").unwrap(); - fs::write(root.join("b.mq.md"), "# B\n\n## 查询\n\n*2*").unwrap(); - - let index = ProjectIndex::build(ProjectRoot::new(&root).unwrap()).unwrap(); - assert_eq!(index.symbols_named("查询").len(), 2); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn percent_encoding_preserves_unicode_boundaries() { - assert_eq!( - percent_encode("李白/出生 年份"), - "%E6%9D%8E%E7%99%BD%2F%E5%87%BA%E7%94%9F%20%E5%B9%B4%E4%BB%BD" - ); - } - - #[test] - fn object_children_are_classified_without_changing_their_symbol_identity() { - let root = fixture_root("callable-kind"); - fs::write( - root.join("facts.mq.md"), - "# 李白\n\n## 出生年份\n\n*701*\n\n## 名称\n\n*`self`*", - ) - .unwrap(); - - let index = ProjectIndex::build(ProjectRoot::new(&root).unwrap()).unwrap(); - let fact = index.symbols_named("出生年份").pop().unwrap(); - let method = index.symbols_named("名称").pop().unwrap(); - assert_eq!(fact.kind, SymbolKind::Function); - assert_eq!(fact.callable, Some(CallableKind::AssociatedFunction)); - assert_eq!(method.callable, Some(CallableKind::InstanceMethod)); - assert!(fact.id.as_str().contains("/function/")); - fs::remove_dir_all(root).unwrap(); - } -} diff --git a/src/source_map_tests.rs b/src/source_map_tests.rs deleted file mode 100755 index 252f634..0000000 --- a/src/source_map_tests.rs +++ /dev/null @@ -1,581 +0,0 @@ -use crate::diagnostics::{Diagnostic, Span}; -use crate::{ - bytecode::{compile_module, Vm}, - interp::Interpreter, - load::load_module, - value::Value, -}; -use serde_json::json; -use sha2::{Digest, Sha256}; -use std::path::{Path, PathBuf}; - -fn digest(text: &str) -> String { - format!("{:x}", Sha256::digest(text.as_bytes())) -} -fn line(text: &str, marker: &str) -> u32 { - text.lines() - .position(|s| s.contains(marker)) - .expect("oracle marker") as u32 - + 1 -} -fn root(label: &str) -> PathBuf { - // Scratch belongs to the build target dir; honor CARGO_TARGET_DIR when set. - let base = std::env::var_os("CARGO_TARGET_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); - let dir = base - .join("source-map") - .join(format!("{label}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir -} -fn save(path: &Path, text: &str) { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, text).unwrap(); -} -fn source(key: &str, path: &Path, text: &str) -> serde_json::Value { - json!({"key":key,"path":path,"text":text,"virtual":!path.is_absolute()}) -} -fn site(key: &str, marker: &str) -> serde_json::Value { - json!({"source":key,"marker":marker}) -} -fn frame( - name: &str, - declaration: serde_json::Value, - call_site: Option, -) -> serde_json::Value { - json!({"function":name,"declaration":declaration,"call_site":call_site}) -} -fn record( - id: &str, - backend: &str, - diagnostic: &Diagnostic, - sources: Vec, - origin: serde_json::Value, - frames: Vec, -) { - if let Some(directory) = std::env::var_os("MARQDO_SOURCE_MAP_DIR") { - let directory = PathBuf::from(directory); - std::fs::create_dir_all(&directory).unwrap(); - std::fs::write( - directory.join(format!("{id}-{backend}.json")), - serde_json::to_vec_pretty( - &json!({"version":1,"id":id,"backend":backend,"sources":sources, - "expected":{"origin":origin,"frames":frames},"diagnostic":diagnostic.to_json()}), - ) - .unwrap(), - ) - .unwrap(); - } -} -fn assert_site(site: &crate::diagnostics::SourceLocation, path: &Path, text: &str, expected: u32) { - assert_eq!( - site.source.path.as_deref().unwrap().canonicalize().unwrap(), - path.canonicalize().unwrap() - ); - assert_eq!(site.source.sha256.as_deref(), Some(digest(text).as_str())); - assert_eq!(site.span, Span::new(expected, 1)); -} -fn assert_origin(d: &Diagnostic, path: &Path, text: &str, expected: u32) { - assert_eq!( - d.path.as_deref().unwrap().canonicalize().unwrap(), - path.canonicalize().unwrap() - ); - assert_eq!(d.source_sha256.as_deref(), Some(digest(text).as_str())); - assert_eq!(d.span, Span::new(expected, 1)); - assert!(d.message.contains("division by zero"), "{d}"); - assert_eq!(d.to_json()["source_sha256"], json!(digest(text))); -} - -#[test] -fn external_argument_binding_uses_target_declaration_source() { - let dir = root("external-binding"); - let entry = dir.join("entry.mq.md"); - let target = dir.join("target.mq.md"); - let leaf = dir.join("leaf.mq.md"); - let main = "# main\n*7*\n"; - let text = "---\nimport:\n leaf: leaf.mq.md\n---\n\n\n## required\n + `x`\n*x*\n\n## defaulted\n + `x`=> leaf.explode\n*x*\n"; - let leaf_text = "\n\n\n## explode\n**bad = 1 / 0**\n*bad*\n"; - save(&entry, main); - save(&target, text); - save(&leaf, leaf_text); - let module = load_module(&target).unwrap(); - let mut tree = Interpreter::with_capture(Some(&entry), false); - let before = tree.diagnostic_scope_state(); - for name in ["required", "defaulted"] { - let fun = module.functions.iter().find(|f| f.name == name).unwrap(); - let error = tree.bind_external_args(&module, fun, &[]).unwrap_err(); - let d = Diagnostic::find(&error).unwrap(); - assert_eq!(tree.diagnostic_scope_state(), before); - let expected_frames = if name == "required" { - assert_eq!(d.code, "call.missing_arg"); - assert_eq!(d.path.as_deref(), Some(target.as_path())); - assert_eq!(d.source_sha256.as_deref(), Some(digest(text).as_str())); - assert_eq!(d.span, fun.span); - vec![frame("required", site("target", "## required"), None)] - } else { - assert_origin(d, &leaf, leaf_text, line(leaf_text, "**bad")); - vec![ - frame("defaulted", site("target", "## defaulted"), None), - frame( - "explode", - site("leaf", "## explode"), - Some(site("target", "+ `x`=> leaf.explode")), - ), - ] - }; - record( - &format!("external-binding-{name}"), - "tree", - d, - vec![ - source("entry", &entry, main), - source("target", &target, text), - source("leaf", &leaf, leaf_text), - ], - if name == "required" { - site("target", "## required") - } else { - site("leaf", "**bad") - }, - expected_frames, - ); - let first = d.to_json(); - let bound = tree - .bind_external_args(&module, fun, &[("x".into(), Value::Int(7))]) - .unwrap(); - assert_eq!(bound, vec![("x".into(), Value::Int(7))]); - assert_eq!(tree.diagnostic_scope_state(), before); - let again = tree.bind_external_args(&module, fun, &[]).unwrap_err(); - assert_eq!(Diagnostic::find(&again).unwrap().to_json(), first); - assert_eq!(tree.diagnostic_scope_state(), before); - } -} - -#[test] -fn imported_source_identity_frames_and_reuse_match_on_both_backends() { - let root = root("imports"); - let mut count = 0; - for pad in [0, 4, 17] { - for crlf in [false, true] { - for side in ["left", "right"] { - let dir = root.join(format!("{pad}-{crlf}-{side}")); - let basename = if pad == 17 { - "共同源.mq.md" - } else { - "shared.mq.md" - }; - let left = dir.join("left").join(basename); - let right = dir.join("right").join(basename); - let middle = dir.join("middle.mq.md"); - let entry = dir.join("entry.mq.md"); - let lf = |s: String| if crlf { s.replace('\n', "\r\n") } else { s }; - let leaf_a = lf(format!( - "源位置验证 🧪\n{}## explode\n**bad = 1 / 0**\n*bad*\n\n## good\n*7*\n", - "\n".repeat(pad) - )); - let leaf_b = if pad == 4 { - leaf_a.clone() - } else { - lf(format!( - "{}## explode\n\n**bad = 1 / 0**\n*bad*\n\n## good\n*7*\n", - "\n".repeat(pad + 3) - )) - }; - save(&left, &leaf_a); - save(&right, &leaf_b); - let mid=lf(format!("---\nmarkup: occlusion\nimport:\n leaf: {side}/{basename}\n---\n## relay\n**answer = > leaf.explode**\n*answer*\n")); - let main=lf("---\nmarkup: occlusion\nimport:\n mid: middle.mq.md\n---\n# main\n**answer = > mid.relay**\n*answer*\n".into()); - save(&middle, &mid); - save(&entry, &main); - let module = load_module(&entry).unwrap(); - let (leaf_path, leaf) = if side == "left" { - (&left, &leaf_a) - } else { - (&right, &leaf_b) - }; - let leaf_module = &module.import_modules["mid"].import_modules["leaf"]; - let program = compile_module(Some(&entry), &module).unwrap(); - // Dependencies are private, so API calls compile that module - // directly rather than assuming transitive re-exports. - let good_code = - crate::bytecode::compile_for_call(Some(leaf_path), leaf_module).unwrap(); - let good_fid = good_code.path_index[&vec!["good".into()]]; - for backend in ["tree", "bytecode"] { - let host = || { - let mut h = - crate::host::HostContext::for_capture(Some(&entry), Default::default()); - h.call_stack.push("outside-source-entry".into()); - h.call_site_lines.push(99); - h - }; - let mut tree = Interpreter::with_capture(Some(&entry), false).with_host(host()); - let mut vm = Vm::with_capture(Some(&entry)).with_host(host()); - let before_tree = tree.diagnostic_scope_state(); - let before_vm = vm.diagnostic_scope_state(); - let err = if backend == "tree" { - tree.run_module(&module) - } else { - vm.run(&program) - } - .unwrap_err(); - let diagnostic = Diagnostic::find(&err).unwrap(); - assert_origin(diagnostic, leaf_path, leaf, line(leaf, "**bad")); - assert_eq!(diagnostic.frames.len(), 3); - assert_eq!( - diagnostic - .frames - .iter() - .map(|f| f.function.as_str()) - .collect::>(), - ["main", "relay", "explode"] - ); - assert!(diagnostic.frames[0].call_site.is_none()); - assert_site( - diagnostic.frames[1].call_site.as_ref().unwrap(), - &entry, - &main, - line(&main, "**answer"), - ); - assert_site( - diagnostic.frames[2].call_site.as_ref().unwrap(), - &middle, - &mid, - line(&mid, "**answer"), - ); - assert_site( - &diagnostic.frames[2].declaration, - leaf_path, - leaf, - line(leaf, "## explode"), - ); - assert_eq!(tree.diagnostic_scope_state(), before_tree); - assert_eq!(vm.diagnostic_scope_state(), before_vm); - record( - &format!("imports-{pad}-{crlf}-{side}"), - backend, - diagnostic, - vec![ - source("entry", &entry, &main), - source("middle", &middle, &mid), - source("leaf", leaf_path, leaf), - ], - site("leaf", "**bad"), - vec![ - frame("main", site("entry", "# main"), None), - frame( - "relay", - site("middle", "## relay"), - Some(site("entry", "**answer")), - ), - frame( - "explode", - site("leaf", "## explode"), - Some(site("middle", "**answer")), - ), - ], - ); - let expected = diagnostic.to_json(); - let good = if backend == "tree" { - tree.invoke_function(leaf_module, "good", &[]) - } else { - vm.call_function(&good_code, good_fid, &[]) - } - .unwrap(); - assert_eq!(good, Value::Int(7)); - let again = if backend == "tree" { - tree.run_module(&module) - } else { - vm.run(&program) - } - .unwrap_err(); - assert_eq!( - Diagnostic::find(&again).unwrap().to_json(), - expected, - "stale caller leaked after reuse" - ); - assert_eq!(tree.diagnostic_scope_state(), before_tree); - assert_eq!(vm.diagnostic_scope_state(), before_vm); - count += 1; - } - } - } - } - println!( - "SOURCE_MAP_METRIC:{}", - json!({"kind":"imports","cases":count,"correct":true}) - ); -} - -#[test] -fn source_revision_is_loaded_text_not_later_disk_contents() { - let root = root("revision"); - let lib = root.join("shared.mq.md"); - let entry = root.join("entry.mq.md"); - let first = "## explode\n**bad = 1 / 0**\n*bad*\n"; - let second = "\n\n\n\n\n## explode\n**bad = 1 / 0**\n*bad*\n"; - let main="---\nmarkup: occlusion\nimport:\n lib: shared.mq.md\n---\n# main\n**answer = > lib.explode**\n*answer*\n"; - save(&entry, main); - save(&lib, first); - let old = load_module(&entry).unwrap(); - let old_code = compile_module(Some(&entry), &old).unwrap(); - save(&lib, second); - let new = load_module(&entry).unwrap(); - let new_code = compile_module(Some(&entry), &new).unwrap(); - for (revision, module, code, text) in [ - ("old", &old, &old_code, first), - ("new", &new, &new_code, second), - ] { - let mut tree = Interpreter::with_capture(Some(&entry), false); - let mut vm = Vm::with_capture(Some(&entry)); - for (backend, error) in [ - ("tree", tree.run_module(module).unwrap_err()), - ("bytecode", vm.run(code).unwrap_err()), - ] { - let d = Diagnostic::find(&error).unwrap(); - assert_origin(d, &lib, text, line(text, "**bad")); - assert_site( - d.frames[1].call_site.as_ref().unwrap(), - &entry, - main, - line(main, "**answer"), - ); - record( - &format!("revision-{revision}"), - backend, - d, - vec![source("entry", &entry, main), source("leaf", &lib, text)], - site("leaf", "**bad"), - vec![ - frame("main", site("entry", "# main"), None), - frame( - "explode", - site("leaf", "## explode"), - Some(site("entry", "**answer")), - ), - ], - ); - } - } -} - -#[test] -#[cfg(feature = "exec-host")] -fn foreign_boundary_diagnostics_keep_library_origin_and_real_user_call_site() { - let root = root("foreign"); - let lib = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib/foreign.mq.md"); - let library = std::fs::read_to_string(&lib).unwrap(); - let mut count = 0; - for lang in ["python", "node"] { - for output in [false, true] { - let entry = root.join(format!("{lang}-{output}.mq.md")); - let action = if output { - "**> foreign.session_eval id=`s` source=\"n = 99; 9007199254740992\"**" - } else { - "**> foreign.session_set id=`s` name=\"n\" value=`s`**" - }; - let main=format!("---\nmarkup: occlusion\nimport:\n foreign: {}\n---\n# main\n**s = > foreign.session_open lang=\"{lang}\"**\n**> foreign.session_set id=`s` name=\"n\" value=1**\n{action}\n",lib.display()); - save(&entry, &main); - let module = load_module(&entry).unwrap(); - let program = compile_module(Some(&entry), &module).unwrap(); - let expected_function = if output { - "session_eval" - } else { - "session_set" - }; - let expected_primitive = if output { - "host_foreign_session_eval" - } else { - "host_foreign_session_set" - }; - for backend in ["tree", "bytecode"] { - let mut tree = Interpreter::with_capture(Some(&entry), false); - let mut vm = Vm::with_capture(Some(&entry)); - let error = if backend == "tree" { - tree.run_module(&module) - } else { - vm.run(&program) - } - .unwrap_err(); - let d = Diagnostic::find(&error).unwrap(); - assert!(d.message.contains("outside V_safe")); - assert_eq!( - d.path.as_ref().unwrap().canonicalize().unwrap(), - lib.canonicalize().unwrap() - ); - assert_eq!(d.source_sha256, Some(digest(&library))); - assert_eq!(d.span.line, line(&library, expected_primitive)); - let last_frame = d.frames.last().unwrap(); - assert_eq!(last_frame.function, expected_function); - assert_site( - last_frame.call_site.as_ref().unwrap(), - &entry, - &main, - line(&main, action), - ); - assert!(d.format_message().contains(&format!( - "{}:{}:1", - entry.display(), - line(&main, action) - ))); - let (_, values, _) = if backend == "tree" { - tree.foreign_source_evidence() - } else { - vm.foreign_source_evidence() - }; - assert_eq!(values, vec![Value::Int(if output { 99 } else { 1 })]); - record( - &format!("foreign-{lang}-{output}"), - backend, - d, - vec![ - source("entry", &entry, &main), - source("foreign", &lib, &library), - ], - site("foreign", expected_primitive), - vec![ - frame("main", site("entry", "# main"), None), - frame( - expected_function, - site("foreign", &format!("## {expected_function}")), - Some(site("entry", action)), - ), - ], - ); - count += 1; - } - } - } - println!( - "SOURCE_MAP_METRIC:{}", - json!({"kind":"foreign","cases":count,"correct":true}) - ); -} - -#[test] -fn memory_dynamic_and_method_calls_keep_their_own_sources() { - let directory = root("entry-kinds"); - let memory="---\nmarkup: occlusion\nimport:\n json: lib/json.mq.md\n---\n# main\n**bad = > json.parse text=not-json**\n"; - let module = crate::load::load_module_from_source(memory).unwrap(); - let json_text = crate::embedded_lib::read_file("json.mq.md").unwrap(); - let code = compile_module(None, &module).unwrap(); - let dynamic="# main\n**name = \"explode\"**\n> call_fn name=`name`\n\n## explode\n**bad = 1 / 0**\n*bad*\n"; - let dynamic_path = directory.join("dynamic.mq.md"); - save(&dynamic_path, dynamic); - let dynamic_module = load_module(&dynamic_path).unwrap(); - let dynamic_code = compile_module(Some(&dynamic_path), &dynamic_module).unwrap(); - let object_path = directory.join("object.mq.md"); - let json_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib/json.mq.md"); - let object=format!("---\nmarkup: occlusion\nimport:\n json: {}\n---\n# Counter\n**state = > json.parse text={{\"n\":1}}**\n*state*\n\n## fail\n**saved = `self`**\n**bad = 1 / 0**\n*bad*\n",json_path.display()); - save(&object_path, &object); - let entry_path = directory.join("method.mq.md"); - let method="---\nmarkup: occlusion\nimport:\n obj: object.mq.md\n---\n# main\n**c = > obj.Counter**\n> `c`.fail\n"; - save(&entry_path, method); - let method_module = load_module(&entry_path).unwrap(); - let method_code = compile_module(Some(&entry_path), &method_module).unwrap(); - for backend in ["tree", "bytecode"] { - let error = if backend == "tree" { - Interpreter::with_capture(None, false).run_module(&module) - } else { - Vm::with_capture(None).run(&code) - } - .unwrap_err(); - let d = Diagnostic::find(&error).unwrap(); - assert_eq!(d.path.as_deref(), Some(Path::new("lib/json.mq.md"))); - assert_eq!(d.source_sha256, Some(digest(&json_text))); - assert_eq!(d.span.line, line(&json_text, "host_json_parse")); - assert_eq!( - d.frames - .last() - .unwrap() - .call_site - .as_ref() - .unwrap() - .source - .path - .as_deref(), - Some(Path::new("")) - ); - record( - "memory", - backend, - d, - vec![ - source("entry", Path::new(""), memory), - source("json", Path::new("lib/json.mq.md"), &json_text), - ], - site("json", "host_json_parse"), - vec![ - frame("main", site("entry", "# main"), None), - frame( - "parse", - site("json", "## parse"), - Some(site("entry", "**bad")), - ), - ], - ); - let error = if backend == "tree" { - Interpreter::with_capture(Some(&dynamic_path), false).run_module(&dynamic_module) - } else { - Vm::with_capture(Some(&dynamic_path)).run(&dynamic_code) - } - .unwrap_err(); - let d = Diagnostic::find(&error).unwrap(); - assert_origin(d, &dynamic_path, dynamic, line(dynamic, "**bad")); - assert_eq!(d.frames.last().unwrap().function, "explode"); - assert_site( - d.frames.last().unwrap().call_site.as_ref().unwrap(), - &dynamic_path, - dynamic, - line(dynamic, "> call_fn"), - ); - record( - "dynamic", - backend, - d, - vec![source("entry", &dynamic_path, dynamic)], - site("entry", "**bad"), - vec![ - frame("main", site("entry", "# main"), None), - frame( - "explode", - site("entry", "## explode"), - Some(site("entry", "> call_fn")), - ), - ], - ); - let error = if backend == "tree" { - Interpreter::with_capture(Some(&entry_path), false).run_module(&method_module) - } else { - Vm::with_capture(Some(&entry_path)).run(&method_code) - } - .unwrap_err(); - let d = Diagnostic::find(&error).unwrap(); - assert_origin(d, &object_path, &object, line(&object, "**bad")); - assert_eq!(d.frames.last().unwrap().function, "fail"); - assert_site( - d.frames.last().unwrap().call_site.as_ref().unwrap(), - &entry_path, - method, - line(method, "> `c`.fail"), - ); - record( - "method", - backend, - d, - vec![ - source("entry", &entry_path, method), - source("object", &object_path, &object), - ], - site("object", "**bad"), - vec![ - frame("main", site("entry", "# main"), None), - frame( - "fail", - site("object", "## fail"), - Some(site("entry", "> `c`.fail")), - ), - ], - ); - } -} diff --git a/src/source_refinement_tests.rs b/src/source_refinement_tests.rs deleted file mode 100755 index 1408001..0000000 --- a/src/source_refinement_tests.rs +++ /dev/null @@ -1,452 +0,0 @@ -//! Export the actual loaded AST and independently observe both real backends. -//! Unsupported AST constructs are errors, never omitted or normalized to no-op. -use crate::ast::{Arg, BinaryOp, CallExpr, Expr, Function, Literal, Module, Stmt}; -use crate::host::{foreign_session, json::value_to_json, HostContext}; -use crate::value::Value; -use serde_json::{json, Value as Json}; -use sha2::{Digest, Sha256}; -use std::path::PathBuf; - -pub(crate) fn boundary_evidence( - ctx: &mut HostContext, -) -> (Vec, Vec, Vec) { - let observations = ctx.oracle_observations.clone(); - let protocol = ctx.foreign_protocol_steps.clone(); - let mut ids = ctx.foreign_sessions.keys().cloned().collect::>(); - ids.sort(); - // These verification reads bypass the document observation API. They occur - // only after its journal was captured, and never alter that journal. - let values = ids - .iter() - .map(|id| { - foreign_session::get(ctx, &Value::Handle(id.clone()), &Value::Text("n".into())).unwrap() - }) - .collect(); - assert_eq!(observations, ctx.oracle_observations); - (observations, values, protocol) -} - -fn expr(e: &Expr) -> Result { - Ok(match e { - Expr::Literal(Literal::None) => json!(["literal", null]), - Expr::Literal(Literal::Bool(b)) => json!(["literal", b]), - Expr::Literal(Literal::Int(n)) => json!(["literal", n]), - Expr::Literal(Literal::Text(s)) => json!(["literal", s]), - Expr::Var(name) => json!(["var", name]), - Expr::Binary { op, left, right } => { - let tag = match op { - BinaryOp::Add => "add", - BinaryOp::Sub => "sub", - BinaryOp::Lt => "lt", - _ => return Err(format!("unsupported source binary op {op:?}")), - }; - json!([tag, expr(left)?, expr(right)?]) - } - _ => return Err(format!("unsupported source expression {e:?}")), - }) -} - -fn call(c: &CallExpr, dest: Option<&str>, defs: &[&Function]) -> Result { - if c.receiver.is_some() || !c.pre_modifiers.is_empty() { - return Err("unsupported receiver/modifiers".into()); - } - if let Some(path) = &c.path { - if path.len() != 2 || path[0] != "foreign" { - return Err(format!("unsupported library path {path:?}")); - } - let mut args = std::collections::BTreeMap::new(); - for a in &c.args { - let Arg::Named { name, value } = a else { - return Err("foreign primitive needs named arguments".into()); - }; - if args.insert(name.as_str(), value).is_some() { - return Err("duplicate argument".into()); - } - } - let allowed: &[&str] = match path[1].as_str() { - "session_open" => &["lang"], - "session_set" => &["id", "name", "value"], - "session_get" => &["id", "name"], - "session_eval" => &["id", "source", "input", "stdin"], - "session_close" => &["id"], - _ => return Err(format!("unsupported primitive {path:?}")), - }; - if args.keys().any(|k| !allowed.contains(k)) { - return Err("unsupported primitive option".into()); - } - let arg = |name: &str| { - args.get(name) - .copied() - .ok_or_else(|| format!("missing {name}")) - }; - let name = || match arg("name")? { - Expr::Literal(Literal::Text(s)) => Ok(s.clone()), - _ => Err("dynamic binding name unsupported".to_string()), - }; - match path[1].as_str() { - "session_open" => Ok(json!([ - "open", - dest.ok_or("open destination required")?, - expr(arg("lang")?)? - ])), - "session_get" => Ok(json!([ - "get", - dest.ok_or("get destination required")?, - expr(arg("id")?)?, - name()? - ])), - _ if dest.is_some() => { - Err("assigned set/eval/close record requires a richer adapter".into()) - } - "session_set" => Ok(json!([ - "set", - expr(arg("id")?)?, - name()?, - expr(arg("value")?)? - ])), - "session_eval" => Ok(json!([ - "eval", - expr(arg("id")?)?, - expr(arg("source")?)?, - args.get("input") - .map(|v| expr(v)) - .transpose()? - .unwrap_or(json!(["literal", null])), - args.get("stdin").map(|v| expr(v)).transpose()? - ])), - "session_close" => Ok(json!(["close", expr(arg("id")?)?])), - _ => unreachable!(), - } - } else { - let f = defs - .iter() - .find(|f| f.name == c.callee) - .ok_or_else(|| format!("unknown function {}", c.callee))?; - let mut values = std::collections::BTreeMap::new(); - let mut positional = 0; - for a in &c.args { - let (name, value) = match a { - Arg::Named { name, value } => (name.as_str(), value), - Arg::Positional(value) => { - let p = f.params.get(positional).ok_or("too many arguments")?; - positional += 1; - (p.name.as_str(), value) - } - }; - if !f.params.iter().any(|p| p.name == name) || values.insert(name, value).is_some() { - return Err("invalid call argument".into()); - } - } - let ordered = f - .params - .iter() - .map(|p| expr(values.get(p.name.as_str()).ok_or("missing parameter")?)) - .collect::, _>>()?; - Ok(json!(["call", dest, c.callee, ordered])) - } -} - -fn block(body: &[Stmt], defs: &[&Function]) -> Result, String> { - body.iter() - .map(|s| { - Ok(match s { - Stmt::Assign { - name, - value: Expr::Call(c), - .. - } => call(c, Some(name), defs)?, - Stmt::Assign { name, value, .. } => json!(["assign", name, expr(value)?]), - Stmt::Return { value, .. } => json!(["return", expr(value)?]), - Stmt::Call { call: c, .. } => call(c, None, defs)?, - Stmt::While { - condition, body, .. - } => json!(["while", expr(condition)?, block(body, defs)?]), - Stmt::Branch { arms, .. } => { - let mut rest = Vec::new(); - for (i, arm) in arms.iter().enumerate().rev() { - let body = block(&arm.body, defs)?; - if let Some(condition) = &arm.condition { - rest = vec![json!(["if", expr(condition)?, body, rest])]; - } else { - if i != arms.len() - 1 { - return Err("nonterminal else".into()); - } - rest = body; - } - } - if rest.len() != 1 || rest[0][0] != "if" { - return Err("branch needs condition".into()); - } - rest.pop().unwrap() - } - _ => return Err(format!("unsupported source statement {s:?}")), - }) - }) - .collect() -} - -fn source_ir(module: &Module) -> Result { - if module.functions.len() != 1 || !module.uses.is_empty() { - return Err("module needs the declared single-entry adapter".into()); - } - let main = module - .functions - .iter() - .find(|f| f.name == "main") - .ok_or("missing main")?; - let defs = main.children.iter().collect::>(); - if !main.params.is_empty() { - return Err("entry parameters need an explicit environment adapter".into()); - } - let mut seen = std::collections::HashSet::new(); - for f in &defs { - if !seen.insert(&f.name) - || !f.children.is_empty() - || f.params.iter().any(|p| p.default.is_some()) - { - return Err("unsupported function scope/default".into()); - } - } - let functions = defs.iter().map(|f| Ok(json!({"name":f.name,"params":f.params.iter().map(|p|p.name.clone()).collect::>(),"body":block(&f.body,&defs)?}))).collect::,String>>()?; - let initial = module - .metadata - .iter() - .map(|(name, value)| { - if !matches!( - value, - Value::None | Value::Bool(_) | Value::Int(_) | Value::Text(_) - ) { - return Err("non-scalar metadata needs an explicit initial-value adapter".into()); - } - Ok(json!([name, value_to_json(value)?])) - }) - .collect::, String>>()?; - Ok(json!({"initial":initial,"entry":block(&main.body,&defs)?,"functions":functions})) -} - -fn source(lang: &str, seed: i64, rounds: usize, scenario: &str) -> String { - let increment = "n += 1; n"; - let bad = "n = 99; 9007199254740992"; - let stdin = if scenario == "explicit_empty_stdin" { - " stdin=\"\"" - } else { - "" - }; - let condition = if scenario == "else_branch" { - seed - 1 - } else { - seed + 1 - }; - let function = match scenario { - "recursive" => "advance_rec", - "early_return" => "early", - _ => "adjust", - }; - let failure = match scenario { - "closed_get" => "**> foreign.session_close id=`alias`**\n**lost = > foreign.session_get id=`alias` name=\"n\"**".into(), - "copy_handle" => "**> foreign.session_set id=`a` name=\"n\" value=`b`**".into(), - "closed_copy" => "**> foreign.session_close id=`alias`**\n**> foreign.session_set id=`alias` name=\"n\" value=`b`**".into(), - "wide_input" => "**> foreign.session_set id=`a` name=\"n\" value=9007199254740992**".into(), - "wide_output" => format!("**> foreign.session_eval id=`a` source=\"{bad}\"**"), - _ => String::new(), - }; - format!( - r#"--- -markup: occlusion -import: - foreign: lib/foreign.mq.md ---- -# main -**a = > foreign.session_open lang="{lang}"** -**b = > foreign.session_open lang="{lang}"** -**> foreign.session_set id=`a` name="n" value={seed}** -**> foreign.session_set id=`b` name="n" value=100** -**alias = `a`** -**counter = 777** -**before = > foreign.session_get id=`a` name="n"** -{failure} - -1. `before` < {condition} - **answer = > {function} s=`alias` rounds={rounds}** -2. * - **> foreign.session_set id=`a` name="n" value={else_value}** - -**after = > foreign.session_get id=`a` name="n"** -**peer = > foreign.session_get id=`b` name="n"** -**> foreign.session_close id=`alias`** -**c = > foreign.session_open lang="{lang}"** -**> foreign.session_set id=`c` name="n" value=7** -**fresh = > foreign.session_get id=`c` name="n"** -**> foreign.session_close id=`b`** -**> foreign.session_close id=`c`** -**total = after + peer + fresh + counter** -*total* - -## adjust - + `s` - + `rounds` -**counter = 0** -- `counter` < `rounds` - > bump s=`s` - **counter = counter + 1** - -**answer = > foreign.session_get id=`s` name="n"** -*answer* - -## bump - + `s` -> foreign.session_eval id=`s` source="{increment}"{stdin} - -## advance_rec - + `s` - + `rounds` -1. 0 < `rounds` - > bump s=`s` - **remaining = rounds - 1** - **answer = > advance_rec s=`s` rounds=`remaining`** - *answer* -2. * - **answer = > foreign.session_get id=`s` name="n"** - *answer* - -## early - + `s` - + `rounds` -**counter = 0** -- `counter` < `rounds` - **answer = > foreign.session_get id=`s` name="n"** - *answer* - -**answer = > foreign.session_get id=`s` name="n"** -*answer* -"#, - else_value = seed + 20 - ) -} - -#[test] -fn parsed_source_control_matches_independent_oracles_on_both_backends() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let out = std::env::var_os("MARQDO_SOURCE_ARTIFACT_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| root.join("target/source-refinement")); - std::fs::create_dir_all(&out).unwrap(); - let seeds = std::env::var("MARQDO_SOURCE_SEEDS") - .unwrap_or("3".into()) - .split(',') - .map(|x| x.parse::().unwrap()) - .collect::>(); - let lengths = std::env::var("MARQDO_SOURCE_ROUNDS") - .unwrap_or("0,3".into()) - .split(',') - .map(|x| x.parse::().unwrap()) - .collect::>(); - let scenarios = [ - "normal", - "recursive", - "early_return", - "else_branch", - "closed_get", - "copy_handle", - "closed_copy", - "wide_input", - "wide_output", - "explicit_empty_stdin", - ]; - let mut count = 0; - for lang in ["python", "node"] { - for &seed in &seeds { - for &rounds in &lengths { - for scenario in scenarios { - let id = format!("{lang}-{seed}-{rounds}-{scenario}"); - let text = source(lang, seed, rounds, scenario); - // Absolute import is only a fixture location; the actual module is loaded. - let text = text.replace( - "foreign: lib/foreign.mq.md", - &format!("foreign: {}", root.join("lib/foreign.mq.md").display()), - ); - let path = out.join(format!("{id}.mq.md")); - std::fs::write(&path, &text).unwrap(); - let module = crate::load::load_module(&path).unwrap(); - let ir = source_ir(&module).unwrap_or_else(|e| panic!("{id}: AST export: {e}")); - let mut executions = Vec::new(); - for backend in ["tree", "bytecode"] { - let (result, journal, values, protocol) = if backend == "tree" { - let mut interpreter = - crate::interp::Interpreter::with_capture(Some(&path), false); - let result = interpreter.run_module(&module); - let (journal, values, protocol) = interpreter.foreign_source_evidence(); - assert!(interpreter.captured_stdout.is_empty(), "unexpected stdout"); - (result, journal, values, protocol) - } else { - let code = - crate::bytecode::compile_module(Some(&path), &module).unwrap(); - let mut vm = crate::bytecode::Vm::with_capture(Some(&path)); - let result = vm.run(&code); - let (journal, values, protocol) = vm.foreign_source_evidence(); - assert!(vm.captured_stdout.is_empty(), "unexpected stdout"); - (result, journal, values, protocol) - }; - let failure = matches!( - scenario, - "closed_get" - | "copy_handle" - | "closed_copy" - | "wide_input" - | "wide_output" - ); - assert_eq!(result.is_err(), failure, "{id} {backend}: {result:?}"); - if !failure { - let expected = seed - + if scenario == "early_return" { - 0 - } else if scenario == "else_branch" { - 20 - } else { - rounds as i64 - }; - assert_eq!( - result.as_ref().unwrap(), - &Value::Int(expected + 884), - "{id} {backend}" - ); - } - let error = result.as_ref().err().map(|e| e.to_string()); - let diagnostic = result.as_ref().err().and_then(crate::diagnostics::Diagnostic::find).map(crate::diagnostics::Diagnostic::to_json); - let fault = if let Some(e) = &error { - if e.contains("not found") { - "unknown" - } else if e.contains("outside V_safe") - || e.contains("cannot be serialized") - { - if protocol.last().is_some_and(|p| { - p.response.as_ref().is_ok_and(|reply| { - reply.get("domain_error").and_then(Json::as_bool) - == Some(true) - }) - }) { - "outputDomain" - } else { - "inputDomain" - } - } else { - panic!("{id} {backend}: unclassified error {e}") - } - } else { - "none" - }; - let protocol = protocol.iter().map(|p| json!({"session":p.session,"request":p.request,"response":p.response})).collect::>(); - executions.push(json!({"backend":backend,"ok":result.is_ok(),"result":result.ok().map(|v|value_to_json(&v).unwrap()),"error":error,"fault":fault,"protocol":protocol,"diagnostic":diagnostic, - "journal":value_to_json(&Value::List(journal)).unwrap(),"live_values":value_to_json(&Value::List(values)).unwrap()})); - } - std::fs::write(out.join(format!("{id}.json")),serde_json::to_vec_pretty(&json!({"version":1,"id":id,"language":lang,"seed":seed,"rounds":rounds,"scenario":scenario,"source_sha256":format!("{:x}",Sha256::digest(text.as_bytes())),"ast":ir,"executions":executions})).unwrap()).unwrap(); - count += 1; - } - } - } - } - println!( - "SOURCE_METRIC:{}", - json!({"cases":count,"executions":count*2,"scenarios":scenarios,"correct":true}) - ); -} diff --git a/src/value.rs b/src/value.rs deleted file mode 100755 index fbea257..0000000 --- a/src/value.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! Runtime values (Phase I). - -use std::fmt; - -use crate::formula::Expr as FormulaExpr; - -/// An object's defining module instance, expressed as import binding segments. -/// This is ordinary copied data, not an unforgeable session capability. -pub(crate) const OBJECT_MODULE_KEY: &str = "_type_module"; - -pub(crate) fn instance_module(value: &Value) -> Result>, String> { - let Value::Map(fields) = value else { return Ok(None); }; - let Some((_, module)) = fields.iter().find(|(key, _)| key == OBJECT_MODULE_KEY) else { return Ok(None); }; - let Value::List(segments) = module else { return Err("object module tag must be a list of text segments".into()); }; - segments.iter().map(|segment| match segment { - Value::Text(name) => Ok(name.clone()), - _ => Err("object module tag must be a list of text segments".into()), - }).collect::,_>>().map(Some) -} - -pub(crate) fn tag_instance(type_name: &str, module: &[String], value: Value) -> Value { - let mut fields = match value { - Value::Map(fields) => fields, - Value::None => Vec::new(), - other => vec![("value".into(),other)], - }; - fields.retain(|(key,_)| key != "_type" && key != OBJECT_MODULE_KEY); - fields.insert(0,("_type".into(),Value::Text(type_name.into()))); - fields.insert(1,(OBJECT_MODULE_KEY.into(),Value::List(module.iter().cloned().map(Value::Text).collect()))); - Value::Map(fields) -} - -pub(crate) fn preserve_instance_module(receiver: &Value, value: Value) -> Value { - let Ok(Some(module)) = instance_module(receiver) else { return value; }; - match value { - Value::Map(mut fields) => { - fields.retain(|(key,_)| key != OBJECT_MODULE_KEY); - fields.insert(1.min(fields.len()),(OBJECT_MODULE_KEY.into(),Value::List(module.into_iter().map(Value::Text).collect()))); - Value::Map(fields) - } - other => other, - } -} - -/// Bound Markdown code fence (`type` → `code`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CodeBlock { - pub lang: String, - pub source: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Value { - None, - Bool(bool), - Int(i64), - /// Floating-point number (`type` → `num`). - Num(f64), - Text(String), - /// Vertical (1-column) table rows, or nested list values in a column map. - List(Vec), - /// String-keyed map (insertion order): JSON objects / horizontal tables. - Map(Vec<(String, Value)>), - /// Parsed symbolic expression (`type` → `formula`). - Formula(FormulaExpr), - /// External language source from ```lang fence (`type` → `code`). - Code(CodeBlock), - /// Sensitive text from `${secret.*}` — Display shows ``; reveal on Text concat. - Secret(String), - /// Opaque foreign-session handle. Not JSON-serializable; not printable structure. - Handle(String), -} - -impl Value { - pub fn truthy(&self) -> bool { - match self { - Value::None => false, - Value::Bool(b) => *b, - Value::Int(n) => *n != 0, - Value::Num(n) => *n != 0.0 && !n.is_nan(), - Value::Text(s) => !s.is_empty(), - Value::Secret(s) => !s.is_empty(), - Value::Handle(s) => !s.is_empty(), - Value::List(xs) => !xs.is_empty(), - Value::Map(xs) => !xs.is_empty(), - Value::Formula(_) => true, - Value::Code(c) => !c.source.is_empty(), - } - } - - /// Plaintext for Text / Secret (Authorization etc.). Prefer [`as_display`] for logs. - pub fn reveal_text(&self) -> Option<&str> { - match self { - Value::Text(s) | Value::Secret(s) => Some(s.as_str()), - _ => None, - } - } - - pub fn as_display(&self) -> String { - match self { - Value::None => "None".into(), - Value::Bool(true) => "True".into(), - Value::Bool(false) => "False".into(), - Value::Int(n) => n.to_string(), - Value::Num(n) => crate::formula::format_num(*n), - Value::Text(s) => s.clone(), - Value::Secret(_) => "".into(), - Value::Handle(_) => "".into(), - Value::List(xs) => { - let parts: Vec = xs.iter().map(|v| v.as_display()).collect(); - format!("[{}]", parts.join(", ")) - } - Value::Map(pairs) => { - let parts: Vec = pairs - .iter() - .filter(|(key,_)| key != OBJECT_MODULE_KEY) - .map(|(k, v)| format!("{k}: {}", v.as_display())) - .collect(); - format!("{{{}}}", parts.join(", ")) - } - Value::Formula(e) => e.as_display(), - Value::Code(c) => format!("```{}\n{}\n```", c.lang, c.source), - } - } -} - -impl fmt::Display for Value { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.as_display()) - } -} diff --git a/src/version_check.rs b/src/version_check.rs deleted file mode 100755 index ce6461e..0000000 --- a/src/version_check.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Optional check against GitHub Releases (`marqdo version --check`). - -use std::cmp::Ordering; - -const REPO: &str = "cflmy/marqdo"; - -pub fn print_version() { - println!("marqdo {}", env!("CARGO_PKG_VERSION")); -} - -pub fn check_latest() -> Result<(), String> { - let current = env!("CARGO_PKG_VERSION"); - let url = format!("https://api.github.com/repos/{REPO}/releases/latest"); - let response = ureq::get(&url) - .set("Accept", "application/vnd.github+json") - .set("User-Agent", &format!("marqdo/{current}")) - .call() - .map_err(|e| format!("version check failed: {e}"))?; - let body = response - .into_string() - .map_err(|e| format!("version check read failed: {e}"))?; - let tag = parse_tag_name(&body).ok_or_else(|| "version check: missing tag_name".to_string())?; - let latest = tag.trim_start_matches('v'); - match compare_semver(latest, current) { - Ordering::Greater => { - println!("Update available: v{latest} (you have {current})"); - println!("https://github.com/{REPO}/releases/latest"); - } - _ => println!("marqdo {current} is up to date (latest v{latest})."), - } - Ok(()) -} - -fn parse_tag_name(json: &str) -> Option { - let needle = "\"tag_name\""; - let start = json.find(needle)? + needle.len(); - let rest = json[start..].trim_start(); - if !rest.starts_with(':') { - return None; - } - let rest = rest[1..].trim_start(); - if !rest.starts_with('"') { - return None; - } - let rest = &rest[1..]; - let end = rest.find('"')?; - Some(rest[..end].to_string()) -} - -fn compare_semver(a: &str, b: &str) -> Ordering { - let pa: Vec = a - .split('-') - .next() - .unwrap_or(a) - .split('.') - .map(|s| s.parse().unwrap_or(0)) - .collect(); - let pb: Vec = b - .split('-') - .next() - .unwrap_or(b) - .split('.') - .map(|s| s.parse().unwrap_or(0)) - .collect(); - for i in 0..3 { - let da = pa.get(i).copied().unwrap_or(0); - let db = pb.get(i).copied().unwrap_or(0); - match da.cmp(&db) { - Ordering::Equal => {} - other => return other, - } - } - Ordering::Equal -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_release_tag() { - let json = r#"{"tag_name":"v0.1.2","name":"Marqdo"}"#; - assert_eq!(parse_tag_name(json).as_deref(), Some("v0.1.2")); - } - - #[test] - fn semver_order() { - assert_eq!(compare_semver("0.1.2", "0.1.1"), Ordering::Greater); - assert_eq!(compare_semver("0.1.1", "0.1.2"), Ordering::Less); - } -} diff --git a/src/view/annot.rs b/src/view/annot.rs deleted file mode 100755 index dbe4972..0000000 --- a/src/view/annot.rs +++ /dev/null @@ -1,1147 +0,0 @@ -//! View annotations: bind values, returns, writebacks, branch/loop trace → Structure callouts. - -use std::collections::HashMap; - -use crate::ast::{Function, Module, Stmt}; -use crate::capture::{RunCapture, StmtEventKind}; -use crate::host::writeback; -use crate::parse::{scan_prose_line, ProseBit}; -use crate::value::Value; -use crate::view::html::escape; - -/// One result callout anchored to a source span. -#[derive(Debug, Clone)] -pub struct ViewAnnot { - pub id: String, - pub kind: AnnotKind, - pub anchor_line: u32, - pub anchor_byte_start: Option, - pub anchor_byte_end: Option, - pub label: String, - pub value: String, - pub detail: String, - pub arm_index: Option, - pub call_id: Option, - pub loop_id: Option, - /// 0-based iteration index when inside a loop frame. - pub iter: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AnnotKind { - Bind, - Return, - #[allow(dead_code)] - Call, - #[allow(dead_code)] // reserved for non-call BoldCode expr chips - Expr, - Branch, - Loop, - Writeback, - /// Synthetic: one per CallFrame for function picker (label = fn name, value = args_brief). - CallFrame, - /// Synthetic: one per loop iteration for loop picker. - LoopFrame, -} - -impl AnnotKind { - pub fn as_str(self) -> &'static str { - match self { - AnnotKind::Bind => "bind", - AnnotKind::Return => "return", - AnnotKind::Call => "call", - AnnotKind::Expr => "expr", - AnnotKind::Branch => "branch", - AnnotKind::Loop => "loop", - AnnotKind::Writeback => "writeback", - AnnotKind::CallFrame => "callframe", - AnnotKind::LoopFrame => "loopframe", - } - } -} - -/// Truncate display text for callout chips. -pub fn brief_value(v: &Value) -> String { - let s = v.as_display(); - if s.chars().count() > 48 { - format!("{}…", s.chars().take(48).collect::()) - } else { - s - } -} - -fn brief_str(s: &str) -> String { - if s.chars().count() > 48 { - format!("{}…", s.chars().take(48).collect::()) - } else { - s.to_string() - } -} - -/// Build annotations from capture + source (post-stmt events preferred). -pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec { - let mut out = Vec::new(); - let mut id_seq = 0u32; - let mut next_id = |prefix: &str| -> String { - id_seq += 1; - format!("{prefix}{id_seq}") - }; - - let name_sites = collect_name_sites(module, source); - let lines: Vec<&str> = source.lines().collect(); - - // Prefer StmtEvent assign/return (post-stmt). Keep one chip per (line,name,call,loop,iter). - type AssignKey = (u32, String, u32, Option, Option); - let mut last_assign: HashMap = HashMap::new(); - let mut assign_counts: HashMap = HashMap::new(); - for ev in &cap.view_trace.events { - if ev.kind == StmtEventKind::Assign { - if let Some(ref name) = ev.name { - let key = (ev.line, name.clone(), ev.call_id, ev.loop_id, ev.iter); - *assign_counts.entry(key.clone()).or_insert(0) += 1; - last_assign.insert(key, ev); - } - } - } - - if !last_assign.is_empty() { - for ((line, name, _cid, _lid, _iter), ev) in &last_assign { - let (start, end) = name_sites - .get(name.as_str()) - .and_then(|(l, s, e)| if l == line { Some((*s, *e)) } else { None }) - .unwrap_or_else(|| { - find_name_in_line( - lines - .get((*line as usize).saturating_sub(1)) - .copied() - .unwrap_or(""), - name, - ) - }); - let key = (*line, name.clone(), ev.call_id, ev.loop_id, ev.iter); - let raw = ev.value_after.clone().unwrap_or_else(|| "?".into()); - let (value, detail) = abbreviate_bind_value(&raw); - let mut value = value; - let count = assign_counts.get(&key).copied().unwrap_or(1); - if count > 1 { - value = format!("{value} · ×{count}"); - } - out.push(ViewAnnot { - id: next_id("b"), - kind: AnnotKind::Bind, - anchor_line: *line, - anchor_byte_start: start, - anchor_byte_end: end, - label: name.clone(), - value: brief_str(&value), - detail, - arm_index: None, - call_id: Some(ev.call_id), - loop_id: ev.loop_id, - iter: ev.iter, - }); - } - } else { - // Fallback (bytecode / empty events): final bindings — only when no events. - for (name, val) in &cap.bindings { - let (line, start, end) = name_sites - .get(name.as_str()) - .copied() - .unwrap_or((0, None, None)); - if line == 0 { - continue; - } - out.push(ViewAnnot { - id: next_id("b"), - kind: AnnotKind::Bind, - anchor_line: line, - anchor_byte_start: start, - anchor_byte_end: end, - label: name.clone(), - value: brief_value(val), - detail: val.as_display(), - arm_index: None, - call_id: None, - loop_id: None, - iter: None, - }); - } - } - - // BindRef: foreach item = collection[i] (one per iteration). - for ev in &cap.view_trace.events { - if ev.kind != StmtEventKind::BindRef { - continue; - } - let Some(ref name) = ev.name else { continue }; - let value = ev.value_after.clone().unwrap_or_default(); - // Label is `分`; value is `分数表[3] · 88` (not `分 = …` again). - let display = if let Some((left, right)) = value.split_once('=') { - format!("{left} · {right}") - } else { - value.clone() - }; - out.push(ViewAnnot { - id: next_id("brf"), - kind: AnnotKind::Bind, - anchor_line: ev.line, - anchor_byte_start: None, - anchor_byte_end: None, - label: name.clone(), - value: brief_str(&display), - detail: format!("{name} = {display}"), - arm_index: None, - call_id: Some(ev.call_id), - loop_id: ev.loop_id, - iter: ev.iter, - }); - } - - // Return events (last per line+call+iter). - type RetKey = (u32, u32, Option, Option); - let mut last_ret: HashMap = HashMap::new(); - for ev in &cap.view_trace.events { - if ev.kind == StmtEventKind::Return { - last_ret.insert((ev.line, ev.call_id, ev.loop_id, ev.iter), ev); - } - } - let call_sites: HashMap = cap - .view_trace - .calls - .iter() - .map(|fr| (fr.call_id, fr.call_line)) - .collect(); - for ((line, _, _, _), ev) in last_ret { - // Return events from an imported library carry the callee's line - // number. Anchor the chip at the caller's line instead. - let anchor_line = call_sites - .get(&ev.call_id) - .copied() - .filter(|l| *l > 0) - .unwrap_or(line); - let text = lines - .get(anchor_line.saturating_sub(1) as usize) - .copied() - .unwrap_or(""); - let mut start = None; - let mut end = None; - for bit in scan_prose_line(text) { - if let ProseBit::ItalicReturn { at, .. } = &bit { - start = Some(*at); - end = Some(prose_bit_end(text, &bit)); - } - } - let value = ev.value_after.clone().unwrap_or_default(); - out.push(ViewAnnot { - id: next_id("r"), - kind: AnnotKind::Return, - anchor_line, - anchor_byte_start: start, - anchor_byte_end: end, - label: "return".into(), - value: brief_str(&value), - detail: value, - arm_index: None, - call_id: Some(ev.call_id), - loop_id: ev.loop_id, - iter: ev.iter, - }); - } - - // Writebacks. - let wb = writeback::writeback_map(source); - for (line, body) in wb { - let brief = body.lines().next().unwrap_or(body.as_str()); - out.push(ViewAnnot { - id: next_id("w"), - kind: AnnotKind::Writeback, - anchor_line: line, - anchor_byte_start: None, - anchor_byte_end: None, - label: "output".into(), - value: brief_str(brief), - detail: body, - arm_index: None, - call_id: None, - loop_id: None, - iter: None, - }); - } - - // Branch hits — one annot per (line, arm, call) with call_id for frame filtering. - for hit in &cap.view_trace.branches { - out.push(ViewAnnot { - id: next_id("br"), - kind: AnnotKind::Branch, - anchor_line: hit.line, - anchor_byte_start: None, - anchor_byte_end: None, - label: format!("arm {}", hit.arm_index + 1), - value: if hit.count > 1 { - format!("taken ×{}", hit.count) - } else { - "taken".into() - }, - detail: format!( - "arm {} hit {} time(s) call {}", - hit.arm_index + 1, - hit.count, - hit.call_id - ), - arm_index: Some(hit.arm_index), - call_id: Some(hit.call_id), - loop_id: None, - iter: None, - }); - } - - // Per-iteration frames for the picker. Foreach item binding is already a BindRef chip - // (`分` → `分数表[i] · v`); do not emit a second Loop summary on the same line. - for fr in &cap.view_trace.loop_frames { - let item = fr.item_name.as_deref().unwrap_or("item"); - let coll = fr.collection.as_deref().unwrap_or("?"); - let has_item_bind = fr.item_name.is_some() && !fr.iterations.is_empty(); - if !has_item_bind { - // while / empty: keep a single summary chip (no BindRef duplicate). - let last = fr.iterations.last(); - let summary = if let Some(it) = last { - format!("{} iters · last={}", fr.iterations.len(), it.item_value) - } else { - format!("{} iters", fr.iterations.len()) - }; - out.push(ViewAnnot { - id: next_id("lp"), - kind: AnnotKind::Loop, - anchor_line: fr.line, - anchor_byte_start: None, - anchor_byte_end: None, - label: "loop".into(), - value: brief_str(&summary), - detail: summary, - arm_index: None, - call_id: last.map(|it| it.call_id), - loop_id: Some(fr.loop_id), - iter: None, - }); - } - for it in &fr.iterations { - let value = format!("{} = {}[{}] · {}", item, coll, it.index, it.item_value); - out.push(ViewAnnot { - id: format!("lf{}-{}", fr.loop_id, it.index), - kind: AnnotKind::LoopFrame, - anchor_line: fr.line, - anchor_byte_start: None, - anchor_byte_end: None, - label: format!("{}", it.index + 1), - value: brief_str(&value), - detail: value, - arm_index: None, - call_id: Some(it.call_id), - loop_id: Some(fr.loop_id), - iter: Some(it.index), - }); - } - } - // Fallback LoopHit when no LoopFrame (legacy / while without frames). - if cap.view_trace.loop_frames.is_empty() { - for hit in &cap.view_trace.loops { - let mut value = format!("{} iters", hit.iterations); - if let Some(ref last) = hit.last_item { - value.push_str(" · last="); - value.push_str(last); - } - out.push(ViewAnnot { - id: next_id("lp"), - kind: AnnotKind::Loop, - anchor_line: hit.line, - anchor_byte_start: None, - anchor_byte_end: None, - label: "loop".into(), - value, - detail: format!("iterations={}", hit.iterations), - arm_index: None, - call_id: None, - loop_id: None, - iter: None, - }); - } - } - - // Call / expr events → chips; zip with BoldCode spans when several share a line. - let mut calls_by_line: HashMap> = HashMap::new(); - for ev in &cap.view_trace.events { - if ev.kind == StmtEventKind::Call { - calls_by_line.entry(ev.line).or_default().push(ev); - } - } - for (line, evs) in calls_by_line { - let text = lines - .get(line.saturating_sub(1) as usize) - .copied() - .unwrap_or(""); - let bold_spans: Vec<(usize, usize)> = scan_prose_line(text) - .into_iter() - .filter_map(|bit| match bit { - ProseBit::BoldCode { .. } => { - let start = bit_at(&bit); - Some((start, prose_bit_end(text, &bit))) - } - _ => None, - }) - .collect(); - for (i, ev) in evs.iter().enumerate() { - // One BoldCode on the line (e.g. print across call frames): share it. - // Several BoldCodes (e.g. two greets in main): zip by index. - let (start, end) = if bold_spans.is_empty() { - (None, None) - } else if bold_spans.len() == 1 { - let (s, e) = bold_spans[0]; - (Some(s), Some(e)) - } else { - bold_spans - .get(i) - .copied() - .map(|(s, e)| (Some(s), Some(e))) - .unwrap_or((None, None)) - }; - let value = ev.value_after.clone().unwrap_or_default(); - let label = ev.name.clone().unwrap_or_else(|| "call".into()); - out.push(ViewAnnot { - id: next_id("c"), - kind: AnnotKind::Call, - anchor_line: line, - anchor_byte_start: start, - anchor_byte_end: end, - label, - value: brief_str(&value), - detail: value, - arm_index: None, - call_id: Some(ev.call_id), - loop_id: ev.loop_id, - iter: ev.iter, - }); - } - } - - // Call frames for picker (label = fn name). - for fr in &cap.view_trace.calls { - out.push(ViewAnnot { - id: format!("cf{}", fr.call_id), - kind: AnnotKind::CallFrame, - anchor_line: fr.fn_line, - anchor_byte_start: None, - anchor_byte_end: None, - label: fr.fn_name.clone(), - value: fr.args_brief.clone(), - detail: format!("call #{} {}", fr.ordinal, fr.args_brief), - arm_index: None, - call_id: Some(fr.call_id), - loop_id: None, - iter: None, - }); - } - - // Param Decl sites in function body: bind chips from CallFrame args. - for fr in &cap.view_trace.calls { - let Some(fun) = find_fun_by_line(module, fr.fn_line) else { - continue; - }; - let body_lines = fun_stmt_lines(fun); - for (pname, pval) in parse_args_brief_pairs(&fr.args_brief) { - for (i, text) in lines.iter().enumerate() { - let line_no = (i + 1) as u32; - if !body_lines.contains(&line_no) { - continue; - } - for bit in scan_prose_line(text) { - if let ProseBit::Decl { name, at, .. } = &bit { - if name != &pname { - continue; - } - let end = prose_bit_end(text, &bit); - out.push(ViewAnnot { - id: next_id("p"), - kind: AnnotKind::Bind, - anchor_line: line_no, - anchor_byte_start: Some(*at), - anchor_byte_end: Some(end), - label: pname.clone(), - value: brief_str(&pval), - detail: format!("{pname}={pval}"), - arm_index: None, - call_id: Some(fr.call_id), - loop_id: None, - iter: None, - }); - } - } - } - } - } - - // Same prose span across call frames shares one id so - // matches the visible chip after frame filter (else L-leaders find no anchor). - unify_annot_ids_by_span(&mut out); - - out -} - -fn unify_annot_ids_by_span(annots: &mut [ViewAnnot]) { - let mut first: HashMap<(u32, Option, Option, u8), String> = HashMap::new(); - for a in annots.iter_mut() { - if matches!(a.kind, AnnotKind::CallFrame | AnnotKind::LoopFrame) { - continue; - } - if a.anchor_byte_start.is_none() { - continue; - } - let tag = match a.kind { - AnnotKind::Bind => 1u8, - AnnotKind::Return => 2, - AnnotKind::Call | AnnotKind::Expr => 3, - AnnotKind::Branch => 4, - AnnotKind::Loop => 5, - AnnotKind::Writeback => 6, - AnnotKind::CallFrame | AnnotKind::LoopFrame => 0, - }; - let key = ( - a.anchor_line, - a.anchor_byte_start, - a.anchor_byte_end, - tag, - ); - if let Some(id) = first.get(&key) { - a.id = id.clone(); - } else { - first.insert(key, a.id.clone()); - } - } -} - -fn abbreviate_bind_value(raw: &str) -> (String, String) { - if raw.contains(" 96 { - let short: String = raw.chars().take(48).collect(); - return (format!("{short}…"), format!("{short}…")); - } - (raw.to_string(), raw.to_string()) -} - -fn parse_args_brief_pairs(brief: &str) -> Vec<(String, String)> { - let mut out = Vec::new(); - for part in brief.split(", ") { - if let Some((k, v)) = part.split_once('=') { - if !k.is_empty() { - out.push((k.to_string(), v.to_string())); - } - } - } - out -} - -fn find_fun_by_line(module: &Module, line: u32) -> Option<&Function> { - fn walk<'a>(fun: &'a Function, line: u32) -> Option<&'a Function> { - if fun.span.line == line { - return Some(fun); - } - for c in &fun.children { - if let Some(f) = walk(c, line) { - return Some(f); - } - } - None - } - for f in &module.functions { - if let Some(found) = walk(f, line) { - return Some(found); - } - } - None -} - -fn fun_stmt_lines(fun: &Function) -> std::collections::HashSet { - let mut s = std::collections::HashSet::new(); - crate::ast::walk_stmts(fun, &mut |st| { - s.insert(crate::ast::stmt_line(st)); - }); - s -} - -/// Serialize ViewExecutionReport JSON for AI / page embed. -pub fn view_execution_report_json(path: &str, ok: bool, cap: &RunCapture) -> String { - use serde_json::{json, Map}; - let mut bindings = Map::new(); - for (k, v) in &cap.bindings { - bindings.insert(k.clone(), json!(v.as_display())); - } - let calls: Vec<_> = cap - .view_trace - .calls - .iter() - .map(|c| { - json!({ - "call_id": c.call_id, - "fn": c.fn_name, - "fn_line": c.fn_line, - "ordinal": c.ordinal, - "args_brief": c.args_brief, - }) - }) - .collect(); - let events: Vec<_> = cap - .view_trace - .events - .iter() - .map(|e| { - json!({ - "line": e.line, - "kind": e.kind.as_str(), - "name": e.name, - "value_after": e.value_after, - "arm_index": e.arm_index, - "iter": e.iter, - "call_id": e.call_id, - "loop_id": e.loop_id, - }) - }) - .collect(); - let loops: Vec<_> = cap - .view_trace - .loop_frames - .iter() - .map(|fr| { - json!({ - "loop_id": fr.loop_id, - "line": fr.line, - "item": fr.item_name, - "collection": fr.collection, - "iters": fr.iterations.iter().map(|it| json!({ - "index": it.index, - "value": it.item_value, - "call_id": it.call_id, - })).collect::>(), - }) - }) - .collect(); - json!({ - "version": 1, - "path": path, - "ok": ok, - "calls": calls, - "loops": loops, - "events": events, - "bindings_final": bindings, - }) - .to_string() -} - -fn collect_name_sites( - module: &Module, - source: &str, -) -> HashMap, Option)> { - let mut map = HashMap::new(); - let lines: Vec<&str> = source.lines().collect(); - for fun in &module.functions { - collect_name_sites_fun(fun, &lines, &mut map); - } - for (i, text) in lines.iter().enumerate() { - let line_no = (i + 1) as u32; - for bit in scan_prose_line(text) { - if let ProseBit::Decl { name, at, .. } = &bit { - let end = prose_bit_end(text, &bit); - map.entry(name.clone()) - .or_insert((line_no, Some(*at), Some(end))); - } - } - } - map -} - -fn collect_name_sites_fun( - fun: &Function, - lines: &[&str], - map: &mut HashMap, Option)>, -) { - for stmt in &fun.body { - if let Stmt::Assign { name, span, .. } = stmt { - let text = lines - .get(span.line.saturating_sub(1) as usize) - .copied() - .unwrap_or(""); - let (start, end) = find_name_in_line(text, name); - // Prefer first site for fallback map; post-stmt uses line from event. - map.entry(name.clone()) - .or_insert((span.line, start, end)); - } - walk_stmt_nested(stmt, lines, map); - } - for child in &fun.children { - collect_name_sites_fun(child, lines, map); - } -} - -fn walk_stmt_nested( - stmt: &Stmt, - lines: &[&str], - map: &mut HashMap, Option)>, -) { - match stmt { - Stmt::Branch { arms, .. } => { - for arm in arms { - for s in &arm.body { - if let Stmt::Assign { name, span, .. } = s { - let text = lines - .get(span.line.saturating_sub(1) as usize) - .copied() - .unwrap_or(""); - let (start, end) = find_name_in_line(text, name); - map.entry(name.clone()) - .or_insert((span.line, start, end)); - } - walk_stmt_nested(s, lines, map); - } - } - } - Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { - for s in body { - if let Stmt::Assign { name, span, .. } = s { - let text = lines - .get(span.line.saturating_sub(1) as usize) - .copied() - .unwrap_or(""); - let (start, end) = find_name_in_line(text, name); - map.entry(name.clone()) - .or_insert((span.line, start, end)); - } - walk_stmt_nested(s, lines, map); - } - } - _ => {} - } -} - -fn find_name_in_line(text: &str, name: &str) -> (Option, Option) { - for bit in scan_prose_line(text) { - match &bit { - ProseBit::Decl { name: n, at, .. } if n == name => { - return (Some(*at), Some(prose_bit_end(text, &bit))); - } - ProseBit::BoldCode { inner, at } if inner.contains(name) => { - return (Some(*at), Some(prose_bit_end(text, &bit))); - } - _ => {} - } - } - if let Some(at) = text.find(name) { - return (Some(at), Some(at + name.len())); - } - (None, None) -} - -/// Byte end (exclusive) of a prose bit in `line`. -pub fn prose_bit_end(line: &str, bit: &ProseBit) -> usize { - match bit { - ProseBit::Decl { name, default, at } => { - let after_ticks = *at + 1 + name.len() + 1; - match default { - None => after_ticks, - Some(d) => { - let mut end = after_ticks; - if line.get(end..end + 1) == Some("=") { - end += 1 + d.len(); - } - end.min(line.len()) - } - } - } - ProseBit::BoldCode { inner, at } => (*at + 2 + inner.len() + 2).min(line.len()), - ProseBit::ItalicReturn { inner, at } => (*at + 1 + inner.len() + 1).min(line.len()), - } -} - -pub fn bit_at(bit: &ProseBit) -> usize { - match bit { - ProseBit::Decl { at, .. } - | ProseBit::BoldCode { at, .. } - | ProseBit::ItalicReturn { at, .. } => *at, - } -} - -pub fn bit_kind_class(bit: &ProseBit) -> &'static str { - match bit { - ProseBit::Decl { .. } => "decl", - ProseBit::BoldCode { .. } => "code", - ProseBit::ItalicReturn { .. } => "return", - } -} - -/// Render annotation band HTML for a set of annots (already filtered to one block). -/// -/// SSR defaults to the **last** call_id and **last** iteration per loop_id (matches -/// pickers). Overflow (`max_visible`) is counted only among chips visible in that -/// default frame — so `who` on the last greet call is not buried behind +N. -/// Client `applyCallFrame` recomputes overflow after switching. -pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String { - let annots: Vec<&ViewAnnot> = annots - .iter() - .filter(|a| a.kind != AnnotKind::CallFrame && a.kind != AnnotKind::LoopFrame) - .collect(); - if annots.is_empty() { - return String::new(); - } - // Default visible iteration = max index per loop_id (matches picker default = last). - let mut default_iter: HashMap, u32> = HashMap::new(); - for a in &annots { - if let Some(i) = a.iter { - let e = default_iter.entry(a.loop_id).or_insert(i); - if i > *e { - *e = i; - } - } - } - // Default call frame = max call_id among chips that carry one (last invocation). - let default_call_id: Option = annots.iter().filter_map(|a| a.call_id).max(); - // Left-to-right by anchor so chips sit under their underlines (avoids - // crossed L-leaders that look like “missing” lines when crowded). - let mut ordered: Vec<&ViewAnnot> = annots; - ordered.sort_by(|a, b| { - let sa = a.anchor_byte_start.unwrap_or(usize::MAX); - let sb = b.anchor_byte_start.unwrap_or(usize::MAX); - sa.cmp(&sb).then_with(|| a.id.cmp(&b.id)) - }); - - let mut s = String::from(r#"
      "#); - // Leaders live on the parent .doc-block (see initAnnotLeaders); keep a hook - // for keyed mode / a11y but geometry is computed against the block. - s.push_str(r#""#); - s.push_str(r#"
      "#); - let mut shown = 0usize; - let mut overflow_count = 0usize; - for a in &ordered { - let iter_miss = a - .iter - .zip(default_iter.get(&a.loop_id)) - .map(|(i, d)| i != *d) - .unwrap_or(false); - let call_miss = match (a.call_id, default_call_id) { - (Some(cid), Some(def)) if cid != def => true, - _ => false, - }; - let frame_miss = iter_miss || call_miss; - let overflow = if frame_miss { - false - } else if shown >= max_visible { - overflow_count += 1; - true - } else { - shown += 1; - false - }; - let mut classes = format!("annot-chip annot-{}", a.kind.as_str()); - if overflow { - classes.push_str(" annot-chip-overflow"); - } - if frame_miss { - classes.push_str(" is-frame-hidden"); - } - let call_attr = a - .call_id - .map(|c| format!(r#" data-call-id="{c}""#)) - .unwrap_or_default(); - let loop_attr = a - .loop_id - .map(|c| format!(r#" data-loop-id="{c}""#)) - .unwrap_or_default(); - let iter_attr = a - .iter - .map(|c| format!(r#" data-iter="{c}""#)) - .unwrap_or_default(); - let arm_attr = a - .arm_index - .map(|c| format!(r#" data-arm-index="{c}""#)) - .unwrap_or_default(); - // All call/iteration chips share the same source span, even when the - // rendered mark carries another frame's annotation ID. - let source_attr = format!( - " data-anchor-line=\"{}\"{}{}", - a.anchor_line, - a.anchor_byte_start.map(|n| format!(" data-anchor-byte-start=\"{n}\"")).unwrap_or_default(), - a.anchor_byte_end.map(|n| format!(" data-anchor-byte-end=\"{n}\"")).unwrap_or_default(), - ); - let hidden_attr = if frame_miss { " hidden" } else { "" }; - s.push_str(&format!( - r#""#, - classes = classes, - kind = a.kind.as_str(), - id = escape(&a.id), - call = call_attr, - loop_id = loop_attr, - iter = iter_attr, - arm = arm_attr, - source = source_attr, - hidden = hidden_attr, - detail = escape(&a.detail), - label = escape(&a.label), - value = escape(&a.value), - )); - } - if overflow_count > 0 { - s.push_str(&format!( - r#""#, - overflow_count - )); - } - s.push_str("
      "); - s -} - -/// Group annots by anchor line. -pub fn annots_by_line(annots: &[ViewAnnot]) -> HashMap> { - let mut m: HashMap> = HashMap::new(); - for a in annots { - if a.kind == AnnotKind::CallFrame || a.kind == AnnotKind::LoopFrame { - continue; - } - m.entry(a.anchor_line).or_default().push(a); - } - m -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::capture::{RunCapture, ViewTrace}; - - #[test] - fn prose_bit_end_bold_and_return() { - let line = "操作**n=n+1**接着返回*n*。"; - let bits = scan_prose_line(line); - assert!(bits.len() >= 2, "{bits:?}"); - for bit in &bits { - let end = prose_bit_end(line, bit); - assert!(end <= line.len()); - assert!(end > bit_at(bit)); - } - } - - #[test] - fn post_stmt_init_not_final() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let annots = build_view_annots(&module, src, &cap); - // Find bind for 总分 on the init line (**总分 = 0**). - let init = annots.iter().find(|a| { - a.kind == AnnotKind::Bind && a.label == "总分" && a.value.starts_with('0') - }); - assert!( - init.is_some(), - "expected 总分=0 post-stmt annot, got: {:?}", - annots - .iter() - .filter(|a| a.label == "总分") - .map(|a| (&a.value, a.anchor_line)) - .collect::>() - ); - } - - #[test] - fn build_annots_branch_and_loop() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let annots = build_view_annots(&module, src, &cap); - assert!(annots.iter().any(|a| a.kind == AnnotKind::Branch)); - assert!(!cap.view_trace.events.is_empty(), "expected stmt events"); - // Branch annots must carry call_id so call picker can filter. - assert!( - annots - .iter() - .filter(|a| a.kind == AnnotKind::Branch) - .all(|a| a.call_id.is_some()), - "branch annots missing call_id" - ); - assert!(!cap.view_trace.loop_frames.is_empty(), "expected loop frames"); - assert!(annots.iter().any(|a| a.kind == AnnotKind::LoopFrame)); - // Foreach: BindRef chips only — no duplicate Loop summary on the same line. - let loop_line = cap.view_trace.loop_frames[0].line; - let on_loop: Vec<_> = annots - .iter() - .filter(|a| a.anchor_line == loop_line) - .collect(); - assert!( - on_loop.iter().any(|a| a.kind == AnnotKind::Bind && a.label == "分"), - "expected BindRef for 分" - ); - assert!( - !on_loop.iter().any(|a| a.kind == AnnotKind::Loop), - "foreach must not emit duplicate Loop summary chip: {:?}", - on_loop.iter().map(|a| a.kind.as_str()).collect::>() - ); - } - - #[test] - fn call_frames_filter_branch_arms() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let grade_calls: Vec<_> = cap - .view_trace - .calls - .iter() - .filter(|c| c.fn_name == "等级说明") - .collect(); - assert!(grade_calls.len() >= 2, "expected ≥2 calls to 等级说明"); - let c1 = grade_calls[0].call_id; - let c2 = grade_calls[1].call_id; - let arm_for = |cid: u32| { - cap.view_trace - .events - .iter() - .find(|e| e.kind == StmtEventKind::Branch && e.call_id == cid) - .and_then(|e| e.arm_index) - }; - let a1 = arm_for(c1).expect("branch for call 1"); - let a2 = arm_for(c2).expect("branch for call 2"); - assert_ne!(a1, a2, "two calls should take different arms"); - } - - #[test] - fn loop_frame_item_binding() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let fr = cap.view_trace.loop_frames.first().expect("loop frame"); - assert_eq!(fr.item_name.as_deref(), Some("分")); - assert_eq!(fr.collection.as_deref(), Some("分数表")); - assert_eq!(fr.iterations.len(), 4); - assert_eq!(fr.iterations.last().unwrap().item_value, "88"); - assert_eq!(fr.iterations.last().unwrap().index, 3); - } - - #[test] - fn loop_band_ssr_hides_non_default_iters() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let annots = build_view_annots(&module, src, &cap); - // Collect bind annots on the 总分 assign line inside the loop. - let total_line = annots - .iter() - .find(|a| a.kind == AnnotKind::Bind && a.label == "总分" && a.iter == Some(3)) - .map(|a| a.anchor_line) - .expect("last-iter 总分"); - let on_line: Vec<_> = annots - .iter() - .filter(|a| a.anchor_line == total_line && a.kind == AnnotKind::Bind) - .cloned() - .collect(); - assert!(on_line.len() >= 4, "expected per-iter 总分 chips"); - let html = render_annot_band(&on_line, 8); - // Non-last iters are SSR-hidden; last remains visible. - assert!(html.contains(r#"data-iter="3""#), "{html}"); - assert!( - html.contains(r#"data-iter="0""#) && html.contains("is-frame-hidden"), - "expected non-default iters hidden: {html}" - ); - let visible_totals = html.matches(r#"data-iter="3""#).count(); - assert_eq!(visible_totals, 1); - // Hidden attribute on iter 0 chip. - assert!( - html.contains(r#"data-iter="0""#) - && html - .split("` call under - /// `## 安装` belongs to that method — it does **not** run until something - /// calls `安装`. This is object semantics, not a parser failure. - #[test] - fn call_under_child_heading_does_not_auto_run() { - let src = r#"--- -title: t ---- - -# main - -## 安装 - -> 问候 谁=a - -## 问候 - + `谁` - -> print text=hi `谁` -"#; - let module = crate::parse::parse_source(src).unwrap(); - let main = &module.functions[0]; - assert_eq!(main.name, "main"); - let install = main.children.iter().find(|c| c.name == "安装").expect("安装"); - let install_calls: Vec<_> = install - .body - .iter() - .filter_map(|s| match s { - crate::ast::Stmt::Call { call, .. } => Some(call.callee.as_str()), - _ => None, - }) - .collect(); - let main_calls: Vec<_> = main - .body - .iter() - .filter_map(|s| match s { - crate::ast::Stmt::Call { call, .. } => Some(call.callee.as_str()), - _ => None, - }) - .collect(); - assert!(main_calls.is_empty()); - assert_eq!(install_calls, ["问候"]); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - assert!( - cap.stdout.trim().is_empty(), - "entry does not auto-run ## 安装; stdout={:?}", - cap.stdout - ); - assert!( - !cap.view_trace.calls.iter().any(|c| c.fn_name == "问候"), - "no CallFrame for 问候 when only nested under uncalled ## 安装" - ); - } - - #[test] - fn call_in_main_before_child_def_runs_like_nested_call() { - let src = include_str!("../../tests/structure/nested-call.mq.md"); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - assert!(cap.stdout.contains("Hello"), "{:?}", cap.stdout); - assert!( - cap.view_trace.calls.iter().any(|c| c.fn_name == "问候"), - "expected CallFrame for 问候: {:?}", - cap.view_trace.calls - ); - } - - #[test] - fn report_json_has_version() { - let cap = RunCapture { - stdout: String::new(), - value: Value::None, - plots: Vec::new(), - bindings: HashMap::new(), - view_trace: ViewTrace::default(), - }; - let j = view_execution_report_json("x.mq.md", true, &cap); - assert!(j.contains("\"version\":1"), "{j}"); - assert!(j.contains("events"), "{j}"); - assert!(j.contains("loops"), "{j}"); - } -} diff --git a/src/view/assets/README.md b/src/view/assets/README.md deleted file mode 100755 index a4fcb8d..0000000 --- a/src/view/assets/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Reader assets - -The reader embeds these resources into its shared live/static HTML shell. There are -no remote logo, decoration, math-script or math-font requests. - -- `logo.svg`: new project-native geometric M/book mark, olive and champagne gold. - `logo.uri` is its base64 data URI for favicon and wordmarks. -- `blossom.png`, `feather.png`: original transparent artwork generated with the - built-in imagegen tool for this redesign. Their WebP copies are resized browser - assets; `.uri` files contain the same WebP bytes as base64 data URIs. -- `vendor/`: KaTeX 0.16.22, reused from the workspace's existing local distribution. - See `vendor/KATEX-LICENSE`. CSS fonts are embedded as woff2 data URIs, so opening - a static export from disk also renders formulas offline. - -## Final generation prompts - -### Blossom - -Use case: illustration-story. Asset type: transparent corner botanical ornament for Marqdo literary executable-document reader. A single elegant cherry blossom branch entering from upper left, thin olive and muted gold stems, delicate ivory and pale blush five-petal blossoms, sparse small olive leaves. Refined East Asian botanical watercolor with very fine warm gold ink contours, airy asymmetrical composition, most flowers concentrated in upper-left quadrant with branch tapering toward lower right. True transparent background, no paper rectangle, no text, no logo, no UI, no shadow. Soft quiet sophisticated editorial style, readable content will be placed beside this ornament. Square canvas. - -### Feather - -Use case: illustration-story. Asset type: small elegant quill ornament for a literary document reader wordmark. One single fine feather, curved stem rising diagonally from lower left to upper right, graceful tapered silhouette, warm pale champagne gold watercolor wash with delicate gold ink veins, restrained antique engraving style, no pen nib, no text, no shadows, no other objects. True transparent background. Portrait composition with clear edges, entire feather visible, sophisticated quiet airy appearance. - -## Updating embedded resources - -After replacing a project asset, regenerate its URI from its bytes (base64 with no -line wrapping, prefixed with `data:image/webp;base64,` or -`data:image/svg+xml;base64,`). Keep PNG originals for future design edits. No -runtime asset server or extra Cargo dependency is required. diff --git a/src/view/assets/blossom.png b/src/view/assets/blossom.png deleted file mode 100755 index 2e1f646..0000000 Binary files a/src/view/assets/blossom.png and /dev/null differ diff --git a/src/view/assets/blossom.uri b/src/view/assets/blossom.uri deleted file mode 100755 index e5d0db1..0000000 --- a/src/view/assets/blossom.uri +++ /dev/null @@ -1 +0,0 @@ -data:image/webp;base64,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 \ No newline at end of file diff --git a/src/view/assets/blossom.webp b/src/view/assets/blossom.webp deleted file mode 100755 index 35b7b91..0000000 Binary files a/src/view/assets/blossom.webp and /dev/null differ diff --git a/src/view/assets/feather.png b/src/view/assets/feather.png deleted file mode 100755 index 3e522bf..0000000 Binary files a/src/view/assets/feather.png and /dev/null differ diff --git a/src/view/assets/feather.uri b/src/view/assets/feather.uri deleted file mode 100755 index 998a243..0000000 --- a/src/view/assets/feather.uri +++ /dev/null @@ -1 +0,0 @@ -data:image/webp;base64,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 \ No newline at end of file diff --git a/src/view/assets/feather.webp b/src/view/assets/feather.webp deleted file mode 100755 index 7dd900c..0000000 Binary files a/src/view/assets/feather.webp and /dev/null differ diff --git a/src/view/assets/logo.svg b/src/view/assets/logo.svg deleted file mode 100755 index a279cb6..0000000 --- a/src/view/assets/logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/view/assets/logo.uri b/src/view/assets/logo.uri deleted file mode 100755 index a334bfe..0000000 --- a/src/view/assets/logo.uri +++ /dev/null @@ -1 +0,0 @@ -data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHBhdGggZmlsbD0iIzM0M2YyMiIgZD0iTTggOHY0NWw5LTVWMjdsMTUgMTIgMTUtMTJ2MjFsOSA1VjhMMzIgMjh6Ii8+PHBhdGggZmlsbD0iI2M1OWE1NSIgZD0ibTggOCAyNCAyMEw1NiA4IDMyIDM4eiIvPjxwYXRoIGZpbGw9IiNmY2Y5ZjQiIGQ9Im0xOSAxNyAxMyAxMSAxMy0xMS0xMyAxN3oiLz48cGF0aCBmaWxsPSIjYzU5YTU1IiBkPSJtMjcgNDkgNS01IDUgNS01IDd6Ii8+PC9zdmc+ \ No newline at end of file diff --git a/src/view/assets/vendor/KATEX-LICENSE b/src/view/assets/vendor/KATEX-LICENSE deleted file mode 100755 index 37c6433..0000000 --- a/src/view/assets/vendor/KATEX-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013-2020 Khan Academy and other contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/view/assets/vendor/auto-render.min.js b/src/view/assets/vendor/auto-render.min.js deleted file mode 100755 index 32a7dd8..0000000 --- a/src/view/assets/vendor/auto-render.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("katex")):"function"==typeof define&&define.amd?define(["katex"],t):"object"==typeof exports?exports.renderMathInElement=t(require("katex")):e.renderMathInElement=t(e.katex)}("undefined"!=typeof self?self:this,(function(e){return function(){"use strict";var t={757:function(t){t.exports=e}},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var i=n[e]={exports:{}};return t[e](i,i.exports,r),i.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};var o={};r.d(o,{default:function(){return p}});var i=r(757),a=r.n(i);const l=function(e,t,n){let r=n,o=0;const i=e.length;for(;re.left.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"))).join("|")+")");for(;n=e.search(o),-1!==n;){n>0&&(r.push({type:"text",data:e.slice(0,n)}),e=e.slice(n));const o=t.findIndex((t=>e.startsWith(t.left)));if(n=l(t[o].right,e,t[o].left.length),-1===n)break;const i=e.slice(0,n+t[o].right.length),a=s.test(i)?i:e.slice(t[o].left.length,n);r.push({type:"math",data:a,rawData:i,display:t[o].display}),e=e.slice(n+t[o].right.length)}return""!==e&&r.push({type:"text",data:e}),r};const c=function(e,t){const n=d(e,t.delimiters);if(1===n.length&&"text"===n[0].type)return null;const r=document.createDocumentFragment();for(let e=0;e-1===e.indexOf(" "+t+" ")))&&f(r,t)}}};var p=function(e,t){if(!e)throw new Error("No element provided to render");const n={};for(const e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);n.delimiters=n.delimiters||[{left:"$$",right:"$$",display:!0},{left:"\\(",right:"\\)",display:!1},{left:"\\begin{equation}",right:"\\end{equation}",display:!0},{left:"\\begin{align}",right:"\\end{align}",display:!0},{left:"\\begin{alignat}",right:"\\end{alignat}",display:!0},{left:"\\begin{gather}",right:"\\end{gather}",display:!0},{left:"\\begin{CD}",right:"\\end{CD}",display:!0},{left:"\\[",right:"\\]",display:!0}],n.ignoredTags=n.ignoredTags||["script","noscript","style","textarea","pre","code","option"],n.ignoredClasses=n.ignoredClasses||[],n.errorCallback=n.errorCallback||console.error,n.macros=n.macros||{},f(e,n)};return o=o.default}()})); \ No newline at end of file diff --git a/src/view/assets/vendor/katex.min.css b/src/view/assets/vendor/katex.min.css deleted file mode 100755 index 18778b1..0000000 --- a/src/view/assets/vendor/katex.min.css +++ /dev/null @@ -1 +0,0 @@ -@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:700;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,d09GMgABAAAAABr8AA4AAAAAMFAAABqnAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAARAgsCZwMEQgKswioXgE2AiQDfAtAAAQgBYkwB2gMgScb9ilFhbBxAEHgXHWC/y8HnMgQOkOZ9yIilmjBiFGLB6Wgda61ylHEir4Wxxl7sNM+3bmMN1fXoyprq19rVad70JFv/v5lBwS+IQMHi/FMses8tgwwh+l1phGSzA7Qzf9T13Vdurx0S2uIU3OrBqEBeMQepL09Ah/CrLK1mX3U7hCbqq29l20kFm3E5LVySCKKiCjUEL93mcoNoKQrZZQJst9uSnPZNG0516JJlXzrA9gAKw1QB9evdWcsjwfwHOpMXce7VbacB3TQeWBWrBKMhGs7Z33GEqBjMZXJUm95+Lja+103UARhs9plrcjOkiQS0HWYNon2QWCbLITEv7q47Y6lQKlnrSBu+v2mYP+zXcb3qvxYyiY2sbB1FbKH7xIWuHSWfy20ySGE0lXjcdP89G5Ri9oVEnCfmUOXI/cxC63DfdNe6cxKv63RR65Jd2OpvAISgEPIaq74Zla/SHKR7lx097vORS69obzwUpt7YXYAbJgGwAAYxk1QUADksbFUB65sghRP22evsfU/eJmMcgi9AcL7kVcAQMNf96lZCRT7J8Dc13cH/7Kqk7unTwLkB65/37nAzEHdqleK5AC2/5PejBjqGyUhLM8p1aEfJJf7C42xQFjddY6qecaYdcrNN+pgNCXq9Zed37yUEwypO66JUG8w/Da/bhhKvd5z9wMwAFeuFqKFM6BnbQHoxRuHoHEY7vyAYt4toBDOMWlTtT7vamMA3AEgVx2git5mAAGqPMgAgQ2bDDCoPYSHLilbgk/y3iZoqLRJlyMgbu4TCA+IZWiBnO53kHP0Ft6NGwYQy46dDG3cIEBk2/F1sPSWAZy6PelE6iwDshgcIaQjswqi0sSb1dQSzq8Cyd50Bu1m3a+BbjkDOMj6WzeV07HQkEmJgaOEsEvm2++EkqiHFoZPJanBlEUsGnA+RwOKQ5Ue4OwNoVQEl6gQCIm9yMwpAAUQ7AM4dwAOdmz0io5KuaTyIJxxpa94ljOaVEXaIACjSCIgdxEispUMNFBNQEJoCXSuOtC9BeatNkYAljOgeTcEMUv0qqVJFLev46AXDzd3HbSSGbp5UqQ+9mtMluYAJFtzflWHdXEsRgiOC0ei4Sn59GMZ6ACDEx3g8AYsz/CWCcDxuACoOgBYi0EvtSoDFPQabPbPEKmSoQYcZZka+Wr4JRwdo0dY23HDIGBuziifMJaAke0USPDqgqipUJv1EBhHZhGocTgyFwMOoF/Z2hfWPAG0ywhsdQ1siix3yOqSXD10YqPZyLjJwEGC3BZq8HoGLtoSROBwfiavk3kr4Erx3HJpA14EbnZOSGeI1KKmAh49xUqTZhD4hCQWNl1C6pXcBavB+wbw+9fcwsYh0KY5/CkFSMAAtyqkWANgxYIXJbYMCjZxjshdBWDKBDgckvK4JJBg45DZr3NLhufLMl+rAeTxwjkv4LAHrvfMLaC2LVieNgHC9xVAAlj5AVVPd0wIlQBXbzqQ3lINtrdgeYBlS/5UMjIk/XJBrLVAgOCCAVaSoC1iThy/IxlESEASM4ilAkGiIJAqGLwUAjJFA7lCQaHooFQYqBRjrj+Yhu8FWl7YdEw5wKdFY+quAZPaRO7rM41tevftQ6OgwInp9gOsHB9IbJYmeqOhGg01aKhFQx0a6tHQBw0NaOiLhn5ofSZQwVwwL+EhKVPpi5TYUjWKqXR7LYDSCHPpeMgKot7WSW1wmOQGv+2KokEAW3HfSOyWrcL7IVhLiaZJ7e5Lsn5gnrZdtS8I9CSBOcFQYi9brl8eYAyJxhtA+gfcreF+wZMpSJOUP5QQUEG9NGIALKZ+RaHIrxQZ7J/UAbI/d4owJEjSQDn1APhFMzwXh3Y8ywK5Xd19L8Lbzq6aXBzPEA4A6Ze4Bkh4FqafOBGyASYn9qLJExXR7p4jIqJ8FxNQo6xVJVT2llUdZ+4QsTHTIsvGxsR23CZOihrNmBtf9si6Fd/1it+cvgOhbxk0hnYz3SBoEt/xtqibBKalk2TchEnNwNkACu+Cs6N6WgsLZkA8Kq9PCwE041UgmTcqMCxKHXUTl4OSIRISJnMGLRMxF5MjbVERcLVK48k6kdkdrVKIqgi4MR5z6XIq2OhpB6HwupCJARrU3eZ+hCmiudWiL5Emnvu7xgTUTdzEf6ezxdjLWGcOMOVgGn5iMd2qXhdHheTJokMT0LNjX7yuV/fuNLHNmm/aBYRHy3k3EBEjtVOpHWO0f7IYUOawLEJcBKRl6mcEzA8gvM0BMXV5poJynnSTxiPhK2I/3dHc/lv0iplSo3726oIntSmbGUbChYS5wEIEhxNVs88wvKGkNssFJvlJ/YcdsNArF+z2kNILSR5OQQK0GyCU6qlA2FvSwNxwiymnJmoqoIXpYHaAtN5iUIlO2M6oVIDWQKNCrCruKEcCvAYGFYtHHArChMkJyKOAxQmp6kpVU6iuUEMh0zVuqUUr2Bp4VMhVxV31SMCngb8Ky26Hh27HQbfjotvx0O34WDgBup0QCydC96IYCUUiaRNpAFndFC3Jsl8YEAZyJKwKRQt2yhYM1SwUZRxrNwobN8pv3yFAhxil29PVHwQCj1dbNE5uNM5uNC5uNK5uNG5uNO5uNB5tMXi6MXi5MXi7Mfi4Mfi6Mfi5MX0/fowfcHP7UdmFQcq59xqjjRQ5/aHWnmDtduBL+3uMCgTmKI47reJHD8tiRwB+INoJEzaDCKRdemkBEdrmh3spgLSc077F04tNbkFDboJ+eqm1IC69tDHPvhPmmpKamDQmkj+E5d/4Tu6TA+FTshgqVN9jzhRQ8O9kvoJEnvuSBd0hmRUcqhM7QaUFWdtZkVnAf+3elkL9O63dwgMl4cY0C+Ga9QI6vGoo0KlCTsxGp28fSBlXcrNYcXiCmhQkHRUqPgVbYif8w1QLTj42Axp4Arkz5ARj4MXIUlrr0xSADOXlJqjRQMS/ycacPJS5iTu1EzN4cOwHlQho8hqNGqhQ3c9likzihFJs24Ayg/Rmdgy85r+/WknFkCKr+Pm+sNKpKVjSUmZKTvW4ZJlYzt4sUFTD7mPcR6BHYjp4LIdxDk9Oah8Xw3j4JFK6tBhysk8Di/Z1Ad0iFzCGeNSU1SsEoqRgqBl3UAYuy3u2kkVPCHBDYsXgERRFq7OP01h30cfqn5M0CfsB74e1Wm2WXMPyrG8YcYkUzGCW+IIyDYFqll45oEr9jptVdGS4XsHIPcp2tjR3FS82e+uui2RDSP5Tmg/hnByYp6kyhacU1MlUEwoO9mMb74D5qAuGP2L0nwYYgxeR4fn30xrpv/ByV2XyIw573p8UsbOvQ5TJnOQ8iseoF6Ln4Sg947thepyBXBWLalVaTlLzUOYAciwA+yeO2laJBLD/p+RGJikw1JuG2+p4DAUHC/4NocgOee3JA5Quj2oairoKy7DJNYYerONfC1Zo3tgIqnNF23Awhhf2D7cborglVYaqt35v7YXn8rb4hVSyaLWal547QfmF60CnGk4ZOJDV61yXy81HneOmx1olgQtbosSGg7q5dCUnUVEmp7H8UDT3fOSz6a05ieI9r15OV1icCmM1+50eX6fYpAXKskfunq8mk2xae0rPpwzbx4kI+cxSLl7j1lv6i7jCXFErDljKyvcDKjRwjyodC76gbZt5cpeaUNEpcgljGaa5fII6nhpsIpAntjLbZO3gvqbg23gz44+QAHcklfdHwB4tnDQrAqb8UuCuYJvHxszjgFFOu+t+3iu9qpqX5SffMMk5nGyUfSimdfGgqI74v2beFqNOKtx78sUUsUM13t6fZML60vi3JxyKl2jTJBxY00jTtJ/Pqo+ygk9ZvbxMU4XmaU1U7ZlPdT+qajiiQESACtzticug79z/CNBHrUdmUhRGnI5jZdd06X8LTT5OPkzSlDVvwPtl5MbbfPf152HUgU1g4x0mgHpYYMO2Yfb/fXxpDireE+S8K3PQQl+yYU6uS0XbbEoPFWpKJjVS8sCe/P9RaZWJnHw9nYsMhQKRUJnozkGl0p7a/YFdx3Xn5YDhteQxBU3VjPenHJ5VJ93MKJfk0Tp5a6r6awzxGr41c1BacXWsEvKhvv48TLcEag0H1l6hWJ33tMp13v99hWjkOLxdFlhU66EZJEfbrNyT11x6nAzLyN7uVmpNWVfeY9uyKGqjHZV6cubq2FXW8lx6oyjTil9O9EyW+GEn0mdHT9a6AYXwNrH2lDCGONxggJgUFi9q6i5ODyVS5x0Lij+eU2R4S65DXdDMbi7UAyXjUvMmjNKVJgd8bVlIrN6fpYzE74BrocLmD5PDtjxEXmdpKKPHwjgNDupAPuWrkA+8L2TMRKGiySdK5bs00G1UllCHyCmJGQK3fhD3KFMFXgcGy/7DnrsAeAvFfjlFLN2tbMB7Xc2WxIL/2S05F23Mz2X9u7iOz8otXgI5WM4ME2yGrV2H6RwY3GN/k28yRES1vOkdvYEtol44MsGL1RdHXPJdX61WF4vQWm320idYycUT1C1gU7XuWk1hVm+HgkkENnTuo8ntgsfcVGEj7A3SLfgdRudZ8CjygtoK+/Z3JAN5gomh4rCyZpZ2K5WOJWnG20H1OYUEwCrXNKPjGkddjXpiiYi0Z84y3UW3rH5/8O1U0CsRJT+Axq+T6IldZUHlOyuwDuByHWaWHb+u46AVpxBl9L/wdlJqB4Y/p9pqO2ADXso/Y+FqwRwhw5qR0rT6Ret7EKPz6Ih4ollMmudtJtYiabefJYu2qThcNhx6bsaeOKFA/Sx48otyEoSnTgEuaj6UjAvV5Pr+BifSrkRtjZ2eO7Mp6xIIHlpyAbPksZi8T5+fndCZKt/5wo/Obk08LA422lLpkLlUt/Rpm67w7d2nHKwPhZYZi8TV5vNeJ1AlAsPS3e9Jgvwk12PxTIEXQVwCZdeL4dnldeN4HdIqUZovD5dOa3uS4X/lsseVHabaKE7Y0llJqOWpvDdiy1Qx/c0qR7pxMIbgpvNvnHDQSPT9CIeJh1udKzMTnZ+mhM4I58bqV5RWxM1wudFMBleUAkUjqkZ9wvXjM3+hM0P528Y+d7DFU2Tmyyn64H5Tc21JVntGsi310neo9iVjBQ2EhZDQva++CVXcF3layeiqqEH1LNXQUP2sup2iTwuANGs1yvzPNnNLd/kPEgiE9DBQ/JKovgGGgfuul1Gc/CXZPSyIwy5X30y79EDXD1WYlqXJlyUIOV7Y28Z0H7ftn/jZaYkoTNEKDC1sWc+eP3lcJr1xAtuYU6xyXZNbdg9+lBD4d28OZp7OUGryH0hMqWFRWcFpGxQCLhP7zeZal5MW54m361L8qztdKFHbSXGZSMr/WT4a0MvfEe/9FKhX+Hodl3I5+CKkHqiCwYlkmqL0CBcaO3Y6bFi4EecT4Yd18fvWt7oC9JnCjNFQOmPkfTbTlcyXfspAgmO1OdnHTSe8VhVD8eiCqMyEmgS9aJl3hn2zo0fCZuLSct+VxhR3Z4d8uU8ydPpvBL/znQ3buicBE4MhVI4MdboSArMIHplwakaT8aK8d8fePsUti19lX2ECjMlCit3/aTk48+6D814Qaq5MAbNTV8L5qH+sxhSyvKl14D81Y1hkKT+7LLPE+qCVxcMc7A5ZDtg/UC9Icp4eu/cExWfCM0MX+63Vz8GrMQET1uowbfbIiDuWzdjS2BHoFmRN9McZ7dpFargNaKv3KtZUhOTfe05yiRBNmW5CHQSatOeD+BB+MsxwvyNGM4QmuZsAKwCGOGX1aydJ0Hw2ZYb7B1VuAy5S1XTm7eHf+ckgv9+/33uGsDBCUVyocbAqM+HDRUv600duBvKZdLs4uc5nRxkMBaYDuhXL6KwPQs/7mI81LfIeedcXiry1A2j8sLWtdxYC8zvTRfzXGdal8jzV+O7+6Mdb+uOH1cLgdKPuE8rW/fyjlQVJxaLIVFeU7vFXsgLhI8P2nGf/r2xPAmpLRJrCFJoz/ZlCkNEZ4xu/tQbFzy6CuGxVAbPOq95vg3mqIg3sSBPQVwrANbYpfqs04wkPkRli3/NjFf4f69oe5kqMw/qfQKmTmxtGXZcJrSheVV2xOXYr4bd5QebvfJKD2X0mpGayqBhTykDG9USYDml+3/JiWrJiv+oCW+71BvsdpUVg8aHy118Z2qTx8g6ui1HeVLgwtFhcIv7Avt3btylBysYh2Whj3umPYmW3tlBUfvH9ylEpyWGwvw/U5gsyjXv9CyjH7vy8Ogzaj0TZyniErP4W8ONy0HVnNdnO8HTvk4EH7n+WSIPSUrVjpvwgf0S5aISYTL/XEoBOT8iKxNHuCi82wYq9Wey84sC9vr/to5DRcRp9DXVaEpdXNHv7hbRsuCi/2oZifS0GlzR11HfD1WuaFfalQUMT4jEK82opF9MD3vTRaXHa2v09evclx37JgYpVJHqB6pSQ8lN9dCTPnXe/Jo3yZH4ueRsTOr6fz6Gr3ZY97sPBSwILE/npykHtNOMW09T6wDwM+hFmDbL9z8wis6177Ikin4khD4Lvs0CgAKqaRXjvAWOSsdKn2divG+wByXRqZ9h264JvZ6L55wuLBmtSxEneLfsOdxhckriwK9/GjS+mMGa9KTNhwlDORrcF5TFpuknns8yt25j1GDU3zyGItxftrh4nShK43EWJLanCscBIVtLUkW9BAY52KpMMGSXNPGuf+7NAyo36jUqoj36z0EpXYM4gx7hpj9ZFpUOiYD6E7+qclEPrcZ3Uelss12YrvKTfFfxu6Nq34YajchtKO99GerPRYH+QS7XAvyh08wZP9ZiS0tRUt1tcOk6TcTs3xvhr030BCzt1ZrI+KGC0MmBsb357SMKGqkzWY5XLWeFYRDGI5vEHCyMc/i7RFXWCuIJyih21aQM8HzZBM/zYnLrqZ7F+x1e12hIVjc8iCfy7wOOLHflARHi1oaDgiCEnud8wOlCcxVdk5xbUsxNvhbFMRMIbcLhUz9di+wyVaJeS/H707B+XSCbrvjuxVLRNwbQUfiSoDGXaEGDjsr2GsyoRinLQC5NOiPkmoXO5GFQoFb9W/JGfvKQ+Bd7Zr5FqMUfk/9L78lxMUYCVFeccuZ1DEpA0kiN59yqOVBdLEh0sP+dwY6K3cV4My3iSP7ywKXFyX3RWsjbq1IhaxGS4P1vt9KsQYz5BsbWT9VnXVaRI1RiY4O1B1gr5pHjmwbQxjniaFf1s5CcvHoP9y8/fH9bUAVVQx1lpqTZZF7uFxWHSxmuy+AnisK/sH0J5c3nVrZc+DeXT9C13gy9jHK522zedsXWbvkElLh4hcao3RAYHabzivlBnRM7+aqHaX6MVCxPMB7+IHld0SZ4VtOG5lWGrzpnwu20w8hdhNuzmhHQvfcPhstNLdcGkaKYowTQMavI7FjW53X6zf2LzOsPaTN47ydjoBcaG7+cJuCMcUeQlVDLA/UkWsaMw+/8MRp2EALdRTeULDsaEE8qbP5ESYdaXVuJRsCuIGSGcsnBPSkF1QWlGURZISFHFEHtP1K2w/G9nIxwuKhkgOQqPX5c0o6uGNxbkFg7tLWxZWLja0YbBOjGScVtA6OKFye737J9AzYOQ1K5NXuWRXMWnMsKW+mUWyj0SmkuqJFvOga2LJ3xVhkAJ9M/sT3lJsC54lf4jUTyJLeZkDRDl3IFyO1GmyNlg4KCuWlEnn0Cg4x5ruNKcuaIZG88QoDTw1qLSk3wWNZVDcIcV0o0ypc9vzITwWTnzaSC9mDEQe82H1v+9ldmHbYUFycLPf+An0ZIZKJYWCtLHZ7cm9vBZWjncC+saN/4tlu6X6WetCrs7N+8mSJ/St+4kdxOEZieRLGag1p1rdef1SFhgAgMaN7TWtGAT1wr8xmJLhbojWXRq6sF45URZ88Kvm5pT0hbU9VowkVBmcRjEIxId25VI25g5nBn7N5JX44rgfV0c1z1t4azjaCAbJ5ZvnTs0rd/yfhsmju4e/LGmacI76SQnIxWX6/Tray4+3sRn0pE5yonxj0GKbnTjLszhOHyfTyYWt1TXrQHZH44IYW44gM+WorTFQN+EwU6Pi4qsY+TQ1ULmyuz3y7MINgOSif+ITi8mF6lDaxn1uFm5KgUFHoB5dDacCO06khoXLYZs/ociVKDoEKLZEYfdixjTUYzQzhI6TKijuNohCCWgzriiRDaoY7Q6D9R+gGYAOowVOtVCm5k610fzQR1E076QE6kjMN9/HAFzaK7J93mYroIT+RvGgb8EAMA43brzr6uNfsxOpBMWhvmY0DS6MVOgGDkAtf/f08jmd9mJqPzNJjrAFfx9EfCcskVUcQCiCQNk3Mz35G8vR8DS8PLOj21n7m/KDqLeAfIF5WeTC+84clZdzUxk5ci8qevKH6ol3WvSbghqLVVP6Pwd5gCg0hc0vXRKzJvj9YnhbAxdYGCLAQDAZoBsIkht80QI2+WJsGwPJyJsp51I44z8XdHxiaxGV6y8WbaghwMu7ToM6tKoXoMeFINqvjKxsbBaGKOErWVpilutbh1uy5hjAtZyteAAwyYNx2niYLRVENo5BbUe4xibeNSUkVaDUjTMfahQBZe0mPVip0cHN55JtlqDewH25KXjtWvT88pd3ta6taYkXmk4yuwejLsdrcn5qu2Cy2lPrEycIxTuObgO5d5g2410tQFk+5Q/nnYmgXzpOVABOzJXi9T/MGLSyhOSBk2SB/QidP+QaL5EbslxV7Pybp7t5gFwQKn1awzPUgDbbli5T8yrQRE9JSWdR+v2k0ulWcPlSnfvNsY5CtZx/4FdPqVYELYaSuzGGuy1NSFZKkhbayRJkhqqGTp0Nnewe6ohDNiGAvFNAW7d/QjFo8/bxhLrrNKyKwWT9TiuxcqSZT3C4ZR5kTsCm1mtWzWV3JFNtKYgelqA//ibZYiXqhtB7l5ydKqy6Vb9R/Rl09LR82Hgy4+/AEYm5hL6tW0CBQkWIpRdmHARIkUdRO+tGi33X1tUygu4vu4OgOD88gv8m32jPgDQ/+4a8nsz/0ogIL4ZRboRbPmBHWPMTBWG5gKnfCMY4D5rddbudr/jvVAONcpQPY4BG5rYKGXJ3OVOYpOALXxm9eUEujvRITYCsv1eeHQ6muad3bXklVbTAdwFAAA=) format("woff2");font-style:normal;font-weight:700;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:700;src:url(data:font/woff2;base64,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) format("woff2");font-style:italic;font-weight:700;src:url(data:font/woff2;base64,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) format("woff2");font-style:italic;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:italic;font-weight:700;src:url(data:font/woff2;base64,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) format("woff2");font-style:italic;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:700;src:url(data:font/woff2;base64,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) format("woff2");font-style:italic;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,d09GMgABAAAAABRYAA4AAAAALRQAABQBAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAgUQIDgmcDBEICqowoRYBNgIkA4EeC1IABCAFiQAHgiQMgRwbMycjEXZztMJT/OUBT8ZvqgIwIbZlhOVRe5/Y4TgOVm/26guMVEV+hCSzx9O2ft7ukikmSyhLL+AhNmAmWIHeF87oyyi4/NktATDObmBpQqkO0XGZSf5Woc5WoP4HGIc9v1xv0DrMVJGay0kidb3pvFxg18l2T0BGVkUSqOrh9sU0W9oBQkuW72GnqAI0AYKjV580ZSBCW8pFlbACq2yAdAEyoJ6MIAUl/9lF7aK+rhqdIUkCYlX6/79Wad/9VbUMdjlEHkgnwsaYP6+65tT/v5sDVcMNgz0nW9W7YeSeDhAqVnt8TjQeDyRJmMhNLDsdFyFcpM5yOPrRK2x+f6/1Zlt1xUpMECYMsfVK+7xHARg+gbYBAwDbgN0LAJukS0YfgiOAgVjjMoAfxPDtd/B8aodFfeBFlpk4OePRGqnFO0mArZ04iM1INxduUXJo0HIiAdGQQtbvIhtIRnYdFlrsGPY49i6OayXaBK1N+4iOZ/jKhJkIE3NmJgASxa4NPxHTilZv1j6oYxu+NME39+4i7w1bbTH4X8l/zv8E72Pv/f3e1++1vKd4M/N13eva1zWAQPzD1PAoQICn0Isi6/9g7G4d5sP3QPoy1Fs6kybwChb5P1sGpBrqibEWeAOo3RZUmLwDATI/c2BQq9aBQ+oLfObWiO8go6TkCzbT8SW1m2A8OBf4DsZOriFuz1usq4vJo+k8sG3xVjg7evBAQkx9K9Npxe0pcBtOY6vUrn6JiOEJBUOSk6T09J6qkVp48BYi+95SOsresAfzKFjwiHs/giVummaj9rahvHsejzzoeYtSoJhrqOippErQmsbTgxE5k2ZDwRBXJVmTCM2VhZvcQYrR0AAs4HMI3AfgYqms6JsoUmpTLvI/sQxx9/GPIWWMdY6gFGMcFF8KlFQfHQxITyAi1wKLOwGWe9jujbXGcu5gJl0mSgOFVXrR4UEnzSD4ZQDkaxFG2448dUpD/kc1Fbo3ILLdkHZM3otBo42C9yEkbdjxArojBwtw+KaFrmwTe2iOexXAfQYrz0DVsR1YbQcHQnk7Qg7/EVKKmxLePGoWUndyd1y0nDFhz7+244d4ux5PSb6r+0ZJAUJEkl6jK6ROeR6W87IQchlv2gLw0CW7PR0QgZUc+lnA7s5IyMOKXAhGpPtopL41auNr6xChYF1H9KmLDjHWGhFEXLPThAP3sccq3ENcdEhA3dTUlX+EVI2uQMIkTbcROUZaV4r1g1CIuhufIujouUyyym5Y31/njF0t2YJyFJjqHPpS2BhUeCQpAgQLX0QziLcJmlMBj51hTmItRPhmg/VeFLetmpsVSYPijjK66mhExAFi0NTbjZztkUzeYwGRaRdEYKdFqtuXTYGRAl1HBwGpe+khdI/AgdxL+qtaGJXJkRsj3nseSP6gQUWRDyQ2puUn0aFEgdk3jjgiEKkERvECpwRBUKJgUJJgUrJgUYpgk1pwOszQItwmzHz9IKhUoK9L5pgOi85wpf27ZuvwNPvvCiMxgihFWwEVV2uGXUUJDQxaGHQw6GFIhSENBgMMFAxGGEywsg0yN27JHk+ocukoazqZlSSPrXL7aGBPnxum7XBAZCAlLWme0uv7HsdpwwE5E6tSEfYd1d3t4WgXhs72wvsYa9KVpD2OLKdDvtBvn4UR2J8jz8cPSoS4tQRzlyC2U7igUyVdZyO+QtyQORlEEQCsHyBHBqo7cw5PhyKIQ1ODTBRM5p5JJQPAL5m+1WbDib9POUs4MTaC3Lce1dmbrx1ZAOaIcw8R2dWuX/hyAI9vThubi8w1Hrc22QWpllsITPcmLUL3jWWb3rtwQdikGTiQTS5Ff7utcimNzizQfqrHRbAY+JaXeDTdAsFUKwzmujZxuWySTre73TQMs8rMEJn285RRuOyDBXJ9HW6SmVZQ2leJFGFEBrup2wKRhSJC4dC7ne7CY0905DCyAhGBkQU6NzUwPLcAF+X3PffNpUznIdwhJfiW8ioeQyVzak3zulNgZCSEGdK+Vt/BJHK5uzXvlUz7yN9nPp00s6bT25zdHHhzpgMvVM1cSlA/jmHH7MUgc7EqtM680azVt+E9s7P/fgd72OwCF4Cs1G+0EGSnhty50o5g4+kgVUVW0HNUVIC5Kk1m/A9m+O4TwOPUV2O3VDrlJV6Mwu0J7/fykb1UDGqZI+Ob2TnndMrYqtnURrJU0gEbb7hRpZLcN7U655h2lQiUJWfP/nwLl7l/ozvC3V435X0VKKBcjoxUrASZiKruCuZ6KpX0G13BWb4a4zpHFROrQQtSXFArlOpGIUG9UN2ARIloZKDAKCQICo034QIECjKaLaWW0UjQaqluQwsk2oWKDqGiU6ju8owi0Y0j0YMj0YsjHUKiVPThFEz9rppmW8jcQQ6F1gDLFB6NABELmTnAgEEL0dBoBBi20MIRSwxy8mhGVbmol7HH4NPjqXcn8PsT7SRCjohOOsiachBNbw65rjHXzsU8O9fMB/eABd6BFjqIFjlILb6G52GJnYeldh6W2XlY7gGtcBCtdJBa5YfnY7WdjzV2Ptba+VjnAa13EG1wUHmj5Rrv/W0kyky8RmD0/pt1mkRNS4vfHGX3R3F97bx79m1YAQGamUkEYhRlRK07mAWYVwA4GSBGsWEMBvuF5hsNgCZigK8TmogDox4GiCDiE4VsEbu2Qka7ahqVlZwPq2hRyFOS7Q7mNhNUKWphCl8svJdsqVgidbhuzAzcHreLcFt0QhDkXOSgjC/E2ABB3hh3ts0D+0wiM4yLIiyA4GyAlIUZv9P+/s1vjbHbXoKylWf4RSCaiN6WYIAqGJwQSDHbwmyGU2qaE8UVBHFygiDFXFR/KopYHde3Vmbcx1lfHkvoeQbXl+bztRnGFNDkg1F5QAIBcqJBHvxCCC1CQU0oQFgGXp1uDCDXldJfZ1eqydaEdV+uZgt4oUsD0Qu2fLJKBy3V8nkq/Hc/NLvAn/dzP5/LmYte61N/KnLsObfGPj8JjqirSD0FU39j5jUqnkDKuSM4LT6cXkw3OI1/n5tlnBtKZ+U5UiteWuNmWKSCX2ZpTYhlbK5f6w9bWj9PxisFxqAEZ87JO5fabVNtu/7aiI8Qgj2B0cXuu0erKB97a7uycklJsq5dw1rxJEXMRS76aXeJ3qOGHBf4zEwf+/j1iVgHwdHHmYWSL/zax3eYdC7az2SS4bS3aJqkEbJ93PbqqHF2zNjvF264FF5ovbBNLDP0VWz4/7GPr+zwT/2xn+O0GCzeQOo1KFcya2sMKfJCkKfcxa3ww3LRN0i5AfJtnL5q5Vf7GIWlZdcQBhq+r1tywfrvCyEeeEE+gd+vzBzWVJ+pkmLxZey/w4Wo39nGLuw/6aThPUdq1if5oKroXYTDU97we2SkiX4mJ9UcSO+PHLynOKuIV5DqYy9fZk2k2lvAs9YJqdleb9NMTSJfl03vhuqrQBCtrftcEZAERVh8umrFpvt6/it/yP3u297PnEMqyPNAt1nc8gXuY59kr+P01d7G+3RSUh1TkKaAN15vEc2fJZE9+BypEc6td1Hdbb5/W1IGqJLAcgUlQglXMHj5kpVgDLdciBs4NQSU55MmbdoE1kj1cZu3Kcvhli3y/Hlmx3LUDCzWWaKTlwN2b3rsrfqBmuGu3xx9/1Z3WaSGUcgDg9IvJoiD/EzwUJ6P3EH5P/7wX+AfpL7qYy0+7G3t0QfT8rNBFYjykZcQa1c+A6G18FocPd2+9BgAJuvCyiKnZKnUjvd24t6PG2HKTKTxJ6AIwziWc9xBt18temdS2JHa+DexT3RyedhBsS9d+v5UD2X01mkXqZvAn7QIX4zpqM3+zoK/z8azPADpvONXgRimkfoJISCqdRDUIUT+D+sdspegfJ1nGEOZdKy2a9e9/YPug97AM6oQfh5vCYDqMF3a/VIfKP0oJ33v3yI4hVpqQ0MOZ8wJ9AYPJPUH9/5N7Xbd/eEHrnsbnC/fSArgxHMv/vGaesYro54DLH2cPSEQYMd89P6TEQhDbLhPlub/7zXNnx/cB1VXdUoe9fobWqNkIy69+ZThg3XAYn3hugHM4zdc8NOoKk5s1FGvv01wv+fxW7QzWwNEVLi+mPx/DLT7gEBw/VpeygTNgefhp4SSYU3jgHOHW5WxY8CpaRwuTYAf9ZlwIBdD8so2z7nTYzxhQCjQj3d+XuwQFsfDj6Z82GwFpGyK+Kj6HTcP5CZPIbDanG+CHxKExcWOzzvH9QJgTUZEhSLBo6+9X+uWlhb9+BWTWVB8oWSlni/Qr/x/Z9DLbWF+9WORtLTW/f5rjwqEASHH47zucNfU7uDDm4kxq/fK5o9PrhyjLcXmrTQHnoOfmDtqat2O604P/HIX+mIVjp3AsVeKIZj85awXP4GhR2f9VQD2DwlVyJ1zfxv5Wyytuibp0T/IerHYULrUETStsVTZ+bf8HeRnGhe4xnDdK3e9Ad3+SPypDGnjGq77Rzd3cXwFdfu3dmg9HQld3LyhM6PQ5s6VioZO+7EZY/94Gm293+5U/+vAH7mhaW3NXPO8uuIjPTVE1TW7Rgqe4WM20M+fn6dAuKgFvXJeso5ZJtmhq+8pz6FSs09mHmiG1lQdC5Olxa3e5y3l2BDyNW973FPFGRQqIHc2mcmXagjN5zeUsyV8eUH6PcfMH8l/XyvZPJqZfdpn3NrAFH2Sdux/OPOpuUrq1CU8+K42/a/E5aY/WiSrVYoGZZ11lbP2M5balesjk15KjJtRVap02r2ar6QM8Z9kK9lieDp5u+pAl34pUi9R+PUjdz3vteYVqJNenPgZuv4NJ4oL+BfwDwu3UCEIuipTy63+hvVTtejHwXw/g7sxsNS41rLL6QtRJLu3hxU3rnk6Y38FUZHaYi2qa7D6PxzyWplZF7Yc2GeB95dUfLg0HL9U2ipn6G++5q2JBb1BWbDK2Y6SSdVKq2nNkhIFM/leQaV1KH659t1F8Kf8ovZ+fokafL/bZZcVKW9Lnyp6ugzFN27XPZ0if1bOwqmkWUrZneqkN6RJgUQlBvjEKtkVhfqpDNWr8/viJ3ehr5IVl2UsTDkUkT6RlPyV1PZ9ozBiQB5uKtOj20QjjWXu7sOC5kqot/QdJ29pT9P4vQ9wONs+efVUWVH8kGHDddYI54F7cfq09haJPwFPcOMe3jq9dADwlVvVZ6SSmzMqX+vgKDvxKLktaRXlW3aURpxzLZ8GeIfqj3SF5Wv8Jh4JE9Sub82rV3+otesUN7ty/7cu+CdQjEv/wcPIvzB25eBEQuFKkeD7eNa1qKGn85NA4NoTvcrivs8TnexLTRRGrrgzHFZDrg8GxS5eu67kvMgTD8KtO2/cEN64iV4/GGR8jr5qyz62QhB2vDN78K2ynacnU0fy79q54NCKJ+LTR/XX4pTPV+zevtm7FhxZFSw65rI3RJWrxxZGsk4mt3Ufrd5UsvCXE0cEkuQkxxCn29JvO3zaGDYPT5w9JV5cMV2sKqf8lENjoD5ntebzRQrPn5sfBg3Y9eaY4R9Wyv1VfCTbppMQtQaZDGGIhfMXLXyzt3xZp2TX/oZthspXhS6KN+tRXsxQG+G0m4M7O7bwiqtibyDjj57hr+raSASbIpGHxFAPExuXt6UUL1uOYcyFv/ivoY9Ub9qxc5xYvszx8OKNqKkpPL4bWv8JbGC+ojlw8Msv0YqVCJv117zKPQKHx7FbsKDyr9Saetkf6bKf0d6kscFweJD8OSJRX3pczSIV4UiQV/pVUvJbpbxgJKwgWerHL6klkZ9JNPt3TWvw6Sn91LS/+qdpubykE6ZX29dsXwzTgxL2Og5/7n3mKXh7QXMGRBKtb7O9de7eLlHOb2wR/uWkZ1Hu8IPS/fwr+/cE615GLQCwATOVoux1QWvUoxnx/yJW71oMGPwNThiJqujvIhaAG/e2dSEzeAJvwocE7gFx8CDMBUZW8C9nWknk/pWFWSrif/AUI6cgoxsdCVogI5zjR0Q9rmI/mmBmUAwfZsRSGIJRPy8Q+QI8jJbVJT2Lch8wvNho8yCAkA9i2xwYhwMiOJ5OeIq5CJROzMVACHfOxaHY43MJSAvw5zLAH3Duk9k6V4DNRpOvpBDSQ29DgRGj5hsXdocBk0iUECOSE42WySorR1iUVKjfhIEaLmiQAf0qBKsWpDI4cTZc99Md0uFRFUrT4xq+sEdf7R8yX4WAxlU269IgbEG/U73+cE9TBvUYV2zEsElJjXdNvydjo31CspCO9sO63CuwKiiZcSaskdDBBlQ2VZOHmq1UUyEcMXCkhmM309irpoeNi5H5g8qyZGetOeY+9dsM6QnhgAhpn8fG0N8kj7FEu+U3NQe7r57Frv2HFly9CZMzJL9mglU1DTv7kOVcJqlaj6E9VEKutFYuNLK97wlz1UAxW809MJ4icWqQmBB7mEAfpkwfCUPSMv0uwjKVobXGqMGu3O+70g0se6AmkjZ6u++9n9Rj2ptwVU3sNbhPkhnT47fVp05RnZSFW6Rw0qhX9rd1Qqh4UlST0dgoZAa5vurb1ShWaVjAQGzszMqc0tRfM993wAM+SOXJ59WpO4DBm/AWwhEBBxAD9sNpOISYiIXYiIO4iIf4SICESITESIKkSIbkSIGUKI41NRymaR8tXbuLdnImw4N9/f8Zk9UVp9NBw1hngVNoF40toB2H47RcU120x8l0fJZ/akaRx8qc6qNpx+E4nfR7c0PFEzxZ3xxDaEtLFP0sucNRDFj+GIAJ1so9510AwFtK2AAHKLzWo3V1zVHvumYl9Qmq5U42zFmv1E6MGZaRu9nLABHqzUKNzSxuOQZC051oZvWIzTGsU3vL6GNCYRUA) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");font-style:normal;font-weight:400;src:url(data:font/woff2;base64,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) format("woff2");line-height:1.2;text-indent:0;text-rendering:auto}.katex *{-ms-high-contrast-adjust:none!important;border-color:currentColor}.katex .katex-version:after{content:"0.16.22"}.katex .katex-mathml{clip:rect(1px,1px,1px,1px);border:0;height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:-webkit-min-content;width:-moz-min-content;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathnormal{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-style:italic;font-weight:700}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathboldfrak,.katex .textboldfrak{font-family:KaTeX_Fraktur;font-weight:700}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .mathsfit,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{border-collapse:collapse;display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;position:relative;vertical-align:bottom}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;font-size:1px;min-width:2px;vertical-align:bottom;width:2px}.katex .vbox{align-items:baseline;display:inline-flex;flex-direction:column}.katex .hbox{width:100%}.katex .hbox,.katex .thinbox{display:inline-flex;flex-direction:row}.katex .thinbox{max-width:0;width:0}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{position:relative;width:0}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{border:0 solid;display:inline-block;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline{border-bottom-style:dashed;display:inline-block;width:100%}.katex .sqrt>.root{margin-left:.2777777778em;margin-right:-.5555555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.1666666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.3333333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.6666666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.4566666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.1466666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.7142857143em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.8571428571em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.1428571429em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.2857142857em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.4285714286em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.7142857143em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.0571428571em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.4685714286em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.9628571429em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.5542857143em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.5555555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.6666666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.7777777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.8888888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.1111111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.3333333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.3044444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.7644444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.4166666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.5833333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.6666666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.7283333333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.0733333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.3472222222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.4166666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.4861111111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.5555555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.6944444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.4402777778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.7277777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.2893518519em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.3472222222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.4050925926em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.462962963em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.5208333333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.6944444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.2002314815em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.4398148148em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.2410800386em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.2892960463em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.337512054em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.3857280617em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.4339440694em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.4821600771em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.5785920926em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.6943105111em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.8331726133em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.1996142719em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.2009646302em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.2411575563em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.2813504823em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.3215434084em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.3617363344em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.4019292605em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.4823151125em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.578778135em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.6945337621em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.8336012862em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .accent>.vlist-t,.katex .op-limits>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;display:block;height:inherit;position:absolute;width:100%}.katex svg path{stroke:none}.katex img{border-style:none;max-height:none;max-width:none;min-height:0;min-width:0}.katex .stretchy{display:block;overflow:hidden;position:relative;width:100%}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{overflow:hidden;position:relative;width:100%}.katex .halfarrow-left{left:0;overflow:hidden;position:absolute;width:50.2%}.katex .halfarrow-right{overflow:hidden;position:absolute;right:0;width:50.2%}.katex .brace-left{left:0;overflow:hidden;position:absolute;width:25.1%}.katex .brace-center{left:25%;overflow:hidden;position:absolute;width:50%}.katex .brace-right{overflow:hidden;position:absolute;right:0;width:25.1%}.katex .x-arrow-pad{padding:0 .5em}.katex .cd-arrow-pad{padding:0 .55556em 0 .27778em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{border:.04em solid;box-sizing:border-box}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex .angl{border-right:.049em solid;border-top:.049em solid;box-sizing:border-box;margin-right:.03889em}.katex .anglpad{padding:0 .03889em}.katex .eqn-num:before{content:"(" counter(katexEqnNo) ")";counter-increment:katexEqnNo}.katex .mml-eqn-num:before{content:"(" counter(mmlEqnNo) ")";counter-increment:mmlEqnNo}.katex .mtr-glue{width:50%}.katex .cd-vert-arrow{display:inline-block;position:relative}.katex .cd-label-left{display:inline-block;position:absolute;right:calc(50% + .3em);text-align:left}.katex .cd-label-right{display:inline-block;left:calc(50% + .3em);position:absolute;text-align:right}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{padding-left:2em;text-align:left}body{counter-reset:katexEqnNo mmlEqnNo} diff --git a/src/view/assets/vendor/katex.min.js b/src/view/assets/vendor/katex.min.js deleted file mode 100755 index f59062a..0000000 --- a/src/view/assets/vendor/katex.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.katex=t():e.katex=t()}("undefined"!=typeof self?self:this,(function(){return function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return Wn}});class r{constructor(e,t){this.name=void 0,this.position=void 0,this.length=void 0,this.rawMessage=void 0;let n,o,s="KaTeX parse error: "+e;const i=t&&t.loc;if(i&&i.start<=i.end){const e=i.lexer.input;n=i.start,o=i.end,n===e.length?s+=" at end of input: ":s+=" at position "+(n+1)+": ";const t=e.slice(n,o).replace(/[^]/g,"$&\u0332");let r,a;r=n>15?"\u2026"+e.slice(n-15,n):e.slice(0,n),a=o+15":">","<":"<",'"':""","'":"'"},i=/[&><"']/g;const a=function(e){return"ordgroup"===e.type||"color"===e.type?1===e.body.length?a(e.body[0]):e:"font"===e.type?a(e.body):e};var l={contains:function(e,t){return-1!==e.indexOf(t)},deflt:function(e,t){return void 0===e?t:e},escape:function(e){return String(e).replace(i,(e=>s[e]))},hyphenate:function(e){return e.replace(o,"-$1").toLowerCase()},getBaseElem:a,isCharacterBox:function(e){const t=a(e);return"mathord"===t.type||"textord"===t.type||"atom"===t.type},protocolFromUrl:function(e){const t=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(e);return t?":"!==t[2]?null:/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(t[1])?t[1].toLowerCase():null:"_relative"}};const h={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format "},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color ",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:e=>"#"+e},macros:{type:"object",cli:"-m, --macro ",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(e,t)=>(t.push(e),t)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:e=>Math.max(0,e),cli:"--min-rule-thickness ",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:e=>Math.max(0,e),cli:"-s, --max-size ",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:e=>Math.max(0,e),cli:"-e, --max-expand ",cliProcessor:e=>"Infinity"===e?1/0:parseInt(e)},globalGroup:{type:"boolean",cli:!1}};function c(e){if(e.default)return e.default;const t=e.type,r=Array.isArray(t)?t[0]:t;if("string"!=typeof r)return r.enum[0];switch(r){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{}}}class m{constructor(e){this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{};for(const t in h)if(h.hasOwnProperty(t)){const r=h[t];this[t]=void 0!==e[t]?r.processor?r.processor(e[t]):e[t]:c(r)}}reportNonstrict(e,t,r){let o=this.strict;if("function"==typeof o&&(o=o(e,t,r)),o&&"ignore"!==o){if(!0===o||"error"===o)throw new n("LaTeX-incompatible input and strict mode is set to 'error': "+t+" ["+e+"]",r);"warn"===o?"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+t+" ["+e+"]"):"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+o+"': "+t+" ["+e+"]")}}useStrictBehavior(e,t,r){let n=this.strict;if("function"==typeof n)try{n=n(e,t,r)}catch(e){n="error"}return!(!n||"ignore"===n)&&(!0===n||"error"===n||("warn"===n?("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+t+" ["+e+"]"),!1):("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+n+"': "+t+" ["+e+"]"),!1)))}isTrusted(e){if(e.url&&!e.protocol){const t=l.protocolFromUrl(e.url);if(null==t)return!1;e.protocol=t}const t="function"==typeof this.trust?this.trust(e):this.trust;return Boolean(t)}}class p{constructor(e,t,r){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=t,this.cramped=r}sup(){return u[d[this.id]]}sub(){return u[g[this.id]]}fracNum(){return u[f[this.id]]}fracDen(){return u[b[this.id]]}cramp(){return u[y[this.id]]}text(){return u[x[this.id]]}isTight(){return this.size>=2}}const u=[new p(0,0,!1),new p(1,0,!0),new p(2,1,!1),new p(3,1,!0),new p(4,2,!1),new p(5,2,!0),new p(6,3,!1),new p(7,3,!0)],d=[4,5,4,5,6,7,6,7],g=[5,5,5,5,7,7,7,7],f=[2,3,4,5,6,7,6,7],b=[3,3,5,5,7,7,7,7],y=[1,1,3,3,5,5,7,7],x=[0,1,2,3,2,3,2,3];var w={DISPLAY:u[0],TEXT:u[2],SCRIPT:u[4],SCRIPTSCRIPT:u[6]};const v=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];const k=[];function S(e){for(let t=0;t=k[t]&&e<=k[t+1])return!0;return!1}v.forEach((e=>e.blocks.forEach((e=>k.push(...e)))));const M=80,z={doubleleftarrow:"M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",doublerightarrow:"M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",leftarrow:"M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",leftbrace:"M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",leftbraceunder:"M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",leftgroup:"M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",leftgroupunder:"M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",leftharpoon:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",leftharpoonplus:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",leftharpoondown:"M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",leftharpoondownplus:"M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",lefthook:"M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",leftlinesegment:"M40 281 V428 H0 V94 H40 V241 H400000 v40z\nM40 281 V428 H0 V94 H40 V241 H400000 v40z",leftmapsto:"M40 281 V448H0V74H40V241H400000v40z\nM40 281 V448H0V74H40V241H400000v40z",leftToFrom:"M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",longequal:"M0 50 h400000 v40H0z m0 194h40000v40H0z\nM0 50 h400000 v40H0z m0 194h40000v40H0z",midbrace:"M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",midbraceunder:"M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",oiintSize1:"M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",oiintSize2:"M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",oiiintSize1:"M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",oiiintSize2:"M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",rightarrow:"M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",rightbrace:"M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",rightbraceunder:"M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",rightgroup:"M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",rightgroupunder:"M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",rightharpoon:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",rightharpoonplus:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",rightharpoondown:"M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",rightharpoondownplus:"M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",righthook:"M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",rightlinesegment:"M399960 241 V94 h40 V428 h-40 V281 H0 v-40z\nM399960 241 V94 h40 V428 h-40 V281 H0 v-40z",rightToFrom:"M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",twoheadleftarrow:"M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",twoheadrightarrow:"M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",tilde1:"M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",tilde2:"M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",tilde3:"M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",tilde4:"M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",vec:"M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",widehat1:"M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",widehat2:"M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat3:"M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat4:"M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widecheck1:"M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",widecheck2:"M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck3:"M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck4:"M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",baraboveleftarrow:"M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",rightarrowabovebar:"M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",baraboveshortleftharpoon:"M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",rightharpoonaboveshortbar:"M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",shortbaraboveleftharpoon:"M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",shortrightharpoonabovebar:"M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"};class A{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return l.contains(this.classes,e)}toNode(){const e=document.createDocumentFragment();for(let t=0;te.toText())).join("")}}var T={"AMS-Regular":{32:[0,0,0,0,.25],65:[0,.68889,0,0,.72222],66:[0,.68889,0,0,.66667],67:[0,.68889,0,0,.72222],68:[0,.68889,0,0,.72222],69:[0,.68889,0,0,.66667],70:[0,.68889,0,0,.61111],71:[0,.68889,0,0,.77778],72:[0,.68889,0,0,.77778],73:[0,.68889,0,0,.38889],74:[.16667,.68889,0,0,.5],75:[0,.68889,0,0,.77778],76:[0,.68889,0,0,.66667],77:[0,.68889,0,0,.94445],78:[0,.68889,0,0,.72222],79:[.16667,.68889,0,0,.77778],80:[0,.68889,0,0,.61111],81:[.16667,.68889,0,0,.77778],82:[0,.68889,0,0,.72222],83:[0,.68889,0,0,.55556],84:[0,.68889,0,0,.66667],85:[0,.68889,0,0,.72222],86:[0,.68889,0,0,.72222],87:[0,.68889,0,0,1],88:[0,.68889,0,0,.72222],89:[0,.68889,0,0,.72222],90:[0,.68889,0,0,.66667],107:[0,.68889,0,0,.55556],160:[0,0,0,0,.25],165:[0,.675,.025,0,.75],174:[.15559,.69224,0,0,.94666],240:[0,.68889,0,0,.55556],295:[0,.68889,0,0,.54028],710:[0,.825,0,0,2.33334],732:[0,.9,0,0,2.33334],770:[0,.825,0,0,2.33334],771:[0,.9,0,0,2.33334],989:[.08167,.58167,0,0,.77778],1008:[0,.43056,.04028,0,.66667],8245:[0,.54986,0,0,.275],8463:[0,.68889,0,0,.54028],8487:[0,.68889,0,0,.72222],8498:[0,.68889,0,0,.55556],8502:[0,.68889,0,0,.66667],8503:[0,.68889,0,0,.44445],8504:[0,.68889,0,0,.66667],8513:[0,.68889,0,0,.63889],8592:[-.03598,.46402,0,0,.5],8594:[-.03598,.46402,0,0,.5],8602:[-.13313,.36687,0,0,1],8603:[-.13313,.36687,0,0,1],8606:[.01354,.52239,0,0,1],8608:[.01354,.52239,0,0,1],8610:[.01354,.52239,0,0,1.11111],8611:[.01354,.52239,0,0,1.11111],8619:[0,.54986,0,0,1],8620:[0,.54986,0,0,1],8621:[-.13313,.37788,0,0,1.38889],8622:[-.13313,.36687,0,0,1],8624:[0,.69224,0,0,.5],8625:[0,.69224,0,0,.5],8630:[0,.43056,0,0,1],8631:[0,.43056,0,0,1],8634:[.08198,.58198,0,0,.77778],8635:[.08198,.58198,0,0,.77778],8638:[.19444,.69224,0,0,.41667],8639:[.19444,.69224,0,0,.41667],8642:[.19444,.69224,0,0,.41667],8643:[.19444,.69224,0,0,.41667],8644:[.1808,.675,0,0,1],8646:[.1808,.675,0,0,1],8647:[.1808,.675,0,0,1],8648:[.19444,.69224,0,0,.83334],8649:[.1808,.675,0,0,1],8650:[.19444,.69224,0,0,.83334],8651:[.01354,.52239,0,0,1],8652:[.01354,.52239,0,0,1],8653:[-.13313,.36687,0,0,1],8654:[-.13313,.36687,0,0,1],8655:[-.13313,.36687,0,0,1],8666:[.13667,.63667,0,0,1],8667:[.13667,.63667,0,0,1],8669:[-.13313,.37788,0,0,1],8672:[-.064,.437,0,0,1.334],8674:[-.064,.437,0,0,1.334],8705:[0,.825,0,0,.5],8708:[0,.68889,0,0,.55556],8709:[.08167,.58167,0,0,.77778],8717:[0,.43056,0,0,.42917],8722:[-.03598,.46402,0,0,.5],8724:[.08198,.69224,0,0,.77778],8726:[.08167,.58167,0,0,.77778],8733:[0,.69224,0,0,.77778],8736:[0,.69224,0,0,.72222],8737:[0,.69224,0,0,.72222],8738:[.03517,.52239,0,0,.72222],8739:[.08167,.58167,0,0,.22222],8740:[.25142,.74111,0,0,.27778],8741:[.08167,.58167,0,0,.38889],8742:[.25142,.74111,0,0,.5],8756:[0,.69224,0,0,.66667],8757:[0,.69224,0,0,.66667],8764:[-.13313,.36687,0,0,.77778],8765:[-.13313,.37788,0,0,.77778],8769:[-.13313,.36687,0,0,.77778],8770:[-.03625,.46375,0,0,.77778],8774:[.30274,.79383,0,0,.77778],8776:[-.01688,.48312,0,0,.77778],8778:[.08167,.58167,0,0,.77778],8782:[.06062,.54986,0,0,.77778],8783:[.06062,.54986,0,0,.77778],8785:[.08198,.58198,0,0,.77778],8786:[.08198,.58198,0,0,.77778],8787:[.08198,.58198,0,0,.77778],8790:[0,.69224,0,0,.77778],8791:[.22958,.72958,0,0,.77778],8796:[.08198,.91667,0,0,.77778],8806:[.25583,.75583,0,0,.77778],8807:[.25583,.75583,0,0,.77778],8808:[.25142,.75726,0,0,.77778],8809:[.25142,.75726,0,0,.77778],8812:[.25583,.75583,0,0,.5],8814:[.20576,.70576,0,0,.77778],8815:[.20576,.70576,0,0,.77778],8816:[.30274,.79383,0,0,.77778],8817:[.30274,.79383,0,0,.77778],8818:[.22958,.72958,0,0,.77778],8819:[.22958,.72958,0,0,.77778],8822:[.1808,.675,0,0,.77778],8823:[.1808,.675,0,0,.77778],8828:[.13667,.63667,0,0,.77778],8829:[.13667,.63667,0,0,.77778],8830:[.22958,.72958,0,0,.77778],8831:[.22958,.72958,0,0,.77778],8832:[.20576,.70576,0,0,.77778],8833:[.20576,.70576,0,0,.77778],8840:[.30274,.79383,0,0,.77778],8841:[.30274,.79383,0,0,.77778],8842:[.13597,.63597,0,0,.77778],8843:[.13597,.63597,0,0,.77778],8847:[.03517,.54986,0,0,.77778],8848:[.03517,.54986,0,0,.77778],8858:[.08198,.58198,0,0,.77778],8859:[.08198,.58198,0,0,.77778],8861:[.08198,.58198,0,0,.77778],8862:[0,.675,0,0,.77778],8863:[0,.675,0,0,.77778],8864:[0,.675,0,0,.77778],8865:[0,.675,0,0,.77778],8872:[0,.69224,0,0,.61111],8873:[0,.69224,0,0,.72222],8874:[0,.69224,0,0,.88889],8876:[0,.68889,0,0,.61111],8877:[0,.68889,0,0,.61111],8878:[0,.68889,0,0,.72222],8879:[0,.68889,0,0,.72222],8882:[.03517,.54986,0,0,.77778],8883:[.03517,.54986,0,0,.77778],8884:[.13667,.63667,0,0,.77778],8885:[.13667,.63667,0,0,.77778],8888:[0,.54986,0,0,1.11111],8890:[.19444,.43056,0,0,.55556],8891:[.19444,.69224,0,0,.61111],8892:[.19444,.69224,0,0,.61111],8901:[0,.54986,0,0,.27778],8903:[.08167,.58167,0,0,.77778],8905:[.08167,.58167,0,0,.77778],8906:[.08167,.58167,0,0,.77778],8907:[0,.69224,0,0,.77778],8908:[0,.69224,0,0,.77778],8909:[-.03598,.46402,0,0,.77778],8910:[0,.54986,0,0,.76042],8911:[0,.54986,0,0,.76042],8912:[.03517,.54986,0,0,.77778],8913:[.03517,.54986,0,0,.77778],8914:[0,.54986,0,0,.66667],8915:[0,.54986,0,0,.66667],8916:[0,.69224,0,0,.66667],8918:[.0391,.5391,0,0,.77778],8919:[.0391,.5391,0,0,.77778],8920:[.03517,.54986,0,0,1.33334],8921:[.03517,.54986,0,0,1.33334],8922:[.38569,.88569,0,0,.77778],8923:[.38569,.88569,0,0,.77778],8926:[.13667,.63667,0,0,.77778],8927:[.13667,.63667,0,0,.77778],8928:[.30274,.79383,0,0,.77778],8929:[.30274,.79383,0,0,.77778],8934:[.23222,.74111,0,0,.77778],8935:[.23222,.74111,0,0,.77778],8936:[.23222,.74111,0,0,.77778],8937:[.23222,.74111,0,0,.77778],8938:[.20576,.70576,0,0,.77778],8939:[.20576,.70576,0,0,.77778],8940:[.30274,.79383,0,0,.77778],8941:[.30274,.79383,0,0,.77778],8994:[.19444,.69224,0,0,.77778],8995:[.19444,.69224,0,0,.77778],9416:[.15559,.69224,0,0,.90222],9484:[0,.69224,0,0,.5],9488:[0,.69224,0,0,.5],9492:[0,.37788,0,0,.5],9496:[0,.37788,0,0,.5],9585:[.19444,.68889,0,0,.88889],9586:[.19444,.74111,0,0,.88889],9632:[0,.675,0,0,.77778],9633:[0,.675,0,0,.77778],9650:[0,.54986,0,0,.72222],9651:[0,.54986,0,0,.72222],9654:[.03517,.54986,0,0,.77778],9660:[0,.54986,0,0,.72222],9661:[0,.54986,0,0,.72222],9664:[.03517,.54986,0,0,.77778],9674:[.11111,.69224,0,0,.66667],9733:[.19444,.69224,0,0,.94445],10003:[0,.69224,0,0,.83334],10016:[0,.69224,0,0,.83334],10731:[.11111,.69224,0,0,.66667],10846:[.19444,.75583,0,0,.61111],10877:[.13667,.63667,0,0,.77778],10878:[.13667,.63667,0,0,.77778],10885:[.25583,.75583,0,0,.77778],10886:[.25583,.75583,0,0,.77778],10887:[.13597,.63597,0,0,.77778],10888:[.13597,.63597,0,0,.77778],10889:[.26167,.75726,0,0,.77778],10890:[.26167,.75726,0,0,.77778],10891:[.48256,.98256,0,0,.77778],10892:[.48256,.98256,0,0,.77778],10901:[.13667,.63667,0,0,.77778],10902:[.13667,.63667,0,0,.77778],10933:[.25142,.75726,0,0,.77778],10934:[.25142,.75726,0,0,.77778],10935:[.26167,.75726,0,0,.77778],10936:[.26167,.75726,0,0,.77778],10937:[.26167,.75726,0,0,.77778],10938:[.26167,.75726,0,0,.77778],10949:[.25583,.75583,0,0,.77778],10950:[.25583,.75583,0,0,.77778],10955:[.28481,.79383,0,0,.77778],10956:[.28481,.79383,0,0,.77778],57350:[.08167,.58167,0,0,.22222],57351:[.08167,.58167,0,0,.38889],57352:[.08167,.58167,0,0,.77778],57353:[0,.43056,.04028,0,.66667],57356:[.25142,.75726,0,0,.77778],57357:[.25142,.75726,0,0,.77778],57358:[.41951,.91951,0,0,.77778],57359:[.30274,.79383,0,0,.77778],57360:[.30274,.79383,0,0,.77778],57361:[.41951,.91951,0,0,.77778],57366:[.25142,.75726,0,0,.77778],57367:[.25142,.75726,0,0,.77778],57368:[.25142,.75726,0,0,.77778],57369:[.25142,.75726,0,0,.77778],57370:[.13597,.63597,0,0,.77778],57371:[.13597,.63597,0,0,.77778]},"Caligraphic-Regular":{32:[0,0,0,0,.25],65:[0,.68333,0,.19445,.79847],66:[0,.68333,.03041,.13889,.65681],67:[0,.68333,.05834,.13889,.52653],68:[0,.68333,.02778,.08334,.77139],69:[0,.68333,.08944,.11111,.52778],70:[0,.68333,.09931,.11111,.71875],71:[.09722,.68333,.0593,.11111,.59487],72:[0,.68333,.00965,.11111,.84452],73:[0,.68333,.07382,0,.54452],74:[.09722,.68333,.18472,.16667,.67778],75:[0,.68333,.01445,.05556,.76195],76:[0,.68333,0,.13889,.68972],77:[0,.68333,0,.13889,1.2009],78:[0,.68333,.14736,.08334,.82049],79:[0,.68333,.02778,.11111,.79611],80:[0,.68333,.08222,.08334,.69556],81:[.09722,.68333,0,.11111,.81667],82:[0,.68333,0,.08334,.8475],83:[0,.68333,.075,.13889,.60556],84:[0,.68333,.25417,0,.54464],85:[0,.68333,.09931,.08334,.62583],86:[0,.68333,.08222,0,.61278],87:[0,.68333,.08222,.08334,.98778],88:[0,.68333,.14643,.13889,.7133],89:[.09722,.68333,.08222,.08334,.66834],90:[0,.68333,.07944,.13889,.72473],160:[0,0,0,0,.25]},"Fraktur-Regular":{32:[0,0,0,0,.25],33:[0,.69141,0,0,.29574],34:[0,.69141,0,0,.21471],38:[0,.69141,0,0,.73786],39:[0,.69141,0,0,.21201],40:[.24982,.74947,0,0,.38865],41:[.24982,.74947,0,0,.38865],42:[0,.62119,0,0,.27764],43:[.08319,.58283,0,0,.75623],44:[0,.10803,0,0,.27764],45:[.08319,.58283,0,0,.75623],46:[0,.10803,0,0,.27764],47:[.24982,.74947,0,0,.50181],48:[0,.47534,0,0,.50181],49:[0,.47534,0,0,.50181],50:[0,.47534,0,0,.50181],51:[.18906,.47534,0,0,.50181],52:[.18906,.47534,0,0,.50181],53:[.18906,.47534,0,0,.50181],54:[0,.69141,0,0,.50181],55:[.18906,.47534,0,0,.50181],56:[0,.69141,0,0,.50181],57:[.18906,.47534,0,0,.50181],58:[0,.47534,0,0,.21606],59:[.12604,.47534,0,0,.21606],61:[-.13099,.36866,0,0,.75623],63:[0,.69141,0,0,.36245],65:[0,.69141,0,0,.7176],66:[0,.69141,0,0,.88397],67:[0,.69141,0,0,.61254],68:[0,.69141,0,0,.83158],69:[0,.69141,0,0,.66278],70:[.12604,.69141,0,0,.61119],71:[0,.69141,0,0,.78539],72:[.06302,.69141,0,0,.7203],73:[0,.69141,0,0,.55448],74:[.12604,.69141,0,0,.55231],75:[0,.69141,0,0,.66845],76:[0,.69141,0,0,.66602],77:[0,.69141,0,0,1.04953],78:[0,.69141,0,0,.83212],79:[0,.69141,0,0,.82699],80:[.18906,.69141,0,0,.82753],81:[.03781,.69141,0,0,.82699],82:[0,.69141,0,0,.82807],83:[0,.69141,0,0,.82861],84:[0,.69141,0,0,.66899],85:[0,.69141,0,0,.64576],86:[0,.69141,0,0,.83131],87:[0,.69141,0,0,1.04602],88:[0,.69141,0,0,.71922],89:[.18906,.69141,0,0,.83293],90:[.12604,.69141,0,0,.60201],91:[.24982,.74947,0,0,.27764],93:[.24982,.74947,0,0,.27764],94:[0,.69141,0,0,.49965],97:[0,.47534,0,0,.50046],98:[0,.69141,0,0,.51315],99:[0,.47534,0,0,.38946],100:[0,.62119,0,0,.49857],101:[0,.47534,0,0,.40053],102:[.18906,.69141,0,0,.32626],103:[.18906,.47534,0,0,.5037],104:[.18906,.69141,0,0,.52126],105:[0,.69141,0,0,.27899],106:[0,.69141,0,0,.28088],107:[0,.69141,0,0,.38946],108:[0,.69141,0,0,.27953],109:[0,.47534,0,0,.76676],110:[0,.47534,0,0,.52666],111:[0,.47534,0,0,.48885],112:[.18906,.52396,0,0,.50046],113:[.18906,.47534,0,0,.48912],114:[0,.47534,0,0,.38919],115:[0,.47534,0,0,.44266],116:[0,.62119,0,0,.33301],117:[0,.47534,0,0,.5172],118:[0,.52396,0,0,.5118],119:[0,.52396,0,0,.77351],120:[.18906,.47534,0,0,.38865],121:[.18906,.47534,0,0,.49884],122:[.18906,.47534,0,0,.39054],160:[0,0,0,0,.25],8216:[0,.69141,0,0,.21471],8217:[0,.69141,0,0,.21471],58112:[0,.62119,0,0,.49749],58113:[0,.62119,0,0,.4983],58114:[.18906,.69141,0,0,.33328],58115:[.18906,.69141,0,0,.32923],58116:[.18906,.47534,0,0,.50343],58117:[0,.69141,0,0,.33301],58118:[0,.62119,0,0,.33409],58119:[0,.47534,0,0,.50073]},"Main-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.35],34:[0,.69444,0,0,.60278],35:[.19444,.69444,0,0,.95833],36:[.05556,.75,0,0,.575],37:[.05556,.75,0,0,.95833],38:[0,.69444,0,0,.89444],39:[0,.69444,0,0,.31944],40:[.25,.75,0,0,.44722],41:[.25,.75,0,0,.44722],42:[0,.75,0,0,.575],43:[.13333,.63333,0,0,.89444],44:[.19444,.15556,0,0,.31944],45:[0,.44444,0,0,.38333],46:[0,.15556,0,0,.31944],47:[.25,.75,0,0,.575],48:[0,.64444,0,0,.575],49:[0,.64444,0,0,.575],50:[0,.64444,0,0,.575],51:[0,.64444,0,0,.575],52:[0,.64444,0,0,.575],53:[0,.64444,0,0,.575],54:[0,.64444,0,0,.575],55:[0,.64444,0,0,.575],56:[0,.64444,0,0,.575],57:[0,.64444,0,0,.575],58:[0,.44444,0,0,.31944],59:[.19444,.44444,0,0,.31944],60:[.08556,.58556,0,0,.89444],61:[-.10889,.39111,0,0,.89444],62:[.08556,.58556,0,0,.89444],63:[0,.69444,0,0,.54305],64:[0,.69444,0,0,.89444],65:[0,.68611,0,0,.86944],66:[0,.68611,0,0,.81805],67:[0,.68611,0,0,.83055],68:[0,.68611,0,0,.88194],69:[0,.68611,0,0,.75555],70:[0,.68611,0,0,.72361],71:[0,.68611,0,0,.90416],72:[0,.68611,0,0,.9],73:[0,.68611,0,0,.43611],74:[0,.68611,0,0,.59444],75:[0,.68611,0,0,.90138],76:[0,.68611,0,0,.69166],77:[0,.68611,0,0,1.09166],78:[0,.68611,0,0,.9],79:[0,.68611,0,0,.86388],80:[0,.68611,0,0,.78611],81:[.19444,.68611,0,0,.86388],82:[0,.68611,0,0,.8625],83:[0,.68611,0,0,.63889],84:[0,.68611,0,0,.8],85:[0,.68611,0,0,.88472],86:[0,.68611,.01597,0,.86944],87:[0,.68611,.01597,0,1.18888],88:[0,.68611,0,0,.86944],89:[0,.68611,.02875,0,.86944],90:[0,.68611,0,0,.70277],91:[.25,.75,0,0,.31944],92:[.25,.75,0,0,.575],93:[.25,.75,0,0,.31944],94:[0,.69444,0,0,.575],95:[.31,.13444,.03194,0,.575],97:[0,.44444,0,0,.55902],98:[0,.69444,0,0,.63889],99:[0,.44444,0,0,.51111],100:[0,.69444,0,0,.63889],101:[0,.44444,0,0,.52708],102:[0,.69444,.10903,0,.35139],103:[.19444,.44444,.01597,0,.575],104:[0,.69444,0,0,.63889],105:[0,.69444,0,0,.31944],106:[.19444,.69444,0,0,.35139],107:[0,.69444,0,0,.60694],108:[0,.69444,0,0,.31944],109:[0,.44444,0,0,.95833],110:[0,.44444,0,0,.63889],111:[0,.44444,0,0,.575],112:[.19444,.44444,0,0,.63889],113:[.19444,.44444,0,0,.60694],114:[0,.44444,0,0,.47361],115:[0,.44444,0,0,.45361],116:[0,.63492,0,0,.44722],117:[0,.44444,0,0,.63889],118:[0,.44444,.01597,0,.60694],119:[0,.44444,.01597,0,.83055],120:[0,.44444,0,0,.60694],121:[.19444,.44444,.01597,0,.60694],122:[0,.44444,0,0,.51111],123:[.25,.75,0,0,.575],124:[.25,.75,0,0,.31944],125:[.25,.75,0,0,.575],126:[.35,.34444,0,0,.575],160:[0,0,0,0,.25],163:[0,.69444,0,0,.86853],168:[0,.69444,0,0,.575],172:[0,.44444,0,0,.76666],176:[0,.69444,0,0,.86944],177:[.13333,.63333,0,0,.89444],184:[.17014,0,0,0,.51111],198:[0,.68611,0,0,1.04166],215:[.13333,.63333,0,0,.89444],216:[.04861,.73472,0,0,.89444],223:[0,.69444,0,0,.59722],230:[0,.44444,0,0,.83055],247:[.13333,.63333,0,0,.89444],248:[.09722,.54167,0,0,.575],305:[0,.44444,0,0,.31944],338:[0,.68611,0,0,1.16944],339:[0,.44444,0,0,.89444],567:[.19444,.44444,0,0,.35139],710:[0,.69444,0,0,.575],711:[0,.63194,0,0,.575],713:[0,.59611,0,0,.575],714:[0,.69444,0,0,.575],715:[0,.69444,0,0,.575],728:[0,.69444,0,0,.575],729:[0,.69444,0,0,.31944],730:[0,.69444,0,0,.86944],732:[0,.69444,0,0,.575],733:[0,.69444,0,0,.575],915:[0,.68611,0,0,.69166],916:[0,.68611,0,0,.95833],920:[0,.68611,0,0,.89444],923:[0,.68611,0,0,.80555],926:[0,.68611,0,0,.76666],928:[0,.68611,0,0,.9],931:[0,.68611,0,0,.83055],933:[0,.68611,0,0,.89444],934:[0,.68611,0,0,.83055],936:[0,.68611,0,0,.89444],937:[0,.68611,0,0,.83055],8211:[0,.44444,.03194,0,.575],8212:[0,.44444,.03194,0,1.14999],8216:[0,.69444,0,0,.31944],8217:[0,.69444,0,0,.31944],8220:[0,.69444,0,0,.60278],8221:[0,.69444,0,0,.60278],8224:[.19444,.69444,0,0,.51111],8225:[.19444,.69444,0,0,.51111],8242:[0,.55556,0,0,.34444],8407:[0,.72444,.15486,0,.575],8463:[0,.69444,0,0,.66759],8465:[0,.69444,0,0,.83055],8467:[0,.69444,0,0,.47361],8472:[.19444,.44444,0,0,.74027],8476:[0,.69444,0,0,.83055],8501:[0,.69444,0,0,.70277],8592:[-.10889,.39111,0,0,1.14999],8593:[.19444,.69444,0,0,.575],8594:[-.10889,.39111,0,0,1.14999],8595:[.19444,.69444,0,0,.575],8596:[-.10889,.39111,0,0,1.14999],8597:[.25,.75,0,0,.575],8598:[.19444,.69444,0,0,1.14999],8599:[.19444,.69444,0,0,1.14999],8600:[.19444,.69444,0,0,1.14999],8601:[.19444,.69444,0,0,1.14999],8636:[-.10889,.39111,0,0,1.14999],8637:[-.10889,.39111,0,0,1.14999],8640:[-.10889,.39111,0,0,1.14999],8641:[-.10889,.39111,0,0,1.14999],8656:[-.10889,.39111,0,0,1.14999],8657:[.19444,.69444,0,0,.70277],8658:[-.10889,.39111,0,0,1.14999],8659:[.19444,.69444,0,0,.70277],8660:[-.10889,.39111,0,0,1.14999],8661:[.25,.75,0,0,.70277],8704:[0,.69444,0,0,.63889],8706:[0,.69444,.06389,0,.62847],8707:[0,.69444,0,0,.63889],8709:[.05556,.75,0,0,.575],8711:[0,.68611,0,0,.95833],8712:[.08556,.58556,0,0,.76666],8715:[.08556,.58556,0,0,.76666],8722:[.13333,.63333,0,0,.89444],8723:[.13333,.63333,0,0,.89444],8725:[.25,.75,0,0,.575],8726:[.25,.75,0,0,.575],8727:[-.02778,.47222,0,0,.575],8728:[-.02639,.47361,0,0,.575],8729:[-.02639,.47361,0,0,.575],8730:[.18,.82,0,0,.95833],8733:[0,.44444,0,0,.89444],8734:[0,.44444,0,0,1.14999],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.31944],8741:[.25,.75,0,0,.575],8743:[0,.55556,0,0,.76666],8744:[0,.55556,0,0,.76666],8745:[0,.55556,0,0,.76666],8746:[0,.55556,0,0,.76666],8747:[.19444,.69444,.12778,0,.56875],8764:[-.10889,.39111,0,0,.89444],8768:[.19444,.69444,0,0,.31944],8771:[.00222,.50222,0,0,.89444],8773:[.027,.638,0,0,.894],8776:[.02444,.52444,0,0,.89444],8781:[.00222,.50222,0,0,.89444],8801:[.00222,.50222,0,0,.89444],8804:[.19667,.69667,0,0,.89444],8805:[.19667,.69667,0,0,.89444],8810:[.08556,.58556,0,0,1.14999],8811:[.08556,.58556,0,0,1.14999],8826:[.08556,.58556,0,0,.89444],8827:[.08556,.58556,0,0,.89444],8834:[.08556,.58556,0,0,.89444],8835:[.08556,.58556,0,0,.89444],8838:[.19667,.69667,0,0,.89444],8839:[.19667,.69667,0,0,.89444],8846:[0,.55556,0,0,.76666],8849:[.19667,.69667,0,0,.89444],8850:[.19667,.69667,0,0,.89444],8851:[0,.55556,0,0,.76666],8852:[0,.55556,0,0,.76666],8853:[.13333,.63333,0,0,.89444],8854:[.13333,.63333,0,0,.89444],8855:[.13333,.63333,0,0,.89444],8856:[.13333,.63333,0,0,.89444],8857:[.13333,.63333,0,0,.89444],8866:[0,.69444,0,0,.70277],8867:[0,.69444,0,0,.70277],8868:[0,.69444,0,0,.89444],8869:[0,.69444,0,0,.89444],8900:[-.02639,.47361,0,0,.575],8901:[-.02639,.47361,0,0,.31944],8902:[-.02778,.47222,0,0,.575],8968:[.25,.75,0,0,.51111],8969:[.25,.75,0,0,.51111],8970:[.25,.75,0,0,.51111],8971:[.25,.75,0,0,.51111],8994:[-.13889,.36111,0,0,1.14999],8995:[-.13889,.36111,0,0,1.14999],9651:[.19444,.69444,0,0,1.02222],9657:[-.02778,.47222,0,0,.575],9661:[.19444,.69444,0,0,1.02222],9667:[-.02778,.47222,0,0,.575],9711:[.19444,.69444,0,0,1.14999],9824:[.12963,.69444,0,0,.89444],9825:[.12963,.69444,0,0,.89444],9826:[.12963,.69444,0,0,.89444],9827:[.12963,.69444,0,0,.89444],9837:[0,.75,0,0,.44722],9838:[.19444,.69444,0,0,.44722],9839:[.19444,.69444,0,0,.44722],10216:[.25,.75,0,0,.44722],10217:[.25,.75,0,0,.44722],10815:[0,.68611,0,0,.9],10927:[.19667,.69667,0,0,.89444],10928:[.19667,.69667,0,0,.89444],57376:[.19444,.69444,0,0,0]},"Main-BoldItalic":{32:[0,0,0,0,.25],33:[0,.69444,.11417,0,.38611],34:[0,.69444,.07939,0,.62055],35:[.19444,.69444,.06833,0,.94444],37:[.05556,.75,.12861,0,.94444],38:[0,.69444,.08528,0,.88555],39:[0,.69444,.12945,0,.35555],40:[.25,.75,.15806,0,.47333],41:[.25,.75,.03306,0,.47333],42:[0,.75,.14333,0,.59111],43:[.10333,.60333,.03306,0,.88555],44:[.19444,.14722,0,0,.35555],45:[0,.44444,.02611,0,.41444],46:[0,.14722,0,0,.35555],47:[.25,.75,.15806,0,.59111],48:[0,.64444,.13167,0,.59111],49:[0,.64444,.13167,0,.59111],50:[0,.64444,.13167,0,.59111],51:[0,.64444,.13167,0,.59111],52:[.19444,.64444,.13167,0,.59111],53:[0,.64444,.13167,0,.59111],54:[0,.64444,.13167,0,.59111],55:[.19444,.64444,.13167,0,.59111],56:[0,.64444,.13167,0,.59111],57:[0,.64444,.13167,0,.59111],58:[0,.44444,.06695,0,.35555],59:[.19444,.44444,.06695,0,.35555],61:[-.10889,.39111,.06833,0,.88555],63:[0,.69444,.11472,0,.59111],64:[0,.69444,.09208,0,.88555],65:[0,.68611,0,0,.86555],66:[0,.68611,.0992,0,.81666],67:[0,.68611,.14208,0,.82666],68:[0,.68611,.09062,0,.87555],69:[0,.68611,.11431,0,.75666],70:[0,.68611,.12903,0,.72722],71:[0,.68611,.07347,0,.89527],72:[0,.68611,.17208,0,.8961],73:[0,.68611,.15681,0,.47166],74:[0,.68611,.145,0,.61055],75:[0,.68611,.14208,0,.89499],76:[0,.68611,0,0,.69777],77:[0,.68611,.17208,0,1.07277],78:[0,.68611,.17208,0,.8961],79:[0,.68611,.09062,0,.85499],80:[0,.68611,.0992,0,.78721],81:[.19444,.68611,.09062,0,.85499],82:[0,.68611,.02559,0,.85944],83:[0,.68611,.11264,0,.64999],84:[0,.68611,.12903,0,.7961],85:[0,.68611,.17208,0,.88083],86:[0,.68611,.18625,0,.86555],87:[0,.68611,.18625,0,1.15999],88:[0,.68611,.15681,0,.86555],89:[0,.68611,.19803,0,.86555],90:[0,.68611,.14208,0,.70888],91:[.25,.75,.1875,0,.35611],93:[.25,.75,.09972,0,.35611],94:[0,.69444,.06709,0,.59111],95:[.31,.13444,.09811,0,.59111],97:[0,.44444,.09426,0,.59111],98:[0,.69444,.07861,0,.53222],99:[0,.44444,.05222,0,.53222],100:[0,.69444,.10861,0,.59111],101:[0,.44444,.085,0,.53222],102:[.19444,.69444,.21778,0,.4],103:[.19444,.44444,.105,0,.53222],104:[0,.69444,.09426,0,.59111],105:[0,.69326,.11387,0,.35555],106:[.19444,.69326,.1672,0,.35555],107:[0,.69444,.11111,0,.53222],108:[0,.69444,.10861,0,.29666],109:[0,.44444,.09426,0,.94444],110:[0,.44444,.09426,0,.64999],111:[0,.44444,.07861,0,.59111],112:[.19444,.44444,.07861,0,.59111],113:[.19444,.44444,.105,0,.53222],114:[0,.44444,.11111,0,.50167],115:[0,.44444,.08167,0,.48694],116:[0,.63492,.09639,0,.385],117:[0,.44444,.09426,0,.62055],118:[0,.44444,.11111,0,.53222],119:[0,.44444,.11111,0,.76777],120:[0,.44444,.12583,0,.56055],121:[.19444,.44444,.105,0,.56166],122:[0,.44444,.13889,0,.49055],126:[.35,.34444,.11472,0,.59111],160:[0,0,0,0,.25],168:[0,.69444,.11473,0,.59111],176:[0,.69444,0,0,.94888],184:[.17014,0,0,0,.53222],198:[0,.68611,.11431,0,1.02277],216:[.04861,.73472,.09062,0,.88555],223:[.19444,.69444,.09736,0,.665],230:[0,.44444,.085,0,.82666],248:[.09722,.54167,.09458,0,.59111],305:[0,.44444,.09426,0,.35555],338:[0,.68611,.11431,0,1.14054],339:[0,.44444,.085,0,.82666],567:[.19444,.44444,.04611,0,.385],710:[0,.69444,.06709,0,.59111],711:[0,.63194,.08271,0,.59111],713:[0,.59444,.10444,0,.59111],714:[0,.69444,.08528,0,.59111],715:[0,.69444,0,0,.59111],728:[0,.69444,.10333,0,.59111],729:[0,.69444,.12945,0,.35555],730:[0,.69444,0,0,.94888],732:[0,.69444,.11472,0,.59111],733:[0,.69444,.11472,0,.59111],915:[0,.68611,.12903,0,.69777],916:[0,.68611,0,0,.94444],920:[0,.68611,.09062,0,.88555],923:[0,.68611,0,0,.80666],926:[0,.68611,.15092,0,.76777],928:[0,.68611,.17208,0,.8961],931:[0,.68611,.11431,0,.82666],933:[0,.68611,.10778,0,.88555],934:[0,.68611,.05632,0,.82666],936:[0,.68611,.10778,0,.88555],937:[0,.68611,.0992,0,.82666],8211:[0,.44444,.09811,0,.59111],8212:[0,.44444,.09811,0,1.18221],8216:[0,.69444,.12945,0,.35555],8217:[0,.69444,.12945,0,.35555],8220:[0,.69444,.16772,0,.62055],8221:[0,.69444,.07939,0,.62055]},"Main-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.12417,0,.30667],34:[0,.69444,.06961,0,.51444],35:[.19444,.69444,.06616,0,.81777],37:[.05556,.75,.13639,0,.81777],38:[0,.69444,.09694,0,.76666],39:[0,.69444,.12417,0,.30667],40:[.25,.75,.16194,0,.40889],41:[.25,.75,.03694,0,.40889],42:[0,.75,.14917,0,.51111],43:[.05667,.56167,.03694,0,.76666],44:[.19444,.10556,0,0,.30667],45:[0,.43056,.02826,0,.35778],46:[0,.10556,0,0,.30667],47:[.25,.75,.16194,0,.51111],48:[0,.64444,.13556,0,.51111],49:[0,.64444,.13556,0,.51111],50:[0,.64444,.13556,0,.51111],51:[0,.64444,.13556,0,.51111],52:[.19444,.64444,.13556,0,.51111],53:[0,.64444,.13556,0,.51111],54:[0,.64444,.13556,0,.51111],55:[.19444,.64444,.13556,0,.51111],56:[0,.64444,.13556,0,.51111],57:[0,.64444,.13556,0,.51111],58:[0,.43056,.0582,0,.30667],59:[.19444,.43056,.0582,0,.30667],61:[-.13313,.36687,.06616,0,.76666],63:[0,.69444,.1225,0,.51111],64:[0,.69444,.09597,0,.76666],65:[0,.68333,0,0,.74333],66:[0,.68333,.10257,0,.70389],67:[0,.68333,.14528,0,.71555],68:[0,.68333,.09403,0,.755],69:[0,.68333,.12028,0,.67833],70:[0,.68333,.13305,0,.65277],71:[0,.68333,.08722,0,.77361],72:[0,.68333,.16389,0,.74333],73:[0,.68333,.15806,0,.38555],74:[0,.68333,.14028,0,.525],75:[0,.68333,.14528,0,.76888],76:[0,.68333,0,0,.62722],77:[0,.68333,.16389,0,.89666],78:[0,.68333,.16389,0,.74333],79:[0,.68333,.09403,0,.76666],80:[0,.68333,.10257,0,.67833],81:[.19444,.68333,.09403,0,.76666],82:[0,.68333,.03868,0,.72944],83:[0,.68333,.11972,0,.56222],84:[0,.68333,.13305,0,.71555],85:[0,.68333,.16389,0,.74333],86:[0,.68333,.18361,0,.74333],87:[0,.68333,.18361,0,.99888],88:[0,.68333,.15806,0,.74333],89:[0,.68333,.19383,0,.74333],90:[0,.68333,.14528,0,.61333],91:[.25,.75,.1875,0,.30667],93:[.25,.75,.10528,0,.30667],94:[0,.69444,.06646,0,.51111],95:[.31,.12056,.09208,0,.51111],97:[0,.43056,.07671,0,.51111],98:[0,.69444,.06312,0,.46],99:[0,.43056,.05653,0,.46],100:[0,.69444,.10333,0,.51111],101:[0,.43056,.07514,0,.46],102:[.19444,.69444,.21194,0,.30667],103:[.19444,.43056,.08847,0,.46],104:[0,.69444,.07671,0,.51111],105:[0,.65536,.1019,0,.30667],106:[.19444,.65536,.14467,0,.30667],107:[0,.69444,.10764,0,.46],108:[0,.69444,.10333,0,.25555],109:[0,.43056,.07671,0,.81777],110:[0,.43056,.07671,0,.56222],111:[0,.43056,.06312,0,.51111],112:[.19444,.43056,.06312,0,.51111],113:[.19444,.43056,.08847,0,.46],114:[0,.43056,.10764,0,.42166],115:[0,.43056,.08208,0,.40889],116:[0,.61508,.09486,0,.33222],117:[0,.43056,.07671,0,.53666],118:[0,.43056,.10764,0,.46],119:[0,.43056,.10764,0,.66444],120:[0,.43056,.12042,0,.46389],121:[.19444,.43056,.08847,0,.48555],122:[0,.43056,.12292,0,.40889],126:[.35,.31786,.11585,0,.51111],160:[0,0,0,0,.25],168:[0,.66786,.10474,0,.51111],176:[0,.69444,0,0,.83129],184:[.17014,0,0,0,.46],198:[0,.68333,.12028,0,.88277],216:[.04861,.73194,.09403,0,.76666],223:[.19444,.69444,.10514,0,.53666],230:[0,.43056,.07514,0,.71555],248:[.09722,.52778,.09194,0,.51111],338:[0,.68333,.12028,0,.98499],339:[0,.43056,.07514,0,.71555],710:[0,.69444,.06646,0,.51111],711:[0,.62847,.08295,0,.51111],713:[0,.56167,.10333,0,.51111],714:[0,.69444,.09694,0,.51111],715:[0,.69444,0,0,.51111],728:[0,.69444,.10806,0,.51111],729:[0,.66786,.11752,0,.30667],730:[0,.69444,0,0,.83129],732:[0,.66786,.11585,0,.51111],733:[0,.69444,.1225,0,.51111],915:[0,.68333,.13305,0,.62722],916:[0,.68333,0,0,.81777],920:[0,.68333,.09403,0,.76666],923:[0,.68333,0,0,.69222],926:[0,.68333,.15294,0,.66444],928:[0,.68333,.16389,0,.74333],931:[0,.68333,.12028,0,.71555],933:[0,.68333,.11111,0,.76666],934:[0,.68333,.05986,0,.71555],936:[0,.68333,.11111,0,.76666],937:[0,.68333,.10257,0,.71555],8211:[0,.43056,.09208,0,.51111],8212:[0,.43056,.09208,0,1.02222],8216:[0,.69444,.12417,0,.30667],8217:[0,.69444,.12417,0,.30667],8220:[0,.69444,.1685,0,.51444],8221:[0,.69444,.06961,0,.51444],8463:[0,.68889,0,0,.54028]},"Main-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.27778],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.77778],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.19444,.10556,0,0,.27778],45:[0,.43056,0,0,.33333],46:[0,.10556,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.64444,0,0,.5],49:[0,.64444,0,0,.5],50:[0,.64444,0,0,.5],51:[0,.64444,0,0,.5],52:[0,.64444,0,0,.5],53:[0,.64444,0,0,.5],54:[0,.64444,0,0,.5],55:[0,.64444,0,0,.5],56:[0,.64444,0,0,.5],57:[0,.64444,0,0,.5],58:[0,.43056,0,0,.27778],59:[.19444,.43056,0,0,.27778],60:[.0391,.5391,0,0,.77778],61:[-.13313,.36687,0,0,.77778],62:[.0391,.5391,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.77778],65:[0,.68333,0,0,.75],66:[0,.68333,0,0,.70834],67:[0,.68333,0,0,.72222],68:[0,.68333,0,0,.76389],69:[0,.68333,0,0,.68056],70:[0,.68333,0,0,.65278],71:[0,.68333,0,0,.78472],72:[0,.68333,0,0,.75],73:[0,.68333,0,0,.36111],74:[0,.68333,0,0,.51389],75:[0,.68333,0,0,.77778],76:[0,.68333,0,0,.625],77:[0,.68333,0,0,.91667],78:[0,.68333,0,0,.75],79:[0,.68333,0,0,.77778],80:[0,.68333,0,0,.68056],81:[.19444,.68333,0,0,.77778],82:[0,.68333,0,0,.73611],83:[0,.68333,0,0,.55556],84:[0,.68333,0,0,.72222],85:[0,.68333,0,0,.75],86:[0,.68333,.01389,0,.75],87:[0,.68333,.01389,0,1.02778],88:[0,.68333,0,0,.75],89:[0,.68333,.025,0,.75],90:[0,.68333,0,0,.61111],91:[.25,.75,0,0,.27778],92:[.25,.75,0,0,.5],93:[.25,.75,0,0,.27778],94:[0,.69444,0,0,.5],95:[.31,.12056,.02778,0,.5],97:[0,.43056,0,0,.5],98:[0,.69444,0,0,.55556],99:[0,.43056,0,0,.44445],100:[0,.69444,0,0,.55556],101:[0,.43056,0,0,.44445],102:[0,.69444,.07778,0,.30556],103:[.19444,.43056,.01389,0,.5],104:[0,.69444,0,0,.55556],105:[0,.66786,0,0,.27778],106:[.19444,.66786,0,0,.30556],107:[0,.69444,0,0,.52778],108:[0,.69444,0,0,.27778],109:[0,.43056,0,0,.83334],110:[0,.43056,0,0,.55556],111:[0,.43056,0,0,.5],112:[.19444,.43056,0,0,.55556],113:[.19444,.43056,0,0,.52778],114:[0,.43056,0,0,.39167],115:[0,.43056,0,0,.39445],116:[0,.61508,0,0,.38889],117:[0,.43056,0,0,.55556],118:[0,.43056,.01389,0,.52778],119:[0,.43056,.01389,0,.72222],120:[0,.43056,0,0,.52778],121:[.19444,.43056,.01389,0,.52778],122:[0,.43056,0,0,.44445],123:[.25,.75,0,0,.5],124:[.25,.75,0,0,.27778],125:[.25,.75,0,0,.5],126:[.35,.31786,0,0,.5],160:[0,0,0,0,.25],163:[0,.69444,0,0,.76909],167:[.19444,.69444,0,0,.44445],168:[0,.66786,0,0,.5],172:[0,.43056,0,0,.66667],176:[0,.69444,0,0,.75],177:[.08333,.58333,0,0,.77778],182:[.19444,.69444,0,0,.61111],184:[.17014,0,0,0,.44445],198:[0,.68333,0,0,.90278],215:[.08333,.58333,0,0,.77778],216:[.04861,.73194,0,0,.77778],223:[0,.69444,0,0,.5],230:[0,.43056,0,0,.72222],247:[.08333,.58333,0,0,.77778],248:[.09722,.52778,0,0,.5],305:[0,.43056,0,0,.27778],338:[0,.68333,0,0,1.01389],339:[0,.43056,0,0,.77778],567:[.19444,.43056,0,0,.30556],710:[0,.69444,0,0,.5],711:[0,.62847,0,0,.5],713:[0,.56778,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.66786,0,0,.27778],730:[0,.69444,0,0,.75],732:[0,.66786,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.68333,0,0,.625],916:[0,.68333,0,0,.83334],920:[0,.68333,0,0,.77778],923:[0,.68333,0,0,.69445],926:[0,.68333,0,0,.66667],928:[0,.68333,0,0,.75],931:[0,.68333,0,0,.72222],933:[0,.68333,0,0,.77778],934:[0,.68333,0,0,.72222],936:[0,.68333,0,0,.77778],937:[0,.68333,0,0,.72222],8211:[0,.43056,.02778,0,.5],8212:[0,.43056,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5],8224:[.19444,.69444,0,0,.44445],8225:[.19444,.69444,0,0,.44445],8230:[0,.123,0,0,1.172],8242:[0,.55556,0,0,.275],8407:[0,.71444,.15382,0,.5],8463:[0,.68889,0,0,.54028],8465:[0,.69444,0,0,.72222],8467:[0,.69444,0,.11111,.41667],8472:[.19444,.43056,0,.11111,.63646],8476:[0,.69444,0,0,.72222],8501:[0,.69444,0,0,.61111],8592:[-.13313,.36687,0,0,1],8593:[.19444,.69444,0,0,.5],8594:[-.13313,.36687,0,0,1],8595:[.19444,.69444,0,0,.5],8596:[-.13313,.36687,0,0,1],8597:[.25,.75,0,0,.5],8598:[.19444,.69444,0,0,1],8599:[.19444,.69444,0,0,1],8600:[.19444,.69444,0,0,1],8601:[.19444,.69444,0,0,1],8614:[.011,.511,0,0,1],8617:[.011,.511,0,0,1.126],8618:[.011,.511,0,0,1.126],8636:[-.13313,.36687,0,0,1],8637:[-.13313,.36687,0,0,1],8640:[-.13313,.36687,0,0,1],8641:[-.13313,.36687,0,0,1],8652:[.011,.671,0,0,1],8656:[-.13313,.36687,0,0,1],8657:[.19444,.69444,0,0,.61111],8658:[-.13313,.36687,0,0,1],8659:[.19444,.69444,0,0,.61111],8660:[-.13313,.36687,0,0,1],8661:[.25,.75,0,0,.61111],8704:[0,.69444,0,0,.55556],8706:[0,.69444,.05556,.08334,.5309],8707:[0,.69444,0,0,.55556],8709:[.05556,.75,0,0,.5],8711:[0,.68333,0,0,.83334],8712:[.0391,.5391,0,0,.66667],8715:[.0391,.5391,0,0,.66667],8722:[.08333,.58333,0,0,.77778],8723:[.08333,.58333,0,0,.77778],8725:[.25,.75,0,0,.5],8726:[.25,.75,0,0,.5],8727:[-.03472,.46528,0,0,.5],8728:[-.05555,.44445,0,0,.5],8729:[-.05555,.44445,0,0,.5],8730:[.2,.8,0,0,.83334],8733:[0,.43056,0,0,.77778],8734:[0,.43056,0,0,1],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.27778],8741:[.25,.75,0,0,.5],8743:[0,.55556,0,0,.66667],8744:[0,.55556,0,0,.66667],8745:[0,.55556,0,0,.66667],8746:[0,.55556,0,0,.66667],8747:[.19444,.69444,.11111,0,.41667],8764:[-.13313,.36687,0,0,.77778],8768:[.19444,.69444,0,0,.27778],8771:[-.03625,.46375,0,0,.77778],8773:[-.022,.589,0,0,.778],8776:[-.01688,.48312,0,0,.77778],8781:[-.03625,.46375,0,0,.77778],8784:[-.133,.673,0,0,.778],8801:[-.03625,.46375,0,0,.77778],8804:[.13597,.63597,0,0,.77778],8805:[.13597,.63597,0,0,.77778],8810:[.0391,.5391,0,0,1],8811:[.0391,.5391,0,0,1],8826:[.0391,.5391,0,0,.77778],8827:[.0391,.5391,0,0,.77778],8834:[.0391,.5391,0,0,.77778],8835:[.0391,.5391,0,0,.77778],8838:[.13597,.63597,0,0,.77778],8839:[.13597,.63597,0,0,.77778],8846:[0,.55556,0,0,.66667],8849:[.13597,.63597,0,0,.77778],8850:[.13597,.63597,0,0,.77778],8851:[0,.55556,0,0,.66667],8852:[0,.55556,0,0,.66667],8853:[.08333,.58333,0,0,.77778],8854:[.08333,.58333,0,0,.77778],8855:[.08333,.58333,0,0,.77778],8856:[.08333,.58333,0,0,.77778],8857:[.08333,.58333,0,0,.77778],8866:[0,.69444,0,0,.61111],8867:[0,.69444,0,0,.61111],8868:[0,.69444,0,0,.77778],8869:[0,.69444,0,0,.77778],8872:[.249,.75,0,0,.867],8900:[-.05555,.44445,0,0,.5],8901:[-.05555,.44445,0,0,.27778],8902:[-.03472,.46528,0,0,.5],8904:[.005,.505,0,0,.9],8942:[.03,.903,0,0,.278],8943:[-.19,.313,0,0,1.172],8945:[-.1,.823,0,0,1.282],8968:[.25,.75,0,0,.44445],8969:[.25,.75,0,0,.44445],8970:[.25,.75,0,0,.44445],8971:[.25,.75,0,0,.44445],8994:[-.14236,.35764,0,0,1],8995:[-.14236,.35764,0,0,1],9136:[.244,.744,0,0,.412],9137:[.244,.745,0,0,.412],9651:[.19444,.69444,0,0,.88889],9657:[-.03472,.46528,0,0,.5],9661:[.19444,.69444,0,0,.88889],9667:[-.03472,.46528,0,0,.5],9711:[.19444,.69444,0,0,1],9824:[.12963,.69444,0,0,.77778],9825:[.12963,.69444,0,0,.77778],9826:[.12963,.69444,0,0,.77778],9827:[.12963,.69444,0,0,.77778],9837:[0,.75,0,0,.38889],9838:[.19444,.69444,0,0,.38889],9839:[.19444,.69444,0,0,.38889],10216:[.25,.75,0,0,.38889],10217:[.25,.75,0,0,.38889],10222:[.244,.744,0,0,.412],10223:[.244,.745,0,0,.412],10229:[.011,.511,0,0,1.609],10230:[.011,.511,0,0,1.638],10231:[.011,.511,0,0,1.859],10232:[.024,.525,0,0,1.609],10233:[.024,.525,0,0,1.638],10234:[.024,.525,0,0,1.858],10236:[.011,.511,0,0,1.638],10815:[0,.68333,0,0,.75],10927:[.13597,.63597,0,0,.77778],10928:[.13597,.63597,0,0,.77778],57376:[.19444,.69444,0,0,0]},"Math-BoldItalic":{32:[0,0,0,0,.25],48:[0,.44444,0,0,.575],49:[0,.44444,0,0,.575],50:[0,.44444,0,0,.575],51:[.19444,.44444,0,0,.575],52:[.19444,.44444,0,0,.575],53:[.19444,.44444,0,0,.575],54:[0,.64444,0,0,.575],55:[.19444,.44444,0,0,.575],56:[0,.64444,0,0,.575],57:[.19444,.44444,0,0,.575],65:[0,.68611,0,0,.86944],66:[0,.68611,.04835,0,.8664],67:[0,.68611,.06979,0,.81694],68:[0,.68611,.03194,0,.93812],69:[0,.68611,.05451,0,.81007],70:[0,.68611,.15972,0,.68889],71:[0,.68611,0,0,.88673],72:[0,.68611,.08229,0,.98229],73:[0,.68611,.07778,0,.51111],74:[0,.68611,.10069,0,.63125],75:[0,.68611,.06979,0,.97118],76:[0,.68611,0,0,.75555],77:[0,.68611,.11424,0,1.14201],78:[0,.68611,.11424,0,.95034],79:[0,.68611,.03194,0,.83666],80:[0,.68611,.15972,0,.72309],81:[.19444,.68611,0,0,.86861],82:[0,.68611,.00421,0,.87235],83:[0,.68611,.05382,0,.69271],84:[0,.68611,.15972,0,.63663],85:[0,.68611,.11424,0,.80027],86:[0,.68611,.25555,0,.67778],87:[0,.68611,.15972,0,1.09305],88:[0,.68611,.07778,0,.94722],89:[0,.68611,.25555,0,.67458],90:[0,.68611,.06979,0,.77257],97:[0,.44444,0,0,.63287],98:[0,.69444,0,0,.52083],99:[0,.44444,0,0,.51342],100:[0,.69444,0,0,.60972],101:[0,.44444,0,0,.55361],102:[.19444,.69444,.11042,0,.56806],103:[.19444,.44444,.03704,0,.5449],104:[0,.69444,0,0,.66759],105:[0,.69326,0,0,.4048],106:[.19444,.69326,.0622,0,.47083],107:[0,.69444,.01852,0,.6037],108:[0,.69444,.0088,0,.34815],109:[0,.44444,0,0,1.0324],110:[0,.44444,0,0,.71296],111:[0,.44444,0,0,.58472],112:[.19444,.44444,0,0,.60092],113:[.19444,.44444,.03704,0,.54213],114:[0,.44444,.03194,0,.5287],115:[0,.44444,0,0,.53125],116:[0,.63492,0,0,.41528],117:[0,.44444,0,0,.68102],118:[0,.44444,.03704,0,.56666],119:[0,.44444,.02778,0,.83148],120:[0,.44444,0,0,.65903],121:[.19444,.44444,.03704,0,.59028],122:[0,.44444,.04213,0,.55509],160:[0,0,0,0,.25],915:[0,.68611,.15972,0,.65694],916:[0,.68611,0,0,.95833],920:[0,.68611,.03194,0,.86722],923:[0,.68611,0,0,.80555],926:[0,.68611,.07458,0,.84125],928:[0,.68611,.08229,0,.98229],931:[0,.68611,.05451,0,.88507],933:[0,.68611,.15972,0,.67083],934:[0,.68611,0,0,.76666],936:[0,.68611,.11653,0,.71402],937:[0,.68611,.04835,0,.8789],945:[0,.44444,0,0,.76064],946:[.19444,.69444,.03403,0,.65972],947:[.19444,.44444,.06389,0,.59003],948:[0,.69444,.03819,0,.52222],949:[0,.44444,0,0,.52882],950:[.19444,.69444,.06215,0,.50833],951:[.19444,.44444,.03704,0,.6],952:[0,.69444,.03194,0,.5618],953:[0,.44444,0,0,.41204],954:[0,.44444,0,0,.66759],955:[0,.69444,0,0,.67083],956:[.19444,.44444,0,0,.70787],957:[0,.44444,.06898,0,.57685],958:[.19444,.69444,.03021,0,.50833],959:[0,.44444,0,0,.58472],960:[0,.44444,.03704,0,.68241],961:[.19444,.44444,0,0,.6118],962:[.09722,.44444,.07917,0,.42361],963:[0,.44444,.03704,0,.68588],964:[0,.44444,.13472,0,.52083],965:[0,.44444,.03704,0,.63055],966:[.19444,.44444,0,0,.74722],967:[.19444,.44444,0,0,.71805],968:[.19444,.69444,.03704,0,.75833],969:[0,.44444,.03704,0,.71782],977:[0,.69444,0,0,.69155],981:[.19444,.69444,0,0,.7125],982:[0,.44444,.03194,0,.975],1009:[.19444,.44444,0,0,.6118],1013:[0,.44444,0,0,.48333],57649:[0,.44444,0,0,.39352],57911:[.19444,.44444,0,0,.43889]},"Math-Italic":{32:[0,0,0,0,.25],48:[0,.43056,0,0,.5],49:[0,.43056,0,0,.5],50:[0,.43056,0,0,.5],51:[.19444,.43056,0,0,.5],52:[.19444,.43056,0,0,.5],53:[.19444,.43056,0,0,.5],54:[0,.64444,0,0,.5],55:[.19444,.43056,0,0,.5],56:[0,.64444,0,0,.5],57:[.19444,.43056,0,0,.5],65:[0,.68333,0,.13889,.75],66:[0,.68333,.05017,.08334,.75851],67:[0,.68333,.07153,.08334,.71472],68:[0,.68333,.02778,.05556,.82792],69:[0,.68333,.05764,.08334,.7382],70:[0,.68333,.13889,.08334,.64306],71:[0,.68333,0,.08334,.78625],72:[0,.68333,.08125,.05556,.83125],73:[0,.68333,.07847,.11111,.43958],74:[0,.68333,.09618,.16667,.55451],75:[0,.68333,.07153,.05556,.84931],76:[0,.68333,0,.02778,.68056],77:[0,.68333,.10903,.08334,.97014],78:[0,.68333,.10903,.08334,.80347],79:[0,.68333,.02778,.08334,.76278],80:[0,.68333,.13889,.08334,.64201],81:[.19444,.68333,0,.08334,.79056],82:[0,.68333,.00773,.08334,.75929],83:[0,.68333,.05764,.08334,.6132],84:[0,.68333,.13889,.08334,.58438],85:[0,.68333,.10903,.02778,.68278],86:[0,.68333,.22222,0,.58333],87:[0,.68333,.13889,0,.94445],88:[0,.68333,.07847,.08334,.82847],89:[0,.68333,.22222,0,.58056],90:[0,.68333,.07153,.08334,.68264],97:[0,.43056,0,0,.52859],98:[0,.69444,0,0,.42917],99:[0,.43056,0,.05556,.43276],100:[0,.69444,0,.16667,.52049],101:[0,.43056,0,.05556,.46563],102:[.19444,.69444,.10764,.16667,.48959],103:[.19444,.43056,.03588,.02778,.47697],104:[0,.69444,0,0,.57616],105:[0,.65952,0,0,.34451],106:[.19444,.65952,.05724,0,.41181],107:[0,.69444,.03148,0,.5206],108:[0,.69444,.01968,.08334,.29838],109:[0,.43056,0,0,.87801],110:[0,.43056,0,0,.60023],111:[0,.43056,0,.05556,.48472],112:[.19444,.43056,0,.08334,.50313],113:[.19444,.43056,.03588,.08334,.44641],114:[0,.43056,.02778,.05556,.45116],115:[0,.43056,0,.05556,.46875],116:[0,.61508,0,.08334,.36111],117:[0,.43056,0,.02778,.57246],118:[0,.43056,.03588,.02778,.48472],119:[0,.43056,.02691,.08334,.71592],120:[0,.43056,0,.02778,.57153],121:[.19444,.43056,.03588,.05556,.49028],122:[0,.43056,.04398,.05556,.46505],160:[0,0,0,0,.25],915:[0,.68333,.13889,.08334,.61528],916:[0,.68333,0,.16667,.83334],920:[0,.68333,.02778,.08334,.76278],923:[0,.68333,0,.16667,.69445],926:[0,.68333,.07569,.08334,.74236],928:[0,.68333,.08125,.05556,.83125],931:[0,.68333,.05764,.08334,.77986],933:[0,.68333,.13889,.05556,.58333],934:[0,.68333,0,.08334,.66667],936:[0,.68333,.11,.05556,.61222],937:[0,.68333,.05017,.08334,.7724],945:[0,.43056,.0037,.02778,.6397],946:[.19444,.69444,.05278,.08334,.56563],947:[.19444,.43056,.05556,0,.51773],948:[0,.69444,.03785,.05556,.44444],949:[0,.43056,0,.08334,.46632],950:[.19444,.69444,.07378,.08334,.4375],951:[.19444,.43056,.03588,.05556,.49653],952:[0,.69444,.02778,.08334,.46944],953:[0,.43056,0,.05556,.35394],954:[0,.43056,0,0,.57616],955:[0,.69444,0,0,.58334],956:[.19444,.43056,0,.02778,.60255],957:[0,.43056,.06366,.02778,.49398],958:[.19444,.69444,.04601,.11111,.4375],959:[0,.43056,0,.05556,.48472],960:[0,.43056,.03588,0,.57003],961:[.19444,.43056,0,.08334,.51702],962:[.09722,.43056,.07986,.08334,.36285],963:[0,.43056,.03588,0,.57141],964:[0,.43056,.1132,.02778,.43715],965:[0,.43056,.03588,.02778,.54028],966:[.19444,.43056,0,.08334,.65417],967:[.19444,.43056,0,.05556,.62569],968:[.19444,.69444,.03588,.11111,.65139],969:[0,.43056,.03588,0,.62245],977:[0,.69444,0,.08334,.59144],981:[.19444,.69444,0,.08334,.59583],982:[0,.43056,.02778,0,.82813],1009:[.19444,.43056,0,.08334,.51702],1013:[0,.43056,0,.05556,.4059],57649:[0,.43056,0,.02778,.32246],57911:[.19444,.43056,0,.08334,.38403]},"SansSerif-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.36667],34:[0,.69444,0,0,.55834],35:[.19444,.69444,0,0,.91667],36:[.05556,.75,0,0,.55],37:[.05556,.75,0,0,1.02912],38:[0,.69444,0,0,.83056],39:[0,.69444,0,0,.30556],40:[.25,.75,0,0,.42778],41:[.25,.75,0,0,.42778],42:[0,.75,0,0,.55],43:[.11667,.61667,0,0,.85556],44:[.10556,.13056,0,0,.30556],45:[0,.45833,0,0,.36667],46:[0,.13056,0,0,.30556],47:[.25,.75,0,0,.55],48:[0,.69444,0,0,.55],49:[0,.69444,0,0,.55],50:[0,.69444,0,0,.55],51:[0,.69444,0,0,.55],52:[0,.69444,0,0,.55],53:[0,.69444,0,0,.55],54:[0,.69444,0,0,.55],55:[0,.69444,0,0,.55],56:[0,.69444,0,0,.55],57:[0,.69444,0,0,.55],58:[0,.45833,0,0,.30556],59:[.10556,.45833,0,0,.30556],61:[-.09375,.40625,0,0,.85556],63:[0,.69444,0,0,.51945],64:[0,.69444,0,0,.73334],65:[0,.69444,0,0,.73334],66:[0,.69444,0,0,.73334],67:[0,.69444,0,0,.70278],68:[0,.69444,0,0,.79445],69:[0,.69444,0,0,.64167],70:[0,.69444,0,0,.61111],71:[0,.69444,0,0,.73334],72:[0,.69444,0,0,.79445],73:[0,.69444,0,0,.33056],74:[0,.69444,0,0,.51945],75:[0,.69444,0,0,.76389],76:[0,.69444,0,0,.58056],77:[0,.69444,0,0,.97778],78:[0,.69444,0,0,.79445],79:[0,.69444,0,0,.79445],80:[0,.69444,0,0,.70278],81:[.10556,.69444,0,0,.79445],82:[0,.69444,0,0,.70278],83:[0,.69444,0,0,.61111],84:[0,.69444,0,0,.73334],85:[0,.69444,0,0,.76389],86:[0,.69444,.01528,0,.73334],87:[0,.69444,.01528,0,1.03889],88:[0,.69444,0,0,.73334],89:[0,.69444,.0275,0,.73334],90:[0,.69444,0,0,.67223],91:[.25,.75,0,0,.34306],93:[.25,.75,0,0,.34306],94:[0,.69444,0,0,.55],95:[.35,.10833,.03056,0,.55],97:[0,.45833,0,0,.525],98:[0,.69444,0,0,.56111],99:[0,.45833,0,0,.48889],100:[0,.69444,0,0,.56111],101:[0,.45833,0,0,.51111],102:[0,.69444,.07639,0,.33611],103:[.19444,.45833,.01528,0,.55],104:[0,.69444,0,0,.56111],105:[0,.69444,0,0,.25556],106:[.19444,.69444,0,0,.28611],107:[0,.69444,0,0,.53056],108:[0,.69444,0,0,.25556],109:[0,.45833,0,0,.86667],110:[0,.45833,0,0,.56111],111:[0,.45833,0,0,.55],112:[.19444,.45833,0,0,.56111],113:[.19444,.45833,0,0,.56111],114:[0,.45833,.01528,0,.37222],115:[0,.45833,0,0,.42167],116:[0,.58929,0,0,.40417],117:[0,.45833,0,0,.56111],118:[0,.45833,.01528,0,.5],119:[0,.45833,.01528,0,.74445],120:[0,.45833,0,0,.5],121:[.19444,.45833,.01528,0,.5],122:[0,.45833,0,0,.47639],126:[.35,.34444,0,0,.55],160:[0,0,0,0,.25],168:[0,.69444,0,0,.55],176:[0,.69444,0,0,.73334],180:[0,.69444,0,0,.55],184:[.17014,0,0,0,.48889],305:[0,.45833,0,0,.25556],567:[.19444,.45833,0,0,.28611],710:[0,.69444,0,0,.55],711:[0,.63542,0,0,.55],713:[0,.63778,0,0,.55],728:[0,.69444,0,0,.55],729:[0,.69444,0,0,.30556],730:[0,.69444,0,0,.73334],732:[0,.69444,0,0,.55],733:[0,.69444,0,0,.55],915:[0,.69444,0,0,.58056],916:[0,.69444,0,0,.91667],920:[0,.69444,0,0,.85556],923:[0,.69444,0,0,.67223],926:[0,.69444,0,0,.73334],928:[0,.69444,0,0,.79445],931:[0,.69444,0,0,.79445],933:[0,.69444,0,0,.85556],934:[0,.69444,0,0,.79445],936:[0,.69444,0,0,.85556],937:[0,.69444,0,0,.79445],8211:[0,.45833,.03056,0,.55],8212:[0,.45833,.03056,0,1.10001],8216:[0,.69444,0,0,.30556],8217:[0,.69444,0,0,.30556],8220:[0,.69444,0,0,.55834],8221:[0,.69444,0,0,.55834]},"SansSerif-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.05733,0,.31945],34:[0,.69444,.00316,0,.5],35:[.19444,.69444,.05087,0,.83334],36:[.05556,.75,.11156,0,.5],37:[.05556,.75,.03126,0,.83334],38:[0,.69444,.03058,0,.75834],39:[0,.69444,.07816,0,.27778],40:[.25,.75,.13164,0,.38889],41:[.25,.75,.02536,0,.38889],42:[0,.75,.11775,0,.5],43:[.08333,.58333,.02536,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,.01946,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,.13164,0,.5],48:[0,.65556,.11156,0,.5],49:[0,.65556,.11156,0,.5],50:[0,.65556,.11156,0,.5],51:[0,.65556,.11156,0,.5],52:[0,.65556,.11156,0,.5],53:[0,.65556,.11156,0,.5],54:[0,.65556,.11156,0,.5],55:[0,.65556,.11156,0,.5],56:[0,.65556,.11156,0,.5],57:[0,.65556,.11156,0,.5],58:[0,.44444,.02502,0,.27778],59:[.125,.44444,.02502,0,.27778],61:[-.13,.37,.05087,0,.77778],63:[0,.69444,.11809,0,.47222],64:[0,.69444,.07555,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,.08293,0,.66667],67:[0,.69444,.11983,0,.63889],68:[0,.69444,.07555,0,.72223],69:[0,.69444,.11983,0,.59722],70:[0,.69444,.13372,0,.56945],71:[0,.69444,.11983,0,.66667],72:[0,.69444,.08094,0,.70834],73:[0,.69444,.13372,0,.27778],74:[0,.69444,.08094,0,.47222],75:[0,.69444,.11983,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,.08094,0,.875],78:[0,.69444,.08094,0,.70834],79:[0,.69444,.07555,0,.73611],80:[0,.69444,.08293,0,.63889],81:[.125,.69444,.07555,0,.73611],82:[0,.69444,.08293,0,.64584],83:[0,.69444,.09205,0,.55556],84:[0,.69444,.13372,0,.68056],85:[0,.69444,.08094,0,.6875],86:[0,.69444,.1615,0,.66667],87:[0,.69444,.1615,0,.94445],88:[0,.69444,.13372,0,.66667],89:[0,.69444,.17261,0,.66667],90:[0,.69444,.11983,0,.61111],91:[.25,.75,.15942,0,.28889],93:[.25,.75,.08719,0,.28889],94:[0,.69444,.0799,0,.5],95:[.35,.09444,.08616,0,.5],97:[0,.44444,.00981,0,.48056],98:[0,.69444,.03057,0,.51667],99:[0,.44444,.08336,0,.44445],100:[0,.69444,.09483,0,.51667],101:[0,.44444,.06778,0,.44445],102:[0,.69444,.21705,0,.30556],103:[.19444,.44444,.10836,0,.5],104:[0,.69444,.01778,0,.51667],105:[0,.67937,.09718,0,.23889],106:[.19444,.67937,.09162,0,.26667],107:[0,.69444,.08336,0,.48889],108:[0,.69444,.09483,0,.23889],109:[0,.44444,.01778,0,.79445],110:[0,.44444,.01778,0,.51667],111:[0,.44444,.06613,0,.5],112:[.19444,.44444,.0389,0,.51667],113:[.19444,.44444,.04169,0,.51667],114:[0,.44444,.10836,0,.34167],115:[0,.44444,.0778,0,.38333],116:[0,.57143,.07225,0,.36111],117:[0,.44444,.04169,0,.51667],118:[0,.44444,.10836,0,.46111],119:[0,.44444,.10836,0,.68334],120:[0,.44444,.09169,0,.46111],121:[.19444,.44444,.10836,0,.46111],122:[0,.44444,.08752,0,.43472],126:[.35,.32659,.08826,0,.5],160:[0,0,0,0,.25],168:[0,.67937,.06385,0,.5],176:[0,.69444,0,0,.73752],184:[.17014,0,0,0,.44445],305:[0,.44444,.04169,0,.23889],567:[.19444,.44444,.04169,0,.26667],710:[0,.69444,.0799,0,.5],711:[0,.63194,.08432,0,.5],713:[0,.60889,.08776,0,.5],714:[0,.69444,.09205,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,.09483,0,.5],729:[0,.67937,.07774,0,.27778],730:[0,.69444,0,0,.73752],732:[0,.67659,.08826,0,.5],733:[0,.69444,.09205,0,.5],915:[0,.69444,.13372,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,.07555,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,.12816,0,.66667],928:[0,.69444,.08094,0,.70834],931:[0,.69444,.11983,0,.72222],933:[0,.69444,.09031,0,.77778],934:[0,.69444,.04603,0,.72222],936:[0,.69444,.09031,0,.77778],937:[0,.69444,.08293,0,.72222],8211:[0,.44444,.08616,0,.5],8212:[0,.44444,.08616,0,1],8216:[0,.69444,.07816,0,.27778],8217:[0,.69444,.07816,0,.27778],8220:[0,.69444,.14205,0,.5],8221:[0,.69444,.00316,0,.5]},"SansSerif-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.31945],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.75834],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,0,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.65556,0,0,.5],49:[0,.65556,0,0,.5],50:[0,.65556,0,0,.5],51:[0,.65556,0,0,.5],52:[0,.65556,0,0,.5],53:[0,.65556,0,0,.5],54:[0,.65556,0,0,.5],55:[0,.65556,0,0,.5],56:[0,.65556,0,0,.5],57:[0,.65556,0,0,.5],58:[0,.44444,0,0,.27778],59:[.125,.44444,0,0,.27778],61:[-.13,.37,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,0,0,.66667],67:[0,.69444,0,0,.63889],68:[0,.69444,0,0,.72223],69:[0,.69444,0,0,.59722],70:[0,.69444,0,0,.56945],71:[0,.69444,0,0,.66667],72:[0,.69444,0,0,.70834],73:[0,.69444,0,0,.27778],74:[0,.69444,0,0,.47222],75:[0,.69444,0,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,0,0,.875],78:[0,.69444,0,0,.70834],79:[0,.69444,0,0,.73611],80:[0,.69444,0,0,.63889],81:[.125,.69444,0,0,.73611],82:[0,.69444,0,0,.64584],83:[0,.69444,0,0,.55556],84:[0,.69444,0,0,.68056],85:[0,.69444,0,0,.6875],86:[0,.69444,.01389,0,.66667],87:[0,.69444,.01389,0,.94445],88:[0,.69444,0,0,.66667],89:[0,.69444,.025,0,.66667],90:[0,.69444,0,0,.61111],91:[.25,.75,0,0,.28889],93:[.25,.75,0,0,.28889],94:[0,.69444,0,0,.5],95:[.35,.09444,.02778,0,.5],97:[0,.44444,0,0,.48056],98:[0,.69444,0,0,.51667],99:[0,.44444,0,0,.44445],100:[0,.69444,0,0,.51667],101:[0,.44444,0,0,.44445],102:[0,.69444,.06944,0,.30556],103:[.19444,.44444,.01389,0,.5],104:[0,.69444,0,0,.51667],105:[0,.67937,0,0,.23889],106:[.19444,.67937,0,0,.26667],107:[0,.69444,0,0,.48889],108:[0,.69444,0,0,.23889],109:[0,.44444,0,0,.79445],110:[0,.44444,0,0,.51667],111:[0,.44444,0,0,.5],112:[.19444,.44444,0,0,.51667],113:[.19444,.44444,0,0,.51667],114:[0,.44444,.01389,0,.34167],115:[0,.44444,0,0,.38333],116:[0,.57143,0,0,.36111],117:[0,.44444,0,0,.51667],118:[0,.44444,.01389,0,.46111],119:[0,.44444,.01389,0,.68334],120:[0,.44444,0,0,.46111],121:[.19444,.44444,.01389,0,.46111],122:[0,.44444,0,0,.43472],126:[.35,.32659,0,0,.5],160:[0,0,0,0,.25],168:[0,.67937,0,0,.5],176:[0,.69444,0,0,.66667],184:[.17014,0,0,0,.44445],305:[0,.44444,0,0,.23889],567:[.19444,.44444,0,0,.26667],710:[0,.69444,0,0,.5],711:[0,.63194,0,0,.5],713:[0,.60889,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.67937,0,0,.27778],730:[0,.69444,0,0,.66667],732:[0,.67659,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.69444,0,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,0,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,0,0,.66667],928:[0,.69444,0,0,.70834],931:[0,.69444,0,0,.72222],933:[0,.69444,0,0,.77778],934:[0,.69444,0,0,.72222],936:[0,.69444,0,0,.77778],937:[0,.69444,0,0,.72222],8211:[0,.44444,.02778,0,.5],8212:[0,.44444,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5]},"Script-Regular":{32:[0,0,0,0,.25],65:[0,.7,.22925,0,.80253],66:[0,.7,.04087,0,.90757],67:[0,.7,.1689,0,.66619],68:[0,.7,.09371,0,.77443],69:[0,.7,.18583,0,.56162],70:[0,.7,.13634,0,.89544],71:[0,.7,.17322,0,.60961],72:[0,.7,.29694,0,.96919],73:[0,.7,.19189,0,.80907],74:[.27778,.7,.19189,0,1.05159],75:[0,.7,.31259,0,.91364],76:[0,.7,.19189,0,.87373],77:[0,.7,.15981,0,1.08031],78:[0,.7,.3525,0,.9015],79:[0,.7,.08078,0,.73787],80:[0,.7,.08078,0,1.01262],81:[0,.7,.03305,0,.88282],82:[0,.7,.06259,0,.85],83:[0,.7,.19189,0,.86767],84:[0,.7,.29087,0,.74697],85:[0,.7,.25815,0,.79996],86:[0,.7,.27523,0,.62204],87:[0,.7,.27523,0,.80532],88:[0,.7,.26006,0,.94445],89:[0,.7,.2939,0,.70961],90:[0,.7,.24037,0,.8212],160:[0,0,0,0,.25]},"Size1-Regular":{32:[0,0,0,0,.25],40:[.35001,.85,0,0,.45834],41:[.35001,.85,0,0,.45834],47:[.35001,.85,0,0,.57778],91:[.35001,.85,0,0,.41667],92:[.35001,.85,0,0,.57778],93:[.35001,.85,0,0,.41667],123:[.35001,.85,0,0,.58334],125:[.35001,.85,0,0,.58334],160:[0,0,0,0,.25],710:[0,.72222,0,0,.55556],732:[0,.72222,0,0,.55556],770:[0,.72222,0,0,.55556],771:[0,.72222,0,0,.55556],8214:[-99e-5,.601,0,0,.77778],8593:[1e-5,.6,0,0,.66667],8595:[1e-5,.6,0,0,.66667],8657:[1e-5,.6,0,0,.77778],8659:[1e-5,.6,0,0,.77778],8719:[.25001,.75,0,0,.94445],8720:[.25001,.75,0,0,.94445],8721:[.25001,.75,0,0,1.05556],8730:[.35001,.85,0,0,1],8739:[-.00599,.606,0,0,.33333],8741:[-.00599,.606,0,0,.55556],8747:[.30612,.805,.19445,0,.47222],8748:[.306,.805,.19445,0,.47222],8749:[.306,.805,.19445,0,.47222],8750:[.30612,.805,.19445,0,.47222],8896:[.25001,.75,0,0,.83334],8897:[.25001,.75,0,0,.83334],8898:[.25001,.75,0,0,.83334],8899:[.25001,.75,0,0,.83334],8968:[.35001,.85,0,0,.47222],8969:[.35001,.85,0,0,.47222],8970:[.35001,.85,0,0,.47222],8971:[.35001,.85,0,0,.47222],9168:[-99e-5,.601,0,0,.66667],10216:[.35001,.85,0,0,.47222],10217:[.35001,.85,0,0,.47222],10752:[.25001,.75,0,0,1.11111],10753:[.25001,.75,0,0,1.11111],10754:[.25001,.75,0,0,1.11111],10756:[.25001,.75,0,0,.83334],10758:[.25001,.75,0,0,.83334]},"Size2-Regular":{32:[0,0,0,0,.25],40:[.65002,1.15,0,0,.59722],41:[.65002,1.15,0,0,.59722],47:[.65002,1.15,0,0,.81111],91:[.65002,1.15,0,0,.47222],92:[.65002,1.15,0,0,.81111],93:[.65002,1.15,0,0,.47222],123:[.65002,1.15,0,0,.66667],125:[.65002,1.15,0,0,.66667],160:[0,0,0,0,.25],710:[0,.75,0,0,1],732:[0,.75,0,0,1],770:[0,.75,0,0,1],771:[0,.75,0,0,1],8719:[.55001,1.05,0,0,1.27778],8720:[.55001,1.05,0,0,1.27778],8721:[.55001,1.05,0,0,1.44445],8730:[.65002,1.15,0,0,1],8747:[.86225,1.36,.44445,0,.55556],8748:[.862,1.36,.44445,0,.55556],8749:[.862,1.36,.44445,0,.55556],8750:[.86225,1.36,.44445,0,.55556],8896:[.55001,1.05,0,0,1.11111],8897:[.55001,1.05,0,0,1.11111],8898:[.55001,1.05,0,0,1.11111],8899:[.55001,1.05,0,0,1.11111],8968:[.65002,1.15,0,0,.52778],8969:[.65002,1.15,0,0,.52778],8970:[.65002,1.15,0,0,.52778],8971:[.65002,1.15,0,0,.52778],10216:[.65002,1.15,0,0,.61111],10217:[.65002,1.15,0,0,.61111],10752:[.55001,1.05,0,0,1.51112],10753:[.55001,1.05,0,0,1.51112],10754:[.55001,1.05,0,0,1.51112],10756:[.55001,1.05,0,0,1.11111],10758:[.55001,1.05,0,0,1.11111]},"Size3-Regular":{32:[0,0,0,0,.25],40:[.95003,1.45,0,0,.73611],41:[.95003,1.45,0,0,.73611],47:[.95003,1.45,0,0,1.04445],91:[.95003,1.45,0,0,.52778],92:[.95003,1.45,0,0,1.04445],93:[.95003,1.45,0,0,.52778],123:[.95003,1.45,0,0,.75],125:[.95003,1.45,0,0,.75],160:[0,0,0,0,.25],710:[0,.75,0,0,1.44445],732:[0,.75,0,0,1.44445],770:[0,.75,0,0,1.44445],771:[0,.75,0,0,1.44445],8730:[.95003,1.45,0,0,1],8968:[.95003,1.45,0,0,.58334],8969:[.95003,1.45,0,0,.58334],8970:[.95003,1.45,0,0,.58334],8971:[.95003,1.45,0,0,.58334],10216:[.95003,1.45,0,0,.75],10217:[.95003,1.45,0,0,.75]},"Size4-Regular":{32:[0,0,0,0,.25],40:[1.25003,1.75,0,0,.79167],41:[1.25003,1.75,0,0,.79167],47:[1.25003,1.75,0,0,1.27778],91:[1.25003,1.75,0,0,.58334],92:[1.25003,1.75,0,0,1.27778],93:[1.25003,1.75,0,0,.58334],123:[1.25003,1.75,0,0,.80556],125:[1.25003,1.75,0,0,.80556],160:[0,0,0,0,.25],710:[0,.825,0,0,1.8889],732:[0,.825,0,0,1.8889],770:[0,.825,0,0,1.8889],771:[0,.825,0,0,1.8889],8730:[1.25003,1.75,0,0,1],8968:[1.25003,1.75,0,0,.63889],8969:[1.25003,1.75,0,0,.63889],8970:[1.25003,1.75,0,0,.63889],8971:[1.25003,1.75,0,0,.63889],9115:[.64502,1.155,0,0,.875],9116:[1e-5,.6,0,0,.875],9117:[.64502,1.155,0,0,.875],9118:[.64502,1.155,0,0,.875],9119:[1e-5,.6,0,0,.875],9120:[.64502,1.155,0,0,.875],9121:[.64502,1.155,0,0,.66667],9122:[-99e-5,.601,0,0,.66667],9123:[.64502,1.155,0,0,.66667],9124:[.64502,1.155,0,0,.66667],9125:[-99e-5,.601,0,0,.66667],9126:[.64502,1.155,0,0,.66667],9127:[1e-5,.9,0,0,.88889],9128:[.65002,1.15,0,0,.88889],9129:[.90001,0,0,0,.88889],9130:[0,.3,0,0,.88889],9131:[1e-5,.9,0,0,.88889],9132:[.65002,1.15,0,0,.88889],9133:[.90001,0,0,0,.88889],9143:[.88502,.915,0,0,1.05556],10216:[1.25003,1.75,0,0,.80556],10217:[1.25003,1.75,0,0,.80556],57344:[-.00499,.605,0,0,1.05556],57345:[-.00499,.605,0,0,1.05556],57680:[0,.12,0,0,.45],57681:[0,.12,0,0,.45],57682:[0,.12,0,0,.45],57683:[0,.12,0,0,.45]},"Typewriter-Regular":{32:[0,0,0,0,.525],33:[0,.61111,0,0,.525],34:[0,.61111,0,0,.525],35:[0,.61111,0,0,.525],36:[.08333,.69444,0,0,.525],37:[.08333,.69444,0,0,.525],38:[0,.61111,0,0,.525],39:[0,.61111,0,0,.525],40:[.08333,.69444,0,0,.525],41:[.08333,.69444,0,0,.525],42:[0,.52083,0,0,.525],43:[-.08056,.53055,0,0,.525],44:[.13889,.125,0,0,.525],45:[-.08056,.53055,0,0,.525],46:[0,.125,0,0,.525],47:[.08333,.69444,0,0,.525],48:[0,.61111,0,0,.525],49:[0,.61111,0,0,.525],50:[0,.61111,0,0,.525],51:[0,.61111,0,0,.525],52:[0,.61111,0,0,.525],53:[0,.61111,0,0,.525],54:[0,.61111,0,0,.525],55:[0,.61111,0,0,.525],56:[0,.61111,0,0,.525],57:[0,.61111,0,0,.525],58:[0,.43056,0,0,.525],59:[.13889,.43056,0,0,.525],60:[-.05556,.55556,0,0,.525],61:[-.19549,.41562,0,0,.525],62:[-.05556,.55556,0,0,.525],63:[0,.61111,0,0,.525],64:[0,.61111,0,0,.525],65:[0,.61111,0,0,.525],66:[0,.61111,0,0,.525],67:[0,.61111,0,0,.525],68:[0,.61111,0,0,.525],69:[0,.61111,0,0,.525],70:[0,.61111,0,0,.525],71:[0,.61111,0,0,.525],72:[0,.61111,0,0,.525],73:[0,.61111,0,0,.525],74:[0,.61111,0,0,.525],75:[0,.61111,0,0,.525],76:[0,.61111,0,0,.525],77:[0,.61111,0,0,.525],78:[0,.61111,0,0,.525],79:[0,.61111,0,0,.525],80:[0,.61111,0,0,.525],81:[.13889,.61111,0,0,.525],82:[0,.61111,0,0,.525],83:[0,.61111,0,0,.525],84:[0,.61111,0,0,.525],85:[0,.61111,0,0,.525],86:[0,.61111,0,0,.525],87:[0,.61111,0,0,.525],88:[0,.61111,0,0,.525],89:[0,.61111,0,0,.525],90:[0,.61111,0,0,.525],91:[.08333,.69444,0,0,.525],92:[.08333,.69444,0,0,.525],93:[.08333,.69444,0,0,.525],94:[0,.61111,0,0,.525],95:[.09514,0,0,0,.525],96:[0,.61111,0,0,.525],97:[0,.43056,0,0,.525],98:[0,.61111,0,0,.525],99:[0,.43056,0,0,.525],100:[0,.61111,0,0,.525],101:[0,.43056,0,0,.525],102:[0,.61111,0,0,.525],103:[.22222,.43056,0,0,.525],104:[0,.61111,0,0,.525],105:[0,.61111,0,0,.525],106:[.22222,.61111,0,0,.525],107:[0,.61111,0,0,.525],108:[0,.61111,0,0,.525],109:[0,.43056,0,0,.525],110:[0,.43056,0,0,.525],111:[0,.43056,0,0,.525],112:[.22222,.43056,0,0,.525],113:[.22222,.43056,0,0,.525],114:[0,.43056,0,0,.525],115:[0,.43056,0,0,.525],116:[0,.55358,0,0,.525],117:[0,.43056,0,0,.525],118:[0,.43056,0,0,.525],119:[0,.43056,0,0,.525],120:[0,.43056,0,0,.525],121:[.22222,.43056,0,0,.525],122:[0,.43056,0,0,.525],123:[.08333,.69444,0,0,.525],124:[.08333,.69444,0,0,.525],125:[.08333,.69444,0,0,.525],126:[0,.61111,0,0,.525],127:[0,.61111,0,0,.525],160:[0,0,0,0,.525],176:[0,.61111,0,0,.525],184:[.19445,0,0,0,.525],305:[0,.43056,0,0,.525],567:[.22222,.43056,0,0,.525],711:[0,.56597,0,0,.525],713:[0,.56555,0,0,.525],714:[0,.61111,0,0,.525],715:[0,.61111,0,0,.525],728:[0,.61111,0,0,.525],730:[0,.61111,0,0,.525],770:[0,.61111,0,0,.525],771:[0,.61111,0,0,.525],776:[0,.61111,0,0,.525],915:[0,.61111,0,0,.525],916:[0,.61111,0,0,.525],920:[0,.61111,0,0,.525],923:[0,.61111,0,0,.525],926:[0,.61111,0,0,.525],928:[0,.61111,0,0,.525],931:[0,.61111,0,0,.525],933:[0,.61111,0,0,.525],934:[0,.61111,0,0,.525],936:[0,.61111,0,0,.525],937:[0,.61111,0,0,.525],8216:[0,.61111,0,0,.525],8217:[0,.61111,0,0,.525],8242:[0,.61111,0,0,.525],9251:[.11111,.21944,0,0,.525]}};const B={slant:[.25,.25,.25],space:[0,0,0],stretch:[0,0,0],shrink:[0,0,0],xHeight:[.431,.431,.431],quad:[1,1.171,1.472],extraSpace:[0,0,0],num1:[.677,.732,.925],num2:[.394,.384,.387],num3:[.444,.471,.504],denom1:[.686,.752,1.025],denom2:[.345,.344,.532],sup1:[.413,.503,.504],sup2:[.363,.431,.404],sup3:[.289,.286,.294],sub1:[.15,.143,.2],sub2:[.247,.286,.4],supDrop:[.386,.353,.494],subDrop:[.05,.071,.1],delim1:[2.39,1.7,1.98],delim2:[1.01,1.157,1.42],axisHeight:[.25,.25,.25],defaultRuleThickness:[.04,.049,.049],bigOpSpacing1:[.111,.111,.111],bigOpSpacing2:[.166,.166,.166],bigOpSpacing3:[.2,.2,.2],bigOpSpacing4:[.6,.611,.611],bigOpSpacing5:[.1,.143,.143],sqrtRuleThickness:[.04,.04,.04],ptPerEm:[10,10,10],doubleRuleSep:[.2,.2,.2],arrayRuleWidth:[.04,.04,.04],fboxsep:[.3,.3,.3],fboxrule:[.04,.04,.04]},C={"\xc5":"A","\xd0":"D","\xde":"o","\xe5":"a","\xf0":"d","\xfe":"o","\u0410":"A","\u0411":"B","\u0412":"B","\u0413":"F","\u0414":"A","\u0415":"E","\u0416":"K","\u0417":"3","\u0418":"N","\u0419":"N","\u041a":"K","\u041b":"N","\u041c":"M","\u041d":"H","\u041e":"O","\u041f":"N","\u0420":"P","\u0421":"C","\u0422":"T","\u0423":"y","\u0424":"O","\u0425":"X","\u0426":"U","\u0427":"h","\u0428":"W","\u0429":"W","\u042a":"B","\u042b":"X","\u042c":"B","\u042d":"3","\u042e":"X","\u042f":"R","\u0430":"a","\u0431":"b","\u0432":"a","\u0433":"r","\u0434":"y","\u0435":"e","\u0436":"m","\u0437":"e","\u0438":"n","\u0439":"n","\u043a":"n","\u043b":"n","\u043c":"m","\u043d":"n","\u043e":"o","\u043f":"n","\u0440":"p","\u0441":"c","\u0442":"o","\u0443":"y","\u0444":"b","\u0445":"x","\u0446":"n","\u0447":"n","\u0448":"w","\u0449":"w","\u044a":"a","\u044b":"m","\u044c":"a","\u044d":"e","\u044e":"m","\u044f":"r"};function N(e,t,r){if(!T[t])throw new Error("Font metrics not found for font: "+t+".");let n=e.charCodeAt(0),o=T[t][n];if(!o&&e[0]in C&&(n=C[e[0]].charCodeAt(0),o=T[t][n]),o||"text"!==r||S(n)&&(o=T[t][77]),o)return{depth:o[0],height:o[1],italic:o[2],skew:o[3],width:o[4]}}const q={};const I=[[1,1,1],[2,1,1],[3,1,1],[4,2,1],[5,2,1],[6,3,1],[7,4,2],[8,6,3],[9,7,6],[10,8,7],[11,10,9]],R=[.5,.6,.7,.8,.9,1,1.2,1.44,1.728,2.074,2.488],H=function(e,t){return t.size<2?e:I[e-1][t.size-1]};class O{constructor(e){this.style=void 0,this.color=void 0,this.size=void 0,this.textSize=void 0,this.phantom=void 0,this.font=void 0,this.fontFamily=void 0,this.fontWeight=void 0,this.fontShape=void 0,this.sizeMultiplier=void 0,this.maxSize=void 0,this.minRuleThickness=void 0,this._fontMetrics=void 0,this.style=e.style,this.color=e.color,this.size=e.size||O.BASESIZE,this.textSize=e.textSize||this.size,this.phantom=!!e.phantom,this.font=e.font||"",this.fontFamily=e.fontFamily||"",this.fontWeight=e.fontWeight||"",this.fontShape=e.fontShape||"",this.sizeMultiplier=R[this.size-1],this.maxSize=e.maxSize,this.minRuleThickness=e.minRuleThickness,this._fontMetrics=void 0}extend(e){const t={style:this.style,size:this.size,textSize:this.textSize,color:this.color,phantom:this.phantom,font:this.font,fontFamily:this.fontFamily,fontWeight:this.fontWeight,fontShape:this.fontShape,maxSize:this.maxSize,minRuleThickness:this.minRuleThickness};for(const r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return new O(t)}havingStyle(e){return this.style===e?this:this.extend({style:e,size:H(this.textSize,e)})}havingCrampedStyle(){return this.havingStyle(this.style.cramp())}havingSize(e){return this.size===e&&this.textSize===e?this:this.extend({style:this.style.text(),size:e,textSize:e,sizeMultiplier:R[e-1]})}havingBaseStyle(e){e=e||this.style.text();const t=H(O.BASESIZE,e);return this.size===t&&this.textSize===O.BASESIZE&&this.style===e?this:this.extend({style:e,size:t})}havingBaseSizing(){let e;switch(this.style.id){case 4:case 5:e=3;break;case 6:case 7:e=1;break;default:e=6}return this.extend({style:this.style.text(),size:e})}withColor(e){return this.extend({color:e})}withPhantom(){return this.extend({phantom:!0})}withFont(e){return this.extend({font:e})}withTextFontFamily(e){return this.extend({fontFamily:e,font:""})}withTextFontWeight(e){return this.extend({fontWeight:e,font:""})}withTextFontShape(e){return this.extend({fontShape:e,font:""})}sizingClasses(e){return e.size!==this.size?["sizing","reset-size"+e.size,"size"+this.size]:[]}baseSizingClasses(){return this.size!==O.BASESIZE?["sizing","reset-size"+this.size,"size"+O.BASESIZE]:[]}fontMetrics(){return this._fontMetrics||(this._fontMetrics=function(e){let t;if(t=e>=5?0:e>=3?1:2,!q[t]){const e=q[t]={cssEmPerMu:B.quad[t]/18};for(const r in B)B.hasOwnProperty(r)&&(e[r]=B[r][t])}return q[t]}(this.size)),this._fontMetrics}getColor(){return this.phantom?"transparent":this.color}}O.BASESIZE=6;var E=O;const L={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:1.00375,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:1.00375},D={ex:!0,em:!0,mu:!0},V=function(e){return"string"!=typeof e&&(e=e.unit),e in L||e in D||"ex"===e},P=function(e,t){let r;if(e.unit in L)r=L[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if("mu"===e.unit)r=t.fontMetrics().cssEmPerMu;else{let o;if(o=t.style.isTight()?t.havingStyle(t.style.text()):t,"ex"===e.unit)r=o.fontMetrics().xHeight;else{if("em"!==e.unit)throw new n("Invalid unit: '"+e.unit+"'");r=o.fontMetrics().quad}o!==t&&(r*=o.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*r,t.maxSize)},F=function(e){return+e.toFixed(4)+"em"},G=function(e){return e.filter((e=>e)).join(" ")},U=function(e,t,r){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=r||{},t){t.style.isTight()&&this.classes.push("mtight");const e=t.getColor();e&&(this.style.color=e)}},Y=function(e){const t=document.createElement(e);t.className=G(this.classes);for(const e in this.style)this.style.hasOwnProperty(e)&&(t.style[e]=this.style[e]);for(const e in this.attributes)this.attributes.hasOwnProperty(e)&&t.setAttribute(e,this.attributes[e]);for(let e=0;e/=\x00-\x1f]/,W=function(e){let t="<"+e;this.classes.length&&(t+=' class="'+l.escape(G(this.classes))+'"');let r="";for(const e in this.style)this.style.hasOwnProperty(e)&&(r+=l.hyphenate(e)+":"+this.style[e]+";");r&&(t+=' style="'+l.escape(r)+'"');for(const e in this.attributes)if(this.attributes.hasOwnProperty(e)){if(X.test(e))throw new n("Invalid attribute name '"+e+"'");t+=" "+e+'="'+l.escape(this.attributes[e])+'"'}t+=">";for(let e=0;e",t};class _{constructor(e,t,r,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,U.call(this,e,r,n),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return l.contains(this.classes,e)}toNode(){return Y.call(this,"span")}toMarkup(){return W.call(this,"span")}}class j{constructor(e,t,r,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,U.call(this,t,n),this.children=r||[],this.setAttribute("href",e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return l.contains(this.classes,e)}toNode(){return Y.call(this,"a")}toMarkup(){return W.call(this,"a")}}class ${constructor(e,t,r){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=["mord"],this.style=r}hasClass(e){return l.contains(this.classes,e)}toNode(){const e=document.createElement("img");e.src=this.src,e.alt=this.alt,e.className="mord";for(const t in this.style)this.style.hasOwnProperty(t)&&(e.style[t]=this.style[t]);return e}toMarkup(){let e=''+l.escape(this.alt)+'=n[0]&&e<=n[1])return r.name}}return null}(this.text.charCodeAt(0));l&&this.classes.push(l+"_fallback"),/[\xee\xef\xed\xec]/.test(this.text)&&(this.text=Z[this.text])}hasClass(e){return l.contains(this.classes,e)}toNode(){const e=document.createTextNode(this.text);let t=null;this.italic>0&&(t=document.createElement("span"),t.style.marginRight=F(this.italic)),this.classes.length>0&&(t=t||document.createElement("span"),t.className=G(this.classes));for(const e in this.style)this.style.hasOwnProperty(e)&&(t=t||document.createElement("span"),t.style[e]=this.style[e]);return t?(t.appendChild(e),t):e}toMarkup(){let e=!1,t="0&&(r+="margin-right:"+this.italic+"em;");for(const e in this.style)this.style.hasOwnProperty(e)&&(r+=l.hyphenate(e)+":"+this.style[e]+";");r&&(e=!0,t+=' style="'+l.escape(r)+'"');const n=l.escape(this.text);return e?(t+=">",t+=n,t+="
      ",t):n}}class J{constructor(e,t){this.children=void 0,this.attributes=void 0,this.children=e||[],this.attributes=t||{}}toNode(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");for(const t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);for(let t=0;t':''}}class ee{constructor(e){this.attributes=void 0,this.attributes=e||{}}toNode(){const e=document.createElementNS("http://www.w3.org/2000/svg","line");for(const t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);return e}toMarkup(){let e="","\\gt",!0),ie(ae,he,xe,"\u2208","\\in",!0),ie(ae,he,xe,"\ue020","\\@not"),ie(ae,he,xe,"\u2282","\\subset",!0),ie(ae,he,xe,"\u2283","\\supset",!0),ie(ae,he,xe,"\u2286","\\subseteq",!0),ie(ae,he,xe,"\u2287","\\supseteq",!0),ie(ae,ce,xe,"\u2288","\\nsubseteq",!0),ie(ae,ce,xe,"\u2289","\\nsupseteq",!0),ie(ae,he,xe,"\u22a8","\\models"),ie(ae,he,xe,"\u2190","\\leftarrow",!0),ie(ae,he,xe,"\u2264","\\le"),ie(ae,he,xe,"\u2264","\\leq",!0),ie(ae,he,xe,"<","\\lt",!0),ie(ae,he,xe,"\u2192","\\rightarrow",!0),ie(ae,he,xe,"\u2192","\\to"),ie(ae,ce,xe,"\u2271","\\ngeq",!0),ie(ae,ce,xe,"\u2270","\\nleq",!0),ie(ae,he,we,"\xa0","\\ "),ie(ae,he,we,"\xa0","\\space"),ie(ae,he,we,"\xa0","\\nobreakspace"),ie(le,he,we,"\xa0","\\ "),ie(le,he,we,"\xa0"," "),ie(le,he,we,"\xa0","\\space"),ie(le,he,we,"\xa0","\\nobreakspace"),ie(ae,he,we,null,"\\nobreak"),ie(ae,he,we,null,"\\allowbreak"),ie(ae,he,ye,",",","),ie(ae,he,ye,";",";"),ie(ae,ce,pe,"\u22bc","\\barwedge",!0),ie(ae,ce,pe,"\u22bb","\\veebar",!0),ie(ae,he,pe,"\u2299","\\odot",!0),ie(ae,he,pe,"\u2295","\\oplus",!0),ie(ae,he,pe,"\u2297","\\otimes",!0),ie(ae,he,ve,"\u2202","\\partial",!0),ie(ae,he,pe,"\u2298","\\oslash",!0),ie(ae,ce,pe,"\u229a","\\circledcirc",!0),ie(ae,ce,pe,"\u22a1","\\boxdot",!0),ie(ae,he,pe,"\u25b3","\\bigtriangleup"),ie(ae,he,pe,"\u25bd","\\bigtriangledown"),ie(ae,he,pe,"\u2020","\\dagger"),ie(ae,he,pe,"\u22c4","\\diamond"),ie(ae,he,pe,"\u22c6","\\star"),ie(ae,he,pe,"\u25c3","\\triangleleft"),ie(ae,he,pe,"\u25b9","\\triangleright"),ie(ae,he,be,"{","\\{"),ie(le,he,ve,"{","\\{"),ie(le,he,ve,"{","\\textbraceleft"),ie(ae,he,ue,"}","\\}"),ie(le,he,ve,"}","\\}"),ie(le,he,ve,"}","\\textbraceright"),ie(ae,he,be,"{","\\lbrace"),ie(ae,he,ue,"}","\\rbrace"),ie(ae,he,be,"[","\\lbrack",!0),ie(le,he,ve,"[","\\lbrack",!0),ie(ae,he,ue,"]","\\rbrack",!0),ie(le,he,ve,"]","\\rbrack",!0),ie(ae,he,be,"(","\\lparen",!0),ie(ae,he,ue,")","\\rparen",!0),ie(le,he,ve,"<","\\textless",!0),ie(le,he,ve,">","\\textgreater",!0),ie(ae,he,be,"\u230a","\\lfloor",!0),ie(ae,he,ue,"\u230b","\\rfloor",!0),ie(ae,he,be,"\u2308","\\lceil",!0),ie(ae,he,ue,"\u2309","\\rceil",!0),ie(ae,he,ve,"\\","\\backslash"),ie(ae,he,ve,"\u2223","|"),ie(ae,he,ve,"\u2223","\\vert"),ie(le,he,ve,"|","\\textbar",!0),ie(ae,he,ve,"\u2225","\\|"),ie(ae,he,ve,"\u2225","\\Vert"),ie(le,he,ve,"\u2225","\\textbardbl"),ie(le,he,ve,"~","\\textasciitilde"),ie(le,he,ve,"\\","\\textbackslash"),ie(le,he,ve,"^","\\textasciicircum"),ie(ae,he,xe,"\u2191","\\uparrow",!0),ie(ae,he,xe,"\u21d1","\\Uparrow",!0),ie(ae,he,xe,"\u2193","\\downarrow",!0),ie(ae,he,xe,"\u21d3","\\Downarrow",!0),ie(ae,he,xe,"\u2195","\\updownarrow",!0),ie(ae,he,xe,"\u21d5","\\Updownarrow",!0),ie(ae,he,fe,"\u2210","\\coprod"),ie(ae,he,fe,"\u22c1","\\bigvee"),ie(ae,he,fe,"\u22c0","\\bigwedge"),ie(ae,he,fe,"\u2a04","\\biguplus"),ie(ae,he,fe,"\u22c2","\\bigcap"),ie(ae,he,fe,"\u22c3","\\bigcup"),ie(ae,he,fe,"\u222b","\\int"),ie(ae,he,fe,"\u222b","\\intop"),ie(ae,he,fe,"\u222c","\\iint"),ie(ae,he,fe,"\u222d","\\iiint"),ie(ae,he,fe,"\u220f","\\prod"),ie(ae,he,fe,"\u2211","\\sum"),ie(ae,he,fe,"\u2a02","\\bigotimes"),ie(ae,he,fe,"\u2a01","\\bigoplus"),ie(ae,he,fe,"\u2a00","\\bigodot"),ie(ae,he,fe,"\u222e","\\oint"),ie(ae,he,fe,"\u222f","\\oiint"),ie(ae,he,fe,"\u2230","\\oiiint"),ie(ae,he,fe,"\u2a06","\\bigsqcup"),ie(ae,he,fe,"\u222b","\\smallint"),ie(le,he,de,"\u2026","\\textellipsis"),ie(ae,he,de,"\u2026","\\mathellipsis"),ie(le,he,de,"\u2026","\\ldots",!0),ie(ae,he,de,"\u2026","\\ldots",!0),ie(ae,he,de,"\u22ef","\\@cdots",!0),ie(ae,he,de,"\u22f1","\\ddots",!0),ie(ae,he,ve,"\u22ee","\\varvdots"),ie(le,he,ve,"\u22ee","\\varvdots"),ie(ae,he,me,"\u02ca","\\acute"),ie(ae,he,me,"\u02cb","\\grave"),ie(ae,he,me,"\xa8","\\ddot"),ie(ae,he,me,"~","\\tilde"),ie(ae,he,me,"\u02c9","\\bar"),ie(ae,he,me,"\u02d8","\\breve"),ie(ae,he,me,"\u02c7","\\check"),ie(ae,he,me,"^","\\hat"),ie(ae,he,me,"\u20d7","\\vec"),ie(ae,he,me,"\u02d9","\\dot"),ie(ae,he,me,"\u02da","\\mathring"),ie(ae,he,ge,"\ue131","\\@imath"),ie(ae,he,ge,"\ue237","\\@jmath"),ie(ae,he,ve,"\u0131","\u0131"),ie(ae,he,ve,"\u0237","\u0237"),ie(le,he,ve,"\u0131","\\i",!0),ie(le,he,ve,"\u0237","\\j",!0),ie(le,he,ve,"\xdf","\\ss",!0),ie(le,he,ve,"\xe6","\\ae",!0),ie(le,he,ve,"\u0153","\\oe",!0),ie(le,he,ve,"\xf8","\\o",!0),ie(le,he,ve,"\xc6","\\AE",!0),ie(le,he,ve,"\u0152","\\OE",!0),ie(le,he,ve,"\xd8","\\O",!0),ie(le,he,me,"\u02ca","\\'"),ie(le,he,me,"\u02cb","\\`"),ie(le,he,me,"\u02c6","\\^"),ie(le,he,me,"\u02dc","\\~"),ie(le,he,me,"\u02c9","\\="),ie(le,he,me,"\u02d8","\\u"),ie(le,he,me,"\u02d9","\\."),ie(le,he,me,"\xb8","\\c"),ie(le,he,me,"\u02da","\\r"),ie(le,he,me,"\u02c7","\\v"),ie(le,he,me,"\xa8",'\\"'),ie(le,he,me,"\u02dd","\\H"),ie(le,he,me,"\u25ef","\\textcircled");const ke={"--":!0,"---":!0,"``":!0,"''":!0};ie(le,he,ve,"\u2013","--",!0),ie(le,he,ve,"\u2013","\\textendash"),ie(le,he,ve,"\u2014","---",!0),ie(le,he,ve,"\u2014","\\textemdash"),ie(le,he,ve,"\u2018","`",!0),ie(le,he,ve,"\u2018","\\textquoteleft"),ie(le,he,ve,"\u2019","'",!0),ie(le,he,ve,"\u2019","\\textquoteright"),ie(le,he,ve,"\u201c","``",!0),ie(le,he,ve,"\u201c","\\textquotedblleft"),ie(le,he,ve,"\u201d","''",!0),ie(le,he,ve,"\u201d","\\textquotedblright"),ie(ae,he,ve,"\xb0","\\degree",!0),ie(le,he,ve,"\xb0","\\degree"),ie(le,he,ve,"\xb0","\\textdegree",!0),ie(ae,he,ve,"\xa3","\\pounds"),ie(ae,he,ve,"\xa3","\\mathsterling",!0),ie(le,he,ve,"\xa3","\\pounds"),ie(le,he,ve,"\xa3","\\textsterling",!0),ie(ae,ce,ve,"\u2720","\\maltese"),ie(le,ce,ve,"\u2720","\\maltese");const Se='0123456789/@."';for(let e=0;e<14;e++){const t=Se.charAt(e);ie(ae,he,ve,t,t)}const Me='0123456789!@*()-=+";:?/.,';for(let e=0;e<25;e++){const t=Me.charAt(e);ie(le,he,ve,t,t)}const ze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";for(let e=0;e<52;e++){const t=ze.charAt(e);ie(ae,he,ge,t,t),ie(le,he,ve,t,t)}ie(ae,ce,ve,"C","\u2102"),ie(le,ce,ve,"C","\u2102"),ie(ae,ce,ve,"H","\u210d"),ie(le,ce,ve,"H","\u210d"),ie(ae,ce,ve,"N","\u2115"),ie(le,ce,ve,"N","\u2115"),ie(ae,ce,ve,"P","\u2119"),ie(le,ce,ve,"P","\u2119"),ie(ae,ce,ve,"Q","\u211a"),ie(le,ce,ve,"Q","\u211a"),ie(ae,ce,ve,"R","\u211d"),ie(le,ce,ve,"R","\u211d"),ie(ae,ce,ve,"Z","\u2124"),ie(le,ce,ve,"Z","\u2124"),ie(ae,he,ge,"h","\u210e"),ie(le,he,ge,"h","\u210e");let Ae="";for(let e=0;e<52;e++){const t=ze.charAt(e);Ae=String.fromCharCode(55349,56320+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56372+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56424+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56580+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56684+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56736+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56788+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56840+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56944+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),e<26&&(Ae=String.fromCharCode(55349,56632+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,56476+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae))}Ae=String.fromCharCode(55349,56668),ie(ae,he,ge,"k",Ae),ie(le,he,ve,"k",Ae);for(let e=0;e<10;e++){const t=e.toString();Ae=String.fromCharCode(55349,57294+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,57314+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,57324+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae),Ae=String.fromCharCode(55349,57334+e),ie(ae,he,ge,t,Ae),ie(le,he,ve,t,Ae)}const Te="\xd0\xde\xfe";for(let e=0;e<3;e++){const t=Te.charAt(e);ie(ae,he,ge,t,t),ie(le,he,ve,t,t)}const Be=[["mathbf","textbf","Main-Bold"],["mathbf","textbf","Main-Bold"],["mathnormal","textit","Math-Italic"],["mathnormal","textit","Math-Italic"],["boldsymbol","boldsymbol","Main-BoldItalic"],["boldsymbol","boldsymbol","Main-BoldItalic"],["mathscr","textscr","Script-Regular"],["","",""],["","",""],["","",""],["mathfrak","textfrak","Fraktur-Regular"],["mathfrak","textfrak","Fraktur-Regular"],["mathbb","textbb","AMS-Regular"],["mathbb","textbb","AMS-Regular"],["mathboldfrak","textboldfrak","Fraktur-Regular"],["mathboldfrak","textboldfrak","Fraktur-Regular"],["mathsf","textsf","SansSerif-Regular"],["mathsf","textsf","SansSerif-Regular"],["mathboldsf","textboldsf","SansSerif-Bold"],["mathboldsf","textboldsf","SansSerif-Bold"],["mathitsf","textitsf","SansSerif-Italic"],["mathitsf","textitsf","SansSerif-Italic"],["","",""],["","",""],["mathtt","texttt","Typewriter-Regular"],["mathtt","texttt","Typewriter-Regular"]],Ce=[["mathbf","textbf","Main-Bold"],["","",""],["mathsf","textsf","SansSerif-Regular"],["mathboldsf","textboldsf","SansSerif-Bold"],["mathtt","texttt","Typewriter-Regular"]],Ne=function(e,t,r){return se[r][e]&&se[r][e].replace&&(e=se[r][e].replace),{value:e,metrics:N(e,t,r)}},qe=function(e,t,r,n,o){const s=Ne(e,t,r),i=s.metrics;let a;if(e=s.value,i){let t=i.italic;("text"===r||n&&"mathit"===n.font)&&(t=0),a=new K(e,i.height,i.depth,t,i.skew,i.width,o)}else"undefined"!=typeof console&&console.warn("No character metrics for '"+e+"' in style '"+t+"' and mode '"+r+"'"),a=new K(e,0,0,0,0,0,o);if(n){a.maxFontSize=n.sizeMultiplier,n.style.isTight()&&a.classes.push("mtight");const e=n.getColor();e&&(a.style.color=e)}return a},Ie=(e,t)=>{if(G(e.classes)!==G(t.classes)||e.skew!==t.skew||e.maxFontSize!==t.maxFontSize)return!1;if(1===e.classes.length){const t=e.classes[0];if("mbin"===t||"mord"===t)return!1}for(const r in e.style)if(e.style.hasOwnProperty(r)&&e.style[r]!==t.style[r])return!1;for(const r in t.style)if(t.style.hasOwnProperty(r)&&e.style[r]!==t.style[r])return!1;return!0},Re=function(e){let t=0,r=0,n=0;for(let o=0;ot&&(t=s.height),s.depth>r&&(r=s.depth),s.maxFontSize>n&&(n=s.maxFontSize)}e.height=t,e.depth=r,e.maxFontSize=n},He=function(e,t,r,n){const o=new _(e,t,r,n);return Re(o),o},Oe=(e,t,r,n)=>new _(e,t,r,n),Ee=function(e){const t=new A(e);return Re(t),t},Le=function(e,t,r){let n,o="";switch(e){case"amsrm":o="AMS";break;case"textrm":o="Main";break;case"textsf":o="SansSerif";break;case"texttt":o="Typewriter";break;default:o=e}return n="textbf"===t&&"textit"===r?"BoldItalic":"textbf"===t?"Bold":"textit"===t?"Italic":"Regular",o+"-"+n},De={mathbf:{variant:"bold",fontName:"Main-Bold"},mathrm:{variant:"normal",fontName:"Main-Regular"},textit:{variant:"italic",fontName:"Main-Italic"},mathit:{variant:"italic",fontName:"Main-Italic"},mathnormal:{variant:"italic",fontName:"Math-Italic"},mathsfit:{variant:"sans-serif-italic",fontName:"SansSerif-Italic"},mathbb:{variant:"double-struck",fontName:"AMS-Regular"},mathcal:{variant:"script",fontName:"Caligraphic-Regular"},mathfrak:{variant:"fraktur",fontName:"Fraktur-Regular"},mathscr:{variant:"script",fontName:"Script-Regular"},mathsf:{variant:"sans-serif",fontName:"SansSerif-Regular"},mathtt:{variant:"monospace",fontName:"Typewriter-Regular"}},Ve={vec:["vec",.471,.714],oiintSize1:["oiintSize1",.957,.499],oiintSize2:["oiintSize2",1.472,.659],oiiintSize1:["oiiintSize1",1.304,.499],oiiintSize2:["oiiintSize2",1.98,.659]};var Pe={fontMap:De,makeSymbol:qe,mathsym:function(e,t,r,n){return void 0===n&&(n=[]),"boldsymbol"===r.font&&Ne(e,"Main-Bold",t).metrics?qe(e,"Main-Bold",t,r,n.concat(["mathbf"])):"\\"===e||"main"===se[t][e].font?qe(e,"Main-Regular",t,r,n):qe(e,"AMS-Regular",t,r,n.concat(["amsrm"]))},makeSpan:He,makeSvgSpan:Oe,makeLineSpan:function(e,t,r){const n=He([e],[],t);return n.height=Math.max(r||t.fontMetrics().defaultRuleThickness,t.minRuleThickness),n.style.borderBottomWidth=F(n.height),n.maxFontSize=1,n},makeAnchor:function(e,t,r,n){const o=new j(e,t,r,n);return Re(o),o},makeFragment:Ee,wrapFragment:function(e,t){return e instanceof A?He([],[e],t):e},makeVList:function(e,t){const{children:r,depth:n}=function(e){if("individualShift"===e.positionType){const t=e.children,r=[t[0]],n=-t[0].shift-t[0].elem.depth;let o=n;for(let e=1;e0)return qe(s,h,o,t,i.concat(c));if(l){let e,n;if("boldsymbol"===l){const t=function(e,t,r,n,o){return"textord"!==o&&Ne(e,"Math-BoldItalic",t).metrics?{fontName:"Math-BoldItalic",fontClass:"boldsymbol"}:{fontName:"Main-Bold",fontClass:"mathbf"}}(s,o,0,0,r);e=t.fontName,n=[t.fontClass]}else a?(e=De[l].fontName,n=[l]):(e=Le(l,t.fontWeight,t.fontShape),n=[l,t.fontWeight,t.fontShape]);if(Ne(s,e,o).metrics)return qe(s,e,o,t,i.concat(n));if(ke.hasOwnProperty(s)&&"Typewriter"===e.slice(0,10)){const r=[];for(let a=0;a{const r=He(["mspace"],[],t),n=P(e,t);return r.style.marginRight=F(n),r},staticSvg:function(e,t){const[r,n,o]=Ve[e],s=new Q(r),i=new J([s],{width:F(n),height:F(o),style:"width:"+F(n),viewBox:"0 0 "+1e3*n+" "+1e3*o,preserveAspectRatio:"xMinYMin"}),a=Oe(["overlay"],[i],t);return a.height=o,a.style.height=F(o),a.style.width=F(n),a},svgData:Ve,tryCombineChars:e=>{for(let t=0;t{const r=t.classes[0],n=e.classes[0];"mbin"===r&&l.contains(tt,n)?t.classes[0]="mord":"mbin"===n&&l.contains(et,r)&&(e.classes[0]="mord")}),{node:i},a,h),st(o,((e,t)=>{const r=lt(t),n=lt(e),o=r&&n?e.hasClass("mtight")?Xe[r][n]:Ye[r][n]:null;if(o)return Pe.makeGlue(o,s)}),{node:i},a,h),o},st=function(e,t,r,n,o){n&&e.push(n);let s=0;for(;sr=>{e.splice(t+1,0,r),s++})(s)}n&&e.pop()},it=function(e){return e instanceof A||e instanceof j||e instanceof _&&e.hasClass("enclosing")?e:null},at=function(e,t){const r=it(e);if(r){const e=r.children;if(e.length){if("right"===t)return at(e[e.length-1],"right");if("left"===t)return at(e[0],"left")}}return e},lt=function(e,t){return e?(t&&(e=at(e,t)),nt[e.classes[0]]||null):null},ht=function(e,t){const r=["nulldelimiter"].concat(e.baseSizingClasses());return Qe(t.concat(r))},ct=function(e,t,r){if(!e)return Qe();if(_e[e.type]){let n=_e[e.type](e,t);if(r&&t.size!==r.size){n=Qe(t.sizingClasses(r),[n],t);const e=t.sizeMultiplier/r.sizeMultiplier;n.height*=e,n.depth*=e}return n}throw new n("Got group of unknown type: '"+e.type+"'")};function mt(e,t){const r=Qe(["base"],e,t),n=Qe(["strut"]);return n.style.height=F(r.height+r.depth),r.depth&&(n.style.verticalAlign=F(-r.depth)),r.children.unshift(n),r}function pt(e,t){let r=null;1===e.length&&"tag"===e[0].type&&(r=e[0].tag,e=e[0].body);const n=ot(e,t,"root");let o;2===n.length&&n[1].hasClass("tag")&&(o=n.pop());const s=[];let i,a=[];for(let e=0;e0&&(s.push(mt(a,t)),a=[]),s.push(n[e]));a.length>0&&s.push(mt(a,t)),r?(i=mt(ot(r,t,!0)),i.classes=["tag"],s.push(i)):o&&s.push(o);const l=Qe(["katex-html"],s);if(l.setAttribute("aria-hidden","true"),i){const e=i.children[0];e.style.height=F(l.height+l.depth),l.depth&&(e.style.verticalAlign=F(-l.depth))}return l}function ut(e){return new A(e)}class dt{constructor(e,t,r){this.type=void 0,this.attributes=void 0,this.children=void 0,this.classes=void 0,this.type=e,this.attributes={},this.children=t||[],this.classes=r||[]}setAttribute(e,t){this.attributes[e]=t}getAttribute(e){return this.attributes[e]}toNode(){const e=document.createElementNS("http://www.w3.org/1998/Math/MathML",this.type);for(const t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);this.classes.length>0&&(e.className=G(this.classes));for(let t=0;t0&&(e+=' class ="'+l.escape(G(this.classes))+'"'),e+=">";for(let t=0;t",e}toText(){return this.children.map((e=>e.toText())).join("")}}class gt{constructor(e){this.text=void 0,this.text=e}toNode(){return document.createTextNode(this.text)}toMarkup(){return l.escape(this.toText())}toText(){return this.text}}var ft={MathNode:dt,TextNode:gt,SpaceNode:class{constructor(e){this.width=void 0,this.character=void 0,this.width=e,this.character=e>=.05555&&e<=.05556?"\u200a":e>=.1666&&e<=.1667?"\u2009":e>=.2222&&e<=.2223?"\u2005":e>=.2777&&e<=.2778?"\u2005\u200a":e>=-.05556&&e<=-.05555?"\u200a\u2063":e>=-.1667&&e<=-.1666?"\u2009\u2063":e>=-.2223&&e<=-.2222?"\u205f\u2063":e>=-.2778&&e<=-.2777?"\u2005\u2063":null}toNode(){if(this.character)return document.createTextNode(this.character);{const e=document.createElementNS("http://www.w3.org/1998/Math/MathML","mspace");return e.setAttribute("width",F(this.width)),e}}toMarkup(){return this.character?""+this.character+"":''}toText(){return this.character?this.character:" "}},newDocumentFragment:ut};const bt=function(e,t,r){return!se[t][e]||!se[t][e].replace||55349===e.charCodeAt(0)||ke.hasOwnProperty(e)&&r&&(r.fontFamily&&"tt"===r.fontFamily.slice(4,6)||r.font&&"tt"===r.font.slice(4,6))||(e=se[t][e].replace),new ft.TextNode(e)},yt=function(e){return 1===e.length?e[0]:new ft.MathNode("mrow",e)},xt=function(e,t){if("texttt"===t.fontFamily)return"monospace";if("textsf"===t.fontFamily)return"textit"===t.fontShape&&"textbf"===t.fontWeight?"sans-serif-bold-italic":"textit"===t.fontShape?"sans-serif-italic":"textbf"===t.fontWeight?"bold-sans-serif":"sans-serif";if("textit"===t.fontShape&&"textbf"===t.fontWeight)return"bold-italic";if("textit"===t.fontShape)return"italic";if("textbf"===t.fontWeight)return"bold";const r=t.font;if(!r||"mathnormal"===r)return null;const n=e.mode;if("mathit"===r)return"italic";if("boldsymbol"===r)return"textord"===e.type?"bold":"bold-italic";if("mathbf"===r)return"bold";if("mathbb"===r)return"double-struck";if("mathsfit"===r)return"sans-serif-italic";if("mathfrak"===r)return"fraktur";if("mathscr"===r||"mathcal"===r)return"script";if("mathsf"===r)return"sans-serif";if("mathtt"===r)return"monospace";let o=e.text;if(l.contains(["\\imath","\\jmath"],o))return null;se[n][o]&&se[n][o].replace&&(o=se[n][o].replace);return N(o,Pe.fontMap[r].fontName,n)?Pe.fontMap[r].variant:null};function wt(e){if(!e)return!1;if("mi"===e.type&&1===e.children.length){const t=e.children[0];return t instanceof gt&&"."===t.text}if("mo"===e.type&&1===e.children.length&&"true"===e.getAttribute("separator")&&"0em"===e.getAttribute("lspace")&&"0em"===e.getAttribute("rspace")){const t=e.children[0];return t instanceof gt&&","===t.text}return!1}const vt=function(e,t,r){if(1===e.length){const n=St(e[0],t);return r&&n instanceof dt&&"mo"===n.type&&(n.setAttribute("lspace","0em"),n.setAttribute("rspace","0em")),[n]}const n=[];let o;for(let r=0;r=1&&("mn"===o.type||wt(o))){const e=s.children[0];e instanceof dt&&"mn"===e.type&&(e.children=[...o.children,...e.children],n.pop())}else if("mi"===o.type&&1===o.children.length){const e=o.children[0];if(e instanceof gt&&"\u0338"===e.text&&("mo"===s.type||"mi"===s.type||"mn"===s.type)){const e=s.children[0];e instanceof gt&&e.text.length>0&&(e.text=e.text.slice(0,1)+"\u0338"+e.text.slice(1),n.pop())}}}n.push(s),o=s}return n},kt=function(e,t,r){return yt(vt(e,t,r))},St=function(e,t){if(!e)return new ft.MathNode("mrow");if(je[e.type]){return je[e.type](e,t)}throw new n("Got group of unknown type: '"+e.type+"'")};function Mt(e,t,r,n,o){const s=vt(e,r);let i;i=1===s.length&&s[0]instanceof dt&&l.contains(["mrow","mtable"],s[0].type)?s[0]:new ft.MathNode("mrow",s);const a=new ft.MathNode("annotation",[new ft.TextNode(t)]);a.setAttribute("encoding","application/x-tex");const h=new ft.MathNode("semantics",[i,a]),c=new ft.MathNode("math",[h]);c.setAttribute("xmlns","http://www.w3.org/1998/Math/MathML"),n&&c.setAttribute("display","block");const m=o?"katex":"katex-mathml";return Pe.makeSpan([m],[c])}const zt=function(e){return new E({style:e.displayMode?w.DISPLAY:w.TEXT,maxSize:e.maxSize,minRuleThickness:e.minRuleThickness})},At=function(e,t){if(t.displayMode){const r=["katex-display"];t.leqno&&r.push("leqno"),t.fleqn&&r.push("fleqn"),e=Pe.makeSpan(r,[e])}return e},Tt=function(e,t,r){const n=zt(r);let o;if("mathml"===r.output)return Mt(e,t,n,r.displayMode,!0);if("html"===r.output){const t=pt(e,n);o=Pe.makeSpan(["katex"],[t])}else{const s=Mt(e,t,n,r.displayMode,!1),i=pt(e,n);o=Pe.makeSpan(["katex"],[s,i])}return At(o,r)};const Bt={widehat:"^",widecheck:"\u02c7",widetilde:"~",utilde:"~",overleftarrow:"\u2190",underleftarrow:"\u2190",xleftarrow:"\u2190",overrightarrow:"\u2192",underrightarrow:"\u2192",xrightarrow:"\u2192",underbrace:"\u23df",overbrace:"\u23de",overgroup:"\u23e0",undergroup:"\u23e1",overleftrightarrow:"\u2194",underleftrightarrow:"\u2194",xleftrightarrow:"\u2194",Overrightarrow:"\u21d2",xRightarrow:"\u21d2",overleftharpoon:"\u21bc",xleftharpoonup:"\u21bc",overrightharpoon:"\u21c0",xrightharpoonup:"\u21c0",xLeftarrow:"\u21d0",xLeftrightarrow:"\u21d4",xhookleftarrow:"\u21a9",xhookrightarrow:"\u21aa",xmapsto:"\u21a6",xrightharpoondown:"\u21c1",xleftharpoondown:"\u21bd",xrightleftharpoons:"\u21cc",xleftrightharpoons:"\u21cb",xtwoheadleftarrow:"\u219e",xtwoheadrightarrow:"\u21a0",xlongequal:"=",xtofrom:"\u21c4",xrightleftarrows:"\u21c4",xrightequilibrium:"\u21cc",xleftequilibrium:"\u21cb","\\cdrightarrow":"\u2192","\\cdleftarrow":"\u2190","\\cdlongequal":"="},Ct={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],"\\cdrightarrow":[["rightarrow"],3,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],"\\cdleftarrow":[["leftarrow"],3,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],"\\cdlongequal":[["longequal"],3,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xrightleftarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xrightequilibrium:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xleftequilibrium:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]};var Nt=function(e,t,r,n,o){let s;const i=e.height+e.depth+r+n;if(/fbox|color|angl/.test(t)){if(s=Pe.makeSpan(["stretchy",t],[],o),"fbox"===t){const e=o.color&&o.getColor();e&&(s.style.borderColor=e)}}else{const e=[];/^[bx]cancel$/.test(t)&&e.push(new ee({x1:"0",y1:"0",x2:"100%",y2:"100%","stroke-width":"0.046em"})),/^x?cancel$/.test(t)&&e.push(new ee({x1:"0",y1:"100%",x2:"100%",y2:"0","stroke-width":"0.046em"}));const r=new J(e,{width:"100%",height:F(i)});s=Pe.makeSvgSpan([],[r],o)}return s.height=i,s.style.height=F(i),s},qt=function(e){const t=new ft.MathNode("mo",[new ft.TextNode(Bt[e.replace(/^\\/,"")])]);return t.setAttribute("stretchy","true"),t},It=function(e,t){const{span:r,minWidth:n,height:o}=function(){let r=4e5;const n=e.label.slice(1);if(l.contains(["widehat","widecheck","widetilde","utilde"],n)){const s="ordgroup"===(o=e.base).type?o.body.length:1;let i,a,l;if(s>5)"widehat"===n||"widecheck"===n?(i=420,r=2364,l=.42,a=n+"4"):(i=312,r=2340,l=.34,a="tilde4");else{const e=[1,1,2,2,3,3][s];"widehat"===n||"widecheck"===n?(r=[0,1062,2364,2364,2364][e],i=[0,239,300,360,420][e],l=[0,.24,.3,.3,.36,.42][e],a=n+e):(r=[0,600,1033,2339,2340][e],i=[0,260,286,306,312][e],l=[0,.26,.286,.3,.306,.34][e],a="tilde"+e)}const h=new Q(a),c=new J([h],{width:"100%",height:F(l),viewBox:"0 0 "+r+" "+i,preserveAspectRatio:"none"});return{span:Pe.makeSvgSpan([],[c],t),minWidth:0,height:l}}{const e=[],o=Ct[n],[s,i,a]=o,l=a/1e3,h=s.length;let c,m;if(1===h){c=["hide-tail"],m=[o[3]]}else if(2===h)c=["halfarrow-left","halfarrow-right"],m=["xMinYMin","xMaxYMin"];else{if(3!==h)throw new Error("Correct katexImagesData or update code here to support\n "+h+" children.");c=["brace-left","brace-center","brace-right"],m=["xMinYMin","xMidYMin","xMaxYMin"]}for(let n=0;n0&&(r.style.minWidth=F(n)),r};function Rt(e,t){if(!e||e.type!==t)throw new Error("Expected node of type "+t+", but got "+(e?"node of type "+e.type:String(e)));return e}function Ht(e){const t=Ot(e);if(!t)throw new Error("Expected node of symbol group type, but got "+(e?"node of type "+e.type:String(e)));return t}function Ot(e){return e&&("atom"===e.type||ne.hasOwnProperty(e.type))?e:null}const Et=(e,t)=>{let r,n,o;e&&"supsub"===e.type?(n=Rt(e.base,"accent"),r=n.base,e.base=r,o=function(e){if(e instanceof _)return e;throw new Error("Expected span but got "+String(e)+".")}(ct(e,t)),e.base=n):(n=Rt(e,"accent"),r=n.base);const s=ct(r,t.havingCrampedStyle());let i=0;if(n.isShifty&&l.isCharacterBox(r)){const e=l.getBaseElem(r);i=te(ct(e,t.havingCrampedStyle())).skew}const a="\\c"===n.label;let h,c=a?s.height+s.depth:Math.min(s.height,t.fontMetrics().xHeight);if(n.isStretchy)h=It(n,t),h=Pe.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"elem",elem:h,wrapperClasses:["svg-align"],wrapperStyle:i>0?{width:"calc(100% - "+F(2*i)+")",marginLeft:F(2*i)}:void 0}]},t);else{let e,r;"\\vec"===n.label?(e=Pe.staticSvg("vec",t),r=Pe.svgData.vec[1]):(e=Pe.makeOrd({mode:n.mode,text:n.label},t,"textord"),e=te(e),e.italic=0,r=e.width,a&&(c+=e.depth)),h=Pe.makeSpan(["accent-body"],[e]);const o="\\textcircled"===n.label;o&&(h.classes.push("accent-full"),c=s.height);let l=i;o||(l-=r/2),h.style.left=F(l),"\\textcircled"===n.label&&(h.style.top=".2em"),h=Pe.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"kern",size:-c},{type:"elem",elem:h}]},t)}const m=Pe.makeSpan(["mord","accent"],[h],t);return o?(o.children[0]=m,o.height=Math.max(m.height,o.height),o.classes[0]="mord",o):m},Lt=(e,t)=>{const r=e.isStretchy?qt(e.label):new ft.MathNode("mo",[bt(e.label,e.mode)]),n=new ft.MathNode("mover",[St(e.base,t),r]);return n.setAttribute("accent","true"),n},Dt=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map((e=>"\\"+e)).join("|"));$e({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],props:{numArgs:1},handler:(e,t)=>{const r=Ke(t[0]),n=!Dt.test(e.funcName),o=!n||"\\widehat"===e.funcName||"\\widetilde"===e.funcName||"\\widecheck"===e.funcName;return{type:"accent",mode:e.parser.mode,label:e.funcName,isStretchy:n,isShifty:o,base:r}},htmlBuilder:Et,mathmlBuilder:Lt}),$e({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\c","\\r","\\H","\\v","\\textcircled"],props:{numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["primitive"]},handler:(e,t)=>{const r=t[0];let n=e.parser.mode;return"math"===n&&(e.parser.settings.reportNonstrict("mathVsTextAccents","LaTeX's accent "+e.funcName+" works only in text mode"),n="text"),{type:"accent",mode:n,label:e.funcName,isStretchy:!1,isShifty:!0,base:r}},htmlBuilder:Et,mathmlBuilder:Lt}),$e({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],props:{numArgs:1},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0];return{type:"accentUnder",mode:r.mode,label:n,base:o}},htmlBuilder:(e,t)=>{const r=ct(e.base,t),n=It(e,t),o="\\utilde"===e.label?.12:0,s=Pe.makeVList({positionType:"top",positionData:r.height,children:[{type:"elem",elem:n,wrapperClasses:["svg-align"]},{type:"kern",size:o},{type:"elem",elem:r}]},t);return Pe.makeSpan(["mord","accentunder"],[s],t)},mathmlBuilder:(e,t)=>{const r=qt(e.label),n=new ft.MathNode("munder",[St(e.base,t),r]);return n.setAttribute("accentunder","true"),n}});const Vt=e=>{const t=new ft.MathNode("mpadded",e?[e]:[]);return t.setAttribute("width","+0.6em"),t.setAttribute("lspace","0.3em"),t};$e({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium","\\\\cdrightarrow","\\\\cdleftarrow","\\\\cdlongequal"],props:{numArgs:1,numOptionalArgs:1},handler(e,t,r){let{parser:n,funcName:o}=e;return{type:"xArrow",mode:n.mode,label:o,body:t[0],below:r[0]}},htmlBuilder(e,t){const r=t.style;let n=t.havingStyle(r.sup());const o=Pe.wrapFragment(ct(e.body,n,t),t),s="\\x"===e.label.slice(0,2)?"x":"cd";let i;o.classes.push(s+"-arrow-pad"),e.below&&(n=t.havingStyle(r.sub()),i=Pe.wrapFragment(ct(e.below,n,t),t),i.classes.push(s+"-arrow-pad"));const a=It(e,t),l=-t.fontMetrics().axisHeight+.5*a.height;let h,c=-t.fontMetrics().axisHeight-.5*a.height-.111;if((o.depth>.25||"\\xleftequilibrium"===e.label)&&(c-=o.depth),i){const e=-t.fontMetrics().axisHeight+i.height+.5*a.height+.111;h=Pe.makeVList({positionType:"individualShift",children:[{type:"elem",elem:o,shift:c},{type:"elem",elem:a,shift:l},{type:"elem",elem:i,shift:e}]},t)}else h=Pe.makeVList({positionType:"individualShift",children:[{type:"elem",elem:o,shift:c},{type:"elem",elem:a,shift:l}]},t);return h.children[0].children[0].children[1].classes.push("svg-align"),Pe.makeSpan(["mrel","x-arrow"],[h],t)},mathmlBuilder(e,t){const r=qt(e.label);let n;if(r.setAttribute("minsize","x"===e.label.charAt(0)?"1.75em":"3.0em"),e.body){const o=Vt(St(e.body,t));if(e.below){const s=Vt(St(e.below,t));n=new ft.MathNode("munderover",[r,s,o])}else n=new ft.MathNode("mover",[r,o])}else if(e.below){const o=Vt(St(e.below,t));n=new ft.MathNode("munder",[r,o])}else n=Vt(),n=new ft.MathNode("mover",[r,n]);return n}});const Pt=Pe.makeSpan;function Ft(e,t){const r=ot(e.body,t,!0);return Pt([e.mclass],r,t)}function Gt(e,t){let r;const n=vt(e.body,t);return"minner"===e.mclass?r=new ft.MathNode("mpadded",n):"mord"===e.mclass?e.isCharacterBox?(r=n[0],r.type="mi"):r=new ft.MathNode("mi",n):(e.isCharacterBox?(r=n[0],r.type="mo"):r=new ft.MathNode("mo",n),"mbin"===e.mclass?(r.attributes.lspace="0.22em",r.attributes.rspace="0.22em"):"mpunct"===e.mclass?(r.attributes.lspace="0em",r.attributes.rspace="0.17em"):"mopen"===e.mclass||"mclose"===e.mclass?(r.attributes.lspace="0em",r.attributes.rspace="0em"):"minner"===e.mclass&&(r.attributes.lspace="0.0556em",r.attributes.width="+0.1111em")),r}$e({type:"mclass",names:["\\mathord","\\mathbin","\\mathrel","\\mathopen","\\mathclose","\\mathpunct","\\mathinner"],props:{numArgs:1,primitive:!0},handler(e,t){let{parser:r,funcName:n}=e;const o=t[0];return{type:"mclass",mode:r.mode,mclass:"m"+n.slice(5),body:Je(o),isCharacterBox:l.isCharacterBox(o)}},htmlBuilder:Ft,mathmlBuilder:Gt});const Ut=e=>{const t="ordgroup"===e.type&&e.body.length?e.body[0]:e;return"atom"!==t.type||"bin"!==t.family&&"rel"!==t.family?"mord":"m"+t.family};$e({type:"mclass",names:["\\@binrel"],props:{numArgs:2},handler(e,t){let{parser:r}=e;return{type:"mclass",mode:r.mode,mclass:Ut(t[0]),body:Je(t[1]),isCharacterBox:l.isCharacterBox(t[1])}}}),$e({type:"mclass",names:["\\stackrel","\\overset","\\underset"],props:{numArgs:2},handler(e,t){let{parser:r,funcName:n}=e;const o=t[1],s=t[0];let i;i="\\stackrel"!==n?Ut(o):"mrel";const a={type:"op",mode:o.mode,limits:!0,alwaysHandleSupSub:!0,parentIsSupSub:!1,symbol:!1,suppressBaseShift:"\\stackrel"!==n,body:Je(o)},h={type:"supsub",mode:s.mode,base:a,sup:"\\underset"===n?null:s,sub:"\\underset"===n?s:null};return{type:"mclass",mode:r.mode,mclass:i,body:[h],isCharacterBox:l.isCharacterBox(h)}},htmlBuilder:Ft,mathmlBuilder:Gt}),$e({type:"pmb",names:["\\pmb"],props:{numArgs:1,allowedInText:!0},handler(e,t){let{parser:r}=e;return{type:"pmb",mode:r.mode,mclass:Ut(t[0]),body:Je(t[0])}},htmlBuilder(e,t){const r=ot(e.body,t,!0),n=Pe.makeSpan([e.mclass],r,t);return n.style.textShadow="0.02em 0.01em 0.04px",n},mathmlBuilder(e,t){const r=vt(e.body,t),n=new ft.MathNode("mstyle",r);return n.setAttribute("style","text-shadow: 0.02em 0.01em 0.04px"),n}});const Yt={">":"\\\\cdrightarrow","<":"\\\\cdleftarrow","=":"\\\\cdlongequal",A:"\\uparrow",V:"\\downarrow","|":"\\Vert",".":"no arrow"},Xt=e=>"textord"===e.type&&"@"===e.text;function Wt(e,t,r){const n=Yt[e];switch(n){case"\\\\cdrightarrow":case"\\\\cdleftarrow":return r.callFunction(n,[t[0]],[t[1]]);case"\\uparrow":case"\\downarrow":{const e={type:"atom",text:n,mode:"math",family:"rel"},o={type:"ordgroup",mode:"math",body:[r.callFunction("\\\\cdleft",[t[0]],[]),r.callFunction("\\Big",[e],[]),r.callFunction("\\\\cdright",[t[1]],[])]};return r.callFunction("\\\\cdparent",[o],[])}case"\\\\cdlongequal":return r.callFunction("\\\\cdlongequal",[],[]);case"\\Vert":{const e={type:"textord",text:"\\Vert",mode:"math"};return r.callFunction("\\Big",[e],[])}default:return{type:"textord",text:" ",mode:"math"}}}$e({type:"cdlabel",names:["\\\\cdleft","\\\\cdright"],props:{numArgs:1},handler(e,t){let{parser:r,funcName:n}=e;return{type:"cdlabel",mode:r.mode,side:n.slice(4),label:t[0]}},htmlBuilder(e,t){const r=t.havingStyle(t.style.sup()),n=Pe.wrapFragment(ct(e.label,r,t),t);return n.classes.push("cd-label-"+e.side),n.style.bottom=F(.8-n.depth),n.height=0,n.depth=0,n},mathmlBuilder(e,t){let r=new ft.MathNode("mrow",[St(e.label,t)]);return r=new ft.MathNode("mpadded",[r]),r.setAttribute("width","0"),"left"===e.side&&r.setAttribute("lspace","-1width"),r.setAttribute("voffset","0.7em"),r=new ft.MathNode("mstyle",[r]),r.setAttribute("displaystyle","false"),r.setAttribute("scriptlevel","1"),r}}),$e({type:"cdlabelparent",names:["\\\\cdparent"],props:{numArgs:1},handler(e,t){let{parser:r}=e;return{type:"cdlabelparent",mode:r.mode,fragment:t[0]}},htmlBuilder(e,t){const r=Pe.wrapFragment(ct(e.fragment,t),t);return r.classes.push("cd-vert-arrow"),r},mathmlBuilder(e,t){return new ft.MathNode("mrow",[St(e.fragment,t)])}}),$e({type:"textord",names:["\\@char"],props:{numArgs:1,allowedInText:!0},handler(e,t){let{parser:r}=e;const o=Rt(t[0],"ordgroup").body;let s="";for(let e=0;e=1114111)throw new n("\\@char with invalid code point "+s);return a<=65535?i=String.fromCharCode(a):(a-=65536,i=String.fromCharCode(55296+(a>>10),56320+(1023&a))),{type:"textord",mode:r.mode,text:i}}});const _t=(e,t)=>{const r=ot(e.body,t.withColor(e.color),!1);return Pe.makeFragment(r)},jt=(e,t)=>{const r=vt(e.body,t.withColor(e.color)),n=new ft.MathNode("mstyle",r);return n.setAttribute("mathcolor",e.color),n};$e({type:"color",names:["\\textcolor"],props:{numArgs:2,allowedInText:!0,argTypes:["color","original"]},handler(e,t){let{parser:r}=e;const n=Rt(t[0],"color-token").color,o=t[1];return{type:"color",mode:r.mode,color:n,body:Je(o)}},htmlBuilder:_t,mathmlBuilder:jt}),$e({type:"color",names:["\\color"],props:{numArgs:1,allowedInText:!0,argTypes:["color"]},handler(e,t){let{parser:r,breakOnTokenText:n}=e;const o=Rt(t[0],"color-token").color;r.gullet.macros.set("\\current@color",o);const s=r.parseExpression(!0,n);return{type:"color",mode:r.mode,color:o,body:s}},htmlBuilder:_t,mathmlBuilder:jt}),$e({type:"cr",names:["\\\\"],props:{numArgs:0,numOptionalArgs:0,allowedInText:!0},handler(e,t,r){let{parser:n}=e;const o="["===n.gullet.future().text?n.parseSizeGroup(!0):null,s=!n.settings.displayMode||!n.settings.useStrictBehavior("newLineInDisplayMode","In LaTeX, \\\\ or \\newline does nothing in display mode");return{type:"cr",mode:n.mode,newLine:s,size:o&&Rt(o,"size").value}},htmlBuilder(e,t){const r=Pe.makeSpan(["mspace"],[],t);return e.newLine&&(r.classes.push("newline"),e.size&&(r.style.marginTop=F(P(e.size,t)))),r},mathmlBuilder(e,t){const r=new ft.MathNode("mspace");return e.newLine&&(r.setAttribute("linebreak","newline"),e.size&&r.setAttribute("height",F(P(e.size,t)))),r}});const $t={"\\global":"\\global","\\long":"\\\\globallong","\\\\globallong":"\\\\globallong","\\def":"\\gdef","\\gdef":"\\gdef","\\edef":"\\xdef","\\xdef":"\\xdef","\\let":"\\\\globallet","\\futurelet":"\\\\globalfuture"},Zt=e=>{const t=e.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(t))throw new n("Expected a control sequence",e);return t},Kt=(e,t,r,n)=>{let o=e.gullet.macros.get(r.text);null==o&&(r.noexpand=!0,o={tokens:[r],numArgs:0,unexpandable:!e.gullet.isExpandable(r.text)}),e.gullet.macros.set(t,o,n)};$e({type:"internal",names:["\\global","\\long","\\\\globallong"],props:{numArgs:0,allowedInText:!0},handler(e){let{parser:t,funcName:r}=e;t.consumeSpaces();const o=t.fetch();if($t[o.text])return"\\global"!==r&&"\\\\globallong"!==r||(o.text=$t[o.text]),Rt(t.parseFunction(),"internal");throw new n("Invalid token after macro prefix",o)}}),$e({type:"internal",names:["\\def","\\gdef","\\edef","\\xdef"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){let{parser:t,funcName:r}=e,o=t.gullet.popToken();const s=o.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(s))throw new n("Expected a control sequence",o);let i,a=0;const l=[[]];for(;"{"!==t.gullet.future().text;)if(o=t.gullet.popToken(),"#"===o.text){if("{"===t.gullet.future().text){i=t.gullet.future(),l[a].push("{");break}if(o=t.gullet.popToken(),!/^[1-9]$/.test(o.text))throw new n('Invalid argument number "'+o.text+'"');if(parseInt(o.text)!==a+1)throw new n('Argument number "'+o.text+'" out of order');a++,l.push([])}else{if("EOF"===o.text)throw new n("Expected a macro definition");l[a].push(o.text)}let{tokens:h}=t.gullet.consumeArg();return i&&h.unshift(i),"\\edef"!==r&&"\\xdef"!==r||(h=t.gullet.expandTokens(h),h.reverse()),t.gullet.macros.set(s,{tokens:h,numArgs:a,delimiters:l},r===$t[r]),{type:"internal",mode:t.mode}}}),$e({type:"internal",names:["\\let","\\\\globallet"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){let{parser:t,funcName:r}=e;const n=Zt(t.gullet.popToken());t.gullet.consumeSpaces();const o=(e=>{let t=e.gullet.popToken();return"="===t.text&&(t=e.gullet.popToken()," "===t.text&&(t=e.gullet.popToken())),t})(t);return Kt(t,n,o,"\\\\globallet"===r),{type:"internal",mode:t.mode}}}),$e({type:"internal",names:["\\futurelet","\\\\globalfuture"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){let{parser:t,funcName:r}=e;const n=Zt(t.gullet.popToken()),o=t.gullet.popToken(),s=t.gullet.popToken();return Kt(t,n,s,"\\\\globalfuture"===r),t.gullet.pushToken(s),t.gullet.pushToken(o),{type:"internal",mode:t.mode}}});const Jt=function(e,t,r){const n=N(se.math[e]&&se.math[e].replace||e,t,r);if(!n)throw new Error("Unsupported symbol "+e+" and font size "+t+".");return n},Qt=function(e,t,r,n){const o=r.havingBaseStyle(t),s=Pe.makeSpan(n.concat(o.sizingClasses(r)),[e],r),i=o.sizeMultiplier/r.sizeMultiplier;return s.height*=i,s.depth*=i,s.maxFontSize=o.sizeMultiplier,s},er=function(e,t,r){const n=t.havingBaseStyle(r),o=(1-t.sizeMultiplier/n.sizeMultiplier)*t.fontMetrics().axisHeight;e.classes.push("delimcenter"),e.style.top=F(o),e.height-=o,e.depth+=o},tr=function(e,t,r,n,o,s){const i=function(e,t,r,n){return Pe.makeSymbol(e,"Size"+t+"-Regular",r,n)}(e,t,o,n),a=Qt(Pe.makeSpan(["delimsizing","size"+t],[i],n),w.TEXT,n,s);return r&&er(a,n,w.TEXT),a},rr=function(e,t,r){let n;n="Size1-Regular"===t?"delim-size1":"delim-size4";return{type:"elem",elem:Pe.makeSpan(["delimsizinginner",n],[Pe.makeSpan([],[Pe.makeSymbol(e,t,r)])])}},nr=function(e,t,r){const n=T["Size4-Regular"][e.charCodeAt(0)]?T["Size4-Regular"][e.charCodeAt(0)][4]:T["Size1-Regular"][e.charCodeAt(0)][4],o=new Q("inner",function(e,t){switch(e){case"\u239c":return"M291 0 H417 V"+t+" H291z M291 0 H417 V"+t+" H291z";case"\u2223":return"M145 0 H188 V"+t+" H145z M145 0 H188 V"+t+" H145z";case"\u2225":return"M145 0 H188 V"+t+" H145z M145 0 H188 V"+t+" H145zM367 0 H410 V"+t+" H367z M367 0 H410 V"+t+" H367z";case"\u239f":return"M457 0 H583 V"+t+" H457z M457 0 H583 V"+t+" H457z";case"\u23a2":return"M319 0 H403 V"+t+" H319z M319 0 H403 V"+t+" H319z";case"\u23a5":return"M263 0 H347 V"+t+" H263z M263 0 H347 V"+t+" H263z";case"\u23aa":return"M384 0 H504 V"+t+" H384z M384 0 H504 V"+t+" H384z";case"\u23d0":return"M312 0 H355 V"+t+" H312z M312 0 H355 V"+t+" H312z";case"\u2016":return"M257 0 H300 V"+t+" H257z M257 0 H300 V"+t+" H257zM478 0 H521 V"+t+" H478z M478 0 H521 V"+t+" H478z";default:return""}}(e,Math.round(1e3*t))),s=new J([o],{width:F(n),height:F(t),style:"width:"+F(n),viewBox:"0 0 "+1e3*n+" "+Math.round(1e3*t),preserveAspectRatio:"xMinYMin"}),i=Pe.makeSvgSpan([],[s],r);return i.height=t,i.style.height=F(t),i.style.width=F(n),{type:"elem",elem:i}},or={type:"kern",size:-.008},sr=["|","\\lvert","\\rvert","\\vert"],ir=["\\|","\\lVert","\\rVert","\\Vert"],ar=function(e,t,r,n,o,s){let i,a,h,c,m="",p=0;i=h=c=e,a=null;let u="Size1-Regular";"\\uparrow"===e?h=c="\u23d0":"\\Uparrow"===e?h=c="\u2016":"\\downarrow"===e?i=h="\u23d0":"\\Downarrow"===e?i=h="\u2016":"\\updownarrow"===e?(i="\\uparrow",h="\u23d0",c="\\downarrow"):"\\Updownarrow"===e?(i="\\Uparrow",h="\u2016",c="\\Downarrow"):l.contains(sr,e)?(h="\u2223",m="vert",p=333):l.contains(ir,e)?(h="\u2225",m="doublevert",p=556):"["===e||"\\lbrack"===e?(i="\u23a1",h="\u23a2",c="\u23a3",u="Size4-Regular",m="lbrack",p=667):"]"===e||"\\rbrack"===e?(i="\u23a4",h="\u23a5",c="\u23a6",u="Size4-Regular",m="rbrack",p=667):"\\lfloor"===e||"\u230a"===e?(h=i="\u23a2",c="\u23a3",u="Size4-Regular",m="lfloor",p=667):"\\lceil"===e||"\u2308"===e?(i="\u23a1",h=c="\u23a2",u="Size4-Regular",m="lceil",p=667):"\\rfloor"===e||"\u230b"===e?(h=i="\u23a5",c="\u23a6",u="Size4-Regular",m="rfloor",p=667):"\\rceil"===e||"\u2309"===e?(i="\u23a4",h=c="\u23a5",u="Size4-Regular",m="rceil",p=667):"("===e||"\\lparen"===e?(i="\u239b",h="\u239c",c="\u239d",u="Size4-Regular",m="lparen",p=875):")"===e||"\\rparen"===e?(i="\u239e",h="\u239f",c="\u23a0",u="Size4-Regular",m="rparen",p=875):"\\{"===e||"\\lbrace"===e?(i="\u23a7",a="\u23a8",c="\u23a9",h="\u23aa",u="Size4-Regular"):"\\}"===e||"\\rbrace"===e?(i="\u23ab",a="\u23ac",c="\u23ad",h="\u23aa",u="Size4-Regular"):"\\lgroup"===e||"\u27ee"===e?(i="\u23a7",c="\u23a9",h="\u23aa",u="Size4-Regular"):"\\rgroup"===e||"\u27ef"===e?(i="\u23ab",c="\u23ad",h="\u23aa",u="Size4-Regular"):"\\lmoustache"===e||"\u23b0"===e?(i="\u23a7",c="\u23ad",h="\u23aa",u="Size4-Regular"):"\\rmoustache"!==e&&"\u23b1"!==e||(i="\u23ab",c="\u23a9",h="\u23aa",u="Size4-Regular");const d=Jt(i,u,o),g=d.height+d.depth,f=Jt(h,u,o),b=f.height+f.depth,y=Jt(c,u,o),x=y.height+y.depth;let v=0,k=1;if(null!==a){const e=Jt(a,u,o);v=e.height+e.depth,k=2}const S=g+x+v,M=S+Math.max(0,Math.ceil((t-S)/(k*b)))*k*b;let z=n.fontMetrics().axisHeight;r&&(z*=n.sizeMultiplier);const A=M/2-z,T=[];if(m.length>0){const e=M-g-x,t=Math.round(1e3*M),r=function(e,t){switch(e){case"lbrack":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+" v1759 h347 v-84\nH403z M403 1759 V0 H319 V1759 v"+t+" v1759 h84z";case"rbrack":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+" v1759 H0 v84 H347z\nM347 1759 V0 H263 V1759 v"+t+" v1759 h84z";case"vert":return"M145 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v"+t+" v585 h43z";case"doublevert":return"M145 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v"+t+" v585 h43z\nM367 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M410 15 H367 v585 v"+t+" v585 h43z";case"lfloor":return"M319 602 V0 H403 V602 v"+t+" v1715 h263 v84 H319z\nMM319 602 V0 H403 V602 v"+t+" v1715 H319z";case"rfloor":return"M319 602 V0 H403 V602 v"+t+" v1799 H0 v-84 H319z\nMM319 602 V0 H403 V602 v"+t+" v1715 H319z";case"lceil":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+" v602 h84z\nM403 1759 V0 H319 V1759 v"+t+" v602 h84z";case"rceil":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+" v602 h84z\nM347 1759 V0 h-84 V1759 v"+t+" v602 h84z";case"lparen":return"M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1\nc-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349,\n-36,557 l0,"+(t+84)+"c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210,\n949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9\nc0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5,\n-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189\nl0,-"+(t+92)+"c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3,\n-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z";case"rparen":return"M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3,\n63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5\nc11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0,"+(t+9)+"\nc-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664\nc-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11\nc0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17\nc242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558\nl0,-"+(t+144)+"c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,\n-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z";default:throw new Error("Unknown stretchy delimiter.")}}(m,Math.round(1e3*e)),o=new Q(m,r),s=(p/1e3).toFixed(3)+"em",i=(t/1e3).toFixed(3)+"em",a=new J([o],{width:s,height:i,viewBox:"0 0 "+p+" "+t}),l=Pe.makeSvgSpan([],[a],n);l.height=t/1e3,l.style.width=s,l.style.height=i,T.push({type:"elem",elem:l})}else{if(T.push(rr(c,u,o)),T.push(or),null===a){const e=M-g-x+.016;T.push(nr(h,e,n))}else{const e=(M-g-x-v)/2+.016;T.push(nr(h,e,n)),T.push(or),T.push(rr(a,u,o)),T.push(or),T.push(nr(h,e,n))}T.push(or),T.push(rr(i,u,o))}const B=n.havingBaseStyle(w.TEXT),C=Pe.makeVList({positionType:"bottom",positionData:A,children:T},B);return Qt(Pe.makeSpan(["delimsizing","mult"],[C],B),w.TEXT,n,s)},lr=.08,hr=function(e,t,r,n,o){const s=function(e,t,r){t*=1e3;let n="";switch(e){case"sqrtMain":n=function(e,t){return"M95,"+(622+e+t)+"\nc-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14\nc0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54\nc44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10\ns173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429\nc69,-144,104.5,-217.7,106.5,-221\nl"+e/2.075+" -"+e+"\nc5.3,-9.3,12,-14,20,-14\nH400000v"+(40+e)+"H845.2724\ns-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7\nc-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z\nM"+(834+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,M);break;case"sqrtSize1":n=function(e,t){return"M263,"+(601+e+t)+"c0.7,0,18,39.7,52,119\nc34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120\nc340,-704.7,510.7,-1060.3,512,-1067\nl"+e/2.084+" -"+e+"\nc4.7,-7.3,11,-11,19,-11\nH40000v"+(40+e)+"H1012.3\ns-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232\nc-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1\ns-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26\nc-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z\nM"+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,M);break;case"sqrtSize2":n=function(e,t){return"M983 "+(10+e+t)+"\nl"+e/3.13+" -"+e+"\nc4,-6.7,10,-10,18,-10 H400000v"+(40+e)+"\nH1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7\ns-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744\nc-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30\nc26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722\nc56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5\nc53.7,-170.3,84.5,-266.8,92.5,-289.5z\nM"+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,M);break;case"sqrtSize3":n=function(e,t){return"M424,"+(2398+e+t)+"\nc-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514\nc0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20\ns-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121\ns209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081\nl"+e/4.223+" -"+e+"c4,-6.7,10,-10,18,-10 H400000\nv"+(40+e)+"H1014.6\ns-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185\nc-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2z M"+(1001+e)+" "+t+"\nh400000v"+(40+e)+"h-400000z"}(t,M);break;case"sqrtSize4":n=function(e,t){return"M473,"+(2713+e+t)+"\nc339.3,-1799.3,509.3,-2700,510,-2702 l"+e/5.298+" -"+e+"\nc3.3,-7.3,9.3,-11,18,-11 H400000v"+(40+e)+"H1017.7\ns-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200\nc0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26\ns76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,\n606zM"+(1001+e)+" "+t+"h400000v"+(40+e)+"H1017.7z"}(t,M);break;case"sqrtTall":n=function(e,t,r){return"M702 "+(e+t)+"H400000"+(40+e)+"\nH742v"+(r-54-t-e)+"l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1\nh-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170\nc-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667\n219 661 l218 661zM702 "+t+"H400000v"+(40+e)+"H742z"}(t,M,r)}return n}(e,n,r),i=new Q(e,s),a=new J([i],{width:"400em",height:F(t),viewBox:"0 0 400000 "+r,preserveAspectRatio:"xMinYMin slice"});return Pe.makeSvgSpan(["hide-tail"],[a],o)},cr=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230a","\u230b","\\lceil","\\rceil","\u2308","\u2309","\\surd"],mr=["\\uparrow","\\downarrow","\\updownarrow","\\Uparrow","\\Downarrow","\\Updownarrow","|","\\|","\\vert","\\Vert","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27ee","\u27ef","\\lmoustache","\\rmoustache","\u23b0","\u23b1"],pr=["<",">","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"],ur=[0,1.2,1.8,2.4,3],dr=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],gr=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"stack"}],fr=[{type:"small",style:w.SCRIPTSCRIPT},{type:"small",style:w.SCRIPT},{type:"small",style:w.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}],br=function(e){if("small"===e.type)return"Main-Regular";if("large"===e.type)return"Size"+e.size+"-Regular";if("stack"===e.type)return"Size4-Regular";throw new Error("Add support for delim type '"+e.type+"' here.")},yr=function(e,t,r,n){for(let o=Math.min(2,3-n.style.size);ot)return r[o]}return r[r.length-1]},xr=function(e,t,r,n,o,s){let i;"<"===e||"\\lt"===e||"\u27e8"===e?e="\\langle":">"!==e&&"\\gt"!==e&&"\u27e9"!==e||(e="\\rangle"),i=l.contains(pr,e)?dr:l.contains(cr,e)?fr:gr;const a=yr(e,t,i,n);return"small"===a.type?function(e,t,r,n,o,s){const i=Pe.makeSymbol(e,"Main-Regular",o,n),a=Qt(i,t,n,s);return r&&er(a,n,t),a}(e,a.style,r,n,o,s):"large"===a.type?tr(e,a.size,r,n,o,s):ar(e,t,r,n,o,s)};var wr={sqrtImage:function(e,t){const r=t.havingBaseSizing(),n=yr("\\surd",e*r.sizeMultiplier,fr,r);let o=r.sizeMultiplier;const s=Math.max(0,t.minRuleThickness-t.fontMetrics().sqrtRuleThickness);let i,a,l=0,h=0,c=0;return"small"===n.type?(c=1e3+1e3*s+80,e<1?o=1:e<1.4&&(o=.7),l=(1+s+lr)/o,h=(1+s)/o,i=hr("sqrtMain",l,c,s,t),i.style.minWidth="0.853em",a=.833/o):"large"===n.type?(c=1080*ur[n.size],h=(ur[n.size]+s)/o,l=(ur[n.size]+s+lr)/o,i=hr("sqrtSize"+n.size,l,c,s,t),i.style.minWidth="1.02em",a=1/o):(l=e+s+lr,h=e+s,c=Math.floor(1e3*e+s)+80,i=hr("sqrtTall",l,c,s,t),i.style.minWidth="0.742em",a=1.056),i.height=h,i.style.height=F(l),{span:i,advanceWidth:a,ruleWidth:(t.fontMetrics().sqrtRuleThickness+s)*o}},sizedDelim:function(e,t,r,o,s){if("<"===e||"\\lt"===e||"\u27e8"===e?e="\\langle":">"!==e&&"\\gt"!==e&&"\u27e9"!==e||(e="\\rangle"),l.contains(cr,e)||l.contains(pr,e))return tr(e,t,!1,r,o,s);if(l.contains(mr,e))return ar(e,ur[t],!1,r,o,s);throw new n("Illegal delimiter: '"+e+"'")},sizeToMaxHeight:ur,customSizedDelim:xr,leftRightDelim:function(e,t,r,n,o,s){const i=n.fontMetrics().axisHeight*n.sizeMultiplier,a=5/n.fontMetrics().ptPerEm,l=Math.max(t-i,r+i),h=Math.max(l/500*901,2*l-a);return xr(e,h,!0,n,o,s)}};const vr={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}},kr=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230a","\u230b","\\lceil","\\rceil","\u2308","\u2309","<",">","\\langle","\u27e8","\\rangle","\u27e9","\\lt","\\gt","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27ee","\u27ef","\\lmoustache","\\rmoustache","\u23b0","\u23b1","/","\\backslash","|","\\vert","\\|","\\Vert","\\uparrow","\\Uparrow","\\downarrow","\\Downarrow","\\updownarrow","\\Updownarrow","."];function Sr(e,t){const r=Ot(e);if(r&&l.contains(kr,r.text))return r;throw new n(r?"Invalid delimiter '"+r.text+"' after '"+t.funcName+"'":"Invalid delimiter type '"+e.type+"'",e)}function Mr(e){if(!e.body)throw new Error("Bug: The leftright ParseNode wasn't fully parsed.")}$e({type:"delimsizing",names:["\\bigl","\\Bigl","\\biggl","\\Biggl","\\bigr","\\Bigr","\\biggr","\\Biggr","\\bigm","\\Bigm","\\biggm","\\Biggm","\\big","\\Big","\\bigg","\\Bigg"],props:{numArgs:1,argTypes:["primitive"]},handler:(e,t)=>{const r=Sr(t[0],e);return{type:"delimsizing",mode:e.parser.mode,size:vr[e.funcName].size,mclass:vr[e.funcName].mclass,delim:r.text}},htmlBuilder:(e,t)=>"."===e.delim?Pe.makeSpan([e.mclass]):wr.sizedDelim(e.delim,e.size,t,e.mode,[e.mclass]),mathmlBuilder:e=>{const t=[];"."!==e.delim&&t.push(bt(e.delim,e.mode));const r=new ft.MathNode("mo",t);"mopen"===e.mclass||"mclose"===e.mclass?r.setAttribute("fence","true"):r.setAttribute("fence","false"),r.setAttribute("stretchy","true");const n=F(wr.sizeToMaxHeight[e.size]);return r.setAttribute("minsize",n),r.setAttribute("maxsize",n),r}}),$e({type:"leftright-right",names:["\\right"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{const r=e.parser.gullet.macros.get("\\current@color");if(r&&"string"!=typeof r)throw new n("\\current@color set to non-string in \\right");return{type:"leftright-right",mode:e.parser.mode,delim:Sr(t[0],e).text,color:r}}}),$e({type:"leftright",names:["\\left"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{const r=Sr(t[0],e),n=e.parser;++n.leftrightDepth;const o=n.parseExpression(!1);--n.leftrightDepth,n.expect("\\right",!1);const s=Rt(n.parseFunction(),"leftright-right");return{type:"leftright",mode:n.mode,body:o,left:r.text,right:s.delim,rightColor:s.color}},htmlBuilder:(e,t)=>{Mr(e);const r=ot(e.body,t,!0,["mopen","mclose"]);let n,o,s=0,i=0,a=!1;for(let e=0;e{Mr(e);const r=vt(e.body,t);if("."!==e.left){const t=new ft.MathNode("mo",[bt(e.left,e.mode)]);t.setAttribute("fence","true"),r.unshift(t)}if("."!==e.right){const t=new ft.MathNode("mo",[bt(e.right,e.mode)]);t.setAttribute("fence","true"),e.rightColor&&t.setAttribute("mathcolor",e.rightColor),r.push(t)}return yt(r)}}),$e({type:"middle",names:["\\middle"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{const r=Sr(t[0],e);if(!e.parser.leftrightDepth)throw new n("\\middle without preceding \\left",r);return{type:"middle",mode:e.parser.mode,delim:r.text}},htmlBuilder:(e,t)=>{let r;if("."===e.delim)r=ht(t,[]);else{r=wr.sizedDelim(e.delim,1,t,e.mode,[]);const n={delim:e.delim,options:t};r.isMiddle=n}return r},mathmlBuilder:(e,t)=>{const r="\\vert"===e.delim||"|"===e.delim?bt("|","text"):bt(e.delim,e.mode),n=new ft.MathNode("mo",[r]);return n.setAttribute("fence","true"),n.setAttribute("lspace","0.05em"),n.setAttribute("rspace","0.05em"),n}});const zr=(e,t)=>{const r=Pe.wrapFragment(ct(e.body,t),t),n=e.label.slice(1);let o,s=t.sizeMultiplier,i=0;const a=l.isCharacterBox(e.body);if("sout"===n)o=Pe.makeSpan(["stretchy","sout"]),o.height=t.fontMetrics().defaultRuleThickness/s,i=-.5*t.fontMetrics().xHeight;else if("phase"===n){const e=P({number:.6,unit:"pt"},t),n=P({number:.35,unit:"ex"},t);s/=t.havingBaseSizing().sizeMultiplier;const a=r.height+r.depth+e+n;r.style.paddingLeft=F(a/2+e);const l=Math.floor(1e3*a*s),c="M400000 "+(h=l)+" H0 L"+h/2+" 0 l65 45 L145 "+(h-80)+" H400000z",m=new J([new Q("phase",c)],{width:"400em",height:F(l/1e3),viewBox:"0 0 400000 "+l,preserveAspectRatio:"xMinYMin slice"});o=Pe.makeSvgSpan(["hide-tail"],[m],t),o.style.height=F(a),i=r.depth+e+n}else{/cancel/.test(n)?a||r.classes.push("cancel-pad"):"angl"===n?r.classes.push("anglpad"):r.classes.push("boxpad");let s=0,l=0,h=0;/box/.test(n)?(h=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness),s=t.fontMetrics().fboxsep+("colorbox"===n?0:h),l=s):"angl"===n?(h=Math.max(t.fontMetrics().defaultRuleThickness,t.minRuleThickness),s=4*h,l=Math.max(0,.25-r.depth)):(s=a?.2:0,l=s),o=Nt(r,n,s,l,t),/fbox|boxed|fcolorbox/.test(n)?(o.style.borderStyle="solid",o.style.borderWidth=F(h)):"angl"===n&&.049!==h&&(o.style.borderTopWidth=F(h),o.style.borderRightWidth=F(h)),i=r.depth+l,e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor,e.borderColor&&(o.style.borderColor=e.borderColor))}var h;let c;if(e.backgroundColor)c=Pe.makeVList({positionType:"individualShift",children:[{type:"elem",elem:o,shift:i},{type:"elem",elem:r,shift:0}]},t);else{const e=/cancel|phase/.test(n)?["svg-align"]:[];c=Pe.makeVList({positionType:"individualShift",children:[{type:"elem",elem:r,shift:0},{type:"elem",elem:o,shift:i,wrapperClasses:e}]},t)}return/cancel/.test(n)&&(c.height=r.height,c.depth=r.depth),/cancel/.test(n)&&!a?Pe.makeSpan(["mord","cancel-lap"],[c],t):Pe.makeSpan(["mord"],[c],t)},Ar=(e,t)=>{let r=0;const n=new ft.MathNode(e.label.indexOf("colorbox")>-1?"mpadded":"menclose",[St(e.body,t)]);switch(e.label){case"\\cancel":n.setAttribute("notation","updiagonalstrike");break;case"\\bcancel":n.setAttribute("notation","downdiagonalstrike");break;case"\\phase":n.setAttribute("notation","phasorangle");break;case"\\sout":n.setAttribute("notation","horizontalstrike");break;case"\\fbox":n.setAttribute("notation","box");break;case"\\angl":n.setAttribute("notation","actuarial");break;case"\\fcolorbox":case"\\colorbox":if(r=t.fontMetrics().fboxsep*t.fontMetrics().ptPerEm,n.setAttribute("width","+"+2*r+"pt"),n.setAttribute("height","+"+2*r+"pt"),n.setAttribute("lspace",r+"pt"),n.setAttribute("voffset",r+"pt"),"\\fcolorbox"===e.label){const r=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness);n.setAttribute("style","border: "+r+"em solid "+String(e.borderColor))}break;case"\\xcancel":n.setAttribute("notation","updiagonalstrike downdiagonalstrike")}return e.backgroundColor&&n.setAttribute("mathbackground",e.backgroundColor),n};$e({type:"enclose",names:["\\colorbox"],props:{numArgs:2,allowedInText:!0,argTypes:["color","text"]},handler(e,t,r){let{parser:n,funcName:o}=e;const s=Rt(t[0],"color-token").color,i=t[1];return{type:"enclose",mode:n.mode,label:o,backgroundColor:s,body:i}},htmlBuilder:zr,mathmlBuilder:Ar}),$e({type:"enclose",names:["\\fcolorbox"],props:{numArgs:3,allowedInText:!0,argTypes:["color","color","text"]},handler(e,t,r){let{parser:n,funcName:o}=e;const s=Rt(t[0],"color-token").color,i=Rt(t[1],"color-token").color,a=t[2];return{type:"enclose",mode:n.mode,label:o,backgroundColor:i,borderColor:s,body:a}},htmlBuilder:zr,mathmlBuilder:Ar}),$e({type:"enclose",names:["\\fbox"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!0},handler(e,t){let{parser:r}=e;return{type:"enclose",mode:r.mode,label:"\\fbox",body:t[0]}}}),$e({type:"enclose",names:["\\cancel","\\bcancel","\\xcancel","\\sout","\\phase"],props:{numArgs:1},handler(e,t){let{parser:r,funcName:n}=e;const o=t[0];return{type:"enclose",mode:r.mode,label:n,body:o}},htmlBuilder:zr,mathmlBuilder:Ar}),$e({type:"enclose",names:["\\angl"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!1},handler(e,t){let{parser:r}=e;return{type:"enclose",mode:r.mode,label:"\\angl",body:t[0]}}});const Tr={};function Br(e){let{type:t,names:r,props:n,handler:o,htmlBuilder:s,mathmlBuilder:i}=e;const a={type:t,numArgs:n.numArgs||0,allowedInText:!1,numOptionalArgs:0,handler:o};for(let e=0;e{if(!e.parser.settings.displayMode)throw new n("{"+e.envName+"} can be used only in display mode.")};function Or(e){if(-1===e.indexOf("ed"))return-1===e.indexOf("*")}function Er(e,t,r){let{hskipBeforeAndAfter:o,addJot:s,cols:i,arraystretch:a,colSeparationType:l,autoTag:h,singleRow:c,emptySingleRow:m,maxNumCols:p,leqno:u}=t;if(e.gullet.beginGroup(),c||e.gullet.macros.set("\\cr","\\\\\\relax"),!a){const t=e.gullet.expandMacroAsText("\\arraystretch");if(null==t)a=1;else if(a=parseFloat(t),!a||a<0)throw new n("Invalid \\arraystretch: "+t)}e.gullet.beginGroup();let d=[];const g=[d],f=[],b=[],y=null!=h?[]:void 0;function x(){h&&e.gullet.macros.set("\\@eqnsw","1",!0)}function w(){y&&(e.gullet.macros.get("\\df@tag")?(y.push(e.subparse([new Ir("\\df@tag")])),e.gullet.macros.set("\\df@tag",void 0,!0)):y.push(Boolean(h)&&"1"===e.gullet.macros.get("\\@eqnsw")))}for(x(),b.push(Rr(e));;){let t=e.parseExpression(!1,c?"\\end":"\\\\");e.gullet.endGroup(),e.gullet.beginGroup(),t={type:"ordgroup",mode:e.mode,body:t},r&&(t={type:"styling",mode:e.mode,style:r,body:[t]}),d.push(t);const o=e.fetch().text;if("&"===o){if(p&&d.length===p){if(c||l)throw new n("Too many tab characters: &",e.nextToken);e.settings.reportNonstrict("textEnv","Too few columns specified in the {array} column argument.")}e.consume()}else{if("\\end"===o){w(),1===d.length&&"styling"===t.type&&0===t.body[0].body.length&&(g.length>1||!m)&&g.pop(),b.length0&&(x+=.25),c.push({pos:x,isDashed:e[t]})}for(v(i[0]),r=0;r0&&(p+=y,le)))for(r=0;r=a)continue;(o>0||e.hskipBeforeAndAfter)&&(i=l.deflt(c.pregap,u),0!==i&&(z=Pe.makeSpan(["arraycolsep"],[]),z.style.width=F(i),M.push(z)));let d=[];for(r=0;r0){const e=Pe.makeLineSpan("hline",t,m),r=Pe.makeLineSpan("hdashline",t,m),n=[{type:"elem",elem:h,shift:0}];for(;c.length>0;){const t=c.pop(),o=t.pos-k;t.isDashed?n.push({type:"elem",elem:r,shift:o}):n.push({type:"elem",elem:e,shift:o})}h=Pe.makeVList({positionType:"individualShift",children:n},t)}if(0===T.length)return Pe.makeSpan(["mord"],[h],t);{let e=Pe.makeVList({positionType:"individualShift",children:T},t);return e=Pe.makeSpan(["tag"],[e],t),Pe.makeFragment([h,e])}},Vr={c:"center ",l:"left ",r:"right "},Pr=function(e,t){const r=[],n=new ft.MathNode("mtd",[],["mtr-glue"]),o=new ft.MathNode("mtd",[],["mml-eqn-num"]);for(let s=0;s0){const t=e.cols;let r="",n=!1,o=0,i=t.length;"separator"===t[0].type&&(a+="top ",o=1),"separator"===t[t.length-1].type&&(a+="bottom ",i-=1);for(let e=o;e0?"left ":"",a+=c[c.length-1].length>0?"right ":"";for(let e=1;e-1?"alignat":"align",s="split"===e.envName,i=Er(e.parser,{cols:r,addJot:!0,autoTag:s?void 0:Or(e.envName),emptySingleRow:!0,colSeparationType:o,maxNumCols:s?2:void 0,leqno:e.parser.settings.leqno},"display");let a,l=0;const h={type:"ordgroup",mode:e.mode,body:[]};if(t[0]&&"ordgroup"===t[0].type){let e="";for(let r=0;r0&&c&&(n=1),r[e]={type:"align",align:t,pregap:n,postgap:0}}return i.colSeparationType=c?"align":"alignat",i};Br({type:"array",names:["array","darray"],props:{numArgs:1},handler(e,t){const r=(Ot(t[0])?[t[0]]:Rt(t[0],"ordgroup").body).map((function(e){const t=Ht(e).text;if(-1!=="lcr".indexOf(t))return{type:"align",align:t};if("|"===t)return{type:"separator",separator:"|"};if(":"===t)return{type:"separator",separator:":"};throw new n("Unknown column alignment: "+t,e)})),o={cols:r,hskipBeforeAndAfter:!0,maxNumCols:r.length};return Er(e.parser,o,Lr(e.envName))},htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix","matrix*","pmatrix*","bmatrix*","Bmatrix*","vmatrix*","Vmatrix*"],props:{numArgs:0},handler(e){const t={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[e.envName.replace("*","")];let r="c";const o={hskipBeforeAndAfter:!1,cols:[{type:"align",align:r}]};if("*"===e.envName.charAt(e.envName.length-1)){const t=e.parser;if(t.consumeSpaces(),"["===t.fetch().text){if(t.consume(),t.consumeSpaces(),r=t.fetch().text,-1==="lcr".indexOf(r))throw new n("Expected l or c or r",t.nextToken);t.consume(),t.consumeSpaces(),t.expect("]"),t.consume(),o.cols=[{type:"align",align:r}]}}const s=Er(e.parser,o,Lr(e.envName)),i=Math.max(0,...s.body.map((e=>e.length)));return s.cols=new Array(i).fill({type:"align",align:r}),t?{type:"leftright",mode:e.mode,body:[s],left:t[0],right:t[1],rightColor:void 0}:s},htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["smallmatrix"],props:{numArgs:0},handler(e){const t=Er(e.parser,{arraystretch:.5},"script");return t.colSeparationType="small",t},htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["subarray"],props:{numArgs:1},handler(e,t){const r=(Ot(t[0])?[t[0]]:Rt(t[0],"ordgroup").body).map((function(e){const t=Ht(e).text;if(-1!=="lc".indexOf(t))return{type:"align",align:t};throw new n("Unknown column alignment: "+t,e)}));if(r.length>1)throw new n("{subarray} can contain only one column");let o={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5};if(o=Er(e.parser,o,"script"),o.body.length>0&&o.body[0].length>1)throw new n("{subarray} can contain only one column");return o},htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["cases","dcases","rcases","drcases"],props:{numArgs:0},handler(e){const t=Er(e.parser,{arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},Lr(e.envName));return{type:"leftright",mode:e.mode,body:[t],left:e.envName.indexOf("r")>-1?".":"\\{",right:e.envName.indexOf("r")>-1?"\\}":".",rightColor:void 0}},htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["align","align*","aligned","split"],props:{numArgs:0},handler:Fr,htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["gathered","gather","gather*"],props:{numArgs:0},handler(e){l.contains(["gather","gather*"],e.envName)&&Hr(e);const t={cols:[{type:"align",align:"c"}],addJot:!0,colSeparationType:"gather",autoTag:Or(e.envName),emptySingleRow:!0,leqno:e.parser.settings.leqno};return Er(e.parser,t,"display")},htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["alignat","alignat*","alignedat"],props:{numArgs:1},handler:Fr,htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["equation","equation*"],props:{numArgs:0},handler(e){Hr(e);const t={autoTag:Or(e.envName),emptySingleRow:!0,singleRow:!0,maxNumCols:1,leqno:e.parser.settings.leqno};return Er(e.parser,t,"display")},htmlBuilder:Dr,mathmlBuilder:Pr}),Br({type:"array",names:["CD"],props:{numArgs:0},handler(e){return Hr(e),function(e){const t=[];for(e.gullet.beginGroup(),e.gullet.macros.set("\\cr","\\\\\\relax"),e.gullet.beginGroup();;){t.push(e.parseExpression(!1,"\\\\")),e.gullet.endGroup(),e.gullet.beginGroup();const r=e.fetch().text;if("&"!==r&&"\\\\"!==r){if("\\end"===r){0===t[t.length-1].length&&t.pop();break}throw new n("Expected \\\\ or \\cr or \\end",e.nextToken)}e.consume()}let r=[];const o=[r];for(let a=0;a-1);else{if(!("<>AV".indexOf(o)>-1))throw new n('Expected one of "<>AV=|." after @',l[t]);for(let e=0;e<2;e++){let r=!0;for(let h=t+1;h{const r=e.font,n=t.withFont(r);return ct(e.body,n)},Yr=(e,t)=>{const r=e.font,n=t.withFont(r);return St(e.body,n)},Xr={"\\Bbb":"\\mathbb","\\bold":"\\mathbf","\\frak":"\\mathfrak","\\bm":"\\boldsymbol"};$e({type:"font",names:["\\mathrm","\\mathit","\\mathbf","\\mathnormal","\\mathsfit","\\mathbb","\\mathcal","\\mathfrak","\\mathscr","\\mathsf","\\mathtt","\\Bbb","\\bold","\\frak"],props:{numArgs:1,allowedInArgument:!0},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=Ke(t[0]);let s=n;return s in Xr&&(s=Xr[s]),{type:"font",mode:r.mode,font:s.slice(1),body:o}},htmlBuilder:Ur,mathmlBuilder:Yr}),$e({type:"mclass",names:["\\boldsymbol","\\bm"],props:{numArgs:1},handler:(e,t)=>{let{parser:r}=e;const n=t[0],o=l.isCharacterBox(n);return{type:"mclass",mode:r.mode,mclass:Ut(n),body:[{type:"font",mode:r.mode,font:"boldsymbol",body:n}],isCharacterBox:o}}}),$e({type:"font",names:["\\rm","\\sf","\\tt","\\bf","\\it","\\cal"],props:{numArgs:0,allowedInText:!0},handler:(e,t)=>{let{parser:r,funcName:n,breakOnTokenText:o}=e;const{mode:s}=r,i=r.parseExpression(!0,o);return{type:"font",mode:s,font:"math"+n.slice(1),body:{type:"ordgroup",mode:r.mode,body:i}}},htmlBuilder:Ur,mathmlBuilder:Yr});const Wr=(e,t)=>{let r=t;return"display"===e?r=r.id>=w.SCRIPT.id?r.text():w.DISPLAY:"text"===e&&r.size===w.DISPLAY.size?r=w.TEXT:"script"===e?r=w.SCRIPT:"scriptscript"===e&&(r=w.SCRIPTSCRIPT),r},_r=(e,t)=>{const r=Wr(e.size,t.style),n=r.fracNum(),o=r.fracDen();let s;s=t.havingStyle(n);const i=ct(e.numer,s,t);if(e.continued){const e=8.5/t.fontMetrics().ptPerEm,r=3.5/t.fontMetrics().ptPerEm;i.height=i.height0?3*c:7*c,u=t.fontMetrics().denom1):(h>0?(m=t.fontMetrics().num2,p=c):(m=t.fontMetrics().num3,p=3*c),u=t.fontMetrics().denom2),l){const e=t.fontMetrics().axisHeight;m-i.depth-(e+.5*h){let r=new ft.MathNode("mfrac",[St(e.numer,t),St(e.denom,t)]);if(e.hasBarLine){if(e.barSize){const n=P(e.barSize,t);r.setAttribute("linethickness",F(n))}}else r.setAttribute("linethickness","0px");const n=Wr(e.size,t.style);if(n.size!==t.style.size){r=new ft.MathNode("mstyle",[r]);const e=n.size===w.DISPLAY.size?"true":"false";r.setAttribute("displaystyle",e),r.setAttribute("scriptlevel","0")}if(null!=e.leftDelim||null!=e.rightDelim){const t=[];if(null!=e.leftDelim){const r=new ft.MathNode("mo",[new ft.TextNode(e.leftDelim.replace("\\",""))]);r.setAttribute("fence","true"),t.push(r)}if(t.push(r),null!=e.rightDelim){const r=new ft.MathNode("mo",[new ft.TextNode(e.rightDelim.replace("\\",""))]);r.setAttribute("fence","true"),t.push(r)}return yt(t)}return r};$e({type:"genfrac",names:["\\dfrac","\\frac","\\tfrac","\\dbinom","\\binom","\\tbinom","\\\\atopfrac","\\\\bracefrac","\\\\brackfrac"],props:{numArgs:2,allowedInArgument:!0},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0],s=t[1];let i,a=null,l=null,h="auto";switch(n){case"\\dfrac":case"\\frac":case"\\tfrac":i=!0;break;case"\\\\atopfrac":i=!1;break;case"\\dbinom":case"\\binom":case"\\tbinom":i=!1,a="(",l=")";break;case"\\\\bracefrac":i=!1,a="\\{",l="\\}";break;case"\\\\brackfrac":i=!1,a="[",l="]";break;default:throw new Error("Unrecognized genfrac command")}switch(n){case"\\dfrac":case"\\dbinom":h="display";break;case"\\tfrac":case"\\tbinom":h="text"}return{type:"genfrac",mode:r.mode,continued:!1,numer:o,denom:s,hasBarLine:i,leftDelim:a,rightDelim:l,size:h,barSize:null}},htmlBuilder:_r,mathmlBuilder:jr}),$e({type:"genfrac",names:["\\cfrac"],props:{numArgs:2},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0],s=t[1];return{type:"genfrac",mode:r.mode,continued:!0,numer:o,denom:s,hasBarLine:!0,leftDelim:null,rightDelim:null,size:"display",barSize:null}}}),$e({type:"infix",names:["\\over","\\choose","\\atop","\\brace","\\brack"],props:{numArgs:0,infix:!0},handler(e){let t,{parser:r,funcName:n,token:o}=e;switch(n){case"\\over":t="\\frac";break;case"\\choose":t="\\binom";break;case"\\atop":t="\\\\atopfrac";break;case"\\brace":t="\\\\bracefrac";break;case"\\brack":t="\\\\brackfrac";break;default:throw new Error("Unrecognized infix genfrac command")}return{type:"infix",mode:r.mode,replaceWith:t,token:o}}});const $r=["display","text","script","scriptscript"],Zr=function(e){let t=null;return e.length>0&&(t=e,t="."===t?null:t),t};$e({type:"genfrac",names:["\\genfrac"],props:{numArgs:6,allowedInArgument:!0,argTypes:["math","math","size","text","math","math"]},handler(e,t){let{parser:r}=e;const n=t[4],o=t[5],s=Ke(t[0]),i="atom"===s.type&&"open"===s.family?Zr(s.text):null,a=Ke(t[1]),l="atom"===a.type&&"close"===a.family?Zr(a.text):null,h=Rt(t[2],"size");let c,m=null;h.isBlank?c=!0:(m=h.value,c=m.number>0);let p="auto",u=t[3];if("ordgroup"===u.type){if(u.body.length>0){const e=Rt(u.body[0],"textord");p=$r[Number(e.text)]}}else u=Rt(u,"textord"),p=$r[Number(u.text)];return{type:"genfrac",mode:r.mode,numer:n,denom:o,continued:!1,hasBarLine:c,barSize:m,leftDelim:i,rightDelim:l,size:p}},htmlBuilder:_r,mathmlBuilder:jr}),$e({type:"infix",names:["\\above"],props:{numArgs:1,argTypes:["size"],infix:!0},handler(e,t){let{parser:r,funcName:n,token:o}=e;return{type:"infix",mode:r.mode,replaceWith:"\\\\abovefrac",size:Rt(t[0],"size").value,token:o}}}),$e({type:"genfrac",names:["\\\\abovefrac"],props:{numArgs:3,argTypes:["math","size","math"]},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0],s=function(e){if(!e)throw new Error("Expected non-null, but got "+String(e));return e}(Rt(t[1],"infix").size),i=t[2],a=s.number>0;return{type:"genfrac",mode:r.mode,numer:o,denom:i,continued:!1,hasBarLine:a,barSize:s,leftDelim:null,rightDelim:null,size:"auto"}},htmlBuilder:_r,mathmlBuilder:jr});const Kr=(e,t)=>{const r=t.style;let n,o;"supsub"===e.type?(n=e.sup?ct(e.sup,t.havingStyle(r.sup()),t):ct(e.sub,t.havingStyle(r.sub()),t),o=Rt(e.base,"horizBrace")):o=Rt(e,"horizBrace");const s=ct(o.base,t.havingBaseStyle(w.DISPLAY)),i=It(o,t);let a;if(o.isOver?(a=Pe.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"kern",size:.1},{type:"elem",elem:i}]},t),a.children[0].children[0].children[1].classes.push("svg-align")):(a=Pe.makeVList({positionType:"bottom",positionData:s.depth+.1+i.height,children:[{type:"elem",elem:i},{type:"kern",size:.1},{type:"elem",elem:s}]},t),a.children[0].children[0].children[0].classes.push("svg-align")),n){const e=Pe.makeSpan(["mord",o.isOver?"mover":"munder"],[a],t);a=o.isOver?Pe.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:e},{type:"kern",size:.2},{type:"elem",elem:n}]},t):Pe.makeVList({positionType:"bottom",positionData:e.depth+.2+n.height+n.depth,children:[{type:"elem",elem:n},{type:"kern",size:.2},{type:"elem",elem:e}]},t)}return Pe.makeSpan(["mord",o.isOver?"mover":"munder"],[a],t)};$e({type:"horizBrace",names:["\\overbrace","\\underbrace"],props:{numArgs:1},handler(e,t){let{parser:r,funcName:n}=e;return{type:"horizBrace",mode:r.mode,label:n,isOver:/^\\over/.test(n),base:t[0]}},htmlBuilder:Kr,mathmlBuilder:(e,t)=>{const r=qt(e.label);return new ft.MathNode(e.isOver?"mover":"munder",[St(e.base,t),r])}}),$e({type:"href",names:["\\href"],props:{numArgs:2,argTypes:["url","original"],allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[1],o=Rt(t[0],"url").url;return r.settings.isTrusted({command:"\\href",url:o})?{type:"href",mode:r.mode,href:o,body:Je(n)}:r.formatUnsupportedCmd("\\href")},htmlBuilder:(e,t)=>{const r=ot(e.body,t,!1);return Pe.makeAnchor(e.href,[],r,t)},mathmlBuilder:(e,t)=>{let r=kt(e.body,t);return r instanceof dt||(r=new dt("mrow",[r])),r.setAttribute("href",e.href),r}}),$e({type:"href",names:["\\url"],props:{numArgs:1,argTypes:["url"],allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=Rt(t[0],"url").url;if(!r.settings.isTrusted({command:"\\url",url:n}))return r.formatUnsupportedCmd("\\url");const o=[];for(let e=0;e{let{parser:r,funcName:o,token:s}=e;const i=Rt(t[0],"raw").string,a=t[1];let l;r.settings.strict&&r.settings.reportNonstrict("htmlExtension","HTML extension is disabled on strict mode");const h={};switch(o){case"\\htmlClass":h.class=i,l={command:"\\htmlClass",class:i};break;case"\\htmlId":h.id=i,l={command:"\\htmlId",id:i};break;case"\\htmlStyle":h.style=i,l={command:"\\htmlStyle",style:i};break;case"\\htmlData":{const e=i.split(",");for(let t=0;t{const r=ot(e.body,t,!1),n=["enclosing"];e.attributes.class&&n.push(...e.attributes.class.trim().split(/\s+/));const o=Pe.makeSpan(n,r,t);for(const t in e.attributes)"class"!==t&&e.attributes.hasOwnProperty(t)&&o.setAttribute(t,e.attributes[t]);return o},mathmlBuilder:(e,t)=>kt(e.body,t)}),$e({type:"htmlmathml",names:["\\html@mathml"],props:{numArgs:2,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;return{type:"htmlmathml",mode:r.mode,html:Je(t[0]),mathml:Je(t[1])}},htmlBuilder:(e,t)=>{const r=ot(e.html,t,!1);return Pe.makeFragment(r)},mathmlBuilder:(e,t)=>kt(e.mathml,t)});const Jr=function(e){if(/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(e))return{number:+e,unit:"bp"};{const t=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e);if(!t)throw new n("Invalid size: '"+e+"' in \\includegraphics");const r={number:+(t[1]+t[2]),unit:t[3]};if(!V(r))throw new n("Invalid unit: '"+r.unit+"' in \\includegraphics.");return r}};$e({type:"includegraphics",names:["\\includegraphics"],props:{numArgs:1,numOptionalArgs:1,argTypes:["raw","url"],allowedInText:!1},handler:(e,t,r)=>{let{parser:o}=e,s={number:0,unit:"em"},i={number:.9,unit:"em"},a={number:0,unit:"em"},l="";if(r[0]){const e=Rt(r[0],"raw").string.split(",");for(let t=0;t{const r=P(e.height,t);let n=0;e.totalheight.number>0&&(n=P(e.totalheight,t)-r);let o=0;e.width.number>0&&(o=P(e.width,t));const s={height:F(r+n)};o>0&&(s.width=F(o)),n>0&&(s.verticalAlign=F(-n));const i=new $(e.src,e.alt,s);return i.height=r,i.depth=n,i},mathmlBuilder:(e,t)=>{const r=new ft.MathNode("mglyph",[]);r.setAttribute("alt",e.alt);const n=P(e.height,t);let o=0;if(e.totalheight.number>0&&(o=P(e.totalheight,t)-n,r.setAttribute("valign",F(-o))),r.setAttribute("height",F(n+o)),e.width.number>0){const n=P(e.width,t);r.setAttribute("width",F(n))}return r.setAttribute("src",e.src),r}}),$e({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],props:{numArgs:1,argTypes:["size"],primitive:!0,allowedInText:!0},handler(e,t){let{parser:r,funcName:n}=e;const o=Rt(t[0],"size");if(r.settings.strict){const e="m"===n[1],t="mu"===o.value.unit;e?(t||r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" supports only mu units, not "+o.value.unit+" units"),"math"!==r.mode&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" works only in math mode")):t&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" doesn't support mu units")}return{type:"kern",mode:r.mode,dimension:o.value}},htmlBuilder(e,t){return Pe.makeGlue(e.dimension,t)},mathmlBuilder(e,t){const r=P(e.dimension,t);return new ft.SpaceNode(r)}}),$e({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0];return{type:"lap",mode:r.mode,alignment:n.slice(5),body:o}},htmlBuilder:(e,t)=>{let r;"clap"===e.alignment?(r=Pe.makeSpan([],[ct(e.body,t)]),r=Pe.makeSpan(["inner"],[r],t)):r=Pe.makeSpan(["inner"],[ct(e.body,t)]);const n=Pe.makeSpan(["fix"],[]);let o=Pe.makeSpan([e.alignment],[r,n],t);const s=Pe.makeSpan(["strut"]);return s.style.height=F(o.height+o.depth),o.depth&&(s.style.verticalAlign=F(-o.depth)),o.children.unshift(s),o=Pe.makeSpan(["thinbox"],[o],t),Pe.makeSpan(["mord","vbox"],[o],t)},mathmlBuilder:(e,t)=>{const r=new ft.MathNode("mpadded",[St(e.body,t)]);if("rlap"!==e.alignment){const t="llap"===e.alignment?"-1":"-0.5";r.setAttribute("lspace",t+"width")}return r.setAttribute("width","0px"),r}}),$e({type:"styling",names:["\\(","$"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(e,t){let{funcName:r,parser:n}=e;const o=n.mode;n.switchMode("math");const s="\\("===r?"\\)":"$",i=n.parseExpression(!1,s);return n.expect(s),n.switchMode(o),{type:"styling",mode:n.mode,style:"text",body:i}}}),$e({type:"text",names:["\\)","\\]"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(e,t){throw new n("Mismatched "+e.funcName)}});const Qr=(e,t)=>{switch(t.style.size){case w.DISPLAY.size:return e.display;case w.TEXT.size:return e.text;case w.SCRIPT.size:return e.script;case w.SCRIPTSCRIPT.size:return e.scriptscript;default:return e.text}};$e({type:"mathchoice",names:["\\mathchoice"],props:{numArgs:4,primitive:!0},handler:(e,t)=>{let{parser:r}=e;return{type:"mathchoice",mode:r.mode,display:Je(t[0]),text:Je(t[1]),script:Je(t[2]),scriptscript:Je(t[3])}},htmlBuilder:(e,t)=>{const r=Qr(e,t),n=ot(r,t,!1);return Pe.makeFragment(n)},mathmlBuilder:(e,t)=>{const r=Qr(e,t);return kt(r,t)}});const en=(e,t,r,n,o,s,i)=>{e=Pe.makeSpan([],[e]);const a=r&&l.isCharacterBox(r);let h,c,m;if(t){const e=ct(t,n.havingStyle(o.sup()),n);c={elem:e,kern:Math.max(n.fontMetrics().bigOpSpacing1,n.fontMetrics().bigOpSpacing3-e.depth)}}if(r){const e=ct(r,n.havingStyle(o.sub()),n);h={elem:e,kern:Math.max(n.fontMetrics().bigOpSpacing2,n.fontMetrics().bigOpSpacing4-e.height)}}if(c&&h){const t=n.fontMetrics().bigOpSpacing5+h.elem.height+h.elem.depth+h.kern+e.depth+i;m=Pe.makeVList({positionType:"bottom",positionData:t,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:h.elem,marginLeft:F(-s)},{type:"kern",size:h.kern},{type:"elem",elem:e},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:F(s)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]},n)}else if(h){const t=e.height-i;m=Pe.makeVList({positionType:"top",positionData:t,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:h.elem,marginLeft:F(-s)},{type:"kern",size:h.kern},{type:"elem",elem:e}]},n)}else{if(!c)return e;{const t=e.depth+i;m=Pe.makeVList({positionType:"bottom",positionData:t,children:[{type:"elem",elem:e},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:F(s)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]},n)}}const p=[m];if(h&&0!==s&&!a){const e=Pe.makeSpan(["mspace"],[],n);e.style.marginRight=F(s),p.unshift(e)}return Pe.makeSpan(["mop","op-limits"],p,n)},tn=["\\smallint"],rn=(e,t)=>{let r,n,o,s=!1;"supsub"===e.type?(r=e.sup,n=e.sub,o=Rt(e.base,"op"),s=!0):o=Rt(e,"op");const i=t.style;let a,h=!1;if(i.size===w.DISPLAY.size&&o.symbol&&!l.contains(tn,o.name)&&(h=!0),o.symbol){const e=h?"Size2-Regular":"Size1-Regular";let r="";if("\\oiint"!==o.name&&"\\oiiint"!==o.name||(r=o.name.slice(1),o.name="oiint"===r?"\\iint":"\\iiint"),a=Pe.makeSymbol(o.name,e,"math",t,["mop","op-symbol",h?"large-op":"small-op"]),r.length>0){const e=a.italic,n=Pe.staticSvg(r+"Size"+(h?"2":"1"),t);a=Pe.makeVList({positionType:"individualShift",children:[{type:"elem",elem:a,shift:0},{type:"elem",elem:n,shift:h?.08:0}]},t),o.name="\\"+r,a.classes.unshift("mop"),a.italic=e}}else if(o.body){const e=ot(o.body,t,!0);1===e.length&&e[0]instanceof K?(a=e[0],a.classes[0]="mop"):a=Pe.makeSpan(["mop"],e,t)}else{const e=[];for(let r=1;r{let r;if(e.symbol)r=new dt("mo",[bt(e.name,e.mode)]),l.contains(tn,e.name)&&r.setAttribute("largeop","false");else if(e.body)r=new dt("mo",vt(e.body,t));else{r=new dt("mi",[new gt(e.name.slice(1))]);const t=new dt("mo",[bt("\u2061","text")]);r=e.parentIsSupSub?new dt("mrow",[r,t]):ut([r,t])}return r},on={"\u220f":"\\prod","\u2210":"\\coprod","\u2211":"\\sum","\u22c0":"\\bigwedge","\u22c1":"\\bigvee","\u22c2":"\\bigcap","\u22c3":"\\bigcup","\u2a00":"\\bigodot","\u2a01":"\\bigoplus","\u2a02":"\\bigotimes","\u2a04":"\\biguplus","\u2a06":"\\bigsqcup"};$e({type:"op",names:["\\coprod","\\bigvee","\\bigwedge","\\biguplus","\\bigcap","\\bigcup","\\intop","\\prod","\\sum","\\bigotimes","\\bigoplus","\\bigodot","\\bigsqcup","\\smallint","\u220f","\u2210","\u2211","\u22c0","\u22c1","\u22c2","\u22c3","\u2a00","\u2a01","\u2a02","\u2a04","\u2a06"],props:{numArgs:0},handler:(e,t)=>{let{parser:r,funcName:n}=e,o=n;return 1===o.length&&(o=on[o]),{type:"op",mode:r.mode,limits:!0,parentIsSupSub:!1,symbol:!0,name:o}},htmlBuilder:rn,mathmlBuilder:nn}),$e({type:"op",names:["\\mathop"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"op",mode:r.mode,limits:!1,parentIsSupSub:!1,symbol:!1,body:Je(n)}},htmlBuilder:rn,mathmlBuilder:nn});const sn={"\u222b":"\\int","\u222c":"\\iint","\u222d":"\\iiint","\u222e":"\\oint","\u222f":"\\oiint","\u2230":"\\oiiint"};$e({type:"op",names:["\\arcsin","\\arccos","\\arctan","\\arctg","\\arcctg","\\arg","\\ch","\\cos","\\cosec","\\cosh","\\cot","\\cotg","\\coth","\\csc","\\ctg","\\cth","\\deg","\\dim","\\exp","\\hom","\\ker","\\lg","\\ln","\\log","\\sec","\\sin","\\sinh","\\sh","\\tan","\\tanh","\\tg","\\th"],props:{numArgs:0},handler(e){let{parser:t,funcName:r}=e;return{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:rn,mathmlBuilder:nn}),$e({type:"op",names:["\\det","\\gcd","\\inf","\\lim","\\max","\\min","\\Pr","\\sup"],props:{numArgs:0},handler(e){let{parser:t,funcName:r}=e;return{type:"op",mode:t.mode,limits:!0,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:rn,mathmlBuilder:nn}),$e({type:"op",names:["\\int","\\iint","\\iiint","\\oint","\\oiint","\\oiiint","\u222b","\u222c","\u222d","\u222e","\u222f","\u2230"],props:{numArgs:0},handler(e){let{parser:t,funcName:r}=e,n=r;return 1===n.length&&(n=sn[n]),{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!0,name:n}},htmlBuilder:rn,mathmlBuilder:nn});const an=(e,t)=>{let r,n,o,s,i=!1;if("supsub"===e.type?(r=e.sup,n=e.sub,o=Rt(e.base,"operatorname"),i=!0):o=Rt(e,"operatorname"),o.body.length>0){const e=o.body.map((e=>{const t=e.text;return"string"==typeof t?{type:"textord",mode:e.mode,text:t}:e})),r=ot(e,t.withFont("mathrm"),!0);for(let e=0;e{let{parser:r,funcName:n}=e;const o=t[0];return{type:"operatorname",mode:r.mode,body:Je(o),alwaysHandleSupSub:"\\operatornamewithlimits"===n,limits:!1,parentIsSupSub:!1}},htmlBuilder:an,mathmlBuilder:(e,t)=>{let r=vt(e.body,t.withFont("mathrm")),n=!0;for(let e=0;ee.toText())).join("");r=[new ft.TextNode(e)]}const o=new ft.MathNode("mi",r);o.setAttribute("mathvariant","normal");const s=new ft.MathNode("mo",[bt("\u2061","text")]);return e.parentIsSupSub?new ft.MathNode("mrow",[o,s]):ft.newDocumentFragment([o,s])}}),Nr("\\operatorname","\\@ifstar\\operatornamewithlimits\\operatorname@"),Ze({type:"ordgroup",htmlBuilder(e,t){return e.semisimple?Pe.makeFragment(ot(e.body,t,!1)):Pe.makeSpan(["mord"],ot(e.body,t,!0),t)},mathmlBuilder(e,t){return kt(e.body,t,!0)}}),$e({type:"overline",names:["\\overline"],props:{numArgs:1},handler(e,t){let{parser:r}=e;const n=t[0];return{type:"overline",mode:r.mode,body:n}},htmlBuilder(e,t){const r=ct(e.body,t.havingCrampedStyle()),n=Pe.makeLineSpan("overline-line",t),o=t.fontMetrics().defaultRuleThickness,s=Pe.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r},{type:"kern",size:3*o},{type:"elem",elem:n},{type:"kern",size:o}]},t);return Pe.makeSpan(["mord","overline"],[s],t)},mathmlBuilder(e,t){const r=new ft.MathNode("mo",[new ft.TextNode("\u203e")]);r.setAttribute("stretchy","true");const n=new ft.MathNode("mover",[St(e.body,t),r]);return n.setAttribute("accent","true"),n}}),$e({type:"phantom",names:["\\phantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"phantom",mode:r.mode,body:Je(n)}},htmlBuilder:(e,t)=>{const r=ot(e.body,t.withPhantom(),!1);return Pe.makeFragment(r)},mathmlBuilder:(e,t)=>{const r=vt(e.body,t);return new ft.MathNode("mphantom",r)}}),$e({type:"hphantom",names:["\\hphantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"hphantom",mode:r.mode,body:n}},htmlBuilder:(e,t)=>{let r=Pe.makeSpan([],[ct(e.body,t.withPhantom())]);if(r.height=0,r.depth=0,r.children)for(let e=0;e{const r=vt(Je(e.body),t),n=new ft.MathNode("mphantom",r),o=new ft.MathNode("mpadded",[n]);return o.setAttribute("height","0px"),o.setAttribute("depth","0px"),o}}),$e({type:"vphantom",names:["\\vphantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"vphantom",mode:r.mode,body:n}},htmlBuilder:(e,t)=>{const r=Pe.makeSpan(["inner"],[ct(e.body,t.withPhantom())]),n=Pe.makeSpan(["fix"],[]);return Pe.makeSpan(["mord","rlap"],[r,n],t)},mathmlBuilder:(e,t)=>{const r=vt(Je(e.body),t),n=new ft.MathNode("mphantom",r),o=new ft.MathNode("mpadded",[n]);return o.setAttribute("width","0px"),o}}),$e({type:"raisebox",names:["\\raisebox"],props:{numArgs:2,argTypes:["size","hbox"],allowedInText:!0},handler(e,t){let{parser:r}=e;const n=Rt(t[0],"size").value,o=t[1];return{type:"raisebox",mode:r.mode,dy:n,body:o}},htmlBuilder(e,t){const r=ct(e.body,t),n=P(e.dy,t);return Pe.makeVList({positionType:"shift",positionData:-n,children:[{type:"elem",elem:r}]},t)},mathmlBuilder(e,t){const r=new ft.MathNode("mpadded",[St(e.body,t)]),n=e.dy.number+e.dy.unit;return r.setAttribute("voffset",n),r}}),$e({type:"internal",names:["\\relax"],props:{numArgs:0,allowedInText:!0,allowedInArgument:!0},handler(e){let{parser:t}=e;return{type:"internal",mode:t.mode}}}),$e({type:"rule",names:["\\rule"],props:{numArgs:2,numOptionalArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["size","size","size"]},handler(e,t,r){let{parser:n}=e;const o=r[0],s=Rt(t[0],"size"),i=Rt(t[1],"size");return{type:"rule",mode:n.mode,shift:o&&Rt(o,"size").value,width:s.value,height:i.value}},htmlBuilder(e,t){const r=Pe.makeSpan(["mord","rule"],[],t),n=P(e.width,t),o=P(e.height,t),s=e.shift?P(e.shift,t):0;return r.style.borderRightWidth=F(n),r.style.borderTopWidth=F(o),r.style.bottom=F(s),r.width=n,r.height=o+s,r.depth=-s,r.maxFontSize=1.125*o*t.sizeMultiplier,r},mathmlBuilder(e,t){const r=P(e.width,t),n=P(e.height,t),o=e.shift?P(e.shift,t):0,s=t.color&&t.getColor()||"black",i=new ft.MathNode("mspace");i.setAttribute("mathbackground",s),i.setAttribute("width",F(r)),i.setAttribute("height",F(n));const a=new ft.MathNode("mpadded",[i]);return o>=0?a.setAttribute("height",F(o)):(a.setAttribute("height",F(o)),a.setAttribute("depth",F(-o))),a.setAttribute("voffset",F(o)),a}});const hn=["\\tiny","\\sixptsize","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"];$e({type:"sizing",names:hn,props:{numArgs:0,allowedInText:!0},handler:(e,t)=>{let{breakOnTokenText:r,funcName:n,parser:o}=e;const s=o.parseExpression(!1,r);return{type:"sizing",mode:o.mode,size:hn.indexOf(n)+1,body:s}},htmlBuilder:(e,t)=>{const r=t.havingSize(e.size);return ln(e.body,r,t)},mathmlBuilder:(e,t)=>{const r=t.havingSize(e.size),n=vt(e.body,r),o=new ft.MathNode("mstyle",n);return o.setAttribute("mathsize",F(r.sizeMultiplier)),o}}),$e({type:"smash",names:["\\smash"],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:(e,t,r)=>{let{parser:n}=e,o=!1,s=!1;const i=r[0]&&Rt(r[0],"ordgroup");if(i){let e="";for(let t=0;t{const r=Pe.makeSpan([],[ct(e.body,t)]);if(!e.smashHeight&&!e.smashDepth)return r;if(e.smashHeight&&(r.height=0,r.children))for(let e=0;e{const r=new ft.MathNode("mpadded",[St(e.body,t)]);return e.smashHeight&&r.setAttribute("height","0px"),e.smashDepth&&r.setAttribute("depth","0px"),r}}),$e({type:"sqrt",names:["\\sqrt"],props:{numArgs:1,numOptionalArgs:1},handler(e,t,r){let{parser:n}=e;const o=r[0],s=t[0];return{type:"sqrt",mode:n.mode,body:s,index:o}},htmlBuilder(e,t){let r=ct(e.body,t.havingCrampedStyle());0===r.height&&(r.height=t.fontMetrics().xHeight),r=Pe.wrapFragment(r,t);const n=t.fontMetrics().defaultRuleThickness;let o=n;t.style.idr.height+r.depth+s&&(s=(s+c-r.height-r.depth)/2);const m=a.height-r.height-s-l;r.style.paddingLeft=F(h);const p=Pe.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r,wrapperClasses:["svg-align"]},{type:"kern",size:-(r.height+m)},{type:"elem",elem:a},{type:"kern",size:l}]},t);if(e.index){const r=t.havingStyle(w.SCRIPTSCRIPT),n=ct(e.index,r,t),o=.6*(p.height-p.depth),s=Pe.makeVList({positionType:"shift",positionData:-o,children:[{type:"elem",elem:n}]},t),i=Pe.makeSpan(["root"],[s]);return Pe.makeSpan(["mord","sqrt"],[i,p],t)}return Pe.makeSpan(["mord","sqrt"],[p],t)},mathmlBuilder(e,t){const{body:r,index:n}=e;return n?new ft.MathNode("mroot",[St(r,t),St(n,t)]):new ft.MathNode("msqrt",[St(r,t)])}});const cn={display:w.DISPLAY,text:w.TEXT,script:w.SCRIPT,scriptscript:w.SCRIPTSCRIPT};$e({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e,t){let{breakOnTokenText:r,funcName:n,parser:o}=e;const s=o.parseExpression(!0,r),i=n.slice(1,n.length-5);return{type:"styling",mode:o.mode,style:i,body:s}},htmlBuilder(e,t){const r=cn[e.style],n=t.havingStyle(r).withFont("");return ln(e.body,n,t)},mathmlBuilder(e,t){const r=cn[e.style],n=t.havingStyle(r),o=vt(e.body,n),s=new ft.MathNode("mstyle",o),i={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]}[e.style];return s.setAttribute("scriptlevel",i[0]),s.setAttribute("displaystyle",i[1]),s}});Ze({type:"supsub",htmlBuilder(e,t){const r=function(e,t){const r=e.base;if(r)return"op"===r.type?r.limits&&(t.style.size===w.DISPLAY.size||r.alwaysHandleSupSub)?rn:null:"operatorname"===r.type?r.alwaysHandleSupSub&&(t.style.size===w.DISPLAY.size||r.limits)?an:null:"accent"===r.type?l.isCharacterBox(r.base)?Et:null:"horizBrace"===r.type&&!e.sub===r.isOver?Kr:null;return null}(e,t);if(r)return r(e,t);const{base:n,sup:o,sub:s}=e,i=ct(n,t);let a,h;const c=t.fontMetrics();let m=0,p=0;const u=n&&l.isCharacterBox(n);if(o){const e=t.havingStyle(t.style.sup());a=ct(o,e,t),u||(m=i.height-e.fontMetrics().supDrop*e.sizeMultiplier/t.sizeMultiplier)}if(s){const e=t.havingStyle(t.style.sub());h=ct(s,e,t),u||(p=i.depth+e.fontMetrics().subDrop*e.sizeMultiplier/t.sizeMultiplier)}let d;d=t.style===w.DISPLAY?c.sup1:t.style.cramped?c.sup3:c.sup2;const g=t.sizeMultiplier,f=F(.5/c.ptPerEm/g);let b,y=null;if(h){const t=e.base&&"op"===e.base.type&&e.base.name&&("\\oiint"===e.base.name||"\\oiiint"===e.base.name);(i instanceof K||t)&&(y=F(-i.italic))}if(a&&h){m=Math.max(m,d,a.depth+.25*c.xHeight),p=Math.max(p,c.sub2);const e=4*c.defaultRuleThickness;if(m-a.depth-(h.height-p)0&&(m+=t,p-=t)}const r=[{type:"elem",elem:h,shift:p,marginRight:f,marginLeft:y},{type:"elem",elem:a,shift:-m,marginRight:f}];b=Pe.makeVList({positionType:"individualShift",children:r},t)}else if(h){p=Math.max(p,c.sub1,h.height-.8*c.xHeight);const e=[{type:"elem",elem:h,marginLeft:y,marginRight:f}];b=Pe.makeVList({positionType:"shift",positionData:p,children:e},t)}else{if(!a)throw new Error("supsub must have either sup or sub.");m=Math.max(m,d,a.depth+.25*c.xHeight),b=Pe.makeVList({positionType:"shift",positionData:-m,children:[{type:"elem",elem:a,marginRight:f}]},t)}const x=lt(i,"right")||"mord";return Pe.makeSpan([x],[i,Pe.makeSpan(["msupsub"],[b])],t)},mathmlBuilder(e,t){let r,n,o=!1;e.base&&"horizBrace"===e.base.type&&(n=!!e.sup,n===e.base.isOver&&(o=!0,r=e.base.isOver)),!e.base||"op"!==e.base.type&&"operatorname"!==e.base.type||(e.base.parentIsSupSub=!0);const s=[St(e.base,t)];let i;if(e.sub&&s.push(St(e.sub,t)),e.sup&&s.push(St(e.sup,t)),o)i=r?"mover":"munder";else if(e.sub)if(e.sup){const r=e.base;i=r&&"op"===r.type&&r.limits&&t.style===w.DISPLAY||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(t.style===w.DISPLAY||r.limits)?"munderover":"msubsup"}else{const r=e.base;i=r&&"op"===r.type&&r.limits&&(t.style===w.DISPLAY||r.alwaysHandleSupSub)||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(r.limits||t.style===w.DISPLAY)?"munder":"msub"}else{const r=e.base;i=r&&"op"===r.type&&r.limits&&(t.style===w.DISPLAY||r.alwaysHandleSupSub)||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(r.limits||t.style===w.DISPLAY)?"mover":"msup"}return new ft.MathNode(i,s)}}),Ze({type:"atom",htmlBuilder(e,t){return Pe.mathsym(e.text,e.mode,t,["m"+e.family])},mathmlBuilder(e,t){const r=new ft.MathNode("mo",[bt(e.text,e.mode)]);if("bin"===e.family){const n=xt(e,t);"bold-italic"===n&&r.setAttribute("mathvariant",n)}else"punct"===e.family?r.setAttribute("separator","true"):"open"!==e.family&&"close"!==e.family||r.setAttribute("stretchy","false");return r}});const mn={mi:"italic",mn:"normal",mtext:"normal"};Ze({type:"mathord",htmlBuilder(e,t){return Pe.makeOrd(e,t,"mathord")},mathmlBuilder(e,t){const r=new ft.MathNode("mi",[bt(e.text,e.mode,t)]),n=xt(e,t)||"italic";return n!==mn[r.type]&&r.setAttribute("mathvariant",n),r}}),Ze({type:"textord",htmlBuilder(e,t){return Pe.makeOrd(e,t,"textord")},mathmlBuilder(e,t){const r=bt(e.text,e.mode,t),n=xt(e,t)||"normal";let o;return o="text"===e.mode?new ft.MathNode("mtext",[r]):/[0-9]/.test(e.text)?new ft.MathNode("mn",[r]):"\\prime"===e.text?new ft.MathNode("mo",[r]):new ft.MathNode("mi",[r]),n!==mn[o.type]&&o.setAttribute("mathvariant",n),o}});const pn={"\\nobreak":"nobreak","\\allowbreak":"allowbreak"},un={" ":{},"\\ ":{},"~":{className:"nobreak"},"\\space":{},"\\nobreakspace":{className:"nobreak"}};Ze({type:"spacing",htmlBuilder(e,t){if(un.hasOwnProperty(e.text)){const r=un[e.text].className||"";if("text"===e.mode){const n=Pe.makeOrd(e,t,"textord");return n.classes.push(r),n}return Pe.makeSpan(["mspace",r],[Pe.mathsym(e.text,e.mode,t)],t)}if(pn.hasOwnProperty(e.text))return Pe.makeSpan(["mspace",pn[e.text]],[],t);throw new n('Unknown type of space "'+e.text+'"')},mathmlBuilder(e,t){let r;if(!un.hasOwnProperty(e.text)){if(pn.hasOwnProperty(e.text))return new ft.MathNode("mspace");throw new n('Unknown type of space "'+e.text+'"')}return r=new ft.MathNode("mtext",[new ft.TextNode("\xa0")]),r}});const dn=()=>{const e=new ft.MathNode("mtd",[]);return e.setAttribute("width","50%"),e};Ze({type:"tag",mathmlBuilder(e,t){const r=new ft.MathNode("mtable",[new ft.MathNode("mtr",[dn(),new ft.MathNode("mtd",[kt(e.body,t)]),dn(),new ft.MathNode("mtd",[kt(e.tag,t)])])]);return r.setAttribute("width","100%"),r}});const gn={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},fn={"\\textbf":"textbf","\\textmd":"textmd"},bn={"\\textit":"textit","\\textup":"textup"},yn=(e,t)=>{const r=e.font;return r?gn[r]?t.withTextFontFamily(gn[r]):fn[r]?t.withTextFontWeight(fn[r]):"\\emph"===r?"textit"===t.fontShape?t.withTextFontShape("textup"):t.withTextFontShape("textit"):t.withTextFontShape(bn[r]):t};$e({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup","\\emph"],props:{numArgs:1,argTypes:["text"],allowedInArgument:!0,allowedInText:!0},handler(e,t){let{parser:r,funcName:n}=e;const o=t[0];return{type:"text",mode:r.mode,body:Je(o),font:n}},htmlBuilder(e,t){const r=yn(e,t),n=ot(e.body,r,!0);return Pe.makeSpan(["mord","text"],n,r)},mathmlBuilder(e,t){const r=yn(e,t);return kt(e.body,r)}}),$e({type:"underline",names:["\\underline"],props:{numArgs:1,allowedInText:!0},handler(e,t){let{parser:r}=e;return{type:"underline",mode:r.mode,body:t[0]}},htmlBuilder(e,t){const r=ct(e.body,t),n=Pe.makeLineSpan("underline-line",t),o=t.fontMetrics().defaultRuleThickness,s=Pe.makeVList({positionType:"top",positionData:r.height,children:[{type:"kern",size:o},{type:"elem",elem:n},{type:"kern",size:3*o},{type:"elem",elem:r}]},t);return Pe.makeSpan(["mord","underline"],[s],t)},mathmlBuilder(e,t){const r=new ft.MathNode("mo",[new ft.TextNode("\u203e")]);r.setAttribute("stretchy","true");const n=new ft.MathNode("munder",[St(e.body,t),r]);return n.setAttribute("accentunder","true"),n}}),$e({type:"vcenter",names:["\\vcenter"],props:{numArgs:1,argTypes:["original"],allowedInText:!1},handler(e,t){let{parser:r}=e;return{type:"vcenter",mode:r.mode,body:t[0]}},htmlBuilder(e,t){const r=ct(e.body,t),n=t.fontMetrics().axisHeight,o=.5*(r.height-n-(r.depth+n));return Pe.makeVList({positionType:"shift",positionData:o,children:[{type:"elem",elem:r}]},t)},mathmlBuilder(e,t){return new ft.MathNode("mpadded",[St(e.body,t)],["vcenter"])}}),$e({type:"verb",names:["\\verb"],props:{numArgs:0,allowedInText:!0},handler(e,t,r){throw new n("\\verb ended by end of line instead of matching delimiter")},htmlBuilder(e,t){const r=xn(e),n=[],o=t.havingStyle(t.style.text());for(let t=0;te.body.replace(/ /g,e.star?"\u2423":"\xa0");var wn=We;const vn="[ \r\n\t]",kn="(\\\\[a-zA-Z@]+)"+vn+"*",Sn="[\u0300-\u036f]",Mn=new RegExp(Sn+"+$"),zn="("+vn+"+)|\\\\(\n|[ \r\t]+\n?)[ \r\t]*|([!-\\[\\]-\u2027\u202a-\ud7ff\uf900-\uffff]"+Sn+"*|[\ud800-\udbff][\udc00-\udfff]"+Sn+"*|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5|"+kn+"|\\\\[^\ud800-\udfff])";class An{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(zn,"g"),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){const e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new Ir("EOF",new qr(this,t,t));const r=this.tokenRegex.exec(e);if(null===r||r.index!==t)throw new n("Unexpected character: '"+e[t]+"'",new Ir(e[t],new qr(this,t,t+1)));const o=r[6]||r[3]||(r[2]?"\\ ":" ");if(14===this.catcodes[o]){const t=e.indexOf("\n",this.tokenRegex.lastIndex);return-1===t?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict("commentAtEnd","% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)")):this.tokenRegex.lastIndex=t+1,this.lex()}return new Ir(o,new qr(this,t,this.tokenRegex.lastIndex))}}class Tn{constructor(e,t){void 0===e&&(e={}),void 0===t&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(0===this.undefStack.length)throw new n("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");const e=this.undefStack.pop();for(const t in e)e.hasOwnProperty(t)&&(null==e[t]?delete this.current[t]:this.current[t]=e[t])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return this.current.hasOwnProperty(e)||this.builtins.hasOwnProperty(e)}get(e){return this.current.hasOwnProperty(e)?this.current[e]:this.builtins[e]}set(e,t,r){if(void 0===r&&(r=!1),r){for(let t=0;t0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{const t=this.undefStack[this.undefStack.length-1];t&&!t.hasOwnProperty(e)&&(t[e]=this.current[e])}null==t?delete this.current[e]:this.current[e]=t}}var Bn=Cr;Nr("\\noexpand",(function(e){const t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}})),Nr("\\expandafter",(function(e){const t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}})),Nr("\\@firstoftwo",(function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}})),Nr("\\@secondoftwo",(function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}})),Nr("\\@ifnextchar",(function(e){const t=e.consumeArgs(3);e.consumeSpaces();const r=e.future();return 1===t[0].length&&t[0][0].text===r.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}})),Nr("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}"),Nr("\\TextOrMath",(function(e){const t=e.consumeArgs(2);return"text"===e.mode?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}}));const Cn={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};Nr("\\char",(function(e){let t,r=e.popToken(),o="";if("'"===r.text)t=8,r=e.popToken();else if('"'===r.text)t=16,r=e.popToken();else if("`"===r.text)if(r=e.popToken(),"\\"===r.text[0])o=r.text.charCodeAt(1);else{if("EOF"===r.text)throw new n("\\char` missing argument");o=r.text.charCodeAt(0)}else t=10;if(t){if(o=Cn[r.text],null==o||o>=t)throw new n("Invalid base-"+t+" digit "+r.text);let s;for(;null!=(s=Cn[e.future().text])&&s{let s=e.consumeArg().tokens;if(1!==s.length)throw new n("\\newcommand's first argument must be a macro name");const i=s[0].text,a=e.isDefined(i);if(a&&!t)throw new n("\\newcommand{"+i+"} attempting to redefine "+i+"; use \\renewcommand");if(!a&&!r)throw new n("\\renewcommand{"+i+"} when command "+i+" does not yet exist; use \\newcommand");let l=0;if(s=e.consumeArg().tokens,1===s.length&&"["===s[0].text){let t="",r=e.expandNextToken();for(;"]"!==r.text&&"EOF"!==r.text;)t+=r.text,r=e.expandNextToken();if(!t.match(/^\s*[0-9]+\s*$/))throw new n("Invalid number of arguments: "+t);l=parseInt(t),s=e.consumeArg().tokens}return a&&o||e.macros.set(i,{tokens:s,numArgs:l}),""};Nr("\\newcommand",(e=>Nn(e,!1,!0,!1))),Nr("\\renewcommand",(e=>Nn(e,!0,!1,!1))),Nr("\\providecommand",(e=>Nn(e,!0,!0,!0))),Nr("\\message",(e=>{const t=e.consumeArgs(1)[0];return console.log(t.reverse().map((e=>e.text)).join("")),""})),Nr("\\errmessage",(e=>{const t=e.consumeArgs(1)[0];return console.error(t.reverse().map((e=>e.text)).join("")),""})),Nr("\\show",(e=>{const t=e.popToken(),r=t.text;return console.log(t,e.macros.get(r),wn[r],se.math[r],se.text[r]),""})),Nr("\\bgroup","{"),Nr("\\egroup","}"),Nr("~","\\nobreakspace"),Nr("\\lq","`"),Nr("\\rq","'"),Nr("\\aa","\\r a"),Nr("\\AA","\\r A"),Nr("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`\xa9}"),Nr("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}"),Nr("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`\xae}"),Nr("\u212c","\\mathscr{B}"),Nr("\u2130","\\mathscr{E}"),Nr("\u2131","\\mathscr{F}"),Nr("\u210b","\\mathscr{H}"),Nr("\u2110","\\mathscr{I}"),Nr("\u2112","\\mathscr{L}"),Nr("\u2133","\\mathscr{M}"),Nr("\u211b","\\mathscr{R}"),Nr("\u212d","\\mathfrak{C}"),Nr("\u210c","\\mathfrak{H}"),Nr("\u2128","\\mathfrak{Z}"),Nr("\\Bbbk","\\Bbb{k}"),Nr("\xb7","\\cdotp"),Nr("\\llap","\\mathllap{\\textrm{#1}}"),Nr("\\rlap","\\mathrlap{\\textrm{#1}}"),Nr("\\clap","\\mathclap{\\textrm{#1}}"),Nr("\\mathstrut","\\vphantom{(}"),Nr("\\underbar","\\underline{\\text{#1}}"),Nr("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}'),Nr("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`\u2260}}"),Nr("\\ne","\\neq"),Nr("\u2260","\\neq"),Nr("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`\u2209}}"),Nr("\u2209","\\notin"),Nr("\u2258","\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`\u2258}}"),Nr("\u2259","\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`\u2258}}"),Nr("\u225a","\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`\u225a}}"),Nr("\u225b","\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`\u225b}}"),Nr("\u225d","\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`\u225d}}"),Nr("\u225e","\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`\u225e}}"),Nr("\u225f","\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`\u225f}}"),Nr("\u27c2","\\perp"),Nr("\u203c","\\mathclose{!\\mkern-0.8mu!}"),Nr("\u220c","\\notni"),Nr("\u231c","\\ulcorner"),Nr("\u231d","\\urcorner"),Nr("\u231e","\\llcorner"),Nr("\u231f","\\lrcorner"),Nr("\xa9","\\copyright"),Nr("\xae","\\textregistered"),Nr("\ufe0f","\\textregistered"),Nr("\\ulcorner",'\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}'),Nr("\\urcorner",'\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}'),Nr("\\llcorner",'\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}'),Nr("\\lrcorner",'\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}'),Nr("\\vdots","{\\varvdots\\rule{0pt}{15pt}}"),Nr("\u22ee","\\vdots"),Nr("\\varGamma","\\mathit{\\Gamma}"),Nr("\\varDelta","\\mathit{\\Delta}"),Nr("\\varTheta","\\mathit{\\Theta}"),Nr("\\varLambda","\\mathit{\\Lambda}"),Nr("\\varXi","\\mathit{\\Xi}"),Nr("\\varPi","\\mathit{\\Pi}"),Nr("\\varSigma","\\mathit{\\Sigma}"),Nr("\\varUpsilon","\\mathit{\\Upsilon}"),Nr("\\varPhi","\\mathit{\\Phi}"),Nr("\\varPsi","\\mathit{\\Psi}"),Nr("\\varOmega","\\mathit{\\Omega}"),Nr("\\substack","\\begin{subarray}{c}#1\\end{subarray}"),Nr("\\colon","\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax"),Nr("\\boxed","\\fbox{$\\displaystyle{#1}$}"),Nr("\\iff","\\DOTSB\\;\\Longleftrightarrow\\;"),Nr("\\implies","\\DOTSB\\;\\Longrightarrow\\;"),Nr("\\impliedby","\\DOTSB\\;\\Longleftarrow\\;"),Nr("\\dddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}"),Nr("\\ddddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");const qn={",":"\\dotsc","\\not":"\\dotsb","+":"\\dotsb","=":"\\dotsb","<":"\\dotsb",">":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"};Nr("\\dots",(function(e){let t="\\dotso";const r=e.expandAfterFuture().text;return r in qn?t=qn[r]:("\\not"===r.slice(0,4)||r in se.math&&l.contains(["bin","rel"],se.math[r].group))&&(t="\\dotsb"),t}));const In={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};Nr("\\dotso",(function(e){return e.future().text in In?"\\ldots\\,":"\\ldots"})),Nr("\\dotsc",(function(e){const t=e.future().text;return t in In&&","!==t?"\\ldots\\,":"\\ldots"})),Nr("\\cdots",(function(e){return e.future().text in In?"\\@cdots\\,":"\\@cdots"})),Nr("\\dotsb","\\cdots"),Nr("\\dotsm","\\cdots"),Nr("\\dotsi","\\!\\cdots"),Nr("\\dotsx","\\ldots\\,"),Nr("\\DOTSI","\\relax"),Nr("\\DOTSB","\\relax"),Nr("\\DOTSX","\\relax"),Nr("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"),Nr("\\,","\\tmspace+{3mu}{.1667em}"),Nr("\\thinspace","\\,"),Nr("\\>","\\mskip{4mu}"),Nr("\\:","\\tmspace+{4mu}{.2222em}"),Nr("\\medspace","\\:"),Nr("\\;","\\tmspace+{5mu}{.2777em}"),Nr("\\thickspace","\\;"),Nr("\\!","\\tmspace-{3mu}{.1667em}"),Nr("\\negthinspace","\\!"),Nr("\\negmedspace","\\tmspace-{4mu}{.2222em}"),Nr("\\negthickspace","\\tmspace-{5mu}{.277em}"),Nr("\\enspace","\\kern.5em "),Nr("\\enskip","\\hskip.5em\\relax"),Nr("\\quad","\\hskip1em\\relax"),Nr("\\qquad","\\hskip2em\\relax"),Nr("\\tag","\\@ifstar\\tag@literal\\tag@paren"),Nr("\\tag@paren","\\tag@literal{({#1})}"),Nr("\\tag@literal",(e=>{if(e.macros.get("\\df@tag"))throw new n("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"})),Nr("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}"),Nr("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)"),Nr("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}"),Nr("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1"),Nr("\\newline","\\\\\\relax"),Nr("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");const Rn=F(T["Main-Regular"]["T".charCodeAt(0)][1]-.7*T["Main-Regular"]["A".charCodeAt(0)][1]);Nr("\\LaTeX","\\textrm{\\html@mathml{L\\kern-.36em\\raisebox{"+Rn+"}{\\scriptstyle A}\\kern-.15em\\TeX}{LaTeX}}"),Nr("\\KaTeX","\\textrm{\\html@mathml{K\\kern-.17em\\raisebox{"+Rn+"}{\\scriptstyle A}\\kern-.15em\\TeX}{KaTeX}}"),Nr("\\hspace","\\@ifstar\\@hspacer\\@hspace"),Nr("\\@hspace","\\hskip #1\\relax"),Nr("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax"),Nr("\\ordinarycolon",":"),Nr("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}"),Nr("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}'),Nr("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}'),Nr("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}'),Nr("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}'),Nr("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}'),Nr("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}'),Nr("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}'),Nr("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}'),Nr("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}'),Nr("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}'),Nr("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}'),Nr("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}'),Nr("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}'),Nr("\u2237","\\dblcolon"),Nr("\u2239","\\eqcolon"),Nr("\u2254","\\coloneqq"),Nr("\u2255","\\eqqcolon"),Nr("\u2a74","\\Coloneqq"),Nr("\\ratio","\\vcentcolon"),Nr("\\coloncolon","\\dblcolon"),Nr("\\colonequals","\\coloneqq"),Nr("\\coloncolonequals","\\Coloneqq"),Nr("\\equalscolon","\\eqqcolon"),Nr("\\equalscoloncolon","\\Eqqcolon"),Nr("\\colonminus","\\coloneq"),Nr("\\coloncolonminus","\\Coloneq"),Nr("\\minuscolon","\\eqcolon"),Nr("\\minuscoloncolon","\\Eqcolon"),Nr("\\coloncolonapprox","\\Colonapprox"),Nr("\\coloncolonsim","\\Colonsim"),Nr("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),Nr("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}"),Nr("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),Nr("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"),Nr("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220c}}"),Nr("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}"),Nr("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}"),Nr("\\injlim","\\DOTSB\\operatorname*{inj\\,lim}"),Nr("\\projlim","\\DOTSB\\operatorname*{proj\\,lim}"),Nr("\\varlimsup","\\DOTSB\\operatorname*{\\overline{lim}}"),Nr("\\varliminf","\\DOTSB\\operatorname*{\\underline{lim}}"),Nr("\\varinjlim","\\DOTSB\\operatorname*{\\underrightarrow{lim}}"),Nr("\\varprojlim","\\DOTSB\\operatorname*{\\underleftarrow{lim}}"),Nr("\\gvertneqq","\\html@mathml{\\@gvertneqq}{\u2269}"),Nr("\\lvertneqq","\\html@mathml{\\@lvertneqq}{\u2268}"),Nr("\\ngeqq","\\html@mathml{\\@ngeqq}{\u2271}"),Nr("\\ngeqslant","\\html@mathml{\\@ngeqslant}{\u2271}"),Nr("\\nleqq","\\html@mathml{\\@nleqq}{\u2270}"),Nr("\\nleqslant","\\html@mathml{\\@nleqslant}{\u2270}"),Nr("\\nshortmid","\\html@mathml{\\@nshortmid}{\u2224}"),Nr("\\nshortparallel","\\html@mathml{\\@nshortparallel}{\u2226}"),Nr("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{\u2288}"),Nr("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{\u2289}"),Nr("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{\u228a}"),Nr("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{\u2acb}"),Nr("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{\u228b}"),Nr("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{\u2acc}"),Nr("\\imath","\\html@mathml{\\@imath}{\u0131}"),Nr("\\jmath","\\html@mathml{\\@jmath}{\u0237}"),Nr("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27e6}}"),Nr("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27e7}}"),Nr("\u27e6","\\llbracket"),Nr("\u27e7","\\rrbracket"),Nr("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}"),Nr("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}"),Nr("\u2983","\\lBrace"),Nr("\u2984","\\rBrace"),Nr("\\minuso","\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`\u29b5}}"),Nr("\u29b5","\\minuso"),Nr("\\darr","\\downarrow"),Nr("\\dArr","\\Downarrow"),Nr("\\Darr","\\Downarrow"),Nr("\\lang","\\langle"),Nr("\\rang","\\rangle"),Nr("\\uarr","\\uparrow"),Nr("\\uArr","\\Uparrow"),Nr("\\Uarr","\\Uparrow"),Nr("\\N","\\mathbb{N}"),Nr("\\R","\\mathbb{R}"),Nr("\\Z","\\mathbb{Z}"),Nr("\\alef","\\aleph"),Nr("\\alefsym","\\aleph"),Nr("\\Alpha","\\mathrm{A}"),Nr("\\Beta","\\mathrm{B}"),Nr("\\bull","\\bullet"),Nr("\\Chi","\\mathrm{X}"),Nr("\\clubs","\\clubsuit"),Nr("\\cnums","\\mathbb{C}"),Nr("\\Complex","\\mathbb{C}"),Nr("\\Dagger","\\ddagger"),Nr("\\diamonds","\\diamondsuit"),Nr("\\empty","\\emptyset"),Nr("\\Epsilon","\\mathrm{E}"),Nr("\\Eta","\\mathrm{H}"),Nr("\\exist","\\exists"),Nr("\\harr","\\leftrightarrow"),Nr("\\hArr","\\Leftrightarrow"),Nr("\\Harr","\\Leftrightarrow"),Nr("\\hearts","\\heartsuit"),Nr("\\image","\\Im"),Nr("\\infin","\\infty"),Nr("\\Iota","\\mathrm{I}"),Nr("\\isin","\\in"),Nr("\\Kappa","\\mathrm{K}"),Nr("\\larr","\\leftarrow"),Nr("\\lArr","\\Leftarrow"),Nr("\\Larr","\\Leftarrow"),Nr("\\lrarr","\\leftrightarrow"),Nr("\\lrArr","\\Leftrightarrow"),Nr("\\Lrarr","\\Leftrightarrow"),Nr("\\Mu","\\mathrm{M}"),Nr("\\natnums","\\mathbb{N}"),Nr("\\Nu","\\mathrm{N}"),Nr("\\Omicron","\\mathrm{O}"),Nr("\\plusmn","\\pm"),Nr("\\rarr","\\rightarrow"),Nr("\\rArr","\\Rightarrow"),Nr("\\Rarr","\\Rightarrow"),Nr("\\real","\\Re"),Nr("\\reals","\\mathbb{R}"),Nr("\\Reals","\\mathbb{R}"),Nr("\\Rho","\\mathrm{P}"),Nr("\\sdot","\\cdot"),Nr("\\sect","\\S"),Nr("\\spades","\\spadesuit"),Nr("\\sub","\\subset"),Nr("\\sube","\\subseteq"),Nr("\\supe","\\supseteq"),Nr("\\Tau","\\mathrm{T}"),Nr("\\thetasym","\\vartheta"),Nr("\\weierp","\\wp"),Nr("\\Zeta","\\mathrm{Z}"),Nr("\\argmin","\\DOTSB\\operatorname*{arg\\,min}"),Nr("\\argmax","\\DOTSB\\operatorname*{arg\\,max}"),Nr("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits"),Nr("\\bra","\\mathinner{\\langle{#1}|}"),Nr("\\ket","\\mathinner{|{#1}\\rangle}"),Nr("\\braket","\\mathinner{\\langle{#1}\\rangle}"),Nr("\\Bra","\\left\\langle#1\\right|"),Nr("\\Ket","\\left|#1\\right\\rangle");const Hn=e=>t=>{const r=t.consumeArg().tokens,n=t.consumeArg().tokens,o=t.consumeArg().tokens,s=t.consumeArg().tokens,i=t.macros.get("|"),a=t.macros.get("\\|");t.macros.beginGroup();const l=t=>r=>{e&&(r.macros.set("|",i),o.length&&r.macros.set("\\|",a));let s=t;if(!t&&o.length){"|"===r.future().text&&(r.popToken(),s=!0)}return{tokens:s?o:n,numArgs:0}};t.macros.set("|",l(!1)),o.length&&t.macros.set("\\|",l(!0));const h=t.consumeArg().tokens,c=t.expandTokens([...s,...h,...r]);return t.macros.endGroup(),{tokens:c.reverse(),numArgs:0}};Nr("\\bra@ket",Hn(!1)),Nr("\\bra@set",Hn(!0)),Nr("\\Braket","\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}"),Nr("\\Set","\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}"),Nr("\\set","\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}"),Nr("\\angln","{\\angl n}"),Nr("\\blue","\\textcolor{##6495ed}{#1}"),Nr("\\orange","\\textcolor{##ffa500}{#1}"),Nr("\\pink","\\textcolor{##ff00af}{#1}"),Nr("\\red","\\textcolor{##df0030}{#1}"),Nr("\\green","\\textcolor{##28ae7b}{#1}"),Nr("\\gray","\\textcolor{gray}{#1}"),Nr("\\purple","\\textcolor{##9d38bd}{#1}"),Nr("\\blueA","\\textcolor{##ccfaff}{#1}"),Nr("\\blueB","\\textcolor{##80f6ff}{#1}"),Nr("\\blueC","\\textcolor{##63d9ea}{#1}"),Nr("\\blueD","\\textcolor{##11accd}{#1}"),Nr("\\blueE","\\textcolor{##0c7f99}{#1}"),Nr("\\tealA","\\textcolor{##94fff5}{#1}"),Nr("\\tealB","\\textcolor{##26edd5}{#1}"),Nr("\\tealC","\\textcolor{##01d1c1}{#1}"),Nr("\\tealD","\\textcolor{##01a995}{#1}"),Nr("\\tealE","\\textcolor{##208170}{#1}"),Nr("\\greenA","\\textcolor{##b6ffb0}{#1}"),Nr("\\greenB","\\textcolor{##8af281}{#1}"),Nr("\\greenC","\\textcolor{##74cf70}{#1}"),Nr("\\greenD","\\textcolor{##1fab54}{#1}"),Nr("\\greenE","\\textcolor{##0d923f}{#1}"),Nr("\\goldA","\\textcolor{##ffd0a9}{#1}"),Nr("\\goldB","\\textcolor{##ffbb71}{#1}"),Nr("\\goldC","\\textcolor{##ff9c39}{#1}"),Nr("\\goldD","\\textcolor{##e07d10}{#1}"),Nr("\\goldE","\\textcolor{##a75a05}{#1}"),Nr("\\redA","\\textcolor{##fca9a9}{#1}"),Nr("\\redB","\\textcolor{##ff8482}{#1}"),Nr("\\redC","\\textcolor{##f9685d}{#1}"),Nr("\\redD","\\textcolor{##e84d39}{#1}"),Nr("\\redE","\\textcolor{##bc2612}{#1}"),Nr("\\maroonA","\\textcolor{##ffbde0}{#1}"),Nr("\\maroonB","\\textcolor{##ff92c6}{#1}"),Nr("\\maroonC","\\textcolor{##ed5fa6}{#1}"),Nr("\\maroonD","\\textcolor{##ca337c}{#1}"),Nr("\\maroonE","\\textcolor{##9e034e}{#1}"),Nr("\\purpleA","\\textcolor{##ddd7ff}{#1}"),Nr("\\purpleB","\\textcolor{##c6b9fc}{#1}"),Nr("\\purpleC","\\textcolor{##aa87ff}{#1}"),Nr("\\purpleD","\\textcolor{##7854ab}{#1}"),Nr("\\purpleE","\\textcolor{##543b78}{#1}"),Nr("\\mintA","\\textcolor{##f5f9e8}{#1}"),Nr("\\mintB","\\textcolor{##edf2df}{#1}"),Nr("\\mintC","\\textcolor{##e0e5cc}{#1}"),Nr("\\grayA","\\textcolor{##f6f7f7}{#1}"),Nr("\\grayB","\\textcolor{##f0f1f2}{#1}"),Nr("\\grayC","\\textcolor{##e3e5e6}{#1}"),Nr("\\grayD","\\textcolor{##d6d8da}{#1}"),Nr("\\grayE","\\textcolor{##babec2}{#1}"),Nr("\\grayF","\\textcolor{##888d93}{#1}"),Nr("\\grayG","\\textcolor{##626569}{#1}"),Nr("\\grayH","\\textcolor{##3b3e40}{#1}"),Nr("\\grayI","\\textcolor{##21242c}{#1}"),Nr("\\kaBlue","\\textcolor{##314453}{#1}"),Nr("\\kaGreen","\\textcolor{##71B307}{#1}");const On={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0};class En{constructor(e,t,r){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=t,this.expansionCount=0,this.feed(e),this.macros=new Tn(Bn,t.macros),this.mode=r,this.stack=[]}feed(e){this.lexer=new An(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return 0===this.stack.length&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){let t,r,n;if(e){if(this.consumeSpaces(),"["!==this.future().text)return null;t=this.popToken(),({tokens:n,end:r}=this.consumeArg(["]"]))}else({tokens:n,start:t,end:r}=this.consumeArg());return this.pushToken(new Ir("EOF",r.loc)),this.pushTokens(n),t.range(r,"")}consumeSpaces(){for(;;){if(" "!==this.future().text)break;this.stack.pop()}}consumeArg(e){const t=[],r=e&&e.length>0;r||this.consumeSpaces();const o=this.future();let s,i=0,a=0;do{if(s=this.popToken(),t.push(s),"{"===s.text)++i;else if("}"===s.text){if(--i,-1===i)throw new n("Extra }",s)}else if("EOF"===s.text)throw new n("Unexpected end of input in a macro argument, expected '"+(e&&r?e[a]:"}")+"'",s);if(e&&r)if((0===i||1===i&&"{"===e[a])&&s.text===e[a]){if(++a,a===e.length){t.splice(-a,a);break}}else a=0}while(0!==i||r);return"{"===o.text&&"}"===t[t.length-1].text&&(t.pop(),t.shift()),t.reverse(),{tokens:t,start:o,end:s}}consumeArgs(e,t){if(t){if(t.length!==e+1)throw new n("The length of delimiters doesn't match the number of args!");const r=t[0];for(let e=0;ethis.settings.maxExpand)throw new n("Too many expansions: infinite loop or need to increase maxExpand setting")}expandOnce(e){const t=this.popToken(),r=t.text,o=t.noexpand?null:this._getExpansion(r);if(null==o||e&&o.unexpandable){if(e&&null==o&&"\\"===r[0]&&!this.isDefined(r))throw new n("Undefined control sequence: "+r);return this.pushToken(t),!1}this.countExpansion(1);let s=o.tokens;const i=this.consumeArgs(o.numArgs,o.delimiters);if(o.numArgs){s=s.slice();for(let e=s.length-1;e>=0;--e){let t=s[e];if("#"===t.text){if(0===e)throw new n("Incomplete placeholder at end of macro body",t);if(t=s[--e],"#"===t.text)s.splice(e+1,1);else{if(!/^[1-9]$/.test(t.text))throw new n("Not a valid argument number",t);s.splice(e,2,...i[+t.text-1])}}}}return this.pushTokens(s),s.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(!1===this.expandOnce()){const e=this.stack.pop();return e.treatAsRelax&&(e.text="\\relax"),e}throw new Error}expandMacro(e){return this.macros.has(e)?this.expandTokens([new Ir(e)]):void 0}expandTokens(e){const t=[],r=this.stack.length;for(this.pushTokens(e);this.stack.length>r;)if(!1===this.expandOnce(!0)){const e=this.stack.pop();e.treatAsRelax&&(e.noexpand=!1,e.treatAsRelax=!1),t.push(e)}return this.countExpansion(t.length),t}expandMacroAsText(e){const t=this.expandMacro(e);return t?t.map((e=>e.text)).join(""):t}_getExpansion(e){const t=this.macros.get(e);if(null==t)return t;if(1===e.length){const t=this.lexer.catcodes[e];if(null!=t&&13!==t)return}const r="function"==typeof t?t(this):t;if("string"==typeof r){let e=0;if(-1!==r.indexOf("#")){const t=r.replace(/##/g,"");for(;-1!==t.indexOf("#"+(e+1));)++e}const t=new An(r,this.settings),n=[];let o=t.lex();for(;"EOF"!==o.text;)n.push(o),o=t.lex();n.reverse();return{tokens:n,numArgs:e}}return r}isDefined(e){return this.macros.has(e)||wn.hasOwnProperty(e)||se.math.hasOwnProperty(e)||se.text.hasOwnProperty(e)||On.hasOwnProperty(e)}isExpandable(e){const t=this.macros.get(e);return null!=t?"string"==typeof t||"function"==typeof t||!t.unexpandable:wn.hasOwnProperty(e)&&!wn[e].primitive}}const Ln=/^[\u208a\u208b\u208c\u208d\u208e\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u2090\u2091\u2095\u1d62\u2c7c\u2096\u2097\u2098\u2099\u2092\u209a\u1d63\u209b\u209c\u1d64\u1d65\u2093\u1d66\u1d67\u1d68\u1d69\u1d6a]/,Dn=Object.freeze({"\u208a":"+","\u208b":"-","\u208c":"=","\u208d":"(","\u208e":")","\u2080":"0","\u2081":"1","\u2082":"2","\u2083":"3","\u2084":"4","\u2085":"5","\u2086":"6","\u2087":"7","\u2088":"8","\u2089":"9","\u2090":"a","\u2091":"e","\u2095":"h","\u1d62":"i","\u2c7c":"j","\u2096":"k","\u2097":"l","\u2098":"m","\u2099":"n","\u2092":"o","\u209a":"p","\u1d63":"r","\u209b":"s","\u209c":"t","\u1d64":"u","\u1d65":"v","\u2093":"x","\u1d66":"\u03b2","\u1d67":"\u03b3","\u1d68":"\u03c1","\u1d69":"\u03d5","\u1d6a":"\u03c7","\u207a":"+","\u207b":"-","\u207c":"=","\u207d":"(","\u207e":")","\u2070":"0","\xb9":"1","\xb2":"2","\xb3":"3","\u2074":"4","\u2075":"5","\u2076":"6","\u2077":"7","\u2078":"8","\u2079":"9","\u1d2c":"A","\u1d2e":"B","\u1d30":"D","\u1d31":"E","\u1d33":"G","\u1d34":"H","\u1d35":"I","\u1d36":"J","\u1d37":"K","\u1d38":"L","\u1d39":"M","\u1d3a":"N","\u1d3c":"O","\u1d3e":"P","\u1d3f":"R","\u1d40":"T","\u1d41":"U","\u2c7d":"V","\u1d42":"W","\u1d43":"a","\u1d47":"b","\u1d9c":"c","\u1d48":"d","\u1d49":"e","\u1da0":"f","\u1d4d":"g","\u02b0":"h","\u2071":"i","\u02b2":"j","\u1d4f":"k","\u02e1":"l","\u1d50":"m","\u207f":"n","\u1d52":"o","\u1d56":"p","\u02b3":"r","\u02e2":"s","\u1d57":"t","\u1d58":"u","\u1d5b":"v","\u02b7":"w","\u02e3":"x","\u02b8":"y","\u1dbb":"z","\u1d5d":"\u03b2","\u1d5e":"\u03b3","\u1d5f":"\u03b4","\u1d60":"\u03d5","\u1d61":"\u03c7","\u1dbf":"\u03b8"}),Vn={"\u0301":{text:"\\'",math:"\\acute"},"\u0300":{text:"\\`",math:"\\grave"},"\u0308":{text:'\\"',math:"\\ddot"},"\u0303":{text:"\\~",math:"\\tilde"},"\u0304":{text:"\\=",math:"\\bar"},"\u0306":{text:"\\u",math:"\\breve"},"\u030c":{text:"\\v",math:"\\check"},"\u0302":{text:"\\^",math:"\\hat"},"\u0307":{text:"\\.",math:"\\dot"},"\u030a":{text:"\\r",math:"\\mathring"},"\u030b":{text:"\\H"},"\u0327":{text:"\\c"}},Pn={"\xe1":"a\u0301","\xe0":"a\u0300","\xe4":"a\u0308","\u01df":"a\u0308\u0304","\xe3":"a\u0303","\u0101":"a\u0304","\u0103":"a\u0306","\u1eaf":"a\u0306\u0301","\u1eb1":"a\u0306\u0300","\u1eb5":"a\u0306\u0303","\u01ce":"a\u030c","\xe2":"a\u0302","\u1ea5":"a\u0302\u0301","\u1ea7":"a\u0302\u0300","\u1eab":"a\u0302\u0303","\u0227":"a\u0307","\u01e1":"a\u0307\u0304","\xe5":"a\u030a","\u01fb":"a\u030a\u0301","\u1e03":"b\u0307","\u0107":"c\u0301","\u1e09":"c\u0327\u0301","\u010d":"c\u030c","\u0109":"c\u0302","\u010b":"c\u0307","\xe7":"c\u0327","\u010f":"d\u030c","\u1e0b":"d\u0307","\u1e11":"d\u0327","\xe9":"e\u0301","\xe8":"e\u0300","\xeb":"e\u0308","\u1ebd":"e\u0303","\u0113":"e\u0304","\u1e17":"e\u0304\u0301","\u1e15":"e\u0304\u0300","\u0115":"e\u0306","\u1e1d":"e\u0327\u0306","\u011b":"e\u030c","\xea":"e\u0302","\u1ebf":"e\u0302\u0301","\u1ec1":"e\u0302\u0300","\u1ec5":"e\u0302\u0303","\u0117":"e\u0307","\u0229":"e\u0327","\u1e1f":"f\u0307","\u01f5":"g\u0301","\u1e21":"g\u0304","\u011f":"g\u0306","\u01e7":"g\u030c","\u011d":"g\u0302","\u0121":"g\u0307","\u0123":"g\u0327","\u1e27":"h\u0308","\u021f":"h\u030c","\u0125":"h\u0302","\u1e23":"h\u0307","\u1e29":"h\u0327","\xed":"i\u0301","\xec":"i\u0300","\xef":"i\u0308","\u1e2f":"i\u0308\u0301","\u0129":"i\u0303","\u012b":"i\u0304","\u012d":"i\u0306","\u01d0":"i\u030c","\xee":"i\u0302","\u01f0":"j\u030c","\u0135":"j\u0302","\u1e31":"k\u0301","\u01e9":"k\u030c","\u0137":"k\u0327","\u013a":"l\u0301","\u013e":"l\u030c","\u013c":"l\u0327","\u1e3f":"m\u0301","\u1e41":"m\u0307","\u0144":"n\u0301","\u01f9":"n\u0300","\xf1":"n\u0303","\u0148":"n\u030c","\u1e45":"n\u0307","\u0146":"n\u0327","\xf3":"o\u0301","\xf2":"o\u0300","\xf6":"o\u0308","\u022b":"o\u0308\u0304","\xf5":"o\u0303","\u1e4d":"o\u0303\u0301","\u1e4f":"o\u0303\u0308","\u022d":"o\u0303\u0304","\u014d":"o\u0304","\u1e53":"o\u0304\u0301","\u1e51":"o\u0304\u0300","\u014f":"o\u0306","\u01d2":"o\u030c","\xf4":"o\u0302","\u1ed1":"o\u0302\u0301","\u1ed3":"o\u0302\u0300","\u1ed7":"o\u0302\u0303","\u022f":"o\u0307","\u0231":"o\u0307\u0304","\u0151":"o\u030b","\u1e55":"p\u0301","\u1e57":"p\u0307","\u0155":"r\u0301","\u0159":"r\u030c","\u1e59":"r\u0307","\u0157":"r\u0327","\u015b":"s\u0301","\u1e65":"s\u0301\u0307","\u0161":"s\u030c","\u1e67":"s\u030c\u0307","\u015d":"s\u0302","\u1e61":"s\u0307","\u015f":"s\u0327","\u1e97":"t\u0308","\u0165":"t\u030c","\u1e6b":"t\u0307","\u0163":"t\u0327","\xfa":"u\u0301","\xf9":"u\u0300","\xfc":"u\u0308","\u01d8":"u\u0308\u0301","\u01dc":"u\u0308\u0300","\u01d6":"u\u0308\u0304","\u01da":"u\u0308\u030c","\u0169":"u\u0303","\u1e79":"u\u0303\u0301","\u016b":"u\u0304","\u1e7b":"u\u0304\u0308","\u016d":"u\u0306","\u01d4":"u\u030c","\xfb":"u\u0302","\u016f":"u\u030a","\u0171":"u\u030b","\u1e7d":"v\u0303","\u1e83":"w\u0301","\u1e81":"w\u0300","\u1e85":"w\u0308","\u0175":"w\u0302","\u1e87":"w\u0307","\u1e98":"w\u030a","\u1e8d":"x\u0308","\u1e8b":"x\u0307","\xfd":"y\u0301","\u1ef3":"y\u0300","\xff":"y\u0308","\u1ef9":"y\u0303","\u0233":"y\u0304","\u0177":"y\u0302","\u1e8f":"y\u0307","\u1e99":"y\u030a","\u017a":"z\u0301","\u017e":"z\u030c","\u1e91":"z\u0302","\u017c":"z\u0307","\xc1":"A\u0301","\xc0":"A\u0300","\xc4":"A\u0308","\u01de":"A\u0308\u0304","\xc3":"A\u0303","\u0100":"A\u0304","\u0102":"A\u0306","\u1eae":"A\u0306\u0301","\u1eb0":"A\u0306\u0300","\u1eb4":"A\u0306\u0303","\u01cd":"A\u030c","\xc2":"A\u0302","\u1ea4":"A\u0302\u0301","\u1ea6":"A\u0302\u0300","\u1eaa":"A\u0302\u0303","\u0226":"A\u0307","\u01e0":"A\u0307\u0304","\xc5":"A\u030a","\u01fa":"A\u030a\u0301","\u1e02":"B\u0307","\u0106":"C\u0301","\u1e08":"C\u0327\u0301","\u010c":"C\u030c","\u0108":"C\u0302","\u010a":"C\u0307","\xc7":"C\u0327","\u010e":"D\u030c","\u1e0a":"D\u0307","\u1e10":"D\u0327","\xc9":"E\u0301","\xc8":"E\u0300","\xcb":"E\u0308","\u1ebc":"E\u0303","\u0112":"E\u0304","\u1e16":"E\u0304\u0301","\u1e14":"E\u0304\u0300","\u0114":"E\u0306","\u1e1c":"E\u0327\u0306","\u011a":"E\u030c","\xca":"E\u0302","\u1ebe":"E\u0302\u0301","\u1ec0":"E\u0302\u0300","\u1ec4":"E\u0302\u0303","\u0116":"E\u0307","\u0228":"E\u0327","\u1e1e":"F\u0307","\u01f4":"G\u0301","\u1e20":"G\u0304","\u011e":"G\u0306","\u01e6":"G\u030c","\u011c":"G\u0302","\u0120":"G\u0307","\u0122":"G\u0327","\u1e26":"H\u0308","\u021e":"H\u030c","\u0124":"H\u0302","\u1e22":"H\u0307","\u1e28":"H\u0327","\xcd":"I\u0301","\xcc":"I\u0300","\xcf":"I\u0308","\u1e2e":"I\u0308\u0301","\u0128":"I\u0303","\u012a":"I\u0304","\u012c":"I\u0306","\u01cf":"I\u030c","\xce":"I\u0302","\u0130":"I\u0307","\u0134":"J\u0302","\u1e30":"K\u0301","\u01e8":"K\u030c","\u0136":"K\u0327","\u0139":"L\u0301","\u013d":"L\u030c","\u013b":"L\u0327","\u1e3e":"M\u0301","\u1e40":"M\u0307","\u0143":"N\u0301","\u01f8":"N\u0300","\xd1":"N\u0303","\u0147":"N\u030c","\u1e44":"N\u0307","\u0145":"N\u0327","\xd3":"O\u0301","\xd2":"O\u0300","\xd6":"O\u0308","\u022a":"O\u0308\u0304","\xd5":"O\u0303","\u1e4c":"O\u0303\u0301","\u1e4e":"O\u0303\u0308","\u022c":"O\u0303\u0304","\u014c":"O\u0304","\u1e52":"O\u0304\u0301","\u1e50":"O\u0304\u0300","\u014e":"O\u0306","\u01d1":"O\u030c","\xd4":"O\u0302","\u1ed0":"O\u0302\u0301","\u1ed2":"O\u0302\u0300","\u1ed6":"O\u0302\u0303","\u022e":"O\u0307","\u0230":"O\u0307\u0304","\u0150":"O\u030b","\u1e54":"P\u0301","\u1e56":"P\u0307","\u0154":"R\u0301","\u0158":"R\u030c","\u1e58":"R\u0307","\u0156":"R\u0327","\u015a":"S\u0301","\u1e64":"S\u0301\u0307","\u0160":"S\u030c","\u1e66":"S\u030c\u0307","\u015c":"S\u0302","\u1e60":"S\u0307","\u015e":"S\u0327","\u0164":"T\u030c","\u1e6a":"T\u0307","\u0162":"T\u0327","\xda":"U\u0301","\xd9":"U\u0300","\xdc":"U\u0308","\u01d7":"U\u0308\u0301","\u01db":"U\u0308\u0300","\u01d5":"U\u0308\u0304","\u01d9":"U\u0308\u030c","\u0168":"U\u0303","\u1e78":"U\u0303\u0301","\u016a":"U\u0304","\u1e7a":"U\u0304\u0308","\u016c":"U\u0306","\u01d3":"U\u030c","\xdb":"U\u0302","\u016e":"U\u030a","\u0170":"U\u030b","\u1e7c":"V\u0303","\u1e82":"W\u0301","\u1e80":"W\u0300","\u1e84":"W\u0308","\u0174":"W\u0302","\u1e86":"W\u0307","\u1e8c":"X\u0308","\u1e8a":"X\u0307","\xdd":"Y\u0301","\u1ef2":"Y\u0300","\u0178":"Y\u0308","\u1ef8":"Y\u0303","\u0232":"Y\u0304","\u0176":"Y\u0302","\u1e8e":"Y\u0307","\u0179":"Z\u0301","\u017d":"Z\u030c","\u1e90":"Z\u0302","\u017b":"Z\u0307","\u03ac":"\u03b1\u0301","\u1f70":"\u03b1\u0300","\u1fb1":"\u03b1\u0304","\u1fb0":"\u03b1\u0306","\u03ad":"\u03b5\u0301","\u1f72":"\u03b5\u0300","\u03ae":"\u03b7\u0301","\u1f74":"\u03b7\u0300","\u03af":"\u03b9\u0301","\u1f76":"\u03b9\u0300","\u03ca":"\u03b9\u0308","\u0390":"\u03b9\u0308\u0301","\u1fd2":"\u03b9\u0308\u0300","\u1fd1":"\u03b9\u0304","\u1fd0":"\u03b9\u0306","\u03cc":"\u03bf\u0301","\u1f78":"\u03bf\u0300","\u03cd":"\u03c5\u0301","\u1f7a":"\u03c5\u0300","\u03cb":"\u03c5\u0308","\u03b0":"\u03c5\u0308\u0301","\u1fe2":"\u03c5\u0308\u0300","\u1fe1":"\u03c5\u0304","\u1fe0":"\u03c5\u0306","\u03ce":"\u03c9\u0301","\u1f7c":"\u03c9\u0300","\u038e":"\u03a5\u0301","\u1fea":"\u03a5\u0300","\u03ab":"\u03a5\u0308","\u1fe9":"\u03a5\u0304","\u1fe8":"\u03a5\u0306","\u038f":"\u03a9\u0301","\u1ffa":"\u03a9\u0300"};class Fn{constructor(e,t){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new En(e,t,this.mode),this.settings=t,this.leftrightDepth=0}expect(e,t){if(void 0===t&&(t=!0),this.fetch().text!==e)throw new n("Expected '"+e+"', got '"+this.fetch().text+"'",this.fetch());t&&this.consume()}consume(){this.nextToken=null}fetch(){return null==this.nextToken&&(this.nextToken=this.gullet.expandNextToken()),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor");try{const e=this.parseExpression(!1);return this.expect("EOF"),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){const t=this.nextToken;this.consume(),this.gullet.pushToken(new Ir("}")),this.gullet.pushTokens(e);const r=this.parseExpression(!1);return this.expect("}"),this.nextToken=t,r}parseExpression(e,t){const r=[];for(;;){"math"===this.mode&&this.consumeSpaces();const n=this.fetch();if(-1!==Fn.endOfExpression.indexOf(n.text))break;if(t&&n.text===t)break;if(e&&wn[n.text]&&wn[n.text].infix)break;const o=this.parseAtom(t);if(!o)break;"internal"!==o.type&&r.push(o)}return"text"===this.mode&&this.formLigatures(r),this.handleInfixNodes(r)}handleInfixNodes(e){let t,r=-1;for(let o=0;o=0&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+t[0]+'" used in math mode',e);const r=se[this.mode][t].group,n=qr.range(e);let s;if(re.hasOwnProperty(r)){const e=r;s={type:"atom",mode:this.mode,family:e,loc:n,text:t}}else s={type:r,mode:this.mode,loc:n,text:t};o=s}else{if(!(t.charCodeAt(0)>=128))return null;this.settings.strict&&(S(t.charCodeAt(0))?"math"===this.mode&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+t[0]+'" used in math mode',e):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+t[0]+'" ('+t.charCodeAt(0)+")",e)),o={type:"textord",mode:"text",loc:qr.range(e),text:t}}if(this.consume(),r)for(let t=0;t, - #[allow(dead_code)] - path: PathBuf, -} - -fn sessions() -> &'static Mutex>> { - static S: OnceLock>>> = OnceLock::new(); - S.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn new_id() -> String { - use std::time::{SystemTime, UNIX_EPOCH}; - let t = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - format!("dbg-{t}") -} - -fn parse_breakpoints(v: &serde_json::Value) -> HashSet { - v.get("breakpoints") - .and_then(|b| b.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|x| x.as_u64().map(|n| n as u32)) - .collect() - }) - .unwrap_or_default() -} - -pub fn api_debug_start(root: &Path, body: &str) -> serde_json::Value { - let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); - let rel = v.get("path").and_then(|p| p.as_str()).unwrap_or(""); - if rel.is_empty() { - return serde_json::json!({ "ok": false, "error": "missing path" }); - } - let abs = root.join(rel.replace('/', std::path::MAIN_SEPARATOR_STR)); - if !abs.is_file() { - return serde_json::json!({ "ok": false, "error": format!("file not found: {rel}") }); - } - - let bps = parse_breakpoints(&v); - let stdin_raw = v.get("stdin").and_then(|s| s.as_str()).unwrap_or(""); - let stdin_lines = split_stdin_text(stdin_raw); - - let ctrl = DebugController::new(bps.clone()); - if bps.is_empty() { - // No breakpoints: pause on the first statement so Debug is always useful. - ctrl.request_step(); - } - ctrl.set_running(); - let id = new_id(); - let session = Arc::new(Session { - ctrl: ctrl.clone(), - path: abs.clone(), - }); - sessions().lock().unwrap().insert(id.clone(), session); - - let opts = RunOptions { - sleep_limit_ms: Some(0), - fs_root: Some(root.to_path_buf()), - ..RunOptions::default() - }; - let path_for_thread = abs; - let root_for_thread = root.to_path_buf(); - let ctrl_t = ctrl.clone(); - thread::spawn(move || { - let source = match std::fs::read_to_string(&path_for_thread) { - Ok(s) => s, - Err(e) => { - ctrl_t.set_done(false, String::new(), format!("read: {e}")); - return; - } - }; - let stdin = effective_stdin(&source, &stdin_lines); - let module = match load_module(&path_for_thread) { - Ok(m) => m, - Err(e) => { - ctrl_t.set_done(false, String::new(), e.to_string()); - return; - } - }; - let mut host = HostContext::for_capture(Some(&path_for_thread), opts.host_caps()); - host.fs_root = Some(root_for_thread); - host.entry_metadata = module.metadata.clone(); - if let Some(lim) = opts.sleep_limit_ms { - host.sleep_limit_ms = Some(lim); - } - let mut interp = Interpreter::with_capture(Some(&path_for_thread), false) - .with_stdin(stdin) - .with_host(host) - .with_debug(ctrl_t.clone()); - match interp.run_module(&module) { - Ok(_) => { - ctrl_t.set_done(true, interp.captured_stdout.clone(), String::new()); - } - Err(e) => { - let msg = e.to_string(); - if msg.contains("debug stopped") { - ctrl_t.set_done(true, interp.captured_stdout.clone(), "stopped".into()); - } else { - ctrl_t.set_done(false, interp.captured_stdout.clone(), msg); - } - } - } - }); - - let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(30)); - wrap_ok(&id, &snap) -} - -pub fn api_debug_action(body: &str, action: DebugAction) -> serde_json::Value { - let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); - let id = v.get("session").and_then(|s| s.as_str()).unwrap_or(""); - let sessions = sessions().lock().unwrap(); - let Some(sess) = sessions.get(id) else { - return serde_json::json!({ "ok": false, "error": "unknown session" }); - }; - let ctrl = sess.ctrl.clone(); - drop(sessions); - - if v.get("breakpoints").map(|b| b.is_array()).unwrap_or(false) { - ctrl.set_breakpoints(parse_breakpoints(&v)); - } - - match ctrl.snapshot() { - DebugSnapshot::Done { .. } => return wrap_ok(id, &ctrl.snapshot()), - DebugSnapshot::Paused(_) => {} - other => { - return serde_json::json!({ - "ok": false, - "error": format!("session not paused (status={})", status_name(&other)), - "session": id, - }); - } - } - - ctrl.send_action(action); - let snap = ctrl.wait_until_paused_or_done(Duration::from_secs(30)); - wrap_ok(id, &snap) -} - -pub fn api_debug_stop(body: &str) -> serde_json::Value { - let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); - let id = v.get("session").and_then(|s| s.as_str()).unwrap_or(""); - let mut map = sessions().lock().unwrap(); - if let Some(sess) = map.remove(id) { - sess.ctrl.send_action(DebugAction::Stop); - return serde_json::json!({ "ok": true, "status": "stopped", "session": id }); - } - serde_json::json!({ "ok": false, "error": "unknown session" }) -} - -pub fn api_debug_set_breakpoints(body: &str) -> serde_json::Value { - let v: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null); - let id = v.get("session").and_then(|s| s.as_str()).unwrap_or(""); - let bps = parse_breakpoints(&v); - let map = sessions().lock().unwrap(); - let Some(sess) = map.get(id) else { - return serde_json::json!({ "ok": false, "error": "unknown session" }); - }; - sess.ctrl.set_breakpoints(bps.clone()); - let mut lines: Vec = bps.into_iter().collect(); - lines.sort_unstable(); - serde_json::json!({ - "ok": true, - "session": id, - "breakpoints": lines, - }) -} - -fn wrap_ok(id: &str, snap: &DebugSnapshot) -> serde_json::Value { - let mut out = snapshot_json(snap); - if let Some(obj) = out.as_object_mut() { - obj.insert("ok".into(), serde_json::Value::Bool(true)); - obj.insert("session".into(), serde_json::Value::String(id.to_string())); - } - out -} - -fn status_name(s: &DebugSnapshot) -> &'static str { - match s { - DebugSnapshot::Idle => "idle", - DebugSnapshot::Running => "running", - DebugSnapshot::Paused(_) => "paused", - DebugSnapshot::Done { .. } => "done", - } -} diff --git a/src/view/debug_page.rs b/src/view/debug_page.rs deleted file mode 100755 index bdb5c7c..0000000 --- a/src/view/debug_page.rs +++ /dev/null @@ -1,973 +0,0 @@ -//! Dedicated `marqdo debug` UI — VS Code / Chrome DevTools–style layout. -//! -//! Toolbar · Structure (breakpoints) · Variables / Breakpoints / Frame · Console - -use std::path::{Path, PathBuf}; -use super::html::escape_js_string; - -use crate::view::html::{escape, nav_html, LinkMode}; -use crate::view::render::{render_function_outline, render_module_structure_mode, StructureMode}; - -pub struct DebugPageModel { - #[allow(dead_code)] - pub rel_path: String, - #[allow(dead_code)] - pub source: String, - pub structure_html: String, - pub outline_html: String, - pub stdin_preset: String, - pub has_input: bool, -} - -pub fn build_debug_model(abs: &Path, rel: &str, source: &str) -> DebugPageModel { - let _ = abs; - let (structure, outline, has_input) = match crate::load::parse_source_auto(source) { - Ok(module) => ( - render_module_structure_mode(&module, source, StructureMode::Debug), - render_function_outline(&module), - !crate::view::render::collect_input_prompts(&module).is_empty(), - ), - Err(e) => ( - format!( - "
      parse error: {}
      ", - escape(&e.to_string()) - ), - String::new(), - false, - ), - }; - let stdin_preset = crate::input_feed::effective_stdin(source, &[]).join("\n"); - DebugPageModel { - rel_path: rel.to_string(), - source: source.to_string(), - structure_html: structure, - outline_html: outline, - stdin_preset, - has_input, - } -} - -pub fn page_debug(files: &[PathBuf], rel: &str, vm: &DebugPageModel) -> String { - let nav = nav_html(files, Some(rel), &LinkMode::Live); - let title = Path::new(rel) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(rel) - .trim_end_matches(".mq.md"); - - let stdin_box = if vm.has_input { - format!( - r#""#, - stdin = escape(&vm.stdin_preset), - ) - } else { - String::new() - }; - - let outline = if vm.outline_html.is_empty() { - String::new() - } else { - format!(r#"
      {}
      "#, vm.outline_html) - }; - - let body = format!( - r#" - -
      -
      - - marqdo - debug -
      -
      - - - - -
      -
      Idle — set breakpoints, then Start · drag edges to resize panes
      -
      -
      -
      - -
      -
      -
      -

      {title}

      -

      {rel}

      - {stdin} -
      -
      -
      -

      Structure gutter = breakpoint

      -
      {structure}
      -
      - {outline} -
      -
      -
      - -
      -
      -
      -

      Debug Console

      -
      (idle)
      -
      -
      -"#, - path_js = escape_js_string(rel), - nav = nav, - title = escape(title), - rel = escape(rel), - stdin = stdin_box, - structure = vm.structure_html, - outline = outline, - ); - - layout_debug(rel, &body) -} - - -fn layout_debug(title: &str, main: &str) -> String { - format!( - r##" - - - - -debug · {title} · marqdo - - - - - - -{main} - - - -"##, - title = escape(title), - css = debug_css(), - main = main, - js = debug_js(), - ) -} - -fn debug_css() -> &'static str { - r#" -:root { - --bg: #1e1e1e; - --panel: #252526; - --ink: #d4d4d4; - --muted: #858585; - --line: #3c3c3c; - --accent: #0e639c; - --accent-hover: #1177bb; - --current: #264f78; - --bp: #e51400; - --ok: #4ec9b0; - --nav-w: 168px; - --side-w: 220px; - --console-h: 120px; - --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; -} -* { box-sizing: border-box; } -html, body { margin: 0; height: 100%; } -.dbg-body { - font-family: var(--sans); - font-size: 12.5px; - color: var(--ink); - background: var(--bg); - display: flex; - flex-direction: column; - height: 100vh; - overflow: hidden; -} -.dbg-toolbar { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.5rem 0.85rem; - padding: 0.35rem 0.65rem; - background: #333; - border-bottom: 1px solid #000; - flex-shrink: 0; -} -.dbg-brand { display: flex; align-items: center; gap: 0.4rem; } -.dbg-logo { display: block; border-radius: 3px; flex-shrink: 0; } -.dbg-mark { font-weight: 700; letter-spacing: -0.02em; color: #fff; font-size: 0.9rem; } -.dbg-mode { - font-size: 0.65rem; - text-transform: uppercase; - letter-spacing: 0.08em; - color: var(--ok); - font-weight: 600; -} -.dbg-actions { display: flex; gap: 0.3rem; } -.dbg-btn { - font: 0.72rem/1 var(--sans); - padding: 0.32rem 0.6rem; - border: 1px solid #555; - border-radius: 3px; - background: #3c3c3c; - color: #fff; - cursor: pointer; -} -.dbg-btn:hover:not(:disabled) { background: #505050; } -.dbg-btn:disabled { opacity: 0.4; cursor: default; } -.dbg-btn.primary { background: var(--accent); border-color: var(--accent); } -.dbg-btn.primary:hover:not(:disabled) { background: var(--accent-hover); } -.dbg-btn.danger { background: #5a1d1d; border-color: #7a2d2d; } -.dbg-status { color: var(--muted); font-family: var(--mono); font-size: 0.7rem; flex: 1; min-width: 8rem; } -.dbg-work { - flex: 1; - display: flex; - flex-direction: column; - min-height: 0; - overflow: hidden; -} -.dbg-shell { - flex: 1; - display: flex; - min-height: 0; - overflow: hidden; -} -.dbg-nav, .dbg-side { - flex-shrink: 0; - background: var(--panel); - overflow: auto; - padding: 0.35rem 0.3rem 0.6rem; -} -.dbg-nav { width: var(--nav-w); border-right: none; } -.dbg-side { width: var(--side-w); } -.dbg-split-v { - flex: 0 0 4px; - background: var(--line); - cursor: col-resize; - position: relative; - z-index: 2; -} -.dbg-split-v:hover, .dbg-split-v.dragging { background: var(--accent); } -.dbg-split-h { - flex: 0 0 5px; - background: var(--line); - cursor: row-resize; - position: relative; - z-index: 2; -} -.dbg-split-h:hover, .dbg-split-h.dragging { background: var(--accent); } -.dbg-nav h2, .dbg-side h2, .dbg-structure-pane h2, .dbg-console h2 { - margin: 0.2rem 0.35rem 0.3rem; - font-size: 0.6rem; - text-transform: uppercase; - letter-spacing: 0.08em; - color: var(--muted); - font-weight: 600; -} -.dbg-nav ul { list-style: none; margin: 0; padding: 0; } -.dbg-nav a.file { - display: block; - padding: 0.22rem 0.4rem; - border-radius: 3px; - color: var(--ink); - text-decoration: none; - font-family: var(--mono); - font-size: 0.68rem; - line-height: 1.25; -} -.dbg-nav a.file:hover { background: #2a2d2e; } -.dbg-nav a.file.active { background: #094771; color: #fff; } -.dbg-nav .folder { margin: 0.2rem 0; } -.dbg-nav .folder > summary { - color: var(--muted); - cursor: pointer; - font-size: 0.68rem; - padding: 0.15rem 0.35rem; - line-height: 1.25; -} -.dbg-main { - flex: 1; - display: flex; - flex-direction: column; - min-width: 0; - overflow: hidden; - background: var(--bg); -} -.dbg-main-head { - padding: 0.4rem 0.75rem 0.3rem; - border-bottom: 1px solid var(--line); - flex-shrink: 0; -} -.dbg-main-head h1 { margin: 0; font-size: 0.95rem; font-weight: 600; color: #fff; line-height: 1.2; } -.dbg-main-head .meta { - margin: 0.1rem 0 0; - color: var(--muted); - font-family: var(--mono); - font-size: 0.65rem; - line-height: 1.2; -} -.dbg-stdin-label { - display: block; - margin-top: 0.3rem; - color: var(--muted); - font-size: 0.65rem; -} -.dbg-stdin-label textarea { - display: block; - width: 100%; - margin-top: 0.15rem; - background: #1e1e1e; - border: 1px solid var(--line); - color: var(--ink); - font-family: var(--mono); - font-size: 0.7rem; - border-radius: 3px; - padding: 0.25rem 0.35rem; - line-height: 1.3; - max-height: 4rem; -} -.dbg-center { - flex: 1; - display: flex; - min-height: 0; - overflow: hidden; -} -.dbg-structure-pane { - flex: 1; - overflow: auto; - padding: 0.35rem 0.55rem 0.6rem; - min-width: 0; -} -.dbg-outline { - flex: 0 0 9.5rem; - border-left: 1px solid var(--line); - overflow: auto; - padding: 0.35rem; - background: var(--panel); -} -.outline-panel { background: transparent; border: none; padding: 0; box-shadow: none; } -.fn-search { - width: 100%; - margin-bottom: 0.3rem; - padding: 0.25rem 0.35rem; - background: #1e1e1e; - border: 1px solid var(--line); - color: var(--ink); - border-radius: 3px; - font-size: 0.68rem; -} -.outline-tree, .outline-tree ul { list-style: none; margin: 0; padding: 0; } -.outline-tree ul { padding-left: 0.5rem; border-left: 1px solid var(--line); } -.outline-item { margin: 0.05rem 0; font-size: 0.68rem; line-height: 1.25; } -.outline-item.hidden { display: none; } -.outline-item a { color: #9cdcfe; text-decoration: none; font-family: var(--mono); } -.outline-item .ol-meta { color: var(--muted); margin-left: 0.15rem; font-size: 0.6rem; } - -/* Compact structure — dense like an editor, not a docs card list */ -.structure.debug-surface { - background: #1e1e1e; - border: 1px solid var(--line); - border-radius: 3px; - padding: 0; - line-height: 1.25; -} -.structure.debug-surface .card { - border: none; - border-bottom: 1px solid #2d2d2d; - border-radius: 0; - padding: 0.18rem 0.45rem; - margin: 0; - background: transparent; - color: var(--ink); - line-height: 1.25; -} -.structure.debug-surface .fun-card, -.structure.debug-surface .call-card, -.structure.debug-surface .branch-card, -.structure.debug-surface .loop-card, -.structure.debug-surface .ret-card { - border-left: 2px solid #555; - padding-left: 0.4rem; -} -.structure.debug-surface .badge { - background: transparent; - border: none; - color: #808080; - font-size: 0.58rem; - padding: 0 0.2rem 0 0; - margin-right: 0.25rem; -} -.structure.debug-surface .chip { - background: #2d2d2d; - color: #9cdcfe; - font-size: 0.62rem; - padding: 0.05rem 0.28rem; - margin: 0.05rem 0.1rem 0 0; - border-radius: 3px; -} -.structure.debug-surface .params { margin: 0.1rem 0 0; } -.structure.debug-surface code.expr { - color: #dcdcaa; - font-family: var(--mono); - font-size: 0.72rem; - line-height: 1.25; -} -.structure.debug-surface strong { font-size: 0.78rem; font-weight: 600; color: #fff; } -.structure.debug-surface .comment-card { - border-left: 2px solid #3a4a30; - background: #1a1f18; - padding: 0.1rem 0.4rem; -} -.structure.debug-surface .comment-card .badge { display: none; } -.structure.debug-surface .comment-text { - color: #6a9955; - font-size: 0.68rem; - line-height: 1.3; - max-height: 2.6em; - overflow: hidden; - display: -webkit-box; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; -} -.structure.debug-surface .comment-text p { - margin: 0; - display: inline; -} -.structure.debug-surface .comment-text p + p::before { content: " · "; color: #4a6a40; } -.structure.debug-surface .nested { - margin: 0.08rem 0 0.08rem 0.15rem; - padding-left: 0.4rem; - border-left: 1px solid #333; -} -.structure.debug-surface .arm { - margin: 0.12rem 0; - padding: 0.15rem 0.35rem; - background: #252525; - border-radius: 2px; -} -/* Foreign code cards (Run → /api/foreign-run) */ -.structure.debug-surface .code-card { - padding: 0 !important; - overflow: hidden; -} -.structure.debug-surface .code-head { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.35rem 0.5rem; - padding: 0.3rem 0.45rem; - border-bottom: 1px solid #2d2d2d; - background: #252526; -} -.structure.debug-surface .code-lang { - font: 0.62rem/1 var(--mono); - color: var(--muted); - text-transform: lowercase; -} -.structure.debug-surface .code-actions { - margin-left: auto; - display: flex; - align-items: center; - gap: 0.3rem; -} -.structure.debug-surface .code-cmd { - min-width: 6rem; - max-width: 12rem; - padding: 0.2rem 0.35rem; - border: 1px solid var(--line); - border-radius: 3px; - font: 0.68rem/1.2 var(--mono); - color: var(--ink); - background: #1e1e1e; -} -.structure.debug-surface .code-run { - padding: 0.2rem 0.55rem; - border: none; - border-radius: 3px; - background: var(--accent); - color: #fff; - font: 0.68rem/1.2 var(--sans); - font-weight: 600; - cursor: pointer; -} -.structure.debug-surface .code-run:disabled { opacity: 0.45; cursor: not-allowed; } -.structure.debug-surface .code-body { - margin: 0; - padding: 0.4rem 0.55rem; - overflow: auto; - max-height: 12rem; - background: #1e1e1e; - color: #d4d4d4; - font: 0.7rem/1.35 var(--mono); - white-space: pre; -} -.structure.debug-surface .code-body code { - font: inherit; - background: none; - padding: 0; - color: inherit; -} -.structure.debug-surface .code-out { - margin: 0; - padding: 0.4rem 0.55rem; - border-top: 1px solid #2d2d2d; - background: #1a1a1a; - font: 0.7rem/1.35 var(--mono); - white-space: pre-wrap; - word-break: break-word; - color: #b5cea8; -} -.structure.debug-surface .code-out.err { color: #f48771; background: #2a1515; } -.structure.debug-surface .code-out[hidden] { display: none !important; } -.stmt { - display: grid; - grid-template-columns: 1rem 1fr; - align-items: stretch; -} -.stmt .bp-gutter { - border: 0; - background: transparent; - cursor: pointer; - padding: 0; - display: flex; - align-items: flex-start; - justify-content: center; - padding-top: 0.28rem; -} -.stmt .bp-gutter:hover { background: #3a1d1d; } -.stmt.bp .bp-gutter::after { - content: ""; - width: 0.42rem; - height: 0.42rem; - border-radius: 50%; - background: var(--bp); - display: block; -} -.stmt.current { - background: var(--current); - box-shadow: inset 2px 0 0 #75beff; -} -.stmt-body > .card { border-bottom: 1px solid #2d2d2d; } -.dbg-panel { - margin-bottom: 0.45rem; - padding-bottom: 0.35rem; - border-bottom: 1px solid var(--line); -} -.dbg-vars, .dbg-frame { - font-family: var(--mono); - font-size: 0.7rem; - padding: 0.15rem 0.4rem; - white-space: pre-wrap; - color: #b5cea8; - min-height: 1.5rem; - line-height: 1.3; -} -.dbg-bps { list-style: none; margin: 0; padding: 0 0.35rem; } -.dbg-bps li { - font-family: var(--mono); - font-size: 0.68rem; - padding: 0.12rem 0; - color: #f48771; - cursor: pointer; - line-height: 1.25; -} -.dbg-bps li.muted { color: var(--muted); cursor: default; } -.dbg-console { - flex-shrink: 0; - height: var(--console-h); - border-top: none; - background: var(--panel); - display: flex; - flex-direction: column; - min-height: 48px; - max-height: 55vh; - overflow: hidden; -} -.dbg-out { - margin: 0; - padding: 0.3rem 0.55rem 0.45rem; - overflow: auto; - font-family: var(--mono); - font-size: 0.72rem; - color: var(--ink); - white-space: pre-wrap; - flex: 1; - line-height: 1.35; -} -.hint { color: var(--muted); font-weight: 400; text-transform: none; letter-spacing: 0; font-size: 0.62rem; } -.err { color: #f48771; padding: 0.5rem; } -body.resizing-col { cursor: col-resize; user-select: none; } -body.resizing-row { cursor: row-resize; user-select: none; } -@media (max-width: 900px) { - .dbg-shell { flex-wrap: wrap; } - .dbg-nav, .dbg-side { width: 100% !important; max-height: 120px; } - .dbg-split-v { display: none; } - .dbg-outline { display: none; } -} -"# -} - -fn debug_js() -> &'static str { - r#" -(function () { - function initResizers() { - var root = document.documentElement; - var KEY = "marqdo.debug.layout"; - try { - var saved = JSON.parse(localStorage.getItem(KEY) || "{}"); - if (saved.nav) root.style.setProperty("--nav-w", saved.nav + "px"); - if (saved.side) root.style.setProperty("--side-w", saved.side + "px"); - if (saved.console) root.style.setProperty("--console-h", saved.console + "px"); - } catch (e) {} - function persist() { - var nav = parseInt(getComputedStyle(root).getPropertyValue("--nav-w"), 10) || 168; - var side = parseInt(getComputedStyle(root).getPropertyValue("--side-w"), 10) || 220; - var cons = parseInt(getComputedStyle(root).getPropertyValue("--console-h"), 10) || 120; - try { localStorage.setItem(KEY, JSON.stringify({ nav: nav, side: side, console: cons })); } catch (e) {} - } - function bindCol(splitId, prop, min, max, fromRight) { - var el = document.getElementById(splitId); - if (!el) return; - el.addEventListener("mousedown", function (ev) { - ev.preventDefault(); - el.classList.add("dragging"); - document.body.classList.add("resizing-col"); - function move(e) { - var x = e.clientX; - var w; - if (fromRight) { - w = Math.min(max, Math.max(min, window.innerWidth - x)); - } else { - w = Math.min(max, Math.max(min, x)); - } - root.style.setProperty(prop, w + "px"); - } - function up() { - el.classList.remove("dragging"); - document.body.classList.remove("resizing-col"); - document.removeEventListener("mousemove", move); - document.removeEventListener("mouseup", up); - persist(); - } - document.addEventListener("mousemove", move); - document.addEventListener("mouseup", up); - }); - } - function bindRow(splitId, prop, min, max) { - var el = document.getElementById(splitId); - if (!el) return; - el.addEventListener("mousedown", function (ev) { - ev.preventDefault(); - el.classList.add("dragging"); - document.body.classList.add("resizing-row"); - function move(e) { - var h = Math.min(max, Math.max(min, window.innerHeight - e.clientY)); - root.style.setProperty(prop, h + "px"); - } - function up() { - el.classList.remove("dragging"); - document.body.classList.remove("resizing-row"); - document.removeEventListener("mousemove", move); - document.removeEventListener("mouseup", up); - persist(); - } - document.addEventListener("mousemove", move); - document.addEventListener("mouseup", up); - }); - } - bindCol("split-nav", "--nav-w", 120, 360, false); - bindCol("split-side", "--side-w", 140, 420, true); - bindRow("split-console", "--console-h", 48, Math.floor(window.innerHeight * 0.55)); - } - initResizers(); - - var structure = document.getElementById("structure"); - var startBtn = document.getElementById("dbg-start"); - var contBtn = document.getElementById("dbg-continue"); - var stepBtn = document.getElementById("dbg-step"); - var stopBtn = document.getElementById("dbg-stop"); - var statusEl = document.getElementById("dbg-status"); - var localsEl = document.getElementById("dbg-locals"); - var stdoutEl = document.getElementById("dbg-stdout"); - var frameEl = document.getElementById("dbg-frame"); - var bpsEl = document.getElementById("dbg-bps"); - if (!structure || !startBtn) return; - - var bps = new Set(); - var session = null; - var path = window.MARQDO_FILE_PATH || ""; - - function bpList() { - return Array.from(bps).sort(function (a, b) { return a - b; }); - } - function setStatus(t) { if (statusEl) statusEl.textContent = t; } - function setPausedUi(paused) { - startBtn.disabled = !!session; - contBtn.disabled = !paused; - stepBtn.disabled = !paused; - stopBtn.disabled = !session; - } - function clearCurrent() { - structure.querySelectorAll(".stmt.current").forEach(function (el) { - el.classList.remove("current"); - }); - } - function renderBps() { - if (!bpsEl) return; - var list = bpList(); - if (!list.length) { - bpsEl.innerHTML = '
    1. none
    2. '; - return; - } - var html = ""; - list.forEach(function (n) { - html += '
    3. line ' + n + '
    4. '; - }); - bpsEl.innerHTML = html; - bpsEl.querySelectorAll("li[data-line]").forEach(function (li) { - li.addEventListener("click", function () { - var line = li.getAttribute("data-line"); - var row = structure.querySelector('.stmt[data-line="' + line + '"]'); - if (row) row.scrollIntoView({ block: "nearest", behavior: "smooth" }); - }); - }); - } - function showLocals(obj) { - if (!localsEl) return; - if (!obj || typeof obj !== "object") { - localsEl.textContent = "(none)"; - return; - } - var keys = Object.keys(obj).sort(); - if (!keys.length) { - localsEl.textContent = "(none)"; - return; - } - localsEl.textContent = keys.map(function (k) { - return k + " = " + obj[k]; - }).join("\n"); - } - function applySnap(data) { - if (!data) return; - if (data.session) session = data.session; - clearCurrent(); - if (data.status === "paused") { - setStatus("Paused at line " + data.line + " · " + (data.fun || "")); - var row = structure.querySelector('.stmt[data-line="' + data.line + '"]'); - if (row) { - row.classList.add("current"); - row.scrollIntoView({ block: "nearest", behavior: "smooth" }); - } - showLocals(data.locals); - if (frameEl) frameEl.textContent = data.fun || "(unknown)"; - if (stdoutEl) stdoutEl.textContent = data.stdout === "" ? "(empty)" : data.stdout; - setPausedUi(true); - } else if (data.status === "done") { - setStatus(data.ok === false ? "Terminated with error" : "Finished"); - showLocals(null); - if (frameEl) frameEl.textContent = "(done)"; - if (stdoutEl) { - var t = data.stdout || ""; - if (data.stderr) t = (t ? t + "\n" : "") + data.stderr; - stdoutEl.textContent = t || "(empty)"; - } - session = null; - setPausedUi(false); - startBtn.disabled = false; - stopBtn.disabled = true; - } else if (data.status === "running") { - setStatus("Running…"); - setPausedUi(false); - stopBtn.disabled = !session; - } else { - setStatus(data.status || "Idle"); - setPausedUi(false); - } - if (data.ok === false && data.error) setStatus(data.error); - } - function post(url, body) { - return fetch(url, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body || {}) - }).then(function (r) { return r.json(); }); - } - function stdinText() { - var ta = document.getElementById("stdin"); - return ta ? ta.value : ""; - } - - structure.querySelectorAll(".stmt > .bp-gutter").forEach(function (btn) { - btn.addEventListener("click", function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - var row = btn.closest(".stmt"); - if (!row) return; - var line = parseInt(row.getAttribute("data-line"), 10); - if (bps.has(line)) { - bps.delete(line); - row.classList.remove("bp"); - } else { - bps.add(line); - row.classList.add("bp"); - } - renderBps(); - if (session) { - post("api/debug/breakpoints", { - session: session, - breakpoints: bpList() - }).catch(function () {}); - } - }); - }); - - startBtn.addEventListener("click", function () { - startBtn.disabled = true; - setStatus("Starting…"); - clearCurrent(); - post("api/debug/start", { - path: path, - breakpoints: bpList(), - stdin: stdinText() - }).then(applySnap).catch(function (e) { - setStatus(String(e)); - startBtn.disabled = false; - session = null; - }); - }); - contBtn.addEventListener("click", function () { - if (!session) return; - setStatus("Continue…"); - setPausedUi(false); - post("api/debug/continue", { - session: session, - breakpoints: bpList() - }).then(applySnap).catch(function (e) { setStatus(String(e)); }); - }); - stepBtn.addEventListener("click", function () { - if (!session) return; - setStatus("Step…"); - setPausedUi(false); - post("api/debug/step", { - session: session, - breakpoints: bpList() - }).then(applySnap).catch(function (e) { setStatus(String(e)); }); - }); - stopBtn.addEventListener("click", function () { - if (!session) return; - post("api/debug/stop", { session: session }).then(function () { - session = null; - clearCurrent(); - setStatus("Stopped"); - setPausedUi(false); - startBtn.disabled = false; - stopBtn.disabled = true; - }).catch(function (e) { setStatus(String(e)); }); - }); - - document.addEventListener("keydown", function (ev) { - if (ev.key === "F5" && !contBtn.disabled) { - ev.preventDefault(); - contBtn.click(); - } else if (ev.key === "F10" && !stepBtn.disabled) { - ev.preventDefault(); - stepBtn.click(); - } - }); - - var input = document.getElementById("fn-search"); - var tree = document.querySelector(".outline-tree"); - if (input && tree) { - input.addEventListener("input", function () { - var q = (input.value || "").trim().toLowerCase(); - tree.querySelectorAll(".outline-item").forEach(function (li) { - if (!q) { li.classList.remove("hidden"); return; } - var name = (li.getAttribute("data-fn") || "").toLowerCase(); - var fpath = (li.getAttribute("data-fn-path") || "").toLowerCase(); - var selfMatch = name.indexOf(q) !== -1 || fpath.indexOf(q) !== -1; - var childMatch = false; - li.querySelectorAll(".outline-item").forEach(function (c) { - var cn = (c.getAttribute("data-fn") || "").toLowerCase(); - var cp = (c.getAttribute("data-fn-path") || "").toLowerCase(); - if (cn.indexOf(q) !== -1 || cp.indexOf(q) !== -1) childMatch = true; - }); - li.classList.toggle("hidden", !(selfMatch || childMatch)); - }); - }); - } - - renderBps(); - setPausedUi(false); - - // Foreign code cards (same API as view) - document.querySelectorAll(".code-card").forEach(function (card) { - var btn = card.querySelector(".code-run"); - var cmd = card.querySelector(".code-cmd"); - var out = card.querySelector(".code-out"); - var body = card.querySelector(".code-body code"); - if (!btn || !out || !body) return; - btn.addEventListener("click", function () { - btn.disabled = true; - out.hidden = false; - out.classList.remove("err"); - out.textContent = "Running…"; - fetch("api/foreign-run", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - lang: card.getAttribute("data-lang") || "python", - source: body.textContent, - cmd: cmd ? cmd.value : "" - }) - }) - .then(function (r) { return r.json(); }) - .then(function (data) { - var parts = []; - if (data.stdout) parts.push(data.stdout); - if (data.stderr) parts.push("[stderr]\n" + data.stderr); - if (data.error) parts.push(data.error); - var meta = []; - if (typeof data.code === "number") meta.push("exit " + data.code); - if (typeof data.ms === "number") meta.push(data.ms + "ms"); - if (data.timed_out) meta.push("timed out"); - if (data.truncated) meta.push("truncated"); - if (meta.length) parts.push("— " + meta.join(" · ")); - if (data.ok) { - out.classList.remove("err"); - } else { - out.classList.add("err"); - } - out.textContent = parts.length ? parts.join("\n\n") : "(no output)"; - }) - .catch(function (e) { - out.classList.add("err"); - out.textContent = String(e); - }) - .finally(function () { btn.disabled = false; }); - }); - }); -})(); -"# -} diff --git a/src/view/document.rs b/src/view/document.rs deleted file mode 100755 index 2679739..0000000 --- a/src/view/document.rs +++ /dev/null @@ -1,1681 +0,0 @@ -//! Browse Structure as a prose-preserving document surface + annotation bands. -//! -//! See `doc/design/view-document-annotations.md` · `doc/design/view-execution-trace.md`. - -use std::collections::{HashMap, HashSet}; - -use crate::ast::{Function, Module, Stmt}; -use crate::host::writeback; -use crate::lex::{classify_source, ClassifiedLine, LineKind}; -use crate::parse::{scan_prose_line, ProseBit}; -use crate::view::annot::{ - annots_by_line, bit_at, bit_kind_class, prose_bit_end, render_annot_band, ViewAnnot, -}; -use crate::view::html::escape; -use crate::view::render::{ - comment_markdown_to_html, render_code_assign_card, render_formula_assign_card, -}; - -const MAX_VISIBLE_ANNOTS: usize = 4; - -/// Render Browse Structure: narration kept, executable spans marked, annot bands attached. -pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot]) -> String { - let lines = classify_source(source); - let by_line = annots_by_line(annots); - let fun_by_line = index_functions(module); - let special = index_special_assigns(module, source); - let skip_body = special_body_lines(&special); - let stmt_lines = index_stmt_lines(module); - let occluded_lines = index_occluded_lines(module); - let writebacks = writeback::writeback_map(source); - let taken_arms = taken_arms_by_branch_line(annots); - - let mut out = String::from(r#"
      "#); - out.push_str(&render_syntax_guide()); - - if !module.imports.is_empty() || !module.uses.is_empty() { - out.push_str(r#"
      "#); - for imp in &module.imports { - out.push_str(&format!( - r#"{}:{}"#, - escape(&imp.bind), - escape(&imp.path) - )); - } - for u in &module.uses { - out.push_str(&format!( - r#"{}:{}"#, - escape(&u.bind), - escape(&u.path.join(".")) - )); - } - out.push_str("
      "); - } - - let body_start = skip_frontmatter_end(&lines).unwrap_or(1); - let mut para: Vec<(u32, String)> = Vec::new(); - let flush_para = |para: &mut Vec<(u32, String)>, out: &mut String| { - if para.is_empty() { return; } - let first_line = para[0].0; - let source_anchors = para.iter().skip(1).map(|(line,_)| - format!(r#""#)).collect::(); - let mut replacements = Vec::new(); - let mut notes = String::new(); - let text = para.iter().map(|(line, text)| { - let fragment = super::logic::narrative(*line, text, 0); - replacements.extend(fragment.replacements); - notes.push_str(&fragment.notes); - fragment.markdown - }).collect::>().join(" "); - para.clear(); - let md = super::logic::replace(comment_markdown_to_html(&text), &replacements); - let band = render_document_band(&[], ¬es); - out.push_str(&format!( - r#"
      {source_anchors}
      {md}
      {band}
      "# - )); - }; - - let mut i = 0usize; - while i < lines.len() { - let l = &lines[i]; - if l.line_no < body_start { - i += 1; - continue; - } - // Body lines of $$ / ``` already folded into formula/code cards. - if skip_body.contains(&l.line_no) { - flush_para(&mut para, &mut out); - i += 1; - continue; - } - - // GFM table block (may be Comment or Code classified). - if looks_like_table_row(l.text.trim()) { - flush_para(&mut para, &mut out); - let (html, next) = render_table_block(&lines, i, &by_line, &writebacks); - out.push_str(&html); - i = next; - continue; - } - - match l.kind { - LineKind::Blank => { - flush_para(&mut para, &mut out); - i += 1; - } - LineKind::Writeback => { - flush_para(&mut para, &mut out); - let start_line = l.line_no; - let mut block = String::new(); - while i < lines.len() && matches!(lines[i].kind, LineKind::Writeback) { - if !block.is_empty() { - block.push('\n'); - } - block.push_str(lines[i].text.trim_end_matches(['\r', '\n'])); - i += 1; - } - out.push_str(&crate::view::render::render_writeback_source_line( - start_line, &block, - )); - } - LineKind::Comment => { - let text = l.text.trim_end_matches(['\r', '\n']); - let trimmed = text.trim(); - // Unbound ```lang fences stay Comment in lex — render as code cards - // (same chrome as bound foreign), never join into a prose blob. - if crate::foreign::is_fence_opener(trimmed) - || (trimmed.starts_with("```") && !crate::foreign::is_fence_closer(trimmed)) - { - flush_para(&mut para, &mut out); - let (html, next) = render_narrative_fence(&lines, i); - out.push_str(&html); - i = next; - continue; - } - if crate::foreign::is_fence_closer(trimmed) { - // Orphan closer — skip. - flush_para(&mut para, &mut out); - i += 1; - continue; - } - let bits = scan_prose_line(text); - let is_stmt = stmt_lines.contains(&l.line_no); - let has_annots = by_line - .get(&l.line_no) - .map(|v| !v.is_empty()) - .unwrap_or(false); - // Decl alone stays in Markdown prose (keep links). Open a marked - // line block when there is executable prose, a stmt, or chips. - let needs_annot = is_stmt - || has_annots - || bits.iter().any(|b| { - matches!(b, ProseBit::BoldCode { .. } | ProseBit::ItalicReturn { .. }) - }); - if needs_annot { - flush_para(&mut para, &mut out); - out.push_str(&render_line_block( - l.line_no, - text, - &bits, - by_line.get(&l.line_no).map(|v| v.as_slice()).unwrap_or(&[]), - special.get(&l.line_no), - writebacks.get(&l.line_no), - None, - &occluded_lines, - )); - } else if !trimmed.is_empty() { - para.push((l.line_no, trimmed.to_string())); - } - i += 1; - } - LineKind::Code => { - flush_para(&mut para, &mut out); - let text = l.text.trim_end_matches(['\r', '\n']); - if let Some(fun) = fun_by_line.get(&l.line_no) { - out.push_str(&render_fun_heading(fun, annots)); - if let Some(list) = by_line.get(&l.line_no) { - if !list.is_empty() { - let owned: Vec = list.iter().map(|a| (*a).clone()).collect(); - out.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS)); - } - } - i += 1; - continue; - } - - let trimmed = text.trim_start(); - if let Some((kind, marker_len)) = list_marker(trimmed) { - let (html, next) = render_list_block( - &lines, - i, - kind, - marker_len, - &by_line, - &special, - &writebacks, - &taken_arms, - annots, - &occluded_lines, - ); - out.push_str(&html); - i = next; - continue; - } - - let bits = scan_prose_line(text); - out.push_str(&render_line_block( - l.line_no, - text, - &bits, - by_line.get(&l.line_no).map(|v| v.as_slice()).unwrap_or(&[]), - special.get(&l.line_no), - writebacks.get(&l.line_no), - None, - &occluded_lines, - )); - i += 1; - } - } - } - flush_para(&mut para, &mut out); - out.push_str("
      "); - super::logic::link_definitions(out, module) -} - -#[derive(Clone, Copy)] -enum ListKind { - Ul, - Ol, -} - -fn list_marker(trimmed: &str) -> Option<(ListKind, usize)> { - if let Some(rest) = trimmed.strip_prefix("- ") { - let _ = rest; - return Some((ListKind::Ul, 2)); - } - if trimmed.starts_with("-") && trimmed.len() > 1 && trimmed.as_bytes()[1].is_ascii_whitespace() { - return Some((ListKind::Ul, 2)); - } - // N. or N. * - let bytes = trimmed.as_bytes(); - let mut i = 0; - while i < bytes.len() && bytes[i].is_ascii_digit() { - i += 1; - } - if i > 0 && i < bytes.len() && bytes[i] == b'.' { - let after = i + 1; - if after < bytes.len() && bytes[after].is_ascii_whitespace() { - return Some((ListKind::Ol, after + 1)); - } - if after < bytes.len() && bytes[after] == b'*' { - // "3.*" else — marker through '*' - return Some((ListKind::Ol, after + 1)); - } - } - None -} - -fn looks_like_table_row(trimmed: &str) -> bool { - trimmed.starts_with('|') && trimmed.matches('|').count() >= 2 -} - -fn looks_like_table_sep(trimmed: &str) -> bool { - if !trimmed.starts_with('|') { - return false; - } - trimmed - .chars() - .all(|c| c == '|' || c == '-' || c == ':' || c.is_whitespace()) -} - -fn indent_level(text: &str) -> usize { - let mut n = 0usize; - for c in text.chars() { - match c { - ' ' => n += 1, - '\t' => n += 4, - _ => break, - } - } - n / 2 // 2 spaces per visual level -} - -fn render_table_block( - lines: &[ClassifiedLine], - start: usize, - by_line: &HashMap>, - writebacks: &HashMap, -) -> (String, usize) { - let mut rows: Vec<(u32, String)> = Vec::new(); - let mut i = start; - while i < lines.len() { - let t = lines[i].text.trim_end_matches(['\r', '\n']); - let trimmed = t.trim(); - if !looks_like_table_row(trimmed) { - break; - } - rows.push((lines[i].line_no, trimmed.to_string())); - i += 1; - } - if rows.is_empty() { - return (String::new(), start + 1); - } - let first_line = rows[0].0; - let mut html = format!( - r#"
      "#, - line = first_line - ); - let mut header_done = false; - let mut notes = String::new(); - for (idx, (line, row)) in rows.iter().enumerate() { - if looks_like_table_sep(row) { continue; } - let cells: Vec<&str> = row.trim().trim_matches('|').split('|').map(str::trim).collect(); - let rendered: Vec = cells.iter().map(|cell| { - let base = cell.as_ptr() as usize - row.as_ptr() as usize; - notes.push_str(&super::logic::narrative(*line, cell, base).notes); - render_narrative_inline(*line, cell, base) - }).collect(); - if !header_done { - html.push_str(""); - for cell in &rendered { html.push_str(&format!("")); } - html.push_str(""); - header_done = true; - if idx + 1 < rows.len() && looks_like_table_sep(&rows[idx + 1].1) { continue; } - if rows.len() == 1 { - html.push_str(""); - for cell in &cells { html.push_str(&format!("", escape(cell))); } - html.push_str(""); - } - continue; - } - html.push_str(""); - for cell in &rendered { html.push_str(&format!("")); } - html.push_str(""); - } - if header_done { html.push_str(""); } - html.push_str("
      {cell}
      {}
      {cell}
      "); - // The table is already a readable collection; retain only non-call results. - let owned: Vec = by_line.get(&first_line).into_iter().flatten() - .filter(|a| a.kind != crate::view::annot::AnnotKind::Call) - .map(|a| (**a).clone()).collect(); - html.push_str(&render_document_band(&owned, ¬es)); - if let Some(body) = writebacks.get(&first_line) { - html.push_str(&crate::view::render::render_output_card(first_line, body)); - } - html.push_str(""); - (html, i) -} - -fn render_list_block( - lines: &[ClassifiedLine], - start: usize, - kind: ListKind, - _marker_len: usize, - by_line: &HashMap>, - special: &HashMap, - writebacks: &HashMap, - taken_arms: &HashMap, - all_annots: &[ViewAnnot], - occluded_lines: &HashSet, -) -> (String, usize) { - let base_indent = indent_level(&lines[start].text); - let tag = match kind { - ListKind::Ul => "ul", - ListKind::Ol => "ol", - }; - let cls = match kind { - ListKind::Ul => "doc-loop", - ListKind::Ol => "doc-branch", - }; - // Branch stmt line = list head line for taken-arm lookup. - let branch_line = lines[start].line_no; - let taken = taken_arms.get(&branch_line).copied(); - - let loop_id = all_annots - .iter() - .find(|a| { - a.kind == crate::view::annot::AnnotKind::LoopFrame && a.anchor_line == branch_line - }) - .and_then(|a| a.loop_id); - - let mut html = format!( - r#"<{tag} class="{cls}" data-line="{line}"{loop_attr} style="--doc-indent:{indent}">"#, - tag = tag, - cls = cls, - line = branch_line, - loop_attr = loop_id - .map(|id| format!(r#" data-loop-id="{id}""#)) - .unwrap_or_default(), - indent = base_indent.max(1), - ); - - // Loop iteration picker (default = last). - if matches!(kind, ListKind::Ul) { - let frames: Vec<&ViewAnnot> = all_annots - .iter() - .filter(|a| { - a.kind == crate::view::annot::AnnotKind::LoopFrame && a.anchor_line == branch_line - }) - .collect(); - if frames.len() >= 2 { - html.push_str(r#"
    5. "); - } - } - - let mut i = start; - let mut arm_index = 0usize; - while i < lines.len() { - let text = lines[i].text.trim_end_matches(['\r', '\n']); - let trimmed = text.trim_start(); - let ind = indent_level(text); - if lines[i].kind == LineKind::Blank { - // Blank inside list: peek ahead — if next is deeper/same list continue, else break. - if i + 1 < lines.len() { - let n = &lines[i + 1]; - let nt = n.text.trim_end_matches(['\r', '\n']); - if nt.trim().is_empty() { - i += 1; - continue; - } - let nind = indent_level(nt); - if nind > base_indent - || (nind == base_indent && list_marker(nt.trim_start()).is_some()) - { - i += 1; - continue; - } - } - break; - } - if ind < base_indent { - break; - } - if ind == base_indent { - if let Some((k, mlen)) = list_marker(trimmed) { - if !matches!( - (k, kind), - (ListKind::Ul, ListKind::Ul) | (ListKind::Ol, ListKind::Ol) - ) { - break; - } - let head = trimmed[mlen..].trim(); - let arm_cls = match (kind, taken) { - (ListKind::Ol, Some(t)) if t == arm_index => "arm-taken", - (ListKind::Ol, Some(_)) => "arm-miss", - (ListKind::Ol, None) => "", - _ => "", - }; - html.push_str(&format!( - r#"
    6. "#, - arm_cls = arm_cls, - line = lines[i].line_no, - arm_idx = arm_index, - indent = ind.max(1), - )); - html.push_str(&format!( - r#"
      {}
      "#, - render_surface_line( - lines[i].line_no, - head, - by_line, - occluded_lines.contains(&lines[i].line_no) - ) - )); - // Annots for this line; Branch chips on the arm they refer to (filtered by call frame in JS). - let mut head_annots: Vec = Vec::new(); - if let Some(list) = by_line.get(&lines[i].line_no) { - for a in list { - if a.kind == crate::view::annot::AnnotKind::Branch { - continue; - } - head_annots.push((*a).clone()); - } - } - if matches!(kind, ListKind::Ol) { - // Branch annots are keyed to the list's first line, not each arm head. - if let Some(list) = by_line.get(&branch_line) { - for a in list { - if a.kind == crate::view::annot::AnnotKind::Branch - && a.arm_index == Some(arm_index) - { - head_annots.push((*a).clone()); - } - } - } - } - let notes = render_logic_notes(lines[i].line_no, head, &scan_prose_line(head), occluded_lines.contains(&lines[i].line_no)); - html.push_str(&render_document_band(&head_annots, ¬es)); - // Body: following lines with greater indent until next sibling. - i += 1; - html.push_str(r#"
      "#); - while i < lines.len() { - let t2 = lines[i].text.trim_end_matches(['\r', '\n']); - if t2.trim().is_empty() { - // allow blank inside body - if i + 1 < lines.len() && indent_level(&lines[i + 1].text) > base_indent { - i += 1; - continue; - } - break; - } - let ind2 = indent_level(t2); - if ind2 <= base_indent { - break; - } - // Nested list at deeper indent. - let tr2 = t2.trim_start(); - if let Some((nk, _)) = list_marker(tr2) { - let (inner, next) = render_list_block( - lines, - i, - nk, - 0, - by_line, - special, - writebacks, - taken_arms, - all_annots, - occluded_lines, - ); - html.push_str(&inner); - i = next; - continue; - } - if looks_like_table_row(tr2) { - let (th, next) = render_table_block(lines, i, by_line, writebacks); - html.push_str(&th); - i = next; - continue; - } - let bits = scan_prose_line(t2); - html.push_str(&render_line_block( - lines[i].line_no, - t2, - &bits, - by_line - .get(&lines[i].line_no) - .map(|v| v.as_slice()) - .unwrap_or(&[]), - special.get(&lines[i].line_no), - writebacks.get(&lines[i].line_no), - Some(ind2), - occluded_lines, - )); - i += 1; - } - html.push_str("
    7. "); - arm_index += 1; - continue; - } - break; - } - // Deeper than base but not under an open item — shouldn't happen; stop. - break; - } - html.push_str(&format!("", tag = tag)); - (html, i) -} - -fn render_surface_line( - line_no: u32, - head: &str, - by_line: &HashMap>, - occluded: bool, -) -> String { - if occluded && !occlusion_spans(head).is_empty() { - return format!( - r#"{}"#, - head.len(), - render_occlusion_text(line_no, head, 0) - ); - } - let bits = scan_prose_line(head); - if bits.is_empty() { - // Else arm "*" or plain condition text. - if head.trim() == "*" { - return r#"else"#.into(); - } - format!(r#"{}"#, render_narrative_inline(line_no, head, 0)) - } else { - let annots = by_line.get(&line_no).map(|v| v.as_slice()).unwrap_or(&[]); - render_prose_with_marks(line_no, head, &bits, annots, false) - } -} - -/// SSR default: taken arm for the highest `call_id` per branch line (matches last-call picker). -fn taken_arms_by_branch_line(annots: &[ViewAnnot]) -> HashMap { - let mut best: HashMap = HashMap::new(); - for a in annots { - if a.kind != crate::view::annot::AnnotKind::Branch { - continue; - } - let Some(idx) = a.arm_index else { continue }; - let cid = a.call_id.unwrap_or(0); - let entry = best.entry(a.anchor_line).or_insert((cid, idx)); - if cid >= entry.0 { - *entry = (cid, idx); - } - } - best.into_iter().map(|(line, (_, arm))| (line, arm)).collect() -} - -fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String { - let mut s = format!( - r##"
      -
      -

      {name}

      -说明"##, - line = fun.span.line, - name = escape(&fun.name), - ); - // Call picker placeholder: filled when ≥2 call frames exist for this fn. - let call_labels: Vec<&ViewAnnot> = annots - .iter() - .filter(|a| a.kind == crate::view::annot::AnnotKind::CallFrame && a.label == fun.name) - .collect(); - if call_labels.len() >= 2 { - s.push_str( - r#""); - } - s.push_str("
      "); - if !fun.params.is_empty() { - // Default SSR values = last call frame (matches picker default = last option). - let default_args = call_labels - .last() - .map(|a| parse_args_brief(&a.value)) - .unwrap_or_default(); - s.push_str(r#"
      "#); - for p in &fun.params { - let cls = if p.inferred { "chip inferred" } else { "chip" }; - let title = if p.inferred { - "inferred from prose / body" - } else { - "explicit + param" - }; - let val = default_args - .get(p.name.as_str()) - .filter(|v| !v.is_empty()) - .map(|v| format!("={}", escape(v))) - .unwrap_or_default(); - // Always emit chip-val so call-picker JS can refresh per frame. - s.push_str(&format!( - r#"{name}{val}"#, - cls = cls, - title = title, - name = escape(&p.name), - fn = escape(&fun.name), - val = val, - )); - } - s.push_str("
      "); - } - s.push_str("
      "); - s -} - -/// Parse `args_brief` (`谁=marqdo, n=37`) into name → value. -fn parse_args_brief(brief: &str) -> HashMap { - let mut m = HashMap::new(); - if brief.trim().is_empty() { - return m; - } - for part in brief.split(", ") { - if let Some((k, v)) = part.split_once('=') { - if !k.is_empty() { - m.insert(k.to_string(), v.to_string()); - } - } - } - m -} - -/// Display-only source spans. The AST decides whether this line contains an occlusion. -/// Scan only executable fragments, preserving quoted links as literal data. -fn occlusion_spans(text: &str) -> Vec> { - super::logic::spans(text, true) -} -fn render_occlusion_text(line: u32, text: &str, base: usize) -> String { - let mut html = String::new(); - let mut cursor = 0; - for span in occlusion_spans(text) { - html.push_str(&escape(&text[cursor..span.start])); - html.push_str(&super::logic::source(line, &span, base)); - cursor = span.end; - } - html.push_str(&escape(&text[cursor..])); - html -} -fn render_logic_notes(line: u32, text: &str, bits: &[ProseBit], occluded: bool) -> String { - let mut notes = String::new(); - if occluded && bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })) { - for span in occlusion_spans(text) { - notes.push_str(&super::logic::note(line, &span, 0, true)); - } - return notes; - } - let mut cursor = 0; - for bit in bits { - let start = bit_at(bit); - let end = prose_bit_end(text, bit); - if start > cursor { - notes.push_str(&super::logic::narrative(line, &text[cursor..start], cursor).notes); - } - if occluded { - if let ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } = bit { - for span in occlusion_spans(inner) { - notes.push_str(&super::logic::note(line, &span, inner_offset(text, bit), true)); - } - } - } - cursor = end.max(cursor); - } - if cursor < text.len() { - notes.push_str(&super::logic::narrative(line, &text[cursor..], cursor).notes); - } - notes -} -fn inner_offset(text: &str, bit: &ProseBit) -> usize { - let start = bit_at(bit); - match bit { - ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } => - start + text[start..prose_bit_end(text, bit)].find(inner).unwrap_or(0), - _ => start, - } -} -fn render_document_band(annots: &[ViewAnnot], notes: &str) -> String { - let band = render_annot_band(annots, MAX_VISIBLE_ANNOTS); - if notes.is_empty() { - return band; - } - if band.is_empty() { - return format!( - r#"
      {notes}
      "# - ); - } - band.replacen( - r#"
      "#, - &format!(r#"
      {notes}"#), - 1, - ) -} - -fn render_line_block( - line_no: u32, - text: &str, - bits: &[ProseBit], - annots: &[&ViewAnnot], - special: Option<&SpecialAssign>, - writeback_body: Option<&String>, - indent: Option, - occluded_lines: &HashSet, -) -> String { - let indent_style = indent - .map(|n| format!(r#" style="--doc-indent:{n}""#)) - .unwrap_or_default(); - // Source structure always visible — do not stamp data-call-ids (frame filter is chips-only). - let mut s = format!( - r#"
      "#, - line = line_no, - indent = indent_style, - ); - - match special { - Some(SpecialAssign::Formula { name, tex, .. }) => { - s.push_str(&render_formula_assign_card(name, tex)); - } - Some(SpecialAssign::Code { - name, lang, source, .. - }) => { - s.push_str(&render_code_assign_card(name, lang, source)); - } - None => { - let trimmed = text.trim_start(); - if bits.is_empty() - || (occluded_lines.contains(&line_no) - && bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. }))) - { - if occluded_lines.contains(&line_no) && !occlusion_spans(text).is_empty() { - s.push_str(&format!(r#"
      {}
      "#,text.len(),render_occlusion_text(line_no,text,0))); - } else if let Some(rest) = trimmed.strip_prefix("> ") { - let aid = match_annot_for_line(annots) - .map(|a| a.id.as_str()) - .unwrap_or(""); - s.push_str(&format!( - r#"
      > {rest}
      "#, - line = line_no, - aid = escape(aid), - rest = escape(rest), - )); - } else if let Some(rest) = trimmed.strip_prefix('>') { - let aid = match_annot_for_line(annots) - .map(|a| a.id.as_str()) - .unwrap_or(""); - s.push_str(&format!( - r#"
      > {rest}
      "#, - line = line_no, - aid = escape(aid), - rest = escape(rest.trim_start()), - )); - } else { - s.push_str(&format!( - r#"
      {}
      "#, - escape(trimmed) - )); - } - } else { - s.push_str(r#"
      "#); - s.push_str(&render_prose_with_marks( - line_no, - text, - bits, - annots, - occluded_lines.contains(&line_no), - )); - s.push_str("
      "); - } - } - } - - if let Some(body) = writeback_body { - s.push_str(&crate::view::render::render_output_card(line_no, body)); - } - - // Formula/code cards are the single visual truth — do not stack Bind chips - // (or fence/SVG dumps) underneath. Variables rail still has final values. - let band_annots: Vec = if special.is_some() { - Vec::new() - } else { - annots - .iter() - .filter(|a| !is_noisy_result_chip(a)) - .map(|a| (*a).clone()) - .collect() - }; - let notes = if special.is_none() { - render_logic_notes(line_no, text, bits, occluded_lines.contains(&line_no)) - } else { - String::new() - }; - s.push_str(&render_document_band(&band_annots, ¬es)); - - s.push_str("
      "); - s -} - -/// Huge SVG / fenced code dumps — prefer abbreviated chips from annot builder; -/// only drop if detail is still an unreadable dump. -fn is_noisy_result_chip(a: &ViewAnnot) -> bool { - if a.kind != crate::view::annot::AnnotKind::Bind { - return false; - } - let v = a.detail.as_str(); - v.contains(" 96 -} - -fn match_annot_for_line<'a>(annots: &[&'a ViewAnnot]) -> Option<&'a ViewAnnot> { - annots.iter().copied().find(|a| { - matches!( - a.kind, - crate::view::annot::AnnotKind::Call - | crate::view::annot::AnnotKind::Bind - | crate::view::annot::AnnotKind::Return - ) - }) -} - -/// Unbound Markdown fence → same visual card as bound foreign (no Run chrome). -fn render_narrative_fence(lines: &[ClassifiedLine], start: usize) -> (String, usize) { - let opener = lines[start].text.trim_end_matches(['\r', '\n']).trim(); - let lang = crate::foreign::fence_lang(opener).unwrap_or_else(|| "text".into()); - let line_no = lines[start].line_no; - let mut body: Vec = Vec::new(); - let mut j = start + 1; - while j < lines.len() { - let t = lines[j].text.trim_end_matches(['\r', '\n']); - if crate::foreign::is_fence_closer(t.trim()) { - j += 1; - break; - } - body.push(t.to_string()); - j += 1; - } - let source = body.join("\n"); - let html = format!( - r#"
      -
      - code - {lang} -
      -
      {src}
      -
      "#, - line = line_no, - lang = escape(&lang), - src = escape(&source), - ); - (html, j) -} - -/// Preserve ordinary Markdown links/emphasis outside executable marks. Raw HTML -/// stays literal here, as it did in mixed executable prose before this renderer. -fn render_narrative_inline(line: u32, text: &str, base: usize) -> String { - let inner = text.trim(); - if inner.is_empty() { - return escape(text); - } - let start = text.find(inner).unwrap(); - let end = start + inner.len(); - let fragment = super::logic::narrative(line, inner, base + start); - let parser = pulldown_cmark::Parser::new(&fragment.markdown).map(|event| match event { - pulldown_cmark::Event::Html(html) | pulldown_cmark::Event::InlineHtml(html) => pulldown_cmark::Event::Text(html), - other => other, - }); - let mut html = String::new(); - pulldown_cmark::html::push_html(&mut html, parser); - let Some(body) = html - .strip_prefix("

      ") - .and_then(|s| s.strip_suffix("

      \n")) - else { - return escape(text); - }; - format!("{}{}{}", escape(&text[..start]), super::logic::replace(body.to_string(), &fragment.replacements), escape(&text[end..])) -} - -/// Render prose with markers stripped; show surface inner text only. -fn render_prose_with_marks( - line_no: u32, - text: &str, - bits: &[ProseBit], - annots: &[&ViewAnnot], - occluded: bool, -) -> String { - let mut html = String::new(); - let mut cursor = 0usize; - for bit in bits { - let start = bit_at(bit); - let end = prose_bit_end(text, bit); - if start > cursor { - html.push_str(&render_narrative_inline(line_no, &text[cursor..start], cursor)); - } - if start < end && end <= text.len() { - let (cls, display) = bit_display(bit); - let annot_id = match_annot_for_span(annots, start, end) - .map(|a| a.id.as_str()) - .unwrap_or(""); - html.push_str(&format!( - r#"{inner}"#, - cls = cls, - hint = match bit {ProseBit::Decl{..}=>"参数或变量声明",ProseBit::BoldCode{..}=>"语句:计算、赋值或调用",ProseBit::ItalicReturn{..}=>"返回:把结果交给调用方"}, - line = line_no, - start = start, - end = end, - aid = escape(annot_id), - inner = if occluded && !matches!(bit,ProseBit::Decl{..}) {render_occlusion_text(line_no,&display,inner_offset(text, bit))}else{escape(&display)}, - )); - } - cursor = end.max(cursor); - } - if cursor < text.len() { - html.push_str(&render_narrative_inline(line_no, &text[cursor..], cursor)); - } - html -} - -fn bit_display(bit: &ProseBit) -> (&'static str, String) { - match bit { - ProseBit::Decl { name, default, .. } => { - let cls = bit_kind_class(bit); - let s = match default { - Some(d) => format!("{name}={d}"), - None => name.clone(), - }; - (cls, s) - } - ProseBit::BoldCode { inner, .. } => (bit_kind_class(bit), inner.clone()), - ProseBit::ItalicReturn { inner, .. } => (bit_kind_class(bit), inner.clone()), - } -} - -fn match_annot_for_span<'a>( - annots: &[&'a ViewAnnot], - start: usize, - end: usize, -) -> Option<&'a ViewAnnot> { - annots.iter().copied().find(|a| match (a.anchor_byte_start, a.anchor_byte_end) { - (Some(s), Some(e)) => s < end && e > start, - (Some(s), None) => s >= start && s < end, - _ => false, - }) -} - -#[derive(Clone)] -enum SpecialAssign { - Formula { - name: String, - tex: String, - /// Last source line of the `$$ … $$` block (inclusive). - end_line: u32, - }, - Code { - name: String, - lang: String, - source: String, - /// Last source line of the fenced block (inclusive). - end_line: u32, - }, -} - -fn special_body_lines(special: &HashMap) -> HashSet { - let mut s = HashSet::new(); - for (start, sp) in special { - let end = match sp { - SpecialAssign::Formula { end_line, .. } | SpecialAssign::Code { end_line, .. } => { - *end_line - } - }; - let mut ln = *start + 1; - while ln <= end { - s.insert(ln); - ln += 1; - } - } - s -} - -fn index_functions(module: &Module) -> HashMap { - let mut m = HashMap::new(); - fn walk<'a>(fun: &'a Function, m: &mut HashMap) { - m.insert(fun.span.line, fun); - for c in &fun.children { - walk(c, m); - } - } - for f in &module.functions { - walk(f, &mut m); - } - m -} - -fn index_stmt_lines(module: &Module) -> HashSet { - let mut s = HashSet::new(); - for f in &module.functions { - crate::ast::walk_stmts(f, &mut |st| { - s.insert(crate::ast::stmt_line(st)); - }); - } - s -} - - -fn index_occluded_lines(module: &Module) -> HashSet { - use crate::ast::{Arg, Expr}; - fn expr(e: &Expr) -> bool { - match e { - Expr::Occluded { .. } => true, - Expr::Unary { expr: e, .. } => expr(e), - Expr::Binary { left, right, .. } => expr(left) || expr(right), - Expr::Call(c) => c.args.iter().any(|a| match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => expr(e), - }), - Expr::List(xs) => xs.iter().any(expr), - Expr::Map(xs) => xs.iter().any(|(_, e)| expr(e)), - Expr::Index { base, .. } => expr(base), - _ => false, - } - } - let mut lines = HashSet::new(); - for f in &module.functions { - crate::ast::walk_stmts(f, &mut |s| { - let has = match s { - Stmt::Assign { value, .. } - | Stmt::Return { value, .. } - | Stmt::Expr { value, .. } => expr(value), - Stmt::Call { call, .. } => call.args.iter().any(|a| match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => expr(e), - }), - Stmt::ForEach { .. } => true, - Stmt::While { condition, .. } => expr(condition), - Stmt::Branch { arms, .. } => { - arms.iter().any(|a| a.condition.as_ref().is_some_and(expr)) - } - }; - if has { - lines.insert(crate::ast::stmt_line(s)); - } - }); - } - lines -} - -fn index_special_assigns(module: &Module, source: &str) -> HashMap { - let src_lines: Vec<&str> = source.lines().collect(); - let mut m = HashMap::new(); - fn walk(fun: &Function, m: &mut HashMap, src_lines: &[&str]) { - for st in &fun.body { - record(st, m, src_lines); - match st { - Stmt::Branch { arms, .. } => { - for arm in arms { - for b in &arm.body { - record(b, m, src_lines); - } - } - } - Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { - for b in body { - record(b, m, src_lines); - } - } - _ => {} - } - } - for c in &fun.children { - walk(c, m, src_lines); - } - } - fn record(st: &Stmt, m: &mut HashMap, src_lines: &[&str]) { - match st { - Stmt::Assign { - name, - value: crate::ast::Expr::Formula(e), - span, - end_line, - .. - } => { - let tex = match e { - crate::formula::Expr::Matrix { source, .. } => source.clone(), - _ => crate::view::render::formula_ascii_to_tex_pub(&e.as_display()), - }; - let end_line = (*end_line).max(fence_block_end(src_lines, span.line, "$$")); - m.insert( - span.line, - SpecialAssign::Formula { - name: name.clone(), - tex, - end_line, - }, - ); - } - Stmt::Assign { - name, - value: crate::ast::Expr::Code(c), - span, - end_line, - .. - } => { - let end_line = (*end_line).max(fence_block_end(src_lines, span.line, "```")); - m.insert( - span.line, - SpecialAssign::Code { - name: name.clone(), - lang: c.lang.clone(), - source: c.source.clone(), - end_line, - }, - ); - } - _ => {} - } - } - for f in &module.functions { - walk(f, &mut m, &src_lines); - } - m -} - -/// Inclusive end line of a `$$` / ` ``` ` block starting on or after `assign_line`. -fn fence_block_end(src_lines: &[&str], assign_line: u32, fence: &str) -> u32 { - if assign_line == 0 || assign_line as usize > src_lines.len() { - return assign_line; - } - let assign = src_lines[assign_line as usize - 1].trim(); - // Meta formula: assign span is the opening `$$` line itself. - if fence == "$$" && assign == "$$" { - let mut i = assign_line as usize; // 0-based next line - while i < src_lines.len() { - if src_lines[i].trim() == "$$" { - return (i + 1) as u32; - } - i += 1; - } - return assign_line; - } - if fence == "$$" && assign.starts_with("$$") && assign.ends_with("$$") && assign.len() > 4 { - return assign_line; - } - let mut i = assign_line as usize; // 0-based index of line after assign - let mut seen_open = false; - while i < src_lines.len() { - let t = src_lines[i].trim(); - let line_no = (i + 1) as u32; - if !seen_open { - if t.starts_with(fence) { - seen_open = true; - if fence == "```" && t == "```" { - return line_no; - } - if fence == "$$" && t == "$$" { - i += 1; - while i < src_lines.len() { - if src_lines[i].trim() == "$$" { - return (i + 1) as u32; - } - i += 1; - } - return line_no; - } - } else if t.is_empty() { - i += 1; - continue; - } else { - return assign_line; - } - } else if fence == "```" && t.starts_with("```") { - return line_no; - } - i += 1; - } - assign_line -} - -fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option { - let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?; - if first_code.text.trim() != "---" { - return Some(1); - } - for l in lines.iter().skip_while(|l| l.line_no <= first_code.line_no) { - if l.kind == LineKind::Code && l.text.trim() == "---" { - return Some(l.line_no + 1); - } - } - Some(1) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::view::annot::build_view_annots; - - #[test] - fn document_keeps_inc_prose_narration() { - let src = include_str!("../../tests/markup-v03/inc-prose.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_document(&module, src, &[]); - assert!( - html.contains("对于输入变量") && html.contains("我们执行操作"), - "narration stripped: {html}" - ); - assert!(html.contains("mq-anchor"), "expected anchors: {html}"); - assert!(html.contains("document-surface"), "{html}"); - // Marker surface: no raw ** delimiters around assign. - assert!( - !html.contains("**n=n+1**") && !html.contains("**n = n + 1**"), - "raw bold delimiters leaked: {html}" - ); - assert!(html.contains("n=n+1") || html.contains(">n=n+1<") || html.contains("n=n+1"), "{html}"); - } - - #[test] - fn document_strips_marker_delimiters() { - let src = "# main\n\n**x = 1**\n"; - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_document(&module, src, &[]); - assert!(html.contains("mq-code"), "{html}"); - assert!(!html.contains("**x = 1**"), "{html}"); - assert!(html.contains(">x = 1<") || html.contains("x = 1"), "{html}"); - } - - #[test] - fn document_renders_table_and_lists() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_document(&module, src, &[]); - assert!(html.contains("doc-table") || html.contains("仓库") && html.contains("data-logic-kind=\"link\""), - "{html}" - ); - } - - #[test] - fn document_annot_demo_keeps_narration_and_control_flow() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let annots = build_view_annots(&module, src, &cap); - let html = render_module_document(&module, src, &annots); - assert!(html.contains("本页演示"), "{html}"); - assert!(html.contains("annot-band"), "{html}"); - assert!( - annots - .iter() - .any(|a| a.kind == crate::view::annot::AnnotKind::LoopFrame - || (a.kind == crate::view::annot::AnnotKind::Bind && a.loop_id.is_some())), - "loop frame / item bind missing: {:?}", - cap.view_trace - ); - assert!( - annots.iter().any(|a| a.kind == crate::view::annot::AnnotKind::Branch), - "branch annot missing: {:?}", - cap.view_trace - ); - } - - #[test] - fn inferred_param_chip_shows_call_value() { - let src = include_str!("../../tests/markup-v03/inc-prose.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let add = module - .functions - .iter() - .find(|f| f.name == "加一函数") - .expect("加一函数"); - assert!(add.params.iter().any(|p| p.name == "n" && p.inferred)); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let annots = build_view_annots(&module, src, &cap); - let html = render_module_document(&module, src, &annots); - assert!( - html.contains(r#"data-param-name="n""#) && html.contains("chip inferred"), - "inferred param chip missing: {html}" - ); - assert!( - html.contains(r#"class="chip-val">=37"#) || html.contains("chip-val\">=37"), - "expected param chip value from call frame: {html}" - ); - } - - #[test] - fn document_frame_pickers_and_all_arms() { - let src = include_str!("../../tests/view/document-annot-demo.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let annots = build_view_annots(&module, src, &cap); - let html = render_module_document(&module, src, &annots); - // All three return arms of 等级说明 stay in the source surface. - assert!(html.contains("均分很高"), "arm1 return missing: {html}"); - assert!(html.contains("已过线"), "arm2 return missing: {html}"); - assert!(html.contains("建议安排复习周"), "arm3 return missing: {html}"); - assert!(html.contains("arm-miss"), "expected dimmed arms: {html}"); - assert!(html.contains("arm-taken"), "expected taken arm: {html}"); - // Call picker uses numeric call_id values (not cfN ids). - assert!(html.contains("call-picker"), "{html}"); - assert!( - html.contains(r#"value="2""#) || html.contains(r#"value="3""#), - "call picker should use numeric call_id: {html}" - ); - // Loop iteration picker defaults to last. - assert!(html.contains("loop-picker"), "{html}"); - assert!(html.contains("分数表[3]"), "expected last-iter binding: {html}"); - // Branch chips carry call_id for frame filter. - assert!( - html.contains(r#"data-call-id=""#) || html.contains("data-call-id="), - "{html}" - ); - } - - #[test] - fn narrative_text_fence_renders_as_code_card() { - let src = r#"# main - -```text -marqdo ext add web -marqdo ext add quantum -``` - -> print text=ok -"#; - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_document(&module, src, &[]); - assert!( - html.contains(r#"data-lang="text""#) && html.contains("code-body"), - "text fence should be a code card: {html}" - ); - assert!( - html.contains("marqdo ext add web\nmarqdo ext add quantum"), - "fence body newlines preserved: {html}" - ); - assert!( - !html.contains("text marqdo"), - "must not collapse fence into inline code: {html}" - ); - } - - #[test] - fn prose_calls_and_param_decl_get_chips() { - let src = r#"# main - -Try **greet who="a"** and **greet who="b"**. - -## greet - -When we meet `who`, we **print text="Hi, `who`!"** and close with*None*. -"#; - let module = crate::parse::parse_source(src).unwrap(); - let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); - let annots = build_view_annots(&module, src, &cap); - assert!( - annots - .iter() - .filter(|a| a.kind == crate::view::annot::AnnotKind::Call) - .count() - >= 3, - "expected greet×2 + print call events: {:?}", - cap.view_trace.events - ); - assert!( - annots.iter().any(|a| { - a.kind == crate::view::annot::AnnotKind::Bind && a.label == "who" - }), - "param Decl bind missing: {annots:?}" - ); - let html = render_module_document(&module, src, &annots); - assert!(html.contains("annot-call"), "{html}"); - assert!(html.contains("annot-bind"), "{html}"); - assert!(html.contains("Hi, a!") || html.contains("Hi, b!"), "{html}"); - // Dual greet call sites each get a non-empty annot id. - let greet_ids: Vec<_> = html - .match_indices("mq-code") - .filter(|_| true) - .collect(); - assert!( - html.matches(r#"data-annot-id="c"#).count() >= 2 - || html.contains(r#"data-annot-id="c"#), - "expected call annot ids on greet marks: {html}" - ); - let _ = greet_ids; - // Last-frame who bind must not be buried in overflow (frame-aware density). - assert!( - !html.contains(r#"annot-bind annot-chip-overflow"#) - || html.contains(r#"annot-label">who"#), - "who bind should be visible for default (last) call frame: {html}" - ); - // Prefer: no overflow on bind chips when last frame has ≤4 chips. - let bind_overflow = html.matches("annot-bind annot-chip-overflow").count(); - assert_eq!( - bind_overflow, 0, - "default frame who/print/return must not overflow: {html}" - ); - } -} - -#[cfg(test)] -mod occl_render_tests { - use super::render_module_document; - - fn div_balance(html: &str) -> i32 { - let mut depth = 0i32; - let b = html.as_bytes(); - let mut i = 0usize; - while i + 3 < b.len() { - if b[i] == b'<' { - if i + 4 <= b.len() && &b[i..i + 4] == b"')) { - depth += 1; - } else if i + 6 <= b.len() && &b[i..i + 6] == b"
      " { - depth -= 1; - } - } - i += 1; - } - depth - } - - #[test] - fn occlusion_line_closes_doc_block() { - let src = r#"--- -markup: occlusion ---- - -# main - -`v` = [描述](1) -"#; - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_document(&module, src, &[]); - assert!(html.contains("doc-occl"), "{html}"); - assert_eq!( - div_balance(&html), - 0, - "occlusion must not leave .doc-block open: {html}" - ); - assert!( - html.contains("doc-occl") && html.contains("
      "), - "doc-block around occlusion must close: {html}" - ); - } -} - - -/// Explain the existing core surface, including compatibility constructs, without executing it. -fn render_syntax_guide() -> String { - let mut html = String::from( - r#"
      怎样读这份可执行文档

      正文说明意图,标记指出哪些片段会执行。遮蔽只在正文显示动作说明,实际逻辑放在侧注;阅读、展开与定位都不会运行代码。

      "#, - ); - for (id, surface) in crate::parse::CORE_CONSTRUCTS { - let meaning=match *id { - "narrative"=>"作者的解释,按普通 Markdown 阅读。", "blank"=>"分隔叙述与结构,不是计算步骤。", - "heading-unit"=>"一级标题声明对象或入口,更深标题声明函数;说明按钮可查看输入、返回与依据。", - "call-line"=>"调用函数;实际执行结果另有标注。", "branch-list"=>"按条件选择分支,不是普通编号说明。", - "loop-list"=>"重复或遍历结构;迭代选择器只切换已有运行记录。", "param"=>"兼容的显式形参;新库优先在叙述中声明参数,标题下的表格解释契约。", - "table"=>"未绑定的契约表是说明;绑定表按列、行和 @ 形态构成数据。", "fence"=>"代码块;绑定的外语代码与普通示例区分展示,数学公式另有公式卡片。", - "hr"=>"分隔内容,不能把分隔线当作函数返回。", "writeback"=>"程序写回的结果,区别于作者原始正文。", - "ident"=>"叙述中的参数或变量;默认值跟在名称之后。", "bold-code"=>"执行语句:赋值、调用或计算;不是打印,也不是返回。", - "italic-return"=>"返回表达式;句中以返回、Return 等明确引出。", "empty-return"=>"显式返回空值或结束当前函数。", - "link-index"=>"正文显示描述,侧注按函数与参数、可跳转链接、结构化内容展示括号内的细节;空括号表示待补充实际逻辑。阅读不会执行调用。classic 模式保留旧链接取元。", - "bracket-call"=>"兼容的带修饰调用;不能把任意普通链接当作执行授权。", "footnote-index"=>"兼容的脚注取元;当前库优先用 access 读取集合。", - "soft-emphasis"=>"普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。", _=>"按源码中的真实结构阅读。" - }; - html.push_str(&format!( - r#""#, - escape(id), - escape(surface), - escape(meaning) - )); - } - html.push_str("
      标记阅读含义
      {}{}
      "); - html -} - -#[cfg(test)] -mod readable_occlusion_tests { - use super::*; - fn render(source: &str) -> String { - let module = crate::load::parse_source_auto(source).unwrap(); - render_module_document(&module, source, &[]) - } - #[test] - fn prose_keeps_multiple_actions_and_returns_without_exposing_payloads() { - let html=render("# main\n\n先**a = [读取甲](1 + 2)**,接着**b = [读取乙](3 + 4)**,最后返回*[合计](a + b)*。\n"); - let line = html - .split("doc-line doc-prose-line\"") - .nth(1) - .unwrap() - .split("") - .next() - .unwrap(); - for text in ["先", "读取甲", "接着", "读取乙", "最后返回", "合计"] { - assert!(line.contains(text), "{line}"); - } - for code in ["1 + 2", "3 + 4", "a + b", "[读取甲]"] { - assert!(!line.contains(code), "payload leaked into prose: {line}"); - } - assert_eq!( - html.matches("class=\"annot-chip annot-implementation\"") - .count(), - 3 - ); - assert!(html.contains("data-syntax=\"return\"")); - assert!(html.contains(">1 + 2
      ") && html.contains(">a + b
      ")); - } - #[test] - fn empty_logic_quotes_nested_parentheses_and_html_are_safe() { - let html = - render("# main\n\n得到**a = [括号](str(value=\") \"))**,再**b = [待接]()**。\n"); - assert!(html.contains("待补充实际逻辑")); - assert!(html.contains("<tag>") && !html.contains("")); - assert!(html.contains("str(value=") <tag>")")); - assert!(html.contains("当前空遮蔽返回 None")); - } - #[test] - fn table_links_and_prose_content_are_readable_with_exact_source_notes() { - let html = render("# main\n\n| 内容 | 说明 |\n| --- | --- |\n| [指南](guide.mq.md) | [解释](plain explanatory text with **emphasis**) |\n\n*None*\n"); - assert!(html.contains(">指南")); - assert!(html.contains("emphasis")); - assert_eq!(html.matches("class=\"annot-chip annot-implementation\"").count(), 2); - assert_eq!(html.matches("data-logic-kind=\"link\"").count(), 1); - assert_eq!(html.matches("data-logic-kind=\"content\"").count(), 1); - } - #[test] - fn navigation_and_quoted_links_are_not_executable_occlusions() { - let html=render("# main\n\n参阅 [普通链接](https://example.com/guide)。\n\n得到**literal = \"[数据链接](should_stay_text)\"**,以及**value = [真实动作](5)**,参阅 [混合链接](https://example.com/mixed)。\n"); - assert!(html.contains("href=\"https://example.com/guide\"")); - assert!(html.contains("href=\"https://example.com/mixed\"")); - assert_eq!( - html.matches("class=\"annot-chip annot-implementation\"") - .count(), - 3 - ); - assert!(html.contains("[数据链接](should_stay_text)")); - assert_eq!(html.matches("data-logic-kind=\"link\"").count(), 2); - assert_eq!(html.matches("文档引用 · 阅读不会执行").count(), 2); - let classic = render("---\nmarkup: classic\n---\n# main\n\n**value = [key](`record`)**\n"); - assert!(!classic.contains("class=\"annot-chip annot-implementation\"")); - } - #[test] - fn semantic_loop_labels_and_every_core_construct_are_explained() { - let html=render("# main\n\n`items` =\n\n| n |\n|---|\n| 1 |\n| 2 |\n\n- [逐项处理](遍历 items 为 item)\n **out = item + 1**\n"); - assert!(html.contains("逐项处理")); - assert!(html.contains("遍历 items 为 item")); - for (id, _) in crate::parse::CORE_CONSTRUCTS { - assert!( - html.contains(&format!("data-construct-id=\"{id}\"")), - "missing {id}" - ); - } - } -} diff --git a/src/view/html.rs b/src/view/html.rs deleted file mode 100755 index 1c577c5..0000000 --- a/src/view/html.rs +++ /dev/null @@ -1,4572 +0,0 @@ -//! Shared live/static reader shell with an offline, botanical editorial theme. - -use std::path::{Component, Path, PathBuf}; - -use crate::view::render::FileViewModel; - -pub fn escape(s: &str) -> String { - s.chars() - .map(|c| match c { - '&' => "&".into(), - '<' => "<".into(), - '>' => ">".into(), - '"' => """.into(), - '\'' => "'".into(), - _ => c.to_string(), - }) - .collect() -} - -/// How navigation hrefs are built. -#[derive(Debug, Clone)] -pub enum LinkMode { - /// Live server: `/file?path=…` - Live, - /// Static export: relative links under `pages/`. - /// `from` is the source rel path of the current page (`None` = index.html). - Static { from: Option }, -} - -fn stylesheet() -> &'static str { - // Inspired by Apple HIG clarity + docs-site layouts (sticky sidebar, readable - // center column, system grays). Monochrome only; no remote fonts. - r#" -:root { - --bg: #f5f5f7; - --surface: #ffffff; - --ink: #1d1d1f; - --muted: #6e6e73; - --line: #d2d2d7; - --line-strong: #1d1d1f; - --fill: #f5f5f7; - --hover: #e8e8ed; - --focus: #0071e3; - --fail-bg: #fff5f5; - --ok-bg: #f5f5f7; - --radius: 12px; - --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; - --syn-fg: #f0f0f0; - --syn-comment: #6a9955; - --syn-keyword: #569cd6; - --syn-string: #ce9178; - --syn-number: #b5cea8; - --syn-variable: #9cdcfe; - --syn-function: #dcdcaa; - --syn-type: #4ec9b0; - --syn-meta: #c586c0; -} -* { box-sizing: border-box; } -html { scroll-behavior: smooth; } -[id] { scroll-margin-top: 4.5rem; } -.knowledge-block summary { cursor: pointer; font-weight: 600; } -.knowledge-hint { color: var(--muted); font-size: 0.85em; margin: 0.25rem 0 0.5rem; } -.knowledge-error .err { color: #8b1a1a; } -@media print { - .topbar, .stdin-form, .stream-panel, .exec-clear, #notebook-bar, nav { display: none !important; } - .knowledge-block, .source-block { display: block; } -} -@media (prefers-reduced-motion: reduce) { - html { scroll-behavior: auto; } -} -body { - margin: 0; - min-height: 100vh; - font-family: var(--sans); - color: var(--ink); - background: var(--bg); - line-height: 1.47; - font-size: 17px; - -webkit-font-smoothing: antialiased; - text-rendering: optimizeLegibility; -} -a { color: var(--ink); text-decoration: none; } -a:hover { opacity: 0.72; } -a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } -#nav-toggle { position: absolute; opacity: 0; pointer-events: none; } -.topbar { - display: none; - align-items: center; - gap: 0.75rem; - padding: 0.7rem 1rem; - border-bottom: 1px solid var(--line); - background: rgba(255,255,255,0.86); - backdrop-filter: saturate(180%) blur(16px); - -webkit-backdrop-filter: saturate(180%) blur(16px); - position: sticky; - top: 0; - z-index: 20; -} -.topbar .brand { margin: 0; font-size: 1.05rem; font-weight: 600; letter-spacing: -0.022em; } -.brand-row { - display: flex; - align-items: center; - gap: 0.55rem; -} -.brand-row .brand { margin: 0; } -.logo { - width: 1.75rem; - height: 1.75rem; - object-fit: contain; - flex-shrink: 0; - border-radius: 6px; -} -.topbar .logo { width: 1.45rem; height: 1.45rem; } -.nav-brand .logo { width: 2rem; height: 2rem; } -.nav-btn { - appearance: none; - border: 1px solid var(--line); - background: var(--surface); - color: var(--ink); - border-radius: 10px; - width: 2.35rem; - height: 2.35rem; - font-size: 1.05rem; - line-height: 1; - cursor: pointer; - display: inline-flex; - align-items: center; - justify-content: center; - transition: background 0.15s ease, border-color 0.15s ease; -} -.nav-btn:hover { background: var(--hover); } -.shell { - display: grid; - grid-template-columns: 280px minmax(0, 1fr); - min-height: 100vh; - max-width: 1680px; - margin: 0 auto; -} -.nav { - border-right: 1px solid var(--line); - padding: 1.75rem 1rem 2.5rem 1.15rem; - overflow: auto; - background: var(--bg); - position: sticky; - top: 0; - align-self: start; - height: 100vh; -} -.nav-brand { display: block; padding: 0 0.35rem; margin-bottom: 1.15rem; } -.nav-brand .tagline { margin: 0.1rem 0 0; } -.brand { - font-size: 1.35rem; - font-weight: 700; - letter-spacing: -0.03em; - margin: 0 0 0.1rem; -} -.tagline { - color: var(--muted); - font-size: 0.78rem; - margin: 0; - font-weight: 500; -} -.nav > h2:first-of-type { margin-top: 0.35rem; } -.nav h2 { - font-size: 0.68rem; - text-transform: uppercase; - letter-spacing: 0.09em; - color: var(--muted); - font-weight: 600; - margin: 1.15rem 0.35rem 0.45rem; -} -.nav ul { list-style: none; padding: 0; margin: 0; } -.nav li { margin: 0.08rem 0; } -.nav a.file { - display: block; - padding: 0.42rem 0.65rem; - border-radius: 8px; - border-bottom: none; - color: var(--ink); - font-family: var(--mono); - font-size: 0.78rem; - transition: background 0.12s ease, color 0.12s ease; -} -.nav a.file:hover { background: var(--hover); opacity: 1; } -.nav a.file.active { - background: var(--ink); - color: #fff; - opacity: 1; - font-weight: 500; -} -.nav-root { margin: 0; padding: 0; list-style: none; } -.folder { - margin: 0.55rem 0 0.2rem; - border: none; -} -.folder > summary { - list-style: none; - cursor: pointer; - user-select: none; - color: var(--muted); - font-size: 0.72rem; - font-weight: 600; - letter-spacing: 0.01em; - padding: 0.35rem 0.45rem; - border-radius: 8px; - display: flex; - align-items: center; - gap: 0.35rem; - transition: background 0.12s ease, color 0.12s ease; -} -.folder > summary::-webkit-details-marker { display: none; } -.folder > summary::before { - content: ""; - width: 0; - height: 0; - border-style: solid; - border-width: 4px 0 4px 6px; - border-color: transparent transparent transparent var(--muted); - opacity: 0.85; - transition: transform 0.12s ease; - flex-shrink: 0; -} -.folder[open] > summary::before { - transform: rotate(90deg); -} -.folder > summary:hover { - background: var(--hover); - color: var(--ink); -} -.folder > ul { - list-style: none; - padding: 0.1rem 0 0.15rem 0.55rem; - margin: 0; -} -.panel-wrap { - min-width: 0; - overflow: auto; - background: var(--bg); - /* Content-pane width (excludes file nav) drives outline stacking — not the - * viewport. A 960px viewport media query wrongly put Functions/Variables - * under a tall Structure while the left nav was still visible. */ - container-type: inline-size; - container-name: mq-panel; -} -main.panel { - padding: 2rem 2.25rem 3.5rem; - margin: 0; - width: 100%; - max-width: 76rem; -} -h1.page { - font-size: clamp(1.75rem, 2.4vw, 2.35rem); - font-weight: 700; - letter-spacing: -0.035em; - margin: 0 0 0.3rem; - line-height: 1.15; -} -.meta { - color: var(--muted); - font-size: 0.88rem; - margin: 0 0 1.75rem; - font-family: var(--mono); -} -.status-pill { - display: inline-block; - font-size: 0.68rem; - font-weight: 600; - letter-spacing: 0.04em; - text-transform: uppercase; - padding: 0.18rem 0.5rem; - border-radius: 999px; - border: 1px solid var(--line); - margin-left: 0.5rem; - vertical-align: middle; -} -.status-pill.ok { background: var(--surface); color: var(--muted); } -.status-pill.pending { background: var(--surface); color: var(--ink); border-color: var(--ink); } -.status-pill.fail { background: var(--ink); color: #fff; border-color: var(--ink); } -section.block { margin: 2rem 0; } -section.block > h2 { - font-size: 0.72rem; - text-transform: uppercase; - letter-spacing: 0.08em; - color: var(--muted); - font-weight: 600; - margin: 0 0 0.85rem; -} -.stdin-form { - margin: 0 0 1rem; - display: grid; - gap: 0.45rem; - max-width: 36rem; -} -.stdin-form label { - font-size: 0.85rem; - color: var(--ink); -} -.stdin-form .hint { - color: var(--muted); - font-size: 0.8rem; - margin-left: 0.35rem; -} -.stdin-form textarea { - font: inherit; - font-family: var(--mono); - font-size: 0.9rem; - padding: 0.65rem 0.75rem; - border: 1px solid var(--line); - border-radius: 8px; - background: var(--surface); - color: var(--ink); - resize: vertical; - min-height: 4.5rem; -} -.stdin-form button { - justify-self: start; - font: inherit; - font-size: 0.9rem; - font-weight: 600; - padding: 0.5rem 1rem; - border: 1px solid var(--ink); - border-radius: 8px; - background: var(--ink); - color: #ffffff; - cursor: pointer; -} -.stdin-form button:hover { opacity: 0.88; } -.stdin-form button:focus-visible { - outline: 2px solid var(--focus); - outline-offset: 2px; -} -.structure { - background: var(--surface); - border: 1px solid var(--line); - border-radius: var(--radius); - padding: 0.35rem 0.15rem; - box-shadow: 0 1px 0 rgba(0,0,0,0.02); -} -.card { - border: none; - border-bottom: 1px solid var(--line); - border-radius: 0; - padding: 0.85rem 1.1rem; - margin: 0; - background: transparent; -} -.card:last-child { border-bottom: none; } -.fun-card, .call-card, .branch-card, .loop-card, .ret-card { - border-left: 2px solid var(--line-strong); - padding-left: calc(1.1rem - 2px); -} -.comment-card { - border-left: 2px solid var(--line); - background: transparent; - padding-left: calc(1.1rem - 2px); -} -/* Document surface (Browse Structure) */ -.document-surface { - padding: 0.5rem 1rem 1.25rem; - color: var(--ink); - line-height: 1.55; -} -.doc-imports { margin: 0 0 0.85rem; } -.doc-fun { - margin: 1.1rem 0 0.65rem; - padding-bottom: 0.35rem; - border-bottom: 1px solid var(--line); -} -.doc-fun-title { - margin: 0; - font-size: 1.15rem; - font-weight: 650; - letter-spacing: -0.01em; -} -.doc-fun-bar { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.5rem 1rem; -} -.call-picker-label { - font-size: 0.78rem; - color: var(--muted); - display: inline-flex; - align-items: center; - gap: 0.35rem; -} -.call-picker, .loop-picker { - font-size: 0.78rem; - padding: 0.2rem 0.4rem; - border: 1px solid var(--line); - border-radius: 8px; - background: var(--surface); - color: var(--ink); -} -.loop-picker-label { - font-size: 0.78rem; - color: var(--muted); - display: inline-flex; - align-items: center; - gap: 0.35rem; -} -li.doc-list-meta { - list-style: none; - margin: 0.25rem 0 0.5rem; - margin-left: -1.25rem; -} -.doc-block { position: relative; margin: 0.55rem 0 0.85rem; } -.doc-block > .annot-leaders { - position: absolute; - inset: 0; - pointer-events: none; - overflow: visible; - z-index: 1; /* below .annot-chips */ -} -.doc-block > .annot-leaders svg { - position: absolute; - left: 0; - top: 0; - overflow: visible; -} -.doc-block.is-keyed > .annot-leaders { display: none; } -.doc-block.doc-exec[style*="--doc-indent"] { - margin-left: calc(var(--doc-indent, 1) * 1.5rem); -} -.doc-prose { color: var(--ink); } -.doc-prose > :first-child { margin-top: 0; } -.doc-prose > :last-child { margin-bottom: 0; } -.doc-line { margin: 0.15rem 0; } -/* `` M8: occlusion statement — description reads as prose, payload as code. - Stubs (empty payload) get a badge so "未接通" is visible at a glance. */ -.doc-occl { - display: flex; - align-items: baseline; - flex-wrap: wrap; - gap: 0.4rem; - margin: 0.3rem 0; -} -.occl-pre { - font-family: var(--mono); - font-size: 0.86em; - color: var(--muted); -} -.occl-label { - color: var(--ink); -} -.occl-code { - font-family: var(--mono); - font-size: 0.84em; - color: var(--ink); - background: var(--fill); - border: 1px solid var(--line); - border-radius: 6px; - padding: 0.02rem 0.38rem; -} -.occl-card { - display: flex; - align-items: baseline; - flex-wrap: wrap; - gap: 0.4rem; -} -.occl-card .occl-label { font-weight: 500; } -.occl-card .occl-code { font-size: 0.9em; } -.occl-stub { - font-size: 0.72em; - line-height: 1.5; - padding: 0.02rem 0.42rem; - border-radius: 999px; - background: rgba(255, 159, 10, 0.18); - color: #9a5b00; - border: 1px solid rgba(255, 159, 10, 0.35); -} -.doc-prose-line { white-space: pre-wrap; } -.doc-stmt, .doc-call, .doc-cond { - font-family: var(--mono); - font-size: 0.92em; -} -.mq-call-gt { color: var(--muted); margin-right: 0.25rem; } -.mq-else { font-family: var(--mono); color: var(--muted); font-style: italic; } -.doc-table-wrap { overflow-x: auto; } -.doc-table { - border-collapse: collapse; - width: auto; - min-width: 12rem; - font-size: 0.92rem; - margin: 0.35rem 0; -} -.doc-table th, .doc-table td { - border: 1px solid var(--line); - padding: 0.35rem 0.7rem; - text-align: left; -} -.doc-table th { - background: var(--fill); - font-weight: 600; -} -ul.doc-loop, ol.doc-branch { - margin: 0.5rem 0 0.75rem; - padding-left: calc(var(--doc-indent, 1) * 1.5rem + 1.25rem); -} -.doc-list-item { margin: 0.45rem 0; } -.doc-list-head { font-family: var(--mono); font-size: 0.92em; } -.doc-list-body { - margin: 0.35rem 0 0.2rem; - padding-left: 1.5rem; - border-left: 2px solid var(--line); -} -.doc-list-item.arm-taken { - border-left: 3px solid #bf5af2; - padding-left: 0.55rem; - margin-left: -0.15rem; -} -.doc-list-item.arm-taken > .doc-list-head { font-weight: 600; } -.doc-list-item.arm-miss { opacity: 0.45; } -.doc-code { - font-family: var(--mono); - font-size: 0.9em; - white-space: pre-wrap; -} -.mq-anchor { - background: transparent; - color: inherit; - padding: 0 0.05em; - border-radius: 0; - border-bottom: 2px solid var(--line-strong); - font-style: normal; - font-weight: inherit; - cursor: default; -} -.mq-anchor.mq-decl { - border-bottom-color: #5ac8fa; - font-family: var(--mono); - font-size: 0.95em; -} -.mq-anchor.mq-code { - border-bottom-color: #ff9f0a; - font-family: var(--mono); - font-size: 0.95em; - font-weight: 600; -} -.mq-anchor.mq-return { - border-bottom-color: #30d158; - font-family: var(--mono); - font-size: 0.95em; - font-style: italic; -} -.mq-anchor.is-focus { background: rgba(0,0,0,0.04); } -.annot-band { - position: relative; - margin: 0.55rem 0 0.15rem; - min-height: 1.6rem; - padding-top: 1.15rem; /* room for mid→mid leaders (rail + stub) */ - z-index: 1; -} -/* Band-local leaders kept for keyed fallback; geometry uses .doc-block > .annot-leaders */ -.annot-band > .annot-leaders { display: none; } -.annot-leader { - fill: none; - stroke-width: 1.5; - stroke-linecap: round; - stroke-linejoin: round; - pointer-events: none; -} -.annot-chips { - display: flex; - flex-wrap: wrap; - gap: 0.45rem 0.7rem; - position: relative; - z-index: 3; /* chips above leaders */ -} -.annot-chip { - display: inline-flex; - align-items: baseline; - gap: 0.35rem; - max-width: 100%; - margin: 0; - padding: 0.22rem 0.5rem; - border: 1px solid var(--line); - border-left-width: 3px; - border-radius: 8px; - background: var(--fill); - color: var(--ink); - font-family: var(--mono); - font-size: 0.72rem; - cursor: pointer; - text-align: left; -} -/* Author `display:inline-flex` must not defeat frame filtering. */ -.annot-chip[hidden], -.annot-chip.is-frame-hidden { - display: none !important; -} -.annot-chip:hover, -.annot-chip.is-focus { background: #fff; } -.annot-chip.annot-bind { border-left-color: #5ac8fa; } -.annot-chip.annot-return { border-left-color: #30d158; } -.annot-chip.annot-call, -.annot-chip.annot-expr, -.annot-chip.annot-code { border-left-color: #ff9f0a; } -.annot-chip.annot-branch { border-left-color: #bf5af2; } -.annot-chip.annot-loop { border-left-color: #64d2ff; } -.annot-chip.annot-writeback { border-left-color: #8e8e93; } -.annot-chip.annot-chip-overflow { display: none !important; } -.annot-band.is-expanded .annot-chip.annot-chip-overflow:not([hidden]):not(.is-frame-hidden) { - display: inline-flex !important; -} -.annot-label { color: var(--muted); font-weight: 600; } -.annot-value { color: var(--ink); word-break: break-word; } -.annot-more { - border: 1px dashed var(--line); - border-radius: 8px; - background: transparent; - color: var(--muted); - font-size: 0.72rem; - padding: 0.22rem 0.45rem; - cursor: pointer; -} -.annot-band.is-keyed .annot-chip::before, -.doc-block.is-keyed .annot-chip::before { - content: attr(data-annot-key) " "; - color: var(--muted); -} -@media (max-width: 640px) { - .annot-band { padding-top: 0.25rem; } - .doc-block > .annot-leaders { display: none; } -} -@media (prefers-reduced-motion: reduce) { - .doc-block > .annot-leaders { display: none; } -} -.badge { - display: inline-block; - font-family: var(--mono); - font-size: 0.66rem; - padding: 0.14rem 0.4rem; - border-radius: 6px; - border: 1px solid var(--line); - background: var(--fill); - color: var(--ink); - margin-right: 0.4rem; - font-weight: 600; - letter-spacing: 0.02em; -} -.params { margin: 0.35rem 0 0; } -.chip { - display: inline-block; - font-family: var(--mono); - font-size: 0.72rem; - padding: 0.14rem 0.45rem; - margin: 0.15rem 0.15rem 0 0; - border-radius: 6px; - background: var(--fill); - border: 1px solid transparent; - color: var(--ink); -} -.chip.inferred { - border-style: dashed; - border-color: var(--line); - opacity: 0.92; -} -.chip.inferred::after { - content: " ↑"; - font-size: 0.65em; - opacity: 0.7; -} -.chip .chip-val { - font-weight: 500; - opacity: 0.78; - font-family: var(--mono); - font-size: 0.92em; -} -.chip .chip-val:empty { - display: none; -} -.nested { - margin: 0.45rem 0 0.15rem 0.15rem; - padding-left: 0.85rem; - border-left: 1px solid var(--line); -} -.arm { - margin: 0.4rem 0; - padding: 0.55rem 0.7rem; - background: var(--fill); - border-radius: 10px; - border: 1px solid transparent; -} -.exec-clear { - float: right; - font: inherit; - font-size: 0.72rem; - padding: 0.2rem 0.6rem; - border: 1px solid var(--line); - border-radius: 999px; - background: var(--surface); - color: var(--muted); - cursor: pointer; -} -.exec-clear:hover { color: var(--ink); border-color: var(--muted); } -body.notebook-page .exec-clear { - border-color: var(--nb-border); - background: var(--nb-surface-2); - color: var(--nb-text); -} -body.notebook-page .exec-clear:hover { border-color: var(--nb-accent); color: var(--nb-strong); } -.out, .source { - font-family: var(--mono); - font-size: 0.82rem; - white-space: pre-wrap; - background: var(--surface); - border-radius: var(--radius); - padding: 1rem 1.15rem; - border: 1px solid var(--line); - line-height: 1.55; - box-shadow: 0 1px 0 rgba(0,0,0,0.02); -} -.stmt { display: block; } -.stmt-body { min-width: 0; } -.stmt-body > .card { border-bottom: 1px solid var(--line); } -.structure > .stmt:last-child > .stmt-body > .card, -.structure > .card:last-child { border-bottom: none; } -.struct-wrap { - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(9.5rem, 12.5rem); - gap: 0.75rem; - align-items: start; -} -/* Stack only when the *panel* is too narrow for Structure + outline rail. - * Prefer keeping the rail beside the doc at tablet widths (matches ≤800px - * shell collapse in doc/design/view.md). When stacked, pull the rail above - * so it is not buried under a long document. */ -@container mq-panel (max-width: 32rem) { - .struct-wrap { grid-template-columns: 1fr; } - .outline-rail { - order: -1; - position: static; - } - .outline-panel { position: static; } -} -.outline-rail { - position: sticky; - top: 1rem; - display: flex; - flex-direction: column; - gap: 0.55rem; - min-width: 0; -} -.outline-section { - background: var(--surface); - border: 1px solid var(--line); - border-radius: var(--radius); - padding: 0.35rem 0.55rem 0.55rem; - box-shadow: 0 1px 0 rgba(0,0,0,0.02); -} -.outline-summary { - cursor: pointer; - font: 600 0.72rem/1.3 var(--sans); - color: var(--muted); - letter-spacing: 0.02em; - text-transform: uppercase; - list-style: none; - padding: 0.2rem 0 0.35rem; -} -.outline-summary::-webkit-details-marker { display: none; } -.outline-panel { - position: static; - background: transparent; - border: none; - border-radius: 0; - padding: 0; - box-shadow: none; -} -.vars-panel { - max-height: min(52vh, 30rem); - overflow: auto; - font: 0.72rem/1.35 var(--sans); - padding-right: 0.1rem; -} -.vars-list { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; - gap: 0.45rem; -} -.vars-card { - display: block; - margin: 0; - padding: 0.45rem 0.5rem 0.5rem; - border: 1px solid var(--line); - border-radius: 10px; - background: #fff; - cursor: pointer; - transition: border-color 0.12s ease, box-shadow 0.12s ease; -} -.vars-card:hover { - border-color: #a1a1a6; - box-shadow: 0 4px 14px rgba(0,0,0,0.06); -} -.vars-card:focus-visible { - outline: 2px solid var(--focus); - outline-offset: 2px; -} -.vars-head { - display: flex; - flex-wrap: wrap; - align-items: baseline; - justify-content: space-between; - gap: 0.25rem 0.55rem; - margin-bottom: 0.35rem; -} -.vars-name { - font: 600 0.8rem/1.25 var(--mono); - color: var(--ink); - word-break: break-all; -} -.vars-kind { - font: 500 0.65rem/1.2 var(--sans); - color: var(--muted); -} -.vars-preview { - max-height: 7.5rem; - overflow: hidden; - position: relative; - border-radius: 8px; - background: #fafafa; - border: 1px solid var(--line); - padding: 0.35rem; - pointer-events: none; -} -.vars-preview::after { - content: ""; - position: absolute; - left: 0; right: 0; bottom: 0; - height: 1.6rem; - background: linear-gradient(transparent, #fafafa); - pointer-events: none; -} -.vars-preview .matrix-wrap { - border: none; - padding: 0.25rem; - background: transparent; -} -.vars-preview .matrix-cell { - min-width: 2.4rem; - padding: 0.28rem 0.35rem; - font-size: 0.68rem; -} -.vars-muted { color: var(--muted); } -.vars-peek { font-size: 0.68rem; } -.math-sm .katex-display { font-size: 0.92em; margin: 0.1rem 0; } -.vars-table { - width: 100%; - border-collapse: collapse; - font: 0.72rem/1.35 var(--mono); -} -.vars-table th, -.vars-table td { - border: 1px solid var(--line); - padding: 0.15rem 0.3rem; - text-align: left; - vertical-align: top; - word-break: break-word; -} -.vars-table th { - background: #f5f5f7; - font-weight: 600; - color: var(--muted); -} -.vars-idx, .vars-key { color: var(--muted); white-space: nowrap; } -.vars-scalar { white-space: pre-wrap; } -.vars-empty, .vars-skipped { color: var(--muted); margin: 0.2rem 0; } -.vars-nested > summary { cursor: pointer; color: var(--muted); } -.var-dialog { - border: none; - padding: 0; - max-width: min(920px, 94vw); - max-height: min(88vh, 900px); - width: min(920px, 94vw); - border-radius: 18px; - background: transparent; - box-shadow: none; -} -.var-dialog::backdrop { - background: rgba(29, 29, 31, 0.42); - backdrop-filter: blur(6px); -} -.var-dialog-sheet { - background: linear-gradient(180deg, #fffef9 0%, #ffffff 42%); - border: 1px solid var(--line); - border-radius: 18px; - box-shadow: 0 24px 80px rgba(0,0,0,0.22); - overflow: hidden; - display: flex; - flex-direction: column; - max-height: min(88vh, 900px); -} -.var-dialog-head { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - padding: 1rem 1.15rem; - border-bottom: 1px solid var(--line); - background: rgba(255,255,255,0.85); -} -.var-dialog-head h2 { - margin: 0; - font: 650 1.05rem/1.25 var(--mono); - color: var(--ink); - word-break: break-all; -} -.var-dialog-close { - appearance: none; - width: 2rem; - height: 2rem; - border-radius: 999px; - border: 1px solid var(--line); - background: #f5f5f7; - color: var(--ink); - font-size: 1.15rem; - line-height: 1; - cursor: pointer; -} -.var-dialog-close:hover { background: var(--hover); } -.var-dialog-body { - padding: 1.15rem 1.25rem 1.4rem; - overflow: auto; - font: 0.85rem/1.45 var(--sans); -} -.var-rich-meta { - display: flex; - flex-wrap: wrap; - gap: 0.4rem; - margin: 0 0 0.85rem; -} -.var-chip { - display: inline-block; - padding: 0.2rem 0.55rem; - border-radius: 999px; - background: #1d1d1f; - color: #fff; - font: 600 0.68rem/1.2 var(--sans); -} -.var-chip.muted { - background: #e8e8ed; - color: var(--muted); -} -.var-rich-more { - margin-top: 1rem; - color: var(--muted); - font-size: 0.78rem; -} -.matrix-wrap { - overflow: auto; - border-radius: 14px; - border: 1px solid var(--line); - background: - radial-gradient(120% 80% at 0% 0%, rgba(0,113,227,0.06), transparent 55%), - #fff; - padding: 0.75rem; -} -.matrix-cap { - caption-side: top; - text-align: left; - font: 500 0.7rem/1.2 var(--sans); - color: var(--muted); - margin-bottom: 0.45rem; -} -.matrix-grid { - border-collapse: separate; - border-spacing: 0.35rem; - margin: 0 auto; - font: 0.78rem/1.2 var(--mono); -} -.matrix-cell { - min-width: 3.6rem; - padding: 0.55rem 0.65rem; - text-align: center; - border-radius: 10px; - border: 1px solid var(--line); - background: #f7f8fa; - color: var(--ink); - box-shadow: inset 0 1px 0 rgba(255,255,255,0.65); -} -.matrix-cell span { font-variant-numeric: tabular-nums; } -.math-lg .katex-display { font-size: 1.15em; } -.fn-search { - width: 100%; - box-sizing: border-box; - margin: 0 0 0.45rem; - padding: 0.4rem 0.5rem; - border: 1px solid var(--line); - border-radius: 8px; - font: 0.78rem/1.2 var(--sans); - color: var(--ink); - background: #fff; -} -.fn-search:focus { - outline: 2px solid var(--focus); - outline-offset: 1px; -} -.outline-tree, .outline-tree ul { - list-style: none; - margin: 0; - padding: 0; -} -.outline-tree ul { - padding-left: 0.7rem; - border-left: 1px solid var(--line); - margin-left: 0.25rem; -} -.outline-item { - margin: 0.12rem 0; - font-size: 0.78rem; - line-height: 1.35; -} -.outline-item.hidden { display: none; } -.outline-item > a { - font-family: var(--mono); - font-size: 0.76rem; - color: var(--ink); -} -.outline-item > a:hover { opacity: 1; text-decoration: underline; } -.outline-item .ol-meta { - color: var(--muted); - font-size: 0.66rem; - margin-left: 0.2rem; -} -.outline-item .ol-params { - margin-left: 0.25rem; - font-family: var(--mono); - font-size: 0.62rem; - color: var(--muted); -} -.outline-item .ol-param.inferred { - border-bottom: 1px dashed var(--line); -} -.fun-card:target { - outline: 2px solid var(--focus); - outline-offset: 2px; - background: #f0f7ff; -} -.out.ok { background: var(--ok-bg); } -.out.fail { - background: var(--fail-bg); - border-color: #e4c1c1; - color: var(--ink); - font-weight: 500; -} -.formula-card .math-block { - display: block; - margin: 0.35rem 0 0.1rem; - overflow: visible; - max-width: 100%; -} -.formula-card .katex-display { - margin: 0.2rem 0; - overflow-x: auto; - overflow-y: hidden; - padding-bottom: 0.15rem; -} -.code-card { - padding: 0; - overflow: hidden; -} -.output-card { - border-left: 3px solid #2563eb; - background: #f8fafc; -} -.output-card.output-card-image { - border-left-color: #0d9488; -} -.output-card .wb-badges { - display: flex; - flex-wrap: wrap; - gap: 0.35rem; -} -.wb-badge.wb-ok { background: #dcfce7; color: #166534; } -.wb-badge.wb-error { background: #fee2e2; color: #991b1b; } -.wb-badge.wb-trace { background: #e0e7ff; color: #3730a3; } -.output-card .output-body { - margin: 0.35rem 0 0; - padding: 0.5rem 0.65rem; - font: 0.85rem/1.45 var(--mono); - white-space: pre-wrap; - color: #0f172a; -} -.wb-figure { - margin: 0.5rem 0 0; - padding: 0; -} -.wb-image { - display: block; - max-width: 100%; - height: auto; - border-radius: 6px; - border: 1px solid var(--line); - background: #fff; -} -.wb-image-url { - margin: 0.35rem 0 0; - font: 0.75rem/1.35 var(--mono); - color: var(--muted); - word-break: break-all; -} -.doc-writeback { - margin: 0.35rem 0; - padding: 0.45rem 0.6rem; - border-radius: 8px; - border: 1px dashed #94a3b8; - background: #f1f5f9; -} -.doc-writeback[data-wb-kind="image"] { - border-color: #0d9488; - background: #f0fdfa; -} -.wb-source-badge { - display: inline-block; - margin-bottom: 0.28rem; - font: 0.68rem/1.2 var(--sans); - letter-spacing: 0.04em; - text-transform: uppercase; - color: #334155; - background: #e2e8f0; - padding: 0.12rem 0.4rem; - border-radius: 4px; -} -.doc-writeback[data-wb-kind="image"] .wb-source-badge { - background: #ccfbf1; - color: #115e59; -} -.wb-source-text { - display: block; - font: 0.82rem/1.4 var(--mono); - color: #0f172a; - white-space: pre-wrap; - word-break: break-word; -} -.wb-outline { - margin-top: 0.75rem; - padding-top: 0.75rem; - border-top: 1px solid var(--line); -} -.wb-outline-title { - font: 0.72rem/1.2 var(--sans); - letter-spacing: 0.04em; - text-transform: uppercase; - color: var(--muted); - margin-bottom: 0.35rem; -} -.plan-card { - margin: 0 0 0.85rem; - padding: 0.75rem 0.9rem; - border: 1px solid var(--line); - border-radius: var(--radius); - background: #f8fafc; - font: 0.88rem/1.45 var(--sans); -} -.plan-card .plan-meta { - display: flex; - flex-wrap: wrap; - gap: 0.5rem 1rem; - margin: 0.35rem 0 0.55rem; - color: var(--muted); - font: 0.8rem/1.35 var(--mono); -} -.plan-card a { color: #1d4ed8; } -.plan-card .plan-process { - list-style: none; - margin: 0.45rem 0 0; - padding: 0; - border-top: 1px solid var(--line); -} -.plan-card .plan-process li { - display: flex; - flex-wrap: wrap; - gap: 0.35rem 0.65rem; - padding: 0.4rem 0; - border-bottom: 1px solid #eef2f7; - font: 0.8rem/1.35 var(--sans); - color: var(--ink); -} -.plan-card .plan-process li:last-child { border-bottom: none; } -.plan-card .plan-process .pp-type { - font: 0.72rem/1.2 var(--mono); - letter-spacing: 0.04em; - text-transform: uppercase; - color: #475569; - min-width: 4.5rem; -} -.plan-card .plan-process .pp-detail { - color: var(--muted); - font: 0.78rem/1.35 var(--mono); - word-break: break-word; -} -.stream-panel { - margin: 0 0 0.85rem; - border: 1px solid var(--line); - border-radius: var(--radius); - background: var(--surface); - overflow: hidden; - position: relative; -} -.stream-head { - display: flex; - align-items: center; - gap: 0.65rem; - padding: 0.65rem 0.85rem; - background: #fafafa; - border-bottom: 1px solid var(--line); - font: 0.85rem/1 var(--sans); - color: var(--ink); -} -.stream-head button { - font: 0.78rem/1 var(--sans); - padding: 0.4rem 0.85rem; - border-radius: 8px; - border: 1px solid var(--line); - background: #1d1d1f; - color: #fff; - cursor: pointer; -} -.stream-head button:disabled { - opacity: 0.45; - cursor: not-allowed; -} -.stream-status { - margin-left: auto; - color: var(--muted); - font: 0.72rem/1 var(--mono); -} -.stream-head button.stream-stop { - background: #fff; - color: #1d1d1f; - border-color: var(--line); -} -.stream-jump { - position: absolute; - left: 50%; - bottom: 0.65rem; - transform: translateX(-50%); - z-index: 2; - font: 0.72rem/1 var(--sans); - padding: 0.35rem 0.7rem; - border-radius: 999px; - border: 1px solid var(--line); - background: #fff; - color: var(--ink); - cursor: pointer; - box-shadow: 0 1px 2px rgba(0,0,0,0.06); -} -.stream-jump[hidden] { display: none; } -.stream-body { - position: relative; - padding: 0.85rem 1rem 1rem; - min-height: 5rem; - max-height: 28rem; - overflow: auto; - display: flex; - flex-direction: column; - gap: 0.75rem; -} -.stream-empty { - color: var(--muted); - font: 0.85rem/1.4 var(--sans); - margin: 0; -} -.stream-turn { - display: flex; - flex-direction: column; - gap: 0.55rem; -} -.stream-thinking { - border: 1px solid var(--line); - border-radius: 10px; - background: #f5f5f7; - padding: 0.35rem 0.65rem 0.55rem; -} -.stream-thinking > summary { - cursor: pointer; - list-style: none; - font: 0.78rem/1.4 var(--sans); - color: var(--muted); - user-select: none; - padding: 0.25rem 0; -} -.stream-thinking > summary::-webkit-details-marker { display: none; } -.stream-thinking > summary::before { - content: "▸ "; - color: #aeaeb2; -} -.stream-thinking[open] > summary::before { content: "▾ "; } -.stream-thinking-body { - margin: 0.15rem 0 0; - font: 0.82rem/1.5 var(--sans); - color: #6e6e73; - white-space: pre-wrap; - word-break: break-word; -} -.stream-answer { - font: 0.95rem/1.55 var(--sans); - color: var(--ink); - white-space: pre-wrap; - word-break: break-word; -} -.stream-answer:empty { display: none; } -.stream-decision { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 0.35rem 0.65rem; - font: 0.78rem/1.35 var(--sans); - color: var(--muted); - padding: 0.15rem 0; - border-top: 1px dashed var(--line); -} -.stream-decision strong { - font-weight: 600; - color: #1d1d1f; - letter-spacing: 0.02em; -} -.stream-tool { - border: 1px solid var(--line); - border-left: 3px solid #94a3b8; - border-radius: 8px; - background: #f1f5f9; - padding: 0.45rem 0.7rem; - margin: 0.25rem 0; -} -.stream-tool-head { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 0.35rem 0.65rem; - font: 0.78rem/1.3 var(--sans); - color: var(--muted); -} -.stream-tool-head strong { - color: #334155; - font-weight: 600; -} -.stream-tool-meta { - font: 0.72rem/1.3 var(--mono); - color: #64748b; -} -.stream-tool-body { - margin-top: 0.3rem; - font: 0.78rem/1.4 var(--mono); - color: #475569; - white-space: pre-wrap; - word-break: break-word; -} -.stream-child { - border: 1px solid var(--line); - border-left: 3px solid #2563eb; - border-radius: 10px; - background: #f8fafc; - padding: 0.65rem 0.85rem; -} -.stream-child-await { - border-left-color: #94a3b8; - background: #f8fafc; - opacity: 0.95; -} -.stream-child-await .stream-child-head strong { - color: #64748b; -} -.stream-phase { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 0.35rem 0.65rem; - font: 0.78rem/1.35 var(--sans); - color: var(--muted); - padding: 0.2rem 0; - border-top: 1px dashed var(--line); -} -.stream-phase strong { - font-weight: 600; - color: #475569; - letter-spacing: 0.02em; -} -.stream-child-head { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.4rem 0.75rem; - font: 0.78rem/1.3 var(--sans); - color: var(--muted); - margin-bottom: 0.35rem; -} -.stream-child-head strong { - color: #1d1d1f; - font-weight: 600; -} -.stream-child-head a { color: #1d4ed8; } -.stream-child-meta { - font: 0.72rem/1.3 var(--mono); - color: var(--muted); -} -.stream-child-body { - font: 0.88rem/1.5 var(--sans); - color: var(--ink); - white-space: pre-wrap; - word-break: break-word; -} -.stream-child-body:empty { display: none; } -.stream-err { - font: 0.85rem/1.45 var(--sans); - color: #9b1c1c; - background: #fff5f5; - border: 1px solid #e4c1c1; - border-radius: 8px; - padding: 0.55rem 0.75rem; - white-space: pre-wrap; -} -.code-head { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.45rem 0.65rem; - padding: 0.65rem 0.85rem; - border-bottom: 1px solid var(--line); - background: #fafafa; -} -.code-lang { - font: 0.72rem/1 var(--mono); - color: var(--muted); - text-transform: lowercase; -} -.code-actions { - margin-left: auto; - display: flex; - align-items: center; - gap: 0.4rem; -} -.code-foot { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.45rem 0.65rem; - padding: 0.5rem 0.85rem; - border-top: 1px solid var(--line); - background: #fafafa; -} -.code-foot .code-actions { margin-left: auto; } -.code-cmd { - min-width: 9rem; - max-width: 16rem; - padding: 0.35rem 0.55rem; - border: 1px solid var(--line); - border-radius: 8px; - font: 0.78rem/1.2 var(--mono); - color: var(--ink); - background: #fff; -} -.code-cmd:focus { - outline: 2px solid rgba(29,29,31,0.18); - outline-offset: 1px; -} -.code-run { - padding: 0.35rem 0.75rem; - border: none; - border-radius: 8px; - background: var(--ink); - color: #fff; - font: 0.78rem/1.2 var(--sans); - font-weight: 600; - cursor: pointer; -} -.code-run:hover { opacity: 0.9; } -.code-run:disabled { - opacity: 0.45; - cursor: not-allowed; -} -.code-body { - margin: 0; - padding: 0.85rem 1rem; - overflow: auto; - resize: vertical; - min-height: 2.4rem; - max-height: 40rem; - background: #1e1e1e; - color: var(--syn-fg); - font: 0.82rem/1.45 var(--mono); - min-height: 2.4rem; -} -.code-body code { - font: inherit; - background: none; - padding: 0; - color: inherit; -} -.code-body .hljs { color: var(--syn-fg); background: transparent; } -.code-body .hljs-comment, -.code-body .hljs-quote { color: var(--syn-comment); font-style: italic; } -.code-body .hljs-keyword, -.code-body .hljs-selector-tag, -.code-body .hljs-literal, -.code-body .hljs-section, -.code-body .hljs-link, -.code-body .hljs-doctag, -.code-body .hljs-type, -.code-body .hljs-tag, -.code-body .hljs-name { color: var(--syn-keyword); } -.code-body .hljs-string, -.code-body .hljs-regexp, -.code-body .hljs-addition, -.code-body .hljs-meta .hljs-string { color: var(--syn-string); } -.code-body .hljs-number, -.code-body .hljs-symbol, -.code-body .hljs-bullet { color: var(--syn-number); } -.code-body .hljs-variable, -.code-body .hljs-template-variable, -.code-body .hljs-attr, -.code-body .hljs-attribute, -.code-body .hljs-selector-attr, -.code-body .hljs-selector-pseudo { color: var(--syn-variable); } -.code-body .hljs-title, -.code-body .hljs-title.function_, -.code-body .hljs-function .hljs-title { color: var(--syn-function); } -.code-body .hljs-built_in, -.code-body .hljs-title.class_ { color: var(--syn-type); } -.code-body .hljs-meta, -.code-body .hljs-meta .hljs-keyword { color: var(--syn-meta); } -.code-body .hljs-deletion { color: var(--syn-string); } -.code-body .hljs-emphasis { font-style: italic; } -.code-body .hljs-strong { font-weight: 700; } -.code-out { - margin: 0; - padding: 0.75rem 1rem; - border-top: 1px solid var(--line); - background: #f0f0f2; - font: 0.8rem/1.45 var(--mono); - white-space: pre-wrap; - word-break: break-word; -} -.code-out.err { - background: #fff5f5; - color: #9b1c1c; -} -.code-out:not([hidden]) { display: block; } -.plots { - display: grid; - gap: 1rem; - margin-top: 1rem; - justify-items: center; -} -.plot { - overflow: auto; - background: var(--surface); - border: 1px solid var(--line); - border-radius: var(--radius); - padding: 0.75rem; - width: 100%; - display: flex; - justify-content: center; -} -.plot:has(svg[data-theme="dark"]) { - background: #070b10; - border-color: #1c2838; - padding: 1.1rem 1.25rem; -} -.plot:has(svg[data-theme="light"]), -.plot:has(svg[data-theme="bw"]) { - background: #f7f9fc; - border-color: #d5dde8; -} -.plot svg { - display: block; - max-width: 100%; - height: auto; - margin-inline: auto; - min-width: min(100%, 28rem); -} -.comment-text { - color: var(--muted); - font-size: 0.92rem; - display: block; - margin-top: 0.35rem; - line-height: 1.55; - max-width: 42em; -} -.comment-text > :first-child { margin-top: 0; } -.comment-text > :last-child { margin-bottom: 0; } -.comment-text p { margin: 0.45em 0; } -.comment-text a { - color: var(--ink); - text-decoration: underline; - text-underline-offset: 0.12em; - border-bottom: none; -} -.comment-text a:hover { opacity: 0.72; } -.comment-text code { - font-family: var(--mono); - font-size: 0.86em; - background: var(--fill); - padding: 0.08em 0.28em; - border-radius: 4px; -} -.comment-text ul, .comment-text ol { - margin: 0.4em 0; - padding-left: 1.35em; -} -code.expr { - font-family: var(--mono); - font-size: 0.84rem; - color: var(--ink); -} -.err { color: var(--ink); font-weight: 600; padding: 0.75rem 1rem; } -.welcome { - max-width: 40rem; - margin: 4rem auto; - text-align: center; -} -.welcome p { color: var(--muted); font-size: 1.05rem; } -.backdrop { - display: none; - position: fixed; - inset: 0; - background: rgba(0,0,0,0.28); - z-index: 25; - animation: fade-in 0.18s ease; -} -@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } -@media (max-width: 900px) { - .shell { grid-template-columns: 240px minmax(0, 1fr); } - main.panel { max-width: 64rem; padding: 1.75rem 1.5rem 3rem; } -} -@media (max-width: 800px) { - .topbar { display: flex; } - .nav-brand { display: none; } - .shell { - grid-template-columns: 1fr; - max-width: none; - min-height: calc(100vh - 3.25rem); - } - .nav { - position: fixed; - top: 0; - left: 0; - bottom: 0; - width: min(82vw, 300px); - height: 100vh; - z-index: 30; - transform: translateX(-105%); - transition: transform 0.22s cubic-bezier(0.2, 0.8, 0.2, 1); - border-right: 1px solid var(--line); - background: var(--surface); - box-shadow: 8px 0 32px rgba(0,0,0,0.08); - } - #nav-toggle:checked ~ .shell .nav { transform: translateX(0); } - #nav-toggle:checked ~ .backdrop { display: block; } - main.panel { - max-width: none; - padding: 1.4rem 1.15rem 3rem; - } -} -"# -} - -fn reader_icon(path: &str) -> String { - format!(r#""#, path) -} - -pub fn layout(title: &str, nav: &str, main: &str) -> String { - format!( - r##" - - - - -{title} · marqdo - - - - - - - - -
      - - MarqdoEXECUTABLE KNOWLEDGE - - -
      - -
      - -
      -
      - {main} -
      -
      -
      - -
      MARQDO代码即文档 · 文档即知识库 · 知识即可执行
      - - -

      - - - -
      -
      -

      Variable

      - -
      -
      -
      -
      - - - - - - - -"##, - title = escape(title), - css = stylesheet(), - katex_css = include_str!("assets/vendor/katex.min.css"), - katex_js = include_str!("assets/vendor/katex.min.js"), - katex_render_js = include_str!("assets/vendor/auto-render.min.js"), - reader_feather = include_str!("assets/feather.uri"), - reader_css = include_str!("reader.css"), - reader_js = include_str!("reader.js"), - reader_logo = include_str!("assets/logo.uri"), - reader_blossom = include_str!("assets/blossom.uri"), - menu_icon = reader_icon("M4 6h16M4 12h16M4 18h16"), - search_icon = reader_icon("M21 21l-5-5M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0"), - reload_icon = reader_icon("M20 7V3l-3 3a8 8 0 1 0 2 11M20 3h-5"), - settings_icon = reader_icon("M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M5 19l2-2M17 7l2-2"), - play_icon = reader_icon("m9 5 11 7-11 7z"), - clear_icon = reader_icon("m14 3 4 2-4 8M5 12l8 2 2 6H3zM7 15l-1 4M10 16l-1 4"), - more_icon = reader_icon("M5 12h.01M12 12h.01M19 12h.01"), - nav = nav, - main = main - ) -} - -pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> String { - let mut out = String::from("

      Files

      "); - let mut last_folder: Option = None; - - for f in files { - let rel = f.to_string_lossy().replace('\\', "/"); - let folder = Path::new(&rel) - .parent() - .map(|p| p.to_string_lossy().replace('\\', "/")) - .unwrap_or_default(); - - if last_folder.as_deref() != Some(folder.as_str()) { - close_nav_group(&mut out, last_folder.as_deref()); - open_nav_group(&mut out, &folder, active); - last_folder = Some(folder); - } - - let name = Path::new(&rel) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(&rel); - let active_cls = if active == Some(rel.as_str()) { - " active" - } else { - "" - }; - let href = href_file(links, &rel); - out.push_str(&format!( - "
    8. {}
    9. ", - escape(&href), - escape(name) - )); - } - close_nav_group(&mut out, last_folder.as_deref()); - - // index link for static pages - if matches!(links, LinkMode::Static { from: Some(_) }) { - let home = href_index(links); - out.insert_str( - 0, - &format!( - "

      Index

      ", - escape(&home) - ), - ); - } - out -} - -fn close_nav_group(out: &mut String, folder: Option<&str>) { - match folder { - None => {} - Some("") => out.push_str(""), - Some(_) => out.push_str(""), - } -} - -fn open_nav_group(out: &mut String, folder: &str, active: Option<&str>) { - if folder.is_empty() { - out.push_str("
        "); - return; - } - let contains_active = active.is_some_and(|a| { - Path::new(a) - .parent() - .map(|p| p.to_string_lossy().replace('\\', "/") == folder) - .unwrap_or(false) - }); - // Index (no active): keep folders open for browsing; else open only the active folder. - let open_attr = if active.is_none() || contains_active { - " open" - } else { - "" - }; - out.push_str(&format!( - "
        {}
          ", - escape(folder) - )); -} - -fn href_file(links: &LinkMode, target_rel: &str) -> String { - match links { - LinkMode::Live => format!("/file?path={}", urlencoding_path(target_rel)), - LinkMode::Static { from: None } => format!("pages/{}.html", target_rel), - LinkMode::Static { - from: Some(from_rel), - } => relative_page_href(from_rel, target_rel), - } -} - -fn href_index(links: &LinkMode) -> String { - match links { - LinkMode::Live => "/".into(), - LinkMode::Static { from: None } => "index.html".into(), - LinkMode::Static { - from: Some(from_rel), - } => { - let depth = Path::new(from_rel) - .parent() - .map(|p| p.components().filter(|c| matches!(c, Component::Normal(_))).count()) - .unwrap_or(0); - // pages//file.html → up (depth+1) to OUT_DIR - format!("{}index.html", "../".repeat(depth + 1)) - } - } -} - -/// From `pages/.html` to `pages/.html`. -fn relative_page_href(from_rel: &str, to_rel: &str) -> String { - let from_parent = Path::new(from_rel).parent().unwrap_or_else(|| Path::new("")); - let to_path = PathBuf::from(format!("{to_rel}.html")); - let mut ups = 0usize; - for c in from_parent.components() { - if matches!(c, Component::Normal(_)) { - ups += 1; - } - } - format!("{}{}", "../".repeat(ups), to_path.to_string_lossy().replace('\\', "/")) -} - - -pub fn page_index(files: &[PathBuf], only: Option<&Path>, links: &LinkMode) -> String { - let nav = nav_html(files, None, links); - let main = if let Some(p) = only { - let rel = p.to_string_lossy().replace('\\', "/"); - format!( - "

          marqdo

          Open {}

          ", - escape(&href_file(links, &rel)), - escape(&rel) - ) - } else if files.is_empty() { - "

          marqdo

          No .mq.md files found in this path.

          ".into() - } else { - // Prefer callers to render the first file at `/` / index.html; this is a fallback. - let first = files[0].to_string_lossy().replace('\\', "/"); - format!( - "

          marqdo

          Opening {}…

          ", - escape(&href_file(links, &first)), - escape(&first) - ) - }; - layout("index", &nav, &main) -} - -fn notebook_ui() -> &'static str { - r#" - -
          - - -
          - - -"# -} - - -/// Resolve links to documents in this View tree; retain the authored target so -/// live responses and static exports can share the same read model. -pub(crate) fn document_links(source: &str, files: &[PathBuf], rel: &str, links: &LinkMode) -> String { - fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { - let start = tag.find(&format!(" {name}=\""))? + name.len() + 3; - tag[start..].split('"').next() - } - fn decode(value: &str) -> String { - value.replace(""", "\"").replace("'", "'") - .replace("<", "<").replace(">", ">").replace("&", "&") - } - let mut out = String::new(); - let mut rest = source; - while let Some(start) = rest.find("') else { break }; - let tag = &rest[..=end]; - let mut replacement = None; - if let Some(original) = attribute(tag, "data-document-href") { - let target = decode(original); - let split = target.find(['?', '#']).unwrap_or(target.len()); - let path = &target[..split]; - if path.ends_with(".mq.md") && !path.contains(':') && !path.starts_with("//") { - let path = percent_decode_document_path(path); - let joined = if path.starts_with('/') { PathBuf::from(path.trim_start_matches('/')) } - else { Path::new(rel).parent().unwrap_or(Path::new("")).join(path) }; - let mut parts = Vec::new(); - let mut valid = true; - for component in joined.components() { - match component { - Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()), - Component::ParentDir => { if parts.pop().is_none() { valid = false; break; } } - Component::CurDir => {} - _ => { valid = false; break; } - } - } - let resolved = parts.join("/"); - if valid && files.iter().any(|file| file.to_string_lossy().replace('\\', "/") == resolved) { - if let Some(current) = attribute(tag, "href") { - let suffix = &target[split..]; - let suffix = if matches!(links, LinkMode::Live) && suffix.starts_with('?') { - format!("&{}", &suffix[1..]) - } else { suffix.to_string() }; - let href = format!("{}{suffix}", href_file(links, &resolved)); - replacement = Some(tag.replacen(&format!(" href=\"{current}\""), &format!(" href=\"{}\"", escape(&href)), 1)); - } - } - } - } - out.push_str(replacement.as_deref().unwrap_or(tag)); - rest = &rest[end+1..]; - } - out.push_str(rest); - out -} - -#[cfg(test)] -mod document_link_tests { - use super::*; - #[test] - fn document_links_round_trip_between_live_and_offline_views() { - let files = vec![PathBuf::from("docs/entry.mq.md"), PathBuf::from("read me.mq.md")]; - let tag = r#"打开"#; - let live = document_links(tag, &files, "docs/entry.mq.md", &LinkMode::Live); - assert!(live.contains("href=\"/file?path=read%20me.mq.md&stdin=a&b=c#fn-2\""), "{live}"); - let offline = document_links(&live, &files, "docs/entry.mq.md", &LinkMode::Static {from: Some("docs/entry.mq.md".into())}); - assert!(offline.contains("href=\"../read me.mq.md.html?stdin=a&b=c#fn-2\""), "{offline}"); - } - #[test] - fn unknown_paths_external_urls_and_encoded_unicode_stay_intact() { - let files = vec![PathBuf::from("next.mq.md")]; - for target in ["../../next.mq.md", "https://example.com/next.mq.md", "missing.mq.md", "%中.mq.md"] { - let tag = format!("目标"); - assert_eq!(document_links(&tag, &files, "entry.mq.md", &LinkMode::Live), tag); - } - } -} - -fn percent_decode_document_path(value: &str) -> String { - let bytes = value.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'%' && i+2 < bytes.len() { - let hex = |b: u8| (b as char).to_digit(16).map(|v| v as u8); - if let (Some(a), Some(b)) = (hex(bytes[i+1]), hex(bytes[i+2])) { - out.push(a*16+b); i += 3; continue; - } - } - out.push(bytes[i]); i += 1; - } - String::from_utf8(out).unwrap_or_else(|_| value.to_string()) -} - -pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String { - let nav = nav_html(files, Some(rel), links); - let (status, status_label, out_text) = if vm.awaiting_input { - ( - "pending", - "input", - if vm.show_stream { - "Fill preset input, then Run with input — output streams in the panel (no page reload)." - .to_string() - } else { - "Fill preset input, then Run with input." - .to_string() - }, - ) - } else if vm.auto_stream { - ( - "pending", - "stream", - "Streaming in the panel below…".to_string(), - ) - } else if vm.library_document { - ( - "pending", - "module", - "这是可调用模块,未自动执行。通过 marqdo call 选择函数并提供参数。".to_string(), - ) - } else if vm.ok { - ( - "ok", - "ok", - if vm.stdout.is_empty() { - "(no stdout)".into() - } else { - escape(&vm.stdout) - }, - ) - } else if vm.stderr.is_empty() { - ("fail", "fail", "(skipped)".into()) - } else { - ("fail", "fail", escape(&vm.stderr)) - }; - let stdin_panel = if vm.library_document || vm.input_prompts.is_empty() { - String::new() - } else { - let placeholder = vm.input_prompts.join("\n"); - let rows = vm.input_prompts.len().clamp(2, 8); - match links { - LinkMode::Live => { - let hint = if vm.input_prompts.iter().any(|p| !p.is_empty()) { - format!( - "prompts: {}", - escape(&vm.input_prompts.join(" · ")) - ) - } else { - "one line per input".into() - }; - format!( - r#"
          - - - - -
          "#, - path = escape(rel), - hint = hint, - rows = rows, - placeholder = escape(&placeholder), - stdin = escape(&vm.preset_stdin), - ) - } - LinkMode::Static { .. } => { - if vm.preset_stdin.is_empty() { - String::new() - } else { - format!( - r#"

          Demo stdin (static export cannot re-run interactively); prompts: {prompts}

          -
          {stdin}
          "#, - prompts = escape(&vm.input_prompts.join(" · ")), - stdin = escape(&vm.preset_stdin), - ) - } - } - } - }; - let fallback_title = Path::new(rel) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(rel) - .trim_end_matches(".mq.md"); - let title = crate::view::title_from_source(&vm.source, fallback_title); - let plots_html = if vm.plots.is_empty() { - String::new() - } else { - let mut s = String::from(r#"
          "#); - for svg in &vm.plots { - s.push_str(r#"
          "#); - s.push_str(svg); - s.push_str("
          "); - } - s.push_str("
          "); - s - }; - let live_flag = match links { - LinkMode::Live => "true", - LinkMode::Static { .. } => "false", - }; - let exec_clear = r#""#; - let outline_block = if vm.outline_html.is_empty() { - String::new() - } else { - vm.outline_html.clone() - }; - let structure_html = document_links(&vm.structure_html, files, rel, links); - let structure_block = if outline_block.is_empty() { - format!( - r#"
          {structure}
          "#, - structure = structure_html - ) - } else { - format!( - r#"
          -
          {structure}
          - {outline} -
          "#, - structure = structure_html, - outline = outline_block, - ) - }; - let plan_card = plan_result_card(&vm.stdout, links); - let stream_panel = match links { - LinkMode::Live if vm.show_stream => r#"
          -
          - Stream - - - idle -
          -
          -

          Use Run with input or Run — thinking and answer stream here.

          -
          - -
          "# - .to_string(), - _ => String::new(), - }; - let trace_safe = vm - .trace_json - .replace(" -window.MARQDO_VIEW_LIVE = {live}; -window.MARQDO_FILE_PATH = {path_js}; -window.MARQDO_AUTO_STREAM = {auto_stream}; -window.MARQDO_VIEW_PAGE_TOKEN = {page_token_js}; - - -

          {title}{status_label}

          -

          {rel}

          -{notebook} -
          -

          文档

          - {structure_block} -
          -{knowledge} -
          -

          运行与结果 {exec_clear}

          - {stdin_panel} - {stream_panel} - {plan_card} -
          {out}
          - {plots} -
          -
          - 完整源码 -
          {source}
          -
          -"#, - live = live_flag, - path_js = escape_js_string(rel), - auto_stream = if vm.auto_stream { "true" } else { "false" }, - page_token_js = escape_js_string(&vm.page_token), - trace = if trace_safe.is_empty() { - "{}" - } else { - trace_safe.as_str() - }, - title = escape(&title), - status = status, - status_label = status_label, - rel = escape(rel), - notebook = notebook, - knowledge = { - if !vm.knowledge_error.is_empty() { - format!( - "

          知识关系

          {}

          ", - escape(&vm.knowledge_error) - ) - } else if vm.knowledge_html.is_empty() { - String::new() - } else { - format!( - "
          可执行知识 · 输入、返回与依据{}
          ", - vm.knowledge_html - ) - } - }, - exec_clear = exec_clear, - structure_block = structure_block, - stdin_panel = stdin_panel, - stream_panel = stream_panel, - plan_card = plan_card, - out = out_text, - plots = plots_html, - source = escape(&vm.source), - ); - layout(rel, &nav, &main) -} - -/// Plan / agent result map → card with workbook link, cache/rounds, and process events. -fn plan_result_card(stdout: &str, links: &LinkMode) -> String { - let trimmed = stdout.trim(); - if trimmed.is_empty() { - return String::new(); - } - let candidate = trimmed - .lines() - .rev() - .find(|l| l.trim_start().starts_with('{')) - .unwrap_or(trimmed); - let Ok(v) = serde_json::from_str::(candidate) else { - return String::new(); - }; - let workbook = v.get("workbook").and_then(|x| x.as_str()); - let cache = v.get("cache").and_then(|x| x.as_str()); - let match_kind = v.get("match").and_then(|x| x.as_str()); - let rounds = v - .get("rounds") - .and_then(|x| x.as_u64()) - .or_else(|| v.get("round").and_then(|x| x.as_u64())); - let status = v.get("status").and_then(|x| x.as_str()); - let events = v.get("events").and_then(|x| x.as_array()); - if workbook.is_none() && cache.is_none() && rounds.is_none() && events.is_none() { - return String::new(); - } - let mut meta = Vec::new(); - if let Some(s) = status { - meta.push(format!("status={}", escape(s))); - } - if let Some(c) = cache { - meta.push(format!("cache={}", escape(c))); - } - if let Some(m) = match_kind { - meta.push(format!("match={}", escape(m))); - } - if let Some(r) = rounds { - meta.push(format!("rounds={r}")); - } - let link = match (workbook, links) { - (Some(wb), LinkMode::Live) => { - let href = format!("/file?path={}", urlencoding_path(wb)); - format!( - r#"Open workbook {}"#, - escape(wb) - ) - } - (Some(wb), LinkMode::Static { .. }) => { - format!(r#"workbook {}"#, escape(wb)) - } - _ => String::new(), - }; - let process = plan_process_list(events); - format!( - r#"
          Plan result
          {}
          {}{}
          "#, - meta.join(" · "), - link, - process - ) -} - -fn plan_process_list(events: Option<&Vec>) -> String { - let Some(events) = events else { - return String::new(); - }; - if events.is_empty() { - return String::new(); - } - let mut items = Vec::new(); - for ev in events { - let t = ev.get("type").and_then(|x| x.as_str()).unwrap_or("event"); - // Skip raw token deltas in the static card — live Stream panel owns those. - if matches!(t, "delta" | "reasoning") { - continue; - } - let detail = match t { - "decision" => { - let d = ev.get("decision").and_then(|x| x.as_str()).unwrap_or("?"); - let sum = ev.get("summary").and_then(|x| x.as_str()).unwrap_or(""); - if sum.is_empty() { - escape(d) - } else { - format!("{} — {}", escape(d), escape(sum)) - } - } - "round" => { - let mut bits = Vec::new(); - if let Some(r) = ev.get("round") { - bits.push(format!("round={r}")); - } - if let Some(wb) = ev.get("workbook").and_then(|x| x.as_str()) { - bits.push(format!("workbook={}", escape(wb))); - } - if let Some(c) = ev.get("exit_code") { - bits.push(format!("exit={c}")); - } - if let Some(res) = ev.get("result").and_then(|x| x.as_str()) { - let brief: String = res.chars().take(80).collect(); - bits.push(format!("result={}", escape(&brief))); - } - bits.join(" · ") - } - "tool_start" | "tool_end" => { - let name = ev.get("name").and_then(|x| x.as_str()).unwrap_or("?"); - let kind = ev.get("kind").and_then(|x| x.as_str()).unwrap_or(""); - if kind.is_empty() { - escape(name) - } else { - format!("{} ({})", escape(name), escape(kind)) - } - } - "done" => { - if let Some(res) = ev.get("result").and_then(|x| x.as_str()) { - let brief: String = res.chars().take(80).collect(); - escape(&brief) - } else { - String::new() - } - } - "error" => escape(ev.get("message").and_then(|x| x.as_str()).unwrap_or("error")), - _ => String::new(), - }; - items.push(format!( - r#"
        • {}{}
        • "#, - escape(t), - detail - )); - } - if items.is_empty() { - return String::new(); - } - format!(r#"
            {}
          "#, items.join("")) -} - -/// Percent-encode a path for `?path=` (shared by every link builder). -pub(crate) fn urlencoding_path(s: &str) -> String { - let mut out = String::new(); - for b in s.as_bytes() { - match *b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { - out.push(*b as char); - } - _ => out.push_str(&format!("%{b:02X}")), - } - } - out -} - -/// Escape a Rust string as a JS string literal (keeps U+2028/2029 escaped, -/// which the debug-page copy used to miss). -pub(crate) fn escape_js_string(s: &str) -> String { - let mut out = String::from('"'); - for c in s.chars() { - match c { - '\\' => out.push_str("\\\\"), - '"' => out.push_str("\\\""), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\u{2028}' => out.push_str("\\u2028"), - '\u{2029}' => out.push_str("\\u2029"), - c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)), - c => out.push(c), - } - } - out.push('"'); - out -} - -#[cfg(test)] -mod plan_card_tests { - use super::{plan_result_card, LinkMode}; - - #[test] - fn plan_card_renders_process_events() { - let stdout = r#"{"status":"ok","cache":"hit","match":"exact","rounds":1,"workbook":"wb.mq.md","events":[{"type":"decision","decision":"REUSE","summary":"OKF hit"},{"type":"round","round":1,"workbook":"wb.mq.md","exit_code":0,"result":"pong"},{"type":"delta","text":"skip"},{"type":"done","result":"pong"}]}"#; - let html = plan_result_card(stdout, &LinkMode::Static { from: None }); - assert!(html.contains("plan-card"), "{html}"); - assert!(html.contains("cache=hit"), "{html}"); - assert!(html.contains("match=exact"), "{html}"); - assert!(html.contains("plan-process"), "{html}"); - assert!(html.contains("REUSE"), "{html}"); - assert!(html.contains("pp-type\">round"), "{html}"); - assert!(!html.contains("pp-type\">delta"), "{html}"); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn outline_rail_stacks_by_panel_container_not_960_viewport() { - let css = stylesheet(); - assert!( - css.contains("container-name: mq-panel"), - "panel-wrap should be a size container for outline layout" - ); - assert!( - css.contains("@container mq-panel (max-width: 32rem)"), - "outline must stack from panel width, not a mid-width viewport media query" - ); - assert!( - !css.contains("@media (max-width: 960px) {\n .struct-wrap"), - "960px viewport media wrongly buried the outline under Structure" - ); - let html = layout("t", "

          nav

          ", "

          main

          "); - assert!(html.contains("container-name: mq-panel"), "{html}"); - } - - #[test] - fn notebook_ui_has_controls() { - let ui = notebook_ui(); - for id in [ - "nb-run-all", - "nb-restart", - "nb-step", - "nb-state", - "nb-journal", - "nb-reload", - "nb-debug", - "nb-theme", - "nb-kernel-input", - "nb-push", - "nb-pull", - "nb-state-out", - ] { - assert!(ui.contains(id), "notebook UI missing {id}"); - } - assert!( - !ui.contains("\"/api/session"), - "notebook API URLs must stay relative for path-prefix proxy" - ); - assert!(ui.contains("post(\"api/session/open\"")); - assert!(!ui.contains("In ["), "view cells must not mimic Jupyter In[] prompts"); - assert!(!ui.contains("Out ["), "view cells must not mimic Jupyter Out[] prompts"); - assert!(ui.contains("id=\"nb-clear\""), "view must expose Clear outputs"); - assert!(ui.contains("api/session/clear"), "Clear outputs must call the session API"); - } - -} diff --git a/src/view/knowledge_present.rs b/src/view/knowledge_present.rs deleted file mode 100755 index c2a838a..0000000 --- a/src/view/knowledge_present.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! V1 KnowledgePresentation model — structured facts shared by body, outline, and detail. -//! -//! Semantic facts come from SemanticProject; this module does not invent verification. - -use crate::sema::{SemanticArtifact, SemanticProject}; -use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; - -#[derive(Debug, Clone)] -pub struct KnowledgeNode { - pub node_id: String, - pub artifact_id: Option, - pub display_name: String, - pub kind: String, - pub source_file: String, - pub source_line: u32, - pub signature: Option, - pub effects: Vec, - pub evidence: String, - pub dependencies: Vec, - pub artifact_digest: String, -} - -#[derive(Debug, Clone)] -pub struct KnowledgePresentation { - pub document_id: String, - pub title: String, - pub source_digest: String, - /// V2: semantic generation / run matching token (empty when not compiled under CURRENT). - pub semantic_generation: String, - /// V2: page token for SSE stale-packet rejection (digest of document facts). - pub page_token: String, - pub execution_state: String, - pub nodes: Vec, - pub diagnostics: Vec, -} - -impl KnowledgePresentation { - pub fn from_project(project: &SemanticProject, rel: &str, title: &str) -> Self { - let mut nodes = Vec::new(); - for artifact in &project.artifacts { - if artifact.source.file != rel { - continue; - } - if artifact.kind == "module" { - continue; - } - nodes.push(node_from_artifact(artifact)); - } - let mut hasher_parts: Vec<&str> = project - .artifacts - .iter() - .filter(|a| a.source.file == rel) - .map(|a| a.hashes.artifact.0.as_str()) - .collect(); - hasher_parts.sort(); - let mut h = Sha256::new(); - h.update(project.project_id.as_bytes()); - h.update(rel.as_bytes()); - for part in &hasher_parts { - h.update(part.as_bytes()); - } - let digest_hex = format!("{:x}", h.finalize()); - let source_digest = format!("sha256:{digest_hex}"); - // page_token is filled by caller from raw source so SSE can match without recompile. - let page_token = String::new(); - let semantic_generation = { - let mut gh = Sha256::new(); - gh.update(project.project_id.as_bytes()); - for a in &project.artifacts { - gh.update(a.hashes.artifact.0.as_bytes()); - } - format!("{:x}", gh.finalize())[..16].to_string() - }; - let mut diagnostics = Vec::new(); - for n in &nodes { - if n.evidence == "sourced" { - // Never imply sourced == verified (V2). - diagnostics.push(format!( - "{}: 已关联来源,内容尚未核验", - n.display_name - )); - } - } - Self { - document_id: rel.to_string(), - title: title.to_string(), - source_digest, - semantic_generation, - page_token, - execution_state: "not_run".into(), - nodes, - diagnostics, - } - } - - pub fn to_json(&self) -> Value { - json!({ - "schema_version": 1, - "document_id": self.document_id, - "title": self.title, - "source_digest": self.source_digest, - "semantic_generation": self.semantic_generation, - "page_token": self.page_token, - "execution_state": self.execution_state, - "nodes": self.nodes.iter().map(|n| json!({ - "node_id": n.node_id, - "artifact_id": n.artifact_id, - "display_name": n.display_name, - "kind": n.kind, - "source": {"file": n.source_file, "line": n.source_line}, - "signature": n.signature, - "effects": n.effects, - "evidence": n.evidence, - "dependencies": n.dependencies, - "artifact_digest": n.artifact_digest, - "verified_claim": false, - })).collect::>(), - "local_deps": self.nodes.iter().flat_map(|n| { - n.dependencies.iter().map(|d| json!({ - "from": n.node_id, - "to": d, - })).collect::>() - }).collect::>(), - "diagnostics": self.diagnostics, - }) - } -} - -/// Live View SSE: whether a result packet may update the document structure. -/// -/// Legacy packets without a token are accepted so older live-view clients keep -/// working. **Embedded DocumentView clients must use [`sse_accepts_packet_strict`] -/// instead** — missing/empty tokens and mismatches are rejected there. -pub fn sse_accepts_packet(page_token: &str, packet_token: Option<&str>) -> bool { - match packet_token { - None | Some("") => true, // legacy packets without token still apply - Some(_tok) if page_token.is_empty() => true, - Some(tok) => tok == page_token, - } -} - -/// Strict SSE / embed gate: reject missing, empty, or mismatched page tokens. -/// -/// Use this for DocumentView / qdagent embed hosts. Do not inherit the live-view -/// leniency of [`sse_accepts_packet`]. -pub fn sse_accepts_packet_strict(page_token: &str, packet_token: Option<&str>) -> bool { - match packet_token { - None | Some("") => false, - Some(_tok) if page_token.is_empty() => false, - Some(tok) => tok == page_token, - } -} - -/// Stable page token from raw source bytes (used by SSE run path). -pub fn page_token_from_source(rel: &str, source: &str) -> String { - let mut h = Sha256::new(); - h.update(rel.as_bytes()); - h.update(source.as_bytes()); - let hex = format!("{:x}", h.finalize()); - hex[..hex.len().min(32)].to_string() -} - -fn node_from_artifact(artifact: &SemanticArtifact) -> KnowledgeNode { - let signature = artifact.signature.as_ref().map(|sig| { - let params = sig - .params - .iter() - .map(|p| format!("{}:{}", p.name, p.ty)) - .collect::>() - .join(", "); - format!("({params}) → {}", sig.returns) - }); - KnowledgeNode { - node_id: artifact - .symbol_id - .as_ref() - .map(|id| id.as_str().to_string()) - .unwrap_or_else(|| artifact.artifact_id.0.clone()), - artifact_id: Some(artifact.artifact_id.0.clone()), - display_name: artifact.display_name.clone(), - kind: artifact.kind.clone(), - source_file: artifact.source.file.clone(), - source_line: artifact.source.line, - signature, - effects: artifact.effects.values(), - evidence: artifact.verification.evidence.clone(), - dependencies: artifact.dependencies.iter().map(|d| d.0.clone()).collect(), - artifact_digest: artifact.hashes.artifact.0.clone(), - } -} - -/// Pull `title:` from YAML frontmatter without a full YAML parser. -pub fn title_from_source(source: &str, fallback: &str) -> String { - let mut lines = source.lines(); - if lines.next().map(|l| l.trim_end()) != Some("---") { - return fallback.to_string(); - } - for line in lines { - let t = line.trim_end(); - if t.trim() == "---" { - break; - } - let trimmed = t.trim(); - if let Some(rest) = trimmed.strip_prefix("title:") { - let title = rest.trim().trim_matches('"').trim_matches('\'').to_string(); - if !title.is_empty() { - return title; - } - } - } - fallback.to_string() -} diff --git a/src/view/knowledge_reading.rs b/src/view/knowledge_reading.rs deleted file mode 100755 index 6676f38..0000000 --- a/src/view/knowledge_reading.rs +++ /dev/null @@ -1,266 +0,0 @@ -//! Reader-facing projection of compiler facts; no evaluation or invented evidence. -use crate::ast::{Function, Module}; -use crate::sema::{SemanticArtifact, SemanticProject}; -use crate::view::{html::escape, render::expr_display}; - -fn find_function(functions: &[Function], line: u32) -> Option<&Function> { - functions.iter().find_map(|f| { - if f.span.line == line { - Some(f) - } else { - find_function(&f.children, line) - } - }) -} -fn state(value: &str) -> String { - match value { - "passed" => "检查通过".into(), - "failed" => "检查失败".into(), - "unchecked" => "尚未检查".into(), - "not_run" => "分析未运行程序".into(), - "unknown" => "没有可用记录".into(), - "sourced" => "已关联来源,内容尚未核验".into(), - "verified" => "证据已核验".into(), - "unverified" => "尚无已核验证据".into(), - "unreviewed" => "尚未进行领域审阅".into(), - other => format!("原始状态:{other}"), - } -} -fn effect(value: &str) -> &str { - match value { - "pure" => "无已知宿主副作用", - "fs.read" => "读取文件", - "fs.write" => "写入文件", - "net.http" | "network" => "网络请求", - "process.exec" => "启动进程", - "plugin" => "加载原生插件", - "environment.read" => "读取环境配置", - "output.write" => "输出文本", - "input.read" => "读取输入", - "unknown" => "调用效应尚不能确定", - _ => value, - } -} -fn kind(value: &str) -> &str { - match value { - "type" => "对象", - "function" => "函数", - "constant" => "常量", - _ => value, - } -} -fn step_kind(value: &str) -> &str { - match value { - "derive" => "计算", - "observe" => "观察", - "iterate" => "遍历", - "call" => "调用", - "return" => "返回", - "branch" => "条件", - "narrate" | "reference" => "正文引用", - _ => value, - } -} -fn render_steps( - project: &SemanticProject, - steps: &[&crate::sema::ir::KnowledgeStep], - title: &str, -) -> String { - if steps.is_empty() { - return String::new(); - } - let mut out=format!("
          {}

          这是源码结构,不是实际执行时序;正文引用不会因阅读而执行。

            ",escape(title)); - for step in steps { - let label = project - .refs - .iter() - .find(|r| r.id == step.reference) - .map(|r| r.label.as_str()) - .unwrap_or("未命名步骤"); - out.push_str(&format!(r##"
          1. {meaning}{label}
          2. "##,kind=escape(&step.kind),line=step.source.line,meaning=escape(step_kind(&step.kind)),label=escape(label))); - } - out.push_str("
          "); - out -} -fn technical(artifact: &SemanticArtifact) -> String { - let v = &artifact.verification; - format!( - r##"
          技术详情:身份、摘要与原始状态
          目标标识
          {target}
          制品摘要(未检查锁定状态)
          {digest}
          依赖标识
          {deps}
          原始验证状态
          parse: {parse}; resolve: {resolve}; contract: {contract}; execution: {execution}; tests: {tests}; evidence: {evidence}; domain: {domain}
          "##, - target = escape( - artifact - .symbol_id - .as_ref() - .map(|id| id.as_str()) - .unwrap_or(&artifact.artifact_id.0) - ), - digest = escape(&artifact.hashes.artifact.0), - deps = escape( - &artifact - .dependencies - .iter() - .map(|id| id.0.as_str()) - .collect::>() - .join("\n") - ), - parse = escape(&v.parse), - resolve = escape(&v.resolve), - contract = escape(&v.contract), - execution = escape(&v.execution), - tests = escape(&v.tests), - evidence = escape(&v.evidence), - domain = escape(&v.domain) - ) -} -/// Facts are grouped by exact source unit, with machine identities behind disclosure. -pub(super) fn render(project: &SemanticProject, rel: &str, module: Option<&Module>) -> String { - let mut artifacts: Vec<_> = project - .artifacts - .iter() - .filter(|a| a.source.file == rel && a.kind != "module") - .collect(); - artifacts.sort_by_key(|a| a.source.line); - let steps: Vec<_> = project - .steps - .iter() - .filter(|s| s.source.file == rel) - .collect(); - if artifacts.is_empty() && steps.is_empty() { - return String::new(); - } - let mut out = format!( - r##"

          这份文档怎样成为可调用的知识

          {} 个知识单元 · {} 个结构步骤。先读输入、返回与调用边界,再按需查看依赖和依据。

          以下来自静态分析,不代表程序已经运行、测试通过或内容已获领域确认。实际运行见正文标注与“运行与结果”。

          "##, - artifacts.len(), - steps.len() - ); - let first = artifacts.first().map(|a| a.source.line).unwrap_or(u32::MAX); - let introductory: Vec<_> = steps - .iter() - .copied() - .filter(|s| s.source.line < first) - .collect(); - out.push_str(&render_steps(project, &introductory, "正文中的引用与步骤")); - for (index, a) in artifacts.iter().enumerate() { - let line = a.source.line; - let function = module.and_then(|m| find_function(&m.functions, line)); - let end = artifacts - .get(index + 1) - .map(|a| a.source.line) - .unwrap_or(u32::MAX); - out.push_str(&format!(r##"
          {name}{kind}
          回到正文 · 第 {line} 行"##,name=escape(&a.display_name),kind=escape(if function.is_some_and(|f|f.name=="main"&&f.level==1){"程序入口"}else{kind(&a.kind)}))); - if let Some(signature) = &a.signature { - if signature.receiver == "instance" { - out.push_str("

          实例方法:先创建所属对象,再通过同一实例调用。

          "); - } - out.push_str("

          需要什么输入

          "); - if signature.params.is_empty() { - out.push_str("

          无需提供输入参数。

          "); - } else { - out.push_str("
          "); - for param in &signature.params { - let authored = function - .and_then(|f| f.contract.as_ref()) - .and_then(|c| c.params.iter().find(|p| p.name == param.name)); - let default = function - .and_then(|f| f.params.iter().find(|p| p.name == param.name)) - .and_then(|p| p.default.as_ref()) - .map(expr_display); - let supply = if param.required { - "必填".into() - } else { - default - .map(|v| format!("默认 {v}")) - .unwrap_or("可省略;默认值见源码".into()) - }; - out.push_str(&format!( - "", - escape(¶m.name), - escape(¶m.ty), - escape(&supply), - escape( - authored - .map(|p| p.desc.as_str()) - .filter(|s| !s.is_empty()) - .unwrap_or("源码未提供参数说明") - ) - )); - } - out.push_str("
          参数类型提供方式含义
          {}{}{}{}
          "); - } - let returns = function - .and_then(|f| f.contract.as_ref()) - .and_then(|c| c.returns.as_ref()); - out.push_str(&format!( - "

          返回什么

          {} · {}

          ", - escape(&signature.returns), - escape( - returns - .map(|r| r.desc.as_str()) - .filter(|s| !s.is_empty()) - .unwrap_or("源码未提供返回值说明;请结合正文实现阅读。") - ) - )); - } else { - out.push_str("

          这是程序入口或对象声明。成员函数的输入输出在各自说明中列出。

          "); - if let Some(returns) = function - .and_then(|f| f.contract.as_ref()) - .and_then(|c| c.returns.as_ref()) - { - out.push_str(&format!( - "

          源码中的返回契约

          {} · {}

          ", - escape(&returns.ty.name()), - escape(&returns.desc) - )); - } - } - out.push_str(&format!( - "

          调用边界

          {}。权限由实际运行入口授予;静态副作用信息不等于运行许可。

          ", - escape( - &a.effects - .values() - .iter() - .map(|s| effect(s)) - .collect::>() - .join("、") - ) - )); - if !a.dependencies.is_empty() { - out.push_str("

          依赖哪些知识

            "); - for dependency in &a.dependencies { - if let Some(target) = project - .artifacts - .iter() - .find(|other| other.artifact_id == *dependency) - { - if target.source.file == rel && target.kind != "module" { - out.push_str(&format!( - r##"
          • {}
          • "##, - target.source.line, - escape(&target.display_name) - )); - } else { - out.push_str(&format!( - "
          • {} {}
          • ", - escape(&target.display_name), - escape(&target.source.file) - )); - } - } else { - out.push_str("
          • 依赖尚未解析;完整标识见技术详情。
          • "); - } - } - out.push_str("
          "); - } - let v = &a.verification; - out.push_str(&format!("

          当前有哪些依据

          语法与引用
          {};{}
          契约检查
          {}
          测试记录
          {}
          内容来源
          {}
          领域审阅
          {}
          ",escape(&state(&v.parse)),escape(&state(&v.resolve)),escape(&state(&v.contract)),escape(&state(&v.tests)),escape(&state(&v.evidence)),escape(&state(&v.domain)))); - let owned: Vec<_> = steps - .iter() - .copied() - .filter(|s| s.source.line >= line && s.source.line < end) - .collect(); - out.push_str(&render_steps(project, &owned, "查看本单元的结构步骤")); - out.push_str(&technical(a)); - out.push_str("
          "); - } - out.push_str("
          "); - out -} diff --git a/src/view/logic.rs b/src/view/logic.rs deleted file mode 100755 index a3707d4..0000000 --- a/src/view/logic.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! Read-only presentation of link-shaped descriptions. No evaluation or fetching. -use crate::ast::{Arg, CallExpr, Expr, Literal, Module}; -use crate::view::{html::escape, render::expr_display}; -use pulldown_cmark::{html, Event, Options, Parser, Tag}; -use std::collections::HashMap; - -pub(crate) struct Span<'a> { - pub start: usize, - pub end: usize, - pub label: &'a str, - pub payload: &'a str, -} - -/// Preserve quoted source data in executable spans and inline code in narration. -pub(crate) fn spans(text: &str, code: bool) -> Vec> { - let bytes = text.as_bytes(); - let mut found = Vec::new(); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'\\' { i = (i + 2).min(bytes.len()); continue; } - if bytes[i] == b'\x60' || code && matches!(bytes[i], b'"' | b'\'') { - let quote = bytes[i]; - let run = if quote == b'\x60' { bytes[i..].iter().take_while(|b| **b == quote).count() } else { 1 }; - i += run; - while i < bytes.len() { - if bytes[i] == b'\\' { i = (i + 2).min(bytes.len()); } - else if bytes[i..].starts_with(&vec![quote; run]) { i += run; break; } - else { i += 1; } - } - continue; - } - if bytes[i] != b'[' || bytes.get(i + 1) == Some(&b'^') - || i > 0 && bytes[i - 1] == b'!' { - i += 1; continue; - } - let start = i; - let mut j = i + 1; - let mut depth = 1; - while j < bytes.len() { - match bytes[j] { - b'\\' => { j += 2; continue; } - b'[' => depth += 1, - b']' => { depth -= 1; if depth == 0 { break; } } - _ => {} - } - j += 1; - } - if depth != 0 || bytes.get(j + 1) != Some(&b'(') { i += 1; continue; } - let label_end = j; - j += 2; - let payload_start = j; - depth = 1; - while j < bytes.len() { - match bytes[j] { - b'\\' => { j += 2; continue; } - b'"' | b'\'' | b'\x60' if code || j == payload_start - || bytes.get(j.wrapping_sub(1)).is_some_and(|b| b" (=,[{:\t".contains(b)) => { - let quote = bytes[j]; j += 1; - while j < bytes.len() { - if bytes[j] == b'\\' { j += 2; } - else if bytes[j] == quote { j += 1; break; } - else { j += 1; } - } - continue; - } - b'(' => depth += 1, - b')' => { depth -= 1; if depth == 0 { break; } } - _ => {} - } - j += 1; - } - if depth == 0 { - found.push(Span { start, end: j + 1, label: &text[start + 1..label_end], payload: text[payload_start..j].trim() }); - i = j + 1; - } else { i += 1; } - } - found -} - -pub(crate) fn id(line: u32, at: usize) -> String { format!("logic-{line}-{at}") } - -fn markdown(text: &str) -> String { - let parser = Parser::new_ext(text, Options::ENABLE_STRIKETHROUGH).map(|event| match event { - Event::Html(value) | Event::InlineHtml(value) => Event::Text(value), - Event::Start(Tag::Image { .. }) => Event::Html("".into()), - Event::End(pulldown_cmark::TagEnd::Image) => Event::Html("".into()), - Event::Start(Tag::Link { dest_url, .. }) => Event::Html(format!("", escape(&dest_url)).into()), - Event::End(pulldown_cmark::TagEnd::Link) => Event::Html("".into()), - other => other, - }); - let mut rendered = String::new(); - html::push_html(&mut rendered, parser); - rendered -} -fn label_html(label: &str) -> String { - let label = if label.is_empty() { "未命名内容" } else { label }; - let value = markdown(label); - value.strip_prefix("

          ").and_then(|v| v.strip_suffix("

          \n")).unwrap_or(&value).to_string() -} -fn safe_href(target: &str) -> bool { - let normalized: String = target.chars().filter(|c| !c.is_ascii_whitespace() && !c.is_control()).collect(); - let lower = normalized.to_ascii_lowercase(); - !lower.starts_with("javascript:") && !lower.starts_with("vbscript:") - && !lower.starts_with("data:") && !lower.starts_with("file:") -} -fn destination(payload: &str) -> Option { - let candidate = format!("[target]({payload})"); - let target = Parser::new(&candidate).find_map(|event| match event { - Event::Start(Tag::Link { dest_url, .. }) => Some(dest_url.into_string()), - _ => None, - }).unwrap_or_else(|| payload.trim_matches(['<', '>']).to_string()); - let scheme = target.split_once(':').is_some_and(|(scheme, _)| - scheme.starts_with(|c: char| c.is_ascii_alphabetic()) - && scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))); - let relative_path = target.contains('/') && !target.contains(['(', ')']) - && !target.chars().any(char::is_whitespace) - && target.starts_with(|c: char| c.is_alphabetic()); - let looks_like_link = scheme || relative_path || target.starts_with('#') || target.starts_with('/') - || target.starts_with("./") || target.starts_with("../") - || target.starts_with("mailto:") || target.starts_with("tel:") - || target.to_ascii_lowercase().starts_with("javascript:") - || target.to_ascii_lowercase().starts_with("data:") - || target.to_ascii_lowercase().starts_with("vbscript:") - || [".mq.md", ".md", ".html", ".pdf", ".txt", ".json", ".svg", ".png"] - .iter().any(|ext| target.split(['?', '#']).next().unwrap_or("").ends_with(ext)); - looks_like_link.then_some(target) -} - -struct Payload { kind: &'static str, heading: &'static str, body: String, href: Option } -fn payload(text: &str) -> Payload { - if text.trim().is_empty() { - return Payload { kind:"empty", heading:"待补充", body:"

          待补充实际逻辑

          ".into(), href:None }; - } - let expression = crate::parse::expr::parse_expr_prefer_var(text).ok(); - if let Some(target) = destination(text).filter(|_| !matches!(expression, Some(Expr::List(_) | Expr::Map(_) | Expr::Literal(_)))) { - let body = if safe_href(&target) { - let external = target.starts_with("https://") || target.starts_with("http://") || target.starts_with("//"); - let attributes = if external { " target=\"_blank\" rel=\"noopener noreferrer\"" } else { "" }; - format!("{}打开链接 ↗", escape(&target), escape(&target), escape(&target)) - } else { - format!("

          此目标仅作为文字显示,不启用跳转。

          ", escape(&target)) - }; - return Payload { kind:"link", heading:"跳转链接", body, href:safe_href(&target).then_some(target) }; - } - if text.starts_with(['[', '{']) { - if let Ok(value) = serde_json::from_str::(text) { - return Payload { kind:"value", heading:"内容与值", body:json_html(&value, 0), href:None }; - } - } - if let Some(expression) = expression { - let (kind, heading) = match expression { - Expr::Call(_) => ("call", "函数调用"), - Expr::List(_) | Expr::Map(_) | Expr::Literal(_) => ("value", "内容与值"), - Expr::Var(_) => ("reference", "引用"), - _ => ("expression", "表达式"), - }; - return Payload { kind, heading, body:expression_html(&expression, 0), href:None }; - } - Payload { kind:"content", heading:"内容说明", body:format!("
          {}
          ", markdown(text)), href:None } -} -/// JSON is document content here, never passed to the evaluator as an expression. -fn json_html(value: &serde_json::Value, depth: usize) -> String { - if depth > 5 { return format!("{}", escape(&value.to_string())); } - match value { - serde_json::Value::Array(values) => { - if values.is_empty() { return "空列表".into(); } - format!("
            {}
          ", values.iter() - .map(|v| format!("
        • {}
        • ", json_html(v, depth + 1))).collect::()) - } - serde_json::Value::Object(values) => { - if values.is_empty() { return "空记录".into(); } - format!("
          {}
          ", values.iter() - .map(|(key, v)| format!("
          {}
          {}
          ", escape(key), json_html(v, depth + 1))).collect::()) - } - serde_json::Value::String(value) => format!("{}", escape(value)), - _ => format!("{}", escape(&value.to_string())), - } -} -fn call_name(call: &CallExpr) -> String { - if let Some(receiver) = &call.receiver { format!("{receiver}.{}", call.callee) } - else if let Some(path) = &call.path { path.join(".") } - else { call.callee.clone() } -} -fn expression_html(expression: &Expr, depth: usize) -> String { - if depth > 5 { return format!("{}", escape(&expr_display(expression))); } - match expression { - Expr::Call(call) => { - let name = call_name(call); - let mut out = format!("
          {}", escape(&name), escape(&name)); - if !call.pre_modifiers.is_empty() { out.push_str(&format!("{}", escape(&call.pre_modifiers.join(" ")))); } - if call.args.is_empty() { out.push_str("

          无需传入参数

          "); } - else { - out.push_str("
          "); - for (index, argument) in call.args.iter().enumerate() { - let (name, value) = match argument { - Arg::Named { name, value } => (name.clone(), value), - Arg::Positional(value) => (format!("参数 {}", index + 1), value), - }; - out.push_str(&format!("
          {}
          {}
          ", escape(&name), expression_html(value, depth + 1))); - } - out.push_str("
          "); - } - out.push_str("
          "); out - } - Expr::Literal(Literal::Text(value)) => - format!("{}", escape(value)), - Expr::Literal(_) | Expr::Var(_) => - format!("{}", escape(&expr_display(expression))), - Expr::List(values) => { - if values.is_empty() { return "空列表".into(); } - let rows = values.iter().map(|v| format!("
        • {}
        • ", expression_html(v, depth + 1))).collect::(); - format!("
            {rows}
          ") - } - Expr::Map(values) => { - if values.is_empty() { return "空记录".into(); } - let rows = values.iter().map(|(key, value)| format!("
          {}
          {}
          ", escape(key), expression_html(value, depth + 1))).collect::(); - format!("
          {rows}
          ") - } - Expr::Occluded { label, payload } => format!("
          {}{}
          ", escape(label), payload.as_deref().map(|v|expression_html(v,depth+1)).unwrap_or_else(||"待补充实际逻辑".into())), - _ => format!("{}", escape(&expr_display(expression))), - } -} - -pub(crate) fn source(line: u32, span: &Span<'_>, base: usize) -> String { - let id = id(line, base + span.start); - let item = payload(span.payload); - let attrs = format!("id=\"{id}-source\" data-logic-id=\"{id}\" data-line=\"{line}\" data-byte-start=\"{}\" data-byte-end=\"{}\" aria-describedby=\"{id}-note\"", base+span.start,base+span.end); - let label = label_html(span.label); - let mut out = if let Some(href) = item.href { - format!("{label}", escape(&href), escape(&href)) - } else { - format!("", item.heading) - }; - if item.kind == "empty" { out.push_str("待补充实际逻辑"); } - out -} -pub(crate) fn note(line: u32, span: &Span<'_>, base: usize, executable: bool) -> String { - let id = id(line, base+span.start); - let item = payload(span.payload); - let hint = if executable { "源码说明 · 不是运行结果" } else { "文档引用 · 阅读不会执行" }; - let original = if span.payload.is_empty() && executable { "待补充实际逻辑;当前空遮蔽返回 None。" } else { span.payload }; - format!(r#"
          {heading}{label}
          {body}
          原始写法
          {original}
          {hint}
          "#, - kind=item.kind, start=base+span.start, end=base+span.end, heading=item.heading, - label=label_html(span.label), body=item.body, original=escape(original)) -} - -pub(crate) struct Narrative { - pub markdown: String, - pub replacements: Vec<(String,String)>, - pub notes: String, -} -pub(crate) fn narrative(line: u32, text: &str, base: usize) -> Narrative { - let mut result = Narrative { markdown:String::new(), replacements:Vec::new(), notes:String::new() }; - let mut prefix = format!("MQVIEWLINK{line}X{base}Q"); - while text.contains(&prefix) { prefix.push('Q'); } - let mut cursor = 0; - for (index, span) in spans(text, false).into_iter().enumerate() { - let token = format!("{prefix}{index}END"); - result.markdown.push_str(&text[cursor..span.start]); - result.markdown.push_str(&token); - result.replacements.push((token,source(line,&span,base))); - result.notes.push_str(¬e(line,&span,base,false)); - cursor=span.end; - } - result.markdown.push_str(&text[cursor..]); - result -} -pub(crate) fn replace(mut html: String, replacements: &[(String,String)]) -> String { - for (token,value) in replacements { html=html.replace(token,value); } - html -} - -/// Link only unambiguous definitions in this document. -pub(crate) fn link_definitions(mut html: String, module: &Module) -> String { - fn walk(functions: &[crate::ast::Function], prefix:&str, names:&mut HashMap>) { - for function in functions { - let path=if prefix.is_empty(){function.name.clone()}else{format!("{prefix}.{}",function.name)}; - names.entry(path.clone()).or_default().push(function.span.line); - if !prefix.is_empty(){names.entry(function.name.clone()).or_default().push(function.span.line);} - walk(&function.children,&path,names); - } - } - let mut names=HashMap::new();walk(&module.functions,"",&mut names); - for (name,lines) in names { - if lines.len()!=1 {continue;} - let escaped=escape(&name); - html=html.replace(&format!("{escaped}"), - &format!("{escaped} ↗",lines[0])); - } - html -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn calls_and_collections_containing_urls_remain_structured_values() { - let call = payload("fetch(url=\"https://example.com/file.mq.md\", options={retry: 2})"); - assert_eq!(call.kind, "call"); - assert!(call.body.contains("logic-call-name") && call.body.contains("
          url
          ")); - assert!(call.body.contains("
          options
          ")); - assert!(!call.body.contains("logic-link-target")); - for text in ["[\"https://example.com\", 2]", "{\"url\": \"https://example.com\"}", "\"guide.mq.md\""] { - assert_eq!(payload(text).kind, "value", "{text}"); - } - } - #[test] - fn balanced_scanning_preserves_inline_code_quotes_and_byte_anchors() { - let code = "\"[data](untouched)\" [操作](f(value=\")\", nested=g(2))) [空]()"; - let found = spans(code, true); - assert_eq!(found.len(), 2); - assert_eq!(found[0].payload, "f(value=\")\", nested=g(2))"); - assert_eq!(&code[found[0].start..found[0].end], "[操作](f(value=\")\", nested=g(2)))"); - let narrative = "don't hide [链接](https://example.com/a(b)) or `[代码](opaque)`"; - let found = spans(narrative, false); - assert_eq!(found.len(), 1); - assert_eq!(found[0].label, "链接"); - } - #[test] - fn unsafe_targets_and_html_are_displayed_without_navigation_or_execution() { - for text in ["javascript:alert(1)", "data:text/html,", "vbscript:evil"] { - let item = payload(text); - assert_eq!(item.kind, "link"); - assert!(item.href.is_none()); - assert!(!item.body.contains("alert(1) beautiful prose"); - assert!(!item.body.contains("
          parse/load error: {}
          ", - escape(&tidy_user_error(&format!("{e:#}"), abs, rel)) - ), - None, - Vec::new(), - ), - }; - // Named tools are readable modules, not failed programs. Preserve actual - // execution for main, object entries and Artifact declarations. - let library_document = module_opt.as_ref().is_some_and(|module| { - !module.functions.is_empty() - && module.functions.iter().all(|f| !f.is_object() && f.name != "main") - && !module.metadata_raw.iter().any(|(key, _)| key == "type" || key == "类型") - }); - let effective = effective_stdin(&source, stdin_lines); - let awaiting_input = !library_document - && awaiting_preset_input(&input_prompts, stdin_lines, &source); - let show_stream = !library_document - && module_opt.as_ref().map(uses_stream_panel).unwrap_or(false); - // Live + LLM/agent import + has `input` + stdin ready → stream via client `/api/run`. - let auto_stream = live - && show_stream - && !input_prompts.is_empty() - && !awaiting_input - && !stdin_lines.is_empty(); - // Same host caps as `marqdo run`. Soft exit + sleep clamp only. - let mut opts = RunOptions::default(); - opts.stdin_lines = effective.clone(); - opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) }; - // Optional: sandbox to the whole view tree so sibling folders are reachable. - opts.fs_root = Some(root.root.clone()); - let mut captured: Option = None; - let (stdout, stderr, ok, plots, mut bindings_html) = if !execute { - ( - String::new(), - "execution skipped (--no-exec)".into(), - true, - Vec::new(), - String::from(r#"

          skipped

          "#), - ) - } else if library_document { - ( - String::new(), - String::new(), - true, - Vec::new(), - String::from(r#"

          Choose a named function with marqdo call.

          "#), - ) - } else if awaiting_input || auto_stream { - ( - String::new(), - String::new(), - true, - Vec::new(), - String::new(), - ) - } else { - match run_file_capture(abs, &opts) { - Ok(cap) => { - let stdout = cap.stdout.clone(); - let plots = cap.plots.iter().map(|p| p.svg.clone()).collect(); - let bindings_html = render_bindings_html(&cap.bindings); - captured = Some(cap); - (stdout, String::new(), true, plots, bindings_html) - } - Err(e) => ( - String::new(), - tidy_user_error(&format!("{e:#}"), abs, rel), - false, - Vec::new(), - String::new(), - ), - } - }; - // Re-read after run so writeback slots / workbook edits show in Structure. - if execute && !library_document && !awaiting_input && !auto_stream { - if let Ok(next) = fs::read_to_string(abs) { - source = next; - } - if let Ok(module) = crate::load::parse_source_auto(&source) { - let annots = match &captured { - Some(cap) => build_view_annots(&module, &source, cap), - None => Vec::new(), - }; - structure = render_module_structure_with_annots(&module, &source, &annots); - module_opt = Some(module); - } - } - let wb = crate::view::render::render_writeback_outline(&source); - let outline = match &module_opt { - Some(module) => render_right_rail(module, &bindings_html, &wb), - None => { - if bindings_html.is_empty() && wb.is_empty() { - String::new() - } else { - render_right_rail(&crate::ast::Module::default(), &bindings_html, &wb) - } - } - }; - let trace_json = match &captured { - Some(cap) => view_execution_report_json(rel, ok, cap), - None => String::new(), - }; - // Analysis is intentionally independent from capture/run. If a document - // has side effects, its facts remain visible while its values stay absent. - let title_guess = crate::view::title_from_source(&source, rel); - let analysis = if root.only_file.is_some() { - crate::sema::compile_file_closure(abs) - } else { - crate::sema::compile_project(&crate::sema::CompileOptions { - project_root: root.root.clone(), - entry: Some(abs.to_path_buf()), - lock_mode: crate::sema::LockMode::Off, - }) - }; - let (knowledge_html, knowledge_error, page_token) = match analysis { - Ok(compilation) => { - // Dependency closures may have a wider root than the reader's file directory. - let semantic_rel = abs - .strip_prefix(&compilation.semantics.root) - .unwrap_or(abs) - .to_string_lossy() - .replace('\\', "/"); - let html = crate::view::knowledge_reading::render( - &compilation.semantics, - &semantic_rel, - module_opt.as_ref(), - ); - // V1: also materialize structured presentation (JSON available to page scripts). - let mut presentation = crate::view::KnowledgePresentation::from_project( - &compilation.semantics, - &semantic_rel, - &title_guess, - ); - presentation.document_id = rel.to_string(); - presentation.page_token = crate::view::page_token_from_source(rel, &source); - let json = presentation.to_json().to_string(); - let with_model = if html.is_empty() { - format!( - r#""#, - json = json.replace("{json}"#, - html = html, - json = json.replace(" ( - String::new(), - format!( - "知识关系暂不可用:{}", - tidy_user_error(&format!("{e:#}"), abs, rel) - ), - crate::view::page_token_from_source(rel, &source), - ), - }; - let page_token = if page_token.is_empty() { - crate::view::page_token_from_source(rel, &source) - } else { - page_token - }; - Ok(FileViewModel { - rel_path: rel.to_string(), - source, - structure_html: html::document_links(&structure, &root.files, rel, &LinkMode::Live), - outline_html: outline, - stdout, - stderr, - ok, - library_document, - preset_stdin: effective.join("\n"), - input_prompts, - awaiting_input, - auto_stream, - show_stream, - plots, - bindings_html: std::mem::take(&mut bindings_html), - trace_json, - knowledge_html, - knowledge_error, - page_token, - }) -} - -/// Defer execution until the view preset-input form supplies lines (no query stdin, no FM stdin). -pub(crate) fn awaiting_preset_input( - input_prompts: &[String], - stdin_lines: &[String], - source: &str, -) -> bool { - !input_prompts.is_empty() - && stdin_lines.is_empty() - && extract_frontmatter_stdin(source).is_empty() -} - -/// Prefer view-relative paths and strip Windows `\\?\` noise in error text. -fn tidy_user_error(msg: &str, abs: &Path, rel: &str) -> String { - use crate::diagnostics::display_path; - let mut s = msg.to_string(); - let abs_disp = abs.display().to_string(); - let abs_clean = display_path(abs); - for candidate in [ - abs_disp.as_str(), - abs_clean.as_str(), - &abs_disp.replace('/', "\\"), - &abs_clean.replace('/', "\\"), - &abs_disp.replace('\\', "/"), - &abs_clean.replace('\\', "/"), - ] { - if !candidate.is_empty() { - s = s.replace(candidate, rel); - } - } - // Leftover extended prefixes anywhere in the message - s = s.replace(r"\\?\", ""); - s = s.replace("//?/", ""); - s -} - -fn resolve_rel(root: &ViewRoot, rel: &str) -> Result { - if rel.is_empty() { - bail!("missing path"); - } - let rel_path = PathBuf::from(rel.replace('\\', "/")); - if rel_path - .components() - .any(|c| matches!(c, std::path::Component::ParentDir)) - { - bail!("path escapes root"); - } - if let Some(only) = &root.only_file { - if &rel_path != only { - bail!("file not in view scope"); - } - } else if !root.files.iter().any(|f| f == &rel_path) { - // also allow forward-slash normalized compare - let norm = rel_path.to_string_lossy().replace('\\', "/"); - if !root - .files - .iter() - .any(|f| f.to_string_lossy().replace('\\', "/") == norm) - { - bail!("unknown file: {rel}"); - } - } - let abs = root.root.join(&rel_path); - let canon = abs.canonicalize().unwrap_or(abs.clone()); - let root_canon = root.root.canonicalize().unwrap_or_else(|_| root.root.clone()); - if !canon.starts_with(&root_canon) { - bail!("path escapes root"); - } - if !is_mq_md(&canon) { - bail!("not a .mq.md file"); - } - Ok(canon) -} - -fn split_url(url: &str) -> (&str, &str) { - match url.split_once('?') { - Some((p, q)) => (p, q), - None => (url, ""), - } -} - -fn query_param<'a>(query: &'a str, key: &str) -> Option { - for pair in query.split('&') { - let mut kv = pair.splitn(2, '='); - let k = kv.next()?; - let v = kv.next().unwrap_or(""); - if k == key { - return Some(urlencoding_decode(v)); - } - } - None -} - -fn urlencoding_decode(s: &str) -> String { - // Minimal decode for %XX and + (UTF-8 byte sequences, not Latin-1 chars). - let mut out = Vec::new(); - let bytes = s.as_bytes(); - let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'+' => { - out.push(b' '); - i += 1; - } - b'%' if i + 2 < bytes.len() => { - let hex = &s[i + 1..i + 3]; - if let Ok(v) = u8::from_str_radix(hex, 16) { - out.push(v); - i += 3; - } else { - out.push(b'%'); - i += 1; - } - } - c => { - out.push(c); - i += 1; - } - } - } - String::from_utf8_lossy(&out).into_owned() -} - -fn files_json(files: &[PathBuf]) -> String { - let list: Vec = files - .iter() - .map(|f| format!("\"{}\"", escape_json(&f.to_string_lossy().replace('\\', "/")))) - .collect(); - format!("{{\"files\":[{}]}}", list.join(",")) -} - -fn escape_json(s: &str) -> String { - s.replace('\\', "\\\\").replace('"', "\\\"") -} - -fn api_debug_post( - mut request: Request, - f: impl FnOnce(&str) -> serde_json::Value, -) -> Result<()> { - let mut body = Vec::new(); - std::io::Read::read_to_end(&mut request.as_reader(), &mut body)?; - let body = String::from_utf8_lossy(&body); - respond_json(request, f(&body).to_string()) -} - -fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> { - let mut body = Vec::new(); - std::io::Read::read_to_end(&mut request.as_reader(), &mut body)?; - let body = String::from_utf8_lossy(&body); - let v: serde_json::Value = serde_json::from_str(&body).unwrap_or(serde_json::Value::Null); - let lang = v - .get("lang") - .and_then(|x| x.as_str()) - .unwrap_or("python"); - let source = v.get("source").and_then(|x| x.as_str()).unwrap_or(""); - let stdin = v.get("stdin").and_then(|x| x.as_str()); - let timeout = v.get("timeout").and_then(|x| x.as_f64()); - let cmd = v - .get("cmd") - .and_then(|x| x.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()); - let json = if source.is_empty() { - serde_json::json!({ "ok": false, "error": "missing source" }).to_string() - } else { - match crate::host::foreign::invoke_for_view( - &root.root, - lang, - source, - cmd, - stdin, - timeout, - ) { - Ok(value) => match crate::host::json::value_to_json(&value) { - Ok(j) => j.to_string(), - Err(e) => serde_json::json!({ "ok": false, "error": e }).to_string(), - }, - Err(error) => serde_json::json!({ "ok": false, "error": error }).to_string(), - } - }; - respond_json(request, json) -} - -/// SSE: long-lived `text/event-stream` of EventBus JSON maps (`data: …\n\n`). -/// Kept for debugging; the Stream panel uses `POST /api/run` instead (no page-load spinner). -fn api_events(request: Request) -> Result<()> { - let rx = crate::host::event_bus::EventBus::global().subscribe(); - respond_sse(request, SseBody::new(rx, false)) -} - -/// Run a file and stream EventBus events as SSE on this same response (ChatGPT-style fetch stream). -fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> { - let mut body = Vec::new(); - std::io::Read::read_to_end(&mut request.as_reader(), &mut body)?; - let body = String::from_utf8_lossy(&body); - let v: serde_json::Value = serde_json::from_str(&body).unwrap_or(serde_json::Value::Null); - let rel = v.get("path").and_then(|x| x.as_str()).unwrap_or("").to_string(); - let stdin_raw = v.get("stdin").and_then(|x| x.as_str()).unwrap_or(""); - let stdin_lines = split_stdin_text(stdin_raw); - if rel.is_empty() { - return respond_json_status( - request, - StatusCode(400), - serde_json::json!({ "ok": false, "error": "missing path" }).to_string(), - ); - } - let abs = match resolve_rel(root, &rel) { - Ok(p) => p, - Err(e) => { - return respond_json_status( - request, - StatusCode(400), - serde_json::json!({ "ok": false, "error": format!("{e:#}") }).to_string(), - ); - } - }; - // Subscribe before spawn so early tokens are not lost. - let rx = crate::host::event_bus::EventBus::global().subscribe(); - let run_id = next_run_id(); - let root_path = root.root.clone(); - let rel_clone = rel.clone(); - std::thread::spawn(move || { - let start = serde_json::json!({ - "type": "run_start", - "run_id": run_id, - "path": rel_clone, - }); - crate::host::event_bus::EventBus::global().publish_json(&start.to_string()); - let source = fs::read_to_string(&abs).unwrap_or_default(); - let effective = effective_stdin(&source, &stdin_lines); - let mut opts = RunOptions::default(); - opts.stdin_lines = effective; - opts.sleep_limit_ms = Some(30_000); - opts.fs_root = Some(root_path); - match run_file_capture(&abs, &opts) { - Ok(cap) => { - // Keep the terminal frame small — tokens already streamed via bus. - let preview: String = cap.stdout.chars().take(500).collect(); - let bindings_html = render_bindings_html(&cap.bindings); - let source_now = fs::read_to_string(&abs).unwrap_or(source); - let (structure_html, trace_json) = match crate::load::parse_source_auto(&source_now) { - Ok(module) => { - let annots = build_view_annots(&module, &source_now, &cap); - ( - render_module_structure_with_annots(&module, &source_now, &annots), - view_execution_report_json(&rel_clone, true, &cap), - ) - } - Err(_) => (String::new(), String::new()), - }; - let page_token = crate::view::page_token_from_source(&rel_clone, &source_now); - let done = serde_json::json!({ - "type": "done", - "run_id": run_id, - "path": rel_clone, - "ok": true, - "result": preview, - "bindings_html": bindings_html, - "structure_html": structure_html, - "trace_json": trace_json, - "page_token": page_token, - }); - crate::host::event_bus::EventBus::global().publish_json(&done.to_string()); - } - Err(e) => { - let err = serde_json::json!({ - "type": "error", - "run_id": run_id, - "path": rel_clone, - "message": format!("{e:#}"), - }); - crate::host::event_bus::EventBus::global().publish_json(&err.to_string()); - } - } - }); - // Only close on this run's terminal frame — ignore nested LLM `done` without run_id. - respond_sse(request, SseBody::for_run(rx, run_id)) -} - -fn next_run_id() -> u64 { - use std::sync::atomic::{AtomicU64, Ordering}; - static SEQ: AtomicU64 = AtomicU64::new(1); - SEQ.fetch_add(1, Ordering::Relaxed) -} - -fn respond_sse(request: Request, body: SseBody) -> Result<()> { - let ct = Header::from_bytes(&b"Content-Type"[..], &b"text/event-stream; charset=utf-8"[..]) - .map_err(|_| anyhow::anyhow!("header"))?; - let cc = Header::from_bytes(&b"Cache-Control"[..], &b"no-cache, no-transform"[..]) - .map_err(|_| anyhow::anyhow!("header"))?; - let conn = Header::from_bytes(&b"Connection"[..], &b"keep-alive"[..]) - .map_err(|_| anyhow::anyhow!("header"))?; - let xb = Header::from_bytes(&b"X-Accel-Buffering"[..], &b"no"[..]) - .map_err(|_| anyhow::anyhow!("header"))?; - let resp = Response::empty(StatusCode(200)) - .with_header(ct) - .with_header(cc) - .with_header(conn) - .with_header(xb) - .with_data(body, None) - .with_chunked_threshold(0); - request.respond(resp).context("respond sse")?; - Ok(()) -} - -struct SseBody { - rx: Receiver, - buf: Vec, - pos: usize, - /// When set, close after a `done`/`error` frame that carries this `run_id`. - stop_run_id: Option, - closed: bool, -} - -impl SseBody { - fn new(rx: Receiver, _legacy: bool) -> Self { - Self { - rx, - buf: Vec::new(), - pos: 0, - stop_run_id: None, - closed: false, - } - } - - fn for_run(rx: Receiver, run_id: u64) -> Self { - // Prime with a comment so proxies/browsers flush response headers immediately - // (industry SSE practice: first bytes ASAP after Content-Type). - Self { - rx, - buf: b": connected\n\n".to_vec(), - pos: 0, - stop_run_id: Some(run_id), - closed: false, - } - } - - fn frame_ends_run(json: &str, run_id: u64) -> bool { - let id_marker = format!("\"run_id\":{run_id}"); - if !json.contains(&id_marker) { - return false; - } - json.contains("\"type\":\"done\"") || json.contains("\"type\":\"error\"") - } -} - -impl Read for SseBody { - fn read(&mut self, out: &mut [u8]) -> io::Result { - if self.closed && self.pos >= self.buf.len() { - return Ok(0); - } - loop { - if self.pos < self.buf.len() { - let n = (self.buf.len() - self.pos).min(out.len()); - out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]); - self.pos += n; - return Ok(n); - } - if self.closed { - return Ok(0); - } - match self.rx.recv_timeout(Duration::from_secs(15)) { - Ok(json) => { - // One event per TCP write — smooth token UX. Do not coalesce large - // batches (that caused jumpy "dump then pause" in the Stream panel). - let terminal = self - .stop_run_id - .map(|id| Self::frame_ends_run(&json, id)) - .unwrap_or(false); - self.buf = format!("data: {json}\n\n").into_bytes(); - self.pos = 0; - if terminal { - self.closed = true; - } - } - Err(RecvTimeoutError::Timeout) => { - // Comment heartbeat keeps intermediaries from buffering forever. - self.buf = b": ping\n\n".to_vec(); - self.pos = 0; - } - Err(RecvTimeoutError::Disconnected) => { - self.closed = true; - return Ok(0); - } - } - } - } -} - -fn respond_html(request: Request, body: String) -> Result<()> { - let header = Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]) - .map_err(|_| anyhow::anyhow!("header"))?; - let resp = Response::from_string(body).with_header(header); - request.respond(resp).context("respond")?; - Ok(()) -} - -fn respond_json(request: Request, body: String) -> Result<()> { - respond_json_status(request, StatusCode(200), body) -} - -fn respond_json_status(request: Request, code: StatusCode, body: String) -> Result<()> { - let header = Header::from_bytes(&b"Content-Type"[..], &b"application/json; charset=utf-8"[..]) - .map_err(|_| anyhow::anyhow!("header"))?; - let resp = Response::from_string(body) - .with_status_code(code) - .with_header(header); - request.respond(resp).context("respond")?; - Ok(()) -} - -fn open_url(url: &str) -> Result<()> { - #[cfg(target_os = "windows")] - { - Command::new("cmd") - .args(["/C", "start", "", url]) - .spawn() - .context("open browser")?; - } - #[cfg(target_os = "macos")] - { - Command::new("open").arg(url).spawn().context("open browser")?; - } - #[cfg(all(unix, not(target_os = "macos")))] - { - Command::new("xdg-open") - .arg(url) - .spawn() - .context("open browser")?; - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::awaiting_preset_input; - - #[test] - fn awaiting_input_when_no_stdin_source() { - let src = include_str!("../../tests/keywords/input.mq.md"); - assert!(awaiting_preset_input(&["Name: ".into()], &[], src)); - assert!(!awaiting_preset_input(&["Name: ".into()], &["Ada".into()], src)); - } - - #[test] - fn not_awaiting_when_frontmatter_stdin() { - let src = "---\nstdin: Ada\n---\n\n# main\n\n**n = > input**\n"; - assert!(!awaiting_preset_input(&["p".into()], &[], src)); - } -} diff --git a/src/view/notebook_api.rs b/src/view/notebook_api.rs deleted file mode 100755 index 900eaf5..0000000 --- a/src/view/notebook_api.rs +++ /dev/null @@ -1,662 +0,0 @@ -//! Live-view notebook session APIs. - -#[cfg(all(test, unix))] -mod interrupt_http_tests; - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, OnceLock, MutexGuard, TryLockError}; -use std::sync::atomic::{AtomicBool, Ordering}; - -use crate::host::json::{json_to_value, value_to_json}; -use crate::host::foreign_doc::DocumentSession; -use crate::value::Value; - -struct ApiSession { - closed: AtomicBool, - document: OnceLock, String>>, - control: crate::host::foreign_doc::DocumentControl, -} -impl ApiSession { - fn mutex(&self) -> Result<&Mutex, String> { - // `OnceLock::wait` needs Rust ≥1.84; MSRV is 1.81 — poll until init. - loop { - match self.document.get() { - Some(slot) => return slot.as_ref().map_err(Clone::clone), - None => std::thread::yield_now(), - } - } - } - fn lock(&self) -> Result, String> { - let guard = self.mutex()?.lock().map_err(|_| "session lock poisoned".to_string())?; - if self.closed.load(Ordering::Acquire) { return Err("session closed".into()); } - Ok(guard) - } -} -fn sessions() -> &'static Mutex>> { - static S: OnceLock>>> = OnceLock::new(); - S.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn body_value(body: &str) -> serde_json::Value { - serde_json::from_str(body).unwrap_or(serde_json::Value::Null) -} - -fn requested_path(root: &Path, v: &serde_json::Value) -> Result<(String, PathBuf), String> { - let rel = v - .get("path") - .and_then(|p| p.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if rel.is_empty() { - return Err("missing path".into()); - } - let abs = root.join(rel.replace('/', std::path::MAIN_SEPARATOR_STR)); - Ok((rel, abs)) -} - -fn path_of(root: &Path, v: &serde_json::Value) -> Result<(String, PathBuf), String> { - let (rel, abs) = requested_path(root, v)?; - if !abs.is_file() { - return Err(format!("file not found: {rel}")); - } - Ok((rel, abs)) -} - -fn get_or_open(root: &Path, abs: &Path) -> Result, String> { - let key = abs.display().to_string(); - let arc = { - let mut map = sessions().lock().map_err(|_| "session lock poisoned".to_string())?; - Arc::clone(map.entry(key.clone()).or_insert_with(|| Arc::new(ApiSession { - closed: AtomicBool::new(false), - control: Default::default(), document: OnceLock::new(), - }))) - }; - // Kernel startup may block. It must never hold the registry lock needed by - // interrupt requests for an unrelated already-running document. - let initialized = arc.document.get_or_init(|| DocumentSession::open(abs, root).map(|mut session| { - session.adopt_control(arc.control.clone()); - Mutex::new(session) - })); - if let Err(error) = initialized { - let mut map = sessions().lock().map_err(|_| "session lock poisoned".to_string())?; - if map.get(&key).is_some_and(|old| Arc::ptr_eq(old, &arc)) { map.remove(&key); } - return Err(error.clone()); - } - Ok(arc) -} - -fn json_value(v: &Value) -> serde_json::Value { - value_to_json(v).unwrap_or(serde_json::Value::Null) -} - -fn ok_session(session: &DocumentSession, extra: serde_json::Value) -> serde_json::Value { - let mut out = serde_json::json!({ - "ok": true, - "session": json_value(&session.summary()), - }); - if let (Some(dst), Some(src)) = (out.as_object_mut(), extra.as_object()) { - for (k, v) in src { - dst.insert(k.clone(), v.clone()); - } - } - out -} - -fn err(error: String) -> serde_json::Value { - serde_json::json!({ "ok": false, "error": error }) -} - -pub fn api_run_document(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let (rel, abs) = match path_of(root, &v) { - Ok(p) => p, - Err(e) => return err(e), - }; - let source = match std::fs::read_to_string(&abs) { - Ok(source) => source, - Err(e) => return err(e.to_string()), - }; - let mut opts = crate::RunOptions::default(); - opts.fs_root = Some(root.to_path_buf()); - opts.sleep_limit_ms = Some(30_000); - opts.stdin_lines = crate::input_feed::split_stdin_text(v["stdin"].as_str().unwrap_or("")); - match crate::run_file_capture(&abs, &opts) { - Ok(cap) => { - // Render annotations from this exact capture: fetching /api/view-trace - // would execute the program a second time and could change its result. - let (structure_html, trace_json) = match crate::load::parse_source_auto(&source) { - Ok(module) => { - let annots = crate::view::annot::build_view_annots(&module, &source, &cap); - ( - crate::view::render::render_module_structure_with_annots(&module, &source, &annots), - crate::view::annot::view_execution_report_json(&rel, true, &cap), - ) - } - Err(_) => (String::new(), String::new()), - }; - serde_json::json!({ - "ok": true, - "stdout": cap.stdout, - "value": json_value(&cap.value), - "structure_html": structure_html, - "trace_json": trace_json, - "bindings_html": crate::view::render::render_bindings_html(&cap.bindings), - "page_token": crate::view::page_token_from_source(&rel, &source), - }) - } - Err(e) => serde_json::json!({ "ok": false, "error": format!("{e:#}") }), - } -} - -pub fn api_open(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let (_rel, abs) = match path_of(root, &v) { - Ok(p) => p, - Err(e) => return err(e), - }; - match get_or_open(root, &abs) { - Ok(s) => match s.lock() { - Ok(mut sess) => { - if let Err(e) = sess.reload(root) { - return err(e); - } - ok_session(&sess, serde_json::json!({})) - } - Err(_) => err("session lock poisoned".into()), - }, - Err(e) => err(e), - } -} - -pub fn api_reload(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let (_rel, abs) = match path_of(root, &v) { - Ok(p) => p, - Err(e) => return err(e), - }; - match get_or_open(root, &abs) { - Ok(s) => match s.lock() { - Ok(mut sess) => match sess.reload(root) { - Ok(()) => ok_session(&sess, serde_json::json!({})), - Err(e) => err(e), - }, - Err(_) => err("session lock poisoned".into()), - }, - Err(e) => err(e), - } -} - -pub fn api_close(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let (_rel, abs) = match path_of(root, &v) { - Ok(p) => p, - Err(e) => return err(e), - }; - let key = abs.display().to_string(); - let removed = sessions() - .lock() - .ok() - .and_then(|mut m| m.remove(&key)); - if let Some(arc) = removed { - if let Ok(mut s) = arc.lock() { - arc.closed.store(true, Ordering::Release); - s.close(); - } - } - serde_json::json!({ "ok": true }) -} - -fn with_session(root: &Path, body: &str, action: &str, f: F) -> serde_json::Value -where - F: FnOnce(&mut DocumentSession) -> Result, -{ - let v = body_value(body); - let (_rel, abs) = match path_of(root, &v) { - Ok(p) => p, - Err(e) => return err(e), - }; - let arc = match get_or_open(root, &abs) { - Ok(s) => s, - Err(e) => return err(e), - }; - let mut sess = match arc.lock() { - Ok(s) => s, - Err(_) => return err("session lock poisoned".into()), - }; - match f(&mut sess) { - Ok(value) => { - let mut extra = serde_json::Map::new(); - extra.insert(action.into(), json_value(&value)); - ok_session(&sess, serde_json::Value::Object(extra)) - } - Err(e) => err(e), - } -} - -pub fn api_persist_cell(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); - let key = v.get("key").and_then(|x| x.as_str()).unwrap_or(""); - if cell.is_empty() { - return err("missing cell".into()); - } - with_session(root, body, "persisted", |s| s.persist_cell(cell, key)) -} - -pub fn api_interrupt(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - // A control request addresses an existing loaded session. It neither reads - // the source again nor creates a process as a side effect of cancellation. - let (_, abs) = match requested_path(root, &v) { Ok(p) => p, Err(e) => return err(e) }; - let session = match sessions().lock() { - Ok(map) => match map.get(&abs.display().to_string()) { Some(s) => s.clone(), None => return err("no open session".into()) }, - Err(_) => return err("session lock poisoned".into()), - }; - if session.closed.load(Ordering::Acquire) { return err("session closed".into()); } - let mutex = match session.document.get() { - Some(Ok(mutex)) => mutex, Some(Err(error)) => return err(error.clone()), - None => return err("session is still opening; no evaluation is active".into()), - }; - let result = match mutex.try_lock() { - Ok(mut document) => if session.closed.load(Ordering::Acquire) { err("session closed".into()) } else { match document.interrupt() { - Ok(value) => ok_session(&document, serde_json::json!({ "interrupted": json_value(&value), "in_flight": false })), - Err(error) => err(error), - } }, - Err(TryLockError::WouldBlock) => match session.control.interrupt() { - Ok(value) => { - let receipt = json_value(&value); - let accepted = receipt["results"].as_array().is_some_and(|rows| rows.iter().all(|row| row["accepted"] == true)); - if accepted { serde_json::json!({ "ok": true, "interrupted": receipt, "in_flight": true }) } - else { serde_json::json!({ "ok": false, "error": "interrupt delivery failed", "interrupted": receipt, "in_flight": true }) } - }, - Err(error) => err(error), - }, - Err(TryLockError::Poisoned(_)) => err("session lock poisoned".into()), - }; - result -} - -pub fn api_export_snapshot(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let compact = match v.get("compact") { None | Some(serde_json::Value::Bool(false)) => false, - Some(serde_json::Value::Bool(true)) => true, _ => return err("compact must be boolean".into()) }; - with_session(root, body, "snapshot", |s| { - let snapshot = s.export_snapshot()?; - if compact { crate::host::foreign_doc::packing::pack(&snapshot) } else { Ok(snapshot) } - }) -} - -pub fn api_import_snapshot(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let snapshot = v.get("snapshot").cloned().unwrap_or(serde_json::Value::Null); - let snapshot = match json_to_value(&snapshot).and_then(|value| if crate::host::foreign_doc::packing::is_packed(&value) { - crate::host::foreign_doc::packing::unpack(&value) - } else { Ok(value) }) { - Ok(v) => v, - Err(e) => return err(e), - }; - with_session(root, body, "restored", |s| s.import_snapshot(&snapshot)) -} - -pub fn api_replay_snapshot(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let snapshot = v.get("snapshot").cloned().unwrap_or(serde_json::Value::Null); - let snapshot = match json_to_value(&snapshot).and_then(|value| if crate::host::foreign_doc::packing::is_packed(&value) { - crate::host::foreign_doc::packing::unpack(&value) - } else { Ok(value) }) { - Ok(v) => v, - Err(e) => return err(e), - }; - with_session(root, body, "replay", |s| s.replay_snapshot(&snapshot)) -} - -pub fn api_replay_check(root: &Path, body: &str) -> serde_json::Value { - // Decode before serde_json::Value can overwrite duplicate recording fields. - let request = match crate::host::json::parse(&Value::Text(body.to_string())) { - Ok(value) => value, - Err(error) => return err(error), - }; - let v = match value_to_json(&request) { Ok(v) => v, Err(e) => return err(e) }; - let (_, abs) = match path_of(root, &v) { Ok(path) => path, Err(e) => return err(e) }; - let Value::Map(fields) = request else { return err("request must be a map".into()) }; - let Some((_, snapshot)) = fields.iter().find(|(k,_)| k == "snapshot") else { return err("missing snapshot".into()) }; - let check = match DocumentSession::check_snapshot_isolated(&abs, root, snapshot) { - Ok(check) => check, Err(error) => return err(error), - }; - let existing = match sessions().lock() { - Ok(map) => map.get(&abs.display().to_string()).cloned(), - Err(_) => return err("session lock poisoned".into()), - }; - let extra = serde_json::json!({"replay_check": json_value(&check)}); - if let Some(arc) = existing { - match arc.lock() { Ok(session) => ok_session(&session, extra), Err(_) => err("session lock poisoned".into()) } - } else { - serde_json::json!({"ok": true, "replay_check": json_value(&check)}) - } -} - -pub fn api_clear_cell(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); - if cell.is_empty() { - return err("missing cell".into()); - } - with_session(root, body, "cleared", |s| s.clear_cell(cell)) -} - -pub fn api_clear(root: &Path, body: &str) -> serde_json::Value { - with_session(root, body, "cleared", |s| Ok(s.clear_outputs())) -} - -pub fn api_cell_run(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); - let kernel = v.get("kernel").and_then(|x| x.as_str()).filter(|s| !s.is_empty()); - let stdin = v.get("stdin").and_then(|x| x.as_str()); - if cell.is_empty() { - return err("missing cell".into()); - } - with_session(root, body, "record", |s| s.run_cell_with_stdin(cell, kernel, stdin)) -} - -pub fn api_cell_step(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let stdin = v.get("stdin").and_then(|x| x.as_str()); - with_session(root, body, "record", |s| s.step_with_stdin(stdin)) -} - -pub fn api_run_all(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let restart = v.get("restart").and_then(|x| x.as_bool()).unwrap_or(false); - let stdin = v.get("stdin").and_then(|x| x.as_str()); - let inputs: Option> = v.get("inputs").and_then(|x| x.as_object()).map(|m| { - m.iter() - .filter_map(|(k, val)| val.as_str().map(|s| (k.clone(), s.to_string()))) - .collect() - }); - with_session(root, body, "summary", |s| s.run_all_with_inputs(restart, stdin, inputs.as_ref())) -} - -pub fn api_kernel_restart(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); - if kernel.is_empty() { - return err("missing kernel".into()); - } - with_session(root, body, "value", |s| s.restart_kernel(kernel)) -} - -pub fn api_plan_assign(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); - let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); - if cell.is_empty() || kernel.is_empty() { - return err("missing cell/kernel".into()); - } - with_session(root, body, "value", |s| s.assign_kernel(cell, kernel)) -} - -pub fn api_plan_add(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); - let lang = v.get("lang").and_then(|x| x.as_str()).unwrap_or(""); - let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); - let source = v.get("source").and_then(|x| x.as_str()).unwrap_or(""); - if cell.is_empty() || lang.is_empty() || kernel.is_empty() { - return err("missing cell/lang/kernel".into()); - } - with_session(root, body, "value", |s| s.add_cell(cell, lang, source, kernel)) -} - -pub fn api_plan_remove(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); - if cell.is_empty() { - return err("missing cell".into()); - } - with_session(root, body, "value", |s| s.remove_cell(cell)) -} - -pub fn api_plan_value(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); - let name = v.get("name").and_then(|x| x.as_str()).unwrap_or(""); - if kernel.is_empty() || name.is_empty() { - return err("missing kernel/name".into()); - } - let value = match v.get("value") { - Some(v) => match json_to_value(v) { - Ok(v) => v, - Err(e) => return err(e), - }, - None => Value::None, - }; - with_session(root, body, "value", |s| s.set_value(kernel, name, value)) -} - -pub fn api_assign(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); - let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); - if cell.is_empty() || kernel.is_empty() { - return err("missing cell/kernel".into()); - } - with_session(root, body, "value", |s| s.assign_kernel(cell, kernel)) -} - -pub fn api_state_list(root: &Path, body: &str) -> serde_json::Value { - with_session(root, body, "state", |s| s.state_list()) -} - -pub fn api_state_push(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); - let name = v.get("name").and_then(|x| x.as_str()).unwrap_or(""); - if kernel.is_empty() || name.is_empty() { - return err("missing kernel/name".into()); - } - let value = match v.get("value") { - Some(v) => match json_to_value(v) { - Ok(v) => v, - Err(e) => return err(e), - }, - None => Value::None, - }; - with_session(root, body, "value", |s| s.push_value(kernel, name, value)) -} - -pub fn api_state_pull(root: &Path, body: &str) -> serde_json::Value { - let v = body_value(body); - let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); - let name = v.get("name").and_then(|x| x.as_str()).unwrap_or(""); - if kernel.is_empty() || name.is_empty() { - return err("missing kernel/name".into()); - } - with_session(root, body, "value", |s| s.pull_value(kernel, name)) -} - -pub fn api_journal(root: &Path, body: &str) -> serde_json::Value { - with_session(root, body, "journal", |s| Ok(s.journal_json())) -} - -pub fn api_oracle_journal(root: &Path, body: &str) -> serde_json::Value { - with_session(root, body, "oracle_journal", |s| Ok(s.oracle_journal_json())) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn node_available() -> bool { - std::process::Command::new("node") - .args(["-e", "process.exit(0)"]) - .output() - .map(|o| o.status.success()) - .unwrap_or(false) - } - - fn open_body() -> &'static str { - r#"{"path":"shared.mq.md"}"# - } - - #[test] - fn api_shared_state_and_kernel_switch() { - if !node_available() { - return; - } - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/notebook"); - let open = api_open(&root, open_body()); - assert_eq!(open.get("ok").and_then(|v| v.as_bool()), Some(true), "{open:?}"); - let run = api_cell_run( - &root, - r#"{"path":"shared.mq.md","cell":"设置"}"#, - ); - assert_eq!(run.get("ok").and_then(|v| v.as_bool()), Some(true), "{run:?}"); - let read = api_cell_run( - &root, - r#"{"path":"shared.mq.md","cell":"读取"}"#, - ); - let stdout = read - .get("record") - .and_then(|r| r.get("stdout")) - .and_then(|v| v.as_str()) - .unwrap_or(""); - assert_eq!(stdout, "42\n", "{read:?}"); - let assign = api_assign( - &root, - r#"{"path":"shared.mq.md","cell":"读取","kernel":"绘图"}"#, - ); - assert_eq!(assign.get("ok").and_then(|v| v.as_bool()), Some(true), "{assign:?}"); - let failed = api_cell_run( - &root, - r#"{"path":"shared.mq.md","cell":"读取"}"#, - ); - assert_eq!( - failed - .get("record") - .and_then(|r| r.get("ok")) - .and_then(|v| v.as_bool()), - Some(false), - "{failed:?}" - ); - let clear = api_clear(&root, r#"{"path":"shared.mq.md"}"#); - assert_eq!(clear.get("ok").and_then(|v| v.as_bool()), Some(true), "{clear:?}"); - let cleared = clear.get("session").and_then(|s| s.get("cells")).and_then(|c| c.as_array()).cloned().unwrap_or_default(); - assert!(cleared.iter().all(|c| c.get("runs").and_then(|v| v.as_u64()) == Some(0))); - let push = api_state_push( - &root, - r#"{"path":"shared.mq.md","kernel":"分析","name":"z","value":9}"#, - ); - assert_eq!(push.get("ok").and_then(|v| v.as_bool()), Some(true), "{push:?}"); - let pull = api_state_pull( - &root, - r#"{"path":"shared.mq.md","kernel":"分析","name":"z"}"#, - ); - assert_eq!( - pull.get("value").and_then(|v| v.as_i64()), - Some(9), - "{pull:?}" - ); - let _ = api_close(&root, open_body()); - } -} - -#[cfg(test)] -mod replay_api_tests { - use super::*; - #[test] - fn closed_api_session_cannot_be_reactivated_after_path_reopen() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let relative = format!("target/api-close-capability-{}.mq.md", std::process::id()); - let path = root.join(&relative); - std::fs::write(&path, "---\nimport:\n foreign: lib/foreign.mq.md\n---\n# main\n\n`会话` = > foreign.session\n\n`a` =\n```python\nn = 1\n```\n").unwrap(); - let old = get_or_open(&root, &path).unwrap(); - old.lock().unwrap().run_all(false).unwrap(); - let body = serde_json::json!({"path": relative}).to_string(); - assert_eq!(api_close(&root, &body)["ok"], true); - let fresh = get_or_open(&root, &path).unwrap(); - assert!(!Arc::ptr_eq(&old, &fresh)); - assert!(old.lock().is_err()); - fresh.lock().unwrap().run_all(false).unwrap(); - assert_eq!(api_close(&root, &body)["ok"], true); - std::fs::remove_file(path).unwrap(); - } - #[test] - fn strict_replay_endpoint_uses_isolation_and_preserves_warm_session() { - let root=PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let relative=format!("target/api-replay-isolated-{}.mq.md",std::process::id());let path=root.join(&relative); - std::fs::write(&path,"---\nimport:\n foreign: lib/foreign.mq.md\n---\n# main\n\n`会话` = > foreign.session\n\n`a` =\n```python\nstate = globals().get('state',0) + 1\nprint(state)\n```\n").unwrap(); - let arc=get_or_open(&root,&path).unwrap(); - let (snapshot,kernel)={let mut live=arc.lock().unwrap();live.run_all(false).unwrap();let snapshot=live.export_snapshot().unwrap();let kernel=live.cells[0].kernel.clone();live.set_value(&kernel,"state",Value::Int(99)).unwrap();(snapshot,kernel)}; - let before={let live=arc.lock().unwrap();live.summary()}; - let body=serde_json::json!({"path":relative,"snapshot":value_to_json(&snapshot).unwrap()}).to_string(); - let response=api_replay_check(&root,&body); - assert_eq!(response["ok"],true,"{response}");assert_eq!(response["replay_check"]["ok"],true,"{response}"); - assert_eq!(arc.lock().unwrap().summary(),before,"verification mutated live state"); - let duplicate=body.replacen("\"snapshot\":", "\"snapshot\":null,\"snapshot\":",1); - let bad=api_replay_check(&root,&duplicate);assert_eq!(bad["ok"],false);assert!(bad["error"].as_str().unwrap().contains("duplicate")); - assert_eq!(arc.lock().unwrap().summary(),before); - assert_eq!(arc.lock().unwrap().pull_value(&kernel,"state").unwrap(),Value::Int(99),"isolated verification reset the user's actual kernel"); - sessions().lock().unwrap().remove(&path.display().to_string());arc.lock().unwrap().close();std::fs::remove_file(path).unwrap(); - } - #[cfg(unix)] - #[test] - fn malformed_replay_does_not_start_declared_seed_kernel() { - use std::os::unix::fs::PermissionsExt; - let root=PathBuf::from(env!("CARGO_MANIFEST_DIR"));let pid=std::process::id(); - let relative=format!("target/api-replay-seeded-{pid}.mq.md");let path=root.join(&relative); - let wrapper=root.join(format!("target/api-replay-wrapper-{pid}.py"));let marker=root.join(format!("target/api-replay-marker-{pid}")); - let marker_literal=serde_json::to_string(&marker.display().to_string()).unwrap(); - let script=format!("#!/usr/bin/env python3\nimport os,sys\nfrom pathlib import Path\nPath({marker_literal}).write_text('started')\nos.execv(sys.executable,[sys.executable]+sys.argv[1:])\n"); - std::fs::write(&wrapper,script).unwrap();std::fs::set_permissions(&wrapper,std::fs::Permissions::from_mode(0o755)).unwrap(); - let command=serde_json::to_string(&wrapper.display().to_string()).unwrap(); - let source=format!("---\nimport:\n foreign: lib/foreign.mq.md\n---\n# main\n\n`kernels` =\n| 名称 | 语言 | 命令 |\n|---|---|---|\n| py | python | {command} |\n\n`units` =\n| 单元 | 内核 |\n|---|---|\n| a | py |\n\n`initial` =\n| 内核 | 名称 | 值 |\n|---|---|---|\n| py | n | 1 |\n\n`会话` = > foreign.session kernels=`kernels` cells=`units` values=`initial`\n\n`a` =\n```python\nprint(n)\n```\n"); - std::fs::write(&path,source).unwrap();let mut recording=DocumentSession::open(&path,&root).unwrap(); - recording.run_all(false).unwrap();let snapshot=recording.export_snapshot().unwrap();recording.close();assert!(marker.exists());std::fs::remove_file(&marker).unwrap(); - let valid=value_to_json(&snapshot).unwrap();let mut malformed=valid.clone();malformed["actions"].as_array_mut().unwrap().pop(); - let cold = api_interrupt(&root, &serde_json::json!({"path":relative}).to_string()); - assert_eq!(cold["ok"], false); assert!(!marker.exists(), "cold interrupt started a kernel"); - let body=serde_json::json!({"path":relative,"snapshot":malformed}).to_string();let response=api_replay_check(&root,&body); - assert_eq!(response["ok"],false,"{response}");assert!(!marker.exists(),"malformed suffix started a seed kernel before preflight"); - assert!(!sessions().lock().unwrap().contains_key(&path.display().to_string())); - let packed = crate::host::foreign_doc::packing::pack(&snapshot).unwrap(); - let mut corrupt = value_to_json(&packed).unwrap(); corrupt["sha256"] = "bad".into(); - let response = api_replay_check(&root, &serde_json::json!({"path":relative,"snapshot":corrupt}).to_string()); - assert_eq!(response["ok"], false); assert!(!marker.exists(), "corrupt DAG started a seed kernel"); - let mut controls = valid.clone(); - controls["actions"][0]["controls"] = serde_json::json!([{"after_us":-1,"results":[]}]); - let response = api_replay_check(&root, &serde_json::json!({"path":relative,"snapshot":controls}).to_string()); - assert_eq!(response["ok"], false); assert!(!marker.exists(), "invalid control started a seed kernel"); - let response=api_replay_check(&root,&serde_json::json!({"path":relative,"snapshot":valid}).to_string()); - assert_eq!(response["replay_check"]["ok"],true,"{response}");assert!(marker.exists()); - assert!(!sessions().lock().unwrap().contains_key(&path.display().to_string())); - std::fs::remove_file(path).unwrap();std::fs::remove_file(wrapper).unwrap();std::fs::remove_file(marker).unwrap(); - } - -} - -#[cfg(test)] -mod reader_run_tests { - use super::*; - - #[test] - fn document_run_returns_matching_prose_trace_and_bindings() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let rel = format!("target/reader-run-{}.mq.md", std::process::id()); - let path = root.join(&rel); - std::fs::write(&path, "# main\n\n**n = 1**\n**n = n + 1**\n> print text=`n`\n*n*\n").unwrap(); - let result = api_run_document(&root, &serde_json::json!({"path": rel}).to_string()); - let _ = std::fs::remove_file(path); - assert_eq!(result["ok"], true, "{result}"); - assert_eq!(result["stdout"].as_str().unwrap().trim(), "2"); - let trace: serde_json::Value = serde_json::from_str(result["trace_json"].as_str().unwrap()).unwrap(); - let writes: Vec<_> = trace["events"].as_array().unwrap().iter() - .filter(|e| e["name"] == "n").filter_map(|e| e["value_after"].as_str()).collect(); - assert!(writes.contains(&"1") && writes.contains(&"2"), "{trace}"); - assert!(result["structure_html"].as_str().unwrap().contains("data-annot-band")); - assert!(result["bindings_html"].as_str().unwrap().contains("n")); - assert!(!result["page_token"].as_str().unwrap().is_empty()); - } -} diff --git a/src/view/notebook_api/interrupt_http_tests.rs b/src/view/notebook_api/interrupt_http_tests.rs deleted file mode 100755 index 32ce1cb..0000000 --- a/src/view/notebook_api/interrupt_http_tests.rs +++ /dev/null @@ -1,296 +0,0 @@ -use super::*; -use std::io::{Read, Write}; -use std::net::{SocketAddr, TcpStream}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; - -struct HttpServer { - addr: SocketAddr, - stop: Arc, - thread: Option>, -} -impl HttpServer { - fn start(root: &Path) -> Self { - let root = Arc::new(crate::view::build_root(root).unwrap()); - let server = tiny_http::Server::http("127.0.0.1:0").unwrap(); - let addr = server.server_addr().to_ip().unwrap(); - let stop = Arc::new(AtomicBool::new(false)); - let stopping = stop.clone(); - let thread = std::thread::spawn(move || { - let mut workers = Vec::new(); - while !stopping.load(Ordering::SeqCst) { - if let Some(request) = server.recv_timeout(Duration::from_millis(50)).unwrap() { - let root = root.clone(); - workers.push(std::thread::spawn(move || { - crate::view::handle(&root, request) - })); - } - } - for worker in workers { - let _ = worker.join(); - } - }); - Self { - addr, - stop, - thread: Some(thread), - } - } -} -impl Drop for HttpServer { - fn drop(&mut self) { - self.stop.store(true, Ordering::SeqCst); - if let Some(thread) = self.thread.take() { - let _ = thread.join(); - } - } -} -fn post(addr: SocketAddr, endpoint: &str, body: &serde_json::Value) -> serde_json::Value { - let bytes = body.to_string(); - let mut stream = TcpStream::connect(addr).unwrap(); - stream - .set_read_timeout(Some(Duration::from_secs(20))) - .unwrap(); - write!(stream, "POST /api/session/{endpoint} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{bytes}", bytes.len()).unwrap(); - let mut response = String::new(); - stream.read_to_string(&mut response).unwrap(); - let (_, body) = response.split_once("\r\n\r\n").unwrap(); - serde_json::from_str(body).unwrap_or_else(|e| panic!("{endpoint}: {e}: {response}")) -} - -#[test] -fn real_http_interrupt_preserves_store_stops_batch_and_replays_control_input() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let server = HttpServer::start(&root); - let repeats: usize = std::env::var("MARQDO_CANCEL_REPEATS") - .map(|s| s.parse().unwrap()) - .unwrap_or(1); - assert!(repeats > 0); - for language in ["python", "node"] { - for mode in ["cell/run", "cell/step", "run_all"] { - for trial in 0..repeats { - let id = format!( - "{}-{}-{language}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let relative = format!("target/http-cancel-{id}.mq.md"); - let path = root.join(&relative); - let marker = root.join(format!("target/http-cancel-started-{id}")); - let suffix = root.join(format!("target/http-cancel-suffix-{id}")); - let marker_literal = serde_json::to_string(&marker.display().to_string()).unwrap(); - let suffix_literal = serde_json::to_string(&suffix.display().to_string()).unwrap(); - let (busy, after) = if language == "python" { - (format!("n = 99\nopen({marker_literal}, 'w').write('started')\nwhile True: pass"), - format!("open({suffix_literal}, 'w').write('unexpected')\nn = 100")) - } else { - (format!("n = 99; require('fs').writeFileSync({marker_literal}, 'started'); while (true) {{}}"), - format!("require('fs').writeFileSync({suffix_literal}, 'unexpected'); n = 100;")) - }; - let source = format!("---\nimport:\n foreign: lib/foreign.mq.md\n---\n# main\n\n`kernels` =\n| 名称 | 语言 |\n|---|---|\n| worker | {language} |\n\n`units` =\n| 单元 | 内核 |\n|---|---|\n| busy | worker |\n| after | worker |\n\n`initial` =\n| 内核 | 名称 | 值 |\n|---|---|---|\n| worker | n | 1 |\n\n`会话` = > foreign.session kernels=`kernels` cells=`units` values=`initial`\n\n`busy` =\n```{language}\n{busy}\n```\n\n`after` =\n```{language}\n{after}\n```\n"); - std::fs::write(&path, &source).unwrap(); - let body = serde_json::json!({"path": relative}); - assert_eq!(post(server.addr, "open", &body)["ok"], true); - let addr = server.addr; - let mut running_body = body.clone(); - if mode == "cell/run" { - running_body["cell"] = "busy".into(); - } - let runner = std::thread::spawn(move || post(addr, mode, &running_body)); - let deadline = Instant::now() + Duration::from_secs(3); - while !marker.exists() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(2)); - } - assert!( - marker.exists(), - "{language}: evaluation never reached its side effect" - ); - let slow_open = if language == "python" && mode == "run_all" && trial == 0 { - let slow_relative = format!("target/http-slow-open-{id}.mq.md"); - let slow_path = root.join(&slow_relative); - let wrapper = root.join(format!("target/http-slow-wrapper-{id}.py")); - let started = root.join(format!("target/http-slow-started-{id}")); - let literal = serde_json::to_string(&started.display().to_string()).unwrap(); - std::fs::write(&wrapper, format!("import os,sys,time\nfrom pathlib import Path\nPath({literal}).write_text('opening')\ntime.sleep(2)\nos.execv(sys.executable,[sys.executable]+sys.argv[1:])\n")).unwrap(); - let command = - serde_json::to_string(&format!("python3 {}", wrapper.display())).unwrap(); - std::fs::write(&slow_path, format!("---\nimport:\n foreign: lib/foreign.mq.md\n---\n# main\n\n`kernels` =\n| 名称 | 语言 | 命令 |\n|---|---|---|\n| slow | python | {command} |\n\n`initial` =\n| 内核 | 名称 | 值 |\n|---|---|---|\n| slow | n | 1 |\n\n`会话` = > foreign.session kernels=`kernels` values=`initial`\n")).unwrap(); - let slow_body = serde_json::json!({"path":slow_relative}); - let opening_body = slow_body.clone(); - let opener = std::thread::spawn(move || post(addr, "open", &opening_body)); - let deadline = Instant::now() + Duration::from_secs(3); - while !started.exists() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(2)); - } - assert!(started.exists(), "unrelated slow kernel never started"); - let start = Instant::now(); - let pending = post(addr, "interrupt", &slow_body); - assert_eq!(pending["ok"], false, "{pending}"); - assert!( - start.elapsed() < Duration::from_secs(1), - "control waited for initialization" - ); - Some((opener, slow_body, slow_path, wrapper, started)) - } else { - None - }; - std::thread::sleep(Duration::from_millis([0, 5, 25, 50][trial % 4])); - let removed_source = language == "node" && mode == "cell/run" && trial == 0; - if removed_source { - std::fs::remove_file(&path).unwrap(); - } - let start = Instant::now(); - let interrupted = post(server.addr, "interrupt", &body); - let latency = start.elapsed(); - assert!( - latency < Duration::from_secs(1), - "interrupt queued behind execution: {latency:?}" - ); - assert_eq!(interrupted["ok"], true, "{interrupted}"); - assert_eq!(interrupted["in_flight"], true, "{interrupted}"); - assert_eq!( - interrupted["interrupted"]["results"][0]["active"], true, - "{interrupted}" - ); - let run = runner.join().unwrap(); - let completion_latency = start.elapsed(); - assert!( - completion_latency < Duration::from_secs(1), - "cancel did not finish execution promptly: {completion_latency:?}" - ); - if removed_source { - std::fs::write(&path, &source).unwrap(); - } - if let Some((opener, slow_body, slow_path, wrapper, started)) = slow_open { - assert_eq!(opener.join().unwrap()["ok"], true); - assert_eq!(post(server.addr, "close", &slow_body)["ok"], true); - for file in [slow_path, wrapper, started] { - std::fs::remove_file(file).unwrap(); - } - } - let record = if mode == "run_all" { - assert_eq!(run["summary"]["cancelled"], true, "{run}"); - assert_eq!(run["summary"]["ran"], 1, "{run}"); - assert_eq!(run["summary"]["remaining"], 1, "{run}"); - &run["summary"]["records"][0] - } else { - &run["record"] - }; - assert_eq!(record["ok"], false, "{run}"); - assert_eq!(record["timed_out"], false, "{run}"); - assert_eq!(record["alive"], true, "{run}"); - assert!( - !suffix.exists(), - "cancelled batch executed its dependent suffix" - ); - let pull = serde_json::json!({"path":relative,"kernel":"worker","name":"n"}); - assert_eq!(post(server.addr, "state/pull", &pull)["value"], 99); - let exported = post(server.addr, "snapshot/export", &body); - let snapshot = &exported["snapshot"]; - assert_eq!(snapshot["version"], 5); - let controls: Vec<_> = snapshot["actions"] - .as_array() - .unwrap() - .iter() - .filter(|a| a.get("controls").is_some()) - .collect(); - assert_eq!(controls.len(), 1); - assert_eq!( - controls[0]["kind"], - match mode { - "cell/run" => "cell", - "cell/step" => "step", - _ => "run_all", - } - ); - assert_eq!(controls[0]["controls"].as_array().unwrap().len(), 1); - let replay = post( - server.addr, - "snapshot/replay_check", - &serde_json::json!({"path":relative,"snapshot":snapshot}), - ); - assert_eq!(replay["replay_check"]["ok"], true, - "{language}: expected snapshot={snapshot}; actual replay={replay}"); - assert!(!suffix.exists(), "replay executed a cancelled suffix"); - let compact = post( - server.addr, - "snapshot/export", - &serde_json::json!({"path":relative,"compact":true}), - ); - assert_eq!( - compact["snapshot"]["format"], "marqdo.history.dag", - "{compact}" - ); - let replay_compact = post( - server.addr, - "snapshot/replay_check", - &serde_json::json!({"path":relative,"snapshot":compact["snapshot"]}), - ); - assert_eq!( - replay_compact["replay_check"]["ok"], true, - "expected snapshot={snapshot}; actual compact replay={replay_compact}" - ); - let mut corrupt = compact["snapshot"].clone(); - corrupt["sha256"] = "bad".into(); - let rejected = post( - server.addr, - "snapshot/replay_check", - &serde_json::json!({"path":relative,"snapshot":corrupt}), - ); - assert_eq!(rejected["ok"], false, "{rejected}"); - // A malformed cancellation suffix must fail before any replay executes. - for mutation in ["time", "receipt", "duplicate", "version"] { - let mut bad = snapshot.clone(); - let index = bad["actions"] - .as_array() - .unwrap() - .iter() - .position(|a| a.get("controls").is_some()) - .unwrap(); - match mutation { - "time" => bad["actions"][index]["controls"][0]["after_us"] = (-1).into(), - "receipt" => { - bad["actions"][index]["controls"][0]["results"][0]["accepted"] = - false.into() - } - "duplicate" => { - let row = bad["actions"][index]["controls"][0]["results"][0].clone(); - bad["actions"][index]["controls"][0]["results"] - .as_array_mut() - .unwrap() - .push(row); - } - _ => bad["version"] = 4.into(), - } - let rejected = post( - server.addr, - "snapshot/replay_check", - &serde_json::json!({"path":relative,"snapshot":bad}), - ); - assert_eq!(rejected["ok"], false, "{mutation}: {rejected}"); - } - assert_eq!( - post(server.addr, "state/pull", &pull)["value"], - 99, - "checker disturbed warm state" - ); - assert_eq!(post(server.addr, "close", &body)["ok"], true); - println!("E11 {language} {mode} trial {trial}: real HTTP interrupt {:?}, retained n=99, skipped suffix, control-input replay and four malformed histories verified", latency); - println!( - "CONTROL_METRIC:{}", - serde_json::json!({ - "language": language, "mode": mode, "trial": trial, - "ack_ns": latency.as_nanos(), "completion_ns": completion_latency.as_nanos(), - "expected_store": 99, "plain_replay": true, "compact_replay": true, - "malformed_histories": 5, "correct": true - }) - ); - std::fs::remove_file(path).unwrap(); - std::fs::remove_file(marker).unwrap(); - } - } - } -} diff --git a/src/view/output.rs b/src/view/output.rs deleted file mode 100755 index 8aa894c..0000000 --- a/src/view/output.rs +++ /dev/null @@ -1,390 +0,0 @@ -//! Static HTML export: `marqdo view output`. - -use std::collections::HashMap; -use std::fs; -use std::path::PathBuf; - -use anyhow::{Context, Result}; -use sha2::{Digest, Sha256}; - -use crate::host::foreign_doc::DocumentSession; -use crate::host::json::json_to_value; -use crate::value::Value; -use crate::view::html::{escape, page_file, page_index, LinkMode}; -use crate::view::{build_file_view, build_file_view_with_exec, build_root, ViewRoot}; - -pub struct OutputOptions { - pub path: PathBuf, - pub out_dir: PathBuf, - pub no_exec: bool, - pub snapshot: Option, -} - -pub struct CaptureOptions { - pub path: PathBuf, - pub out: PathBuf, -} - -#[derive(Debug, Clone)] -struct StaticCellOutput { - ok: bool, - text: String, -} - -fn source_hash(source: &str) -> String { - let mut h = Sha256::new(); - h.update(source.as_bytes()); - format!("{:x}", h.finalize()) -} - -fn value_text(v: &Value) -> Option { - match v { - Value::Text(s) => Some(s.clone()), - Value::None => None, - _ => v.reveal_text().map(|s| s.to_string()), - } -} - -fn value_bool(v: &Value) -> Option { - match v { - Value::Bool(b) => Some(*b), - _ => None, - } -} - -fn record_field(record: &Value, key: &str) -> Option { - match record { - Value::Map(entries) => entries - .iter() - .find(|(k, _)| k == key) - .map(|(_, v)| v.clone()), - _ => None, - } -} - -/// Run the document's cells at export time and keep their real outputs. This -/// is what makes a static page show foreign results instead of just source. -fn static_page_data( - root: &ViewRoot, - abs: &std::path::Path, - stdin: &str, -) -> (HashMap, Option) { - let mut out = HashMap::new(); - let Ok(mut session) = DocumentSession::open(abs, &root.root) else { - return (out, None); - }; - let page_stdin = if stdin.trim().is_empty() { None } else { Some(stdin) }; - let Ok(summary) = session.run_all_with_stdin(false, page_stdin) else { - session.close(); - return (out, None); - }; - let records = match &summary { - Value::Map(entries) => entries - .iter() - .find(|(k, _)| k == "records") - .map(|(_, v)| v.clone()), - _ => None, - }; - if let Some(Value::List(records)) = records { - for rec in records { - let Some(cell) = record_field(&rec, "cell").and_then(|v| value_text(&v)) else { - continue; - }; - let ok = record_field(&rec, "ok") - .and_then(|v| value_bool(&v)) - .unwrap_or(false); - let mut parts = Vec::new(); - if let Some(stdout) = record_field(&rec, "stdout").and_then(|v| value_text(&v)) { - if !stdout.is_empty() { - parts.push(stdout); - } - } - if let Some(stderr) = record_field(&rec, "stderr").and_then(|v| value_text(&v)) { - if !stderr.is_empty() { - parts.push(format!("[stderr]\n{stderr}")); - } - } - if let Some(error) = record_field(&rec, "error").and_then(|v| value_text(&v)) { - if !error.is_empty() { - parts.push(error); - } - } - let has_body = !parts.is_empty(); - let mut meta = Vec::new(); - if let Some(code) = record_field(&rec, "code").and_then(|v| match v { - Value::Int(n) => Some(n), - _ => None, - }) { - if code != 0 { - meta.push(format!("exit {code}")); - } - } - if let Some(ms) = record_field(&rec, "ms").and_then(|v| match v { - Value::Int(n) => Some(n), - _ => None, - }) { - if ms > 0 { - meta.push(format!("{ms}ms")); - } - } - if !meta.is_empty() { - parts.push(format!("— {}", meta.join(" · "))); - } - let text = if !has_body { - "(no output)".to_string() - } else { - parts.join("\n\n") - }; - out.insert(cell, StaticCellOutput { ok, text }); - } - } - let view_summary = session.summary(); - session.close(); - (out, Some(view_summary)) -} - -/// Inject static cell outputs into code cards without running client JS. -fn inject_cell_outputs(html: &str, outputs: &HashMap) -> String { - let mut html = html.to_string(); - for (name, out) in outputs { - let marker = format!(r#"data-code-name="{name}""#); - let Some(pos) = html.find(&marker) else { - continue; - }; - let tail = &html[pos..]; - let Some(out_pos) = tail.find(r#""#) else { - continue; - }; - let abs_pos = pos + out_pos; - let replacement = if out.ok { - format!(r#"
          {}
          "#, escape(&out.text)) - } else { - format!(r#"
          {}
          "#, escape(&out.text)) - }; - html.replace_range( - abs_pos..abs_pos + r#""#.len(), - &replacement, - ); - } - html -} - -fn inject_static_session(html: &str, summary: Option<&Value>) -> String { - let Some(summary) = summary else { - return html.to_string(); - }; - let Ok(json) = crate::host::json::value_to_json(summary) else { - return html.to_string(); - }; - let Ok(json) = serde_json::to_string(&json) else { - return html.to_string(); - }; - let line = format!( - "window.MARQDO_VIEW_LIVE = false;\nwindow.MARQDO_STATIC_SESSION = {json};" - ); - html.replace("window.MARQDO_VIEW_LIVE = false;", &line) -} - -/// Capture live-cell results into a snapshot consumed by `view output --snapshot`. -pub fn write_capture(opts: CaptureOptions) -> Result<()> { - let root = build_root(&opts.path)?; - let mut pages = serde_json::Map::new(); - for rel_pb in &root.files { - let rel = rel_pb.to_string_lossy().replace('\\', "/"); - let abs = resolve_abs(&root, &rel)?; - let vm = build_file_view(&root, &abs, &rel, &[], false)?; - let (outputs, summary) = static_page_data(&root, &abs, &vm.preset_stdin); - let mut out_map = serde_json::Map::new(); - for (name, output) in outputs { - out_map.insert( - name, - serde_json::json!({ "ok": output.ok, "text": output.text }), - ); - } - let summary_json = summary - .as_ref() - .and_then(|v| crate::host::json::value_to_json(v).ok()) - .unwrap_or(serde_json::Value::Null); - pages.insert( - rel.clone(), - serde_json::json!({ - "source_hash": source_hash(&vm.source), - "summary": summary_json, - "outputs": out_map, - }), - ); - } - let doc = serde_json::json!({ "version": 1, "pages": pages }); - if let Some(parent) = opts.out.parent() { - fs::create_dir_all(parent)?; - } - fs::write(&opts.out, serde_json::to_string_pretty(&doc)?) - .with_context(|| format!("write {}", opts.out.display()))?; - eprintln!("marqdo view capture: {} page(s) → {}", root.files.len(), opts.out.display()); - Ok(()) -} - -fn snapshot_page( - snapshot: &serde_json::Value, - rel: &str, - source: &str, -) -> Result<(HashMap, Option)> { - let page = snapshot - .get("pages") - .and_then(|p| p.get(rel)) - .ok_or_else(|| anyhow::anyhow!("snapshot has no page `{rel}`"))?; - let expected = page - .get("source_hash") - .and_then(|v| v.as_str()) - .unwrap_or(""); - if expected != source_hash(source) { - anyhow::bail!("snapshot source hash mismatch for `{rel}`"); - } - let mut outputs = HashMap::new(); - if let Some(map) = page.get("outputs").and_then(|v| v.as_object()) { - for (name, value) in map { - outputs.insert( - name.clone(), - StaticCellOutput { - ok: value.get("ok").and_then(|v| v.as_bool()).unwrap_or(false), - text: value - .get("text") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(), - }, - ); - } - } - let summary = page - .get("summary") - .filter(|v| !v.is_null()) - .and_then(|v| json_to_value(v).ok()); - Ok((outputs, summary)) -} - -pub fn write_static(opts: OutputOptions) -> Result<()> { - let snapshot = match &opts.snapshot { - Some(path) => Some(serde_json::from_str::( - &fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?, - )?), - None => None, - }; - let root = build_root(&opts.path)?; - fs::create_dir_all(&opts.out_dir) - .with_context(|| format!("create {}", opts.out_dir.display()))?; - - let pages_root = opts.out_dir.join("pages"); - let mut first_page_html: Option = None; - - for rel_pb in &root.files { - let rel = rel_pb.to_string_lossy().replace('\\', "/"); - let abs = resolve_abs(&root, &rel)?; - // V0: apply --no-exec before any capture run (do not execute then clear). - let vm = build_file_view_with_exec(&root, &abs, &rel, &[], false, !opts.no_exec)?; - let links = LinkMode::Static { - from: Some(rel.clone()), - }; - let (cell_outputs, static_summary) = if let Some(snapshot) = &snapshot { - snapshot_page(snapshot, &rel, &vm.source)? - } else if opts.no_exec { - (HashMap::new(), None) - } else { - static_page_data(&root, &abs, &vm.preset_stdin) - }; - let html = inject_static_session( - &inject_cell_outputs( - &page_file(&root.files, &rel, &vm, &links), - &cell_outputs, - ), - static_summary.as_ref(), - ); - let out_file = pages_root.join(format!("{rel}.html")); - if let Some(parent) = out_file.parent() { - fs::create_dir_all(parent)?; - } - fs::write(&out_file, html).with_context(|| format!("write {}", out_file.display()))?; - - if first_page_html.is_none() { - // index.html = first file (same content, links rooted at OUT_DIR) - first_page_html = Some(inject_static_session( - &inject_cell_outputs( - &page_file( - &root.files, - &rel, - &vm, - &LinkMode::Static { from: None }, - ), - &cell_outputs, - ), - static_summary.as_ref(), - )); - } - } - - let index_html = first_page_html.unwrap_or_else(|| { - page_index(&root.files, root.only_file.as_deref(), &LinkMode::Static { from: None }) - }); - let index_path = opts.out_dir.join("index.html"); - fs::write(&index_path, index_html) - .with_context(|| format!("write {}", index_path.display()))?; - - eprintln!( - "marqdo view output: {} page(s) → {}", - root.files.len(), - opts.out_dir.display() - ); - Ok(()) -} - -fn resolve_abs(root: &ViewRoot, rel: &str) -> Result { - let abs = root.root.join(rel); - Ok(abs.canonicalize().unwrap_or(abs)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn snapshot_page_rejects_source_hash_mismatch() { - let snap = serde_json::json!({ - "pages": { - "a.mq.md": { - "source_hash": "bad", - "summary": null, - "outputs": {} - } - } - }); - assert!(snapshot_page(&snap, "a.mq.md", "# main\n").is_err()); - } - - #[test] - fn snapshot_page_reads_outputs_and_summary() { - let source = "# main\n"; - let hash = source_hash(source); - let snap = serde_json::json!({ - "pages": { - "a.mq.md": { - "source_hash": hash, - "summary": {"persistent": false, "cells": [], "kernels": []}, - "outputs": {"a": {"ok": true, "text": "42"}} - } - } - }); - let (outputs, summary) = snapshot_page(&snap, "a.mq.md", source).unwrap(); - assert_eq!(outputs["a"].text, "42"); - assert!(summary.is_some()); - } - - #[test] - fn injects_visible_static_cell_outputs() { - let html = r#"
          "#; - let mut outputs = HashMap::new(); - outputs.insert("a".to_string(), StaticCellOutput { ok: true, text: "42".into() }); - let html = inject_cell_outputs(html, &outputs); - assert!(html.contains(r#"
          42
          "#), "{html}"); - assert!(!html.contains("hidden"), "{html}"); - } -} diff --git a/src/view/reader.css b/src/view/reader.css deleted file mode 100755 index d61386d..0000000 --- a/src/view/reader.css +++ /dev/null @@ -1,268 +0,0 @@ -/* The shared live/export reading theme. All assets are embedded by html::layout. */ -body.reader-page, body.reader-page.notebook-page, body.reader-page.notebook-page[data-theme="light"] { - color-scheme: light; - --bg:#fcf9f5; --surface:#fffcf8; --ink:#29251f; --muted:#847565; - --line:#e7ddce; --line-strong:#a98243; --fill:#f7f0e5; --hover:#f1e6d5; --focus:#8a622e; - --gold:#b88a45; --olive:#52603a; --radius:12px; - --serif:"Iowan Old Style","Palatino Linotype","Noto Serif CJK SC","Source Han Serif SC","Songti SC",SimSun,Georgia,serif; - --nb-bg:var(--bg); --nb-surface:var(--surface); --nb-surface-2:var(--fill); --nb-surface-3:var(--hover); - --nb-border:var(--line); --nb-border-soft:var(--line); --nb-text:var(--ink); --nb-strong:#252019; - --nb-muted:var(--muted); --nb-accent:#91692f; --nb-accent-hover:#795623; --nb-success:#52603a; - --nb-error:#a63e30; --nb-warning:#996b28; --nb-selection:#efe3ce; --nb-on-accent:#33291b; - --nb-topbar:#fcf9f5ee; --nb-code-bg:#f7f2e9; --nb-code-text:var(--ink); --nb-error-bg:#faede7; - --nb-error-border:#dba494; --syn-fg:#332c22; --syn-comment:#7d8067; --syn-keyword:#896132; - --syn-string:#536741; --syn-number:#a05b36; --syn-variable:#775341; --syn-function:#78622c; - --syn-type:#42645b; --syn-meta:#8e677c; - background:var(--bg); color:var(--ink); font-size:16px; line-height:1.65; -} -body.reader-page.notebook-page[data-theme="dark"] { - color-scheme:dark; --bg:#24261f; --surface:#2d3027; --ink:#e7e0d2; --muted:#b2a58f; - --line:#46483a; --fill:#34372c; --hover:#414333; --focus:#e0bb79; --gold:#d2ac6e; --olive:#beca98; - --nb-strong:#f0e8d8; --nb-accent:#b58c4f; --nb-accent-hover:#caa468; --nb-success:#bccb98; - --nb-code-bg:#282b23; --nb-selection:#4b4a33; --nb-on-accent:#f5eddc; --nb-code-text:var(--ink); - --syn-fg:#e0dbc9; --syn-comment:#a6ab90; --syn-keyword:#dbbb83; --syn-string:#b7ca9b; - --syn-number:#d3ae8e; --syn-variable:#e0ba9f; --syn-function:#d3c589; --syn-type:#9fc2b2; -} -.reader-page *:focus-visible { outline:2px solid var(--gold); outline-offset:4px; } -.reader-page button { font-family:var(--sans); } -.reader-header { position:relative; z-index:5; max-width:1080px; margin:0 auto; padding:22px 70px 0; text-align:center; } -.reader-brand { display:inline-flex; align-items:center; gap:10px; text-align:left; } -.reader-brand span { font:32px/1.1 var(--serif); letter-spacing:-1px; } -.reader-brand small { display:block; font:9px/2.6 var(--sans); letter-spacing:3px; padding-left:2px; } -.reader-tabs { display:flex; justify-content:center; gap:clamp(20px,5vw,70px); border-bottom:1px solid var(--line); margin-top:20px; } -.reader-tabs button { position:relative; background:none; border:0; padding:12px 16px; font:20px/1.5 var(--serif); color:var(--ink); cursor:pointer; } -.reader-tabs button.is-active { color:var(--focus); } -.reader-tabs button.is-active::after { content:""; height:2px; background:var(--gold); position:absolute; bottom:-1px; left:0; right:0; } -.icon-button { display:inline-flex; justify-content:center; align-items:center; padding:10px; border:0; background:transparent; color:var(--ink); cursor:pointer; border-radius:50%; } -.icon-button:hover { background:var(--hover); } -.reader-menu,.reader-search { position:absolute; top:36px; } -.reader-menu { left:22px; }.reader-search { right:22px; } -body.reader-page .shell { display:block; min-height:65vh; max-width:none; } -body.reader-page .panel-wrap { overflow:visible; background:transparent; container-type:normal; } -body.reader-page main.panel { max-width:1180px; margin:auto; padding:48px 210px 60px; } -body.reader-page .nav { position:fixed; width:min(340px,88vw); top:0; left:0; bottom:0; height:100dvh; z-index:40; background:var(--bg); padding:30px 22px; transform:translateX(-105%); transition:transform .2s ease; box-shadow:10px 0 50px #33241312; } -body.reader-page #nav-toggle:checked ~ .shell .nav { transform:translateX(0); } -body.reader-page #nav-toggle:checked ~ .backdrop { display:block; z-index:35; } -body.reader-page .nav-brand { display:block; margin-bottom:30px; }.reader-page .nav a.file.active { background:var(--fill); color:var(--focus); box-shadow:inset 2px 0 var(--gold); } -.reader-ornament { position:absolute; pointer-events:none; background-repeat:no-repeat; background-size:contain; z-index:0; } -.reader-blossom-top { top:0; left:0; width:280px; height:330px; opacity:.64; } -.reader-blossom-bottom { right:0; bottom:20px; width:250px; height:270px; transform:rotate(180deg); opacity:.55; } -body.reader-page { position:relative; } -body.reader-page .reader-hero { text-align:center; margin:0 -60px 42px; } -.reader-hero .eyebrow { color:var(--focus); font:12px var(--serif); letter-spacing:7px; margin:0 0 8px; } -.reader-hero h1 { font:italic 88px/1.15 var(--serif); letter-spacing:-3px; margin:0; color:var(--gold); background:linear-gradient(120deg,#b98b46,#e8c78f 60%,#b98b46); background-clip:text; -webkit-background-clip:text; -webkit-text-fill-color:transparent; } -.reader-hero h1::after { content:"❧"; font-size:66px; display:inline-block; margin-left:10px; } -.reader-hero .reader-motto { font:15px/1.9 var(--serif); letter-spacing:3px; color:var(--muted); margin:14px 0 0; } -body.reader-page h1.page { font:600 30px/1.4 var(--serif); letter-spacing:0; margin:0 0 8px; } -body.reader-page .meta { font:12px/1.6 var(--sans); margin-bottom:30px; color:var(--muted); overflow-wrap:anywhere; } -body.reader-page .meta::before { content:"▱"; color:var(--gold); margin-right:8px; } -body.reader-page .structure-block > h2 { display:none; } -body.reader-page .struct-wrap { display:block; } -body.reader-page .outline-rail { display:none; } -body.reader-page .structure { display:block; border:0; border-radius:0; background:transparent; overflow:visible; } -body.reader-page .document-surface { font-family:var(--serif); } -body.reader-page .structure .doc-block, body.reader-page .structure > .card { border:0; background:transparent; padding:0; margin:18px 0; border-radius:0; box-shadow:none; } -body.reader-page .structure .doc-prose { font:19px/1.72 var(--serif); color:var(--ink); overflow-wrap:anywhere; } -body.reader-page .doc-fun-title { font:600 34px/1.4 var(--serif); letter-spacing:0; margin:32px 0 18px; border:0; padding:0 0 0 22px; position:relative; } -body.reader-page .doc-fun-title::before { content:""; position:absolute; left:0; top:.2em; bottom:.15em; width:5px; transform:skew(-10deg); background:linear-gradient(#b98b46,#efd3a0,#b98b46); } -body.reader-page .doc-imports { display:flex; gap:10px; flex-wrap:wrap; margin:10px 0 26px; } -body.reader-page .chip { border:1px solid var(--line); background:var(--fill); border-radius:22px; padding:4px 12px; font:12px/1.5 var(--mono); } -body.reader-page .doc-imports .chip::before { content:"◇"; color:var(--gold); margin-right:8px; } -body.reader-page .doc-prose code,body.reader-page .mq-anchor { border-radius:6px; padding:2px 5px; background:var(--fill); color:var(--ink); } -body.reader-page .mq-anchor { border-bottom:1px solid var(--gold); } -body.reader-page .mq-anchor.is-focus { background:var(--hover); outline:1px solid var(--gold); } -body.reader-page blockquote { margin:24px 0; padding:18px 22px; background:var(--fill); border:1px solid var(--line); border-radius:9px; color:var(--muted); } -body.reader-page blockquote p { margin:0; } -body.reader-page .formula-card { background:var(--fill); border:1px solid var(--line); border-left:4px solid var(--gold); border-radius:10px; margin:24px 0; } -body.reader-page .code-card { border:1px solid var(--line); border-radius:10px; overflow:hidden; margin:22px 0; } -body.reader-page .doc-table { font:14px/1.7 var(--sans); } -body.reader-page .doc-table-wrap { margin:22px 0; } -body.reader-page .annot-band { padding-top:5px; margin:10px 0; min-height:0; } -body.reader-page .annot-chip { font:12px/1.5 var(--sans); padding:5px 10px; background:var(--fill); border-color:var(--line); border-left-color:var(--gold); border-radius:18px; } -body.reader-page .annot-chip.annot-return { border-left-color:var(--olive); } -body.reader-page .annot-chip:hover,body.reader-page .annot-chip.is-focus { background:var(--hover); } -body.reader-page .annot-label { color:var(--olive); }.reader-page .annot-value { color:var(--ink); } -/* Side notes retain their owning band and frame attributes. JS only positions them. */ -body.reader-page .document-surface { position:relative; padding-bottom:var(--reader-note-tail, 0px); } -body.reader-page .doc-list-item { position:relative; } -body.reader-page .has-margin-notes > .annot-band { height:0; margin:0; padding:0; position:static; } -body.reader-page .has-margin-notes > .annot-band > .annot-chips { position:static; display:block; } -body.reader-page .annot-chip.is-margin-note { position:absolute; width:170px; max-width:none; display:flex; flex-direction:column; align-items:flex-start; gap:6px; padding:5px 0; border:0; border-radius:0; background:var(--bg); font:13px/1.65 var(--sans); overflow-wrap:anywhere; z-index:3; } -body.reader-page .is-margin-note .annot-label { font:600 18px/1.4 var(--serif); } -body.reader-page .is-margin-note .annot-value { max-height:100px; overflow:auto; max-width:100%; } -body.reader-page .is-margin-note:hover { background:var(--fill); } -.reader-connectors { position:absolute; top:0; overflow:visible; pointer-events:none; z-index:4; } -.reader-connectors path { fill:none; stroke-linecap:round; stroke-linejoin:round; } -.reader-connectors .reader-leader-halo { stroke:var(--bg); stroke-width:4; } -.reader-connectors .reader-leader { stroke:var(--olive); stroke-width:1.05; opacity:.78; } -.reader-connectors circle { fill:var(--gold); } -.reader-curve-gold { stop-color:var(--gold); } -.reader-curve-olive { stop-color:var(--olive); } -.reader-connectors .is-focus .reader-leader { opacity:1; stroke-width:1.5; } -body.reader-page #notebook-bar,body.reader-page #nb-stdin-bar,body.reader-page #nb-state-actions { display:none; } -body.reader-page.reader-tools #notebook-bar,body.reader-page.reader-tools #nb-stdin-bar,body.reader-page.reader-tools #nb-state-actions:not([hidden]) { display:flex; position:static; flex-wrap:wrap; border-radius:10px; margin-bottom:14px; } -body.reader-page #nb-status { white-space:normal; } -body.reader-page .exec-block { border-top:1px solid var(--line); padding-top:24px; margin-top:46px; } -body.reader-page .out,body.reader-page .source { background:var(--fill); border:1px solid var(--line); border-radius:10px; } -body.reader-page .source-block { color:var(--muted); font-size:13px; } -.reader-dock { position:fixed; z-index:20; bottom:24px; left:50%; transform:translateX(-50%); display:flex; align-items:flex-end; gap:17px; padding:10px 18px 8px; max-width:calc(100vw - 24px); border:1px solid var(--line); border-radius:44px; background:color-mix(in srgb,var(--bg) 90%,transparent); backdrop-filter:blur(18px); box-shadow:0 8px 28px #78562614,inset 0 1px #ffffff55; } -.reader-dock > .icon-button { display:flex; flex-direction:column; gap:5px; padding:0 3px; min-width:44px; border-radius:20px; } -.reader-dock-icon { display:flex; align-items:center; justify-content:center; width:34px; height:34px; } -.reader-dock-label { font:11px/1.6 var(--sans); letter-spacing:.08em; color:var(--muted); white-space:nowrap; } -.reader-dock .reader-play .reader-dock-icon { width:54px; height:54px; margin-top:-13px; color:white; border-radius:50%; background:linear-gradient(125deg,#a97632,#edc57e 55%,#c5964e); border:1px solid #f9e3bb; box-shadow:0 3px 12px #b18c4530; } -.reader-dock .reader-play .reader-dock-label { color:var(--focus); } -.reader-play svg { fill:currentColor; width:22px; } -.reader-footer { position:relative; padding:32px 20px 125px; display:flex; flex-direction:column; gap:10px; align-items:center; color:var(--muted); font:11px/1.8 var(--sans); letter-spacing:2px; border-top:1px solid var(--line); background:linear-gradient(170deg,transparent,var(--fill)); } -.reader-footer > :first-child { letter-spacing:5px; color:var(--gold); } -.reader-dialog,.reader-page .var-dialog { color:var(--ink); background:var(--bg); border:1px solid var(--line); border-radius:16px; width:min(620px,calc(100vw - 32px)); max-height:80dvh; padding:24px; box-shadow:0 20px 90px #33241325; } -.reader-dialog::backdrop,.reader-page .var-dialog::backdrop { background:#29251f50; backdrop-filter:blur(5px); } -.reader-dialog-head { display:flex; align-items:center; justify-content:space-between; gap:15px; margin-bottom:16px; } -.reader-dialog-head h2 { font:24px var(--serif); margin:0; } -.reader-dialog pre { white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.6 var(--mono); } -.reader-dialog input[type="search"] { width:100%; background:var(--surface); color:var(--ink); border:1px solid var(--line); border-radius:8px; padding:12px; font:15px var(--sans); } -.reader-dialog button.reader-option { display:block; width:100%; padding:12px; margin:8px 0; text-align:left; background:var(--fill); color:var(--ink); border:1px solid var(--line); border-radius:8px; cursor:pointer; } -.reader-dialog .vars-panel { max-height:none; }.reader-dialog .outline-section { border:0; background:transparent; } -.reader-toast { position:fixed; z-index:60; bottom:130px; left:50%; transform:translateX(-50%); max-width:calc(100vw - 32px); padding:10px 18px; border:1px solid var(--line); border-radius:12px; background:var(--surface); color:var(--ink); box-shadow:0 4px 25px #33241318; font:13px/1.5 var(--sans); } -body.reader-page.reader-large .doc-prose { font-size:22px; } -body.reader-page.reader-hide-notes .annot-band,body.reader-page.reader-hide-notes .annot-leaders { display:none; } -.reader-search-result { display:block; padding:12px 0; border-bottom:1px solid var(--line); font:14px/1.6 var(--sans); } -@media(min-width:1500px) { .reader-blossom-top { width:340px; height:390px; } } -@media(max-width:1000px) { - body.reader-page main.panel { max-width:800px; padding:35px 42px 50px; } - .reader-blossom-top { width:175px; opacity:.4; } - body.reader-page .reader-hero { margin:0 0 35px; } -} -@media(max-width:600px) { - .reader-header { padding:20px 18px 0; }.reader-brand span { font-size:26px; }.reader-brand img { width:36px; height:36px; }.reader-brand small { font-size:7px; letter-spacing:2px; } - .reader-menu { left:8px; top:24px; }.reader-search { right:8px; top:24px; } - .reader-tabs { gap:0; justify-content:space-between; margin-top:16px; }.reader-tabs button { font-size:17px; padding:10px 13px; } - body.reader-page main.panel { padding:30px 22px 40px; }.reader-hero h1 { font-size:62px; }.reader-hero h1::after { font-size:40px; margin-left:3px; } - .reader-hero .eyebrow { font-size:10px; letter-spacing:5px; }.reader-hero .reader-motto { font-size:11px; letter-spacing:1px; } - body.reader-page .structure .doc-prose { font-size:17px; line-height:1.8; }body.reader-page .doc-fun-title { font-size:28px; } - .reader-blossom-top { width:115px; opacity:.28; }.reader-blossom-bottom { width:120px; height:150px; opacity:.3; } - .reader-dock { gap:10px; bottom:16px; padding:10px 12px 7px; }.reader-dock .reader-play .reader-dock-icon { width:50px; height:50px; }.reader-dock-label { font-size:10px; } -} -@media(prefers-reduced-motion:reduce) { .reader-page *, .reader-page *::before { scroll-behavior:auto!important; transition:none!important; } } -@media print { - .reader-header,.reader-dock,.reader-ornament,.reader-footer,.reader-toast,.reader-connectors { display:none!important; } - body.reader-page main.panel { max-width:none; padding:0; }.reader-page .annot-chip.is-margin-note { position:static; width:auto; } - body.reader-page .has-margin-notes > .annot-band { height:auto; } -} -/* Refine document rhythm without the old notebook cell dividers. */ -body.reader-page #document-section > h2 { display:none; } -body.reader-page .doc-fun { border:0; margin:24px 0 12px; padding:0; } -body.reader-page .document-surface { padding:0 0 var(--reader-note-tail, 0px); } -body.reader-page .reader-hero h1::after { content:""; width:85px; height:90px; vertical-align:middle; margin-left:12px; background-size:contain; background-position:center; background-repeat:no-repeat; } -body.reader-page .mq-anchor.mq-decl,body.reader-page .mq-anchor.mq-code { border-bottom-color:var(--gold); } -body.reader-page .mq-anchor.mq-return { border-bottom-color:var(--olive); } -body.reader-page .doc-list-item.arm-taken { border-left-color:var(--olive); } -body.reader-page .formula-head { color:var(--muted); } -body.reader-page .formula-head .badge { display:none; } -body.reader-page .formula-card .math-block { font-size:1.35rem; padding:8px 18px; } -body.reader-page .reader-hero + h1.page { font-size:0; height:0; overflow:hidden; margin:0; } -body.reader-page .reader-hero + h1.page .status-pill { display:none; } -@media(max-width:600px) { body.reader-page .reader-hero h1::after { width:48px; height:60px; margin-left:4px; } } - -body.reader-page.reader-welcome h1.page { display:none; } - -body.reader-page .nav { visibility:hidden; } -body.reader-page #nav-toggle:checked ~ .shell .nav { visibility:visible; } - -@media print { body.reader-page .document-surface { padding-bottom:0; } } - -/* Action text belongs to the sentence; its implementation belongs to a note. */ -body.reader-page .doc-line { font:19px/1.8 var(--serif); overflow-wrap:anywhere; } -body.reader-page .mq-anchor:has(.occl-label) { background:transparent; border:0; padding:0; } -body.reader-page button.occl-label { display:inline; appearance:none; font:inherit; color:var(--olive); background:transparent; border:0; border-bottom:1px dotted var(--gold); border-radius:0; padding:0 1px; cursor:pointer; text-align:inherit; } -body.reader-page button.occl-label:hover { background:var(--fill); } -body.reader-page .occl-stub { display:inline; font:11px/1.5 var(--sans); border:1px solid var(--gold); border-radius:5px; padding:2px 5px; margin-left:6px; color:var(--focus); white-space:normal; } -body.reader-page details.annot-implementation { display:block; padding:8px 12px; border-radius:7px; border:1px solid var(--line); margin:5px 0; } -body.reader-page .annot-implementation > summary { cursor:pointer; font:12px/1.6 var(--sans); color:var(--olive); } -body.reader-page .annot-implementation .occl-code { display:block; text-align:left; white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); padding:6px 0; border:0; border-radius:0; background:transparent; } -body.reader-page details.annot-implementation.is-margin-note { padding:5px 0; border:0; margin:0; } -body.reader-page .is-margin-note.annot-implementation > summary { font:15px/1.5 var(--serif); } -.logic-hint { display:block; color:var(--muted); font:10px/1.6 var(--sans); margin-top:5px; } -.reader-syntax-guide { font:13px/1.7 var(--sans); border:1px solid var(--line); padding:12px 16px; border-radius:9px; margin:0 0 28px; color:var(--muted); } -.reader-syntax-guide > summary { cursor:pointer; color:var(--olive); } -.reader-syntax-guide p { margin:12px 0; } -.knowledge-table-wrap { max-width:100%; overflow-x:auto; } -.reader-syntax-guide table,.knowledge-panel table { width:100%; border-collapse:collapse; font:12px/1.65 var(--sans); } -.reader-syntax-guide th,.reader-syntax-guide td,.knowledge-panel th,.knowledge-panel td { padding:9px 10px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; } -.reader-syntax-guide td:first-child { min-width:115px; } -.reader-page .knowledge-block { border-top:1px solid var(--line); padding-top:22px; font:14px/1.7 var(--sans); } -.reader-page .knowledge-block > summary { color:var(--olive); font:18px/1.6 var(--serif); } -.knowledge-intro { margin:20px 0; }.knowledge-intro h3 { font:22px/1.5 var(--serif); margin:0 0 8px; } -.knowledge-intro p { margin:7px 0; } -.knowledge-card { margin:12px 0; border:1px solid var(--line); border-radius:10px; overflow:hidden; font:13px/1.75 var(--sans); } -.knowledge-card > summary { display:flex; align-items:baseline; flex-wrap:wrap; gap:10px; padding:14px 18px; cursor:pointer; background:var(--fill); } -.knowledge-card > summary::before { content:'›'; color:var(--gold); }.knowledge-card[open] > summary::before { content:'⌄'; } -.knowledge-unit-name { font:18px/1.6 var(--serif); overflow-wrap:anywhere; }.knowledge-unit-kind { font:11px/1.5 var(--sans); color:var(--muted); } -.knowledge-unit-body { padding:16px 18px; }.knowledge-unit-body h4 { margin:20px 0 8px; font:600 13px/1.6 var(--sans); color:var(--olive); } -.knowledge-unit-body p { margin:6px 0; }.knowledge-source-link { color:var(--olive); border-bottom:1px dotted var(--gold); font-size:12px; } -.knowledge-status { display:grid; grid-template-columns:100px minmax(0,1fr); gap:7px 12px; margin:8px 0; }.knowledge-status dt { color:var(--muted); }.knowledge-status dd { margin:0; } -.knowledge-panel code { white-space:pre-wrap; overflow-wrap:anywhere; font:11px/1.65 var(--mono); } -.knowledge-dependencies { padding-left:20px; }.knowledge-dependencies a { border-bottom:1px dotted var(--gold); } -.knowledge-steps,.knowledge-technical { border-top:1px solid var(--line); margin-top:18px; padding-top:12px; } -.knowledge-steps > summary,.knowledge-technical > summary { font:12px/1.7 var(--sans); cursor:pointer; color:var(--muted); } -.knowledge-step { padding:5px 0; overflow-wrap:anywhere; }.knowledge-step-kind { display:inline-block; color:var(--olive); min-width:4em; margin-right:8px; } -.knowledge-technical dl { font-size:11px; }.knowledge-technical dd { margin:4px 0 14px; overflow-wrap:anywhere; } -.reader-dialog:has(.knowledge-panel) { width:min(850px,calc(100vw - 32px)); } -@media(max-width:600px) { body.reader-page .doc-line { font-size:17px; }.knowledge-unit-body { padding:12px; }.knowledge-status { grid-template-columns:80px minmax(0,1fr); }.knowledge-card > summary { padding:12px; }.knowledge-table-wrap th,.knowledge-table-wrap td { min-width:65px; }.reader-syntax-guide { padding:10px; } } -@media print { .annot-implementation { break-inside:avoid; }.reader-syntax-guide { display:none; }.knowledge-technical { overflow-wrap:anywhere; } } -.reader-dialog .knowledge-table-wrap table { width:100%; border-collapse:collapse; font:12px/1.7 var(--sans); } -.reader-dialog .knowledge-table-wrap th,.reader-dialog .knowledge-table-wrap td { text-align:left; padding:8px 10px; border-bottom:1px solid var(--line); vertical-align:top; overflow-wrap:anywhere; } -.reader-run-summary { color:var(--olive); }.reader-dialog > details { margin:16px 0; } - - -/* Expanded details need reading room; collapsed neighbours keep their own height. */ -body.reader-page .annot-chips:has(> .annot-implementation) { align-items:flex-start; } -body.reader-page .annot-implementation[open]:not(.is-margin-note) { flex-basis:100%; width:100%; } -body.reader-page .annot-implementation > summary { list-style:none; } -body.reader-page .annot-implementation > summary::-webkit-details-marker { display:none; } -body.reader-page .annot-implementation > summary::before { content:'›'; float:right; margin-left:12px; color:var(--gold); } -body.reader-page .annot-implementation[open] > summary::before { content:'⌄'; } -.logic-body pre { white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); margin:8px 0; } -@media(max-width:600px) { - body.reader-page .annot-chips:has(> .annot-implementation) { flex-direction:column; align-items:stretch; } - body.reader-page .annot-chips > .annot-implementation { width:100%; max-width:none; flex:none; } -} - -/* Describe the intent in the sentence; read typed details beside it. */ -body.reader-page a.occl-label { color:var(--olive); border-bottom:1px dotted var(--gold); text-decoration:none; padding:0 1px; } -body.reader-page a.occl-label:hover { background:var(--fill); } -.occl-label:focus-visible,.logic-definition:focus-visible,.logic-link-target:focus-visible { outline:2px solid var(--gold); outline-offset:4px; } -.logic-kind { display:block; font:10px/1.5 var(--sans); letter-spacing:.06em; color:var(--muted); } -.logic-note-label { font:15px/1.6 var(--serif); } -.logic-body { min-width:0; text-align:left; font:12px/1.7 var(--sans); color:var(--ink); overflow-wrap:anywhere; } -body.reader-page .annot-implementation .logic-body { display:block; white-space:normal; padding:8px 0 0; max-height:none; } -body.reader-page .annot-implementation.is-margin-note .logic-body { max-height:320px; overflow:auto; scrollbar-width:thin; } -.logic-call { border-left:2px solid var(--gold); padding:2px 0 2px 10px; } -.logic-call-name { color:var(--olive); font:600 12px/1.6 var(--mono); white-space:normal; overflow-wrap:anywhere; } -.logic-definition { color:var(--olive); text-decoration:none; border-bottom:1px dotted var(--gold); } -.logic-arguments { margin:8px 0 0; padding:0; } -.logic-argument { display:grid; grid-template-columns:minmax(45px,.7fr) minmax(0,1.3fr); gap:4px 8px; padding:5px 0; border-top:1px solid var(--line); } -.logic-argument dt { color:var(--muted); overflow-wrap:anywhere; font:11px/1.65 var(--mono); } -.logic-argument dd { margin:0; min-width:0; } -.logic-argument .logic-argument { display:block; } -.logic-string { white-space:pre-wrap; } -.logic-expression { white-space:pre-wrap; font:12px/1.7 var(--mono); color:var(--ink); } -.logic-values { padding-left:19px; margin:4px 0; } -.logic-values > li { margin:3px 0; padding-left:2px; } -.logic-no-args,.logic-empty-value { font-size:11px; color:var(--muted); } -.logic-body p { margin:5px 0; } -.logic-body .logic-link-target { display:block; border:1px solid var(--line); border-radius:7px; padding:9px 10px; color:var(--olive); text-decoration:none; background:var(--fill); } -.logic-link-address { display:block; font:11px/1.7 var(--mono); overflow-wrap:anywhere; } -.logic-link-open { display:block; margin-top:5px; font:11px/1.6 var(--sans); } -.logic-body .logic-source { margin-top:10px; border-top:1px solid var(--line); padding-top:6px; color:var(--muted); } -.logic-source > summary { cursor:pointer; font:10px/1.7 var(--sans); } -.logic-source pre { margin:5px 0 0; white-space:pre-wrap; overflow-wrap:anywhere; } -.logic-nested-label { color:var(--olive); } -.logic-content > :first-child { margin-top:0; } -.reader-dialog .logic-body { font-size:14px; } -.reader-dialog .logic-call-name { font-size:15px; } -.reader-dialog .logic-argument { grid-template-columns:minmax(70px,.6fr) minmax(0,1.4fr); padding:9px 0; } -.reader-dialog .logic-body .occl-code { white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); } -@media(max-width:600px) { - .logic-note-label { font-size:14px; } - .reader-dialog .logic-argument { grid-template-columns:minmax(55px,.6fr) minmax(0,1.4fr); } -} diff --git a/src/view/reader.js b/src/view/reader.js deleted file mode 100755 index bc63c8d..0000000 --- a/src/view/reader.js +++ /dev/null @@ -1,594 +0,0 @@ -/* No network dependencies: this module also runs from a file:// static export. */ -(function () { - 'use strict'; - var dialog, content, returnNodes = [], pending = false, toastTimer; - // User choices belong to the document, not to one temporary layout or DOM. - var disclosureChoices = new Map(), layoutToggles = new WeakMap(); - function disclosureKey(node) { - var note=node.closest('.annot-implementation'); - if(!note || !note.dataset.annotId) return null; - return note.dataset.annotId+(node===note ? '' : ':source'); - } - function setDisclosure(node, open) { - if(node.open===open) return; - layoutToggles.set(node,open); - node.open=open; - } - function implementationOpen(note, margin) { - var key=disclosureKey(note); - return disclosureChoices.has(key) ? disclosureChoices.get(key) : margin; - } - function restoreDisclosures(root) { - root.querySelectorAll('.annot-implementation, .annot-implementation .logic-source').forEach(function(node){ - var key=disclosureKey(node); - if(disclosureChoices.has(key)) setDisclosure(node,disclosureChoices.get(key)); - }); - } - function toast(message) { - var el = document.querySelector('.reader-toast'); - el.textContent = message; el.hidden = false; - clearTimeout(toastTimer); toastTimer = setTimeout(function () { el.hidden = true; }, 4200); - } - function restorePanels() { - returnNodes.forEach(function (item) { if (item.marker.parentNode) item.marker.replaceWith(item.node); }); - returnNodes = []; - document.querySelectorAll('.reader-tabs button').forEach(function (b) { - var active = b.dataset.readerAction === 'document'; - b.classList.toggle('is-active', active); - if (active) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); - }); - } - function openDialog(title, action) { - restorePanels(); content.replaceChildren(); - document.getElementById('reader-dialog-title').textContent = title; - if (!dialog.open) dialog.showModal(); - document.querySelectorAll('.reader-tabs button').forEach(function (b) { - var active = b.dataset.readerAction === action; - b.classList.toggle('is-active', active); - if (active) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); - }); - } - function movePanel(node) { - if (!node) { content.textContent = '当前文档暂无此类信息。'; return; } - var marker = document.createComment('reader-panel'); node.before(marker); - returnNodes.push({ node: node, marker: marker }); content.appendChild(node); - } - function option(label, callback) { - var b = document.createElement('button'); b.type = 'button'; b.className = 'reader-option'; - b.textContent = label; b.addEventListener('click', callback); content.appendChild(b); return b; - } - function clickExisting(id) { - var el = document.getElementById(id); - if (el && !el.disabled) el.click(); else toast('当前文档没有可用的此项操作。'); - } - function scrollTo(el) { - if (!el) { toast('当前文档暂无此类信息。'); return; } - if (dialog.open) dialog.close(); - el.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'center' }); - } - function showSearch() { - openDialog('搜索文档', 'search'); - var input = document.createElement('input'); input.type = 'search'; input.placeholder = '搜索正文、函数或文件…'; input.setAttribute('aria-label', '搜索内容'); - var results = document.createElement('div'); results.setAttribute('aria-live', 'polite'); content.append(input, results); - input.addEventListener('input', function () { - results.replaceChildren(); var q = input.value.trim().toLocaleLowerCase(); if (!q) return; - var nodes = Array.from(document.querySelectorAll('.document-surface .doc-prose, .doc-fun-title, .nav a.file')); - var count = 0; - nodes.forEach(function (node) { - if (count >= 40 || node.textContent.toLocaleLowerCase().indexOf(q) < 0) return; - count++; - var b = document.createElement('button'); b.type = 'button'; b.className = 'reader-option'; - b.textContent = node.textContent.trim().slice(0, 150); - b.addEventListener('click', function () { if (node.matches('a')) location.href = node.href; else scrollTo(node); }); results.appendChild(b); - }); - if (!count) results.textContent = '没有找到匹配内容。'; - }); - input.focus(); - } - function action(name) { - if (name === 'files') { - var toggle = document.getElementById('nav-toggle'); toggle.checked = !toggle.checked; - document.querySelector('.reader-menu').setAttribute('aria-expanded', String(toggle.checked)); - if (toggle.checked) { var first = document.querySelector('.nav a'); if (first) first.focus(); } return; - } - if (name === 'close-dialog') { dialog.close(); return; } - if (name === 'document') { if (dialog.open) dialog.close(); scrollTo(document.getElementById('document-section') || document.querySelector('main')); return; } - if (name === 'search') { showSearch(); return; } - if (name === 'knowledge') { openDialog('可执行知识', name); movePanel(document.querySelector('.knowledge-panel')); return; } - if (name === 'syntax') { var guide=document.getElementById('reader-syntax-guide'); if(guide) {guide.open=true;scrollTo(guide);} return; } - if (name === 'functions' || name === 'variables') { - var panel = document.getElementById(name === 'functions' ? 'fn-outline' : 'vars-panel'); - openDialog(name === 'functions' ? '函数目录' : '文档变量', name); movePanel(panel); return; - } - if (name === 'memory') { - openDialog('执行内存与调用轨迹', name); - var hint = document.createElement('p'); hint.textContent = window.MARQDO_VIEW_LIVE ? '当前文档已捕获的绑定与调用轨迹;会话状态可在高级工具中查看。' : '以下为导出时保存的执行快照。'; content.appendChild(hint); - var report; - try { report=JSON.parse((document.getElementById('mq-view-trace') || {}).textContent || '{}'); } - catch (_) { report={}; } - if(typeof report.ok!=='boolean') { - var empty=document.createElement('p');empty.textContent='本页没有捕获执行记录;静态知识分析不会自动产生运行结果。';content.appendChild(empty);return; - } - var status=document.createElement('p');status.className='reader-run-summary'; - status.textContent=(report.ok?'这次运行成功':'这次运行失败')+' · '+(report.calls||[]).length+' 次调用 · '+(report.loops||[]).length+' 个循环记录';content.appendChild(status); - function reportTable(title,headers,rows) { - var heading=document.createElement('h3');heading.textContent=title;content.appendChild(heading); - var wrap=document.createElement('div');wrap.className='knowledge-table-wrap'; - var table=document.createElement('table'),head=document.createElement('tr'); - headers.forEach(function(text){var cell=document.createElement('th');cell.textContent=text;head.appendChild(cell);});table.appendChild(head); - rows.forEach(function(row){var tr=document.createElement('tr');row.forEach(function(text){var cell=document.createElement('td');cell.textContent=text;tr.appendChild(cell);});table.appendChild(tr);}); - wrap.appendChild(table);content.appendChild(wrap); - } - var bindings=report.bindings_final||{}; - reportTable('最终绑定',['名称','值'],Object.keys(bindings).map(function(key){return [key,String(bindings[key])];})); - reportTable('调用记录',['函数','源码位置','输入'],(report.calls||[]).map(function(call){return [call.fn,'第 '+call.fn_line+' 行',call.args_brief||'无实参'];})); - var details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='完整执行报告(技术详情)';details.appendChild(summary); - var pre=document.createElement('pre');pre.textContent=JSON.stringify(report,null,2);details.appendChild(pre);content.appendChild(details);return; - } - if (name === 'execution') { scrollTo(document.getElementById('exec-block')); return; } - if (name === 'run') { - if (!window.MARQDO_VIEW_LIVE) { toast('静态页面展示导出时的结果。请使用 marqdo view 启动实时运行。'); return; } - clickExisting(document.getElementById('stream-run') ? 'stream-run' : 'nb-run-all'); toast('已请求运行文档。'); return; - } - if (name === 'reload') { location.reload(); return; } - if (name === 'clear') { - if (window.MARQDO_VIEW_LIVE) clickExisting('nb-clear'); - else { document.querySelectorAll('.code-out, #exec-main').forEach(function (el) { el.hidden = true; }); toast('已隐藏输出,重新加载可恢复导出快照。'); } - return; - } - if (name === 'settings') { - openDialog('阅读设置', name); - option('切换浅色 / 深色', function () { clickExisting('nb-theme'); }); - option('切换标准 / 大号正文', function () { document.body.classList.toggle('reader-large'); refreshAnnotations(); }); - option('显示 / 隐藏执行标注', function () { document.body.classList.toggle('reader-hide-notes'); refreshAnnotations(); }); - return; - } - if (name === 'more') { - openDialog('文档工具', name); - option('可执行知识', function () { action('knowledge'); }); - option('语法与阅读说明', function () { dialog.close(); action('syntax'); }); - option('文件目录', function () { dialog.close(); action('files'); }); - option('查看完整源码', function () { var source = document.querySelector('.source-block'); if (source) { source.open = true; scrollTo(source); } }); - option('高级运行工具', function () { document.body.classList.toggle('reader-tools'); dialog.close(); scrollTo(document.getElementById('notebook-bar')); }); - option('打印 / 保存为 PDF', function () { dialog.close(); window.print(); }); - } - } - var anchorSequence = 0; - function noteOwner(band) { - return band ? band.closest('.doc-block, .doc-list-item') : null; - } - function findAnchor(owner, chip) { - if (!owner) return null; - var line = chip.dataset.anchorLine, start = Number(chip.dataset.anchorByteStart); - var end = Number(chip.dataset.anchorByteEnd), id = chip.dataset.annotId; - var anchors = Array.from(owner.querySelectorAll('.mq-anchor')).filter(function (el) { - return el.closest('.doc-block, .doc-list-item') === owner; - }); - var exact = anchors.find(function (el) { return id && (el.dataset.logicId === id || el.dataset.annotId === id); }); - if (exact) return exact; - var onLine = anchors.filter(function (el) { return line && el.dataset.line === line; }); - if (chip.hasAttribute('data-anchor-byte-start')) { - var span = onLine.filter(function (el) { - return el.hasAttribute('data-byte-start') && Number(el.dataset.byteStart) <= start - && Number(el.dataset.byteEnd) > start; - }).sort(function (x, y) { - return (Number(x.dataset.byteEnd) - Number(x.dataset.byteStart)) - - (Number(y.dataset.byteEnd) - Number(y.dataset.byteStart)); - }); - if (span.length) return span[0]; - if (chip.hasAttribute('data-anchor-byte-end')) { - var overlap = onLine.find(function (el) { - return Number(el.dataset.byteStart) < end && Number(el.dataset.byteEnd) > start; - }); - if (overlap) return overlap; - } - } - // A branch chip belongs to this arm, not to the first arm's source line. - if (owner.matches('.doc-list-item') && chip.dataset.annotKind === 'branch') { - return owner.querySelector(':scope > .doc-list-head'); - } - if (onLine.length === 1) return onLine[0]; - if (line && owner.dataset.line === line) { - return owner.querySelector(':scope > .doc-list-head, :scope > .doc-line.doc-stmt, :scope > .doc-line.doc-occl'); - } - // No guessed first declaration / whole paragraph: retain an inline result. - return null; - } - function anchorFragments(anchor) { - var rects; - if (anchor.matches('.mq-anchor')) rects = Array.from(anchor.getClientRects()); - else { - var range = document.createRange(); range.selectNodeContents(anchor); - rects = Array.from(range.getClientRects()); - } - return rects.filter(function (r) { return r.width > 1 && r.height > 1; }); - } - function resetNotes(bands, surface) { - bands.forEach(function (band) { - var owner = noteOwner(band); - if (owner) { - owner.classList.remove('has-margin-notes', 'is-keyed'); - owner.querySelectorAll(':scope > .annot-leaders').forEach(function (el) { el.replaceChildren(); }); - } - band.classList.remove('is-keyed'); - band.querySelectorAll('.annot-chip').forEach(function (chip) { - chip.classList.remove('is-margin-note'); - if(chip.classList.contains('annot-implementation')) setDisclosure(chip,implementationOpen(chip,false)); - ['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); }); - delete chip.dataset.readerAnchor; delete chip.dataset.readerSide; - }); - }); - if (surface) surface.querySelectorAll(':scope > .reader-connectors').forEach(function (el) { el.remove(); }); - } - function setNoteTail(surface, height) { - var value = Math.ceil(Math.max(0, height)) + 'px'; - if (surface.style.getPropertyValue('--reader-note-tail') !== value) surface.style.setProperty('--reader-note-tail', value); - } - function curvePoint(points, t) { - var u = 1 - t; - return {x:u*u*u*points[0].x + 3*u*u*t*points[1].x + 3*u*t*t*points[2].x + t*t*t*points[3].x, - y:u*u*u*points[0].y + 3*u*u*t*points[1].y + 3*u*t*t*points[2].y + t*t*t*points[3].y}; - } - function splitCurve(points) { - function mid(a,b) { return {x:(a.x+b.x)/2,y:(a.y+b.y)/2}; } - var a=mid(points[0],points[1]), b=mid(points[1],points[2]), c=mid(points[2],points[3]); - var d=mid(a,b), e=mid(b,c), center=mid(d,e); - return [[points[0],a,d,center],[center,e,c,points[3]]]; - } - function curveData(curves) { - var first=curves[0][0], path='M '+first.x+' '+first.y; - curves.forEach(function (curve) { - path+=' C '+curve[1].x+' '+curve[1].y+' '+curve[2].x+' '+curve[2].y+' '+curve[3].x+' '+curve[3].y; - }); - return path; - } - function sourceObstacles(surface, inset, top) { - var rects=[], walker=document.createTreeWalker(surface,NodeFilter.SHOW_TEXT); - while (walker.nextNode()) { - var text=walker.currentNode, parent=text.parentElement; - if (!text.textContent.trim() || !parent || parent.closest('.annot-band,.annot-leaders,.reader-connectors,script,style')) continue; - var range=document.createRange(); range.selectNodeContents(text); - Array.from(range.getClientRects()).forEach(function (r) { - if (r.width>1 && r.height>1) rects.push({left:r.left-inset-2,right:r.right-inset+2,top:r.top-top-1,bottom:r.bottom-top+1}); - }); - } - surface.querySelectorAll('.doc-table,.code-card,.formula-card').forEach(function (el) { - var r=el.getBoundingClientRect(); - rects.push({left:r.left-inset-3,right:r.right-inset+3,top:r.top-top-2,bottom:r.bottom-top+2}); - }); - return rects; - } - function clearCurve(points, obstacles) { - var left=Math.min.apply(Math,points.map(function(p){return p.x;})); - var right=Math.max.apply(Math,points.map(function(p){return p.x;})); - var top=Math.min.apply(Math,points.map(function(p){return p.y;})); - var bottom=Math.max.apply(Math,points.map(function(p){return p.y;})); - var nearby=obstacles.filter(function(r){return r.leftleft&&r.toptop;}); - for (var step=1;step<48;step++) { - var p=curvePoint(points,step/48); - if (nearby.some(function(r){return p.x>r.left&&p.xr.top&&p.yprior.right||box.bottom+8prior.bottom) return true; - for(var i=1;iMath.max(c.x,d.x) - ||Math.max(a.y,b.y)+8Math.max(c.y,d.y)) continue; - if(cross(a,b,c)*cross(a,b,d)<0 && cross(c,d,a)*cross(c,d,b)<0) return false; - var shared=Math.hypot(samples[0].x-other[0].x,samples[0].y-other[0].y)<3; - if(shared && Math.hypot(a.x-samples[0].x,a.y-samples[0].y)<16 - && Math.hypot(c.x-other[0].x,c.y-other[0].y)<16) continue; - if(Math.min(distance(a,c,d),distance(b,c,d),distance(c,a,b),distance(d,a,b))<64) return false; - } - return true; - }); - } - function flowingCurve(start, end, direction, bounds, inset, obstacles, routes) { - var distance=Math.abs(end.x-start.x); - var amplitude=Math.max(32,Math.min(128,distance*.24)); - var preferred=end.y>=start.y?-1:1; - // Prefer one continuous, visible S-curve. Try the opposite sweep when a - // paragraph occupies that space; never trade readable prose for ornament. - for (var scale=1;scale>=.3;scale-=.35) { - for (var signIndex=0;signIndex<2;signIndex++) { - var wave=preferred*(signIndex===0?1:-1)*amplitude*scale; - var points=[start,{x:start.x+direction*distance*.34,y:start.y+wave}, - {x:end.x-direction*distance*.34,y:end.y-wave},end]; - var curves=splitCurve(points); - if (clearCurve(points,obstacles) && clearRoutes(curves,routes)) return curves; - } - } - // In flowing paragraphs, keep a gently bowed passage beneath the source - // line, then devote the free margin to a fuller curve. No straight rails. - var edge={x:(direction<0?bounds.left-14:bounds.right+14)-inset,y:start.y+5}; - var innerDistance=Math.abs(edge.x-start.x), outerDistance=Math.abs(end.x-edge.x); - var outerWave=Math.max(22,Math.min(84,outerDistance*.32)); - var fallback; - for(var sweep=0;sweep<2;sweep++) { - var wave=(sweep===0?1:-1)*outerWave; - fallback=[[start,{x:start.x+direction*innerDistance*.28,y:start.y+8}, - {x:edge.x-direction*innerDistance*.28,y:edge.y},edge], - [edge,{x:edge.x+direction*outerDistance*.34,y:edge.y}, - {x:end.x-direction*outerDistance*.34,y:end.y-wave},end]]; - if(fallback.every(function(curve){return clearCurve(curve,obstacles);}) && clearRoutes(fallback,routes)) return fallback; - } - return fallback; - } - - function drawConnections(surface, bounds, inset, notes) { - var ns = 'http://www.w3.org/2000/svg'; - var svg = document.createElementNS(ns, 'svg'); - svg.classList.add('reader-connectors'); svg.setAttribute('aria-hidden', 'true'); - svg.style.left = (inset - bounds.left) + 'px'; - svg.setAttribute('width', String(innerWidth - inset * 2)); - svg.setAttribute('height', String(surface.offsetHeight)); - var obstacles=sourceObstacles(surface,inset,bounds.top), routes=[]; - var defs=document.createElementNS(ns,'defs');svg.appendChild(defs); - notes.forEach(function (note, noteIndex) { - var fragments = anchorFragments(note.anchor); - var a = note.side === 0 ? fragments[0] : fragments[fragments.length - 1]; - if (!a) return; - var c = note.chip.getBoundingClientRect(), heading = note.chip.querySelector('.annot-label').getBoundingClientRect(); - var direction = note.side === 0 ? -1 : 1; - var sx = (note.side === 0 ? a.left - 2 : a.right + 2) - inset, sy = a.bottom - bounds.top + 2; - var ex = (note.side === 0 ? heading.right + 9 : heading.left - 9) - inset; - var ey = heading.top + heading.height / 2 - bounds.top; - var curves=flowingCurve({x:sx,y:sy},{x:ex,y:ey},direction,bounds,inset,obstacles,routes); - routes.push(routeSamples(curves)); - var pathData=curveData(curves); - var gradient=document.createElementNS(ns,'linearGradient'); - gradient.id='reader-curve-ink-'+noteIndex;gradient.setAttribute('gradientUnits','userSpaceOnUse'); - gradient.setAttribute('x1',sx);gradient.setAttribute('y1',sy);gradient.setAttribute('x2',ex);gradient.setAttribute('y2',ey); - [['0%','reader-curve-gold'],['55%','reader-curve-olive'],['100%','reader-curve-gold']].forEach(function(stop){ - var node=document.createElementNS(ns,'stop');node.setAttribute('offset',stop[0]);node.setAttribute('class',stop[1]);gradient.appendChild(node); - }); - defs.appendChild(gradient); - var group = document.createElementNS(ns, 'g'); group.classList.add('reader-connector'); - group.dataset.annotId = note.chip.dataset.annotId; - if (!note.anchor.dataset.readerSourceAnchor) note.anchor.dataset.readerSourceAnchor = 'reader-anchor-' + (++anchorSequence); - group.dataset.readerAnchor = note.anchor.dataset.readerSourceAnchor; - note.chip.dataset.readerAnchor = group.dataset.readerAnchor; - group.dataset.startX = String(sx + inset); group.dataset.startY = String(sy + bounds.top); - ['reader-leader-halo', 'reader-leader'].forEach(function (cls) { - var path = document.createElementNS(ns, 'path'); path.setAttribute('class', cls); path.setAttribute('d', pathData); - if(cls==='reader-leader') path.style.stroke='url(#'+gradient.id+')'; - group.appendChild(path); - }); - [[sx, sy, 'reader-source-dot'], [ex, ey, 'reader-note-dot']].forEach(function (point) { - var dot = document.createElementNS(ns, 'circle'); dot.setAttribute('cx', point[0]); dot.setAttribute('cy', point[1]); - dot.setAttribute('r', point[2] === 'reader-source-dot' ? '2.2' : '1.7'); dot.setAttribute('class', point[2]); group.appendChild(dot); - }); - svg.appendChild(group); - }); - surface.appendChild(svg); - } - function layoutAnnotations() { - var bands = Array.from(document.querySelectorAll('[data-annot-band]')); - var surface = document.querySelector('.document-surface'); - resetNotes(bands, surface); - if (!surface) return; - if (innerWidth <= 1000 || document.body.classList.contains('reader-hide-notes') || matchMedia('print').matches) { - setNoteTail(surface, 0); return; - } - var inset = Math.max(24, Math.min(56, innerWidth * .025)); - var bounds = surface.getBoundingClientRect(); - var space = [bounds.left - inset, innerWidth - inset - bounds.right]; - if (Math.min.apply(Math, space) < 180) { setNoteTail(surface, 0); return; } - var eligible = bands.map(function (band) { - var owner = noteOwner(band); - if (!owner || !owner.getClientRects().length || owner.matches('.doc-table-wrap')) return null; - var chips = Array.from(band.querySelectorAll('.annot-chip')).filter(function (chip) { - return !chip.hidden && !chip.classList.contains('is-frame-hidden') - && (!chip.classList.contains('annot-chip-overflow') || band.classList.contains('is-expanded')); - }); - var more = band.querySelector('[data-annot-more]'); - if (!chips.length || chips.length > 4 || more && !more.hidden) return null; - var items = chips.map(function (chip) { return {chip:chip, anchor:findAnchor(owner,chip), owner:owner, band:band}; }); - return items.every(function (it) { return it.anchor && anchorFragments(it.anchor).length; }) ? {band:band, owner:owner, items:items} : null; - }).filter(Boolean); - var excluded = new Set(), finalNotes = []; - // Falling back to flow changes later source positions. Re-measure the whole - // document after each fallback batch, instead of leaving stale endpoints. - for (var pass = 0; pass <= eligible.length; pass++) { - resetNotes(bands, surface); - var active = eligible.filter(function (b) { return !excluded.has(b.band); }); - active.forEach(function (b) { b.owner.classList.add('has-margin-notes'); }); - bounds = surface.getBoundingClientRect(); - var nextY = [bounds.top + scrollY + 6, bounds.top + scrollY + 6], counts = [0,0]; - var items = [].concat.apply([], active.map(function (b) { return b.items; })); - items.sort(function (a,b) { return a.anchor.getBoundingClientRect().top - b.anchor.getBoundingClientRect().top; }); - var rejected = new Set(), notes = []; - items.forEach(function (item, index) { - if (rejected.has(item.band)) return; - var fragments = anchorFragments(item.anchor); - var width = Math.max(140, Math.min(190, Math.min.apply(Math, space) * .58)); - item.chip.classList.add('is-margin-note'); item.chip.style.width = width + 'px'; - if(item.chip.classList.contains('annot-implementation')) setDisclosure(item.chip,implementationOpen(item.chip,true)); - var height = item.chip.offsetHeight, stagger = [-58, 44, -34, 68][index % 4]; - var choices = nextY.map(function (y, side) { - var fragment = side === 0 ? fragments[0] : fragments[fragments.length - 1]; - var desired = Math.max(bounds.top + scrollY + 6, fragment.bottom + scrollY - 16 + stagger); - var top = Math.max(desired, y); - return {side:side, anchor:fragment, top:top, - cost:Math.max(0, y - desired) * 3 + counts[side] * 35 + (side === index % 2 ? 0 : 24)}; - }); - var choice = choices[0].cost <= choices[1].cost ? choices[0] : choices[1]; - var side = choice.side, top = choice.top; - if (top - (choice.anchor.bottom + scrollY) > 170) { rejected.add(item.band); return; } - var maxGap=space[side]-width; - var baseGap=Math.min(130,space[side]*.24,maxGap-12); - var gap=Math.max(24,Math.min(maxGap,baseGap+[0,28,-16,44][counts[side]%4])); - var x=side===0?bounds.left-gap-width:bounds.right+gap; - var ownerRect = item.owner.getBoundingClientRect(); - item.chip.style.left = (x - ownerRect.left) + 'px'; item.chip.style.top = (top - scrollY - ownerRect.top) + 'px'; - item.chip.dataset.readerSide = side === 0 ? 'left' : 'right'; - nextY[side] = top + height + 28; counts[side]++; - notes.push({chip:item.chip,anchor:item.anchor,side:side}); - }); - if (rejected.size) { rejected.forEach(function (band) { excluded.add(band); }); continue; } - finalNotes = notes; break; - } - var tail = parseFloat(surface.style.getPropertyValue('--reader-note-tail')) || 0; - var bottom = bounds.bottom - tail; - var noteBottom = finalNotes.reduce(function (max,note) { return Math.max(max,note.chip.getBoundingClientRect().bottom); }, bottom); - setNoteTail(surface, noteBottom > bottom ? noteBottom - bottom + 20 : 0); - if (finalNotes.length) drawConnections(surface, bounds, inset, finalNotes); - } - function refreshAnnotations() { - if (pending) return; pending = true; - requestAnimationFrame(function () { pending = false; layoutAnnotations(); }); - } - function applyExecution(data) { - if (!data.ok) return; - var token = window.MARQDO_VIEW_PAGE_TOKEN || ''; - if (token && data.page_token && token !== data.page_token) { toast('文档已修改,请重新加载以查看新执行信息。'); return; } - var trace = document.getElementById('mq-view-trace'); - if (trace && data.trace_json) trace.textContent = data.trace_json; - var structure = document.getElementById('structure'); - var choices = []; - if (structure && data.structure_html) { - structure.querySelectorAll('.call-picker,.loop-picker').forEach(function (el, i) { choices.push({index:i,value:el.value}); }); - var destinations = new Map(); - structure.querySelectorAll('a[data-document-href]').forEach(function (link) { - destinations.set(link.dataset.documentHref, link.getAttribute('href')); - }); - structure.innerHTML = data.structure_html; - restoreDisclosures(structure); - structure.querySelectorAll('a[data-document-href]').forEach(function (link) { - if(destinations.has(link.dataset.documentHref)) link.setAttribute('href', destinations.get(link.dataset.documentHref)); - }); - if (window.marqdoInitDocument) window.marqdoInitDocument(); - var pickers = structure.querySelectorAll('.call-picker,.loop-picker'); - choices.forEach(function (choice) { - var el=pickers[choice.index]; if(el && Array.from(el.options).some(function(o){return o.value===choice.value;})) {el.value=choice.value;el.dispatchEvent(new Event('change',{bubbles:true}));} - }); - if (window.renderMathInElement) window.renderMathInElement(structure, {delimiters:[{left:'$$',right:'$$',display:true},{left:'\\(',right:'\\)',display:false}]}); - } - var vars = document.getElementById('vars-panel'); if (vars && typeof data.bindings_html === 'string') vars.innerHTML = data.bindings_html; - refreshAnnotations(); - } - window.MarqdoReader = { refreshAnnotations: refreshAnnotations, applyExecution: applyExecution }; - function init() { - dialog = document.getElementById('reader-dialog'); content = document.getElementById('reader-dialog-content'); - dialog.addEventListener('close', function () { restorePanels(); refreshAnnotations(); }); - // Capture native summary activation before other handlers can stop bubbling. - // Keyboard activation also produces a click; never cancel the native toggle. - document.addEventListener('click', function(ev) { - var summary=ev.target.closest('.annot-implementation > summary, .annot-implementation .logic-source > summary'); - if(!summary || summary.closest('#reader-dialog')) return; - var node=summary.parentElement, key=disclosureKey(node); - if(key) disclosureChoices.set(key,!node.open); - refreshAnnotations(); - }, true); - document.addEventListener('click', function (ev) { - var definition=ev.target.closest('.logic-definition'); - if(definition && dialog.open) dialog.close(); - var logic=ev.target.closest('button[data-logic-id]'); - if(logic) { - ev.preventDefault(); - var note=document.getElementById(logic.dataset.logicId+'-note'); - var kind=note && note.querySelector('.logic-kind'); - openDialog((kind ? kind.textContent : '内容详情')+' · '+logic.textContent,'logic'); - var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码与说明,阅读不会执行;运行结果另有标注。';content.appendChild(hint); - var body=note && note.querySelector('.logic-body'); - if(body) { - var copy=body.cloneNode(true);copy.classList.remove('annot-value'); - content.appendChild(copy); - } else { - var fallback=document.createElement('p');fallback.textContent='此片段的详情暂不可用。';content.appendChild(fallback); - } - return; - } - var knowledge=ev.target.closest('.knowledge-explain, [data-knowledge-link]'); - if(knowledge) { - var target=document.getElementById((knowledge.getAttribute('href')||'').slice(1)); - if(target){ev.preventDefault();if(dialog.open)dialog.close();var parent=target;while(parent){if(parent.tagName==='DETAILS')parent.open=true;parent=parent.parentElement;}scrollTo(target);}return; - } - var sourceLink=ev.target.closest('.knowledge-source-link,.knowledge-step a'); - if(sourceLink && dialog.open) dialog.close(); - var button = ev.target.closest('[data-reader-action]'); if (button) action(button.dataset.readerAction); - var chip = ev.target.closest('.annot-chip'); - if (chip && !chip.classList.contains('annot-implementation')) { openDialog(chip.querySelector('.annot-label').textContent, 'annotation'); var pre = document.createElement('pre'); pre.textContent = chip.title || chip.textContent; content.appendChild(pre); } - if (ev.target.closest('.reader-brand')) { ev.preventDefault(); window.scrollTo({top:0,behavior:'auto'}); } - if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); } - }); - document.addEventListener('toggle', function(ev) { - var node=ev.target; - if(!node.matches('.annot-implementation, .annot-implementation .logic-source') || node.closest('#reader-dialog')) return; - var expected=layoutToggles.get(node); - layoutToggles.delete(node); - // Layout writes can coalesce into one native toggle event. They must not - // become user choices or schedule another reset/measure cycle. - if(expected===node.open) return; - var key=disclosureKey(node); - if(key) disclosureChoices.set(key,node.open); - refreshAnnotations(); - }, true); - function focusNote(ev, focus) { - var trigger=ev.target.closest('.annot-chip,[data-logic-id]'); - if(!trigger || ev.relatedTarget && trigger.contains(ev.relatedTarget)) return; - var chip=trigger.matches('.annot-chip') ? trigger : document.getElementById(trigger.dataset.logicId+'-note'); - if(!chip) return; - var owner = noteOwner(chip.closest('[data-annot-band]')); - var anchor = findAnchor(owner,chip); if (anchor) anchor.classList.toggle('is-focus', focus); - chip.classList.toggle('is-focus',focus); - document.querySelectorAll('.reader-connector').forEach(function (group) { - if (group.dataset.annotId === chip.dataset.annotId) group.classList.toggle('is-focus',focus); - }); - } - document.addEventListener('pointerover',function(e){focusNote(e,true);}); - document.addEventListener('pointerout',function(e){focusNote(e,false);}); - document.addEventListener('focusin',function(e){focusNote(e,true);}); - document.addEventListener('focusout',function(e){focusNote(e,false);}); - document.addEventListener('keydown',function(e){ - if(e.key==='Escape'){ var inspector=document.getElementById('var-dialog'); if(inspector && inspector.open) return; if(dialog.open){e.preventDefault();dialog.close();} document.getElementById('nav-toggle').checked=false; document.querySelector('.reader-menu').setAttribute('aria-expanded','false'); } - if((e.ctrlKey||e.metaKey)&&e.key==='k'){ e.preventDefault(); showSearch(); } - }); - document.addEventListener('change',refreshAnnotations); - var path = window.MARQDO_FILE_PATH || ''; - if (/(^|\/)(00[-_])?(welcome|欢迎)/i.test(path)) { - document.body.classList.add('reader-welcome'); - var hero = document.createElement('section'); hero.className = 'reader-hero'; hero.setAttribute('aria-label','Welcome to Marqdo'); - hero.innerHTML = '

          WELCOME TO

          Marqdo

          代码即文档 · 文档即知识库 · 知识即可执行

          '; - document.querySelector('main.panel').prepend(hero); - } - // Observe replacement after live runs, not our own leader/position writes. - var surface = document.getElementById('structure'); - if (surface) { - new MutationObserver(function (changes) { - if (changes.some(function(m){ - if (m.target.closest && m.target.closest('.reader-connectors')) return false; - return Array.from(m.addedNodes).concat(Array.from(m.removedNodes)).some(function(n){ - return n.nodeType===1 && !n.matches('.reader-connectors,.reader-leader,.annot-leaders'); - }); - })) refreshAnnotations(); - }).observe(surface,{childList:true,subtree:true}); - if (typeof ResizeObserver !== 'undefined') new ResizeObserver(refreshAnnotations).observe(surface); - } - window.addEventListener('resize',refreshAnnotations); - window.addEventListener('beforeprint',layoutAnnotations); window.addEventListener('afterprint',refreshAnnotations); - if(document.fonts) document.fonts.ready.then(refreshAnnotations); - refreshAnnotations(); - } - if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',init); else init(); -})(); diff --git a/src/view/render.rs b/src/view/render.rs deleted file mode 100755 index d183190..0000000 --- a/src/view/render.rs +++ /dev/null @@ -1,1970 +0,0 @@ -//! Render Marqdo AST as HTML fragments for `view`. -//! -//! Comments are not in the AST; they are interleaved from classified source lines. -//! Expressions are shown in surface syntax, never Rust `Debug`. - -use std::collections::HashMap; - -use crate::ast::{ - Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp, -}; -use crate::host::writeback; -use crate::lex::{classify_source, ClassifiedLine, LineKind}; -use crate::view::html::escape; -use pulldown_cmark::{html, Options, Parser}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum StructureMode { - /// Documentation browse: fun anchors, no breakpoint gutters - Browse, - /// Debugger: breakpoint gutters on statements - Debug, -} - -pub struct FileViewModel { - #[allow(dead_code)] - pub rel_path: String, - pub source: String, - pub structure_html: String, - pub outline_html: String, - pub stdout: String, - pub stderr: String, - pub ok: bool, - /// A callable-only module has no automatic program entry. - pub library_document: bool, - /// Text shown in the live-view preset stdin box. - pub preset_stdin: String, - /// One entry per `input` / `输入` call (prompt text; may be empty). - /// Empty vec → page does not use input; hide the preset form. - pub input_prompts: Vec, - /// Live view: program uses `input` but no stdin yet — execution deferred until form submit. - pub awaiting_input: bool, - /// Live view: stdin present — skip blocking page-load run; client auto-starts Stream SSE. - pub auto_stream: bool, - /// Show the LLM/agent Stream panel (live view only; gated on ext llm/agent import). - pub show_stream: bool, - /// SVG plots from math lib (embedded in Execution). - pub plots: Vec, - /// HTML for Variables panel (entry bindings after run). - #[allow(dead_code)] - pub bindings_html: String, - /// ViewExecutionReport JSON for AI / call-picker (empty if no run). - pub trace_json: String, - /// Static semantic facts; generated without evaluating the document. - pub knowledge_html: String, - /// Visible when semantic analysis fails (V0); empty when analysis succeeded or was skipped. - pub knowledge_error: String, - /// V2: page token for SSE stale-packet rejection (empty when unknown). - pub page_token: String, -} - -/// A compact, textual (not colour-only) explanation of executable knowledge. -/// View deliberately compiles semantics without running the target, so a page -/// can show binding/effect/verification facts even in `--no-exec` exports. -/// -/// The reader groups facts by source unit and folds raw identifiers into technical detail. -pub fn render_knowledge_html(project: &crate::sema::SemanticProject, rel: &str) -> String { - crate::view::knowledge_reading::render(project, rel, None) -} - -/// Collect prompt strings from every `input` / `输入` call in the module (pre-order). -pub fn collect_input_prompts(module: &Module) -> Vec { - let mut out = Vec::new(); - for fun in &module.functions { - collect_input_prompts_fun(fun, &mut out); - } - out -} - -/// Stream panel is for LLM/agent token streaming — only when those ext packages are imported. -pub fn uses_stream_panel(module: &Module) -> bool { - module.imports.iter().any(|imp| import_enables_stream(&imp.path)) -} - -fn import_enables_stream(path: &str) -> bool { - let norm = path.replace('\\', "/"); - let lower = norm.to_ascii_lowercase(); - lower.contains("ext/ai/llm") - || lower.contains("/llm.mq.md") - || lower.ends_with("llm.mq.md") - || lower.contains("ext/llm") - || norm.contains("ext/ai/大模型") - || norm.contains("大模型.mq.md") - || lower.contains("ext/ai/agent") - || lower.contains("/agent.mq.md") - || lower.ends_with("agent.mq.md") - || lower.contains("ext/agent") - || norm.contains("ext/ai/智能体") - || norm.contains("智能体.mq.md") -} - -fn collect_input_prompts_fun(fun: &Function, out: &mut Vec) { - for stmt in &fun.body { - collect_input_prompts_stmt(stmt, out); - } - for child in &fun.children { - collect_input_prompts_fun(child, out); - } -} - -fn collect_input_prompts_stmt(stmt: &Stmt, out: &mut Vec) { - match stmt { - Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { - collect_input_prompts_expr(value, out); - } - Stmt::Call { call, .. } => { - push_input_prompt(call, out); - for a in &call.args { - match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => { - collect_input_prompts_expr(e, out); - } - } - } - } - Stmt::Branch { arms, .. } => { - for arm in arms { - if let Some(c) = &arm.condition { - collect_input_prompts_expr(c, out); - } - for s in &arm.body { - collect_input_prompts_stmt(s, out); - } - } - } - Stmt::While { - condition, body, .. - } => { - collect_input_prompts_expr(condition, out); - for s in body { - collect_input_prompts_stmt(s, out); - } - } - Stmt::ForEach { body, .. } => { - for s in body { - collect_input_prompts_stmt(s, out); - } - } - } -} - -fn collect_input_prompts_expr(expr: &Expr, out: &mut Vec) { - match expr { - Expr::Occluded { payload, .. } => { - if let Some(inner) = payload { - collect_input_prompts_expr(inner, out); - } - } - Expr::Call(call) => { - push_input_prompt(call, out); - for a in &call.args { - match a { - Arg::Positional(e) | Arg::Named { value: e, .. } => { - collect_input_prompts_expr(e, out); - } - } - } - } - Expr::Unary { expr, .. } => collect_input_prompts_expr(expr, out), - Expr::Binary { left, right, .. } => { - collect_input_prompts_expr(left, out); - collect_input_prompts_expr(right, out); - } - Expr::List(items) => { - for e in items { - collect_input_prompts_expr(e, out); - } - } - Expr::Map(pairs) => { - for (_, e) in pairs { - collect_input_prompts_expr(e, out); - } - } - Expr::Index { base, .. } => collect_input_prompts_expr(base, out), - Expr::Literal(_) | Expr::Var(_) | Expr::Interp(_) | Expr::Formula(_) | Expr::Code(_) => {} - } -} - -fn push_input_prompt(call: &CallExpr, out: &mut Vec) { - if crate::aliases::canonical_builtin(&call.callee) != Some("input") { - return; - } - for a in &call.args { - if let Arg::Named { name, value } = a { - if crate::aliases::canonical_param("input", name) == "prompt" { - out.push(prompt_expr_text(value)); - return; - } - } - } - if let Some(Arg::Positional(value)) = call.args.first() { - out.push(prompt_expr_text(value)); - return; - } - out.push(String::new()); -} - -fn prompt_expr_text(expr: &Expr) -> String { - match expr { - Expr::Literal(Literal::Text(t)) => t.clone(), - Expr::Literal(lit) => lit_display(lit), - other => expr_display(other), - } -} - -/// Browse Structure without run annotations (empty callouts). -pub fn render_module_structure(module: &Module, source: &str) -> String { - render_module_structure_mode(module, source, StructureMode::Browse) -} - -/// Browse Structure: document surface with optional result annotations. -pub fn render_module_structure_with_annots( - module: &Module, - source: &str, - annots: &[crate::view::annot::ViewAnnot], -) -> String { - crate::view::document::render_module_document(module, source, annots) -} - -pub fn render_module_structure_mode( - module: &Module, - source: &str, - mode: StructureMode, -) -> String { - match mode { - StructureMode::Browse => render_module_structure_with_annots(module, source, &[]), - StructureMode::Debug => render_module_structure_cards(module, source, mode), - } -} - -/// Legacy AST-card Structure (debug + tests that need card markup). -pub fn render_module_structure_cards( - module: &Module, - source: &str, - mode: StructureMode, -) -> String { - let lines = classify_source(source); - let writebacks = writeback::writeback_map(source); - let mut out = String::new(); - - if !module.imports.is_empty() || !module.uses.is_empty() { - out.push_str("
          import"); - for imp in &module.imports { - let label = format!("{}:{}", imp.bind, imp.path); - out.push_str(&format!("{}", escape(&label))); - } - for u in &module.uses { - let label = format!("{}:{}", u.bind, u.path.join(".")); - out.push_str(&format!("{}", escape(&label))); - } - out.push_str("
          "); - } - - let body_start = skip_frontmatter_end(&lines).unwrap_or(1); - let mut cursor = body_start; - - if module.functions.is_empty() { - out.push_str(&emit_comments(&lines, cursor, u32::MAX)); - if out.is_empty() { - out.push_str("

          (empty module)

          "); - } - return out; - } - - // Leading comments before first function - let first = module.functions[0].span.line; - out.push_str(&emit_comments(&lines, cursor, first)); - cursor = first; - - for (i, fun) in module.functions.iter().enumerate() { - if i > 0 { - out.push_str(&emit_comments(&lines, cursor, fun.span.line)); - } - let (html, next) = render_fun(fun, &lines, 0, "", mode, &writebacks); - out.push_str(&html); - cursor = next; - } - - // Trailing comments after last function tree - out.push_str(&emit_comments(&lines, cursor, u32::MAX)); - out -} - -pub fn render_function_outline(module: &Module) -> String { - if module.functions.is_empty() { - return String::new(); - } - let mut out = String::from( - r#"
          - -
            "#, - ); - for fun in &module.functions { - out.push_str(&outline_fun(fun, "")); - } - out.push_str("
          "); - out -} - -/// Right rail: collapsible Functions + Variables (+ optional writeback HTML appended by caller). -pub fn render_right_rail(module: &Module, bindings_html: &str, writeback_html: &str) -> String { - let fn_inner = if module.functions.is_empty() { - r#"

          No functions

          "#.to_string() - } else { - let mut tree = String::from( - r#" -
            "#, - ); - for fun in &module.functions { - tree.push_str(&outline_fun(fun, "")); - } - tree.push_str("
          "); - tree - }; - let vars = if bindings_html.is_empty() { - r#"

          No bindings

          "# - } else { - bindings_html - }; - format!( - r#"
          -
          -Functions -
          {fn_inner}
          -
          -
          -Variables -
          {vars}
          -
          -{wb} -
          "#, - fn_inner = fn_inner, - vars = vars, - wb = writeback_html, - ) -} - -/// Render entry bindings: visible preview in the rail; click card → inspect dialog. -pub fn render_bindings_html(bindings: &HashMap) -> String { - if bindings.is_empty() { - return String::new(); - } - let mut names: Vec<&String> = bindings.keys().collect(); - names.sort(); - let mut out = String::from(r#"
            "#); - for (i, name) in names.into_iter().enumerate() { - let Some(val) = bindings.get(name) else { - continue; - }; - let kind = value_kind_label(val); - let preview = render_value_preview_html(val); - let full = render_value_rich(val, 0); - out.push_str(&format!( - r#"
          • -
            -{name} -{kind} -
            -
            {preview}
            - -
          • "#, - name = escape(name), - kind = escape(&kind), - preview = preview, - id = i, - full = full, - )); - } - out.push_str("
          "); - out -} - -/// Compact inline preview (may truncate visually via CSS). -fn render_value_preview_html(v: &crate::value::Value) -> String { - use crate::value::Value; - match v { - Value::Formula(e) => { - let tex = match e { - crate::formula::Expr::Matrix { source, .. } => escape(source), - _ => escape(&formula_ascii_to_tex(&e.as_display())), - }; - format!(r#"
          $${}$$
          "#, tex) - } - Value::List(xs) => { - if let Some((_, _, complex)) = detect_matrix(xs) { - return render_matrix_grid(xs, complex); - } - render_value_html(v, 0) - } - Value::Map(pairs) => { - if let Some(Value::List(rows)) = pairs - .iter() - .find(|(k, _)| k == "matrix" || k == "矩阵") - .map(|(_, v)| v) - { - if let Some((_, _, complex)) = detect_matrix(rows) { - return render_matrix_grid(rows, complex); - } - } - // Prefer a short key/value peek for objects. - let mut s = String::from(r#""#); - for (k, val) in pairs.iter().take(6) { - if k == "matrix" || k == "矩阵" || k == "ops" { - s.push_str(&format!( - "", - escape(k) - )); - continue; - } - s.push_str(&format!( - "", - escape(k), - escape(&brief_preview_cell(val)) - )); - } - if pairs.len() > 6 { - s.push_str( - r#""#, - ); - } - s.push_str("
          {}…
          {}{}
          …
          "); - s - } - other => format!( - r#"{}"#, - escape(&other.as_display()) - ), - } -} - -fn brief_preview_cell(v: &crate::value::Value) -> String { - use crate::value::Value; - match v { - Value::List(xs) => format!("List({})", xs.len()), - Value::Map(xs) => format!("Map({})", xs.len()), - Value::Formula(_) => "formula".into(), - other => { - let s = other.as_display(); - if s.chars().count() > 36 { - format!("{}…", s.chars().take(36).collect::()) - } else { - s - } - } - } -} - -fn value_kind_label(v: &crate::value::Value) -> String { - use crate::value::Value; - match v { - Value::None => "none".into(), - Value::Bool(_) => "bool".into(), - Value::Int(_) => "int".into(), - Value::Num(_) => "num".into(), - Value::Text(_) => "text".into(), - Value::Secret(_) => "secret".into(), - Value::Handle(_) => "handle".into(), - Value::Formula(crate::formula::Expr::Matrix { rows, .. }) => { - format!("formula · {}×{}", rows.len(), rows.first().map(|r| r.len()).unwrap_or(0)) - } - Value::Formula(_) => "formula".into(), - Value::Code(c) => format!("code · {}", c.lang), - Value::List(xs) => { - if let Some((r, c, _)) = detect_matrix(xs) { - format!("matrix · {r}×{c}") - } else { - format!("list · {}", xs.len()) - } - } - Value::Map(pairs) => { - if let Some(t) = pairs.iter().find(|(k, _)| k == "_type").and_then(|(_, v)| match v { - Value::Text(s) => Some(s.as_str()), - _ => None, - }) { - if let Some(Value::List(rows)) = pairs - .iter() - .find(|(k, _)| k == "matrix" || k == "矩阵") - .map(|(_, v)| v) - { - if let Some((r, c, _)) = detect_matrix(rows) { - return format!("{t} · {r}×{c}"); - } - } - t.to_string() - } else { - format!("map · {}", pairs.len()) - } - } - } -} - -/// Complex or real matrix: rows × cols, and whether cells are complex maps. -fn detect_matrix(xs: &[crate::value::Value]) -> Option<(usize, usize, bool)> { - use crate::value::Value; - if xs.is_empty() { - return None; - } - let mut cols = None; - let mut complex = false; - for row in xs { - let Value::List(cells) = row else { - return None; - }; - if cells.is_empty() { - return None; - } - match cols { - None => cols = Some(cells.len()), - Some(c) if c != cells.len() => return None, - _ => {} - } - for c in cells { - match c { - Value::Num(_) | Value::Int(_) => {} - Value::Map(m) - if m.iter().any(|(k, _)| k == "re") - && m.iter().any(|(k, _)| k == "im") => - { - complex = true; - } - _ => return None, - } - } - } - Some((xs.len(), cols.unwrap_or(0), complex)) -} - -fn format_complex_cell(v: &crate::value::Value) -> String { - use crate::value::Value; - match v { - Value::Num(n) => format_matrix_num(*n), - Value::Int(i) => i.to_string(), - Value::Map(m) => { - let re = m - .iter() - .find(|(k, _)| k == "re") - .and_then(|(_, v)| match v { - Value::Num(n) => Some(*n), - Value::Int(i) => Some(*i as f64), - _ => None, - }) - .unwrap_or(0.0); - let im = m - .iter() - .find(|(k, _)| k == "im") - .and_then(|(_, v)| match v { - Value::Num(n) => Some(*n), - Value::Int(i) => Some(*i as f64), - _ => None, - }) - .unwrap_or(0.0); - if im.abs() < 1e-12 { - format_matrix_num(re) - } else if re.abs() < 1e-12 { - format!("{}i", format_matrix_num(im)) - } else { - format!("{}{:+}i", format_matrix_num(re), im) - } - } - other => other.as_display(), - } -} - -fn format_matrix_num(n: f64) -> String { - if n.fract().abs() < 1e-12 && n.abs() < 1e15 { - format!("{}", n as i64) - } else { - let s = format!("{n:.6}"); - s.trim_end_matches('0').trim_end_matches('.').to_string() - } -} - -fn render_matrix_grid(xs: &[crate::value::Value], complex: bool) -> String { - let mut s = String::from(r#"
          "#); - if complex { - s.push_str(r#""#); - } - s.push_str(""); - for row in xs { - let crate::value::Value::List(cells) = row else { - continue; - }; - s.push_str(""); - for c in cells { - let label = escape(&format_complex_cell(c)); - let mag = match c { - crate::value::Value::Num(n) => n.abs(), - crate::value::Value::Int(i) => (*i as f64).abs(), - crate::value::Value::Map(m) => { - let re = m - .iter() - .find(|(k, _)| k == "re") - .and_then(|(_, v)| match v { - crate::value::Value::Num(n) => Some(*n), - _ => None, - }) - .unwrap_or(0.0); - let im = m - .iter() - .find(|(k, _)| k == "im") - .and_then(|(_, v)| match v { - crate::value::Value::Num(n) => Some(*n), - _ => None, - }) - .unwrap_or(0.0); - (re * re + im * im).sqrt() - } - _ => 0.0, - }; - let heat = mag.clamp(0.0, 1.0); - let bg = format!( - "rgba(74, 111, 165, {:.3})", - 0.06 + heat * 0.42 - ); - s.push_str(&format!( - r#""# - )); - } - s.push_str(""); - } - s.push_str("
          complex amplitudes
          {label}
          "); - s -} - -const BIND_MAX_DEPTH: usize = 3; - -/// Full rich HTML for the inspect dialog (matrices get a dedicated grid). -fn render_value_rich(v: &crate::value::Value, depth: usize) -> String { - use crate::value::Value; - match v { - Value::List(xs) => { - if let Some((_, _, complex)) = detect_matrix(xs) { - return render_matrix_grid(xs, complex); - } - if let Some(keys) = record_keys(xs) { - return render_records_table(xs, &keys, depth); - } - render_value_html(v, depth) - } - Value::Map(pairs) => { - // Prefer pretty matrix when object carries `matrix` / `矩阵`. - if let Some(Value::List(rows)) = pairs - .iter() - .find(|(k, _)| k == "matrix" || k == "矩阵") - .map(|(_, v)| v) - { - if let Some((_, _, complex)) = detect_matrix(rows) { - let mut s = String::from(r#"
          "#); - if let Some(Value::Text(t)) = - pairs.iter().find(|(k, _)| k == "_type").map(|(_, v)| v) - { - s.push_str(&format!( - r#"

          {}"#, - escape(t) - )); - if let Some(Value::Text(n)) = - pairs.iter().find(|(k, _)| k == "name" || k == "名").map(|(_, v)| v) - { - s.push_str(&format!( - r#" {}"#, - escape(n) - )); - } - s.push_str("

          "); - } - s.push_str(&render_matrix_grid(rows, complex)); - // Other keys (skip matrix / _type / name noise) - let rest: Vec<_> = pairs - .iter() - .filter(|(k, _)| { - k != "matrix" - && k != "矩阵" - && k != "_type" - && k != "name" - && k != "名" - && k != "custom" - }) - .collect(); - if !rest.is_empty() { - s.push_str(r#"
          Other fields"#); - s.push_str(r#""#); - for (k, val) in rest { - s.push_str(&format!( - "", - escape(k), - cell_html(val, depth) - )); - } - s.push_str("
          {}{}
          "); - } - s.push_str("
          "); - return s; - } - } - render_value_html(v, depth) - } - Value::Formula(e) => { - let tex = match e { - crate::formula::Expr::Matrix { source, .. } => escape(source), - _ => escape(&formula_ascii_to_tex(&e.as_display())), - }; - format!( - r#"
          $${}$$
          "#, - tex - ) - } - other => render_value_html(other, depth), - } -} - -fn render_value_html(v: &crate::value::Value, depth: usize) -> String { - use crate::value::Value; - match v { - Value::List(xs) => { - if let Some((_, _, complex)) = detect_matrix(xs) { - return render_matrix_grid(xs, complex); - } - if let Some(keys) = record_keys(xs) { - return render_records_table(xs, &keys, depth); - } - let mut s = String::from(r#""#); - for (i, item) in xs.iter().enumerate() { - s.push_str(&format!( - "", - i + 1, - cell_html(item, depth) - )); - } - if xs.is_empty() { - s.push_str(r#""#); - } - s.push_str("
          #value
          {}{}
          ∅
          "); - s - } - Value::Map(pairs) => { - let mut s = String::from( - r#""#, - ); - for (k, val) in pairs { - s.push_str(&format!( - "", - escape(k), - cell_html(val, depth) - )); - } - if pairs.is_empty() { - s.push_str(r#""#); - } - s.push_str("
          keyvalue
          {}{}
          ∅
          "); - s - } - Value::Formula(e) => { - let tex = match e { - crate::formula::Expr::Matrix { source, .. } => escape(source), - _ => escape(&formula_ascii_to_tex(&e.as_display())), - }; - format!(r#"
          $${}$$
          "#, tex) - } - other => format!(r#"{}"#, escape(&other.as_display())), - } -} - -fn cell_html(v: &crate::value::Value, depth: usize) -> String { - use crate::value::Value; - match v { - Value::List(_) | Value::Map(_) if depth >= BIND_MAX_DEPTH => { - format!( - r#"
          {}{}
          "#, - escape(&brief_type(v)), - escape(&v.as_display()) - ) - } - Value::List(_) | Value::Map(_) => render_value_html(v, depth + 1), - Value::Formula(e) => { - let tex = match e { - crate::formula::Expr::Matrix { source, .. } => escape(source), - _ => escape(&formula_ascii_to_tex(&e.as_display())), - }; - format!(r#"
          $${}$$
          "#, tex) - } - other => escape(&other.as_display()), - } -} - -fn brief_type(v: &crate::value::Value) -> String { - use crate::value::Value; - match v { - Value::List(xs) => format!("List({})", xs.len()), - Value::Map(xs) => format!("Map({})", xs.len()), - _ => "…".into(), - } -} - -fn record_keys(xs: &[crate::value::Value]) -> Option> { - use crate::value::Value; - if xs.is_empty() { - return None; - } - let mut keys: Vec = Vec::new(); - for (i, item) in xs.iter().enumerate() { - let Value::Map(pairs) = item else { - return None; - }; - if i == 0 { - keys = pairs.iter().map(|(k, _)| k.clone()).collect(); - if keys.is_empty() { - return None; - } - } - } - Some(keys) -} - -fn render_records_table( - xs: &[crate::value::Value], - keys: &[String], - depth: usize, -) -> String { - use crate::value::Value; - let mut s = String::from(r#""#); - for k in keys { - s.push_str(&format!("", escape(k))); - } - s.push_str(""); - for (i, item) in xs.iter().enumerate() { - let Value::Map(pairs) = item else { - continue; - }; - s.push_str(&format!(r#""#, i + 1)); - for k in keys { - let cell = pairs - .iter() - .find(|(kk, _)| kk == k) - .map(|(_, v)| cell_html(v, depth)) - .unwrap_or_else(|| String::from("")); - s.push_str(&format!("")); - } - s.push_str(""); - } - s.push_str("
          #{}
          {}{cell}
          "); - s -} - -fn outline_fun(fun: &Function, parent_path: &str) -> String { - let fn_path = fn_path(parent_path, &fun.name); - let mut s = format!( - "
        • \ - {} h{}", - escape(&fun.name), - escape(&fn_path), - fun.span.line, - escape(&fun.name), - fun.level, - ); - if !fun.params.is_empty() { - s.push_str(" "); - for (i, p) in fun.params.iter().enumerate() { - if i > 0 { - s.push(' '); - } - if p.inferred { - s.push_str(&format!( - "{}", - escape(&p.name) - )); - } else { - s.push_str(&format!( - "{}", - escape(&p.name) - )); - } - } - s.push_str(""); - } - if !fun.children.is_empty() { - s.push_str("
            "); - for child in &fun.children { - s.push_str(&outline_fun(child, &fn_path)); - } - s.push_str("
          "); - } - s.push_str("
        • "); - s -} - -fn fn_path(parent_path: &str, name: &str) -> String { - if parent_path.is_empty() { - name.to_string() - } else { - format!("{parent_path}/{name}") - } -} - -/// Line after closing frontmatter `---`, or 1 if none. -fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option { - let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?; - if first_code.text.trim() != "---" { - return Some(1); - } - for l in lines.iter().skip_while(|l| l.line_no <= first_code.line_no) { - if l.kind == LineKind::Code && l.text.trim() == "---" { - return Some(l.line_no + 1); - } - } - Some(1) -} - -fn emit_comments(lines: &[ClassifiedLine], from_line: u32, before_line: u32) -> String { - let mut s = String::new(); - let mut paragraph: Vec = Vec::new(); - - let flush = |paragraph: &mut Vec, s: &mut String| { - if paragraph.is_empty() { - return; - } - // Soft-wrapped source lines → one Markdown paragraph (spaces between). - let text = paragraph.join(" "); - paragraph.clear(); - s.push_str(&format!( - "
          comment
          {}
          ", - comment_markdown_to_html(&text) - )); - }; - - for l in lines { - if l.line_no < from_line { - continue; - } - if l.line_no >= before_line { - break; - } - match l.kind { - LineKind::Comment => { - let text = l.text.trim(); - if !text.is_empty() { - paragraph.push(text.to_string()); - } - } - LineKind::Blank | LineKind::Writeback | LineKind::Code => flush(&mut paragraph, &mut s), - } - } - flush(&mut paragraph, &mut s); - s -} - -/// Render narrative comments as Markdown (links, emphasis, code, lists, …). -pub(crate) fn comment_markdown_to_html(md: &str) -> String { - let mut opts = Options::empty(); - opts.insert(Options::ENABLE_STRIKETHROUGH); - opts.insert(Options::ENABLE_TABLES); - opts.insert(Options::ENABLE_TASKLISTS); - let parser = Parser::new_ext(md, opts); - let mut out = String::new(); - html::push_html(&mut out, parser); - out -} - -fn render_fun( - fun: &Function, - lines: &[ClassifiedLine], - depth: usize, - parent_path: &str, - mode: StructureMode, - writebacks: &HashMap, -) -> (String, u32) { - let fn_path = fn_path(parent_path, &fun.name); - let mut s = String::new(); - let nest = if depth > 0 { " nested" } else { "" }; - s.push_str(&format!( - "
          ", - fun.span.line, - escape(&fun.name), - escape(&fn_path), - )); - s.push_str(&format!( - "
          fn · h{}{}
          ", - fun.level, - escape(&fun.name) - )); - if !fun.params.is_empty() { - s.push_str("
          "); - for p in &fun.params { - let (cls, title) = if p.inferred { - ("chip inferred", "inferred from prose / body") - } else { - ("chip", "explicit + param") - }; - s.push_str(&format!( - "{name}", - cls = cls, - title = title, - name = escape(&p.name), - fn = escape(&fun.name), - )); - } - s.push_str("
          "); - } - - let mut cursor = fun.span.line + 1; - - // Comments / gap before first body stmt or child - let first_body = fun.body.first().map(stmt_start); - let first_child = fun.children.first().map(|c| c.span.line); - let first_content = match (first_body, first_child) { - (Some(a), Some(b)) => Some(a.min(b)), - (Some(a), None) => Some(a), - (None, Some(b)) => Some(b), - (None, None) => None, - }; - if let Some(fc) = first_content { - s.push_str(&emit_comments(lines, cursor, fc)); - cursor = fc; - } - - // Interleave body stmts and nested functions by source line - let mut bi = 0usize; - let mut ci = 0usize; - while bi < fun.body.len() || ci < fun.children.len() { - let stmt_line = fun.body.get(bi).map(stmt_start); - let child_line = fun.children.get(ci).map(|c| c.span.line); - let take_stmt = match (stmt_line, child_line) { - (Some(sl), Some(cl)) => sl <= cl, - (Some(_), None) => true, - (None, Some(_)) => false, - (None, None) => break, - }; - if take_stmt { - let stmt = &fun.body[bi]; - let start = stmt_start(stmt); - s.push_str(&emit_comments(lines, cursor, start)); - let (html, end) = render_stmt(stmt, lines, mode, writebacks); - s.push_str(&html); - cursor = end; - bi += 1; - } else { - let child = &fun.children[ci]; - s.push_str(&emit_comments(lines, cursor, child.span.line)); - let (html, end) = render_fun(child, lines, depth + 1, &fn_path, mode, writebacks); - s.push_str(&format!("
          {html}
          ")); - cursor = end; - ci += 1; - } - } - - s.push_str("
          "); - (s, cursor) -} - -fn stmt_start(stmt: &Stmt) -> u32 { - match stmt { - Stmt::Assign { span, .. } - | Stmt::Return { span, .. } - | Stmt::Call { span, .. } - | Stmt::Expr { span, .. } - | Stmt::Branch { span, .. } - | Stmt::While { span, .. } - | Stmt::ForEach { span, .. } => span.line, - } -} - -fn stmt_end_line(stmt: &Stmt) -> u32 { - match stmt { - Stmt::Assign { end_line, .. } => end_line + 1, - Stmt::Return { span, .. } | Stmt::Call { span, .. } | Stmt::Expr { span, .. } => { - span.line + 1 - } - Stmt::Branch { arms, span, .. } => { - let mut end = span.line + 1; - for arm in arms { - for st in &arm.body { - end = end.max(stmt_end_line(st)); - } - } - end - } - Stmt::While { body, span, .. } | Stmt::ForEach { body, span, .. } => { - let mut end = span.line + 1; - for st in body { - end = end.max(stmt_end_line(st)); - } - end - } - } -} - -fn output_card(line: u32, writebacks: &HashMap) -> String { - match writebacks.get(&line) { - Some(body) => render_output_card(line, body), - None => String::new(), - } -} - -/// Live view + static site: text `
          ` and/or `` for image writebacks.
          -pub fn render_output_card(line: u32, combined: &str) -> String {
          -    if combined.trim().is_empty() {
          -        return String::new();
          -    }
          -    let badges = writeback_badges(combined);
          -    let mut body_html = String::new();
          -    let mut buf_text = String::new();
          -    let flush_text = |buf: &mut String, out: &mut String| {
          -        if buf.is_empty() {
          -            return;
          -        }
          -        out.push_str(&format!(
          -            r#"
          {}
          "#, - escape(buf.trim_end()) - )); - buf.clear(); - }; - for line_s in combined.lines() { - let t = line_s.trim(); - if let Some(url) = extract_md_image_url(t) { - flush_text(&mut buf_text, &mut body_html); - body_html.push_str(&format!( - r#"
          writeback
          {cap}
          "#, - src = escape(&url), - cap = escape(&url), - )); - } else { - if !buf_text.is_empty() { - buf_text.push('\n'); - } - buf_text.push_str(line_s); - } - } - flush_text(&mut buf_text, &mut body_html); - let has_img = body_html.contains("wb-image"); - format!( - r#"
          {badges}
          {body}
          "#, - line = line, - img_cls = if has_img { " output-card-image" } else { "" }, - badges = badges, - body = body_html, - ) -} - -fn extract_md_image_url(line: &str) -> Option { - let t = line.trim(); - let rest = t.strip_prefix("![")?; - let alt_end = rest.find("](")?; - let after = &rest[alt_end + 2..]; - let url_end = after.rfind(')')?; - let url = after[..url_end].trim(); - if url.is_empty() { - None - } else { - Some(url.to_string()) - } -} - -/// Document-surface marker for a writeback source line (comment or image). -pub fn render_writeback_source_line(line_no: u32, text: &str) -> String { - let trimmed = text.trim(); - let is_image = trimmed.starts_with("![") && trimmed.contains("marqdo-out"); - let kind = if is_image { "image" } else { "comment" }; - let label = if is_image { - "writeback · image" - } else { - "writeback" - }; - format!( - r#"
          {label}{text}
          "#, - line = line_no, - kind = kind, - label = label, - text = escape(trimmed), - ) -} - -fn writeback_badges(body: &str) -> String { - let mut keys = Vec::new(); - for line in body.lines() { - if let Some(rest) = line.strip_prefix('[') { - if let Some(end) = rest.find(']') { - let k = &rest[..end]; - if !k.is_empty() && !keys.iter().any(|x| x == k) { - keys.push(k.to_string()); - } - } - } - } - if keys.is_empty() { - return r#"output"#.into(); - } - keys.into_iter() - .map(|k| { - let cls = match k.as_str() { - "ok" => "wb-ok", - "error" => "wb-error", - "trace" => "wb-trace", - _ => "wb-other", - }; - format!(r#"{k}"#, k = escape(&k)) - }) - .collect::>() - .join(" ") -} - -/// Outline links to writeback cards (`#wb-{line}`). -pub fn render_writeback_outline(source: &str) -> String { - let map = writeback::writeback_map(source); - if map.is_empty() { - return String::new(); - } - let mut lines: Vec = map.keys().copied().filter(|l| *l > 0).collect(); - lines.sort_unstable(); - if lines.is_empty() { - return String::new(); - } - let mut out = String::from( - r#"
          Writebacks
            "#, - ); - for line in lines { - let body = map.get(&line).map(|s| s.as_str()).unwrap_or(""); - let label = if body.contains("[error]") { - "error" - } else if body.contains("[ok]") { - "ok" - } else if body.contains("[trace]") { - "trace" - } else { - "output" - }; - out.push_str(&format!( - r##"
          • L{line} · {label}
          • "##, - line = line, - label = label, - )); - } - out.push_str("
          "); - out -} - -/// `` M8: occlusion card — the description reads as prose, the payload as a -/// code chip, stubs get a badge. Shared by bind / expr / return statements. -fn occl_card(name: Option<&str>, label: &str, payload: Option<&Expr>) -> String { - let pre = match name { - Some(n) => format!( - "`{}` =", - escape(n) - ), - None => String::new(), - }; - let val = match payload { - Some(e) => format!( - "{}", - escape(&expr_display(e)) - ), - None => String::from( - "待补充实际逻辑", - ), - }; - format!( - "
          遮蔽{pre}{}{val}
          ", - escape(label) - ) -} - -fn render_stmt( - stmt: &Stmt, - lines: &[ClassifiedLine], - mode: StructureMode, - writebacks: &HashMap, -) -> (String, u32) { - let end = stmt_end_line(stmt); - let line = stmt_start(stmt); - let inner = match stmt { - Stmt::Assign { - name, - value: Expr::Occluded { label, payload }, - .. - } => occl_card(Some(name), label, payload.as_deref()), - Stmt::Expr { - value: Expr::Occluded { label, payload }, - .. - } => occl_card(None, label, payload.as_deref()), - Stmt::Return { - value: Expr::Occluded { label, payload }, - .. - } => occl_card(None, label, payload.as_deref()), - Stmt::Assign { - name, - value: Expr::Formula(e), - .. - } => { - // Matrix fences keep original LaTeX/`[[…]]` source — feed KaTeX as-is. - // Scalar ASCII formulas go through formula_ascii_to_tex. - let tex = match e { - crate::formula::Expr::Matrix { source, .. } => escape(source), - _ => escape(&formula_ascii_to_tex(&e.as_display())), - }; - format!( - "
          formula \ - `{}` = \ -
          $${}$$
          ", - escape(name), - tex - ) - } - Stmt::Assign { - name, - value: Expr::Code(c), - .. - } => { - let placeholder = escape(&crate::foreign::default_cmd_display(&c.lang)); - let lang = escape(&c.lang); - let src = escape(&c.source); - format!( - r#"
          -
          - code - `{name}` = - {lang} - - -
          -
          {src}
          -
          -
          - - -
          -
          - -
          "#, - lang = lang, - name = escape(name), - placeholder = placeholder, - src = src, - ) - } - Stmt::Assign { name, value, .. } => format!( - "
          bind `{}` = {}
          ", - escape(name), - escape(&expr_display(value)) - ), - Stmt::Return { value, .. } => format!( - "
          return{}
          ", - escape(&expr_display(value)) - ), - Stmt::Call { call, .. } => format!( - "
          call{}
          ", - escape(&call_display(call)) - ), - Stmt::Expr { value, .. } => format!( - "
          expr{}
          ", - escape(&expr_display(value)) - ), - Stmt::Branch { arms, .. } => { - let mut body = - String::from("
          branch"); - let mut arm_cursor = stmt_start(stmt) + 1; - for arm in arms { - let label = match &arm.condition { - None => "else".to_string(), - Some(c) => expr_display(c), - }; - // comments before first stmt in arm (approx: between arms hard; use body starts) - let arm_first = arm.body.first().map(stmt_start); - body.push_str(&format!( - "
          arm{}", - escape(&label) - )); - if let Some(af) = arm_first { - body.push_str(&emit_comments(lines, arm_cursor, af)); - arm_cursor = af; - } - body.push_str("
          "); - for st in &arm.body { - let start = stmt_start(st); - body.push_str(&emit_comments(lines, arm_cursor, start)); - let (h, e) = render_stmt(st, lines, mode, writebacks); - body.push_str(&h); - arm_cursor = e; - } - body.push_str("
          "); - } - body.push_str("
          "); - body - } - Stmt::While { - condition, body, .. - } => { - let mut body_html = format!( - "
          while{}
          ", - escape(&expr_display(condition)) - ); - let mut cursor = stmt_start(stmt) + 1; - for st in body { - let start = stmt_start(st); - body_html.push_str(&emit_comments(lines, cursor, start)); - let (h, e) = render_stmt(st, lines, mode, writebacks); - body_html.push_str(&h); - cursor = e; - } - body_html.push_str("
          "); - body_html - } - Stmt::ForEach { - item, - collection, - body, - .. - } => { - let mut body_html = format!( - "
          foreach[{}]({})
          ", - escape(item), - escape(collection) - ); - let mut cursor = stmt_start(stmt) + 1; - for st in body { - let start = stmt_start(st); - body_html.push_str(&emit_comments(lines, cursor, start)); - let (h, e) = render_stmt(st, lines, mode, writebacks); - body_html.push_str(&h); - cursor = e; - } - body_html.push_str("
          "); - body_html - } - }; - let inner = format!("{}{}", inner, output_card(line, writebacks)); - (stmt_shell(line, &inner, mode), end) -} - -fn stmt_shell(line: u32, inner: &str, mode: StructureMode) -> String { - match mode { - StructureMode::Browse => format!( - r#"
          {inner}
          "#, - line = line, - inner = inner, - ), - StructureMode::Debug => format!( - r#"
          {inner}
          "#, - line = line, - inner = inner, - ), - } -} - -fn call_display(call: &CallExpr) -> String { - let mut s = String::new(); - let bracket = call.bracket_marked || !call.pre_modifiers.is_empty(); - if bracket { - for m in &call.pre_modifiers { - s.push_str(m); - s.push(' '); - } - s.push('['); - if let Some(recv) = &call.receiver { - s.push('`'); - s.push_str(recv); - s.push('`'); - s.push('.'); - s.push_str(&call.callee); - } else if let Some(path) = &call.path { - s.push_str(&path.join(".")); - } else { - s.push_str(&call.callee); - } - s.push(']'); - } else { - s.push_str("> "); - if let Some(recv) = &call.receiver { - s.push('`'); - s.push_str(recv); - s.push('`'); - s.push('.'); - s.push_str(&call.callee); - } else if let Some(path) = &call.path { - s.push_str(&path.join(".")); - } else { - s.push_str(&call.callee); - } - } - for a in &call.args { - match a { - Arg::Positional(e) => { - s.push(' '); - s.push_str(&expr_display(e)); - } - Arg::Named { name, value } => { - s.push(' '); - s.push_str(name); - s.push('='); - s.push_str(&expr_display(value)); - } - } - } - s -} - -/// Surface-syntax preview for view (not Debug). -pub fn expr_display(expr: &Expr) -> String { - expr_prec(expr, 0) -} - -fn expr_prec(expr: &Expr, parent_prec: u8) -> String { - match expr { - // `` M2: show the occlusion surface (label + payload). - Expr::Occluded { label, payload } => match payload { - Some(inner) => format!("[{}]({})", label, expr_prec(inner, 0)), - None => format!("[{}]()", label), - }, - Expr::Literal(lit) => lit_display(lit), - Expr::Var(name) => format!("`{name}`"), - Expr::Interp(parts) => { - let mut s = String::new(); - for p in parts { - match p { - InterpPart::Lit(t) => s.push_str(t), - InterpPart::Var(n) => { - s.push('`'); - s.push_str(n); - s.push('`'); - } - InterpPart::Index { base, labels } => { - // Preferred surface: nested `[key](base)` (legacy footnote still parses). - let mut inner = format!("`{base}`"); - for label in labels { - inner = format!("[{label}]({inner})"); - } - s.push_str(&inner); - } - } - } - s - } - Expr::Unary { op, expr } => { - let prec = 5; - let inner = match op { - UnaryOp::Not => format!("not {}", expr_prec(expr, prec)), - UnaryOp::Neg => format!("-{}", expr_prec(expr, prec)), - }; - wrap(inner, prec, parent_prec) - } - Expr::Binary { op, left, right } => { - let (sym, prec) = bin_sym_prec(*op); - let inner = format!( - "{} {} {}", - expr_prec(left, prec), - sym, - expr_prec(right, prec + 1) // left-assoc bias - ); - wrap(inner, prec, parent_prec) - } - Expr::Call(call) => call_display(call), - Expr::List(items) => { - let parts: Vec = items.iter().map(|e| expr_prec(e, 0)).collect(); - format!("[{}]", parts.join(", ")) - } - Expr::Map(pairs) => { - let parts: Vec = pairs - .iter() - .map(|(k, e)| format!("{}: {}", k, expr_prec(e, 0))) - .collect(); - format!("{{{}}}", parts.join(", ")) - } - Expr::Index { base, label } => { - let key = match label { - crate::ast::IndexKey::Lit(s) => s.clone(), - crate::ast::IndexKey::Var(n) => format!("`{n}`"), - }; - // Preferred surface: GFM link shape (legacy footnote still accepted by parser). - format!("[{}]({})", key, expr_prec(base, 0)) - } - Expr::Formula(e) => format!("$$ {} $$", e.as_display()), - Expr::Code(c) => format!("```{} …```", c.lang), - } -} - -/// Best-effort ASCII formula → TeX for KaTeX in view Structure. -pub(crate) fn formula_ascii_to_tex_pub(ascii: &str) -> String { - formula_ascii_to_tex(ascii) -} - -/// Formula assign card for document surface embedding (single visual layer). -pub(crate) fn render_formula_assign_card(name: &str, tex: &str) -> String { - format!( - r#"
          -
          formula {name}
          -
          $${tex}$$
          -
          "#, - name = escape(name), - tex = escape(tex), - ) -} - -/// Foreign code assign card for document surface embedding (single visual layer). -/// Head → body → foot(actions) so the source is never collapsed under the Run row. -pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> String { - let placeholder = escape(&crate::foreign::default_cmd_display(lang)); - format!( - r#"
          -
          - code - {name} - {lang} - - -
          -
          {src}
          -
          -
          - - -
          -
          - -
          "#, - lang = escape(lang), - name = escape(name), - placeholder = placeholder, - src = escape(source), - ) -} - -fn formula_ascii_to_tex(ascii: &str) -> String { - let mut out = String::new(); - let chars: Vec = ascii.chars().collect(); - let mut i = 0usize; - while i < chars.len() { - let c = chars[i]; - if c == '*' { - // multiplication: a*b → a \cdot b - out.push_str(r" \cdot "); - i += 1; - continue; - } - if c == '^' { - out.push('^'); - i += 1; - if i < chars.len() && chars[i] == '(' { - out.push('{'); - i += 1; - let start = i; - let mut depth = 1i32; - while i < chars.len() && depth > 0 { - match chars[i] { - '(' => depth += 1, - ')' => depth -= 1, - _ => {} - } - if depth > 0 { - i += 1; - } - } - out.push_str(&chars[start..i].iter().collect::()); - if i < chars.len() && chars[i] == ')' { - i += 1; - } - out.push('}'); - } else if i < chars.len() { - out.push('{'); - out.push(chars[i]); - out.push('}'); - i += 1; - } - continue; - } - // TeX specials that may appear in identifiers rarely - match c { - '{' | '}' | '%' | '&' | '#' | '$' => { - out.push('\\'); - out.push(c); - } - _ => out.push(c), - } - i += 1; - } - out -} - -fn wrap(inner: String, prec: u8, parent_prec: u8) -> String { - if prec < parent_prec { - format!("({inner})") - } else { - inner - } -} - -fn bin_sym_prec(op: BinaryOp) -> (&'static str, u8) { - match op { - BinaryOp::Or => ("or", 1), - BinaryOp::And => ("and", 2), - BinaryOp::Eq => ("==", 3), - BinaryOp::Ne => ("!=", 3), - BinaryOp::Lt => ("<", 3), - BinaryOp::Le => ("<=", 3), - BinaryOp::Gt => (">", 3), - BinaryOp::Ge => (">=", 3), - BinaryOp::Add => ("+", 4), - BinaryOp::Sub => ("-", 4), - BinaryOp::Mul => ("*", 5), - BinaryOp::Div => ("/", 5), - } -} - -fn lit_display(lit: &Literal) -> String { - match lit { - Literal::None => "None".into(), - Literal::Bool(true) => "True".into(), - Literal::Bool(false) => "False".into(), - Literal::Int(n) => n.to_string(), - Literal::Num(n) => crate::formula::format_num(*n), - Literal::Text(t) => t.clone(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::ast::{Arg, BinaryOp, CallExpr, Expr, Literal}; - - #[test] - fn expr_gt_is_surface() { - let e = Expr::Binary { - op: BinaryOp::Gt, - left: Box::new(Expr::Var("x".into())), - right: Box::new(Expr::Literal(Literal::Int(0))), - }; - assert_eq!(expr_display(&e), "`x` > 0"); - assert!(!expr_display(&e).contains("Binary")); - } - - #[test] - fn structure_keeps_comments_and_surface_expr() { - let src = include_str!("../../tests/structure/nested-call.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_structure(&module, src); - assert!(html.contains("doc-prose") || html.contains("打印一句问候"), "{html}"); - assert!(html.contains("print")); - assert!(!html.contains("Binary {")); - assert!(!html.contains("Literal(Int")); - } - - #[test] - fn comments_render_as_paragraphs() { - let src = "段首说明\n续行仍属同段\n\n下一段\n\n# main\n\n> print text=x\n"; - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_structure(&module, src); - let blocks = html.matches("doc-prose").count(); - assert!(blocks >= 2, "blank line should split comment paragraphs: {html}"); - assert!(html.contains("段首说明 续行仍属同段") || html.contains("段首说明

          ") || html.contains("段首说明")); - assert!(html.contains("下一段")); - } - - #[test] - fn comments_render_markdown_links() { - let src = "见[仓库](https://github.com/cflmy/marqdo)与 `code`\n\n# main\n\n> print text=x\n"; - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_structure(&module, src); - assert!( - html.contains("href=\"https://github.com/cflmy/marqdo\"") && html.contains(">仓库"), - "{html}" - ); - assert!(html.contains("code"), "{html}"); - assert!(!html.contains("[仓库](https://github.com/cflmy/marqdo)")); - } - - #[test] - fn collect_input_prompts_from_fixture() { - let src = include_str!("../../tests/keywords/input.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let prompts = collect_input_prompts(&module); - assert_eq!(prompts, vec!["Name:".to_string()]); - } - - #[test] - fn collect_input_prompts_absent_without_input() { - let src = include_str!("../../tests/structure/hello.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - assert!(collect_input_prompts(&module).is_empty()); - } - - #[test] - fn structure_omits_imported_lib_bodies() { - let src = "---\ntitle: t\nimport:\n text: lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n"; - let local = crate::parse::parse_source(src).unwrap(); - let html = render_module_structure(&local, src); - assert!(html.contains("doc-imports") || html.contains("lib/text.mq.md"), "{html}"); - assert!(html.contains("lib/text.mq.md"), "{html}"); - assert!(html.contains("main"), "{html}"); - assert!(!html.contains("trim"), "{html}"); - assert!(html.contains("data-line="), "{html}"); - assert_eq!(local.functions.len(), 1); - assert_eq!(local.functions[0].name, "main"); - } - - #[test] - fn structure_formula_assign_not_comment() { - let src = include_str!("../../tests/lib/math-formula.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_structure(&module, src); - assert!(html.contains("badge\">formula"), "{html}"); - assert!(html.contains("math-block"), "{html}"); - assert!(html.contains("$$"), "{html}"); - assert!( - !html.contains("comment-text\">x^2 - 2") - && !html.contains("comment-text\">

          x^2 - 2"), - "formula fence leaked into comments: {html}" - ); - } - - #[test] - fn structure_code_card() { - let src = include_str!("../../tests/lib/foreign-python.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_structure(&module, src); - assert!(html.contains("code-card"), "{html}"); - assert!(html.contains("code-run"), "{html}"); - assert!(html.contains("hello-from-python"), "{html}"); - assert!(!html.contains("python name=hi"), "{html}"); - } - - #[test] - fn formula_ascii_to_tex_pow_and_mul() { - assert_eq!(formula_ascii_to_tex("x^2 - 2"), "x^{2} - 2"); - assert_eq!(formula_ascii_to_tex("2*x"), r"2 \cdot x"); - } - - #[test] - fn structure_mode_browse_vs_debug() { - let src = include_str!("../../tests/structure/nested-call.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let browse = render_module_structure_mode(&module, src, StructureMode::Browse); - let debug = render_module_structure_mode(&module, src, StructureMode::Debug); - assert!(browse.contains("id=\"fn-"), "{browse}"); - assert!(browse.contains("document-surface"), "{browse}"); - assert!(!browse.contains("bp-gutter"), "{browse}"); - assert!(debug.contains("bp-gutter"), "{debug}"); - assert!(debug.contains("id=\"stmt-"), "{debug}"); - assert!(debug.contains("card"), "{debug}"); - } - - #[test] - fn browse_preserves_prose_unified_line() { - let src = include_str!("../../tests/markup-v03/inc-prose.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let html = render_module_structure(&module, src); - assert!(html.contains("对于输入变量"), "{html}"); - assert!(html.contains("mq-anchor"), "{html}"); - assert!(!html.contains("badge\">bind"), "{html}"); - } - - #[test] - fn function_outline_lists_nested_names() { - let src = include_str!("../../tests/structure/nested-call.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let outline = render_function_outline(&module); - assert!(outline.contains("outline-item"), "{outline}"); - assert!(outline.contains("data-fn=\"main\""), "{outline}"); - assert!(outline.contains("data-fn=\"问候\""), "{outline}"); - assert!(outline.contains("data-fn-path=\"main/问候\""), "{outline}"); - assert!(outline.contains("href=\"#fn-"), "{outline}"); - assert!(outline.contains("ol-meta\">h"), "{outline}"); - } - - #[test] - fn right_rail_has_functions_and_variables() { - let src = include_str!("../../tests/structure/hello.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let mut bind = HashMap::new(); - bind.insert( - "xs".into(), - crate::value::Value::List(vec![ - crate::value::Value::Text("a".into()), - crate::value::Value::Text("b".into()), - ]), - ); - let html = render_right_rail(&module, &render_bindings_html(&bind), ""); - assert!(html.contains("outline-rail"), "{html}"); - assert!(html.contains("Functions"), "{html}"); - assert!(html.contains("Variables"), "{html}"); - assert!(html.contains("vars-panel"), "{html}"); - assert!(html.contains("vars-card"), "{html}"); - assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}"); - } - - #[test] - fn output_card_renders_image_writeback() { - let html = render_output_card(3, "[ok]\n![](plots/a.svg)"); - assert!(html.contains("output-card-image"), "{html}"); - assert!(html.contains(r#"src="plots/a.svg""#), "{html}"); - assert!(html.contains("wb-ok") || html.contains(">ok<"), "{html}"); - let text = render_output_card(1, "plain-42"); - assert!(text.contains("output-body"), "{text}"); - assert!(!text.contains("wb-image"), "{text}"); - let src = render_writeback_source_line(4, "![marqdo-out](plots/a.svg)"); - assert!(src.contains(r#"data-wb-kind="image""#), "{src}"); - assert!(src.contains("writeback · image"), "{src}"); - } - - #[test] - fn structure_marks_inferred_params() { - let src = include_str!("../../tests/markup-v03/inc-prose.mq.md"); - let module = crate::parse::parse_source(src).unwrap(); - let add = module - .functions - .iter() - .find(|f| f.name == "加一函数") - .expect("加一函数"); - assert!(add.params.iter().any(|p| p.name == "n" && p.inferred)); - let html = render_module_structure(&module, src); - assert!( - html.contains("chip inferred") - && (html.contains(">n<") || html.contains(r#"data-param-name="n""#)), - "expected inferred chip for n: {html}" - ); - let outline = render_function_outline(&module); - assert!( - outline.contains("ol-param inferred") && outline.contains(">n<"), - "expected outline inferred param: {outline}" - ); - } - - #[test] - fn stream_panel_gated_on_llm_or_agent_import() { - let hello = crate::parse::parse_source(include_str!("../../tests/structure/hello.mq.md")) - .unwrap(); - assert!(!uses_stream_panel(&hello)); - let llm = crate::parse::parse_source(include_str!("../../tests/ext/llm-import.mq.md")).unwrap(); - assert!(uses_stream_panel(&llm)); - } - - #[test] - fn call_display_bracket_without_modifiers() { - let call = CallExpr { - callee: "parse".into(), - path: Some(vec!["json".into(), "parse".into()]), - receiver: None, - args: vec![Arg::Named { - name: "text".into(), - value: Expr::Literal(Literal::Text("{}".into())), - }], - pre_modifiers: vec![], - bracket_marked: true, - }; - let d = call_display(&call); - assert!(d.starts_with("[json.parse]"), "{d}"); - assert!(!d.starts_with("> "), "{d}"); - } - - #[test] - fn call_display_gt_when_not_bracket() { - let call = CallExpr { - callee: "print".into(), - path: None, - receiver: None, - args: vec![Arg::Named { - name: "text".into(), - value: Expr::Literal(Literal::Text("hi".into())), - }], - pre_modifiers: vec![], - bracket_marked: false, - }; - let d = call_display(&call); - assert!(d.starts_with("> print"), "{d}"); - } -} diff --git a/src/wasm_cli.rs b/src/wasm_cli.rs deleted file mode 100755 index 7b8c3b6..0000000 --- a/src/wasm_cli.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! `marqdo wasm build` — compile `marqdo-wasm` and copy artifacts for the browser host. - -use std::path::{Path, PathBuf}; -use std::process::Command; - -use anyhow::{bail, Context, Result}; - -/// Build size-optimized wasm32 artifact and copy into `out_dir`: -/// - `marqdo_wasm.wasm` -/// - `marqdo-bridge.js` (canonical host glue) -pub fn build_wasm(out_dir: &Path) -> Result<()> { - let status = Command::new("cargo") - .args([ - "build", - "-p", - "marqdo-wasm", - "--target", - "wasm32-unknown-unknown", - "--profile", - "release-wasm", - ]) - .status() - .context("failed to spawn cargo (is it on PATH?)")?; - if !status.success() { - bail!("cargo build -p marqdo-wasm --profile release-wasm failed with {status}"); - } - - let mut artifact = find_wasm_artifact()?; - std::fs::create_dir_all(out_dir) - .with_context(|| format!("create {}", out_dir.display()))?; - - if let Some(optimized) = try_wasm_opt(&artifact)? { - artifact = optimized; - } - - let dest_wasm = out_dir.join("marqdo_wasm.wasm"); - std::fs::copy(&artifact, &dest_wasm).with_context(|| { - format!( - "copy {} → {}", - artifact.display(), - dest_wasm.display() - ) - })?; - let bytes = std::fs::metadata(&dest_wasm) - .map(|m| m.len()) - .unwrap_or(0); - println!( - "wrote {} ({:.1} KiB)", - dest_wasm.display(), - bytes as f64 / 1024.0 - ); - - let bridge_src = find_bridge_js()?; - let dest_bridge = out_dir.join("marqdo-bridge.js"); - std::fs::copy(&bridge_src, &dest_bridge).with_context(|| { - format!( - "copy {} → {}", - bridge_src.display(), - dest_bridge.display() - ) - })?; - println!("wrote {}", dest_bridge.display()); - Ok(()) -} - -fn find_bridge_js() -> Result { - let mut candidates = Vec::new(); - if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") { - candidates.push( - PathBuf::from(manifest).join("crates/marqdo-wasm/js/marqdo-bridge.js"), - ); - } - candidates.push(PathBuf::from("crates/marqdo-wasm/js/marqdo-bridge.js")); - // When running from installed binary, try next to current_exe ../../… - if let Ok(exe) = std::env::current_exe() { - if let Some(root) = exe.parent().and_then(|p| p.parent()).and_then(|p| p.parent()) { - candidates.push(root.join("crates/marqdo-wasm/js/marqdo-bridge.js")); - } - } - for c in &candidates { - if c.is_file() { - return Ok(c.clone()); - } - } - bail!( - "marqdo-bridge.js not found; tried: {}", - candidates - .iter() - .map(|p| p.display().to_string()) - .collect::>() - .join(", ") - ) -} - -fn try_wasm_opt(input: &Path) -> Result> { - let which = Command::new("wasm-opt").arg("--version").output(); - let Ok(out) = which else { - return Ok(None); - }; - if !out.status.success() { - return Ok(None); - } - let tmp = input.with_extension("opt.wasm"); - let status = Command::new("wasm-opt") - .args(["-Oz", "--enable-bulk-memory"]) - .arg(input) - .arg("-o") - .arg(&tmp) - .status() - .context("wasm-opt spawn failed")?; - if !status.success() { - let status2 = Command::new("wasm-opt") - .args(["-Oz"]) - .arg(input) - .arg("-o") - .arg(&tmp) - .status() - .context("wasm-opt spawn failed")?; - if !status2.success() { - eprintln!("warning: wasm-opt failed; keeping cargo artifact"); - return Ok(None); - } - } - println!("wasm-opt: {}", tmp.display()); - Ok(Some(tmp)) -} - -fn find_wasm_artifact() -> Result { - let mut candidates = Vec::new(); - if let Ok(td) = std::env::var("CARGO_TARGET_DIR") { - candidates.push( - PathBuf::from(&td).join("wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm"), - ); - candidates.push( - PathBuf::from(td).join("wasm32-unknown-unknown/release/marqdo_wasm.wasm"), - ); - } - candidates.push(PathBuf::from( - "target/wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm", - )); - candidates.push(PathBuf::from( - "target/wasm32-unknown-unknown/release/marqdo_wasm.wasm", - )); - for c in &candidates { - if c.is_file() { - return Ok(c.clone()); - } - } - bail!( - "built wasm not found; tried: {}", - candidates - .iter() - .map(|p| p.display().to_string()) - .collect::>() - .join(", ") - ) -} diff --git a/src/workbench/analysis_cache.rs b/src/workbench/analysis_cache.rs deleted file mode 100755 index cf4c59f..0000000 --- a/src/workbench/analysis_cache.rs +++ /dev/null @@ -1,441 +0,0 @@ -//! AnalysisCache v2 (M-R5): SnapshotKey → Arc with single-flight. -//! Cache hits must reuse the compilation result, not merely a digest ticket. - -use sha2::{Digest, Sha256}; -use std::collections::{HashMap, VecDeque}; -use std::path::Path; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, OnceLock}; -use std::time::{Duration, Instant}; - -use crate::sema::Compilation; - -/// Full-project snapshot identity (design §8.1). Built from the compiler's -/// source enumeration — never a truncated `take(200)` directory listing. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct SnapshotKey { - pub project_identity: String, - pub source_digest: String, - pub compiler_version: String, -} - -impl SnapshotKey { - pub fn compute(project_root: &Path) -> Result { - let root = crate::project::ProjectRoot::new(project_root) - .map_err(|e| format!("snapshot.project: {e:#}"))?; - let files = root - .source_files() - .map_err(|e| format!("snapshot.enumerate: {e:#}"))?; - let mut h = Sha256::new(); - h.update(root.path().to_string_lossy().as_bytes()); - for p in &files { - let rel = p - .strip_prefix(root.path()) - .unwrap_or(p) - .to_string_lossy(); - h.update(rel.as_bytes()); - let meta = - std::fs::metadata(p).map_err(|e| format!("snapshot.meta {}: {e}", p.display()))?; - h.update(meta.len().to_le_bytes()); - let bytes = - std::fs::read(p).map_err(|e| format!("snapshot.read {}: {e}", p.display()))?; - h.update(&bytes); - } - let identity = root - .path() - .canonicalize() - .unwrap_or_else(|_| root.path().to_path_buf()) - .to_string_lossy() - .to_string(); - Ok(Self { - project_identity: identity, - source_digest: format!("{:x}", h.finalize()), - compiler_version: env!("CARGO_PKG_VERSION").to_string(), - }) - } - - pub fn cache_key(&self) -> String { - format!( - "{}::{}::{}", - self.project_identity, self.source_digest, self.compiler_version - ) - } -} - -struct CacheEntry { - #[allow(dead_code)] - key: SnapshotKey, - compilation: Arc, - bytes: usize, - #[allow(dead_code)] - compiled_at: Instant, -} - -struct InflightSlot { - waiters: usize, - result: Option, String>>, -} - -struct CacheState { - order: VecDeque, - entries: HashMap, - inflight: HashMap, - bytes_used: usize, - budget_bytes: usize, -} - -fn cache() -> &'static (Mutex, Condvar) { - static C: OnceLock<(Mutex, Condvar)> = OnceLock::new(); - C.get_or_init(|| { - ( - Mutex::new(CacheState { - order: VecDeque::new(), - entries: HashMap::new(), - inflight: HashMap::new(), - bytes_used: 0, - budget_bytes: default_budget_bytes(), - }), - Condvar::new(), - ) - }) -} - -fn default_budget_bytes() -> usize { - 512 * 1024 * 1024 -} - -static HITS: AtomicU64 = AtomicU64::new(0); -static MISSES: AtomicU64 = AtomicU64::new(0); -static MERGES: AtomicU64 = AtomicU64::new(0); -static COMPILE_INVOCATIONS: AtomicU64 = AtomicU64::new(0); -static EVICTIONS: AtomicU64 = AtomicU64::new(0); -static RESULT_HITS: AtomicU64 = AtomicU64::new(0); - -fn key_compiles() -> &'static Mutex> { - static K: OnceLock>> = OnceLock::new(); - K.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn estimate_bytes(c: &Compilation) -> usize { - let arts = c.semantics.artifacts.len() * 512; - let refs = c.semantics.refs.len() * 128; - let steps = c.semantics.steps.len() * 128; - let diags = c.diagnostics.len() * 64; - 4096 + arts + refs + steps + diags -} - -enum Admit { - Hit(Arc), - Wait, - Lead, -} - -fn admit(key: &str) -> Admit { - let (lock, _cv) = cache(); - let mut g = lock.lock().unwrap(); - if let Some(e) = g.entries.get(key) { - let arc = Arc::clone(&e.compilation); - if let Some(pos) = g.order.iter().position(|k| k == key) { - g.order.remove(pos); - } - g.order.push_back(key.to_string()); - HITS.fetch_add(1, Ordering::Relaxed); - RESULT_HITS.fetch_add(1, Ordering::Relaxed); - return Admit::Hit(arc); - } - if g.inflight.contains_key(key) { - if let Some(slot) = g.inflight.get_mut(key) { - slot.waiters += 1; - } - MERGES.fetch_add(1, Ordering::Relaxed); - return Admit::Wait; - } - g.inflight.insert( - key.to_string(), - InflightSlot { - waiters: 0, - result: None, - }, - ); - MISSES.fetch_add(1, Ordering::Relaxed); - Admit::Lead -} - -fn wait_for(key: &str, deadline: Instant) -> Result, String> { - let (lock, cv) = cache(); - let mut g = lock.lock().unwrap(); - loop { - if let Some(e) = g.entries.get(key) { - let arc = Arc::clone(&e.compilation); - if let Some(slot) = g.inflight.get_mut(key) { - slot.waiters = slot.waiters.saturating_sub(1); - if slot.waiters == 0 { - g.inflight.remove(key); - } - } - HITS.fetch_add(1, Ordering::Relaxed); - RESULT_HITS.fetch_add(1, Ordering::Relaxed); - return Ok(arc); - } - if let Some(slot) = g.inflight.get(key) { - if let Some(res) = &slot.result { - let out = res.clone(); - let waiters = slot.waiters.saturating_sub(1); - if let Some(slot) = g.inflight.get_mut(key) { - slot.waiters = waiters; - if slot.waiters == 0 { - g.inflight.remove(key); - } - } - HITS.fetch_add(1, Ordering::Relaxed); - RESULT_HITS.fetch_add(1, Ordering::Relaxed); - return out; - } - } else { - // Leader finished without leaving a result — retry admit. - return Err("analysis.retry".into()); - } - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - if let Some(slot) = g.inflight.get_mut(key) { - slot.waiters = slot.waiters.saturating_sub(1); - if slot.waiters == 0 && slot.result.is_none() { - g.inflight.remove(key); - } - } - return Err("analysis.wait_deadline".into()); - } - let (guard, timeout) = cv.wait_timeout(g, remaining).unwrap(); - g = guard; - if timeout.timed_out() { - if let Some(slot) = g.inflight.get_mut(key) { - slot.waiters = slot.waiters.saturating_sub(1); - if slot.waiters == 0 && slot.result.is_none() { - g.inflight.remove(key); - } - } - return Err("analysis.wait_deadline".into()); - } - } -} - -fn finish_leader(key: &str, snap: SnapshotKey, compiled: Result, String>) { - if compiled.is_ok() { - let mut kc = key_compiles().lock().unwrap(); - *kc.entry(key.to_string()).or_insert(0) += 1; - } - let (lock, cv) = cache(); - let mut g = lock.lock().unwrap(); - if let Ok(ref arc) = compiled { - insert_entry(&mut g, snap, Arc::clone(arc)); - } - if let Some(slot) = g.inflight.get_mut(key) { - slot.result = Some(compiled); - if slot.waiters == 0 { - g.inflight.remove(key); - } - } - cv.notify_all(); -} - -/// Compile once per SnapshotKey; followers await the same Arc. -pub fn get_or_compile(project_root: &Path) -> Result, String> { - let snap = SnapshotKey::compute(project_root)?; - let key = snap.cache_key(); - let deadline = Instant::now() + Duration::from_secs(300); - loop { - match admit(&key) { - Admit::Hit(arc) => return Ok(arc), - Admit::Wait => match wait_for(&key, deadline) { - Err(e) if e == "analysis.retry" => continue, - other => return other, - }, - Admit::Lead => { - let compiled = compile_leader(project_root); - COMPILE_INVOCATIONS.fetch_add(1, Ordering::Relaxed); - let out = compiled.clone(); - finish_leader(&key, snap, compiled); - return out; - } - } - } -} - -fn compile_leader(project_root: &Path) -> Result, String> { - let options = crate::sema::CompileOptions::for_path(project_root) - .map_err(|e| format!("view.compile_failed: {e:#}"))?; - let c = crate::sema::compile_project(&options) - .map_err(|e| format!("view.compile_failed: {e:#}"))?; - Ok(Arc::new(c)) -} - -fn insert_entry(g: &mut CacheState, key: SnapshotKey, compilation: Arc) { - let ck = key.cache_key(); - let bytes = estimate_bytes(&compilation); - while g.bytes_used + bytes > g.budget_bytes && !g.order.is_empty() { - if let Some(old) = g.order.pop_front() { - if let Some(e) = g.entries.remove(&old) { - g.bytes_used = g.bytes_used.saturating_sub(e.bytes); - EVICTIONS.fetch_add(1, Ordering::Relaxed); - } - } - } - if bytes > g.budget_bytes || g.entries.contains_key(&ck) { - return; - } - g.bytes_used += bytes; - g.order.push_back(ck.clone()); - g.entries.insert( - ck, - CacheEntry { - key, - compilation, - bytes, - compiled_at: Instant::now(), - }, - ); -} - -pub fn project_source_digest(project_root: &Path) -> String { - SnapshotKey::compute(project_root) - .map(|k| k.source_digest) - .unwrap_or_else(|_| "digest-error".into()) -} - -fn project_key(project_root: &Path) -> String { - project_root - .canonicalize() - .unwrap_or_else(|_| project_root.to_path_buf()) - .to_string_lossy() - .to_string() -} - -pub struct AnalysisTicket { - #[allow(dead_code)] - key: String, - #[allow(dead_code)] - digest: String, - pub is_leader: bool, -} - -pub fn begin_analysis(project_root: &Path) -> AnalysisTicket { - match get_or_compile(project_root) { - Ok(_) => AnalysisTicket { - key: project_key(project_root), - digest: project_source_digest(project_root), - is_leader: false, - }, - Err(_) => AnalysisTicket { - key: project_key(project_root), - digest: String::new(), - is_leader: true, - }, - } -} - -pub fn finish_analysis(_ticket: AnalysisTicket) {} - -pub fn note_analysis(project_root: &Path) -> bool { - // True iff this SnapshotKey was already cached (result hit), independent of - // other projects compiled concurrently in the same process. - let before = compile_count_for(project_root); - let _ = get_or_compile(project_root); - let after = compile_count_for(project_root); - after == before && before > 0 -} - -pub fn cache_keys_isolated(a: &Path, b: &Path) -> bool { - project_key(a) != project_key(b) -} - -pub fn cache_stats() -> (u64, u64, u64) { - ( - HITS.load(Ordering::Relaxed), - MISSES.load(Ordering::Relaxed), - MERGES.load(Ordering::Relaxed), - ) -} - -pub fn compile_invocations() -> u64 { - COMPILE_INVOCATIONS.load(Ordering::Relaxed) -} - -/// Successful compile count for one SnapshotKey (M-R5 / MR-06). -pub fn compile_count_for(project_root: &Path) -> u64 { - let Ok(snap) = SnapshotKey::compute(project_root) else { - return 0; - }; - key_compiles() - .lock() - .unwrap() - .get(&snap.cache_key()) - .copied() - .unwrap_or(0) -} - -pub fn result_hits() -> u64 { - RESULT_HITS.load(Ordering::Relaxed) -} - -pub fn eviction_count() -> u64 { - EVICTIONS.load(Ordering::Relaxed) -} - -pub fn reset_cache_for_tests() { - let (lock, cv) = cache(); - let mut g = lock.lock().unwrap(); - g.entries.clear(); - g.order.clear(); - g.inflight.clear(); - g.bytes_used = 0; - HITS.store(0, Ordering::Relaxed); - MISSES.store(0, Ordering::Relaxed); - MERGES.store(0, Ordering::Relaxed); - COMPILE_INVOCATIONS.store(0, Ordering::Relaxed); - EVICTIONS.store(0, Ordering::Relaxed); - RESULT_HITS.store(0, Ordering::Relaxed); - key_compiles().lock().unwrap().clear(); - cv.notify_all(); -} - -/// Serialize tests that call [`reset_cache_for_tests`] so parallel suites cannot -/// clear another test's SnapshotKey mid-flight. Recovers from poison so one -/// failing cache test does not brick the rest of the suite. -pub fn test_serial_guard() -> std::sync::MutexGuard<'static, ()> { - static G: OnceLock> = OnceLock::new(); - let m = G.get_or_init(|| Mutex::new(())); - m.lock().unwrap_or_else(|p| p.into_inner()) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::{Arc, Barrier}; - use std::thread; - - #[test] - fn same_snapshot_compiles_once_under_load() { - let _g = test_serial_guard(); - reset_cache_for_tests(); - let root = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests/executable_knowledge/baseline/02-extract"); - let n = 32usize; - let barrier = Arc::new(Barrier::new(n)); - let mut handles = Vec::with_capacity(n); - for _ in 0..n { - let barrier = Arc::clone(&barrier); - let root = root.clone(); - handles.push(thread::spawn(move || { - barrier.wait(); - get_or_compile(&root).expect("compile") - })); - } - let first = handles.pop().unwrap().join().unwrap(); - for h in handles { - let arc = h.join().unwrap(); - assert!(Arc::ptr_eq(&first, &arc), "followers must share the same Arc"); - } - assert_eq!(compile_count_for(&root), 1); - assert_eq!(compile_invocations(), 1); - } -} diff --git a/src/workbench/capabilities.rs b/src/workbench/capabilities.rs deleted file mode 100755 index 3f1ddce..0000000 --- a/src/workbench/capabilities.rs +++ /dev/null @@ -1,256 +0,0 @@ -//! MLSP `capabilities` — probe loaded plugins and declared features (M00 / F16). -//! Feature integers must reflect *implemented and testable* behavior only. - -use serde_json::{json, Value}; -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; - -/// Host/tests may force stream/cancel off for honesty / F16 mismatch cases. -static FORCE_STREAM_OFF: AtomicBool = AtomicBool::new(false); -static FORCE_CANCEL_OFF: AtomicBool = AtomicBool::new(false); - -pub fn set_event_stream_ready(ready: bool) { - FORCE_STREAM_OFF.store(!ready, Ordering::Relaxed); -} - -pub fn set_cancel_ready(ready: bool) { - FORCE_CANCEL_OFF.store(!ready, Ordering::Relaxed); -} - -/// Build the capabilities document. Does not call providers or execute project code. -pub fn probe_capabilities(params: &Value) -> Value { - let runtime_version = env!("CARGO_PKG_VERSION").to_string(); - let mut adapters = vec![json!({ - "id": "openai-compatible", - "available": true, - "notes": "HTTP chat completions; messages[] preferred over single prompt" - })]; - adapters.push(json!({ - "id": "ollama-compatible", - "available": true, - "notes": "OpenAI-compatible path; not a distinct native protocol" - })); - adapters.push(json!({ - "id": "anthropic-native", - "available": false, - "notes": "not verified in this release" - })); - adapters.push(json!({ - "id": "gemini-native", - "available": false, - "notes": "not verified in this release" - })); - - let extract_formats = vec![ - json!({"format": "text", "available": true}), - json!({"format": "markdown", "available": true}), - json!({"format": "pdf", "available": false}), - json!({"format": "docx", "available": false}), - json!({"format": "ocr", "available": false}), - // M-A0 freeze: format matrix rows remain unavailable until M-A3/M-A5. - json!({"format": "json", "available": true}), - json!({"format": "csv", "available": true}), - json!({"format": "image", "available": false}), - json!({"format": "html", "available": false}), - json!({"format": "svg", "available": false}), - json!({"format": "xlsx", "available": false}), - json!({"format": "pptx", "available": false}), - ]; - - let loaded_plugins = probe_loaded_plugins(params); - - let llm_loaded = loaded_plugins.iter().any(|p| { - p.get("name").and_then(|n| n.as_str()) == Some("llm") - && p.get("available").and_then(|a| a.as_bool()) == Some(true) - }); - - let stream_off = FORCE_STREAM_OFF.load(Ordering::Relaxed) - || params - .get("force_stream_off") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let cancel_off = FORCE_CANCEL_OFF.load(Ordering::Relaxed) - || params - .get("force_cancel_off") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - let mut features = serde_json::Map::new(); - features.insert( - "llm.explicit_selection".into(), - json!(if llm_loaded { 1 } else { 0 }), - ); - features.insert( - "llm.call_usage".into(), - json!(if llm_loaded { 1 } else { 0 }), - ); - features.insert( - "llm.messages".into(), - json!(if llm_loaded { 1 } else { 0 }), - ); - // M02 implemented: event_sink + web sse-live + MARQDO_CANCEL in llm plugin. - features.insert( - "runtime.event_stream".into(), - json!(if stream_off { 0 } else { 1 }), - ); - features.insert( - "runtime.cancel".into(), - json!(if cancel_off { 0 } else { 1 }), - ); - // Isolated web runtime (doc/design/isolated-web-runtime-development-2026-10-26.md). - // HTTP execute / sse-live defaults to the Supervisor worker pool (ADR 0009). - features.insert("runtime.isolated_execution".into(), json!(1)); - // task_control_v2 / event_replay: host_query("runtime") + /_runtime/* system routes. - features.insert("runtime.task_control_v2".into(), json!(1)); - features.insert("runtime.event_replay".into(), json!(1)); - // short/read/control HTTP invokes use isolated admission (no parent INVOKE_LOCK). - features.insert("runtime.read_lane".into(), json!(1)); - #[cfg(feature = "view")] - { - features.insert("view.analysis_cache_v2".into(), json!(1)); - features.insert("view.document".into(), json!(1)); - features.insert("view.reference_resolve".into(), json!(1)); - } - #[cfg(not(feature = "view"))] - { - features.insert("view.analysis_cache_v2".into(), json!(0)); - features.insert("view.document".into(), json!(0)); - features.insert("view.reference_resolve".into(), json!(0)); - } - // M-A0–M-A4: protocol capability bits. - features.insert("agent.error_v1".into(), json!(1)); - features.insert("agent.checkpoint_v2".into(), json!(1)); - features.insert("agent.tool_schema_v1".into(), json!(1)); - features.insert("agent.output_channels_v1".into(), json!(1)); - features.insert("agent.context_pack_v2".into(), json!(1)); - #[cfg(feature = "view")] - { - features.insert("resource.view_v1".into(), json!(1)); - } - #[cfg(not(feature = "view"))] - { - features.insert("resource.view_v1".into(), json!(0)); - } - - json!({ - "schema_version": 1, - "runtime_version": runtime_version, - "features": features, - "adapters": adapters, - "extract_formats": extract_formats, - "loaded_plugins": loaded_plugins, - "contracts": [ - "ModelSelectionV1", - "ModelCallUsageV1", - "RuntimeEventV1", - "RuntimeEventV2", - "InvokeRequestV2", - "DocumentViewV1", - "KnowledgeLocatorV1" - ] - }) -} - -fn probe_loaded_plugins(params: &Value) -> Vec { - let mut out = Vec::new(); - let candidates = [ - ("llm", "MARQDO_LLM_PLUGIN", plugin_name("llm")), - ("agent", "MARQDO_AGENT_PLUGIN", plugin_name("agent")), - ("web", "MARQDO_WEB_PLUGIN", plugin_name("web")), - ]; - let ext_hint = params - .get("ext_root") - .and_then(|v| v.as_str()) - .map(PathBuf::from) - .or_else(|| std::env::var_os("MARQDO_EXT").map(PathBuf::from)); - - let force_unloaded = params - .get("force_unloaded") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - for (name, env_key, filename) in candidates { - if force_unloaded { - out.push(json!({ - "name": name, - "available": false, - "path": Value::Null, - "capabilities": [], - })); - continue; - } - let mut path: Option = std::env::var_os(env_key).map(PathBuf::from); - if path.as_ref().map(|p| !p.is_file()).unwrap_or(true) { - let debug = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("target") - .join("debug") - .join(&filename); - if debug.is_file() { - path = Some(debug); - } - } - if path.as_ref().map(|p| !p.is_file()).unwrap_or(true) { - if let Some(ext) = &ext_hint { - let native = ext.join("native").join(&filename); - if native.is_file() { - path = Some(native); - } - } - } - let available = path.as_ref().map(|p| p.is_file()).unwrap_or(false); - let mut caps = Vec::new(); - if name == "llm" && available { - caps.push("call_usage_v1"); - caps.push("messages_v1"); - caps.push("explicit_selection_v1"); - caps.push("cancel_v1"); - } - if name == "agent" && available { - caps.push("eng_bind_execute"); - caps.push("publish_gate"); - } - out.push(json!({ - "name": name, - "available": available, - "path": path.map(|p| p.to_string_lossy().to_string()), - "capabilities": caps, - })); - } - out -} - -fn plugin_name(stem: &str) -> String { - if cfg!(windows) { - format!("{stem}.dll") - } else if cfg!(target_os = "macos") { - format!("lib{stem}.dylib") - } else { - format!("lib{stem}.so") - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn force_off_and_unloaded_honest() { - let caps = probe_capabilities(&json!({ - "force_unloaded": true, - "force_stream_off": true, - "force_cancel_off": true, - })); - assert_eq!(caps["features"]["runtime.event_stream"], 0); - assert_eq!(caps["features"]["runtime.cancel"], 0); - assert_eq!(caps["features"]["llm.messages"], 0); - assert_eq!(caps["features"]["agent.error_v1"], 1); - assert_eq!(caps["features"]["agent.checkpoint_v2"], 1); - assert_eq!(caps["features"]["agent.tool_schema_v1"], 1); - assert_eq!(caps["features"]["agent.output_channels_v1"], 1); - assert_eq!(caps["features"]["agent.context_pack_v2"], 1); - #[cfg(feature = "view")] - assert_eq!(caps["features"]["resource.view_v1"], 1); - #[cfg(not(feature = "view"))] - assert_eq!(caps["features"]["resource.view_v1"], 0); - } -} diff --git a/src/workbench/document_view.rs b/src/workbench/document_view.rs deleted file mode 100755 index e7ca796..0000000 --- a/src/workbench/document_view.rs +++ /dev/null @@ -1,478 +0,0 @@ -//! DocumentViewV1 — read-only embedded view (M03). Never executes the document. - -use std::fs; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; - -use crate::view::{render_knowledge_html, render_module_document, KnowledgePresentation}; - -#[derive(Debug, Clone)] -pub struct DocumentViewRequest { - pub project: PathBuf, - pub document: String, - pub revision: Option, - pub generation: Option, - pub node_id: Option, - pub include: Vec, -} - -impl DocumentViewRequest { - pub fn from_params(params: &Value) -> Result { - let project = params - .get("project") - .and_then(|v| v.as_str()) - .ok_or_else(|| "view.document requires params.project".to_string())?; - let document = params - .get("document") - .and_then(|v| v.as_str()) - .ok_or_else(|| "view.document requires params.document".to_string())?; - let mode = params - .get("mode") - .and_then(|v| v.as_str()) - .unwrap_or("read"); - if mode != "read" { - return Err(format!("view.document unsupported mode={mode}; only read")); - } - let include = match params.get("include") { - Some(Value::Array(a)) => a - .iter() - .filter_map(|v| v.as_str().map(|s| s.to_string())) - .collect(), - _ => vec![ - "fragment".into(), - "outline".into(), - "nodes".into(), - "refs".into(), - "diagnostics".into(), - ], - }; - Ok(Self { - project: PathBuf::from(project), - document: document.to_string(), - revision: params - .get("revision") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - generation: params - .get("generation") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - node_id: params - .get("node_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - include, - }) - } -} - -/// Pure read path: compile_project (no plugin load / no eval) + fragment render. -/// Must never call `build_file_view` with execute=true. -pub fn build_document_view(req: &DocumentViewRequest) -> Result { - let project_root = canonicalize_project(&req.project)?; - let abs = resolve_under(&project_root, &req.document)?; - let raw = fs::read(&abs).map_err(|e| { - err( - "view.document_read_failed", - format!("cannot read {}: {e}", abs.display()), - ) - })?; - let source_revision = format!("sha256:{:x}", Sha256::digest(&raw)); - if let Some(expected) = &req.revision { - if expected != &source_revision && !expected.is_empty() { - return Err(err( - "view.revision_mismatch", - format!("requested {expected} but file is {source_revision}; refusing silent downgrade"), - )); - } - } - let source = String::from_utf8_lossy(&raw).into_owned(); - let title = title_from_source(&source, &req.document); - - // Semantic projection — compile_project does not load plugins / evaluate. - // M-R5: Arc single-flight cache; followers reuse the same result. - let compilation = crate::workbench::analysis_cache::get_or_compile(&project_root) - .map_err(|e| err("view.compile_failed", e))?; - - let rel = req.document.replace('\\', "/"); - let mut presentation = KnowledgePresentation::from_project(&compilation.semantics, &rel, &title); - presentation.page_token = { - let mut h = Sha256::new(); - h.update(raw.as_slice()); - h.update(presentation.semantic_generation.as_bytes()); - format!("{:x}", h.finalize()) - }; - - if let Some(gen) = &req.generation { - if !gen.is_empty() && gen != &presentation.semantic_generation { - return Err(err( - "view.generation_mismatch", - format!( - "requested generation {gen} but projection is {}; refusing silent downgrade", - presentation.semantic_generation - ), - )); - } - } - - let wants = |k: &str| req.include.iter().any(|x| x == k); - - let heading_outline = outline_from_headings(&source, &presentation); - - // Prefer document surface HTML when parseable; fall back to knowledge HTML. - // Never call build_file_view (that path executes). - let fragment = if wants("fragment") { - let raw_html = match crate::load::parse_source_auto(&source) { - Ok(module) => render_module_document(&module, &source, &[]), - Err(_) => render_knowledge_html(&compilation.semantics, &rel), - }; - wrap_fragment(&inject_mq_node_attrs(&raw_html, &heading_outline, &presentation)) - } else { - String::new() - }; - - let outline = if wants("outline") { - if heading_outline.is_empty() { - outline_from_presentation(&presentation) - } else { - json!(heading_outline) - } - } else { - json!([]) - }; - let nodes = if wants("nodes") { - nodes_from_presentation_and_steps( - &presentation, - &compilation.semantics, - &rel, - &req.node_id, - ) - } else { - json!([]) - }; - let refs = if wants("refs") { - refs_from_project(&compilation.semantics, &rel) - } else { - json!([]) - }; - - let mut diag_msgs: Vec = presentation.diagnostics.clone(); - for d in &compilation.diagnostics { - diag_msgs.push(d.message.clone()); - } - let diagnostics = if wants("diagnostics") { - json!(diag_msgs) - } else { - json!([]) - }; - - let completeness = if diag_msgs.is_empty() { - "complete" - } else { - "partial" - }; - - let snapshot = crate::workbench::snapshot::build_snapshot_manifest( - &project_root, - &rel, - &raw, - &compilation.semantics, - "1", - ); - - Ok(json!({ - "schema": "DocumentViewV1", - "schema_version": 1, - "document": { - "id": rel, - "title": title, - "source_revision": source_revision, - "semantic_digest": presentation.source_digest, - "generation_id": if presentation.semantic_generation.is_empty() { - Value::Null - } else { - json!(presentation.semantic_generation) - }, - "presentation_token": presentation.page_token, - }, - "execution": {"state": "not_run", "run_id": Value::Null}, - "render": { - "format": "sanitized_html", - "fragment": fragment, - "renderer_version": "1" - }, - "outline": outline, - "nodes": nodes, - "refs": refs, - "diagnostics": diagnostics, - "completeness": completeness, - "snapshot": snapshot, - "capabilities": {"read_only": true, "has_semantics": true, "executed": false} - })) -} - -fn wrap_fragment(inner: &str) -> String { - // No html/body, no scripts, namespaced for host theming. - let sanitized = strip_script_tags(inner); - format!("

          {sanitized}
          ") -} - -/// Remove `` blocks (case-insensitive) so embed fragments stay non-executable. -fn strip_script_tags(html: &str) -> String { - let lower = html.to_ascii_lowercase(); - let mut out = String::with_capacity(html.len()); - let mut i = 0usize; - while i < html.len() { - if lower[i..].starts_with("') - .map(|p| i + p + 1) - .unwrap_or(html.len()); - if let Some(rel) = lower[after_open..].find("') - .map(|p| close_at + p + 1) - .unwrap_or(html.len()); - i = end; - } else { - // Truncate from the dangerous open tag onward. - break; - } - continue; - } - // Advance one UTF-8 char so multi-byte text stays intact. - let ch = html[i..].chars().next().unwrap(); - out.push(ch); - i += ch.len_utf8(); - } - out -} - -fn title_from_source(source: &str, fallback: &str) -> String { - for line in source.lines().take(40) { - let t = line.trim(); - if let Some(rest) = t.strip_prefix("# ") { - return rest.trim().to_string(); - } - if let Some(rest) = t.strip_prefix("title:") { - return rest.trim().trim_matches('"').to_string(); - } - } - Path::new(fallback) - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or(fallback) - .to_string() -} - -/// Outline entries from Markdown / Marqdo `#` headings; prefer matching node ids. -fn outline_from_headings(source: &str, p: &KnowledgePresentation) -> Vec { - let mut items = Vec::new(); - let mut order = 0usize; - for (idx, line) in source.lines().enumerate() { - let line_no = (idx + 1) as u32; - let trimmed = line.trim_start(); - if !trimmed.starts_with('#') { - continue; - } - let hashes = trimmed.chars().take_while(|c| *c == '#').count(); - if hashes == 0 || hashes > 6 { - continue; - } - // `# Title`, `## Section`, or Marqdo `#main` / `##greet` (no space). - let after = &trimmed[hashes..]; - let label = after.trim(); - if label.is_empty() { - continue; - } - let matched = p.nodes.iter().find(|n| { - n.source_line == line_no - || n.display_name == label - || n.node_id == label - || n.artifact_id.as_deref() == Some(label) - }); - let id = matched - .map(|n| n.node_id.clone()) - .unwrap_or_else(|| format!("heading:{line_no}")); - let artifact_id = matched.and_then(|n| n.artifact_id.clone()); - items.push(json!({ - "id": id, - "parent_id": Value::Null, - "kind": "heading", - "label": label, - "order": order, - "source_span": {"line": line_no}, - "artifact_id": artifact_id, - })); - order += 1; - } - items -} - -/// Stamp `data-mq-node` onto elements that already carry `data-line` matching a node/outline id. -fn inject_mq_node_attrs(html: &str, outline: &[Value], p: &KnowledgePresentation) -> String { - let mut out = html.to_string(); - let mut bindings: Vec<(u32, String)> = Vec::new(); - for n in &p.nodes { - bindings.push((n.source_line, n.node_id.clone())); - } - for item in outline { - if let (Some(line), Some(id)) = ( - item.pointer("/source_span/line").and_then(|v| v.as_u64()), - item.get("id").and_then(|v| v.as_str()), - ) { - bindings.push((line as u32, id.to_string())); - } - } - bindings.sort_by_key(|(line, _)| *line); - bindings.dedup_by_key(|(line, _)| *line); - for (line, id) in bindings { - let needle = format!("data-line=\"{line}\""); - let attr = format!("data-line=\"{line}\" data-mq-node=\"{}\"", html_attr_escape(&id)); - if out.contains(&needle) && !out.contains(&format!("data-mq-node=\"{}\"", html_attr_escape(&id))) { - out = out.replacen(&needle, &attr, 1); - } - } - out -} - -fn html_attr_escape(s: &str) -> String { - s.replace('&', "&") - .replace('"', """) - .replace('<', "<") -} - -fn outline_from_presentation(p: &KnowledgePresentation) -> Value { - json!(p - .nodes - .iter() - .enumerate() - .map(|(i, n)| json!({ - "id": n.node_id, - "parent_id": Value::Null, - "kind": "heading", - "label": n.display_name, - "order": i, - "artifact_id": n.artifact_id, - })) - .collect::>()) -} - -fn nodes_from_presentation_and_steps( - p: &KnowledgePresentation, - project: &crate::sema::SemanticProject, - rel: &str, - filter: &Option, -) -> Value { - let mut out = Vec::new(); - for n in &p.nodes { - if filter - .as_ref() - .map(|f| &n.node_id == f || n.artifact_id.as_ref() == Some(f)) - .unwrap_or(true) - { - out.push(json!({ - "id": n.node_id, - "parent_id": Value::Null, - "kind": n.kind, - "label": n.display_name, - "order": n.source_line, - "source_span": {"file": n.source_file, "line": n.source_line}, - "artifact_id": n.artifact_id, - "ref_ids": [], - "children": [], - "evidence": n.evidence, - "effects": n.effects, - "dependencies": n.dependencies, - "signature": n.signature, - })); - } - } - // F09: project KnowledgeStep kinds (observe/derive/call/iterate/…) into the read model. - for step in &project.steps { - if step.source.file != rel { - continue; - } - let id = step.id.0.clone(); - if filter - .as_ref() - .map(|f| &id == f || &step.reference == f) - .unwrap_or(true) - { - out.push(json!({ - "id": id, - "parent_id": Value::Null, - "kind": step.kind, - "label": step.reference, - "order": step.source.line, - "source_span": { - "file": step.source.file, - "line": step.source.line, - "end_line": step.source.end_line - }, - "artifact_id": Value::Null, - "ref_ids": step.calls.iter().map(|c| c.as_str()).collect::>(), - "children": [], - "evidence": "unverified", - "effects": step.effects.values(), - })); - } - } - json!(out) -} - -fn refs_from_project(project: &crate::sema::SemanticProject, rel: &str) -> Value { - let mut refs = Vec::new(); - for a in &project.artifacts { - if a.source.file != rel { - continue; - } - for dep in &a.dependencies { - refs.push(json!({ - "id": format!("ref:{}:{}", a.artifact_id.0, dep.0), - "from_artifact_id": a.artifact_id.0, - "to": dep.0, - "relation": "depends_on", - })); - } - } - json!(refs) -} - -fn canonicalize_project(p: &Path) -> Result { - let root = if p.is_file() { - p.parent().unwrap_or_else(|| Path::new(".")).to_path_buf() - } else { - p.to_path_buf() - }; - root.canonicalize().map_err(|e| { - err( - "view.project_invalid", - format!("project {}: {e}", root.display()), - ) - }) -} - -fn resolve_under(root: &Path, rel: &str) -> Result { - let joined = root.join(rel); - let canon = joined.canonicalize().map_err(|e| { - err( - "view.document_not_found", - format!("{}: {e}", joined.display()), - ) - })?; - if !canon.starts_with(root) { - return Err(err( - "view.path_escape", - "document path escapes project root", - )); - } - Ok(canon) -} - -fn err(code: &str, message: impl Into) -> Value { - json!({"code": code, "message": message.into()}) -} diff --git a/src/workbench/event_sink.rs b/src/workbench/event_sink.rs deleted file mode 100755 index 9b7acf2..0000000 --- a/src/workbench/event_sink.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! Request-local RuntimeEventV1 sink (M02). Avoids process-global event mix-up. - -use serde_json::{json, Value}; -use std::fs::OpenOptions; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; - -static SEQ: AtomicU64 = AtomicU64::new(0); - -fn sink_path() -> &'static Mutex> { - static SINK: OnceLock>> = OnceLock::new(); - SINK.get_or_init(|| Mutex::new(None)) -} - -/// Bind this process/request to an NDJSON event file (also used by web sse-live). -pub fn bind_event_sink(path: impl AsRef) { - if let Ok(mut g) = sink_path().lock() { - *g = Some(path.as_ref().to_path_buf()); - } - crate::workbench::capabilities::set_event_stream_ready(true); -} - -pub fn clear_event_sink() { - if let Ok(mut g) = sink_path().lock() { - *g = None; - } -} - -pub fn emit_event(run_id: &str, event_type: &str, payload: Value) -> Value { - let seq = SEQ.fetch_add(1, Ordering::Relaxed); - let event_id = format!("evt-{run_id}-{seq}"); - let ev = crate::workbench::usage::runtime_event(&event_id, seq, run_id, event_type, payload); - if let Ok(g) = sink_path().lock() { - if let Some(path) = g.as_ref() { - if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(path) { - let _ = writeln!(f, "{}", ev); - } - } - } - // Also honor MARQDO_EVENT_FORWARD for subtask/web bridge. - if let Ok(fwd) = std::env::var("MARQDO_EVENT_FORWARD") { - if !fwd.is_empty() { - if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&fwd) { - let _ = writeln!(f, "{}", ev); - } - } - } - ev -} - -pub fn emit_message_delta(run_id: &str, text: &str) -> Value { - emit_event( - run_id, - "message.delta", - json!({"text": text, "format": "plain"}), - ) -} diff --git a/src/workbench/locator.rs b/src/workbench/locator.rs deleted file mode 100755 index 5fc246f..0000000 --- a/src/workbench/locator.rs +++ /dev/null @@ -1,304 +0,0 @@ -//! KnowledgeLocatorV1 + view.reference_resolve (M04). - -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; - -#[derive(Debug, Clone)] -pub struct KnowledgeLocator { - pub project_id: String, - pub document_id: String, - pub source_revision: Option, - pub generation_id: Option, - pub artifact_id: Option, - pub node_id: Option, - pub source_ref_id: Option, - pub span: Option, - pub relation: String, -} - -impl KnowledgeLocator { - pub fn from_params(params: &Value) -> Result { - let loc = params.get("locator").unwrap_or(params); - Ok(Self { - project_id: loc - .get("project_id") - .or_else(|| params.get("project")) - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(), - document_id: loc - .get("document_id") - .or_else(|| params.get("document")) - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(), - source_revision: loc - .get("source_revision") - .or_else(|| loc.get("revision")) - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - generation_id: loc - .get("generation_id") - .or_else(|| loc.get("generation")) - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - artifact_id: loc - .get("artifact_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - node_id: loc - .get("node_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - source_ref_id: loc - .get("source_ref_id") - .or_else(|| loc.get("ref_id")) - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - span: loc.get("span").cloned(), - relation: loc - .get("relation") - .and_then(|v| v.as_str()) - .unwrap_or("cites") - .to_string(), - }) - } - - pub fn to_json(&self) -> Value { - json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "project_id": self.project_id, - "document_id": self.document_id, - "source_revision": self.source_revision, - "generation_id": self.generation_id, - "artifact_id": self.artifact_id, - "node_id": self.node_id, - "source_ref_id": self.source_ref_id, - "span": self.span, - "relation": self.relation, - }) - } -} - -/// Resolve a locator or current-document ref_id against a project snapshot. -/// Never silently falls back to "latest" when expected revision/generation mismatch. -pub fn resolve_reference(params: &Value) -> Result { - let locator = KnowledgeLocator::from_params(params).map_err(|e| { - json!({"code": "locator.bad_request", "message": e}) - })?; - if locator.project_id.is_empty() { - return Err(json!({ - "code": "locator.bad_request", - "message": "project_id/project required" - })); - } - let root = PathBuf::from(&locator.project_id); - let root = root.canonicalize().map_err(|e| { - json!({"code": "locator.project_invalid", "message": format!("{e}")}) - })?; - - let options = crate::sema::CompileOptions::for_path(&root).map_err(|e| { - json!({"code": "locator.compile_failed", "message": format!("{e:#}")}) - })?; - let compilation = crate::sema::compile_project(&options).map_err(|e| { - json!({"code": "locator.compile_failed", "message": format!("{e:#}")}) - })?; - - // Generation mismatch → version_unavailable / stale (no silent current). - if let Some(expected_gen) = &locator.generation_id { - if !expected_gen.is_empty() { - let current_gen = semantic_generation(&compilation.semantics); - if ¤t_gen != expected_gen { - return Ok(crate::workbench::snapshot::version_unavailable_result( - &locator.to_json(), - &format!( - "expected generation {expected_gen}, current projection is {current_gen}; refusing silent downgrade (no retained snapshot)" - ), - expected_gen, - Some(¤t_gen), - )); - } - } - } - - // Source revision check when document is known. - if let (Some(expected_rev), true) = ( - &locator.source_revision, - !locator.document_id.is_empty(), - ) { - if !expected_rev.is_empty() { - let abs = resolve_under(&root, &locator.document_id)?; - let raw = std::fs::read(&abs).map_err(|e| { - json!({"code": "locator.source_unreadable", "message": format!("{e}")}) - })?; - use sha2::{Digest, Sha256}; - let actual = format!("sha256:{:x}", Sha256::digest(&raw)); - if &actual != expected_rev { - return Ok(json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "resolution": "stale", - "precision": "document", - "locator": locator.to_json(), - "target": { - "document_id": locator.document_id, - "source_revision": actual, - "note": "source changed since citation" - }, - "candidates": [], - "diagnostics": [{ - "code": "source_revision_mismatch", - "message": format!("expected {expected_rev}, actual {actual}") - }], - "label": "该来源已变化" - })); - } - } - } - - let query = locator - .artifact_id - .clone() - .or_else(|| locator.node_id.clone()) - .or_else(|| locator.source_ref_id.clone()); - - let Some(q) = query else { - if locator.document_id.is_empty() { - return Ok(json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "resolution": "unresolved", - "precision": "none", - "locator": locator.to_json(), - "target": Value::Null, - "candidates": [], - "diagnostics": [{"code": "missing_target", "message": "no artifact/node/ref id"}], - "label": "无法定位该知识" - })); - } - return Ok(json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "resolution": "resolved", - "precision": "document", - "locator": locator.to_json(), - "target": { - "document_id": locator.document_id, - "relation": locator.relation, - }, - "candidates": [], - "diagnostics": [], - "label": locator.document_id, - })); - }; - - let mut matches: Vec<&crate::sema::SemanticArtifact> = compilation - .semantics - .artifacts - .iter() - .filter(|a| { - a.artifact_id.0 == q - || a.display_name == q - || a.symbol_id - .as_ref() - .map(|s| s.as_str() == q) - .unwrap_or(false) - }) - .collect(); - - if !locator.document_id.is_empty() { - let scoped: Vec<_> = matches - .iter() - .copied() - .filter(|a| a.source.file == locator.document_id) - .collect(); - if !scoped.is_empty() { - matches = scoped; - } - } - - match matches.len() { - 0 => Ok(json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "resolution": "unresolved", - "precision": "none", - "locator": locator.to_json(), - "target": Value::Null, - "candidates": [], - "diagnostics": [{"code": "not_found", "message": format!("no artifact matching {q}")}], - "label": "尚未定位到具体知识" - })), - 1 => { - let a = matches[0]; - Ok(json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "resolution": "resolved", - "precision": "artifact", - "locator": locator.to_json(), - "target": { - "artifact_id": a.artifact_id.0, - "display_name": a.display_name, - "document_id": a.source.file, - "span": {"line": a.source.line, "end_line": a.source.end_line}, - "evidence": a.verification.evidence, - "relation": locator.relation, - }, - "candidates": [], - "diagnostics": [], - "label": a.display_name, - })) - } - _ => { - let candidates: Vec = matches - .iter() - .map(|a| { - json!({ - "artifact_id": a.artifact_id.0, - "display_name": a.display_name, - "document_id": a.source.file, - "line": a.source.line, - }) - }) - .collect(); - Ok(json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "resolution": "ambiguous", - "precision": "none", - "locator": locator.to_json(), - "target": Value::Null, - "candidates": candidates, - "diagnostics": [{"code": "ambiguous", "message": format!("{} candidates for {q}", matches.len())}], - "label": "存在多个候选" - })) - } - } -} - -fn semantic_generation(project: &crate::sema::SemanticProject) -> String { - use sha2::{Digest, Sha256}; - let mut gh = Sha256::new(); - gh.update(project.project_id.as_bytes()); - for a in &project.artifacts { - gh.update(a.hashes.artifact.0.as_bytes()); - } - format!("{:x}", gh.finalize())[..16].to_string() -} - -fn resolve_under(root: &Path, rel: &str) -> Result { - let joined = root.join(rel); - let canon = joined.canonicalize().map_err(|e| { - json!({"code": "locator.document_not_found", "message": format!("{}: {e}", joined.display())}) - })?; - if !canon.starts_with(root) { - return Err(json!({ - "code": "locator.path_escape", - "message": "document path escapes project root" - })); - } - Ok(canon) -} diff --git a/src/workbench/mod.rs b/src/workbench/mod.rs deleted file mode 100755 index f3c65e6..0000000 --- a/src/workbench/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Workbench runtime contracts (M00–M05): schemas, capabilities, DocumentView, -//! KnowledgeLocator, ModelSelection / ModelCallUsage / RuntimeEvent / RunContext. -//! -//! Spec: `doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md`. -//! These are v1 contracts distinct from KnowledgePresentation `schema_version:1`. - -pub mod analysis_cache; -pub mod capabilities; -#[cfg(feature = "view")] -pub mod document_view; -pub mod event_sink; -pub mod locator; -#[cfg(feature = "view")] -pub mod resource_view; -pub mod run_context; -pub mod selection; -pub mod snapshot; -pub mod usage; - -pub use analysis_cache::{ - begin_analysis, cache_keys_isolated, cache_stats, compile_count_for, compile_invocations, - finish_analysis, get_or_compile, note_analysis, project_source_digest, reset_cache_for_tests, - result_hits, test_serial_guard, AnalysisTicket, SnapshotKey, -}; -pub use capabilities::probe_capabilities; -#[cfg(feature = "view")] -pub use document_view::{build_document_view, DocumentViewRequest}; -pub use event_sink::{bind_event_sink, clear_event_sink, emit_event, emit_message_delta}; -#[cfg(feature = "view")] -pub use resource_view::{build_resource_view, ResourceViewRequest}; -pub use locator::{resolve_reference, KnowledgeLocator}; -pub use run_context::{ - cancel_requested, cancel_token_body_means_cancel, RequestContext, RunContext, -}; -pub use selection::{parse_model_selection, ModelSelection}; -pub use snapshot::{build_snapshot_manifest, version_unavailable_result}; -pub use usage::{ - model_call_usage_from_provider, model_call_usage_from_provider_rev, replace_usage_if_newer, - runtime_event, token_or_null, -}; diff --git a/src/workbench/resource_view.rs b/src/workbench/resource_view.rs deleted file mode 100755 index 137b0fe..0000000 --- a/src/workbench/resource_view.rs +++ /dev/null @@ -1,1050 +0,0 @@ -//! ResourceViewV1 — static read-only preview for ordinary resources (M-A3). -//! Never executes Marqdo / never loads plugins. `.mq.md` remains on DocumentView. - -use std::fs; -use std::path::{Path, PathBuf}; - -use serde_json::{json, Value}; -use sha2::{Digest, Sha256}; - -#[derive(Debug, Clone)] -pub struct ResourceViewRequest { - pub workspace_root: PathBuf, - pub path: String, - pub revision: Option, - pub max_bytes: usize, - /// Optional focus locator from resources/preview (page/line/cell). - pub locator: Option, -} - -impl ResourceViewRequest { - pub fn from_params(params: &Value) -> Result { - let root = params - .get("workspace_root") - .or_else(|| params.get("project")) - .and_then(|v| v.as_str()) - .ok_or_else(|| "resource.view requires workspace_root or project".to_string())?; - let path = params - .get("path") - .or_else(|| params.get("document")) - .and_then(|v| v.as_str()) - .ok_or_else(|| "resource.view requires path or document".to_string())?; - let mode = params - .get("mode") - .and_then(|v| v.as_str()) - .unwrap_or("read"); - if mode != "read" { - return Err(format!("resource.view unsupported mode={mode}; only read")); - } - let max_bytes = params - .get("max_bytes") - .and_then(|v| v.as_u64()) - .unwrap_or(256 * 1024) as usize; - Ok(Self { - workspace_root: PathBuf::from(root), - path: path.to_string(), - revision: params - .get("revision") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()), - max_bytes, - locator: params.get("locator").cloned().filter(|v| !v.is_null()), - }) - } -} - -/// Build a ResourceViewV1 for text / markdown / code. No compile, no eval, no network. -pub fn build_resource_view(req: &ResourceViewRequest) -> Result { - let root = canonicalize_root(&req.workspace_root)?; - let abs = resolve_under(&root, &req.path)?; - let meta = fs::metadata(&abs).map_err(|e| { - err( - "resource.read_failed", - format!("cannot stat {}: {e}", abs.display()), - ) - })?; - if !meta.is_file() { - return Err(err( - "resource.not_file", - format!("{} is not a file", abs.display()), - )); - } - let size = meta.len() as usize; - let raw = fs::read(&abs).map_err(|e| { - err( - "resource.read_failed", - format!("cannot read {}: {e}", abs.display()), - ) - })?; - let digest = format!("sha256:{:x}", Sha256::digest(&raw)); - if let Some(expected) = &req.revision { - if !expected.is_empty() && expected != &digest { - return Err(err( - "resource.revision_mismatch", - format!("requested {expected} but file is {digest}"), - )); - } - } - - let rel = req.path.replace('\\', "/"); - let media = media_type_for(&rel); - let kind = kind_for(&rel, media); - let title = Path::new(&rel) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(&rel) - .to_string(); - - // `.mq.md` semantic view stays on view.document — refuse silent exec/compile here. - if rel.ends_with(".mq.md") || media == "application/x-marqdo" { - return Ok(json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": { - "resource_id": rel, - "workspace_id": "local", - "kind": "marqdo", - "media_type": "application/x-marqdo", - "revision": digest, - "digest": digest, - "title": title, - "size": size, - "origin": "workspace", - "locator": Value::Null - }, - "renderer": {"id": "redirect_document_view", "version": "1", "trust": "none"}, - "render": { - "format": "text", - "fragment": Value::Null, - "text": "该资源是 Marqdo 文档;请使用 view.document 获取语义只读视图。" - }, - "outline": [], - "locators": [], - "completeness": "partial", - "no_exec": true, - "diagnostics": [{"code": "use_document_view", "message": "use view.document for .mq.md"}], - "next_cursor": Value::Null - })); - } - - // PDF / image: framework supplies authorized blob_ref for client visual - // preview (PDF.js / ImagePreview). Extract and OCR stay independently - // unavailable — never claim text was extracted (F16 / QA-10). - if let Some(view) = - binary_blob_view(&rel, media, kind, &digest, &title, size, req.locator.as_ref()) - { - return Ok(view); - } - - let truncated = size > req.max_bytes; - let slice = if truncated { - &raw[..req.max_bytes] - } else { - &raw[..] - }; - let text = String::from_utf8_lossy(slice).into_owned(); - - // Structured JSON / CSV (M-A5 / Q-A5 subset): bounded parse, no exec. - if media == "application/json" { - return Ok(render_json_view( - &rel, &digest, &title, size, &text, truncated, req.max_bytes, kind, - )); - } - if media == "text/csv" { - return Ok(render_csv_view( - &rel, &digest, &title, size, &text, truncated, req.max_bytes, kind, - )); - } - if media == "text/x-code" || media == "text/plain" { - return Ok(render_code_view( - &rel, - media, - kind, - &digest, - &title, - size, - &text, - truncated, - req.max_bytes, - req.locator.as_ref(), - )); - } - - let (renderer_id, format, fragment) = match media { - "text/markdown" => ( - "markdown", - "sanitized_html", - wrap_pre(&simple_markdown_to_html(&text)), - ), - other => { - return Ok(json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(&rel, other, &digest, &title, size), - "renderer": {"id": "unavailable", "version": "1", "trust": "none"}, - "render": {"format": "text", "fragment": Value::Null, "text": format!("unsupported media_type={other}")}, - "outline": [], - "locators": [], - "completeness": "partial", - "no_exec": true, - "diagnostics": [{"code": "unsupported_format", "message": other}], - "next_cursor": Value::Null, - "capabilities": {"read_only": true, "executed": false, "kind": kind, "preview": false, "extract": false} - })); - } - }; - - let completeness = if truncated { "partial" } else { "complete" }; - let mut diagnostics = Vec::new(); - if truncated { - diagnostics.push(json!({ - "code": "truncated", - "message": format!("preview truncated at {} bytes", req.max_bytes) - })); - } - - Ok(json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(&rel, media, &digest, &title, size), - "renderer": {"id": renderer_id, "version": "1", "trust": "sanitized"}, - "render": {"format": format, "fragment": fragment}, - "outline": [], - "locators": [], - "completeness": completeness, - "no_exec": true, - "diagnostics": diagnostics, - "next_cursor": Value::Null, - "capabilities": {"read_only": true, "executed": false, "kind": kind} - })) -} - -fn resource_ref(id: &str, media: &str, digest: &str, title: &str, size: usize) -> Value { - json!({ - "resource_id": id, - "workspace_id": "local", - "kind": kind_for(id, media), - "media_type": media, - "revision": digest, - "digest": digest, - "title": title, - "size": size, - "origin": "workspace", - "locator": Value::Null - }) -} - -fn media_type_for(path: &str) -> &'static str { - let lower = path.to_ascii_lowercase(); - if lower.ends_with(".mq.md") { - "application/x-marqdo" - } else if lower.ends_with(".md") || lower.ends_with(".markdown") { - "text/markdown" - } else if lower.ends_with(".json") { - "application/json" - } else if lower.ends_with(".csv") { - "text/csv" - } else if lower.ends_with(".pdf") { - "application/pdf" - } else if lower.ends_with(".png") { - "image/png" - } else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") { - "image/jpeg" - } else if lower.ends_with(".webp") { - "image/webp" - } else if lower.ends_with(".gif") { - "image/gif" - } else if lower.ends_with(".docx") { - "application/vnd.openxmlformats-officedocument.wordprocessingml.document" - } else if lower.ends_with(".xlsx") { - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - } else if lower.ends_with(".pptx") { - "application/vnd.openxmlformats-officedocument.presentationml.presentation" - } else if lower.ends_with(".rs") - || lower.ends_with(".ts") - || lower.ends_with(".tsx") - || lower.ends_with(".js") - || lower.ends_with(".jsx") - || lower.ends_with(".py") - || lower.ends_with(".go") - || lower.ends_with(".toml") - || lower.ends_with(".yaml") - || lower.ends_with(".yml") - || lower.ends_with(".css") - || lower.ends_with(".html") - || lower.ends_with(".sh") - { - "text/x-code" - } else if lower.ends_with(".txt") || lower.ends_with(".log") { - "text/plain" - } else { - "application/octet-stream" - } -} - -fn kind_for(path: &str, media: &str) -> &'static str { - if media == "application/x-marqdo" || path.ends_with(".mq.md") { - "marqdo" - } else if media == "text/markdown" { - "markdown" - } else if media == "application/json" { - "json" - } else if media == "text/csv" { - "csv" - } else if media == "application/pdf" { - "pdf" - } else if media.starts_with("image/") { - "image" - } else if media.contains("wordprocessingml") { - "docx" - } else if media.contains("spreadsheetml") { - "xlsx" - } else if media.contains("presentationml") { - "pptx" - } else if media == "text/x-code" { - "code" - } else if media.starts_with("text/") { - "text" - } else { - "file" - } -} - -/// PDF/image → `blob_ref` for client visual preview; Office stays conversion-gated. -/// Extract/OCR capabilities remain false and must not be implied by a visible page. -fn binary_blob_view( - rel: &str, - media: &str, - kind: &str, - digest: &str, - title: &str, - size: usize, - locator: Option<&Value>, -) -> Option { - match kind { - "pdf" | "image" => { - let focus_page = locator - .and_then(|l| l.get("page")) - .and_then(|v| v.as_u64()) - .filter(|&p| p >= 1) - .map(|p| p as usize); - let (renderer_id, diagnostics) = if kind == "pdf" { - ( - "pdf_blob", - vec![ - json!({"code": "extract.unavailable", "message": "pdf text extract unavailable"}), - json!({"code": "ocr.unavailable", "message": "ocr not claimed; visual page ≠ extracted text"}), - ], - ) - } else { - ( - "image_blob", - vec![ - json!({"code": "extract.unavailable", "message": "image/ocr extract unavailable"}), - json!({"code": "vision.unclaimed", "message": "image preview ≠ model vision support"}), - ], - ) - }; - let page = focus_page.unwrap_or(1); - Some(json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(rel, media, digest, title, size), - "renderer": {"id": renderer_id, "version": "1", "trust": "blob"}, - "render": { - "format": "blob_ref", - "fragment": Value::Null, - "text": Value::Null, - "blob_ref": { - "path": rel, - "digest": digest, - "media_type": media, - "byte_length": size, - "title": title - } - }, - "outline": [], - "locators": if kind == "pdf" { - json!([{"id": format!("page-{page}"), "kind": "page", "locator": {"page": page}}]) - } else { - json!([]) - }, - "focus_locator": locator.cloned().unwrap_or(Value::Null), - "completeness": "partial", - "no_exec": true, - "diagnostics": diagnostics, - "next_cursor": Value::Null, - "capabilities": { - "read_only": true, - "executed": false, - "kind": kind, - "visual_preview": "client", - "extract": false, - "ocr": false, - "page_locator": kind == "pdf" - } - })) - } - "docx" | "xlsx" | "pptx" => { - let text = format!( - "Office 文档「{title}」({media}, {size} bytes)\n\n转换插件未安装;不会伪造预览或提取结果。可下载原件。能力闭环仍要求转换插件落地后按派生格式预览,本卡不是终态替代方案。" - ); - Some(json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(rel, media, digest, title, size), - "renderer": {"id": "office_conversion_pending", "version": "1", "trust": "none"}, - "render": { - "format": "sanitized_html", - "fragment": wrap_pre(&escape_html(&text)) - }, - "outline": [], - "locators": [], - "completeness": "partial", - "no_exec": true, - "diagnostics": [ - {"code": "conversion.unavailable", "message": "office conversion plugin not installed"}, - {"code": "extract.unavailable", "message": format!("{kind} extract unavailable")} - ], - "next_cursor": Value::Null, - "capabilities": { - "read_only": true, - "executed": false, - "kind": kind, - "visual_preview": false, - "extract": false, - "ocr": false, - "conversion": false - } - })) - } - _ => None, - } -} - -const JSON_OUTLINE_MAX: usize = 40; -const CSV_MAX_ROWS: usize = 200; -const CSV_MAX_COLS: usize = 32; -const CODE_LINE_LOCATOR_MAX: usize = 400; - -fn outline_to_path_locators(outline: &[Value]) -> Vec { - let mut out = Vec::new(); - fn walk(nodes: &[Value], out: &mut Vec) { - for n in nodes { - if out.len() >= JSON_OUTLINE_MAX { - return; - } - if let Some(path) = n.get("locator").and_then(|l| l.get("path")).and_then(|p| p.as_str()) { - out.push(json!({ - "id": n.get("id").cloned().unwrap_or_else(|| json!(path)), - "kind": "json_path", - "locator": {"path": path} - })); - } - if let Some(kids) = n.get("children").and_then(|c| c.as_array()) { - walk(kids, out); - } - } - } - walk(outline, &mut out); - out -} - -fn render_code_view( - rel: &str, - media: &str, - kind: &str, - digest: &str, - title: &str, - size: usize, - text: &str, - truncated: bool, - max_bytes: usize, - locator: Option<&Value>, -) -> Value { - let mut diagnostics = Vec::new(); - if truncated { - diagnostics.push(json!({ - "code": "truncated", - "message": format!("preview truncated at {max_bytes} bytes") - })); - } - let lines: Vec<&str> = text.lines().collect(); - if lines.len() > CODE_LINE_LOCATOR_MAX { - diagnostics.push(json!({ - "code": "code.line_locator_capped", - "message": format!("line locators capped at {CODE_LINE_LOCATOR_MAX}") - })); - } - let focus_line = locator - .and_then(|l| l.get("line")) - .and_then(|v| v.as_u64()) - .filter(|&n| n >= 1) - .map(|n| n as usize); - let mut locators = Vec::new(); - for (i, _) in lines.iter().take(CODE_LINE_LOCATOR_MAX).enumerate() { - let line = i + 1; - locators.push(json!({ - "id": format!("L{line}"), - "kind": "line", - "locator": {"line": line} - })); - } - let fragment = wrap_pre(&escape_html(text)); - let completeness = if truncated { "partial" } else { "complete" }; - json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(rel, media, digest, title, size), - "renderer": {"id": if kind == "code" { "code" } else { "plaintext" }, "version": "1", "trust": "sanitized"}, - "render": { - "format": "sanitized_html", - "fragment": fragment, - "text": text - }, - "outline": [], - "locators": locators, - "focus_locator": locator.cloned().unwrap_or(Value::Null), - "completeness": completeness, - "no_exec": true, - "diagnostics": diagnostics, - "next_cursor": Value::Null, - "capabilities": { - "read_only": true, - "executed": false, - "kind": kind, - "line_locator": true, - "line_count": lines.len() - }, - "line_count": lines.len(), - "focus_line": focus_line - }) -} - -fn render_json_view( - rel: &str, - digest: &str, - title: &str, - size: usize, - text: &str, - truncated: bool, - max_bytes: usize, - kind: &str, -) -> Value { - let mut diagnostics = Vec::new(); - if truncated { - diagnostics.push(json!({ - "code": "truncated", - "message": format!("preview truncated at {max_bytes} bytes") - })); - } - match serde_json::from_str::(text) { - Ok(val) => { - let outline = json_outline(&val, "", 0, &mut 0); - let pretty = serde_json::to_string_pretty(&val).unwrap_or_else(|_| text.to_string()); - let fragment = wrap_pre(&escape_html(&pretty)); - let completeness = if truncated { "partial" } else { "complete" }; - json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(rel, "application/json", digest, title, size), - "renderer": {"id": "json", "version": "1", "trust": "sanitized"}, - "render": { - "format": "sanitized_html", - "fragment": fragment, - "text": pretty - }, - "outline": outline, - "locators": outline_to_path_locators(&outline), - "completeness": completeness, - "no_exec": true, - "diagnostics": diagnostics, - "next_cursor": Value::Null, - "capabilities": {"read_only": true, "executed": false, "kind": kind} - }) - } - Err(e) => { - diagnostics.push(json!({ - "code": "json.parse_error", - "message": e.to_string() - })); - json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(rel, "application/json", digest, title, size), - "renderer": {"id": "json", "version": "1", "trust": "sanitized"}, - "render": { - "format": "sanitized_html", - "fragment": wrap_pre(&escape_html(text)), - "text": text - }, - "outline": [], - "locators": [], - "completeness": "partial", - "no_exec": true, - "diagnostics": diagnostics, - "next_cursor": Value::Null, - "capabilities": {"read_only": true, "executed": false, "kind": kind} - }) - } - } -} - -fn json_outline(val: &Value, path: &str, depth: usize, count: &mut usize) -> Vec { - if *count >= JSON_OUTLINE_MAX || depth > 3 { - return Vec::new(); - } - match val { - Value::Object(map) => { - let mut out = Vec::new(); - for (k, v) in map.iter().take(24) { - if *count >= JSON_OUTLINE_MAX { - break; - } - *count += 1; - let child = if path.is_empty() { - k.clone() - } else { - format!("{path}.{k}") - }; - let label = format!("{k}: {}", json_type_label(v)); - let mut node = json!({ - "id": child, - "label": label, - "kind": "json_key", - "locator": {"path": child} - }); - if depth < 2 { - let kids = json_outline(v, &child, depth + 1, count); - if !kids.is_empty() { - if let Some(obj) = node.as_object_mut() { - obj.insert("children".into(), json!(kids)); - } - } - } - out.push(node); - } - out - } - Value::Array(items) => { - *count += 1; - vec![json!({ - "id": path, - "label": format!("[{}] ({} items)", path, items.len()), - "kind": "json_array", - "locator": {"path": path} - })] - } - _ => Vec::new(), - } -} - -fn json_type_label(v: &Value) -> &'static str { - match v { - Value::Null => "null", - Value::Bool(_) => "bool", - Value::Number(_) => "number", - Value::String(_) => "string", - Value::Array(_) => "array", - Value::Object(_) => "object", - } -} - -fn render_csv_view( - rel: &str, - digest: &str, - title: &str, - size: usize, - text: &str, - truncated: bool, - max_bytes: usize, - kind: &str, -) -> Value { - let mut diagnostics = Vec::new(); - if truncated { - diagnostics.push(json!({ - "code": "truncated", - "message": format!("preview truncated at {max_bytes} bytes") - })); - } - let mut rows: Vec<&str> = text.lines().collect(); - while rows.last().is_some_and(|l| l.trim().is_empty()) { - rows.pop(); - } - let shown = rows.len().min(CSV_MAX_ROWS + 1); // header + data - if rows.len() > CSV_MAX_ROWS + 1 { - diagnostics.push(json!({ - "code": "csv.row_limit", - "message": format!("showing first {CSV_MAX_ROWS} data rows") - })); - } - let mut html = String::from("
          "); - let mut locators = Vec::new(); - for (i, line) in rows.iter().take(shown).enumerate() { - let cells = split_csv_line(line); - let tag = if i == 0 { "th" } else { "td" }; - html.push_str(""); - for (c, cell) in cells.iter().take(CSV_MAX_COLS).enumerate() { - html.push('<'); - html.push_str(tag); - html.push('>'); - html.push_str(&escape_html(cell)); - html.push_str("'); - if i > 0 && c == 0 { - locators.push(json!({ - "id": format!("r{i}"), - "kind": "csv_row", - "locator": {"row": i, "col": c + 1} - })); - } - } - html.push_str(""); - } - html.push_str("
          "); - let text_out = rows - .iter() - .take(shown) - .copied() - .collect::>() - .join("\n"); - let completeness = if truncated || rows.len() > CSV_MAX_ROWS + 1 { - "partial" - } else { - "complete" - }; - json!({ - "schema": "ResourceViewV1", - "schema_version": 1, - "resource": resource_ref(rel, "text/csv", digest, title, size), - "renderer": {"id": "csv", "version": "1", "trust": "sanitized"}, - "render": {"format": "sanitized_html", "fragment": html, "text": text_out}, - "outline": [], - "locators": locators, - "completeness": completeness, - "no_exec": true, - "diagnostics": diagnostics, - "next_cursor": Value::Null, - "capabilities": {"read_only": true, "executed": false, "kind": kind} - }) -} - -/// Minimal CSV splitter (no quoted-newline support — preview only). -fn split_csv_line(line: &str) -> Vec { - let mut out = Vec::new(); - let mut cur = String::new(); - let mut in_q = false; - for ch in line.chars() { - match ch { - '"' => in_q = !in_q, - ',' if !in_q => { - out.push(cur.clone()); - cur.clear(); - } - c => cur.push(c), - } - } - out.push(cur); - out -} - -fn wrap_pre(inner: &str) -> String { - format!("
          {inner}
          ") -} - -fn escape_html(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for ch in s.chars() { - match ch { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - c => out.push(c), - } - } - out -} - -/// Minimal markdown → HTML (headings/paragraphs/code fences). Not a full parser. -fn simple_markdown_to_html(src: &str) -> String { - let mut out = String::new(); - let mut in_fence = false; - for line in src.lines() { - if line.trim_start().starts_with("```") { - if in_fence { - out.push_str("
          \n"); - in_fence = false; - } else { - out.push_str("
          ");
          -                in_fence = true;
          -            }
          -            continue;
          -        }
          -        if in_fence {
          -            out.push_str(&escape_html(line));
          -            out.push('\n');
          -            continue;
          -        }
          -        let t = line.trim_end();
          -        if let Some(rest) = t.strip_prefix("### ") {
          -            out.push_str("

          "); - out.push_str(&escape_html(rest)); - out.push_str("

          \n"); - } else if let Some(rest) = t.strip_prefix("## ") { - out.push_str("

          "); - out.push_str(&escape_html(rest)); - out.push_str("

          \n"); - } else if let Some(rest) = t.strip_prefix("# ") { - out.push_str("

          "); - out.push_str(&escape_html(rest)); - out.push_str("

          \n"); - } else if t.is_empty() { - out.push_str("
          \n"); - } else { - out.push_str("

          "); - out.push_str(&escape_html(t)); - out.push_str("

          \n"); - } - } - if in_fence { - out.push_str("
          \n"); - } - out -} - -fn canonicalize_root(project: &Path) -> Result { - fs::canonicalize(project).map_err(|e| { - err( - "resource.bad_root", - format!("cannot canonicalize {}: {e}", project.display()), - ) - }) -} - -fn resolve_under(root: &Path, rel: &str) -> Result { - let cleaned = rel.trim_start_matches(['/', '\\']); - if cleaned.is_empty() || cleaned.contains("..") { - return Err(err( - "resource.path_escape", - format!("refusing path {rel:?}"), - )); - } - let abs = root.join(cleaned); - let canon = fs::canonicalize(&abs).map_err(|e| { - err( - "resource.not_found", - format!("cannot resolve {}: {e}", abs.display()), - ) - })?; - if !canon.starts_with(root) { - return Err(err( - "resource.path_escape", - format!("{} escapes workspace root", canon.display()), - )); - } - Ok(canon) -} - -fn err(code: &str, message: impl Into) -> Value { - json!({ - "ok": false, - "error": {"code": code, "message": message.into()} - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn scratch_dir(label: &str) -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let dir = std::env::temp_dir().join(format!("marqdo-resource-view-{label}-{nanos}")); - fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn plaintext_no_exec_and_escape() { - let dir = scratch_dir("plain"); - let path = dir.join("note.txt"); - let mut f = fs::File::create(&path).unwrap(); - writeln!(f, "").unwrap(); - let req = ResourceViewRequest { - workspace_root: dir.clone(), - path: "note.txt".into(), - revision: None, - max_bytes: 10_000, - locator: None, - }; - let view = build_resource_view(&req).unwrap(); - assert_eq!(view["no_exec"], true); - assert_eq!(view["schema"], "ResourceViewV1"); - let frag = view["render"]["fragment"].as_str().unwrap(); - assert!(frag.contains("<script>")); - assert!(!frag.contains("